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
}
Below are my functions that sum up all prime numbers that are below a given maxNum.
I don't understand why the for loop in the isPrime function doesn't work when using j <= num instead of j ** 2 <= num.
function sumPrimes(maxNum) {
let sum = 0;
for (let i = 2; i <= maxNum; i++) {
if (isPrime(i)) {
sum += i
}
}
return sum
}
function isPrime(num) {
for (let j = 2; j <= num; j++) { // when I use j ** 2 <= num it works
if (num % j === 0) {
return false
}
}
return true
}
console.log(sumPrimes(20))
if you use j <= num, the loop will count j up to the number itself and then it would match num % j === 0 and return false.
So if num was 17, the loop would be executed with 17 <= 17 which passes and the loop body executes 17 % 17 === 0 so it always returns false, no matter what number you pass in.
you could use j < num instead of j <= num in the loop head which should also work because the number itself is never reached when using the smaller than sign.
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; }
"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;
}
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);
}
}