From 12e1a3c389f14fe1add45869a4f8672d958cbba7 Mon Sep 17 00:00:00 2001 From: Jessica Kwok Date: Wed, 10 Mar 2021 06:59:10 -0800 Subject: [PATCH] Add loop and multiply solution --- .../arrays/sort_squares_of_an_array.rb | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 data_structures/arrays/sort_squares_of_an_array.rb diff --git a/data_structures/arrays/sort_squares_of_an_array.rb b/data_structures/arrays/sort_squares_of_an_array.rb new file mode 100644 index 0000000..8eef282 --- /dev/null +++ b/data_structures/arrays/sort_squares_of_an_array.rb @@ -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) \ No newline at end of file