dimanche 12 septembre 2021

How to pick a random item from a Map

I have written some codes to pick a random item from a Map<String, Map<String, List>>. But it seems a bit complicated, is it spaghetti code at the moment? Any more direct ways? thanks.

import 'dart:math';

Map<String, Map> allEquations = {'mech' : mechTopics, 'elect' : electTopics};

Map<String, List> mechTopics = {'motion' : motionEquations, 'newtonsLaw' : newtonsLawEquations};
Map<String, List> electTopics = {'electronics' : electronicsEquations, 'charge' : chargeEquations};

List<String> motionEquations = ['a','b','c'];
List<String> newtonsLawEquations = ['d','e','f'];
List<String> electronicsEquations = ['h','i','j'];
List<String> chargeEquations = ['k','l','m'];

void main() {
  
  getRandomItem ();
  
}


void getRandomItem (){
  
  String selectedItem;
  
  var topicList = allEquations.keys.toList();
  var randomTopic = topicList[Random().nextInt(topicList.length)];
  
  var subtopicList = allEquations[randomTopic]!.keys.toList();
  var randomSubtopic = subtopicList[Random().nextInt(subtopicList.length)];
  List randomItemList = allEquations[randomTopic]![randomSubtopic];
   
  
 selectedItem = allEquations [randomTopic]![randomSubtopic][Random().nextInt(randomItemList.length)];
 print (selectedItem);
}



Aucun commentaire:

Enregistrer un commentaire