Finding the Determinant of a 4x4 Matrix: A Ray-Tracing Adventure in JavaScript

Currently, I am in the process of developing a raytracer using Javascript/Canvas and following "The Ray Tracer Challenge" by Jamis Buck. Initially, my code successfully computed the determinant of a 3x3 matrix but encountered issues with a 4x4 matrix. As a result, I decided to discard the faulty code and replace it with converted C code. Surprisingly, even though the original C version works perfectly fine, the ported Javascript code fails to produce the correct determinant for a 4x4 input matrix.

I'm puzzled and seeking guidance on what could be going wrong or what essential aspect I might be overlooking.

(The functional C code is provided at the end.)

"use strict";
// HELPER FUNCTION

function initArray(rows, cols)  {

var result = [];

for (var r = 0; r < rows; r++)  {

    result[r] = [];

    for (var c = 0; c < cols; c++)  {

        result[r][c] = 0;
    }

}

return result;

}
//--------------------------------
// DETERMINANT

// Function to get cofactor of mat[p][q] in temp[][]. n is current 

// dimension of mat[][] 

function getCofactor(mat, temp, p, q, n)
{


var i = 0, j = 0; 

// Looping for each element of the matrix 
for (var row = 0; row < n; row++) 
{ 
    for (var col = 0; col < n; col++) 
    { 
        // Copying into temporary matrix only those element 
        // which are not in given row and column 
        if (row != p && col != q) 
        { 
            temp[i][j++] = mat[row][col];

            // Row is filled, so increase row index and 
            // reset col index 
            if (j == n - 1) 
            {
                j = 0; 
                i++; 
            }
        }
    } 
}

return temp;
}


/* Recursive function for finding determinant of matrix. 
n is current dimension of mat[][]. */

function determinantOfMatrix(mat, n) 
{ 

var D = 0; // Initialize result 

// Base case : if matrix contains single element 
if (n == 1) 
    return mat[0][0]; 

var temp = initArray(4, 4); // To store cofactors 

var sign = 1; // To store sign multiplier 

// Iterate for each element of first row 
for (var f = 0; f < n; f++) 
{ 
    // Getting Cofactor of mat[0][f] 
    temp = getCofactor(mat, temp, 0, f, n); 
    D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); 

    // terms are to be added with alternate sign 
    sign = -sign; 
}

return D;  
} 

// Finally, this is how I test it:

function test7()    {

var m = initArray(4, 4);

m[0][0] = -2, m[0][1] = -8, m[0][2] = 3, m[0][3] = 5;
m[1][0] = -3, m[1][1] = 1, m[1][2] = 7, m[1][3] = 3;
m[2][0] = 1, m[2][1] = 2, m[2][2] = -9, m[2][3] = 6;
m[3][0] = 6, m[3][1] = 7, m[3][2] = 7, m[3][3] = -9;


var determinant = determinantOfMatrix(m, 4 /*m.length*/);

alert("determinant = " + determinant); // SHOULD BE -4071

}

//------------------------ BELOW IS THE C CODE, WHICH WORKS --------

#include <stdio.h>

// Dimension of input square matrix 

#define N 4 

// Function to get cofactor of mat[p][q] in temp[][]. n is current 
// dimension of mat[][] 

void getCofactor(int mat[N][N], int temp[N][N], int p, int q, int n) 
{ 

int i = 0, j = 0; 

// Looping for each element of the matrix 
for (int row = 0; row < n; row++) 
{ 
    for (int col = 0; col < n; col++) 
    { 
        // Copying into temporary matrix only those element 
        // which are not in given row and column 
        if (row != p && col != q) 
        { 
            temp[i][j++] = mat[row][col]; 

            // Row is filled, so increase row index and 
            // reset col index 
            if (j == n - 1) 
            { 
                j = 0; 
                i++; 
            }
        } 
    }
}
} 

/* Recursive function for finding determinant of matrix. 
n is current dimension of mat[][]. */

int determinantOfMatrix(int mat[N][N], int n) 
{ 

int D = 0; // Initialize result 

// Base case: if matrix contains a single element 
if (n == 1) 
    return mat[0][0]; 

int temp[N][N]; // To store cofactors 

int sign = 1; // To store sign multiplier 

// Iterate for each element of the first row 
for (int f = 0; f < n; f++) 
{ 
    // Getting Cofactor of mat[0][f] 
    getCofactor(mat, temp, 0, f, n); 
    D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); 

    // The terms are to be added with an alternate sign 
    sign = -sign; 
}

return D; 
} 

// Driver program to test the above functions 

int main() 
{ 

int mat[N][N] = {{-2, -8, 3, 5}, 
                {-3, 1, 7, 3},
                {1, 2, -9, 6}, 
                {-6, 7, 7, -9} 
                }; 

printf("Determinant of the matrix is: %d", determinantOfMatrix(mat, N)); 
return 0; 
} 

Answer №1

I couldn't figure out the reason why your code was not working initially. However, after attempting to translate the code, I managed to get it to work successfully.

var N = 4; 
function initArray(rows, cols)  {
    var result = [];

    for (var r = 0; r < rows; r++)  {
        result[r] = [];

        for (var c = 0; c < cols; c++) result[r][c] = 0;

    }

    return result;
}

function getCofactor(mat, temp, p, q, n){ 
    var i = 0, j = 0;

// Looping for each element of the matrix 
    for (var row = 0; row < n; row++) { 
        for (var col = 0; col < n; col++) { 
            // Copying into temporary matrix only those element 
            // which are not in given row and column 
            if (row != p && col != q) { 
                temp[i][j++] = mat[row][col]; 

                // Row is filled, so increase row index and 
                // reset col index 
                if (j === n - 1) { 
                    j = 0; 
                    i++; 
                }
            }
        }
    }
} 

/* Recursive function for finding determinant of matrix. 
n is current dimension of mat[][]. */

function determinantOfMatrix(mat, n) {

    var D = 0; // Initialize result 

    // Base case : if matrix contains single element 
    if (n == 1) return mat[0][0]; 

    var temp = initArray(N,N); // To store cofactors 

    var sign = 1; // To store sign multiplier 

    // Iterate for each element of first row 
    for (var f = 0; f < n; f++) { 
        // Getting Cofactor of mat[0][f] 
        getCofactor(mat, temp, 0, f, n); 
        D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); 

        // terms are to be added with alternate sign 
        sign = -sign; 
    }

    return D; 
} 

// Driver program to test above functions 
var mat = [[-2, -8, 3, 5], 
           [-3, 1, 7, 3],
           [1, 2, -9, 6], 
           [-6, 7, 7, -9]
          ];

alert("Determinant of the matrix is : " + 
determinantOfMatrix(mat, N)); 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Display a Modal Window Automatically Using Bootstrap.js?

Recently, I've become interested in using the Bootstrap library by Twitter for my simple web page. My goal is to have a modal window automatically display after the page loads. If anyone has any tips on how to achieve this, I would greatly appreciate ...

Vue.js axios method returns undefined; v-for directive fails to iterate - Issue on Wordpress site

Using a shortcode, I have integrated Vue.js into a Wordpress page. pl2010_vue_init_directory = pl2010_vue_init_directory || (function(ctx) { new Vue( { el: '#'+ctx.el, data: { errorMsg: "", successMsg: "", show ...

Tips for capturing audio in flac codec format using JS/AJAX

Is there a way to record audio in flac codec instead of opus codec? I attempted setting the codec to flac like this: let blob = new Blob(audioChunks,{type: 'audio/ogg; codecs=flac' }); I also tried this: var options = { audioBitsPerSecond : ...

Changing C Code to JNI C Code

To convert the provided C code into JNI C code, you would need to consider what data type to use for JsonResult. Should it be a jstring, jint, or any other specific data type that JNI supports for JSON strings or objects? Any guidance on this matter woul ...

What is the best way to add a new row to an existing CSV file using json2csv in Node.js?

I need to append a new row to an existing CSV file. If the CSV file already exists, I want to add the new row after the last existing row without adding a column header. Here is the code snippet that I have been using: var fields = ['total', &a ...

Direct your attention solely on the input fields and buttons

Is it possible to restrict focus to specific elements, such as input fields and buttons? For example, if a user is focused on an input field and then clicks somewhere else on the page, the input field should retain focus. But if the user clicks on another ...

Tips to avoid the page from scrolling to the top when the menu is opened

Whenever a user taps the menu button on the page, a full-page menu opens. However, there is an issue - the main content page automatically scrolls to the top. Can you provide suggestions on how to prevent this from happening? I have already looked into a s ...

Retrieve all instances of a key-value pair within an object that share the same key

Here is some JSON data: [{"name":"David","text":"Hi"},{"name":"Test_user","text":"test"},{"name":"David","text":"another text"}] I am l ...

What is the best way to retrieve the file name from the current document's URL using JavaScript?

I need help with a Javascript function that can extract the current file name without any parameters. $(location).attr('href').match(/([a-zA-Z\-\_0-9]+\.\w+)$/); var current_path = RegExp.$1; if ((current_path == 'index. ...

Utilizing the Bootstrap 5 Alpha validation script within a React environment

I've been working on implementing Bootstrap 5 alpha's validation in my React app. https://i.sstatic.net/tbqLr.png The form should not submit if left blank, and it should display a check or an error mark at the bottom accordingly. So far, I&apo ...

Ensuring the accuracy of nested objects through class validator in combination with nestjs

I'm currently facing an issue with validating nested objects using class-validator and NestJS. I attempted to follow this thread, where I utilized the @Type decorator from class-transform but unfortunately, it did not work as expected. Here is my setu ...

A guide on setting up fixed row numbers in MUI-X DataGrid

One challenge I am facing is rendering the row numbers in a table so that they remain static even when columns are sorted or filtered. I attempted to use the getRowIndexRelativeToVisibleRows method of the grid API, but unfortunately, it does not work as ex ...

Are there any security risks in transmitting a password over HTTPS using jsonp?

Is it secure to send a password in JSONP using jquery over HTTPS for authentication if I can't use a JSON POST? EDIT: $.ajax({ type : "POST", url: "https://example.com/api.php", dataType: "jsonp", jsonp: "callback", data: { ...

Use the document.getElementById function in JavaScript to dynamically retrieve elements based on user input in an HTML document. This will

I am currently working towards creating a gallery using pure JavaScript. To start, I am experimenting with a model that involves two buttons - when button #1 is clicked, the string "1.jpg" appears below, and when button #2 is clicked, "2.jpg" is displayed. ...

Unleashing the full potential of ajax through endless scrolling performance

Recently, I implemented an infinite scroll feature on my website's index page by making ajax requests to retrieve a JSON containing 40 objects. Then, I add them using a JavaScript loop. However, I've noticed that it slows down the site at times. ...

What is preventing Bootstrap properties from being applied to HTML elements appended to the DOM through JavaScript?

Currently, I am immersed in a project that utilizes Bootstrap to generate various nested components styled in accordance with Bootstrap's class system. I triumphantly crafted a card component using Bootstrap, but encountered a challenge when attemptin ...

"Facing rendering issues with handlebars.js when trying to display an

I have been diligently working on trying to display an array from my running express app, but despite the lack of errors, nothing is being rendered. Take a look at my handlebars template: <h3>Registered Users:</h3> <h5>{{users}}</h5& ...

Error in Express application due to uncaught SyntaxError

I am attempting to live stream data using websockets to Chartjs, however I keep encountering the following error. main.js:1 Uncaught SyntaxError: Unexpected token <https://i.sstatic.net/9OCI1.png https://i.sstatic.net/bmGeW.gif What could be causi ...

Utilize JavaScript or JQuery to create a dynamic pop-up window that appears seamlessly on the

Looking to create a unique feature on an HTML page? Want a clickable link that opens a "pop-up" displaying a specific image, right within the page rather than in a new tab or window? Ideally, this pop-up should be movable around the page like a separate ...

The body tag mysteriously disappears after the function is called within the $().html() command

As I delve into scraping the source code of a website, I encounter an interesting phenomenon. Initially, when I print out the complete source code, everything appears as expected. However, upon attempting to print an actual DOM, I notice a slight change i ...