How can I iterate through each item in an array in a random order using c++?
- User
How can I iterate through each item in an array in a random order using c++?
- Assistant
To iterate through each item in an array in a random order using C++, you can use the Fisher-Yates shuffle algorithm.
Here is an example implementation:
cpp#include <iostream> #include <cstdlib> #include <ctime> using namespace std; void shuffle(int arr[], int size) { srand(time(NULL)); // initialize random seed for (int i = size - 1; i >= 1; i–) { int j = rand() % (i + 1); // generate a random index between 0 and i swap(arr[i], arr[j]); // swap the elements at indices i and j } } int main() { int arr[] = {1, 2, 3, 4, 5, 6}; int size = sizeof(arr) / sizeof(arr[0]); // obtain the size of the array shuffle(arr, size); // shuffle the array elements // iterate through the shuffled array for (int i = 0; i < size; i++) { cout << arr[i] << " "; } cout << endl; return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)