Simplifying Scala expression calculating ratio
Asked Answered
Y

3

5

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
Yarber answered 29/10, 2014 at 6:57 Comment(0)
F
8

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.

Felike answered 29/10, 2014 at 7:7 Comment(1)
Creating sequence and doing 3 operations at it is too complicated solution to such easy task.Hyperaemia
H
20

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)
Hyperaemia answered 29/10, 2014 at 9:9 Comment(0)
F
8

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.

Felike answered 29/10, 2014 at 7:7 Comment(1)
Creating sequence and doing 3 operations at it is too complicated solution to such easy task.Hyperaemia
L
6
val aspectRatio = if(rect.getWidth >= rect.getHeight) rect.getWidth / rect.getHeight else rect.getHeight / rect.getWidth
Lefevre answered 29/10, 2014 at 7:48 Comment(1)
It is properly formatted. Please look at the last paragraph of the style guide: docs.scala-lang.org/style/control-structures.html, "Trivial conditions". Besides, this is a really trivial task. I see no reason why we should use anything more than if/else here.Lefevre

© 2022 - 2024 — McMap. All rights reserved.