I have the follwing array:
char song[] = {'c', 'd',' ', 'e', 'f',' ', 'g', 'a', 'b', 'C',' '};
I want to generate a random string of length specified by me like this int len=10
How can i do this
char notes[] = "RANDOM DATA GENERATED HERE";
I have the follwing array:
char song[] = {'c', 'd',' ', 'e', 'f',' ', 'g', 'a', 'b', 'C',' '};
I want to generate a random string of length specified by me like this int len=10
How can i do this
char notes[] = "RANDOM DATA GENERATED HERE";
Use a for loop than runs the required number of times and for each iteration of the loop generate a random number between 0 and the number of indices in the song array. Use the random number to select the appropriate entry from the song array and then save it in the notes array using the current value of the for loop variable as the index to the notes array. Don'y forget put a '\0' at the end of the notes array to terminate the string.
Something like this
char song[] = {'c', 'd',' ', 'e', 'f',' ', 'g', 'a', 'b', 'C',' '};
const byte songLength = sizeof(song) / sizeof(song[0]);
char notes[11]; //allow 1 extra for the NULL
void setup()
{
Serial.begin(115200);
for (int n = 0; n < 10 ; n++)
{
notes[n] = song[random(0, songLength)];
notes[n + 1] = '\0';
Serial.println(notes);
}
}
void loop()
{
}
NOTE (pun intended)
The random() function will produce the same sequence of numbers each time the program is run
It seems to me that you have got the names of the arrays round the wrong way.
The thread title asks about creating a String but the text seems to indicate that a string is required.
You forgot the all-important "int len = 10;".
const int len = 10;
char song[] = {'c', 'd',' ', 'e', 'f',' ', 'g', 'a', 'b', 'C',' '};
const byte songLength = sizeof(song) / sizeof(song[0]);
char notes[len+1]; //allow 1 extra for the NULL
void setup()
{
Serial.begin(115200);
for (int n = 0; n < len ; n++)
{
notes[n] = song[random(0, songLength)];
notes[n + 1] = '\0';
Serial.println(notes);
}
}
void loop()
{
}