/** * Speed testing of Kotlin V2. * Close to purely functional -- really close. * Also, does not fall into speed fallacy of IntArray * @author gtowell * created:July 20, 2021 */ import java.time.LocalDateTime import java.time.Duration import kotlin.random.Random // Function programming "val is OK" // The chars used to build random strings private val charPool : List = ('a'..'z') + ('A'..'Z') + ('0'..'9') /** * A tail-recursive random string builder!! * Be sure the understand the ugly in the final return @param len the number of characters yet to add @param rtn the string to be returned, defaults to empty @return a random string of at least the given length -- will be longer (and not random) if the initially provided string is non-zero length */ tailrec fun randString (len: Int, rtn:String="") : String { if (len==0) return rtn return randString(len-1, "$rtn${charPool.get(Random.nextInt(0, charPool.size))}") } /** * The sort function is in-place and returns nothing. * This just does the sort and returns a pointer to the sorted list * @param arr the list to to be sorted. This assume that the objects * contained in the list implement comprable. * @return the list, sorted */ fun sortrtn(arr: Array) : Array { arr.sort(); return arr; } /** * A class that simply contains a string and an int. The class implements comparable on the string. */ class Strrr(val sss: String, val sii: Int) : Comparable { override fun toString(): String = "strrr ${sss}" override fun compareTo(other: Strrr): Int = this.sss.compareTo(other.sss) } /** * A class that simply contains an integer. Again, is it necessary? Not really. */ class Interr(val num: Int) : Comparable { override fun toString(): String = "INTERR ${num}" override fun compareTo(other: Interr): Int = this.num.compareTo(other.num) } // A type. I just find it easier to define a type and then use it in function params typealias WKLambda = ()->Unit; fun timer (funcc: WKLambda, nw:LocalDateTime = LocalDateTime.now()) { funcc() println("The operation took ${Duration.between(nw, LocalDateTime.now())} ms") } /** * A purely function way of printing a part of a list */ fun printt(arr : Array, lw: Int, hi:Int) { println(arr.copyOfRange(lw, hi + 1).contentToString()) } /** * Largely identical to printt, but uses an explicit loop. */ fun print3(arr : Array, lw: Int, hi:Int) { for (i in lw..hi) { println(arr.get(i)) } } @Suppress("UNUSED_PARAMETER") fun main(args: Array) { // run tests twice timer({ printt(sortrtn(Array(5000000) { Strrr(randString(10), Random.nextInt(0, 5000000)) }), 0, 3) }) timer({ printt(sortrtn(Array(5000000) { Interr(Random.nextInt(0, 5000000)) }), 0, 3) }) timer({ printt(sortrtn(Array(5000000) { Random.nextInt(0, 5000000) }), 0, 3) }) timer({ printt(sortrtn(Array(10000000) { Strrr(randString(10), Random.nextInt(0, 5000000)) }), 0, 3) }) timer({ printt(sortrtn(Array(10000000) { Interr(Random.nextInt(0, 5000000)) }), 0, 3) }) timer({ printt(sortrtn(Array(10000000) { Random.nextInt(0, 5000000) }), 0, 3) }) }