When attempting to solve the problem
How many seven-element subsets (not repeatable) are there in a set of nine elements ?
I tried
IEnumerable<string> NineSet =new string[] {"a","b","c","d","e","f","g","h","i"};
var SevenSet =
from first in NineSet
from second in NineSet
where first.CompareTo(second)< 0 && first.Count() + second.Count()==7
select new { first, second };
What is the problem that prevents me from attempting to use first.Count() and second.Count()? I did not check whether it is the best solution for the problem.
As already stated, what you have written down will lead you to nowhere. This is a question of combinatorics. AFAIK there is nothing pre-made in the .NET framework to solve for you combinatorics problems, hence you will have to implement the correct algorithm. If you get stuck, there are solutions out there, e.g. http://www.codeproject.com/KB/recipes/Combinatorics.aspx, where you can look at the source to see what you need to do.
first and second are strings, so you'll count their characters (this compiles, but intellisence hides it).
You're looking for something like NineSet.Count(first.Equals)
Well...
You haven't shown the error message, so it's hard to know what's wrong
Every element is of length exactly one, so I'm not sure what you're expecting to happen
As you know that first and second are strings, why aren't you using first.Length and second.Length?
As a side issue, I don't think this approach is going to solve the problem for you, I'm afraid...
Related
I am very new to C# and am trying to feel it out. Slow going so far! What I am trying to achieve should be relatively simple; I want to read a row from a CSV file with a search. I.e. if I search for username "Toby" it would fetch the entire row, preferably as an array.
Here is my users.csv file:
Id,Name,Password
1,flugs,password
2,toby,foo
I could post the code that I've tried, but I haven't even come close in previous attempts. It's a bit easier to do such a thing in Python, it may be easy in C# too but I'm far too new to know!
Does anyone have any ideas as to how I should approach/code this? Many thanks.
Easy to do in c# too:
var lineAsArray = File.ReadLines("path").First(s => s.Contains(",toby,")).Split(',');
If you want case insens, use e.g. Contains(",toby,", StringComparison.OrdinalIgnoreCase)
If your user is going to type in "Toby" you can either concatenate a comma on the start/end of it to follow this simplistic searching (which will find Toby anywhere on the line) or you can split the lone first and look to see if the second element is Toby
var lineAsArray = File.ReadLines("path").Split(',').First(a => a[1].Equals("toby"));
To make this one case insensitive, put a suitable StringComparison argument into the Equals using the same approach as above
Sky's the limit with how involved you want to get with it; using a library that parses CSV to objects that represent your lines with named, typed parameters is probably where I'd stop.. take a look at CSVHelper from josh close or ServiceStack Text, though there are no shortage of csv parser libs- it's been done to death!
How can I retrieve the highest number in an array recursively in C#?
Right now you're probably thinking that we're mean for not giving you the answer -- and I admit that I have the answer written down and part of me wants to give it to you, even.
Programming is all about finding the solutions to problems yourself. When you're hired as a programmer, you may have other people to lean on, but they've all got their own problems, and you'll need to be able to pull your own weight.
Recursion (in an oversimplifed answer) means to call the same operation over and over until the result is produced. That means you need in every recursive operation, you need to know (at least) two things:
What you're looking for
What you've found so far
The 'What you're looking for' is the termination condition. Once you find that, all work can stop and you can go home.
The 'what you've found so far' is how you know what've you've checked so you don't retread old ground.
So what do you need to know in order to find the highest value in an array recursively?
The contents of the Array.
The highest number you've found so far.
Have you already looked at this part of the Array? (Why look through it again?)
That would produce a method signature that looks like:
public int GetHighestNumber(int[] array, int highestNumberFound, int lastIndexChecked);
Once you're inside the array, you've got to do the following:
Iterate through the array
Stop when you find a value that is higher than the highestNumberFound
Call GetHighestNumber again with the new highestNumberFound and lastIndexChecked updated.
When there are no more 'higher' numbers, then return the highest number found.
I realize it sounds trite, but learning this stuff on your own will make you a better programmer.
If you want to be a professional programmer, you have got to learn this stuff on your own.
If you don't want to be a professional programmer, then drop the course and do something you love.
Here's just a hint (taking int[] as an example):
public int FindMax(int[] array, int indexSoFar, int maxSoFar)
Think about:
The start conditions
The termination conditions
How you move through the array recursively
Reason of EDIT: Didnt want to spoil the answere.
Greetings.
I am wondering: what is the best instruction in terms of performance between those 2 versions:
Background = Application.Current.Resources[condition ? BackgroundName1 : BackgroundName2] as Brush;
and:
Background = condition ? Application.Current.Resources[BackgroundName1] as Brush : Application.Current.Resources[BackgroundName2] as Brush;
is there any difference? and if yes, which one is better?
NB: BackgroundName1 & 2 are simply strings
The first one is shorter and more readable.
It's also easier to maintain.
If you later change it to read a different Resources dictionary, you might forget to change the second half of the second one.
The first one is also more clearly reading from the same dictionary.
First: Use a profiler to find the slowest thing. If you're having a performance problem it doesn't make sense to spend hours or days working on making something faster that is already fast enough.
Second: You can determine the answer to your question by trying it both ways and carefully measuring to see if there is a difference. Don't ask us which is faster; we don't know because we haven't tried it and have no ability to try it.
Don't get too caught up in micro-optimizations! The performance gain you'll get will be nil. Go for the code that is more readable and easier to understand in the end.
No difference whatsoever.
I assume this should be fine
bool prefMatch = false;
// Is the frequency the same?
prefMatch = string.Compare(user.Frequency, pref.Action.ToString()) == 0;
so if user.Frequency is "3" and pref.Action.ToString() is "3" then it should set the prefMatch to true right? I'm getting false and I've definitely checked the 2 values in the watch tab in VS 2008 just to be sure they're the same
You can just use ==
prefMath = (user.Frequency == pref.Action.ToString());
Though string.Compare will also work. I suggest there is a problem elsewhere.
-- Edit
Also, just for completeness, there is no point assigning a variable to something, and then assigning it again directly after. It's slightly confusing to do so, so better to leave it unassigned, or assign it all in one spot. This way the compiler can help you if you have a case where it doesn't get assigned like you think. It is, obviously, acceptable to assign first if you wrap the second assignment in a try/catch though.
In situations like these, it's sometimes tempting to point the finger of blame at third-party code, as you've done here. Sometimes, this is justified - but not here. String.Compare is a central, extremely-well-tested piece of the .NET Framework. It's not failing. I guarantee it.
What I find helpful in these situations is to isolate the failure. Write a small, self-contained test case that attempts to demonstrate the problem. Write it with as few dependencies as possible. Make it a stand-alone console application, if possible. Post it here. If we can take it, compile and run it, and reproduce the problem, we can help you. I'd bet money, though, that in the course of creating this test case, you'll experience a head-slapping moment - "of course!" - and realize what the problem is.
Maybe the string(s) contain unprintable characters ?
To check, I'd do something like :
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(user.Frequency);
byte[] b2 = System.Text.Encoding.UTF8.GetBytes(pref.Action.ToString());
then compare the contents of b1 and b2.
I have a question about this question. I posted a reply there but since it's been marked as answered, I don't think I'll get a response to my post there.
I am running C# framework 2.0 and I
would like to get some of the data
from a list? The list is a List<>. How
can I do that without looping and
doing comparaison manually on each
element of the List<>?
It really looks like the answers are just a more elegant ways of comparing every element of the List. Given that the list is not guaranteed to be sorted prior to the search, do any of the methods provided in the original post ensure that they are looking at a smaller subset of the original list?
EDIT: One thing to note is that I'm not trying to do anything here. I just want to know if the solutions provided in another question truly do what the OP asked, with regards to looping through the whole list. In general, to search an unsorted list (at least it's not required given the data structure), you will have to search the entire list. However, do any of the solutions on the other thread have an underlying optimization to prevent searching the entire list?
EDIT: I really didn't get any answers that were all that helpful but I will give credit to the answer that at least confirmed my common sense belief. If I notice a new answer that is better, I will change my vote.
If your requirement is to find things quickly in an arbitrary collection, then perhaps a list isn't the best data structure for the job. :)
You might want to check out LINQ support for .Net 2.0.
Has explain in the thread your mentionned you can get some of the object from the list without LINQ.
list = list.FindAll(yourFilterCriteria);
The object yourFilterCriteria is a Predicate and can do comparison with all Property or Function in your object so it's very customizable.
Predicate<SimpleObject> yourFilterCriteria = delegate(SimpleObject simpleObject)
{
return simpleObject.FirstName.Contains("Skeet") && simpleObject.Age < 30;
};
This example show you that you can search the list without looping manullay and you will get all people with the First Name Skeet and Age under 30.
If you're only looking for the first match, then the Find method will do the job. It won't loop through the entire list, rather it will return the first occurrence of the object. However, if you want to find all of them, how exactly do you expect to search through only a subset of the data if it isn't sorted?