Leetcode(Easy問題) でRubyの勉強をしてみました！　＜備忘録＞

# 概要
プログラミング初心者でWebアプリケーションを制作していますが、
それだけではプログラミングの知識が浅いためLeetcodeで勉強をしました！

何問か解きましたが、勉強になったことが多いので備忘録として残しておこうと思います！
もっと綺麗な書き方あるよーって教えてくれる方がいたら是非コメントにお願いします！
（※解いた順なので、番号は前後します。）
（※他の方の解答を参考にした問題もあります。）

#  1672. Richest Customer Wealth
You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has.

A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.

 

**Example**:

Input: accounts = [[1,2,3],[3,2,1]]
Output: 6
Explanation:
1st customer has wealth = 1 + 2 + 3 = 6
2nd customer has wealth = 3 + 2 + 1 = 6
Both customers are considered the richest with a wealth of 6 each, so return 6.

**解答**

```Ruby
def maximum_wealth(accounts)
    accounts.map(&:sum).max
end
```

**学んだこと**

 - `.map(&:メソッド名)`<br>
　　要素１つ１つに`(&:メソッド名)`で与えられたメソッドを呼ぶ<br>
　　ここではacconuntsの要素（Exampleだと`[1,2,3]`と`[3,2,1]`それぞれにsumが呼び出されている

```Ruby
accounts.map(&:sum) #=> [6,6]
```

 - `max`<br>
　　配列の中の最大値を持つ要素を取得することができるメソッド<br>

```Ruby
[6, 6].max #=> 6
[5, 6, 2].max #=> 6
[5, 6, 2, 4, 8, 4].max(3) #=>  [8, 6, 5]
```

# 1470. Shuffle the Array
Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].

Return the array in the form [x1,y1,x2,y2,...,xn,yn].

 

**Example**:
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7] 
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].

**Constraints**:
1 <= n <= 500
nums.length == 2n
1 <= nums[i] <= 10^3

**解答**

```Ruby
def shuffle(nums, n)
    ans = []
    n.times do |i|
        ans.push nums[i]　#ans << nums[i]でも同じ結果
        ans.push nums[i+n] #i番目にnを足すことでynの値を抜き出せる
    end
    ans
end
```

- `push`<br>
　　オブジェクト.push(“要素”)で配列の末尾に要素を追加できる<br>
　　`<<`でも同じ結果が得られる

# 771. Jewels and Stones
You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.

Letters are case sensitive, so "a" is considered a different type of stone from "A".

 

**Example**:

Input: jewels = "aA", stones = "aAAbbbb"
Output: 3

**解答**

```Ruby
def num_jewels_in_stones(jewels, stones)
    cnt = 0
    jewels.split(//).each do |j|
        cnt += stones.count(j)
    end
    cnt
end
```

 - `split(//)`<br>
　　文字列を分割して配列にするメソッド<br>
　　任意の文字や正規表現で分割する場合は第一引数で指定する<br>
　　`//`は`文字列全体を 1 文字ずつに分割`

```Ruby
文字列.split(区切り文字)
文字列.split(正規表現)
```

 - `count`<br>
　　countの引数に指定した要素と一致するものを数える

```Ruby
'abc'.count('c') # => 1
'123456789'.count('2378') # => 4
```

# 1773. Count Items Matching a Rule
You are given an array items, where each items[i] = [typei, colori, namei] describes the type, color, and name of the ith item. You are also given a rule represented by two strings, ruleKey and ruleValue.

The ith item is said to match the rule if one of the following is true:

ruleKey == "type" and ruleValue == typei.
ruleKey == "color" and ruleValue == colori.
ruleKey == "name" and ruleValue == namei.
Return the number of items that match the given rule.

**Example**:

Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
Output: 1
Explanation: There is only one item matching the given rule, which is ["computer","silver","lenovo"].

**解答**

```Ruby
def count_matches(items, rule_key, rule_value)
    cnt = 0
    items.each do |i|
        if rule_key == "type" && i[0] == rule_value
            cnt += 1
        elsif rule_key == "color" && i[1] == rule_value
            cnt += 1
        elsif rule_key == "name" && i[2] == rule_value
            cnt += 1
        end
    end
    cnt
end
```

# 1365. How Many Numbers Are Smaller Than the Current Number
Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].

Return the answer in an array.

**Example**:

Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation: 
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). 
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1). 
For nums[3]=2 there exist one smaller number than it (1). 
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).

**解答**

```Ruby
def smaller_numbers_than_current(nums)
    nums.map do |n|
        cnt = 0
        nums.each do |x|
            cnt += 1 if n > x
        end
        cnt
    end
end
```

- `each do`と`map do`の違い<br>
  - `each `<br>
  　　繰り返し処理<br>
  - `mach`<br>
     結果を配列で返す
  

```Ruby
array = [1, 2, 3, 4]
array.each do |a|
  puts a * 2
end
2
4
6
8
=> [1, 2, 3, 4]
``` 

```Ruby
array = [1, 2, 3, 4]
ans = array.map do |a|
  a * 2
end
=> [2, 4, 6, 8]

#上記をeachで書き換えると
array = [1, 2, 3, 4]
ans = []
array.each do |a|
 ans << a * 2
end
=> [1, 2, 3, 4]
result #=> [2, 4, 6, 8]
```

# 1342. Number of Steps to Reduce a Number to Zero
Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.

**Example**:

Input: num = 14
Output: 6
Explanation: 
Step 1) 14 is even; divide by 2 and obtain 7. 
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3. 
Step 4) 3 is odd; subtract 1 and obtain 2. 
Step 5) 2 is even; divide by 2 and obtain 1. 
Step 6) 1 is odd; subtract 1 and obtain 0.

**解答**

```Ruby
def number_of_steps (num)
    cnt = 0
    while num > 0 do
        if num.even?
            num = num / 2
            cnt += 1
        else
            num = num - 1
            cnt += 1
        end
    end
    cnt
end
```

- `even?`<br>
　偶数の場合→true<br>
　奇数の場合→false
 （奇数か確かめたい場合は`odd?`）

# 1528. Shuffle String

Given a string s and an integer array indices of the same length.

The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.

Return the shuffled string.

**Example**:
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
Explanation: As shown, "codeleet" becomes "leetcode" after shuffling.

**解答**

```Ruby
def restore_string(s, indices)
    ans = []
    indices.each_with_index do |n, i|
        ans[n] = s[i]
    end
    ans.join
end
```

- `join`<br>
　　配列を連結させ、１つの文字列にする

```Ruby
array = ["foo", "bar"]
array.join
=> "foobar"
```

# 1281. Subtract the Product and Sum of Digits of an Integer

Given an integer number n, return the difference between the product of its digits and the sum of its digits.
 
**Example** :

Input: n = 234
Output: 15 
Explanation: 
Product of digits = 2 * 3 * 4 = 24 
Sum of digits = 2 + 3 + 4 = 9 
Result = 24 - 9 = 15

**解答**

```Ruby
def subtract_product_and_sum(n)
    arr = n.to_s.chars.map(&:to_i)
    arr.inject(:*) - arr.sum
end
```

- `to_s`<br>
　文字列以外のオブジェクトを文字列に変換するメソッド

```Ruby
n = 234
n.to_s
=> "234"
```

- `chars`<br>
　　文字列の各文字を文字列の配列で返す

```Ruby
n.to_s.chars
=> ["2", "3", "4"]
```

- `to_i`<br>
　　文字列を整数に変換<br>
　　配列ひとつひとつに適用したいので、mapを用いる

```Ruby
n.to_s.chars.map(&:to_i)
=> [2, 3, 4]
```

最初、ここまでの作業をsplit(//)で分割しようとしていました。。
splitは文字列を分割できるだけなので、integerには使えません

- `inject(:*)`<br>
　　injectはブロックを使用して、繰り返し計算するメソッド

```Ruby
n.inject(:*)
=> 24
```

- `sum`<br>
　　inject(:+)と書いても良いが、sumの方が早いらしい。<br>
　　inject(:*)の書き換えは見つからなかったので、知っている方がいたら教えてください・・

```Ruby
n.sum
=> 9
```

#最後に
まだまだLeetcodeは始めたばかりなので、どんどん解いてアップしていきたいと思います！
誰かのお役に立てたら嬉しいです:)