1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

数値配列のすべての乗算のパターンを実行してその合計値を取得する

Posted at

前提

表題のとおり、JavaScript で数値で構成された配列のすべてのパターンを実行してその合計値を取得します。
例えば[3, 1, 2]という配列がある場合には以下のパターンを実行します。

  1. 3 * 1
  2. 3 * 2
  3. 1 * 2

そしてその全ての計算の合計値を取得してみます。

コード


function combination(input) {
  let numbers = input;
  let result = 0;
  numbers.forEach((number) => {
    numbers = numbers.slice(1)
    numbers.forEach((number2) => {
      result += number * number2;
    })
  });
  console.log(result);
}

combination([3, 1, 2]); //=> 11

slice() で配列を作り直しているところがポイントなのですが、もう少しマシに書けそうです。

1
0
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?