# Solving Simple Transposition in Java

## The challenge

Simple transposition is a basic and simple cryptography technique. We make 2 rows and put first a letter in Row 1, the second in Row 2, third in Row 1, and so on until the end. Then we put the text from Row 2 next to the Row 1 text and that’s it.

Complete the function that receives a string and encrypts it with this simple transposition.

Example:

For example, if the text to encrypt is: `"Simple text"`, the 2 rows will be:

Row 1Smlet
Row 2ipetx

So the result string will be: `"Sml etipetx"`

## The solution in Java code

Option 1:

``````public class Solution {
public static String simpleTransposition(String text) {
String right = "";
String left = "";
for (int i=0; i<text.length(); i++) {
if (i%2 == 0) left+=text.charAt(i);
else right+=text.charAt(i);
}
return left+right;
}
}
``````

Option 2:

``````public class Solution {
public static String simpleTransposition(String text) {
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
for(int i = 0; i < text.length(); ++i)
if(i % 2 == 0) sb1.append(text.charAt(i));
else sb2.append(text.charAt(i));
return sb1.append(sb2).toString();
}
}
``````

Option 3:

``````import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Solution {
public static String simpleTransposition(String text) {
String[] letters = text.split("");

String firstRow = IntStream.range(0, letters.length)
.filter(i -> i % 2 == 0)
.mapToObj(i -> letters[i])
.collect(Collectors.joining());
String secondRow = IntStream.range(0, letters.length)
.filter(i -> i % 2 != 0)
.mapToObj(i -> letters[i])
.collect(Collectors.joining());

return firstRow + secondRow;
}
}
``````

## Test cases to validate our solution

``````import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SampleTest {
@Test
public void basicTest() {
doTest("Sample text", "Sml etapetx");
doTest("Simple transposition", "Sml rnpstoipetasoiin");
doTest("All that glitters is not gold", "Alta ltesi o odl htgitr sntgl");
doTest("The better part of valor is discretion", "Tebte ato ao sdsrtoh etrpr fvlri icein");
doTest("Conscience does make cowards of us all", "Cncec osmk oad fu losinede aecwrso sal");
doTest("Imagination is more important than knowledge", "Iaiaini oeipratta nwegmgnto smr motn hnkolde");
}
private void doTest(String text, String expected) {
assertEquals(expected, Solution.simpleTransposition(text));
}
}
``````