0
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?

今日も前回に引き続き、多重ループを使って問題を解いていく!


問題概要

与えられた 配列A に対して、要素同士をかけ算してかけ算表(配列B)を作って出力してね!


入力例:

3
56 37 30

出力例:

3136 2072 1680
2072 1369 1110
1680 1110 900




✅OK例:

const rl = require('readline').createInterface({input:process.stdin});

const lines = [];

rl.on('line', (input) => {
    lines.push(input);
});



rl.on('close', () => {
    const N = Number(lines[0]);
    const arrA = lines[1].split(' ').map(Number);
    
    for (let i = 0; i < N; i++){
        const product = [];
        
        for(let j = 0; j < N; j++){
            product.push(arrA[i] * arrA[j]);
        }
        
        console.log(product.join(' '));
    }
    
});

▶ 外側で行をためて、最後にまとめて出力するのがポイント!



✅① .map()バージョン

arrA.forEach(a =>
  console.log(arrA.map(b => a * b).join(' '))
);

▶ forEach+mapで超短縮! でも、やってることは同じ。



✅②

const arrB = arrA.map(ai => arrA.map(aj => ai * aj));

arrB.forEach(row => console.log(row.join(' ')));

▶ 二次元配列をまず作ってから出力。再利用したいときに便利!




📝気づきメモ

  • console.log を内側ループに置いたら、1要素ずつ改行されて行列がバラバラに…。まとめて出力する発想が必要だった!

  • 二重ループは「なんとなく」じゃなくて、どうデータが並ぶのかをイメージする力がめっちゃ大事(外側=行、内側=列)




僕の失敗談(´;ω;`)と解決法🐈

0
0
0

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
0
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?