Fundamentals
Games
Code
Diff
  • def riddle(word):
        return word.rindex("?")
  • 11
    def riddle(word):
    
    2
        return len(word) - 1
    
    2+
        return word.rindex("?")
    

A bit faster:

Rehearsal ------------------------------------
   3.207147   0.008056   3.215203 (  3.215506)
   0.760552   0.000013   0.760565 (  0.760609)
   1.287006   0.000000   1.287006 (  1.287230)
   0.466994   0.000000   0.466994 (  0.467006)
   0.105617   0.000005   0.105622 (  0.105649)
   0.065559   0.000017   0.065576 (  0.065609)
--------------------------- total: 5.900966sec

       user     system      total        real
   1.493939   0.000000   1.493939 (  1.494093) # Eileenandrea
   0.785715   0.000000   0.785715 (  0.785772) # Eileenandrea, a==b check
   1.238191   0.000018   1.238209 (  1.238325) # 深紅心
   0.484410   0.000000   0.484410 (  0.484429) # 深紅心, a==b check
   0.076156   0.000000   0.076156 (  0.076182) # pawptart
   0.065472   0.000000   0.065472 (  0.065472) # pawptart (refactored)
Code
Diff
  • def one_away(a, b)
      return true if a == b
      
      case a.size - b.size
      when -1 then compare(a, b)
      when 0 then compare(b, a, 1)
      when 1 then compare(b, a)
      else false
      end
    end
    
    def compare(a, b, o = 0)  
      (0..b.size).each do |i|
        return a[0, i] == b[0, i] && a[i + o, a.size] == b[i + 1, b.size] if a[i] != b[i]
      end
      
      true
    end
  • 11
    def one_away(a, b)
    
    22
      return true if a == b
    
    33
      
    
    44
      case a.size - b.size
    
    5
      when -1..1 then compare(a, b)
    
    5+
      when -1 then compare(a, b)
    
    6+
      when 0 then compare(b, a, 1)
    
    7+
      when 1 then compare(b, a)
    
    66
      else false
    
    77
      end
    
    88
    end
    
    99
    10
    def compare(a, b)
    
    11
      c     = 0
    
    12
      i     = 0
    
    13
      x, y  = [a, b].sort_by(&:size)  # Don't have to do this, but it makes the code easier
    
    14
      x_off = x.size < y.size ? 0 : 1 # Used in case the string sizes are mismatched
    
    15
      
    
    16
      # Find the first difference
    
    17
      # Use the index to split the strings into substrings
    
    18
      # Compare the substrings
    
    19
      while i < y.size
    
    20
        if x[i] != y[i]
    
    21
          return x[0, i] == y[0, i] && x[i + x_off, x.size] == y[i + 1, y.size]
    
    22
        end
    
    23
        i += 1                        
    
    12+
    def compare(a, b, o = 0)  
    
    13+
      (0..b.size).each do |i|
    
    14+
        return a[0, i] == b[0, i] && a[i + o, a.size] == b[i + 1, b.size] if a[i] != b[i]
    
    2424
      end
    
    16+
      
    
    17+
      true
    
    2525
    end
    

Added some benchmarks, improved some existing solutions

Substring comparison is orders of magnitude faster than iterating over each letter of the string in Ruby.

== drops down into C to perform the comparison instead of relying on Ruby's relatively slow iteration.

Sample benchmark:

Rehearsal ------------------------------------
   2.953821   0.028788   2.982609 (  2.983072) # Eileenandrea
   1.069810   0.000000   1.069810 (  1.069971) # 深紅心
   0.414153   0.000074   0.414227 (  0.414269) # 深紅心 (modified)
   0.087044   0.003973   0.091017 (  0.091033) # pawptart
--------------------------- total: 4.557663sec

       user     system      total        real
   1.521839   0.000000   1.521839 (  1.522046)
   1.044602   0.000028   1.044630 (  1.044804)
   0.407469   0.000000   0.407469 (  0.407515)
   0.065739   0.000000   0.065739 (  0.065745)
Code
Diff
  • def one_away(a, b)
      return true if a == b
      
      case a.size - b.size
      when -1..1 then compare(a, b)
      else false
      end
    end
    
    def compare(a, b)
      c     = 0
      i     = 0
      x, y  = [a, b].sort_by(&:size)  # Don't have to do this, but it makes the code easier
      x_off = x.size < y.size ? 0 : 1 # Used in case the string sizes are mismatched
      
      # Find the first difference
      # Use the index to split the strings into substrings
      # Compare the substrings
      while i < y.size
        if x[i] != y[i]
          return x[0, i] == y[0, i] && x[i + x_off, x.size] == y[i + 1, y.size]
        end
        i += 1                        
      end
    end
  • 1
    def one_away(a,b)
    
    2
      case a.length - b.length
    
    3
      when 0
    
    4
        i = 0
    
    5
        while i < a.length && a[i] == b[i]
    
    6
          i += 1
    
    7
        end
    
    8
        i += 1
    
    9
        # probably slower than just using substring equality,
    
    10
        while i < a.length && a[i] == b[i]
    
    11
          i += 1
    
    12
        end
    
    13
        # but the allure of pretty complexities is too much
    
    14
        return i >= a.length
    
    15
      when 1
    
    16
        return helper(a,b)
    
    17
      when -1
    
    18
        return helper(b, a)
    
    19
      else
    
    20
        return false
    
    1+
    def one_away(a, b)
    
    2+
      return true if a == b
    
    3+
      
    
    4+
      case a.size - b.size
    
    5+
      when -1..1 then compare(a, b)
    
    6+
      else false
    
    2121
      end
    
    2222
    end
    
    2323
    24
    def helper(longer, shorter)
    
    25
      i = 0
    
    26
      while i < shorter.length && longer[i] == shorter[i]
    
    27
        i += 1
    
    28
      end
    
    29
      while i < shorter.length && longer[i + 1] == shorter[i]
    
    30
        i += 1
    
    10+
    def compare(a, b)
    
    11+
      c     = 0
    
    12+
      i     = 0
    
    13+
      x, y  = [a, b].sort_by(&:size)  # Don't have to do this, but it makes the code easier
    
    14+
      x_off = x.size < y.size ? 0 : 1 # Used in case the string sizes are mismatched
    
    15+
      
    
    16+
      # Find the first difference
    
    17+
      # Use the index to split the strings into substrings
    
    18+
      # Compare the substrings
    
    19+
      while i < y.size
    
    20+
        if x[i] != y[i]
    
    21+
          return x[0, i] == y[0, i] && x[i + x_off, x.size] == y[i + 1, y.size]
    
    22+
        end
    
    23+
        i += 1                        
    
    3131
      end
    
    32
      return i >= shorter.length
    
    3333
    end
    
Recursion
Algorithms
Computability Theory
Theoretical Computer Science
Arrays
Methods
Functions
Object-oriented Programming
Control Flow
Basic Language Features
Fundamentals
Classes
Code
Diff
  • class Array
      def flip
        reverse.map{|e|e.flip rescue e}
      end
    end
  • 1
    class Array # Opens up the Array class for method creation
    
    1+
    class Array
    
    22
      def flip
    
    3
        self.reverse.map{|e| e.is_a?(Array) ? e.flip : e}
    
    3+
        reverse.map{|e|e.flip rescue e}
    
    44
      end
    
    55
    end
    
Code
Diff
  • from functools import reduce
    
    def prod(numbers):
        return reduce(lambda x, y: x * y, numbers or [0], 1)
        
  • 1+
    from functools import reduce
    
    2+
    11
    def prod(numbers):
    
    2
        return numbers[0] * (prod(numbers[1:]) or 1) if numbers else 0
    
    4+
        return reduce(lambda x, y: x * y, numbers or [0], 1)
    
    5+
        
    
Fundamentals
Puzzles
Games
Code
Diff
  • # It doesn't get any simpler, but we can definitely make it harder!
    
    def minimal_square(a, b):
        # This solution abuses the fact that we can multiply by True/False:
        # For instance, 1 * True = 1 and 1 * False = 0
        #
        # A step further:
        # (a * (a > b ) + b * ( b >= a )) is equivalent to max(a, b)
        #
        # And:
        # (a * ( a < b ) + b * ( b <= a )) is equivalent to min(a, b)
        #
        # Putting it all together, the following is equivalent to:
        # max(min(a,b)*2,max(a,b))**2
    
        side = (((a*(a<b)+b*(b<=a))*2)*(((a*(a<b)+b*(b<=a))*2)>(a*(a>b)+b*(b>=a))))+\
            ((a*(a>b)+b*(b>=a))*(((a*(a<b)+b*(b<=a))*2)<=(a*(a>b)+b*(b>=a))))
        return side**2
    
  • 1+
    # It doesn't get any simpler, but we can definitely make it harder!
    
    2+
    11
    def minimal_square(a, b):
    
    2
        return max(min(a, b)*2, max(a, b))**2
    
    3
    # This is my first kumite (∩_∩)
    
    4
    # I think this is the best solution there's not much to improve on
    
    5
    # The problem isn't too hard
    
    4+
        # This solution abuses the fact that we can multiply by True/False:
    
    5+
        # For instance, 1 * True = 1 and 1 * False = 0
    
    6+
        #
    
    7+
        # A step further:
    
    8+
        # (a * (a > b ) + b * ( b >= a )) is equivalent to max(a, b)
    
    9+
        #
    
    10+
        # And:
    
    11+
        # (a * ( a < b ) + b * ( b <= a )) is equivalent to min(a, b)
    
    12+
        #
    
    13+
        # Putting it all together, the following is equivalent to:
    
    14+
        # max(min(a,b)*2,max(a,b))**2
    
    15+
    16+
        side = (((a*(a<b)+b*(b<=a))*2)*(((a*(a<b)+b*(b<=a))*2)>(a*(a>b)+b*(b>=a))))+\
    
    17+
            ((a*(a>b)+b*(b>=a))*(((a*(a<b)+b*(b<=a))*2)<=(a*(a>b)+b*(b>=a))))
    
    18+
        return side**2
    
Mathematics
Algorithms
Numbers
Code
Diff
  • def average(g)
      g==[] ? nil : g.sum.to_f/g.size
    end 
  • 11
    def average(g)
    
    2
      g.size < 1 ? nil : g.reduce(:+).to_f / g.size
    
    2+
      g==[] ? nil : g.sum.to_f/g.size
    
    33
    end 
    

Add in non-arithmetic operators

Code
Diff
  • def calculator(a, operator, b):
        return "Not a valid operation" if operator not in ['+', '-', '/', '*'] else eval(str(a) + operator + str(b))
    
  • 11
    def calculator(a, operator, b):
    
    2
        return eval(str(a) + operator + str(b))
    
    2+
        return "Not a valid operation" if operator not in ['+', '-', '/', '*'] else eval(str(a) + operator + str(b))
    
Code
Diff
  • def calculator(a, operator, b):
        return eval(str(a) + operator + str(b))
    
  • 11
    def calculator(a, operator, b):
    
    2
        operations = {"+": lambda x, y: x + y, "-": lambda x, y: x - y,
    
    3
        "*": lambda x, y: x * y, "/": lambda x, y: x / y}
    
    4
        return operations[operator](a, b)
    
    2+
        return eval(str(a) + operator + str(b))
    
Code
Diff
  • def high_and_low(str_in)
        str_in.split.map(&:to_i).minmax.reverse.join(' ')
    end
  • 1
    def high_and_low(str_in):
    
    2
        arr = sorted(int(n) for n in str_in.split(" "))
    
    3
        return "{} {}".format(arr[-1], arr[0])
    
    1+
    def high_and_low(str_in)
    
    2+
        str_in.split.map(&:to_i).minmax.reverse.join(' ')
    
    3+
    end
    
Numbers
Algorithms

One character less

Code
Diff
  • def isOdd(n):
        return str(n % 2 > 0)
  • 11
    def isOdd(n):
    
    2
        return str(n % 2 != 0)
    
    2+
        return str(n % 2 > 0)
    
Numbers
Algorithms
Code
Diff
  • def isOdd(n):
        return str(n % 2 != 0)
  • 1
    def isOdd(n) :
    
    2
        return "False" if n % 2 == 0 else "True"
    
    1+
    def isOdd(n):
    
    2+
        return str(n % 2 != 0)
    
Code
Diff
  • function findBiggestSubArray(arr) {
      let maxSum = null;
      let startIndex, lastIndex = 0;
      
      for (let i = 0; i < arr.length; i++) {
        let sequence = [];
        for (let j = i; j < arr.length; j++) {
          sequence.push(arr[j]);
          let sum = sequence.reduce((c,a)=>c+a);
          if (maxSum == null || sum > maxSum) {
            startIndex = i;
            lastIndex = j;
            maxSum = sum;
          }
        }
      }
      
      return [maxSum, startIndex, lastIndex];
    }
  • 11
    function findBiggestSubArray(arr) {
    
    2
      return []
    
    2+
      let maxSum = null;
    
    3+
      let startIndex, lastIndex = 0;
    
    4+
      
    
    5+
      for (let i = 0; i < arr.length; i++) {
    
    6+
        let sequence = [];
    
    7+
        for (let j = i; j < arr.length; j++) {
    
    8+
          sequence.push(arr[j]);
    
    9+
          let sum = sequence.reduce((c,a)=>c+a);
    
    10+
          if (maxSum == null || sum > maxSum) {
    
    11+
            startIndex = i;
    
    12+
            lastIndex = j;
    
    13+
            maxSum = sum;
    
    14+
          }
    
    15+
        }
    
    16+
      }
    
    17+
      
    
    18+
      return [maxSum, startIndex, lastIndex];
    
    33
    }
    

Tiny, tiny performance bump under certain circumstances.

Code
Diff
  • require 'benchmark'
    
    strings = []
    
    10000.times do
      string = Array.new(rand(500..1000)) do rand(10) end.join
      strings << string
    end
    
    def solution1(s) s.chars.sum(&:to_i) end
    def solution2(s) s.sum - s.size * 48 end
    def solution3(s) s.sum do |x| x - 48 end end
    def solution4(s) s.sum do |x| x - '0' end end
    def solution5(s) s.sum{|x|x-'0'} end
    
    Benchmark.bmbm do |x|
      x.report do strings.each(&method(:solution1)) end # farekkusu
      x.report do strings.each(&method(:solution2)) end # ttakuru88
      x.report do strings.each(&method(:solution3)) end # steffan153 (test code author)
      x.report do strings.each(&method(:solution4)) end # rowcased
      x.report do strings.each(&method(:solution5)) end # pawptart
    end
    
    puts "<PASSED::>" # prevent from saying failed tests
  • 88
    end
    
    99
    1010
    def solution1(s) s.chars.sum(&:to_i) end
    
    1111
    def solution2(s) s.sum - s.size * 48 end
    
    1212
    def solution3(s) s.sum do |x| x - 48 end end
    
    1313
    def solution4(s) s.sum do |x| x - '0' end end
    
    14+
    def solution5(s) s.sum{|x|x-'0'} end
    
    1414
    1515
    Benchmark.bmbm do |x|
    
    1616
      x.report do strings.each(&method(:solution1)) end # farekkusu
    
    1717
      x.report do strings.each(&method(:solution2)) end # ttakuru88
    
    1818
      x.report do strings.each(&method(:solution3)) end # steffan153 (test code author)
    
    1919
      x.report do strings.each(&method(:solution4)) end # rowcased
    
    21+
      x.report do strings.each(&method(:solution5)) end # pawptart
    
    2020
    end
    
    2121
    2222
    puts "<PASSED::>" # prevent from saying failed tests
    

I made it pretty

Code
Diff
  • def hello_world
      print(HELLO_WORLD)
    end
  • 1
    char* Hi (void)
    
    2
    {char* ans;
    
    3
    asprintf(&ans, "Hello World.");
    
    4
    return ans;}
    
    1+
    def hello_world
    
    2+
      print(HELLO_WORLD)
    
    3+
    end
    
Loading more items...