luhn: add a test case#1246
Conversation
rpottsoh
left a comment
There was a problem hiding this comment.
At a quick glance your addition seems reasonable.
However, please increase second version component of the JSON file. If current version is x . y . z, make the new version x . y+1 . 0
| "expected": true | ||
| }, | ||
| { | ||
| "description": "strings with non-digits is invalid", |
There was a problem hiding this comment.
How is this new case different from "valid strings with a non-digit included become invalid"?
There was a problem hiding this comment.
package luhn
import "strings"
func Valid(str string) bool {
str = strings.Replace(str, " ", "", -1)
if len(str) < 2 {
return false
}
var sum = 0
for i, ch := range str {
val := int(ch - '0')
if (len(str)-i)%2 == 0 {
product := val * 2
if product > 9 {
product -= 9
}
sum += product
} else {
sum += val
}
}
return sum%10 == 0
}The code with a mistake above will pass current tests, but not this one.
So we have to check non-digits by adding:
if val > 9 || val < 0 {
return false
}There was a problem hiding this comment.
Thanks for the explanation. I can see now how "valid strings with a non-digit included become invalid" passes without the new test case.
Other reviewers may ask that your new test case be moved to an earlier location in the JSON file. I'll leave that open to others to address.
@idealhack thanks for your time in improving this exercise! 👍
|
@rpottsoh I've increased the minor version number, please take a look |
|
|
|
I think enough time has passed for others to convey their thoughts on this PR. I am going to go ahead and merge. Thanks @idealhack for giving some of your time to Exercism and making Luhn a better exercise. |
|
@rpottsoh You are welcome. Exercism is great because of your work. |
luhn 1.5.0 Continuation of #1246 #1246 placed a non-digit in a doubled position. However, there are some solutions which still pass all tests: They reject the above case, perhaps by being "clever" with integer division (results in 1 or 0 for digits, but other values for non-digits) but yet would incorrectly accept an input with a non-digit in non-doubled position This commit adds such an input.
https://github.com/exercism/problem-specifications/blob/master/exercises/luhn/description.md