I've created an array that I now want to reverse. The array should display every number from the number specified down to 0.
I've tried using the reverse() method in various ways but it either misses out every other number in the array or returns nothing at all?
In the code below the else if statement is where the array wants reversing.
Is there a way to use the reverse() method on the array here or an alternative way to do this?
Thanks
function myFunc() {
var x = Math.floor(Math.random() * 100);
var counter = [];
var start = 0;
if (x > 40) {
start = 40;
} else {
start = 0; }
for (var i = start; i < x; i++) {
if (x > 40 && i % 2 == 1) {
counter.push(i);
} else if (x < 40) {
counter.push(i).reverse(); //reverse here returns nothing
counter.reverse(); //reverse here returns every other number only
}
}
return counter + ',' + x;
}
console.log(myFunc())
......
for (var i = start; i < x; i++) {
if ((x > 40 && i % 2 == 1) || x < 40) {
counter.push(i);
}
}
if(x<40)
counter.reverse();
return counter;
}
Should work like this.. (unless I misunderstood your problem?)
http://jsfiddle.net/aLUfh/2/
var x = Math.floor(Math.random() * 100);
var counter = [];
for (i = 0; i < x; i++) {
counter.push(i);
}
counter.reverse();
$('#Xis').html(x);
$('#outcome').html(counter + ',' + x);
I've created an array that I now want to reverse. The array should display every number from the number specified down to 0.
If this is the problem, then you can solve it easier like this:
var x = Math.floor(Math.random() * 100);
var counter = [];
var end = (x > 40 ? 40 : 0);
while (end <= x) {
counter.push(x);
--x;
}
return counter;
Demo
Try before buy
Your code however does something else, but you can adjust it like:
while (end <= x) {
if ( ((40 < x) && (1 == x % 2)) || (40 > x)) {
counter.push(x);
}
--x;
}
Related
Super noob question here. I have the code below from an as3 project below where frame numbers are randomized then clicking a sprite (next) will move to the next random frame. I am having trouble figuring out what else I need to do to convert it to javascript. Can anyone help me out or point me in the right direction? TIA!
var sortedNumbers:Array = [];
for(var i:int = 1; i < 21; i++)
{
sortedNumbers.push(i);
}
var unsortedNumbers:Array = sortedNumbers.slice();
while(sortedNumbers.join() == unsortedNumbers.join())
{
unsortedNumbers.sort(function (a:int, b:int):int { return Math.random() > .5 ? -1 : 1; });
}
this.start.addEventListener("click", f_nextRE.bind(this));
function f_nextRE() {
if(index == 20) {
gotoAndStop (22);
}
else {
gotoAndStop (unsortedNumbers [index] + 1);
index +=1;
}
}
So it took me a few days but I found my answer (a combination of several sources many on this site)... Posting it here to help others...
//create array
var shuffledFrames = [];
//fill array
for (var i = 1; i <= 35; i++) {
shuffledFrames.push(i);
}
//shuffle array
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
}
//run shuffle function
shuffle(shuffledFrames);
//function to call next random frame then repeat when reaching the end.
function f_next()
{
if (shown == 1){
if (nextF == 35) {
nextF = 0;
}
else {
nextF += 1;
}
this.gotoAndStop (shuffledFrames [nextF]);
}
}
https://codepen.io/aholston/pen/ZJbrjd
The codepen link has commented code as well as actual instructions in HTML
Otherwise.... what I ultimately have to do is write a function that takes two params(a and b) and takes all the numbers between those two params (a-b) and put every number that can be added to the consecutive fowers and be equal to that number into a new array. Ex: 89 = 8^1 + 9^2 = 89 or 135 = 1^1 + 3^2 + 5^3 = 135
function sumDigPow(a, b) {
// Your code here
var numbers = [];
var checkNum = [];
var finalNum = [];
var total = 0;
for (var i = 1; i <= b; i++) {
if (i >= a && i <= b) {
numbers.push(i);
}
}
for (var x = 0; x < numbers.length; x++) {
var checkNum = numbers[x].toString().split('');
if (checkNum.length == 1) {
var together = parseInt(checkNum);
finalNum.push(together);
} else if (checkNum.length > 1) {
var together = checkNum.join('');
var togNumber = parseInt(together);
for (var y = checkNum.length; y > 0; y--) {
total += Math.pow(checkNum[y - 1], y);
}
if (total == togNumber) {
finalNum.push(togNumber);
}
}
}
return finalNum;
}
try this:
function listnum(a, b) {
var finalNum = [];
for (var i = a; i <= b; i++) {
var x = i;
var y = i;
var tot = 0;
j = i.toString().length;
while (y) {
tot += Math.pow((y%10), j--);
y = Math.floor(y/10);
}
if (tot == x)
finalNum.push(i);
}
return finalNum;
}
console.log(listnum(1, 200));
Okay, after debugging this is what I learned.
for (var y = checkNum.length; y > 0; y--) {
total += Math.pow(checkNum[y - 1], y);
}
if (total == togNumber) {
finalNum.push(togNumber);
}
}
}
return finalNum;
}
Everytime this loop happened, I neglected to reset the 'total' variable back to 0. So I was never getting the right answer for my Math.pow() because my answer was always adding to the previous value of total. In order to fix this, I added var total = 0; after i decided whether or not to push 'togNumber' into 'finalNum.' So my code looks like this..
for (var y = checkNum.length; y > 0; y--) {
total += Math.pow(checkNum[y - 1], y);
}
if (total == togNumber) {
finalNum.push(togNumber);}
}
var total = 0;
}
return finalNum;
}
i have to solve the following function: "x" represent a number of cycles. One cycle sums +1 and then multiply the result *2. For example:
0 cycles = 0 + 1 = 1 (result)
1 cycles = 1 * 2 = 2 (result)
2 cycles = 2 + 1 = 3 (result)
3 cycles = 3 * 2 = 6 (result)
4 cycles = 6 + 1 = 7 (result) and so on.
I have this function:
function final(x) {
for (var i = 0; i < x; i++) {
var result = x[i] * 2 + 1
}
return result;
}
Can you help me out?
If you want to store the results, you can use answer by #Kornflexx. If not, you can directly calculate the value :
function final (x) {
var t = (4 << (x / 2)) - 2;
return x % 2 ? t : t / 2;
}
Note that if x is large you will quickly pass the int limit and would then need to deal with big integers
This should work if you don't care of the fact that the for start at 1.
function final(x) {
var result = [];
result[0] = 1;
for (var i = 1; i < x; i++) {
result[i] = i % 2 ? result[i - 1] * 2 : result[i - 1] + 1;
}
return result;
}
If you only require the final result of the function then the following will achieve that for you.
function final(x) {
var result = 0;
for (var i = 0; i < x; i++) {
if (x % 2 === 0) {
result = result + 1;
} else {
result = result * 2;
}
}
return result;
}
Thanks for your help, the solution finally was this:
function final(x){
var result = 0;
for (var i = 0; i < x; i++){
if (i % 2 === 0){
result = result * 2 + 1;}
else{
result = (result + 1);}
}
return result+1;
}
Just for variety, you can have this short form
function final(x) {
var result = 0;
for (var i = 0; i < x; i++) {
result = x % 2 == 0 ? result + 1 : result * 2
}
console.log(x,result)
return result;
}
final(3)
I'm trying to find all of the numbers that are multiple of 3 or 5 below 1000. After I get all of the numbers, I would like to add them up.
I was able to figure out how to find the multiples and add them to an array but unable to figure out how to add them together.
Here's my code:
var add = [];
var count = 0;
if ( i % 3 == 0 || i %5 == 0) {
for (var i = 1; i <= 1000; i ++) {
add.push(i);
}
};
function whole () {
for(var i = 0 ; i <= add.length; i ++) {
count = count + add[i];
}
};
whole();
The first loop won't ever happen because i is undefined (i%3 is NaN) at that point.
I think you just need to invert the for with the if.
for (var i = 1; i <= 1000; i ++) {
if ( i % 3 == 0 || i %5 == 0) {
add.push(i);
}
};
The assertion that you need to return count isn't true. The function is simply going to act on the global count.
A cleaner, functionally pure way to do this:
function whole(i, count, max){
if(i > max){
return count;
}
if(i % 3 === 0 || i % 5 === 0){
return whole(i + 1, count + i, max);
}
return whole(i + 1, count, max);
}
whole(0, 0, 1000);
You need to put the condition inside the loop as well letting the loop run until i < 1000 because you only want the numbers below 1000.
for (var i = 1; i < 1000; i ++) {
if (i % 3 == 0 || i %5 == 0) {
add.push(i);
}
}
In the whole function you need to run ntil i < add.lengthor else you will try to add an undefined index to your sum.
function whole () {
for(var i = 0 ; i < add.length; i ++) {
count = count + add[i];
}
};
I think that you were close. In your whole function, you need to return count.
function whole () {
for(var i = 0 ; i <= add.length; i ++) {
count = count + add[i];
}
return count;
};
Here's a better way to sum an array of numbers.
You can use a reduce function on your array to get a "reduced" value
add.reduce(function(x,y) { return x+y; }, 0);
For example ((0 + 1) + 2) + 3 will return 6
[1,2,3].reduce(function(x,y) { return x+y; }, 0); //=> 6
Here's another interesting way to potentially solve the problem with a more functional approach.
It uses ES6, but do not fret. You can easily copy/paste the example into babeljs.io/repl to see it run. Babel will also give you the equivalent ES5.
// let's say we have an array of 1000 numbers
let ns = new Array(1000);
// fill the array with numbers
for (let i=0, len=ns.length; i<len; i++) {
ns[i] = i+1;
}
// some reusable functions
let mod = y => x => x % y;
let eq = y => x => x === y;
let id = x => x;
let filter = f => xs => xs.filter(f);
let reduce = f => i => xs => xs.reduce(uncurry(f), i);
let comp = g => f => x => g(f(x));
let compN = reduce(comp)(id);
let uncurry = f => (x,y) => f(x)(y);
// these are some helpers you could define using the reusable functions
let add = y => x => x + y;
let sum = reduce(add)(0);
let divisibleBy = x => comp(eq(0))(mod(x));
// define your solution as a composition
// of `sum`, `divisbleBy(5)`, and `divisibleBy(3)`
let solution = compN([
sum,
filter(divisibleBy(5)),
filter(divisibleBy(3))
]);
// output the solution passing in the original `ns` array
console.log(solution(ns));
Just call reduce without start parameter.
arr.reduce(callback[, initialValue]): If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second. MDN
add.reduce(function(x, y) { return x + y; });
I'm trying to write a code that randomizes a number (1 - 100), then prints all the odd numbers from 40 to that one. If the number is smaller than 40 it should print all the numbers up to the randomized one.
i.e. if the number is 45, it should print 41, 43, 45. And if it's 5 it should print 1,2,3,4,5.
My code below works until I add the else if statement. When I add this if the number is above 40 it still includes all numbers from 0 to 40? I don't understand why as I thought if statements should go one way or another not both?
Any ideas help on how to solve this, or what i'm doing wrong?
Thanks in advance
function myFunc() {
var x = Math.floor(Math.random() * 100);
var counter = [];
for (var i = 0; i < x; i++) {
if (i > 40 && i % 2 == 1) {
counter.push(i);
} else if (i < 40) {
counter.push(i);
}
}
return counter + ',' + x;
}
console.log(myFunc())
Just add a new variable that checks where to start from. That way you can shorten the conditional in the loop too.
function myFunc() {
var x = Math.floor(Math.random() * 100);
var counter = [];
var start = x >= 40 ? 40 : 0; // new variable
for (var i = start; i < x; i++) {
if (i % 2 === 1) { counter.push(i); }
}
return counter + ',' + x;
}
console.log(myFunc())
you write not correct conditional:
else if (i < 40)
this statement is run, because first statement is false and i in progress 1,2,3,4,
you must change second statement to x < 40
function myFunc() {
var x = Math.floor(Math.random() * 100);
var counter = [];
for (var i = 0; i < x; i++) {
if (i > 40 && i % 2 == 1) {
counter.push(i);
} else if (x <= 40) { // only when x <= 40
counter.push(i);
}
}
return counter + ',' + x;
}
console.log(myFunc())