Logic not firing correctly in javascript [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Edit: I've solved the problem by changing the 2d array to a simple array and using arithmetic and logic to get coordinates, see below.
I have an algorithm that adds 50 to a two dimensional array when the coordinates have an odd-odd pairing (e.g. [1][1], [3][5], etc). The only problem is, it isn't working. According to the browser console it never fires. This is what it is:
if(((col & 1) & row) == 1) { y+= 50; }
A fuller example of my code is here:
//goes through the board's array and calls
//drawChecker to print each found piece
function drawPieces() {
var row = 0;
var col= 0;
for(row = 0; row < 1; row++) {
var y = row * 100;
console.log("row " + row + " set x to " + x);
var flag = (row & 1);
for(col = 0; col < 8; col++) {
var x = col*50;
console.log("column " + col + " set y to " + y);
console.log("y was " + y);
if(((col & 1) & row) == 1) { y+= 50; }
console.log("Now y is " + y);
console.log("Done setting " + row + "," + col);
console.log("Final coordinates are " + x + "," + y);
drawChecker(x,y,square[row][col]);
}
}
}
The array was set up with the following code:
var square = new Array(4);
for(i = 0; i < 4; i++) { square[i] = new Array(8); }

You can not test the algorithms just on row 0.
function drawPieces() {
square.forEach(function (a, i) {
a.forEach(function (b, j) {
if (i & j & 1) {
square[i][j] = '#';
}
});
});
}
var square = Array.apply(null, { length: 4 }).map(function () { return Array.apply(null, { length: 8 }).map(function () { return '.'; }); });
drawPieces();
document.write('<pre>'+square.map(function (a) { return a.join(''); }).join('\n')+'</pre>');

So, I ended up switching my 2d array of 4x8 to a 1d array of 32 elements, and I changed the function to just this:
function drawPieces() {
for(i = 0; i < 32; i++) {
var value = square[i];
var x = (i % 4) * 100; //i%4 gets its column, 0-3
var y = Math.floor(i / 4) * 50; //i / 4 gets the row 0-3
if((i & 4) != 4) { x += 50; } //offset on even-numbered rows
drawChecker(x,y,value);
console.log(i + " has coordinates " + x + "," + y);
}
}

Related

How do I write a function to multiple numbers from 1-10? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
var a = 7;
var b;
for (var i = 1; i <= 10 ; i++) {
b = a * i;
document.write(" " +a+ "*", + b + "<br>");
}
This works however it has to be a loop, not code for one specific number so I need to write it so it goes for all numbers 1 through 10.
I'm using http://js.do which we have to use.
You need to have two loops - one nested inside the other - both going from 1 to 10.
Something like:
for (let i = 1; i <= 10; i++) {
for (let j = 1; j <= 10; j++) {
let s = i * j;
document.write(i + "*" + j + "=" + s + "<br>");
}
}
Or, to allow the user to enter a number of their choice:
let a = prompt("Enter a number: ");
if (a) {
for (let i = 1; i <= 10; i++) {
let b = i * a;
document.write(a + "*" + i + "=" + b + "<br>");
}
}
var a;
var b;
for (var a = 1; a <= 10 ; a++) { // loop the a number 1 to 10
for (var i = 1; i <= 10 ; i++) {
b = a * i;
document.write(" " +a+ "*", + b + "<br>");
}
}

Storing concatenated numbers as string in a 2D array. Result remains "undefined"

I am a novice programmer. I am creating a 2D battleship game. I have successfully randomised the spawn points of said ships and I have an idea on how to proceed next.
I am using a 2D ship array to store the ships coordinates and the last address in each row would be its status: 0=floats, 1=single hit, 2=two hits and so on. But I ran into a problem and need help. I seem to be unable to store anything to said array. as you can see in my code board[][] works but ship[][] doesn't.
I am having an error in this segment:
var z = 1; //set to 1 for debugging purposes. z is supposed to be the length of each battleship.
ship[c][z] = 1; // for debug only. line to be removed during final iteration
console.log("c z = " + c + " " + z);
console.log("ship c z = " + ship[c][z]);
if(c == 0)
{
for(z = 0; z < 4; z++)// this for loop is for battlehsip. more for loops to be added one for each ship type.
{
console.log("a b = " + a + " " + b);
ship[c][z] = ("" + a + b);
console.log("sketchy array " + ship[c][z]);
a++;
console.log("Z = " + z);
}
}
and this is the console output(trimmed):
Loop start
i = 0
rn = 7
rn = 0
x y =7 0
board x y = 1
Board 7 0
C = 0
rng = 0
VH = 0
c z = 0 1
ship c z = undefined
a b = 7 0
sketchy array undefined
Z = 0
a b = 8 0
sketchy array undefined
Z = 1
a b = 9 0
sketchy array undefined
Z = 2
a b = 10 0
sketchy array undefined
Z = 3
This is my full code. Maybe this will clear out what I am trying to achieve. feel free to correct my existing logic.
var vhposition = 0;
var x = 0;
var y = 0;
var guess;
var guesses
var fsunk;
var userchoices = [];
var board = [];
var ship = []; //ship array. converted to 2D array to hold ship status and X
Y coordinates.
function createboard()
{
for (var i = 0; i < 10; i++)
{
board[i] = [];
}
return board;
}
function fleet()
{
for(var i = 0; i < 10; i ++)
ship[i] = [];
}
function rng() //Generates Random Numbers
{
var rn = Math.floor(Math.random() * 10);
console.log("rn = " + rn);
return rn;
}
function rngesus()
{
var rng = Math.floor(Math.random() * 2);
console.log("rng = " + rng);
return rng;
}
function play() // onclick function
{
console.log("game start");
bhit = 0; //battleship hit counter set to zero
c1hit = 0; //cruiser hit counter set to zero
//console.log("sunk array = " + sunk[0] + " " + sunk[1]);
fsunk = 0; //fleet status
createboard();
fleet();
var i = 0;
while(i < 10) // generates random points for ship spawn
{
ship[i] = 0; //overkill to ensure no residual data
console.log("Loop start"); //makes reading console easier
console.log("i = " + i);
spawn(i); //i acts as the ship id that is being worked on
i++;
}
//game();
}
function spawn(j) // ship positon generated, i think
{
x = rng();
y = rng();
console.log("x y =" + x +" "+ y);
board[x][y] = 1;
console.log(" board x y = " + board[x][y]);
position(x, y, j);
}
function position(a,b,c)
{
console.log("Board " + a + " " + b);
console.log("C = " + c);
vhposition = rngesus(); //returns 0 or 1 for ship orienetation. maybe later will add 4 way
console.log("VH = " + vhposition);
var z = 1; //set to 1 for debugging purposes. z is supposed to be the length of each battleship.
ship[c][z] = 1; // for debug only. line to be removed during final iteration
console.log("c z = " + c + " " + z);
console.log("ship c z = " + ship[c][z]);
if(c == 0)
{
for(z = 0; z < 4; z++)// this for loop is for battleship. more for loops to be added one for each ship type.
{
console.log("a b = " + a + " " + b);
ship[c][z] = ("" + a + b);
console.log("sketchy array " + ship[c][z]);
a++;
console.log("Z = " + z);
}
}
}
//function game()
{
//to be continued...
}
function userinput()// this works fine
{
guess = prompt("Enter the grid coordinates. Do not use space. X-coordinates 0-6, Y-coordinates 0-6.");
console.log("users input = " + guess);
while(guess < 0 || guess > 99 || userchoices.includes(guess)) //checks user input for repeated strikes or out of range. Suggest better way if possible. this is just bad code
{
alert("You have entered an invalid coordinate.");
guess = prompt("Try Again!");
}
guesses++; //increments no of guessess
userchoices.push(guess); //add users guess to array
return guess;
}
Sorry for the long question/post.
Thank you.
function position is called from spawn, spawn is called from play and in play you assign 0 to ship[i] ? So the ship is no longer a 2D array.

Javascript snake pattern grid

I am trying to draw a grid on screen numbered in a snake pattern in Javascript, I have a working grid but it follows the pattern of
12345
67890
And what I need is
12345
09876
I have seen this done with modulo and have tried to implement but im having trouble getting the right number sequence.
Here is my function
function createGrid(length, height) {
var ledNum = 0;
for (var rows = 0; rows < height; rows++) {
for (var columns = 0; columns < length; columns++) {
var backwards = ledNum + columns;
if (rows % 2 == 0 || rows != 0) {
$("#container").append("<div class='grid' id='" + ledNum + "'>" + //HERE IS MY PROBLEM+"</div>");
}
else if (!rows % 2 == 0) {
$("#container").append("<div class='grid' id='" + ledNum + "'>" + ledNum + "</div>");
}
ledNum++;
};
};
$(".grid").width(960 / length);
$(".grid").height(960 / height);
};
How do I work out the true modulo case to show the numbers correctly in snake pattern?
I am not well versed with 2d arrays but perhaps that might be a better way?
The best way I can think of is to use an object with arrays and exploit its inbuilt functions to ease your job...for example
function createGrid(length,height) {
var lednum = 0;
var grid = [];
for (var row = 0; row < height; row++) {
grid[row] = [];
for (var col = 0; col < length; col++) {
if ((row % 2) === 0) {
grid[row].push(lednum);
} else {
grid[row].unshift(lednum);
}
lednum++;
}
}
return grid;
}
console.log(createGrid(10, 10))
Then you can just print out above grid
Update : How to print above data. You could simply use two for loops.
var length = 10;
var height = 15;
var brNode = document.createElement('br');
var grid = createGrid(length, height));
for (var row = 0; row < height; row++) {
var rowPrint = "";
for (var col = 0; col < length; col++) {
rowPrint += String(grid[row][col]) + " ";
}
var rowNode = document.createTextNode(rowPrint)
$("#container").appendChild(rowNode);
$("#container").appendChild(brNode);
}
Note that this will create rows of textNode broken by <br/> tags. if you want it formatted in some other way..well you have the preformatted data..all you need to do is traverse through it and print it how you want.
This general idea seems to work...
// Input variables
var data = 'abcdefghijklmnopqrstuvwxyz';
var width = 5;
// The actual algorithm.
var rows = Math.ceil(data.length / width);
for (var y = 0; y < rows; y++) {
var rowText = "";
for (var x = 0; x < width; x++) {
// Basically, for every other row (y % 2 == 1),
// we count backwards within the row, as it were, while still
// outputting forward.
var offset = y * width + (y % 2 == 1 ? width - 1 - x : x);
rowText += data[offset] || " ";
}
console.log(rowText);
}
$ node so51356871.js
abcde
jihgf
klmno
tsrqp
uvwxy
z
As I mentioned in comments, there is a lot wrong with the boolean logic in your code:
The first if condition always evaluates to true, except in the first iteration
The second if condition is therefor only evaluated once, and it will be false.
I would split the functionality in two parts:
Create a 2D array with the numbers in "snake" sequence
Create the DOM elements from such a matrix, using some CSS to control the line breaks
function createSnake(width, height) {
const numbers = [...Array(width*height).keys()];
return Array.from({length:height}, (_, row) =>
numbers.splice(0, width)[row % 2 ? "reverse" : "slice"]()); // 2D array
}
function createGrid(matrix) {
$("#grid").empty().append(
[].concat(...matrix.map(row => row.map((val,i) =>
$("<div>").addClass("grid").toggleClass("newline", !i).text(val))))
);
}
// Demo generating a 3 x 3 grid
createGrid(createSnake(3,3));
.grid {
float: left;
padding: 3px;
}
.newline {
clear:left
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="grid"></div>

How to console.log multiplication table without repeating x*y=z, y*x=z

How to make multiplication table without repeating reverse calculations like this xy=z yx=z? I tried to use if else with !== operator but it shows nothing. My code:
for (var x = 1; x <= 10; x++) {
for (var i = 1; i <= 10; i++) {
var result = x * i;
if (result !== result){
console.log(x + ' * ' + i + ' = ' + result);
}
else {
}
}
}
Pretty simple :
for (var x = 1; x <= 10; x++) {
for (var i = x; i <= 10; i++) {
var result = x * i;
console.log(x + ' * ' + i + ' = ' + result);
}
}
Replace i = 1 by i = x on the second line so that it starts later and ignores all the previous calculations it already did.
E.G.: When you're calculating the table 3, you can start with 3*3 as you already already did 3*1 (1*3) with table 1 and 3*2 (2*3) with table 2
You could keep track of the calculations you've already done in an hash table. If it's already in the table - skip that calculation. Something like this:
var doneCalculations = {};
for (var x = 1; x <= 10; x++) {
for (var i = 1; i <= 10; i++) {;
if (doneCalculations[i+'x'+x]) continue;
doneCalculations[x+'x'+i] = true;
var result = x * i;
console.log(x + ' * ' + i + ' = ' + result);
}
}
start the second loop with first loop variable
for (var x = 1; x <= 10; x++) {
for (var i = x; i <= 10; i++) {
var result = x * i;
console.log(x + ' * ' + i + ' = ' + result);
}
}
You want to print full multiplication table for each values of x, 1 to 10. Use memoization to avoid recalculation
In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
var doneCalculations = {};
var calculations = {};
var doneCalculations = {};
for (var x = 1; x <= 10; x++) {
for (var i = 1; i <= 10; i++) {;
if (doneCalculations[i+'x'+x]) {
result = calculations[i+'x'+x]
}
else {
doneCalculations[x+'x'+i] = true;
var result = x * i;
calculations[x+'x'+i] = result;
}
console.log(x + ' * ' + i + ' = ' + result);
}
}
console.log(calculations)

How to add a variable in javascript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
var count=0 ;
for(var x=0; x<data_len; x++)
{
count = count + num_arr[x];
}
// alert(count);
If count = 352 I want to add 3+5+2 which is 10 and then 1+0 which is 1.
function sumParts(x) {
var sumX = 0;
var strX = x.toString();
var arrX = strX.split("");
for (a = 0; a < arrX.length; a++) {
sumX += parseInt(arrX[a], 10);
};
return sumX;
}
y = sumParts(count);
z = sumParts(y);
// y = 10; (3 + 5 + 2)
// z = 1; (1 + 0)
And, I believe (untested), if the return was changed to return sumParts(sumX), it would continue until it was a single digit integer.
You have an array of strings, not numbers. You can convert them to numbers with:
count = count + +num_arr[x];
The second + is the unary plus operator, and will cast num_arr[x] to a number.
If your numbers are all integers, you can use:
count = count + parseInt(num_arr[x], 10);
or (if you have floats):
count = count + parseFloat(num_arr[x]);
Convert count into a string :
var count = 352;
count += ''; // makes a string : "352"
while (count.length > 1) {
count = Function('return ' + count.split('').join('+') + ';')() + '';
}
This part :
Function('return ' + count.split('').join('+') + ';')
Gives successively :
function () { return 3+5+2; }
function () { return 1+0; }

Categories