Coding in C++: How do you display a random array?
I am attempting to code in C++ a program that would display random strings from an array, arranged in different groupings within two columns. I am trying to simulate a simple economy. I have an array of Products offered and Products Desired. How would I make this a reality so that the economy is different each time the program is run?
Observing members:
0
Composing members:
0
6 Answers
Are you having trouble generating the array or just displaying it?
I’m curious about the choice of C++ too. There are other languages where this would be much simpler.
If there’s a built in way to generate random strings in C++, then I don’t know about it, but here’s basically how I would go about doing it manually. I also don’t know your level of programming proficiency so let me know if I need to explain any of these bullets further.
- There is a library called random (I believe, my peak in C was awhile ago and I haven’t worked with ++ much at all) for generating random numbers.
– Is the desired length of strings known or should that be random too? I’d start by generating string lengths if that also needs to be generated.
– Allocate the memory necessary for that number of chars. Unless C++ has better string handling than C, keep in mind that this will be an array of character arrays….less than ideal.
– For each string, again generate random numbers. If you only want letters a-z and A-Z then generate numbers from 65–90 and 97–122. You can then cast these integers to char and it will convert them to the character in the ASCII table that corresponds to the number. See ASCII table here: http://www.asciitable.com/. Obviously if you want numerals or punctuation to be available you’ll have to alter your ranges as needed
– Ta da. To display, iterate through the array and use printf.
Oh shit I just reread your question…...oops
OK so you’re not trying to generate random strings. You already have the array and you want to sample from it randomly? That’s easier.
- Generate a random number in the range of the indices of your array
– Index your array with that number (i.e. strings[numberYouveAlreadyGenerated])
– call printf with that ^ as the argument.
Just use the rand function in your index to grab array elements.
If it’s a simulation, where you actually need to remember the randomized products and use them, rather than just display random names once, then you’ll probably want a product class, with a data member variable for name and/or type, and when you create each object of that class, assign it a random value for name and/or type, with product names (and possibly type names too) chosen randomly from one or more tables of names, which you could either define in code in a const array of string constants, or by loading from a file.
Answer this question
This question is in the General Section. Responses must be helpful and on-topic.