Prefacio
Ahora las aplicaciones están surgiendo después de una lluvia y se están elevando. Experimentado, inexperto, calificado y no calificado, todos quieren comenzar un negocio. Más del 90% de los empresarios necesitan hacer una aplicación, lo que parece haberse convertido en la configuración estándar para el emprendimiento.
Una vez que haces una aplicación, debes promocionarla. ¿Cómo promocionarlo? Enviar cupones es lo más indispensable. Ahora, muchos productos u operaciones requieren que la cantidad de cupones se emita aleatoriamente, pero no puede ser demasiado aleatorio. ¿Se envían todos los cupones? El dinero de los inversores, ¿verdad?
Por lo tanto, en la cantidad generada aleatoriamente, se requiere que la probabilidad de pequeñas cantidades sea mayor y la probabilidad de grandes cantidades debe ser menor. Por ejemplo, el 70% de 3 yuanes, el 25% de 5 yuanes y el 5% de 10 yuanes. ¿Qué debo hacer si genero cupones con este tipo de probabilidad?
Para las preguntas anteriores, no es suficiente usar nuestro random.next (rango entero); directamente. Debido a que este pseudo-aleatorio no está ponderado, la probabilidad de 3, 5 y 10 que aparecen es la misma.
Ideas de implementación
Tomemos el ejemplo anterior. La probabilidad de que 3 aparezcan es del 70%. Le asignamos un peso de 70. La probabilidad de que 5 aparezca es 25. Le asignamos un peso de 25. La probabilidad de 10 aparece es del 5%. Le asignamos un peso de 5.
Calculamos la suma de pesos en orden, usamos el valor antes de la suma de los pesos que aparecen en el número actual como el valor del punto de partida de su rango de peso y usamos el valor después de la suma como el valor del punto final de su rango de peso.
De esta manera, podemos usar Random.Next (100) para hacer números aleatorios, luego juzgar el rango en el que caen los números aleatorios y luego asignar al valor del cupón correspondiente.
Implementación de Java
paquete com.nggirl.test.weight.random; import java.util.arrayList; import java.util.hashmap; import java.util.list; import java.util.random; Public Class FisheTrandom {public static void main (string [] args) {pescado wr = new avetrandom (); wr.initweight (neoinitweight (neoinitweight (neoinitweight (neoinitweight (neoinitweape String [] {"1", "2", "3", "4"}, nuevo entero [] {100,100,200,600}); Random r = new Random (); for (int i = 0; i <10; i ++) {Integer rv = r.nextint(wr.getMaxRandomValue());System.out.println(rv);System.out.println(wr.getElementByRandomValue(rv).getKey() + " " + rv);}HashMap<String, Integer> keyCount = new HashMap<String, Integer>();keyCount.put("1", 0); keyCount.put ("2", 0); keyCount.put ("3", 0); keyCount.put ("4", 0); para (int i = 0; i <10000; i ++) {integer rv = r.nextint (wr.getmaxrandomValue ()); string key = wr.getElementByRandomValue (rv) .getKey (); keyCount.put (key, keyCount.get (key) .intvalue ()+1);} system.out.println ("");} private list <weavesElement> weightElements; public void Iniciente de peso (cadena [] Keys, interger [] pesos) {if (keys == n. keys.length! = weights.length) {return;} weighteelements = new ArrayList <Weightsement> (); for (int i = 0; i <keys.length; i ++) {weightEelements.Add (new WeightEelement (teclas [i], pesos [i]));} rangeWeightElemnts (); prinTvs ();} VOOCI rangeAwightElEmnts () {if (weightElements.size () == 0) {return;} weightElement ele0 = weightElements.get (0); ele0.setthreshholdlow (0); ele0.setthreshholdHigh (ele0.getPeight ()); para (int i = 1; i <i <weightelements.size (); i ++) {weatesement ()); WeightEelements.get (i); WeightElement Preelement = WeightEelements.get (i - 1); Curelement.SetthResholdLow (preelement.getthResholdHigh ()); Curelement.SetthRhesholdHigh (Curelement.getthReshOldLow () + Curelement.getWeight ());} El rango de peso se incrementa de manera ordenada, se puede cambiar a una búsqueda binaria de (WeightElement E: Weightelements) {if (rv> = e.getthreshholdlow () && rv <E.getthresholdhigh ()) {return e;}} return null;} public intreger getMaxrandomValue () {if (weaveelements | a nullsements (a nulle. 0) {return null;} return weightElements.get (weightElements.size () - 1) .getthreshholdHigh ();} public void printrvs () {for (weighteElement e: weaveseelements) {system.out.println (e.ToString ());}} de clase estatica {/*** Element tag*/private string key; Peso entero;/*** El peso corresponde al rango de números aleatorios de líneas bajas*/privado umbresholdlow;/*** El peso corresponde al rango de números aleatorios de líneas altas*/umbral entero privado umbral; peso) {this.key = key; this.weight = weight;} public String getKey () {return key;} public void setKey (string key) {this.key = key;} public integer getweight () {return weight;} public void setweight (entero de peso) {this.weight = weight;} public integer getThresholdlow () {return setweight theawlew;} setthreshholdlow (entero umbresholdlow) {this.threshesholdlow = Threshholdlow;} public Integer getthreshHoldHighHigh () {return ThresholdHigh;} public void setthresholdHigh (Integer ThrhesholdHigh) {this.threshholdhigh = ThresholdHoldHigh;} public String TOSTRING () +this.weight+"Low:"+this.threshesholdlow+"altura:"+this.thresholdhigh;}}}resultado:
2 1028764 876
Implementación de dicotomía
Public WeightElement getElementByRandomValue (Integer RV) {if (RV <0 || RV> getMaxRandomValue () -1) {return null;} // En este momento, RV debe estar en el rango de 0 -getMaxrandomValue () -1, // Es que debe ser capaz de alcanzar un cierto valor intent = 0, final = final (final) () 1; int index = weighteelements.size ()/2; while (true) {if (rv <weighteelements.get (index) .getthreshtheshLow ()) {end = index - 1;} else if (rv> = weightelements.get (index) .getthreshholdhigh ()) {inicio = index + 1;} el más {return weaveelements.get (índice);} (index = (inicio = (start + (start + (start + + (start + + (start + + + final)/2;}}¡Compartamos otro ejemplo a continuación para fortalecer la comprensión de los algoritmos aleatorios de peso y estar en su lugar a la vez!
El algoritmo aleatorio de peso se usa ampliamente en sistemas como lotería, programación de recursos, etc. Es una implementación aleatoria simple según el peso. El peso es la relación de golpes de varios objetos aleatorios (categorizados). Cuanto mayor sea la configuración de peso, más fáciles serán los golpes y la suma de los golpes no puede ser igual a 100;
El código de implementación simple es el siguiente:
import java.util.arrayList; import java.util.list; import java.util.random; public class fisheTrandom {list static <weavesCategory> categorías = new ArrayList <WeightCategory> (); private static static aleator = new aleator (); public static initData () {weightscatory wc1 = newcategory ("60); 60); 60); 60); 60); 60); 60); 60); 60); 60); wc2 = new WeightCategory ("B", 20); WeightCategory wc3 = new WeightCategory ("c", 20); categorys.Add (wc1); categorys.add (wc2); categorys.add (wc3);} public static void main (string [] args) {initData (); integer weightsum = 0; para (weightcategors) {weightsum + = wc.getweight ();} if (weightsum <= 0) {system.err.println ("error: weightsum =" + weessum.ToString ()); return;} integer n = random.nextint (weightsum); // n [0, intento) <m +wc.getweight ()) {system.out.println ("Esta categoría aleatoria es" +wc.getCategory ()); break;} m += wc.getweight ();}} class WeightCategory {Categoría de cadena privada de cadena; peso entero privado; Public WeightCategory () {Super ();} Public WeightCategory (Categoría de string String Weight); {super (); this.setCategory (categoría); this.setweight (weight);} public integer getPeight () {return weight;} public void setweight (integer weight) {this.weight = weight;} public string getCategory () {return Category;} public void setCategory (categoría de cadena) {this.category = categoría;}}}}resultado:
Resumir
Lo anterior es el contenido completo de este artículo sobre la implementación del algoritmo aleatorio de peso del lenguaje Java. Espero que sea útil para todos. Si hay alguna deficiencia, deje un mensaje para señalarlo. ¡Gracias amigos por su apoyo para este sitio!