-2

I'm trying to randomly pick three letters from a string that the user inputs and so far I have this:

    Scanner reader = new Scanner(System.in)
    String inp = reader.nextLine();
            String inputName1;
            inputName1 = inp.substring(int i = (int)(Math.random()*(inp.length()-0)+0), i+=1);

I feel like I'm missing something obvious and I'm pretty new to Java but could anyone help me with this? Thanks everybody

Fool
  • 117
  • 1
  • 8

5 Answers5

2

What you desire is something called Knuth shuffle (aka Fisher–Yates shuffle). Such algorithm allows you to randomly pick elements of a vector (here, your string), without replacement. To obtain such result, you just have to sort your vector (or string) and select, for example, the first n elements to obtain n randomly picked elements without repetition.

"Fisher–Yates shuffling is similar to randomly picking numbered tickets (combinatorics: distinguishable objects) out of a hat without replacement until there are none left." in Knuth Shuffle wikipedia article

Java Knuth shuffle code example:

public class Knuth { 

// this class should not be instantiated
private Knuth() { }

/**
 * Rearranges an array of objects in uniformly random order
 * (under the assumption that <tt>Math.random()</tt> generates independent
 * and uniformly distributed numbers between 0 and 1).
 * @param a the array to be shuffled
 */
public static void shuffle(Object[] a) {
    int N = a.length;
    for (int i = 0; i < N; i++) {
        // choose index uniformly in [i, N-1]
        int r = i + (int) (Math.random() * (N - i));
        Object swap = a[r];
        a[r] = a[i];
        a[i] = swap;
    }
}

/**
 * Reads in a sequence of strings from standard input, shuffles
 * them, and prints out the results.
 */
public static void main(String[] args) {

    // read in the data
    String[] a = StdIn.readAllStrings();

    // shuffle the array
    Knuth.shuffle(a);

    // print results.
    for (int i = 0; i < a.length; i++)
        StdOut.println(a[i]);
}

}

in Java Knuth shuffle example

corporateAbaper
  • 428
  • 3
  • 15
1

You can calculate 3 numbers and then get 3 random characters by charAt() and then concatenate them in a string.
You could implement something like this:

Scanner keyboard = new Scanner(System.in);
String inp = keyboard.nextLine();
Random generator = new Random();
String newString = ""; //contains the extracted letters
int randomPositionOfLetter; 
for(int i=1;i<=3;i++){
    // calculating a random position of a char in the string
    randomPositionOfLetter = generator.nextInt(inp.length());
    newString = newString + inp.charAt(randomPositionOfLetter);
}

You could also modify the code to not be able to randomly choose the same number more than one time.

DimLek
  • 123
  • 8
1

First, please use java.util.ThreadLocalRandom instead. Refer to this for the reason why. What you can do is pick a random index of the String using ThreadLocalRandom and get the character in the index using charAt() method.

    Scanner reader = new Scanner(System.in);
    String inp = reader.nextLine();
    char[] chars = new char[3];

    for(int x = 0; x < 3; x++){
        chars[x] = inp.charAt(ThreadLocalRandom.current().nextInt(0, inp.length()));  
    }

    System.out.println(Arrays.toString(chars));
anonymouse
  • 109
  • 2
  • 9
0

You can calculate 3 random numbers then select the chars with those numbers as positions in the string. Using the method Random.nextInt() is better than using Math.random(). You can see this post for more details

import java.util.Scanner;

public class Test {

    public static void main( String args[] ){
        Scanner reader = new Scanner(System.in);
        String inp = reader.nextLine();
        java.util.Random rnd = new java.util.Random();
        int i = rnd.nextInt(inp.length()), 
                j = rnd.nextInt(inp.length()), 
                k = rnd.nextInt(inp.length());

        System.out.println("Letter 1: "+inp.charAt(i)+", Letter 2: "+inp.charAt(j)+" and Letter 3: "+inp.charAt(k));
    } 

}
Community
  • 1
  • 1
  • Hey! Make sure you have some words in your answer and tell us why your answer works or should work to make in understood by person asking the question. – Vinay Prajapati Dec 17 '15 at 02:40
0

I think just simple do like: get user input, generate the random number from that String. Repeat that step until you reach your random length(here is 3 chars). Then print the result. You also can allow user to put more inputs or stop. Like the code bellow:

   public class GenerateString {

    public static void main(String[] args) {        
        generateChars(3);
    }
    /**
     * get input from user at start
     * */
    public static String getInputString(int length) {
        System.out.println("Put your String to get " +  length + " random chars: ");
        Scanner input = new Scanner(System.in);
        String userInput = input.nextLine();

        if(userInput.length() < length) {
            System.out.println("Your input is less than " + length + ".");
            userInput = getInputString(length);
        }

        return userInput;
    }

    /**
     * generate chars with the given length
     * */
    public static void generateChars(int length) {

        String input = getInputString(length);
        int i = 0;
        int inputLength = input.length();
        StringBuilder stringBuilder = new StringBuilder();
        while(i < length) {
            char randomChar = input.charAt(getRandomPosition(inputLength));
            stringBuilder.append(randomChar);
            i++;
        }
        System.out.println("Your random string is: " + stringBuilder.toString());
        stop(length);
    }

    /**
     * get random position
     * */
    public static int getRandomPosition(int length) {
        Random generator = new Random();
        return generator.nextInt(length);
    }

    /**
     * stop the program
     * */
    public static void stop(int length) {
        System.out.println("Do you want to stop? Press 2 to continue, press any number to exit.");
        Scanner input = new Scanner(System.in);
        try {
            int in = input.nextInt();
            if(in == 2) {
                generateChars(length);
            } else {
                System.exit(1);
            }   
        } catch(Exception ex){
            System.out.println("Input is not number!");
            stop(length);
        }

    }
}

@Fool: can you try?! Hope this help!

Kenny Tai Huynh
  • 1,464
  • 2
  • 11
  • 23