Make an array in java script with window.prompt() - javascript

I try to make an Array in javascript with number of elements and elements inputted by user through window.prompt().
This is what i got by now :
var n = window.prompt("Insert number of numbers", "")
var nr = new Array(n)
for (i = 0; i < n; i++) {
nr[i] = window.prompt("Number: ", "")
}
for (i = 0; i < n; i++) {
if ((i + 1) % 2 != 0) {
if (nr[i] % 2 == 0)
document.write("Even numbers on odd position are: ", nr[i], "<br/>")
}
}
document.write("The numbers are :")
for (i = 0; i < n; i++) {
document.write(nr[i] + "<br/>")
}
On web page shows nothing.

Defining elements.
The first thing in your code is that you should define an array as this:
var numbers = [];
In this array, you will handle every element you will receive from the prompt. So, with this said, you just need the total amount of numbers that you will use which can be retrieved by doing a prompt for a number:
var times = window.prompt("Insert number of numbers: ");
So, times would be our variable containing the amount of numbers we should ask the user, which will be saved on numbers.
Asking user for numbers X amount of times.
Now, what you could do is just a simple for loop which only job is to push the new number provided by the user:
for (let i = 0; i < times; i++) {
numbers.push(window.prompt(`Number ${i+1}: `))
}
This will give the user a prompt saying Number X:, which means the number that is being added.
Checking numbers for even and odds.
And for your functionality of giving a message when there is an even number in an odd index, you could do this:
numbers.forEach((n,i)=>{
if(n%2===0 && i%2!=0){
document.write(`Even number ${n} in odd position ${i} <br/>`);
}
});
Which will check every number you received from the user and check in one inline condition if even number is in odd position and will output the line only if this condition is true.
Printing the numbers.
And simply to output every number you can do:
numbers.forEach((n)=>{
document.write(n + "<br/>")
});
See how it works:
var times = window.prompt("Insert number of numbers"), numbers = [];
for (let i = 0; i < times; i++) {
numbers.push(window.prompt(`Number ${i+1}: `))
}
numbers.forEach((n,i)=>{
if(n%2===0 && i%2!=0){
document.write(`Even number ${n} in odd position ${i} <br/>`);
}
});
document.write("The numbers are: <br/>")
numbers.forEach((n)=>{
document.write(n + "<br/>")
});

Related

Getting average number of an array , breaks if one of them is -1 on JS

I'm resolving some problems given at college but I canĀ“t figure out this one.
The exercise goes like this :
Create a program where users enter numbers until they enter "-1", in this case, the program breaks and prints the average of the numbers entered.
I've written this on JS
array=[];
for( var i =0; i<3; i++){
val = parseInt(prompt( "Insert your numbers: "));
array.push(val)
}
function insert (array){
var sum = 0;
array.forEach(num=>{
sum+= (num) / array.length;
})
return sum
}
console.log( "Average is " + Math.round(insert(array)))
I tried to write:
if (val == -1){
breaks;
}
But it just breaks everything. I know maybe there is a simplier way to solve it and probably I'm still strugling with logic in loops. The thing is that the promps has to stop looping if the user inserts -1.
Thanks in advance!
How about this:
array = [];
while((val = parseInt(prompt( "Insert your numbers: ")))!=-1)
{
array.push(val)
}
function avg (array){
var sum = 0;
array.forEach(num=>{
sum += num;
})
return array.length ? sum / array.length : 0;
}
console.log( "Average is " + Math.round(avg(array)))
let numbers = [];
let val, sum, result
askForInput();
function askForInput(){
val = parseInt(prompt("Pls enter a number: "));
if(val == (-1)){
result = getAverage(numbers);
console.log("Result is: " + result);
} else {
askForInput();
}
}
function getAverage(array){
if(array.length == 0) return 0;
for(let i = 0; i < array.length; i++){
sum += array[i];
}
return sum / array.length;
}
An example using recursion
I would change the for loop to while so that the loop will only terminate if the user puts in -1 (the way you have it written currently, the for loop will terminate once the user has entered 3 numbers). If you initialize a variable before the while loop that changes to equal the user input, then you can even handle the logic in the loop definition.
EX:
array = [];
user_input = 0;
while (user_input != -1 ) {
user_input = parseInt(prompt( "Insert a number: "));
array.push(user_input)
}
This code should continually prompt the user until they enter -1 at which point the while loop would stop.

User Input is not storing correctly in array

Im given the task of storing 10 elements in an Array, then I have to add all of those elements.
My problem comes at the time of storing each individual element in the array.
When I set the length of the for loop as numbers.length it fills the array with the first number that was inputted, and if I set the length to 10, it only places the value in the index[0] and leaves the others as undefined.
var numbers = new Array();
function addnew() {
var un = document.getElementById('userNumber').value;
for (var i = 0; i < 10; i++) {
numbers.push(" " + un[i]);
}
console.log(numbers);
document.getElementById('elements').innerHTML = numbers;
The output that is expected is a list that shows the values entered by the user inputs into the array (length of 10) and the sum of those values.
What it's actually showing is the first number inputted followed by undefined till it reaches the maximum length which is 10.
it's because un string length is 1 as it not saved completely
var numbers = new Array();
function addnew() {
var un = '123';
for (var i = 0; i < Math.min(10,un.length); i++) {
numbers.push(" " + un[i]);
}
console.log(numbers);
document.getElementById('elements').innerHTML = numbers;
}
}
If your user is entering a space inbetween each number, you can just split that one string into an array.
numbers = un.split(" ");
numbers now contains an array of strings.
Then convert the strings to numbers, so you can get the sum.
for (var i = 0; i < numbers.length; i++) {
numbers[i] = Number(numbers[i]);
}
And then this will give you the sum.
sumOfNumbers = numbers.reduce((a, b) => a + b, 0);
console.log(sumOfNumbers);
un = "1 2 3 12";
numbers = un.split(" ");
console.log(numbers);
for (var i = 0; i < numbers.length; i++) {
numbers[i] = Number(numbers[i]);
}
console.log(numbers);
sumOfNumbers = numbers.reduce((a, b) => a + b, 0);
console.log("sum is " + sumOfNumbers);
At beginning your numbers.length is 0. I think you should do un.length
function addnew() {
var numbers = [];
var un = document.getElementById('userNumber').value;
for (var i = 0; i < un.length; i++) {
numbers.push(" " + un[i]);
}
console.log(numbers);
document.getElementById('elements').innerHTML = numbers;
}
<input type="text" id="userNumber" onChange="addnew()"/>
<span id="elements"></span>

How come it doesn't slice a number until the end despite including the number's length

I made a code to extract every odd numbers from one number, and it works for numbers that are not too long such as "1341" (which give me the numbers "1,13,1341,341,41,1") but oddly doesn't work for very long numbers.
function solve(s) {
var newarray = [];
for (var i = 0; i <= s.length; i++) {
for (var j = 0; j <= s.length; j++) {
var slicing = s.slice(i, j);
if (slicing % 2 !== 0) {
newarray.push(slicing);
}
}
}
return newarray.length;
}
Despite putting s.length, it slices until a certain point. For example:
With "93711892377292643581488317", it slices until "9371189237729", then when it starts from 3 it slices until "93711892377292643" (until the next odd number)
With "65266112954758467", from the start it slices until "6526611295475", then when it starts from 5, it slices until "65266112954758467" (until the next odd number).
What's going on?
slicing % 2 doesn't work properly when slicing is large. Javascript treats large numbers as floating-point numbers, which means it's not accurate to know the value to the nearest integer - in binary, the units bit becomes 0, so it's a multiple of 2.
You want to count all odd numeric substrings within a numeric string.
First, consult the documentation of str.slice(beginIndex[, endIndex]).
Then, in order to gain a better understanding of your code, it is helpful to slowly iterate through a few steps of your loops and write down the expected vs. the observed output.
I recommend to use the debugger built into all modern browsers:
Add a debugger; statement into the inner for-loop:
function solve(s) {
var newarray = [];
for (var i = 0; i <= s.length; i++) {
for (var j = 0; j <= s.length; j++) {
var slicing = s.slice(i, j);
debugger; // <-- we want to break here and check our values
if (slicing % 2 !== 0) {
newarray.push(slicing);
}
}
}
return newarray.length;
}
Press [F12] and run this code in your browser's console for some exemplary input.
The debugger tab should now pop up. Press [F8] to step through your code and keep track of the value of your slicing variable.
You will probably notice that slicing is empty at the beginning. You should start your inner loop from j = i + 1 to fix that.
Also, you might notice that your i iterates one time too many, so that slicing is empty during the final iterations of the inner for-loop. You need to terminate your outer loop one step earlier.
Then, for the problematic input "93711892377292643581488317" you will notice that large numeric slices such as "93711892377292643" will not be recognized as odd. "93711892377292643" % 2 evaluates to 0 instead of 1. In order to understand this, you need to know that JavaScript numbers are internally represented as limited precision floating point values. If you put 93711892377292643 into your browser console, it will evaluate to 93711892377292640 - an even number! JavaScript can only handle integer numbers up to Number.MAX_SAFE_INTEGER == 9007199254740991 without introducing such truncation errors.
Now, how to solve this issue? Well, a number is odd if and only if the last digit is odd. So we don't have to inspect the full number, just the last digit:
function solve(s) {
var newarray = [];
for (var i = 0; i < s.length; i++) {
for (var j = i; j < s.length; j++) {
var digit = s.slice(j, j + 1);
if (digit % 2 !== 0) {
var slicing = s.slice(i, j + 1);
newarray.push(slicing);
}
}
}
return newarray.length;
}
console.log(solve("1234567890")); // 25
Once you have sufficient understanding of this code, you could start improving it. You could for example replace the newarray with a simple counter, as you are only interested in the number of off digits, not the digits themselves.
A faster solution could be written down as follows:
function solve(str) {
let count = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] % 2) count += i + 1;
}
return count;
}
console.log(solve("1234567890")); // 25
Or, written in a more declarative way:
const solve = (str) =>
str.split('').reduce((count, chr, i) => chr % 2 ? count + i + 1 : count, 0);
console.log(solve("1234567890")); // 25

JS for Kids Hangman game

I don't know what the [i] in answerArray[i] does/means. If someone could explain what it does it would mean a lot. This code came from the book "JavaScript for kids" and I'm trying to get started with just any kind of coding
var words = [
"money",
"pillow",
"maracas"
];
var word = words[Math.floor(Math.random() * words.length)];
var answerArray = [];
Here
for (var i = 0; i < word.length; i++) {
*answerArray[i] = "_";*
}
var remainingLetters = word.length;
while (remainingLetters > 0) {
alert(answerArray.join(" "));
var guess = prompt("Guess a letter, or click cancel to stop playing.");
if (guess === null) {
break;
} else if (guess.length !== 1) {
alert("Please enter a single letter.");
} else {
And here
*for (var j = 0; j < word.length; j++) {
if (word[j] === guess) {
answerArray[j] = guess;*
remainingLetters--;
}
}
}
}
alert(answerArray.join(" "));
alert("Good job! The answer was " + word);
Here's an example
https://www.w3schools.com/js/tryit.asp?filename=tryjs_loop_for_ex
The letters i or j or litterally anything put in that slot when you write for (i = 0; i < 5; i++) represents the current itteration. This is thing called a for loop and you should definitely get to know it if you are just getting started with javascript.
The letter, in short, represents the current itteration of the loop.
for (i = 0; i < 5; i++) { }
What this loop is saying is first i = 0. the variable "i" is 0. Then it says i < 5. This part is the "test". If the test passes, the loop with run again. Then it says i++. This is something that happens after the loop has been run. In this example it increases i with 1.
What happens inside { } will occure 5 times, and the letter i will increase in value, representing the "current loop".
In the demo i linked, you see that the sentence "The number is x" appears in increasing order, starting with 0.
The loop essentially means "While i is less than 5, do this" and the i increases in value each loop and the test inside () is rerun.
In arrays, each slot is represented by a number. MyArray[1] refers to the second item in the array.
If you have an array like this var myArray = ["fi", "fa", "fo"] then you can write console.log[2] to print the third item.
Lets combine this knowledge like this!
var myArray = ["fi", "fa", "fo"];
for (i = 0; i < 3; i++) {
alert(myArray[i]);
}
The for-loop is run 3 times, and each time it is run, i has a bigger value. This lets us refer to every item in the array. A better loop to write would be for(var i = 0; i < myArray.length; i++. This makes us compare i to the size of your array, so the array can be any size it wants to be
1 > the answer array initially empty array=[];
2 > then words[Math.floor(Math.random() * words.length)] this will return a
random string from words array .
3 > then the for loop is just counting the number of characters present in the
selected word and that same time number of _ is inserted in answers Array
4 > then this will just joining all the underscores and make a single string (with in the spaces).
eg -> word "pillow" is selected
then answers Array= ['_','_','_','_','_','_']
then answerArray= "_ _ _ _ _ _" ( Join with spaces).
Thanks.

the if statement condition logic

I am in need of help in this script. I am trying to write a program, where each array element is assign to a "point". I concated all the arrays and assigned it to a variable. The array runs through an if statement to tally up the score.
For this instance, I am trying to get a total of 6. However, when I run the program I am getting "2" rather than "6" in the console log. How should I write my if condition to get the result of 6?
var zero = [1,2,3,5,7]; // 0
var one = [0,4,6,9]; // 1
var two = 8; //2
function calculate(){
var NUMBERS = zero.concat(one,two);
var TOTAL = 0; // 6
for(var i = 0; i < NUMBERS.length; i++){
if(NUMBERS[i] === one[i]){
TOTAL += 1;
}else if(NUMBERS[i] == two){
TOTAL +=2;
}else {
TOTAL += 0;
}
}
console.log(TOTAL);
}
calculate();
This will only match if the value in NUMBERS[i] is in the same position of the array one.
if(NUMBERS[i] === one[i]){
Change it to this:
if (one.indexOf(NUMBERS[i]) !== -1){
to test for the presence of NUMBERS[i] in one.
Also, you have a four in both the zero and one array.
As #TJCrowder mentioned - the answer is seven.
You can omit:
TOTAL += 0
Adding zero doesn't change anything.

Categories