stackman
stackman

Reputation: 342

Avoid hard-coding all possibilities

I'm making a Xamarin app which has a slider between 1-100. I want it to be so when the slider is at a certain number, the output will do this valueLabel.Text = output; I.e. it will display the contents of the output variable.

output = p1 + p11 + p2

Random r = new Random();
int countLower = r.Next(lower.Count);//I have a list called lower, im getting random values from it
int countLower1 = r.Next(lower.Count);

var p1 = lower[countLower];
var p11 = lower[countLower1];

For example, if the value of the slider (var cat) is 5, I want the output to have 5 things (countLower + countLower1 + countLower2 + countLower3 + countLower4) But i dont know how i can automate the creation of this code based on the slider number. I dont want to hard-code each possibility, is there any way?

I am getting the slider value as such:

public void Slider_ValueChanged(object sender, ValueChangedEventArgs e)
{
    var newStep = Math.Round(e.NewValue/step);
    var cat =newStep.ToString(); 
    label.Text = cat;
}

Upvotes: 0

Views: 234

Answers (2)

Enigmativity
Enigmativity

Reputation: 117144

Try this:

int output = Enumerable.Range(0, newStep).Select(x => lower[r.Next(lower.Count)]).Sum();

Upvotes: 1

AJ X.
AJ X.

Reputation: 2770

This isn't tested, but the idea is that for each movement on the slider, you generated N random numbers up to the slider value then use String.Join() to bring them all together.

public void Slider_ValueChanged(object sender, ValueChangedEventArgs e)
{
    var things = new List<int>();
    var newStep = Math.Round(e.NewValue/step);
    Random r = new Random();

    for (var i = 0; i < newStep; i++) {
         things.Add(r.Next(i);     
    }

    var cat = string.Join(",", things); 
    label.Text = cat;
}

Upvotes: 0

Related Questions