In this HackerRank Lazy Evaluation problem solution in ruby programming, Lazy evaluation is an evaluation strategy that delays the assessment of an expression until its value is needed.
Ruby 2.0 introduced a lazy enumeration feature. Lazy evaluation increases performance by avoiding needless calculations, and it has the ability to create potentially infinite data structures.
Example:
power_array = -> (power, array_size) do
1.upto(Float::INFINITY).lazy.map { |x| x**power }.first(array_size)
end
puts power_array.(2 , 4) #[1, 4, 9, 16]
puts power_array.(2 , 10) #[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
puts power_array.(3, 5) #[1, 8, 27, 64, 125]
In this example, lazy avoids needless calculations to compute power_array.
If we remove lazy from the above code, then our code would try to compute all x ranging from 1 to Float::INFINITY.
To avoid timeouts and memory allocation exceptions, we use lazy. Now, our code will only compute up to first(array_size).
Task
Your task is to print an array of the first N palindromic prime numbers.
For example, the first 10 palindromic prime numbers are [2,3,5,7,11,101,131,151,181,191].
Problem solution.
# Enter your code here. Read input from STDIN. Print output to STDOUT def prime?(x) return false if x == 1 return true if x < 4 m = (x**0.5).to_i (2..m).none? { |div| x % div == 0 } end def palindromic?(x) x.to_s == x.to_s.reverse and prime?(x) end n = gets p 1.upto(Float::INFINITY).lazy.select { |x| palindromic?(x) }.first(n.to_i)
Second solution.
def prime? (n) if n <= 1 return false elsif n <= 3 return true elsif n % 2 == 0 || n % 3 == 0 return false end i = 5 while i*i <= n if n % i == 0 || n % (i+2) == 0 return false end i += 6 end return true end def palindrome? (s) return s == s.reverse end array = -> (n) do 1.upto(Float::INFINITY).lazy.select { |x| x if prime?(x) && palindrome?(x.to_s) }.first(n) end p array.(gets.strip.to_i)
0 Comments