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.

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  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).


Task

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 .

Constraints

You are not given how big  is.

Output Format.

Print an array of the first  palindromic primes.

Sample Input.

5

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
end

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
end

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

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

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe