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?
Related
I have this method that prints my permutations of a Set I'm giving with my parameters. But I need to save them in 2 separate sets and compare them. So, for instance I have [5,6,3,1] and [5,6,1,3], by adding them in two separate BST, I can compare them by using the compareTo function to check whether their level order is the same. But I am having trouble with saving these permutations from my method into a set in my main. Does anyone know how to save these into a set?
What I have now:
import edu.princeton.cs.algs4.BST;
import java.util.*;
public class MyBST {
public static void main(String[] args) {
int size = 4;
BST<Integer, Integer> bst1 = new BST<Integer, Integer>();
BST<Integer, Integer> bst2 = new BST<Integer, Integer>();
Random r = new Random();
Set<Integer> tes = new LinkedHashSet<>(size);
Stack<Integer> stack = new Stack<>();
while (tes.size() < size) {
tes.add(r.nextInt(10));
}
System.out.println(tes);
System.out.println("possible combinations");
Iterator<Integer> it = tes.iterator();
for (int i = 0; i < tes.toArray().length; i++) {
Integer key = it.next();
bst1.put(key, 0);
}
combos(tes, stack, tes.size());
}
}
and here is the method I use:
public static void combos(Set<Integer> items, Stack<Integer> stack, int size) {
if (stack.size() == size) {
System.out.println(stack);
}
Integer[] itemz = items.toArray(new Integer[0]);
for (Integer i : itemz) {
stack.push(i);
items.remove(i);
combos(items, stack, size);
items.add(stack.pop());
}
}
And this is the output:
I'm not sure if I understood your idea but maybe this will help:
Yours combos method will return set of all permutations (as Stacks)
...
for (int i = 0; i < tes.toArray().length; i++) {
Integer key = it.next();
bst1.put(key, 0);
}
Set<Stack<Integer>> combos = combos(tes, stack, tes.size()); //there you have set with all Stacks
}
}
public static Set<Stack<Integer>> combos(Set<Integer> items, Stack<Integer> stack, int size) {
Set<Stack<Integer>> set = new HashSet<>();
if(stack.size() == size) {
System.out.println(stack.to);
set.add((Stack) stack.clone());
}
Integer[] itemz = items.toArray(new Integer[0]);
for(Integer i : itemz) {
stack.push(i);
items.remove(i);
set.addAll(combos(items, stack, size));
items.add(stack.pop());
}
return set;
}
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.
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);
}
}
}
I'm creating a program that will generate 100 random numbers between 1 and 1000, add them to a list, and then sum up those numbers. Here's my code:
public class Iteration {
public static void main (String [] args){
private int RandomDataAnalyzer(int Rando) {
Random rand = new Random();
List<Integer> NumList = new ArrayList<Integer>();
for (int i=0;i<=100;i++){
Rando = rand.nextInt(1001);
NumList.add(Rando);
}
int sum = 0;
for (int i=0; i<100; i++)
{
Rando = rand.nextInt(100);
sum = sum + Rando;
}
return sum;
}
}
}
And here's my errors:
H:\Java\Iteration.java:12: error: illegal start of expression
private int RandomDataAnalyzer(int Rando) {
^
H:\Java\Iteration.java:12: error: ';' expected
private int RandomDataAnalyzer(int Rando) {
^
H:\Java\Iteration.java:12: error: ';' expected
private int RandomDataAnalyzer(int Rando) {
Any help, please?
You can't define a method inside another method. Close your main method first, then start RandomDataAnalyzer:
public static void main(String[] args) {
// Contents of main.
}
public int RandomDataAnalyzer(int Rando) {
// Contents of RandomDataAnalyzer.
}
I'm going to assume that this isn't a homework problem and that you're learning Java on your own. If I'm wrong, shame on me for giving a working version. But my impression is that you'll learn from this:
public class gpaCalc
{
static Random rand;
static int rando;
public static void main(String[] args)
{
ArrayList<Integer> NumList = new ArrayList<>(); // use ArrayList
for (int i=0;i<=100;i++)
{
rand = new Random();
rando = rand.nextInt(1001);
NumList.add(rando);
}
int sum = 0;
for (int i=0; i<100; i++)
{
rando = NumList.get(i); // get is "opposite" of put--get the value put into the list earlier
sum = sum + rando;
}
System.out.println(sum);
}
}
There doesn't seem to be a need for a separate method called randomDataAnalyzer.
Welcome to StackOverflow.
Let's begin with the first issue: randomDataAnalyzer is being defined inside main method. Which is wrong, you should be actually defining it at the same level.
Taken into consideration, you should also add the static word before this function because this method is part of the class, and not of the elements. It's not necessary to create a new element of the class 'Iteration' for using a simple method.
Last, but not least, you are looping through the arraylist incorrectly. You are not even calling it. As you will see now:
import java.util.*;
public class Iteration
{
public static void main(String[] args)
{
ArrayList<int> numberList = new ArrayList<int>(); // we define the arraylist
for (int i = 0; i < 100; i++)
{
numberList.add(new Random().nextInt(1001)); // we add a random number to the list
}
// finally, after the 100 values were added..
System.out.println(randomDataAnalyzer(numberList)); // we show the output
}
public static int randomDataAnalyzer(ArrayList<int> list) // we will send this function an arraylist which will get the Σ.
{
int sum = 0;
for (int value : list) // this is how we loop through foreach value in the list
{
sum += value; // which means sum = sum + value.
}
return sum; // after looping and summing up, here'll be the result
}
}
I hope this was what you were looking for.
Here's a working version. Note the changes to your original:
Don't define methods inside methods: it is illegal syntax.
Rando, NumList: the naming conventions are to start classes, interfaces, enums (i.e. types) with a capital letter, and methods, fields, and variables with a lowercase case letter;
Removed the int Rando parameter alltogether: it's value was never used (it was only assigned to)
Use the values from numList rather than generating new numbers.
Added a method illustrating that the use of such a list is not needed in this case; the 'list' of 1000 numbers is still present, but only conceptually.
import java.util.*;
public class Iteration {
public static void main (String [] args) {
int sum = new Iteration().randomDataAnalyzer();
System.out.println(sum);
}
private int randomDataAnalyzer() {
Random rand = new Random();
List<Integer> numList = new ArrayList<Integer>();
for ( int i=0; i<100; i++ )
{
numList.add( 1 + rand.nextInt(1000) );
}
int sum = 0;
for ( int i=0; i<numList.size(); i++ )
{
sum = sum + numList.get(i);
}
return sum;
}
// Note that the above method has the same effect as this one:
private int moreEfficient() {
Random rand = new Random();
int sum = 0;
for ( int i=0; i < 100; i++)
sum += 1 + rand.nextInt(1000);
return sum;
}
}
I am trying to create a random sized array of 1's and 0's. I can get the program to run and compile if I remove the random aspect of the of it and enter the size of the array manually. For some reason when I bring in the random utility I can not get the program to compile.
mport java.util.Random;
public class Project1a {
int[][] sample={{0,0,1,1,1},
{1,1,0,1,1},
{1,1,1,0,1},
{0,1,0,1,1}};
int box[][];
Random randomNumbers = new Random();
int m = randomNumbers.nextInt(100);
int n = randomNumbers.nextInt(100);
int results[][] = new int [m][n];
int goodData = 1;
public static void main(String[] args){
analyzeTable();
printTable(results);
}
public void analyzeTable() {
int row=0;
while (row < sample.length) {
analyzeRow(row);
row++;
}
}
public void analyzeRow(int row) {
int xCol = 0;
int rCount = 0;
while (xCol < sample[row].length) {
rCount = analyzeCell(row,xCol);
results[row][xCol] = rCount;
xCol++;
}
}
int analyzeCell(int row, int col) {
int xCol = col;
int runCount = 0;
int rowLen = sample[row].length;
int hereData = sample[row][xCol];
while (hereData == goodData && xCol < rowLen) {
runCount++;
xCol++;
if (xCol < rowLen) { hereData = sample[row][xCol];}
}
return runCount;
}
public void printTable(int[][] aTable ) {
for (int[] row : aTable) {
printRow(row);
System.out.println();
}
}
public void printRow(int[] aRow) {
for (int cell : aRow) {
System.out.printf("%d ", cell);
}
}
}
Your class name conflicts with java.util.Random. Renaming your class is the easiest fix here.
the problem is you are declaring your instance variable in a block which makes it in-accessible in methods
check this : remove curly braces { } from here and the way you are accessing your results and goodData you need to declare them static
{ // remove this
Random randomNumbers = new Random();
int m = randomNumbers.nextInt(100);
int n = randomNumbers.nextInt(100);
static int results = new int [m][n];
static int goodData = 1;
} // remove this