Daily Programmer 239 Easy – Game of Threes


So, the latest Daily Programmer project I’m working on(I’ll get to finishing the last one, eventually) is this weeks Easy level project, Game of Threes.

This one wasn’t complicated, here’s the code.


def get_diff_from_multiple(n):
    """ Returns -1, 0, or 1, whichever will add to n to           
    make the sum divisible by 3
    """
    if n % 3 == 2:
        return 1
    elif n % 3 == 1:
        return -1
    elif n % 3 == 0:
        return 0

The core of the program is to either divide by three, or tweak the number to make it divisible by three.  The easiest way I saw was to just check how far it was from a multiple of three, and add the appropriate value.  It was pretty clear that modulus 3 would be the easy way- a remainder of 2, means adding 1 will make the number divisible by 3.  A remainder of 1, just subtract 1.  Remainder of 0, no change needed.

The function to play the game runs a loop until n reaches 1, outputting the appropriate status on each iteration of the loop.


def game_of_threes(n):
    """ Plays the game of threes with starting number n """

    while n > 1:
        diff = get_diff_from_multiple(n)
        print("{} {}".format(n, diff))
        n = (n + diff) // 3

    print(n)

There you go. Simple design for a simple project, though I’m sure there are some cleverer ways to do it.

Advertisements

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

%d bloggers like this: