Loading collection data...
Collections are a way for you to organize kata so that you can create your own training routines. Every collection you create is public and automatically sharable with other warriors. After you have added a few kata to a collection you and others can train on the kata contained within the collection.
Get started now by creating a new collection.
"You can use if..else or ternary operator to complete it."
Ok.
This comment is hidden because it contains spoiler information about the solution
if someone new is having doubt here go read about String pool, basically in each concatenation a new string object is created and it consumes way too much memory
Ahuenno pocany
Any code monkey can do it the string way. We don't see many solutions that do it the math way. Good one!
you made me chuckle XD
lolololol
Because a String object can't be changed. In this code in the line "s+=string;" a new string is created every iteration.
can you please explain why?
Commmon man, it is a cool kata. I mentioned in the description that this kata is not about coding skill. There is a pattern in the list that should be discovered.
I appologize for wasting your time.
You are, perhaps, not familiar with how expensive sorting is. I'd pit this solution against a sorting-based solution any day.
That being said, it would probably be more performant to perform the
mapToInt
function once per array, store in an intermediate array, then get the max and min out of that one array. Shockingly, the most performant solution is probably just a single for loop per array that keeps track of both max and min as it cycles, but I bet it doesn't beat map-reduce by a human-noticeable amount, even for large datasets.If you wanted to keep the streams--which, why wouldn't you?--a similar "one stream/one loop" strategy would be to
mapToInt
,reduce
to a two-tuple with max and min, thenreduce
your two-tuple with subtraction. This kind of thing is a PITA in Java, even with streams, but trivial in a language like Scala (when, Codewars, when?)But you should never sort something just to get max and min out of it (you should sort something because you want ALL the elements in a particular order).
Edit: 2 things: apparently Codewars has Scala now, so, yay! Also, I forgot that this one has the (max of a1) - (max of a2) cross stream calculation thing going on, which invalidates my stream strategy above. But you can still do the intermediate array thing, or possibly something with combined streams. This is probably slightly more efficient than the above. But look at that verbosity!