If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Friday, July 5, 2013

Fun exercices Scala vs Java

import scala.math.pow
object StringUtils {
/**
*
* @param source
* @param char
* @param interval
* @return a new string with char c appended after each interval of characters
*/
def interleave(source: String, char:Char, interval: Int): String = {
if (source.length < interval + 1) source
else source.take(interval).concat(String.valueOf(char)
.concat(interleave(source.drop(interval), char, interval)))
}
/**
*
* @param source
* @return a Double representation of a binary string
*/
def binaryString2Double(source: String): Double = {
source.reverse.map(c => Integer.valueOf(String.valueOf(c)))
.zipWithIndex.map(zipped => zipped._1 * pow(2, zipped._2)).sum
}
}
view raw gistfile1.scala hosted with ❤ by GitHub

import static java.lang.Math.pow;
public class JavaStringUtils {
/**
*
* @param source
* @param c
* @param interval
* @return a new string with char c appended after each interval of characters
*/
public static String interleave(String source, char c, int interval) {
return
source.length() < interval + 1
? source
: source.substring(0, interval).concat(String.valueOf(c))
.concat(interleave(source.substring(interval), c, interval));
}
/**
*
* @param source
* @return a Double representation of a binary string
*/
public static Double binaryString2Double(String source) {
Double result = 0D;
int length = source.length();
for (int index = length - 1; index > -1; index--) {
int numAtIndex = Integer.valueOf(String.valueOf(source.charAt(index)));
result = result + numAtIndex * pow(2, index);
}
return result;
}
}
view raw gistfile1.java hosted with ❤ by GitHub

No comments:

Post a Comment