Given a sequence, write a program to detect cycles within it.
A file containing a sequence of numbers (space delimited). The file can have multiple such lines. e.g
Code
2 0 6 3 1 6 3 1 6 3 1Print to stdout the first sequence you find in each line. Ensure that there are no trailing empty spaces on each line you print. e.g.
Code
6 3 1Code
help me please.....!!
VulpesRank #55 · 29.2K reputationPosted Oct 2, 2012, 9:01 AM EDT
Console.ReadKey();
I'll leave you to insert the bit about reading the sequences from a file.
Ankit Gupta9 reputationPosted Oct 3, 2012, 8:33 AM EDT
VulpesRank #55 · 29.2K reputationPosted Oct 3, 2012, 9:48 AM EDT
So, in this line:
2 0 6 3 1 6 3 1 6 3 1
the sequence 6 3 1 is repeated three times and that's what my program should give you.
Ankit Gupta9 reputationPosted Oct 6, 2012, 3:22 AM EDT
string regexp = @"(?'cycle'(\d+\s)+(\d+))\s\k'cycle'";
Match m = Regex.Match(sequence, regexp);
if (m.Success)
{ Console.WriteLine(m.Groups["cycle"]);
}
VulpesRank #55 · 29.2K reputationPosted Oct 6, 2012, 7:48 AM EDT
If you're not familiar with regular expressions, then \d matches any digit (0 to 9), \s matches whitepace and + means that what immediately precedes it occurs at least once.
So \d+ means at least one digit.
The construct (?'cycle' ...) means that everything within the parentheses should be considered to be a group with a name of 'cycle'.
\k'cycle' means match the group named 'cycle' that was previously captured.
If the Regex.Match method succeeds in finding such a sequence of numbers, the sequence - represented by m.Groups["cycle"] - is printed to the console.
Notice that this approach only looks for the first cycle - in general, there could be others. For example, there are two (1 2 3 and 4 5 6) in the following line:
1 2 3 1 2 3 4 5 6 4 5 6