java program that takes a word and randomizes the letters and creates an anagram

早过忘川 提交于 2020-02-25 13:52:34

问题


I need to create a program that will take a word without spaces, punctuation, and all lowercase, and rearranges the letters randomly. It needs to have substrings or charAt, I cannot use an array since we have not learned them yet. It also hsa to be different everytime, really n! times I think. This is what I have so far-

public static void main(String[] args) {
      Scanner kboard = new Scanner(System.in);
      System.out.println("Enter a word that is less than 11 lowercase letters and has no punctuation or spaces: ");       
      String word = kboard.next();
      while(word.length()>1)
      {
            System.out.print(word.charAt(1));
            System.out.print(word.charAt(0));
            word = word.substring(2);
      }
      System.out.println(word);
}

This rearranges the words, but it does not do it random every time. I thought I could do something like this, but I think it is messy and doesn't make much sense.

public static void main(String[] args) {
      Scanner kboard = new Scanner(System.in);
      String word, pt1 = "", pt2 = "", pt3 = "";
      System.out.println("Enter a word that is less than 11 lowercase letters and has no punctuation or spaces: ");
      word = kboard.nextLine();
      int num1 = 0, num2 = 0, thing = 0;
      while(thing<4)
      {
          thing = thing + 1;
          num1 = (int)(word.length() * Math.random() + 1);
          num2 = (word.length() - (word.length() % num1));
      }
          pt1 = word.substring(num1, num2);
          pt2 = word.substring(num1, num2);
          pt3 = word.substring(num1, num2);
          System.out.print(pt1);
          System.out.print(pt2);
          System.out.print(pt3); 

So what can I do to randomize the letters?


回答1:


A simple solution to all "how do I randomize" a fixed set of elements is: shuffling.

Simply turn your String into a List of Character, to then shuffle that list.

( creating that list boils down to new ArrayList<>(yourWord.toCharArray() ).




回答2:


GhostCat beat me in a few seconds :)

    char[] arr = "abcdefg".toCharArray();
    List<Character> list = new LinkedList<>(); // copy the chars to a list
    for (int i = 0; i < arr.length; i++) {
        list.add(arr[i]);
    }
    Collections.shuffle(list);  // use to shuffle
    for (int i = 0; i < arr.length; i++) { // copy the shuffled chars back to the array
        arr[i] = list.get(i);
    }
    System.out.println(new String(arr));



回答3:


This could be implemented very easily using standard libraries, but it seems you cannot use arrays and lists, which makes this exercise a bit harder than it needs to be.

You can implement the following algorithm:

  • Initialize the output as an empty string
  • while the word is not empty
    • Pick a character randomly
    • Append the character to the output
    • Remove the selected character from the word, by replacing word with the part before the index + the part after the index

This can be implemented reasonably efficiently using a StringBuilder:

String shuffled(Random random, String word) {
    StringBuilder result = new StringBuilder(word.length());
    StringBuilder rest = new StringBuilder(word);
    while (rest.length() > 0) {
        int index = random.nextInt(rest.length());
        result.append(rest.charAt(index));
        rest.deleteCharAt(index);
    }
    return result.toString();
}

If you cannot use a StringBuilder, then you can work with strings, but this will be less efficient, and normally not recommended in Java. (Because it involves many string concatenations, which is inefficient.)

String shuffled(Random random, String word) {
    String result = "";
    String rest = word;
    while (!rest.isEmpty()) {
        int index = random.nextInt(rest.length());
        result += rest.charAt(index);
        rest = rest.substring(0, index) + rest.substring(index + 1);
    }
    return result;
}

You can call this with:

String shuffled = shuffled(new Random(), word);



回答4:


What about this :

public static void main(String[] args) {
        String test = "onetwothree";
        Random random = new Random();
        for (int i=0;i<test.length();i++){
            int randomCharacterPosition = random.nextInt(test.length());
            String start = test.substring(0,randomCharacterPosition);
            String end = test.substring(randomCharacterPosition);
            test = end.concat(start);

        }
        System.out.println(test);
    }

Basically you getting a string, randomly choose a position in string. Using this position you dividing input string into two strings and swaping them.

Nothing more than random, substring and concat (which can be replaced with + operator)



来源:https://stackoverflow.com/questions/47252538/java-program-that-takes-a-word-and-randomizes-the-letters-and-creates-an-anagram

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!