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.

W3Schools says that:

It's a good programming practice to close all files after you have finished with them. You don't want an open file running around on your server taking up resources!

Just wanted to edit my Kumite to demonstrate the best practice way of reading the user's solution within your test cases without wasting Codewars server resources by forgetting to close files.

Fundamentals
Code
Diff
  • #include <iostream>
    #include <string>
    using namespace std ;
    
    int helloCplusplus(){
      string str("Hello, C++!");
      cout << str << endl;
      return 0;
    }
  • 11 #include <iostream>
    22 #include <string>
    33 using namespace std ;
    44
    55 int helloCplusplus(){
    6- string str = "Hello, C++!";
    7- cout << str << '\n';
    6+ string str("Hello, C++!");
    7+ cout << str << endl;
    88 return 0;
    99 }
Code
Diff
  • def get_list(may):
        return ' '.join(may)
  • 11 def get_list(may):
    2- out=''
    3- for i in may:
    4- out+=i+' '
    5- return out[:-1]
    2+ return ' '.join(may)
require 'sinatra'

class Greeter < Sinatra::Application

  get '/' do
    'Hello world!'
  end
  
  get '/:name' do
    name = params[:name]
    name[0] =~ /[aeiou]/i ? "Hola, #{name}" : "Hello, #{name}"
  end
  
end
Code
Diff
  • import java.util.Arrays;
    class Solution {
      
    	   
         public static int retSmallestPositiveInteger() {
             for(int i=1; true ; i++) {
                if (i % 10 == 0)
                    continue;
                if(hasSameDigits(i, i*2, i*3, i*4 , i*5, i*6))
                    return i; 
             }
         }
      
    	    private static boolean hasSameDigits(int a, int b, int c, int d, int e, int f) {
          
    		      char[] aDigits = Integer.toString(a).toCharArray();
    		      char[] bDigits = Integer.toString(b).toCharArray();
              char[] cDigits = Integer.toString(c).toCharArray();
              char[] dDigits = Integer.toString(d).toCharArray();
              char[] eDigits = Integer.toString(e).toCharArray();
              char[] fDigits = Integer.toString(f).toCharArray();
              
    		      Arrays.sort(aDigits);
    		      Arrays.sort(bDigits);
              Arrays.sort(cDigits);
              Arrays.sort(dDigits);
              Arrays.sort(eDigits);
              Arrays.sort(fDigits);
              
    		      return (Arrays.equals(aDigits, bDigits) && Arrays.equals(aDigits, cDigits) && Arrays.equals(aDigits, dDigits) && Arrays.equals(aDigits, eDigits) && Arrays.equals(aDigits, fDigits));
              
          }
    }
  • 1-import java.util.*;
    1+import java.util.Arrays;
    22 class Solution {
    33
    44
    55 public static int retSmallestPositiveInteger() {
    6- for(int i=1; ; i++) {
    7- if(hasSameDigits(i, i*2) && hasSameDigits(i, i*3) && hasSameDigits(i, i*4) && hasSameDigits(i, i*5) && hasSameDigits(i, i*6))
    8- return i;
    6+ for(int i=1; true ; i++) {
    7+ if (i % 10 == 0)
    8+ continue;
    9+ if(hasSameDigits(i, i*2, i*3, i*4 , i*5, i*6))
    10+ return i;
    99 }
    1010 }
    1111
    12- private static boolean hasSameDigits(int x, int y) {
    13- char[] xdigits = Integer.toString(x).toCharArray();
    14- char[] ydigits = Integer.toString(y).toCharArray();
    15- Arrays.sort(xdigits);
    16- Arrays.sort(ydigits);
    17- return Arrays.equals(xdigits, ydigits);
    14+ private static boolean hasSameDigits(int a, int b, int c, int d, int e, int f) {
    15+
    16+ char[] aDigits = Integer.toString(a).toCharArray();
    17+ char[] bDigits = Integer.toString(b).toCharArray();
    18+ char[] cDigits = Integer.toString(c).toCharArray();
    19+ char[] dDigits = Integer.toString(d).toCharArray();
    20+ char[] eDigits = Integer.toString(e).toCharArray();
    21+ char[] fDigits = Integer.toString(f).toCharArray();
    22+
    23+ Arrays.sort(aDigits);
    24+ Arrays.sort(bDigits);
    25+ Arrays.sort(cDigits);
    26+ Arrays.sort(dDigits);
    27+ Arrays.sort(eDigits);
    28+ Arrays.sort(fDigits);
    29+
    30+ return (Arrays.equals(aDigits, bDigits) && Arrays.equals(aDigits, cDigits) && Arrays.equals(aDigits, dDigits) && Arrays.equals(aDigits, eDigits) && Arrays.equals(aDigits, fDigits));
    31+
    1818 }
    1919 }
Code
Diff
  • def is_prime(n):
        return n > 1 and all(n % i for i in range(2, int(n**0.5)+1))
  • 1-from math import sqrt
    22 def is_prime(n):
    3- return n > 1 and all(n % i for i in range(2, int(sqrt(n))+1))
    2+ return n > 1 and all(n % i for i in range(2, int(n**0.5)+1))

In the study of math, we usually assert (x,y) to set the point in 2-D condition. (x,y,z) to set the point in 3-D condition. As so on.
When we count the distance of two points in 2-D condition, like (x1,y1) and (x2,y2) . We do:
sqrt[(x1-x2)**2+(y1-y2)**2]

The same idea to apply in N-dimensions.

Code
Diff
  • def distance_count(a,b):
        return sum([(i-j)**2 for (i,j) in zip(a,b)])**0.5
            
    
  • 1-import numpy as np
    2-
    3-# calculate the distance between two points in 2d,3d ... nD
    4-def distanceND(pA, pB, nD = None):
    5- return np.linalg.norm(np.array(pA) - np.array(pB))
    6-
    7-distance2D = distanceND
    8-
    9-distance3D =distanceND
    10-
    1+def distance_count(a,b):
    2+ return sum([(i-j)**2 for (i,j) in zip(a,b)])**0.5
    3+
Mathematics
Algorithms
Numbers

Removed duplicate code and multiple executions of fmod by calculating it before all the places where it's needed, reducing probability of copy/paste error and slightly improving performance.
Also added a space before every left bracket, for readability (personal preference).

Code
Diff
  • function calcTokenCost($price, $token) {
        if ($price == 0 && $token == 0) {
            return 0;
        }
        if ($price < $token) {
            return $token;
        }
        $mod = fmod($price, $token);
        if ($mod < ($token / 2)) {
            return $price - $mod;
        }
        return $price + $token - $mod;
    }
  • 1-function calcTokenCost($price, $token){
    2- if ($price == 0 && $token == 0){
    1+function calcTokenCost($price, $token) {
    2+ if ($price == 0 && $token == 0) {
    33 return 0;
    44 }
    5- if ($price < $token){
    5+ if ($price < $token) {
    66 return $token;
    77 }
    8- if (fmod($price, $token) < ($token / 2)){
    9- return $price - fmod($price, $token);
    8+ $mod = fmod($price, $token);
    9+ if ($mod < ($token / 2)) {
    10+ return $price - $mod;
    1010 }
    11- return $price + $token - fmod($price, $token);
    12+ return $price + $token - $mod;
    1212 }
hsamuelsonFailed Tests

R Tests

plot a quadradic from 0-10, with the equation x^2

print("Hellow")
#THis doesnt work becasue R is not supported yet

It is usefull for algorithmic tasks, where your code has to have certain complexity. It is not a save way of using In/out, so I woudln't reccomend using it somewhere else besides webpages like SPOJ etc. where programms read from standard input and write to standard output. It should compile with newest gcc and -std=c++11 flag.
Try to write your own functions for fixed point types and cstrings! =)

Bibliography:
http://www.algorytm.edu.pl/fast-i-o.html

#include <cstdio>

template <class type>
inline void getUI ( type* des ) // reads unsigned integer from input
{
  register char c = 0;
  while ( c <= ' ' ) c = getc_unlocked(stdin);
  (*des) = 0;
  while ( c > ' ' )
  {
    (*des) = (*des) * 10 + ( c - '0' );
    c = getc_unlocked(stdin);
  }
}
template <class type>
inline void putUI ( type src ) // writes unsigned integer to output
{
  if ( src == 0 )
  {
    putc_unlocked( '0', stdout );
    return;
  }
  register char c [21];
  register short k = 0;
  while ( src > 0 )
  {
    c[k ++] = src % 10 + '0';
    src /= 10;
  }
  -- k;
  while ( k >= 0 )
    putc_unlocked( c[k --], stdout );
}

int main ()
{
  putUI(2000);
}
Code
Diff
  • const exec = require('child_process').exec;
    
    function parse(error, stdout, stderr) {
      if (error) throw error;  
      console.log(`stdout: ${stdout}`);
      console.log(`stderr: ${stderr}`);
    }
    
    // gives an error I don't understand but I guess the below command sort of works. 
    // exec('npm -g list', (err, stdout, stderr) => parse(err, stdout, stderr));
    
    exec('ls ../../runner/node_modules', (err, stdout, stderr) => parse(err, stdout, stderr));
  • 1-from subprocess import call
    2-call(["pip", "freeze"])
    1+const exec = require('child_process').exec;
    2+
    3+function parse(error, stdout, stderr) {
    4+ if (error) throw error;
    5+ console.log(`stdout: ${stdout}`);
    6+ console.log(`stderr: ${stderr}`);
    7+}
    8+
    9+// gives an error I don't understand but I guess the below command sort of works.
    10+// exec('npm -g list', (err, stdout, stderr) => parse(err, stdout, stderr));
    11+
    12+exec('ls ../../runner/node_modules', (err, stdout, stderr) => parse(err, stdout, stderr));
Code
Diff
  • print("Hello World")
  • 1-cat("Hello World!\n")
    1+print("Hello World")
# caesar cipher shifted of 13 characters with maketrans for python 2.7
from string import maketrans
import string
def caesar(s):
    print(s)
    s=s.translate(maketrans(string.ascii_uppercase, string.ascii_uppercase[13:]+string.ascii_uppercase[:13]))
    return s
Testing

When writing python katas, you might want to create modules that can be imported by the solution or tests.

This kata shows how to by manipulating sys.path to allow importing from /home/codewarrior folder and writing a python file there.

import sys
HOME_DIR = '/home/codewarrior'

def make_module(module_name):
    if HOME_DIR not in sys.path:
        sys.path.append(HOME_DIR)

    moduleContent = 'foo = lambda x: x+1'
    with open('{}/{}.py'.format(HOME_DIR, module_name), 'w') as moduleFile:
        moduleFile.write(moduleContent)

It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.

Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.

function lowestPermutedMultiple(n) {
    let base = n;
    let numDigits = n.toString().length;
    let i = 1;
    let solution = i;
    while ((n * i).toString().length <= numDigits) {
        if (base.toString().split('').sort().join('') == (n*i).toString().split('').sort().join('')) {
            solution = i;
        }
        i++;
    }
    return solution;
}
Code
Diff
  • SELECT name FROM greetings
    WHERE upper(greeting) like '%HELLO%';
  • 11 SELECT name FROM greetings
    2-WHERE greeting='Hello';
    2+WHERE upper(greeting) like '%HELLO%';

I needed to iterate a block on a value n times and return the value to solve a kata. Getting f(f(..f(x)..)) applying f n times. This is the trivial solution:

n.times do
  x = f.call(x)
end
return x

As times returns n rather than anything in the block a separate return x is needed after the block. Also x = modified x is needed. Wouldn't it be nice to have something built in for this purpose? like

x.modify(n, &block)

It turns out that we can achieve something pretty close to this with the built in inject. As times without a block returns an Enumerator, as most Enumerable functions do, (yielding increasing numbers), with the daisy chaining of Enumerables, using only the accumulator of inject this works fine:

n.times.inject(x) { |x| block.call(x) }

However this doesn't work :( as inject in this case feeds in the index:

n.times.inject(x, &block)
class Object
  def modify(n)
    return to_enum :modify unless block_given?
    case n
    when Enumerator then n.each.inject(self) { |acc| yield(acc) }
    when Numeric    then n.times.inject(self) { |acc| yield(acc) }
    end    
  end
end

p 5.modify 2.times, &:~@ # flipping bits twice

A really arcaic calculator for pi, that takes ages to get a little precision.

var ex431 = function(tries){
    var inc=0, outc=0, x, y;
    
    while(tries>0){
        x =  Math.random();
        y =  Math.random();
        
        if (x*x + y*y <= 1) inc++;
        else outc++;
        tries--;
    }
    return inc/(inc+outc);
}

Changed s.ToLower() → s.ToUpperInvariant(), fitting msdn recommended best practices for strings.

Code
Diff
  • using System;
    using System.Linq;
    
    public class Kata
    {
        public static int DuplicateCount(string s) => 
            s.ToUpperInvariant()
             .GroupBy(c => c)
             .Count(g => g.Skip(1).Any());
    }
  • 11 using System;
    22 using System.Linq;
    33
    44 public class Kata
    55 {
    66 public static int DuplicateCount(string s) =>
    7- s.ToLower()
    8- .GroupBy(c => c)
    9- .Count(g => g.Skip(1).Any());
    7+ s.ToUpperInvariant()
    8+ .GroupBy(c => c)
    9+ .Count(g => g.Skip(1).Any());
    1010 }
dpleshkovFailed Tests

Quine

This is a quine in Python 2 (Will not work in 3).

_='_=%r;print _%%_';print _%_
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

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));

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
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);
}