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.

Code
Diff
  • using System;
    class Kata {
        public static void Main(string greeting, string language) {
    			Console.WriteLine("{0}, {1}!", greeting, language);
        }
    }
  • 11 using System;
    22 class Kata {
    33 public static void Main(string greeting, string language) {
    4- Console.WriteLine($"{greeting}, {language}!");
    4+ Console.WriteLine("{0}, {1}!", greeting, language);
    55 }
    66 }
Code
Diff
  • module NCR where
    
    --Combinations nCr
    comb:: Integer -> Integer -> Integer
    comb n r = factorial n `div` (factorial r * factorial (n-r))
      where
      factorial n = foldr (*) 1 [2..n]
  • 11 module NCR where
    22
    33 --Combinations nCr
    44 comb:: Integer -> Integer -> Integer
    5-comb n r | n/=r = (factorial n) `div` (factorial r * factorial (n-r) )
    6- | n==r = (factorial n) `div` (factorial r)
    7-
    8-factorial n= foldl (*) 1 [1..n]
    5+comb n r = factorial n `div` (factorial r * factorial (n-r))
    6+ where
    7+ factorial n = foldr (*) 1 [2..n]
Strings
Code
Diff
  • def last_char(str):
      return str[len(str)-1]
  • 11 def last_char(str):
    2- return str[-1]
    2+ return str[len(str)-1]

Allow for passing parents into the constructor. Also, add some spaces to make code consistent. Also, avoid mutating parents array, just for the sake of it.

Code
Diff
  • class Human {
      constructor (firstName = '', lastName = '', parents = []) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.parents = parents;  // modern family. who takes parental care?
      }
      
      filterMyFamily(humans) {
        return humans.filter(human => human.lastName === this.lastName)
      }
      
      hasParent(p) {
        return this.parents.some(parent => parent === p);
      }
      
      hasChild(c) {
        return c.hasParent(this);
      }
      
      addParent(p) {
        if (!this.hasParent(p)) this.parents = [ ...this.parents, p ];
        return this;
      }
    }
  • 11 class Human {
    2- constructor (firstName = '', lastName = '') {
    2+ constructor (firstName = '', lastName = '', parents = []) {
    33 this.firstName = firstName;
    44 this.lastName = lastName;
    5- this.parents = []; // modern family. who takes parental care?
    5+ this.parents = parents; // modern family. who takes parental care?
    66 }
    7+
    77 filterMyFamily(humans) {
    88 return humans.filter(human => human.lastName === this.lastName)
    99 }
    1010
    11- addParent(p){
    12- if (!this.hasParent(p)) this.parents.push(p);
    13- return this;
    12+ hasParent(p) {
    13+ return this.parents.some(parent => parent === p);
    1414 }
    1515
    16- hasChild(c){
    16+ hasChild(c) {
    1717 return c.hasParent(this);
    1818 }
    1919
    20- hasParent(p){
    21- return this.parents.some(parent => parent === p);
    20+ addParent(p) {
    21+ if (!this.hasParent(p)) this.parents = [ ...this.parents, p ];
    22+ return this;
    2222 }
    2323 }

That's a simple threading test using JavaFX. It currently has troubles due to codewars JVM runner.

package codigosjava.modernizandohilos;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;

/**
 * Created by Javatlacati on 08/02/2017.
 */
public class Aciago extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Thread miHilo = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Corriendo");
                while (true) {
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("ola soi un hilo :v");
                        }
                    });

                    try {
                        System.out.println("anuma me voi a dormir");
                        Thread.sleep(5000);
                    } catch (InterruptedException ex) {
                        System.err.println("#PosMeMuero");
                        break;
                    }
                }
            }
        }
        );

        miHilo.setName("soy el mapa soy el mapa soy el mapa soy el mapa soy el mapa!");
        miHilo.setDaemon(true);
        miHilo.start();
    }
}

Any help is welcome :)

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by Javatlacati on 07/02/2017.
 */
public class ThreadIssueSolution extends ScheduledThreadPoolExecutor {
    public boolean isUsable=true;
    public ThreadIssueSolution() {
        super(1);
    }

    @Override
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
        return super.scheduleAtFixedRate(wrapRunnable(command), initialDelay, period, unit);
    }

    @Override
    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
        return super.scheduleWithFixedDelay(wrapRunnable(command), initialDelay, delay, unit);
    }

    private Runnable wrapRunnable(Runnable command) {
        return new LogOnExceptionRunnable(command);
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
//        super.afterExecute(r, t);
        if(!(t == null && r == null)){
            throw new ArithmeticException("ooops");
        }
    }

    private class LogOnExceptionRunnable implements Runnable {
        private Runnable theRunnable;

        public LogOnExceptionRunnable(Runnable theRunnable) {
            super();
            this.theRunnable = theRunnable;
        }

        @Override
        public void run() {
            try {
                theRunnable.run();
            } catch (Throwable e) {
               System.err.println("error ejecutando: " + theRunnable + ". no seguirá corriendo!");
                //e.printStackTrace();
                // and re throw it so that the Executor also gets this error so that it can do what it would
                // usually do
                throw new RuntimeException(e);
            }
        }
    }
}
Code
Diff
  • package main
    
    import "fmt"
    
    func main() {
        var age int
        fmt.Printf("Enter your age on Earth: ")
        _, err := fmt.Scanf("%d", &age)
        if (err != nil) {
            fmt.Println(err)
        }
        age = age * 365 / 687
        fmt.Printf("Your age on the surface of Mars is %d years old.\n", age)
    }
  • 11 package main
    22
    33 import "fmt"
    44
    55 func main() {
    6- age := 28 * 365 / 687
    7- fmt.Printf("My age on the surface of Mars is %d years old.\n", age)
    6+ var age int
    7+ fmt.Printf("Enter your age on Earth: ")
    8+ _, err := fmt.Scanf("%d", &age)
    9+ if (err != nil) {
    10+ fmt.Println(err)
    11+ }
    12+ age = age * 365 / 687
    13+ fmt.Printf("Your age on the surface of Mars is %d years old.\n", age)
    88 }

Test output documentation: https://github.com/Codewars/codewars-runner-cli/blob/00a657c99f347ef8ecb075b8a19ebab7d8fc1535/documentation/output_format.md#nested-describes

If you print '<COMPLETEDIN::>' after a Test.describe() or Test.it(), you can close describe/it groupings and have a nested structure like you can for the other languages.

def hi():
    return 'hi'


# https://github.com/Codewars/codewars-runner-cli/blob/00a657c99f347ef8ecb075b8a19ebab7d8fc1535/documentation/output_format.md#nested-describes
# use this to close Test.describe and Test.it groupings
def close_group():
    print('<COMPLETEDIN::>')


close_describe = close_it = close_group;
let projectEulerProblemOne = [1 .. 999] |> List.filter(fun x -> x % 3 = 0 || x % 5 = 0) |> List.sum
Code
Diff
  • const countLetterInSentence = (sentence, letter) => ([...sentence].filter(test => letter === test).length)
    
    function countLettersInSentence(sentence, letters){
      return letters.map(letter => countLetterInSentence(sentence, letter))
    }
  • 1-function testAmount(sentence, letters){
    2- return letters.map(letter =>
    3- [...sentence].filter(test => letter === test).length)
    1+const countLetterInSentence = (sentence, letter) => ([...sentence].filter(test => letter === test).length)
    2+
    3+function countLettersInSentence(sentence, letters){
    4+ return letters.map(letter => countLetterInSentence(sentence, letter))
    44 }
Code
Diff
  • const longestString = str => str.split(' ').reduce((a, b) => b.length > a.length ? b : a);
  • 1-var longestString = (str) => str.split(' ').sort((a, b) => b.length - a.length)[0];
    1+const longestString = str => str.split(' ').reduce((a, b) => b.length > a.length ? b : a);
Code
Diff
  • def myMap(mine):
        return [i+1 for i in mine]    
  • 11 def myMap(mine):
    2- l = [i+1 for i in mine]
    3- return l
    4-
    2+ return [i+1 for i in mine]
Code
Diff
  • from itertools import *
    
    def groups_combinations(arr2D):
        res = list(product(*arr2D))
        return [len(res), res]
        
    
  • 11 from itertools import *
    2-def product_(arr2D):
    3- return product(*arr2D)
    44
    55 def groups_combinations(arr2D):
    6- res = []
    7- for comb in product_(arr2D):
    8- res.append(comb)
    4+ res = list(product(*arr2D))
    99 return [len(res), res]
    1010
Code
Diff
  • from math import sqrt, pow
    
    # calculate the distance between two points in 2d,3d ... nD
    def distanceND(pA, pB, nD = None):
        return sqrt(sum(pow(a-b,2) for a,b in zip(pA,pB)))
    
    distance2D = distanceND
        
    distance3D =distanceND
    
    
  • 11 from math import sqrt, pow
    22
    33 # calculate the distance between two points in 2d,3d ... nD
    44 def distanceND(pA, pB, nD = None):
    55 return sqrt(sum(pow(a-b,2) for a,b in zip(pA,pB)))
    66
    7-def distance2D(pA, pB):
    8- return(distanceND(pA, pB))
    7+distance2D = distanceND
    99
    10-def distance3D(pA, pB):
    11- return(distanceND(pA, pB))
    9+distance3D =distanceND
    1212
Code
Diff
  • using System;
    using System.Linq;
    
    public class Kata
    {
        public static int DuplicateCount(string s) => 
            s.ToLower()
                .GroupBy(c => c)
                .Count(g => g.Skip(1).Any());
    }
  • 11 using System;
    22 using System.Linq;
    33
    44 public class Kata
    55 {
    6- public static int DuplicateCount(string str)
    7- {
    8- return str
    9- .ToLower()
    10- .GroupBy(c => c)
    11- .Count (g => g.Count () > 1);
    12- }
    6+ public static int DuplicateCount(string s) =>
    7+ s.ToLower()
    8+ .GroupBy(c => c)
    9+ .Count(g => g.Skip(1).Any());
    1313 }

This is possible because python has mutable default arguments. It is functionally the same as the lrucache approach (though arguably less pythonic)

I like this approach because it allows you to reset the cache when needed, while also keeping it between problems, so if you want to keep looking for fib numbers, the memoization is already done, but if you're using this method for something like kepping track of visited nodes in a graph, you can just clear the cache every time you make a new graph.

Code
Diff
  • def fib(n, memo = {0:1, 1:1}):
        if n not in memo:
            memo[n] = fib(n-1)+fib(n-2)
        return memo[n]
        
  • 1-def fib(n):
    2- memo = {0:1, 1:1}
    3- def recursiveFib(n):
    4- if n not in memo:
    5- memo[n] = recursiveFib(n-1)+recursiveFib(n-2)
    6- return memo[n]
    7- return recursiveFib(n)
    1+def fib(n, memo = {0:1, 1:1}):
    2+ if n not in memo:
    3+ memo[n] = fib(n-1)+fib(n-2)
    4+ return memo[n]
    88

Javascript version of fast code to get all the proper factors of a number

var sortNumber = function(a, b){return a - b;};

function getDiv(n){
    var factL= [], i;
    for (i = 1; i <= Math.floor(Math.sqrt(n)); i += 1) {
        if (n % i === 0) {
            factL.push(i);
            if (n / i !== i) factL.push(n / i);
        }
    }
    factL.sort(sortNumber);
    return factL;
}

We have n different groups of elements and we want to know all the possible combinations of n elements from these groups.
Each combinations should be formed having one element from each group.
The function generates all the possible different combinations.

function groupCombinations_() {
    var r = [], arg = arguments, max = arg.length-1;
    function helper(arr, i) {
        for (var j=0, l=arg[i].length; j<l; j++) {
            var a = arr.slice(0); 
            a.push(arg[i][j]);
            if (i==max)
                r.push(a);
            else
                helper(a, i+1);
        }
    }
    helper([], 0);
    return r;
}

function groupCombinations(arr2D) {
    var combL = groupCombinations_.apply(this, arr2D);
    return [combL.length, combL];
}

We have n different groups of elements and we want to know all the possible combinations of n elements from these groups.
Each combinations should be formed having one element from each group.
The function generates all the possible different combinations.

def groups_combination_(a)
	  a[1..-1].inject(a[0]){ |m,v| m = m.product(v).map(&:flatten) }
end

def groups_combinations(arr2D)
    res = groups_combination_(arr2D)
    return [res.length, res]
end

Prints "Hello, Obj-c"

#import <Foundation/Foundation.h>

NSString *helloObjC(NSString *language) {
  NSLog(@"Hello, %@!\n", language);
  return "Hello Obj-C!";
}
Code
Diff
  • function isPrime(n) {
        if (n < 2)
          return false;
        // do an early exit for even numbers
        if (n == 2)
          return true;
        if (n % 2 == 0)
          return false;
        // we only have to check odd numbers, starting with 3
        for (var x = 3; x <= Math.floor(Math.sqrt(n)); x += 2)
          if (n % x == 0)
            return false;
        return true;
    }
  • 11 function isPrime(n) {
    2- if (n < 2) return false;
    3- for (var x = 2; x <= Math.floor(Math.sqrt(n)); x++) {if (n % x == 0) return false;}
    2+ if (n < 2)
    3+ return false;
    4+ // do an early exit for even numbers
    5+ if (n == 2)
    6+ return true;
    7+ if (n % 2 == 0)
    8+ return false;
    9+ // we only have to check odd numbers, starting with 3
    10+ for (var x = 3; x <= Math.floor(Math.sqrt(n)); x += 2)
    11+ if (n % x == 0)
    12+ return false;
    44 return true;
    55 }

The checkWorkHours(dateTime time.Time) function accepts a time.Time object and returns true or false if the time given is within work hours.

Includes a function to test the outputs of your function.

package main

import (
	"fmt"
	"time"
)

func main() {
	testCheckWorkHours()
}

func checkWorkHours(dateTime time.Time) bool {
	beginWorkHour := 8
	endWorkHour := 18

	currentHour := dateTime.Hour()
	currentDay := dateTime.Weekday()

	if currentDay > 0 && currentDay < 6 {
		if currentHour < endWorkHour && currentHour >= beginWorkHour {
			return true
		}
	}

	return false
}

func testCheckWorkHours() {
	// Tests the function
	timeFormat := "2006-01-02 15:04:05 -0700 MST"

	// True Cases
	dateTime, _ := time.Parse(timeFormat, "2017-01-16 15:00:00 -0500 EST")
	fmt.Println(fmt.Sprintf("Monday @ 3pm should be True: %t", checkWorkHours(dateTime)))

	dateTime, _ = time.Parse(timeFormat, "2017-01-16 17:59:59 -0500 EST")
	fmt.Println(fmt.Sprintf("Friday @ 5:59pm should be True: %t", checkWorkHours(dateTime)))

	// False Cases
	dateTime, _ = time.Parse(timeFormat, "2017-01-15 15:00:00 -0500 EST")
	fmt.Println(fmt.Sprintf("Sunday @ 3pm should be False: %t", checkWorkHours(dateTime)))

	dateTime, _ = time.Parse(timeFormat, "2017-01-13 18:00:00 -0500 EST")
	fmt.Println(fmt.Sprintf("Friday @ 6pm should be False: %t", checkWorkHours(dateTime)))

	dateTime, _ = time.Parse(timeFormat, "2017-01-17 07:00:00 -0500 EST")
	fmt.Println(fmt.Sprintf("Tuesday @ 7am should be False: %t", checkWorkHours(dateTime)))
}
Code
Diff
  • import random
    
    
    def rabinMiller(num):
        s = num - 1
        t = 0
        while s % 2 == 0:
            s = s // 2
            t += 1
    
        for trials in range(5):
            a = random.randrange(2, num - 1)
            v = pow(a, s, num)
            if v != 1:
                i = 0
                while v != (num - 1):
                    if i == t - 1:
                        return False
                    else:
                        i = i + 1
                        v = (v ** 2) % num
        return True
    def is_prime(num):
        if (num < 2):
            return False
        lowPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
        if num in lowPrimes:
            return True
        for prime in lowPrimes:
            if (num % prime == 0):
                return False
        return rabinMiller(num)
  • 11 import random
    2-
    3-def decompose(n):
    4- exponentOfTwo = 0
    5- while n % 2 == 0:
    6- n = n/2
    7- exponentOfTwo += 1
    8- return exponentOfTwo, n
    9-
    10-def isWitness(possibleWitness, p, exponent, remainder):
    11- possibleWitness = pow(possibleWitness, remainder, p)
    12- if possibleWitness == 1 or possibleWitness == p - 1:
    13- return False
    14- for _ in range(exponent):
    15- possibleWitness = pow(possibleWitness, 2, p)
    16- if possibleWitness == p - 1:
    17- return False
    2+
    3+
    4+def rabinMiller(num):
    5+ s = num - 1
    6+ t = 0
    7+ while s % 2 == 0:
    8+ s = s // 2
    9+ t += 1
    10+
    11+ for trials in range(5):
    12+ a = random.randrange(2, num - 1)
    13+ v = pow(a, s, num)
    14+ if v != 1:
    15+ i = 0
    16+ while v != (num - 1):
    17+ if i == t - 1:
    18+ return False
    19+ else:
    20+ i = i + 1
    21+ v = (v ** 2) % num
    1818 return True
    19-
    20-def is_prime(p, accuracy=100):
    21- if p == 2 or p == 3: return True
    22- if p < 2: return False
    23- exponent, remainder = decompose(p - 1)
    24- for _ in range(accuracy):
    25- possibleWitness = random.randint(2, p - 2)
    26- if isWitness(possibleWitness, p, exponent, remainder):
    23+def is_prime(num):
    24+ if (num < 2):
    25+ return False
    26+ lowPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
    27+ if num in lowPrimes:
    28+ return True
    29+ for prime in lowPrimes:
    30+ if (num % prime == 0):
    2727 return False
    28- return True
    32+ return rabinMiller(num)

A very easy method importting the library prime in Ruby. It's a bit slower than the last code we've seen in Ruby

require 'prime'

def is_prime(n)
    Prime.prime?(n)
end

Again we can see that the runtime is less (more less than a half) than the previous version

def is_prime(n)
    return false if n < 2
    return true if n == 2
    return false if n % 2 == 0
    (3..Math.sqrt(n).round).step(2) do |x|
        return false if n % x == 0
    end
    return true
end

I received a fork to my version in python by the user Mc Code. The average runtime for different tries is under 500 ms. The half runtime that the previous version in Javascript, too (1000 ms)

function isPrime(n) {
    if (n < 2) return false;
    else if (n == 2) return true;
    else if (n % 2 === 0) return false;
    for (var x = 3; x <= Math.floor(Math.sqrt(n)); x += 2) {if (n % x === 0) return false;}
    return true;
}

We can turn this into a one-liner (minus the import)

Code
Diff
  • from math import sqrt
    
    is_prime = lambda n: n == 2 or (n > 2 and n % 2 != 0 and all(n % x != 0 for x in range(3, int(sqrt(n)) + 1, 2)))
    
    
  • 11 from math import sqrt
    22
    3+is_prime = lambda n: n == 2 or (n > 2 and n % 2 != 0 and all(n % x != 0 for x in range(3, int(sqrt(n)) + 1, 2)))
    33
    4-def is_prime(n):
    5- if n < 2:
    6- return False
    7- elif n == 2:
    8- return True
    9- elif n % 2 == 0:
    10- return False
    11-
    12- for x in range(3, int(sqrt(n)) + 1, 2):
    13- if n % x == 0:
    14- return False
    15-
    16- return True

A very fast code to test if a number is a prime. You can see its performance having 100 tests from 1000 to 10e12 in less than 1000 ms

def is_prime(n)
    return false if n < 2
    for x in 2.. Math.sqrt(n).round
        return false if n % x == 0
    end
    return true
end

This is the real "bubble sort", your implementation similar to "selection sort" =)

Code
Diff
  • package main
    
    import "fmt"
    
    func bubble_sort(dataset []int){
      for i := 1; i <= len(dataset)-1; i++ {
        
          if dataset[i] >= dataset[i-1] { continue }
          
          var y int = dataset[i]
          var j int = i - 1
          
          for {
    	      if j < 0 || dataset[j] <= y { break }
          	dataset[j+1] = dataset[j]
    	      j--
          }
          
          dataset[j+1] = y
      }
    }
    
    
    func main(){
    
      dataset := []int{5, 2, 4, 6, 1, 3, 15, 6, 23645, 23, 462, 2, 2, -12};
    
      fmt.Println(dataset)
    
      bubble_sort(dataset);
    
      fmt.Println(dataset)
    }
    
  • 11 package main
    22
    33 import "fmt"
    44
    5-func swap(dataset []int, a, b int) {
    6- var x int = dataset[a]
    7- dataset[a] = dataset[b]
    8- dataset[b] = x
    9-}
    10-
    1111 func bubble_sort(dataset []int){
    12- for i := 0; i <= len(dataset)-1; i++ {
    13- for j := len(dataset)-1; j >= i + 1; j-- {
    14- if dataset[j] < dataset[j-1] {
    15- swap(dataset, j, j - 1)
    6+ for i := 1; i <= len(dataset)-1; i++ {
    7+
    8+ if dataset[i] >= dataset[i-1] { continue }
    9+
    10+ var y int = dataset[i]
    11+ var j int = i - 1
    12+
    13+ for {
    14+ if j < 0 || dataset[j] <= y { break }
    15+ dataset[j+1] = dataset[j]
    16+ j--
    1616 }
    17- }
    18+
    19+ dataset[j+1] = y
    1818 }
    1919 }
    2020
    2121
    2222 func main(){
    2323
    24- dataset := []int{5, 2, 4, 6, 1, 3};
    26+ dataset := []int{5, 2, 4, 6, 1, 3, 15, 6, 23645, 23, 462, 2, 2, -12};
    2525
    2626 fmt.Println(dataset)
    2727
    2828 bubble_sort(dataset);
    2929
    3030 fmt.Println(dataset)
    3131 }
Code
Diff
  • public class Dinglemouse {
    
      // Use CSS to display a pretty version of the flap display
      // From: https://www.codewars.com/kata/airport-arrivals-slash-departures-number-1/java
      public static String[] prettyPrint(final String[] lines) {
        String s = "";
        for (int y = 0; y < lines.length; y++) {
          s += "<div style=\"height:23px\">";
          for (int x = 0; x < lines[y].length(); x++) {
            s += "<span style=\"font-size:10px;color:yellow;padding:5px;border:1px solid gray;background:black\">"+lines[y].charAt(x)+"</span>";
          }
          s += "</div>";
        }
        System.out.println(s);
        return lines;
      }
    
    }
  • 11 public class Dinglemouse {
    22
    33 // Use CSS to display a pretty version of the flap display
    44 // From: https://www.codewars.com/kata/airport-arrivals-slash-departures-number-1/java
    55 public static String[] prettyPrint(final String[] lines) {
    6- String s = "<pre>";
    6+ String s = "";
    77 for (int y = 0; y < lines.length; y++) {
    88 s += "<div style=\"height:23px\">";
    99 for (int x = 0; x < lines[y].length(); x++) {
    1010 s += "<span style=\"font-size:10px;color:yellow;padding:5px;border:1px solid gray;background:black\">"+lines[y].charAt(x)+"</span>";
    1111 }
    1212 s += "</div>";
    1313 }
    14- s+= "</pre>";
    1515 System.out.println(s);
    1616 return lines;
    1717 }
    1818
    1919 }
Mathematics
Algorithms
Numbers
Fundamentals
Code
Diff
  • const dice = _ => -~(Math.random()*6);
  • 1-const dice=_=>~~(Math.random()*6)+1;
    1+const dice = _ => -~(Math.random()*6);
Arrays
Map/Reduce
Algorithms
  • result in ordered by value
  • correct test cases
Code
Diff
  • const duplicates = n => n.sort((a, b) => a - b)
      .reduce((p, c, i, a) => c !== [...p].pop() && c === a[i-1] ? [...p, c] : p, [])
  • 1-function duplicates(arr) {
    2- var out = [];
    3- for(var x=0;x<arr.length-1;x++)
    4- {
    5- var ch = arr[x];
    6- for(var y=x+1;y<arr.length;y++)
    7- {
    8- var comp = arr[y];
    9- if (comp === ch && out.indexOf(comp) === -1)
    10- {
    11- out.push(comp);
    12- break;
    13- }
    14- }
    15- }
    16- out.sort();
    17- return out;
    18-}
    1+const duplicates = n => n.sort((a, b) => a - b)
    2+ .reduce((p, c, i, a) => c !== [...p].pop() && c === a[i-1] ? [...p, c] : p, [])
Code
Diff
  • const middleCharacter = s => s.slice(~(s.length/2), -~(s.length/2));
  • 1-const middleCharacter = s => s.slice(s.length/2 - !(s.length % 2), s.length/2+1);
    1+const middleCharacter = s => s.slice(~(s.length/2), -~(s.length/2));

String.split Demo:

'123456'.split('');

// [ '1', '2', '3', '4', '5', '6' ]

How about:

'123456'.spliter(2);
// [ '12', '34', '56' ]

?

console.log(
  '123456'.split('')
);
Code
Diff
  • package com.mystuff.juststuff;
    
    import java.text.*;
    import java.util.*;
    
    public class Palindrome {
    
    	private static final SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
    
    	public Set<Date> countDatePalindromes(final Date startDate, final Date endDate) {
    		final Set<Date> set = new TreeSet<>();
    		final GregorianCalendar startCal = new GregorianCalendar();
    		final GregorianCalendar endCal = new GregorianCalendar();
    
        // If end date is before start date, flip them.
        startCal.setTime(startDate.before(endDate) ? startDate : endDate);
        endCal.setTime(startDate.after(endDate) ? startDate : endDate);
        
    		for (; startCal.before(endCal) || startCal.equals(endCal); startCal.add(Calendar.DAY_OF_MONTH, 1)) {   
    			final String forward = sdf.format(startCal.getTime());
          final String back = new StringBuilder(forward).reverse().toString();            
    			if (forward.equals(back)) {
            set.add(startCal.getTime()); // Date string looks same both ways	
          }
    		}	
        
    		return set;
    	}
    	
    }
    
  • 11 package com.mystuff.juststuff;
    22
    33 import java.text.*;
    4-import java.util.Calendar;
    5-import java.util.Date;
    6-import java.util.GregorianCalendar;
    7-import java.util.TreeSet;
    4+import java.util.*;
    88
    99 public class Palindrome {
    10- SimpleDateFormat sdf;
    11-
    12- public Palindrome() {
    13- this.sdf = new SimpleDateFormat("MMddyyyy");
    14- sdf.setLenient(false);
    15- }
    16-
    17- public TreeSet<Date> countDatePalindromes(Date startDate, Date endDate) {
    18- TreeSet<Date> palSet = new TreeSet<Date>();
    19- GregorianCalendar startCal = new GregorianCalendar();
    20- GregorianCalendar endCal = new GregorianCalendar();
    2121
    8+ private static final SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
    2222
    23- /*
    24- end date is chronologically before start date. flip them.
    25- NOTE: lines 23-30 should be a pre-condition to the countDatePalindromes method,
    26- so they should be deleted.
    27- */
    28- if (startDate.getTime() > endDate.getTime()) {
    43- if (regularDate.equals(palDate))
    44- palSet.add(startCal.getTime());
    45-
    46- startCal.add(Calendar.DAY_OF_MONTH, 1);
    10+ public Set<Date> countDatePalindromes(final Date startDate, final Date endDate) {
    11+ final Set<Date> set = new TreeSet<>();
    12+ final GregorianCalendar startCal = new GregorianCalendar();
    13+ final GregorianCalendar endCal = new GregorianCalendar();
    14+
    15+ // If end date is before start date, flip them.
    16+ startCal.setTime(startDate.before(endDate) ? startDate : endDate);
    17+ endCal.setTime(startDate.after(endDate) ? startDate : endDate);
    18+
    19+ for (; startCal.before(endCal) || startCal.equals(endCal); startCal.add(Calendar.DAY_OF_MONTH, 1)) {
    20+ final String forward = sdf.format(startCal.getTime());
    21+ final String back = new StringBuilder(forward).reverse().toString();
    22+ if (forward.equals(back)) {
    23+ set.add(startCal.getTime()); // Date string looks same both ways
    24+ }
    4747 }
    48- return palSet;
    26+
    27+ return set;
    4949 }
    5050
    51- private String palindromify(final Date arg) {
    52- StringBuffer palBuff = new StringBuffer(8);
    53- palBuff = sdf.format(arg, palBuff, new FieldPosition(0));
    54- return palBuff.reverse().toString();
    55- }
    56-
    5757 }
Code
Diff
  • function getFactors (n) {
      if (!Number.isInteger(n) || n < 1) return [];
      
      var divisors = new Set(); 
      var step = n % 2 == 0 ? 1 : 2;
      for (let i = 1; i <= Math.sqrt(n); i += step) {
        if (n % i == 0) divisors.add(i).add(n/i)
      }
      return Array.from(divisors).sort((a,b)=>a-b)
    }
  • 11 function getFactors (n) {
    22 if (!Number.isInteger(n) || n < 1) return [];
    33
    4- var divisors = new Set();
    5- for (let i = 1; i <= Math.sqrt(n); i++) {
    4+ var divisors = new Set();
    5+ var step = n % 2 == 0 ? 1 : 2;
    6+ for (let i = 1; i <= Math.sqrt(n); i += step) {
    66 if (n % i == 0) divisors.add(i).add(n/i)
    77 }
    8- return Array.from(divisors)
    9+ return Array.from(divisors).sort((a,b)=>a-b)
    99 }

A little help to calculate the distances between two points in a plane(2D cases) and in the space (3D cases)

function distance2D(pA, pB) {
    if (pA == pB) return 0;
    var xA = pA[0], yA = pA[1], xB= pB[0], yB = pB[1];
    return Math.sqrt((xA - xB)**2 + (yA - yB)**2)
}
    
function distance3D(pA, pB) {
    if (pA == pB) return 0;
    var xA = pA[0], yA = pA[1], zA = pA[2], xB= pB[0], yB = pB[1], zB = pB[2];
    return Math.sqrt((xA - xB)**2 + (yA - yB)**2 + (zA - zB) **2);
}

A little help for claculate the distances between two points in a plane(2D cases) and in the space (3D cases)

def distance2D(pA, pB)
    return 0 if pA == pB
    xA = pA[0]; yA = pA[1]; xB= pB[0]; yB = pB[1]
    return Math.sqrt((xA - xB)**2 + (yA - yB)**2)
end
    
def distance3D(pA, pB)
    return 0 if pA == pB
    xA = pA[0]; yA = pA[1]; zA = pA[2]; xB= pB[0]; yB = pB[1]; zB = pB[2]
    return Math.sqrt((xA - xB)**2 + (yA - yB)**2 + (zA - zB) **2)
end  

def range (min, max)
    rand * (max-min) + min
end
Code
Diff
  • const convert = n => Number(n.toFixed(2));
  • 1-const convert = (num) => {
    2- return parseFloat(num.toFixed(2));
    3-};
    1+const convert = n => Number(n.toFixed(2));
Mathematics
Algorithms
Numbers
Code
Diff
  • function calcTokenCost($price, $token){
        if ($price == 0 && $token == 0){
            return 0;
        }
        if ($price < $token){
            return $token;
        }
        if (fmod($price, $token) < ($token / 2)){
            return $price - fmod($price, $token);
        }
        return $price + $token - fmod($price, $token);
    }
  • 1-function calcTokenCost($price, $token) {
    2-
    3-
    1+function calcTokenCost($price, $token){
    2+ if ($price == 0 && $token == 0){
    3+ return 0;
    4+ }
    5+ if ($price < $token){
    6+ return $token;
    7+ }
    8+ if (fmod($price, $token) < ($token / 2)){
    9+ return $price - fmod($price, $token);
    10+ }
    11+ return $price + $token - fmod($price, $token);
    44 }

Comparing lists using the length function is problematical because it requires counting every item in both lists. However, we only need to count up until the length of the shortest list + 1 to know which one is shorter. This can make a big difference in performance if one list is much longer than the other -- and make the difference between termination and non-termination if one list is infinite.

My change fixes this problem by avoiding the use of the length function. I've also changed the tests to make sure the solution works when one list is infinite.

Code
Diff
  • module CmpStr where
    
    import Data.Function
    import Data.Monoid
    
    cmpStr :: String -> String -> Ordering
    cmpStr = (compare `on` map (const ())) `mappend` compare
  • 11 module CmpStr where
    22
    33 import Data.Function
    44 import Data.Monoid
    55
    66 cmpStr :: String -> String -> Ordering
    7-cmpStr = (compare `on` length) `mappend` compare
    7+cmpStr = (compare `on` map (const ())) `mappend` compare

Return the names of everyone to greet with "Hello".

SELECT name FROM greetings
WHERE greeting='Hello';
Fundamentals
Code
Diff
  • #include<stdio.h>
    
    int hello(char* name) {
      printf("Hello, %s!\n", name);
      return 0;
    }
  • 11 #include<stdio.h>
    22
    3-int main(int argc, char **argv) {
    4- printf("Hello, %s!\n", argv[0]);
    3+int hello(char* name) {
    4+ printf("Hello, %s!\n", name);
    55 return 0;
    66 }
Fundamentals
Arrays
Code
Diff
  • const thirdGreatest = a => [...a].sort((a,b) => b - a)[2];
  • 1-var thirdGreatest = a => JSON.parse(JSON.stringify(a)).sort((a,b) => b - a)[2];
    1+const thirdGreatest = a => [...a].sort((a,b) => b - a)[2];

The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.

There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.

How many circular primes are there below one million?

function countCirculars(n) {
  let count = 0;

  for (let i=3;i<=n; i+=2) {
    if (isPrime(i) && isCirclePrime(i))
      count++;
  }

  return count+1;
}

function isPrime(n) {
  for (let i=2; i<=Math.sqrt(n); i++) {
    if (n%i === 0)
      return false;
  }
  return true;
}

function isCirclePrime(n) {
  let strN = n.toString();
  for (let i = 1; i<strN.length; i++) {
    strN = shiftString(strN);
    if (!isPrime(parseInt(strN)))
      return false
  }
  return true;
}

function shiftString(str) {
  return str.substring(1) + str.substring(0,1);
}

This uses lambda expressions insted of return.

Code
Diff
  • using System.Linq;   
    public class Kata { public static string[] LiningUpHisStudents(string s) => s.Split(' ').OrderByDescending(x => x.Length).ThenByDescending(x => x).ToArray(); }
  • 1-using System;
    22 using System.Linq;
    3-
    4- public class Kata
    5- {
    6- public static string[] LiningUpHisStudents(string s)
    7- {
    8- var query = s.Split(' ').OrderByDescending(x => x.Length).ThenByDescending(x => x).ToArray();
    9- return query;
    10- }
    11- }
    2+public class Kata { public static string[] LiningUpHisStudents(string s) => s.Split(' ').OrderByDescending(x => x.Length).ThenByDescending(x => x).ToArray(); }
Code
Diff
  • def divisors(n)
        fact = []
        for i in 1.. (Math.sqrt(n)).floor
            if n % i == 0 
                fact << i
                # more rubyish i think
                fact << (n / i) if (n / i) != i
            end
        end
        # no need for "return" in ruby
        fact.sort
    end
  • 11 def divisors(n)
    2- fact = [];
    2+ fact = []
    33 for i in 1.. (Math.sqrt(n)).floor
    44 if n % i == 0
    55 fact << i
    6- if n / i != i
    7- fact << n / i
    8- end
    6+ # more rubyish i think
    7+ fact << (n / i) if (n / i) != i
    99 end
    1010 end
    11- fact.sort!
    12- return fact
    10+ # no need for "return" in ruby
    11+ fact.sort
    1313 end
String.prototype.scan = function(regex) {
    if (!regex.global) throw "regex must have 'global' flag set";
    var r = []
    this.replace(regex, function() {
        r.push(Array.prototype.slice.call(arguments, 1, -2));
    });
    return r;
}

function reverseComplement(dna) {
  return /[^ATCG]/.test(dna) ? "Invalid sequence" :
  [...dna.replace(/./g,x=>x=="A"?"T":x=="T"?"A":x=="C"?"G":"C")].reverse().join("")
}

function getFrames(seq){
  var rev        = reverseComplement(seq)
  var seq_length = seq.length
  return { 
    "1" : seq,  "2": seq.substring(1,seq_length-1),  "3": seq.substring(2,seq_length-1),
    "-1": rev, "-2": rev.substring(1,seq_length-1), "-3": rev.substring(2,seq_length-1)
  }
}

function findOrfInFrame(seq,frame,min,len) {
  var orfs    = []
  var tri_nts = seq.match(/.{1,3}/g)
  var start   = ""
  var stop    = ""
  var orf_seq = ""

  var is_neg  = frame < 0
  var neg_offset = {"1" :  1, "2" :  3, "3" : 5}
  var offset     = neg_offset[Math.abs(frame).toString()]

  tri_nts.forEach( function(tri_nt,i){
    // The very end of the sequence
    if  (i == tri_nts.size - 1) {
      stop  = ((i*3)+frame+2)
      if (is_neg) {
        start = (len - parseInt(start) - offset)
        stop  = (len - parseInt(stop)  - offset)
      }
      if ((orf_seq.length + 3) >= min) {
        orfs.push([start.toString(),">#{stop}",orf_seq])
      }
    }
    // Start of an ORF
    if (orf_seq == "" && tri_nt == "ATG") {
      orf_seq  += tri_nt
      start = (i * 3) + frame
    // Not a stop codon
    } else if (codons[tri_nt] != "*" && orf_seq != ""){
      orf_seq  += tri_nt
    // Find a stop codon
    } else if (codons[tri_nt] == "*" && orf_seq != ""){
      if ((orf_seq.length + 3) >= min){
        stop  = ((i*3)+frame+2)
        if (is_neg) {
          start = (len - parseInt(start) - offset)
          stop  = (len - parseInt(stop)  - offset)
        }
        orfs.push([start.toString(),stop.toString(),orf_seq])
        start   = ""
        stop    = ""
        orf_seq = "" 
      }
    }
  });
  return orfs
}

function findOrfs(seq,min) {
  var frames    = getFrames(seq)
  var len       = seq.length
  var all_orfs  = {}
  var count     = 1
  var frames_l  = [1]//,2,3,-1,-2,-3]
  frames_l.forEach(function(frame){
    var is_neg = frame < 0 ? true : false
    var seq    = frames[frame.toString()]
    var orfs   = findOrfInFrame(seq,frame,min,len)
    orfs.forEach(function(orf){
      var orf_info = {
        'start' : orf[0],
        'stop'  : orf[1],
        'strand': frame > 0 ? "+" : "-",
        'seq'   : orf[2].match(/.{1,3}/g).map(codon=>codons[codon]).join(""),
        'bp'    : orf[2].length + 3,
        'aa'    : orf[2].length / 3,
        'frame' : frame,
      };
      all_orfs[`ORF${count}`] = orf_info
      count += 1
    });
  });
  console.log(all_orfs)
  return all_orfs
}
def get_frames(seq)
  rev = seq.gsub(/[ATGC]/, 'A' => 'T', 'T' => 'A', 'G' => 'C', 'C' => 'G').reverse
  { "1":  seq, "2":  seq[1..-1], "3": seq[2..-1],
    "-1": rev, "-2": rev[1..-1], "-3": rev[2..-1] }
end

def find_orf_in_frame(seq,frame,min,len)
  orfs    = []
  tri_nts = seq.scan(/.{3}/)
  start   = stop = seq = ""
  seq     = seq.reverse.tr("ACTG","TGAC")

  is_neg  = frame < 0
  neg_offset = {"1" =>  1, "2" =>  3, "3" => 5}
  offset     = neg_offset[frame.abs().to_s]

  tri_nts.each_with_index do |tri_nt,i|
    if  (i == tri_nts.size - 1)
        stop  = ((i*3)+frame+2)
        start = (len - start.to_i - offset) if is_neg
        stop  = (len - stop.to_i  - offset) if is_neg
      orfs << [start.to_s,">#{stop}",seq] if (seq.length + 3) >= min
      break
    end
    if seq == "" && tri_nt == "ATG"
      # p "ATG"
      seq  += tri_nt
      start = (i * 3) + frame
    elsif (!$codons.select {|k,v| v == "*"}.keys.include?(tri_nt)) && seq != ""
      seq  += tri_nt
    elsif $codons.select {|k,v| v == "*"}.keys.include?(tri_nt)
      print "\n-----\n"
      print seq.scan(/.{3}/).map{|a| $codons[a]}.join()
      if (seq.length + 3) >= min
        stop  = ((i*3)+frame+2)
        start = (len - start.to_i - offset) if is_neg
        stop  = (len - stop.to_i  - offset) if is_neg
        orfs << [start.to_s,stop.to_s,seq]
      end
      start = stop = seq = ""
    end
  end
  orfs
end

def find_orfs(seq,min)
  frames = get_frames(seq)
  len    = seq.length
  all_orfs  = Hash.new()
  count = 1
  # [1,2,3,-1,-2,-3].each do |frame|
  [1].each do |frame|
    is_neg = frame < 0 ? true : false
    seq    = frames[frame.to_s.to_sym]
    orfs   = find_orf_in_frame(seq,frame,min,len)
    orfs.each do |orf|
      orf_info = {
        start:  orf[0],
        stop:   orf[1],
        strand: frame > 0 ? "+" : "-",
        seq:    orf[2].scan(/.{3}/).map{|a| $codons[a]}.join(),
        bp:     orf[2].length + 3,
        aa:     orf[2].length / 3,
        frame:  frame,
      }
      all_orfs["ORF#{count}"] = orf_info
      count += 1
    end
  end
  all_orfs
end

Improve test cases.

Code
Diff
  • #!/bin/bash
    
    if [ $# -eq 1 ]; then
      echo "$(dirname $1), $(basename ${1%.*}), ${1##*.}"
    fi
  • 11 #!/bin/bash
    2-filename=$1
    3-echo "$(dirname $filename), $(basename ${filename%.*}), ${filename##*.}"
    2+
    3+if [ $# -eq 1 ]; then
    4+ echo "$(dirname $1), $(basename ${1%.*}), ${1##*.}"
    5+fi

With this one we close the trilogy Javascript-Python-Ruby to get the primes factor.

def prime_fac(i)
    factors = []
    check = proc do |p|
        while(q, r = i.divmod(p) 
        	   r.zero?)
            factors << p
            i = q
        end
    end
    check[2]
    check[3]
    p = 5
    while p * p <= i
        check[p]
        p += 2
        check[p]
        p += 4    # skip multiples of 2 and 3
    end
    factors << i if i > 1
    factors
end

A similar kata in python to get the prime factors of a number.

from math import sqrt, floor
def fac(n):  
    step = lambda x: 1 + (x<<2) - ((x>>1)<<1)  
    maxq = long(floor(sqrt(n))) 
    d = 1
    q = n % 2 == 0 and 2 or 3 
    while q <= maxq and n % q != 0:
        q = step(d)
        d += 1
    return q <= maxq and [q] + fac(n//q) or [n]

Sometimes we need a fast code to do this operation as fast as possible. Perhaps this one may help.

function primeFactorization(num){
    var root = Math.sqrt(num),  
    result = arguments[1] || [],x = 2; 
    if(num % x){
        x = 3;
        while((num % x) && ((x = x + 2) < root)){}
    }
    x = (x <= root) ? x : num;
    result.push(x);
    return (x === num) ? result : primeFactorization(num/x, result);
}

This is a way to block the random.seed command which breaks your random tests

import random
random.seed = None

I found a way to make random tests in python not random.

import random
random.seed(0)#Or any other number

Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.

What is the total of all the name scores in the file?

function nameScores(names) {
  var t1 = console.time("names");;
  names.sort();
  var sum = 0;
  var index = 1;
  for (var name = 0; name < names.length; name++) {
    var nameSum = 0;
    for (var character = 0; character < names[name].length; character++) {
      nameSum += (names[name][character].charCodeAt(0) - 64);
    }
    sum += (nameSum * index);
    index++;
  }
  var t2 = console.timeEnd('names');
  return sum;
}

Use a recursive method to calculate the sum of all integers from 1 to n.

An ArgumentError should be raised if the input is below 1.

Code
Diff
  • def sum n
      raise ArgumentError('n must be greater than 0') if n < 1
      n == 1 ? 1 : n + sum(n - 1)
    end
  • 11 def sum n
    2- return 1 if n == 1 # Base case of recursion method - must be defined; otherwise infinite recursion may occur
    3- n + sum(n - 1)
    2+ raise ArgumentError('n must be greater than 0') if n < 1
    3+ n == 1 ? 1 : n + sum(n - 1)
    44 end

This is how you prevent the user from importing certain modules in your kata.

import sys
sys.modules['module name'] = None
Code
Diff
  • #! /bin/csh -f
    
    echo $2
  • 1-echo $1
    1+#! /bin/csh -f
    2+
    3+echo $2
Code
Diff
  • #!/bin/bash
    
    # Without newline:
    echo -n test
    # With newline
    echo test
  • 1+#!/bin/bash
    2+
    3+# Without newline:
    4+echo -n test
    5+# With newline
    11 echo test
Code
Diff
  • # What are all the ways to output a string in Ruby?
    def hello_ruby
      greet = "Hello Ruby!"
    
      print           greet, "\n"
      puts            greet
      print           greet, "\n"
      puts            greet
      $stdout.write   greet + "\n"
      $stdout.puts    greet
      $stdout.print   greet, "\n"
      $stdout <<      greet + "\n"
      (greet+"\n").chars {|c| print c}
    end
  • 11 # What are all the ways to output a string in Ruby?
    22 def hello_ruby
    33 greet = "Hello Ruby!"
    44
    55 print greet, "\n"
    66 puts greet
    7- print "#{greet}\n"
    8- puts "Hello Ruby!"
    7+ print greet, "\n"
    8+ puts greet
    99 $stdout.write greet + "\n"
    1010 $stdout.puts greet
    1111 $stdout.print greet, "\n"
    1212 $stdout << greet + "\n"
    13- (greet+"\n").each_char {|c| print c}
    13+ (greet+"\n").chars {|c| print c}
    1414 end

Find the number that only odd times form an array.

For example:

findOnlyOddTimesNumber([1,1,1,2,3,4,2,4,2,1,3]); // 2 
const findOnlyOddTimesNumber = arr => arr.reduce((p,c) => p^c);

findOnlyOddTimesNumber([1,1,1,2,3,4,2,4,2,1,3]);

Try to return the File Extension from the provided arguement.

#!/bin/bash
file1=$1; echo ${file1##*.}

Caesar-cipher (obfuscated, golfed)

sub c{map{chr($_[0]+ord)}split'',$_[1]}
Code
Diff
  • def id_matrix(size):
         return [[i == j for j in range(size)] for i in range(size)]
    
  • 11 def id_matrix(size):
    2- return [[1 if i == j else 0 for j in range(size)] for i in range(size)]
    2+ return [[i == j for j in range(size)] for i in range(size)]
Code
Diff
  • def  getVillianName(birthday):
        return '{} {}'.format(  FIRSTNAME[birthday.strftime("%B")], 
                                LASTNAME[birthday.strftime("%d")[1]])
    
  • 1-
    22 def getVillianName(birthday):
    3- result = ""
    4-
    5- result = FIRSTNAME[birthday.strftime("%B")] + " "
    6- result += LASTNAME[birthday.strftime("%d")[1]]
    7- return result
    2+ return '{} {}'.format( FIRSTNAME[birthday.strftime("%B")],
    3+ LASTNAME[birthday.strftime("%d")[1]])
Code
Diff
  • import itertools
    
    
    def eratosthenes():
        # From Coobook recipies
        # Credits to: Credit: David Eppstein, Tim Peters, Alex Martelli,
        # Wim Stolker, Kazuo Moriwaka, Hallvard Furuseth, Pierre Denis,
        # Tobias Klausmann, David Lees, Raymond Hettinger
        D = {}
        yield 2
        for q in itertools.islice(itertools.count(3), 0, None, 2):
            p = D.pop(q, None)
            if p is None:
                D[q * q] = q
                yield q
            else:
                x = p + q
                while x in D or not (x & 1):
                    x += p
                D[x] = p
    
    
    def count_primes(limit):
        count = 0
        for prime in eratosthenes():
            if prime > limit:
                return count
            count += 1
  • 11 import itertools
    2-from itertools import *
    2+
    3+
    33 def eratosthenes():
    4- #From Coobook recipies
    5- #Credits to: Credit: David Eppstein, Tim Peters, Alex Martelli,
    6- #Wim Stolker, Kazuo Moriwaka, Hallvard Furuseth, Pierre Denis,
    7- #Tobias Klausmann, David Lees, Raymond Hettinger
    8- D = { }
    5+ # From Coobook recipies
    6+ # Credits to: Credit: David Eppstein, Tim Peters, Alex Martelli,
    7+ # Wim Stolker, Kazuo Moriwaka, Hallvard Furuseth, Pierre Denis,
    8+ # Tobias Klausmann, David Lees, Raymond Hettinger
    9+ D = {}
    99 yield 2
    1010 for q in itertools.islice(itertools.count(3), 0, None, 2):
    1111 p = D.pop(q, None)
    1212 if p is None:
    13- D[q*q] = q
    14+ D[q * q] = q
    1414 yield q
    1515 else:
    1616 x = p + q
    17- while x in D or not (x&1):
    18+ while x in D or not (x & 1):
    1818 x += p
    1919 D[x] = p
    20-
    21+
    22+
    2121 def count_primes(limit):
    2222 count = 0
    2323 for prime in eratosthenes():
    24- if prime > limit: return count
    26+ if prime > limit:
    27+ return count
    2525 count += 1
Code
Diff
  • using System;
    using System.Linq;  
    
    public class Kata
        {
          private const int monmeValue = 60;
        
            public static int[] PurchaseTofu(int cost, string box)
            {
                string[] boxSplited = box.Split(' ');
                
                var monCount = boxSplited.Count(x => x == "mon");//one foreach will be faster than this 2 lines but this is easier to read
                var monmeCount = boxSplited.Count(x => x == "monme");
    
                var totalValue = monCount + (monmeCount * monmeValue);
    
                int monmeCounter = Math.Min(cost / monmeValue, monmeCount);
                cost -= monmeCounter * monmeValue;
    
                return (monCount < cost) ? 
                  new[] { 0 } : //leaving the market
                  new[] { monCount, monmeCount, totalValue, monmeCounter + cost };
            }
        }
  • 11 using System;
    22 using System.Linq;
    33
    44 public class Kata
    55 {
    6+ private const int monmeValue = 60;
    7+
    66 public static int[] PurchaseTofu(int cost, string box)
    77 {
    8- string[] boxSplited = box.Split(' ');
    10+ string[] boxSplited = box.Split(' ');
    99
    1010 var monCount = boxSplited.Count(x => x == "mon");//one foreach will be faster than this 2 lines but this is easier to read
    1111 var monmeCount = boxSplited.Count(x => x == "monme");
    1212
    13- var totalValue = monCount + (monmeCount * 60);
    15+ var totalValue = monCount + (monmeCount * monmeValue);
    1414
    15- int monmeCounter = cost / 60;
    16- if (monmeCounter > monmeCount)
    17- {
    18- monmeCounter = monmeCount;
    19- }
    20- cost -= monmeCounter*60;
    17+ int monmeCounter = Math.Min(cost / monmeValue, monmeCount);
    18+ cost -= monmeCounter * monmeValue;
    2121
    22- if (monCount < cost)
    23- {
    24- return new[] { 0 };//leaving the market
    25- }
    26-
    27- return new[] { monCount, monmeCount, totalValue, monmeCounter + cost };
    20+ return (monCount < cost) ?
    21+ new[] { 0 } : //leaving the market
    22+ new[] { monCount, monmeCount, totalValue, monmeCounter + cost };
    2828 }
    2929 }

[Please, leave a feedback when you complete it or this will always stay in beta and you will not earn language points].

Print all numbers up to 3rd parameter which are multiple of both 1st and 2nd paramater.

#!/bin/bash
for i in $(eval echo {1..$3});
do
if [ `expr $i % $1` -eq 0 -a `expr $i % $2` -eq 0 ]
then
echo $i
fi
done
Code
Diff
  • const getMin = (l) => l.sort((a, b) => a && b ? a - b : b)[0] || 0
    
  • 1-const getMin = (l) => l.filter(i => i > 0).sort((a, b) => a - b)[0] || 0
    1+const getMin = (l) => l.sort((a, b) => a && b ? a - b : b)[0] || 0