I'm doing my school homework which is just a basic programming exercise, and at the minute I'm stuck. I tried to solve everything as simple and as elegant as possible, whereas my classmates just used a bunch of for loops, which I consider disgusting. I could do the same, that wouldn't be a challange for me, but I think I should do the way it helps me improve more.
So the task is we have a txt file with some data about radio programmes. The first line tells the number of all the songs played, and each line after that consists of four items, the number of the radio channel, the length of the song (minutes and seconds) and the name of the song. We have to be able to read it, and answer some questions based on it. I'm stuck at the following:
"Tell exactly how much time went past since the beginning and the end of the first and last Eric Clapton song on radio channel #1."
The file looks like this:
677
1 5 3 Deep Purple:Bad Attitude
2 3 36 Eric Clapton:Terraplane Blues
3 2 46 Eric Clapton:Crazy Country Hop
3 3 25 Omega:Ablakok
2 4 23 Eric Clapton:Catch Me If You Can
1 3 27 Eric Clapton:Willie And The Hand Jive
3 4 33 Omega:A szamuzott
2 6 20 Eric Clapton:Old love
...
I read it using this code:
const int N_COL = 4;
const int N_ROW = 1000;
string[][] RDATA = new string[N_COL][];
for (int i = 0; i < N_COL; i++)
RDATA[i] = new string[N_ROW];
using (StreamReader sr = new StreamReader("musor.txt"))
{
int n_lines = Convert.ToInt32(sr.ReadLine());
for (int i = 0; i < n_lines; i++)
{
int idx = 0;
foreach (string s in (sr.ReadLine().Split(new char[] {' '}, 4)))
RDATA[idx++][i] = s;
}
}
And this is how I tried to answer the question:
int[] first = new int[] { Array.FindIndex(RDATA[3], x => x.Contains("Eric Clapton")), 0 };
int[] last = new int[] { Array.FindLastIndex(RDATA[3], RDATA[3].Count(x => x != null) - 1, x => x.Contains("Eric Clapton")), 0 };
for (int i = 0; i < first[0]; i++)
if (RDATA[0][i] == RDATA[0][first[0]])
first[1] += Convert.ToInt32(RDATA[1][i]) * 60 + Convert.ToInt32(RDATA[2][i]);
for (int i = 0; i <= last[0]; i++)
if (RDATA[0][i] == RDATA[0][last[0]])
last[1] += Convert.ToInt32(RDATA[1][i]) * 60 + Convert.ToInt32(RDATA[2][i]);
Console.WriteLine("\nDifference: {0}", TimeSpan.FromSeconds(last[1] - first[1]));
Well, it works perfectly, but the problem is, it's not the answer for the question above, it only answers how much time went past in the whole section, on all three channels. How could I implement that to search for only the ones on channel #1? Is it possible to get the current index of x (object) in the FindIndex method itself? Should I use LINQ instead?
Please help me, I found it so clean with these one line methods, and now I'm facing a problem I can not solve. I have no idea either.