Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
nielsm
Jun 1, 2009



crazypenguin posted:

I'm not sure what the composite pattern is, so perhaps they're making you do something that makes things hard for no reason.

I think it literally just means "objects owning and containing other objects". The Pattern People want to have a name for literally everything. Actually, the "composite pattern" might be somewhat intended to be the antithesis to inheritance madness with deep class trees, but I don't see that really being relevant in this case.

Adbot
ADBOT LOVES YOU

hooah
Feb 6, 2006
WTF?

crazypenguin posted:

Flat hierarchy means everything should derive from Exp. Nothing deriving from other things that derive from Exp.

I'm not sure what the composite pattern is, so perhaps they're making you do something that makes things hard for no reason.

Composite is basically when you have a derived class that can be composed of other classes that derive from the same class. In this case, we have e.g. a Negation, which is derived from Expression. Negation can negate either a Variable/Literal or another Expression.

When you mentioned constants as a subclass of variables not making sense, then how would you deal with the literals ("true" and "false")?

quote:

Helper visitor is just another visitor, like the ones I suggested. If you haven't done enums, then writing the two I suggested that just return booleans works too.

I can sort of see where you're going with this, but let me see if I actually am: isConstant would check if something is a literal, and constantValue would return the value for that literal?

crazypenguin
Mar 9, 2005
nothing witty here, move along

quote:

When you mentioned constants as a subclass of variables not making sense, then how would you deal with the literals ("true" and "false")?
Depends on how you want to do it. I would have a True class and a False class each deriving from Exp. An alternative would be to have a Constant class with a boolean member. However you like, just prefer flat over subclasses.

quote:

I can sort of see where you're going with this, but let me see if I actually am: isConstant would check if something is a literal, and constantValue would return the value for that literal?
Yeah, and perhaps recursively. An AndExpr could be const if both its operands are const, for example.

hooah
Feb 6, 2006
WTF?

crazypenguin posted:

Depends on how you want to do it. I would have a True class and a False class each deriving from Exp. An alternative would be to have a Constant class with a boolean member. However you like, just prefer flat over subclasses.

I tried to figure out how to do your first suggestion, but couldn't make it work in my head. Your alternative sounds like what we had before we realized we needed something to handle unknowns. We had made Literal derive from Variable (which in turn derives from Exp) because after our SimplificationVisitor prints the simplified version, the main function asks for values to assign to the variables and then calls the visitor that evaluates the expression, so those two classes seemed like they'd be closely related. What are you suggesting we do with the Variable class? Does it not need to be closely related to Literal?

duck monster
Dec 15, 2004

Scaevolus posted:

It depends on how the expressions are represented.

Assuming you have a tree structure, and an expression like x AND (False AND y) could be constructed something like AndOp(Var("x"), AndOp(Literal(false), Var("y")), you could write a structural matching/replacement function, and then have all your axioms as data:

code:
Sometype patterns[][] = {
   { AndOp(Literal(false), Var("x")), 
     Literal(false) },
   { NotOp(AndOp(Var("x"), Var("y")), 
     OrOp(NotOp(Var("x")), NotOp(Var("y")) },
   ...
}

Why not use an S-Expression parser for this? Theres a number of decent implementations out on the net.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

duck monster posted:

Why not use an S-Expression parser for this? Theres a number of decent implementations out on the net.

That seems sort of overkill to avoid having to type some nested literals, no? His big problem isn't parsing, it's manipulating the resulting tree.

hooah
Feb 6, 2006
WTF?
I ended up keeping the class hierarchy the same and adding a "contents" member to Literal and Variable that has a string - the letter of the variable or the value of the literal (true/false). The SimplificationVisitor then maintains a stack of these strings, taking two off the top (for the binary expressions) and deciding if any simplification needs to be done with some if/then/else blocks.

Thanks for your help, guys.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Subjunctive posted:

That seems sort of overkill to avoid having to type some nested literals, no? His big problem isn't parsing, it's manipulating the resulting tree.

Pattern matching is a very common operation in Lisp-likes, and usually part of the parser.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Suspicious Dish posted:

Pattern matching is a very common operation in Lisp-likes, and usually part of the parser.

You can probably do his simplification stuff with template metaprogramming too, but I thought he was a little more constrained that that in terms of what he had to implement Visitor-wise for the assignment.

I've written optimizing compilers, but I don't think I've ever seen a parser do meaningful Boolean expression simplification; it's a lot easier to walk the resulting AST, and that lets you use constant propagation and CSE and such to do a more complete job. If I pulled in a s-expr processing library and it started "simplifying" the resulting tree for me, I would make unpleasant sounds. I guess if his syntax exactly matches Lisp, and he wants to hook the reader somehow, but...a lot of work to avoid typing some structure literals and a few pattern matches. :shobon:

Edit: yeah, he inherited an existing class hierarchy Expression representation, so transcoding through a Lisp parser seems unlikely to be a suitable approach. That said, "just use sexps"/"embed a Lisp" are underused approaches to problem solving for sure.

Subjunctive fucked around with this message at 04:36 on Mar 18, 2014

Boris Galerkin
Dec 17, 2011

I don't understand why I can't harass people online. Seriously, somebody please explain why I shouldn't be allowed to stalk others on social media!
I want to write a small program for myself that deals with financial math (decimals) and from what I understand I really shouldn't be using floats/doubles for this. I mean I'm not a bank so a couple cents of round off errors won't matter, but I'd like to Do It Right™. So two questions: are there any resources to read about doing math with decimals/finance and is there a commonly accepted library for this?

Nippashish
Nov 2, 2005

Let me see you dance!

Boris Galerkin posted:

I want to write a small program for myself that deals with financial math (decimals) and from what I understand I really shouldn't be using floats/doubles for this.

Literally the only place this is relevant is if you are processing transactions and your numbers represent actual values of currency that belong to someone. Even banks use floating point numbers for simulations/forecasting.

Zerf
Dec 17, 2004

I miss you, sandman

Nippashish posted:

Literally the only place this is relevant is if you are processing transactions and your numbers represent actual values of currency that belong to someone. Even banks use floating point numbers for simulations/forecasting.

Pretty much this. I used to work at a place which built a Matlab-like product(but it's sole use was to simulate economical models and generate reports) and we simply used doubles for everything. I was really surprised at first, but doubles can represent a lot of numbers exactly and should be sufficient for modeling most economical simulations. Real transactions, as mentioned, are a different beast though.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Nippashish posted:

Literally the only place this is relevant is if you are processing transactions and your numbers represent actual values of currency that belong to someone. Even banks use floating point numbers for simulations/forecasting.

Using double representation also means you really can't use == without epsilon ranges, which is often a source of annoying and hard-to-diagnose bugs. (C.f. the perennial 0.1 + 0.2 == 0.30000000000000004 confusion from JS programmers.) For a lot of stuff, including statistical analysis, there's enough "fuzz" to hide this stuff, but if you're dealing with a small number of inputs then it can be frustrating to manage and display correctly.

I'd grab a decimal-arithmetic library and let it do the hard work, personally.

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe
I'm trying to set up Netbeans 8.0 for C++, and have so far been able to make it work pretty well. Everything compiles like you'd expect. However, I have an issue with it not wanting to recognise member functions of the vector [class. I have the vector declared and initialised but when I type out the following line of code:

C++ code:
currentState = stateList.begin();
where currentstate is an iterator and stateList is a vector, I get an error on the begin() saying Netbeans is unable to resolve it as an identifier. Furthermore, when I remove the begin(), to see autocomplete options, it only shows vector constructors. The code compiles as expected, so I'm fairly sure it's a problem with Netbeans.

Is there an easy way to fix this?

E: If it's relevant, the standard I use is C++11, I use g++-4.8 to compile and code assistance has links to the relevant directories for g++-4.8.

E2: Apparently it works if I revert to gcc to version 4.6. Then I can't use C++11, though.

Joda fucked around with this message at 22:12 on Mar 19, 2014

hooah
Feb 6, 2006
WTF?
I'm working on a bipartate graph problem. I have a vector<vector<Vertex>>. Here's Vertex:
C++ code:
class Vertex{
public:
	Vertex(int i) : _visited(false), _label(i), _color(10) {};
	void setVisitedFalse(){ _visited = false; }
	void setVisitedTrue(){ _visited = true; }
	void setColor(int c){ _color = c; }
	int getLabel(){ return _label; }
	bool isVisited(){ return _visited; }
	int getColor() { return _color; }
protected:
	bool _visited;
	int _color;
	int _label;
};
I want to iterate over each Vertex in the inner vector except the first one. I tried using a for loop, but the condition needs to be a constant expression, so I can't say "go from 1 to [inner vector].size()". How else can I go about this?

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

hooah posted:

I want to iterate over each Vertex in the inner vector except the first one. I tried using a for loop, but the condition needs to be a constant expression, so I can't say "go from 1 to [inner vector].size()". How else can I go about this?

Go from [inner vector].size() backwards to 1? I may not be understanding the constraint correctly. Or go from begin()+1 to end(), which is more idiomatic I guess.

hooah
Feb 6, 2006
WTF?

Subjunctive posted:

Go from [inner vector].size() backwards to 1? I may not be understanding the constraint correctly. Or go from begin()+1 to end(), which is more idiomatic I guess.

I forgot I can use iterators in a for loop! Thanks.

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe
I'm having an issue with a vector of int vectors suddenly having an obscene size after trying to pass it through a couple of classes.

Here is the vector I'm creating in main, and how I pass it on to the class that needs it:

C++ code:
    std::vector< std::vector<int> > rules = std::vector< std::vector<int> >();
    std::vector<int> rule = {0,0,0,10000,0};
    
    rules.push_back(rule);
    
    std::cout << "Ruleset size in main(): " << rules.size() << std::endl;
    
    sm.addState(rules,move);
    sm.update(1,false);
Here is addState in StateMachine (which sm is an instance of)

C++ code:
void StateMachine::addState(std::vector< std::vector<int> > ruleSet, Move stateMove)
{
  std::cout << "Ruleset size in StateMachine::addState(): " << ruleSet.size() << std::endl;
    
  State newState(ruleSet, stateNumber, stateMove);
  stateList.push_back(&newState);
}
Here is the State constructor

C++ code:
State::State(std::vector< std::vector<int> > ruleSet, int& sMachineState, Move stateMove) {
  this->currentMachineState = sMachineState;
  this->ruleSet = ruleSet;
  startTime = (int) std::time(0);
  this->stateMove = stateMove;
  
  std::cout << "Ruleset size for Class in State constructor: " << this->ruleSet.size() << std::endl;
}
And finally here is the State update function (which is called from the StateMachine update function):

C++ code:
void State::update(int input, bool isJumping)
{
  std::cout << "Ruleset size in state::update(): " << ruleSet.size() << std::endl;
    
  int elapsedTime = (int) std::time(0) - startTime;
  
  for(auto iter = ruleSet.begin(); iter != ruleSet.end(); iter++) {
    
    if(input == iter->at(0) &&
      (int) isJumping == iter->at(1) &&
      elapsedTime > iter->at(2) &&
      elapsedTime < iter->at(3))
    {
        currentMachineState = iter->at(4);
    }
  }
}
Notice how I added debug statements to keep an eye on the size of my ruleset as it's passed down. This is the ouput I get:

code:
Ruleset size in main(): 1
Ruleset size in StateMachine::addState(): 1
Ruleset size for Class in State constructor: 1
Ruleset size in state::update(): 6148908827317490774

RUN FINISHED; Segmentation fault; real time: 0ms; user: 0ms; system: 0ms
Obviously I get a segmentation fault because it thinks my ruleset is much larger than it really is. As far as I can tell, the original ruleset from main is assigned properly in the State constructor, but for some reason when I access it in the update() function it suddenly has an absolutely obscene size (a size which varies greatly from run to run.)

Does anyone know how such an issue can occur and what steps I can take to debug it?

Joda fucked around with this message at 05:17 on Mar 21, 2014

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

Joda posted:

C++ code:
std::vector< std::vector<int> > rules = std::vector< std::vector<int> >();
This is equivalent to std::vector<std::vector<int>> rules;,

Joda posted:

C++ code:
void StateMachine::addState(std::vector< std::vector<int> > ruleSet, Move stateMove)
{
  std::cout << "Ruleset size in StateMachine::addState(): " << ruleSet.size() << std::endl;
    
  State newState(ruleSet, stateNumber, stateMove);
  stateList.push_back(&newState);
}
This is adding a pointer to an object on the stack to stateList. That object ceases to exist once you return from addState, and you're left with an invalid pointer.

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe
Oh, thanks. Is there any way to call the constructor in that function or do I have to pass a pointer to a State as an argument?

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Joda posted:

Oh, thanks. Is there any way to call the constructor in that function or do I have to pass a pointer to a State as an argument?
You're already passing a pointer to a State as an argument, that's half of your problem. You might find it just works if you make StateList out of non-pointers, and pass a non-pointer (I can't tell because I don't know whether your State class has copy or move behavior, or whether you'd think to construct it inline with the push_back if not.)

Alternatively, keep using a pointer but then you have to put it on the heap (new and delete), in which case you should probably be wrapping it in a std::unique_ptr or std::shared_ptr or something these days.

Praseodymi
Aug 26, 2010

I need a lightweight way to get keyboard input that will work in Unix. I don't know what to call it, but not in a text input way, instead reading all input as separate button presses like a game. Anyone help me?

Vanadium
Jan 8, 2005

If you want keyboard input for the current terminal, it's probably not going to get much better than using termios to set the terminal into raw mode and doing text-style input, except without buffering or that sort of thing. Otherwise you'd use anything between libxcb, glfw or sdl to create your own window and wait for x input events, not sure what's that like for non-desktop-linux or even non-x11 environments.

python prez hsss
Mar 24, 2014
Not to brag but loving look at this. If you're seriously just browsing the entire thread looking for something loving amazing just look at this poo poo. I looked at it and i loving almost jumped out my chair, I found it in some Linux kernel programming book.
code:
//
//  main.c
//  goons
//
//  Created by jon on 3/23/14.
//  Copyright (c) 2014 jon inc. All rights reserved.
//

#include <stdio.h>

struct result{
    int x;
    int y;
    int z;
};

struct result store()
{
    struct result temp;
    temp.x = 10;
    temp.y = 20;
    temp.z = 30;
    return temp;
}
int main(int argc, const char * argv[])
{
    // prints out the results of temp in
    // store()
    printf("%d", store().x);
    return 0;
}
you can also replace store() as a pointer function. But really, loving look at that.

For some loving reason, may it be if i got a bad compiler (I mean really bad, like it basically insulted me and my girlfriend after it finished compiling) the auto complete doesn't show up on most modern ides, or even outdated ides like emacs

Nippashish
Nov 2, 2005

Let me see you dance!

python prez hsss posted:

Not to brag but loving look at this. If you're seriously just browsing the entire thread looking for something loving amazing just look at this poo poo. I looked at it and i loving almost jumped out my chair, I found it in some Linux kernel programming book.

I don't understand this post. What did you expect to happen?

Dicky B
Mar 23, 2004

Nippashish posted:

I don't understand this post. What did you expect to happen?
Just look at that poo poo man. I mean, motherfucking poo poo. I don't even know who the gently caress I am anymore

seiken
Feb 7, 2005

hah ha ha

python prez hsss posted:

Not to brag but loving look at this. If you're seriously just browsing the entire thread looking for something loving amazing just look at this poo poo. I looked at it and i loving almost jumped out my chair, I found it in some Linux kernel programming book.

you can also replace store() as a pointer function. But really, loving look at that.

oh my god that's crazy how did you find that

python prez hsss
Mar 24, 2014

Nippashish posted:

I don't understand this post. What did you expect to happen?

Well, I honestly didn't know you could use a member from a struct in a function, or whatever, thats pretty loving cool I mean I didn't see any tutorials on this poo poo on the internet. I was trying to code something that used that particular way of retrieving data and I just stumbled upon those lines of code, just felt like sharing

python prez hsss
Mar 24, 2014

seiken posted:

oh my god that's crazy how did you find that

Seriously, I was just browsing safari books and blam, loving ejeet code

hooah
Feb 6, 2006
WTF?
That's one of the main points of structs/classes (especially structs). If you couldn't find any tutorials that covered data members, you didn't try very hard.

Nippashish
Nov 2, 2005

Let me see you dance!

python prez hsss posted:

Well, I honestly didn't know you could use a member from a struct in a function, or whatever, thats pretty loving cool I mean I didn't see any tutorials on this poo poo on the internet. I was trying to code something that used that particular way of retrieving data and I just stumbled upon those lines of code, just felt like sharing

Would it surprise you less if it was written
code:
    struct result dicks = store();
    printf("%d", dicks.x);
?

python prez hsss
Mar 24, 2014

Nippashish posted:

Would it surprise you less if it was written
code:
    struct result dicks = store();
    printf("%d", dicks.x);
?

Oh

edit: Believe it or not it does surprise me. 5's all around.

Dicky B
Mar 23, 2004

If you think that's something, just look at this poo poo. I found it in an old COM programming book. loving jumped out of my skin and punched my girlfriend in the oval office when I saw it.

code:
int main(int argc, const char * argv[])
{
    printf("Hello, world!");
    return 0;
}

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
:byob1: postin pals

Dicky B
Mar 23, 2004

Actually I don't know him I just thought his post was funny v:3:v

seiken
Feb 7, 2005

hah ha ha
Jesus loving christ. I mean I don't want to scare anyone but take a look at this loving thing I found. I dug it up on an old hacker BBS, took one look at it and shat all over the loving floor. Just loving look at this.

C++ code:
/*
                    .---.
                  /       \   boo!
    ---- _       |  O   O  | /     _ ---
    \       ~-.  `.       .'  .-~      /
     \          ~-_>     <_-~         /
       \                             /
         \                         /
           \                     /
             \                 /
               \             /
                 \         /
                   \       \
                     \      \
                       \     \
                         \    \
                           \   l
                             \ /
                              V

  Copyright (c) 2014 sa forums goons
  DON'T STEAL */

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE
It's valid to treat the output of an RNG as "N random bits of output", right? So if I have a RNG that outputs a long (64 bits), I can treat that as 2x32 bits?

The syntax on this is working fine (a union), I just want to be sure there's not something theoretical I'm missing.

Paul MaudDib fucked around with this message at 21:26 on Mar 24, 2014

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Paul MaudDib posted:

It's valid to treat the output of an RNG as "N random bits of output", right? So if I have a RNG that outputs a long (64 bits), I can treat that as 2x32 bits?

The syntax on this is working fine (a union), I just want to be sure there's not something theoretical I'm missing.

A good PRNG is equally random across all bits (or you would be able to partially predict the bits that are less likely to change). A bad PRNG is probably less balanced, but there are lots of reasons not to use a bad one. "True" randomness like /dev/random will also be equally distributed.

Gazpacho
Jun 18, 2004

by Fluffdaddy
Slippery Tilde
It depends very much on the generator. Aside from what Subjunctive said, a good PRNG also distributes bits independently of earlier bits (within the limits of its algorithm). So each group of bits from the generator is distributed independently of the last group.

In some Unix systems (but not recent Linux versions), the C rand function is not a good PRNG.

Adbot
ADBOT LOVES YOU

nebby
Dec 21, 2000
resident mog

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply