Print all possible strings that can be made by placing spaces
I came across this problem.
Print all possible strings that can be made by placing spaces.
I also came across this solution.
var spacer = function (input)
var result = '' ;
var inputArray = input.split('');
var length = inputArray.length;
var resultSize = Math.pow(2,length-1); // how this works
for(var i = 0 ; i< resultSize ; i++)
for(var j=0;j<length;j++)
result += inputArray[j];
if((i & (1<<j))>0) // how this works
result += ' ' ;
result += 'n' ;
return result;
var main = function()
var input = 'abcd' ;
var result = spacer(input);
console.log(result);
main();
I am not getting how the marked lines work?
Can you clarify on what technique is being used? And what is the basic logic behind this? What are some of other areas where we can use this?
Thanks.
javascript bitwise-operators
add a comment |
I came across this problem.
Print all possible strings that can be made by placing spaces.
I also came across this solution.
var spacer = function (input)
var result = '' ;
var inputArray = input.split('');
var length = inputArray.length;
var resultSize = Math.pow(2,length-1); // how this works
for(var i = 0 ; i< resultSize ; i++)
for(var j=0;j<length;j++)
result += inputArray[j];
if((i & (1<<j))>0) // how this works
result += ' ' ;
result += 'n' ;
return result;
var main = function()
var input = 'abcd' ;
var result = spacer(input);
console.log(result);
main();
I am not getting how the marked lines work?
Can you clarify on what technique is being used? And what is the basic logic behind this? What are some of other areas where we can use this?
Thanks.
javascript bitwise-operators
Please try and use snippets when you can, I've updated your question to use a snippet.
– Keith
Aug 24 '17 at 22:10
ok got it, thanks...
– Arthanari C
Aug 24 '17 at 22:16
add a comment |
I came across this problem.
Print all possible strings that can be made by placing spaces.
I also came across this solution.
var spacer = function (input)
var result = '' ;
var inputArray = input.split('');
var length = inputArray.length;
var resultSize = Math.pow(2,length-1); // how this works
for(var i = 0 ; i< resultSize ; i++)
for(var j=0;j<length;j++)
result += inputArray[j];
if((i & (1<<j))>0) // how this works
result += ' ' ;
result += 'n' ;
return result;
var main = function()
var input = 'abcd' ;
var result = spacer(input);
console.log(result);
main();
I am not getting how the marked lines work?
Can you clarify on what technique is being used? And what is the basic logic behind this? What are some of other areas where we can use this?
Thanks.
javascript bitwise-operators
I came across this problem.
Print all possible strings that can be made by placing spaces.
I also came across this solution.
var spacer = function (input)
var result = '' ;
var inputArray = input.split('');
var length = inputArray.length;
var resultSize = Math.pow(2,length-1); // how this works
for(var i = 0 ; i< resultSize ; i++)
for(var j=0;j<length;j++)
result += inputArray[j];
if((i & (1<<j))>0) // how this works
result += ' ' ;
result += 'n' ;
return result;
var main = function()
var input = 'abcd' ;
var result = spacer(input);
console.log(result);
main();
I am not getting how the marked lines work?
Can you clarify on what technique is being used? And what is the basic logic behind this? What are some of other areas where we can use this?
Thanks.
var spacer = function (input)
var result = '' ;
var inputArray = input.split('');
var length = inputArray.length;
var resultSize = Math.pow(2,length-1); // how this works
for(var i = 0 ; i< resultSize ; i++)
for(var j=0;j<length;j++)
result += inputArray[j];
if((i & (1<<j))>0) // how this works
result += ' ' ;
result += 'n' ;
return result;
var main = function()
var input = 'abcd' ;
var result = spacer(input);
console.log(result);
main();
var spacer = function (input)
var result = '' ;
var inputArray = input.split('');
var length = inputArray.length;
var resultSize = Math.pow(2,length-1); // how this works
for(var i = 0 ; i< resultSize ; i++)
for(var j=0;j<length;j++)
result += inputArray[j];
if((i & (1<<j))>0) // how this works
result += ' ' ;
result += 'n' ;
return result;
var main = function()
var input = 'abcd' ;
var result = spacer(input);
console.log(result);
main();
javascript bitwise-operators
javascript bitwise-operators
edited Aug 24 '17 at 22:09
Keith
8,5061720
8,5061720
asked Aug 24 '17 at 22:05
Arthanari CArthanari C
845
845
Please try and use snippets when you can, I've updated your question to use a snippet.
– Keith
Aug 24 '17 at 22:10
ok got it, thanks...
– Arthanari C
Aug 24 '17 at 22:16
add a comment |
Please try and use snippets when you can, I've updated your question to use a snippet.
– Keith
Aug 24 '17 at 22:10
ok got it, thanks...
– Arthanari C
Aug 24 '17 at 22:16
Please try and use snippets when you can, I've updated your question to use a snippet.
– Keith
Aug 24 '17 at 22:10
Please try and use snippets when you can, I've updated your question to use a snippet.
– Keith
Aug 24 '17 at 22:10
ok got it, thanks...
– Arthanari C
Aug 24 '17 at 22:16
ok got it, thanks...
– Arthanari C
Aug 24 '17 at 22:16
add a comment |
6 Answers
6
active
oldest
votes
Let's take string abcd
as an example.
There are 3 possible places where space can be put:
- Between "a" and "b"
- Between "b" and "c"
- Between "c" and "d"
So generally if length of your string is length
then you have length - 1
places for spaces.
Assume that each such place is represented with a separate digit in a binary number. This digit is 0 when we don't put space there, and 1 when we do. E.g.:
a b c d
0 0 0
means that we don't put any spaces - abcd
0 0 1
means that we put space between "c" and "d" only - abc d
0 1 0
means that we put space between "b" and "c" only - ab cd
0 1 1
means ab c d
1 0 0
means a bcd
1 0 1
means a bc d
1 1 0
means a b cd
1 1 1
means a b c d
Converting 000
, 001
, 010
, ..., 111
from binary to decimal will give us values 0
, 1
, 2
, ..., 7
.
With 3 places for spaces we have 8 options to put them. It's exactly 2^3
or 2^(length - 1)
.
Thus we need to iterate all numbers between 0
(inclusive) and 2^(length - 1)
(exclusive).
Condition (i & (1 << j)) > 0
in the code you provided just checks whether digit at position j
(starting from the end, 0-based) is 0
(and we don't need to insert space) or 1
(and space should be added).
Let's take value 6
(110
in binary) for example.
(6 & (1 << 0)) = 110 & 001 = 000 = 0
(condition > 0
is not met)
(6 & (1 << 1)) = 110 & 010 = 010 = 2
(condition > 0
is met)
(6 & (1 << 2)) = 110 & 100 = 100 = 4
(condition > 0
is met)
ok i got it, the 000-111 logic really made it clear for me. still one doubt. how is(i & (1 << j)) > 0
creating this 000-111 sequence. Seems like in that one line it is generating the binary number 0,1,2,... in sequence like 0 0 0 0 0 1 0 1 0 ...
– Arthanari C
Aug 24 '17 at 22:35
Sequence 000-111 is generated by simply iterating decimal values 0, 1, 2, 3, 4, 5, 6, 7. 0 is 000 and 7 is 111 in binary.(i & (1 << j)) > 0
then is used just for extracting ones and zeroes from numbers from this sequence. I added an example at the end of my answer.
– Olexiy Sadovnikov
Aug 24 '17 at 22:48
add a comment |
There are 2 possibilities between each 2 characters: either has space or not. If spaces are allowed only between characters then the number of possibilities for 4 characters is 2 * 2 * 2 or 2 ^ (length - 1)
add a comment |
resultSize = Math.pow(2, length - 1)
says there are 2^n-1 possible ways to print a string given the problem definition. As far as to why that is the number of solutions is pretty easy to understand if you start with a string that has 2 characters and work your way upward. So pretend you have the string "ab". There is two solutions, you can put a space between a and b or you can not put a space between a and b. Lets add a character to get "abc". Well, we already know that there are two solutions for the string "ab" so we need multiply that solution by the number of ways you can put a space between b and c. Which is 2 so that gives us 2 * 2 solutions. You can extend that to a string of n size. So that means that the number of solutions is 2 * 2 * 2 * 2 * ... n - 1. Or in otherwords 2 ^ n-1.
The next part is a little trickier, but its a clever way of determining how many spaces and where they go in any given solution. The bitwise &
takes the each bit of two numbers, compares them, then spits out a new number where each bit is a 1 if both the bits of the two numbers were 1, or 0 if the bits were not 1 and 1. For example (binary numbers):
01 & 01 = 01
10 & 01 = 00
Or a bigger example:
10010010 & 10100010 = 10000010
The <<
operator just moves all bits n position to left where n is the right hand expression (multiply by 2 n times).
For example:
1 << 1 = 2
2 << 1 = 4
2 << 2 = 8
1 << 4 = 8
So back to your code now. Lets break down the if statement
if(i & (1 << j) > 0) ...
In english this says, if the number index of the solution we are looking at shares any 1 bits with 1 shifted by the index of the character we are looking at, then put a space after that character. Olexiy Sadovnikov's answer has some good examples of what this would look like for some of the iterations.
Its also worth noting that this is not the only way to do this. You could pretty easily determine that the max number of spaces is n - 1 then just linearly find all of the solutions that have 0 spaces in them, then find all the solutions that have 1 space in them, then 2 spaces .... to n - 1 spaces. Though the solution you posted would be faster than doing it this way. Of course when your talking about algorithms of exponential complexity it ultimately won't matter because strings bigger than about 60 chars will take longer than you probably care to wait for even with a strictly 2^n algorithm.
In answer to the question of how these techniques can be used in other places. Bit shifting is used very frequently in encryption algorithms as well as the bitwise & and | operators.
add a comment |
'''
The idea was to fix each character from the beginning and print space separated rest of the string.
Like for "ABCD":
A BCD # Fix A and print rest string
AB CD # Add B to previous value A and print rest of the string
ABC D # Add C to previous value AB and print rest of the string
Similarly we can add a space to produce all permutations.
Like:
In second step above we got "AB CD" by having "A" as prefix
So now we can get "A B CD" by having "A " as a prefix
'''
def printPermute(arr, s, app):
if len(arr) <= 1:
return
else:
print(app +''+arr[0:s] +' '+ arr[s:len(arr)])
prefix = app + ''+arr[0:s]
suffix = arr[s:len(arr)]
printPermute(suffix, 1, prefix)
printPermute(suffix, 1, prefix+' ') #Appending space
printPermute("ABCDE", 1, '') #Empty string
add a comment |
simple solution Using Javascript
String.prototype.splice = function(idx, rem, str)
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
;
function printPattern(str, i, n)
if(i==n)
return;
var buff = str;
var j = str.length - n + i;
buff = str.splice(j,0," ");
console.log(buff);
printPattern(str, i+1, n);
printPattern(buff, i+1, n);
var str = "ABCD"
printPattern(str, 1, str.length);
console.log(str);
add a comment |
.pow
is a method fromMath
which stands for "power". It takes two arguments: the base (here2
) and the exponent. Read here for more information.&
is the bitwise AND operator, it takes the two binary representation of the numbers and performs a logical AND, here's a thread on bitwise operators
EDIT: why Math.pow(2,length-1)
gives us the number of possible strings?
I remember doing it in an exercise last year in math class, but I'll try to explain it without sums.
Essentially we want to determine the number of strings you can make by adding one or no space in between letters. Your initial string has n
letters. Here's the reason why:
Starting from the left or the word after each letter you have two choices
1 - to put a space
2 - not to put a space
You will have to choose between the two options exactly n-1
times.
This means you will have a total of 2^(n-1)
possible solutions.
I get that, but for the given problem how does 2^m give the number of possible results? That is where i have doubt.
– Arthanari C
Aug 24 '17 at 22:14
@ArthanariC Here's my edit, have a look :)
– Ivan
Aug 24 '17 at 22:38
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45871640%2fprint-all-possible-strings-that-can-be-made-by-placing-spaces%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
Let's take string abcd
as an example.
There are 3 possible places where space can be put:
- Between "a" and "b"
- Between "b" and "c"
- Between "c" and "d"
So generally if length of your string is length
then you have length - 1
places for spaces.
Assume that each such place is represented with a separate digit in a binary number. This digit is 0 when we don't put space there, and 1 when we do. E.g.:
a b c d
0 0 0
means that we don't put any spaces - abcd
0 0 1
means that we put space between "c" and "d" only - abc d
0 1 0
means that we put space between "b" and "c" only - ab cd
0 1 1
means ab c d
1 0 0
means a bcd
1 0 1
means a bc d
1 1 0
means a b cd
1 1 1
means a b c d
Converting 000
, 001
, 010
, ..., 111
from binary to decimal will give us values 0
, 1
, 2
, ..., 7
.
With 3 places for spaces we have 8 options to put them. It's exactly 2^3
or 2^(length - 1)
.
Thus we need to iterate all numbers between 0
(inclusive) and 2^(length - 1)
(exclusive).
Condition (i & (1 << j)) > 0
in the code you provided just checks whether digit at position j
(starting from the end, 0-based) is 0
(and we don't need to insert space) or 1
(and space should be added).
Let's take value 6
(110
in binary) for example.
(6 & (1 << 0)) = 110 & 001 = 000 = 0
(condition > 0
is not met)
(6 & (1 << 1)) = 110 & 010 = 010 = 2
(condition > 0
is met)
(6 & (1 << 2)) = 110 & 100 = 100 = 4
(condition > 0
is met)
ok i got it, the 000-111 logic really made it clear for me. still one doubt. how is(i & (1 << j)) > 0
creating this 000-111 sequence. Seems like in that one line it is generating the binary number 0,1,2,... in sequence like 0 0 0 0 0 1 0 1 0 ...
– Arthanari C
Aug 24 '17 at 22:35
Sequence 000-111 is generated by simply iterating decimal values 0, 1, 2, 3, 4, 5, 6, 7. 0 is 000 and 7 is 111 in binary.(i & (1 << j)) > 0
then is used just for extracting ones and zeroes from numbers from this sequence. I added an example at the end of my answer.
– Olexiy Sadovnikov
Aug 24 '17 at 22:48
add a comment |
Let's take string abcd
as an example.
There are 3 possible places where space can be put:
- Between "a" and "b"
- Between "b" and "c"
- Between "c" and "d"
So generally if length of your string is length
then you have length - 1
places for spaces.
Assume that each such place is represented with a separate digit in a binary number. This digit is 0 when we don't put space there, and 1 when we do. E.g.:
a b c d
0 0 0
means that we don't put any spaces - abcd
0 0 1
means that we put space between "c" and "d" only - abc d
0 1 0
means that we put space between "b" and "c" only - ab cd
0 1 1
means ab c d
1 0 0
means a bcd
1 0 1
means a bc d
1 1 0
means a b cd
1 1 1
means a b c d
Converting 000
, 001
, 010
, ..., 111
from binary to decimal will give us values 0
, 1
, 2
, ..., 7
.
With 3 places for spaces we have 8 options to put them. It's exactly 2^3
or 2^(length - 1)
.
Thus we need to iterate all numbers between 0
(inclusive) and 2^(length - 1)
(exclusive).
Condition (i & (1 << j)) > 0
in the code you provided just checks whether digit at position j
(starting from the end, 0-based) is 0
(and we don't need to insert space) or 1
(and space should be added).
Let's take value 6
(110
in binary) for example.
(6 & (1 << 0)) = 110 & 001 = 000 = 0
(condition > 0
is not met)
(6 & (1 << 1)) = 110 & 010 = 010 = 2
(condition > 0
is met)
(6 & (1 << 2)) = 110 & 100 = 100 = 4
(condition > 0
is met)
ok i got it, the 000-111 logic really made it clear for me. still one doubt. how is(i & (1 << j)) > 0
creating this 000-111 sequence. Seems like in that one line it is generating the binary number 0,1,2,... in sequence like 0 0 0 0 0 1 0 1 0 ...
– Arthanari C
Aug 24 '17 at 22:35
Sequence 000-111 is generated by simply iterating decimal values 0, 1, 2, 3, 4, 5, 6, 7. 0 is 000 and 7 is 111 in binary.(i & (1 << j)) > 0
then is used just for extracting ones and zeroes from numbers from this sequence. I added an example at the end of my answer.
– Olexiy Sadovnikov
Aug 24 '17 at 22:48
add a comment |
Let's take string abcd
as an example.
There are 3 possible places where space can be put:
- Between "a" and "b"
- Between "b" and "c"
- Between "c" and "d"
So generally if length of your string is length
then you have length - 1
places for spaces.
Assume that each such place is represented with a separate digit in a binary number. This digit is 0 when we don't put space there, and 1 when we do. E.g.:
a b c d
0 0 0
means that we don't put any spaces - abcd
0 0 1
means that we put space between "c" and "d" only - abc d
0 1 0
means that we put space between "b" and "c" only - ab cd
0 1 1
means ab c d
1 0 0
means a bcd
1 0 1
means a bc d
1 1 0
means a b cd
1 1 1
means a b c d
Converting 000
, 001
, 010
, ..., 111
from binary to decimal will give us values 0
, 1
, 2
, ..., 7
.
With 3 places for spaces we have 8 options to put them. It's exactly 2^3
or 2^(length - 1)
.
Thus we need to iterate all numbers between 0
(inclusive) and 2^(length - 1)
(exclusive).
Condition (i & (1 << j)) > 0
in the code you provided just checks whether digit at position j
(starting from the end, 0-based) is 0
(and we don't need to insert space) or 1
(and space should be added).
Let's take value 6
(110
in binary) for example.
(6 & (1 << 0)) = 110 & 001 = 000 = 0
(condition > 0
is not met)
(6 & (1 << 1)) = 110 & 010 = 010 = 2
(condition > 0
is met)
(6 & (1 << 2)) = 110 & 100 = 100 = 4
(condition > 0
is met)
Let's take string abcd
as an example.
There are 3 possible places where space can be put:
- Between "a" and "b"
- Between "b" and "c"
- Between "c" and "d"
So generally if length of your string is length
then you have length - 1
places for spaces.
Assume that each such place is represented with a separate digit in a binary number. This digit is 0 when we don't put space there, and 1 when we do. E.g.:
a b c d
0 0 0
means that we don't put any spaces - abcd
0 0 1
means that we put space between "c" and "d" only - abc d
0 1 0
means that we put space between "b" and "c" only - ab cd
0 1 1
means ab c d
1 0 0
means a bcd
1 0 1
means a bc d
1 1 0
means a b cd
1 1 1
means a b c d
Converting 000
, 001
, 010
, ..., 111
from binary to decimal will give us values 0
, 1
, 2
, ..., 7
.
With 3 places for spaces we have 8 options to put them. It's exactly 2^3
or 2^(length - 1)
.
Thus we need to iterate all numbers between 0
(inclusive) and 2^(length - 1)
(exclusive).
Condition (i & (1 << j)) > 0
in the code you provided just checks whether digit at position j
(starting from the end, 0-based) is 0
(and we don't need to insert space) or 1
(and space should be added).
Let's take value 6
(110
in binary) for example.
(6 & (1 << 0)) = 110 & 001 = 000 = 0
(condition > 0
is not met)
(6 & (1 << 1)) = 110 & 010 = 010 = 2
(condition > 0
is met)
(6 & (1 << 2)) = 110 & 100 = 100 = 4
(condition > 0
is met)
edited Aug 24 '17 at 22:46
answered Aug 24 '17 at 22:22
Olexiy SadovnikovOlexiy Sadovnikov
31316
31316
ok i got it, the 000-111 logic really made it clear for me. still one doubt. how is(i & (1 << j)) > 0
creating this 000-111 sequence. Seems like in that one line it is generating the binary number 0,1,2,... in sequence like 0 0 0 0 0 1 0 1 0 ...
– Arthanari C
Aug 24 '17 at 22:35
Sequence 000-111 is generated by simply iterating decimal values 0, 1, 2, 3, 4, 5, 6, 7. 0 is 000 and 7 is 111 in binary.(i & (1 << j)) > 0
then is used just for extracting ones and zeroes from numbers from this sequence. I added an example at the end of my answer.
– Olexiy Sadovnikov
Aug 24 '17 at 22:48
add a comment |
ok i got it, the 000-111 logic really made it clear for me. still one doubt. how is(i & (1 << j)) > 0
creating this 000-111 sequence. Seems like in that one line it is generating the binary number 0,1,2,... in sequence like 0 0 0 0 0 1 0 1 0 ...
– Arthanari C
Aug 24 '17 at 22:35
Sequence 000-111 is generated by simply iterating decimal values 0, 1, 2, 3, 4, 5, 6, 7. 0 is 000 and 7 is 111 in binary.(i & (1 << j)) > 0
then is used just for extracting ones and zeroes from numbers from this sequence. I added an example at the end of my answer.
– Olexiy Sadovnikov
Aug 24 '17 at 22:48
ok i got it, the 000-111 logic really made it clear for me. still one doubt. how is
(i & (1 << j)) > 0
creating this 000-111 sequence. Seems like in that one line it is generating the binary number 0,1,2,... in sequence like 0 0 0 0 0 1 0 1 0 ...– Arthanari C
Aug 24 '17 at 22:35
ok i got it, the 000-111 logic really made it clear for me. still one doubt. how is
(i & (1 << j)) > 0
creating this 000-111 sequence. Seems like in that one line it is generating the binary number 0,1,2,... in sequence like 0 0 0 0 0 1 0 1 0 ...– Arthanari C
Aug 24 '17 at 22:35
Sequence 000-111 is generated by simply iterating decimal values 0, 1, 2, 3, 4, 5, 6, 7. 0 is 000 and 7 is 111 in binary.
(i & (1 << j)) > 0
then is used just for extracting ones and zeroes from numbers from this sequence. I added an example at the end of my answer.– Olexiy Sadovnikov
Aug 24 '17 at 22:48
Sequence 000-111 is generated by simply iterating decimal values 0, 1, 2, 3, 4, 5, 6, 7. 0 is 000 and 7 is 111 in binary.
(i & (1 << j)) > 0
then is used just for extracting ones and zeroes from numbers from this sequence. I added an example at the end of my answer.– Olexiy Sadovnikov
Aug 24 '17 at 22:48
add a comment |
There are 2 possibilities between each 2 characters: either has space or not. If spaces are allowed only between characters then the number of possibilities for 4 characters is 2 * 2 * 2 or 2 ^ (length - 1)
add a comment |
There are 2 possibilities between each 2 characters: either has space or not. If spaces are allowed only between characters then the number of possibilities for 4 characters is 2 * 2 * 2 or 2 ^ (length - 1)
add a comment |
There are 2 possibilities between each 2 characters: either has space or not. If spaces are allowed only between characters then the number of possibilities for 4 characters is 2 * 2 * 2 or 2 ^ (length - 1)
There are 2 possibilities between each 2 characters: either has space or not. If spaces are allowed only between characters then the number of possibilities for 4 characters is 2 * 2 * 2 or 2 ^ (length - 1)
answered Aug 24 '17 at 22:27
SlaiSlai
15.3k32235
15.3k32235
add a comment |
add a comment |
resultSize = Math.pow(2, length - 1)
says there are 2^n-1 possible ways to print a string given the problem definition. As far as to why that is the number of solutions is pretty easy to understand if you start with a string that has 2 characters and work your way upward. So pretend you have the string "ab". There is two solutions, you can put a space between a and b or you can not put a space between a and b. Lets add a character to get "abc". Well, we already know that there are two solutions for the string "ab" so we need multiply that solution by the number of ways you can put a space between b and c. Which is 2 so that gives us 2 * 2 solutions. You can extend that to a string of n size. So that means that the number of solutions is 2 * 2 * 2 * 2 * ... n - 1. Or in otherwords 2 ^ n-1.
The next part is a little trickier, but its a clever way of determining how many spaces and where they go in any given solution. The bitwise &
takes the each bit of two numbers, compares them, then spits out a new number where each bit is a 1 if both the bits of the two numbers were 1, or 0 if the bits were not 1 and 1. For example (binary numbers):
01 & 01 = 01
10 & 01 = 00
Or a bigger example:
10010010 & 10100010 = 10000010
The <<
operator just moves all bits n position to left where n is the right hand expression (multiply by 2 n times).
For example:
1 << 1 = 2
2 << 1 = 4
2 << 2 = 8
1 << 4 = 8
So back to your code now. Lets break down the if statement
if(i & (1 << j) > 0) ...
In english this says, if the number index of the solution we are looking at shares any 1 bits with 1 shifted by the index of the character we are looking at, then put a space after that character. Olexiy Sadovnikov's answer has some good examples of what this would look like for some of the iterations.
Its also worth noting that this is not the only way to do this. You could pretty easily determine that the max number of spaces is n - 1 then just linearly find all of the solutions that have 0 spaces in them, then find all the solutions that have 1 space in them, then 2 spaces .... to n - 1 spaces. Though the solution you posted would be faster than doing it this way. Of course when your talking about algorithms of exponential complexity it ultimately won't matter because strings bigger than about 60 chars will take longer than you probably care to wait for even with a strictly 2^n algorithm.
In answer to the question of how these techniques can be used in other places. Bit shifting is used very frequently in encryption algorithms as well as the bitwise & and | operators.
add a comment |
resultSize = Math.pow(2, length - 1)
says there are 2^n-1 possible ways to print a string given the problem definition. As far as to why that is the number of solutions is pretty easy to understand if you start with a string that has 2 characters and work your way upward. So pretend you have the string "ab". There is two solutions, you can put a space between a and b or you can not put a space between a and b. Lets add a character to get "abc". Well, we already know that there are two solutions for the string "ab" so we need multiply that solution by the number of ways you can put a space between b and c. Which is 2 so that gives us 2 * 2 solutions. You can extend that to a string of n size. So that means that the number of solutions is 2 * 2 * 2 * 2 * ... n - 1. Or in otherwords 2 ^ n-1.
The next part is a little trickier, but its a clever way of determining how many spaces and where they go in any given solution. The bitwise &
takes the each bit of two numbers, compares them, then spits out a new number where each bit is a 1 if both the bits of the two numbers were 1, or 0 if the bits were not 1 and 1. For example (binary numbers):
01 & 01 = 01
10 & 01 = 00
Or a bigger example:
10010010 & 10100010 = 10000010
The <<
operator just moves all bits n position to left where n is the right hand expression (multiply by 2 n times).
For example:
1 << 1 = 2
2 << 1 = 4
2 << 2 = 8
1 << 4 = 8
So back to your code now. Lets break down the if statement
if(i & (1 << j) > 0) ...
In english this says, if the number index of the solution we are looking at shares any 1 bits with 1 shifted by the index of the character we are looking at, then put a space after that character. Olexiy Sadovnikov's answer has some good examples of what this would look like for some of the iterations.
Its also worth noting that this is not the only way to do this. You could pretty easily determine that the max number of spaces is n - 1 then just linearly find all of the solutions that have 0 spaces in them, then find all the solutions that have 1 space in them, then 2 spaces .... to n - 1 spaces. Though the solution you posted would be faster than doing it this way. Of course when your talking about algorithms of exponential complexity it ultimately won't matter because strings bigger than about 60 chars will take longer than you probably care to wait for even with a strictly 2^n algorithm.
In answer to the question of how these techniques can be used in other places. Bit shifting is used very frequently in encryption algorithms as well as the bitwise & and | operators.
add a comment |
resultSize = Math.pow(2, length - 1)
says there are 2^n-1 possible ways to print a string given the problem definition. As far as to why that is the number of solutions is pretty easy to understand if you start with a string that has 2 characters and work your way upward. So pretend you have the string "ab". There is two solutions, you can put a space between a and b or you can not put a space between a and b. Lets add a character to get "abc". Well, we already know that there are two solutions for the string "ab" so we need multiply that solution by the number of ways you can put a space between b and c. Which is 2 so that gives us 2 * 2 solutions. You can extend that to a string of n size. So that means that the number of solutions is 2 * 2 * 2 * 2 * ... n - 1. Or in otherwords 2 ^ n-1.
The next part is a little trickier, but its a clever way of determining how many spaces and where they go in any given solution. The bitwise &
takes the each bit of two numbers, compares them, then spits out a new number where each bit is a 1 if both the bits of the two numbers were 1, or 0 if the bits were not 1 and 1. For example (binary numbers):
01 & 01 = 01
10 & 01 = 00
Or a bigger example:
10010010 & 10100010 = 10000010
The <<
operator just moves all bits n position to left where n is the right hand expression (multiply by 2 n times).
For example:
1 << 1 = 2
2 << 1 = 4
2 << 2 = 8
1 << 4 = 8
So back to your code now. Lets break down the if statement
if(i & (1 << j) > 0) ...
In english this says, if the number index of the solution we are looking at shares any 1 bits with 1 shifted by the index of the character we are looking at, then put a space after that character. Olexiy Sadovnikov's answer has some good examples of what this would look like for some of the iterations.
Its also worth noting that this is not the only way to do this. You could pretty easily determine that the max number of spaces is n - 1 then just linearly find all of the solutions that have 0 spaces in them, then find all the solutions that have 1 space in them, then 2 spaces .... to n - 1 spaces. Though the solution you posted would be faster than doing it this way. Of course when your talking about algorithms of exponential complexity it ultimately won't matter because strings bigger than about 60 chars will take longer than you probably care to wait for even with a strictly 2^n algorithm.
In answer to the question of how these techniques can be used in other places. Bit shifting is used very frequently in encryption algorithms as well as the bitwise & and | operators.
resultSize = Math.pow(2, length - 1)
says there are 2^n-1 possible ways to print a string given the problem definition. As far as to why that is the number of solutions is pretty easy to understand if you start with a string that has 2 characters and work your way upward. So pretend you have the string "ab". There is two solutions, you can put a space between a and b or you can not put a space between a and b. Lets add a character to get "abc". Well, we already know that there are two solutions for the string "ab" so we need multiply that solution by the number of ways you can put a space between b and c. Which is 2 so that gives us 2 * 2 solutions. You can extend that to a string of n size. So that means that the number of solutions is 2 * 2 * 2 * 2 * ... n - 1. Or in otherwords 2 ^ n-1.
The next part is a little trickier, but its a clever way of determining how many spaces and where they go in any given solution. The bitwise &
takes the each bit of two numbers, compares them, then spits out a new number where each bit is a 1 if both the bits of the two numbers were 1, or 0 if the bits were not 1 and 1. For example (binary numbers):
01 & 01 = 01
10 & 01 = 00
Or a bigger example:
10010010 & 10100010 = 10000010
The <<
operator just moves all bits n position to left where n is the right hand expression (multiply by 2 n times).
For example:
1 << 1 = 2
2 << 1 = 4
2 << 2 = 8
1 << 4 = 8
So back to your code now. Lets break down the if statement
if(i & (1 << j) > 0) ...
In english this says, if the number index of the solution we are looking at shares any 1 bits with 1 shifted by the index of the character we are looking at, then put a space after that character. Olexiy Sadovnikov's answer has some good examples of what this would look like for some of the iterations.
Its also worth noting that this is not the only way to do this. You could pretty easily determine that the max number of spaces is n - 1 then just linearly find all of the solutions that have 0 spaces in them, then find all the solutions that have 1 space in them, then 2 spaces .... to n - 1 spaces. Though the solution you posted would be faster than doing it this way. Of course when your talking about algorithms of exponential complexity it ultimately won't matter because strings bigger than about 60 chars will take longer than you probably care to wait for even with a strictly 2^n algorithm.
In answer to the question of how these techniques can be used in other places. Bit shifting is used very frequently in encryption algorithms as well as the bitwise & and | operators.
edited Aug 24 '17 at 23:30
answered Aug 24 '17 at 23:14
Joseph DittonJoseph Ditton
31816
31816
add a comment |
add a comment |
'''
The idea was to fix each character from the beginning and print space separated rest of the string.
Like for "ABCD":
A BCD # Fix A and print rest string
AB CD # Add B to previous value A and print rest of the string
ABC D # Add C to previous value AB and print rest of the string
Similarly we can add a space to produce all permutations.
Like:
In second step above we got "AB CD" by having "A" as prefix
So now we can get "A B CD" by having "A " as a prefix
'''
def printPermute(arr, s, app):
if len(arr) <= 1:
return
else:
print(app +''+arr[0:s] +' '+ arr[s:len(arr)])
prefix = app + ''+arr[0:s]
suffix = arr[s:len(arr)]
printPermute(suffix, 1, prefix)
printPermute(suffix, 1, prefix+' ') #Appending space
printPermute("ABCDE", 1, '') #Empty string
add a comment |
'''
The idea was to fix each character from the beginning and print space separated rest of the string.
Like for "ABCD":
A BCD # Fix A and print rest string
AB CD # Add B to previous value A and print rest of the string
ABC D # Add C to previous value AB and print rest of the string
Similarly we can add a space to produce all permutations.
Like:
In second step above we got "AB CD" by having "A" as prefix
So now we can get "A B CD" by having "A " as a prefix
'''
def printPermute(arr, s, app):
if len(arr) <= 1:
return
else:
print(app +''+arr[0:s] +' '+ arr[s:len(arr)])
prefix = app + ''+arr[0:s]
suffix = arr[s:len(arr)]
printPermute(suffix, 1, prefix)
printPermute(suffix, 1, prefix+' ') #Appending space
printPermute("ABCDE", 1, '') #Empty string
add a comment |
'''
The idea was to fix each character from the beginning and print space separated rest of the string.
Like for "ABCD":
A BCD # Fix A and print rest string
AB CD # Add B to previous value A and print rest of the string
ABC D # Add C to previous value AB and print rest of the string
Similarly we can add a space to produce all permutations.
Like:
In second step above we got "AB CD" by having "A" as prefix
So now we can get "A B CD" by having "A " as a prefix
'''
def printPermute(arr, s, app):
if len(arr) <= 1:
return
else:
print(app +''+arr[0:s] +' '+ arr[s:len(arr)])
prefix = app + ''+arr[0:s]
suffix = arr[s:len(arr)]
printPermute(suffix, 1, prefix)
printPermute(suffix, 1, prefix+' ') #Appending space
printPermute("ABCDE", 1, '') #Empty string
'''
The idea was to fix each character from the beginning and print space separated rest of the string.
Like for "ABCD":
A BCD # Fix A and print rest string
AB CD # Add B to previous value A and print rest of the string
ABC D # Add C to previous value AB and print rest of the string
Similarly we can add a space to produce all permutations.
Like:
In second step above we got "AB CD" by having "A" as prefix
So now we can get "A B CD" by having "A " as a prefix
'''
def printPermute(arr, s, app):
if len(arr) <= 1:
return
else:
print(app +''+arr[0:s] +' '+ arr[s:len(arr)])
prefix = app + ''+arr[0:s]
suffix = arr[s:len(arr)]
printPermute(suffix, 1, prefix)
printPermute(suffix, 1, prefix+' ') #Appending space
printPermute("ABCDE", 1, '') #Empty string
answered Dec 18 '17 at 18:27
quintinquintin
337522
337522
add a comment |
add a comment |
simple solution Using Javascript
String.prototype.splice = function(idx, rem, str)
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
;
function printPattern(str, i, n)
if(i==n)
return;
var buff = str;
var j = str.length - n + i;
buff = str.splice(j,0," ");
console.log(buff);
printPattern(str, i+1, n);
printPattern(buff, i+1, n);
var str = "ABCD"
printPattern(str, 1, str.length);
console.log(str);
add a comment |
simple solution Using Javascript
String.prototype.splice = function(idx, rem, str)
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
;
function printPattern(str, i, n)
if(i==n)
return;
var buff = str;
var j = str.length - n + i;
buff = str.splice(j,0," ");
console.log(buff);
printPattern(str, i+1, n);
printPattern(buff, i+1, n);
var str = "ABCD"
printPattern(str, 1, str.length);
console.log(str);
add a comment |
simple solution Using Javascript
String.prototype.splice = function(idx, rem, str)
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
;
function printPattern(str, i, n)
if(i==n)
return;
var buff = str;
var j = str.length - n + i;
buff = str.splice(j,0," ");
console.log(buff);
printPattern(str, i+1, n);
printPattern(buff, i+1, n);
var str = "ABCD"
printPattern(str, 1, str.length);
console.log(str);
simple solution Using Javascript
String.prototype.splice = function(idx, rem, str)
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
;
function printPattern(str, i, n)
if(i==n)
return;
var buff = str;
var j = str.length - n + i;
buff = str.splice(j,0," ");
console.log(buff);
printPattern(str, i+1, n);
printPattern(buff, i+1, n);
var str = "ABCD"
printPattern(str, 1, str.length);
console.log(str);
answered Nov 13 '18 at 20:58
Gaurav GargGaurav Garg
1
1
add a comment |
add a comment |
.pow
is a method fromMath
which stands for "power". It takes two arguments: the base (here2
) and the exponent. Read here for more information.&
is the bitwise AND operator, it takes the two binary representation of the numbers and performs a logical AND, here's a thread on bitwise operators
EDIT: why Math.pow(2,length-1)
gives us the number of possible strings?
I remember doing it in an exercise last year in math class, but I'll try to explain it without sums.
Essentially we want to determine the number of strings you can make by adding one or no space in between letters. Your initial string has n
letters. Here's the reason why:
Starting from the left or the word after each letter you have two choices
1 - to put a space
2 - not to put a space
You will have to choose between the two options exactly n-1
times.
This means you will have a total of 2^(n-1)
possible solutions.
I get that, but for the given problem how does 2^m give the number of possible results? That is where i have doubt.
– Arthanari C
Aug 24 '17 at 22:14
@ArthanariC Here's my edit, have a look :)
– Ivan
Aug 24 '17 at 22:38
add a comment |
.pow
is a method fromMath
which stands for "power". It takes two arguments: the base (here2
) and the exponent. Read here for more information.&
is the bitwise AND operator, it takes the two binary representation of the numbers and performs a logical AND, here's a thread on bitwise operators
EDIT: why Math.pow(2,length-1)
gives us the number of possible strings?
I remember doing it in an exercise last year in math class, but I'll try to explain it without sums.
Essentially we want to determine the number of strings you can make by adding one or no space in between letters. Your initial string has n
letters. Here's the reason why:
Starting from the left or the word after each letter you have two choices
1 - to put a space
2 - not to put a space
You will have to choose between the two options exactly n-1
times.
This means you will have a total of 2^(n-1)
possible solutions.
I get that, but for the given problem how does 2^m give the number of possible results? That is where i have doubt.
– Arthanari C
Aug 24 '17 at 22:14
@ArthanariC Here's my edit, have a look :)
– Ivan
Aug 24 '17 at 22:38
add a comment |
.pow
is a method fromMath
which stands for "power". It takes two arguments: the base (here2
) and the exponent. Read here for more information.&
is the bitwise AND operator, it takes the two binary representation of the numbers and performs a logical AND, here's a thread on bitwise operators
EDIT: why Math.pow(2,length-1)
gives us the number of possible strings?
I remember doing it in an exercise last year in math class, but I'll try to explain it without sums.
Essentially we want to determine the number of strings you can make by adding one or no space in between letters. Your initial string has n
letters. Here's the reason why:
Starting from the left or the word after each letter you have two choices
1 - to put a space
2 - not to put a space
You will have to choose between the two options exactly n-1
times.
This means you will have a total of 2^(n-1)
possible solutions.
.pow
is a method fromMath
which stands for "power". It takes two arguments: the base (here2
) and the exponent. Read here for more information.&
is the bitwise AND operator, it takes the two binary representation of the numbers and performs a logical AND, here's a thread on bitwise operators
EDIT: why Math.pow(2,length-1)
gives us the number of possible strings?
I remember doing it in an exercise last year in math class, but I'll try to explain it without sums.
Essentially we want to determine the number of strings you can make by adding one or no space in between letters. Your initial string has n
letters. Here's the reason why:
Starting from the left or the word after each letter you have two choices
1 - to put a space
2 - not to put a space
You will have to choose between the two options exactly n-1
times.
This means you will have a total of 2^(n-1)
possible solutions.
edited Aug 24 '17 at 22:36
answered Aug 24 '17 at 22:10
IvanIvan
5,27331339
5,27331339
I get that, but for the given problem how does 2^m give the number of possible results? That is where i have doubt.
– Arthanari C
Aug 24 '17 at 22:14
@ArthanariC Here's my edit, have a look :)
– Ivan
Aug 24 '17 at 22:38
add a comment |
I get that, but for the given problem how does 2^m give the number of possible results? That is where i have doubt.
– Arthanari C
Aug 24 '17 at 22:14
@ArthanariC Here's my edit, have a look :)
– Ivan
Aug 24 '17 at 22:38
I get that, but for the given problem how does 2^m give the number of possible results? That is where i have doubt.
– Arthanari C
Aug 24 '17 at 22:14
I get that, but for the given problem how does 2^m give the number of possible results? That is where i have doubt.
– Arthanari C
Aug 24 '17 at 22:14
@ArthanariC Here's my edit, have a look :)
– Ivan
Aug 24 '17 at 22:38
@ArthanariC Here's my edit, have a look :)
– Ivan
Aug 24 '17 at 22:38
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45871640%2fprint-all-possible-strings-that-can-be-made-by-placing-spaces%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Please try and use snippets when you can, I've updated your question to use a snippet.
– Keith
Aug 24 '17 at 22:10
ok got it, thanks...
– Arthanari C
Aug 24 '17 at 22:16