hi all,
my problem is i have data like below(dates are in dd\mm\yyyy format)
start_date end_date fruits_eaten per_day_fruit_eaten
5/5/2008 14/5/2008 40 40/10 = 4
12/5/2008 21/5/2008 30 30/10 = 3
20/5/2008 30/5/208 55 55/11 = 5
i want to calculate above data like below
for the dates between 10/5/2008 and 25/5/2008 total fruits eaten are :
10/5/2008 = 4
11/5/2008 = 4
12/5/2008 = 4 + 3
13/5/2008 = 4 + 3
14/5/2008 = 4 + 3
15/5/2008 = 3
16/5/2008 = 3
17/5/2008 = 3
18/5/2008 = 3
19/5/2008 = 3
20/5/2008 = 3 + 5
21/5/2008 = 3 + 5
22/5/2008 = 5
23/5/2008 = 5
24/5/2008 = 5
25/5/2008 = 5
please help me solve this puzzle as it is driving me nuts !! i want to solve it in c# but logics are also welcomed
thanks in advance !
AlanPosted Oct 19, 2008, 11:30 AM
May need some work to make it more bulletproof but try this:
using System;
using System.Globalization;
class Program
{
// ensure dates can always be parsed in d/M/yyyy format
static CultureInfo ci = CultureInfo.CreateSpecificCulture("en-GB");
static void Main()
{
string[] data = new string[3];
data[0] = "5/5/2008 14/5/2008 40 40/10 = 4";
data[1] = "12/5/2008 21/5/2008 30 30/10 = 3";
data[2] = "20/5/2008 30/5/2008 55 55/11 = 5";
DateTime start = DateTime.Parse("10/5/2008", ci);
DateTime end = DateTime.Parse("25/5/2008", ci);
GetFruitsEaten(data, start, end);
Console.ReadLine();
}
static void GetFruitsEaten(string[] data, DateTime start, DateTime end)
{
string[] results = new string[(end - start).Days + 1];
DateTime dt = start;
for(int i = 0; i < results.Length; i++)
{
results[i] = dt.ToString("dd/MM/yyyy") + " = ";
dt = dt.AddDays(1);
}
for(int i = 0; i < data.Length; i++)
{
string[] items = data[i].Split(' ');
DateTime dt1 = DateTime.Parse(items[0], ci);
if (dt1 > end) continue;
DateTime dt2 = DateTime.Parse(items[1], ci);
if (dt2 < start) continue;
int eatenPerDay = int.Parse(items[items.Length - 1]);
int days = (dt2 - dt1).Days + 1;
DateTime dt3 = dt1;
for (int j = 0; j < days; j++)
{
if (dt3 < start)
{
dt3 = dt3.AddDays(1);
continue;
}
if (dt3 > end) break;
int index = (dt3 - start).Days;
if (results[index].EndsWith("= "))
{
results[index] += eatenPerDay.ToString();
}
else
{
results[index] += " + " + eatenPerDay.ToString();
}
dt3 = dt3.AddDays(1);
}
}
foreach(string result in results)
{
Console.WriteLine(result);
}
}
}