Skip to content

Instantly share code, notes, and snippets.

@uehaj
Created May 8, 2013 04:29
Show Gist options
  • Select an option

  • Save uehaj/5538209 to your computer and use it in GitHub Desktop.

Select an option

Save uehaj/5538209 to your computer and use it in GitHub Desktop.
CompileStatic benchmark
@Grab('org.gperfutils:gbench:0.4.2-groovy-2.1')
import groovy.transform.*
@CompileStatic
class BusStatic {
int ceil10(int n) { (Math.ceil(n/10) * 10) as Integer }
int half(int n) { ceil10(n/2) }
List parse(String input) {
String[] tmp = input.split(':')
String p = tmp[0]
String list = tmp[1]
return [Integer.parseInt(p), list.split(",") as List]
}
int calc(int basePrice, List<String> passengers) {
Map<String,Closure> map
map = [An:{int it->it},
Ap:{int it->0},
Aw:{int it->half((int)map.get('An')(it))},
Cn:{int it->half((int)map.get('An')(it))},
Cp:{int it->0},
Cw:{int it->half((int)map.get('Cn')(it))},
In:{int it->half((int)map.get('An')(it))},
Ip:{int it->0},
Iw:{int it->half((int)map.get('In')(it))}]
Map<String,List> groups = passengers
.collect{String it -> [it, map.get(it)(basePrice)]}
.groupBy{List<String> it -> it[0][0]}.withDefault{[]}
return ((groups.get('A')+groups.get('C')+groups.get('I').sort{List<Integer> it -> it[1]}
.take(groups.get('I').size()-(groups.get('A').size()*2)))
.sum{List<Integer> it -> it[1]}) as Integer
}
static void test(String input, String answer) {
BusStatic b = new BusStatic()
List tmp = b.parse(input)
int basePrice = (int)tmp[0]
List<String> passengers = (List<String>)tmp[1]
int expected = Integer.parseInt(answer)
assert expected==b.calc(basePrice, passengers)
}
}
class BusDynamic {
def ceil10(n) { (Math.ceil(n/10) * 10) as Integer }
def half(n) { ceil10(n/2) }
def parse(input) {
def (p, list) = input.split(':')
return [Integer.parseInt(p), list.split(",") as List]
}
def calc(basePrice, passengers) {
def map
map = [An:{it},
Ap:{0},
Aw:{half(map.An(it))},
Cn:{half(map.An(it))},
Cp:{0},
Cw:{half(map.Cn(it))},
In:{half(map.An(it))},
Ip:{0},
Iw:{half(map.In(it))}]
def groups = passengers
.collect{[it, map[it](basePrice)]}
.groupBy{it[0][0]}.withDefault{[]}
return (groups.A+groups.C+groups.I.sort{it[1]}
.take(groups.I.size()-(groups.A.size()*2)))
.sum{it[1]}
}
static test(input, answer) {
def b = new BusDynamic()
def (basePrice, passengers) = b.parse(input)
answer = Integer.parseInt(answer)
assert answer==b.calc(basePrice, passengers)
}
}
def r = benchmark {
'test_static' {
/*17*/ BusStatic.test( "1480:In,An,In,In,In,Iw,Cp,Cw,In,Aw,In,In,Iw,Cn,Aw,Iw", "5920" );
/*25*/ BusStatic.test( "150:In,Ip,Ip,Iw,In,Iw,Iw,In,An,Iw,Aw,Cw,Iw,Cw,An,Cp,Iw", "580" );
}
'test_dynamic' {
/*17*/ BusDynamic.test( "1480:In,An,In,In,In,Iw,Cp,Cw,In,Aw,In,In,Iw,Cn,Aw,Iw", "5920" );
/*25*/ BusDynamic.test( "150:In,Ip,Ip,Iw,In,Iw,Iw,In,An,Iw,Aw,Cw,Iw,Cw,An,Cp,Iw", "580" );
}
}
r.prettyPrint()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment