Published
- 1 min read
CodeWars - Catching Car Mileage Numbers
Problem
You need to identify “interesting” numbers.
When the number is interesting return 2, if it is “near” an interesting number return 1 and if it is not interesting return 0
Original Problem: //https://www.codewars.com/kata/52c4dd683bfd3b434c000292/train/typescript
Comments problem definition
When looking at the rules of the “interesting numbers” you will notice that there is a redundant rule:
- Every digit is the same number: 1111
- The digits are a palindrome: 1221 or 73837
When every digit is the same number, it is a palindrome. Thus a special check for it would be unneeded.
In a real life scenario you would have to clarify if both features need to be implemented or not.
Approaching the solution
Every rule can be written as a function const rule = (n:number) => boolean
. This makes it ideal to experiment with Test Driven Development.
For the rule “Any digit followed by all zeros: 100, 90000”. We can write following code:
1. Step: Minimal Code
CatchingCarMileageNumbers.ts
:
export const isNumberFollowedByZeros = (n: number) => {}
2. Step: Write Tests
CatchingCarMileageNumbers.test.ts
:
it('tests for Numbers Followed by Zeros', () => {
expect(isNumberFollowedByZeros(1000)).toBe(true)
expect(isNumberFollowedByZeros(10020)).toBe(false)
expect(isNumberFollowedByZeros(1336)).toBe(false)
})
3. Step: Implementation
Now we can implement the function to pass the test:
export const isNumberFollowedByZeros = (n: number) => {
const match = `${n}`.match(/^\d0*$/)
return match !== null
}
Code Solution
Full Solution can be found here: https://github.com/CodeAndChaos/training-typescript/tree/main/src/CodeWars/4kyu