javascript minesweeper placed unnecessary "1" - javascript

i wrote a minesweeper in JavaScript which was working fine for a while, and then randomly on 1 run (i was trying to improve the styling) it gave me this:
note the "1" in the upper-right corner as well as 2 missing 1's two and three spaces below it
here is my function for adding numbers to squares:
function nextToBombCheck(event) {
//reset bomb count
bombCount = 0 ;
//initialize variable for checking nerby boxes
var nextToBox = 0;
//asign the box's id as a number
var boxNum = parseInt(event.id);
var checkSide = 0;
for ( var i = 9 ; i <= 11 ; i++ ) {
nextToBox = boxNum + i;
//check if its a wrap
if ( ( nextToBox%10 === 0 && boxNum%10 === 9 ) || ( nextToBox%10 === 9 && boxNum%10 === 0 ) ) {
continue;
//check boxes below
} else if ( bomb.indexOf( nextToBox ) >= 0 ) {
bombCount++;
}
}
for ( i = -1 ; i <= 1 ; i++ ) {
nextToBox = boxNum + i;
//check if its a wrap (above and below wont work anyway)
if ( ( nextToBox%10 === 0 && boxNum%10 === 9 ) || ( nextToBox%10 === 9 && boxNum%10 === 0 ) ) {
continue;
//check boxes alongside
} else if ( bomb.indexOf( nextToBox ) >= 0 ) {
bombCount++;
}
}
for ( i = -11 ; i <= -9 ; i++ ) {
nextToBox = boxNum + i;
if ( ( nextToBox%10 === 0 && boxNum%10 === 9 ) || ( nextToBox%10 === 9 && boxNum%10 === 0 ) ) {
continue;
//check boxes above
} else if ( bomb.indexOf( nextToBox ) >= 0 ) {
bombCount++;
}
}
//set class(colors) based on bombCount
event.className = classList[ bombCount ];
if ( bombCount !== 0 ) {
//write number of neighboring bombs
event.innerHTML = bombCount;
}
}
my program works on using a table and each td has an id 0-99
heres a link if that helps

Nice game. But you commit the common error of counting the last index. Do you see that your table have size of 11x11 = 121? But in your program you use
var rowAmount = 10;
var columnAmount = 10;
cellAmount = columnAmount * rowAmount;
which is wrong. The for loop also explicitly assume there are 11 column:
for ( i = 0 ; i <= rowAmount ; i++ ) {
gameBox += "<tr>";
for ( var j = 0 ; j <= columnAmount ; j++ ) {
var idValue = i * 10 + j;
gameBox += "<td class = 'box' id = '" + idValue + "' onclick = 'process(this);' ></td>"; }
gameBox += "</tr>";
}
but idValue is using 10 column. It means that your program will ignore the last column. Change that in all your codes and you will be fine.

I believe that the problem is related to the multiple elements with the same id as you can see in the screen shot from Chrome inspector. As you can notice the last cell of the row and the first cell of the next row have the same id. And this is true for all rows.

Instead of using modulo trickery etc, use X and Y coordinates and have a function to get a cell id from given X and Y, that is
function getCellId(x, y) {
return 'cell-' + x + '-' + y);
}
And name your cell id's cell-0-0 -> cell-9-9
Then the neighboring cells are
(x - 1, y - 1)
(x, y - 1)
(x + 1, y - 1)
(x - 1, y )
(x + 1, y )
(x - 1, y + 1)
(x, y + 1)
(x + 1, y + 1)
This problem could have also be avoided, provided that this approach was used.

Related

Move the knight from position 1 to position 2 with less than 10 moves

I have a question.
here is my chess board , ok?
enter image description here
I wanna move knight from postion 1 to postion 2 with all possible ways.
but with less than 10 moves.
can any one help me have to do this?
function isSafe(x,y,board){
if(x >= 0 && y >= 0 && x < 8 && y < 8 && board[y][x] == 0){return true}
else{return false}
}
function printBoard(board){
for(let i = 0; i < 8; i++){
for(let x = 0; x < 8; x++){
console.log(board[i][x] + " ");
}
}
}
function solve(){
let board = [];
for(let i = 0; i < 8; i++){
board[i] = [];
for(let x = 0; x < 8; x++){
board[i][x] = 0;
}
}
var move_x = [2, 1, -1, -2, -2, -1, 1, 2];
var move_y = [1, 2, 2, 1, -1, -2, -2, -1];
board[0][0] = 1;
var pos = 1;
if(solveKTUtil(board,0,0,move_x,move_y,pos)){
printBoard(board);
}
else{console.log('no answer')}
console.log(board)
}
function solveKTUtil(board,curr_x,curr_y,move_x,move_y,pos){
if(curr_x == 7 && curr_y == 7){return true}
for(let i = 0; i < 8; i++){
var new_y = curr_y + move_y[i] ;
var new_x = curr_x + move_x[i] ;
if(isSafe(new_x,new_y,board)){
console.log(new_x,new_y)
board[new_y][new_x] = pos;
if(board[7][7] === 1){return true}
else{
solveKTUtil(board,curr_x,curr_y,move_x,move_y,pos);
}
}
}
return false
}
solve();
now it's nowt working fine . please help me
Refactored your code, and shaped the solution into a depth first search (DFS) with a taxicab distance heuristic to favor the moves of the knight that are closer to the goal square. Additionally, introduced a recursive generator function in the event that one wants to control how often and how long the solutions are sought.
The solution count ramps up quickly, of course, when seeking more moves. Some quick testing reveals that there are...
108 solutions of 6 moves or less
1896 solutions of 8 moves or less
40432 solutions of 10 moves or less
736396 solutions of 12 moves or less
Inline comments assist in understanding the recursive generator function...
Running the code snippet will display all 108 solutions of 6 moves or less.
function printBoard( board ){
let bm = '';
for (let rank = 7; 0 <= rank; rank-- ) {
for ( let file = 0; file < 8; file++ ) {
if ( board[ rank ][ file ] === -1 ) {
bm += " X ";
} else if ( board[ rank ][ file ] === 0 ) {
bm += " - ";
} else {
bm += ( " " + board[ rank ][ file ] ).slice( -2 ) + " ";
}
}
bm += '\n'
}
return bm + '\n';
}
function genAndSortKnightMoves( knightRank, knightFile, goalRank, goalFile ) {
const knightMoves = [ [-2,-1], [-2,1], [-1,-2], [-1,2], [1,-2], [1,2], [2,-1], [2,1] ];
function isKnightOnTheBoard( r, f ){
return ( 0 <= r && 0 <= f && r < 8 && f < 8 );
}
// Generate list of possible moves where the Knight is on the board and the
// square has not already been visited.
let moves = [];
knightMoves.forEach( rf => {
let rank = knightRank + rf[ 0 ];
let file = knightFile + rf[ 1 ];
if ( isKnightOnTheBoard( rank, file ) ) {
moves.push( [ rank, file ] );
}
} );
// Now, sort the moves based on which is closer to the goal using the
// taxicab distance.
moves.sort( ( a, b ) =>
( Math.abs( a[ 0 ] - goalRank ) + Math.abs( a[ 1 ] - goalFile ) )
- ( Math.abs( b[ 0 ] - goalRank ) + Math.abs( b[ 1 ] - goalFile ) )
);
return moves;
}
// Set up zero filled 8 x 8 array.
let workingBoard = new Array( 8 ).fill( 0 ).map( () => new Array( 8 ).fill( 0 ) );
function* solve( startRank, startFile, goalRank, goalFile, maxDepth = 12, depth = 0 ) {
// Set the square that the knight landed on.
workingBoard[ startRank ][ startFile ] = ( depth === 0 ? -1 : depth );
// If we reached the goal square, let's yield the result.
if ( startRank === goalRank && startFile === goalFile ) {
yield workingBoard;
} else if ( depth < maxDepth ) {
// Otherwise, if we haven't reached maxDepth, let's go deeper. First, get
// the list of candidate knight moves, sorted by the squares closest to the
// goal using the simple taxicab distance.
let candidateMoves = genAndSortKnightMoves( startRank, startFile, goalRank, goalFile );
// Now, loop through the options, and if the square is empty, let's jump
// to that square.
for ( let move of candidateMoves ) {
let rank = move[ 0 ];
let file = move[ 1 ];
if ( workingBoard[ rank ][ file ] === 0 ) {
yield* solve( rank, file, goalRank, goalFile, maxDepth, depth + 1 );
}
}
}
// At this point, the recursion has unwound, so lets clear the knight off
// the square by resetting it to zero.
workingBoard[ startRank ][ startFile ] = 0;
}
// Set up the solution, by creating the iterator with the beginning square and
// goal square, and setting the max depth to the number of max moves sought.
let solutionsCount = 0;
let moveCountSought = 6;
const findSolution = solve( 0, 0, 7, 7, moveCountSought );
// Now, simply iterate over the yielded solutions.
do {
let soln = findSolution.next();
if ( soln.done ) {
break;
}
if ( workingBoard[ 7 ][ 7 ] <= moveCountSought ) {
solutionsCount++;
console.log( printBoard( workingBoard ) );
}
} while ( true );
console.log( `Number of solutions less than or equal to ${moveCountSought} moves is ${solutionsCount}.` );

What is the Logic behind " i = (i + 1) % word.length "

Im new to Coding. can someone explain ("i = (i + 1) % word.length")
var text = document.querySelector('#text-wrap');
var word = text.getElementsByTagName('span');
var i = 0;
function run(){
word[i].style.display = 'none';
i = (i + 1) % word.length
word[i].style.display = 'initial';
}
setInterval(run,800)
if (i < word.length - 1):
  i = i + 1; // increment
else if (i == word.length - 1):
  i = 0; // go back to 0
For example, if word.length is 5 and the initial i is 0, then
the output sequence of i is 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, ....
It resets i to 0 ( to select the first word ) after the last word is selected.
var text = document.querySelector('#text-wrap');
var word = text.getElementsByTagName('span');
var i = 0;
function run(){
// hide i-th word
word[i].style.display = 'none';
// set i to
// if the last word is selected select the first word ( reset to 0 )
i = (i + 1) % word.length
// display i-th word
word[i].style.display = 'initial';
}
setInterval(run,800)
I would not recommend doing it like this. An if statement is much clearer. This should do the same:
var text = document.querySelector('#text-wrap');
var word = text.getElementsByTagName('span');
var i = 0;
function run(){
word[i].style.display = 'none';
if( i+1 !== word.length )
i++;
else // if i+1 === word.length
i = 0;
word[i].style.display = 'initial';
}
setInterval(run,800)
Still you shouldn't use i as a global variable. At least use a variable name that is incredibly unlikely to exist in other code instead.
a quick modulus explanation
the modulus is what is leftover when you cannot iteratively remove an amount. Some examples:
6 % 2 = 0 ( 6 - 2 - 2 - 2 = 0)
5 % 2 = 1 ( 5 - 2 -2 = 1 )
1 % 2 = 1 ( cannot substract 2 from 1 so the value is 1 )
simplified example
var word = [ '1', '2', '3'];
var i = 0;
function run(){
console.log( word[i] );
if( i+1 !== word.length )
i++;
else // if i+1 === word.length
i = 0;
}
setInterval(run,1000);

Choropleth Pretty Breaks

I'm trying to develop pretty breaks function in javascript, but I only find examples in r.
Do you know where to find the information for javascript ?
My issue is that I dont understand how to generate the breaks. I understand how to make a round breaks, but how do we calculate the ranges of breaks when selecting 4 breaks ?
I use geojson file working with density.
Thank you for the help
PS : I apologize for my english, I am not a native speaker.
I've solved using this steps.
I hope it serves someone else.
Thanks a lot :D
function prettyBreaks(minimum, maximum, classes) {
let breaks = [];
if ( classes < 1 ) {
breaks.push( maximum );
return breaks;
}
let minimumCount = parseInt(classes / 3 );
let shrink = 0.75;
let highBias = 1.5;
let adjustBias = 0.5 + 1.5 * highBias;
let divisions = parseInt( classes );
let h = highBias;
let cell;
let small = false;
let dx = maximum - minimum;
if (NearTo( dx, 0.0 ) && NearTo( maximum, 0.0 )) {
cell = 1.0;
small = true;
} else {
let U = 1;
cell = (Math.abs(maximum) >= Math.abs(minimum)) ? Math.abs(maximum) : Math.abs(minimum);
if ( adjustBias >= 1.5 * h + 0.5) {
U = parseInt( 1 + (1.0 / (1 + h)) );
} else {
U = parseInt( 1 + ( 1.5 / ( 1 + adjustBias ) ) );
}
let maxBetweenDivisions = (1 >= divisions) ? 1 : divisions;
small = dx < ( cell * U * maxBetweenDivisions * 1e-07 * 3.0 );
}
if (small) {
if (cell > 10) {
cell = 9 + cell / 10;
cell = cell * shrink;
}
if (minimumCount > 1) {
cell = cell / minimumCount;
}
} else {
cell = dx;
if (divisions > 1) {
cell = cell / divisions;
}
}
if (cell < 20 * 1e-07) {
cell = 20 * 1e-07;
}
let base = Math.pow(10.0, Math.floor( Math.log10( cell )));
let unit = base;
if ( ( 2 * base ) - cell < h * ( cell - unit ) ) {
unit = 2.0 * base;
if ( ( 5 * base ) - cell < adjustBias * ( cell - unit ) )
{
unit = 5.0 * base;
if ( ( 10.0 * base ) - cell < h * ( cell - unit ) )
{
unit = 10.0 * base;
}
}
}
let start = parseInt( Math.floor( minimum / unit + 1e-07 ) );
let end = parseInt( Math.ceil( maximum / unit - 1e-07 ) );
// Extend the range out beyond the data. Does this ever happen??
while ( start * unit > minimum + ( 1e-07 * unit ) ) {
start = start - 1;
}
while ( end * unit < maximum - ( 1e-07 * unit ) ) {
end = end + 1;
}
let k = parseInt( Math.floor( 0.5 + end - start ) );
if ( k < minimumCount ) {
k = minimumCount - k;
if ( start >= 0 ) {
end = end + k / 2;
start = start - k / 2 + k % 2;
}
else {
start = start - k / 2;
end = end + k / 2 + k % 2;
}
}
let minimumBreak = start * unit;
let count = parseInt( end - start );
breaks = [];
for ( let i = 1; i < count + 1; i++ ) {
breaks.push( minimumBreak + i * unit );
}
if ( breaks.length === 0 ) return breaks;
if ( breaks[0] < minimum ) {
breaks.splice(0, 1, minimum);
}
if ( breaks[breaks.length-1] > maximum ) {
breaks.splice(breaks.length-1, 1, maximum);
}
if ( minimum < 0.0 && maximum > 0.0 ) { //then there should be a zero somewhere
let breaksMinusZero = []; // compute difference "each break - 0"
for ( let i = 0; i <= breaks.length; i++ ) {
breaksMinusZero.push( breaks[i] - 0.0 );
}
let posOfMin = 0;
for ( let i = 1; i <= breaks.length; i++ ) { // find position of minimal difference
if ( Math.abs( breaksMinusZero[i] ) < Math.abs( breaksMinusZero[i - 1] ) )
posOfMin = i;
}
breaks[posOfMin] = 0.0;
}
return breaks;
};
/** Check if value1 is nearest to value2 */
function NearTo(value1, value2) {
if (value1 > 1 || value2 > 1) return false;
else if ((value1 >= 0 && value1 < 1 ) && (value2 >= 0 && value2 < 1 )) return true;
else return false;
};

how to write a function in javascript that transforms multiple of 3 into a string

This is what I have done so far but how to create the list of numbers and how to put in the loop thank you:
Simply use an Object with arrays in it to return your results.
In addition, you must install the parameters in the loop counter
function mojitor(startOfCount, endOfCount) {
var output = {
menthe : [],
glace : [],
rhum : [],
mentheGlace : [],
mojito : [],
};
for (var x=startOfCount; x <= endOfCount; x++){
if( x % 3 == 0 ){
output.menthe.push(x)
}
if( x % 5 == 0 ){
output.glace.push(x)
}
if( x % 7 == 0 ){
output.rhum.push(x)
}
if( ( x % 3 == 0 ) && ( x % 5 == 0 ) ){
output.mentheGlace.push(x)
}
if( ( x % 3 == 0 ) && ( x % 5 == 0 )&& ( x % 7 == 0 ) ){
output.mojito.push(x)
}
}
return output;
}
var result = mojitor(1, 110);
console.log('Menthe: ' + result.menthe); //"Menthe"
console.log('Glace: ' + result.glace); //"Glace"
console.log('Rhum: ' + result.rhum); //"Rhum"
console.log('MentheGlace: ' + result.mentheGlace); //"MentheGlace"
console.log('Mojito: ' + result.mojito); //"Mojito"
I think you want something like this:
function mojitor(startOfCount, endOfCount) {
var items = [];
for (var x=startOfCount; x <= endOfCount; x++){
if( ( x % 3 == 0 ) && ( x % 5 == 0 )&& ( x % 7 == 0 ) ){
items.push("Mojito");
}
else if( ( x % 3 == 0 ) && ( x % 5 == 0 ) ){
items.push("MentheGlace");
}
else if( ( x % 3 == 0 ) && ( x % 7 == 0 ) ){
items.push("MentheRum");
}
else if( x % 3 == 0 ){
items.push("Menthe");
}
else if( x % 5 == 0 ){
items.push("Glace");
}
else if( x % 7 == 0 ){
items.push("Rhum");
}
else {
items.push(x);
}
}
return items;
}
var numbers = mojitor(1,110);
var line = "";
var j = 0;
for(i = 0; i < numbers.length; i++) {
line += numbers[i] + " ";
j++;
if(j === 11){
console.log(line);
line = "";
j = 0;
}
}
if(line != ""){
console.log(line); //prints the remaining
}

I want to output the number that contain "7" as the LUCKY NUMBER and the number that can be divided evenly by 7 as LUCKY NUMBER

I tried this code. It works for number that can be divided evenly by 7 as Lucky Numbers. But it doesn't work for some numbers. I can't find where I made a mistake.
for(i=1; i<=1000; i++)
{
var x = 7;
var y = i;
var z = y % x ;
if ( z == 0 )
{
document.write("Lucky Number" +"<br>");
i++;
}
var number = i;
var num = number.toString();
var matchedposition = num.search(["7"]);
if ( matchedposition == true )
{
document.write("Lucky Number" +"<br>");
i++;
}
document.write(i+"<br>");
}
You can try like this.
for(i=1; i<=1000; i++)
{
var z = i % 7 ;
if (( z == 0 ) &&( i.toString().search(7)))
{
console.log("Lucky Number"+ i +"<br>");
}
}
So here in this code i did two things
1) I am not incrementing 'i' after every If . Because if you increment i after every IF condition then you will not check all numbers from 1 to 1000 . So whenever yours condition will be true u increase i by one and then again i will increment by loop. so you are escaping one number to be checked.
2) I combine both condition together to reduce code.
I hope it will help you
Try this not sure:
for(i=1; i<=1000; i++)
{
var x = 7;
var y = i;
var z = y % x ;
var isFound=false;
if ( z == 0 )
{
document.write("Lucky Number" +"<br>");
isFound =true;
}
var number = i;
var num = number.toString();
var matchedposition = num.search("7");
if ( matchedposition > 0 && !isFound)
{
document.write("Lucky Number" +"<br>");
}
document.write(i+"<br>");
}

Categories

Resources