Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplifying Scala expression calculating ratio

I'm trying to calculate the aspect ratio of a java.awt.Rectangle in Scala. I'm going for the "ratio of longer side to shorter side" definition of aspect ratio, not the "width to height" type of aspect ratio.

The following code works, but is there any way to avoid temporary variable and turn it into a one-liner?

val sizes = Seq(rect.getWidth, rect.getHeight)
val aspectRatio = sizes.max / sizes.min
like image 721
My other car is a cadr Avatar asked Oct 29 '14 06:10

My other car is a cadr


2 Answers

You don't have to create sequence to compute min and max values. You can use Math methods instead

Math.max(rect.getWidth, rect.getHeight) / Math.min(rect.getWidth, rect.getHeight)
like image 109
rtruszk Avatar answered Sep 30 '22 13:09

rtruszk


An approach, assuming only two values are added to the sequence,

Seq(rect.getWidth, rect.getHeight).sorted.reverse.foldRight(1.0)( _ / _ ) 

The code you propose is more readable though, and lesser prone to errors, at most division by zero would need some care.

like image 36
elm Avatar answered Sep 30 '22 13:09

elm