I want to get 4 random numbers. The numbers will be between 1-6. I want
to disregard the smallest number and add the three biggest numbers
together. So far I wrote some ruby that I thought would do this but I
keep getting an error.
It would be easier for others to help you if you included the actual
error message you get in addition to the code that purportedly produced
the error. Not everyone seeing your post has the ability (that’s me at
the moment) or desire to copy and paste your code, but they may be able
to help anyway with the error message in hand.
On Sat, Feb 4, 2012 at 9:43 AM, h4y4shi 13bladex [email protected] wrote:
I want to get 4 random numbers. The numbers will be between 1-6. I want
to disregard the smallest number and add the three biggest numbers
together. So far I wrote some ruby that I thought would do this but I
keep getting an error.
This is a different approach but if it doesn’t work, I think it is
easier to fix errors if you have them because it is short and easier
to read.
Once you have your random numbers try something like this.
arr = [2,4,1,5]
p arr.sort[1…-1].inject{|a,b| a+b}
On Sat, Feb 4, 2012 at 9:43 AM, h4y4shi 13bladex [email protected] wrote:
I want to get 4 random numbers. The numbers will be between 1-6. I want
to disregard the smallest number and add the three biggest numbers
together. So far I wrote some ruby that I thought would do this but I
keep getting an error.
If you don’t like inject, this is even shorter and easier to understand.
It’s not very flexible but…
If you always have 4 numbers and always want to add the largest 3
numbers,
Hi, lots of problems here, to the point where it’s very unclear where to
even begin identifying them. I recommend you start with something simple
that you can prove works to a given point (e.g. initializing the
variables)
then slowly build onto it (e.g. find the largest, second largest, third
largest, and then their sum. This is very doable iteratively.
In the end, I think Harry’s solution is best (except both array indexes
should count from the end so that it works for any given array of
numbers).
But since you’re clearly struggling with something considerably simpler
than that, it’s probably best to see this idea through to the end in
order
to build up your knowledge and problem solving abilities. Then later,
learn
more about the fancy built in methods around enumerable classes.