Open Side Menu Go to the Top
Register
Programming homework and newbie help thread Programming homework and newbie help thread

03-24-2015 , 08:46 PM
Should I just assume something will always screw up a small % of the time in asynchronous programming?
Programming homework and newbie help thread Quote
03-25-2015 , 01:31 AM
Quote:
Originally Posted by Anais
in other news, trying to overload the binary operator + as a member function and not sure how to go about it best.

For now, I've got:

Code:
className className::operator+(const className & r) const
{
	className temp(*this);
	temp.valOne += r.getvalOne();
	temp.valTwo += r.getvalTwo();
	return temp;
}
and I feel like this isn't right.

The interwebs tell me it should be more of the form like this:

Code:
class Cents
{
private:
    int m_nCents;
 
public:
    Cents(int nCents) { m_nCents = nCents; }
 
    // Overload cCents + int
    Cents operator+(int nCents);
 
    int GetCents() { return m_nCents; }
};
 
// note: this function is a member function!
Cents Cents::operator+(int nCents)
{t
    return Cents(m_nCents + nCents);
}
They both overload the + operator. The first function takes the a parameter of the same object and returns a new object with the sum of the calling object and parameter object.

The second takes a parameter of an integer, creates and return a new object with the nCents added.

Quote:
Originally Posted by Anais
aside from not knowing what the "{ m_nCents = nCents; }" in what I assume is the constructor means, I'm not fully sure what's going on in the function itself.

Is it calling the constructor and returning what it creates?
The { m_nCents = cents;} is the definition of the constructor. You probably are used to seeing this in the header

Code:
header
Cents(int);

cpp
Cents(int nCents)
{
  m_nCents = nCents;
}
Quote:
Originally Posted by Anais
Only stuff in our book is about overloading binary operators as friend functions.

*edit*

using the above format, I tried:

Code:
return className((*this).getBothValues() + r.getBothValues());
but that didn't work either

neither did setBothValues(); return *this;
I'm assuming because something about the const on the end of the function prototype
If this function prototype is a friend function, having a const at the end won't work. Because remember, a friend function is not a member function. Const at the end usually means "don't modify any member variables" but friend functions aren't member functions.

Hope that helps.
Programming homework and newbie help thread Quote
03-25-2015 , 08:20 AM
I assume that's why I had to copy the invoking instance, because of the const at the end preventing member variables of the invoking instance being modified.

I tried about five different ways of writing it, and the first way I have it is the only way that works/doesn't throw compile errors. Just gonna assume it's right then.

Not sure I get the utility of an overloaded + member function const, but what the hell. Book said we should friend functions with two parameters typically. I think.

Appreciate the clarification.
Programming homework and newbie help thread Quote
03-25-2015 , 09:56 AM
Quote:
Originally Posted by Craggoo
Should I just assume something will always screw up a small % of the time in asynchronous programming?
Explain what you mean by asynchronous programming. I'm pretty sure I know what you mean. If we're just talking software (software gracefully handling hardware malfunctions complicates the issue greatly), I would say you should not have that expectation.
Programming homework and newbie help thread Quote
03-25-2015 , 10:22 AM
Quote:
Originally Posted by Craggoo
Should I just assume something will always screw up a small % of the time in asynchronous programming?
http://en.wikipedia.org/wiki/Race_condition

If it screws up some small percentage of time in an asynchronous system and you don't know why, you probably have a bug, not that asynchronous systems always fail some percentage of time. It helps to force yourself to understand the root cause and fix it instead of treating the symptoms. Far too many programmers to respond to race conditions with "workarounds" like: "this fails when X happens before Y so let's just put a delay right here so that X never happens before Y" which can make those race conditions more devastating and difficult to reproduce.
Programming homework and newbie help thread Quote
03-25-2015 , 10:27 AM
Quote:
Originally Posted by Anais
Okay, don't mind me, i'm a complete idiot for the most part.
No this stuff is hard.


Quote:
in other news, trying to overload the binary operator + as a member function and not sure how to go about it best.

For now, I've got:

Code:
className className::operator+(const className & r) const
{
	className temp(*this);
	temp.valOne += r.getvalOne();
	temp.valTwo += r.getvalTwo();
	return className(temp);
}
I think that will work. The way to think about it is in terms of the left hand side of the equal and the right hand side of the equal sign. What happens on the right hand side usually involves something that is temporary (a=b++, post increment not so much I guess) used to replace something on the left hand side of the equal sign. Clearly overloading the + operator is happening on the right hand side of the equal sign and thus is temporary. This is why copy constructors are important. You are invoking the copy constructor with your creation of temp and your return.


Quote:
aside from not knowing what the "{ m_nCents = nCents; }" in what I assume is the constructor means
Yeah you can put it in your .h file, you put the entire class code, attributes, member signatures all in one file if you want.
Btw a class member with a signature of void foo() const; can modify attributes specified with the mutable keyword. To illustrate:

mutable int x;
int y;

If foo() modifies x the compiler will not complain. If foo() modifies y, the compiler will complain.
Programming homework and newbie help thread Quote
03-25-2015 , 10:58 AM
Oh, nice! Thanks!

We're finally getting into inheritance. Soooo excite! Really hoping we hit polymorphism this semester.
Programming homework and newbie help thread Quote
03-25-2015 , 04:20 PM
Quote:
Originally Posted by econophile
I'm working on a method that checks whether pieces are in the way of horizontal, vertical, or diagonal chess moves. (Other types of moves have another method). If the move is from square A to B, the method needs to look at each square between A and B. This is what I came up with as a first draft.

Code:
def clear_path(self):
    (x1, y1), (x2, y2) = self.coords
    (xmin, xmax), (ymin, ymax) = sorted([x1, x2]), sorted([y1, y2])
    if x1 == x2:
        for y in range(ymin + 1, ymax):
            square = board.notation((x1, y))
            if board.piece(square) != None:
                print 'Move is not allowed because there is a',
                print board.piece(square), 'in the way.'
                return False
    elif y1 == y2:
        for x in range(xmin + 1, xmax):
            square = board.notation((x, y1))
            if board.piece(square) != None:
                print 'Move is not allowed because there is a',
                print board.piece(square), 'in the way.'
                return False
    elif xmax - xmin == ymax - ymin:
        if x1 < x2:
            x_change = 1
        else:
            x_change = -1
        if y1 < y2:
            y_change = 1
        else:
            y_change = -1
        for i in range(xmax - xmin - 1):
            x1 += x_change
            y1 += y_change
            square = board.notation((x1, y1))
            if board.piece(square) != None:
                print 'Move is not allowed because there is a',
                print board.piece(square), 'in the way.'
                return False                
    return True
That looked pretty ugly, so I figured out how to generalize a single approach that would handle all three types of moves and ended up with:

Code:
def clear_path(self):
    (x1, y1), (x2, y2) = self.coords
    xdist, ydist = (x1 - x2), (y1 - y2)
    dist = max(abs(xdist), abs(ydist))
    x_change, y_change = xdist/dist , ydist/dist
    if x1 == x2 or y1 == y2 or abs(xdist) == abs(ydist):
        for d in range(dist - 1):
            x1 += x_change
            y1 += y_change
            square = board.notation((x1, y1))
            if board.piece(square) != None:
                    print 'Move is not allowed because there is a',
                    print board.piece(square), 'in the way.'
                    return False
    return True
It's a lot shorter, but it still doesn't seem very elegant.

I don't like how I'm basically entering formulas twice. I could write loops, but sometimes it seems like overkill to write a loop to just do one thing twice.

Also, instead of

x_change, y_change = xdist/dist, ydist/dist

I could write something like

x_change, y_change = [i/dist for i in (xdist, ydist)]

But that also seems silly.

Any advice? Should I break the method up into multiple functions? Use more loops?
Looking only at the second version, what are you assuming about the input your function will get? If the two squares are the same, you'll have a division by zero where x_change and y_change are computed. Also if the squares don't lie on the same diagonal, vertical, or horizontal line you're returning True, even though it's not a possible rook/bishop/queen move. Assuming the move is from (x1,y1) to (x2,y2), you're calculating the opposite of xdist, ydist and the line should be changed to this:
Code:
xdist, ydist = (x2 - x1), (y2 - y1)
Otherwise I think this works for determining if you have a clear path between the two squares. Given a piece of the right type on (x1,y1) and as long as (x2,y2) is either unoccupied or occupied by an enemy piece (and assuming the move didn't expose or leave your king in check), that's a legal move. That said, I wonder why you'd have this function at all. Any chess program is going to have a function that generates all legal moves, so instead of checking each possible move one by one, why not generate all legal moves and from there you'd just check whether this move appears on the move list?
Programming homework and newbie help thread Quote
03-25-2015 , 06:05 PM
Quote:
Originally Posted by JSLigon
Looking only at the second version, what are you assuming about the input your function will get? If the two squares are the same, you'll have a division by zero where x_change and y_change are computed. Also if the squares don't lie on the same diagonal, vertical, or horizontal line you're returning True, even though it's not a possible rook/bishop/queen move.
I have a separate method to check that the start and end squares are different, so that should prevent division by zero. I also plan to have another method that would check if the type of move is allowed for the piece, so that would rule moves that aren't horizontal, vertical or diagonal (except for knight moves).

Quote:
Assuming the move is from (x1,y1) to (x2,y2), you're calculating the opposite of xdist, ydist and the line should be changed to this:
Code:
xdist, ydist = (x2 - x1), (y2 - y1)
You're right -- it should be x2 - x1 and y2 - y1.

Quote:
Otherwise I think this works for determining if you have a clear path between the two squares. Given a piece of the right type on (x1,y1) and as long as (x2,y2) is either unoccupied or occupied by an enemy piece (and assuming the move didn't expose or leave your king in check), that's a legal move. That said, I wonder why you'd have this function at all. Any chess program is going to have a function that generates all legal moves, so instead of checking each possible move one by one, why not generate all legal moves and from there you'd just check whether this move appears on the move list?
That's a good question. The way I was thinking of doing it is.
  1. Test if input is valid (this would rule out moves like a2-z9)
  2. Test if start and end squares are different (this would rule out a2-a2)
  3. Test if start square contains one of the moving player's pieces
  4. Test if end square is empty or contains one of the other player's pieces
  5. Test if path for move is blocked (the method from my previous post)
  6. Test if move belongs to set of possible legal moves for the type of piece being moved (e.g., for a rook this would generate all other squares on the same rank or file, without regard to other piece positions)

The program will have to generate all legal moves for a given position to see if the king is in check or checkmate. But I haven't figured out a way to generate all legal moves without checking if the path is blocked.

I guess if you took a rook as an example, you could find legal moves by checking one square at a time in each direction and stopping when you get to an illegal move. But that seems like a different way of doign the same thing I'm doing here.
Programming homework and newbie help thread Quote
03-25-2015 , 08:31 PM
Quote:
Originally Posted by econophile
The program will have to generate all legal moves for a given position to see if the king is in check or checkmate. But I haven't figured out a way to generate all legal moves without checking if the path is blocked.

I guess if you took a rook as an example, you could find legal moves by checking one square at a time in each direction and stopping when you get to an illegal move. But that seems like a different way of doign the same thing I'm doing here.
Right but if you're generating moves along the way through every empty square along the path instead of just checking if the move to a particular square is legal, it's more efficient. For a rook you'd generate all possible moves from the rook's starting square by radiating out in each of four directions until you either encounter a piece of the opposite color, the same color, or the edge of the board. For every square you pass through, that move gets added to the move list (which you'll have to prune later to get rid of moves that exposed your king to check). Same for bishops except its four diagonals, and for the queen you go all eight directions. If you're only checking one potential move at a time, your program does redundant work passing through the squares in between.
Programming homework and newbie help thread Quote
03-26-2015 , 12:54 AM
Quote:
Originally Posted by econophile
Any advice? Should I break the method up into multiple functions? Use more loops?
Without going into specific refactoring routes, my general advice would be break the code up into multiple functions and/or use descriptive intermediate variables for the sake of readability. When you come back to this code in a month, you'll thank yourself for writing things like: (pseudocode)

Code:
def clear_path(path):
  for point in points_in_path(path):
    if not point.empty():
      return false
  return true

def points_in_path(path):
  move_type = get_move_type(path)
  if move_type == horizontal:
    // logic to build path for horizontal moves
    // etc
That will be much easier than trying to remember what these ranges of x1, xmax, x2-y2, etc. mean.

I tend to err on the side of creating too many methods rather than too few. If several lines of code are combining to do a certain thing, then abstract them out. It's much easier to read the outer method when it says 'Do a thing, do another thing, finally do the last thing, return a value' and then drill down into the components if necessary.
Programming homework and newbie help thread Quote
04-02-2015 , 05:36 AM
At work we have a certain fixed folder structure for projects. I often have to copy a certain part of the structure, but the folders and subfolders are numbered, so when I do that I have to manually change the numbering of each subfolder. For example there could be a folder “4.1 abc” that has subfolders “4.1.1 xyz”, “4.1.2 bla”, … and then subsequent subfolders (4.1.1.2.3. etc). If I copy that folder and rename it “4.2. def”, I would have to rename each subfolder down the tree manually.

I already did some googling for command prompt stuff (protected PC/network so downloading software for this is not an option) but have trouble getting REN / RENAME to work with wildcards for folders (ren “4.1.*” “4.2.*” does not work), even using /S and other options.

Ideally I’d have a batch file that does this automatically down the entire tree (so not just the direct subfolders of the actual folder), and that is simple enough to use/understand so that I could share it with colleagues who aren’t very IT-minded.

Any help appreciated, thanks in advance!
Programming homework and newbie help thread Quote
04-02-2015 , 09:08 AM
Quote:
Originally Posted by pablito_21
At work we have a certain fixed folder structure for projects. I often have to copy a certain part of the structure, but the folders and subfolders are numbered, so when I do that I have to manually change the numbering of each subfolder. For example there could be a folder “4.1 abc” that has subfolders “4.1.1 xyz”, “4.1.2 bla”, … and then subsequent subfolders (4.1.1.2.3. etc). If I copy that folder and rename it “4.2. def”, I would have to rename each subfolder down the tree manually.

I already did some googling for command prompt stuff (protected PC/network so downloading software for this is not an option) but have trouble getting REN / RENAME to work with wildcards for folders (ren “4.1.*” “4.2.*” does not work), even using /S and other options.

Ideally I’d have a batch file that does this automatically down the entire tree (so not just the direct subfolders of the actual folder), and that is simple enough to use/understand so that I could share it with colleagues who aren’t very IT-minded.

Any help appreciated, thanks in advance!
Managed to do this with a PowerShell script. It's very basic but does the job, and might be simple enough to share with colleagues.
Programming homework and newbie help thread Quote
04-08-2015 , 04:53 AM
Hi! quick haskell question

I was given this :
-- Type Definitions (Given)

type Var = String
type Z = Integer
type T = Bool
type State = Var -> Z

data Aexp = N Integer | V Var | Add Aexp Aexp | Mult Aexp Aexp | Sub Aexp Aexp deriving (Show)
data Bexp = TRUE | FALSE | Eq Aexp Aexp | Le Aexp Aexp | Neg Bexp | And Bexp Bexp deriving (Show)
data Stm = Ass Var Aexp | Skip | Comp Stm Stm | If Bexp Stm Stm | While Bexp Stm deriving (Show)

and i'm supposed to implement a function fv_Aexp which should take a Aexp as input and return a list of [Var] (takes in an arithmetic expression and returns all the free variables in it)

but i'm not sure now to do it this is what i'm trying to do:
fv_aexp :: Aexp -> [Var]
fv_aexp a =
if a.type == N then do return []
else if a.type == V then do return [a.Var]
else if a.type == Add then do return fv_aexp a.Aexp ++ fv_aexp a.Aexp
else if a.type == Mult then do return fv_aexp a.Aexp ++ fv_aexp a.Aexp
else if a.type == Sub then do return fv_aexp a.Aexp ++ fv_aexp a.Aexp

but obviously some of the syntax is wrong, can some one please point me to the right direction i'm completely new to haskell by the way so u may assume i am an idiot
Programming homework and newbie help thread Quote
04-08-2015 , 09:41 AM
okay after doing some research i arrived at this point:

fv_aexp :: Aexp -> [Var]
fv_aexp a = case a of
Integer -> return []
Var -> return [V]
Add -> return fv_aexp a.Aexp ++ fv_aexp a.Aexp
Mult -> return fv_aexp a.Aexp ++ fv_aexp a.Aexp
Sub -> return fv_aexp a.Aexp ++ fv_aexp a.Aexp

but its giving me errors
'Not in scope: data constructor Integer'
'Not in scope: data constructor Var'
'Not in scope: data constructor Aexp'

=(
Programming homework and newbie help thread Quote
04-08-2015 , 01:30 PM
The cases need to be constructors and not types. For instance

Code:
Integer -> return []
should actually be

Code:
N _ -> return []
Given that you're matching against an Aexp, your only options for the cases are N, V, Add, Mult, and Sub
Programming homework and newbie help thread Quote
04-09-2015 , 07:15 PM
the **** is function notation?

google leads me to believe it'd be something like

Code:
thing a = (b*c) + d;
would be

Code:
thing a = operator+(d, operator*(b,c));
is that, like, a thing?

pretty sure this was only mentioned once in class as a sort of throwaway "did you know" type comment
Programming homework and newbie help thread Quote
04-09-2015 , 10:24 PM
can some one please explain to me what this line does?

data Aexp = N Integer | V Var | Add Aexp Aexp | Mult Aexp Aexp | Sub Aexp Aexp deriving (Show)

so i define a new data type call Aexp and it can either be a integer, Var, Add, Mult and Sub?

and specifically for the add,sub and mult which consist of 2 Aexps, how do i access each of them? for example suppose if i input in 'x Add (y Sub 1)' i want the function to treat it as f(x) + f(y - 1) = f(x) + f(y)+f(-1) I know i'm supposed to define the function recursively, but i'm not sure of the exact syntax

haskell is just so different from all the languages i learned before =(
Programming homework and newbie help thread Quote
04-09-2015 , 11:40 PM
Quote:
Originally Posted by CyberShark93
can some one please explain to me what this line does?

data Aexp = N Integer | V Var | Add Aexp Aexp | Mult Aexp Aexp | Sub Aexp Aexp deriving (Show)

so i define a new data type call Aexp and it can either be a integer, Var, Add, Mult and Sub?

and specifically for the add,sub and mult which consist of 2 Aexps, how do i access each of them? for example suppose if i input in 'x Add (y Sub 1)' i want the function to treat it as f(x) + f(y - 1) = f(x) + f(y)+f(-1) I know i'm supposed to define the function recursively, but i'm not sure of the exact syntax

haskell is just so different from all the languages i learned before =(
okay to answer my own question data Aexp is a constructor for a new type Aexp

and i need to specify the type of input in my function definition
ie
fv_aexp :: Aexp -> [Var]
fv_aexp (N n) = []
fv_aexp (V v) = [v]
fv_aexp (Add a1 a2) = fv_aexp a1 ++ fv_aexp a2
fv_aexp (Mult a1 a2) = fv_aexp a1 ++ fv_aexp a2
fv_aexp (Sub a1 a2) = fv_aexp a1 ++ fv_aexp a2

now i just have to figure out how to handle duplicates in the list for example
i want fv_aexp (Add (V "x") (V "x")) to be ["x"] and not ["x", "x"] i'm not sure if i should check for duplicates at the end for Add Mult and Sub or is there a way do do it when the whole recursion ends
Programming homework and newbie help thread Quote
04-10-2015 , 03:06 AM
Basic Netbeans GUI question

Hi guys, Ive created a Jframe, added a JPanel, and overridden the paintComponent() method:

public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.black);
g.drawRect(100, 100, 100, 100);
}


However the constructor of the JPanel never seems to invoke the paintComponent() method:

public TablePanel() {
initComponents();
}



In all the examples I've found online paintComponent(g) seems to be invoke automatically from the constructor. Any idea what I'm doing wrong?

Thanks alot, been stuck on this over an hour and going crazy!
Programming homework and newbie help thread Quote
04-10-2015 , 10:28 AM
Hey guys, beein trying to learn coding conventions for java and read about that variable decleration should be as close to the first use as possible:

Code:
int a;
int b;
int c;
int i;

for (i = 0; i <=10; i++)
{
     a = 2 + i;
}

for (i = 0; i <=10; i++)
{
     b = 3 + i;
}

for (i = 0; i <=10; i++)
{
     c = 4 + i;
}
would be the current way I code, but I read that the right way to do it would be:

Code:
int a;
int i;

for (i = 0; i <=10; i++)
{
     a = 2 + i;
}

int b;

for (i = 0; i <=10; i++)
{
     b = 3 + i;
}

int c;

for (i = 0; i <=10; i++)
{
     c = 4 + i;
}
would be the correct way to do it?
Programming homework and newbie help thread Quote
04-10-2015 , 10:53 AM
whatever makes it most readable is the proper way to do, or whatever way your boss/professor says is the way you should do it.

I tend to like

Code:
int a, b, c, i;
to get them all out of the way, but i'm not 100% certain if java allows that. Probably does.
Programming homework and newbie help thread Quote
04-10-2015 , 12:11 PM
for(int i = 0; ; ) no reason to have i exist outside for loop and better readability imho.
Programming homework and newbie help thread Quote
04-10-2015 , 01:20 PM
i agree, but then he has to reinitialize 'i' as an int in each for loop

probably bad practice to do it the way he's doing it, but not the end of the world while starting out

****

I've decided our current professor is more obsessed with getting students to do what they want students to do, as opposed to learning or coming up with good solutions.

First test is take home program assignment, basically. We have to write a small program to make use of a couple of classes using composition. Problem is we have a lot of restrictions on what libraries we can use (basically none), and as written, a lot of what they want done returns wrong answers.

So yes, I can write a program to give inaccurate information, and I can probably do so on purpose. But why would I want to? (netflix chaos monkey aside)
Programming homework and newbie help thread Quote
04-10-2015 , 03:23 PM
Quote:
Originally Posted by CyberShark93
now i just have to figure out how to handle duplicates in the list for example
i want fv_aexp (Add (V "x") (V "x")) to be ["x"] and not ["x", "x"] i'm not sure if i should check for duplicates at the end for Add Mult and Sub or is there a way do do it when the whole recursion ends
Are you allowed to use standard library functions? Data.List.nub when the recursion ends would be most straightforward.
Programming homework and newbie help thread Quote

      
m