Write a function that calculates body mass index
Note: bmi = weight / height ^ 2
if bmi <= 18.5 return "Underweight"
if bmi <= 25.0 return...
For further actions, you may consider blocking this person and/or reporting abuse
LabVIEW: ;)
Awesome, haven't seen LabVIEW since I was at uni.
Well, I tried something different:
Apart from being ugly, it works like this:
t=[18.5,25,30]
k=['Underweight','Normal','Overweight']
t.find(v=>w/(h^2)<=v)
. For example, it will return25
if the processed BMI is between 18.5 and 25.t.indexOf(...)
, in order to get the same element in the label array:k[...]
. For example, if25
is returned, it will fetchk[1]
, hence"Normal"
"Obese"
That is an interested method, but come back at your code in a few months with absolutely no explanation and I do think that it is not going to be that easy.
I think that a code should be self explanatory (especially to newcomers on your codebase) and, even if this one is a tour-de-force in terms of one-liner, it is not self explanatory. 😉
That is why, I would find that a switch case method would be better.
I completely agree with you on this one! (Hi fellow french dev!) I tend to try to golf a lot in these challenges, even though I completely agree on the fact that it's as ugly as it can be. That way, I can discover new principles (like the
reduce
method, that I hated a few months back even if it is really useful) that I can later use on my projects or at work.Indeed, this challenge was clearly made for a switch/case solution, but as I had some free time I though I could try something different haha
I like it!
Haskell
I couldn't resist posting a quick JavaScript solution... 😀
Might propose a change? Instead of underweight, overweight, obsese, etc, how about we replace the return values with "no idea, consult a health professional and have your body composition correctly measured"? It will be significantly more accurate! :D
Something like:
I concur with this response.
This seems to do the job
C++:
Rust:
Let's say you need to run this a few billion times times, then a more complex look up table approach might be worth it.
(in JS because I like it, and I find it can be nice to mock up performance code in a slowish language first up.)
Have you tested if your code is faster than a simpler conditional version (as most other solutions are written)?
Fair point Craig, in this case it turns out to be a bunch slower due to the complexity in
indexFromBmi
.I just figured it was worth posting as an alternative approach as there are problems where luts are gold. In this case apparently not.
I'd say that here it's best to just use
and be done with it.
I did two functions, one that expects imperial units (Go America!) and one that expects metric units (the rest of the world!).
body.go
body_test.go
A solution in gwion
Scala:
[gist.github.com/devparkk/9117b0780...]