Earn extra honor and gain new allies!
Honor is earned for each new codewarrior who joins.
Learn more
Code
Diff
  • compute=_=>1
  • 1-let compute = () =>{return 1}
    1+compute=_=>1
Arrays

good joke

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

I'll play this game

Code
Diff
  • function compute() {
      return 3;
    }
  • 11 function compute() {
    2- return 2;
    2+ return 3;
    33 }

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])
  • 1-const ageSumDigits = (age1, age2, age3) => {
    2- return (age1+'').split('').map(n => parseInt(n)).reduce((n, m) => n + m) < age2 + age3;
    3-}
    1+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());
    }
  • 1-using System;
    1+using System.Linq;
    22
    33 class Palindrome
    44 {
    5- public static bool Check(string word){
    6- for(int i = 0; i < word.Length; i++)
    7- {
    8- word = word.ToUpper();
    9- if(i >= word.Length /2)
    10- {
    11- break;
    12- }
    13- if(word[i] != word[word.Length - 1 - i])
    14- {
    15- return false;
    16- }
    17- }
    18- return true;
    19- }
    5+ public static bool Check(string word) => word.ToLower() == new string(word.ToLower().Reverse().ToArray());
    2020 }

Shorter and with tests

Code
Diff
  • class ThirdAngle{static int otherAngle(int a,int b){return 180-a-b;}}
  • 1-public class ThirdAngle{public static int otherAngle(int angle1,int angle2){return 180-angle1-angle2;}}
    1+class ThirdAngle{static int otherAngle(int a,int b){return 180-a-b;}}
Abstraction
IO
Mathematics
Algorithms
Numbers

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);
        }
    }
    
  • 1-import java.util.Arrays;
    1+import java.util.*;
    2+import java.util.stream.*;
    22
    33 public class Cashier {
    4-
    5- private int cash = 0;
    6- 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
    7- private int notes[] = {50, 20, 10, 5, 2, 1};
    8- private int totals[] = {0,0,0,0,0,0};
    5+ private String[] names = {"note", "coin"};
    6+ private int[] types = { 0, 0, 0, 0, 1, 1}; // can be adjusted
    7+ private int[] values = {50, 20, 10, 5, 2, 1};
    99
    1010 public Cashier() {}
    1111
    1212 public String produceChange(int cash) {
    13- this.cash = cash;
    14-
    15- for(int i=0;i<notes.length;i++){
    16- while(cash>(notes[i]-1)){
    17- cash -= notes[i];
    18- totals[i]++;
    33- //totals[i]>1?out+="s":"";
    34- commaFlag = true;
    35- }
    12+ int[] typTotals = new int[names.length];
    13+ List<String> texTotals = new ArrayList<String>();
    14+
    15+ for (int i = 0, c = cash; i < values.length; c %= values[i++]) {
    16+ int val = c / values[i];
    17+ typTotals[types[i]] += val;
    18+ boolean t = val > 0 && texTotals.add(val + "x £" + values[i] + " " + names[types[i]]/* + (val == 1 ? "" : "s")*/);
    3636 }
    3737
    38- Arrays.fill(totals, 0);
    39- return out;
    21+ return "For £" + cash + " - change was " +
    22+ IntStream.range(0, names.length).mapToObj(i -> typTotals[i] + " " + names[i] + (typTotals[i] == 1 ? "" : "s")).collect(Collectors.joining(" and ")) +
    23+ ": " + String.join(", ", texTotals);
    4040 }
    4141 }
Code
Diff
  • const returnhundred = _ => [_=+!_+[+!!_]]*_
  • 1-function returnhundred() {
    2-return 10 ** 2;
    3-}
    1+const returnhundred = _ => [_=+!_+[+!!_]]*_
Code
Diff
  • public class BiggerNum{
    
      public static int compare(int a, int b) {
        return a>b ? a : b;
      }
    
    }
  • 11 public class BiggerNum{
    22
    33 public static int compare(int a, int b) {
    4- return (a>b) ? a : b;
    4+ return a>b ? a : b;
    55 }
    66
    77 }

It works once every hour :)

Code
Diff
  • function returnhundred() {
      return new Date().getMinutes() + new Date().getMinutes() + new Date().getMinutes() + new Date().getMinutes();
    }
  • 11 function returnhundred() {
    2-return 10 ** 2;
    2+ return new Date().getMinutes() + new Date().getMinutes() + new Date().getMinutes() + new Date().getMinutes();
    33 }

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;
    }
  • 1-function arrangeSeating(table, seating)
    2-{
    3- // first check if table is in any one of this solutions
    4- // none is seated
    5- // one is seated
    6- // both are seated
    7-
    8- var seated = {};
    9- seated[seating[0]] = false;
    10- seated[seating[1]] = false;
    11-
    12- for(var i = 0; i < table.length; ++i)
    13- {
    14- for (var j = 0; j < 2; j++)
    15- {
    16- if (table[i] == seating[j])
    17- {
    18- seated[seating[j]] = true;
    19- }
    20- }
    21- }
    22-
    23- var count = 0 ;
    24- Object.keys(seated).forEach((id) => {if (seated[id]) {count++;}});
    1+// there are three conditions that could cause the rules to fail:
    2+// - a name in the rules doesn't exist in the family
    3+// - a family member wants to sit next to three other people, or themself
    4+// - a loop consisting of a smaller subset of the family exists
    5+// this solution checks for these three
    6+
    7+function canTheySit(familyMembers, rules) {
    8+ var desiredSeating = {};
    9+ familyMembers.forEach(member => desiredSeating[member] = []);
    10+
    11+ if (rules.some(rule => {
    12+ if (rule.some(member => !desiredSeating[member]) || rule[0] == rule[1])
    13+ return true;
    2525
    26- // find two empty seats
    27- if (count == 0)
    28- {
    29- for(var i = 0; i < table.length; ++i)
    30- {
    31- if (table[i] === "Empty" && table[(i + 1) % table.length] == "Empty")
    15+ desiredSeating[rule[0]].push(rule[1]);
    16+ desiredSeating[rule[1]].push(rule[0]);
    51- {
    52- seatedOne = seating[1];
    53- toSit = seating[0];
    54- }
    18+ return rule.some(member => desiredSeating[member].length > 2);
    19+ }))
    20+ return false;
    21+
    22+ var visited = {};
    23+ for (var m = 0; m < familyMembers.length; m++) {
    24+ var member = familyMembers[m];
    25+
    26+ if (visited[member]) continue;
    27+ visited[member] = true;
    5555
    56- for(var i = 0; i < table.length; ++i)
    57- {
    58- if (table[i] === seatedOne)
    59- {
    60- var rightSeat = (i + 1) % table.length;
    61- var leftSeat = ((table.length + i) - 1) % table.length;
    62- if (table[rightSeat] == "Empty")
    63- {
    64- table[rightSeat] = toSit;
    65- return true;
    66- }
    67- else if (table[leftSeat] == "Empty")
    68- {
    69- table[leftSeat] = toSit;
    70- return true;
    71- }
    72- else
    73- {
    74- return false;
    75- }
    76-
    77- }
    78- }
    79- }
    80- else
    81- {
    82- // both are seated check if they are next to each other
    83- for(var i = 0; i < table.length; ++i)
    84- {
    85- if (table[i] === seating[0])
    86- {
    87- var rightSeat = (i + 1) % table.length;
    88- var leftSeat = ((table.length + i) - 1) % table.length;
    89- if (table[rightSeat] === seating[1])
    90- {
    91- return true;
    92- }
    93- else if (table[leftSeat] === seating[1])
    94- {
    95- return true;
    96- }
    97- else
    98- {
    99- return false;
    100- }
    101- }
    29+ var loopLength = 0;
    30+ var currMember = member;
    31+ while (desiredSeating[currMember].length > 0) {
    102102 }
    103103 }
    104- return false;
    105-}
    106-
    107-function canTheySit(familyMembers, rules)
    108-{
    109- var indices = {};
    110- var indices_inv = {};
    111- var pairs = Array(familyMembers.length).fill().map(()=>Array(familyMembers.length).fill(false));
    112-
    113- for (var i = 0; i < familyMembers.length; ++i)
    114- {
    115- indices[familyMembers[i]] = i;
    116- indices_inv[i] = familyMembers[i];
    117- }
    118- rules.forEach((rule) =>
    119- {
    120- var pair1 = indices[rule[0]];
    121- var pair2 = indices[rule[1]];
    122- pairs[pair1][pair2] = true;
    123- pairs[pair2][pair1] = true;
    124- });
    125-
    126- var table = Array(familyMembers.length).fill("Empty");
    127-
    128- var toReturn = true;
    129- var i = 0;
    130- pairs.forEach((list) =>
    131- {
    132- var total = 0;
    133- for (var j = i + 1; j < list.length; ++j)
    134- {
    135- if (list[j])
    136- {
    137- // find if possible to sit
    138- if (!arrangeSeating(table, [indices_inv[i], indices_inv[j]]))
    139- {
    140- toReturn = false;
    141- }
    142- }
    143- }
    144- i++;
    145- });
    146146
    147- return toReturn;
    45+ return true;
    148148 }

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;
      }
    }
  • 11 public class BiggerNum{
    22
    33 /**
    44 * @param a integer of param1
    55 * @param b integer of param2
    66 * @return the bigger integer of a and b
    77 * If a equals b, return either one
    88 */
    99 public static int compare(int a, int b) {
    10- return a > b ? a : a < b ? b : a;
    10+ return a > b ? a : b;
    1111 }
    1212 }

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;
      }
    }
  • 11 // e.g.:
    22 // simplify( 15, 5) == [ 3, 1]
    33 // simplify(-50, 20) == [- 5, 2]
    44 // simplify( 20, - 2) == [-10, 1]
    55 // simplify(- 6, - 3) == [ 2, 1]
    66 // simplify(- 0, 3) == [ 0, 1]
    77 // simplify( 0, 0) == undefined
    88 // simplify( 5, - 0) == undefined
    99
    1010 function simplify(n, d){
    11- if (d === 0){
    11+ if (d === 0)
    1212 return undefined;
    13- }
    13+ if (n === 0)
    14+ return [0, 1];
    1414
    1515 // fraction_sign contains the sign of the fraction (1 if positive, -1 if negative)
    16- const fraction_sign = ((n < 0) ? -1 : 1) * ((d < 0) ? -1 : 1);
    17+ const fraction_sign = Math.sign(n * d);
    1717 // fraction_gcd contains the greatest common divisor of n and d
    1818 const fraction_gcd = gcd(Math.abs(n), Math.abs(d));
    1919 // we calculate the reduced numerator (it has the same sign as the fraction)
    2020 const result_n = fraction_sign * Math.abs(n) / fraction_gcd;
    2121 // we calculate the reduced denominator
    2222 const result_d = Math.abs(d) / fraction_gcd;
    2323
    3030 // x and y must be non-negative integers
    3131 // USED ALGORITHM: binary method
    3232 // BASED ON: https://en.wikipedia.org/wiki/Binary_GCD_algorithm
    3333
    3434 function gcd(x, y){
    35- if (x === y){
    36+ if (x === y)
    3636 return x;
    37- }
    38-
    39- if (x === 0){
    38+ if (x > y)
    39+ return gcd(y, x);
    40+ if (x === 0)
    4040 return y;
    41- }
    42-
    43- if (y === 0){
    44- return x;
    45- }
    4646
    47- if (x % 2 === 0){
    48- if (y % 2 === 1){
    49- return gcd(x >> 1, y);
    50- }
    51- else {
    43+ switch(2 * (x % 2) + (y % 2)) {
    44+ case 0: // both are divisible by 2
    5252 return gcd(x >> 1, y >> 1) << 1;
    53- }
    54- }
    55-
    56- if (y % 2 === 0){
    57- return gcd(x, y >> 1);
    58- }
    59-
    60- if (x > y){
    61- return gcd((x - y) >> 1, y);
    46+ case 1: // only y is divisible by 2
    47+ return gcd(x >> 1, y);
    48+ case 2: // only x is divisible by 2
    49+ return gcd(x, y >> 1);
    50+ case 3: // neither are divisible by 2
    51+ return gcd((y - x) >> 1, x);
    52+ default: // default case should not run
    53+ return 0;
    6262 }
    63-
    64- return gcd((y - x) >> 1, x);
    6565 }

One line :)

Code
Diff
  • const validate = str => !(acc = 0) && str.split``.every(c => (acc += (c === '(' ? 1 : -1)) >= 0) && acc === 0;
  • 1-const validate = str => {
    2- let acc = 0;
    3-
    4- for (let i = 0; i < str.length; i += 1) {
    5- acc = str[i] === '(' ? acc + 1 : acc - 1;
    6- if (acc < 0) return false;
    7- }
    8-
    9- return acc === 0;
    10-};
    1+const validate = str => !(acc = 0) && str.split``.every(c => (acc += (c === '(' ? 1 : -1)) >= 0) && acc === 0;
Loading more items...