Last active
June 27, 2016 11:59
-
-
Save AlinaWithAFace/bfe376ce32a374b31e4b53bbb8253bea to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
https://goo.gl/z0Rk3j | |
Written in JavaScript | |
Background | |
Back in middle school, I had a peculiar way of dealing with super boring classes. I would take my handy pocket calculator and play a "Game of Threes". Here's how you play it: | |
First, you mash in a random large number to start with. Then, repeatedly do the following: | |
If the number is divisible by 3, divide it by 3. | |
If it's not, either add 1 or subtract 1 (to make it divisible by 3), then divide it by 3. | |
The game stops when you reach "1". | |
While the game was originally a race against myself in order to hone quick math reflexes, it also poses an opportunity for some interesting programming challenges. Today, the challenge is to create a program that "plays" the Game of Threes. | |
Challenge Description | |
The input is a single number: the number at which the game starts. Write a program that plays the Threes game, and outputs a valid sequence of steps you need to take to get to 1. Each step should be output as the number you start at, followed by either -1 or 1 (if you are adding/subtracting 1 before dividing), or 0 (if you are just dividing). The last line should simply be 1. | |
Input Description | |
The input is a single number: the number at which the game starts. | |
100 | |
Output Description | |
The output is a list of valid steps that must be taken to play the game. Each step is represented by the number you start at, followed by either -1 or 1 (if you are adding/subtracting 1 before dividing), or 0 (if you are just dividing). The last line should simply be 1. | |
100 -1 | |
33 0 | |
11 1 | |
4 -1 | |
1 | |
Challenge Input | |
31337357 | |
*/ | |
var x = 31337357; | |
// var x = prompt("Pick a number, any number!"); | |
var GameofThrees = function(x) { | |
// Create a function to hold everything | |
while (x != 1) { | |
// Create a while loop to keep running the function until the number is 1 | |
if (x % 3 === 0){ | |
console.log(x + " 0"); | |
x/=3 | |
// If the function is evenly divisible by 3, divide and reassign | |
} else if (((x + 1)/3) % 1 === 0){ | |
console.log(x + " 1"); | |
x ++; | |
// Otherwise, if adding 1 makes it evenly divisible by 3, do that | |
} else { | |
console.log(x + " -1"); | |
x--; | |
// Otherwise, subtract 1 and repeat until it equals 1 | |
} | |
} | |
console.log(x); | |
// Print out the final "1" | |
}; | |
GameofThrees(x); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment