L
L
Luka Tarkhnishvili2016-06-02 17:59:23
C++ / C#
Luka Tarkhnishvili, 2016-06-02 17:59:23

How to write faster?

int summ = 0;
foreach (int r in new int[] { 5, -6, 2, 7, -5, 9, 1, -3 }) summ += (r < 0) ? r : 0;

how to write this expression in a simpler way (at a low level), for a lecturer who loves "everything is simple".

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
Kronic, 2016-06-02
@Zorner

Maybe so? Outline for readability

int summ = 0;
int[] massive = new int[] {5, -6, 2, 7, -5, 9, 1, -3};
foreach (int r in massive)
{
  if (r < 0)
  {
    summ += r;
  }
}

Either use Linq
int summ = (new int[] {5, -6, 2, 7, -5, 9, 1, -3}).Where(x => x < 0).Sum();

F
Fat Lorrie, 2016-06-02
@Free_ze

int result = new int[] { 5, -6, 2, 7, -5, 9, 1, -3 }.Where(i => i<0).Sum();

A
Alexey, 2016-06-02
@alsopub

foreach (int r in new int[] { -6, -5, -3 }) summ += r;

or
or I did not understand what the lecturer wants.

A
AcidBat, 2016-06-02
@AcidBat

What is there to simplify? The code itself is basically illogical. If this array is created in a loop (read, by a weak link) with previously known values, which are then simply added up by a trigger, then what's the point?
What an inadequate lecturer you have.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question