反向阵列时不使用红宝石循环 [英] Reverse an array without using a loop in ruby
本文介绍了反向阵列时不使用红宝石循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个编码的挑战扭转数组与它5个元素。我将如何做到这一点,而无需使用逆向方法?
code:
高清反转(阵列)
排列
结束
p反向([A,1,苹果,8,90])
解决方案
您可以把数组作为栈和流行
从最终的元素:
高清反转(阵列)
REV = []
转<< array.pop直到array.empty?
转
结束
如果你不喜欢修改对象,使用更多的功能,如减少
:
高清反转(阵列)
array.reduce([]){| ACC,X | [X] + ACC}
结束
卡里的有关性能注释中。该功能的方法可能不是最快的方式,所以如果你真的想这样做快,创建一个buffor阵列和刚刚从末尾添加的项目开始:
高清反转(阵列)
反转= Array.new(array.count)
array.each_with_index做|项,指数|
逆转[ - (索引+ 1)] =项目
结束
反向的
结束
I have a coding challenge to reverse a an array with 5 elements in it. How would I do this without using the reverse method?
Code:
def reverse(array)
array
end
p reverse(["a", 1, "apple", 8, 90])
解决方案
You can treat array as a stack and pop
the elements from the end:
def reverse(array)
rev = []
rev << array.pop until array.empty?
rev
end
or if you don't like modifying objects, use more functional-like reduce
:
def reverse(array)
array.reduce([]) {|acc, x| [x] + acc}
end
Cary mentioned in the comment about the performance. The functional approach might not be the fastest way, so if you really want to do it fast, create a buffor array and just add the items from the end to begin:
def reverse(array)
reversed = Array.new(array.count)
array.each_with_index do |item, index|
reversed[-(index + 1)] = item
end
reversed
end
这篇关于反向阵列时不使用红宝石循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文