Swift 3 Fight Club: Challenge Day 1

new-swift-sport1

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:

caughtSpeeding

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.

 

One thought on “Swift 3 Fight Club: Challenge Day 1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s