Skip to content

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.


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=; i<text.length(); i++) { if (i%2 == ) left+=text.charAt(i); else right+=text.charAt(i); } return left+right; } }
Code language: Java (java)

Option 2:

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

Option 3:

import; import; public class Solution { public static String simpleTransposition(String text) { String[] letters = text.split(""); String firstRow = IntStream.range(, letters.length) .filter(i -> i % 2 == ) .mapToObj(i -> letters[i]) .collect(Collectors.joining()); String secondRow = IntStream.range(, letters.length) .filter(i -> i % 2 != ) .mapToObj(i -> letters[i]) .collect(Collectors.joining()); return firstRow + secondRow; } }
Code language: Java (java)

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)); } }
Code language: Java (java)

See also  How to Clone a Graph in Java
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x