From the book Think Like a Programmer (emphasis mine)
The Luhn formula is a widely used system for validating identification numbers. Using the original number, double the value of every other digit. Then add the values of the individual digits together (if a doubled value now has two digits, add the digits individually). The identification number is valid if the sum is divisible by 10. Write a program that takes an identification number of arbitrary length and determines whether the number is valid under the Luhn formula. The program must process each character before reading the next one.
In a broader sense, what does it mean to process each character before reading the next one? What does this look like syntactically? What does the opposite mean and what does it look like syntactically?
Update:
For some background, here's my attempt at the problem (in JavaScript):
Array.prototype.sum = function() {
var sum = 0,
itemCount = this.length,
i;
for(i = 0; i <= itemCount - 1; i++) {
sum += this[i];
}
return sum;
}
function validateNumberWithLuhnForumla(number) {
var numbersArray = number.toString().split(''),
numberCount = numbersArray.length,
i = 0,
isValid = false,
doubledDigit,
checksum,
numbersToSum = [];
for(i = 0; i <= numberCount - 1; i++) {
if(i % 2 > 0 && i > 0) {
doubledDigit = numbersArray[i] * 2;
if(doubledDigit > 9) {
numbersToSum.push(1, (doubledDigit - 10));
} else {
numbersToSum.push(doubledDigit);
}
}
}
checkSum = numbersToSum.sum();
if(checkSum % 10 === 0) {
isValid = true;
}
return isValid;
}
foreach(c in input)state=calcSomething(state, c);
– ratchet freak May 18 '13 at 19:34