Given an 2d array of strings how to I add up all the elements so that each index in the array is the sum of the rest of the array? For example with an array [[a], [b], [c], [d], [e]]
I end up with[[a+b+c+d+e], [a+b+c+d+e], [a+b+c+d+e], [a+b+c+d+e],[a+b+c+d+e]]
. I guess it doesn't have to be a 2d array it can be a 1d array of string and I end up with a string "a+b+c+d+e" in every index. When I say circularly I mean with loops, no extra memory space. So maybe after the first iteration it could look something like [[a], [a + b], [a+b+c], [a+b+c+d], [a+b+c+d+e]]
. What would the code for something like this be? The answer can be is psuedocode or any language
something like this: https://andrew.gibiansky.com/blog/machine-learning/baidu-allreduce/
I'm not quite sure what you want to achieve. But it might be worthwhile if you look at Arrays#parallelPrefix
, which you can use to cumulate the single elements of an array.
public static void main(String[] args) {
String[] str = {"a","b","c","d","e"};
Arrays.parallelPrefix(str, (s1,s2) -> s1+s2);
System.out.println(Arrays.toString(str));
}
//[a, ab, abc, abcd, abcde]
You can get such string by adding all elements to one of the items and then copying the result to other items.
String[] arr = new String[] {"a", "b", "c", "d", "e"};
for(int i = 1; i < arr.length; ++i) {
arr[0] += arr[i];
}
for(int i = 1; i < arr.length; ++i) {
arr[i] = arr[0];
}
System.out.println(Arrays.toString(arr));
According to your attached link i think below solution will help you:
int n = 5, i, j;
String[][] gpu = new String[n][n];
//here generate initial gpu....
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
char ch = (char) (97 + j);
gpu[i][j] = ""+ch+i;
}
}
System.out.println("Initial Gpu: ");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
System.out.print(gpu[i][j] + "|");
}
System.out.println();
}
// here calculated your expected logic
for (i = 0; i < n-1; i++) {
for (j = 0; j < n; j++) {
gpu[(i+j+1)%n][j] = gpu[(i+j)%n][j] + gpu[(i+j+1)%n][j];
}
}
System.out.println("Final Gpu: ");
for (i = 0; i < n; i++) {
System.out.print(gpu[n-1][i] + "|");
}
System.out.println();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.