Writing 1 through 125 in javascript - javascript

I'm trying to write some code so that when the user clicks a button, the page writes the numbers 1 through 125, while modifying some in between My first question is how do I write the conde so that the function writes these numbers. Here's the code I have so far.
<script>
function randomNumber() {
var num = Math.floor(Math.random() * 125);
for (var i = 0; i < 125; i++) {
document.write(num);
}
</script>
My second question is how do I modify each a few of the numbers to read, for example, ten instead of 10. I assume that this will use a nested for loop, unless I'm wrong. Any help would be great! Thank you.

your code is on the right track
<script>
function randomNumber() {
for (var i = 0; i < 125; i++) {
var num = Math.floor(Math.random() * 125);
console.log(num);
//document.write(num); - bad!
}
}
document.getElementById('yourElement').onclick = randomNumber;
</script>
You didn't close off your function, unless it was a mis-copy. Also, your variable num needs to be within the for loop so it can call a random number each tick, unless you want one random number written 125 times, then keep num outside randomNumber().
Secondly, don't use document.write, it is bad practice. Utilize document.getElementById('yourElement').innerHTML = num.
Lastly, if you want to resolve the number based upon it's english counterpart, you will need an object with numbers 1 - 125, and their respective word set as the value of each number...
var numbers = {
1: "one",
2: "two"
// etc....
}
In the loop you will need something along the lines of a switch or if/else if chain that has a condition for each number and utilizes your i increment as an index number[i] to print out the proper text.

Related

How to use map() and reduce() functions in Javascript?

I am writting a simple function that would allow me to calculate prime numbers on one of nosql databases. After multiple approaches, i got an error that value i am looking for is not defined, thus I would appreciate your feedback.
Here is what i have tried:
First I have generated a set of numbers:
for (var i = 0; i < 1000; i++) db.exemplary.insert( {x: Math.random()} );
2.Secondly I have defined map function
map = function() {
for (var i = 2; i < x; i++){
if(x % i == 0)
try {} catch (e) {};
}
emit(i, value);
};
In the end the reduce function:
reduce = function (i,value){return array.sum(value)}
I assigned the collection to variable and called the function:
collection = db.exemplary
var result = collection.mapReduce(map, reduce, {out: {inline: 1}});
As per my begginer understanding the map step should check whether the number is prime or not.
Reduce step on the other hand should sum all occurrences of prime numbers.
I got error that x is not defined, but it is present in the db.exemplary collection.
I would appreciate every improvement hint/suggestion for above functionality.
EDIT: Currently my function does not "emit" any results of map operation, working on this bit now.
Math.random() generates by default float numbers from 0 to <1.
then in your generator you should use a function like this, for example to get random numbers from 0 to 999 :
{ x: Math.floor(Math.random()*1000) }

Why does generating a random number outside of a loop, causes it to be always the same?

When I create a random number inside a while loop as a local variable everything works, but when I generate a random number as a global variable then I get stuck in an infinite loop.
I don't understand how and why this should make any difference.
Goal is to output all the random numbers that are less than 0.7 with a While Loop.
Here is the code that creates an infinite loop:
let rnd = Math.random();
let continue = true;
while (continue) {
console.log(rnd);
if (rnd > 0.7) {
continue = false;
alert(rnd + ' is bigger than 0.7!');
}
}
Here is the code that works (only thing that is changed is that the random number is generated within the while loop).
let continue = true;
while (continue) {
let rnd = Math.random();
console.log(rnd);
if (rnd > 0.7) {
continue = false;
alert(rnd + ' is bigger than 0.7!');
}
}
I'm not interested in creating this with another kind of loop, I'm just trying to understand the While Loop better.
let rnd = Math.random();
let continue = true;
while (continue) {
console.log(rnd);
if (rnd > 0.7) {
continue = false;
alert(rnd + ' is bigger than 0.7!');
}
}
Here, the random number generator will only execute one time, before the while loop. If th random number isn´t > 0.7, continue would be always true and it will be an infinite loop.
However, if the random number is generated locally in the while loop, in each loop a new number will be generated so you only need to wait for a rnd number > 0.7.
It is because when you declare Math.random() as a variable it creates a binding with a random value which doesn't change. Example: 0.8.
And if it is less than or equal to 0.7 then it would result in an infinite loop because the value doesn't change with each iteration.
In the second example it works fine because it is declared locally and it's value changes with each iteration.
Hope you understood.

Randomize number on click but never the same number

I want to random a number on clicking button but I don't want same numbers to be randomized any solutions?
$('button').click(function(){
var nomeri = Math.floor(Math.random() * 100);
}
<button>დამაკლიკე</button>
You could use a recursive function to generate a unique number.
I am implementing the function with an array which will hold the value of the previously used numbers and the Math.random() to generate the random number.
steps:
Step 1. Create a function.
Step 2: Generate a random number
step 3: check if it exists in the array
step 4: if already exists then call the function again otherwise we have the unique random number.
if the function exceeds the max random numbers then it will return a negative number. You could handle this according to your need, you could reset the array or something like that.
Try this.
$('button').click(function(){
var nomeri = genRandomNum();
console.log(nomeri);
});
let random = [];
function genRandomNum() {
let randNum = Math.floor(Math.random() * 100);
if (random.length >= 100) {
return -1;
} else if (random.includes(randNum)) {
return genRandomNum();
} else {
random.push(randNum);
return randNum;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Random Number</button>
Here is a more efficient way to do this. Doing it the way Sohail proposed could result in many many function calls, especially once there have been a large share of the available numbers added to the array. Each time it finds a number that has been used before it calls the function again in search of a random number that has not been used yet. It could take a long time to find an unused number.
This way you are guaranteed to get an unused number the first time you call the function.
1) All possible answers are added to an array.
2) Then a random value from that array is returned.
3) The array is then modified to exclude the values already returned.
See: array.splice()
const allPossibleValues = [];
for(let i = 0; i < 100; i++){
allPossibleValues.push(i);
}
$('button').click(function(){
if(allPossibleValues.length){
let nomeri = returnRandomValueFromArray();
console.log(nomeri);
}
else {
console.log("No more values left");
}
});
function returnRandomValueFromArray() {
const randomIndex = Math.floor(Math.random() * allPossibleValues.length);
const randomValue = allPossibleValues[randomIndex];
allPossibleValues.splice(randomIndex, 1);
return randomValue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>დამაკლიკე</button>

How does Javascript variable works?

Recently started learning Javascript.
Given an assignment for my class, to click a button (a number 10 is written on the button), and there has to be "Result = 55". (here all numbers from 0 to 10 are added)
To change words by clicking buttons, wrote code like this:
function myFunction(num) {
var p = document.getElementById("mydata");
for (var i = 0; i <= num; i++) {
sum = sum + i;
p.innerHTML = "Result = " + sum;
}
}
After submitting assignment for school, learned that had to add var sum = 0 above var p = document.getElementById("mydata")
However, do not understand what var sum = 0 means. As for looks already show when to begin and end calculating, feel like it doesn't have to be there.
var sum = 0; declares a local variable named sum, and sets its initial value to 0.
If you don't do this, when you do:
sum = sum + i;
the variable sum is initially undefined, and adding i to it results in NaN (Not a Number).
Some languages (e.g. PHP) automatically treat initialized variables as 0 in arithmetic expressions, but JavaScript doesn't do this, so you need to specify the initial value of the variable.
This has nothing to do with the way the for loop determines when to begin and end. It's about how to correctly add the numbers along the way.
It doesn't have to be before the p assignment, but it needs to be before the for loop.
Also, the line
p.innerHTML = "Result = " + sum;
doesn't need to be inside the loop. You should wait until the loop is done.

Is it Possiable to call to previous increments of a variable?

for example lets say i have a loop that is doing basic counting, while the variable is less than 16 the loop will run and at the end of the loop you add 2 to the variable and add one to a "count" variable
what i want to know is if its possible to callback to any of the previous variables for either variable for example can i count all the times count % 2 === 0?
im not quite sure if once a variable makes any kind of change if all previous versions of that variable are gone
http://codepen.io/anon/pen/Gojoxm
var two = 0;
var count = 0;
while ( two < 16) {
two += 2;
count++;
};
console.log(count);
If I understand you right, then no, you cannot. When you assign a new value to a variable, the previous value is lost.
You have to either run this loop again or store intermediate values in an array:
var values = [];
var two = 0;
while (two < 16) {
two += 2;
values.push(two);
}
console.log(values.length); // the same result
Then, you will always be able to do whatever you want with these values.
For example, you can check if there were any odd values:
var anyOddNumbers = values.some(function(x) { return x % 2 === 1; }); // false

Categories