• 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

    • When will the Photos app be updated to remember the window size and position when reopened? They addressed this issue in a 2024 version of the app (though I can't recall the build number). Unfortunately, after that specific version, the problem persists! Please prioritise this fix in your K2 schedule. Additionally, the Snipping Tool has lost the ability to capture the Windows Taskbar starting from the 2024 version!
    • Same, never saw it on Android or iOS. Guess only some people got it *shrugs*
    • Anthropic pulls Fable 5 and Mythos 5 after US export control order by Pradeep Viswanathan In April this year, Anthropic launched the Claude Mythos Preview frontier model with state-of-the-art cyber and coding capabilities for a select set of companies around the world. After preparing appropriate guardrails, early this week, Anthropic launched Claude Fable 5 and Mythos 5, its most capable AI models. Claude Fable 5 is for general users and comes with strict safeguards, while Mythos 5 is designed with fewer safeguards for cybersecurity and biology use cases. Today, Anthropic abruptly suspended access to its Fable 5 and Mythos 5 AI models for all customers after receiving an export control directive from the US government. The company received the directive from the government today at 5:21 p.m. ET, and the received letter did not provide any details regarding the national security concern. Anthropic understands that the government became aware of a method to bypass, or “jailbreak,” Fable 5, which might be the reason behind the directive. The order was issued under national security authorities and requires the company to suspend all access to Fable 5 and Mythos 5 by any foreign national, whether they are inside or outside the United States. The restriction also applies to foreign national employees working at Anthropic. As a result, the company has disabled both models for all customers to ensure compliance. Access to previous Anthropic models like Opus and Sonnet is not affected by this government order. The company highlighted that it had developed strong safeguards to reduce the possibility that Fable is misused for tasks related to cybersecurity. In fact, many developers are complaining that the safeguards are going overboard. Additionally, the company worked with the US government, the UK AISI, multiple private third-party organizations, and internal teams to red-team Fable’s safeguards for thousands of hours. Finally, Anthropic noted that no testers have yet been able to find a universal jailbreak on Fable 5. As expected, Anthropic disagrees that a narrow potential jailbreak should lead to the recall of a commercial model used by hundreds of millions of people. It warned that applying this standard across the AI industry could effectively halt new frontier model deployments. Anthropic concluded by mentioning that it is working to restore access to Fable 5 and Mythos 5 as soon as possible and plans to share more details within the next 24 hours.
    • Brave Browser 1.91.172 is out.
  • Recent Achievements

    • Week One Done
      ssd21345 earned a badge
      Week One Done
    • Contributor
      MarkHughes4096 went up a rank
      Contributor
    • Dedicated
      jordanspringer earned a badge
      Dedicated
    • Rookie
      Rimplesnort went up a rank
      Rookie
    • One Year In
      Markus94287 earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      503
    2. 2
      +Edouard
      176
    3. 3
      PsYcHoKiLLa
      147
    4. 4
      ATLien_0
      92
    5. 5
      Steven P.
      79
  • Tell a friend

    Love Neowin? Tell a friend!