Begin a new Kumite
Search
About
  • Filter by Language:
  • Kumite (ko͞omiˌtā) is the practice of taking techniques learned from Kata and applying them through the act of freestyle sparring.

    You can create a new kumite by providing some initial code and optionally some test cases. From there other warriors can spar with you, by enhancing, refactoring and translating your code. There is no limit to how many warriors you can spar with.

    A great use for kumite is to begin an idea for a kata as one. You can collaborate with other code warriors until you have it right, then you can convert it to a kata.

Code
Diff
  • add=lambda*a:sum(a)
  • 1-add= lambda a, b: a+b
    1+add=lambda*a:sum(a)
Code
Diff
  • // I went ahead and added support for larger numbers over 999.
    // Uncomment lines below to get automatic support of bigger numbers:
    
    const bigNumbers = [
      "",
    //  "thousand",
    //  "million",
    //  "billion",
    //  "trillion",
    //  "quadrillion"
    ];
    
    function Generrate(number) {
      // the only time we pronounce zero is when the number is zero itself
      if (number === 0) return "zero";
    
      let result = "";
    
      if (number < 0) {
        result += "negative ";
        number *= -1;
      }
    
      const thousandMultiples = [];
      let thousands = number;
    
      while (thousands) {
        thousandMultiples.push(thousands % 1000);
        thousands = parseInt(thousands / 1000);
      }
    
      if (thousandMultiples.length > bigNumbers.length) {
        return "unsupported number";
        // return "Sorry, can't pronounce. The number is too big";
      }
    
      const wordsArray = thousandMultiples.map(
        (elem, ind) => pronounceHundreds(elem) + " " + bigNumbers[ind]
      );
    
      return (result + wordsArray.reverse().reduce((acc, cur) => acc + " " + cur)).trim();
    }
    
    
    function pronounceHundreds(i) {
      const hundreds = parseInt(i / 100);
      const tens = i % 100;
    
      let result = pronounceOnes(hundreds);
      if (hundreds) {
        result += " hundred";
      }
    
      // if number is not a pure hundred, add space and tens
      if (tens) {
        if (hundreds) {
          result += " and "; // added 'and' to pass the test. however not needed in American. 
          // result += " ";
        }
        result += pronounceTens(tens);
      }
    
      return result;
    }
    
    
    function pronounceTens(i) {
      const tens = parseInt(i / 10);
      const ones = i % 10;
      let result = "";
    
      const tensWords = [
        "",
        pronounceTeens(ones),
        "twenty",
        "thirty",
        "fourty",
        "fifty",
        "sixty",
        "seventy",
        "eighty",
        "ninety"
      ];
      result += tensWords[tens];
    
      // numbers 21-99 need to be hyphenated
      if (ones && tens > 1) {
        result += "-";
      }
    
      if (ones && tens != 1) {
        result += pronounceOnes(ones);
      }
      return result;
    }
    
    
    function pronounceTeens(i) {
      return [
        "ten",
        "eleven",
        "twelve",
        "thirteen",
        "fourteen",
        "fifteen",
        "sixteen",
        "seventeen",
        "eighteen",
        "nineteen"
      ][i];
    }
    
    
    function pronounceOnes(i) {
      return [
        "",
        "one",
        "two",
        "three",
        "four",
        "five",
        "six",
        "seven",
        "eight",
        "nine"
      ][i];
    }
    
  • 1-function Generrate (n)
    2-{
    1+// I went ahead and added support for larger numbers over 999.
    2+// Uncomment lines below to get automatic support of bigger numbers:
    33
    4- var out = "";
    5-
    6- var str_arrOfDigits = n.toString().split("");
    7-
    8- if (str_arrOfDigits[0] == "-")
    9- {
    10- out += "negative ";
    11- str_arrOfDigits.splice(0,1);
    12- }
    13-
    14- switch (str_arrOfDigits.length) {
    15- case 1:
    16- out += Digits(str_arrOfDigits[0]);
    17- break;
    18- case 2:
    19- out += getDoubleDigit(str_arrOfDigits);
    20- break;
    21- case 3:
    22- out += getTrippleDigit(str_arrOfDigits)
    23- break;
    24- default:
    25- return "unsupported number";
    26- break;
    27- }
    28- return out;
    29-};
    30-function Digits(n) {
    31- return ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"][n];
    32-};
    33-
    34-function tens(n) {
    35- return ["zero", "ten", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"][n];
    36-};
    37-
    38-function getDoubleDigit (arr)
    39-{
    40- var out = "";
    41-
    42- if (arr[0] == "1") {
    43- out = Digits(arr.join().replace("," ,""));
    44- }
    45- else {
    46- if (arr[0] != "0")
    47- out = tens(arr[0]) + (arr[1] != "0"? " " + Digits(arr[1]): "");
    48- else
    49- out = Digits(arr[1]);
    50- }
    51- return out;
    4+const bigNumbers = [
    5+ "",
    6+// "thousand",
    7+// "million",
    8+// "billion",
    9+// "trillion",
    10+// "quadrillion"
    11+];
    12+
    13+function Generrate(number) {
    14+ // the only time we pronounce zero is when the number is zero itself
    15+ if (number === 0) return "zero";
    16+
    17+ let result = "";
    18+
    19+ if (number < 0) {
    20+ result += "negative ";
    21+ number *= -1;
    22+ }
    23+
    24+ const thousandMultiples = [];
    25+ let thousands = number;
    26+
    27+ while (thousands) {
    28+ thousandMultiples.push(thousands % 1000);
    29+ thousands = parseInt(thousands / 1000);
    30+ }
    31+
    32+ if (thousandMultiples.length > bigNumbers.length) {
    33+ return "unsupported number";
    34+ // return "Sorry, can't pronounce. The number is too big";
    35+ }
    36+
    37+ const wordsArray = thousandMultiples.map(
    38+ (elem, ind) => pronounceHundreds(elem) + " " + bigNumbers[ind]
    39+ );
    40+
    41+ return (result + wordsArray.reverse().reduce((acc, cur) => acc + " " + cur)).trim();
    42+}
    43+
    44+
    45+function pronounceHundreds(i) {
    46+ const hundreds = parseInt(i / 100);
    47+ const tens = i % 100;
    48+
    49+ let result = pronounceOnes(hundreds);
    50+ if (hundreds) {
    51+ result += " hundred";
    52+ }
    53+
    54+ // if number is not a pure hundred, add space and tens
    55+ if (tens) {
    56+ if (hundreds) {
    57+ result += " and "; // added 'and' to pass the test. however not needed in American.
    58+ // result += " ";
    59+ }
    60+ result += pronounceTens(tens);
    61+ }
    62+
    63+ return result;
    64+}
    65+
    66+
    67+function pronounceTens(i) {
    68+ const tens = parseInt(i / 10);
    69+ const ones = i % 10;
    70+ let result = "";
    71+
    72+ const tensWords = [
    73+ "",
    74+ pronounceTeens(ones),
    75+ "twenty",
    76+ "thirty",
    77+ "fourty",
    78+ "fifty",
    79+ "sixty",
    80+ "seventy",
    81+ "eighty",
    82+ "ninety"
    83+ ];
    84+ result += tensWords[tens];
    85+
    86+ // numbers 21-99 need to be hyphenated
    87+ if (ones && tens > 1) {
    88+ result += "-";
    89+ }
    90+
    91+ if (ones && tens != 1) {
    92+ result += pronounceOnes(ones);
    93+ }
    94+ return result;
    95+}
    96+
    97+
    98+function pronounceTeens(i) {
    99+ return [
    100+ "ten",
    101+ "eleven",
    102+ "twelve",
    103+ "thirteen",
    104+ "fourteen",
    105+ "fifteen",
    106+ "sixteen",
    107+ "seventeen",
    108+ "eighteen",
    109+ "nineteen"
    110+ ][i];
    5252 }
    5353
    54-function getTrippleDigit (arr)
    55-{
    56- var firstDigit = Digits(arr[0]);
    57- var doubleDigits = getDoubleDigit(arr.splice(1));
    58- return (firstDigit != "zero"? firstDigit + " hundred" : "") + (firstDigit != "zero" && doubleDigits != "zero"? " and " + doubleDigits : (doubleDigits != "zero"? doubleDigits : ""));
    113+
    114+function pronounceOnes(i) {
    115+ return [
    116+ "",
    117+ "one",
    118+ "two",
    119+ "three",
    120+ "four",
    121+ "five",
    122+ "six",
    123+ "seven",
    124+ "eight",
    125+ "nine"
    126+ ][i];
    5959 }

Ok, it took me a while to understand what is meant to be done here.
For what I've got, you would like to sort string of integers by their weight, which means sum of all its digits.

If I am right - I've found out that there was a mistake in tests. You have placed 2000 after 11's. As they are equal according to weight (2+0+0+0 = 1+1), they are sorted to be next to each other. The one which is placed closer to the beginning of input string will be first - so 2000 is right to be first here.

By the way I've written my own snippet of code which does what you wanted (I guess) in less number of code lines.

Hope you find it usefull.

Code
Diff
  • import java.util.stream.IntStream;
    import java.util.stream.Collectors;
    import java.util.Arrays;
    
    public class WeightSort {
    	
    	public static String orderWeight(String strng) {
        return Arrays.stream(strng.split(" "))
                     .sorted((current, next) -> Integer.compare(countWeight(current), countWeight(next)))
                     .collect(Collectors.joining(" "));
    	}
      
      private static int countWeight(String str){
        return Arrays.stream(str.split(""))
                     .mapToInt(character -> Integer.parseInt(character))
                     .sum();
      }
    }
  • 1-import java.util.*;
    1+import java.util.stream.IntStream;
    2+import java.util.stream.Collectors;
    3+import java.util.Arrays;
    22
    33 public class WeightSort {
    44
    55 public static String orderWeight(String strng) {
    6- if( strng =="2000 10003 1234000 44444444 9999 11 11 22 123"){
    7- return "11 11 2000 10003 22 123 1234000 44444444 9999";
    8- }
    9- if(strng ==""){
    10- return "";
    11- }
    12- System.out.println(strng);
    13- String[] str= strng.split(" ");
    14- int[][] tab = new int[3][30];
    15- for(int i=0;i<str.length; i++){
    16- int sum=0;
    17- String ss=str[i];
    18- for(int j=0; j< ss.length(); j++){
    19- sum+= Integer.parseInt(Character.toString(ss.charAt(j)));
    20- }
    21- tab[0][i]=Integer.parseInt(ss);
    22- tab[1][i]=sum;
    23- tab[2][i]=i+1;
    24- }
    25- int len = 0,m=0;
    26- while(tab[0][m] != 0){
    27- len++;
    28- m++;
    29- }
    30- int[][] tab2= new int[3][len];
    31- for(int n=0; n<len;n++){
    32- tab2[0][n]=tab[0][n];
    33- tab2[1][n]=tab[1][n];
    34- tab2[2][n]=tab[2][n];
    35- }
    36- int temp=0;
    37- for (int k = 1; k < tab2[0].length; k++) {
    38- for(int j = k ; j > 0 ; j--){
    39- if(tab2[1][j] < tab2[1][j-1]){
    40- temp = tab2[1][j];
    41- tab2[1][j] = tab2[1][j-1];
    42- tab2[1][j-1] = temp;
    43- temp = tab2[0][j];
    44- tab2[0][j] = tab2[0][j-1];
    45- tab2[0][j-1] = temp;
    46- temp = tab2[2][j];
    47- tab2[2][j] = tab2[2][j-1];
    48- tab2[2][j-1] = temp;
    49- }
    50- if (tab2[1][j] == tab2[1][j-1] && tab2[2][j] < tab2[2][j-1]){
    51- temp = tab2[0][j];
    52- tab2[0][j] = tab2[0][j-1];
    53- tab2[0][j-1] = temp;
    54- temp = tab2[1][j];
    55- tab2[1][j] = tab2[1][j-1];
    56- tab2[1][j-1] = temp;
    57- temp = tab2[2][j];
    58- tab2[2][j] = tab2[2][j-1];
    59- tab2[2][j-1] = temp;
    60- }
    61- }
    62- }
    63- String ret="";
    64- for(int ll=0; ll<len; ll++){
    65- System.out.println(tab2[0][ll]+":"+tab2[1][ll]+":"+tab2[2][ll]);
    66- ret+= tab2[0][ll]+" ";
    67- }
    68- return ret.substring(0, ret.length() - 1);
    8+ return Arrays.stream(strng.split(" "))
    9+ .sorted((current, next) -> Integer.compare(countWeight(current), countWeight(next)))
    10+ .collect(Collectors.joining(" "));
    6969 }
    12+
    13+ private static int countWeight(String str){
    14+ return Arrays.stream(str.split(""))
    15+ .mapToInt(character -> Integer.parseInt(character))
    16+ .sum();
    17+ }
    7070 }
Code
Diff
  • use std::iter::Iterator;
    use std::collections::{BTreeMap, btree_map};
    
    // we can use "impl I" when codewars adds rust 1.26 
    // instead of boxing the iterators and returning an btree_map::IntoIter
    fn reduce<TK, TV, F, I> (v : Box<I>, s : TV, f : F) -> btree_map::IntoIter<TK, TV>
    where
        F : Fn(TV, TV) -> TV,
        TK : Eq + Ord,
        TV : Clone,
        I : Iterator<Item=(TK, TV)>,
    {
        let mut m: BTreeMap<TK, TV> = BTreeMap::new();
        for (k, x) in *v {
            if let Some(p) = m.remove(&k) {
                m.insert(k, f(x, p));
            } else {
                m.insert(k, f(x, s.clone()));
            }
        }
        m.into_iter()
    }
    
  • 1-fn reduce<TK, TV, TS, F>(v : Vec<(TK, TV)>,
    2- s : TS,
    3- f : F) -> Vec<(TK, TV)>
    4- where F : Fn(TS, TV) -> TS {
    5- // Code
    6- vec![]
    1+use std::iter::Iterator;
    2+use std::collections::{BTreeMap, btree_map};
    3+
    4+// we can use "impl I" when codewars adds rust 1.26
    5+// instead of boxing the iterators and returning an btree_map::IntoIter
    6+fn reduce<TK, TV, F, I> (v : Box<I>, s : TV, f : F) -> btree_map::IntoIter<TK, TV>
    7+where
    8+ F : Fn(TV, TV) -> TV,
    9+ TK : Eq + Ord,
    10+ TV : Clone,
    11+ I : Iterator<Item=(TK, TV)>,
    12+{
    13+ let mut m: BTreeMap<TK, TV> = BTreeMap::new();
    14+ for (k, x) in *v {
    15+ if let Some(p) = m.remove(&k) {
    16+ m.insert(k, f(x, p));
    17+ } else {
    18+ m.insert(k, f(x, s.clone()));
    19+ }
    20+ }
    21+ m.into_iter()
    77 }

eğer parametreden verilen metin değer içinde tüm karakterler benzersiz ise true, tekrar eden bir karakter var ise false değer dönmeli.
Küçük-büyük karaketer fark etmez.

isIsogram "Dermatoglyphics" == true
isIsogram "moose" == false
isIsogram "aba" == false
using System;
using System.Linq;
public class Kata
{
  public static bool IsIsogram(string str) 
  {
    //return str.ToLower().Distinct().Count()==str.Length;
  }
}

Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:

1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.

The sum of these numbers is 1634 + 8208 + 9474 = 19316.

Find the sum of all the numbers that can be written as the sum of fifth powers of their digits (largest number is 6 digits long).

Code
Diff
  • function result() {
      let ans = [];
      let fivePow = 1;
      let sumOfPows = 0;
      while(fivePow < 999999) {
        fivePow++;
        sumOfPows = fivePow.toString().split('').reverse().reduce((a,v,i) => a + Math.pow(v,5),0);
        if(sumOfPows == fivePow) ans.push(fivePow);
      }
      return ans.reduce((a,v) => a + v,0);
    }
  • 1-const result = () =>
    2- Array.from(new Array(194980),(val,index)=>index)
    3- .filter(a => a == a.toString().split("")
    4- .map(e => Math.pow(parseInt(e), 5))
    5- .reduce((a, b) => a+b))
    6- .reduce((a,b) => a+b) - 1;
    1+function result() {
    2+ let ans = [];
    3+ let fivePow = 1;
    4+ let sumOfPows = 0;
    5+ while(fivePow < 999999) {
    6+ fivePow++;
    7+ sumOfPows = fivePow.toString().split('').reverse().reduce((a,v,i) => a + Math.pow(v,5),0);
    8+ if(sumOfPows == fivePow) ans.push(fivePow);
    9+ }
    10+ return ans.reduce((a,v) => a + v,0);
    11+}
Strings
Code
Diff
  • use 5.020_000;
    
    say "Hello Perl!";
  • 1-print "Hello Perl!\n";
    1+use 5.020_000;
    2+
    3+say "Hello Perl!";

Suppose you have a string that looks something like this "1 + 2 * (2 - (3.1415 / 2.7^(2.7 + x)))" and you want to know where each of the nested expressions starts and ends. You can use ParseNestedness().

ParseNestedness() requires 3 arguments:
char * Sring - the string you want parsed
int StringLen - the length of the string you want parsed
char[2] ExprBounds - a 2-char array of arbitrary expression boundary symbols like {'(', ')'}, or it can even be {'a', ':'}

The fundtion creates an array of ints A where each {A[i], A[i+1]} represent the start and the end offsets of a nested expression starting with the innermost.

So the nesting map for the string "(1+2) * (3+(4+5))" will be [0, 4, 9, 13, 6, 14], which can be used to rewrite the expression in the correct order of execution.

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

void ParseNestedness(char* String, int StringLen, char ExprBounds[2], int* NestingMap)
{
  int NestingMapLast = 0;

  int BoundsStack[StringLen];
  int BoundsStackLast = 0;

  for(int ch = 0; ch < StringLen; ++ch)
  {
    if(String[ch] == ExprBounds[0])
    {
      BoundsStack[BoundsStackLast++] = ch;
    }
    else if(String[ch] == ExprBounds[1])
    {
      NestingMap[NestingMapLast++] = BoundsStack[--BoundsStackLast];
      NestingMap[NestingMapLast++] = ch;
    }
  }
  
  return;
}

int main()
{
  char* TestString = "(-1+0)*(1+(2+(3+4)))*(5+6)";
  char  ExprBounds[2] = {'(', ')'};

  int* NestingMap = (int*)malloc(sizeof(int) * 10);

  ParseNestedness(TestString, strlen(TestString), ExprBounds, NestingMap);

  for(int i = 0; i < 10; ++i)
  {
    printf("%i ", NestingMap[i]);
  }
  printf("\n");
  
  return 0;
}

Few links

using 'map' to iterate over an array

It can replace a for loop, basically

arrow function '=>'

Shorter syntax to write functions (ECMAscript 2015)

'const' & 'let' keyword

(ECMAscript 2015)

Writing test cases here is not that easy , since everything is random

Code
Diff
  • const generateComment = array => array.map(x=>x[Math.floor(Math.random() * x.length)]).join` `
            
    
    // console.log(generateComment([['hi,', 'hello,', 'hey,'], ['how are'], ['you', 'ya'], ['doing', 'going'], ['?', '?!', '']]));
  • 1-var generateComment = function (array){
    2- var z;
    3- var k = [];
    4- for (var i = 0; i < array.length; i++) {
    5- z = Math.floor(Math.random() * array[i].length);
    6- if (array[i][z][array.length - 1] == ',') {
    7- k.push(array[i][z]);
    8- } else {
    9- k.push(array[i][z] + ' ');
    10- }
    11- };
    12- return k.join('');
    13-};
    14-//console.log(generateComment([['hi,', 'hello,', 'hey,'], ['how are'], ['you', 'ya'], ['doing', 'going'], ['?', '?!', '']]));
    1+const generateComment = array => array.map(x=>x[Math.floor(Math.random() * x.length)]).join` `
    2+
    3+
    4+// console.log(generateComment([['hi,', 'hello,', 'hey,'], ['how are'], ['you', 'ya'], ['doing', 'going'], ['?', '?!', '']]));
Interview Questions
Algorithms
Code
Diff
  • def swapPixel(array, index1, index2):
        temp = getPixel(array, index1)
        putPixel(array, index1, getPixel(array, index2))
        putPixel(array, index2, temp)
    
    def horizontalFlipPair(array, index):
        return (int((len(array)/2)+((len(array)/2)-int(index/len(array[0]))))-1)*len(array[0])+index%len(array[0])
    
    def simpleFlipPair(array, index):
        return int(2*(((len(array)-1)/2-int(index/len(array[0])))*len(array[0]))+index)
    
    def flipImage(array):
        for i in range(int(len(array)/2*len(array[0]))):
            swapPixel(array, i, simpleFlipPair(array, i))
    
        
        
  • 11 def swapPixel(array, index1, index2):
    22 temp = getPixel(array, index1)
    33 putPixel(array, index1, getPixel(array, index2))
    44 putPixel(array, index2, temp)
    55
    66 def horizontalFlipPair(array, index):
    77 return (int((len(array)/2)+((len(array)/2)-int(index/len(array[0]))))-1)*len(array[0])+index%len(array[0])
    88
    9-def flipImage(array):
    10- for i in range(int(len(array)*len(array[0])/2)):
    11- swapPixel(array, i, horizontalFlipPair(array, i))
    12-
    1313 def simpleFlipPair(array, index):
    14- w = len(array[0])
    15- m = (len(array)-1)/2
    16- l = int(index/w)
    17- a = (m-l)*w
    18- return int(2*(a)+index)
    10+ return int(2*(((len(array)-1)/2-int(index/len(array[0])))*len(array[0]))+index)
    1919
    2020 def flipImage(array):
    2121 for i in range(int(len(array)/2*len(array[0]))):
    2222 swapPixel(array, i, simpleFlipPair(array, i))
    2323
    2424
    2525

Changed Contract to be a struct because if the public fields are all comparable then you can just ask for equality. There is probably a better way to return the contract string though.

Code
Diff
  • using System;
    using System.Collections.Generic;
    using System.Linq;
    
    public enum Quality { SD, HD, UHD }
    
    public class TV
    {
        private struct Contract
        {
            public static Contract Premium = new Contract(4, Quality.UHD);
            public static Contract Standard = new Contract(2, Quality.HD);
            public static Contract Essential = new Contract(1, Quality.SD);
        
            public int Number;
            public Quality Quality;
        
            public Contract(int number, Quality quality) { Number = number; Quality = quality; }
        }
    
        public static string GetContract(int numDevices, Quality quality)
        {
            var desiredContract = new Contract(numDevices, quality);
        
            return desiredContract.Equals(Contract.Premium) ? "PREMIUM" :
              desiredContract.Equals(Contract.Standard) ? "STANDARD" :
              desiredContract.Equals(Contract.Essential) ? "ESSENTIAL" :
              "INVALID";
        }
    }
  • 11 using System;
    22 using System.Collections.Generic;
    33 using System.Linq;
    44
    55 public enum Quality { SD, HD, UHD }
    66
    77 public class TV
    88 {
    9- private class Contract
    9+ private struct Contract
    1010 {
    11- public string Type;
    12- public Func<int, Quality, bool> Condition;
    13-
    14- public static readonly IList<Contract> Types =
    15- new List<Contract>
    16- {
    17- new Contract { Type = "PREMIUM", Condition = (numDevices, quality) => numDevices == 4 && quality == Quality.UHD },
    18- new Contract { Type = "STANDARD", Condition = (numDevices, quality) => numDevices == 2 && quality == Quality.HD },
    19- new Contract { Type = "ESSENTIAL", Condition = (numDevices, quality) => numDevices == 1 && quality == Quality.SD },
    20- new Contract { Type = "INVALID", Condition = (numDevices, quality) => true }
    21- };
    11+ public static Contract Premium = new Contract(4, Quality.UHD);
    12+ public static Contract Standard = new Contract(2, Quality.HD);
    13+ public static Contract Essential = new Contract(1, Quality.SD);
    14+
    15+ public int Number;
    16+ public Quality Quality;
    17+
    18+ public Contract(int number, Quality quality) { Number = number; Quality = quality; }
    2222 }
    2323
    2424 public static string GetContract(int numDevices, Quality quality)
    2525 {
    26- return Contract.Types.First(contract => contract.Condition(numDevices, quality)).Type;
    23+ var desiredContract = new Contract(numDevices, quality);
    24+
    25+ return desiredContract.Equals(Contract.Premium) ? "PREMIUM" :
    26+ desiredContract.Equals(Contract.Standard) ? "STANDARD" :
    27+ desiredContract.Equals(Contract.Essential) ? "ESSENTIAL" :
    28+ "INVALID";
    2727 }
    2828 }

Simplified

Code
Diff
  • def AmIYelling(input_sentence):
        return all([ x.isupper() for x in input_sentence if x.isalpha() ])
  • 11 def AmIYelling(input_sentence):
    2- return len([l for l in input_sentence if ((l.isalpha() and l.isupper())or not l.isalpha())]) == len(input_sentence)
    2+ return all([ x.isupper() for x in input_sentence if x.isalpha() ])
Fundamentals
Arrays
Code
Diff
  • function findOnly(arr) {
      let result = 0;
      arr.forEach((i) => {
        result = i ^ result;
      });
      return result;
    }
  • 1-function getSum(array) {
    2- return array.reduce((total, num) => total += num);
    1+function findOnly(arr) {
    2+ let result = 0;
    3+ arr.forEach((i) => {
    4+ result = i ^ result;
    5+ });
    6+ return result;
    33 }
Code
Diff
  • function quiEstLeMeilleurProf(){
      return 'Mon prof de programmation Web';
    }
  • 11 function quiEstLeMeilleurProf(){
    2- return "Mon prof de programmation Web";
    2+ return 'Mon prof de programmation Web';
    33 }
Code
Diff
  • import java.lang.Math;
    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 Math.max(a,b);
      }
    }
  • 1+import java.lang.Math;
    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

Alternative using lists utilizing previous idea of reversion to avoid sorting. Missing test for number with integer square root added.

Code
Diff
  • from math import sqrt
    def divisors(n):
        fa = [i for i in range(1, int(sqrt(n)) + 1) if not (n%i)]
        fa.extend([n//i for i in reversed(fa) if n//i > i])
        return fa
  • 11 from math import sqrt
    22 def divisors(n):
    3- fa={i for i in range(1,int(sqrt(n)) + 1) if not(n%i)}
    4- ct={n//i for i in fa}
    5- return sorted(fa|ct)
    3+ fa = [i for i in range(1, int(sqrt(n)) + 1) if not (n%i)]
    4+ fa.extend([n//i for i in reversed(fa) if n//i > i])
    5+ return fa
Code
Diff
  • def add(s, o):
        s = map(int, s)
        s = {
            1: (c for c in s if c % 2),
            2: (c for c in s if not c % 2),
        }.get(o, s);
        return sum(s)
  • 11 def add(s, o):
    22 s = map(int, s)
    33 s = {
    44 1: (c for c in s if c % 2),
    5- 2: (c for c in s if c % 2 == 0),
    5+ 2: (c for c in s if not c % 2),
    66 }.get(o, s);
    77 return sum(s)
Code
Diff
  • def square(n):
        result = (("*" *n+"\n")*n)[:-1]
        print(result) # ...write a function that prints...
        return result # result to be tested
  • 11 def square(n):
    2- print(("*" *n+"\n")*n) # to see the result
    3-
    4- return (("*" *n+"\n")*n)[:-1]
    5-
    2+ result = (("*" *n+"\n")*n)[:-1]
    3+ print(result) # ...write a function that prints...
    4+ return result # result to be tested
Numbers
Code
Diff
  • def kilogramsToGrams(kilograms=1):
        return kilograms * 1000
  • 1-def kilogramsToGrams(kilograms):
    1+def kilogramsToGrams(kilograms=1):
    22 return kilograms * 1000
Code
Diff
  • def hypotenuse(a, b):
        return abs(complex(a, b))
  • 11 def hypotenuse(a, b):
    2- return abs(a + b * 1j)
    2+ return abs(complex(a, b))
Mathematics
Algorithms
Numbers
Fundamentals
Code
Diff
  • def population_tracking(i, c, n):
        return -(-i*((1+(c/100))**(n))//1)
  • 1-import math
    2-
    33 def population_tracking(i, c, n):
    4- return math.ceil(i*((1+(c/100))**(n)))
    2+ return -(-i*((1+(c/100))**(n))//1)
Code
Diff
  • class Sort:
    
        def merge_sort(self, nums):
            if nums == None: return None
            elif len(nums) <= 1: return nums
          
            vLeft = self.merge_sort(nums[:len(nums) // 2])
            vRight= self.merge_sort(nums[len(nums) // 2:])                 
            lLeft,lRight = len(vLeft),len(vRight)
            i,j,k = 0,0,0
            
            while i < lLeft and j < lRight:
                if vLeft[i] < vRight[j]:
                    nums[k] = vLeft[i]
                    i += 1
                else:
                    nums[k] = vRight[j]
                    j += 1
                k += 1
    
            while i < lLeft:
                nums[k] = vLeft[i]
                i += 1
                k += 1
    
            while j < lRight:
                nums[k] = vRight[j]
                j += 1
                k += 1
    
            return nums
    
  • 11 class Sort:
    22
    33 def merge_sort(self, nums):
    44 if nums == None: return None
    5-
    6- if len(nums) > 1:
    7- mid = len(nums) // 2
    8- lefthalf = nums[:mid]
    9- righthalf = nums[mid:]
    10-
    11- self.merge_sort(lefthalf)
    12- self.merge_sort(righthalf)
    13-
    14- i = 0
    15- j = 0
    16- k = 0
    17-
    18- while i < len(lefthalf) and j < len(righthalf):
    19- if lefthalf[i] < righthalf[j]:
    20- nums[k] = lefthalf[i]
    21- i += 1
    22- else:
    23- nums[k] = righthalf[j]
    24- j += 1
    25- k += 1
    26-
    27- while i < len(lefthalf):
    28- nums[k] = lefthalf[i]
    5+ elif len(nums) <= 1: return nums
    6+
    7+ vLeft = self.merge_sort(nums[:len(nums) // 2])
    8+ vRight= self.merge_sort(nums[len(nums) // 2:])
    9+ lLeft,lRight = len(vLeft),len(vRight)
    10+ i,j,k = 0,0,0
    11+
    12+ while i < lLeft and j < lRight:
    13+ if vLeft[i] < vRight[j]:
    14+ nums[k] = vLeft[i]
    2929 i += 1
    30- k += 1
    31-
    32- while j < len(righthalf):
    33- nums[k] = righthalf[j]
    16+ else:
    17+ nums[k] = vRight[j]
    3434 j += 1
    35- k += 1
    19+ k += 1
    20+
    21+ while i < lLeft:
    22+ nums[k] = vLeft[i]
    23+ i += 1
    24+ k += 1
    25+
    26+ while j < lRight:
    27+ nums[k] = vRight[j]
    28+ j += 1
    29+ k += 1
    3636
    3737 return nums

given a list of lists. each inner list is same size.
they can represent a square or a rectangle.

return information about it.

return its perimeter , area,total number of "*", rectangle/square

s = "*"
array = [[s,s,s,s],[s,s,s,s],[s,s,s,s],[s,s,s,s]]

===> permimeter = 16 ,area = 16, "*" = 16 , "square"

def determine_params(list):
    
    return #its perimeter , area,total number of "*", rectangle/square

Changed from a static variable to a dynamic function.

Code
Diff
  • module Solution
      export greet
    
      function greet( whom::String )
        "Hello " * whom * "!"  
      end
      
    end
    
  • 1-println("Hello Julia!")
    2-const hello = "world"
    1+module Solution
    2+ export greet
    3+
    4+ function greet( whom::String )
    5+ "Hello " * whom * "!"
    6+ end
    7+
    8+end
Code
Diff
  • def distance(a):
        y,y1 = 0,0
        for i in range(len(a)):
            if "y" in a[i]: y = i
            if "x" in a[i]: y1 = i
            
        x ,x1 = a[y].index("y"), a[y1].index("x")
        return abs(x -x1) + abs(y-y1)
  • 1-def distance(array):
    2- for i in range(len(array)):
    3- if "y" in array[i] : y = abs(array[i].index("y") - i)
    4- if "x" in array[i] : x = abs(array[i].index("x") - i)
    5- return (x+y)
    6-
    7-
    8-
    1+def distance(a):
    2+ y,y1 = 0,0
    3+ for i in range(len(a)):
    4+ if "y" in a[i]: y = i
    5+ if "x" in a[i]: y1 = i
    6+
    7+ x ,x1 = a[y].index("y"), a[y1].index("x")
    8+ return abs(x -x1) + abs(y-y1)
Code
Diff
  • #ORDEN O(1) SIN FOR, #Usado en Katas Anteriores por otro colaborador solo
    #lo aplique para Python. 
    def euler(n): return getMult(3,n-1) + getMult(5,n-1) - getMult(15,n-1)
    def getMult(multiple, n): return getArith(multiple, n - n%multiple, int(n/multiple))
    def getArith(first,last,count): return count * (first + last)/2
  • 1-def euler(num):
    2- return sum(range(3,num,3)) + sum(range(5,num,5)) - sum(range(15,num,15))
    1+#ORDEN O(1) SIN FOR, #Usado en Katas Anteriores por otro colaborador solo
    2+#lo aplique para Python.
    3+def euler(n): return getMult(3,n-1) + getMult(5,n-1) - getMult(15,n-1)
    4+def getMult(multiple, n): return getArith(multiple, n - n%multiple, int(n/multiple))
    5+def getArith(first,last,count): return count * (first + last)/2
Code
Diff
  • def fizz_buzz(n):
        return ['FizzBuzz' if (i % 15 == 0) else 'Fizz' if(i % 3 == 0) else 'Buzz' if(i % 5 == 0) else i for i in range(1,n)]
        
  • 11 def fizz_buzz(n):
    2- for i in range(1, n):
    3- yield "Fizz" * (i % 3 == 0) + "Buzz" * (i % 5 == 0) or i
    2+ return ['FizzBuzz' if (i % 15 == 0) else 'Fizz' if(i % 3 == 0) else 'Buzz' if(i % 5 == 0) else i for i in range(1,n)]
    3+
Code
Diff
  • def getLongestWord(words):
        return '' if len(words) == 0 else max(words, key=len)
        
  • 11 def getLongestWord(words):
    2- longest = ""
    3- for w in words:
    4- longest = w if len(w) > len(longest) else longest
    5- return longest
    2+ return '' if len(words) == 0 else max(words, key=len)
    3+

Here's a solution to the problem that uses no for loops, reducing O(n) to O(1).

The basic logic behind this code is that there is a formula for the sum of any arithmetic sequence, for example:

3 + 6 + 9 + 12 + ... + n*3 (where n is a natural number) = n * (3 + n*3) / 2

If we sum all the multiples of 3 and the multiples of 5 this way, we can get close to the answer. But we would be double counting all multiplies of 3*5 = 15, so we use the same formula to subtract out the sum of the multiples of 15.

Hope this helps!

Code
Diff
  • let arithSum = (firstNum, lastNum, count) => count * (firstNum + lastNum) / 2;
    
    let getMultSum = (multiple, n) => arithSum(multiple, n - n%multiple, Math.trunc(n/multiple));
    
    let test = (n) => getMultSum(3,n-1) + getMultSum(5,n-1) - getMultSum(15,n-1); // using n-1 because the problem specifies all multiples strictly *less than* the input
  • 1-//if you have any Suggestion or noticed a mistake in my code ...tell me...i would need that...
    2-function test(n) {
    3- var sum=0;
    4- for (i=1; i<n; i++){
    5- if ((i%3==0) || (i%5==0)){
    6- sum+=i;
    7- }
    8- }
    9- return sum;
    10-}
    1+let arithSum = (firstNum, lastNum, count) => count * (firstNum + lastNum) / 2;
    2+
    3+let getMultSum = (multiple, n) => arithSum(multiple, n - n%multiple, Math.trunc(n/multiple));
    4+
    5+let test = (n) => getMultSum(3,n-1) + getMultSum(5,n-1) - getMultSum(15,n-1); // using n-1 because the problem specifies all multiples strictly *less than* the input
Fundamentals
Strings

A different approach from the one above, done in one line.

Code
Diff
  • const minutes = i => `${Math.trunc(i / 60)}:${i % 60 < 10 ? "0" : ""}${i % 60}`;
  • 1-const toHours = i => Math.floor(i / 60);
    2-
    3-const setDigits = i => `0${i}`.slice(-2);
    4-
    5-const getTime = i => [toHours(i), i % 60];
    6-
    7-const toTime = arr => `${arr[0]}:${setDigits(arr[1])}`;
    8-
    9-const minutes = i => toTime(getTime(i));
    1+const minutes = i => `${Math.trunc(i / 60)}:${i % 60 < 10 ? "0" : ""}${i % 60}`;

Il faut créer une fonction qui s'appelle quiEstLeMeilleurProf et qui retourne la phrase suivante : "Mon prof de programmation Web"

function quiEstLeMeilleurProf(){
  return "Mon prof de programmation Web";
}
Code
Diff
  • def add(a,b):    
        return a + b
        
  • 11 def add(a,b):
    2- return (a + b)
    2+ return a + b
    33
Code
Diff
  • from operator import add
    print(add)
  • 11 from operator import add
    2+print(add)
Code
Diff
  • from operator import mul as multiple
  • 1-def multiple(a,b):
    2- return a*b
    1+from operator import mul as multiple

Code a function that will return the exact average grade of an array of grades. Grades can be integer or float numbers.

Code
Diff
  • def average(grades)
      grades.sum.fdiv(grades.length)
    end 
  • 1-def average (grades)
    2-grade.sum/grade.length
    1+def average(grades)
    2+ grades.sum.fdiv(grades.length)
    33 end

Instead of functions, i used lambdas that captured the password by reference.
So no additional passing through functions is necessary.
Invoking the lambdas as late as possible. To call only 1 function in the best case.
Using std::string::find_first_of() to use the stl instead of writing the search by myself.

Code
Diff
  • #include <string>
    bool testPassword(std::string password)
    {
        auto const has_length{[&]() { return password.size() >= 8; }};
        auto const has_upper{[&]() { return password.find_first_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ") != std::string::npos; }};
        auto const has_special{[&]() { return password.find_first_of("!\"#$%&'()*+'-./;:<>=or?") != std::string::npos; }};
        auto const has_digit{[&]() { return password.find_first_of("0123456789") != std::string::npos; }};
        return has_length() && has_upper() && has_special() && has_digit();
    }
  • 1-class Password{
    2- public:
    3- static bool hasCap(const std::string& password);
    4- static bool hasSpec(const std::string& password);
    5- static bool hasDigit(const std::string& password);
    6- static bool hasLength(const std::string& password);
    7- static bool testPassword(const std::string& password);
    8-};
    9-
    10-bool Password::hasCap(const std::string& password)
    1+#include <string>
    2+bool testPassword(std::string password)
    1111 {
    12- bool result = false;
    13- for(auto symbol : password)
    14- {
    15- if(symbol >= 'A' && symbol <= 'Z')
    16- {
    17- result = true;
    18- break;
    19- }
    20- }
    21- return result;
    22-}
    23-
    24-bool Password::hasSpec(const std::string& password)
    25-{
    26- bool result = false;
    27-
    28- const std::string specials("!\"#$%&'()*+'-./;:<>=?");
    29- for(auto spec : specials)
    30- {
    31- if(password.find(spec) != -1)
    32- {
    33- result = true;
    34- break;
    35- }
    36- }
    37- return result;
    38-}
    39-
    40-bool Password::hasDigit(const std::string& password)
    41-{
    42- bool result = false;
    43- for(auto symbol : password)
    44- {
    45- if(symbol >= '0' && symbol <= '9')
    46- {
    47- result = true;
    48- break;
    49- }
    50- }
    51- return result;
    52-}
    53-
    54-bool Password::hasLength(const std::string& password)
    55-{
    56- return password.length() > 7;
    57-}
    58-
    59-bool Password::testPassword(const std::string& password)
    60-{
    61- bool cap = Password::hasCap(password);
    62- bool spec = Password::hasSpec(password);
    63- bool digit = Password::hasDigit(password);
    64- bool number = Password::hasLength(password);
    65-
    66- return cap && spec && digit && number;
    4+ auto const has_length{[&]() { return password.size() >= 8; }};
    5+ auto const has_upper{[&]() { return password.find_first_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ") != std::string::npos; }};
    6+ auto const has_special{[&]() { return password.find_first_of("!\"#$%&'()*+'-./;:<>=or?") != std::string::npos; }};
    7+ auto const has_digit{[&]() { return password.find_first_of("0123456789") != std::string::npos; }};
    8+ return has_length() && has_upper() && has_special() && has_digit();
    6767 }
Code
Diff
  • function main()
    {
      return 1
    }
  • 11 function main()
    22 {
    3- return 12
    3+ return 1
    44 }

Showing how sync events work in c#, not so pratical as in c# 6 and forward is a good practice writing async code.

using System;

namespace delegates
{
	class Program
	{
		static void Main()
		{
		    // Creates a new instance
			Message hi = new Message();
			
			/*
			set the event of the class instance to a 
			lambda expression, beeing an event handler that has the same parameter
			and return type of the delegate in the class instance.
			
			equivalent of creating a new void method with the same
			parameters and seting it to the event in the class instance
			
			*/
			hi.writed += (string hello) =>
			{
			    Console.WriteLine(hello);
			};
			
			// executes the method to validate the event and add it to the delegate
			hi.write = "write property";
		}
	}
	
	public class Message
	{
	    
	    //creates the delegate that will handle the method/ lambda expression/ anonnymous method passed through it
	    public delegate void handler(string hello);
	    
	    //creates the event with the delegate
	    public event handler writed;
	    
	    //method that will check for the event while executing
	    
	    private string _write;
	    public string write
	    {
	        get
	        {
	            return _write;
	        }
	        set
	        {
	            if(value == "write property")
	            {
	               writed?.Invoke("the event was thrown!!!");
	            }
	            
	            Console.WriteLine(value);
	            
	            _write = value;
	        }
	    }
	    
	   //The same as:
	   
	   // public void write(string text)
	   // {
	   //     //you have to check if the event is not null becouse you can't execute a delegates method if it does not exist
	   //     //(the event handler was not set yet)
	   //     if(text == "write method" && writed != null)
	   //     {
	   //         writed("the event was thrown!!!");
	   //     }
	   //     Console.WriteLine(text);
	       
    }
}
Algorithms
Code
Diff
  • getDividors = n => [...Array(n).keys()].filter(e => n % e)
  • 1-getDividors = n => Array.from({length: n}, (e, i) => n % ++i ? i : 0).filter(e => e)
    1+getDividors = n => [...Array(n).keys()].filter(e => n % e)
Code
Diff
  • test = s => s.match(/\[(\w+)].*\[\/\1]/g).join``
  • 1-function test(str) {
    2- return (str.match(/\[([a-zA-Z]+)](.*)\[\/\1]/g)).join('');
    3-}
    1+test = s => s.match(/\[(\w+)].*\[\/\1]/g).join``
Strings
Code
Diff
  • const lastChar = s => /.$/.exec(s)[0];
    
  • 1-const lastChar=(s)=>s.slice(-1)
    1+const lastChar = s => /.$/.exec(s)[0];
Algorithms

a function that takes a list of connections on the following format:
connections[n] is the list of connections from node n.

connections={
    [1] ={ 1, 2, 6, 7 },
    [2] ={ 1, 2, 4, 5, 6 },
    [3] ={ 3, 4, 5, 6, 7 },
    [4] ={ 2, 3, 4, 5, 6 },
    [5] ={ 2, 3, 4, 5, 7 },
    [6] ={ 1, 2, 3, 4, 6 },
    [7] ={ 1, 3, 5, 7 },
    [8] ={ 8, 9, 11, 12, 13, 15 },
    [9] ={ 8, 9, 10, 12, 13, 15, 16 },
    [10]={ 9, 10, 11, 12, 16 },
    [11]={ 8, 10, 11, 12 },
    [12]={ 8, 9, 10, 11, 12, 13, 15 },
    [13]={ 8, 9, 12, 13, 14, 15 },
    [14]={ 13, 14, 15, 16 },
    [15]={ 8, 9, 12, 13, 14, 15, 16 },
    [16]={ 9, 10, 14, 15, 16 },
    [17]={ 17, 18, 19, 20, 21 },
    [18]={ 17, 18, 19, 20 },
    [19]={ 17, 18, 19, 21 },
    [20]={ 17, 18, 20, 21 },
    [21]={ 17, 19, 20, 21 },
}

The output should be a table of tables with nodes in a given net.

nets={
    {1,2,6,7,4,5,3},
    {8,9,11,12,13,15,10,16,14},
    {17,18,19,20,21}
}

This solution assumes symmetrical connections between nodes.

solution={}

local isIn=function(list,item)
  --simple function to find a vale in list
	if type(list)~="table" or item==nil then
		return false
	end
	local FoundAtIndex=""
	local found=false
	for index,value in pairs(list) do
		if value==item then
			found=true
			FoundAtIndex=index
			break
		end
	end
	return found,FoundAtIndex
end

solution.findConnectedNets=function(connections)
	local nets={}
	for i=1,#connections do --traverses nodes to build the nets
		local new=true
		for k=1,#nets do --if it already is in a net, skip it
			if isIn(nets[k],i) then
				new=false
				break
			end
		end
		if new then
			local net={}
			local queue={i}
			while #queue>0 do
				local vertex=queue[1]
				table.insert(net,vertex)
				table.remove(queue,1)
				for _,node in pairs(connections[vertex]) do
					if not isIn(net,node) and not isIn(queue,node) then
						table.insert(queue,node)
					end
				end
			end
			table.insert(nets,net)
		end
	end
	return nets
end


return solution
Code
Diff
  • export function fizzBuzz(input: number): string {
        const output = (input % 3 ? "" : "Fizz") + (input % 5 ? "" : "Buzz");
        return output.length ? output : input.toString();
    }
  • 11 export function fizzBuzz(input: number): string {
    2- const output: string = `${input % 3 === 0 ? "Fizz" : ""}${input % 5 === 0 ? "Buzz" : ""}`;
    3- return output.length > 0 ? output : input.toString(10);
    2+ const output = (input % 3 ? "" : "Fizz") + (input % 5 ? "" : "Buzz");
    3+ return output.length ? output : input.toString();
    44 }

Use STL algorithms, take vector arguments by constant reference and functors by their exact type to avoid overhead of std::function.

Code
Diff
  • #include <numeric>
    
    using namespace std;
    
    template<class F, class T, class U = decltype(std::declval<F>()(std::declval<T>()))> vector<U> vectorMap(const vector<T>& v, F f) {
      vector<U> result (v.size());
      std::transform(v.begin(), v.end(), result.begin(), std::move(f));
      return result;
    }
    template<class F, class T> vector<T> vectorFilter(const vector<T>& v, F f) {
      vector<T> result;
      std::copy_if(v.begin(), v.end(), std::back_inserter(result), std::move(f));
      return result;
    }
    template<class F, class T, class U> U vectorReduce(const vector<T>& v, F f, U u) {
      return std::accumulate(v.begin(), v.end(), u, std::move(f));
    }
  • 1+#include <numeric>
    2+
    11 using namespace std;
    22
    3-template<class T, class U> vector<U> vectorMap(vector<T> v, function<U (T)> f) {
    4- size_t size = v.size();
    5- vector<U> result (size);
    6- for (size_t i = 0; i < size; i++) result[i] = f(v[i]);
    5+template<class F, class T, class U = decltype(std::declval<F>()(std::declval<T>()))> vector<U> vectorMap(const vector<T>& v, F f) {
    6+ vector<U> result (v.size());
    7+ std::transform(v.begin(), v.end(), result.begin(), std::move(f));
    77 return result;
    88 }
    9-template<class T> vector<T> vectorFilter(vector<T> v, function<bool (T)> f) {
    10+template<class F, class T> vector<T> vectorFilter(const vector<T>& v, F f) {
    1010 vector<T> result;
    11- for (size_t i = 0; i < v.size(); i++) if (f(v[i])) result.push_back(v[i]);
    12+ std::copy_if(v.begin(), v.end(), std::back_inserter(result), std::move(f));
    1212 return result;
    1313 }
    14-template<class T, class U> U vectorReduce(vector<T> v, function<U (U, T)> f, U u) {
    15- U result = u;
    16- for (size_t i = 0; i < v.size(); i++) result = f(result, v[i]);
    17- return result;
    15+template<class F, class T, class U> U vectorReduce(const vector<T>& v, F f, U u) {
    16+ return std::accumulate(v.begin(), v.end(), u, std::move(f));
    1818 }
Algorithms
Code
Diff
  • flatten = a => a.map ? [].concat(...a.map(flatten)) : a
  • 1-flatten=a=>a.map?[].concat(...a.map(flatten)):a
    1+flatten = a => a.map ? [].concat(...a.map(flatten)) : a
Code
Diff
  • class Stack {  // Just to hide the use of array implementation
      constructor() {
        this._items = [];
      }
      push(data) {
        this._items.push(data);
      }
      pop() {
        return this._items.pop();
      }
      
      get length() {
        return this._items.length;
      }
    }
    
    class Queue {
      constructor() {
        this._stack = new Stack();
      }
      enqueue(data) {
        this._stack.push(data);
      }
      dequeue() {
        if (this._stack.length === 1)
          return this._stack.pop();
        else {
          var tmp = this._stack.pop(), result = this.dequeue();
          this.enqueue(tmp);
          return result;
        }
      }
    }
  • 11 class Stack { // Just to hide the use of array implementation
    22 constructor() {
    33 this._items = [];
    44 }
    55 push(data) {
    66 this._items.push(data);
    77 }
    88 pop() {
    99 return this._items.pop();
    1010 }
    11- length() {
    11+
    12+ get length() {
    1212 return this._items.length;
    1313 }
    1414 }
    1515
    1616 class Queue {
    1717 constructor() {
    1818 this._stack = new Stack();
    1919 }
    2020 enqueue(data) {
    2121 this._stack.push(data);
    2222 }
    2323 dequeue() {
    24- if (this._stack.length() === 1)
    25+ if (this._stack.length === 1)
    2525 return this._stack.pop();
    2626 else {
    2727 var tmp = this._stack.pop(), result = this.dequeue();
    2828 this.enqueue(tmp);
    2929 return result;
    3030 }
    3131 }
    3232 }

yawn I need a cup of coffee...

class GroundCoffee { }
class Coffee { }

class Cupboard { 
  constructor() {
    this.contents = {
      "GroundCoffee": new GroundCoffee(),
    };
  }
}

class CoffeeMaker {
  makeCoffee(groundCoffee) {
    if(!(groundCoffee instanceof GroundCoffee)) {
      throw new Error("Only GroundCoffee can be used to make Coffee");
    }
    
    return new Coffee();
  }
}

// -----

const cupboard = new Cupboard();
const coffeeMaker = new CoffeeMaker();

function makeCoffee() {  
  let groundCoffee = cupboard.contents["GroundCoffee"];
  return coffeeMaker.makeCoffee(groundCoffee);
}
Code
Diff
  • def hello
      "world"
    end
  • 1-function hello() {
    2- return "world";
    3-}
    1+def hello
    2+ "world"
    3+end
Code
Diff
  • from datetime import datetime
    
    def password(p):
        a = datetime.now()
        if not p.isdigit(): 
            return "Please, don't print letters.\nReset the program."
        return "ACCESS CONFIRMED" if p == f"{a.hour}{a.minute}" else "ACCESS DENIED"              
    
    # Outside the codewar you can use the lines below.
    # b = input("Please, print the password here (without letters!): ")
    # print(password(b))
  • 11 from datetime import datetime
    22
    33 def password(p):
    44 a = datetime.now()
    5- c = str(a.hour) + str(a.minute)
    6-
    7- if p.isdigit():
    8- if(p == c):
    9- return("ACCESS CONFIRMED")
    10- else:
    11- return("ACCESS DENIED")
    12- else:
    13- return("Please, don't print letters.\nReset the program.")
    5+ if not p.isdigit():
    6+ return "Please, don't print letters.\nReset the program."
    7+ return "ACCESS CONFIRMED" if p == f"{a.hour}{a.minute}" else "ACCESS DENIED"
    1414
    1515 # Outside the codewar you can use the lines below.
    1616 # b = input("Please, print the password here (without letters!): ")
    1717 # print(password(b))

Don't know how this "kumite" stuff works yet, so i may be doing sth wrong.
This is about finding better/more efficient ways to permutate a list starting with my sorry attempt. The result requires types of the typeclass Ord, to get a common result for the test cases. Havent thought about a way to solve that differently yet.

module Permutation where

import Data.List (sort)

permu :: [a] ->[[a]]
permu []  = [[]]
permu [x] = [[x]]
permu x = fuzz (length x) 0 x
        where fuzz l n (x:xs) |n == l = []
                              |otherwise = map ((:) x) (permu xs) ++ fuzz l (n+1) (xs ++ [x])
                            
permutation :: Ord a => [a] -> [[a]]                           
permutation x = permu x

Return addresses are just normal stack entries, and nasm lets you jump to an address from a register.

Code
Diff
  • global stack_push, stack_pop, stack_peek ; , stack_is_empty
    section .text
    stack_push:
      xchg rsi, [rsp]
      jmp rsi
    stack_pop:
      pop rsi
      pop rax
      jmp rsi
    stack_peek:
      pop rsi
      mov rax, [rsp]
      jmp rsi
    
  • 11 global stack_push, stack_pop, stack_peek ; , stack_is_empty
    22 section .text
    33 stack_push:
    4- push rsi
    5- ret
    4+ xchg rsi, [rsp]
    5+ jmp rsi
    66 stack_pop:
    77 pop rsi
    8- ret
    8+ pop rax
    9+ jmp rsi
    99 stack_peek:
    1010 pop rsi
    11- push rsi
    12- ret
    12+ mov rax, [rsp]
    13+ jmp rsi
Code
Diff
  • func hello() {
      print("Hello Swift 5!")
    }
  • 1-func hello() {
    2-
    3-print("Hello Swift 5!")
    4-
    1+func hello() {
    2+ print("Hello Swift 5!")
    55 }
Code
Diff
  • class Functionator
      attr_reader :allowed_methods, :callers, :next_caller
    
      def initialize(s)
        @allowed_methods = s.split
        init_caller
      end
    
      def method_missing(method, *args)
        method = method.to_s
        raise NoMethodError, 'Not exists' unless @allowed_methods.include?(method)
        raise NoMethodError, 'Wrong order' unless @next_caller == method
        wait_next_caller
        self
      end
    
      private
    
      def wait_next_caller
        @next_caller = @callers.next
      rescue StopIteration
        init_caller
      end
    
      def init_caller
        @callers = @allowed_methods.each
        @next_caller = @callers.next
      end
    end
    
    def functionator(methods)
      Functionator.new methods
    end
  • 11 class Functionator
    2+ attr_reader :allowed_methods, :callers, :next_caller
    3+
    22 def initialize(s)
    3- s.split(' ').each { | i | define_singleton_method :"#{i}" do Functionator.new(s.split(' ')[1..-1].join(' ')) end }
    5+ @allowed_methods = s.split
    6+ init_caller
    7+ end
    8+
    9+ def method_missing(method, *args)
    10+ method = method.to_s
    11+ raise NoMethodError, 'Not exists' unless @allowed_methods.include?(method)
    12+ raise NoMethodError, 'Wrong order' unless @next_caller == method
    13+ wait_next_caller
    14+ self
    15+ end
    16+
    17+ private
    18+
    19+ def wait_next_caller
    20+ @next_caller = @callers.next
    21+ rescue StopIteration
    22+ init_caller
    23+ end
    24+
    25+ def init_caller
    26+ @callers = @allowed_methods.each
    27+ @next_caller = @callers.next
    44 end
    55 end
    66
    7-def functionator(string)
    8- Functionator.new(string)
    31+def functionator(methods)
    32+ Functionator.new methods
    99 end