Strings
split
Haskell Packages
Code
Diff
  • maestroSplit=(s,l=s.toLowerCase(),f=l[p="slice"](i=l.length/2))=>f[p](0,1).toUpperCase()+f[p](1)+l[p](0,i)
  • 1
    maestroSplit=(s,l=s.toLowerCase(),i=l.length/2,f=l.slice(i))=>f.charAt(0).toUpperCase()+f.slice(1)+l.slice(0,i)
    
    1+
    maestroSplit=(s,l=s.toLowerCase(),f=l[p="slice"](i=l.length/2))=>f[p](0,1).toUpperCase()+f[p](1)+l[p](0,i)
    
Dictionary
Data Structures
Code
Diff
  • f=lambda b:b[1:]and{b[0]:f(b[1:])}or b[0];nested_dic=lambda*a:[*map(f,zip(*a))]
    
  • 1
    def nested_dic(*args):
    
    2
        def nest(data):
    
    3
            nested = data[(i := len(data) - 1)]
    
    4
            while i:
    
    5
                nested = {data[(i := i - 1)] : nested}
    
    6
            return nested
    
    7
        return [*map(nest, zip(*args))]
    
    1+
    f=lambda b:b[1:]and{b[0]:f(b[1:])}or b[0];nested_dic=lambda*a:[*map(f,zip(*a))]
    

malloc does not have to initialize to 0. Although this is obviously a much more extreme showcase, you have to be very careful to not write stupid code when working with C. output[n] already being a NULL was lucky.

Code
Diff
  • int*fanis(char*r,int k){char*w=malloc(0);for(int i=0;r[i];w[i++]=k+r[i]);return w;}
  • 1
    #include <stdlib.h>
    
    2
    #include <string.h>
    
    3
    4
    char *fanis(const char *input, int value) {
    
    5
      size_t n = strlen(input);
    
    6
      char *output = (char *) malloc((n + 1) * sizeof(char));
    
    7
      for(size_t i=0; i<n; i++) {
    
    8
          output[i] = input[i] + value;
    
    9
      }
    
    10
      return output;
    
    11
    }
    
    1+
    int*fanis(char*r,int k){char*w=malloc(0);for(int i=0;r[i];w[i++]=k+r[i]);return w;}
    

I now have an yet another reason to dislike the assignment expression to add to the list.

Code
Diff
  • """
    length_longest_palindrome=\
    lambda s:max(k for k in range(len(s)+1)if any((J:=s[i:i+k])==J[::-1]for i in range(1+len(s)-k)))
    """
    length_longest_palindrome=\
    lambda s:(R:=range(1+len(s)),max(j-i for i in R for j in R if(J:=s[i:j])==J[::-1]))[1]
    
  • 1+
    """
    
    11
    length_longest_palindrome=\
    
    22
    lambda s:max(k for k in range(len(s)+1)if any((J:=s[i:i+k])==J[::-1]for i in range(1+len(s)-k)))
    
    4+
    """
    
    5+
    length_longest_palindrome=\
    
    6+
    lambda s:(R:=range(1+len(s)),max(j-i for i in R for j in R if(J:=s[i:j])==J[::-1]))[1]
    
Fundamentals

First time using Prolog.
Removed the testcase for0^0 because it is not well defined and 1000001^1001 because it times out.

Code
Diff
  • /*
    Try not to use this solution.
    pow(Base, Exponent, Result) :- Result is (Base ^ Exponent).
    */
    pow(Base, Exponent, Result) :- 
      Exponent1 is Exponent / 2, 
      pow(Base, Exponent1, SQRTResult),
      (0 is mod(Exponent, 2)) -> 
        Result is SQRTResult * SQRTResult;
        Result is Base * SQRTResult * SQRTResult.
    pow(_, 0, Result) :- Result is 1.
    
  • 1
    using System.Numerics;
    
    2
    3
    public class basic 
    
    4
    {
    
    5
    		public static BigInteger pow(long down, ulong up)
    
    6
    		{
    
    7
    			BigInteger output = 1;
    
    8
    			BigInteger cumulativeDown = down;
    
    9
    10
    			for(ulong bitChecker = 1; bitChecker > 0 && bitChecker <= up; bitChecker <<= 1)
    
    11
    			{
    
    12
    				if((bitChecker & up) != 0)
    
    13
    				{
    
    14
    					output *= cumulativeDown;
    
    15
    				}
    
    16
    17
    				cumulativeDown *= cumulativeDown;
    
    18
    			}
    
    19
    20
    			return output;
    
    21
    		}
    
    22
    }
    
    1+
    /*
    
    2+
    Try not to use this solution.
    
    3+
    pow(Base, Exponent, Result) :- Result is (Base ^ Exponent).
    
    4+
    */
    
    5+
    pow(Base, Exponent, Result) :- 
    
    6+
      Exponent1 is Exponent / 2, 
    
    7+
      pow(Base, Exponent1, SQRTResult),
    
    8+
      (0 is mod(Exponent, 2)) -> 
    
    9+
        Result is SQRTResult * SQRTResult;
    
    10+
        Result is Base * SQRTResult * SQRTResult.
    
    11+
    pow(_, 0, Result) :- Result is 1.
    

JSON.parse does not play well with undefined.

The things Python slice syntax makes me do sometimes...

Code
Diff
  • def length_longest_palindrome(s):
        for k in range(len(s), -1, -1):
            for i in range(1 + len(s) - k):
                if s[i : i + k] == s[i + k - 1 : i - 1 if i else None : -1]:
                    return k
    
  • 1
    def length_longest_palindrome(string):
    
    2
        n = len(string)
    
    3
        if n in [0,1]: return n
    
    4
        s = range(n)
    
    5
        sol = [string[i:j+1] for i in s[:-1] for j in s[1:] if string[i:j+1] == string[i:j+1][::-1]]
    
    6
        if len(sol) == 0: return 0
    
    7
        return max([len(i) for i in sol])
    
    1+
    def length_longest_palindrome(s):
    
    2+
        for k in range(len(s), -1, -1):
    
    3+
            for i in range(1 + len(s) - k):
    
    4+
                if s[i : i + k] == s[i + k - 1 : i - 1 if i else None : -1]:
    
    5+
                    return k
    
Code
Diff
  • (ns reverseint.core)
    
    (defn reverse-int' [acc x] 
      (let [quot-rem (.divideAndRemainder
                      x
                      java.math.BigInteger/TEN)]
        (if (= (nth quot-rem 0) 0) (+ (* 10 acc) (nth quot-rem 1)) 
          (reverse-int' (+ (* 10 acc) (nth quot-rem 1)) (nth quot-rem 0)))))
    
    (defn reverse-int [n] 
      (let [quot-rem (.divideAndRemainder 
                      (biginteger n) 
                      java.math.BigInteger/TEN)]
        (reverse-int' (nth quot-rem 1) (nth quot-rem 0))))
    
    
  • 1
    public class Algorithms {
    
    2
      public static int reverseInt(int n) {
    
    3
        int reversed = 0;
    
    4
        
    
    5
        while(n != 0){
    
    6
          reversed = reversed * 10 + (n % 10);
    
    7
          n /= 10;
    
    8
        }
    
    9
        
    
    10
        return reversed;
    
    11
      }
    
    12
    }
    
    1+
    (ns reverseint.core)
    
    2+
    3+
    (defn reverse-int' [acc x] 
    
    4+
      (let [quot-rem (.divideAndRemainder
    
    5+
                      x
    
    6+
                      java.math.BigInteger/TEN)]
    
    7+
        (if (= (nth quot-rem 0) 0) (+ (* 10 acc) (nth quot-rem 1)) 
    
    8+
          (reverse-int' (+ (* 10 acc) (nth quot-rem 1)) (nth quot-rem 0)))))
    
    9+
    10+
    (defn reverse-int [n] 
    
    11+
      (let [quot-rem (.divideAndRemainder 
    
    12+
                      (biginteger n) 
    
    13+
                      java.math.BigInteger/TEN)]
    
    14+
        (reverse-int' (nth quot-rem 1) (nth quot-rem 0))))
    
    15+

Can't get confused by an interface you're not using.

Code
Diff
  • # won't be needing this anymore
    # from collections import deque
    
    def minNumberOfCoinsForChange(n, ks):
        if n == 0:
            return 0
        ks = tuple(denomination_pruner(ks))
        kk = max(ks)
        dp = min(n + 1, kk) * [float("inf")]
        dp[0] = 0
        for i in range(1, len(dp)):
            print(dp)
            ck = float("inf")
            for k in ks:
                print(k, i)
                if k <= i:
                    ck = min(ck, 1 + dp[(i - k) % len(dp)])
            dp[i % len(dp)] = ck
        dp[0] = 1
        if n <= kk:
            return dp[n % kk]
        for i in range(kk + 1, n + 1):
            print(dp)
            ck = float("inf")
            for k in ks:
                ck = min(ck, 1 + dp[(i - k) % kk])
            dp[i % kk] = ck
        return -1 if dp[i % kk] == float("inf") else dp[i % kk]
    
    def denomination_pruner(denominations):
        seen = set()
        for coin in denominations:
            # theoretically negative coins might be important to consider
            # f(9, [1, 10, -1]) => 2
            # not going to worry about them here though
            if coin > 0 and coin not in seen:
                seen.add(coin)
                yield coin
    
  • 1
    from collections import deque
    
    1+
    # won't be needing this anymore
    
    2+
    # from collections import deque
    
    22
    33
    def minNumberOfCoinsForChange(n, ks):
    
    44
        if n == 0:
    
    55
            return 0
    
    66
        ks = tuple(denomination_pruner(ks))
    
    77
        kk = max(ks)
    
    8
        dp = deque((0,), maxlen=kk)
    
    9
        for i in range(1, min(n + 1, kk)):
    
    9+
        dp = min(n + 1, kk) * [float("inf")]
    
    10+
        dp[0] = 0
    
    11+
        for i in range(1, len(dp)):
    
    12+
            print(dp)
    
    1010
            ck = float("inf")
    
    1111
            for k in ks:
    
    15+
                print(k, i)
    
    1212
                if k <= i:
    
    13
                    ck = min(ck, 1 + dp[-k])
    
    14
            dp.append(ck)
    
    15
        if n < kk:
    
    16
            return dp[-1]
    
    17
        dp.popleft()
    
    18
        dp.append(1)
    
    17+
                    ck = min(ck, 1 + dp[(i - k) % len(dp)])
    
    18+
            dp[i % len(dp)] = ck
    
    19+
        dp[0] = 1
    
    20+
        if n <= kk:
    
    21+
            return dp[n % kk]
    
    1919
        for i in range(kk + 1, n + 1):
    
    23+
            print(dp)
    
    2020
            ck = float("inf")
    
    2121
            for k in ks:
    
    22
                ck = min(ck, 1 + dp[-k])
    
    23
            dp.popleft()
    
    24
            dp.append(ck)
    
    25
        return -1 if dp[-1] == float("inf") else dp[-1]
    
    26+
                ck = min(ck, 1 + dp[(i - k) % kk])
    
    27+
            dp[i % kk] = ck
    
    28+
        return -1 if dp[i % kk] == float("inf") else dp[i % kk]
    
    2626
    2727
    def denomination_pruner(denominations):
    
    2828
        seen = set()
    
    2929
        for coin in denominations:
    
    3030
            # theoretically negative coins might be important to consider
    
    3131
            # f(9, [1, 10, -1]) => 2
    
    3232
            # not going to worry about them here though
    
    3333
            if coin > 0 and coin not in seen:
    
    3434
                seen.add(coin)
    
    3535
                yield coin
    

I love how easy it is to remember the deque interfaces of Python, Java, and C++.

O(min(n, max(ks))) auxiliary space.

Code
Diff
  • from collections import deque
    
    def minNumberOfCoinsForChange(n, ks):
        if n == 0:
            return 0
        ks = tuple(denomination_pruner(ks))
        kk = max(ks)
        dp = deque((0,), maxlen=kk)
        for i in range(1, min(n + 1, kk)):
            ck = float("inf")
            for k in ks:
                if k <= i:
                    ck = min(ck, 1 + dp[-k])
            dp.append(ck)
        if n < kk:
            return dp[-1]
        dp.popleft()
        dp.append(1)
        for i in range(kk + 1, n + 1):
            ck = float("inf")
            for k in ks:
                ck = min(ck, 1 + dp[-k])
            dp.popleft()
            dp.append(ck)
        return -1 if dp[-1] == float("inf") else dp[-1]
    
    def denomination_pruner(denominations):
        seen = set()
        for coin in denominations:
            # theoretically negative coins might be important to consider
            # f(9, [1, 10, -1]) => 2
            # not going to worry about them here though
            if coin > 0 and coin not in seen:
                seen.add(coin)
                yield coin
    
  • 1
    def minNumberOfCoinsForChange(n, denoms):
    
    2
    	numOfCoins = [float('inf') for amount in range(n+1)]  
    
    3
    	numOfCoins[0] = 0 
    
    4
    	for denom in denoms:
    
    5
    		for amount in range(len(numOfCoins)):
    
    6
    			if denom <= amount:
    
    7
    				numOfCoins[amount] = min(numOfCoins[amount],1+numOfCoins[amount - denom])
    
    8
    	return numOfCoins[n] if numOfCoins[n] != float('inf') else -1
    
    1+
    from collections import deque
    
    2+
    3+
    def minNumberOfCoinsForChange(n, ks):
    
    4+
        if n == 0:
    
    5+
            return 0
    
    6+
        ks = tuple(denomination_pruner(ks))
    
    7+
        kk = max(ks)
    
    8+
        dp = deque((0,), maxlen=kk)
    
    9+
        for i in range(1, min(n + 1, kk)):
    
    10+
            ck = float("inf")
    
    11+
            for k in ks:
    
    12+
                if k <= i:
    
    13+
                    ck = min(ck, 1 + dp[-k])
    
    14+
            dp.append(ck)
    
    15+
        if n < kk:
    
    16+
            return dp[-1]
    
    17+
        dp.popleft()
    
    18+
        dp.append(1)
    
    19+
        for i in range(kk + 1, n + 1):
    
    20+
            ck = float("inf")
    
    21+
            for k in ks:
    
    22+
                ck = min(ck, 1 + dp[-k])
    
    23+
            dp.popleft()
    
    24+
            dp.append(ck)
    
    25+
        return -1 if dp[-1] == float("inf") else dp[-1]
    
    26+
    27+
    def denomination_pruner(denominations):
    
    28+
        seen = set()
    
    29+
        for coin in denominations:
    
    30+
            # theoretically negative coins might be important to consider
    
    31+
            # f(9, [1, 10, -1]) => 2
    
    32+
            # not going to worry about them here though
    
    33+
            if coin > 0 and coin not in seen:
    
    34+
                seen.add(coin)
    
    35+
                yield coin
    
Code
Diff
  • let ReverseInt x =
      let rec ReverseInt'(acc, x) =
        match System.Math.DivRem(x, 10) with
        | (0, rem) -> 10 * acc + rem
        | (quot, rem) -> ReverseInt'(10 * acc + rem, quot)
      match System.Math.DivRem(x, 10) with
      | (0, rem) -> rem
      | (quot, rem) -> ReverseInt'(rem, quot)
    ;;
      
  • 1
    public class Algorithms {
    
    2
      public static int reverseInt(int n) {
    
    3
        int reversed = 0;
    
    4
        
    
    5
        while(n != 0){
    
    6
          reversed = reversed * 10 + (n % 10);
    
    7
          n /= 10;
    
    8
        }
    
    9
        
    
    10
        return reversed;
    
    11
      }
    
    12
    }
    
    1+
    let ReverseInt x =
    
    2+
      let rec ReverseInt'(acc, x) =
    
    3+
        match System.Math.DivRem(x, 10) with
    
    4+
        | (0, rem) -> 10 * acc + rem
    
    5+
        | (quot, rem) -> ReverseInt'(10 * acc + rem, quot)
    
    6+
      match System.Math.DivRem(x, 10) with
    
    7+
      | (0, rem) -> rem
    
    8+
      | (quot, rem) -> ReverseInt'(rem, quot)
    
    9+
    ;;
    
    10+
      
    

The same thing as my C solution, just more Pythonic because it is written in Python.

Code
Diff
  • def reverse_int(int_reverse: int) -> int:
        div_mod: (int, int) = divmod(int_reverse, 10)
        reverse_int: int = div_mod[1]
        while div_mod[0]:
            div_mod = divmod(div_mod[0], 10)
            reverse_int *= 10
            reverse_int += div_mod[1]
        return reverse_int
  • 1
    public class Algorithms {
    
    2
      public static int reverseInt(int n) {
    
    3
        int reversed = 0;
    
    4
        
    
    5
        while(n != 0){
    
    6
          reversed = reversed * 10 + (n % 10);
    
    7
          n /= 10;
    
    8
        }
    
    9
        
    
    10
        return reversed;
    
    11
      }
    
    12
    }
    
    1+
    def reverse_int(int_reverse: int) -> int:
    
    2+
        div_mod: (int, int) = divmod(int_reverse, 10)
    
    3+
        reverse_int: int = div_mod[1]
    
    4+
        while div_mod[0]:
    
    5+
            div_mod = divmod(div_mod[0], 10)
    
    6+
            reverse_int *= 10
    
    7+
            reverse_int += div_mod[1]
    
    8+
        return reverse_int
    

(reverse_int int)int_reverse int

Code
Diff
  • #include <stdlib.h>
    
    int reverse_int(int int_reverse) {
        div_t div_x = div(int_reverse, 10);
        int reverse_int = div_x.rem;
        while (div_x.quot) {
            div_x = div(div_x.quot, 10);
            reverse_int *= 10;
            reverse_int += div_x.rem;
        }
        return reverse_int;
    }
  • 1
    public class Algorithms {
    
    2
      public static int reverseInt(int n) {
    
    3
        int reversed = 0;
    
    4
        
    
    5
        while(n != 0){
    
    6
          reversed = reversed * 10 + (n % 10);
    
    7
          n /= 10;
    
    1+
    #include <stdlib.h>
    
    2+
    3+
    int reverse_int(int int_reverse) {
    
    4+
        div_t div_x = div(int_reverse, 10);
    
    5+
        int reverse_int = div_x.rem;
    
    6+
        while (div_x.quot) {
    
    7+
            div_x = div(div_x.quot, 10);
    
    8+
            reverse_int *= 10;
    
    9+
            reverse_int += div_x.rem;
    
    88
        }
    
    9
        
    
    10
        return reversed;
    
    11
      }
    
    11+
        return reverse_int;
    
    1212
    }
    

Extra reversed because of how backwards of a language Forth is.

Code
Diff
  • : REVERSE-INT 0 BEGIN SWAP DUP WHILE 10 /MOD SWAP ROT 10 * + REPEAT DROP ;
  • 1
    public class Algorithms {
    
    2
      public static int reverseInt(int n) {
    
    3
        int reversed = 0;
    
    4
        
    
    5
        while(n != 0){
    
    6
          reversed = reversed * 10 + (n % 10);
    
    7
          n /= 10;
    
    8
        }
    
    9
        
    
    10
        return reversed;
    
    11
      }
    
    12
    }
    
    1+
    : REVERSE-INT 0 BEGIN SWAP DUP WHILE 10 /MOD SWAP ROT 10 * + REPEAT DROP ;
    
Games
Arrays
Algorithms

Same thing, just turned it into Haskell.

Code
Diff
  • module Platforms where
    
    platforms :: [Integer] -> Integer
    platforms [] = 0
    platforms (_:[]) = 0
    platforms (x:xs) = platforms' (abs . (x -), xs) where
      platforms' :: (Integer -> Integer, [Integer]) -> Integer
      platforms' (acc, x:[]) = acc x
      platforms' (acc, x:xs) = platforms' (((+) (acc x)) . abs . (x -), xs)
    
  • 1
    (* *)
    
    2
    let (<<) f g x = f @@ g x ;;
    
    1+
    module Platforms where
    
    33
    4
    let platforms xs =
    
    5
      let rec platforms' (acc, xs) = 
    
    6
        match xs with
    
    7
        | x::[] -> acc x
    
    8
        | x::xs'-> platforms' ((+) @@ acc x << abs << (-) x, xs')
    
    3+
    platforms :: [Integer] -> Integer
    
    4+
    platforms [] = 0
    
    5+
    platforms (_:[]) = 0
    
    6+
    platforms (x:xs) = platforms' (abs . (x -), xs) where
    
    7+
      platforms' :: (Integer -> Integer, [Integer]) -> Integer
    
    8+
      platforms' (acc, x:[]) = acc x
    
    9+
      platforms' (acc, x:xs) = platforms' (((+) (acc x)) . abs . (x -), xs)
    
Loading more items...