Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

397
Views
¿C# tiene algo equivalente a Pythons random.choices()?

Estoy tratando de hacer elecciones basadas en su peso/probabilidad

esto es lo que tenía en python:

 import random myChoiceList = ["Attack", "Heal", "Amplify", "Defense"] myWeights = [70, 0, 15, 15] // % probability = 100% Ex. Attack has 70% of selection print(random.choices(myChoicelist , weights = myWeights, k = 1))

Quiero hacer lo mismo en C#, ¿cómo se hace eso? ¿C# tiene algún método similar a random.choices() todo lo que sé es random.Next()

*este código de python funciona bien randome.choice toma (secuencia, pesos, k) secuencia: valores, pesos: una lista donde puede sopesar la posibilidad de cada valor, k: la longitud de la lista devuelta,

Estoy buscando hacer lo mismo para C #, elija valores según la probabilidad

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

No hay nada integrado en C# como este, sin embargo, no es tan difícil agregar un método de extensión para recrear el mismo comportamiento básico:

 static class RandomUtils { public static string Choice(this Random rnd, IEnumerable<string> choices, IEnumerable<int> weights) { var cumulativeWeight = new List<int>(); int last = 0; foreach (var cur in weights) { last += cur; cumulativeWeight.Add(last); } int choice = rnd.Next(last); int i = 0; foreach (var cur in choices) { if (choice < cumulativeWeight[i]) { return cur; } i++; } return null; } }

Luego puede llamarlo de manera similar a la versión de Python:

 string[] choices = { "Attack", "Heal", "Amplify", "Defense" }; int[] weights = { 70, 0, 15, 15 }; Random rnd = new Random(); Console.WriteLine(rnd.Choice(choices, weights));
over 4 years ago · Santiago Trujillo Report

0

puede obtener random.next (0,100), luego elegir el elemento relevante con un simple interruptor o algo así. sus dominios serán así, [0-70, 70-85, 85-100]. déjame saber si necesitas el código completo.

 Random ran = new Random(); int probability = ran.Next(0, 100); string s; if (probability == 0) s = "Heal"; else if (probability <= 70) s = "Attack"; else if (probability <= 85) s = "Amplify"; else if (probability <= 100) s = "Defense";
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!