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
2 0 6 3 1 6 3 1 6 3 1Ensure to account for numbers that have more than one digit eg. 12. If there is no sequence, ignore that line.
Print 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.
6 3 1
help me please.....!!
VulpesPosted Oct 6, 2012, 11:48 AM
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
Ankit GuptaPosted Oct 6, 2012, 7:22 AM
string regexp = @"(?'cycle'(\d+\s)+(\d+))\s\k'cycle'";
Match m = Regex.Match(sequence, regexp);
if (m.Success)
{ Console.WriteLine(m.Groups["cycle"]);
}
VulpesPosted Oct 3, 2012, 1:48 PM
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 GuptaPosted Oct 3, 2012, 12:33 PM
VulpesPosted Oct 2, 2012, 1:01 PM
Console.ReadKey();
I'll leave you to insert the bit about reading the sequences from a file.