# Thread: permutations - code efficiency

1. Member
Join Date
Apr 2013
Posts
15
Rep Power
0

## permutations - code efficiency

Hi all,
I'm on my learning task to find all possible permutations. It works fine for short strings, but tooks too long for longer strings. Basically, my approach is to randomize string, add results to the list and then get rid of duplicates in the list. Please help me to improve code efficiency. Just to clarify, finally I should return middle result for even length of input string or length/2 for odd one (this part is ok, just to let you know what my code does).

Java Code:
```package learn;

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class simpleFun159MiddlePermutation {

public static String findMidPerm(String strng) {
// your code here!
String result = "";
List<String> mylist = new ArrayList<>();

int i = 0;
while (true){
List<Character> characters = new ArrayList<Character>();
for(char c:strng.toCharArray()){
}
StringBuilder output = new StringBuilder(strng.length());
while(characters.size()!=0){
int randPicker = (int)(Math.random()*characters.size());
output.append(characters.remove(randPicker));
}
//System.out.println(output.toString());
i = i + 1;
if (i>50000000){break;}
}
Set<String> hs = new HashSet<>();
mylist.clear();
Collections.sort(mylist);
//System.out.println(mylist);
//System.out.println(mylist.size());
int myindex = 0;
if ( (myindex & 1) == 0 ) { myindex = (mylist.size() / 2)-1; } else { myindex = (mylist.size() / 2); }
//System.out.println(mylist.get(myindex));
result = mylist.get(myindex);
return result;
}

public static void main(String[] args) {
String s = "abc";
//String s = "wulaydcrjhzt";
System.out.println(findMidPerm(s));
}
}```
Last edited by marchello; 10-01-2018 at 09:11 PM.

2. ## Re: permutations - code efficiency

Search this forum for 'permutation'. we're babbling a lot about it as well as` 'combinations'.

kind regards,

Jos
Last edited by JosAH; 10-05-2018 at 05:02 PM.

3. Member
Join Date
Apr 2013
Posts
15
Rep Power
0

## Re: permutations - code efficiency

Hi Jos,

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•