Finding all possible combinations of int[] array, constrained by length in C# - c#

int[] listOfValues = {1, 2, 5, 2, 6};
I need to be able to find all pair combinations of this array, including repetitions. Each value in the array comes from a deck of cards. So, if the value "2" appears twice in the array, for example, we can assume that these are two different values, and as such, need to be treated separately.
Sample of expected pairs of cards:
{1, 2}
{1, 2}
{2, 1}
{2, 1}
{2, 2}
{1, 5}
{1, 6}
etc.......
These separate int[] results will then need to be added to a List (if you can even add duplicate int[] values to a list, that is!), once all possible values have been found.
I have looked for a few hours online, and can't seem to get any of the solutions working for my particular task.
Does anyone have any ideas please?

You should really do homework on your own. Or at least try it first. You haven't provided code, so I cannot ethically give you the full solution.
However, this will get you started:
Think about it as if you were to do it by hand. Most people would pick the first value and the second value and write them down. Then they would write that pair backwards. Then they would do the first value and the third, then backwards, and so on and so on.
It would look something like:
{1,2}
{2,1}
{1,5}
{5,1}
{1,2}
{2,1}
{1,6}
{6,1}
{2,5} -Now we iterate again, starting with the second value
So how would we express that in code? Nested loops!
Here is the skeleton of an algorithm to solve your problem:
List<int[]> pairs = new List<int[]>();
for(int x = 0; x < listOfValues.Length - 1; x++)
{
for(int y = x+1; y < listOfValues.Length; y++)
{
// Create an array of the [x] position and [y] position of listOfValues
// Create another array, except swap the positions {[y],[x]}
// Add both arrays to the "pairs" List
}
}
Try to understand what this code is doing. Then fill in the blanks. You should get the correct answer. Always make sure to understand why, though. Also, try to see if you can figure out any improvements to this code.

With linq you could do it this way.
int[] listOfValues = { 1, 2, 5, 2, 6 };
var combination = listOfValues.Select(i => listOfValues.Select(i1 => new Tuple<int, int>(i, i1)).ToList())
.ToList()
.SelectMany(list => list.Select(x => x)).ToList();

With thanks to Clay07g's post, I was able to resolve the problem with the following code:
public static List<int[]> getCardCombos(int[] values)
{
List<int[]> pairs = new List<int[]>();
for (int x = 0; x < values.Length - 1; x++)
{
for (int y = x + 1; y < values.Length; y++)
{
int firstValue = values[x];
int secondValue = values[y];
// Create an array of the [x] position and [y] position of listOfValues
int[] xAndY = { firstValue, secondValue};
// Create another array, except swap the positions {[y],[x]}
int[] yAndX = { secondValue, firstValue };
pairs.Add(xAndY);
pairs.Add(yAndX);
// Add both arrays to the "pairs" List
}
}
return pairs;
}

Related

Efficiently finding arrays with the most occurences of the same number

Let's say I have the following nested array:
[
[1, 2, 3],
[4, 7, 9, 13],
[1, 2],
[2, 3]
[12, 15, 16]
]
I only need the arrays with the most occurrences of the same numbers. In the above example this would be:
[
[1, 2, 3],
[4, 7, 9, 13],
[12, 15, 16]
]
How can I do this efficiently with C#?
EDIT
Indeed my question is really confusing. What I wanted to ask is: How can I eliminate sub-arrays if some bigger sub-array already contains all the elements of a smaller sub-array.
My current implementation of the problem is the following:
var allItems = new List<List<int>>{
new List<int>{1, 2, 3},
new List<int>{4, 7, 9, 13},
new List<int>{1, 2},
new List<int>{2, 3},
new List<int>{12, 15, 16}
};
var itemsToEliminate = new List<List<int>>();
for(var i = 0; i < allItems.ToList().Count; i++){
var current = allItems[i];
var itemsToVerify = allItems.Where(item => item != current).ToList();
foreach(var item in itemsToVerify){
bool containsSameNumbers = item.Intersect(current).Any();
if(containsSameNumbers && item.Count > current.Count){
itemsToEliminate.Add(current);
}
}
}
allItems.RemoveAll(item => itemsToEliminate.Contains(item));
foreach(var item in allItems){
Console.WriteLine(string.Join(", ", item));
}
This does work, but the nested loops for(var i = 0; i < allItems.ToList().Count; i++) and foreach(var item in itemsToVerify) gives it a bad performance. Especially if you know that the allItems array can contain about 10000000 rows.
I would remember the items that are already in the list.
First sort your lists by decreasing length, then check for each item if it's already present.
Given your algorithm, the array is not added if even a single integer is in the list already of known integers already.
Therefore I would use the following algorithm:
List<List<int>> allItems = new List<List<int>>{
new List<int>{1, 2, 3},
new List<int>{4, 7, 9, 13},
new List<int>{1, 2},
new List<int>{2, 3},
new List<int>{12, 15, 16}
};
allItems = allItems.OrderByDescending(x => x.Count()).ToList(); // order by length, decreasing order
List<List<int>> result = new List<List<int>>();
SortedSet<int> knownItems = new SortedSet<int>(); // keep track of numbers, so you don't have to loop arrays
// https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedset-1?view=netframework-4.7.2
foreach (List<int> l in allItems)
{
// bool allUnique = true;
foreach (int elem in l)
{
if (knownItems.Contains(elem))
{
// allUnique = false;
break;
}
else
{
// OK, because duplicates not allowed in single list
// and because how the data is constrained (I still have my doubts about how the data is allowed to look and what special cases may pop up that ruin this, so use with care)
// this WILL cause problems if a list starts with any number which has not yet been provided appears before the first match that would cause the list to be discarded.
knownItems.Add(elem);
}
}
// see comment above near knownItems.Add()
/*
if (allUnique)
{
result.Add(l);
foreach (int elem in l)
{
knownItems.Add(elem);
}
}
*/
}
// output
foreach(List<int> item in result){
Console.WriteLine(string.Join(", ", item));
}
Instead of looping over your original array twice nestedly (O(n^2)), you only do it once (O(n)) and do a search in known numbers (binary search tree lookup: O(n*log2(n))).
Instead of removing from the array, you add to a new one. This uses more memory for the new array. The reordering is done because it is more likely that any subsequent array contains numbers already processed. However sorting a large amount of lists may be slower than the benefit you gain if you have many small lists. If you have even a few long ones, this may pay off.
Sorting your list of lists by the length is valid because
what is to happen if a list has items from different lists? say instead of new List{2, 3} it was new List{2, 4}?
That unexpected behavior. You can see the ints as an id of a person. Each group of ints forms, for example, a family. If the algorithm creates [2, 4], then we are creating, for example, an extramarital relationship. Which is not desirable.
From this I gather the arrays will contain subsets of at most only one other array or be unique. Therefore the Order is irrelevant.
This also assumes that at least one such array would contain all elements of such subsets (and therefore be the longest one and come first.)
The sorting could be removed if it were not so, and should probably be removed if in doubt.
For example:
{1, 2, 3, 4, 5} - contains all elements that future arrays will have subsets of
{1, 4, 5} - must contain no element that {1,2,3,4,5} does not contain
{1, 2, 6} - illegal in this case
{7, 8 ,9} - OK
{8, 9} - OK (will be ignored)
{7, 9} - OK (will be ignored, is only subset in {7,8,9})
{1, 7} - - illegal, but would be legal if {1,2,3,4,5,7,8,9} was in this list. because it is longer it would've been earlier, making this valid to ignore.

c# foreach loop not able to add literals in an array

Firstly I know that I can't use a foreach loop in C# to add values in let's say an array... But why? Why for example I can't do this
int[] numbers = { 1, 4, 3, 5, 7, 9 };
foreach (int item in numbers)
{
numbers[item] = 2;
}
Does it have something to do with the actual realisation of the foreach loop in the back-end? And how does the foreach loop exactly work? I know that it goes through the whole collection(array) but how exactly?
You are passing in the value of an item (your variable, item, will be the value of the array at each position in sequence, not the index) in the array as the index. The index used there is meant to be the position of the item you are attempting to access, not the value. So each iteration of the loop you are calling:
numbers[1]
numbers[4]
numbers[3]
numbers[5]
numbers[7]
numbers[9]
The array has 6 numbers, so when you get to numbers[7], you are asking for a value that is not there, hence the exception.
A better method of doing what you are trying to do would be:
for(int i = 0; i < numbers.Length; i++)
{
numbers[i] = 2;
}
On each iteration of this loop you would be accessing:
numbers[0]
numbers[1]
numbers[2]
numbers[3]
numbers[4]
numbers[5]
I'm looking at this:
numbers[item] = 2;
In this expression, you're using the item variable like an index, as if it had the values 1, 2, 3, 4, etc. That's not how the foreach iteration variable works for C#. The only language I know that does it this way is Javascript.
Remember that foreach and for are not the same thing. Just about every other language, including C#, gives you the actual array values in the item variable of a foreach loop: 1,4, 3, 5 etc. Now, these are integers, so you could try to use them as indexes. You can run the loop for a while like that... until you get to the value 7. At this point, your array only has six values. You're trying to do this:
numbers[7] = 2;
for an array where the largest valid index you can use is 5.
This is true even taking your modification of the array into account. Let's look at the array after each iteration through the loop:
{ 1, 4, 3, 5, 7, 9 } //initial state
{ 1, 2, 3, 5, 7, 9 } // after 1st iteration (index 0). Value at index 0 is 1, so item as index 1 is set to 2
{ 1, 2, 2, 5, 7, 9 } // after 2nd iteration (index 1). Value at index 1 is now 2, so item at index 2 is set to 2
{ 1, 2, 2, 5, 7, 9 } // after 3rd iteration (index 2). Value at index 2 is now 2, so item at index 2 is set to 2
{ 1, 2, 2, 5, 7, 2 } // after 4th iteration (index 3). Value at index 3 is 5, so item at index 5 is set to 2
// The 5th iteration (index 4). Value at index 4 is 7, which is beyond the end of the array
For the why of this... it sounds like you're used to a more dynamic language. Some these other languages, like php or Javascript, don't have real arrays at all in the pure computer science sense. Instead, they have collection types they'll call an array, but when you get down to it are really something different.
C# has real arrays, and real arrays have a fixed size. If what you really want is a collection, C# has collections, too. You can use List<T> objects, for example, to get an array-like collection you can append to easily.
For the other languages, the results vary depending on what you're talking about, but for the most permissive the result of your 5th iteration is something like this:
{ 1, 2, 2, 5, 7, 2, ,2 }
Note the missing value at index 6. That kind of things leads to mistakes that slip through your tests and don't show up until run-time. You also need to start wondering just how densely or sparsely the array will be filled, because the best strategy for handling these arrays can vary wildly depending on your answer... everything from just a big backing array with empty nodes that the programmer has to know about all the way to Hashtables and Dictionaries. And, by the way, C# again has these options available to you.
You need to step through your code in a debugger.
A for statement is more like a while statement, not like a foreach.
The line int[] numbers = { 1, 4, 3, 5, 7, 9 }; create this:
numbers[0] = 1;
numbers[1] = 4;
numbers[2] = 3;
numbers[3] = 5;
numbers[4] = 7;
numbers[5] = 9;
Your foreach statement does this:
numbers[1] = 2;
numbers[4] = 2;
numbers[3] = 2;
numbers[5] = 2;
numbers[7] = 2; <- this line overflows your array!
numbers[9] = 2; <- and so would this.
You have to learn the difference between an array index and an array value.
You need to create counter, in other case you trying to access item outside of array
int[] numbers = new int[]{ 1, 4, 3, 5, 7, 9 };
int i = 0;
foreach (int item in numbers)
{
numbers[i] = 2;
i++;
}
// Print the items of the array
foreach (int item in numbers)
{
Console.WriteLine(item);
}

C# Calculate items in List<int> values vertically

I have a list of int values some thing like below (upper bound and lower bounds are dynamic)
1, 2, 3
4, 6, 0
5, 7, 1
I want to calculate the column values in vertical wise like
1 + 4 + 5 = 10
2 + 6 + 7 = 15
3 + 0 + 1 = 4
Expected Result = 10,15,4
Any help would be appreciated
Thanks
Deepu
Here's the input data using array literals, but the subsequent code works exactly the same on arrays or lists.
var grid = new []
{
new [] {1, 2, 3},
new [] {4, 6, 0},
new [] {5, 7, 1},
};
Now produce a sequence with one item for each column (take the number of elements in the shortest row), in which the value of the item is the sum of the row[column] value:
var totals = Enumerable.Range(0, grid.Min(row => row.Count()))
.Select(column => grid.Sum(row => row[column]));
Print that:
foreach (var total in totals)
Console.WriteLine(total);
If you use a 2D array you can just sum the first, second,... column of each row.
If you use a 1D array you can simply use a modulo:
int[] results = new results[colCount];
for(int i=0, i<list.Count; list++)
{
results[i%colCount] += list[i];
}
Do you have to use a "List"-object? Elseway, I would use a twodimensional array.
Otherwise, you simply could try, how to reach rows and columns separatly, so you can add the numbers within a simply for-loop. It depends on the methods of the List-object.
Quite inflexible based on the question, but how about:
int ans = 0;
for(int i = 0; i < list.length; i+=3)
{
ans+= list[i];
}
You could either run the same thing 3 times with a different initial iterator value, or put the whole thing in another loop with startValue as an interator that runs 3 times.
Having said this, you may want to a) look at a different way of storing your data if, indeed they are in a single list b) look at more flexible ways to to this or wrap in to a function which allows you to take in to account different column numbers etc...
Cheers,
Adam

How to select values within a provided index range from a List using LINQ

I am a LINQ newbie trying to use it to acheive the following:
I have a list of ints:-
List<int> intList = new List<int>(new int[]{1,2,3,3,2,1});
Now, I want to compare the sum of the first three elements [index range 0-2] with the last three [index range 3-5] using LINQ. I tried the LINQ Select and Take extension methods as well as the SelectMany method, but I cannot figure out how to say something like
(from p in intList
where p in Take contiguous elements of intList from index x to x+n
select p).sum()
I looked at the Contains extension method too, but that doesn't see to get me what I want. Any suggestions? Thanks.
Use Skip then Take.
yourEnumerable.Skip(4).Take(3).Select( x=>x )
(from p in intList.Skip(x).Take(n) select p).sum()
You can use GetRange()
list.GetRange(index, count);
For larger lists, a separate extension method could be more appropriate for performance. I know this isn't necessary for the initial case, but the Linq (to objects) implementation relies on iterating the list, so for large lists this could be (pointlessly) expensive. A simple extension method to achieve this could be:
public static IEnumerable<TSource> IndexRange<TSource>(
this IList<TSource> source,
int fromIndex,
int toIndex)
{
int currIndex = fromIndex;
while (currIndex <= toIndex)
{
yield return source[currIndex];
currIndex++;
}
}
Starting from .NET 6 it is possible to use range syntax for Take method.
List<int> intList = new List<int>(new int[]{1, 2, 3, 3, 2, 1});
// Starting from index 0 (including) to index 3 (excluding) will select indexes (0, 1, 2)
Console.WriteLine(intList.Take(0..3).Sum()); // {1, 2, 3} -> 6
// By default is first index 0 and can be used following shortcut.
Console.WriteLine(intList.Take(..3).Sum()); // {1, 2, 3} -> 6
// Starting from index 3 (including) to index 6 (excluding) will select indexes (3, 4, 5)
Console.WriteLine(intList.Take(3..6).Sum()); // {3, 2, 1} -> 6
// By default is last index lent -1 and can be used following shortcut.
Console.WriteLine(intList.Take(3..).Sum()); // {3, 4, 5} -> 6
// Reverse index syntax can be used. Take last 3 items.
Console.WriteLine(intList.Take(^3..).Sum()); // {3, 2, 1} -> 6
// No exception will be raised in case of range is exceeded.
Console.WriteLine(intList.Take(^100..1000).Sum());
So simply put, intList.Take(..3).Sum() and intList.Take(3..).Sum() can be used with .NET 6.
To filter by specific indexes (not from-to):
public static class ListExtensions
{
public static IEnumerable<TSource> ByIndexes<TSource>(this IList<TSource> source, params int[] indexes)
{
if (indexes == null || indexes.Length == 0)
{
foreach (var item in source)
{
yield return item;
}
}
else
{
foreach (var i in indexes)
{
if (i >= 0 && i < source.Count)
yield return source[i];
}
}
}
}
For example:
string[] list = {"a1", "b2", "c3", "d4", "e5", "f6", "g7", "h8", "i9"};
var filtered = list.ByIndexes(5, 8, 100, 3, 2); // = {"f6", "i9", "d4", "c3"};

How can I count the unique numbers in an array without rearranging the array elements?

I am having trouble counting the unique values in an array, and I need to do so without rearranging the array elements.
How can I accomplish this?
If you have .NET 3.5 you can easily achieve this with LINQ via:
int numberOfElements = myArray.Distinct().Count();
Non LINQ:
List<int> uniqueValues = new List<int>();
for(int i = 0; i < myArray.Length; ++i)
{
if(!uniqueValues.Contains(myArray[i]))
uniqueValues.Add(myArray[i]);
}
int numberOfElements = uniqueValues.Count;
This is a far more efficient non LINQ implementation.
var array = new int[] { 1, 2, 3, 3, 3, 4 };
// .Net 3.0 - use Dictionary<int, bool>
// .Net 1.1 - use Hashtable
var set = new HashSet<int>();
foreach (var item in array) {
if (!set.Contains(item)) set.Add(item);
}
Console.WriteLine("There are {0} distinct values. ", set.Count);
O(n) running time max_value memory usage
boolean[] data = new boolean[maxValue];
for (int n : list) {
if (data[n]) counter++
else data[n] = true;
}
Should only the distinct values be counted or should each number in the array be counted (e.g. "number 5 is contained 3 times")?
The second requirement can be fulfilled with the starting steps of the counting sort algorithm.
It would be something like this:
build a set where the index/key is
the element to be counted
a key is connected to a variable which holds the number of occurences
of the key element
iterate the array
increment value of key(array[index])
Regards

Categories