我的Java学习-约瑟夫环和密码

有这样个问题,对字符串进行加密,形成密文,假设原文是abcdefg,加密后形成的密文s1s2s3s4s5s6s7。
读入一个正整数大于1,作为加密钥匙key,将原字符串按顺时针方向连成一个环,当数到第key个字符位置时,将原文中的字符放入密文字符,同时从原文里除去字符位置,从原文下一个字符位置开始计算,再数到key位置时,将原文中字符放入密文,直至全部放入密文。
这个问题其实是约瑟夫环的简化版本,里面的密钥key是固定不变的,简化了问题的难度。
看到这个问题的第一眼,我感觉,用循环链表应该是最好解决的办法了,循环链表嘛,可以循环,不然怎么解决计数的问题呢,于是我开始用循环链表。但是的但是,没有解决。各种问题接踵而来,总是有问题,我感觉到或许是我的链表结构有问题,于是我用java自带的ArrayList,还是有问题。头发都掉了很多根的样子,最后只有翻书看看。
约瑟夫环的编程里面有这个

for(int i = 1; i <= size; i++){
	index = (--index + password) % circle.size();
	circle.remove(index);
}

原来,这个位置的定位是需要计算出来的,不是依靠链表的数据结构来解决。果然,程序= 数据结构+ 算法。
还有,里面有String到Character类型的转换,也有Character到String类型的转换。前面的比较简单,s.charAt()方法可以实现。后面的也是各种找资料,发现用String s = “”; s += char;的办法比较方便。

class Code{                           //与密码处理有关的方法在code类里面实现
    private String origcode;
    private int key;
    private ArrayList<Character> list ;
    public Code(String origcode, int key){
        this.origcode = origcode;
        this.key = key;        
    }
    
    public String ciperCode(){
        String result = "";
        if(key <= 1){
            result = null;
            return result;
        }else{
            list = new ArrayList<Character>();
            int index = key;
            for(int i = 0; i < origcode.length(); i++){
                list.add(origcode.charAt(i));              
            }
            
            for(int j = 0; j < origcode.length(); j++){
                index = ( --index + key) % list.size();  //计算当前index的大小
                result += list.remove(index);
            }                     
        }        
        return result;
    }        
}

//编制程序对上面实现进行测试
public class Data{
    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);
        System.out.println("请输入需要加密的英文原文:");
        String origcode = sc.nextLine();
        System.out.println("请输入一个大于1的整型数字作为密钥:");
        int key = sc.nextInt();
        
        Code code = new Code(origcode, key);
        String result = code.ciperCode();
        System.out.println("您输入的原文是: " + origcode);
        System.out.println("加密后的密文是: " + result);
     }
 }

猜你喜欢

转载自blog.csdn.net/qq_43399072/article/details/83065012