Simple hill climbing algorithm? [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm trying to use the Simple hill climbing algorithm to solve the travelling salesman problem. I want to create a Java program to do this. I know it's not the best one to use but I mainly want it to see the results and then compare the results with the following that I will also create:
Stochastic Hill Climber
Random Restart Hill Climber
Simulated Annealing.
Anyway back to the simple hill climbing algorithm I already have this:
import java.util.*;
public class HCSA
{
static private Random rand;
static public void main(String args[])
{
for(int i=0;i<10;++i) System.out.println(UR(3,4));
}
static public double UR(double a,double b)
{
if (rand == null)
{
rand = new Random();
rand.setSeed(System.nanoTime());
}
return((b-a)*rand.nextDouble()+a);
}
}
Is this all I need? Is this code even right..? I have a range of different datasets in text documents that I want the program to read from and then produce results.
Would really appreciate any help on this.
----- EDIT ----
I was being an idiot and opened the Java file straight into Eclipse when i should have opened it in notepad first.. here is the code i have now got.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.util.ArrayList;
{
//Print a 2D double array to the console Window
static public void PrintArray(double x[][])
{
for(int i=0;i<x.length;++i)
{
for(int j=0;j<x[i].length;++j)
{
System.out.print(x[i][j]);
System.out.print(" ");
}
System.out.println();
}
}
//reads in a text file and parses all of the numbers in it
//is for reading in a square 2D numeric array from a text file
//This code is not very good and can be improved!
//But it should work!!!
//'sep' is the separator between columns
static public double[][] ReadArrayFile(String filename,String sep)
{
double res[][] = null;
try
{
BufferedReader input = null;
input = new BufferedReader(new FileReader(filename));
String line = null;
int ncol = 0;
int nrow = 0;
while ((line = input.readLine()) != null)
{
++nrow;
String[] columns = line.split(sep);
ncol = Math.max(ncol,columns.length);
}
res = new double[nrow][ncol];
input = new BufferedReader(new FileReader(filename));
int i=0,j=0;
while ((line = input.readLine()) != null)
{
String[] columns = line.split(sep);
for(j=0;j<columns.length;++j)
{
res[i][j] = Double.parseDouble(columns[j]);
}
++i;
}
}
catch(Exception E)
{
System.out.println("+++ReadArrayFile: "+E.getMessage());
}
return(res);
}
//This method reads in a text file and parses all of the numbers in it
//This code is not very good and can be improved!
//But it should work!!!
//It takes in as input a string filename and returns an array list of Integers
static public ArrayList<Integer> ReadIntegerFile(String filename)
{
ArrayList<Integer> res = new ArrayList<Integer>();
Reader r;
try
{
r = new BufferedReader(new FileReader(filename));
StreamTokenizer stok = new StreamTokenizer(r);
stok.parseNumbers();
stok.nextToken();
while (stok.ttype != StreamTokenizer.TT_EOF)
{
if (stok.ttype == StreamTokenizer.TT_NUMBER)
{
res.add((int)(stok.nval));
}
stok.nextToken();
}
}
catch(Exception E)
{
System.out.println("+++ReadIntegerFile: "+E.getMessage());
}
return(res);
}
}

You can compare your results against the code repository for the textbook
"Artificial Intelligence a Modern Approach", here is the aima code repository.
Their hill climbing implementation is HillClimbingSearch.java

I'm not sure what the code you pasted has to do with Traveling Salesman. You have a function UR which generates a random number in the interval [a,b).

Related

Use integers from CSV file to initialize corresponding integers [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I'm working on a text based game to run out of the Command Prompt that simulates Decking in Shadowrun. Ideally, the player should be able to have a CSV file (65 rows, 2 columns) with all the character's pertinent information, and that information should be able to be uploaded into the program.
I am at the point where the csv file is properly loaded and displays everything correctly, while still in the loop. I cannot for the life of me figure out how to get the values out of the loop and into something that I can use to set the values of the various character stats. Snippets of my code are as follows:
public class Program {
static int[][] Character = new int[65][2];
public static void main (String[]args) {
Scanner user_input = new Scanner(System.in);
String DeckerName;
System.out.println("What is your name? (Name of your .csv file)"); //Load Decker character
DeckerName = user_input.nextLine();
System.out.println("Alright, " + DeckerName + ". Jacking into the Matrix now...");
String csvFile = "FILE LOCATION";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
Scanner loader = new Scanner(System.in);
//Opens and loads .csv file into an array
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String characterload[] = line.split(cvsSplitBy);
System.out.println ("" + characterload[0] + ": " + characterload[1]); // for testing purposes, characterload[0] is a text description, characterload[1] is an integer
int intDeckerProgram = Integer.parseInt(characterload[1]);
System.out.println(intDeckerProgram); //for testing purposes
for (int i = 0; i < characterload.length; i++)
{
Character[i][1] = intDeckerProgram;
System.out.println(Character[i][1]); //for testing purposes
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br!= null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
int DeckerDetectionFactor = Character[0][1];
System.out.println(Character[0][1]); //for testing purposes
System.out.println(DeckerDetectionFactor); //for testing purposes
int DeckerHackingPool = Character[1][1];
System.out.println(Character[1][1]); //for testing purposes
System.out.println(DeckerHackingPool); //for testing purposes
TL;DR without downloading other java packages, how can I bring the values imported into the characterload array, and put them into the Character array so that my integers are properly initialized? Thank you for your time, I truly appreciate it!
Edit: The two values at the bottom, DeckerDetectionFactor and DeckerHackingPool, need to be 6 and 9, respectively (this info being drawn from the CSV file). I am looking for a little direction on how to ensure these values are properly loaded into the Character[][] array so the variables are initialized properly instead of being put at 0.
After some helpful advice as given, I ended up removing the inner For loop from the While loop. Setting up a row integer followed by incrementing that solved the whole issue. If it helps anyone, here is the code I am using now:
...
br = new BufferedReader(new FileReader(csvFile));
int row = 0;
while ((line = br.readLine()) != null) {
String characterload[] = line.split(cvsSplitBy);
int intDeckerProgram = Integer.parseInt(characterload[1]);
Character[row][1] = intDeckerProgram;
row++;
}
...

BufferedReader sometimes read text, sometimes doesn't

I'm trying to read from a .java the methods I have on it, also the classes, I'm using taggs to identify them and stored them, the problem is that using BufferedReader sometimes just doesn't work, the buffer skips a lot of lines for a reason that I can't understand, sometimes when checking the file by myself I just put random spaces between lines, and that fixes some parts, but I can't get the Buffer read all my text without skipping anything, my code so far is like this:
public class ReadFile {
public static void main(String[] args) {
int numclas=0,numbase=0,numbaseagr=0,numbmet=0,numag=0;
String mt="//MT";
String[] nomclass2 = new String[10];
String[] nommetodo2 = new String[50];
boolean metodo=false;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("\\Program.java"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] splited = read.trim().split("\\s+");
for(int i=0;i<splited.length;i++){
System.out.println(splited[i]);
if(splited[i].equals("class")){
nomclass2[numclas]=splited[i+1];
numclas=numclas+1;
}
if (splited[i].equals(mt)){
metodo=true;
}
if (splited[i].equals("public")){
if (splited[i+1].equals("static")){
nommetodo2[numbmet]=splited[i+3];
numbmet=numbmet+1;
}
if (splited[i+1].equals("int")||splited[i+1].equals("double")||splited[i+1].equals("String")||splited[i+1].equals("boolean")){
nommetodo2[numbmet]=splited[i+2];
numbmet=numbmet+1;
}
if (splited[i].equals("int")||splited[i].equals("double")||splited[i].equals("String")||splited[i].equals("boolean")){
nommetodo2[numbmet]=splited[i+1];
numbmet=numbmet+1;
}
metodo=false;
}
if ((splited[i].equals("int")||splited[i].equals("double")||splited[i].equals("String")||splited[i].equals("boolean"))&&metodo){
nommetodo2[numbmet]=splited[i+1];
numbmet=numbmet+1;
metodo=false;
}
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
Now let me show you the .java I'm trying to read:
import java.text.DecimalFormat;
import java.io.*;
//Main file of the program 1
public class Program1 {
//MT
public static void main (String args []) {
DecimalFormat format=new DecimalFormat("##.##");
System.out.println("How many data do you want to insert?");
int num=Leer.Int();
Fila lista=new Fila();
Fila lista2=new Fila();
double x=0.0;
for(int i=0;i<num;i++){
x=Leer.Double();
lista.addNum(x);
}
double prom=0.0;
double desv=0.0;
prom=lista.getprom();
desv=lista.getdevst();
System.out.println("The mean for column 1 is: "+format.format(prom));
System.out.println("The Std.Dev for column 1 is: "+format.format(desv));
System.out.println("How many data do you want to insert?");
num=Leer.Int();
x=0.0;
for(int i=0;i<num;i++) {
x=Leer.Double();
lista2.addNum(x);
}
prom=0.0;
desv=0.0;
prom=lista2.getprom();
desv=lista2.getdevst();
System.out.println("The mean for column 2 is: "+format.format(prom));
System.out.println("The Std.Dev for column 2 is: "+format.format(desv));
}
}
And the result when I print the array
Date:
12/12/12
import
java.text.DecimalFormat;
//Main
file
of
the
program
1
//MT
DecimalFormat
format=new
DecimalFormat("##.##");
so on...
See how in the //MT the Buffer skips a lot of lines, a lot of this is happening (see how it ignores the first lines of the program), and I don't know how to fix it, because sometimes when I try to "fix it" and add some spaces in the lines, I get a nullpointer and the program ends.
Any help will be appreciated, thank you.
This is just a partial answer - at the very least your program is skipping every other line:
while ((read = in.readLine()) != null)
will read a line from the file. The line is immediately discarded because the immediately following statement:
read = in.readLine();
reads and processes the next line from the file.
(also, 'splited' should be 'splitted' along with numerous other spelling mistakes but they're not really affecting your program, just it's readability :-))

Read a text file to an array Java

I know there are many questions about reading text files here but I have gone through all of them and I think I'm having some difficulty with syntax or SOMETHING because nothing that I've been trying has been working at all.
What I'm attempting to do is this:
1) read a text file inputed by user
2) copy each individual line into an array, so each line is its own element in the array
I feel like I am very close but for some reason I can't figure out exactly how to get it to work!
Here is the relevant code I have right now:
I keep getting out of bounds exceptions in three locations which I've marked off.
Been working on this for quite a while not sure what to do next! Any ideas?
import java.io.IOException;
import java.util.Scanner;
public class FindWords {
public static void main (String args[]) throws IOException{
FindWords d = new Dictionary();
((Dictionary) d).dictionary(); //********* out of bounds here
}
/**
* Validates and returns the dictionary inputed by the user.
*
* #param
* #return the location of the dictionary
*/
public static String getDict(){
///////////////////ASK FOR DICTIONARY////////////////////
System.out.println("Please input your dictionary file");
//initiate input scanner
Scanner in = new Scanner(System.in);
// input by user
String dictionary = in.nextLine();
System.out.println("Sys.print: " + dictionary);
//make sure there is a dictionary file
if (dictionary.length() == 0){
throw new IllegalArgumentException("You must enter a dictionary");
}
else return dictionary;
}
}
which calls on the class Dictionary:
import java.io.*;
public class Dictionary extends FindWords{
public void dictionary () throws IOException{
String dict = getDict();
String[] a = readFile(dict); //********** out of bounds here
int i = 0;
while(a[i] != null){
System.out.println(a[i]);
i++;
}
}
public static String[] readFile(String input) throws IOException{
//read file
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(input)));
System.out.println ();
int count = 0;
String[] array = new String[count];
try{
while (br.readLine() != null){
array[count] = br.readLine(); //********out of bounds here
count++;
}
br.close();
}
catch (IOException e){
}
return array;
}
}
Thank you for looking!
Edit: Just fyi: I have my .txt file in the parent project folder.
Have you tried this?:
List<String> lines = Files.readAllLines(Paths.get("/path/to/my/file.txt"));
and then transform your list to an array if you want:
String[] myLines = lines.toArray(new String[lines.size()]);
You start with an array size of zero...
int count = 0;
String[] array = new String[count];
Several issues here :
In Java, you can't expand arrays, i.e you have to know their length in advance when you instantiate them. Hence the ArrayOutOfBoundException. To make this easy, I suggest that you use an ArrayList instead.
In your while loop, you're making 2 calls to br.readLine(), so basically you're skipping one line out of 2.
You are initializing a zero-length array, hence the exception on the first iteration:
int count = 0;
String[] array = new String[count];
Since you probably don't know the expected size, work with a List instead:
List<String> list = new ArrayList<>();
String thisLine = null;
try{
while ((thisLine = br.readLine()) != null) {
list.add(thisLine);
}
}
You can get the total size afterwards by:
list.size();
Or even better, go with morganos solution and use Files.readAllLines().

How can I parse through a file for a string matching a generated string?

My bad for the title, I am usually not good at making those.
I have a programme that will generate all permutations of an inputted word and that is supposed to check to see if those are words (checks dictionary), and output the ones that are. Really I just need the last the part and I can not figure out how to parse through a file.
I took out what was there (now displaying the "String words =") because it really made thing worse (was an if statement). Right now, all it will do is output all permutations.
Edit: I should add that the try/catch was added in when I tried turning the file in a list (as opposed to the string format which it is currently in). So right now it does nothing.
One more thing: is it possible (well how, really) to get the permutations to display permutations with lesser characters than entered ? Sorry for the bad wording, like if I enter five characters, show all five character permutations, and four, and three, and two, and one.
import java.util.List;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import static java.lang.System.out;
public class Permutations
{
public static void main(String[] args) throws Exception
{
out.println("Enter anything to get permutations: ");
Scanner scan = new Scanner(System.in);
String io = scan.nextLine();
String str = io;
StringBuffer strBuf = new StringBuffer(str);
mutate(strBuf,str.length());
}
private static void mutate(StringBuffer str, int index)
{
try
{
String words = FileUtils.readFileToString(new File("wordsEn.txt"));
if(index <= 0)
{
out.println(str);
}
else
{
mutate(str, index - 1);
int currLoc = str.length()-index;
for (int i = currLoc + 1; i < str.length(); i++)
{
change(str, currLoc, i);
mutate(str, index - 1);
change(str, i, currLoc);
}
}
}
catch(IOException e)
{
out.println("Your search found no results");
}
}
private static void change(StringBuffer str, int loc1, int loc2)
{
char t1 = str.charAt(loc1);
str.setCharAt(loc1, str.charAt(loc2));
str.setCharAt(loc2, t1);
}
}
If each word in your file is actually on a different line, maybe you can try this:
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null)
{
... // check and print here
}
Or if you want to try something else, the Apache Commons IO library has something called LineIterator.
An Iterator over the lines in a Reader.
LineIterator holds a reference to an open Reader. When you have finished with the iterator you should close the reader to free internal resources. This can be done by closing the reader directly, or by calling the close() or closeQuietly(LineIterator) method on the iterator.
The recommended usage pattern is:
LineIterator it = FileUtils.lineIterator(file, "UTF-8");
try {
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
}
} finally {
it.close();
}

BufferedReader skip questions on a test/quiz

Alright, so I'm taking on this little personal project for my teacher (Not my Computer Science teacher) and I'm trying to make a test from a fairly large list of questions. So far I've been able to read in the first question, ask the answer, and tell if they're right or not. The only problem is, it repeats the same question over and over.
Sadly, I'm stumped as to how I can make the program check to see if the question has been answered or not. My initial thought was to take the line from the question file that says "QUESTION #", separate the number, parse it into an integer and somehow make the BufferedReader skip that question.
Here is the quizTest:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class quizTest {
public static void main (String[] args) throws IOException{
BufferedReader reader = null;
reader = new BufferedReader(new FileReader("C:/Users/Kevin/Desktop/eclipse/WorkspaceCompTIA.ActualTests.220-802.v2012-11-05.by.Caitto.txt/"));
String line, userAnswer;
int i = 0;
Scanner scan = new Scanner(System.in);
String questionNum = "";
String question = "", choiceA = "", choiceB = "", choiceC = "", choiceD = "", answer = "";
while((line = reader.readLine()) != null){
if(line.contains("?")){
question = line;
}
if(line.contains("A.")){
choiceA = line;
}
if(line.contains("B.")){
choiceB = line;
}
if(line.contains("C.")){
choiceC = line;
}
if(line.contains("D.")){
choiceD = line;
}
if(line.contains("Correct Answer: ")){
String[] a = line.split(": ");
answer = a[1];
}
}
while(i < 274){
quizClass run = new quizClass(i, question, choiceA, choiceB, choiceC, choiceD, answer);
System.out.print(questionNum);
System.out.println(run.getQuestion());
System.out.println();
System.out.println(run.getChoiceA());
System.out.println(run.getChoiceB());
System.out.println(run.getChoiceC());
System.out.println(run.getChoiceD());
System.out.println();
System.out.print("Your Answer: ");
System.out.println();
userAnswer = scan.next();
if(userAnswer.equalsIgnoreCase(answer)){
System.out.println("Correct!");
i++;
}
}
if(i == 274){
reader.close();
scan.close();
}
}
}
Here is quizClass:
public class quizClass {
private String question, answer, choiceA, choiceB, choiceC, choiceD;
private int questionNum;
public quizClass(int questionNum, String question, String choiceA, String choiceB, String choiceC, String choiceD, String answer){
this.question = question;
this.answer = answer;
this.choiceA = choiceA;
this.choiceB = choiceB;
this.choiceC = choiceC;
this.choiceD = choiceD;
}
public String getQuestion(){
return question;
}
public String getAnswer(){
return answer;
}
public String getChoiceA(){
return choiceA;
}
public String getChoiceB(){
return choiceB;
}
public String getChoiceC(){
return choiceC;
}
public String getChoiceD(){
return choiceD;
}
public int getQuestionNum(){
return questionNum;
}
}
And finally here is the format of the question file:
http://puu.sh/5nJhS.png
EDIT:
So after fiddling around with it, I've managed to get it working now(I'm sure there are better ways to go about it, but this way works, so I'm happy :P):
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class QuizTest {
public static void main (String[] args) throws IOException{
String question = "";
String choiceA = "";
String choiceB = "";
String choiceC = "";
String choiceD = "";
String answer = "";
String line;
String userAnswer;
int i = 0;
BufferedReader reader = null;
reader = new BufferedReader(new FileReader("C:/Users/Kevin/Desktop/eclipse/Workspace/CompTIA.ActualTests.220-802.v2012-11-05.by.Caitto.txt/"));
Scanner scan = new Scanner(System.in);
QuizClass run = new QuizClass(i, question, choiceA, choiceB, choiceC, choiceD, answer);
while((line = reader.readLine()) != null){
//Finds the question
if(line.contains("?")){
run.question = line;
System.out.println(run.getQuestion() + "\n");
}
//Finds answer "A"
if(line.contains("A.")){
run.choiceA = line;
System.out.println(run.getChoiceA());
}
//Finds answer "B"
if(line.contains("B.")){
run.choiceB = line;
System.out.println(run.getChoiceB());
}
//Finds answer "C"
if(line.contains("C.")){
run.choiceC = line;
System.out.println(run.getChoiceC());
}
//Finds answer "D"
if(line.contains("D.")){
run.choiceD = line;
System.out.println(run.getChoiceD() + "\n");
}
//Finds the correct answer for the question
if(line.contains("Correct Answer: ")){
String[] a = line.split(": ");
answer = a[1];
run.answer = answer;
System.out.print("Your Answer: ");
userAnswer = scan.next();
//Checks if the user's input matches the correct answer from the file
if(userAnswer.equalsIgnoreCase(answer)){
System.out.println("Correct!\n");
i++;
}
//Checks if the user's input doesn't match the correct answer from the file
else if (!userAnswer.equalsIgnoreCase(answer)) {
System.out.println("Wrong, the correct answer was: " + run.getAnswer());
i++;
}
}
}
if(i == 274){
reader.close();
scan.close();
}
}
}
You're reading in the whole file in your initial while loop and writing over your variables. So, to simplify, the program will read the line
A. NETSTAT
and set choiceA to "A. NETSTAT". It will then continue looping until it sees
A. Windows XP
and then update choiceA to be "A. Windows XP".
In the end, it will be like your program only read the last question.
How should you solve this? My first thought would be to encode your questions in XML, from which you load a set of questions. This is a less clunky solution but requires a bit more infrastructure.
If you want to stay with your current set up, you should have two loops: one outer loop the runs until your reach EOF, and an inner that loops until the "Correct Answer" line.
Extra tips/comments:
Add a toString() method QuizClass (note the standard Java naming scheme -- always captialize) like this:
public toString() {
System.out.print(questionNum);
System.out.println(question);
System.out.println();
System.out.println(choiceA);
System.out.println(choiceB);
System.out.println(choiceC);
System.out.println(choiceD);
System.out.println();
}
and then call it in main with
System.out.print(run);
answer variable in your QuizClass class does nothing. You instead use another variable, userAnswer, in the main class. Why?
What is 274? Don't use magic numbers that don't mean anything. There's probably a constant defined in the classes you are using that are more informative.
I see, your answer variable is declared all the way to the right in a long line of multiple variable declarations -- please don't do that. Whitespace is cheap, and so use it (but don't over-use it and sacrifice readability) -- give each variable its own line.
As for your problem, you have two while loops, in one, you read in your data, but discard it, and in the second you try to use the data, but can't since it's already been discarded.
To solve this, you could do it using only one while loop, not two. And in that while loop, read in your question data and act on it, and then loop to the next. If you must use two loops, then you'll need to first fill an ArrayList of quizClass (ArrayList<quizClass>) while reading in from the file, and then in the second loop, use a for loop, not a while loop (since you'll know the size of the ArrayList), and use the quizClass objects held in the ArrayList second loop to ask your questino and get your answers.

Categories