I made a simple program in JavaScript to find a matrix of the cofactors of a 3X3 matrix. However, the program is crashing my page repeatedly, and I cannot find any logical error in the program. Here's my code :
var matrixA = {
a11:"",
a12:"",
a13:"",
a21:"",
a22:"",
a23:"",
a31:"",
a32:"",
a33:""
};
function determinant (given,order) {
if(order==3){
var det = (given.a11*((given.a22*given.a33)-(given.a23*given.a32)))-
(given.a21*((given.a12*given.a33)-(given.a13*given.a32)))+
(given.a31*((given.a12*given.a23)-(given.a13*given.a22)));
}
else if(order==2){
var det = (given.a11*given.a22)-(given.a21*given.a12);
}
return det;
}
function cofactors(given){
var multiplier;
var temp = {
a11:"",
a12:"",
a21:"",
a22:""
};
var found_cofactor_matrix = {};
for (var i = 1; i <4; i++) {
for (var j = 1; i < 4; j++) {
if(((i+j)%2)==0){
multiplier = 1;
}
else if(((i+j)%2)==1){
multiplier = -1;
}
//Check whether row or column number is the same to make a 2X2 matrix
for(var a = 1; a < 4; a++){
for (var b = 0; b < 4; b++) {
if((a==i)||(b==j)){
} //do nothing
else{
if(temp.a11==""){
temp.a11 = given["a"+a+b];
}
else if(temp.a12 == ""){
temp.a12 = given["a"+a+b];
}
else if(temp.a21 == ""){
temp.a21 = given["a"+a+b];
}
else if(temp.a22 == ""){
temp.a22 = given["a"+a+b];
}
}
};
};
found_cofactor_matrix["a"+i+j] = multiplier*determinant(temp,2);
};
};
return found_cofactor_matrix;
}
Here, the parameter "given" is an object sent to it from the place where the function is called, and is the original matrix (matrixA) whose cofactors have to be found. I basically create a 2X2 matrix first, find its determinant and multiply it with 1 or -1 as required. I then write this value into the appropriate position in the matrix.
for (var j = 1; i < 4; j++) { should be for (var j = 1; j < 4; j++) {.
Remove semicolons at the end of for loop. And add your determinant function.
Did you open your console? Running this code in Chrome's console yields Uncaught ReferenceError: found_cofactor is not defined. You are trying to define the ["a"+i+j] property of an undefined object. It should be found_cofactor_matrix.
Besides, the determinant() function may be undefined (it does not appear in your piece of code)
Related
I'm trying to get N ways of solves a N rook problem. The issue I am having is currently, I seem to get n*n solutions while it needs to be N! . Below is my code, I have written it in simple loops and functions, so it's quite long. Any help would be greatly appreciated
Note: Please ignore case for n = 2. I get some duplicates which I thought I would handle via JSON.stringify
var createMatrix = function (n) {
var newMatrix = new Array(n);
// build matrix
for (var i = 0; i < n; i++) {
newMatrix[i] = new Array(n);
}
for (var i = 0; i < n; i++) {
for (var j = 0; j < n; j++) {
newMatrix[i][j] = 0;
}
}
return newMatrix;
};
var newMatrix = createMatrix(n);
// based on rook position, greying out function
var collision = function (i, j) {
var col = i;
var row = j;
while (col < n) {
// set the row (i) to all 'a'
col++;
if (col < n) {
if (newMatrix[col][j] !== 1) {
newMatrix[col][j] = 'x';
}
}
}
while (row < n) {
// set columns (j) to all 'a'
row++;
if (row < n) {
if (newMatrix[i][row] !== 1) {
newMatrix[i][row] = 'x';
}
}
}
if (i > 0) {
col = i;
while (col !== 0) {
col--;
if (newMatrix[col][j] !== 1) {
newMatrix[col][j] = 'x';
}
}
}
if (j > 0) {
row = j;
while (row !== 0) {
row--;
if (newMatrix[i][row] !== 1) {
newMatrix[i][row] = 'x';
}
}
}
};
// checks position with 0 and sets it with Rook
var emptyPositionChecker = function (matrix) {
for (var i = 0; i < matrix.length; i++) {
for (var j = 0; j < matrix.length; j++) {
if (matrix[i][j] === 0) {
matrix[i][j] = 1;
collision(i, j);
return true;
}
}
}
return false;
};
// loop for every position on the board
loop1:
for (var i = 0; i < newMatrix.length; i++) {
var row = newMatrix[i];
for (var j = 0; j < newMatrix.length; j++) {
// pick a position for rook
newMatrix[i][j] = 1;
// grey out collison zones due to the above position
collision(i, j);
var hasEmpty = true;
while (hasEmpty) {
//call empty position checker
if (emptyPositionChecker(newMatrix)) {
continue;
} else {
//else we found a complete matrix, break
hasEmpty = false;
solutionCount++;
// reinitiaze new array to start all over
newMatrix = createMatrix(n);
break;
}
}
}
}
There seem to be two underlying problems.
The first is that several copies of the same position are being found.
If we consider the case of N=3 and we visualise the positions by making the first rook placed red, the second placed green and the third to be placed blue, we get these three boards:
They are identical positions but will count as 3 separate ones in the given Javascript.
For a 3x3 board there are also 2 other positions which have duplicates. The gets the count of unique positions to 9 - 2 - 1 -1 = 5. But we are expecting N! = 6 positions.
This brings us to the second problem which is that some positions are missed. In the case of N=3 this occurs once when i===j==1 - ie the mid point of the board.
This position is reached:
This position is not reached:
So now we have the number of positions that should be found as 9 - 2 - 1 - 1 +1;
There appears to be nothing wrong with the actual Javascript in as much as it is implementing the given algorithm. What is wrong is the algorithm which is both finding and counting duplicates and is missing some positions.
A common way of solving the N Rooks problem is to use a recursive method rather than an iterative one, and indeed iteration might very soon get totally out of hand if it's trying to evaluate every single position on a board of any size.
This question is probably best taken up on one of the other stackexchange sites where algorithms are discussed.
I want to write this function "guessPasscode", but don't think my codes work. (the other functions are correct) It is supposed to guess every number from 0000 ~ 9999 as four-digit passcodes.
I run the function and it doesn't print out anything, and I also don't think the function works the way I wanted it to.
var guess = "";
var guessCode ="";
function start() {
var secretPasscode = generateRandomPasscode();
guessPasscode(secretPasscode);
}
// Checks whether the given guess passcode is the correct passcode
function isCorrect(guessCode, correctCode) {
return guessCode == correctCode;
}
// Generates a random 4 digit passcode and returns it as a String
function generateRandomPasscode() {
var randomPasscode = "";
for(var i = 0; i < 4; i++) {
var randomDigit = Randomizer.nextInt(0, 9);
randomPasscode += randomDigit;
}
return randomPasscode;
}
function guessPasscode(secretPasscode){
for (var a = 0; a < 10; a++){
guess += a;
for (var b = 0; b < 10; b++){
guess += b;
for(var c = 0; c < 10; c++){
guess += c;
for (var d = 0; d < 10; d++){
guess += d;
if (isCorrect(guessCode, secretPasscode)){
println("Success!");
break;
}
guess = 0; //I am not sure about this line though
}
}
}
}
if (isCorrect(guessCode, secretPasscode)){
println("Success!");
}
}
I expect it to print "success" and stop the loop after it has found the correct password.
Those nested for loops are really wild and incredibly inefficient. If you want to guess from 0 to 9999, just run the loop through and then pad zeroes to the left.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
for (let i = 0; i < 9999; i++) {
let guess = String(i).padStart(4, '0')
guessAnswer(guess)
//whatever logic here to exit loop on correct guess
}
I am newbie in machine learning, but decided to make own js library for neural networks, everything went perfect until i tryed to train my NN. In My Mini Library i created some functions...
1) A Function That Creates My Neuron-Object:
this.Node = function (conns) {
var output = {};
output.b = hyth.Random({type: "TanH"});
output.w = [];
for (var a = 0; a < conns; a++){
output.w[a] = hyth.Random({type: "TanH"});
}
output.Value = function (i) {
if (i.length == conns) {
var sum = 0;
for (var a = 0; a < conns; a++){
sum += i[a] * output.w[a];
}
sum += output.b;
return myMath.Activate(sum, {type: "Sigmoid"});
}
}
return output;
}
This function has one argument , which is the amount of wanted weights from neuron, and it returns an object with two properties - "b" the float (bias), and "w" the 1D Array which contains floats, and one method - which calculates the activation of neuron-object.
2) A Function That Creates My Neural Net
this.Network = function () {
var p = arguments;
var arr = [];
for (var a = 0; a < p.length-1; a++){
arr[a] = [];
for (var b = 0; b < p[a+1]; b++){
arr[a][b] = this.Node(p[a]);
}
}
return arr;
}
This Function Returns A 2D Array with Neuron-Object as It's final value, using argument array as settings for layer count and node count for each layer.
3) A Function That Feeds Forward The NN
this.Forward = function (network, input) {
if (network[0][0].w.length == input.length) {
var activations = [];
for (var a = 0; a < network.length; a++){
activations[a] = [];
for (var c = 0; c < network[a].length; c++){
if (a == 0){
activations[0][c] = network[0][c].Value(input);
continue;
}
activations[a][c] = network[a][c].Value(activations[a-1]);
}
}
return activations;
}
}
This Function Returns 2D array with an activation float for every neuron as it's final value. It uses 2 agruments - the output of 2nd function, input array.
4) And Final Function That Backpropagates
this.Backward = function (network, input, target) {
if (network[0][0].w.length == input.length && network[network.length-1].length == target.length) {
var activations = this.Forward(network, input, true);
var predictions = activations[activations.length-1];
var errors = [];
for (var v = 0; v < network.length; v++) {
errors[v] = [];
}
for (var a = network.length-1; a > -1; a--){
for (var x = 0; x < network[a].length; x++) {
var deract = hyth.Deractivate(activations[a][x]);
if (a == network.length-1) {
errors[a][x] = (predictions[x] - target[x]) * deract;
} else {
errors[a][x] = 0;
for (var y = 0; y < network[a+1].length; y++) {
errors[a][x] += network[a+1][y].w[x] * errors[a+1][y];
}
errors[a][x] *= deract;
}
}
}
return errors;
}
}
This Function Returns 2D array with the rror float for every neuron as it's final value. Arguments are 3 - the nnet , input and wanted output.
So I can make a neural network, feed forward and and backpropagate, receive activations and errors, but i always fail to train my net with my errors and activations to work perfect , last time it was outputing same result for every type of input. I want to understand training algorithm from zero , so i need someone's help.
P.S. - i dont want someone say that i need to use famous libraries , i want to understand and make it myself.
I am working on a minesweeper game in javascript. The mechanism that is causing me trouble is the for loop inside the Mine object that sets the isBomb variable to true or false.
var board = [];
var bombs = [];
var mines;
function findNeighbors(x,y) {
return 'work in progress'
}
function setup() {
// create bombs
for (var i = 0; i < 45; i++) {
var position = [floor(random(0,15)),floor(random(0,15))];
if (!bombs.includes(position)) {
bombs[i] = position;
}
}
// create board
for (var y = 0; y < 15; y++) {
board[y] = new Array();
for (var x = 0; x < 15; x++) {
board[y][x] = new Mine(y,x);
}
}
}
console.log(board);
console.log(bombs);
function Mine(x,y) {
this.x = x;
this.y = y;
this.neighbors = findNeighbors(this.x,this.y);
for (var iter = 0; iter < 45; iter++) {
if (bombs[iter] == [this.x,this.y]) {
this.isBomb = true;
}
else {
this.isBomb = false;
}
}
this.show = function() {
return 'show'
}
this.setValue = function(value) {
this.value = value;
return value;
}
}
When I type bombs[44] in the console for example, it returns something like [5,11] yet when I check if bombs[44] = [5,11] it will always return false. Is there a specific way I have to denote the [5,11] array for it to be recognized?
This is because you cannot compare two arrays in javascript. What you can do is using join() and then compare as strings in single step,
bombs[44].join(",") == [5,11].join(",")
Or you can compare the contents of the array individually
Try changing the conditional expression in your for-loop at the top for (var i = 0; i < 45; i++) to for (var i = 0; i < arr.length; i++)
this will make the loop , go over the full array length with less room for error. for loops can be , error prone and tedious.
I'm creating a program that will ask a question and give 5 choices for answers.
One is pre-defined and is correct, the others I want to be random selections from a bank of answers and the entire array is to be shuffled too.
I've written something, but it has some inconsistencies.
For one, sometimes the pre-defined choice appears twice in the list (it appears to skip over my if check).
Another is that sometimes, the editor crashes when I run it.
I use for in loops and I'm worried the crash is caused by a never-ending loop.
Here's my code:
private var numberOfComponents:int;
private var maxComponents:int = 5;
//numberOfComponents returns the length property of my 'components' answer bank
componentsSelection = buildComponentSelectionList(0); //0 is the index of my correct answer
function buildComponentSelectionList(correctItemIndex){
var theArray:Array = new Array();
var indicesOfSelection:Array = getIndicesByIncluding(correctItemIndex);
Debug.Log(indicesOfSelection);
for (var i=0;i<indicesOfSelection.length;i++)
theArray.Push(components[indicesOfSelection[i]]);
return theArray;
}
function getIndicesByIncluding(correctItem){
var indicesArray:Array = new Array();
var numberOfChoices = maxComponents-1;
for(var i=0;i<numberOfChoices;i++){
var number = Mathf.Round(Random.value*(numberOfComponents-1));
addToRandomNumberSelection(indicesArray, number,correctItem);
}
indicesArray.Push(correctItem);
RandomizeArray(indicesArray);
return indicesArray;
}
function addToRandomNumberSelection(indicesArray:Array,number,correctItem){
if(indicesArray.length == 0){
indicesArray.Push(number);
} else {
var doesntExist = true;
for(var i=0;i<indicesArray.length;i++){
if(indicesArray[i] == correctItem)
doesntExist = false;
if (indicesArray[i] == number)
doesntExist = false;
}
if(doesntExist) {
indicesArray.Push(number);
} else {
addToRandomNumberSelection(indicesArray, Mathf.Round(Random.value*(numberOfComponents-1)),correctItem);
}
}
}
function RandomizeArray(arr : Array)
{
for (var i = arr.length - 1; i > 0; i--) {
var r = Random.Range(0,i);
var tmp = arr[i];
arr[i] = arr[r];
arr[r] = tmp;
}
}
The editor is Unity3D, and the code is a version of JavaScript; I think my error is a logic one, rather than a syntactical one.
I feel I've been staring at this code for too long now and I'm missing something obvious.
Can anybody help me?
You can loop through the options and determine the probability that it should be included, then shuffle the included options:
function getRandomOptions(allOptions, correctIndex, count){
var result = [allOptions[correctIndex]];
count--;
var left = allOptions.length;
for (var i = 0; count > 0; i++) {
if (i != correctIndex && Math.floor(Math.random() * left) < count) {
result.push(allOptions[i]);
count--;
}
left--;
}
shuffleArray(result);
return result;
}
function shuffleArray(arr) {
for (var i = arr.length - 1; i > 0; i--) {
var r = Math.floor(Math.random() * i);
var tmp = arr[i];
arr[i] = arr[r];
arr[r] = tmp;
}
}
Demo: http://jsfiddle.net/Guffa/wXsjz/