Choosing a random value from an array gives undefined - javascript

When I Input the first number to be for example 5 and the second Number to be like 10 I get undefined. I tried alert(array); to see the contents of it but there was nothing and hence undefined. It works for other numbers like 1 to 9. Why does it give me an undefined value from range 5 to 10? I just want to make a random number chooser where you will input the first number and the second number and a random number will be given to you?
function promptUser() {
var first = prompt("First number?");
var second = prompt("Second number?");
var array = [];
//Make a range from First number to last number then choose a random number
for (x = first; x <= second; x++) {
array.push(x);
}
alert(array);
randomInt = Math.floor(Math.random() * array.length);
alert("The random number is " + array[randomInt]);
}

prompt() returns the result in string literal, you need to use parseInt() or other methods to convert string to Number.
var first = parseInt(prompt("First number?"), 10);
var second = parseInt(prompt("Second number?"), 10);
var array = [];
for (x = first; x <= second; x++) {
array.push(x);
}
randomInt = Math.floor(Math.random() * array.length);
console.log(array, randomInt, "The random number is " + array[randomInt]);
Additionally, alert() is not a debugging tool, Learn to use Console

your first number is being treated as string needed to be parsed as int
function promptUser(){
var first = prompt("First number?");
var second = prompt("Second number?");
var array = [];
<!--Make a range from First number to last number then choose a random number-->
for (x = parseInt(first); x <= parseInt(second); x++){
array.push(x);
}
console.log(array);
randomInt = Math.floor(Math.random()*array.length);
console.log(randomInt);
alert("The random number is " + array[randomInt]);
}
promptUser();

Use:
var first = parseInt(prompt("First number?"));
var second = parseInt(prompt("Second number?"));
instead of:
var first = prompt("First number?");
var second = prompt("Second number?");
prompt returns string

Related

Sum the number equivalent of alphabets in a word until it's single digit? [duplicate]

This question already has answers here:
Sum up a number until it becomes 1 digit JS
(16 answers)
Closed 3 years ago.
I am trying to solve a problem where a user gives a text input then I have to convert the text into given numeric values, add them together unless the answer is a single digit number.
So far, I have been able to get input, transform them into given numbers and store them in an array. But I cannot figure out what I will do next. How I will add the values together until it is left a single digit number.
var values = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10,k:11,l:12,m:13,n:14,o:15,p:16,q:17,r:18,s:19,t:20,u:21,v:22,w:23,x:24,y:25,z:26};
var someText = prompt('');
someText = someText.trim();
someText = someText.match(/\S/g);
var result = "";
for (i = 0; i < someText.length; i++) {
result += values[someText[i]];
}
alert(result);
For Example if input is "action" then numeric values will be
=>1.3.20.9.15.14.
-Add these values together.
1+3+20+9+15+14 answer will be 62.
-As the Answer is a 2 digit number, we add the numbers again
e.g 62 = 6+2= 8.
Note:
If answer is more then 1 digits: e.g 199 => 1+9+9 => 19 => 1+9 => 10 = 1+0 = 1.
Answer must always be a single digit number.
You can use reduce() to get the sum of all the digits of string. If the result is single digit then return the the number otherwise call the function recursively.
You also don't need to hard code the object with letter values. Just use reduce() and chatCodeAt to make a string of numbers.
var someText = prompt('').trim().toLowerCase().match(/\S/g)
let result = someText.reduce((ac,a) => ac + (a.charCodeAt(0) - 96),'');
function findSum(num){
if(num.length === 1) return num;
else return findSum(String(num.split('').reduce((ac,a) => ac + +a,0)))
}
console.log(findSum(result))
Here's how you can do it:
var values = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10,k:11,l:12,m:13,n:14,o:15,p:16,q:17,r:18,s:19,t:20,u:21,v:22,w:23,x:24,y:25,z:26};
var someText = prompt('');
someText = someText.trim();
someText = someText.match(/\S/g);
var result = "";
for (i = 0; i < someText.length; i++) {
result += values[someText[i]];
}
// While the result is >9, which means that there's more than 1 digit
while(result > 9) {
// Cast result as String, so we can use charAt()
var stringedResult = String(result);
// Reset our result var, because we're going to recalculate it
result = 0;
// For each int in our result, we add them up (ex. 621 = 6+2+1)
for(var i=0; i<stringedResult.length; i++) {
// Cast the stringed result back to a number, and add it to our result variable
result += Number(stringedResult.charAt(i));
}
}
alert(result);
You should use a function to sum the values and return the value when it's one digit or call itself otherwise:
var values = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10,k:11,l:12,m:13,n:14,o:15,p:16,q:17,r:18,s:19,t:20,u:21,v:22,w:23,x:24,y:25,z:26};
var someText = prompt('');
someText = someText.match(/\S/g);
var result = 0;
function getSum(string) {
for (i = 0; i < string.length; i++) {
if (isNaN(string[i])) {
result += values[string[i]];
} else {
result += parseInt(string[i]);
}
}
if (result.toString().length > 1) {
var aux = result.toString();
result = 0;
return getSum(aux);
} else {
return result;
}
}
alert(getSum(someText));

Index of each CharAt and multiplying each index number

I am trying to multiply each every index number together and seems like parseInt also return a decimal in the end...Not sure why?
var decNum = "12312312312312";
if( decNum.length == 14)
{
var lastnum = decNum.charAt(13);
var newNum = parseInt(decNum)/14; // rather 1231231231231 it shows 1231231231231.2 should be 13 nums left without last digit in int.
var validNum = [1,7,4,2,8,7,3,2,1,2,3,4,1,3];
var sum;
for (var i = 0; i < validNum.length; i++) {
//since I can't use charAt for for INT so parse to string and parse it back to int to do the math.
sum += parseInt(validNum[i]) * parseInt(String(newNum.charAt(i)));
}
parseInt returns a number, so var newNum = parseInt(decNum)/14; results in newNum being a number, not a string. So, you can't use charAt on a number - you want the string. You have decimals because when you divide an integer (decNum) by 14, the result is a continuing decimal.
If you want to use explicit type conversions:
const newNum = String(parseInt(decNum / 14));
You don't need to parseInt the elements of validNum since they're already integers.
Your sum is not initialized to 0, so subsequent sum += lines will fail.
Even after fixing that, it would still be more elegant to use array methods to iterate over the string, though:
const decNum = "12312312312312";
if( decNum.length == 14) {
const newNum = String(parseInt(decNum / 14));
const validNum = [1,7,4,2,8,7,3,2,1,2,3,4,1,3];
const charCodeArr = newNum.split('').map(char => char.charAt(0));
const sum = charCodeArr.reduce((sumSoFar, charCode, i) => {
return sumSoFar + (charCode * validNum[i]);
}, 0);
console.log(sum);
}
everything works fine now, thanks, everyone.
var decNum = "12312312312312";
if( decNum.length == 14)
{
var lastnum = decNum.charAt(13);
var newNum = String(parseInt(decNum)/14);
var validNum = [1,7,4,2,8,7,3,2,1,2,3,4,1,3];
var sum = 0;
for (var i = 0; i < validNum.length; i++) {
sum += parseInt(validNum[i]) * parseInt(newNum.charAt(i));
}

Random String Generator Javascript - While Loop

Trying to create a random letter generator with a "while" loop. It's return one value into the randomString and then quits the loop.
var alpha = "abcdefghijklmnopqrstuvwxyz";
var randomString = "";
while (randomString.length < 6) {
console.log(randomString += alpha.charAt(Math.floor(Math.random() * alpha.length)));
randomString++;
}
Returns one value from alpha string to randomString and then quits the loop instead of going on for 4 more loops - condition set at (randomString.length < 6).
Incrementing a string results in NaN, which doesn't have a length property, so the loop ends after one iteration.
Don't increment your randomString:
var alpha = "abcdefghijklmnopqrstuvwxyz";
var randomString = "";
while (randomString.length < 6) {
console.log(randomString += alpha.charAt(Math.floor(Math.random() * alpha.length)));
}
create a variable and set is an empty string. Then, create a while loop that will continually add new random letters to this string, as long as the string length is less than 6 or any length you choose. += operator to add a new letter to the end of the string.
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var randomString = "" // first, create an empty string
while (randomString.length < 6) {
console.log(randomString += alphabet[Math.floor(Math.random() * alphabet.length)]);
randomString++;
}

sum of uint8array javascript

I'm trying to sum and then average a stream of data, some code here.
var getAverage = function(dataArray){
var total,
sample = dataArray.length,
eArray = Array.prototype.slice.call(dataArray);
for (var i = 0; i< sample; i++) {
total+= eArray[i];
}
return total;
}
var output = function(){
//source data
var dataArray = new Uint8Array(bufferLength);
analyser.getByteTimeDomainData(dataArray);
var average = getAverage(dataArray);
$('#average').text(average);
window.requestAnimationFrame(output);
Every element in the array returns a number, but it still returns NaN. Help?
Set total = 0; currently it is defaulting to undefined. undefined + a number = NaN, and NaN + a number = NaN.
The declared variable total is undefined which means it will create NaN (Not-a-Number) when a number is added to it.
Also, Typed Array (ArrayBuffer/views) and Array are not the same, and converting a typed array to an ordinary Array is making iteration slower as typed arrays are actual byte-buffers while Arrays are (node) lists. That on top of the cost of conversion itself.
Just add them straight forward. Remember to divide the sum on length and of course to initialize total:
var getAverage = function(dataArray){
var total = 0, // initialize to 0
i = 0, length = dataArray.length;
while(i < length) total += dataArray[i++]; // add all
return length ? total / length : 0; // divide (when length !== 0)
}

Find greatest value in array (in set of integers)

My friend asked me to help him with homework, and I'm stuck. Here is assignment:
user must enter in first prompt box number of elements in array. Then, he will get prompt box for each number to enter. Now, output must be greatest number in array. But that simply doesn't work. With my code below, I always get the element who has greatest first digit. (it's doesn't matter if number is negative or positive, code doesn't work as it should)
Here is my code (it even doesn't work in jsfiddle, just in my file)
<button onclick="duzinaNiza()">Do it!</button>
and here is JavaScript
function duzinaNiza() {
var brClanova = prompt("Enter the number of array elements:");
if (brClanova > 0) {
var niz = new Array();
for (i=0; i<brClanova; i++) {
var redniBr = i+1;
niz[i] = prompt("Enter "+ redniBr +". array number:");
\\ prompt for geting each array element
}
var maximum = niz[0];
for (a=0; a<brClanova; a++) {
if (maximum < niz[a]) {
maximum = niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}
My friend's proffesor doesn't want to use functions for sorting arrays, this must be done with loops.
P.S. Yeah, I know... But don't ask about document.write thing, it must be printed in that way...
That is because the input is a String, you have to parse it to a Integer. Like:
niz[i] = parseInt(prompt("Enter "+ redniBr +". array number:"), 10);
Try this:
function duzinaNiza() {
var brClanova = prompt("Enter the number of array elements:");
if (brClanova > 0) {
var niz = new Array();
for (i=0; i<brClanova; i++) {
var redniBr = i+1;
niz[i] = parseInt(prompt("Enter "+ redniBr +". array number:"));
// prompt for geting each array element
}
var maximum = niz[0];
for (a=0; a<brClanova; a++) {
if (maximum < niz[a]) {
maximum = niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}
The problem is that you are comparing two strings, when you wanted to compare two numbers.
In other words, the following expression is LEGAL in javascript and evaluates to true:
if('4' > '393939393'){
//true! string '4' is greater than string '3' (first char of '393939393')
}
What you should do is cast the value received from the function prompt, so it is treated as a number. You can do that using the following function:
parseInt(prompt("Enter "+ redniBr +". array number:"), 10);
The first parameter is the value you want to cast to a number, while the second is the radix (or "base") of the number.
So, the main problem here is that you're not threat your numbers as "number", but as string. The method prompt returns a string, so you need to convert them:
function duzinaNiza() {
var brClanova = +prompt("Enter the number of array elements:");
if (!brClanova)
return;
var niz = [];
for (var i=0; i < brClanova; i++) {
var redniBr = i + 1;
niz[i] = +prompt("Enter "+ redniBr + ". array number:");
}
var max = niz[0];
for (var a = 1; a < brClanova; a++) {
if (max < niz[a])
max = niz[a];
}
document.write("Greatest value in array is: " + max);
}
I used the Unary Plus Operator for that.
Just for to know, in JS you can actually avoid the last loop using Math.max to get the maximum of an array of numbers. So instead of:
var max = niz[0];
for (var a = 1; a < brClanova; a++) {
if (max < niz[a])
max = niz[a];
}
document.write("Greatest value in array is: " + max);
You will have:
var max = Math.max.apply(null, niz);
document.write("Greatest value in array is: " + max);
In that case, you don't even need the unary plus operator because Math.max takes care of that.
try this out, [Tip: i just utilised the '+' operator for casting the value to number (values from prompt.). The '+' operator will return NaN, if the entered value could not get converted into a number. so in that situation, you should use isNan function to get rid of that.]
duzinaNiza = function () {
var brClanova = prompt("Enter the number of array elements:");
if (brClanova > 0) {
var niz = new Array();
var maximum;
for (i=0; i<brClanova; i++) {
var temp = +prompt("Enter "+ i+1 +". number:");
if(i===0) { maximum = temp }
else { maximum = (temp > maximum)?temp:maximum; }
}
alert("Greatest value in array is: " + maximum);
}
}
You don't need parseInt- if you subtract strings that can be converted to numbers, they are converted. So you can subtract the maximum from the next number, and see if it leaves a remainder.
Also, parseInt will destroy decimals, so you won't know that 1.5 is greater than 1.
Your comment used the wrong characters- `('\' should be '//')
function duzinaNiza(){
var brClanova= prompt("Enter the number of array elements:");
if(brClanova>0){
var niz= new Array();
for(var i= 0;i<brClanova;i++){
var redniBr= i+1;
niz[i]= prompt("Enter "+ redniBr +". array number:");
//prompt for geting each array element
}
var maximum= niz[0];
for(var a= 0;a<brClanova;a++){
if(niz[a]-maximum>0){
maximum= niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}
Modified Code JSFIDDLE
function duzinaNiza() {
var brClanova = prompt("Enter the number of array elements:")*1; //convert string to intger
if (brClanova > 0) {
var niz = new Array();
for (i=0; i<brClanova; i++) {
var redniBr = i+1;
niz[i] = prompt("Enter "+ redniBr +". array number:")*1;
// prompt for geting each array element
}
var maximum = niz[0];
for (a=0; a<brClanova; a++) {
if (maximum < niz[a]) {
maximum = niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}

Categories