• 0

Java: Generate the alphabet in random order, no duplicates


Question

Hi guys,

I am taking an introductory programming course and need a bit of help. The assignment is to have the Java program read a message (I am assuming from a .dat file, not quite sure). The program creates substitutes each random letter with a different letter chosen at random by the computer. If the letter M is chosen to replace the letter P in the message, then M replaces P in every instance of the message.

Right now, I just need help with generating a set of the 26 letters ordered randomly without duplicates. Here is what I have:

import java.util.Random;

public class encrypt {

public static void main(String[] args) {

char [] alphabet =

{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

char [] substitute =

{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

boolean done=false;

Random generator = new Random();

int i, j, k, random;

while(done==false) {

for(i=0; i<=25; i++) {

random = generator.nextInt(25);

substitute=alphabet[random];

for(j=0; j<=i; j++) {

while(substitute[j]==substitute) {

random = generator.nextInt(25);

if(substitute[j]!=substitute) {

substitute=alphabet[random];

}

}

}

}

for(k=0; k<=25; k++) {

System.out.print(substitute[k] + ", ");

}

done=true;

}

}

}

Right now the program does nothing. If I remove the last for loop with j as the counter and everything within that for loop, I get an output of 26 letters randomly chosen, but there are duplicates. The last for loop is supposed to say something like, "If the randomly generated letter (substitute) has appeared before in substitute[], then generate a new random number until it is no longer a duplicate of a previous number, at which point the letter which corresponds to the random number is stored in substitute.

So if you could give me some suggestions it would be much appreciated. If I am overcomplicating things and there is a much easier way to do this, please guide me in the right direction.

Thanks,

Noah

EDIT: Spacing in the program code isn't working. Looks fine while I'm editing it though. What's wrong?

EDIT 2: See here for my code, correctly formatted.

Edited by -Noah-

Recommended Posts

  • 0
These solutions are all overkill...

- Make an ArrayList containing all 26 letters.

- generate random number from 0 to List.size()-1.

- List.get(randomNumber)

- List.remove(randomNumber)

loop and restart at step 2 until List.size() returns 0.

import java.util.*;

class alphaRandom {

	public static void main(String[] args) {

	ArrayList&lt;Character&gt; al = new ArrayList&lt;Character&gt;();
	Random gen = new Random();
	int num;

	for(int i = 65; i &lt;= 90; i++) {
		al.add((char)i);
	}

	while(al.size() &gt; 0) {
		num = gen.nextInt(al.size());
		System.out.print(al.get(num));
		al.remove(num);
	}
 }
}

There you go.

Was about to post but saw that... that's the right idea!

Chris

  • 0

Tech God (and bmaher): That's awesome! Only thing I don't understand is this line:

num = gen.nextInt(al.size());

As the size gets smaller, and eventually reaches 1, the equivalent would be:

num = gen.nextInt(1);

Wouldn't this be telling the program to generate a random integer from 0 to 0? Other than that, sweet!

  • 0

The Teej: Thanks for the reply, but unfortunately, the same problem occurs. :huh: I decided to modify it a bit. I figured there was no reason for a do while over a while, and that I could eliminate the for loop, and put a counter in the new while loop. Here is the result:

import java.util.Random;

public class encrypt {

  public static void main(String[] args) {
	char [] alphabet =  {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
	char [] substitute = {'.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.'};
	int [] numbers = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
	Random generator = new Random();
	int random, j=0;
	boolean done=false;
	random=generator.nextInt(26);

	while (done==false) { //While the program has not generated all of the letters of the alphabet in random order without duplicates
		if (numbers[random] == -1) { //If the random number has not yet been used
			numbers[random] = random; //then assign that position in the array that number (i.e. position 10 in the array will now have the number 10), so it's considered to be used
			substitute[j] = alphabet[random];  //assign the current position of the substitute alphabet array the random letter from the real alphabet
			j++; //Counter goes up by one because a letter has been successfully chosen
			random=generator.nextInt(26); //Generate a new random number for the next iteration of the while loop
			if (j==26) {
				done=true; //If the counter has reached 26, stop the while loop, as all 26 letters of the alphabet have been generated
			}
		} else { //If the random number has been used already
			random = generator.nextInt(26); //then generate a new random number for the next iteration of the while loop
		}
	}

	for(int i=0; i&lt;=25; i++) {
		System.out.print(substitute[i] + ", "); //Prints out the randomized alphabet
	}
  }
}

It works, too! Thanks for leading me in the right direction. Wonder why your code doesn't work, though. :rofl:

@ All:

Thanks for all the helpful posts. I will make sure to show my teacher some of the posts on the defining of the integer within the for-loop. :D

EDIT: Figured out how to use code tags! Thought you guys used quote tags 'cause the boxes look similar. :blush:

Edited by -Noah-
  • 0
Tech God (and bmaher): That's awesome! Only thing I don't understand is this line:

num = gen.nextInt(al.size());

As the size gets smaller, and eventually reaches 1, the equivalent would be:

num = gen.nextInt(1);

Wouldn't this be telling the program to generate a random integer from 0 to 0? Other than that, sweet!

yep, so you'd have no choice except to get zero. The last element left.

  • 0
yep, so you'd have no choice except to get zero. The last element left.

Got it now. So it chooses a number at random, removes it from the array, and then repeats the process until there are no numbers left. Awesome. I'm gonna have to remember ArrayLists. :D

  • 0
Got it now. So it chooses a number at random, removes it from the array, and then repeats the process until there are no numbers left. Awesome. I'm gonna have to remember ArrayLists. :D

Familiarise yourself with the Java Collections Framework, it has all kinda of handy classes/interfaces like ArrayList :)

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I bought one of these last year. I really hope I won't have to deal with this crap. My drive is in good condition at the moment.
    • Umm, read my answer again! If you have something to add or contribute, feel free. Otherwise my point was that you apparently dont want faster updates... so you want slower updates by process of elimination. If you have something to contribute, meaningful answers are better.
    • These features described above are good, but far from what developers will like the most. The main feature that developers will care and love the most it's called "Bring Your Own Models". It gives us the ability to connect to LOCAL AI models running on Ollama. The feature it's located on GitHub Copilot tab -> On the model picker where you can select "manage models" instead of paid models and then it will show you the "Bring your own models" window where you can now select Ollama and the endpoint of your local server. So if you have a beefy spec machine you can now use your own model 100% local inside Visual Studio 2026 18.7.0
    • Microsoft Teams is getting a controversial location tracking feature that users may hate by Usama Jawad Image generated with Microsoft Copilot Earlier this year, Microsoft planned to roll out a controversial location tracking feature in Teams, but following customer feedback, it decided to delay its release. The bad news is that the company has decided to launch it later this year, but it's based on roughly the same design that was shared earlier, which means that many users still have good reason to worry. Basically, Microsoft Places and Teams have received workplace check-ins via Wi-Fi. The idea is that if an employee arrives at the office and connects to their enterprise network, their profile status indicator will show them as being present in the office. For example, if you arrive at work, open Teams on your PC, and connect to the "Studio B" company Wi-Fi network, your Teams profile will indicate that you are present in "Studio B", as shown below: Microsoft says that this feature is basically a replacement for physical workplace check-in peripherals, it reduces the need to manually update your status, and it also enables co-workers to know that you're at work so that they can coordinate in-person meetings with you. IT admins can enable this workplace check-in capability at a tenant level, and users have the ability to control whether they want to enable it or not. Of course, all of that sounds great on paper, but naturally, many Teams customers may still have concerns, as they did before. This is because it enables your reporting manager and other members of the organization to track if you are at the office, when you arrive at the office, and where you are right now. This could be problematic for people who work in what they consider to be flexible work environments or hybrid setups, and this kind of location tracking could be considered an invasion of privacy. Microsoft has tried to alleviate some of these concerns by letting users know that they can manually set their location easily, which essentially overrides workplace check-in if they feel uncomfortable with it. However, that doesn't really solve the problem because your organization could enforce a workplace policy that mandates that this feature remains enabled. The Redmond tech giant has also assured users that this capability does not store historical data and is only a real-time indicator of location. Finally, it only generates a signal when you connect to a corporate network, which means that if you are working from home and connect your PC to your personal Wi-Fi, it won't broadcast your location to your employer; you will simply be shown as "Remote". Microsoft has encouraged IT admins to prepare for this change and begin informing users so they know what to expect once it begins rolling out later this year.
  • Recent Achievements

    • Very Popular
      AndrewSteel earned a badge
      Very Popular
    • Veteran
      Taliseian went up a rank
      Veteran
    • One Month Later
      Clizby earned a badge
      One Month Later
    • One Month Later
      Timaximus earned a badge
      One Month Later
    • Week One Done
      Timaximus earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      516
    2. 2
      +Edouard
      162
    3. 3
      PsYcHoKiLLa
      157
    4. 4
      Steven P.
      82
    5. 5
      ATLien_0
      81
  • Tell a friend

    Love Neowin? Tell a friend!