Last active
January 2, 2020 22:59
-
-
Save ncarandini/a901564a1944bb07e680c43205254911 to your computer and use it in GitHub Desktop.
Random list from a list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
// Deve essere compreso tra 1 e il numero di quitz | |
const int numOfQuitzzes = 3; | |
// Chiamo il servizio che mi genera la lista di quitz | |
List<string> RandomQuitzList = QuitzService.GetQuitzList(numOfQuitzzes); | |
// Mostro il risultato | |
for(int i = 0; i < numOfQuitzzes; i++) | |
{ | |
Console.WriteLine($"Domanda n.{i}: {RandomQuitzList[i]}"); | |
} | |
} | |
// Define other methods and classes here | |
public static class QuitzService | |
{ | |
static List<string> Quitzzes = new List<string> | |
{ | |
"Di che colore è il cavallo bianco di Napoleone?", | |
"Quanti trentini entrarono in Trento, trottorellando?", | |
"Quante lune ha Giove?", | |
"Quanti mesi dura un anno cinese?", | |
"Pesa più un chilo di paglia o di ferro?", | |
"Qual'è il pianeta più vicino al sole?", | |
"Quanti fusi orari ci sono nel mondo?", | |
"Qual'è il fiume più lungo della terra?", | |
"Chi inventò la macchina a vapore?" | |
}; | |
public static List<string> GetQuitzList(int numOfQuitzzes) | |
{ | |
// Sempre verificare che i parametri siano nel range di valori valido | |
if (numOfQuitzzes < 1 || numOfQuitzzes > Quitzzes.Count) | |
{ | |
throw new ArgumentOutOfRangeException($"Il numero di quiz deve essere compreso tra 1 e {Quitzzes.Count}"); | |
} | |
Random r = new Random(); | |
List<string> result = new List<string>(); | |
while (result.Count < numOfQuitzzes) | |
{ | |
// Creiamo l'elenco delle domande ancora disponibili | |
// (all'inizio sono tutte, poi sono quelle iniziali con esclusione di quelle gia scelte) | |
List<string> availableQuitzzes = Quitzzes.Except(result).ToList(); | |
// Prendiamo un'indice random tra 0 e il numero degli elementi delle domande disponibili (questultimo escluso) | |
int i = r.Next(0,availableQuitzzes.Count); | |
// Aggiungiamo al risultato l'elemento random | |
result.Add(availableQuitzzes[i]); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment