DAY 2
0

## 吾即是汝，汝即是吾，Ruby 30 天刷題修行篇第二話

Are they the "same"?」

Given two arrays a and b write a function comp(a, b) (orcompSame(a, b)) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in b are the elements in a squared, regardless of the order.

Examples

Valid arrays

``````a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]
``````

Invalid arrays

``````a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [132, 14641, 20736, 361, 25921, 361, 20736, 361]
``````

Remarks

a or b might be [] or {} (all languages except R, Shell).
a or b might be nil or null or None or nothing (except in C++, Elixir, Haskell, PureScript, Pascal, Perl, R, Rust, Shell).
If a or b are nil (or null or None, depending on the language), the problem doesn't make sense so return false.

1. 要對 a 和 b 陣列每一個元素做平方或開平方的運算，對陣列中每個元素做某件事，我們會用到 map 方法；而開平方這件事，我用了 Math.sqrt 方法。
2. 為了能讓 a 和 b 陣列中每個元素依照大小順序排好，方便我們依照索引值比對每個元素，要使用 sort 方法。
3. 要先判斷 a 和 b 陣列是否為 nil，對此，神奇語法師 Ruby 有提供物件 nil? 方法，如果該物件是 nil，則會回傳 true；另外，我還使用 hash 方法，去比較兩個陣列的內容是否一樣。

``````def comp(array1, array2)
if !array1.nil? and !array2.nil?
array2.map { |e| Math.sqrt(e) }.sort.hash == array1.map { |e| e.to_f }.sort.hash
else
false
end
end
``````

``````def comp(array1, array2)
return false if array1.nil? || array2.nil?
array1.map {|num| num ** 2}.sort == array2.sort
end
``````