1
votes

Comment renvoyer un palindrome de longueur spécifiée et de caractères distincts spécifiés

J'ai du mal à écrire une fonction qui, lorsqu'on lui donne deux valeurs entières (int a, int b), renvoie un palindrome aléatoire

(int a = le nombre de caractères dans la chaîne) (int b = le nombre de caractères distincts dans la chaîne)

public static String solution(int a, int b) {

Random random = new Random(26);
StringBuilder sb = new StringBuilder(a);
ArrayList <Character> distinctChars = new ArrayList <Character>();



//generate the correct amount of distinct characters and populate arraylist with them
for (int i = 0; i < b; i++) {
distinctChars.add( (char) (random.nextInt('z' - 'a')) );
}


//generate each char individually to make a string to return of the specificed length
   for(int i = 0; i < a; i++) {

       char letter = (char) ('a' + (random.nextInt(??????????)));
       sb.append(letter);
   
   }
return sb.toString();
}

J'ai donc 2 questions principales

  1. Où j'ai inséré "??????", comment puis-je spécifier la plage de random comme étant le contenu de ce qui se trouve dans mon arraylist (nommé distinctChars)

  2. Ce code ne renverra pas encore de palindrome pour le moment, est-ce que quelqu'un a connaissance de fonctions java supplémentaires qui pourraient vous aider?


6 commentaires

al devrait probablement être changé en distinctChars


Avez-vous besoin d'un palindrome aléatoire ?


Le palindrome est-il supposé être composé de mots légitimes ou est-il destiné à être du charabia?


ça peut être du charabia


Le caractère distinct généré dans la boucle for peut être dupliqué, nous devons donc réessayer dans ce cas.


Quand vous dites distinct, c'est juste une limitation du nombre de caractères distincts dans l'alphabet que vous pouvez utiliser, n'est-ce pas?


4 Réponses :


1
votes

Where I have inserted "??????", how do I specify the range for random as being the contents of whats inside my arraylist (named distinctChars)

Vous devez utiliser nextInt(int) où le paramètre est la valeur limite supérieure qui est exclusive. Dans ce cas, 'a' représente 0 et 'z' vaut 25 donc nextInt(26) renverrait une valeur maximale de 25.

This code will not actually return a palindrome as of yet, is anyone aware of any addition java functions that will help with this?

La méthode StringBuilder#reverse peut être utile pour cela.

Solution possible

Cette solution est basée sur votre code existant avec quelques modifications. Tout ce que je fais différemment, c'est de créer une liste de valeurs entières qui représentent les caractères uniques autorisés. Lors de la génération des caractères distincts, nous vérifions si le prochain personnage choisi au hasard a déjà été choisi et si c'est le cas, réessayez. Lors du remplissage du StringBuilder, nous choisissons un entier aléatoire dans la liste et l'ajoutons au résultat, et l'ajoutons à la tête du StringBuilder qui représente le résultat inversé.

mraarjmqqmjraarm

Exemple de a = 16, b = 8

    public static String solution(int a, int b) {
        if (a % 2 != 0) {
            throw new IllegalArgumentException("a must be an even number.");
        }
        if (b > 26 || b < 0) {
            throw new IllegalArgumentException("b must be between the random of 0 and 26.");
        }
        Random random = new Random();

        StringBuilder result = new StringBuilder(a / 2);

        StringBuilder reverse = new StringBuilder(a / 2);

        List<Integer> distinctChars = new ArrayList<>();

        for (int i = 0; i < b; i++) {
            int distinct;

            while (true) {
                distinct = 'a' + random.nextInt(26);

                if (distinctChars.contains(distinct)) {
                    continue;
                }
                break;
            }
            distinctChars.add(distinct);
        }

        for(int i = 0; i < a / 2; i++) {
            int letter = distinctChars.get(random.nextInt(distinctChars.size()));

            result.append((char) letter);

            reverse.insert(0, (char) letter);
        }
        return result.toString() + reverse.toString();
    }


2 commentaires

Il veut une plage pour sélectionner un personnage dans sa liste distinctChars ("??????")


Cela ne gère pas les demandes de palindrome de longueur impaire et ne gère pas l'exigence de caractères distincts.



0
votes

Voici une façon de le faire. Il y a beaucoup de.

Les palindromes peuvent avoir un nombre pair ou impair de caractères. Mais il y a des limitations et le programme signalera une erreur si elles ne sont pas respectées. Par exemple, les caractères abcd peuvent créer un palindrome le plus étrange de 7 caractères et un pair de 8.

public static String genPalindrome(int length, int nchars) {
    // some palindromes cannot be created with supplied conditions.
    if (nchars < ((length+1)/2) || nchars > 26) {
        System.out.printf("Not possible with '%d' character set and a length of %d%n", nchars, length);
        return null;
    }

    char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
    Random r = new Random();
    StringBuilder part1 = new StringBuilder();
    int halfLength = (length+1)/2;
    // this loop generates distinct characters and
    // appends them to the StringBuilder
    while(halfLength-- > 0) {
        int ci = r.nextInt(nchars);
        part1.append(chars[ci]);
        chars[ci] = chars[--nchars];
    }
    return part1.append(new 
     StringBuilder(part1).reverse().substring(length%2)).toString();
}

Imprime quelque chose comme

cidbdic
gaddag

Voici la méthode

System.out.println(genPalindrome(7, 9));
System.out.println(genPalindrome(6, 7));

La méthode fonctionne comme suit

  • créer une instance de Random
  • générer la première partie du palindrome qui sera exactement la moitié ou un de plus de la moitié de la taille requise.
  • Les caractères sont choisis de manière à éviter la duplication.
  • chaque caractère est ajouté au StringBuilder .
  • dès que la première partie est terminée, concaténer une sous-chaîne inversée de cette partie en commençant par 0 si la longueur est paire. Sinon, commencez par 1 (obtenu via la length%2 ).


0 commentaires

0
votes
public static String genPalindrome(int length, int nchars) {
            char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
            Random r = new Random();
            StringBuilder part1 = new StringBuilder();
            int halfLength = (length+1)/2;
            // this loop generates distinct characters and
            // appends them to the StringBuilder
            while(halfLength-- > 0) {
                int ci = r.nextInt(nchars);
                part1.append(chars[ci]);
                if(nchars>1)
                    chars[ci] = chars[--nchars];
                else
                    chars[ci] = chars[0];
            }
            return part1.append(new 
             StringBuilder(part1).reverse().substring(length%2)).toString();
        }

1 commentaires

Ajout d'un bloc if à la solution donnée dans StackOverflow pour générer le palindrome de n'importe quel personnage



0
votes

test de colis;

import java.util.ArrayList; import java.util.Random;

public class test5 {

public static void main(String[] args) {
    int uniquechar = 2;
    int length = 5;
    ArrayList<String> arr = new ArrayList<String>(length);
    String randomString = generateRandomChars(uniquechar, length);
    for (int i = 0; i < length; i++) {

        if (arr.contains(randomString)) {
            randomString = generateRandomChars(uniquechar, length);
        } else {
            if (isPalindrome(randomString)) {
                System.out.println("Palindrome found : " + randomString);
                break;
            } else {
                arr.add(randomString);
                }
        }

    }

}

public static String generateRandomChars(int uniquechars, int length) {
    String givenchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    givenchars = givenchars.substring(0, uniquechars);
    StringBuilder sb = new StringBuilder();
    Random random = new Random();
    for (int i = 0; i < length; i++) {
        sb.append(givenchars.charAt(random.nextInt(givenchars.length())));
    }

    return sb.toString();
}

public static boolean isPalindrome(String str) {
    int i = 0, j = str.length() - 1;
    while (i < j) {
        if (str.charAt(i) != str.charAt(j))
            return false;
        i++;
        j--;
    }
    return true;
}

}


0 commentaires