25
\$\begingroup\$

Given a list of positive integers that contains at least 3 distinct entries, output a permutation of that list that isn't sorted in ascending or descending order.

Examples

1,2,3 -> 2,1,3 or 3,1,2 or 1,3,2 or 2,3,1
1,2,3,3 -> 2,1,3,3 or 3,1,2,3 or 1,3,2,3 etc..

Thanks @Arnauld and @NoOneIsHere for the title!

\$\endgroup\$
5
  • \$\begingroup\$ Will the input always be sorted? \$\endgroup\$
    – xnor
    Commented Aug 13, 2017 at 20:31
  • \$\begingroup\$ Must the sort be "reliable" in that given a given set of entries, it always produces the same permutation as output? Or must it only be "reliable" in that the output is not sorted? \$\endgroup\$
    – Wildcard
    Commented Aug 15, 2017 at 3:16
  • \$\begingroup\$ It must just satisfy the specs. \$\endgroup\$
    – flawr
    Commented Aug 15, 2017 at 14:58
  • \$\begingroup\$ Would a nested array be allowed as output? e.g., [2,[1,3]]. \$\endgroup\$
    – Shaggy
    Commented Aug 19, 2017 at 9:51
  • \$\begingroup\$ No, it should be one single array/list. \$\endgroup\$
    – flawr
    Commented Aug 19, 2017 at 11:47

37 Answers 37

14
\$\begingroup\$

JavaScript (ES6), 39 34 bytes

a=>[a.sort((x,y)=>x-y).pop(),...a]

Sort the array in ascending order, pop the last element and use it as the first element of a new array. Then destructure the remaining elements of the original array into the new array (In JS, both sort and pop modify the original array).


Test it

o.innerText=(f=

a=>[a.sort((x,y)=>x-y).pop(),...a]

)(i.value=[1,2,3]);oninput=_=>o.innerText=f(i.value.split`,`)
<input id=i><pre id=o>

\$\endgroup\$
3
  • \$\begingroup\$ Why cant you just do a.sort()? \$\endgroup\$
    – geokavel
    Commented Aug 14, 2017 at 14:47
  • 1
    \$\begingroup\$ @geokavel: Because JS's sort method sorts lexicographically. \$\endgroup\$
    – Shaggy
    Commented Aug 14, 2017 at 14:50
  • 3
    \$\begingroup\$ So because it's already unreliably broken? =D \$\endgroup\$
    – jpmc26
    Commented Aug 15, 2017 at 4:12
10
\$\begingroup\$

Brachylog, 2 bytes

o↻

Try it online!

or

o↺

Try it online!

Sorts then rotates the list

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

Jelly, 3 bytes

Ṣṙ1

Try it online!

\$\endgroup\$
5
  • \$\begingroup\$ Ṣṙ- also works (just felt like saying that; you probably knew :P) \$\endgroup\$
    – hyperneutrino
    Commented Aug 13, 2017 at 20:05
  • \$\begingroup\$ @HyperNeutrino Yep that works too, same bytecount :p \$\endgroup\$ Commented Aug 14, 2017 at 7:43
  • \$\begingroup\$ In which encoding is Ṣṙ1 only three bytes? In UTF-8, it's 7 bytes. \$\endgroup\$ Commented Aug 15, 2017 at 0:46
  • 2
    \$\begingroup\$ @heinrich5991 Jelly uses a custom codepage. \$\endgroup\$
    – cole
    Commented Aug 15, 2017 at 0:54
  • \$\begingroup\$ I feel like everyone who uses Jelly must have a browser extension which adds a button to automatically post the "Jelly uses a custom codepage" comment. \$\endgroup\$
    – 12Me21
    Commented Oct 21, 2017 at 5:13
6
\$\begingroup\$

Ohm, 2 bytes

S╙

Try it online!

Sort and rotate to the right.

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

Japt, 3 bytes

n é

Test it

Sorts (n) the array and rotates it (é) one element to the right.

\$\endgroup\$
5
\$\begingroup\$

Python 3, 31 bytes

lambda a:sorted(a)[1:]+[min(a)]

Try it online!

-1 byte thanks to xnor

\$\endgroup\$
4
  • \$\begingroup\$ ...How did I not see this basic logic. >.> \$\endgroup\$ Commented Aug 13, 2017 at 20:02
  • \$\begingroup\$ @totallyhuman lol all 3 of my answers do the exact same thing. but ha :P Also I merged your PR for iOS -> MacOS :P \$\endgroup\$
    – hyperneutrino
    Commented Aug 13, 2017 at 20:02
  • \$\begingroup\$ Yeah, I noticed and deleted my branch. :P \$\endgroup\$ Commented Aug 13, 2017 at 20:04
  • \$\begingroup\$ Putting the min at the end saves a byte. \$\endgroup\$
    – xnor
    Commented Aug 13, 2017 at 20:11
5
\$\begingroup\$

APL, 9 bytes

{1⌽⍵[⍋⍵]}

Try it online!

How?

⍵[⍋⍵] - sort the list

1⌽ - rotate by 1

\$\endgroup\$
2
  • \$\begingroup\$ Also works in GNU and ngn! \$\endgroup\$
    – Adalynn
    Commented Aug 13, 2017 at 20:32
  • \$\begingroup\$ @Zacharý guess I'll just remove the dyalog... \$\endgroup\$
    – Uriel
    Commented Aug 13, 2017 at 20:37
5
\$\begingroup\$

TI-Basic (TI-84 Plus CE), 31 bytes

Prompt A
SortA(LA
max(LA→B
dim(LA)-1→dim(LA
augment({B},LA

Prompts for input in the format {1,2,3,4}.

TI-Basic is a tokenized language, all tokens used here are one-byte.

Explanation:

Prompt A         # 3 bytes, store user input in LA
SortA(LA         # 4 bytes, sort LA ascending
max(LA→B         # 6 bytes, save the last value in the sorted list to B
dim(LA)-1→dim(LA # 11 bytes, remove the last value from LA
augment({B},LA   # 7 bytes, prepend B to LA and implicitly print the result
\$\endgroup\$
5
\$\begingroup\$

Pyth, 7 5 4 bytes

.P1S

Try it online!

-1 byte thanks to FryAmTheEggman

\$\endgroup\$
2
  • \$\begingroup\$ You can save a byte by using permutations: pyth.herokuapp.com/… \$\endgroup\$ Commented Aug 13, 2017 at 20:52
  • \$\begingroup\$ @FryAmTheEggman thanks, I'll update it when I get to a computer. \$\endgroup\$ Commented Aug 13, 2017 at 21:13
4
\$\begingroup\$

05AB1E, 2 bytes

Try it online!

\$\endgroup\$
4
\$\begingroup\$

05AB1E, 2 bytes

Try it online!

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

Retina, 21 bytes

O#`
s`(.*)¶(.*)
$2¶$1

Try it online! Sort and rotate as per usual. At least there's no unary conversion this time.

\$\endgroup\$
3
\$\begingroup\$

Java 8, 68 37 bytes

l->{l.sort(null);l.add(l.remove(0));}

-31 bytes thanks to @Nevay (forgot Java 8 had a List#sort(Comparator) method..)

Modifies the input-ArrayList, instead of returning a new one.

Explanation:

Try it here.

l->{                   // Method with ArrayList parameter and no return-type
  l.sort(null);        //  Sort the input-list (no need for a Comparator, thus null)
  l.add(l.remove(0));  //  Remove the first element, and add it last
}                      // End of method
\$\endgroup\$
3
  • \$\begingroup\$ You can use l->{l.sort(null);java.util.Collections.rotate(l,1);} to save 16 bytes. \$\endgroup\$
    – Nevay
    Commented Aug 14, 2017 at 12:19
  • 2
    \$\begingroup\$ Alternatively you can use l->{l.sort(null);l.add(l.remove(0));} to save 31 bytes (requires the usage of a not fixed sized list). \$\endgroup\$
    – Nevay
    Commented Aug 14, 2017 at 12:24
  • \$\begingroup\$ @Nevay nice one, but... the parentheses are a bit off in regards to the documentation: the reality is that the optional operations add and remove must be implemented; nothing is said about fixed-sized list... Kevin Cruijssen, given that there are much better alternatives in the previous comments, I'll wait for an edit before +1ing. \$\endgroup\$ Commented Aug 14, 2017 at 13:52
3
\$\begingroup\$

Haskell, 36 37 bytes

import Data.List
f(a:b)=b++[a];f.sort

Use view patterns to match on the head of a sorted version of the input list, then append the first item of the list to the tail of the remaining list.

View patterns aren't worth it. Sort the list, take the head off, append it to the end. In this case, it turns out that the naive solution typed out compactly is the best.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Welcome to PPCG! Great idea to use view patterns, I didn't know about them before. Unfortunately, they are not enabled in standard Haskell, so per site rules you need to include the bytes for the command line flag -XViewPatterns. Counting those the standard way f(a:b)=b++[a];f.sort is shorter. \$\endgroup\$
    – Laikoni
    Commented Aug 15, 2017 at 18:57
  • \$\begingroup\$ I somehow wasn't thinking about the flag needed. I guess I use them so much that I forgot that I turn it on in my Cabal files and that it's not part of the language. \$\endgroup\$
    – typedrat
    Commented Aug 16, 2017 at 19:37
2
\$\begingroup\$

Perl 6,  43  19 bytes

{first {![<=]($_)&&![>=] $_},.permutations}

Try it

*.sort[1..*,0].flat

Try it

Note that [1..*,0] would result in ((2,3),1), so .flat is there to turn it into (2,3,1)

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

Mathematica, 18 bytes

RotateLeft@Sort@#&

Try it online!

\$\endgroup\$
1
  • 4
    \$\begingroup\$ Shorter: RotateLeft@*Sort \$\endgroup\$ Commented Aug 14, 2017 at 3:46
2
\$\begingroup\$

Ly, 7 bytes

&nasprl

Try it online!

Ugh, ruining the sort is so expensive!

Explanation:

&nasprl

&n      # take input as a list of numbers
  a     # sort
   sp   # save top of stack and pop
     r  # reverse stack
      l # load saved item
\$\endgroup\$
2
\$\begingroup\$

R, 33 32 29 bytes

Takes input from stdin. Sorts the list and then moves the first element to the end, ensuring that it is no longer sorted. Saved three bytes due to Giuseppe.

c(sort(x<-scan())[-1],min(x))

Another implementation, same byte count:

c((x<-sort(scan()))[-1],x[1])
\$\endgroup\$
1
  • \$\begingroup\$ c(sort(x<-scan())[-1],min(x)) is 29 bytes using essentially the same idea as yours. \$\endgroup\$
    – Giuseppe
    Commented Aug 29, 2017 at 21:15
1
\$\begingroup\$

Ohm, 2 bytes

S╜

Try it online!

I think this is dissimilar enough from totallyhuman's post to post a new answer; I hope you don't mind :P EDIT: DAMMIT YOU NINJA'D ME

\$\endgroup\$
1
  • \$\begingroup\$ Ninja'd you. ;) \$\endgroup\$ Commented Aug 13, 2017 at 20:11
1
\$\begingroup\$

Python, 31 bytes

def f(a):a[1:]=a[a.sort():0:-1]

Yet another Python solution.

Sadly, this one has the same length to HyperNeutrino's answer.

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

Gaia, 3 bytes

ȯ1«

Try it online!

Same as other answers: sort ȯ and rotate left once .

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

Retina, 10 bytes

O#`
O^#-2`

Try it online!

O#`     Sort the list
O^#-2`  Reverse sort the list other than the last element

This leaves the list with the 2nd highest element first and the highest element last which is never correctly sorted

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

Ruby, 18 bytes

Submitted on mobile. Please don't kill me for problems.

->a{a.sort.rotate}
\$\endgroup\$
1
\$\begingroup\$

Pyth, 5 bytes

.>SQ1

Explanation

SQ - sort input list

.>SQ1 - rotate input list cyclicaly by 1

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

Proton, 19 bytes

a=>sorted(a)[1to,0]

Try it online!

-2 bytes indirectly thanks to xnor

Not yet working on TIO; waiting for a pull.

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

Python 3, 28 bytes

lambda a:a[1:a.sort()]+a[:1]

Try it online!

a.sort() sorts a in place and returns None. None can be used as a slicing index and is the same as omitting that index.

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

Python 3, 31 bytes

lambda a:a.sort()or[a.pop(),*a]

Try it online! or Verify all test cases.

Inspired by Shaggy's JS answer.

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

RProgN 2, 2 bytes

§›

Try it online!

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

PHP, 44 bytes

requires PHP 5.4 or later for short array syntax.

sort($a=&$argv);print_r([array_pop($a)]+$a);

sort arguments, replace 0-th argument with removed last argument, print.
Run with -nr or try it online.


The 0-th argument is the script file name, "-" if you call PHP with -r. "-" is compared to the other arguments as a string, and since ord("-")==45, it is smaller than any number. The numbers themselves, although strings, are compared as numbers: "12" > "2".

php -nr '<code>' 3 4 2 5 1 and sort($a=&$argv) lead to $a=["-","1","2","3","4","5"]
[array_pop($a)]+$a is [0=>"5"]+[0=>"-",1=>"1",2=>"2",3=>"3",4=>"4"],
which results in [0=>"5",1=>"1",2=>"2",3=>"3",4=>"4"].

\$\endgroup\$
2
  • \$\begingroup\$ Can you explain why [array_pop($a)]+$a doesn't overwrite the 0th index of $a? For example: $a=[1,2,3,4,5], array_pop($a) = 5, $a=[1,2,3,4]. If you do [5]+[1,2,3,4], shouldn't it end up being [5,2,3,4] because both arrays have a 0th index? I'm confused because the PHP manual says "The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored." \$\endgroup\$
    – halfmang
    Commented Aug 14, 2017 at 23:08
  • \$\begingroup\$ @jstnthms The + operator does not append, it merges (without reordering the indexes; but that doesn´t matter here). The important point is that $a points to $argv and $argv[0] contains the script´s file name, the arguments start at index 1. I extended the description. Thanks for the question. \$\endgroup\$
    – Titus
    Commented Aug 15, 2017 at 7:49
1
\$\begingroup\$

Julia, 23 bytes

f(x)=sort(x)[[2:end;1]]

Slightly shorter than, but equivalent to f(x)=circshift(sort(x),1). I wish I could makeamethod based on select that was more, compact but I can not

\$\endgroup\$

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.