gpt4 book ai didi

javascript - AEMO 校验和 Ruby 代码

转载 作者:行者123 更新时间:2023-12-03 04:56:42 25 4
gpt4 key购买 nike

我不会编写 Ruby 代码,但我找到了这个 Ruby 代码来计算 AEMO NMI 的校验和

def checksum
summation = 0
@nmi.reverse.split(//).each_index do |i|
value = nmi[nmi.length - i - 1].ord
value *= 2 if i.even?
value = value.to_s.split(//).map(&:to_i).reduce(:+)
summation += value
end
checksum = (10 - (summation % 10)) % 10
checksum
end

有人可以帮我解释一下这行代码的含义吗?

value = value.to_s.split(//).map(&:to_i).reduce(:+)

我尝试将上面的代码转换为 Excel 的 VBA。

输入“4103738516”将为您提供 8“4102030716”==> 2“QFFF0000LV”==>7

本文档第 40 页有 JavaScript 代码来计算它,但我无法理解该代码。

https://www.aemo.com.au/-/media/Files/PDF/0610-0008-pdf.pdf

谢谢

最佳答案

下面的代码应该可以让您更好地理解该声明:

# Say
value = 82478923 # any random number
value.to_s # => "82478923"

# `split(//)` is similar to `split` and `split('')`, they split a string after each character to generate an array of characters.
ary = value.to_s.split(//) # => ["8", "2", "4", "7", "8", "9", "2", "3"]

ary.map(&:to_i) # => [8, 2, 4, 7, 8, 9, 2, 3]

# `inject(:+)` will iterate the array and calculate sum of all numbers
ary.map(&:to_i).inject(:+) # => 43

了解更多关于inject的信息在这里。

关于javascript - AEMO 校验和 Ruby 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42405684/

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