Question

Write a function that takes an array A of integers as the input and does the...

Write a function that takes an array A of integers as the input and does the following:
(a) Uses each method to print the square of each element of A, (b) Uses each_slice method to print the
elements while printing 4 elements at a time, (c) Uses select method to find the integers (in A) which are
multiple of 4, (d) Uses map method to build a new array of squares of the elements of A, and (e) Uses inject
method to find the product of all elements of A. To test the function, generate an array A of 51 random
integers between 20 and 100, and pass into the function as a parameter

In ruby language
0 0
Add a comment Improve this question Transcribed image text
Answer #1

a)A.each {|array| print (array*array).to_s() +"\n" }

b)A.each_slice(4) {|array| print (array).to_s() +"\n" }

c) A.select {|array| array%4==0 }

d)A.map {|array| array*array }

e)A.inject(1) {|result,element| result*element}

Testing Code:

A = Array.new(51) {rand(20...100)} #generating 51 random number between 20 to 100
A.each {|array| print (array*array).to_s() +"\n" } #using each

A.each_slice(4) {|array| print (array).to_s() +"\n" } #using each slice
A.select {|array| array%4==0 } #using select

A.map {|array| array*array } #using map

A.inject(1) {|result,element| result*element} #using inject

Happy Chegging!

Add a comment
Know the answer?
Add Answer to:
Write a function that takes an array A of integers as the input and does the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT