[GAP Forum] Comparison of Length of Lists of list

Stephen Linton steve.linton at st-andrews.ac.uk
Fri Oct 17 03:06:11 BST 2014


If performance is critical, you can do it in one pass, but it’s a little more complicated

maxlen := -1;
bestlists := [];

for x in l do
	if Length(x) > maxlen then
		bestlists := [x];
		maxlen := Length(x);
	elif Length(x) = maxlen then
		Add(bestlists, x);
	fi;
od;

At the end of this bestlists will be what you want.  Chris’s code is much simpler and easier though.

	Steve


On 10 Oct 2014, at 10:10, Christopher Jefferson <caj21 at st-andrews.ac.uk> wrote:

> I would switch to doing this in two passes:
> 
> First get the length of the longest sublist:
> 
> Maximum(List(l, x -> Length(x));
> 
> Then get the lists of that length:
> 
> Filtered(l, x -> Length(x)=4);
> 
> If you aren't familiar with these notations (they are worth learning), you
> could write out some loops instead:
> 
> maxlen := 0;
> for i in [1..Length(l)] do
>  maxlen := Maximum(maxlen, Length(l[i]));
> od;
> 
> k := [];
> for i in [1..Length(l)] do
>  if Length(l[i]) = maxlen then
>    Add(k, l[i]);
>  fi;
> od;
> 
> 
> 
> Or, we could loop directly over the members of l:
> 
> maxlen := 0;
> for i in l do
>  maxlen := Maximum(maxlen, Length(i));
> od;
> 
> k := [];
>  for i in l do
>  if Length(i) = maxlen then
>    Add(k, i);
>  fi;
> od;
> 
> 
> 
> On 10/10/2014 13:59, "Siddiqua Mazhar (PGR)" <s.mazhar at newcastle.ac.uk>
> wrote:
> 
>> Dear Sir/Madam,
>> Here I made changes in my previous email, sorry for inconvinience
>> 
>> If I have a list let say
>> a:=[[1,2,3],[4,5],[6,7,8,9],[10,11,12,],[13,14],[15,16,17,18]];
>> 
>> I want to find the list of maximum length in it, or collection of list of
>> max length from above
>> 
>> For instance,  result:=[[6,7,8,9],[15,16,17,18]]; how can i find this
>> result?
>> 
>> here is one algorithm that I tried
>> 
>>> Comparison:=function(a)
>>> local i,k;
>>> k:=[];
>>> for i in [1..(Length(a)-1)] do
>>>    if Length(a[i])<Length(a[i+1]) then
>>>        Add(k,a[i+1]);
>>>     elif not a[i] in k then
>>>         Add(k,a[i]);
>>>    fi;
>>> od;
>>> return k;
>>> end;
>> 
>> This program works, however , what if two list are of same length next to
>> each other?
>> for instance a:=[[1,2,3],[4,5],[6,7],[8,9,10]]?
>> 
>> want this result:=[1,2,3],[8,9,10]
>> 
>> or if a:=[[1,2],[3,4],[5,6]] in this case the result wouldl be the same
>> as a because every list are of same length.
>> 
>> Many thanks.
>> 
>> Kind regards
>> Siddiqua
>> _______________________________________________
>> Forum mailing list
>> Forum at mail.gap-system.org
>> http://mail.gap-system.org/mailman/listinfo/forum
> 
> 
> _______________________________________________
> Forum mailing list
> Forum at mail.gap-system.org
> http://mail.gap-system.org/mailman/listinfo/forum




More information about the Forum mailing list