Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: the simplest way to detect duplicate, non-consecutive values in a list

Tags:

groovy

I know that in Groovy, if

list = [1,2,3,1]

when

list.unique()

with return

[1,2,3]

But if I want to detect duplicate value for duplicate, non-consecutive items in a list. How can I do this?

detect([1,2,3,1]) => true
detect([1,2,3,2]) => true
detect([1,1,2,3]) => false
detect([1,2,2,3,3]) => false
detect([1,2,3,4]) => false

Thanks.

Edit: add these two cases

detect([1,2,2,1]) => true
detect([1,2,1,1]) => true

true means any non-consecutive, duplicate occur.

like image 927
Harold Chan Avatar asked May 30 '13 03:05

Harold Chan


2 Answers

In case you need to obtain duplicate elements:

    def nonUniqueElements = {list ->
        list.findAll{a -> list.findAll{b -> b == a}.size() > 1}.unique()
    }

    assert nonUniqueElements(['a', 'b', 'b', 'c', 'd', 'c']) == ['b', 'c']
like image 169
Ivan Pianetti Avatar answered Nov 13 '22 23:11

Ivan Pianetti


This should do it:

List list = ["a", "b", "c", "a", "d", "c", "a"]

and

list.countBy{it}.grep{it.value > 1}.collect{it.key}
like image 32
Gema Peña Chimeno Avatar answered Nov 14 '22 01:11

Gema Peña Chimeno