'Swap' values within a range - javascript

I get data that is a floating point value between 1 and 7.
1 is bad, 7 is good.
Sometimes, when I get that data, I'd like to 'reverse' it, as the questions were written negatively, where 1 is good, and 7 bad.
A score of 1 should be 'swapped' to a score of 7.
A score of 2 should be 'swapped' to a score of 6.
A score of 2.5 should be 'swapped' to a score of 4.5.
Originally I thought I could use an array:
const array = [1,2,3,4,5,6,7]
return array[answer] - 1;
or Math.abs(answer - 6) but neither are going to work out.

I think you don't need an array, if your values are fixed (from 1 to 7) you can just substract from 8:
return 8 - answer;

Here is a simple function to achieve that:
function reverseRating(rating) {
return 8 - rating
}

The following function accomplishes this:
function reverseOnScale(answer, from, to) {
answerMinus = answer - from;
reversedMinus = Math.abs(answerMinus - (to - from));
reversed = reversedMinus + from;
return reversed;
}
Usage example:
reverseOnScale(5, 1, 7);
Outputs the value 3.

Related

JavasScript Add half a percent to a number any amount of times I choose

Hi I need a block of code for some math that I'm trying to work out. The code I'm looking for will be able to add half a percent (0.005) to a number and return the result back to me. I need the code to take two separate inputs, the first is the start number, and the second is how many times I want the loop to execute. An example would be if I started with 7000 the code should output ~7321.37 (if possible let it stop after 2 decimal points). Thank you for the help in advance!
Code example of what I'm trying to do:
function growth(initialValue, timesOfExecution)` {
let answer;
let execute;
while (execute > 0) {
answer = initialValue + initialValue(0.05)
execute--
}
return answer;
}
console.log(growth(7000, 9))
Here you go:
function growth(initialValue, timesOfExecution) {
for (let i = 0; i < timesOfExecution; i++) {
initialValue = initialValue + (initialValue * 0.005)
}
return initialValue.toFixed(2);
}
console.log(growth(7000, 9))

Divide 100 in equal percentages in JavaScript

Ok. I will try to explain my case as good as I can.
Basically, I have this function here that will add an increment to my bootstrap progressbar:
function progress(increment) {
f = parseInt(document.getElementsByClassName('progress-bar')[0].style.width);
document.getElementsByClassName('progress-bar')[0].style.width = (f + increment) +'%';
}
Now for each step, for instance there are 6 steps, I must divide 100 into 6 steps incrementally.
For instance, if we are in step 1: 100 / 6 = 16.67 each so this must add 16.67 incrementally.
So it would be like this:
Step 1: Add 16.67
Step 2: Add 33.34
Step 3: Add 50.01
---- and the list go on
So on my program I have the ff variables:
let current_step = 0;
let stepCount = 6
So if I used the progress function, I tried dividing 100 to stepCount to the current_step:
progress(100 / (stepCount - current_step)
But this did not resolve the issue and I am getting only weird numbers.
Any idea what's the proper formula here to get the right numbers to add on the progressbar?
PS. Sorry, I hope its not that confusing. I tried to explain this at the best I can.
Your calculation isn't correct. This should give you the correct value.
progress((100 / stepCount) * current_step);
function progress(value) {
document.getElementsByClassName('progress-bar')[0].style.width = `${value}%`;
}
or you can do it like this
progress(100 / stepCount);
function progress(increment) {
let f = +document.querySelector('.progress-bar')[0].style.width.slice(0, -1);
// I'm slicing the width to remove the `%`
document.getElementsByClassName('progress-bar')[0].style.width = `${f + increment}%`;
}

Not every number are shown, when their sum of the divisors are good for the conditions

I did a bit of coding in javascript and I don't understand the problem...
My goal is to get every divisor of a given number and check if the sum of them is greater than the number itself.
The divisors should include one, but not the number itself.
I made 2 functions to separate the code and make it more readable for now.
In the first 12 number, the condition apply only for the number 12 because 1+2+3+4+6=16 which is greater than 12 and it shows it correctly, but when I try the function with the first 20 number, only 18 and 20 are shown, when 12 is clearly good. It disappears when the loop reaches the number 16.
Here is my code:
function getDivisors(n){
var divisors=new Array();
for(var x=1;x<n;x++){
if(n%x==0) divisors.push(x);
}
return divisors;
}
function getNumbers(n){
var numbers=new Array(),
sum=0;
for(var x=1;x<=n;x++){
sum=getDivisors(x).reduce((a, b) => a + b, 0);
if(sum>n) numbers.push(x);
console.log("Number: "+x+" sum:"+sum);
}
return numbers;
}
console.log(getNumbers(20));
You should have if (sum>x) instead of if (sum>n) inside the for loop in getNumbers(n).

Javascript: Basic for loop?

I just completed some form of a competency exam for a programming school, and I got every question correct except this, although it appears really quite easy, yet I couldn't get it. Any ideas?
Observe the code below.
var x = [1,5,7,13];
for(i=0; i < x.length; i++)
{
x[i] = x[3-i] + 2;
}
Once the program is done, what would be in x?
a [3,7,9,15]
b [15,9,11,3]
c [15,9,7,3]
d [15,9,11,17]
The answer is d
first loop
x[0] = 13 + 2 = 15
second loop
x[1] = 7 + 2 = 9
third loop
x[2] = 9 + 2 = 11
fourth loop
x[3] = 15 + 2 = 17
x = {15, 9, 11, 17}
To figure this out, you'll have to understand that x[] is used to refer to a specific index of the array. For example:
var x = [5,6,7];
In this case, x[0] would be equal to 5, assuming a 0-index based array.
Knowing this, let's break down your loop. We'll start by filling in the variable name instead of the variable value step by step, to leave out confusion of following variables in your head.
var x = [1,5,7,13];
for(0=0; 0 < x.length; 0++)
{
x[0] = x[3-0] + 2;
}
For the first iteration, everything starts to become a little clearer as you can tell that now it's setting x[0] (the first value in the array) to equal x[3-0] (which would be x[3], which in turn would be 13 due to the 0-index array), plus 2. 13 + 2 = 15. The first number is 15.
var x = [1,5,7,13];
for(1=1; 1 < x.length; 1++)
{
x[1] = x[3-1] + 2;
}
Let's try one more! x[3-1] is the same as x[2] which is 7; 7 + 2 = 9. Your second number is 9.
Following the same logic you can see how the loop functions and understand how it's referencing the array's values.
The key here is that you're updating the same array you're reading from as you go through it. (Note: generally I'd consider this bad practice and I've seen a lot of programmers fall into this trap - it's very easy to misunderstand the code).
First thing to realize is that x[3-i] basically reads the opposite end of the current index. To be more generic, it should really have been x[(x.length-1)-i] but the 3 is hardcoded in this case.
Now, the first round is easy: 13+2 = 15. 13 because the opposite end of the first element is the last element:
x = [15,5,7,13]
▲ │ this+2
└──────┘
In the second round we replace 5 with 7+2 = 9:
x = [15,9,7,13]
▲ │ this+2
└─┘
In the third round we find ourselves doing something not initially obvious. Instead of replacing 7 with 5+2 we replace it with 9+2 instead because we've already replaced 5 with 9:
x = [15,9,11,13]
│ ▲
this+2 └─┘
Now finally we replace the last element with 15+2 using the same reasoning above:
x = [15,9,11,17]
│ ▲
└───────┘
this+2

number incrementing in Angular.js

I'm attempting to build an app that calculates sales metrics. I have run into an unusual problem in my build.
Part of the app allows users to increase/decrease a variable by 5% and then see how that will effect an overall metric. It also allows the user to see the percentage increase/decrease.
I have the functionality working roughly as intended, however if I enter a number lower than 20 into the input and then try in increase it with my incrementing function it only increments once and then stops.
If the number I enter into the input is 20 or greater it increments in the intended way.
Below is my angular code:
function controller ($scope) {
$scope.firstNumber = 0;
$scope.firstPercent = 0;
$scope.increase = function(id) {
var A = parseInt(id);
var B = A * 5/100;
var C = 0;
var C = A + B;
if (id === $scope.firstNumber) {
$scope.firstNumber = C;
$scope.firstPercent = $scope.firstPercent + 5;
}
};
$scope.decrease = function(id) {
var A = parseInt(id);
var B = A * 5/100;
var C = 0;
var C = A - B;
if (id === $scope.firstNumber) {
$scope.firstNumber = C;
$scope.firstPercent = $scope.firstPercent - 5;
}
};
I can't see anything wrong with my maths, my thinking is that perhaps I'm approaching angular in the wrong way. However I'm not sure.
I have put together a fiddle that shows the full code.
jsFiddle
I have updated the fiddle to use parseFloat. Seems like the numbers are incrementing now.
var A = parseFloat(id);
http://jsfiddle.net/kjDx7/1/
The reason why it was working with values above 20 was that it was just reading the part before decimals each time it tried to increase. So 20 became 21 and 22.05 and so on. As long the the value before decimal kept changing, it showed different (but incorrect) answers.
On the other hand, 10 became 10.5 which when parsed yielded 10. As you can see, this cycle continued endlessly.
The reason why you face the issue is because 5% of anything less than or equal to 20 is less than or equal to 1.
When you parseInt() the value, you always end up with the same number again.
Take 15 for example.
5% of 15 = 15.75
After parseInt(), you get the value 15 again.
You use the same value to increment / decrement each time.
Hence for values below 20, you don't get any changes.
As #Akash suggests, use parseFloat() instead - or why even do that when the value that you get is float anyway
I made a fork of your fiddle. I'm not completely sure what you want to achive.
Take a look at this fiddle.
$scope.increase = function() {
$scope.firstPercent = $scope.firstPercent + 5;
var A = $scope.firstNumber;
var B = (A / 100) * $scope.firstPercent;
var C = A + B;
$scope.firstNumberWithPercent = C;
};
update
After posting, i see that question is already answered. But is this what you really want? When you hit increase, it takes 5 % off of the number in the input field. That is ok, but when you hit decrease after that, it takes 5 % off the number in the same field. So your starting point is different.
100 + 5/100 = 105
105 - 5/105 = 99,75

Categories

Resources