How to get all possible classes combinations in C# - c#

Let say we have the fallowing classes 'X','Y','Z',
The result so I need will be like this
(X),(X,Y),(X,Z),(X,Y,Z),(Y),(Y,Z),(Z)
And if we have 'X','Y','Z','J',
The result so I need will be like this
(X), (X,Y),(X,Z),(X,J), (Y), (Y,Z),(Y,J), (Z),(Z,J)
(X,Y,Z), (X,Y,Z,J), (Y,Z,J), (Z,J,X)
What algorithm do I need to accomplish this?

What you are looking for is called a power set. There are both recursive and iterative ways to calculate it; it should not be difficult to google one.
Have a try at implementing an algorithm and come back to update the question if you have specific trouble.

If that is a power set, you missed out the empty set (which is always a member of a power set, of course!).
Anyway, something like this might work for you:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Demo
{
class Program
{
static void Main()
{
string[] classes = {"X", "Y", "Z"};
foreach (var combination in PowerSet(classes))
{
foreach (var item in combination)
{
Console.Write(item + ", ");
}
Console.WriteLine("");
}
}
public static IEnumerable<IEnumerable<T>> PowerSet<T>(T[] sequence)
{
return from m in Enumerable.Range(0, 1 << sequence.Length)
select
from i in Enumerable.Range(0, sequence.Length)
where (m & (1 << i)) != 0
select sequence[i];
}
}
}
This algorithm works by "pretending" that the combinations are binary numbers. See http://en.wikipedia.org/wiki/Power_set for details (especially the section titled "Representing subsets as functions").

Related

How do I add 1 number to a array? [duplicate]

This question already has answers here:
Add new item in existing array in c#.net
(20 answers)
Closed 1 year ago.
I do not have anything other than the normal
using System;
namespace TryStuff
{
class Program
{
static void Main(string[] args)
{
}
}
}
And I know that having nothing at the start and still asking questions isnt highly looked on but STILL...
Im trying to create a code that asks you for an integer, and if you answer anything over 0, it ADDS the given number to an array, once you stop giving numbers (example type some "stop") it prints out ALL the numbers given to the array.
I DO NOT need the full code for something like this, just an answer to how do I append to an array without making it insanely complicated (things ive found on the google are like 20 lines of code but im pretty sure its not that hard).
Sorry for the long post and in short, how do I append to an array? If you can provide me a code, please implement it in the C# code or give me a "explanation" how to do it. Thank you very much!
You probably don't want to use an array, you want a different data structure that allows easy expansion, like List<T>. For List<T>, you simply call .Add, like:
using System;
using System.Collections.Generic;
namespace TryStuff
{
class Program
{
static void Main(string[] args)
{
var myList = new List<int>();
while(int.TryParse(Console.ReadLine(), out int x))
{
if (x > 0)
{
myList.Add(x);
}
}
Console.WriteLine("You entered: " + string.Join(",", myList));
}
}
}
This should keep allowing you to enter integer numbers and add them to the list if the number is greater than 0. It ignores all numbers 0 or less than 0. If you type anything that is not a number, it will stop and print out the list you entered.

Counting duplicate chars in a C# string

I'm new to C# and trying to work out how to count the number of duplicates in a string. Example input and output would be:
"indivisibility" -> 1 # 'i' occurs six times
"Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice
"aA11" -> 2 # 'a' and '1'
"ABBA" -> 2 # 'A' and 'B' each occur twice
My code so far is as follows:
using System;
using System.Collections;
using System.Linq;
public class Kata
{
public static int DuplicateCount(string str)
{
Stack checkedChars = new Stack();
Stack dupChars = new Stack();
str = str.ToLower();
for (int i=1; i < str.Length; i++) {
var alreadyCounted = checkedChars.Contains(str[i]) && dupChars.Contains(str[i]);
if (!checkedChars.Contains(str[i])) {
checkedChars.Push(str[i]);
} else if (checkedChars.Contains(str[i])) {
dupChars.Push(str[i]);
} else if (alreadyCounted) {
break;
}
}
return dupChars.Count;
}
}
My approach is to loop through each character in the string. If it hasn't been seen before, to add it to a 'checkedChars' Stack (to keep track of it). If it's already been counted, add it to a 'dupChars' Stack. However, this is failing the tests. E.g:
aabbcde is the string, and the test fails with: Expected: 2 But Was: 1
Also when I console out errors, it appears that the checkedChars Stack is empty.
Can anyone spot where I have gone wrong please?
I'd suggest you use LINQ instead. It's a more suitable tool for the problem, and it results in much cleaner code:
class Program
{
static void Main(string[] args)
{
var word = "indivisibility";
Console.WriteLine($"{word} has {CountDuplicates(word)} duplicates.");
word = "Indivisibilities";
Console.WriteLine($"{word} has {CountDuplicates(word)} duplicates.");
word = "aA11";
Console.WriteLine($"{word} has {CountDuplicates(word)} duplicates.");
word = "ABBA";
Console.WriteLine($"{word} has {CountDuplicates(word)} duplicates.");
Console.ReadLine();
}
public static int CountDuplicates(string str) =>
(from c in str.ToLower()
group c by c
into grp
where grp.Count() > 1
select grp.Key).Count();
}
}
Here's the output:
indivisibility has 1 duplicates.
Indivisibilities has 2 duplicates.
aA11 has 2 duplicates.
ABBA has 2 duplicates.
Hope this helps.
You need to start the loop at int i = 0, because indexing start at 0 and not 1. So to get the first character you'll need to call str[0].
You can also remove the break as your code will never hit it, since the first 2 conditions are exactly the opposite of each other. Instead check first if alreadyCounted is true and use continue (not break as it will exit the loop entirely!) to skip to the next iteration, to avoid counting the same characters more than once.
you can use LINQ for this -
var str = "aabbcde";
var count = str.ToLower().GroupBy(x => x).Select(y => y).Where(z=>z.Count()>1).Count();
You can also use MoreLinq.CountBy:
using System;
using System.Linq;
using MoreLinq;
namespace ConsoleApp1
{
internal class Program
{
private static int CountDuplicateCharacters(string s)
{
return s?.CountBy(c => c).Where(kvp => kvp.Value > 1).Count() ?? 0;
}
private static void Main(string[] args)
{
foreach (var s in new string[] { "indivisibility", "Indivisibilities", "aA11", "ABBA" })
{
Console.WriteLine(s + ": " + CountDuplicateCharacters(s));
}
}
}
}
In case you do not want to differentiate between lower and upper case you need to supply an EqualityComparer as a second argument to CountBy.

How efficient are compilers with nested foreach loops?

If I have some foreach loops e.g.
foreach (ObjectA a in getAs(param1))
{
foreach (ObjectB b in getBs(param2))
{
//compare a & b
}
}
Assuming I don't make any edits to the returning lists (they are the same list returned), will the compiler be smart enough to only call getAs() & getBs() once, each? Will it even be smart enough to know that it should convert them to a dictionary?
Will the fact that it is eventually interacting with a SQL database, through LNQ, make a difference (e.g. perhaps the code assumes that a SQL database can change at any moment, but maybe it can do a check to see if it's changed?)
The short answer is No, but the long answer has more to do with the way your code is written rather than the efficiency of the compiler.
In your first foreach loop, you obtain the source once, and iterate through its elements, effectively calling the method only once in order to obtain the source, but the nested foreach loop is called once for every iteration in the outer loop, and since the compiler has no way of knowing if the output of the method in the nested loop won't change, it actually makes sense for it to always call the method in order to obtain the source to iterate through.
In this case you need to improve your logic and avoid unnecessary calls to methods if you know the output will be the same, specially if you know that there is some resource consuming operation (such as a call to a DB) going on inside that method.
For the sake of giving a detailed answer, i tried your statements in the following program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StackOverflow
{
public class Class1
{
public static void Main(string[] args)
{
var serv1 = new Testserv1();
foreach (int x in serv1.CallA())
{
foreach (int y in serv1.CallB())
{
}
}
Console.WriteLine(string.Format("Calls to A: {0}", serv1.ACount));
Console.WriteLine(string.Format("Calls to B: {0}", serv1.BCount));
Console.ReadLine();
}
}
public class Testserv1
{
private static int CallACount = 0;
private static int CallBCount = 0;
public int ACount {
get
{
return CallACount;
}
}
public int BCount
{
get
{
return CallBCount;
}
}
public Testserv1()
{
//InitializeComponent();
}
public List<int> CallA()
{
CallACount++;
return new List<int>() {
1,2,3,4,5,6
};
}
public List<int> CallB()
{
CallBCount++;
return new List<int>() {
7,8,9,10,11,12
};
}
}
}
The output for the previous code is:
Calls to A: 1
Calls to B: 6
Given the information presented in your question, there is no legitimate reason to assume that the compiler would convert to a dictionary. In fact, there is no reason for a dictionary. Why would one expect the compiler to divine a unique key from a method call result?
The question posed does not provide sufficient information to even reply with a relevant response.
Necessary details include:
What are the return types of the methods getAs and getBs?
On what basis are the comparisons being made?
What is the usage and result type expected from the loop?
Each loop is using a different object, on what basis would one assume the compile would optimize in any manner given the complete lack of forthright information?
Given a more specific example such as this:
List<string> intersection = new List<string>();
foreach (string a in GetaList())
{
foreach (string b in GetbList())
{
if (a.Equals(b))
{
intersection.Add(a);
}
}
}
The assembly (F11 to step in, CTRL-F11 to view assembly) would indicate that the GetbList is actually getting called for each iteration, at least in debug mode.
I believe the answer to your question is: No, the compiler is not optimizing the inner method call for you. If you want the inner method call to occur only once, make the call outside the outer loop.

Writing a C# version of Haskell infinite Fibonacci series function

Note: The point of this question is more from a curiosity perspective. I want to know out of curiosity whether it is even possible to transliterate the Haskell implementation into a functional C# equivalent.
So I've been learning myself Haskell for great good, and while solving Project Euler problems I ran into this beautiful Haskell Fibonacci implementation:
fibs :: [Integer]
fibs = 1:1:zipWith (+) fibs (tail fibs)
Of course I was tempted to write a C# version like this, so:
If I do this:
IEnumerable<int> fibs =
Enumerable.Zip(Enumerable.Concat(new int[] { 1, 1 }, fibs),
//^^error
fibs.Skip(1), (f, s) => f + s);
The error says use of unassigned local variable fibs.
So I went slightly imperative, while this compiles...
public static IEnumerable<int> Get()
{
return Enumerable.Zip(Enumerable.Concat(new int[] { 1, 1 }, Get()),
Get().Skip(1), (f, s) => f + s);
}
It breaks with a stack overflow exception! So I came here..
Questions:
Can anyone think of a functional C# equivalent that works?
I'd like some insight into why my solutions don't work.
The answer to your first question is: this is how to do it in C#:
using System;
using System.Collections.Generic;
using System.Linq;
class P
{
static IEnumerable<int> F()
{
yield return 1;
yield return 1;
foreach(int i in F().Zip(F().Skip(1), (a,b)=>a+b))
yield return i;
}
static void Main()
{
foreach(int i in F().Take(10))
Console.WriteLine(i);
}
}
The answer to your second question is: C# is eager by default, so your method has an unbounded recursion. Iterators that use yield however return an enumerator immediately, but do not construct each element until required; they are lazy. In Haskell everything is lazy automatically.
UPDATE: Commenter Yitz points out correctly that this is inefficient because, unlike Haskell, C# does not automatically memoize the results. It's not immediately clear to me how to fix it while keeping this bizarre recursive algorithm intact.
Of course you would never actually write fib like this in C# when it is so much easier to simply:
static IEnumerable<BigInteger> Fib()
{
BigInteger prev = 0;
BigInteger curr = 1;
while (true)
{
yield return curr;
var next = curr + prev;
prev = curr;
curr = next;
}
}
Unlike the C# version provided in Eric Lippert's answer, this F# version avoids repeated computation of elements and therefore has comparable efficiency with Haskell:
let rec fibs =
seq {
yield 1
yield 1
for (a, b) in Seq.zip fibs (Seq.skip 1 fibs) do
yield a + b
}
|> Seq.cache // this is critical for O(N)!
I have to warn you that I'm trying to fix your attempts, not to make a productive code.
Also, this solution is good to make our brains to explode, and maybe the computer also.
In your first snippet you tried to call recursive your field or local variable, that is not possible.Instead we can try with a lambda which could be more similar to that. We know from Church, that is also not possible, at least in the traditional way. Lambda expressions are unnamed; you can't call them by their name ( inside of the implementation ). But you can use the fixed point to do recursion. If you have a sane mind there is big chance of not knowing what is that, anyway you should give a try to this link before continuing with this.
fix :: (a -> a) -> a
fix f = f (fix f)
This will be the c# implementation (which is wrong)
A fix<A>(Func<A,A> f) {
return f(fix(f));
}
Why is wrong? Because fix(f) represents a beautiful stackoverflow. So we need to make it lazy:
A fix<A>(Func<Func<A>,A> f) {
return f(()=>fix(f));
}
Now is lazy! Actually you will see a lot of this in the following code.
In your second snippet and also in the first, you have the problem that the second argument to Enumerable.Concat is not lazy, and you will have stackoverflow exception, or infinite loop in the idealistic way. So let's make it lazy.
static IEnumerable<T> Concat<T>(IEnumerable<T> xs,Func<IEnumerable<T>> f) {
foreach (var x in xs)
yield return x;
foreach (var y in f())
yield return y;
}
Now, we have the whole "framework" to implement what you have tried in the functional way.
void play() {
Func<Func<Func<IEnumerable<int>>>, Func<IEnumerable<int>>> F = fibs => () =>
Concat(new int[] { 1, 1 },
()=> Enumerable.Zip (fibs()(), fibs()().Skip(1), (a,b)=> a + b));
//let's see some action
var n5 = fix(F)().Take(5).ToArray(); // instant
var n20 = fix(F)().Take(20).ToArray(); // relative fast
var n30 = fix(F)().Take(30).ToArray(); //this will take a lot of time to compute
//var n40 = fix(F)().Take(40).ToArray(); //!!! OutOfMemoryException
}
I know that the F signature is ugly like hell, but this is why languages like haskell exists, and even F#. C# is not made for this work to be done like this.
Now, the question is, why haskell can achieve something like this?Why? because whenever you say something like
a:: Int
a = 4
The most similar translation in C# is :
Func<Int> a = () => 4
Actually is much more involved in the haskell implementation, but this is the idea why similar method of solving problems looks so different if you want to write it in both languages
Here it is for Java, dependent on Functional Java:
final Stream<Integer> fibs = new F2<Integer, Integer, Stream<Integer>>() {
public Stream<Integer> f(final Integer a, final Integer b) {
return cons(a, curry().f(b).lazy().f(a + b));
}
}.f(1, 2);
For C#, you could depend on XSharpX
A take on Eric's answer that has Haskell equivalent performance, but still has other issues(thread safety, no way to free memory).
private static List<int> fibs = new List<int>(){1,1};
static IEnumerable<int> F()
{
foreach (var fib in fibs)
{
yield return fib;
}
int a, b;
while (true)
{
a = fibs.Last();
b = fibs[fibs.Count() - 2];
fibs.Add(a+b);
yield return a + b;
}
}
Translating from a Haskell environment to a .NET environment is much easier if you use F#, Microsoft's functional declarative language similar to Haskell.

Why is .ForEach() on IList<T> and not on IEnumerable<T>? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why is there not a ForEach extension method on the IEnumerable interface?
I've noticed when writing LINQ-y code that .ForEach() is a nice idiom to use. For example, here is a piece of code that takes the following inputs, and produces these outputs:
{ "One" } => "One"
{ "One", "Two" } => "One, Two"
{ "One", "Two", "Three", "Four" } => "One, Two, Three and Four";
And the code:
private string InsertCommasAttempt(IEnumerable<string> words)
{
List<string> wordList = words.ToList();
StringBuilder sb = new StringBuilder();
var wordsAndSeparators = wordList.Select((string word, int pos) =>
{
if (pos == 0) return new { Word = word, Leading = string.Empty };
if (pos == wordList.Count - 1) return new { Word = word, Leading = " and " };
return new { Word = word, Leading = ", " };
});
wordsAndSeparators.ToList().ForEach(v => sb.Append(v.Leading).Append(v.Word));
return sb.ToString();
}
Note the interjected .ToList() before the .ForEach() on the second to last line.
Why is it that .ForEach() isn't available as an extension method on IEnumerable<T>? With an example like this, it just seems weird.
Because ForEach(Action) existed before IEnumerable<T> existed.
Since it was not added with the other extension methods, one can assume that the C# designers felt it was a bad design and prefer the foreach construct.
Edit:
If you want you can create your own extension method, it won't override the one for a List<T> but it will work for any other class which implements IEnumerable<T>.
public static class IEnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (T item in source)
action(item);
}
}
According to Eric Lippert, this is mostly for philosophical reasons. You should read the whole post, but here's the gist as far as I'm concerned:
I am philosophically opposed to
providing such a method, for two
reasons.
The first reason is that doing so
violates the functional programming
principles that all the other sequence
operators are based upon. Clearly the
sole purpose of a call to this method
is to cause side effects.
The purpose of an expression is to
compute a value, not to cause a side
effect. The purpose of a statement is
to cause a side effect. The call site
of this thing would look an awful lot
like an expression (though,
admittedly, since the method is
void-returning, the expression could
only be used in a “statement
expression” context.)
It does not sit well with me to make
the one and only sequence operator
that is only useful for its side
effects.
The second reason is that doing so
adds zero new representational power
to the language.
Because ForEach() on an IEnumerable is just a normal for each loop like this:
for each T item in MyEnumerable
{
// Action<T> goes here
}
ForEach isn't on IList it's on List. You were using the concrete List in your example.
I am just guessing here , but putting foreach on IEnumerable would make operations on it to have side effects . None of the "available" extension methods cause side effects , putting an imperative method like foreach on there would muddy the api I guess . Also, foreach would initialize the lazy collection .
Personally I've been fending off the temptation to just add my own , just to keep side effect free functions separate from ones with side effects.
ForEach is implemented in the concrete class List<T>
Just a guess, but List can iterate over its items without creating an enumerator:
public void ForEach(Action<T> action)
{
if (action == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
for (int i = 0; i < this._size; i++)
{
action(this._items[i]);
}
}
This can lead to better performance. With IEnumerable, you don't have the option to use an ordinary for-loop.
LINQ follows the pull-model and all its (extension) methods should return IEnumerable<T>, except for ToList(). The ToList() is there to end the pull-chain.
ForEach() is from the push-model world.
You can still write your own extension method to do this, as pointed out by Samuel.
I honestly don't know for sure why the .ForEach(Action) isn't included on IEnumerable but, right, wrong or indifferent, that's the way it is...
I DID however want to highlight the performance issue mentioned in other comments. There is a performance hit based on how you loop over a collection. It is relatively minor but nevertheless, it certainly exists. Here is an incredibly fast and sloppy code snippet to show the relations... only takes a minute or so to run through.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Start Loop timing test: loading collection...");
List<int> l = new List<int>();
for (long i = 0; i < 60000000; i++)
{
l.Add(Convert.ToInt32(i));
}
Console.WriteLine("Collection loaded with {0} elements: start timings",l.Count());
Console.WriteLine("\n<===============================================>\n");
Console.WriteLine("foreach loop test starting...");
DateTime start = DateTime.Now;
//l.ForEach(x => l[x].ToString());
foreach (int x in l)
l[x].ToString();
Console.WriteLine("foreach Loop Time for {0} elements = {1}", l.Count(), DateTime.Now - start);
Console.WriteLine("\n<===============================================>\n");
Console.WriteLine("List.ForEach(x => x.action) loop test starting...");
start = DateTime.Now;
l.ForEach(x => l[x].ToString());
Console.WriteLine("List.ForEach(x => x.action) Loop Time for {0} elements = {1}", l.Count(), DateTime.Now - start);
Console.WriteLine("\n<===============================================>\n");
Console.WriteLine("for loop test starting...");
start = DateTime.Now;
int count = l.Count();
for (int i = 0; i < count; i++)
{
l[i].ToString();
}
Console.WriteLine("for Loop Time for {0} elements = {1}", l.Count(), DateTime.Now - start);
Console.WriteLine("\n<===============================================>\n");
Console.WriteLine("\n\nPress Enter to continue...");
Console.ReadLine();
}
Don't get hung up on this too much though. Performance is the currency of application design but unless your application is experiencing an actual performance hit that is causing usability problems, focus on coding for maintainability and reuse since time is the currency of real life business projects...
It's called "Select" on IEnumerable<T>
I am enlightened, thank you.

Categories

Resources