From d113667a8f4fc12aaf44bacee00254398ddf27b2 Mon Sep 17 00:00:00 2001 From: Alexandru Mariuti Date: Mon, 21 Sep 2026 10:33:45 +0700 Subject: [PATCH] Feat/challenge matching_brackets: add the Matching brackets challenge in 6 languages across 12 locales --- assets/challenges/matching_brackets.svg | 1 + de/c/challenges/data.json | 4 + de/c/challenges/matching_brackets.md | 280 ++++++++++++++++++ de/dart/challenges/data.json | 4 + de/dart/challenges/matching_brackets.md | 167 +++++++++++ de/javascript/challenges/data.json | 4 + de/javascript/challenges/matching_brackets.md | 154 ++++++++++ de/kotlin/challenges/data.json | 4 + de/kotlin/challenges/matching_brackets.md | 157 ++++++++++ de/python/challenges/data.json | 4 + de/python/challenges/matching_brackets.md | 149 ++++++++++ de/swift/challenges/data.json | 4 + de/swift/challenges/matching_brackets.md | 152 ++++++++++ en/c/challenges/data.json | 4 + en/c/challenges/matching_brackets.md | 280 ++++++++++++++++++ en/dart/challenges/data.json | 4 + en/dart/challenges/matching_brackets.md | 167 +++++++++++ en/javascript/challenges/data.json | 4 + en/javascript/challenges/matching_brackets.md | 154 ++++++++++ en/kotlin/challenges/data.json | 4 + en/kotlin/challenges/matching_brackets.md | 157 ++++++++++ en/python/challenges/data.json | 4 + en/python/challenges/matching_brackets.md | 149 ++++++++++ en/swift/challenges/data.json | 4 + en/swift/challenges/matching_brackets.md | 152 ++++++++++ es/c/challenges/data.json | 4 + es/c/challenges/matching_brackets.md | 280 ++++++++++++++++++ es/dart/challenges/data.json | 4 + es/dart/challenges/matching_brackets.md | 167 +++++++++++ es/javascript/challenges/data.json | 4 + es/javascript/challenges/matching_brackets.md | 154 ++++++++++ es/kotlin/challenges/data.json | 4 + es/kotlin/challenges/matching_brackets.md | 157 ++++++++++ es/python/challenges/data.json | 4 + es/python/challenges/matching_brackets.md | 149 ++++++++++ es/swift/challenges/data.json | 4 + es/swift/challenges/matching_brackets.md | 152 ++++++++++ fr/c/challenges/data.json | 4 + fr/c/challenges/matching_brackets.md | 280 ++++++++++++++++++ fr/dart/challenges/data.json | 4 + fr/dart/challenges/matching_brackets.md | 167 +++++++++++ fr/javascript/challenges/data.json | 4 + fr/javascript/challenges/matching_brackets.md | 154 ++++++++++ fr/kotlin/challenges/data.json | 4 + fr/kotlin/challenges/matching_brackets.md | 157 ++++++++++ fr/python/challenges/data.json | 4 + fr/python/challenges/matching_brackets.md | 149 ++++++++++ fr/swift/challenges/data.json | 4 + fr/swift/challenges/matching_brackets.md | 152 ++++++++++ hi/c/challenges/data.json | 4 + hi/c/challenges/matching_brackets.md | 280 ++++++++++++++++++ hi/dart/challenges/data.json | 4 + hi/dart/challenges/matching_brackets.md | 167 +++++++++++ hi/javascript/challenges/data.json | 4 + hi/javascript/challenges/matching_brackets.md | 154 ++++++++++ hi/kotlin/challenges/data.json | 4 + hi/kotlin/challenges/matching_brackets.md | 157 ++++++++++ hi/python/challenges/data.json | 4 + hi/python/challenges/matching_brackets.md | 149 ++++++++++ hi/swift/challenges/data.json | 4 + hi/swift/challenges/matching_brackets.md | 152 ++++++++++ it/c/challenges/data.json | 4 + it/c/challenges/matching_brackets.md | 280 ++++++++++++++++++ it/dart/challenges/data.json | 4 + it/dart/challenges/matching_brackets.md | 167 +++++++++++ it/javascript/challenges/data.json | 4 + it/javascript/challenges/matching_brackets.md | 154 ++++++++++ it/kotlin/challenges/data.json | 4 + it/kotlin/challenges/matching_brackets.md | 157 ++++++++++ it/python/challenges/data.json | 4 + it/python/challenges/matching_brackets.md | 149 ++++++++++ it/swift/challenges/data.json | 4 + it/swift/challenges/matching_brackets.md | 152 ++++++++++ ja/c/challenges/data.json | 4 + ja/c/challenges/matching_brackets.md | 280 ++++++++++++++++++ ja/dart/challenges/data.json | 4 + ja/dart/challenges/matching_brackets.md | 167 +++++++++++ ja/javascript/challenges/data.json | 4 + ja/javascript/challenges/matching_brackets.md | 154 ++++++++++ ja/kotlin/challenges/data.json | 4 + ja/kotlin/challenges/matching_brackets.md | 157 ++++++++++ ja/python/challenges/data.json | 4 + ja/python/challenges/matching_brackets.md | 149 ++++++++++ ja/swift/challenges/data.json | 4 + ja/swift/challenges/matching_brackets.md | 152 ++++++++++ ko/c/challenges/data.json | 4 + ko/c/challenges/matching_brackets.md | 280 ++++++++++++++++++ ko/dart/challenges/data.json | 4 + ko/dart/challenges/matching_brackets.md | 167 +++++++++++ ko/javascript/challenges/data.json | 4 + ko/javascript/challenges/matching_brackets.md | 154 ++++++++++ ko/kotlin/challenges/data.json | 4 + ko/kotlin/challenges/matching_brackets.md | 157 ++++++++++ ko/python/challenges/data.json | 4 + ko/python/challenges/matching_brackets.md | 149 ++++++++++ ko/swift/challenges/data.json | 4 + ko/swift/challenges/matching_brackets.md | 152 ++++++++++ pl/c/challenges/data.json | 6 +- pl/c/challenges/matching_brackets.md | 280 ++++++++++++++++++ pl/dart/challenges/data.json | 6 +- pl/dart/challenges/matching_brackets.md | 167 +++++++++++ pl/javascript/challenges/data.json | 6 +- pl/javascript/challenges/matching_brackets.md | 154 ++++++++++ pl/kotlin/challenges/data.json | 6 +- pl/kotlin/challenges/matching_brackets.md | 157 ++++++++++ pl/python/challenges/data.json | 6 +- pl/python/challenges/matching_brackets.md | 149 ++++++++++ pl/swift/challenges/data.json | 6 +- pl/swift/challenges/matching_brackets.md | 152 ++++++++++ pt/c/challenges/data.json | 4 + pt/c/challenges/matching_brackets.md | 280 ++++++++++++++++++ pt/dart/challenges/data.json | 4 + pt/dart/challenges/matching_brackets.md | 167 +++++++++++ pt/javascript/challenges/data.json | 4 + pt/javascript/challenges/matching_brackets.md | 154 ++++++++++ pt/kotlin/challenges/data.json | 4 + pt/kotlin/challenges/matching_brackets.md | 157 ++++++++++ pt/python/challenges/data.json | 4 + pt/python/challenges/matching_brackets.md | 149 ++++++++++ pt/swift/challenges/data.json | 4 + pt/swift/challenges/matching_brackets.md | 152 ++++++++++ ru/c/challenges/data.json | 6 +- ru/c/challenges/matching_brackets.md | 280 ++++++++++++++++++ ru/dart/challenges/data.json | 6 +- ru/dart/challenges/matching_brackets.md | 167 +++++++++++ ru/javascript/challenges/data.json | 6 +- ru/javascript/challenges/matching_brackets.md | 154 ++++++++++ ru/kotlin/challenges/data.json | 6 +- ru/kotlin/challenges/matching_brackets.md | 157 ++++++++++ ru/python/challenges/data.json | 6 +- ru/python/challenges/matching_brackets.md | 149 ++++++++++ ru/swift/challenges/data.json | 6 +- ru/swift/challenges/matching_brackets.md | 152 ++++++++++ zh/c/challenges/data.json | 4 + zh/c/challenges/matching_brackets.md | 280 ++++++++++++++++++ zh/dart/challenges/data.json | 4 + zh/dart/challenges/matching_brackets.md | 167 +++++++++++ zh/javascript/challenges/data.json | 4 + zh/javascript/challenges/matching_brackets.md | 154 ++++++++++ zh/kotlin/challenges/data.json | 4 + zh/kotlin/challenges/matching_brackets.md | 157 ++++++++++ zh/python/challenges/data.json | 4 + zh/python/challenges/matching_brackets.md | 149 ++++++++++ zh/swift/challenges/data.json | 4 + zh/swift/challenges/matching_brackets.md | 152 ++++++++++ 145 files changed, 13009 insertions(+), 12 deletions(-) create mode 100644 assets/challenges/matching_brackets.svg create mode 100644 de/c/challenges/matching_brackets.md create mode 100644 de/dart/challenges/matching_brackets.md create mode 100644 de/javascript/challenges/matching_brackets.md create mode 100644 de/kotlin/challenges/matching_brackets.md create mode 100644 de/python/challenges/matching_brackets.md create mode 100644 de/swift/challenges/matching_brackets.md create mode 100644 en/c/challenges/matching_brackets.md create mode 100644 en/dart/challenges/matching_brackets.md create mode 100644 en/javascript/challenges/matching_brackets.md create mode 100644 en/kotlin/challenges/matching_brackets.md create mode 100644 en/python/challenges/matching_brackets.md create mode 100644 en/swift/challenges/matching_brackets.md create mode 100644 es/c/challenges/matching_brackets.md create mode 100644 es/dart/challenges/matching_brackets.md create mode 100644 es/javascript/challenges/matching_brackets.md create mode 100644 es/kotlin/challenges/matching_brackets.md create mode 100644 es/python/challenges/matching_brackets.md create mode 100644 es/swift/challenges/matching_brackets.md create mode 100644 fr/c/challenges/matching_brackets.md create mode 100644 fr/dart/challenges/matching_brackets.md create mode 100644 fr/javascript/challenges/matching_brackets.md create mode 100644 fr/kotlin/challenges/matching_brackets.md create mode 100644 fr/python/challenges/matching_brackets.md create mode 100644 fr/swift/challenges/matching_brackets.md create mode 100644 hi/c/challenges/matching_brackets.md create mode 100644 hi/dart/challenges/matching_brackets.md create mode 100644 hi/javascript/challenges/matching_brackets.md create mode 100644 hi/kotlin/challenges/matching_brackets.md create mode 100644 hi/python/challenges/matching_brackets.md create mode 100644 hi/swift/challenges/matching_brackets.md create mode 100644 it/c/challenges/matching_brackets.md create mode 100644 it/dart/challenges/matching_brackets.md create mode 100644 it/javascript/challenges/matching_brackets.md create mode 100644 it/kotlin/challenges/matching_brackets.md create mode 100644 it/python/challenges/matching_brackets.md create mode 100644 it/swift/challenges/matching_brackets.md create mode 100644 ja/c/challenges/matching_brackets.md create mode 100644 ja/dart/challenges/matching_brackets.md create mode 100644 ja/javascript/challenges/matching_brackets.md create mode 100644 ja/kotlin/challenges/matching_brackets.md create mode 100644 ja/python/challenges/matching_brackets.md create mode 100644 ja/swift/challenges/matching_brackets.md create mode 100644 ko/c/challenges/matching_brackets.md create mode 100644 ko/dart/challenges/matching_brackets.md create mode 100644 ko/javascript/challenges/matching_brackets.md create mode 100644 ko/kotlin/challenges/matching_brackets.md create mode 100644 ko/python/challenges/matching_brackets.md create mode 100644 ko/swift/challenges/matching_brackets.md create mode 100644 pl/c/challenges/matching_brackets.md create mode 100644 pl/dart/challenges/matching_brackets.md create mode 100644 pl/javascript/challenges/matching_brackets.md create mode 100644 pl/kotlin/challenges/matching_brackets.md create mode 100644 pl/python/challenges/matching_brackets.md create mode 100644 pl/swift/challenges/matching_brackets.md create mode 100644 pt/c/challenges/matching_brackets.md create mode 100644 pt/dart/challenges/matching_brackets.md create mode 100644 pt/javascript/challenges/matching_brackets.md create mode 100644 pt/kotlin/challenges/matching_brackets.md create mode 100644 pt/python/challenges/matching_brackets.md create mode 100644 pt/swift/challenges/matching_brackets.md create mode 100644 ru/c/challenges/matching_brackets.md create mode 100644 ru/dart/challenges/matching_brackets.md create mode 100644 ru/javascript/challenges/matching_brackets.md create mode 100644 ru/kotlin/challenges/matching_brackets.md create mode 100644 ru/python/challenges/matching_brackets.md create mode 100644 ru/swift/challenges/matching_brackets.md create mode 100644 zh/c/challenges/matching_brackets.md create mode 100644 zh/dart/challenges/matching_brackets.md create mode 100644 zh/javascript/challenges/matching_brackets.md create mode 100644 zh/kotlin/challenges/matching_brackets.md create mode 100644 zh/python/challenges/matching_brackets.md create mode 100644 zh/swift/challenges/matching_brackets.md diff --git a/assets/challenges/matching_brackets.svg b/assets/challenges/matching_brackets.svg new file mode 100644 index 000000000..fe5f86e0d --- /dev/null +++ b/assets/challenges/matching_brackets.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/de/c/challenges/data.json b/de/c/challenges/data.json index 7bc46665d..d2634dff0 100644 --- a/de/c/challenges/data.json +++ b/de/c/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramm" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Passende Klammern" } } diff --git a/de/c/challenges/matching_brackets.md b/de/c/challenges/matching_brackets.md new file mode 100644 index 000000000..d932598bf --- /dev/null +++ b/de/c/challenges/matching_brackets.md @@ -0,0 +1,280 @@ +--- +language: c +exerciseType: 1 +difficulty: 3 +title: Passende Klammern +--- + +# --description-- + +Text, der Code, Formeln oder Markup enthält, ist voller Klammern, und jede öffnende Klammer braucht eine schließende derselben Art. Ein String ist ausgeglichen, wenn sich seine Klammern paarweise entsprechen und wie die Schichten einer Zwiebel verschachteln: `{[()]}` ist ausgeglichen, `{[(])}` dagegen nicht, weil das runde Paar vor dem eckigen Paar geschlossen wird, in dem es liegt. + +Hier zählen drei Paare: runde `()`, eckige `[]` und geschweifte `{}`. Jedes andere Zeichen im String wird ignoriert. Eine schließende Klammer muss die zuletzt geöffnete Klammer schließen, die noch offen ist, und wenn der String endet, darf keine Klammer offen geblieben sein. + +# --instructions-- + +Schreiben Sie eine Funktion `is_balanced`, die einen String entgegennimmt und `true` zurückgibt, wenn alle darin enthaltenen Klammern übereinstimmen und korrekt verschachtelt sind, und andernfalls `false`. + +Beispiele: +``` +is_balanced("") ➞ true +is_balanced("{[()]}") ➞ true +is_balanced("{what is (42)}[?]") ➞ true +is_balanced("{[(])}") ➞ false +is_balanced("(") ➞ false +is_balanced(")(") ➞ false +``` + +- Ein leerer String ist ausgeglichen. +- Zeichen, die keine Klammern sind, werden ignoriert. +- Eine schließende Klammer muss zu der zuletzt geöffneten Klammer passen, die noch offen ist. +- Wenn der String endet, darf keine Klammer offen geblieben sein. + +# --before-seed-- + +```c +// DO NOT EDIT FROM HERE +#include +#include +#include + +#ifndef _CEXCEPTION_H +#define _CEXCEPTION_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +//This is the value to assign when there isn't an exception +#ifndef CEXCEPTION_NONE +#define CEXCEPTION_NONE (0x5A5A5A5A) +#endif + +//This is number of exception stacks to keep track of (one per task) +#ifndef CEXCEPTION_NUM_ID +#define CEXCEPTION_NUM_ID (1) //there is only the one stack by default +#endif + +//This is the method of getting the current exception stack index (0 if only one stack) +#ifndef CEXCEPTION_GET_ID +#define CEXCEPTION_GET_ID (0) //use the first index always because there is only one anyway +#endif + +//The type to use to store the exception values. +#ifndef CEXCEPTION_T +#define CEXCEPTION_T unsigned int +#endif + +//This is an optional special handler for when there is no global Catch +#ifndef CEXCEPTION_NO_CATCH_HANDLER +#define CEXCEPTION_NO_CATCH_HANDLER(id) +#endif + +//These hooks allow you to inject custom code into places, particularly useful for saving and restoring additional state +#ifndef CEXCEPTION_HOOK_START_TRY +#define CEXCEPTION_HOOK_START_TRY +#endif +#ifndef CEXCEPTION_HOOK_HAPPY_TRY +#define CEXCEPTION_HOOK_HAPPY_TRY +#endif +#ifndef CEXCEPTION_HOOK_AFTER_TRY +#define CEXCEPTION_HOOK_AFTER_TRY +#endif +#ifndef CEXCEPTION_HOOK_START_CATCH +#define CEXCEPTION_HOOK_START_CATCH +#endif + +//exception frame structures +typedef struct { + jmp_buf* pFrame; + CEXCEPTION_T volatile Exception; +} CEXCEPTION_FRAME_T; + +//actual root frame storage (only one if single-tasking) +extern volatile CEXCEPTION_FRAME_T CExceptionFrames[]; + +//Try +#define Try \ + { \ + jmp_buf *PrevFrame, NewFrame; \ + unsigned int MY_ID = CEXCEPTION_GET_ID; \ + PrevFrame = CExceptionFrames[MY_ID].pFrame; \ + CExceptionFrames[MY_ID].pFrame = (jmp_buf*)(&NewFrame); \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_START_TRY; \ + if (setjmp(NewFrame) == 0) { \ + if (1) + +//Catch +#define Catch(e) \ + else { } \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_HAPPY_TRY; \ + } \ + else \ + { \ + e = CExceptionFrames[MY_ID].Exception; \ + (void)e; \ + CEXCEPTION_HOOK_START_CATCH; \ + } \ + CExceptionFrames[MY_ID].pFrame = PrevFrame; \ + CEXCEPTION_HOOK_AFTER_TRY; \ + } \ + if (CExceptionFrames[CEXCEPTION_GET_ID].Exception != CEXCEPTION_NONE) + +#endif + +volatile CEXCEPTION_FRAME_T CExceptionFrames[CEXCEPTION_NUM_ID] = {{ 0 }}; + +void Throw(CEXCEPTION_T ExceptionID) +{ + unsigned int MY_ID = CEXCEPTION_GET_ID; + CExceptionFrames[MY_ID].Exception = ExceptionID; + if (CExceptionFrames[MY_ID].pFrame) + { + longjmp(*CExceptionFrames[MY_ID].pFrame, 1); + } + CEXCEPTION_NO_CATCH_HANDLER(ExceptionID); +} + +CEXCEPTION_T e; +int _test_failed_count = 0; +int _test_count = 0; + +void try_catch(bool assertion) { + _test_count++; + Try { + if (!assertion) { + Throw(_test_count); + } + } Catch (e) { + _test_failed_count += 1; + printf("Test Case '--err-t%i--' failed\n", e); + } +} +// DO NOT EDIT UNTIL HERE +#include +#include +``` + +# --seed-- + +```c +bool is_balanced(const char* text) { + +} +``` + +# --before-asserts-- + +```c +int main() { +``` + +# --asserts-- + +Ein leerer String ist ausgeglichen + +```c + try_catch(is_balanced("") == true); +``` + +Ein einzelnes Paar runder Klammern ist ausgeglichen + +```c + try_catch(is_balanced("()") == true); +``` + +Die drei Arten von Paaren, ineinander verschachtelt, sind ausgeglichen + +```c + try_catch(is_balanced("{[()]}") == true); +``` + +Klammern, die mit anderem Text vermischt sind, sind weiterhin ausgeglichen + +```c + try_catch(is_balanced("{what is (42)}[?]") == true); +``` + +Nebeneinander stehende Paare sind ausgeglichen + +```c + try_catch(is_balanced("()[]{}") == true); +``` + +Ein String ohne jegliche Klammern ist ausgeglichen + +```c + try_catch(is_balanced("no brackets in here at all") == true); +``` + +Ein überkreuztes Paar ist nicht ausgeglichen + +```c + try_catch(is_balanced("{[(])}") == false); +``` + +Eine öffnende Klammer, die nie geschlossen wird, ist nicht ausgeglichen + +```c + try_catch(is_balanced("(") == false); +``` + +Eine schließende Klammer vor jeder öffnenden ist nicht ausgeglichen + +```c + try_catch(is_balanced(")(") == false); +``` + +Überkreuzte Paare tiefer im String sind nicht ausgeglichen + +```c + try_catch(is_balanced("(([]{[}]))") == false); +``` + +Eine am Ende übrig gebliebene schließende Klammer ist nicht ausgeglichen + +```c + try_catch(is_balanced("())") == false); +``` + +# --after-asserts-- + +```c + printf("Executed %d tests, with %d failures", _test_count, _test_failed_count); + return 0; +} +``` + +# --solutions-- + +```c +bool is_balanced(const char* text) { + size_t length = strlen(text); + char stack[length + 1]; + size_t top = 0; + + for (size_t i = 0; i < length; i++) { + char current = text[i]; + + if (current == '(' || current == '[' || current == '{') { + stack[top++] = current; + } else if (current == ')' || current == ']' || current == '}') { + if (top == 0) { + return false; + } + + char opening = stack[--top]; + if ((current == ')' && opening != '(') || + (current == ']' && opening != '[') || + (current == '}' && opening != '{')) { + return false; + } + } + } + + return top == 0; +} +``` diff --git a/de/dart/challenges/data.json b/de/dart/challenges/data.json index 835e8f5e9..8619dbb0d 100644 --- a/de/dart/challenges/data.json +++ b/de/dart/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramm" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Passende Klammern" } } diff --git a/de/dart/challenges/matching_brackets.md b/de/dart/challenges/matching_brackets.md new file mode 100644 index 000000000..4ddd7a179 --- /dev/null +++ b/de/dart/challenges/matching_brackets.md @@ -0,0 +1,167 @@ +--- +language: dart +exerciseType: 1 +difficulty: 3 +title: Passende Klammern +--- + +# --description-- + +Text, der Code, Formeln oder Markup enthält, ist voller Klammern, und jede öffnende Klammer braucht eine schließende derselben Art. Ein String ist ausgeglichen, wenn sich seine Klammern paarweise entsprechen und wie die Schichten einer Zwiebel verschachteln: `{[()]}` ist ausgeglichen, `{[(])}` dagegen nicht, weil das runde Paar vor dem eckigen Paar geschlossen wird, in dem es liegt. + +Hier zählen drei Paare: runde `()`, eckige `[]` und geschweifte `{}`. Jedes andere Zeichen im String wird ignoriert. Eine schließende Klammer muss die zuletzt geöffnete Klammer schließen, die noch offen ist, und wenn der String endet, darf keine Klammer offen geblieben sein. + +# --instructions-- + +Schreiben Sie eine Funktion `isBalanced`, die einen String entgegennimmt und `true` zurückgibt, wenn alle darin enthaltenen Klammern übereinstimmen und korrekt verschachtelt sind, und andernfalls `false`. + +Beispiele: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Ein leerer String ist ausgeglichen. +- Zeichen, die keine Klammern sind, werden ignoriert. +- Eine schließende Klammer muss zu der zuletzt geöffneten Klammer passen, die noch offen ist. +- Wenn der String endet, darf keine Klammer offen geblieben sein. + +# --seed-- + +```dart +bool isBalanced(String text) { + +} +``` + +# --before-asserts-- + +```dart +import 'package:dart_runner/main.dart'; +import 'package:test/test.dart'; + +void main() { + group('MainTest -', () { +``` + +# --asserts-- + +Ein leerer String ist ausgeglichen + +```dart + test('test1', () { + expect(isBalanced(''), true, reason: '--err-t1--'); + }); +``` + +Ein einzelnes Paar runder Klammern ist ausgeglichen + +```dart + test('test2', () { + expect(isBalanced('()'), true, reason: '--err-t2--'); + }); +``` + +Die drei Arten von Paaren, ineinander verschachtelt, sind ausgeglichen + +```dart + test('test3', () { + expect(isBalanced('{[()]}'), true, reason: '--err-t3--'); + }); +``` + +Klammern, die mit anderem Text vermischt sind, sind weiterhin ausgeglichen + +```dart + test('test4', () { + expect(isBalanced('{what is (42)}[?]'), true, reason: '--err-t4--'); + }); +``` + +Nebeneinander stehende Paare sind ausgeglichen + +```dart + test('test5', () { + expect(isBalanced('()[]{}'), true, reason: '--err-t5--'); + }); +``` + +Ein String ohne jegliche Klammern ist ausgeglichen + +```dart + test('test6', () { + expect(isBalanced('no brackets in here at all'), true, reason: '--err-t6--'); + }); +``` + +Ein überkreuztes Paar ist nicht ausgeglichen + +```dart + test('test7', () { + expect(isBalanced('{[(])}'), false, reason: '--err-t7--'); + }); +``` + +Eine öffnende Klammer, die nie geschlossen wird, ist nicht ausgeglichen + +```dart + test('test8', () { + expect(isBalanced('('), false, reason: '--err-t8--'); + }); +``` + +Eine schließende Klammer vor jeder öffnenden ist nicht ausgeglichen + +```dart + test('test9', () { + expect(isBalanced(')('), false, reason: '--err-t9--'); + }); +``` + +Überkreuzte Paare tiefer im String sind nicht ausgeglichen + +```dart + test('test10', () { + expect(isBalanced('(([]{[}]))'), false, reason: '--err-t10--'); + }); +``` + +Eine am Ende übrig gebliebene schließende Klammer ist nicht ausgeglichen + +```dart + test('test11', () { + expect(isBalanced('())'), false, reason: '--err-t11--'); + }); +``` + +# --after-asserts-- + +```dart + }, timeout: Timeout(const Duration(seconds: 1))); +} +``` + +# --solutions-- + +```dart +bool isBalanced(String text) { + const pairs = {')': '(', ']': '[', '}': '{'}; + final stack = []; + + for (final char in text.split('')) { + if (char == '(' || char == '[' || char == '{') { + stack.add(char); + } else if (pairs.containsKey(char)) { + if (stack.isEmpty || stack.removeLast() != pairs[char]) { + return false; + } + } + } + + return stack.isEmpty; +} +``` diff --git a/de/javascript/challenges/data.json b/de/javascript/challenges/data.json index ea9da610c..73170cff3 100644 --- a/de/javascript/challenges/data.json +++ b/de/javascript/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramm" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Passende Klammern" } } diff --git a/de/javascript/challenges/matching_brackets.md b/de/javascript/challenges/matching_brackets.md new file mode 100644 index 000000000..d72b732e4 --- /dev/null +++ b/de/javascript/challenges/matching_brackets.md @@ -0,0 +1,154 @@ +--- +language: javascript +exerciseType: 1 +difficulty: 3 +title: Passende Klammern +--- + +# --description-- + +Text, der Code, Formeln oder Markup enthält, ist voller Klammern, und jede öffnende Klammer braucht eine schließende derselben Art. Ein String ist ausgeglichen, wenn sich seine Klammern paarweise entsprechen und wie die Schichten einer Zwiebel verschachteln: `{[()]}` ist ausgeglichen, `{[(])}` dagegen nicht, weil das runde Paar vor dem eckigen Paar geschlossen wird, in dem es liegt. + +Hier zählen drei Paare: runde `()`, eckige `[]` und geschweifte `{}`. Jedes andere Zeichen im String wird ignoriert. Eine schließende Klammer muss die zuletzt geöffnete Klammer schließen, die noch offen ist, und wenn der String endet, darf keine Klammer offen geblieben sein. + +# --instructions-- + +Schreiben Sie eine Funktion `isBalanced`, die einen String entgegennimmt und `true` zurückgibt, wenn alle darin enthaltenen Klammern übereinstimmen und korrekt verschachtelt sind, und andernfalls `false`. + +Beispiele: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Ein leerer String ist ausgeglichen. +- Zeichen, die keine Klammern sind, werden ignoriert. +- Eine schließende Klammer muss zu der zuletzt geöffneten Klammer passen, die noch offen ist. +- Wenn der String endet, darf keine Klammer offen geblieben sein. + +# --before-seed-- + +```javascript +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +var assert = require('assert') +const tryCatch = (...args) => { + _testCount++ + try { assert(...args) } + catch (e) { + _testFailedCount++ + console.log(`Test Case '--err-t${_testCount}--' failed`); + } +}; +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```javascript +function isBalanced(text) { + +} +``` + +# --asserts-- + +Ein leerer String ist ausgeglichen + +```javascript +tryCatch(isBalanced("") === true); +``` + +Ein einzelnes Paar runder Klammern ist ausgeglichen + +```javascript +tryCatch(isBalanced("()") === true); +``` + +Die drei Arten von Paaren, ineinander verschachtelt, sind ausgeglichen + +```javascript +tryCatch(isBalanced("{[()]}") === true); +``` + +Klammern, die mit anderem Text vermischt sind, sind weiterhin ausgeglichen + +```javascript +tryCatch(isBalanced("{what is (42)}[?]") === true); +``` + +Nebeneinander stehende Paare sind ausgeglichen + +```javascript +tryCatch(isBalanced("()[]{}") === true); +``` + +Ein String ohne jegliche Klammern ist ausgeglichen + +```javascript +tryCatch(isBalanced("no brackets in here at all") === true); +``` + +Ein überkreuztes Paar ist nicht ausgeglichen + +```javascript +tryCatch(isBalanced("{[(])}") === false); +``` + +Eine öffnende Klammer, die nie geschlossen wird, ist nicht ausgeglichen + +```javascript +tryCatch(isBalanced("(") === false); +``` + +Eine schließende Klammer vor jeder öffnenden ist nicht ausgeglichen + +```javascript +tryCatch(isBalanced(")(") === false); +``` + +Überkreuzte Paare tiefer im String sind nicht ausgeglichen + +```javascript +tryCatch(isBalanced("(([]{[}]))") === false); +``` + +Eine am Ende übrig gebliebene schließende Klammer ist nicht ausgeglichen + +```javascript +tryCatch(isBalanced("())") === false); +``` + +# --after-asserts-- + +```javascript +// DO NOT EDIT FROM HERE +console.log(`Executed ${_testCount} tests, with ${_testFailedCount} failures`); +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```javascript +function isBalanced(text) { + const pairs = { ")": "(", "]": "[", "}": "{" }; + const stack = []; + + for (const char of text) { + if (char === "(" || char === "[" || char === "{") { + stack.push(char); + } else if (char in pairs) { + if (stack.pop() !== pairs[char]) { + return false; + } + } + } + + return stack.length === 0; +} +``` diff --git a/de/kotlin/challenges/data.json b/de/kotlin/challenges/data.json index e3d167e99..3a651ac94 100644 --- a/de/kotlin/challenges/data.json +++ b/de/kotlin/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramm" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Passende Klammern" } } diff --git a/de/kotlin/challenges/matching_brackets.md b/de/kotlin/challenges/matching_brackets.md new file mode 100644 index 000000000..24860e92e --- /dev/null +++ b/de/kotlin/challenges/matching_brackets.md @@ -0,0 +1,157 @@ +--- +language: kotlin +exerciseType: 1 +difficulty: 3 +title: Passende Klammern +--- + +# --description-- + +Text, der Code, Formeln oder Markup enthält, ist voller Klammern, und jede öffnende Klammer braucht eine schließende derselben Art. Ein String ist ausgeglichen, wenn sich seine Klammern paarweise entsprechen und wie die Schichten einer Zwiebel verschachteln: `{[()]}` ist ausgeglichen, `{[(])}` dagegen nicht, weil das runde Paar vor dem eckigen Paar geschlossen wird, in dem es liegt. + +Hier zählen drei Paare: runde `()`, eckige `[]` und geschweifte `{}`. Jedes andere Zeichen im String wird ignoriert. Eine schließende Klammer muss die zuletzt geöffnete Klammer schließen, die noch offen ist, und wenn der String endet, darf keine Klammer offen geblieben sein. + +# --instructions-- + +Schreiben Sie eine Funktion `isBalanced`, die einen String entgegennimmt und `true` zurückgibt, wenn alle darin enthaltenen Klammern übereinstimmen und korrekt verschachtelt sind, und andernfalls `false`. + +Beispiele: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Ein leerer String ist ausgeglichen. +- Zeichen, die keine Klammern sind, werden ignoriert. +- Eine schließende Klammer muss zu der zuletzt geöffneten Klammer passen, die noch offen ist. +- Wenn der String endet, darf keine Klammer offen geblieben sein. + +# --seed-- + +```kotlin +fun isBalanced(text: String): Boolean { + +} +``` + +# --before-seed-- + +```kotlin +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +fun tryCatch(assertion: Boolean) { + _testCount++ + try { + if (!assertion) throw Exception() + } + catch (e: Throwable) { + _testFailedCount++ + println("Test Case '--err-t$_testCount--' failed"); + } +}; +// DO NOT EDIT UNTIL HERE +fun main() { +``` + +# --asserts-- + +Ein leerer String ist ausgeglichen + +```kotlin + tryCatch(isBalanced("") == true) +``` + +Ein einzelnes Paar runder Klammern ist ausgeglichen + +```kotlin + tryCatch(isBalanced("()") == true) +``` + +Die drei Arten von Paaren, ineinander verschachtelt, sind ausgeglichen + +```kotlin + tryCatch(isBalanced("{[()]}") == true) +``` + +Klammern, die mit anderem Text vermischt sind, sind weiterhin ausgeglichen + +```kotlin + tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +Nebeneinander stehende Paare sind ausgeglichen + +```kotlin + tryCatch(isBalanced("()[]{}") == true) +``` + +Ein String ohne jegliche Klammern ist ausgeglichen + +```kotlin + tryCatch(isBalanced("no brackets in here at all") == true) +``` + +Ein überkreuztes Paar ist nicht ausgeglichen + +```kotlin + tryCatch(isBalanced("{[(])}") == false) +``` + +Eine öffnende Klammer, die nie geschlossen wird, ist nicht ausgeglichen + +```kotlin + tryCatch(isBalanced("(") == false) +``` + +Eine schließende Klammer vor jeder öffnenden ist nicht ausgeglichen + +```kotlin + tryCatch(isBalanced(")(") == false) +``` + +Überkreuzte Paare tiefer im String sind nicht ausgeglichen + +```kotlin + tryCatch(isBalanced("(([]{[}]))") == false) +``` + +Eine am Ende übrig gebliebene schließende Klammer ist nicht ausgeglichen + +```kotlin + tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```kotlin +// DO NOT EDIT FROM HERE + println("Executed $_testCount tests, with $_testFailedCount failures"); +} +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```kotlin +fun isBalanced(text: String): Boolean { + val pairs = mapOf(')' to '(', ']' to '[', '}' to '{') + val stack = ArrayDeque() + + for (char in text) { + if (char == '(' || char == '[' || char == '{') { + stack.addLast(char) + } else if (pairs.containsKey(char)) { + if (stack.isEmpty() || stack.removeLast() != pairs[char]) { + return false + } + } + } + + return stack.isEmpty() +} +``` diff --git a/de/python/challenges/data.json b/de/python/challenges/data.json index f40d89219..a2ed76113 100644 --- a/de/python/challenges/data.json +++ b/de/python/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramm" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Passende Klammern" } } diff --git a/de/python/challenges/matching_brackets.md b/de/python/challenges/matching_brackets.md new file mode 100644 index 000000000..322613964 --- /dev/null +++ b/de/python/challenges/matching_brackets.md @@ -0,0 +1,149 @@ +--- +language: python +exerciseType: 1 +difficulty: 3 +title: Passende Klammern +--- + +# --description-- + +Text, der Code, Formeln oder Markup enthält, ist voller Klammern, und jede öffnende Klammer braucht eine schließende derselben Art. Ein String ist ausgeglichen, wenn sich seine Klammern paarweise entsprechen und wie die Schichten einer Zwiebel verschachteln: `{[()]}` ist ausgeglichen, `{[(])}` dagegen nicht, weil das runde Paar vor dem eckigen Paar geschlossen wird, in dem es liegt. + +Hier zählen drei Paare: runde `()`, eckige `[]` und geschweifte `{}`. Jedes andere Zeichen im String wird ignoriert. Eine schließende Klammer muss die zuletzt geöffnete Klammer schließen, die noch offen ist, und wenn der String endet, darf keine Klammer offen geblieben sein. + +# --instructions-- + +Schreiben Sie eine Funktion `is_balanced`, die einen String entgegennimmt und `True` zurückgibt, wenn alle darin enthaltenen Klammern übereinstimmen und korrekt verschachtelt sind, und andernfalls `False`. + +Beispiele: +``` +is_balanced("") ➞ True +is_balanced("{[()]}") ➞ True +is_balanced("{what is (42)}[?]") ➞ True +is_balanced("{[(])}") ➞ False +is_balanced("(") ➞ False +is_balanced(")(") ➞ False +``` + +- Ein leerer String ist ausgeglichen. +- Zeichen, die keine Klammern sind, werden ignoriert. +- Eine schließende Klammer muss zu der zuletzt geöffneten Klammer passen, die noch offen ist. +- Wenn der String endet, darf keine Klammer offen geblieben sein. + +# --seed-- + +```python +def is_balanced(text): + pass +``` + +# --before-asserts-- + +```python +import unittest + +class CodigoTests(unittest.TestCase): +``` + +# --asserts-- + +Ein leerer String ist ausgeglichen + +```python + def test1(self): + self.assertEqual(is_balanced(""), True, "--err-t1--") +``` + +Ein einzelnes Paar runder Klammern ist ausgeglichen + +```python + def test2(self): + self.assertEqual(is_balanced("()"), True, "--err-t2--") +``` + +Die drei Arten von Paaren, ineinander verschachtelt, sind ausgeglichen + +```python + def test3(self): + self.assertEqual(is_balanced("{[()]}"), True, "--err-t3--") +``` + +Klammern, die mit anderem Text vermischt sind, sind weiterhin ausgeglichen + +```python + def test4(self): + self.assertEqual(is_balanced("{what is (42)}[?]"), True, "--err-t4--") +``` + +Nebeneinander stehende Paare sind ausgeglichen + +```python + def test5(self): + self.assertEqual(is_balanced("()[]{}"), True, "--err-t5--") +``` + +Ein String ohne jegliche Klammern ist ausgeglichen + +```python + def test6(self): + self.assertEqual(is_balanced("no brackets in here at all"), True, "--err-t6--") +``` + +Ein überkreuztes Paar ist nicht ausgeglichen + +```python + def test7(self): + self.assertEqual(is_balanced("{[(])}"), False, "--err-t7--") +``` + +Eine öffnende Klammer, die nie geschlossen wird, ist nicht ausgeglichen + +```python + def test8(self): + self.assertEqual(is_balanced("("), False, "--err-t8--") +``` + +Eine schließende Klammer vor jeder öffnenden ist nicht ausgeglichen + +```python + def test9(self): + self.assertEqual(is_balanced(")("), False, "--err-t9--") +``` + +Überkreuzte Paare tiefer im String sind nicht ausgeglichen + +```python + def test10(self): + self.assertEqual(is_balanced("(([]{[}]))"), False, "--err-t10--") +``` + +Eine am Ende übrig gebliebene schließende Klammer ist nicht ausgeglichen + +```python + def test11(self): + self.assertEqual(is_balanced("())"), False, "--err-t11--") +``` + +# --after-asserts-- + +```python +if __name__ == "__main__": + unittest.main() +``` + +# --solutions-- + +```python +def is_balanced(text): + pairs = {")": "(", "]": "[", "}": "{"} + stack = [] + + for char in text: + if char in "([{": + stack.append(char) + elif char in pairs: + if not stack or stack.pop() != pairs[char]: + return False + + return not stack +``` diff --git a/de/swift/challenges/data.json b/de/swift/challenges/data.json index 684b34180..c3823dcd2 100644 --- a/de/swift/challenges/data.json +++ b/de/swift/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramm" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Passende Klammern" } } diff --git a/de/swift/challenges/matching_brackets.md b/de/swift/challenges/matching_brackets.md new file mode 100644 index 000000000..249f5e91b --- /dev/null +++ b/de/swift/challenges/matching_brackets.md @@ -0,0 +1,152 @@ +--- +language: swift +exerciseType: 1 +difficulty: 3 +title: Passende Klammern +--- + +# --description-- + +Text, der Code, Formeln oder Markup enthält, ist voller Klammern, und jede öffnende Klammer braucht eine schließende derselben Art. Ein String ist ausgeglichen, wenn sich seine Klammern paarweise entsprechen und wie die Schichten einer Zwiebel verschachteln: `{[()]}` ist ausgeglichen, `{[(])}` dagegen nicht, weil das runde Paar vor dem eckigen Paar geschlossen wird, in dem es liegt. + +Hier zählen drei Paare: runde `()`, eckige `[]` und geschweifte `{}`. Jedes andere Zeichen im String wird ignoriert. Eine schließende Klammer muss die zuletzt geöffnete Klammer schließen, die noch offen ist, und wenn der String endet, darf keine Klammer offen geblieben sein. + +# --instructions-- + +Schreiben Sie eine Funktion `isBalanced`, die einen String entgegennimmt und `true` zurückgibt, wenn alle darin enthaltenen Klammern übereinstimmen und korrekt verschachtelt sind, und andernfalls `false`. + +Beispiele: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Ein leerer String ist ausgeglichen. +- Zeichen, die keine Klammern sind, werden ignoriert. +- Eine schließende Klammer muss zu der zuletzt geöffneten Klammer passen, die noch offen ist. +- Wenn der String endet, darf keine Klammer offen geblieben sein. + +# --before-seed-- + +```swift +// DO NOT EDIT FROM HERE +import Foundation + +var _testCount = 0 +var _testFailedCount = 0 +func tryCatch(_ assertion: Bool) { + _testCount += 1 + if !assertion { + _testFailedCount += 1 + print("Test Case '--err-t\(_testCount)--' failed") + } +} +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```swift +func isBalanced(_ text: String) -> Bool { + +} +``` + +# --asserts-- + +Ein leerer String ist ausgeglichen + +```swift +tryCatch(isBalanced("") == true) +``` + +Ein einzelnes Paar runder Klammern ist ausgeglichen + +```swift +tryCatch(isBalanced("()") == true) +``` + +Die drei Arten von Paaren, ineinander verschachtelt, sind ausgeglichen + +```swift +tryCatch(isBalanced("{[()]}") == true) +``` + +Klammern, die mit anderem Text vermischt sind, sind weiterhin ausgeglichen + +```swift +tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +Nebeneinander stehende Paare sind ausgeglichen + +```swift +tryCatch(isBalanced("()[]{}") == true) +``` + +Ein String ohne jegliche Klammern ist ausgeglichen + +```swift +tryCatch(isBalanced("no brackets in here at all") == true) +``` + +Ein überkreuztes Paar ist nicht ausgeglichen + +```swift +tryCatch(isBalanced("{[(])}") == false) +``` + +Eine öffnende Klammer, die nie geschlossen wird, ist nicht ausgeglichen + +```swift +tryCatch(isBalanced("(") == false) +``` + +Eine schließende Klammer vor jeder öffnenden ist nicht ausgeglichen + +```swift +tryCatch(isBalanced(")(") == false) +``` + +Überkreuzte Paare tiefer im String sind nicht ausgeglichen + +```swift +tryCatch(isBalanced("(([]{[}]))") == false) +``` + +Eine am Ende übrig gebliebene schließende Klammer ist nicht ausgeglichen + +```swift +tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```swift +print("Executed \(_testCount) tests, with \(_testFailedCount) failures") +``` + +# --solutions-- + +```swift +func isBalanced(_ text: String) -> Bool { + let pairs: [Character: Character] = [")": "(", "]": "[", "}": "{"] + var stack: [Character] = [] + + for char in text { + if char == "(" || char == "[" || char == "{" { + stack.append(char) + } else if let opening = pairs[char] { + if stack.popLast() != opening { + return false + } + } + } + + return stack.isEmpty +} +``` diff --git a/en/c/challenges/data.json b/en/c/challenges/data.json index 5cb5007a2..6f8688de7 100644 --- a/en/c/challenges/data.json +++ b/en/c/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagram" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Matching brackets" } } diff --git a/en/c/challenges/matching_brackets.md b/en/c/challenges/matching_brackets.md new file mode 100644 index 000000000..d6695f97b --- /dev/null +++ b/en/c/challenges/matching_brackets.md @@ -0,0 +1,280 @@ +--- +language: c +exerciseType: 1 +difficulty: 3 +title: Matching brackets +--- + +# --description-- + +Text that carries code, maths or markup is full of brackets, and every opening bracket needs a closing one of the same kind. A string is balanced when its brackets pair up and nest like the layers of an onion: `{[()]}` is balanced, while `{[(])}` is not, because the round pair is closed before the square pair it sits inside. + +Three pairs count here: round `()`, square `[]` and curly `{}`. Every other character in the string is ignored. A closing bracket must close the most recently opened bracket that is still open, and when the string ends no bracket may be left open. + +# --instructions-- + +Write a function `is_balanced` that takes a string and returns `true` when all the brackets in it are matched and properly nested, and `false` otherwise. + +Examples: +``` +is_balanced("") ➞ true +is_balanced("{[()]}") ➞ true +is_balanced("{what is (42)}[?]") ➞ true +is_balanced("{[(])}") ➞ false +is_balanced("(") ➞ false +is_balanced(")(") ➞ false +``` + +- An empty string is balanced. +- Characters that are not brackets are ignored. +- A closing bracket must match the most recently opened bracket that is still open. +- No bracket may be left open when the string ends. + +# --before-seed-- + +```c +// DO NOT EDIT FROM HERE +#include +#include +#include + +#ifndef _CEXCEPTION_H +#define _CEXCEPTION_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +//This is the value to assign when there isn't an exception +#ifndef CEXCEPTION_NONE +#define CEXCEPTION_NONE (0x5A5A5A5A) +#endif + +//This is number of exception stacks to keep track of (one per task) +#ifndef CEXCEPTION_NUM_ID +#define CEXCEPTION_NUM_ID (1) //there is only the one stack by default +#endif + +//This is the method of getting the current exception stack index (0 if only one stack) +#ifndef CEXCEPTION_GET_ID +#define CEXCEPTION_GET_ID (0) //use the first index always because there is only one anyway +#endif + +//The type to use to store the exception values. +#ifndef CEXCEPTION_T +#define CEXCEPTION_T unsigned int +#endif + +//This is an optional special handler for when there is no global Catch +#ifndef CEXCEPTION_NO_CATCH_HANDLER +#define CEXCEPTION_NO_CATCH_HANDLER(id) +#endif + +//These hooks allow you to inject custom code into places, particularly useful for saving and restoring additional state +#ifndef CEXCEPTION_HOOK_START_TRY +#define CEXCEPTION_HOOK_START_TRY +#endif +#ifndef CEXCEPTION_HOOK_HAPPY_TRY +#define CEXCEPTION_HOOK_HAPPY_TRY +#endif +#ifndef CEXCEPTION_HOOK_AFTER_TRY +#define CEXCEPTION_HOOK_AFTER_TRY +#endif +#ifndef CEXCEPTION_HOOK_START_CATCH +#define CEXCEPTION_HOOK_START_CATCH +#endif + +//exception frame structures +typedef struct { + jmp_buf* pFrame; + CEXCEPTION_T volatile Exception; +} CEXCEPTION_FRAME_T; + +//actual root frame storage (only one if single-tasking) +extern volatile CEXCEPTION_FRAME_T CExceptionFrames[]; + +//Try +#define Try \ + { \ + jmp_buf *PrevFrame, NewFrame; \ + unsigned int MY_ID = CEXCEPTION_GET_ID; \ + PrevFrame = CExceptionFrames[MY_ID].pFrame; \ + CExceptionFrames[MY_ID].pFrame = (jmp_buf*)(&NewFrame); \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_START_TRY; \ + if (setjmp(NewFrame) == 0) { \ + if (1) + +//Catch +#define Catch(e) \ + else { } \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_HAPPY_TRY; \ + } \ + else \ + { \ + e = CExceptionFrames[MY_ID].Exception; \ + (void)e; \ + CEXCEPTION_HOOK_START_CATCH; \ + } \ + CExceptionFrames[MY_ID].pFrame = PrevFrame; \ + CEXCEPTION_HOOK_AFTER_TRY; \ + } \ + if (CExceptionFrames[CEXCEPTION_GET_ID].Exception != CEXCEPTION_NONE) + +#endif + +volatile CEXCEPTION_FRAME_T CExceptionFrames[CEXCEPTION_NUM_ID] = {{ 0 }}; + +void Throw(CEXCEPTION_T ExceptionID) +{ + unsigned int MY_ID = CEXCEPTION_GET_ID; + CExceptionFrames[MY_ID].Exception = ExceptionID; + if (CExceptionFrames[MY_ID].pFrame) + { + longjmp(*CExceptionFrames[MY_ID].pFrame, 1); + } + CEXCEPTION_NO_CATCH_HANDLER(ExceptionID); +} + +CEXCEPTION_T e; +int _test_failed_count = 0; +int _test_count = 0; + +void try_catch(bool assertion) { + _test_count++; + Try { + if (!assertion) { + Throw(_test_count); + } + } Catch (e) { + _test_failed_count += 1; + printf("Test Case '--err-t%i--' failed\n", e); + } +} +// DO NOT EDIT UNTIL HERE +#include +#include +``` + +# --seed-- + +```c +bool is_balanced(const char* text) { + +} +``` + +# --before-asserts-- + +```c +int main() { +``` + +# --asserts-- + +An empty string is balanced + +```c + try_catch(is_balanced("") == true); +``` + +A single pair of round brackets is balanced + +```c + try_catch(is_balanced("()") == true); +``` + +The three kinds of pair nested inside each other are balanced + +```c + try_catch(is_balanced("{[()]}") == true); +``` + +Brackets mixed with other text are still balanced + +```c + try_catch(is_balanced("{what is (42)}[?]") == true); +``` + +Pairs placed side by side are balanced + +```c + try_catch(is_balanced("()[]{}") == true); +``` + +A string without any brackets is balanced + +```c + try_catch(is_balanced("no brackets in here at all") == true); +``` + +A crossed pair is not balanced + +```c + try_catch(is_balanced("{[(])}") == false); +``` + +An opening bracket that is never closed is not balanced + +```c + try_catch(is_balanced("(") == false); +``` + +A closing bracket before any opening one is not balanced + +```c + try_catch(is_balanced(")(") == false); +``` + +Crossed pairs deeper in the string are not balanced + +```c + try_catch(is_balanced("(([]{[}]))") == false); +``` + +A closing bracket left over at the end is not balanced + +```c + try_catch(is_balanced("())") == false); +``` + +# --after-asserts-- + +```c + printf("Executed %d tests, with %d failures", _test_count, _test_failed_count); + return 0; +} +``` + +# --solutions-- + +```c +bool is_balanced(const char* text) { + size_t length = strlen(text); + char stack[length + 1]; + size_t top = 0; + + for (size_t i = 0; i < length; i++) { + char current = text[i]; + + if (current == '(' || current == '[' || current == '{') { + stack[top++] = current; + } else if (current == ')' || current == ']' || current == '}') { + if (top == 0) { + return false; + } + + char opening = stack[--top]; + if ((current == ')' && opening != '(') || + (current == ']' && opening != '[') || + (current == '}' && opening != '{')) { + return false; + } + } + } + + return top == 0; +} +``` diff --git a/en/dart/challenges/data.json b/en/dart/challenges/data.json index 5cb5007a2..6f8688de7 100644 --- a/en/dart/challenges/data.json +++ b/en/dart/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagram" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Matching brackets" } } diff --git a/en/dart/challenges/matching_brackets.md b/en/dart/challenges/matching_brackets.md new file mode 100644 index 000000000..11b7b8435 --- /dev/null +++ b/en/dart/challenges/matching_brackets.md @@ -0,0 +1,167 @@ +--- +language: dart +exerciseType: 1 +difficulty: 3 +title: Matching brackets +--- + +# --description-- + +Text that carries code, maths or markup is full of brackets, and every opening bracket needs a closing one of the same kind. A string is balanced when its brackets pair up and nest like the layers of an onion: `{[()]}` is balanced, while `{[(])}` is not, because the round pair is closed before the square pair it sits inside. + +Three pairs count here: round `()`, square `[]` and curly `{}`. Every other character in the string is ignored. A closing bracket must close the most recently opened bracket that is still open, and when the string ends no bracket may be left open. + +# --instructions-- + +Write a function `isBalanced` that takes a string and returns `true` when all the brackets in it are matched and properly nested, and `false` otherwise. + +Examples: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- An empty string is balanced. +- Characters that are not brackets are ignored. +- A closing bracket must match the most recently opened bracket that is still open. +- No bracket may be left open when the string ends. + +# --seed-- + +```dart +bool isBalanced(String text) { + +} +``` + +# --before-asserts-- + +```dart +import 'package:dart_runner/main.dart'; +import 'package:test/test.dart'; + +void main() { + group('MainTest -', () { +``` + +# --asserts-- + +An empty string is balanced + +```dart + test('test1', () { + expect(isBalanced(''), true, reason: '--err-t1--'); + }); +``` + +A single pair of round brackets is balanced + +```dart + test('test2', () { + expect(isBalanced('()'), true, reason: '--err-t2--'); + }); +``` + +The three kinds of pair nested inside each other are balanced + +```dart + test('test3', () { + expect(isBalanced('{[()]}'), true, reason: '--err-t3--'); + }); +``` + +Brackets mixed with other text are still balanced + +```dart + test('test4', () { + expect(isBalanced('{what is (42)}[?]'), true, reason: '--err-t4--'); + }); +``` + +Pairs placed side by side are balanced + +```dart + test('test5', () { + expect(isBalanced('()[]{}'), true, reason: '--err-t5--'); + }); +``` + +A string without any brackets is balanced + +```dart + test('test6', () { + expect(isBalanced('no brackets in here at all'), true, reason: '--err-t6--'); + }); +``` + +A crossed pair is not balanced + +```dart + test('test7', () { + expect(isBalanced('{[(])}'), false, reason: '--err-t7--'); + }); +``` + +An opening bracket that is never closed is not balanced + +```dart + test('test8', () { + expect(isBalanced('('), false, reason: '--err-t8--'); + }); +``` + +A closing bracket before any opening one is not balanced + +```dart + test('test9', () { + expect(isBalanced(')('), false, reason: '--err-t9--'); + }); +``` + +Crossed pairs deeper in the string are not balanced + +```dart + test('test10', () { + expect(isBalanced('(([]{[}]))'), false, reason: '--err-t10--'); + }); +``` + +A closing bracket left over at the end is not balanced + +```dart + test('test11', () { + expect(isBalanced('())'), false, reason: '--err-t11--'); + }); +``` + +# --after-asserts-- + +```dart + }, timeout: Timeout(const Duration(seconds: 1))); +} +``` + +# --solutions-- + +```dart +bool isBalanced(String text) { + const pairs = {')': '(', ']': '[', '}': '{'}; + final stack = []; + + for (final char in text.split('')) { + if (char == '(' || char == '[' || char == '{') { + stack.add(char); + } else if (pairs.containsKey(char)) { + if (stack.isEmpty || stack.removeLast() != pairs[char]) { + return false; + } + } + } + + return stack.isEmpty; +} +``` diff --git a/en/javascript/challenges/data.json b/en/javascript/challenges/data.json index b0f31ce27..c5d1d9160 100644 --- a/en/javascript/challenges/data.json +++ b/en/javascript/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagram" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Matching brackets" } } diff --git a/en/javascript/challenges/matching_brackets.md b/en/javascript/challenges/matching_brackets.md new file mode 100644 index 000000000..eb5d661ef --- /dev/null +++ b/en/javascript/challenges/matching_brackets.md @@ -0,0 +1,154 @@ +--- +language: javascript +exerciseType: 1 +difficulty: 3 +title: Matching brackets +--- + +# --description-- + +Text that carries code, maths or markup is full of brackets, and every opening bracket needs a closing one of the same kind. A string is balanced when its brackets pair up and nest like the layers of an onion: `{[()]}` is balanced, while `{[(])}` is not, because the round pair is closed before the square pair it sits inside. + +Three pairs count here: round `()`, square `[]` and curly `{}`. Every other character in the string is ignored. A closing bracket must close the most recently opened bracket that is still open, and when the string ends no bracket may be left open. + +# --instructions-- + +Write a function `isBalanced` that takes a string and returns `true` when all the brackets in it are matched and properly nested, and `false` otherwise. + +Examples: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- An empty string is balanced. +- Characters that are not brackets are ignored. +- A closing bracket must match the most recently opened bracket that is still open. +- No bracket may be left open when the string ends. + +# --before-seed-- + +```javascript +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +var assert = require('assert') +const tryCatch = (...args) => { + _testCount++ + try { assert(...args) } + catch (e) { + _testFailedCount++ + console.log(`Test Case '--err-t${_testCount}--' failed`); + } +}; +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```javascript +function isBalanced(text) { + +} +``` + +# --asserts-- + +An empty string is balanced + +```javascript +tryCatch(isBalanced("") === true); +``` + +A single pair of round brackets is balanced + +```javascript +tryCatch(isBalanced("()") === true); +``` + +The three kinds of pair nested inside each other are balanced + +```javascript +tryCatch(isBalanced("{[()]}") === true); +``` + +Brackets mixed with other text are still balanced + +```javascript +tryCatch(isBalanced("{what is (42)}[?]") === true); +``` + +Pairs placed side by side are balanced + +```javascript +tryCatch(isBalanced("()[]{}") === true); +``` + +A string without any brackets is balanced + +```javascript +tryCatch(isBalanced("no brackets in here at all") === true); +``` + +A crossed pair is not balanced + +```javascript +tryCatch(isBalanced("{[(])}") === false); +``` + +An opening bracket that is never closed is not balanced + +```javascript +tryCatch(isBalanced("(") === false); +``` + +A closing bracket before any opening one is not balanced + +```javascript +tryCatch(isBalanced(")(") === false); +``` + +Crossed pairs deeper in the string are not balanced + +```javascript +tryCatch(isBalanced("(([]{[}]))") === false); +``` + +A closing bracket left over at the end is not balanced + +```javascript +tryCatch(isBalanced("())") === false); +``` + +# --after-asserts-- + +```javascript +// DO NOT EDIT FROM HERE +console.log(`Executed ${_testCount} tests, with ${_testFailedCount} failures`); +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```javascript +function isBalanced(text) { + const pairs = { ")": "(", "]": "[", "}": "{" }; + const stack = []; + + for (const char of text) { + if (char === "(" || char === "[" || char === "{") { + stack.push(char); + } else if (char in pairs) { + if (stack.pop() !== pairs[char]) { + return false; + } + } + } + + return stack.length === 0; +} +``` diff --git a/en/kotlin/challenges/data.json b/en/kotlin/challenges/data.json index 5799afed0..d90dc49a2 100644 --- a/en/kotlin/challenges/data.json +++ b/en/kotlin/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagram" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Matching brackets" } } diff --git a/en/kotlin/challenges/matching_brackets.md b/en/kotlin/challenges/matching_brackets.md new file mode 100644 index 000000000..0f7ec5b02 --- /dev/null +++ b/en/kotlin/challenges/matching_brackets.md @@ -0,0 +1,157 @@ +--- +language: kotlin +exerciseType: 1 +difficulty: 3 +title: Matching brackets +--- + +# --description-- + +Text that carries code, maths or markup is full of brackets, and every opening bracket needs a closing one of the same kind. A string is balanced when its brackets pair up and nest like the layers of an onion: `{[()]}` is balanced, while `{[(])}` is not, because the round pair is closed before the square pair it sits inside. + +Three pairs count here: round `()`, square `[]` and curly `{}`. Every other character in the string is ignored. A closing bracket must close the most recently opened bracket that is still open, and when the string ends no bracket may be left open. + +# --instructions-- + +Write a function `isBalanced` that takes a string and returns `true` when all the brackets in it are matched and properly nested, and `false` otherwise. + +Examples: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- An empty string is balanced. +- Characters that are not brackets are ignored. +- A closing bracket must match the most recently opened bracket that is still open. +- No bracket may be left open when the string ends. + +# --seed-- + +```kotlin +fun isBalanced(text: String): Boolean { + +} +``` + +# --before-seed-- + +```kotlin +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +fun tryCatch(assertion: Boolean) { + _testCount++ + try { + if (!assertion) throw Exception() + } + catch (e: Throwable) { + _testFailedCount++ + println("Test Case '--err-t$_testCount--' failed"); + } +}; +// DO NOT EDIT UNTIL HERE +fun main() { +``` + +# --asserts-- + +An empty string is balanced + +```kotlin + tryCatch(isBalanced("") == true) +``` + +A single pair of round brackets is balanced + +```kotlin + tryCatch(isBalanced("()") == true) +``` + +The three kinds of pair nested inside each other are balanced + +```kotlin + tryCatch(isBalanced("{[()]}") == true) +``` + +Brackets mixed with other text are still balanced + +```kotlin + tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +Pairs placed side by side are balanced + +```kotlin + tryCatch(isBalanced("()[]{}") == true) +``` + +A string without any brackets is balanced + +```kotlin + tryCatch(isBalanced("no brackets in here at all") == true) +``` + +A crossed pair is not balanced + +```kotlin + tryCatch(isBalanced("{[(])}") == false) +``` + +An opening bracket that is never closed is not balanced + +```kotlin + tryCatch(isBalanced("(") == false) +``` + +A closing bracket before any opening one is not balanced + +```kotlin + tryCatch(isBalanced(")(") == false) +``` + +Crossed pairs deeper in the string are not balanced + +```kotlin + tryCatch(isBalanced("(([]{[}]))") == false) +``` + +A closing bracket left over at the end is not balanced + +```kotlin + tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```kotlin +// DO NOT EDIT FROM HERE + println("Executed $_testCount tests, with $_testFailedCount failures"); +} +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```kotlin +fun isBalanced(text: String): Boolean { + val pairs = mapOf(')' to '(', ']' to '[', '}' to '{') + val stack = ArrayDeque() + + for (char in text) { + if (char == '(' || char == '[' || char == '{') { + stack.addLast(char) + } else if (pairs.containsKey(char)) { + if (stack.isEmpty() || stack.removeLast() != pairs[char]) { + return false + } + } + } + + return stack.isEmpty() +} +``` diff --git a/en/python/challenges/data.json b/en/python/challenges/data.json index b0f31ce27..c5d1d9160 100644 --- a/en/python/challenges/data.json +++ b/en/python/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagram" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Matching brackets" } } diff --git a/en/python/challenges/matching_brackets.md b/en/python/challenges/matching_brackets.md new file mode 100644 index 000000000..8fcfeb913 --- /dev/null +++ b/en/python/challenges/matching_brackets.md @@ -0,0 +1,149 @@ +--- +language: python +exerciseType: 1 +difficulty: 3 +title: Matching brackets +--- + +# --description-- + +Text that carries code, maths or markup is full of brackets, and every opening bracket needs a closing one of the same kind. A string is balanced when its brackets pair up and nest like the layers of an onion: `{[()]}` is balanced, while `{[(])}` is not, because the round pair is closed before the square pair it sits inside. + +Three pairs count here: round `()`, square `[]` and curly `{}`. Every other character in the string is ignored. A closing bracket must close the most recently opened bracket that is still open, and when the string ends no bracket may be left open. + +# --instructions-- + +Write a function `is_balanced` that takes a string and returns `True` when all the brackets in it are matched and properly nested, and `False` otherwise. + +Examples: +``` +is_balanced("") ➞ True +is_balanced("{[()]}") ➞ True +is_balanced("{what is (42)}[?]") ➞ True +is_balanced("{[(])}") ➞ False +is_balanced("(") ➞ False +is_balanced(")(") ➞ False +``` + +- An empty string is balanced. +- Characters that are not brackets are ignored. +- A closing bracket must match the most recently opened bracket that is still open. +- No bracket may be left open when the string ends. + +# --seed-- + +```python +def is_balanced(text): + pass +``` + +# --before-asserts-- + +```python +import unittest + +class CodigoTests(unittest.TestCase): +``` + +# --asserts-- + +An empty string is balanced + +```python + def test1(self): + self.assertEqual(is_balanced(""), True, "--err-t1--") +``` + +A single pair of round brackets is balanced + +```python + def test2(self): + self.assertEqual(is_balanced("()"), True, "--err-t2--") +``` + +The three kinds of pair nested inside each other are balanced + +```python + def test3(self): + self.assertEqual(is_balanced("{[()]}"), True, "--err-t3--") +``` + +Brackets mixed with other text are still balanced + +```python + def test4(self): + self.assertEqual(is_balanced("{what is (42)}[?]"), True, "--err-t4--") +``` + +Pairs placed side by side are balanced + +```python + def test5(self): + self.assertEqual(is_balanced("()[]{}"), True, "--err-t5--") +``` + +A string without any brackets is balanced + +```python + def test6(self): + self.assertEqual(is_balanced("no brackets in here at all"), True, "--err-t6--") +``` + +A crossed pair is not balanced + +```python + def test7(self): + self.assertEqual(is_balanced("{[(])}"), False, "--err-t7--") +``` + +An opening bracket that is never closed is not balanced + +```python + def test8(self): + self.assertEqual(is_balanced("("), False, "--err-t8--") +``` + +A closing bracket before any opening one is not balanced + +```python + def test9(self): + self.assertEqual(is_balanced(")("), False, "--err-t9--") +``` + +Crossed pairs deeper in the string are not balanced + +```python + def test10(self): + self.assertEqual(is_balanced("(([]{[}]))"), False, "--err-t10--") +``` + +A closing bracket left over at the end is not balanced + +```python + def test11(self): + self.assertEqual(is_balanced("())"), False, "--err-t11--") +``` + +# --after-asserts-- + +```python +if __name__ == "__main__": + unittest.main() +``` + +# --solutions-- + +```python +def is_balanced(text): + pairs = {")": "(", "]": "[", "}": "{"} + stack = [] + + for char in text: + if char in "([{": + stack.append(char) + elif char in pairs: + if not stack or stack.pop() != pairs[char]: + return False + + return not stack +``` diff --git a/en/swift/challenges/data.json b/en/swift/challenges/data.json index 5cb5007a2..6f8688de7 100644 --- a/en/swift/challenges/data.json +++ b/en/swift/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagram" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Matching brackets" } } diff --git a/en/swift/challenges/matching_brackets.md b/en/swift/challenges/matching_brackets.md new file mode 100644 index 000000000..724e92f99 --- /dev/null +++ b/en/swift/challenges/matching_brackets.md @@ -0,0 +1,152 @@ +--- +language: swift +exerciseType: 1 +difficulty: 3 +title: Matching brackets +--- + +# --description-- + +Text that carries code, maths or markup is full of brackets, and every opening bracket needs a closing one of the same kind. A string is balanced when its brackets pair up and nest like the layers of an onion: `{[()]}` is balanced, while `{[(])}` is not, because the round pair is closed before the square pair it sits inside. + +Three pairs count here: round `()`, square `[]` and curly `{}`. Every other character in the string is ignored. A closing bracket must close the most recently opened bracket that is still open, and when the string ends no bracket may be left open. + +# --instructions-- + +Write a function `isBalanced` that takes a string and returns `true` when all the brackets in it are matched and properly nested, and `false` otherwise. + +Examples: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- An empty string is balanced. +- Characters that are not brackets are ignored. +- A closing bracket must match the most recently opened bracket that is still open. +- No bracket may be left open when the string ends. + +# --before-seed-- + +```swift +// DO NOT EDIT FROM HERE +import Foundation + +var _testCount = 0 +var _testFailedCount = 0 +func tryCatch(_ assertion: Bool) { + _testCount += 1 + if !assertion { + _testFailedCount += 1 + print("Test Case '--err-t\(_testCount)--' failed") + } +} +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```swift +func isBalanced(_ text: String) -> Bool { + +} +``` + +# --asserts-- + +An empty string is balanced + +```swift +tryCatch(isBalanced("") == true) +``` + +A single pair of round brackets is balanced + +```swift +tryCatch(isBalanced("()") == true) +``` + +The three kinds of pair nested inside each other are balanced + +```swift +tryCatch(isBalanced("{[()]}") == true) +``` + +Brackets mixed with other text are still balanced + +```swift +tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +Pairs placed side by side are balanced + +```swift +tryCatch(isBalanced("()[]{}") == true) +``` + +A string without any brackets is balanced + +```swift +tryCatch(isBalanced("no brackets in here at all") == true) +``` + +A crossed pair is not balanced + +```swift +tryCatch(isBalanced("{[(])}") == false) +``` + +An opening bracket that is never closed is not balanced + +```swift +tryCatch(isBalanced("(") == false) +``` + +A closing bracket before any opening one is not balanced + +```swift +tryCatch(isBalanced(")(") == false) +``` + +Crossed pairs deeper in the string are not balanced + +```swift +tryCatch(isBalanced("(([]{[}]))") == false) +``` + +A closing bracket left over at the end is not balanced + +```swift +tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```swift +print("Executed \(_testCount) tests, with \(_testFailedCount) failures") +``` + +# --solutions-- + +```swift +func isBalanced(_ text: String) -> Bool { + let pairs: [Character: Character] = [")": "(", "]": "[", "}": "{"] + var stack: [Character] = [] + + for char in text { + if char == "(" || char == "[" || char == "{" { + stack.append(char) + } else if let opening = pairs[char] { + if stack.popLast() != opening { + return false + } + } + } + + return stack.isEmpty +} +``` diff --git a/es/c/challenges/data.json b/es/c/challenges/data.json index 429638db8..3d8cbe784 100644 --- a/es/c/challenges/data.json +++ b/es/c/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagrama" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Corchetes coincidentes" } } diff --git a/es/c/challenges/matching_brackets.md b/es/c/challenges/matching_brackets.md new file mode 100644 index 000000000..2c55916d3 --- /dev/null +++ b/es/c/challenges/matching_brackets.md @@ -0,0 +1,280 @@ +--- +language: c +exerciseType: 1 +difficulty: 3 +title: Corchetes coincidentes +--- + +# --description-- + +El texto que contiene código, matemáticas o marcado está lleno de corchetes, y cada corchete de apertura necesita uno de cierre de la misma clase. Una cadena está equilibrada cuando sus corchetes se emparejan y se anidan como las capas de una cebolla: `{[()]}` está equilibrada, mientras que `{[(])}` no lo está, porque el par redondo se cierra antes que el par cuadrado dentro del cual se encuentra. + +Aquí cuentan tres pares: paréntesis `()`, corchetes `[]` y llaves `{}`. Todos los demás caracteres de la cadena se ignoran. Un corchete de cierre debe cerrar el último corchete que se haya abierto y que aún siga abierto, y cuando la cadena termina no debe quedar ningún corchete abierto. + +# --instructions-- + +Escribe una función `is_balanced` que tome una cadena y devuelva `true` cuando todos los corchetes que contiene estén emparejados y anidados correctamente, y `false` en caso contrario. + +Ejemplos: +``` +is_balanced("") ➞ true +is_balanced("{[()]}") ➞ true +is_balanced("{what is (42)}[?]") ➞ true +is_balanced("{[(])}") ➞ false +is_balanced("(") ➞ false +is_balanced(")(") ➞ false +``` + +- Una cadena vacía está equilibrada. +- Los caracteres que no son corchetes se ignoran. +- Un corchete de cierre debe corresponder al último corchete que se haya abierto y que aún siga abierto. +- No debe quedar ningún corchete abierto cuando la cadena termina. + +# --before-seed-- + +```c +// DO NOT EDIT FROM HERE +#include +#include +#include + +#ifndef _CEXCEPTION_H +#define _CEXCEPTION_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +//This is the value to assign when there isn't an exception +#ifndef CEXCEPTION_NONE +#define CEXCEPTION_NONE (0x5A5A5A5A) +#endif + +//This is number of exception stacks to keep track of (one per task) +#ifndef CEXCEPTION_NUM_ID +#define CEXCEPTION_NUM_ID (1) //there is only the one stack by default +#endif + +//This is the method of getting the current exception stack index (0 if only one stack) +#ifndef CEXCEPTION_GET_ID +#define CEXCEPTION_GET_ID (0) //use the first index always because there is only one anyway +#endif + +//The type to use to store the exception values. +#ifndef CEXCEPTION_T +#define CEXCEPTION_T unsigned int +#endif + +//This is an optional special handler for when there is no global Catch +#ifndef CEXCEPTION_NO_CATCH_HANDLER +#define CEXCEPTION_NO_CATCH_HANDLER(id) +#endif + +//These hooks allow you to inject custom code into places, particularly useful for saving and restoring additional state +#ifndef CEXCEPTION_HOOK_START_TRY +#define CEXCEPTION_HOOK_START_TRY +#endif +#ifndef CEXCEPTION_HOOK_HAPPY_TRY +#define CEXCEPTION_HOOK_HAPPY_TRY +#endif +#ifndef CEXCEPTION_HOOK_AFTER_TRY +#define CEXCEPTION_HOOK_AFTER_TRY +#endif +#ifndef CEXCEPTION_HOOK_START_CATCH +#define CEXCEPTION_HOOK_START_CATCH +#endif + +//exception frame structures +typedef struct { + jmp_buf* pFrame; + CEXCEPTION_T volatile Exception; +} CEXCEPTION_FRAME_T; + +//actual root frame storage (only one if single-tasking) +extern volatile CEXCEPTION_FRAME_T CExceptionFrames[]; + +//Try +#define Try \ + { \ + jmp_buf *PrevFrame, NewFrame; \ + unsigned int MY_ID = CEXCEPTION_GET_ID; \ + PrevFrame = CExceptionFrames[MY_ID].pFrame; \ + CExceptionFrames[MY_ID].pFrame = (jmp_buf*)(&NewFrame); \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_START_TRY; \ + if (setjmp(NewFrame) == 0) { \ + if (1) + +//Catch +#define Catch(e) \ + else { } \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_HAPPY_TRY; \ + } \ + else \ + { \ + e = CExceptionFrames[MY_ID].Exception; \ + (void)e; \ + CEXCEPTION_HOOK_START_CATCH; \ + } \ + CExceptionFrames[MY_ID].pFrame = PrevFrame; \ + CEXCEPTION_HOOK_AFTER_TRY; \ + } \ + if (CExceptionFrames[CEXCEPTION_GET_ID].Exception != CEXCEPTION_NONE) + +#endif + +volatile CEXCEPTION_FRAME_T CExceptionFrames[CEXCEPTION_NUM_ID] = {{ 0 }}; + +void Throw(CEXCEPTION_T ExceptionID) +{ + unsigned int MY_ID = CEXCEPTION_GET_ID; + CExceptionFrames[MY_ID].Exception = ExceptionID; + if (CExceptionFrames[MY_ID].pFrame) + { + longjmp(*CExceptionFrames[MY_ID].pFrame, 1); + } + CEXCEPTION_NO_CATCH_HANDLER(ExceptionID); +} + +CEXCEPTION_T e; +int _test_failed_count = 0; +int _test_count = 0; + +void try_catch(bool assertion) { + _test_count++; + Try { + if (!assertion) { + Throw(_test_count); + } + } Catch (e) { + _test_failed_count += 1; + printf("Test Case '--err-t%i--' failed\n", e); + } +} +// DO NOT EDIT UNTIL HERE +#include +#include +``` + +# --seed-- + +```c +bool is_balanced(const char* text) { + +} +``` + +# --before-asserts-- + +```c +int main() { +``` + +# --asserts-- + +Una cadena vacía está equilibrada + +```c + try_catch(is_balanced("") == true); +``` + +Un solo par de paréntesis está equilibrado + +```c + try_catch(is_balanced("()") == true); +``` + +Los tres tipos de pares anidados unos dentro de otros están equilibrados + +```c + try_catch(is_balanced("{[()]}") == true); +``` + +Los corchetes mezclados con otro texto siguen estando equilibrados + +```c + try_catch(is_balanced("{what is (42)}[?]") == true); +``` + +Los pares colocados uno al lado del otro están equilibrados + +```c + try_catch(is_balanced("()[]{}") == true); +``` + +Una cadena sin ningún corchete está equilibrada + +```c + try_catch(is_balanced("no brackets in here at all") == true); +``` + +Un par cruzado no está equilibrado + +```c + try_catch(is_balanced("{[(])}") == false); +``` + +Un corchete de apertura que nunca se cierra no está equilibrado + +```c + try_catch(is_balanced("(") == false); +``` + +Un corchete de cierre antes de cualquier corchete de apertura no está equilibrado + +```c + try_catch(is_balanced(")(") == false); +``` + +Los pares cruzados en lo profundo de la cadena no están equilibrados + +```c + try_catch(is_balanced("(([]{[}]))") == false); +``` + +Un corchete de cierre que sobra al final no está equilibrado + +```c + try_catch(is_balanced("())") == false); +``` + +# --after-asserts-- + +```c + printf("Executed %d tests, with %d failures", _test_count, _test_failed_count); + return 0; +} +``` + +# --solutions-- + +```c +bool is_balanced(const char* text) { + size_t length = strlen(text); + char stack[length + 1]; + size_t top = 0; + + for (size_t i = 0; i < length; i++) { + char current = text[i]; + + if (current == '(' || current == '[' || current == '{') { + stack[top++] = current; + } else if (current == ')' || current == ']' || current == '}') { + if (top == 0) { + return false; + } + + char opening = stack[--top]; + if ((current == ')' && opening != '(') || + (current == ']' && opening != '[') || + (current == '}' && opening != '{')) { + return false; + } + } + } + + return top == 0; +} +``` diff --git a/es/dart/challenges/data.json b/es/dart/challenges/data.json index 84810a66f..2ea3e0e15 100644 --- a/es/dart/challenges/data.json +++ b/es/dart/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagrama" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Corchetes coincidentes" } } diff --git a/es/dart/challenges/matching_brackets.md b/es/dart/challenges/matching_brackets.md new file mode 100644 index 000000000..9e7641714 --- /dev/null +++ b/es/dart/challenges/matching_brackets.md @@ -0,0 +1,167 @@ +--- +language: dart +exerciseType: 1 +difficulty: 3 +title: Corchetes coincidentes +--- + +# --description-- + +El texto que contiene código, matemáticas o marcado está lleno de corchetes, y cada corchete de apertura necesita uno de cierre de la misma clase. Una cadena está equilibrada cuando sus corchetes se emparejan y se anidan como las capas de una cebolla: `{[()]}` está equilibrada, mientras que `{[(])}` no lo está, porque el par redondo se cierra antes que el par cuadrado dentro del cual se encuentra. + +Aquí cuentan tres pares: paréntesis `()`, corchetes `[]` y llaves `{}`. Todos los demás caracteres de la cadena se ignoran. Un corchete de cierre debe cerrar el último corchete que se haya abierto y que aún siga abierto, y cuando la cadena termina no debe quedar ningún corchete abierto. + +# --instructions-- + +Escribe una función `isBalanced` que tome una cadena y devuelva `true` cuando todos los corchetes que contiene estén emparejados y anidados correctamente, y `false` en caso contrario. + +Ejemplos: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Una cadena vacía está equilibrada. +- Los caracteres que no son corchetes se ignoran. +- Un corchete de cierre debe corresponder al último corchete que se haya abierto y que aún siga abierto. +- No debe quedar ningún corchete abierto cuando la cadena termina. + +# --seed-- + +```dart +bool isBalanced(String text) { + +} +``` + +# --before-asserts-- + +```dart +import 'package:dart_runner/main.dart'; +import 'package:test/test.dart'; + +void main() { + group('MainTest -', () { +``` + +# --asserts-- + +Una cadena vacía está equilibrada + +```dart + test('test1', () { + expect(isBalanced(''), true, reason: '--err-t1--'); + }); +``` + +Un solo par de paréntesis está equilibrado + +```dart + test('test2', () { + expect(isBalanced('()'), true, reason: '--err-t2--'); + }); +``` + +Los tres tipos de pares anidados unos dentro de otros están equilibrados + +```dart + test('test3', () { + expect(isBalanced('{[()]}'), true, reason: '--err-t3--'); + }); +``` + +Los corchetes mezclados con otro texto siguen estando equilibrados + +```dart + test('test4', () { + expect(isBalanced('{what is (42)}[?]'), true, reason: '--err-t4--'); + }); +``` + +Los pares colocados uno al lado del otro están equilibrados + +```dart + test('test5', () { + expect(isBalanced('()[]{}'), true, reason: '--err-t5--'); + }); +``` + +Una cadena sin ningún corchete está equilibrada + +```dart + test('test6', () { + expect(isBalanced('no brackets in here at all'), true, reason: '--err-t6--'); + }); +``` + +Un par cruzado no está equilibrado + +```dart + test('test7', () { + expect(isBalanced('{[(])}'), false, reason: '--err-t7--'); + }); +``` + +Un corchete de apertura que nunca se cierra no está equilibrado + +```dart + test('test8', () { + expect(isBalanced('('), false, reason: '--err-t8--'); + }); +``` + +Un corchete de cierre antes de cualquier corchete de apertura no está equilibrado + +```dart + test('test9', () { + expect(isBalanced(')('), false, reason: '--err-t9--'); + }); +``` + +Los pares cruzados en lo profundo de la cadena no están equilibrados + +```dart + test('test10', () { + expect(isBalanced('(([]{[}]))'), false, reason: '--err-t10--'); + }); +``` + +Un corchete de cierre que sobra al final no está equilibrado + +```dart + test('test11', () { + expect(isBalanced('())'), false, reason: '--err-t11--'); + }); +``` + +# --after-asserts-- + +```dart + }, timeout: Timeout(const Duration(seconds: 1))); +} +``` + +# --solutions-- + +```dart +bool isBalanced(String text) { + const pairs = {')': '(', ']': '[', '}': '{'}; + final stack = []; + + for (final char in text.split('')) { + if (char == '(' || char == '[' || char == '{') { + stack.add(char); + } else if (pairs.containsKey(char)) { + if (stack.isEmpty || stack.removeLast() != pairs[char]) { + return false; + } + } + } + + return stack.isEmpty; +} +``` diff --git a/es/javascript/challenges/data.json b/es/javascript/challenges/data.json index 1e3d1dd82..dad647e8b 100644 --- a/es/javascript/challenges/data.json +++ b/es/javascript/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagrama" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Corchetes coincidentes" } } diff --git a/es/javascript/challenges/matching_brackets.md b/es/javascript/challenges/matching_brackets.md new file mode 100644 index 000000000..8a3923377 --- /dev/null +++ b/es/javascript/challenges/matching_brackets.md @@ -0,0 +1,154 @@ +--- +language: javascript +exerciseType: 1 +difficulty: 3 +title: Corchetes coincidentes +--- + +# --description-- + +El texto que contiene código, matemáticas o marcado está lleno de corchetes, y cada corchete de apertura necesita uno de cierre de la misma clase. Una cadena está equilibrada cuando sus corchetes se emparejan y se anidan como las capas de una cebolla: `{[()]}` está equilibrada, mientras que `{[(])}` no lo está, porque el par redondo se cierra antes que el par cuadrado dentro del cual se encuentra. + +Aquí cuentan tres pares: paréntesis `()`, corchetes `[]` y llaves `{}`. Todos los demás caracteres de la cadena se ignoran. Un corchete de cierre debe cerrar el último corchete que se haya abierto y que aún siga abierto, y cuando la cadena termina no debe quedar ningún corchete abierto. + +# --instructions-- + +Escribe una función `isBalanced` que tome una cadena y devuelva `true` cuando todos los corchetes que contiene estén emparejados y anidados correctamente, y `false` en caso contrario. + +Ejemplos: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Una cadena vacía está equilibrada. +- Los caracteres que no son corchetes se ignoran. +- Un corchete de cierre debe corresponder al último corchete que se haya abierto y que aún siga abierto. +- No debe quedar ningún corchete abierto cuando la cadena termina. + +# --before-seed-- + +```javascript +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +var assert = require('assert') +const tryCatch = (...args) => { + _testCount++ + try { assert(...args) } + catch (e) { + _testFailedCount++ + console.log(`Test Case '--err-t${_testCount}--' failed`); + } +}; +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```javascript +function isBalanced(text) { + +} +``` + +# --asserts-- + +Una cadena vacía está equilibrada + +```javascript +tryCatch(isBalanced("") === true); +``` + +Un solo par de paréntesis está equilibrado + +```javascript +tryCatch(isBalanced("()") === true); +``` + +Los tres tipos de pares anidados unos dentro de otros están equilibrados + +```javascript +tryCatch(isBalanced("{[()]}") === true); +``` + +Los corchetes mezclados con otro texto siguen estando equilibrados + +```javascript +tryCatch(isBalanced("{what is (42)}[?]") === true); +``` + +Los pares colocados uno al lado del otro están equilibrados + +```javascript +tryCatch(isBalanced("()[]{}") === true); +``` + +Una cadena sin ningún corchete está equilibrada + +```javascript +tryCatch(isBalanced("no brackets in here at all") === true); +``` + +Un par cruzado no está equilibrado + +```javascript +tryCatch(isBalanced("{[(])}") === false); +``` + +Un corchete de apertura que nunca se cierra no está equilibrado + +```javascript +tryCatch(isBalanced("(") === false); +``` + +Un corchete de cierre antes de cualquier corchete de apertura no está equilibrado + +```javascript +tryCatch(isBalanced(")(") === false); +``` + +Los pares cruzados en lo profundo de la cadena no están equilibrados + +```javascript +tryCatch(isBalanced("(([]{[}]))") === false); +``` + +Un corchete de cierre que sobra al final no está equilibrado + +```javascript +tryCatch(isBalanced("())") === false); +``` + +# --after-asserts-- + +```javascript +// DO NOT EDIT FROM HERE +console.log(`Executed ${_testCount} tests, with ${_testFailedCount} failures`); +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```javascript +function isBalanced(text) { + const pairs = { ")": "(", "]": "[", "}": "{" }; + const stack = []; + + for (const char of text) { + if (char === "(" || char === "[" || char === "{") { + stack.push(char); + } else if (char in pairs) { + if (stack.pop() !== pairs[char]) { + return false; + } + } + } + + return stack.length === 0; +} +``` diff --git a/es/kotlin/challenges/data.json b/es/kotlin/challenges/data.json index 841e6edfa..b58474d78 100644 --- a/es/kotlin/challenges/data.json +++ b/es/kotlin/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagrama" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Corchetes coincidentes" } } diff --git a/es/kotlin/challenges/matching_brackets.md b/es/kotlin/challenges/matching_brackets.md new file mode 100644 index 000000000..b58f3ea6d --- /dev/null +++ b/es/kotlin/challenges/matching_brackets.md @@ -0,0 +1,157 @@ +--- +language: kotlin +exerciseType: 1 +difficulty: 3 +title: Corchetes coincidentes +--- + +# --description-- + +El texto que contiene código, matemáticas o marcado está lleno de corchetes, y cada corchete de apertura necesita uno de cierre de la misma clase. Una cadena está equilibrada cuando sus corchetes se emparejan y se anidan como las capas de una cebolla: `{[()]}` está equilibrada, mientras que `{[(])}` no lo está, porque el par redondo se cierra antes que el par cuadrado dentro del cual se encuentra. + +Aquí cuentan tres pares: paréntesis `()`, corchetes `[]` y llaves `{}`. Todos los demás caracteres de la cadena se ignoran. Un corchete de cierre debe cerrar el último corchete que se haya abierto y que aún siga abierto, y cuando la cadena termina no debe quedar ningún corchete abierto. + +# --instructions-- + +Escribe una función `isBalanced` que tome una cadena y devuelva `true` cuando todos los corchetes que contiene estén emparejados y anidados correctamente, y `false` en caso contrario. + +Ejemplos: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Una cadena vacía está equilibrada. +- Los caracteres que no son corchetes se ignoran. +- Un corchete de cierre debe corresponder al último corchete que se haya abierto y que aún siga abierto. +- No debe quedar ningún corchete abierto cuando la cadena termina. + +# --seed-- + +```kotlin +fun isBalanced(text: String): Boolean { + +} +``` + +# --before-seed-- + +```kotlin +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +fun tryCatch(assertion: Boolean) { + _testCount++ + try { + if (!assertion) throw Exception() + } + catch (e: Throwable) { + _testFailedCount++ + println("Test Case '--err-t$_testCount--' failed"); + } +}; +// DO NOT EDIT UNTIL HERE +fun main() { +``` + +# --asserts-- + +Una cadena vacía está equilibrada + +```kotlin + tryCatch(isBalanced("") == true) +``` + +Un solo par de paréntesis está equilibrado + +```kotlin + tryCatch(isBalanced("()") == true) +``` + +Los tres tipos de pares anidados unos dentro de otros están equilibrados + +```kotlin + tryCatch(isBalanced("{[()]}") == true) +``` + +Los corchetes mezclados con otro texto siguen estando equilibrados + +```kotlin + tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +Los pares colocados uno al lado del otro están equilibrados + +```kotlin + tryCatch(isBalanced("()[]{}") == true) +``` + +Una cadena sin ningún corchete está equilibrada + +```kotlin + tryCatch(isBalanced("no brackets in here at all") == true) +``` + +Un par cruzado no está equilibrado + +```kotlin + tryCatch(isBalanced("{[(])}") == false) +``` + +Un corchete de apertura que nunca se cierra no está equilibrado + +```kotlin + tryCatch(isBalanced("(") == false) +``` + +Un corchete de cierre antes de cualquier corchete de apertura no está equilibrado + +```kotlin + tryCatch(isBalanced(")(") == false) +``` + +Los pares cruzados en lo profundo de la cadena no están equilibrados + +```kotlin + tryCatch(isBalanced("(([]{[}]))") == false) +``` + +Un corchete de cierre que sobra al final no está equilibrado + +```kotlin + tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```kotlin +// DO NOT EDIT FROM HERE + println("Executed $_testCount tests, with $_testFailedCount failures"); +} +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```kotlin +fun isBalanced(text: String): Boolean { + val pairs = mapOf(')' to '(', ']' to '[', '}' to '{') + val stack = ArrayDeque() + + for (char in text) { + if (char == '(' || char == '[' || char == '{') { + stack.addLast(char) + } else if (pairs.containsKey(char)) { + if (stack.isEmpty() || stack.removeLast() != pairs[char]) { + return false + } + } + } + + return stack.isEmpty() +} +``` diff --git a/es/python/challenges/data.json b/es/python/challenges/data.json index 1e3d1dd82..dad647e8b 100644 --- a/es/python/challenges/data.json +++ b/es/python/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagrama" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Corchetes coincidentes" } } diff --git a/es/python/challenges/matching_brackets.md b/es/python/challenges/matching_brackets.md new file mode 100644 index 000000000..7ad9579d3 --- /dev/null +++ b/es/python/challenges/matching_brackets.md @@ -0,0 +1,149 @@ +--- +language: python +exerciseType: 1 +difficulty: 3 +title: Corchetes coincidentes +--- + +# --description-- + +El texto que contiene código, matemáticas o marcado está lleno de corchetes, y cada corchete de apertura necesita uno de cierre de la misma clase. Una cadena está equilibrada cuando sus corchetes se emparejan y se anidan como las capas de una cebolla: `{[()]}` está equilibrada, mientras que `{[(])}` no lo está, porque el par redondo se cierra antes que el par cuadrado dentro del cual se encuentra. + +Aquí cuentan tres pares: paréntesis `()`, corchetes `[]` y llaves `{}`. Todos los demás caracteres de la cadena se ignoran. Un corchete de cierre debe cerrar el último corchete que se haya abierto y que aún siga abierto, y cuando la cadena termina no debe quedar ningún corchete abierto. + +# --instructions-- + +Escribe una función `is_balanced` que tome una cadena y devuelva `True` cuando todos los corchetes que contiene estén emparejados y anidados correctamente, y `False` en caso contrario. + +Ejemplos: +``` +is_balanced("") ➞ True +is_balanced("{[()]}") ➞ True +is_balanced("{what is (42)}[?]") ➞ True +is_balanced("{[(])}") ➞ False +is_balanced("(") ➞ False +is_balanced(")(") ➞ False +``` + +- Una cadena vacía está equilibrada. +- Los caracteres que no son corchetes se ignoran. +- Un corchete de cierre debe corresponder al último corchete que se haya abierto y que aún siga abierto. +- No debe quedar ningún corchete abierto cuando la cadena termina. + +# --seed-- + +```python +def is_balanced(text): + pass +``` + +# --before-asserts-- + +```python +import unittest + +class CodigoTests(unittest.TestCase): +``` + +# --asserts-- + +Una cadena vacía está equilibrada + +```python + def test1(self): + self.assertEqual(is_balanced(""), True, "--err-t1--") +``` + +Un solo par de paréntesis está equilibrado + +```python + def test2(self): + self.assertEqual(is_balanced("()"), True, "--err-t2--") +``` + +Los tres tipos de pares anidados unos dentro de otros están equilibrados + +```python + def test3(self): + self.assertEqual(is_balanced("{[()]}"), True, "--err-t3--") +``` + +Los corchetes mezclados con otro texto siguen estando equilibrados + +```python + def test4(self): + self.assertEqual(is_balanced("{what is (42)}[?]"), True, "--err-t4--") +``` + +Los pares colocados uno al lado del otro están equilibrados + +```python + def test5(self): + self.assertEqual(is_balanced("()[]{}"), True, "--err-t5--") +``` + +Una cadena sin ningún corchete está equilibrada + +```python + def test6(self): + self.assertEqual(is_balanced("no brackets in here at all"), True, "--err-t6--") +``` + +Un par cruzado no está equilibrado + +```python + def test7(self): + self.assertEqual(is_balanced("{[(])}"), False, "--err-t7--") +``` + +Un corchete de apertura que nunca se cierra no está equilibrado + +```python + def test8(self): + self.assertEqual(is_balanced("("), False, "--err-t8--") +``` + +Un corchete de cierre antes de cualquier corchete de apertura no está equilibrado + +```python + def test9(self): + self.assertEqual(is_balanced(")("), False, "--err-t9--") +``` + +Los pares cruzados en lo profundo de la cadena no están equilibrados + +```python + def test10(self): + self.assertEqual(is_balanced("(([]{[}]))"), False, "--err-t10--") +``` + +Un corchete de cierre que sobra al final no está equilibrado + +```python + def test11(self): + self.assertEqual(is_balanced("())"), False, "--err-t11--") +``` + +# --after-asserts-- + +```python +if __name__ == "__main__": + unittest.main() +``` + +# --solutions-- + +```python +def is_balanced(text): + pairs = {")": "(", "]": "[", "}": "{"} + stack = [] + + for char in text: + if char in "([{": + stack.append(char) + elif char in pairs: + if not stack or stack.pop() != pairs[char]: + return False + + return not stack +``` diff --git a/es/swift/challenges/data.json b/es/swift/challenges/data.json index 72b275258..6270895a6 100644 --- a/es/swift/challenges/data.json +++ b/es/swift/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagrama" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Corchetes coincidentes" } } diff --git a/es/swift/challenges/matching_brackets.md b/es/swift/challenges/matching_brackets.md new file mode 100644 index 000000000..9103b3ff7 --- /dev/null +++ b/es/swift/challenges/matching_brackets.md @@ -0,0 +1,152 @@ +--- +language: swift +exerciseType: 1 +difficulty: 3 +title: Corchetes coincidentes +--- + +# --description-- + +El texto que contiene código, matemáticas o marcado está lleno de corchetes, y cada corchete de apertura necesita uno de cierre de la misma clase. Una cadena está equilibrada cuando sus corchetes se emparejan y se anidan como las capas de una cebolla: `{[()]}` está equilibrada, mientras que `{[(])}` no lo está, porque el par redondo se cierra antes que el par cuadrado dentro del cual se encuentra. + +Aquí cuentan tres pares: paréntesis `()`, corchetes `[]` y llaves `{}`. Todos los demás caracteres de la cadena se ignoran. Un corchete de cierre debe cerrar el último corchete que se haya abierto y que aún siga abierto, y cuando la cadena termina no debe quedar ningún corchete abierto. + +# --instructions-- + +Escribe una función `isBalanced` que tome una cadena y devuelva `true` cuando todos los corchetes que contiene estén emparejados y anidados correctamente, y `false` en caso contrario. + +Ejemplos: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Una cadena vacía está equilibrada. +- Los caracteres que no son corchetes se ignoran. +- Un corchete de cierre debe corresponder al último corchete que se haya abierto y que aún siga abierto. +- No debe quedar ningún corchete abierto cuando la cadena termina. + +# --before-seed-- + +```swift +// DO NOT EDIT FROM HERE +import Foundation + +var _testCount = 0 +var _testFailedCount = 0 +func tryCatch(_ assertion: Bool) { + _testCount += 1 + if !assertion { + _testFailedCount += 1 + print("Test Case '--err-t\(_testCount)--' failed") + } +} +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```swift +func isBalanced(_ text: String) -> Bool { + +} +``` + +# --asserts-- + +Una cadena vacía está equilibrada + +```swift +tryCatch(isBalanced("") == true) +``` + +Un solo par de paréntesis está equilibrado + +```swift +tryCatch(isBalanced("()") == true) +``` + +Los tres tipos de pares anidados unos dentro de otros están equilibrados + +```swift +tryCatch(isBalanced("{[()]}") == true) +``` + +Los corchetes mezclados con otro texto siguen estando equilibrados + +```swift +tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +Los pares colocados uno al lado del otro están equilibrados + +```swift +tryCatch(isBalanced("()[]{}") == true) +``` + +Una cadena sin ningún corchete está equilibrada + +```swift +tryCatch(isBalanced("no brackets in here at all") == true) +``` + +Un par cruzado no está equilibrado + +```swift +tryCatch(isBalanced("{[(])}") == false) +``` + +Un corchete de apertura que nunca se cierra no está equilibrado + +```swift +tryCatch(isBalanced("(") == false) +``` + +Un corchete de cierre antes de cualquier corchete de apertura no está equilibrado + +```swift +tryCatch(isBalanced(")(") == false) +``` + +Los pares cruzados en lo profundo de la cadena no están equilibrados + +```swift +tryCatch(isBalanced("(([]{[}]))") == false) +``` + +Un corchete de cierre que sobra al final no está equilibrado + +```swift +tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```swift +print("Executed \(_testCount) tests, with \(_testFailedCount) failures") +``` + +# --solutions-- + +```swift +func isBalanced(_ text: String) -> Bool { + let pairs: [Character: Character] = [")": "(", "]": "[", "}": "{"] + var stack: [Character] = [] + + for char in text { + if char == "(" || char == "[" || char == "{" { + stack.append(char) + } else if let opening = pairs[char] { + if stack.popLast() != opening { + return false + } + } + } + + return stack.isEmpty +} +``` diff --git a/fr/c/challenges/data.json b/fr/c/challenges/data.json index 2ba2528b5..2a03139f7 100644 --- a/fr/c/challenges/data.json +++ b/fr/c/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramme" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Crochets correspondants" } } diff --git a/fr/c/challenges/matching_brackets.md b/fr/c/challenges/matching_brackets.md new file mode 100644 index 000000000..7aa861aa4 --- /dev/null +++ b/fr/c/challenges/matching_brackets.md @@ -0,0 +1,280 @@ +--- +language: c +exerciseType: 1 +difficulty: 3 +title: Crochets correspondants +--- + +# --description-- + +Le texte qui contient du code, des maths ou du balisage regorge de crochets, et chaque crochet ouvrant a besoin d'un crochet fermant de même type. Une chaîne est équilibrée lorsque ses crochets s'apparient et s'imbriquent comme les couches d'un oignon : `{[()]}` est équilibrée, alors que `{[(])}` ne l'est pas, car la paire ronde est fermée avant la paire carrée dans laquelle elle se trouve. + +Trois paires comptent ici : les rondes `()`, les carrées `[]` et les accolades `{}`. Tous les autres caractères de la chaîne sont ignorés. Un crochet fermant doit fermer le crochet le plus récemment ouvert encore ouvert, et lorsque la chaîne se termine, aucun crochet ne doit rester ouvert. + +# --instructions-- + +Écrivez une fonction `is_balanced` qui prend une chaîne et retourne `true` lorsque tous les crochets qu'elle contient sont appariés et correctement imbriqués, et `false` sinon. + +Exemples : +``` +is_balanced("") ➞ true +is_balanced("{[()]}") ➞ true +is_balanced("{what is (42)}[?]") ➞ true +is_balanced("{[(])}") ➞ false +is_balanced("(") ➞ false +is_balanced(")(") ➞ false +``` + +- Une chaîne vide est équilibrée. +- Les caractères qui ne sont pas des crochets sont ignorés. +- Un crochet fermant doit correspondre au crochet le plus récemment ouvert encore ouvert. +- Aucun crochet ne doit rester ouvert lorsque la chaîne se termine. + +# --before-seed-- + +```c +// DO NOT EDIT FROM HERE +#include +#include +#include + +#ifndef _CEXCEPTION_H +#define _CEXCEPTION_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +//This is the value to assign when there isn't an exception +#ifndef CEXCEPTION_NONE +#define CEXCEPTION_NONE (0x5A5A5A5A) +#endif + +//This is number of exception stacks to keep track of (one per task) +#ifndef CEXCEPTION_NUM_ID +#define CEXCEPTION_NUM_ID (1) //there is only the one stack by default +#endif + +//This is the method of getting the current exception stack index (0 if only one stack) +#ifndef CEXCEPTION_GET_ID +#define CEXCEPTION_GET_ID (0) //use the first index always because there is only one anyway +#endif + +//The type to use to store the exception values. +#ifndef CEXCEPTION_T +#define CEXCEPTION_T unsigned int +#endif + +//This is an optional special handler for when there is no global Catch +#ifndef CEXCEPTION_NO_CATCH_HANDLER +#define CEXCEPTION_NO_CATCH_HANDLER(id) +#endif + +//These hooks allow you to inject custom code into places, particularly useful for saving and restoring additional state +#ifndef CEXCEPTION_HOOK_START_TRY +#define CEXCEPTION_HOOK_START_TRY +#endif +#ifndef CEXCEPTION_HOOK_HAPPY_TRY +#define CEXCEPTION_HOOK_HAPPY_TRY +#endif +#ifndef CEXCEPTION_HOOK_AFTER_TRY +#define CEXCEPTION_HOOK_AFTER_TRY +#endif +#ifndef CEXCEPTION_HOOK_START_CATCH +#define CEXCEPTION_HOOK_START_CATCH +#endif + +//exception frame structures +typedef struct { + jmp_buf* pFrame; + CEXCEPTION_T volatile Exception; +} CEXCEPTION_FRAME_T; + +//actual root frame storage (only one if single-tasking) +extern volatile CEXCEPTION_FRAME_T CExceptionFrames[]; + +//Try +#define Try \ + { \ + jmp_buf *PrevFrame, NewFrame; \ + unsigned int MY_ID = CEXCEPTION_GET_ID; \ + PrevFrame = CExceptionFrames[MY_ID].pFrame; \ + CExceptionFrames[MY_ID].pFrame = (jmp_buf*)(&NewFrame); \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_START_TRY; \ + if (setjmp(NewFrame) == 0) { \ + if (1) + +//Catch +#define Catch(e) \ + else { } \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_HAPPY_TRY; \ + } \ + else \ + { \ + e = CExceptionFrames[MY_ID].Exception; \ + (void)e; \ + CEXCEPTION_HOOK_START_CATCH; \ + } \ + CExceptionFrames[MY_ID].pFrame = PrevFrame; \ + CEXCEPTION_HOOK_AFTER_TRY; \ + } \ + if (CExceptionFrames[CEXCEPTION_GET_ID].Exception != CEXCEPTION_NONE) + +#endif + +volatile CEXCEPTION_FRAME_T CExceptionFrames[CEXCEPTION_NUM_ID] = {{ 0 }}; + +void Throw(CEXCEPTION_T ExceptionID) +{ + unsigned int MY_ID = CEXCEPTION_GET_ID; + CExceptionFrames[MY_ID].Exception = ExceptionID; + if (CExceptionFrames[MY_ID].pFrame) + { + longjmp(*CExceptionFrames[MY_ID].pFrame, 1); + } + CEXCEPTION_NO_CATCH_HANDLER(ExceptionID); +} + +CEXCEPTION_T e; +int _test_failed_count = 0; +int _test_count = 0; + +void try_catch(bool assertion) { + _test_count++; + Try { + if (!assertion) { + Throw(_test_count); + } + } Catch (e) { + _test_failed_count += 1; + printf("Test Case '--err-t%i--' failed\n", e); + } +} +// DO NOT EDIT UNTIL HERE +#include +#include +``` + +# --seed-- + +```c +bool is_balanced(const char* text) { + +} +``` + +# --before-asserts-- + +```c +int main() { +``` + +# --asserts-- + +Une chaîne vide est équilibrée + +```c + try_catch(is_balanced("") == true); +``` + +Une seule paire de crochets ronds est équilibrée + +```c + try_catch(is_balanced("()") == true); +``` + +Les trois types de paires imbriquées l'une dans l'autre sont équilibrées + +```c + try_catch(is_balanced("{[()]}") == true); +``` + +Des crochets mélangés à d'autres textes restent équilibrés + +```c + try_catch(is_balanced("{what is (42)}[?]") == true); +``` + +Des paires placées côte à côte sont équilibrées + +```c + try_catch(is_balanced("()[]{}") == true); +``` + +Une chaîne sans aucun crochet est équilibrée + +```c + try_catch(is_balanced("no brackets in here at all") == true); +``` + +Une paire croisée n'est pas équilibrée + +```c + try_catch(is_balanced("{[(])}") == false); +``` + +Un crochet ouvrant jamais fermé n'est pas équilibré + +```c + try_catch(is_balanced("(") == false); +``` + +Un crochet fermant avant tout crochet ouvrant n'est pas équilibré + +```c + try_catch(is_balanced(")(") == false); +``` + +Des paires croisées plus profondément dans la chaîne ne sont pas équilibrées + +```c + try_catch(is_balanced("(([]{[}]))") == false); +``` + +Un crochet fermant restant à la fin n'est pas équilibré + +```c + try_catch(is_balanced("())") == false); +``` + +# --after-asserts-- + +```c + printf("Executed %d tests, with %d failures", _test_count, _test_failed_count); + return 0; +} +``` + +# --solutions-- + +```c +bool is_balanced(const char* text) { + size_t length = strlen(text); + char stack[length + 1]; + size_t top = 0; + + for (size_t i = 0; i < length; i++) { + char current = text[i]; + + if (current == '(' || current == '[' || current == '{') { + stack[top++] = current; + } else if (current == ')' || current == ']' || current == '}') { + if (top == 0) { + return false; + } + + char opening = stack[--top]; + if ((current == ')' && opening != '(') || + (current == ']' && opening != '[') || + (current == '}' && opening != '{')) { + return false; + } + } + } + + return top == 0; +} +``` diff --git a/fr/dart/challenges/data.json b/fr/dart/challenges/data.json index 0ebc6056e..f40d547dd 100644 --- a/fr/dart/challenges/data.json +++ b/fr/dart/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramme" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Crochets correspondants" } } diff --git a/fr/dart/challenges/matching_brackets.md b/fr/dart/challenges/matching_brackets.md new file mode 100644 index 000000000..e8f5310ad --- /dev/null +++ b/fr/dart/challenges/matching_brackets.md @@ -0,0 +1,167 @@ +--- +language: dart +exerciseType: 1 +difficulty: 3 +title: Crochets correspondants +--- + +# --description-- + +Le texte qui contient du code, des maths ou du balisage regorge de crochets, et chaque crochet ouvrant a besoin d'un crochet fermant de même type. Une chaîne est équilibrée lorsque ses crochets s'apparient et s'imbriquent comme les couches d'un oignon : `{[()]}` est équilibrée, alors que `{[(])}` ne l'est pas, car la paire ronde est fermée avant la paire carrée dans laquelle elle se trouve. + +Trois paires comptent ici : les rondes `()`, les carrées `[]` et les accolades `{}`. Tous les autres caractères de la chaîne sont ignorés. Un crochet fermant doit fermer le crochet le plus récemment ouvert encore ouvert, et lorsque la chaîne se termine, aucun crochet ne doit rester ouvert. + +# --instructions-- + +Écrivez une fonction `isBalanced` qui prend une chaîne et retourne `true` lorsque tous les crochets qu'elle contient sont appariés et correctement imbriqués, et `false` sinon. + +Exemples : +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Une chaîne vide est équilibrée. +- Les caractères qui ne sont pas des crochets sont ignorés. +- Un crochet fermant doit correspondre au crochet le plus récemment ouvert encore ouvert. +- Aucun crochet ne doit rester ouvert lorsque la chaîne se termine. + +# --seed-- + +```dart +bool isBalanced(String text) { + +} +``` + +# --before-asserts-- + +```dart +import 'package:dart_runner/main.dart'; +import 'package:test/test.dart'; + +void main() { + group('MainTest -', () { +``` + +# --asserts-- + +Une chaîne vide est équilibrée + +```dart + test('test1', () { + expect(isBalanced(''), true, reason: '--err-t1--'); + }); +``` + +Une seule paire de crochets ronds est équilibrée + +```dart + test('test2', () { + expect(isBalanced('()'), true, reason: '--err-t2--'); + }); +``` + +Les trois types de paires imbriquées l'une dans l'autre sont équilibrées + +```dart + test('test3', () { + expect(isBalanced('{[()]}'), true, reason: '--err-t3--'); + }); +``` + +Des crochets mélangés à d'autres textes restent équilibrés + +```dart + test('test4', () { + expect(isBalanced('{what is (42)}[?]'), true, reason: '--err-t4--'); + }); +``` + +Des paires placées côte à côte sont équilibrées + +```dart + test('test5', () { + expect(isBalanced('()[]{}'), true, reason: '--err-t5--'); + }); +``` + +Une chaîne sans aucun crochet est équilibrée + +```dart + test('test6', () { + expect(isBalanced('no brackets in here at all'), true, reason: '--err-t6--'); + }); +``` + +Une paire croisée n'est pas équilibrée + +```dart + test('test7', () { + expect(isBalanced('{[(])}'), false, reason: '--err-t7--'); + }); +``` + +Un crochet ouvrant jamais fermé n'est pas équilibré + +```dart + test('test8', () { + expect(isBalanced('('), false, reason: '--err-t8--'); + }); +``` + +Un crochet fermant avant tout crochet ouvrant n'est pas équilibré + +```dart + test('test9', () { + expect(isBalanced(')('), false, reason: '--err-t9--'); + }); +``` + +Des paires croisées plus profondément dans la chaîne ne sont pas équilibrées + +```dart + test('test10', () { + expect(isBalanced('(([]{[}]))'), false, reason: '--err-t10--'); + }); +``` + +Un crochet fermant restant à la fin n'est pas équilibré + +```dart + test('test11', () { + expect(isBalanced('())'), false, reason: '--err-t11--'); + }); +``` + +# --after-asserts-- + +```dart + }, timeout: Timeout(const Duration(seconds: 1))); +} +``` + +# --solutions-- + +```dart +bool isBalanced(String text) { + const pairs = {')': '(', ']': '[', '}': '{'}; + final stack = []; + + for (final char in text.split('')) { + if (char == '(' || char == '[' || char == '{') { + stack.add(char); + } else if (pairs.containsKey(char)) { + if (stack.isEmpty || stack.removeLast() != pairs[char]) { + return false; + } + } + } + + return stack.isEmpty; +} +``` diff --git a/fr/javascript/challenges/data.json b/fr/javascript/challenges/data.json index 51f92004d..2d4d29a03 100644 --- a/fr/javascript/challenges/data.json +++ b/fr/javascript/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramme" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Crochets correspondants" } } diff --git a/fr/javascript/challenges/matching_brackets.md b/fr/javascript/challenges/matching_brackets.md new file mode 100644 index 000000000..cc7a09f6e --- /dev/null +++ b/fr/javascript/challenges/matching_brackets.md @@ -0,0 +1,154 @@ +--- +language: javascript +exerciseType: 1 +difficulty: 3 +title: Crochets correspondants +--- + +# --description-- + +Le texte qui contient du code, des maths ou du balisage regorge de crochets, et chaque crochet ouvrant a besoin d'un crochet fermant de même type. Une chaîne est équilibrée lorsque ses crochets s'apparient et s'imbriquent comme les couches d'un oignon : `{[()]}` est équilibrée, alors que `{[(])}` ne l'est pas, car la paire ronde est fermée avant la paire carrée dans laquelle elle se trouve. + +Trois paires comptent ici : les rondes `()`, les carrées `[]` et les accolades `{}`. Tous les autres caractères de la chaîne sont ignorés. Un crochet fermant doit fermer le crochet le plus récemment ouvert encore ouvert, et lorsque la chaîne se termine, aucun crochet ne doit rester ouvert. + +# --instructions-- + +Écrivez une fonction `isBalanced` qui prend une chaîne et retourne `true` lorsque tous les crochets qu'elle contient sont appariés et correctement imbriqués, et `false` sinon. + +Exemples : +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Une chaîne vide est équilibrée. +- Les caractères qui ne sont pas des crochets sont ignorés. +- Un crochet fermant doit correspondre au crochet le plus récemment ouvert encore ouvert. +- Aucun crochet ne doit rester ouvert lorsque la chaîne se termine. + +# --before-seed-- + +```javascript +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +var assert = require('assert') +const tryCatch = (...args) => { + _testCount++ + try { assert(...args) } + catch (e) { + _testFailedCount++ + console.log(`Test Case '--err-t${_testCount}--' failed`); + } +}; +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```javascript +function isBalanced(text) { + +} +``` + +# --asserts-- + +Une chaîne vide est équilibrée + +```javascript +tryCatch(isBalanced("") === true); +``` + +Une seule paire de crochets ronds est équilibrée + +```javascript +tryCatch(isBalanced("()") === true); +``` + +Les trois types de paires imbriquées l'une dans l'autre sont équilibrées + +```javascript +tryCatch(isBalanced("{[()]}") === true); +``` + +Des crochets mélangés à d'autres textes restent équilibrés + +```javascript +tryCatch(isBalanced("{what is (42)}[?]") === true); +``` + +Des paires placées côte à côte sont équilibrées + +```javascript +tryCatch(isBalanced("()[]{}") === true); +``` + +Une chaîne sans aucun crochet est équilibrée + +```javascript +tryCatch(isBalanced("no brackets in here at all") === true); +``` + +Une paire croisée n'est pas équilibrée + +```javascript +tryCatch(isBalanced("{[(])}") === false); +``` + +Un crochet ouvrant jamais fermé n'est pas équilibré + +```javascript +tryCatch(isBalanced("(") === false); +``` + +Un crochet fermant avant tout crochet ouvrant n'est pas équilibré + +```javascript +tryCatch(isBalanced(")(") === false); +``` + +Des paires croisées plus profondément dans la chaîne ne sont pas équilibrées + +```javascript +tryCatch(isBalanced("(([]{[}]))") === false); +``` + +Un crochet fermant restant à la fin n'est pas équilibré + +```javascript +tryCatch(isBalanced("())") === false); +``` + +# --after-asserts-- + +```javascript +// DO NOT EDIT FROM HERE +console.log(`Executed ${_testCount} tests, with ${_testFailedCount} failures`); +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```javascript +function isBalanced(text) { + const pairs = { ")": "(", "]": "[", "}": "{" }; + const stack = []; + + for (const char of text) { + if (char === "(" || char === "[" || char === "{") { + stack.push(char); + } else if (char in pairs) { + if (stack.pop() !== pairs[char]) { + return false; + } + } + } + + return stack.length === 0; +} +``` diff --git a/fr/kotlin/challenges/data.json b/fr/kotlin/challenges/data.json index f86b17c6f..f67fe40ca 100644 --- a/fr/kotlin/challenges/data.json +++ b/fr/kotlin/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramme" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Crochets correspondants" } } diff --git a/fr/kotlin/challenges/matching_brackets.md b/fr/kotlin/challenges/matching_brackets.md new file mode 100644 index 000000000..1129315ad --- /dev/null +++ b/fr/kotlin/challenges/matching_brackets.md @@ -0,0 +1,157 @@ +--- +language: kotlin +exerciseType: 1 +difficulty: 3 +title: Crochets correspondants +--- + +# --description-- + +Le texte qui contient du code, des maths ou du balisage regorge de crochets, et chaque crochet ouvrant a besoin d'un crochet fermant de même type. Une chaîne est équilibrée lorsque ses crochets s'apparient et s'imbriquent comme les couches d'un oignon : `{[()]}` est équilibrée, alors que `{[(])}` ne l'est pas, car la paire ronde est fermée avant la paire carrée dans laquelle elle se trouve. + +Trois paires comptent ici : les rondes `()`, les carrées `[]` et les accolades `{}`. Tous les autres caractères de la chaîne sont ignorés. Un crochet fermant doit fermer le crochet le plus récemment ouvert encore ouvert, et lorsque la chaîne se termine, aucun crochet ne doit rester ouvert. + +# --instructions-- + +Écrivez une fonction `isBalanced` qui prend une chaîne et retourne `true` lorsque tous les crochets qu'elle contient sont appariés et correctement imbriqués, et `false` sinon. + +Exemples : +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Une chaîne vide est équilibrée. +- Les caractères qui ne sont pas des crochets sont ignorés. +- Un crochet fermant doit correspondre au crochet le plus récemment ouvert encore ouvert. +- Aucun crochet ne doit rester ouvert lorsque la chaîne se termine. + +# --seed-- + +```kotlin +fun isBalanced(text: String): Boolean { + +} +``` + +# --before-seed-- + +```kotlin +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +fun tryCatch(assertion: Boolean) { + _testCount++ + try { + if (!assertion) throw Exception() + } + catch (e: Throwable) { + _testFailedCount++ + println("Test Case '--err-t$_testCount--' failed"); + } +}; +// DO NOT EDIT UNTIL HERE +fun main() { +``` + +# --asserts-- + +Une chaîne vide est équilibrée + +```kotlin + tryCatch(isBalanced("") == true) +``` + +Une seule paire de crochets ronds est équilibrée + +```kotlin + tryCatch(isBalanced("()") == true) +``` + +Les trois types de paires imbriquées l'une dans l'autre sont équilibrées + +```kotlin + tryCatch(isBalanced("{[()]}") == true) +``` + +Des crochets mélangés à d'autres textes restent équilibrés + +```kotlin + tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +Des paires placées côte à côte sont équilibrées + +```kotlin + tryCatch(isBalanced("()[]{}") == true) +``` + +Une chaîne sans aucun crochet est équilibrée + +```kotlin + tryCatch(isBalanced("no brackets in here at all") == true) +``` + +Une paire croisée n'est pas équilibrée + +```kotlin + tryCatch(isBalanced("{[(])}") == false) +``` + +Un crochet ouvrant jamais fermé n'est pas équilibré + +```kotlin + tryCatch(isBalanced("(") == false) +``` + +Un crochet fermant avant tout crochet ouvrant n'est pas équilibré + +```kotlin + tryCatch(isBalanced(")(") == false) +``` + +Des paires croisées plus profondément dans la chaîne ne sont pas équilibrées + +```kotlin + tryCatch(isBalanced("(([]{[}]))") == false) +``` + +Un crochet fermant restant à la fin n'est pas équilibré + +```kotlin + tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```kotlin +// DO NOT EDIT FROM HERE + println("Executed $_testCount tests, with $_testFailedCount failures"); +} +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```kotlin +fun isBalanced(text: String): Boolean { + val pairs = mapOf(')' to '(', ']' to '[', '}' to '{') + val stack = ArrayDeque() + + for (char in text) { + if (char == '(' || char == '[' || char == '{') { + stack.addLast(char) + } else if (pairs.containsKey(char)) { + if (stack.isEmpty() || stack.removeLast() != pairs[char]) { + return false + } + } + } + + return stack.isEmpty() +} +``` diff --git a/fr/python/challenges/data.json b/fr/python/challenges/data.json index 51f92004d..2d4d29a03 100644 --- a/fr/python/challenges/data.json +++ b/fr/python/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramme" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Crochets correspondants" } } diff --git a/fr/python/challenges/matching_brackets.md b/fr/python/challenges/matching_brackets.md new file mode 100644 index 000000000..848f444be --- /dev/null +++ b/fr/python/challenges/matching_brackets.md @@ -0,0 +1,149 @@ +--- +language: python +exerciseType: 1 +difficulty: 3 +title: Crochets correspondants +--- + +# --description-- + +Le texte qui contient du code, des maths ou du balisage regorge de crochets, et chaque crochet ouvrant a besoin d'un crochet fermant de même type. Une chaîne est équilibrée lorsque ses crochets s'apparient et s'imbriquent comme les couches d'un oignon : `{[()]}` est équilibrée, alors que `{[(])}` ne l'est pas, car la paire ronde est fermée avant la paire carrée dans laquelle elle se trouve. + +Trois paires comptent ici : les rondes `()`, les carrées `[]` et les accolades `{}`. Tous les autres caractères de la chaîne sont ignorés. Un crochet fermant doit fermer le crochet le plus récemment ouvert encore ouvert, et lorsque la chaîne se termine, aucun crochet ne doit rester ouvert. + +# --instructions-- + +Écrivez une fonction `is_balanced` qui prend une chaîne et retourne `True` lorsque tous les crochets qu'elle contient sont appariés et correctement imbriqués, et `False` sinon. + +Exemples : +``` +is_balanced("") ➞ True +is_balanced("{[()]}") ➞ True +is_balanced("{what is (42)}[?]") ➞ True +is_balanced("{[(])}") ➞ False +is_balanced("(") ➞ False +is_balanced(")(") ➞ False +``` + +- Une chaîne vide est équilibrée. +- Les caractères qui ne sont pas des crochets sont ignorés. +- Un crochet fermant doit correspondre au crochet le plus récemment ouvert encore ouvert. +- Aucun crochet ne doit rester ouvert lorsque la chaîne se termine. + +# --seed-- + +```python +def is_balanced(text): + pass +``` + +# --before-asserts-- + +```python +import unittest + +class CodigoTests(unittest.TestCase): +``` + +# --asserts-- + +Une chaîne vide est équilibrée + +```python + def test1(self): + self.assertEqual(is_balanced(""), True, "--err-t1--") +``` + +Une seule paire de crochets ronds est équilibrée + +```python + def test2(self): + self.assertEqual(is_balanced("()"), True, "--err-t2--") +``` + +Les trois types de paires imbriquées l'une dans l'autre sont équilibrées + +```python + def test3(self): + self.assertEqual(is_balanced("{[()]}"), True, "--err-t3--") +``` + +Des crochets mélangés à d'autres textes restent équilibrés + +```python + def test4(self): + self.assertEqual(is_balanced("{what is (42)}[?]"), True, "--err-t4--") +``` + +Des paires placées côte à côte sont équilibrées + +```python + def test5(self): + self.assertEqual(is_balanced("()[]{}"), True, "--err-t5--") +``` + +Une chaîne sans aucun crochet est équilibrée + +```python + def test6(self): + self.assertEqual(is_balanced("no brackets in here at all"), True, "--err-t6--") +``` + +Une paire croisée n'est pas équilibrée + +```python + def test7(self): + self.assertEqual(is_balanced("{[(])}"), False, "--err-t7--") +``` + +Un crochet ouvrant jamais fermé n'est pas équilibré + +```python + def test8(self): + self.assertEqual(is_balanced("("), False, "--err-t8--") +``` + +Un crochet fermant avant tout crochet ouvrant n'est pas équilibré + +```python + def test9(self): + self.assertEqual(is_balanced(")("), False, "--err-t9--") +``` + +Des paires croisées plus profondément dans la chaîne ne sont pas équilibrées + +```python + def test10(self): + self.assertEqual(is_balanced("(([]{[}]))"), False, "--err-t10--") +``` + +Un crochet fermant restant à la fin n'est pas équilibré + +```python + def test11(self): + self.assertEqual(is_balanced("())"), False, "--err-t11--") +``` + +# --after-asserts-- + +```python +if __name__ == "__main__": + unittest.main() +``` + +# --solutions-- + +```python +def is_balanced(text): + pairs = {")": "(", "]": "[", "}": "{"} + stack = [] + + for char in text: + if char in "([{": + stack.append(char) + elif char in pairs: + if not stack or stack.pop() != pairs[char]: + return False + + return not stack +``` diff --git a/fr/swift/challenges/data.json b/fr/swift/challenges/data.json index 4020e975b..4aa180e26 100644 --- a/fr/swift/challenges/data.json +++ b/fr/swift/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramme" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Crochets correspondants" } } diff --git a/fr/swift/challenges/matching_brackets.md b/fr/swift/challenges/matching_brackets.md new file mode 100644 index 000000000..968514871 --- /dev/null +++ b/fr/swift/challenges/matching_brackets.md @@ -0,0 +1,152 @@ +--- +language: swift +exerciseType: 1 +difficulty: 3 +title: Crochets correspondants +--- + +# --description-- + +Le texte qui contient du code, des maths ou du balisage regorge de crochets, et chaque crochet ouvrant a besoin d'un crochet fermant de même type. Une chaîne est équilibrée lorsque ses crochets s'apparient et s'imbriquent comme les couches d'un oignon : `{[()]}` est équilibrée, alors que `{[(])}` ne l'est pas, car la paire ronde est fermée avant la paire carrée dans laquelle elle se trouve. + +Trois paires comptent ici : les rondes `()`, les carrées `[]` et les accolades `{}`. Tous les autres caractères de la chaîne sont ignorés. Un crochet fermant doit fermer le crochet le plus récemment ouvert encore ouvert, et lorsque la chaîne se termine, aucun crochet ne doit rester ouvert. + +# --instructions-- + +Écrivez une fonction `isBalanced` qui prend une chaîne et retourne `true` lorsque tous les crochets qu'elle contient sont appariés et correctement imbriqués, et `false` sinon. + +Exemples : +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Une chaîne vide est équilibrée. +- Les caractères qui ne sont pas des crochets sont ignorés. +- Un crochet fermant doit correspondre au crochet le plus récemment ouvert encore ouvert. +- Aucun crochet ne doit rester ouvert lorsque la chaîne se termine. + +# --before-seed-- + +```swift +// DO NOT EDIT FROM HERE +import Foundation + +var _testCount = 0 +var _testFailedCount = 0 +func tryCatch(_ assertion: Bool) { + _testCount += 1 + if !assertion { + _testFailedCount += 1 + print("Test Case '--err-t\(_testCount)--' failed") + } +} +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```swift +func isBalanced(_ text: String) -> Bool { + +} +``` + +# --asserts-- + +Une chaîne vide est équilibrée + +```swift +tryCatch(isBalanced("") == true) +``` + +Une seule paire de crochets ronds est équilibrée + +```swift +tryCatch(isBalanced("()") == true) +``` + +Les trois types de paires imbriquées l'une dans l'autre sont équilibrées + +```swift +tryCatch(isBalanced("{[()]}") == true) +``` + +Des crochets mélangés à d'autres textes restent équilibrés + +```swift +tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +Des paires placées côte à côte sont équilibrées + +```swift +tryCatch(isBalanced("()[]{}") == true) +``` + +Une chaîne sans aucun crochet est équilibrée + +```swift +tryCatch(isBalanced("no brackets in here at all") == true) +``` + +Une paire croisée n'est pas équilibrée + +```swift +tryCatch(isBalanced("{[(])}") == false) +``` + +Un crochet ouvrant jamais fermé n'est pas équilibré + +```swift +tryCatch(isBalanced("(") == false) +``` + +Un crochet fermant avant tout crochet ouvrant n'est pas équilibré + +```swift +tryCatch(isBalanced(")(") == false) +``` + +Des paires croisées plus profondément dans la chaîne ne sont pas équilibrées + +```swift +tryCatch(isBalanced("(([]{[}]))") == false) +``` + +Un crochet fermant restant à la fin n'est pas équilibré + +```swift +tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```swift +print("Executed \(_testCount) tests, with \(_testFailedCount) failures") +``` + +# --solutions-- + +```swift +func isBalanced(_ text: String) -> Bool { + let pairs: [Character: Character] = [")": "(", "]": "[", "}": "{"] + var stack: [Character] = [] + + for char in text { + if char == "(" || char == "[" || char == "{" { + stack.append(char) + } else if let opening = pairs[char] { + if stack.popLast() != opening { + return false + } + } + } + + return stack.isEmpty +} +``` diff --git a/hi/c/challenges/data.json b/hi/c/challenges/data.json index 37fee3e64..a12ebb596 100644 --- a/hi/c/challenges/data.json +++ b/hi/c/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "अनाग्राम" + }, + "matching_brackets": { + "difficulty": 3, + "name": "कोष्ठकों का मिलान" } } diff --git a/hi/c/challenges/matching_brackets.md b/hi/c/challenges/matching_brackets.md new file mode 100644 index 000000000..558a031e5 --- /dev/null +++ b/hi/c/challenges/matching_brackets.md @@ -0,0 +1,280 @@ +--- +language: c +exerciseType: 1 +difficulty: 3 +title: कोष्ठकों का मिलान +--- + +# --description-- + +कोड, गणित या मार्कअप ले जाने वाला टेक्स्ट कोष्ठकों से भरा होता है, और हर खोलने वाले कोष्ठक को उसी किस्म का एक बंद करने वाला कोष्ठक चाहिए। एक स्ट्रिंग तब संतुलित होती है जब उसके कोष्ठक जोड़े बनाते हैं और प्याज की परतों की तरह एक-दूसरे के भीतर नेस्ट होते हैं: `{[()]}` संतुलित है, जबकि `{[(])}` संतुलित नहीं है, क्योंकि गोल जोड़ा उस वर्ग जोड़े से पहले बंद हो जाता है जिसके भीतर वह स्थित है। + +यहाँ तीन जोड़े मायने रखते हैं: गोल `()`, वर्ग `[]` और कर्ली `{}`। स्ट्रिंग का बाकी हर कैरेक्टर नज़रअंदाज़ कर दिया जाता है। एक बंद करने वाले कोष्ठक को सबसे हाल में खोले गए उस कोष्ठक को बंद करना चाहिए जो अभी भी खुला है, और जब स्ट्रिंग समाप्त हो जाए तो कोई कोष्ठक खुला नहीं रहना चाहिए। + +# --instructions-- + +एक फ़ंक्शन `is_balanced` लिखें जो एक स्ट्रिंग लेता है और तब `true` लौटाता है जब उसके सभी कोष्ठक मेल खाते हों और ठीक से नेस्ट होते हों, अन्यथा `false`। + +उदाहरण: +``` +is_balanced("") ➞ true +is_balanced("{[()]}") ➞ true +is_balanced("{what is (42)}[?]") ➞ true +is_balanced("{[(])}") ➞ false +is_balanced("(") ➞ false +is_balanced(")(") ➞ false +``` + +- खाली स्ट्रिंग संतुलित होती है। +- जो कैरेक्टर कोष्ठक नहीं हैं उन्हें नज़रअंदाज़ कर दिया जाता है। +- एक बंद करने वाला कोष्ठक सबसे हाल में खोले गए उस कोष्ठक से मेल खाना चाहिए जो अभी भी खुला है। +- जब स्ट्रिंग समाप्त हो तब कोई कोष्ठक खुला नहीं रहना चाहिए। + +# --before-seed-- + +```c +// DO NOT EDIT FROM HERE +#include +#include +#include + +#ifndef _CEXCEPTION_H +#define _CEXCEPTION_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +//This is the value to assign when there isn't an exception +#ifndef CEXCEPTION_NONE +#define CEXCEPTION_NONE (0x5A5A5A5A) +#endif + +//This is number of exception stacks to keep track of (one per task) +#ifndef CEXCEPTION_NUM_ID +#define CEXCEPTION_NUM_ID (1) //there is only the one stack by default +#endif + +//This is the method of getting the current exception stack index (0 if only one stack) +#ifndef CEXCEPTION_GET_ID +#define CEXCEPTION_GET_ID (0) //use the first index always because there is only one anyway +#endif + +//The type to use to store the exception values. +#ifndef CEXCEPTION_T +#define CEXCEPTION_T unsigned int +#endif + +//This is an optional special handler for when there is no global Catch +#ifndef CEXCEPTION_NO_CATCH_HANDLER +#define CEXCEPTION_NO_CATCH_HANDLER(id) +#endif + +//These hooks allow you to inject custom code into places, particularly useful for saving and restoring additional state +#ifndef CEXCEPTION_HOOK_START_TRY +#define CEXCEPTION_HOOK_START_TRY +#endif +#ifndef CEXCEPTION_HOOK_HAPPY_TRY +#define CEXCEPTION_HOOK_HAPPY_TRY +#endif +#ifndef CEXCEPTION_HOOK_AFTER_TRY +#define CEXCEPTION_HOOK_AFTER_TRY +#endif +#ifndef CEXCEPTION_HOOK_START_CATCH +#define CEXCEPTION_HOOK_START_CATCH +#endif + +//exception frame structures +typedef struct { + jmp_buf* pFrame; + CEXCEPTION_T volatile Exception; +} CEXCEPTION_FRAME_T; + +//actual root frame storage (only one if single-tasking) +extern volatile CEXCEPTION_FRAME_T CExceptionFrames[]; + +//Try +#define Try \ + { \ + jmp_buf *PrevFrame, NewFrame; \ + unsigned int MY_ID = CEXCEPTION_GET_ID; \ + PrevFrame = CExceptionFrames[MY_ID].pFrame; \ + CExceptionFrames[MY_ID].pFrame = (jmp_buf*)(&NewFrame); \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_START_TRY; \ + if (setjmp(NewFrame) == 0) { \ + if (1) + +//Catch +#define Catch(e) \ + else { } \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_HAPPY_TRY; \ + } \ + else \ + { \ + e = CExceptionFrames[MY_ID].Exception; \ + (void)e; \ + CEXCEPTION_HOOK_START_CATCH; \ + } \ + CExceptionFrames[MY_ID].pFrame = PrevFrame; \ + CEXCEPTION_HOOK_AFTER_TRY; \ + } \ + if (CExceptionFrames[CEXCEPTION_GET_ID].Exception != CEXCEPTION_NONE) + +#endif + +volatile CEXCEPTION_FRAME_T CExceptionFrames[CEXCEPTION_NUM_ID] = {{ 0 }}; + +void Throw(CEXCEPTION_T ExceptionID) +{ + unsigned int MY_ID = CEXCEPTION_GET_ID; + CExceptionFrames[MY_ID].Exception = ExceptionID; + if (CExceptionFrames[MY_ID].pFrame) + { + longjmp(*CExceptionFrames[MY_ID].pFrame, 1); + } + CEXCEPTION_NO_CATCH_HANDLER(ExceptionID); +} + +CEXCEPTION_T e; +int _test_failed_count = 0; +int _test_count = 0; + +void try_catch(bool assertion) { + _test_count++; + Try { + if (!assertion) { + Throw(_test_count); + } + } Catch (e) { + _test_failed_count += 1; + printf("Test Case '--err-t%i--' failed\n", e); + } +} +// DO NOT EDIT UNTIL HERE +#include +#include +``` + +# --seed-- + +```c +bool is_balanced(const char* text) { + +} +``` + +# --before-asserts-- + +```c +int main() { +``` + +# --asserts-- + +खाली स्ट्रिंग संतुलित होती है + +```c + try_catch(is_balanced("") == true); +``` + +गोल कोष्ठकों का एक जोड़ा संतुलित होता है + +```c + try_catch(is_balanced("()") == true); +``` + +एक-दूसरे के भीतर नेस्ट किए गए तीनों किस्म के जोड़े संतुलित होते हैं + +```c + try_catch(is_balanced("{[()]}") == true); +``` + +दूसरे टेक्स्ट के साथ मिले कोष्ठक भी संतुलित होते हैं + +```c + try_catch(is_balanced("{what is (42)}[?]") == true); +``` + +बगल में रखे गए जोड़े संतुलित होते हैं + +```c + try_catch(is_balanced("()[]{}") == true); +``` + +बिना किसी कोष्ठक वाली स्ट्रिंग संतुलित होती है + +```c + try_catch(is_balanced("no brackets in here at all") == true); +``` + +क्रॉस हो चुका जोड़ा संतुलित नहीं होता + +```c + try_catch(is_balanced("{[(])}") == false); +``` + +कभी बंद न होने वाला खोलने वाला कोष्ठक संतुलित नहीं होता + +```c + try_catch(is_balanced("(") == false); +``` + +किसी खोलने वाले कोष्ठक से पहले आया बंद करने वाला कोष्ठक संतुलित नहीं होता + +```c + try_catch(is_balanced(")(") == false); +``` + +स्ट्रिंग में गहराई में क्रॉस हो चुके जोड़े संतुलित नहीं होते + +```c + try_catch(is_balanced("(([]{[}]))") == false); +``` + +अंत में बचा हुआ बंद करने वाला कोष्ठक संतुलित नहीं होता + +```c + try_catch(is_balanced("())") == false); +``` + +# --after-asserts-- + +```c + printf("Executed %d tests, with %d failures", _test_count, _test_failed_count); + return 0; +} +``` + +# --solutions-- + +```c +bool is_balanced(const char* text) { + size_t length = strlen(text); + char stack[length + 1]; + size_t top = 0; + + for (size_t i = 0; i < length; i++) { + char current = text[i]; + + if (current == '(' || current == '[' || current == '{') { + stack[top++] = current; + } else if (current == ')' || current == ']' || current == '}') { + if (top == 0) { + return false; + } + + char opening = stack[--top]; + if ((current == ')' && opening != '(') || + (current == ']' && opening != '[') || + (current == '}' && opening != '{')) { + return false; + } + } + } + + return top == 0; +} +``` diff --git a/hi/dart/challenges/data.json b/hi/dart/challenges/data.json index 683234af2..8cf3f4ee2 100644 --- a/hi/dart/challenges/data.json +++ b/hi/dart/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "अनाग्राम" + }, + "matching_brackets": { + "difficulty": 3, + "name": "कोष्ठकों का मिलान" } } diff --git a/hi/dart/challenges/matching_brackets.md b/hi/dart/challenges/matching_brackets.md new file mode 100644 index 000000000..437cc8006 --- /dev/null +++ b/hi/dart/challenges/matching_brackets.md @@ -0,0 +1,167 @@ +--- +language: dart +exerciseType: 1 +difficulty: 3 +title: कोष्ठकों का मिलान +--- + +# --description-- + +कोड, गणित या मार्कअप ले जाने वाला टेक्स्ट कोष्ठकों से भरा होता है, और हर खोलने वाले कोष्ठक को उसी किस्म का एक बंद करने वाला कोष्ठक चाहिए। एक स्ट्रिंग तब संतुलित होती है जब उसके कोष्ठक जोड़े बनाते हैं और प्याज की परतों की तरह एक-दूसरे के भीतर नेस्ट होते हैं: `{[()]}` संतुलित है, जबकि `{[(])}` संतुलित नहीं है, क्योंकि गोल जोड़ा उस वर्ग जोड़े से पहले बंद हो जाता है जिसके भीतर वह स्थित है। + +यहाँ तीन जोड़े मायने रखते हैं: गोल `()`, वर्ग `[]` और कर्ली `{}`। स्ट्रिंग का बाकी हर कैरेक्टर नज़रअंदाज़ कर दिया जाता है। एक बंद करने वाले कोष्ठक को सबसे हाल में खोले गए उस कोष्ठक को बंद करना चाहिए जो अभी भी खुला है, और जब स्ट्रिंग समाप्त हो जाए तो कोई कोष्ठक खुला नहीं रहना चाहिए। + +# --instructions-- + +एक फ़ंक्शन `isBalanced` लिखें जो एक स्ट्रिंग लेता है और तब `true` लौटाता है जब उसके सभी कोष्ठक मेल खाते हों और ठीक से नेस्ट होते हों, अन्यथा `false`। + +उदाहरण: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- खाली स्ट्रिंग संतुलित होती है। +- जो कैरेक्टर कोष्ठक नहीं हैं उन्हें नज़रअंदाज़ कर दिया जाता है। +- एक बंद करने वाला कोष्ठक सबसे हाल में खोले गए उस कोष्ठक से मेल खाना चाहिए जो अभी भी खुला है। +- जब स्ट्रिंग समाप्त हो तब कोई कोष्ठक खुला नहीं रहना चाहिए। + +# --seed-- + +```dart +bool isBalanced(String text) { + +} +``` + +# --before-asserts-- + +```dart +import 'package:dart_runner/main.dart'; +import 'package:test/test.dart'; + +void main() { + group('MainTest -', () { +``` + +# --asserts-- + +खाली स्ट्रिंग संतुलित होती है + +```dart + test('test1', () { + expect(isBalanced(''), true, reason: '--err-t1--'); + }); +``` + +गोल कोष्ठकों का एक जोड़ा संतुलित होता है + +```dart + test('test2', () { + expect(isBalanced('()'), true, reason: '--err-t2--'); + }); +``` + +एक-दूसरे के भीतर नेस्ट किए गए तीनों किस्म के जोड़े संतुलित होते हैं + +```dart + test('test3', () { + expect(isBalanced('{[()]}'), true, reason: '--err-t3--'); + }); +``` + +दूसरे टेक्स्ट के साथ मिले कोष्ठक भी संतुलित होते हैं + +```dart + test('test4', () { + expect(isBalanced('{what is (42)}[?]'), true, reason: '--err-t4--'); + }); +``` + +बगल में रखे गए जोड़े संतुलित होते हैं + +```dart + test('test5', () { + expect(isBalanced('()[]{}'), true, reason: '--err-t5--'); + }); +``` + +बिना किसी कोष्ठक वाली स्ट्रिंग संतुलित होती है + +```dart + test('test6', () { + expect(isBalanced('no brackets in here at all'), true, reason: '--err-t6--'); + }); +``` + +क्रॉस हो चुका जोड़ा संतुलित नहीं होता + +```dart + test('test7', () { + expect(isBalanced('{[(])}'), false, reason: '--err-t7--'); + }); +``` + +कभी बंद न होने वाला खोलने वाला कोष्ठक संतुलित नहीं होता + +```dart + test('test8', () { + expect(isBalanced('('), false, reason: '--err-t8--'); + }); +``` + +किसी खोलने वाले कोष्ठक से पहले आया बंद करने वाला कोष्ठक संतुलित नहीं होता + +```dart + test('test9', () { + expect(isBalanced(')('), false, reason: '--err-t9--'); + }); +``` + +स्ट्रिंग में गहराई में क्रॉस हो चुके जोड़े संतुलित नहीं होते + +```dart + test('test10', () { + expect(isBalanced('(([]{[}]))'), false, reason: '--err-t10--'); + }); +``` + +अंत में बचा हुआ बंद करने वाला कोष्ठक संतुलित नहीं होता + +```dart + test('test11', () { + expect(isBalanced('())'), false, reason: '--err-t11--'); + }); +``` + +# --after-asserts-- + +```dart + }, timeout: Timeout(const Duration(seconds: 1))); +} +``` + +# --solutions-- + +```dart +bool isBalanced(String text) { + const pairs = {')': '(', ']': '[', '}': '{'}; + final stack = []; + + for (final char in text.split('')) { + if (char == '(' || char == '[' || char == '{') { + stack.add(char); + } else if (pairs.containsKey(char)) { + if (stack.isEmpty || stack.removeLast() != pairs[char]) { + return false; + } + } + } + + return stack.isEmpty; +} +``` diff --git a/hi/javascript/challenges/data.json b/hi/javascript/challenges/data.json index 4672e9a18..0737c2a5b 100644 --- a/hi/javascript/challenges/data.json +++ b/hi/javascript/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "अनाग्राम" + }, + "matching_brackets": { + "difficulty": 3, + "name": "कोष्ठकों का मिलान" } } diff --git a/hi/javascript/challenges/matching_brackets.md b/hi/javascript/challenges/matching_brackets.md new file mode 100644 index 000000000..339a0ba83 --- /dev/null +++ b/hi/javascript/challenges/matching_brackets.md @@ -0,0 +1,154 @@ +--- +language: javascript +exerciseType: 1 +difficulty: 3 +title: कोष्ठकों का मिलान +--- + +# --description-- + +कोड, गणित या मार्कअप ले जाने वाला टेक्स्ट कोष्ठकों से भरा होता है, और हर खोलने वाले कोष्ठक को उसी किस्म का एक बंद करने वाला कोष्ठक चाहिए। एक स्ट्रिंग तब संतुलित होती है जब उसके कोष्ठक जोड़े बनाते हैं और प्याज की परतों की तरह एक-दूसरे के भीतर नेस्ट होते हैं: `{[()]}` संतुलित है, जबकि `{[(])}` संतुलित नहीं है, क्योंकि गोल जोड़ा उस वर्ग जोड़े से पहले बंद हो जाता है जिसके भीतर वह स्थित है। + +यहाँ तीन जोड़े मायने रखते हैं: गोल `()`, वर्ग `[]` और कर्ली `{}`। स्ट्रिंग का बाकी हर कैरेक्टर नज़रअंदाज़ कर दिया जाता है। एक बंद करने वाले कोष्ठक को सबसे हाल में खोले गए उस कोष्ठक को बंद करना चाहिए जो अभी भी खुला है, और जब स्ट्रिंग समाप्त हो जाए तो कोई कोष्ठक खुला नहीं रहना चाहिए। + +# --instructions-- + +एक फ़ंक्शन `isBalanced` लिखें जो एक स्ट्रिंग लेता है और तब `true` लौटाता है जब उसके सभी कोष्ठक मेल खाते हों और ठीक से नेस्ट होते हों, अन्यथा `false`। + +उदाहरण: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- खाली स्ट्रिंग संतुलित होती है। +- जो कैरेक्टर कोष्ठक नहीं हैं उन्हें नज़रअंदाज़ कर दिया जाता है। +- एक बंद करने वाला कोष्ठक सबसे हाल में खोले गए उस कोष्ठक से मेल खाना चाहिए जो अभी भी खुला है। +- जब स्ट्रिंग समाप्त हो तब कोई कोष्ठक खुला नहीं रहना चाहिए। + +# --before-seed-- + +```javascript +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +var assert = require('assert') +const tryCatch = (...args) => { + _testCount++ + try { assert(...args) } + catch (e) { + _testFailedCount++ + console.log(`Test Case '--err-t${_testCount}--' failed`); + } +}; +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```javascript +function isBalanced(text) { + +} +``` + +# --asserts-- + +खाली स्ट्रिंग संतुलित होती है + +```javascript +tryCatch(isBalanced("") === true); +``` + +गोल कोष्ठकों का एक जोड़ा संतुलित होता है + +```javascript +tryCatch(isBalanced("()") === true); +``` + +एक-दूसरे के भीतर नेस्ट किए गए तीनों किस्म के जोड़े संतुलित होते हैं + +```javascript +tryCatch(isBalanced("{[()]}") === true); +``` + +दूसरे टेक्स्ट के साथ मिले कोष्ठक भी संतुलित होते हैं + +```javascript +tryCatch(isBalanced("{what is (42)}[?]") === true); +``` + +बगल में रखे गए जोड़े संतुलित होते हैं + +```javascript +tryCatch(isBalanced("()[]{}") === true); +``` + +बिना किसी कोष्ठक वाली स्ट्रिंग संतुलित होती है + +```javascript +tryCatch(isBalanced("no brackets in here at all") === true); +``` + +क्रॉस हो चुका जोड़ा संतुलित नहीं होता + +```javascript +tryCatch(isBalanced("{[(])}") === false); +``` + +कभी बंद न होने वाला खोलने वाला कोष्ठक संतुलित नहीं होता + +```javascript +tryCatch(isBalanced("(") === false); +``` + +किसी खोलने वाले कोष्ठक से पहले आया बंद करने वाला कोष्ठक संतुलित नहीं होता + +```javascript +tryCatch(isBalanced(")(") === false); +``` + +स्ट्रिंग में गहराई में क्रॉस हो चुके जोड़े संतुलित नहीं होते + +```javascript +tryCatch(isBalanced("(([]{[}]))") === false); +``` + +अंत में बचा हुआ बंद करने वाला कोष्ठक संतुलित नहीं होता + +```javascript +tryCatch(isBalanced("())") === false); +``` + +# --after-asserts-- + +```javascript +// DO NOT EDIT FROM HERE +console.log(`Executed ${_testCount} tests, with ${_testFailedCount} failures`); +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```javascript +function isBalanced(text) { + const pairs = { ")": "(", "]": "[", "}": "{" }; + const stack = []; + + for (const char of text) { + if (char === "(" || char === "[" || char === "{") { + stack.push(char); + } else if (char in pairs) { + if (stack.pop() !== pairs[char]) { + return false; + } + } + } + + return stack.length === 0; +} +``` diff --git a/hi/kotlin/challenges/data.json b/hi/kotlin/challenges/data.json index ab018af3a..68fd57445 100644 --- a/hi/kotlin/challenges/data.json +++ b/hi/kotlin/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "अनाग्राम" + }, + "matching_brackets": { + "difficulty": 3, + "name": "कोष्ठकों का मिलान" } } diff --git a/hi/kotlin/challenges/matching_brackets.md b/hi/kotlin/challenges/matching_brackets.md new file mode 100644 index 000000000..ee7034bc0 --- /dev/null +++ b/hi/kotlin/challenges/matching_brackets.md @@ -0,0 +1,157 @@ +--- +language: kotlin +exerciseType: 1 +difficulty: 3 +title: कोष्ठकों का मिलान +--- + +# --description-- + +कोड, गणित या मार्कअप ले जाने वाला टेक्स्ट कोष्ठकों से भरा होता है, और हर खोलने वाले कोष्ठक को उसी किस्म का एक बंद करने वाला कोष्ठक चाहिए। एक स्ट्रिंग तब संतुलित होती है जब उसके कोष्ठक जोड़े बनाते हैं और प्याज की परतों की तरह एक-दूसरे के भीतर नेस्ट होते हैं: `{[()]}` संतुलित है, जबकि `{[(])}` संतुलित नहीं है, क्योंकि गोल जोड़ा उस वर्ग जोड़े से पहले बंद हो जाता है जिसके भीतर वह स्थित है। + +यहाँ तीन जोड़े मायने रखते हैं: गोल `()`, वर्ग `[]` और कर्ली `{}`। स्ट्रिंग का बाकी हर कैरेक्टर नज़रअंदाज़ कर दिया जाता है। एक बंद करने वाले कोष्ठक को सबसे हाल में खोले गए उस कोष्ठक को बंद करना चाहिए जो अभी भी खुला है, और जब स्ट्रिंग समाप्त हो जाए तो कोई कोष्ठक खुला नहीं रहना चाहिए। + +# --instructions-- + +एक फ़ंक्शन `isBalanced` लिखें जो एक स्ट्रिंग लेता है और तब `true` लौटाता है जब उसके सभी कोष्ठक मेल खाते हों और ठीक से नेस्ट होते हों, अन्यथा `false`। + +उदाहरण: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- खाली स्ट्रिंग संतुलित होती है। +- जो कैरेक्टर कोष्ठक नहीं हैं उन्हें नज़रअंदाज़ कर दिया जाता है। +- एक बंद करने वाला कोष्ठक सबसे हाल में खोले गए उस कोष्ठक से मेल खाना चाहिए जो अभी भी खुला है। +- जब स्ट्रिंग समाप्त हो तब कोई कोष्ठक खुला नहीं रहना चाहिए। + +# --seed-- + +```kotlin +fun isBalanced(text: String): Boolean { + +} +``` + +# --before-seed-- + +```kotlin +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +fun tryCatch(assertion: Boolean) { + _testCount++ + try { + if (!assertion) throw Exception() + } + catch (e: Throwable) { + _testFailedCount++ + println("Test Case '--err-t$_testCount--' failed"); + } +}; +// DO NOT EDIT UNTIL HERE +fun main() { +``` + +# --asserts-- + +खाली स्ट्रिंग संतुलित होती है + +```kotlin + tryCatch(isBalanced("") == true) +``` + +गोल कोष्ठकों का एक जोड़ा संतुलित होता है + +```kotlin + tryCatch(isBalanced("()") == true) +``` + +एक-दूसरे के भीतर नेस्ट किए गए तीनों किस्म के जोड़े संतुलित होते हैं + +```kotlin + tryCatch(isBalanced("{[()]}") == true) +``` + +दूसरे टेक्स्ट के साथ मिले कोष्ठक भी संतुलित होते हैं + +```kotlin + tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +बगल में रखे गए जोड़े संतुलित होते हैं + +```kotlin + tryCatch(isBalanced("()[]{}") == true) +``` + +बिना किसी कोष्ठक वाली स्ट्रिंग संतुलित होती है + +```kotlin + tryCatch(isBalanced("no brackets in here at all") == true) +``` + +क्रॉस हो चुका जोड़ा संतुलित नहीं होता + +```kotlin + tryCatch(isBalanced("{[(])}") == false) +``` + +कभी बंद न होने वाला खोलने वाला कोष्ठक संतुलित नहीं होता + +```kotlin + tryCatch(isBalanced("(") == false) +``` + +किसी खोलने वाले कोष्ठक से पहले आया बंद करने वाला कोष्ठक संतुलित नहीं होता + +```kotlin + tryCatch(isBalanced(")(") == false) +``` + +स्ट्रिंग में गहराई में क्रॉस हो चुके जोड़े संतुलित नहीं होते + +```kotlin + tryCatch(isBalanced("(([]{[}]))") == false) +``` + +अंत में बचा हुआ बंद करने वाला कोष्ठक संतुलित नहीं होता + +```kotlin + tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```kotlin +// DO NOT EDIT FROM HERE + println("Executed $_testCount tests, with $_testFailedCount failures"); +} +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```kotlin +fun isBalanced(text: String): Boolean { + val pairs = mapOf(')' to '(', ']' to '[', '}' to '{') + val stack = ArrayDeque() + + for (char in text) { + if (char == '(' || char == '[' || char == '{') { + stack.addLast(char) + } else if (pairs.containsKey(char)) { + if (stack.isEmpty() || stack.removeLast() != pairs[char]) { + return false + } + } + } + + return stack.isEmpty() +} +``` diff --git a/hi/python/challenges/data.json b/hi/python/challenges/data.json index afcacf985..f9a0957ec 100644 --- a/hi/python/challenges/data.json +++ b/hi/python/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "अनाग्राम" + }, + "matching_brackets": { + "difficulty": 3, + "name": "कोष्ठकों का मिलान" } } diff --git a/hi/python/challenges/matching_brackets.md b/hi/python/challenges/matching_brackets.md new file mode 100644 index 000000000..fb2f0dccd --- /dev/null +++ b/hi/python/challenges/matching_brackets.md @@ -0,0 +1,149 @@ +--- +language: python +exerciseType: 1 +difficulty: 3 +title: कोष्ठकों का मिलान +--- + +# --description-- + +कोड, गणित या मार्कअप ले जाने वाला टेक्स्ट कोष्ठकों से भरा होता है, और हर खोलने वाले कोष्ठक को उसी किस्म का एक बंद करने वाला कोष्ठक चाहिए। एक स्ट्रिंग तब संतुलित होती है जब उसके कोष्ठक जोड़े बनाते हैं और प्याज की परतों की तरह एक-दूसरे के भीतर नेस्ट होते हैं: `{[()]}` संतुलित है, जबकि `{[(])}` संतुलित नहीं है, क्योंकि गोल जोड़ा उस वर्ग जोड़े से पहले बंद हो जाता है जिसके भीतर वह स्थित है। + +यहाँ तीन जोड़े मायने रखते हैं: गोल `()`, वर्ग `[]` और कर्ली `{}`। स्ट्रिंग का बाकी हर कैरेक्टर नज़रअंदाज़ कर दिया जाता है। एक बंद करने वाले कोष्ठक को सबसे हाल में खोले गए उस कोष्ठक को बंद करना चाहिए जो अभी भी खुला है, और जब स्ट्रिंग समाप्त हो जाए तो कोई कोष्ठक खुला नहीं रहना चाहिए। + +# --instructions-- + +एक फ़ंक्शन `is_balanced` लिखें जो एक स्ट्रिंग लेता है और तब `True` लौटाता है जब उसके सभी कोष्ठक मेल खाते हों और ठीक से नेस्ट होते हों, अन्यथा `False`। + +उदाहरण: +``` +is_balanced("") ➞ True +is_balanced("{[()]}") ➞ True +is_balanced("{what is (42)}[?]") ➞ True +is_balanced("{[(])}") ➞ False +is_balanced("(") ➞ False +is_balanced(")(") ➞ False +``` + +- खाली स्ट्रिंग संतुलित होती है। +- जो कैरेक्टर कोष्ठक नहीं हैं उन्हें नज़रअंदाज़ कर दिया जाता है। +- एक बंद करने वाला कोष्ठक सबसे हाल में खोले गए उस कोष्ठक से मेल खाना चाहिए जो अभी भी खुला है। +- जब स्ट्रिंग समाप्त हो तब कोई कोष्ठक खुला नहीं रहना चाहिए। + +# --seed-- + +```python +def is_balanced(text): + pass +``` + +# --before-asserts-- + +```python +import unittest + +class CodigoTests(unittest.TestCase): +``` + +# --asserts-- + +खाली स्ट्रिंग संतुलित होती है + +```python + def test1(self): + self.assertEqual(is_balanced(""), True, "--err-t1--") +``` + +गोल कोष्ठकों का एक जोड़ा संतुलित होता है + +```python + def test2(self): + self.assertEqual(is_balanced("()"), True, "--err-t2--") +``` + +एक-दूसरे के भीतर नेस्ट किए गए तीनों किस्म के जोड़े संतुलित होते हैं + +```python + def test3(self): + self.assertEqual(is_balanced("{[()]}"), True, "--err-t3--") +``` + +दूसरे टेक्स्ट के साथ मिले कोष्ठक भी संतुलित होते हैं + +```python + def test4(self): + self.assertEqual(is_balanced("{what is (42)}[?]"), True, "--err-t4--") +``` + +बगल में रखे गए जोड़े संतुलित होते हैं + +```python + def test5(self): + self.assertEqual(is_balanced("()[]{}"), True, "--err-t5--") +``` + +बिना किसी कोष्ठक वाली स्ट्रिंग संतुलित होती है + +```python + def test6(self): + self.assertEqual(is_balanced("no brackets in here at all"), True, "--err-t6--") +``` + +क्रॉस हो चुका जोड़ा संतुलित नहीं होता + +```python + def test7(self): + self.assertEqual(is_balanced("{[(])}"), False, "--err-t7--") +``` + +कभी बंद न होने वाला खोलने वाला कोष्ठक संतुलित नहीं होता + +```python + def test8(self): + self.assertEqual(is_balanced("("), False, "--err-t8--") +``` + +किसी खोलने वाले कोष्ठक से पहले आया बंद करने वाला कोष्ठक संतुलित नहीं होता + +```python + def test9(self): + self.assertEqual(is_balanced(")("), False, "--err-t9--") +``` + +स्ट्रिंग में गहराई में क्रॉस हो चुके जोड़े संतुलित नहीं होते + +```python + def test10(self): + self.assertEqual(is_balanced("(([]{[}]))"), False, "--err-t10--") +``` + +अंत में बचा हुआ बंद करने वाला कोष्ठक संतुलित नहीं होता + +```python + def test11(self): + self.assertEqual(is_balanced("())"), False, "--err-t11--") +``` + +# --after-asserts-- + +```python +if __name__ == "__main__": + unittest.main() +``` + +# --solutions-- + +```python +def is_balanced(text): + pairs = {")": "(", "]": "[", "}": "{"} + stack = [] + + for char in text: + if char in "([{": + stack.append(char) + elif char in pairs: + if not stack or stack.pop() != pairs[char]: + return False + + return not stack +``` diff --git a/hi/swift/challenges/data.json b/hi/swift/challenges/data.json index 48080b587..a9443ed7d 100644 --- a/hi/swift/challenges/data.json +++ b/hi/swift/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "अनाग्राम" + }, + "matching_brackets": { + "difficulty": 3, + "name": "कोष्ठकों का मिलान" } } diff --git a/hi/swift/challenges/matching_brackets.md b/hi/swift/challenges/matching_brackets.md new file mode 100644 index 000000000..3ca343875 --- /dev/null +++ b/hi/swift/challenges/matching_brackets.md @@ -0,0 +1,152 @@ +--- +language: swift +exerciseType: 1 +difficulty: 3 +title: कोष्ठकों का मिलान +--- + +# --description-- + +कोड, गणित या मार्कअप ले जाने वाला टेक्स्ट कोष्ठकों से भरा होता है, और हर खोलने वाले कोष्ठक को उसी किस्म का एक बंद करने वाला कोष्ठक चाहिए। एक स्ट्रिंग तब संतुलित होती है जब उसके कोष्ठक जोड़े बनाते हैं और प्याज की परतों की तरह एक-दूसरे के भीतर नेस्ट होते हैं: `{[()]}` संतुलित है, जबकि `{[(])}` संतुलित नहीं है, क्योंकि गोल जोड़ा उस वर्ग जोड़े से पहले बंद हो जाता है जिसके भीतर वह स्थित है। + +यहाँ तीन जोड़े मायने रखते हैं: गोल `()`, वर्ग `[]` और कर्ली `{}`। स्ट्रिंग का बाकी हर कैरेक्टर नज़रअंदाज़ कर दिया जाता है। एक बंद करने वाले कोष्ठक को सबसे हाल में खोले गए उस कोष्ठक को बंद करना चाहिए जो अभी भी खुला है, और जब स्ट्रिंग समाप्त हो जाए तो कोई कोष्ठक खुला नहीं रहना चाहिए। + +# --instructions-- + +एक फ़ंक्शन `isBalanced` लिखें जो एक स्ट्रिंग लेता है और तब `true` लौटाता है जब उसके सभी कोष्ठक मेल खाते हों और ठीक से नेस्ट होते हों, अन्यथा `false`। + +उदाहरण: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- खाली स्ट्रिंग संतुलित होती है। +- जो कैरेक्टर कोष्ठक नहीं हैं उन्हें नज़रअंदाज़ कर दिया जाता है। +- एक बंद करने वाला कोष्ठक सबसे हाल में खोले गए उस कोष्ठक से मेल खाना चाहिए जो अभी भी खुला है। +- जब स्ट्रिंग समाप्त हो तब कोई कोष्ठक खुला नहीं रहना चाहिए। + +# --before-seed-- + +```swift +// DO NOT EDIT FROM HERE +import Foundation + +var _testCount = 0 +var _testFailedCount = 0 +func tryCatch(_ assertion: Bool) { + _testCount += 1 + if !assertion { + _testFailedCount += 1 + print("Test Case '--err-t\(_testCount)--' failed") + } +} +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```swift +func isBalanced(_ text: String) -> Bool { + +} +``` + +# --asserts-- + +खाली स्ट्रिंग संतुलित होती है + +```swift +tryCatch(isBalanced("") == true) +``` + +गोल कोष्ठकों का एक जोड़ा संतुलित होता है + +```swift +tryCatch(isBalanced("()") == true) +``` + +एक-दूसरे के भीतर नेस्ट किए गए तीनों किस्म के जोड़े संतुलित होते हैं + +```swift +tryCatch(isBalanced("{[()]}") == true) +``` + +दूसरे टेक्स्ट के साथ मिले कोष्ठक भी संतुलित होते हैं + +```swift +tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +बगल में रखे गए जोड़े संतुलित होते हैं + +```swift +tryCatch(isBalanced("()[]{}") == true) +``` + +बिना किसी कोष्ठक वाली स्ट्रिंग संतुलित होती है + +```swift +tryCatch(isBalanced("no brackets in here at all") == true) +``` + +क्रॉस हो चुका जोड़ा संतुलित नहीं होता + +```swift +tryCatch(isBalanced("{[(])}") == false) +``` + +कभी बंद न होने वाला खोलने वाला कोष्ठक संतुलित नहीं होता + +```swift +tryCatch(isBalanced("(") == false) +``` + +किसी खोलने वाले कोष्ठक से पहले आया बंद करने वाला कोष्ठक संतुलित नहीं होता + +```swift +tryCatch(isBalanced(")(") == false) +``` + +स्ट्रिंग में गहराई में क्रॉस हो चुके जोड़े संतुलित नहीं होते + +```swift +tryCatch(isBalanced("(([]{[}]))") == false) +``` + +अंत में बचा हुआ बंद करने वाला कोष्ठक संतुलित नहीं होता + +```swift +tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```swift +print("Executed \(_testCount) tests, with \(_testFailedCount) failures") +``` + +# --solutions-- + +```swift +func isBalanced(_ text: String) -> Bool { + let pairs: [Character: Character] = [")": "(", "]": "[", "}": "{"] + var stack: [Character] = [] + + for char in text { + if char == "(" || char == "[" || char == "{" { + stack.append(char) + } else if let opening = pairs[char] { + if stack.popLast() != opening { + return false + } + } + } + + return stack.isEmpty +} +``` diff --git a/it/c/challenges/data.json b/it/c/challenges/data.json index 807dd8f18..4c6fc3aed 100644 --- a/it/c/challenges/data.json +++ b/it/c/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramma" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Parentesi bilanciate" } } diff --git a/it/c/challenges/matching_brackets.md b/it/c/challenges/matching_brackets.md new file mode 100644 index 000000000..14279c5b1 --- /dev/null +++ b/it/c/challenges/matching_brackets.md @@ -0,0 +1,280 @@ +--- +language: c +exerciseType: 1 +difficulty: 3 +title: Parentesi bilanciate +--- + +# --description-- + +Il testo che contiene codice, formule matematiche o markup è pieno di parentesi, e ogni parentesi aperta ha bisogno di una chiusa dello stesso tipo. Una stringa è bilanciata quando le sue parentesi si accoppiano e si annidano come gli strati di una cipolla: `{[()]}` è bilanciata, mentre `{[(])}` non lo è, perché la coppia tonda viene chiusa prima della coppia quadrata al cui interno si trova. + +Qui contano tre coppie: le tonde `()`, le quadre `[]` e le graffe `{}`. Ogni altro carattere della stringa viene ignorato. Una parentesi chiusa deve chiudere la parentesi aperta più di recente che risulta ancora aperta, e quando la stringa termina nessuna parentesi può rimanere aperta. + +# --instructions-- + +Scrivi una funzione `is_balanced` che prende una stringa e restituisce `true` quando tutte le parentesi in essa contenute sono accoppiate e correttamente annidate, e `false` altrimenti. + +Esempi: +``` +is_balanced("") ➞ true +is_balanced("{[()]}") ➞ true +is_balanced("{what is (42)}[?]") ➞ true +is_balanced("{[(])}") ➞ false +is_balanced("(") ➞ false +is_balanced(")(") ➞ false +``` + +- Una stringa vuota è bilanciata. +- I caratteri che non sono parentesi vengono ignorati. +- Una parentesi chiusa deve corrispondere alla parentesi aperta più di recente che risulta ancora aperta. +- Nessuna parentesi può rimanere aperta quando la stringa termina. + +# --before-seed-- + +```c +// DO NOT EDIT FROM HERE +#include +#include +#include + +#ifndef _CEXCEPTION_H +#define _CEXCEPTION_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +//This is the value to assign when there isn't an exception +#ifndef CEXCEPTION_NONE +#define CEXCEPTION_NONE (0x5A5A5A5A) +#endif + +//This is number of exception stacks to keep track of (one per task) +#ifndef CEXCEPTION_NUM_ID +#define CEXCEPTION_NUM_ID (1) //there is only the one stack by default +#endif + +//This is the method of getting the current exception stack index (0 if only one stack) +#ifndef CEXCEPTION_GET_ID +#define CEXCEPTION_GET_ID (0) //use the first index always because there is only one anyway +#endif + +//The type to use to store the exception values. +#ifndef CEXCEPTION_T +#define CEXCEPTION_T unsigned int +#endif + +//This is an optional special handler for when there is no global Catch +#ifndef CEXCEPTION_NO_CATCH_HANDLER +#define CEXCEPTION_NO_CATCH_HANDLER(id) +#endif + +//These hooks allow you to inject custom code into places, particularly useful for saving and restoring additional state +#ifndef CEXCEPTION_HOOK_START_TRY +#define CEXCEPTION_HOOK_START_TRY +#endif +#ifndef CEXCEPTION_HOOK_HAPPY_TRY +#define CEXCEPTION_HOOK_HAPPY_TRY +#endif +#ifndef CEXCEPTION_HOOK_AFTER_TRY +#define CEXCEPTION_HOOK_AFTER_TRY +#endif +#ifndef CEXCEPTION_HOOK_START_CATCH +#define CEXCEPTION_HOOK_START_CATCH +#endif + +//exception frame structures +typedef struct { + jmp_buf* pFrame; + CEXCEPTION_T volatile Exception; +} CEXCEPTION_FRAME_T; + +//actual root frame storage (only one if single-tasking) +extern volatile CEXCEPTION_FRAME_T CExceptionFrames[]; + +//Try +#define Try \ + { \ + jmp_buf *PrevFrame, NewFrame; \ + unsigned int MY_ID = CEXCEPTION_GET_ID; \ + PrevFrame = CExceptionFrames[MY_ID].pFrame; \ + CExceptionFrames[MY_ID].pFrame = (jmp_buf*)(&NewFrame); \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_START_TRY; \ + if (setjmp(NewFrame) == 0) { \ + if (1) + +//Catch +#define Catch(e) \ + else { } \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_HAPPY_TRY; \ + } \ + else \ + { \ + e = CExceptionFrames[MY_ID].Exception; \ + (void)e; \ + CEXCEPTION_HOOK_START_CATCH; \ + } \ + CExceptionFrames[MY_ID].pFrame = PrevFrame; \ + CEXCEPTION_HOOK_AFTER_TRY; \ + } \ + if (CExceptionFrames[CEXCEPTION_GET_ID].Exception != CEXCEPTION_NONE) + +#endif + +volatile CEXCEPTION_FRAME_T CExceptionFrames[CEXCEPTION_NUM_ID] = {{ 0 }}; + +void Throw(CEXCEPTION_T ExceptionID) +{ + unsigned int MY_ID = CEXCEPTION_GET_ID; + CExceptionFrames[MY_ID].Exception = ExceptionID; + if (CExceptionFrames[MY_ID].pFrame) + { + longjmp(*CExceptionFrames[MY_ID].pFrame, 1); + } + CEXCEPTION_NO_CATCH_HANDLER(ExceptionID); +} + +CEXCEPTION_T e; +int _test_failed_count = 0; +int _test_count = 0; + +void try_catch(bool assertion) { + _test_count++; + Try { + if (!assertion) { + Throw(_test_count); + } + } Catch (e) { + _test_failed_count += 1; + printf("Test Case '--err-t%i--' failed\n", e); + } +} +// DO NOT EDIT UNTIL HERE +#include +#include +``` + +# --seed-- + +```c +bool is_balanced(const char* text) { + +} +``` + +# --before-asserts-- + +```c +int main() { +``` + +# --asserts-- + +Una stringa vuota è bilanciata + +```c + try_catch(is_balanced("") == true); +``` + +Una singola coppia di parentesi tonde è bilanciata + +```c + try_catch(is_balanced("()") == true); +``` + +I tre tipi di coppia annidati l'uno dentro l'altro sono bilanciati + +```c + try_catch(is_balanced("{[()]}") == true); +``` + +Parentesi mescolate ad altro testo restano comunque bilanciate + +```c + try_catch(is_balanced("{what is (42)}[?]") == true); +``` + +Coppie poste una accanto all'altra sono bilanciate + +```c + try_catch(is_balanced("()[]{}") == true); +``` + +Una stringa senza alcuna parentesi è bilanciata + +```c + try_catch(is_balanced("no brackets in here at all") == true); +``` + +Una coppia incrociata non è bilanciata + +```c + try_catch(is_balanced("{[(])}") == false); +``` + +Una parentesi aperta che non viene mai chiusa non è bilanciata + +```c + try_catch(is_balanced("(") == false); +``` + +Una parentesi chiusa prima di qualsiasi parentesi aperta non è bilanciata + +```c + try_catch(is_balanced(")(") == false); +``` + +Coppie incrociate più in profondità nella stringa non sono bilanciate + +```c + try_catch(is_balanced("(([]{[}]))") == false); +``` + +Una parentesi chiusa lasciata alla fine non è bilanciata + +```c + try_catch(is_balanced("())") == false); +``` + +# --after-asserts-- + +```c + printf("Executed %d tests, with %d failures", _test_count, _test_failed_count); + return 0; +} +``` + +# --solutions-- + +```c +bool is_balanced(const char* text) { + size_t length = strlen(text); + char stack[length + 1]; + size_t top = 0; + + for (size_t i = 0; i < length; i++) { + char current = text[i]; + + if (current == '(' || current == '[' || current == '{') { + stack[top++] = current; + } else if (current == ')' || current == ']' || current == '}') { + if (top == 0) { + return false; + } + + char opening = stack[--top]; + if ((current == ')' && opening != '(') || + (current == ']' && opening != '[') || + (current == '}' && opening != '{')) { + return false; + } + } + } + + return top == 0; +} +``` diff --git a/it/dart/challenges/data.json b/it/dart/challenges/data.json index 925e8b68a..04b372367 100644 --- a/it/dart/challenges/data.json +++ b/it/dart/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramma" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Parentesi bilanciate" } } diff --git a/it/dart/challenges/matching_brackets.md b/it/dart/challenges/matching_brackets.md new file mode 100644 index 000000000..b66fff6f0 --- /dev/null +++ b/it/dart/challenges/matching_brackets.md @@ -0,0 +1,167 @@ +--- +language: dart +exerciseType: 1 +difficulty: 3 +title: Parentesi bilanciate +--- + +# --description-- + +Il testo che contiene codice, formule matematiche o markup è pieno di parentesi, e ogni parentesi aperta ha bisogno di una chiusa dello stesso tipo. Una stringa è bilanciata quando le sue parentesi si accoppiano e si annidano come gli strati di una cipolla: `{[()]}` è bilanciata, mentre `{[(])}` non lo è, perché la coppia tonda viene chiusa prima della coppia quadrata al cui interno si trova. + +Qui contano tre coppie: le tonde `()`, le quadre `[]` e le graffe `{}`. Ogni altro carattere della stringa viene ignorato. Una parentesi chiusa deve chiudere la parentesi aperta più di recente che risulta ancora aperta, e quando la stringa termina nessuna parentesi può rimanere aperta. + +# --instructions-- + +Scrivi una funzione `isBalanced` che prende una stringa e restituisce `true` quando tutte le parentesi in essa contenute sono accoppiate e correttamente annidate, e `false` altrimenti. + +Esempi: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Una stringa vuota è bilanciata. +- I caratteri che non sono parentesi vengono ignorati. +- Una parentesi chiusa deve corrispondere alla parentesi aperta più di recente che risulta ancora aperta. +- Nessuna parentesi può rimanere aperta quando la stringa termina. + +# --seed-- + +```dart +bool isBalanced(String text) { + +} +``` + +# --before-asserts-- + +```dart +import 'package:dart_runner/main.dart'; +import 'package:test/test.dart'; + +void main() { + group('MainTest -', () { +``` + +# --asserts-- + +Una stringa vuota è bilanciata + +```dart + test('test1', () { + expect(isBalanced(''), true, reason: '--err-t1--'); + }); +``` + +Una singola coppia di parentesi tonde è bilanciata + +```dart + test('test2', () { + expect(isBalanced('()'), true, reason: '--err-t2--'); + }); +``` + +I tre tipi di coppia annidati l'uno dentro l'altro sono bilanciati + +```dart + test('test3', () { + expect(isBalanced('{[()]}'), true, reason: '--err-t3--'); + }); +``` + +Parentesi mescolate ad altro testo restano comunque bilanciate + +```dart + test('test4', () { + expect(isBalanced('{what is (42)}[?]'), true, reason: '--err-t4--'); + }); +``` + +Coppie poste una accanto all'altra sono bilanciate + +```dart + test('test5', () { + expect(isBalanced('()[]{}'), true, reason: '--err-t5--'); + }); +``` + +Una stringa senza alcuna parentesi è bilanciata + +```dart + test('test6', () { + expect(isBalanced('no brackets in here at all'), true, reason: '--err-t6--'); + }); +``` + +Una coppia incrociata non è bilanciata + +```dart + test('test7', () { + expect(isBalanced('{[(])}'), false, reason: '--err-t7--'); + }); +``` + +Una parentesi aperta che non viene mai chiusa non è bilanciata + +```dart + test('test8', () { + expect(isBalanced('('), false, reason: '--err-t8--'); + }); +``` + +Una parentesi chiusa prima di qualsiasi parentesi aperta non è bilanciata + +```dart + test('test9', () { + expect(isBalanced(')('), false, reason: '--err-t9--'); + }); +``` + +Coppie incrociate più in profondità nella stringa non sono bilanciate + +```dart + test('test10', () { + expect(isBalanced('(([]{[}]))'), false, reason: '--err-t10--'); + }); +``` + +Una parentesi chiusa lasciata alla fine non è bilanciata + +```dart + test('test11', () { + expect(isBalanced('())'), false, reason: '--err-t11--'); + }); +``` + +# --after-asserts-- + +```dart + }, timeout: Timeout(const Duration(seconds: 1))); +} +``` + +# --solutions-- + +```dart +bool isBalanced(String text) { + const pairs = {')': '(', ']': '[', '}': '{'}; + final stack = []; + + for (final char in text.split('')) { + if (char == '(' || char == '[' || char == '{') { + stack.add(char); + } else if (pairs.containsKey(char)) { + if (stack.isEmpty || stack.removeLast() != pairs[char]) { + return false; + } + } + } + + return stack.isEmpty; +} +``` diff --git a/it/javascript/challenges/data.json b/it/javascript/challenges/data.json index 67f17964d..dfd72e69f 100644 --- a/it/javascript/challenges/data.json +++ b/it/javascript/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramma" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Parentesi bilanciate" } } diff --git a/it/javascript/challenges/matching_brackets.md b/it/javascript/challenges/matching_brackets.md new file mode 100644 index 000000000..1f3afe237 --- /dev/null +++ b/it/javascript/challenges/matching_brackets.md @@ -0,0 +1,154 @@ +--- +language: javascript +exerciseType: 1 +difficulty: 3 +title: Parentesi bilanciate +--- + +# --description-- + +Il testo che contiene codice, formule matematiche o markup è pieno di parentesi, e ogni parentesi aperta ha bisogno di una chiusa dello stesso tipo. Una stringa è bilanciata quando le sue parentesi si accoppiano e si annidano come gli strati di una cipolla: `{[()]}` è bilanciata, mentre `{[(])}` non lo è, perché la coppia tonda viene chiusa prima della coppia quadrata al cui interno si trova. + +Qui contano tre coppie: le tonde `()`, le quadre `[]` e le graffe `{}`. Ogni altro carattere della stringa viene ignorato. Una parentesi chiusa deve chiudere la parentesi aperta più di recente che risulta ancora aperta, e quando la stringa termina nessuna parentesi può rimanere aperta. + +# --instructions-- + +Scrivi una funzione `isBalanced` che prende una stringa e restituisce `true` quando tutte le parentesi in essa contenute sono accoppiate e correttamente annidate, e `false` altrimenti. + +Esempi: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Una stringa vuota è bilanciata. +- I caratteri che non sono parentesi vengono ignorati. +- Una parentesi chiusa deve corrispondere alla parentesi aperta più di recente che risulta ancora aperta. +- Nessuna parentesi può rimanere aperta quando la stringa termina. + +# --before-seed-- + +```javascript +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +var assert = require('assert') +const tryCatch = (...args) => { + _testCount++ + try { assert(...args) } + catch (e) { + _testFailedCount++ + console.log(`Test Case '--err-t${_testCount}--' failed`); + } +}; +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```javascript +function isBalanced(text) { + +} +``` + +# --asserts-- + +Una stringa vuota è bilanciata + +```javascript +tryCatch(isBalanced("") === true); +``` + +Una singola coppia di parentesi tonde è bilanciata + +```javascript +tryCatch(isBalanced("()") === true); +``` + +I tre tipi di coppia annidati l'uno dentro l'altro sono bilanciati + +```javascript +tryCatch(isBalanced("{[()]}") === true); +``` + +Parentesi mescolate ad altro testo restano comunque bilanciate + +```javascript +tryCatch(isBalanced("{what is (42)}[?]") === true); +``` + +Coppie poste una accanto all'altra sono bilanciate + +```javascript +tryCatch(isBalanced("()[]{}") === true); +``` + +Una stringa senza alcuna parentesi è bilanciata + +```javascript +tryCatch(isBalanced("no brackets in here at all") === true); +``` + +Una coppia incrociata non è bilanciata + +```javascript +tryCatch(isBalanced("{[(])}") === false); +``` + +Una parentesi aperta che non viene mai chiusa non è bilanciata + +```javascript +tryCatch(isBalanced("(") === false); +``` + +Una parentesi chiusa prima di qualsiasi parentesi aperta non è bilanciata + +```javascript +tryCatch(isBalanced(")(") === false); +``` + +Coppie incrociate più in profondità nella stringa non sono bilanciate + +```javascript +tryCatch(isBalanced("(([]{[}]))") === false); +``` + +Una parentesi chiusa lasciata alla fine non è bilanciata + +```javascript +tryCatch(isBalanced("())") === false); +``` + +# --after-asserts-- + +```javascript +// DO NOT EDIT FROM HERE +console.log(`Executed ${_testCount} tests, with ${_testFailedCount} failures`); +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```javascript +function isBalanced(text) { + const pairs = { ")": "(", "]": "[", "}": "{" }; + const stack = []; + + for (const char of text) { + if (char === "(" || char === "[" || char === "{") { + stack.push(char); + } else if (char in pairs) { + if (stack.pop() !== pairs[char]) { + return false; + } + } + } + + return stack.length === 0; +} +``` diff --git a/it/kotlin/challenges/data.json b/it/kotlin/challenges/data.json index b13d0eadc..dfc34dedd 100644 --- a/it/kotlin/challenges/data.json +++ b/it/kotlin/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramma" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Parentesi bilanciate" } } diff --git a/it/kotlin/challenges/matching_brackets.md b/it/kotlin/challenges/matching_brackets.md new file mode 100644 index 000000000..e6d51cbdb --- /dev/null +++ b/it/kotlin/challenges/matching_brackets.md @@ -0,0 +1,157 @@ +--- +language: kotlin +exerciseType: 1 +difficulty: 3 +title: Parentesi bilanciate +--- + +# --description-- + +Il testo che contiene codice, formule matematiche o markup è pieno di parentesi, e ogni parentesi aperta ha bisogno di una chiusa dello stesso tipo. Una stringa è bilanciata quando le sue parentesi si accoppiano e si annidano come gli strati di una cipolla: `{[()]}` è bilanciata, mentre `{[(])}` non lo è, perché la coppia tonda viene chiusa prima della coppia quadrata al cui interno si trova. + +Qui contano tre coppie: le tonde `()`, le quadre `[]` e le graffe `{}`. Ogni altro carattere della stringa viene ignorato. Una parentesi chiusa deve chiudere la parentesi aperta più di recente che risulta ancora aperta, e quando la stringa termina nessuna parentesi può rimanere aperta. + +# --instructions-- + +Scrivi una funzione `isBalanced` che prende una stringa e restituisce `true` quando tutte le parentesi in essa contenute sono accoppiate e correttamente annidate, e `false` altrimenti. + +Esempi: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Una stringa vuota è bilanciata. +- I caratteri che non sono parentesi vengono ignorati. +- Una parentesi chiusa deve corrispondere alla parentesi aperta più di recente che risulta ancora aperta. +- Nessuna parentesi può rimanere aperta quando la stringa termina. + +# --seed-- + +```kotlin +fun isBalanced(text: String): Boolean { + +} +``` + +# --before-seed-- + +```kotlin +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +fun tryCatch(assertion: Boolean) { + _testCount++ + try { + if (!assertion) throw Exception() + } + catch (e: Throwable) { + _testFailedCount++ + println("Test Case '--err-t$_testCount--' failed"); + } +}; +// DO NOT EDIT UNTIL HERE +fun main() { +``` + +# --asserts-- + +Una stringa vuota è bilanciata + +```kotlin + tryCatch(isBalanced("") == true) +``` + +Una singola coppia di parentesi tonde è bilanciata + +```kotlin + tryCatch(isBalanced("()") == true) +``` + +I tre tipi di coppia annidati l'uno dentro l'altro sono bilanciati + +```kotlin + tryCatch(isBalanced("{[()]}") == true) +``` + +Parentesi mescolate ad altro testo restano comunque bilanciate + +```kotlin + tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +Coppie poste una accanto all'altra sono bilanciate + +```kotlin + tryCatch(isBalanced("()[]{}") == true) +``` + +Una stringa senza alcuna parentesi è bilanciata + +```kotlin + tryCatch(isBalanced("no brackets in here at all") == true) +``` + +Una coppia incrociata non è bilanciata + +```kotlin + tryCatch(isBalanced("{[(])}") == false) +``` + +Una parentesi aperta che non viene mai chiusa non è bilanciata + +```kotlin + tryCatch(isBalanced("(") == false) +``` + +Una parentesi chiusa prima di qualsiasi parentesi aperta non è bilanciata + +```kotlin + tryCatch(isBalanced(")(") == false) +``` + +Coppie incrociate più in profondità nella stringa non sono bilanciate + +```kotlin + tryCatch(isBalanced("(([]{[}]))") == false) +``` + +Una parentesi chiusa lasciata alla fine non è bilanciata + +```kotlin + tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```kotlin +// DO NOT EDIT FROM HERE + println("Executed $_testCount tests, with $_testFailedCount failures"); +} +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```kotlin +fun isBalanced(text: String): Boolean { + val pairs = mapOf(')' to '(', ']' to '[', '}' to '{') + val stack = ArrayDeque() + + for (char in text) { + if (char == '(' || char == '[' || char == '{') { + stack.addLast(char) + } else if (pairs.containsKey(char)) { + if (stack.isEmpty() || stack.removeLast() != pairs[char]) { + return false + } + } + } + + return stack.isEmpty() +} +``` diff --git a/it/python/challenges/data.json b/it/python/challenges/data.json index 67f17964d..dfd72e69f 100644 --- a/it/python/challenges/data.json +++ b/it/python/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramma" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Parentesi bilanciate" } } diff --git a/it/python/challenges/matching_brackets.md b/it/python/challenges/matching_brackets.md new file mode 100644 index 000000000..801f9d778 --- /dev/null +++ b/it/python/challenges/matching_brackets.md @@ -0,0 +1,149 @@ +--- +language: python +exerciseType: 1 +difficulty: 3 +title: Parentesi bilanciate +--- + +# --description-- + +Il testo che contiene codice, formule matematiche o markup è pieno di parentesi, e ogni parentesi aperta ha bisogno di una chiusa dello stesso tipo. Una stringa è bilanciata quando le sue parentesi si accoppiano e si annidano come gli strati di una cipolla: `{[()]}` è bilanciata, mentre `{[(])}` non lo è, perché la coppia tonda viene chiusa prima della coppia quadrata al cui interno si trova. + +Qui contano tre coppie: le tonde `()`, le quadre `[]` e le graffe `{}`. Ogni altro carattere della stringa viene ignorato. Una parentesi chiusa deve chiudere la parentesi aperta più di recente che risulta ancora aperta, e quando la stringa termina nessuna parentesi può rimanere aperta. + +# --instructions-- + +Scrivi una funzione `is_balanced` che prende una stringa e restituisce `True` quando tutte le parentesi in essa contenute sono accoppiate e correttamente annidate, e `False` altrimenti. + +Esempi: +``` +is_balanced("") ➞ True +is_balanced("{[()]}") ➞ True +is_balanced("{what is (42)}[?]") ➞ True +is_balanced("{[(])}") ➞ False +is_balanced("(") ➞ False +is_balanced(")(") ➞ False +``` + +- Una stringa vuota è bilanciata. +- I caratteri che non sono parentesi vengono ignorati. +- Una parentesi chiusa deve corrispondere alla parentesi aperta più di recente che risulta ancora aperta. +- Nessuna parentesi può rimanere aperta quando la stringa termina. + +# --seed-- + +```python +def is_balanced(text): + pass +``` + +# --before-asserts-- + +```python +import unittest + +class CodigoTests(unittest.TestCase): +``` + +# --asserts-- + +Una stringa vuota è bilanciata + +```python + def test1(self): + self.assertEqual(is_balanced(""), True, "--err-t1--") +``` + +Una singola coppia di parentesi tonde è bilanciata + +```python + def test2(self): + self.assertEqual(is_balanced("()"), True, "--err-t2--") +``` + +I tre tipi di coppia annidati l'uno dentro l'altro sono bilanciati + +```python + def test3(self): + self.assertEqual(is_balanced("{[()]}"), True, "--err-t3--") +``` + +Parentesi mescolate ad altro testo restano comunque bilanciate + +```python + def test4(self): + self.assertEqual(is_balanced("{what is (42)}[?]"), True, "--err-t4--") +``` + +Coppie poste una accanto all'altra sono bilanciate + +```python + def test5(self): + self.assertEqual(is_balanced("()[]{}"), True, "--err-t5--") +``` + +Una stringa senza alcuna parentesi è bilanciata + +```python + def test6(self): + self.assertEqual(is_balanced("no brackets in here at all"), True, "--err-t6--") +``` + +Una coppia incrociata non è bilanciata + +```python + def test7(self): + self.assertEqual(is_balanced("{[(])}"), False, "--err-t7--") +``` + +Una parentesi aperta che non viene mai chiusa non è bilanciata + +```python + def test8(self): + self.assertEqual(is_balanced("("), False, "--err-t8--") +``` + +Una parentesi chiusa prima di qualsiasi parentesi aperta non è bilanciata + +```python + def test9(self): + self.assertEqual(is_balanced(")("), False, "--err-t9--") +``` + +Coppie incrociate più in profondità nella stringa non sono bilanciate + +```python + def test10(self): + self.assertEqual(is_balanced("(([]{[}]))"), False, "--err-t10--") +``` + +Una parentesi chiusa lasciata alla fine non è bilanciata + +```python + def test11(self): + self.assertEqual(is_balanced("())"), False, "--err-t11--") +``` + +# --after-asserts-- + +```python +if __name__ == "__main__": + unittest.main() +``` + +# --solutions-- + +```python +def is_balanced(text): + pairs = {")": "(", "]": "[", "}": "{"} + stack = [] + + for char in text: + if char in "([{": + stack.append(char) + elif char in pairs: + if not stack or stack.pop() != pairs[char]: + return False + + return not stack +``` diff --git a/it/swift/challenges/data.json b/it/swift/challenges/data.json index c4a1c64b1..7ec948d6f 100644 --- a/it/swift/challenges/data.json +++ b/it/swift/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagramma" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Parentesi bilanciate" } } diff --git a/it/swift/challenges/matching_brackets.md b/it/swift/challenges/matching_brackets.md new file mode 100644 index 000000000..929f5cb38 --- /dev/null +++ b/it/swift/challenges/matching_brackets.md @@ -0,0 +1,152 @@ +--- +language: swift +exerciseType: 1 +difficulty: 3 +title: Parentesi bilanciate +--- + +# --description-- + +Il testo che contiene codice, formule matematiche o markup è pieno di parentesi, e ogni parentesi aperta ha bisogno di una chiusa dello stesso tipo. Una stringa è bilanciata quando le sue parentesi si accoppiano e si annidano come gli strati di una cipolla: `{[()]}` è bilanciata, mentre `{[(])}` non lo è, perché la coppia tonda viene chiusa prima della coppia quadrata al cui interno si trova. + +Qui contano tre coppie: le tonde `()`, le quadre `[]` e le graffe `{}`. Ogni altro carattere della stringa viene ignorato. Una parentesi chiusa deve chiudere la parentesi aperta più di recente che risulta ancora aperta, e quando la stringa termina nessuna parentesi può rimanere aperta. + +# --instructions-- + +Scrivi una funzione `isBalanced` che prende una stringa e restituisce `true` quando tutte le parentesi in essa contenute sono accoppiate e correttamente annidate, e `false` altrimenti. + +Esempi: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Una stringa vuota è bilanciata. +- I caratteri che non sono parentesi vengono ignorati. +- Una parentesi chiusa deve corrispondere alla parentesi aperta più di recente che risulta ancora aperta. +- Nessuna parentesi può rimanere aperta quando la stringa termina. + +# --before-seed-- + +```swift +// DO NOT EDIT FROM HERE +import Foundation + +var _testCount = 0 +var _testFailedCount = 0 +func tryCatch(_ assertion: Bool) { + _testCount += 1 + if !assertion { + _testFailedCount += 1 + print("Test Case '--err-t\(_testCount)--' failed") + } +} +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```swift +func isBalanced(_ text: String) -> Bool { + +} +``` + +# --asserts-- + +Una stringa vuota è bilanciata + +```swift +tryCatch(isBalanced("") == true) +``` + +Una singola coppia di parentesi tonde è bilanciata + +```swift +tryCatch(isBalanced("()") == true) +``` + +I tre tipi di coppia annidati l'uno dentro l'altro sono bilanciati + +```swift +tryCatch(isBalanced("{[()]}") == true) +``` + +Parentesi mescolate ad altro testo restano comunque bilanciate + +```swift +tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +Coppie poste una accanto all'altra sono bilanciate + +```swift +tryCatch(isBalanced("()[]{}") == true) +``` + +Una stringa senza alcuna parentesi è bilanciata + +```swift +tryCatch(isBalanced("no brackets in here at all") == true) +``` + +Una coppia incrociata non è bilanciata + +```swift +tryCatch(isBalanced("{[(])}") == false) +``` + +Una parentesi aperta che non viene mai chiusa non è bilanciata + +```swift +tryCatch(isBalanced("(") == false) +``` + +Una parentesi chiusa prima di qualsiasi parentesi aperta non è bilanciata + +```swift +tryCatch(isBalanced(")(") == false) +``` + +Coppie incrociate più in profondità nella stringa non sono bilanciate + +```swift +tryCatch(isBalanced("(([]{[}]))") == false) +``` + +Una parentesi chiusa lasciata alla fine non è bilanciata + +```swift +tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```swift +print("Executed \(_testCount) tests, with \(_testFailedCount) failures") +``` + +# --solutions-- + +```swift +func isBalanced(_ text: String) -> Bool { + let pairs: [Character: Character] = [")": "(", "]": "[", "}": "{"] + var stack: [Character] = [] + + for char in text { + if char == "(" || char == "[" || char == "{" { + stack.append(char) + } else if let opening = pairs[char] { + if stack.popLast() != opening { + return false + } + } + } + + return stack.isEmpty +} +``` diff --git a/ja/c/challenges/data.json b/ja/c/challenges/data.json index ac7f2ca29..ae495a036 100644 --- a/ja/c/challenges/data.json +++ b/ja/c/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "アナグラム" + }, + "matching_brackets": { + "difficulty": 3, + "name": "括弧の対応" } } diff --git a/ja/c/challenges/matching_brackets.md b/ja/c/challenges/matching_brackets.md new file mode 100644 index 000000000..e763a04aa --- /dev/null +++ b/ja/c/challenges/matching_brackets.md @@ -0,0 +1,280 @@ +--- +language: c +exerciseType: 1 +difficulty: 3 +title: 括弧の対応 +--- + +# --description-- + +コードや数式、マークアップを含むテキストには括弧が数多く登場し、開き括弧にはどれも同じ種類の閉じ括弧が必要です。括弧が対をなして玉ねぎの層のように入れ子になっていくとき、その文字列はバランスが取れています。`{[()]}` はバランスが取れていますが、`{[(])}` はバランスが取れていません。丸括弧の組が、その丸括弧が内側に収まっている角括弧の組よりも先に閉じられているからです。 + +ここで数えるのは、丸括弧 `()`、角括弧 `[]`、波括弧 `{}` の3組です。文字列内のそれ以外の文字はすべて無視されます。閉じ括弧は、まだ開いている括弧の中で最も新しく開かれた括弧を閉じなければならず、文字列が終わるときに開いたままの括弧が残っていてはいけません。 + +# --instructions-- + +文字列を受け取り、その中のすべての括弧が対応して正しく入れ子になっていれば `true` を、そうでなければ `false` を返す関数 `isBalanced` を書いてください。 + +例: +``` +is_balanced("") ➞ true +is_balanced("{[()]}") ➞ true +is_balanced("{what is (42)}[?]") ➞ true +is_balanced("{[(])}") ➞ false +is_balanced("(") ➞ false +is_balanced(")(") ➞ false +``` + +- 空の文字列はバランスが取れています。 +- 括弧以外の文字は無視されます。 +- 閉じ括弧は、まだ開いている括弧の中で最も新しく開かれた括弧と対応しなければなりません。 +- 文字列が終わるとき、開いたままの括弧が残っていてはいけません。 + +# --before-seed-- + +```c +// DO NOT EDIT FROM HERE +#include +#include +#include + +#ifndef _CEXCEPTION_H +#define _CEXCEPTION_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +//This is the value to assign when there isn't an exception +#ifndef CEXCEPTION_NONE +#define CEXCEPTION_NONE (0x5A5A5A5A) +#endif + +//This is number of exception stacks to keep track of (one per task) +#ifndef CEXCEPTION_NUM_ID +#define CEXCEPTION_NUM_ID (1) //there is only the one stack by default +#endif + +//This is the method of getting the current exception stack index (0 if only one stack) +#ifndef CEXCEPTION_GET_ID +#define CEXCEPTION_GET_ID (0) //use the first index always because there is only one anyway +#endif + +//The type to use to store the exception values. +#ifndef CEXCEPTION_T +#define CEXCEPTION_T unsigned int +#endif + +//This is an optional special handler for when there is no global Catch +#ifndef CEXCEPTION_NO_CATCH_HANDLER +#define CEXCEPTION_NO_CATCH_HANDLER(id) +#endif + +//These hooks allow you to inject custom code into places, particularly useful for saving and restoring additional state +#ifndef CEXCEPTION_HOOK_START_TRY +#define CEXCEPTION_HOOK_START_TRY +#endif +#ifndef CEXCEPTION_HOOK_HAPPY_TRY +#define CEXCEPTION_HOOK_HAPPY_TRY +#endif +#ifndef CEXCEPTION_HOOK_AFTER_TRY +#define CEXCEPTION_HOOK_AFTER_TRY +#endif +#ifndef CEXCEPTION_HOOK_START_CATCH +#define CEXCEPTION_HOOK_START_CATCH +#endif + +//exception frame structures +typedef struct { + jmp_buf* pFrame; + CEXCEPTION_T volatile Exception; +} CEXCEPTION_FRAME_T; + +//actual root frame storage (only one if single-tasking) +extern volatile CEXCEPTION_FRAME_T CExceptionFrames[]; + +//Try +#define Try \ + { \ + jmp_buf *PrevFrame, NewFrame; \ + unsigned int MY_ID = CEXCEPTION_GET_ID; \ + PrevFrame = CExceptionFrames[MY_ID].pFrame; \ + CExceptionFrames[MY_ID].pFrame = (jmp_buf*)(&NewFrame); \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_START_TRY; \ + if (setjmp(NewFrame) == 0) { \ + if (1) + +//Catch +#define Catch(e) \ + else { } \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_HAPPY_TRY; \ + } \ + else \ + { \ + e = CExceptionFrames[MY_ID].Exception; \ + (void)e; \ + CEXCEPTION_HOOK_START_CATCH; \ + } \ + CExceptionFrames[MY_ID].pFrame = PrevFrame; \ + CEXCEPTION_HOOK_AFTER_TRY; \ + } \ + if (CExceptionFrames[CEXCEPTION_GET_ID].Exception != CEXCEPTION_NONE) + +#endif + +volatile CEXCEPTION_FRAME_T CExceptionFrames[CEXCEPTION_NUM_ID] = {{ 0 }}; + +void Throw(CEXCEPTION_T ExceptionID) +{ + unsigned int MY_ID = CEXCEPTION_GET_ID; + CExceptionFrames[MY_ID].Exception = ExceptionID; + if (CExceptionFrames[MY_ID].pFrame) + { + longjmp(*CExceptionFrames[MY_ID].pFrame, 1); + } + CEXCEPTION_NO_CATCH_HANDLER(ExceptionID); +} + +CEXCEPTION_T e; +int _test_failed_count = 0; +int _test_count = 0; + +void try_catch(bool assertion) { + _test_count++; + Try { + if (!assertion) { + Throw(_test_count); + } + } Catch (e) { + _test_failed_count += 1; + printf("Test Case '--err-t%i--' failed\n", e); + } +} +// DO NOT EDIT UNTIL HERE +#include +#include +``` + +# --seed-- + +```c +bool is_balanced(const char* text) { + +} +``` + +# --before-asserts-- + +```c +int main() { +``` + +# --asserts-- + +空の文字列はバランスが取れている + +```c + try_catch(is_balanced("") == true); +``` + +丸括弧1組だけの文字列はバランスが取れている + +```c + try_catch(is_balanced("()") == true); +``` + +3種類の組が互いに入れ子になった文字列はバランスが取れている + +```c + try_catch(is_balanced("{[()]}") == true); +``` + +括弧が他のテキストと混ざっていてもバランスが取れている + +```c + try_catch(is_balanced("{what is (42)}[?]") == true); +``` + +組が横に並んでいてもバランスが取れている + +```c + try_catch(is_balanced("()[]{}") == true); +``` + +括弧をまったく含まない文字列はバランスが取れている + +```c + try_catch(is_balanced("no brackets in here at all") == true); +``` + +交差した組はバランスが取れていない + +```c + try_catch(is_balanced("{[(])}") == false); +``` + +閉じられないままの開き括弧はバランスが取れていない + +```c + try_catch(is_balanced("(") == false); +``` + +開き括弧より先に来る閉じ括弧はバランスが取れていない + +```c + try_catch(is_balanced(")(") == false); +``` + +文字列の奥で交差した組はバランスが取れていない + +```c + try_catch(is_balanced("(([]{[}]))") == false); +``` + +最後に余った閉じ括弧はバランスが取れていない + +```c + try_catch(is_balanced("())") == false); +``` + +# --after-asserts-- + +```c + printf("Executed %d tests, with %d failures", _test_count, _test_failed_count); + return 0; +} +``` + +# --solutions-- + +```c +bool is_balanced(const char* text) { + size_t length = strlen(text); + char stack[length + 1]; + size_t top = 0; + + for (size_t i = 0; i < length; i++) { + char current = text[i]; + + if (current == '(' || current == '[' || current == '{') { + stack[top++] = current; + } else if (current == ')' || current == ']' || current == '}') { + if (top == 0) { + return false; + } + + char opening = stack[--top]; + if ((current == ')' && opening != '(') || + (current == ']' && opening != '[') || + (current == '}' && opening != '{')) { + return false; + } + } + } + + return top == 0; +} +``` diff --git a/ja/dart/challenges/data.json b/ja/dart/challenges/data.json index 6eb9346e3..4620d688e 100644 --- a/ja/dart/challenges/data.json +++ b/ja/dart/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "アナグラム" + }, + "matching_brackets": { + "difficulty": 3, + "name": "括弧の対応" } } diff --git a/ja/dart/challenges/matching_brackets.md b/ja/dart/challenges/matching_brackets.md new file mode 100644 index 000000000..3ba5bd5d1 --- /dev/null +++ b/ja/dart/challenges/matching_brackets.md @@ -0,0 +1,167 @@ +--- +language: dart +exerciseType: 1 +difficulty: 3 +title: 括弧の対応 +--- + +# --description-- + +コードや数式、マークアップを含むテキストには括弧が数多く登場し、開き括弧にはどれも同じ種類の閉じ括弧が必要です。括弧が対をなして玉ねぎの層のように入れ子になっていくとき、その文字列はバランスが取れています。`{[()]}` はバランスが取れていますが、`{[(])}` はバランスが取れていません。丸括弧の組が、その丸括弧が内側に収まっている角括弧の組よりも先に閉じられているからです。 + +ここで数えるのは、丸括弧 `()`、角括弧 `[]`、波括弧 `{}` の3組です。文字列内のそれ以外の文字はすべて無視されます。閉じ括弧は、まだ開いている括弧の中で最も新しく開かれた括弧を閉じなければならず、文字列が終わるときに開いたままの括弧が残っていてはいけません。 + +# --instructions-- + +文字列を受け取り、その中のすべての括弧が対応して正しく入れ子になっていれば `true` を、そうでなければ `false` を返す関数 `isBalanced` を書いてください。 + +例: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- 空の文字列はバランスが取れています。 +- 括弧以外の文字は無視されます。 +- 閉じ括弧は、まだ開いている括弧の中で最も新しく開かれた括弧と対応しなければなりません。 +- 文字列が終わるとき、開いたままの括弧が残っていてはいけません。 + +# --seed-- + +```dart +bool isBalanced(String text) { + +} +``` + +# --before-asserts-- + +```dart +import 'package:dart_runner/main.dart'; +import 'package:test/test.dart'; + +void main() { + group('MainTest -', () { +``` + +# --asserts-- + +空の文字列はバランスが取れている + +```dart + test('test1', () { + expect(isBalanced(''), true, reason: '--err-t1--'); + }); +``` + +丸括弧1組だけの文字列はバランスが取れている + +```dart + test('test2', () { + expect(isBalanced('()'), true, reason: '--err-t2--'); + }); +``` + +3種類の組が互いに入れ子になった文字列はバランスが取れている + +```dart + test('test3', () { + expect(isBalanced('{[()]}'), true, reason: '--err-t3--'); + }); +``` + +括弧が他のテキストと混ざっていてもバランスが取れている + +```dart + test('test4', () { + expect(isBalanced('{what is (42)}[?]'), true, reason: '--err-t4--'); + }); +``` + +組が横に並んでいてもバランスが取れている + +```dart + test('test5', () { + expect(isBalanced('()[]{}'), true, reason: '--err-t5--'); + }); +``` + +括弧をまったく含まない文字列はバランスが取れている + +```dart + test('test6', () { + expect(isBalanced('no brackets in here at all'), true, reason: '--err-t6--'); + }); +``` + +交差した組はバランスが取れていない + +```dart + test('test7', () { + expect(isBalanced('{[(])}'), false, reason: '--err-t7--'); + }); +``` + +閉じられないままの開き括弧はバランスが取れていない + +```dart + test('test8', () { + expect(isBalanced('('), false, reason: '--err-t8--'); + }); +``` + +開き括弧より先に来る閉じ括弧はバランスが取れていない + +```dart + test('test9', () { + expect(isBalanced(')('), false, reason: '--err-t9--'); + }); +``` + +文字列の奥で交差した組はバランスが取れていない + +```dart + test('test10', () { + expect(isBalanced('(([]{[}]))'), false, reason: '--err-t10--'); + }); +``` + +最後に余った閉じ括弧はバランスが取れていない + +```dart + test('test11', () { + expect(isBalanced('())'), false, reason: '--err-t11--'); + }); +``` + +# --after-asserts-- + +```dart + }, timeout: Timeout(const Duration(seconds: 1))); +} +``` + +# --solutions-- + +```dart +bool isBalanced(String text) { + const pairs = {')': '(', ']': '[', '}': '{'}; + final stack = []; + + for (final char in text.split('')) { + if (char == '(' || char == '[' || char == '{') { + stack.add(char); + } else if (pairs.containsKey(char)) { + if (stack.isEmpty || stack.removeLast() != pairs[char]) { + return false; + } + } + } + + return stack.isEmpty; +} +``` diff --git a/ja/javascript/challenges/data.json b/ja/javascript/challenges/data.json index 18cc71ddb..122617866 100644 --- a/ja/javascript/challenges/data.json +++ b/ja/javascript/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "アナグラム" + }, + "matching_brackets": { + "difficulty": 3, + "name": "括弧の対応" } } diff --git a/ja/javascript/challenges/matching_brackets.md b/ja/javascript/challenges/matching_brackets.md new file mode 100644 index 000000000..45651caa6 --- /dev/null +++ b/ja/javascript/challenges/matching_brackets.md @@ -0,0 +1,154 @@ +--- +language: javascript +exerciseType: 1 +difficulty: 3 +title: 括弧の対応 +--- + +# --description-- + +コードや数式、マークアップを含むテキストには括弧が数多く登場し、開き括弧にはどれも同じ種類の閉じ括弧が必要です。括弧が対をなして玉ねぎの層のように入れ子になっていくとき、その文字列はバランスが取れています。`{[()]}` はバランスが取れていますが、`{[(])}` はバランスが取れていません。丸括弧の組が、その丸括弧が内側に収まっている角括弧の組よりも先に閉じられているからです。 + +ここで数えるのは、丸括弧 `()`、角括弧 `[]`、波括弧 `{}` の3組です。文字列内のそれ以外の文字はすべて無視されます。閉じ括弧は、まだ開いている括弧の中で最も新しく開かれた括弧を閉じなければならず、文字列が終わるときに開いたままの括弧が残っていてはいけません。 + +# --instructions-- + +文字列を受け取り、その中のすべての括弧が対応して正しく入れ子になっていれば `true` を、そうでなければ `false` を返す関数 `isBalanced` を書いてください。 + +例: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- 空の文字列はバランスが取れています。 +- 括弧以外の文字は無視されます。 +- 閉じ括弧は、まだ開いている括弧の中で最も新しく開かれた括弧と対応しなければなりません。 +- 文字列が終わるとき、開いたままの括弧が残っていてはいけません。 + +# --before-seed-- + +```javascript +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +var assert = require('assert') +const tryCatch = (...args) => { + _testCount++ + try { assert(...args) } + catch (e) { + _testFailedCount++ + console.log(`Test Case '--err-t${_testCount}--' failed`); + } +}; +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```javascript +function isBalanced(text) { + +} +``` + +# --asserts-- + +空の文字列はバランスが取れている + +```javascript +tryCatch(isBalanced("") === true); +``` + +丸括弧1組だけの文字列はバランスが取れている + +```javascript +tryCatch(isBalanced("()") === true); +``` + +3種類の組が互いに入れ子になった文字列はバランスが取れている + +```javascript +tryCatch(isBalanced("{[()]}") === true); +``` + +括弧が他のテキストと混ざっていてもバランスが取れている + +```javascript +tryCatch(isBalanced("{what is (42)}[?]") === true); +``` + +組が横に並んでいてもバランスが取れている + +```javascript +tryCatch(isBalanced("()[]{}") === true); +``` + +括弧をまったく含まない文字列はバランスが取れている + +```javascript +tryCatch(isBalanced("no brackets in here at all") === true); +``` + +交差した組はバランスが取れていない + +```javascript +tryCatch(isBalanced("{[(])}") === false); +``` + +閉じられないままの開き括弧はバランスが取れていない + +```javascript +tryCatch(isBalanced("(") === false); +``` + +開き括弧より先に来る閉じ括弧はバランスが取れていない + +```javascript +tryCatch(isBalanced(")(") === false); +``` + +文字列の奥で交差した組はバランスが取れていない + +```javascript +tryCatch(isBalanced("(([]{[}]))") === false); +``` + +最後に余った閉じ括弧はバランスが取れていない + +```javascript +tryCatch(isBalanced("())") === false); +``` + +# --after-asserts-- + +```javascript +// DO NOT EDIT FROM HERE +console.log(`Executed ${_testCount} tests, with ${_testFailedCount} failures`); +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```javascript +function isBalanced(text) { + const pairs = { ")": "(", "]": "[", "}": "{" }; + const stack = []; + + for (const char of text) { + if (char === "(" || char === "[" || char === "{") { + stack.push(char); + } else if (char in pairs) { + if (stack.pop() !== pairs[char]) { + return false; + } + } + } + + return stack.length === 0; +} +``` diff --git a/ja/kotlin/challenges/data.json b/ja/kotlin/challenges/data.json index 3dca9a298..6011a5da3 100644 --- a/ja/kotlin/challenges/data.json +++ b/ja/kotlin/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "アナグラム" + }, + "matching_brackets": { + "difficulty": 3, + "name": "括弧の対応" } } diff --git a/ja/kotlin/challenges/matching_brackets.md b/ja/kotlin/challenges/matching_brackets.md new file mode 100644 index 000000000..afa9aa0f8 --- /dev/null +++ b/ja/kotlin/challenges/matching_brackets.md @@ -0,0 +1,157 @@ +--- +language: kotlin +exerciseType: 1 +difficulty: 3 +title: 括弧の対応 +--- + +# --description-- + +コードや数式、マークアップを含むテキストには括弧が数多く登場し、開き括弧にはどれも同じ種類の閉じ括弧が必要です。括弧が対をなして玉ねぎの層のように入れ子になっていくとき、その文字列はバランスが取れています。`{[()]}` はバランスが取れていますが、`{[(])}` はバランスが取れていません。丸括弧の組が、その丸括弧が内側に収まっている角括弧の組よりも先に閉じられているからです。 + +ここで数えるのは、丸括弧 `()`、角括弧 `[]`、波括弧 `{}` の3組です。文字列内のそれ以外の文字はすべて無視されます。閉じ括弧は、まだ開いている括弧の中で最も新しく開かれた括弧を閉じなければならず、文字列が終わるときに開いたままの括弧が残っていてはいけません。 + +# --instructions-- + +文字列を受け取り、その中のすべての括弧が対応して正しく入れ子になっていれば `true` を、そうでなければ `false` を返す関数 `isBalanced` を書いてください。 + +例: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- 空の文字列はバランスが取れています。 +- 括弧以外の文字は無視されます。 +- 閉じ括弧は、まだ開いている括弧の中で最も新しく開かれた括弧と対応しなければなりません。 +- 文字列が終わるとき、開いたままの括弧が残っていてはいけません。 + +# --seed-- + +```kotlin +fun isBalanced(text: String): Boolean { + +} +``` + +# --before-seed-- + +```kotlin +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +fun tryCatch(assertion: Boolean) { + _testCount++ + try { + if (!assertion) throw Exception() + } + catch (e: Throwable) { + _testFailedCount++ + println("Test Case '--err-t$_testCount--' failed"); + } +}; +// DO NOT EDIT UNTIL HERE +fun main() { +``` + +# --asserts-- + +空の文字列はバランスが取れている + +```kotlin + tryCatch(isBalanced("") == true) +``` + +丸括弧1組だけの文字列はバランスが取れている + +```kotlin + tryCatch(isBalanced("()") == true) +``` + +3種類の組が互いに入れ子になった文字列はバランスが取れている + +```kotlin + tryCatch(isBalanced("{[()]}") == true) +``` + +括弧が他のテキストと混ざっていてもバランスが取れている + +```kotlin + tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +組が横に並んでいてもバランスが取れている + +```kotlin + tryCatch(isBalanced("()[]{}") == true) +``` + +括弧をまったく含まない文字列はバランスが取れている + +```kotlin + tryCatch(isBalanced("no brackets in here at all") == true) +``` + +交差した組はバランスが取れていない + +```kotlin + tryCatch(isBalanced("{[(])}") == false) +``` + +閉じられないままの開き括弧はバランスが取れていない + +```kotlin + tryCatch(isBalanced("(") == false) +``` + +開き括弧より先に来る閉じ括弧はバランスが取れていない + +```kotlin + tryCatch(isBalanced(")(") == false) +``` + +文字列の奥で交差した組はバランスが取れていない + +```kotlin + tryCatch(isBalanced("(([]{[}]))") == false) +``` + +最後に余った閉じ括弧はバランスが取れていない + +```kotlin + tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```kotlin +// DO NOT EDIT FROM HERE + println("Executed $_testCount tests, with $_testFailedCount failures"); +} +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```kotlin +fun isBalanced(text: String): Boolean { + val pairs = mapOf(')' to '(', ']' to '[', '}' to '{') + val stack = ArrayDeque() + + for (char in text) { + if (char == '(' || char == '[' || char == '{') { + stack.addLast(char) + } else if (pairs.containsKey(char)) { + if (stack.isEmpty() || stack.removeLast() != pairs[char]) { + return false + } + } + } + + return stack.isEmpty() +} +``` diff --git a/ja/python/challenges/data.json b/ja/python/challenges/data.json index 18cc71ddb..122617866 100644 --- a/ja/python/challenges/data.json +++ b/ja/python/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "アナグラム" + }, + "matching_brackets": { + "difficulty": 3, + "name": "括弧の対応" } } diff --git a/ja/python/challenges/matching_brackets.md b/ja/python/challenges/matching_brackets.md new file mode 100644 index 000000000..5600f1a36 --- /dev/null +++ b/ja/python/challenges/matching_brackets.md @@ -0,0 +1,149 @@ +--- +language: python +exerciseType: 1 +difficulty: 3 +title: 括弧の対応 +--- + +# --description-- + +コードや数式、マークアップを含むテキストには括弧が数多く登場し、開き括弧にはどれも同じ種類の閉じ括弧が必要です。括弧が対をなして玉ねぎの層のように入れ子になっていくとき、その文字列はバランスが取れています。`{[()]}` はバランスが取れていますが、`{[(])}` はバランスが取れていません。丸括弧の組が、その丸括弧が内側に収まっている角括弧の組よりも先に閉じられているからです。 + +ここで数えるのは、丸括弧 `()`、角括弧 `[]`、波括弧 `{}` の3組です。文字列内のそれ以外の文字はすべて無視されます。閉じ括弧は、まだ開いている括弧の中で最も新しく開かれた括弧を閉じなければならず、文字列が終わるときに開いたままの括弧が残っていてはいけません。 + +# --instructions-- + +文字列を受け取り、その中のすべての括弧が対応して正しく入れ子になっていれば `True` を、そうでなければ `False` を返す関数 `is_balanced` を書いてください。 + +例: +``` +is_balanced("") ➞ True +is_balanced("{[()]}") ➞ True +is_balanced("{what is (42)}[?]") ➞ True +is_balanced("{[(])}") ➞ False +is_balanced("(") ➞ False +is_balanced(")(") ➞ False +``` + +- 空の文字列はバランスが取れています。 +- 括弧以外の文字は無視されます。 +- 閉じ括弧は、まだ開いている括弧の中で最も新しく開かれた括弧と対応しなければなりません。 +- 文字列が終わるとき、開いたままの括弧が残っていてはいけません。 + +# --seed-- + +```python +def is_balanced(text): + pass +``` + +# --before-asserts-- + +```python +import unittest + +class CodigoTests(unittest.TestCase): +``` + +# --asserts-- + +空の文字列はバランスが取れている + +```python + def test1(self): + self.assertEqual(is_balanced(""), True, "--err-t1--") +``` + +丸括弧1組だけの文字列はバランスが取れている + +```python + def test2(self): + self.assertEqual(is_balanced("()"), True, "--err-t2--") +``` + +3種類の組が互いに入れ子になった文字列はバランスが取れている + +```python + def test3(self): + self.assertEqual(is_balanced("{[()]}"), True, "--err-t3--") +``` + +括弧が他のテキストと混ざっていてもバランスが取れている + +```python + def test4(self): + self.assertEqual(is_balanced("{what is (42)}[?]"), True, "--err-t4--") +``` + +組が横に並んでいてもバランスが取れている + +```python + def test5(self): + self.assertEqual(is_balanced("()[]{}"), True, "--err-t5--") +``` + +括弧をまったく含まない文字列はバランスが取れている + +```python + def test6(self): + self.assertEqual(is_balanced("no brackets in here at all"), True, "--err-t6--") +``` + +交差した組はバランスが取れていない + +```python + def test7(self): + self.assertEqual(is_balanced("{[(])}"), False, "--err-t7--") +``` + +閉じられないままの開き括弧はバランスが取れていない + +```python + def test8(self): + self.assertEqual(is_balanced("("), False, "--err-t8--") +``` + +開き括弧より先に来る閉じ括弧はバランスが取れていない + +```python + def test9(self): + self.assertEqual(is_balanced(")("), False, "--err-t9--") +``` + +文字列の奥で交差した組はバランスが取れていない + +```python + def test10(self): + self.assertEqual(is_balanced("(([]{[}]))"), False, "--err-t10--") +``` + +最後に余った閉じ括弧はバランスが取れていない + +```python + def test11(self): + self.assertEqual(is_balanced("())"), False, "--err-t11--") +``` + +# --after-asserts-- + +```python +if __name__ == "__main__": + unittest.main() +``` + +# --solutions-- + +```python +def is_balanced(text): + pairs = {")": "(", "]": "[", "}": "{"} + stack = [] + + for char in text: + if char in "([{": + stack.append(char) + elif char in pairs: + if not stack or stack.pop() != pairs[char]: + return False + + return not stack +``` diff --git a/ja/swift/challenges/data.json b/ja/swift/challenges/data.json index ac6456450..7dcd502d7 100644 --- a/ja/swift/challenges/data.json +++ b/ja/swift/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "アナグラム" + }, + "matching_brackets": { + "difficulty": 3, + "name": "括弧の対応" } } diff --git a/ja/swift/challenges/matching_brackets.md b/ja/swift/challenges/matching_brackets.md new file mode 100644 index 000000000..9e23bafbe --- /dev/null +++ b/ja/swift/challenges/matching_brackets.md @@ -0,0 +1,152 @@ +--- +language: swift +exerciseType: 1 +difficulty: 3 +title: 括弧の対応 +--- + +# --description-- + +コードや数式、マークアップを含むテキストには括弧が数多く登場し、開き括弧にはどれも同じ種類の閉じ括弧が必要です。括弧が対をなして玉ねぎの層のように入れ子になっていくとき、その文字列はバランスが取れています。`{[()]}` はバランスが取れていますが、`{[(])}` はバランスが取れていません。丸括弧の組が、その丸括弧が内側に収まっている角括弧の組よりも先に閉じられているからです。 + +ここで数えるのは、丸括弧 `()`、角括弧 `[]`、波括弧 `{}` の3組です。文字列内のそれ以外の文字はすべて無視されます。閉じ括弧は、まだ開いている括弧の中で最も新しく開かれた括弧を閉じなければならず、文字列が終わるときに開いたままの括弧が残っていてはいけません。 + +# --instructions-- + +文字列を受け取り、その中のすべての括弧が対応して正しく入れ子になっていれば `true` を、そうでなければ `false` を返す関数 `isBalanced` を書いてください。 + +例: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- 空の文字列はバランスが取れています。 +- 括弧以外の文字は無視されます。 +- 閉じ括弧は、まだ開いている括弧の中で最も新しく開かれた括弧と対応しなければなりません。 +- 文字列が終わるとき、開いたままの括弧が残っていてはいけません。 + +# --before-seed-- + +```swift +// DO NOT EDIT FROM HERE +import Foundation + +var _testCount = 0 +var _testFailedCount = 0 +func tryCatch(_ assertion: Bool) { + _testCount += 1 + if !assertion { + _testFailedCount += 1 + print("Test Case '--err-t\(_testCount)--' failed") + } +} +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```swift +func isBalanced(_ text: String) -> Bool { + +} +``` + +# --asserts-- + +空の文字列はバランスが取れている + +```swift +tryCatch(isBalanced("") == true) +``` + +丸括弧1組だけの文字列はバランスが取れている + +```swift +tryCatch(isBalanced("()") == true) +``` + +3種類の組が互いに入れ子になった文字列はバランスが取れている + +```swift +tryCatch(isBalanced("{[()]}") == true) +``` + +括弧が他のテキストと混ざっていてもバランスが取れている + +```swift +tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +組が横に並んでいてもバランスが取れている + +```swift +tryCatch(isBalanced("()[]{}") == true) +``` + +括弧をまったく含まない文字列はバランスが取れている + +```swift +tryCatch(isBalanced("no brackets in here at all") == true) +``` + +交差した組はバランスが取れていない + +```swift +tryCatch(isBalanced("{[(])}") == false) +``` + +閉じられないままの開き括弧はバランスが取れていない + +```swift +tryCatch(isBalanced("(") == false) +``` + +開き括弧より先に来る閉じ括弧はバランスが取れていない + +```swift +tryCatch(isBalanced(")(") == false) +``` + +文字列の奥で交差した組はバランスが取れていない + +```swift +tryCatch(isBalanced("(([]{[}]))") == false) +``` + +最後に余った閉じ括弧はバランスが取れていない + +```swift +tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```swift +print("Executed \(_testCount) tests, with \(_testFailedCount) failures") +``` + +# --solutions-- + +```swift +func isBalanced(_ text: String) -> Bool { + let pairs: [Character: Character] = [")": "(", "]": "[", "}": "{"] + var stack: [Character] = [] + + for char in text { + if char == "(" || char == "[" || char == "{" { + stack.append(char) + } else if let opening = pairs[char] { + if stack.popLast() != opening { + return false + } + } + } + + return stack.isEmpty +} +``` diff --git a/ko/c/challenges/data.json b/ko/c/challenges/data.json index bf2794f14..7e622197a 100644 --- a/ko/c/challenges/data.json +++ b/ko/c/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "애너그램" + }, + "matching_brackets": { + "difficulty": 3, + "name": "괄호 짝 맞추기" } } diff --git a/ko/c/challenges/matching_brackets.md b/ko/c/challenges/matching_brackets.md new file mode 100644 index 000000000..17383ca5b --- /dev/null +++ b/ko/c/challenges/matching_brackets.md @@ -0,0 +1,280 @@ +--- +language: c +exerciseType: 1 +difficulty: 3 +title: 괄호 짝 맞추기 +--- + +# --description-- + +코드, 수식 또는 마크업을 담는 텍스트에는 괄호가 가득하며, 모든 여는 괄호에는 같은 종류의 닫는 괄호가 필요합니다. 문자열의 괄호들이 양파의 겹처럼 쌍을 이루고 중첩될 때 그 문자열은 균형이 잡혀 있다고 합니다: `{[()]}`는 균형이 잡혀 있지만, `{[(])}`는 그렇지 않습니다. 이는 그 안에 있는 둥근 괄호 쌍이 자신을 감싸고 있는 대괄호 쌍보다 먼저 닫히기 때문입니다. + +여기서는 세 쌍이 대상입니다: 둥근 괄호 `()`, 대괄호 `[]`, 그리고 중괄호 `{}`입니다. 문자열에 있는 다른 모든 문자는 무시합니다. 닫는 괄호는 아직 열려 있는 괄호 중 가장 최근에 열린 괄호를 닫아야 하며, 문자열이 끝날 때 열려 있는 괄호가 남아 있어서는 안 됩니다. + +# --instructions-- + +문자열을 받아 그 안의 모든 괄호가 서로 맞고 올바르게 중첩되어 있으면 `true`를, 그렇지 않으면 `false`를 반환하는 함수 `is_balanced`를 작성하세요. + +예시: +``` +is_balanced("") ➞ true +is_balanced("{[()]}") ➞ true +is_balanced("{what is (42)}[?]") ➞ true +is_balanced("{[(])}") ➞ false +is_balanced("(") ➞ false +is_balanced(")(") ➞ false +``` + +- 빈 문자열은 균형이 잡혀 있습니다. +- 괄호가 아닌 문자는 무시합니다. +- 닫는 괄호는 아직 열려 있는 괄호 중 가장 최근에 열린 괄호와 맞아야 합니다. +- 문자열이 끝날 때 열려 있는 괄호가 남아 있으면 안 됩니다. + +# --before-seed-- + +```c +// DO NOT EDIT FROM HERE +#include +#include +#include + +#ifndef _CEXCEPTION_H +#define _CEXCEPTION_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +//This is the value to assign when there isn't an exception +#ifndef CEXCEPTION_NONE +#define CEXCEPTION_NONE (0x5A5A5A5A) +#endif + +//This is number of exception stacks to keep track of (one per task) +#ifndef CEXCEPTION_NUM_ID +#define CEXCEPTION_NUM_ID (1) //there is only the one stack by default +#endif + +//This is the method of getting the current exception stack index (0 if only one stack) +#ifndef CEXCEPTION_GET_ID +#define CEXCEPTION_GET_ID (0) //use the first index always because there is only one anyway +#endif + +//The type to use to store the exception values. +#ifndef CEXCEPTION_T +#define CEXCEPTION_T unsigned int +#endif + +//This is an optional special handler for when there is no global Catch +#ifndef CEXCEPTION_NO_CATCH_HANDLER +#define CEXCEPTION_NO_CATCH_HANDLER(id) +#endif + +//These hooks allow you to inject custom code into places, particularly useful for saving and restoring additional state +#ifndef CEXCEPTION_HOOK_START_TRY +#define CEXCEPTION_HOOK_START_TRY +#endif +#ifndef CEXCEPTION_HOOK_HAPPY_TRY +#define CEXCEPTION_HOOK_HAPPY_TRY +#endif +#ifndef CEXCEPTION_HOOK_AFTER_TRY +#define CEXCEPTION_HOOK_AFTER_TRY +#endif +#ifndef CEXCEPTION_HOOK_START_CATCH +#define CEXCEPTION_HOOK_START_CATCH +#endif + +//exception frame structures +typedef struct { + jmp_buf* pFrame; + CEXCEPTION_T volatile Exception; +} CEXCEPTION_FRAME_T; + +//actual root frame storage (only one if single-tasking) +extern volatile CEXCEPTION_FRAME_T CExceptionFrames[]; + +//Try +#define Try \ + { \ + jmp_buf *PrevFrame, NewFrame; \ + unsigned int MY_ID = CEXCEPTION_GET_ID; \ + PrevFrame = CExceptionFrames[MY_ID].pFrame; \ + CExceptionFrames[MY_ID].pFrame = (jmp_buf*)(&NewFrame); \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_START_TRY; \ + if (setjmp(NewFrame) == 0) { \ + if (1) + +//Catch +#define Catch(e) \ + else { } \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_HAPPY_TRY; \ + } \ + else \ + { \ + e = CExceptionFrames[MY_ID].Exception; \ + (void)e; \ + CEXCEPTION_HOOK_START_CATCH; \ + } \ + CExceptionFrames[MY_ID].pFrame = PrevFrame; \ + CEXCEPTION_HOOK_AFTER_TRY; \ + } \ + if (CExceptionFrames[CEXCEPTION_GET_ID].Exception != CEXCEPTION_NONE) + +#endif + +volatile CEXCEPTION_FRAME_T CExceptionFrames[CEXCEPTION_NUM_ID] = {{ 0 }}; + +void Throw(CEXCEPTION_T ExceptionID) +{ + unsigned int MY_ID = CEXCEPTION_GET_ID; + CExceptionFrames[MY_ID].Exception = ExceptionID; + if (CExceptionFrames[MY_ID].pFrame) + { + longjmp(*CExceptionFrames[MY_ID].pFrame, 1); + } + CEXCEPTION_NO_CATCH_HANDLER(ExceptionID); +} + +CEXCEPTION_T e; +int _test_failed_count = 0; +int _test_count = 0; + +void try_catch(bool assertion) { + _test_count++; + Try { + if (!assertion) { + Throw(_test_count); + } + } Catch (e) { + _test_failed_count += 1; + printf("Test Case '--err-t%i--' failed\n", e); + } +} +// DO NOT EDIT UNTIL HERE +#include +#include +``` + +# --seed-- + +```c +bool is_balanced(const char* text) { + +} +``` + +# --before-asserts-- + +```c +int main() { +``` + +# --asserts-- + +빈 문자열은 균형이 잡혀 있습니다 + +```c + try_catch(is_balanced("") == true); +``` + +둥근 괄호 한 쌍은 균형이 잡혀 있습니다 + +```c + try_catch(is_balanced("()") == true); +``` + +세 종류의 쌍이 서로 중첩되어 있으면 균형이 잡혀 있습니다 + +```c + try_catch(is_balanced("{[()]}") == true); +``` + +다른 텍스트와 섞인 괄호도 여전히 균형이 잡혀 있습니다 + +```c + try_catch(is_balanced("{what is (42)}[?]") == true); +``` + +나란히 놓인 쌍들은 균형이 잡혀 있습니다 + +```c + try_catch(is_balanced("()[]{}") == true); +``` + +괄호가 전혀 없는 문자열은 균형이 잡혀 있습니다 + +```c + try_catch(is_balanced("no brackets in here at all") == true); +``` + +교차된 쌍은 균형이 잡혀 있지 않습니다 + +```c + try_catch(is_balanced("{[(])}") == false); +``` + +끝까지 닫히지 않는 여는 괄호는 균형이 잡혀 있지 않습니다 + +```c + try_catch(is_balanced("(") == false); +``` + +여는 괄호보다 먼저 나오는 닫는 괄호는 균형이 잡혀 있지 않습니다 + +```c + try_catch(is_balanced(")(") == false); +``` + +문자열 깊은 곳에서 교차된 쌍들은 균형이 잡혀 있지 않습니다 + +```c + try_catch(is_balanced("(([]{[}]))") == false); +``` + +끝에 남는 닫는 괄호는 균형이 잡혀 있지 않습니다 + +```c + try_catch(is_balanced("())") == false); +``` + +# --after-asserts-- + +```c + printf("Executed %d tests, with %d failures", _test_count, _test_failed_count); + return 0; +} +``` + +# --solutions-- + +```c +bool is_balanced(const char* text) { + size_t length = strlen(text); + char stack[length + 1]; + size_t top = 0; + + for (size_t i = 0; i < length; i++) { + char current = text[i]; + + if (current == '(' || current == '[' || current == '{') { + stack[top++] = current; + } else if (current == ')' || current == ']' || current == '}') { + if (top == 0) { + return false; + } + + char opening = stack[--top]; + if ((current == ')' && opening != '(') || + (current == ']' && opening != '[') || + (current == '}' && opening != '{')) { + return false; + } + } + } + + return top == 0; +} +``` diff --git a/ko/dart/challenges/data.json b/ko/dart/challenges/data.json index ae5115b71..803a6d1ef 100644 --- a/ko/dart/challenges/data.json +++ b/ko/dart/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "애너그램" + }, + "matching_brackets": { + "difficulty": 3, + "name": "괄호 짝 맞추기" } } diff --git a/ko/dart/challenges/matching_brackets.md b/ko/dart/challenges/matching_brackets.md new file mode 100644 index 000000000..d33395e8b --- /dev/null +++ b/ko/dart/challenges/matching_brackets.md @@ -0,0 +1,167 @@ +--- +language: dart +exerciseType: 1 +difficulty: 3 +title: 괄호 짝 맞추기 +--- + +# --description-- + +코드, 수식 또는 마크업을 담는 텍스트에는 괄호가 가득하며, 모든 여는 괄호에는 같은 종류의 닫는 괄호가 필요합니다. 문자열의 괄호들이 양파의 겹처럼 쌍을 이루고 중첩될 때 그 문자열은 균형이 잡혀 있다고 합니다: `{[()]}`는 균형이 잡혀 있지만, `{[(])}`는 그렇지 않습니다. 이는 그 안에 있는 둥근 괄호 쌍이 자신을 감싸고 있는 대괄호 쌍보다 먼저 닫히기 때문입니다. + +여기서는 세 쌍이 대상입니다: 둥근 괄호 `()`, 대괄호 `[]`, 그리고 중괄호 `{}`입니다. 문자열에 있는 다른 모든 문자는 무시합니다. 닫는 괄호는 아직 열려 있는 괄호 중 가장 최근에 열린 괄호를 닫아야 하며, 문자열이 끝날 때 열려 있는 괄호가 남아 있어서는 안 됩니다. + +# --instructions-- + +문자열을 받아 그 안의 모든 괄호가 서로 맞고 올바르게 중첩되어 있으면 `true`를, 그렇지 않으면 `false`를 반환하는 함수 `isBalanced`를 작성하세요. + +예시: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- 빈 문자열은 균형이 잡혀 있습니다. +- 괄호가 아닌 문자는 무시합니다. +- 닫는 괄호는 아직 열려 있는 괄호 중 가장 최근에 열린 괄호와 맞아야 합니다. +- 문자열이 끝날 때 열려 있는 괄호가 남아 있으면 안 됩니다. + +# --seed-- + +```dart +bool isBalanced(String text) { + +} +``` + +# --before-asserts-- + +```dart +import 'package:dart_runner/main.dart'; +import 'package:test/test.dart'; + +void main() { + group('MainTest -', () { +``` + +# --asserts-- + +빈 문자열은 균형이 잡혀 있습니다 + +```dart + test('test1', () { + expect(isBalanced(''), true, reason: '--err-t1--'); + }); +``` + +둥근 괄호 한 쌍은 균형이 잡혀 있습니다 + +```dart + test('test2', () { + expect(isBalanced('()'), true, reason: '--err-t2--'); + }); +``` + +세 종류의 쌍이 서로 중첩되어 있으면 균형이 잡혀 있습니다 + +```dart + test('test3', () { + expect(isBalanced('{[()]}'), true, reason: '--err-t3--'); + }); +``` + +다른 텍스트와 섞인 괄호도 여전히 균형이 잡혀 있습니다 + +```dart + test('test4', () { + expect(isBalanced('{what is (42)}[?]'), true, reason: '--err-t4--'); + }); +``` + +나란히 놓인 쌍들은 균형이 잡혀 있습니다 + +```dart + test('test5', () { + expect(isBalanced('()[]{}'), true, reason: '--err-t5--'); + }); +``` + +괄호가 전혀 없는 문자열은 균형이 잡혀 있습니다 + +```dart + test('test6', () { + expect(isBalanced('no brackets in here at all'), true, reason: '--err-t6--'); + }); +``` + +교차된 쌍은 균형이 잡혀 있지 않습니다 + +```dart + test('test7', () { + expect(isBalanced('{[(])}'), false, reason: '--err-t7--'); + }); +``` + +끝까지 닫히지 않는 여는 괄호는 균형이 잡혀 있지 않습니다 + +```dart + test('test8', () { + expect(isBalanced('('), false, reason: '--err-t8--'); + }); +``` + +여는 괄호보다 먼저 나오는 닫는 괄호는 균형이 잡혀 있지 않습니다 + +```dart + test('test9', () { + expect(isBalanced(')('), false, reason: '--err-t9--'); + }); +``` + +문자열 깊은 곳에서 교차된 쌍들은 균형이 잡혀 있지 않습니다 + +```dart + test('test10', () { + expect(isBalanced('(([]{[}]))'), false, reason: '--err-t10--'); + }); +``` + +끝에 남는 닫는 괄호는 균형이 잡혀 있지 않습니다 + +```dart + test('test11', () { + expect(isBalanced('())'), false, reason: '--err-t11--'); + }); +``` + +# --after-asserts-- + +```dart + }, timeout: Timeout(const Duration(seconds: 1))); +} +``` + +# --solutions-- + +```dart +bool isBalanced(String text) { + const pairs = {')': '(', ']': '[', '}': '{'}; + final stack = []; + + for (final char in text.split('')) { + if (char == '(' || char == '[' || char == '{') { + stack.add(char); + } else if (pairs.containsKey(char)) { + if (stack.isEmpty || stack.removeLast() != pairs[char]) { + return false; + } + } + } + + return stack.isEmpty; +} +``` diff --git a/ko/javascript/challenges/data.json b/ko/javascript/challenges/data.json index 248a06a11..c511a4767 100644 --- a/ko/javascript/challenges/data.json +++ b/ko/javascript/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "애너그램" + }, + "matching_brackets": { + "difficulty": 3, + "name": "괄호 짝 맞추기" } } diff --git a/ko/javascript/challenges/matching_brackets.md b/ko/javascript/challenges/matching_brackets.md new file mode 100644 index 000000000..3e3308b6d --- /dev/null +++ b/ko/javascript/challenges/matching_brackets.md @@ -0,0 +1,154 @@ +--- +language: javascript +exerciseType: 1 +difficulty: 3 +title: 괄호 짝 맞추기 +--- + +# --description-- + +코드, 수식 또는 마크업을 담는 텍스트에는 괄호가 가득하며, 모든 여는 괄호에는 같은 종류의 닫는 괄호가 필요합니다. 문자열의 괄호들이 양파의 겹처럼 쌍을 이루고 중첩될 때 그 문자열은 균형이 잡혀 있다고 합니다: `{[()]}`는 균형이 잡혀 있지만, `{[(])}`는 그렇지 않습니다. 이는 그 안에 있는 둥근 괄호 쌍이 자신을 감싸고 있는 대괄호 쌍보다 먼저 닫히기 때문입니다. + +여기서는 세 쌍이 대상입니다: 둥근 괄호 `()`, 대괄호 `[]`, 그리고 중괄호 `{}`입니다. 문자열에 있는 다른 모든 문자는 무시합니다. 닫는 괄호는 아직 열려 있는 괄호 중 가장 최근에 열린 괄호를 닫아야 하며, 문자열이 끝날 때 열려 있는 괄호가 남아 있어서는 안 됩니다. + +# --instructions-- + +문자열을 받아 그 안의 모든 괄호가 서로 맞고 올바르게 중첩되어 있으면 `true`를, 그렇지 않으면 `false`를 반환하는 함수 `isBalanced`를 작성하세요. + +예시: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- 빈 문자열은 균형이 잡혀 있습니다. +- 괄호가 아닌 문자는 무시합니다. +- 닫는 괄호는 아직 열려 있는 괄호 중 가장 최근에 열린 괄호와 맞아야 합니다. +- 문자열이 끝날 때 열려 있는 괄호가 남아 있으면 안 됩니다. + +# --before-seed-- + +```javascript +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +var assert = require('assert') +const tryCatch = (...args) => { + _testCount++ + try { assert(...args) } + catch (e) { + _testFailedCount++ + console.log(`Test Case '--err-t${_testCount}--' failed`); + } +}; +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```javascript +function isBalanced(text) { + +} +``` + +# --asserts-- + +빈 문자열은 균형이 잡혀 있습니다 + +```javascript +tryCatch(isBalanced("") === true); +``` + +둥근 괄호 한 쌍은 균형이 잡혀 있습니다 + +```javascript +tryCatch(isBalanced("()") === true); +``` + +세 종류의 쌍이 서로 중첩되어 있으면 균형이 잡혀 있습니다 + +```javascript +tryCatch(isBalanced("{[()]}") === true); +``` + +다른 텍스트와 섞인 괄호도 여전히 균형이 잡혀 있습니다 + +```javascript +tryCatch(isBalanced("{what is (42)}[?]") === true); +``` + +나란히 놓인 쌍들은 균형이 잡혀 있습니다 + +```javascript +tryCatch(isBalanced("()[]{}") === true); +``` + +괄호가 전혀 없는 문자열은 균형이 잡혀 있습니다 + +```javascript +tryCatch(isBalanced("no brackets in here at all") === true); +``` + +교차된 쌍은 균형이 잡혀 있지 않습니다 + +```javascript +tryCatch(isBalanced("{[(])}") === false); +``` + +끝까지 닫히지 않는 여는 괄호는 균형이 잡혀 있지 않습니다 + +```javascript +tryCatch(isBalanced("(") === false); +``` + +여는 괄호보다 먼저 나오는 닫는 괄호는 균형이 잡혀 있지 않습니다 + +```javascript +tryCatch(isBalanced(")(") === false); +``` + +문자열 깊은 곳에서 교차된 쌍들은 균형이 잡혀 있지 않습니다 + +```javascript +tryCatch(isBalanced("(([]{[}]))") === false); +``` + +끝에 남는 닫는 괄호는 균형이 잡혀 있지 않습니다 + +```javascript +tryCatch(isBalanced("())") === false); +``` + +# --after-asserts-- + +```javascript +// DO NOT EDIT FROM HERE +console.log(`Executed ${_testCount} tests, with ${_testFailedCount} failures`); +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```javascript +function isBalanced(text) { + const pairs = { ")": "(", "]": "[", "}": "{" }; + const stack = []; + + for (const char of text) { + if (char === "(" || char === "[" || char === "{") { + stack.push(char); + } else if (char in pairs) { + if (stack.pop() !== pairs[char]) { + return false; + } + } + } + + return stack.length === 0; +} +``` diff --git a/ko/kotlin/challenges/data.json b/ko/kotlin/challenges/data.json index f6692adad..55f120982 100644 --- a/ko/kotlin/challenges/data.json +++ b/ko/kotlin/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "애너그램" + }, + "matching_brackets": { + "difficulty": 3, + "name": "괄호 짝 맞추기" } } diff --git a/ko/kotlin/challenges/matching_brackets.md b/ko/kotlin/challenges/matching_brackets.md new file mode 100644 index 000000000..e837044eb --- /dev/null +++ b/ko/kotlin/challenges/matching_brackets.md @@ -0,0 +1,157 @@ +--- +language: kotlin +exerciseType: 1 +difficulty: 3 +title: 괄호 짝 맞추기 +--- + +# --description-- + +코드, 수식 또는 마크업을 담는 텍스트에는 괄호가 가득하며, 모든 여는 괄호에는 같은 종류의 닫는 괄호가 필요합니다. 문자열의 괄호들이 양파의 겹처럼 쌍을 이루고 중첩될 때 그 문자열은 균형이 잡혀 있다고 합니다: `{[()]}`는 균형이 잡혀 있지만, `{[(])}`는 그렇지 않습니다. 이는 그 안에 있는 둥근 괄호 쌍이 자신을 감싸고 있는 대괄호 쌍보다 먼저 닫히기 때문입니다. + +여기서는 세 쌍이 대상입니다: 둥근 괄호 `()`, 대괄호 `[]`, 그리고 중괄호 `{}`입니다. 문자열에 있는 다른 모든 문자는 무시합니다. 닫는 괄호는 아직 열려 있는 괄호 중 가장 최근에 열린 괄호를 닫아야 하며, 문자열이 끝날 때 열려 있는 괄호가 남아 있어서는 안 됩니다. + +# --instructions-- + +문자열을 받아 그 안의 모든 괄호가 서로 맞고 올바르게 중첩되어 있으면 `true`를, 그렇지 않으면 `false`를 반환하는 함수 `isBalanced`를 작성하세요. + +예시: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- 빈 문자열은 균형이 잡혀 있습니다. +- 괄호가 아닌 문자는 무시합니다. +- 닫는 괄호는 아직 열려 있는 괄호 중 가장 최근에 열린 괄호와 맞아야 합니다. +- 문자열이 끝날 때 열려 있는 괄호가 남아 있으면 안 됩니다. + +# --seed-- + +```kotlin +fun isBalanced(text: String): Boolean { + +} +``` + +# --before-seed-- + +```kotlin +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +fun tryCatch(assertion: Boolean) { + _testCount++ + try { + if (!assertion) throw Exception() + } + catch (e: Throwable) { + _testFailedCount++ + println("Test Case '--err-t$_testCount--' failed"); + } +}; +// DO NOT EDIT UNTIL HERE +fun main() { +``` + +# --asserts-- + +빈 문자열은 균형이 잡혀 있습니다 + +```kotlin + tryCatch(isBalanced("") == true) +``` + +둥근 괄호 한 쌍은 균형이 잡혀 있습니다 + +```kotlin + tryCatch(isBalanced("()") == true) +``` + +세 종류의 쌍이 서로 중첩되어 있으면 균형이 잡혀 있습니다 + +```kotlin + tryCatch(isBalanced("{[()]}") == true) +``` + +다른 텍스트와 섞인 괄호도 여전히 균형이 잡혀 있습니다 + +```kotlin + tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +나란히 놓인 쌍들은 균형이 잡혀 있습니다 + +```kotlin + tryCatch(isBalanced("()[]{}") == true) +``` + +괄호가 전혀 없는 문자열은 균형이 잡혀 있습니다 + +```kotlin + tryCatch(isBalanced("no brackets in here at all") == true) +``` + +교차된 쌍은 균형이 잡혀 있지 않습니다 + +```kotlin + tryCatch(isBalanced("{[(])}") == false) +``` + +끝까지 닫히지 않는 여는 괄호는 균형이 잡혀 있지 않습니다 + +```kotlin + tryCatch(isBalanced("(") == false) +``` + +여는 괄호보다 먼저 나오는 닫는 괄호는 균형이 잡혀 있지 않습니다 + +```kotlin + tryCatch(isBalanced(")(") == false) +``` + +문자열 깊은 곳에서 교차된 쌍들은 균형이 잡혀 있지 않습니다 + +```kotlin + tryCatch(isBalanced("(([]{[}]))") == false) +``` + +끝에 남는 닫는 괄호는 균형이 잡혀 있지 않습니다 + +```kotlin + tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```kotlin +// DO NOT EDIT FROM HERE + println("Executed $_testCount tests, with $_testFailedCount failures"); +} +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```kotlin +fun isBalanced(text: String): Boolean { + val pairs = mapOf(')' to '(', ']' to '[', '}' to '{') + val stack = ArrayDeque() + + for (char in text) { + if (char == '(' || char == '[' || char == '{') { + stack.addLast(char) + } else if (pairs.containsKey(char)) { + if (stack.isEmpty() || stack.removeLast() != pairs[char]) { + return false + } + } + } + + return stack.isEmpty() +} +``` diff --git a/ko/python/challenges/data.json b/ko/python/challenges/data.json index 248a06a11..c511a4767 100644 --- a/ko/python/challenges/data.json +++ b/ko/python/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "애너그램" + }, + "matching_brackets": { + "difficulty": 3, + "name": "괄호 짝 맞추기" } } diff --git a/ko/python/challenges/matching_brackets.md b/ko/python/challenges/matching_brackets.md new file mode 100644 index 000000000..4c6fdd38d --- /dev/null +++ b/ko/python/challenges/matching_brackets.md @@ -0,0 +1,149 @@ +--- +language: python +exerciseType: 1 +difficulty: 3 +title: 괄호 짝 맞추기 +--- + +# --description-- + +코드, 수식 또는 마크업을 담는 텍스트에는 괄호가 가득하며, 모든 여는 괄호에는 같은 종류의 닫는 괄호가 필요합니다. 문자열의 괄호들이 양파의 겹처럼 쌍을 이루고 중첩될 때 그 문자열은 균형이 잡혀 있다고 합니다: `{[()]}`는 균형이 잡혀 있지만, `{[(])}`는 그렇지 않습니다. 이는 그 안에 있는 둥근 괄호 쌍이 자신을 감싸고 있는 대괄호 쌍보다 먼저 닫히기 때문입니다. + +여기서는 세 쌍이 대상입니다: 둥근 괄호 `()`, 대괄호 `[]`, 그리고 중괄호 `{}`입니다. 문자열에 있는 다른 모든 문자는 무시합니다. 닫는 괄호는 아직 열려 있는 괄호 중 가장 최근에 열린 괄호를 닫아야 하며, 문자열이 끝날 때 열려 있는 괄호가 남아 있어서는 안 됩니다. + +# --instructions-- + +문자열을 받아 그 안의 모든 괄호가 서로 맞고 올바르게 중첩되어 있으면 `True`를, 그렇지 않으면 `False`를 반환하는 함수 `is_balanced`를 작성하세요. + +예시: +``` +is_balanced("") ➞ True +is_balanced("{[()]}") ➞ True +is_balanced("{what is (42)}[?]") ➞ True +is_balanced("{[(])}") ➞ False +is_balanced("(") ➞ False +is_balanced(")(") ➞ False +``` + +- 빈 문자열은 균형이 잡혀 있습니다. +- 괄호가 아닌 문자는 무시합니다. +- 닫는 괄호는 아직 열려 있는 괄호 중 가장 최근에 열린 괄호와 맞아야 합니다. +- 문자열이 끝날 때 열려 있는 괄호가 남아 있으면 안 됩니다. + +# --seed-- + +```python +def is_balanced(text): + pass +``` + +# --before-asserts-- + +```python +import unittest + +class CodigoTests(unittest.TestCase): +``` + +# --asserts-- + +빈 문자열은 균형이 잡혀 있습니다 + +```python + def test1(self): + self.assertEqual(is_balanced(""), True, "--err-t1--") +``` + +둥근 괄호 한 쌍은 균형이 잡혀 있습니다 + +```python + def test2(self): + self.assertEqual(is_balanced("()"), True, "--err-t2--") +``` + +세 종류의 쌍이 서로 중첩되어 있으면 균형이 잡혀 있습니다 + +```python + def test3(self): + self.assertEqual(is_balanced("{[()]}"), True, "--err-t3--") +``` + +다른 텍스트와 섞인 괄호도 여전히 균형이 잡혀 있습니다 + +```python + def test4(self): + self.assertEqual(is_balanced("{what is (42)}[?]"), True, "--err-t4--") +``` + +나란히 놓인 쌍들은 균형이 잡혀 있습니다 + +```python + def test5(self): + self.assertEqual(is_balanced("()[]{}"), True, "--err-t5--") +``` + +괄호가 전혀 없는 문자열은 균형이 잡혀 있습니다 + +```python + def test6(self): + self.assertEqual(is_balanced("no brackets in here at all"), True, "--err-t6--") +``` + +교차된 쌍은 균형이 잡혀 있지 않습니다 + +```python + def test7(self): + self.assertEqual(is_balanced("{[(])}"), False, "--err-t7--") +``` + +끝까지 닫히지 않는 여는 괄호는 균형이 잡혀 있지 않습니다 + +```python + def test8(self): + self.assertEqual(is_balanced("("), False, "--err-t8--") +``` + +여는 괄호보다 먼저 나오는 닫는 괄호는 균형이 잡혀 있지 않습니다 + +```python + def test9(self): + self.assertEqual(is_balanced(")("), False, "--err-t9--") +``` + +문자열 깊은 곳에서 교차된 쌍들은 균형이 잡혀 있지 않습니다 + +```python + def test10(self): + self.assertEqual(is_balanced("(([]{[}]))"), False, "--err-t10--") +``` + +끝에 남는 닫는 괄호는 균형이 잡혀 있지 않습니다 + +```python + def test11(self): + self.assertEqual(is_balanced("())"), False, "--err-t11--") +``` + +# --after-asserts-- + +```python +if __name__ == "__main__": + unittest.main() +``` + +# --solutions-- + +```python +def is_balanced(text): + pairs = {")": "(", "]": "[", "}": "{"} + stack = [] + + for char in text: + if char in "([{": + stack.append(char) + elif char in pairs: + if not stack or stack.pop() != pairs[char]: + return False + + return not stack +``` diff --git a/ko/swift/challenges/data.json b/ko/swift/challenges/data.json index 54a16b27b..8c2e011cd 100644 --- a/ko/swift/challenges/data.json +++ b/ko/swift/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "애너그램" + }, + "matching_brackets": { + "difficulty": 3, + "name": "괄호 짝 맞추기" } } diff --git a/ko/swift/challenges/matching_brackets.md b/ko/swift/challenges/matching_brackets.md new file mode 100644 index 000000000..6e11cb052 --- /dev/null +++ b/ko/swift/challenges/matching_brackets.md @@ -0,0 +1,152 @@ +--- +language: swift +exerciseType: 1 +difficulty: 3 +title: 괄호 짝 맞추기 +--- + +# --description-- + +코드, 수식 또는 마크업을 담는 텍스트에는 괄호가 가득하며, 모든 여는 괄호에는 같은 종류의 닫는 괄호가 필요합니다. 문자열의 괄호들이 양파의 겹처럼 쌍을 이루고 중첩될 때 그 문자열은 균형이 잡혀 있다고 합니다: `{[()]}`는 균형이 잡혀 있지만, `{[(])}`는 그렇지 않습니다. 이는 그 안에 있는 둥근 괄호 쌍이 자신을 감싸고 있는 대괄호 쌍보다 먼저 닫히기 때문입니다. + +여기서는 세 쌍이 대상입니다: 둥근 괄호 `()`, 대괄호 `[]`, 그리고 중괄호 `{}`입니다. 문자열에 있는 다른 모든 문자는 무시합니다. 닫는 괄호는 아직 열려 있는 괄호 중 가장 최근에 열린 괄호를 닫아야 하며, 문자열이 끝날 때 열려 있는 괄호가 남아 있어서는 안 됩니다. + +# --instructions-- + +문자열을 받아 그 안의 모든 괄호가 서로 맞고 올바르게 중첩되어 있으면 `true`를, 그렇지 않으면 `false`를 반환하는 함수 `isBalanced`를 작성하세요. + +예시: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- 빈 문자열은 균형이 잡혀 있습니다. +- 괄호가 아닌 문자는 무시합니다. +- 닫는 괄호는 아직 열려 있는 괄호 중 가장 최근에 열린 괄호와 맞아야 합니다. +- 문자열이 끝날 때 열려 있는 괄호가 남아 있으면 안 됩니다. + +# --before-seed-- + +```swift +// DO NOT EDIT FROM HERE +import Foundation + +var _testCount = 0 +var _testFailedCount = 0 +func tryCatch(_ assertion: Bool) { + _testCount += 1 + if !assertion { + _testFailedCount += 1 + print("Test Case '--err-t\(_testCount)--' failed") + } +} +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```swift +func isBalanced(_ text: String) -> Bool { + +} +``` + +# --asserts-- + +빈 문자열은 균형이 잡혀 있습니다 + +```swift +tryCatch(isBalanced("") == true) +``` + +둥근 괄호 한 쌍은 균형이 잡혀 있습니다 + +```swift +tryCatch(isBalanced("()") == true) +``` + +세 종류의 쌍이 서로 중첩되어 있으면 균형이 잡혀 있습니다 + +```swift +tryCatch(isBalanced("{[()]}") == true) +``` + +다른 텍스트와 섞인 괄호도 여전히 균형이 잡혀 있습니다 + +```swift +tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +나란히 놓인 쌍들은 균형이 잡혀 있습니다 + +```swift +tryCatch(isBalanced("()[]{}") == true) +``` + +괄호가 전혀 없는 문자열은 균형이 잡혀 있습니다 + +```swift +tryCatch(isBalanced("no brackets in here at all") == true) +``` + +교차된 쌍은 균형이 잡혀 있지 않습니다 + +```swift +tryCatch(isBalanced("{[(])}") == false) +``` + +끝까지 닫히지 않는 여는 괄호는 균형이 잡혀 있지 않습니다 + +```swift +tryCatch(isBalanced("(") == false) +``` + +여는 괄호보다 먼저 나오는 닫는 괄호는 균형이 잡혀 있지 않습니다 + +```swift +tryCatch(isBalanced(")(") == false) +``` + +문자열 깊은 곳에서 교차된 쌍들은 균형이 잡혀 있지 않습니다 + +```swift +tryCatch(isBalanced("(([]{[}]))") == false) +``` + +끝에 남는 닫는 괄호는 균형이 잡혀 있지 않습니다 + +```swift +tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```swift +print("Executed \(_testCount) tests, with \(_testFailedCount) failures") +``` + +# --solutions-- + +```swift +func isBalanced(_ text: String) -> Bool { + let pairs: [Character: Character] = [")": "(", "]": "[", "}": "{"] + var stack: [Character] = [] + + for char in text { + if char == "(" || char == "[" || char == "{" { + stack.append(char) + } else if let opening = pairs[char] { + if stack.popLast() != opening { + return false + } + } + } + + return stack.isEmpty +} +``` diff --git a/pl/c/challenges/data.json b/pl/c/challenges/data.json index 54fadd0b4..943ab7c0f 100644 --- a/pl/c/challenges/data.json +++ b/pl/c/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagram" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Pasujące nawiasy" } -} +} \ No newline at end of file diff --git a/pl/c/challenges/matching_brackets.md b/pl/c/challenges/matching_brackets.md new file mode 100644 index 000000000..30c3d591b --- /dev/null +++ b/pl/c/challenges/matching_brackets.md @@ -0,0 +1,280 @@ +--- +language: c +exerciseType: 1 +difficulty: 3 +title: Pasujące nawiasy +--- + +# --description-- + +Tekst zawierający kod, zapis matematyczny czy znaczniki jest pełen nawiasów, a każdy nawias otwierający potrzebuje nawiasu zamykającego tego samego rodzaju. Ciąg znaków jest zrównoważony, gdy jego nawiasy tworzą pary i zagnieżdżają się jak warstwy cebuli: `{[()]}` jest zrównoważony, natomiast `{[(])}` już nie, ponieważ para okrągła zostaje zamknięta przed parą kwadratową, wewnątrz której się znajduje. + +Liczą się tutaj trzy pary: okrągła `()`, kwadratowa `[]` i klamrowa `{}`. Każdy inny znak w ciągu jest ignorowany. Nawias zamykający musi zamykać ostatnio otwarty nawias, który wciąż jest otwarty, a gdy ciąg się kończy, żaden nawias nie może pozostać otwarty. + +# --instructions-- + +Napisz funkcję `is_balanced`, która przyjmuje ciąg znaków i zwraca `true`, gdy wszystkie zawarte w niej nawiasy są sparowane i poprawnie zagnieżdżone, a w przeciwnym razie zwraca `false`. + +Przykłady: +``` +is_balanced("") ➞ true +is_balanced("{[()]}") ➞ true +is_balanced("{what is (42)}[?]") ➞ true +is_balanced("{[(])}") ➞ false +is_balanced("(") ➞ false +is_balanced(")(") ➞ false +``` + +- Pusty ciąg znaków jest zrównoważony. +- Znaki, które nie są nawiasami, są ignorowane. +- Nawias zamykający musi pasować do ostatnio otwartego nawiasu, który wciąż jest otwarty. +- Żaden nawias nie może pozostać otwarty, gdy ciąg znaków się kończy. + +# --before-seed-- + +```c +// DO NOT EDIT FROM HERE +#include +#include +#include + +#ifndef _CEXCEPTION_H +#define _CEXCEPTION_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +//This is the value to assign when there isn't an exception +#ifndef CEXCEPTION_NONE +#define CEXCEPTION_NONE (0x5A5A5A5A) +#endif + +//This is number of exception stacks to keep track of (one per task) +#ifndef CEXCEPTION_NUM_ID +#define CEXCEPTION_NUM_ID (1) //there is only the one stack by default +#endif + +//This is the method of getting the current exception stack index (0 if only one stack) +#ifndef CEXCEPTION_GET_ID +#define CEXCEPTION_GET_ID (0) //use the first index always because there is only one anyway +#endif + +//The type to use to store the exception values. +#ifndef CEXCEPTION_T +#define CEXCEPTION_T unsigned int +#endif + +//This is an optional special handler for when there is no global Catch +#ifndef CEXCEPTION_NO_CATCH_HANDLER +#define CEXCEPTION_NO_CATCH_HANDLER(id) +#endif + +//These hooks allow you to inject custom code into places, particularly useful for saving and restoring additional state +#ifndef CEXCEPTION_HOOK_START_TRY +#define CEXCEPTION_HOOK_START_TRY +#endif +#ifndef CEXCEPTION_HOOK_HAPPY_TRY +#define CEXCEPTION_HOOK_HAPPY_TRY +#endif +#ifndef CEXCEPTION_HOOK_AFTER_TRY +#define CEXCEPTION_HOOK_AFTER_TRY +#endif +#ifndef CEXCEPTION_HOOK_START_CATCH +#define CEXCEPTION_HOOK_START_CATCH +#endif + +//exception frame structures +typedef struct { + jmp_buf* pFrame; + CEXCEPTION_T volatile Exception; +} CEXCEPTION_FRAME_T; + +//actual root frame storage (only one if single-tasking) +extern volatile CEXCEPTION_FRAME_T CExceptionFrames[]; + +//Try +#define Try \ + { \ + jmp_buf *PrevFrame, NewFrame; \ + unsigned int MY_ID = CEXCEPTION_GET_ID; \ + PrevFrame = CExceptionFrames[MY_ID].pFrame; \ + CExceptionFrames[MY_ID].pFrame = (jmp_buf*)(&NewFrame); \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_START_TRY; \ + if (setjmp(NewFrame) == 0) { \ + if (1) + +//Catch +#define Catch(e) \ + else { } \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_HAPPY_TRY; \ + } \ + else \ + { \ + e = CExceptionFrames[MY_ID].Exception; \ + (void)e; \ + CEXCEPTION_HOOK_START_CATCH; \ + } \ + CExceptionFrames[MY_ID].pFrame = PrevFrame; \ + CEXCEPTION_HOOK_AFTER_TRY; \ + } \ + if (CExceptionFrames[CEXCEPTION_GET_ID].Exception != CEXCEPTION_NONE) + +#endif + +volatile CEXCEPTION_FRAME_T CExceptionFrames[CEXCEPTION_NUM_ID] = {{ 0 }}; + +void Throw(CEXCEPTION_T ExceptionID) +{ + unsigned int MY_ID = CEXCEPTION_GET_ID; + CExceptionFrames[MY_ID].Exception = ExceptionID; + if (CExceptionFrames[MY_ID].pFrame) + { + longjmp(*CExceptionFrames[MY_ID].pFrame, 1); + } + CEXCEPTION_NO_CATCH_HANDLER(ExceptionID); +} + +CEXCEPTION_T e; +int _test_failed_count = 0; +int _test_count = 0; + +void try_catch(bool assertion) { + _test_count++; + Try { + if (!assertion) { + Throw(_test_count); + } + } Catch (e) { + _test_failed_count += 1; + printf("Test Case '--err-t%i--' failed\n", e); + } +} +// DO NOT EDIT UNTIL HERE +#include +#include +``` + +# --seed-- + +```c +bool is_balanced(const char* text) { + +} +``` + +# --before-asserts-- + +```c +int main() { +``` + +# --asserts-- + +Pusty ciąg znaków jest zrównoważony + +```c + try_catch(is_balanced("") == true); +``` + +Pojedyncza para nawiasów okrągłych jest zrównoważona + +```c + try_catch(is_balanced("()") == true); +``` + +Trzy rodzaje par zagnieżdżone jeden w drugim są zrównoważone + +```c + try_catch(is_balanced("{[()]}") == true); +``` + +Nawiasy przeplatane innym tekstem nadal są zrównoważone + +```c + try_catch(is_balanced("{what is (42)}[?]") == true); +``` + +Pary ustawione obok siebie są zrównoważone + +```c + try_catch(is_balanced("()[]{}") == true); +``` + +Ciąg znaków bez żadnych nawiasów jest zrównoważony + +```c + try_catch(is_balanced("no brackets in here at all") == true); +``` + +Skrzyżowana para nawiasów nie jest zrównoważona + +```c + try_catch(is_balanced("{[(])}") == false); +``` + +Nawias otwierający, który nigdy nie zostaje zamknięty, nie jest zrównoważony + +```c + try_catch(is_balanced("(") == false); +``` + +Nawias zamykający pojawiający się przed jakimkolwiek nawiasem otwierającym nie jest zrównoważony + +```c + try_catch(is_balanced(")(") == false); +``` + +Skrzyżowane pary głębiej w ciągu znaków nie są zrównoważone + +```c + try_catch(is_balanced("(([]{[}]))") == false); +``` + +Nawias zamykający pozostawiony na końcu nie jest zrównoważony + +```c + try_catch(is_balanced("())") == false); +``` + +# --after-asserts-- + +```c + printf("Executed %d tests, with %d failures", _test_count, _test_failed_count); + return 0; +} +``` + +# --solutions-- + +```c +bool is_balanced(const char* text) { + size_t length = strlen(text); + char stack[length + 1]; + size_t top = 0; + + for (size_t i = 0; i < length; i++) { + char current = text[i]; + + if (current == '(' || current == '[' || current == '{') { + stack[top++] = current; + } else if (current == ')' || current == ']' || current == '}') { + if (top == 0) { + return false; + } + + char opening = stack[--top]; + if ((current == ')' && opening != '(') || + (current == ']' && opening != '[') || + (current == '}' && opening != '{')) { + return false; + } + } + } + + return top == 0; +} +``` diff --git a/pl/dart/challenges/data.json b/pl/dart/challenges/data.json index d8ba72e52..222e24e4c 100644 --- a/pl/dart/challenges/data.json +++ b/pl/dart/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagram" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Pasujące nawiasy" } -} +} \ No newline at end of file diff --git a/pl/dart/challenges/matching_brackets.md b/pl/dart/challenges/matching_brackets.md new file mode 100644 index 000000000..691868777 --- /dev/null +++ b/pl/dart/challenges/matching_brackets.md @@ -0,0 +1,167 @@ +--- +language: dart +exerciseType: 1 +difficulty: 3 +title: Pasujące nawiasy +--- + +# --description-- + +Tekst zawierający kod, zapis matematyczny czy znaczniki jest pełen nawiasów, a każdy nawias otwierający potrzebuje nawiasu zamykającego tego samego rodzaju. Ciąg znaków jest zrównoważony, gdy jego nawiasy tworzą pary i zagnieżdżają się jak warstwy cebuli: `{[()]}` jest zrównoważony, natomiast `{[(])}` już nie, ponieważ para okrągła zostaje zamknięta przed parą kwadratową, wewnątrz której się znajduje. + +Liczą się tutaj trzy pary: okrągła `()`, kwadratowa `[]` i klamrowa `{}`. Każdy inny znak w ciągu jest ignorowany. Nawias zamykający musi zamykać ostatnio otwarty nawias, który wciąż jest otwarty, a gdy ciąg się kończy, żaden nawias nie może pozostać otwarty. + +# --instructions-- + +Napisz funkcję `isBalanced`, która przyjmuje ciąg znaków i zwraca `true`, gdy wszystkie zawarte w niej nawiasy są sparowane i poprawnie zagnieżdżone, a w przeciwnym razie zwraca `false`. + +Przykłady: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Pusty ciąg znaków jest zrównoważony. +- Znaki, które nie są nawiasami, są ignorowane. +- Nawias zamykający musi pasować do ostatnio otwartego nawiasu, który wciąż jest otwarty. +- Żaden nawias nie może pozostać otwarty, gdy ciąg znaków się kończy. + +# --seed-- + +```dart +bool isBalanced(String text) { + +} +``` + +# --before-asserts-- + +```dart +import 'package:dart_runner/main.dart'; +import 'package:test/test.dart'; + +void main() { + group('MainTest -', () { +``` + +# --asserts-- + +Pusty ciąg znaków jest zrównoważony + +```dart + test('test1', () { + expect(isBalanced(''), true, reason: '--err-t1--'); + }); +``` + +Pojedyncza para nawiasów okrągłych jest zrównoważona + +```dart + test('test2', () { + expect(isBalanced('()'), true, reason: '--err-t2--'); + }); +``` + +Trzy rodzaje par zagnieżdżone jeden w drugim są zrównoważone + +```dart + test('test3', () { + expect(isBalanced('{[()]}'), true, reason: '--err-t3--'); + }); +``` + +Nawiasy przeplatane innym tekstem nadal są zrównoważone + +```dart + test('test4', () { + expect(isBalanced('{what is (42)}[?]'), true, reason: '--err-t4--'); + }); +``` + +Pary ustawione obok siebie są zrównoważone + +```dart + test('test5', () { + expect(isBalanced('()[]{}'), true, reason: '--err-t5--'); + }); +``` + +Ciąg znaków bez żadnych nawiasów jest zrównoważony + +```dart + test('test6', () { + expect(isBalanced('no brackets in here at all'), true, reason: '--err-t6--'); + }); +``` + +Skrzyżowana para nawiasów nie jest zrównoważona + +```dart + test('test7', () { + expect(isBalanced('{[(])}'), false, reason: '--err-t7--'); + }); +``` + +Nawias otwierający, który nigdy nie zostaje zamknięty, nie jest zrównoważony + +```dart + test('test8', () { + expect(isBalanced('('), false, reason: '--err-t8--'); + }); +``` + +Nawias zamykający pojawiający się przed jakimkolwiek nawiasem otwierającym nie jest zrównoważony + +```dart + test('test9', () { + expect(isBalanced(')('), false, reason: '--err-t9--'); + }); +``` + +Skrzyżowane pary głębiej w ciągu znaków nie są zrównoważone + +```dart + test('test10', () { + expect(isBalanced('(([]{[}]))'), false, reason: '--err-t10--'); + }); +``` + +Nawias zamykający pozostawiony na końcu nie jest zrównoważony + +```dart + test('test11', () { + expect(isBalanced('())'), false, reason: '--err-t11--'); + }); +``` + +# --after-asserts-- + +```dart + }, timeout: Timeout(const Duration(seconds: 1))); +} +``` + +# --solutions-- + +```dart +bool isBalanced(String text) { + const pairs = {')': '(', ']': '[', '}': '{'}; + final stack = []; + + for (final char in text.split('')) { + if (char == '(' || char == '[' || char == '{') { + stack.add(char); + } else if (pairs.containsKey(char)) { + if (stack.isEmpty || stack.removeLast() != pairs[char]) { + return false; + } + } + } + + return stack.isEmpty; +} +``` diff --git a/pl/javascript/challenges/data.json b/pl/javascript/challenges/data.json index 59494a708..bd151fdf8 100644 --- a/pl/javascript/challenges/data.json +++ b/pl/javascript/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagram" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Pasujące nawiasy" } -} +} \ No newline at end of file diff --git a/pl/javascript/challenges/matching_brackets.md b/pl/javascript/challenges/matching_brackets.md new file mode 100644 index 000000000..dd78c6534 --- /dev/null +++ b/pl/javascript/challenges/matching_brackets.md @@ -0,0 +1,154 @@ +--- +language: javascript +exerciseType: 1 +difficulty: 3 +title: Pasujące nawiasy +--- + +# --description-- + +Tekst zawierający kod, zapis matematyczny czy znaczniki jest pełen nawiasów, a każdy nawias otwierający potrzebuje nawiasu zamykającego tego samego rodzaju. Ciąg znaków jest zrównoważony, gdy jego nawiasy tworzą pary i zagnieżdżają się jak warstwy cebuli: `{[()]}` jest zrównoważony, natomiast `{[(])}` już nie, ponieważ para okrągła zostaje zamknięta przed parą kwadratową, wewnątrz której się znajduje. + +Liczą się tutaj trzy pary: okrągła `()`, kwadratowa `[]` i klamrowa `{}`. Każdy inny znak w ciągu jest ignorowany. Nawias zamykający musi zamykać ostatnio otwarty nawias, który wciąż jest otwarty, a gdy ciąg się kończy, żaden nawias nie może pozostać otwarty. + +# --instructions-- + +Napisz funkcję `isBalanced`, która przyjmuje ciąg znaków i zwraca `true`, gdy wszystkie zawarte w niej nawiasy są sparowane i poprawnie zagnieżdżone, a w przeciwnym razie zwraca `false`. + +Przykłady: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Pusty ciąg znaków jest zrównoważony. +- Znaki, które nie są nawiasami, są ignorowane. +- Nawias zamykający musi pasować do ostatnio otwartego nawiasu, który wciąż jest otwarty. +- Żaden nawias nie może pozostać otwarty, gdy ciąg znaków się kończy. + +# --before-seed-- + +```javascript +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +var assert = require('assert') +const tryCatch = (...args) => { + _testCount++ + try { assert(...args) } + catch (e) { + _testFailedCount++ + console.log(`Test Case '--err-t${_testCount}--' failed`); + } +}; +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```javascript +function isBalanced(text) { + +} +``` + +# --asserts-- + +Pusty ciąg znaków jest zrównoważony + +```javascript +tryCatch(isBalanced("") === true); +``` + +Pojedyncza para nawiasów okrągłych jest zrównoważona + +```javascript +tryCatch(isBalanced("()") === true); +``` + +Trzy rodzaje par zagnieżdżone jeden w drugim są zrównoważone + +```javascript +tryCatch(isBalanced("{[()]}") === true); +``` + +Nawiasy przeplatane innym tekstem nadal są zrównoważone + +```javascript +tryCatch(isBalanced("{what is (42)}[?]") === true); +``` + +Pary ustawione obok siebie są zrównoważone + +```javascript +tryCatch(isBalanced("()[]{}") === true); +``` + +Ciąg znaków bez żadnych nawiasów jest zrównoważony + +```javascript +tryCatch(isBalanced("no brackets in here at all") === true); +``` + +Skrzyżowana para nawiasów nie jest zrównoważona + +```javascript +tryCatch(isBalanced("{[(])}") === false); +``` + +Nawias otwierający, który nigdy nie zostaje zamknięty, nie jest zrównoważony + +```javascript +tryCatch(isBalanced("(") === false); +``` + +Nawias zamykający pojawiający się przed jakimkolwiek nawiasem otwierającym nie jest zrównoważony + +```javascript +tryCatch(isBalanced(")(") === false); +``` + +Skrzyżowane pary głębiej w ciągu znaków nie są zrównoważone + +```javascript +tryCatch(isBalanced("(([]{[}]))") === false); +``` + +Nawias zamykający pozostawiony na końcu nie jest zrównoważony + +```javascript +tryCatch(isBalanced("())") === false); +``` + +# --after-asserts-- + +```javascript +// DO NOT EDIT FROM HERE +console.log(`Executed ${_testCount} tests, with ${_testFailedCount} failures`); +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```javascript +function isBalanced(text) { + const pairs = { ")": "(", "]": "[", "}": "{" }; + const stack = []; + + for (const char of text) { + if (char === "(" || char === "[" || char === "{") { + stack.push(char); + } else if (char in pairs) { + if (stack.pop() !== pairs[char]) { + return false; + } + } + } + + return stack.length === 0; +} +``` diff --git a/pl/kotlin/challenges/data.json b/pl/kotlin/challenges/data.json index 6dc2799b2..6f9653248 100644 --- a/pl/kotlin/challenges/data.json +++ b/pl/kotlin/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagram" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Pasujące nawiasy" } -} +} \ No newline at end of file diff --git a/pl/kotlin/challenges/matching_brackets.md b/pl/kotlin/challenges/matching_brackets.md new file mode 100644 index 000000000..75a54bcb5 --- /dev/null +++ b/pl/kotlin/challenges/matching_brackets.md @@ -0,0 +1,157 @@ +--- +language: kotlin +exerciseType: 1 +difficulty: 3 +title: Pasujące nawiasy +--- + +# --description-- + +Tekst zawierający kod, zapis matematyczny czy znaczniki jest pełen nawiasów, a każdy nawias otwierający potrzebuje nawiasu zamykającego tego samego rodzaju. Ciąg znaków jest zrównoważony, gdy jego nawiasy tworzą pary i zagnieżdżają się jak warstwy cebuli: `{[()]}` jest zrównoważony, natomiast `{[(])}` już nie, ponieważ para okrągła zostaje zamknięta przed parą kwadratową, wewnątrz której się znajduje. + +Liczą się tutaj trzy pary: okrągła `()`, kwadratowa `[]` i klamrowa `{}`. Każdy inny znak w ciągu jest ignorowany. Nawias zamykający musi zamykać ostatnio otwarty nawias, który wciąż jest otwarty, a gdy ciąg się kończy, żaden nawias nie może pozostać otwarty. + +# --instructions-- + +Napisz funkcję `isBalanced`, która przyjmuje ciąg znaków i zwraca `true`, gdy wszystkie zawarte w niej nawiasy są sparowane i poprawnie zagnieżdżone, a w przeciwnym razie zwraca `false`. + +Przykłady: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Pusty ciąg znaków jest zrównoważony. +- Znaki, które nie są nawiasami, są ignorowane. +- Nawias zamykający musi pasować do ostatnio otwartego nawiasu, który wciąż jest otwarty. +- Żaden nawias nie może pozostać otwarty, gdy ciąg znaków się kończy. + +# --seed-- + +```kotlin +fun isBalanced(text: String): Boolean { + +} +``` + +# --before-seed-- + +```kotlin +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +fun tryCatch(assertion: Boolean) { + _testCount++ + try { + if (!assertion) throw Exception() + } + catch (e: Throwable) { + _testFailedCount++ + println("Test Case '--err-t$_testCount--' failed"); + } +}; +// DO NOT EDIT UNTIL HERE +fun main() { +``` + +# --asserts-- + +Pusty ciąg znaków jest zrównoważony + +```kotlin + tryCatch(isBalanced("") == true) +``` + +Pojedyncza para nawiasów okrągłych jest zrównoważona + +```kotlin + tryCatch(isBalanced("()") == true) +``` + +Trzy rodzaje par zagnieżdżone jeden w drugim są zrównoważone + +```kotlin + tryCatch(isBalanced("{[()]}") == true) +``` + +Nawiasy przeplatane innym tekstem nadal są zrównoważone + +```kotlin + tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +Pary ustawione obok siebie są zrównoważone + +```kotlin + tryCatch(isBalanced("()[]{}") == true) +``` + +Ciąg znaków bez żadnych nawiasów jest zrównoważony + +```kotlin + tryCatch(isBalanced("no brackets in here at all") == true) +``` + +Skrzyżowana para nawiasów nie jest zrównoważona + +```kotlin + tryCatch(isBalanced("{[(])}") == false) +``` + +Nawias otwierający, który nigdy nie zostaje zamknięty, nie jest zrównoważony + +```kotlin + tryCatch(isBalanced("(") == false) +``` + +Nawias zamykający pojawiający się przed jakimkolwiek nawiasem otwierającym nie jest zrównoważony + +```kotlin + tryCatch(isBalanced(")(") == false) +``` + +Skrzyżowane pary głębiej w ciągu znaków nie są zrównoważone + +```kotlin + tryCatch(isBalanced("(([]{[}]))") == false) +``` + +Nawias zamykający pozostawiony na końcu nie jest zrównoważony + +```kotlin + tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```kotlin +// DO NOT EDIT FROM HERE + println("Executed $_testCount tests, with $_testFailedCount failures"); +} +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```kotlin +fun isBalanced(text: String): Boolean { + val pairs = mapOf(')' to '(', ']' to '[', '}' to '{') + val stack = ArrayDeque() + + for (char in text) { + if (char == '(' || char == '[' || char == '{') { + stack.addLast(char) + } else if (pairs.containsKey(char)) { + if (stack.isEmpty() || stack.removeLast() != pairs[char]) { + return false + } + } + } + + return stack.isEmpty() +} +``` diff --git a/pl/python/challenges/data.json b/pl/python/challenges/data.json index 7dbdb8cca..3905a1caf 100644 --- a/pl/python/challenges/data.json +++ b/pl/python/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagram" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Pasujące nawiasy" } -} +} \ No newline at end of file diff --git a/pl/python/challenges/matching_brackets.md b/pl/python/challenges/matching_brackets.md new file mode 100644 index 000000000..65dba0213 --- /dev/null +++ b/pl/python/challenges/matching_brackets.md @@ -0,0 +1,149 @@ +--- +language: python +exerciseType: 1 +difficulty: 3 +title: Pasujące nawiasy +--- + +# --description-- + +Tekst zawierający kod, zapis matematyczny czy znaczniki jest pełen nawiasów, a każdy nawias otwierający potrzebuje nawiasu zamykającego tego samego rodzaju. Ciąg znaków jest zrównoważony, gdy jego nawiasy tworzą pary i zagnieżdżają się jak warstwy cebuli: `{[()]}` jest zrównoważony, natomiast `{[(])}` już nie, ponieważ para okrągła zostaje zamknięta przed parą kwadratową, wewnątrz której się znajduje. + +Liczą się tutaj trzy pary: okrągła `()`, kwadratowa `[]` i klamrowa `{}`. Każdy inny znak w ciągu jest ignorowany. Nawias zamykający musi zamykać ostatnio otwarty nawias, który wciąż jest otwarty, a gdy ciąg się kończy, żaden nawias nie może pozostać otwarty. + +# --instructions-- + +Napisz funkcję `is_balanced`, która przyjmuje ciąg znaków i zwraca `True`, gdy wszystkie zawarte w niej nawiasy są sparowane i poprawnie zagnieżdżone, a w przeciwnym razie zwraca `False`. + +Przykłady: +``` +is_balanced("") ➞ True +is_balanced("{[()]}") ➞ True +is_balanced("{what is (42)}[?]") ➞ True +is_balanced("{[(])}") ➞ False +is_balanced("(") ➞ False +is_balanced(")(") ➞ False +``` + +- Pusty ciąg znaków jest zrównoważony. +- Znaki, które nie są nawiasami, są ignorowane. +- Nawias zamykający musi pasować do ostatnio otwartego nawiasu, który wciąż jest otwarty. +- Żaden nawias nie może pozostać otwarty, gdy ciąg znaków się kończy. + +# --seed-- + +```python +def is_balanced(text): + pass +``` + +# --before-asserts-- + +```python +import unittest + +class CodigoTests(unittest.TestCase): +``` + +# --asserts-- + +Pusty ciąg znaków jest zrównoważony + +```python + def test1(self): + self.assertEqual(is_balanced(""), True, "--err-t1--") +``` + +Pojedyncza para nawiasów okrągłych jest zrównoważona + +```python + def test2(self): + self.assertEqual(is_balanced("()"), True, "--err-t2--") +``` + +Trzy rodzaje par zagnieżdżone jeden w drugim są zrównoważone + +```python + def test3(self): + self.assertEqual(is_balanced("{[()]}"), True, "--err-t3--") +``` + +Nawiasy przeplatane innym tekstem nadal są zrównoważone + +```python + def test4(self): + self.assertEqual(is_balanced("{what is (42)}[?]"), True, "--err-t4--") +``` + +Pary ustawione obok siebie są zrównoważone + +```python + def test5(self): + self.assertEqual(is_balanced("()[]{}"), True, "--err-t5--") +``` + +Ciąg znaków bez żadnych nawiasów jest zrównoważony + +```python + def test6(self): + self.assertEqual(is_balanced("no brackets in here at all"), True, "--err-t6--") +``` + +Skrzyżowana para nawiasów nie jest zrównoważona + +```python + def test7(self): + self.assertEqual(is_balanced("{[(])}"), False, "--err-t7--") +``` + +Nawias otwierający, który nigdy nie zostaje zamknięty, nie jest zrównoważony + +```python + def test8(self): + self.assertEqual(is_balanced("("), False, "--err-t8--") +``` + +Nawias zamykający pojawiający się przed jakimkolwiek nawiasem otwierającym nie jest zrównoważony + +```python + def test9(self): + self.assertEqual(is_balanced(")("), False, "--err-t9--") +``` + +Skrzyżowane pary głębiej w ciągu znaków nie są zrównoważone + +```python + def test10(self): + self.assertEqual(is_balanced("(([]{[}]))"), False, "--err-t10--") +``` + +Nawias zamykający pozostawiony na końcu nie jest zrównoważony + +```python + def test11(self): + self.assertEqual(is_balanced("())"), False, "--err-t11--") +``` + +# --after-asserts-- + +```python +if __name__ == "__main__": + unittest.main() +``` + +# --solutions-- + +```python +def is_balanced(text): + pairs = {")": "(", "]": "[", "}": "{"} + stack = [] + + for char in text: + if char in "([{": + stack.append(char) + elif char in pairs: + if not stack or stack.pop() != pairs[char]: + return False + + return not stack +``` diff --git a/pl/swift/challenges/data.json b/pl/swift/challenges/data.json index 909c960a9..35cfda3d7 100644 --- a/pl/swift/challenges/data.json +++ b/pl/swift/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagram" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Pasujące nawiasy" } -} +} \ No newline at end of file diff --git a/pl/swift/challenges/matching_brackets.md b/pl/swift/challenges/matching_brackets.md new file mode 100644 index 000000000..330fa713f --- /dev/null +++ b/pl/swift/challenges/matching_brackets.md @@ -0,0 +1,152 @@ +--- +language: swift +exerciseType: 1 +difficulty: 3 +title: Pasujące nawiasy +--- + +# --description-- + +Tekst zawierający kod, zapis matematyczny czy znaczniki jest pełen nawiasów, a każdy nawias otwierający potrzebuje nawiasu zamykającego tego samego rodzaju. Ciąg znaków jest zrównoważony, gdy jego nawiasy tworzą pary i zagnieżdżają się jak warstwy cebuli: `{[()]}` jest zrównoważony, natomiast `{[(])}` już nie, ponieważ para okrągła zostaje zamknięta przed parą kwadratową, wewnątrz której się znajduje. + +Liczą się tutaj trzy pary: okrągła `()`, kwadratowa `[]` i klamrowa `{}`. Każdy inny znak w ciągu jest ignorowany. Nawias zamykający musi zamykać ostatnio otwarty nawias, który wciąż jest otwarty, a gdy ciąg się kończy, żaden nawias nie może pozostać otwarty. + +# --instructions-- + +Napisz funkcję `isBalanced`, która przyjmuje ciąg znaków i zwraca `true`, gdy wszystkie zawarte w niej nawiasy są sparowane i poprawnie zagnieżdżone, a w przeciwnym razie zwraca `false`. + +Przykłady: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Pusty ciąg znaków jest zrównoważony. +- Znaki, które nie są nawiasami, są ignorowane. +- Nawias zamykający musi pasować do ostatnio otwartego nawiasu, który wciąż jest otwarty. +- Żaden nawias nie może pozostać otwarty, gdy ciąg znaków się kończy. + +# --before-seed-- + +```swift +// DO NOT EDIT FROM HERE +import Foundation + +var _testCount = 0 +var _testFailedCount = 0 +func tryCatch(_ assertion: Bool) { + _testCount += 1 + if !assertion { + _testFailedCount += 1 + print("Test Case '--err-t\(_testCount)--' failed") + } +} +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```swift +func isBalanced(_ text: String) -> Bool { + +} +``` + +# --asserts-- + +Pusty ciąg znaków jest zrównoważony + +```swift +tryCatch(isBalanced("") == true) +``` + +Pojedyncza para nawiasów okrągłych jest zrównoważona + +```swift +tryCatch(isBalanced("()") == true) +``` + +Trzy rodzaje par zagnieżdżone jeden w drugim są zrównoważone + +```swift +tryCatch(isBalanced("{[()]}") == true) +``` + +Nawiasy przeplatane innym tekstem nadal są zrównoważone + +```swift +tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +Pary ustawione obok siebie są zrównoważone + +```swift +tryCatch(isBalanced("()[]{}") == true) +``` + +Ciąg znaków bez żadnych nawiasów jest zrównoważony + +```swift +tryCatch(isBalanced("no brackets in here at all") == true) +``` + +Skrzyżowana para nawiasów nie jest zrównoważona + +```swift +tryCatch(isBalanced("{[(])}") == false) +``` + +Nawias otwierający, który nigdy nie zostaje zamknięty, nie jest zrównoważony + +```swift +tryCatch(isBalanced("(") == false) +``` + +Nawias zamykający pojawiający się przed jakimkolwiek nawiasem otwierającym nie jest zrównoważony + +```swift +tryCatch(isBalanced(")(") == false) +``` + +Skrzyżowane pary głębiej w ciągu znaków nie są zrównoważone + +```swift +tryCatch(isBalanced("(([]{[}]))") == false) +``` + +Nawias zamykający pozostawiony na końcu nie jest zrównoważony + +```swift +tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```swift +print("Executed \(_testCount) tests, with \(_testFailedCount) failures") +``` + +# --solutions-- + +```swift +func isBalanced(_ text: String) -> Bool { + let pairs: [Character: Character] = [")": "(", "]": "[", "}": "{"] + var stack: [Character] = [] + + for char in text { + if char == "(" || char == "[" || char == "{" { + stack.append(char) + } else if let opening = pairs[char] { + if stack.popLast() != opening { + return false + } + } + } + + return stack.isEmpty +} +``` diff --git a/pt/c/challenges/data.json b/pt/c/challenges/data.json index 717cc8466..a24023aa5 100644 --- a/pt/c/challenges/data.json +++ b/pt/c/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagrama" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Colchetes correspondentes" } } diff --git a/pt/c/challenges/matching_brackets.md b/pt/c/challenges/matching_brackets.md new file mode 100644 index 000000000..46de20e13 --- /dev/null +++ b/pt/c/challenges/matching_brackets.md @@ -0,0 +1,280 @@ +--- +language: c +exerciseType: 1 +difficulty: 3 +title: Colchetes correspondentes +--- + +# --description-- + +Textos que contêm código, matemática ou marcação estão cheios de colchetes, e todo colchete de abertura precisa de um colchete de fechamento do mesmo tipo. Uma string está balanceada quando seus colchetes formam pares e se aninham como as camadas de uma cebola: `{[()]}` está balanceada, enquanto `{[(])}` não está, porque o par redondo é fechado antes do par de colchetes dentro do qual ele está. + +Três pares contam aqui: parênteses `()`, colchetes `[]` e chaves `{}`. Todos os outros caracteres da string são ignorados. Um colchete de fechamento deve fechar o colchete aberto mais recentemente que ainda esteja aberto, e quando a string termina nenhum colchete pode ficar aberto. + +# --instructions-- + +Escreva uma função `is_balanced` que recebe uma string e retorna `true` quando todos os colchetes nela estão correspondidos e corretamente aninhados, e `false` caso contrário. + +Exemplos: +``` +is_balanced("") ➞ true +is_balanced("{[()]}") ➞ true +is_balanced("{what is (42)}[?]") ➞ true +is_balanced("{[(])}") ➞ false +is_balanced("(") ➞ false +is_balanced(")(") ➞ false +``` + +- Uma string vazia está balanceada. +- Caracteres que não são colchetes são ignorados. +- Um colchete de fechamento deve corresponder ao colchete aberto mais recentemente que ainda esteja aberto. +- Nenhum colchete pode ficar aberto quando a string termina. + +# --before-seed-- + +```c +// DO NOT EDIT FROM HERE +#include +#include +#include + +#ifndef _CEXCEPTION_H +#define _CEXCEPTION_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +//This is the value to assign when there isn't an exception +#ifndef CEXCEPTION_NONE +#define CEXCEPTION_NONE (0x5A5A5A5A) +#endif + +//This is number of exception stacks to keep track of (one per task) +#ifndef CEXCEPTION_NUM_ID +#define CEXCEPTION_NUM_ID (1) //there is only the one stack by default +#endif + +//This is the method of getting the current exception stack index (0 if only one stack) +#ifndef CEXCEPTION_GET_ID +#define CEXCEPTION_GET_ID (0) //use the first index always because there is only one anyway +#endif + +//The type to use to store the exception values. +#ifndef CEXCEPTION_T +#define CEXCEPTION_T unsigned int +#endif + +//This is an optional special handler for when there is no global Catch +#ifndef CEXCEPTION_NO_CATCH_HANDLER +#define CEXCEPTION_NO_CATCH_HANDLER(id) +#endif + +//These hooks allow you to inject custom code into places, particularly useful for saving and restoring additional state +#ifndef CEXCEPTION_HOOK_START_TRY +#define CEXCEPTION_HOOK_START_TRY +#endif +#ifndef CEXCEPTION_HOOK_HAPPY_TRY +#define CEXCEPTION_HOOK_HAPPY_TRY +#endif +#ifndef CEXCEPTION_HOOK_AFTER_TRY +#define CEXCEPTION_HOOK_AFTER_TRY +#endif +#ifndef CEXCEPTION_HOOK_START_CATCH +#define CEXCEPTION_HOOK_START_CATCH +#endif + +//exception frame structures +typedef struct { + jmp_buf* pFrame; + CEXCEPTION_T volatile Exception; +} CEXCEPTION_FRAME_T; + +//actual root frame storage (only one if single-tasking) +extern volatile CEXCEPTION_FRAME_T CExceptionFrames[]; + +//Try +#define Try \ + { \ + jmp_buf *PrevFrame, NewFrame; \ + unsigned int MY_ID = CEXCEPTION_GET_ID; \ + PrevFrame = CExceptionFrames[MY_ID].pFrame; \ + CExceptionFrames[MY_ID].pFrame = (jmp_buf*)(&NewFrame); \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_START_TRY; \ + if (setjmp(NewFrame) == 0) { \ + if (1) + +//Catch +#define Catch(e) \ + else { } \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_HAPPY_TRY; \ + } \ + else \ + { \ + e = CExceptionFrames[MY_ID].Exception; \ + (void)e; \ + CEXCEPTION_HOOK_START_CATCH; \ + } \ + CExceptionFrames[MY_ID].pFrame = PrevFrame; \ + CEXCEPTION_HOOK_AFTER_TRY; \ + } \ + if (CExceptionFrames[CEXCEPTION_GET_ID].Exception != CEXCEPTION_NONE) + +#endif + +volatile CEXCEPTION_FRAME_T CExceptionFrames[CEXCEPTION_NUM_ID] = {{ 0 }}; + +void Throw(CEXCEPTION_T ExceptionID) +{ + unsigned int MY_ID = CEXCEPTION_GET_ID; + CExceptionFrames[MY_ID].Exception = ExceptionID; + if (CExceptionFrames[MY_ID].pFrame) + { + longjmp(*CExceptionFrames[MY_ID].pFrame, 1); + } + CEXCEPTION_NO_CATCH_HANDLER(ExceptionID); +} + +CEXCEPTION_T e; +int _test_failed_count = 0; +int _test_count = 0; + +void try_catch(bool assertion) { + _test_count++; + Try { + if (!assertion) { + Throw(_test_count); + } + } Catch (e) { + _test_failed_count += 1; + printf("Test Case '--err-t%i--' failed\n", e); + } +} +// DO NOT EDIT UNTIL HERE +#include +#include +``` + +# --seed-- + +```c +bool is_balanced(const char* text) { + +} +``` + +# --before-asserts-- + +```c +int main() { +``` + +# --asserts-- + +Uma string vazia está balanceada + +```c + try_catch(is_balanced("") == true); +``` + +Um único par de parênteses está balanceado + +```c + try_catch(is_balanced("()") == true); +``` + +Os três tipos de par aninhados uns dentro dos outros estão balanceados + +```c + try_catch(is_balanced("{[()]}") == true); +``` + +Colchetes misturados com outro texto ainda estão balanceados + +```c + try_catch(is_balanced("{what is (42)}[?]") == true); +``` + +Pares colocados lado a lado estão balanceados + +```c + try_catch(is_balanced("()[]{}") == true); +``` + +Uma string sem nenhum colchete está balanceada + +```c + try_catch(is_balanced("no brackets in here at all") == true); +``` + +Um par cruzado não está balanceado + +```c + try_catch(is_balanced("{[(])}") == false); +``` + +Um colchete de abertura que nunca é fechado não está balanceado + +```c + try_catch(is_balanced("(") == false); +``` + +Um colchete de fechamento antes de qualquer colchete de abertura não está balanceado + +```c + try_catch(is_balanced(")(") == false); +``` + +Pares cruzados mais no fundo da string não estão balanceados + +```c + try_catch(is_balanced("(([]{[}]))") == false); +``` + +Um colchete de fechamento que sobra no final não está balanceado + +```c + try_catch(is_balanced("())") == false); +``` + +# --after-asserts-- + +```c + printf("Executed %d tests, with %d failures", _test_count, _test_failed_count); + return 0; +} +``` + +# --solutions-- + +```c +bool is_balanced(const char* text) { + size_t length = strlen(text); + char stack[length + 1]; + size_t top = 0; + + for (size_t i = 0; i < length; i++) { + char current = text[i]; + + if (current == '(' || current == '[' || current == '{') { + stack[top++] = current; + } else if (current == ')' || current == ']' || current == '}') { + if (top == 0) { + return false; + } + + char opening = stack[--top]; + if ((current == ')' && opening != '(') || + (current == ']' && opening != '[') || + (current == '}' && opening != '{')) { + return false; + } + } + } + + return top == 0; +} +``` diff --git a/pt/dart/challenges/data.json b/pt/dart/challenges/data.json index fbf37d758..889969e7c 100644 --- a/pt/dart/challenges/data.json +++ b/pt/dart/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagrama" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Colchetes correspondentes" } } diff --git a/pt/dart/challenges/matching_brackets.md b/pt/dart/challenges/matching_brackets.md new file mode 100644 index 000000000..dad99ec00 --- /dev/null +++ b/pt/dart/challenges/matching_brackets.md @@ -0,0 +1,167 @@ +--- +language: dart +exerciseType: 1 +difficulty: 3 +title: Colchetes correspondentes +--- + +# --description-- + +Textos que contêm código, matemática ou marcação estão cheios de colchetes, e todo colchete de abertura precisa de um colchete de fechamento do mesmo tipo. Uma string está balanceada quando seus colchetes formam pares e se aninham como as camadas de uma cebola: `{[()]}` está balanceada, enquanto `{[(])}` não está, porque o par redondo é fechado antes do par de colchetes dentro do qual ele está. + +Três pares contam aqui: parênteses `()`, colchetes `[]` e chaves `{}`. Todos os outros caracteres da string são ignorados. Um colchete de fechamento deve fechar o colchete aberto mais recentemente que ainda esteja aberto, e quando a string termina nenhum colchete pode ficar aberto. + +# --instructions-- + +Escreva uma função `isBalanced` que recebe uma string e retorna `true` quando todos os colchetes nela estão correspondidos e corretamente aninhados, e `false` caso contrário. + +Exemplos: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Uma string vazia está balanceada. +- Caracteres que não são colchetes são ignorados. +- Um colchete de fechamento deve corresponder ao colchete aberto mais recentemente que ainda esteja aberto. +- Nenhum colchete pode ficar aberto quando a string termina. + +# --seed-- + +```dart +bool isBalanced(String text) { + +} +``` + +# --before-asserts-- + +```dart +import 'package:dart_runner/main.dart'; +import 'package:test/test.dart'; + +void main() { + group('MainTest -', () { +``` + +# --asserts-- + +Uma string vazia está balanceada + +```dart + test('test1', () { + expect(isBalanced(''), true, reason: '--err-t1--'); + }); +``` + +Um único par de parênteses está balanceado + +```dart + test('test2', () { + expect(isBalanced('()'), true, reason: '--err-t2--'); + }); +``` + +Os três tipos de par aninhados uns dentro dos outros estão balanceados + +```dart + test('test3', () { + expect(isBalanced('{[()]}'), true, reason: '--err-t3--'); + }); +``` + +Colchetes misturados com outro texto ainda estão balanceados + +```dart + test('test4', () { + expect(isBalanced('{what is (42)}[?]'), true, reason: '--err-t4--'); + }); +``` + +Pares colocados lado a lado estão balanceados + +```dart + test('test5', () { + expect(isBalanced('()[]{}'), true, reason: '--err-t5--'); + }); +``` + +Uma string sem nenhum colchete está balanceada + +```dart + test('test6', () { + expect(isBalanced('no brackets in here at all'), true, reason: '--err-t6--'); + }); +``` + +Um par cruzado não está balanceado + +```dart + test('test7', () { + expect(isBalanced('{[(])}'), false, reason: '--err-t7--'); + }); +``` + +Um colchete de abertura que nunca é fechado não está balanceado + +```dart + test('test8', () { + expect(isBalanced('('), false, reason: '--err-t8--'); + }); +``` + +Um colchete de fechamento antes de qualquer colchete de abertura não está balanceado + +```dart + test('test9', () { + expect(isBalanced(')('), false, reason: '--err-t9--'); + }); +``` + +Pares cruzados mais no fundo da string não estão balanceados + +```dart + test('test10', () { + expect(isBalanced('(([]{[}]))'), false, reason: '--err-t10--'); + }); +``` + +Um colchete de fechamento que sobra no final não está balanceado + +```dart + test('test11', () { + expect(isBalanced('())'), false, reason: '--err-t11--'); + }); +``` + +# --after-asserts-- + +```dart + }, timeout: Timeout(const Duration(seconds: 1))); +} +``` + +# --solutions-- + +```dart +bool isBalanced(String text) { + const pairs = {')': '(', ']': '[', '}': '{'}; + final stack = []; + + for (final char in text.split('')) { + if (char == '(' || char == '[' || char == '{') { + stack.add(char); + } else if (pairs.containsKey(char)) { + if (stack.isEmpty || stack.removeLast() != pairs[char]) { + return false; + } + } + } + + return stack.isEmpty; +} +``` diff --git a/pt/javascript/challenges/data.json b/pt/javascript/challenges/data.json index 386c5768b..b5c4705fc 100644 --- a/pt/javascript/challenges/data.json +++ b/pt/javascript/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagrama" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Colchetes correspondentes" } } diff --git a/pt/javascript/challenges/matching_brackets.md b/pt/javascript/challenges/matching_brackets.md new file mode 100644 index 000000000..5a4df7c17 --- /dev/null +++ b/pt/javascript/challenges/matching_brackets.md @@ -0,0 +1,154 @@ +--- +language: javascript +exerciseType: 1 +difficulty: 3 +title: Colchetes correspondentes +--- + +# --description-- + +Textos que contêm código, matemática ou marcação estão cheios de colchetes, e todo colchete de abertura precisa de um colchete de fechamento do mesmo tipo. Uma string está balanceada quando seus colchetes formam pares e se aninham como as camadas de uma cebola: `{[()]}` está balanceada, enquanto `{[(])}` não está, porque o par redondo é fechado antes do par de colchetes dentro do qual ele está. + +Três pares contam aqui: parênteses `()`, colchetes `[]` e chaves `{}`. Todos os outros caracteres da string são ignorados. Um colchete de fechamento deve fechar o colchete aberto mais recentemente que ainda esteja aberto, e quando a string termina nenhum colchete pode ficar aberto. + +# --instructions-- + +Escreva uma função `isBalanced` que recebe uma string e retorna `true` quando todos os colchetes nela estão correspondidos e corretamente aninhados, e `false` caso contrário. + +Exemplos: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Uma string vazia está balanceada. +- Caracteres que não são colchetes são ignorados. +- Um colchete de fechamento deve corresponder ao colchete aberto mais recentemente que ainda esteja aberto. +- Nenhum colchete pode ficar aberto quando a string termina. + +# --before-seed-- + +```javascript +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +var assert = require('assert') +const tryCatch = (...args) => { + _testCount++ + try { assert(...args) } + catch (e) { + _testFailedCount++ + console.log(`Test Case '--err-t${_testCount}--' failed`); + } +}; +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```javascript +function isBalanced(text) { + +} +``` + +# --asserts-- + +Uma string vazia está balanceada + +```javascript +tryCatch(isBalanced("") === true); +``` + +Um único par de parênteses está balanceado + +```javascript +tryCatch(isBalanced("()") === true); +``` + +Os três tipos de par aninhados uns dentro dos outros estão balanceados + +```javascript +tryCatch(isBalanced("{[()]}") === true); +``` + +Colchetes misturados com outro texto ainda estão balanceados + +```javascript +tryCatch(isBalanced("{what is (42)}[?]") === true); +``` + +Pares colocados lado a lado estão balanceados + +```javascript +tryCatch(isBalanced("()[]{}") === true); +``` + +Uma string sem nenhum colchete está balanceada + +```javascript +tryCatch(isBalanced("no brackets in here at all") === true); +``` + +Um par cruzado não está balanceado + +```javascript +tryCatch(isBalanced("{[(])}") === false); +``` + +Um colchete de abertura que nunca é fechado não está balanceado + +```javascript +tryCatch(isBalanced("(") === false); +``` + +Um colchete de fechamento antes de qualquer colchete de abertura não está balanceado + +```javascript +tryCatch(isBalanced(")(") === false); +``` + +Pares cruzados mais no fundo da string não estão balanceados + +```javascript +tryCatch(isBalanced("(([]{[}]))") === false); +``` + +Um colchete de fechamento que sobra no final não está balanceado + +```javascript +tryCatch(isBalanced("())") === false); +``` + +# --after-asserts-- + +```javascript +// DO NOT EDIT FROM HERE +console.log(`Executed ${_testCount} tests, with ${_testFailedCount} failures`); +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```javascript +function isBalanced(text) { + const pairs = { ")": "(", "]": "[", "}": "{" }; + const stack = []; + + for (const char of text) { + if (char === "(" || char === "[" || char === "{") { + stack.push(char); + } else if (char in pairs) { + if (stack.pop() !== pairs[char]) { + return false; + } + } + } + + return stack.length === 0; +} +``` diff --git a/pt/kotlin/challenges/data.json b/pt/kotlin/challenges/data.json index 382233de8..20ef5921e 100644 --- a/pt/kotlin/challenges/data.json +++ b/pt/kotlin/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagrama" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Colchetes correspondentes" } } diff --git a/pt/kotlin/challenges/matching_brackets.md b/pt/kotlin/challenges/matching_brackets.md new file mode 100644 index 000000000..a97f7b51c --- /dev/null +++ b/pt/kotlin/challenges/matching_brackets.md @@ -0,0 +1,157 @@ +--- +language: kotlin +exerciseType: 1 +difficulty: 3 +title: Colchetes correspondentes +--- + +# --description-- + +Textos que contêm código, matemática ou marcação estão cheios de colchetes, e todo colchete de abertura precisa de um colchete de fechamento do mesmo tipo. Uma string está balanceada quando seus colchetes formam pares e se aninham como as camadas de uma cebola: `{[()]}` está balanceada, enquanto `{[(])}` não está, porque o par redondo é fechado antes do par de colchetes dentro do qual ele está. + +Três pares contam aqui: parênteses `()`, colchetes `[]` e chaves `{}`. Todos os outros caracteres da string são ignorados. Um colchete de fechamento deve fechar o colchete aberto mais recentemente que ainda esteja aberto, e quando a string termina nenhum colchete pode ficar aberto. + +# --instructions-- + +Escreva uma função `isBalanced` que recebe uma string e retorna `true` quando todos os colchetes nela estão correspondidos e corretamente aninhados, e `false` caso contrário. + +Exemplos: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Uma string vazia está balanceada. +- Caracteres que não são colchetes são ignorados. +- Um colchete de fechamento deve corresponder ao colchete aberto mais recentemente que ainda esteja aberto. +- Nenhum colchete pode ficar aberto quando a string termina. + +# --seed-- + +```kotlin +fun isBalanced(text: String): Boolean { + +} +``` + +# --before-seed-- + +```kotlin +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +fun tryCatch(assertion: Boolean) { + _testCount++ + try { + if (!assertion) throw Exception() + } + catch (e: Throwable) { + _testFailedCount++ + println("Test Case '--err-t$_testCount--' failed"); + } +}; +// DO NOT EDIT UNTIL HERE +fun main() { +``` + +# --asserts-- + +Uma string vazia está balanceada + +```kotlin + tryCatch(isBalanced("") == true) +``` + +Um único par de parênteses está balanceado + +```kotlin + tryCatch(isBalanced("()") == true) +``` + +Os três tipos de par aninhados uns dentro dos outros estão balanceados + +```kotlin + tryCatch(isBalanced("{[()]}") == true) +``` + +Colchetes misturados com outro texto ainda estão balanceados + +```kotlin + tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +Pares colocados lado a lado estão balanceados + +```kotlin + tryCatch(isBalanced("()[]{}") == true) +``` + +Uma string sem nenhum colchete está balanceada + +```kotlin + tryCatch(isBalanced("no brackets in here at all") == true) +``` + +Um par cruzado não está balanceado + +```kotlin + tryCatch(isBalanced("{[(])}") == false) +``` + +Um colchete de abertura que nunca é fechado não está balanceado + +```kotlin + tryCatch(isBalanced("(") == false) +``` + +Um colchete de fechamento antes de qualquer colchete de abertura não está balanceado + +```kotlin + tryCatch(isBalanced(")(") == false) +``` + +Pares cruzados mais no fundo da string não estão balanceados + +```kotlin + tryCatch(isBalanced("(([]{[}]))") == false) +``` + +Um colchete de fechamento que sobra no final não está balanceado + +```kotlin + tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```kotlin +// DO NOT EDIT FROM HERE + println("Executed $_testCount tests, with $_testFailedCount failures"); +} +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```kotlin +fun isBalanced(text: String): Boolean { + val pairs = mapOf(')' to '(', ']' to '[', '}' to '{') + val stack = ArrayDeque() + + for (char in text) { + if (char == '(' || char == '[' || char == '{') { + stack.addLast(char) + } else if (pairs.containsKey(char)) { + if (stack.isEmpty() || stack.removeLast() != pairs[char]) { + return false + } + } + } + + return stack.isEmpty() +} +``` diff --git a/pt/python/challenges/data.json b/pt/python/challenges/data.json index ae3b9a9a3..0451ae355 100644 --- a/pt/python/challenges/data.json +++ b/pt/python/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagrama" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Colchetes correspondentes" } } diff --git a/pt/python/challenges/matching_brackets.md b/pt/python/challenges/matching_brackets.md new file mode 100644 index 000000000..44c0d431a --- /dev/null +++ b/pt/python/challenges/matching_brackets.md @@ -0,0 +1,149 @@ +--- +language: python +exerciseType: 1 +difficulty: 3 +title: Colchetes correspondentes +--- + +# --description-- + +Textos que contêm código, matemática ou marcação estão cheios de colchetes, e todo colchete de abertura precisa de um colchete de fechamento do mesmo tipo. Uma string está balanceada quando seus colchetes formam pares e se aninham como as camadas de uma cebola: `{[()]}` está balanceada, enquanto `{[(])}` não está, porque o par redondo é fechado antes do par de colchetes dentro do qual ele está. + +Três pares contam aqui: parênteses `()`, colchetes `[]` e chaves `{}`. Todos os outros caracteres da string são ignorados. Um colchete de fechamento deve fechar o colchete aberto mais recentemente que ainda esteja aberto, e quando a string termina nenhum colchete pode ficar aberto. + +# --instructions-- + +Escreva uma função `is_balanced` que recebe uma string e retorna `True` quando todos os colchetes nela estão correspondidos e corretamente aninhados, e `False` caso contrário. + +Exemplos: +``` +is_balanced("") ➞ True +is_balanced("{[()]}") ➞ True +is_balanced("{what is (42)}[?]") ➞ True +is_balanced("{[(])}") ➞ False +is_balanced("(") ➞ False +is_balanced(")(") ➞ False +``` + +- Uma string vazia está balanceada. +- Caracteres que não são colchetes são ignorados. +- Um colchete de fechamento deve corresponder ao colchete aberto mais recentemente que ainda esteja aberto. +- Nenhum colchete pode ficar aberto quando a string termina. + +# --seed-- + +```python +def is_balanced(text): + pass +``` + +# --before-asserts-- + +```python +import unittest + +class CodigoTests(unittest.TestCase): +``` + +# --asserts-- + +Uma string vazia está balanceada + +```python + def test1(self): + self.assertEqual(is_balanced(""), True, "--err-t1--") +``` + +Um único par de parênteses está balanceado + +```python + def test2(self): + self.assertEqual(is_balanced("()"), True, "--err-t2--") +``` + +Os três tipos de par aninhados uns dentro dos outros estão balanceados + +```python + def test3(self): + self.assertEqual(is_balanced("{[()]}"), True, "--err-t3--") +``` + +Colchetes misturados com outro texto ainda estão balanceados + +```python + def test4(self): + self.assertEqual(is_balanced("{what is (42)}[?]"), True, "--err-t4--") +``` + +Pares colocados lado a lado estão balanceados + +```python + def test5(self): + self.assertEqual(is_balanced("()[]{}"), True, "--err-t5--") +``` + +Uma string sem nenhum colchete está balanceada + +```python + def test6(self): + self.assertEqual(is_balanced("no brackets in here at all"), True, "--err-t6--") +``` + +Um par cruzado não está balanceado + +```python + def test7(self): + self.assertEqual(is_balanced("{[(])}"), False, "--err-t7--") +``` + +Um colchete de abertura que nunca é fechado não está balanceado + +```python + def test8(self): + self.assertEqual(is_balanced("("), False, "--err-t8--") +``` + +Um colchete de fechamento antes de qualquer colchete de abertura não está balanceado + +```python + def test9(self): + self.assertEqual(is_balanced(")("), False, "--err-t9--") +``` + +Pares cruzados mais no fundo da string não estão balanceados + +```python + def test10(self): + self.assertEqual(is_balanced("(([]{[}]))"), False, "--err-t10--") +``` + +Um colchete de fechamento que sobra no final não está balanceado + +```python + def test11(self): + self.assertEqual(is_balanced("())"), False, "--err-t11--") +``` + +# --after-asserts-- + +```python +if __name__ == "__main__": + unittest.main() +``` + +# --solutions-- + +```python +def is_balanced(text): + pairs = {")": "(", "]": "[", "}": "{"} + stack = [] + + for char in text: + if char in "([{": + stack.append(char) + elif char in pairs: + if not stack or stack.pop() != pairs[char]: + return False + + return not stack +``` diff --git a/pt/swift/challenges/data.json b/pt/swift/challenges/data.json index 4296d4efa..555f12d82 100644 --- a/pt/swift/challenges/data.json +++ b/pt/swift/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Anagrama" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Colchetes correspondentes" } } diff --git a/pt/swift/challenges/matching_brackets.md b/pt/swift/challenges/matching_brackets.md new file mode 100644 index 000000000..c9507367c --- /dev/null +++ b/pt/swift/challenges/matching_brackets.md @@ -0,0 +1,152 @@ +--- +language: swift +exerciseType: 1 +difficulty: 3 +title: Colchetes correspondentes +--- + +# --description-- + +Textos que contêm código, matemática ou marcação estão cheios de colchetes, e todo colchete de abertura precisa de um colchete de fechamento do mesmo tipo. Uma string está balanceada quando seus colchetes formam pares e se aninham como as camadas de uma cebola: `{[()]}` está balanceada, enquanto `{[(])}` não está, porque o par redondo é fechado antes do par de colchetes dentro do qual ele está. + +Três pares contam aqui: parênteses `()`, colchetes `[]` e chaves `{}`. Todos os outros caracteres da string são ignorados. Um colchete de fechamento deve fechar o colchete aberto mais recentemente que ainda esteja aberto, e quando a string termina nenhum colchete pode ficar aberto. + +# --instructions-- + +Escreva uma função `isBalanced` que recebe uma string e retorna `true` quando todos os colchetes nela estão correspondidos e corretamente aninhados, e `false` caso contrário. + +Exemplos: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Uma string vazia está balanceada. +- Caracteres que não são colchetes são ignorados. +- Um colchete de fechamento deve corresponder ao colchete aberto mais recentemente que ainda esteja aberto. +- Nenhum colchete pode ficar aberto quando a string termina. + +# --before-seed-- + +```swift +// DO NOT EDIT FROM HERE +import Foundation + +var _testCount = 0 +var _testFailedCount = 0 +func tryCatch(_ assertion: Bool) { + _testCount += 1 + if !assertion { + _testFailedCount += 1 + print("Test Case '--err-t\(_testCount)--' failed") + } +} +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```swift +func isBalanced(_ text: String) -> Bool { + +} +``` + +# --asserts-- + +Uma string vazia está balanceada + +```swift +tryCatch(isBalanced("") == true) +``` + +Um único par de parênteses está balanceado + +```swift +tryCatch(isBalanced("()") == true) +``` + +Os três tipos de par aninhados uns dentro dos outros estão balanceados + +```swift +tryCatch(isBalanced("{[()]}") == true) +``` + +Colchetes misturados com outro texto ainda estão balanceados + +```swift +tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +Pares colocados lado a lado estão balanceados + +```swift +tryCatch(isBalanced("()[]{}") == true) +``` + +Uma string sem nenhum colchete está balanceada + +```swift +tryCatch(isBalanced("no brackets in here at all") == true) +``` + +Um par cruzado não está balanceado + +```swift +tryCatch(isBalanced("{[(])}") == false) +``` + +Um colchete de abertura que nunca é fechado não está balanceado + +```swift +tryCatch(isBalanced("(") == false) +``` + +Um colchete de fechamento antes de qualquer colchete de abertura não está balanceado + +```swift +tryCatch(isBalanced(")(") == false) +``` + +Pares cruzados mais no fundo da string não estão balanceados + +```swift +tryCatch(isBalanced("(([]{[}]))") == false) +``` + +Um colchete de fechamento que sobra no final não está balanceado + +```swift +tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```swift +print("Executed \(_testCount) tests, with \(_testFailedCount) failures") +``` + +# --solutions-- + +```swift +func isBalanced(_ text: String) -> Bool { + let pairs: [Character: Character] = [")": "(", "]": "[", "}": "{"] + var stack: [Character] = [] + + for char in text { + if char == "(" || char == "[" || char == "{" { + stack.append(char) + } else if let opening = pairs[char] { + if stack.popLast() != opening { + return false + } + } + } + + return stack.isEmpty +} +``` diff --git a/ru/c/challenges/data.json b/ru/c/challenges/data.json index 2ebfecce8..50ff8f5b3 100644 --- a/ru/c/challenges/data.json +++ b/ru/c/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Анаграмма" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Сбалансированные скобки" } -} +} \ No newline at end of file diff --git a/ru/c/challenges/matching_brackets.md b/ru/c/challenges/matching_brackets.md new file mode 100644 index 000000000..8de4dd2a4 --- /dev/null +++ b/ru/c/challenges/matching_brackets.md @@ -0,0 +1,280 @@ +--- +language: c +exerciseType: 1 +difficulty: 3 +title: Сбалансированные скобки +--- + +# --description-- + +Текст, в котором есть код, математика или разметка, полон скобок, и каждой открывающей скобке нужна закрывающая того же вида. Строка сбалансирована, когда её скобки образуют пары и вкладываются друг в друга, как слои луковицы: `{[()]}` сбалансирована, а `{[(])}` — нет, ведь круглая пара закрывается раньше квадратной пары, внутри которой она находится. + +Здесь учитываются три пары: круглые `()`, квадратные `[]` и фигурные `{}`. Все остальные символы строки игнорируются. Закрывающая скобка должна закрывать последнюю из ещё открытых скобок, а к концу строки не должно остаться ни одной незакрытой скобки. + +# --instructions-- + +Напишите функцию `is_balanced`, которая принимает строку и возвращает `true`, если все скобки в ней образуют пары и правильно вложены, и `false` в противном случае. + +Примеры: +``` +is_balanced("") ➞ true +is_balanced("{[()]}") ➞ true +is_balanced("{what is (42)}[?]") ➞ true +is_balanced("{[(])}") ➞ false +is_balanced("(") ➞ false +is_balanced(")(") ➞ false +``` + +- Пустая строка сбалансирована. +- Символы, не являющиеся скобками, игнорируются. +- Закрывающая скобка должна соответствовать последней из ещё открытых скобок. +- К концу строки не должно оставаться ни одной открытой скобки. + +# --before-seed-- + +```c +// DO NOT EDIT FROM HERE +#include +#include +#include + +#ifndef _CEXCEPTION_H +#define _CEXCEPTION_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +//This is the value to assign when there isn't an exception +#ifndef CEXCEPTION_NONE +#define CEXCEPTION_NONE (0x5A5A5A5A) +#endif + +//This is number of exception stacks to keep track of (one per task) +#ifndef CEXCEPTION_NUM_ID +#define CEXCEPTION_NUM_ID (1) //there is only the one stack by default +#endif + +//This is the method of getting the current exception stack index (0 if only one stack) +#ifndef CEXCEPTION_GET_ID +#define CEXCEPTION_GET_ID (0) //use the first index always because there is only one anyway +#endif + +//The type to use to store the exception values. +#ifndef CEXCEPTION_T +#define CEXCEPTION_T unsigned int +#endif + +//This is an optional special handler for when there is no global Catch +#ifndef CEXCEPTION_NO_CATCH_HANDLER +#define CEXCEPTION_NO_CATCH_HANDLER(id) +#endif + +//These hooks allow you to inject custom code into places, particularly useful for saving and restoring additional state +#ifndef CEXCEPTION_HOOK_START_TRY +#define CEXCEPTION_HOOK_START_TRY +#endif +#ifndef CEXCEPTION_HOOK_HAPPY_TRY +#define CEXCEPTION_HOOK_HAPPY_TRY +#endif +#ifndef CEXCEPTION_HOOK_AFTER_TRY +#define CEXCEPTION_HOOK_AFTER_TRY +#endif +#ifndef CEXCEPTION_HOOK_START_CATCH +#define CEXCEPTION_HOOK_START_CATCH +#endif + +//exception frame structures +typedef struct { + jmp_buf* pFrame; + CEXCEPTION_T volatile Exception; +} CEXCEPTION_FRAME_T; + +//actual root frame storage (only one if single-tasking) +extern volatile CEXCEPTION_FRAME_T CExceptionFrames[]; + +//Try +#define Try \ + { \ + jmp_buf *PrevFrame, NewFrame; \ + unsigned int MY_ID = CEXCEPTION_GET_ID; \ + PrevFrame = CExceptionFrames[MY_ID].pFrame; \ + CExceptionFrames[MY_ID].pFrame = (jmp_buf*)(&NewFrame); \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_START_TRY; \ + if (setjmp(NewFrame) == 0) { \ + if (1) + +//Catch +#define Catch(e) \ + else { } \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_HAPPY_TRY; \ + } \ + else \ + { \ + e = CExceptionFrames[MY_ID].Exception; \ + (void)e; \ + CEXCEPTION_HOOK_START_CATCH; \ + } \ + CExceptionFrames[MY_ID].pFrame = PrevFrame; \ + CEXCEPTION_HOOK_AFTER_TRY; \ + } \ + if (CExceptionFrames[CEXCEPTION_GET_ID].Exception != CEXCEPTION_NONE) + +#endif + +volatile CEXCEPTION_FRAME_T CExceptionFrames[CEXCEPTION_NUM_ID] = {{ 0 }}; + +void Throw(CEXCEPTION_T ExceptionID) +{ + unsigned int MY_ID = CEXCEPTION_GET_ID; + CExceptionFrames[MY_ID].Exception = ExceptionID; + if (CExceptionFrames[MY_ID].pFrame) + { + longjmp(*CExceptionFrames[MY_ID].pFrame, 1); + } + CEXCEPTION_NO_CATCH_HANDLER(ExceptionID); +} + +CEXCEPTION_T e; +int _test_failed_count = 0; +int _test_count = 0; + +void try_catch(bool assertion) { + _test_count++; + Try { + if (!assertion) { + Throw(_test_count); + } + } Catch (e) { + _test_failed_count += 1; + printf("Test Case '--err-t%i--' failed\n", e); + } +} +// DO NOT EDIT UNTIL HERE +#include +#include +``` + +# --seed-- + +```c +bool is_balanced(const char* text) { + +} +``` + +# --before-asserts-- + +```c +int main() { +``` + +# --asserts-- + +Пустая строка сбалансирована + +```c + try_catch(is_balanced("") == true); +``` + +Одна пара круглых скобок сбалансирована + +```c + try_catch(is_balanced("()") == true); +``` + +Три вида пар, вложенные друг в друга, сбалансированы + +```c + try_catch(is_balanced("{[()]}") == true); +``` + +Скобки вперемешку с другим текстом остаются сбалансированными + +```c + try_catch(is_balanced("{what is (42)}[?]") == true); +``` + +Пары, стоящие друг за другом, сбалансированы + +```c + try_catch(is_balanced("()[]{}") == true); +``` + +Строка вовсе без скобок сбалансирована + +```c + try_catch(is_balanced("no brackets in here at all") == true); +``` + +Перекрёстная пара не сбалансирована + +```c + try_catch(is_balanced("{[(])}") == false); +``` + +Открывающая скобка, которая никогда не закрывается, не сбалансирована + +```c + try_catch(is_balanced("(") == false); +``` + +Закрывающая скобка раньше любой открывающей не сбалансирована + +```c + try_catch(is_balanced(")(") == false); +``` + +Перекрёстные пары в глубине строки не сбалансированы + +```c + try_catch(is_balanced("(([]{[}]))") == false); +``` + +Лишняя закрывающая скобка в конце строки не сбалансирована + +```c + try_catch(is_balanced("())") == false); +``` + +# --after-asserts-- + +```c + printf("Executed %d tests, with %d failures", _test_count, _test_failed_count); + return 0; +} +``` + +# --solutions-- + +```c +bool is_balanced(const char* text) { + size_t length = strlen(text); + char stack[length + 1]; + size_t top = 0; + + for (size_t i = 0; i < length; i++) { + char current = text[i]; + + if (current == '(' || current == '[' || current == '{') { + stack[top++] = current; + } else if (current == ')' || current == ']' || current == '}') { + if (top == 0) { + return false; + } + + char opening = stack[--top]; + if ((current == ')' && opening != '(') || + (current == ']' && opening != '[') || + (current == '}' && opening != '{')) { + return false; + } + } + } + + return top == 0; +} +``` diff --git a/ru/dart/challenges/data.json b/ru/dart/challenges/data.json index fb29a99b3..a2ee02a1e 100644 --- a/ru/dart/challenges/data.json +++ b/ru/dart/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Анаграмма" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Сбалансированные скобки" } -} +} \ No newline at end of file diff --git a/ru/dart/challenges/matching_brackets.md b/ru/dart/challenges/matching_brackets.md new file mode 100644 index 000000000..3b7c5310c --- /dev/null +++ b/ru/dart/challenges/matching_brackets.md @@ -0,0 +1,167 @@ +--- +language: dart +exerciseType: 1 +difficulty: 3 +title: Сбалансированные скобки +--- + +# --description-- + +Текст, в котором есть код, математика или разметка, полон скобок, и каждой открывающей скобке нужна закрывающая того же вида. Строка сбалансирована, когда её скобки образуют пары и вкладываются друг в друга, как слои луковицы: `{[()]}` сбалансирована, а `{[(])}` — нет, ведь круглая пара закрывается раньше квадратной пары, внутри которой она находится. + +Здесь учитываются три пары: круглые `()`, квадратные `[]` и фигурные `{}`. Все остальные символы строки игнорируются. Закрывающая скобка должна закрывать последнюю из ещё открытых скобок, а к концу строки не должно остаться ни одной незакрытой скобки. + +# --instructions-- + +Напишите функцию `isBalanced`, которая принимает строку и возвращает `true`, если все скобки в ней образуют пары и правильно вложены, и `false` в противном случае. + +Примеры: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Пустая строка сбалансирована. +- Символы, не являющиеся скобками, игнорируются. +- Закрывающая скобка должна соответствовать последней из ещё открытых скобок. +- К концу строки не должно оставаться ни одной открытой скобки. + +# --seed-- + +```dart +bool isBalanced(String text) { + +} +``` + +# --before-asserts-- + +```dart +import 'package:dart_runner/main.dart'; +import 'package:test/test.dart'; + +void main() { + group('MainTest -', () { +``` + +# --asserts-- + +Пустая строка сбалансирована + +```dart + test('test1', () { + expect(isBalanced(''), true, reason: '--err-t1--'); + }); +``` + +Одна пара круглых скобок сбалансирована + +```dart + test('test2', () { + expect(isBalanced('()'), true, reason: '--err-t2--'); + }); +``` + +Три вида пар, вложенные друг в друга, сбалансированы + +```dart + test('test3', () { + expect(isBalanced('{[()]}'), true, reason: '--err-t3--'); + }); +``` + +Скобки вперемешку с другим текстом остаются сбалансированными + +```dart + test('test4', () { + expect(isBalanced('{what is (42)}[?]'), true, reason: '--err-t4--'); + }); +``` + +Пары, стоящие друг за другом, сбалансированы + +```dart + test('test5', () { + expect(isBalanced('()[]{}'), true, reason: '--err-t5--'); + }); +``` + +Строка вовсе без скобок сбалансирована + +```dart + test('test6', () { + expect(isBalanced('no brackets in here at all'), true, reason: '--err-t6--'); + }); +``` + +Перекрёстная пара не сбалансирована + +```dart + test('test7', () { + expect(isBalanced('{[(])}'), false, reason: '--err-t7--'); + }); +``` + +Открывающая скобка, которая никогда не закрывается, не сбалансирована + +```dart + test('test8', () { + expect(isBalanced('('), false, reason: '--err-t8--'); + }); +``` + +Закрывающая скобка раньше любой открывающей не сбалансирована + +```dart + test('test9', () { + expect(isBalanced(')('), false, reason: '--err-t9--'); + }); +``` + +Перекрёстные пары в глубине строки не сбалансированы + +```dart + test('test10', () { + expect(isBalanced('(([]{[}]))'), false, reason: '--err-t10--'); + }); +``` + +Лишняя закрывающая скобка в конце строки не сбалансирована + +```dart + test('test11', () { + expect(isBalanced('())'), false, reason: '--err-t11--'); + }); +``` + +# --after-asserts-- + +```dart + }, timeout: Timeout(const Duration(seconds: 1))); +} +``` + +# --solutions-- + +```dart +bool isBalanced(String text) { + const pairs = {')': '(', ']': '[', '}': '{'}; + final stack = []; + + for (final char in text.split('')) { + if (char == '(' || char == '[' || char == '{') { + stack.add(char); + } else if (pairs.containsKey(char)) { + if (stack.isEmpty || stack.removeLast() != pairs[char]) { + return false; + } + } + } + + return stack.isEmpty; +} +``` diff --git a/ru/javascript/challenges/data.json b/ru/javascript/challenges/data.json index 0c3dd5aae..6c4c08902 100644 --- a/ru/javascript/challenges/data.json +++ b/ru/javascript/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Анаграмма" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Сбалансированные скобки" } -} +} \ No newline at end of file diff --git a/ru/javascript/challenges/matching_brackets.md b/ru/javascript/challenges/matching_brackets.md new file mode 100644 index 000000000..f0894a620 --- /dev/null +++ b/ru/javascript/challenges/matching_brackets.md @@ -0,0 +1,154 @@ +--- +language: javascript +exerciseType: 1 +difficulty: 3 +title: Сбалансированные скобки +--- + +# --description-- + +Текст, в котором есть код, математика или разметка, полон скобок, и каждой открывающей скобке нужна закрывающая того же вида. Строка сбалансирована, когда её скобки образуют пары и вкладываются друг в друга, как слои луковицы: `{[()]}` сбалансирована, а `{[(])}` — нет, ведь круглая пара закрывается раньше квадратной пары, внутри которой она находится. + +Здесь учитываются три пары: круглые `()`, квадратные `[]` и фигурные `{}`. Все остальные символы строки игнорируются. Закрывающая скобка должна закрывать последнюю из ещё открытых скобок, а к концу строки не должно остаться ни одной незакрытой скобки. + +# --instructions-- + +Напишите функцию `isBalanced`, которая принимает строку и возвращает `true`, если все скобки в ней образуют пары и правильно вложены, и `false` в противном случае. + +Примеры: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Пустая строка сбалансирована. +- Символы, не являющиеся скобками, игнорируются. +- Закрывающая скобка должна соответствовать последней из ещё открытых скобок. +- К концу строки не должно оставаться ни одной открытой скобки. + +# --before-seed-- + +```javascript +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +var assert = require('assert') +const tryCatch = (...args) => { + _testCount++ + try { assert(...args) } + catch (e) { + _testFailedCount++ + console.log(`Test Case '--err-t${_testCount}--' failed`); + } +}; +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```javascript +function isBalanced(text) { + +} +``` + +# --asserts-- + +Пустая строка сбалансирована + +```javascript +tryCatch(isBalanced("") === true); +``` + +Одна пара круглых скобок сбалансирована + +```javascript +tryCatch(isBalanced("()") === true); +``` + +Три вида пар, вложенные друг в друга, сбалансированы + +```javascript +tryCatch(isBalanced("{[()]}") === true); +``` + +Скобки вперемешку с другим текстом остаются сбалансированными + +```javascript +tryCatch(isBalanced("{what is (42)}[?]") === true); +``` + +Пары, стоящие друг за другом, сбалансированы + +```javascript +tryCatch(isBalanced("()[]{}") === true); +``` + +Строка вовсе без скобок сбалансирована + +```javascript +tryCatch(isBalanced("no brackets in here at all") === true); +``` + +Перекрёстная пара не сбалансирована + +```javascript +tryCatch(isBalanced("{[(])}") === false); +``` + +Открывающая скобка, которая никогда не закрывается, не сбалансирована + +```javascript +tryCatch(isBalanced("(") === false); +``` + +Закрывающая скобка раньше любой открывающей не сбалансирована + +```javascript +tryCatch(isBalanced(")(") === false); +``` + +Перекрёстные пары в глубине строки не сбалансированы + +```javascript +tryCatch(isBalanced("(([]{[}]))") === false); +``` + +Лишняя закрывающая скобка в конце строки не сбалансирована + +```javascript +tryCatch(isBalanced("())") === false); +``` + +# --after-asserts-- + +```javascript +// DO NOT EDIT FROM HERE +console.log(`Executed ${_testCount} tests, with ${_testFailedCount} failures`); +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```javascript +function isBalanced(text) { + const pairs = { ")": "(", "]": "[", "}": "{" }; + const stack = []; + + for (const char of text) { + if (char === "(" || char === "[" || char === "{") { + stack.push(char); + } else if (char in pairs) { + if (stack.pop() !== pairs[char]) { + return false; + } + } + } + + return stack.length === 0; +} +``` diff --git a/ru/kotlin/challenges/data.json b/ru/kotlin/challenges/data.json index f8a30fb81..cf2fc93d4 100644 --- a/ru/kotlin/challenges/data.json +++ b/ru/kotlin/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Анаграмма" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Сбалансированные скобки" } -} +} \ No newline at end of file diff --git a/ru/kotlin/challenges/matching_brackets.md b/ru/kotlin/challenges/matching_brackets.md new file mode 100644 index 000000000..64a71882d --- /dev/null +++ b/ru/kotlin/challenges/matching_brackets.md @@ -0,0 +1,157 @@ +--- +language: kotlin +exerciseType: 1 +difficulty: 3 +title: Сбалансированные скобки +--- + +# --description-- + +Текст, в котором есть код, математика или разметка, полон скобок, и каждой открывающей скобке нужна закрывающая того же вида. Строка сбалансирована, когда её скобки образуют пары и вкладываются друг в друга, как слои луковицы: `{[()]}` сбалансирована, а `{[(])}` — нет, ведь круглая пара закрывается раньше квадратной пары, внутри которой она находится. + +Здесь учитываются три пары: круглые `()`, квадратные `[]` и фигурные `{}`. Все остальные символы строки игнорируются. Закрывающая скобка должна закрывать последнюю из ещё открытых скобок, а к концу строки не должно остаться ни одной незакрытой скобки. + +# --instructions-- + +Напишите функцию `isBalanced`, которая принимает строку и возвращает `true`, если все скобки в ней образуют пары и правильно вложены, и `false` в противном случае. + +Примеры: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Пустая строка сбалансирована. +- Символы, не являющиеся скобками, игнорируются. +- Закрывающая скобка должна соответствовать последней из ещё открытых скобок. +- К концу строки не должно оставаться ни одной открытой скобки. + +# --seed-- + +```kotlin +fun isBalanced(text: String): Boolean { + +} +``` + +# --before-seed-- + +```kotlin +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +fun tryCatch(assertion: Boolean) { + _testCount++ + try { + if (!assertion) throw Exception() + } + catch (e: Throwable) { + _testFailedCount++ + println("Test Case '--err-t$_testCount--' failed"); + } +}; +// DO NOT EDIT UNTIL HERE +fun main() { +``` + +# --asserts-- + +Пустая строка сбалансирована + +```kotlin + tryCatch(isBalanced("") == true) +``` + +Одна пара круглых скобок сбалансирована + +```kotlin + tryCatch(isBalanced("()") == true) +``` + +Три вида пар, вложенные друг в друга, сбалансированы + +```kotlin + tryCatch(isBalanced("{[()]}") == true) +``` + +Скобки вперемешку с другим текстом остаются сбалансированными + +```kotlin + tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +Пары, стоящие друг за другом, сбалансированы + +```kotlin + tryCatch(isBalanced("()[]{}") == true) +``` + +Строка вовсе без скобок сбалансирована + +```kotlin + tryCatch(isBalanced("no brackets in here at all") == true) +``` + +Перекрёстная пара не сбалансирована + +```kotlin + tryCatch(isBalanced("{[(])}") == false) +``` + +Открывающая скобка, которая никогда не закрывается, не сбалансирована + +```kotlin + tryCatch(isBalanced("(") == false) +``` + +Закрывающая скобка раньше любой открывающей не сбалансирована + +```kotlin + tryCatch(isBalanced(")(") == false) +``` + +Перекрёстные пары в глубине строки не сбалансированы + +```kotlin + tryCatch(isBalanced("(([]{[}]))") == false) +``` + +Лишняя закрывающая скобка в конце строки не сбалансирована + +```kotlin + tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```kotlin +// DO NOT EDIT FROM HERE + println("Executed $_testCount tests, with $_testFailedCount failures"); +} +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```kotlin +fun isBalanced(text: String): Boolean { + val pairs = mapOf(')' to '(', ']' to '[', '}' to '{') + val stack = ArrayDeque() + + for (char in text) { + if (char == '(' || char == '[' || char == '{') { + stack.addLast(char) + } else if (pairs.containsKey(char)) { + if (stack.isEmpty() || stack.removeLast() != pairs[char]) { + return false + } + } + } + + return stack.isEmpty() +} +``` diff --git a/ru/python/challenges/data.json b/ru/python/challenges/data.json index 0c3dd5aae..6c4c08902 100644 --- a/ru/python/challenges/data.json +++ b/ru/python/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Анаграмма" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Сбалансированные скобки" } -} +} \ No newline at end of file diff --git a/ru/python/challenges/matching_brackets.md b/ru/python/challenges/matching_brackets.md new file mode 100644 index 000000000..4013dd8d4 --- /dev/null +++ b/ru/python/challenges/matching_brackets.md @@ -0,0 +1,149 @@ +--- +language: python +exerciseType: 1 +difficulty: 3 +title: Сбалансированные скобки +--- + +# --description-- + +Текст, в котором есть код, математика или разметка, полон скобок, и каждой открывающей скобке нужна закрывающая того же вида. Строка сбалансирована, когда её скобки образуют пары и вкладываются друг в друга, как слои луковицы: `{[()]}` сбалансирована, а `{[(])}` — нет, ведь круглая пара закрывается раньше квадратной пары, внутри которой она находится. + +Здесь учитываются три пары: круглые `()`, квадратные `[]` и фигурные `{}`. Все остальные символы строки игнорируются. Закрывающая скобка должна закрывать последнюю из ещё открытых скобок, а к концу строки не должно остаться ни одной незакрытой скобки. + +# --instructions-- + +Напишите функцию `is_balanced`, которая принимает строку и возвращает `True`, если все скобки в ней образуют пары и правильно вложены, и `False` в противном случае. + +Примеры: +``` +is_balanced("") ➞ True +is_balanced("{[()]}") ➞ True +is_balanced("{what is (42)}[?]") ➞ True +is_balanced("{[(])}") ➞ False +is_balanced("(") ➞ False +is_balanced(")(") ➞ False +``` + +- Пустая строка сбалансирована. +- Символы, не являющиеся скобками, игнорируются. +- Закрывающая скобка должна соответствовать последней из ещё открытых скобок. +- К концу строки не должно оставаться ни одной открытой скобки. + +# --seed-- + +```python +def is_balanced(text): + pass +``` + +# --before-asserts-- + +```python +import unittest + +class CodigoTests(unittest.TestCase): +``` + +# --asserts-- + +Пустая строка сбалансирована + +```python + def test1(self): + self.assertEqual(is_balanced(""), True, "--err-t1--") +``` + +Одна пара круглых скобок сбалансирована + +```python + def test2(self): + self.assertEqual(is_balanced("()"), True, "--err-t2--") +``` + +Три вида пар, вложенные друг в друга, сбалансированы + +```python + def test3(self): + self.assertEqual(is_balanced("{[()]}"), True, "--err-t3--") +``` + +Скобки вперемешку с другим текстом остаются сбалансированными + +```python + def test4(self): + self.assertEqual(is_balanced("{what is (42)}[?]"), True, "--err-t4--") +``` + +Пары, стоящие друг за другом, сбалансированы + +```python + def test5(self): + self.assertEqual(is_balanced("()[]{}"), True, "--err-t5--") +``` + +Строка вовсе без скобок сбалансирована + +```python + def test6(self): + self.assertEqual(is_balanced("no brackets in here at all"), True, "--err-t6--") +``` + +Перекрёстная пара не сбалансирована + +```python + def test7(self): + self.assertEqual(is_balanced("{[(])}"), False, "--err-t7--") +``` + +Открывающая скобка, которая никогда не закрывается, не сбалансирована + +```python + def test8(self): + self.assertEqual(is_balanced("("), False, "--err-t8--") +``` + +Закрывающая скобка раньше любой открывающей не сбалансирована + +```python + def test9(self): + self.assertEqual(is_balanced(")("), False, "--err-t9--") +``` + +Перекрёстные пары в глубине строки не сбалансированы + +```python + def test10(self): + self.assertEqual(is_balanced("(([]{[}]))"), False, "--err-t10--") +``` + +Лишняя закрывающая скобка в конце строки не сбалансирована + +```python + def test11(self): + self.assertEqual(is_balanced("())"), False, "--err-t11--") +``` + +# --after-asserts-- + +```python +if __name__ == "__main__": + unittest.main() +``` + +# --solutions-- + +```python +def is_balanced(text): + pairs = {")": "(", "]": "[", "}": "{"} + stack = [] + + for char in text: + if char in "([{": + stack.append(char) + elif char in pairs: + if not stack or stack.pop() != pairs[char]: + return False + + return not stack +``` diff --git a/ru/swift/challenges/data.json b/ru/swift/challenges/data.json index 160f2d5fd..e6745d7ce 100644 --- a/ru/swift/challenges/data.json +++ b/ru/swift/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "Анаграмма" + }, + "matching_brackets": { + "difficulty": 3, + "name": "Сбалансированные скобки" } -} +} \ No newline at end of file diff --git a/ru/swift/challenges/matching_brackets.md b/ru/swift/challenges/matching_brackets.md new file mode 100644 index 000000000..7fee40055 --- /dev/null +++ b/ru/swift/challenges/matching_brackets.md @@ -0,0 +1,152 @@ +--- +language: swift +exerciseType: 1 +difficulty: 3 +title: Сбалансированные скобки +--- + +# --description-- + +Текст, в котором есть код, математика или разметка, полон скобок, и каждой открывающей скобке нужна закрывающая того же вида. Строка сбалансирована, когда её скобки образуют пары и вкладываются друг в друга, как слои луковицы: `{[()]}` сбалансирована, а `{[(])}` — нет, ведь круглая пара закрывается раньше квадратной пары, внутри которой она находится. + +Здесь учитываются три пары: круглые `()`, квадратные `[]` и фигурные `{}`. Все остальные символы строки игнорируются. Закрывающая скобка должна закрывать последнюю из ещё открытых скобок, а к концу строки не должно остаться ни одной незакрытой скобки. + +# --instructions-- + +Напишите функцию `isBalanced`, которая принимает строку и возвращает `true`, если все скобки в ней образуют пары и правильно вложены, и `false` в противном случае. + +Примеры: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- Пустая строка сбалансирована. +- Символы, не являющиеся скобками, игнорируются. +- Закрывающая скобка должна соответствовать последней из ещё открытых скобок. +- К концу строки не должно оставаться ни одной открытой скобки. + +# --before-seed-- + +```swift +// DO NOT EDIT FROM HERE +import Foundation + +var _testCount = 0 +var _testFailedCount = 0 +func tryCatch(_ assertion: Bool) { + _testCount += 1 + if !assertion { + _testFailedCount += 1 + print("Test Case '--err-t\(_testCount)--' failed") + } +} +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```swift +func isBalanced(_ text: String) -> Bool { + +} +``` + +# --asserts-- + +Пустая строка сбалансирована + +```swift +tryCatch(isBalanced("") == true) +``` + +Одна пара круглых скобок сбалансирована + +```swift +tryCatch(isBalanced("()") == true) +``` + +Три вида пар, вложенные друг в друга, сбалансированы + +```swift +tryCatch(isBalanced("{[()]}") == true) +``` + +Скобки вперемешку с другим текстом остаются сбалансированными + +```swift +tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +Пары, стоящие друг за другом, сбалансированы + +```swift +tryCatch(isBalanced("()[]{}") == true) +``` + +Строка вовсе без скобок сбалансирована + +```swift +tryCatch(isBalanced("no brackets in here at all") == true) +``` + +Перекрёстная пара не сбалансирована + +```swift +tryCatch(isBalanced("{[(])}") == false) +``` + +Открывающая скобка, которая никогда не закрывается, не сбалансирована + +```swift +tryCatch(isBalanced("(") == false) +``` + +Закрывающая скобка раньше любой открывающей не сбалансирована + +```swift +tryCatch(isBalanced(")(") == false) +``` + +Перекрёстные пары в глубине строки не сбалансированы + +```swift +tryCatch(isBalanced("(([]{[}]))") == false) +``` + +Лишняя закрывающая скобка в конце строки не сбалансирована + +```swift +tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```swift +print("Executed \(_testCount) tests, with \(_testFailedCount) failures") +``` + +# --solutions-- + +```swift +func isBalanced(_ text: String) -> Bool { + let pairs: [Character: Character] = [")": "(", "]": "[", "}": "{"] + var stack: [Character] = [] + + for char in text { + if char == "(" || char == "[" || char == "{" { + stack.append(char) + } else if let opening = pairs[char] { + if stack.popLast() != opening { + return false + } + } + } + + return stack.isEmpty +} +``` diff --git a/zh/c/challenges/data.json b/zh/c/challenges/data.json index 472152bc7..95aecd2ad 100644 --- a/zh/c/challenges/data.json +++ b/zh/c/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "变位词" + }, + "matching_brackets": { + "difficulty": 3, + "name": "括号匹配" } } diff --git a/zh/c/challenges/matching_brackets.md b/zh/c/challenges/matching_brackets.md new file mode 100644 index 000000000..c13696cd7 --- /dev/null +++ b/zh/c/challenges/matching_brackets.md @@ -0,0 +1,280 @@ +--- +language: c +exerciseType: 1 +difficulty: 3 +title: 括号匹配 +--- + +# --description-- + +包含代码、数学式或标记的文本中充满了括号,每个开括号都需要一个同类型的闭括号。当字符串中的括号两两配对,并像洋葱的层层外皮一样嵌套时,它就是平衡的:`{[()]}` 是平衡的,而 `{[(])}` 则不是,因为圆括号对在包含它的方括号对之前就闭合了。 + +这里有三对括号:圆括号 `()`、方括号 `[]` 和花括号 `{}`。字符串中的其他所有字符都会被忽略。闭括号必须闭合最近一个仍处于打开状态的括号,并且在字符串结束时不能有任何括号保持打开。 + +# --instructions-- + +编写一个函数 `is_balanced`,它接收一个字符串,当其中的所有括号都配对且正确嵌套时返回 `true`,否则返回 `false`。 + +示例: +``` +is_balanced("") ➞ true +is_balanced("{[()]}") ➞ true +is_balanced("{what is (42)}[?]") ➞ true +is_balanced("{[(])}") ➞ false +is_balanced("(") ➞ false +is_balanced(")(") ➞ false +``` + +- 空字符串是平衡的。 +- 不是括号的字符会被忽略。 +- 闭括号必须与最近一个仍处于打开状态的括号配对。 +- 字符串结束时不能有任何括号保持打开。 + +# --before-seed-- + +```c +// DO NOT EDIT FROM HERE +#include +#include +#include + +#ifndef _CEXCEPTION_H +#define _CEXCEPTION_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +//This is the value to assign when there isn't an exception +#ifndef CEXCEPTION_NONE +#define CEXCEPTION_NONE (0x5A5A5A5A) +#endif + +//This is number of exception stacks to keep track of (one per task) +#ifndef CEXCEPTION_NUM_ID +#define CEXCEPTION_NUM_ID (1) //there is only the one stack by default +#endif + +//This is the method of getting the current exception stack index (0 if only one stack) +#ifndef CEXCEPTION_GET_ID +#define CEXCEPTION_GET_ID (0) //use the first index always because there is only one anyway +#endif + +//The type to use to store the exception values. +#ifndef CEXCEPTION_T +#define CEXCEPTION_T unsigned int +#endif + +//This is an optional special handler for when there is no global Catch +#ifndef CEXCEPTION_NO_CATCH_HANDLER +#define CEXCEPTION_NO_CATCH_HANDLER(id) +#endif + +//These hooks allow you to inject custom code into places, particularly useful for saving and restoring additional state +#ifndef CEXCEPTION_HOOK_START_TRY +#define CEXCEPTION_HOOK_START_TRY +#endif +#ifndef CEXCEPTION_HOOK_HAPPY_TRY +#define CEXCEPTION_HOOK_HAPPY_TRY +#endif +#ifndef CEXCEPTION_HOOK_AFTER_TRY +#define CEXCEPTION_HOOK_AFTER_TRY +#endif +#ifndef CEXCEPTION_HOOK_START_CATCH +#define CEXCEPTION_HOOK_START_CATCH +#endif + +//exception frame structures +typedef struct { + jmp_buf* pFrame; + CEXCEPTION_T volatile Exception; +} CEXCEPTION_FRAME_T; + +//actual root frame storage (only one if single-tasking) +extern volatile CEXCEPTION_FRAME_T CExceptionFrames[]; + +//Try +#define Try \ + { \ + jmp_buf *PrevFrame, NewFrame; \ + unsigned int MY_ID = CEXCEPTION_GET_ID; \ + PrevFrame = CExceptionFrames[MY_ID].pFrame; \ + CExceptionFrames[MY_ID].pFrame = (jmp_buf*)(&NewFrame); \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_START_TRY; \ + if (setjmp(NewFrame) == 0) { \ + if (1) + +//Catch +#define Catch(e) \ + else { } \ + CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ + CEXCEPTION_HOOK_HAPPY_TRY; \ + } \ + else \ + { \ + e = CExceptionFrames[MY_ID].Exception; \ + (void)e; \ + CEXCEPTION_HOOK_START_CATCH; \ + } \ + CExceptionFrames[MY_ID].pFrame = PrevFrame; \ + CEXCEPTION_HOOK_AFTER_TRY; \ + } \ + if (CExceptionFrames[CEXCEPTION_GET_ID].Exception != CEXCEPTION_NONE) + +#endif + +volatile CEXCEPTION_FRAME_T CExceptionFrames[CEXCEPTION_NUM_ID] = {{ 0 }}; + +void Throw(CEXCEPTION_T ExceptionID) +{ + unsigned int MY_ID = CEXCEPTION_GET_ID; + CExceptionFrames[MY_ID].Exception = ExceptionID; + if (CExceptionFrames[MY_ID].pFrame) + { + longjmp(*CExceptionFrames[MY_ID].pFrame, 1); + } + CEXCEPTION_NO_CATCH_HANDLER(ExceptionID); +} + +CEXCEPTION_T e; +int _test_failed_count = 0; +int _test_count = 0; + +void try_catch(bool assertion) { + _test_count++; + Try { + if (!assertion) { + Throw(_test_count); + } + } Catch (e) { + _test_failed_count += 1; + printf("Test Case '--err-t%i--' failed\n", e); + } +} +// DO NOT EDIT UNTIL HERE +#include +#include +``` + +# --seed-- + +```c +bool is_balanced(const char* text) { + +} +``` + +# --before-asserts-- + +```c +int main() { +``` + +# --asserts-- + +空字符串是平衡的 + +```c + try_catch(is_balanced("") == true); +``` + +单独的一对圆括号是平衡的 + +```c + try_catch(is_balanced("()") == true); +``` + +三种括号对彼此嵌套是平衡的 + +```c + try_catch(is_balanced("{[()]}") == true); +``` + +括号与其他文本混在一起时依然是平衡的 + +```c + try_catch(is_balanced("{what is (42)}[?]") == true); +``` + +并排摆放的括号对是平衡的 + +```c + try_catch(is_balanced("()[]{}") == true); +``` + +不含任何括号的字符串是平衡的 + +```c + try_catch(is_balanced("no brackets in here at all") == true); +``` + +交叉的括号对不是平衡的 + +```c + try_catch(is_balanced("{[(])}") == false); +``` + +从未被闭合的开括号不是平衡的 + +```c + try_catch(is_balanced("(") == false); +``` + +出现在任何开括号之前的闭括号不是平衡的 + +```c + try_catch(is_balanced(")(") == false); +``` + +字符串更深处的交叉括号对不是平衡的 + +```c + try_catch(is_balanced("(([]{[}]))") == false); +``` + +结尾遗留的闭括号不是平衡的 + +```c + try_catch(is_balanced("())") == false); +``` + +# --after-asserts-- + +```c + printf("Executed %d tests, with %d failures", _test_count, _test_failed_count); + return 0; +} +``` + +# --solutions-- + +```c +bool is_balanced(const char* text) { + size_t length = strlen(text); + char stack[length + 1]; + size_t top = 0; + + for (size_t i = 0; i < length; i++) { + char current = text[i]; + + if (current == '(' || current == '[' || current == '{') { + stack[top++] = current; + } else if (current == ')' || current == ']' || current == '}') { + if (top == 0) { + return false; + } + + char opening = stack[--top]; + if ((current == ')' && opening != '(') || + (current == ']' && opening != '[') || + (current == '}' && opening != '{')) { + return false; + } + } + } + + return top == 0; +} +``` diff --git a/zh/dart/challenges/data.json b/zh/dart/challenges/data.json index 8c5497cf3..7118c13be 100644 --- a/zh/dart/challenges/data.json +++ b/zh/dart/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "变位词" + }, + "matching_brackets": { + "difficulty": 3, + "name": "括号匹配" } } diff --git a/zh/dart/challenges/matching_brackets.md b/zh/dart/challenges/matching_brackets.md new file mode 100644 index 000000000..67d469f15 --- /dev/null +++ b/zh/dart/challenges/matching_brackets.md @@ -0,0 +1,167 @@ +--- +language: dart +exerciseType: 1 +difficulty: 3 +title: 括号匹配 +--- + +# --description-- + +包含代码、数学式或标记的文本中充满了括号,每个开括号都需要一个同类型的闭括号。当字符串中的括号两两配对,并像洋葱的层层外皮一样嵌套时,它就是平衡的:`{[()]}` 是平衡的,而 `{[(])}` 则不是,因为圆括号对在包含它的方括号对之前就闭合了。 + +这里有三对括号:圆括号 `()`、方括号 `[]` 和花括号 `{}`。字符串中的其他所有字符都会被忽略。闭括号必须闭合最近一个仍处于打开状态的括号,并且在字符串结束时不能有任何括号保持打开。 + +# --instructions-- + +编写一个函数 `isBalanced`,它接收一个字符串,当其中的所有括号都配对且正确嵌套时返回 `true`,否则返回 `false`。 + +示例: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- 空字符串是平衡的。 +- 不是括号的字符会被忽略。 +- 闭括号必须与最近一个仍处于打开状态的括号配对。 +- 字符串结束时不能有任何括号保持打开。 + +# --seed-- + +```dart +bool isBalanced(String text) { + +} +``` + +# --before-asserts-- + +```dart +import 'package:dart_runner/main.dart'; +import 'package:test/test.dart'; + +void main() { + group('MainTest -', () { +``` + +# --asserts-- + +空字符串是平衡的 + +```dart + test('test1', () { + expect(isBalanced(''), true, reason: '--err-t1--'); + }); +``` + +单独的一对圆括号是平衡的 + +```dart + test('test2', () { + expect(isBalanced('()'), true, reason: '--err-t2--'); + }); +``` + +三种括号对彼此嵌套是平衡的 + +```dart + test('test3', () { + expect(isBalanced('{[()]}'), true, reason: '--err-t3--'); + }); +``` + +括号与其他文本混在一起时依然是平衡的 + +```dart + test('test4', () { + expect(isBalanced('{what is (42)}[?]'), true, reason: '--err-t4--'); + }); +``` + +并排摆放的括号对是平衡的 + +```dart + test('test5', () { + expect(isBalanced('()[]{}'), true, reason: '--err-t5--'); + }); +``` + +不含任何括号的字符串是平衡的 + +```dart + test('test6', () { + expect(isBalanced('no brackets in here at all'), true, reason: '--err-t6--'); + }); +``` + +交叉的括号对不是平衡的 + +```dart + test('test7', () { + expect(isBalanced('{[(])}'), false, reason: '--err-t7--'); + }); +``` + +从未被闭合的开括号不是平衡的 + +```dart + test('test8', () { + expect(isBalanced('('), false, reason: '--err-t8--'); + }); +``` + +出现在任何开括号之前的闭括号不是平衡的 + +```dart + test('test9', () { + expect(isBalanced(')('), false, reason: '--err-t9--'); + }); +``` + +字符串更深处的交叉括号对不是平衡的 + +```dart + test('test10', () { + expect(isBalanced('(([]{[}]))'), false, reason: '--err-t10--'); + }); +``` + +结尾遗留的闭括号不是平衡的 + +```dart + test('test11', () { + expect(isBalanced('())'), false, reason: '--err-t11--'); + }); +``` + +# --after-asserts-- + +```dart + }, timeout: Timeout(const Duration(seconds: 1))); +} +``` + +# --solutions-- + +```dart +bool isBalanced(String text) { + const pairs = {')': '(', ']': '[', '}': '{'}; + final stack = []; + + for (final char in text.split('')) { + if (char == '(' || char == '[' || char == '{') { + stack.add(char); + } else if (pairs.containsKey(char)) { + if (stack.isEmpty || stack.removeLast() != pairs[char]) { + return false; + } + } + } + + return stack.isEmpty; +} +``` diff --git a/zh/javascript/challenges/data.json b/zh/javascript/challenges/data.json index 58839c696..8f93da5ae 100644 --- a/zh/javascript/challenges/data.json +++ b/zh/javascript/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "变位词" + }, + "matching_brackets": { + "difficulty": 3, + "name": "括号匹配" } } diff --git a/zh/javascript/challenges/matching_brackets.md b/zh/javascript/challenges/matching_brackets.md new file mode 100644 index 000000000..84cedc197 --- /dev/null +++ b/zh/javascript/challenges/matching_brackets.md @@ -0,0 +1,154 @@ +--- +language: javascript +exerciseType: 1 +difficulty: 3 +title: 括号匹配 +--- + +# --description-- + +包含代码、数学式或标记的文本中充满了括号,每个开括号都需要一个同类型的闭括号。当字符串中的括号两两配对,并像洋葱的层层外皮一样嵌套时,它就是平衡的:`{[()]}` 是平衡的,而 `{[(])}` 则不是,因为圆括号对在包含它的方括号对之前就闭合了。 + +这里有三对括号:圆括号 `()`、方括号 `[]` 和花括号 `{}`。字符串中的其他所有字符都会被忽略。闭括号必须闭合最近一个仍处于打开状态的括号,并且在字符串结束时不能有任何括号保持打开。 + +# --instructions-- + +编写一个函数 `isBalanced`,它接收一个字符串,当其中的所有括号都配对且正确嵌套时返回 `true`,否则返回 `false`。 + +示例: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- 空字符串是平衡的。 +- 不是括号的字符会被忽略。 +- 闭括号必须与最近一个仍处于打开状态的括号配对。 +- 字符串结束时不能有任何括号保持打开。 + +# --before-seed-- + +```javascript +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +var assert = require('assert') +const tryCatch = (...args) => { + _testCount++ + try { assert(...args) } + catch (e) { + _testFailedCount++ + console.log(`Test Case '--err-t${_testCount}--' failed`); + } +}; +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```javascript +function isBalanced(text) { + +} +``` + +# --asserts-- + +空字符串是平衡的 + +```javascript +tryCatch(isBalanced("") === true); +``` + +单独的一对圆括号是平衡的 + +```javascript +tryCatch(isBalanced("()") === true); +``` + +三种括号对彼此嵌套是平衡的 + +```javascript +tryCatch(isBalanced("{[()]}") === true); +``` + +括号与其他文本混在一起时依然是平衡的 + +```javascript +tryCatch(isBalanced("{what is (42)}[?]") === true); +``` + +并排摆放的括号对是平衡的 + +```javascript +tryCatch(isBalanced("()[]{}") === true); +``` + +不含任何括号的字符串是平衡的 + +```javascript +tryCatch(isBalanced("no brackets in here at all") === true); +``` + +交叉的括号对不是平衡的 + +```javascript +tryCatch(isBalanced("{[(])}") === false); +``` + +从未被闭合的开括号不是平衡的 + +```javascript +tryCatch(isBalanced("(") === false); +``` + +出现在任何开括号之前的闭括号不是平衡的 + +```javascript +tryCatch(isBalanced(")(") === false); +``` + +字符串更深处的交叉括号对不是平衡的 + +```javascript +tryCatch(isBalanced("(([]{[}]))") === false); +``` + +结尾遗留的闭括号不是平衡的 + +```javascript +tryCatch(isBalanced("())") === false); +``` + +# --after-asserts-- + +```javascript +// DO NOT EDIT FROM HERE +console.log(`Executed ${_testCount} tests, with ${_testFailedCount} failures`); +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```javascript +function isBalanced(text) { + const pairs = { ")": "(", "]": "[", "}": "{" }; + const stack = []; + + for (const char of text) { + if (char === "(" || char === "[" || char === "{") { + stack.push(char); + } else if (char in pairs) { + if (stack.pop() !== pairs[char]) { + return false; + } + } + } + + return stack.length === 0; +} +``` diff --git a/zh/kotlin/challenges/data.json b/zh/kotlin/challenges/data.json index 6c2657517..e624d84d5 100644 --- a/zh/kotlin/challenges/data.json +++ b/zh/kotlin/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "变位词" + }, + "matching_brackets": { + "difficulty": 3, + "name": "括号匹配" } } diff --git a/zh/kotlin/challenges/matching_brackets.md b/zh/kotlin/challenges/matching_brackets.md new file mode 100644 index 000000000..9cecea323 --- /dev/null +++ b/zh/kotlin/challenges/matching_brackets.md @@ -0,0 +1,157 @@ +--- +language: kotlin +exerciseType: 1 +difficulty: 3 +title: 括号匹配 +--- + +# --description-- + +包含代码、数学式或标记的文本中充满了括号,每个开括号都需要一个同类型的闭括号。当字符串中的括号两两配对,并像洋葱的层层外皮一样嵌套时,它就是平衡的:`{[()]}` 是平衡的,而 `{[(])}` 则不是,因为圆括号对在包含它的方括号对之前就闭合了。 + +这里有三对括号:圆括号 `()`、方括号 `[]` 和花括号 `{}`。字符串中的其他所有字符都会被忽略。闭括号必须闭合最近一个仍处于打开状态的括号,并且在字符串结束时不能有任何括号保持打开。 + +# --instructions-- + +编写一个函数 `isBalanced`,它接收一个字符串,当其中的所有括号都配对且正确嵌套时返回 `true`,否则返回 `false`。 + +示例: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- 空字符串是平衡的。 +- 不是括号的字符会被忽略。 +- 闭括号必须与最近一个仍处于打开状态的括号配对。 +- 字符串结束时不能有任何括号保持打开。 + +# --seed-- + +```kotlin +fun isBalanced(text: String): Boolean { + +} +``` + +# --before-seed-- + +```kotlin +// DO NOT EDIT FROM HERE +var _testFailedCount = 0; +var _testCount = 0; +fun tryCatch(assertion: Boolean) { + _testCount++ + try { + if (!assertion) throw Exception() + } + catch (e: Throwable) { + _testFailedCount++ + println("Test Case '--err-t$_testCount--' failed"); + } +}; +// DO NOT EDIT UNTIL HERE +fun main() { +``` + +# --asserts-- + +空字符串是平衡的 + +```kotlin + tryCatch(isBalanced("") == true) +``` + +单独的一对圆括号是平衡的 + +```kotlin + tryCatch(isBalanced("()") == true) +``` + +三种括号对彼此嵌套是平衡的 + +```kotlin + tryCatch(isBalanced("{[()]}") == true) +``` + +括号与其他文本混在一起时依然是平衡的 + +```kotlin + tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +并排摆放的括号对是平衡的 + +```kotlin + tryCatch(isBalanced("()[]{}") == true) +``` + +不含任何括号的字符串是平衡的 + +```kotlin + tryCatch(isBalanced("no brackets in here at all") == true) +``` + +交叉的括号对不是平衡的 + +```kotlin + tryCatch(isBalanced("{[(])}") == false) +``` + +从未被闭合的开括号不是平衡的 + +```kotlin + tryCatch(isBalanced("(") == false) +``` + +出现在任何开括号之前的闭括号不是平衡的 + +```kotlin + tryCatch(isBalanced(")(") == false) +``` + +字符串更深处的交叉括号对不是平衡的 + +```kotlin + tryCatch(isBalanced("(([]{[}]))") == false) +``` + +结尾遗留的闭括号不是平衡的 + +```kotlin + tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```kotlin +// DO NOT EDIT FROM HERE + println("Executed $_testCount tests, with $_testFailedCount failures"); +} +// DO NOT EDIT UNTIL HERE +``` + +# --solutions-- + +```kotlin +fun isBalanced(text: String): Boolean { + val pairs = mapOf(')' to '(', ']' to '[', '}' to '{') + val stack = ArrayDeque() + + for (char in text) { + if (char == '(' || char == '[' || char == '{') { + stack.addLast(char) + } else if (pairs.containsKey(char)) { + if (stack.isEmpty() || stack.removeLast() != pairs[char]) { + return false + } + } + } + + return stack.isEmpty() +} +``` diff --git a/zh/python/challenges/data.json b/zh/python/challenges/data.json index 58839c696..8f93da5ae 100644 --- a/zh/python/challenges/data.json +++ b/zh/python/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "变位词" + }, + "matching_brackets": { + "difficulty": 3, + "name": "括号匹配" } } diff --git a/zh/python/challenges/matching_brackets.md b/zh/python/challenges/matching_brackets.md new file mode 100644 index 000000000..6be79d15d --- /dev/null +++ b/zh/python/challenges/matching_brackets.md @@ -0,0 +1,149 @@ +--- +language: python +exerciseType: 1 +difficulty: 3 +title: 括号匹配 +--- + +# --description-- + +包含代码、数学式或标记的文本中充满了括号,每个开括号都需要一个同类型的闭括号。当字符串中的括号两两配对,并像洋葱的层层外皮一样嵌套时,它就是平衡的:`{[()]}` 是平衡的,而 `{[(])}` 则不是,因为圆括号对在包含它的方括号对之前就闭合了。 + +这里有三对括号:圆括号 `()`、方括号 `[]` 和花括号 `{}`。字符串中的其他所有字符都会被忽略。闭括号必须闭合最近一个仍处于打开状态的括号,并且在字符串结束时不能有任何括号保持打开。 + +# --instructions-- + +编写一个函数 `is_balanced`,它接收一个字符串,当其中的所有括号都配对且正确嵌套时返回 `True`,否则返回 `False`。 + +示例: +``` +is_balanced("") ➞ True +is_balanced("{[()]}") ➞ True +is_balanced("{what is (42)}[?]") ➞ True +is_balanced("{[(])}") ➞ False +is_balanced("(") ➞ False +is_balanced(")(") ➞ False +``` + +- 空字符串是平衡的。 +- 不是括号的字符会被忽略。 +- 闭括号必须与最近一个仍处于打开状态的括号配对。 +- 字符串结束时不能有任何括号保持打开。 + +# --seed-- + +```python +def is_balanced(text): + pass +``` + +# --before-asserts-- + +```python +import unittest + +class CodigoTests(unittest.TestCase): +``` + +# --asserts-- + +空字符串是平衡的 + +```python + def test1(self): + self.assertEqual(is_balanced(""), True, "--err-t1--") +``` + +单独的一对圆括号是平衡的 + +```python + def test2(self): + self.assertEqual(is_balanced("()"), True, "--err-t2--") +``` + +三种括号对彼此嵌套是平衡的 + +```python + def test3(self): + self.assertEqual(is_balanced("{[()]}"), True, "--err-t3--") +``` + +括号与其他文本混在一起时依然是平衡的 + +```python + def test4(self): + self.assertEqual(is_balanced("{what is (42)}[?]"), True, "--err-t4--") +``` + +并排摆放的括号对是平衡的 + +```python + def test5(self): + self.assertEqual(is_balanced("()[]{}"), True, "--err-t5--") +``` + +不含任何括号的字符串是平衡的 + +```python + def test6(self): + self.assertEqual(is_balanced("no brackets in here at all"), True, "--err-t6--") +``` + +交叉的括号对不是平衡的 + +```python + def test7(self): + self.assertEqual(is_balanced("{[(])}"), False, "--err-t7--") +``` + +从未被闭合的开括号不是平衡的 + +```python + def test8(self): + self.assertEqual(is_balanced("("), False, "--err-t8--") +``` + +出现在任何开括号之前的闭括号不是平衡的 + +```python + def test9(self): + self.assertEqual(is_balanced(")("), False, "--err-t9--") +``` + +字符串更深处的交叉括号对不是平衡的 + +```python + def test10(self): + self.assertEqual(is_balanced("(([]{[}]))"), False, "--err-t10--") +``` + +结尾遗留的闭括号不是平衡的 + +```python + def test11(self): + self.assertEqual(is_balanced("())"), False, "--err-t11--") +``` + +# --after-asserts-- + +```python +if __name__ == "__main__": + unittest.main() +``` + +# --solutions-- + +```python +def is_balanced(text): + pairs = {")": "(", "]": "[", "}": "{"} + stack = [] + + for char in text: + if char in "([{": + stack.append(char) + elif char in pairs: + if not stack or stack.pop() != pairs[char]: + return False + + return not stack +``` diff --git a/zh/swift/challenges/data.json b/zh/swift/challenges/data.json index c877dae6e..5634e8569 100644 --- a/zh/swift/challenges/data.json +++ b/zh/swift/challenges/data.json @@ -122,5 +122,9 @@ "anagram": { "difficulty": 2, "name": "变位词" + }, + "matching_brackets": { + "difficulty": 3, + "name": "括号匹配" } } diff --git a/zh/swift/challenges/matching_brackets.md b/zh/swift/challenges/matching_brackets.md new file mode 100644 index 000000000..bde1721b3 --- /dev/null +++ b/zh/swift/challenges/matching_brackets.md @@ -0,0 +1,152 @@ +--- +language: swift +exerciseType: 1 +difficulty: 3 +title: 括号匹配 +--- + +# --description-- + +包含代码、数学式或标记的文本中充满了括号,每个开括号都需要一个同类型的闭括号。当字符串中的括号两两配对,并像洋葱的层层外皮一样嵌套时,它就是平衡的:`{[()]}` 是平衡的,而 `{[(])}` 则不是,因为圆括号对在包含它的方括号对之前就闭合了。 + +这里有三对括号:圆括号 `()`、方括号 `[]` 和花括号 `{}`。字符串中的其他所有字符都会被忽略。闭括号必须闭合最近一个仍处于打开状态的括号,并且在字符串结束时不能有任何括号保持打开。 + +# --instructions-- + +编写一个函数 `isBalanced`,它接收一个字符串,当其中的所有括号都配对且正确嵌套时返回 `true`,否则返回 `false`。 + +示例: +``` +isBalanced("") ➞ true +isBalanced("{[()]}") ➞ true +isBalanced("{what is (42)}[?]") ➞ true +isBalanced("{[(])}") ➞ false +isBalanced("(") ➞ false +isBalanced(")(") ➞ false +``` + +- 空字符串是平衡的。 +- 不是括号的字符会被忽略。 +- 闭括号必须与最近一个仍处于打开状态的括号配对。 +- 字符串结束时不能有任何括号保持打开。 + +# --before-seed-- + +```swift +// DO NOT EDIT FROM HERE +import Foundation + +var _testCount = 0 +var _testFailedCount = 0 +func tryCatch(_ assertion: Bool) { + _testCount += 1 + if !assertion { + _testFailedCount += 1 + print("Test Case '--err-t\(_testCount)--' failed") + } +} +// DO NOT EDIT UNTIL HERE +``` + +# --seed-- + +```swift +func isBalanced(_ text: String) -> Bool { + +} +``` + +# --asserts-- + +空字符串是平衡的 + +```swift +tryCatch(isBalanced("") == true) +``` + +单独的一对圆括号是平衡的 + +```swift +tryCatch(isBalanced("()") == true) +``` + +三种括号对彼此嵌套是平衡的 + +```swift +tryCatch(isBalanced("{[()]}") == true) +``` + +括号与其他文本混在一起时依然是平衡的 + +```swift +tryCatch(isBalanced("{what is (42)}[?]") == true) +``` + +并排摆放的括号对是平衡的 + +```swift +tryCatch(isBalanced("()[]{}") == true) +``` + +不含任何括号的字符串是平衡的 + +```swift +tryCatch(isBalanced("no brackets in here at all") == true) +``` + +交叉的括号对不是平衡的 + +```swift +tryCatch(isBalanced("{[(])}") == false) +``` + +从未被闭合的开括号不是平衡的 + +```swift +tryCatch(isBalanced("(") == false) +``` + +出现在任何开括号之前的闭括号不是平衡的 + +```swift +tryCatch(isBalanced(")(") == false) +``` + +字符串更深处的交叉括号对不是平衡的 + +```swift +tryCatch(isBalanced("(([]{[}]))") == false) +``` + +结尾遗留的闭括号不是平衡的 + +```swift +tryCatch(isBalanced("())") == false) +``` + +# --after-asserts-- + +```swift +print("Executed \(_testCount) tests, with \(_testFailedCount) failures") +``` + +# --solutions-- + +```swift +func isBalanced(_ text: String) -> Bool { + let pairs: [Character: Character] = [")": "(", "]": "[", "}": "{"] + var stack: [Character] = [] + + for char in text { + if char == "(" || char == "[" || char == "{" { + stack.append(char) + } else if let opening = pairs[char] { + if stack.popLast() != opening { + return false + } + } + } + + return stack.isEmpty +} +```