• + 0 comments
    public static String encryption(String s) {
            // Remove spaces from the string
            s = s.replaceAll("\\s", "");
            int length = s.length();
    
            // Determine grid dimensions
            int floor = (int) Math.floor(Math.sqrt(length));
            int ceil = (int) Math.ceil(Math.sqrt(length));
    
            // Adjust rows and columns based on calculated dimensions
            int rows = floor;
            int columns = ceil;
            if (rows * columns < length) {
                if (ceil * ceil >= length) {
                    rows = ceil;
                    columns = ceil;
                } else if (ceil * floor >= length) {
                    rows = ceil;
                }
            }
    
            StringBuilder encrypted = new StringBuilder();
            // Construct column-wise encryption
            for (int col = 0; col < columns; col++) {
                for (int row = 0; row < rows; row++) {
                    int index = row * columns + col;
                    if (index < length) {
                        encrypted.append(s.charAt(index));
                    }
                }
                if (col < columns - 1) {
                    encrypted.append(' ');
                }
            }
    
            return encrypted.toString();
        }
    
    }