I wonder what this function really does .split(' ').map(x => +x); - javascript

I saw this line of code in a correction in a coding game
const tC = readline().split(' ').map(x => +x);
I wonder what it does because when I log this function it render the same thing that this one
const tC = readline().split(' ').map(x => x);
but the rest of the code didn't work
Context :
/** Temperatures (easy) https://www.codingame.com/training/easy/temperatures
* Solving this puzzle validates that the loop concept is understood and that
* you can compare a list of values.
* This puzzle is also a playground to experiment the concept of lambdas in
* different programming languages. It's also an opportunity to discover
* functional programming.
*
* Statement:
* Your program must analyze records of temperatures to find the closest to
* zero.
*
* Story:
* It's freezing cold out there! Will you be able to find the temperature
* closest to zero in a set of temperatures readings?
**/
const N = +readline();
const tC = readline().split(' ').map(x => +x);
let min = Infinity;
for (let i in tC) {
(Math.abs(tC[i]) < Math.abs(min) || tC[i] === -min && tC[i] > 0) && (min = tC[i]);
}
print(min || 0);
Thanks a lot

The .map(x => +x) converts all items in the array to a number. And returns a new array with those converted values.
If you change it to .map(x => x) then the values are left untouched und you just create a copy of the original array. So the strings remain strings which will break the code if numbers are expected.
I personally would avoid the +x syntax and use the more verbose Number(x), and write either .map(x => Number(x)) or .map(Number).

According to this site below are the inputs the program should receive
Line 1: N, the number of temperatures to analyze
Line 2: A string with the N temperatures expressed as integers ranging from -273 to 5526
Let me provide line by line comments with respect to the game rules
// Line 1: reads number temperature inputs. + converts to number
const N = +readline();
// Line 2: reads string of temperatures.
// tC contains an array of temperatures of length N in numbers. + converts to number
const tC = readline().split(' ').map(x => +x);
let min = Infinity;
// iterate over tC array
for (let i in tC) {
// If two numbers are equally close to zero, positive integer has to be considered closest to zero
// set min = current iterating number if it matches above condition
(Math.abs(tC[i]) < Math.abs(min) || tC[i] === -min && tC[i] > 0) && (min = tC[i]);
}
print(min || 0);
Here is the working demo in javascript
modified to make it understandable for beginners.
// Line 1: reads number temperature inputs. + converts to number
// const N = +readline(); SAMPLE ALTERNATIVE
const N = +"5";
// Line 2: reads string of temperatures.
// tC contains an array of temperatures of length N in numbers. + converts to number
// const tC = readline().split(' ').map(x => +x); SAMPLE ALTERNATIVE
const tC = "1 -2 -8 4 5".split(' ').map(x => +x);
let min = Infinity;
// iterate over tC array
for (let i in tC) {
// If two numbers are equally close to zero, positive integer has to be considered closest to zero
// set min = current iterating number if it matches above condition
(Math.abs(tC[i]) < Math.abs(min) || tC[i] === -min && tC[i] > 0) && (min = tC[i]);
}
console.log(min || 0);

function readLine(){
return "123456"
}
var result = readLine().split("").map(x => +x)
console.log(result)
readLine().split("") // splits the string into an array as follows ["1", "2", "3", "4", "5", "6"]
.map(x => +x) // map method returns a new array which will take each item and gives a new array , here number changing from string to numbers as follows [1, 2, 3, 4, 5, 6] since +x is used
// the above is written in es6, which can be re written in es5 as follows
readLine().split("").map(function(x) {
return +x
})
// Note
In es6 if we have a single thing to pass we can avoid the function(x) to x
also we can remove the {} [curly braces and return too]
{return +x} to +x
ES2015
readLine().split("").map(function(x) {
return +x
})
ES2016
readLine().split("").map(x => +x);

Related

in Javascript, exist a function that return only the fractional part of a number, like Math dot something.... ? How can I get it? [duplicate]

I have a floating point number:
var f = 0.1457;
Or:
var f = 4.7005
How do I get just the fraction remainder as integer?
I.e. in the first example I want to get:
var remainder = 1457;
In the second example:
var remainder = 7005;
function frac(f) {
return f % 1;
}
While this is not what most people will want, but TS asked for fract as integer, here it is:
function fract(n){ return Number(String(n).split('.')[1] || 0); }
fract(1.23) // = 23
fract(123) // = 0
fract(0.0008) // = 8
This will do it (up to the 4 digits that you want, change the multipler (10000) to larger or smaller if you want smaller or larger number):
Math.ceil(((f < 1.0) ? f : (f % Math.floor(f))) * 10000)
parseInt(parseFloat(amount).toString().split('.')[1], 10)
You can subtract the floor of the number, giving you just the fractional part, and then multiply by 10000, i.e.:
var remainder = (f-Math.floor(f))*10000;
I would argue that, assuming we want to display these values to the user, treating these numbers as strings would be the best approach. This gets round the issue of fractional values such as 0.002.
I came accross this issue when trying to display prices with the cents in superscript.
let price = 23.43; // 23.43
let strPrice = price.toFixed(2) + ''; // "23.43"
let integer = strPrice.split(".")[0] // "23"
let fractional = strPrice.split(".")[1] // "43"
This also depends on what you want to do with the remainder (as commenters already asked). For instance, if the base number is 1.03, do you want the returned remainder as 3 or 03 -- I mean, do you want it as a number or as a string (for purposes of displaying it to the user). One example would be article price display, where you don't want to conver 03 to 3 (for instance $1.03) where you want to superscript 03.
Next, the problem is with float precision. Consider this:
var price = 1.03;
var frac = (price - Math.floor(price))*100;
// frac = 3.0000000000000027
So you can "solve" this by slicing the string representation without multiplication (and optional zero-padding) in such cases. At the same time, you avoid floating precision issue. Also demonstrated in this jsfiddle.
This post about floating precision might help as well as this one.
var strNumber = f.toString();
var remainder = strNumber.substr(strNumber.indexOf('.') + 1, 4);
remainder = Number(reminder);
Similar method to Martina's answer with a basic modulo operation but solves some of the issues in the comments by returning the same number of decimal places as passed in.
Modifies a method from an answer to a different question on SO which handles the scientific notation for small floats.
Additionally allows the fractional part to be returned as an integer (ie OP's request).
function sfract(n, toInt) {
toInt = false || toInt;
let dec = n.toString().split('e-');
let places = dec.length > 1
? parseInt(dec[1], 10)
: Math.floor(n) !== n ? dec[0].split('.')[1].length : 0;
let fract = parseFloat((n%1).toFixed(places));
return toInt ? fract * Math.pow(10,places) : fract;
};
Tests
function sfract(n, toInt) {
toInt = false || toInt;
let dec = n.toString().split('e-');
let places = dec.length > 1
? parseInt(dec[1], 10)
: Math.floor(n) !== n ? dec[0].split('.')[1].length : 0;
let fract = parseFloat((n%1).toFixed(places));
return toInt ? fract * Math.pow(10,places) : fract;
};
console.log(sfract(0.0000005)); // 5e-7
console.log(sfract(0.0000005, true)); // 5
console.log(sfract(4444)); // 0
console.log(sfract(4444, true)); // 0
console.log(sfract(44444.0000005)); // 5e-7
console.log(sfract(44444.00052121, true)); // 52121
console.log(sfract(34.5697)); // 0.5697
console.log(sfract(730.4583333333321, true)); // 4583333333321
#Udara Seneviratne
const findFraction = (num) => {
return parseInt( // 5.---------------- And finally we parses a "string" type and returns an integer
// 1. We convert our parameter "num" to the "string" type (to work as with an array in the next step)
// result: "1.012312"
num.toString()
// 2. Here we separating the string as an array using the separator: " . "
// result: ["1", "012312"]
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
.split('.')
// 3. With help a method "Array.splice" we cut the first element of our array
// result: ["012312"]
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
.splice(1.1)
// 4. With help a method "Array.shift" we remove the first element from an array and returns that
// result: 012312 (But it's still the "string" type)
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
.shift()
)
}
// Try it
console.log("Result is = " + findFraction (1.012312))
// Type of result
console.log("Type of result = " + typeof findFraction (1.012312))
// Some later operation
console.log("Result + some number is = " + findFraction (1.012312) + 555)

What am I missing in my approach to this Dynamic Programming problem? (Leetcode 740. Delete and Earn)

I'm trying to understand how to solve Leetcode Problem #740: Delete and Earn
I recently was given this problem as part of a pre-interview assessment and was unable to complete it in the allotted time. I've been working on it today to try and wrap my head around it, but I'm kinda spinning in circles at the moment. I've checked numerous resources, videos, tutorials, etc, but I'm working in vanilla JS and a lot of the guides are in C++, Python, or Typescript which I don't currently know. (I plan on learning Python and Typescript at minimum, but I'm working with my current set of knowledge for the time being). This is leading to confusion and frustration, as an accurate translation of sample python/c++ code, etc continues to elude me.
The problem is as follows:
You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times:
Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1.
Return the maximum number of points you can earn by applying the above operation some number of times.
Example 1
Input: nums = [3,4,2]
Output: 6
Explanation: You can perform the following operations:
- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2].
- Delete 2 to earn 2 points. nums = [].
You earn a total of 6 points.
Example 2
Input: nums = [2,2,3,3,3,4]
Output: 9
Explanation: You can perform the following operations:
- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3].
- Delete a 3 again to earn 3 points. nums = [3].
- Delete a 3 once more to earn 3 points. nums = [].
You earn a total of 9 points.
What I have so far:
const deleteAndEarn = (nums) => {
if(!nums || nums.length === 0) return 0;
if(nums.length === 1) return nums[0];
if(nums.length === 2) return nums[1];
const freq = makeDict(nums);
let prevNum
let [keep, avoid] = [0, 0];
for(const num of [...Object.keys(freq)].sort()){
let max = Math.max(keep, avoid)
if(parseInt(num) - 1 !== prevNum){
[keep, avoid] = [
(freq[num] * parseInt(num)) + max,
max
]
}else{
[keep, avoid] = [
parseInt(num) * freq[num] + avoid,
max
]
}
prevNum = parseInt(num)
}
return Math.max(keep, avoid)
};
const makeDict = (nums) => {
const dict = {}
for(const num of nums){
dict[num] = !!dict[num] ? dict[num]++ : 1
}
return dict
}
Provided Python Solution
This is what I've tried to model my code off of, but I don't actually know Python syntax so I'm sure I'm missing something.
class Solution(object):
def deleteAndEarn(self, nums):
count = collections.Counter(nums)
prev = None
avoid = using = 0
for k in sorted(count):
if k - 1 != prev:
avoid, using = max(avoid, using), k * count[k] + max(avoid, using)
else:
avoid, using = max(avoid, using), k * count[k] + avoid
prev = k
return max(avoid, using)
I really don't understand at all why this code isn't working, and I've even gone as far as to run sample cases step by step. Please help me understand how to do this so I can get a job!
Many thanks
I figured it out! The problem is twofold.
Bug Number One
First, shoutout to David Eisenstat for catching the bug in my makeDict() function.
The incorrect line of code reads:
dict[num] = !!dict[num] ? dict[num]++ : 1
Whereas the correct syntax is as follows:
dict[num] = !!dict[num] ? ++dict[num] : 1
or alternatively
dict[num] = !!dict[num] ? dict[num] + 1 : 1
The issue comes from how postfix vs prefix increment operators work in Javascript.
From the MDN docs:
If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing.
If used prefix, with operator before operand (for example, ++x), the increment operator increments and returns the value after incrementing.
Bug Number Two
The second issue comes from my initial guard clauses.
if(nums.length === 2) return nums[1];
I think this was a remnant from when I was sorting the provided array at the very start, but even then automatically selecting the last element doesn't really make any sense. I deleted this line and, combined with the adjustment to the previous makeDict() function, the code passed all the provided tests.
My working solution is provided below. Open to any suggestions as to how to improve the code for both readability, or efficiency.
Appreciate the help!
const deleteAndEarn = (nums) => {
if(!nums || nums.length === 0) return 0;
if(nums.length === 1) return nums[0];
const freq = makeDict(nums);
let prevNum
let [keep, avoid] = [0, 0];
for(const num of Object.keys(freq)){
let max = Math.max(keep, avoid)
if(parseInt(num) - 1 !== prevNum){
[keep, avoid] = [
(freq[num] * parseInt(num)) + max,
max
]
}else{
[keep, avoid] = [
parseInt(num) * freq[num] + avoid,
max
]
}
prevNum = parseInt(num)
}
return Math.max(keep, avoid)
};
const makeDict = (nums) => {
const dict = {}
for(const num of nums){
dict[num] = !!dict[num] ? ++dict[num] : 1
}
return dict
}
One bug in your existing code is that
[...Object.keys(freq)].sort()
will not sort numbers in order - see here.
Another bug is that your algorithm doesn't have any backtracking - you don't want to greedily choose 3 when given [3, 4, 4, 4].
I think the best way to approach this is to understand that it's only strings of consecutive numbers in the input that need to be considered. For example, given
[1, 2, 3, 6, 7, 8]
Separate it out into all the consecutive strings of integers:
[1, 2, 3]
[6, 7, 8]
Then decide the optimal picks for each sequence.
You can't just pick all odd numbers or all even numbers in the sequence, because that would fail to pick, eg, 1 and 4 for [1, 1, 1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 4]. The best approach I can see is to use a recursive function: when checking a sequence, getBestSequenceSum, starting with N, return the maximum of:
Sum of N plus getBestSequenceSum(seq.slice(2)) (skipping the next item in the sequence), OR
Sum of getBestSequenceSum(seq.slice(1)) (using the next item in the sequence)
to adequately cover all possibilities.
There may be more efficient algorithms, but this is relatively simple and intuitive.
const getBestSequenceSum = (seq) => {
if (seq.length === 0) return 0;
// Include the lowest value in the sequence, or not?
const sumOfLowestVal = seq[0].num * seq[0].count;
return Math.max(
sumOfLowestVal + getBestSequenceSum(seq.slice(2)),
getBestSequenceSum(seq.slice(1))
);
};
const deleteAndEarn = (nums) => {
nums.sort((a, b) => a - b);
let lastNum;
const sequences = [];
for (const num of nums) {
if (num !== lastNum && num !== lastNum + 1) {
// New sequence
sequences.push([]);
}
const thisSequence = sequences[sequences.length - 1];
if (num !== lastNum) {
thisSequence.push({ num, count: 0 });
}
thisSequence[thisSequence.length - 1].count++;
lastNum = num;
}
return sequences.reduce((a, seq) => a + getBestSequenceSum(seq), 0);
};
console.log(deleteAndEarn([10,8,4,2,1,3,4,8,2,9,10,4,8,5,9,1,5,1,6,8,1,1,6,7,8,9,1,7,6,8,4,5,4,1,5,9,8,6,10,6,4,3,8,4,10,8,8,10,6,4,4,4,9,6,9,10,7,1,5,3,4,4,8,1,1,2,1,4,1,1,4,9,4,7,1,5,1,10,3,5,10,3,10,2,1,10,4,1,1,4,1,2,10,9,7,10,1,2,7,5]));
The number of calculations could be reduced somewhat by changing the { num, count: 0 } objects to a single number instead, but that would be more difficult to understand when reading the code.
You could also reduce the number of calculations by caching already-optimized sequences so as not to recalculate them multiple times, but that'd make the code significantly longer.

Javascript how to round a whole number up and find its addition value?

Goal
I am at the final stage of scripting a Luhn algorithm.
Problem
Let's say I have a final calculation of 73
How can I round it up to the next 0? So the final value is 80.
And lastly, how can I get the value that made the addition? e.g. 7 is the final answer.
Current code
function validateCred(array) {
// Array to return the result of the algorithm
const algorithmValue = [];
// Create a [2, 1, 2] Pattern
const pattern = array.map((x, y) => {
return 2 - (y % 2);
});
// From given array, multiply each element by it's pattern
const multiplyByPattern = array.map((n, i) => {
return n * pattern[i];
});
// From the new array, split the numbers with length of 2 e.g. 12 and add them together e.g. 1 + 2 = 3
multiplyByPattern.forEach(el => {
// Check for lenght of 2
if(el.toString().length == 2) {
// Split the number
const splitNum = el.toString().split('');
// Add the 2 numbers together
const addSplitNum = splitNum.map(Number).reduce(add, 0);
// Function to add number together
function add(accumalator, a) {
return accumalator + a;
}
algorithmValue.push(addSplitNum);
}
// Check for lenght of 1
else if(el.toString().length == 1){
algorithmValue.push(el);
}
});
// Sum up the algorithmValue together
const additionOfAlgorithmValue = algorithmValue.reduce((a, b) => {
return a + b;
});
// Mod the final value by 10
if((additionOfAlgorithmValue % 10) == 0) {
return true;
}
else{
return false;
}
}
// Output is False
console.log(validateCred([2,7,6,9,1,4,8,3,0,4,0,5,9,9,8]));
Summary of the code above
The output should be True. This is because, I have given the total length of 15 digits in the array. Whereas it should be 16. I know the 16th value is 7, because the total value of the array given is 73, and rounding it up to the next 0 is 80, meaning the check digit is 7.
Question
How can I get the check number if given array length is less than 15?
You could do something like this:
let x = [73,81,92,101,423];
let y = x.map((v) => {
let remainder = v % 10;
let nextRounded = v + (10-remainder);
/* or you could use
let nextRounded = (parseInt(v/10)+1)*10;
*/
let amountToNextRounded = 10 - remainder;
return [nextRounded,amountToNextRounded];
});
console.log(y);
EDIT
As noticed by #pilchard you could find nextRounded using this more simplified way:
let nextRounded = v + (10-remainder);
https://stackoverflow.com/users/13762301/pilchard
I think what you need is this:
var oldNum = 73
var newNum = Math.ceil((oldNum+1) / 10) * 10;;
Then check the difference using this:
Math.abs(newNum - oldNum);

Is there a simple way to split a number into an array of digits without converting it to a string and back?

I was working on a Javascript exercise that required a number to be converted into an array of single digits and the only way I can seem to achieve this is by converting the number into a string and then converting it back to a number.
let numbers = 12345;
Array.from(numbers.toString(10), Number) // [1, 2, 3, 4, 5]
Basically, I'm wondering if this is the best way to achieve a split like this on a number or if there is a more efficient method that doesn't require such a conversion.
You can always get the smallest digit with n % 10. You can remove this digit with subtraction and division by 10 (or divide and floor). This makes for a pretty simple loop:
function digits(numbers){
if (numbers == 0) return [numbers]
let res = []
while (numbers){
let n = numbers % 10
res.push(n)
numbers = (numbers - n) / 10
}
return res.reverse()
}
console.log(digits(1279020))
This takes the numbers in reverse order so you either have to unshift the results on to the array or push and reverse at the end.
One of the nice things about this, is that you can find the digits of different bases by swapping out 10 for a the base of your choice:
function digits(numbers, base){
if (numbers == 0) return [numbers]
let res = []
while (numbers){
let n = numbers % base
res.push(n)
numbers = (numbers - n) / base
}
return res.reverse()
}
// binary
console.log(digits(20509, 2).join(''))
console.log((20509).toString(2))
// octal
console.log(digits(20509, 8).join(''))
console.log((20509).toString(8))
Although once your base is larger than 10 you will have to map those digits to the appropriate letters.
One approach would be to iterate through the number of digits and calculate the difference of each modulo by base, and then populate the output list from the result of each iteration.
A quick way to identify the number of digits in your base 10 input would be the following:
Math.floor(Math.log(input) / Math.LN10 + 1) // 5 for input of 12349
Next, iterate through this range and for each iteration, calculate the base of the current and previous iterations, and perform module of the input against these. The digit for the current iteration is then derived from the difference of the modulo calculations like this:
function arrayFromInput(input) {
const output = [];
for (let i = 0; i < Math.floor(Math.log(input) / Math.LN10 + 1); i++) {
const lastBase = Math.pow(10, i);
const nextBase = Math.pow(10, i + 1);
const lastMod = input % lastBase;
const nextMod = input % nextBase;
const digit = (nextMod - lastMod) / lastBase;
output.unshift(digit);
}
return output;
}
console.log(arrayFromInput(12345), '= [1,2,3,4,5]');
console.log(arrayFromInput(12), '= [1,2]');
console.log(arrayFromInput(120), '= [1,2 0]');
console.log(arrayFromInput(9), '= [9]');
console.log(arrayFromInput(100), '= [1,0,0]');

Flipping 0's and 1's from a natural number

I want to create a javascript function to flip 1's to 0's in a natural number and I'm out of Ideas to achieve this,
Actually, I had a couple of URL's, and I replaced all 0's from a query parameter with 1's and now I no longer know the original parameter value, because there were few 1's in the original parameter value and now both are mixed, so basically I screwed myself,
The only solution for me is to try flipping each 1 to 0 and then 0's to 1's and test each number as the parameter.
This is the parameter value (after replacing 0's with 1's)
11422971
using above input I want to generate numbers as follows and test each of these
11422970
10422971
10422970
01422971
As you can see only 1's and 0's are changing, the change according to binary,
Each position in your string can be one of n characters:
A "0" can be either "0" or "1"
A "1" can be either "0" or "1"
Any other character c can only be c
We can store this in an array of arrays:
"11422971" -> [ ["0", "1"], ["0, "1"], ["4"], ... ]
To transform your string to this format, you can do a split and map:
const chars = "11422971"
.split("")
.map(c => c === "1" || c === "0" ? ["1", "0"] : [ c ]);
Once you got this format, the remaining logic is to create all possible combinations from this array. There are many ways to do so (search for "array combinations" or "permutations"). I've chosen to show a recursive pattern:
const chars = "11422971"
.split("")
.map(c =>
c === "1" || c === "0"
? ["1", "0"]
: [ c ]
);
const perms = ([ xs, ...others ], s = "", ps = []) =>
xs
? ps.concat(...xs.map(x => perms(others, s + x, ps)))
: ps.concat(s);
console.log(perms(chars));
you can do it with a number like a string, and after parse it, something like that
var number= "12551";
number= number.replace("1","0");
The result of number will be "02550"
after that parse number to int
This will generate all permutations.
const generatePermutations = (number) => {
let digits = number.split('');
// find out which digits can be flipped
let digitPositions = digits.reduce((acc, val, i) => {
if (val === '0' || val === '1') acc.push(i);
return acc;
}, []);
// we're going to be taking things in reverse order
digitPositions.reverse();
// how many digits can we flip
let noBits = digitPositions.length;
// number of permutations is 2^noBits i.e. 3 digits means 2^3 = 8 permutations.
let combinations = Math.pow(2, digitPositions.length);
let permutations = [];
// for each permutation
for (var p = 0; p < combinations; p++) {
// take a copy of digits for this permutation
permutations[p] = digits.slice();
// set each of the flippable bits according to the bit positions for this permutation
// i = 3 = 011 in binary
for (var i = 0; i < noBits; i++) {
permutations[p][digitPositions[i]] = '' + ((p >> i) & 1);
}
permutations[p] = permutations[p].join('');
}
return permutations;
};
console.log(generatePermutations('11422970'));
In case your looking for a recursive approach:
function recursive(acc, first, ...rest) {
if(!first) return acc;
if(first == '0' || first == '1') {
var acc0 = acc.map(x => x + '0');
var acc1 = acc.map(x => x + '1');
return recursive([].concat(acc0, acc1), ...rest);
} else {
return recursive(acc.map(x => x + first), ...rest);
}
}
recursive([''], ...'11422971')
// output ["00422970", "10422970", "01422970", "11422970", "00422971", "10422971", "01422971", "11422971"]
This just counts in binary and fills out a template for each value.
function getPossibleValues(str) {
function getResult(n) {
let nIndex = 0;
const strValue = n.toString(2).padStart(nDigits, '0');
return str.replace(rxMatch, () => strValue.charAt(nIndex++));
}
const rxMatch = /[01]/g;
const nDigits = str.length - str.replace(rxMatch, '').length;
const nMax = Math.pow(2, nDigits);
const arrResult = [];
for(let n = 0; n<nMax; n++) {
arrResult.push(getResult(n));
}
return arrResult;
}
console.log(getPossibleValues('11422970'));
Thank you all to respond, you saved my life, btw the approach I used was,
0- convert the number into a string. (so we can perform string operations like split())
1- count the number of 1's in the string (let's say the string is "11422971", so we get three 1's, I used split('1')-1 to count)
2- generate binary of three-digit length,(ie from 000 to 111). three came from step 1.
2- break down the string to single chars, (we'll get
array=['1','1','4','2','2','9','7','1'] )
3- take the first binary number (ie b=0b000)
4- replace first 1 from the character array with the first binary digit of b (ie replace 1 with 0), similarly replace second 1 with the second binary digit of b and so on.
5- we'll get the first combination (ie "00422970")
5- repeat step 3 and 4 for all binary numbers we generated in step 2.

Categories