I have created a table that displays all prime numbers from 2-1013 but it is displaying from the bottom right to the top left and I would like it to display from the top left to the bottom right. How would I achieve this?
<!DOCTYPE HTML Public>
<html>
<head>
<title>Prime Numbers</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>
<body onload='CalcPrime()'>
<script type='text/javascript'>
function CalcPrime() {
var setIt = 0;
var count = 0;
var num = 3;
var primeArray = new Array();
primeArray.unshift(2)
while (count < 169) {
setIt = 0;
var i = 2
while (i < num + 1) {
if (num % i == 0) {
setIt = setIt + 1;
}
i = i + 1
}
if (setIt < 2) {
primeArray.unshift(num);
count = count + 1;
}
num = num + 1;
}
var a;
document.write("<table cols='10' border='1'>");
document.write("<tr><th colspan=10 border='1'>Prime Numbers 2-1013</th></tr>");
for (var it = 0; it < 161; it = it + 10) {
document.write("<tr>");
for (var colm = 0; colm < 10; colm++) {
a = it + colm;
document.write("<td style='border:1px line;padding:10px;'>" + primeArray[a] + "</td>");
}
}
}
</script>
</body>
</html>
If you push your values onto the array instead of unshifting them, that will put them at the end of your array instead of the start. Which would do exactly what you want.
This will get you close. Basically, instead if incrementing your indices, decrement them. Instead of starting with 0, start with the final number and go down to zero. In other words, reverse your loop.
for (var it = 161; it >= 0; it -= 10) {
document.write("<tr>");
for (var colm = 10; colm >= 0; colm--) {
a = it + colm;
document.write("<td style='border:1px line;padding:10px;'>" + primeArray[a] + "</td>");
}
}
It's not perfect yet, but this will get you close for now. I'll edit after I tweak it a bit.
Before writing the table, reverse the primeArray variable by adding:
primeArray = primeArray.reverse();
Related
I tried to a do Multiplication Table in JS and I want to print in <p> element out (Use DOM and not use document.write method).
I tried to use " " or "\t" to align column , but when number is double digit (from x3 column) , it got typographic issue.
Does it any ways could solve this problem?
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
for (var j = 1; j <= 9; j++) {
s = s + j + "*" + i + " = " + (i * j) + " ";
}
s = s + "<br>";
}
p1.innerHTML = s;
<pre id="printout"></pre>
Instead of printing table column wise, print row wise.
And wrap your each table in a div, so that aligning them becomes easy.
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
s = s + "<div>";
for (var j = 1; j <= 9; j++) {
s = s + i + "*" + j + " = " + (i*j) + "<Br/>" ;
}
s = s + "</div>";
}
p1.innerHTML = s;
Little bit CSS
#printout {
display:flex;
flex-wrap:wrap;
}
#printout div {
padding:10px;
min-width:100px
}
https://jsfiddle.net/wkg92rud/
Inspiring from #Andreas suggestion, Using <table>
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
let row = document.createElement("tr");
for (var j = 1; j <= 9; j++) {
let col = document.createElement("td");
col.innerText = j + "*" + i + " = " + (i * j);
row.append(col);
}
p1.append(row);
}
td {
padding: 2px 2px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<table id="printout"></table>
</body>
</html>
#Dalvik method is the correct way, styling and alignment should be done through CSS.
However, in other environments like command line, or if you are doing this as an exercise to learn JS you can use string padding, here is an example:
const p1 = document.getElementById("printout");
const LONGEST_ENTRY = 9; // Longest string you will have is 9 characters long
const entries = []
for (let i = 1; i <= 9; i++) {
for (let j = 1; j <= 9; j++) {
const entry = `${j}*${i} = ${(i*j)}`.padEnd(LONGEST_ENTRY, " ") ; // use string interpolation, then pad the string with spaces until the length of LONGEST_ENTRY is reached
entries.push(entry); // store all the entries in an array
}
entries.push("<br/>"); // add a line break at the end of each row
}
p1.innerHTML = entries.join(''); // join all the elements
Here is a jsfiddle as an example
I can get my array to work and display perfectly as a 2d array but the second I attempt to add another element it never shows it always stays undefined. I tried many different methods, in this version I attempted to duplicate the way that I add the 2d elements.
Ultimately I want to save data to the array to make the walls "#" that are displaying correctly to have further data stating "solid" and then I would be able to test for that before moving the "#"
I actually have a working version of this but using a second array which would get very cumbersome if I add further data.
Also as it is right now I am surprised the entire map is not getting overwritten with the letter k
function gameloop(){
var mainArray = [];
var mapSizeX = 32;
var mapSizeY = 128;
var arrayDepth = 10;
var idPos = {x:0, y:0};
function initMap(mainArray, mapSizeX, mapSizeY){
for (var i = 0; i < mapSizeX; i++) {
mainArray.push([0])
for (var j = 0; j < mapSizeY; j++) {
mainArray[i][j] = ".";
if(j == 0){mainArray[i][j] = "#";}
if(j == mapSizeY-1){mainArray[i][j] = "#";}
if(i == 0){mainArray[i][j] = "#";}
if(i == mapSizeX-1){mainArray[i][j] = "#";}
for (var k = 0; k < arrayDepth; k++) {
mainArray[i][j][k] = "k";
}
}
}
}
function nl(){GameScreen.innerText += "\n";}
function render() {GameScreen.innerText = mainArray.map(arr => arr.join("")).join("\n");
nl(); nl();}
function reposition(xChange,yChange,strA){
//mainArray[idPos.x][idPos.y] = ".";
//idPos.x = idPos.x + xChange;
//idPos.y = idPos.y + yChange;
//mainArray[idPos.x][idPos.y] = "#";
if(mainArray[idPos.x+xChange][idPos.y+yChange][1] === "Solid"){GameLog.innerText ="You can not travel in that direction"}
else{
mainArray[idPos.x][idPos.y] = ".";
idPos.x = idPos.x + xChange;
idPos.y = idPos.y + yChange;
mainArray[idPos.x][idPos.y] = "#";
GameLog.innerText = "You take a step to the " + strA
alert(mainArray[0][0][1]);
}
render();
}
//Startup
initMap(mainArray, mapSizeX, mapSizeY);
idPos.x = mapSizeX/2; idPos.y = mapSizeY/2;
mainArray[idPos.x][idPos.y] = "#";
//First Render
render();
document.addEventListener('keydown', function(event) {
if(event.keyCode === 38 ){reposition(-1,0,"North");}
if(event.keyCode === 40 ){reposition(1,0,"South");}
if(event.keyCode === 37 ){reposition(0,-1,"West");}
if(event.keyCode === 39 ){reposition(0,1,"East");}
//alert(event.keyCode);
});
}
gameloop();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello</title>
</head>
<body>
<br>
<p style="color:#7d7d7d;font-family:Lucida Console;">Dungeon Valley.<br>
<font style="color:#ABABAB;font-family:Lucida Console;font-size:0.5em";>
Taming the Borderlands.<br>
v0.005 By heromedel. </P></font>
<P>
<section id="GameScreen" style="color:#000000;font-family:Lucida Console;"></section>
<P>
<section id="GameLog" style="color:#000000;font-family:Lucida Console;">Arrow Keys to move.<br></section>
<script src="main.js"></script>
</body>
</html>
If I'm understanding what you're trying to do, this is wrong:
for (var k = 0; k < arrayDepth; k++) {
mainArray[i][j][k] = "k";
}
mainArray is supposed to be a 2d array of strings, right? So why are you using var k to add a 3rd dimension to it? Unless you're trying to append to the string? In Javascript you append to strings with +, not with [].
By the way, this is also wrong:
mainArray.push([0])
You want to push an empty array [], not an array with a 0 in it [0].
How can display a new random number with each new line element?
Currently, my HTML is displaying
The number is 4
The number is 4
The number is 4
The number is 4
The number is 4
I would like it to show a random number with each line.
The number is 4
The number is 1
The number is 9
The number is 3
The number is 11
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="info">
</div>
<script src="main.js"></script>
</body>
</html>
var divInfo = document.getElementById('info');
var quote = document.createElement('p');
var randNum = Math.floor(Math.random() * 11) + 1;
var messNum = '';
for (var i = 0; i < 5; i++) {
messNum = "The number is " + randNum + "</br>";
divInfo.appendChild(quote);
quote.innerHTML += messNum;
}
You are assigning randNum once outside of your for loop.
Put randNum = Math.floor(Math.random() * 11) + 1; as your first line inside the for loop, that way it changes with every iteration
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="info">
</div>
<script src="main.js"></script>
</body>
</html>
var divInfo = document.getElementById('info');
var quote = document.createElement('p');
var messNum = '';
for (var i = 0; i < 5; i++) {
var randNum = Math.floor(Math.random() * 11) + 1;
messNum = "The number is " + randNum + "</br>";
divInfo.appendChild(quote);
quote.innerHTML += messNum;
}
You have to calculate the random number inside the for loop. So for each line it will get a different number like this:
for (var i = 0; i < 5; i++) {
// calculate random here
var randNum = Math.floor(Math.random() * 11) + 1;
messNum = "The number is " + randNum + "</br>";
// ...
You have a good start. Just move your call to generate the random number inside your for-loop. Try this:
<script>
var divInfo = document.getElementById('info');
var quote = document.createElement('p');
var randNum;
var messNum = '';
for (var i = 0; i < 5; i++) {
randNum = Math.floor(Math.random() * 11) + 1;
messNum = "The number is " + randNum + "</br>";
divInfo.appendChild(quote);
quote.innerHTML += messNum;
}
</script>
Here's a jsfiddle for it.
How to ensure i have a dynamic increment of Alphabets in a new cell on left side, next to each cell in a row which is dynamically created based on the option chosen in Select. This newly generated alphabet will be considered as bullet points/serial number for that particular row's text box.
jsfiddle
js code
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
html
<select id="Number_of_position">
</select> <table id="Positions_names">
</table>
This is essentially a base26 question, you can search for an implementation of this in javascript pretty easily - How to create a function that converts a Number to a Bijective Hexavigesimal?
alpha = "abcdefghijklmnopqrstuvwxyz";
function hex(a) {
// First figure out how many digits there are.
a += 1; // This line is funky
var c = 0;
var x = 1;
while (a >= x) {
c++;
a -= x;
x *= 26;
}
// Now you can do normal base conversion.
var s = "";
for (var i = 0; i < c; i++) {
s = alpha.charAt(a % 26) + s;
a = Math.floor(a/26);
}
return s;
}
So you can do
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td>" + hex(i) + "</td><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
Heres the example http://jsfiddle.net/v2ksyy7L/6/
And if you want it to be uppercase just do
hex(i).toUpperCase();
Also - this will work up to any number of rows that javascript can handle
if i have understood you correctly, that's maybe what you want:
http://jsfiddle.net/v2ksyy7L/3/
I have added an array for the alphabet:
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
and then added the output to your "render" loop:
rows += "<tr><td>" + alphabet[i] + " <input type='text'></td></tr>";
The code below came as an included file with a beginner puzzle app tutorial I'm working through. The code works, however now that I've completed the tutorial, I'm trying to read through the files that came preloaded which were not explained.
I'm really tripped up over the "spacecount" variable, and what exactly it's doing. Can anyone comment each line in plain english, so that I can better understand how exactly the code below is populating the rowCount array. Thank you so much.
var totalRows = puzzle.length;
var totalCols = puzzle[0].length;
/* Loop through the rows to create the rowCount array
containing the totals for each row in the puzzle */
var rowCount = [];
for (var i = 0; i < totalRows; i++) {
rowCount[i]="";
spaceCount = 0;
for (var j = 0; j < totalCols; j++) {
if (puzzle[i][j] == "#") {
spaceCount++;
if (j == totalCols-1) rowCount[i] += spaceCount + " ";
} else {
if (spaceCount > 0) {
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}
}
}
Here's a slightly more legible version:
var totalRows = puzzle.length;
var totalCols = puzzle[0].length;
/* Loop through the rows to create the rowCount array
containing the totals for each row in the puzzle */
var rowCount = [];
for (var i = 0; i < totalRows; i++) {
rowCount[i] = "";
spaceCount = 0;
for (var j = 0; j < totalCols; j++) {
if (puzzle[i][j] == "#") {
spaceCount++;
if (j == totalCols - 1) {
rowCount[i] += spaceCount + " ";
}
} else if (spaceCount > 0) {
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}
}
}
The confusing parts are probably the if blocks in the middle.
if (puzzle[i][j] == "#") { // If a puzzle piece is `#` (a space?)
spaceCount++; // Increment the spaceCount by 1.
if (j == totalCols - 1) { // Only if we are on the last column, add the text
// to the row.
rowCount[i] += spaceCount + " ";
}
} else if (spaceCount > 0) { // If the current piece isn't a `#` but
// spaces have already been counted,
// add them to the row's text and reset `spaceCount`
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}
From what I can tell, this code counts the number of consecutive pound signs and appends this text to each row.