I’ve started doing code puzzles from CodingBat. CodingBat is a project by Nick Parlante, a computer science lecturer at Stanford.
The idea being that if you want to build skill in running, what do you do? You run.
To build skill in code, write code.
With CodingBat Nick created an environment where people can concentrate on the coding with nothing else to get in the way. With all the surrounding structure taken care of, you can get a lot of coding practice done in just an hour or two.
Nick provides an easy way to flex your Java or Python muscles but no Swift. Well – why not do these in Swift 3 thanks to IBM’s Swift Sandbox.
The first puzzle I picked as a warm-up was in the Logic-1 section.
Since Swift is a synonym for Fast its appropriate we get caughtSpeeding.
The challenge has the following description:
You are driving a little too fast, and a police officer stops you.
Write code to compute the fine you would have to pay.
* If your speed is 60 or less, the result is 0 since there is no fine.
* If speed is between 61 and 80 inclusive, the fine is 100 dollars.
* If speed is 81 or more, the result is 200.
Unless it is a holiday — on that day, your speed can be 5 higher in all cases.
My test cases are:
print(caughtSpeeding(speed: 60, isHoliday: false))
print(caughtSpeeding(speed: 65, isHoliday: false))
print(caughtSpeeding(speed: 65, isHoliday: true))
print(caughtSpeeding(speed: 85, isHoliday: false))
Try it on your own.
My Swift 3 code is as follows:
I could have used a Switch statement instead of the three if statements on lines 19-21 but thought this was more readable. That’s a matter of style.
You can test this code on the IBM Swift Sandbox.
Great idea, thanks for the suggestion and link to IBM playbox. You’re awesome.