5 Replies - 3420 Views - Last Post: 16 December 2015 - 04:19 PM Rate Topic: -----

#1 Yoshimiii   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 20-November 15

C# Get random string from list based on parameter

Posted 16 December 2015 - 12:04 PM

I want to be able to get a random string from the List of animation strings based on the type of animation that it is, e.g. attack, chase, death, idle etc.

How do I do this without having a long switch statement and an enum or lots of if/else statements?

    public class AnimationController
    {
        private List<string> _animations = new List<string>
    	{
    			"Zombie_Atk_Loop_1", "Zombie_Atk_Loop_3", "Zombie_Atk_Loop_4",
    			"Zombie_Chase_1_Full_Loop_IP", "Zombie_Chase_4_Full_Loop_IP",
    			"Zombie_Crawl_1_Loop", "Zombie_Crawl_2_Loop",
    			"Zombie_Death_Back_Mid_1", "Zombie_Death_Forward_1", "Zombie_Death_Left_1", "Zombie_Death_Right_1",
    			"Zombie_Idle_1",
    			"Zombie_Reach_1", "Zombie_Reach_2",
    			"Zombie_Stand_Chase_1", "Zombie_Stand_Chase_4",
    			"Zombie_Stand_To_Atk_1", "Zombie_Stand_To_Atk_3", "Zombie_Stand_To_Atk_4",
    			"Zombie_Stand_Walk_F_1", "Zombie_Stand_Walk_F_5",
    			"Zombie_Turn_L_90_1", "Zombie_Turn_L_180_1", "Zombie_Turn_R_90_1", "Zombie_Turn_R_180_1",
    			"Zombie_Walk_F_1_Full_Loop_IP", "Zombie_Walk_F_1_Loop_IP", "Zombie_Walk_F_5_Full_Loop_IP", "Zombie_Walk_F_5_Loop_IP"
        };
    
        public void PlayRandomAnimation(/*animation type*/)
    	{
    		//Get a random animation based on the above type of animation parameter passed in (idle, chase, death etc).
    	}
    }

    public class ZombieAI
    {
        AnimationController _animationController;
       
        void Idle()
    	{
    		_animationController.PlayRandomAnimation(/*Animation Type passed in*/);
    	}
    }


Is This A Good Question/Topic? 0
  • +

Replies To: C# Get random string from list based on parameter

#2 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: C# Get random string from list based on parameter

Posted 16 December 2015 - 12:20 PM

Well, I have a question for you: does the "type of animation parameter passed in" relate to part of the string? I.e. if you pass in "walk", you want to return a random result that contains the text "walk" in it? Or do you need to categorize these various strings some other way?

If it's the first, you can use LINQ to filter your collection. Example:

var strings = new List<string>() { "String1", "String2", "X-String3"};
var filteredStrings = strings.Where(s => s.StartsWith("S")).ToList();
//filteredStrings now contains {"String1", "String2"}


Then, since your filteredStrings would be a List, you can just get a random number between 0 and filteredStrings.Count, and use that to get the string at that index.
Was This Post Helpful? 1
  • +
  • -

#3 Yoshimiii   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 20-November 15

Re: C# Get random string from list based on parameter

Posted 16 December 2015 - 12:50 PM

View PostCurtis Rutland, on 16 December 2015 - 12:20 PM, said:

Well, I have a question for you: does the "type of animation parameter passed in" relate to part of the string? I.e. if you pass in "walk", you want to return a random result that contains the text "walk" in it? Or do you need to categorize these various strings some other way?

If it's the first, you can use LINQ to filter your collection. Example:

var strings = new List<string>() { "String1", "String2", "X-String3"};
var filteredStrings = strings.Where(s => s.StartsWith("S")).ToList();
//filteredStrings now contains {"String1", "String2"}


Then, since your filteredStrings would be a List, you can just get a random number between 0 and filteredStrings.Count, and use that to get the string at that index.


That works, thanks.
Was This Post Helpful? 0
  • +
  • -

#4 JacobH   User is offline

  • D.I.C Head
  • member icon

Reputation: 27
  • View blog
  • Posts: 181
  • Joined: 07-September 15

Re: C# Get random string from list based on parameter

Posted 16 December 2015 - 01:01 PM

Maybe you mean something like this?

Use:
   
    // This should return a random B- string.
    var example = new Example();
    var randomString = example.SelectSemiRandomString("B-");
    Console.WriteLine(randomString);


The class:

  public class Example
    {
        public List<string> Items { get; } = new List<string>();

        public Example()
        {
            FillList("A-Hi", "A-Bye", "A-Run", "B-Walk", "B-Sit", "B-Stand");
        }

        public void FillList(params string[] strings)
        {
            Array.ForEach(strings, s => Items.Add(s));
        }

        public string SelectSemiRandomString(string relatedString)
        {
            var newStringArray = Items.TakeWhile(s => s.Contains(relatedString)).ToArray();
            const int minValue = 0;
            var maxValue = newStringArray.Length;
            var random = RandomHelper.GenerateNumber(minValue, maxValue);
            return newStringArray[random];
        }
    }

Was This Post Helpful? 0
  • +
  • -

#5 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: C# Get random string from list based on parameter

Posted 16 December 2015 - 02:43 PM

@Jacob, you're basically doing the same thing I did, but with several more steps. There are things you can do to make your code somewhat more efficient from a readability and code-writing sense.

For example, your FillList takes a params array and loops it. But this is just as effective:

Items = strings.ToList();


But the method itself is unnecessary, because you can use a collection initializer.

Similar stuff in the SelectSemiRandomString; TakeWhile is an interesting function, but Where is the more "correct" one. In fact, TakeWhile doesn't do what you think it does here. It will take from the List until it reaches the first "false" result, then it will stop taking. So, if the first item doesn't match, it will yield an empty array. Basically, if you give it any parameter other than "A", it will not find any strings to match. Where is the "filter" method. It will test each element in the collection, and include the ones that evaluate to true in the resulting collection.

Here's how I would re-write your example:

public class Example
{
	private Random random = new Random();
	
	public List<string> Items { get; } = new List<string>
	{
		"A-Hi", "A-Bye", "A-Run", "B-Walk", "B-Sit", "B-Stand"
	};

	public string SelectSemiRandomString(string part)
	{
		var filtered = Items.Where(i => i.Contains(part)).ToList();
		var result = filtered[random.Next(0, filtered.Count)];
		return result;
	}
}

Was This Post Helpful? 0
  • +
  • -

#6 JacobH   User is offline

  • D.I.C Head
  • member icon

Reputation: 27
  • View blog
  • Posts: 181
  • Joined: 07-September 15

Re: C# Get random string from list based on parameter

Posted 16 December 2015 - 04:19 PM

Quote

@Jacob, you're basically doing the same thing I did, but with several more steps.


Right, I actually came back to this thread after having it open an hour or so and when I made my post I was not aware you already responded.

Quote

There are things you can do to make your code somewhat more efficient from a readability and code-writing sense.


I would hope so, considering I am still very new all things considering and have a lot of poor code even in my own projects I care about. I'm sure it's even worse in my snippet examples trying to show some one how it *could* be done to give them a brain storm, I pretty much never want to show people *how* to do X.

Quote

For example, your FillList takes a params array and loops it. But this is just as effective:


I chose the FillList method in my example because I was writing the test inside a WinForm app I wrote that compiles and runs the code on the fly, so I used it to clear and add new objects easily with just typing "a", "b", etc. It sucks of course in practical use.

Quote

Here's how I would re-write your example:


Much better. It looks about how I would want it to look, assuming I did not care about my list being exposed to the public as a writable object. Just ever so slightly more tidy, I think that those brackets pop out on too short of a line for my taste and I am not the biggest fan of multi line variable chains, I prefer zero in small methods if I can.

Sadly, with out enumerating over the items twice I am not sure how the two lines can be avoided :)/>/>.


   public class Example
    {
        private Random Random { get; } = new Random();
        public List<string> Items { get; } = new List<string> {"A-Hi", "A-Bye", "A-Run", "B-Walk", "B-Sit", "B-Stand"};

        public string SelectSemiRandomString(string part)
        {
            var list = Items.Where(s => s.Contains(part)).ToList();
            return list[Random.Next(0, list.Count)];
        }
    }

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1