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();
Related
Given a list of intervals [start, end] I have to merge them based on a specified merge distance. The intervals are arriving in a particular order, and as they arrive it should merge them according to the specified merge distance as each interval is received. Some of these intervals will be removed (in the arrival stream they will be marked as removed) – in that situation I've to treat the original interval as if it never existed. Example:
Merge distance is 7 – in the following example the input is arriving in order
I've tried the following algorithm to merge them but my Output isn't coming like the above example. Can somebody assists me, what I'm missing here!
Here is my code.
class Program
{
static void Main(string[] args)
{
var intervals = new List<Interval>
{
new Interval
{
start = 1,
end = 20
},
new Interval
{
start = 55,
end = 58
},
new Interval
{
start = 60,
end = 89
},
new Interval
{
start = 15,
end = 31
},
new Interval
{
start = 10,
end = 15
},
new Interval
{
start = 1,
end = 20
}
};
var mergedIntervals = Merge(intervals, 7);
foreach (var item in mergedIntervals)
{
Console.WriteLine($"[{item.start}, {item.end}]");
}
Console.ReadKey();
}
public static List<Interval> Merge(List<Interval> intervals, int mergeDistance)
{
var result = new List<Interval>();
for (int i = 0; i < intervals.Count; i++)
{
var newInterval = new Interval(intervals[i].start, intervals[i].end);
//while (i < intervals.Count - 1 && newInterval.end >= intervals[i + 1].start)
while (i < intervals.Count - 1 && newInterval.end <= mergeDistance) // intervals[i + 1].start)
{
newInterval.end = Math.Max(newInterval.end, intervals[i + 1].end);
i++;
}
result.Add(newInterval);
}
return result;
}
}
public class Interval
{
public int start { get; set; }
public int end { get; set; }
public Interval()
{
}
public Interval(int start, int end)
{
this.start = start;
this.end = end;
}
}
Can you please try this code, working demo code here
class Program
{
static void Main(string[] args)
{
var intervals = new List<Interval>
{
new Interval
{
start = 1,
end = 20,
isAdded = true
},
new Interval
{
start = 55,
end = 58,
isAdded = true
},
new Interval
{
start = 60,
end = 89,
isAdded = true
},
new Interval
{
start = 15,
end = 31,
isAdded = true
},
new Interval
{
start = 10,
end = 15,
isAdded = true
},
new Interval
{
start = 1,
end = 20,
isAdded = false
}
};
var mergedIntervals = Merge(intervals, 7);
foreach (var item in mergedIntervals)
{
Console.WriteLine($"[{item.start}, {item.end}]");
}
Console.ReadKey();
}
public static List<Interval> Merge(List<Interval> intervals, int mergeDistance)
{
var result = new List<IntervalGroup>();
var group = new IntervalGroup();
foreach (var item in intervals)
{
group = result.Where(c => c.Groups.Any(g =>
Math.Abs(g.end - item.start) <= mergeDistance ||
Math.Abs(g.end - item.end) <= mergeDistance)).FirstOrDefault();
if (group != null && item.isAdded)
{
group.Groups.Add(item);
}
else if(item.isAdded)
{
group = new IntervalGroup();
group.Groups = new List<Interval>();
result.Add(group);
group.Groups.Add(item);
}
else if(item.isAdded == false)
{
group.Groups.Remove(group.Groups.Where(c => c.start == item.start && c.end == item.end).First());
}
}
var finalResult = result.Select(s => new Interval { start = s.Groups.Min(min => min.start), end = s.Groups.Max(min => min.end) });
return finalResult.ToList();
}
}
public class Interval
{
public int start { get; set; }
public int end { get; set; }
public bool isAdded { get; set; }
public Interval()
{
}
public Interval(int start, int end, bool isAdded)
{
this.start = start;
this.end = end;
this.isAdded = isAdded;
}
}
public class IntervalGroup
{
public List<Interval> Groups { get; set; }
}
When a problem is beyond your grasp, it is very helpful to break it up into smaller pieces and code the bits that you do understand. Here's how I break it down, step by step.
First, I think it would be convenient to be able to check the length of an interval, so let's add a property.
class Interval
{
/* Prior code */
public int Length => this.end - this.start;
Now let's write a method that merges two intervals:
class Interval
{
/* Prior code */
static public Interval Merge(Interval a, Interval b )
{
return new Interval(Math.Min(a.start, b.start), Math.Max(a.end, b.end));
}
Now we need to write the code that decides if two intervals are capable of being merged. The prototype could look like this:
static public bool CanMerge(Interval a, Interval b, int mergeDistance)
What logic do we need inside? Well, we could check for overlaps and check the merge distance from both ends, but I know a shortcut. Given a merge A + B = C, the merge is allowed if and only if the length of C is less than or equal to the sum of A + B + the merge distance. So we can write this:
class Interval
{
/* Prior code */
static public bool CanMerge(Interval a, Interval b, int mergeDistance)
{
var merged = Merge(a,b);
var canMerge = merged.Length <= a.Length + b.Length + mergeDistance;
return canMerge;
}
From there you can add to a list by checking for mergeable items. Note that recursion is required because the act of merging an interval could result in another interval becoming mergeable.
void AddToList(List<Interval> list, Interval newInterval, int mergeDistance)
{
var target = list.FirstOrDefault( x => Interval.CanMerge(x, newInterval, mergeDistance) );
if (target == null)
{
list.Add(newInterval);
return;
}
list.Remove(target);
AddToList(list, Interval.Merge(target, newInterval), mergeDistance);
}
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
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);
}
}
I am hoping someone can help me with a optimal solution for this. I have a list of time logs. It contains a datatime entry for each clockin per employee per day.
I am trying to come up with a good solution to calculate the time worked per day. The time lapsed between each clock-in and clock-out for one employee.
The final result must give me the following.
Total Time Worked
Total Time Out
The time lapsed between each log / row to extract and show times worked and times out.
For example
ClockIn : 06:00
ClockedOut : 10:00
ClockedIn : 10:15
BreakTime = 00:15
and so on.
I am trying to avoid using to many for loops / foreach loops.
This is a sample piece of code representing what the list of time logs is. The type is. I = for Clock-In and O = Clock-Out. Each Shift has a Block Start Time and Block End Time.
var blockStart = new TimeSpan(0,6,0,0,0);
var blockEnd = new TimeSpan(0,17,0,0);
var listOfTimeLogs = new List<TimeLog>()
{
new TimeLog() {EntryDateTime = new DateTime(2016,05,20,6,0,0),Type = "I"},
new TimeLog() {EntryDateTime = new DateTime(2016,05,20,10,0,0),Type = "O"},
new TimeLog() {EntryDateTime = new DateTime(2016,05,20,10,15,0),Type = "I"},
new TimeLog() {EntryDateTime = new DateTime(2016,05,20,12,0,0),Type = "O"},
new TimeLog() {EntryDateTime = new DateTime(2016,05,20,12,30,0),Type = "I"},
new TimeLog() {EntryDateTime = new DateTime(2016,05,20,15,0,0),Type = "O"},
new TimeLog() {EntryDateTime = new DateTime(2016,05,20,15,15,0),Type = "I"},
new TimeLog() {EntryDateTime = new DateTime(2016,05,20,18,00,0),Type = "O"}
};
Hope this make sense. any help will be appreciated.
Thank you
Computers are made to do loops.
Here is a sample of how I would handle the problem.
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace TimeClock
{
class Program
{
static void Main()
{
var blockStart = new TimeSpan(0, 6, 0, 0);
var blockEnd = new TimeSpan(0, 17, 0, 0);
var listOfTimeLogs = new List<TimeLog>
{
new TimeLog {EntryDateTime = new DateTime(2016,05,20,6,0,0),EntryType = EntryTypes.In},
new TimeLog {EntryDateTime = new DateTime(2016,05,20,10,0,0),EntryType = EntryTypes.Out},
new TimeLog {EntryDateTime = new DateTime(2016,05,20,10,15,0),EntryType = EntryTypes.In},
new TimeLog {EntryDateTime = new DateTime(2016,05,20,12,0,0),EntryType = EntryTypes.Out},
new TimeLog {EntryDateTime = new DateTime(2016,05,20,12,30,0),EntryType = EntryTypes.In},
new TimeLog {EntryDateTime = new DateTime(2016,05,20,15,0,0),EntryType = EntryTypes.Out},
new TimeLog {EntryDateTime = new DateTime(2016,05,20,15,15,0),EntryType = EntryTypes.In},
new TimeLog {EntryDateTime = new DateTime(2016,05,20,18,00,0),EntryType = EntryTypes.Out}
};
// You are going to have have for / for each unless you use Linq
// fist I would count clock in's versus the out's
var totalIn = listOfTimeLogs.Count(e => e.EntryType == EntryTypes.In);
var totalOut = listOfTimeLogs.Count() - totalIn;
// check if we have in the number of time entries
if (totalIn > totalOut)
{
Console.WriteLine("Employee didn't clock out");
}
// as I was coding this sample program, i thought of another way to store the time
// I would store them in blocks - we have to loop
var timeBlocks = new List<TimeBlock>();
for (var x = 0; x < listOfTimeLogs.Count; x += 2)
{
// create a new WORKING block based on the in/out time entries
timeBlocks.Add(new TimeBlock
{
BlockType = BlockTypes.Working,
In = listOfTimeLogs[x],
Out = listOfTimeLogs[x + 1]
});
// create a BREAK block based on gaps
// check if the next entry in a clock in
var breakOut = x + 2;
if (breakOut < listOfTimeLogs.Count)
{
var breakIn = x + 1;
// create a new BREAK block
timeBlocks.Add(new TimeBlock
{
BlockType = BlockTypes.Break,
In = listOfTimeLogs[breakIn],
Out = listOfTimeLogs[breakOut]
});
}
}
var breakCount = 0;
// here is a loop for displaying detail
foreach (var block in timeBlocks)
{
var lineTitle = block.BlockType.ToString();
// this is me trying to be fancy
if (block.BlockType == BlockTypes.Break)
{
if (block.IsBreak())
{
lineTitle = $"Break #{++breakCount}";
}
else
{
lineTitle = "Lunch";
}
}
Console.WriteLine($" {lineTitle,-10} {block} === Length: {block.Duration.ToString(#"hh\:mm")}");
}
// calculating total time for each block type
var workingTime = timeBlocks.Where(b => b.BlockType == BlockTypes.Working)
.Aggregate(new TimeSpan(0), (p, v) => p.Add(v.Duration));
var breakTime = timeBlocks.Where(b => b.BlockType == BlockTypes.Break)
.Aggregate(new TimeSpan(0), (p, v) => p.Add(v.Duration));
Console.WriteLine($"\nTotal Working Hours: {workingTime.ToString(#"hh\:mm")}");
Console.WriteLine($" Total Break Time: {breakTime.ToString(#"hh\:mm")}");
Console.ReadLine();
}
}
}
TimeBlock.cs
using System;
namespace TimeClock
{
public enum BlockTypes
{
Working,
Break
}
public class TimeBlock
{
public BlockTypes BlockType;
public TimeLog In;
public TimeLog Out;
public TimeSpan Duration
{
get
{
// TODO: Need error checking
return Out.EntryDateTime.Subtract(In.EntryDateTime);
}
}
public override string ToString()
{
return $"In: {In.EntryDateTime:HH:mm} - Out: {Out.EntryDateTime:HH:mm}";
}
}
// a little extension class
public static class Extensions
{
public static bool IsBreak(this TimeBlock block)
{
// if the length of the break period is less than 19 minutes
// we will consider it a break, the person could have clock IN late
return block.Duration.TotalMinutes < 19 ? true : false;
}
}
}
TimeLog.cs
using System;
namespace TimeClock
{
public class TimeLog
{
public DateTime EntryDateTime;
public EntryTypes EntryType;
}
}
EntryTypes.cs
namespace TimeClock
{
public enum EntryTypes
{
In,
Out
}
}
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; }
}