gpt4 book ai didi

arrays - 在不使用长度的情况下获取数组的长度

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:00 26 4
gpt4 key购买 nike

在 exercism.io 上的一个完全人为的问题中,我的任务是想出一种方法来获取数组的长度/大小,而无需使用任何可枚举的方法。

我最初只是有:

  arr = [1,3,4]
ctr = 0
while arr[ctr]
ctr += 1
end
ctr

问题是我可以有 arr = Array.new(5),它是 [nil, nil, nil, nil, nil]

我找到了两种方法:

ctr = 0
loop do
element = arr.fetch(ctr) { 'outofbounds!' }
break if element == 'outofbounds!'
ctr += 1
end
ctr

我想在不使用 Array#fetch 的情况下执行此操作,因为索引越界很可能是在查看已知长度(我再次尝试实现)。

另一种解决方案:

  ctr = 0
copy = arr.dup
while copy != []
ctr += 1
copy.pop
end
ctr

这感觉有点正确,但是 Array 上的 == 首先检查长度,然后检查每个元素上的 ==。我正在尝试实现长度,所以再次卡住。

最佳答案

这里有一个故意在那里的解决方案,因为这个问题是一个不使用核心 API 做事的练习:

def array_length(a)
b = a.dup
c = [ ]
f = 0

while (b != [ ])
c.push('')
b.pop
f = 1
end

e = c.join("\x01").to_s.unpack('C*')

while (e[0])
f += e.pop
end

f
end

关于arrays - 在不使用长度的情况下获取数组的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47148950/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com