Showing posts with label list. Show all posts
Showing posts with label list. Show all posts

Thursday, May 29, 2014

Simple Linked List

class Node implements Cloneable {
    private int val
    private int i
    private Node prev
    private Node next
    
    private static Node head
    private static Node last
    
    Node(int val, int i = 0) {
        if (!head) head = this
        if (!last) last = this
        
        this.i = i
        this.val = val
    }
    
    Integer at(int x, Node node = this) {
        //println "" + x + node.i + node.next
        
        if (x > node.i) {
            if (node.next != null) 
                return this.at(x, node.next)
            else 
                return null
        }

        return node.val
    }
    
    Node add(int val) {
        Node newNode = new Node(val, last.i + 1)
        
        newNode.prev = last
        last.next = newNode
        
        last = newNode
        
        //println "---\nadd done\n---"
        
        return head
    }
    
    Node reverse() {
        Node r = last.clone()
        Node prev = last.prev
        
        while (prev != null) {
            r.add(prev.val)
            prev = prev.prev    
        }
        
        return r
    }
}



Node list = new Node(1)

assert list.at(0) == 1

list.add(4).add(6) // chained adding

assert list.at(0) == 1

assert list.at(1) == 4

assert list.at(2) == 6

assert list.at(3) == null

assert list.reverse().at(0) == list.at(2)

Wednesday, January 15, 2014

collectEntries - List to Map

List a = (1..50).toList()

Closure remainder = { return (it % 8) }

Map b = a.collectEntries{ i-> [(i.toString()) : remainder(i)]}

assert b['5'] == 5
assert b['7'] == 7
assert b['8'] == 0
assert b['17'] == 1
String last = b.keySet()[-1]
assert b[last] == 2 // [50:2]



a = ('a'..'z').toList()

Closure mult = { return (it * 8) }

b = a.collectEntries{ i-> [(i.toString()) : mult(i)]}

assert b['a'] == 'a'*8
last = b.keySet()[-1]
assert b[last] == 'z'*8 // [z:zzzzzzzz]

Monday, July 29, 2013

Intersect Lists and Maps

List a = [1,2,3]
List b = [2,3,4]
assert [2,3] == a.intersect(b)
assert [1,2,3,4] == (a + b).unique()
assert [1] == a - b
assert [4] == b - a


Map c = [a:1, b:2, c:44]
Map d = [b:2, c:3]
assert [b:2] == c.intersect(d)
assert [a:1, b:2, c:3] == c + d
assert [a:1, b:2, c:44] == d + c
assert [a:1, c:44] == c - d
assert [c:3] == d - c

Wednesday, June 5, 2013

Immutable Maps (and Lists)

//source: http://royontechnology.blogspot.co.at/2010/06/creating-collection-with-single-element.html

//note the different constructor args; both return immutables

assert [2] == Collections.singletonMap(1, 1).collect {k,v ->
    return k+v
}

assert [3, 7] == Collections.unmodifiableMap([1:2, 3:4]).collect {k,v ->
    return k+v
}

Wednesday, February 29, 2012

collate

//src: http://blog.bloidonia.com/post/18073244930/whats-new-in-groovy-1-8-6-the-collate-method

//v1.8.6+//
def list = 1..10
def listInFours  = list.collate( 4 )
assert listInFours == [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10 ] ]

def listInFours2 = list.collate( 4, false )

// Notice the [ 9, 10 ] remainder has been dropped
assert listInFours2 == [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ]

def gridList = list.collate( 3 ).collate( 2 )

assert gridList == [ [ [1, 2, 3], [4, 5, 6] ],
                     [ [7, 8, 9], [10]      ] ]

def mph        = [ 10, 26, 30, 32, 27, 14, 19, 22, 40, 14 ]
def window     = mph.collate( 3, 1, false )

assert window == [ [10, 26, 30],
                   [26, 30, 32],
                   [30, 32, 27],
                   [32, 27, 14],
                   [27, 14, 19],
                   [14, 19, 22],
                   [19, 22, 40],
                   [22, 40, 14] ]
                   
def windowAvg  = window*.sum()*.intdiv( 3 )
assert windowAvg == [22, 29, 29, 24, 20, 18, 27, 25]

def items   = [ 'ham', 30, 'cheese', 20, 'steak', 95 ]
def itemMap = items.collate( 2 ).collectEntries()

assert itemMap == [ ham:30, cheese:20, steak:95 ]

def range   = 1..20
def (odds,evens) = range.collate( 2 ).transpose()

assert odds  == (1..19).step( 2 ) // odd numbers 1 - 19
assert evens == (2..20).step( 2 ) // even numbers 2 - 20

Friday, February 10, 2012

Apache Commons Collections

@Grapes(
    @Grab(group='commons-collections', module='commons-collections', version='3.2.1')
)
import org.apache.commons.collections.*
import org.apache.commons.collections.map.*
import org.apache.commons.collections.bidimap.*

IterableMap map1 = [a:1, b:2] as HashedMap
map1.each {
    print it.key
    println it.value
}

OrderedMap map = new LinkedMap()
map.with {
    put("FIVE", "5")
    put("SIX", "6")
    put("SEVEN", "7")
    assert firstKey() == "FIVE"
    assert nextKey("FIVE") == "SIX" 
    assert nextKey("SIX")  == "SEVEN"
}

BidiMap bidi = new TreeBidiMap()
bidi.with {
    put("SIX", "6")
    assert get("SIX") == "6"
    assert get("SIX") == "6"
    assert getKey("6") == "SIX"
    removeValue("6")
    assert getKey("SIX") == null
    put("ONE", "1")
}
BidiMap inverse = bidi.inverseBidiMap()  // returns a map with keys and values swapped
assert inverse.getKey("ONE") == "1"

Buffer buffer = new UnboundedFifoBuffer()
buffer.with {
    add("ONE")
    add("TWO")
    add("THREE")
    assert remove() == "ONE"
    assert remove() == "TWO"
}

Bag bag = new HashBag()
bag.with {
    add("ONE", 6)  // add 6 copies of "ONE"
    remove("ONE", 2)  // removes 2 copies of "ONE"
    assert getCount("ONE") == 4
}

Trove - high speed regular and primitive collections

/*
 * see: http://trove.starlight-systems.com/
 */
@Grapes(
    @Grab(group='net.sf.trove4j', module='trove4j', version='3.0.2')
)
import gnu.trove.set.*
import gnu.trove.set.hash.*
import gnu.trove.list.*
import gnu.trove.list.array.*
import gnu.trove.list.linked.*
import gnu.trove.map.*
import gnu.trove.map.hash.*

//Most Trove classes start with the letter "T" to indicate that they're part of the Trove library.
THashSet s = new THashSet()
100.times { i ->
  s.add ((i / 2).toInteger())
}
assert s.size() == 50
assert s.contains(0)

TIntArrayList a = new TIntArrayList()
100.times { i ->
  a.add ((i / 3).toInteger())
}
assert a.size() == 100
assert a.get(0) == 0

TIntLinkedList l = new TLinkedList()
100.times { i ->
  l.add ((i / 4).toInteger())
}
assert l.size() == 100
assert l.get(0) == 0

THashMap m = new THashMap()
m['a'] = 1
m.b = 2
assert m.a == 1

Thursday, February 9, 2012

Google Guava

/*
 * see: http://code.google.com/p/guava-libraries/
 * grails caching idea: http://refactr.com/blog/2012/05/grails-in-memory-cache-using-googles-guava-library/
 */
@Grapes([
     @Grab("com.google.guava:guava:14.0.1")
])
import java.util.concurrent.TimeUnit
import com.google.common.primitives.Ints
import com.google.common.collect.Iterables
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableMap
import com.google.common.hash.Hashing
import com.google.common.cache.Cache
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader

List list = [1,2,3,3]
assert Iterables.frequency(list, 2) == 1
assert Iterables.frequency(list, 3) == 2

String temp = "test"
md5 = Hashing.md5()
String hash = md5.newHasher().putBytes(temp as byte[]).hash()
assert hash != temp
assert hash == "098f6bcd4621d373cade4e832627b4f6"

ImmutableList of = ImmutableList.of("a", "b", "c", "d");
// Same one for map
ImmutableMap map = ImmutableMap.of("key1", "value1", "key2", "value2");
//list of ints
List theList = Ints.asList(1, 2, 3, 4, 522, 5, 6);

//see: https://code.google.com/p/guava-libraries/wiki/CachesExplained
Cache cache = 
CacheBuilder.newBuilder()
  .weakKeys()
  .maximumSize(10000)
  .expireAfterWrite(10, TimeUnit.MINUTES)
  .build( new CacheLoader() {
    @Override
    public String load(Integer key) throws Exception {
      return retreveStringForKey(key);
    }
    @Override
    public Object load(Object o) { return o; } //???
  });

cache.metaClass.propertyMissing { k -> delegate.get(k) }
cache.metaClass.propertyMissing { k, v -> delegate.put(k, v) }
cache["a"] = 9
assert cache.size() == 1
assert cache["a"] == 9

Wednesday, December 14, 2011

Various index techniques

enum Coin {
    penny(1), nickel(5), dime(10), quarter(25)
    private final int value
    Coin(int value) { this.value = value }
    public int value() { return value }
}
assert 'penny' == Coin.penny.toString()
assert 1 == Coin.penny.value

Map Coin2 = [penny:1, nickel:5, dime:10, quarter:25]
assert 1 == Coin2.penny

List Coin3 = ['penny', 'nickel']
assert 1 == Coin3.indexOf('nickel')