So we have to implement Bresenhams line drawing algorithm as well as Cohen-Sutherland line clipping algorithm.

For some reason my whole program (9 classes, but only will include Line.java here) runs fine, but the output .xpm file contains a picture that is not what it's supposed to look like from the input .ps file. Some lines aren't appearing, some appear but are clipped wrong. I'm assuming it's a problem with my algorithms so I was wondering if I could get some feedback.

If you guys need to see more of my code let me know as I have it all.

[code=java]//
// Line class.
//
public class Line
{
// lines have two points that make them up
private Point _a;
private Point _b;

// for Cohen Sutherland clipping
private int RIGHT = 2;
private int TOP = 8;
private int BOTTOM = 4;
private int LEFT = 1;

/**
 * Constructor takes in two points.
 * 
 * @param Point a
 * @param Point b
 */
public Line(Point a, Point b)
{
    _a = a;
    _b = b;
}

/**
 * Getters and setters.
 */
public Point getFirstPoint()
{
    return _a;
}

public Point getSecondPoint()
{
    return _b;
}

public void setFirstPoint(Point a)
{
    _a = a;
}

public void setSecondPoint(Point b)
{
    _b = b;
}

public void displayLine()
{
    System.out.println(this.getFirstPoint().getX() + "," + this.getFirstPoint().getY());
    System.out.println(this.getSecondPoint().getX() + "," + this.getSecondPoint().getY());
}

/**
 * DDA Algorithm for drawing Lines
 * 
 * @param FrameBuffer pixelMap
 */
public void DDA(FrameBuffer pixelMap)
{ ...

So one of the problems I have been having with my programs is the length of time it takes to print out a pixel map into the XPM file.

I tested it with like :
500 rows and 2 columns -- 1 second
500 rows and 10 columns -- a few seconds
500 rows and 200 columns -- about 20 seconds

When I try and output the full 500x500 grid after about 4 minutes it's still not done.

Here is the only method I have been using to do this, maybe there is a more efficient way of doing it that I don't know about?

[code=java]public void addRowsToGrid()
{
String allRows = "";

    for(int i = 0;i < 500; i++) {
        allRows += "\"";
        for(int j = 0;j < 500; j++) {
            allRows += grid[i][j].getColor();
        }
        if (i != 499) {allRows += "\",\n";}
        else if (i == 499) {allRows += "\"\n";}
    }
    allRows += "};\n";

    XPM += allRows;
}[/code]

Can I get some feedback?

So I have a lot of code so I guess I'll just post the couple classes that seem to be giving me problems and where the problem is occuring.

[CODE=java]// line class to store lines from .ps file
class line {

// for outcodes
private int RIGHT = 2;
private int TOP = 8;
private int LEFT = 1;
private int BOTTOM = 4;

// two points signify each line
private point point0;
private point point1;

public line(point _point1, point _point2) {
    point0 = _point1;
    point1 = _point2;
}
public void setPoint1(point _new) {
    point0 = _new;
}

public void setPoint2 (point _another) {
    point1 = _another;
}

public point getPoint1() {
    return point0;
}

public point getPoint2() {
    return point1;
}

public float getSlope() {
    int rise = point0.getY() - point1.getY();
    int run = point0.getX() - point1.getX();

    float slope = rise/run;
    return slope;
}

// only for drawing
// AFTER clipping
public void DDA(xpm _file) {
    int x1 = this.getPoint1().getX();
    int y1 = this.getPoint1().getY();
    int x2 = this.getPoint2().getX();
    int y2 = this.getPoint2().getY();

    double m = (double)(y2-y1)/(x2-x1);
    double y = (double)y1;
    int iy;
    for (int x = x1 ; x <= x2 ; x++) {
        iy = (int)Math.round(y);
        setPixel(x, iy, _file);
        y += m;
    }
}

// actually setting the correct pixel in .XPM
private void setPixel(int x, int iy, xpm _file) {
    _file.pixels[x][iy].setValue("b");
}

// getting the codes for the inputted lines
// find out where to clip them
public int ComputeOutCode (int x, int y, int xmin, int ...

[QUOTE=VernonDozier;947033]I assume you have no messages like this:[/QUOTE]

nope no errors it just doesnt change

ok I had a seperate main class that just ran my gui(). would that have anything to do with it?

[QUOTE=VernonDozier;946983]It DOES change to three stars when you pull down the combo box and change it (I downloaded some PNG files. I assume GIF would work too). Your code is sort of hard to follow due to rating being a local variable of type int and also a JLabel or something somewhere else. And you also have a JLabel called ratingImage, where you do a switch on rating in actionPerformed. So some more descriptive variable names would be helpful. It's pretty confusing looking at a switch statement based on [ICODE]rating[/ICODE] when I thought rating was a JLabel. That said, I don't think you are INITIALIZING any JLabels to contain stars, so they don't until you do the drop-down. I did have to RESIZE the frame in order to see the stars, but my PNG's were pretty big.

Also, I had to add a main () function.[/QUOTE]

yours changes? lol mine doesn't i dont know what you are doing differently,

[QUOTE=llemes4011;946228]? You only have one recipe entered. It won't change because there's nothing to change it to! Code in another recipe, with a different rating, and try then.[/QUOTE]

But that one recipe that is in there has a rating of 3/5 stars. The initial rating picture the label uses is the 0/5 stars one. Shouldn't it load with the 3/5 stars picture from that code? Even if I go into the drop down list again, and click the same recipe, it should load the 3/5 stars picture shouldn't it?

So I have a JComboBox, which contains recipe names. I want, when the recipe name is changed, for the label that is an icon of the rating (1 to 5) stars, based on my recipe object, to change as well.

My code seems like it should work perfect but it doesn't. Any help please?

[code=java]
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.WindowConstants;

// GUI Class
// Will contain all the code that will display my GUI
// Will use the recipe class.

public class gui {

recipe test = new recipe(); 

DefaultComboBoxModel recipeNames = new DefaultComboBoxModel();
ArrayList<recipe> recipes = new ArrayList<recipe>();
ArrayList<String> recipeNamesArray = new ArrayList<String>();

ImageIcon stars0 = createImageIcon("amazonstar0C.gif");
ImageIcon stars1 = createImageIcon("amazonstar1C.gif");
ImageIcon stars2 = createImageIcon("amazonstar2C.gif");
ImageIcon stars3 = createImageIcon("amazonstar3C.gif");
ImageIcon stars4 = createImageIcon("amazonstar4C.gif");
ImageIcon stars5 = createImageIcon("amazonstar5C.gif");

JLabel ratingImage = new JLabel();
JComboBox recipeList = new JComboBox(recipeNames);

// Constructor will initialize everything.
public gui() {

test.setName("test");
test.setRating(3);
test.addIngredient("1/4 cup milk");
test.addDirection("Get milk.");
test.setNote("testNote");
test.setPeople(4);
test.setTime("00:01");

recipes.add(test);
recipeNamesArray.add(test.getName());
recipeNames.addElement(test.getName());

// The main JFrame that will hold my whole GUI.
JFrame main = new JFrame("E-Chef");

// The main tabbed pane that will run my program.
// Everything is done from this.
JTabbedPane menu = new JTabbedPane();

// All 3 panels for each tab.
JPanel mainMenu = new JPanel();
mainMenu.setLayout(new BoxLayout(mainMenu, BoxLayout.X_AXIS));

JPanel add = new JPanel();
JPanel search = new JPanel();

// All 3 tabbed icons.
ImageIcon icon1 = createImageIcon("menucooking.png");
ImageIcon icon2 ...

hey guys. OK so, I've been wondering this for a while now. my code is always so unnecessarily cluttered because I don't know how to do this, lol.

say I have a set of private class variables:

[code=java]
private ArrayList row0 = new ArrayList<String>();
private ArrayList row1 = new ArrayList<String>();
// etc. all the way to 7 in this case
[/code]

Now i have a loop where i want to assign (for example), 8 periods or something to each array list as separate elements. I don't want to do this same code and repeat it 8 times for each list, like this:

[code=java]
for (int i = 0; i < 7; i++) {
row0.add(".");
row1.add(".");
// etc.
}
[/code]

instead I would like to be able do something like this....

[code=java]
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 7; j++) {
rowi.add(".");
}
}
[/code]

how do I substitute that "i" in there though?

So I have my text files saving perfectly from my program in the exact way I want them to. Here is a copy of the text file that my program saves that I am now trying to load back in, parse, and set up internally as another object:

[CODE]scott-survey
m/c
mctext
a.b.c.d.

essay
write about me

[/CODE]
This is just one of the samples.

Here is the code that is supposed to take in this text file and set it all up internally. When I run the code, it recognizes that the text file exists and the directory it is in, but when it goes through all the loading code I have, it seems to just return a blank survey, like it doesn't load anything right. No errors, just doesn't work right. Why?

Here is my loading code:

[code=java]
public survey loadSurvey(String fileName) throws SecurityException, IOException {

    survey loadedSurvey = new survey();

// all the code for reading and parsing .txt file and setting up survey (loading)
System.out.println("What directory is your file in? ");
String whatDir;
BufferedReader readWhatDir = new BufferedReader(new InputStreamReader(System.in));
whatDir = readWhatDir.readLine();

    File file = null;
    FileReader freader = null;
    LineNumberReader lnreader = null;

    try{
        file = new File(whatDir + fileName + ".txt");
        freader = new FileReader(file);
        lnreader = new LineNumberReader(freader);
        String line = "";
        while ((line = lnreader.readLine()) != null) {

          if (lnreader.getLineNumber() == 0) {
              loadedSurvey.setName(line);
          }
          else {
              if ((line.equals("m/c"))) {
                  mc newMC = new mc();
                  String text = lnreader.readLine();
                  newMC.setQuesText(text);
                  String lchoices = ...

So I have this function that is supposed to output an object (save an object) to a .txt file. It doesn't output anything when the program comes to the point where it runs this function. I am 99% sure this is where the program hangs.

[code=java]
public void saveSurvey(String txtFile) throws SecurityException, IOException {
// creates a .txt file of a survey
// .txt file will have name on first line
// then from then on it will have type of question, followed by question text and then choices (if any)
// then the answer
// have to have type there because reader has to know if line determines next question or still choices, etc.

    // first create a writer output
    Writer output = null;

    // this is the actual text that will be written to the .txt file
    String text = this.name + "\n";

    for (int i = 0; i < this.numQues(); i++) {
        if (this.getQues(i).getType().equals("m/c") || this.getQues(i).getType().equals("t/f")
                || this.getQues(i).getType().equals("matching") || this.getQues(i).getType().equals("ranking")) {
            text += this.getQues(i).getType() + "\n";
            text += this.getQues(i).getQuesText() + "\n";
            text += this.getQues(i).getLeftChoices() + "\n";
            text += this.getQues(i).getRightChoices() + "\n";
            text += this.getQues(i).getUserAns() + "\n";
        }
        else {
            text += this.getQues(i).getType() + "\n";
            text += this.getQues(i).getQuesText() + "\n";
            text += this.getQues(i).getUserAns() + "\n";
        }
    }
    File saveFile = new File(txtFile + ".txt");
    output = new BufferedWriter(new FileWriter(saveFile));
    output.write(text);
    output.close();     
}[/code]

The alternate constructor to the survey class calls upon a text file name and loads that .txt file (that should be in the format above), into ...

ok so i want to read a .txt file line by line. I have the code for that BUT i want to keep track of what line im on, i might be completely braindead from working on this whole project forever but heres the line by line code i am using.

[code=java]
// all the code for reading and parsing .txt file and setting up survey (loading)
File file = new File(txtFile + ".txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;

    try {
      fis = new FileInputStream(file);

      // Here BufferedInputStream is added for fast reading.
      bis = new BufferedInputStream(fis);
      dis = new DataInputStream(bis);

      // dis.available() returns 0 if the file does not have more lines.
      while (dis.available() != 0) {

      // this statement reads the line from the file and parses them
      dis.readLine();

      }

      // dispose all the resources after using them.
      fis.close();
      bis.close();
      dis.close();

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

[/code]

is there a way I can keep a line counter because like the way my program is set up, certain lines mean different things to me. I need to use conditions on a lot of the lines, some depending on the number of the line and some depending on what a key word of a line says.

Thank you.

[code=python]

!/usr/bin/python

import os.path

n = 10
allPositions = []
state = []
blackPairCap = 0
whitePairCap = 0
blackInaRow = 0
whiteInaRow = 0

row0 = []
row1 = []
row2 = []
row3 = []
row4 = []
row5 = []
row6 = []
row7 = []
row8 = []
row9 = []

allDirections = [[-1, 0],[1, 0],[0, -1],[0, 1],[-1, -1],[-1, 1],[1, -1],[1, 1]]

def displayBoard(playersTurn):
print ""
print " 0 1 2 3 4 5 6 7 8 9 "
print " +--+--+--+--+--+--+--+--+--+--+--+"

------------------------------------------------
print "0" + " |  " + str(row0[0]) + "  " + str(row0[1]) + "  " + str(row0[2]) + "  " + str(row0[3]) + "  " + str(row0[4]) + "  " + str(row0[5]) + "  " + str(row0[6]) + "  " + str(row0[7]) + "  " + str(row0[8]) + "  " + str(row0[9]) + "  " + "|"
print "1" + " |  " + str(row1[0]) + "  " + str(row1[1]) + "  " + str(row1[2]) + "  " + str(row1[3]) + "  " + str(row1[4]) + "  " + str(row1[5]) + "  " + str(row1[6]) + "  " + str(row1[7]) + "  " + str(row1[8]) + "  " + str(row1[9]) + "  " + "|"
print "2" + " |  " + str(row2[0]) + "  " + str(row2[1]) + "  " + str(row2[2]) + "  " + str(row2[3]) + "  " + str(row2[4]) + "  " + str(row2[5]) + "  " + str(row2[6]) + "  " + str(row2[7]) + "  " + ...

I did that and now there's another error in line 102 (lines switched around cuz I kinda reformatted the whole thing). Ugh I hate these elif errors!

[code=python]

!/usr/bin/python

import os.path

nxn board, in this case n = 10

n = 10

will hold the positions similar to n-queens

allPositions = []

current state of board used for comparisons

state = []

defining captured and inaRow

blackPairCap = 0

whitePairCap = 0

blackInaRow = 0

whiteInaRow = 0

the initial state of the board is all blank
im storing each row of the board as a list
this is pretty much only for displaying the board

row0 = []

row1 = []

row2 = []

row3 = []

row4 = []

row5 = []

row6 = []

row7 = []

row8 = []

row9 = []

similar to the n-queens problem,
i'll make an allDirections list so i can test later for things such as
if it's next to another piece of itself or the opponent

allDirections = [[-1, 0],[1, 0],[0, -1],[0, 1],[-1, -1],[-1, 1],[1, -1],[1, 1]]

creating all rules without precond or anything

def createPositions():

for i in range(0,n):

    for j in range(0,n):

        allPositions.append([i,j])
winner

def winner():

if (blackPairCap == 5):

    print "White is the winner!"

    return True

elif (whitePairCap == 5):

    print "Black is the winner!"

    return True

elif (blackInaRow >= 5):

    print "Black is the winner!"

    return True

elif (whiteInaRow >= 5):

    print "White is the winner!"

    return True

else:

    inGameMenu()
for next function

player1 = "" ...

Ok I restructured things around a little bit and that first elif error went away but now I have another one!!!

[code=python]

!/usr/bin/python

import os.path

nxn board, in this case n = 10

n = 10

will hold the positions similar to n-queens

allPositions = []

current state of board used for comparisons

state = []

defining captured and inaRow

blackPairCap = 0
whitePairCap = 0
blackInaRow = 0
whiteInaRow = 0

the initial state of the board is all blank
im storing each row of the board as a list
this is pretty much only for displaying the board

row0 = []
row1 = []
row2 = []
row3 = []
row4 = []
row5 = []
row6 = []
row7 = []
row8 = []
row9 = []

similar to the n-queens problem,
i'll make an allDirections list so i can test later for things such as
if it's next to another piece of itself or the opponent

allDirections = [[-1, 0],[1, 0],[0, -1],[0, 1],[-1, -1],[-1, 1],[1, -1],[1, 1]]

creating all rules without precond or anything

def createPositions():
for i in range(0,n):
for j in range(0,n):
allPositions.append([i,j])

winner

def winner():
if (blackPairCap == 5):
print "White is the winner!"
return True
elif (whitePairCap == 5):
print "Black is the winner!"
return True
elif (blackInaRow >= 5):
print "Black is the winner!"
return True
elif (whiteInaRow >= 5):
print "White is the winner!"
return True
else:
inGameMenu()

for next function

player1 = ""
player2 = ""
comp1 = "" ...

It keeps giving me this elif syntax error in line 103 and I have NO idea where it's coming from. UGH!!!

[code=python]

!/usr/bin/python

import os.path

nxn board, in this case n = 10

n = 10

will hold the positions similar to n-queens

allPositions = []

current state of board used for comparisons

state = []

defining captured and inaRow

blackPairCap = 0
whitePairCap = 0
blackInaRow = 0
whiteInaRow = 0

the initial state of the board is all blank
im storing each row of the board as a list
this is pretty much only for displaying the board

row0 = []
row1 = []
row2 = []
row3 = []
row4 = []
row5 = []
row6 = []
row7 = []
row8 = []
row9 = []

similar to the n-queens problem,
i'll make an allDirections list so i can test later for things such as
if it's next to another piece of itself or the opponent

allDirections = [[-1, 0],[1, 0],[0, -1],[0, 1],[-1, -1],[-1, 1],[1, -1],[1, 1]]

creating all rules without precond or anything

def createPositions():
for i in range(0,n):
for j in range(0,n):
allPositions.append([i,j])

winner

def winner():
if (blackPairCap == 5):
print "White is the winner!"
return True
elif (whitePairCap == 5):
print "Black is the winner!"
return True
elif (blackInaRow >= 5):
print "Black is the winner!"
return True
elif (whiteInaRow >= 5):
print "White is the winner!"
return True
else:
inGameMenu()

for next function

player1 = ""
player2 = ""
comp1 = "" ...

It keeps giving me this exception when it [I]seems[/I] like I am adding a choice to my choices vector, and I don't know why.

Here is that snippet of code. If you need more I can provide it.

Thanks ahead of time.

[CODE=java]import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;

public class multipleChoice extends question
{
public Vector<String> choices;

public multipleChoice()
{
    System.out.println("Please enter the text of your question: ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    try {
        String textIn = br.readLine();
        text = textIn;
        System.out.println("Please enter the answer of your question: ");
        BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
        try {
            String AnsIn = br.readLine();
            answer = AnsIn;
            BufferedReader inStream = new BufferedReader (
                    new InputStreamReader(System.in)
                );
                    System.out.println("Enter the number of choices: ");
                    String inLine = inStream.readLine();
                    int numChoices = Integer.parseInt(inLine);
                    for (int j = 0; j < numChoices - 1; j++) {
                        System.out.println("Please enter choice number " + (j + 1) + ": ");
                        BufferedReader br3 = new BufferedReader(new InputStreamReader(System.in));
                        try {
                            String choice= br.readLine();
                            choices.add(choice);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }   
                    }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}[/CODE]

Oh, and apparently my blocked function is not recursive? I thought it was, but it needs to be, so any help I'll take :) If not though that's fine too.

So here is my program:

[code=python]#!/usr/local/bin/python

Scott Landau
CS 380
Assignment 1 Programming Portion in Python
Created - 4/6/09
Last Edited - 4/22/09

import pdb

n is going to be equal to 4 for this queens problem.

n = 4

Assigning the empty list to initialState.

initialState = []

Making an allDirections list.

allDirections = [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]

declare the list 'state' which represents the number of non threatening
queens that have been placed on the board.

state = []

def goal(state):
if ((len(state)) == n):
return True
else:
return False

defining allRules list which the contents of which will be created in next function.

allRules = []

defining all the rules for an nxn board. assigning these rules to allRules

def makeRules(n):
for i in range(0, (n), 1):
for j in range(0, (n), 1):
allRules.append([i,j])
return

this function will apply the rule that is in the rule list to the given state, which just appends it to the state list.

def applyRule(rule,state):
state.append(rule)
return

returns true if the row or column of 'pos' is out of bounds.

def outOfBounds(pos):
if ((pos[0] < 0) or (pos[0] > (n-1)) or (pos[1] < 0) or (pos[1] > (n-1))):
return True
else:
return False

function that will determine which positions queens cannot be placed into because they might eventually run into another queen already on the board.

def blocked(pos,state,direction):
newpos = [(pos[0]+direction[0]),(pos[1]+direction[1])]
if newpos in state:
return True
elif outOfBounds(newpos):
return False
else:
return True
blocked(newpos,state,direction)

precondition to the actions checker

def precondition(rule,state):
for k ...

Honestly, this was an assignment. I would not have lied if someone asked that in the first place. I like this forum though because I always try my assignments to the best of my ability beforehand. And when they fail, I debug. And if that still doesn't work, I try it again. I did all these things before coming here. I also asked my TA as well, so it's not like he didn't know I was seeking help.

I would never have came here asking for an answer to a question that I didn't try. Whats the point of going to school if that's the case, I would just fail later on in life.

I thank you for all the help you guys gave me though. I took everything into consideration and created a better program out of it. I don't cheat.

[code]backTrack ( stateList )
    state = first element of stateList
     if state is a member of the rest of stateList, return 'FAILED-l 
     if deadEnd?(state) return 'FAILED-2
     if goal(state), return NULL
     if length(stateList) > depthBound, return 'FAILED-3

     ruleSet = applicableRules(state) 
     if ruleSet == NULL, return 'FAILED-4

     for each rule r in ruleSet,
      newState = applyRule(r,state) 
       newStateList = addToFront(newState,stateList) 
       path = backTrack(newStateList)
       if path != 'FAILED return append(path,r)

     return 'FAILED-5[/code]

So this is the backTrack algorithm I am working with. I need some help modifying it. I want it, instead of returning a solution path when found, to just print that it found one and keep going searching for other solution paths, then returning the last one that it finds, or FAILED if that was the only one it could find.

Any ideas? I have tried a lot of different things but I am stuck. By the way, this is pseudo code, so I have not done any formal testing but I just need some ideas.

How come this just hangs, after debugging I found it never returns True for precondition even though it should on the very first go around....ugh!!!

[code=python]#!/usr/local/bin/python

Scott Landau
CS 380
Assignment 1 Programming Portion in Python
Created - 4/6/09
Last Edited - 4/8/09

import pdb

n is going to be equal to 4 for this queens problem.

n = 4

Assigning the empty list to initialState.

initialState = []

Making an allDirections list.

allDirections = [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]

declare the list 'state' which represents the number of non threatening
queens that have been placed on the board.

state = []

def goal(state):
if ((len(state)) == n):
return True
else:
return False

defining allRules list which the contents of which will be created in next function.

allRules = []

defining all the rules for an nxn board. assigning these rules to allRules

def makeRules(n):
for i in range(0, (n), 1):
for j in range(0, (n), 1):
allRules.append([i,j])
return

this function will apply the rule that is in the rule list to the given state, which just appends it to the state list.

def applyRule(rule,state):
state.append(rule)
return

returns true if the row or column of 'pos' is out of bounds.

def outOfBounds(pos):
if ((pos[0] < 0) or (pos[0] > (n-1)) or (pos[1] < 0) or (pos[1] > (n-1))):
return True
else:
return False

function that will determine which positions queens cannot be placed into because they might eventually run into another queen already on the board.

def blocked(pos,state,direction):
newpos = [(pos[0]+direction[0]),(pos[1]+direction[1])]
if newpos in ...

I did test the code using print statements. I also debugged it and stepped through my while loop into functions hoping I would find the problem.

I know when the problem hits, just not exactly what it is. It comes when i am adding another coordinate to state. It adds the first one ([1,1]) fine, but then the blocked function and the precondition function should determine that the next one it runs through, which is [1,2], will eventually run into [1,1] through the direction [0,1], but it never does and it just adds this one to state anyway.

I know it's a problem with either my blocked() or precondition() functions, I just don't know which one and what the problem is.

[code=python]#!/usr/local/bin/python

Scott Landau
CS 380
Assignment 1 Programming Portion in Python
Created - 4/6/09
Last Edited - 4/7/09
n is going to be equal to 4 for this queens problem.

n = 4

Assigning the empty list to initialState.

initialState = []

Making an allDirections list.

allDirections = [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]

declare the list 'state' which represents the number of non threatening
queens that have been placed on the board.

state = []

def goal(state):
if ((len(state)) == n):
print "true"
return True
else:
print "false"
return False

defining allRules list which the contents of which will be created in next function.

allRules = []

defining all the rules for an nxn board. assigning these rules to allRules

def makeRules(n):
for i in range(1, (n+1), 1):
for j in range(1, (n+1), 1):
allRules.append([i,j])
return

making a rule list. this list will probably be refined in future assignments but it will contain the one rule that is applicable in the current state. for #now we will just make it an empty list.

rule = []

this function will apply the rule that is in the rule list to the given state, which just appends it to the state list.

def applyRule(rule,state):
state.append(rule)
return

returns true if the row or column of 'pos' is out of bounds.

def outOfBounds(pos):
if ((pos[0] < 1) or (pos[0] > n) or (pos[1] < 1) or (pos[1] > n)):
print "true"
return True
else:
print "false"
return False

function that will determine which positions queens cannot be placed ...

[code=python]#!/usr/local/bin/python

Scott Landau
CS 380
Assignment 1 Programming Portion in Python
Created - 4/6/09
Last Edited - 4/7/09
n is going to be equal to 4 for this queens problem.

n = 4

Assigning the empty list to initialState.

initialState = []

Making an allDirections list.

allDirections = [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]

declare the list 'state' which represents the number of non threatening
queens that have been placed on the board.

state = []

def goal(state):
if (len(state) == n):
return True
else:
return False

defining allRules list which the contents of which will be created in next function.

allRules = []

defining all the rules for an nxn board. assigning these rules to allRules

def makeRules(n):
for i in range(1, (n+1), 1):
for j in range(1, (n+1), 1):
allRules.append([i,j])
return

making a rule list. this list will probably be refined in future assignments but it will contain the one rule that is applicable in the current state. for #now we will just make it an empty list.

rule = []

this function will apply the rule that is in the rule list to the given state, which just appends it to the state list.

def applyRule(rule,state):
state.append(rule)
return

returns true if the row or column of 'pos' is out of bounds.

def outOfBounds(pos):
if ((pos[0] < 1) or (pos[0] > n) or (pos[1] < 1) or (pos[1] > n)):
return True
else:
return False

function that will determine which positions queens cannot be placed into because they might eventually run into another ...

[QUOTE=nmaillet;749740]The problem is with line 203. You're trying the assign the value of [icode]newAccount[/icode] to memory outside the bounds of the vector's array. Use [icode]account_Names.push_back(newAccount)[/icode] instead, and it should reallocate the memory for you.

Nick[/QUOTE]

Thank you so much that fixed it. I have one more question though. The loop after that section where I am writing to the file. When the program finishes, and I looked at the file, it has one line with just the first line of the original file in it. From the program you can probably see what I want it to do, which is just append pretty much one more line of info to the file, even though the way I have it set up to do it is rewrite the whole thing line by line.

Any help on this?

[CODE=C++]#include <iostream>

include <fstream>
include <vector>
include <string>
include <sstream>
include <stdio.h>
include <time.h>

using namespace std;

bool StringToInt(const string &s, int &i);

int main()
{

// opening up and setting up the input file stream so we can read it
// to perform the "account info" and the "history" parts of the program.
// the inserting part will be done later.
ifstream logFileIn;
logFileIn.open("logfile.txt");

// store each line of the logfile into an array where each element
// of the array is each line of the text file.
vector<string> each_Line;
ifstream ifs( "logfile.txt" );
string temp;
while( getline( ifs, temp ) )
{
    each_Line.push_back( temp );
}

//closing file so we can open later to write to it
logFileIn.close();

int numLines = each_Line.size();

// storing the account holders # in another array and then removing
// dupes.
vector<string> account_Numbers(numLines);
int i;
for (i=0;i<numLines-1;i++)
{
    account_Numbers[i] = each_Line[i].substr(0,4);
}

// storing the peoples names in another array in the same positions
// as the previous array of their account #'s.
vector<string> account_Names(numLines);

int j;
for (j=0;j<numLines-1;j++)
{
    account_Names[j] = each_Line[j].erase(0,5);
    int colonPos = account_Names[j].find(":",0);
    account_Names[j] = account_Names[j].substr(0,colonPos);
}

// now doing the same thing with a date array.
vector<string> account_Dates(numLines);

for (int k=0;k<numLines-1;k++)
{
    account_Dates[k] = each_Line[k].erase(0,5);
    int colonPos2 = account_Dates[k].find(":",0);
    account_Dates[k] = account_Dates[k].substr(colonPos2+1,8);
}   

// once again but for the type of transaction.
vector<string> account_Tran(numLines);

for (int l=0;l<numLines-1;l++)
{
    account_Tran[l] = each_Line[l];
    int colonPos3 = account_Tran[l].rfind(":",(account_Tran[l].length()-1));
    account_Tran[l] = account_Tran[l].substr(colonPos3-1,1);
}

// and finally an array for the amount.
vector<string> ...

[QUOTE=Salem;719819]Well yeah, you need a cross-compiler which runs on your machine AND outputs MIPS assembly.[/QUOTE]

Is there any place that has instructions for me to be able to set this up? I know running g++ on a MIPS platform would give me the code easy, but setting up a cross platform compiler seems very confusing without some sort of direction. Have you done this?