Printing a random string from my ArrayList to the console - java

Here's my code:
public static void main(String[] args) {
ArrayList<String> eMinor = new ArrayList<String>();
eMinor.add("E");
eMinor.add("F#");
eMinor.add("G");
eMinor.add("A");
eMinor.add("B");
eMinor.add("C");
eMinor.add("D");
}
What do I need to add in order to generate a random string from the list and print it in the console?

You can randomly select a value from the list with something like:
int index = new java.util.Random().nextInt(eMinor.size());
String value = eMinor.get(index);
and then print it to the console with:
System.out.println(value);

public static void main(String[] args) {
ArrayList<String> eMinor = new ArrayList<String>();
eMinor.add("E");
eMinor.add("F#");
eMinor.add("G");
eMinor.add("A");
eMinor.add("B");
eMinor.add("C");
eMinor.add("D");
Random rand = new Random()
int random = rand.nextInt(eMinor.size());
String note = eMinor.get(random);
System.out.println(note);
}

e minor is one of my favorite keys, so I'll answer. You need a random number generator:
Random ran = new Random();
int x = ran.nextInt(eMinor.size() - 1)
System.out.println(eMinor.get(x));
You could generate multiple notes with a loop:
Random ran = new Random();
for (int i = 0, i < 10; i++) {
int x = ran.nextInt(7)
System.out.println(eMinor.get(x));
}

You could do something like this:
int min = 3;
int range = 3;
Random random = new Random();
int length = min + random.nextInt(range);
String randomString = "";
for (int i = 0; i < length; ++i)
{
randomString += eMinor.get(random.nextInt(eMinor.size() - 1));
}
System.out.println(randomString);

You can use a simple model, but to complex application is necessary more attention with Random class;
enter code here
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
public static void main(String[] args) {
ArrayList<String> eMinor = new ArrayList<String>();
eMinor.add("E");
eMinor.add("F#");
eMinor.add("G");
eMinor.add("A");
eMinor.add("B");
eMinor.add("C");
eMinor.add("D");
for (int f = 0; f < 3; f++) {
System.out.printf("------------ list %s ------------\n",f);
for (String value : generateList(eMinor)) {
System.out.println(value);
}
}
}
private static List<String> generateList(ArrayList<String> eMinor) {
List<String> tempList = new ArrayList<>();
Random random = new Random();
while (tempList.size() != eMinor.size()) {
String value = eMinor.get(random.nextInt(eMinor.size()));
if (!tempList.contains(value)) {
tempList.add(value);
}
}
return tempList;
}
}

You may use the below complete example:
/*
* Created by Mohammed.Kharma on 2/9/2016.
*/
import java.util.Random;
import java.util.ArrayList;
public class Scrambler {
public static int[] Scramble(final int key, final int elementsCount) throws NegativeArraySizeException {
if (elementsCount < 0) {
NegativeArraySizeException ex = new NegativeArraySizeException("scrambler elementCount");
throw ex;
}
Random rand = new Random(key);
int[] order = new int[elementsCount];
for (int i = 0; i < elementsCount; i++) {
order[i] = i;
}
int count = elementsCount;
while (--count > 0) {
int nextRandom = rand.nextInt(count + 1); // 0 <= k <= count (!)
int temp = order[count];
order[count] = order[nextRandom];
order[nextRandom] = temp;
}
return order;
}
public static void main(String[] args) {
ArrayList<String> eMinor = new ArrayList<String>();
eMinor.add("E");
eMinor.add("F#");
eMinor.add("G");
eMinor.add("A");
eMinor.add("B");
eMinor.add("C");
eMinor.add("D");
for (int numOFRandoStrings = 0; numOFRandoStrings < 10; numOFRandoStrings++) {
int[] randomList = Scramble(new Long(System.currentTimeMillis()).intValue() * numOFRandoStrings, 7); //numOFRandoStrings or any seed,7 means give me 7 random numbers from zero to 6
StringBuffer randomString = new StringBuffer();
for (int ind = 0; ind < randomList.length; ind++) {
randomString.append(eMinor.get(randomList[ind] ));
}
System.out.println("New Random String: " + randomString);
}
}
}

Related

Random strange behavior

I've created just for fun this method to find out how long it takes until this random method goes into a loop and what the seed is when this occurs:
public static void main(String[] args) {
HashMap<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < 1000; i++) {
int key = firstRepeatingSeed();
Integer integer = map.get(key);
map.put(key, integer == null ? 1 : integer+1);
}
System.out.println(map);
}
}
public static int firstRepeatingSeed(){
Random random = new Random();
HashSet<Integer> loopDetector = new HashSet<>();
while (true) {
int gen = random.nextInt();
random.setSeed(gen);
if (!loopDetector.add(gen))
return gen;
}
}
These are the results:
-1381274646=2,
-1686548232=2,
154051178=717,
-381624123=1,
-334394727=1,
-1261880000=1,
-1128634575=1,
658182704=1,
364776881=141,
-1985197764=11,
1266282155=13,
-1108864769=1,
266843583=9,
-1939453764=2,
349725186=4,
1525333558=2,
-106280330=1,
-1865148662=1,
-296326218=1,
-84817968=2,
332765684=1,
-1181949977=1,
-595175830=59,
-206288251=1,
-2043038133=1,
1220626100=1,
-541517940=1,
1373871195=14,
1890953100=3,
-1529367891=1,
-1022666507=3
My question is why does 154051178 and 364776881 show up so often?

How can I compile this program?

I have a problem with compilation of this program I don't know how can I solve this problem
class ArrayTester{
public void arrayTester(ArrayDeque arrayDeque) {
List evenlist = new ArrayList();
List oddlist = new ArrayList();
for (int n = 0; n < arrayDeque.size(); n++) {
if (arrayDeque.Length() % 2 == 0) {
arrayDeque.addAll(evenlist);
} else {
arrayDeque.addAll(oddlist);
}
System.out.println(evenlist);
System.out.println(oddlist);
}
}
}
class Kodilla {
public static void main(String[] args) {
ArrayDeque<String> arrayDeque = new ArrayDeque<>();
Random random = new Random();
String text = "";
int howLong = random.nextInt(50) + 1;
while (text.length() < howLong) {
text = text + "a";
for (int i = 0; i < 50; i++) {
arrayDeque.add(text);
System.out.println(arrayDeque);
System.out.println(arrayDeque.size());
arrayTester tester = new ArrayTester();
tester.arrayTester(arrayDeque);
System.out.println(arrayTester);
}
}
}
}
what I see is that in this line
arrayTester tester = new ArrayTester();
there is typo in the variable definition. (lowercase a)

My Program stops printing to console, but continues to run in background. No Exception is thrown

My program Runs and prints the first few system.out statements, then stops printing them. There is no exception thrown, and the program continues to run until manually terminated.
I've tried System.out.flush(); but am not even sure where to put that
import java.io.*;
import java.util.ArrayList;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws
FileNotFoundException {
String inputFileStr = args[0];//"input.txt";
String outputFileStr = args[1];//"output.txt";
String deleteFileStr = args[2];//"CS401Project5Delete_Varner_Sav58.txt";//
String replaceFileStr = args[3]; //"CS401Project5Replace_VARNER_SAV58.txt";
// create files w/ corresponding file names
try{
File inputFile = new File(inputFileStr);
File outputFile = new File(outputFileStr);
File deleteFile = new File(deleteFileStr);
File replaceFile = new File(replaceFileStr);
// create arrayLists
ArrayList<StringBuilder> deleteArray;
ArrayList<StringBuilder> replaceArray;
ArrayList<StringBuilder> inputArray;
ArrayList<String> inputStringArray = new ArrayList<>();
ArrayList<String> tokensArray = new ArrayList<>();
ArrayList<Integer> frequenciesArray = new ArrayList<>();
// turn Files into arrayLists of StringBuilders
deleteArray = fileToArray(deleteFile);
replaceArray = fileToArray(replaceFile);
inputArray = fileToArray(inputFile);
System.out.println("# words in original file: " + wordCount(inputArray));
// create a deleteList object
DeleteList delete = new DeleteList();
delete.compareArray(inputArray, deleteArray);
System.out.println("Word Count After Deleteing noise: " + delete.wordCount(inputArray));
System.out.flush();
// create a replacelist object
ReplaceList replace = new ReplaceList();
replace.compareArray(inputArray, replaceArray);
System.out.println("Word count after replacing words: " + replace.wordCount(inputArray));
System.out.println("New input printed to 'output.txt'");
}
catch (FileNotFoundException e){
System.out.println("File not found");
}
}
// turns a file into an arraylist of string builders
public static ArrayList<StringBuilder> fileToArray(File fileName) throws FileNotFoundException {
ArrayList<String> array = new ArrayList<>();
ArrayList<StringBuilder> sbArray = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null)
{
if (!line.isEmpty()) {
Stream.of(line.split("\\s+")).forEachOrdered(word -> array.add(word));
}
}
} catch (Exception e) {
System.out.printf("Caught Exception: %s%n", e.getMessage());
e.printStackTrace();
}
for(int i = 0; i < array.size(); i++) {
StringBuilder sb = new StringBuilder();
sb.append(array.get(i));
sbArray.add(sb);
}
for(int i = 0; i < sbArray.size(); i ++) {
if
(sbArray.get(i).toString().endsWith(",") ||
sbArray.get(i).toString().endsWith(".") ||
sbArray.get(i).toString().endsWith(" ")
||sbArray.get(i).toString().endsWith(":")) {
sbArray.get(i).deleteCharAt(array.get(i).length() - 1);
}
}
return sbArray;
}
public static int wordCount(ArrayList<StringBuilder> array) {
int count = 0;
for (int i = 0; i < array.size(); i++) {
count++;
}
return count;
}
}
import java.util.ArrayList;
public class DeleteList extends ArrayList<Object> implements MyInterface {
/**
*
*/
private static final long serialVersionUID = 1L;
//constructor
#Override
public ArrayList<StringBuilder>
compareArray(ArrayList<StringBuilder> inputArray, ArrayList<StringBuilder> deleteArray) {
for (int i = 0; i < deleteArray.size(); i++) {
for (int j = 0; j < inputArray.size(); j++) {
if (deleteArray.get(i).toString().equals(inputArray.get(j).toString())){
inputArray.remove(j);
}
}
}
return inputArray;
}
#Override
public int wordCount(ArrayList<StringBuilder> inputArray) {
int count = 0;
for (int i = 0; i < inputArray.size(); i++) {
count++;
}
return count;
}
}
import java.util.ArrayList;
public class ReplaceList extends ArrayList<Object> implements MyInterface {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public ArrayList<StringBuilder>
compareArray(ArrayList<StringBuilder> inputArray, ArrayList<StringBuilder> replaceArray) {
String wordToReplace, wordReplacingWith = null;
for (int i = 0; i < replaceArray.size(); i++) {
wordToReplace = replaceArray.get(i).toString();
wordReplacingWith = replaceArray.get(i +1).toString();
for (int j = 0; j < inputArray.size(); j++) {
if (inputArray.get(j).toString().equalsIgnoreCase((wordToReplace))) {
StringBuilder strB = new StringBuilder();
strB.append(wordReplacingWith);
inputArray.set(j, strB);
}
}
}
return inputArray;
}
#Override
public int wordCount(ArrayList<StringBuilder> inputArray) {
int count = 0;
for (int i = 0; i < inputArray.size(); i++) {
count++;
}
return count;
}
}
It should be printing to the console:
words in the original file :
words after deleting noise:
words after replacing words:
New Input printed to "output.txt" <--- (i haven't coded this part yet)
Note:
I have to use string builders, implement an interface, and have the
delteList and replaceList extend ArrayList & handle all exceptions in
main
You're problem is this:
ReplaceList#compareArray
while (i < replaceArray.size()) {
wordReplacingWith = replaceArray.get(i + 1).toString();
}
You probably want to increment i at some point or more likely you need a different counter here.
And those System.exit() commands that prevent compilation ;)
The only thing I am seeing in the updated version is a potential ArrayIndexOutOfBoundsException for
for (int i = 0; i < replaceArray.size(); i++) {
...
wordReplacingWith = replaceArray.get(i +1).toString();
...
}
Unrelated to any endless loop problem you might still have:
DeleteList#compareArray is likely to skip elements after a remove operation,
as the new element on position j (the former j+1) element is not covered by your loop.

Max Fitness stuck at local maxima in genetic algorithm implementation

Having trouble with this code below. It is implementation of population evolution. In my case the max fitness is struck at a local maxima everytime and is unable to reach max possible value. Kindly suggest necessary edits and reason for the same.
Individual.java
package genetic.algorithm.project;
import java.util.Random;
public class Individual {
public static int SIZE = 300;
private int[] genes = new int[SIZE];
private double fitnessValue = 0.0;
// Getters and Setters
public void setGene(int index,int gene){
this.genes[index] = gene;
}
public int getGene(int index){
return this.genes[index];
}
public void setFitnessValue(double fitness){
this.fitnessValue = fitness;
}
public double getFitnessValue(){
return this.fitnessValue;
}
//Function to generate a new individual with random set of genes
public void generateIndividual(){
Random rand = new Random();
for(int i=0;i<SIZE;i++){
this.setGene(i, rand.nextInt(2));
}
}
//Mutation Function
public void mutate(){
Random rand = new Random();
int index = rand.nextInt(SIZE);
this.setGene(index, 1-this.getGene(index)); // Flipping value of gene
}
//Function to set Fitness value of an individual
public int evaluate(){
int fitness = 0;
for(int i=0; i<SIZE; ++i) {
fitness += this.getGene(i);
}
this.setFitnessValue(fitness);
return fitness;
}
}
Population.java
import java.util.Random;
public class Population {
final static int ELITISM = 1;
final static int POP_SIZE = 200+ELITISM; //Population size + Elitism (1)
final static int MAX_ITER = 2000;
final static double MUTATION_RATE = 0.05;
final static double CROSSOVER_RATE = 0.7;
private static Random rand = new Random();
private double totalFitness;
private Individual[] pop;
//Constructor
public Population(){
pop = new Individual[POP_SIZE];
//Initialising population
for(int i=0;i<POP_SIZE;i++){
pop[i] = new Individual();
pop[i].generateIndividual();
}
this.evaluate();
}
//Storing new generation in population
public void setPopulation(Individual[] newPop) {
this.pop = newPop;
}
//Method to find total fitness of population
public double evaluate(){
this.totalFitness = 0.0;
for (int i = 0; i < POP_SIZE; i++) {
this.totalFitness += pop[i].evaluate();
}
return this.totalFitness;
}
//Getters
public Individual getIndividual(int index) {
return pop[index];
}
//Function to find fittest individual for elitism
public Individual getFittest() {
Individual fittest = pop[0];
for (int i = 0; i < POP_SIZE; i++) {
if (fittest.getFitnessValue() <= getIndividual(i).getFitnessValue()) {
fittest = getIndividual(i);
}
}
return fittest;
}
//CROSSOVER Function : Takes 2 individuals and returns 2 new individuals
public static Individual[] crossover(Individual indiv1,Individual indiv2) {
Individual[] newIndiv = new Individual[2];
newIndiv[0] = new Individual();
newIndiv[1] = new Individual();
int randPoint = rand.nextInt(Individual.SIZE);
int i;
for (i=0; i<randPoint; ++i) {
newIndiv[0].setGene(i, indiv1.getGene(i));
newIndiv[1].setGene(i, indiv2.getGene(i));
}
for (; i<Individual.SIZE; ++i) {
newIndiv[0].setGene(i, indiv2.getGene(i));
newIndiv[1].setGene(i, indiv1.getGene(i));
}
return newIndiv;
}
//Roulette Wheel Selection Function
public Individual rouletteWheelSelection() {
double randNum = rand.nextDouble() * this.totalFitness;
int idx;
for (idx=0; idx<POP_SIZE && randNum>0; idx++) {
randNum -= pop[idx].getFitnessValue();
}
return pop[idx-1];
}
//Main method
public static void main(String[] args) {
Population pop = new Population();
Individual[] newPop = new Individual[POP_SIZE];
Individual[] indiv = new Individual[2];
//Current Population Stats
System.out.println("Total Fitness = "+pop.totalFitness);
System.out.println("Best Fitness = "+pop.getFittest().getFitnessValue());
int count;
for(int iter=0;iter<MAX_ITER;iter++){
count =0;
//Elitism
newPop[count] = pop.getFittest();
count++;
//Creating new population
while(count < POP_SIZE){
//Selecting parents
indiv[0] = pop.rouletteWheelSelection();
indiv[1] = pop.rouletteWheelSelection();
// Crossover
if (rand.nextDouble() < CROSSOVER_RATE ) {
indiv = crossover(indiv[0], indiv[1]);
}
// Mutation
if ( rand.nextDouble() < MUTATION_RATE ) {
indiv[0].mutate();
}
if ( rand.nextDouble() < MUTATION_RATE ) {
indiv[1].mutate();
}
// add to new population
newPop[count] = indiv[0];
newPop[count+1] = indiv[1];
count += 2;
}
// Saving new population in pop
pop.setPopulation(newPop);
//Evaluating new population
pop.evaluate();
System.out.print("Total Fitness = " + pop.totalFitness);
System.out.println(" ; Best Fitness = " +pop.getFittest().getFitnessValue());
}
Individual bestIndiv = pop.getFittest();
}
}
The max possible value of fitness is 300 in my case but it always stucks around 200-230.
Replaced this function :
public void setPopulation(Individual[] newPop) {
this.pop = newPop;
}
with
public void setPopulation(Individual[] newPop) {
System.arraycopy(newPop, 0, this.pop, 0, POP_SIZE);
}
and it works fine now.

random string of numbers

I want to print a string of numbers, but I get the followyng: [I#7c230be4
This is my code:
import java.util.Random;
class Aleatorio {
public static void main(String[] args) {
Random diceRoller = new Random();
int cifra[]= new int[5];
for (int i = 0; i < cifra.length; i++) {
int roll = diceRoller.nextInt(9)+1 ;
cifra[i]=roll;
}
System.out.println(cifra);
}
}
You are seeing the Object#toString representation of the int array Object. To display its contents, you could use:
Arrays.toString(cifra)
Try this
for (int c : cifra) {
System.out.println(c);
}
instead of this
System.out.println(cifra);

Categories

Resources