Find all available combinations

I have one done the same with strings. However, I just swapped random digits until I get all combinations(which is the factorial of the length of the string). I then print out the non-recurring ones.

Here is how I did it, just change the String you input to the allpos() method and it will work for any number.

import java.util.Random;
import java.util.Scanner;

public class shift {

public static void main(String[] args) {

    //Change "012" to anything, even a String.
  allpos("012");
}
public static int unbin(String s){

    int ans=0;
    for(int x=0;x<s.length();x++){
        char c=s.charAt(x);
        if(c=='1'){
        ans+=Math.pow(2, s.length()-1-x);
        }

    }
    return ans;


}
public static String bin(int n){
    int[] ans=new int[32];
    int a=n;
    for(int x=31;x>=0;x--){
        if(Math.pow(2, x)<=a){
            a-=Math.pow(2, x);
            ans[x]=1;
        }
    }
    String s="";boolean zero=false;
    for(int x=ans.length-1;x>=0;x--){
        if(ans[x]==1){
            s+="1";
            zero=true;
            continue;
        }else if(zero){
            s+="0";
        }
    }
    return s;
}
public static boolean ispresent(String[] words,String s){
    for(int x=0;x<words.length;x++){
        if(words[x]==null){return false;}
        if(words[x].equals(s)){return true;}

    }
    return false;



}   
public static void allpos(String s){

    int fac=1;
    for(int x=1;x<=s.length();x++){
        fac*=x;
    }
    int len=s.length();
    String[] values=new String[fac];
    values[0]=s;
    System.out.println(s+" (1)");
    int id1=0,id2=0;
    Random r=new Random();
    for(int x=1;x<fac;){

        s=inchange(s,r.nextInt(len),r.nextInt(len));
        if(ispresent(values,s)==false){
            values[x]=s;
            x++;
            System.out.println(s+" ("+x+")");
        }

    }


}
public static String inchange(String s,int id1,int id2){
    char[] chars=new char[s.length()];
    for(int x=0;x<s.length();x++){
        chars[x]=s.charAt(x);

    }
    char temp=chars[id1];
    chars[id1]=chars[id2];
    chars[id2]=temp;
    String ans="";
    for(int x=0;x<s.length();x++){
        ans+=chars[x];

    }
    return ans;
}

}

I know that it is inefficient but it gets the job done for smaller numbers. I hope this helped.

Browse More Popular Posts

Leave a Comment