Is there a simpler way to do this?

  • (2 Pages)
  • +
  • 1
  • 2

25 Replies - 936 Views - Last Post: 20 June 2013 - 11:22 AM Rate Topic: -----

#1 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Is there a simpler way to do this?

Posted 18 June 2013 - 01:48 PM

I have spent the last few hours doing each challenge in my book up to the chapter I am currently on. I figure this is probably the best way to give myself a refresher of what I have already learned. So, each chapter I finish from this point forward I'm going to go back and do every challenge again until I can do them without looking at any hints.

Which brings me to this next question.

The challenge has asked me to write a program that asks the user for 10 numbers, which are to be stored in an array. The program then asks the user for one last number, and then the program will check to see how many times that number is in the array.

Here is my code:

            int[] numbers = new int[10];
            Console.WriteLine("Please enter 10 numbers:\n");
            for (int x = 0;x < 10; x++)
            {
                Console.Write("#{0}: ", x + 1);
                numbers[x] = int.Parse(Console.ReadLine());
            }
            Console.Clear();
            int num2;
            int num3 = 0;
            Console.Write("Please enter one more number: ");
            num2 = int.Parse(Console.ReadLine());
            bool exists = numbers.Contains(num2);
            if (exists)
            {
                for (int x = 0; x < 10; x++)
                {
                    if (num2 == numbers[x])
                    {
                        num3++;
                    }
                }
                Console.WriteLine("{0} is in the array!!{0} appears in the array {1} time(s).", num2, num3);
            }
            else
            {
                Console.WriteLine("That number is not in the array!");
            }           
            Console.ReadLine();


With a lot of the programs I have been asked to write, I've been over complicating things with a few of them. In fact, there are probably simpler ways to do all of the challenges I have done so far.

Is there a much simpler way of doing this particular program? I'd love to see some other ways, if there are any. I just have this feeling that I'm trying to make it harder on myself than it has to be.

Is This A Good Question/Topic? 0
  • +

Replies To: Is there a simpler way to do this?

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10397
  • View blog
  • Posts: 38,479
  • Joined: 27-December 08

Re: Is there a simpler way to do this?

Posted 18 June 2013 - 01:59 PM

Since you're using arrays, that's probably as simple as you're going to get. If you used a Dictionary, you could relate numbers and their frequencies as key-value pairs. Then you would just look-up the key and get its frequency.
Was This Post Helpful? 1
  • +
  • -

#3 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Re: Is there a simpler way to do this?

Posted 18 June 2013 - 02:05 PM

View Postmacosxnerd101, on 18 June 2013 - 01:59 PM, said:

Since you're using arrays, that's probably as simple as you're going to get. If you used a Dictionary, you could relate numbers and their frequencies as key-value pairs. Then you would just look-up the key and get its frequency.


Appreciate the feedback. I just had this bad feeling that I was over doing it or wasn't seeing an option that may have been right in front of me.

I'm always looking for simpler ways to do things, but I need to understand how things function before I go after shortcuts.
Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10397
  • View blog
  • Posts: 38,479
  • Joined: 27-December 08

Re: Is there a simpler way to do this?

Posted 18 June 2013 - 02:07 PM

This is a fairly standard introductory exercise. You're doing good here. :^:
Was This Post Helpful? 0
  • +
  • -

#5 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3253
  • View blog
  • Posts: 10,908
  • Joined: 12-December 12

Re: Is there a simpler way to do this?

Posted 18 June 2013 - 02:13 PM

There are always different ways, particularly when LINQ lurks around the corner:

    int[] result = Array.FindAll(numbers, delegate(int i) { return i == num2; });
    Console.WriteLine(result.Length);

Personally, I think your way is better. It is easier to read and, therefore, to maintain. I would therefore consider it simpler than other approaches.

I'm always exploring different ways to do things; it is a great way to extend knowledge and understanding. Don't waste time, though, on trying to make something faster - unless it is a bottleneck, or you are not happy with your current code.

I like this in particular:

bool exists = numbers.Contains(num2);
if (exists)

It is very neat :smartass: (and I like neat code).

You might practice with TryParse though, which you were exploring earlier.
Was This Post Helpful? 0
  • +
  • -

#6 AVReidy  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 65
  • View blog
  • Posts: 431
  • Joined: 17-February 11

Re: Is there a simpler way to do this?

Posted 18 June 2013 - 02:15 PM

If it runs, you're doing well. If you're concerned with style, you can make things a bit simpler by simply calling the numbers.Contains(num2); line inside the if-statement.
if (numbers.Contains(num2)) {}



Also, while it might seem counterintuitive at first, you could improve efficiency by not checking if the array contains the value because the Contains() function has to go through each element to check, and you're going to do that anyway while counting the occurrences. You could write a function like the following, if you wanted. It's in Javascript, but you'll get the idea.

function count_occurrences_of(number) {
    var count = 0;
    for (var i = 0; i < total; i++) {
        if (numbers[i] == number)
            count++;
    }
    return count;
}


Was This Post Helpful? 0
  • +
  • -

#7 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2241
  • View blog
  • Posts: 9,418
  • Joined: 29-May 08

Re: Is there a simpler way to do this?

Posted 18 June 2013 - 02:18 PM

Another way slightly more advance using the LINQ method .Count

The main method.
int n = 10;
int[] numbers = new int[n];
Console.WriteLine("Please enter {0} numbers:\n",n);
for(int x=0; x< n; x++)
{
  Console.Write("{0}:= "; x)
  nums[x] = getNumber();
}
Console.Clear();
Console.Write("Please enter a number to look for: ");
int l = getNumber();
int c = nums.Count(x=> x==l)
if ( c > 0) 
{
  Console.WriteLine("{0} found occurrences of {1}",c,l);
}
else
{
  Console.WriteLine("Number not found");
}



Separate out the get of a number.
int getNumber()
{
  int value = 0;
  while(true) /* infinite loop */
  {
    if( Integer.TryParse(Console.ReadLine(), value) ) { return value; }
    Console.WriteLine("Not a number. Please try again.")
  }
}


This post has been edited by AdamSpeight2008: 18 June 2013 - 02:45 PM

Was This Post Helpful? 0
  • +
  • -

#8 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3253
  • View blog
  • Posts: 10,908
  • Joined: 12-December 12

Re: Is there a simpler way to do this?

Posted 18 June 2013 - 02:19 PM

@AVReidy Contains won't check the whole array - it will stop if it finds the value, so I still prefer the OPs version. Although, I agree with this:

if (numbers.Contains(num2)) {}

This post has been edited by andrewsw: 18 June 2013 - 02:22 PM

Was This Post Helpful? 0
  • +
  • -

#9 AVReidy  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 65
  • View blog
  • Posts: 431
  • Joined: 17-February 11

Re: Is there a simpler way to do this?

Posted 18 June 2013 - 02:26 PM

View Postandrewsw, on 18 June 2013 - 04:19 PM, said:

Contains won't check the whole array - it will stop if it finds the value, so I still prefer the OPs version. Although, I agree with this:

if (numbers.Contains(num2)) {}

You're probably looking for more than one number, so it's very redundant to see if something exists before counting occurrences unless it's critical that you halt the program once it's detected. Using .Contains() is like calling the function I provided twice, like this:
if (count_occurrances_of(number) != 0) alert(count_occurrances_of(number)); // BAD


Not to be nit-picky, but that could be a giant performance sink if the array was larger. Personally, I would just use a function like that and get the number of occurrences; if it returns zero, so be it.

This post has been edited by AVReidy: 18 June 2013 - 02:28 PM

Was This Post Helpful? 1
  • +
  • -

#10 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Re: Is there a simpler way to do this?

Posted 18 June 2013 - 02:38 PM

I've been experimenting with TryParse over the past couple days. Usually, though, I've been using sort of a template (taken from another user here on the forums). That's been my go-to when I want to write a program that has to convert any string representation of a number into an actual value.

I see that AdamSpeight2008 used a different variation of TryParse than what I've been using.

Here is the code he used:

int getNumber()
{
  int value = 0;
  while(true) /* infinite loop */
  {
    if( Integer.TryPase(Console.ReadLine(), value) ) { return value; }
    Console.WriteLine("Not a number. Please try again.")
  }
}



This looks a bit complicated, but that might be because I just haven't seen it used this way before. Does it involve LINQ as the code above it does?

This post has been edited by Semus: 18 June 2013 - 02:39 PM

Was This Post Helpful? 0
  • +
  • -

#11 h4nnib4l  Icon User is offline

  • The Noid
  • member icon

Reputation: 1181
  • View blog
  • Posts: 1,673
  • Joined: 24-August 11

Re: Is there a simpler way to do this?

Posted 18 June 2013 - 02:48 PM

I'll offer a few minor critiques here. First, try using variable names that are a bit more descriptive (like "occurences" instead of "num2", for example). When the whole shebang is only around 30 lines of code, it isn't really a big deal, but as you progress you will be really glad you developed the habit early on. Also, I don't know if you've covered creating separate methods or not, but the logic that checks if that final number is in the array and then chooses the correct output would be a great candidate for another method.

EDIT: I KNEW I should have refreshed before posting after I left my response sitting unposted for half an hour...

What I was getting at was basically what AVReidy was suggesting: shop the counting logic out to a separate method and return the occurences, then run an if/else based on the returned value. That way you're only making one pass over the array.

This post has been edited by h4nnib4l: 18 June 2013 - 02:57 PM

Was This Post Helpful? 1
  • +
  • -

#12 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2241
  • View blog
  • Posts: 9,418
  • Joined: 29-May 08

Re: Is there a simpler way to do this?

Posted 18 June 2013 - 02:48 PM

Note that I did spell it wrong. There is no LINQ used is the section you pointed out.

Think about the types being used. The return type of the Console.ReadLine and the type of the first parameter of Integer.TryParse.
Was This Post Helpful? 0
  • +
  • -

#13 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3253
  • View blog
  • Posts: 10,908
  • Joined: 12-December 12

Re: Is there a simpler way to do this?

Posted 18 June 2013 - 02:56 PM

View PostAVReidy, on 18 June 2013 - 09:26 PM, said:

Not to be nit-picky, but that could be a giant performance sink if the array was larger. Personally, I would just use a function like that and get the number of occurrences; if it returns zero, so be it.

Fair enough ;).

I suppose another approach would be to (try to) obtain the index of the value and then count (loop) from this point forwards. But, as we have already seen, there are many different approaches. Andy.
Was This Post Helpful? 0
  • +
  • -

#14 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2241
  • View blog
  • Posts: 9,418
  • Joined: 29-May 08

Re: Is there a simpler way to do this?

Posted 18 June 2013 - 03:22 PM

View Posth4nnib4l, on 18 June 2013 - 10:48 PM, said:

What I was getting at was basically what AVReidy was suggesting: shop the counting logic out to a separate method and return the occurences, then run an if/else based on the returned value. That way you're only making one pass over the array.


That be Enumerable.Count when your re-factor to be generic and agnostic over how the collection type is actually implemented, so long as the collection implements the interface IEnumerable< T >. Which all of the collection types in .net do.

or since it is an Array you could also use
int c = Array.Find(numbers, new Predicate(Of Integer)(x=> x==l)).Count;


This post has been edited by AdamSpeight2008: 18 June 2013 - 03:27 PM

Was This Post Helpful? 0
  • +
  • -

#15 Witchking  Icon User is offline

  • D.I.C Head

Reputation: 68
  • View blog
  • Posts: 188
  • Joined: 17-February 13

Re: Is there a simpler way to do this?

Posted 18 June 2013 - 03:37 PM

Here's how i'd do it.
static void Main(string[] args)
{
	int[] numbers = new int[10];
	int number;

	for (int i = 0; i < 10; i++) do { Console.Write("Enter number " + (i + 1) + ": "); } while (!int.TryParse(Console.ReadLine(), out numbers[i]));

	Console.WriteLine();
	do { Console.Write("Enter the number to check for: "); } while (!int.TryParse(Console.ReadLine(), out number));
	Console.WriteLine("The number " + number + " occurred " + numbers.Where(n => n == number).Count() + " times.");
	Console.Read();
}

Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2