Skip to content

Instantly share code, notes, and snippets.

@zdennis
Created February 27, 2015 15:03
Show Gist options
  • Save zdennis/3b93d16bd01a0021806b to your computer and use it in GitHub Desktop.
Save zdennis/3b93d16bd01a0021806b to your computer and use it in GitHub Desktop.
Project Euler problem #86 (First Attempt, Naive I know :)
=begin
Cuboid room:
* consider all integer up to cuboids: M x M x M
* where M = 100
* a^2 + b^2 = c^2
* c = sqrt(a^2 + b^2)
* shortest path thru cuboid: Math.sqrt( l**2 + (w + h)**2 )
=end
require 'benchmark'
Benchmark.bm do |x|
x.report do
m = 1
count = nil
loop do
range = (1..m+=1)
arr_of_triplets = range.to_a.repeated_combination(3).to_a
count = 0
arr_of_triplets.each do |triplets|
h, w, l = triplets
shortest_path = Math.sqrt( l**2 + (w + h)**2 )
if shortest_path % 1 == 0
count += 1
end
end
break m if count > 1_000_000
end
puts m, count
end
end
@diiq
Copy link

diiq commented Feb 27, 2015

So arr_of_triplets = range.to_a.repeated_combination(3).to_a is going to be a big, big, big array -- on the order of billions of elements when m ~1000.

I'd recommend doing

(1...m).each do |h|
  (1...h).each do |w|
    (1...w).each do |l|

It's the same time complexity but uses almost no space.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment