কম্পিউটার টিউটোরিয়াল

জাভাস্ক্রিপ্টে দুটি ২D অ্যারে থেকে ম্যাট্রিক্স মাল্টিপ্লিকেশন ফলাফল বের করা

আমাদের দুটি ২D অ্যারে (ম্যাট্রিক্স) ইনপুট নেওয়া থাকলে তাদের ম্যাট্রিক্স গুণফল বের করার ফাংশন লিখতে হবে।

ধরি আমাদের দুটি ম্যাট্রিক্স নিচের মতো:

// 5 x 4
let a = [
    [1, 2, 3, 1],
    [4, 5, 6, 1],
    [7, 8, 9, 1],
    [1, 1, 1, 1],
    [5, 7, 2, 6]
];
// 4 x 6
let b = [
    [1, 4, 7, 3, 4, 6],
    [2, 5, 8, 7, 3, 2],
    [3, 6, 9, 6, 7, 8],
    [1, 1, 1, 2, 3, 6]
];

উদাহরণ

ফাংশনের কোড:

const multiplyMatrices = (a, b) => {
    if (!Array.isArray(a) || !Array.isArray(b) || !a.length || !b.length) {
        throw new Error('arguments should be in 2-dimensional array format');
    }
    let x = a.length,
        z = a[0].length,
        y = b[0].length;
    if (b.length !== z) {
        throw new Error('number of columns in the first matrix should be the same as the number of rows in the second');
    }
    let productRow = Array.apply(null, new Array(y)).map(Number.prototype.valueOf, 0);
    let product = new Array(x);
    for (let p = 0; p < x; p++) {
        product[p] = productRow.slice();
    }
    for (let i = 0; i < x; i++) {
        for (let j = 0; j < y; j++) {
            for (let k = 0; k < z; k++) {
                product[i][j] += a[i][k] * b[k][j];
            }
        }
    }
    return product;
}
// 5 x 4
let a = [
    [1, 2, 3, 1],
    [4, 5, 6, 1],
    [7, 8, 9, 1],
    [1, 1, 1, 1],
    [5, 7, 2, 6]
];
// 4 x 6
let b = [
    [1, 4, 7, 3, 4, 6],
    [2, 5, 8, 7, 3, 2],
    [3, 6, 9, 6, 7, 8],
    [1, 1, 1, 2, 3, 6]
];
// ফলাফল ৫ x ৬ ম্যাট্রিক্স হবে
console.log(multiplyMatrices(a, b));

আউটপুট

কনসোলে নিচের আউটপুটটি দেখাবে (৫ x ৬ ম্যাট্রিক্স):

[
    [ 15, 33, 51, 37, 34, 40 ],
    [ 33, 78, 123, 85, 76, 88 ],
    [ 51, 123, 195, 133, 118, 136 ],
    [ 7, 16, 25, 18, 17, 22 ],
    [ 31, 73, 115, 88, 73, 96 ]
]
  1. জাভাস্ক্রিপ্টে দুটি সংখ্যা তুলনা করার পদ্ধতি

  2. JavaScript-এ অ্যারে ডেটা স্ট্রাকচার: ধারণা, অপারেশন এবং ব্যবহার

  3. জাভাস্ক্রিপ্টে দুটি অ্যারে জয়েন করা

  4. জাভাস্ক্রিপ্টে দুটি অ্যারে গুণ করা