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
  • 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))
Code
Diff
  • let helloLangs = {
      english: "hello",
      pirate: "yar"
    }
    
    const hello = (whoever, lang="english") => `${helloLangs[lang]} ${whoever}`;
  • 1-const helloLangs = {
    1+let helloLangs = {
    22 english: "hello",
    33 pirate: "yar"
    44 }
    55
    66 const hello = (whoever, lang="english") => `${helloLangs[lang]} ${whoever}`;

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

Let's just hide that the Stack is implemented with an array, so that we're not tempted to use other methods as shift() 😇

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();
      }
      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;
        }
      }
    }
  • 1+class Stack { // Just to hide the use of array implementation
    2+ constructor() {
    3+ this._items = [];
    4+ }
    5+ push(data) {
    6+ this._items.push(data);
    7+ }
    8+ pop() {
    9+ return this._items.pop();
    10+ }
    11+ length() {
    12+ return this._items.length;
    13+ }
    14+}
    15+
    11 class Queue {
    22 constructor() {
    3- this._stack = []; // We will be using this array as a stack - only
    4- // its push and pop operations will ever be called
    18+ this._stack = new Stack();
    55 }
    66 enqueue(data) {
    77 this._stack.push(data);
    88 }
    99 dequeue() {
    10- if (this._stack.length === 1)
    24+ if (this._stack.length() === 1)
    1111 return this._stack.pop();
    1212 else {
    1313 var tmp = this._stack.pop(), result = this.dequeue();
    1414 this.enqueue(tmp);
    1515 return result;
    1616 }
    1717 }
    1818 }
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
Fundamentals
Strings

You will be given a number of minutes. Your task is to return a string on the heap that formats the number into 'hours:minutes".

Make sure you always return two integers for the minutes section of the conversion.

i.e. ('0:01' instead of '0:1')

Example:

minutes(90) => '1:30'

Code
Diff
  • char *minutes(int num){
      char *ret = calloc(64, sizeof(char));
      sprintf(ret, "%d:%02d", (num / 60), (num % 60));
      return ret;
    }
  • 1-function minutes(num){
    2- return num % 60 < 10 ? Math.floor(num/60) + ':' + '0' + (num % 60) : Math.floor(num/60) + ':' + (num % 60)
    1+char *minutes(int num){
    2+ char *ret = calloc(64, sizeof(char));
    3+ sprintf(ret, "%d:%02d", (num / 60), (num % 60));
    4+ return ret;
    33 }
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 }

i know it's too late to reply ...but as said in the previous comment your Code is fine you just need some little changes..and because i am a bad explainer i am just going to show my simple version of the code .....

Code
Diff
  • //if you have any Suggestion or noticed a mistake in my code ...tell me...i would need that...
    function test(n) {
      var sum=0;
      for (i=1; i<n; i++){
        if ((i%3==0) || (i%5==0)){
        sum+=i;
        }
      }
       return sum;
    }
  • 1-function test() {
    2- var a = [];
    3- for (i=1; i<10; i++){
    1+//if you have any Suggestion or noticed a mistake in my code ...tell me...i would need that...
    2+function test(n) {
    3+ var sum=0;
    4+ for (i=1; i<n; i++){
    44 if ((i%3==0) || (i%5==0)){
    5- a.push(i);
    6+ sum+=i;
    66 }
    77 }
    8- return a;
    9+ return sum;
    99 }
    10-
    11-function sum(number){
    12- var sum= 0;
    13- for(i=0; i<number.length; i++){
    14- sum += number[i];
    15- }
    16- return sum;
    17- }
    18-var ab = test();
    19-var abc = sum(ab);
    20-console.log(abc);
Algorithms

update for ES6 with spread operator

Code
Diff
  • const flatten = arr =>
      arr.reduce((acc, item) =>  [...acc, ...(Array.isArray(item) ? flatten(item) : [item])],[]);
  • 11 const flatten = arr =>
    2- arr.reduce((acc, item) => acc.concat(Array.isArray(item) ? flatten(item) : item), []);
    2+ arr.reduce((acc, item) => [...acc, ...(Array.isArray(item) ? flatten(item) : [item])],[]);

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 }
Strings
Code
Diff
  • const lastChar = ([...s]) => s.pop();
    
  • 1-const lastChar=s=>[...s].pop()
    1+const lastChar = ([...s]) => s.pop();
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 }
Advanced Language Features
Fundamentals

Pointers

Fortran has basic support for pointers. A pointer is a rather primitive type of reference - it is essentially a memory address (associated with a given type) which is said to "point to" the data it is referencing. Unlike C/C++/ObjC, Fortran does not support pointers to pointers, function pointers, arrays of pointers or pointer arithmetic but it is still sufficient to allow us to define simple recursive datatypes such as linked lists or binary trees.

To declare a pointer:

integer, pointer :: p ! `p` is a non-associated integer pointer

To associate a pointer to a target:

! The `target` annotation is required for a pointer to point to it
! Otherwise, `n` is just another ordinary integer
integer, target :: n = 42
integer, pointer :: p => n ! `p` is now associated with `n`

To dereference a pointer:

integer, target :: n = 42
integer, pointer :: p => n ! `p` points to `n`
p = 100 ! `p` is automatically dereferenced and its target `n` set to 100

To associate a pointer to another target:

integer, target :: m = 100, n = 42
integer, pointer :: p => n ! `p` points to `n`
p => m ! `p` now points to `m` instead

To make two (or more) pointers point to the same target:

integer, target :: n = 42
integer, pointer :: p1, p2
p1 => n ! `p1` points to `n`
p2 => p1 ! `p2` now points to the TARGET of `p1` which is `n`
! REMEMBER: `p2` does NOT point to `p1` - pointers
! to pointers are not permitted in Fortran

To define a null pointer (i.e. one that does not reference any data):

integer, pointer :: p => null()

To allocate memory for a pointer instead of pointing it to a pre-existing target:

integer, pointer :: p
allocate(p) ! Allocate memory under pointer (just sufficient for one integer)
! Do something with `p`.  Make sure `p` doesn't point to anything else
! before it is deallocated (otherwise a memory leak will occur)!
deallocate(p) ! Free the memory under the pointer

To check whether a pointer is associated with a target:

associated(p) ! Checks whether `p` is associated with a target
! Evaluates to the corresponding logical value
! (.true. if associated, .false. otherwise)

The main code example in this Kumite involves derived data types.

module Pointers
  implicit none
  type Node ! A node of a singly linked list
    integer :: data
    type(Node), pointer :: next
  end type Node
end module Pointers

Operator Overloading

In Fortran, operator overloading is done via interfacing. The syntax is almost identical to overloading procedures except the name of the alias is replaced by operator (OPERATOR) (where OPERATOR is a placeholder for the actual operator).

Unlike some programming languages such as Haskell, operators to be overloaded cannot contain arbitrary symbols (or a sequence thereof). Only the following operators and types of operators can be overloaded/defined:

  • Symbol / symbol combinations already defined as operators in Fortran (e.g. +, -, *, /, ==, /=, etc.)
  • .OPERATOR_NAME. where OPERATOR_NAME may only contain English letters (not even numbers, not even underscore)

Operators can be unary or binary or both (of the form OPERATOR OPERAND or OPERAND_1 OPERATOR OPERAND_2) depending on whether the function(s) implementing it accept one or two arguments. However, for operators intrinsic to Fortran (such as * or /), the functions implemeting their overloads may only accept as many arguments as they were originally defined (e.g. you cannot overload * to accept only one operand).

Note that operators must be pure in Fortran, i.e. they are not permitted to mutate their operands. Therefore, functions implementing the overloaded operator must be declared pure (or if not, at least all input parameters must be declared intent(in)).

module OperatorOverloading
  implicit none
  private :: realRecip, cmplxRecip ! Hide implementation details of overloaded operator
  interface operator (.recip.) ! Operator for finding the reciprocal
  ! (i.e. multiplicative inverse) of a number
    module procedure realRecip, cmplxRecip
  end interface
contains
  pure function realRecip(x)
    real, intent(in) :: x
    real :: realRecip
    realRecip = 1.0 / x
  end function realRecip
  pure function cmplxRecip(z)
    complex, intent(in) :: z
    complex :: cmplxRecip
    cmplxRecip = cmplx(1, 0) / z
  end function cmplxRecip
end module OperatorOverloading

Just a simple C function void say_hello() written in NASM v2.11.x which prints Hello World! to the console.

global say_hello
section .text
say_hello:
  mov eax, 4 ; system call for write (for Linux)
  mov ebx, 1 ; file handle 1 is STDOUT
  mov ecx, message ; memory address of output buffer
  mov edx, msgLen ; size of output buffer in bytes
  int 0x80 ; invoke OS to do the write
  ret ; Return to the caller

section .data ; Read-only data
message db "Hello World!", 10 ; message = "Hello World!\n"
msgLen equ $-message ; msgLen = strlen(message)
Interfaces
Basic Language Features
Object-oriented Programming
Fundamentals

Interfacing

In Fortran modules, it is possible to "overload" a prodecure with several variants, each accepting different types/numbers of arguments through interfacing. An interface is essentially a named alias to one or more defined procedures. For example, when we first introduced functions, our add function was only capable of accepting two default (32-bit) integers and compute its sum (as a 32-bit integer). What if we wanted our add function to work on reals as well? Or complex numbers? In that case, all we have to do is to define three separate functions and implement them accordingly - let's call them addIntegers, addReals and addComplexNumbers. After that, we alias them all under the same name add through interfacing which is achieved by using the interface keyword and has the following syntax (ALL_CAPS denote placeholders):

interface ALIAS_NAME
  module procedure PROC_1, PROC_2, ..., PROC_N
end interface ALIAS_NAME

The interface is always placed at the top section of the module, i.e. before the contains keyword:

module InterfacingExample
  implicit none
  ! Our interface
  interface add
    ! The `addIntegers`, `addReals` and `addComplexNumbers`
    ! functions should all be aliased number the name `add`
    module procedure addIntegers, addReals, addComplexNumbers
  end interface add
contains
  pure function addIntegers(a, b) result(c)
    integer, intent(in) :: a, b
    integer :: c
    c = a + b
  end function addIntegers
  pure function addReals(a, b) result(c)
    real, intent(in) :: a, b
    real :: c
    c = a + b
  end function addReals
  pure function addComplexNumbers(a, b) result(c)
    complex, intent(in) :: a, b
    complex :: c
    c = a + b
  end function addComplexNumbers
end module InterfacingExample

Now let's test it in our program:

program Main
  use InterfacingExample
  implicit none
  print *, add(1, 2) ! > 3 (perhaps with padding)
  print *, add(3.5, 4.5) ! > 8.0 (perhaps with padding)
  print *, add(cmplx(3, -4), cmplx(2, 1)) ! > (5.0, -3.0) (perhaps with padding)
end program Main

Our alias works as expected. However, at this point, you might be wondering if the functions are still accessible through their original names (e.g. addIntegers). If that is the case then your doubts are well-founded - the functions are still accessible through their original names (which may not be desirable). To hide the original names of the functions and expose only the alias, simply declare the original function names as private the same way you would variables/constants:

module InterfacingExample
  implicit none
  private :: addIntegers, addReals, addComplexNumbers
  ! Our interface
  interface add
    ! The `addIntegers`, `addReals` and `addComplexNumbers`
    ! functions should all be aliased number the name `add`
    module procedure addIntegers, addReals, addComplexNumbers
  end interface add
contains
  pure function addIntegers(a, b) result(c)
    integer, intent(in) :: a, b
    integer :: c
    c = a + b
  end function addIntegers
  pure function addReals(a, b) result(c)
    real, intent(in) :: a, b
    real :: c
    c = a + b
  end function addReals
  pure function addComplexNumbers(a, b) result(c)
    complex, intent(in) :: a, b
    complex :: c
    c = a + b
  end function addComplexNumbers
end module InterfacingExample
module InterfacingExample
  implicit none
  private :: addIntegers, addReals, addComplexNumbers
  ! Our interface
  interface add
    ! The `addIntegers`, `addReals` and `addComplexNumbers`
    ! functions should all be aliased number the name `add`
    module procedure addIntegers, addReals, addComplexNumbers
  end interface add
contains
  pure function addIntegers(a, b) result(c)
    integer, intent(in) :: a, b
    integer :: c
    c = a + b
  end function addIntegers
  pure function addReals(a, b) result(c)
    real, intent(in) :: a, b
    real :: c
    c = a + b
  end function addReals
  pure function addComplexNumbers(a, b) result(c)
    complex, intent(in) :: a, b
    complex :: c
    c = a + b
  end function addComplexNumbers
end module InterfacingExample
Functions
Control Flow
Basic Language Features
Fundamentals
Recursion
Algorithms
Computability Theory
Theoretical Computer Science

Fortran Procedures - Subroutines

In a previous Kumite, I mentioned that there are two types of procedures in Fortran:

  1. Functions - These evaluate to a given value which is returned to the caller (for further computation by other parts of the program, for example)
  2. Subroutines - These only perform a set of actions and do not evaluate to any value

This Kumite aims to demonstrate how to define and invoke a Fortran subroutine.

A Fortran subroutine is in fact declared/defined in the same way as a function except the function keyword (in both the first and last lines) are replaced with subroutine. Pretty much everything else that holds for functions also holds for subroutines, with the exception of a lack of return value (and therefore result(<res_var>) annotation is not permitted). You can even declare a subroutine as recursive (and/or even pure)!

module Solution
  implicit none
contains
  recursive subroutine print1ToN(n)
    integer :: n
    if (n > 0) then
      call print1ToN(n - 1) ! NOTE: See explanation below code example
      print "(I0)", n
    end if
  end subroutine print1ToN
end module Solution

When invoking a subroutine, the syntax is slightly different - you have to add the call keyword in front of the subroutine name, like such:

program TestCases
  use Solution
  implicit none
  call print1ToN(10)
  ! > 1
  ! > 2
  ! > ... (you get the idea ;) )
  ! > 10
end program TestCases
module Solution
  implicit none
contains
  recursive subroutine print1ToN(n)
    integer :: n
    if (n > 0) then
      call print1ToN(n - 1) ! NOTE: See explanation below code example
      print "(I0)", n
    end if
  end subroutine print1ToN
end module Solution
Functions
Control Flow
Basic Language Features
Fundamentals
Recursion
Algorithms
Computability Theory
Theoretical Computer Science

Fortran Procedures - Recursive Functions

In my last Kumite you learned how to declare and define a function in Fortran. If you were interested in it, you may have done some experimentation on defining a few of your own. Some of you might even have attempted to define a recursive function in Fortran using the syntax shown in the last Kumite. For example, you might have tried to find the sum of the first n positive integers recursively:

module Solution
  implicit none
contains
  function sum1ToN(n) result(sum)
    integer :: n, sum
    if (n <= 0) then
      sum = 0
    else
      sum = n + sum1ToN(n - 1)
    end if
  end function sum1ToN
end module Solution

However, if you attempted to compile and execute this module (with an accompanying program), you would've seen an error message similar to the following: Error: Function 'sum1ton' at (1) cannot be called recursively, as it is not RECURSIVE. In fact, you can define a recursive function in Fortran, but you need to add the recursive modifier to the beginning of your function declaration in order to do so:

module Solution
  implicit none
contains
  recursive function sum1ToN(n) result(sum)
    integer :: n, sum
    if (n <= 0) then
      sum = 0
    else
      sum = n + sum1ToN(n - 1)
    end if
  end function sum1ToN
end module Solution

Now, when we define our program using this module and test our sum1ToN function, everything works as expected:

program TestCases
    use Solution
    implicit none
    print "(I0)", sum1ToN(10) ! > 55
end program TestCases

The recursive keyword can also be used in conjunction with the pure keyword to specify a pure function that has the capacity to invoke itself recursively.

module Solution
  implicit none
contains
  pure recursive function sum1ToN(n) result(sum)
    integer, intent(in) :: n
    integer :: sum
    if (n <= 0) then
      sum = 0
    else
      sum = n + sum1ToN(n - 1)
    end if
  end function sum1ToN
end module Solution
module Solution
  implicit none
contains
  pure recursive function sum1ToN(n) result(sum)
    integer, intent(in) :: n
    integer :: sum
    if (n <= 0) then
      sum = 0
    else
      sum = n + sum1ToN(n - 1)
    end if
  end function sum1ToN
end module Solution
Functions
Control Flow
Basic Language Features
Fundamentals

Fortran Procedures - Functions, Pass By Reference and Purity

In Fortran it is possible to define reusable sets of instructions that either perform a given action / actions or evaluate to a certain value (or do both) which are called procedures. There are two main types of procedures:

  1. Functions - These eventually evaluate to a certain value which can then be used by the caller. They can be pure (i.e. do not cause any side effects, more on that later) or impure (causing side effects and/or modifying the state of the program in the process).
  2. Subroutines - These only perform a given set of actions and do not evaluate to any value. Subroutines may also be pure/impure.

This Kumite demonstrates how to define and use a function.

A function (and in fact any procedure) can be defined in any module/program (it does not matter which, the declaration syntax is identical in both cases) by placing them at the bottom half of the module/procedure. To do that, the given program/module has to be split into exactly two sections using the contains statement/keyword in between. The top section contains all of the variable declarations and statements of the program/module, while the bottom section contains all of the procedure definitions:

module FunctionExample
  implicit none
  ! Top section - contains all variable declarations/definitions
contains
  ! Bottom section - contains all function and subroutine
  ! (i.e. procedure) definitions
end module FunctionExample

Then, under the contains statement, we declare and define our function using a function declaration of the form function <fn_name>(<var_1>, <var_2>, ..., <var_n>). We end our function definition using end function <fn_name> and our function body goes between these two lines. For example, if we want to declare and define an add function that adds two integers, our module would look like this:

module FunctionExample
  implicit none
  ! Variable declarations
contains
  function add(a, b)
    ! TODO
  end function add
end module FunctionExample

If you've paid any amount of attention to my previous Kumite then it should've occurred to you by now that Fortran is a statically typed language, i.e. each variable has a fixed type that cannot be changed at runtime. However, our function declaration shown above didn't assign any types to the parameters a and b (which we want to be integers). So, how to declare their types? Fortunately, it's very simple and straightforward - just declare them at the top of the function body like you would global variables at the start of a program/module!

module FunctionExample
  implicit none
  ! Variable declarations
contains
  function add(a, b)
    integer :: a, b
  end function add
end module FunctionExample

In our add function, we would like to compute the sum of the integers a and b and return the corresponding integer value to the caller. Unfortunately, there is no return keyword in Fortran so how is it done? In Fortran we must store the result we want to return to the caller in a variable with an identical name to the function name which is add in this case. Our result is anticipated to be an integer so we need to declare the type of add as well:

module FunctionExample
  implicit none
  ! Variable declarations
contains
  function add(a, b)
    integer :: a, b
    integer :: add
  end function add
end module FunctionExample

Then, we simply assign the result of adding a and b to add:

module FunctionExample
  implicit none
  ! Variable declarations
contains
  function add(a, b)
    integer :: a, b
    integer :: add
    add = a + b
  end function add
end module FunctionExample

Now our function declaration/definition is complete and we can use it in our program as desired.

program MyProgram
  use FunctionExample
  implicit none
  print "(I0)", add(3, 5) ! > 8
end program MyProgram

Using a custom variable name for the returned result

What if you don't want to use the function name to store the returned result? For example, instead of add = a + b, you want to do c = a + b and have c store the result to be returned. All you have to do is modify the function declaration to function <fn_name>(<var_1>, <var_2>, ..., <var_n>) result(<result_var>) and subsequently the affected variable declarations:

module FunctionExample
  implicit none
  ! Variable declarations
contains
  function add(a, b) result(c)
    integer :: a, b
    integer :: c
    c = a + b
  end function add
end module FunctionExample

Procedure arguments in Fortran are passed by variable reference, not by value or object reference

Unlike many modern programming languages such as C, Java or Python, procedure (and hence function) arguments in Fortran are passed by variable reference. This means that if you reassign the values of arguments within your function, the passed in variable itself will be affected.

module FunctionExample
  implicit none
contains
  function add(a, b) result(c)
    integer :: a, b
    integer :: c
    a = a + b ! Argument `a` is assigned the value of the result
    c = a ! Result variable `c` assigned the new value of `a`
  end function add
end module FunctionExample
program MyProgram
  use FunctionExample
  implicit none
  integer :: m = 3, n = 5

  ! > m = 3, n = 5
  print "(A4, I0, A6, I0)", "m = ", m, ", n = ", n

  ! > add(m, n) = 8
  print "(A12, I0)", "add(m, n) = ", add(m, n)

  ! This segfaults
  ! print "(I0)", add(3, 5)

  ! > m = 8, n = 5
  print "(A4, I0, A6, I0)", "m = ", m, ", n = ", n
end program MyProgram

Therefore, in Fortran, one must be careful not to assign any new values to existing parameters (unless there is a good reason to do so deliberately).

Pure Functions

A pure function is one that does not mutate its input in any way and does not depend on and/or change the state of the program when it is executed/evaluated. Due to Fortran's pass-by-variable-reference, it is easy to make a mistake and mutate the value of argument variables passed in and therefore violate this rule. Fortunately, Fortran has native syntactical support for these types of functions - simply prepend the function declaration with the pure keyword: pure function <fn_name>(<v1>, <v2>, ..., <vn>) result(<rv>).

By explicitly declaring your function as pure, Fortran enforces compile-time restrictions on the type declarations of all the parameters to ensure that all parameters are declared in a way that their value cannot be reassigned. This means that we need to modify the parameter declarations by adding a comma, followed by intent(in) after the type name (and before the ::) - this tells the Fortran compiler that the values of the parameters are read-only:

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

Now we can use the add function with the guarantee that it will never mutate its inputs:

program MyProgram
  use FunctionExample
  implicit none
  integer :: m = 3, n = 5
  print "(I0)", add(m, n) ! > 8
  print "(I0)", add(3, 5) ! Works - no segfault :)
  print "(I0)", m ! > 3
  print "(I0)", n ! > 5
end program MyProgram
module FunctionExample
  implicit none
contains
  pure function add(a, b) result(c)
    integer, intent(in) :: a, b
    integer :: c
    c = a + b
  end function add
end module FunctionExample

Just a quick test to see how Preloaded works with GNU Fortran on Codewars ...

module Solution
  use Preloaded
  implicit none
  integer :: n = answer - 42 ! n = 0
end module Solution
Modules
Fundamentals
Object-oriented Programming

Fortran Modules

Fortran modules allow us to split our code into logical chunks across files, each providing a specific functionality and/or set of functionalities and allows us to reuse certain code files in different projects/programs. To create a module, a separate file should first be created. Then, in that separate file, add a module <module_name> statement where <module_name> is a placeholder for the name of our module. In our case, let's name it MyFirstModule. After that, we end our module by adding end module <module_name> on the last line and put everything else in between.

Our module now looks like this:

module MyFirstModule
  ! TODO
end module MyFirstModule

Same as in a program, the first statement inside a module should almost always be implicit none which disables type inference in the case of a programmer error (e.g. forgetting to declare a variable before defining/using it).

module MyFirstModule
  implicit none
  ! TODO
end module MyFirstModule

Apart from the fact that modules are not executed themselves (they are used in other programs which are then executed), they are almost identical to a program, with one major difference: No action can be performed in a module (at least at the top level). This means that you cannot use print statements among other things as you would in a program - you can only declare/define variables, constants and procedures (more on procedures in future Kumite). For example:

module MyFirstModule
  implicit none
  integer, parameter :: answer = 42
  real :: x = 0.0, y = 1.0
  character(len=12) :: hello = "Hello World!"
end module MyFirstModule

Then, to use a module in our program, we add the statement use <module_name> before implicit none:

program MyProgram
  use MyFirstModule
  implicit none
  ! TODO
end program MyProgram

Now our program will be able to see all of the variables, constants and procedures that our module has declared/defined. What if we want to hide the two reals x and y (because it is an implementation detail and not intended to be used directly in a program, for example) from the main program? To do that, we simply add a declaration private :: <variable_or_procedure_name_1>, <variable_or_procedure_name_2>, ..., <variable_or_procedure_name_n> to control its visiblity. Our module now looks like this:

module MyFirstModule
  implicit none
  integer, parameter :: answer = 42
  real :: x = 0.0, y = 1.0
  character(len=12) :: hello = "Hello World!"
  private :: x, y ! x and y are now private to the module itself
  ! and no longer exposed to the program using it
end module MyFirstModule

Finally, we can use the (exposed) variables/constants/procedures from our module in our main program as if they were defined in our program in the first place:

program MyProgram
  use MyFirstModule
  implicit none
  print "(I0)", answer
  print "(A12)", hello
end program MyProgram

See both Kumite "Code" and "Fixture" for the full code example.

module MyFirstModule
  implicit none
  integer, parameter :: answer = 42
  real :: x = 0.0, y = 1.0
  character(len=12) :: hello = "Hello World!"
  private :: x, y ! x and y are now private to the module itself
  ! and no longer exposed to the program using it
end module MyFirstModule
Fundamentals
Variables
Basic Language Features

Constants, Variables and Datatypes in Fortran

In Fortran, there are a few intrinsic datatypes (known as primitive datatypes in other programming languages):

  • integer - An integral value such as 23 or -133. By default, an integer is 4 bytes (32 bits) long. Integers of custom size can be specified using the integer(kind=n) syntax where n is the number of bytes that the integer occupies in memory an can be either of 1, 2, 4, 8 and 16.
  • real - A floating point value such as 2.0 or 3.14. By default, real is single precision (i.e. only 4 bytes long) but real(kind=8) is double precision (since it occupies 8 bytes in memory)
  • complex - A set of (two) floating point values representing a complex number. By default, both floats are single precision but complex(kind=8) holds two double-precision floats instead. Complex numbers are defined using the intrinsic function cmplx with two or three arguments, e.g. cmplx(3, 4) defines a default complex number (components are single precision floating point values) representing the value 3 + 4i
  • logical - A special type of value that can only ever take two values: .true. or .false.. Equivalent to a boolean in most modern programming languages.
  • character - A character (i.e. string with length 1) or character string. By default, it specifies a character such as 'C' or "0" but character(len=n) specifies a character string of length n instead.

Declaration of a variable must be done after implicit none and before any other statements. It takes the following form: <type_name> :: <variable_1>, <variable_2>, ... , <variable_n>. For example, if we want to declare a variable answer with type integer, our program would look like this:

program ConstantsVariablesAndDatatypes
  implicit none
  integer :: answer
end program ConstantsVariablesAndDatatypes

We can also define our variable on the same line as the declaration, like such:

program ConstantsVariablesAndDatatypes
  implicit none
  integer :: answer = 42 ! `=` is the assignment operator
end program ConstantsVariablesAndDatatypes

After we declare a variable, we can assign/reassign to it, use it in our computations and/or print it out as desired. For example:

program ConstantsVariablesAndDatatypes
  implicit none
  integer :: answer = 42
  print "(I0)", answer ! > 42
  answer = 100 ! Reassignment
  print "(I0)", answer ! > 100
end program ConstantsVariablesAndDatatypes

What if we don't want to change the value of a "variable" after initialization? We can do that by adding a comma followed by the parameter keyword to mark a "variable" as a constant. For example:

program ConstantsVariablesAndDatatypes
  implicit none
  real(kind=8), parameter :: PI = 3.141592653589793
end program ConstantsVariablesAndDatatypes

We can then use it in our computations and/or print it out but not reassign to it:

program ConstantsVariablesAndDatatypes
  implicit none
  real(kind=8), parameter :: PI = 3.141592653589793 ! Our PI constant
  print *, PI ! Prints something like "3.141592653589793", perhaps with leading/trailing whitespace

  ! The line below causes compilation to fail with an error
  ! PI = 2.718281828459045
end program ConstantsVariablesAndDatatypes

See "Fixture" of this Kumite for more examples.

module Solution
  ! Please refer to "Fixture" for examples, we will learn about modules in future Kumite ;)
end module Solution
Fundamentals

In my previous Kumite, we learned how to print out Hello World! to the console in Fortran. However, you may have noticed it wasn't perfect - the output has an unnecessary leading whitespace! So, the question is, how to remove it?

When the default settings (denoted by *) is used for the format specifier for print in Fortran, Fortran has to guess how much space it should reserve for the output which it usually overestimates, resulting in undesired padding of the output. To rectify this issue, we can provide our customized format specifier for print.

A customized format specifier for print is passed as a string and is always enclosed in parentheses (). Inside the parentheses, one or more individual format specifiers are separated by a comma , which may or may not be prepended/appended with one or more whitespace characters as desired. The individual format specifiers are as follows:

  • An (n is a positive integer) - a string of length n. For example, A10 specifies that the output contains a string of length 10.
  • I0 - an integer (of any size) containing any number of digits
  • In - an integer containing exactly n digits

There are also many other format specifiers for floating point values, logical values (known as booleans in most modern programming languages) and so on but we won't cover them in this Kumite.

Since we know that the string "Hello World!" contains exactly 12 characters, our format specifier for this string when printing it to STDOUT is A12. Hence, the full format specifier for the entire line of output should be (A12):

program HelloWorld
  implicit none
  print "(A12)", "Hello World!"
end program HelloWorld

This should print the output text Hello World! to the console without any leading or trailing whitespace as the length of the string (which is 12) fits the format specifier perfectly (A12). In the case where the value of n specified in the format specifier exceeds the length of the string, the output is padded with leading/trailing whitespace as required to make up to the given length n. Conversely, if the n in the format specifier is smaller than the size of the output then the output is truncated one way or another. This also applies to integers (and other data types).

module Solution
  ! See "Fixture" for actual Kumite content; we will explore modules in future Kumite ;)
end module Solution
Fundamentals

[GNU Fortran] Free-format Hello World Program

Background

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

Initially conceived in late 1953 and realized in 1957, Fortran (formerly known as FORTRAN, short for "Formula Transformation") is considered to be the oldest high-level programming language in existence. In its early days, FORTRAN was limited to scientific computing (such as calculating trajectories of missiles) and wasn't even Turing-complete due to lack of support for dynamic memory allocation which is a requirement for initializing arrays of varying size during runtime. Nevertheless, FORTRAN gained widespread acceptance in both the science and engineering communities and became the main programming language used in academia for decades. Most notably, the formulation of the first FORTRAN compiler paved the way for modern compiler theory and influenced one of the most successful and widespread programming languages of all time, C.

Modern Fortran standards and implementations (e.g. F90, F95, F2003, F2008, GNU Fortran) are believed to be Turing-complete. In particular, I have successfully demonstrated that GNU Fortran (an extension of the F95 standard) is indeed Turing-complete by implementing a full-fledged BF interpreter (which itself has been proven to be Turing-complete).

This Kumite

In this Kumite I will show you how to print out the text Hello World! (perhaps with a few leading/trailing whitespace) in GNU Fortran. In Fortran, a program is defined by using the program keyword, then giving the program a name (such as HelloWorld). At the end of the program, one should type end program followed by the program name (which is HelloWorld in this case). The contents of the program are placed between these two statements:

program HelloWorld
  ! Program code here.  Fortran comments start with an exclamation mark
end program HelloWorld

Note that Fortran is case-insensitve, i.e. HelloWorld is the same as helloWorld or helloworld. In fact, we can start with pROGRAM HelloWorld and end with END Program hELLOwORLD and the code will compile/execute just fine.

After we define our program, the first statement inside that program should (almost) always be implicit none. This tells the compiler that any and all variables declared by the programmer should be done so explicitly with a specified type instead of attempting to type-infer when no such type is provided. It is not an absolute necessity to add this statement but is added to 99% of programs as a best practice.

program HelloWorld
  implicit none
end program HelloWorld

Then, we use the print command to print out our text Hello World!. The print statement accepts a format specifier as its first "argument" (double-quoted here because print is not a Fortran procedure) which we'll learn about later but we'll set it to * in this Kumite which means "use the default settings". Any subsequent "arguments" passed to the print command are comma-separated. In our case, our only other "argument" is the string "Hello World!" so our program would appear as follows:

program HelloWorld
  implicit none
  print *, "Hello World!" ! Print the text "Hello World!" to the screen
  ! with the default formatting settings
end program HelloWorld

Note that:

  1. When the default settings * are used for the format specifier in the print command, Fortran is likely to pad the displayed output with one or more leading and/or trailing whitespace. We will learn how to get rid of them in the next Kumite.
  2. Fortran does not make a distinction between characters and strings - in fact, a string is declared as character type and an actual character is just a string with length 1. Due to this, both characters and strings can be wrapped in single quotes '' or double quotes "", e.g. 'Hello World!' is equally valid as "Hello World!" and "H" is considered equal to 'H'.
module Solution
  ! Please refer to the "Test Cases" for the actual Kumite code example - we'll learn
  ! about modules in future Kumite ;)
end module Solution
Testing
Frameworks

Basic idea for the new cw-2.py's timeout function to have an extra argument that prevents running the function right away.

pass
Code
Diff
  • import java.util.stream.IntStream;
    
    public class Area {
    
      public static long[] workOutArea(final long[] values){
        return values.length % 2 != 0? null: IntStream.range(0, values.length).filter(x -> x % 2 == 0).mapToLong(x -> values[x] * values[x+1]).toArray();
      }
    
    }
  • 1+import java.util.stream.IntStream;
    2+
    11 public class Area {
    22
    33 public static long[] workOutArea(final long[] values){
    4- if (values.length % 2 != 0) {
    5- return null; // This is ugly!
    6- } else {
    7- final long[] areas = new long[values.length / 2];
    8- for (int i = 0; i < values.length; i += 2) {
    9- areas[i / 2] = values[i] * values[i + 1];
    10- }
    11- return areas;
    12- }
    6+ return values.length % 2 != 0? null: IntStream.range(0, values.length).filter(x -> x % 2 == 0).mapToLong(x -> values[x] * values[x+1]).toArray();
    1313 }
    1414
    1515 }

Show optimization of code. Instead 4 passs throught array (max,min,count double time), use only one pass durring sorting.

Code
Diff
  • # Find stray number
    def find_stray(n)
      n.count(n.min) > n.count(n.max) ? n.max : n.min
    end
    
    # Find stray optimization
    def find_stray_o(n)
      n.sort!
      n[0] == n[1] ? n[-1] : n[0]
    end
    
    require "benchmark"
    
    array = (Array.new(1000_000,7) + [1]).shuffle
    
    Benchmark.bm(10) do |x|
      x.report("Find stray") { 10.times{ find_stray(array.clone.shuffle) }}
      x.report("Optimized") { 10.times{find_stray_o(array.clone.shuffle) }}
    end
  • 11 # Find stray number
    22 def find_stray(n)
    33 n.count(n.min) > n.count(n.max) ? n.max : n.min
    44 end
    5+
    6+# Find stray optimization
    7+def find_stray_o(n)
    8+ n.sort!
    9+ n[0] == n[1] ? n[-1] : n[0]
    10+end
    11+
    12+require "benchmark"
    13+
    14+array = (Array.new(1000_000,7) + [1]).shuffle
    15+
    16+Benchmark.bm(10) do |x|
    17+ x.report("Find stray") { 10.times{ find_stray(array.clone.shuffle) }}
    18+ x.report("Optimized") { 10.times{find_stray_o(array.clone.shuffle) }}
    19+end
Code
Diff
  • ++++++[>++++++<-]>[->+>++>+++>+++<<<<]>>.>-------.>..+++.<<<----.>-.>----.+.>+++.<+++++++.----.>------.
  • 1--[------->+<]>-.-[->+++++<]>++.+++++++..+++.[--->+<]>-----.+++[->++<]>+.-[------>+<]>.+.[--->+<]>----.---------.----.+++++++.
    1+++++++[>++++++<-]>[->+>++>+++>+++<<<<]>>.>-------.>..+++.<<<----.>-.>----.+.>+++.<+++++++.----.>------.

Missing what is it about. Just simplyfing things :)

Code
Diff
  • COLORS = set("RGB")
    def blend(c1, c2):
        colors = {c1, c2}
        return c1 if len(colors) == 1 else (COLORS - colors).pop()
    
    
    def preprocess(row):
        check = ""
        for r in row:
            if r != check:
                yield r
                check = r
    
    
    def triangle(row):
        row = list(preprocess(row))
        while len(row) > 1:
            for i,r in enumerate(row[:-1]):
                row[i] = blend(r, row[i+1])
            row.pop()
        return row[0]
    
  • 1-import re
    2-
    1+COLORS = set("RGB")
    33 def blend(c1, c2):
    4- if c1 == c2: return c1
    5- colors = c1 + c2
    6- if colors == "RB" or colors == "BR": return "G"
    7- if colors == "RG" or colors == "GR": return "B"
    8- if colors == "GB" or colors == "BG": return "R"
    3+ colors = {c1, c2}
    4+ return c1 if len(colors) == 1 else (COLORS - colors).pop()
    5+
    99
    1010 def preprocess(row):
    11- orig = row
    12- row,_ = re.subn('RR+', 'R', row)
    13- row,_ = re.subn('BB+', 'B', row)
    14- row,_ = re.subn('GG+', 'G', row)
    15- print(orig, row)
    16- return row
    8+ check = ""
    9+ for r in row:
    10+ if r != check:
    11+ yield r
    12+ check = r
    13+
    1717
    1818 def triangle(row):
    19- if len(row) == 1: return row
    20- row = preprocess(row)
    21- row = list(row)
    22- for j in range(len(row)-1,0,-1):
    23- for i in range(j):
    24- row[i] = blend(row[i], row[i+1])
    16+ row = list(preprocess(row))
    17+ while len(row) > 1:
    18+ for i,r in enumerate(row[:-1]):
    19+ row[i] = blend(r, row[i+1])
    20+ row.pop()
    2525 return row[0]

Looks familiar?

Expected: equal to [unsupported type]
Actual: [unsupported type]

No more!

Code
Diff
  • template <class... Args>
    bool alwaysTrue(Args&&...) {
      return true;
    }
    
    template <class T>
    T id(T&& x)  {
      return x;
    }
    
  • 11 template <class... Args>
    22 bool alwaysTrue(Args&&...) {
    33 return true;
    44 }
    5+
    6+template <class T>
    7+T id(T&& x) {
    8+ return x;
    9+}