javascript matrix manipulation is not working - javascript

This is a bad coded solution to a problem in "advent of code": link to problem
I don't know the reason because my code is not working properly, I had an error related to regular expressions cause I didn't reset the pointer of the regexp object, now that error is fixed I think, but something is escaping to my knowledge in what I've done bad.
The problem is that the solution that my code displays is not correct, you can submit a solution on the link I've provided and get feedback of your solutions.
Correct solution: 543903
Given solution: 418954
// day 6 of advent of code
var input = "removed, take from problem";
function processInput(input, matrix) {
var linesOfInput = input.split("\n");
var matches;
var turnOnRE = /turn on (\d+),(\d+).*?(\d+),(\d+)/g;
var turnOffRE = /turn off (\d+),(\d+).*?(\d+),(\d+)/g;
var toggleRE = /toggle (\d+),(\d+).*?(\d+),(\d+)/g;
// regular expression objects lastIndex property must be 'reseted' in order to work well
for (var i = 0 ; i < linesOfInput.length; i++) {
turnOnRE.lastIndex = 0;
turnOffRE.lastIndex = 0;
toggleRE.lastIndex = 0;
matches = turnOnRE.exec(linesOfInput[i]);
if (matches != null) {
manipulateLights(matrix, matches[1], matches[2], matches[3], matches[4], true);
continue;
}
matches = turnOffRE.exec(linesOfInput[i]);
if (matches != null) {
manipulateLights(matrix, matches[1], matches[2], matches[3], matches[4], false);
continue;
}
matches = toggleRE.exec(linesOfInput[i]);
manipulateLights(matrix, matches[1], matches[2], matches[3], matches[4]);
}
}
function manipulateLights(matrix, startI, startJ, endI, endJ, newValue) {
if (newValue == undefined) { // toogle
for (var i = startI ; i <= endI; i++) {
for (var j = startJ ; j <= endJ; j++) {
matrix[i][j] = !matrix[i][j];
}
}
console.log(startI, startJ, endI, endJ, newValue);
} else {
for (var i = startI ; i <= endI; i++) {
for (var j = startJ ; j <= endJ; j++) {
matrix[i][j] = newValue;
}
}
console.log(startI, startJ, endI, endJ, newValue);
}
console.log(countTurnedOnLights(matrix));
}
function countTurnedOnLights(matrix) {
var turnedOn = 0;
for (var i = 0 ; i < matrixWidth; i++) {
for (var j = 0 ; j < matrixHeigth; j++) {
if (matrix[i][j] == true) {
turnedOn++;
}
}
}
return turnedOn;
}
var matrixHeigth = 1000;
var matrixWidth = 1000;
// define a bidimensional array, is almost like in C++
var lightMatrix = new Array(matrixWidth);
for (var i = 0 ; i < matrixWidth; i++) {
lightMatrix[i] = new Array(matrixHeigth);
}
// turn off all lights
for (var i = 0 ; i < matrixWidth; i++) {
for (var j = 0 ; j < matrixHeigth; j++) {
lightMatrix[i][j] = false;
}
}
processInput(input, lightMatrix);
console.log(countTurnedOnLights(lightMatrix));

OK I figured out the error - your regular expression matches are being treated as strings when you first create your for loops.
for (var i = startI ; i <= endI; i++) {
for (var j = startJ ; j <= endJ; j++) {
When you hit a combo like 756,53 through 923,339, it thinks 53 > 339 and it exits the loop immediately. Either wrap each "start" variable with Number() in your for loops, or do so when passing the parameters.

Related

How can speed up search loop?

There is a cycle with the condition how can it be optimized so that the search is faster?
for (var i = 0; i < db.rows.length; i++) {
for (var j = 0; j < user.rows.length; j++) {
for (var k = 0; k < work.length; k++) {
if (db.rows[i].LOGIN === user.rows[j].login && work[k].name === db.rows[i].NAME) {
}
}
}
}
This is typically something that you would expect to see executed on the database.
That being said, you can split up the condition, so that you don't need to perform the second nested loop for every row:
for (var i = 0; i < db.rows.length; i++) {
for (var j = 0; j < user.rows.length; j++) {
if (db.rows[i].LOGIN === user.rows[j].login) {
for (var k = 0; k < work.length; k++) {
if (work[k].name === db.rows[i].NAME) {
}
}
}
}
}
You could take two Maps for the user logins and work names.
var userLogins = new Map(user.rows.map(o => [o.login, o])),
workNames = new Map(o => [o.name, o]),
for (var i = 0; i < db.rows.length; i++) {
if (userLogins.has(db.rows[i].LOGIN) && workNames.has(work[k].name)) {
// do something
}
}
If you need just the simple check with using the objects of user.rows or work, you could take a Set instead.
var userLogins = new Set(user.rows.map(({ login } => login)),
workNames = new Set(({ name }) => name),
for (var i = 0; i < db.rows.length; i++) {
if (userLogins.has(db.rows[i].LOGIN) && workNames.has(work[k].name)) {
// do something
}
}

How do I log some tests for javascript?

I was hoping to get your assistance with this "Is Unique" algorithm in Javascript.
var allUniqueChars = function(string) {
// O(n^2) approach, no additional data structures used
// for each character, check remaining characters for duplicates
for (var i = 0; i < string.length; i++) {
console.log(i);
for (var j = i + 1; j < string.length; j++) {
if (string[i] === string[j]) {
return false; // if match, return false
}
}
}
return true; // if no match, return true
};
/* TESTS */
// log some tests here
allUniqueChars('er412344');
I am looking to log some tests, to see it display in the console. How do I call the function with unique strings to test it?
John
You can always create an Array with your strings and test like:
var allUniqueChars = function(string) {
// O(n^2) approach, no additional data structures used
// for each character, check remaining characters for duplicates
for (var i = 0; i < string.length; i++) {
for (var j = i + 1; j < string.length; j++) {
if (string[i] === string[j]) {
return false; // if match, return false
}
}
}
return true; // if no match, return true
};
/* TESTS */
// log some tests here
[
'er412344',
'ghtu',
'1234',
'abba'
].forEach(v => console.log(allUniqueChars(v)));
MDN Array.prototype.foreach
Run the snippet multiple times to generate unique random strings and display results:
var allUniqueChars = function(string) {
for (var i = 0; i < string.length; i++)
for (var j = i + 1; j < string.length; j++)
if (string[i] === string[j])
return false;
return true;
};
var getUniqueStr = () => Math.random().toString(36).substr(2, 9);
let myStringArray = [];
for(var i =0 ; i<8; i++) // 8 test cases in this example
myStringArray.push(getUniqueStr());
console.log(myStringArray.map(e=>e + " : " + allUniqueChars(e)));
You can use this function found here to generate random strings for testing (not mine!):
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));

Aligning contents of range to other range

I would like align row in function of the Name (column B & D), for exemple on the picture (1) the 2 red rectangles should be on the same line like for the 2 green rectangles but I don't know why, it doesn't work, here the code :
function onOpen(event){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("test1");
var data = sheet.getDataRange().getValues();
for(var j = 1; j < data.length; j++) {
if(data[j][1].trim() != '') {
for (var i = 1; i < data.length; i++) {
if(data[i][3].trim() != '') {
if(data[j][1] == data[i][3]) {
if(j != i) {
var j1 = j + 1;
var i1 = i + 1;
sheet.getRange('D'+j1+':E'+j1).moveTo(sheet.getRange('F1:G1'));
sheet.getRange('D'+i1+':E'+i1).moveTo(sheet.getRange('D'+j1+':E'+j1));
sheet.getRange('F1:G1').moveTo(sheet.getRange('D'+i1+':E'+i1));
}
break;
}
}
}
}
}
}
I'm pretty sure this code should work
Oddly it works if I'm running the code step by step like this, firstly :
for(var j = 1; j < 2; j++)
after
for(var j = 2; j < 3; j++)
after
...
until
for(var j = 6; j < 7; j++)
Well I found a workaround :)
function onOpen(event){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("test1");
var data = sheet.getDataRange().getValues();
var blank = 0;
// I count the blank case so I don't run the code effortlessly on blank case
for(var j = 1; j < data.length; j++) {
if(data[j][1].trim() == '')
blank++;
}
var length = data.length - blank;
// I don't make a real switch in fact, I'm using a tempory space where I order the data
for(var j = 1; j < length; j++) {
for (var i = 1; i < length; i++) {
if(data[j][1] === data[i][3]) {
var j1 = j + 1;
var i1 = i + 1;
sheet.getRange('D'+i1+':E'+i1).moveTo(sheet.getRange('F'+j1+':G'+j1)); // column F & G is the tempory space where I put the ordered data
break;
}
}
}
// I move back the tempory space ordered now to his initial place
sheet.getRange('F2:G'+length).moveTo(sheet.getRange('D2:E'+length));
}

Print prime numbers between 0 and 100

I'm trying to print all prime number between 0 and 100, but when executing this code the browser's tab just outputs nothing!!
for(var i = 2; i < 100; i++)
{
var prime = [];
for(var j = 0; j <= i; j++)
{
var p = i % j;
}
if(p != 0) prime.push(i);
else continue;
}
for(var k = 0; k < prime.length; k++)
{
document.writeln(prime[k], "<br>");
}
Try this one. I have also optimise the code (you only need to check upto sqrt(i) ).
var prime = [];
prime.push(2); //smallest prime
var flag = 0;
for(var i = 3; i < 100; i=i+2) //skip all even no
{
for(var j = 3; j*j <= i; j=j+2) //check by upto sqrt(i), skip all even no
{
if(i % j == 0) {
flag = 0;break; //not a prime, break
}
flag = 1;
}
if (flag == 1) prime.push(i); //prime, add to answer
}
for(var k = 0; k < prime.length; k++)
{
document.writeln(prime[k], "<br>");
}
Because you blank your list of primes EVERY loop cycle, move it outside the for loop
You need to make your variable prime outside of your loop
This is the code you have re-written
var prime = [];
for(var i = 2; i < 100; i++)
{
for(var j = 0; j <= i; j++)
{
var p = i % j;
}
if(p != 0) prime.push(i);
else continue;
}
for(var k = 0; k < prime.length; k++)
{
document.writeln(prime[k], "<br>");
}
I'm a fan of the sieve of Eratosthenes.
The following code should do what you wanted.
var prime = Array(101).fill(true);
for (var i = 2; i < 100; ++i){
if (prime[i]){
document.writeln(i, "<br>");
for (var j = i*i; j < 100; j += i){
prime[j] = false;
}
}
}
Or since it's only up to 100 you could just manually type the list (but, hey where's the learning if you do it that way?).
(1) Move prime outside the for loop, (2) start j at 2 and end when j < i, (3) check when p == 0 with a boolean flag and break inner loop.
var prime = []; //put prime out here so it does not reassign
for(var i = 2; i < 100; i++)
{
var isPrime = true;
for(var j = 2; j < i; j++) //start j at 2
{
var p = i % j;
if(p == 0)
{
isPrime = false;
break;
}
}
if(isPrime) prime.push(i);
}
for(var k = 0; k < prime.length; k++)
{
document.writeln(prime[k], "<br>");
}

bruteforce string matching javascript

function search(pattern, text) {
var M = pattern.length;
var N = text.length;
for (var i = 0; i < N - M; i++) {
var j =0;
while (j < M) {
if (text.charAt(i + j) != pattern.charAt(j)) {break;}
}
if (j == M) {return i;}
}
return -1;
}
console.log(search("rf", "jdsrfan"));
I want to make an brute-force string matching algorithm in JavaScript. Can anyone tell me whats wrong with above code?
I did fixed it myself fixed code as follows:
// return offset of first match or -1 if no match
function bruteForcePatternSearch(sPattern, sText) {
var M = sPattern.length,
N = sText.length;
for (var i = 0; i <= N - M; i++) {
var j=0;
while (j < M) {
if (sText.charAt(i+j) !=sPattern.charAt(j)){
break;
}
j++;
}
if (j == M) {return i;} // found at offset i
}
return -1; // not found
}
bruteForcePatternSearch("abracadabra","abacadabrabracabracadabrabrabracad");
You're never incrementing j to start with. Hence the infinite loop.
Then, as Claudio commented, i < N - M is wrong. Should be i <= N - M.
Spoiler: here the fixed function. But I advise you not to take it as-is, but to try doing it yourself instead.
function search(pattern, text) {
var M = pattern.length;
var N = text.length;
for (var i = 0; i <= N - M; ++i) {
var matched = true;
for (var j = 0; j < M; ++j) {
if (text.charAt(i + j) != pattern.charAt(j)) {
matched = false;
break;
}
}
if (matched) {
return i;
}
}
return -1;
}
i guess this will work
for (var i = 0; i < M; i++) {
var j =0;
while (j < N) {
if (text.charAt(j) != pattern.charAt(i)) {
break;
}
j++
}
if (j == M) {return i;}
}
here is the explanation
on each pattern
match each character of text

Categories

Resources