[英]Finding the sum of common elements between n number of arrays in java
我有一個程序,將兩個數組的公共元素求和。 為此,我使用了兩個for循環,如果我有三個,則可以使用三個for循環。 但是如何求和n個數組的公共元素,其中n在運行時出現。
我不知道如何在運行時更改循環數,或者對此是否還有其他相關概念?
這是我嘗試求和兩個數組的代碼:
import java.util.Scanner;
public class Sample {
public static void main(String... args)
{
Scanner sc=new Scanner(System.in);
int arr1[]={1,2,3,4,5},arr2[]={4,5,6,7,8},sum=0;
for (int i=0;i<arr1.length;i++)
{
for (int j=0;j<arr2.length;j++)
{
if (arr1[i]==arr2[j])
{
sum+=(arr1[i]);
}
}
}
}
}
可以有不同的實現方式。 您可以使用以下方法。 這是偽代碼
input[n][m]
ArrayList
commonItems
存儲其公共項。 用input[0]
的元素啟動它 i = 1 to n-1
遍歷數組。 與每個input[i]
進行比較,在每個步驟僅存儲commonItems
和input[i]
的公共項。 您可以通過將input[i]
轉換為列表並使用retainAll
方法來實現。 commonItem
列表將僅包含公共數字。 現在求和該列表的值。 假定元素的索引並不重要:a [1] = 2和a [5] = 2,則只需要兩個嵌套循環。
首先,您需要將n-1個數組放入集合列表中。 然后循環遍歷第n個數組,並檢查列表中所有集合中是否存在每個元素。 如果確實存在,則加到總計中。
實際上,有一個更通用的方法,該方法還回答了“如何在運行時更改循環數?”這一問題。
我們正在尋找一種實現與之等效的方法:
for (i1 = 0; i1 < k1; i1++) {
for (i2 = 0; i2 < k2; i2++) {
for (i3 = 0; i3 < k3; i3++) {
...
for (in = 0; in < kn; in++) {
f(x1[i1], x2[i2], ... xn[in]);
}
...
}
}
}
其中, n
是在運行時給出的, f
是使用n
參數列表處理當前n個元組的函數。
有一個基於遞歸概念的通用解決方案。
這是一種產生所需行為的實現:
void process(int idx, int n, int[][] x, int[] k, Object[] ntuple) {
if (idx == n) {
// we have a complete n-tuple,
// with an element from each of the n arrays
f(ntuple);
return;
}
// this is the idx'th "for" statement
for (int i = 0; i < k[idx]; i++) {
ntuple[idx] = x[idx][i];
// with this recursive call we make sure that
// we also generate the rest of the for's
process(idx + 1, n, x, k, ntuple);
}
}
該函數假定n
數組存儲在矩陣x
,並且第一次調用應如下所示:
process(0, n, x, k, new Object[n]);
上述方案中具有高的復雜性(它是O(K 1⋅k2⋅..⋅kn))的 ,但有時也能夠避免下去,直到最深循環。
確實,在這篇文章中提到的特定問題(需要對所有數組中的公共元素求和)中,我們可以跳過生成一些元組的操作, 例如,如果已經x 2 [i 2 ]≠x 1 [i 1 ]。
在遞歸解決方案中,可以輕松修剪那些情況。 此問題的特定代碼可能如下所示:
void process(int idx, int n, int[][] x, int[] k, int value) {
if (idx == n) {
// all elements from the current tuple are equal to "value".
// add this to the global "sum" variable
sum += value;
return;
}
for (int i = 0; i < k[idx]; i++) {
if (idx == 0) {
// this is the outer "for", set the new value
value = x[0][i];
} else {
// check if the current element from the idx'th for
// has the same value as all previous elements
if (x[idx][i] == value) {
process(idx + 1, n, x, k, value);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.