Friday, October 14, 2011

GPars: Find the greatest product of five consecutive digits in the 1000-digit number

This post was inspired by this article.

/* calc the maximum product of $len consecutive integers $loops times within $bigNum */

String bigNum = '73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158523863050715693290963295227443043557668966489504452445231617318564030987111217223831136222989342338030813533627661428280644448664523874930358907296290491560440772390713810515859307960866701724271218839987979087922749219016997208880937766572733300105336788122023542180975125454059475224352584907711670556013604839586446706324415722155397536978179778461740649551492908625693219784686224828397224137565705605749026140797296865241453510047482166370484403199890008895243450658541227588666881164271714799244429282308634656748139191231628245861786645835912456652947654568284891288314260769004224219022671055626321111109370544217506941658960408071984038509624554443629812309878799272442849091888458015616609791913387549920052406368991256071760605886116467109407754100225698315520005593572972571636269561882670428252483600823257530420752963450'
int len = 5
int loops = 2000

int poolSize = 2 // for testing

def ts // start time
Integer r // calc result

println "*" * 40

////normal////
ts = Calendar.instance.time.time
loops.times {
r = (0..bigNum.size()-len).collect { bigNum[it..<(it+len)].toList().inject(1) { p,n -> p*n.toInteger() } }.max { it }
}
println ("normal=$r\ntime:" + (Calendar.instance.time.time - ts)/1000)

println "*" * 40

////gpars////
ts = Calendar.instance.time.time
groovyx.gpars.GParsPool.withPool(poolSize) {
loops.times {
r = (0..bigNum.size()-len).collectParallel { bigNum[it..<(it+len)].toList().inject(1) { p,n -> p*n.toInteger() } }.maxParallel { it }
}
}
println ("gpars=$r\ntime:" + (Calendar.instance.time.time - ts)/1000)

println "*" * 40


source posted: here (crashes the console!)

No comments:

Post a Comment