How to get string from odd's array ? - javascript

I need help... I'm learning JavaScript, and it seems easy, but I may just be overlooking... everything... My problem is I need to return a string of all the even numbers between 0 and num inclusive; ex 7 gets you 0246, etc. I've gotten:
function stringOfEvens(num) {
for (let i = 0; i <= num.length; ++i) {
if (i % 2 === 0 ); {
return i;
}
}
}
I know the whole outlook is to run a for loop that goes from 0 to the number in question appending each time and if that number % 2 = 0, return that number, but something is a miss... I may even be overthinking and approaching this whole thing wrong... It is figuratively driving me mad...

function theJob(limit) {
var res = ''; //initialize as a string so that the other numbers will be appended instead of added
for (i = 0; i <= limit; i += 2) { // step increase by 2 to skip odd numbers
res += i;
}
return res; // returning the resulting string
}
console.log(theJob(10));

You can do this without using the modular function, by simply starting the loop at zero and incrementing by 2 each time the loop iterates...
function stringOfEvens(num) {
var result = "";
for (let i = 0; i <= num; i += 2) {
result += i; // append this even number to the result string
}
return result;
}
console.log(stringOfEvens(10));

You're returning the first number you find. a better approach would be to build the string in the loop then return after that string after the loop. Also no need for num.length if num is an int.
function stringOfEvens(num) {
var stringToReturn = "";
for (let i = 0; i <= num; i++) {
if (i % 2 === 0) {
stringToReturn = stringToReturn + i;
}
}
return stringToReturn;
}

function stringOfEvens(num) {
var str= ' ';
for(var i = 0; i <= num; i = i + 2){
str += i;
}
return str;
}
console.log(stringOfEvens(10))

Just for fun, since it's not particularly efficient:
const stringOfEvens = n => Array(~~(n/2)+1).fill().map((_, i) => 2*i).join("")
or annotated:
const stringOfEvens = n => // arrow function definition, returning:
Array(~~(n / 2) +1) // a sparse array of the required length
.fill() // made unsparse, so .map works
.map((_, i) => 2 * i) // then containing the even numbers
.join("") // and converted to a string
or alternatively (and more efficiently) using Array.from which can call an explicit map function in place:
const stringOfEvens = n => Array.from(Array(~~(n/2)+1), (_, i) => 2*i).join("")

Related

Javascript for loop not iterating across array or values in an if statement not updating as planned

Trying to return the highest 5 digit number out of any given number i.e 34858299999234
will return 99999
I think I have it narrowed down to the for loop not iterating the array properly OR the values for 'hold1' and 'hold2' are not updating.
function solution(digits){
//Convert string to array to iterate through
let arr = digits.split("");
let final = 0;
//iterate through the array in 5 sequence steps
for(let i = 0; i < arr.length-1; i++){
let hold1 = arr[i] + arr[i+1] + arr[i+2] + arr[i+3] + arr[i+4];
hold1 = parseInt(hold1,10); //converting string to int so if statement functions correctly
let hold2 = arr[i+1] + arr[i+2]+ arr[i+3] + arr[i+4] + arr[i+5];
hold2 = parseInt(hold2,10);
if(hold1 >= hold2){
final = hold1;
}else{
final = hold2;
}
return final;
}
}
if you need a five digits result you need to change the for loop in something like this:
for (let i = 0; i < arr.length - 5; i++) {
Otherwise you will generate results shorter than 5 digits.
Also, I think you are missing the Math.max method that will compare two numbers to return the bigger one.
I rewrote your function this way:
function solution(digits) {
let op = 0;
let length = 5;
let stringDigits = String(digits); /// <-- I use string instead of array
if (stringDigits.length <= length) {
return digits; /// <-- If input is shorter than 5 digits
}
for (let i = 0; i < stringDigits.length - length; i++) {
const fiveDigitsValue = stringDigits.substr(i, length);
op = Math.max(op, Number(fiveDigitsValue));
}
return op;
}

Js function top calculate factorial not working

I was doing this challenge from coderbyte where you have to make a function that calculate the factorial of a given number, this is my not so working solution.
function firstFactorial(num) {
for (var i = num; i == 1; i--) {
num = num * i;
}
return num;
}
It just returns whatever number i pass in as an argument, and i'm trying to understand what's wrong. Is it something to do with the loop or is it something with the variable scope ?
i == 1 is wired in loop condition it will always be false for all number except 1.So it will always return the same number as result.
i = num should be i = num-1 to get correct factorial.
function FirstFactorial(num) {
for(var i = num-1; i >= 1; i--){
num = num * i;
}
return num;
}
console.log( FirstFactorial(5))
Your for loop was a bit messed up. Now it should work.
function factorial(num){
for(var i = num - 1; i > 0; i--){
num *= i;
}
return num;
}
console.log(factorial(5));
Your problem is that you have a loop condition i == 1. For factorials, it should be i >= 1, or i > 1 depending on what algorithm you use. My take on a factorial function would be:
function calculate(factorial) {
var newFactorial = factorial;
while (factorial > 1) {
factorial--;
newFactorial *= factorial;
}
return newFactorial;
}
function firstFactorial(num) {
const output = eval(Array.from({length: num}, (_, index) => (index + 1)).reverse().join("*"));
return output;
}
console.log(firstFactorial(8));
Rather than iterating through all the numbers using for loop or recursion. I used built-in Javascript functions.
I first created an array of length 1-N using Array.from
Then, I reversed that array and joined it with *. Then, I used the eval function to get evaluate the expression.
You can also shrink it down to just one line. So the code will be:
const findFactorial = num => eval(Array.from({length: num}, (_, index) => (index + 1)).reverse().join("*")

Find out which one of the given numbers differs from the others for Javascript

I'm trying to solve this exercise. There is a string of numbers and among the given numbers the program finds one that is different in evenness, and returns a position of this number. The element has to be returned by its index (with the number being the actual position the number is in). If its index 0, it has to be returned as 1. I have this so far but it's not passing one test. I'm not too sure why because it feels like it should. Is anyone able to see what the error is? Any help is appreciated!
function iqTest(numbers) {
var num = numbers.split(" ");
var odd = 0;
var even = 0;
var position = 0;
for(var i = 0; i < num.length; i++) {
if(num[i]%2!==0) {
odd++;
if(odd===1) {
position = num.indexOf(num[i]) + 1;
}
}
else if(num[i]%2===0) {
even++;
if(even===1) {
position = num.indexOf(num[i]) + 1;
}
}
}
return position;
}
iqTest("2 4 7 8 10") output 3
iqTest("2 1 2 2") output 2
iqTest("1 2 2") outputs 2 when it should be 1
The simplest way is to collect all even/odd positions in subarrays and check what array has the length 1 at the end:
function iqTest(numbers) {
numbers = numbers.split(' ');
var positions = [[], []];
for (var i = 0; i < numbers.length; i++) {
positions[numbers[i] % 2].push(i + 1);
}
if(positions[0].length === 1) return positions[0][0];
if(positions[1].length === 1) return positions[1][0];
return 0;
}
console.log(iqTest("2 4 7 8 10"))
console.log(iqTest("2 1 2 2"))
console.log(iqTest("1 2 2"))
console.log(iqTest("1 3 2 2"))
Your code is overly complex.
Since the first number determines whether you're looking for an even number or an odd one, calculate it separately. Then, find the first number that doesn't match it.
function iqTest(numbers) {
numbers = numbers.split(" ");
var parity = numbers.shift() % 2;
for( var i=0; i<numbers.length; i++) {
if( numbers[i] % 2 != parity) {
return i+2; // 1-based, but we've also skipped the first
}
}
return 0; // no number broke the pattern
}
That being said, iqTest("1 2 2") should return 2 because the number in position 2 (the first 2 in the string) is indeed the first number that breaks the parity pattern (which 1 has established to be odd)
You have to define which "evenness" is the different one. Use different counters for the two cases, and return -1 if you don't have a single different one. Something like this:
function iqTest(numbers) {
var num = numbers.split(" ");
var odd = 0;
var even = 0;
var positionOdd = 0;
var positionEven = 0;
for(var i = 0; i < num.length; i++) {
if(num[i]%2!==0) {
odd++;
if(odd===1) {
positionOdd = i + 1;
}
}
else if(num[i]%2===0) {
even++;
if(even===1) {
positionEven = i + 1;
}
}
}
if (odd == 1)
return positionOdd;
else if (even == 1)
return positionEven;
else
return -1;
}
Note that, if you have exactly a single even number and a single odd one, the latter will be returned with the method of mine. Adjust the logic as your will starting from my solution.
Since the first number determines whether you're looking for an even number or an odd one, calculate it separately.
Then, find the first number that doesn't match it.
function iqTest(numbers){
// ...
const numArr = numbers.split(' ');
const checkStatus = num => (parseInt(num) % 2) ? 'odd' : 'even';
const findUniqueStatus = array => {
let numEvens = 0;
array.forEach(function(value){
if (checkStatus(value) == 'even') { numEvens++; }
});
return (numEvens === 1) ? 'even' : 'odd'
}
let statuses = numArr.map(checkStatus),
uniqueStatus = findUniqueStatus(numArr);
return statuses.indexOf(uniqueStatus) + 1;
}
}
public static int Test(string numbers)
{
var ints = numbers.Split(' ');
var data = ints.Select(int.Parse).ToList();
var unique = data.GroupBy(n => n % 2).OrderBy(c =>
c.Count()).First().First();
return data.FindIndex(c => c == unique) + 1;
}

Factorize function javascript

I am having a little issue writing a function that factorizes numbers. The hard part is done. However I cannot seem to tell the function to return 1 when num is 0.
PS: which other ways would you write the same function in JavaScript?
var arrOfNum = [];
function factorialize(num) {
for(i = 1; i <= num; i++){
// push all numbers to array
arrOfNum.push(i);
}
// multiply each element of array
var result = arrOfNum.reduce(function(a,b){
return a * b;
});
console.log(result);
}
You already have a for loop, in which you can calculate the factorial at once, without array and reduce.
function factorial(num) {
var result = 1;
for(i = 2; i <= num; i++) {
result *= i;
}
return result;
}
You can use the following method that uses the recursion:
function factorize(num){
if(num === 0){
return 1 ;
}
else {
return num = num * factorize(num-1);
}
}
Roundup:
Declaration of local variable i is missing
var i;
Declaration of other used variables are over the function distributed. A better way is to declare the variables at top of the function.
Array#reduce needs for this task an initialValue as the second parameter.
The first time the callback is called, previousValue and currentValue can be one of two values. If initialValue is provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. 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.
function factorial(num) {
var i,
arrOfNum = [],
result;
for (i = 1; i <= num; i++) {
// push all numbers to array
arrOfNum.push(i);
}
// multiply each element of array
result = arrOfNum.reduce(function (a, b) {
return a * b;
}, 1);
document.write(num+'! = '+result + '<br>');
}
factorial(0);
factorial(1);
factorial(2);
factorial(5);
factorial(8);
Simply return the value 1
function factorialize(num) {
if (num < 1) return 1; //this line is added
for(i = 1; i <= num; i++){
arrOfNum.push(i);
}
var result = arrOfNum.reduce(function(a,b){
return a * b;
});
console.log(result);
}
If you give reduce an initial value of 1, everything will work fine even without an explicit check:
var result = arrOfNum.reduce(function(a,b){
return a * b;
}, 1);
^^^ // PROVIDE EXPLICIT INITIAL VALUE TO REDUCE
function factorial(n) {
return Array.apply(0, Array(n)).reduce(function(x, y, z) {
return x + x * z; //1+(1*0), 1+(1*1),2+(2*2), 6+(6*3), 24+(24*4), ...
}, 1);
}
DEMO
Here's a fairly streamlined function that returns an array of all factors of 'n'
You only need to look at candidates < sqrt(n)
For those of you who don't know the | 0; bit when getting sqrt(n) is a faster equivalent of Math.floor()
As factn is defined after some sanity checking the function will either return undefined or an array which is easy to check with something like if(factors = factorize(n) { success code } sorta structure
There are improvements that can be made to this but they're complex and were beyond the requirements when I wrote it - specifically I used this to calculate CSS sprite sizes from a large image by using factorize on the x + y dimensions of an image then creating a third array of shared factors (which gives you a list of all the possible square sprite sizes).
function factorize(n) {
n = Number(n);
if(n) {
if(n > 1) {
var sqrtn = Math.sqrt(n) | 0;
var factn = [1, n];
var ipos = 0;
for(i = 2; i <= sqrtn; i++) {
if((n % i) == 0) {
ipos++;
if((n / i) !== i) {
factn.splice(ipos, 0, i, n / i);
} else {
factn.splice(ipos, 0, i);
}
}
}
}
}
return factn;
}
Don't know why there are complicated answers. A very simple answer is:
var i;
function factorialOf(num) {
//Initially set factorial as number
var factorial = num;
//A for loop starting with 1 and running the times equal to num
for (i = 1; i < num; i++) {
//Set factorial to the number itself * i
factorial = factorial * i;
}
//Return factorial
return factorial;
}
console.log(factorialOf(5));

Need help finding the sum of all numbers in an array

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; });

Categories