Encryption

An English text needs to be encrypted using the following encryption scheme.
First, the spaces are removed from the text. Let  be the length of this text.
Then, characters are written into a grid, whose rows and columns have the following constraints:
For example, the sentence , after removing spaces is  characters long.  is between  and , so it is written in the form of a grid with 7 rows and 8 columns.
ifmanwas  
meanttos          
tayonthe  
groundgo  
dwouldha  
vegivenu  
sroots
static String encryption(String s) {
        int totalChar = 0;
        String finalString = "";
        for(int i=0;i<s.length();i++){
            if((int)s.charAt(i) != 32){
                totalChar +=1;
            }
        }
        int sqrRoot = (int) Math.sqrt(totalChar);
        int result = sqrRoot * sqrRoot;
        int row = 0;
        int columns = 0;
        if(totalChar == result){
            row = sqrRoot;
            columns = sqrRoot;
        }else{
            row = sqrRoot;
            columns = sqrRoot+1;
        }
        //System.out.println(row+" "+columns);
        if(totalChar > row*columns) {
         row = columns;
        }
        //System.out.println(row+" "+columns);
        String st = "";
        int counter = 0;
        for(int i=0;i<s.length();i++) {
         if(counter<columns) {
          st +=s.charAt(i);
          counter++;
         }else {
          st += " ";
          counter = 0;
          i--;
         }
        }
        String[] strArr = st.split("\\s");
        //System.out.println(st+" "+Arrays.toString(strArr));
        for(int i=0;i<columns;i++) {
         for(int j=0;j<strArr.length;j++) {
          String ss = strArr[j];
          if(i<ss.length()) {
           //System.out.println(strArr[j].charAt(i));
           finalString += strArr[j].charAt(i);
          }
          
        }
         finalString += " ";
        }
        //System.out.println(finalString);
        return finalString;

    }



Post a Comment

Previous Post Next Post