Let's say I'm ten steps away from my destination. I walk there following the old saying, "Two steps forward and one step back". I take two steps forward, one back, until I'm standing exactly on my destination. (This might involve stepping past my destination, and returning to it). How many steps did I walk?
Of course, I might not be 10 steps away. I might be 11 steps away, or 100. I could measure ten paces, and keep walking back and forth to solve the problem, or... I could write some code!
- Write a function to work out how many steps it takes to get N steps away, in the sequence: two steps forward, one step back.
- Assume you've started at step 0. Count the "two steps forward" as two steps, not one.
- Assume all steps are a uniform length.
- It should return the number of steps first taken when you reach that space. (For instance, 10 steps away takes 26 steps, but you'd hit it again at step 30). We're interested in the 26.
- Use any language you like.
- It should accept any positive integer as input. This represents the target step.
- Smallest number of bytes win.
I want to get 5 steps away:
| | | | | | <- I'm at step 0, not yet on the grid. | |X| | | | <- I take two steps forward, I'm on step 2: the count is 2 |X| | | | | <- I take one step back, I'm on step 1: the count is 3 | | |X| | | <- I take two steps forward, I'm on step 3: the count is 5 | |X| | | | <- I take one step back, I'm on step 2 again: the count is 6 | | | |X| | <- I take two steps forward, I'm on step 4: the count is 8 | | |X| | | <- I take one step back, I'm on step 3 again: the count is 9 | | | | |X| <- I take two steps forward, I'm on step 5: the count is 11
In this case, the result of the function would be 11.
1 => 3 5 => 11 9 => 23 10 => 26 11 => 29 100 => 296 1000 => 2996 10000 => 29996 100000 => 299996
Have fun, golfers!