1
1

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.

JavaScriptで簡単なドラゴンボール総当たり戦の表を作る

Last updated at Posted at 2019-04-11

方針

かけ算九九でやったみたく、多重ループを使ってやったらいけそう。

コード

ES5まで

var member = ['悟空','ベジータ','ピッコロ','クリリン','亀仙人'];
for(var cnt_a=0; cnt_a<5; cnt_a++){
    for(var cnt_b=0; cnt_b<5; cnt_b++){
        console.log(member[cnt_a] + ' vs ' + member[cnt_b]);
    }
}

ES2015

let member = ['悟空','ベジータ','ピッコロ','クリリン','亀仙人'];
for(let player1 of member){
    for(let player2 of member){
        console.log(player1 + ' vs ' + player2);
    }
}

これだと、悟空 vs 悟空みたいなことが起こっているので、この辺をif文を使って修正する。

コード修正版

ES5まで

var member = ['悟空','ベジータ','ピッコロ','クリリン','亀仙人'];
for(var cnt_a=0; cnt_a<5; cnt_a++){
    for(var cnt_b=0; cnt_b<5; cnt_b++){
        if(member[cnt_a] !== member[cnt_b])
        console.log(member[cnt_a] + ' vs ' + member[cnt_b]);
    }
}

ES2015

let member = ['悟空','ベジータ','ピッコロ','クリリン','亀仙人'];
for(let player1 of member){
    for(let player2 of member){
        if(player1 !== player2){
        console.log(player1 + ' vs ' + player2);
        }
    }
}

ここでまた問題発生。悟空vsベジータベジータvs悟空は一緒じゃん。
同じ組み合わせを避けたい。

コード修正版(改)

##ES5まで

var member1 = ['悟空','ベジータ','ピッコロ','クリリン','亀仙人'];
var member2 = ['悟空','ベジータ','ピッコロ','クリリン','亀仙人'];
for(var cnt_a=0; cnt_a<5; cnt_a++){
    member2.shift();
    for(var cnt_b=0; cnt_b<(5-(cnt_a+1)); cnt_b++){
        console.log(member1[cnt_a] + ' vs ' + member2[cnt_b]);
    }
}

##ES2015

let member1 = ['悟空','ベジータ','ピッコロ','クリリン','亀仙人'];
let member2 = ['悟空','ベジータ','ピッコロ','クリリン','亀仙人'];
for(let m1 of member1){
    member2.shift();
    for(let m2 of member2){
        console.log(m1 + ' vs ' + m2);
    }
}

参考

ふりがなプログラミング

1
1
6

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?