gpt4 book ai didi

ruby - Ruby 中的 Luhn 算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:47:00 24 4
gpt4 key购买 nike

我一直在尝试在 Ruby 中实现 Luhn 算法,但不断收到错误消息,指出无法将 nil 合并到 Fixnum 中。

Luhn 算法应该:

从倒数第二个数字开始,每隔一个数字加倍,直到达到第一个数字

将所有未碰过的数字和翻倍的数字相加(翻倍的数字需要拆开,10变成1+0)

如果总数是 10 的倍数,则您收到了有效的信用卡号!

这是我的:

class CreditCard
def initialize (card_number)
if (card_number.to_s.length != 16 )
raise ArgumentError.new("Please enter a card number with exactly 16 integars")
end
@card_number = card_number
@total_sum = 0
end

def check_card
@new_Array = []
@new_Array = @card_number.to_s.split('')
@new_Array.map! { |x| x.to_i }
@new_Array.each_with_index.map { |x,y|
if (y % 2 != 0)
x = x*2
end
}
@new_Array.map! {|x|
if (x > 9)
x = x-9
end
}
@new_Array.each { |x|
@total_sum = @total_sum + x
}
if (@total_sum % 10 == 0)
return true
else
return false
end
end
end

最佳答案

在你的部分

@new_Array.each_with_index.map { |x,y| 
if (y % 2 != 0)
x = x*2
end
}

更改不是永久性的。此外,正如 Victor 所写,如果测试失败,你的@new_Array 将被填充为 nils。最后

if (@total_sum % 10 == 0)
return true
else
return false
end

你可以直接写

@total_sum % 10 == 0

因为 ruby​​ 方法的最后一行已经是一个返回。我找到了一个 slightly different algorithm 并在这里实现了它:

# 1) Reverse the order of the digits in the number.
# 2) Take the first, third, ... and every other odd digit in the reversed digits
# and sum them to form the partial sum s1
# 3) Taking the second, fourth ... and every other even digit in the reversed digits:
# a) Multiply each digit by two (and sum the digits if the answer is greater than nine) to form partial sums for the even digits
# b) Sum the partial sums of the even digits to form s2
# 4) If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.

def luhn n
s = n.to_s.reverse
sum=0
tmp=0
(0..s.size-1).step(2) {|k| #k is odd, k+1 is even
sum+=s[k].to_i #s1
tmp = s[k+1].to_i*2
tmp = tmp.to_s.split(//).map(&:to_i).reduce(:+) if tmp>9
sum+=tmp
}
sum%10 == 0
end

[49927398716, 49927398717, 1234567812345678, 1234567812345670].each {|num|
puts "%20s %s" % [num, luhn(num)]
}

# 49927398716 true
# 49927398717 false
# 1234567812345678 false
# 1234567812345670 true

希望这对您有所帮助。

关于ruby - Ruby 中的 Luhn 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18138907/

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