Kushagra Sinha
Kushagra Sinha

Reputation: 29

swapping of numbers using index in java is not working

    package dspermutation;

    import java.util.Scanner;

    public class DSPermutation {
        String s;
        char[] c;
        int n;

        public static void main(String[] args) {
            DSPermutation ds=new DSPermutation();
            ds.input();
        }

        private void input() {
            Scanner sc=new Scanner(System.in);
            System.out.println("Enter the string");
            s=sc.next();
            c=s.toCharArray();
            n=c.length;
            permutation(c,n-1,0);
        }

        private void permutation(char[] cc,int nn,int ii) {
            if(ii==nn)
            {
               System.out.println(cc);
            }
            else
            {
                for(int j=ii;j<=nn;j++)
                {
                    swap(cc[ii],cc[j]);
                    permutation(cc,nn,ii+1);
                    swap(cc[ii],cc[j]);
                }
            }    
        }

        private void swap(char p, char c0) {
            int x=s.indexOf(p);
            int y=s.indexOf(c0);
           /*1*/ char temp=c[x];
           /*2*/c[x]=c[y];
           /*3*/c[y]=temp;

           /*c[x]=c0;
            c[y]=p;*/         
        }   
    }

The above program is for printing all permutations of a given string.The result is coming true but in swap() method if i replace line 1,2,3(written in comment) by logic written in comment(after line 1,2,3) then answer comes wrong. Why could this be happening?

Upvotes: 2

Views: 86

Answers (2)

hiren
hiren

Reputation: 1812

You are swapping values of character array using immutable string's position (i.e String always holds the same initial values). To make your commented code work you have to add this s = String.valueOf(c);at the end of swap function.

private void swap(char p, char c0) {
    int x = s.indexOf(p);
    int y = s.indexOf(c0);

    // char temp = c[x];
    // c[x] = c[y];
    // c[y] = temp;

    c[y] = p;
    c[x] = c0;

    s = String.valueOf(c);


}

Upvotes: 0

shmosel
shmosel

Reputation: 50716

Your mistake is assuming c[x] == p and c[y] == c0. But the indexes x and y are derived from the immutable string s, which doesn't reflect the values in c in its shuffled state.

Upvotes: 2

Related Questions