Simplified Scala Expression Evaluation Coefficient

I am trying to calculate aspect ratio java.awt.Rectanglein Scala. I use the β€œratio of long side to shorter side ” rather than the ratio of width to width.

The following code works, but is there a way to avoid a temporary variable and turn it into a single line?

val sizes = Seq(rect.getWidth, rect.getHeight)
val aspectRatio = sizes.max / sizes.min
+5
source share
3 answers

An approach that assumes that only two values ​​are added to a sequence,

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

The code you offer is more readable, although less error prone, with most divisions by zero, a little attention will be required.

+8
source

.

Math.max(rect.getWidth, rect.getHeight) / Math.min(rect.getWidth, rect.getHeight)
+20
val aspectRatio = if(rect.getWidth >= rect.getHeight) rect.getWidth / rect.getHeight else rect.getHeight / rect.getWidth
+6
source

All Articles