Choose random numbers from a string

Hi all, first post here.

I’m wondering how I might go about writing a function or a few lines of code that would translate a string like “R2_1001+1002+1003+1004” into a string like “1001+1003”, with those 2 numbers being chosen randomly (or pseudo-randomly) from the ones listed. The “R2_” prefix indicates that 2 random numbers should be chosen. Other cases might be much longer strings with a prefix like “R16_” or something.

Any help would be much appreciated!

split the string on the _, as that seems to be your delimeter for ‘count’ vs ‘selectable numbers’. You now have 2 strings: “R####” and “####+####+####+####+####”.

Remove the R from the front of the first string, and parse the rest to an integer (int.TryParse).

This is your count.

Next with your second string, split the string on the “+” sign, as that is your delimeter there.

From that collection of strings, select ‘count’ number of them randomly. You could do this by shuffling the array and grabbing the first ‘count’, or you could stick them in a list and remove ‘count’ of them at random indices, or many other ways of ‘picking a random set’.

Then join the selected strings back together, using the “+” as the delimeter again, with string.Join.

Done.

2 Likes

Thanks for the quick reply! Much appreciated :slight_smile: