Duck, Duck, Josephus

49

4

Given an Integer array:

  1. Start from the first number
  2. Jump forward n positions where n is the value of the current position
  3. Delete the current position, making what was the next position the current position.
  4. Goto step 2 until there is one number remaining
  5. Print that number

Rules

The array wraps-around (the next number after the last number in the array is the first number).

A zero removes itself (Obviously).

Negative numbers are not allowed as input.

Test Cases

[1] => 1
[1,2] => 1
[1,2,3] => 3
[1,2,2] => 1
[1,2,3,4] => 1
[6,2,3,4] => 4
[1,2,3,4,5] => 5
[0,1] => 1
[0,0,2,0,0] => 0

Step-by-step example

[1,4,2,3,5]
 ^          start from the first position
   ^        jump 1 position (value of the position)
[1,  2,3,5] remove number in that position
     ^      take next position of the removed number (the 'new' 'current' position)
         ^  jump 2 positions
[1,  2,3  ] remove number in that position
 ^          take next position (looping on the end of the array)
     ^      jump 1 position
[1,    3  ] remove number in that position
       ^    take next position (looping)
 ^          jump 3 positions (looping on the end of the array)
[      3  ] remove number in that position
print 3

Example #2

[4,3,2,1,6,3]
 ^            start from the first position
         ^    jump 4 positions
[4,3,2,1,  3] remove number in that position    
           ^  take next position
     ^        jump 3 positions
[4,3,  1,  3] remove number in that position    
       ^      take next position
           ^  jump 1 positions
[4,3,  1    ] remove number in that position    
 ^            take next position
   ^          jump 4 positions
[4,    1    ] remove number in that position    
       ^      take next position
 ^            jump 1 position
[      1    ] remove number in that position
print 1

This is , the shortest answer in bytes wins!

workoverflow

Posted 2017-12-12T13:47:34.180

Reputation: 1 025

14Nice first challenge! – Luis Mendo – 2017-12-12T13:49:20.387

2@LuisMendo Yes.. the "skip like a..." challenges – J42161217 – 2017-12-12T13:58:37.770

2@Jenny_mathy I didn't think there would be a similar one, but as Luis said, the wraparound array makes an interesting challenge for golfing. I think :/ – workoverflow – 2017-12-12T14:00:15.497

1Related, but I don't think it's a duplicate – Luis Mendo – 2017-12-12T14:09:59.270

1closely related (dupe?) – Erik the Outgolfer – 2017-12-12T14:11:46.790

3@EriktheOutgolfer Not really a dupe. The elements there are indistinguishable and the step size is fixed. Luis's is much closer, but still sufficiently different I think. – Martin Ender – 2017-12-12T14:12:16.947

3Does it need to actually print the final number, or can it just return it? Does it need to actually return the number, or can it just operate on the array in-place so the after the function is run, the array contains just the number? – Reinstate Monica -- notmaynard – 2017-12-12T16:48:10.297

1

@iamnotmaynard, see this consensus.

– Shaggy – 2017-12-12T21:35:27.223

Answers

9

Husk, 7 bytes

This returns the result as a singleton list

ΩεSotṙ←

Try it online!

Explanation

Ω               Until
 ε              the result is a singleton list
     ṙ          Rotate left by
  S   ←         the first element
   ot           Then remove the first element  

H.PWiz

Posted 2017-12-12T13:47:34.180

Reputation: 10 962

7

Haskell, 54 50 48 bytes

f[x]=x
f(x:r)=f$snd<$>zip r(drop(x+1)$cycle$x:r)

Try it online!

Explanation:

  • f[x]=x: If the given list is a singleton list, return its element.
  • f(x:r)=f$ ...: Otherwise recursively apply f to the following list:
    • The elements of the current list cycled infinitely (cycle$x:r),
    • with the first x+1 elements removed (drop(x+1)$),
    • and truncated to length of r. (snd<$>zip r is a shorter alternative to take(length r)).

Previous 54 byte version:

f=(%)=<<head
_%[x]=x
n%(x:r)|n<1=f r|s<-r++[x]=(n-1)%s

Try it online!

Laikoni

Posted 2017-12-12T13:47:34.180

Reputation: 23 676

7

Ruby, 37 bytes

->r{r.rotate!(r[0]).shift while r[1]}

Modifies the array in-place, which appears to be acceptable as output. Try it online!

Reinstate Monica -- notmaynard

Posted 2017-12-12T13:47:34.180

Reputation: 1 053

6

MATL, 21 bytes

1`yy)+ynX\[]w(5Mynq]x

Try it online! Or verify all test cases.

Explanation

1        % Push 1: current position in the array
`        % Do...while
  yy     %   Duplicate top two elements in the stack. Takes input implicitly
         %   in the first iteration.
         %   STACK: array, position, array, position
  )      %   Get specified entry in the array
         %   STACK: array, position, selected entry
  +      %   Add
         %   STACK: array, position (updated)
  y      %   Duplicate from below
         %   STACK: array, position, array
  n      %   Number of elements of array
         %   STACK: array, position, number of elements or array
  X\     %   1-based modulus
         %   STACK: array, position (wrapped around)
  []     %   Push empty array
         %   STACK: array, position, []
  w      %   Swap
         %   STACK: array, [], position
  (      %   Write value into specified entry in array. Writing [] removes
         %   the entry
         %   STACK: array (with one entry removed)
  5M     %   Push latest used position. Because of the removal, this now
         %   points to the entry that was after the removed one
         %   STACK: array, position
  y      %   Duplicate from below
         %   STACK: array, position, array
  n      %   Number of elements of array
         %   STACK: array, position, number of elements of array
  q      %   Subtract 1
         %   STACK: array, position, number of elements of array minus 1
]        % End. If top of the stack is nonzero, proceed with next iteration
         % STACK: array (containing 1 entry), position
x        % Delete. Implicitly display
         % STACK: array (containing 1 entry)

Luis Mendo

Posted 2017-12-12T13:47:34.180

Reputation: 87 464

1Note: using list rotations instead of keeping a pointer will probably make this much shorter. – Erik the Outgolfer – 2017-12-12T18:02:43.957

1@Erik Thanks. But now that I added the explanation I think I’ll leave it like this – Luis Mendo – 2017-12-12T19:18:28.470

Well, you can always remove the explanation, it will be kept in the history :) – Erik the Outgolfer – 2017-12-12T19:22:43.610

6

Python 3, 54 51 bytes

f=lambda x:x and f((x+x*x[0])[x[0]:][1:len(x)])or x

Output is a singleton list.

Try it online!

Dennis

Posted 2017-12-12T13:47:34.180

Reputation: 196 637

Completely unrelated, but I like your unicorn hat, Dennis. xD (And nice answer of course, as always!) – Kevin Cruijssen – 2017-12-18T10:02:03.443

5

CJam, 15 bytes

l~_,({_0=m<1>}*

Try it online!

Explanation

Instead of keeping track of a pointer, I just shift the array cyclically so that the current element is always at the front.

l~     e# Read and evaluate input.
_,(    e# Get its length L and decrement to L-1.
{      e# Run this block L-1 times...
  _0=  e#   Get the first element X.
  m<   e#   Rotate the array left by X positions.
  1>   e#   Discard the first element.
}*
       e# The final element remains on the stack and gets printed implicitly.

A fun alternative which unfortunately doesn't save any bytes:

l~_{;m<1>_0=}*;

Martin Ender

Posted 2017-12-12T13:47:34.180

Reputation: 184 808

5

Python 2, 55 bytes

def f(a):
 while a[1:]:l=a[0]%len(a);a[:]=a[-~l:]+a[:l]

Try it online!

Outputs as a singleton list, as allowed by default. Saved a few bytes thanks to Dennis, by reminding me that modifying the function argument is allowed.

How it works

  • def f(a) - Defines a function with a parameter a.

  • while a[1:]: - While a with the first element removed is truthy, run the block of code to follow. A list with one element or more is truthy, and empty lists are falsy in Python, hence this will stop once a reaches a length of 1.

  • l=a[0]%len(a) - Take the first element, and get the remainder of its division by the length of a. Assign the result to l.

  • a[:]=a[-~l:]+a[:l] - Rotate a to the left by l elements, and remove the first one, while assigning this to a in place.


Python 2, 63 bytes

f=lambda a,i=0:a[1:]and f(a,a.pop(((a*-~i)[i]+i)%len(a))+1)or a

Try it online!

Although longer, this seems much more elegant. Also thanks to ovs for helping in chat.

Mr. Xcoder

Posted 2017-12-12T13:47:34.180

Reputation: 39 774

1Couldn't you do something like a,*b=input() (python3) and save few bytes? However I'm not sure how that would affect l and the slice – Rod – 2017-12-12T14:44:40.023

1@Rod I don't think so, I would need to evaluate the input too in Python 3 – Mr. Xcoder – 2017-12-12T14:46:25.170

5

Brain-Flak, 88 bytes

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

Try it online!

Explanation

([[]]())                      Push negative N: the stack height - 1
{({}< … >())}{}               Do N times
     (({}))                     Duplicate M: the top of the stack
     {({}< … >[()])}{}          Do M times 
                                  Rotate the stack by 1:
          ({}< … >)               Pop the top of the stack and put it back down after
          ([]){({}{}<>)<>([])}{}  Pushing the rest of the stack on to the other one, in reverse, with the stack height added to each element (to ensure that all are positive)
          <>{({}[<>[]])<>}<>      Push the rest of the stack back, unreversing, and subtracting the stack height from each element
                      {}        Pop the top of stack

H.PWiz

Posted 2017-12-12T13:47:34.180

Reputation: 10 962

1

A very strange golf but here it is in 88 bytes.

– Post Rock Garf Hunter – 2017-12-12T18:35:05.850

1@WheatWizard Nice, surprisingly I tried something like that earlier on. – H.PWiz – 2017-12-12T18:37:41.747

I can never know how people can code like that! is there a pseudo-code translator or something? – workoverflow – 2017-12-18T13:16:41.460

1@workoverflow no, it's honestly easier than it looks. It was very daunting before I actually started , but the when the commands are this simple, it's easy to learn. – H.PWiz – 2017-12-18T13:22:58.453

4

Jelly, 9 bytes

ṙḷ/ḊµL’$¡

Try it online!

-2 bytes thanks to user202729

Explanation

ṙḷ/ḊµL’$¡  Main Link
     L’$¡  Repeat <length - 1> times
ṙ          Rotate left by
 ḷ/        The first element (from JHT; thanks to user202729)
   Ḋ       Take all but the first element

HyperNeutrino

Posted 2017-12-12T13:47:34.180

Reputation: 26 575

4

Python 3, 60 bytes

def f(a):b=a[0]%len(a);return f(a[-~b:]+a[:b])if a[1:]else a

Try it online!

-3 bytes thanks to ovs

HyperNeutrino

Posted 2017-12-12T13:47:34.180

Reputation: 26 575

4

Jelly, 7 bytes

ṙḷ/ḊµḊ¿

Try it online!

Full program.

Erik the Outgolfer

Posted 2017-12-12T13:47:34.180

Reputation: 38 134

3That ḷ/ is damn clever. – Mr. Xcoder – 2017-12-12T15:20:24.583

Could you add an explanation, please? I've now looked at the Quicks and Atoms on the linked GIT-pages, and +1-ed based on that, but I can imagine not everyone having the patients to do the same. ;) – Kevin Cruijssen – 2017-12-18T10:10:40.080

3

JavaScript (ES6), 54 60 bytes

Saved 1 byte thanks to @Shaggy
Fixed version (+6 bytes)

Modifies the input array, which is reduced to a singleton.

f=(a,p=0)=>1/a||f(a,p=(p+a[p%(l=a.length)])%l,a.splice(p,1))

Test cases

f=(a,p=0)=>1/a||f(a,p=(p+a[p%(l=a.length)])%l,a.splice(p,1))

;[
  [1],         // [1]
  [1,2],       // [1]
  [1,2,3],     // [3]
  [1,2,2],     // [1]
  [1,2,3,4],   // [1]
  [6,2,3,4],   // [4]
  [1,2,3,4,5], // [5]
  [0,1],       // [1]
  [0,0,2,0,0], // [0]
  [3,5,7,9]    // [5]
].forEach(a => f(a) && console.log(JSON.stringify(a)))

How?

We recursively apply the algorithm described in the challenge. Only the stop condition 1/a may seem a bit weird. When applying an arithmetic operator:

  • Arrays of more than one element are coerced to NaN and 1/NaN is also NaN (falsy).
  • Arrays of exactly one integer are coerced to that integer, leading to either 1/0 = +Infinity or 1/N = positive float for N > 0 (both truthy).
f = (a, p = 0) =>                 // a = input array, p = pointer into this array
  1 / a ||                        // if a is not yet a singleton:
    f(                            //   do a recursive call with:
      a,                          //     a
      p = (                       //     the updated pointer
        p + a[p % (l = a.length)] //
      ) % l,                      //
      a.splice(p, 1)              //     the element at the new position removed
    )                             //   end of recursive call

Arnauld

Posted 2017-12-12T13:47:34.180

Reputation: 111 334

Seeing as splice modifies the original array, you could do f=(a,p=0)=>1/a||f(a,p=p+a[p]%a.length,a.splice(p,1)) for 52 bytes

– Shaggy – 2017-12-12T17:06:09.003

it seems it doesn't give the right result for the second step by step example, f=(a,p=0)=>1/a?a:f(a,p=(p%a.length+a[p%a.length])%a.length,a.splice(p,1)) is ok but may be optimized – Nahuel Fouilleul – 2017-12-12T17:13:17.310

@NahuelFouilleul Oops. I thought at some point that the parentheses around p+a[p] could be removed. Which -- of course -- is not the case. Thanks for reporting this! – Arnauld – 2017-12-12T17:19:47.567

See this consensus, which @Neil brought to my attention here.

– Shaggy – 2017-12-12T17:20:56.693

@Shaggy Oh, I see. Thank you! (I missed your TIO link the 1st time...) – Arnauld – 2017-12-12T17:26:56.960

@Arnaud, in fact i think %a.length is needed twice: before splice, to get a valid index, and after to take next position in the case the removed element is the last, maybe tests don't cover all cases – Nahuel Fouilleul – 2017-12-12T20:24:11.003

@NahuelFouilleul I agree, this code is currently incorrect for [3, 5, 7, 9]. – Neil – 2017-12-12T21:48:55.320

3

Mathematica, 36 bytes

uses Martin's algorithm

#//.l:{x_,__}:>Rest@RotateLeft[l,x]&

-5 bytes from Misha Lavrov && Martin Ender

Try it online!

J42161217

Posted 2017-12-12T13:47:34.180

Reputation: 15 931

1You can save two bytes by using the pattern to pick out the first element #//.{x_,y__}:>Rest@RotateLeft[{x,y},x]&. (This stops when there is only one element because {a} no longer matches the pattern {x_,y__}.) – Misha Lavrov – 2017-12-12T22:12:05.830

1@MishaLavrov can't test right now, but you can probably shorten that further by dropping the y, calling the entire list l and then using l instead of {x,y}. – Martin Ender – 2017-12-12T23:08:58.580

1

@MartinEnder You mean like this - #//.l:{x_,__}:>Rest@RotateLeft[l,x]&?

– Misha Lavrov – 2017-12-12T23:14:48.083

1@MishaLavrov yep. – Martin Ender – 2017-12-12T23:27:44.493

3

APL (Dyalog), 20 18 bytes

{1<≢⍵:∇1↓⊖∘⍵⊃⍵⋄⊃⍵}

Try it online!

Erik the Outgolfer

Posted 2017-12-12T13:47:34.180

Reputation: 38 134

3

Java 8, 79 bytes

This lambda accepts a Stack<Integer> and returns an int or Integer.

l->{for(int i=0,s=l.size();s>1;)l.remove(i=(i+l.get(i%s))%s--);return l.pop();}

Try It Online

Ungolfed

l -> {
    for (
        int i = 0, s = l.size()
        ; s > 1
        ;
    )
        l.remove(
            i = (i + l.get(i % s)) % s--
        );
    return l.pop();
}

Acknowledgments

  • -2 bytes thanks to Nahuel Fouilleul

Jakob

Posted 2017-12-12T13:47:34.180

Reputation: 2 428

1i%=s may be removed if l.get(i) changed by l.get(i%s) – Nahuel Fouilleul – 2017-12-13T08:54:32.540

3

J, 21 17 bytes

-4 bytes thanks to FrownyFrog

((1<#)}.{.|.])^:_

Try it online!

Original:

([:}.{.|.])^:(1<#)^:_

How it works:

^:_ repeat until the result stops changing

^:(1<#) if the length of the list is greater than 1

{.|.] rotate the list to the left its first item times

[:}. drop the first element and cap the fork

Try it online!

Galen Ivanov

Posted 2017-12-12T13:47:34.180

Reputation: 13 815

@ FrownyFrog Thanks, I didn't try this - it's much better! – Galen Ivanov – 2017-12-13T11:52:02.243

3

Julia 0.6, 46 42 bytes

!x=length(x)>1?!circshift(x,-x[])[2:end]:x

Try it online!

Straightforward recursive Julia version. x[] accesses the first element of x.

LukeS

Posted 2017-12-12T13:47:34.180

Reputation: 421

2

Pyth, 9 bytes

.WtHt.<Zh

Try it here!

This outputs the result as a singleton list, as allowed by default.

How it works

.WtHt.<Zh ~ Full program.

.W        ~ Functional while. It takes three arguments, two functions: A and B
            and a starting value, which in this case is automatically assigned
            to the input. While A(value) is truthy, value is set to B(value).
            Returns the ending value. A's argument is H and B's is Z.
  tH      ~ A (argument H): Remove the first element of H. A singleton list
            turns into [], which is falsy and thus breaks the loop. Otherwise,
            it is truthy and the loops goes on until the list reaches length 1.
     .<Zh ~ B (argument Z): Cyclically rotate Z by Z[0] places, whereas Z[0]
            represents the first element of Z.
    t     ~ And remove the first element.

Note: If you don't want to see those brackets, just add h or e in front of the whole code.

Mr. Xcoder

Posted 2017-12-12T13:47:34.180

Reputation: 39 774

2

Swift, 87 bytes

func f(a:inout[Int]){var i=0,c=0;while(c=a.count,c>1).1{i=(i+a[i%c])%c;a.remove(at:i)}}

Returns as a singleton list by modifying the input. Try it online!

Explanation

func f(a:inout[Int]){
  var i=0,c=0;            // Set the index i to 0
  while(c=a.count,c>1).1{ // While the length of the list > 0:
    i=(i+a[i%c])%c;       //  Add a[i] to i and loop back using modulo
    a.remove(at:i)        //  Remove a[i]
  }
}

Herman L

Posted 2017-12-12T13:47:34.180

Reputation: 3 611

2

Perl 6, 46 45 bytes

(-1 byte thanks to Brad Gilbert)

{($_,{(|$_ xx*)[.[0]+(1..^$_)]}...1)[*-1][0]}

Try it online!

($_, { ... } ... 1) generates a sequence of lists, starting with the input list $_, each successive element being generated by the brace expression, and terminating when the list smart-matches 1--ie, has a length of 1. The trailing [* - 1] obtains the final element, and the final [0] takes the sole element out of that singleton list.

(|$_ xx *) generates a flat, infinitely replicated copy of the current element. This list is indexed with the range .[0] + (1 ..^ $_) to extract the next finite list in the series.

Sean

Posted 2017-12-12T13:47:34.180

Reputation: 4 136

1mind blown o.O – Adrian – 2017-12-12T20:01:32.477

[*-1][0] can be combined into [*-1;0] saving a byte. Also 1..$_-1 is better written as 1..^$_ again saving a byte. – Brad Gilbert b2gills – 2017-12-17T22:47:22.073

@BradGilbertb2gills I tried [*-1;0], but it seems not to be equivalent somehow. The function then returns a list rather than a number. – Sean – 2017-12-18T00:02:01.027

That doesn't stop the 1..^$_ optimization – Brad Gilbert b2gills – 2017-12-21T22:53:24.220

1

Perl 5, 47 43 41 + 2 (-ap) = 43 bytes

$\=splice@F,($_+=$F[$_%@F])%@F,1while@F}{

Try it online!

Takes input as space separated numbers.

Xcali

Posted 2017-12-12T13:47:34.180

Reputation: 7 671

it seems it does not exactly the same as the step by step example following does but is longer $x%=@F,splice@F,$x=($x+$F[$x])%@F,1while$#F;$_="@F" – Nahuel Fouilleul – 2017-12-12T16:55:23.387

1wow o.O Need to get my game up. – Adrian – 2017-12-12T20:00:08.840

1

Haskell, 56 bytes

f[x]=x
f l|m<-head l`mod`length l=f$drop(m+1)l++take m l

Try it online!

totallyhuman

Posted 2017-12-12T13:47:34.180

Reputation: 15 378

55 bytes – H.PWiz – 2017-12-13T01:01:07.263

1

Python 3, 57 56 bytes

f=lambda a,*b:f(*([a,*b]*-~a)[a+1:a-~len(b)])if b else a

Try it online!

Rod

Posted 2017-12-12T13:47:34.180

Reputation: 17 588

1

Java 8, 325 Bytes

Golfed:

static void n(Integer[]j){Integer[]h;int a=0;h=j;for(int i=0;i<j.length-1;i++){if(h.length==a){a=0;}a=(a+h[a])%h.length;h[a]=null;h=m(h);}System.out.print(h[0]);}static Integer[] m(Integer[]array){Integer[]x=new Integer[array.length-1];int z=0;for(int i=0;i<array.length;i++){if(array[i]!=null){x[z]=array[i];z++;}}return x;}

Ungolfed:

 interface ArrayLeapFrog {
static void main(String[] z) throws Exception {
    Integer[] j = {6, 2, 3, 4};
    n(j);
}

static void n(Integer[] j) {
    Integer[] h;
    int a = 0;
    h = j;
    for (int i = 0; i < j.length - 1; i++) {
        if (h.length == a) {
            a = 0;
        }
        a = (a + h[a]) % h.length;
        h[a] = null;
        h = m(h);
    }
    System.out.print(h[0]);
}

static Integer[] m(Integer[] array) {
    Integer[] x = new Integer[array.length - 1];
    int z = 0;
    for (int i = 0; i < array.length; i++) {
        if (array[i] != null) {
            x[z] = array[i];
            z++;
        }
    }
    return x;
  }
}

DevelopingDeveloper

Posted 2017-12-12T13:47:34.180

Reputation: 1 415

4Welcome! A couple tips: No need to count the static keywords here. Typically multi-method solutions are implemented as non-static members of a class, and main creates an instance for testing. Also, if you do it that way you support Java 7 and can submit as simply a "Java" solution. For future reference, input format tends to be quite flexible here, so for example you could choose to take input as a List (which is quite helpful for this problem). – Jakob – 2017-12-13T00:43:36.340

1

Brain-Flak, 104 bytes

H.PWiz has a shorter answer here that I helped to make, you should check it out.

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

Try it online!

Explanation

([[]]())   #Push 1 minus stackheight
{({}()<    #N times
 (({}))    #Get a copy of the top
 {({}[()]< #N times
  ({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>
           #Roll the top to the bottom (From the wiki)
 >)}{}     #End loop
 {}        #Remove one value
>)}{}      #End loop

Post Rock Garf Hunter

Posted 2017-12-12T13:47:34.180

Reputation: 55 382

I thought I would compete. Then I realised that mine was almost exactly the same as yours, apart from a different "top roll"

– H.PWiz – 2017-12-12T18:24:52.950

I saw that ;). Using the fact that everything is non-negative is rather clever. – Post Rock Garf Hunter – 2017-12-12T18:25:39.257

1

APL+WIN, 36 bytes

¯1↑⍎¨(1⌈¯1+⍴v←,⎕)⍴⊂'v←(1<⍴v)↓v[1]⌽v'

Explanation:

Prompts for screen input.

'v←(1<⍴v)↓v[1]⌽v' Loop logic as a string

 (1<⍴v)↓ only drop the first when number of elements n>1

 (1⌈¯1+⍴v←,⎕)⍴⊂ create a nested vector of logic of length 1 max n-1

 ⍎¨ execute each element of the nested vector in turn

¯1↑ take answer from executing final element

Graham

Posted 2017-12-12T13:47:34.180

Reputation: 3 184

1

JavaScript, 58 56 59 bytes

let f =

a=>{for(i=0,k=a.length;k>1;)i+=a[i%=k],a.splice(i%=k--,1)}
<h2>Test</h2>
Enter or paste a valid array literal within square brackets and click Run.
<blockquote>
   <input id = "array" type="text" length="20">
   <button type="button" onclick="run()">Run</button>
</blockquote>
Result: <pre id="o"></pre>

<script>
    function run() {
       let a = JSON.parse(array.value);
       f(a);
       o.textContent = a;
    }
</script>

Returns the result as the only element remaining in the input array which is updated in place.

Two bytes saved by using a comma separated statement instead of a block statement in the for loop body! Three bytes lost to skip from an element deleted at end of array (:

Less golfed:

a => {
    for(i=0,k=a.length;k>1;) // once less than array length
        i+=a[i%=k],          // the new index
        a.splice(            // delete an element
           i%=k--,           // ensuring index is within array,
                             // and post decrement loop count
           1
        )
}

traktor53

Posted 2017-12-12T13:47:34.180

Reputation: 299

This seems to give the wrong answer for [3, 5, 7, 9]. – Neil – 2017-12-13T09:56:10.313

Wrong for [3,5,7,9]. Expected value 5 – edc65 – 2017-12-13T10:02:52.567

The function does not return the value, i'm not sure if the byte count is proper keeping that in mind, since it can't work on it's own... – Brian H. – 2017-12-13T11:40:21.053

@edc65 and Neil , thanks - the index of an element deleted at end of array was not being adjusted to the start of the shortened array. – traktor53 – 2017-12-13T22:35:38.983

@BrianH. the function modify its parameter, there is consensus about that https://codegolf.meta.stackexchange.com/a/4942/21348

– edc65 – 2017-12-13T22:40:16.643

didn't know that, nevermind me then ;) – Brian H. – 2017-12-14T09:50:44.373

1

Python 2, 61 bytes

def f(x):
 while x[1:]:y=x[0]%len(x);x=x[y+1:]+x[:y]
 print x

Rɪᴋᴇʀ

Posted 2017-12-12T13:47:34.180

Reputation: 7 410

1I know a bunch of python answers exist, but I figured I might as well add my own. – Rɪᴋᴇʀ – 2017-12-13T03:10:23.720

1

Clean, 78 bytes

Uses the same method as Laikoni's Haskell answer.

import StdEnv
f[e]=e
f[x:r]=f(take(length r)(drop(x+1)(flatten(repeat[x:r]))))

Try it online!

Οurous

Posted 2017-12-12T13:47:34.180

Reputation: 7 916

1

R, 111 117 126 bytes

Thanks to @Giuseppe for golfing off 11 bytes by changing to a while loop, got another 4 by removing the function and reading user input directly.

I don't feel great about what it took to get there - I'm sure a more elegant solution exists.

i=scan();m=1;while((l=sum(i|1))-1){j=i[m];p=`if`(j+m>l,j%%l+!m-1,j+m);p=`if`(!p,m,p);i=i[-p];m=`if`(p-l,p,1)};i

Try it online!

Ungolfed code

i=scan()
m=1
while((l=sum(i|1))-1){
  j=i[m]
  p=`if`(j+m>l,j%%l+!m-1,j+m)
  p=`if`(!p,m,p)
  i=i[-p]
  m=`if`(p-l,p,1)
}
i

Mark

Posted 2017-12-12T13:47:34.180

Reputation: 411

117 bytes -- note that since this is a recursive function, the name f= needs to be included – Giuseppe – 2017-12-15T15:45:23.230

1I found this quite a difficult challenge with a 1 based-index language without array rotations; this is potentially 1-3 bytes shorter with a while loop, I think. – Giuseppe – 2017-12-15T15:46:22.357

115 bytes with a while loop – Giuseppe – 2017-12-15T15:50:47.443

my previous 115 byter was invalid since we both forgot the f= part of the recursive function. :( – Giuseppe – 2017-12-15T15:51:11.427

I updated the old score and the new score to reflect the recursiveness :) With the 'while' loop I golfed off another 4 bytes using scan. – Mark – 2017-12-15T15:59:57.380

0

Perl, 62 bytes

@_=@ARGV;while(@_>1){splice(@_,$i=($i+$_[$i])%@_,1)}print$_[0]

Requires that the numbers are added at command line. Default $i equivalent to 0.

@_=@ARGV;                         # gets the array passed on command line
while(@_>1)                       # if there is more than one element in array, loop
{
   splice(@_,$i=($i+$_[$i])%@_,1) # embedded assignment to $i, removes element.
}
print$_[0]                        # prints remaining element

Adrian

Posted 2017-12-12T13:47:34.180

Reputation: 101

0

Perl 5, 43 + 2 (-ap) = 45 bytes

$_="@F[$`%@F+1..$#F,0..$`%@F-1]",redo if/ /

try it online

Nahuel Fouilleul

Posted 2017-12-12T13:47:34.180

Reputation: 5 582

0

Pushy, 11 bytes

@Lt:&:};.;#

Try it online!

This challenge is well suited to be run on a stack:

             \ Implicit: Input on stack
@            \ Reverse the stack
 Lt:     ;   \ len(stack)-1 times do:
    &: ;     \    (last item) times do:
      }      \      Cyclically shift the stack right
        .    \    Pop top of stack
          #  \ Print remaining value

FlipTack

Posted 2017-12-12T13:47:34.180

Reputation: 13 242

0

Python 2, 57 bytes

A couple bytes longer than Mr Xcoder's solution, but I thought it was worth posting this alternate approach.

def f(a,p=0):
 while a[1:]:p=(p+(a+a)[p])%len(a);del a[p]

Try it online!

Initially I did this recursively, but it's a few bytes longer:

def f(a,p=0):
 if a[1:]:p=(p+(a+a)[p])%len(a);del a[p];f(a,p)

Try it online!

FlipTack

Posted 2017-12-12T13:47:34.180

Reputation: 13 242

0

Common Lisp, 129 bytes

(do*((m(coerce(read)'list))(k(rplacd(last m)m)))((eq(cdr m)m)(princ(car m)))(setf k(nthcdr(1-(car m))m)m(cdr(rplacd k(cddr k)))))

Try it online!

Renzo

Posted 2017-12-12T13:47:34.180

Reputation: 2 260

0

><>, 23 + 3 = 26 bytes

{:l3(?\:?\~~
 1-&{&\n;\

Try It Online

Takes a series of integers via the -v option.

How It Works

{:l3(?\   Get the first element of the stack and dupe it
 .....\n; If the length of the stack is only 2 (the first element twice), then print the number and end the program, else enter the loop

 .....\:?\.. Enter the loop with the array and a copy of the first value.
 1-&{&\..\   Exit the loop if the copy is 0, else shift the stack right and decrement the copy.

{:l3(?\..\~~ Pop the excess 0 and the current element of the array
 ...         Go back to the beginning, having one less element than before

Jo King

Posted 2017-12-12T13:47:34.180

Reputation: 38 234

0

Perl, 36 bytes

Includes +2 for ap

perl -apE '--($m||=$_+1)?$F[@F]:$\=$_ for@F}{' <<< "1 4 2 3 5"; echo

Nicely evil...

Ton Hospel

Posted 2017-12-12T13:47:34.180

Reputation: 14 114