Posts

Showing posts from July, 2018

Multiply Characters in a String

Image
Write method to make decryption for the String as the following: Input: a8b2mBa3d9x7uA Output: aaaaaaaabbmmmmmmmmmmmaaadddddddddxxxxxxxuuuuuuuuuu Let's first see how this problem can be solved using Groovy before we get to Java. We shall create a method that takes in a string as input and returns the desired string.  Our first attempt fails because there is something somehow subtle in the input string -the numbers are given in hexadecimal format, that is base 16. We definitely have to modify the algorithm. We have to change the way we are converting Strings to integers.  And it works! Next we should move on to the implementation in Java.  public class HelloWorld { public static void main ( String [] args ){ System . out . println ( transform ( "a8b2mBa3d9x7uA" ) ); } public static String transform ( String str ){ String toReturn = "" ; String letter = "...

Counting Characters in a String using Java

Write a program that coverts input like "aaaaabbccc" to output: a5b2c3 Using functional programming the solution to this problem is trivial. See for example the solution in Groovy: input = "aaaaabbccc" println input. toList (). countBy {it}. collect {it. key + it. value }. join () However, the solution using procedural programming is not as straightforward especially if you don't want to use utility classes like List and maps or dictionaries. Look for example at the the following solution in Java. package realcodeexamples ; /** * * @author Trevor Sinkala */ public class RealCodeExamples { /** * @param args the command line arguments */ public static void main ( String [] args ) { System . out . println ( countChars ( "aaaaaaaaabbcc" )); } public static String countChars ( String input ) { String [] arr = new String [ input . length ()]; for ( i...