Skip to content

Instantly share code, notes, and snippets.

@jedisct1
Created April 27, 2011 05:33
Show Gist options
  • Save jedisct1/943764 to your computer and use it in GitHub Desktop.
Save jedisct1/943764 to your computer and use it in GitHub Desktop.
MongoDB puzzle
n = rand(10) + 2
list = (1..n).to_a.shuffle
list[1 + rand(list.length - 1)] = list.first
puts list.join(", ")
a = n * n.succ / 2
b = n * n.succ * (2 * n).succ / 6
a2 = list.inject(:+)
b2 = list.inject(0) { |acc, x| acc + x * x }
missing = ((b2 - b) / (a2 - a) - a2 + a) / 2
duplicate = a2 - a + missing
puts "missing: #{missing} duplicate: #{duplicate}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment