| Bytes | Lang | Time | Link |
|---|---|---|---|
| 3155 | Python 3 155 Bytes | 251007T033936Z | Random D |
| 031 | Uiua | 251002T044533Z | YufangIG |
| 155 | Go | 251001T152853Z | bigyihsu |
| 048 | Dyalog APL | 250929T182413Z | Aaron |
| 092 | Raku Perl 6 rakudo | 241216T180526Z | xrs |
| 114 | AWK | 241204T194359Z | xrs |
| 183 | TypeScript’s type system | 231214T174944Z | noodle p |
| 089 | Perl 5 p | 231218T224209Z | Xcali |
| 008 | Vyxal 3 j | 231215T131541Z | pacman25 |
| 033 | GolfScript | 200110T092344Z | user8505 |
| 012 | Japt | 170927T110127Z | Shaggy |
| 017 | Stax | 180514T194643Z | Multi |
| 074 | Haskell | 170927T202246Z | nimi |
| 136 | JavaScript | 170928T081707Z | tjespe |
| 062 | R | 170927T125533Z | plannapu |
| 050 | Ruby | 170927T084431Z | G B |
| 081 | Python 2 | 170927T034532Z | fireflam |
| 085 | JavaScript ES6 | 170927T102338Z | edc65 |
| 123 | AWK | 170927T190338Z | Robert B |
| 079 | JavaScript ES6 | 170927T184633Z | Rick Hit |
| nan | TIBasic 83 series | 170927T032206Z | Misha La |
| 042 | Stacked | 170927T152452Z | Conor O& |
| 097 | Haskell | 170927T151213Z | ბიმო |
| 009 | Husk | 170927T144127Z | ბიმო |
| 017 | MATL | 170927T133448Z | Luis Men |
| 205 | Java OpenJDK 8 | 170927T090408Z | Roberto |
| 214 | Java 8 | 170927T075545Z | Kevin Cr |
| 122 | JavaScript ES6 | 170927T082418Z | Neil |
| 011 | 05AB1E | 170927T060639Z | Emigna |
| 142 | Mathematica | 170927T031355Z | ZaMoC |
| 010 | Jelly | 170927T024622Z | hyperneu |
Python 3 155 Bytes
R=range
P=print
a=int(input())+1
*b,=*c,=R(1,a)
while 1:
b=b[::-1];P(b)
for i in R(0,a-1,2):
if i<len(b)-1:b[i],b[i+1]=b[i+1],b[i]
P(b)
if b==c:break
Definitely not the most golfed down version.
Edit 1: Removed a semicolon -1 byte
Edit 2: Shortened a condition -1 byte
Go, 155 bytes
import(."fmt";."slices")
func f(S[]int){s(S)
for!IsSorted(S){s(S)}}
func s(S[]int){Reverse(S)
for i:=0;i<len(S)-1;i+=2{S[i],S[i+1]=S[i+1],S[i]}
Println(S)}
Ungolfed:
import(."fmt";."slices")
func f(S[]int){
Step(S) // initial step
for !IsSorted(S){Step(S)} // only do further steps if not sorted
}
func Step(S[]int){Reverse(S) // slices.Reverse
Reorder(S)
Println(S) // print on each step
}
func Reorder(S[]int){
for i:=0;i<len(S)-1;i+=2{
S[i],S[i+1]=S[i+1],S[i]
}
}
Dyalog APL, 48 bytes
{⊖¯1↓↑{⍵,⍨⊂∊,⍨/¨(⌽⊃⍵)⊂⍨(≢⊃⍵)⍴1 0}⍣{o≡⊃⍺}⊂o←⍵}∘⍳
{ }∘⍳ # Run this function after taking the range of 1..input
⊂o←⍵ # Store in the range in (o)riginal and enclose
{ }⍣ # Repeat this function until
{o≡⊃⍺} # The first entry matches the original
(≢⊃⍵)⍴1 0 # Take length many 1 0 pairs
# This will split the input into groups of two leaving an odd element by itself
⊂⍨ # and partition
(⌽⊃⍵) # the reversed first entry
¨ # To each pair
,⍨/ # reverse concat over
# This will simply swap the two numbers
∊ # Flatten the whole thing
⍵,⍨⊂ # and enclose before prepending to the original list of transformations
↑ # Mix into a matrix so it looks nice
¯1↓ # Drop the last which would be another copy of the original
⊖ # and flip over
💎
Created with the help of Luminespire.
Raku (Perl 6) (rakudo), 92 bytes
{my $x=$_;loop {$x=$x.flip;$x~~s:g/(\d)(\d)/{$/.list[1]~$/.list[0]}/;say $x;last if $x==$_}}
{my $x=$_; # save starting point
loop { # loop
$x=$x.flip; # reverse digits
$x~~s:g/(\d)(\d)/{$/.list[1]~$/.list[0]}/; # switch pairs
say $x; # print
last if $x==$_}} # exit if we're back
AWK, 114 bytes
a=$0{do{s=""
for(i=length;i;)s=s substr($0,i--,1)
$0=gensub(/([^,]+),([^,]+)/,"\\2,\\1","g",s)
print}while($0!=a)}
a=$0{do{s="" # defaults
for(i=length;i;)s=s substr($0,i--,1) # reverse
$0=gensub(/([^,]+),([^,]+)/,"\\2,\\1","g",s) # switch digits
print} # print until
while($0!=a)} # we get back
TypeScript’s type system, 203 193 190 183 bytes
//@ts-ignore
type F<N,A=[],E=A,O=N,G=[...N,...A]>=N extends[1,...infer D]?F<D,[N,...A]>:A extends[...infer R,infer X,infer Y]?F<[...N,X,Y],R,E,O>:E extends O[any]?O:F<[],G,E,[...O,G]>
I can’t believe I got this all to fit in a single type. This is definitely one of the coolest TS types submissions I’ve posted.
Edit: This explanation is really chaotic because this submission itself is chaotic; I don’t blame you if it makes zero sense to you
Explanation
The //@ts-ignore comment on the first line tells the compiler to suppress any warnings from the following line.
The beginning of the type describes its arguments:
type F<N,A=[],E=A,O=N,G=[...N,...A]>
What the arguments do is explained later, but you should know that G is an alias for N with A appended to it; it comes in handy later.
The type has three “stages”, which are entered at different times in the evaluation of the type.
The first stage converts the unary number to the range of unary numbers between 1 and the input. (At this stage, the input is in N, and A is the empty tuple.)
N extends[1,...infer D]Is the first item of N a one? If so, remove it and call the rest D, and…
F<D,[N,...A]>…recurse, with N set to D, and with N prepended to A.
By the end of stage 1, A will contain the range from 1 to the input, E will be set equal to A, and N and O will both be the empty tuple.
(E is the initial step; this will be how the type knows to terminate. O will be the list of intermediate results, which will be the final return value.)
If the first stage was not entered, because N is either empty or contains elements that aren’t ones, then the second stage is entered, to reverse and reorder the elements of A.
A extends[...infer R,infer X,infer Y]If A has two or more items, call the last two X and Y respectively, and the rest R.
F<[...N,X,Y],R,E,O>Recurse, appending X and Y to N, setting A to R, and keeping the values of E and O as they already are.
By the end of this stage, N will contain the reversed and reordered items of A. A will be empty if it originally had an even number of items, but if its length was odd then it will contain the last item to be appended to N. This is a minor pain point of the solution, adding 14 bytes to alias G to N with A appended.
The third stage does the “repeat” step.
E extends O[any]?OIf E (the initial result) is contained in O (the list of intermediate results), then the program is finished; return O.
F<[],G,E,[...O,G]>Otherwise, recurse with N set to the empty tuple (skipping stage 1 and going straight to stage 2), A set to G (the alias for N with A appended), E left unchanged, and O with G appended.
Perl 5 -p, 89 bytes
$_=$;=join$",1..$_;do{$_=join$",reverse/\d+/g;s/(\d+) (\d+)/$2 $1/g;$\+=say}until$;eq$_}{
GolfScript, 33 bytes
Nope, I can't simplify the algorithm.
~),1>:a{-1%2/{-1%}%{+}*.p.a=!}do;
Explanation
~ # Dump the input
), # Generate inclusive range: 0 -> input
1>:a # Set [1 2 ... input-1 input] to a without popping
{ }do # Do ... While
.a=! # The current item does not equal to a
-1% # Reverse the item
2/ # Split into equal parts of 2
{-1%}% # For each equal part, reverse
{+}* # Flatten the list
.p # Print the list
; # We don't need to implicit output the
# extra value left on the stack
Japt, 20 18 15 12 bytes
õ
£=ò2n)ÔcÃâ
Try it (-R flag for visualisation purposes only)
1 byte saved thanks to ETHproductions.
:Implicit input of integer U
õ :Range [1,U]
\n :Reassign to U
£ :Map
ò : Partitions
2 : Of length 2
n : Starting from the end
) : End partition
Ô : Reverse
c : Flatten
= : Reassign to U
à :End map
â :Deduplicate
Stax, 17 bytes
âΩÄ─g╫B♥C╛♠ƒ?|πcD
Explanation
RX~Wr2/{r+}Fc|uPcx=C # Full program, unpacked, implicit input
RX~ # Create range, save to X register, pop back to input stack
W # Start while loop until truthy value
r # reverse array
2/ # Split into groups of 2
{r+}F # Loop through each set and reverse each
c # Copy top value
|u # Convert to string representation of array
P # Pop top value off
cx= # Copy top value, get value of x register, compare to top value
C # If top value is truthy, cancel block and end
Suprised it works as fast as it does, tested up to 399 before I didn't want to temp my browser anymore.
Haskell, 75 74 bytes
g(a:b:c)=b:a:g c
g x=x
h=g.reverse
0!x|x<[2]=[x]|1<2=x:0!h x
p n=0!h[1..n]
g does the pair-wise swaps, h a single step (reverse + reorder), ! repeatedly applies h (and collects the intermediate results) until the order is restored. Note: ! takes the additional but unused extra parameter 0 just to make it an infix operator. The main function p starts it up.
Edit: Thanks to @Angs for a byte.
JavaScript, 136 bytes
(n)=>{for(a=[],i=0;i<n;a[i]=++i);for(j=0;j<(n&1?n:2);j++){a.reverse();for(i=0;i<a.length-1;i += 2)m=a[i],a[i]=a[i+1],a[i+1]=m;alert(a)}}
R, 109 95 94 79 74 62 bytes
If the fact that the code throws warnings on top of the actual solution (no warnings if n is 1, 3 warnings if n is even and n warnings if n is odd) is not an issue, then the following works similarly to the previous solution, thanks to vector recycling:
n=scan();m=1:n;w=0:n+2*1:0;while(print(m<-rev(m)[w[w<=n]])-1)n
Thanks again to @Giuseppe for an extra 12 bytes off!
Previous, warning-less solution at 94 bytes:
n=scan();m=s=1:n;while(any(print(m<-rev(m)[c(if(n>1)2:1+rep(seq(0,n-2,2),e=2),n[n%%2])])!=s))n
Original solution at 109 bytes:
n=scan();m=s=1:n;repeat{cat(m<-rev(m)[c(t(embed(s,min(n,2))[!!s[-n]%%2,]),n[n%%2])],"\n");if(all(m==s))break}
Ruby, 64 57 52 50 bytes
->x{(s=*w=1..x).map{s=w.map{|y|s[-y^1]||s[0]}}|[]}
How it works:
First create the range, then repeat the permutation x times: use a negative index, but flip the last bit, so we get the sequence -2, -1, -4, -3... if x is even, this will end well, if not we will add the remaining element at the end. Last step: filter out repeated arrays (so we cover all cases: x=1, x=2, odd and even numbers)
Python 2, 165 159 138 81 bytes
x=input()+1
b=a=range(1,x)
while b:b=[b[x-min(x,i+1^1)]for i in a];print b;b*=a<b
-20 bytes thanks to @ChasBrown. (Sigh, I made a whole challenge about extended slicing syntax)
Whoa! GolfStorm (-57 bytes)! Thanks to Ian Gödel, tsh, and Jonathan Frech.
JavaScript (ES6), 89 85
Edit 4 bytes saved thx @JustinMariner
Using the fact that when any element is at the right place, all elements are.
n=>{for(l=[];n;l[n-1]=n--);while(alert(l=l.reverse().map((x,i)=>l[i^1]||x)),l[0]-1);}
Less golfed
n => {
for(l=[], i=0; i<n; l[i] = ++i);
while( alert(l=l.reverse().map( (x,i) => l[i^1] || x)),
l[0]-1);
}
Test
var F=
n=>{for(l=[];n;l[n-1]=n--);while(alert(l=l.reverse().map((x,i)=>l[i^1]||x)),l[0]-1);}
alert=x=>console.log(x+'') // to avoid popup stress
function update() {
F(+I.value);
}
update()
<input type=number id=I value=1 min=1 oninput='update()'>
AWK, 123 bytes
Not very tight, but this is the best I could come up with.
{for(N=$1;N>$i=++i;);for(;n++<(i%2?i:i>2?2:1);){for(k=0;k++<i;)K[k]=(z=i-k+(k-1)%2*2)?$z:$1;for(k=0;k++<N;){$k=K[k]}print}}
JavaScript (ES6), 79 bytes
f=(n,a=[...Array(n)],b=a.map((x,i)=>n-((x?x-1:i)^1)||1))=>b[0]>1?b+`
`+f(n,b):b
Outputs a list for each step.
Note that we don't need to initialize the array to get the ball rolling. If uninitialized (x is undefined), we can use the array's indices (parameter i) to do the first step:
b=a.map((x,i)=>n-((x?x-1:i)^1)||1)
Test Cases:
f=(n,a=[...Array(n)],b=a.map((x,i)=>n-((x?x-1:i)^1)||1))=>b[0]>1?b+`
`+f(n,b):b
console.log(f(1));
console.log(f(2));
console.log(f(3));
console.log(f(4));
console.log(f(5));
console.log(f(7));
console.log(f(27));
TI-Basic (83 series), 58 57 54 bytes (104 characters)
:seq(I,I,1,Ans→A
:Ans→B
:Repeat prod(Ans=ᶫB
:ᶫB→C
:int(⁻Ans/2→D
:SortD(ᶫC,ᶫA
:SortD(ᶫD,ᶫA
:Pause ᶫA
:End
Explanation
Takes input in Ans (e.g., write 5:prgmNAME to use lists of size five).
Creates three auxiliary lists of the given size (which are recreated from ᶫB at each step): ᶫB = ᶫC = {1,2,3,4,5,...} and ᶫD = {-1,-1,-2,-2,-3,...}. At each step, sorts ᶫC and ᶫD in descending order, applying the same permutation to ᶫA. In the case of ᶫC, this reverses ᶫA, and in the case of ᶫD, this swaps adjacent pairs because TI-Basic uses a really stupid selection sort implementation for SortD( which reorders as many identical elements as it possibly can. When ᶫA is equal to ᶫB again, we stop.
No, seriously, their built-in sorting algorithm is my second-biggest complaint with the TI-Basic interpreter. (My biggest complaint is how lots of nested loops slow down the interpreter, since the loop data is stored in a stack, but the stack is grown from the wrong end, so the calculator has to move the entire stack every time an element is pushed or popped.) But this time, it's convenient.
-1 byte: Pause stores the value it's printing to Ans, which is shorter to reference than ᶫA.
-3 bytes: take input in Ans
Stacked, 42 bytes
[~>[rev 2#<$revflatmap]periodsteps behead]
Performs the given transformation using the periodsteps builtin. However, this builtin returns all of the elements, which includes the input's range as its first and last elements. We therefore behead the list, returning all but the first element.
Haskell, 97 bytes
This feels a bit long :(
f n|x<-[1..n]=x:takeWhile(/=x)(tail$iterate((r=<<).g.r)x)
r=reverse
g[]=[]
g x=take 2x:g(drop 2x)
Explanation/Ungolfed
-- starting with x, accumulate the results of repeatedly
-- applying the function permute
f n = x : takeWhile (/=x) (tail $ iterate permute x)
where x = [1..n]
-- reverse, cut2, reverse each pair & flatten
permute = concatMap reverse . cut2 . reverse
-- recursively transform a list into groups of 2
cut2 [] = []
cut2 xs = take 2 xs : g (drop 2 xs)
Husk, 9 bytes
U¡ȯṁ↔C2↔ḣ
-- implicit input N | 3
ḣ -- list [1..N] | [1,2,3]
¡( ) -- iterate the following function, | [[1,2,3],[2,3,1],[3,1,2],[1,2,3],...
U -- until the first repetition: | [[1,2,3],[2,3,1],[3,1,2]]
↔ -- reverse | [3,2,1]
C2 -- cut into two | [[3,2],[1]]
ṁ↔ -- reverse each pair & flatten | [2,3,1]
MATL, 17 bytes
:`tP2ePXz!tG:-a]x
Explanation
: % Implicit input: n. Push [1 2 ... n]
` % Do...while
t % Duplicate
P % Reverse
2e % Reshape into a 2-row matrix. A final 0 is added if needed
P % Reverse each column
Xz % Nonzero entries (i.e. remove final 0 if present). Gives a column vector
! % Transpose into a row
t % Duplicate
G: % Push [1 2 ... n] again
- % Subtract element-wise
a % Any. Gives true if there is at least a nonzero value
] % End. Go to next iteration if top of the stack is true. So the loop ends
% when [1 2 ... n] has been found again
x % Delete top of the stack (which is [1 2 ... n]). Implicit display
Java (OpenJDK 8), 257 245 243 226 206 205 bytes
n->{int i=0,k,t[]=new int[n];while(i<n)t[i]=++i;do{for(i=0;i<n/2;t[i]=t[n+~i],t[n+~i++]=k)k=t[i];for(k=1;k<n;t[k]=t[--k],t[k]=i,k+=3)i=t[k];System.out.println(java.util.Arrays.toString(t));}while(t[0]>1);}
Java 8, 215 214 bytes
import java.util.*;n->{Stack a=new Stack(),t;int i=0;for(;i<n;a.add(++i));t=(Stack)a.clone();Collections x=null;for(i=0;i<1|!a.equals(t);System.out.println(t))for(x.reverse(t),i=0;i<n;i++)if(i<n-1)x.swap(t,i,++i);}
I tried to golf it using actual arrays instead of a List, but both reversing and swapping will take up too many bytes.. Maybe it can be combined in one loop (instead of first reversing, then swapping), but I've yet to figure this out.
This can definitely be golfed some more, though.
Explanation:
import java.util.*; // Required import for Stack and Collections
n->{ // Method with integer parameter and no return-type
Stack a=new Stack(), // Original List
t; // Copy-List
int i=0; // Index-integer, starting at 0
for(;i<n;a.add(++i)); // Fill the original list with the integers
t=(Stack)a.clone(); // Make a copy of the List
Collections x=null; // Static `Collections` to reduce bytes
for(i=0; // Reset index `i` to 0
i<1 // Loop (1) as long as `i` is 0 (the first iteration),
|!a.equals(t); // or the input array is not equal to the copy
System.out.println(t)) // After every iteration: print the modified List
for(x.reverse(t), // Reverse the copied List
i=0; // Reset `i` to 0
i<n; // Inner loop (2) over the List
i++) // After every iteration: increase `i` by 1 again
if(i<n-1) // Unless it's the last item in the List:
x.swap(t,i,++i); // Swap the items at indexes `i` and `i+1`
// (by increasing `i` by 1 first with `++i`)
// End of inner loop (2) (implicit / single-line body)
// End of loop (1) (implicit / single-line body)
} // End of method
JavaScript (ES6), 122 bytes
f=(n,a=[...Array(n)].map((_,i)=>i+1),r=[],b=a.map((_,i)=>a[n+~(i^1)]||a[0]))=>b.some((e,i)=>e>b[i+1],r.push(b))?f(n,b,r):r
r.push(a) could be used instead of r.push(b) to put the original permutation at the front.
05AB1E, 13 11 bytes
LIGÂ2ôí˜})Ù
Explanation
L # range [1 ... input]
IG # input-1 times do:
 # bifurcate
2ô # split into pieces of 2
í # reverse each
˜ # flatten
} # end loop
) # wrap stack in a list
Ù # remove duplicates
Mathematica, 142 bytes
(h=Range@#;W={};For[i=1,i<=#,i++,s=Reverse@h;AppendTo[W,h=Join[f=Flatten[Reverse/@Partition[s,{2}]],s~Complement~f]];s=h];DeleteDuplicates@W)&
Jelly, 10 bytes
RµUs2UFµÐĿ
Explanation
RµUs2UFµÐĿ Main link
R Generate the range
ÐĿ While the results are unique (collecting results)
µUs2UFµ Reverse and reorder
U Reverse
s Slice non-overlapping into length
2 2
U Reverse (automatically vectorizes to depth 1)
F Flatten
Note
If the original range needs to be at the end, append ṙ1 to the code for 12 bytes.