illegal start of expression error, working with methods - methods

So I keep getting illegal start of expression errors around line 30 when trying to run my DiceGame program which is practice with methods. Here's my code:
import java.util.Scanner;
public class DiceGame
{
public static void main(String[] args)
{
final int RANGE = 6;
Scanner input = new Scanner(System.in);
int userGuess = input.next();
int throwResult = throw2Dice(RANGE);
int programGuess = throw2Dice(RANGE);
int userError = Math.abs(throwResult - userGuess);
int programError = Math.abs(throwResult - programGuess);
boolean userWins = false;
if(userError < programError)
{
userWins = true;
{
System.out.println("Your guess was: " + userGuess + " the program's guess was: " + programGuess + " and the result was: " + throwResult);
if(userWins == false)
System.out.println("Program Wins!!!");
else
System.out.println("User Wins!!!");
}
public static int throw2Dice(int r)
{
int number1 = (Math.random() * r + 1);
int number2 = (Math.random() * r + 1);
int sum = number1 + number2;
return sum;
}
}

if(userError < programError)
{
userWins = true;
{
You have two open braces instead of an open brace and a close brace.

Related

Optimizing apriori algorithm code

I am writing code for apriori algorithm in data mining my code takes as long as 60 seconds for a pretty small dataset which is solved by other code i got from internet in just 2 seconds but i am not getting where am i doing wrong, can someone tell me why the other code is fast over mine.
My code:
import java.util.*;
import java.io.*;
public class Apriori_p {
double support;
ArrayList<String> trans;
Map<String, Integer> map;
long start;
void print(ArrayList<String> temp) {
for (int i = 0; i < temp.size(); i++) {
System.out.println(temp.get(i));
}
System.out.println("Count :" + temp.size());
}
void run() throws FileNotFoundException {
start = System.currentTimeMillis();
trans = new ArrayList<>();
ArrayList<String> temp = new ArrayList<>();
map = new HashMap<>();
Scanner sc = new Scanner(System.in);
System.out.println("Enter support %");
support = sc.nextDouble();
System.out.println("Enter file name");
String file = sc.next();
sc = new Scanner(new File(file));
int lines = 0;
while (sc.hasNextLine()) {
String s = sc.nextLine();
if (s.matches("\\s*")) {
continue;
}
lines++;
String[] spl = s.split("\\s+");
ArrayList<Integer> elem = new ArrayList<>();
for (int i = 0; i < spl.length; i++) {
String cand;
int n = Integer.parseInt(spl[i]);
cand = spl[i].trim();
if (!elem.contains(n)) {
elem.add(n);
}
if (map.containsKey(cand)) {
int count = map.get(cand);
map.put(cand, count + 1);
} else {
map.put(cand, 1);
}
}
Collections.sort(elem);
String con = " ";
for (int i = 0; i < elem.size(); i++) {
con = con + elem.get(i) + " ";
String s1 = String.valueOf(elem.get(i)).trim();
if(!temp.contains(s1))
temp.add(s1);
}
trans.add(con);
}
support = (support * lines) / 100;
System.out.println(System.currentTimeMillis() - start);
apriori(temp, 1);
}
public static void main(String[] args) throws FileNotFoundException {
new Apriori_p().run();
}
public void apriori(ArrayList<String> temp, int m) {
Set<String> diff = null;
if (m == 1) {
diff = new HashSet<>();
}
for (int i = 0; i < temp.size(); i++) {
if (map.get(temp.get(i)) < support) {
if (m == 1) {
diff.add(temp.get(i));
}
temp.remove(i);
i--;
}
}
for (int i = 0; i < trans.size() && m == 1; i++) {
for (String j : diff) {
String rep = " " + j + " ";
trans.get(i).replace(rep, " ");
}
}
if (temp.size() == 0) {
return;
}
System.out.println("Size " + m + " :");
print(temp);
ArrayList<String> ntemp = new ArrayList<>();
int n = temp.size();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
StringTokenizer st1 = new StringTokenizer(temp.get(i), " ");
StringTokenizer st2 = new StringTokenizer(temp.get(j), " ");
String str1 = "", str2 = "";
for (int s = 0; s < m - 2; s++) {
str1 = str1 + " " + st1.nextToken();
str2 = str2 + " " + st2.nextToken();
}
if (str2.compareToIgnoreCase(str1) == 0) {
int s1 = Integer.parseInt(st1.nextToken()), s2 = Integer.parseInt(st2.nextToken());
String s3;
if (s1 <= s2) {
s3 = (str1 + " " + s1 + " " + s2).trim();
} else {
s3 = (str1 + " " + s2 + " " + s1).trim();
}
if(!ntemp.contains(s3)){
ntemp.add(s3);
}
}
}
}
temp.clear();
for (int j = 0; j < ntemp.size(); j++) {
int c = 0;
for (int i = 0; i < trans.size(); i++) {
int check = 0;
String tr = trans.get(i);
StringTokenizer st1 = new StringTokenizer(ntemp.get(j)," ");
while(st1.hasMoreElements()){
String str = st1.nextToken();
if(!tr.contains(" " + str + " ")){
check = 1;
break;
}
}
if(check == 0){
c= 1;
if (map.containsKey(ntemp.get(j))) {
int count = map.get(ntemp.get(j));
map.put(ntemp.get(j), count + 1);
} else {
map.put(ntemp.get(j), 1);
}
}
}
if (c == 0) {
ntemp.remove(j);
j--;
}
}
apriori(ntemp, m + 1);
}
}
Fast code:
import java.io.*;
import java.util.*;
public class Apriori3{
public static void main(String[] args) throws Exception {
Apriori3 ap = new Apriori3(args);
}
private List<int[]> itemsets;
private String transaFile;
private int numItems;
private int numTransactions;
private double minSup;
private boolean usedAsLibrary = false;
public Apriori3(String[] args) throws Exception {
configure(args);
go();
}
private void go() throws Exception {
long start = System.currentTimeMillis();
createItemsetsOfSize1();
int itemsetNumber = 1;
int nbFrequentSets = 0;
while (itemsets.size() > 0) {
calculateFrequentItemsets();
if (itemsets.size() != 0) {
nbFrequentSets += itemsets.size();
log("Found " + itemsets.size() + " frequent itemsets of size " + itemsetNumber + " (with support " + (minSup * 100) + "%)");;
createNewItemsetsFromPreviousOnes();
}
itemsetNumber++;
}
long end = System.currentTimeMillis();
log("Execution time is: " + ((double) (end - start) / 1000) + " seconds.");
log("Found " + nbFrequentSets + " frequents sets for support " + (minSup * 100) + "% (absolute " + Math.round(numTransactions * minSup) + ")");
log("Done");
}
private void foundFrequentItemSet(int[] itemset, int support) {
if (usedAsLibrary) {
} else {
System.out.println(Arrays.toString(itemset) + " (" + ((support / (double) numTransactions)) + " " + support + ")");
}
}
private void log(String message) {
if (!usedAsLibrary) {
System.err.println(message);
}
}
private void configure(String[] args) throws Exception {
if (args.length != 0) {
transaFile = args[0];
} else {
transaFile = "chess.dat"; // default
}
if (args.length >= 2) {
minSup = (Double.valueOf(args[1]).doubleValue());
} else {
minSup = .8;
}
if (minSup > 1 || minSup < 0) {
throw new Exception("minSup: bad value");
}
numItems = 0;
numTransactions = 0;
BufferedReader data_in = new BufferedReader(new FileReader(transaFile));
while (data_in.ready()) {
String line = data_in.readLine();
if (line.matches("\\s*")) {
continue;
}
numTransactions++;
StringTokenizer t = new StringTokenizer(line, " ");
while (t.hasMoreTokens()) {
int x = Integer.parseInt(t.nextToken());
if (x + 1 > numItems) {
numItems = x + 1;
}
}
}
outputConfig();
}
private void outputConfig() {
log("Input configuration: " + numItems + " items, " + numTransactions + " transactions, ");
log("minsup = " + minSup + "%");
}
private void createItemsetsOfSize1() {
itemsets = new ArrayList<int[]>();
for (int i = 0; i < numItems; i++) {
int[] cand = {i};
itemsets.add(cand);
}
}
private void createNewItemsetsFromPreviousOnes() {
int currentSizeOfItemsets = itemsets.get(0).length;
log("Creating itemsets of size " + (currentSizeOfItemsets + 1) + " based on " + itemsets.size() + " itemsets of size " + currentSizeOfItemsets);
HashMap<String, int[]> tempCandidates = new HashMap<String, int[]>(); //temporary candidates
for (int i = 0; i < itemsets.size(); i++) {
for (int j = i + 1; j < itemsets.size(); j++) {
int[] X = itemsets.get(i);
int[] Y = itemsets.get(j);
assert (X.length == Y.length);
int[] newCand = new int[currentSizeOfItemsets + 1];
for (int s = 0; s < newCand.length - 1; s++) {
newCand[s] = X[s];
}
int ndifferent = 0;
for (int s1 = 0; s1 < Y.length; s1++) {
boolean found = false;
for (int s2 = 0; s2 < X.length; s2++) {
if (X[s2] == Y[s1]) {
found = true;
break;
}
}
if (!found) {
ndifferent++;
newCand[newCand.length - 1] = Y[s1];
}
}
assert (ndifferent > 0);
if (ndifferent == 1) {
Arrays.sort(newCand);
tempCandidates.put(Arrays.toString(newCand), newCand);
}
}
}
itemsets = new ArrayList<int[]>(tempCandidates.values());
log("Created " + itemsets.size() + " unique itemsets of size " + (currentSizeOfItemsets + 1));
}
private void line2booleanArray(String line, boolean[] trans) {
Arrays.fill(trans, false);
StringTokenizer stFile = new StringTokenizer(line, " ");
while (stFile.hasMoreTokens()) {
int parsedVal = Integer.parseInt(stFile.nextToken());
trans[parsedVal] = true;
}
}
private void calculateFrequentItemsets() throws Exception {
log("Passing through the data to compute the frequency of " + itemsets.size() + " itemsets of size " + itemsets.get(0).length);
List<int[]> frequentCandidates = new ArrayList<int[]>();
boolean match;
int count[] = new int[itemsets.size()];
BufferedReader data_in = new BufferedReader(new InputStreamReader(new FileInputStream(transaFile)));
boolean[] trans = new boolean[numItems];
for (int i = 0; i < numTransactions; i++) {
String line = data_in.readLine();
line2booleanArray(line, trans);
for (int c = 0; c < itemsets.size(); c++) {
match = true;
int[] cand = itemsets.get(c);
for (int xx : cand) {
if (trans[xx] == false) {
match = false;
break;
}
}
if (match) {
count[c]++;
}
}
}
data_in.close();
for (int i = 0; i < itemsets.size(); i++) {
if ((count[i] / (double) (numTransactions)) >= minSup) {
foundFrequentItemSet(itemsets.get(i), count[i]);
frequentCandidates.add(itemsets.get(i));
}
}
itemsets = frequentCandidates;
}
}

How to use resolve the zkemkeeper embedd issue?

Please check the code below :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using iTimeService.dsitimeTableAdapters;
using System.IO;
namespace iTimeService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
public zkemkeeper.CZKEMClass axCZKEM1 = new zkemkeeper.CZKEMClass();
private bool bIsConnected = false;//the boolean value identifies whether the device is connected
private int iMachineNumber = 1;//the serial number of the device.After connecting the device ,this value will be changed.
TENTERTableAdapter tenteradapter = new TENTERTableAdapter();
T012_GATETableAdapter gateadapter = new T012_GATETableAdapter();
}
}
I am getting an error on the object creation of zkemkeeper.CZKEMClass where it says : interop type 'zkemkeeper.CZKEMClass' cannot be embedded. Use the application interface instead.
click on the reference you have, I think for that specific project that would be 'zkemkeeper'
then on its properties just set the 'Embed Interop Type' to 'False'
I hope this would help.
OK, Thanks!
private MayChamCongBLL _mayChamCongBLL = new MayChamCongBLL();
private MayChamCongDTO _mayChamCongDTO = new MayChamCongDTO();
// private System.Configuration.Configuration _ngonNgu = ConfigurationManager.OpenExeConfiguration("MitaAttendance.exe");
private int a;
private ArrayList arrMayChamCong = new ArrayList();
//public CZKEM axCZKEM1 = new CZKEM();
public zkemkeeper.CZKEMClass axCZKEM1 = new zkemkeeper.CZKEMClass();
private int b;
// private Bar bar1;
private bool bIsConnected = false;
private int c;
private string sMaMayChamCong;
private string sSuDungWeb;
private int iMachineNumber = 1;
private int iNgonNgu;
private CZKEMClass axCZKEM1 = new CZKEMClass();
private static bool _bIsConnected = false;
private static int _iMachineNumber = 1;
private static int _errorCode = 0;
public bool GetConnectState()
{
return _bIsConnected;
}
private void SetConnectState(bool state)
{
_bIsConnected = state;
}
private int GetMachineNumber()
{
return _iMachineNumber;
}
public int sta_ConnectTCP(string ip, string port, string commKey)
{
if (ip == "" || port == "" || commKey == "")
{
return -1;// ip or port is null
}
if (Convert.ToInt32(port) <= 0 || Convert.ToInt32(port) > 65535)
{
return -1;
}
if (Convert.ToInt32(commKey) < 0 || Convert.ToInt32(commKey) > 999999)
{
return -1;
}
int idwErrorCode = 0;
axCZKEM1.SetCommPassword(Convert.ToInt32(commKey));
if (_bIsConnected)
{
axCZKEM1.Disconnect();
SetConnectState(false);
return -2; //disconnect
}
if (axCZKEM1.Connect_Net(ip, Convert.ToInt32(port)))
{
SetConnectState(true);
return 1;
}
else
{
axCZKEM1.GetLastError(ref idwErrorCode);
return idwErrorCode;
}
}
public void sta_DisConnect()
{
if (GetConnectState())
{
axCZKEM1.Disconnect();
}
}
public int sta_ReadNewAttLog(DataTable dt_log)
{
if (GetConnectState() == false)
{
//Please connect first!";
return -1024;
}
int ret = 0;
axCZKEM1.EnableDevice(GetMachineNumber(), false);//disable the device
string sdwEnrollNumber = "";
int idwVerifyMode = 0;
int idwInOutMode = 0;
int idwYear = 0;
int idwMonth = 0;
int idwDay = 0;
int idwHour = 0;
int idwMinute = 0;
int idwSecond = 0;
int idwWorkcode = 0;
if (axCZKEM1.ReadNewGLogData(GetMachineNumber()))
{
while (axCZKEM1.SSR_GetGeneralLogData(GetMachineNumber(), out sdwEnrollNumber, out idwVerifyMode,
out idwInOutMode, out idwYear, out idwMonth, out idwDay, out idwHour, out idwMinute, out idwSecond, ref idwWorkcode))//get records from the memory
{
DataRow dr = dt_log.NewRow();
dr["User ID"] = sdwEnrollNumber;
dr["Verify Date"] = idwYear + "-" + idwMonth + "-" + idwDay + " " + idwHour + ":" + idwMinute + ":" + idwSecond;
dr["idwYear"] = idwYear;
dr["idwMonth"] = idwMonth;
dr["idwDay"] = idwDay;
dr["idwHour"] = idwHour;
dr["idwMinute"] = idwMinute;
dr["idwSecond"] = idwSecond;
dr["Verify Type"] = idwVerifyMode;
dr["Verify State"] = idwInOutMode;
dr["WorkCode"] = idwWorkcode;
dt_log.Rows.Add(dr);
}
ret = 1;
}
else
{
axCZKEM1.GetLastError(ref _errorCode);
ret = _errorCode;
if (_errorCode != 0)
{
//"*Read attlog by period failed,ErrorCode: " + idwErrorCode.ToString();
}
else
{
//"No data from terminal returns!";
}
}
//lblOutputInfo.Items.Add("[func ReadNewGLogData]Temporarily unsupported");
axCZKEM1.EnableDevice(GetMachineNumber(), true);//enable the device
return ret;
}

Affine Cipher Code in java that also encrypts integer

private static int firstKey = 5;
private static int secondKey = 19;
private static int module = 26;
public static void main(String[] args) {
String input = "abcdefghijklmnopqrstuvwxyz";
String cipher = encrypt(input);
String deciphered = decrypt(cipher);
System.out.println("Source: " + input);
System.out.println("Encrypted: " + cipher);
System.out.println("Decrypted: " + deciphered);
}
static String encrypt(String input) {
StringBuilder builder = new StringBuilder();
for (int in = 0; in < input.length(); in++) {
char character = input.charAt(in);
// if (Character.isLetter(character)) {
character = (char) ((firstKey * (character - 'a') + secondKey) % module + 'a');
//}
builder.append(character);
}
return builder.toString();
}
static String decrypt(String input) {
StringBuilder builder = new StringBuilder();
// compute firstKey^-1 aka "modular inverse"
BigInteger inverse = BigInteger.valueOf(firstKey).modInverse(BigInteger.valueOf(module));
// perform actual decryption
for (int in = 0; in < input.length(); in++) {
char character = input.charAt(in);
// if (Character.isLetter(character)) {
int decoded = inverse.intValue() * (character - 'a' - secondKey + module);
character = (char) (decoded % module + 'a');
//}
builder.append(character);
}
return builder.toString();
}
i got this code from this site itself
but the above code does not decrpyt the integers ..
please help
above is a code that i got from this site.
but this doesnot decrypts the integer.
please help.
I have added two more functiond that incrypt and decrypt integers that work.You can use them when you want to incrypt, decrypt integers, and the previous functions when you want to enc/dec lower case alphabets
//Code
import java.math.BigInteger;
public class main{
private static int firstKey = 5;
private static int secondKey = 19;
private static int module = 26;
public static void main(String[] args) {
String input = "abcdefghijklmnopqrstuvwxyz";
String cipher = encrypt(input);
String deciphered = decrypt(cipher);
System.out.println("Source: " + input);
System.out.println("Encrypted: " + cipher);
System.out.println("Decrypted: " + deciphered);
System.out.println("\n");
//for Integer
String input1 = "826429837598327598327549832";
String cipher1 = encryptInt(input1);
String deciphered1 = decryptInt(cipher1);
System.out.println("Source: " + input1);
System.out.println("Encrypted: " + cipher1);
System.out.println("Decrypted: " + deciphered1);
}
static String encrypt(String input) {
StringBuilder builder = new StringBuilder();
for (int in = 0; in < input.length(); in++) {
char character = input.charAt(in);
// if (Character.isLetter(character)) {
character = (char) ((firstKey * (character - 'a') + secondKey) % module + 'a');
//}
builder.append(character);
}
return builder.toString();
}
static String decrypt(String input) {
StringBuilder builder = new StringBuilder();
// compute firstKey^-1 aka "modular inverse"
BigInteger inverse = BigInteger.valueOf(firstKey).modInverse(BigInteger.valueOf(module));
// perform actual decryption
for (int in = 0; in < input.length(); in++) {
char character = input.charAt(in);
// if (Character.isLetter(character)) {
int decoded = inverse.intValue() * (character - 'a' - secondKey + module);
character = (char) (decoded % module + 'a');
//}
builder.append(character);
}
return builder.toString();
}
//ENCRIPTION DECRIPTION FOR INTEGERS
static String encryptInt(String input) {
StringBuilder builder = new StringBuilder();
for (int in = 0; in < input.length(); in++) {
char character = input.charAt(in);
// if (Character.isLetter(character)) {
character = (char) ((firstKey * (character - '0') + secondKey) % module + '0');
//}
builder.append(character);
}
return builder.toString();
}
static String decryptInt(String input) {
StringBuilder builder = new StringBuilder();
// compute firstKey^-1 aka "modular inverse"
BigInteger inverse = BigInteger.valueOf(firstKey).modInverse(BigInteger.valueOf(module));
// perform actual decryption
for (int in = 0; in < input.length(); in++) {
char character = input.charAt(in);
// if (Character.isLetter(character)) {
int decoded = inverse.intValue() * (character - '0' - secondKey + module);
character = (char) (decoded % module + '0');
//}
builder.append(character);
}
return builder.toString();
}
}

Processing skipping every other

I am trying to group segments of the XBee output into a variable that joins them. I am using Processing to code and compile. The issue I am having is that the output (println) is skipping every other byte (maybe that's the wrong term). So XBee output for i = 4 though 11 should look like this:
0,19,162,0,64,121,230,206 (this is the XBee address converted from hex).
But the println shows this:
19,0,121,206,125,1,0,3 (which starts getting into other segments of the output).
Later, I tried a different route by using an array. It still skips every other entry and I've found that it has to do with my check for i == 126. Is there an alternate way of doing a check like this?
Substitute this draw section for the one below. It's simpler to follow. This was a test with same results...
void draw() {
if (myPort.available() > 21) {
int[] XBeeAddr = new int[22];
for (int i=0; i<22; i++) {
XBeeAddr[i] = myPort.read();
if (myPort.read == 126) {
i=0;
}
println(XBeeAddr[0] + "," + XBeeAddr[1] + "," + XBeeAddr[2]);
}
}
Original code
import processing.serial.*;
import de.bezier.data.sql.*; // For SQLite database
SQLite db; // For SQLite database
Serial myPort;
void setup() {
println(Serial.list());
myPort = new Serial(this, Serial.list()[0],9600);
// For SQLite database...
size( 100, 100 );
db = new SQLite( this, "test.db" ); // Open database file
if ( db.connect() ) {
String[] tableNames = db.getTableNames();
db.query( "SELECT * FROM %s", tableNames[0] );
while (db.next()) {
TableOne t = new TableOne();
db.setFromRow( t );
println( t );
}
}
}
// For SQLite database
class TableOne {
public String fieldOne;
public int fieldTwo;
public String toString () {
return String.format("fieldOne: %s fieldTwo: %d", fieldOne, fieldTwo);
}
}
void draw() {
if (myPort.available() > 21) {
int XBeeAddr1 = 0;
int XBeeAddr2 = 0;
int XBeeAddr3 = 0;
int XBeeAddr4 = 0;
int XBeeAddr5 = 0;
int XBeeAddr6 = 0;
int XBeeAddr7 = 0;
int XBeeAddr8 = 0;
for (int i=0; i<22; i++) {
int inByte = myPort.read();
if (inByte == 126) {
i=0; // This resets the counter if XBee data was incomplete on the last run.
}
if (i == 4) {
XBeeAddr1 = myPort.read();
}
if (i == 5) {
XBeeAddr2 = myPort.read();
}
if (i == 6) {
XBeeAddr3 = myPort.read();
}
if (i == 7) {
XBeeAddr4 = myPort.read();
}
if (i == 8) {
XBeeAddr5 = myPort.read();
}
if (i == 9) {
XBeeAddr6 = myPort.read();
}
if (i == 10) {
XBeeAddr7 = myPort.read();
}
if (i == 11) {
XBeeAddr8 = myPort.read();
}
String XBeeAddrAll = XBeeAddr1 + "," +
XBeeAddr2 + "," +
XBeeAddr3 + "," +
XBeeAddr4 + "," +
XBeeAddr5 + "," +
XBeeAddr6 + "," +
XBeeAddr7 + "," +
XBeeAddr8;
println(XBeeAddrAll);
}
}
}
It was fixed by changing myPort.read == 126 to if XBeeAddr[0] != 126, break. Then later I did an if XBeeAddr[0] == 126 println.

Can someone with GA experience examine my fitness function?

Here is my problem, I'm modifying code I found for Genetic Algorithms to do numerical optimization of a function. Essentially, given a function F and our Desired Value, the program uses GA to searches for values of x and y which provide the appropriate Desired Value.
I keep tinkering with my fitness function, which I feel is the root of the issue.
The basic code break down is:
Generate a random chromosome population
Use a bubble sort based on each chromosomes fitness
Check if any of them happen to solve the function
If one solves it, then stop and print it
Else,
Generate children based on the parents
Sort, check the best answer, loop
I hope someone can point me in the right direction I'm going to dissect it again some more tonight but I seem to have hit a snag on this. For more complex functions than that I have hard coded, it seems to converge around a random percentage (usually less than 20)... but it should be much closer to 0. The simple coded function keeps returning around 99% difference... so I'm not 100% on whats up.
import java.util.*;
import java.util.Comparator;
import java.util.TreeMap;
/**
* Modified from a file created Jul 9, 2003
* Original #author Fabian Jones
* Modified #author Cutright
* #version 2
*/
public class ScratchGA
{
private static int NUM_CHROMOSOMES = 100; //num of chromosomes in population
private static double MUTATE = .01; //chance of a mutation i.e. 88.8%
private static int desiredValue = 60466176; //desired value of function
private static int cutoff = 1000; // number of iterations before cut off
private static int longPrint = 0; //1 means print out each iteration of the population
private boolean done = false;
private Chromosome[] population;
int iteration = 0;
/**
* Constructor for objects of class ScratchGA
*/
public ScratchGA()
{
generateRandomPopulation(NUM_CHROMOSOMES);
printPopulation();
}
/**
* Generate a random population of chromosomes - WORKS
*
*/
private void generateRandomPopulation(int pop)
{
System.out.println("Generating random population of " + pop + ", now." +"\n");
population = new Chromosome[pop];
for(int i=0; i<pop; i++)
{
int rand = (int)(Math.random()*4095); // Range 0 to 4095
population[i] = (new Chromosome(rand, 12));
}
}
/**
* Codesaver for generating a new line in the output
*/
private void newLine()
{
System.out.println("\n");
}
/**
* Prints the population (the chromosomes)
*/
private void printPopulation()
{
int x=1; // variable to print 10 chromosomes on a line
if (iteration==0)
{
System.out.println("Initial population: " + "\n" );
}
else
{
if (longPrint ==1)
{
System.out.println("Population " + iteration + " :" + "\n");
for(int i=0; i<=(NUM_CHROMOSOMES-1); i++)
{
System.out.print(population[i] + " ");
if(x == 10)
{
newLine();
x=1;
}
else
{
x++;
}
}
newLine();
}
else
{
System.out.println("Best answer for iteration " + iteration + " is: " + population[0] + " with a % difference of " +population[0].getFitness());
newLine();
}
}
}
/**
* Start
* Bubblesort initial population by their fitness, see if the first chromosome
* in the sorted array satisfies our constraint.
* IF done ==true or max num of iterations
* Print best solution and its fitness
* ELSE
* generate new population based on old one, and continue on
*/
public void start()
{
// System.out.println("Starting bubblesort... Please Wait.");
bubbleSort();
//System.out.println("After Bubblesort: " );
//printPopulation();
topFitness();
if(done || iteration==cutoff){
System.out.println("DONE!!");
System.out.println("Best solution: " + population[0] + " % Difference: " + population[0].getFitness());
}
else{
iteration++;
generateNewPopulation();
printPopulation();
start();
}
}
/**
* If the top chromosomes fitness (after being sorted by bubblesort) is 100%
* done == true
*/
private void topFitness()
{
if (population[0].getFitness() == 0)
{
done = true;
}
}
/**
* Called from chromosome,
* Tests the x and y values in the function and returns their output
*/
public static double functionTest(int x, int y)
{
return (3*x)^(2*y); // From our desired value we're looking for x=2, y=5
}
/**
* Returns the desired outcome of the function, with ideal x and y
* Stored above in a private static
*/
public static int getDesired()
{
return desiredValue;
}
/**
* Sort Chromosome array, based on fitness
* utilizes a bubblesort
*/
private void bubbleSort()
{
Chromosome temp;
for(int i=0; i<NUM_CHROMOSOMES; i++){
for(int j=1; j<(NUM_CHROMOSOMES-i); j++){
if(population[j-1].getFitness() > population[j].getFitness())
{
//swap elements
temp = population[j-1];
population[j-1] = population[j];
population[j] = temp;
}
}
}
}
/**
* Top 30: Elitism
* Next 60: Offspring of Elitists
* Next 10: Random
*/
private void generateNewPopulation(){
System.out.println("***Generating New Population");
Chromosome[] temp = new Chromosome[100];
for (int i = 0; i < 30; i++)
{
Chromosome x = population[i];
if (shouldMutate())
mutate(x);
temp[i]=x;
}
for (int i = 0; i < 30; i++)
{
temp[i+30] =cross1(population[i], population[i+1]);
temp[i+60] = cross2(population[i], population[i+1]);
}
for (int i = 90; i<100; i++)
{
int rand = (int)(Math.random()*4095); // Range 0 to 4095
Chromosome x = new Chromosome(rand, 12);
temp[i] = x;
}
population = temp;
}
/**
* First cross type, with two parents
*/
private Chromosome cross1(Chromosome parent1, Chromosome parent2){
String bitS1 = parent1.getBitString();
String bitS2 = parent2.getBitString();
int length = bitS1.length();
int num = (int)(Math.random()*length); // number from 0 to length-1
String newBitString = bitS2.substring(0, num) + bitS1.substring(num, length);
Chromosome offspring = new Chromosome();
offspring.setBitString(newBitString);
if(shouldMutate()){
mutate(offspring);
}
return offspring;
}
/**
* Second cross type, parents given in same order as first, but reverses internal workings
*/
private Chromosome cross2(Chromosome parent1, Chromosome parent2){
String bitS1 = parent1.getBitString();
String bitS2 = parent2.getBitString();
int length = bitS1.length();
int num = (int)(Math.random()*length); // number from 0 to length-1
String newBitString = bitS2.substring(0, num) + bitS1.substring(num, length);
Chromosome offspring = new Chromosome();
offspring.setBitString(newBitString);
if(shouldMutate()){
mutate(offspring);
}
return offspring;
}
/**
* Returns a boolean of whether a character should mutate based on the mutation value at top
*/
private boolean shouldMutate(){
double num = Math.random()*100;
return (num <= MUTATE);
}
/**
* Returns a boolean of whether a character should mutate based on the mutation value at top
*/
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);
}
/**
* Flips bits in a string 1 to 0, 0 to 1
*/
private String flip(String s){
return s.equals("0")? "1":"0";
}
}
import java.lang.Comparable;
import java.math.*;
/**
* Modified from a file created on Jul 9, 2003
* Unsure of original author
*
*/
public class Chromosome implements Comparable
{
protected String bitString;
/**
* Constructor for objects of class Chromosome
*/
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 double getFitness()
{
String working = bitString;
int x1 = Integer.parseInt(working.substring(0,6),2);
int x2 = Integer.parseInt(working.substring(6),2);
double result = ScratchGA.functionTest(x1,x2);
double percentDiff = ((ScratchGA.getDesired() - result)/ScratchGA.getDesired())*100;
if (percentDiff >= 0)
{
return percentDiff;
}
else
{
return -percentDiff;
}
}
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 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);
if(test.equals("1")){
sum = sum + 1;
}
}
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());
}
}
Actually, it was a simple error that eluded me, that I should have caught. The major issue was in using return (3*x)^(2*y); ^ is a bitwise XOR in java, but an exponent. (Whoops) The problem was rectified using Math.pow(3*x,2*y); ...and a little double check of the fitness function had it up and running with some other minor changes :)

Resources