Home > Software design >  Print max values of four integer types: Int, Long, Short, and Byte in ascending order. Output each v
Print max values of four integer types: Int, Long, Short, and Byte in ascending order. Output each v

Time:04-09

How can I make this better?

This is a challenge that worked but i was wondering if it could be even simpler.

val int = Int.MAX_VALUE.toLong()
val long = Long.MAX_VALUE
val short = Short.MAX_VALUE.toLong()
val byte = Byte.MAX_VALUE.toLong()

val array = mutableListOf(byte, int, long, short)
var temp: Long?

for (i in 1..array.size) {
    temp = array.minOrNull()
    println(temp)
    array.removeAt(array.indexOf(temp))
}

CodePudding user response:

val int = Int.MAX_VALUE.toLong()
val long = Long.MAX_VALUE
val short = Short.MAX_VALUE.toLong()
val byte = Byte.MAX_VALUE.toLong()

//Creates a sequence and then sorts it by the number(ascending)
//Then it loops and prints each number
sequenceOf(byte, int, long, short).sortedBy { it }.forEach {
    println(it)
}

CodePudding user response:

Here's a shorter variation on AzureStar123's answer:

listOf(Int.MAX_VALUE, Long.MAX_VALUE, Short.MAX_VALUE, Byte.MAX_VALUE)
    .map{ it.toLong() }
    .sorted()
    .forEach{ println(it) }

This uses a List, which is likely to be a little more efficient than a Sequence (as well as saving a few characters). However, you don't need to modify the resulting list; you can just iterate through it.

It avoids the separate variables by using the constants directly in the list constructor. It avoids multiple calls to toLong() with a single map(). And because the resulting element type has a natural order, you can simply call sorted() on it.

(Of course, the mapping wouldn't be needed if the common Number superclass itself had a natural order… It really is a pretty useless class!) 

  • Related