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

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

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

Code
Diff
  • #define add std::plus<>()
  • 1-template<typename T>
    2-T add(const T& a, const T &b){
    3- return std::plus<T>()(a, b);
    4-}
    1+#define add std::plus<>()
Code
Diff
  • def mul():
        sum=0
        for i in range(1, 1000):
            if(i % 3 == 0 or i % 5 == 0):
                sum += i
        return sum
        
  • 11 def mul():
    22 sum=0
    3- for i in range(1001):
    4- if i>0:
    5- if(i%3==0 or i%5==0):
    6- sum=sum+1
    7- return sum
    3+ for i in range(1, 1000):
    4+ if(i % 3 == 0 or i % 5 == 0):
    5+ sum += i
    6+ return sum
    7+
Arrays
Code
Diff
  • const func = (N, p) => Array(N).fill().map((_,i)=>i>=p?i-p:p-i);
  • 1-function func(N, point) {
    2- let start = 0; // starting position of array
    3- let clonePoint = point; // clone for point to start counting from that number at begining of array
    4- let arr = [...Array(N).keys()] // generate array and fill with 0 to 10
    5- if(!(point > N)) {
    6- arr.forEach((o, index) => {
    7- index < point ? arr[index] = clonePoint-- : arr[index] = start++;
    8- });
    9- return arr;
    10- }
    11- return [];
    12-}
    1+const func = (N, p) => Array(N).fill().map((_,i)=>i>=p?i-p:p-i);
Mathematics
Algorithms
Numbers

PEP 8 - Naming Conventions - Function Names:

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

This naming style is commonly known as snake_case.

Furthermore, the variable assignment in the previous Kumite is not required; the computed result can be returned immediately.

Finally, as per the Python Test Reference in the official Codewars Docs, the order of arguments for Test.assert_equals should be actual, expected instead of the other way round.

Code
Diff
  • from itertools import permutations
    def sequence_permutation(t, n):
        return list(permutations(t, n))
  • 11 from itertools import permutations
    2-
    3-def SequencePermutation(plenty, count):
    4- ret = list(permutations(plenty, count))
    5- return ret
    6-
    7-
    2+def sequence_permutation(t, n):
    3+ return list(permutations(t, n))

A simple algorithm in Brainf**k that receives exactly 1 byte of input and prints it out as a numerical string. For example: "H" -> "72". Note that this algorithm only works for byte values up to 99 though - it won't handle three-digit bytes properly.

This program might be somewhat useful in writing a short and concise program that prints out the lyrics to "99 bottles of beer" since the lyrics are highly repetitive and involves printing out a lot of numbers in descending order. However, upon second thought, it might not be that useful at all since my program fails to preserve its input :p

,[->>+>+>>-<<----------[[+]>>+<<]>>[[+]<<<----------<+>>>>]<<<[->+>+<<]>>[-<<+>>]<<<<]>[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]>++++++++++++++++++++++++++++++++++++++++++++++++.
// add the values "codewars" to the websites array
var websites = ['codears'];

Hello World in Julia, since there's nothing on codewars ⊙﹏⊙.

println("Hello Julia!")
const hello = "world"

Hello Brainf**k with "default arguments"

The last two BF programs I published would simply print a weirdly formatted string if the input is empty (or not provided), like so: "Hello "/"Hello !". Obviously, that isn't desirable behavior so I refactored my program to print "Hello World!" in case of empty input.

Code
Diff
  • ++++++++++[>+++++++>++++++++++>+++++++++++>+++<<<<-]>++.>+.>--..+++.>++.>->,[.<[+]>,]<[[+]++++++++++[>+++++++++>+++++++++++>++++++++++<<<-]>---.>+.+++.------.>.<<<]<+.
  • 1-++++++++++[>+++++++>++++++++++>+++++++++++>+++<<<<-]>++.>+.>--..+++.>++.>,[.,]<+.
    1+++++++++++[>+++++++>++++++++++>+++++++++++>+++<<<<-]>++.>+.>--..+++.>++.>->,[.<[+]>,]<[[+]++++++++++[>+++++++++>+++++++++++>++++++++++<<<-]>---.>+.+++.------.>.<<<]<+.
use Math;

proc chebyshev(n: int, v: real) : real
{
  if (v > 1) {
    return cosh(n * acosh(v));
  } else if (v < -1) {
    return (-1) ** n * cosh(n * acosh(-v));
  } else {
    return cos(n * acos(v));
  }
}
Code
Diff
  • const package = require('fs').readFileSync('../../runner/package.json','utf8');
    
    console.log(package);
    
  • 1-const exec = require('child_process').exec;
    1+const package = require('fs').readFileSync('../../runner/package.json','utf8');
    22
    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));
    3+console.log(package);
Code
Diff
  • (princ "Welcome to Common Lisp, made with secret alien technology.")
  • 1-(format t "Welcome to Common Lisp, made with secret alien technology.")
    1+(princ "Welcome to Common Lisp, made with secret alien technology.")
Puzzles
Games
Mathematics
Algorithms
Numbers
Sequences
Arrays

Naive, brute force solution

Code
Diff
  • function Generate_Kolakoski_Seq(seed, n){
      seed = seed.join("");
      let seq = seed[0].repeat(seed[0]), tptr = 0, sptr = 0;
      while(seq.length < n) {
        sptr++; tptr = ++tptr % seed.length;
        seq += seed[tptr].repeat(seq[sptr] || seed[sptr]);
      }
      return seq.substring(0, n).split("").join(",");
    }
    
    function Find_Kolakoski_Number(seed, n){
      // Ehh, I'll leave the thinking up to someone else.
      return +Generate_Kolakoski_Seq(seed, n)[(n-1) * 2];
    }
  • 1-// takes int[] and int, returns string (comma seperated integers)
    22 function Generate_Kolakoski_Seq(seed, n){
    3-
    2+ seed = seed.join("");
    3+ let seq = seed[0].repeat(seed[0]), tptr = 0, sptr = 0;
    4+ while(seq.length < n) {
    5+ sptr++; tptr = ++tptr % seed.length;
    6+ seq += seed[tptr].repeat(seq[sptr] || seed[sptr]);
    7+ }
    8+ return seq.substring(0, n).split("").join(",");
    44 }
    55
    6-
    7-// takes int[] and int, returns int
    8-function Find_Kolaskoski_Number(seed, n){
    9-
    11+function Find_Kolakoski_Number(seed, n){
    12+ // Ehh, I'll leave the thinking up to someone else.
    13+ return +Generate_Kolakoski_Seq(seed, n)[(n-1) * 2];
    1010 }
Code
Diff
  • def parse(expr):
    
        class State:
            current = expr[0]
            tokens = []
    
        def exp():
            result = term()
            while State.current in ('+', '-'):
                if State.current == '+':
                    next_token()
                    result += term()
                if State.current == '-':
                    next_token()
                    result -= term()
            return result
    
        def factor():
            result = None
            if State.current[0].isdigit() or State.current[-1].isdigit():
                result = float(State.current)
                next_token()
            elif State.current is '(':
                next_token()
                result = exp()
                next_token()
            return result
    
        def next_token():
            State.tokens = State.tokens[1:]
            State.current = State.tokens[0] if len(State.tokens) > 0 else None
    
        def term():
            result = factor()
            while State.current in ('*', '/'):
                if State.current == '*':
                    next_token()
                    result *= term()
                if State.current == '/':
                    next_token()
                    result /= term()
            return result
    
        for i in range(len(expr)):
            if expr[i].isdigit() and i > 0 and (State.tokens[-1].isdigit() or State.tokens[-1][-1] is '.'):
                State.tokens[-1] += expr[i]
            elif expr[i] is '.' and i > 0 and State.tokens[-1].isdigit():
                State.tokens[-1] += expr[i]
            else:
                State.tokens.append(expr[i])
    
        return exp()
    
  • 1-def parse(expr): #The main parser
    2- ps = 0 #Number of open parentheses
    3- cval = 0 #Current value
    4- op = "+" #Current operation
    5- accum = "" #Accumulating value
    6- for i in range(len(expr)):
    7- c = expr[i]
    8- if c in ["+","-"] and not ps: #Operation not inside parens
    9- if op=="+": #Addition
    10- cval+=parse_fact(accum)
    11- else: #Subtraction
    12- cval-=parse_fact(accum)
    13- accum = "" #Reset the value
    14- op = c #New operation once that was calculated
    15- else:
    16- if c=="(": ps+=1 #Open paren
    17- if c==")": ps-=1 #Close paren
    18- accum+=c #Add a character to accumulating value
    19- if op=="+": #Do the operation one more time
    20- cval+=parse_fact(accum)
    21- else:
    22- cval-=parse_fact(accum)
    23- return cval
    24-def parse_fact(term):
    25- ps = 0
    26- cval = 1
    27- op = "*"
    28- accum = ""
    29- for i in range(len(term)):
    30- c = term[i]
    31- if c in ["*","/"] and not ps:
    32- if op=="*":
    33- cval*=parse_val(accum)
    34- else:
    35- cval/=parse_val(accum)
    36- accum = ""
    37- op = c
    38- else:
    39- if c=="(": ps+=1
    40- if c==")": ps-=1
    41- accum+=c
    42- if op=="*":
    43- cval*=parse_val(accum)
    44- else:
    45- cval/=parse_val(accum)
    46- return cval
    47-def parse_val(val):
    48- if val[0] == "(": #Parenthetical expression
    49- return parse(val[1:-1]) #Cut off parentheses and reevaluate
    50- else:
    51- return float(val) #Not parenthetical
    1+def parse(expr):
    2+
    3+ class State:
    4+ current = expr[0]
    5+ tokens = []
    6+
    7+ def exp():
    8+ result = term()
    9+ while State.current in ('+', '-'):
    10+ if State.current == '+':
    11+ next_token()
    12+ result += term()
    13+ if State.current == '-':
    14+ next_token()
    15+ result -= term()
    16+ return result
    17+
    18+ def factor():
    19+ result = None
    20+ if State.current[0].isdigit() or State.current[-1].isdigit():
    21+ result = float(State.current)
    22+ next_token()
    23+ elif State.current is '(':
    24+ next_token()
    25+ result = exp()
    26+ next_token()
    27+ return result
    28+
    29+ def next_token():
    30+ State.tokens = State.tokens[1:]
    31+ State.current = State.tokens[0] if len(State.tokens) > 0 else None
    32+
    33+ def term():
    34+ result = factor()
    35+ while State.current in ('*', '/'):
    36+ if State.current == '*':
    37+ next_token()
    38+ result *= term()
    39+ if State.current == '/':
    40+ next_token()
    41+ result /= term()
    42+ return result
    43+
    44+ for i in range(len(expr)):
    45+ if expr[i].isdigit() and i > 0 and (State.tokens[-1].isdigit() or State.tokens[-1][-1] is '.'):
    46+ State.tokens[-1] += expr[i]
    47+ elif expr[i] is '.' and i > 0 and State.tokens[-1].isdigit():
    48+ State.tokens[-1] += expr[i]
    49+ else:
    50+ State.tokens.append(expr[i])
    51+
    52+ return exp()

Game of Life :

The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.

Game of Life

Your task is to write a program to calculate the next generation of Conway's game of life, given any starting position.
You start with a two dimensional grid of cells, where each cell is either alive or dead.
The grid is finite, and no life can exist off the edges.
When calculating the next generation of the grid, follow these four rules:

  1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
  2. Any live cell with more than three live neighbours dies, as if by overcrowding.
  3. Any live cell with two or three live neighbours lives on to the next generation.
  4. Any dead cell with exactly three live neighbours becomes a live cell.

Examples: * indicates live cell, . indicates dead cell

Example input: (4 x 8 grid)
........
....*...
...**...
........

Example output:
........
...**...
...**...
........
function nextGeneration(grid) {
  return grid.map((row, rowIndex) => {
    return row.map((cell, colIndex) => {
      if (rowIndex !== 0 && colIndex !== 0 && rowIndex < grid.length - 1 && colIndex < row.length - 1) {
        let neighboursCount = 0;
        if (grid[rowIndex][colIndex + 1] === 1) neighboursCount++;
        if (grid[rowIndex][colIndex - 1] === 1) neighboursCount++;
        if (grid[rowIndex + 1][colIndex] === 1) neighboursCount++;
        if (grid[rowIndex - 1][colIndex] === 1) neighboursCount++;
        if (grid[rowIndex + 1][colIndex + 1] === 1) neighboursCount++;
        if (grid[rowIndex + 1][colIndex - 1] === 1) neighboursCount++;
        if (grid[rowIndex - 1][colIndex + 1] === 1) neighboursCount++;
        if (grid[rowIndex - 1][colIndex - 1] === 1) neighboursCount++;
      
        if (cell === 1) {
          if (neighboursCount === 2 || neighboursCount === 3 ) {
            return 1;
          }
        } else {
          if (neighboursCount === 3 ) {
            return 1;
          }
        }
        return 0;
      }
      return 0;
    });
  });
}
Mathematics
Algorithms
Numbers

Computing the real Gamma Function with Stirling's Approximation

Related Kata

Computing the complex Gamma function <-- click on the link to attempt the Kata now :D

Related Collection

Complex Analysis

Overview

The Gamma Function Γ(x) is an extension of the factorial function - while the factorial n! is only defined for non-negative integers, the gamma function is defined for all numbers except the non-positive integers. However, the gamma function has its argument shifted down by 1 such that Γ(n) = (n - 1)! for all n where n is a positive integer. One of its many applications is in fractional calculus.

Definitions

The main definition of the gamma function is based on a definite integral with positive infinity as one of its limits. There are also other exact definitions of the gamma function such as "Euler's definition as an infinite product" and the "Weierstrass definition". However, I will not elaborate on these definitions - more information can be easily found on Wikipedia (or by consulting your math professor).

The Problem

It is technically impossible to implement an exact definition of the Gamma Function in a computer/calculator since "there are, relatively speaking, no such simple solutions for factorials; no finite combination of sums, products, powers, exponential functions, or logarithms will suffice to express x!" (source: Wikipedia) so one must always resort to numerically approximating the Gamma function, ideally to a high degree of accuracy. A common, well-known approximation to the Gamma Function is known as Stirling's Approximation which has a simple formula and is usually sufficiently accurate for large values of x; however, since it is an asymptotic approximation, it loses its accuracy for small values of x and doesn't work with negative values of x due to an attempt at squarerooting a negative number (JavaScript Math.sqrt returns NaN for negative inputs).

The Challenge

Stirling's Approximation is implemented in this Kumite as a possible implementation for the Gamma Function; however, you will notice that it fails most, if not all, of the tests. The challenge, should you accept it, is to properly implement the Gamma Function such that it passes all test cases properly.

function gamma(x) {
  // Stirling's Approximation is simple and efficient (just a single calculation)
  // but will it work?
  x -= 1; // Shift argument down by 1
  return Math.sqrt(2 * Math.PI * x) * Math.pow(x / Math.E, x); // Compute Stirling's Formula
}
Mathematics
Algorithms
Numbers
Code
Diff
  • #include <complex.h>
    
    double complex multiply(double complex z, double complex w) {
      return z*w;
    }
  • 1-proc multiply(z: complex, w: complex): complex {
    1+#include <complex.h>
    2+
    3+double complex multiply(double complex z, double complex w) {
    22 return z*w;
    33 }
Code
Diff
  • package com.mystuff.juststuff;
    
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.time.format.DateTimeParseException;
    import java.util.Arrays;
    import java.util.Set;
    import java.util.SortedSet;
    import java.util.TreeSet;
    import java.util.function.Predicate;
    import java.util.stream.Collectors;
    import java.util.stream.IntStream;
    
    public class Palindrome {
    
      private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMddyyyy");
    
      public Set<LocalDate> countDatePalindromes(final LocalDate startDate, final LocalDate endDate) {
        final SortedSet<LocalDate> sortedDates = new TreeSet<>(Arrays.asList(startDate, endDate));
        return IntStream.rangeClosed(sortedDates.first().getYear(), sortedDates.last().getYear())
            .filter(Palindrome::isPalindromePossible)
            .mapToObj(Palindrome::createPalindrome)
            .filter(isDateInRange(sortedDates.first(), sortedDates.last()))
            .collect(Collectors.toCollection(TreeSet::new));
      }
      
      private static boolean isPalindromePossible(int year) {
          int monthFirstDigit = year % 10;
          return monthFirstDigit == 0 || monthFirstDigit == 1; 
      }
    
      private static LocalDate createPalindrome(final int year) {
        final String yearStr = String.valueOf(year);
        final String datePalindrome = new StringBuilder(yearStr).reverse().append(yearStr).toString();
        try {
          return LocalDate.parse(datePalindrome, formatter);
        } catch (final DateTimeParseException e) {}
        return null;
      }
    
      private static Predicate<LocalDate> isDateInRange(final LocalDate startDate, final LocalDate endDate) {
        return (date) -> !(date == null || date.isBefore(startDate) || date.isAfter(endDate));
      }
    }
  • 1515
    1616 private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMddyyyy");
    1717
    1818 public Set<LocalDate> countDatePalindromes(final LocalDate startDate, final LocalDate endDate) {
    1919 final SortedSet<LocalDate> sortedDates = new TreeSet<>(Arrays.asList(startDate, endDate));
    2020 return IntStream.rangeClosed(sortedDates.first().getYear(), sortedDates.last().getYear())
    21+ .filter(Palindrome::isPalindromePossible)
    2121 .mapToObj(Palindrome::createPalindrome)
    2222 .filter(isDateInRange(sortedDates.first(), sortedDates.last()))
    2323 .collect(Collectors.toCollection(TreeSet::new));
    25+ }
    26+
    27+ private static boolean isPalindromePossible(int year) {
    28+ int monthFirstDigit = year % 10;
    29+ return monthFirstDigit == 0 || monthFirstDigit == 1;
    2424 }
    2525
    2626 private static LocalDate createPalindrome(final int year) {
    2727 final String yearStr = String.valueOf(year);
    2828 final String datePalindrome = new StringBuilder(yearStr).reverse().append(yearStr).toString();
    2929 try {
    3030 return LocalDate.parse(datePalindrome, formatter);
    3131 } catch (final DateTimeParseException e) {}
    3232 return null;
    3333 }
    3434
    3535 private static Predicate<LocalDate> isDateInRange(final LocalDate startDate, final LocalDate endDate) {
    3636 return (date) -> !(date == null || date.isBefore(startDate) || date.isAfter(endDate));
    3737 }
    3838 }
Mathematics
Algorithms
Numbers

Division of Complex Numbers

Related Collection

Complex Analysis <-- click on the link to train on this Collection :D

The Problem

Given two complex numbers z = x + iy and w = u + iv, how do I divide one by the other, e.g. compute z / w (or the reverse)?

The Solution

Just as one may rationalize the denominator of 1 / sqrt(2) to obtain sqrt(2) / 2, it is also possible to real-ize the denominator of z / w by multiplying both the numerator and denominator by the complex conjugate of "w" w* = u - iv. Then use the identity i^2 = -1 where necessary and collect real and imaginary terms.

z / w
= (z * w*) / (w * w*)
= ((x + iy) * (u - iv)) / ((u + iv) * (u - iv))
= (xu - xiv + iyu - yvi^2) / (u^2 - (iv)^2)
= ((xu + yv) + i(yu - xv)) / (u^2 + v^2)
= ((xu + yv) / (u^2 + v^2)) + i((yu - xv) / (u^2 + v^2))

Also note that u^2 + v^2 = |w|^2 which may help to simplify your code further.

function divide(z, w) {
  var x = Re(z);
  var y = Im(z);
  var u = Re(w);
  var v = Im(w);
  const abs = z => Math.hypot(Re(z), Im(z));
  return new ComplexNumber((x * u + y * v) / Math.pow(abs(w), 2), (y * u - x * v) / Math.pow(abs(w), 2));
}

Calculate A = B + alpha * C

proc stream(b, c, alpha) {
    return b + alpha * c;
}
Mathematics
Algorithms
Numbers

Complex Addition and Subtraction

Related Collection

Complex Analysis

The Problem

Given two complex numbers z = x + iy and w = u + iv, how do I add them together? Furthermore, how do I compute z - w if required?

The Solution

For addition, adding two complex numbers is as easy as adding their real and imaginary components together. So z + w becomes (x + iy) + (u + iv) = (x + u) + i(y + v) and z - w becomes (x + iy) - (u + iv) = (x - u) + i(y - v).

function add(z, w) {
  var x = Re(z);
  var y = Im(z);
  var u = Re(w);
  var v = Im(w);
  return new ComplexNumber(x + u, y + v); // z + w = (x + u) + i(y + v)
}
function subtract(z, w) {
  var x = Re(z);
  var y = Im(z);
  var u = Re(w);
  var v = Im(w);
  return new ComplexNumber(x - u, y - v); // z - w = (x - u) + i(y - v)
}

Changed game of life to take an array of arrays of rows and columns.

Code
Diff
  • function nextGeneration(grid) {
      const neighborsInit = {
        l:true,bl:true,bc:true,br:true,r:true,tr:true,tc:true,tl:true
      };
      let neighbors = JSON.parse(JSON.stringify(neighborsInit));
      let liveNeighbors = 0;
      let isAlive = true;
      var nextGen = JSON.parse(JSON.stringify(grid));
      grid.map(function(row,rowIndex,rows){
        row.map(function(element,index,thisRow){
          liveNeighbors = 0;
          neighbors = JSON.parse(JSON.stringify(neighborsInit));
          if(element == 1){
            isAlive = true;
          } else {
            isAlive = false;
          }
    
          //Where to check
          if(rowIndex === 0){
            //If it is the first row don't look for life above
            neighbors.tr = neighbors.tc = neighbors.tl = false;
          }
          if(rowIndex === grid.length-1){
            //If it is the last row don't look for life below
            neighbors.br = neighbors.bc = neighbors.bl = false;
          }
          if(index == 0){
            //If it is the first column don't look for life left
            neighbors.tl = neighbors.l = neighbors.bl = false;
          }
          if(index == row.length-1){
            //If it is the last column don't look for life right
            neighbors.tr = neighbors.r = neighbors.br = false;
          }
          //Top
          if(neighbors.tl && grid[rowIndex-1][index-1] == 1){
            liveNeighbors++;
          }
          if(neighbors.tc && grid[rowIndex-1][index] == 1){
            liveNeighbors++;
          }
          if(neighbors.tr && grid[rowIndex-1][index+1] == 1){
            liveNeighbors++;
          }
          //right
          if(neighbors.r && grid[rowIndex][index+1] == 1){
            liveNeighbors++;
          }
          //Bottom
          if(neighbors.br && (grid[rowIndex+1][index+1] === 1)){
            liveNeighbors++;
          }
          if(neighbors.bc && grid[rowIndex+1][index] == 1){
            liveNeighbors++;
          }
          if(neighbors.bl && grid[rowIndex+1][index-1] == 1){
            liveNeighbors++;
          }
          //left
          if(neighbors.l && grid[rowIndex][index-1] == 1){
            liveNeighbors++;
          }
    
          //Live?
          if(isAlive){
    
            //Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
            if(liveNeighbors < 2){
              //kill
              //console.log('die from lonliness :(');
              nextGen[rowIndex][index] = 0;
            }
            //Any live cell with more than three live neighbours dies, as if by overcrowding.
            if(liveNeighbors > 3){
              //kill
              //console.log('died from over crowding');
              nextGen[rowIndex][index] = 0;
            }
          }
          //Any dead cell with exactly three live neighbours becomes a live cell.
          if(!isAlive && liveNeighbors == 3){
            nextGen[rowIndex][index] = 1;
          } else {
            //console.info('he stay ded');
          }
        });
      });
      return nextGen;
    }
  • 11 function nextGeneration(grid) {
    2- return grid;
    2+ const neighborsInit = {
    3+ l:true,bl:true,bc:true,br:true,r:true,tr:true,tc:true,tl:true
    4+ };
    5+ let neighbors = JSON.parse(JSON.stringify(neighborsInit));
    6+ let liveNeighbors = 0;
    7+ let isAlive = true;
    8+ var nextGen = JSON.parse(JSON.stringify(grid));
    9+ grid.map(function(row,rowIndex,rows){
    10+ row.map(function(element,index,thisRow){
    11+ liveNeighbors = 0;
    12+ neighbors = JSON.parse(JSON.stringify(neighborsInit));
    13+ if(element == 1){
    14+ isAlive = true;
    15+ } else {
    16+ isAlive = false;
    17+ }
    18+
    19+ //Where to check
    20+ if(rowIndex === 0){
    21+ //If it is the first row don't look for life above
    22+ neighbors.tr = neighbors.tc = neighbors.tl = false;
    23+ }
    24+ if(rowIndex === grid.length-1){
    25+ //If it is the last row don't look for life below
    26+ neighbors.br = neighbors.bc = neighbors.bl = false;
    27+ }
    28+ if(index == 0){
    29+ //If it is the first column don't look for life left
    30+ neighbors.tl = neighbors.l = neighbors.bl = false;
    31+ }
    32+ if(index == row.length-1){
    33+ //If it is the last column don't look for life right
    34+ neighbors.tr = neighbors.r = neighbors.br = false;
    35+ }
    36+ //Top
    37+ if(neighbors.tl && grid[rowIndex-1][index-1] == 1){
    38+ liveNeighbors++;
    39+ }
    40+ if(neighbors.tc && grid[rowIndex-1][index] == 1){
    41+ liveNeighbors++;
    42+ }
    43+ if(neighbors.tr && grid[rowIndex-1][index+1] == 1){
    44+ liveNeighbors++;
    45+ }
    46+ //right
    47+ if(neighbors.r && grid[rowIndex][index+1] == 1){
    48+ liveNeighbors++;
    49+ }
    50+ //Bottom
    51+ if(neighbors.br && (grid[rowIndex+1][index+1] === 1)){
    52+ liveNeighbors++;
    53+ }
    54+ if(neighbors.bc && grid[rowIndex+1][index] == 1){
    55+ liveNeighbors++;
    56+ }
    57+ if(neighbors.bl && grid[rowIndex+1][index-1] == 1){
    58+ liveNeighbors++;
    59+ }
    60+ //left
    61+ if(neighbors.l && grid[rowIndex][index-1] == 1){
    62+ liveNeighbors++;
    63+ }
    64+
    65+ //Live?
    66+ if(isAlive){
    67+
    68+ //Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
    69+ if(liveNeighbors < 2){
    70+ //kill
    71+ //console.log('die from lonliness :(');
    72+ nextGen[rowIndex][index] = 0;
    73+ }
    74+ //Any live cell with more than three live neighbours dies, as if by overcrowding.
    75+ if(liveNeighbors > 3){
    76+ //kill
    77+ //console.log('died from over crowding');
    78+ nextGen[rowIndex][index] = 0;
    79+ }
    80+ }
    81+ //Any dead cell with exactly three live neighbours becomes a live cell.
    82+ if(!isAlive && liveNeighbors == 3){
    83+ nextGen[rowIndex][index] = 1;
    84+ } else {
    85+ //console.info('he stay ded');
    86+ }
    87+ });
    88+ });
    89+ return nextGen;
    33 }
Mathematics
Algorithms
Numbers

Sinus Cardinalis

Related Kata

Implement the (Unnormalized) Cardinal Sine (JavaScript)

Summary

This Kumite extends the built-in Math object in JavaScript with the sinc method which computes the cardinal sine of the first argument x (a Number) passed in.

Implementation Details

Math.sinc receives two arguments: the first argument x (a Number) is required and the second argument isNormalized (a boolean) is optional. If the second argument is not specified or set to false, the function returns the historical (unnormalized) cardinal sine of x. Otherwise, if the second argument is set to true, the function will return the normalized cardinal sine of x instead. Any invalid arguments passed in will cause the function to throw a TypeError with a suitable message.

Code
Diff
  • Math.sinc = function (x, isNormalized = false) {
      // Type check "x" - if "x" is not a number then a TypeError is thrown
      if (typeof x !== 'number') throw new TypeError('In Math.sinc, the first argument "x" passed in must be a Number!');
      // Type check "isNormalized" - if it is not a boolean then a TypeError is thrown
      if (typeof isNormalized !== 'boolean') throw new TypeError('In Math.sinc, the second argument "isNormalized" passed in must be a Boolean!');
      // Special Case - sinc(0) = 1 regardless of which definition of cardinal sine is used
      if (x === 0) return 1;
      // If isNormalized is set to true then multiply argument by pi and pass into unnormalized cardinal sine
      if (isNormalized) return Math.sinc(Math.PI * x);
      // Otherwise just use sinc(x) = sin(x) / x and return the result
      return Math.sin(x) / x;
    };
  • 1-/*
    2- function.sinc.php
    3- A simple math function (with input validation)
    4- that computes the cardinal sine of a real
    5- number $x
    6- Author: Donald Leung
    7- NOTE: Comes with two user-defined constants
    8-*/
    9-// Constants (for use by the sinc() function as flags)
    10-define('SINC_DEFAULT', 0);
    11-define('SINC_NORMALIZED', 1);
    12-// Function declaration and definition
    13-function sinc($x, $flag = SINC_DEFAULT) {
    14- // Type check "x" - confirm that it is either of an integer or a float
    15- if (!is_int($x) && !is_float($x)) throw new InvalidArgumentException('In sinc(), the first argument "x" passed in must either be an integer or a float');
    16- // Validate the flag - it can only be one of SINC_DEFAULT and SINC_NORMALIZED
    17- if ($flag !== SINC_DEFAULT && $flag !== SINC_NORMALIZED) throw new InvalidArgumentException('The sinc() function only accepts 2 possible flags: SINC_DEFAULT and SINC_NORMALIZED');
    18- // Special Case: where x = 0, sinc(x) = sinc(0) = 1
    19- if ($x == 0) return 1;
    20- // If the flag is set to SINC_NORMALIZED then multiply the argument "x" by pi and compute its unnormalized cardinal sine at pi * x
    21- if ($flag === SINC_NORMALIZED) return sinc(M_PI * $x);
    22- // Otherwise just return the unnormalized cardinal sine of x
    23- return sin($x) / $x;
    24-}
    1+Math.sinc = function (x, isNormalized = false) {
    2+ // Type check "x" - if "x" is not a number then a TypeError is thrown
    3+ if (typeof x !== 'number') throw new TypeError('In Math.sinc, the first argument "x" passed in must be a Number!');
    4+ // Type check "isNormalized" - if it is not a boolean then a TypeError is thrown
    5+ if (typeof isNormalized !== 'boolean') throw new TypeError('In Math.sinc, the second argument "isNormalized" passed in must be a Boolean!');
    6+ // Special Case - sinc(0) = 1 regardless of which definition of cardinal sine is used
    7+ if (x === 0) return 1;
    8+ // If isNormalized is set to true then multiply argument by pi and pass into unnormalized cardinal sine
    9+ if (isNormalized) return Math.sinc(Math.PI * x);
    10+ // Otherwise just use sinc(x) = sin(x) / x and return the result
    11+ return Math.sin(x) / x;
    12+};
Code
Diff
  • const sayHello = (input='World') => `Hello ${input}!`
      
    
  • 1-function sayHello(input) {
    2- return !input ? "Hello World!" : "Hello " + input + "!"
    3-};
    1+const sayHello = (input='World') => `Hello ${input}!`
    2+
Numbers
Integers
Algorithms

Find the shortest or fastest answer.

Code
Diff
  • public class Kumite
    {
    // Unrolled div loop
      public static int Digits(ulong n) => n.ToString().Length;
    }
  • 11 public class Kumite
    22 {
    33 // Unrolled div loop
    4- public static int Digits(ulong n)
    5- {
    6- var l = 1;
    7- while(true)
    8- {
    9- if (n < 10) return l;
    10- if (n < 100) return l + 1;
    11- if (n < 1000) return l + 2;
    12- if (n < 10000) return l + 3;
    13- n /= 10000;
    14- l += 4;
    15- }
    16- }
    4+ public static int Digits(ulong n) => n.ToString().Length;
    1717 }

The Codewars built-in runBF interpreter should correctly interpret a CAT program. According to the specs, the runBF interpreter treats EOF as byte(-1).

,+[-.,+]

According to the Esolangs Wiki, the BF program presented in this Kumite often triggers interpreter bugs. Regardless, the Codewars built-in runBF interpreter should interpret the program correctly without any issues and return the string "Hello World!\n".

>++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->
+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.

Testing the Codewars built-in runBF interpreter with no program input and with a simple Hello World program that contains a simple (non-nested) loop. The interpreter should be able to interpret the program properly and return the string "Hello World!".

++++++++++[>+++++++>++++++++++>+++++++++++>+++>+++++++++<<<<<-]>++.>+.>--..+++.>++.>---.<<.+++.------.<-.>>+.

The exact same program as before but with some rather messy comments in between (and at the start and end of the program). The Codewars built-in runBF interpreter should correctly handle the program regardless and return the string "Hello World!".

Code
Diff
  • [
      This is a loop comment.
      Command characters, they should be ignored <here>.
      Including [matching square brackets].
      Oh, and "+" and >-< signs.
      And gibberish: skldfjsdklfjs,..sd,dsf,s.fd,++--sdfsdsdfKLSDJFKLDSJ[[[][]][][[[][]]]]
      And unmatched round brackets: ((((()))(((()))))))))))))))))))))))
    ]
    sdklfjsdkldfjskldfs+++++++++++++++++sdlkfjsdlkfjsdfklsdjfkldsjfd++++++++++++++++++SDLKFJSDKLJSDFKLDSFJFDSKLJDFS++++++++++++++++++++++++SDLKFJDSFKLJFSDKLDSFJKSLDFJDSFKLDFSJ+++++++++++++.>++++(+++++(+()++)+((++)(++)))++++++++++++++NESWNEWSNEWWWSEEEEE+++++++++++++++;;++++++++++++;;;;;++++++++++++;;;;+++++++++;;;;;++++++++++++********++++++++++.>+++*****++++++++++++++***;;;*****++++++++++++;;**;;;+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++.+++++sdfsfdsdfsdfsfd++++sdfsdffdsfds++sdfsdffsddfssdf+ (These last few plus signs should not affect the final output)
  • 1-++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++.
    1+[
    2+ This is a loop comment.
    3+ Command characters, they should be ignored <here>.
    4+ Including [matching square brackets].
    5+ Oh, and "+" and >-< signs.
    6+ And gibberish: skldfjsdklfjs,..sd,dsf,s.fd,++--sdfsdsdfKLSDJFKLDSJ[[[][]][][[[][]]]]
    7+ And unmatched round brackets: ((((()))(((()))))))))))))))))))))))
    8+]
    9+sdklfjsdkldfjskldfs+++++++++++++++++sdlkfjsdlkfjsdfklsdjfkldsjfd++++++++++++++++++SDLKFJSDKLJSDFKLDSFJFDSKLJDFS++++++++++++++++++++++++SDLKFJDSFKLJFSDKLDSFJKSLDFJDSFKLDFSJ+++++++++++++.>++++(+++++(+()++)+((++)(++)))++++++++++++++NESWNEWSNEWWWSEEEEE+++++++++++++++;;++++++++++++;;;;;++++++++++++;;;;+++++++++;;;;;++++++++++++********++++++++++.>+++*****++++++++++++++***;;;*****++++++++++++;;**;;;+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++.+++++sdfsfdsdfsdfsfd++++sdfsdffdsfds++sdfsdffsddfssdf+ (These last few plus signs should not affect the final output)

After doing:

  • Extract method
  • Move method donde calcular el precio (movie or rental)?
  • Unit test smell: Indirect Testing
  • Replace temp with query
  • Replace Type Code with State/Strategy
  • Replace Conditional with Polymorphism
  • Replace Constructor with Factory Method
Code
Diff
  • class RentalReport {
      statement(customer) {
        let result = "Rental Record for " + customer.name + "\n";
        customer.rentals.forEach((each) => {
          //show figures for this rental
          result += "\t" + each.movie.title+ "\t" + each.getAmount() + "\n";
        });
        //add footer lines
        result += "Amount owed is " + customer.getTotalAmount() + "\n";
        result += "You earned " + customer.getFrequentPoints() + " frequent renter points";
        return result;
      }
    }
    
    const MovieType = {
        CHILDREN: Symbol('CHILDREN'),
        REGULAR: Symbol('REGULAR'),
        NEW_RELEASE: Symbol('NEW_RELEASE'),
    }
    
    class Price {
      static create(priceCode) {
        switch (priceCode) {
          case MovieType.REGULAR:
            return new RegularPrice();
          case MovieType.NEW_RELEASE:
            return new NewReleasePrice();
          case MovieType.CHILDREN:
            return new ChildrenPrice();
        }
      }
      get code() {
        throw "not implemented";
      }
      getAmount(daysRented) {
        throw "not implemented";
      }
      getFrequentPoints(daysRented) {
        return 1;
      }
    }
    
    class ChildrenPrice extends Price {
      get code() {
        return MovieType.CHILDREN;
      }
      getAmount(daysRented) {
        let amount = 1.5;
        if (daysRented > 3)
          amount += (daysRented - 3) * 1.5;
        return amount;  
      }
    }
    
    class RegularPrice extends Price {
      get code() {
        return MovieType.REGULAR;
      }
      getAmount(daysRented) {
        let amount = 2;
        if (daysRented > 2)
          amount += (daysRented - 2) * 1.5;
        return amount;  
      }
    }
    
    class NewReleasePrice extends Price {
      get code() {
        return MovieType.NEW_RELEASE;
      }
      getAmount(daysRented) {
        return daysRented * 3;
      }
      getFrequentPoints(daysRented) {
        return daysRented > 1 ? 2 : 1;
      }
    }
    
    
    class Movie {
      constructor (title, priceCode) {
        this._title = title;
        this.priceCode = priceCode;
      }
      set priceCode(priceCode) {
        this._price = Price.create(priceCode);
      }
      get priceCode() {
        return this._price.code;
      }
      get title() {
        return this._title;
      }
      getAmount(daysRented) {
        return this._price.getAmount(daysRented);  
      }
      getFrequentPoints(daysRented) {
        return this._price.getFrequentPoints(daysRented);
      }
    }
    
    class Rental {
      constructor(movie, daysRented) {
        this._movie = movie;
        this._daysRented = daysRented;
      }
      get daysRented() {
        return this._daysRented;
      }
      get movie() {
        return this._movie;
      }
      getAmount() {
        return this.movie.getAmount(this.daysRented);
      }
      getFrequentPoints() {
        return this.movie.getFrequentPoints(this.daysRented);
      }
    }
    
    class Customer {
      constructor(name) {
        this._name = name;
        this._rentals = [];
      }
      get name() {
        return this._name;
      }
      get rentals() {
        return this._rentals;
      }
      addRental(rental) {
        this._rentals.push(rental);
      }
      getFrequentPoints() {
        return this.rentals.reduce((frequentPoints, rental) => frequentPoints + rental.getFrequentPoints(), 0);
      }
      getTotalAmount() {
        return this.rentals.reduce((amount, rental) => amount + rental.getAmount(), 0);
      }
    }
  • 11 class RentalReport {
    22 statement(customer) {
    3- let totalAmount = 0;
    4- let frequentRenterPoints = 0;
    55 let result = "Rental Record for " + customer.name + "\n";
    66 customer.rentals.forEach((each) => {
    7- let thisAmount = 0;
    8- //determine amounts for each line
    9- switch (each.movie.priceCode) {
    10- case MovieType.REGULAR:
    11- thisAmount += 2;
    12- if (each.daysRented > 2)
    2929 //show figures for this rental
    30- result += "\t" + each.movie.title+ "\t" + thisAmount + "\n";
    31- totalAmount += thisAmount;
    6+ result += "\t" + each.movie.title+ "\t" + each.getAmount() + "\n";
    3232 });
    3333 //add footer lines
    34- result += "Amount owed is " + totalAmount + "\n";
    35- result += "You earned " + frequentRenterPoints + " frequent renter points";
    9+ result += "Amount owed is " + customer.getTotalAmount() + "\n";
    10+ result += "You earned " + customer.getFrequentPoints() + " frequent renter points";
    3636 return result;
    3737 }
    38-
    3939 }
    4040
    4141 const MovieType = {
    4242 CHILDREN: Symbol('CHILDREN'),
    4343 REGULAR: Symbol('REGULAR'),
    4444 NEW_RELEASE: Symbol('NEW_RELEASE'),
    4545 }
    4646
    29+ return new ChildrenPrice();
    30+ }
    31+ }
    32+ get code() {
    33+ throw "not implemented";
    34+ }
    35+ getAmount(daysRented) {
    36+ throw "not implemented";
    37+ }
    38+ getFrequentPoints(daysRented) {
    39+ return 1;
    40+ }
    41+}
    42+
    43+class ChildrenPrice extends Price {
    44+ get code() {
    45+ return MovieType.CHILDREN;
    46+ }
    47+ getAmount(daysRented) {
    48+ let amount = 1.5;
    49+ if (daysRented > 3)
    50+ amount += (daysRented - 3) * 1.5;
    51+ return amount;
    52+ }
    53+}
    54+
    55+class RegularPrice extends Price {
    56+ get code() {
    57+ return MovieType.REGULAR;
    58+ }
    59+ getAmount(daysRented) {
    60+ let amount = 2;
    61+ if (daysRented > 2)
    62+ amount += (daysRented - 2) * 1.5;
    63+ return amount;
    64+ }
    65+}
    66+
    67+class NewReleasePrice extends Price {
    68+ get code() {
    69+ return MovieType.NEW_RELEASE;
    70+ }
    71+ getAmount(daysRented) {
    72+ return daysRented * 3;
    73+ }
    74+ getFrequentPoints(daysRented) {
    75+ return daysRented > 1 ? 2 : 1;
    76+ }
    77+}
    78+
    79+
    4747 class Movie {
    4848 constructor (title, priceCode) {
    4949 this._title = title;
    50- this._priceCode = priceCode;
    83+ this.priceCode = priceCode;
    84+ }
    85+ set priceCode(priceCode) {
    86+ this._price = Price.create(priceCode);
    5151 }
    5252 get priceCode() {
    53- return this._priceCode;
    89+ return this._price.code;
    5454 }
    5555 get title() {
    5656 return this._title;
    5757 }
    5858 }
    5959
    6060 class Rental {
    6161 constructor(movie, daysRented) {
    6262 this._movie = movie;
    6363 this._daysRented = daysRented;
    6464 }
    6565 get daysRented() {
    6666 return this._daysRented;
    6767 }
    6868 get movie() {
    6969 return this._movie;
    7070 }
    7171 }
    7272
    7373 class Customer {
    7474 constructor(name) {
    7575 this._name = name;
    7676 this._rentals = [];
    7777 }
    7878 get name() {
    7979 return this._name;
    8080 }
    8181 get rentals() {
    8282 return this._rentals;
    8383 }
    8484 addRental(rental) {
    8585 this._rentals.push(rental);
    8686 }
    8787 }
    88-
Hashes
Data Structures
Code
Diff
  • /* HashMap Example */
     
    import java.util.*;
    import java.util.function.*;
    import java.util.stream.*;
     
    class HashMapDemo {
      public static void main (final String[] args) throws Exception {
        System.out.println(toString(mapFromRangeClosed(1, 6, i -> 1), formattingEntry(), "\n"));
      }
      
      public static <T> Map<Integer, T> mapFromRangeClosed(final int lo, final int hi, final Function<Integer, T> valueMapper) {
        return IntStream.rangeClosed(lo, hi).boxed().collect(Collectors.toMap(Function.identity(), valueMapper));
      }
      
      public static <K,V> String toString(final Map<K, V> map, final Function<Map.Entry<K, V>, String> entryFormatter, final CharSequence delimiter) {
        return map.entrySet().stream().map(entryFormatter).collect(Collectors.joining(delimiter));
      }
      
      public static <K,V> Function<Map.Entry<K, V>, String> formattingEntry() {
        return e -> e.getKey() + " " + e.getValue();
      }
    }
  • 11 /* HashMap Example */
    22
    33 import java.util.*;
    4-import java.lang.*;
    5-import java.io.*;
    4+import java.util.function.*;
    5+import java.util.stream.*;
    66
    7-class HashMapDemo
    8-{
    9- public static void main (String[] args) throws java.lang.Exception {
    10- Map<Integer, Integer> map = new HashMap<Integer, Integer>() {{
    11- put(1, 1);
    12- put(2, 1);
    13- put(3, 1);
    14- put(4, 1);
    15- put(5, 1);
    16- put(6, 1);
    17- }};
    18-
    19- map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));
    7+class HashMapDemo {
    8+ public static void main (final String[] args) throws Exception {
    9+ System.out.println(toString(mapFromRangeClosed(1, 6, i -> 1), formattingEntry(), "\n"));
    10+ }
    11+
    12+ public static <T> Map<Integer, T> mapFromRangeClosed(final int lo, final int hi, final Function<Integer, T> valueMapper) {
    13+ return IntStream.rangeClosed(lo, hi).boxed().collect(Collectors.toMap(Function.identity(), valueMapper));
    14+ }
    15+
    16+ public static <K,V> String toString(final Map<K, V> map, final Function<Map.Entry<K, V>, String> entryFormatter, final CharSequence delimiter) {
    17+ return map.entrySet().stream().map(entryFormatter).collect(Collectors.joining(delimiter));
    18+ }
    19+
    20+ public static <K,V> Function<Map.Entry<K, V>, String> formattingEntry() {
    21+ return e -> e.getKey() + " " + e.getValue();
    2020 }
    2121 }
Code
Diff
  • import java.util.Map;
    import java.util.function.Function;
    import java.util.stream.Collectors;
    import java.util.stream.IntStream;
    
    /**
      Time Complexity  : O(N)
      Space Complexity : O(N)
    */
    class MaxOccurence {
    
      public static int findMax(final int[] nums) {
        return IntStream.of(nums).boxed()
          .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
          .entrySet().stream()
          .max(Map.Entry.comparingByValue())
          .map(Map.Entry::getKey).orElse(-1);
      }
    }
  • 1-import java.util.*;
    2-import java.util.List;
    33 import java.util.Map;
    4-import java.util.Optional;
    2+import java.util.function.Function;
    55 import java.util.stream.Collectors;
    66 import java.util.stream.IntStream;
    77
    88 /**
    99 Time Complexity : O(N)
    1010 Space Complexity : O(N)
    1111 */
    1212 class MaxOccurence {
    13-
    14- public static int findMax(int[] nums) {
    15- Optional<Map.Entry<Integer, List<Integer>>> max = IntStream.of(nums)
    16- .boxed()
    17- .collect(Collectors.groupingBy(num -> num))
    11+
    12+ public static int findMax(final int[] nums) {
    13+ return IntStream.of(nums).boxed()
    14+ .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
    15+ .entrySet().stream()
    16+ .max(Map.Entry.comparingByValue())
    17+ .map(Map.Entry::getKey).orElse(-1);
    2323 }
    2424 }
Code
Diff
  • import java.util.*;
    import java.util.stream.*;
    
    class Solution {
         
      public static int retSmallestPositiveInteger() {
        return IntStream.iterate(1, x -> x + 1).filter(Solution::hasSameDigitsForFactorsInRange).findFirst().getAsInt();
      }
      
      private static boolean hasSameDigitsForFactorsInRange(final int x) {
        final Map<Integer, Integer> xDigits = digitsOf(x);
        return IntStream.rangeClosed(2, 6).allMatch(f -> xDigits.equals(digitsOf(x * f)));
      }
      
      private static Map<Integer, Integer> digitsOf(final int number) {
        return String.valueOf(number).chars().map(Character::getNumericValue)
    			    .collect(HashMap<Integer, Integer>::new,
    			             (m, x) -> m.put(x, m.getOrDefault(x, 0) + 1),
    			             HashMap::putAll);
      }
    }
  • 11 import java.util.*;
    2+import java.util.stream.*;
    3+
    22 class Solution {
    5+
    6+ public static int retSmallestPositiveInteger() {
    7+ return IntStream.iterate(1, x -> x + 1).filter(Solution::hasSameDigitsForFactorsInRange).findFirst().getAsInt();
    8+ }
    33
    4-
    5- 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;
    9- }
    10- }
    10+ private static boolean hasSameDigitsForFactorsInRange(final int x) {
    11+ final Map<Integer, Integer> xDigits = digitsOf(x);
    12+ return IntStream.rangeClosed(2, 6).allMatch(f -> xDigits.equals(digitsOf(x * f)));
    13+ }
    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);
    18- }
    15+ private static Map<Integer, Integer> digitsOf(final int number) {
    16+ return String.valueOf(number).chars().map(Character::getNumericValue)
    17+ .collect(HashMap<Integer, Integer>::new,
    18+ (m, x) -> m.put(x, m.getOrDefault(x, 0) + 1),
    19+ HashMap::putAll);
    20+ }
    1919 }
Code
Diff
  • public class Primes {
      public static boolean isAPrime(int number) {
        if (number < 2 || (number % 2 == 0 && number != 2)) return false;
        for (int i = 3; i*i <= number; i += 2) {
          if (number % i == 0) return false;
        }
        return true;
      }
    }
  • 11 public class Primes {
    22 public static boolean isAPrime(int number) {
    3- if(number > 1 && number == 2) return true; //1 is not a prime number by definition
    4- else {
    5- for(int i = 3; i*i < number; i +=2) {
    6- if (number % i == 0) return false;
    7- }
    3+ if (number < 2 || (number % 2 == 0 && number != 2)) return false;
    4+ for (int i = 3; i*i <= number; i += 2) {
    5+ if (number % i == 0) return false;
    88 }
    99 return true;
    1010 }
    1111 }
class Node:
    def __init__(self,x,Next, Prev):
        self.data = x
        self.next = Next
        self.prev = Prev

class LinkedList:
    def __init__(self, *x):
        self.start = None
        self.last = None
        self.lenght = 0
        if x:
            for i in x:
                self.add(i)
        
    def __str__(self):
        if self.start != None:
            current = self.start
            out = '[ ' + str(current.data)
            while current.next != None:
                current = current.next
                out += ' '+ str(current.data)
            out += ' ]'
            return out
        
    def clear(self):
        self.__init__()
        
    def add(self, x):
        if self.start == None:
            self.start = self.last = Node(x,None,None)
            self.lenght += 1
        else:
            prev = self.last
            self.last.next = self.last = Node(x,None,None)
            self.last.prev = prev
            self.lenght += 1
            
    def addFew(self,*x):
        if x:
            for i in x:
                self.add(i)
            
            
    def remove(self, x,remove_all = False):
        current = self.start
        
        for i in range(self.lenght):
            if current.data == x:
                if current.prev == None:
                    if current.next != None:
                        self.start = current.next
                        current.next.prev = None
                        self.lenght -= 1
                        
                if current.next == None:
                    if current.prev != None:
                        current.prev.next = None
                        self.last = current.prev
                        self.last.next = None
                        self.lenght -= 1
                        
                if current.prev != None and current.next != None:
                    current.prev.next = current.next
                    current.next.prev = current.prev
                    self.lenght -= 1
                
                if current.next == None and current.prev == None:
                    clear(self)
                    self.lenght -= 0
                if remove_all == False:
                    break
            current = current.next
def binary_search(lst,item):
    low = 0
    high = len(lst) - 1
    while low <= high:
        mid = int((high + low)/2)
        guess = lst[mid]
        print (guess,mid)
        if guess > item:
            high = mid - 1
        if guess < item:
            low = mid + 1
        if guess == item:
            return mid
    else:
        return None

Changing "if n % i == 0" on line 6 to "if not(n % i)" made the time drop from 4126ms to 3810ms (as the longest time).

Code
Diff
  • from math import sqrt, floor
    
    def divisors(n):
        fact = [];
        for i in range(1, int(floor(sqrt(n))) + 1):
            if not(n % i):
                fact.append(i)
                if n / i != i:
                    fact.append(n / i)
        fact.sort()
        return fact
  • 11 from math import sqrt, floor
    22
    33 def divisors(n):
    44 fact = [];
    55 for i in range(1, int(floor(sqrt(n))) + 1):
    6- if n % i == 0:
    6+ if not(n % i):
    77 fact.append(i)
    88 if n / i != i:
    99 fact.append(n / i)
    1010 fact.sort()
    1111 return fact
Fundamentals
Lists
Data Structures
Functional Programming
Declarative Programming

That's good

/**
 * Created by ice1000 on 2017/4/27.
 *
 * @author ice1000
 */

fun <A, B, C : Any> zipWith(op: (A, B) -> C) = { x: Sequence<A> ->
	{ y: Sequence<B> ->
		val iX = x.iterator()
		val iY = y.iterator()
		generateSequence {
			if (iX.hasNext() and iY.hasNext()) op(iX.next(), iY.next())
			else null
		}
	}
}

fun <T : Any> generate() = zipWith { x: Int, y: T -> "[$y * x^$x]" } (
	generateSequence(0, Int::inc)
)

fun main(args: Array<String>) =
		generate<Int>()(sequenceOf(1, 1, 2, 3, 5, 8, 13, 21)).forEach(::println)

Quick implementation of splitter algorithm with use of regular expressions.

Probably could be done better if offset characters would be cut off & added to result array rather than adding some random chars to _str and removing them right before returning result.

Also instead of using regexp straightforward for-loop can make it better - because of lack of positive lookbehind in js rexegp implementations results are not always OK (problem with strings which length is not divisible by _n).

Code
Diff
  • function splitter (_str, _n) {
      _n = parseInt(_n);
      
      var offset = _n - _str.length % _n;
      
      if (offset !== _n) {
        _str += Math.pow(10, offset - 1);
      }
      
      var result = _str.split(new RegExp('(?=(?:.{' + _n + '})+$)', 'g'));
      
      if (offset !== _n) {
        var len = result.length,
            lastGroup = result[len - 1];
        
        result[len - 1] = lastGroup.substring(0, lastGroup.length - offset);
      }
      
      return result;
    }
  • 1-console.log(
    2- '123456'.split('')
    3-);
    1+function splitter (_str, _n) {
    2+ _n = parseInt(_n);
    3+
    4+ var offset = _n - _str.length % _n;
    5+
    6+ if (offset !== _n) {
    7+ _str += Math.pow(10, offset - 1);
    8+ }
    9+
    10+ var result = _str.split(new RegExp('(?=(?:.{' + _n + '})+$)', 'g'));
    11+
    12+ if (offset !== _n) {
    13+ var len = result.length,
    14+ lastGroup = result[len - 1];
    15+
    16+ result[len - 1] = lastGroup.substring(0, lastGroup.length - offset);
    17+ }
    18+
    19+ return result;
    20+}
ES2015
Babel
Objects

Robert.Cutright's implementation was great. (underscore.js has this function called omit http://underscorejs.org/#omit)
I forked his code and modified two parts.

First, I reused _.pick.
Second, I use reduce instead of assing and filter. Because reduce is more useful and simple solution to get result that I want.

Code
Diff
  • var _ = {};
    
    // Joeun's Pick implementation (GREAT JOB!)
    _.pick = (target, ...keys) => {
      if (typeof keys[0] == 'function') {
    
        var predicate = keys[0];
        keys = Object.keys(target);
        
        return keys.reduce((obj, key) => {
          return predicate(target[key], key, target) ? (obj[key] = target[key], obj) : obj;
        }, {})
      }
    
      return keys.reduce((obj, key) => {
        return obj[key] = target[key], obj;
      }, {});
    };
    
    // Robert.Cutright's implementation of the inverse of pick (called flick);
    // In other words, you supply the keys you want to throw away.
    _.flick = (target, ...keys) => {
      if (typeof keys[0] == 'function') {
    
        var predicate = keys[0];
        keys = Object.keys(target);
        
        return keys.reduce((obj, key) => {
          return predicate(target[key], key, target) ? obj : (obj[key] = target[key], obj);
        }, {})
      }
    
      var obj = Object.assign({}, target);
      Object.keys(obj).filter(key => keys.includes(key) ? delete obj[key] : obj[key]);
      return obj;
    };
    
    // Joeun's flick (called flick2)
    _.flick2 = (target, ...keys) => {
      if (typeof keys[0] == 'function') {
        var predicate = keys[0];
        return _.pick(target, (...args) => !predicate(...args)) // first part
      }
      
      var target_keys = Object.keys(target); // second part
      return target_keys.reduce((obj, key) => {
        return keys.includes(key) ? obj : (obj[key] = target[key], obj);
      }, {});
    };
    
  • 3131 }
    3232
    3333 var obj = Object.assign({}, target);
    3434 Object.keys(obj).filter(key => keys.includes(key) ? delete obj[key] : obj[key]);
    3535 return obj;
    3636 };
    37+
    38+// Joeun's flick (called flick2)
    39+_.flick2 = (target, ...keys) => {
    40+ if (typeof keys[0] == 'function') {
    41+ var predicate = keys[0];
    42+ return _.pick(target, (...args) => !predicate(...args)) // first part
    43+ }
    44+
    45+ var target_keys = Object.keys(target); // second part
    46+ return target_keys.reduce((obj, key) => {
    47+ return keys.includes(key) ? obj : (obj[key] = target[key], obj);
    48+ }, {});
    49+};

An implementation of the Sieve of Eratosthenes for finding prime numbers, fully focusing on performance.

The biggest performance gains come from forcing data set manipluation loops to be performed in the C-level code inside Python and not inside loops within the source code of the sieve. The places where this is used in particular are:

  • Striking out compounds in the sieve using the list[start::skip] = list syntax
  • Creating the final list of primes by using compress() to filter primes from the sieve
from math import sqrt, ceil
from itertools import compress

def sieve(until):
    if until < 2:
        return []
    store_len = until >> 1
    is_prime = [True] * store_len
    for offset, number in enumerate(range(3, int(sqrt(until)) + 1, 2)):
        if is_prime[offset]:
            first_compound_at = (number*number-3) >> 1
            nr_of_compounds = int(ceil((store_len-first_compound_at) / number))
            is_prime[first_compound_at::number] = [False] * nr_of_compounds
    return [2] + list(compress(range(3, until + 1, 2), is_prime))
Algorithms

This is my implementation of the Baillie-PSW prime number test. It is my response to a kumite title that claimed a fast prime test, while the implemented check was not actually that fast.

The response as provided by the isPrime() function is not simply a boolean, but instead a tuple providing two values: a boolean indicating probably primality and a string describing the test to lead to the provided conclusing.
Knowing the actual test that triggered the outcome has proven a very valuable tool during development. If this were production code, I'd most likely make the isPrime() function return a boolean directly.

It was great fun to puzzle together all the required pieces and to translate mathmatical notation into working programming code! I learned a lot of new things about modular arithmatics.

Code
Diff
  • from math import sqrt, ceil
    from itertools import compress
    
    TRIAL_DIVISION_UNTIL=1000
    
    
    def isPrime(n):
        """This primality check implements the composite Baillie-PSW test.
           See: https://en.wikipedia.org/wiki/Baillie%E2%80%93PSW_primality_test
    
           Input:
               n: the number to check
           Output:
               a tuple containing two elements:
               - True if (probable) prime, False otherwise
               - The name of the test that lead to that conclusion
           """
        if not isInteger(n):
            return (False, "not an integer")
        if isBelowLowestPrime(n):
            return (False, "below lowest prime")
        if isLowPrime(n):
            return (True, "low prime")
        if isTrialDivisionCompound(n):
            return (False, "trial division")
        if not isRabinMillerProbablePrime(n):
            return (False, "rabin-miller")
        if isPerfectSquare(n):
            return (False, "perfect square")
        if not isLucasProbablePrime(n):
            return (False, "lucas")
        return (True, "passed all tests")
    
    
    def isInteger(n):
        return int(n) == n
            
            
    def isBelowLowestPrime(n):
        return n < 2
    
    
    def isLowPrime(n):
        return (
            n <= TRIAL_DIVISION_UNTIL and
            n in lowPrimes
        )
    
    
    def isTrialDivisionCompound(n):
        return any(
            n % prime == 0
            for prime in lowPrimes
            if prime < n
        )
    
    
    def isRabinMillerProbablePrime(n):
        """Based on pseudo code for the Rabin-Miller algorithm.
           See: https://en.wikipedia.org/wiki/Miller-Rabin_primality_test
           This simple version implements only a single pass using base 2,
           as prescribed by the Baillie-PSW specification."""
        (factor, exponent) = factorizeBase2(n - 1)
        x = pow(2, factor, n)
        if x == 1 or x == n - 1:
            return True
        for _ in range(exponent - 1):
            x = pow(x, 2, n)
            if x == 1:
                return False
            elif x == n - 1:
                return True
        return False
    
    
    def isPerfectSquare(n):
        """A quick check to make sure that no perfect squares are fed to the
           Lucas probable prime check."""
        return isqrt(n) ** 2 == n
    
    
    def isqrt(n):
        """Integer square root, see:
          https://en.wikipedia.org/wiki/Integer_square_root"""
        x = n
        y = (x + 1) >> 1
        while y < x:
            x = y
            y = (x + n // x) >> 1
        return x
    
    
    def isLucasProbablePrime(n):
        """Code based on "Implementing a Lucas probable prime test" to be found at:
           https://en.wikipedia.org/wiki/Lucas_pseudoprime"""
    
        def getLucasSequenceInputAsSuggestedBySelfridge():
            seq = ((-1 if i&1 else 1) * (i*2 + 5) for i in range(0, n>>1))
            D = next((D for D in seq if jacobi(D, n) == -1))
            Q = (1 - D) // 4
            P = 1
            return D, Q, P
    
        D, Q, P = getLucasSequenceInputAsSuggestedBySelfridge()
    
        def computeLucasValue(subscript):
            U = V = k = 0
            for digit in format(subscript, "b"):
                U, V, k = doubleK(U, V, k)
                if digit == "1":
                    U, V, k = incrementK(U, V, k)
            return U, V, subscript
    
        def doubleK(U, V, subscript):
            return (U*V) % n,  (pow(V, 2, n) - 2 * pow(Q, subscript, n)) % n, subscript << 1
    
        def incrementK(U, V, subscript):
            U, V = (P*U + V), (D*U + P*V)
            makeEven = lambda x: x+n if x&1 else x
            div2modn = lambda x: (x >> 1) % n
            return (div2modn(makeEven(U)), div2modn(makeEven(V)), subscript+1)
    
        # Weak check.
        U, V, k = computeLucasValue(n+1)
        if U != 0:
            return False
    
        # Strong check.
        (factor, exponent) = factorizeBase2(n + 1)
        U, V, k = computeLucasValue(factor)
        if U == 0 or V == 0:
            return True
        for r in range(exponent-1):
            U, V, k = doubleK(U, V, k)
            if V == 0:
                return True
    
    
    def factorizeBase2(factor, exponent=0):
        """Factor out 2 from a number. For example factorizeBase2(80) returns (5, 4),
           which indicates that 2 ** 5 + 4 == 80."""
        if factor&1:
            return (factor, exponent)
        return factorizeBase2(factor >> 1, exponent + 1)
    
    
    def jacobi(a, n):
        """Compute the Jacobi symbol. The code uses ideas from:
           https://www.academia.edu/1012630/A_binary_algorithm_for_the_Jacobi_symbol"""
        t = 1
        while a:
            if a < 0:
                a = -a
                if n&3 == 3: t = -t
            while not a&1:
                a = a >> 1
                if n&7 == 3 or n&7 == 5: t = -t
            if (a < n):
                a, n = n, a
                if a&3 == 3 and n&3 == 3: t = -t
            a = (a - n) >> 1
            if n&7 == 3 or n&7 == 5: t = -t
        return t if n == 1 else 0
    
    
    def sieve(until):
        """This is an optimized sieve-algorithm that I created for an exercism.io assignment.
           On my system, it is able to produce primes until 10,000,000 in half a second.
           See: http://exercism.io/submissions/a6085623b76a6747d300420e"""
        if until < 2:
            return []
        store_len = until >> 1
        is_prime = [True] * store_len
        for offset, number in enumerate(range(3, int(sqrt(until)) + 1, 2)):
            if is_prime[offset]:
                first_compound_at = (number*number-3) >> 1
                nr_of_compounds = int(ceil((store_len-first_compound_at) / number))
                is_prime[first_compound_at::number] = [False] * nr_of_compounds
        return [2] + list(compress(range(3, until + 1, 2), is_prime))
    
    
    lowPrimes = set(sieve(TRIAL_DIVISION_UNTIL))
  • 1-import math
    2-def isprime(num):
    3- if num<2 or int(num)!=num: return False
    4- if not num%2 and num>2: return False
    5- for n in range(3,math.ceil((num-1)**.5)+1,2):
    6- if not num%n:
    7- return False
    8- return True
    1+from math import sqrt, ceil
    2+from itertools import compress
    3+
    4+TRIAL_DIVISION_UNTIL=1000
    5+
    6+
    7+def isPrime(n):
    8+ """This primality check implements the composite Baillie-PSW test.
    9+ See: https://en.wikipedia.org/wiki/Baillie%E2%80%93PSW_primality_test
    10+
    11+ Input:
    12+ n: the number to check
    13+ Output:
    14+ a tuple containing two elements:
    15+ - True if (probable) prime, False otherwise
    16+ - The name of the test that lead to that conclusion
    17+ """
    18+ if not isInteger(n):
    19+ return (False, "not an integer")
    20+ if isBelowLowestPrime(n):
    21+ return (False, "below lowest prime")
    22+ if isLowPrime(n):
    23+ return (True, "low prime")
    24+ if isTrialDivisionCompound(n):
    25+ return (False, "trial division")
    26+ if not isRabinMillerProbablePrime(n):
    27+ return (False, "rabin-miller")
    28+ if isPerfectSquare(n):
    29+ return (False, "perfect square")
    30+ if not isLucasProbablePrime(n):
    31+ return (False, "lucas")
    32+ return (True, "passed all tests")
    33+
    34+
    35+def isInteger(n):
    36+ return int(n) == n
    37+
    38+
    39+def isBelowLowestPrime(n):
    40+ return n < 2
    41+
    42+
    43+def isLowPrime(n):
    44+ return (
    45+ n <= TRIAL_DIVISION_UNTIL and
    46+ n in lowPrimes
    47+ )
    48+
    49+
    50+def isTrialDivisionCompound(n):
    51+ return any(
    52+ n % prime == 0
    53+ for prime in lowPrimes
    54+ if prime < n
    55+ )
    56+
    57+
    58+def isRabinMillerProbablePrime(n):
    59+ """Based on pseudo code for the Rabin-Miller algorithm.
    60+ See: https://en.wikipedia.org/wiki/Miller-Rabin_primality_test
    61+ This simple version implements only a single pass using base 2,
    62+ as prescribed by the Baillie-PSW specification."""
    63+ (factor, exponent) = factorizeBase2(n - 1)
    64+ x = pow(2, factor, n)
    65+ if x == 1 or x == n - 1:
    66+ return True
    67+ for _ in range(exponent - 1):
    68+ x = pow(x, 2, n)
    69+ if x == 1:
    70+ return False
    71+ elif x == n - 1:
    72+ return True
    73+ return False
    74+
    75+
    76+def isPerfectSquare(n):
    77+ """A quick check to make sure that no perfect squares are fed to the
    78+ Lucas probable prime check."""
    79+ return isqrt(n) ** 2 == n
    80+
    81+
    82+def isqrt(n):
    83+ """Integer square root, see:
    84+ https://en.wikipedia.org/wiki/Integer_square_root"""
    85+ x = n
    86+ y = (x + 1) >> 1
    87+ while y < x:
    88+ x = y
    89+ y = (x + n // x) >> 1
    90+ return x
    91+
    92+
    93+def isLucasProbablePrime(n):
    94+ """Code based on "Implementing a Lucas probable prime test" to be found at:
    95+ https://en.wikipedia.org/wiki/Lucas_pseudoprime"""
    96+
    97+ def getLucasSequenceInputAsSuggestedBySelfridge():
    98+ seq = ((-1 if i&1 else 1) * (i*2 + 5) for i in range(0, n>>1))
    99+ D = next((D for D in seq if jacobi(D, n) == -1))
    100+ Q = (1 - D) // 4
    101+ P = 1
    102+ return D, Q, P
    103+
    104+ D, Q, P = getLucasSequenceInputAsSuggestedBySelfridge()
    105+
    106+ def computeLucasValue(subscript):
    107