我有一個數組建築陣列和添加元素「N」次
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}
我怎樣才能做到這一點???
我有一個數組建築陣列和添加元素「N」次
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}
我怎樣才能做到這一點???
// 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);
不要爲他們做人的功課,這對任何人都沒有幫助。 – 2012-03-13 12:04:29
@ ErnestFriedman-Hill羅傑。 – 2012-03-13 14:22:55
這裏有一個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
這是非常容易的;你卡在哪裏? – 2012-03-13 04:40:30
一次又一次地重複[同一個問題](http://stackoverflow.com/questions/9675524/doubling-the-array-elements-in-tcl)。絕對是一份家庭作業。 – kostix 2012-03-13 06:22:36