Rounding off to 6 decimals - javascript

I would like to round off this code to 6 digits
function plus-minus(arr) {
let pos = 0;
let neg = 0;
let zero = 0;
let len = 6;
for (let i = 0; i < len; i++){
if (arr[i] > 0) {
neg++;
} else if (arr[i] < 0) {
pos++;
} else {
zero++;
}
}
console.log(pos/len);
console.log(neg/len);
console.log(zero/len);
}

For rounding you can use a little trick like this:
var number = 0.00012367
var round = 6;
number = Math.round(number * 10**round) / (10**round)
console.log(number)
Or you can use the toFixed method:
var number = 0.00012367
number = number.toFixed(6)
console.log(number)

Related

Repeat String Infinitely - Return Count of Specific Character Within N Length of Infinite String - JavaScript

Trying to solve this HackerRank challenge:
Lilah has a string, s, of lowercase English letters that she repeated infinitely many times.
Given an integer, n, find and print the number of letter a's in the first letters of Lilah's infinite string.
For example, if the string s = abcac and n = 10, the substring we consider is abcacabcac, the first 10 characters of her infinite string. There are 4 occurrences of "a" in the substring.
I wrote:
function repeatedString(s, n) {
s = s.repeat(n);
s = s.slice(0, n);
let array = Array.from(s);
let count = 0;
for (let i = 0; i < array.length; i++) {
let char = array[i];
if (char.match(/[a]/gi)) {
count++;
}
}
return count;
}
console.log(repeatedString("abcac", 10));
But HackerRank does not like s = s.repeat(n);, apparently:
I'm not sure how else to generate a string of an appropriate length to slice from. s = s.repeat(Infinity) does not work, and s is not already repeated an infinite number of times when it's passed in as a parameter.
I.e. console.logging(s), initially, logs
abcac
In this case.
I also tried:
function repeatedString(s, n) {
let j = n;
let newString = "";
while (n > 0) {
newString += s;
n--;
}
newString = newString.slice(0, j);
let count = 0;
let array = Array.from(newString);
for (let i = 0; i < array.length; i++) {
let char = array[i];
if (char.match(/[a]/gi)) {
count++;
}
}
return count;
}
console.log(repeatedString("abcac", 10));
But this caused a timeout error.
Any other ideas for how to create a string of valid length to slice from?
EDIT:
Constraints:
1 <= |s| <= 100
1 <= n <= 10^12
For 25% of the test cases, n <= 10^6
actually repeating the string n times is a tremendous waste of memory and runtime.
just compute how often the entire string would be repeated times how many as the string has plus the number of as in the part of s.slice(0, n%s.length)
And your runtime goes down to s.length instead of n
function repeatedString(s, n) {
var r = n % s.length,
m = (n - r) / s.length,
count = 0;
for (var i = 0; i < s.length; ++i) {
if (s[i] === "a") {
count += m + (i < r);
}
}
return count;
}
console.log(repeatedString("abcac", 1234567890));
function repeatedString(s, n) {
var r = n % s.length,
m = (n - r) / s.length,
count = 0;
for (var i = 0; i < s.length; ++i) {
if (s[i] === "a") {
count += m + (i < r);
}
}
return count;
}
console.log(repeatedString("abcac", 1234567890));
I tested this and knows it works. Essentially, I'm not creating a new string, I just find out how many times I have to multiply the original string in order to be able to truncate it. Then I multiply that number by how many a's there were in the original string.
function repeatedString(s, n) {
var charLength = s.length;
var repeat = Math.floor(n/charLength);
var remainder = n%(charLength);
var strCut = s.slice(0, remainder);
let count = 0;
let arrayX = Array.from(s);
for (let i = 0; i < arrayX.length; i++) {
let char = arrayX[i];
if (char.match(/[a]/gi)) {
count++;
}
}
count = count * repeat;
let arrayY = Array.from(strCut);
for (let i = 0; i < arrayY.length; i++) {
let char = arrayY[i];
if (char.match(/[a]/gi)) {
count++;
}
}
return count;
}
console.log(repeatedString("abcac", 10));
I tried a small solution with .repeat but as Thomas said, it's expensive and was taking ages to run tests.
function repeatedString(s, n) {
const allAs = s.match(/a/g);
if (!allAs) {
return 0;
}
if (s === 'a') {
return n;
}
const reps = s.repeat(Math.ceil(n/s.length)).slice(0, n).match(/a/g)
if (!reps) return 0;
return reps.length;
};
console.log(repeatedString('abc', 10));
console.log(repeatedString('abcde', 10));
But I followed Thomas idea and came up with a simpler solution
function repeatedString(s, n) {
const allAs = s.match(/a/g);
if (!allAs) {
return 0;
}
if (s === 'a') {
return n;
}
const rem = n % s.length;
const reps = (n-rem)/s.length;
let count = reps * allAs.length;
if (rem) {
const rest = s.slice(0, rem).match(/a/g);
if (rest) count = count + rest.length
}
return count;
}
console.log(repeatedString('a', 100000));
console.log(repeatedString('abcde', 10000000000));
You could use while loop to repeat original string until length is matched and then match to count the numbers of a.
function repeatedString(s, n) {
let i = 0, l = s.length;
while (s.length < n) s += s[i++ % l]
return s.match(/a/g).length;
}
console.log(repeatedString("abcac", 10));
I did this code and it worked well.
function repeatedString(s, n) {
let modulus = n % s.length;
let repetition = (n - modulus) / s.length;
let remainCounts = s.slice(0, modulus).split("").filter((item) => item == "a").length
return (s.split("").filter((item) => item == "a").length * repetition) + remainCounts
}
enter image description here

How can I see in Javascript if the element of an array is in an odd or in an even position?

For my program, I've to double the numbers of the array in an odd position and then, if that number is over 9, subtract 9 to it. If I had to do it with odd numbers I could easily do it with the following code(Numero is the name of the array):
for (var k = 0; k < Numero.length;k++) {
if ( (Numero[k] % 2) != 0) {
var doppioNumero = Numero[k] * 2;
Numero[k] = doppioNumero;
if ( Numero[k] > 9) {
var nuovoNum = Numero[k] - 9;
Numero[k] = nuovoNum;
}
}
}
The problem is that I do NOT have to do it on odd numbers, I've to do it on numbers in odd positions, like the first number, the third, the fifth, the seventh, the ninth and so on. How can I do it? Thank you very much.
You can change your code to
for (var k = 0; k < Numero.length;k++) {
if ( (k+1)&1) {
var doppioNumero = Numero[k] * 2;
Numero[k] = doppioNumero;
if ( Numero[k] > 9) {
var nuovoNum = Numero[k] - 9;
Numero[k] = nuovoNum;
}
}
}
which would check at odd positions
To check for odd positions, you simply have to check the value of k (modulo) 2:
for (var k = 0; k < Numero.length;k++) {
if ( k % 2) != 0) {
var doppioNumero = Numero[k] * 2;
Numero[k] = doppioNumero;
if ( Numero[k] > 9) {
var nuovoNum = Numero[k] - 9;
Numero[k] = nuovoNum;
}
}
}
for (var i = 0; i < Numero.length; i += 2) {
Numero[i] = (Numero[i] * 2) % 9;
}
You can use map instead of a for loop
Numero.forEach((v, k, arr)=>{
if(k%2==1) arr[k]=arr[k]*2 % 9;
});

Java script random number with allowed to 2 repeat value

How to create the random number to assign in java script array with following condition.
need to create random number with (1-28).
Number allowed to repeat 2 times. (EX: 1,3,5,4,5). .
Simple solution for adding a number to an array based on your criteria:
function addNumberToArray(arr){
const minValue = 1;
const maxValue = 28;
if(arr.length==maxValue*2){ //no possible numbers left
return;
}
function getRandomArbitrary(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
function isValueInArrayLessThenTwoTimes(value, arr){
var occurrences = 0;
for(var i=0; i<arr.length; i++){
if(arr[i]===value){
occurrences++;
}
}
return occurrences<2;
}
var newValue;
do {
newValue = getRandomArbitrary(minValue,maxValue);
} while(!isValueInArrayLessThenTwoTimes(newValue, arr));
arr.push(newValue);
}
A shorter and faster solution:
min=1;
max=28;
nums= new Array();
for(i=1;nums.length<28;i++){
a = Math.round(Math.random()*(max-min+1)+min);
if(nums.indexOf(a)==-1 || nums.indexOf(a)==nums.length-nums.reverse().indexOf(a)-1){
if(nums.indexOf(a)>-1){
nums.reverse();
}
nums.push(a);
}
}
console.log(nums);
https://jsfiddle.net/znge41fn/1/
var array = [];
for (var i = 0; i < 28; i++) {
var randomNumberBetween1and28 = Math.floor(Math.random() * (28 - 1) + 1);
while (getCount(array, randomNumberBetween1and28) > 2) {
randomNumberBetween1and28 = Math.floor(Math.random() * (28 - 1) + 1);
}
array.push(randomNumberBetween1and28);
}
function getCount(arr, value) {
var count = 1;
for (var i = 0; i < arr.length; i++) {
if (value == arr[i]) count++;
}
return count;
}

3 numbers bingo. How could I write it better and shorter?

So I took simple task from a course where they wanted to let user input 3 numbers between 1 and 100 and repeat it until user numbers are higher then 70.
I made this:https://github.com/itayJoseph/Javascript-Bingo/blob/master/Bingo%20V2.js
//Bingo : User puts 3 numbers and they must be all equal to the computer 3 numbers
//Gets 3 Numbers from User
function getUserNum() {
var userNum = [];
for (var i = 0; userNum.length < 3; i++) {
userNum[i] = prompt("insert one number at a time ranging from 1 to 100");
if (userNum[i] > 100 || userNum[i] < 1 || userNum[i] == '') {
alert("Inavlid Number");
comparison();
} else {
userNum[i] = parseInt(userNum[i]);
}
}
console.log(userNum);
return userNum;
}
//Generate numbers from 1 to 100
function numG(x, y) {
var bingo;
bingo = Math.random() * (y - x) + x;
return parseInt(bingo);
}
//Get 3 Numbers from computer
function compNum() {
var bingoNum = [];
for (var j = 0; bingoNum.length < 3; j++) {
bingoNum[j] = numG(1, 100);
}
return bingoNum;
}
/*
This last function does the job of getting the 3
numbers from user then generating its own 3 numbers untill
all 3 numbers are equal.(follow the console to see the progress)
*/
function comparison() {
var userNumbers = getUserNum();
var bingoNumbers;
if (userNumbers.length == 3) {
do {
var numMatches = 0;
bingoNumbers = compNum();
console.log(bingoNumbers);
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
if (userNumbers[i] == bingoNumbers[j]) {
numMatches += 1;
}
}
}
} while (numMatches != 3)
}
if (numMatches == 3) {
alert("BINGOOOO");
}
}
comparison();

formatMoney function in Javascript doesn't work

I need a function which can transform the number 10000 to this number: 10.000.
So I tried the following:
function formatMoney(money){
var value = money.toString();
var l = value.length;
var new_value = 0;
new_value = new_value.toString();
if(l > 3){
var moneyarray = value.split('');
var u = 0;
for(i = l;i >= 0;i--){
if(u > 3){
u = 0;
new_value = "."+new_value;
}
new_value = moneyarray[i]+new_value;
u++;
}
}
return new_value;
}
And then call this:
formatMoney("10000");
But the result is
10.000undefined0"
What did I do wrong?
You're assigning the index counter to the length of the string;
var l = value.length;
...
for(i = l;i >= 0;i--){
And the down count starts with the length-index, which isn't present since arrays are zero-based. Subtract beforehand instead;
for(i = l;i >= 0;--i){
EDIT: Disregard this, I wasn't paying enough attention to the question.
If all you're looking to do is take numbers that are 4 digits or greater and put a dot in three digits from the right, you could give this a shot:
function formatMoney(money) {
var moneyString = money.toString();
var moneyLength = moneyString.length;
if(moneyLength < 4) {
return 0;
}
var dotIndex = moneyLength - 3;
return moneyString.substr(0, dotIndex) + "." + moneyString.substr(dotIndex);
}
Also, formatting your code in the post is good stuff. Indent it all by four spaces.
function formatMoney(money){
var value = money.toString();
var l = value.length;
var new_value = 0;
new_value = new_value.toString();
if(l > 3){
var moneyarray = value.split('');
for(var i = l-1;i >= 0;i--){
if((l-i)%3 === 0){
new_value = "."+new_value;
}
new_value = moneyarray[i]+new_value;
}
} else {
new_value = value;
}
return new_value;
}
A couple of things:
You were counting down with the wrong index (you were starting at l, instead of l-1)
You were not handling any value less than 1000
You don't need to use a counter variable u, you can just use modulo math to keep track of threes.
I cut off some parts:
function formatMoney(money) {
var value = money.toString();
var l = value.length;
var new_value = "";
if (l > 3) {
var u = 0;
for (i = l-1;i >= 0;i--) {
if (u == 3) {
u = 0;
new_value = "." + new_value;
}
new_value = value[i]+new_value;
u++;
}
}
return new_value;
}
You could do it like this:
function money(m) {
m = m.toString().split('');
for (var i = m.length - 3; i > 0; i -= 3)
m.splice(i,0,".");
return m.join('');
}
console.log(money(1000000)); // "1.000.000
See this JsBin

Categories

Resources