Ruby Lazy Evaluation – HackerRank Solution

In this post, we will solve Ruby Lazy Evaluation HackerRank Solution. This problem (Lazy Evaluation) is a part of HackerRank Ruby series.

Contents

Problem

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

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

Input Format

A single line of input containing the integerÂ N.

Constraints

You are not given how bigÂ NÂ is.

Output Format

Print an array of the firstÂ NÂ palindromic primes.

Sample Input

``5``

Sample Output

``[2, 3, 5, 7, 11]``

Solution – Ruby Lazy Evaluation – HackerRank Solution

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

require 'prime'
primes = []
puts "[#{Prime.each.lazy.select{|x| x.to_s == x.to_s.reverse}.first(gets.to_i).join(", ")}]"
```

Note: This problem (Lazy Evaluation) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.