ocaml - Re-generate random numbers in a loop -


i create basic genetic algorithm in order output set of input enter in emulator. basically, :

  • generate input sheet
  • list item
  • run said input
  • slightly modify it
  • run it
  • see whichever input set performed better , "fork" , repeat until problem solved

so : here code generate first set of inputs :

(* rng initialization   * unit *) random.self_init();;   (* generating starting input file   * array   * 500 inputs long *) let first_input = let first_array = array.make 500 "start" in = 1 499     let input =          match random.int(5)         | 0 -> "a "         | 1 -> "b "         | 2 -> "down "         | 3 -> "left "         | 4 -> "right "         | _ -> "start " in     first_array.(i) <- input done; first_array;; 

and here "mutation" function randomly alters inputs :

(* mutating input_file   * rate : in percent, must positive , <= 100   * must array of strings *)  let mutation n= let mutation_rate = n in = 0 ((array.length(a) * mutation_rate / 100) - 1)     let input =          match random.int(5)         | 0 -> "a "         | 1 -> "b "         | 2 -> "down "         | 3 -> "left "         | 4 -> "right "         | _ -> "start " in     a.( random.int(498) + 1) <- input done;; 

however, don't feel function efficient because had paste pattern matching part in mutation function , think there has smarter way proceed. if define "input" function global function, evaluated once (let's "right" , occurrences of "input" return "right" not useful.

thanks.

there isn't wrong putting it's own function. missing argument make function deal side-effect of random.int. since not using argument, it's often/always case people use unit.

   let random_input () = match random.int 5      | 0 -> "a "      | 1 -> "b "      | 2 -> "down "      | 3 -> "left "      | 4 -> "right "      | _ -> "start " 

what doing here pattern matching argument, , since there 1 constructor matching exhaustive. technically, can replace () above _. match making function polymorphic against it's argument, 'a -> string. in case it's bad form since may lead confusion parameter for.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -