RubyMonk经典习题记录

Posted by 竹林品雨 on June 20, 2013

RubyMonk经典习题记录

给定字符串Array返回字符串长度组成的Array

def length_finder(input_array)
  input_array.map{|str| str.length}
end

找出给定word在给定语句中出现的次数

count计算元素在数组中出现的次数
   
def find_frequency(sentence, word)
  sentence.downcase.split.count(word.downcase)
end

Sort the words in a given sentence (将给定句子的所有单词 按单词的length排序)

def sort_string(string)
  string.split.sort{|a, b| a.length <=> b.length}.join(' ')
end

随机选择n个数组元素

其中rand(n)方法 返回小于n的任意正整数

def random_select(array, n)
  result = []
  n.times do 
    result << array[rand(array.length)]
  end
  result
end

回文
应用reverse方法

Find non-duplicate values in an Array(在数组中找出非重复元素)
eg. Given [1,2,2,3,3,4,5], the method should return [1,4,5]

def non_duplicated_values(values)
  values.find_all { |x| values.count(x) == 1 }
end

Kaprekar’s Number

def kaprekar?(k)
  kstr = (k**2).to_s
  n = kstr.length/2
  l = kstr[0, n]
  r = kstr[n, kstr.length-n]
  k==(l.to_i + r.to_i)
end

给定一个三位或四位数生成 其全排列的数组
eg. 123  [123, 132, 213, 231, 312, 321]
注意shuffle方法,随机排列数组元素

def number_shuffle(number)
  no_of_combinations = number.to_s.size == 3 ? 6 : 24
  digits = number.to_s.split("")
  combinations = []
  combinations << digits.shuffle.join.to_i while combinations.uniq.size!=no_of_combinations
  combinations.uniq.sort
end

###数组hash元素求和/article_images/array_hash_sum.png

数组hash元素求和


数字数组求和
   
a=[1,2,3]
a.inject(:+)