Как найти сумму определенных элементов массива

Урок 22. Сумма элементов массива

Просмотров 22.9к. Обновлено 23 ноября 2020

Урок из серии: «Язык программирования Паскаль«

При работе с элементами одномерного массива можно выделить несколько видов подзадач. Алгоритмы для решения этих подзадач   необходимо знать.

На этом уроке рассмотрим  алгоритмы для  нахождения суммы (или произведения) элементов одномерного массива. Здесь могут быть различные модификации — найти сумму элементов с заданным свойством.

Пример 1. Найти сумму элементов массива.

Решение.

Воспользуемся написанными ранее процедурами для ввода и вывода массива.   Массив заполним случайными числами.

Добавим  функцию Sum для  нахождения суммы элементов массива.  В алгоритме переменная i — является счетчиком элементов массива,  s — сумма элементов массива, она вычисляется по реккурентной формуле s = s+m(i).

Обработка элементов массива производится в цикле. Перед циклом сумме присваивается начальное значение равное нулю: sum := 0. В теле цикла записывается рабочая формула для накопления суммы: s := s + m[i].

Текст функции получится таким:

Function Sum(m: myarray): Integer;
Var   i, s : Integer;
Begin
   sum:=0;
   For i:=1 To n Do
     {к уже найденной сумме первых (i-1) элементов прибавляем i-ый элемент}
     s:=s+m[i];
     sum:=s;
End;

Составим программу. В ней воспользуемся для заполнения массива процедурой  Init2, которая заполняет массив случайными числами из заданного интервала.

Program primer_1;
   Const n = 30;  {n - это количество элементов массива}
   Type
      myarray = Array [1...n] Of Integer;
   Var C : myarray;
       s : Integer; {s - сумма всех элементов массива}

   Procedure Init2(a,b: integer; Var m : myarray);
   {Процедура заполнения массива случайными числами из интервала [a,b] и вывода на экран}
   ...
   Function Sum(m: myarray): Integer;
   {Функция для нахождения суммы элементов массива}
   ...
Begin {main}
   {заполняем массив случайными числами из интервала [-25, 25] и выводим на экран}
   Init2(-25, 25, C);
   s:=Sum(C); {находим сумму элементов}
   Writeln ('Их сумма равна ',s);{выводим результат}
   Readln;
End.

Для нахождения произведение  элементов массива,  переменной P перед циклом присваиваем начальное значение  равное 1: P:= 1. В теле цикла ставится рабочая  рекуррентная формула для нахождения произведения: P:= P* C[i].

Пример 2. Найти сумму элементов массива, кратных заданному числу Решение. Воспользуемся функцией Sum из предыдущей программы, но будем суммировать не все элементы, а только те, которые делятся на заданное число (остаток от деления равен 0)

Function Sum(m : myarray) : Integer;
Var i, s, k : Integer;
Begin
   Writeln ('введите число');
   Readln(k);
   s:=0; {начальное значение суммы}
   For i:=1 To n Do
     {если элемент кратен k,то прибавляем его сумме}
     If m[i] Mod k = 0 Then s := s + m[i];
   sum:=s;
End;

Все остальное можно оставить без изменения.

Вы познакомились с алгоритмом суммирования элементов массива. На следующем уроке продолжим изучение алгоритмов для одномерных массивов.

TL;DR

If you care about performance, define a function that uses a for-loop.

function sum(arr) {
    var res = 0;
    for (var x of arr) {
        res += x;
    }
    return res;
}

Benchmark

I benchmarked a selection of implementations using benchmark.js (typescript version):

const arr = Array.from({ length: 100 }, () => Math.random());
const reducer = function (p: number, a: number) {
    return p + a;
};
const recursion = function (arr: number[], i: number) {
    if(i > 0) return arr[i] + recursion(arr, i - 1)
    else return 0
};
const recursion2 = function (arr: number[], i: number, len: number) {
    if(i < len) return arr[i] +  recursion2(arr, i + 1, len)
    else return 0
};
const recursion3 = function (arr: number[], i: number) {
    if(i < arr.length) return arr[i] + recursion3(arr, i + 1)
    else return 0
};
new Benchmark.Suite()
    .add("jquery", () => {
        let res = 0;
        $.each(arr, (_, x) => (res += x));
    })
    .add("lodash", ()=>_.sum(arr))
    .add("forEach", () => {
        let res = 0;
        arr.forEach((x) => (res += x));
    })
    .add("reduce", () => arr.reduce((p, a) => p + a, 0))
    .add("predefined reduce", () => arr.reduce(reducer, 0))
    .add("eval", () => eval(arr.join("+")))
    .add("recursion", () => recursion(arr, arr.length - 1))
    .add("recursion2", () => recursion2(arr, 0, arr.length))
    .add("recursion3", () => recursion3(arr, 0))
    .add("naive", () => (
        arr[0]+arr[1]+arr[2]+arr[3]+arr[4]+arr[5]+arr[6]+arr[7]+arr[8]+arr[9]+
        arr[10]+arr[11]+arr[12]+arr[13]+arr[14]+arr[15]+arr[16]+arr[17]+arr[18]+arr[19]+
        arr[20]+arr[21]+arr[22]+arr[23]+arr[24]+arr[25]+arr[26]+arr[27]+arr[28]+arr[29]+
        arr[30]+arr[31]+arr[32]+arr[33]+arr[34]+arr[35]+arr[36]+arr[37]+arr[38]+arr[39]+
        arr[40]+arr[41]+arr[42]+arr[43]+arr[44]+arr[45]+arr[46]+arr[47]+arr[48]+arr[49]+
        arr[50]+arr[51]+arr[52]+arr[53]+arr[54]+arr[55]+arr[56]+arr[57]+arr[58]+arr[59]+
        arr[60]+arr[61]+arr[62]+arr[63]+arr[64]+arr[65]+arr[66]+arr[67]+arr[68]+arr[69]+
        arr[70]+arr[71]+arr[72]+arr[73]+arr[74]+arr[75]+arr[76]+arr[77]+arr[78]+arr[79]+
        arr[80]+arr[81]+arr[82]+arr[83]+arr[84]+arr[85]+arr[86]+arr[87]+arr[88]+arr[89]+
        arr[90]+arr[91]+arr[92]+arr[93]+arr[94]+arr[95]+arr[96]+arr[97]+arr[98]+arr[99]))
    .add("loop with iterator", () => {
        let res = 0;
        for (const x of arr) res += x;
    })
    .add("traditional for loop", () => {
        let res = 0;
        // cache the length in case the browser can't do it automatically
        const len = arr.length;
        for (let i = 0; i < len; i++) res += arr[i];
    })
    .add("while loop", () => {
        let res = 0;
        let i = arr.length;
        while (i--) res += arr[i];
    })
    .add("loop in a function ", () => sum(arr))
    .on("cycle", (event) => console.log(String(event.target)))
    .run();

In chrome 104, the for-loop-based implementations are the fastest:

jquery               x  1,832,472 ops/sec ±1.35% (61 runs sampled)
lodash               x  2,079,009 ops/sec ±1.11% (68 runs sampled)
forEach              x  4,887,484 ops/sec ±2.35% (67 runs sampled)
reduce               x 21,762,391 ops/sec ±0.46% (69 runs sampled)
predefined reduce    x  2,026,411 ops/sec ±0.50% (68 runs sampled)
eval                 x     33,381 ops/sec ±2.54% (66 runs sampled)
recursion            x  2,252,353 ops/sec ±2.13% (62 runs sampled)
recursion2           x  2,301,516 ops/sec ±1.15% (65 runs sampled)
recursion3           x  2,395,563 ops/sec ±1.65% (66 runs sampled)
naive                x 31,244,240 ops/sec ±0.76% (66 runs sampled)
loop with iterator   x 29,554,762 ops/sec ±1.07% (66 runs sampled)
traditional for loop x 30,052,685 ops/sec ±0.67% (66 runs sampled)
while loop           x 18,624,045 ops/sec ±0.17% (69 runs sampled)
loop in a function   x 29,437,954 ops/sec ±0.54% (66 runs sampled)

Firefox 104 shows similar behaviour:

jquery               x  1,461,578 ops/sec ±1.58% (64 runs sampled)
lodash               x  4,931,619 ops/sec ±0.80% (66 runs sampled)
forEach              x  5,594,013 ops/sec ±0.51% (68 runs sampled)
reduce               x  3,731,232 ops/sec ±0.53% (66 runs sampled)
predefined reduce    x  2,633,652 ops/sec ±0.54% (66 runs sampled)
eval                 x    105,003 ops/sec ±0.88% (66 runs sampled)
recursion            x  1,194,551 ops/sec ±0.24% (67 runs sampled)
recursion2           x  1,186,138 ops/sec ±0.20% (68 runs sampled)
recursion3           x  1,191,921 ops/sec ±0.24% (68 runs sampled)
naive                x 21,610,416 ops/sec ±0.66% (66 runs sampled)
loop with iterator   x 15,311,298 ops/sec ±0.43% (67 runs sampled)
traditional for loop x 15,406,772 ops/sec ±0.59% (67 runs sampled)
while loop           x 11,513,234 ops/sec ±0.60% (67 runs sampled)
loop in a function   x 15,417,944 ops/sec ±0.32% (68 runs sampled)

Discussion

Implementations defining an anonymous function are generally slower because creating an anonymous function is a significant overhead. When running the benchmark with a large array, e.g., with length 1000 instead of 100, the difference between reduce and the for-loop-based implementations becomes insignificant in chrome.

Chrome’s V8 engine knows how to inline simple anonymous functions in reduce since the reduce test case is much faster than the predefined reduce test case. Firefox seems to try something similar but is less efficient in doing so. Non-inlined function calls are pretty slow in js since the call stack is less efficient than the call stack in compiled software.

Similar to reduce, the forEach— and jquery-based implementations use anonymous functions and are relatively slow. lodash has a specialized sum implementation, but it is (as of v4.0.0) implemented as a special case of sumBy, which is relatively inefficient.

eval is the by far slowest test case. This makes sense since constructing the string using concatenations might cause several dynamic allocations (which are slow). Next, the parser has to be invoked and only then can the code be finally executed.

I’ve included some recursive implementations because some people on the internet claim that recursion is faster than loops in js. I can’t reproduce their example — using benchmark.js, recursion is very slow, and when using console.time with a loop, both functions take the same time. When calculating the sum, as expected, recursion is much slower than loops, probably due to intense usage of the js call stack.

The naive implementation would be manually adding all 100 elements of the array. While being quite inconvenient, this is the fastest implementation. But, luckily, for-loops come very close. Adding a single function call around the loop doesn’t harm the performance. Therefore, you can feel free to use the utility function from above.

I have no explanation why the while loop is slower than the for loop. Iterating the array in reverse doesn’t seem to be the problem here.

В этом посте мы обсудим, как найти сумму элементов в массиве C++.

1. Использование STL accumulate() функция

Стандартным решением является использование std::accumulate предоставляется стандартной библиотекой. Он определен в заголовочном файле numeric. Операция по умолчанию заключается в добавлении элементов до но, чтобы сделать контекст более понятным. Мы также можем передать функцию в необязательном четвертом параметре, которая выполняет операцию сложения двух чисел и возвращает результат.

#include <iostream>

#include <numeric>

int main()

{

    int arr[] = { 5, 3, 7, 9, 2 };

    int sum = std::accumulate(std::begin(arr), std::end(arr), 0, std::plus<int>());

    std::cout << sum;

    return 0;

}

Скачать  Выполнить код

2. Использование Boost accumulate() функция

Еще одна хорошая альтернатива — использовать boost accumulate() функция, которая определена в заголовочном файле boost/range/numeric.hpp.

#include <iostream>

#include <boost/range/numeric.hpp>

int main()

{

    int arr[] = { 5, 3, 7, 9, 2 };

    int sum = boost::accumulate(arr, 0);

    std::cout << sum;

    return 0;

}

Скачать код

3. Использование STL for_each() функция

Мы также можем написать логику суммирования в предикате для std::for_each стандартный алгоритм. Это показано ниже с использованием лямбда-выражений:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

#include <iostream>

#include <algorithm>

int main()

{

    int arr[] = { 5, 3, 7, 9, 2 };

    int sum = 0;

    std::for_each(std::begin(arr), std::end(arr),

                [&] (int &i) {

                    sum += i;

                });

    std::cout << sum;

    return 0;

}

Скачать  Выполнить код

4. Цикл for/цикл for на основе диапазона

Мы также можем написать собственную процедуру для этой простой задачи. Идея состоит в том, чтобы пройти массив, используя простой цикл for или цикл for на основе диапазона, и накопить сумму каждого элемента в переменной.

⮚ Для цикла

#include <iostream>

int main()

{

    int arr[] = { 5, 3, 7, 9, 2};

    int n = sizeof(arr) / sizeof(int);

    int sum = 0;

    for (int i = 0; i < n; i++) {

        sum += arr[i];

    }

    std::cout << sum;

    return 0;

}

Скачать  Выполнить код

⮚ Цикл for на основе диапазона

#include <iostream>

int main()

{

    int arr[] = { 5, 3, 7, 9, 2 };

    int sum = 0;

    for (int i: arr) {

        sum += i;

    }

    std::cout << sum;

    return 0;

}

Скачать  Выполнить код

5. Использование valarray sum() функция

Если valarray используется вместо стандартного массива, операция суммирования может быть применена непосредственно к valarray объект, вызвав его функцию-член sum().

#include <iostream>

#include <valarray>

int main()

{

    int arr[] = { 5, 3, 7, 9, 2 };

    int n = sizeof(arr) / sizeof(int);

    std::valarray<int> valarray (arr, n);

    std::cout << valarray.sum();

    return 0;

}

Скачать  Выполнить код

6. C++17 — Свернуть выражения

С C++17 мы можем использовать складывать выражения, как показано ниже:

#include <iostream>

template<typename ...T>

auto sum(T ...args) {

    return (args + ...);

}

int main()

{

    std::cout << sum( 5, 3, 7, 9, 2 );

    return 0;

}

Выполнить код

Это все, что касается нахождения суммы элементов в массиве C++.

Whether you’re using JavaScript, Python, or C++, these programs definitely add up.

Sum of all elements in an array

An array is a collection of elements stored at contiguous memory locations. It’s the most used data structure in programming. In this article, you’ll learn how to find the sum of all elements in an array using C++, Python, and JavaScript.

Problem Statement

You’re given an array of numbers, and you need to calculate and print the sum of all elements in the given array.

Example 1: Let arr = [1, 2, 3, 4, 5]

Therefore, the sum of all elements of the array = 1 + 2 + 3 + 4 + 5 = 15.

Thus, the output is 15.

Example 2: Let arr = [34, 56, 10, -2, 5, 99]

Therefore, the sum of all elements of the array = 34 + 56 + 10 + (-2) + 5 + 99 = 202.

Thus, the output is 202.

Approach to Find the Sum of All Elements in an Array

You can find the sum of all elements in an array by following the approach below:

  1. Initialize a variable sum to store the total sum of all elements of the array.
  2. Traverse the array and add each element of the array with the sum variable.
  3. Finally, return the sum variable.

C++ Program to Find the Sum of All Elements in an Array

Below is the C++ program to find the sum of all elements in an array:

 // C++ program to find the sum of elements in an array
#include <iostream>
using namespace std;

// Function to return the sum of elements in an array
int findSum(int arr[], int size)
{
int sum = 0;

for(int i=0; i<size; i++)
 {
 sum += arr[i];
 }

return sum;

}

// Function to print the elements of the array
void printArray(int arr[], int size)
{
for(int i=0; i<size; i++)
 {
 cout << arr[i] << " ";
 }
 cout << endl;
}

// Driver code
int main()
{
int arr1[] = {1, 2, 3, 4, 5};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
 cout << "Array 1:" << endl;
 printArray(arr1, size1);
 cout << "Sum of elements of the array: " << findSum(arr1, size1) << endl;

int arr2[] = {34, 56, 10, -2, 5, 99};
int size2 = sizeof(arr2) / sizeof(arr2[0]);
 cout << "Array 2:" << endl;
 printArray(arr2, size2);
 cout << "Sum of elements of the array: " << findSum(arr2, size2) << endl;

int arr3[] = {-1, 50, -56, 43, 53, 356, -324};
int size3 = sizeof(arr3) / sizeof(arr3[0]);
 cout << "Array 3:" << endl;
 printArray(arr3, size3);
 cout << "Sum of elements of the array: " << findSum(arr3, size3) << endl;

return 0;
}

Output:

 Array 1:
1 2 3 4 5
Sum of elements of the array: 15
Array 2:
34 56 10 -2 5 99
Sum of elements of the array: 202
Array 3:
-1 50 -56 43 53 356 -324
Sum of elements of the array: 121

C++ Program Using STL to Find the Sum of All Elements in an Array

You can also use C++ STL to find the sum of all elements in an array.

 // C++ program using STL to find the sum of elements in an array
#include <bits/stdc++.h>
using namespace std;

// Function to print the elements of the array
void printArray(int arr[], int size)
{
for(int i=0; i<size; i++)
 {
 cout << arr[i] << " ";
 }
 cout << endl;
}

// Driver code
int main()
{
int arr1[] = {1, 2, 3, 4, 5};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
 cout << "Array 1:" << endl;
 printArray(arr1, size1);
 cout << "Sum of elements of the array: " << accumulate(arr1, arr1 + size1, 0) << endl;

int arr2[] = {34, 56, 10, -2, 5, 99};
int size2 = sizeof(arr2) / sizeof(arr2[0]);
 cout << "Array 2:" << endl;
 printArray(arr2, size2);
 cout << "Sum of elements of the array: " << accumulate(arr2, arr2 + size2, 0) << endl;

int arr3[] = {-1, 50, -56, 43, 53, 356, -324};
int size3 = sizeof(arr3) / sizeof(arr3[0]);
 cout << "Array 3:" << endl;
 printArray(arr3, size3);
 cout << "Sum of elements of the array: " << accumulate(arr3, arr3 + size3, 0) << endl;

return 0;
}

Output:

 Array 1:
1 2 3 4 5
Sum of elements of the array: 15
Array 2:
34 56 10 -2 5 99
Sum of elements of the array: 202
Array 3:
-1 50 -56 43 53 356 -324
Sum of elements of the array: 121

Python Program to Find the Sum of All Elements in an Array

Below is the Python program to find the sum of all elements in an array:

 # Python program to find the sum of elements in an array

# Function to return the sum of elements in an array
def findSum(arr):
    sum = 0
    for element in arr:
        sum += element
    return sum

# Function to print the elements of the array
def printArray(arr):
    for i in range(len(arr)):
        print(arr[i] , end=' ')
    print()

# Driver Code
arr1 = [1, 2, 3, 4, 5]
print("Array 1:")
printArray(arr1)
print("Sum of elements of the array:",findSum(arr1))

arr2 = [34, 56, 10, -2, 5, 99]
print("Array 2:")
printArray(arr2)
print("Sum of elements of the array:",findSum(arr2))

arr3 = [-1, 50, -56, 43, 53, 356, -324]
print("Array 3:")
printArray(arr3)
print("Sum of elements of the array:",findSum(arr3))

Output:

 Array 1:
1 2 3 4 5
Sum of elements of the array: 15
Array 2:
34 56 10 -2 5 99
Sum of elements of the array: 202
Array 3:
-1 50 -56 43 53 356 -324
Sum of elements of the array: 121

Python Program Using Built-in Function to Find the Sum of All Elements in an Array

You can also use Python’s sum() function to find the sum of all elements in an array.

 # Python program to find the sum of elements in an array

# Function to print the elements of the array
def printArray(arr):
    for i in range(len(arr)):
        print(arr[i] , end=' ')
    print()

# Driver Code
arr1 = [1, 2, 3, 4, 5]
print("Array 1:")
printArray(arr1)
print("Sum of elements of the array:",sum(arr1))

arr2 = [34, 56, 10, -2, 5, 99]
print("Array 2:")
printArray(arr2)
print("Sum of elements of the array:",sum(arr2))

arr3 = [-1, 50, -56, 43, 53, 356, -324]
print("Array 3:")
printArray(arr3)
print("Sum of elements of the array:",sum(arr3))

Output:

 Array 1:
1 2 3 4 5
Sum of elements of the array: 15
Array 2:
34 56 10 -2 5 99
Sum of elements of the array: 202
Array 3:
-1 50 -56 43 53 356 -324
Sum of elements of the array: 121

JavaScript Program to Find the Sum of All Elements in an Array

Below is the JavaScript program to find the sum of all elements in an array:

 // JavaScript program to find the sum of elements in an array

// Function to return the sum of elements in an array
function findSum(arr, size)
{
let sum = 0;

for(let i=0; i<size; i++)
 {
 sum += arr[i];
 }

return sum;

}

// Function to print the elements of the array
function printArray(arr, size)
{
for(let i=0; i<size; i++)
 {
document.write(arr[i] + " ");
 }
document.write("
");
}

// Driver code

const arr1 = [1, 2, 3, 4, 5]
size1 = arr1.length;
document.write("Array 1:
");
printArray(arr1, size1);
document.write("Sum of elements of the array: " + findSum(arr1, size1) + "
");

const arr2 = [34, 56, 10, -2, 5, 99]
size2 = arr2.length;
document.write("Array 2:
");
printArray(arr2, size2);
document.write("Sum of elements of the array: " + findSum(arr2, size2) + "
");

const arr3 = [-1, 50, -56, 43, 53, 356, -324]
size3 = arr3.length;
document.write("Array 3:
");
printArray(arr3, size3);
document.write("Sum of elements of the array: " + findSum(arr3, size3) + "
");

Output:

 Array 1:
1 2 3 4 5
Sum of elements of the array: 15
Array 2:
34 56 10 -2 5 99
Sum of elements of the array: 202
Array 3:
-1 50 -56 43 53 356 -324
Sum of elements of the array: 121

JavaScript Program Using the reduce() Method to Find the Sum of All Elements in an Array

You can also use JavaScript’s reduce() method to find the sum of all elements in an array.

 // JavaScript program to find the sum of elements in an array

// Function to print the elements of the array
function printArray(arr, size)
{
for(let i=0; i<size; i++)
 {
document.write(arr[i] + " ");
 }
document.write("
");
}

// Driver code

const arr1 = [1, 2, 3, 4, 5]
size1 = arr1.length;
document.write("Array 1:
");
printArray(arr1, size1);
var sum1 = arr1.reduce(function(a, b) { return a + b; }, 0);
document.write("Sum of elements of the array: " + sum1 + "
");

const arr2 = [34, 56, 10, -2, 5, 99]
size2 = arr2.length;
document.write("Array 2:
");
printArray(arr2, size2);
var sum2 = arr2.reduce(function(a, b) { return a + b; }, 0);
document.write("Sum of elements of the array: " + sum2 + "
");

const arr3 = [-1, 50, -56, 43, 53, 356, -324]
size3 = arr3.length;
document.write("Array 3:
");
printArray(arr3, size3);
var sum3 = arr3.reduce(function(a, b) { return a + b; }, 0);
document.write("Sum of elements of the array: " + sum3 + "
");

Output:

 Array 1:
1 2 3 4 5
Sum of elements of the array: 15
Array 2:
34 56 10 -2 5 99
Sum of elements of the array: 202
Array 3:
-1 50 -56 43 53 356 -324
Sum of elements of the array: 121

Want to Learn C++?

C++ is among the most popular programming languages. You can use C++ for basic programming, developing games, developing GUI-based applications, developing database software, developing operating systems, and much more.

If you’re a beginner to C++ or want to revise your C++ concepts, check out some of the top websites and courses to get you started.

Как найти сумму чисел массива, которых равна определенному числу?

const circle_1 = [7, 2, 3, 5, 16, 50, 25, 40],
      circle_2 = [2, 5, 10, 30, 25, 3, 10, 25],
      circle_3 = [25, 10, 2, 10, 5, 2, 10, 5],
      circle_4 = [7, 2, 3, 20, 3, 7, 2, 5],
      circle_5 = [2, 20, 1, 7, 25, 1, 25],
      circle_6 = [3];

Нужно взять по одному елементу с каждого массива так, чтобы получилось число 136. Как правильно написать алгоритм поиска? Подозреваю, что нужно использовать рекурсию, но никак не раздуплюсь как ее применить. Заранее спасибо

По самому тупому алгоритму получилось так ( МНЕ ОЧЕНЬ СТЫДНО (: )

function findCountByArray() {
  for (let a = 0; a < circle_1.length; a++) {
    for (let b = 0; b < circle_2.length; b++) {
      for (let c = 0; c < circle_3.length; c++) {
        for (let d = 0; d < circle_4.length; d++) {
          for (let e = 0; e < circle_5.length; e++) {
            for (let f = 0; f < circle_6.length; f++) {
              if (circle_1[a] + circle_2[b] + circle_3[c] + circle_4[d] + circle_5[e] + circle_6[f] == 136) {
                return [circle_1[a], circle_2[b], circle_3[c], circle_4[d], circle_5[e], circle_6[f]];
              }
            }
          }
        }
      }
    }
  }
  return [];
}


  • Вопрос задан

    более трёх лет назад

  • 3430 просмотров

Вот вариант на ES6, используется spread operator:

const circle_1 = [7, 2, 3, 5, 16, 50, 25, 40],
      circle_2 = [2, 5, 10, 30, 25, 3, 10, 25],
      circle_3 = [25, 10, 2, 10, 5, 2, 10, 5],
      circle_4 = [7, 2, 3, 20, 3, 7, 2, 5],
      circle_5 = [2, 20, 1, 7, 25, 1, 25],
      circle_6 = [3];
      
function findSum(value, arrays, i = 0) {
  for (let j = 0; j < arrays[i].length; j++) {
    const el = arrays[i][j];
    
    if (i < arrays.length - 1) {
      const result = findSum(value - el, arrays, i + 1);
      
      if (result !== null) {
        return [el, ...result];
      }
    } else if (el === value) {
      return [el];
    }
  }
  return null;
}

console.log('result', findSum(136, [
  circle_1, 
  circle_2, 
  circle_3, 
  circle_4, 
  circle_5,
  circle_6
]));

// => result  [50, 30, 25, 3, 25, 3]

Демо: https://jsfiddle.net/0ho4g942/

Пригласить эксперта

Тут товарищ рекурсия нужна

CIRCLES = [
    [7, 2, 3, 5, 16, 50, 25, 40],
    [2, 5, 10, 30, 25, 3, 10, 25],
    [25, 10, 2, 10, 5, 2, 10, 5],
    [7, 2, 3, 20, 3, 7, 2, 5],
    [2, 20, 1, 7, 25, 1, 25],
    [3]
]
condidats = [0,0,0,0,0,0]
      
R  = [];
function get_sum(s, ind){
    if (ind >= CIRCLES.length) {
        if (s == 136) {
           alert(condidats)
         }
     }
    else {
      for (let i in CIRCLES[ind] ){
      	item =  CIRCLES[ind][i];
        condidats[ind] = item;
        get_sum(s+item, ind+1);
      }
    }
}

get_sum(0, 0)

думаю псевдокод понятен
упд: исправил
вот и js говнокод
https://jsfiddle.net/m1nsra5d/4/

Если по легче, то — const count = 136
А если без шуток, что-то типо того:

function findCount (arrays, maxValue) {
  let count = 0
  let chunkPositions = [-1, 0]

  let mergedArray = []
  let resultArray = []

  arrays.forEach(array => {
    mergedArray = mergedArray.concat(array)
  })
  
  for (let i = 0; i < mergedArray.length; i++) {
    if (++chunkPositions[0] == arrays.length) {
      chunkPositions[0] = 0
      ++chunkPositions[1]
    }
    
    if (count >= maxValue) break
    else {
      const [aposition, iposition] = chunkPositions
      const value = arrays[aposition][iposition]
      
      if (!value || (count + value > maxValue)) continue

      count += value
      resultArray.push(value)
    }
  }

  return resultArray
}

findCount([
  [7, 2, 3, 5, 16, 50, 25, 40],
  [2, 5, 10, 30, 25, 3, 10, 25],
  [25, 10, 2, 10, 5, 2, 10, 5],
  [7, 2, 3, 20, 3, 7, 2, 5],
  [2, 20, 1, 7, 25, 1, 25],
  [3]
], 136)

// Output => [7, 2, 25, 7, 2, 3, 2, 5, 10, 2, 20, 3, 10, 2, 3, 1, 5, 10, 7, 5, 3, 2]

Функция работает без рекурсии


  • Показать ещё
    Загружается…

25 мая 2023, в 11:42

1000 руб./за проект

25 мая 2023, в 11:34

1000 руб./за проект

25 мая 2023, в 11:34

15000 руб./за проект

Минуточку внимания

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как составить интересный репортаж
  • Как найти процент обученности учащихся
  • Как найти долю в процентном соотношении
  • Алгебра найдите значение выражения как решать
  • Как найти простые числа через питон

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии