I am going back to my old standard playtime function, finding the duplicated integer in a set of integers. I have been playing around a lot more with Groovy lately and I realized that I had never really done a Groovy version of that little function.

1
2
3
4
5
6
def findDups( n ){
    n.sort()
    for( i in (1..n.size())){
        if(n[i] == n[i-1]) return n[i]
    }
}

In this case, I am allowing null to be the value returned when no duplicate is found. It does seem to be a more realistic value for Groovy. It’s a pretty straight forward function, along the same lines as the other languages. I thought maybe I could find some really cool feature of Groovy that would make this radically different from the Java version… nope. It does collapse nicely down to a single line though:

1
def findDups( n ){ n.sort(); for( i in (1..n.size()) ) if(n[i] == n[i-1]) return n[i] }

If you like that sort of thing.

Shortly after, I decided to do a quick little Ruby version as well:

1
2
3
4
5
6
7
def findDups( n )
    n.sort!()
    for i in (1..n.size())
        if(n[i] == n[i-1]) then return n[i] end
    end
    return nil
end

Nothing exciting in either case, but worth doing for completeness.

Popularity: 3% [?]

  • Share/Bookmark