I'm only learning to program and was trying to make a program to count in binary.
I made a function that could convert the provided decimal to binary and it looks to be working just ok, but when I try to count upwards using a for loop my browser freezes and I can't understand why. Using a similar while loop produces the result I needed.
The problem is right at the bottom commented out. Please help figure out what I'm doing wrong here.
Here's my code:
function isOdd(num) {return num % 2};
var toBinary = function (number) {
ints = [];
binary = [];
ints.push(Math.floor(number));
while (number >= 1) {
number = (Math.floor(number))/2;
ints.push(Math.floor(number));
}
for (i=ints.length-1;i>=0;i--) {
if (isOdd(ints[i])) {
binary.push(1);
} else {
binary.push(0);
}
}
if (binary[0] === 0) {
binary.splice(0,1);
}
return binary;
};
var count = 0;
while (count <= 50) {
console.log(toBinary(count));
count++;
}
/*
for (i=1;i<=50;i++) {
console.log(toBinary(i));
}
*/
Use for (var i=ints.length-1;i>=0;i--) and for (var i=1;i<=50;i++), otherwise i will be a global variable and it will be overwritten inside toBinary.
You haven't declared i in the toBinary function, hence i is redefined on every call of toBinary in the last loop, and i will never reach 50.
Use var to declare variables like so:
var toBinary = function (number) {
var ints = [],
binary = [],
i;
:
}
Related
I'm generating random numbers, pushing them to an array, and then looping over the array to reference each number in turn.
What I'd like to be able to do is generate the numbers continually (within reason! Say, up to 500 iterations, for example), but always keep just 5 numbers in the array.
I've tried pushing the new numbers to the array and then shifting the array, but something's not working. My current code is:
let initArray = [];
function makeArray() {
do {
let val = Math.floor(Math.random() * 9)
initArray.push(val)
i++
}
while (i < 500)
}
function shiftArray() {
if (initArray.length > 5) {
initArray.shift();
}
}
I'm a beginner, so I'm sure I've missed something basic, but I'd love to know what it is!
Thank you so much!
There were two problems:
A: i was not defined
B: you weren't calling shiftArray().
let initArray = [];
i=0; // define i
function makeArray() {
do {
let val = Math.floor(Math.random() * 9)
initArray.push(val);
shiftArray(); //call shiftArray
console.log(initArray);
i++;
}
while (i < 100) //reduced to prevent computers from screaming
}
function shiftArray() {
if (initArray.length > 5) {
initArray.shift();
}
}
makeArray();
I am doing a coding challenge that reads like this:
Create a function runningAverage() that returns a callable function object. Update the series with each given value and calculate the current average.
rAvg = runningAverage();
rAvg(10) = 10.0;
rAvg(11) = 10.5;
rAvg(12) = 11;
I got a working solution, yet they also want the results to be rounded like this:
rAvg(13) = 13.50678; => 13.50
rAvg(13) = 13.50; => 13.50
rAvg(13) = 13.5; => 13.5
rAvg(13) = 13; => 13
Here is my code:
function runningAverage() {
let number = 0;
let numbOfFunctionCalls = 0;
return function (y) {
number += y;
numbOfFunctionCalls ++;
let average = (number/numbOfFunctionCalls);
let averageArray = average.toString().split('.');
//to get the number of decimal places
//e.g 11.543 ==> ['11', '543']
if ((Array.from(averageArray[1]).length) >= 2) {
return average.toPrecision(2);
}
else if ((Array.from(averageArray[1]).length) = 1) {
return average.toPrecision(1);
}
else {
return average;
}
}
}
I tested parts of the function separately and it seems to work, yet when I invoke it I get the message 'cannot convert undefined or null to object'.
This sounds like a fun coding challenge!
In this case, you want toFixed(), not toPrecision(). toPrecision() essentially allows you determine how many digits TOTAL (including those on the left of the decimal point) should appear, whereas toFixed() focuses on the number of digits to the right of the decimal point. Feel free to look these two methods up on MDN. When you read that toPrecision() may return exponential notation, this should make you pause and think, "That's weird. Why does this happen? When does this happen?", rather than "this detail is unimportant."
Your .length = 1 comparison needs to be modified to a ===.
Your code currently fails if an integer is the first number provided to rAvg(). In your first conditional, Array.from(undefined) may run, which is not permissible in JavaScript. You should consider ways to only work with "the digits to the right of the decimal" only if "there are digits to the right of the decimal."
Here is a working solution including all the suggestions, in case someone is interested:
function runningAverage() {
let number = 0;
let numbOfFunctionCalls = 0;
return function (y) {
number += y;
numbOfFunctionCalls ++;
let average = (number/numbOfFunctionCalls);
let numIsDecimal = average.toString().includes('.');
if (numIsDecimal) {
let averageArray = average.toString().split('.');
//to get the number of decimal places
//e.g 11.543 ==> ['11', '543']
if ((Array.from(averageArray[1]).length) >= 2) {
return Number(average.toFixed(2));
}
if ((Array.from(averageArray[1]).length) === 1) {
return Number(average.toFixed(1));
}
}
else {
return Number(average);
}
}
}
Not sure if this works but try it
function runningAverage() {
let number = 0;
let numbOfFunctionCalls = 0;
return function (y) {
number += y;
numbOfFunctionCalls ++;
let average = (number/numbOfFunctionCalls);
let averageArray = average.toString().split('.');
if ((Array.from(averageArray[1]).length) >= 2) {
return Math.round(average.toPrecision(2) * 2) / 2;
} else if ((Array.from(averageArray[1]).length) == 1) {
return Math.round(average.toPrecision(1) * 2) / 2;
} else {
return Math.round(average * 2) / 2;
};
};
};
Can't seem to find an answer to this, say I have this:
setInterval(function() {
m = Math.floor(Math.random()*7);
$('.foo:nth-of-type('+m+')').fadeIn(300);
}, 300);
How do I make it so that random number doesn't repeat itself. For example if the random number is 2, I don't want 2 to come out again.
There are a number of ways you could achieve this.
Solution A:
If the range of numbers isn't large (let's say less than 10), you could just keep track of the numbers you've already generated. Then if you generate a duplicate, discard it and generate another number.
Solution B:
Pre-generate the random numbers, store them into an array and then go through the array. You could accomplish this by taking the numbers 1,2,...,n and then shuffle them.
shuffle = function(o) {
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
var randorder = shuffle([0,1,2,3,4,5,6]);
var index = 0;
setInterval(function() {
$('.foo:nth-of-type('+(randorder[index++])+')').fadeIn(300);
}, 300);
Solution C:
Keep track of the numbers available in an array. Randomly pick a number. Remove number from said array.
var randnums = [0,1,2,3,4,5,6];
setInterval(function() {
var m = Math.floor(Math.random()*randnums.length);
$('.foo:nth-of-type('+(randnums[m])+')').fadeIn(300);
randnums = randnums.splice(m,1);
}, 300);
You seem to want a non-repeating random number from 0 to 6, so similar to tskuzzy's answer:
var getRand = (function() {
var nums = [0,1,2,3,4,5,6];
var current = [];
function rand(n) {
return (Math.random() * n)|0;
}
return function() {
if (!current.length) current = nums.slice();
return current.splice(rand(current.length), 1);
}
}());
It will return the numbers 0 to 6 in random order. When each has been drawn once, it will start again.
could you try that,
setInterval(function() {
m = Math.floor(Math.random()*7);
$('.foo:nth-of-type(' + m + ')').fadeIn(300);
}, 300);
I like Neal's answer although this is begging for some recursion. Here it is in java, you'll still get the general idea. Note that you'll hit an infinite loop if you pull out more numbers than MAX, I could have fixed that but left it as is for clarity.
edit: saw neal added a while loop so that works great.
public class RandCheck {
private List<Integer> numbers;
private Random rand;
private int MAX = 100;
public RandCheck(){
numbers = new ArrayList<Integer>();
rand = new Random();
}
public int getRandomNum(){
return getRandomNumRecursive(getRand());
}
private int getRandomNumRecursive(int num){
if(numbers.contains(num)){
return getRandomNumRecursive(getRand());
} else {
return num;
}
}
private int getRand(){
return rand.nextInt(MAX);
}
public static void main(String[] args){
RandCheck randCheck = new RandCheck();
for(int i = 0; i < 100; i++){
System.out.println(randCheck.getRandomNum());
}
}
}
Generally my approach is to make an array containing all of the possible values and to:
Pick a random number <= the size of the array
Remove the chosen element from the array
Repeat steps 1-2 until the array is empty
The resulting set of numbers will contain all of your indices without repetition.
Even better, maybe something like this:
var numArray = [0,1,2,3,4,5,6];
numArray.shuffle();
Then just go through the items because shuffle will have randomized them and pop them off one at a time.
Here's a simple fix, if a little rudimentary:
if(nextNum == lastNum){
if (nextNum == 0){nextNum = 7;}
else {nextNum = nextNum-1;}
}
If the next number is the same as the last simply minus 1 unless the number is 0 (zero) and set it to any other number within your set (I chose 7, the highest index).
I used this method within the cycle function because the only stipulation on selecting a number was that is musn't be the same as the last one.
Not the most elegant or technically gifted solution, but it works :)
Use sets. They were introduced to the specification in ES6. A set is a data structure that represents a collection of unique values, so it cannot include any duplicate values. I needed 6 random, non-repeatable numbers ranging from 1-49. I started with creating a longer set with around 30 digits (if the values repeat the set will have less elements), converted the set to array and then sliced it's first 6 elements. Easy peasy. Set.length is by default undefined and it's useless that's why it's easier to convert it to an array if you need specific length.
let randomSet = new Set();
for (let index = 0; index < 30; index++) {
randomSet.add(Math.floor(Math.random() * 49) + 1)
};
let randomSetToArray = Array.from(randomSet).slice(0,6);
console.log(randomSet);
console.log(randomSetToArray);
An easy way to generate a list of different numbers, no matter the size or number:
function randomNumber(max) {
return Math.floor(Math.random() * max + 1);
}
const list = []
while(list.length < 10 ){
let nbr = randomNumber(500)
if(!list.find(el => el === nbr)) list.push(nbr)
}
console.log("list",list)
I would like to add--
var RecordKeeper = {};
SRandom = function () {
currTimeStamp = new Date().getTime();
if (RecordKeeper.hasOwnProperty(currTimeStamp)) {
RecordKeeper[currTimeStamp] = RecordKeeper[currTimeStamp] + 1;
return currTimeStamp.toString() + RecordKeeper[currTimeStamp];
}
else {
RecordKeeper[currTimeStamp] = 1;
return currTimeStamp.toString() + RecordKeeper[currTimeStamp];
}
}
This uses timestamp (every millisecond) to always generate a unique number.
you can do this. Have a public array of keys that you have used and check against them with this function:
function in_array(needle, haystack)
{
for(var key in haystack)
{
if(needle === haystack[key])
{
return true;
}
}
return false;
}
(function from: javascript function inArray)
So what you can do is:
var done = [];
setInterval(function() {
var m = null;
while(m == null || in_array(m, done)){
m = Math.floor(Math.random()*7);
}
done.push(m);
$('.foo:nth-of-type('+m+')').fadeIn(300);
}, 300);
This code will get stuck after getting all seven numbers so you need to make sure it exists after it fins them all.
Working on a game and cant figure out why my functions aren't working right..
Uncaught RangeError: Maximum call stack size exceeded
By my knowledge one of my functions have a infinite loop(?)
I have a array witch needs to have 3 random speeds in it.
var randomSpeeds = new Array();
I have a function made witch generate a random speed:
function generateSpeed() {
var randomSpeed = Math.random().toFixed(1) * 5;
if(randomSpeed == 0){
randomSpeed = 1;
}
return randomSpeed;
}
The array is filled by this function:
function fillSpeedArray() {
for(var i = 0; i < 3; i++) {
var randomSpeed = generateSpeed();
if(speedArrayChecker(randomSpeed) != false) {
randomSpeeds.splice(i, 0, randomSpeed);
} else {
fillSpeedArray();
}
}
}
The function loops 3 times and each time it generates a random speed and goos through a if/else statement for checking if the array already has got the random generated number (speedArrayChecker).
The speedArrayChecker:
function speedArrayChecker(speed) {
for(speeds in randomSpeeds) {
if(speeds != speed) {
return true;
}
}
return false;
}
This last function goos through the array and if the array already go the random generated number, return true else false.
Function called and checked:
fillSpeedArray();
console.log(randomSpeeds);
By a reason I don't see the functions aren't working correctly.
Thanks and regards.
Solution:
var randomSpeeds = new Array();
function generateSpeed() {
var randomSpeed = Math.random().toFixed(1) * 5;
if(randomSpeed == 0){
randomSpeed = 1;
}
return randomSpeed;
}
function fillSpeedArray() {
while (randomSpeeds.length < 3) {
var randomSpeed = generateSpeed();
if (speedArrayChecker(randomSpeed) != false) {
randomSpeeds.splice(randomSpeeds.length, 0, randomSpeed);
}
}
}
function speedArrayChecker(speed) {
return randomSpeeds.indexOf(speed) === -1
}
fillSpeedArray();
console.log(randomSpeeds);
Explanation:
There were two problems with your code.
The implementation of the speedArrayChecker function was fundamentally flawed. It returned false only when the randomSpeeds was empty.
You had an infinite loop caused by infinite recursion.
The solution was to correct the speedArrayChecker implementation and to use a while loop instead of a for loop.
You have an infinite loop(by recursion) here:
function fillSpeedArray() {
for(var i = 0; i < 3; i++) {
var randomSpeed = generateSpeed();
if(speedArrayChecker(randomSpeed) != false) {
randomSpeeds.splice(i, 0, randomSpeed);
} else {
fillSpeedArray();
}
}
}
In the else if the speed exists already it will call the function it's currently in again and again. This function will never exit, unless you get 3 random speeds perfectly the first time. I would recommend changing fillSpeedArray() to maybe i--.
On a side note why don't you use randomSpeeds.push(randomSpeed) to add speeds to the array.
Why isn't this working? I'm getting a stack too deep error:
var countRecursion = function(array) {
var sum = 0
var count = 0
sum += array[count]
count ++
if (count < array.length) {
countRecursion(array);
} else {
return sum
}
}
You made a mistake and reset sum and counter inside the recursive block. I simply moved them outside.
var countRecursion = function(array) {
sum += array[count]
count ++
if (count < array.length) {
countRecursion(array);
} else {
return sum
}
}
var sum = 0
var count = 0
countRecursion([1,2,3]);
alert(sum);
This code is not recursive but iterative. I am not 100% sure if that's what you really wanted. But since you mentioned it, some people down voted my answer since I only fixed your code, but didn't made it recursive I guess. For completeness, here is recursive version of your code:
var countRecursion = function(array, ind) {
if (ind < array.length) {
return array[ind] + countRecursion(array, ind + 1);
} else {
return 0;
}
}
var sum = 0
var count = 0
sum = sum + countRecursion([1,2,3, 5, 6, 7], count);
alert(sum);
For recursion: pass data up, return data down.
The original code has a different count variable, being a local variable defined in the function, that is initial set to 0. As such the base case is never reached and the function recurses until the exception is thrown.
In addition to using a variable from an outer scope (or another side-effect) this can also be addressed by by following the recommendation on how to handle recursion, eg.
var countRecursion = function(array, index) {
index = index || 0; // Default to 0 when not specified
if (index >= array.length) {
// Base case
return 0;
}
// Recurrence case - add the result to the sum of the current item.
// The recursive function is supplied the next index so it will eventually terminate.
return array[index] + countRecursion(array, index + 1);
}
I see what you're thinking.
The issue with your code is that everytime you call countRecursion, count goes back to 0 (since it's initialized to 0 within your function body). This is making countRecursion execute infinitely many times, as you're always coming back to count = 0 and checking the first term. You can solve this by either:
Initializing count outside the function body, that way when you do count++, it increases and doesn't get reset to 0.
Passing count along with array as a parameter. That way, the first time you call the function, you say countRecursion(array, 0) to initialize count for you.
Note that you have to do the same for sum, else that will also revert to zero always.
Finally, (and this doesn't have to do with the stack error) you have to actually call return countRecursion(array) to actually move up the stack (at least that's how it is in C++ and what not - pretty sure it applies to javascript too though).
Array sum using recursive method
var countRecursion = function(arr, current_index) {
if(arr.length === current_index) return 0;
current_index = current_index || 0;
return countRecursion(arr, current_index+1) + arr[current_index];
}
document.body.innerHTML = countRecursion([1,2,3,4,5, 6])