JavaScript - Making a sum of values in same row and column - javascript

How can I make a sum of values in same row and column and make another array (can be one-dimensional) of results.
Array [
[ 1, 1, 0, 1 ],
[ 1, 1, 1, 1 ],
[ 1, 1, 1, 1 ],
[ 1, 1, 0, 1 ]
]

var res = []; //the 1D array to hold the sums
var hArr = [
[ 1, 1, 0, 1 ],
[ 1, 1, 1, 1 ],
[ 1, 1, 1, 1 ],
[ 1, 1, 0, 1 ]
]; //your array
var vArr = []; //Now lets create an array of arrays with the columns of hArr
for (var j=0; j<hArr[0].length; j++) {
var temp = [];
for (var i=0; i<hArr.length; i++) {
temp.push(hArr[i][j]);
}
vArr.push(temp);
}
//sum all the element in the line - Vertically and Horizontally
function SumVH (hInd, vInd) {
var sum = 0;
//add horizontal elements
for(var i=0; i<hArr[hInd].length; i++) {
sum += hArr[hInd][i];
}
//add vertical elements
for(var i=0; i<vArr[vInd].length; i++) {
sum += vArr[vInd][i];
}
//console.log("hInd="+hInd+" vInd="+vInd+" Sum="+sum);
return sum;
}
// go through the main array and get result
var sumR = 0;
//sum of each row
for (var i=0; i<hArr.length; i++) {
for (var j=0; j<hArr[i].length; j++) {
sumR = SumVH(i,j) - (2 * hArr[i][j]);
res.push(sumR);
}
}
Please check it now. The variable res holds the result
For my array writen above I want result array like 7, 7, 5, 7, 8, 8,
6, 8, 8, 8, 6, 8, 7, 7, 5, 7
Now the above code does not count the number itself in sum. But to get the result as your comment, please replace this line
sumR = SumVH(i,j) - (2 * hArr[i][j]);
with
sumR = SumVH(i,j);
Thank you.

Related

What is N-2 doing in the Sudoku for loop to validate the block JavaScript

I was researching solution to the Sudoku Solution Validator algorithm and came across this example. The code works and validates but what I do not understand is why in the for loops to get to validate a block there is a N-2? If N = 9 and the board is 9 * 9 then why would that need to be changed to 7?
When I remove the -2 and just leave N I do not see any changes in my console.
Here is the link https://www.geeksforgeeks.org/check-if-given-sudoku-solution-is-valid-or-not/
Thank you!!
<script>
// JavaScript program to implement
// the above approach
var N = 9;
// Function to check if all elements
// of the board[][] array store
// value in the range[1, 9]
function isinRange(board)
{
// Traverse board[][] array
for(var i = 0; i < N; i++)
{
for(var j = 0; j < N; j++)
{
// Check if board[i][j]
// lies in the range
if (board[i][j] <= 0 ||
board[i][j] > 9)
{
return false;
}
}
}
return true;
}
// Function to check if the solution
// of sudoku puzzle is valid or not
function isValidSudoku(board)
{
// Check if all elements of board[][]
// stores value in the range[1, 9]
if (isinRange(board) == false)
{
return false;
}
// Stores unique value
// from 1 to N
var unique = Array(N+1).fill(false);
// Traverse each row of
// the given array
for(var i = 0; i < N; i++)
{
unique = Array(N+1).fill(false);
// Traverse each column
// of current row
for(var j = 0; j < N; j++)
{
// Stores the value
// of board[i][j]
var Z = board[i][j];
// Check if current row
// stores duplicate value
if (unique[Z])
{
return false;
}
unique[Z] = true;
}
}
// Traverse each column of
// the given array
for(var i = 0; i < N; i++)
{
// Initialize unique[]
// array to false
unique = Array(N+1).fill(false);
// Traverse each row
// of current column
for(var j = 0; j < N; j++)
{
// Stores the value
// of board[j][i]
var Z = board[j][i];
// Check if current column
// stores duplicate value
if (unique[Z])
{
return false;
}
unique[Z] = true;
}
}
// Traverse each block of
// size 3 * 3 in board[][] array
for(var i = 0; i < N - 2; i += 3) //<====== what is the point of N-2? What is it doing?
{
// j stores first column of
// each 3 * 3 block
for(var j = 0; j < N - 2; j += 3) //<====== what is the point of N-2? What is it doing?
{
// Initialize unique[]
// array to false
unique = Array(N+1).fill(false);
// Traverse current block
for(var k = 0; k < 3; k++)
{
for(var l = 0; l < 3; l++)
{
// Stores row number
// of current block
var X = i + k;
// Stores column number
// of current block
var Y = j + l;
// Stores the value
// of board[X][Y]
var Z = board[X][Y];
// Check if current block
// stores duplicate value
if (unique[Z])
{
return false;
}
unique[Z] = true;
}
}
}
}
// If all conditions satisfied
return true;
}
// Driver Code
var board = [ [ 7, 9, 2, 1, 5, 4, 3, 8, 6 ],
[ 6, 4, 3, 8, 2, 7, 1, 5, 9 ],
[ 8, 5, 1, 3, 9, 6, 7, 2, 4 ],
[ 2, 6, 5, 9, 7, 3, 8, 4, 1 ],
[ 4, 8, 9, 5, 6, 1, 2, 7, 3 ],
[ 3, 1, 7, 4, 8, 2, 9, 6, 5 ],
[ 1, 3, 6, 7, 4, 8, 5, 9, 2 ],
[ 9, 7, 4, 2, 1, 5, 6, 3, 8 ],
[ 5, 2, 8, 6, 3, 9, 4, 1, 7 ] ];
if (isValidSudoku(board))
{
document.write("Valid");
}
else
{
document.write("Not Valid");
}
</script>
Sudoku contains sub blocks each is 3X3
So the code loops over the first cell in each sub block then iterate over the each sub-block cell.
The author of the code added N-2 condition so when he iterate over the sub-block cells
Var X = i+k; he make sure he doesn't access out of bound cell.
How ever when the number of columns and number of rows in sudoku are multiple of 3 this check is useless.
That's why you see no difference when you remove -2.
This is because the code is working in steps of 3
for(var i = 0; i < N - 2; i += 3)
You can see i += 3
so i = 0, 3, 6
as N = 9 -> 9-2 = 7 -> 6 is bigger than 7
Later in teh code you can see loop k & l, this is taking care of the 3x3 matrix

elements are being added to every row when inserting into a row for a 2D array that has been filled with empty Arrays

I am creating a new matrix where I want to take the rows of the original matrix and make them into columns as well as take the columns of the original matrix and make them into rows.
A matrix of:
[[1,2]
[3,4] [[1,3,5]
[5,6]] turns into [2,4,6]]
When I initialize the new matrix while using the fill() method to create my rows, the insertions duplicate for every row when inserting into a row.
const arrOne = [[1,2,3],[4,5,6],[7,8,9]]
var transpose = function(matrix) {
const transposedArr = new Array(matrix[0].length).fill(new Array()); // initializes array to [ [], [], [] ]
//iterate through row
for(let i = 0; i < matrix.length; i++) {
//iterate through columns at row
for(let j = 0; j < matrix[i].length; j++) {
transposedArr[j].push(matrix[i][j])
}
}
return transposedArr;
};
console.log(transpose(arrOne));
This will print
[
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
]
When I initialize my array using a for loop, I do not get duplicate entries
const arrOne = [[1,2,3],[4,5,6],[7,8,9]]
var transpose = function(matrix) {
const transposedArr = [] // initializing using const transposedArr = Array() also works!
for(let i = 0; i < matrix[0].length; i++) { // initializes array to [ [], [], [] ]
transposedArr.push(new Array())
}
//iterate through row
for(let i = 0; i < matrix.length; i++) {
//iterate through columns at row
for(let j = 0; j < matrix[i].length; j++) {
transposedArr[j].push(matrix[i][j])
}
}
return transposedArr;
};
console.log(transpose(arrOne));
This will print:
[
[ 1, 4, 7 ],
[ 2, 5, 8 ],
[ 3, 6, 9 ]
]
ASK: Why is it that when I initialize the array using the fill() method, it is duplicating my insertions for each row?
I came across this issue when working on this Leetcode problem: https://leetcode.com/problems/transpose-matrix/
I also tested this code in repl. It was to make sure it wasn't an issue in Leetcode's environment.
const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
/* Allocate newMatrix array */
const newMatrix = [];
for (const i in matrix) {
const temp = [];
for (const j in matrix[i])
temp.push(matrix[j][i]);
newMatrix.push(temp);
}
console.log(newMatrix);
First of all, I have created and new array with the opposite length from the first array (Rows = Cols / Cols = Rows).
Then you just have to initialize the second array with [i][j] = [j][i] so it will initialize the column of the original matrix to the row of the new one.
Hope you understood.
By the way fill method "fills" the array element to a STATIC value, and the parameters should be (value, start, end).
Documentation: Array.prototype.fill()

creating an array Javascript breakout game

I'm creating a simple breakout clone using HTML5 Canvas and have come across the loadHitGrid() function, but I'm having difficulty understanding what it does.
It looks like its creating arrays within the hitgrid array
and then filling this with 1's
Can someone help or draw this out?
function loadHitGrid() {
for (var i = 0; i < NUM_ROWS; i++) {
hitGrid[i] = new Array;
for (var j = 0; j < NUM_COLS; j++) {
hitGrid[i][j] = 1;
}
}
}
//Can i replace hitGrid with the following?
hitGrid = [
1, 1, 1, 1, 1, // is this the same as the above????
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1
]
function drawblocks() {
for (var i = 0; i < NUM_ROWS; i++) { // loops trough number of rows
for (var j = 0; j < NUM_COLS; j++) { // loops thgrough number of cols
if (hitGrid[i][j] == 1) { // for each row / col check for 1
ctx.beginPath(); // Satrts a new path used when drawing!
ctx.fillStyle = colours[i];
ctx.fillRect(j * (blockW + SPACING) + SPACING,
i * (blockH + SPACING) + SPACING, blockW, blockH);
}
}
}
This would be :
hitGrid = [[1, 1, 1, 1, 1], // is this the same as the above????
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]];
Of course that means that NUM_ROWS, and NUM_COLUMNS is 5 :)
Check out my comments on the code below:
function loadHitGrid () {
for(var i = 0 ; i < NUM_ROWS ; i ++) {
hitGrid[i] = new Array; //Creating an empty array NUM_ROWS amount of times
for(var j = 0; j < NUM_COLS; j ++) {
hitGrid[i][j] = 1 ; //Populating each newly created empty array with NUM_COLS amount of ones.
}
}
}
So in NUM_ROWS and NUM_COLS both equal 5 and assuming hitGrid was an empty array, the output would look more like:
[[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]]

How to create multidimensional array for each row?

For a website I used a grid layout. What I want is to store all items per row inside a row.
I have an overall array that is calling arrWrap = [];. Now I want to create for each row an new array, where I store each time 4 items. So a new array should be created after the third item in a row.
How do I achieve this?
I use Javascript for this project.
var arrPos = [];
for (var i = 0; i < elements.length; ++i) {
arrPos[i] = i;
console.dir(arrPos[i]);
if (arrPos[i] > 3) {
alert(arrPos[i]);
};
}
var arrWrap = [];
var steps = 4;
for (var i = 0; i < elements.length; i=i+steps) {
arrWrap.push(elements.slice(i,i+steps));
}
This proposal feature the Array.prototype.reduce and offers two solutions:
Grouped by consecutive elements dataGroupedA
[
[ 0, 1, 2 ],
[ 3, 4, 5 ],
[ 6, 7, 8 ],
[ 9, 10, 11 ],
[ 12, 13, 14 ]
]
Grouped by the 5th element dataGroupedB
[
[ 0, 5, 10 ],
[ 1, 6, 11 ],
[ 2, 7, 12 ],
[ 3, 8, 13 ],
[ 4, 9, 14 ]
]
The calculation of index is the important part. The rest is standard default assignment and pushing the actual element.
var data = Array.apply(Array, { length: 15 }).map(function (_, i) { return i; }),
dataGroupedA = data.reduce(function (r, a, i) {
var index = i / 3 | 0;
r[index] = r[index] || [];
r[index].push(a);
return r;
}, []),
dataGroupedB = data.reduce(function (r, a, i) {
var index = i % 5;
r[index] = r[index] || [];
r[index].push(a);
return r;
}, []);
document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(dataGroupedA, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(dataGroupedB, 0, 4) + '</pre>');
Please use the following code:
var cIndex= 0;
var data=[];
var cars = ["Saab", "Volvo", "BMW", "a", "v", "c", "q"];
for(var i = 0; i <= 3; i++)
{
cIndex = cIndex + 3;
var row = cars.slice(cIndex -3,cIndex );
data.push(row);
}
console.log(data);

sort array keys by value

I'm using javascript, and I have an array containing multiple values, which may be non-unique. I'd like to take this array and generate a new array, or ordered list, of its keys in ascending order of value. For example, if I have [ 2, 2, 4, 5, 1, 6 ], I'd like to generate [ 5, 4, 0, 1, 2, 3 ].
I was thinking of iterating over the original list and inserting each value into the new list while checking for proper placement by comparing to the existing values of the new list every time an insertion is performed. This seems wasteful, though, as I'd have to (potentially) check every value of the new list for every insertion.
Anyone have a simpler method for this?
I think you meant [ 4, 0, 1, 2, 3, 5 ].
function GetSortedKeys(values) {
var array_with_keys = [];
for (var i = 0; i < values.length; i++) {
array_with_keys.push({ key: i, value: values[i] });
}
array_with_keys.sort(function(a, b) {
if (a.value < b.value) { return -1; }
if (a.value > b.value) { return 1; }
return 0;
});
var keys = [];
for (var i = 0; i < array_with_keys.length; i++) {
keys.push(array_with_keys[i].key);
}
return keys;
}
var array = [2, 2, 4, 5, 1, 6];
alert(GetSortedKeys(array));
This is the simplest method I can come up with on Javascript, unfortunately.
Using the nice Underscore.JS:
var get_sorted_keys = function(values) {
var keys_idx = [], i;
for (i = 0; i < values.length; i++) {
keys_idx.push(i);
}
var keys = _.sortBy(keys_idx, function(idx){ return values[idx]; });
return keys;
};
var array = [2, 2, 4, 5, 1, 6];
console.log("Sorted keys:", get_sorted_keys(array));
Output:
Sorted keys: [4, 0, 1, 2, 3, 5]

Categories

Resources