mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-27 21:58:57 +01:00
Add loop and multiply solution
This commit is contained in:
parent
dee635f6da
commit
12e1a3c389
1 changed files with 23 additions and 0 deletions
23
data_structures/arrays/sort_squares_of_an_array.rb
Normal file
23
data_structures/arrays/sort_squares_of_an_array.rb
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
# Arrays - Sorted Squares
|
||||||
|
|
||||||
|
# Algorithm challenge description:
|
||||||
|
# Given an integer array nums sorted in non-decreasing order
|
||||||
|
# return an array of the squares of each number sorted in non-decreasing order.
|
||||||
|
# Input: [4, -1, -9, 2]
|
||||||
|
# Output: [1, 4, 16, 81]
|
||||||
|
|
||||||
|
# Loop and multiply
|
||||||
|
|
||||||
|
array = [4, -1, -9, 2]
|
||||||
|
|
||||||
|
def square_and_sort(array)
|
||||||
|
result_array = []
|
||||||
|
|
||||||
|
array.each do |num|
|
||||||
|
result_array.push(num*num)
|
||||||
|
end
|
||||||
|
|
||||||
|
result_array.sort
|
||||||
|
end
|
||||||
|
|
||||||
|
print square_and_sort(array)
|
Loading…
Reference in a new issue