Generate a random integer on an interval - java

So I have this class called Organism:
public class Organism implements Comparable{
// Represents the organisms guess for the unknown string
String value;
// String the organism is trying to guess
String goalString;
int n;
public Organism(String goalString) {
this.goalString = goalString;
this.value = goalString;
}
public Organism(String value, String goalString, int n) {
this.goalString = goalString;
this.value = value;
this.n = n;
}
public int fitness(){
// Represents the fitness of the organism
int count = 0;
for(int i = 0; i < goalString.length(); i++) {
if(value.charAt(i) == goalString.charAt(i)) {
count ++;
}
}
return count;
}
public Organism[] mate(Organism other) {
// Generate a random integer from [0, n-1]
int crossOver;
return new Organism[0];
}
#Override
public int compareTo(Object o) {
return 0;
}
public void mutate(double mutateProb) {
}
#Override
public String toString() {
return "Value: " + value + " " + "Goal: " + goalString + " " + "Fitness: " + fitness();
}
public String getValue() {
return value;
}
public String getGoalString() {
return goalString;
}
public int getN() {
return n;
}
}
Inside of the mate method I need to generate a random integer on the interval [0, n-1] where n is the length of value and goalString. I then need to store that inside of the crossOver variable inside of the mate method. What would be the best way to do that?

This should do the thing:
int n = other.getValue().length() + other.getGoalString().length();
Random rand = new Random();
int crossOver = rand.nextInt(n);
If you meant n should be the sum of the value and goalStrng of the current (this) object, simply remove the other. or replace it with this..
All have to be placed in the public Organism[] mate(Organism other) method.

Related

Why the program is not showing any output?

I have been trying to troubleshoot this java program from hours now and has not been able to find what is wrong with the execution. I think that the main class is not defined correctly.
It compiles successfully but the output is blank which should not be the case right? I intially tried to call the main class using the objects but still no luck. Any suggestions will work.
The original program:It compiles successfully on adding the main method but the output is blank.
import java.lang.Math; // headers MUST be above the first class
// one class needs to have a main() method
public class OrdSetSimple
{
// arguments are passed using the text field below this editor
public static void main(String[] args){
OrdSetSimple obj = new OrdSetSimple(10);
System.out.print("Success");
}
private int _set_size;
private int _set[];
private int _last;
public OrdSetSimple(int size) {
int k;
_set_size=size;
_set = new int[_set_size];
for(k=0; k<_set_size; k++)
_set[k]=0;
_last=-1;
}
private int make_a_free_slot(int val) {
int pos, i, j;
pos = binSearch(val);
if (pos >= 0)
return -1;
for (i=0; i<=_last; i++) {
if (_set[i] > val)
break;
}
if ((i<=_last)||(_last==-1)) {
for (j=_last; j>=i; j--)
_set[j+1] = _set[j];
pos = i;
} else {
pos = _last+1;
}
_last++;
return pos;
}
public void addElement(int n) {
int pos;
if (n<0) {
System.out.println("Addition of a negative integer impossible\n");
return;
}
if (_last+1>=_set_size) {
System.out.print("Addition of " + n);
System.out.println(" impossible since the array is already full");
System.out.println("The array is: " + toString());
} else {
pos = make_a_free_slot(n);
if (pos>=0)
_set[pos]=n;
}
return;
}
public int getSize() {
return _last+1;
}
public int getElementAt(int i) {
if ((i<0)||(i>_last))
return -1;
else
return _set[i];
}
private int binSearch(int x) {
int i=0;
int j=_last-1;
int m=0;
if (_last==-1)
return -1;
while(i<j) {
m= (i+j)/2;
if (x>_set[m])
i=m+1;
else
j=m;
}
if (x == _set[i]) return i;
else return -1;
}
public OrdSetSimple difference(OrdSetSimple s2) {
OrdSetSimple s1 = this;
int size1=s1.getSize();
int size2=s2.getSize();
OrdSetSimple set=new OrdSetSimple(size2);
int k;
for(k=0; k<size1; k++)
if (s2.binSearch(s1.getElementAt(k)) < 0)
set.addElement(s1.getElementAt(k));
return set;
}
public String toString() {
int k = 0;
String s="";
for (k=0; k<=_last; k++)
s += _set[k] + " ";
return s;
}
}
Your very first statement is wrong.
OrdSetSimple obj = new OrdSetSimple();//This will call the default constructor which will not initialize anything. This constructor will be added to your program by compiler, hence you don't get any compilation error.
Correct it like
OrdSetSimple obj = new OrdSetSimple(100);

Binary search program printing false

Hello every one i'm working on a binary search program. My algorithm is correct but when I run the program with the driver program i get back the value "false" repeated instead of a table that looks like this.
Table output(LINK)
here is my driver program and main program.
public class TestResulter {
public static void main(String[] args) {
//Resulter resulter = new Resulter();
int numberOfItems = 10000;
int item;
int a[ ] = new int[ numberOfItems ];
for( int i = 0; i < 20; i++ )
{
item = Resulter.randomitem( a );
System.out.println( Resulter.binarySearch( a , item ) );
}
}
}
My main program with binarySearch algorithm.
import java.util.Random;
public class Resulter extends TestResulter {
private static class Result {
public Boolean found; // true if found, false if not found
public int index; // index where item was found, -1 if not found
public int steps; // number of comparisons performed
public Result(boolean f, int ind, int st) {
found = f;
index = ind;
steps = st;
}
#Override
public String toString() {
return "Result [found=" + found + ", index=" + index + ", steps=" + steps + "]";
}
}
public static boolean binarySearch(int[] a, int item) {
int start=0, end=a.length-1;
while(end>=start) {
int mid = start + ((end - start) / 2);
if (a[mid] == item)
return true;
if (a[mid] > item)
end = mid-1;
else start = mid+1;
}
return false;
}
public static int randomitem ( int[] a ) {
int i;
Random random = new Random();
int item = random.nextInt( 10999 );
for( i = 0; i < 10000; i++ )
{
a[ i ] = random.nextInt( 10000 );
}
return item;
}
}
I want my program to have a similar output to my image from my linear search program.
Here is your code with some changes and refactoring:
public class TestResulter
{
public static void main(String[] args)
{
int numberOfItems = 10000;
int item;
int[] a = new int[numberOfItems];
fillArray(a);
for( int i = 0; i < 20; i++ )
{
item = Resulter.randomitem(a);
System.out.println(Resulter.binarySearch(a, item));
}
}
private static void fillArray(int[] a)
{
Random random = new Random();
for(int i = 0; i < a.length; i++)
a[i] = random.nextInt(10000);
Arrays.sort(a);
}
}
public class Resulter
{
private static class Result
{
public boolean found; // true if found, false if not found
public int index; // index where item was found, -1 if not found
public int steps; // number of comparisons performed
public Result(boolean f, int ind, int st)
{
found = f;
index = ind;
steps = st;
}
#Override
public String toString()
{
return "Result [found=" + found + ", index=" + index + ", steps=" + steps + "]";
}
}
public static Result binarySearch(int[] a, int item)
{
int start=0, end=a.length-1;
int stepCount = 0;
while(end>=start)
{
stepCount++;
int mid = start + ((end - start) / 2);
if(a[mid] == item)
return new Result(true, mid, stepCount);
else if(a[mid] > item)
end = mid-1;
else
start = mid+1;
}
return new Result(false, -1, stepCount);
}
public static int randomitem(int[] a)
{
return new Random().nextInt(10000);
}
}
As I see it, the main problems in your solution were:
The array was not sorted. Binary search only works on sorted arrays, therefore the Arrays.sort(a) command.
The binarySearch returned a boolean and not a Result object, which is what you wanted to print out.
You have a syntax hiccup in your main function. Change int a[] to int[] a.
Also, the logic actions performed in randomitem are likely a contributing factor. The item it returns which binarysearch uses is not pulled from the search array a, but is generated at random. Try return a[random.nestIng(a.length)];
I'm on the mobile app, so my syntax may not be perfect.

implementing Subset Sum with genetic Algorithm

import java.util.Collections;
import java.util.Vector;
public class Metaheuristic {
private static int[] DATA;
private static int NUM_CHROMOSOMES ;
private static int MAX_POWER;
private static int MAX_NUMBER;
private static int FITNESS_THRESHOLD;
private static float MUTATE = (float) .05;
private Vector population;
private boolean done = true;
int numRuns = 0;
public void GeneticAlgorithm (int[] data, int target, int n){
NUM_CHROMOSOMES = n;
MAX_POWER = data.length;
MAX_NUMBER = (int) Math.pow(2, MAX_POWER) - 1;
FITNESS_THRESHOLD = target;
DATA = new int[data.length];
DATA = data;
Metaheuristic s = new Metaheuristic();
s.start();
//System.out.println("s");
}
public Metaheuristic(){
generateRandomPopulation();
}
private void generateRandomPopulation(){
System.out.println("***Randomly Generating population with: " + NUM_CHROMOSOMES + " Chromosome(s)***");
population = new Vector();
for(int i = 0; i < NUM_CHROMOSOMES; ++i){
int randomValue = (int) (Math.random()*MAX_NUMBER);
population.add(new Chromosome(randomValue, MAX_POWER));
}
System.out.println("First Population: " + population +"\n");
}
public void start(){
Collections.sort(population);
Chromosome fitess = (Chromosome) population.lastElement();
done = fitess.fitness(DATA, FITNESS_THRESHOLD) >= MAX_POWER? true:false;
if(done){
System.out.println("DONE, solution found: " + fitess);
}
else{
numRuns++;
System.out.println("FITESS: " + fitess + " fitness: " + fitess.fitness(DATA, FITNESS_THRESHOLD ));
generateNewPopulation();
start();
}
}
private void generateNewPopulation(){
System.out.println("***Generating New Population");
Vector temp = new Vector();
for(int i = 0; i < population.size()/2; ++i){
Chromosome p1 = selectParent();
Chromosome p2 = selectParent();
temp.add(cross1(p1, p2));
temp.add(cross2(p1, p2));
}
population.clear();
population.addAll(temp);
System.out.println("New Population: " + population + "\n");
}
private Chromosome selectParent(){
int delta = population.size();
delta = NUM_CHROMOSOMES - NUM_CHROMOSOMES/2;
int num = (int) (Math.random()*10 + 1);
int index;
if(num >= 4){
index = (int) (Math.random()*delta + NUM_CHROMOSOMES/2);
}
else{
index = (int) (Math.random()*delta);
}
return (Chromosome) population.get(index);
}
private Chromosome cross1(Chromosome parent1, Chromosome parent2){
String bitS1 = parent1.getBitString();
String bitS2 = parent2.getBitString();
int length = bitS1.length();
String newBitString = bitS1.substring(0, length/2) + bitS2.substring(length/2, length);
Chromosome offspring = new Chromosome();
offspring.setBitString(newBitString);
if(shouldMutate()){
mutate(offspring);
}
return offspring;
}
private Chromosome cross2(Chromosome parent1, Chromosome parent2){
String bitS1 = parent1.getBitString();
String bitS2 = parent2.getBitString();
int length = bitS1.length();
String newBitString = bitS2.substring(0, length/2) + bitS1.substring(length/2, length);
Chromosome offspring = new Chromosome();
offspring.setBitString(newBitString);
if(shouldMutate()){
mutate(offspring);
}
return offspring;
}
private boolean shouldMutate(){
double num = Math.random();
int number = (int) (num*100);
num = (double) number/100;
return (num <= MUTATE);
}
private void mutate(Chromosome offspring){
String s = offspring.getBitString();
int num = s.length();
int index = (int) (Math.random()*num);
String newBit = flip(s.substring(index, index+1));
String newBitString = s.substring(0, index) + newBit + s.substring(index+1, s.length());
offspring.setBitString(newBitString);
}
private String flip(String s){
return s.equals("0")? "1":"0";
}
public static void main(String[] args) {
double average = 0;
int sum = 0;
for(int i = 0; i < 10; ++i){
Metaheuristic s = new Metaheuristic();
s.start();
sum = sum + s.numRuns;
average = (double) sum / (double)(i+1);
System.out.println("Number of runs: " + s.numRuns);
}
System.out.println("average runs: " + average);
}
}
import java.lang.Comparable;
public class Chromosome implements Comparable{
protected String bitString;
public static int[] DATA;
public int TARGET;
public Chromosome(){
}
public Chromosome(int value, int length){
bitString = convertIntToBitString(value, length);
}
public void setBitString(String s){
bitString = s;
}
public String getBitString(){
return bitString;
}
public int compareTo(Object o) {
Chromosome c = (Chromosome) o;
int num = countOnes(this.bitString) - countOnes(c.getBitString());
return num;
}
public int fitness(int[] data, int target){
DATA = new int[data.length];
System.arraycopy(data, 0, DATA, 0, data.length);
TARGET = target;
return countOnes(bitString);
}
public boolean equals(Object o){
if(o instanceof Chromosome){
Chromosome c = (Chromosome) o;
return c.getBitString().equals(bitString);
}
return false;
}
public int hashCode(){
return bitString.hashCode();
}
public String toString(){
return "Chromosome: " + bitString;
}
public static int countOnes(String bits){
int sum = 0;
for(int i = 0; i < bits.length(); ++ i){
String test = bits.substring(i, i+1);
sum = sum + (DATA[i]*Integer.parseInt(test));
}
return sum;
}
public static String convertIntToBitString(int val, int length){
int reval = val;
StringBuffer bitString = new StringBuffer(length);
for(int i = length-1; i >=0; --i ){
if( reval - (Math.pow(2, i)) >= 0 ){
bitString.append("1");
reval = (int) (reval - Math.pow(2, i));
}
else{
bitString.append("0");
}
}
return bitString.toString();
}
/* public static void main(String[] args){
//System.out.println(convertIntToBitString(2046, 10));
Chromosome c = new Chromosome(1234, 10);
System.out.println(c.fitness());
}*/
}
My fitness function is f(x ) = s · (C − P(x )) + (1 − s) · P(x ) in which C is my target value to reach and P(*x ) = (Sigma) wixi, where wi is the element's set and xi is 0 or 1 (the element is chosen or not). also s is 0 or 1, depends on p(x) value. please help me to write this fitness.
I have just tried it but the program run with errors.
You have several problems in your code, and obviously you didn't debug it. Here are some tips though.
First NUM_CHROMOSOMES is 0, because it's an uninitialized field (of the GeneticAlgorithm which you don't use).
Since NUM_CHROMOSOMES is 0, this for loop is useless:
for (int i = 0; i < NUM_CHROMOSOMES; ++i) {
Then, this line:
int randomValue = (int) (Math.random() * MAX_NUMBER);
Since MAX_NUMBER is never manually initialized (same as NUM_CHROMOSOMES, its value is 0, and so is randomValue.
Anyway, population is empty and since you don't test for emptyness, this line:
Chromosome fitess = (Chromosome) population.lastElement();
... throws an exception, because there is no such thing as a last element in your empty population Vector.
As a side note, StringBuffer, Vector are obsolete classes, and you never need to import Comparable, since it belongs to the java.lang package.

Java counter not counting properly

Hi I'm very new to Java and have this HW problem, we are asked to build Class LTile, a tile in the game of Scrabble.
The ID number of a tile should be assigned by a class/static data member, which keeps track of the number of LTile objects produced.
My ID output didn't not print from 1 to 26, instead, they are all assign 26.
I suspect my ID attribute must be wrong, but couldn't figure out the exactly error. Any help is greatly appreciated! Thanks!
package hw2;
public class LTile {
char letter;
private int value;
private static int ID=0;
public LTile(){
this.letter = '?';
this.value = 0;
LTile.ID++;
}
public LTile(char letter, int value){
this.letter=letter;
this.value=value;
LTile.ID++;
}
public char getLetter(){
return this.letter;
}
public int getValue(){
return this.value;
}
public int getID(){
return LTile.ID;
}
public boolean equals(Object obj){
if(this ==obj){
return true;}
else{
return false;
}
}
public String toString(){
return "["+ID+":" + letter+","+value+"]";
}
//**
//** main() for testing LTile
//**
public static void main(String[] args)
{
final String letters = "EAIONRTLSUDGBCMPFHVWYKJXQZ";
final int[] values = {1,1,1,1,1,1,1,1,1,1,2,2,3,3,3,3,4,4,4,4,4,5,8,8,10,10};
java.util.List<LTile> lst = new java.util.ArrayList<LTile>();
for (int i = 0; i < letters.length(); ++i)
lst.add(new LTile(letters.charAt(i), values[i]));
for (LTile tile : lst)
System.out.println(tile);
System.out.println();
// test for equals
boolean found = false;
for (int i = 0; i < lst.size()-1; ++i) {
for (int j = i+1; j < lst.size(); ++j) {
if (lst.get(i).equals(lst.get(j))) {
System.out.println("ERROR in equals() found for "
+ lst.get(i) + " and " + lst.get(j));
found = true;
}
}
}
if (!found)
System.out.println("No error in equals().");
}
}
My output is:
[26:E,1]
[26:A,1]
[26:I,1]
[26:O,1]
[26:N,1]
[26:R,1]
[26:T,1]
[26:L,1]
[26:S,1]
[26:U,1]
[26:D,2]
[26:G,2]
[26:B,3]
[26:C,3]
[26:M,3]
[26:P,3]
[26:F,4]
[26:H,4]
[26:V,4]
[26:W,4]
[26:Y,4]
[26:K,5]
[26:J,8]
[26:X,8]
[26:Q,10]
[26:Z,10]
No error in equals()
**The correct output should be:**
[1: E,1]
[2: A,1]
[3: I,1]
[4: O,1]
[5: N,1]
[6: R,1]
[7: T,1]
[8: L,1]
[9: S,1]
[10: U,1]
[11: D,2]
[12: G,2]
[13: B,3]
[14: C,3]
[15: M,3]
[16: P,3]
[17: F,4]
[18: H,4]
[19: V,4]
[20: W,4]
[21: Y,4]
[22: K,5]
[23: J,8]
[24: X,8]
[25: Q,10]
[26: Z,10]
No error in equals().
The ID number of a tile should be assigned by a class/static data member, which keeps track of the number of LTile objects produced.
This means that the id value should come from a static data member, not that it should be a static data member. So you need two fields: an instance id field to keep the object's id and a static CURRENT_ID field to keep track of how many objects you have created so far.
public class LTile {
char letter;
private int value;
private int id; // instance id
private static int CURRENT_ID = 0; // static counter from where the instance ids will be drawn
public LTile() {
// Call the other constructor to avoid unnecessary repetition
this('?', 0);
}
public LTile(char letter, int value) {
this.letter = letter;
this.value = value;
this.id = LTile.CURRENT_ID++;
}
// rest of the code
public int getID() {
return this.id;
}
public String toString() {
return "["+this.id+":" + this.letter+","+this.value+"]";
}
}
Note you also need to change getId() and toString() to use the instance id instead of the static counter.

trouble with array lists

I am doing a project and instead of using an array, I figured an array list would be better. I know I need to declare the array list and its methods, but I am not too sure where to go from there. Any suggestions? Here's code...
public class Student {
private String name;
private int[] tests;
public Student() {
this("");
}
public Student(String nm) {
this(nm, 3);
}
public Student(String nm, int n) {
name = nm;
tests = new int[n];
for (int i = 0; i < tests.length; i++) {
tests[i] = 0;
}
}
public Student(String nm, int[] t) {
tests = new int[t.length];
}
public Student(Student s) {
this(s.name, s.tests);
}
public int getNumberOfTests() {
return tests.length;
}
public void setName(String nm) {
name = nm;
}
public String getName() {
return name;
}
public void setScore(int i, int score) {
tests[i - 1] = score;
}
public int getScore(int i) {
return tests[i - 1];
}
public int getAverage() {
int sum = 0;
for (int score : tests) {
sum += score;
}
return sum / tests.length;
}
public int getHighScore() {
int highScore = 0;
for (int score : tests) {
highScore = Math.max(highScore, score);
}
return highScore;
}
public String toString() {
String str = "Name: " + name + "\n";
for (int i = 0; i < tests.length; i++) {
str += "test " + (i + 1) + ": " + tests[i] + "\n";
}
str += "Average: " + getAverage();
return str;
}
public String validateData() {
if (name.equals("")) {
return "SORRY: name required";
}
for (int score : tests) {
if (score < 0 || score > 100) {
String str = "SORRY: must have " + 0 + " <= test score <= " + 100;
return str;
}
}
return null;
}
}
I figured an array list would be better
Maybe. Maybe not. It depends. Does it look like you would get a benefit in using one based on the ArrayList API?
If your "list" never changes size, and you don't need to find things in it, then an array is just as good.
I know I need to declare the array list and its methods, but I am not
too sure where to go from there
You need to create a reference to an instance of an ArrayList. That's as simple as
List<Integer> myList = new ArrayList<Integer>();
in your class declaration. You don't need to "declare its methods". When you have a reference to an object, you can invoke its methods.
To use an ArrayList, you just need to declare and instantiate it:
// <SomeObject> tells Java what kind of things go in the ArrayList
ArrayList<SomeObject> aDescriptiveNameHere = new ArrayList<SomeObject>();
// This is also valid, since an ArrayList is also a List
List<SomeObject> list = new ArrayList<SomeObject>();
Then you can add things with the add() method:
// Please don't name your list "list"
list.add(new Thing(1));
list.add(new Thing(2));
You can get something by index (like you would with someArray[index]) as:
list.get(index);
// For example
Thing t = list.get(5);
You probably also need the size().
See the JavaDocs for more info.
All of the operations you're using are mirrored in the ArrayList API. One thing that's worth noting is that you cannot declare an ArrayList of primitive types, but for each of the primitive types there exists an Object that is the boxed version of the primative.
The boxed version of int is Integer, so you have
ArrayList<Integer> myList = new ArrayList<Integer>();
From there, you need to look up the methods you would need to use in order to manipulate the array. For example, if you want to add the number 42 to the end of the array, you would say
myList.add(42);
The ArrayList API is located here.
I think it could be better to use the stl vector instead make your own arrays
I tried to change the array to arraylist.
Reply if this doesn't compile correctly.
import java.util.ArrayList;
public class Student {
private String name;
// private int[] tests;
private ArrayList<Integer> tests;
public Student() {
this("");
}
public Student(String nm) {
// this(nm, 3);
name = nm;
}
/*
* public Student(String nm, int n) { name = nm; tests = new int[n]; for
* (int i = 0; i < tests.length; i++) { tests[i] = 0; } }
*/
/*
* public Student(String nm, int[] t) { tests = new int[t.length]; }
*/
public Student(Student s) {
this(s.name, s.tests);
}
public Student(String name2, ArrayList<Integer> tests2) {
name = name2;
tests = tests2;
}
public int getNumberOfTests() {
return tests.size();
}
public void setName(String nm) {
name = nm;
}
public String getName() {
return name;
}
// public void setScore(int i, int score) {
// tests[i - 1] = score;
public void setScore(int score) {
tests.add(score);
}
public int getScore(int i) {
// return tests[i - 1];
return tests.get(i - 1);
}
public int getAverage() {
int sum = 0;
for (int score : tests) {
sum += score;
}
// return sum / tests.length;
return sum / tests.size();
}
public int getHighScore() {
int highScore = 0;
for (int score : tests) {
highScore = Math.max(highScore, score);
}
return highScore;
}
public String toString() {
String str = "Name: " + name + "\n";
for (int i = 0; i < tests.size(); i++) {
str += "test " + (i + 1) + ": " + tests.get(i) + "\n";
}
str += "Average: " + getAverage();
return str;
}
public String validateData() {
if (name.equals("")) {
return "SORRY: name required";
}
for (int score : tests) {
if (score < 0 || score > 100) {
String str = "SORRY: must have " + 0 + " <= test score <= "
+ 100;
return str;
}
}
return null;
}
public ArrayList<Integer> getTests() {
return tests;
}
public void setTests(ArrayList<Integer> tests) {
this.tests = tests;
}
}

Categories