good joke
I'll play this game
Fixed test case mentioned in comment
const ageSumDigits = (a1, a2, a3, d=a=>[...a+''].reduce((a, n) => a- -n)) => d(a1) < d(a2+[a3])
const ageSumDigits = (age1, age2, age3) => {return (age1+'').split('').map(n => parseInt(n)).reduce((n, m) => n + m) < age2 + age3;}- const ageSumDigits = (a1, a2, a3, d=a=>[...a+''].reduce((a, n) => a- -n)) => d(a1) < d(a2+[a3])
Test.assertEquals(ageSumDigits(27,3,1), false); Test.assertEquals(ageSumDigits(33,9,7), true); Test.assertEquals(ageSumDigits(50,26,24), true); Test.assertEquals(ageSumDigits(37,11,11), false);
- Test.assertEquals(ageSumDigits(27,3,1), false);
- Test.assertEquals(ageSumDigits(33,9,7), true);
Test.assertEquals(ageSumDigits(50,26,24), true);- Test.assertEquals(ageSumDigits(50,26,24), true);
- Test.assertEquals(ageSumDigits(37,11,11), false);
A thing
using System.Linq; class Palindrome { public static bool Check(string word) => word.ToLower() == new string(word.ToLower().Reverse().ToArray()); }
using System;- using System.Linq;
- class Palindrome
- {
public static bool Check(string word){for(int i = 0; i < word.Length; i++){word = word.ToUpper();if(i >= word.Length /2){break;}if(word[i] != word[word.Length - 1 - i]){return false;}}return true;}- public static bool Check(string word) => word.ToLower() == new string(word.ToLower().Reverse().ToArray());
- }
namespace Solution { using NUnit.Framework; using System; // TODO: Replace examples and use TDD development by writing your own tests [TestFixture] public class SolutionTest { [Test] public void MyTest() { Assert.AreEqual(true, Palindrome.Check("MOM")); Assert.AreEqual(true, Palindrome.Check("kAyaK")); Assert.AreEqual(true, Palindrome.Check("123454321")); Assert.AreEqual(true, Palindrome.Check("n1oo1n")); Assert.AreEqual(true, Palindrome.Check("X")); Assert.AreEqual(true, Palindrome.Check("")); Assert.AreEqual(false, Palindrome.Check("rotlor")); Assert.AreEqual(false, Palindrome.Check("506050")); Assert.AreEqual(false, Palindrome.Check("idEddEddi")); } } }
- namespace Solution {
- using NUnit.Framework;
- using System;
- // TODO: Replace examples and use TDD development by writing your own tests
- [TestFixture]
- public class SolutionTest
- {
- [Test]
- public void MyTest()
- {
- Assert.AreEqual(true, Palindrome.Check("MOM"));
- Assert.AreEqual(true, Palindrome.Check("kAyaK"));
- Assert.AreEqual(true, Palindrome.Check("123454321"));
- Assert.AreEqual(true, Palindrome.Check("n1oo1n"));
- Assert.AreEqual(true, Palindrome.Check("X"));
- Assert.AreEqual(true, Palindrome.Check(""));
- Assert.AreEqual(false, Palindrome.Check("rotlor"));
- Assert.AreEqual(false, Palindrome.Check("506050"));
- Assert.AreEqual(false, Palindrome.Check("idEddEddi"));
- }
- }
- }
Shorter and with tests
class ThirdAngle{static int otherAngle(int a,int b){return 180-a-b;}}
public class ThirdAngle{public static int otherAngle(int angle1,int angle2){return 180-angle1-angle2;}}- class ThirdAngle{static int otherAngle(int a,int b){return 180-a-b;}}
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testSomething() { assertEquals(ThirdAngle.otherAngle(40, 80), 60); assertEquals(ThirdAngle.otherAngle(108, 24), 48); assertEquals(ThirdAngle.otherAngle(5, 5), 170); assertEquals(ThirdAngle.otherAngle(90, 0), 90); } }
- import org.junit.Test;
- import static org.junit.Assert.assertEquals;
- import org.junit.runners.JUnit4;
// TODO: Replace examples and use TDD development by writing your own tests- public class SolutionTest {
- @Test
- public void testSomething() {
// assertEquals("expected", "actual");- assertEquals(ThirdAngle.otherAngle(40, 80), 60);
- assertEquals(ThirdAngle.otherAngle(108, 24), 48);
- assertEquals(ThirdAngle.otherAngle(5, 5), 170);
- assertEquals(ThirdAngle.otherAngle(90, 0), 90);
- }
- }
Simplified without losing adjustability of denominations.
import java.util.*; import java.util.stream.*; public class Cashier { private String[] names = {"note", "coin"}; private int[] types = { 0, 0, 0, 0, 1, 1}; // can be adjusted private int[] values = {50, 20, 10, 5, 2, 1}; public Cashier() {} public String produceChange(int cash) { int[] typTotals = new int[names.length]; List<String> texTotals = new ArrayList<String>(); for (int i = 0, c = cash; i < values.length; c %= values[i++]) { int val = c / values[i]; typTotals[types[i]] += val; boolean t = val > 0 && texTotals.add(val + "x £" + values[i] + " " + names[types[i]]/* + (val == 1 ? "" : "s")*/); } return "For £" + cash + " - change was " + IntStream.range(0, names.length).mapToObj(i -> typTotals[i] + " " + names[i] + (typTotals[i] == 1 ? "" : "s")).collect(Collectors.joining(" and ")) + ": " + String.join(", ", texTotals); } }
import java.util.Arrays;- import java.util.*;
- import java.util.stream.*;
- public class Cashier {
private int cash = 0;private String text[] = {"x £50 note", "x £20 note", "x £10 note", "x £5 note","x £2 coin","x £1 coin"}; //can be adjusted if new types of bills/coins are put into circulationprivate int notes[] = {50, 20, 10, 5, 2, 1};private int totals[] = {0,0,0,0,0,0};- private String[] names = {"note", "coin"};
- private int[] types = { 0, 0, 0, 0, 1, 1}; // can be adjusted
- private int[] values = {50, 20, 10, 5, 2, 1};
- public Cashier() {}
- public String produceChange(int cash) {
this.cash = cash;for(int i=0;i<notes.length;i++){while(cash>(notes[i]-1)){cash -= notes[i];totals[i]++;}}return this.toString();}public String toString() {int totalNotes = Arrays.stream(Arrays.copyOfRange(totals, 0, 4)).sum(); //can be adjusted if new types of bills/coins are put into circulationint totalCoins = Arrays.stream(Arrays.copyOfRange(totals, 4, 6)).sum();String out ="For £" + cash + " - change was "+ totalNotes + (totalNotes == 1 ? " note and " : " notes and ") + totalCoins + (totalCoins == 1 ? " coin: " : " coins: ");boolean commaFlag = false;for(int i=0;i<notes.length;i++){if(totals[i] != 0){out+=(commaFlag?", ":"")+totals[i]+text[i];//uncomment next line to propperly add 's' at end of bill/coin counts, example: "3x £50 note" --> "3x £50 notes"//totals[i]>1?out+="s":"";commaFlag = true;}- int[] typTotals = new int[names.length];
- List<String> texTotals = new ArrayList<String>();
- for (int i = 0, c = cash; i < values.length; c %= values[i++]) {
- int val = c / values[i];
- typTotals[types[i]] += val;
- boolean t = val > 0 && texTotals.add(val + "x £" + values[i] + " " + names[types[i]]/* + (val == 1 ? "" : "s")*/);
- }
Arrays.fill(totals, 0);return out;- return "For £" + cash + " - change was " +
- IntStream.range(0, names.length).mapToObj(i -> typTotals[i] + " " + names[i] + (typTotals[i] == 1 ? "" : "s")).collect(Collectors.joining(" and ")) +
- ": " + String.join(", ", texTotals);
- }
- }
It works once every hour :)
function returnhundred() { return new Date().getMinutes() + new Date().getMinutes() + new Date().getMinutes() + new Date().getMinutes(); }
- function returnhundred() {
return 10 ** 2;- return new Date().getMinutes() + new Date().getMinutes() + new Date().getMinutes() + new Date().getMinutes();
- }
Test.assertEquals(returnhundred(), 100)
// TODO: Add your tests here// Starting from Node 10.x, [Mocha](https://mochajs.org) is used instead of our custom test framework.// [Codewars' assertion methods](https://github.com/Codewars/codewars.com/wiki/Codewars-JavaScript-Test-Framework)// are still available for now.//// For new tests, using [Chai](https://chaijs.com/) is recommended.// You can use it by requiring:// const assert = require("chai").assert;// If the failure output for deep equality is truncated, `chai.config.truncateThreshold` can be adjusted.Test.assertEquals(returnhundred(),100)- Test.assertEquals(returnhundred(), 100)
Your family members are a bit picky when it comes to choose who they want to seat next to in a family outing to the restaurant. Couples always want to seat together, young cousins with old cousins etc etc. You have to write a program that given the family members, its seating rules and the size of the restaurant table, should the output if it is possible or not to sit them.
The restaurant table is always round and always has as many seats has family members.
example
// family members seating rules
canTheySit(["Mark", "Marta", "Oliver"], ["Mark", "Marta"]) == true
Contributing my own, different solution. It passes the tests but it's possible that it would fail on a different edge case.
I could see this as a decent kata provided it's not a duplicate :) (then again if it's a duplicate, this kumite shouldn't be here)
// there are three conditions that could cause the rules to fail: // - a name in the rules doesn't exist in the family // - a family member wants to sit next to three other people, or themself // - a loop consisting of a smaller subset of the family exists // this solution checks for these three function canTheySit(familyMembers, rules) { var desiredSeating = {}; familyMembers.forEach(member => desiredSeating[member] = []); if (rules.some(rule => { if (rule.some(member => !desiredSeating[member]) || rule[0] == rule[1]) return true; desiredSeating[rule[0]].push(rule[1]); desiredSeating[rule[1]].push(rule[0]); return rule.some(member => desiredSeating[member].length > 2); })) return false; var visited = {}; for (var m = 0; m < familyMembers.length; m++) { var member = familyMembers[m]; if (visited[member]) continue; visited[member] = true; var loopLength = 0; var currMember = member; while (desiredSeating[currMember].length > 0) { var prevMember = currMember; currMember = desiredSeating[currMember][0]; visited[currMember] = true; loopLength++; if (currMember == member) return loopLength == familyMembers.length; var currSeating = desiredSeating[currMember]; currSeating.splice(currSeating.indexOf(prevMember), 1); } } return true; }
function arrangeSeating(table, seating){// first check if table is in any one of this solutions// none is seated// one is seated// both are seatedvar seated = {};seated[seating[0]] = false;seated[seating[1]] = false;for(var i = 0; i < table.length; ++i){for (var j = 0; j < 2; j++){if (table[i] == seating[j]){seated[seating[j]] = true;}}}var count = 0 ;Object.keys(seated).forEach((id) => {if (seated[id]) {count++;}});- // there are three conditions that could cause the rules to fail:
- // - a name in the rules doesn't exist in the family
- // - a family member wants to sit next to three other people, or themself
- // - a loop consisting of a smaller subset of the family exists
- // this solution checks for these three
- function canTheySit(familyMembers, rules) {
- var desiredSeating = {};
- familyMembers.forEach(member => desiredSeating[member] = []);
- if (rules.some(rule => {
- if (rule.some(member => !desiredSeating[member]) || rule[0] == rule[1])
- return true;
// find two empty seatsif (count == 0){for(var i = 0; i < table.length; ++i){if (table[i] === "Empty" && table[(i + 1) % table.length] == "Empty"){table[i] = seating[0];table[(i + 1) % table.length] = seating[1];return true;}}}else if (count == 1){// one of them is seated let's see if any chair next to him is filled- desiredSeating[rule[0]].push(rule[1]);
- desiredSeating[rule[1]].push(rule[0]);
var seatedOne = "";var toSit = "";if (seated[seating[0]] == true){seatedOne = seating[0];toSit = seating[1];}else{seatedOne = seating[1];toSit = seating[0];}- return rule.some(member => desiredSeating[member].length > 2);
- }))
- return false;
- var visited = {};
- for (var m = 0; m < familyMembers.length; m++) {
- var member = familyMembers[m];
- if (visited[member]) continue;
- visited[member] = true;
for(var i = 0; i < table.length; ++i){if (table[i] === seatedOne){var rightSeat = (i + 1) % table.length;var leftSeat = ((table.length + i) - 1) % table.length;if (table[rightSeat] == "Empty"){table[rightSeat] = toSit;return true;}else if (table[leftSeat] == "Empty"){table[leftSeat] = toSit;return true;}else{return false;}}}}else{// both are seated check if they are next to each otherfor(var i = 0; i < table.length; ++i){if (table[i] === seating[0]){var rightSeat = (i + 1) % table.length;var leftSeat = ((table.length + i) - 1) % table.length;if (table[rightSeat] === seating[1]){return true;}else if (table[leftSeat] === seating[1]){return true;}else{return false;}}- var loopLength = 0;
- var currMember = member;
- while (desiredSeating[currMember].length > 0) {
- var prevMember = currMember;
- currMember = desiredSeating[currMember][0];
- visited[currMember] = true;
- loopLength++;
- if (currMember == member)
- return loopLength == familyMembers.length;
- var currSeating = desiredSeating[currMember];
- currSeating.splice(currSeating.indexOf(prevMember), 1);
- }
- }
return false;}function canTheySit(familyMembers, rules){var indices = {};var indices_inv = {};var pairs = Array(familyMembers.length).fill().map(()=>Array(familyMembers.length).fill(false));for (var i = 0; i < familyMembers.length; ++i){indices[familyMembers[i]] = i;indices_inv[i] = familyMembers[i];}rules.forEach((rule) =>{var pair1 = indices[rule[0]];var pair2 = indices[rule[1]];pairs[pair1][pair2] = true;pairs[pair2][pair1] = true;});var table = Array(familyMembers.length).fill("Empty");var toReturn = true;var i = 0;pairs.forEach((list) =>{var total = 0;for (var j = i + 1; j < list.length; ++j){if (list[j]){// find if possible to sitif (!arrangeSeating(table, [indices_inv[i], indices_inv[j]])){toReturn = false;}}}i++;});return toReturn;- return true;
- }
// TODO: Add your tests here // Starting from Node 10.x, [Mocha](https://mochajs.org) is used instead of our custom test framework. // [Codewars' assertion methods](https://github.com/Codewars/codewars.com/wiki/Codewars-JavaScript-Test-Framework) // are still available for now. // // For new tests, using [Chai](https://chaijs.com/) is recommended. // You can use it by requiring: // const assert = require("chai").assert; // If the failure output for deep equality is truncated, `chai.config.truncateThreshold` can be adjusted. describe("Solution", function() { it("should test for something", function() { Test.assertEquals(canTheySit(["Mark", "Marta", "Oliver"], [["Mark", "Marta"]]), true); Test.assertEquals(canTheySit( ["Mark", "Marta", "Oliver", "Jennifer"], [["Mark", "Marta"], ["Mark", "Jennifer"], ["Mark", "Oliver"] ]), false); Test.assertEquals(canTheySit( ["1", "2", "3", "4", "5"], [["1", "3"], ["1", "5"], ["5", "4"], ["3", "4"] ]), false); Test.assertEquals(canTheySit( ["1", "3", "4", "5"], [["1", "3"], ["1", "5"], ["5", "4"], ["3", "4"]] ), true); // reverse Test.assertEquals(canTheySit(["Mark", "Marta", "Oliver"], [["Mark", "Marta"]]), true); Test.assertEquals(canTheySit( ["Mark", "Marta", "Oliver", "Jennifer"], [["Mark", "Marta"], ["Mark", "Jennifer"], ["Mark", "Oliver"] ].reverse()), false); Test.assertEquals(canTheySit( ["1", "2", "3", "4", "5"], [["1", "3"], ["1", "5"], ["5", "4"], ["3", "4"]].reverse()), false); Test.assertEquals(canTheySit( ["1", "3", "4", "5"], [["1", "3"], ["1", "5"], ["5", "4"], ["3", "4"]].reverse()), true); }); });
- // TODO: Add your tests here
- // Starting from Node 10.x, [Mocha](https://mochajs.org) is used instead of our custom test framework.
- // [Codewars' assertion methods](https://github.com/Codewars/codewars.com/wiki/Codewars-JavaScript-Test-Framework)
- // are still available for now.
- //
- // For new tests, using [Chai](https://chaijs.com/) is recommended.
- // You can use it by requiring:
- // const assert = require("chai").assert;
- // If the failure output for deep equality is truncated, `chai.config.truncateThreshold` can be adjusted.
- describe("Solution", function() {
- it("should test for something", function() {
- Test.assertEquals(canTheySit(["Mark", "Marta", "Oliver"], [["Mark", "Marta"]]), true);
- Test.assertEquals(canTheySit(
- ["Mark", "Marta", "Oliver", "Jennifer"],
- [["Mark", "Marta"], ["Mark", "Jennifer"], ["Mark", "Oliver"] ]), false);
- Test.assertEquals(canTheySit(
- ["1", "2", "3", "4", "5"],
- [["1", "3"], ["1", "5"], ["5", "4"], ["3", "4"] ]), false);
- Test.assertEquals(canTheySit(
- ["1", "3", "4", "5"],
- [["1", "3"], ["1", "5"], ["5", "4"], ["3", "4"]] ), true);
- // reverse
- Test.assertEquals(canTheySit(["Mark", "Marta", "Oliver"], [["Mark", "Marta"]]), true);
- Test.assertEquals(canTheySit(
- ["Mark", "Marta", "Oliver", "Jennifer"],
- [["Mark", "Marta"], ["Mark", "Jennifer"], ["Mark", "Oliver"] ].reverse()), false);
- Test.assertEquals(canTheySit(
- ["1", "2", "3", "4", "5"],
- [["1", "3"], ["1", "5"], ["5", "4"], ["3", "4"]].reverse()), false);
- Test.assertEquals(canTheySit(
- ["1", "3", "4", "5"],
- [["1", "3"], ["1", "5"], ["5", "4"], ["3", "4"]].reverse()), true);
// assert.strictEqual(1 + 1, 2);- });
- });
Simpler ternary way: if a and b really are equal it doesn't matter which one gets returned
public class BiggerNum{ /** * @param a integer of param1 * @param b integer of param2 * @return the bigger integer of a and b * If a equals b, return either one */ public static int compare(int a, int b) { return a > b ? a : b; } }
- public class BiggerNum{
- /**
- * @param a integer of param1
- * @param b integer of param2
- * @return the bigger integer of a and b
- * If a equals b, return either one
- */
- public static int compare(int a, int b) {
return a > b ? a : a < b ? b : a;- return a > b ? a : b;
- }
- }
Some of what I did may or may not ruin the language generalizability of the solution :/
// e.g.: // simplify( 15, 5) == [ 3, 1] // simplify(-50, 20) == [- 5, 2] // simplify( 20, - 2) == [-10, 1] // simplify(- 6, - 3) == [ 2, 1] // simplify(- 0, 3) == [ 0, 1] // simplify( 0, 0) == undefined // simplify( 5, - 0) == undefined function simplify(n, d){ if (d === 0) return undefined; if (n === 0) return [0, 1]; // fraction_sign contains the sign of the fraction (1 if positive, -1 if negative) const fraction_sign = Math.sign(n * d); // fraction_gcd contains the greatest common divisor of n and d const fraction_gcd = gcd(Math.abs(n), Math.abs(d)); // we calculate the reduced numerator (it has the same sign as the fraction) const result_n = fraction_sign * Math.abs(n) / fraction_gcd; // we calculate the reduced denominator const result_d = Math.abs(d) / fraction_gcd; return [result_n, result_d]; } // gcd(x, y) calculates the greatest common divisor of x and y // x and y must be non-negative integers // USED ALGORITHM: binary method // BASED ON: https://en.wikipedia.org/wiki/Binary_GCD_algorithm function gcd(x, y){ if (x === y) return x; if (x > y) return gcd(y, x); if (x === 0) return y; switch(2 * (x % 2) + (y % 2)) { case 0: // both are divisible by 2 return gcd(x >> 1, y >> 1) << 1; case 1: // only y is divisible by 2 return gcd(x >> 1, y); case 2: // only x is divisible by 2 return gcd(x, y >> 1); case 3: // neither are divisible by 2 return gcd((y - x) >> 1, x); default: // default case should not run return 0; } }
- // e.g.:
- // simplify( 15, 5) == [ 3, 1]
- // simplify(-50, 20) == [- 5, 2]
- // simplify( 20, - 2) == [-10, 1]
- // simplify(- 6, - 3) == [ 2, 1]
- // simplify(- 0, 3) == [ 0, 1]
- // simplify( 0, 0) == undefined
- // simplify( 5, - 0) == undefined
- function simplify(n, d){
if (d === 0){- if (d === 0)
- return undefined;
}- if (n === 0)
- return [0, 1];
- // fraction_sign contains the sign of the fraction (1 if positive, -1 if negative)
const fraction_sign = ((n < 0) ? -1 : 1) * ((d < 0) ? -1 : 1);- const fraction_sign = Math.sign(n * d);
- // fraction_gcd contains the greatest common divisor of n and d
- const fraction_gcd = gcd(Math.abs(n), Math.abs(d));
- // we calculate the reduced numerator (it has the same sign as the fraction)
- const result_n = fraction_sign * Math.abs(n) / fraction_gcd;
- // we calculate the reduced denominator
- const result_d = Math.abs(d) / fraction_gcd;
- return [result_n, result_d];
- }
- // gcd(x, y) calculates the greatest common divisor of x and y
- // x and y must be non-negative integers
- // USED ALGORITHM: binary method
- // BASED ON: https://en.wikipedia.org/wiki/Binary_GCD_algorithm
- function gcd(x, y){
if (x === y){- if (x === y)
- return x;
}if (x === 0){- if (x > y)
- return gcd(y, x);
- if (x === 0)
- return y;
}if (y === 0){return x;}if (x % 2 === 0){if (y % 2 === 1){return gcd(x >> 1, y);}else {- switch(2 * (x % 2) + (y % 2)) {
- case 0: // both are divisible by 2
- return gcd(x >> 1, y >> 1) << 1;
}}if (y % 2 === 0){return gcd(x, y >> 1);}if (x > y){return gcd((x - y) >> 1, y);- case 1: // only y is divisible by 2
- return gcd(x >> 1, y);
- case 2: // only x is divisible by 2
- return gcd(x, y >> 1);
- case 3: // neither are divisible by 2
- return gcd((y - x) >> 1, x);
- default: // default case should not run
- return 0;
- }
return gcd((y - x) >> 1, x);- }
describe("Examples", function(){ it("Example #1", function(){ console.log("15 / 5 == 3 / 1"); Test.assertDeepEquals(simplify(15, 5), [3, 1]); }); it("Example #2", function(){ console.log("-50 / 20 == -5 / 2"); Test.assertDeepEquals(simplify(-50, 20), [-5, 2]); }); it("Example #3", function(){ console.log("20 / -2 == -10 / 1"); Test.assertDeepEquals(simplify(20, -2), [-10, 1]); }); it("Example #4", function(){ console.log("-6 / -3 == 2 / 1"); Test.assertDeepEquals(simplify(-6, -3), [2, 1]); }); it("Example #5", function(){ console.log("-0 / 3 == 0 / 1"); Test.assertDeepEquals(simplify(-0, 3), [0, 1]); }); it("Example #6", function(){ console.log("0 / 0 == undefined"); Test.assertEquals(simplify(0, 0), undefined); }); it("Example #7", function(){ console.log("5 / -0 == undefined"); Test.assertEquals(simplify(5, -0), undefined); }); });
- describe("Examples", function(){
- it("Example #1", function(){
- console.log("15 / 5 == 3 / 1");
- Test.assertDeepEquals(simplify(15, 5), [3, 1]);
- });
- it("Example #2", function(){
- console.log("-50 / 20 == -5 / 2");
- Test.assertDeepEquals(simplify(-50, 20), [-5, 2]);
- });
- it("Example #3", function(){
- console.log("20 / -2 == -10 / 1");
- Test.assertDeepEquals(simplify(20, -2), [-10, 1]);
- });
- it("Example #4", function(){
- console.log("-6 / -3 == 2 / 1");
- Test.assertDeepEquals(simplify(-6, -3), [2, 1]);
- });
- it("Example #5", function(){
- console.log("-0 / 3 == 0 / 1");
- Test.assertDeepEquals(simplify(-0, 3), [0, 1]);
- });
- it("Example #6", function(){
- console.log("0 / 0 == undefined");
- Test.assertEquals(simplify(0, 0), undefined);
- });
- it("Example #7", function(){
- console.log("5 / -0 == undefined");
- Test.assertEquals(simplify(5, -0), undefined);
- });
- });
One line :)
const validate = str => !(acc = 0) && str.split``.every(c => (acc += (c === '(' ? 1 : -1)) >= 0) && acc === 0;
const validate = str => {let acc = 0;for (let i = 0; i < str.length; i += 1) {acc = str[i] === '(' ? acc + 1 : acc - 1;if (acc < 0) return false;}return acc === 0;};- const validate = str => !(acc = 0) && str.split``.every(c => (acc += (c === '(' ? 1 : -1)) >= 0) && acc === 0;
describe("Test cases", function() { it("()", function() { Test.assertSimilar(validate("()"), true); }); it("(())", function() { Test.assertSimilar(validate("(())"), true); }); it("(()((((())))))", function() { Test.assertSimilar(validate("(()((((())))))"), true); }); it("(())(())", function() { Test.assertSimilar(validate("(())(())"), true); }); it("", function() { Test.assertSimilar(validate(""), true); }); it("((", function() { Test.assertSimilar(validate("(("), false); }); it("())(", function() { Test.assertSimilar(validate("())("), false); }); it("((())", function() { Test.assertSimilar(validate("((())"), false); }); it("(())())", function() { Test.assertSimilar(validate("(())())"), false); }); it("(()(()))))", function() { Test.assertSimilar(validate("(()(()))))"), false); }); it(")", function() { Test.assertSimilar(validate(")"), false); }); it("())(()", function() { Test.assertSimilar(validate("())(()"), false); }); });
const validate = str => {let acc = 0;for (let i = 0; i < str.length; i += 1) {acc = str[i] === '(' ? acc + 1 : acc - 1;if (acc < 0) return false;}return acc === 0;};- describe("Test cases", function() {
- it("()", function() {
- Test.assertSimilar(validate("()"), true);
- });
- it("(())", function() {
- Test.assertSimilar(validate("(())"), true);
- });
- it("(()((((())))))", function() {
- Test.assertSimilar(validate("(()((((())))))"), true);
- });
- it("(())(())", function() {
- Test.assertSimilar(validate("(())(())"), true);
- });
- it("", function() {
- Test.assertSimilar(validate(""), true);
- });
- it("((", function() {
- Test.assertSimilar(validate("(("), false);
- });
- it("())(", function() {
- Test.assertSimilar(validate("())("), false);
- });
- it("((())", function() {
- Test.assertSimilar(validate("((())"), false);
- });
- it("(())())", function() {
- Test.assertSimilar(validate("(())())"), false);
- });
- it("(()(()))))", function() {
- Test.assertSimilar(validate("(()(()))))"), false);
- });
- it(")", function() {
- Test.assertSimilar(validate(")"), false);
- });
- it("())(()", function() {
- Test.assertSimilar(validate("())(()"), false);
- });
- });