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.

Refactored to insert in order. This may run a bit faster due to no longer using sort() function.

Code
Diff
  • def divisors(n):
        fact = []
        for i in range(1, int(n**0.5) + 1):
            if not(n % i):
                v = n // i
                if v != i:
                    fact.insert(len(fact)//2,v)
                fact.insert(len(fact)//2,i)
        return fact
  • 11 def divisors(n):
    2- fact = [];
    2+ fact = []
    33 for i in range(1, int(n**0.5) + 1):
    44 if not(n % i):
    5- fact.append(i)
    6- if n / i != i:
    7- fact.append(n / i)
    8- fact.sort()
    5+ v = n // i
    6+ if v != i:
    7+ fact.insert(len(fact)//2,v)
    8+ fact.insert(len(fact)//2,i)
    99 return fact

caring about {[( and ingredinents with numbers like "vitamin B1"

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(/[^\w\d]{2,}/)
        .some(x => gluten.includes(x));
    }
  • 1818 "kamut",
    1919 "einkorn"
    2020 ];
    2121
    2222 return ingredients
    2323 .toLowerCase()
    24- .split(/[,\s]+/)
    24+ .split(/[^\w\d]{2,}/)
    2525 .some(x => gluten.includes(x));
    2626 }
Algorithms

Data.Set is better. It's safer than head/tail and faster than nub (O(n^2)). For instance, size is O(1) and fromList is O(n*log n).

Code
Diff
  • module AllEqual where
    import Data.Set (fromList, size)
    
    allEqual :: [Int] -> Bool 
    allEqual xs = (size $ fromList xs) <= 1
  • 11 module AllEqual where
    2-import Data.List
    2+import Data.Set (fromList, size)
    33
    44 allEqual :: [Int] -> Bool
    5-allEqual xs = length (nub xs) <= 1
    5+allEqual xs = (size $ fromList xs) <= 1
Code
Diff
  • SELECT * FROM current_catalog
  • 1-SELECT current_database();
    1+SELECT * FROM current_catalog
Parsing
Algorithms
Strings

Useful information concerning validity of email addresses can be found in this RFC document: https://tools.ietf.org/html/rfc5322

function validate(email) {
  return /(.+)@(.+){2,}\.(.+){2,}/.test(email);
}
#include <iostream>
#include <iterator>

int main() {
  static const int xs[] = {1, 2, 3};
  const auto ie = std::make_reverse_iterator(std::begin(xs));
  for (auto ix = std::make_reverse_iterator(std::end(xs)); ix != ie; ++ix)
    std::cout << *ix << ' ';
  std::cout << std::endl;
}
Mathematics
Algorithms
Numbers

You can declare Array with running numbers up by using [...Array(n).keys]. Then if you want it start from 1, you just increase array size then slice it of.

Code
Diff
  • const isPerfect = n => 
      [...Array(n).keys()].slice(1).filter(e => !(n % e)).reduce((a, b) => a + b) === n
  • 11 const isPerfect = n =>
    2- Array(n - 1).fill(1).map((e, i) => e + i).filter(e => n % e === 0).reduce((a, b) => a + b) === n
    2+ [...Array(n).keys()].slice(1).filter(e => !(n % e)).reduce((a, b) => a + b) === n
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 
      puts("#{e.message}\n#{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 
      puts("#{e.message}\n#{e.class}")
    end
    
  • 1818 p e.class
    1919 end
    2020 begin
    2121 #c (fore:"4") # calling with wrong argument
    2222 # this lead to syntaxix error
    2323 rescue Exception => e
    24- p e.message
    25- p e.class
    24+ puts("#{e.message}\n#{e.class}")
    2626 end
    2727
    2828 hash = {one: 'One', two: 'Two', three: 'Three'}
    2929 c hash # calling with hash
    3030 hash = {two: 'Two', three: 'Three', one: 'One', }
    3131 c hash # calling with hash mess in order
    4242
    4343 begin
    4444 hash = { one: 'One', fore: "4" }
    4545 c hash # calling with hash that contain pair unlisetd in named arguments
    4646 rescue Exception => e
    47- p e.message
    48- p e.class
    46+ puts("#{e.message}\n#{e.class}")
    4949 end

It requires some optimization, but it works with just any number.

Code
Diff
  • import java.util.stream.IntStream;
    
    public class Primes {
      public static boolean isAPrime(int number) {
        return IntStream.range(2, number)
          .noneMatch(divider -> (number % divider) == 0); 
      }
    }
  • 1+import java.util.stream.IntStream;
    2+
    11 public class Primes {
    22 public static boolean isAPrime(int number) {
    3- if (number < 2 || (number % 2 == 0 && number != 2)) return false;
    4- for (int i = 3; i*i <= number; i += 2) {
    5- if (number % i == 0) return false;
    6- }
    7- return true;
    5+ return IntStream.range(2, number)
    6+ .noneMatch(divider -> (number % divider) == 0);
    88 }
    99 }
Code
Diff
  • wordCount=s=>s.trim().split` `.length
  • 1-function wordCount(str) {
    2- return str.trim().split(" ").length;
    3-}
    1+wordCount=s=>s.trim().split` `.length

Just confirming that the Criterion testing framework is not supported in Objective-C in Codewars.

int add(int a, int b) {
  return a + b;
}

This is a response to the kumite https://www.codewars.com/kumite/5a4edf17d8e145968c00015e to show that it has an elegant solution for ruby using the compiled bash utility "tr"

It's my first kumite so I'm not sure if this is how to use it. Don't mind if I do!

Code
Diff
  • def pattern a,b
      a.tr(a,b)==b && b.tr(b,a)==a
    end
  • 1-def pattern(p,st):
    2- def encode(s):
    3- dic={} # dictionary to hold values from the input string
    4- num=0
    5- sn="" # a numerical string to hold the encoding
    6- for i in s:
    7- if i not in dic:
    8- dic[i]=num
    9- num+=1
    10- sn+=str(dic[i])
    11- return sn
    12- return encode(st)==encode(p)
    1+def pattern a,b
    2+ a.tr(a,b)==b && b.tr(b,a)==a
    3+end
Code
Diff
  • public static int euler(int x){
        int sum = 0;
            if(x%3==0||x%5==0){
                sum += x;}
                
        return sum ;
        
      }
  • 1-def euler(num):
    2- sum = 0
    3- for x in range(num):
    4- if x%3==0 or x%5==0:
    5- sum += x
    6- return sum
    1+public static int euler(int x){
    2+ int sum = 0;
    3+ if(x%3==0||x%5==0){
    4+ sum += x;}
    5+
    6+ return sum ;
    7+
    8+ }

Reduced, printing only simple stuff.

Code
Diff
  • bool alwaysTrue(int, int, int) {
      return true;
    }
  • 1-template <class... Args>
    2-bool alwaysTrue(Args&&...) {
    1+bool alwaysTrue(int, int, int) {
    33 return true;
    44 }

Although C++ templates can be a right pain in the arse when you're trying to model Peano numbers and their operations, they can come in handy when you want to define generic functions that work over a wide range of datatypes, especially higher-order functions that map a vector, for example.

using namespace std;

template<class T, class U> vector<U> vectorMap(vector<T> v, function<U (T)> f) {
  size_t size = v.size();
  vector<U> result (size);
  for (size_t i = 0; i < size; i++) result[i] = f(v[i]);
  return result;
}
template<class T> vector<T> vectorFilter(vector<T> v, function<bool (T)> f) {
  vector<T> result;
  for (size_t i = 0; i < v.size(); i++) if (f(v[i])) result.push_back(v[i]);
  return result;
}
template<class T, class U> U vectorReduce(vector<T> v, function<U (U, T)> f, U u) {
  U result = u;
  for (size_t i = 0; i < v.size(); i++) result = f(result, v[i]);
  return result;
}
Code
Diff
  • inline int multiply(int x, int y, int counter)
    {
      if (y <= 0)
        return 0;
      
      if (y == 1)
        return x;
      
      if (y & 0x1)
        return x + multiply(x, y - 1, 0);
      
      if (counter + counter <= y)
        return multiply(x + x, y >> 1, counter + counter);
      else
        return x + multiply(x, y - counter, 0);
    }
    
    int squared(int number)
    {
      return multiply(number, number, 0);
    }
    
  • 1-int sqauring (int num)
    1+inline int multiply(int x, int y, int counter)
    22 {
    3-int times ;
    4- times = num ;
    5- int squared ;
    6- squared = 0;
    7-
    8- for (int i = 0 ; i <times ; i++ )
    9- {
    10- squared = squared + num ;
    11- }
    12-
    13-return squared ;
    3+ if (y <= 0)
    4+ return 0;
    5+
    6+ if (y == 1)
    7+ return x;
    8+
    9+ if (y & 0x1)
    10+ return x + multiply(x, y - 1, 0);
    11+
    12+ if (counter + counter <= y)
    13+ return multiply(x + x, y >> 1, counter + counter);
    14+ else
    15+ return x + multiply(x, y - counter, 0);
    16+}
    17+
    18+int squared(int number)
    19+{
    20+ return multiply(number, number, 0);
    1414 }

Just a simple demonstration of how the contents of std::cout can be tested in a Kata by redirecting the stream to file I/O operations.

Credits and recommended resources:

#include <iostream>

void myFirstHelloWorld() {
  std::cout << "Goodbye World!" << std::endl;
}
Strings
Arrays

Not really useful, but calling replace with an array as replacement calls toString on it. It doesn't work the same using objects

const weird = 'asdf'.replace('a', [])
const weirdness = 'asdf'.replace('a', [1,2])
const volatile = 'asdf'.replace('a', {})

https://en.wikipedia.org/wiki/Quaternion

Quaternions are a number system that extends complex numbers. Like complex numbers, it has one real component, but quaternions have three imaginary components instead of just one. It retains many operations and properties of complex numbers, such as addition, subtraction and multiplication. However, due to its complexity, it has fewer properties than complex numbers, the most notable one being that multiplication is no longer commutative, i.e. given two quaternions p and q, pq /= qp in most cases. Quaternions form an algebraically closed system like the complex numbers, i.e. given any polynomial with quaternion coefficients, it is guaranteed that all roots of the polynomial will also be quaternions. Quaternions find a wide range of applications in other branches of mathematics, such as 3D rotations (in place of 3 by 3 matrices), and was even widely used in 3D geometry before the "invention" of the concept of the modern 3D vector (which provided simpler calculations for certain types of problems).

This Kumite contains a rudimentary definition/implementation of quaternions in Haskell with only a small fraction of possible operations and/or functions defined because I don't want to spoil a potential future Kata on quaternions (which I plan to author in Fortran once it arrives on Codewars, among other languages). Stay tuned ;)


Note to Haskell experts/mathematicians: I originally intended to create two constructors for the Quaternion data type, one initialized with 4 real numbers and one with 2 complex numbers (in agreement with the Cayley-Dickson construction of quaternions from complex numbers), but couldn't quite find a way to make all the operators work without defining an extra equation for each one (which doesn't feel pure but instead rather hacky). So feel free to remix this Kumite and add this functionality if you're feeling up for it, cheers :D

module Quaternions where

import Test.Hspec

data Quaternion a = Quaternion a a a a
  deriving (Eq, Show)

instance RealFloat a => Num (Quaternion a) where
  (Quaternion a1 b1 c1 d1) + (Quaternion a2 b2 c2 d2) = Quaternion (a1 + a2) (b1 + b2) (c1 + c2) (d1 + d2)
  (*) = error "Quaternion multiplication is not implemented here to minimize spoilers for my potential future Kata"
  abs (Quaternion a b c d) = Quaternion (sqrt $ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2) 0.0 0.0 0.0
  signum = error "Not implemented in this Kumite"
  fromInteger n = Quaternion (fromInteger n) 0.0 0.0 0.0
  negate (Quaternion a b c d) = Quaternion (negate a) (negate b) (negate c) (negate d)

instance RealFloat a => Fractional (Quaternion a) where
  (/) = error "General division is not well-defined for quaternions - please specify whether left division or right division is desired"
  recip = error "Not implemented in this Kumite to minimize spoilers"
  fromRational x = Quaternion (fromRational x) 0.0 0.0 0.0

infix 7 `ldiv`
infix 7 `rdiv`

ldiv, rdiv :: Quaternion a -> Quaternion a -> Quaternion a
ldiv = error "Left division of a quaternion: not implemented in this Kumite to minimize spoilers"
rdiv = error "Right division of a quaternion: not implemented in this Kumite to minimize spoilers"

main = hspec $ do
  describe "Quaternions" $ do
    it "should be able to be compared for equality" $ do
      Quaternion 1.0 2.0 4.0 3.0 `shouldBe` Quaternion 1.0 2.0 4.0 3.0
    it "should be able to be compared for inequality" $ do
      Quaternion 1.0 2.0 4.0 3.0 `shouldNotBe` Quaternion 2.0 1.0 4.0 3.0
    it "should support addition (of two quaternions)" $ do
      Quaternion 3.0 5.0 2.3 9.9 + Quaternion 4.3 5.5 17.3 1.2 `shouldBe` Quaternion 7.3 10.5 19.6 11.1
    it "should support finding the absolute value (of a quaternion)" $ do
      abs (Quaternion 3.0 4.0 12.0 0.0) `shouldBe` 13.0
    it "should support the construction of a quaternion from an integer" $ do
      fromInteger 5 `shouldBe` Quaternion 5.0 0.0 0.0 0.0
    it "should support negation (i.e. finding the additive inverse)" $ do
      negate (Quaternion 234.4432 43.5 (negate 5.0) (negate 55.5)) `shouldBe` Quaternion (negate 234.4432) (negate 43.5) 5.0 55.5
    it "should support the construction of a quaternion from a rational" $ do
      fromRational (negate 44235.948372) `shouldBe` Quaternion (negate 44235.948372) 0.0 0.0 0.0
Code
Diff
  • template< class T >
    void Swap( T& a, T& b ) 
    {
      a = (b - a) + (b = a);
    }
  • 1-#include <algorithm>
    2-#include <math.h>
    3-
    44 template< class T >
    55 void Swap( T& a, T& b )
    66 {
    7- std::swap(a, b);
    4+ a = (b - a) + (b = a);
    88 }

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

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

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"