Related
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.
I am using tafgeet javascript function to convert numbers into Arabic words, but the problem is that it supports only 2 decimal places, how can I modify the function to make it read 3 decimal places:
It actually translates upto a million on the left hand side, so it would be possible to apply the same methodology on the right side.
I tried to fiddle with it, but it doesn't work. I am posting the original javascript.
/**
* TafgeetJS module.
* #module TafgeetJS
* #description Converts currency digits into written Arabic words
* #author Mohammed Mahgoub <mmahgoub#gmail.com>
*/
function Tafgeet(digit) {
var currency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "SDG";
//Split fractions
var splitted = digit.toString().split(".");
this.fraction = 0;
if (splitted.length > 1) {
var fraction = parseInt(splitted[1]);
if (fraction >= 1 && fraction <= 99) {
this.fraction = splitted[1].length === 1 ? fraction * 10 : fraction;
} else {
//trim it
var trimmed = Array.from(splitted[1]);
this.fraction = "" + trimmed[0] + trimmed[1];
}
}
this.digit = splitted[0];
this.currency = currency;
}
Tafgeet.prototype.parse = function () {
var serialized = [];
var tmp = [];
var inc = 1;
var count = this.length();
var column = this.getColumnIndex();
if (count >= 16) {
console.error("Number out of range!");
return;
}
//Sperate the number into columns
Array.from(this.digit.toString()).reverse().forEach(function (d, i) {
tmp.push(d);
if (inc == 3) {
serialized.unshift(tmp);
tmp = [];
inc = 0;
}
if (inc == 0 && count - (i + 1) < 3 && count - (i + 1) != 0) {
serialized.unshift(tmp);
}
inc++;
});
// Generate concatenation array
var concats = []
for (i = this.getColumnIndex(); i < this.columns.length; i++) {
concats[i] = " و";
}
//We do not need some "و"s check last column if 000 drill down until otherwise
if (this.digit > 999) {
if (parseInt(Array.from(serialized[serialized.length - 1]).join("")) == 0) {
concats[parseInt(concats.length - 1)] = ""
for (i = serialized.length - 1; i >= 1; i--) {
if (parseInt(Array.from(serialized[i]).join("")) == 0) {
concats[i] = ""
} else {
break;
}
}
}
}
var str = "";
str += "فقط ";
if (this.length() >= 1 && this.length() <= 3) {
str += this.read(this.digit);
} else {
for (i = 0; i < serialized.length; i++) {
var joinedNumber = parseInt(serialized[i].reverse().join(""));
if (joinedNumber == 0) {
column++;
continue;
}
if (column == null || column + 1 > this.columns.length) {
str += this.read(joinedNumber);
} else {
str += this.addSuffixPrefix(serialized[i], column) + concats[column];
}
column++;
}
}
if (this.currency != "") {
if (this.digit >= 3 && this.digit <= 10) {
str += " " + this.currencies[this.currency].plural;
} else {
str += " " + this.currencies[this.currency].singular;
}
if (this.fraction != 0) {
if (this.digit >= 3 && this.digit <= 10) {
str +=
" و" +
this.read(this.fraction) +
" " +
this.currencies[this.currency].fractions;
} else {
str +=
" و" +
this.read(this.fraction) +
" " +
this.currencies[this.currency].fraction;
}
}
}
str += " لا غير";
return str;
};
Tafgeet.prototype.addSuffixPrefix = function (arr, column) {
if (arr.length == 1) {
if (parseInt(arr[0]) == 1) {
return this[this.columns[column]].singular;
}
if (parseInt(arr[0]) == 2) {
return this[this.columns[column]].binary;
}
if (parseInt(arr[0]) > 2 && parseInt(arr[0]) <= 9) {
return (
this.readOnes(parseInt(arr[0])) +
" " +
this[this.columns[column]].plural
);
}
} else {
var joinedNumber = parseInt(arr.join(""));
if (joinedNumber > 1) {
return this.read(joinedNumber) + " " + this[this.columns[column]].singular;
} else {
return this[this.columns[column]].singular;
}
}
};
Tafgeet.prototype.read = function (d) {
var str = "";
var len = Array.from(d.toString()).length;
if (len == 1) {
str += this.readOnes(d);
} else if (len == 2) {
str += this.readTens(d);
} else if (len == 3) {
str += this.readHundreds(d);
}
return str;
};
Tafgeet.prototype.readOnes = function (d) {
if (d == 0) return;
return this.ones["_" + d.toString()];
};
Tafgeet.prototype.readTens = function (d) {
if (Array.from(d.toString())[1] === "0") {
return this.tens["_" + d.toString()];
}
if (d > 10 && d < 20) {
return this.teens["_" + d.toString()];
}
if (d > 19 && d < 100 && Array.from(d.toString())[1] !== "0") {
return (
this.readOnes(Array.from(d.toString())[1]) +
" و" +
this.tens["_" + Array.from(d.toString())[0] + "0"]
);
}
};
Tafgeet.prototype.readHundreds = function (d) {
var str = "";
str += this.hundreds["_" + Array.from(d.toString())[0] + "00"];
if (
Array.from(d.toString())[1] === "0" &&
Array.from(d.toString())[2] !== "0"
) {
str += " و" + this.readOnes(Array.from(d.toString())[2]);
}
if (Array.from(d.toString())[1] !== "0") {
str +=
" و" +
this.readTens(
(Array.from(d.toString())[1] + Array.from(d.toString())[2]).toString()
);
}
return str;
};
Tafgeet.prototype.length = function () {
return Array.from(this.digit.toString()).length;
};
Tafgeet.prototype.getColumnIndex = function () {
var column = null;
if (this.length() > 12) {
column = 0;
} else if (this.length() <= 12 && this.length() > 9) {
column = 1;
} else if (this.length() <= 9 && this.length() > 6) {
column = 2;
} else if (this.length() <= 6 && this.length() >= 4) {
column = 3;
}
return column;
};
Tafgeet.prototype.ones = {
_1: "واحد",
_2: "ٱثنين",
_3: "ثلاثة",
_4: "أربعة",
_5: "خمسة",
_6: "ستة",
_7: "سبعة",
_8: "ثمانية",
_9: "تسعة"
};
Tafgeet.prototype.teens = {
_11: "أحد عشر",
_12: "أثني عشر",
_13: "ثلاثة عشر",
_14: "أربعة عشر",
_15: "خمسة عشر",
_16: "ستة عشر",
_17: "سبعة عشر",
_18: "ثمانية عشر",
_19: "تسعة عشر"
};
Tafgeet.prototype.tens = {
_10: "عشرة",
_20: "عشرون",
_30: "ثلاثون",
_40: "أربعون",
_50: "خمسون",
_60: "ستون",
_70: "سبعون",
_80: "ثمانون",
_90: "تسعون"
};
Tafgeet.prototype.hundreds = {
_100: "مائة",
_200: "مائتين",
_300: "ثلاثمائة",
_400: "أربعمائة",
_500: "خمسمائة",
_600: "ستمائة",
_700: "سبعمائة",
_800: "ثمانمائة",
_900: "تسعمائة"
};
Tafgeet.prototype.thousands = {
singular: "ألف",
binary: "ألفين",
plural: "ألآف"
};
Tafgeet.prototype.milions = {
singular: "مليون",
binary: "مليونين",
plural: "ملايين"
};
Tafgeet.prototype.bilions = {
singular: "مليار",
binary: "مليارين",
plural: "مليارات"
};
Tafgeet.prototype.trilions = {
singular: "ترليون",
binary: "ترليونين",
plural: "ترليونات"
};
Tafgeet.prototype.columns = ["trilions", "bilions", "milions", "thousands"];
Tafgeet.prototype.currencies = {
SDG: {
singular: "جنيه سوداني",
plural: "جنيهات سودانية",
fraction: "قرش",
fractions: "قروش"
},
SAR: {
singular: "ريال سعودي",
plural: "ريالات سعودية",
fraction: "هللة",
fractions: "هللات"
},
QAR: {
singular: "ريال قطري",
plural: "ريالات قطرية",
fraction: "درهم",
fractions: "دراهم"
},
AED: {
singular: "درهم أماراتي",
plural: "دراهم أماراتية",
fraction: "فلس",
fractions: "فلوس"
},
EGP: {
singular: "جنيه مصري",
plural: "جنيهات مصرية",
fraction: "قرش",
fractions: "قروش"
},
USD: {
singular: "دولار أمريكي",
plural: "دولارات أمريكية",
fraction: "سنت",
fractions: "سنتات"
},
AUD: {
singular: "دولار أسترالي",
plural: "دولارات أسترالية",
fraction: "سنت",
fractions: "سنتات"
},
TND: {
singular: "دينار تونسي",
plural: "دنانير تونسية",
fraction: "مليم",
fractions: "مليمات"
}
};
module.exports = Tafgeet;
Thanks.
Change this:
this.fraction = "" + trimmed[0] + trimmed[1];
To this:
this.fraction = "" + trimmed[0] + trimmed[1] + trimmed[2];
But this is a crude solution you need to do some validations and checks before you deploy this to production
This is a problem where I need to return a number which only appears once in the array while the rest of the elements appear twice. Using binary search I did what I can but I was stuck at the first test case. I don't understand why it's returning undefined when I can log the same. Help me understand what's going on.
function singleNonDuplicate(nums) {
if(nums.length == 1) {
console.log(nums[0]);
return nums[0];
}
if((nums[Math.floor(nums.length/2)] !== nums[Math.floor(nums.length/2) - 1]) && (nums[Math.floor(nums.length/2)] !== nums[Math.floor(nums.length/2) + 1])) {
return nums[Math.floor(nums.length/2)];
}
if(Math.floor(nums.length/2) % 2 == 0) {
if(nums[Math.floor(nums.length/2)] == nums[Math.floor(nums.length/2) - 1]) {
singleNonDuplicate(nums.slice(0, Math.floor(nums.length/2) - 1));
console.log('g');
} else {
singleNonDuplicate(nums.slice(Math.floor(nums.length/2) + 2));
console.log('g');
}
} else {
if(nums[Math.floor(nums.length/2)] == nums[Math.floor(nums.length/2) - 1]) {
console.log(nums.slice(Math.floor(nums.length/2) + 1));
singleNonDuplicate(nums.slice(Math.floor(nums.length/2) + 1));
} else {
console.log('g');
singleNonDuplicate(nums.slice(0, Math.floor(nums.length/2)));
}
}
}
console.log(singleNonDuplicate([1,1,2]));
This might be a little off topic but there is a much better way to do this kind of problem using XOR:
function appearsOnlyOnce(array) {
var single = array[0];
for (var i=1; i<array.length; i++) {
single ^= array[i];
}
return single
}
When you call singleNonDuplicate from within your functio you have to return the result.
function singleNonDuplicate(nums) {
if(nums.length == 1) {
console.log(nums[0]);
return nums[0];
}
if((nums[Math.floor(nums.length/2)] !== nums[Math.floor(nums.length/2) - 1]) && (nums[Math.floor(nums.length/2)] !== nums[Math.floor(nums.length/2) + 1])) {
return nums[Math.floor(nums.length/2)];
}
if(Math.floor(nums.length/2) % 2 == 0) {
if(nums[Math.floor(nums.length/2)] == nums[Math.floor(nums.length/2) - 1]) {
return singleNonDuplicate(nums.slice(0, Math.floor(nums.length/2) - 1));
console.log('g');
} else {
return singleNonDuplicate(nums.slice(Math.floor(nums.length/2) + 2));
console.log('g');
}
} else {
if(nums[Math.floor(nums.length/2)] == nums[Math.floor(nums.length/2) - 1]) {
console.log(nums.slice(Math.floor(nums.length/2) + 1));
return singleNonDuplicate(nums.slice(Math.floor(nums.length/2) + 1));
} else {
console.log('g');
return singleNonDuplicate(nums.slice(0, Math.floor(nums.length/2)));
}
}
}
console.log(singleNonDuplicate([1,1,2]));
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.
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);
}