35
\$\begingroup\$

Inspired by this question:

Make a function (or a full program) that receives a list of numbers and outputs the list rearranged, so that even-indexed numbers appear first, and odd-indexed numbers follow. The values of the numbers themselves don't affect ordering - only their indices do. All indices are zero-based.

For example:

Input: [0, 1, 2, 3, 4]

Output: [0, 2, 4, 1, 3]

Another example:

Input: [110, 22, 3330, 4444, 55555, 6]

Output: [110, 3330, 55555, 22, 4444, 6]

Use most natural representation for lists that your language has. There are no limitations on complexity (e.g. allocating a temporary list is OK - no need to do it in-place).

P.S. It should work for the empty list (empty input => empty output).

\$\endgroup\$
8
  • \$\begingroup\$ This is effectively the inverse of the current answers to this question \$\endgroup\$ Commented Nov 19, 2015 at 18:44
  • \$\begingroup\$ Can we assume that all list elements are positive or non-negative or something? \$\endgroup\$ Commented Nov 19, 2015 at 21:43
  • \$\begingroup\$ @MartinBüttner Assume anything reasonable, maybe even that they are in the range 0...255. \$\endgroup\$
    – anatolyg
    Commented Nov 19, 2015 at 21:47
  • \$\begingroup\$ Related \$\endgroup\$
    – Alex A.
    Commented Nov 20, 2015 at 0:21
  • \$\begingroup\$ Can we output a comma-separated list? \$\endgroup\$
    – Oliver
    Commented Feb 25, 2019 at 12:11

55 Answers 55

1
2
2
\$\begingroup\$

JavaScript (Node.js), 47 bytes

x=>f=i=>1/x[i|i]?[x.splice(i,1)[0],...f(-~i)]:x

Try it online!

JavaScript (Node.js), 50 bytes

x=>(i=a=[]).concat(x.filter(v=>i++%2||!a.push(v)))

Try it online!

Not shortest now but fun

\$\endgroup\$
2
\$\begingroup\$

Elm, 78 bytes

g x y i z=case(z,i)of
 (a::b,_)->g(y++[a])x(1-i)b
 (_,0)->x++y
 _->y++x
g[][]1
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Your final case can match _ instead of (_,_), I think. \$\endgroup\$
    – DLosc
    Commented Jan 9, 2023 at 18:13
1
\$\begingroup\$

Pyth, 8 bytes

+%2Q%2tQ

Relatively simple

\$\endgroup\$
1
\$\begingroup\$

Vitsy, 22 Bytes

Vitsy really wasn't made to do this...

r' 'Vl2/\[N{VO]l\[NVO]
r                       Reverse the implicit numerical input stack.
 ' 'V                   Save the "space" character as a global final variable.
     l2/\[....]         Repeat the stuff in the brackets the length of the input
                        stack divided by 2.
          N{VO          Output the top item of the stack as a number, then shift
                        the stack over once to the left, push a space, output it.
               l\[...]  For the rest of the stack, repeat that many times...
                  NVO   Output the top item of the stack as a number separated 
                        by a space.
\$\endgroup\$
1
\$\begingroup\$

Minkolang 0.12, 15 bytes

$nI2:[i1+g]r$N.

Try it here.

Explanation

$n                 Read in all of input as numbers
  I2:              The length of the stack divided by 2 (n)
     [             Open for loop that repeats n times
      i1+          Loop counter + 1
         g         Gets the (i+1)th item from the stack and puts it on top
          ]        Close for loop
           r       Reverse the stack (for outputting)
            $N.    Output the whole stack as numbers and stop.
\$\endgroup\$
1
\$\begingroup\$

Clojure/ClojureScript, 52 bytes

(defn f[l](flatten(map #(take-nth 2 %)[l(rest l)])))

Written in a ClojureScript REPL, should also be valid Clojure.

\$\endgroup\$
1
\$\begingroup\$

R, 49 bytes

q<-function(x)c(x[seq(x)%%2==1],x[seq(x)%%2==0])

Call it as q(blah). Or, if x already contains the list to be rearranged, then

c(x[seq(x)%%2==1],x[seq(x)%%2==0])

is just 35 bytes.

\$\endgroup\$
1
  • \$\begingroup\$ function(x,y=!seq(!x)%%2)c(x[!y],x[y]) is 38 bytes (and will work for input that's empty/length one) \$\endgroup\$
    – Giuseppe
    Commented Dec 14, 2020 at 21:43
1
\$\begingroup\$

F#, 64

fun x->List.mapi(fun i l->l,i%2)x|>List.sortBy snd|>List.map fst

Inspired by Sehnsucht's answer (but not enough rep to comment).

Maps each value to a tuple where the second entry is the modulo of the list index, sorts by modulo, then maps back to the original value.

\$\endgroup\$
1
\$\begingroup\$

Prolog, 103 bytes

r([E,O|T],[E|A],[O|B]):-r(T,A,B).
r([],[],[]).
r([E],[E],[]).
p(L):-r(L,A,B),append(A,B,X),write(X).

Example

>p([1,2,3,4,5]).
[1,3,5,2,4]
\$\endgroup\$
1
\$\begingroup\$

Hassium, 191 Bytes

This one was pretty long :(
It reads the array from args, so run this with hassium file.has 0 1 2 3 4

func main(){a=args;e,o=[]for(c=0;c<a.length;c++)if(c%2==0)e.add(a[c])else o.add(a[c])print("["+(e+o).toString().replace("{", "").replace("}", "").replace("Array", "").replace("  ", "")+"]");}

Run and see expanded with test case here

\$\endgroup\$
1
\$\begingroup\$

Go, 92 bytes

func s(l []int) (r []int){for i:=0;i<len(l)*2;i+=2 {r=append(r,append(l,l...)[i])};return}

"Go. at least it's shorter than prolog"

degolf

func s(l []int) (r []int){
   for i:=0;i<len(l)*2;i+=2 {
      r=append(r,append(l,l...)[i])
   }
   return
}
\$\endgroup\$
1
\$\begingroup\$

𝔼𝕊𝕄𝕚𝕟, 12 chars / 22 bytes (noncompetitive)

Ѩťᶏש,Ѩą(ï,2⸩

Try it here (Firefox only).

Just switched to Lodash, which has way more functions. Thus, this answer is rendered noncompetitive.

\$\endgroup\$
1
\$\begingroup\$

bash and GNU coreutils, 68 bytes

We assume that the list is newline-separated and passed on standard input.

(paste - <(seq 0 5 9999)|tee x|grep 0$;grep 5$<x)|cut -f1|grep -v ^$

Unfortunately this will ignore any inputs beyond index 1999, so it doesn't quite meet the spec.

It also clobbers a hardcoded temporary file ('x'), which could be problematic if run in parallel, and it doesn't remove it afterwards. Sorry about that!

\$\endgroup\$
1
\$\begingroup\$

PHP, 78 69 bytes

PHP can chunk and slice, but not interleave arrays; that makes this a bit bulky:

function(&$a){while($i++<count($a)>>1)$a[]=array_splice($a,$i,1)[0];}

Call by reference or try it online.


first approach (programs for 78 bytes):

for(;++$i<$argc;)echo",",$argv[$i++];for($i=1;++$i<$argc;)echo",",$argv[$i++];

prints a leading comma; insert [!$i] before the first$argv to remove it.

Two other 78 byte solutions (print a leading and a trailing comma):

for($n=$argc-2|1;++$i<$argc*2;)$i&1?print",".$argv[$i]:$argv[$n+=2]=$argv[$i];
for($n=$argc-2;++$i<$argc*2;)$i&1?print",".$argv[$i]:$argv[1|$n+=2]=$argv[$i];

Run with php -nr '<code>' <arguments> or try them online

\$\endgroup\$
1
\$\begingroup\$

Factor, 34 bytes

[ dup <evens> swap <odds> append ]

Try it online!

It's a quotation (anonymous function) that takes a sequence from the data stack as input and leaves a sequence on the data stack as output. It rips out the even indices into a sequence, rips out the odd indices into a sequence, and smushes them back together. [ 2 group flip concat ] works for sequences of even length, but flip can only transpose square matrices correctly.

\$\endgroup\$
1
\$\begingroup\$

Rust 109 bytes

fn f(x:Vec<u8>)->Vec<u8>{x.iter().cloned().step_by(2).chain(x.iter().cloned().skip(1).step_by(2)).collect()}

"at least it's shorter than C#"

\$\endgroup\$
5
  • 1
    \$\begingroup\$ fn f(x:&[u8])->Vec<u8>{x.iter().chain(&x[1-x.len()%2..]).cloned().step_by(2).collect()} \$\endgroup\$
    – alephalpha
    Commented Jan 4, 2023 at 3:13
  • 1
    \$\begingroup\$ let f=|x:&[u8]|x.iter().chain(&x[1-x.len()%2..]).cloned().step_by(2).collect(); \$\endgroup\$
    – don bright
    Commented Jan 4, 2023 at 3:29
  • 1
    \$\begingroup\$ fn f(a:&mut[u8])->&mut[u8]{for i in 1..(a.len()+1)/2{a[i..=2*i].rotate_right(1)};a}, or fn f(a:&mut[u8]){for i in 1..(a.len()+1)/2{a[i..=2*i].rotate_right(1)}} if we can modify the slice in-place without returning. \$\endgroup\$
    – alephalpha
    Commented Jan 4, 2023 at 3:29
  • 1
    \$\begingroup\$ let f=|x:&mut[u8]|for i in 1..(x.len()+1)/2{x[i..=2*i].rotate_right(1)}; \$\endgroup\$
    – don bright
    Commented Jan 4, 2023 at 3:32
  • \$\begingroup\$ thanks for posting this, very interesting!!! im not sure if modifying in place is 'cheating' or if closures are cheating but .. your fn is down to 71. (closure doesnt even help that case) \$\endgroup\$
    – don bright
    Commented Jan 4, 2023 at 3:33
1
\$\begingroup\$

Go, 97 96 91 bytes, idiomatic

func(L[]int)(E,O[]int){for i,e:=range L{if i%2<1{E=append(E,e)}else{O=append(O,e)}}
return}

Attempt This Online!

Because Go supports multiple return values, this returns 2 lists, the even-indexed elements and the odd-indexed elements.

  • -1 byte: ==0 into <1
  • -5 bytes: return values share a type

Go, 96 bytes, generic

func f[T any](L[]T)(E,O[]T){for i,e:=range L{if i%2<1{E=append(E,e)}else{O=append(O,e)}}
return}

Attempt This Online!

Go, 122 114 bytes (literal interpretation)

func(L[]int)[]int{var E,O[]int
for i,e:=range L{if i%2<1{E=append(E,e)}else{O=append(O,e)}}
return append(E,O...)}

Attempt This Online!

This longer solution merges the filtered lists into a single list.

  • -8 bytes: E and O share the same type
\$\endgroup\$
1
\$\begingroup\$

C# 7.3, 100 bytes

List<int> M(List<int> x)=>x.Select((y,i)=>(y,i)).GroupBy(y=>y.i%2,y=>y.y).SelectMany(y=>y).ToList();

This is pretty much idiomatic for C#, but I don't think a non-idiomatic solution would be much shorter.

\$\endgroup\$
1
  • \$\begingroup\$ pretty cool if wordy \$\endgroup\$
    – don bright
    Commented Jan 4, 2023 at 2:14
1
\$\begingroup\$

Arturo, 27 bytes

$=>[i:0arrange&=>[i%2'i+1]]

Try it

\$\endgroup\$
1
\$\begingroup\$

Thunno, \$ 3 \log_{256}(96) \approx \$ 2.47 bytes

ZlS

Attempt This Online!

Explanation

ZlS  # Implicit input
Zl   # Uninterleave
  S  # Sum (acts as flatten 
     # for nested lists)
     # Implicit output
\$\endgroup\$
1
\$\begingroup\$

Java 8 (OpenJDK 8), 70 bytes

Pretty much straightforward in Java

l->{for(int i=1;i<=l.size()/2;l.remove(i++))l.add(l.get(i));return l;}

Sadly not golfable using only streams because index isn't easily accessible from inside, and conversion from stream to list is still a pain until Java 16

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Zsh, 34 bytes

for i j;a+=($i) b+=($j);echo $b $a

Try it online!. Note that arrays in Zsh are 1-indexed, that's why the output appears backwards from the example given. If the requirement for "even" indices first is relaxed, and the order of outputs is more important, just switch $a and $b

\$\endgroup\$
0
\$\begingroup\$

Haskell + hgl, 8 bytes

mp<$%uak

Attempt This Online!

Explanation

  • uak: splits a list into even and odd indices
  • mp: "Monoidal action", concatenates two lists
  • (<$%): Uncurry compose, this composes a curried two argument function like mp with a function that returns a tuple like uak.

Reflection

I'm pretty happy with this. Really glad to have (<$%) and uak is proving to be quite useful. It is worth considering if either or both of these deserve a "promotion" to a smaller byte count.

\$\endgroup\$
0
\$\begingroup\$

JavaScript (Node.js), 49 bytes

After a few fails it finally works, but is now longer than expected :-/

t=>t.map((_,i)=>t[(i*2-1)%((l=t.length)+~l%2)+1])

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Thunno 2 S, 1 byte

z

Attempt This Online!

Explanation

    # Implicit input
z   # Uninterleave the input into two pieces
    #   e.g.  [1,2,3,4,5,6]  ->  [[1,3,5], [2,4,6]]
    #   e.g.  [0,1,2,3,4]    ->  [[0,2,4], [1,3]]
    # S flag takes the sum of this list
    #  i.e. flattens the nested list
    #   e.g.  [[1,3,5], [2,4,6]]  ->  [1,3,5,2,4,6]
    #   e.g.  [[0,2,4], [1,3]]    ->  [0,2,4,1,3]
    # Implicit output
\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.