Why all my loops don`t work? - javascript

http://jsfiddle.net/VaAlina/oupmd0hf/
Commented code don`t work.
Area next to bomb is green. Yellow - bombs. Blue - emptiness .
I want to replace this kind of code->
var dangerItem1 = "#" + danger1;//Replace thise code to commented
var dangerItem2 = "#" + danger2;
var dangerItem3 = "#" + danger3;
var dangerItem4 = "#" + danger4;
With this->
/*
for(var j = 0; j < 4; j++){
var dangerItem+j = "#" + danger+j;
}
*/
Where is the mistake?

You can't dynamically create a variable name.
What you could do though is store them in arrays or objects.
Objects can accept dynamic property names using [] notation.
var danger =['green','red','blue','pink'];
var dangerItem = [];
for(var j = 0; j < 4; j++){
dangerItem.push( "#" + danger[j]);
}
// returns ["#green", "#red", "#blue", "#pink"]
/* or */
var dangerItem = {};
for(var j = 0; j < 4; j++){
dangerItem[ danger[j] ] = "#" + danger[j];
}
// returns {"green":"#green","red":"#red","blue":"#blue","pink":"#pink"}

Related

Javascript Multiplication table in 2D array

I've a task to write a program that creates a multiplication table for the given variable n.
The results need to be saved to a two-dimensional array. In the console I need to display the entire table with appropriate data formatting (as below). I'm starting with Javascript and already know loops and arrays only, I haven't learnt functions yet so I need some really basic solution.
This is how the result should look like:
Here is my code that I wrote so far and I don't know what to do next:
const n = 3;
const calc = []
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n; j++) {
calc.push(i + " * " + j + " = " + (i * j));
}
console.log(calc)
}
You're almost there:
Not sure that you need the array calc if your aim is to print the table
Define a new variable row inside the outer loop as an empty array, [];
In the inner loop, instead of calc.push, use row.push
After the inner loop, you have a complete row, which you can output using the array .join() method
If you need to, then add the row to calc with calc.push(row); not necessary in my view.
const n = 3;
//const calc = []; //may not be necessary
for (let i = 1; i <= n; i++) {
const row = [];
for (let j = 1; j <= n; j++) {
row.push(i + " x " + j + " = " + (i * j));
}
console.log( row.join(' | ') );
//calc.push(row);//not sure if you still need this
}
/* OUTPUT
1 x 1 = 1 | 1 x 2 = 2 | 1 x 3 = 3
2 x 1 = 2 | 2 x 2 = 4 | 2 x 3 = 6
3 x 1 = 3 | 3 x 2 = 6 | 3 x 3 = 9
*/
From the code you've presented, it appears that you're yet to understand what a 2d array really is. The way you've done it, everything's just stuffed into a single 1d array.
You may think of the pixels on a screen as being part of a 2d array. The first array holds all of the horizontal lines. The horizontal lines contain the pixels.
So.. let's concentrate on that part first.
let result = [];
for (var y=0; y<n; y++)
{
result.push( [] );
for (var x=0; x<n; x++)
{
result[y].push( (x+1) * (y+1) );
}
}
First we create a result array, and then for every row in our table, we add an array that will hold the columns, then for each column in that row, we add the values.
Next, we just step through that table and turn the values into the original equations. We start by ascertaining the dimensions of the array, before we create a table the same size.
function printTable( tbl )
{
let nRows = tbl.length;
let nCols = tbl[0].length;
for (var y=0; y<nRows; y++)
{
let rowStr = '';
for (var x=0; x<nCols; x++)
{
if (x!=0) rowStr += " | ";
rowStr += `${y+1} x ${x+1} = ${tbl[y][x]}`;
}
console.log(rowStr);
}
}
Chucking it all together, I present the following code. Yes, I know you're not using functions yet - but you can still see the important concepts. You can change it so that the whole equation for each entry in the table is saved, instead of just the answer.
window.addEventListener('load', init, false);
function init()
{
let result = makeMultTable(3);
printTable(result);
}
function makeMultTable(n)
{
let result = [];
for (var y=0; y<n; y++)
{
result.push( [] );
for (var x=0; x<n; x++)
{
result[y].push( (x+1) * (y+1) );
}
}
return result;
}
function printTable( tbl )
{
let nRows = tbl.length;
let nCols = tbl[0].length;
for (var y=0; y<nRows; y++)
{
let rowStr = '';
for (var x=0; x<nCols; x++)
{
if (x!=0) rowStr += " | ";
rowStr += `${y+1} x ${x+1} = ${tbl[y][x]}`;
}
console.log(rowStr);
}
}
Here is a short version of putting those multiplications into a 2D array:
const arr=[...Array(4)].map((_,i)=>i+1),
arr2=arr.map(i=>arr.map(j=>`${i}*${j}=${i*j}`));
console.log(arr2);
Multiplication of table in two dimension array
Function name: multiplyNumber
Syntex multiplyNumber(n)
n Number to be passed to function to create table upto that number.
Snippet
function multiplyNumber(n){
let table = [];
let data = [];
for (var i = 1; i <= n; i++){
for (var j = 1; j <= n; j++){
data.push(`${i} x ${j} = ${i * j}`);
}
table.push(data); // pushing data to table.
data = []; //Resetting data array to store new data each time.
}
return table;
}
var result = multiplyNumber(3);
console.log(result);
For every line I created an array line, filling it with the calculations. after the line loop I pushed it into calc.
const n = 3;
const calc = [];
for (let i = 1; i <= n; i++) {
const line = [];
for (let j = 1; j <= n; j++) {
line.push(i + " * " + j + " = " + (i * j));
}
calc.push(line);
}
console.log(calc);

JavaScript to remove string in OBX 5.1 starting with first occurance of "\\." till the end

I am trying to write a JavaScript to remove string in OBX 5.1 after "\."
Here is the inbound OBX segment:
OBX|2|NM|WBC^White Blood Cell Count^WinPath||3.2\\.br\\This result could indicate your patient might have\\.br\\sepsis. Take into consideration the absolute\\.br\\neutrophil and lymphocyte counts when making your|x 10^9/l|4 - 10|L|||F|||||
Here is the expected outbound OBX segment:
OBX|2|NM|WBC^White Blood Cell Count^WinPath||3.2|x 10^9/l|4 - 10|L|||F|||||
I have written this Javascript code. It is compiling but not removing the unwanted text.
Here is what I have written:
var RegExp_pattern = "\\.";
function indexOf(stringToTrim) {
return stringToTrim.indexOf(RegExp_pattern);
}
function substring(ssstringToTrim) {
return ssstringToTrim.substring(indexOf(OBX_TestValue), -1);
}
/* Single input message case */
var next = output.append(input[0]);
// loop through Order Group (OBR) & Result Group (OBX)
//
var cntObs = next.getRepeatCount("ObservationMessage");
for (var i = 0; i < cntObs; i++) {
var cntOrders = next.getRepeatCount("ObservationMessage[" + i + "]/Order");
for (var j = 0; j < cntOrders; j++) {
var cntResults = next.getRepeatCount("ObservationMessage[" + i + "]/Order[" + j + "]/Results");
for (var k = 0; k < cntResults; k++) {
var OBX_TestValue = next.getField("ObservationMessage[" + i + "]/Order[" + j + "]/Results[" + k + "]/OBX/ObservationValue");
if (OBX_TestValue.indexOf(OBX_TestValue) > 0) {
OBX_TestValue = substring(OBX_TestValue);
}
}
}
}
To remove everything from the first occurance of "\." until the end of the string you should use a regular expression.
var str = "OBX|2|NM|WBC^White Blood Cell Count^WinPath||3.2\\.br\\This result could indicate your patient might have\\.br\\sepsis. Take into consideration the absolute\\.br\\neutrophil and lymphocyte counts when making your|x 10^9/l|4 - 10|L|||F|||||";
var mtch = str.replace(/\\\..*/, '');
console.log(mtch);

How to add a JSON array to an infinite amount of option menus?

For a WebInterface I need to add a JSON array to an infinite amount of option menus with JavaScript. I'm still new to programming with JavaScript and I thought you could help me.
I found a solution for adding a JSON array to an optionmenu which worked so I tried to add some code to make it work with an infinite amount of option menus.
I have two select tags:
<select id="selection1" class="selectionMenu"> </select>
<select id="selection2" class="selectionMenu"> </select>
the following code is the script I worked out to add option tags into both of the select menus which doesn't work for me.
<script>
var arr = [
'selection1',
'selection2'
]
var arrLen = arr.length - 1;
for (j = 0; j < arrLen; j++) {
var arrElm = arr[j];
var select = doucment.getElementById(arrElm);
var text = '{"nrrps":[' +
'{"dbC":"PI1","PIIP":"192.168.2.17" },' +
'{"dbC":"PI2","PIIP":"192.168.2.18" },' +
'{"dbC":"PI3","PIIP":"192.168.2.19" }]}';
for (i=0; i < text.length; i++;) {
var opt = document.createElement('option');
var counter2 = i + 1;
obj = JSON.parse(text);
var insertText = obj.nrrps[i].dbC + " " + obj.nrrps[i].PIIP + " ";
var optVal = obj.nrrps[i].dbC;
opt.value = optVal;
opt.innerHTML = insertText;
opt.setAttribute("class", "sOption");
select.appendChild(opt);
}
}
</script>
When I run the code, the JSON array is inserted into the first select tag but not the second one. I don't know why. In addition is there a possibility to get the value of every select tag after choosing the options?
I hope you can help me with this.
Thank you in advance!
1st : First as #kamesh mentioned you already applied -1 in length so change the operator like below j <= arrLen;
for (j = 0; j <= arrLen; j++) { ... }
2nd : In second for loop your checking length for text so it will give the text length 122 something .it's wrong so you need to apply JSON.parse() then find length of option like below
var obj = JSON.parse(text);
for (i=0; i < obj.nrrps.length; i++) {...}
var arr = [
'selection1',
'selection2'
]
var arrLen = arr.length - 1;
for (j = 0; j <= arrLen; j++) {
var arrElm = arr[j];
var select = document.getElementById(arrElm);
var text = '{"nrrps":[' +
'{"dbC":"PI1","PIIP":"192.168.2.17" },' +
'{"dbC":"PI2","PIIP":"192.168.2.18" },' +
'{"dbC":"PI3","PIIP":"192.168.2.19" }]}';
//console.log(text.length);
var obj = JSON.parse(text);
for (i=0; i < obj.nrrps.length; i++) {
var opt = document.createElement('option');
var counter2 = i + 1;
var insertText = obj.nrrps[i].dbC + " " + obj.nrrps[i].PIIP + " ";
var optVal = obj.nrrps[i].dbC;
opt.value = optVal;
opt.innerHTML = insertText;
opt.setAttribute("class", "sOption");
select.appendChild(opt);
}
}
<select id="selection1" class="selectionMenu"> </select>
<select id="selection2" class="selectionMenu"> </select>
You are already subtracting one from your array length. So run your for loop till <= array.length.
....
....
for (j = 0; j <= arrLen; j++) {
var arrElm = arr[j];
....
....

JavaScript syntax issue

I'm doing "fifteen puzzle" game. I'm only a beginner, so I chose this project to implement. My problem is shuffle algorithm :
function shuffle() {
$('td').empty();
var p = 0;
var f = 0;
do {
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
var rand = arr[Math.floor(Math.random() * arr.length)];
if ($('#' + rand).is(':empty')) {
p = p + 1;
document.getElementById(rand).textContent = p
var f = $('td').not(":empty").length;
} else {}
} while (f < 15)
That works cool, but I've heard that almost 50% of all random shuffle like mine is unsolvable. So I found math formula at wikipedia.org for this game, explaining how you can avoid that.
Here's modified algorithm that doesn't work either. The way I know it is alert stuff: it launches only 2 times instead of 31.
array = [];
function algorithm (){
// alert('works')
for (var c=16; c<17; c++){
document.getElementById(c).textContent = '100';
}
for (var i=1; i<16; i++){
var curId = document.getElementById(i).id;
var curIdNum = Math.floor(curId);
alert('works')
var curIn = document.getElementById(i).textContent;
var curInNum = Math.floor(curIn);
array.push(i);
array[i] = new Array();
for (var j=1; j<15; j++){
var nextId = curIdNum + j; //curIdNum NOT cerIdNum
var nextIn = document.getElementById(nextId).textContent;
//alert('works')
if (nextId < 16){
var nextInNum = Math.floor(nextIn);
if (curInNum > nextInNum){
array[i].push(j)
}
}
}
var sum = 0;
for (var a=0; a<15; a++){
var add = array[a].length;
sum = sum + add;
}
var end = sum + 4;
if (end % 2 == 0){
document.getElementById('16').textContent = "";
}
else {
shuffle();
}
}
}
The question is the same:
What's wrong? Two-dimensional array doesn't work.If you've got any questions - ask.
Just to make it clear: 2 for loops with i and j should make a 2-dimensional array like this [ this is " var i" -->[1,3,4,5,7], this is "var i" too-->[5,7,9,14,15]]. Inside each i there's j. The for loop with var a should count the number of js inside each i. if the number of js is even, the code is finished and shuffle's accomplished, otherwise shuffle should be made once again.
var nextId = cerIdNum + j;
in that fiddle, I don't see this cerIdNum declared & defined neither as local nor as global variable, I suppose that is curIdNum
Please use the below definition of algorithm and let us know if this works. Basically, the alert messages would come only twice, since there were usages of undefined variables. For the purpose of illustration, I have placed comments at where the problem points occured. Due to these problems, your script would stop executing abruptly thereby resulting in the behavior you described.
Oh and by the way - I did not have time to go through the Wiki link provided - hence you will have to verify your logic is correct. However, I have definitely resolved the errors causing the behavior you observed.
As an aside - consider using jQuery, your code will be a lot cleaner...
function algorithm (){
// alert('works')
for (var c=16; c<17; c++){
document.getElementById(c).textContent = '100';
}
for (var i=1; i<16; i++){
var curId = document.getElementById(i).id;
var curIdNum = Math.floor(curId);
alert('works')
var curIn = document.getElementById(i).textContent;
var curInNum = Math.floor(curIn);
array.push(i);
for (var j=1; j<15; j++){
var nextId = curIdNum + j; //curIdNum NOT cerIdNum
var nextIn = document.getElementById(nextId).textContent;
//alert('works')
if (nextId < 16){
var nextInNum = Math.floor(nextIn);
if (curInNum > nextInNum){
array.push(j) //array[i].push does not make sense
}
}
}
var sum = 0;
for (var a=0; a<15; a++){
var add = array.length; //array[1].length does not make sense
sum = sum + add;
}
var end = sum + 4;
if (end % 2 == 0){
document.getElementById('16').textContent = "";
}
else {
shuffle();
}
}
}
I found the solution by totally rewriting the code. Thank everyone for help!
Here's what do work:
function shuffle (){
press = 1;
$('td').empty().removeClass();
p=0;
var f;
do {
var arr=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var rand=arr[Math.floor(Math.random()*arr.length)];
if ($('#'+ rand).is(':empty')){
p = p + 1;
document.getElementById(rand).textContent = p
var f = $('td').not(":empty").length;
}
else{}
}while(f < 15){
winChance();
}
}
function winChance (){
array = [];
for (i=1;i<16;i++){
array[i]= new Array();
var currentId = $('#' + i).attr('id');
var currentIn = $('#' + i).html()
var currentIdNum = parseInt(currentId, 10);
var currentInNum = parseInt(currentIn, 10);
for (j=1;j<16;j++){
var nextId = currentIdNum + j;
if (nextId < 16){
var nextIn = $('#' + nextId).html();
var nextInNum = parseInt(nextIn, 10);
if (currentInNum > nextInNum){
array[i].push(j);
}
}
}
}
checkSum();
}
function checkSum(){
var sum = 0;
for (var a=1; a<16; a++){
var add = array[a].length;
sum = sum + add;
}
var end = sum + 4;
if (end % 2 == 0){}
else {
shuffle();
}
}

How to make calculations in Javascript?

i = 3;
j = 2;
function domath(x) {
i = 4;
j = 1;
return i*x + j;
}
j = domath(i) - j;
alert(j); //expected result = 11
k = domath(i) + j;
alert(k); //expected result = 15
The above JavaScript code does not return the expected results (as indicated by the comments in the code). Please correct the code for me anyone ?
As you're not using var , the variables i and j you're defining in the first lines are actually the same variable as you define in your domath() function...
try this :
i = 3;
j = 2;
function domath(x) {
var i = 4;
var j = 1;
return i*x + j;
}
j = domath(i) - j;
alert(j); //expected result = 11
k = domath(i) + j;
alert(k); //expected result = 15
P.S : it could be a good idea to vary your variable name in order to make your code more readable
Declare your variables using var:
var i = 3;
var j = 2;
function domath(x) {
var i = 4;
var j = 1;
return i * x + j;
}
It seems to be a really nasty way to do things.
I would personally do something like:
var v1;
var v2;
function math(x){ //do math here then return}
alert(math(1))
If you really have to use the same varible every where at least do it like:
var i = 3;
var j = 2;
function domath(x) {
var i = 4;
var j = 1;
return i*x + j;
}
Also meaningful varibles names will keep you on a good track and using var and not global will also help you!
var i = 3;
var j = 2;
function domath(x) {
var i = 4;
var j = 1;
return i*x + j;
}
var x = domath(i) - j; // overwriting J will change your next expected result
alert(x); //expected result = 11
var k = domath(i) + j;
alert(k); //expected result = 15
The problem is you're overwriting global variables, i.e. screwing up your math:
j = domath(i) - j;
This expression is evaluated from left to right. The call to domath() will assign new values to i and j, so the effective code here would be this:
j = (i = 4) * 3 + 1 - 1;
So once this is done, j will be set to 12, which is indeed not 11. In addition, i will have a value of 4.
To use local variables within your function, you'll have to redeclare them, essentially hiding the global variables being outside this scope:
function domath(x) {
var i = 4;
var j = 1;
return i * x + j;
}
This time, the first assignment will be resolved to this, because domath() won't touch i and j assigned outside:
j = 4 * 3 + 1 - 2
Once this i done, j will be set to 11, just as expected.
To avoid such issues, it's good practice to always use var when defining new variables (which you'll have to do when wanting to write strict code anyway), and not to use such short, not-telling variable names. I'd consider limiting the use of one-character variable names to iterators and other things with very limited scope. Never for something being global.

Categories

Resources