Home > Net >  C# how to count how many numbers in an array that are not within a specifc number
C# how to count how many numbers in an array that are not within a specifc number

Time:11-06

the input is like this 100 5 0 10 0 5 75 95 12 17 13 14 and the output is 65 so i want the program to count which numbers from 0-100 are not in the array.

this is how i started

static void Main(string[] args)
        {
            string input1 = Console.ReadLine();
            int roadlength = Convert.ToInt32(input1.Split(" ")[0]);
            int stagecnt = Convert.ToInt32(input1.Split(" ")[1]);
            int[] startpoint = new int[stagecnt];
            int[] endpoint = new int[stagecnt];
            int km = 0;

            for (int i = 0; i < stagecnt; i  )
            {
                string input2 = Console.ReadLine();
                startpoint[i] = Convert.ToInt32(input2.Split(' ')[0]);
                endpoint[i] = Convert.ToInt32(input2.Split(' ')[1]);
                
            }
            for (int i = 0; i < stagecnt; i  )
            {

CodePudding user response:

Let's count distinct numbers that are in 0..100 range and then subtract from total number in 0..100 range:

using System.Linq;

...

int[] data = new int[] {
  100, 5, 0, 10, 0, 5, 75, 95, 12, 17, 13, 14,
};

...

int min = 0;
int max = 100;

int result = max - min   1 - data
  .Where(item => item >= min && item <= max)
  .Distinct()
  .Count(); 

CodePudding user response:

you are complicating the problem, it's very simple.

Initialize an array/list with the given range. and check all your input items one by one whether they are present in the first carry. and if not present then just increment the count.

though complexity is high but its simplest solution.

int[] items = ;
int start = 1;
int end = 100;

int[] arr = Enumerable.Range(start, end - start).ToArray();
int count = 0;
for(int i = 0; i < arr.Length; i  )
{
    if (!items.Contains(arr[i]))
    {
        count  ;
    }
}
  • Related