JavaScript Nested While Loop, Loops infinitely - javascript

So I'm trying to create a loop that will reduce any number put into it to a single digit. The way I'm doing my math is adding each number up one by one. In this case 9+9+9+9+9+9+9+9+9+9+9+9=108. I want it to run through and check that 108 is still greater than 9 and do it till the result is less than 9. It just gets stuck in a loop. I've also tried some variants that will return NaN.
<html>
<body>
<h1>Reduce Loop</h1>
<p id="Result"></p>
<script type="text/javascript">
//Defined var start
var Result = 0;
var TempReduce1 = 0;
var LoopTempLength = 0;
var LoopTempString;
var i = 0;
//Defined var end
//The LongNumber variable represents user input
var LongNumber = 999999999999;
//Converts LongNumber to a integer
var LoopTemp = parseInt(LongNumber);
//Check if LoopTemp is greater than 9; it is
while (LoopTemp > 9) {
//Gets the Length of LoopTemp by converting it to a string and grabbing the length to then convert back to a integer
LoopTempLength = parseInt(LoopTemp.toString().length);
//Converts LoopTemp to a string for manipulation
LoopTempString = LoopTemp.toString();
i = 0;
//Check to see if i is less than the length of LoopTempLength
while (i < LoopTempLength) {
//Grabs the number in relationship to i, converts it to a integer and added it to TempReduce1
TempReduce1 += parseInt(LoopTempString.charAt(i));
i++;
}
LoopTemp = TempReduce1;
}
Result = LoopTemp;
document.getElementById("Result").innerHTML = Result;
</script>
</body>
</html>

So Patrick Evans has it right. I inserted
TempReduce1=0;
in your code after the line
i=0
and the routine kicked out 9 as one would expect.

Related

trying to make an lfsr in js

i'm trying to make an lfsr in js, on its head every thing is looking good, i'm using strings and im converting them back and forth to get the last bit, my problem is printing the number i'm trying to make a large hex number, my logic is give me a seed and a length and the function should generate a hex number in that length.
function lfsr(seed, length ){
var arr = Array.from(seed.toString(2));
result ="";
for (var i = 0; i < lenght; i++) {
let _last = parseInt(arr.pop());
let _blast = parseInt(arr[arr.length - 1])
let _newbit = _last ^ _blast;
arr.splice(0 , 0 ,_newbit.toString());
result += _newbit.toString();
}
return parseInt(result, 2).toString(16);
this is my code, i ran some tests and got a good output, but when i pring the answer i get this output:
be92231350d87800000000000
oh, and my input is this:
var ans = lfsr(6543123123798,100);
any idea how to get rid of the excess 0's and get what I need? thanks for your time.
i've changed the code to be :
function lfsr(seed, length,base){
var arr = Array.from(seed.toString(base));
var result ="";
for (var i = 0; i < length ; i++) {
let _newbit = parseInt(arr.pop(),16) ^ parseInt(arr[arr.length - 1],base);
arr.splice(0 , 0 ,_newbit.toString(base));
result += _newbit.toString(base);
}
return result;
}
and it solved my problem. any one is welcome to use it.

Searching for number inside of an array

Forgive me, I am not quite skilled and fairly new to the language and programming practices. I am creating a button which prompts the user to enter a number once the number is entered, I create a for loop that iterates through the same amount as the number. For example, the user enters 4 and the screen will display 0 1 2 3 and then I have a button that asks the user to enter a number to see if that number exists in the previous array. So if the user entered 3 it would dispay "it exists" if they entered 5 it would display "number not found". Should I create an array to store the iterations and then run that array through a function that searches for the number. Looking for guidance, thank you for the help guys.
function getNumber() {
var el = document.getElementById("demo");
// Get the user's input and convert it to a number
var n = parseInt(prompt("Please enter a number"),10);
// Set up a string that will become the output.
var output = " ";
// loop through given number
for(var i = 0; i < n; i++){
// variable containing iterations
output += i;
//var numArray[i] = output;
}
//display iterations
el.textContent = output;
}
function findNumber(){
var sn = parseInt(prompt("Search for number"),10);
for(var j = 0; j < sn; j++){
}
}
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
<button onclick ="findNumber()">Click!</button>
Make your n variable global
Than compare if sn is higher than n
var n; // Make it global
function getNumber() {
var el = document.getElementById("demo");
// Get the user's input and convert it to a number
n = parseInt(prompt("Please enter a number"), 10);
// Set up a string that will become the output.
var output = " ";
// loop through given number
for (var i = 0; i < n; i++) {
// variable containing iterations
output += i;
//var numArray[i] = output;
}
//display iterations
el.textContent = output;
}
function findNumber() {
var sn = parseInt(prompt("Search for number"), 10);
var isHigher = sn > n; // n is now accessible in this function
var message = isHigher ? "Not found" : "Number found!";
alert( message );
}
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
<button onclick="findNumber()">Click!</button>
To search an array, use the indexOf() method of a JavaScript array. The original post gives an example populating the array with myArray[x]=x, creating options pointed out by other solutions. Presuming you want to search a more general case of an array, you could use indexOf directly or define a function that returns true or false:
function inArray(myArray, queryValue) {
return myArray.indexOf(queryValue) > -1;
};
Arrays in JavaScript are objects with some additional methods like pop(), indexOf(), etc. JavaScript objects are associative arrays; this solution only applies to Array objects. Array objects are constructed with the [] literal or the Array() constructor. Arrays can only have properties named by ints, unlike other JavaScript associative arrays. See Eloquent JavaScript.
In this theoretic example, it's true that you only need to check if the second number entered is smaller than the first number. If you want to search for a number in an array of any numbers, you can use the javascript indexOf function. See example below:
var arr = [1,6,77,888];
if (arr.indexOf(66) > -1) {
alert('number is in array');
} else {
alert('number is not in array');
}
There are a couple of ways to do this. For the sake of simplicity, I'll use a global variable here.
// A global variable to store user input
var userInput;
function getNumber() {
var el = document.getElementById("demo");
// Get the user's input and convert it to a number
var n = parseInt(prompt("Please enter a number"),10);
// Store the user's input to our global variable
userInput = n;
// Set up a string that will become the output.
var output = " ";
// loop through given number
for(var i = 0; i < n; i++){
// variable containing iterations
output += i;
//var numArray[i] = output;
}
//display iterations
el.textContent = output;
}
function findNumber(){
var el = document.getElementById("result");
var sn = parseInt(prompt("Search for number"),10);
// If number is within the range
if (sn < userInput) {
el.textContent = "it exists";
}
// If number is not within the range
else {
el.textContent = "number not found";
}
}
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
<button onclick ="findNumber()">Click!</button>
<p id="result"></p>

Generate 7 unique random numbers in javascript

I have a project i'm working on.
I am to basically recreate lotto on the client side using javascript to generate 6 random numbers plus a bonus ball. as we all know, lotto numbers cannot be the same. this is where my question comes in.
Is it possible to remove a number that has been generated from being available in the next time round in the loop? This would make the function completely random. or do I need to still compare the number with the others in the array using indexOf?
for example, is the following possible?,
the first number that generates is 25,
the function then removes that number from being able to come up again.
so on...
Here is my js code,
function play(){
numbersArray = [];
for (i=0; i<=6;){
n = Math.floor(Math.random()*40)+1;
a = numbersArray.indexOf(n);
if ( a == "-1"){
numbersArray[i] = n;
i++;
var ballId = "ball"+i;
if( i != "7"){
document.getElementById(ballId).innerHTML = '<p>'+ n +'</p>';
} else {
document.getElementById("bonus").innerHTML = '<p>'+ n +'</p>';
}
} //end of if
}//end of for loop
}//end of play function
You need to create an object, in this case you could use an array, that holds all the possible numbers that can appear on the ball, we'll cal it n. Then you can use a while loop to keep picking numbers from that array, and splice/remove that specific number from the array on every iteration.
function play(n) {
var picks = [];
// Store possibilities in the numbersArr array
var numbersArr = [];
// n is the max number you can choose to appear on a ball
for ( var i = 0; i < n; i++ ) {
numbersArr.push(i);
}
while (picks.length < 7){
var randomIndex = Math.floor(Math.random() * numbersArr.length);
picks.push(numbersArr[randomIndex]);
numbersArr.splice(randomIndex, 1);
}
return picks;
}

Finding Products within large Digits

I have been working on a way to find products of 5 digits within a large number. For example, I have the number 158293846502992387489496092739449602783 And I want to take the first 5 digits (1,5,8,2,9) and multiply them, then the second, (5,8,2,9,3), multiply then, then the third... And so on. Then I want to find the largest of all of them I find, now I came up with the following code to solve this problem:
// I put the digit into a string so I can modify certain parts.
var digit = "158293846502992387489496092739449602783";
var digitLength = digit.length;
var max = 0;
var tempHolder;
var tempDigit = 0;
var tempArray = [];
for(var i = 0; i<=digitLength; i++){
tempHolder = digit.substring(i, i+5);
tempArray = tempHolder.split("");
for(var j = 0; j < 5; j++){
tempDigit += tempArray[j];
}
if(tempDigit > max){
max = tempDigit;
}
}
console.log(max);
It logs to the console A longer number than what I put into it, along with 10 undefined, no spaces. Can anyone figure out the problem here?

javascript storing array values

Im trying to get the total combined value of a set of numbers.
Im getting the numbers as the text in an element tag storing them in an array then adding them all together. My problem is that its not inserting the numbers into the array as pairs.. it adding them as single integers .what am doing wrong.
check the jsfiddle too see example
http://jsfiddle.net/Wd78j/
var z = $('.impressions').text();
var x = [];
for(var i = 0; i < z.length; i++){
x.push(parseInt(z[i]));
}
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
When you get text, it's taking all the numbers and concatenating them into a string. The below takes each element one at a time and pushes it.
var x = [];
$('.impressions').each( function( ) {
var z = $(this).text();
x.push(parseInt(z, 10));
})
Of course, you could build the sum up inside that each function, but I did it like this to more closely mirror your code.
text() returns the concatenated text of all of your impressions elements, of which you're adding together each character.
You want to loop through each impressions element, and keep a running sum going. Something like this should work
var sum = 0;
$('.impressions').each(function(){
sum = sum + (+$(this).text());
});
Updated Fiddle
Or to keep your original structure (don't forget the radix parameter to parseInt):
var z = $('.impressions');
var x = [];
z.each(function(){
x.push(parseInt($(this).text(), 10));
});
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
Updated fiddle
You are iterating over a string, you could just use $.map to build the array instead, if you need it, otherwise just iterate and sum up the values :
var x = $.map($('.impressions'), function(el,i) {return parseInt($(el).text(), 10);}),
total = 0,
n = x.length;
while(n--) total += x[n] || 0;
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
FIDDLE

Categories

Resources