Monday, August 10, 2015

Generating Random Strings


How would you generate a random list of strings in java?

This is an exercise I set for myself today. And here's the code:

Collection generateRandomStrings(int numberOfStrings)
	{
		Random r = new Random();
		int range = 26, len;
		Character alphabet;
		StringBuffer word;
		
		List wordList = new ArrayList();
		for(int i=0; i< numberOfStrings; i++)
		{
			len = r.nextInt(5) +1;
			word = new StringBuffer();
			for(int j=0; j< len; j++)
			{
				alphabet = (char) ('a' + r.nextInt(range));
				word.append(alphabet);
			}
			wordList.add(word.toString());
		}
		return wordList;
	}

No comments:

Post a Comment