I am trying to write a program that generates an array of 3 random letters out of a choice of 6. I then want to copy the array and sort it, then check that none of the letters are duplicated. This is causing me major problems. The code I have done so far is

``````final int SIZE = 3;
char [] letters = new char [SIZE];
for (int i=0; i< SIZE; ++i)
{
letters [i] = (char)((int)6*Math.random() + (int)'a');
sortArray(letters);
}

char sortArray(char [] letters)
{
int swaps, length=letters.length;
char temp;
do
{
{
swaps =0;
for i=0; i < length-1; ++i)
{
if (letters[i] > letters [i+1]
{
temp  = letters[i];
letters[i] = letters[i+1];
letters[i+1] = temp;
++swaps
}
}
}
while swaps>0;
return sortArray;
}

if sortArray[0] == sortArray[1] || sortArray[0] == sortArray [2] || sortArray[1] == sortArray[2]
final int SIZE = 3;
char [] letters = new char [SIZE];
for (int i=0; i< SIZE; ++i)
{
letters [i] = (char)((int)6*Math.random() + (int)'a');
}
``````

very messy I know. I am running out of time and would appreciate it greatly if someone could point out where I am going wrong. I've rewritten this code many times and it is not getting any clearer!
Thanks

Edited by Dani: Formatting fixed

2
Contributors
2
Replies
4
Views
12 Years
Discussion Span
Last Post by hjangel

One thing I notice immediately is that you're throwing away the result of your sortArray method.
That means you're never sorting your array at all (or at least, you're sorting it but then keep on using the unsorted array).

Thanks for the pointer - could you tell me where I am doing this (I've been staring at this piece of code for weeks and find it hard to be objectionable now)? How do I avoid throwing it away?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.