Skip to content

Instantly share code, notes, and snippets.

@dannypage
Last active July 28, 2017 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dannypage/9caa154a3e933b1a5e1d95570b507623 to your computer and use it in GitHub Desktop.
Save dannypage/9caa154a3e933b1a5e1d95570b507623 to your computer and use it in GitHub Desktop.
Trying to solve the chain problem by brute force. Uses 4 cores with the Parallel gem. https://fivethirtyeight.com/features/pick-a-number-any-number/
# ruby chain.rb &
# writes to /tmp/chain_results.log
require 'parallel'
def number_chain( n, range, chain)
chain << n
range.delete(n)
next_numbers = []
range.each do |r|
next_numbers << r if ((n % r) == 0)
next_numbers << r if ((r % n) == 0)
end
if next_numbers.count > 0
next_numbers.each do |nx|
number_chain( nx, range.dup, chain.dup )
end
else
if chain.count > 45
IO.write("/tmp/chain_results.log", "-----\n", mode: 'a')
IO.write("/tmp/chain_results.log", "Count: #{chain.count}\n", mode: 'a')
IO.write("/tmp/chain_results.log", "Chain: #{chain.to_s}\n", mode: 'a')
end
end
end
a = (1..100).to_a
Parallel.each(a, in_processes: 4) do |n|
IO.write("/tmp/chain_results.log", "Processing #{n}\n", mode: 'a')
number_chain(n, (1..100).to_a, [])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment