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

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

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

Code
Diff
  •  int compare(int a, int b){return a>b?a:b;}
  • 1-public class BiggerNum{
    2-
    3- public static int compare(int a, int b) {
    4- return 0;
    5- }
    6-
    7-}
    1+ int compare(int a, int b){return a>b?a:b;}
Code
Diff
  • def add(a,b):    
        return a + b
        
  • 11 def add(a,b):
    2- return (a + b)
    2+ return a + b
    33
Code
Diff
  • from operator import add
    print(add)
  • 11 from operator import add
    2+print(add)
Code
Diff
  • from operator import mul as multiple
  • 1-def multiple(a,b):
    2- return a*b
    1+from operator import mul as multiple
Code
Diff
  • def getLongestWord(words):
        return max(words, key=len, default="")
  • 11 def getLongestWord(words):
    2- longest = ""
    3- for w in words:
    4- longest = w if len(w) > len(longest) else longest
    5- return longest
    2+ return max(words, key=len, default="")
Code
Diff
  • def square(n):
        return ['*' * n] * n
  • 11 def square(n):
    2- return ['*' * n for x in range(0,n)]
    2+ return ['*' * n] * n

Code a function that will return the exact average grade of an array of grades. Grades can be integer or float numbers.

Code
Diff
  • def average(grades)
      grades.sum.fdiv(grades.length)
    end 
  • 1-def average (grades)
    2-grade.sum/grade.length
    1+def average(grades)
    2+ grades.sum.fdiv(grades.length)
    33 end
Code
Diff
  • def fizz_buzz(n):
        for i in range(1, n):
            yield "Fizz" * (i % 3 == 0) + "Buzz" * (i % 5 == 0) or i
  • 1-def fizzBuzz(num):
    2- for i in range(1,num):
    3- yield ("Fizz Buzz" if i % 3 == 0 and i % 5 == 0 else ("Fizz" if i % 3 == 0 else ("Buzz" if i % 5 == 0 else i)))
    4-
    5-list = list(fizzBuzz(17))
    1+def fizz_buzz(n):
    2+ for i in range(1, n):
    3+ yield "Fizz" * (i % 3 == 0) + "Buzz" * (i % 5 == 0) or i

Instead of functions, i used lambdas that captured the password by reference.
So no additional passing through functions is necessary.
Invoking the lambdas as late as possible. To call only 1 function in the best case.
Using std::string::find_first_of() to use the stl instead of writing the search by myself.

Code
Diff
  • #include <string>
    bool testPassword(std::string password)
    {
        auto const has_length{[&]() { return password.size() >= 8; }};
        auto const has_upper{[&]() { return password.find_first_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ") != std::string::npos; }};
        auto const has_special{[&]() { return password.find_first_of("!\"#$%&'()*+'-./;:<>=or?") != std::string::npos; }};
        auto const has_digit{[&]() { return password.find_first_of("0123456789") != std::string::npos; }};
        return has_length() && has_upper() && has_special() && has_digit();
    }
  • 1-class Password{
    2- public:
    3- static bool hasCap(const std::string& password);
    4- static bool hasSpec(const std::string& password);
    5- static bool hasDigit(const std::string& password);
    6- static bool hasLength(const std::string& password);
    7- static bool testPassword(const std::string& password);
    8-};
    9-
    10-bool Password::hasCap(const std::string& password)
    1+#include <string>
    2+bool testPassword(std::string password)
    1111 {
    12- bool result = false;
    13- for(auto symbol : password)
    14- {
    15- if(symbol >= 'A' && symbol <= 'Z')
    16- {
    17- result = true;
    18- break;
    19- }
    20- }
    21- return result;
    22-}
    23-
    24-bool Password::hasSpec(const std::string& password)
    25-{
    26- bool result = false;
    27-
    28- const std::string specials("!\"#$%&'()*+'-./;:<>=?");
    29- for(auto spec : specials)
    30- {
    31- if(password.find(spec) != -1)
    32- {
    33- result = true;
    34- break;
    35- }
    36- }
    37- return result;
    38-}
    39-
    40-bool Password::hasDigit(const std::string& password)
    41-{
    42- bool result = false;
    43- for(auto symbol : password)
    44- {
    45- if(symbol >= '0' && symbol <= '9')
    46- {
    47- result = true;
    48- break;
    49- }
    50- }
    51- return result;
    52-}
    53-
    54-bool Password::hasLength(const std::string& password)
    55-{
    56- return password.length() > 7;
    57-}
    58-
    59-bool Password::testPassword(const std::string& password)
    60-{
    61- bool cap = Password::hasCap(password);
    62- bool spec = Password::hasSpec(password);
    63- bool digit = Password::hasDigit(password);
    64- bool number = Password::hasLength(password);
    65-
    66- return cap && spec && digit && number;
    4+ auto const has_length{[&]() { return password.size() >= 8; }};
    5+ auto const has_upper{[&]() { return password.find_first_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ") != std::string::npos; }};
    6+ auto const has_special{[&]() { return password.find_first_of("!\"#$%&'()*+'-./;:<>=or?") != std::string::npos; }};
    7+ auto const has_digit{[&]() { return password.find_first_of("0123456789") != std::string::npos; }};
    8+ return has_length() && has_upper() && has_special() && has_digit();
    6767 }
Code
Diff
  • function main()
    {
      return 1
    }
  • 11 function main()
    22 {
    3- return 12
    3+ return 1
    44 }

Showing how sync events work in c#, not so pratical as in c# 6 and forward is a good practice writing async code.

using System;

namespace delegates
{
	class Program
	{
		static void Main()
		{
		    // Creates a new instance
			Message hi = new Message();
			
			/*
			set the event of the class instance to a 
			lambda expression, beeing an event handler that has the same parameter
			and return type of the delegate in the class instance.
			
			equivalent of creating a new void method with the same
			parameters and seting it to the event in the class instance
			
			*/
			hi.writed += (string hello) =>
			{
			    Console.WriteLine(hello);
			};
			
			// executes the method to validate the event and add it to the delegate
			hi.write = "write property";
		}
	}
	
	public class Message
	{
	    
	    //creates the delegate that will handle the method/ lambda expression/ anonnymous method passed through it
	    public delegate void handler(string hello);
	    
	    //creates the event with the delegate
	    public event handler writed;
	    
	    //method that will check for the event while executing
	    
	    private string _write;
	    public string write
	    {
	        get
	        {
	            return _write;
	        }
	        set
	        {
	            if(value == "write property")
	            {
	               writed?.Invoke("the event was thrown!!!");
	            }
	            
	            Console.WriteLine(value);
	            
	            _write = value;
	        }
	    }
	    
	   //The same as:
	   
	   // public void write(string text)
	   // {
	   //     //you have to check if the event is not null becouse you can't execute a delegates method if it does not exist
	   //     //(the event handler was not set yet)
	   //     if(text == "write method" && writed != null)
	   //     {
	   //         writed("the event was thrown!!!");
	   //     }
	   //     Console.WriteLine(text);
	       
    }
}
Algorithms
Code
Diff
  • getDividors = n => [...Array(n).keys()].filter(e => n % e)
  • 1-getDividors = n => Array.from({length: n}, (e, i) => n % ++i ? i : 0).filter(e => e)
    1+getDividors = n => [...Array(n).keys()].filter(e => n % e)
Code
Diff
  • test = s => s.match(/\[(\w+)].*\[\/\1]/g).join``
  • 1-function test(str) {
    2- return (str.match(/\[([a-zA-Z]+)](.*)\[\/\1]/g)).join('');
    3-}
    1+test = s => s.match(/\[(\w+)].*\[\/\1]/g).join``
Strings
Code
Diff
  • const lastChar = s => /.$/.exec(s)[0];
    
  • 1-const lastChar=(s)=>s.slice(-1)
    1+const lastChar = s => /.$/.exec(s)[0];
Fundamentals
Strings
Code
Diff
  • const toHours = i => Math.floor(i / 60);
    
    const setDigits = i => `0${i}`.slice(-2);
    
    const getTime = i => [toHours(i), i % 60];
    
    const toTime = arr => `${arr[0]}:${setDigits(arr[1])}`;
    
    const minutes = i => toTime(getTime(i));
  • 1-const toHours = ( i ) => Math.floor( i / 60 );
    1+const toHours = i => Math.floor(i / 60);
    22
    3-const setDigits = ( i ) => i < 10 ? `0${i}` : i;
    3+const setDigits = i => `0${i}`.slice(-2);
    44
    5-const getTime = ( i ) => [toHours(i), i % 60];
    5+const getTime = i => [toHours(i), i % 60];
    66
    7-const toTime = ( arr ) => `${arr[0]}:${setDigits(arr[1])}`;
    7+const toTime = arr => `${arr[0]}:${setDigits(arr[1])}`;
    88
    9-const minutes = ( i ) => toTime(getTime(i));
    9+const minutes = i => toTime(getTime(i));
Algorithms

a function that takes a list of connections on the following format:
connections[n] is the list of connections from node n.

connections={
    [1] ={ 1, 2, 6, 7 },
    [2] ={ 1, 2, 4, 5, 6 },
    [3] ={ 3, 4, 5, 6, 7 },
    [4] ={ 2, 3, 4, 5, 6 },
    [5] ={ 2, 3, 4, 5, 7 },
    [6] ={ 1, 2, 3, 4, 6 },
    [7] ={ 1, 3, 5, 7 },
    [8] ={ 8, 9, 11, 12, 13, 15 },
    [9] ={ 8, 9, 10, 12, 13, 15, 16 },
    [10]={ 9, 10, 11, 12, 16 },
    [11]={ 8, 10, 11, 12 },
    [12]={ 8, 9, 10, 11, 12, 13, 15 },
    [13]={ 8, 9, 12, 13, 14, 15 },
    [14]={ 13, 14, 15, 16 },
    [15]={ 8, 9, 12, 13, 14, 15, 16 },
    [16]={ 9, 10, 14, 15, 16 },
    [17]={ 17, 18, 19, 20, 21 },
    [18]={ 17, 18, 19, 20 },
    [19]={ 17, 18, 19, 21 },
    [20]={ 17, 18, 20, 21 },
    [21]={ 17, 19, 20, 21 },
}

The output should be a table of tables with nodes in a given net.

nets={
    {1,2,6,7,4,5,3},
    {8,9,11,12,13,15,10,16,14},
    {17,18,19,20,21}
}

This solution assumes symmetrical connections between nodes.

solution={}

local isIn=function(list,item)
  --simple function to find a vale in list
	if type(list)~="table" or item==nil then
		return false
	end
	local FoundAtIndex=""
	local found=false
	for index,value in pairs(list) do
		if value==item then
			found=true
			FoundAtIndex=index
			break
		end
	end
	return found,FoundAtIndex
end

solution.findConnectedNets=function(connections)
	local nets={}
	for i=1,#connections do --traverses nodes to build the nets
		local new=true
		for k=1,#nets do --if it already is in a net, skip it
			if isIn(nets[k],i) then
				new=false
				break
			end
		end
		if new then
			local net={}
			local queue={i}
			while #queue>0 do
				local vertex=queue[1]
				table.insert(net,vertex)
				table.remove(queue,1)
				for _,node in pairs(connections[vertex]) do
					if not isIn(net,node) and not isIn(queue,node) then
						table.insert(queue,node)
					end
				end
			end
			table.insert(nets,net)
		end
	end
	return nets
end


return solution
Code
Diff
  • export function fizzBuzz(input: number): string {
        const output = (input % 3 ? "" : "Fizz") + (input % 5 ? "" : "Buzz");
        return output.length ? output : input.toString();
    }
  • 11 export function fizzBuzz(input: number): string {
    2- const output: string = `${input % 3 === 0 ? "Fizz" : ""}${input % 5 === 0 ? "Buzz" : ""}`;
    3- return output.length > 0 ? output : input.toString(10);
    2+ const output = (input % 3 ? "" : "Fizz") + (input % 5 ? "" : "Buzz");
    3+ return output.length ? output : input.toString();
    44 }

Started with 3, because why waste 2 loops on answers you know aren't correct.

Code
Diff
  • function test(n) {
      let sum=0;
      for (let i=3; i<n; i++){
        if ((i%3==0) || (i%5==0)){
        sum+=i;
        }
      }
       return sum;
    }
  • 1-//if you have any Suggestion or noticed a mistake in my code ...tell me...i would need that...
    22 function test(n) {
    3- var sum=0;
    4- for (i=1; i<n; i++){
    2+ let sum=0;
    3+ for (let i=3; i<n; i++){
    55 if ((i%3==0) || (i%5==0)){
    66 sum+=i;
    77 }
    88 }
    99 return sum;
    1010 }

Use STL algorithms, take vector arguments by constant reference and functors by their exact type to avoid overhead of std::function.

Code
Diff
  • #include <numeric>
    
    using namespace std;
    
    template<class F, class T, class U = decltype(std::declval<F>()(std::declval<T>()))> vector<U> vectorMap(const vector<T>& v, F f) {
      vector<U> result (v.size());
      std::transform(v.begin(), v.end(), result.begin(), std::move(f));
      return result;
    }
    template<class F, class T> vector<T> vectorFilter(const vector<T>& v, F f) {
      vector<T> result;
      std::copy_if(v.begin(), v.end(), std::back_inserter(result), std::move(f));
      return result;
    }
    template<class F, class T, class U> U vectorReduce(const vector<T>& v, F f, U u) {
      return std::accumulate(v.begin(), v.end(), u, std::move(f));
    }
  • 1+#include <numeric>
    2+
    11 using namespace std;
    22
    3-template<class T, class U> vector<U> vectorMap(vector<T> v, function<U (T)> f) {
    4- size_t size = v.size();
    5- vector<U> result (size);
    6- for (size_t i = 0; i < size; i++) result[i] = f(v[i]);
    5+template<class F, class T, class U = decltype(std::declval<F>()(std::declval<T>()))> vector<U> vectorMap(const vector<T>& v, F f) {
    6+ vector<U> result (v.size());
    7+ std::transform(v.begin(), v.end(), result.begin(), std::move(f));
    77 return result;
    88 }
    9-template<class T> vector<T> vectorFilter(vector<T> v, function<bool (T)> f) {
    10+template<class F, class T> vector<T> vectorFilter(const vector<T>& v, F f) {
    1010 vector<T> result;
    11- for (size_t i = 0; i < v.size(); i++) if (f(v[i])) result.push_back(v[i]);
    12+ std::copy_if(v.begin(), v.end(), std::back_inserter(result), std::move(f));
    1212 return result;
    1313 }
    14-template<class T, class U> U vectorReduce(vector<T> v, function<U (U, T)> f, U u) {
    15- U result = u;
    16- for (size_t i = 0; i < v.size(); i++) result = f(result, v[i]);
    17- return result;
    15+template<class F, class T, class U> U vectorReduce(const vector<T>& v, F f, U u) {
    16+ return std::accumulate(v.begin(), v.end(), u, std::move(f));
    1818 }
Algorithms
Code
Diff
  • flatten = a => a.map ? [].concat(...a.map(flatten)) : a
  • 1-flatten=a=>a.map?[].concat(...a.map(flatten)):a
    1+flatten = a => a.map ? [].concat(...a.map(flatten)) : a
Code
Diff
  • class Stack {  // Just to hide the use of array implementation
      constructor() {
        this._items = [];
      }
      push(data) {
        this._items.push(data);
      }
      pop() {
        return this._items.pop();
      }
      
      get length() {
        return this._items.length;
      }
    }
    
    class Queue {
      constructor() {
        this._stack = new Stack();
      }
      enqueue(data) {
        this._stack.push(data);
      }
      dequeue() {
        if (this._stack.length === 1)
          return this._stack.pop();
        else {
          var tmp = this._stack.pop(), result = this.dequeue();
          this.enqueue(tmp);
          return result;
        }
      }
    }
  • 11 class Stack { // Just to hide the use of array implementation
    22 constructor() {
    33 this._items = [];
    44 }
    55 push(data) {
    66 this._items.push(data);
    77 }
    88 pop() {
    99 return this._items.pop();
    1010 }
    11- length() {
    11+
    12+ get length() {
    1212 return this._items.length;
    1313 }
    1414 }
    1515
    1616 class Queue {
    1717 constructor() {
    1818 this._stack = new Stack();
    1919 }
    2020 enqueue(data) {
    2121 this._stack.push(data);
    2222 }
    2323 dequeue() {
    24- if (this._stack.length() === 1)
    25+ if (this._stack.length === 1)
    2525 return this._stack.pop();
    2626 else {
    2727 var tmp = this._stack.pop(), result = this.dequeue();
    2828 this.enqueue(tmp);
    2929 return result;
    3030 }
    3131 }
    3232 }

yawn I need a cup of coffee...

class GroundCoffee { }
class Coffee { }

class Cupboard { 
  constructor() {
    this.contents = {
      "GroundCoffee": new GroundCoffee(),
    };
  }
}

class CoffeeMaker {
  makeCoffee(groundCoffee) {
    if(!(groundCoffee instanceof GroundCoffee)) {
      throw new Error("Only GroundCoffee can be used to make Coffee");
    }
    
    return new Coffee();
  }
}

// -----

const cupboard = new Cupboard();
const coffeeMaker = new CoffeeMaker();

function makeCoffee() {  
  let groundCoffee = cupboard.contents["GroundCoffee"];
  return coffeeMaker.makeCoffee(groundCoffee);
}
Code
Diff
  • def hello
      "world"
    end
  • 1-function hello() {
    2- return "world";
    3-}
    1+def hello
    2+ "world"
    3+end
Code
Diff
  • from math import sqrt
    def divisors(n):
        fa={i for i in range(1,int(sqrt(n)) + 1) if not(n%i)}
        ct={n//i for i in fa}
        return sorted(fa|ct)
  • 1+from math import sqrt
    11 def divisors(n):
    2- fact = []
    3- for i in range(1, int(n**0.5) + 1):
    4- if not(n % i):
    5- v = n // i
    6- if v != i:
    7- fact.insert(len(fact)//2,v)
    8- fact.insert(len(fact)//2,i)
    9- return fact
    3+ fa={i for i in range(1,int(sqrt(n)) + 1) if not(n%i)}
    4+ ct={n//i for i in fa}
    5+ return sorted(fa|ct)

?

Code
Diff
  • from math import hypot as hypotenuse
        
  • 1-from math import *
    2-def hypotenuse(a, b): return hypot(a,b)
    1+from math import hypot as hypotenuse
    33
Code
Diff
  • from datetime import datetime
    
    def password(p):
        a = datetime.now()
        if not p.isdigit(): 
            return "Please, don't print letters.\nReset the program."
        return "ACCESS CONFIRMED" if p == f"{a.hour}{a.minute}" else "ACCESS DENIED"              
    
    # Outside the codewar you can use the lines below.
    # b = input("Please, print the password here (without letters!): ")
    # print(password(b))
  • 11 from datetime import datetime
    22
    33 def password(p):
    44 a = datetime.now()
    5- c = str(a.hour) + str(a.minute)
    6-
    7- if p.isdigit():
    8- if(p == c):
    9- return("ACCESS CONFIRMED")
    10- else:
    11- return("ACCESS DENIED")
    12- else:
    13- return("Please, don't print letters.\nReset the program.")
    5+ if not p.isdigit():
    6+ return "Please, don't print letters.\nReset the program."
    7+ return "ACCESS CONFIRMED" if p == f"{a.hour}{a.minute}" else "ACCESS DENIED"
    1414
    1515 # Outside the codewar you can use the lines below.
    1616 # b = input("Please, print the password here (without letters!): ")
    1717 # print(password(b))

Don't know how this "kumite" stuff works yet, so i may be doing sth wrong.
This is about finding better/more efficient ways to permutate a list starting with my sorry attempt. The result requires types of the typeclass Ord, to get a common result for the test cases. Havent thought about a way to solve that differently yet.

module Permutation where

import Data.List (sort)

permu :: [a] ->[[a]]
permu []  = [[]]
permu [x] = [[x]]
permu x = fuzz (length x) 0 x
        where fuzz l n (x:xs) |n == l = []
                              |otherwise = map ((:) x) (permu xs) ++ fuzz l (n+1) (xs ++ [x])
                            
permutation :: Ord a => [a] -> [[a]]                           
permutation x = permu x

Return addresses are just normal stack entries, and nasm lets you jump to an address from a register.

Code
Diff
  • global stack_push, stack_pop, stack_peek ; , stack_is_empty
    section .text
    stack_push:
      xchg rsi, [rsp]
      jmp rsi
    stack_pop:
      pop rsi
      pop rax
      jmp rsi
    stack_peek:
      pop rsi
      mov rax, [rsp]
      jmp rsi
    
  • 11 global stack_push, stack_pop, stack_peek ; , stack_is_empty
    22 section .text
    33 stack_push:
    4- push rsi
    5- ret
    4+ xchg rsi, [rsp]
    5+ jmp rsi
    66 stack_pop:
    77 pop rsi
    8- ret
    8+ pop rax
    9+ jmp rsi
    99 stack_peek:
    1010 pop rsi
    11- push rsi
    12- ret
    12+ mov rax, [rsp]
    13+ jmp rsi
Code
Diff
  • func hello() {
      print("Hello Swift 5!")
    }
  • 1-func hello() {
    2-
    3-print("Hello Swift 5!")
    4-
    1+func hello() {
    2+ print("Hello Swift 5!")
    55 }
Code
Diff
  • class Functionator
      attr_reader :allowed_methods, :callers, :next_caller
    
      def initialize(s)
        @allowed_methods = s.split
        init_caller
      end
    
      def method_missing(method, *args)
        method = method.to_s
        raise NoMethodError, 'Not exists' unless @allowed_methods.include?(method)
        raise NoMethodError, 'Wrong order' unless @next_caller == method
        wait_next_caller
        self
      end
    
      private
    
      def wait_next_caller
        @next_caller = @callers.next
      rescue StopIteration
        init_caller
      end
    
      def init_caller
        @callers = @allowed_methods.each
        @next_caller = @callers.next
      end
    end
    
    def functionator(methods)
      Functionator.new methods
    end
  • 11 class Functionator
    2+ attr_reader :allowed_methods, :callers, :next_caller
    3+
    22 def initialize(s)
    3- s.split(' ').each { | i | define_singleton_method :"#{i}" do Functionator.new(s.split(' ')[1..-1].join(' ')) end }
    5+ @allowed_methods = s.split
    6+ init_caller
    7+ end
    8+
    9+ def method_missing(method, *args)
    10+ method = method.to_s
    11+ raise NoMethodError, 'Not exists' unless @allowed_methods.include?(method)
    12+ raise NoMethodError, 'Wrong order' unless @next_caller == method
    13+ wait_next_caller
    14+ self
    15+ end
    16+
    17+ private
    18+
    19+ def wait_next_caller
    20+ @next_caller = @callers.next
    21+ rescue StopIteration
    22+ init_caller
    23+ end
    24+
    25+ def init_caller
    26+ @callers = @allowed_methods.each
    27+ @next_caller = @callers.next
    44 end
    55 end
    66
    7-def functionator(string)
    8- Functionator.new(string)
    31+def functionator(methods)
    32+ Functionator.new methods
    99 end
Code
Diff
  • def array_of_two(n)
      [n.to_int, n.to_int]
    end
    
  • 11 def array_of_two(n)
    2- raise 'n is not a number' unless n.is_a?(Numeric) # comment to fail test case
    3- [n, n]
    2+ [n.to_int, n.to_int]
    44 end

A mistake they don't want to fix...

function describePhp() {
  return 2 * 2 == 4 ? 'php is good' : 2 * 2 == 5 ? 'php is weird' : 'php has features';
}
Code
Diff
  • function pairs(target_value, array) {
      array.map(i => { array.map(j => {
       (i !== j && array[i] === array[j])? 1 : 0
        })
      })
    }
      
     //shorter way to write what you wrote
  • 11 function pairs(target_value, array) {
    2- var num_elements = array.length;
    3-
    4- for ( var i = 0; i < num_elements; i++ ) {
    5- for ( var j = 0; j < num_elements; j++ ) {
    6- if ( i !== j && array[i] === array[j] ) {
    7- return -1;
    8- }
    9- }
    10- }
    11-
    12- return 0;
    2+ array.map(i => { array.map(j => {
    3+ (i !== j && array[i] === array[j])? 1 : 0
    4+ })
    5+ })
    1313 }
    7+
    8+ //shorter way to write what you wrote
Code
Diff
  • #include <stdlib.h>
    
    typedef struct IntVector {
      int *data;
    } IntVector;
    
    static void IntVector_construct(IntVector *this, size_t size) {
      this->data = calloc(sizeof(*this->data), size);
    }
    
    static void IntVector_destruct(IntVector *this) {
      free(this->data);
    }
    
    static int IntVector_get(const IntVector *this, size_t index) {
      return this->data[index];
    }
    
    static void IntVector_set(const IntVector *this, size_t index, int value) {
      return this->data[index] = value;
    }
    
  • 11 #include <stdlib.h>
    22
    33 typedef struct IntVector {
    44 int *data;
    55 } IntVector;
    66
    7-IntVector *IntVector_new(size_t size) {
    8- IntVector *this = malloc(sizeof(IntVector));
    7+static void IntVector_construct(IntVector *this, size_t size) {
    99 this->data = calloc(sizeof(*this->data), size);
    10- return this;
    1111 }
    1212
    13-void IntVector_free(IntVector *this) {
    11+static void IntVector_destruct(IntVector *this) {
    1414 free(this->data);
    15- free(this);
    1616 }
    1717
    18-int IntVector_get(const IntVector *this, size_t index) {
    15+static int IntVector_get(const IntVector *this, size_t index) {
    1919 return this->data[index];
    2020 }
    2121
    22-void IntVector_set(IntVector *this, size_t index, int value) {
    19+static void IntVector_set(const IntVector *this, size_t index, int value) {
    2323 return this->data[index] = value;
    2424 }
Algorithms
Code
Diff
  • module AllEqual where
    
    allEqual :: [Int] -> Bool
    allEqual = and . (zipWith (==) <*> tail)
  • 11 module AllEqual where
    22
    33 allEqual :: [Int] -> Bool
    4-allEqual = all =<< (==) . head
    4+allEqual = and . (zipWith (==) <*> tail)
Code
Diff
  • String.prototype.toBase64 = function () {
      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
      let result = '';
      let i = 0;
      while (i < this.length) {
        let a = this.charCodeAt(i++) || 0;
        let b = this.charCodeAt(i++) || 0;
        let c = this.charCodeAt(i++) || 0;
    
        let b1 = (a >> 2) & 0x3F;
        let b2 = ((a & 0x3) << 4) | ((b >> 4) & 0xF);
        let b3 = ((b & 0xF) << 2) | ((c >> 6) & 0x3);
        let b4 = c & 0x3F;
    
        if (!b) b3 = b4 = 64;
        else if (!c) b4 = 64;
        
        result += characters.charAt(b1) + 
                  characters.charAt(b2) + 
                  characters.charAt(b3) +
                  characters.charAt(b4);
      }
      return result;
    }
    
    const hexToBase64 = hex => 
      hex
        .match(/.{1,2}/g)
        .map(v => String.fromCharCode(parseInt(v, 16)))
        .join``
        .toBase64();
    
    
  • 1-function hexToBase64(hex) {
    2- return hex;
    1+String.prototype.toBase64 = function () {
    2+ const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    3+ let result = '';
    4+ let i = 0;
    5+ while (i < this.length) {
    6+ let a = this.charCodeAt(i++) || 0;
    7+ let b = this.charCodeAt(i++) || 0;
    8+ let c = this.charCodeAt(i++) || 0;
    9+
    10+ let b1 = (a >> 2) & 0x3F;
    11+ let b2 = ((a & 0x3) << 4) | ((b >> 4) & 0xF);
    12+ let b3 = ((b & 0xF) << 2) | ((c >> 6) & 0x3);
    13+ let b4 = c & 0x3F;
    14+
    15+ if (!b) b3 = b4 = 64;
    16+ else if (!c) b4 = 64;
    17+
    18+ result += characters.charAt(b1) +
    19+ characters.charAt(b2) +
    20+ characters.charAt(b3) +
    21+ characters.charAt(b4);
    22+ }
    23+ return result;
    33 }
    25+
    26+const hexToBase64 = hex =>
    27+ hex
    28+ .match(/.{1,2}/g)
    29+ .map(v => String.fromCharCode(parseInt(v, 16)))
    30+ .join``
    31+ .toBase64();
    32+

This one should be faster since we only compute 2 products of less numbers.

Code
Diff
  • module NCR where
    
    --Combinations nCr
    comb:: Integer -> Integer -> Integer
    comb n r = product [n-r+1..n] `div` product [2..r]
  • 11 module NCR where
    22
    33 --Combinations nCr
    44 comb:: Integer -> Integer -> Integer
    5-comb n r = factorial n `div` (factorial r * factorial (n-r))
    6- where
    7- factorial n = product [1 .. n]
    5+comb n r = product [n-r+1..n] `div` product [2..r]
Data Structures
Algorithms
Binary Search Trees
Trees
Binary
Maps

Map/Dictionary/Associative Array as a binary search tree of entries

Suggested reading: Binary Search Tree - Wikipedia

Last time we saw how the map/dictionary/assoc array datatype can be implemented as a linked list of entries. We also noted how this implementation is seldomly used in real-world applications due to its sheer inefficiency for pretty much every operation.

So is there a way to make this data type more efficient? As it turns out, using a different data structure can really make an impact on the runtime complexity of operations on maps. One particular data structure that suits maps pretty well is the binary search tree (BST). A binary search tree is a special case of a binary tree where when one traverses its elements pre-order (left -> value -> right), the sequence of elements are in order. When the BST is perfectly balanced (i.e. all its branches have the same depth), its insertion, lookup and deletion operations are all logarithmic in time (O(log n)) because for every level you advance through the tree, you can effectively discard half of the tree. Another advantage of using a BST in our map is that we can implement a function converting the map into an iterator (if we wish to iterate through our key-value pairs in the map) such that the sequence of elements in the iterator are guaranteed to arrive in-order. However, the major drawback of (ordinary) BSTs is that if the elements are inserted in-order (or in reversed order), it degenerates into a linked list so its operations become O(n) again. Furthermore, if one inserts elements randomly into a BST, its operations converge towards an O(sqrt n) time complexity which is significantly less efficient than O(log n).

If only there were a way to ensure that our BST is sufficiently balanced at all times ... ;)

Code
Diff
  • #include <stddef.h>
    
    typedef struct {
      // Denotes a key-value pair of integers, e.g. 7 => 34
      int key, value;
    } Entry;
    
    typedef struct node_t {
      // A node of a binary (search) tree - the internal implementation of our map
      Entry *entry;
      struct node_t *left, *right;
    } Node;
    
    typedef struct {
      // Our map datatype, implemented as a simple wrapper around our BST
      // This allows us to insert elements to a map by object reference and
      // reserves NULL for indicating an invalid reference to a Map (instead
      // of an empty map)
      Node *root;
    } Map;
    
    int map_get(const Map *map, int key) {
      // Retrieves the corresponding value for a given key in a map
      // Assumption: The given key-value pair in the map exists
      const Node *nd = map->root;
      while (nd->entry->key != key)
        nd = key < nd->entry->key ? nd->left : nd->right;
      return nd->entry->value;
    }
    
    void map_set(Map *map, int key, int value) {
      // Adds the key-value pair to the map if no entry with the given key exists;
      // otherwise modifies the value of the entry with the given key to the given value
      if (map->root == NULL) {
        map->root = malloc(sizeof(Node));
        map->root->entry = malloc(sizeof(Entry));
        map->root->entry->key = key;
        map->root->entry->value = value;
        map->root->left = map->root->right = NULL;
      } else {
        Node *nd = map->root;
        while (nd->entry->key != key) {
          const Node *tmp = key < nd->entry->key ? nd->left : nd->right;
          if (tmp == NULL)
            break;
          nd = tmp;
        }
        if (nd->entry->key == key)
          nd->entry->value = value;
        else if (key < nd->entry->key) {
          nd->left = malloc(sizeof(Node));
          nd->left->entry = malloc(sizeof(Entry));
          nd->left->entry->key = key;
          nd->left->entry->value = value;
          nd->left->left = nd->left->right = NULL;
        } else {
          nd->right = malloc(sizeof(Node));
          nd->right->entry = malloc(sizeof(Entry));
          nd->right->entry->key = key;
          nd->right->entry->value = value;
          nd->right->left = nd->right->right = NULL;
        }
      }
    }
    
    void map_remove(Map *map, int key) {
      // Removes the key-value entry from the map with the given key
      // Assumption: The key-value pair in the map exists
      if (map->root->entry->key == key) {
        if (map->root->right == NULL) {
          Node *tmp = map->root->left;
          free(map->root->entry);
          free(map->root);
          map->root = tmp;
        } else if (map->root->left == NULL) {
          Node *tmp = map->root->right;
          free(map->root->entry);
          free(map->root);
          map->root = tmp;
        } else if (rand() % 2) {
          Node *parent = map->root, *child = parent->left;
          while (child->right != NULL) {
            parent = child;
            child = child->right;
          }
          if (parent->left == child)
            parent->left = child->left;
          else
            parent->right = child->left;
          map->root->entry->key = child->entry->key;
          map->root->entry->value = child->entry->value;
          free(child->entry);
          free(child);
        } else {
          Node *parent = map->root, *child = parent->right;
          while (child->left != NULL) {
            parent = child;
            child = child->left;
          }
          if (parent->left == child)
            parent->left = child->right;
          else
            parent->right = child->right;
          map->root->entry->key = child->entry->key;
          map->root->entry->value = child->entry->value;
          free(child->entry);
          free(child);
        }
      } else {
        Node *nd_parent = map->root, *nd = key < nd_parent->entry->key ? nd_parent->left : nd_parent->right;
        while (nd->entry->key != key) {
          nd_parent = nd;
          nd = key < nd->entry->key ? nd->left : nd->right;
        }
        if (nd->right == NULL) {
          if (nd_parent->left == nd)
            nd_parent->left = nd->left;
          else
            nd_parent->right = nd->left;
          free(nd->entry);
          free(nd);
        } else if (nd->left == NULL) {
          if (nd_parent->left == nd)
            nd_parent->left = nd->right;
          else
            nd_parent->right = nd->right;
          free(nd->entry);
          free(nd);
        } else if (rand() % 2) {
          Node *parent = nd, *child = parent->left;
          while (child->right != NULL) {
            parent = child;
            child = child->right;
          }
          if (parent->left == child)
            parent->left = child->left;
          else
            parent->right = child->left;
          nd->entry->key = child->entry->key;
          nd->entry->value = child->entry->value;
          free(child->entry);
          free(child);
        } else {
          Node *parent = nd, *child = parent->right;
          while (child->left != NULL) {
            parent = child;
            child = child->left;
          }
          if (parent->left == child)
            parent->left = child->right;
          else
            parent->right = child->right;
          nd->entry->key = child->entry->key;
          nd->entry->value = child->entry->value;
          free(child->entry);
          free(child);
        }
      }
    }
  • 11 #include <stddef.h>
    22
    33 typedef struct {
    4- // A key-value pair of integers
    4+ // Denotes a key-value pair of integers, e.g. 7 => 34
    55 int key, value;
    66 } Entry;
    77
    88 typedef struct node_t {
    9- // A node in a linked list - internal implementation of a Map
    10- Entry *entry; // The current entry in our map
    11- struct node_t *next; // The rest of our map
    9+ // A node of a binary (search) tree - the internal implementation of our map
    10+ Entry *entry;
    11+ struct node_t *left, *right;
    1212 } Node;
    1313
    1414 typedef struct {
    15- // Outer map wrapper (to hide interal implementation and
    16- // reserve `NULL` for representing an invalid map reference instead of an empty map)
    15+ // Our map datatype, implemented as a simple wrapper around our BST
    16+ // This allows us to insert elements to a map by object reference and
    17+ // reserves NULL for indicating an invalid reference to a Map (instead
    18+ // of an empty map)
    1717 Node *root;
    1818 } Map;
    1919
    2020 int map_get(const Map *map, int key) {
    21- // Returns the corresponding value to the key in the map
    22- // Assumption: the key is present in the map
    23- // (querying a nonexistent key yields undefined behavior)
    24- const Node *n = map->root;
    25- while (n->entry->key != key)
    26- n = n->next;
    27- return n->entry->value;
    23+ // Retrieves the corresponding value for a given key in a map
    24+ // Assumption: The given key-value pair in the map exists
    25+ const Node *nd = map->root;
    26+ while (nd->entry->key != key)
    27+ nd = key < nd->entry->key ? nd->left : nd->right;
    28+ return nd->entry->value;
    2828 }
    2929
    3030 void map_set(Map *map, int key, int value) {
    31- // Adds the key-value pair to the map if not present;
    32- // otherwise reassigns it at the corresponding entry
    33- Node *n = map->root;
    34- while (n != NULL && n->entry->key != key)
    35- n = n->next;
    36- if (n != NULL)
    37- n->entry->value = value;
    38- else {
    39- Node *tmp = map->root;
    32+ // Adds the key-value pair to the map if no entry with the given key exists;
    33+ // otherwise modifies the value of the entry with the given key to the given value
    34+ if (map->root == NULL) {
    4040 map->root = malloc(sizeof(Node));
    4141 map->root->entry = malloc(sizeof(Entry));
    4242 map->root->entry->key = key;
    4343 map->root->entry->value = value;
    44- map->root->next = tmp;
    39+ map->root->left = map->root->right = NULL;
    40+ } else {
    41+ Node *nd = map->root;
    42+ while (nd->entry->key != key) {
    43+ const Node *tmp = key < nd->entry->key ? nd->left : nd->right;
    44+ if (tmp == NULL)
    45+ break;
    46+ nd = tmp;
    47+ }
    48+ if (nd->entry->key == key)
    49+ nd->entry->value = value;
    50+ else if (key < nd->entry->key) {
    51+ nd->left = malloc(sizeof(Node));
    52+ nd->left->entry = malloc(sizeof(Entry));
    53+ nd->left->entry->key = key;
    54+ nd->left->entry->value = value;
    55+ nd->left->left = nd->left->right = NULL;
    56+ } else {
    57+ nd->right = malloc(sizeof(Node));
    58+ nd->right->entry = malloc(sizeof(Entry));
    59+ nd->right->entry->key = key;
    60+ nd->right->entry->value = value;
    61+ nd->right->left = nd->right->right = NULL;
    62+ }
    4545 }
    4646 }
    4747
    4848 void map_remove(Map *map, int key) {
    49- // Removes an entry from the map with the given key
    50- // Assumption: The given key-value pair exists
    51- // (attempting to delete a nonexistent entry yields undefined behavior)
    52- // This also implies that the map cannot be empty
    67+ // Removes the key-value entry from the map with the given key
    68+ // Assumption: The key-value pair in the map exists
    5353 if (map->root->entry->key == key) {
    54- Node *tmp = map->root->next;
    55- free(map->root->entry);
    56- free(map->root);
    57- map->root = tmp;
    70+ if (map->root->right == NULL) {
    71+ Node *tmp = map->root->left;
    5858 } else {
    59- Node *parent = map->root, *child = parent->next;
    60- while (child->next != NULL && child->entry->key != key) {
    61- parent = child;
    62- child = child->next;
    6363 }
    64- parent->next = child->next;
    65- free(child->entry);
    66- free(child);
    6767 }
    6868 }

TIL that

instance Foldable ((,) a) where
    foldMap f (_, y) = f y
    foldr f z (_, y) = f y z
module FoldableTuple2 where
-- see the tests
Code
Diff
  • function throttle(wait, onLast, onFirst, interval, timestamps) {
      ret = [];
      if(onFirst) {
        ret.push(timestamps[0]); // account for first element
      }
      let clusterStart = timestamps[0];
      
      for(let i=1; i<timestamps.length; i++) {
        if(timestamps[i] - timestamps[i-1] > wait) { // 2.) new cluster
          clusterStart = timestamps[i];
          if(onFirst) {
            ret.push(clusterStart); // push cluster start
          }
        }
        if(interval !=0 && (timestamps[i+1] - timestamps[i] > wait || i == timestamps.length-1)) { // 1.) do interval shit
          let intervalVal = clusterStart + interval;
          let loopInvariant = timestamps[i-1];
          if(i == timestamps.length-1){
            loopInvariant = timestamps[i];
          }
          if(onLast) {
            loopInvariant += wait;
          }
      
          console.log('intervalVal: ' + intervalVal);
          console.log('loopInvariant: ' + loopInvariant);
          while(intervalVal <= loopInvariant) {
            console.log('pushing intervalVal: ' + intervalVal);
            ret.push(intervalVal);
            intervalVal += interval;
          }
        }
          
        if(timestamps[i+1] - timestamps[i] > wait) { // 2.) new cluster
          if(onLast) {
            ret.push(timestamps[i] + wait); // push cluster end
          }
        }
        
        if(i == timestamps.length-1 && onLast && interval == 0) { // 3.) Account for last element (needs updating)
          ret.push(timestamps[i] + wait);
        }
      }
      
      return ret;
    }
    
  • 11 function throttle(wait, onLast, onFirst, interval, timestamps) {
    2- let ret = [];
    3- let cluster = [timestamps[0]];
    2+ ret = [];
    3+ if(onFirst) {
    4+ ret.push(timestamps[0]); // account for first element
    5+ }
    6+ let clusterStart = timestamps[0];
    44
    55 for(let i=1; i<timestamps.length; i++) {
    6- if(timestamps[i] - timestamps[i-1] <= wait) {
    7- cluster.push(timestamps[i]);
    8- } else {
    9- let clusterEventTimes = evaluateCluster(wait, onLast, onFirst, interval, cluster);
    10- clusterEventTimes.forEach( function(el){ ret.push(el); });
    11- cluster = [timestamps[i]];
    12- }
    13-
    14- if(i == timestamps.length-1) {
    15- let clusterEventTimes = evaluateCluster(wait, onLast, onFirst, interval, cluster);
    16- clusterEventTimes.forEach( function(el){ ret.push(el); });
    9+ if(timestamps[i] - timestamps[i-1] > wait) { // 2.) new cluster
    10+ clusterStart = timestamps[i];
    11+ if(onFirst) {
    12+ ret.push(clusterStart); // push cluster start
    13+ }
    1717 }
    18- }
    19-
    20- return ret;
    21-}
    22-
    23-// Determines all times when an event needs to be fired
    24-function evaluateCluster(wait, onLast, onFirst, interval, cluster){
    25- let ret = [];
    15+ if(interval !=0 && (timestamps[i+1] - timestamps[i] > wait || i == timestamps.length-1)) { // 1.) do interval shit
    16+ let intervalVal = clusterStart + interval;
    17+ let loopInvariant = timestamps[i-1];
    18+ if(i == timestamps.length-1){
    19+ loopInvariant = timestamps[i];
    20+ }
    21+ if(onLast) {
    22+ loopInvariant += wait;
    23+ }
    2626
    27- if(onFirst) {
    28- ret.push(cluster[0]); // push cluster start
    29- }
    30- if(interval != 0) {
    31- let maxInterval = cluster[cluster.length-1];
    32- if(onLast) {
    33- maxInterval += wait;
    25+ console.log('intervalVal: ' + intervalVal);
    26+ console.log('loopInvariant: ' + loopInvariant);
    27+ while(intervalVal <= loopInvariant) {
    28+ console.log('pushing intervalVal: ' + intervalVal);
    29+ ret.push(intervalVal);
    30+ intervalVal += interval;
    31+ }
    3434 }
    35- for(let intEv = cluster[0]+interval; intEv < maxInterval; intEv+=interval) {
    36- ret.push(intEv);
    33+
    34+ if(timestamps[i+1] - timestamps[i] > wait) { // 2.) new cluster
    35+ if(onLast) {
    36+ ret.push(timestamps[i] + wait); // push cluster end
    37+ }
    3737 }
    38- }
    39- if(onLast) {
    40- ret.push(cluster[cluster.length-1]+wait); // push cluster end
    41- }
    4242
    40+ if(i == timestamps.length-1 && onLast && interval == 0) { // 3.) Account for last element (needs updating)
    41+ ret.push(timestamps[i] + wait);
    42+ }
    43+ }
    44+
    4343 return ret;
    4444 }

It should be as easy as this?

Testing

replicate in one line

Code
Diff
  • def replicate(times, num):
        return [] if times <= 0 else [num] + replicate(times-1, num)
    replicate(8,5)
  • 11 def replicate(times, num):
    2- if times <= 0: return []
    3- return [num] + replicate(times-1, num)
    2+ return [] if times <= 0 else [num] + replicate(times-1, num)
    44 replicate(8,5)
Code
Diff
  • using System;
    using System.Linq;
    
    public static class Kata
    {
      public static int ArraySum(params int[][] arrs)
      {
        return arrs.SelectMany(arr => arr).Sum();
      }
    }
    
  • 11 using System;
    22 using System.Linq;
    33
    44 public static class Kata
    55 {
    66 public static int ArraySum(params int[][] arrs)
    77 {
    8- int sum = 0;
    9- foreach (int[] arr in arrs)
    10- {
    11- sum += arr.Sum();
    12- }
    13- return sum;
    8+ return arrs.SelectMany(arr => arr).Sum();
    1414 }
    1515 }
Code
Diff
  • package kata
    
    // CalcAgeOnMars calculates the age on Mars from on a age on Earth 
    func CalcAgeOnMars(age int) int {
      return age * 365 / 687
    }
    
  • 1-package main
    1+package kata
    22
    3-import "fmt"
    4-
    5-func main() {
    6- var age int
    7- fmt.Printf("Enter your age on Earth: ")
    8- _, err := fmt.Scanf("%d", &age)
    9- if (err != nil) {
    10- fmt.Println(err)
    11- }
    12- age = age * 365 / 687
    13- fmt.Printf("Your age on the surface of Mars is %d years old.\n", age)
    3+// CalcAgeOnMars calculates the age on Mars from on a age on Earth
    4+func CalcAgeOnMars(age int) int {
    5+ return age * 365 / 687
    1414 }

Yet another one-liner.

Code
Diff
  • def mul():
        return sum(list (x for x in range(1000) if (not x%3) or (not x%5)))
        
  • 11 def mul():
    2- return sum(filter(lambda x:x%3==0 or x%5==0,range(1000)))
    2+ return sum(list (x for x in range(1000) if (not x%3) or (not x%5)))
    33
Code
Diff
  • type Gender = Male | Female    
    type Person = { Name : string; Gender : Gender }
    
    let alice = { Name = "Alice"; Gender = Female }
    let bob = { Name = "Bob"; Gender = Male }
    
    let femaleOrMale = function 
      | { Name = name; Gender = Female } -> name + " is female."
      | { Name = name; Gender = Male } -> name + " is male."
  • 11 type Gender = Male | Female
    22 type Person = { Name : string; Gender : Gender }
    33
    44 let alice = { Name = "Alice"; Gender = Female }
    55 let bob = { Name = "Bob"; Gender = Male }
    66
    7-let femaleOrMale p =
    8- match p.Gender with
    9- | Female -> p.Name + " is female."
    10- | Male -> p.Name + " is male."
    7+let femaleOrMale = function
    8+ | { Name = name; Gender = Female } -> name + " is female."
    9+ | { Name = name; Gender = Male } -> name + " is male."
Code
Diff
  • # finally fixed
    echo $1
  • 1+# finally fixed
    11 echo $1
Code
Diff
  • # finally fixed
    printf test
  • 1+# finally fixed
    11 printf test

Objective: given 1 <= K <= 26, 0 <= N count the number of different strings of length N that contain exactly K different characters from the alphabet.

Ideas: for small values of N it should be bruteforce-able.
For large values of N?

Clarifications:
-> "The alphabet" is the 26 lowercase letters of the English alphabet

alphabet = 'abcdefghijklmnopqrstuvwxyz'

import itertools

def counter(N, K):
    return counterNaive(N, K)

def counterNaive(N, K):
#    print(f"counterNaive({K}, {N})")
    allCombs = [x for x in itertools.product(alphabet, repeat=N)]
#    print(f"All combinations of length {N}: 26^N = {26**N}")
    return sum( len(set(x)) == K for x in allCombs )
    
def counterSmart(N, K):
    # Idea:
    # Find all ways of splitting N in K parts
    # For each such way, once we know the lenght of the parts K1, ..., Kn
    # (And they must be such that K1+...+Kn = N)
        # Calculate the possible combinations: they are N!/(N-K)! options for the choice of K letters
        # divided by the product of:
            # L! where L = count(Kn == j) for j in range(N)
            # to compensate the fact that if letters 'a' and 'b' appear in the same amount,
            # then doing (a, b) = (b, a) does not give a different sequenec
        # times the permutations of N elements with K1, ..., Kn repetitions
    # Then add these up
    pass
Code
Diff
  • #!/bin/bash
    for (( i=1; i <= $3; i++)); do
      (( $i % ($1 * $2) )) || echo $i
    done
  • 11 #!/bin/bash
    2-for i in $(eval echo {1..$3});
    3-do
    4-if [ $(( $i % ( $1*$2) )) -eq 0 ]
    5-then
    6-echo $i
    7-fi
    2+for (( i=1; i <= $3; i++)); do
    3+ (( $i % ($1 * $2) )) || echo $i
    88 done
Code
Diff
  • #include <utility>
    
    std::pair<int, int> foo() {
      return {1, 1};
    }
    
  • 11 #include <utility>
    22
    33 std::pair<int, int> foo() {
    4- return {0, 0};
    4+ return {1, 1};
    55 }

Alternative Function Syntax

Just discovered this by looking at a few Fortran code examples online, but it seems that in as early as Fortran 95 (perhaps even earlier!), functions can be defined in at least two ways.

The traditional way:

function FUNCTION_NAME(PARAMETER) ! or parameters
  PARAMETER_TYPE :: PARAMETER
  RETURN_TYPE :: FUNCTION_NAME ! or explicit result variable
  ! Function body
end function FUNCTION_NAME

And the second (perhaps more C-like) way:

RETURN_TYPE function FUNCTION_NAME(PARAMETER)
  PARAMETER_TYPE :: PARAMETER
  ! Function body
end function FUNCTION_NAME

Of course, with either syntax, it is possible to add modifiers such as pure, recursive or result(RESULT_VAR).

module Solution
  implicit none
contains
  integer pure function add(a, b) result(c)
    integer, intent(in) :: a, b
    c = a + b
  end function add
end module Solution

Type Initializers

When you define a derived data type in GNU Fortran, you are automatically given a type initializer which allows you to initialize an instance of your derived data type in one go. One can think of a type initializer as a primitive type of constructor. However, custom-defined constructors weren't available until Fortran 2003 so it may not be available in GNU Fortran (which is an extension of the Fortran 95 standard).

module Solution
  implicit none
  type Vec3D ! A three-dimensional vector
    integer :: x, y, z
  end type Vec3D
  type(Vec3D) :: v = Vec3D(1, 2, 3) ! Using the type initializer provided by Fortran
end module Solution

This Kumite is created to test JQuery support on Codewars.

var jsdom = require("jsdom/lib/old-api.js");

jsdom.env(
    '<!DOCTYPE html><p>Hello world</p><a class="the-link" href="https://github.com/tmpvar/jsdom">jsdom!</a>', ["http://code.jquery.com/jquery.js"],
    function(err, window) {
        console.log(window.document.querySelector("p").textContent);
        var $ = window.$;

        $.getJSON('https://www.codewars.com/users/Javatlacati', null, function(data) {
            console.log(data);
        }).error(function(e) {
            console.log("first attempt failed\n" + JSON.stringify(e));
        });



        var name = "kazk";
        var url = "http://anyorigin.com/go?url=" + encodeURIComponent("https://www.codewars.com/users/") + name + "&callback=?";
        $.get(url, function(response) {
            console.log(response);
        }).error(function(e) {
            console.log("second attempt failed\n" + JSON.stringify(e));
        });
        console.log("contents of a.the-link:", window.$("a.the-link").text());
    }
);

Dynamic Memory Allocation by using C library malloc() function

It is possible to allocate memory dynamically in NASM (obviously, otherwise how would it be possible in C and other higher-level languages?) and the easiest way to do it is probably by relying on the C library function malloc().

global one_two_three
extern malloc ; C library function malloc()
section .text
one_two_three:
  mov rdi, 12 ; size_t bytes_required = 3 * sizeof(int) == 12 (because sizeof(int) == 4 on CW)
  call malloc ; int *result = malloc(bytes_required)
  mov dword [rax], 1 ; result[0] = 1 (`dword` means "double word" where 1 word = 2 bytes)
  mov dword [rax + 4], 2 ; result[1] = 2
  mov dword [rax + 8], 3 ; result[2] = 3
  ret ; return result

Actually, that was double -> int, now int -> double.

Code
Diff
  • global to_double
    section .text
    to_double:
                    cvtsi2sd    xmm0, edi
                    ret
    
  • 1-global trunc_
    1+global to_double
    22 section .text
    3-trunc_:
    4- cvttsd2si eax, xmm0
    3+to_double:
    4+ cvtsi2sd xmm0, edi
    55 ret

String literals are stored as read-only (const), and any attempt to modify the pointer returned will result in a SEGFAULT (crash) in most current computing environments.

Obvserving the following assembly output from GCC:

    .file   "tst.c"
    .text
    .section    .rodata
.LC0:
    .string "Hello World."
    .text
    .globl  Hi
    .type   Hi, @function
Hi:

You can see string literal referred to by label .LC0 is defined within section '.rodata' meaning ready-only data.

Therefore Hi() should have a return type of const char* to avert the possibility of such faulty access occurring.

Code
Diff
  • const char* Hi (void)
    {
      return("Hello World.");
    }
    
    char *oopsHi(void)
    {
      return ("Hello World.");
    }
    
  • 1-char* Hi (void)
    1+const char* Hi (void)
    22 {
    3-return("Hello World.");
    3+ return("Hello World.");
    4+}
    5+
    6+char *oopsHi(void)
    7+{
    8+ return ("Hello World.");
    44 }
Code
Diff
  • syntax error here again
  • 1-syntax error here
    1+syntax error here again
Code
Diff
  • using System;
    
    namespace Solution {
    
      class FizzBuzz {
        public static string Convert(int input)
            {
                var divisableBy3 = input % 3 == 0;
                var divisableBy5 = input % 5 == 0;
                
                return (!divisableBy3 & !divisableBy5) ? input.ToString()
                  : (divisableBy3 ? "Fizz" : string.Empty) +  (divisableBy5 ? "Buzz" : string.Empty);
            }
      }
    }
  • 11 using System;
    22
    33 namespace Solution {
    44
    55 class FizzBuzz {
    66 public static string Convert(int input)
    77 {
    8- var divisableBy3 = (input % 3 == 0);
    9- var divisableBy5 = (input % 5 == 0);
    8+ var divisableBy3 = input % 3 == 0;
    9+ var divisableBy5 = input % 5 == 0;
    1010
    1111 return (!divisableBy3 & !divisableBy5) ? input.ToString()
    1212 : (divisableBy3 ? "Fizz" : string.Empty) + (divisableBy5 ? "Buzz" : string.Empty);
    1313 }
    1414 }
    1515 }