'Finding the middle number in an array; I understand how to do it but can't make it work. :/ (Coral)
Although my code works, it's not the way the question wants it to be solved and I'd like to know the correct way.
The question is:
Given a sorted list of integers, output the middle integer. Assume the number of integers is always odd.
Ex: If the input is 2 3 4 8 11 -1 (a negative indicates end), the output is:
4 The maximum number of inputs for any test case should not exceed 9 positive values. If exceeded, output "Too many inputs".
Hint: Use an array of size 9. First, read the data into an array. Then, based on the number of items, find the middle item.
My code:
integer userInput
integer i
integer mid
integer array(20) number
userInput = 1
for i = 0; userInput >= 0; i = i + 1
if number[i] > -1
userInput = Get next input
number[i] = userInput
i = i - 1
mid = i / 2
if i > 9
Put "Too many inputs" to output
elseif i % 2 == 0
Put number[mid - 1] to output
else
Put number[mid] to output
The problem states that the array has to be configured to a size of 9 but with 9 or 10, the program fails and I don't know why so I set it to 20 out of frustration. I've tried this problem multiple other ways like using a while loop
while number[i] > -1
but for some reason that causes it to never end even though each set of inputs does have a -1 in it. There are other ways I've forgotten but which resulted in an output of -1000000000 instead of any of the actual numbers. I'm at a loss but at least I got it working to some degree.
I asked my teacher for help and all he said was: "Your difficulty relates to your "logic" in setting up and using the array. Try starting over, from scratch"
I've started from scratch about a dozen times and I'm not seeing what he's saying. Is there some way to set up an array in Coral that I'm unaware of?
Solution 1:[1]
The program fails because they mandate you need to set the array to 9. However, they sneakily input the negative number that should stop the program as the 10th input, which would act outside the array range of 9.
So the best thing to do is to set the array to the next highest odd integer: 11
Just change this line:
integer array(20) number to integer array(11) number
Solution 2:[2]
In case anyone else runs across this, I myself was also at the mercy of being too complex with this particular one. Here is the Coral program for this one that passed all 10 tests
Submission passed all tests Total score: 10 / 10
integer userInts
integer i
integer mid
integer array(9) n
userInts = Get next input
while (userInts >=0) and (i < n.size)
n[i] = userInts
userInts = Get next input
i = i + 1
if userInts >=0
Put "Too many inputs" to output
else
mid = i / 2
Put n[mid] to output
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dropkicklippy |
| Solution 2 | user17812885 |
