Home >Backend Development >C++ >How to Randomly Select and Display an Item from an ArrayList?
Get random items from ArrayList
Accessing random elements from a list is a common task in programming. In this article, we will explore an efficient way to retrieve random string items from an ArrayList.
Question:
Given an ArrayList containing strings, the goal is to design a mechanism that allows the user to click a button and randomly select a string from the list. The selected string should then be displayed in the message box.
Solution:
The solution involves the following steps:
Create a random instance: Instantiate a Random class instance. It is recommended to avoid creating new instances frequently to maintain the stability of random number generation. Consider using static fields:
<code class="language-c#">static Random rnd = new Random();</code>
Generate random index: Generate a random number within the item count range of an ArrayList using a Random instance:
<code class="language-c#">int r = rnd.Next(list.Count);</code>
Retrieve and display random items: Get the selected string from the ArrayList using the generated index and display it in the message box:
<code class="language-c#">MessageBox.Show((string)list[r]);</code>
Implementation Overview:
Create a button in your app.
Assign the following event handler to the button's Click event:
<code class="language-c#">private void button_Click(object sender, EventArgs e) { int r = rnd.Next(list.Count); MessageBox.Show((string)list[r]); }</code>
The above is the detailed content of How to Randomly Select and Display an Item from an ArrayList?. For more information, please follow other related articles on the PHP Chinese website!