Skip to content

Instantly share code, notes, and snippets.

@baweaver
Last active August 29, 2015 14:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baweaver/2da59e2f7c825e4b21ce to your computer and use it in GitHub Desktop.
Save baweaver/2da59e2f7c825e4b21ce to your computer and use it in GitHub Desktop.
Variant of Prime Perms, checking mersennes from 1 to 1 million, using block extraction for time comparisons. Surprising results were found when t3 dominated the field.
# From original: https://gist.github.com/baweaver/11163861
# Using Pipeable for clearer code: https://github.com/baweaver/pipeable
# and Benchpress to measure: https://github.com/baweaver/benchpress
# Make Object Pipeable
class Object; include Pipeable end
# Patch numbers to have a prime? method
class Fixnum
def prime?
([1,2].include?(self) || !(2..Math.sqrt(self).ceil).find { |x| self % x == 0 })
end
end
# The original second fastest solution, taking ~18 seconds
def t1
(1..1_000_000).select { |n|
n == 2 ||
n.to_s.chars.pipe { |c|
(c & %w(0 2 4 5 6 8)).count == 0 &&
c.permutation
.flat_map(&:join)
.map(&:to_i)
.all?(&:prime?)
}
}.count
end
# Let's take the select block out of there into a lambda. About 17 seconds, not as large as I had wanted
def t2
prime_perms = -> n {
n == 2 ||
n.to_s.chars.pipe { |c|
(c & %w(0 2 4 5 6 8)).count == 0 &&
c.permutation
.flat_map(&:join)
.map(&:to_i)
.all?(&:prime?)
}
}
(1..1_000_000).select(&prime_perms).count
end
# How about we take the pipe out of there as well? About 15 seconds. Interesting...
def t3
c_pipe = -> c {
(c & %w(0 2 4 5 6 8)).count == 0 &&
c.permutation
.flat_map(&:join)
.map(&:to_i)
.all?(&:prime?)
}
prime_perms = -> n { n == 2 || n.to_s.chars.pipe(&c_pipe) }
(1..1_000_000).select(&prime_perms).count
end
# Now let's chart it, get a bit more data here:
Benchpress::Chart.new(
entities: { t1: -> { t1 }, t2: -> { t2 }, t3: -> { t3 } },
min: 1, max: 5, step: 1, cycle: 5
).render
# Wait wait, what!?
# http://i59.tinypic.com/whjuvq.png
# t3 slaughtered! Interesting.
@baweaver
Copy link
Author

Chart

@josiah14
Copy link

very interesting that t3 has such a big performance gain.

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