All 4 digit combinations
Hello all I recently found a piece of code here I altered it slightly to serve my purpose.
I want it to list out all possible combinations of 4 numbers out of from 0 to 9. The code below will do this but the problem is it repeats the same combinations over and over. Can anyone alter the code to just print each 4 digit combinatin once.
public class Test3 {
public static void main(String[] args) {
int arr[] = {0,1, 2, 3, 4,5,6,7,8,9};
int a[]={1};
printPermutations(new int[0],arr);
int i=0;
}
static void printPermutations(int soFar[], int someArray[]){
int i = 0;
if(someArray.length == 0) {
int j = 0;
for(int ndx = 0; ndx < 4; ndx++) {
System.out.print(soFar[ndx] );
}
System.out.println("****");
return;
}
for(int ele = 0; ele < someArray.length; ele++) {
int newSoFar[] = new int[soFar.length + 1];
for(int ndx = 0; ndx < soFar.length; ndx++) {
newSoFar[ndx] = soFar[ndx];
}
newSoFar[newSoFar.length - 1] = someArray[ele];
int subArray[] = new int[someArray.length - 1];
for(int ndx = 0; ndx < someArray.length; ndx++) {
if(ndx < ele) subArray[ndx] = someArray[ndx];
if(ndx > ele) subArray[ndx - 1] = someArray[ndx];
}
printPermutations(newSoFar, subArray);
}
}
}
bert.
[1407 byte] By [
berta] at [2007-10-2 13:56:24]

final static NumberFormat number = new DecimalFormat("0000");
public static void main(String[] args) throws Exception {
for (int i = 0; i <= 9; i++) {
int output=i;
for (int j = 0; j <= 9; j++) {
if (i == j) {
continue;
}
output=output*10+j;
for (int k = 0; k <= 9; k++) {
if (k == j|| k==i) {
continue;
}
output=output*10+k;
for (int l = 0; l <= 9; l++) {
if (k == l || l==j || l==i) {
continue;
}
output=output*10+l;
System.out.println(number.format(output));
output/=10;
}
output/=10;
}
output/=10;
}
output/=10;
}
}
> > Horrendous... I love it :-D
>
> Yes, I agree :-)
I don't think that the algorithm does what is required. It just prints out all numbers from 0000 to 9999.
The following is a recursive way to solve the "taking 4 from 9" problem:
public class Permutation
{
private int maxDepth = 3;
public void take(char[] array,BitSet occupied,int depth,String print)
{
for(int i=0;i<array.length;++i)
{
if (occupied.get(i)==false)
{
if (depth><maxDepth)
{
occupied.flip(i);
take(array,occupied,depth+1,print+array[i]);
occupied.flip(i);
}
else
{
System.out.println(print+array[i]);
}
}
}
}
/**
* @param args
*/
public static void main(String[] args)
{
char[] array = new char[]{'0','1','2','3','4','5','6','7','8','9'};
BitSet bs = new BitSet();
Permutation t = new Permutation();
t.take(array,bs,0,"");
}
}
It should give you the following:
0123
0124
0125
0126
0127
0128
0129
0132
0134
0135
...
9872
9873
9874
9875
9876
>