HackerRank Ruby Lazy Evaluation Solution

Hello coders, In this post, you will learn how to solve HackerRank Ruby Lazy Evaluation Solution. This problem is a part of the Ruby Tutorial series. One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions.

HackerRank Ruby Lazy Evaluation Solution
HackerRank Ruby Lazy Evaluation Solution

HackerRank Ruby Lazy Evaluation Solution

Let’s get started with Ruby Lazy Evaluation Solution

Problem Statement

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.


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


You are not given how big N is.

Output Format

Print an array of the first N palindromic primes.

Sample Input


Sample Output

[2, 3, 5, 7, 11]

HackerRank Ruby Lazy Evaluation 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 (HackerRank Ruby Lazy Evaluation is generated by HackerRank but the solution is provided by Chase2Learn. This tutorial is only for Educational and Learning purpose.

Sharing Is Caring