Sort odd numbers first

20

4

Rearrange a given list such that all the odd numbers appear before all the even numbers. Besides for this requirement, the output list may be in any order.

The input will only contain integers, but they may be negative and there may be duplicates, and they may appear in any order.

Shortest solution wins.

Test cases

[1,2][1,2]

[2,1][1,2]

[1,0,0][1,0,0]

[0,0,-1][-1,0,0]

[3,4,3][3,3,4]

[-4,3,3][3,3,-4]

[2,2,2,3][3,2,2,2]

[3,2,2,2,1,2][1,3,2,2,2,2] or [3,1,2,2,2,2]

[-2,-2,-2,-1,-2,-3][-1,-3,-2,-2,-2,-2,] or [-3,-1,-2,-2,-2,-2,]

[][]

display_name

Posted 2018-07-18T05:25:32.787

Reputation: 377

Ty. Good question. Answer: odd numbers can come in any order. :) – display_name – 2018-07-18T05:37:27.003

this is somewhat similar – dylnan – 2018-07-18T05:40:26.407

Can there be any negative numbers in the input? – user202729 – 2018-07-18T06:14:44.433

Integers expected. – display_name – 2018-07-18T06:16:23.773

11Even though the challenge is quite simple, adding some test cases would be nice. E.g. at first glance I thought the block of odd and even numbers also needs to be sorted. – Laikoni – 2018-07-18T07:17:34.750

@Laikoni I agree. – display_name – 2018-07-18T07:23:41.847

for test cases I'd suggest [1,2], [2,1], [1,0,0], [0,0,-1], [3,4,3], [-4,3,3], [2,2,2,3], [3,2,2,2,1,2] (with both possible outputs) and [-2,-2,-2,-1,-2,-3] (again giving both outputs). – Jonathan Allan – 2018-07-18T07:55:08.380

You may also want to add some edge cases: [], [3,1,3], and [2,8,8] – Adám – 2018-07-18T08:11:15.783

Nice first challenge! – Adám – 2018-07-18T08:11:54.280

@dylnan, given that the majority of the solutions to that challenge use this sorting method, I'd lean towards this being a dupe, but I won't VTC as my vote is a hammer. – Shaggy – 2018-07-18T08:35:52.650

Will there be repeated numbers in the array? – Asone Tuhid – 2018-07-18T09:38:14.930

1@AsoneTuhid Yes:), numbers can repeat. – display_name – 2018-07-18T09:47:47.843

@Willmore what about negatives? – Asone Tuhid – 2018-07-18T09:50:37.963

@AsoneTuhid Negatives allowed since integers include negatives. – display_name – 2018-07-18T10:07:12.887

11

@Willmore You never know with code golf, rules are important. Please use the Sandbox next time to clarify your question before you post it.

– Asone Tuhid – 2018-07-18T10:09:40.067

12Please edit your question to include the clarifications you gave in the comments. – Laikoni – 2018-07-18T11:18:02.790

Answers

13

05AB1E, 2 bytes

ΣÉ

Try it online!

Mr. Xcoder

Posted 2018-07-18T05:25:32.787

Reputation: 39 774

11

Pyth, 4 3 bytes

-1 byte thanks to isaacg

iD2

Try it online!

crossed out 4 is still regular 4

chromaticiT

Posted 2018-07-18T05:25:32.787

Reputation: 211

2Nice, I had oiI2. – Mr. Xcoder – 2018-07-18T06:01:29.787

4How about iD2? – isaacg – 2018-07-18T17:59:34.677

Alternate 3 byte solution: oi2 – Sok – 2018-07-31T10:33:12.943

9

J, 5 bytes

\:2&|

Try it online!

\: sort descending by

2&| mod-2

Adám

Posted 2018-07-18T05:25:32.787

Reputation: 37 779

Nice to see you coming over to the dark side... – Jonah – 2019-02-05T21:19:35.637

@Jonah I had a weak moment. – Adám – 2019-02-05T21:20:57.977

9

R, 30 24 bytes

(x=scan())[order(!x%%2)]

Try it online!

-6 bytes thanks to JayCe

Giuseppe

Posted 2018-07-18T05:25:32.787

Reputation: 21 077

Nice! you can do 26 bytes

– JayCe – 2018-07-18T14:02:37.890

24 for full program – JayCe – 2018-07-18T14:08:22.637

@JayCe facepalm golfing at 3am with a new baby is not optimal. Thanks! – Giuseppe – 2018-07-18T14:24:20.970

5Congrats! A future Scratch golfer ? – JayCe – 2018-07-18T14:34:43.153

This gives you a 25 bytes answer to this linked question

– JayCe – 2018-07-18T17:04:51.013

@JayCe haha, maybe!! I started on Terrapin Logo, so we'll see what newfangled teaching language has been developed by the time she can program! – Giuseppe – 2018-07-18T20:29:03.587

1My congrats also Giuseppe, as our Dr said to us, well done you have an expensive one :) – MickyT – 2018-07-22T07:07:47.557

9

C++, 79 76 64 bytes

[](auto a,auto b){while(a<--b)*a%2?*++a:(*a^=*b,*b^=*a,*a^=*b);}

This function accepts a pair of iterators (which must be random access iterators), and steadily moves them towards each other. When a points to an odd number, it is advanced. Otherwise, a points to an even number; b is decremented, and iter_swap'ed with a. (We use XOR swap, which saves us having to include <algorithm> - or <utility> for std::swap).

There are unnecessary swaps when b points to an even number, but we're golfing, not squeezing efficiency!

Demo

auto f=[](auto a,auto b){while(a<--b)*a%2?*++a:(*a^=*b,*b^=*a,*a^=*b);};

#include <array>
#include <iostream>
int main()
{
    auto a = std::array{ 3,2,2,5,2,1,2 };

    f(a.begin(),a.end());

    for (auto i: a)
        std::cout << i << " ";
    std::cout << std::endl;
}

Non-competitive answer

The natural C++ method is std::partition, but that comes out at 83 bytes:

#include<algorithm>
[](auto a,auto b){std::partition(a,b,[](auto x){return x&1;});}

Toby Speight

Posted 2018-07-18T05:25:32.787

Reputation: 5 058

I believe that's 80 bytes, since you need a newline after the #include directive. My math sucks though^^. You can replace != with -, saving 1 byte. I like your approach, it's clever! – O.O.Balance – 2018-07-18T14:04:17.353

1otherwise the iterators could pass each other without ever becoming equal. If you're using RandomAccessIterator, you can use while(a<b) if that's more convenient than a!=b using a @O.O.Balance's a-b version. – Peter Cordes – 2018-07-19T11:12:48.590

You can shorten the 83-byte answer a bit by replacing algorithm with regex: https://codegolf.stackexchange.com/a/150895

– O.O.Balance – 2018-07-21T19:22:34.623

8

Japt, 2 bytes

ñv

Try it online!

Luis felipe De jesus Munoz

Posted 2018-07-18T05:25:32.787

Reputation: 9 639

7

Perl 6, 12 bytes

*.sort(*%%2)

Try it online!

Some Whatever code that sorts the input by parity, with odd numbers first. You can remove a % to get even numbers first instead. Note that 'Whatever' is the name of this sort of anonymous function.

Jo King

Posted 2018-07-18T05:25:32.787

Reputation: 38 234

1Sorry! I accidentally edited your answer instead of mine! – Chas Brown – 2018-07-18T05:46:44.283

6

MATL, 6 bytes

tog&)v

Try it on MATL Online

Alternately:

to_2$S

Try it on MATL Online

sundar - Reinstate Monica

Posted 2018-07-18T05:25:32.787

Reputation: 5 296

5

Python 2, 37 36 bytes

lambda a:sorted(a,key=lambda x:~x%2)

Try it online!

1 byte tip o' the hat to Mr. Xcoder.

Chas Brown

Posted 2018-07-18T05:25:32.787

Reputation: 8 959

1~ should work instead of 1-. – Mr. Xcoder – 2018-07-18T06:01:59.797

@Mr. Xcoder: indeed, it does! – Chas Brown – 2018-07-18T06:25:04.363

5

Haskell, 23 22 bytes

f odd<>f even
f=filter

Try it online! This is equivalent to

g x = filter odd x ++ filter even x

-1 byte thanks to Lynn


Other approaches:

(<>).($odd)<*>($even)$filter
f x=[i|m<-[0,1],i<-x,odd$m+i]
f x=[i|m<-[1,0],i<-x,mod i 2==m]
f x=id=<<filter<$>[odd,even]<*>[x]

Laikoni

Posted 2018-07-18T05:25:32.787

Reputation: 23 676

But doesn't this need import Data.Semigroup? – AlexJ136 – 2018-07-18T08:56:35.453

1

@AlexJ136 As of GHC 8.4.1, (<>) is part of Prelude. As TIO still runs an older version, the import is needed there. But you're right, I should have mentioned this directly.

– Laikoni – 2018-07-18T09:02:29.163

1k odd<>k even;k=filter saves a byte. – Lynn – 2018-07-18T10:27:59.883

5

JavaScript (Node.js), 29 bytes

a=>a.sort((a,b)=>(b&1)-(a&1))

Try it online! Save 4 bytes by only supporting positive values using b%2-a%2. If you write this as:

function(a){return a.sort((a,b)=>(b&1)-(a&1))}

then it will work on all sorts of old JavaScript implementations that didn't sort stably.

Neil

Posted 2018-07-18T05:25:32.787

Reputation: 95 035

1Doesn't a=>a.sort((a,b)=>b&1-a&1) work ? – Alexis Facques – 2018-07-18T11:43:08.230

1@AlexisFacques No, that parses as b&(1-a)&1. – Neil – 2018-07-18T13:56:40.950

1a=>a.sort(a=>++a&1) is shorter :) – Max – 2018-07-19T14:34:08.340

@Max It might work on the given test cases but I wouldn't be surprised if someone found an example where it doesn't work. – Neil – 2018-07-19T14:42:20.697

Ah, my appologies! Let me re-write it: a=>a.sort(a=>++a&1-.5). This always returns a negative or a positive -- depending on the parity. Hence, whenever a is odd, and b is even, a will be placed before b. If they are of the same parity, the output of our callback shouldn't matter – Max – 2018-07-19T14:45:02.087

1@Max You might as well submit that as your own answer. – Neil – 2018-07-19T14:47:43.443

@Neil, @Max it should be valid for all valid inputs. (x+1)&1 is 0 for all odd x and 1 for all even x, where x is an integer in the range [-Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], inclusive. – asgallant – 2018-07-19T14:54:00.193

@asgallant I agree -- but disagree it's valid for all inputs. Returning 0 means "you decide" to JS. You need to return a negative value. (EDIT: my fix for this was also wrong, you need to add brackets to make things work) – Max – 2018-07-19T14:54:46.597

@Max I still think it's valid under the ECMAScript specs (browser implementations may vary, of course). The spec says 0 means leave the order unchanged, not "you decide" (MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description). I haven't tested across browsers, but at least Chrome follows the spec here.

– asgallant – 2018-07-19T15:13:57.313

Very interesting, I'll add that version to my answer (unless @Neil wants to add it to theirs?) – Max – 2018-07-19T21:06:14.710

5

Stax, 5 bytes

{|eom

Run and debug it

Explanation:

{|eom Full program, implicit input
{  o  Sort by key:
 |e     Is odd?
    m Map over result:
        Implicit output with newline

wastl

Posted 2018-07-18T05:25:32.787

Reputation: 3 089

5

Attache, 11 bytes

SortBy!Even

Try it online!

Explanation

Even returns true for even numbers and false otherwise. SortBy ranks false < true (by a numerical cast to 0 < 1), thus placing odd numbers before even ones.

Conor O'Brien

Posted 2018-07-18T05:25:32.787

Reputation: 36 228

5

T-SQL, 26 bytes

SELECT*FROM t ORDER BY~i&1

Uses the bitwise AND operator "&" to compare the last digit with 1.

EDIT: Bitwise NOT then shorter than adding 1. EDIT2: Reorder to allow removal of the space.

George Dando

Posted 2018-07-18T05:25:32.787

Reputation: 151

1Nice! Beat me by 5! Save one more byte by swapping the order and dropping the space: ORDER BY~i&1 – BradC – 2018-07-19T16:12:25.893

4

Jelly, 3 bytes

ḂÞṚ

Try it online!

One of the more oft-wanted atoms seems to be an is-even one (which would make this 2 bytes), without it we must reverse I believe...

ḂÞṚ - Link: list of integers
 Þ  - sort by:
Ḃ   -   bit (least significant bit - i.e. 1 if odd 0 if even)
  Ṛ - reverse

Jonathan Allan

Posted 2018-07-18T05:25:32.787

Reputation: 67 804

4

PHP, 55 bytes

~14 months later and I'm a little bit better at golfing now:

for(;''<$n=$argv[++$i];$s=$n%2?"$n $s":"$s $n");echo$s;

Try it online!


PHP (>=5.4), 84 82 bytes

(-2 bytes, thanks to Ismael Miguel)

<?array_shift($a=&$argv);usort($a,function($i){return$i%2==0;});echo join(' ',$a);

To run it:

php -n <filename> <number_1> <number_2> ... <number_n>

Example:

php -n sort_odds_first.php 2 0 1 -1 3 8 29 -666

Or Try it online!

Night2

Posted 2018-07-18T05:25:32.787

Reputation: 5 484

1Instead of $a=array_slice($argv,1);, use array_shift($a=&$argv);, which saves 1 byte. Also, remove the space before $a in join(' ', $a), saving another byte. Also, PHP 5.3 gives different results. You should specify for which version of PHP this solution is for. – Ismael Miguel – 2018-07-20T11:02:22.340

1@IsmaelMiguel: Thanks for the array_shift idea and pointing out the space mistake. I'm not sure how did I miss the space :D I have added the PHP >= 5.4 in title as well. – Night2 – 2018-07-20T18:25:36.203

It is a common mistake. I actually was surprised by the array_shift when I tried it and worked. – Ismael Miguel – 2018-07-20T19:08:16.427

4

JavaScript, 22 20 bytes

a=>a.sort(a=>!(a%2))

Try it online!

andii1997

Posted 2018-07-18T05:25:32.787

Reputation: 41

I think you can drop the parentheses around your third a. – Jonathan Frech – 2018-07-18T11:04:22.800

Doesn't work if 0 is included in the array. – Shaggy – 2018-07-18T11:19:03.550

That's wrong. js comparator doiesn't work in such way. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description

– Qwertiy – 2018-07-18T11:48:15.923

I know how it should work and how you should use it for production, but in this case, this also works – andii1997 – 2018-07-18T11:59:12.743

2According to the ECMA specification, "If comparefn is not undefined and is not a consistent comparison function for the elements of this array (see below), the behaviour of sort is implementation-defined." This compare function is not consistent. So this is not a JavaScript answer, but it might be an answer for some particular JavaScript implementation, and you'd have to name which implementation. – user5090812 – 2018-07-18T13:33:06.897

1I think this fails for [1,2,3,4,5,6,6,-1,-2,-3,-4]. JavaScript array.sort is weird. – Chas Brown – 2018-07-18T20:18:12.260

It is weird, that it works with just one parameter – andii1997 – 2018-07-18T20:27:46.230

a%2 will be weird for negative numbers. For example, -1 % 2 is -1 which is truthy. – Max – 2018-07-19T14:33:15.967

@Max: If you can assume 2's complement in JS, you can use a&1 to get 0 or 1. Negative odd numbers still have their low bit set in 2's complement and sign/magnitude, but not one's complement. – Peter Cordes – 2018-07-20T00:27:30.460

@user5090812: The wording about consistency in Qwerty's link only says it must return the same for the same inputs. Does consistency also require that if (a,b) => -1, (b,a) must return +1 rather than also -1? I think another problem is maybe treating a and b as equal when they're not. So return !(a%2)*2-1 to get -1 or +1. Or something like 1-2*(a&1) might also work, with some operator-precedence golfing. – Peter Cordes – 2018-07-20T00:37:04.450

3

Red, 42 bytes

func[a][sort/compare a func[n][n % 2 = 1]]

Try it online!

If we need to account for negative values:

Red, 43 bytes

func[a][sort/compare a func[n][n // 2 = 1]]

Try it online!

Galen Ivanov

Posted 2018-07-18T05:25:32.787

Reputation: 13 815

3

Husk, 4 bytes

↔Ö%2

Try it online!

Explanation

 Ö     sort input according to the result of the following function
  %2   modulo 2
↔      reverse result to get odd numbers to the front

Laikoni

Posted 2018-07-18T05:25:32.787

Reputation: 23 676

3

Scala, 18 bytes

_.sortBy(_.+(1)%2)

AlexJ136

Posted 2018-07-18T05:25:32.787

Reputation: 251

3

Ruby, 23 bytes

->a{a.sort_by{|i|~i%2}}

Try it online!

Explanation:

sort_by sorts every number as if its value were the result of the block (~i%2)

~x is equivalent to -x-1 and takes precedence over %2

Odd numbers will evaluate to 0 and even numbers will evaluate to 1 so odd numbers will be sorted first.

Barely related: this works on ruby from homebrew 2.5.1p57 (because it's based on a small bug) but only for non-negative integers, 20 bytes

->a{a.sort{|i|i%-2}}

Explanation:

This uses sort which expects a block that takes 2 values and returns -1, 0 or 1 depending on whether the first one is bigger, they're equal or the second one is bigger.

The block given here ignores the second value and returns -1 if the first number is odd or 0 if it's even.

It's not guaranteed to work but it does in some (I think buggy) implementations.

Asone Tuhid

Posted 2018-07-18T05:25:32.787

Reputation: 1 944

We define languages by their implementation here so your 20 byte solution is valid. – Shaggy – 2018-07-18T11:17:39.373

@Shaggy Never mind, I had messed up my testing yesterday. – Asone Tuhid – 2018-07-19T09:30:08.970

3

PowerShell, 22 19 bytes

$args|sort{!($_%2)}

Try it online!

Takes input via splatting, e.g., $a=(3,4,3); .\sort-odd-numbers-first.ps1 @a, which on TIO manifests as separate arguments for each entry.

Like some other answers here, Sort-Object can compare based on an expression. Here the expression is !($_%2), i.e., odds get sorted to $false and evens get sorted to $true. Thanks to how Boolean values are compared, falsey values are sorted first. This moves the odds to the beginning of the output, and the evens to the end. Sort-Object is stable, so the ordering of the individual items in their respective categories doesn't change (as in the TIO example).

-3 bytes thanks to mazzy.

AdmBorkBork

Posted 2018-07-18T05:25:32.787

Reputation: 41 581

It can to use a splatting. For example $a=(3,4,3); .\sort-odd-numbers-first.ps1 @a. So $args|sort{!($_%2)} is enough. Isn't it?

– mazzy – 2018-07-20T14:47:25.557

why "cheating"? it's native powershell feature. One more question: can we to use splatting inside codeGolf solution? for example, a solution contains several functions. if we can then why external call should not? if we cannot then why this feature banned? and what features are banned too? – mazzy – 2018-07-20T18:31:27.833

1@mazzy Thanks for pointing that out. I've updated my submission. – AdmBorkBork – 2018-07-20T19:29:22.330

3

JavaScript (Chrome v67) - 24 19 23 bytes

a=>a.sort(a=>!(a&1)-.5)

The use of &1 rather than Math.abs()%2 was stolen from @Neil. Thanks!

Thanks to @Shaggy for showing my hacky 19 byte solution wasn't valid. If anyone wants it:

Depends on how the browser handles a hacky return value of 0. Chrome v67, after 100000 iterations of random arrays never sorted it wrong. I'm very sure it works -- and it relies on the specific sort algorithm Chrome uses too, I believe. (It might work in other browsers, that's not the point)

a=>a.sort(a=>++a&1)

Max

Posted 2018-07-18T05:25:32.787

Reputation: 131

Welcome to PPCG :) This fails for input [-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19] in my Chrome 67 console, outputting [7,-5,-3,17,-1,15,1,13,3,11,5,9,2,19,14,-4,6,18,-2,16,0,10,8,12,4]. – Shaggy – 2018-07-20T09:07:36.047

@Shaggy -- oops! you're absolutely right! – Max – 2018-07-20T10:21:29.900

3

C#, 23 bytes

i=>i.OrderBy(u=>u%2==0)

Quite straigt forward really: This basically converts the numbers to booleans, whilst true means that the number is even and false that it's odd. Because true is higher than false the even numbers appear first.

The formatted version looks like that:

i => i.OrderBy (u => u % 2 == 0)

And you can test it like that:

Console.WriteLine (string.Join (",", new Func <IEnumerable <int>, IEnumerable <int>> (
                                    i => i.OrderBy (u => u % 2 == 0)
                                ).Invoke (new [] {3, 2, 2, 2, 1, 2, 5, 5})));

Which results in the following:

3,1,5,5,2,2,2,2

MetaColon

Posted 2018-07-18T05:25:32.787

Reputation: 391

1Try it online! – Neil – 2018-07-19T18:58:37.277

3

JavaScript, 23 bytes

6 bytes shorter than @Neil's answer using the same language :D

a=>a.sort(n=>-(n&1)||1)

Explanation:

The function passed to sort only cares about the first parameter. If it is odd it returns -1 (the result of -(n&1)). Otherwise (when -(n&1) yields 0) it returns 1.

Try it online!

ibrahim mahrir

Posted 2018-07-18T05:25:32.787

Reputation: 551

2Welcome to PPCG! – Jonathan Frech – 2018-07-19T22:47:01.327

3

Python, 35 bytes

lambda l:sorted(l,key=(-1).__pow__)

Try it online!

Sorts by the function x -> (-1)**x, which gives -1 for odd and 1 for even.

xnor

Posted 2018-07-18T05:25:32.787

Reputation: 115 687

3

JavaScript, 21 bytes

a=>a.sort(n=>(-1)**n)

Try it online

Shaggy

Posted 2018-07-18T05:25:32.787

Reputation: 24 623

3

6502 machine code routine, 47 bytes

A0 00 84 FE B1 FB 4A 90 07 C8 C4 FD F0 20 D0 F4 2A 85 02 84 FE A4 FD 88 C4 FE
F0 12 B1 FB 4A 90 F6 2A AA A5 02 91 FB A4 FE 8A 91 FB 90 D6 60

Expects a pointer to an array of numbers in $fb/$fc and the length of this array in $fd. Manipulates the array in place to have all odd numbers in front. This is position independent code, so no load address is needed.

As the 6502 is an 8bit chip (so the instructions only deal with 8bit values, optionally signed), the valid number range is [-128 .. 127] and the maximum array size is 256.

Commented disassembly

; function to "partially sort" array, so all odd numbers come before all
; even numbers.
;
; input:
;   $fb/$fc: address of array to sort
;   $fd:     length of array to sort, 0 means 256 (maximum size)
;
; clobbers:
;   $fd/$fe: position from back/front of array
;   $2:      temporary for exchanging two values
;   A, X, Y

 .oddfirst:
A0 00       LDY #$00            ; initialize index from front
84 FE       STY $FE             ; to 0

 .search_front:
B1 FB       LDA ($FB),Y         ; load number from front
4A          LSR A               ; check for even/odd by shifting
90 07       BCC .search_back    ; if odd -> to searching from back
C8          INY                 ; next position from front
C4 FD       CPY $FD             ; same as position searching from back?
F0 20       BEQ .done           ; then we're finished
D0 F4       BNE .search_front   ; else check next from front
 .search_back:
2A          ROL A               ; shift carry back in
85 02       STA $02             ; and save number to temp
84 FE       STY $FE             ; save index from front
A4 FD       LDY $FD             ; load index from back
 .sb_loop:
88          DEY                 ; previous position from back
C4 FE       CPY $FE             ; same as position searching from front?
F0 12       BEQ .done           ; then we're finished
B1 FB       LDA ($FB),Y         ; load number from back
4A          LSR A               ; check for even/odd by shifting
90 F6       BCC .sb_loop        ; if odd -> check previous position
2A          ROL A               ; shift carry back in
AA          TAX                 ; remember in X
A5 02       LDA $02             ; load temporary from front
91 FB       STA ($FB),Y         ; store at current position
A4 FE       LDY $FE             ; load index from front
8A          TXA                 ; load remembered number
91 FB       STA ($FB),Y         ; store at current position
90 D6       BCC .search_front   ; and back to searching from front
 .done:
60          RTS

Example C64 assembler program using the routine:

Online demo

screenshot

Code in ca65 syntax:

.import oddfirst ; link with routine above

.segment "BHDR" ; BASIC header
                .word   $0801           ; load address
                .word   $080b           ; pointer next BASIC line
                .word   2018            ; line number
                .byte   $9e             ; BASIC token "SYS"
                .byte   "2061",$0,$0,$0 ; 2061 ($080d) and terminating 0 bytes

.bss
linebuf:        .res    5               ; maximum length of a valid signed
                                        ; 8-bit number input
convbuf:        .res    3               ; 3 BCD digits for signed 8-bit
                                        ; number conversion
numbers:        .res    $100            ; maximum array size that can be
                                        ; directly handled with indexing
                                        ; instructions

.data
prompt:         .byte   "> ", $0
message:        .byte   $d, $d, "Enter one number per line.", $d
                .byte   "just press enter (empty line) when done.", $0
errmsg:         .byte   "Error parsing number, try again.", $d, $0

.code
                lda     #$17            ; set upper/lower mode
                sta     $d018

                lda     #0
                sta     $2a             ; index for number array
                sta     $52             ; flag that at least one number was
                                        ; entered

                lda     #<message       ; display message
                ldy     #>message
                jsr     $ab1e

inputloop:
                lda     #<prompt        ; display prompt
                ldy     #>prompt
                jsr     $ab1e

                lda     #<linebuf       ; read string into buffer
                ldy     #>linebuf
                ldx     #5
                jsr     readline

                lda     linebuf         ; empty line?
                beq     process         ; -> start processing

                lda     #<linebuf       ; convert input to int8
                ldy     #>linebuf
                jsr     toint8
                bcc     numok           ; successful -> store number
                lda     #<errmsg        ; else show error message and repeat
                ldy     #>errmsg
                jsr     $ab1e
                bcs     inputloop

numok:          ldx     #$ff            ; set flag that we have a number
                stx     $52
                ldx     $2a
                sta     numbers,x
                inc     $2a             ; next index
                bne     inputloop       ; if array not full, next input

process:        lda     $52             ; check we have some numbers
                beq     exit            ; otherwise exit program

                lda     #<numbers       ; address of array to $fb/fc
                sta     $fb
                lda     #>numbers
                sta     $fc
                lda     $2a             ; length of array to $fd
                sta     $fd
                jsr     oddfirst        ; call "sorting" function

                lda     #$0             ; index variable for output loop
                sta     $52
outloop:        ldy     $52             ; load current index
                lda     numbers,y       ; load current number
                jsr     printnum        ; -> output
                inc     $52             ; next index
                lda     $52             ; compare with ...
                cmp     $2a             ; ... array size
                bne     outloop         ; not reached yet -> repeat

exit:           rts                     ; done, exit program

; read a line of input from keyboard, terminate it with 0
; expects pointer to input buffer in A/Y, buffer length in X
.proc readline
                dex
                stx     $fb
                sta     $fc
                sty     $fd
                ldy     #$0
                sty     $cc             ; enable cursor blinking
                sty     $fe             ; temporary for loop variable
getkey:         jsr     $f142           ; get character from keyboard
                beq     getkey
                sta     $2              ; save to temporary
                and     #$7f
                cmp     #$20            ; check for control character
                bcs     checkout        ; no -> check buffer size
                cmp     #$d             ; was it enter/return?
                beq     prepout         ; -> normal flow
                cmp     #$14            ; was it backspace/delete?
                bne     getkey          ; if not, get next char
                lda     $fe             ; check current index
                beq     getkey          ; zero -> backspace not possible
                bne     prepout         ; skip checking buffer size for bs
checkout:       lda     $fe             ; buffer index
                cmp     $fb             ; check against buffer size
                beq     getkey          ; if it would overflow, loop again
prepout:        sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and clear 
                and     #$7f            ;   cursor in
                sta     ($d1),y         ;   current row
output:         lda     $2              ; load character
                jsr     $e716           ;   and output
                ldx     $cf             ; check cursor phase
                beq     store           ; invisible -> to store
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and show
                ora     #$80            ;   cursor in
                sta     ($d1),y         ;   current row
                lda     $2              ; load character
store:          cli                     ; enable interrupts
                cmp     #$14            ; was it backspace/delete?
                beq     backspace       ; to backspace handling code
                cmp     #$d             ; was it enter/return?
                beq     done            ; then we're done.
                ldy     $fe             ; load buffer index
                sta     ($fc),y         ; store character in buffer
                iny                     ; advance buffer index
                sty     $fe
                bne     getkey          ; not zero -> ok
done:           lda     #$0             ; terminate string in buffer with zero
                ldy     $fe             ; get buffer index
                sta     ($fc),y         ; store terminator in buffer
                sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and clear 
                and     #$7f            ;   cursor in
                sta     ($d1),y         ;   current row
                inc     $cc             ; disable cursor blinking
                cli                     ; enable interrupts
                rts                     ; return
backspace:      dec     $fe             ; decrement buffer index
                bcs     getkey          ; and get next key
.endproc

; print an int8 number to the screen
; input:
;   A - the number to print
; clobbers:
;   X, Y
.proc printnum
                bpl     doprint         ; positive? -> direct number output
                eor     #$ff            ; else invert, 
                sta     $2              ; ...
                inc     $2              ; add one,
                lda     #'-'            ; output a minus sign
                jsr     $e716
                lda     $2
doprint:        tax                     ; number to X reg
                lda     #$0             ; set A to 0
                jsr     $bdcd           ; routine for uint16 in X/A output
                lda     #' '            
                jmp     $e716           ; and print a space
.endproc

; parse / convert int8 number using a BCD representation and double-dabble,
; handle negative numbers.
.proc toint8
                sta     $fb
                sty     $fc
                ldy     #$0
                sty     $fd
                sty     $fe
                sty     convbuf
                sty     convbuf+1
                sty     convbuf+2
scanloop:       lda     ($fb),y
                beq     copy
                iny
                cmp     #$20
                beq     scanloop
                cmp     #$2d
                beq     minus
                cmp     #$30
                bcc     error
                cmp     #$3a
                bcs     error
                inc     $fd
                bcc     scanloop
minus:          lda     $fd
                bne     error
                lda     $fe
                bne     error
                inc     $fe
                bne     scanloop
error:          sec
                rts
copy:           dey
                bmi     error
                ldx     #$2
copyloop:       lda     ($fb),y
                cmp     #$30
                bcc     copynext
                cmp     #$3a
                bcs     copynext
                sec
                sbc     #$30
                sta     convbuf,x
                dex
copynext:       dey
                bpl     copyloop
                lda     #$0
                sta     $fb
                ldx     #$8
loop:           lsr     convbuf
                lda     convbuf+1
                bcc     skipbit1
                ora     #$10
skipbit1:       lsr     a
                sta     convbuf+1
                lda     convbuf+2
                bcc     skipbit2
                ora     #$10
skipbit2:       lsr     a
                sta     convbuf+2
                ror     $fb
                dex
                beq     done
                lda     convbuf
                cmp     #$8
                bmi     nosub1
                sbc     #$3
                sta     convbuf
nosub1:         lda     convbuf+1
                cmp     #$8
                bmi     nosub2
                sbc     #$3
                sta     convbuf+1
nosub2:         lda     convbuf+2
                cmp     #$8
                bmi     loop
                sbc     #$3
                sta     convbuf+2
                bcs     loop
done:           lda     $fe
                beq     positive
                lda     #$ff
                eor     $fb
                sta     $fb
                inc     $fb
positive:       lda     $fb
                clc
                rts
.endproc

Felix Palmen

Posted 2018-07-18T05:25:32.787

Reputation: 3 866

2

C (gcc), 71 49 48 bytes

Many thanks to the commenters for the suggestions. Apparently gcc is happy with just a partial ordering of {equal, greater than} for qsort (just to check, clang seems to be happy with this as well.) Although I'm not happy with hardcoding type sizes, it does reduce 7 bytes from sizeof b: change 4 to 8 for systems with a 64-bit int.

q(int*a){a=1-*a&1;}f(a,b)int*a;{qsort(a,b,4,q);}

Try it online!

Alternative version using two passes through the array (79 bytes):

i,j;f(a,b)int*a;{for(i=2;~--i;)for(j=b;~--j;)!(a[j]%2)-i&&printf("%d\t",a[j]);}

Try it online!

ErikF

Posted 2018-07-18T05:25:32.787

Reputation: 2 149

1

72 byte version using qsort: Try it online!

– ErikF – 2018-07-18T08:48:44.107

64 bytes if you replace sizeof(b) by 4 (obviously tying it to a common size of int). – O.O.Balance – 2018-07-18T09:55:36.963

1Even if not, sizeof b is one byte shorter than sizeof(b). – Toby Speight – 2018-07-18T12:21:51.227

@TobySpeight I keep forgetting that sizeof is an operator, not a function. In any case, I've found that it pays to be liberal with parentheses in C, because some of the operator precedence rules are strange and often the cause of many hours of debugging and head-scratching in real programs! – ErikF – 2018-07-18T13:10:54.430

If you sort char elements, the element size is a constant 1. But char is allowed to be an unsigned type, and signed char would be required for correctness on one's complement systems, where checking the low bit does not determine odd/even. Of course, caring about extreme portability is pretty ridiculous when you're using a=blah blah instead of return. That's dependent on the implementation detail that gcc -O0 makes sure to evaluate expression in the return-value register (on all architectures I've looked at), but it of course breaks when compiled normally with optimization. – Peter Cordes – 2018-07-19T10:26:11.090

If you're being gcc-specific anyway, you could limit it to 2's complement systems where you do only need to check the low bit. x(a,b)int*a,*b;{return(*a&1)*2-1;} returns -1 or +1 according to the oddness of a. (Treating equal as less-than is fine, but we can't just return *a&1 because treating less-than as equal is not fine: qsort isn't guaranteed stable.) You can probably save bytes with a !(*a%2) version of that. I played around with a few versions on Godbolt, looking at the asm output to make sure they did the same thing as the working version. https://godbolt.org/g/zo7WG6

– Peter Cordes – 2018-07-19T11:08:12.973

I mean to see if they did the same thing. I'm not 100% sure that all of the ones I left uncommented actually work. – Peter Cordes – 2018-07-19T11:15:33.980

70 bytes if you use C89 style function declaration instead of K&R style – dkudriavtsev – 2018-07-19T18:29:21.117

If qsort works properly with something like return(*a&1)*2-1, we can leave out the ,*b from the declaration. (Some sorts might not like it if a<b and b<a are both true. IDK if qsort requires that. Yeah, the official POSIX qsort(3) man page says: The application shall ensure that the function returns an integer less than, equal to, or greater than 0, if the first argument is considered respectively less than, equal to, or greater than the second. Some implementations may work anyway, though.

– Peter Cordes – 2018-07-20T00:45:51.853

@ceilingcat Indeed it should. I had *a%2 in there previously and the number got skipped. – ErikF – 2018-08-02T02:02:00.807

May be able to get away with ~*a&1 instead of 1-*a&1 – ceilingcat – 2018-08-02T16:13:57.293

f(a,b)int*a;{qsort(a,b,4,"\x8b\7\xf7Ѓ\xe0Ã");} would be 47(+1) bytes. So no gain from lambdafying that function, unfortunately. Also, there's an invisible char there. I think. – None – 2018-08-03T00:31:46.760

However, using a macro in place of f gains you -6 bytes. Compile with -Df(a,b)=qsort(a,b,4,q). – None – 2018-08-03T00:39:32.257

2

Elixir, 37 35 bytes

Code:

fn x->Enum.sort_by x,&(-rem&1,2)end

Expanded version:

fn x -> Enum.sort_by(x, fn y -> -rem(y, 2) end) end

Try it online!

Adnan

Posted 2018-07-18T05:25:32.787

Reputation: 41 965

2

Java 8, 46 29 27 bytes

l->l.sort((i,j)->1-(i&1)*2)

Uses Java 8's List.sort(), thanks to JollyJoker for making me aware of it and for saving me 19 bytes. Try it online here.

Ungolfed:

l -> // lambda taking a List of Integers and modifying it
        l.sort( // sort the List according to ...
        (i, j) ->                // ... a Comparator<Integer> with a compare() method ...
                 1 - (i & 1) * 2 // ... that finds a number smaller than another if it's odd, and greater otherwise

O.O.Balance

Posted 2018-07-18T05:25:32.787

Reputation: 1 499

2Java 8 has List.sort() (if you don't interpret the question as requiring an array specifically) – JollyJoker – 2018-07-18T09:54:46.287

1

@JollyJoker In the absence of a comprehensive spec, I'll choose to interpret it that way :D Thanks for teaching me about List.sort(). This is one of the few instances where golfing suggestions actually improve your real-life programming knowledge. With regards to lists vs. arrays I would reason that since some languages don't have arrays, we can allow lists instead (in keeping with the general rule of when a limited language is allowed something, all languages are allowed that too). Meta post, vote if you like: https://codegolf.meta.stackexchange.com/a/16670/79343

– O.O.Balance – 2018-07-18T10:35:12.533

1Upvoted your meta post. Also played around with the comparator a little but just got equivalent lengths with 1-((i&1)*2) and 1-(i*i%2*2). Thought I'd post them if you see something I missed. – JollyJoker – 2018-07-18T11:50:51.300

1@JollyJoker You can drop the outer parentheses due to operator precedence: 1-(i&1)*2 or 1-i*i%2*2 => 27 bytes – O.O.Balance – 2018-07-18T11:55:28.453

1Just came up with (i&1)*-2 for 26 – JollyJoker – 2018-07-18T11:59:22.237

1@JollyJoker 24 bytes with -(i&1) – O.O.Balance – 2018-07-18T12:07:43.030

Let us continue this discussion in chat.

– O.O.Balance – 2018-07-18T12:10:42.953

2

C++, 174 165 164 149 129 bytes

  • Replace the two include lines with a single include, regex, that happens to include both required headers

 

#include <regex>
int main(int c,char**v){std::sort(v+1,v+c,[](auto s,auto t){return atoi(s)%2>atoi(t)%2;});for(;*++v;)puts(*v);}

149 Bytes

  • For loop trick for printing. This uses the fact that, on Linux at least, the argv array is null-terminated.
  • replace &1 with %2 to remove need for some brackets. Thank you Toby Speight!

 

#include<algorithm>
#include<cstdio>
int main(int c,char**v){std::sort(v+1,v+c,[](auto s,auto t){return atoi(s)%2>atoi(t)%2;});for(;*++v;)puts(*v);}

Older: 164 bytes

#include<algorithm>
#include<cstdio>
int main(int c,char**v){std::sort(v+1,v+c,[](auto s,auto t){return(atoi(s)&1)>(atoi(t)&1);});for(auto i=1;i<c;i++)puts(v[i]);}

Compile as C++14 or higher. Input is taken on the command line, and prints to standard output.

EDIT: removed un-needed return 0; statement

EDIT 2: Removed space after 'return'

Paul Belanger

Posted 2018-07-18T05:25:32.787

Reputation: 189

1Welcome to PPCG! I think you can remove the space after the first return to save a byte. – wastl – 2018-07-18T13:20:11.167

@Toby That would work but finding the last character of the string would involve a call to strlen, which already puts us behind. – Paul Belanger – 2018-07-18T13:28:44.367

1You can save 1 byte: for(int i=1;i<c;)puts(v[i++]); – O.O.Balance – 2018-07-18T14:09:26.767

Thanks for the input -- I've managed to get it down to 129 bytes by removing an include line, and implementing the %2 trick to remove parens, and the second for loop trick! – Paul Belanger – 2018-07-18T19:31:58.030

1

That's certainly some golfing! Welcome to the crazy world of PPCG! I'm glad those tips helped - I'll just observe that Standard C++ guarantees that argv[argc] is null, so that's a portable technique, and not Linux-specific. Nice trick on the include (although that one is compiler-specific). I don't know whether you've found it yet, but if not: have a browse through the [tag:tips] tag, and especially Tips for golfing in C++.

– Toby Speight – 2018-07-20T08:19:23.040

TIO reports a byte count of 128, and you can remove the space in the #include to bring it to 127: https://bit.ly/2LyHlLL

– O.O.Balance – 2018-07-21T19:30:42.100

2

Clojure - 35 bytes

(defn o[c](sort(fn[p _](odd? p))c))

Ungolfed:

(defn oddsort [col]
  (sort (fn [p _] (odd? p)) col))

Bob Jarvis - Reinstate Monica

Posted 2018-07-18T05:25:32.787

Reputation: 544

There is lots of room for improvement, for example you can submit an anonymous function which has a shorter creation syntax via #(...). Also you could give sort-by a try, although the submission already exists. – NikoNyrh – 2018-07-22T10:32:09.057

@NikoNyrh: tried a #() anonymous function but got an arity error as two parameters were passed but only on expected/used, and bringing %2 into it added more characters. Would be interested to see how this could be done. – Bob Jarvis - Reinstate Monica – 2018-07-22T16:11:38.190

2

Retina 0.8.2, 21 bytes

O$`.*(([02468])|.)
$2

Try it online! Link includes header that splits on commas for convenience. Explanation: The last digit of the number is captured if it is even, otherwise it is just matched (this avoids degenerate matches). The $ option then uses the matched digit as the sort key. Odd numbers don't match and end up with an empty sort key, causing them to be sorted first (in their original order), then the even numbers are sorted in order of last digit.

Neil

Posted 2018-07-18T05:25:32.787

Reputation: 95 035

2

T-SQL, 33 bytes

SELECT*FROM t ORDER BY 1-ABS(i)%2

Per our IO standards, input is taken via pre-existing table t with integer column i.

The ABS() function is annoyingly necessary here because the T-SQL modulus operator % returns negative values for negative numbers, which in this case meant I was getting three possible results for i%2: -1, 0, and 1.

Subtracting from 1 is a couple bytes shorter than using DESC.

Note that per the question, I'm not doing any secondary sort, so the order of the odds and evens isn't predictable. If you want a secondary sort, add 2 bytes by adding ,i to the end.

BradC

Posted 2018-07-18T05:25:32.787

Reputation: 6 099

2

sed 4.2.2, 51 43 bytes

Includes +1 for -r

-8 Thanks to Toby Speight

:
s/([^,]*[02468]),([^,]*[13579])/\2,\1/
t

Try it online!

Riley

Posted 2018-07-18T05:25:32.787

Reputation: 11 345

2

Python 2, 34 bytes

lambda a:sorted(a,lambda x,y:x%-2)

Try it online!

This seems to work, but I don't actually understand why it works. If anyone can explain why my half-witted compare function (It returns -1 if the first argument is odd and 0 if the first argument is even, and that's it) works, I'd greatly appreciate it.

Arcanist Lupus

Posted 2018-07-18T05:25:32.787

Reputation: 121

Welcome to PPCG! :) – Shaggy – 2018-07-20T09:10:12.980

2

><>, 40 bytes

l\ /nao01.
:<}\?%2:$-1/?(1
l0=?;naof2.\~

Try it online!

Filter through the list, printing odd numbers, keeping even numbers
l                  Get the length of the stack, use it as an iterator
:          /?(1    Check that there is at least one value left to process
        $-1        Decrement the iterator
    \?%2           Test if the next number is divisible by two
    /nao           Print it if so,
   }               Else, move it to the bottom of the stack
            ~      Delete the iterator after exiting the loop

Print the even numbers left on the stack
l0=?               If there are no values left on the stack,
    ;              Terminate
     nao           Print the next value

Sasha

Posted 2018-07-18T05:25:32.787

Reputation: 431

2

Clojure, 18 bytes

#(sort-by even? %)

Try it online!

MattPutnam

Posted 2018-07-18T05:25:32.787

Reputation: 521

2

Haskell, 44 bytes

Not as byte efficient as Laikoni's answer, but a different approach.

import Data.List
f=uncurry(++).partition odd

Try it online!

Using a sort instead, 47 bytes.

import Data.List
f=sortBy((.even).compare.even)

Try it online!

Adam Boddington

Posted 2018-07-18T05:25:32.787

Reputation: 121

1

Welcome to the site! If you want to talk Haskell/Haskell golfing with us we have a chat room.

– Post Rock Garf Hunter – 2018-07-22T00:29:13.610

2

><>, 25 bytes

l/!?:-1$v?%2:{~
$/<+2oan<

Try it online!

Input is via the -v flag. Ends with an error.

Explanation:

l\            ~  Push length of stack as the counter
 \<

         ?%2:{   Pull a number from the bottom of the stack and check if it is odd

 /   -1$v  If even, subtract one from the counter
 /<+2oan<  If odd, print the number and a newline and add two to the counter

 /!?:      If the counter is 0, go down
$/+2oan<   Print the even number anyway, and set the counter to 2

For a non-erroring version, you can replace the last ~ on the first line with ;?=1

Jo King

Posted 2018-07-18T05:25:32.787

Reputation: 38 234

1

Perl 5 with -M5.010 + -MList::MoreUtils+(sort_by), 21 bytes

sub{sort_by{$_%-2}@_}

Try it online!

Dom Hastings

Posted 2018-07-18T05:25:32.787

Reputation: 16 415

1

Wolfram Language (Mathematica), 15 12 bytes

SortBy@EvenQ

Try it online!

(saved three bytes thanks to JungHwan Min)


Previous version:

#~SortBy~EvenQ&

Try it online!

celtschk

Posted 2018-07-18T05:25:32.787

Reputation: 4 650

@JungHwanMin: Thank you, changed it. – celtschk – 2018-07-18T14:47:04.930

1

Awk: 50 bytes

{and($1,1)?(o=o $1 RS):(e=e $1 RS)}END{print o e}

Input on stdin, Output on stdout

I use RS, the record separator, as a stand-in for "\n", saving two characters each time.

Paul Belanger

Posted 2018-07-18T05:25:32.787

Reputation: 189

1

Ruby, 19 20 bytes

Works on ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux] from Arch Linux repos.

->a{a.sort{|i|~i%2}}

dkudriavtsev

Posted 2018-07-18T05:25:32.787

Reputation: 5 781

Are you sure? It seems to me that this sorts even numbers first. Also, for me (ruby 2.5.1p57 from homebrew) this fails for negative numbers. – Asone Tuhid – 2018-07-20T06:34:21.487

@AsoneTuhid It did not fail for negative numbers for me and i just fixed it to sort odd numbers first (+1 byte) – dkudriavtsev – 2018-07-21T04:11:57.307

1

Pyke, 4 bytes

.#t1.&

Try it here!

.#t1.& - sorted(input, key=lambda i: ↓)
  t    -   i-1
   1.& -  ↑ & 1

4 byte hexdump:

A3 74 31 A6

Try it here!

Blue

Posted 2018-07-18T05:25:32.787

Reputation: 26 661

1

Rust, 38 bytes

|l:&mut Vec<_>|l.sort_by_key(|e|1^e&1)

Try It Online

Jakob

Posted 2018-07-18T05:25:32.787

Reputation: 2 428

1

Swift 4, 40 bytes

print(n.filter{$0%2>0}+n.filter{$0%2<1})

Try it online!

n is the input array

print will be like: [1, 3, 2, 2, 2]

buttercrab

Posted 2018-07-18T05:25:32.787

Reputation: 169

1

Mathematica 25 bytes

Flatten@GatherBy[#, OddQ] &

David G. Stork

Posted 2018-07-18T05:25:32.787

Reputation: 213

1

Chip -z, 44 bytes

V z.
>~#<
|at|Bb
|A-}]~S
>vvv+Cc
DEFGH
defgh

Try it online!

Chip works in bytes, so this expects a sequence of byte-width values on stdin. I use 0x00 as a special delimiter, so that can't be one of the values. (This could be modified to use a different delimiter, at the expense of code size).

The TIO link above uses ASCII "123456789" as the input, corresponding to values 0x31, 0x32, 0x33, ..., 0x39.

This solution reads though the input twice (it knows it hit the end when it sees the 0x00 mentioned earlier, which is tacked onto the end by the flag -z). On the first pass, it prints the odd values, on the second the evens. It actually starts a third pass, but the termination logic kicks in before it does anything else.

Let's look at a rough overview of the code (Chip is 2D, so regions are described, each line on its own would do nothing useful):

           The V is a bookmarker of sorts. The mark is set at the start of a
V z.       pass, and then recalled when the input is exhausted. This does the
>~#<       looping (as opposed to using a stack or queue to hold the data).
|at|Bb     The # is a half-adder, it increments on each pass. When it
>A-}]~S    carries, the t is triggered, terminating the program. The S
>vvv+Cc    suppresses the values we don't want to print on this pass.
DEFGH      The remaining A-H letter pairs are a cat program, smooshed around
defgh      so that the input elements (capital letters) can do double duty,
           for things like detecting oddness, and the end of input.

Phlarx

Posted 2018-07-18T05:25:32.787

Reputation: 1 366

1

Lua, 142 134 bytes

loadstring'p={...}n={}for i=1,#p*2 do n[#n+1]=i<=#p and p[i]%2==1 and p[i]or i>#p and p[i-#p]%2==0 and p[i-#p]or n[#n+1] end return n'

Try it online!

Visckmart

Posted 2018-07-18T05:25:32.787

Reputation: 151

1

k, 8 bytes

{x@>2!x}

Try it online! Loosely based off of the J answer.

{      } /function
    2!x  /  modulo 2 (mapped through list)
   >     /  get indices to sort descending
 x@      /  return the original list at those indices

zgrep

Posted 2018-07-18T05:25:32.787

Reputation: 1 291

1

Julia 1.0, 27 bytes

f(l)=l[sortperm(l.%2 .==0)]

Try it online!

This works too and is a lot more elegant:

f(l)=sort(l,lt=(a,b)->b%2==0)

But it's a few bytes longer :(

niczky12

Posted 2018-07-18T05:25:32.787

Reputation: 301

0

Kotlin, 33 bytes

{l:List<Int>->l.sortedBy{1-it%2}}

Try it online!

snail_

Posted 2018-07-18T05:25:32.787

Reputation: 1 982

is it correct with negative even? 0,0,-1, -2,-2,-2,-1,-2,-3 – mazzy – 2018-07-20T14:56:42.607