Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

java - Multiply elements with other elements in a list

I'm new to programming and I'm writing a program in Java.

How do I multiply every element in a list with every other element i the list? Like this: [1, 3, 5, 7] should be multiplied like this: 1 * 3 + 1 * 5 + 1 * 7 + 3 * 5 + 3 * 7 + 5 * 7

How do I write an algorithm for this? I know it is something in this way but my mind can't figure out what I have to add / change.

    for (int index = 0; index < list.size(); index++) {
        sum += (list.get(index) * (list.get());
    }

Thank you!

question from:https://stackoverflow.com/questions/65831115/multiply-elements-with-other-elements-in-a-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

These approaches are provided based on your implied requirement that you must explicitly multiply each pair of elements and take their sum. There are other ways to achieve the sum that are more effiicent.

You need a nested loop.

  • the outer loop starts at i = 0.
  • the inner loop starts a k = i+1 = 1.
  • this ensures the sum doesn't include the square of each entry.
List<Integer> nums = List.of(1,3,5,7);
int sum = 0;
for (int i = 0; i < nums.size(); i++) {
    for (int k = i+1; k < nums.size(); k++) {
        sum += nums.get(i)*nums.get(k);
    }
}
System.out.println(sum);

Prints

86

You could also do it like this using an enhanced for loop as the outer loop. But the first method is, imo, more straight forward.

int sum = 0;
int i = 1; 
for (int v : nums) {
    for (int k = i++; k < nums.size(); k++) {
        sum += v*nums.get(k);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...