c++ - Mixing two arrays by alternating elements two by two -
what elegant algorithm mix elements 2 two in 2 arrays (of potentially differing sizes) items drawn in alternating fashion each array, leftovers added end?
e.g.
array 1: 0, 2, 4, 6 array 2: 1, 3, 5, 7 mixed array: 0, 2, 1, 3, 4, 6, 5, 7
don't worry null checking or other edge cases, i'll handle those. here solution not work properly:
for (i = 0; < n; i++) { arr[2 * + 0] = a[i]; arr[2 * + 1] = a[i+1]; arr[2 * + 0] = b[i]; arr[2 * + 1] = b[i+1]; }
it fiddly calculate array indices explicitly, if arrays can of different , possibly odd lengths. easier if keep 3 separate indices, 1 each array:
int pairwise(int c[], const int a[], size_t alen, const int b[], size_t blen) { size_t = 0; // index size_t j = 0; // index b size_t k = 0; // index c while (i < alen || j < blen) { if (i < alen) c[k++] = a[i++]; if (i < alen) c[k++] = a[i++]; if (j < blen) c[k++] = b[j++]; if (j < blen) c[k++] = b[j++]; } return k; }
the returned value k
equal alen
+ blen
, implicit dimension of result array c
. because availability of next item checked each array operation, code works arrays of different lengths , when arrays have odd number of elements.
you can use code this:
#define countof(x) (sizeof(x) / sizeof(*x)) int main() { int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int b[] = {-1, -2, -3, -4, -5, -6}; int c[countof(a) + countof(b)]; int i, n; n = pairwise(c, a, countof(a), b, countof(b)); (i = 0; < n; i++) { if (i) printf(", "); printf("%d", c[i]); } puts(""); return 0; }
(the example in c, not c++, code doesn't use of c++'s containers such vector
, i've uses plain old ´int` arrays explicit dimensions, same in c , c++.)
Comments
Post a Comment