Last active
August 29, 2015 14:01
-
-
Save syntacticsugar/e022dc1366652461ef90 to your computer and use it in GitHub Desktop.
project euler #44 Pentagonal Numbers in Ruby. This is probably the most inefficient, naive way to solve it, but it solved the problem. blehhhhh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=begin | |
Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are: | |
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... | |
It can be seen that P^4 + P^7 = 22 + 70 = 92 = P^8. | |
However, their difference, 70 − 22 = 48, is not pentagonal. | |
Find a pair of pentagonal numbers P^j and P^k, | |
for which their sum and difference are pentagonal | |
and D = |P^k - P^j| is minimised (the smallest). What is the value of D? | |
=end | |
require 'set' | |
# require 'benchmark' | |
# (I don't know how to use benchmark properly yet) | |
beginning = Time.now | |
=begin | |
no longer using this | |
class Array | |
def contains? element | |
self.any? { |x| x == element } | |
end | |
end | |
=end | |
class Integer | |
def pentafy | |
self*(self*3 - 1)/2 | |
end | |
#@@first_million = (1..1e6).to_a.map{ |x| x.pentafy } | |
@@first_set = Set.new (1..1e5).to_a.map{ |x| x.pentafy } | |
def pentagonal? | |
#@@first_million.contains? self | |
@@first_set.include? self | |
end | |
end | |
puts "Hi, I just made the class: " | |
p Time.now - beginning | |
beginning = Time.now | |
#boolean: sum AND difference are pentagonal? | |
def sad?(pent1, pent2) | |
(pent1+pent2).pentagonal? and (pent1-pent2).abs.pentagonal? | |
end | |
puts "...and I just defined sad?" | |
p Time.now - beginning | |
beginning = Time.now | |
first_some = (1..1e5).to_a.map{ |x| x.pentafy } | |
#first_ten = [1, 5, 12, 22, 35, 51, 70, 92, 117, 145] | |
#first_five = first_ten.take(5) | |
first_set = first_some.take(10000) | |
puts "Finally, I defined first_set" | |
p Time.now - beginning | |
beginning = Time.now | |
# [1,5] [1,12] [1,22] | |
pairs = [] | |
first_set.each do |n| | |
first_set.each do |m| | |
if n < m | |
pairs << [n,m] | |
end | |
end | |
end | |
puts "Oh, I am so tired. I just defined pairs" | |
p Time.now - beginning | |
beginning = Time.now | |
pentagonal_pairs = pairs.select { |p| sad?(p[0],p[1]) } | |
puts "I work so hard for you. I just defined pentagonal_pairs" | |
p pentagonal_pairs | |
p Time.now - beginning | |
beginning = Time.now | |
# and, inspired by @Spooner | |
puts "\n But don't ask me anymore, I can't be bothered to do any more work after all of this!" | |
# for any n, m | |
# only ONE of these three conditions can be true | |
# n < m | |
# n == m | |
# n > m | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(last five lines from Nicky)