Interleaving multiple arrays into a single array
for example,
function array_zip_merge() {
$output = array();
// The loop incrementer takes each array out of the loop as it gets emptied by array_shift().
for ($args = func_get_args(); count($args); $args = array_filter($args)) {
// &$arg allows array_shift() to change the original.
foreach ($args as &$arg) {
$output[] = array_shift($arg);
}
}
return $output;
}
// test
$a = range(1, 10);
$b = range('a', 'f');
$c = range('A', 'B');
echo implode('', array_zip_merge($a, $b, $c)); // prints 1aA2bB3c4d5e6f78910
Java: Interleaving multiple arrays into a single array
For simplicity, assume that the arrays are the same length, and are int
arrays.
int[] merge(int[] a, int[] b)
{
assert (a.length == b.length);
int[] result = new int[a.length + b.length];
for (int i=0; i<a.length; i++)
{
result[i*2] = a[i];
result[i*2+1] = b[i];
}
return result;
}
How can I interleave two arrays?
If both arrays have the same length then this is a possible solution:
let one = [1,3,5]
let two = [2,4,6]
let merged = zip(one, two).flatMap { [$0, $1] }
print(merged) // [1, 2, 3, 4, 5, 6]
Here zip()
enumerates the arrays in parallel and returns a sequence
of pairs (2-element tuples) with one element from each array. flatMap()
creates a 2-element array from each pair and concatenates the result.
If the arrays can have different length then you append the
extra elements of the longer array to the result:
func mergeFunction<T>(one: [T], _ two: [T]) -> [T] {
let commonLength = min(one.count, two.count)
return zip(one, two).flatMap { [$0, $1] }
+ one.suffixFrom(commonLength)
+ two.suffixFrom(commonLength)
}
Update for Swift 3:
func mergeFunction<T>(_ one: [T], _ two: [T]) -> [T] {
let commonLength = min(one.count, two.count)
return zip(one, two).flatMap { [$0, $1] }
+ one.suffix(from: commonLength)
+ two.suffix(from: commonLength)
}
How to interleave two arrays into a new array
You definitely had the right idea, you almost got it. Guess you don't suck at programming that much :). You can use properties of a List
for this, without casting to a File
.
public static void main(String[] args) {
List<String> list1 = new ArrayList<>();
list1.add("over");
list1.add("river");
list1.add("through");
list1.add("woods");
List<String> list2 = new ArrayList<>();
list2.add("the");
list2.add("and");
mergeLists(list1, list2);
}
private static List<String> mergeLists(List<String> list1, List<String> list2) {
// Get the max length of both arrays
int max = Math.max(list1.size(), list2.size());
// Initialize new list
List<String> newList = new ArrayList<>();
// add an element of the first list to the new list (if there are more elements)
// and then add an element from the second list to the new list (if there are more elements)
// and repeat...
for (int i = 0; i < max; i++) {
if (i < list1.size()) {
newList.add(list1.get(i));
}
if (i < list2.size()) {
newList.add(list2.get(i));
}
}
System.out.println(newList);
return newList;
}
Numpy concatenate arrays with interleaving
Use np.dstack
or np.stack
to stack along the last axis that gives us a 3D
array and then reshape back to 2D
-
np.dstack([a,b,c,d]).reshape(a.shape[0],-1)
np.stack([a,b,c,d],axis=2).reshape(a.shape[0],-1)
interleave mutliple arrays in javascript
You can do this for any number of arrays with two nested forEach statements:
let arr1 = [[1,2,3],[4,5]]
let arr2 = [[1,2,3], [4,5,6], [7,8,9]]
let arr3 = [[1,2,3,4], [4,5,6], [7,8,9], [10,11,12]]
function interLeaveArrays(mainArr){
let maxLen = Math.max(...mainArr.map(arr => arr.length))
mainArr.forEach(arr => {
let lenDiff = maxLen - arr.length
for(let i=lenDiff; i>0; i--){
arr.push(null)
}
})
let newArr = []
mainArr.forEach((arr, idx1) => {
arr.forEach((el, idx2) => {
newArr[idx2 * mainArr.length + idx1] = el
})
})
return newArr
}
console.log(interLeaveArrays(arr1))
console.log(interLeaveArrays(arr2))
console.log(interLeaveArrays(arr3))
Selectively interleave two arrays
You could iterate the sparse array and take only the values with the values at the same index from array one.
var array1 = [1, 2, 3, 4, 5, 6, 7, 8], array2 = [, , , , 1, , 0, 1], result = array2.reduce((r, v, i) => r.concat(array1[i], v), []); console.log(result);
Merge Two Array such like, elements of both array positioned alternate to each other
You can maintain 2 indices, one for the "merged" array, and the index for your loop's iteration. Because you're merging, you'll need to increment the target index by 2 in each iteration:
public static int[] mergeArray(int[] a, int[] b) {
int length = (a.length + b.length);
int result[] = new int[length];
for (int i = 0, e = 0; i <= a.length - 1; i++, e += 2) {
result[e] = a[i];
result[e + 1] = b[i];
}
return result;
}
Which outputs the expected 1 4 3 2 5 7 6 6 7 4 8 2
Merge and interleave two arrays in Ruby
You can do that with:
a.zip(s).flatten.compact
Ruby, equally distribute elements and interleave/merge multiple arrays
I would use a sort to do this, based on element index postion, divided by size of array, plus some offset based on array id, to keep things consistent (if you don't need consistency, you could use a small random offset instead).
a = [:a,:b]
b = [:c]
c = [:d,:e,:f]
d = [:g:,:h,:i,:j]
def sort_pos array, id
(1..array.size).map { |i| (i - 0.5 + id/1000.0)/(array.size + 1e-6) }
end
# Combine all the arrays with their sort index, assigning ids to each array for consistency.
# Depending on how you receive these arrays, this structure can be built up programatically,
# as long as you add an array plus its sort index numbers at the same time
combined = (a + b + c + d).zip( sort_pos(a, 1) + sort_pos(b, 2) + sort_pos(c, 3) + sort_pos(d, 4) )
# Extract the values from the original arrays in their new order
combined.sort_by { |zipped| zipped[1] }.map { |zipped| zipped[0] }
=> [:g, :d, :a, :h, :e, :i, :b, :f, :j, :c]
There might be a cleaner way of doing this in Ruby . . . but I think the end result is what you are after - an "even" mix of multiple arrays.
If you only care about even-ness of mix from a statistical perspective (i.e. over time it is "fair"), you could just do this:
(a+b+c+d).shuffle
=> [:g, :b, :i, :c, :a, :h, :e, :j, :f, :d]
Related Topics
How to Get the Newest File in a Directory in PHP
Which Line Break in PHP Mail Header, \R\N or \N
Should I Use Prepared Statements for MySQL in PHP Performance-Wise
Improve Password Hashing with a Random Salt
Finding Common Prefix of Array of Strings
Logging in to Joomla 1.5 Using External Form (Not Within Joomla Folder, But on Same Server)
Convert a String into an Array of Characters
How to Set a Default Attribute Value for a Laravel/Eloquent Model
Why Is It Whenever I Use Scandir() I Receive Periods at the Beginning of the Array
Utf-8 Character Encoding Battles JSON_Encode()
PHP Error: Function Name Must Be a String
PHP - Plus Sign with Get Query