首页 > 解决方案 > 如何从Ruby中的单词数组中获取所有对角线?

问题描述

我在 Ruby 中有一个数组

words = ["horses", "follow", "useful", "offset"]

参考:

h o r s e s
f o l l o w
u s e f u l
o f f s e t

我想得到一个像这样的所有对角线的列表。这是我期望的结果:

["o", "uf", "fsf", "hoes", "olfe", "rlut", "sol", "ew", "s"]

如果有人能在这方面对我有所帮助,那将会很有帮助。谢谢

标签: ruby-on-railsrubyalgorithmmath

解决方案


试试看:

words = ["horses", "follow", "useful", "offset"]

words.reverse.each_with_index.map{|s,i| " " * i + s }.inject(Array.new(words.size + words.last.size-1,"")) do |a,s| 
  s.chars.each_with_index do |c,i| 
    a[i] = c + a[i]
  end
  a
end.map(&:strip)
# => ["o", "uf", "fsf", "hoes", "olfe", "rlut", "sol", "ew", "s"]

首先words.reverse.each_with_index.map{|s,i| " " * i + s }构建带有空白偏移量的数组:

offset
 useful
  follow
   horses

注入创建空字符串数组,并在主块内将每个字符串字符添加到正确的数组元素


推荐阅读