4
4

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.

【解決済み】配列の最大値を再帰で求めようとしたけどダメだった

Last updated at Posted at 2014-11-02
function maximum(x) {
  console.log('-----------------------');
  console.log(x);
  var x1 = x[0];
  x.splice(0,1);
  console.log(x1, x);
  console.log('-----------------------');
  if (x.length == 0) {
    return x;
  } else {
    return Math.max(x1, maximum(x));
  }
};
// console.log(Math.max(1,2));
console.log(maximum([1,2,3]));

結果は3が期待されるのに、2が返ってくる…これはどうしたものでしょう。

function maximum(x) {
  console.log('-----------------------');
  console.log(x);
  var x1 = x[0];
  x.splice(0,1);
  console.log(x1, x);
  console.log('-----------------------');
  if (x.length == 0) {
    return x1;
  } else {
    return Math.max(x1, maximum(x));
  }
};
// console.log(Math.max(1,2));
console.log(maximum([1,2,3]));

これで動きました。

4
4
2

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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?