Just for fun really. I was curious of the best way to do this.
views:
51answers:
4
+1
A:
I would do the following:
- Sort the original array by length of the strings (with uasort())
- Split the array in half by putting every element in one of two arrays (in a foreach loop)
- Reverse the second array (with array_reverse())
- Merge the two array together (with array_merge())
Kau-Boy
2010-09-05 20:49:02
No need to re-sort the second half as it’s already sorted. You just have to reverse the order.
Gumbo
2010-09-05 20:52:54
That's why I used the array_reverse function :) Ok I'll change my sentence.
Kau-Boy
2010-09-05 20:55:26
You will always have a right-heavy array but I believe this still passes the spec.
erisco
2010-09-06 02:13:53
+3
A:
Here is one way to do it (there's most likely a better solution):
function sort_length($str1, $str2)
{
if(strlen($str1) == strlen($str2))
{
return 0;
}
return strlen($str1) > strlen($str2) ? -1 : 1;
}
$words = array("Hello", "World", "this", "is", "a", "test");
usort($words, 'sort_length');
$new_list = array();
$boolean = true;
foreach($words as $word)
{
if($boolean)
{
array_push($new_list, $word);
}
else
{
array_unshift($new_list, $word);
}
$boolean = !$boolean;
}
//print_r($new_list);
Tim Cooper
2010-09-05 20:52:53
A:
A first attempt could be to first sort them as normal. Then iterate through this array, copying to a new one, with the copy destination alternating between the start and end of the new array, where the start index is incremented and the end index is decremented.
James
2010-09-05 20:54:13
+1
A:
Here’s a solution that preserves the array keys:
// function to compare two strings by their length
function cmp_strlen($a, $b) {
return strlen($a) - strlen($b);
}
// sort array by length while preserving the keys
uasort($arr, 'cmp_strlen');
$ordered = array();
$keys = array_keys($arr);
// fill $ordered with odd keys in order
for ($i=0, $n=count($keys); $i<$n; $i+=2) {
$ordered[$keys[$i]] = $arr[$keys[$i]];
}
// fill $ordered with even keys in reverse order
for ($i=((count($keys)>>1)<<1)-1; $i>0; $i-=2) {
$ordered[$keys[$i]] = $arr[$keys[$i]];
}
Gumbo
2010-09-05 21:32:54