<script>
function calculate() {
var num = document.getElementById("decimal").value; //fetching binary value from html input box.
var bin = [];
while (num > 0) {
bin[bin.length] = num % 2;
num >>= 1; // basically /= 2 without remainder if any
}
document.getElementById("result").innerHTML = "Binary Value: " + bin.reverse().join('');
}
</script>
I am trying to understand this code i can't understand these two lines in this code:
bin[bin.length] = num % 2;
num >>= 1;`
bin[bin.length] = num % 2;
Append a 0 or 1 to bin depending on whether num is even or odd.
num >>= 1;
As the comment says, this divides num by 2 without remainder. Overall, the loop puts the digits of the binary representation of num into bin from least significant to most. That is why it is reversed at the end.
bin[bin.length] is just the index of the number (string,actually) that will be crated. For each bin.reverse() it increments by one. The num is a number in digital form. num >>= 1 just shifts right 1 digits. This has an affect to divine the decimal by 2. bin[bin.length] = num % 2 just result to 0 or 1 and add each time to the string to form the final answer.
I am not sure which part you do not understand. Some operator or the whole logic?
You want to know how bin[bin.length] = ... puts the value in the correct spot. Well, bin starts as an empty array (bin = []) which has length 0. So bin[bin.length] = bin[0] to start and the first thing is inserted appropriately at index 0.
This length property is maintained internally as things are inserted into the array. So it will always insert in the first available slot.
Example: after something has been added at index 0, the length property is updated to 1 and the next insertion is done at bin[bin.length] which is equivalent to bin[1].
Related
could you please help me understand why the following line result is [1,3]?
[1,3,6].filter( item => item % 2)
I was expecting to receive the even number from the array.
Many thanks!
Filter checks for a boolean, 3 % 2 is equal to 1, which evaluates to true.
You want item % 2 == 0
Even numbers are those numbers that are exactly divisible by 2.
The remainder operator % gives the remainder when used with a number. For example,
const number = 6;
const result = number % 4; // 2
Hence, when % is used with 2, the number is even if the remainder is zero. Otherwise, the number is odd.
// program to check if the number is even or odd
// take input from the user
const number = prompt("Enter a number: ");
//check if the number is **even**
if(number % 2 == 0) {
console.log("The number is even.");
}
// if the number is **odd**
else {
console.log("The number is odd.");
}
ref : https://www.programiz.com/javascript/examples/even-odd
code:
function OneDecremented(num) {
num = num.toString()
var count = 0
for(i = 1; i < num.length; i++) {
if(num[i - 1] - num[i] === 1){
count++
}
}
return count
}
console.log(OneDecremented(9876541110))
so I'm struggling to understand two things:
what's the difference between i and num[i]
I don't understand how the calculation is happening inside the if statement, could someone break it down?
sorry if these questions sound too silly, I'm new to JS and couldn't really get my head around the arithmetic calculations. Thank you for you time.
That code is poorly written for few reasons, but most importantly, it leaks the i reference globally so, let's start with a better version:
function OneDecremented(num) {
var str = num.toString();
var count = 0;
for(var i = 1; i < str.length; i++) {
if(str[i - 1] - str[i] === 1)
count++;
}
return count;
}
Strings, in modern JS, can be accessed like arrays, and the index returns the char at the index position:
if(str[i - 1] - str[i] === 1)
// is the same as
if ((str.charAt(i - 1) - str.charAt(i)) === 1)
Once retrieved each char, the code does an implicit "char to number" conversion, thanks to the - operator, but if it was a + instead, it would've concatenated the two chars as string instead (so, be careful).
It's always better to be explicit, but if you know how - works, it does the job for this task.
The loop starts from 1, and it checks that the char at i - 1, which is in the first iteration the char at index 0, minus the current char, is 1, meaning the current char is one less the previous.
When that's the case, the counter sums up.
Andrea and Mitya already nailed it.
The next step could be switching to a first class based approach like using a specific Array method such as reduce.
Such an approach, if implemented correctly, usually improves readability/maintainability of code and allows for better code-reuse.
For the example provided by the OP one could write two functions, the actual method, which gets the count and the above mentioned first class reducer functionality. Since reduce is a standard way of how arrays can be processed the arguments-precedence of the reducer/callback is well specified too ...
[/* ... */].reduce(function(accumulator, currentValue, currentIndex, currentlyProcessedArray) {
// implement reducer/aggregation/accumulator logic here.
// the return value serves as the
// new `accumulator` value within
// the next iteration step.
// thus, always return something! ... e.g ...
return (accumulator + currentValue);
});
function aggregatePrecursorAndDecrementedSuccessorCount(count, char, idx, arr) {
const precursorValue = Number(arr[idx - 1]);
const incrementedCurrentValue = (Number(char) + 1);
const isValidCount = (precursorValue === incrementedCurrentValue);
return (count + (isValidCount ? 1 : 0));
//return (count + Number(isValidCount)); // cast boolean value to either 1 or 0.
}
function getPrecursorAndDecrementedSuccessorCount(int) {
return String(int) // - assure/typecast always a/into string value.
.split('') // - split string value into an array of single characters.
.reduce(aggregatePrecursorAndDecrementedSuccessorCount, 0);
}
console.log(getPrecursorAndDecrementedSuccessorCount(9876541110));
.as-console-wrapper { min-height: 100%!important; top: 0; }
what's the difference between i and num[i]
i is the iteration key, i.e. 0, 1, 2 etc, for as many characters are in the stringified number. num[i] is the character at the index i in the string, i.e. num[i] where i is 0 == 9 (the character in the string at index 0).
I don't understand how the calculation is happening inside the if statement, could someone break it down?
That says: If the calculation of the number at index i-1 of the string, minus the current number being considered (at index i in the string) minus is 1, then increment count.
Step by step for the actual number used:
9 - has no previous character; calculation (undefined - 9) does not equate to 1
8 - previous char is 9; (9 - 8) == 1; increment count
7 - ditto
6 - ditto
5 - ditto
4 - ditto
1 - previous char is 4; calculation (4 - 1) does not equate to 1
1 - previous char is 1; calculation (1 - 1) does not equate to 1
1 - ditto
0 - previous char is 1; (1 - 0) == 1; increment count
I'm trying to solve all the lessons on codility but I failed to do so on the following problem: Ladder by codility
I've searched all over the internet and I'm not finding a answer that satisfies me because no one answers why the max variable impacts so much the result.
So, before posting the code, I'll explain the thinking.
By looking at it I didn't need much time to understand that the total number of combinations it's a Fibonacci number, and removing the 0 from the Fibonacci array, I'd find the answer really fast.
Now, afterwards, they told that we should return the number of combinations modulus 2^B[i].
So far so good, and I decided to submit it without the var max, then I got a score of 37%.. I searched all over the internet and the 100% result was similar to mine but they added that max = Math.pow(2,30).
Can anyone explain to me how and why that max influences so much the score?
My Code:
// Powers 2 to num
function pow(num){
return Math.pow(2,num);
}
// Returns a array with all fibonacci numbers except for 0
function fibArray(num){
// const max = pow(30); -> Adding this max to the fibonaccy array makes the answer be 100%
const arr = [0,1,1];
let current = 2;
while(current<=num){
current++;
// next = arr[current-1]+arr[current-2] % max;
next = arr[current-1]+arr[current-2]; // Without this max it's 30 %
arr.push(next);
}
arr.shift(); // remove 0
return arr;
}
function solution(A, B) {
let f = fibArray(A.length + 1);
let res = new Array(A.length);
for (let i = 0; i < A.length; ++i) {
res[i] = f[A[i]] % (pow(B[i]));
}
return res;
}
console.log(solution([4,4,5,5,1],[3,2,4,3,1])); //5,1,8,0,1
// Note that the console.log wont differ in this solution having max set or not.
// Running the exercise on Codility shows the full log with all details
// of where it passed and where it failed.
The limits for input parameters are:
Assume that:
L is an integer within the range [1..50,000];
each element of array A is an integer within the range [1..L];
each element of array B is an integer within the range [1..30].
So the array f in fibArray can be 50,001 long.
Fibonacci numbers grow exponentially; according to this page, the 50,000th Fib number has over 10,000 digits.
Javascript does not have built-in support for arbitrary precision integers, and even doubles only offer ~14 s.f. of precision. So with your modified code, you will get "garbage" values for any significant value of L. This is why you only got 30%.
But why is max necessary? Modulo math tells us that:
(a + b) % c = ([a % c] + [b % c]) % c
So by applying % max to the iterative calculation step arr[current-1] + arr[current-2], every element in fibArray becomes its corresponding Fib number mod max, without any variable exceeding the value of max (or built-in integer types) at any time:
fibArray[2] = (fibArray[1] + fibArray[0]) % max = (F1 + F0) % max = F2 % max
fibArray[3] = (F2 % max + F1) % max = (F2 + F1) % max = F3 % max
fibArray[4] = (F3 % max + F2 % max) = (F3 + F2) % max = F4 % max
and so on ...
(Fn is the n-th Fib number)
Note that as B[i] will never exceed 30, pow(2, B[i]) <= max; therefore, since max is always divisible by pow(2, B[i]), applying % max does not affect the final result.
Here is a python 100% answer that I hope offers an explanation :-)
In a nutshell; modulus % is similar to 'bitwise and' & for certain numbers.
eg any number % 10 is equivalent to the right most digit.
284%10 = 4
1994%10 = 4
FACTS OF LIFE:
for multiples of 2 -> X % Y is equivalent to X & ( Y - 1 )
precomputing (2**i)-1 for i in range(1, 31) is faster than computing everything in B when super large arrays are given as args for this particular lesson.
Thus fib(A[i]) & pb[B[i]] will be faster to compute than an X % Y style thingy.
https://app.codility.com/demo/results/trainingEXWWGY-UUR/
And for completeness the code is here.
https://github.com/niall-oc/things/blob/master/codility/ladder.py
Here is my explanation and solution in C++:
Compute the first L fibonacci numbers. Each calculation needs modulo 2^30 because the 50000th fibonacci number cannot be stored even in long double, it is so big. Since INT_MAX is 2^31, the summary of previously modulo'd numbers by 2^30 cannot exceed that. Therefore, we do not need to have bigger store and/or casting.
Go through the arrays executing the lookup and modulos. We can be sure this gives the correct result since modulo 2^30 does not take any information away. E.g. modulo 100 does not take away any information for subsequent modulo 10.
vector<int> solution(vector<int> &A, vector<int> &B)
{
const int L = A.size();
vector<int> fibonacci_numbers(L, 1);
fibonacci_numbers[1] = 2;
static const int pow_2_30 = pow(2, 30);
for (int i = 2; i < L; ++i) {
fibonacci_numbers[i] = (fibonacci_numbers[i - 1] + fibonacci_numbers[i - 2]) % pow_2_30;
}
vector<int> consecutive_answers(L, 0);
for (int i = 0; i < L; ++i) {
consecutive_answers[i] = fibonacci_numbers[A[i] - 1] % static_cast<int>(pow(2, B[i]));
}
return consecutive_answers;
}
So I have a number like 5467. I want my code to return 546.
I tried taking the last number and subtracting it from the original number but I get 5460 instead of 546.
Combine / with %:
(5467 - (5467 % 10)) / 10
564
Sounds like you also need to divide my 10. You could do something like this:
var number = 5467;
number = number - (number % 10); // This will subtract off the last digit.
number = number / 10;
console.log(number); // 546
We first use the modulo operator % to get the last digit, and we subtract it from number. That reduces the number from 5467 to 5460. Now to chop off the last digit (which is guaranteed to be a 0) we divide by 10 and get 546.
Written more concisely you could do:
number = (number - ( number % 10)) / 10;
There's a few things you can do the most concise being:
Math.floor(num / 10);
Or, convert to a string, remove the last character and convert back to number.
parseInt(num.toString().slice(0, -1));
If string representation would be fine for you then one other way is
var num = 5467,
cut = (num/10).toFixed(); // <-'547'
Well... warning..! i have to say toFixed() method rounds if necessary. So in this particular example it doesn't work.
I dont mind some of the other answers, but i feel that this maybe too fixed on it being a number.
Which it is, but you want to remove the last digit/char, regardless of the number, so why not substr?
http://www.w3schools.com/jsref/jsref_substr.asp
var s = 5467;
s = s.toString().substr(0, s.toString().length - 1);
console.log(s)
or even easier:
var s = (5467).toString();
s = s.substr(0, s.length - 1);
console.log(s)
These dont take into account single digit numbers, so passing in 1 would return blank. To answer that you could simply do a check like:
var s = (1).toString();
if(s.length > 1)
s = s.substr(0, s.length - 1);
console.log(s)
Also, similar question to:
Remove last digits from an int
Remove the last digits of a number (not string)
Removing the last digits in string
To truncate digits from the right hand side until the number is less than 30, keep dividing by 10 and rounding down until a suitable value is reached:
var n = 12341235;
while (n > 30) n = n/10|0;
document.write(n);
The greater than and division operations will coerce n to a number, so it can be a number or string. If ToNumber(n) results in NaN (e.g. n = 'foo'), then the value of n is not modified.
You can simply divide the number by 10 and parseInt()
var num = 5467;
num = parseInt(num/10);
Update :
To repeat the process until the answer is less than 30, use while loop as
var num = 5467;
while(num >= 30) {
num = parseInt(num/10);
}
document.write(num);
What's the best way to get the Nth digit of a number in javascript?
For example, for 31415926, the function will return 1 if N=2.
EDIT: And if possible, tu return directly a number, not a string.
EDIT 2: It is from left to right.
Try with that : (''+number)[nth] or (''+number)[nth-1] if one-based.
Personally, I would use:
function getNthDigit(number, n){
return parseInt((""+number).charAt(n));
}
But if you don't want it to be in String form ever you could use:
function getNthDigit(number, n){
var num = number,
digits = 0;
do{
num /= 10;
digits++;
}while(num>=1);
num = number / Math.pow(10, (digits - n));
num -= num % 1;
return (num % 10);
}
On second thought, just use the first option.
UPDATE: I didn't consider the fact that it was counting from the right. My bad!
Anyway, considering that the input is STILL a string, I'd use the same function, just with a little tweak.
Why don't you use the CharAt function? I think is the best option, considering the risk of multi-byte strings!!!
EDIT: I forgot the example:
var str = "1234567";
var n = str.charAt(str.length-2); // n is "6"