❔ Random take a File from a Folder
Hello Dear CSharp Programmers
I have a Question, lets say I have a folder with 1_000 Files. From this folder I would like to randomly pick 1_00. But every file should be taken only once.
How would this method look like ?
I tryed it by myself but it always take one file more then once.
my Code:
I wanted to also store all ever picked Files and always check if the newly picked random file has already used once or not but I couldnt manage to code it.
thank you for every help
14 Replies
Get all the files, shuffle them with Fischer-Yates algorithm, pick the first 100
that, or you simply save the numbers you already had before and check if it has been used before, if so, take a new number. sure, near the end it could happen that it says the same number multiple times but unless you need a very high efficient solution, this should do. can be done with only a few lines of extra code
Or use a list, and
.RemoveAt()
to remove the item, then get a new random indexeven better solution tbh, if you don't mind them disappearing from your list ofcrs
Could always later
leftovers.Concat(selected)
to get the full list backwell, then you almost end up to my solution as you now have a list of files to save, instead of a list of numbers 😄 but could be slightly better still
True lol
ok thank you guys. So my code is completly wrong or is anything I could add to it so it those what you said ? xD
Well, your code doesn't guarantee picking all unique files in the first place
It seems to guarantee that two of the same file won't be selected back to back, but nothing more than that
wouldn't call it wrong, just incomplete
might this one be correct ?
yeah, that shoudl do
just make sure to make a new list<int> if you intend to use the methode multiple times without fully restoring the app
otherwise no single number woudl work if you use it a few times 😄
would usedRandomNumbers.clear(); also work every time I call it ?
but well ! thank you very much guys !
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.