Ruby:反转,变异列表
Ruby: reverse, mutating list
我正在尝试编写一种方法来反转列表,但不使用 .reverse。
这是我的代码:
def reverse(list)
a = list.length
while a >= 0
list << list[a]
a = a - 1
end
list
end
print reverse([1,2,3])
我的预期结果不是 [3,2,1],而是 [1, 2, 3, nil, 3, 2, 1]
你有什么建议如何不再重复原来的列表,而只是改变它?
这根据要求改变原始数组。 nil
通过意识到列表的最后一个元素位于 list[list.length-1]
.
来消除
def reverse(list)
a = list.length-1
while a >= 0
list << list[a]
list.delete_at(a)
a = a - 1
end
list
end
p reverse([1, 2, 3]) #=> [3, 2, 1]
更Ruby的方法如下:
arr.sort_by!.with_index { |_,i| -i }
我知道列表要原地颠倒(变异)。下面是两种方法。
如果列表不发生变异,直接对副本进行操作:
def non_mutating_reverse(list)
reverse(list.dup)
end
#1
使用并行赋值(有时称为多重赋值)。
def reverse(list)
(list.size/2).times { |i| list[i], list[-1-i] = list[-1-i], list[i] }
list
end
list = [1,2,3]
reverse list #=> [3, 2, 1]
list #=> [3, 2, 1]
请注意,当列表的大小为奇数时(如本例所示),中间元素不会移动。
#2
def reverse(list)
list.replace(list.size.times.with_object([]) { |i,a| a.unshift(list[i]) })
end
list = [1,2,3]
reverse list #=> [3, 2, 1]
list #=> [3, 2, 1]
我正在尝试编写一种方法来反转列表,但不使用 .reverse。 这是我的代码:
def reverse(list)
a = list.length
while a >= 0
list << list[a]
a = a - 1
end
list
end
print reverse([1,2,3])
我的预期结果不是 [3,2,1],而是 [1, 2, 3, nil, 3, 2, 1]
你有什么建议如何不再重复原来的列表,而只是改变它?
这根据要求改变原始数组。 nil
通过意识到列表的最后一个元素位于 list[list.length-1]
.
def reverse(list)
a = list.length-1
while a >= 0
list << list[a]
list.delete_at(a)
a = a - 1
end
list
end
p reverse([1, 2, 3]) #=> [3, 2, 1]
更Ruby的方法如下:
arr.sort_by!.with_index { |_,i| -i }
我知道列表要原地颠倒(变异)。下面是两种方法。
如果列表不发生变异,直接对副本进行操作:
def non_mutating_reverse(list)
reverse(list.dup)
end
#1
使用并行赋值(有时称为多重赋值)。
def reverse(list)
(list.size/2).times { |i| list[i], list[-1-i] = list[-1-i], list[i] }
list
end
list = [1,2,3]
reverse list #=> [3, 2, 1]
list #=> [3, 2, 1]
请注意,当列表的大小为奇数时(如本例所示),中间元素不会移动。
#2
def reverse(list)
list.replace(list.size.times.with_object([]) { |i,a| a.unshift(list[i]) })
end
list = [1,2,3]
reverse list #=> [3, 2, 1]
list #=> [3, 2, 1]