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 1 S m l e t
Row 2 i p e t x

So the result string will be: "Sml etipetx"

The solution in Java code

Option 1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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));
    }
}