Hackerrank Lazy Evaluation Solution
1 min read

Hackerrank Lazy Evaluation Solution

Hackerrank Lazy Evaluation Solution

Lazy evaluation is an evaluation strategy that delays the assessment of an expression until its value is needed.

Ruby  introduced a lazy enumeration feature. Lazy evaluation increases performance by avoiding needless calculations, and it has the ability to create potentially infinite data structures.


power_array = -> (power, array_size) do 
    1.upto(Float::INFINITY).lazy.map { |x| x**power }.first(array_size) 

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  ranging from  to Float::INFINITY.
To avoid timeouts and memory allocation exceptions, we use lazy. Now, our code will only compute up to first(array_size).


Your task is to print an array of the first  palindromic prime numbers.
For example, the first  palindromic prime numbers are .

Input Format.

A single line of input containing the integer .


You are not given how big  is.

Output Format.

Print an array of the first  palindromic primes.

Sample Input.


Sample Output.

[2, 3, 5, 7, 11]

Solution in ruby

Approach 1.

# Enter your code here. Read input from STDIN. Print output to STDOUT
require 'prime'
n = gets.to_i
p Prime.each.lazy.select {|i| i.to_s == i.to_s.reverse}.first(n)

Approach 2.

# Enter your code here. Read input from STDIN. Print output to STDOUT
require 'prime'

def yield_var(var_num)
    sum = (2..Float::INFINITY).lazy.select{ 
        |x| x.to_s.reverse.to_i == x && Prime.prime?(x) }.first(var_num.to_i)
    return sum

num = gets.chomp
print yield_var(num)

Approach 3.

# Enter your code here. Read input from STDIN. Print output to STDOUT
def prime?(num)
  num >= 2 && (2..Math.sqrt(num)).none? { |div| (num % div).zero? } ? true : false

def palindrome?(num)
  num.to_s == num.to_s.reverse

p 2.upto(Float::INFINITY).lazy.select { |num| palindrome?(num) && prime?(num) }

Enjoying these posts? Subscribe for more

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.