William James
11/18/2015 11:58:00 PM
WJ wrote:
> Kent M. Pitman wrote:
>
> > (defun shrug (list)
> > (loop for (x . sublist-and-more) on list
> > for more = (member x sublist-and-more)
> > when more
> > collect `(g ,x ,(ldiff sublist-and-more more))))
> > => SHRUG
> >
> > (shrug '(a b c a d b d))
> > => ((G A (B C)) (G B (C A D)) (G D (B)))
>
> MatzLisp (Ruby):
>
> def shrug array
> a = array.dup
> result = []
> while a.size > 1
> x = a.shift
> i = a.index(x)
> result << [:g,x,a[0,i]] if i
> end
> result
> end
>
> shrug [:a,:b,:c,:a,:d,:b,:d]
> ==>[[:g, :a, [:b, :c]], [:g, :b, [:c, :a, :d]], [:g, :d, [:b]]]
Without looping:
ary = [:a,:b,:c,:a,:d,:b,:a,:d]
ary.each_with_index.group_by{|x,i| x}.
select{|k,v| v.size > 1}.map{|k,v|
[:g,k] +
v.map(&:last).each_cons(2).map{|a,b| ary[a+1 .. b-1]} }
==>[[:g, :a, [:b, :c], [:d, :b]],
[:g, :b, [:c, :a, :d]],
[:g, :d, [:b, :a]]]