Longest repeating sequence using linq onlyLINQ query on a DataTableDynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>LINQ equivalent of foreach for IEnumerable<T>Multiple “order by” in LINQUsing LINQ to remove elements from a List<T>When to use .First and when to use .FirstOrDefault with LINQ?What is the Java equivalent for LINQ?LEFT OUTER JOIN in LINQLINQ Aggregate algorithm explainedGroup by in LINQ
Why do wings prefer laminar flow if cd is lower for turbulent flows?
Run "cd" command as superuser in Linux
Why did Grima shed a tear?
Why is macOS limited to 1064 processes?
Hypothesis testing- with normal approximation
Can a planet's magnetic field be generated by non-ferromagnetic metals?
Why are my plastic credit card and activation code sent separately?
Transforming the first Bell state into the other Bell states
Is exploit free code, software possible?
What is a GPU year?
Why is Ancient Greek "δέ" translated by Gothic "þan" /then/?
land of light bulbs
Why does Bane's stock exchange robbery actually work to bankrupt Bruce Wayne?
where does black come from in CMYK color mode?
Command which removes data left side of ";" (semicolon) on each row
What are the Advantages of having a Double-pane Space Helmet?
How does a manufacturer determine the warranty for the battery?
In Cura, can I make my top and bottom layer be all perimiters?
Is it bizarre that a professor asks every student for a 3 inch by 5 inch photograph?
How to write pdf object directly in PDF and get number of this object via LaTeX or expl3?
How does a twisted piece of string/yarn wind back on itself? What kinds of forces are responsible for this?
Decay of spin-1/2 particle into two spin-1/2 particles
What is more proper notation in piano sheet music to denote that the left hand should be louder?
What could a technologically advanced but outnumbered alien race do to destroy humanity?
Longest repeating sequence using linq only
LINQ query on a DataTableDynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>LINQ equivalent of foreach for IEnumerable<T>Multiple “order by” in LINQUsing LINQ to remove elements from a List<T>When to use .First and when to use .FirstOrDefault with LINQ?What is the Java equivalent for LINQ?LEFT OUTER JOIN in LINQLINQ Aggregate algorithm explainedGroup by in LINQ
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;
As the title says i have a task to find the longest repeating sequence in a string and it has to be done with linq only - no ifs, no loop, no try, assignment is only allowed on initialization of variables, recursion is allowed. I've found the solution online and i understand what is happening but i can't transform it to linq -I'm not that familiar with it. I would greatly appreciate if someone could help me. Here is a link to what ive found -https://www.javatpoint.com/program-to-find-longest-repeating-sequence-in-a-string.
List<int> a = new List<int> 1, 2, 1, 2, 1, 2, 3, 2, 1, 2;
List<List<int>> aa = new List<List<int>>();
outerLoop(a);
var max = aa.Max(x => x.Count);
var m = from v in aa
where v.Count == max
select v;
m.Dump();
void outerLoop(List<int> list)
List<int> f = new List<int>();
f.AddRange(list.Skip(list.Count-1).Take(list.Count).ToList());
innerLoop(list, list.Skip(1).Take(list.Count).ToList());
f.ForEach(k => outerLoop(list.Skip(1).Take(list.Count).ToList()));
void innerLoop(List<int> l, List<int> subList)
List<int> f = new List<int>();
f.AddRange(subList.Skip(subList.Count-1).Take(subList.Count).ToList());
var tt = l.TakeWhile((ch, i) => i < subList.Count && subList[i] == ch).ToList();
aa.Add(tt);
f.ForEach(k => innerLoop(l, subList.Skip(1).Take(subList.Count).ToList()));
so i came up with this "beauty", i don't think it's good code but i think it works. If anyone is interested and wants to make suggestions how to make it better, they are more than welcome to :)
if input is int[] x= 1, 2, 1, 2, 1, 2, 3, 2, 1, 2
result should be 1212
c# linq lcs lrs
|
show 4 more comments
As the title says i have a task to find the longest repeating sequence in a string and it has to be done with linq only - no ifs, no loop, no try, assignment is only allowed on initialization of variables, recursion is allowed. I've found the solution online and i understand what is happening but i can't transform it to linq -I'm not that familiar with it. I would greatly appreciate if someone could help me. Here is a link to what ive found -https://www.javatpoint.com/program-to-find-longest-repeating-sequence-in-a-string.
List<int> a = new List<int> 1, 2, 1, 2, 1, 2, 3, 2, 1, 2;
List<List<int>> aa = new List<List<int>>();
outerLoop(a);
var max = aa.Max(x => x.Count);
var m = from v in aa
where v.Count == max
select v;
m.Dump();
void outerLoop(List<int> list)
List<int> f = new List<int>();
f.AddRange(list.Skip(list.Count-1).Take(list.Count).ToList());
innerLoop(list, list.Skip(1).Take(list.Count).ToList());
f.ForEach(k => outerLoop(list.Skip(1).Take(list.Count).ToList()));
void innerLoop(List<int> l, List<int> subList)
List<int> f = new List<int>();
f.AddRange(subList.Skip(subList.Count-1).Take(subList.Count).ToList());
var tt = l.TakeWhile((ch, i) => i < subList.Count && subList[i] == ch).ToList();
aa.Add(tt);
f.ForEach(k => innerLoop(l, subList.Skip(1).Take(subList.Count).ToList()));
so i came up with this "beauty", i don't think it's good code but i think it works. If anyone is interested and wants to make suggestions how to make it better, they are more than welcome to :)
if input is int[] x= 1, 2, 1, 2, 1, 2, 3, 2, 1, 2
result should be 1212
c# linq lcs lrs
You may create linq function?
– isaeid
Mar 28 at 21:43
3
@Daniel welcome to SO, unfortunately SO is not a code writing service, if you post your existing code, ie what you have tried, then others might be able to help you better.
– mxmissile
Mar 28 at 21:46
@mxmissile updated, and you know you could have just pointed me to an useful tutorial or something and not get passive aggressive immediately considering ive admitted to not knowing a lot in this subject. Thanks for the tips tho
– Daniel
Mar 28 at 22:14
@isaeid i believe so
– Daniel
Mar 28 at 22:15
Linq has set functions too, like union.
– isaeid
Mar 28 at 22:26
|
show 4 more comments
As the title says i have a task to find the longest repeating sequence in a string and it has to be done with linq only - no ifs, no loop, no try, assignment is only allowed on initialization of variables, recursion is allowed. I've found the solution online and i understand what is happening but i can't transform it to linq -I'm not that familiar with it. I would greatly appreciate if someone could help me. Here is a link to what ive found -https://www.javatpoint.com/program-to-find-longest-repeating-sequence-in-a-string.
List<int> a = new List<int> 1, 2, 1, 2, 1, 2, 3, 2, 1, 2;
List<List<int>> aa = new List<List<int>>();
outerLoop(a);
var max = aa.Max(x => x.Count);
var m = from v in aa
where v.Count == max
select v;
m.Dump();
void outerLoop(List<int> list)
List<int> f = new List<int>();
f.AddRange(list.Skip(list.Count-1).Take(list.Count).ToList());
innerLoop(list, list.Skip(1).Take(list.Count).ToList());
f.ForEach(k => outerLoop(list.Skip(1).Take(list.Count).ToList()));
void innerLoop(List<int> l, List<int> subList)
List<int> f = new List<int>();
f.AddRange(subList.Skip(subList.Count-1).Take(subList.Count).ToList());
var tt = l.TakeWhile((ch, i) => i < subList.Count && subList[i] == ch).ToList();
aa.Add(tt);
f.ForEach(k => innerLoop(l, subList.Skip(1).Take(subList.Count).ToList()));
so i came up with this "beauty", i don't think it's good code but i think it works. If anyone is interested and wants to make suggestions how to make it better, they are more than welcome to :)
if input is int[] x= 1, 2, 1, 2, 1, 2, 3, 2, 1, 2
result should be 1212
c# linq lcs lrs
As the title says i have a task to find the longest repeating sequence in a string and it has to be done with linq only - no ifs, no loop, no try, assignment is only allowed on initialization of variables, recursion is allowed. I've found the solution online and i understand what is happening but i can't transform it to linq -I'm not that familiar with it. I would greatly appreciate if someone could help me. Here is a link to what ive found -https://www.javatpoint.com/program-to-find-longest-repeating-sequence-in-a-string.
List<int> a = new List<int> 1, 2, 1, 2, 1, 2, 3, 2, 1, 2;
List<List<int>> aa = new List<List<int>>();
outerLoop(a);
var max = aa.Max(x => x.Count);
var m = from v in aa
where v.Count == max
select v;
m.Dump();
void outerLoop(List<int> list)
List<int> f = new List<int>();
f.AddRange(list.Skip(list.Count-1).Take(list.Count).ToList());
innerLoop(list, list.Skip(1).Take(list.Count).ToList());
f.ForEach(k => outerLoop(list.Skip(1).Take(list.Count).ToList()));
void innerLoop(List<int> l, List<int> subList)
List<int> f = new List<int>();
f.AddRange(subList.Skip(subList.Count-1).Take(subList.Count).ToList());
var tt = l.TakeWhile((ch, i) => i < subList.Count && subList[i] == ch).ToList();
aa.Add(tt);
f.ForEach(k => innerLoop(l, subList.Skip(1).Take(subList.Count).ToList()));
so i came up with this "beauty", i don't think it's good code but i think it works. If anyone is interested and wants to make suggestions how to make it better, they are more than welcome to :)
if input is int[] x= 1, 2, 1, 2, 1, 2, 3, 2, 1, 2
result should be 1212
c# linq lcs lrs
c# linq lcs lrs
edited Mar 29 at 10:30
Daniel
asked Mar 28 at 21:36
Daniel Daniel
11 bronze badge
11 bronze badge
You may create linq function?
– isaeid
Mar 28 at 21:43
3
@Daniel welcome to SO, unfortunately SO is not a code writing service, if you post your existing code, ie what you have tried, then others might be able to help you better.
– mxmissile
Mar 28 at 21:46
@mxmissile updated, and you know you could have just pointed me to an useful tutorial or something and not get passive aggressive immediately considering ive admitted to not knowing a lot in this subject. Thanks for the tips tho
– Daniel
Mar 28 at 22:14
@isaeid i believe so
– Daniel
Mar 28 at 22:15
Linq has set functions too, like union.
– isaeid
Mar 28 at 22:26
|
show 4 more comments
You may create linq function?
– isaeid
Mar 28 at 21:43
3
@Daniel welcome to SO, unfortunately SO is not a code writing service, if you post your existing code, ie what you have tried, then others might be able to help you better.
– mxmissile
Mar 28 at 21:46
@mxmissile updated, and you know you could have just pointed me to an useful tutorial or something and not get passive aggressive immediately considering ive admitted to not knowing a lot in this subject. Thanks for the tips tho
– Daniel
Mar 28 at 22:14
@isaeid i believe so
– Daniel
Mar 28 at 22:15
Linq has set functions too, like union.
– isaeid
Mar 28 at 22:26
You may create linq function?
– isaeid
Mar 28 at 21:43
You may create linq function?
– isaeid
Mar 28 at 21:43
3
3
@Daniel welcome to SO, unfortunately SO is not a code writing service, if you post your existing code, ie what you have tried, then others might be able to help you better.
– mxmissile
Mar 28 at 21:46
@Daniel welcome to SO, unfortunately SO is not a code writing service, if you post your existing code, ie what you have tried, then others might be able to help you better.
– mxmissile
Mar 28 at 21:46
@mxmissile updated, and you know you could have just pointed me to an useful tutorial or something and not get passive aggressive immediately considering ive admitted to not knowing a lot in this subject. Thanks for the tips tho
– Daniel
Mar 28 at 22:14
@mxmissile updated, and you know you could have just pointed me to an useful tutorial or something and not get passive aggressive immediately considering ive admitted to not knowing a lot in this subject. Thanks for the tips tho
– Daniel
Mar 28 at 22:14
@isaeid i believe so
– Daniel
Mar 28 at 22:15
@isaeid i believe so
– Daniel
Mar 28 at 22:15
Linq has set functions too, like union.
– isaeid
Mar 28 at 22:26
Linq has set functions too, like union.
– isaeid
Mar 28 at 22:26
|
show 4 more comments
2 Answers
2
active
oldest
votes
Give this a go:
List<int> words = new List<int> 1, 2, 1, 2, 1, 2, 3, 2, 1, 2 ;
string result =
words
.Select((c, i) => i)
.SelectMany(i => Enumerable.Range(1, words.Count - i).Select(j => words.Skip(i).Take(j)), (i, w) => new i, w )
.GroupBy(x => String.Join(",", x.w), x => x.i)
.Where(x => x.Skip(1).Any())
.Select(x => x.Key)
.OrderByDescending(x => x.Length)
.First();
That gives me 1,2,1,2
.
If you want one that actually works with strings, try this:
var word = "supercalifragilisticexpialidocious";
string result =
word
.Select((c, i) => i)
.SelectMany(i => Enumerable.Range(1, word.Length - i).Select(j => word.Skip(i).Take(j)), (i, w) => new i, w )
.GroupBy(x => new string(x.w.ToArray()), x => x.i)
.Where(x => x.Skip(1).Any())
.Select(x => x.Key)
.OrderByDescending(x => x.Length)
.First();
That gives me ali
.
Here's a slightly more understandable version:
var word = "supercalifragilisticexpialidocious";
string result =
(
from i in Enumerable.Range(0, word.Length)
from j in Enumerable.Range(1, word.Length - i)
group i by word.Substring(i, j) into gis
where gis.Skip(1).Any()
orderby gis.Key.Length descending
select gis.Key
).First();
I believe this is working (its getting the correct result when i test it), but i don't understand it well enough to test all cases (code is a bit complicated for me right now, and i find it a bit hard to follow)
– Daniel
Mar 29 at 10:36
@Daniel - I've added a slightly more understandable version. Let me know if that's better.
– Enigmativity
Mar 29 at 11:21
Interesting trick with.Skip(1).Any()
for.Count() > 1
but sinceGrouping
implementsCount()
efficiently, it may not be better. Also, while trickier, I prefer handling the case of two equal length sequences being returned when they both repeat. Also suggestSelect((c,i) => i)
is a tricky way to sayEnumerable.Range(0, words.Count-1)
though one reference towords
is nice.
– NetMage
Mar 29 at 17:20
add a comment
|
Here is my version. It isn't a single LINQ expression, but does use only LINQ. It does return all same length subsequences if there are multiple answers. It should work any type of sequence. It was written to only use standard LINQ methods.
It uses GroupBy
with a string key to implement a sequence Distinct
. (Because of this trick, lists that contain items with commas might not work right.) In production code, I would use a Distinct
with an IEqualityComparer
for sequences based on SequenceEqual
. It also has a separate step for finding the maximum repeated sequence length and then finding all the matching sequences, in production code I would use a MaxBy
extension.
Update: Since I was using GroupBy
for DistinctBy
, I realized I could just use that to count the subsequence repeats directly rather than search for them.
var repeaters = Enumerable.Range(0, words.Count) // starting positions
.SelectMany(n => Enumerable.Range(1, (words.Count - n) / 2).Select(l => words.Skip(n).Take(l).ToList())) // subseqs from each starting position
.GroupBy(s => String.Join(",", s), (k, sg) => new seq = sg.First(), Repeats = sg.Count() ) // count each sequence
.Where(sr => sr.Repeats > 1) // only keep repeated sequences
.Select(sr => sr.seq); // no longer need counts
var maxRepeaterLen = repeaters.Select(ss => ss.Count()).Max(); // find longest repeated sequence's length
var maxLenRepeaters = repeaters.Where(ss => ss.Count() == maxRepeaterLen); // return all sequences matching longest length
add a comment
|
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55407210%2flongest-repeating-sequence-using-linq-only%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Give this a go:
List<int> words = new List<int> 1, 2, 1, 2, 1, 2, 3, 2, 1, 2 ;
string result =
words
.Select((c, i) => i)
.SelectMany(i => Enumerable.Range(1, words.Count - i).Select(j => words.Skip(i).Take(j)), (i, w) => new i, w )
.GroupBy(x => String.Join(",", x.w), x => x.i)
.Where(x => x.Skip(1).Any())
.Select(x => x.Key)
.OrderByDescending(x => x.Length)
.First();
That gives me 1,2,1,2
.
If you want one that actually works with strings, try this:
var word = "supercalifragilisticexpialidocious";
string result =
word
.Select((c, i) => i)
.SelectMany(i => Enumerable.Range(1, word.Length - i).Select(j => word.Skip(i).Take(j)), (i, w) => new i, w )
.GroupBy(x => new string(x.w.ToArray()), x => x.i)
.Where(x => x.Skip(1).Any())
.Select(x => x.Key)
.OrderByDescending(x => x.Length)
.First();
That gives me ali
.
Here's a slightly more understandable version:
var word = "supercalifragilisticexpialidocious";
string result =
(
from i in Enumerable.Range(0, word.Length)
from j in Enumerable.Range(1, word.Length - i)
group i by word.Substring(i, j) into gis
where gis.Skip(1).Any()
orderby gis.Key.Length descending
select gis.Key
).First();
I believe this is working (its getting the correct result when i test it), but i don't understand it well enough to test all cases (code is a bit complicated for me right now, and i find it a bit hard to follow)
– Daniel
Mar 29 at 10:36
@Daniel - I've added a slightly more understandable version. Let me know if that's better.
– Enigmativity
Mar 29 at 11:21
Interesting trick with.Skip(1).Any()
for.Count() > 1
but sinceGrouping
implementsCount()
efficiently, it may not be better. Also, while trickier, I prefer handling the case of two equal length sequences being returned when they both repeat. Also suggestSelect((c,i) => i)
is a tricky way to sayEnumerable.Range(0, words.Count-1)
though one reference towords
is nice.
– NetMage
Mar 29 at 17:20
add a comment
|
Give this a go:
List<int> words = new List<int> 1, 2, 1, 2, 1, 2, 3, 2, 1, 2 ;
string result =
words
.Select((c, i) => i)
.SelectMany(i => Enumerable.Range(1, words.Count - i).Select(j => words.Skip(i).Take(j)), (i, w) => new i, w )
.GroupBy(x => String.Join(",", x.w), x => x.i)
.Where(x => x.Skip(1).Any())
.Select(x => x.Key)
.OrderByDescending(x => x.Length)
.First();
That gives me 1,2,1,2
.
If you want one that actually works with strings, try this:
var word = "supercalifragilisticexpialidocious";
string result =
word
.Select((c, i) => i)
.SelectMany(i => Enumerable.Range(1, word.Length - i).Select(j => word.Skip(i).Take(j)), (i, w) => new i, w )
.GroupBy(x => new string(x.w.ToArray()), x => x.i)
.Where(x => x.Skip(1).Any())
.Select(x => x.Key)
.OrderByDescending(x => x.Length)
.First();
That gives me ali
.
Here's a slightly more understandable version:
var word = "supercalifragilisticexpialidocious";
string result =
(
from i in Enumerable.Range(0, word.Length)
from j in Enumerable.Range(1, word.Length - i)
group i by word.Substring(i, j) into gis
where gis.Skip(1).Any()
orderby gis.Key.Length descending
select gis.Key
).First();
I believe this is working (its getting the correct result when i test it), but i don't understand it well enough to test all cases (code is a bit complicated for me right now, and i find it a bit hard to follow)
– Daniel
Mar 29 at 10:36
@Daniel - I've added a slightly more understandable version. Let me know if that's better.
– Enigmativity
Mar 29 at 11:21
Interesting trick with.Skip(1).Any()
for.Count() > 1
but sinceGrouping
implementsCount()
efficiently, it may not be better. Also, while trickier, I prefer handling the case of two equal length sequences being returned when they both repeat. Also suggestSelect((c,i) => i)
is a tricky way to sayEnumerable.Range(0, words.Count-1)
though one reference towords
is nice.
– NetMage
Mar 29 at 17:20
add a comment
|
Give this a go:
List<int> words = new List<int> 1, 2, 1, 2, 1, 2, 3, 2, 1, 2 ;
string result =
words
.Select((c, i) => i)
.SelectMany(i => Enumerable.Range(1, words.Count - i).Select(j => words.Skip(i).Take(j)), (i, w) => new i, w )
.GroupBy(x => String.Join(",", x.w), x => x.i)
.Where(x => x.Skip(1).Any())
.Select(x => x.Key)
.OrderByDescending(x => x.Length)
.First();
That gives me 1,2,1,2
.
If you want one that actually works with strings, try this:
var word = "supercalifragilisticexpialidocious";
string result =
word
.Select((c, i) => i)
.SelectMany(i => Enumerable.Range(1, word.Length - i).Select(j => word.Skip(i).Take(j)), (i, w) => new i, w )
.GroupBy(x => new string(x.w.ToArray()), x => x.i)
.Where(x => x.Skip(1).Any())
.Select(x => x.Key)
.OrderByDescending(x => x.Length)
.First();
That gives me ali
.
Here's a slightly more understandable version:
var word = "supercalifragilisticexpialidocious";
string result =
(
from i in Enumerable.Range(0, word.Length)
from j in Enumerable.Range(1, word.Length - i)
group i by word.Substring(i, j) into gis
where gis.Skip(1).Any()
orderby gis.Key.Length descending
select gis.Key
).First();
Give this a go:
List<int> words = new List<int> 1, 2, 1, 2, 1, 2, 3, 2, 1, 2 ;
string result =
words
.Select((c, i) => i)
.SelectMany(i => Enumerable.Range(1, words.Count - i).Select(j => words.Skip(i).Take(j)), (i, w) => new i, w )
.GroupBy(x => String.Join(",", x.w), x => x.i)
.Where(x => x.Skip(1).Any())
.Select(x => x.Key)
.OrderByDescending(x => x.Length)
.First();
That gives me 1,2,1,2
.
If you want one that actually works with strings, try this:
var word = "supercalifragilisticexpialidocious";
string result =
word
.Select((c, i) => i)
.SelectMany(i => Enumerable.Range(1, word.Length - i).Select(j => word.Skip(i).Take(j)), (i, w) => new i, w )
.GroupBy(x => new string(x.w.ToArray()), x => x.i)
.Where(x => x.Skip(1).Any())
.Select(x => x.Key)
.OrderByDescending(x => x.Length)
.First();
That gives me ali
.
Here's a slightly more understandable version:
var word = "supercalifragilisticexpialidocious";
string result =
(
from i in Enumerable.Range(0, word.Length)
from j in Enumerable.Range(1, word.Length - i)
group i by word.Substring(i, j) into gis
where gis.Skip(1).Any()
orderby gis.Key.Length descending
select gis.Key
).First();
edited Mar 29 at 11:21
answered Mar 29 at 0:06
EnigmativityEnigmativity
82.2k9 gold badges68 silver badges138 bronze badges
82.2k9 gold badges68 silver badges138 bronze badges
I believe this is working (its getting the correct result when i test it), but i don't understand it well enough to test all cases (code is a bit complicated for me right now, and i find it a bit hard to follow)
– Daniel
Mar 29 at 10:36
@Daniel - I've added a slightly more understandable version. Let me know if that's better.
– Enigmativity
Mar 29 at 11:21
Interesting trick with.Skip(1).Any()
for.Count() > 1
but sinceGrouping
implementsCount()
efficiently, it may not be better. Also, while trickier, I prefer handling the case of two equal length sequences being returned when they both repeat. Also suggestSelect((c,i) => i)
is a tricky way to sayEnumerable.Range(0, words.Count-1)
though one reference towords
is nice.
– NetMage
Mar 29 at 17:20
add a comment
|
I believe this is working (its getting the correct result when i test it), but i don't understand it well enough to test all cases (code is a bit complicated for me right now, and i find it a bit hard to follow)
– Daniel
Mar 29 at 10:36
@Daniel - I've added a slightly more understandable version. Let me know if that's better.
– Enigmativity
Mar 29 at 11:21
Interesting trick with.Skip(1).Any()
for.Count() > 1
but sinceGrouping
implementsCount()
efficiently, it may not be better. Also, while trickier, I prefer handling the case of two equal length sequences being returned when they both repeat. Also suggestSelect((c,i) => i)
is a tricky way to sayEnumerable.Range(0, words.Count-1)
though one reference towords
is nice.
– NetMage
Mar 29 at 17:20
I believe this is working (its getting the correct result when i test it), but i don't understand it well enough to test all cases (code is a bit complicated for me right now, and i find it a bit hard to follow)
– Daniel
Mar 29 at 10:36
I believe this is working (its getting the correct result when i test it), but i don't understand it well enough to test all cases (code is a bit complicated for me right now, and i find it a bit hard to follow)
– Daniel
Mar 29 at 10:36
@Daniel - I've added a slightly more understandable version. Let me know if that's better.
– Enigmativity
Mar 29 at 11:21
@Daniel - I've added a slightly more understandable version. Let me know if that's better.
– Enigmativity
Mar 29 at 11:21
Interesting trick with
.Skip(1).Any()
for .Count() > 1
but since Grouping
implements Count()
efficiently, it may not be better. Also, while trickier, I prefer handling the case of two equal length sequences being returned when they both repeat. Also suggest Select((c,i) => i)
is a tricky way to say Enumerable.Range(0, words.Count-1)
though one reference to words
is nice.– NetMage
Mar 29 at 17:20
Interesting trick with
.Skip(1).Any()
for .Count() > 1
but since Grouping
implements Count()
efficiently, it may not be better. Also, while trickier, I prefer handling the case of two equal length sequences being returned when they both repeat. Also suggest Select((c,i) => i)
is a tricky way to say Enumerable.Range(0, words.Count-1)
though one reference to words
is nice.– NetMage
Mar 29 at 17:20
add a comment
|
Here is my version. It isn't a single LINQ expression, but does use only LINQ. It does return all same length subsequences if there are multiple answers. It should work any type of sequence. It was written to only use standard LINQ methods.
It uses GroupBy
with a string key to implement a sequence Distinct
. (Because of this trick, lists that contain items with commas might not work right.) In production code, I would use a Distinct
with an IEqualityComparer
for sequences based on SequenceEqual
. It also has a separate step for finding the maximum repeated sequence length and then finding all the matching sequences, in production code I would use a MaxBy
extension.
Update: Since I was using GroupBy
for DistinctBy
, I realized I could just use that to count the subsequence repeats directly rather than search for them.
var repeaters = Enumerable.Range(0, words.Count) // starting positions
.SelectMany(n => Enumerable.Range(1, (words.Count - n) / 2).Select(l => words.Skip(n).Take(l).ToList())) // subseqs from each starting position
.GroupBy(s => String.Join(",", s), (k, sg) => new seq = sg.First(), Repeats = sg.Count() ) // count each sequence
.Where(sr => sr.Repeats > 1) // only keep repeated sequences
.Select(sr => sr.seq); // no longer need counts
var maxRepeaterLen = repeaters.Select(ss => ss.Count()).Max(); // find longest repeated sequence's length
var maxLenRepeaters = repeaters.Where(ss => ss.Count() == maxRepeaterLen); // return all sequences matching longest length
add a comment
|
Here is my version. It isn't a single LINQ expression, but does use only LINQ. It does return all same length subsequences if there are multiple answers. It should work any type of sequence. It was written to only use standard LINQ methods.
It uses GroupBy
with a string key to implement a sequence Distinct
. (Because of this trick, lists that contain items with commas might not work right.) In production code, I would use a Distinct
with an IEqualityComparer
for sequences based on SequenceEqual
. It also has a separate step for finding the maximum repeated sequence length and then finding all the matching sequences, in production code I would use a MaxBy
extension.
Update: Since I was using GroupBy
for DistinctBy
, I realized I could just use that to count the subsequence repeats directly rather than search for them.
var repeaters = Enumerable.Range(0, words.Count) // starting positions
.SelectMany(n => Enumerable.Range(1, (words.Count - n) / 2).Select(l => words.Skip(n).Take(l).ToList())) // subseqs from each starting position
.GroupBy(s => String.Join(",", s), (k, sg) => new seq = sg.First(), Repeats = sg.Count() ) // count each sequence
.Where(sr => sr.Repeats > 1) // only keep repeated sequences
.Select(sr => sr.seq); // no longer need counts
var maxRepeaterLen = repeaters.Select(ss => ss.Count()).Max(); // find longest repeated sequence's length
var maxLenRepeaters = repeaters.Where(ss => ss.Count() == maxRepeaterLen); // return all sequences matching longest length
add a comment
|
Here is my version. It isn't a single LINQ expression, but does use only LINQ. It does return all same length subsequences if there are multiple answers. It should work any type of sequence. It was written to only use standard LINQ methods.
It uses GroupBy
with a string key to implement a sequence Distinct
. (Because of this trick, lists that contain items with commas might not work right.) In production code, I would use a Distinct
with an IEqualityComparer
for sequences based on SequenceEqual
. It also has a separate step for finding the maximum repeated sequence length and then finding all the matching sequences, in production code I would use a MaxBy
extension.
Update: Since I was using GroupBy
for DistinctBy
, I realized I could just use that to count the subsequence repeats directly rather than search for them.
var repeaters = Enumerable.Range(0, words.Count) // starting positions
.SelectMany(n => Enumerable.Range(1, (words.Count - n) / 2).Select(l => words.Skip(n).Take(l).ToList())) // subseqs from each starting position
.GroupBy(s => String.Join(",", s), (k, sg) => new seq = sg.First(), Repeats = sg.Count() ) // count each sequence
.Where(sr => sr.Repeats > 1) // only keep repeated sequences
.Select(sr => sr.seq); // no longer need counts
var maxRepeaterLen = repeaters.Select(ss => ss.Count()).Max(); // find longest repeated sequence's length
var maxLenRepeaters = repeaters.Where(ss => ss.Count() == maxRepeaterLen); // return all sequences matching longest length
Here is my version. It isn't a single LINQ expression, but does use only LINQ. It does return all same length subsequences if there are multiple answers. It should work any type of sequence. It was written to only use standard LINQ methods.
It uses GroupBy
with a string key to implement a sequence Distinct
. (Because of this trick, lists that contain items with commas might not work right.) In production code, I would use a Distinct
with an IEqualityComparer
for sequences based on SequenceEqual
. It also has a separate step for finding the maximum repeated sequence length and then finding all the matching sequences, in production code I would use a MaxBy
extension.
Update: Since I was using GroupBy
for DistinctBy
, I realized I could just use that to count the subsequence repeats directly rather than search for them.
var repeaters = Enumerable.Range(0, words.Count) // starting positions
.SelectMany(n => Enumerable.Range(1, (words.Count - n) / 2).Select(l => words.Skip(n).Take(l).ToList())) // subseqs from each starting position
.GroupBy(s => String.Join(",", s), (k, sg) => new seq = sg.First(), Repeats = sg.Count() ) // count each sequence
.Where(sr => sr.Repeats > 1) // only keep repeated sequences
.Select(sr => sr.seq); // no longer need counts
var maxRepeaterLen = repeaters.Select(ss => ss.Count()).Max(); // find longest repeated sequence's length
var maxLenRepeaters = repeaters.Where(ss => ss.Count() == maxRepeaterLen); // return all sequences matching longest length
edited Mar 29 at 19:33
answered Mar 29 at 18:51
NetMageNetMage
16.8k1 gold badge22 silver badges37 bronze badges
16.8k1 gold badge22 silver badges37 bronze badges
add a comment
|
add a comment
|
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55407210%2flongest-repeating-sequence-using-linq-only%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
You may create linq function?
– isaeid
Mar 28 at 21:43
3
@Daniel welcome to SO, unfortunately SO is not a code writing service, if you post your existing code, ie what you have tried, then others might be able to help you better.
– mxmissile
Mar 28 at 21:46
@mxmissile updated, and you know you could have just pointed me to an useful tutorial or something and not get passive aggressive immediately considering ive admitted to not knowing a lot in this subject. Thanks for the tips tho
– Daniel
Mar 28 at 22:14
@isaeid i believe so
– Daniel
Mar 28 at 22:15
Linq has set functions too, like union.
– isaeid
Mar 28 at 22:26