I have made this code, but only works for the right half of the diamond, how do I make the full diamond? I need to use nested loops
function myDiamond(){
let row, star;
let toPrint = "";
let rowCount = +prompt("Enter a number to make a diamond");
for (row = 1; row <= rowCount; row++){
for (star = 1; star <= row; star++){
if (star == 1 || star == row){
toPrint +="*";
} else {
toPrint += " ";
}
}
toPrint += "<br>";
}
document.getElementById("figure").innerHTML = toPrint;
for (row = rowCount; row >= 1; row--){
for (star = 1; star <= row; star++){
if (star == 1 || star == row){
toPrint +="*";
} else {
toPrint += " ";
}
toPrint += "<br>";
}
document.getElementById("figure").innerHTML = toPrint;
}
}
Is this what you're trying to do:
function createDimondShape(size) {
var stuff = "";
for (var i = 1; i <= size; i++) {
for (var s = size - 1; s >= i; s--) {
stuff += (" ");
}
for (var j = 1; j <= i; j++) {
stuff += ("* ")
}
stuff += "\n";
}
if (i == size + 1) {
for (var i = 1; i <= size - 1; i++) {
for (var s = 1; s <= i; s++) {
stuff += (" ");
}
for (j = i; j <= size - 1; j++) {
stuff += ("* ");
}
stuff += "\n";
}
}
document.getElementById("figure").innerHTML = stuff;
}
createDimondShape(5);
<pre id="figure"></pre>
Couple of trials here:
function createDimondShape(a, size) {
var stuff = "";
for (var i = 1; i <= size; i++) {
for (var s = size - 1; s >= i; s--) {
stuff += (" ");
}
for (var j = 1; j <= i; j++) {
stuff += ("* ")
}
stuff += "\n";
}
if (i == size + 1) {
for (var i = 1; i <= size - 1; i++) {
for (var s = 1; s <= i; s++) {
stuff += (" ");
}
for (j = i; j <= size - 1; j++) {
stuff += ("* ");
}
stuff += "\n";
}
}
document.getElementById("figure" + a).innerHTML += stuff;
}
createDimondShape(1, 3);
createDimondShape(2, 7);
.f {
display: flex;
flex-direction: row;
}
.f pre {
width: 45%;
}
<div class="f">
<pre id="figure1"></pre>
<pre id="figure2"></pre>
</div>
Preview
With prompt, as asked in the comments:
function createDimondShape(size) {
var stuff = "";
for (var i = 1; i <= size; i++) {
for (var s = size - 1; s >= i; s--) {
stuff += (" ");
}
for (var j = 1; j <= i; j++) {
stuff += ("* ")
}
stuff += "\n";
}
if (i == size + 1) {
for (var i = 1; i <= size - 1; i++) {
for (var s = 1; s <= i; s++) {
stuff += (" ");
}
for (j = i; j <= size - 1; j++) {
stuff += ("* ");
}
stuff += "\n";
}
}
document.getElementById("figure").innerHTML = stuff;
}
createDimondShape(+prompt("Enter a number..."));
<pre id="figure"></pre>
you can do that
document.querySelectorAll('input[type=range]').forEach(r=>r.oninput=_=>r.closest('label').dataset.val=r.value)
btDiamond.onclick=_=>
{
const szD = szDiam.valueAsNumber
oneDiamond.textContent = ''
for(let sp=szD;sp--;)
oneDiamond.textContent += ' '.repeat(sp) + '/'.repeat(szD-sp) + '\\'.repeat(szD-sp) + '\n'
for(let sp=0;sp<szD;sp++)
oneDiamond.textContent += ' '.repeat(sp) + '\\'.repeat(szD-sp) + '/'.repeat(szD-sp) + '\n'
}
label, pre {
margin : 0.5em 1.2em;
}
label input {
vertical-align : middle;
width : 300px;
}
label::after {
display: inline-block;
content : attr(data-val);
width : 2em;
}
<h4>shine bright like a diamond</h4>
<label data-val="6">
size :
<input type="range" id="szDiam" min="1" max="20" value="6">
</label>
<button id="btDiamond"> draw !</button>
<hr>
<pre id="oneDiamond"> your diamond will go here </pre>
Related
I am trying to build a multiplication table and display the results, but need to put the x in the top left corner, for some reason it is showing up on the bottom right, what am I doing wrong?
document.write("<table><tbody>");
var blank = "x";
var cols = 0;
var rows = 0;
// ca
for (let rows = 0; rows <= 10; rows++) {
document.write('<tr>');
for (let cols = 0; cols <= 10; cols++)
document.write('<td>' + rows + ',' + cols + '</td>')
}
if (rows === 0 && cols === 0) {
document.write('<td>' + blank + '</td>')
}
"What am I doing wrong?" A lot.
You should think about what you are trying to do first, before going at it.
Your html table is ill-formed, you don't even close the <tr> tags.
for (let row = 0; row <= 10; row++) {
document.write('<tr>');
for (let col = 0; col <= 10; col++) {
if (row == 0 && col == 0) {
document.write('<td>x</td>');
}
else if (row == 0) {
document.write('<td>' + col + '</td>');
}
else if (col == 0) {
document.write('<td>' + row + '</td>');
}
else {
document.write('<td>' + row * col + '</td>');
}
}
document.write('</tr>');
}
Try it here.
The main goal to let player A pick vertical and player B to pick horizontal.
Please run the snippet code to understand my question better!, thanks a lot
I have unique cell with Symbol S and color red, however if i click any cell, it disappears and normal numbers replace it. How i can force the unique Cell to stay and not disappear when I click any cells in my table?
var isCol = 0;
var board = [];
for (r = 0; r < 7; r++) {
var line = [];
for (c = 0; c < 7; c++) {
line.push(RandomGenerator(50, 500));
}
board.push(line);
}
function prs(c, r) {
showTable(c, r);
isCol = (isCol + 1) % 2;
}
function toColor(col, row, chosen_col, chosen_row) {
var ret = false;
switch (isCol) {
case 0:
if (row == chosen_row) {
ret = true;
}
break;
case 1:
if (col == chosen_col) {
ret = true;
}
break;
}
return ret;
}
function showTable(chosen_col, chosen_row) {
var str = "";
str += "<table border=1>";
for (row = 0; row < 7; row++) {
str += "<tr>";
for (col = 0; col < 7; col++) {
str += "<td onclick='prs(" + col + "," + row + ")'";
if (toColor(col, row, chosen_col, chosen_row)) {
str += " class='grn' ";
}
str += ">";
str += board[row][col];
str += "</td>";
}
str += "</tr>";
}
str += "</table>";
document.getElementById("ff").innerHTML = str;
}
function RandomGenerator(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
showTable(-1);
var getUnique = function(){
var tdElements = document.querySelectorAll('#ff td');
tdElements[
RandomGenerator(0, tdElements.length)
].classList.add('uniqueCell');
// update the text of the cell using the class
document.querySelector('.uniqueCell').textContent = 'S';
};
getUnique();
td{
border:2px solid black;
width:10px;
height:10px;
}
td:hover{background-color:lightgreen;}
.grn{
background-color:green;
color:white;
}
.uniqueCell {
background-color: tomato;
text-align: center;
}
<div id="ff"></div>
added
document.querySelectorAll("#ff td")[uniqueCell].innerHTML='S';
document.querySelectorAll("#ff td")[uniqueCell].className ='uniqueCell';
uniqueCell is the random td number
var isCol = 0;
var board = [];
for (r = 0; r < 7; r++) {
var line = [];
for (c = 0; c < 7; c++) {
line.push(RandomGenerator(50, 500));
}
board.push(line);
}
function prs(c, r) {
showTable(c, r);
isCol = (isCol + 1) % 2;
document.querySelectorAll("#ff td")[uniqueCell].innerHTML='S';
document.querySelectorAll("#ff td")[uniqueCell].className ='uniqueCell';
}
function toColor(col, row, chosen_col, chosen_row) {
var ret = false;
switch (isCol) {
case 0:
if (row == chosen_row) {
ret = true;
}
break;
case 1:
if (col == chosen_col) {
ret = true;
}
break;
}
return ret;
}
function showTable(chosen_col, chosen_row) {
var str = "";
str += "<table border=1>";
for (row = 0; row < 7; row++) {
str += "<tr>";
for (col = 0; col < 7; col++) {
str += "<td onclick='prs(" + col + "," + row + ")'";
if (toColor(col, row, chosen_col, chosen_row)) {
str += " class='grn' ";
}
str += ">";
str += board[row][col];
str += "</td>";
}
str += "</tr>";
}
str += "</table>";
document.getElementById("ff").innerHTML = str;
}
function RandomGenerator(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
showTable(-1);
var getUnique = function(){
var tdElements = document.querySelectorAll('#ff td');
uniqueCell=RandomGenerator(0, tdElements.length);
tdElements[
uniqueCell
].classList.add('uniqueCell');
// update the text of the cell using the class
document.querySelector('.uniqueCell').textContent = 'S';
};
var uniqueCell;
getUnique();
td{
border:2px solid black;
width:10px;
height:10px;
}
td:hover{background-color:lightgreen;}
.grn{
background-color:green;
color:white;
}
.uniqueCell {
background-color: tomato;
text-align: center;
}
<div id="ff"></div>
Function showTable(...) generates table every time and replaces with innerHtml with new one. getUnique marks cell only at beginnning.
The possible solution, to store var randomCell = RandomGenerator(...) before showTable(-1), and set class uniqueCell in showTable(...)
What I'm trying to do, is get it so when all of the buttons have been turned to black, it displays the h2 text in the 'lightsoff' div. So if any of the buttons aren't black, the text will be hidden.
I'd like to be able to do it by writing a new function that carries out the checking of the background colour.
function toggle(i, j) {
b = document.getElementById("but_" + i + j)
t = b.innerHTML
if (t == "X") {
b.innerHTML = "O";
b.setAttribute("style", "color:red; background-color:yellow")
}
if (t == "O") {
b.innerHTML = "X";
b.setAttribute("style", "color:white; background-color:black")
}
}
function press(i, j) {
toggle(i, j);
if (i > 0) {
toggle(i - 1, j);
}
if (i < 4) {
toggle(i + 1, j);
}
if (j > 0) {
toggle(i, j - 1);
}
if (j < 4) {
toggle(i, j + 1);
}
}
function generateGrid() {
var d = document.getElementById("button-grid");
var table = document.createElement("table");
d.appendChild(table);
for (var i = 0; i < 5; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 5; j++) {
var cell = document.createElement("td");
cell.innerHTML = "<button type=button id=but_" + i + j +
" onclick=\"press(" + i + ',' + j + ")\"" +
" style=\"color:red; background-color:yellow\"" +
">O</button>";
row.appendChild(cell);
}
table.appendChild(row);
}
toggle(2, 2)
}
window.onload = function() {
generateGrid();
};
<center>
<h1>Lights Off Puzzle</h1>
<h3>Click on the buttons until they all turn black!</h3>
<div id="button-grid"></div>
<div id="lightsoff">
<h2>All the lights are out, you win!</h2>
</div>
</center>
Use classes and count
function toggle(i, j) {
b = document.getElementById("but_" + i + j)
t = b.innerHTML
if (t == "X") {
b.innerHTML = "O";
b.className="on"
}
if (t == "O") {
b.innerHTML = "X";
b.className="off"
}
var off = document.querySelectorAll(".off").length === document.querySelectorAll("#button-grid table tr td").length; // are all off
document.getElementById("lightsoff").style.display= off ? "block":"none"; // ternary shorthand for if (something) x=a; else x=b;
}
function press(i, j) {
toggle(i, j);
if (i > 0) {
toggle(i - 1, j);
}
if (i < 4) {
toggle(i + 1, j);
}
if (j > 0) {
toggle(i, j - 1);
}
if (j < 4) {
toggle(i, j + 1);
}
}
function generateGrid() {
var d = document.getElementById("button-grid");
var table = document.createElement("table");
d.appendChild(table);
for (var i = 0; i < 5; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 5; j++) {
var cell = document.createElement("td");
cell.innerHTML = "<button type=button id=but_" + i + j +
" onclick=\"press(" + i + ',' + j + ")\"" +
" class='red'" +
">O</button>";
row.appendChild(cell);
}
table.appendChild(row);
}
toggle(2, 2)
}
window.onload = function() {
generateGrid();
};
.on {color:red; background-color:yellow}
.off {color:white; background-color:black}
#lightsoff { display: none }
<center>
<h1>Lights Off Puzzle</h1>
<h3>Click on the buttons until they all turn black!</h3>
<div id="button-grid"></div>
<div id="lightsoff">
<h2>All the lights are out, you win!</h2>
</div>
</center>
Toggle a class using classList for the state and then look at the number of elements with that class by using querySelectorAll().
function toggle(i, j) {
b = document.getElementById("but_" + i + j)
b.classList.toggle("on")
b.textContent = b.classList.contains("on") ? "O" : "X"
}
function press(i, j) {
toggle(i, j);
if (i > 0) {
toggle(i - 1, j);
}
if (i < 4) {
toggle(i + 1, j);
}
if (j > 0) {
toggle(i, j - 1);
}
if (j < 4) {
toggle(i, j + 1);
}
console.log("Number of on buttons is: ", document.querySelectorAll("button.on").length)
}
function generateGrid() {
var d = document.getElementById("button-grid");
var table = document.createElement("table");
d.appendChild(table);
for (var i = 0; i < 5; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 5; j++) {
var cell = document.createElement("td");
cell.innerHTML = "<button type=button id=but_" + i + j +
" onclick=\"press(" + i + ',' + j + ")\"" +
" class='on' " +
">O</button>";
row.appendChild(cell);
}
table.appendChild(row);
}
toggle(2, 2)
}
window.onload = function() {
generateGrid();
};
td button{
color: #FFF;
background-color: #000;
}
td button.on {
color: red;
background-color: #FFC;
}
<center>
<h1>Lights Off Puzzle</h1>
<h3>Click on the buttons until they all turn black!</h3>
<div id="button-grid"></div>
<div id="lightsoff">
<h2>All the lights are out, you win!</h2>
</div>
</center>
If you really want to do it without using classes than you need to loop over all the cells and see if any of them are the color. Checking color codes can be a pain because not all browsers return the same thing. I would just check the text.
function check()
var btns = document.querySelectorAll("button")
for (var i=0; i<btns.length; i++) {
if (btns[i].textContent === "O") return false
}
return true
}
i would like to set a background color for each number that is a multiple of 3 and 2 how can i do this? i'm not very good at this javascript stuff
HTML:
<div id="mainDiv">
<input type="text" id="myNo" />
<input type="button" id="gridSize" value="Show It" />
</div>
Javascript:
var button = document.getElementById('gridSize');
button.onclick = function(e){
result = document.getElementById('result');
num = parseInt(document.getElementById('myNo').value);
alert(num);
if ( isNaN(num) ){
alert("No Numeric Value!");
}
else{
result.innerHTML = num;
}
var str = "<table border='2'>";
for (row = 0; row < num; row++){
str += "<tr>";
for (col = 0; col < num; col++){
str += "<td>";
var randNum = Math.floor(Math.random() * 100) + 1;
if (randNum % 2){
console.log(randNum + "Red");
}
str += randNum;
str += "</td>";
}
str += "</tr>";
}
str = str + "</table>";
result.innerHTML = str;
}
If you put your td creations into a if else statement you can do it pretty simply like this:
HTML
<div id="mainDiv">
<input type="text" id="myNo" />
<input type="button" id="gridSize" value="Show It" />
</div>
<div id="result"></div>
CSS
.two {
background: red;
}
.three {
background: blue;
}
JS
var button = document.getElementById('gridSize');
button.onclick = function(e) {
result = document.getElementById('result');
num = parseInt(document.getElementById('myNo').value);
alert(num);
if (isNaN(num)) {
alert("No Numeric Value!");
} else {
result.innerHTML = num;
}
var str = "<table border='2'>";
for (row = 0; row < num; row++) {
str += "<tr>";
for (col = 0; col < num; col++) {
var randNum = Math.floor(Math.random() * 100) + 1;
if (randNum % 2 === 0) {
str += '<td class="two">';
} else if (randNum % 3 === 0) {
str += '<td class="three">';
} else {
str += "<td>";
}
str += randNum + "</td>";
}
str += "</tr>";
}
str = str + "</table>";
result.innerHTML = str;
}
jsfiddle here
This is how you check, if its
dividable by 2 and 3:
if(randNum %2===0 && randNum %3===0){
// do some
}
Here is the way you can do that(similar to your code)
var resultTable = document.createElement('table');
var tr = resultTable.insertRow();
tbl.style.border = '1px solid black';
for (row = 0; row < num; row++){
var tr = resultTable.insertRow();
for (col = 0; col < num; col++){
var td = tr.insertCell();
var randNum = Math.floor(Math.random() * 100) + 1;
//for example if you want numbers countable with 2 to be red
if ((randNum % 2) === 0){
td.style.backgroundColor = "red";
}
td.appendChild(document.createTextNode(randNum.toString()));
}
}
result.appendChild(resultTable);
This is my demo.jsp page.for this code i'm getting result in single row but i need to print 5 tables per row,remaining 5 multiplication table in second row,vice-versa.where can i change the code to get expected result.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JavaScript Tables</title>
<script>
function getResult() {
var output;
var tableStart = "<table>";
var tableEnd = "</table>";
var trStart = "<tr>";
var trEnd = "</tr>";
var tdStart = "<td>";
var tdEnd = "</td>";
var firstValue = document.getElementById("first").value;
//alert(firstValue);
var secondValue = document.getElementById("second").value;
//alert(secondValue);
if (firstValue < secondValue) {
//alert(secondValue);
document.write(tableStart);
document.write(trStart);
for (var k = firstValue; k <= secondValue; k++) {
document.write(tdStart);
document.write(tableStart);
document.write(trStart);
document.write(tdStart);
document.write(k + ":table");
document.write(tdEnd);
document.write(trEnd);
for (var i = 1; i <= 10; i++) {
output = k * i;
document.write(trStart);
document.write(tdStart);
document.write(k + "*" + i + "=" + output);
document.write(tdEnd);
document.write(trEnd);
}
document.write(tableEnd);
document.write(tdEnd);
}
document.write(trEnd);
document.write(tableEnd);
document.close();
}
else {
//alert(secondValue);
alert("Ending table should be higher number");
}
}
</script>
</head>
<body>
<%
out.println("<table>");
out.println("<tr><td>Starting Number");
out.println("</td><td>Ending Number</td></tr>");
out.println("<tr><td>");
out.println("<input type='text' id='first'>");
out.println("</td><td>");
out.println("<input type='text' id='second'>");
out.println("</td></tr>");
out.println("<tr><td align='right'>");
out.println("<input type='button' value='Get Tables' onclick='getResult()'");
out.println("</td></tr>");
out.println("</table>");
%>
</body>
</html>
You need to nest your loops one more level. There's a new, outer loop that increments j from start to end in steps of 5. Then the k loop goes from j to the end of the current row or the ending value, whichever comes first.
DEMO
function getResult() {
var output;
var tableStart = "<table>";
var tableEnd = "</table>";
var trStart = "<tr>";
var trEnd = "</tr>";
var tdStart = "<td>";
var tdEnd = "</td>";
var firstValue = parseInt(document.getElementById("first").value, 10);
//alert(firstValue);
var secondValue = parseInt(document.getElementById("second").value, 10);
//alert(secondValue);
if (firstValue < secondValue) {
//alert(secondValue);
document.write(tableStart);
for (var j = firstValue; j <= secondValue; j += 5) {
document.write(trStart);
for (var k = j; k <= Math.min(secondValue, j+4); k++) {
document.write(tdStart);
document.write(tableStart);
document.write(trStart);
document.write(tdStart);
document.write(k + ":table");
document.write(tdEnd);
document.write(trEnd);
for (var i = 1; i <= 10; i++) {
output = k * i;
document.write(trStart);
document.write(tdStart);
document.write(k + "*" + i + "=" + output);
document.write(tdEnd);
document.write(trEnd);
}
document.write(tableEnd);
document.write(tdEnd);
}
document.write(trEnd);
}
document.write(tableEnd);
document.close();
} else {
//alert(secondValue);
alert("Ending table should be higher number");
}
}