Encryption

I received a message to solve the HackerRank Encryption. If interested take a look at the requirements. I have been working with encryption for a couple decades and appreciate ciphers.

The following output was produced on the console of the Eclipse IDE using the sample inputs from the challenge:

ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots
imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau

haveaniceday
hae and via ecy

feedthedog
fto ehg ee dd

chillout
clu hlt io

The following code in Java 8 was accepted passing the thirteen test cases:

import java.util.Scanner;

public class Solution {

	/**
	 * Encrypt and return the cipher.
	 */
	static String encrypt(String plain) {
		String cipher 	= "";
		int rows 		= 0;
		int cols 		= 0;
		
		// **** ****
		
		int len 	= plain.length();
		int floor 	= (int)Math.floor(Math.sqrt(len));
		int ceiling = (int)Math.ceil(Math.sqrt(len));
	
		// **** ****
		
		for (rows = floor; rows <= ceiling && cipher.equals(""); rows++) {
			for (cols = floor; cols <= ceiling && cipher.equals(""); cols++) {
				if ((floor <= rows) && (rows <= cols) && (cols <= ceiling) && (len <= rows * cols)) {
					
					// **** ****
					
					String[][] array = new String[rows][cols];

					// *** populate the array *****
					
					for (int r = 0, i = 0; r < rows; r++) {
						for (int c = 0; (c < cols) && (i < len); c++) {
							array[r] = plain.substring(i, i + 1);
							i++;
						}
					}
					
					// **** extract the cipher from the array ****
					
					for (int c = 0; c < cols; c++) {
						for (int r = 0; r < rows; r++) {
							if (array[r] != null) {
								cipher += array[r];
							}
						}
						if (c < (cols - 1)) {
							cipher += " ";						
						}
					}
				}
			}
		}
		
		// **** return cipher ****
		
		return cipher;
	}
	
	/**
	 * Test code.
	 */
	public static void main(String[] args) {

		// **** open a scanner ****
		
		Scanner sc = new Scanner(System.in);
		
		// **** read the string to encrypt ****
		
		String plain = sc.nextLine();
		
		// **** close the scanner ****
		
		sc.close();
		
		// **** encrypt ****
		
		String cipher = encrypt(plain);
		
		// **** display the cipher ****
		
		System.out.println(cipher);
	}

}

If you have comments or questions regarding this or any other post in this blog, please do not hesitate and send me a message. Will reply as soon as possible and will not use your name unless you explicitly allow me to do so.

Regards;

John

john.canessa@gmail.com

Follow me on Twitter:  @john_canessa

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.