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.

Returns the total occurrence count of given digit d in integer sequence of 0 to n, where each integer element is squared.

Code
Diff
  • public class CountTheDigit {
    	
    	public static int nbDig(int n, int d) {
        return n < 0 || d < 0 || d > 9 ? -1 : (int) java.util.stream.IntStream.range(0,n)
          .map(i->i*i)
          .mapToObj(String::valueOf)
          .flatMapToInt(String::chars)
          .filter(i->Character.digit((char)i,10)==d)
          .count();
        }
    	
    }
  • 11 public class CountTheDigit {
    2-
    3-
    44
    55 public static int nbDig(int n, int d) {
    6- String number ="";
    7- int count=0;
    8- for(int i=0; i<n; i++) {
    9- number=(i*i)+"";
    10- count += number.length() - number.replace(d+"", "").length();
    11- }
    12- return count;
    4+ return n < 0 || d < 0 || d > 9 ? -1 : (int) java.util.stream.IntStream.range(0,n)
    5+ .map(i->i*i)
    6+ .mapToObj(String::valueOf)
    7+ .flatMapToInt(String::chars)
    8+ .filter(i->Character.digit((char)i,10)==d)
    9+ .count();
    1313 }
    1414
    1515 }

Example:

Find first most frequently occuring number in given array.

Given input {1, 2, 9, 3, 4, 3, 3, 1, 2, 4, 5, 3, 8, 3, 9, 0, 3, 2},

output should be 3 as it has highest frequency of occurence.

Note: when there's multiple numbers that have the max-occurrence, this solution returns the lowest value rather than the first value.

Code
Diff
  • import java.util.Map;
    import java.util.function.Function;
    import java.util.stream.Collectors;
    import java.util.stream.IntStream;
    
    /**
       I'm not sure how IntStream.sorted() performs time/space-wise,
       complexity noted here ignores whatever implementation is used to sort.
      Time Complexity  : O(N)
      Space Complexity : O(1)
    */
    class MaxOccurence {
    
      public static int findMax(int[] nums) {
            return nums == null || nums.length == 0 ? -1 : IntStream.concat(IntStream.of(nums).sorted(), IntStream.of(-1))
                    .collect(() -> new int[]{-1, -1, -1, -1},//{current,highest,curr-count,highest-count}
                            (arr, i) -> {
                                if (arr[0] != i) {
                                    if (arr[2] > arr[3]) {
                                        arr[1] = arr[0];
                                        arr[3] = arr[2];
                                    }
                                    arr[2] = 0;
                                    arr[0] = i;
                                }
                                ++arr[2];
                            }, null)[1];
      }
    }
  • 11 import java.util.Map;
    22 import java.util.function.Function;
    33 import java.util.stream.Collectors;
    44 import java.util.stream.IntStream;
    55
    66 /**
    7+ I'm not sure how IntStream.sorted() performs time/space-wise,
    8+ complexity noted here ignores whatever implementation is used to sort.
    77 Time Complexity : O(N)
    8- Space Complexity : O(N)
    10+ Space Complexity : O(1)
    99 */
    1010 class MaxOccurence {
    1111
    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);
    14+ public static int findMax(int[] nums) {
    15+ return nums == null || nums.length == 0 ? -1 : IntStream.concat(IntStream.of(nums).sorted(), IntStream.of(-1))
    16+ .collect(() -> new int[]{-1, -1, -1, -1},//{current,highest,curr-count,highest-count}
    17+ (arr, i) -> {
    18+ if (arr[0] != i) {
    19+ if (arr[2] > arr[3]) {
    20+ arr[1] = arr[0];
    21+ arr[3] = arr[2];
    22+ }
    23+ arr[2] = 0;
    24+ arr[0] = i;
    25+ }
    26+ ++arr[2];
    27+ }, null)[1];
    1818 }
    1919 }

A gozinta chain for n is a sequence {1,a,b,...,n} where each element properly divides the next.

There are eight gozinta chains for 12:
{1,12} ,{1,2,12}, {1,2,4,12}, {1,2,6,12}, {1,3,12}, {1,3,6,12}, {1,4,12} and {1,6,12}.

Let g(n) be the number of gozinta chains for n, so g(12)=8.
g(48)=48 and g(120)=132.

Given n, return the number of gozinta chains for g(n).

(Adapted from Project Euler, problem #548)

const g = (n) => {
  return "Good luck!"
}
Code
Diff
  • class Node:
        def __init__(self, x, Next, Prev):
            self.data = x
            self.next = Next
            self.prev = Prev
          
        
    class LinkedListIterator:
        def __init__(self, node):
            self.node = node
        
        def __iter__(self):
            return self
                
        def __next__(self):
            if not self.node:
                raise StopIteration
            value = self.node.data
            self.node = self.node.next        
            return value
    
           
    class LinkedList:
        def __init__(self, *x):
            self.start = None
            self.last = None
            self.length = 0
            self.addAll(x)
            
        def __iter__(self):
            return LinkedListIterator(self.start)
            
        def __str__(self):        
            out = '[ '+' '.join(map(str, self))+' ]'
            return out
        
        def clear(self):
            self.start = None
            self.last = None
            self.length = 0
            
        def add(self, x):
            if self.start == None:
                self.start = self.last = Node(x,None,None)
                self.length = 1
            else:
                prev = self.last
                self.last.next = self.last = Node(x,None,None)
                self.last.prev = prev
                self.length += 1
                
        def addAll(self, xs):        
            for i in xs:
                self.add(i)
        
        
        def remove_node(self, node):
            if not node.prev and node.next:            
                self.start = node.next
                node.next.prev = None
                self.length -= 1
                    
            elif not node.next and node.prev:            
                node.prev.next = None
                self.last = node.prev
                self.last.next = None
                self.length -= 1
                
            elif node.prev and node.next:
                node.prev.next = node.next
                node.next.prev = node.prev
                self.length -= 1
            else:
                self.clear()
                                
                
        def remove(self, x, remove_all = False):
            current = self.start        
            while current:
                if current.data == x:
                    self.remove_node(current)
                    if not remove_all:
                        break
                current = current.next
  • 11 class Node:
    2- def __init__(self,x,Next, Prev):
    2+ def __init__(self, x, Next, Prev):
    33 self.data = x
    44 self.next = Next
    55 self.prev = Prev
    6+
    7+
    8+class LinkedListIterator:
    9+ def __init__(self, node):
    10+ self.node = node
    11+
    12+ def __iter__(self):
    13+ return self
    14+
    15+ def __next__(self):
    16+ if not self.node:
    17+ raise StopIteration
    18+ value = self.node.data
    19+ self.node = self.node.next
    20+ return value
    66
    22+
    77 class LinkedList:
    88 def __init__(self, *x):
    99 self.start = None
    1010 self.last = None
    11- self.lenght = 0
    12- if x:
    13- for i in x:
    14- self.add(i)
    27+ self.length = 0
    28+ self.addAll(x)
    1515
    16- def __str__(self):
    17- if self.start != None:
    18- current = self.start
    19- out = '[ ' + str(current.data)
    20- while current.next != None:
    21- current = current.next
    22- out += ' '+ str(current.data)
    23- out += ' ]'
    24- return out
    30+ def __iter__(self):
    31+ return LinkedListIterator(self.start)
    2525
    33+ def __str__(self):
    34+ out = '[ '+' '.join(map(str, self))+' ]'
    35+ return out
    36+
    2626 def clear(self):
    27- self.__init__()
    38+ self.start = None
    39+ self.last = None
    40+ self.length = 0
    2828
    2929 def add(self, x):
    3030 if self.start == None:
    3131 self.start = self.last = Node(x,None,None)
    32- self.lenght += 1
    45+ self.length = 1
    3333 else:
    3434 prev = self.last
    3535 self.last.next = self.last = Node(x,None,None)
    3636 self.last.prev = prev
    37- self.lenght += 1
    50+ self.length += 1
    3838
    39- def addFew(self,*x):
    40- if x:
    41- for i in x:
    42- self.add(i)
    52+ def addAll(self, xs):
    53+ for i in xs:
    54+ self.add(i)
    4343
    69+ elif node.prev and node.next:
    70+ node.prev.next = node.next
    71+ node.next.prev = node.prev
    72+ self.length -= 1
    73+ else:
    74+ self.clear()
    75+
    4444
    45- def remove(self, x,remove_all = False):
    46- current = self.start
    47-
    48- for i in range(self.lenght):
    77+ def remove(self, x, remove_all = False):
    78+ current = self.start
    79+ while current:
    4949 if current.data == x:
    50- if current.prev == None:
    51- if current.next != None:
    52- self.start = current.next
    53- current.next.prev = None
    54- self.lenght -= 1
    81+ self.remove_node(current)
    82+ if not remove_all:
    7272 break
    7373 current = current.next

Given a number between 0-99999, the function number_to_english, return the same number pass to argument in letters.

Simple task, but the code is a little bit messy :D

Code
Diff
  • convertion = {
        0:'zero', 1:'one', 2:'two', 3:'three', 4:'four', 5:'five',
        6:'six', 7:'seven', 8:'eight', 9:'nine', 10:'ten',
        11:'eleven', 12:'twelve', 13:'thirteen', 14:'fourteen', 15:'fifteen',
        16:'sixteen', 17:'seventeen', 18:'eighteen', 19:'nineteen',
        20:'twenty', 30:'thirty', 40:'forty', 50:'fifty',
        60:'sixty', 70:'seventy', 80:'eighty', 90:'ninety'
    }
    
    
    def convert(num):
        if not 0 <= num <= 99999:
            return ''
    
        thousand, num = divmod(num, 1000)
        hundred, num = divmod(num, 100)
        ten, unit = divmod(num, 10)
        output = []
    
        if thousand:
            output += [convert(thousand), 'thousand']
        if hundred:
            output += [convertion[hundred], 'hundred']
    
        if ten == 1:
            output += [convertion[ten*10 + unit]]
        else:
            if ten:
                output += [convertion[ten*10]]
            if not output or unit:
                output += [convertion[unit]]
    
        return ' '.join(output)
    
    number_to_english = convert
  • 1-def mil(n):
    2- num={'0':'zero','1':'one','2':'two','3':'three','4':'four','5':'five','6':'six','7':'seven','8':'eight','9':'nine'}
    3- dec={'10':'ten','11':'eleven','12':'twelve','13':'thirteen','14':'fourteen','15':'fifteen','16':'sixteen','17':'seventeen','18':'eighteen','19':'nineteen'}
    4- dec_com={'20':'twenty','30':'thirty','40':'forty','50':'fifty','60':'sixty','70':'seventy','80':'eighty','90':'ninety'}
    5- mil="thousand"
    6- th=[]
    7- n_t=[x for x in n]
    8- for i in n_t:
    9- if len(n_t)==2:
    10- if i!='1' and n_t[1]=='0':
    11- th.append(dec_com[i+'0'])
    12- th.append(mil)
    13- break
    14- elif i=='1':
    15- th.append(dec[i+n_t[1]])
    16- th.append(mil)
    17- break
    18- else:
    19- th.append(dec_com[i+'0'])
    20- th.append(num[n_t[1]])
    21- th.append(mil)
    22- break
    23- else:
    24- th.append(num[i])
    25- th.append(mil)
    26- return th
    27-def cen(n):
    28- num={'0':'zero','1':'one','2':'two','3':'three','4':'four','5':'five','6':'six','7':'seven','8':'eight','9':'nine'}
    29- dec={'10':'ten','11':'eleven','12':'twelve','13':'thirteen','14':'fourteen','15':'fifteen','16':'sixteen','17':'seventeen','18':'eighteen','19':'nineteen'}
    30- dec_com={'20':'twenty','30':'thirty','40':'forty','50':'fifty','60':'sixty','70':'seventy','80':'eighty','90':'ninety'}
    31- cen="hundred"
    32- c=[]
    33- n_d=[x for x in n]
    34- for m in n_d:
    35- if n_d[0]!='0':
    36- c.append(num[m])
    37- c.append(cen)
    38- if n_d[1]=='0' and n_d[2]=='0':
    39- break
    40- elif n_d[1]=='0' and n_d[2]!='0':
    41- c.append(num[n_d[2]])
    42- break
    43- elif n_d[1]!='1' and n_d[2]=='0':
    44- c.append(dec_com[n_d[1]+'0'])
    45- break
    46- elif n_d[1]=='1':
    47- c.append(dec[n_d[1]+n_d[2]])
    48- break
    49- else:
    50- c.append(dec_com[n_d[1]+'0'])
    51- c.append(num[n_d[2]])
    52- break
    53- else:
    54- if n_d[1]=='0' and n_d[2]=='0':
    55- break
    56- elif n_d[1]=='0' and n_d[2]!='0':
    57- c.append(num[n_d[2]])
    58- break
    59- elif n_d[1]!='1' and n_d[2]=='0':
    60- c.append(dec_com[n_d[1]+'0'])
    61- break
    62- elif n_d[1]!='1' and n_d[2]!='0':
    63- c.append(dec_com[n_d[1]+'0'])
    64- c.append(num[n_d[2]])
    65- break
    66- elif n_d[1]=='1':
    67- c.append(dec[n_d[1]+n_d[2]])
    68- break
    69-
    70- return c
    71-def number_to_english(n):
    72- num={0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine'}
    73- dec={10:'ten',11:'eleven',12:'twelve',13:'thirteen',14:'fourteen',15:'fifteen',16:'sixteen',17:'seventeen',18:'eighteen',19:'nineteen'}
    74- dec_com={20:'twenty',30:'thirty',40:'forty',50:'fifty',60:'sixty',70:'seventy',80:'eighty',90:'ninety'}
    75- th=[]
    76- c=[]
    77- m='{0:,}'.format(n)
    78- m=m.split(",")
    79- try:
    80- if n<0 or type(n)==float or n>99999:
    81- pass
    82- elif n<10:
    83- c.append(num[n])
    84- elif n<20:
    85- c.append(dec[n])
    86- elif n%10==0 and n<99:
    87- c.append(dec_com[n])
    88- elif n<99:
    89- k=list(str(n))
    90- c.append(dec_com[int(k[0]+'0')])
    91- c.append(num[int(k[1])])
    92- else:
    93- c=cen(m[1])
    94- th=mil(m[0])
    95- except IndexError:
    96- if n<0 or type(n)==float or n>99999:
    97- pass
    98- elif n<10:
    99- c.append(num[n])
    100- elif n<20:
    101- c.append(dec[n])
    102- elif n%10==0 and n<99:
    103- c.append(dec_com[n])
    104- elif n<99:
    105- k=list(str(n))
    106- c.append(dec_com[int(k[0]+'0')])
    107- c.append(num[int(k[1])])
    108- else:
    109- c=cen(m[0])
    110- t=[]
    111- t.extend(th)
    112- t.extend(c)
    113- return " ".join(t)
    1+convertion = {
    2+ 0:'zero', 1:'one', 2:'two', 3:'three', 4:'four', 5:'five',
    3+ 6:'six', 7:'seven', 8:'eight', 9:'nine', 10:'ten',
    4+ 11:'eleven', 12:'twelve', 13:'thirteen', 14:'fourteen', 15:'fifteen',
    5+ 16:'sixteen', 17:'seventeen', 18:'eighteen', 19:'nineteen',
    6+ 20:'twenty', 30:'thirty', 40:'forty', 50:'fifty',
    7+ 60:'sixty', 70:'seventy', 80:'eighty', 90:'ninety'
    8+}
    9+
    10+
    11+def convert(num):
    12+ if not 0 <= num <= 99999:
    13+ return ''
    14+
    15+ thousand, num = divmod(num, 1000)
    16+ hundred, num = divmod(num, 100)
    17+ ten, unit = divmod(num, 10)
    18+ output = []
    19+
    20+ if thousand:
    21+ output += [convert(thousand), 'thousand']
    22+ if hundred:
    23+ output += [convertion[hundred], 'hundred']
    24+
    25+ if ten == 1:
    26+ output += [convertion[ten*10 + unit]]
    27+ else:
    28+ if ten:
    29+ output += [convertion[ten*10]]
    30+ if not output or unit:
    31+ output += [convertion[unit]]
    32+
    33+ return ' '.join(output)
    34+
    35+number_to_english = convert
Code
Diff
  • namespace Currying {
      using System;
    
      public static class Functions {
        public static Func<TOut1> Curry<TOut1>(this Func<TOut1> fn) => () => fn();
        public static Func<TIn1, TOut2> Curry<TIn1, TOut2>(this Func<TIn1, TOut2> fn) => a => fn(a);
        public static Func<TIn1, Func<TIn2, TOut3>> Curry<TIn1, TIn2, TOut3>(this Func<TIn1, TIn2, TOut3> fn) => a => b => fn(a, b);
        public static Func<TIn1, Func<TIn2, Func<TIn3, TOut4>>> Curry<TIn1, TIn2, TIn3, TOut4>(this Func<TIn1, TIn2, TIn3, TOut4> fn) => a => b => c => fn(a, b, c);
        public static Func<TIn1, Func<TIn2, Func<TIn3, Func<TIn4, TOut5>>>> Curry<TIn1, TIn2, TIn3, TIn4, TOut5>(this Func<TIn1, TIn2, TIn3, TIn4, TOut5> fn) => a => b => c => d => fn(a, b, c, d);
        public static Func<TIn1, Func<TIn2, Func<TIn3, Func<TIn4, Func<TIn5, TOut6>>>>> Curry<TIn1, TIn2, TIn3, TIn4, TIn5, TOut6>(this Func<TIn1, TIn2, TIn3, TIn4, TIn5, TOut6> fn) => a => b => c => d => e => fn(a, b, c, d, e);
      }
    }
  • 1-var test = new Currying.TestCurrying();
    2-test.testSequential();
    3-test.testRandom();
    1+namespace Currying {
    2+ using System;
    3+
    4+ public static class Functions {
    5+ public static Func<TOut1> Curry<TOut1>(this Func<TOut1> fn) => () => fn();
    6+ public static Func<TIn1, TOut2> Curry<TIn1, TOut2>(this Func<TIn1, TOut2> fn) => a => fn(a);
    7+ public static Func<TIn1, Func<TIn2, TOut3>> Curry<TIn1, TIn2, TOut3>(this Func<TIn1, TIn2, TOut3> fn) => a => b => fn(a, b);
    8+ public static Func<TIn1, Func<TIn2, Func<TIn3, TOut4>>> Curry<TIn1, TIn2, TIn3, TOut4>(this Func<TIn1, TIn2, TIn3, TOut4> fn) => a => b => c => fn(a, b, c);
    9+ public static Func<TIn1, Func<TIn2, Func<TIn3, Func<TIn4, TOut5>>>> Curry<TIn1, TIn2, TIn3, TIn4, TOut5>(this Func<TIn1, TIn2, TIn3, TIn4, TOut5> fn) => a => b => c => d => fn(a, b, c, d);
    10+ public static Func<TIn1, Func<TIn2, Func<TIn3, Func<TIn4, Func<TIn5, TOut6>>>>> Curry<TIn1, TIn2, TIn3, TIn4, TIn5, TOut6>(this Func<TIn1, TIn2, TIn3, TIn4, TIn5, TOut6> fn) => a => b => c => d => e => fn(a, b, c, d, e);
    11+ }
    12+}
Code
Diff
  • module Developer
      def are_you_dev?
        true
      end
    end
    
    class Ivan
      def give_me_beer?
        true
      end
    end
    class Andy < Ivan
    end
    
    class Vasa < Andy
      include Developer
    end
    
    class Kolya < Vasa
    end
    
    
  • 1+module Developer
    2+ def are_you_dev?
    3+ true
    4+ end
    5+end
    6+
    11 class Ivan
    22 def give_me_beer?
    33 true
    44 end
    55 end
    66 class Andy < Ivan
    77 end
    88
    99 class Vasa < Andy
    16+ include Developer
    1010 end
    1111
    1212 class Kolya < Vasa
    1313 end
    1414
Code
Diff
  • #include <algorithm>
    #include <math.h>
    
    template< class T >
    void Swap( T& a, T& b ) 
    {
      std::swap(a, b);
    }
  • 11 #include <algorithm>
    22 #include <math.h>
    33
    44 template< class T >
    55 void Swap( T& a, T& b )
    66 {
    7- /*
    8- a = (reinterpret_cast<long long >(a) + reinterpret_cast<long long >(b));
    9- b = (reinterpret_cast<long long >(a) - reinterpret_cast<long long >(b));
    10- a = (reinterpret_cast<long long >(a) - reinterpret_cast<long long >(b));
    11- */
    12-
    13- long long plla = *((long long*) &a);
    14- long long pllb = *((long long*) &b);
    15- plla = plla + pllb ;
    16- pllb = plla - pllb ;
    17- plla = plla - pllb ;
    18-
    19- a =*((T*) &plla);
    20- b =*((T*) &pllb);
    21-
    7+ std::swap(a, b);
    2222 }

using find breaks execution once it finds one gluten ingredient. same as someone with celiac disease.

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 !!ingredients
        .toLowerCase()
        .split(" ")
        .find(i => gluten.indexOf(i) > -1);
    }
  • 1616 "farro",
    1717 "graham",
    1818 "kamut",
    1919 "einkorn"
    2020 ];
    2121
    22- return gluten.some(g=>ingredients.includes(g.toUpperCase()));
    22+ return !!ingredients
    23+ .toLowerCase()
    24+ .split(" ")
    25+ .find(i => gluten.indexOf(i) > -1);
    2323 }
Code
Diff
  • # Method with three named arguments
    # https://robots.thoughtbot.com/ruby-2-keyword-arguments
    def c one: "one", two: "tow", three: "three"
    p "one: %s two: %s three: %s" % [one,two,three]
    
    end
    
    c  # calling without arguments
    c  two: "TWO2" # calling with one argument
    c  two: "2", one: 1111111 # Calling with 2 arguments with no order
    c(one: 1, two: 2, three: 3) # Passing 3 Named arguments
    c(two: 22, three: 333, one: 1 ) # Passing 3 Named arguments (mess the order)
    
    begin
      c  fore: "4" # calling with wrong argument
    rescue Exception => e 
      p e.message
      p e.class
    end
    begin
      #c (fore:"4") # calling with wrong argument
      # this lead to syntaxix error
    rescue Exception => e 
      p e.message
      p e.class
    end
    
    hash = {one: 'One', two: 'Two', three: 'Three'}
    c hash # calling with hash
    hash = {two: 'Two', three: 'Three', one: 'One', }
    c hash # calling with hash mess in order
    hash = { one: 'One', }
    c hash # calling with hash where not all argumetns listed
    
    # Super syntax
    hash = { two: '222', }
    c one: 1, **hash 
    # c one: 1, hash  # <== leads to error
    
    
    
    
    begin
      hash = { one: 'One', fore: "4" }
      c hash # calling with hash that contain pair unlisetd in named arguments
    rescue Exception => e 
      p e.message
      p e.class
    end
    
  • 2929 c hash # calling with hash
    3030 hash = {two: 'Two', three: 'Three', one: 'One', }
    3131 c hash # calling with hash mess in order
    3232 hash = { one: 'One', }
    3333 c hash # calling with hash where not all argumetns listed
    3434
    35+# Super syntax
    36+hash = { two: '222', }
    37+c one: 1, **hash
    38+# c one: 1, hash # <== leads to error
    39+
    40+
    41+
    42+
    3535 begin
    3636 hash = { one: 'One', fore: "4" }
    3737 c hash # calling with hash that contain pair unlisetd in named arguments
    3838 rescue Exception => e
    3939 p e.message
    4040 p e.class
    4141 end
Code
Diff
  • const wordCount = s => s.split(/\s/).filter(v=>!!v).length
    
  • 1-const wordCount = str => str.split(" ").filter(a=>!!a).length
    1+const wordCount = s => s.split(/\s/).filter(v=>!!v).length

Need to find amount of natural number that can be generated from an array of digit characters.

1) Answers is one number: total amount of natural numbers can be generated by moving elements of the array.
2) Each number have N digits, where N is an Array size.
3) Each number use each charachter from an Array oney once.

This code needs optimization.

P.S. Question from: https://stackoverflow.com/questions/47616564/find-amount-of-natural-numbers-generated-from-array-of-digit-characters

def g(a)
  answer = a.permutation(a.size)
  .select{|x| x.join.to_i.to_s.split("").size == a.size }
  .to_a.uniq.size
  answer
end

Make hahahah progamm

Improve it for different x inputs.

def ha x
  "Ha" + "-ha" * (x - 1)
end
Code
Diff
  • function sumOfMultiplesUnder(n) {
      return sumAll(--n,3) + sumAll(n,5) - sumAll(n,15);
    }
    function sumAll(n,m){
      return m * (Math.floor(n/m) + 1) * Math.floor(n/m)/2;
    }
  • 11 function sumOfMultiplesUnder(n) {
    2- return sumAll(--n,3)+sumAll(n,5)-sumAll(n,15)
    2+ return sumAll(--n,3) + sumAll(n,5) - sumAll(n,15);
    33 }
    44 function sumAll(n,m){
    5- return m*(Math.floor(n/m)+1)*Math.floor(n/m)/2
    5+ return m * (Math.floor(n/m) + 1) * Math.floor(n/m)/2;
    66 }

Try to make match in ruby to work like js mathc.

def slot s
  p "ONE scan"
  p "input: %s" % s
  p "output " + s.scan(/!+|\?+/).inspect
  
  p "TWO scan"
  p "input: %s" % s
  p "output " + s.scan(/([?!])\1*/).inspect
  
  p "ONE match"
  p "input: %s" % s
  p "match"
  s.match(/!+|\?+/).to_a.each{|x| p x}
  p "TWO  match"
  p "input: %s" % s
  p "match"
  s.match(/([?!])\1*/).to_a.each{|x| p x}
end

slot("!!!??")

Compare JS and Ruby REEGEX

RUBY s.scan(/!+|\?+/).inspect == JS s.match(/!+|\?+/g)

RUBY s.scan(/([?!])\1*/) != JS s.match(/([?!])\1*/g)

https://gist.github.com/lbvf50mobile/4b3cd312ad411e47582af40c7cbd4e05/edit

let slot = s => {
  console.log("ONE")
  console.log("input ", s)
  console.log("output" ,s.match(/!+|\?+/g))
  
  console.log("ONE")
  console.log("input ", s)
  console.log("output", s.match(/([?!])\1*/g))
}

slot("!!!??")

This my solusion pass the KATA, but it fails on
test generated by rolling 3 elements ASC and DESC arrays.
https://www.codewars.com/kata/simple-array-rotation/ruby

Generating tests:

"ROTATING [1, 10, 100]is ASC"
"rt: 0 ar: [1, 10, 100]is ASC a "rt: 1 ar: [10, 100, 1] ac and a>c"

"ROTATING [100, 10, 1]is DESC"
"rt: 0 ar: [100, 10, 1]is DESC a>b and b>c and a>c"
"rt: 1 ar: [10, 1, 100] a>b and b<c and a<c"

PS:
code for generate tests https://gist.github.com/lbvf50mobile/85f5abb840f3926feb80f7dfe85d2e01

def solve(arr)
   return "A" if asc_? arr
   return "D" if desc_? arr
   if( arr.size == 3)
     a = arr
     return "RA" if  a[0] > a[1] and a[1] < a[2];
   end
   ch_rd = arr.chunk_while{ |x,y| x > y }.to_a
   ch_ra = arr.chunk_while{ |x,y| x < y }.to_a
   return "RD" if ch_rd.any?{|x| desc_? x} and ch_rd.size == 2
   return "RA" if ch_ra.any?{|x| asc_? x} and ch_ra.size == 2
   
  
end

def asc_? arr
 arr == arr.sort
end
def desc_? arr
   arr == arr.sort.reverse
end

Added asserts for input validation.

Changed all int types to double

Reduced complexity by using floor() instead... test cases are still passing. (but there is some floating-point voodoo happening)

Added cout for future use.

Code
Diff
  • #include <cmath>
    #include <cassert>
    #include <iomanip>
    
    double custom_sqrt( double a, int accuracy=20 ) {
      assert( 0 <= a );
      assert( 0 <= accuracy );
      assert( 307 >= accuracy ); // evidently, values larger than 307 cause overflow
      const double ACC = std::pow( 10.0, accuracy );
      double result = sqrt( a );
      result *= ACC;
      result = std::floor( result );
      result /= ACC;
      //std::cout << std::setprecision(21) << result << std::endl;
      assert( 0 <= result );
      return result;
    }
  • 1-#include <math.h>
    1+#include <cmath>
    2+#include <cassert>
    3+#include <iomanip>
    22
    3-
    4-double custom_sqrt (int a,int accuracy=20) {
    5- double fIntegerPart;
    6- double fFloatingPart = modf((double)sqrt(a), &fIntegerPart);
    7-
    8- double fTempFloat = fFloatingPart * pow(10, accuracy);
    9- double fTempInt;
    10- fTempFloat = modf(fTempFloat, &fTempInt);
    11-
    12- fTempFloat /= pow(10, accuracy);
    13-
    14- fFloatingPart -= fTempFloat;
    15-
    16- return fIntegerPart+fFloatingPart;
    5+double custom_sqrt( double a, int accuracy=20 ) {
    6+ assert( 0 <= a );
    7+ assert( 0 <= accuracy );
    8+ assert( 307 >= accuracy ); // evidently, values larger than 307 cause overflow
    9+ const double ACC = std::pow( 10.0, accuracy );
    10+ double result = sqrt( a );
    11+ result *= ACC;
    12+ result = std::floor( result );
    13+ result /= ACC;
    14+ //std::cout << std::setprecision(21) << result << std::endl;
    15+ assert( 0 <= result );
    16+ return result;
    1717 }
a = "Baguette baguette baguette Encore!"
b = "Baguette baguette baguette Encore!"
p a == b
p a === b
object Adder {
  def add(a: Int, b: Int): Int = a + b
}
const text* = "Hello world!"
echo text
Code
Diff
  • SELECT name FROM greetings
    WHERE greeting like '%ll%';
  • 11 SELECT name FROM greetings
    2-WHERE upper(greeting) like '%HELLO%';
    2+WHERE greeting like '%ll%';

Just a simple check to confirm that nested NSArrays in Objective-C are allowed.

#import <Foundation/Foundation.h>

void testing() {
  @[
    @[@1, @0, @0],
    @[@0, @1, @0],
    @[@0, @0, @1]
  ];
  NSLog(@"<PASSED::>Success!\n");
}

C# 7.0+ features allow for syntatic sugar to reduce coding length. As well, the tests were using Is.Equal when Is.True and Is.False exist.

Code
Diff
  • namespace Solution 
    {
      using System;
      
      public static class logic
      {
        public static bool  Or(bool i, bool j) => i.i() + j.i() >= 1;
        public static bool And(bool i, bool j) => i.i() + j.i() == 2;
        public static bool Xor(bool i, bool j) => i.i() + j.i() == 1;
      }
      
      public static class BoolExtensions
      {
        public static int i(this bool val) => Convert.ToInt32(val);
      }
    }
  • 11 namespace Solution
    22 {
    33 using System;
    44
    55 public static class logic
    66 {
    7-
    8- public static bool Or(bool i, bool j) { return i.i() + j.i() >= 1; }
    9- public static bool And(bool i, bool j) { return i.i() + j.i() == 2; }
    10- public static bool Xor(bool i, bool j) { return i.i() + j.i() == 1; }
    11-
    7+ public static bool Or(bool i, bool j) => i.i() + j.i() >= 1;
    8+ public static bool And(bool i, bool j) => i.i() + j.i() == 2;
    9+ public static bool Xor(bool i, bool j) => i.i() + j.i() == 1;
    1212 }
    1313
    14-
    1515 public static class BoolExtensions
    1616 {
    17- public static int i(this bool val)
    18- {
    19- return Convert.ToInt32(val);
    20- }
    14+ public static int i(this bool val) => Convert.ToInt32(val);
    2121 }
    2222 }
Fundamentals

This one is even more succinct.

Code
Diff
  • #include <stdio.h>
    
    int helloCplusplus(){
      puts("Hello Cplusplus\n");
      return 0;
    }
  • 11 #include <stdio.h>
    22
    33 int helloCplusplus(){
    4- printf("Hello Cplusplus\n");
    4+ puts("Hello Cplusplus\n");
    55 return 0;
    66 }

Just confirming that UKIntsEqual from UnitKit accepts primitive integers as arguments as opposed to NSNumber.

#import <Foundation/Foundation.h>

Just testing if an NSArray can contain actual ints or only NSNumbers.

#import <Foundation/Foundation.h>

void testFunction() {
  NSMutableArray *myArray = [NSMutableArray array];
  [myArray addObject: 1];
  [myArray addObject: 2];
  [myArray addObject: 3];
  for (int i = 0; i < [myArray count]; i++) NSLog(@"%d\n", myArray[i]);
  // Invalid - compiles but doesn't give correct values 1, 2, 3
  // for (int i = 0; i < [myArray count]; i++) NSLog(@"%@\n", myArray[i]);
  NSLog(@"NSArray can indeed store `int`s as-is :D\n");
}

Just testing if NSInteger literals (e.g. @42) work on Codewars.

#import <Foundation/Foundation.h>

void testFunction() {
  NSLog(@"Just testing that the program isn't crashing here\n");
  NSNumber *answerToEverything = @42;
  NSLog(@"The answer to everything is: %@\n", answerToEverything);
  NSLog(@"Yes it works!  However NSNumber must be used and not NSInteger.\n");
}
Code
Diff
  • #include <numeric>
    
    int stray(std::vector<int> numbers)
    {    
        int sum = std::accumulate( numbers.begin(), numbers.end(), 0);
        int sample = numbers[0] == numbers[1] ? numbers[1] : numbers[2];
        return sum % sample + ( numbers.size() == (sum / sample) ? sample : 0 );
    }
  • 1-int stray(std::vector<int> numbers) {
    2-
    3- for(auto n = numbers.begin(); n != numbers.end(); ++n ){
    4- if (*n != numbers[0]) {
    5- if (*n != *(n + 1))
    6- return *n;
    7- else
    8- return numbers[0];
    9- }
    10- }
    11-};
    1+#include <numeric>
    2+
    3+int stray(std::vector<int> numbers)
    4+{
    5+ int sum = std::accumulate( numbers.begin(), numbers.end(), 0);
    6+ int sample = numbers[0] == numbers[1] ? numbers[1] : numbers[2];
    7+ return sum % sample + ( numbers.size() == (sum / sample) ? sample : 0 );
    8+}
Code
Diff
  • #define makeupper toupper
  • 1-char makeupper(char letter)
    2-{
    3- return toupper(letter);
    4-}
    1+#define makeupper toupper
Code
Diff
  • const rp = require('request-promise');
    
    async function getUserAllies(username) {
      const html = await rp(`https://www.codewars.com/users/${username}`);
      const [, allies] = html.match(/<div class=\"stat\"><b>Allies:<\/b>(\d+)<\/div>/);
      return +allies;
    }
  • 1-// const request = require('request');
    2-
    3-// function getUserAllies(username){
    4-// return new Promise(function(resolve, reject){
    5-// request('https://www.codewars.com/users/'+username, function(err, res, body){
    6-// let html = body;
    7-// let allies = (html.match(/<div class=\"stat\"><b>Allies:<\/b>(\d+)<\/div>/) || [,'null match'])[1];
    8-// resolve(+allies);
    9-// });
    10-// });
    11-// }
    12-
    13-// using request-promise to avoid wrapping a Promise
    1414 const rp = require('request-promise');
    1515
    16-function getUserAllies(username){
    17- return new Promise(() => {}); // never resolves
    3+async function getUserAllies(username) {
    4+ const html = await rp(`https://www.codewars.com/users/${username}`);
    5+ const [, allies] = html.match(/<div class=\"stat\"><b>Allies:<\/b>(\d+)<\/div>/);
    6+ return +allies;
    1818 }

Note

  • random() is not available in Swift 4.0
import Glibc // for random()

let a = random()

print(a)
Code
Diff
  • const hello = () => 'world';
  • 1-function hello() {
    2- return "world";
    3-}
    1+const hello = () => 'world';

This extension add a shuffled() method to any sequence.

References:

import Foundation 

extension Sequence {
  func shuffled() -> [Iterator.Element] {
    return Array(self).sorted { _,_ in drand48() < drand48() }
  }
}

// [Int] -> [Int]
print([1,2,3,4,5,6].shuffled())

// CountableClosedRange<Int> -> [Int]
print((1...6).shuffled())
(defun say-hello ()
  (tagbody
        (setq i 5)
   start
        (format t "[+] Hello there!~%")
        (decf i)
        (go end)
   end
        (and (zerop i) (return-from say-hello "this end."))
        (go start)
   ))

We are adding a new bus provider to our system. In order to implement a very specific requirement of this bus provider our system needs to be able to filter direct connections. We have access to a weekly updated list of bus routes in form of a bus route data file. As this provider has a lot of long bus routes, we need to come up with a proper service to quickly answer if two given stations are connected by a bus route.

public class HelloBus {
}
Code
Diff
  • const plus= (a,b,p) => a%1||b%1?plus(+(a+"0").replace(/(\.)(\d)/,"$2$1"),+(b+"0").replace(/(\.)(\d)/,"$2$1"),p+1):(a+b)/Math.pow(10,p)
    const sum = arr => arr.reduce((a,b)=>0+b===b?plus(a,b,0):a,0)
  • 1-const sum = arr => {
    2- const reducer = (sum, elem) => typeof elem === 'number' ? (sum + elem) : sum
    3- return arr.reduce(reducer, 0);
    4-}
    5-
    1+const plus= (a,b,p) => a%1||b%1?plus(+(a+"0").replace(/(\.)(\d)/,"$2$1"),+(b+"0").replace(/(\.)(\d)/,"$2$1"),p+1):(a+b)/Math.pow(10,p)
    2+const sum = arr => arr.reduce((a,b)=>0+b===b?plus(a,b,0):a,0)
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 };

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+]

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