Count characters used in String - javascript

I have a number - e.g: 1234 and another number 1112
I want to count how many digits are used in the string. e.g for 1234, I would get 4, as all digits are unique. As for 1112, I would get 2, as there is only 1 and 2 in the string.
How do I achieve this using JavaScript?

You can get an array of characters from the string, filter for duplicates, and count the length:
function countUsedDigits(n) {
return n.split('').filter(function (item, index, self) {
return self.indexOf(item) == index;
}).length;
}
countUsedDigits("1234") === 4;
countUsedDigits("1112") === 2;
countUsedDigits("1213242353") === 5;

Related

Codewars division Kata using Javascript is producing results that are not divisble by 6

I am trying to solve this Kata from Codewars: https://www.codewars.com/kata/simple-fun-number-258-is-divisible-by-6/train/javascript
The idea is that a number (expressed as a string) with one digit replaced with *, such as "1047*66", will be inserted into a function. You must return an array in which the values are the original number with the * replaced with any digit that will produce a number divisive by 6. So given "1*0", the correct resulting array should be [120, 150, 180].
I have some code that is producing some correct results but erroring for others, and I can't figure out why. Here's the code:
function isDivisibleBy6(s) {
var results = [];
for(i=0;i<10;i++) {
var string = i.toString(); // Convert i to string, ready to be inserted into s
var array = Array.from(s); // Make an array from s
var index = array.indexOf("*"); // Find where * is in the array of s
array[index] = string; // Replace * with the string of i
var number = array.join(""); // Join all indexes of the s array back together. Now we should have
// a single number expressed as a string, with * replaced with i
parseInt(number, 10); // Convert the string to an integer
if((number % 6) == 0) {
results.push(number);
} // If the integer is divisible by 6, add the integer into the results array
}
return(results);
};
This code works with the above example and generally with all smaller numbers. But it is producing errors for larger numbers. For example, when s is "29070521868839*57", the output should be []. However, I am getting ['29070521868839257', '29070521868839557', '29070521868839857']. I can't figure out where this would be going wrong. Is anyone able to help?
The problem is that these numbers are larger than the Number.MAX_SAFE_INTEGER - the point when JavaScript numbers break down in terms of reliability:
var num = 29070521868839257;
console.log(num > Number.MAX_SAFE_INTEGER);
console.log(num % 6);
console.log(num)
The last log shows that the num actually has a different value than what we gave it. This is because 29070521868839257 simply cannot be represented by a JavaScript number, hence you get the closest possible value that can be represented and that's 29070521868839256.
So, after some point in numbers, all mathematical operations become unreliable as the very numbers are imprecise.
What you can do instead is ignore treating this whole as a number - treat it as a string and only apply the principles of divisibility. This makes the task vastly easier.
For a number to be divisible by 6 it has to cover two criteria:
it has to be divisible by 2.
to verify this, you can just get the very smallest digit and check if it's divisible by 2. For example in 29070521868839257 if we take 7, and check 7 % 2, we get 1 which means that it's odd. We don't need to consider the whole number.
it has to be divisible by 3.
to verify this, you can sum each of the digits and see if that sum is divisible by 3. If we sum all the digits in 29070521868839257 we get 2 + 9 + 0 + 7 + 0 + 5 + 2 + 1 + 8 + 6 + 8 + 8 + 3 + 9 + 2 + 5 + 7 = 82 which is not divisible by 3. If in doubt, we can sum the digits again, since the rule can be applied to any number with more than two digits: 8 + 2 = 10 and 1 + 0 = 1. That is still not divisible by 3.
So, if we apply these we can get something like:
function isDivisibleBy6(s) {
return isDivisibleBy2(s) && isDivisibleBy3(s);
};
function isDivisibleBy2(s) {
var lastDigit = Number(s.slice(-1));
return (lastDigit % 2) === 0;
}
function isDivisibleBy3(s) {
var digits = s.split("")
.map(Number);
var sum = digits.reduce(function(a, b) {
return a + b
});
return (sum % 3) === 0;
}
console.log(isDivisibleBy6("29070521868839257"));
console.log(isDivisibleBy6("29070521868839256"));
These can even be recursively defined true to the nature of these rules:
function isDivisibleBy6(s) {
return isDivisibleBy2(s) && isDivisibleBy3(s);
};
function isDivisibleBy2(s) {
if (s.length === 0) {
return false;
}
if (s.length > 1) {
return isDivisibleBy2(s.slice(-1));
}
var lastDigit = Number(s);
return (lastDigit % 2) === 0;
}
function isDivisibleBy3(s) {
if (s.length === 0) {
return false;
}
if (s.length > 1) {
var digits = s.split("")
.map(Number);
var sum = digits.reduce(function(a, b) {
return a + b
});
return isDivisibleBy3(String(sum));
}
var num = Number(s);
return (num % 3) === 0;
}
console.log(isDivisibleBy6("29070521868839257"));
console.log(isDivisibleBy6("29070521868839256"));
This is purely to demonstrate the rules of division and how they can be applied to strings. You have to create numbers that will be divisible by 6 and to do that, you have to replace an asterisk. The easiest way to do it is like you did - generate all possibilities (e.g., 1*0 will be 100, 110, 120, 130, 140, 150, 160, 170, 180, 190) and then filter out whatever is not divisible by 6:
function isDivisibleBy6(s) {
var allDigits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var allPossibleNumbers = allDigits.map(function(digit) {
return s.replace("*", digit);
});
var numbersDibisibleBySix = allPossibleNumbers.filter(function(s) {
return isDivisibleBy2(s) && isDivisibleBy3(s);
})
return numbersDibisibleBySix;
};
function isDivisibleBy2(s) {
var lastDigit = Number(s.slice(-1));
return (lastDigit % 2) === 0;
}
function isDivisibleBy3(s) {
var digits = s.split("")
.map(Number);
var sum = digits.reduce(function(a, b) {
return a + b
});
return (sum % 3) === 0;
}
console.log(isDivisibleBy6("29070521868839*57"));
console.log(isDivisibleBy6("29070521868839*56"));
As a last note, this can be written more concisely by removing intermediate values and using arrow functions:
function isDivisibleBy6(s) {
return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.map(digit => s.replace("*", digit))
.filter(s => isDivisibleBy2(s) && isDivisibleBy3(s));
};
const isDivisibleBy2 = s => Number(s.slice(-1)) % 2 === 0;
const isDivisibleBy3 = s => s.split("")
.map(Number)
.reduce((a, b) => a + b) % 3 === 0
console.log(isDivisibleBy6("29070521868839*57"));
console.log(isDivisibleBy6("29070521868839*56"));
Sum of all digits is divisible by three and the last digit is divisible by two.
An approach:
Get the index of the star.
Get left and right string beside of the star.
Return early if the last digit is not divisible by two.
Take the sum of all digits.
Finally create an array with missing digits:
Start loop from either zero (sum has no rest with three) or take the delta of three and the rest (because you want a number which is divisible by three).
Go while value is smaller then ten.
Increase the value either by 3 or by 6, if the index of the star is the last character.
Take left, value and right part for pushing to the result set.
Return result.
function get6(s) {
var index = s.indexOf('*'),
left = s.slice(0, index),
right = s.slice(index + 1),
result = [],
sum = 0,
i, step;
if (s[s.length - 1] % 2) return [];
for (i = 0; i < s.length; i++) if (i !== index) sum += +s[i];
i = sum % 3 && 3 - sum % 3;
step = s.length - 1 === index ? 6 : 3;
for (; i < 10; i += step) result.push(left + i + right);
return result;
}
console.log(get6("*")); // ["0", "6"]
console.log(get6("10*")); // ["102", "108"]
console.log(get6("1*0")); // ["120", "150", "180"]
console.log(get6("*1")); // []
console.log(get6("1234567890123456789012345678*0")); // ["123456789012345678901234567800","123456789012345678901234567830","123456789012345678901234567860","123456789012345678901234567890"]
.as-console-wrapper { max-height: 100% !important; top: 0; }
The problem is with:
parseInt(number, 10);
You can check and see that when number is large enough, this result converted back to string is not equal to the original value of number, due to the limit on floating point precision.
This challenge can be solved without having to convert the given string to number. Instead use a property of numbers that are multiples of 6. They are multiples of 3 and even. Multiples of 3 have the property that the sum of the digits (in decimal representation) are also multiples of 3.
So start by checking that the last digit is not 1, 3, 5, 7, or 9, because in that case there is no solution.
Otherwise, sum up the digits (ignore the asterisk). Determine which value you still need to add to that sum to get to a multiple of 3. This will be 0, 1 or 2. If the asterisk is not at the far right, produce solutions with this digit, and 3, 6, 9 added to it (until you get double digits).
If the asterisk is at the far right, you can do the same, but you must make sure that you exclude odd digits in that position.
If you are desperate, here is a solution. But I hope you can make it work yourself.
function isDivisibleBy6(s) {
// If last digit is odd, it can never be divisable by 6
if ("13579".includes(s[s.length-1])) return [];
let [left, right] = s.split("*");
// Calculate the sum of the digits (ignore the asterisk)
let sum = 0;
for (let ch of s) sum += +ch || 0;
// What value remains to be added to make the digit-sum a multiple of 3?
sum = (3 - sum%3) % 3;
// When asterisk in last position, then solution digit are 6 apart, otherwise 3
let mod = right.length ? 3 : 6;
if (mod === 6 && sum % 2) sum += 3; // Don't allow odd digit at last position
// Build the solutions, by injecting the found digit values
let result = [];
for (; sum < 10; sum += mod) result.push(left + sum + right);
return result;
}
// Demo
console.log(isDivisibleBy6("1234567890123456789012345678*0"));
BigInt
There is also another way to get around the floating point precision problem: use BigInt instead of floating point. However, BigInt is not supported on CodeWars, at least not in that specific Kata, where the available version of Node goes up to 8.1.3, while BigInt was introduced only in Node 10.
function isDivisibleBy6(s) {
let [left, right] = s.split("*");
let result = [];
for (let i = 0; i < 10; i++) {
let k = BigInt(left + i + right);
if (k % 6n === 0n) result.push(k.toString());
}
return result;
}
// Demo
console.log(isDivisibleBy6("1234567890123456789012345678*0"));
This would anyway feel like "cheating" (if it were accepted), as it's clearly not the purpose of the Kata.
As mentioned, the values you are using are above the maximum integer value and therefore unsafe, please see the docmentation about this over here Number.MAX_SAFE_INTEGER. You can use BigInt(string) to use larger values.
Thanks for all the responses. I have now created successful code!
function isDivisibleBy6(s) {
var results = [];
for(i=0;i<10;i++) {
var string = i.toString();
var array = Array.from(s);
var index = array.indexOf("*");
array[index] = string;
var div2 = 0;
var div3 = 0;
if(parseInt((array[array.length-1]),10) % 2 == 0) {
div2 = 1;
}
var numarray = array.map((x) => parseInt(x));
if(numarray.reduce(function myFunc(acc, value) {return acc+value}) % 3 == 0) {
div3 = 1;
}
if(div2 == 1 && div3 == 1) {
results.push(array.join(""));
}
}
return(results);
};
I know this could be factored down quite a bit by merging the if expressions together, but I like to see things split out so that when I look back over previous solutions my thought process is clearer.
Thanks again for all the help!

How to double a value if its a string within an array

I'm trying to find the half of the value if the ID is even and for every ID the is odd it would be doubled.
Here is an example I did for the numbers(ID)
var numbers = [8, 12, 5, 2, 5, 7];
var collectionNumbers = {
orginialNumbers: numbers,
doubledNumbers: numbers.map(function(n) { return n * 2; })
};
console.log(collectionNumbers);
Simple gets the job done for multiplying numbers in general but my array looks like this:
I'm trying to figure out how to half or double the last 3 ID's
data = [
{ ID: 1 },
{ ID: 2 },
{ ID: 33 },
{ ID: 66 },
{ ID: 'abc' },
{ ID: 'xyz' },
{ ID: 'A1' }
]
Im trying to figure out how to half or double the last 3 ID's
Since I have it the way I do I get undefined for the strings in the array. Which is fine, I'm mostly concerned about for the strings do I have to convert then to numbers to half or double the value. If so how would I do that with a string?
Speculating that if it's a string then concatenate the string to itself if the length odd otherwise get the first half of the string you can use the following.
If this is homework (as I suspect), the real lesson is to get clear and unambiguous requirements.
var data = [
{ID:1},
{ID:2},
{ID:33},
{ID:66},
{ID:"abc"},
{ID:"xyz"},
{ID:"A1"}
]
var modded = data.map(function(o){
//Set a variable to return
var retval = o.ID
//If it's a number
if(typeof o.ID === "number") {
//Halve it if even, otherwise double it
retval = o.ID % 2 === 0 ? o.ID / 2 : o.ID * 2;
//otherwise
}else{
//if the string length is even, get the first half of the string, otherwise add the string to itself
retval = o.ID.length % 2 === 0 ? o.ID.substring(0, o.ID.length /2) : o.ID + o.ID
}
return retval;
});
console.log(modded);

How to sort set of numbers both lexicographically and numerically?

I currently have a set of strings that are both just numbers and number with + or -. Such as follows :
1 , 1+, 1-, 2, 2+, 2-, 10
Which when I sort using JavaScript's sort functions gives out:
1, 1+ , 1-, 10, 2, 2+, 2-
which is lexicographically orders but not numerically. Is there a way to sort this so the numbers come out in the correct way(the first list) ? I am using ExtJS stores so an answers as a store sorter is preferred but plain javascript is also fine. Thanks ?
Edit: This is not just sorting numbers.
You can use a custom ordering function like so:
var numbers = ['1', '1-', '1+', '2', '2+', '2-', '10'];
numbers.sort(function (a, b){
var _a = parseFloat(a), // If the values are integers only, parseInt will do too
_b = parseFloat(b);
if (_a - _b === 0) {
return (a > b) ? 1 : -1;
} else {
return _a - _b;
}
});
console.log(numbers);
The function checks whether the number values are equal, and if so, falls back to lexicographic ordering to sort the character suffixes. If there are no suffixes in equal-case, hence no matter in which order the numbers are returned. If only one of the operands has a suffix, bare number returns negative. If the number values are not equal, the function simply returns the tristate, i.e a - b, which will be evaluated to one of negative, 0, positive. Or actually it's "bistate", since we've handled 0 case already.
More generic solution
The code above is rather a special case for two different single charactered suffixes only. If suffixes are more complex, here's a more generic code to sort by number and by suffixes:
var numbers = ['1', '1-r', '1+q', '1', '2', '2+q', '2-r', '10'];
function suffixSort (suff, asc) {
asc = 2 * +(!!asc) - 1; // Convert boolean to -1 or 1
return function (a, b) {
var _a = parseFloat(a), // Extract the number value
_b = parseFloat(b),
aSI = -(a.length - _a.toString().length), // Get the index of suffix start
bSI = -(b.length - _b.toString().length);
// Equal number values, sort by suffixes
if (_a === _b) {
return (suff.indexOf(a.substr(aSI)) > suff.indexOf(b.substr(bSI))) ? 1 : -1;
}
// Inequal number values, sort by numbers
return asc * (_a - _b);
}
}
// suffixSort arguments
// suff: An array of the suffix strings to sort, ordered in the desired sorting order
// asc: true = ascending, false = descending. Optional, defaults to descending sort
numbers.sort(suffixSort(['+q', '-r'], true));
console.log(numbers);
The idea is to store the suffixes into an array, and when suffix sorting is needed, function compares the array indices of the suffixes instead of the suffixes themselves.
suffixSort lets you also to decide the sorting direction. Selected sorting direction doesn't have an effect on suffix sorting, they are always returned in the order they appear in suff array.
These values are almost integers, so comparing them according to praseInt will almost get you there. The only thing missing is a special treatment for values that have the same integer part where x- should come first, then x and finally x+:
function specialChar(s) {
c = s.substr(-1);
if (c == '+') {
return 1;
}
if (c == '-') {
return -1;
}
return 0;
}
function numCompare(a, b) {
aNum = parseInt(a);
bNum = parseInt(b);
cmp = aNum - bNum;
if (cmp != 0) {
return cmp;
}
// Integer parts are equal - compare the special char at the end
return specialChar(a) - specialChar(b);
}
arr = ['1' , '1+', '1-', '2', '2+', '2-', '10'];
arr.sort(numCompare);
var result=[];
result=array.map(function(n){
if(typeof n==='number') return n;
if(n[n.length-1]=='+'){
return parseInt(n.substring(0,n.length-1))
}
else if(n[n.length-1]=='-'){
return 0-parseInt(n.substring(0,n.length-1))
}
});
result.sort(function(a,b){return a-b})
You could use Array#sort and split the elements in numbers and the rest, then return the difference or the difference of the order.
var array = ['10', '2', '2+', '2-', '1', '1+', '1-'];
array.sort(function (a, b) {
var r = /\d+|\D+/g,
aa = a.match(r),
bb = b.match(r),
order = { '+': 1, '-': 2 };
return aa[0] - bb[0] || (order[aa[1]] || 0) - (order[bb[1]] || 0);
});
console.log(array);
If there are only three possible states of a number, and the states have the order number, number+, number the states can be recreated by creating an array representation of the numbers, removing the unique numbers from array, from minimum to maximum, concatenating empty string or arithmetic operator in required order to the number, then pushing the value to an array, where .toString() can be used to view the comma separated string representation of the sorted values within the array
var str = `314+, 1-, 7+, 1, 1-, 271-, 10-
, 10+, 271, 271+, 314-, 314
, 10, 2-, 2, 2+, 7-, 7`;
for (var [nums, order, res, num] = [str.match(/\d+/g), ["", "+", "-"], [], null]
; nums.length
; num = Math.min.apply(Math, nums)
, res = [...res, ...order.map(op => num + op)]
, nums = nums.filter(n => n != num)
);
console.log(res.toString() + "\n", res);
Assuming that you just want to throw away the symbols, then you could use parseInt and Array#sort to get order numerically.
var data = ['1' , '1+', '1-', '2', '2+', '2-', '10'];
var sortedData = data.sort(function(a,b){return parseInt(a)-parseInt(b);});

Why does this recursive function skip numbers?

I'm trying to find the various possibilities to equal 100 with digits 1-9. This function produces the desired results, but also others which I had not intended. The other results add up to 100, but without some of these digits, like leaving out 3 or 6. Why are these other results included?
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var signs = ["+", "-", "N"];
var results = [];
find100("1");
function find100(expr) {
if (eval(expr.replace(/N/g, "")) === 100) {
results.push(expr);
} else {
for (var i = eval(expr.substring(expr.length - 1, expr.length)) + 1; i <=
nums.length; i++) {
signs.forEach(function(sign) {
var expr2 = expr;
find100(expr2 += sign + i);
});
}
}
}
Desired output:
1+2+3-4+5+6+78+9,
1+2+34-5+67-8+9,
1+23-4+5+6+78-9,
1+23-4+56+7+8+9,
12+3+4+5-6-7+89,
12+3-4+5+67+8+9,
12-3-4+5-6+7+89,
123+4-5+67-89,
123+45-67+8-9,
123-4-5-6-7+8-9,
123-45-67+89
It's adding undesired results because your first loop iterates through each of the remaining numbers and adds ANY results that evaluate to 100, even if it has skipped a number to do so. If the method finds a solution for a number it adds the solution to results - which is correct, however if it doesn't find a solution it moves onto the next number anyway. This is the source of the skipped numbers. If there was no solution for a number it should have not continued to the next number.
As to how to fix it, that's a different question (but why not ...)
The difference here is that you can ONLY get a result if for any number there exists an expression that uses all remaining numbers.
var results = [];
var operations = [ "+", "-", "" ];
var expected = 100;
var limit = 10;
function findExpression(expr, next) {
if (next === limit) {
eval(expr) === expected && results.push(expr);
} else {
operations.forEach(function(operation) {
findExpression(expr + operation + next, next + 1);
});
}
}
$(document).ready(function() {
findExpression("1", 2);
for(var i=0; i<results.length; i++) {
$("#foo").append(results[i]+"<br />");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<body>
<div id="foo"></div>
</body>
The reason that some digits are skipped is in this loop:
for (var i = eval(expr.substring(expr.length - 1, expr.length)) + 1; i <=
nums.length; i++) {
On the second iteration it will increment that last digit in the expression, which will therefore create a gap in the continued recursion. In short, that loop should not be there.
I would suggest a solution without using eval, not because it would be somehow dangerous, but because it is responsible for a major performance hit.
Instead you could keep a numerical variable updated to what the expression represents. In fact, I suggest to use two such variables, one for the sum of the previous terms, and another for the last term, because that one might need to still be extended with more digits.
To facilitate the different way the signs influence the expression, I have defined a function per sign: it takes the above mentioned numerical values, and also the last digit, and returns the updated values.
Here is a working snippet (ES6 syntax) using that idea, and you'll notice the dramatic performance improvement:
function find100(digits, signs) {
const loop = (expr, i, [sum, value]) =>
// Not yet all digits used?
i < digits.length ?
// Apply each of the signs in turn:
Object.keys(signs).reduce( (results, sign) =>
// Recurse, passing on the modified expression, the sum of the
// preceding terms, and the value of the last term. As '+' is
// not any different than '' before the first digit, skip '+':
sign != '+' || i ?
results.concat(loop(expr+sign+digits[i], i+1,
signs[sign](sum, value, digits[i]))) :
results,
[] ) :
// All digits were used. Did it match?
sum+value == 100 ? [expr] : [];
// Start recursion
return loop('', 0, [0, 0]);
}
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// define how each sign should modify the expression value:
var signs = {
'+': (sum, value, digit) => [sum+value, digit],
'-': (sum, value, digit) => [sum+value, -digit],
'' : (sum, value, digit) => [sum, value*10 + (value<0 ? -digit : digit)]
};
var results = find100(nums, signs);
console.log(results);
Note that this also outputs the following expression:
-1+2-3+4+5+6+78+9
This is because the code also tries the signs before the first digit. I thought it would be relevant to have this also included in the output.

Javascript - String of a Byte with all combinations possible

i have a sting with a byte in it ("00001011") and now id like to get a array with all possible combinations of the 1 (acitve) "bits" in it also as a "byte string"
so from
var bString = "00001011"; //outgoing string
to a array with all string in it with all possible combinations of this "byte string" like - "00000001", "00000011", "00000010" and so on
is that possible?
thank you in advance
function combinations( input ){
var number = parseInt( input, 2 );
var combinations = [];
var zeroes = (new Array(input.length)).join(0);
for(var i=1;i<=number;i++){
if((i&number) == i){ combinations.push( i ) }
}
return combinations.map( function(dec){
return (zeroes + dec.toString(2)).substr( -zeroes.length-1 );
});
}
http://jsfiddle.net/jkf7pfxn/3/
console.log( combinations("00001011") );
// ["00000001", "00000010", "00000011", "00001000", "00001001", "00001010", "00001011"]
The idea goes as follows: iterate all numbers from 1 to the input number. If current number AND input number return the current number then both have 1 bits in the same place.
On a smaller number, "0101" (which is 5) it works as follows:
1 & 5 == 1, (0001 & 0101) push 1 to the matches.
2 & 5 == 0, (0010 & 0101) no match.
3 & 5 == 1, (0011 & 0101) no match.
4 & 5 == 4, (0100 & 0101) push 4 to the matches.
5 & 5 == 5, (0101 & 0101) push 5 to the matches.
So the combinations for 0101 are 1 (0001), 2 (0010), 4 (0100) and 5 (0101).
Then there's this little trick to pad numbers with zeroes:
var zeroes = (new Array(input.length)).join(0); // gives a long enough string of zeroes
then
// convert to base 2, add the zeroas at the beginning,
// then return the last n characters using negative value for substring
return (zeroes + dec.toString(2)).substr( -1 * zeroes.length);
Since 11111111 is 255 so just loop all values and convert them to binary
$(document).ready(function() {
for (var i = 0; i < 256; i++) {
$('#core').append('<div>' + dec2bin(i) + '</div>');
}
function dec2bin(dec) {
return ('00000000' + (dec >>> 0).toString(2)).slice(-8);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='core'></div>
If you want to enumerate all combinations of binary numbers where 1 can only be in the place of your pattern, you can write a simple recursive function:
var input = "00010111";
var current = [];
function combinations()
{
if (input.length === current.length)
{
var output = current.join('');
if (parseInt(output, 2) !== 0) // exclude all-zeroes case
document.body.innerHTML += output + "<br/>";
return;
}
current.push('0');
combinations();
current.pop();
if (input[current.length - 1] === '1')
{
current.push('1');
combinations();
current.pop();
}
}
combinations();
This algorithm works well for input of any length.
Although it is a recursion, it has a linear time complexity.

Categories

Resources