1. 程式人生 > >我的Java學習-約瑟夫環和密碼

我的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);
     }
 }