gpt4 book ai didi

arrays - 使用数字作为默认索引

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

我有一个合理大小的数组,

a = ("a".."z").to_a

我想使用一个特定的默认数字,当用于调用一个值作为索引时(实际上)总是返回 nil

a[some_default_index] # => nil

对于固定的a,我可以设置一个等于或大于a大小的固定数作为默认数,但是a 各不相同。

我尝试了 Float::NANFloat::Infinity,但没有按我的预期工作。

a[Float::NAN] # => out of range error
a[Float::Infinity] # => out of range error

我可以使用什么数字作为索引?

最佳答案

最大正确索引

这是@AndrewGrimm 的优秀 answer 的改编版本:

a = ("a".."z").to_a

start = Time.now
largest_correct_index = 1
smallest_incorrect_index = nil

until smallest_incorrect_index == largest_correct_index + 1
if smallest_incorrect_index.nil?
next_number_to_try = largest_correct_index * 1000
else
next_number_to_try = (smallest_incorrect_index + largest_correct_index) / 2 # Geometric mean would be more efficient, but more risky
end

if next_number_to_try <= largest_correct_index ||
smallest_incorrect_index && next_number_to_try >= smallest_incorrect_index
raise "Can't happen case"
end

begin
a[next_number_to_try]
largest_correct_index = next_number_to_try
rescue RangeError
smallest_incorrect_index = next_number_to_try
end
end

finish = Time.now
puts "The largest correct index is #{largest_correct_index}"
puts "The smallest incorrect index is #{smallest_incorrect_index}"
puts "Calculation took #{finish - start} seconds"

在 32 位 Ruby 上,它返回 2**31-1:

The largest correct index is 2147483647
The smallest incorrect index is 2147483648
Calculation took 0.0 seconds

在 64 位 Ruby 和 JRuby 上,它返回 2**63-1:

The largest correct index is 9223372036854775807
The smallest incorrect index is 9223372036854775808
Calculation took 0.000250378 seconds

所以它看起来像@akuhn 的answer在大多数情况下应该足够好。

备选

根据您的需要,您还可以使用散列:

a = ('a'..'z').to_a
# ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

h = ('a'..'z').map.with_index { |l, i| [i, l] }.to_h
# {0=>"a", 1=>"b", 2=>"c", 3=>"d", 4=>"e", 5=>"f", 6=>"g", 7=>"h", 8=>"i", 9=>"j", 10=>"k", 11=>"l", 12=>"m", 13=>"n", 14=>"o", 15=>"p", 16=>"q", 17=>"r", 18=>"s", 19=>"t", 20=>"u", 21=>"v", 22=>"w", 23=>"x", 24=>"y", 25=>"z"}

require 'fruity'

compare do
_array { a[rand(26)] }
_hash { h[rand(26)] }
end

它似乎不会对性能产生负面影响:

Running each test 16384 times. Test will take about 1 second.
_array is similar to _hash

所有这些:

h[-1]
h[:default]
h[Float::INFINITY]
h[2**1024-1]

将返回nil

关于arrays - 使用数字作为默认索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41818426/

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