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
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With