Chapter 2: Collections

0 概述

Collection 包括String, Array, Hash

0.1 如果String没有对应的函数,那么除非有in-place处理的要求,总是可以用str.chars或者str.split("")把String的问题转化成Array的问题

e.g.

def caesar_cipher(message, n)
  alphabet = ("a".."z").to_a
  new_message = ""
  new_chars = message.chars.map do |char|
    old_index = alphabet.index(char)    
    new_char = (old_index != nil ? alphabet[(old_index + n)%26] : char)
    new_char
  end
  return new_chars.join("")
end

1 处理Sentence的问题

sentence中包含多个词,用空格隔开,处理每个词

circle-check

1.1 sentence中包含多个词,用空格隔开,转换成另一句sentence

通过str.split(" ")把问题转换成array问题 (array of strings), 然后把array用array.map变换成新array new_arr, 最后再用new_arr.join(" ")转回为string。

2 Collection的聚合类问题,输入输出是n => 1的结构

2.1 由一组元素得出一个非boolean的结果

给定一组元素,得出一个非boolean的结果(boolean见2.2),通常是Array元素同样的类型, 用array.injectaccele得到new_acc再结算

e.g. Write a method matrix_addition_reloaded that accepts any number of matrices as arguments. The method should return a new matrix representing the sum of the arguments. Matrix addition can only be performed on matrices of similar dimensions, so if all of the given matrices do not have the same "height" and "width", then return nil.

2.2 对一组元素做一个判断(boolean) 的问题

给定一组元素, 对某个事实做true or false判断的问题,可以认为是inject的特殊情况, 用:

全都是 / 只存在 => array.all? or (0..num).all

有没有 / 至少有一个 => array.any? or (0..num).any

完全没有 / 除去某个就没有了 => array.none? or (0..num).none

e.g. Write a method, coprime?(num_1, num_2), that accepts two numbers as args.The method should return true if the only common divisor between the two numbers is 1. The method should return false otherwise. For example coprime?(25, 12) is true because 1 is the only number that divides both 25 and 12.

3. 在Collection中处理相邻的元素关系的问题

circle-check

3.1 分段处理的问题

circle-check

4. 对Collection进行反复操作直到满足条件的问题

可以用一个变量completed = false, 然后用completed这个boolean变量去记录每一轮的情况,直到completedtrue

5. 在Collection中查找的问题

5.1 查找所有满足条件的元素(的数量)

array.select,block里输出需要满足的条件。如果只需要元素的数量,则可以用arr.count

5.2 查找第一个/最后一个满足条件的元素

这类问题适合单独用一个函数实现(因为找到后可能需要立即退出查找),用变量idx = 0idx = arr.length-1, 用while循环找到,即返回.

5.3 已知range查找的问题

例如找因子, 找公因子, 找质数, 这类问题等同于在collection中查找的问题。

5.3.1 知道算子的范围,用range (1..num).each来逐个检查

5.3.2 知道结果的范围,用while result <= numi += 1来逐个检查

5.4 查找第n个或者前n个满足条件的元素

通常这类问题都不能用select因为我们并不知道元素所处的范围

circle-check

6 对称和反转

检查一个Collection是否对称,或者对一个Collection进行反转,用头尾i = 0, j = arr.length - 1两个marker,以及while i < j相向而行。然后每次都对arr[i]arr[j]进行比较或者交换。

7 求collection或range内元素的两两组合

circle-check

8 Collection内统计所有元素的问题

circle-check

9 2D Array

circle-exclamation

Last updated