The obvious way to convert the wind direction into NSWE is with a nice long switch statement. But that seemed very long winded and boring – and this is my project, I am allowed to find a more interesting way. Thanks to mathsisfun.com for their excellent content on this subject.
Starting value
A number from 0 to 360. This allows for both numbers included.
Result
A string indicating wind direction – N, NE, NW etc.
Algorithm
DirectionMap = ( 0 : “N”, 1 : “E”, 2 : “S”, 3 : “W”}
DirectionPointer = Round(Input / 45) ValA = Round to integer(DirectionPointer / 2) ValB = Absolute value of (ValA - 1) If DirectionPointer is Even Direction is DirectionMap[ValA] Else If ValB is odd Direction is DirectionMap[ValA] + DirectionMap[ValB] Else Direction is DirectionMap[ValB] + DirectionMap[ValA]
And that’s it – seems to be working correctly for two letters indicating the wind direction.
Kotlin implementation
/**
* Wind direction to string
* @param windDir Wind direction degrees
* @return A string representing wind direction
*/
fun windDirToString(windDir: Float): String {
val directionPointer = Math.round(windDir / 45).toFloat()
val valA = Math.round(directionPointer / 2f)
val valB = Math.abs(valA - 1)
if (Math.round(directionPointer) % 2 == 0) {
// wind is due something
return getWindAngleFor(valA)
} else if (valB % 2 == 1) {
return getWindAngleFor(valA) + getWindAngleFor(valB)
} else {
return getWindAngleFor(valB) + getWindAngleFor(valA)
}
}
/**
* Get wind angle for
* @param pointer A number from 0 to 3
* @return Direction as string
*/
fun getWindAngleFor(pointer: Int): String {
return when (pointer % 4) {
0 -> WeatherConstants.NORTH
1 -> WeatherConstants.EAST
2 -> WeatherConstants.SOUTH
3 -> WeatherConstants.WEST
else -> ""
}
}