Compare document.getElementsByClassName().innerHTML with int - javascript

I have the given code:
function fill_random() {
let field = document.getElementsByClassName("field")
let random
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
random = Math.floor(1 + Math.random() * 9)
if (check(random))
field[j + (i * 9)].innerHTML = `${random}`
else
j--
}
}
}
function check(random) {
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (parseInt(document.getElementsByClassName("field")[j + (i * 9)].innerHTML) === random) {
console.log("Match!")
return false
}
}
}
return true
}
random is a let filled with
Math.floor(1 + Math.random() * 9)
When I try to execute it, the page won't load. When I try without parseInt() the page and everything else works but the if-condition never matches.
Obviously because I cant compare the innterHTML to an int.
So how to correctly cast the innerHTML to an int?
EDIT
Added more code as requested in the comments.
By "page won't load" I mean the page is loading forever. After few seconds the browser (Chrome latest version, no addons) asks me to leave the page or wait.
In the state of waiting it wont let me open developer tools.
The output of
console.log(document.getElementsByClassName("field")[j + (i * 9)].innerHTML)
gives a Number from 1 to 9 as string. Which is what I expect. Maybe my problem is not the parseInt() function but something else I can't figure out.

If you are having problems with the parseInt function, you could remove it and use a loose equality comparison (== instead of ===).
function check(random) {
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (document.getElementsByClassName("field")[j + (i * 9)].innerHTML == random) {
console.log("Match!")
return false
}
}
}
return true
}

Related

JS - Convert nested forloops into single loop

I need to convert this nested loop into a single loop.
This is the loop with the scenario:
First incrementer is i which starts from 0 and should run till 10
Second incrementer is j which starts from where i left off + 1 and runs till 10
.
.
My Nested Loop
for (var i = 0; i < 10; i++) {
for (var j = i + 1; j < 10; j++) {
if (some_condition) {
do_sth()
}
}
}
My Attempt at conversion
var i = 0;
while (i < 10){
var j = i + 1;
if (j < 10) {
if (some_condition) {
do_sth()
}
j++;
}
i++;
}
Unfortunately, my attempt doesn't produce the expected results.
The second snippet does not give the output which the first snippet delivers.
Can anyone please suggest me what my mistake is or provide me a better solution to achieve my target?
Thanks!
Not sure it improves readability complexity, but the following should produce the same.
var i = 0, j = 1;
while (i < 9) {
console.log(i, j);
j += 1;
if (j >= 10) {i += 1; j = i + 1}
}
You need to update i inside else statement or use continue. And declare j outside of the while body.
But keep in mind that this neither change "the order of complexity" nor "optimise" your code.
var i = 0;
var j = 1;
while (i < 10) {
if (j < 10) {
if (true) {
console.log(i, j)
}
j++;
} else {
i++;
j = i + 1;
}
}
You could adjust the loop lenght of i and check if j is greater or equal than 9, then increment i and start with fresh j.
var i = 0,
j = 1;
while (i < 9) {
console.log(i, j);
// do you stuff
if (j >= 9) j = ++i;
j++;
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

Why this code printing wrong prime numbers?

"I think problem is in for loop. Because i have used same "j" to iteration in both function's loop."
I wanted to print all prime number from 1-100.
I think all code is good. But it kept showing output other than prime numbers.
I can't find answers myself . And no other places has written answer. Please help me out here. I want to understand this problem.
var n = 100;
var prime1 = new Array();
//producing prime number upto 97
function primeNumber() {
for (j = 1; j <= n; j++) {
if (countRemainder(j) == 2) {
prime1.push(j);
}
}
}
primeNumber();
console.log(prime1);
function countRemainder(n) {
var count = 0;
for (j = 1; j <= n; j++) {
if (n % j == 0) {
count++;
}
}
return count;
}
The problem was indeed happening because you were using the same variable in both for loops.
When you declare a variable like j = 0; and not like var j = 0; the variable will be added to global scope (instead of the scope you are in, so every other scope can see and alter that variable).
If your script is running in strict mode, then this will throw an error, instead of adding the variable to the global scope.
So just add var before each j declaration.
var n = 100;
var prime1 = new Array();
//producing prime number upto 97
function primeNumber() {
for (var j = 1; j <= n; j++) {
if (countRemainder(j) == 2) {
prime1.push(j);
}
}
}
primeNumber();
console.log(prime1);
function countRemainder(n) {
var count = 0;
for (var j = 1; j <= n; j++) {
if (n % j == 0) {
count++;
}
}
return count;
}
Use "let" to declare "j" correctly.
function primeNumber() {
for (let j = 1; j <= n; j++) {
if (countRemainder(j) == 2) {
prime1.push(j);
}
}
}
Try this
var n = 100;
var prime1 = new Array();
//producing prime number upto 97
function primeNumber() {
for (var j = 1; j <= n; j++) {
if (countRemainder(j) == 2) {
prime1.push(j);
}
}
}
primeNumber();
console.log(prime1);
function countRemainder(n) {
var count = 0;
for (var j = 1; j <= n; j++) {
if (n % j == 0) {
count++;
}
}
return count;
}

misprinted number in prime function

function primeSieve() {
for(i = 0; i <= 100; i++){
let flag = true
for(let j = 2; j < i/2; j++){
if(i % j === 0){
flag = false
}
}
if(flag){
console.log(i)
}
}
}
primeSieve();
Hi,
I'm studying some algos and ran into a prime sieve problem. I'm trying to print all prime numbers between 0 and 100 and it's working for the most part. However, i realized that 4 slipped in somehow and i can't figure out why for the life of me. Wondering if i can get a few pairs of eyes and see how 4 ended up being logged to the console and why that's the case.
thank you!
Your condition in the inner loop:
for (let j = 2; j < i / 2; j++) {
is
j < i / 2
This means that when i is 4, once j gets to 2 (or, since j is always initialized to 2, before the first iteration), the loop breaks. So, without any iterations, there's never any chance for an i of 4 to get to flag = false.
Change to
for (let j = 2; j <= i / 2; j++) {
Also, per wikipedia:
A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.
So you should probably start i at 2, not 0.
Also, just like your let j, it would be good to declare i with let as well so as not to implicitly pollute the global scope:
function primeSieve() {
for (let i = 2; i <= 100; i++) {
let flag = true
for (let j = 2; j <= i / 2; j++) {
if (i % j === 0) {
flag = false
}
}
if (flag) {
console.log(i)
}
}
}
primeSieve();
Beside the including the value for j to check with j <= i / 2, you could omit the use of a flag and use continue with a label for the outer loop.
function primeSieve() {
outer: for (var i = 2; i <= 100; i++) {
for (var j = 2; j <= i / 2; j++) {
if (i % j === 0) {
continue outer;
}
}
console.log(i);
}
}
primeSieve();

JavaScript iterate loop every x number of times in same loop?

I am not sure how to phrase this, so please re-title this question if it doesn't make sense. Anyways, this is what I am trying to do.
I have a variable with the length of 9.
And then I have another variable with the length of 3.
How do I write a loop that iterates through all 9 but starts over every third time?
For example: I have this,
x = 3;
l = 9;
for ( var i = 0; i < l; i++)
{
console.log(i + 1);
}
output = 1,2,3,4,5,6,7,8,9
The output I want to create
output = 1,2,3,1,2,3,1,2,3
I was thinking there might be away to do this with an if statement or possibly modulus, but wasn't quite sure how to implement it. What would be a good way to do this? Thanks in advance.
Embrace the modulus:
function expand(length, loop_length) {
for (var i = 0; i < length; i++) {
console.log(i % loop_length + 1);
}
}
expand(9, 3) // => 1, 2, 3, 1, 2, 3, 1, 2, 3
x = 3;
l = 9;
for ( var i = 0; i < l; i++)
{
console.log(i % x + 1);
}
output = 1,2,3,1,2,3,1,2,3
See it in action here: http://jsfiddle.net/BgBGL/
If you want to loop from a min value to a max value a specific number of times, the easiest way is just to have 2 loops, like this:
var min = 1, max = 3, times = 3;
for (var i = 0; i < times; i++) {
for (var j = min; j <= max; j++) {
console.log(j);
}
}
Or if you want to fix total length of the sequence, then yes, you can do it with a single loop and a little bit of math:
var min = 1, max = 3, totalLength = 9;
for (var i = 0; i < totalLength; i++) {
console.log((i % (max - min + 1)) + min);
}
For that case, this works:
x = 3;
l = 9;
for ( var i = 0; i < l; i++)
{
var num=(i %(x+1)) || 1;
console.log(num);
}
You could go mad with following syntax:
var i = 0;
do {
console.log(i++ % 3 + 1);
} while (i < 9);
Alternative, you could define 3 and 9 as a variable also.
I took an advantage of the fact that calling i++ will display old variable and increases it by 1 after, so I saved some bits!
See: fiddle example
x = 3;
l = 9;
for ( var i = 0; i <= l; i++)
{
for ( var j = 1; j <= x; j++)
{
console.log(j);
}
}

How to dynamically update 3 dimensional Array values in Javascript

I have a 3d array-DataSeriesToPlot in Javascript, what I want to do is all first half rows' elements value plus a value- scale, all remaining half rows'elements value minus the value-scale. The code is like the below showed,
for ( var i = 0; i < DataSeriesToPlot.length; i++) {
for ( var j = 0; j < DataSeriesToPlot[i].length; j++) {
if ((i >= 0) && (i < (DataSeriesToPlot.length / 2))) {
DataSeriesToPlot[i][j][1] = (parseFloat(DataSeriesToPlot[i][j][1]) + parseFloat(scale))
.toFixed(2);
} else {
DataSeriesToPlot[i][j][1] = (parseFloat(DataSeriesToPlot[i][j][1]) - parseFloat(scale))
.toFixed(2);
}
for ( var j = 0; j < DataSeriesToPlot.length; j++) {
console.log("aaaaa"+DataSeriesToPlot[j]);
}
But this ways seems incorrect, because the console output the original value of this 3d array, all values haven't been changed. Could you please help me figure out where the error is? Thanks!

Categories