tasks a-s

This commit is contained in:
Ingy döt Net 2013-04-10 23:57:08 -07:00
parent 47bf37c096
commit b83f433714
12433 changed files with 156208 additions and 123 deletions

View file

@ -0,0 +1,42 @@
package require Tcl 8.6
package require Thread
# Pooled computation engine; runs event loop internally
namespace eval pooled {
variable poolSize 3; # Needs to be tuned to system size
proc computation {computationDefinition entryPoint values} {
variable result
variable poolSize
# Add communication shim
append computationDefinition [subst -nocommands {
proc poolcompute {value target} {
set outcome [$entryPoint \$value]
set msg [list set ::pooled::result(\$value) \$outcome]
thread::send -async \$target \$msg
}
}]
# Set up the pool
set pool [tpool::create -initcmd $computationDefinition \
-maxworkers $poolSize]
# Prepare to receive results
unset -nocomplain result
array set result {}
# Dispatch the computations
foreach value $values {
tpool::post $pool [list poolcompute $value [thread::id]]
}
# Wait for results
while {[array size result] < [llength $values]} {vwait pooled::result}
# Dispose of the pool
tpool::release $pool
# Return the results
return [array get result]
}
}

View file

@ -0,0 +1,67 @@
# Code for computing the prime factors of a number
set computationCode {
namespace eval prime {
variable primes [list 2 3 5 7 11]
proc restart {} {
variable index -1
variable primes
variable current [lindex $primes end]
}
proc get_next_prime {} {
variable primes
variable index
if {$index < [llength $primes]-1} {
return [lindex $primes [incr index]]
}
variable current
while 1 {
incr current 2
set p 1
foreach prime $primes {
if {$current % $prime} {} else {
set p 0
break
}
}
if {$p} {
return [lindex [lappend primes $current] [incr index]]
}
}
}
proc factors {num} {
restart
set factors [dict create]
for {set i [get_next_prime]} {$i <= $num} {} {
if {$num % $i == 0} {
dict incr factors $i
set num [expr {$num / $i}]
continue
} elseif {$i*$i > $num} {
dict incr factors $num
break
} else {
set i [get_next_prime]
}
}
return $factors
}
}
}
# The values to be factored
set values {
188573867500151328137405845301
3326500147448018653351160281
979950537738920439376739947
2297143294659738998811251
136725986940237175592672413
3922278474227311428906119
839038954347805828784081
42834604813424961061749793
2651919914968647665159621
967022047408233232418982157
2532817738450130259664889
122811709478644363796375689
}

View file

@ -0,0 +1,15 @@
# Do the computation, getting back a dictionary that maps
# values to its results (itself an ordered dictionary)
set results [pooled::computation $computationCode prime::factors $values]
# Find the maximum minimum factor with sorting magic
set best [lindex [lsort -integer -stride 2 -index {1 0} $results] end-1]
# Print in human-readable form
proc renderFactors {factorDict} {
dict for {factor times} $factorDict {
lappend v {*}[lrepeat $times $factor]
}
return [join $v "*"]
}
puts "$best = [renderFactors [dict get $results $best]]"