使用java中的索引交换数字不起作用 [英] swapping of numbers using index in java is not working

查看:133
本文介绍了使用java中的索引交换数字不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    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;*/         
        }   
    }

上面的程序用于打印给定字符串的所有排列。如果我用注释中写入的逻辑替换第1,2,3行(写在注释中),则在swap()方法中实现结果(在第1,2行之后) ,3)然后回答错误。为什么会发生这种情况?

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?

推荐答案

你的错误是假设 c [x] == p c [y] == c0 。但索引 x y 派生自 immutable 字符串 s ,它不会反映其洗牌状态下 c 中的值。

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.

这篇关于使用java中的索引交换数字不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆