Variable only works locally - javascript

I wrote some functions involving prime factorization and I noticed that when I identified my test paragraph (for testing the results of functions and such) as document.getElementById("text"), it worked fine. However, when I declared a global variable text as var text = document.getElementById("text"), and then substituted in text for the longer version, it no longer worked. I did, however, notice that it worked when I locally declared text. Why is this and how can I fix it? My JSFiddle is here: https://jsfiddle.net/MCBlastoise/3ehcz214/
And this is my code:
var text = document.getElementById("text");
function isPrime(num) {
var lastDigit = parseInt((num + "").split("").reverse()[0]);
if (typeof num !== "number" || num <= 1 || num % 1 !== 0) {
return undefined;
}
else if (num === 2) {
return true;
}
else if (lastDigit === 0 || lastDigit === 2 || lastDigit === 4 || lastDigit === 5 || lastDigit === 6 || lastDigit === 8) {
return false;
}
else {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
}
function factorSplit(dig) {
if (typeof dig !== "number" || dig <= 1 || dig % 1 !== 0) {
return undefined;
}
else if (dig === 2) {
return undefined;
}
else {
var factor;
for (var i = 2; i < dig; i++) {
if (dig % i === 0) {
factor = i;
break;
}
}
if (factor === undefined) {
return undefined;
}
else {
return [factor, (dig / factor)];
}
}
}
function allPrimes(arr) {
if (Array.isArray(arr) === false || arr.length < 1) {
return undefined;
}
else {
for (var i = 0; i < arr.length; i++) {
if (isPrime(arr[i]) !== true) {
return false;
}
}
return true;
}
}
function primeFactors(int) {
if (typeof int !== "number" || int <= 1) {
return undefined;
}
else if (isPrime(int) === true) {
return false;
}
else {
var initFactors = factorSplit(int);
while (allPrimes(initFactors) !== true) {
initFactors = initFactors.concat(factorSplit(initFactors[initFactors.length - 1]));
initFactors.splice((initFactors.length - 3), 1);
}
return initFactors;
}
}
function listPrimes() {
repeat = setInterval(findPrime, 1);
}
var primeInts = [2];
var check;
function findPrime() {
var i = primeInts[primeInts.length - 1] + 1;
if (check === undefined) {
check = true;
text.innerHTML = primeInts[0];
}
else {
while (isPrime(i) !== true) {
i++;
}
primeInts.push(i);
text.innerHTML += ", " + primeInts[primeInts.length - 1];
}
}
//text.innerHTML = isPrime(6);
<div onclick="listPrimes()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
<p id="text"></p>

The text is global, you just need to make sure the whole script file is included in the html. Here's an example of what I mean
Here in code snippets stackoverflow does this for us already.
var text = document.getElementById("text");
function isPrime(num) {
var lastDigit = parseInt((num + "").split("").reverse()[0]);
if (typeof num !== "number" || num <= 1 || num % 1 !== 0) {
return undefined;
} else if (num === 2) {
return true;
} else if (lastDigit === 0 || lastDigit === 2 || lastDigit === 4 || lastDigit === 5 || lastDigit === 6 || lastDigit === 8) {
return false;
} else {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
}
function factorSplit(dig) {
if (typeof dig !== "number" || dig <= 1 || dig % 1 !== 0) {
return undefined;
} else if (dig === 2) {
return undefined;
} else {
var factor;
for (var i = 2; i < dig; i++) {
if (dig % i === 0) {
factor = i;
break;
}
}
if (factor === undefined) {
return undefined;
} else {
return [factor, (dig / factor)];
}
}
}
function allPrimes(arr) {
if (Array.isArray(arr) === false || arr.length < 1) {
return undefined;
} else {
for (var i = 0; i < arr.length; i++) {
if (isPrime(arr[i]) !== true) {
return false;
}
}
return true;
}
}
function primeFactors(int) {
if (typeof int !== "number" || int <= 1) {
return undefined;
} else if (isPrime(int) === true) {
return false;
} else {
var initFactors = factorSplit(int);
while (allPrimes(initFactors) !== true) {
initFactors = initFactors.concat(factorSplit(initFactors[initFactors.length - 1]));
initFactors.splice((initFactors.length - 3), 1);
}
return initFactors;
}
}
function listPrimes() {
repeat = setInterval(findPrime, 1);
}
var primeInts = [2];
var check;
function findPrime() {
var i = primeInts[primeInts.length - 1] + 1;
if (check === undefined) {
check = true;
text.innerHTML = primeInts[0];
} else {
while (isPrime(i) !== true) {
i++;
}
primeInts.push(i);
text.innerHTML += ", " + primeInts[primeInts.length - 1];
}
}
function test() {
console.log("inside test1")
console.log(text);
text.innerHTML = "testtt"
}
function test2() {
console.log("inside test2")
console.log(text);
text.innerHTML = "testtt2"
}
text.innerHTML = isPrime(6);
<div onclick="test()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
<p id="text"></p>
<div onclick="test2()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
In the head the script runs/loads first and because you don't have the var's in a function they are never re-used they remain with the original value which is null since the document didn't exist at that time, then when the page loads all it has is access to the functions a call to the global var is null. This is why the code previously only worked when text = document.getElementById('text') was in a function.

Related

find the overlap between two strings

I have a string and need to check with and get whether the following strings overlap with the start and end of my target string:
target string: "click on the Run"
search strings: "the Run button to", "code and click on"
Apparently:
"the Run button to" is overlapped at the end of target "click on the Run"
"code and click on" is overlapped at the start of target "click on the Run"
Both, "the Run" and "click on" will be the desired results.
I have come up with a function to check and get the overlapped results for the cases at the start and at the end separately.
Question:
But my code could not be able to get the expected results only if I know how the search string overlapped with the target string in the very first place. And how can I combine the searched results in one go as well?
function findOverlapAtEnd(a, b) {
if (b.length === 2) {
return "";
}
if (a.indexOf(b) >= 0) {
return b;
}
if (a.endsWith(b)) {
return b;
}
return findOverlapAtEnd(a, b.substring(0, b.length - 1));
}
function findOverlapAtStart(a, b) {
if (b.length === 2) {
return "";
}
if (a.indexOf(b) >= 0) {
return b;
}
if (a.startsWith(b)) {
return b;
}
return findOverlapAtStart(a, b.substring(1));
}
console.log(findOverlapAtEnd("click on the Run", "the Run button to"))
console.log(findOverlapAtStart("click on the Run", "code and click on"))
edited:
case in the middle is also considered, e.g.:
target string: "click on the Run"
search strings: "on the"
Return value: "on the"
You may try this
function findOverlapAtEnd(a, b, min) {
if (b.length <= min) {
return '';
}
if (a.indexOf(b) >= 0) {
return b;
}
if (a.endsWith(b)) {
return b;
}
return findOverlapAtEnd(a, b.substring(0, b.length - 1), min);
}
function findOverlapAtStart(a, b, min) {
if (b.length <= min) {
return '';
}
if (a.indexOf(b) >= 0) {
return b;
}
if (a.startsWith(b)) {
return b;
}
return findOverlapAtStart(a, b.substring(1), min);
}
const GetOverlappingSection = (target, search, min) => {
if (target.length < search.length) {
const tmp = target;
target = search;
search = tmp;
}
let overlap1 = findOverlapAtStart(target, search, min);
if (overlap1.length === 0) {
overlap1 = findOverlapAtEnd(target, search, min);
}
return overlap1;
};
const removeEmptyKeyword = overlap => {
let tmpFinaloverlap = [];
overlap.forEach((key, idx) => {
if (!(key.trim().length === 0)) {
tmpFinaloverlap = [...tmpFinaloverlap, key];
}
});
return tmpFinaloverlap;
};
// let overlap = ['click on','the Run']
const GetOverlappingOfKeyowrd1And2 = (keywordSet1, keywordSet2,min) => {
let resultSetoverlap = [];
let tmpresultSetoverlap = [];
keywordSet1.forEach(key =>
keywordSet2.forEach(k2 => {
tmpresultSetoverlap = [
...tmpresultSetoverlap,
GetOverlappingSection(key, k2, min),
];
})
);
// get the resultSetoverlap
tmpresultSetoverlap.forEach(element => {
if (element.length > 0) {
resultSetoverlap = [...resultSetoverlap, element];
}
});
return resultSetoverlap;
};
const min = 2;
//To handle overlapping issue in overlapping set, that casuing
overlap.forEach((key, idx) => {
if (idx < overlap.length - 1) {
for (let i = idx + 1; i < overlap.length; i++) {
console.log(`key: ${key}`);
console.log(`search: ${overlap[i]}`);
let overlapSection = GetOverlappingSection(key, overlap[i], min);
if (overlapSection.length > 0) {
console.log(`overlapSection: ${overlapSection}`);
overlap[idx] = overlap[idx].replace(overlapSection, '');
}
}
}
});
overlap = removeEmptyKeyword(overlap);
console.log(overlap);
overlap.forEach(key => {
keywordSet2 = keywordSet2.map((k1, idx) => {
console.log(`checking overlap keyword:'${key}' in '${k1}'`);
return k1.replace(key, '');
});
});
overlap.forEach(key => {
keywordSet1 = keywordSet1.map((k1, idx) => {
console.log(`checking overlap keyword:'${key}' in '${k1}'`);
return k1.replace(key, '');
});
});
keywordSet2 = removeEmptyKeyword(keywordSet2);
keywordSet1 = removeEmptyKeyword(keywordSet1);
overlap.forEach(key => {
text = text.replace(key, `$#k1k2$&$`);
});
keywordSet1.forEach(key => {
text = text.replace(key, `$#k1$&$`);
});
keywordSet2.forEach(key => {
text = text.replace(key, `$#k2$&$`);
});
console.log(`ResultSetoverlap after processing:${text}`);
Because I need to decompress and I find these logic puzzles fun, here's my solution to the problem...
https://highdex.net/begin_end_overlap.htm
You can view source of the page to see JavaScript code I used. But just in case I ever take that page down, here's the important function...
function GetOverlappingSection(str1, str2, minOverlapLen = 4) {
var work1 = str1;
var work2 = str2;
var w1Len = work1.length;
var w2Len = work2.length;
var resultStr = "";
var foundResult = false;
var workIndex;
if (minOverlapLen < 1) { minOverlapLen = 1; }
else if (minOverlapLen > (w1Len > w2Len ? w2Len : w1Len)) { minOverlapLen = (w1Len > w2Len ? w2Len : w1Len); }
//debugger;
//we have four loops to go through. We trim each string down from each end and see if it matches either end of the other string.
for (var i1f = 0; i1f < w1Len; i1f++) {
workIndex = work2.indexOf(work1);
if (workIndex == 0 || (workIndex != -1 && workIndex == w2Len - work1.length)) {
//we found a match!
foundResult = true;
resultStr = work1;
break;
}
work1 = work1.substr(1);
if (work1.length < minOverlapLen) { break; }
}
if (!foundResult) {
//debugger;
//reset the work vars...
work1 = str1;
for (var i1b = 0; i1b < w1Len; i1b++) {
workIndex = work2.indexOf(work1);
if (workIndex == 0 || (workIndex != -1 && workIndex == w2Len - work1.length)) {
//we found a match!
foundResult = true;
resultStr = work1;
break;
}
work1 = work1.substr(0, work1.length - 1);
if (work1.length < minOverlapLen) { break; }
}
}
if (!foundResult) {
//debugger;
//reset the work vars...
work1 = str1;
for (var i2f = 0; i2f < w2Len; i2f++) {
workIndex = work1.indexOf(work2);
if (workIndex == 0 || (workIndex != -1 && workIndex == w1Len - work2.length)) {
//we found a match!
foundResult = true;
resultStr = work2;
break;
}
work2 = work2.substr(1);
if (work2.length < minOverlapLen) { break; }
}
}
if (!foundResult) {
//debugger;
//reset the work vars...
work2 = str2;
for (var i2b = 0; i2b < w2Len; i2b++) {
workIndex = work1.indexOf(work2);
if (workIndex == 0 || (workIndex != -1 && workIndex == w1Len - work2.length)) {
//we found a match!
foundResult = true;
resultStr = work2;
break;
}
work2 = work2.substr(0, work2.length - 1);
if (work2.length < minOverlapLen) { break; }
}
}
return resultStr;
}
Hopefully that's helpful.

No response from recursive function

I want to create a function that is able to determine if a number is same or palindrome. if a given number is palindrome or same then return 2 otherwise if it is not palindrome or same then i need check it twice by increment the given number by 1. after that if it palindrome or same then return 1. if no palindrome or same number found then return 0. i write the function which is giving me the exact result when i give the number as 11211 but the function don't show any response if i enter 1122 or other random value. please help me to find where the error of my function.
function sameOrPalindrome(num) {
var c = 0;
var al = 0;
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse();
for (var i = 0; i < normalArray.length; i++) {
if (normalArray[i] != revArray[i]) {
c++;
}
}
if (c == 0) {
return 2;
} else {
num++;
al = sameOrPalindrome(num);
if (al == 2) {
return 1;
} else {
num++;
al = sameOrPalindrome(num);
if (al == 2) {
return 1;
}
}
}
return 0;
}
console.log("1233",sameOrPalindrome(1233))
here is my solution to this problem:
function reversedNum(num) {
return (
parseFloat(
num
.toString()
.split('')
.reverse()
.join('')
) * Math.sign(num)
)
}
function sameOrPalindrome(num) {
if (num === reversedNum(num)) {
return 2;
} else {
num++;
if (num === reversedNum(num)) {
return 1;
} else {
num++;
if (num === reversedNum(num)) {
return 1;
}
}
}
return 0;
}
console.log("1233",sameOrPalindrome(1233))
Perhaps not using recurse - I think your function loops
const allEqual = arr => arr.every( v => v === arr[0] )
const sameOrPalin = num => {
const str = String(num);
let arr = str.split("")
if (allEqual(arr)) return 2
arr.reverse();
if (arr.join("") === str) return 1;
return 0
};
console.log("1111",sameOrPalin(1111));
console.log("2111",sameOrPalin(2111));
console.log("2112",sameOrPalin(2112));
console.log("1234",sameOrPalin(1234));
for (let i = 2111; i<=2113; i++) console.log(i,sameOrPalin(i));
Question: I assumed if palindrome test is true at first time then return 2. if not try incrementing by one and test the palindrome again . if true return 1 else try incrementing for last time and check the palindrome if true return 1 else 0.
Store string into array first and do arr.reverse().join("") to compare
let arr=num.toString().split("");
if(num.toString() == arr.reverse().join(""))
function sameOrPalindrome(num, times) {
let arr = num.toString().split("");
if (num.toString() == arr.reverse().join("")) {
if (times == 3) return 2
else return 1;
} else if (times > 0) {
num++; times--;
return sameOrPalindrome(num, times);
} else return 0
}
console.log(sameOrPalindrome(123321, 3));
console.log(sameOrPalindrome(223321, 3));
console.log(sameOrPalindrome(323321, 3));
Your function needs to know if it should not call itself any more, e.g. when it's doing the second and third checks:
function sameOrPalindrome(num,stop) { // <-- added "stop"
var c = 0;
var al = 0;
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse();
for (var i = 0; i < normalArray.length; i++) {
if (normalArray[i] != revArray[i]) {
c++;
}
}
if (c == 0) {
return 2;
} else if(!stop) { // <-- check of "stop"
num++;
al = sameOrPalindrome(num,true); // <-- passing true here
if (al == 2) {
return 1;
} else {
num++;
al = sameOrPalindrome(num,true); // <-- and also here
if (al == 2) {
return 1;
}
}
}
return 0;
}
for(let i=8225;i<8230;i++)
console.log(i,sameOrPalindrome(i));
function check_palindrom(num){
var c1 = 0;
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse();
for (var i = 0; i < normalArray.length; i++) {
if (normalArray[i] == revArray[i]) {
c1++;
}
}
if(c1==0){
return 2;
}else{
return 1;
}
}//check_palindrom
function my_fun_check_palindrome(mynum){
//console.log(mynum);
var num = mynum;
var c2 = 0;
var al = 0;
var normalArray = mynum.toString().split("");
var revArray = mynum.toString().split("").reverse();
for (var j = 0; j < normalArray.length; j++) {
if (normalArray[j] == revArray[j]) {
c2++;
}
}
if(c2==0){
console.log('Number is palindrome. Return Value :'+ 2);
}
if(1){
console.log('checking again with incremeting value my one');
num = parseInt(num)+1;
al = check_palindrom(num);
if(al==2){
console.log('Number is palindrome. Return Value :'+ 1);
}else{
console.log('Number is not palindrome. Return Value :'+ 0);
}
}
}//my_fun_check_palindrome
console.log(my_fun_check_palindrome(1122));
console.log(my_fun_check_palindrome(11221));
We should always strive to make function more effiecient... you dont need to run full loop. plus actual checking of palindrome can me modularized
function isSameOrPalindrome(num) {
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse(),
i;
for (i = 0; i < normalArray.length / 2; i++) {
if (normalArray[i] !== revArray[i]) {
break;
}
}
if (i >= normalArray.length/2) {
return "Palindrome";
} else {
return "Not Palindrome";
}
}
function doCheck(num) {
var isPalindrome = isSameOrPalindrome(num);
console.log(isPalindrome);
if(isPalindrome === "Palindrome") {
return 2;
} else {
num++;
isPalindrome = isSameOrPalindrome(num);
if(isPalindrome === "Palindrome") {
return 1;
} else {
return 0
}
}
}
console.log("100",doCheck(100));

JavaScript Recursive function return undefined instead of an array

I have the next function:
function solveSudoku(prev_tab, fila, columna) {
let tab = _.cloneDeep(prev_tab);
let sig_fila = fila;
let sig_col = columna;
if (fila === 8 && columna === 8) {
//console.log(tab);
return tab;
}
if (columna === 8) {
sig_col = 0;
sig_fila = sig_fila + 1
} else {
sig_col = sig_col + 1;
}
if ((tab[fila][columna]) !== '') {
solveSudoku(tab, sig_fila, sig_col)
} else {
for (let num = 1; num <= 9; num++) {
if (numeroValido(tab, num, fila, columna)) {
tab[fila][columna] = num;
//tab.toString();
solveSudoku(tab, sig_fila, sig_col)
}
}
}
}
it returns undefined instead of a 2D array, i already try to add return in every recursive call =>
return solveSudoku( tab, sig_fila, sig_col )
but now that doesn't work either
I'm not really familiar with algorithms for solving sudoku, so I don't know if the algorithm below is correct.
But you need to ensure that the result of the recursion is returned. In my update below, I return the first recursive call. In the loop, I only return it if the recursion successfully found a solution, otherwise the loop continues trying other numbers in the column.
function solveSudoku(prev_tab, fila, columna) {
let tab = _.cloneDeep(prev_tab);
let sig_fila = fila;
let sig_col = columna;
if (fila === 8 && columna === 8) {
//console.log(tab);
return tab;
}
if (columna === 8) {
sig_col = 0;
sig_fila = sig_fila + 1
} else {
sig_col = sig_col + 1;
}
if ((tab[fila][columna]) !== '') {
return solveSudoku(tab, sig_fila, sig_col)
} else {
for (let num = 1; num <= 9; num++) {
if (numeroValido(tab, num, fila, columna)) {
tab[fila][columna] = num;
//tab.toString();
let result = solveSudoku(tab, sig_fila, sig_col);
if (result) { // continue searching if the recursion failed
return result;
}
}
}
}
}

Getting empty data when I'm passing value to an array

I'm just wondering on how I got an empty object, and how to fix it.
tax1 has 16 objects
Payroll controller
if (vm.period === 'Semi-Monthly') {
for (var x = 0; x < vm.tax1.length; x++) {
if (vm.tax1[x].eventType === 'sm') {
vm.tax2[x] = vm.tax1[x];
}
}
} else if( vm.period === 'Monthly'){
for (var y = 0; y < vm.tax1.length; y++) {
if (vm.tax1[y].eventType === 'm') {
vm.tax2[y] = vm.tax1[y];
}
}
}
Output:
Indices are difficult to read and error-prone, you can consider using .push or .filter
Using .push
vm.tax2 = [];
var eventType;
if (vm.period == 'Semi-Monthly') {
eventType = 'sm';
}
else if( vm.period == 'Monthly') {
eventType = 'm';
}
vm.tax1.forEach(function(item) {
if (item.eventType == eventType) {
vm.tax2.push(item);
}
});
Using .filter
var eventType;
if (vm.period == 'Semi-Monthly') {
eventType = 'sm';
}
else if( vm.period == 'Monthly') {
eventType = 'm';
}
vm.tax2 = vm.tax1.filter(function(item) {
return (item.eventType == eventType);
});
Silly mistake from my side..
here's the fix
var x = 0;
var y = 0;
if (vm.period === 'Semi-Monthly') {
for ( x = 0; x < vm.tax1.length; x++) {
if (vm.tax1[x].eventType === 'sm') {
vm.tax2[y] = vm.tax1[x];
y++;
}
}
} else if( vm.period === 'Monthly'){
for ( x = 0; x < vm.tax1.length; x++) {
if (vm.tax1[x].eventType === 'm') {
vm.tax2[y] = vm.tax1[x];
y++;
}
}
}

Recursive program crashes computer

I am writing a labyrinth generator, and I am using a Dijkstra Algorithm to see how many parts my labyrinth is divided into.
What I do is I find a cell that does not have a "mark", and run the function "wave".
Function wave(row,column,marknumber):
1) I give this cell a mark.
2) Then, for every nearby cell that is not separated by a wall, I run the function "wave".
This algorithm should tell me how many parts my labyrinth is divided into, but instead my computer screen turns white, starts flashing, and then the computer turns off.
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<script src="/mazeGenerator.js"></script>
</head>
<body>
<canvas id="field" width="300" height="300"></canvas>
<script>
var mark = 1;
init();
generateBase();
var arsenalNum = window.prompt("How many arsenals?");
for (var i=0;i<arsenalNum;i++) {
arsenal();
}
var prizeNum = window.prompt("How many prizes?");
for (var i=0;i<prizeNum;i++) {
prize(i+1);
}
draw();
for (var r=0; r<DIM; r++) {
for (var c=0; c<DIM; c++) {
if (maze[r][c].mark === 0) {
draw();
//alert(" ");
wave(r,c,mark);
mark++;
}
}
}
draw();
alert("There are " + numberOfMarks() + " marks in this labyrinth.");
</script>
</body>
</html>
And here is my Javascript:
var DIM = window.prompt("Please choose a dimension.");
var maze = new Array (DIM);
// init();
// generate();
// draw();
function init() {
for (var i=0;i<DIM;i++) {
maze[i] = new Array (DIM);
for (var j=0;j<DIM;j++) {
maze[i][j] = {
"walls":[0,0,0,0],
"mark":0,
"hole":-1,
"arsenal":0,
"prize":0,
"blocks_arsenal_entrance":0
};
}
}
}
function generateBase() {
for (var r=0;r<DIM;r++) {
for (var c=0;c<DIM;c++) {
var ind = Math.floor(Math.random()*4);
addWall(r,c,ind);
if (r === 0) {
maze[r][c].walls[0] = 1;
}
if (c === (DIM-1)) {
maze[r][c].walls[1] = 1;
}
if (r === (DIM-1)) {
maze[r][c].walls[2] = 1;
}
if (c === 0) {
maze[r][c].walls[3] = 1;
}
}
}
}
function draw() {
var canvas=document.getElementById("field");
var ctx=canvas.getContext("2d");
for (var r=0;r<DIM;r++) {
for (var c=0;c<DIM;c++) {
drawCell(r,c,ctx);
}
}
}
function drawCell(r,c,ctx) {
var left = c*10;
var top = r*10;
var w = maze[r][c].walls;
if (w[0] === 1) {
ctx.moveTo(left,top);
ctx.lineTo((left+10),top);
ctx.stroke();
}
if (w[1] === 1) {
ctx.moveTo((left+10),top);
ctx.lineTo((left+10),(top+10));
ctx.stroke();
}
if (w[2] === 1) {
ctx.moveTo(left,(top+10));
ctx.lineTo((left+10),(top+10));
ctx.stroke();
}
if (w[3] === 1) {
ctx.moveTo(left,top);
ctx.lineTo((left),(top+10));
ctx.stroke();
}
if (maze[r][c].arsenal == 1) {
ctx.fillStyle = "#FF0000";
ctx.fillRect(left,top,10,10);
}
if (maze[r][c].prize !== 0) {
ctx.fillStyle = "#00FF00";
ctx.fillRect(left,top,10,10);
}
if (maze[r][c].mark === 1) {
ctx.fillStyle = "#FF00FF";
ctx.fillRect(left,top,10,10);
}
if (maze[r][c].mark === 2) {
ctx.fillStyle = "#FFFF00";
ctx.fillRect(left,top,10,10);
}
if (maze[r][c].mark === 3) {
ctx.fillStyle = "#00FFFF";
ctx.fillRect(left,top,10,10);
}
if (maze[r][c].mark === 4) {
ctx.fillStyle = "#0080FF";
ctx.fillRect(left,top,10,10);
}
if (maze[r][c].mark === 5) {
ctx.fillStyle = "#FF0080";
ctx.fillRect(left,top,10,10);
}
if (maze[r][c].mark === 6) {
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(left,top,10,10);
}
if (maze[r][c].mark === 7) {
ctx.fillStyle = "#000000";
ctx.fillRect(left,top,10,10);
}
if (maze[r][c].mark === 8) {
ctx.fillStyle = "#80FF80";
ctx.fillRect(left,top,10,10);
}
if (maze[r][c].mark === 9) {
ctx.fillStyle = "#8080FF";
ctx.fillRect(left,top,10,10);
}
if (maze[r][c].mark === 10) {
ctx.fillStyle = "#FF8080";
ctx.fillRect(left,top,10,10);
}
}
function up(r,c) {
if (r === 0) {
return null;
} else {
return maze[r-1][c];
}
}
function down(r,c) {
if (r == (DIM - 1)) {
return null;
} else {
return maze[r+1][c];
}
}
function left(r,c) {
if (c === 0) {
return null;
} else {
return maze[r][c-1];
}
}
function right(r,c) {
if (c == (DIM - 1)) {
return null;
} else {
return maze[r][c+1];
}
}
function neighbor(r,c,dir) {
if (dir === 0) {
return up(r,c);
}
if (dir === 1) {
return right(r,c);
}
if (dir === 2) {
return down(r,c);
}
if (dir === 3) {
return left(r,c);
}
}
function opposite(dir) {
if (dir === 0) {
return 2;
}
if (dir === 1) {
return 3;
}
if (dir === 2) {
return 0;
}
if (dir === 3) {
return 1;
}
}
function arsenal() {
var done = false;
while (!done) {
var r = Math.floor(Math.random()*DIM);
var c = Math.floor(Math.random()*DIM);
if (maze[r][c].prize !== 0) {
continue;
}
if (maze[r][c].arsenal !== 0) {
continue;
}
if (maze[r][c].blocks_arsenal_entrance !== 0) {
continue;
}
var entrance = Math.floor(Math.random()*4);
if ((r === 0) && (entrance === 0)) {
entrance = opposite(entrance);
}
if ((c === (DIM - 1)) && (entrance === 1)) {
entrance = opposite(entrance);
}
if ((r === (DIM - 1)) && (entrance === 2)) {
entrance = opposite(entrance);
}
if ((c === 0) && (entrance === 3)) {
entrance = opposite(entrance);
}
for (var d=0;d<4;d++) {
removeWall(r,c,d);
}
for (d=0;d<4;d++) {
if (d !== entrance) {
addWall(r,c,d);
}
}
neighbor(r,c,entrance).blocks_arsenal_entrance = 1;
maze[r][c].arsenal = 1;
done = true;
}
}
function prize(n) {
var done = false;
while (!done) {
var r = Math.floor(Math.random()*DIM);
var c = Math.floor(Math.random()*DIM);
if (maze[r][c].prize !== 0) {
continue;
}
if (maze[r][c].arsenal !== 0) {
continue;
}
if (maze[r][c].blocks_arsenal_entrance !== 0) {
continue;
}
for (var d=0;d<4;d++) {
addWall(r,c,d);
}
maze[r][c].prize = n;
done = true;
}
}
function addWall(r,c,ind) {
maze[r][c].walls[ind] = 1;
if (neighbor(r,c,ind) !== null) {
neighbor(r,c,ind).walls[opposite(ind)] = 1;
}
}
function removeWall(r,c,dir) {
maze[r][c].walls[dir] = 0;
var neighborCell = neighbor(r,c,dir);
if (neighborCell !== null) {
neighborCell.walls[opposite(dir)] = 0;
}
}
function wave(r,c,mark) {
//alert("Wave Started with " + r + ", " + c + ".");
if (maze[r][c].mark === 0) {//Make sure the cell doesn't have a mark
// alert(r + ", " + c + " does not have a mark.");
maze[r][c].mark = mark;
// alert("maze["+r+"]["+c+"].mark is now equal to " + maze[r][c].mark);
if ((maze[r][c].walls[0] === 0) && (up(r,c).mark === 0)) {
wave((r-1),c);
}
if ((maze[r][c].walls[1] === 0) && (right(r,c).mark === 0)) {
wave(r,(c+1));
}
if ((maze[r][c].walls[2] === 0) && (down(r,c).mark === 0)) {
wave((r+1),c);
}
if ((maze[r][c].walls[3] === 0) && (left(r,c).mark === 0)) {
wave(r,(c-1));
}
} else {
}
}
function numberOfMarks() {
var maxMark = 0;
for (var r=0;r<DIM;r++) {
for (var c=0;c<DIM;c++) {
if ((maze[r][c].mark) > maxMark) {
maxMark = maze[r][c].mark;
}
}
}
return maxMark;
}
function numberOfPrizes() {
var maxPrize = 0;
for (var r=0;r<DIM;r++) {
for (var c=0;c<DIM;c++) {
if ((maze[r][c].prize) > maxPrize) {
maxPrize = maze[r][c].prize;
}
}
}
return maxPrize;
}
function findMarkBorder() {
for (var r=0;r<DIM;r++) {
for (var c=0;c<DIM;c++) {
if (((maze[r][c].mark) !== up(r,c).mark) && (up(r,c).mark !== null)) {
document.write("<br> The cell above cell "+r+", "+c+" has a different mark.");
}
if (((maze[r][c].mark) !== right(r,c).mark) && (right(r,c).mark !== null)) {
document.write("<br> The cell to the right of cell "+r+", "+c+" has a different mark.");
}
if (((maze[r][c].mark) !== down(r,c).mark) && (down(r,c).mark !== null)) {
document.write("<br> The cell below cell "+r+", "+c+" has a different mark.");
}
if (((maze[r][c].mark) !== left(r,c).mark) && (left(r,c).mark !== null)) {
document.write("<br> The cell to the left of cell "+r+", "+c+" has a different mark.");
}
}
}
}
Please tell me what I am doing wrong! Thanks in advance!
This program is not working, because in the function wave, you are not passing enough arguments -- you are not passing the "mark".
For example,
if ((maze[r][c].walls[3] === 0) && (left(r,c).mark === 0)) {
wave(r,(c-1));
}
should be
if ((maze[r][c].walls[3] === 0) && (left(r,c).mark === 0)) {
wave(r,(c-1),mark);
}

Categories

Resources