Skip to content

Instantly share code, notes, and snippets.

@Soben

Soben/README.md Secret

Last active September 19, 2023 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Soben/c5d1773d45f7fe2caa56b414a3ae2ef5 to your computer and use it in GitHub Desktop.
Save Soben/c5d1773d45f7fe2caa56b414a3ae2ef5 to your computer and use it in GitHub Desktop.
Cassidoo | Integer Odd/Even Sorting

Solution to Cassidoo's Week of Sept 11, 2023 Challenge

Given an array of integers, sort them into two separate sorted arrays of even and odd numbers. If you see a zero, skip it.

I just like recursion functions, okay??

Only supports positive integers at this time. Untested for negative (and ignores all non-positive, greater-than-zero, values)

<?php
function separateAndSort($numbers = [], $result = [/* even */[], /* odd */[]]) {
if (empty($numbers)) return $result;
// Just for ease of reference.
list($even, $odd) = $result;
$current = array_pop($numbers);
if ($current > 0) {
if ($current % 2 == 0) {
// Even
array_push($even, $current);
} else {
array_push($odd, $current);
}
}
sort($even);
sort($odd);
return separateAndSort($numbers, [$even, $odd]);
}
var_dump(separateAndSort([4,3,2,1,5,7,8,9]));
// [[2,4,6], [1,3,5,7,9]]
var_dump(separateAndSort([1,1,1,1]));
// [[], [1,1,1,1]]
// Ignore 0's
var_dump(separateAndSort([0,4,2,0,9]));
// [[2, 4], [9]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment