Permutation and subsequences of stringLongest DNA sequence that appears at least twice (only one DNA string...

Creepy dinosaur pc game identification

Is it better practice to read straight from sheet music rather than memorize it?

What does "Scientists rise up against statistical significance" mean? (Comment in Nature)

What changes for testers when they are testing in agile environments?

Multiplicative persistence

Count the occurrence of each unique word in the file

Does a log transform always bring a distribution closer to normal?

Infinite dials to reset ever?

What was this official D&D 3.5e Lovecraft-flavored rulebook?

What is going on with 'gets(stdin)' on the site coderbyte?

How do you make your own symbol when Detexify fails?

Does Doodling or Improvising on the Piano Have Any Benefits?

How to implement a feedback to keep the DC gain at zero for this conceptual passive filter?

What is the evidence for the "tyranny of the majority problem" in a direct democracy context?

On a tidally locked planet, would time be quantized?

New brakes for 90s road bike

Melting point of aspirin, contradicting sources

A social experiment. What is the worst that can happen?

Strong empirical falsification of quantum mechanics based on vacuum energy density

sed '/^$/d' and grep -Ev '^$' failed to remove blank lines

Why is it that I can sometimes guess the next note?

Can disgust be a key component of horror?

Is (0,1] a closed or open set?

Redundant comparison & "if" before assignment



Permutation and subsequences of string


Longest DNA sequence that appears at least twice (only one DNA string as input)Necklace counting problem-with consecutive prime constraintAlgorithm for detecting keyboard slipsYou need to diversify your stringsDailyProgrammer 284: Wandering FingersHackerrank: Lucky Number Eight (Dynamic Programming)Phone number duplication detectorMars Rover Kata using TDD and SOLIDLongest word in dictionary that is a subsequence of a given stringMr. Muffin's ball-passing game













1












$begingroup$


I have an assignment to solve this problem. I’m not too sure how permutate works by tracing, just tried on inspiration and it works. This code runs on all provided test cases, but I’m just trying to look for ways of improvement in terms of time efficiency, space efficiency and styling.




Question Description



Bob the Dog has a word W containing N distinct lowercase
letters (‘a’ to ‘z’).



Bob the Dog would like you to generate all possible permutations of
the N letters followed by all possible sub-sequences of the
N letters.



A permutation of the letters in W is generated by reordering the
letters in W. You are to print all possible such re-orderings.
For example, permutations of ‘cat’ are ‘cta’, ‘cat’, ‘atc’, ‘act’,
‘tac’, ‘tca’.



A sub-sequence of the letters in W is generated by choosing a
non-empty subset of letters in W, without changing their relative
order in W. For example, sub-sequences of ‘cat’ are ‘c’, ‘a’, ‘t’,
‘ca’, ‘at’, ‘ct’, ‘cat’.



The permutations should be printed in increasing lexicographical
order, followed by the sub- sequences in increasing lexicographical
order as well. In order to sort a list of strings in lexicographical
order, you can simply utilize Collections.sort on a list of
Strings. The default compareTo function in String class is already comparing in lexicographical order.



Input



The input contains a single line, containing the word W of length
N.



Output



The output should contain (N!) + 2^N – 1 lines.



The first N! lines should contain all possible permutations of the
letters in W, printed in increasing lexicographical order.



The next 2^N-1 lines should contain all possible sub-sequences of
the letters in W, printed in increasing lexicographical order as
well.



Limits



• 1≤N≤9



W will only contain distinct lowercase letters (‘a’ to ‘z’).




Here is my attempt, do inform me if any more information is needed.Thanks.



import java.util.*;
import java.util.stream.Collectors;

public class Generate {
private void run() {
Scanner sc = new Scanner(System.in);
String inputs = sc.next();
List<String> sortedString = inputs.codePoints()//split into ASCII int
.sorted()
.mapToObj(x->String.valueOf((char)x))//changes to String
.collect(Collectors.toList());
//breaks the string into an array of String and sort a smaller list

permutate(sortedString, new boolean[sortedString.size()],0,new StringBuilder());

subSequence(inputs);//order requires the original string


}

public static void main(String[] args) {
Generate newGenerate = new Generate();
newGenerate.run();
}

//uses a flag Array to note which character is used before instead of making new String arrays
public static void permutate(List<String> lst, boolean [] used, int numUsed,StringBuilder builder) {
if (lst.size()==numUsed) {
System.out.println(builder);//each permutation must be as long as the input size
return;
}
for (int i=0;i<lst.size();i++) { //For each loop, 1 case will use the character, the other wouldn't
if (used[i]) {
continue;
}
String current = lst.get(i);

StringBuilder copiedBuilder = new StringBuilder(builder.toString());//shallow copy of a String,
//Builders are generally faster than concatenation
boolean [] copied = Arrays.copyOf(used,lst.size());//duplicate 1 flag array for the other case
copied[i]=true; //update only one of them
copiedBuilder.append(current);
permutate(lst,copied,numUsed+1,copiedBuilder);
}

}

//helper method that fills the results list with StringBuilders to be sorted
public static void basicSubSequence(String input,StringBuilder builder, int position,ArrayList<String> results) {
if (position==input.length()) {//no more characters in input is left
if (builder.length()==0) {//excludes the empty String as a subsequence
return;
}
results.add(builder.toString());
return;
}
//similarly, make a copy of builder and update only the copy
StringBuilder copiedBuilder = new StringBuilder(builder.toString());
char current = input.charAt(position);
copiedBuilder.append(current);
basicSubSequence(input,copiedBuilder,position+1,results);
basicSubSequence(input,builder,position+1,results);
}

public static void subSequence(String inputs) {
ArrayList<String> seqResults = new ArrayList<>();//creates a result list
basicSubSequence(inputs, new StringBuilder(),0,seqResults);//fills up the list
Collections.sort(seqResults);//sorts the list
for (String str: seqResults) {
System.out.println(str);
}
}



}


Sample Input



tan


Output



ant
atn
nat
nta
tan
tna
a
an
n
t
ta
tan
tn




Disclaimer



There are some concerns regarding the use of words like "subsequence", which might include some cases that are not included here. However, this code works for all the test cases provided, which means my interpretation of it matches the meaning of the author's, that of which I cannot control.










share|improve this question











$endgroup$












  • $begingroup$
    Your output is incorrectly missing na and nt and incorrectly contains a duplicated tan, which is not a subsequence that is shorter than the complete alphabet. As such your code is not accomplishing the goal it was written for and therefore the question is unfortunately off-topic for this site. For more information, see the help center. Thanks!
    $endgroup$
    – Vogel612
    Mar 14 at 19:21






  • 1




    $begingroup$
    Actually my code fits the question's description, there are 6 permutations and (2^3-1) subsequences. I'm not sure if subsequence's common usage should include the input term itself, but this is consistently the interpretation for all test cases. 'na` and nt will not happen because it is sequentially impossible in tan, the original input. a always comes before n and t always comes before n
    $endgroup$
    – Prashin Jeevaganth
    Mar 14 at 23:01










  • $begingroup$
    you are right. in my defense: the formal strictness of the problem formulation leaves a lot to be desired...
    $endgroup$
    – Vogel612
    Mar 15 at 19:16
















1












$begingroup$


I have an assignment to solve this problem. I’m not too sure how permutate works by tracing, just tried on inspiration and it works. This code runs on all provided test cases, but I’m just trying to look for ways of improvement in terms of time efficiency, space efficiency and styling.




Question Description



Bob the Dog has a word W containing N distinct lowercase
letters (‘a’ to ‘z’).



Bob the Dog would like you to generate all possible permutations of
the N letters followed by all possible sub-sequences of the
N letters.



A permutation of the letters in W is generated by reordering the
letters in W. You are to print all possible such re-orderings.
For example, permutations of ‘cat’ are ‘cta’, ‘cat’, ‘atc’, ‘act’,
‘tac’, ‘tca’.



A sub-sequence of the letters in W is generated by choosing a
non-empty subset of letters in W, without changing their relative
order in W. For example, sub-sequences of ‘cat’ are ‘c’, ‘a’, ‘t’,
‘ca’, ‘at’, ‘ct’, ‘cat’.



The permutations should be printed in increasing lexicographical
order, followed by the sub- sequences in increasing lexicographical
order as well. In order to sort a list of strings in lexicographical
order, you can simply utilize Collections.sort on a list of
Strings. The default compareTo function in String class is already comparing in lexicographical order.



Input



The input contains a single line, containing the word W of length
N.



Output



The output should contain (N!) + 2^N – 1 lines.



The first N! lines should contain all possible permutations of the
letters in W, printed in increasing lexicographical order.



The next 2^N-1 lines should contain all possible sub-sequences of
the letters in W, printed in increasing lexicographical order as
well.



Limits



• 1≤N≤9



W will only contain distinct lowercase letters (‘a’ to ‘z’).




Here is my attempt, do inform me if any more information is needed.Thanks.



import java.util.*;
import java.util.stream.Collectors;

public class Generate {
private void run() {
Scanner sc = new Scanner(System.in);
String inputs = sc.next();
List<String> sortedString = inputs.codePoints()//split into ASCII int
.sorted()
.mapToObj(x->String.valueOf((char)x))//changes to String
.collect(Collectors.toList());
//breaks the string into an array of String and sort a smaller list

permutate(sortedString, new boolean[sortedString.size()],0,new StringBuilder());

subSequence(inputs);//order requires the original string


}

public static void main(String[] args) {
Generate newGenerate = new Generate();
newGenerate.run();
}

//uses a flag Array to note which character is used before instead of making new String arrays
public static void permutate(List<String> lst, boolean [] used, int numUsed,StringBuilder builder) {
if (lst.size()==numUsed) {
System.out.println(builder);//each permutation must be as long as the input size
return;
}
for (int i=0;i<lst.size();i++) { //For each loop, 1 case will use the character, the other wouldn't
if (used[i]) {
continue;
}
String current = lst.get(i);

StringBuilder copiedBuilder = new StringBuilder(builder.toString());//shallow copy of a String,
//Builders are generally faster than concatenation
boolean [] copied = Arrays.copyOf(used,lst.size());//duplicate 1 flag array for the other case
copied[i]=true; //update only one of them
copiedBuilder.append(current);
permutate(lst,copied,numUsed+1,copiedBuilder);
}

}

//helper method that fills the results list with StringBuilders to be sorted
public static void basicSubSequence(String input,StringBuilder builder, int position,ArrayList<String> results) {
if (position==input.length()) {//no more characters in input is left
if (builder.length()==0) {//excludes the empty String as a subsequence
return;
}
results.add(builder.toString());
return;
}
//similarly, make a copy of builder and update only the copy
StringBuilder copiedBuilder = new StringBuilder(builder.toString());
char current = input.charAt(position);
copiedBuilder.append(current);
basicSubSequence(input,copiedBuilder,position+1,results);
basicSubSequence(input,builder,position+1,results);
}

public static void subSequence(String inputs) {
ArrayList<String> seqResults = new ArrayList<>();//creates a result list
basicSubSequence(inputs, new StringBuilder(),0,seqResults);//fills up the list
Collections.sort(seqResults);//sorts the list
for (String str: seqResults) {
System.out.println(str);
}
}



}


Sample Input



tan


Output



ant
atn
nat
nta
tan
tna
a
an
n
t
ta
tan
tn




Disclaimer



There are some concerns regarding the use of words like "subsequence", which might include some cases that are not included here. However, this code works for all the test cases provided, which means my interpretation of it matches the meaning of the author's, that of which I cannot control.










share|improve this question











$endgroup$












  • $begingroup$
    Your output is incorrectly missing na and nt and incorrectly contains a duplicated tan, which is not a subsequence that is shorter than the complete alphabet. As such your code is not accomplishing the goal it was written for and therefore the question is unfortunately off-topic for this site. For more information, see the help center. Thanks!
    $endgroup$
    – Vogel612
    Mar 14 at 19:21






  • 1




    $begingroup$
    Actually my code fits the question's description, there are 6 permutations and (2^3-1) subsequences. I'm not sure if subsequence's common usage should include the input term itself, but this is consistently the interpretation for all test cases. 'na` and nt will not happen because it is sequentially impossible in tan, the original input. a always comes before n and t always comes before n
    $endgroup$
    – Prashin Jeevaganth
    Mar 14 at 23:01










  • $begingroup$
    you are right. in my defense: the formal strictness of the problem formulation leaves a lot to be desired...
    $endgroup$
    – Vogel612
    Mar 15 at 19:16














1












1








1





$begingroup$


I have an assignment to solve this problem. I’m not too sure how permutate works by tracing, just tried on inspiration and it works. This code runs on all provided test cases, but I’m just trying to look for ways of improvement in terms of time efficiency, space efficiency and styling.




Question Description



Bob the Dog has a word W containing N distinct lowercase
letters (‘a’ to ‘z’).



Bob the Dog would like you to generate all possible permutations of
the N letters followed by all possible sub-sequences of the
N letters.



A permutation of the letters in W is generated by reordering the
letters in W. You are to print all possible such re-orderings.
For example, permutations of ‘cat’ are ‘cta’, ‘cat’, ‘atc’, ‘act’,
‘tac’, ‘tca’.



A sub-sequence of the letters in W is generated by choosing a
non-empty subset of letters in W, without changing their relative
order in W. For example, sub-sequences of ‘cat’ are ‘c’, ‘a’, ‘t’,
‘ca’, ‘at’, ‘ct’, ‘cat’.



The permutations should be printed in increasing lexicographical
order, followed by the sub- sequences in increasing lexicographical
order as well. In order to sort a list of strings in lexicographical
order, you can simply utilize Collections.sort on a list of
Strings. The default compareTo function in String class is already comparing in lexicographical order.



Input



The input contains a single line, containing the word W of length
N.



Output



The output should contain (N!) + 2^N – 1 lines.



The first N! lines should contain all possible permutations of the
letters in W, printed in increasing lexicographical order.



The next 2^N-1 lines should contain all possible sub-sequences of
the letters in W, printed in increasing lexicographical order as
well.



Limits



• 1≤N≤9



W will only contain distinct lowercase letters (‘a’ to ‘z’).




Here is my attempt, do inform me if any more information is needed.Thanks.



import java.util.*;
import java.util.stream.Collectors;

public class Generate {
private void run() {
Scanner sc = new Scanner(System.in);
String inputs = sc.next();
List<String> sortedString = inputs.codePoints()//split into ASCII int
.sorted()
.mapToObj(x->String.valueOf((char)x))//changes to String
.collect(Collectors.toList());
//breaks the string into an array of String and sort a smaller list

permutate(sortedString, new boolean[sortedString.size()],0,new StringBuilder());

subSequence(inputs);//order requires the original string


}

public static void main(String[] args) {
Generate newGenerate = new Generate();
newGenerate.run();
}

//uses a flag Array to note which character is used before instead of making new String arrays
public static void permutate(List<String> lst, boolean [] used, int numUsed,StringBuilder builder) {
if (lst.size()==numUsed) {
System.out.println(builder);//each permutation must be as long as the input size
return;
}
for (int i=0;i<lst.size();i++) { //For each loop, 1 case will use the character, the other wouldn't
if (used[i]) {
continue;
}
String current = lst.get(i);

StringBuilder copiedBuilder = new StringBuilder(builder.toString());//shallow copy of a String,
//Builders are generally faster than concatenation
boolean [] copied = Arrays.copyOf(used,lst.size());//duplicate 1 flag array for the other case
copied[i]=true; //update only one of them
copiedBuilder.append(current);
permutate(lst,copied,numUsed+1,copiedBuilder);
}

}

//helper method that fills the results list with StringBuilders to be sorted
public static void basicSubSequence(String input,StringBuilder builder, int position,ArrayList<String> results) {
if (position==input.length()) {//no more characters in input is left
if (builder.length()==0) {//excludes the empty String as a subsequence
return;
}
results.add(builder.toString());
return;
}
//similarly, make a copy of builder and update only the copy
StringBuilder copiedBuilder = new StringBuilder(builder.toString());
char current = input.charAt(position);
copiedBuilder.append(current);
basicSubSequence(input,copiedBuilder,position+1,results);
basicSubSequence(input,builder,position+1,results);
}

public static void subSequence(String inputs) {
ArrayList<String> seqResults = new ArrayList<>();//creates a result list
basicSubSequence(inputs, new StringBuilder(),0,seqResults);//fills up the list
Collections.sort(seqResults);//sorts the list
for (String str: seqResults) {
System.out.println(str);
}
}



}


Sample Input



tan


Output



ant
atn
nat
nta
tan
tna
a
an
n
t
ta
tan
tn




Disclaimer



There are some concerns regarding the use of words like "subsequence", which might include some cases that are not included here. However, this code works for all the test cases provided, which means my interpretation of it matches the meaning of the author's, that of which I cannot control.










share|improve this question











$endgroup$




I have an assignment to solve this problem. I’m not too sure how permutate works by tracing, just tried on inspiration and it works. This code runs on all provided test cases, but I’m just trying to look for ways of improvement in terms of time efficiency, space efficiency and styling.




Question Description



Bob the Dog has a word W containing N distinct lowercase
letters (‘a’ to ‘z’).



Bob the Dog would like you to generate all possible permutations of
the N letters followed by all possible sub-sequences of the
N letters.



A permutation of the letters in W is generated by reordering the
letters in W. You are to print all possible such re-orderings.
For example, permutations of ‘cat’ are ‘cta’, ‘cat’, ‘atc’, ‘act’,
‘tac’, ‘tca’.



A sub-sequence of the letters in W is generated by choosing a
non-empty subset of letters in W, without changing their relative
order in W. For example, sub-sequences of ‘cat’ are ‘c’, ‘a’, ‘t’,
‘ca’, ‘at’, ‘ct’, ‘cat’.



The permutations should be printed in increasing lexicographical
order, followed by the sub- sequences in increasing lexicographical
order as well. In order to sort a list of strings in lexicographical
order, you can simply utilize Collections.sort on a list of
Strings. The default compareTo function in String class is already comparing in lexicographical order.



Input



The input contains a single line, containing the word W of length
N.



Output



The output should contain (N!) + 2^N – 1 lines.



The first N! lines should contain all possible permutations of the
letters in W, printed in increasing lexicographical order.



The next 2^N-1 lines should contain all possible sub-sequences of
the letters in W, printed in increasing lexicographical order as
well.



Limits



• 1≤N≤9



W will only contain distinct lowercase letters (‘a’ to ‘z’).




Here is my attempt, do inform me if any more information is needed.Thanks.



import java.util.*;
import java.util.stream.Collectors;

public class Generate {
private void run() {
Scanner sc = new Scanner(System.in);
String inputs = sc.next();
List<String> sortedString = inputs.codePoints()//split into ASCII int
.sorted()
.mapToObj(x->String.valueOf((char)x))//changes to String
.collect(Collectors.toList());
//breaks the string into an array of String and sort a smaller list

permutate(sortedString, new boolean[sortedString.size()],0,new StringBuilder());

subSequence(inputs);//order requires the original string


}

public static void main(String[] args) {
Generate newGenerate = new Generate();
newGenerate.run();
}

//uses a flag Array to note which character is used before instead of making new String arrays
public static void permutate(List<String> lst, boolean [] used, int numUsed,StringBuilder builder) {
if (lst.size()==numUsed) {
System.out.println(builder);//each permutation must be as long as the input size
return;
}
for (int i=0;i<lst.size();i++) { //For each loop, 1 case will use the character, the other wouldn't
if (used[i]) {
continue;
}
String current = lst.get(i);

StringBuilder copiedBuilder = new StringBuilder(builder.toString());//shallow copy of a String,
//Builders are generally faster than concatenation
boolean [] copied = Arrays.copyOf(used,lst.size());//duplicate 1 flag array for the other case
copied[i]=true; //update only one of them
copiedBuilder.append(current);
permutate(lst,copied,numUsed+1,copiedBuilder);
}

}

//helper method that fills the results list with StringBuilders to be sorted
public static void basicSubSequence(String input,StringBuilder builder, int position,ArrayList<String> results) {
if (position==input.length()) {//no more characters in input is left
if (builder.length()==0) {//excludes the empty String as a subsequence
return;
}
results.add(builder.toString());
return;
}
//similarly, make a copy of builder and update only the copy
StringBuilder copiedBuilder = new StringBuilder(builder.toString());
char current = input.charAt(position);
copiedBuilder.append(current);
basicSubSequence(input,copiedBuilder,position+1,results);
basicSubSequence(input,builder,position+1,results);
}

public static void subSequence(String inputs) {
ArrayList<String> seqResults = new ArrayList<>();//creates a result list
basicSubSequence(inputs, new StringBuilder(),0,seqResults);//fills up the list
Collections.sort(seqResults);//sorts the list
for (String str: seqResults) {
System.out.println(str);
}
}



}


Sample Input



tan


Output



ant
atn
nat
nta
tan
tna
a
an
n
t
ta
tan
tn




Disclaimer



There are some concerns regarding the use of words like "subsequence", which might include some cases that are not included here. However, this code works for all the test cases provided, which means my interpretation of it matches the meaning of the author's, that of which I cannot control.







java algorithm programming-challenge






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 15 at 12:23









abuzittin gillifirca

5,992924




5,992924










asked Mar 14 at 14:42









Prashin JeevaganthPrashin Jeevaganth

2175




2175












  • $begingroup$
    Your output is incorrectly missing na and nt and incorrectly contains a duplicated tan, which is not a subsequence that is shorter than the complete alphabet. As such your code is not accomplishing the goal it was written for and therefore the question is unfortunately off-topic for this site. For more information, see the help center. Thanks!
    $endgroup$
    – Vogel612
    Mar 14 at 19:21






  • 1




    $begingroup$
    Actually my code fits the question's description, there are 6 permutations and (2^3-1) subsequences. I'm not sure if subsequence's common usage should include the input term itself, but this is consistently the interpretation for all test cases. 'na` and nt will not happen because it is sequentially impossible in tan, the original input. a always comes before n and t always comes before n
    $endgroup$
    – Prashin Jeevaganth
    Mar 14 at 23:01










  • $begingroup$
    you are right. in my defense: the formal strictness of the problem formulation leaves a lot to be desired...
    $endgroup$
    – Vogel612
    Mar 15 at 19:16


















  • $begingroup$
    Your output is incorrectly missing na and nt and incorrectly contains a duplicated tan, which is not a subsequence that is shorter than the complete alphabet. As such your code is not accomplishing the goal it was written for and therefore the question is unfortunately off-topic for this site. For more information, see the help center. Thanks!
    $endgroup$
    – Vogel612
    Mar 14 at 19:21






  • 1




    $begingroup$
    Actually my code fits the question's description, there are 6 permutations and (2^3-1) subsequences. I'm not sure if subsequence's common usage should include the input term itself, but this is consistently the interpretation for all test cases. 'na` and nt will not happen because it is sequentially impossible in tan, the original input. a always comes before n and t always comes before n
    $endgroup$
    – Prashin Jeevaganth
    Mar 14 at 23:01










  • $begingroup$
    you are right. in my defense: the formal strictness of the problem formulation leaves a lot to be desired...
    $endgroup$
    – Vogel612
    Mar 15 at 19:16
















$begingroup$
Your output is incorrectly missing na and nt and incorrectly contains a duplicated tan, which is not a subsequence that is shorter than the complete alphabet. As such your code is not accomplishing the goal it was written for and therefore the question is unfortunately off-topic for this site. For more information, see the help center. Thanks!
$endgroup$
– Vogel612
Mar 14 at 19:21




$begingroup$
Your output is incorrectly missing na and nt and incorrectly contains a duplicated tan, which is not a subsequence that is shorter than the complete alphabet. As such your code is not accomplishing the goal it was written for and therefore the question is unfortunately off-topic for this site. For more information, see the help center. Thanks!
$endgroup$
– Vogel612
Mar 14 at 19:21




1




1




$begingroup$
Actually my code fits the question's description, there are 6 permutations and (2^3-1) subsequences. I'm not sure if subsequence's common usage should include the input term itself, but this is consistently the interpretation for all test cases. 'na` and nt will not happen because it is sequentially impossible in tan, the original input. a always comes before n and t always comes before n
$endgroup$
– Prashin Jeevaganth
Mar 14 at 23:01




$begingroup$
Actually my code fits the question's description, there are 6 permutations and (2^3-1) subsequences. I'm not sure if subsequence's common usage should include the input term itself, but this is consistently the interpretation for all test cases. 'na` and nt will not happen because it is sequentially impossible in tan, the original input. a always comes before n and t always comes before n
$endgroup$
– Prashin Jeevaganth
Mar 14 at 23:01












$begingroup$
you are right. in my defense: the formal strictness of the problem formulation leaves a lot to be desired...
$endgroup$
– Vogel612
Mar 15 at 19:16




$begingroup$
you are right. in my defense: the formal strictness of the problem formulation leaves a lot to be desired...
$endgroup$
– Vogel612
Mar 15 at 19:16










2 Answers
2






active

oldest

votes


















2












$begingroup$

The question states you get one line but you operate on a list of strings.



Don't use end-of-line comments. They're hard to read and impossible to format.



Permutations can be generated with a simple recursive divide-and-conquer algorithm:




  1. If string length is 1, there is only one permutation.

  2. For each character in the string


    1. Swap character and the first one

    2. Generate permutations for substring after first character




You need to pass the string, the index of the start of the substring and a collection where you collect the results through the recursions.






share|improve this answer









$endgroup$













  • $begingroup$
    Sorry, I don't really understand what you meant by swapping character and the first one in ur pseudocode, can you illustrate with the test case?
    $endgroup$
    – Prashin Jeevaganth
    Mar 15 at 10:53





















2












$begingroup$

Your algorithm is single threaded, and does not modify the partial solution; so you need not copy about stuff. You can instead just undo what you modified in each step, namely remove the letter you appended and mark it unused.



There is also no reason to convert chars to strings.



private static void permutate2(char[] letters, boolean[] used, int numUsed, StringBuilder builder) {
if (used.length == numUsed) {
System.out.println(builder);
return;
}

for (int i = 0; i < used.length; i++) {
if (used[i]) {
continue;
}

char current = letters[i];

used[i] = true;
builder.append(current);
permutate2(letters, used, numUsed + 1, builder);
used[i] = false;
builder.setLength(builder.length() - 1);
}

}





share|improve this answer









$endgroup$













    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    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: "196"
    };
    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: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    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
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215425%2fpermutation-and-subsequences-of-string%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2












    $begingroup$

    The question states you get one line but you operate on a list of strings.



    Don't use end-of-line comments. They're hard to read and impossible to format.



    Permutations can be generated with a simple recursive divide-and-conquer algorithm:




    1. If string length is 1, there is only one permutation.

    2. For each character in the string


      1. Swap character and the first one

      2. Generate permutations for substring after first character




    You need to pass the string, the index of the start of the substring and a collection where you collect the results through the recursions.






    share|improve this answer









    $endgroup$













    • $begingroup$
      Sorry, I don't really understand what you meant by swapping character and the first one in ur pseudocode, can you illustrate with the test case?
      $endgroup$
      – Prashin Jeevaganth
      Mar 15 at 10:53


















    2












    $begingroup$

    The question states you get one line but you operate on a list of strings.



    Don't use end-of-line comments. They're hard to read and impossible to format.



    Permutations can be generated with a simple recursive divide-and-conquer algorithm:




    1. If string length is 1, there is only one permutation.

    2. For each character in the string


      1. Swap character and the first one

      2. Generate permutations for substring after first character




    You need to pass the string, the index of the start of the substring and a collection where you collect the results through the recursions.






    share|improve this answer









    $endgroup$













    • $begingroup$
      Sorry, I don't really understand what you meant by swapping character and the first one in ur pseudocode, can you illustrate with the test case?
      $endgroup$
      – Prashin Jeevaganth
      Mar 15 at 10:53
















    2












    2








    2





    $begingroup$

    The question states you get one line but you operate on a list of strings.



    Don't use end-of-line comments. They're hard to read and impossible to format.



    Permutations can be generated with a simple recursive divide-and-conquer algorithm:




    1. If string length is 1, there is only one permutation.

    2. For each character in the string


      1. Swap character and the first one

      2. Generate permutations for substring after first character




    You need to pass the string, the index of the start of the substring and a collection where you collect the results through the recursions.






    share|improve this answer









    $endgroup$



    The question states you get one line but you operate on a list of strings.



    Don't use end-of-line comments. They're hard to read and impossible to format.



    Permutations can be generated with a simple recursive divide-and-conquer algorithm:




    1. If string length is 1, there is only one permutation.

    2. For each character in the string


      1. Swap character and the first one

      2. Generate permutations for substring after first character




    You need to pass the string, the index of the start of the substring and a collection where you collect the results through the recursions.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 15 at 10:47









    TorbenPutkonenTorbenPutkonen

    35718




    35718












    • $begingroup$
      Sorry, I don't really understand what you meant by swapping character and the first one in ur pseudocode, can you illustrate with the test case?
      $endgroup$
      – Prashin Jeevaganth
      Mar 15 at 10:53




















    • $begingroup$
      Sorry, I don't really understand what you meant by swapping character and the first one in ur pseudocode, can you illustrate with the test case?
      $endgroup$
      – Prashin Jeevaganth
      Mar 15 at 10:53


















    $begingroup$
    Sorry, I don't really understand what you meant by swapping character and the first one in ur pseudocode, can you illustrate with the test case?
    $endgroup$
    – Prashin Jeevaganth
    Mar 15 at 10:53






    $begingroup$
    Sorry, I don't really understand what you meant by swapping character and the first one in ur pseudocode, can you illustrate with the test case?
    $endgroup$
    – Prashin Jeevaganth
    Mar 15 at 10:53















    2












    $begingroup$

    Your algorithm is single threaded, and does not modify the partial solution; so you need not copy about stuff. You can instead just undo what you modified in each step, namely remove the letter you appended and mark it unused.



    There is also no reason to convert chars to strings.



    private static void permutate2(char[] letters, boolean[] used, int numUsed, StringBuilder builder) {
    if (used.length == numUsed) {
    System.out.println(builder);
    return;
    }

    for (int i = 0; i < used.length; i++) {
    if (used[i]) {
    continue;
    }

    char current = letters[i];

    used[i] = true;
    builder.append(current);
    permutate2(letters, used, numUsed + 1, builder);
    used[i] = false;
    builder.setLength(builder.length() - 1);
    }

    }





    share|improve this answer









    $endgroup$


















      2












      $begingroup$

      Your algorithm is single threaded, and does not modify the partial solution; so you need not copy about stuff. You can instead just undo what you modified in each step, namely remove the letter you appended and mark it unused.



      There is also no reason to convert chars to strings.



      private static void permutate2(char[] letters, boolean[] used, int numUsed, StringBuilder builder) {
      if (used.length == numUsed) {
      System.out.println(builder);
      return;
      }

      for (int i = 0; i < used.length; i++) {
      if (used[i]) {
      continue;
      }

      char current = letters[i];

      used[i] = true;
      builder.append(current);
      permutate2(letters, used, numUsed + 1, builder);
      used[i] = false;
      builder.setLength(builder.length() - 1);
      }

      }





      share|improve this answer









      $endgroup$
















        2












        2








        2





        $begingroup$

        Your algorithm is single threaded, and does not modify the partial solution; so you need not copy about stuff. You can instead just undo what you modified in each step, namely remove the letter you appended and mark it unused.



        There is also no reason to convert chars to strings.



        private static void permutate2(char[] letters, boolean[] used, int numUsed, StringBuilder builder) {
        if (used.length == numUsed) {
        System.out.println(builder);
        return;
        }

        for (int i = 0; i < used.length; i++) {
        if (used[i]) {
        continue;
        }

        char current = letters[i];

        used[i] = true;
        builder.append(current);
        permutate2(letters, used, numUsed + 1, builder);
        used[i] = false;
        builder.setLength(builder.length() - 1);
        }

        }





        share|improve this answer









        $endgroup$



        Your algorithm is single threaded, and does not modify the partial solution; so you need not copy about stuff. You can instead just undo what you modified in each step, namely remove the letter you appended and mark it unused.



        There is also no reason to convert chars to strings.



        private static void permutate2(char[] letters, boolean[] used, int numUsed, StringBuilder builder) {
        if (used.length == numUsed) {
        System.out.println(builder);
        return;
        }

        for (int i = 0; i < used.length; i++) {
        if (used[i]) {
        continue;
        }

        char current = letters[i];

        used[i] = true;
        builder.append(current);
        permutate2(letters, used, numUsed + 1, builder);
        used[i] = false;
        builder.setLength(builder.length() - 1);
        }

        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 15 at 12:53









        abuzittin gillifircaabuzittin gillifirca

        5,992924




        5,992924






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • 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.


            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215425%2fpermutation-and-subsequences-of-string%23new-answer', 'question_page');
            }
            );

            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







            Popular posts from this blog

            is 'sed' thread safeWhat should someone know about using Python scripts in the shell?Nexenta bash script uses...

            How do i solve the “ No module named 'mlxtend' ” issue on Jupyter?

            Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...