Two steps forward and one step back

15

1

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.

Example:

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.

Example results:

1      =>  3
5      =>  11
9      =>  23
10     =>  26
11     =>  29
100    =>  296
1000   =>  2996
10000  =>  29996
100000 =>  299996

Have fun, golfers!

AJFaraday

Posted 2018-03-26T13:02:36.007

Reputation: 10 466

7Hmm ... this feels very familiar. – Shaggy – 2018-03-26T13:14:41.163

3Related – Rod – 2018-03-26T13:22:35.197

@Rod Hooray! I got away with it! ;) – AJFaraday – 2018-03-26T13:23:33.670

Yep, that looks like the one I was thinking of, @Rod. – Shaggy – 2018-03-26T15:05:33.167

@Shaggy Rod changed his comment a little. The earlier one noted that the snails/wells question is asking for the number of iterations, but this is asking for the distance covered. – AJFaraday – 2018-03-26T21:03:08.527

Answers

5

Oasis, 5 4 bytes

1 byte saved thanks to @Adnan

3+23

Not to be confused with 23+3

Try it online!

How?

      implicitly push a(n-1)
3     push 3
 +    sum and implicitly print
  2   a(2) = 2
   3  a(1) = 3

Uriel

Posted 2018-03-26T13:02:36.007

Reputation: 11 708

1You can leave out the b. – Adnan – 2018-03-26T17:07:28.050

I think you meant to multiply with 3, not add it. – Erik the Outgolfer – 2018-03-26T17:17:05.520

@EriktheOutgolfer The program computes a(n) as a(n-1)+3. – Dennis – 2018-03-26T17:18:43.323

12

Python 2, 18 bytes

lambda n:3*n-1%n*4

Try it online.

I picked this trick up from xnor just a few days ago…!

Lynn

Posted 2018-03-26T13:02:36.007

Reputation: 55 648

11

Python 2, 20 bytes

lambda n:n*3-4*(n>1)

Try it online!

Rod

Posted 2018-03-26T13:02:36.007

Reputation: 17 588

10

Python 2, 17 bytes

lambda n:n-3%~n*2

Try it online!

I found the expression by brute-force search. It effectively computes n+2*abs(n-2).

xnor

Posted 2018-03-26T13:02:36.007

Reputation: 115 687

9

Polyglot: Java 8 / JavaScript / C# .NET, 16 14 12 bytes

n->3*n-1%n*4

Try it online (Java 8).

n=>3*n-1%n*4

Try it online (JavaScript).
Try it online (C# .NET).

Port of @Lynn's Python 2 answer, so make sure to upvote his/her answer.


Old answer:

Polyglot: Java 8 / JavaScript / C# .NET, 16 14 bytes

n->n<2?3:n*3-4

Try it online (Java 8).

n=>n<2?3:n*3-4

Try it online (JavaScript).
Try it online (C# .NET).

Explanation:

n->       // Method with integer as both parameter and return-type
  n<2?    //  If the input is 1:
   3      //   Return 3
  :       //  Else:
   n*3-4  //   Return the input multiplied by 3, and subtract 4

Kevin Cruijssen

Posted 2018-03-26T13:02:36.007

Reputation: 67 575

JavaScript polyglot, if you use a fat arrow. – Shaggy – 2018-03-26T15:19:21.747

@Shaggy Added, as well as C# .NET :) Although n=>(--n*3||4)-1 is also possible in JavaScript (also 14 bytes). – Kevin Cruijssen – 2018-03-26T16:06:18.863

7

05AB1E, 8 7 bytes

3*s≠i4-

Try it online!

-1 byte thanks to Emigna !

Kaldo

Posted 2018-03-26T13:02:36.007

Reputation: 1 135

@LuisMendo Thanks, fixed ! – Kaldo – 2018-03-26T13:35:57.617

23*s≠i4- saves a byte – Emigna – 2018-03-26T13:59:43.223

@Emigna Thanks ! – Kaldo – 2018-03-26T14:12:13.160

7

R, 20 bytes

N=scan();3*N-4*(N>1)

Try it online!

Didn't notice the pattern until after I had implemented my less elegant solution.

Giuseppe

Posted 2018-03-26T13:02:36.007

Reputation: 21 077

3Congrats on 10k BTW! – Luis Mendo – 2018-03-26T13:23:38.120

4@LuisMendo thanks! I think my one-year anniversary on the site was a couple days ago, so it's been a good week for me, PPCG-wise. – Giuseppe – 2018-03-26T13:47:31.160

3@Giuseppe I know the feeling: 20k last week, as well as 2nd year anniversary. :) – Kevin Cruijssen – 2018-03-26T14:31:04.917

6

Oasis, 5 bytes

¹y4-3

Explanation:

    3  defines f(1) = 3
¹y4-   defines f(n) as:
¹      push input
 y     triple
  4-   subtract four

Try it online!

Okx

Posted 2018-03-26T13:02:36.007

Reputation: 15 025

5

Haskell, 15 bytes

f 1=3
f n=3*n-4

Try it online!

musicman523

Posted 2018-03-26T13:02:36.007

Reputation: 4 472

5

Standard ML, 16 bytes

fn 1=>3|n=>3*n-4

Try it online!

musicman523

Posted 2018-03-26T13:02:36.007

Reputation: 4 472

5

Dodos, 27 bytes

	dot D
D
	
	d d
	d d
d
	dip

Try it online!

Dennis

Posted 2018-03-26T13:02:36.007

Reputation: 196 637

4

Jelly, 6 bytes

++_>¡4

Try it online!

Erik the Outgolfer

Posted 2018-03-26T13:02:36.007

Reputation: 38 134

4

Prolog (SWI), 21 bytes

1*3.
X*Y:-Y is 3*X-4.

Try it online!

Emigna

Posted 2018-03-26T13:02:36.007

Reputation: 50 798

4

MATL, 7 bytes

Uses the 3*n-4*(n>1) formula. Multiply input by 3 (3*), push input again (G) and decrement it (q). If the result is not zero (?) then subtract 4 from the result (4-).

3*Gq?4-

Try it online!

David

Posted 2018-03-26T13:02:36.007

Reputation: 1 316

6 bytes porting Dennis' Jelly answer 2-|EG+ – Giuseppe – 2018-03-27T19:26:55.117

4

Jelly, 4 bytes

ạ2Ḥ+

Try it online!

How it works

ạ2Ḥ+  Main link. Argument: n

ạ2    Absolute difference with 2; yield |n-2|.
  Ḥ   Unhalve/double; yield 2|n-2|.
   +  Add; yield 2|n-2|+n.

Dennis

Posted 2018-03-26T13:02:36.007

Reputation: 196 637

3

><>, 10 9 bytes

Saved 1 byte thanks to Jo King

3*:3)4*-n

Try it online!

Emigna

Posted 2018-03-26T13:02:36.007

Reputation: 50 798

9 bytes – Jo King – 2018-03-27T00:48:16.590

@JoKing: Don't kow how I missed that. Thanks! – Emigna – 2018-03-27T06:30:21.103

3

APL (Dyalog), 9 bytes

3∘×-4×1∘<

Try it online!

Uriel

Posted 2018-03-26T13:02:36.007

Reputation: 11 708

3

C (gcc), 20 bytes

f(n){n=3*n-4*!!~-n;}

Try it online!

Jonathan Frech

Posted 2018-03-26T13:02:36.007

Reputation: 6 681

Alternative with the same byte-count: f(n){n=n<2?3:n*3-4;} – Kevin Cruijssen – 2018-03-26T17:38:06.907

Another alternative with the same byte count: f(n){n=n*3-4*(n>1);} – MD XF – 2018-03-26T21:39:51.590

3

MachineCode on x86_64, 34 32 24 bytes

8d47fe9931d029d08d0447c3

Requires the i flag for integer output; input is taken via manually appending to the code.

Try it online!


I went through these 4 different C functions to find the 24-byte MachineCode program:

  • n+2*abs(n-2) = 8d47fe9931d029d08d0447c3 (24 bytes)
  • 3*n-4*!!~-n = 8d047f31d2ffcf0f95c2c1e20229d0c3 (32 bytes)
  • n*3-4*(n>1) = 31d283ff028d047f0f9dc2c1e20229d0c3 (34 bytes)
  • n<2?3:n*3-4 = 83ff01b8030000007e068d047f83e804c3 (34 bytes)

MD XF

Posted 2018-03-26T13:02:36.007

Reputation: 11 605

so what exactly is this language? – qwr – 2018-03-28T05:52:01.510

@qwr Check out the README in the repository for a simple description. – MD XF – 2018-03-28T20:39:10.670

2

4, 54 bytes

3.6010160303604047002020003100000180010202046000095024

Try it online!

If you question the input method, please visit first the numerical input and output may be given as a character code meta post.

Uriel

Posted 2018-03-26T13:02:36.007

Reputation: 11 708

Why was this downvoted? – Uriel – 2018-03-26T14:17:30.407

Because the answer appears to be one quarter, which isn't a valid result. As far as I can tell, it doesn't solve the problem. – AJFaraday – 2018-03-26T14:22:53.327

@AJFaraday it uses byte input and output, which is valid by meta consensus. see the explanation inside the input section – Uriel – 2018-03-26T14:26:38.407

Any resources on how to interpret the result? Or the input? – AJFaraday – 2018-03-26T14:27:29.917

1@AJFaraday the char code of the result is the answer. I've edited the question to include the relevant meta post. 4 has only char input. – Uriel – 2018-03-26T14:30:33.897

2

Japt, 7 bytes

A port of Lynn's Python solution.

*3É%U*4

Try it


Alternative

This was a fun alternative to the closed formula solutions that is, unfortunately, a byte longer:

_+3}gN³²

Try it

Shaggy

Posted 2018-03-26T13:02:36.007

Reputation: 24 623

2

TI-Basic, 8 bytes

3Ans-4(Ans>1

Timtech

Posted 2018-03-26T13:02:36.007

Reputation: 12 038

2

05AB1E, 4 bytes

Uses the abs-method from Dennis' Jelly answer

2α·+

Try it online!

Explanation

2α      # abs(input, 2)
  ·     # multiply by 2
   +    # add input

Emigna

Posted 2018-03-26T13:02:36.007

Reputation: 50 798

2

65816 machine code, 22 bytes

I could have made this 65C02 machine code easily for 3 bytes less, but didn't, since the register size on the 65C02 is 8-bit instead of 16-bit. It would work, but it's boring because you can only use really low numbers ;-)

xxd dump:

00000000: 7aa9 0000 aa89 0100 d004 8888 e824 c8e8  z............$..
00000010: 1ac0 0000 d0ef                           ......

disassembly / code explanation:

; target is on the stack
  ply              7A                  ; pull target from stack
  lda #$0000       A9 00 00            ; set loop counter to 0
  tax              AA                  ; set step counter to 0
loop:
  bit #$0001       89 01 00            ; sets Z if loop counter is even
  bne odd          D0 04               ; if Z is not set, jump to 'odd'
  dey              88                  ; decrement target twice
  dey              88
  inx              E8                  ; increment step counter
  .byte $24        24                  ; BIT $xx opcode, effectively skips the next byte
odd:
  iny              C8                  ; increment target

  inx              E8                  ; increment step counter
  inc a            1A                  ; increment loop counter

  cpy #$0000       C0 00 00            ; sets zero flag, can be optimized maybe?
  bne loop         D0 EF               ; if Y is non-zero, loop

; result is in register X

Testing it out on a 65816-compatible emulator:

testing

2xsaiko

Posted 2018-03-26T13:02:36.007

Reputation: 699

1

Python 3, 48 bytes

def a(x):
    if x!=1:
        return((3*x)-4)
    return(3)

Try It Online!

Nathan Dimmer

Posted 2018-03-26T13:02:36.007

Reputation: 511

Nice work. You might want to put some code in the “Footer” section, too. That way you can test your function without padding out your golf entry... – AJFaraday – 2018-03-26T21:06:39.320

@AJFaraday The footer of my post or of my code? – Nathan Dimmer – 2018-03-26T21:12:00.337

On Try It Online; you can add a footer which runs with your code but doesn’t count towards the byte length. Then the output will show your code at work. – AJFaraday – 2018-03-26T21:16:44.897

25 bytes – Jo King – 2018-03-27T00:16:58.360

@JoKing Do you know of a good guide to lambda functions in Python? I really don't understand how the syntax works. – Nathan Dimmer – 2018-03-27T00:32:30.470

The variables directly after the lambda are equivalent to def e.g. a=lambda x,y is the same as def a(x,y). Imagine there's also a return directly after the :, and other than that it's basically the same. def a(x,y): return x+y is the same as a=lambda x,y: x+y – Jo King – 2018-03-27T00:40:35.627

How do the brackets work? Are they if statement equivalents? If not, can you do ifs and loops in a lambda function? – Nathan Dimmer – 2018-03-27T01:16:53.457

It's a list of two elements, where the conditional returns True/False which is equivalent to 1/0, deciding which element is returned. A less golfier, but more readable construction is to use an inline if e.g. Try it online!. If you want to check out more python golfing tips, check out this question

– Jo King – 2018-03-27T06:39:01.983

1

SHELL , 28 Bytes

F(){ bc<<<$1*3-$(($1>1))*4;}

Tests :

F 1
3

F 2
2

F 3
5

F 4
8

F5
11

F 11
29

F 100
296

F 100000
299996

Explanation :

The formula is :

if n == 1  ==> F(1) = 3
else F(n) = 3*n - 4

following the sequence of 3 steps "Two steps forward and one step back", we will have the arithmetic series :

 +2  2 => 2  ( or 6 )
 -1  1 => 3
 -----------
 +2  3 => 5  ( or 9 )
 -1  2 => 6
 -----------
 +2  4 => 8  ( or 12 )
 -1  3 => 9
 -----------
 +2  5 => 11 ( or 15 )
 -1  4 => 12
 -----------
 +2  6 => 14 ( or 18 )
 -1  5 => 15 
 -----------
 +2  7 => 17 ( or 21 )
 -1  6 => 18

At the minimum, or first coincidence :

 1 => 3
 2 => 2
 3 => 5
 4 => 8
 5 => 11
 6 => 14

in one formula :

F(n) = 3*n - 4(n>1)     with n>1 is 1 or 0 (if n==1)

Ali ISSA

Posted 2018-03-26T13:02:36.007

Reputation: 211

please describe which shell this is – qwr – 2018-03-27T22:27:16.770

tested on Cygwin ( CYGWIN_NT-10.0 2.3.1(0.291/5/3) 2015-11-14 12:44 x86_64 Cygwin) – Ali ISSA – 2018-03-28T05:36:16.157

can you write it in bc directly? – qwr – 2018-03-28T05:51:01.070

I'm not familiar with bc, but since the argument of the function ($1) is used several times and some shell-specific stuff (arithmetic expansion, $((…))) is done, probably not. – 2xsaiko – 2018-03-28T18:29:11.640

1F(){bc<<<$1*3-$(($1>1))*4} works in zsh though and removes 2 bytes – 2xsaiko – 2018-03-28T18:35:16.930

1

J, 9 bytes

3&*-4*1&<

Try it online!

Galen Ivanov

Posted 2018-03-26T13:02:36.007

Reputation: 13 815

1

MATLAB/Octave, 15 bytes

@(n)3*n-4*(n>1)

Try it online!

Kind of surprised there isn't already a MATLAB answer. Same algorithm of 3*n-4 if greater than 1, or 3*n otherwise.

Tom Carpenter

Posted 2018-03-26T13:02:36.007

Reputation: 3 990

1

Brain-Flak, 38 bytes

({<([()()]{})>()(){(<((){})>)()}{}}{})

Try it online!

The first answer I see to calculate the answer by stepping back and forth.

({ while not at 0
  <([()()]{})>()() take two steps forward, counting 2 steps
  {(<((){})>)()}{} take one step back, if not at 0, and add 1 step
}{}) remove the 0 and push step sum

MegaTom

Posted 2018-03-26T13:02:36.007

Reputation: 3 787

1

W d, 7 bytes

♦óÖ╣░Θ$

Explanation

3*1a<4*-

Evaluates (a*3)-4*(a>1).

Another possible alternative

3*1am4*-

Evaluates (a*3)-4*(1%a).

user85052

Posted 2018-03-26T13:02:36.007

Reputation:

0

Ruby, 14 bytes

->n{3*n-1%n*4}

Try it online!

Uses the 1%1==0 trick as seen in other answers here.

Reinstate Monica -- notmaynard

Posted 2018-03-26T13:02:36.007

Reputation: 1 053