Populating multidimensional array - javascript

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.

Related

Multiplication Table in javascript and how about to align the row

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

How I can find specific words in the string and add class (Javascript)

There is a text in P element. In this text you can select some terms with a mouse click. But I want to display some previously selected words in a different class
I want to find special words in this text and add class.
Related part
var previosSelectedWords = 'aute,dolor,ex,sed,velit'; // previos selected words
var PSW = previosSelectedWords.split(',');
for (var i = 0; i < words.length; i++) {
if (PSW[i] == words[i]) {
wrapped.push('<span class="previosSelecteds">' + words[i] + '</span>');
} else {
wrapped.push('<span>' + words[i] + '</span>');
}
}
But it doesn't show the pre-selected words. What could be the reason?
The problem was your loop: You used the same loop and the same index for both arrays.
// Loop through each word and wrap
for (var j = 0; j < PSW.length; j++) {
for (var i = 0; i < words.length; i++) {
if (PSW[j] == words[i]) {
var prevS = '<span class="previosSelecteds">' + words[i] + '</span>';
words[i] = prevS;
}
}
}
for (var i = 0; i < words.length; i++) {
if (!words[i].includes('previosSelecteds')) {
wrapped.push('<span>' + words[i] + '</span>');
}
else {
wrapped.push(words[i]);
}
}

How do I input a number / time of 01:10 from my code?

I have this working code below to input a number/tme in textbox. This code below is functioning well but I want to set my textbox value into 00:00 and edit my function code like the second jsfiddle however my edited code is not going well as my idea. In my second jsfiddle I want to input a time of 05:30 but the code is replacing any number that input by a user from the textbox 0
function MaskedTextboxDPSDeparture() {
var myMask = "__:__";
var myCorrectionOut2 = document.getElementById("Departure");
var myText = "";
var myNumbers = [];
var myOutPut = ""
var theLastPos = 1;
myText = myCorrectionOut2.value;
//get numbers
for (var i = 0; i < myText.length; i++) {
if (!isNaN(myText.charAt(i)) && myText.charAt(i) != " ") {
myNumbers.push(myText.charAt(i));
}
}
//write over mask
for (var j = 0; j < myMask.length; j++) {
if (myMask.charAt(j) == "_") { //replace "_" by a number
if (myNumbers.length == 0)
myOutPut = myOutPut + myMask.charAt(j);
else {
myOutPut = myOutPut + myNumbers.shift();
theLastPos = j + 1; //set current position
}
} else {
myOutPut = myOutPut + myMask.charAt(j);
}
}
document.getElementById("Departure").value = myOutPut;
document.getElementById("Departure").setSelectionRange(theLastPos, theLastPos);
}
document.getElementById("Departure").onkeyup = MaskedTextboxDPSDeparture;
HTML
< input id="Departure" type="text" style="width: 35px; text-align: center" value="__:__" />
JSFIDDLE
JSFIDDLE 2
Any suggestion will accepted. Thanks.

Add alphabets dynamically as html row increments

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>";

JavaScript For Loop work hows?

I am using JavaScript for loop, my code is here
content = "";
for (var i = 0; i < 13; i++) {
var alt=glevel[i].getAttribute("name");
if(jQuery.inArray(alt, clickArray) > -1) {
if ($.browser.msie && parseInt($.browser.version, 10) === 8 || $.browser.msie && parseInt($.browser.version, 10) === 7) {
content += "<li id='"+alt+"' style='cursor:pointer;filter:alpha(opacity=50);'>"+alt+"<br><div style='width:auto;'><img src='products/"+alt+".png'><br><font size='1px'>Click Base To Select</font></div><br><p style='text-decoration:none;color:#ffffff;font-size:10px;margin-top:-18px;' id='"+alt+"'>Click Here For Product Info</p></li> \n";
} else {
content += "<li id='"+alt+"' style='cursor:pointer;opacity:0.3;'>"+alt+"<br><div style='width:auto;'><img src='products/"+alt+".png'><br><font size='1px'>Click Base To Select</font></div><br><p style='text-decoration:none;color:#ffffff;font-size:10px;margin-top:-18px;' id='"+alt+"'>Click Here For Product Info</p></li> \n";
}
//$('#'+clickArray[alt]+"").css("opacity","0.5");
} else{
content += "<li id='"+alt+"' style='cursor:pointer'>"+alt+"<br><div style='width:auto;'><img src='products/"+alt+".png'><br><font size='1px'></font></div><br><p style='text-decoration:none;color:#ffffff;font-size:10px;margin-top:-18px;' id='"+alt+"'></p></li> \n";
}
$("#step_2").html(content);
}
output of this code is something like that :-
image1 image2 image3 image4
image5 image6
image7 image8 image9 image10
image11 image12 image13
update:- it looks like that because of my table width and height
It works very fine, it display the real product images what i have.
now i want to display something like this :-
image1 image2 image3 image4
image5 image6 image7
image8 image9 image10
image11 image12 image13
means in the first row 4 images, while 2nd,3rd, and 4th row have 3 images
for (var i = 0; i < 13; i++) {
content += "...";
if (i == 3) // after the fourth line,
content += '<br/><br/>'; // add an empty line
if (i > 3 && (i - 4) % 3 == 2) // then, after every three lines
content += '<br/><br/>'; // add an empty line
}
This is could do the trick:
var content = "", imgNum = 1, max = 4;
for (var i = 0; i < 4; i++) {
if (i != 0) {
max = 3;
}
for (var j = 0; j < max; j++) {
content += "image" + imgNum;
imgNum++;
}
content += "<br />";
}
document.write(content);
demo
This is the logic:
set starting image number to 1
set max to 4 (later we will change it to 3)
loop the num of rows (4 times)
if we are at the first loop, leave max 4, otherwise change it to 3
loop the num of cols (max times)
add stuff to content
increase image number by 1
add the break after the loop
I prefered to use two loops instead of using the % operator, because it is more readable and faster.
edit: If you don't care about performance, I found a way to make a readable version with the %:
var content="";
for (var i = 0; i < 13; i++){
content += "image"+(i+1);
if(i==0||i==12){
continue;
}
if(i%3==0) {
content += "<br />";
}
}
document.write(content);
put this at the end of loop:
if (i == 3) { content += '<br/>'; }
if (i > 3 && (i - 4) % 3 == 2) { content += '<br/>'; }
What about this?
for (var i = 0; i < 13; i++){
content += "<li>...</li>";
if(i==3 || i==6 || i==9) { content += "<br />"; }
}

Categories

Resources