Skip to content

Instantly share code, notes, and snippets.

@imran3
Last active September 23, 2020 10:57
Show Gist options
  • Save imran3/7cb3b914c58a988cc3f770615736ef10 to your computer and use it in GitHub Desktop.
Save imran3/7cb3b914c58a988cc3f770615736ef10 to your computer and use it in GitHub Desktop.
Review a sequence of digits and find the sum of all digits that match the next digit in the list.
/*
Problem:
Review a sequence of digits and find the sum of all digits that match the next digit in the list.
The list is circular, so the digit after the last digit is the first digit in the list.
Input samples:
1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2) matches
the fourth digit.
1111 produces 4 because each digit (all 1) matches the next.
1234 produces 0 because no digit matches the next.
91212129 produces 9 because the only digit that matches the next one is the last digit, 9.
*/
//Solution
function compute(input: string): number {
if(input.length <= 1) return 0
let sum = compareDigits(Number(input[0]), Number(input[input.length-1]))
for(let i=0; i < input.length -1; i++)
sum += compareDigits(Number(input[i]), Number(input[i+1]))
return sum
}
function compareDigits(a: number, b:number): number {
return a == b ? a : 0
}
// Main and Tests
function main(): void {
const inputs = ["1122", "1111", "1234", "91212129", "", "1", "115542"]
const expected = [3, 4, 0, 9, 0, 0, 6]
test(inputs, expected);
}
function test(inputs: string[], expected: number[]): void {
for(let i=0; i < inputs.length; i++){
const res = compute(inputs[i].trim());
console.log("INPUT", inputs[i])
console.log("EXPECTED:", expected[i], "\tACTUAL", res)
}
}
// Run
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment