I have javascript function that add numbers to array start form min to max and increase by step but when I use getNumbers(2, 20, 2); it print 2,22,222,2222,.... It doesn't increase can anyone help me please.
function getNumbers(min, max, step) {
var i;
for(i=min ; i<max ; i+=step){
array.push(i);
alert(array);
}
Nothing wrong with your function, you must pass numbers, if the passing parameters are string, change them to numbers as i did below:
var array = new Array();
function getNumbers (min, max, step) {
var i;
for(i=min ; i<max ; i+=step){
array.push(i);
alert(array);
}
}
//passing numbers:
getNumbers(1, 10, 2);
//output is 1,3,5,7,9
//if your numbers are strings, use:
var min = '1';
var max = '10';
var step = '2';
getNumbers(parseInt(min), parseInt(max), parseInt(step));
//this will work correctly
DEMO
Use parseInt to cast to integers
I see no problem with the function. Other than the array is not defined.
You're probably sending the variables in as a string, which causes concatenation instead of addition.
function getNumbers(min, max, step) {
var array = [];
for(var i = min ; i <= max ; i += step){
array.push(i);
}
return array;
}
You might also need to make sure that you use i <= max in your loop, if you want to include the max.
Related
I am working on a problem that can do the following: -
This function takes a number and returns the largest number that can be made with the same digits.
E.g. if num is 23, the function should return 32.
E.g. if num is 9, the function should return 9.
E.g. if num is 581 the function should return 851.
function largestNumber(num) {
var num = String(num).split().sort().reverse().join('')
return Number(num)
}
Fix your split() call and don't redeclare num:
num = String(num).split('').sort().reverse().join('');
you need to change your split() to split('') as commented.
you don't need to instantiate a new variable you can have your code in the return statement itself.
return Number(String(num).split('').sort().reverse().join(''));
Answer: -
function largestNumber(num) {
num = String(num).split('').sort().reverse().join('');
return Number(num);
}
This passes all my tests.
You can do the following
num = String(num).split('').sort().reverse().join('');
Basically it's sorting the digits from smallest to biggest, then reverses it to get biggest to smallest, and turns it into a string by joining it with a connector. Well, there isn't really a connector
But for people who don't understand:
num = String(num).split('');
var exArray = num;
var a = (i+1)%num.length
//Sorting
for(var i = 0; i < num.length; i++) if(Number(num[i])>Number(num[a])){var x=i;num[i]=a;num[a]=x;}
return num.join('');
You can also do this,
var num = 2134;
var largestNum = parseInt(num.toString().split('').sort().reverse().join(''))
Output : largestNum = 4321
I'm trying to implement a function which takes three arguments(min, max, step)and generates a range of integers from min to max, with the step. The first integer is the minimum value, the second is the maximum of the range and the third is the step.
Here is an example of what it should look like:
generateRange(2, 10, 2) should return array of [2,4,6,8,10].
I'm using the splice method to remove any existing elements in the array that are greater than the max argument.
function generateRange(min, max, step) {
var arr = [];
var count = min;
for (var i = 0; i < max / step; i++) {
arr[i] = count;
count = count + step;
arr[i] > max ? arr.splice(i, 1) : arr[i];
}
return arr;
}
console.log(generateRange(2, 10, 2));
Whenever I console.log my result I get a bunch of commas after the last item...so it looks like this: [2,4,6,8,10, , , , ]
It doesn't appear to be deleting the items. What am I missing? Thanks!
The ternary operator is a bit strange, as the expression is not stored. It fixes the array by removing too large values. That works once, but if there is a second time, i will have increased, and by the assignment to arr[i], the array's length is again as if there had been no splice performed before (except for the undefined value at that i-1 index).
It would be better to exit the loop before assigning a value that is outside of the range. There is no sense in continuing the loop in such a case.
So make the count variable your loop variable and condition:
function generateRange(min, max, step){
var arr = [];
for(var count = min; count <= max; count+=step){
arr.push(count);
}
return arr;
}
var res = generateRange(2, 10, 2);
console.log(res);
A less readable, but shorter ES6 version would be:
function generateRange(min, max, step){
return Array.from(Array(Math.floor((max-min)/step)+1), (x,i) => min+i*step);
}
let res = generateRange(2, 10, 2);
console.log(res);
I am creating a fancy number box. The below is a function that when people finishing loading there ll be a number box count up to the result:
function countUp(count){
var div_by = 100,
speed = Math.round(count/div_by),
$display = $('.count'),// i bind the function to the class count
run_count = 1,
int_speed = 24;
var int = setInterval(function() {
if(run_count < div_by){
$display.text(speed * run_count);
run_count++;
} else if(parseInt($display.text()) < count) {
var curr_count = parseInt($display.text()) + 1;
$display.text(curr_count);
} else {
clearInterval(int);
}
}, int_speed);
}
countUp(6435);
It's working fine by i'd like to add comma to split the thousand like 6,345
I tried to convert the result using toString() but it doesn't work
countUp(6435).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
you can use toLocaleString method
countUp(6435).toLocaleString();
Simply try this one:
var num = countUp(6435);
num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
i'm filling an array from the input fields and i need to find the biggest number in that array.
Using Math.max(myData) gives me NaN error and when i'm using the "if" statement,sometimes it works and sometimes it doesn't.
Example: if i have 40 and 100 in array ,it gives me 40 as bigger number,but when i have 500 than it works fine.
if i want to make Math.max to work i need to make a new function that converts string into numbers,right?
my code,so you can see where is the mistake.
function Data() {
var h = 0;
var secnd = 1;
var najBr = 0;
for (var i = 0; i < valGrup2; i++)
{
var first = 1;
myDataName[i] = document.getElementById('ime' + secnd).value;
for (var j = 0; j < val2; j++)
{
myData[h] = document.getElementById("inputpolja" + first + secnd).value;
if(myData[h]>najBr){
najBr=myData[h];
}
myDataValue[h] = document.getElementById("inputpolja" + first + secnd).value;
h++;
first++;
}
secnd++;
}
//najBr=Math.max(myData);
console.log(najBr);
Math.max accepts only plain numbers, not an array.
Use this:
function getMaxOfArray(numArray) {
return Math.max.apply(null, numArray);
}
Math.max takes multiple arguments, not an array of the numbers. You can use Function#apply() to have it treat the array as a list of arguments:
Math.max.apply(null /* the context */, myData)
I have:
function getRandomInt(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
}
But the problem is I want randomise the population of something with elements in an array (so they do not appear in the same order every time in the thing I am populating) so I need to ensure the number returned is unique compared to the other numbers so far.
So instead of:
for(var i = 0; i < myArray.length; i++) {
}
I have:
var i;
var count = 0;
while(count < myArray.length){
count++;
i = getRandomInt(0, myArray.length); // TODO ensure value is unique
// do stuff with myArray[i];
}
It looks like rather than independent uniform random numbers you rather want a random permutation of the set {1, 2, 3, ..., N}. I think there's a shuffle method for arrays that will do that for you.
As requested, here's the code example:
function shuffle(array) {
var top = array.length;
while (top--) {
var current = Math.floor(Math.random() * top);
var tmp = array[current];
array[current] = array[top - 1];
array[top - 1] = tmp;
}
return array;
}
Sometimes the best way to randomize something (say a card deck) is to not shuffle it before pulling it out, but to shuffle it as you pull it out.
Say you have:
var i,
endNum = 51,
array = new Array(52);
for(i = 0; i <= endNum; i++) {
array[i] = i;
}
Then you can write a function like this:
function drawNumber() {
// set index to draw from
var swap,
drawIndex = Math.floor(Math.random() * (endNum+ 1));
// swap the values at the drawn index and at the "end" of the deck
swap = array[drawIndex];
array[drawIndex] = array[endNum];
array[endNum] = swap;
endNum--;
}
Since I decrement the end counter the drawn items will be "discarded" at the end of the stack and the randomize function will only treat the items from 0 to end as viable.
This is a common pattern I've used, I may have adopted it into js incorrectly since the last time I used it was for writing a simple card game in c#. In fact I just looked at it and I had int ____ instead of var ____ lol
If i understand well, you want an array of integers but sorted randomly.
A way to do it is described here
First create a rand function :
function randOrd(){
return (Math.round(Math.random())-0.5); }
Then, randomize your array. The following example shows how:
anyArray = new Array('1','2','3','4','5');
anyArray.sort( randOrd );
document.write('Random : ' + anyArray + '<br />';);
Hope that will help,
Regards,
Max
You can pass in a function to the Array.Sort method. If this function returns a value that is randomly above or below zero then your array will be randomly sorted.
myarray.sort(function() {return 0.5 - Math.random()})
should do the trick for you without you having to worry about whether or not every random number is unique.
No loops and very simple.