Quickest way to restructure an array?

matlab reshape by row
matlab resize matrix
matlab permute
matlab reshape matrix to vector
matlab reshape 3d matrix
matlab reshape order
matlab array
repmat matlab

I have an array which can have several items in it, e.g:

Item 1
Item 2
Item 3
Item 4
Item 5
Item 6
etc

I need the quickest way to restructure this array so that it has at most X items. So if I say that X is 3, the resulting array must be:

Item 1 , Item 2
Item 3, Item 4
Item 5, Item 6
etc

or if it has 7 items, it would be:

Item 1 , Item 2, Item 3,
Item 4, Item 5, 
Item 6, Item 7

What's the easiest way to do this?

I started with this, but it seems like there really must be an easier way:

foreach ($addressParts as $part)
{
    if (empty($part)) continue;
    if (empty($addressLines[$count]))  $addressLines[$count] = '';
    $addressLines[$count] .= $part;
    $count++;
    if ($count > 2) $count = 0;
}

Also, this won't work, because you will end up with this:

item 1, item 4, item 7
item 2, item 5
item 3, item 6

... which is wrong. Any thoughts?

UPDATE

If I start with:

Array
(
    [0] => item 1
    [1] => item 2
    [2] => item 3
    [3] => item 4
    [4] => item 5
    [5] => item 6
    [6] => item 7
)

I want to end with:

Array
(
    [0] => item 1, item 2, item 3
    [1] => item 4, item 5
    [2] => item 6, item 7
)

Make sense?


This function combines elements to a new array as per your example. It handles any number of input elements.

function ReduceArray($input, $length) {
        $frac = $length / count($input);
        $frac = $frac + 0.0001;    // Offset for float calculations
        $index = 0.0;

        // Copy the elements, rolling over on $index
        $temp = array();
        foreach ($input as $part) {
                $i= floor($index);
                if (!isset($temp[$i])) {
                        $temp[$i] = array($part);
                } else {
                        $temp[$i][] = $part;
                }
                $index += $frac;
        }

        // Combine the sub arrays
        $output = array();
        foreach ($temp as $line) {
            $output[] = implode(', ', $line);
        }
        return $output;
}

$input = array('Item 1',  'Item 2',  'Item 3',  'Item 4',  'Item 5',  'Item 6', 'Item 7');
$output = ReduceArray($input, 3);
print_r($output);

Output

Array
(
    [0] => Item 1, Item 2, Item 3
    [1] => Item 4, Item 5
    [2] => Item 6, Item 7
)

Edit "fixed" the output as per the given output.

Edit See Comment for nine elements, tested for up to 12 elements. Thanks sectus

Most efficient way to restructure complex array of objects in , If the data is already sorted, there is a faster way using only one loop: var output = document.querySelector('#output'); var original = [ { country : 'us', date  It depends upon things like (a) how large the integers are, (b) whether the input array contains integers in a random order or in a nearly-sorted order, (c) whether you need the sorting algorithm to be stable or not, as well as other factors, (d) whether the entire list of numbers fits in memory (in-memory sort vs external sort), and (e) the machine you run it on.


For each group, calculate to offset of the first element and the group length, copy that slice from the input array.

function array_group_elements($array, $groups) {
  $result = array();
  $count = count($array);
  // minimum in each group
  $limit = floor($count / $groups);
  // balance, modulo
  $overhead = $count % $groups;
  // for each group
  for ($i = 0; $i < $groups; ++$i) {
    // group offset, add 1 for each group that got a balance element
    $offset = ($i * $limit) + ($i < $overhead ? $i : $overhead);
    // length, add 1 if it is a group with balance element
    $length = $limit + ($i < $overhead ? 1 : 0);
    // copy slice from original array
    $result[] = array_slice($array, $offset, $length);
  }
  return $result;
}

$input = array('Item 1',  'Item 2',  'Item 3',  'Item 4',  'Item 5',  'Item 6', 'Item 7');
$grouped = array_group_elements($input, 3);
var_dump(
  array_map(
    function($group) {
      return implode(', ', $group);
    },
    $grouped
  )
);

Output:

array(3) {
  [0]=>
  string(22) "Item 1, Item 2, Item 3"
  [1]=>
  string(14) "Item 4, Item 5"
  [2]=>
  string(14) "Item 6, Item 7"
}

The function array_group_elements() loops over the $groups (3 times), not the $array (7 times).

SciPy and NumPy: An Overview for Developers, Now that we have created arrays, we can reshape them in many other ways. the shape of the array has little effect on how fast something operates on the  Matrices and arrays are the fundamental representation of information and data in MATLAB ®.You can create common arrays and grids, combine existing arrays, manipulate an array's shape and content, and use indexing to access array elements.


I have two functions with different approaches.

function restructureArray1($array, $x)
    {
    $size = sizeof($array);
    if ($size < $x)
        return array_chunk($array, 1) + array_fill(0, $x, array());
        // chunk by 1 element and add missing empty elements

    $big_row_length = (int) ($size / $x) + 1;
    $big_rows_chunk = array_splice($array, 0, $size % $x * $big_row_length);
    // $big_rows_chunk contains items with big rows
    // $array now contains items with small rows
    return array_merge(array_chunk($big_rows_chunk, $big_row_length), array_chunk($array, $big_row_length - 1));
    // chunk and merge
    }

function restructureArray2($array, $x)
    {
    $size = sizeof($array);
    $small_row_length = (int) ($size / $x);
    $big_row_count = $size % $x;
    for ($i = 0; $i < $x; ++$i)
        {
        $length = $small_row_length + (int) ($i < $big_row_count); // type juggling
        $return [] = array_splice($array, 0, $length);
        // $return[] contains one row
        // $array now contains rest of array
        }
    return $return;
    }

To get result with array of strings you need just array_map it.

$x = 3;
$size = 7;
$array = range(1, $size);
$result1 = restructureArray1($array, $x);
$result2 = restructureArray2($array, $x);

var_dump(array_map(function($array)
            { return implode(', ', $array); }, $result2));

Demo

Relative links to documentation: array_splice, array_chunk, array_merge

P.S. The shortest solution


function restructureArray3($array, $x)
    {
    while($x)
        $return [] = array_splice($array, 0, ceil(sizeof($array) / $x--));
    return $return;
    }

Demo

Secure Programming Cookbook for C and C++: Recipes for , Knowing how many dimensions an array has can help in understanding the Arrays can be restructured in four ways: • Splitting a one-dimensional array into  In this article, we will discuss different ways for sorting arrays in C# In C#, we can sort an array in multiple ways. 1. Using Array.Sort(Array) : [crayon-5ecdbac2e1332…


I've come up with the following algorithm that keeps fitting the right number of items in each row; in each iteration, we round up the division of the number of remaining lines vs remaining items:

$a = range(1,7);

$len = count($a);
$res = array();
$max = 3;

$i = 0;
while ($i < $len) {
        // divide the remaining number of items by the maximum rows allowed
        // this gives the width for the current row
        $width = ceil(($len - $i) / $max);

        $res[] = join(', ', array_slice($a, $i, $width));

        // adjust pointer and reduce the maximum
        $i += $width;
        --$max;
}

print_r($res);

Demo

Reshaping and Rearranging Arrays, Reshaping. The reshape function changes the size and shape of an array. For example, reshape a 3-by-4 matrix to a 2-by-6 matrix. A = [1 4 7 10; 2 5 8 11; 3 6 9​  In QuickSort, if you skip the recursive calls you don't actually need, you'll get Quickselect: a simple algorithm with an expected O(n) time complexity if you choose the pivot at random.


<?php
$source_array = array(
  'item 1',
  'item 2',
  'item 3',
  'item 4',
  'item 5',
  'item 6',
  'item 7',
  'item 8',
  'item 9',
  'item 10',
);


$k = 4;

// allocating cells
$allocated_cells_sizes = array();
$ik = 0;
foreach ($source_array as $value){
  if (! isset($allocated_cells_sizes[$ik])) $allocated_cells_sizes[$ik] = 0;
  $allocated_cells_sizes[$ik] ++;
  if (++$ik >= $k) $ik = 0;
}

// filling result array
$result = array();
foreach ($allocated_cells_sizes as $cells_sizes){
  $result[] = implode(', ', array_slice($source_array, 0, $cells_sizes));
  $source_array = array_slice($source_array, $cells_sizes, null);
}

print_r($result);

/**
 * Output
 * Array
    (
    [0] => item 1, item 2, item 3
    [1] => item 4, item 5, item 6
    [2] => item 7, item 8
    [3] => item 9, item 10
    )

 */

Processing: A Programming Handbook for Visual Designers and Artists, The arrayCopy() function is the fastest way of copying data from one array to Multiplication can often be converted to addition by restructuring the program. The input data is quickly converted to numbers with textscan, however, trying to convert the newly created numbers back to strings seems to be taking too long (6 times longer than converting the input text to numbers).


Reshape array - MATLAB reshape, forEach provides for a basic way to loop through our data set. This works, but can get clunky and confusing fast. The callback function gets called for each element in the array, and also has access to the index of that element in the array​. Put another way, FROM defines the collection, and JOIN refers to the “inner document” (the array of objects) contained in the outer JSON document. Handling Arrays. JSON also uses arrays to store items inside a document. The ComplexCars document contains an array named CustomerComments.


Iterating Over and Reducing Data, Reshaping data. The reshape() function in NumPy is a powerful tool which allows us to restructure an array according to the arguments we specify. The function 


How to use the reshape() function in NumPy, Computation on NumPy arrays can be very fast, or it can be very slow. x = np.​arange(9).reshape((3, 3)) 2 ** x. Out[6]: For example, if we'd like to reduce an array with a particular operation, we can use the reduce method of any ufunc.