Pick Random String from Array

Pick Random String From Array

The simplest way (but slow for large lists) would be to use a resizeable container like List and remove an element after picking it. Like:

var names = new List<string> { "image1.png", "image2.png", "image3.png", "image4.png", "image5.png" };

int index = random.Next(names.Count);
var name = names[index];
names.RemoveAt(index);
return name;

When your list is empty, all values were picked.

A faster way (especially if your list is long) would be to use a shuffling algorithm on your list. You can then pop the values out one at a time. It would be faster because removing from the end of a List is generally much faster than removing from the middle. As for shuffling, you can take a look at this question for more details.

Random element from string array

Just store the index generated in a variable, and then access the array using this varaible:

int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);

P.S. I usually don't like generating new Random object per randoization - I prefer using a single Random in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.

According to this approach, I will have some variable Random r somewhere, and I will just use:

int idx = r.nextInt(fruits.length)

However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.

How can I select a random string from an array and assign it to a variable?

You should use Math.random method.

var random=Math.floor((Math.random() * names.length));
var randomName=names[random];

Also, in javascript the arrays are declared like this :

var names = ["bob","tom","jake"];

not

var names = array["bob","tom","jake"];

var names = ["bob","tom","jake"];var random=  Math.floor((Math.random() * names.length));var randomName=names[random];console.log(randomName);

Get random string from array in Android and place it in a text view

Put your names in a string array:

<resources>
<string-array name="nomes">
<item>Ivan</item>
...
</string-array>
...
</resources>

Then use Random to get a random name from the array:

private String[] names;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
names = getResources().getStringArray(R.array.nomes);
}

@Override
public void onClick(View v) {
int randomIndex = new Random().nextInt(names.length);
String randomName = names[randomIndex];
yourTextView.setText(randomName);
}

kotlin Get random string from array

Your function doesn't specify a return type, that's why the compiler is expecting 'Unit' which would be the same as void in Java.

When you want to return a String, you need to specify it like so

fun getRandomQuote(): String {
val randomValue = Random.nextInt(quotes.size)
return quotes[randomValue]
}

See the docs for Kotlin functions as a reference.

It is also more kotliny to use indexing for arrays with square brackets instead of get() function.

Get Random String from an Array

I'd rather using arc4random(), this code will pick up random items from your array:

let firstArray = ["hi", "bye", "hello"]
let randomItem = Int(arc4random() % UInt32(firstArray.count))
myLabel.text = "\(firstArray[randomItem])"

Pick randomly string from array in C

You've declared random as a char, which is a single byte integral value. You're assigning to it an element from the words array, and each of those elements is of type char*. Hence, you are getting an error about trying to assign a char* to an integer value.

You meant to declare randomas a char*.

Other things I'll point out about your code:

void pick() {
char* words[2]; // 1
words[0] = "blah";
words[1] = "hmm";

char random; // 2
srand(time(NULL));
random = words[rand() % 2]; // 3
printf(random); // 4
return;
}
  1. This should be declared as an array of const char* since you're assigning string literals (which are immutable) to it.

  2. random also should be declared as const char*.

  3. Using % to get random numbers in a specific range traditionally is not very good. Also see Q13.16 How can I get random integers in a certain range? from the comp.lang.c FAQ.

  4. printf(random) is dangerous. If the string you're printing happens to include % characters, then printf will misbehave (and this potentially could be a security vulnerability). You always should prefer printf("%s", random). And since you probably want a trailing newline, it ought to be printf("%s\n", random) or just puts(random).

Getting multiple random strings from array of strings

You can use Math.random(). This will generate a random number between 0 and 1 (excluding 1). You can then multiply this number by the length of the array, and use Math.floor() to generate an index in the array. When we use splice, it will mutate the original array, but it ensures that there will not be duplicate values.

const arr = ['Text1', 'Text2', 'Text3', 'Text4', 'Text5']const out = []const elements = 2
for (let i = 0; i < elements; i++) { out.push(...arr.splice(Math.floor(Math.random() * arr.length), 1))}
console.log(out)

Select a random string from an array

var textArray = [
'song1.ogg',
'song2.ogg'
];
var randomNumber = Math.floor(Math.random()*textArray.length);

audioElement.setAttribute('src', textArray[randomNumber]);


Related Topics



Leave a reply



Submit