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
  • // Code is in the preload
    fn person_builder(first_name: &str, last_name: &str) -> Person {
      Person { first_name: String::from(first_name), last_name: String::from(last_name) }
    }
  • 11 // Code is in the preload
    2-fn person_builder(first_name:&'static str, last_name: &'static str) -> Person {
    3- Person { first_name: first_name, last_name: last_name }
    2+fn person_builder(first_name: &str, last_name: &str) -> Person {
    3+ Person { first_name: String::from(first_name), last_name: String::from(last_name) }
    44 }
  • Fixed function argument (should be signed)
  • Check only uneven numbers in the main loop and treat mod 2 as a special case.
  • Removed useless cast.
Code
Diff
  • class PrimeNumber {
      public:
        // Check if given number is prime or not.
        static bool isPrime(long long num) {
            if (num <= 1) return false;
            if (num == 2) return true;
            if (num % 2 == 0) return false;
            for (long long i = 3; i * i <= num; i += 2) 
                if (num % i == 0) return false;
            return true;
        }
    };
  • 11 class PrimeNumber {
    22 public:
    33 // Check if given number is prime or not.
    4- static bool isPrime(unsigned long long num ) {
    5- if(num <= 1) return false;
    6- for( long long i = 2; (long long) i * i <= num; i++)
    7- if( num % i == 0) return false;
    4+ static bool isPrime(long long num) {
    5+ if (num <= 1) return false;
    6+ if (num == 2) return true;
    7+ if (num % 2 == 0) return false;
    8+ for (long long i = 3; i * i <= num; i += 2)
    9+ if (num % i == 0) return false;
    88 return true;
    99 }
    1010 };

Splits the string by the spaces present and then removes any empty strings.

Code
Diff
  • function wordCount(str) {
        return str.split(" ").filter(a=>a!="").length
    }
  • 1-function wordCount(str) {
    2- return str.trim() == '' ? 0 : (str.trim().split(" ")).length;
    1+function wordCount(str) {
    2+ return str.split(" ").filter(a=>a!="").length
    33 }

Using default params and arrow functions

Code
Diff
  • /* Array.reduce(
     * (accumulator, currentValue, currentIndex, array) => {
     * return accumulator + currentValue;
     * },
     * initialValue
     * );
     */
    const sumOfElements = (arr=[]) => arr.reduce((sum, currentValue) => sum + currentValue,0)
  • 11 /* Array.reduce(
    22 * (accumulator, currentValue, currentIndex, array) => {
    33 * return accumulator + currentValue;
    44 * },
    55 * initialValue
    66 * );
    77 */
    8-function sumOfElements(arr) {
    9- return (arr||[]).reduce((sum, currentValue) => sum + currentValue,0);
    10-}
    11-
    12-// Using ES6 Arrow Functions
    13-sumOfElements = arr => (arr||[]).reduce((sum, currentValue) => sum + currentValue,0)
    8+const sumOfElements = (arr=[]) => arr.reduce((sum, currentValue) => sum + currentValue,0)

The .unique() method for lists is super slow in Groovy, make it as fast as possible

class Uniquer {
  static List unique(List x) {
    x.groupBy { it }.keySet().collect()
  }
}
Code
Diff
  • >,+
    [-
      [-<+>>>+<<]>>>+
      [[-]<
        [->+<
          [->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<
            [->[-]>>+>+<<<]
          ]]]]]]]]<
        ]>>[>]++++++[-<++++++++>]>>
      ]<<<[.[-]<<<]
      <[->+>[-]+<<]>>[+++[->++++++++<]>.[-]<]<
    ]
  • 1-,[[->+>+<<]>>[-<<+>>]<[->>+>+>>-<<----------[[+]>>+<<]>>[[+]<<<----------<+>>>>]<<<[->+>+<<]>>[-<<+>>]<<<<]>[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]>++++++++++++++++++++++++++++++++++++++++++++++++.[-]>[-]<++++++++++++++++++++++++++++++++.[-]<<<-]++++++++++++++++++++++++++++++++++++++++++++++++.
    1+>,+
    2+[-
    3+ [-<+>>>+<<]>>>+
    4+ [[-]<
    5+ [->+<
    6+ [->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<
    7+ [->[-]>>+>+<<<]
    8+ ]]]]]]]]<
    9+ ]>>[>]++++++[-<++++++++>]>>
    10+ ]<<<[.[-]<<<]
    11+ <[->+>[-]+<<]>>[+++[->++++++++<]>.[-]<]<
    12+]
Code
Diff
  • bool Or(bool a, bool b){
    	return a ? true : (b ? true : false);
    }
    
    bool Xor(bool a, bool b){
    	return a ? (b ? false : true) : (b ? true : false);	
    }
    
    bool And(bool a, bool b){
    	return a ? (b ? true : false) : false;
    }
    
  • 11 bool Or(bool a, bool b){
    2- return a or b;
    2+ return a ? true : (b ? true : false);
    33 }
    44
    55 bool Xor(bool a, bool b){
    6- return a xor b;
    6+ return a ? (b ? false : true) : (b ? true : false);
    77 }
    88
    99 bool And(bool a, bool b){
    10- return a and b;
    10+ return a ? (b ? true : false) : false;
    1111 }
Code
Diff
  • function glutenDetector(ingredients){
      const gluten = [
      "wheat",
      "wheat flour",
      "triticale",
      "barley",
      "rye",
      "brewer's yeast",
      "malt",
      "wheatberries",
      "durum",
      "emmer",
      "semolina",
      "spelt",
      "farina",
      "farro",
      "graham",
      "kamut",
      "einkorn"
      ];
      
      return gluten.some(g=>ingredients.includes(g.toUpperCase()));
    }
  • 1616 "farro",
    1717 "graham",
    1818 "kamut",
    1919 "einkorn"
    2020 ];
    2121
    22- return ingredients
    23- .split(/[,()]/)
    24- .map((el) => el.trim().toLowerCase())
    25- .some((el) => gluten.includes(el));
    22+ return gluten.some(g=>ingredients.includes(g.toUpperCase()));
    2626 }

This kumite is not working as intended so just testing something.

Code
Diff
  • func hello() { 
    
    print("Hello Swift 4!")
    
    }
  • 1-print("Hello Swift!")
    1+func hello() {
    2+
    3+print("Hello Swift 4!")
    4+
    5+}

No need to declare number outside of for loop.

Code
Diff
  • public class CountTheDigit {
    	public static int nbDig(int n, int d) {
        int count=0;
        for(int i=0; i<n; i++) {
    			String number=(i*i)+"";
    			count +=  number.length() - number.replace(d+"", "").length();
    	  }
      	return count;
      }
    }
  • 11 public class CountTheDigit {
    22 public static int nbDig(int n, int d) {
    3- String number = "";
    44 int count=0;
    55 for(int i=0; i<n; i++) {
    6- number=(i*i)+"";
    5+ String number=(i*i)+"";
    77 count += number.length() - number.replace(d+"", "").length();
    88 }
    99 return count;
    1010 }
    1111 }
Code
Diff
  • def euler(num):
        sum=0
        for x in range(num):
            if x%3==0 or x%5==0:
                sum += x
        return sum   
  • 1-def mul():
    1+def euler(num):
    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
    3+ for x in range(num):
    4+ if x%3==0 or x%5==0:
    5+ sum += x
    77 return sum

refactorting

Code
Diff
  • function nextGeneration(grid) {
        // pregenerated coords
        const neighboursCords = [[0, 1], [0, -1], [1, 1], [1, 0], [1, -1], [-1, 1], [-1, 0], [-1, -1]];
        const neighboursCollector = (rowIndex, columnIndex) => ([x, y]) => grid[rowIndex + x][columnIndex + y];
        const sum = (a, b) => a + b;
    
        return grid.map((row, rowIndex) =>
            row.map((column, columnIndex) => {
    
                const isValid = rowIndex !== 0 && columnIndex !== 0 &&
                    rowIndex < grid.length - 1 && columnIndex < row.length - 1;
    
                if (!isValid) return 0;
    
                const currentCellValuesCollector = neighboursCollector(rowIndex, columnIndex);
                const neighboursCount = neighboursCords
                    .map(currentCellValuesCollector)
                    .reduce(sum);
    
                return +(neighboursCount === 3 || (column === 1 && neighboursCount === 2));
            })
        );
    }
  • 11 function nextGeneration(grid) {
    2- var neighboursCords = [[0, 1], [0, -1], [1, 1], [1, 0], [1, -1], [-1, 1], [-1, 0], [-1, -1]];
    3-
    4- return grid.map((r, ri) =>
    5- r.map((c, ci) => {
    6-
    7- if (ri !== 0 && ci !== 0 && ri < grid.length - 1 && ci < r.length - 1) {
    8- let neighboursCount = neighboursCords
    9- .reduce((s, v) => s += grid[ri + v[0]][ci + v[1]], 0);
    10-
    11- return 0 + (neighboursCount === 3 || (c === 1 && neighboursCount === 2));
    12- }
    13-
    14- return 0;
    15- })
    16- );
    2+ // pregenerated coords
    3+ const neighboursCords = [[0, 1], [0, -1], [1, 1], [1, 0], [1, -1], [-1, 1], [-1, 0], [-1, -1]];
    4+ const neighboursCollector = (rowIndex, columnIndex) => ([x, y]) => grid[rowIndex + x][columnIndex + y];
    5+ const sum = (a, b) => a + b;
    6+
    7+ return grid.map((row, rowIndex) =>
    8+ row.map((column, columnIndex) => {
    9+
    10+ const isValid = rowIndex !== 0 && columnIndex !== 0 &&
    11+ rowIndex < grid.length - 1 && columnIndex < row.length - 1;
    12+
    13+ if (!isValid) return 0;
    14+
    15+ const currentCellValuesCollector = neighboursCollector(rowIndex, columnIndex);
    16+ const neighboursCount = neighboursCords
    17+ .map(currentCellValuesCollector)
    18+ .reduce(sum);
    19+
    20+ return +(neighboursCount === 3 || (column === 1 && neighboursCount === 2));
    21+ })
    22+ );
    1717 }

Use snippets in Test Cases and Preloaded sections.

# Uncomment method redefinitions and errors will be thrown(can't publish with errors). (ノ^_^)ノ┻━┻
class NilClass
  # def ==(o)
  #   true
  # end
  # def !=(o)
  #   true
  # end
end

class Object
  # def ==(o)
  #   true
  # end
  # def !=(o)
  #   true
  # end
end

def method
  # nil
end
Code
Diff
  • #!/bin/bash
    for i in $(eval echo {1..$3});
    do
    if [ $(( $i % ( $1*$2) )) -eq 0 ]
    then
    echo $i
    fi
    done
  • 11 #!/bin/bash
    22 for i in $(eval echo {1..$3});
    33 do
    4-if [ `expr $i % $1` -eq 0 -a `expr $i % $2` -eq 0 ]
    4+if [ $(( $i % ( $1*$2) )) -eq 0 ]
    55 then
    66 echo $i
    77 fi
    88 done
char makeupper(char letter) 
{
  return toupper(letter);
}
Algorithms

Based on the pseudocode at: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm

Please check the test cases for an example input.

function dijkstra(numberOfVertices, edges, source, target) {
  if (target >= numberOfVertices) throw new Error('target outside available vertices');
  if (source < 0 || numberOfVertices === 0) throw new Error('source outside available vertices');

  const dist = {};
  const prev = {};
  const q = [];
  
  for (let v = 0; v < numberOfVertices; v++) {
    dist[v] = Infinity;
    prev[v] = null;
    q.push(v);
  }
  dist[source] = 0;
  
  while (q.length) {
    // Node with the least distance will be selected first
    const u = q.reduce((minV, v) => dist[v] < dist[minV] ? v : minV );
    
    if (u === target) break;
    
    // Remove u from q
    q.splice(q.indexOf(u), 1);
    
    (edges[u] || [])
      .forEach(edge => {
        const alt = dist[u] + edge.cost;
        if (alt < dist[edge.to]) {
          dist[edge.to] = alt;
          prev[edge.to] = u;
        }
      });
  }

  if (dist[target] === Infinity) return null;
  
  const s = [];
  let u = target;
  while (prev[u] !== null) {
    s.unshift(u);
    u = prev[u];
  }
  s.unshift(u);
  return s;
}

I've made changes that sum method ignores everything but numbers
Also I've refactored code to ES6

Code
Diff
  • const sum = arr => {
      const reducer = (sum, elem) => typeof elem === 'number' ? (sum + elem) : sum
      return arr.reduce(reducer, 0);
    }
    
    
  • 1-function sum(arr) {
    2- return arr.reduce((sum, elem) => sum + elem, 0);
    1+const sum = arr => {
    2+ const reducer = (sum, elem) => typeof elem === 'number' ? (sum + elem) : sum
    3+ return arr.reduce(reducer, 0);
    33 }
    5+
Puzzles
Games
Sequences
Arrays
Arithmetic
Mathematics
Algorithms
Numbers
Recursion
Computability Theory
Theoretical Computer Science
Code
Diff
  • def ulam_sequence(u = 1, v = 2, n = 10):
        print()
        try:
            # Input manipulation just for fun :)
            if u == v or any(map(lambda x: int(x) != x or x < 1, (u, v))) or int(n) != n:
                raise ValueError
        except ValueError:
            print('ValueError: All arguments should be integer, and the first two should be different and positive.')
            print((u, v, n), end = ' => ')
            n = int(abs(n))
            if n > 0:
                u, v = map(lambda x:x if x > 0 else x + 1, map(lambda x:int(abs(x)), (u, v)))
                v = v if u != v else u + 1
        finally:
            print((u, v, n), end = ': ')
            if n == 0:
                print([])
                return []
            seq = sorted([u, v])
            seq2 = seq
            while len(seq) < n:
                # Test the first half of the sequence. To be proven?
                new = seq[-1] + 1
                while len(list(filter(lambda i : new - seq[i] in seq and new != seq[i]
                    + seq[i], range(len(seq) // 2 + (1 if len(seq) > 4 else 0))))) != 1:
                    new += 1
                seq.append(new)
            while len(seq2) < n:
                # Test the full sequence
                new = seq2[-1] + 1
                while len(list(filter(lambda i : new - seq2[i] in seq2 and new != seq2[i]
                    + seq2[i], range(len(seq2))))) != 2:
                    new += 1
                seq2.append(new)
            print(seq[:n] if seq == seq2 else (seq[:n], seq2[:n]))
            return seq[:n] if seq == seq2 else seq2[:n]
    
    ulam_sequence()
    ulam_sequence(4, 7, 0)
    ulam_sequence(-1.3, .5)
  • 1-def ulam_sequence(u0, u1, n):
    2- u = [u0, u1]
    3- nn = u[-1] + 1
    4- while len(u) < n:
    5- count = 0
    6- for i in u:
    7- if nn - i in u and nn - i != i:
    8- count += 1
    9- if count >= 3:
    10- break
    11- nn += 1
    12- if count == 2:
    13- u.append(nn)
    14- nn += 1
    15- return u
    16-
    17-
    1+def ulam_sequence(u = 1, v = 2, n = 10):
    2+ print()
    3+ try:
    4+ # Input manipulation just for fun :)
    5+ if u == v or any(map(lambda x: int(x) != x or x < 1, (u, v))) or int(n) != n:
    6+ raise ValueError
    7+ except ValueError:
    8+ print('ValueError: All arguments should be integer, and the first two should be different and positive.')
    9+ print((u, v, n), end = ' => ')
    10+ n = int(abs(n))
    11+ if n > 0:
    12+ u, v = map(lambda x:x if x > 0 else x + 1, map(lambda x:int(abs(x)), (u, v)))
    13+ v = v if u != v else u + 1
    14+ finally:
    15+ print((u, v, n), end = ': ')
    16+ if n == 0:
    17+ print([])
    18+ return []
    19+ seq = sorted([u, v])
    20+ seq2 = seq
    21+ while len(seq) < n:
    22+ # Test the first half of the sequence. To be proven?
    23+ new = seq[-1] + 1
    24+ while len(list(filter(lambda i : new - seq[i] in seq and new != seq[i]
    25+ + seq[i], range(len(seq) // 2 + (1 if len(seq) > 4 else 0))))) != 1:
    26+ new += 1
    27+ seq.append(new)
    28+ while len(seq2) < n:
    29+ # Test the full sequence
    30+ new = seq2[-1] + 1
    31+ while len(list(filter(lambda i : new - seq2[i] in seq2 and new != seq2[i]
    32+ + seq2[i], range(len(seq2))))) != 2:
    33+ new += 1
    34+ seq2.append(new)
    35+ print(seq[:n] if seq == seq2 else (seq[:n], seq2[:n]))
    36+ return seq[:n] if seq == seq2 else seq2[:n]
    37+
    38+ulam_sequence()
    39+ulam_sequence(4, 7, 0)
    40+ulam_sequence(-1.3, .5)

I have built two small projects. I wanna with u guys together compare and improve my code quality as well as urs :)
Project A:
Console based bowling game with Java.
-> like the title, it's a game. There are totally 10 rounds per game, after that, the total score will be calculated as usual bowling game. The user can chooose direction as well as strengh.

Project B:
Console library
-> there are three kinds of CSV files: Book, Author and Magazine. The User can choose all books of one specific Author; Can also choose all magazines of one specific Author; Can Based book lookup the information of specifc Author, like his email adresse, or firstname, lastname etc..

I have create two github reposity of my solutions:
Project A: https://github.com/PigeonT/bowling
Project B: https://github.com/PigeonT/bookcontroller

var a = 0;

I have built two project:

Project A: Using Java built one console bowling game.
The User can play for ten rounds. After that the score will be calculated based on real bowling score rule.

Project B: Built one very simple console project that read three CSV files. One is author, One is book and one is magazine. The Auther has Email, Firstname, Lastname, books, maganzin column.
Book has ISBN, bookname, author.
Magazin has ISBN, magazin name, author.

The User can search book based one author name, ISBN etc.
The User can also search the user infomation (firstname, email..) based one book named.

Code are in github repository:
Bowling Game is https://github.com/PigeonT/bowling
Book project is https://github.com/PigeonT/bookcontroller

8
Code
Diff
  • let greeting = {
      en: 'Hello',es: 'Hola',
      de: 'Hallo',fr: 'Bonjour',
      ja: 'こんにちは',ro: 'buna',
      ru: 'Здравствуйте',zh: '你好',
      ko: '안녕하세요',tr: 'Merhaba',
      vi: 'xin chào'}
    const sayHello = (lang,name) => lang ? `${greeting[lang]} ${name}!` : "I don't speak that langauge"
    
  • 1-function sayHello(input) {
    2- return !input ? "Hello World!" : "Hello " + input + "!"
    3-};
    1+let greeting = {
    2+ en: 'Hello',es: 'Hola',
    3+ de: 'Hallo',fr: 'Bonjour',
    4+ ja: 'こんにちは',ro: 'buna',
    5+ ru: 'Здравствуйте',zh: '你好',
    6+ ko: '안녕하세요',tr: 'Merhaba',
    7+ vi: 'xin chào'}
    8+const sayHello = (lang,name) => lang ? `${greeting[lang]} ${name}!` : "I don't speak that langauge"
Numbers
Integers
Algorithms
Code
Diff
  • using System;
    using System.Linq;
    
    public class Kumite
    {
      public static int Digits(ulong n)
      {
        //GEEEEEEET DUUUUUUNKED OOOOOOOOOOOOOON
        int theseDigitsShouldREALLYBeCountedImSureOfIt = n
        .ToString()
        .ToCharArray()
        .Select((c,i)=>new{_char = c, ShouldBeCounted = true, index = i})
        .Select((a,i)=>new{charValue = a._char-'0', shouldREALLYbecounted = a.ShouldBeCounted && a.index==i})
        .OrderBy(a=>a.charValue)
        .ToArray()
        .Where(a=>a.shouldREALLYbecounted.ToString()=="True")
        .ToList()
        .ToArray()
        .Length;
        
        
        int thatNameWasTooLong = theseDigitsShouldREALLYBeCountedImSureOfIt;
        int soWasThatOne = thatNameWasTooLong;
        int betterstill = soWasThatOne;
        int thisone = betterstill;
        int _this = thisone;
        int _ = _this;
        return _;
       } 
    }
  • 1+using System;
    2+using System.Linq;
    3+
    11 public class Kumite
    22 {
    3-// Unrolled div loop
    4- public static int Digits(ulong n) => n.ToString().Length;
    6+ public static int Digits(ulong n)
    7+ {
    8+ //GEEEEEEET DUUUUUUNKED OOOOOOOOOOOOOON
    9+ int theseDigitsShouldREALLYBeCountedImSureOfIt = n
    10+ .ToString()
    11+ .ToCharArray()
    12+ .Select((c,i)=>new{_char = c, ShouldBeCounted = true, index = i})
    13+ .Select((a,i)=>new{charValue = a._char-'0', shouldREALLYbecounted = a.ShouldBeCounted && a.index==i})
    14+ .OrderBy(a=>a.charValue)
    15+ .ToArray()
    16+ .Where(a=>a.shouldREALLYbecounted.ToString()=="True")
    17+ .ToList()
    18+ .ToArray()
    19+ .Length;
    20+
    21+
    22+ int thatNameWasTooLong = theseDigitsShouldREALLYBeCountedImSureOfIt;
    23+ int soWasThatOne = thatNameWasTooLong;
    24+ int betterstill = soWasThatOne;
    25+ int thisone = betterstill;
    26+ int _this = thisone;
    27+ int _ = _this;
    28+ return _;
    29+ }
    55 }
Code
Diff
  • // add the values "codewars" to the websites array
    var websites = ['codewars'];
  • 11 // add the values "codewars" to the websites array
    2-var websites = ['codears'];
    2+var websites = ['codewars'];
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<>()
Arrays
Code
Diff
  • const func = (N, p) => Array(N).fill().map((_,i)=>Math.abs(i-p));
  • 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)=>Math.abs(i-p));
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))

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

println("Hello Julia!")
const hello = "world"
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()
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+};

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 }