Can't track down cause of "Index was out of range" exception - c#

So, i have this frankenstein:
var unsorted = new List<(Hand, List<Card>)>();
And when I try to add smt like this:
unsorted.Add((hand, _tempList));
I receive and error
Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
How to properly initialize this List if I do not know in advance how many items will be stored?
at the request of comments:
_tempList = IsStraightFlush(theValueHand);
if (_tempList.Count == 5)
{
unsorted.Add((hand, _tempList));
continue;
}
A function from where i add a List to the Tuple
private List<Card> IsStraightFlush(List<Card> hList)
{
var st = 0;
_tempList.Clear();
foreach (var t in hList)
{
...
}
if (_tempList.Count < 5)
{
return new List<Card>();
}
hList = _tempList.ToList();
_tempList.Clear();
for (var i = 0; i < hList.Count - 2; i++)
{
...
if (st == 4)
{
_tempList.Add(hList[i + 1]);
return _tempList;
}
}
st = 0;
_tempList.Clear();
if (hList[0].Value == 13) //Ace through 5
for (int i = hList.Count - 1, j = 0; i > 0; i--, j++)
{
...
if (st == 4)
{
_tempList.Add(hList.First());
return _tempList.OrderBy(x => x.Value).ToList();
}
}
return new List<Card>();
}
And when i use it
resultHands.AddRange(SortStraightFlushes(unsorted));
...
private List<(int, Hand)> SortStraightFlushes(List<(Hand, List<Card>)> hList)
{
var sortedHList = hList.OrderBy(x => x.Item2[0].Value).ToList();
List<(int, Hand)> output = new List<(int, Hand)>();
for (int i = 0; i < sortedHList.Count; i++)
{
if(i != sortedHList.Count - 1)
if (sortedHList[i].Item2[0].Value == sortedHList[i + 1].Item2[0].Value)
output.Add((1, sortedHList[i].Item1));
else
output.Add((0, sortedHList[i].Item1));
else
output.Add((0, sortedHList[i].Item1));
}
return output;
}

I don't know how beautiful and accurate it is, but it all worked out the way it did:
unsorted.Add((hand, new List<Card>().Concat(_tempList).ToList()));

Related

Reverse order of bubble sort of null elements

I'm trying to reverse my bubble sort so all null elements are pushed to the end of array instead of the beginning as they're getting sorted now. Any advice on how this can be achieved?
for (int outerLoop = 0; outerLoop < students.Length-1; outerLoop++)
{
for (int innerLoop = 0; innerLoop < students.Length-1; innerLoop++)
{
if (students[outerLoop+1] == null)
{
var tempObject = students[outerLoop+1];
students[outerLoop+1] = students[innerLoop];
students[innerLoop] = tempObject;
}
}
}
Corrected code:
for (int outerLoop = 0; outerLoop < students.Length-1; outerLoop++)
{
for (int innerLoop = 0; innerLoop < students.Length-1; innerLoop++)
{
if (students[innerLoop] == null)
{
var tempObject = students[innerLoop+1];
students[innerLoop+1] = students[innerLoop];
students[innerLoop] = tempObject;
}
}
}
This will not sort your array but only drop the nulls at the bottom.
In fact you can do away with the temp variable:
for (int outerLoop = 0; outerLoop < students.Length-1; outerLoop++)
{
for (int innerLoop = 0; innerLoop < students.Length-1; innerLoop++)
{
if (students[innerLoop] == null)
{
students[innerLoop] = students[innerLoop+1];
students[innerLoop+1] = null;
}
}
}
Note:
C# 7 introduced tuples which enables swapping two variables without a temporary one:
int a = 10;
int b = 2;
(a, b) = (b, a);
This assigns b to a and a to b.
Try following. You have to test for outer being null and inner not being null :
for (int outerLoop = 0; outerLoop < students.Length - 1; outerLoop++)
{
for (int innerLoop = outerLoop + 1; innerLoop < students.Length; innerLoop++)
{
if ((students[outerLoop] == null) && (students[innerLoop] != null))
{
var tempObject = students[outerLoop];
students[outerLoop] = students[innerLoop];
students[innerLoop] = tempObject;
}
}
}
There's a faster, easier and stable approach with O(n) time complexity:
int at = 0;
for (int i = 0; i < students.Length; ++i)
if (students[i] != null)
students[at++] = students[i];
for (int i = at; i < students.Length; ++i)
students[i] = null;
However, if you insist on bubble sort: we can implement it in a bit different way
for (bool wrongOrder = true; wrongOrder;) {
wrongOrder = false;
for (int i = 1; i < students.Length; i++) {
if (students[i - 1] == null && students[i] != null) {
// At least 2 items has wrong order, swap them
var temp = students[i - 1];
students[i - 1] = students[i];
students[i] = temp;
wrongOrder = true;
}
}
}

Hackerrank: Climbing the Leaderboard

i have a deal with a hackerrank algorithm problem.
It works at all cases, except 6-7-8-9. It gives timeout error. I had spent so much time at this level. Someone saw where is problem?
static long[] climbingLeaderboard(long[] scores, long[] alice)
{
//long[] ranks = new long[scores.Length];
long[] aliceRanks = new long[alice.Length]; // same length with alice length
long lastPoint = 0;
long lastRank;
for (long i = 0; i < alice.Length; i++)
{
lastPoint = scores[0];
lastRank = 1;
bool isIn = false; // if never drop in if statement
for (long j = 0; j < scores.Length; j++)
{
if (lastPoint != scores[j]) //if score is not same, raise the variable
{
lastPoint = scores[j];
lastRank++;
}
if (alice[i] >= scores[j])
{
aliceRanks[i] = lastRank;
isIn = true;
break;
}
aliceRanks[i] = !isIn & j + 1 == scores.Length ? ++lastRank : aliceRanks[i]; //drop in here
}
}
return aliceRanks;
}
This problem can be solved in O(n) time, no binary search needed at all. First, we need to extract the most useful piece of data given in the problem statement, which is,
The existing leaderboard, scores, is in descending order.
Alice's scores, alice, are in ascending order.
An approach that makes this useful is to create two pointers, one at the start of alice array, let's call it "i", and the second is at the end of scores array, let's call it "j". We then loop until i reaches the end of alice array and at each iteration, we check for three main conditions. We increment i by one if alice[i] is less than scores[j] because the next element of alice may be also less than the current element of scores, or we decrement j if alice[i] is greater than scores[j] because we are sure that the next elements of alice are also greater than those elements discarded in scores. The last condition is that if alice[i] == scores[j], we only increment i.
I solved this question in C++, my goal here is to make you understand the algorithm, I think you can easily convert it to C# if you understand it. If there are any confusions, please tell me. Here is the code:
// Complete the climbingLeaderboard function below.
vector<int> climbingLeaderboard(vector<int> scores, vector<int> alice) {
int j = 1, i = 1;
// this is to remove duplicates from the scores vector
for(i =1; i < scores.size(); i++){
if(scores[i] != scores[i-1]){
scores[j++] = scores[i];
}
}
int size = scores.size();
for(i = 0; i < size-j; i++){
scores.pop_back();
}
vector<int> ranks;
i = 0;
j = scores.size()-1;
while(i < alice.size()){
if(j < 0){
ranks.push_back(1);
i++;
continue;
}
if(alice[i] < scores[j]){
ranks.push_back(j+2);
i++;
} else if(alice[i] > scores[j]){
j--;
} else {
ranks.push_back(j+1);
i++;
}
}
return ranks;
}
I think this may help you too:
vector is like an array list that resizes itself.
push_back() is inserting at the end of the vector.
pop_back() is removing from the end of the vector.
Here is my solution with c#
public static List<int> climbingLeaderboard(List<int> ranked, List<int> player)
{
List<int> result = new List<int>();
ranked = ranked.Distinct().ToList();
var pLength = player.Count;
var rLength = ranked.Count-1;
int j = rLength;
for (int i = 0; i < pLength; i++)
{
for (; j >= 0; j--)
{
if (player[i] == ranked[j])
{
result.Add(j + 1);
break;
}
else if(player[i] < ranked[j])
{
result.Add(j + 2);
break;
}
else if(player[i] > ranked[j]&&j==0)
{
result.Add(1);
break;
}enter code here
}
}
return result;
}
Here is a solution that utilizes BinarySearch. This method returns the index of the searched number in the array, or if the number is not found then it returns a negative number that is the bitwise complement of the index of the next element in the array. Binary search only works in sorted arrays.
public static int[] GetRanks(long[] scores, long[] person)
{
var defaultComparer = Comparer<long>.Default;
var reverseComparer = Comparer<long>.Create((x, y) => -defaultComparer.Compare(x, y));
var distinctOrderedScores = scores.Distinct().OrderBy(i => i, reverseComparer).ToArray();
return person
.Select(i => Array.BinarySearch(distinctOrderedScores, i, reverseComparer))
.Select(pos => (pos >= 0 ? pos : ~pos) + 1)
.ToArray();
}
Usage example:
var scores = new long[] { 100, 100, 50, 40, 40, 20, 10 };
var alice = new long[] { 5, 25, 50, 120 };
var ranks = GetRanks(scores, alice);
Console.WriteLine($"Ranks: {String.Join(", ", ranks)}");
Output:
Ranks: 6, 4, 2, 1
I was bored so i gave this a go with Linq and heavily commented it for you,
Given
public static IEnumerable<int> GetRanks(long[] scores, long[] person)
// Convert scores to a tuple
=> scores.Select(s => (scores: s, isPerson: false))
// convert persons score to a tuple and concat
.Concat(person.Select(s => (scores: s, isPerson: true)))
// Group by scores
.GroupBy(x => x.scores)
// order by score
.OrderBy(x => x.Key)
// select into an indexable tuple so we know everyones rank
.Select((groups, i) => (rank: i, groups))
// Filter the person
.Where(x => x.groups.Any(y => y.isPerson))
// select the rank
.Select(x => x.rank);
Usage
static void Main(string[] args)
{
var scores = new long[]{1, 34, 565, 43, 44, 56, 67};
var alice = new long[]{578, 40, 50, 67, 6};
var ranks = GetRanks(scores, alice);
foreach (var rank in ranks)
Console.WriteLine(rank);
}
Output
1
3
6
8
10
Based on the given constraint brute-force solution will not be efficient for the problem.
you have to optimize your code and the key part here is to look up for exact place which can be effectively done by using binary search.
Here is the solution using binary search:-
static int[] climbingLeaderboard(int[] scores, int[] alice) {
int n = scores.length;
int m = alice.length;
int res[] = new int[m];
int[] rank = new int[n];
rank[0] = 1;
for (int i = 1; i < n; i++) {
if (scores[i] == scores[i - 1]) {
rank[i] = rank[i - 1];
} else {
rank[i] = rank[i - 1] + 1;
}
}
for (int i = 0; i < m; i++) {
int aliceScore = alice[i];
if (aliceScore > scores[0]) {
res[i] = 1;
} else if (aliceScore < scores[n - 1]) {
res[i] = rank[n - 1] + 1;
} else {
int index = binarySearch(scores, aliceScore);
res[i] = rank[index];
}
}
return res;
}
private static int binarySearch(int[] a, int key) {
int lo = 0;
int hi = a.length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] == key) {
return mid;
} else if (a[mid] < key && key < a[mid - 1]) {
return mid;
} else if (a[mid] > key && key >= a[mid + 1]) {
return mid + 1;
} else if (a[mid] < key) {
hi = mid - 1;
} else if (a[mid] > key) {
lo = mid + 1;
}
}
return -1;
}
You can refer to this link for a more detailed video explanation.
static int[] climbingLeaderboard(int[] scores, int[] alice) {
int[] uniqueScores = IntStream.of(scores).distinct().toArray();
int [] rank = new int [alice.length];
int startIndex=0;
for(int j=alice.length-1; j>=0;j--) {
for(int i=startIndex; i<=uniqueScores.length-1;i++) {
if (alice[j]<uniqueScores[uniqueScores.length-1]){
rank[j]=uniqueScores.length+1;
break;
}
else if(alice[j]>=uniqueScores[i]) {
rank[j]=i+1;
startIndex=i;
break;
}
else{continue;}
}
}
return rank;
}
My solution in javascript for climbing the Leaderboard Hackerrank problem. The time complexity of the problem can be O(i+j), i is the length of scores and j is the length of alice. The space complexity is O(1).
// Complete the climbingLeaderboard function below.
function climbingLeaderboard(scores, alice) {
const ans = [];
let count = 0;
// the alice array is arranged in ascending order
let j = alice.length - 1;
for (let i = 0 ; i < scores.length ; i++) {
const score = scores[i];
for (; j >= 0 ; j--) {
if (alice[j] >= score) {
// if higher than score
ans.unshift(count+1);
} else if (i === scores.length - 1) {
// if smallest
ans.unshift(count+2);
} else {
break;
}
}
// actual rank of the score in leaderboard
if (score !== scores[i-1]) {
count++;
}
}
return ans;
}
Here is my solution
List<int> distinct = null;
List<int> rank = new List<int>();
foreach (int item in player)
{
ranked.Add(item);
ranked.Sort();
ranked.Reverse();
distinct = ranked.Distinct().ToList();
for (int i = 0; i < distinct.Count; i++)
{
if (item == distinct[i])
{
rank.Add(i + 1);
break;
}
}
}
return rank;
This can be modified by removing the inner for loop also
List<int> distinct = null;
List<int> rank = new List<int>();
foreach (int item in player)
{
ranked.Add(item);
ranked.Sort();
ranked.Reverse();
distinct = ranked.Distinct().ToList();
var index = ranked.FindIndex(x => x == item);
rank.Add(index + 1);
}
return rank;
This is my solution in c# for Hackerrank Climbing the Leaderboard based on C++ answer here.
public static List<int> climbingLeaderboard(List<int> ranked, List<int> player)
{
List<int> _ranked = new List<int>();
_ranked.Add(ranked[0]);
for(int a=1; a < ranked.Count(); a++)
if(_ranked[_ranked.Count()-1] != ranked[a])
_ranked.Add(ranked[a]);
int j = _ranked.Count()-1;
int i = 0;
while(i < player.Count())
{
if(j < 0)
{
player[i] = 1;
i++;
continue;
}
if(player[i] < _ranked[j])
{
player[i] = j+2;
i++;
}
else
if(player[i] == _ranked[j])
{
player[i] = j+1;
i++;
}
else
{
j--;
}
}
return player;
}
My solution in Java for climbing the Leaderboard Hackerrank problem.
// Complete the climbingLeaderboard function below.
static int[] climbingLeaderboard(int[] scores, int[] alice) {
Arrays.sort(scores);
HashSet<Integer> set = new HashSet<Integer>();
int[] ar = new int[alice.length];
int sc = 0;
for(int i=0; i<alice.length; i++){
sc = 1;
set.clear();
for(int j=0; j<scores.length; j++){
if(alice[i] < scores[j] && !set.contains(scores[j])){
sc++;
set.add(scores[j]);
}
}
ar[i] = sc;
}return ar;
}

I want to know what is wrong with my minmax algorithm for connect4 game?

iam try to write min max algorithm for connect4 game but when i run this code it go in infinte loop and not return move or result, so i want a help to know what is wrong with it , i work in board of 6*7 cells
private int score()
{
int x = check_Winner();//i checked it and it work right ot return 1 if player 1 win or 2 if pc win or 0 in tie
if (x == 1) return 10;
else if (x == 2) return -10;
else return 0;
}
public int MinMax(int player_num)
{
List<pair> possiple_moves = get_possible_moves();// it works will
int score_so_far = score();
if (possiple_moves.Count == 0 || score_so_far != 0)
return score_so_far;
List<int> scores = new List<int>();
List<pair> moves = new List<pair>();
foreach (pair move in possiple_moves)
{
if (player_num == 1)
{
cells[move.x, move.y].player_num = 1;
scores.Add(MinMax(2));
}
else
{
cells[move.x, move.y].player_num = 2;
scores.Add(MinMax(1));
}
moves.Add(move);
cells[move.x, move.y].player_num = 0;
}
if (player_num == 1)
{
int max_score_indx = 0, tmp = int.MinValue;
for (int i = 0; i < scores.Count; i++)
{
if (scores[i] > tmp)
{
tmp = scores[i];
max_score_indx = i;
}
}
pc_choise = moves[max_score_indx];
return scores[max_score_indx];
}
//==================
else
{
int min_score_indx = 0, tmp = int.MaxValue;
for (int i = 0; i < scores.Count; i++)
{
if (scores[i] < tmp)
{
tmp = scores[i];
min_score_indx = i;
}
}
pc_choise = moves[min_score_indx];
return scores[min_score_indx];
}
}
#Equalsk is right, I believe: you are calling MinMax from within the foreach loop, before you reach the code that evaluates the stop conditions. So providing that the method get_possible_moves returns something different to Null, you will get stuck in foreach --> MinMax --> foreach --> MinMax --> foreach...

Minimax Algorithm

ok my problem has changed my problem now is that im trying to use the minimax algorithm like that website explains http://neverstopbuilding.com/minimax
and it gives me this error: "Argument out of range exception"
why is it happening i cant tell why the exception happens
this is what i did:
int MiniMax(Seed[,] board, Seed currPlayer)
{
if (checkBoard1(this.board) != -1) return score();
List<int> scores = new List<int>();
List<Vector2> moves = generateMoves();
for (int i = 0; i < moves.Count; i++)
{
if (currPlayer == Seed.NOUGHT)
currPlayer = Seed.CROSS;
else
currPlayer = Seed.NOUGHT;
Seed[,] possibleBoard = getPossibleBoard(moves[i]);
scores.Add(MiniMax(possibleBoard, currPlayer));
}
if(currPlayer == Seed.NOUGHT)
{
int max_score_index = getMaxIndexFromList(scores);
choice = (Vector2)moves[max_score_index];
return scores[max_score_index];
}
else
{
int min_score_index = getMinIndexFromList(scores);
choice = (Vector2)moves[min_score_index];
return scores[min_score_index];
}
}
int getMinIndexFromList(List<int> list)
{
int min = list[0], minIndex = 0;
for (int i = 1; i < list.Count; i++)
{
if (list[i] < min)
{
min = list[i];
minIndex = i;
}
}
return minIndex;
}

c# permutation without repetition when order is important [duplicate]

I have a list of Offers, from which I want to create "chains" (e.g. permutations) with limited chain lengths.
I've gotten as far as creating the permutations using the Kw.Combinatorics project.
However, the default behavior creates permutations in the length of the list count. I'm not sure how to limit the chain lengths to 'n'.
Here's my current code:
private static List<List<Offers>> GetPerms(List<Offers> list, int chainLength)
{
List<List<Offers>> response = new List<List<Offers>>();
foreach (var row in new Permutation(list.Count).GetRows())
{
List<Offers> innerList = new List<Offers>();
foreach (var mix in Permutation.Permute(row, list))
{
innerList.Add(mix);
}
response.Add(innerList);
innerList = new List<Offers>();
}
return response;
}
Implemented by:
List<List<AdServer.Offers>> lst = GetPerms(offers, 2);
I'm not locked in KWCombinatorics if someone has a better solution to offer.
Here's another implementation which I think should be faster than the accepted answer (and it's definitely less code).
public static IEnumerable<IEnumerable<T>> GetVariationsWithoutDuplicates<T>(IList<T> items, int length)
{
if (length == 0 || !items.Any()) return new List<List<T>> { new List<T>() };
return from item in items.Distinct()
from permutation in GetVariationsWithoutDuplicates(items.Where(i => !EqualityComparer<T>.Default.Equals(i, item)).ToList(), length - 1)
select Prepend(item, permutation);
}
public static IEnumerable<IEnumerable<T>> GetVariations<T>(IList<T> items, int length)
{
if (length == 0 || !items.Any()) return new List<List<T>> { new List<T>() };
return from item in items
from permutation in GetVariations(Remove(item, items).ToList(), length - 1)
select Prepend(item, permutation);
}
public static IEnumerable<T> Prepend<T>(T first, IEnumerable<T> rest)
{
yield return first;
foreach (var item in rest) yield return item;
}
public static IEnumerable<T> Remove<T>(T item, IEnumerable<T> from)
{
var isRemoved = false;
foreach (var i in from)
{
if (!EqualityComparer<T>.Default.Equals(item, i) || isRemoved) yield return i;
else isRemoved = true;
}
}
On my 3.1 GHz Core 2 Duo, I tested with this:
public static void Test(Func<IList<int>, int, IEnumerable<IEnumerable<int>>> getVariations)
{
var max = 11;
var timer = System.Diagnostics.Stopwatch.StartNew();
for (int i = 1; i < max; ++i)
for (int j = 1; j < i; ++j)
getVariations(MakeList(i), j).Count();
timer.Stop();
Console.WriteLine("{0,40}{1} ms", getVariations.Method.Name, timer.ElapsedMilliseconds);
}
// Make a list that repeats to guarantee we have duplicates
public static IList<int> MakeList(int size)
{
return Enumerable.Range(0, size/2).Concat(Enumerable.Range(0, size - size/2)).ToList();
}
Unoptimized
GetVariations 11894 ms
GetVariationsWithoutDuplicates 9 ms
OtherAnswerGetVariations 22485 ms
OtherAnswerGetVariationsWithDuplicates 243415 ms
With compiler optimizations
GetVariations 9667 ms
GetVariationsWithoutDuplicates 8 ms
OtherAnswerGetVariations 19739 ms
OtherAnswerGetVariationsWithDuplicates 228802 ms
You're not looking for a permutation, but for a variation. Here is a possible algorithm. I prefer iterator methods for functions that can potentially return very many elements. This way, the caller can decide if he really needs all elements:
IEnumerable<IList<T>> GetVariations<T>(IList<T> offers, int length)
{
var startIndices = new int[length];
var variationElements = new HashSet<T>(); //for duplicate detection
while (startIndices[0] < offers.Count)
{
var variation = new List<T>(length);
var valid = true;
for (int i = 0; i < length; ++i)
{
var element = offers[startIndices[i]];
if (variationElements.Contains(element))
{
valid = false;
break;
}
variation.Add(element);
variationElements.Add(element);
}
if (valid)
yield return variation;
//Count up the indices
startIndices[length - 1]++;
for (int i = length - 1; i > 0; --i)
{
if (startIndices[i] >= offers.Count)
{
startIndices[i] = 0;
startIndices[i - 1]++;
}
else
break;
}
variationElements.Clear();
}
}
The idea for this algorithm is to use a number in offers.Count base. For three offers, all digits are in the range 0-2. We then basically increment this number step by step and return the offers that reside at the specified indices. If you want to allow duplicates, you can remove the check and the HashSet<T>.
Update
Here is an optimized variant that does the duplicate check on the index level. In my tests it is a lot faster than the previous variant:
IEnumerable<IList<T>> GetVariations<T>(IList<T> offers, int length)
{
var startIndices = new int[length];
for (int i = 0; i < length; ++i)
startIndices[i] = i;
var indices = new HashSet<int>(); // for duplicate check
while (startIndices[0] < offers.Count)
{
var variation = new List<T>(length);
for (int i = 0; i < length; ++i)
{
variation.Add(offers[startIndices[i]]);
}
yield return variation;
//Count up the indices
AddOne(startIndices, length - 1, offers.Count - 1);
//duplicate check
var check = true;
while (check)
{
indices.Clear();
for (int i = 0; i <= length; ++i)
{
if (i == length)
{
check = false;
break;
}
if (indices.Contains(startIndices[i]))
{
var unchangedUpTo = AddOne(startIndices, i, offers.Count - 1);
indices.Clear();
for (int j = 0; j <= unchangedUpTo; ++j )
{
indices.Add(startIndices[j]);
}
int nextIndex = 0;
for(int j = unchangedUpTo + 1; j < length; ++j)
{
while (indices.Contains(nextIndex))
nextIndex++;
startIndices[j] = nextIndex++;
}
break;
}
indices.Add(startIndices[i]);
}
}
}
}
int AddOne(int[] indices, int position, int maxElement)
{
//returns the index of the last element that has not been changed
indices[position]++;
for (int i = position; i > 0; --i)
{
if (indices[i] > maxElement)
{
indices[i] = 0;
indices[i - 1]++;
}
else
return i;
}
return 0;
}
If I got you correct here is what you need
this will create permutations based on the specified chain limit
public static List<List<T>> GetPerms<T>(List<T> list, int chainLimit)
{
if (list.Count() == 1)
return new List<List<T>> { list };
return list
.Select((outer, outerIndex) =>
GetPerms(list.Where((inner, innerIndex) => innerIndex != outerIndex).ToList(), chainLimit)
.Select(perms => (new List<T> { outer }).Union(perms).Take(chainLimit)))
.SelectMany<IEnumerable<IEnumerable<T>>, List<T>>(sub => sub.Select<IEnumerable<T>, List<T>>(s => s.ToList()))
.Distinct(new PermComparer<T>()).ToList();
}
class PermComparer<T> : IEqualityComparer<List<T>>
{
public bool Equals(List<T> x, List<T> y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(List<T> obj)
{
return (int)obj.Average(o => o.GetHashCode());
}
}
and you'll call it like this
List<List<AdServer.Offers>> lst = GetPerms<AdServer.Offers>(offers, 2);
I made this function is pretty generic so you may use it for other purpose too
eg
List<string> list = new List<string>(new[] { "apple", "banana", "orange", "cherry" });
List<List<string>> perms = GetPerms<string>(list, 2);
result

Categories

Resources