我有一个数组
a[]= {34,45,65,55,67}
我需要C或TCL代码来构建一个新数组,每个元素重复“N”次。
例如,当n = 2时,结果数组应为
b[]= {34,34,45,45,65,65,55,55,67,67}
同样,当n = 3时,数组应为
b[]={34,34,34,45,45,45,65,65,65,55,55,55,67,67,67}
我该怎么做?
答案 0 :(得分:1)
// Input parameters
int i,j;
int a[] = {34,45,65,55,67};
int aSize = 5;
int repeat = 10;
// Create a new array with a dynamic size.
// This array must be freed after to avoid memory leaks
int b* = (int*) malloc(sizeof(int) * aSize * repeat);
for (i = 0; i < aSize; ++i) // for all elements in a
for (j = 0; j < repeat; ++j) // repeat them "repeat" times
b[i * repeat + j] = a[i]; // i * repeat + j is the current element in b
// do something with b here
// release memory
free(b);
答案 1 :(得分:1)
这是一个TCL解决方案:
% package require struct
2.1
% proc dup {items count} {
return [join [struct::list mapfor x $items {struct::list repeat $count $x}]]
}
% dup {1 2 3} 3
1 1 1 2 2 2 3 3 3