Josh Wein
Josh Wein

Reputation: 80

How do I fill an array with randomly chosen characters from a different array

This is done in java by the way.

So I'm attempting to create some sort of pattern generator with characters. The code I have currently will create an array it will print infinitely starting from the first number entered until the last one, taking the characters from the first array. The error is that if I start from the near the end and tell it to copy over more than that; (say start from the 12 character and copy in 15 more characters but there's only 14 characters in the original array.) How do I get it to keep filling in the array after the original array ends, like start back from the beginning and keep going through the array until it fills up.\

import java.util.*;
public class patternGenerator  {
    private static Scanner input;
    public static void main(String[] args)   {      
    char[] anArray = {'!','@','#','$','%','^','&','*','+','=','~','<','>','?'}; 
    int symbolsPerLine = 0, printed, dontStop = 1, difSymbols;
    input = new Scanner(System.in);
    System.out.println("Enter the amount of symbols to use: ");
    difSymbols = input.nextInt();
    while (difSymbols > anArray.length) {
        difSymbols = (anArray.length-1);
    }
    System.out.println("Dif symbols are: "+ difSymbols);
    System.out.println("Enter amount of symbols per row: ");
    symbolsPerLine = input.nextInt();
    System.out.println("Amount of symbols per line are: "+ symbolsPerLine);
    char [] patternArray = new char[symbolsPerLine];
    System.arraycopy(anArray, difSymbols, patternArray, 0, symbolsPerLine);
    System.out.print(patternArray);
    while(dontStop == 1) {
            System.out.print("\n");
            printed = 0;
            for (int a = 0; a< patternArray.length; a++) {
                    System.out.print(patternArray[a]);
                }
                printed++;
        }
    }
}

Upvotes: 0

Views: 294

Answers (4)

Ortwin Angermeier
Ortwin Angermeier

Reputation: 6193

You could use the following. I re-factored your code a bit.

I use a CharBuffer, since it has some nice futures like the Buffer.hasRemaining()(is still some place in the buffer) and Buffer.put(...)(copy into the buffer) that can come handy when facing such a problem.

In the title of your question you want to randomly choose characters, but in your solution you just appends the array on and on. I have added a possible solution for some randomness using SecureRandom.nextIn(...).

import java.nio.CharBuffer;
import java.security.SecureRandom;
import java.util.Scanner;

public class PatternGenerator {


  public static void main(String[] args) {
    char[] anArray = {'!', '@', '#', '$', '%', '^', '&', '*', '+', '=', '~', '<', '>', '?'};
    int symbolsPerLine = 0, difSymbols = 0;

    Scanner input = new Scanner(System.in);

    System.out.println("Enter the amount of symbols to use: ");
    difSymbols = input.nextInt();
    difSymbols = difSymbols < anArray.length ? difSymbols : anArray.length - 1;
    System.out.println("Dif symbols are: " + difSymbols);

    System.out.println("Enter amount of symbols per row: ");
    symbolsPerLine = input.nextInt();
    System.out.println("Amount of symbols per line are: " + symbolsPerLine);
    CharBuffer cb = CharBuffer.allocate(symbolsPerLine);

    /*
     * just a copy of the original array appended.
     */

    int offset = 0;
    int length = 0;
    while (cb.hasRemaining()) {
      length = (cb.remaining() > difSymbols ? difSymbols : cb.remaining()) - offset;
      cb.put(anArray, offset, length);
      offset = (offset + length) % difSymbols;
    }
    // prepare the buffer to be read
    cb.flip();
    System.out.println("appended: " + cb);

    /*
     * use random characters now
     */
    cb.clear();
    SecureRandom secureRandom = new SecureRandom();
    while (cb.hasRemaining())
      cb.put(anArray[secureRandom.nextInt(anArray.length)]);
    cb.flip();

    System.out.println("random: " + cb);


    input.close();
  }
}

Upvotes: 1

henderso
henderso

Reputation: 1045

You can try adding an index over your source array and looping it as you fill the pattern array:

import java.util.*;
public class patternGenerator  {
    private static Scanner input;
    public static void main(String[] args)   {      
    char[] anArray = {'!','@','#','$','%','^','&','*','+','=','~','<','>','?'}; 
    int symbolsPerLine = 0, printed, dontStop = 1, difSymbols;
    input = new Scanner(System.in);
    System.out.println("Enter the amount of symbols to use: ");
    difSymbols = input.nextInt();
    while (difSymbols > anArray.length) {
        difSymbols = (anArray.length-1);
    }
    System.out.println("Dif symbols are: "+ difSymbols);
    System.out.println("Enter amount of symbols per row: ");


    symbolsPerLine = input.nextInt();

    System.out.println("Amount of symbols per line are: "+ symbolsPerLine);
    char [] patternArray = new char[symbolsPerLine];

    int srcIndex =0;
    for(j=0; j < symbolsPerLine; j++) {
       patternArray[j] = anArray[srcIndex];
      srcIndex++;
      if(srcIndex> (anArray.length-1)) srcIndex =0;

    }

    System.out.print(patternArray);

}

Upvotes: 1

Matt Penna
Matt Penna

Reputation: 117

So first thing that i noticed was that you have an infinate loop. You leave dontStop allways == 1 so your code will never exit the while loop. Second System.arraycopy(anArray, difSymbols, patternArray, 0, symbolsPerLine); will get an out of bound error when you use an number that is greater than anArray.length, so you will need to remove this code. Here is a proposed solution:

        char [] patternArray = new char[symbolsPerLine];

        int length = symbolsPerLine;

        int spot = 0;



        if(symbolsPerLine<anArray.length){
            symbolsPerLine = anArray.length;
        }


        while(dontStop==1){

            for(int i= (anArray.length - difSymbols);i<anArray.length-1;i++){

                if(length==0){
                    dontStop =0;
                    break;
                }


                patternArray [spot]= anArray [i];
                spot++;
                length--;
            }

        }

        for(int j=0;j<patternArray.length;j++){
            System.out.print(patternArray[j]);
        }

        System.out.println("\npatternArray.length is: "+ patternArray.length);

The output for this solution is: Output Run1: 13 Dif symbols are: 13 Enter amount of symbols per row: 20 Amount of symbols per line are: 20 Finished Loop @#$%^&+=~<>@#$%^&+ patternArray.length is: 20

Output Run2: Enter the amount of symbols to use: 5 Dif symbols are: 5 Enter amount of symbols per row: 20 Amount of symbols per line are: 20 Finished Loop =~<>=~<>=~<>=~<>=~<> patternArray.length is: 20

This is what i am assuming you were trying to accomplish.

Upvotes: 1

Andrey Chaschev
Andrey Chaschev

Reputation: 16496

One can do this with RandomStringUtils.html#random(int, char...) from Apache's commons-lang. I'm not aware of a single method solution in JDK.

Upvotes: 1

Related Questions