Build up List from another List - c#

I've got a list of Players. Each Player has a Marketvalue. I need to build up a second list which iterates through the player list and builds up a team. The tricky thing is the new team should have at least 15 players and a maximum Marketvalue of 100 Mio +/- 1%.
Does anyone know how to do that elegantly?
private Result<List<Player>> CreateRandomTeam(List<Player> players, int startTeamValue)
{
// start formation 4-4-2
// Threshold tw 20 mio defender 40 mio Midfielder 40 Mio Striker 50 Mio
var playerKeeperList = players.FindAll(p => p.PlayerPosition == PlayerPosition.Keeper);
var playerDefenderList = players.FindAll(p => p.PlayerPosition == PlayerPosition.Defender);
var playerMidfieldList = players.FindAll(p => p.PlayerPosition == PlayerPosition.Midfield);
var playerStrikerList = players.FindAll(p => p.PlayerPosition == PlayerPosition.Striker);
List<Player> keeperPlayers = AddRandomPlayers(playerKeeperList, 2, 0, 20000000);
List<Player> defenderPlayers = AddRandomPlayers(playerDefenderList, 4, 0, 40000000);
List<Player> midfieldPlayers = AddRandomPlayers(playerMidfieldList, 4, 0, 40000000);
List<Player> strikerPlayers = AddRandomPlayers(playerStrikerList, 2, 0, 50000000);
List<Player> team = new List<Player>();
team.AddRange(keeperPlayers);
team.AddRange(defenderPlayers);
team.AddRange(midfieldPlayers);
team.AddRange(strikerPlayers);
var currentTeamValue = team.Sum(s => s.MarketValue);
var budgetLeft = startTeamValue - currentTeamValue;
players.RemoveAll(p => team.Contains(p));
var player1 = AddRandomPlayers(players, 2, 0, budgetLeft);
team.AddRange(player1);
players.RemoveAll(p => player1.Contains(p));
currentTeamValue = team.Sum(t => t.MarketValue);
budgetLeft = startTeamValue - currentTeamValue;
var player2 = players.Aggregate((x, y) => Math.Abs(x.MarketValue - budgetLeft) < Math.Abs(y.MarketValue - budgetLeft) ? x : y);
team.Add(player2);
players.Remove(player2);
return Result<List<Player>>.Ok(team);
}
private static List<Player> AddRandomPlayers(List<Player> players, int playerCount, double minMarketValue, double threshold)
{
// TODO: AYI Implement Random TeamName assign logic
Random rnd = new Random();
var team = new List<Player>();
double assignedTeamValue = 0;
while (team.Count < playerCount)
{
var index = rnd.Next(players.Count);
var player = players[index];
if ((assignedTeamValue + player.MarketValue) <= threshold)
{
team.Add(player);
players.RemoveAt(index);
assignedTeamValue += player.MarketValue;
}
}
return team;
}`

This isn't really a C# question so much as an algorithm question, so there may be a better place for it. AIUI, you want to pick 15 numbers from a list, such that the total adds up to 99-101.
It's likely that there are many solutions, all equally valid.
I think you could do it like this:
Build a list of the 14 cheapest items.
Pick the highest value, so long as the remaining space is greater than the total of the 14 cheapest.
Repeat the above, skipping any players that won't fit.
Fill the remaining places with players from the 'cheapest' list.
This will probably give you a team containing the best and worst players, and one middle-ranking player that just fits.
If you want to do some more research, this sounds like a variant of the coin change problem.

Just to show my solution if someone need's it.
var selection = new EliteSelection();
var crossover = new OnePointCrossover(0);
var mutation = new UniformMutation(true);
var fitness = new TeamFitness(players, startTeamValue);
var chromosome = new TeamChromosome(15, players.Count);
var population = new Population(players.Count, players.Count, chromosome);
var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
{
Termination = new GenerationNumberTermination(100)
};
ga.Start();
var bestChromosome = ga.BestChromosome as TeamChromosome;
var team = new List<Player>();
if (bestChromosome != null)
{
for (int i = 0; i < bestChromosome.Length; i++)
{
team.Add(players[(int) bestChromosome.GetGene(i).Value]);
}
// Remove assigned player to avoid duplicate assignment
players.RemoveAll(p => team.Contains(p));
return Result<List<Player>>.Ok(team);
}
return Result<List<Player>>.Error("Chromosome was null!");
There is a fitness method which handles the logic to get the best result.
class TeamFitness : IFitness
{
private readonly List<Player> _players;
private readonly int _startTeamValue;
private List<Player> _selected;
public TeamFitness(List<Player> players, int startTeamValue)
{
_players = players;
_startTeamValue = startTeamValue;
}
public double Evaluate(IChromosome chromosome)
{
double f1 = 9;
_selected = new List<Player>();
var indexes = new List<int>();
foreach (var gene in chromosome.GetGenes())
{
indexes.Add((int)gene.Value);
_selected.Add(_players[(int)gene.Value]);
}
if (indexes.Distinct().Count() < chromosome.Length)
{
return int.MinValue;
}
var sumMarketValue = _selected.Sum(s => s.MarketValue);
var targetValue = _startTeamValue;
if (sumMarketValue < targetValue)
{
f1 = targetValue - sumMarketValue;
}else if (sumMarketValue > targetValue)
{
f1 = sumMarketValue - targetValue;
}
else
{
f1 = 0;
}
var keeperCount = _selected.Count(s => s.PlayerPosition == PlayerPosition.Keeper);
var strikerCount = _selected.Count(s => s.PlayerPosition == PlayerPosition.Striker);
var defCount = _selected.Count(s => s.PlayerPosition == PlayerPosition.Defender);
var middleCount = _selected.Count(s => s.PlayerPosition == PlayerPosition.Midfield);
var factor = 0;
var penaltyMoney = 10000000;
if (keeperCount > 2)
{
factor += (keeperCount - 2) * penaltyMoney;
}
if (keeperCount == 0)
{
factor += penaltyMoney;
}
if (strikerCount < 2)
{
factor += (2 - strikerCount) * penaltyMoney;
}
if (middleCount < 4)
{
factor += (4 - middleCount) * penaltyMoney;
}
if (defCount < 4)
{
factor += (4 - defCount) * penaltyMoney;
}
return 1.0 - (f1 + factor);
}
}

Related

How can the rows of a list be divided into the largest possible parts (according to the row limit) and the most equal row packages?

RowLimit: 4
Example 1:
List with 10 rows
The desired result: 4, 3, 3
Example 2:
List with 9 rows
The desired result: 3, 3, 3
Example 3:
List with 8 rows
The desired result: 4, 4
Example 4:
List with 7 rows
The desired result: 4, 3
At the moment I simply divide the rows according to the rows limit
public List<List<string>> TextWithRowLimit(List<string> TextRows, int RowLimit)
{
List<List<string>> list = new List<List<string>>();
int RowLimitCounter = 1;
List<string> TextRowPackages = new List<string>();
for (int row = 0; row < TextRows.Count; ++row)
{
TextRowPackages.Add($"{TextRows[row]} ");
if (RowLimitCounter == RowLimit)
{
list.Add(TextRowPackages);
RowLimitCounter = 0;
TextRowPackages = new List<string>();
}
RowLimitCounter++;
}
if(TextRowPackages.Count>0)
list.Add(TextRowPackages);
return list;
}
Probably not the prettiest code, but I think this will work for you.
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var initialList = Enumerable.Range(1, 10).Select(i => i.ToString()).ToList();
var limit = 4;
var bucketUtility = new BucketUtility();
var list = bucketUtility.TextWithRowLimit(initialList, limit);
}
}
public sealed class BucketUtility
{
public List<List<string>> TextWithRowLimit(List<string> textRows, int rowLimit)
{
var totalRowsCount = textRows.Count;
var remainder = textRows.Count % rowLimit;
var totalBucketsNeeded = remainder == 0 ? totalRowsCount / rowLimit : (totalRowsCount / rowLimit) + 1;
// calculate how many would fill buckets
var initialFillCount = totalBucketsNeeded * rowLimit;
// this can be negative
var remainingToFill = totalRowsCount - initialFillCount;
// size the buckets correctly
var buckets = SizeBuckets(totalBucketsNeeded, rowLimit, remainingToFill);
// assign text values to buckets
int skip = 0;
var result = buckets.Select((bucketSize, i) =>
{
var result = textRows.Select(t => t).Skip(skip).Take(bucketSize).ToList();
skip += bucketSize;
return result;
}).ToList();
return result;
}
private List<int> SizeBuckets(int totalBucketsNeeded, int rowLimit, int remainingToFill)
{
var totalBuckets = Enumerable.Range(0, totalBucketsNeeded).ToList();
var buckets = new List<int>();
for (int i = 0; i < totalBuckets.Count; i++)
{
int bucketSize = rowLimit;
if (remainingToFill > 0)
{
bucketSize++;
remainingToFill--;
}
if (remainingToFill < 0)
{
bucketSize--;
remainingToFill++;
}
buckets.Add(bucketSize);
}
// order them in correct order
return buckets.OrderByDescending(i => i).ToList();
}
}
Can run it here
https://dotnetfiddle.net/CxdHaO

Get two teams greatest lead throughout game

I have a Game that involves 2 teams. The Game has a List of ScoreEvents. Each ScoreEvent is a 1 point for the Team that scored. I need to know what the Max lead score was for each team (0 if they never had the lead). The ScoreEvents List is ordered by TimeSinceStart.
public class ScoreEvent
{
public int TeamId { get; set; }
public TimeSpan TimeSinceStart { get; set; }
}
public void GetMaxScoreLead()
{
var ScoreEvents = new List<ScoreEvent>
{
new ScoreEvent { TeamId = 0, TimeSinceStart = new TimeSpan(100)},
new ScoreEvent { TeamId = 0, TimeSinceStart = new TimeSpan(200)},
new ScoreEvent { TeamId = 0, TimeSinceStart = new TimeSpan(300)},
//Score at 300 ticks is 3-0 to TeamdId = 0
new ScoreEvent { TeamId = 1, TimeSinceStart = new TimeSpan(400)},
new ScoreEvent { TeamId = 1, TimeSinceStart = new TimeSpan(500)},
new ScoreEvent { TeamId = 1, TimeSinceStart = new TimeSpan(600)},
new ScoreEvent { TeamId = 1, TimeSinceStart = new TimeSpan(700)},
//Score at 700 ticks is a 3-4 to TeamId = 1
new ScoreEvent { TeamId = 0, TimeSinceStart = new TimeSpan(800)},
new ScoreEvent { TeamId = 0, TimeSinceStart = new TimeSpan(900)},
new ScoreEvent { TeamId = 0, TimeSinceStart = new TimeSpan(1000)},
new ScoreEvent { TeamId = 0, TimeSinceStart = new TimeSpan(1100)}
//Score at 1100 ticks is 7-4 to TeamId 0
};
}
So for the example above the answers for greatest lead per team would be:
TeamId (0) = 3 greatest lead
TeamId (1) = 1 greatest lead
EDIT: Code that I've got to. I know I need to keep track of the current score somewhere.
var teamZeroLargestLead = 0;
var teamOneLargestLead = 0;
var internalTeamZeroLargestLead = 0;
var internalTeamOneLargestLead = 0;
foreach (var scoreEvent in scoreEvents.OrderBy(x => x.TimeSinceStart))
{
if (scoreEvent.TeamId == 0)
{
if (internalTeamOneLargestLead > teamOneLargestLead)
{
teamOneLargestLead = internalTeamOneLargestLead;
internalTeamOneLargestLead = 0;
}
internalTeamZeroLargestLead += 1;
}
else
{
if(internalTeamZeroLargestLead > teamZeroLargestLead)
{
teamZeroLargestLead = internalTeamZeroLargestLead;
internalTeamZeroLargestLead = 0;
}
internalTeamOneLargestLead += 1;
}
}
I've slightly updated and simplified your algorithm with foreach loop and now it returns the correct result - teamZeroLead is 3, teamOneLead is 1.
var teamZeroLead = 0;
var teamOneLead = 0;
var teamZeroScore = 0;
var teamOneScore = 0;
foreach (var scoreEvent in scoreEvents.OrderBy(x => x.TimeSinceStart))
{
if (scoreEvent.TeamId == 0)
{
teamZeroScore++;
teamZeroLead = Math.Max(teamZeroLead, teamZeroScore - teamOneScore);
}
else
{
teamOneScore++;
teamOneLead = Math.Max(teamOneLead, teamOneScore - teamZeroScore);
}
}
At every loop iteration you are calculating the current score of every team, then calculate the lead value and assign it to the result value, if it's greater then previously calculated.
The same logic can be written using Aggregate method and value tuple, you can choose what is more readable and convenient for you
var result = scoreEvents.Aggregate((teamZeroLead: 0, teamOneLead: 0, teamZeroScore: 0, teamOneScore: 0),
(scores, scoreEvent) =>
{
if (scoreEvent.TeamId == 0)
{
scores.teamZeroScore++;
scores.teamZeroLead = Math.Max(scores.teamZeroLead, scores.teamZeroScore - scores.teamOneScore);
}
else
{
scores.teamOneScore++;
scores.teamOneLead = Math.Max(scores.teamOneLead, scores.teamOneScore - scores.teamZeroScore);
}
return scores;
});
After execution you can get the result values using result.teamZeroLead and result.teamOneLead
var leftTeamId = ScoreEvents.First().TeamId
var res = ScoreEvents
.OrderBy(x => x.TimeSinceStart)
.Aggregate(
(max: 0, min: 0, curr: 0),
(acc, currSE) => {
var curr = currSE.TeamId == leftTeamId
? acc.curr +1
: acc.curr - 1;
if(curr > acc.max)
{
return (curr, acc.min, curr);
}
else if (curr < acc.min)
{
return (acc.max, curr, curr);
}
return (acc.max, acc.min, curr);
});
And for "left" team with id leftTeamId you use res.max for "right" team you use Math.Abs(res.min):
TeamId (0) = res.max greatest lead
TeamId (1) = Math.Abs(res.min) greatest lead
I did not get rightTeamId, cause in theory only one team could have scored (but assumed that at least one did =).
Since there are only two teams see if this approach satisfies your needs.
int team1Score = 0;
int team2Score = 0;
int maximumLead = 0;
int maximumLeadTeamId = -1;
for (int i = 0; i < ScoreEvents.Count; i++)
{
if (ScoreEvents[i].TeamId == 0)
{
team1Score++;
}
else
{
team2Score++;
}
int currentLead = Math.Abs(team1Score - team2Score);
if (currentLead > maximumLead)
{
maximumLead = currentLead;
maximumLeadTeamId = ScoreEvents[i].TeamId;
}
}
maximumLeadTeamId is the Id of the team with maximum lead throughout the game and maximumLead is the maximum goals difference between the two teams.
You can use this to get a dictionary of team id to score at the specified timespan:
public static Dictionary<int, int> GetMaxScoreLead(IEnumerable<ScoreEvent> scoreEvents, TimeSpan time)
{
var scoreDictionary = new Dictionary<int, int>();
var grouping = scoreEvents.Where(e => e.TimeSinceStart <= time).GroupBy(e => e.TeamId);
foreach (var group in grouping)
{
scoreDictionary.Add(group.Key, group.Count());
}
return scoreDictionary;
}
This code does not depend on the number of teams. You can trivially determine the winning team from this dictionary structure. For example:
var winningTeam = getScores.OrderByDescending(x => x.Value).FirstOrDefault();

Shuffling list of competitors, each month different competitor

for my friends sportscompetition, each player has to play 1 game a month against an other player. Now if i have a list of 20 players or so its not that hard to randomize the first month so i have 10 matches.
All the months after that though i'm not sure how to get the randomizer working so they won't be matched against a player they have played against.
Right now i made an sql database with Players(Name, (int)Id, Email) , Matches(Id, Player1ID, Player2ID)
I'm thinking for a randomize of the list and checking if each match doesn't contain 2 id's from a match in the database. And if 1 match does, redo the entire randomize of that month.
But i'm not sure if thats the best way.
This is what i have so far, i have yet to test it after i add some 'leden' and 'matches' to my database.
private void MaakMatchen(Maand maand)
{
List<Lid> leden = new List<Lid>();
var dbManager = new Manager();
using (var conGildenhof = dbManager.GetConnection())
{
using (var comLeden = conGildenhof.CreateCommand())
{
comLeden.CommandType = CommandType.Text;
comLeden.CommandText = "select * from dbo.Leden";
conGildenhof.Open();
using (var alleleden = comLeden.ExecuteReader())
{
Int32 voornaamPos = alleleden.GetOrdinal("Voornaam");
Int32 familienaamPos = alleleden.GetOrdinal("Familienaam");
Int32 LidNummerPos = alleleden.GetOrdinal("LidNummer");
while (alleleden.Read())
{
leden.Add(new Classes.Lid(alleleden.GetString(voornaamPos), alleleden.GetString(familienaamPos), alleleden.GetInt32(LidNummerPos)));
}
leden = Randomize(leden);
}
}
using (var comInsert = conGildenhof.CreateCommand())
{
comInsert.CommandType = CommandType.Text;
comInsert.CommandText = "Insert into dbo.Matches (Lid1Id, Lid2Id, Maand) values (#lid1, #lid2, #maand)";
var parLid1 = comInsert.CreateParameter();
parLid1.ParameterName = "#lid1";
comInsert.Parameters.Add(parLid1);
var parLid2 = comInsert.CreateParameter();
parLid2.ParameterName = "#lid2";
comInsert.Parameters.Add(parLid2);
var parMaand = comInsert.CreateParameter();
parMaand.ParameterName = "#maand";
comInsert.Parameters.Add(parMaand);
int lengte = leden.Count();
for (int i = 0; i < lengte; i = i + 2)
{
parLid1.Value = leden[i].LidNummer;
parLid2.Value = leden[i + 1].LidNummer;
parMaand.Value = (int)maand;
comInsert.ExecuteNonQuery();
}
}
}
}
private List<Lid> Randomize(List<Lid> leden)
{
for (int i=0;i<100;i++)
{
leden = Shuffle(leden);
}
int temp = CheckUp(leden);
while (temp != 100)
{
leden = Shuffle(leden, temp);
temp = CheckUp(leden);
}
return leden;
}
private List<Lid> Shuffle(List<Lid> leden)
{
Random rnd = new Random();
int a = rnd.Next(1, leden.Count() + 1);
int b = rnd.Next(1, leden.Count() + 1);
var temp = new Lid();
temp = leden[a];
leden[a] = leden[b];
leden[b] = temp;
return leden;
}
private List<Lid> Shuffle(List<Lid> leden, int id)
{
Random rnd = new Random();
int a = rnd.Next(1, leden.Count() + 1);
int b = id;
var temp = new Lid();
temp = leden[a];
leden[a] = leden[b];
leden[b] = temp;
return leden;
}
private int CheckUp(List<Lid> leden)
{
int lengte = leden.Count();
List<Matches> matches = new List<Matches>();
var dbManager = new Manager();
using (var conGildenhof = dbManager.GetConnection())
{
using (var comMatches = conGildenhof.CreateCommand())
{
comMatches.CommandType = CommandType.Text;
comMatches.CommandText = "select * from dbo.Matches";
conGildenhof.Open();
using (var allematches = comMatches.ExecuteReader())
{
Int32 lid1Pos = allematches.GetOrdinal("Lid1Id");
Int32 lid2Pos = allematches.GetOrdinal("Lid2Id");
Int32 maandPos = allematches.GetOrdinal("Maand");
while (allematches.Read())
{
matches.Add(new Classes.Matches(allematches.GetInt32(lid1Pos), allematches.GetInt32(lid2Pos), (Maand)allematches.GetInt32(maandPos)));
}
}
}
}
for (int i=0;i<lengte;i=i+2)
{
foreach (Matches match in matches)
{
if (leden[i].LidNummer == match.Lid1Id)
{
if (leden[i + 1].LidNummer == match.Lid2Id)
return leden[i].LidNummer;
}
if (leden[i].LidNummer == match.Lid2Id)
{
if (leden[i + 1].LidNummer == match.Lid1Id)
return leden[i].LidNummer;
}
}
}
return 100;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var maand = new int();
int.TryParse(TextBoxMaand.Text, out maand);
if (maand == 0)
TextBoxMaand.Text = "GETAL!";
else
{
MaakMatchen((Maand)maand);
}
}
I would shuffle the players first and create the matches in a second iteration
List<Player> players = GetPlayers();
Random _rnd = new Random();
// shuffle players
players = players.OrderBy(_ => _rnd.Next()).ToList();
// create matches
var matches = players.Take(players.Count / 2).Zip(players.Skip(players.Count / 2), (p1, p2) => new Match(p1,p2));
https://dotnetfiddle.net/sGxbx4

Find values which sum to 0 in Excel with many items

I have to find each subset in a enough big list, 500/1000 items that are positive and negative and are decimal, whiches sum to 0. I'm not an expert so I read many and many articles and solutions, and then I wrote my code. Datas comes from Excel worksheet and I would to mark found sums there.
Code works in this way:
Initally I find all pair that sum to 0
Then I put the remains sums into a list and take the combinations within 20 items, beacause I know the it is not possible bigger combination sum to 0
In these combinations I search if one combinations sums to 0 and save it in result list, else save sum in dictionary as key and then I'll search if dictionary contains next sums (so I check pairs of these subsets)
I keep track of the index so I can reach and modify the cells
To found solutions is enough fast but when I want elaborate the results in Excel become really slow. I don't take care about find all solutions but I want to find as max as possible in a short time.
What do you think about this solution? How can I improve the speed? How can I skip easly the sums that are already taken? And how can mark the cells fastly in my worksheet, beacuse now here is the bottleneck of the program?
I hope it is enough clear :) Thanks to everybody for any help
Here my code of the combination's part:
List<decimal> listDecimal = new List<decimal>();
List<string> listRange = new List<string>();
List<decimal> resDecimal = new List<decimal>();
List<IEnumerable<decimal>> resDecimal2 = new List<IEnumerable<decimal>>();
List<IEnumerable<string>> resIndex = new List<IEnumerable<string>>();
Dictionary<decimal, int> dicSumma = new Dictionary<decimal, int>();
foreach (TarkistaSummat.CellsRemain el in list)
{
decimal sumDec = Convert.ToDecimal(el.Summa.Value);
listDecimal.Add(sumDec);
string row = el.Summa.Cells.Row.ToString();
string col = el.Summa.Cells.Column.ToString();
string range = el.Summa.Cells.Row.ToString() + ":" + el.Summa.Cells.Column.ToString();
listRange.Add(range);
}
var subsets = new List<IEnumerable<decimal>> { new List<decimal>() };
var subsetsIndex = new List<IEnumerable<string>> { new List<string>() };
for (int i = 0; i < list.Count; i++)
{
if (i > 20)
{
List<IEnumerable<decimal>> parSubsets = subsets.GetRange(i, i + 20);
List<IEnumerable<string>> parSubsetsIndex = subsetsIndex.GetRange(i, i + 20);
var Z = parSubsets.Select(x => x.Concat(new[] { listDecimal[i] }));
//var Zfound = Z.Select(x => x).Where(w => w.Sum() ==0);
subsets.AddRange(Z.ToList());
var Zr = parSubsetsIndex.Select(x => x.Concat(new[] { listRange[i] }));
subsetsIndex.AddRange(Zr.ToList());
}
else
{
var T = subsets.Select(y => y.Concat(new[] { listDecimal[i] }));
//var Tfound = T.Select(x => x).Where(w => w.Sum() == 0);
//resDecimal2.AddRange(Tfound);
//var TnotFound = T.Except(Tfound);
subsets.AddRange(T.ToList());
var Tr = subsetsIndex.Select(y => y.Concat(new[] { listRange[i] }));
subsetsIndex.AddRange(Tr.ToList());
}
for (int i = 0; i < subsets.Count; i++)
{
decimal sumDec = subsets[i].Sum();
if (sumDec == 0m)
{
resDecimal2.Add(subsets[i]);
resIndex.Add(subsetsIndex[i]);
continue;
}
else
{
if(dicSumma.ContainsKey(sumDec * -1))
{
dicSumma.TryGetValue(sumDec * -1, out int index);
IEnumerable<decimal> addComb = subsets[i].Union(subsets[index]);
resDecimal2.Add(addComb);
var indexComb = subsetsIndex[i].Union(subsetsIndex[index]);
resIndex.Add(indexComb);
}
else
{
if(!dicSumma.ContainsKey(sumDec))
{
dicSumma.Add(sumDec, i);
}
}
}
}
for (int i = 0; i < resIndex.Count; i++)
{
//List<Range> ranges = new List<Range>();
foreach(string el in resIndex[i])
{
string[] split = el.Split(':');
Range cell = actSheet.Cells[Convert.ToInt32(split[0]), Convert.ToInt32(split[1])];
cell.Interior.ColorIndex = 6;
}
}
}

Determining value jumps in List<T>

I have a class:
public class ShipmentInformation
{
public string OuterNo { get; set; }
public long Start { get; set; }
public long End { get; set; }
}
I have a List<ShipmentInformation> variable called Results.
I then do:
List<ShipmentInformation> FinalResults = new List<ShipmentInformation>();
var OuterNumbers = Results.GroupBy(x => x.OuterNo);
foreach(var item in OuterNumbers)
{
var orderedData = item.OrderBy(x => x.Start);
ShipmentInformation shipment = new ShipmentInformation();
shipment.OuterNo = item.Key;
shipment.Start = orderedData.First().Start;
shipment.End = orderedData.Last().End;
FinalResults.Add(shipment);
}
The issue I have now is that within each grouped item I have various ShipmentInformation but the Start number may not be sequential by x. x can be 300 or 200 based on a incoming parameter. To illustrate I could have
Start = 1, End = 300
Start = 301, End = 600
Start = 601, End = 900
Start = 1201, End = 1500
Start = 1501, End = 1800
Because I have this jump I cannot use the above loop to create an instance of ShipmentInformation and take the first and last item in orderedData to use their data to populate that instance.
I would like some way of identifying a jump by 300 or 200 and creating an instance of ShipmentInformation to add to FinalResults where the data is sequnetial.
Using the above example I would have 2 instances of ShipmentInformation with a Start of 1 and an End of 900 and another with a Start of 1201 and End of 1800
Try the following:
private static IEnumerable<ShipmentInformation> Compress(IEnumerable<ShipmentInformation> shipments)
{
var orderedData = shipments.OrderBy(s => s.OuterNo).ThenBy(s => s.Start);
using (var enumerator = orderedData.GetEnumerator())
{
ShipmentInformation compressed = null;
while (enumerator.MoveNext())
{
var current = enumerator.Current;
if (compressed == null)
{
compressed = current;
continue;
}
if (compressed.OuterNo != current.OuterNo || compressed.End < current.Start - 1)
{
yield return compressed;
compressed = current;
continue;
}
compressed.End = current.End;
}
if (compressed != null)
{
yield return compressed;
}
}
}
Useable like so:
var finalResults = Results.SelectMany(Compress).ToList();
If you want something that probably has terrible performance and is impossible to understand, but only uses out-of-the box LINQ, I think this might do it.
var orderedData = item.OrderBy(x => x.Start);
orderedData
.SelectMany(x =>
Enumerable
.Range(x.Start, 1 + x.End - x.Start)
.Select(n => new { time = n, info = x))
.Select((x, i) => new { index = i, time = x.time, info = x.info } )
.GroupBy(t => t.time - t.info)
.Select(g => new ShipmentInformation {
OuterNo = g.First().Key,
Start = g.First().Start(),
End = g.Last().End });
My brain hurts.
(Edit for clarity: this just replaces what goes inside your foreach loop. You can make it even more horrible by putting this inside a Select statement to replace the foreach loop, like in rich's answer.)
How about this?
List<ShipmentInfo> si = new List<ShipmentInfo>();
si.Add(new ShipmentInfo(orderedData.First()));
for (int index = 1; index < orderedData.Count(); ++index)
{
if (orderedData.ElementAt(index).Start ==
(si.ElementAt(si.Count() - 1).End + 1))
{
si[si.Count() - 1].End = orderedData.ElementAt(index).End;
}
else
{
si.Add(new ShipmentInfo(orderedData.ElementAt(index)));
}
}
FinalResults.AddRange(si);
Another LINQ solution would be to use the Except extension method.
EDIT: Rewritten in C#, includes composing the missing points back into Ranges:
class Program
{
static void Main(string[] args)
{
Range[] l_ranges = new Range[] {
new Range() { Start = 10, End = 19 },
new Range() { Start = 20, End = 29 },
new Range() { Start = 40, End = 49 },
new Range() { Start = 50, End = 59 }
};
var l_flattenedRanges =
from l_range in l_ranges
from l_point in Enumerable.Range(l_range.Start, 1 + l_range.End - l_range.Start)
select l_point;
var l_min = 0;
var l_max = l_flattenedRanges.Max();
var l_allPoints =
Enumerable.Range(l_min, 1 + l_max - l_min);
var l_missingPoints =
l_allPoints.Except(l_flattenedRanges);
var l_lastRange = new Range() { Start = l_missingPoints.Min(), End = l_missingPoints.Min() };
var l_missingRanges = new List<Range>();
l_missingPoints.ToList<int>().ForEach(delegate(int i)
{
if (i > l_lastRange.End + 1)
{
l_missingRanges.Add(l_lastRange);
l_lastRange = new Range() { Start = i, End = i };
}
else
{
l_lastRange.End = i;
}
});
l_missingRanges.Add(l_lastRange);
foreach (Range l_missingRange in l_missingRanges) {
Console.WriteLine("Start = " + l_missingRange.Start + " End = " + l_missingRange.End);
}
Console.ReadKey(true);
}
}
class Range
{
public int Start { get; set; }
public int End { get; set; }
}

Categories