Advertisement
Guest User

RLS as simulated annealing

a guest
Mar 6th, 2015
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.15 KB | None | 0 0
  1. object Anneal {
  2.   val rng = new java.util.Random()
  3.  
  4.   // здесь p - это вероятность взять новую особь, если она хуже
  5.   def anneal[A, E: Ordering, T: Ordering](f: A => E)(startA: A, startT: T)(nextA: (A, T) => A, nextT: (A, T) => T)(minT: T)(p: (T, E, E) => Double): (A, E) = {
  6.     import Ordering.Implicits._
  7.  
  8.     def iteration(currA: A, currE: E, currT: T): (A, E) = {
  9.       if (currT < minT) {
  10.         (currA, currE)
  11.       } else {
  12.         val newA = nextA(currA, currT)
  13.         val newT = nextT(currA, currT)
  14.         val newE = f(newA)
  15.         if (newE <= currE || p(newT, currE, newE) > rng.nextDouble()) {
  16.           iteration(newA, newE, newT)
  17.         } else {
  18.           iteration(currA, currE, newT)
  19.         }
  20.       }
  21.     }
  22.     iteration(startA, f(startA), startT)
  23.   }
  24.  
  25.   def main(args: Array[String]) {
  26.     val oneMin: Long => Int               = 64 - java.lang.Long.bitCount(_)
  27.     val nextA:  (Long, Int) => Long       = (a, t) => a ^ (1L << rng.nextInt(64))
  28.     val nextT:  (Long, Int) => Int        = (a, t) => t - 1
  29.  
  30.     println(anneal(oneMin)(0, 250)(nextA, nextT)(0)((_, _, _) => 0.0))
  31.   }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement