Dag Posted April 6, 2023 Share Posted April 6, 2023 (edited) Hi, I need to randomize name attribute and have a dict of names wich I have to randomize with. Dict is as rob, car, ed. The way I wanted to do it is like this but it does not work if(name == "name", switch(int(rand($PT)*3), 0, "rob", 1, "car", 2, "ed"), "don") How can I get a result I want? Thanks! D. Edited April 6, 2023 by Dag Quote Link to comment Share on other sites More sharing options...
Alain2131 Posted April 6, 2023 Share Posted April 6, 2023 Hi, You want to start with an array of names string names[] = {"rob", "car", "ed"}; Then, you want a random number, which goes from zero to the amount of items in the array float random_value = rand(@ptnum) * len(names); You need an integer, so you can floor() the result int random_id = floor(random_value); This could be combined with the previous line, like so int random_id = floor(rand(@ptnum) * len(names)); Then, you can fetch the corresponding index from your names array string picked_name = names[random_id]; In the end, this is the result string names[] = {"rob", "car", "ed"}; // Array of names int random_id = floor(rand(@ptnum) * len(names)); // Random ID, from zero to the amount of items in the array string picked_name = names[random_id]; // The name corresponding to the random ID 1 Quote Link to comment Share on other sites More sharing options...
Dag Posted April 7, 2023 Author Share Posted April 7, 2023 (edited) Thank you very much also for explaining the steps!!! It works fine Edited April 7, 2023 by Dag Quote Link to comment Share on other sites More sharing options...
Ziyad Posted April 7, 2023 Share Posted April 7, 2023 Just adding a similar way of generating the random value without floor() int rand_id = (int)fit01(rand(@ptnum+1), 0, len(names)); Quote Link to comment Share on other sites More sharing options...
Dag Posted April 7, 2023 Author Share Posted April 7, 2023 Thank you. what a benefit is it versus the floor version? Quote Link to comment Share on other sites More sharing options...
Alain2131 Posted April 11, 2023 Share Posted April 11, 2023 Essentially, both solutions are the same. Speed isn't a concern, and it literally returns the same result (taking into consideration @ptnum+1). Basically, use what makes sense to you, or what you like. Quote Link to comment Share on other sites More sharing options...
Dag Posted April 11, 2023 Author Share Posted April 11, 2023 Thank you! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.