Hackerrank Day 7: Arrays

Task

Given an array, A, of N integers, print ‘s elements in reverse order as a single line of space-separated numbers.

Input Format

The first line contains an integer, N (the size of our array).
The second line contains N space-separated integers describing array A‘s elements.

Output Format

Print the elements of array in reverse order as a single line of space-separated numbers.

Sample Input

4
1 4 3 2

Sample Output

2 3 4 1

My solution in Ruby:  

screen-shot-2016-12-14-at-12-28-10-pm

arr = arr.split(' ').map(&:to_i)

can also be written as:

arr_strings = arr.split(' ') 
arr = arr_strings.map {|n| n.to_i}

A couple other things to remember:

  • .strip removes any unnecessary characters from a string to let you focus on the important ones.  (It does not work on integers/fixnums)
  • splitting a string with space will convert it into an array
  • &: is a shorthand for calling a function on an enumerator.  For example, we can only use .to_i on one value.  If we want to .to_i multiple values (like in an array), we have to use .map (&:to_i) instead.
Advertisements
Hackerrank Day 7: Arrays

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s