Ad
Fundamentals
Games
Code
Diff
  • def riddle _;/#{?\\+??}/=~_ end
    • def riddle(word):
    • return word.rindex("?")
    • def riddle _;/#{?\\+??}/=~_ end
Code
Diff
  • treeHeight=$=_=>_?Math.max($(_.left),$(_.right))+1:0
    • treeHeight=$=_=>!_?0:Math.max($(_.left),$(_.right))+1
    • treeHeight=$=_=>_?Math.max($(_.left),$(_.right))+1:0

O(1) solution.
Now returns None for cases where it is impossible to meet constraints.

Code
Diff
  • def optimal_gifts(gifts: int, recipients: int) -> int:
        if recipients > gifts or gifts == 4 and recipients == 1:
            return None
        if gifts >= recipients * 8:
            return recipients
        if gifts == recipients * 8 - 4 or gifts == (recipients - 1) * 8:
            return recipients - 2
        return gifts // 8
    • def optimal_gifts(gifts: int, recipients: int) -> int:
    • kids = [1 for _ in range(gifts)]
    • gifts -= recipients
    • for i in range(recipients):
    • while (gifts > 0 and kids[i] < 8):
    • kids[i] += 1
    • gifts -= 1
    • eigths = sum([1 if kid == 8 else 0 for kid in kids])
    • if 4 in kids:
    • eigths -= 1
    • return eigths
    • if recipients > gifts or gifts == 4 and recipients == 1:
    • return None
    • if gifts >= recipients * 8:
    • return recipients
    • if gifts == recipients * 8 - 4 or gifts == (recipients - 1) * 8:
    • return recipients - 2
    • return gifts // 8
Regular Expressions
Declarative Programming
Advanced Language Features
Programming Paradigms
Fundamentals
Strings

How easy is it to master even-and-odd-ology from a strong foundation of useless program writing?

Code
Diff
  • import java.util.regex.Pattern;
    import java.math.BigInteger;
    
    class StringParity {
      public static boolean isEvenLength(String str) {
        return 
        //str.matches("(?s)(..)*") // (?s) enables DOTALL
        //str.chars().mapToObj(x->0<1).reduce(0<1,(x,_0)->!x)
        //str.length()<2?str.length()==0:isEvenLength(str.replaceAll("(?s)^..",""))
          str.length()<1||new BigInteger(Pattern.compile("(?s).").matcher(str).replaceAll(match->""+match.start())).testBit(0)
        ;
      }
    }
    • import java.util.regex.Pattern;
    • import java.math.BigInteger;
    • class StringParity {
    • public static boolean isEvenLength(String str) {
    • return str.replaceAll("(?s)..", "").isEmpty(); // (?s) enables DOTALL
    • return
    • //str.matches("(?s)(..)*") // (?s) enables DOTALL
    • //str.chars().mapToObj(x->0<1).reduce(0<1,(x,_0)->!x)
    • //str.length()<2?str.length()==0:isEvenLength(str.replaceAll("(?s)^..",""))
    • str.length()<1||new BigInteger(Pattern.compile("(?s).").matcher(str).replaceAll(match->""+match.start())).testBit(0)
    • ;
    • }
    • }
Lists
Data Structures
Code
Diff
  • def generate_binary_list(a, b, c, d):
        (a, b) = (a, b, a)[d&1:][:2]
        return [*((a, b)*(c-d>>1)), *(a,)[:c>d][:c-d&1]]
    • def generate_binary_list(a, b, c, d):
    • (a, b) = ((a, b), (b, a))[d&1]
    • return [*((a, b)*(c-d>>1)), *((), (a,))[c>d][:c-d&1]]
    • (a, b) = (a, b, a)[d&1:][:2]
    • return [*((a, b)*(c-d>>1)), *(a,)[:c>d][:c-d&1]]
Lists
Data Structures
Code
Diff
  • def generate_binary_list(a, b, c, d):
        (a, b) = ((a, b), (b, a))[d&1]
        return [*((a, b)*(c-d>>1)), *((), (a,))[c>d][:c-d&1]]
    • def generate_binay_list(first_number,second_number,elements_on_list,range_begins_at):
    • return [first_number if x%2==0 else second_number for x in range(range_begins_at, elements_on_list)]
    • def generate_binary_list(a, b, c, d):
    • (a, b) = ((a, b), (b, a))[d&1]
    • return [*((a, b)*(c-d>>1)), *((), (a,))[c>d][:c-d&1]]
Code
Diff
  • export function transform(source: any) {
        const target = {};
        Object.entries(source).forEach(function ([k, v]) {
            k.split("_").slice(0, -1).reduce(function (node: {[key: string]: any}, element: string) {
                return node[element] ??= {};
            }, target)[k.slice(k.lastIndexOf("_") + 1)] = v;
        });
        return target;
    }
    • export function transform(obj: any) {
    • const _RegEx = new RegExp(/_/);
    • const underscoredProp = Object.keys(obj).find(key =>
    • _RegEx.test(key)) || '';
    • const value = obj[underscoredProp];
    • const propertList = underscoredProp.split('_').reverse();
    • let toAdd = {};
    • propertList.map((prop,index) => {
    • toAdd = index==0 ?{[prop]:value} : {[prop]:toAdd}
    • })
    • return toAdd;
    • export function transform(source: any) {
    • const target = {};
    • Object.entries(source).forEach(function ([k, v]) {
    • k.split("_").slice(0, -1).reduce(function (node: {[key: string]: any}, element: string) {
    • return node[element] ??= {};
    • }, target)[k.slice(k.lastIndexOf("_") + 1)] = v;
    • });
    • return target;
    • }
Encoding
Algorithms
Logic

Nice profile picture.
Regex, modulo alternative solution.

Code
Diff
  • defmodule Rot13 do
      def encode(str) do
        Regex.replace(
          ~r/[A-Z]/i,
          str,
          fn x ->
            # from https://elixirforum.com/t/get-ascii-value-of-a-character/16619/3
            <<x::utf8>> = x
            if x < 97 do
              rem(x, 26) + 65
            else
              rem(x - 6, 26) + 97
            end
          end
        )
      end
    end
    • defmodule Rot13 do
    • def rotate({k, v}) do
    • cond do
    • v in ?A..?M ->
    • k + 13
    • v in ?N..?Z ->
    • k - 13
    • true ->
    • k
    • end
    • end
    • def encode(str) do
    • List.zip([
    • str
    • |> String.to_charlist(),
    • str
    • |> String.upcase()
    • |> String.to_charlist()
    • ])
    • |> Enum.map(&rotate/1)
    • |> List.to_string()
    • Regex.replace(
    • ~r/[A-Z]/i,
    • str,
    • fn x ->
    • # from https://elixirforum.com/t/get-ascii-value-of-a-character/16619/3
    • <<x::utf8>> = x
    • if x < 97 do
    • rem(x, 26) + 65
    • else
    • rem(x - 6, 26) + 97
    • end
    • end
    • )
    • end
    • end
Strings
Data Types
Fundamentals
Basic Language Features
Algorithms
Logic

Obligatory Python golf solution. Don't really like the final version I ended up on.
I don't know APL, but this problem almost felt designed for it. The shortest solution I could think of was {s r c←⍵⋄k←+/q←c⍷s⋄(({⍵'0'[' '=⍵]}¨(-k)↑⍕r)@(k↑⍒q))s}, I'm sure it can be greatly improved by somebody who knows what they're doing though. (index origin is 0 btw

Code
Diff
  • # exponential time - fast enough when first testcase is commented out
    f=lambda s,r,c:s and(f(z:=s[:-1],r,c)+s[-1],f(z,r//10,c)+str(r%10))[c==s[-1]]
    # linear recursive
    f=lambda s,r,c:s and(c!=s[-1]and f(s[:-1],r,c)+s[-1]or f(s[:-1],r//10,c)+str(r%10))
    
    f=lambda s,r,c:"".join(x==c and[str(r%10),r:=r//10][0]or x for x in s[::-1])[::-1]
    
    • using System;
    • using System.Linq;
    • using System.Collections.Generic;
    • # exponential time - fast enough when first testcase is commented out
    • f=lambda s,r,c:s and(f(z:=s[:-1],r,c)+s[-1],f(z,r//10,c)+str(r%10))[c==s[-1]]
    • # linear recursive
    • f=lambda s,r,c:s and(c!=s[-1]and f(s[:-1],r,c)+s[-1]or f(s[:-1],r//10,c)+str(r%10))
    • public class Test{
    • static void Main(){
    • Console.WriteLine(Replacer.sValueReplacer("0000##81#059671####=1811", 3, '#'));
    • }
    • }
    • public class Replacer{
    • public static string sValueReplacer(string source, int index, char char_to_replace)
    • {
    • string res = source;
    • try
    • {
    • if (!string.IsNullOrEmpty(char_to_replace.ToString()))
    • {
    • if (res.Contains(char_to_replace.ToString()))
    • {
    • // Get ALL Indexes position of character
    • var Indexes = GetIndexes(res, char_to_replace.ToString());
    • int max = GetMaxValue(Indexes.Count);
    • while (index >= max)
    • {
    • index -= max;
    • }
    • var new_value = index.ToString().PadLeft(Indexes.Count, '0');
    • for (int i = 0; i < Indexes.Count; i++)
    • {
    • res = res.Remove(Indexes[i], 1).Insert(Indexes[i], new_value[i].ToString());
    • }
    • }
    • }
    • }
    • catch (Exception)
    • {
    • res = source;
    • }
    • return res;
    • }
    • private static List<int> GetIndexes(string mainString, string toFind)
    • {
    • var Indexes = new List<int>();
    • for (int i = mainString.IndexOf(toFind); i > -1; i = mainString.IndexOf(toFind, i + 1))
    • {
    • // for loop end when i=-1 (line.counter not found)
    • Indexes.Add(i);
    • }
    • return Indexes;
    • }
    • private static int GetMaxValue(int numIndexes)
    • {
    • int max = 0;
    • for (int i = 0; i < numIndexes; i++)
    • {
    • if (i == 0)
    • max = 9;
    • else
    • max = max * 10 + 9;
    • }
    • return max;
    • }
    • }
    • f=lambda s,r,c:"".join(x==c and[str(r%10),r:=r//10][0]or x for x in s[::-1])[::-1]
Strings
Data Types
Fundamentals
Basic Language Features
Algorithms
Logic

Line 9 is maybe an anti-pattern, but it's the most sensible way to do it I could figure out.

Code
Diff
  • using System.Linq;
    
    public class Replacer
    {
      public static string sValueReplacer(string s, int z, char x)
      {
        var q = Enumerable.Range(0, s.Length).Where((i) => (s[i] == x));
        char[] r = s.ToCharArray();
        q.Zip(z.ToString().PadLeft(q.Count(), '0'), (i, e) => r[i] = e).Count();
        return new string(r);
      }
    }
    • using System;
    • using System.Linq;
    • using System.Collections.Generic;
    • public class Test{
    • static void Main(){
    • Console.WriteLine(Replacer.sValueReplacer("0000##81#059671####=1811", 3, '#'));
    • }
    • }
    • public class Replacer{
    • public static string sValueReplacer(string source, int index, char char_to_replace)
    • public class Replacer
    • {
    • public static string sValueReplacer(string s, int z, char x)
    • {
    • string res = source;
    • try
    • {
    • if (!string.IsNullOrEmpty(char_to_replace.ToString()))
    • {
    • if (res.Contains(char_to_replace.ToString()))
    • {
    • // Get ALL Indexes position of character
    • var Indexes = GetIndexes(res, char_to_replace.ToString());
    • int max = GetMaxValue(Indexes.Count);
    • while (index >= max)
    • {
    • index -= max;
    • }
    • var new_value = index.ToString().PadLeft(Indexes.Count, '0');
    • for (int i = 0; i < Indexes.Count; i++)
    • {
    • res = res.Remove(Indexes[i], 1).Insert(Indexes[i], new_value[i].ToString());
    • }
    • }
    • }
    • }
    • catch (Exception)
    • {
    • res = source;
    • }
    • return res;
    • var q = Enumerable.Range(0, s.Length).Where((i) => (s[i] == x));
    • char[] r = s.ToCharArray();
    • q.Zip(z.ToString().PadLeft(q.Count(), '0'), (i, e) => r[i] = e).Count();
    • return new string(r);
    • }
    • private static List<int> GetIndexes(string mainString, string toFind)
    • {
    • var Indexes = new List<int>();
    • for (int i = mainString.IndexOf(toFind); i > -1; i = mainString.IndexOf(toFind, i + 1))
    • {
    • // for loop end when i=-1 (line.counter not found)
    • Indexes.Add(i);
    • }
    • return Indexes;
    • }
    • private static int GetMaxValue(int numIndexes)
    • {
    • int max = 0;
    • for (int i = 0; i < numIndexes; i++)
    • {
    • if (i == 0)
    • max = 9;
    • else
    • max = max * 10 + 9;
    • }
    • return max;
    • }
    • }
Strings
Data Types
Fundamentals
Basic Language Features
Algorithms
Logic

Many wasted division operations, but this looks elegant.

Code
Diff
  • public class Replacer
    {
      public static string sValueReplacer(string source, int new_text, char old_char)
      {
        char[] intermediate = source.ToCharArray();
        for (int i = intermediate.Length - 1; i >= 0; --i)
        {
          if (intermediate[i] == old_char) 
          {
            intermediate[i] = (char) (0x30 | new_text % 10);
            new_text /= 10;
          }
        }
        return new string(intermediate);
      }
    }
    • using System;
    • using System.Linq;
    • using System.Collections.Generic;
    • public class Test{
    • static void Main(){
    • Console.WriteLine(Replacer.sValueReplacer("0000##81#059671####=1811", 3, '#'));
    • }
    • }
    • public class Replacer{
    • public static string sValueReplacer(string source, int index, char char_to_replace)
    • {
    • string res = source;
    • try
    • {
    • if (!string.IsNullOrEmpty(char_to_replace.ToString()))
    • {
    • if (res.Contains(char_to_replace.ToString()))
    • {
    • // Get ALL Indexes position of character
    • var Indexes = GetIndexes(res, char_to_replace.ToString());
    • int max = GetMaxValue(Indexes.Count);
    • while (index >= max)
    • {
    • index -= max;
    • }
    • var new_value = index.ToString().PadLeft(Indexes.Count, '0');
    • for (int i = 0; i < Indexes.Count; i++)
    • {
    • res = res.Remove(Indexes[i], 1).Insert(Indexes[i], new_value[i].ToString());
    • }
    • }
    • }
    • }
    • catch (Exception)
    • {
    • res = source;
    • }
    • return res;
    • }
    • private static List<int> GetIndexes(string mainString, string toFind)
    • public class Replacer
    • {
    • public static string sValueReplacer(string source, int new_text, char old_char)
    • {
    • var Indexes = new List<int>();
    • for (int i = mainString.IndexOf(toFind); i > -1; i = mainString.IndexOf(toFind, i + 1))
    • char[] intermediate = source.ToCharArray();
    • for (int i = intermediate.Length - 1; i >= 0; --i)
    • {
    • // for loop end when i=-1 (line.counter not found)
    • Indexes.Add(i);
    • }
    • return Indexes;
    • }
    • private static int GetMaxValue(int numIndexes)
    • {
    • int max = 0;
    • for (int i = 0; i < numIndexes; i++)
    • if (intermediate[i] == old_char)
    • {
    • if (i == 0)
    • max = 9;
    • else
    • max = max * 10 + 9;
    • intermediate[i] = (char) (0x30 | new_text % 10);
    • new_text /= 10;
    • }
    • return max;
    • }
    • return new string(intermediate);
    • }
    • }
Mathematics
Algorithms
Logic
Numbers
Data Types

Floyd's

Code
Diff
  • let is_happy h =
      let rec succ n = 
        match n with
        | 0 -> 0
        | _ -> let n' = n mod 10 in n' * n' + succ (n / 10)
      in
      let rec floyd's tortoise hare =
        match hare |> succ |> succ with
        | 1 -> true
        | hare' -> 
            let tortoise' = succ tortoise in 
            tortoise' <> hare' && floyd's tortoise' hare'
      in
      floyd's h h
    ;;
    • def is_happy(h: int) -> bool:
    • """Returns `True` if `h` is happy, `False` otherwise."""
    • seen = set()
    • while h > 1 and h not in seen:
    • seen.add(h)
    • tot = 0
    • while h > 0:
    • tot += pow(h % 10, 2)
    • h //= 10
    • h = tot
    • return h == 1
    • let is_happy h =
    • let rec succ n =
    • match n with
    • | 0 -> 0
    • | _ -> let n' = n mod 10 in n' * n' + succ (n / 10)
    • in
    • let rec floyd's tortoise hare =
    • match hare |> succ |> succ with
    • | 1 -> true
    • | hare' ->
    • let tortoise' = succ tortoise in
    • tortoise' <> hare' && floyd's tortoise' hare'
    • in
    • floyd's h h
    • ;;

Be careful! You were previously implicitly defining a global fact when you really should not have done that. A lot of these problems can be solved by including that "use strict"; at the start of a function, which is especially important when you're starting out.
Also, factorial of 0 is 1, and factorial of negatives is undefined. It's also nice to have proper indentation to make programs a little easier to read.

Code
Diff
  • function factorial (n) {
      "use strict";
      if (n < 0) {
        return NaN
      }
      let i, fact
      i = fact = 1
      while (i <= n) { 
        fact *= i
        i++
      }
      return fact
    }
    • function factorial (n) {
    • if (n <= 0) return 0
    • let i = fact = 1
    • "use strict";
    • if (n < 0) {
    • return NaN
    • }
    • let i, fact
    • i = fact = 1
    • while (i <= n) {
    • fact *= i
    • i++
    • fact *= i
    • i++
    • }
    • return fact
    • }
Mathematics
Algorithms
Logic
Numbers
Data Types

What's [Z?

Code
Diff
  • public class Kata {
      private static Object[] root = {null,
                                        new Object[][]{null, null, null, null, null, null, null, null, null, null, {new Boolean(true)}},
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        new Object[]{new Boolean(false)}
                                       };
      public static boolean isHappy(long current) {
        Boolean[] result = {false};
        outer:
        for (; ; ) {
          long next = 0;
          Object[] node = root;
          while (current > 0) {
            int remainder = (int) (current % 10);
            current /= 10;
            next += remainder * remainder;
            if (node[remainder] == null) {
              node = (Object[]) (node[remainder] = new Object[remainder == 0 ? 10 : 11]);
              while (current > 0) {
                remainder = (int) (current % 10);
                current /= 10;
                next += remainder * remainder;
                node = (Object[]) (node[remainder] = new Object[remainder == 0 ? 10 : 11]);
              }
              node[10] = result;
              current = next;
              continue outer;
            }
            node = (Object[]) node[remainder];
          }
          if (node[10] != null) {
            return result[0] = (Boolean) ((Object[]) node[10])[0];
          }
          node[10] = result;
          current = next;
        }
      }
    }
    
    • def is_happy(h: int) -> bool:
    • """Returns `True` if `h` is happy, `False` otherwise."""
    • seen = set()
    • while h > 1 and h not in seen:
    • seen.add(h)
    • tot = 0
    • while h > 0:
    • tot += pow(h % 10, 2)
    • h //= 10
    • h = tot
    • return h == 1
    • public class Kata {
    • private static Object[] root = {null,
    • new Object[][]{null, null, null, null, null, null, null, null, null, null, {new Boolean(true)}},
    • null,
    • null,
    • null,
    • null,
    • null,
    • null,
    • null,
    • null,
    • new Object[]{new Boolean(false)}
    • };
    • public static boolean isHappy(long current) {
    • Boolean[] result = {false};
    • outer:
    • for (; ; ) {
    • long next = 0;
    • Object[] node = root;
    • while (current > 0) {
    • int remainder = (int) (current % 10);
    • current /= 10;
    • next += remainder * remainder;
    • if (node[remainder] == null) {
    • node = (Object[]) (node[remainder] = new Object[remainder == 0 ? 10 : 11]);
    • while (current > 0) {
    • remainder = (int) (current % 10);
    • current /= 10;
    • next += remainder * remainder;
    • node = (Object[]) (node[remainder] = new Object[remainder == 0 ? 10 : 11]);
    • }
    • node[10] = result;
    • current = next;
    • continue outer;
    • }
    • node = (Object[]) node[remainder];
    • }
    • if (node[10] != null) {
    • return result[0] = (Boolean) ((Object[]) node[10])[0];
    • }
    • node[10] = result;
    • current = next;
    • }
    • }
    • }
Mathematics
Algorithms
Logic
Numbers
Data Types
Code
Diff
  • def is_happy(x, *, _trie=[False,10*[False]+[[True]]]+8*[False]+[[False]]):
        a = [False]
        while True:
            z = 0 # wasting some operations when x is in _trie. nobody cares though.
            t = _trie
            while x:
                r = x%10
                x //= 10
                z += r*r
                if t[r]:
                    t = t[r]
                else:
                    t[r] = (11-(not r))*[False]
                    t = t[r]
                    while x:
                        r = x%10
                        x //= 10
                        z += r*r
                        t[r] = (11-(not r))*[False]
                        t = t[r]
                    break
            else:
                if t[10]:
                    a[0] = t[10][0]
                    return a[0]
            t[10] = a
            x = z
    
    • class ref:
    • def __init__(self, data):
    • self.data = data
    • def is_happy(x, *, _trie=[False,10*[False]+[ref(True)]]+8*[False]+[ref(False)]):
    • a = ref(False)
    • def is_happy(x, *, _trie=[False,10*[False]+[[True]]]+8*[False]+[[False]]):
    • a = [False]
    • while True:
    • z = 0 # wasting some operations when x is in _trie. nobody cares though.
    • t = _trie
    • while x:
    • r = x%10
    • if not t[r]:
    • t[r] = (11-(not r))*[False]
    • t = t[r]
    • x //= 10
    • z += r**2
    • if t[-1]:
    • a.data = t[-1].data
    • return a.data
    • t[-1] = a
    • z += r*r
    • if t[r]:
    • t = t[r]
    • else:
    • t[r] = (11-(not r))*[False]
    • t = t[r]
    • while x:
    • r = x%10
    • x //= 10
    • z += r*r
    • t[r] = (11-(not r))*[False]
    • t = t[r]
    • break
    • else:
    • if t[10]:
    • a[0] = t[10][0]
    • return a[0]
    • t[10] = a
    • x = z
Loading more items...