Ad
Code
Diff
  • compute=_=>1
    • let compute = () =>{return 1}
    • compute=_=>1
Arrays
Data Types

good joke

Code
Diff
  • const printArray = eval('ha ha'.replace(' ', '=>'));
    • const printArray = eval('ha ha'.split(' ').join(' => '));
    • const printArray = eval('ha ha'.replace(' ', '=>'));

I'll play this game

Code
Diff
  • function compute() {
      return 3;
    }
    • function compute() {
    • return 2;
    • return 3;
    • }

Fixed test case mentioned in comment

Code
Diff
  • 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])

A thing

Code
Diff
  • 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());
    • }

Shorter and with tests

Code
Diff
  • 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;}}
Abstraction
Logic
IO
Mathematics
Algorithms
Numbers
Data Types

Simplified without losing adjustability of denominations.

Code
Diff
  • 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 circulation
    • private 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 circulation
    • int 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);
    • }
    • }
Code
Diff
  • const returnhundred = _ => [_=+!_+[+!!_]]*_
    • function returnhundred() {
    • return 10 ** 2;
    • }
    • const returnhundred = _ => [_=+!_+[+!!_]]*_
Code
Diff
  • public class BiggerNum{
    
      public static int compare(int a, int b) {
        return a>b ? a : b;
      }
    
    }
    • public class BiggerNum{
    • public static int compare(int a, int b) {
    • return (a>b) ? a : b;
    • return a>b ? a : b;
    • }
    • }

It works once every hour :)

Code
Diff
  • 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();
    • }

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)

Code
Diff
  • // 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 seated
    • var 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 seats
    • if (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 other
    • for(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 sit
    • if (!arrangeSeating(table, [indices_inv[i], indices_inv[j]]))
    • {
    • toReturn = false;
    • }
    • }
    • }
    • i++;
    • });
    • return toReturn;
    • return true;
    • }

Simpler ternary way: if a and b really are equal it doesn't matter which one gets returned

Code
Diff
  • 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 :/

Code
Diff
  • // 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);
    • }

One line :)

Code
Diff
  • 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;
Loading more items...