How can I do this using Reduce function? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
var y= '110001'.split("").reverse();
var sum = 0;
for (var i = 0; i < y.length; i++) {
sum += (y[i] * Math.pow(2, i));
}
console.log(sum);

It would be simplest to do
console.log(Array.from('110001').reduce((prev, cur) => prev << 1 | cur));
<< is the left-bitshift operator, which here essentially multiplies by two.
Array.from (if available) is preferable to split. In this case it doesn't matter, but split will fail with surrogate pair characters such as 🍺, while Array.from will handle them correctly. This could also be written as [...'110001'], which ends up being the same thing.
Of course, you could also just say
parseInt('110001', 2)

check this snippet
var binary = '110001'.split("").reverse();
var sum = binary.reduce(function(previous, current, index) {
previous = previous + (current * Math.pow(2, index));
return previous;
}, 0);
console.log(sum);
Hope it helps

Related

Calculate Percentage in array using Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am trying to calculate the 10% from total array of values
for eg
perc = [56,50];
function percentage(perc) {
return (perc / 100) * 10;
}
You need to first sum the array, and then calculate 10% of that sum:
function percentage(perc) {
const sum = perc.reduce((a, b) => a + b, 0)
return sum * 0.1;
}

How could i write this random number generating button/div syntax in another way? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I have the following code:
// Reference to the <div> which displays the random number:
var rndDiv = document.getElementById('rndNum')
// Reference to the <button> which generates the random number:
var rndBtn = document.getElementById('rnd')
// Generating the random number through 'click' eventlistener:
rndBtn.addEventListener('click', function intRnd() {
var n = Math.floor((Math.random() * 10) + 1);
console.log(n)
rndDiv.innerHTML = n
})
how could/should i write this code differently, how would you write it? Would you use, for example, arrow functions? let instead of var? I'm just curious. Also i'm the total opposite of a 'pro'-coder, just a beginner, and would like to read your code to this solution.
Thanks for taking your time and reading my post!
Here you go ... !
IIFE
Arrow Function
Let
(function() {
let rndBtn = document.getElementById('rnd');
rndBtn.addEventListener('click', () => {
let rndDiv = document.getElementById('rndNum');
rndDiv.innerHTML = Math.floor((Math.random() * 10) + 1);
});
})();
<button id="rnd">Click</button>
<div id="rndNum"></div>
Here is another way
const randomNumGenerator = () => Math.floor((Math.random() * 10) + 1);
const randomNumDiv = document.getElementById('rndNum');
document.getElementById('rnd').addEventListener('click', () => {
randomNumDiv.innerHTML = randomNumGenerator();
});

Algorithm to convert any string to a 1-3 digit number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to make an algorithm, for a NodeJS app, that converta any given string to a 1 to 3 digit number (better if the number is between 1-500).
e.g
ExampleString -> 214
Can anyone help me find a good solution?
EDIT:
I want to get a crime coefficient number from a username (string).
Ok, you can use JS function to get charCode of letter
let str = "some string example";
let sum = 0;
for (let i=0; i<str.length; i++) {
sum += parseInt(str[i].charCodeAt(0), 10); // Sum all codes
}
// Now we have some value as Number in sum, lets convert it to 0..1 value to scale to needed value
let rangedSum = parseFloat('0.' + String(sum)); // Looks dirty but works
let resultValue = Math.round(rangedSum * 500) + 1; // Same alogorythm as using Math.random(Math.round() * (max-min)) + min;
I hope it helps.
So as you are using nodejs, you can use crypto library to get md5 hash of string and then get it as HEX.
const crypto = require('crypto');
let valueHex = crypto.createHash('md5').update('YOUR STRING HERE').digest('hex');
// then get it as decimal based value
let valueDec = parseInt(valueHex, 16);
// and apply the same algorythm as above to scale it between 1-500
function coeficient() {
return Math.floor(Math.random() * 500) + 1;
}
console.log(coeficient());
console.log(coeficient());
console.log(coeficient());

Addition returns wrong value in JavaScript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
When I tried with additions of variables I saw that:
https://jsfiddle.net/tyfyLsw9/
I think it's because this doesn't contain an integer.
var month = $("#monthd").val();
var J = 1;
var D = 8;
var K = J + D;
var U = J + month;
As you can see in fiddle J + month returns 110 instead of 11, why?
its a string, so the number you are adding gets coerced into a string as well. "10" + "1" = "101";
simply wrap the value returned in a Number Construct
var month = Number($("#monthd").val());
additionally you can use parseInt if the values are integers.
var month = parseInt($("#monthd").val(), 10);
the , 10 is important to parse it with base 10.

javascript next number on multiples of three [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have a number for example 4, i want to get next number on multiples of 3
Multiples of three: [3,6,9,12,15,18,21,24,27,30,...]
the result must be 6
i'm looking for a javascript function
something like this:
function (myNum) { //myNum = 4;
var multiples = [3,6,9,12,15,18,21,24,27,30];
var result;
// do something!!
return result; // returns 6
}
thanks
I suggest another solution:
function getNext(num, dep){
return (((num % dep) ? dep:0) - num % dep) + num;
}
document.write(getNext(4, 3));//6
//document.write(getNext(200, 7));//203
Updated: You can use this method for finding next number on multiples of any number
There are a lot of ways you can achieve this. Here is an easy one. Increment the number until you get a multiple of three.
function multipleOfThree(num){
while(num % 3 != 0)
num++;
return num;
}
You must try before asking a question. If you stuck at somewhere then it is good to ask questions with problem. By the way here what you can try:
function multiple(number) {
return number % 3 === 0 ? ((number/3) * 3) : parseInt((number/3) + 1) * 3;
}

Categories