Is there a simpler way to do this?

  • (2 Pages)
  • +
  • 1
  • 2

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

#16 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 - 05:14 PM

View PostWitchking, on 18 June 2013 - 03:37 PM, said:

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();
}

Once my head stops spinning I'll try to figure out what the heck you just did...
Was This Post Helpful? 0
  • +
  • -

#17 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2251
  • View blog
  • Posts: 9,435
  • Joined: 29-May 08

Re: Is there a simpler way to do this?

Posted 18 June 2013 - 05:27 PM

Semus:- It's not that complex once you expand it out. It uses a lot of stuff you should already know about.
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? 0
  • +
  • -

#18 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 - 06:04 PM

View PostAdamSpeight2008, on 18 June 2013 - 05:27 PM, said:

Semus:- It's not that complex once you expand it out. It uses a lot of stuff you should already know about.


Yes, when you expand it out, it does. Except that it uses the Lambda expression which is part of LINQ, if I remember correctly. That's something I am unfamiliar with. I haven't gotten into LINQ quite yet, and yes, I can just go look it up if I want to know how it works and yes, I do have the link to the MSDN website which explains it.

My only question at this point would be why would you group the lines of code that way instead of expanding it out? It seems to me that it would be easier to read expanded out instead of packed together like that. Perhaps to save space?

That's not to say there is anything wrong with doing it, but I have seen it done multiple times and always wondered why they just didn't expand it out to look like mine does. Is it just a preference thing?

Also, doesn't the compiler format it automatically at compile time anyway?

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

Was This Post Helpful? 0
  • +
  • -

#19 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2251
  • View blog
  • Posts: 9,435
  • Joined: 29-May 08

Re: Is there a simpler way to do this?

Posted 18 June 2013 - 07:14 PM

Lambdas are not part of LINQ you can use them without LINQ and use LINQ without lambdas.
Lambdas make somethings easier to write, or hard to write without them.

A basic Understanding Func<T> and Action<T> and there overloads.

numbers.Where(n => n == Number).Count()

Count goes through each item and counts how many there are.
Where goes through each item in the sequence, I say sequence because it enumerates each item in sequence (see spoiler) and return only those that match the condition you provided (the lambda function).

Func<Integer, Boolean> ValueMatches = (Integer Value) =>{ return Value == Number; };

  numbers.Where( ValueMatches() ).Count()



  numbers.Where( ValueMatches() ).Count();

/* rest of code */

 Boolean ValueMatches()
 {
   Return Value == NumberToMatchAgainst  ;
 }



but this a some issue of need to change the scoping visibility of the variable NumberToMatchAgainst to something less local.
You couldn't use the following because it wouldn't match the required type Integer -> Boolean, or worse it'll match the overload of the method which also supplies an index value to the lambda function (thus give incorrect results).
 Boolean ValueMatches( Integer Value, Integer NumberToMatchAgainst  )
 {
   Return Value == NumberToMatchAgainst  ;
 }



but we could if ValueMatches returned another function. Note the change to the return type.
 Func< Integer, Boolean> ValueMatches( Integer Value, Integer NumberToMatchAgainst  )
 {
   Return  Boolean function( Integer Value )
           {
             Return  Value == NumberToMatchAgainst  ;
           }
 } 


Note that code shouldn't compile (fingers crossed).

Instead we return lambda function
 Func< Integer, Boolean> ValueMatches( Integer NumberToMatchAgainst  )
 {
   Return  (Integer Value ) =>
           {
             /* The argument to the value parameter is supplied by the method using it. */
 
              Return  Value == NumberToMatchAgainst  ;
           };
 } 



So you think a Lambda as light functions that written inline with the code.
Hopefully you can understand at least at a basic level what lambda function do.


Spoiler

This post has been edited by AdamSpeight2008: 18 June 2013 - 07:22 PM

Was This Post Helpful? 0
  • +
  • -

#20 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 19 June 2013 - 05:46 AM

@AdamSpeight2008

I think it's great that you took the time to write out all that code, but it's just a bit over my head right now. This stuff might seem very basic, but from my perspective it's a bunch of stuff I don't understand. That being said, it's not as if I'll just brush it off and forget about it. I don't think it has anything to do with you or how you're explaining it. It has more to do with the fact that I don't have any experience with Lambdas yet, or Delegates for that matter. Func<T> and Action<T> are apparently delegates(??), and delegates are a bit advanced, at least at my current level of knowledge.

I take every single post in these threads very seriously because I am serious about wanting to learn more. I make sure that I track each post with code examples. I am constantly reading and rereading them. I do recognize that I have an issue with asking questions before I have exhausted all possibilities. That's a habit I'm trying to break. Also, you gave me some great advice in another thread which I took to heart. You said that I should keep trying ideas and make many many mistakes and that's how I'll learn. That has actually helped me quite a bit.

At this point I am going back through each challenge in my book and redoing all of them to make sure that I understand each concept without having to look for guidance from the book or elsewhere. That's been a huge help as well. I'll get there eventually and I'm happy with my progress so far. This forum has been invaluable in that respect.
Was This Post Helpful? 0
  • +
  • -

#21 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 19 June 2013 - 08:41 AM

View PostSemus, on 19 June 2013 - 03:04 AM, said:

My only question at this point would be why would you group the lines of code that way instead of expanding it out? It seems to me that it would be easier to read expanded out instead of packed together like that. Perhaps to save space?

That's not to say there is anything wrong with doing it, but I have seen it done multiple times and always wondered why they just didn't expand it out to look like mine does. Is it just a preference thing?

It's just personal preference. I prefer to leave out the brackets when i only have a single statement following an if clause or a loop declaration.
Was This Post Helpful? 0
  • +
  • -

#22 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4454
  • View blog
  • Posts: 7,760
  • Joined: 08-June 10

Re: Is there a simpler way to do this?

Posted 19 June 2013 - 10:55 AM

It really is style. I've found that I like to write "semantic code". Code that can be read from left-to-right that says what it does. Sometimes that means compressing things. Also, a lot of times we won't store temporary values. For example, you might write code like this:

bool isInt;
int myint;
string input = Console.ReadLine();
isInt = int.TryParse(input, out myint);
if(isInt){
  //do stuff
}


Where I'd write something more like this:

int myInt;
if(int.TryParse(Console.ReadLine(), out myInt)){
  //do stuff
}


I'm not storing the result of the comparison or the string value of the input. If it's not an int, I don't care what it is. And once I've checked if the conversion worked, I don't care about storing that value any more.

It might be harder for someone new to read, but the more you get used to it, the more you understand.

But we all have to strike a balance. Readable and maintainable code is better than clever code. Clever code is fun to write and looks neat, but if your coworkers don't understand it (or even if you don't understand it when you read it later) then it's not "good" code.

You'll gain a personal style the more time you spend programming.
Was This Post Helpful? 2
  • +
  • -

#23 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 19 June 2013 - 12:12 PM

I'm actually programming every day. I'm not creating new and exciting code, but I am practicing what I've learned over the past month.

I'm really having a tough time with arrays right now. Especially when attaching a variable to it such as numbers[x]. It's difficult for me to think about what's going on. I eventually start to get it, but I have to teach my brain to understand it and that always takes more time than I'd like it to. I'm sure at some point arrays will become second nature just like writing Console.WriteLine(); has become for me. I think the most trouble I have at the moment is trying to either match user input with values in an array, or trying to extract values in an array. This might seem rather simple, but at the moment it's a bit difficult for me. but that's a subject for another day.
Was This Post Helpful? 0
  • +
  • -

#24 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 19 June 2013 - 01:19 PM

I've often told new programmers that there isn't a learning curve to this, there's a learning cliff; you're learning to think and solve problems in a fashion not necessarily native to humans. That's why there are so many non-programmers (and one of the reasons that this is such an excellent professional field to be in). Once you reach the top of that cliff, things just start clicking and making sense much more easily. There are many lifetimes worth of programming techniques, concepts, and languages out there, but they all seem a little more "conquerable" once you have that first real aha moment. There will be many more conceptual cliffs, but again, once you've conquered a few, they won't seem so big. And with collections, the for and foreach loops are your best friends.
Was This Post Helpful? 0
  • +
  • -

#25 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 19 June 2013 - 03:29 PM

View Posth4nnib4l, on 19 June 2013 - 01:19 PM, said:

I've often told new programmers that there isn't a learning curve to this, there's a learning cliff; you're learning to think and solve problems in a fashion not necessarily native to humans. That's why there are so many non-programmers (and one of the reasons that this is such an excellent professional field to be in). Once you reach the top of that cliff, things just start clicking and making sense much more easily. There are many lifetimes worth of programming techniques, concepts, and languages out there, but they all seem a little more "conquerable" once you have that first real aha moment. There will be many more conceptual cliffs, but again, once you've conquered a few, they won't seem so big. And with collections, the for and foreach loops are your best friends.


Yes, the for and foreach loops are awesome. I've been using them, but it still take me awhile to actually "get" what's going on even after I've written the code lol. I have to visualize before I write it out and I sometimes sit there for minutes trying to "think" the problem out. It's going to take quite a few more times for me to actually "get" it. But I WILL get it, even if I have to do it over and over and over and over to get there. I suppose that's inevitable.
Was This Post Helpful? 1
  • +
  • -

#26 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2251
  • View blog
  • Posts: 9,435
  • Joined: 29-May 08

Re: Is there a simpler way to do this?

Posted 20 June 2013 - 11:22 AM

To help you visualize an Array. Imagine there is a car park with a fixed number of available space. Lets say there is 10.

var CarPark = new Int[10];
/* Value contained in Parking Space defaults to Zero (0) */
for(int ParkingSpaceNumber = 0; ParkingSpaceNumber < 10; ParkingSpaceNumber ++)
{
  CarPark[ ParkingSpaceNumber ] = 2 * ParkingSpaceNumber;
}




This wille produce
ParkingSpaceNumber[ 0 ] = 0
ParkingSpaceNumber[ 1 ] = 2
ParkingSpaceNumber[ 2 ] = 4
ParkingSpaceNumber[ 3 ] = 6
ParkingSpaceNumber[ 4 ] = 8
ParkingSpaceNumber[ 5 ] = 10
ParkingSpaceNumber[ 6 ] = 12
ParkingSpaceNumber[ 7 ] = 14
ParkingSpaceNumber[ 8 ] = 16
ParkingSpaceNumber[ 9 ] = 18


Note how the first Index of the array is Zero (0) and not One (1). The last being as Index Nine (9).

Now suppose you want to add another Car Parking Space. We can't with the instance of an array because it is of fixed.

So we have to resize it, which involves creating space (in memory) copy each of the previous values across. (This is an expensive operation to do).
This is one of the reasons of the reason we suggest the Collection types like List or more preferable the Generic Collections like List<T> for Example List<String>. Which use special techniques behind the scenes to minimise the number of time the internally used array is resized.
Let just go a little more advance and a store a Class Type in the Array.
Spoiler

This post has been edited by AdamSpeight2008: 20 June 2013 - 11:22 AM

Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2