머리말
이제 앱은 비가 오면 튀어 나오고 솟아 오릅니다. 경험이 풍부하고 경험이없고 자격을 갖추지 못하고 자격을 갖추지 못한 사람들은 모두 사업을 시작하기를 원합니다. 기업가의 90% 이상이 앱을 만들어야하는데, 이는 기업가 정신의 표준 구성이 된 것으로 보입니다.
일단 앱을 만들면 앱을 홍보해야합니다. 그것을 홍보하는 방법? 쿠폰을 보내는 것이 가장 필수적인 것입니다. 이제 많은 제품이나 운영에는 쿠폰의 양이 무작위로 발행되어야하지만 너무 무작위는 아닙니다. 모든 쿠폰이 발송됩니까? 투자자의 돈?
따라서 무작위로 생성 된 금액에서는 소량의 확률이 더 커야하고 많은 양의 확률이 더 작아야합니다. 예를 들어, 3 위안의 70%, 5 위안의 25%, 10 위안의 5%. 이런 종류의 확률로 쿠폰을 생성하면 어떻게해야합니까?
위의 질문에 대해서는 Random.next (정수 범위)를 사용하는 것만으로는 충분하지 않습니다. 곧장. 이 의사 랜덤은 가중치가 없기 때문에 3, 5 및 10의 확률은 동일합니다.
구현 아이디어
위의 예를 들어 보겠습니다. 3의 확률은 70%입니다. 우리는 그것을 70의 무게로 할당합니다. 5의 확률은 25입니다. 우리는 그것을 25의 무게를 지정합니다. 10의 확률은 5%입니다. 우리는 그것을 5의 무게를 지정합니다.
순서대로 가중치 합계를 계산하고, 중량 범위의 출발점 값으로 현재 숫자에 나타나는 가중치의 합 앞에 값을 사용하고, 합계 다음 값을 중량 범위의 종점 값으로 사용합니다.
이런 식으로, 우리는 random.next (100)를 사용하여 임의의 숫자를 만들 수있는 다음 임의 숫자가 떨어지는 범위를 판단한 다음 해당 쿠폰 값에 매핑 할 수 있습니다.
Java 구현
package com.nggirl.test.weight.random; import java.util.arraylist; import java.util.hashmap; import java.util.list; import java.util.random; public static void main (string [] args) {meadtrandom wr = new weigtrandom (); 문자열 [] { "1", "2", "3", "4"}, 새 정수 [] {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.getElementBerneTyrandomValue () + "" + rv);} hashmap <string, integer> keycount = new hashmap <strger> (keycount (); "); 0); keyCount.put ( "2", 0); keyCount.put ( "3", 0); keyCount.put ( "4", 0); for (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 ( ""); weightelement> weightlement> public void initweight (문자열 [] 키, 정수 [] weights) {if (keys = | keys.length! = weights.length) {return;} weightElements = new ArrayList <heideLement> (); for (int i = 0; i <keys.length; i ++) {headeLements.add (key weightelement (keys [i]);} 범위 무게 elemnts (); private void ();} rangeweightelemnts () {if (heidelements.size () == 0) {return;} weightelement ele0 = heightelements.get (0); ele0.setthresholdlow (0); headeLements.get (i); WeightElement preElement = weightlement.get (i -1); curelement.setthresholdlow (preElement.getThresholdHigh ()); curelement.setthresholdHigh (curelement.getThresholdLow () + curelement.getweight ())} {public weightelement getelembal getlembal getlement getlement getlement getlement getlement getelement 무게 범위는 순서대로 증가하여 (중력 검색에 이진 검색으로 변경 될 수 있습니다. 0){return null;}return weightElements.get(weightElements.size() - 1).getThresholdHigh();}public void printRvs(){for (WeightElement e:weightElements){System.out.println(e.toString());}}static class WeightElement{/** * Element tag */private String key;/** * Element weight*/private Integer 무게;/*** 무게는 무작위 숫자의 범위에 해당합니다*/개인 정수 임계 값;/*** 무게는 임의 숫자의 범위에 해당합니다. 높은 라인*/개인 정수 임계 값*/public weightelement () {} public weightelement (integer weight) {this.key = weight.toString (this.key)}}}}. key; this.weight = weight;} public string getKey () {return key;} public void setkey (String key) {this.key) {this.key = key;} public integer getweight () {return weight;} public void setweight (정수 웨이트) {weight =} public void void void void setholdlow;} thresholdlow) {this.thresholdlow = thresholdlow;} public integer getthresholdhigh () {return thresholdhigh;} public void setthresholdhigh (정수 임계 값) LOW : "+this.thresholdlow+"높이 : "+this.thresholdhigh;}}}}결과:
2 1028764 876
이분법의 구현
public weightelement getElementByRandomValue (Integer RV) {if (rv <0 || rv> getMaxRandomValue () -1) {return null;} // 현재로서는 RV가 0의 범위에 있어야합니다. 1; int index = weightElements.size ()/2; while (true) {if (rv <headelements.get (index) .getthresholdlow ()) {end = index -1;} else (rv> = weightelements.get (index)) 끝)/2;}}중량 랜덤 알고리즘에 대한 이해를 강화하고 한 번에 마련해 보도록 아래의 또 다른 예를 공유합시다!
중량 랜덤 알고리즘은 복권, 리소스 스케줄링 등과 같은 시스템에서 널리 사용됩니다. 무게에 따라 간단한 랜덤 구현입니다. 무게는 여러 랜덤 물체의 히트 비율입니다 (분류). 무게 설정이 높을수록 적중이 쉽고 적중의 합은 100과 같을 수 없습니다.
간단한 구현 코드는 다음과 같습니다.
import java.util.arraylist; import java.util.list; import java.util.random; public class meadtrandom {정적 목록 <headecategory> category = new arraylist <heidecatecate> (); private static random = new random (); public static void initdata () {heighttatic void initdata (); wc2 = new heightlecategory ( "b", 20); WeightCategory wc3 = new heightedcategory ( "c", 20); categorys.add (wc1); cat {weightsum + = wc.getweight ();} if (weightsum <= 0) {system.err.println ( "error : weightsum =" + weightsum.toString ()); return;} integer n = random.nextint (weightsum); // n) {weightsum) {for (for) {wc : w. n <m +wc.getweight ()) {system.out.println ( "이 랜덤 범주는" +wc.getcategory ()); break;} m += wc.getweight ();}}} 클래스 스트링 카테고리; private weightcategory; public weightcategory () {supercationcations () {super (); this.setcategory (category); this.setweight (weight);} public integer getweight () {return weight;} public void setweight (reteger weight) {this.weight = weight;} public string getCategory () {return category;결과:
요약
위는 Java 언어 가중치 임의 알고리즘의 구현에 대한이 기사의 전체 내용입니다. 모든 사람에게 도움이되기를 바랍니다. 단점이 있으면 메시지를 남겨 두십시오. 이 사이트를 지원해 주신 친구들에게 감사드립니다!