Showing posts with label map. Show all posts
Showing posts with label map. Show all posts

Thursday, January 16, 2014

dotPath

int item = Math.random() * 100000

def doCode = { return 'hi' }
Map $_ = [a: 1, b: ['c d': [z: item, doit: doCode]]]

use (UtilCategory) {

    assert $_.dotPath() == [a: 1, b: ['c d': [z: item, doit: doCode]]]
    assert $_.dotPath('') == [a: 1, b: ['c d': [z: item, doit: doCode]]]
    assert $_.dotPath(null) == [a: 1, b: ['c d': [z: item, doit: doCode]]]
    
    assert $_.dotPath('a') == 1
    assert $_.dotPath('b.c d.z') == item
    assert $_.dotPath('b/c d/z', '/') == item
    
    assert $_.dotPath('b.c d.doit')() == 'hi'
    
    assert $_.dotPath('b.c d.y') == null
    assert $_.dotPath('b.c d.z.z') == null
    assert $_.dotPath('b.c d.z.z.') == null
    assert 1.dotPath('toString') == null

}

//========================================

@Category(Object)
class UtilCategory {
    def dotPath(String path = '', String delimiter = /\./) {
        Object self = this
        
        if (!path) return self
    
        try {
            return path.split(/$delimiter/).inject(self) { x, i->
               x = x[i]
            }
        }
        catch (Exception ex) { return null }
    }
}

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

GroupBy and SubMap

int groups = 7
//divide list up into groups by % (their remainder)
Map a = (1..50).groupBy({ it % groups }) as TreeMap
assert a.keySet() == (0..<groups) as Set
assert a.keySet() == [0, 1, 2, 3, 4, 5, 6] as Set

//pull out specific keys (plus vals) from a Map
assert a.subMap(1) == [1:[1, 8, 15, 22, 29, 36, 43, 50]]
assert a.subMap([1,2]) == [1:[1, 8, 15, 22, 29, 36, 43, 50], 2:[2, 9, 16, 23, 30, 37, 44]]
assert a.subMap([1,2,99]) == [1:[1, 8, 15, 22, 29, 36, 43, 50], 2:[2, 9, 16, 23, 30, 37, 44], 99:null]
assert a.subMap([1,2,99]).findAll({k,v->!!v}) == [1:[1, 8, 15, 22, 29, 36, 43, 50], 2:[2, 9, 16, 23, 30, 37, 44]]
assert a.subMap((1..3)) == [1:[1, 8, 15, 22, 29, 36, 43, 50], 2:[2, 9, 16, 23, 30, 37, 44], 3:[3, 10, 17, 24, 31, 38, 45]]

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, July 11, 2012

Conceptual Map/Reduce Example

//inspiration: http://hamletdarcy.blogspot.ca/2008/01/mapreduce-for-mere-mortals.html

// general purpose function
def mapReduceFunc = { data, mapFunction, reduceFunction ->
  def mappedData = data.collect(mapFunction)
  reduceFunction(mappedData)
}

// the data
Map dictionary = [
  abacus: "a device for making arithmetic calculations", 
  arc: "any unbroken part of the circumference of a circle", 
  beaver: "a large, amphibious rodent of the genus Castor"
]

// the mapping function impl
def startingCharacter = { pair ->
  pair.value = pair.key[0].toLowerCase()
  return pair
}

// the reducing function impl
def countCharacters = { dataMap ->
  Map result = [:]
  ('a'..'z').each{ result[it] = 0 }
  dataMap.each { pair -> result[pair.value]++ }
  return result
}

// put it all together!
def result1 = mapReduceFunc(dictionary, startingCharacter, countCharacters)
println result1

//// TWEAK THE I/O FUNCS!  ////

// the mapping function impl
startingCharacter = { pair ->
  return pair.key[0].toLowerCase()
}

// the reducing function impl
countCharacters = { dataList ->
  Map result = [:]
  ('a'..'z').each{ result[it] = 0 }
  dataList.each { it -> result[it]++ }
  return result
}

// put it all together!
def result2 = mapReduceFunc(dictionary, startingCharacter, countCharacters)
println result2

assert result1 == result2

Tuesday, April 24, 2012

self-referenced tree, in one line!

//source: https://gist.github.com/2478499

def tree = { [:].withDefault{ owner.call() } } // ta-da!

users = tree()

users.harold.username = 'hrldcpr'
users.yates.username = 'tim'

users.with {
    al.username = 'al1'
    derek.username = 'skinnyk1d'
    
    frier.with {
        username = 'great1'
        password = 'changeme1'
        updatedOn = '4/26/2012'
    }
    
    bob.with {
        age = 4
        isOld = false
    }
}

println new groovy.json.JsonBuilder( users ).toPrettyString()

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
}

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

Tuesday, January 24, 2012

FastMap and IdentityHashMap

@Grapes(
    @Grab(group='javolution', module='javolution', version='5.5.1')
)
import javolution.util.FastMap // also FastSet, FastList

Map labels1 = new FastMap().shared()
Map labels2 = [:] as IdentityHashMap // unsorted

100.times { i ->
    labels1[String.valueOf(i)] = i*i
    labels2[String.valueOf(i)] = i*i
}

assert labels1 == labels2.sort()

see http://javolution.org/target/site/apidocs/javolution/util/FastMap.html

Thursday, December 15, 2011

Multi-Assign, Transform Map Keys

(a,b,c) = [1,2]
assert a == 1
assert c == null

(a,b,c) = {[1,2]}()
assert a == 1
assert c == null

Map o = [a:1,b:2,c:3,d:4,aa:5]
// the objective it to keep only the keys with 'a', and uppercase them //

Map f1 = [:]
o.findAll { i -> i.key.contains('a') }
    .each { i -> f1[i.key.toUpperCase()] = i.value }
println f1 // [A:1, AA:5]

Map f2 = [:]
o.each { i ->
    if (i.key.contains('a'))
        f2[i.key.toUpperCase()] = i.value 
}
println f2 // [A:1, AA:5]

Map g1 = o
    .findAll { i -> i.key.contains('a') }
    .inject([:]) { m, i ->
        m[i.key.toUpperCase()] = i.value
        return m
    }
println g1 // [A:1, AA:5]

Map g2 = o
    .inject([:]) { m, i ->
        if (i.key.contains('a'))
            m[i.key.toUpperCase()] = i.value
        return m
    }
println g2 // [A:1, AA:5]

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')

Tuesday, March 29, 2011

Map/Reduce Constructs

.collect() & .inject():

def map1 = { it -> it > 5 ? it * 2 : it * 10 }
def reduce1 = { coll, i -> if (i > 29) coll << i; coll }

println ([1,2,3,4,5,6,7,8,11,88].collect(map1).inject([], reduce1))

def map2 = { it -> it.value *= 2; it }
def reduce2 = { coll, me -> String key = me.key[0]; coll[key] = coll[key] ?: 0; coll[key] += me.value; coll }

println ([a1:1,b1:2,a2:3,b2:4].collect(map2).inject([:], reduce2))

http://groovyconsole.appspot.com/script/450002