Skip to main content
Code Review

Return to Question

replaced http://codereview.stackexchange.com/ with https://codereview.stackexchange.com/
Source Link

I looked at this question question and thought that I could find a much simpler way of doing this, here is the criteria that was given:

Here is what I came up with: (Link to Answer Link to Answer)

I looked at this question and thought that I could find a much simpler way of doing this, here is the criteria that was given:

Here is what I came up with: (Link to Answer)

I looked at this question and thought that I could find a much simpler way of doing this, here is the criteria that was given:

Here is what I came up with: (Link to Answer)

Source Link
Malachi
  • 29k
  • 11
  • 86
  • 188

Special summation of integer array elements

I looked at this question and thought that I could find a much simpler way of doing this, here is the criteria that was given:

My current task is to find a score from an array where the highest/lowest scores have been taken away, and if the highest/lowest occur more than once (ONLY if they occur more than once), one of them can be added:

E.g. int[] scores = [4, 8, 6, 4, 8, 5]

therefore the final addition will be \$\sum{4,8,6, 5} = 23 \$.

Another condition of the task is that LINQ cannot be used, as well as any of the System.Array methods

Here is what I came up with: (Link to Answer)

static void Main(string[] args)
{
 // take an array and sum the distinct numbers
 int[] numberArray = { 4, 8, 6, 4, 8, 5 };
 int[] numberArray2 = { 4, 4, 5, 6, 8, 8 };
 Console.WriteLine(sumSpecial(numberArray).ToString());
 Console.WriteLine(sumSpecial(numberArray).ToString());
 
 Console.ReadLine();
}
static int getHighestScore(int[] integerArray)
{
 var high = 0;
 foreach (int number in integerArray)
 {
 high = high < number ? number : high;
 }
 return high;
}
static int getLowestScore(int[] integerArray)
{
 var low = int.MaxValue;
 foreach (int number in integerArray)
 {
 low = low > number ? number : low;
 }
 return low;
}
static int sumWithoutHighAndLowScores(int[] integerarray)
{
 int sum = 0;
 int high = getHighestScore(integerarray);
 int low = getLowestScore(integerarray);
 foreach (int number in integerarray)
 {
 if (number != high && number != low)
 {
 sum += number;
 }
 }
 return sum;
}
//sum of numbers using high or low only if there is a duplicate of high or low
static int sumSpecial(int[] integerArray)
{
 var sum = sumWithoutHighAndLowScores(integerArray);
 var high = getHighestScore(integerArray);
 var low = getLowestScore(integerArray);
 var highs = 0;
 var lows = 0;
 foreach (int number in integerArray)
 {
 if (number == high) { highs++; }
 if (number == low) { lows++; }
 }
 if (lows > 1) { sum += low; }
 if (highs > 1) { sum += high; }
 return sum;
}

What could be done better or more efficiently without losing the intentions of the exercise?

lang-cs

AltStyle によって変換されたページ (->オリジナル) /