This question already has answers here:
How do I add a delay in a JavaScript loop?
(32 answers)
Closed 10 months ago.
I am trying a little bit of coding and I would like for the 30 character strings to appear in the 1 second intervals one after another when the code is started. I tried setInterval & setTimeout and I couldn't get it to work. If someone could please help that would be much appreciated.
count = 0
while (count < 200) {
console.log(create_random_string(30))
function create_random_string(string_length){
var random_string = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'
for(var i, i = 0; i < characters.length; i++){
random_string += characters.charAt(Math.floor(Math.random() * characters.length))
}
return "|BTC| " + random_string + " | " + " PRIVATNI KLJUČ NIJE ISPRAVAN" + " | " + " STANJE: 0.00"
}
count = count + 1
}
setInterval(code, time);
this function will allow you to wait X miliseconds before running the code defined.
here, the correct code, and i fixed your formatting a bit.
let count = 0;
while (count < 200) {
setTimeout(
function() { console.log(create_random_string(30)); }
, 500);
count++;
}
function create_random_string(string_length){
var random_string = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'
for(var i, i = 0; i < characters.length; i++){
random_string += characters.charAt(Math.floor(Math.random() * characters.length))
}
return "|BTC| " + random_string + " | " + " PRIVATNI KLJUČ NIJE ISPRAVAN" + " | " + " STANJE: 0.00"
}
by the way, you probably wanted to replace characters.length inside your for loop for : string_length to use the fuction's parameter (which you never actually used)
Related
I am trying to find a solution to this task "Determine how many integers, starting from the number 1, need to be added so that the sum will equal more than 100."using JavaScript.
I have my solution but I tend to feel that it is wrong.
Could you please help me?
I do not even realize if I understand the task in the right way.
Please see my solution below:
<script>
let result = 0;
for ( i = 1; i<20; i++){
result+=i;
if( result>100) {
break
}
}
console.log(i)
</script>
Output is 14, It is right , but I am not sure in the way I solving it.
If it works, there is nothing wrong about it.
You could simplify it, for example use a while rather than a for loop :
let total = 0
let count = 1;
// we loop until total is greater or equals to 100.
while(total < 100) {
// add the current count to the total
total += count;
// increment the count.
count++;
}
// we need to account for the last ++;
console.log(count - 1);
Here the while loop will run until the condition is broken.
1 + 2 + 3 + 4 + ... + k is a triangular number.
It can be solved using and then .
There, n is 100 and x is the base of the triangle (k in the above example, i in your loop).
This is a quadratic equation, solved using :
if we replace a b c by their respective values, we get :
x = 13.6509716981 or x = -14.6509716981 depending of the sign we use
If you round up 13.6509716981 you get 14, the expected result
This is written Math.ceil((-1 + Math.sqrt(1 - 4 * 1 * (-2 * num))) / 2) in JS, num being the value to reach (100 in your example)
This can be shortened to Math.ceil((-1 + Math.sqrt(1 + 8 * num)) / 2)
// Your original code, as reference
function FindNumberUsingLoops(num)
{
let result = 0;
// I modified the loop exit condition to make sure every case will run
for ( i = 1; i < num; i++){
result+=i;
if( result>=num) {
return i;
}
}
}
function FindNumber(num)
{
return Math.ceil((-1 + Math.sqrt(1 + 8 * num)) / 2);
}
console.log("using equation : " + FindNumber(100));
console.log("using loops : " + FindNumberUsingLoops(100));
console.log("using equation : " + FindNumber(500));
console.log("using loops : " + FindNumberUsingLoops(500));
console.log("using equation : " + FindNumber(42));
console.log("using loops : " + FindNumberUsingLoops(42));
console.log("using equation : " + FindNumber(1000));
console.log("using loops : " + FindNumberUsingLoops(1000));
console.log("using equation : " + FindNumber(1000000000000000000));
// uncomment below, this takes few seconds to solve
// console.log("using loops : " + FindNumberUsingLoops(1000000000000000000));
You can use this code:
let cheker = 0;
for (i = 1; i; i++) {
cheker += i;
if (cheker <= 100) {
console.log(i, cheker); // sum before 100 (94) and integers before 100 (13)
} else {
console.log(i, cheker); // sum after 100 (105) and integers before 100 (14 - answer)
break;
}
}
function NumStuff(num) {
this.num = num;
this.multipleOfFour = function() {
//if multiple of 4
if (this.num % 4 === 0) {
console.log(this.num + " is a multiple of Four");
console.log("the structure of the given integer " +
this.num + " is ");
for (let i = 0; i < this.num; i++) {
if (4 * i === this.num) { //why is this.num outside of
//lexical scope
console.log(this.num + " = " + i + " x 4");
break;
}
}
//if not a multiple of 4
} else {
console.log(this.num + " isn't a multiple of 4 but here is the integer's structure:");
let remainder = this.num % 4;
let tempNum = this.num - remainder;
for (let i = 0; i < tempNum; i++) {
if (4 * i === tempNum) {
console.log(this.num + " = " + i + " x 4 + " + remainder);
break;
}
}
}
};
}
let num = prompt("Enter an integer:");
let n = new NumStuff(num);
n.multipleOfFour();
Say we enter 20 as our num. It passes through the multipleOfFour() and hits the first if conditional. This.num(20) % 4 is equal to 0 so it passes.Then we loop through i to find what number times 4 is equal to 20. This.num is in the scope of the for statement but not in the scope of the inner if conditional of the for statement. Why is that so?
It is in the scope. That's not the issue.
But this.num is a string (that's what prompt always returns) while 4 * i is a number. And 4 * i === this.num will always be false, regardless of what you enter when prompted.
Try this (here):
for (let i = 0; i < this.num; i++) {
console.log('x', 4 * i, this.num, 4 * i === this.num);
An easy fix is let num = parseInt(prompt("Enter an integer:"));.
I would like to share with you my thoughts about this code:
for (var i = 1, max = 5; i < max; i++) {
let random = Math.random();
let expression = (random < 1 / (i + 1));
if (expression){
console.log('random is: ' + random + ' and the expression is: ' + expression + ', i is: ' + i);
}else{
console.log('random was: ' + random + ' and the expression was: ' + expression + ', i was: ' + i);
}
}
I was studying this example taken from GitHub: https://github.com/chuckha/ColorFlood
And I had trouble trying to know what was the meaning of the expression inside the if().
I used the JS repl: https://jscomplete.com/repl/
The context of this example is that this function would take a random index from 0 to 5, to map a random color to a Node.
Here we have a sample output from the repl:
"random was: 0.7118559117992413 and the expression was: false, i was: 1"
"random was: 0.478919411809795 and the expression was: false, i was: 2"
"random was: 0.4610390397998597 and the expression was: false, i was: 3"
"random was: 0.7051121468181564 and the expression was: false, i was: 4"
The syntax:
let expression = (random < 1 / (i + 1));
Means:
(i + 1) first add 1 to var i
Next, 1 / (i + 1) divide 1 by the sum (i + 1)
Let say result = 1 / (i + 1)
random < result, if the random value less than above division result than return true, else false.
So, something simple like:
for (var i = 1, max = 5; i < max; i++) {
let random = Math.random();
let expression = (random < 1 / (i + 1));
console.log(
i,
random.toFixed(2),
(1 / (i + 1)).toFixed(2),
expression
)
}
I first thought that it would be evaluated random < 1 so then as random uses Math.random() which gets a number between 0 and 1, excluding the one; I thought that part of the expression would be alway true.
But in fact after putting it into the repl I discovered that the 1 / (i+1) part is done first, and then it is done all together: random / result.
I have also read:
https://www.w3schools.com/js/js_comparisons.asp
https://www.w3schools.com/js/js_arithmetic.asp
https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/random
Please note that in the original post I simplified the code, the original code is:
var randomIndexFromCollection = function randomIndexFromCollection(collection) {
var index = 0;
for (var i = 1, max = collection.length; i < max; i++) {
if (Math.random() < 1 / (i + 1)) {
index = i;
debugger;
}
}
return index;
};
I am creating a list of words from a String. I then split that string into individual words, gather a count of how many times each word is repeated, and display it. Everything there works perfectly. However, the result displays the words and counts in no specific order. I will want to display them with the highest number first. I have generated the following code:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the array values after the split.</p>
<button onclick="analyze()">Analyze</button>
<p id="displayText"></p>
<script>
function analyze() {
var str = "This this is is is is is is is is is is is is is is is just just a test test test";
var res = str.split(" ");
document.getElementById("displayText").innerHTML = res;
document.getElementById("displayText").innerHTML += "<br/><br/>The amount of words is: " + res.length + "<br/><br/><br/>";
document.getElementById("displayText").innerHTML += "The list of words:<br/><br/>";
var words = [];
var wordsWithCount = [];
for (i = 0; i < res.length; i++) {
words.push(res[i]);
document.getElementById("displayText").innerHTML += words[i] + "<br/><br/>";
}
var current = null;
var cnt = 0;
for (var i = 0; i < words.length; i++) {
if (words[i] != current) {
if (cnt > 0) {
document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>";
wordsWithCount.push(cnt + " - " + current);
}
current = words[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>";
wordsWithCount.push(cnt + " - " + current);
}
wordsWithCount.sort();
document.getElementById("displayText").innerHTML += "<br/><br/><br/><br/><br/>The list of SORTED words:<br/><br/>";
for (i = 0; i < wordsWithCount.length; i++) {
document.getElementById("displayText").innerHTML += wordsWithCount[i] + "<br/><br/>";
}
}
</script>
</body>
</html>
This is the last bit of the output. As you can see, it's being sorted, but only by first digit. Thus, 15 is displayed before 2. Any thoughts?
The list of SORTED words:
1 - This
1 - a
1 - this
15 - is
2 - just
3 - test
I will most likely need to break this into two arrays at some point, because I will want the user to be able to copy and paste all of the words, without the numbers. However, I assume that will need to be the last step, because if I break the frequency of each word into it's own array of numbers, and keep the words in their own array, then the sort function will sort one array, and the other array will not follow.
Using a parseInt() method and the solution found here (How to sort an array of integers correctly) to the mix it works!
replace wordsWithCount.sort(); with:
function sortNumber(a,b) {
return parseInt(a) - parseInt(b);
}
wordsWithCount.sort(sortNumber);
Live here: https://www.w3schools.com/code/tryit.asp?filename=FFGXRIN0VZWO
Do it using Intl.Collator. Like this:
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
var test = ['1 - this', '3 - this', '14 - this'];
test.sort(collator.compare);
Outputs ["1 - this", "3 - this", "14 - this"]
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
var test = ['1 - this', '3 - this', '14 - this'];
console.log(test.sort(collator.compare));
You can just add a custom compare function to pass into your wordsWithCount.sort() call. Here I declared a function called compareWordCount and used the sugfested method by #Pointy; using parseInt to ignore all non integer parts appended to array value. Take a look at this working snippet:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the array values after the split.</p>
<button onclick="analyze()">Analyze</button>
<p id="displayText"></p>
<script>
function compareWordCount(a,b) {
if (parseInt(a) < parseInt(b))
return -1;
return 1;
}
function analyze() {
var str = "This this is is is is is is is is is is is is is is is just just a test test test";
var res = str.split(" ");
document.getElementById("displayText").innerHTML = res;
document.getElementById("displayText").innerHTML += "<br/><br/>The amount of words is: " + res.length + "<br/><br/><br/>";
document.getElementById("displayText").innerHTML += "The list of words:<br/><br/>";
var words = [];
var wordsWithCount = [];
for (i = 0; i < res.length; i++) {
words.push(res[i]);
document.getElementById("displayText").innerHTML += words[i] + "<br/><br/>";
}
var current = null;
var cnt = 0;
for (var i = 0; i < words.length; i++) {
if (words[i] != current) {
if (cnt > 0) {
document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>";
wordsWithCount.push(cnt + " - " + current);
}
current = words[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>";
wordsWithCount.push(cnt + " - " + current);
}
wordsWithCount.sort(compareWordCount);
document.getElementById("displayText").innerHTML += "<br/><br/><br/><br/><br/>The list of SORTED words:<br/><br/>";
for (i = 0; i < wordsWithCount.length; i++) {
document.getElementById("displayText").innerHTML += wordsWithCount[i] + "<br/><br/>";
}
}
</script>
</body>
</html>
so basically this the prompt:
Addition countdown
you enter a number and the code should be adding a number while countingdown, for example if the user enter 10, then the result should be:
10 + 9 + 8 + 7 + 6 + 5 + 4 +3 +2 +1=55.
This is what I have so far:
var num = Number(prompt("Enter a Number Greater than zero"));
while (num > 0){
first = num;
second = num-=1;
document.write(first + " +" + second + " +");
value = first + num;
document.write(value)
num--;
}
but I keep on getting something like this:
4 +3 +72 +1 +3 (let's say 4 is the number the user inputs)
I'm stuck can someone please help me????!!
You can keep total in one variable outside of while loop.
var num = Number(prompt("Enter a Number Greater than zero"));
var total = 0;
while (num > 0) {
total += num;
document.body.innerHTML += (num == 1 ? num + ' = ' + total : num + ' + ');
num--;
}
You could change the algorithm a bit, because for the first value, you need no plus sign for the output.
var num = Number(prompt("Enter a Number Greater than zero")),
value = 0;
document.body.appendChild(document.createTextNode(num));
value += num;
num--;
while (num > 0) {
document.body.appendChild(document.createTextNode(' + ' + num));
value += num;
num--;
}
document.body.appendChild(document.createTextNode(' = ' + value));