Instructions
https://www.codewars.com/kata/simple-encryption-number-1-alternating-split/train/java
Solution:
public class Kata {
private static String alternatingSplit(final String text) {
StringBuilder sb = new StringBuilder();
final int len = text.length();
final int step = len / 2;
int pos = 1;
for (int i = 0; i < step; i++) {
sb.append(text.charAt(pos));
pos += 2;
}
pos = 0;
for (int i = 0; i < step; i++) {
sb.append(text.charAt(pos));
pos += 2;
}
if (len % 2 == 1) {
sb.append(text.charAt(len - 1));
}
return sb.toString();
}
public static String encrypt(final String text, final int n) {
if (text == null || "".equals(text.trim()) || n <= 0
|| text.length() == 1) {
return text;
}
String result = text;
for (int i = 0; i < n; i++) {
result = alternatingSplit(result);
}
return result;
}
private static String restore(final String encryptedText) {
StringBuilder sb = new StringBuilder();
final int len = encryptedText.length();
final int step = len / 2;
for (int i = 0; i < step; i++) {
sb.append(encryptedText.charAt(step + i));
sb.append(encryptedText.charAt(i));
}
if (len % 2 == 1) {
sb.append(encryptedText.charAt(len - 1));
}
return sb.toString();
}
public static String decrypt(final String encryptedText, final int n) {
if (encryptedText == null || "".equals(encryptedText.trim()) || n <= 0
|| encryptedText.length() == 1) {
return encryptedText;
}
String result = encryptedText;
for (int i = 0; i < n; i++) {
result = restore(result);
}
return result;
}
}
Sample Tests:
import org.junit.Test;
import static org.junit.Assert.*;
public class ExampleTests {
@Test
public void testEncrypt() {
// assertEquals("expected", "actual");
assertEquals("This is a test!", Kata.encrypt("This is a test!", 0));
assertEquals("hsi etTi sats!", Kata.encrypt("This is a test!", 1));
assertEquals("s eT ashi tist!", Kata.encrypt("This is a test!", 2));
assertEquals(" Tah itse sits!", Kata.encrypt("This is a test!", 3));
assertEquals("This is a test!", Kata.encrypt("This is a test!", 4));
assertEquals("This is a test!", Kata.encrypt("This is a test!", -1));
assertEquals("hskt svr neetn!Ti aai eyitrsig", Kata.encrypt("This kata is very interesting!", 1));
}
@Test
public void testDecrypt() {
// assertEquals("expected", "actual");
assertEquals("This is a test!", Kata.decrypt("This is a test!", 0));
assertEquals("This is a test!", Kata.decrypt("hsi etTi sats!", 1));
assertEquals("This is a test!", Kata.decrypt("s eT ashi tist!", 2));
assertEquals("This is a test!", Kata.decrypt(" Tah itse sits!", 3));
assertEquals("This is a test!", Kata.decrypt("This is a test!", 4));
assertEquals("This is a test!", Kata.decrypt("This is a test!", -1));
assertEquals("This kata is very interesting!", Kata.decrypt("hskt svr neetn!Ti aai eyitrsig", 1));
}
@Test
public void testNullOrEmpty() {
// assertEquals("expected", "actual");
assertEquals("", Kata.encrypt("", 0));
assertEquals("", Kata.decrypt("", 0));
assertEquals(null, Kata.encrypt(null, 0));
assertEquals(null, Kata.decrypt(null, 0));
}
}