24. Crear la población inicial app/models/combinacion.rb class Combinacion < ActiveRecord::Base def self.create_random c = Combinacion.new c.impresiones_restantes = NUM_IMPRESIONES_COMBINACION anuncios = Anuncio.find :all NUM_POSICIONES.times do |pos| c.posicion_anuncios << PosicionAnuncio.create( :position => pos, :anuncio => anuncios[(anuncios.size*rand).truncate] ) end c.save return c end end app/controllers/application.rb @poblacion_actual = Array.new(NUM_COMBINACIONES_GENERACION).collect do Combinacion.create_random end
26. Código de la evolución app/controllers/application.rb def escoge_combinacion @poblacion_actual = Combinacion.find :all # Si no existe ninguna combinación, creamos la población inicial @poblacion_actual = Array.new(NUM_COMBINACIONES_GENERACION).collect { Combinacion.create_random } if @poblacion_actual.empty? # Se elige una combinación al azar @combinacion = @poblacion_actual.select {|c| c.impresiones_restantes > 0}.shuffle!.first # Si no quedan combinaciones por mostrar, la población actual evoluciona a una nueva generación if @combinacion.nil? @poblacion_actual.each {|c| c.generaciones +=1 } @ga = GeneticAlgorithm.new( @poblacion_actual, {:p_combination => 1.0, :p_mutation => 0.1, :max_population => NUM_COMBINACIONES_GENERACION} ) @ga.evolve @extinguidos = @poblacion_actual - @ga.generations[-1] @extinguidos.each {|e| e.destroy} @poblacion_actual = @ga.generations[-1] @poblacion_actual.each do |c| c.clicks = 0 c.impresiones_restantes = NUM_IMPRESIONES_COMBINACION c.update end @combinacion = @poblacion_actual.select {|c| c.impresiones_restantes > 0}.shuffle!.first end @combinacion.impresion end
27.
28. ¿Y en las vistas? app/helpers/application_helper.rb def pinta_banner(posicion, orientacion) imagen_path = if orientacion.downcase == "h“ @combinacion.posicion_anuncios[posicion-1].anuncio.banner_h else @combinacion.posicion_anuncios[posicion-1].anuncio.banner_v end link_to image_tag(imagen_path), :action => "cuenta_clicks", :id => @combinacion.posicion_anuncios[posicion-1] end app/views/[vistas que muestren publicidad] <%= pinta_banner 4, "h" %>