如何比对数组元素并从对应数组取值求和(适配大数组场景)
Efficient Approach Using Associative Arrays
For handling both small and large arrays efficiently, the best method is to first create a lookup map (associative array) that links each application name from array1 to its corresponding value in array2. This reduces the time complexity from the slow O(n*m) of nested loops to O(n + m), which is critical for large datasets.
Step-by-Step Implementation
- Define your arrays:
array1=(Application_1 Application_2 Application_3 Application_4 Application_5 Application_6) array2=(60 50 7 9 5 21) array3=(Application_9 Application_11 Application_2 Application_5 Application_1)
- Build the lookup associative array:
We iterate over the indices ofarray1to map each application name directly to its matching value fromarray2:
declare -A app_value_map # Populate the map with app-name-to-value pairs for index in "${!array1[@]}"; do app_name="${array1[$index]}" app_value="${array2[$index]}" app_value_map["$app_name"]="$app_value" done
- Calculate the sum of matching values:
Loop througharray3, check if each application exists in our lookup map, and add its value to the total sum if it does:
total_sum=0 for app in "${array3[@]}"; do # Only add the value if the app exists in our map if [[ -n "${app_value_map[$app]}" ]]; then total_sum=$((total_sum + app_value_map[$app])) fi done echo "Total sum of matching values: $total_sum"
When you run this code, the output will be Total sum of matching values: 115 (the sum of 60, 50, and 5, corresponding to Application_1, Application_2, and Application_5).
Why This Is Efficient for Large Arrays
- Fast Lookups: Associative arrays in bash provide near-constant time (O(1)) lookups. This means checking if an application exists in the map is quick, even for thousands of elements.
- Optimal Time Complexity: Building the map takes O(n) time (where n is the length of
array1), and iterating througharray3takes O(m) time (where m is the length ofarray3). Combined, this is O(n + m), which is vastly more efficient than the naive nested loop approach that slows down drastically as arrays grow.
Naive (Inefficient) Approach (For Comparison)
If you're working with very small arrays and don't care about performance, you could use nested loops. But avoid this for large datasets:
total_sum=0 for app3 in "${array3[@]}"; do for index in "${!array1[@]}"; do if [[ "$app3" == "${array1[$index]}" ]]; then total_sum=$((total_sum + array2[$index])) break # Exit inner loop once a match is found fi done done echo "Total sum: $total_sum"
This works but will be slow if either array has hundreds or thousands of elements.
Note
Associative arrays are supported in Bash 4.0 and above. If you're using an older version of Bash, you'll need to upgrade or use a less efficient workaround (like using grep with indices).
内容的提问来源于stack exchange,提问作者Ramesh Pokhrel

