• + 0 comments

    Java solution

        public static String encryption(String s) throws IOException {
            String output = "";
            //empty string
            if (s.isEmpty()) return output;
            //Remove spaces
            s = s.replaceAll("\\s+", "");
            //Calculate square root of message length
            double sqroot = Math.sqrt(s.length());
            int cols = (int) Math.ceil(sqroot);
            int rows = (int) Math.floor(sqroot);
            if(cols*rows < s.length()) rows++;
            String subtmp;
    
            int reminder ;
            List<String> finList = new ArrayList<>();
            //iterate over string
            for (int i = 0; i < s.length(); i ++) {
                reminder = i % cols;
                if(finList.size()==cols) {
                    subtmp = finList.get(reminder);
                    subtmp=subtmp.concat(String.valueOf(s.charAt(i)));
                    finList.set(reminder, subtmp);
                }else {
                    finList.add(reminder, String.valueOf(s.charAt(i)));
                }
    
            }
    
            for (String st: finList) {
                output += st+" ";
            }
            return output.trim();
        }