Last active
August 29, 2015 14:00
-
-
Save baweaver/11163861 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# 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 | |
# Basic implementation - 42 minutes | |
(1..1_000_000).select { |n| | |
n.to_s | |
.chars | |
.permutation | |
.flat_map(&:join) | |
.map(&:to_i) | |
.all?(&:prime?) | |
}.count | |
# With caching - 38 minutes | |
cache = {} | |
(1..1_000_000).select { |n| | |
n.to_s | |
.chars | |
.permutation | |
.flat_map(&:join) | |
.map(&:to_i) | |
.all? { |x| cache.fetch(x) { |y| cache[x] = y.prime? } } | |
}.count | |
# A lot faster implementation: 42 seconds | |
(1..1_000_000).select { |n| | |
n == 2 || | |
((s = n.to_s.chars) & %w(0 2 4 6 8)).count == 0 && | |
s.permutation | |
.flat_map(&:join) | |
.map(&:to_i) | |
.all?(&:prime?) | |
}.count | |
# Ahaha, left off 5, down to 18 seconds: | |
(1..1_000_000).select { |n| | |
n == 2 || | |
((s = n.to_s.chars) & %w(0 2 4 5 6 8)).count == 0 && | |
s.permutation | |
.flat_map(&:join) | |
.map(&:to_i) | |
.all?(&:prime?) | |
}.count | |
# Implementing pipeable, 1 second hit but I think it's more readable. | |
# https://github.com/baweaver/pipeable | |
(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 |
This solution owns the other one in terms of speed.
(1..1_000_000).select { |n|
n == 2 ||
((s = n.to_s.chars) & %w(0 2 4 6 8)).count == 0 &&
s.permutation
.flat_map(&:join)
.map(&:to_i)
.all?(&:prime?)
}.count
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I really really REALLY need to redo this thing in Haskell. The Ruby version tanks out pretty fast.