1

How can I separate the odd terms in one array and the even terms in another array,i.e., go from

a={1,2,3,4}

to

aeven={2,4} and aodd={1,3}

I thought of:

a={1,2,3,4}

s={}

For[i = 1, i <= 4, i++, 
 If[EvenQ[a[[i]]] == True, AppendTo[a[[i]], s]]]

but it does not work.

Thankyou

Oleksandr R.
  • 23,023
  • 4
  • 87
  • 125
Mencia
  • 1,324
  • 12
  • 26

3 Answers3

8
  GatherBy[a, OddQ]
  (* {{1, 3}, {2, 4}} *)

or

 Pick[a, # /@ a] & /@ {OddQ, EvenQ}

or

 Pick[a, OddQ /@ a, #] & /@ {True, False}

or

 Cases[a, _?#] & /@ {OddQ, EvenQ}

or

 Select[a, #] & /@ {OddQ, EvenQ}

or

 SplitBy[SortBy[a, EvenQ], EvenQ]
kglr
  • 394,356
  • 18
  • 477
  • 896
5

kguler already showed the primary methods so here are some secondary ones.

One for fun:

a = Range@10;

Reap[Sow[#, #~Mod~2] & /@ a, {0, 1}][[2, All, 1]]
{{2, 4, 6, 8, 10}, {1, 3, 5, 7, 9}}

And one for performance:

a = RandomInteger[1*^7, 1*^7];

With[{mask = BitAnd[a, 1]},
  {a[[ SparseArray[mask, Automatic, 1]["AdjacencyLists"] ]],
   a[[ SparseArray[mask]["AdjacencyLists"] ]]}
] // Timing // First
0.234

kguler's fastest method for comparison:

GatherBy[a, OddQ] // Timing // First
0.406

A fast method from Rojo for Mathematica versions 8+ (Pick was optimized after v7):

With[{mask = BitAnd[a, 1]}, Pick[a, mask, #] & /@ {0, 1}]
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
0

I would go with one of the other options, but it can be done with Part and Span, as follows:

dat = Range[10];
{dat[[;; ;; 2]], dat[[2 ;; ;; 2]]}
(* {{1, 3, 5, 7, 9}, {2, 4, 6, 8, 10}} *)
rcollyer
  • 33,976
  • 7
  • 92
  • 191