Home > Back-end >  Do not repeat words from the file
Do not repeat words from the file

Time:10-22

I have a problem with duplicating and repeating words.

I have a file.txt that contains multiple words some of them are duplicated.

What I wanted to do is to get random words from file.txt and if the string has been picked previously ignore and pick another word.

For example:

My file contains => "Hello", "Morning", "Hello", "Hi", "Drink", "Cola"

and I get a random string:

public string[] _randomString;
public Random _randomText = new Random();
(...)
_path = "C:\\test\\file.txt"
_randomString = File.ReadAllLines(_path);
_result.Text = _randomString[_randomText.Next(_randomString.Lenght)];

and what I want to do is:

If the word Hello appears again - continue, if it appears first time - shown in _result.Text

But if all words have been picked from file.txt - _result.Text = "All words was shown"

I've tried many options but nothing works for me.

CodePudding user response:

There are lots of issues in your code. Beyond the typos, it is hard to understand what your code actually looks like. I will assume you meant something like this:

class YourClass
{
    public string[] _randomString;
    public Random _randomText = new Random();
    private Result _result;
    private string _path;

    public void ShowAllWordsInRandomOrder()
    {
        _path = "C:\\test\\file.txt";
        _randomString = File.ReadAllLines(_path);
        _result.Text = _randomString[_randomText.Next(_randomString.Length)];
     }

}

Your first obvious problem is that you are only showing one word. If you wanted to show all of them you would have to iterate through all the words. It sounds like your next issue is that you need to get only the distinct values from the file. Here's a variation of your code that addresses these issues. I have taken the liberty to do some basic code cleanup for you as well:

class YourClass
{
    private Result _result;
    private const string _path = "C:\\test\\file.txt";

    public void ShowAllWordsInRandomOrder()
    {
        var random = new Random();
        var words = File.ReadAllLines(_path).Distinct().ToList();
        while (words.Any())
        {
            DisplayNext(words, random);
        }
    }
    void DisplayNext(IList<string> words, Random random)
    {
        var text = "All words was shown";
        if (words.Any())
        {
            var index = random.Next(0,words.Count-1);
            text = words[index];
            words.RemoveAt(index);
        }
        _result.Text = text;
    }

}

CodePudding user response:

You can use HashSet<string> it will store only unique items. So, you can do this :

var hashSetLines  = new HashSet<string>(File.ReadAllLines(_path));
_randomString = hashSetLines.ToArray();
_result.Text = _randomString[_randomText.Next(_randomString.Lenght)];
  •  Tags:  
  • c#
  • Related