如何从Ruby中的单词数组获取所有对角线?

时间:2018-12-02 14:32:52

标签: ruby-on-rails ruby algorithm math

我在Ruby中有一个数组

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"]

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

AdRequest request = new AdRequest.Builder().Build();
AdManager.bannerAd = new BannerView(adID, GetBanner(), AdPosition.Top);
AdManager.bannerAd.LoadAd(request);

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

1 个答案:

答案 0 :(得分:0)

尝试:

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

Inject会创建一个空字符串数组,并在主块内部将每个字符串char附加到适当的数组元素上