• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Stumpokapow

listen to the mad man
Ran into a fun python (2.7) bug/feature today.

Python has an extremely limited number of special built-in functions called built-ins. Other than that everything works through a module system that has a bunch of sensible, coherent namespace rules. What you need to know for this example is that the mathematical max function is called max and it's one of these special built-ins.

Let's do some basic sanity checking:
Code:
max(2,3)
This returns 3.

Code:
max=3
This creates an int called max, overloading the previous symbol definition for the builtin, so in the current scope, I can no longer call the max function. If this had errored, I wouldn't blame it, not wanting people to override builtins would be a reasonable conceit.

Code:
max(2,3)
If I try to call it again in the same code environment, I get an error, because int type objects are not callables. This is what I would expect.

Okay, now let's clear our environment and run again code from scratch.
Code:
if True:
	my_var = max(2,3)
else:
	max = 4
This will correctly assign the value 3 to my_var, because the interpreter never gets to the max=4 definition and can run the max(2,3) function as it should.

Code:
if False:
	max=4
else:
	my_var = max(2,3)
Now checking if order matters, to see if the interpreter will trip up from seeing the variable before the function call. Okay, this will also correctly assign the value 3 to my_var, because the interpreter never gets to the max=4 definition and can run the max(2,3) function as it should. So as long as the interpreter never executes code that overloads the max() function, I should be able to use it, right?

What do you expect this code will do?
Code:
def test():
	if True:
		my_var = max(2,3)
	else:
		max = 4

test()

If you guessed
a) Work correctly
b) Fail because an int is not callable
You are incorrect.

The answer is:
c) Fail because max is a local variable of indeterminate type that hasn't yet be defined, so I can't access an undefined variable.

I think what's going on is the Python interpreter doesn't seem to pre-scan code in the global interpreter space, so the stuff outside the function works fine. But when you put code inside the function, before it runs any of the function, it does some sort of static analysis to pre-populate the local variable scope space, hitting the line that defines max, and noting in advance that it expects max to be a variable, which then causes the line that does run to fail.

Or else, global variables are pre-analyzed, but lower in the lookup table hierarchy than global built-ins, but local variables are somehow higher in the lookup table than global built-ins.

Either way, it's an unusual scoping and allocation behaviour.
 
I think what's going on is the Python interpreter doesn't seem to pre-scan code in the global interpreter space, so the stuff outside the function works fine. But when you put code inside the function, before it runs any of the function, it does some sort of static analysis to pre-populate the local variable scope space, hitting the line that defines max, and noting in advance that it expects max to be a variable, which then causes the line that does run to fail.

This is mostly correct, The "pre-scanning" is done when the runtime builds the closure for the function though, it's not done by the lexer. You can kinda see this in action with the following code (giveupthefunc shamelessly ripped from here):

Code:
import inspect, gc
def giveupthefunc():
    frame = inspect.currentframe(1)
    code  = frame.f_code
    globs = frame.f_globals
    functype = type(lambda: 0)
    funcs = []
    for func in gc.get_referrers(code):
        if type(func) is functype:
            if getattr(func, "func_code", None) is code:
                if getattr(func, "func_globals", None) is globs:
                    funcs.append(func)
                    if len(funcs) > 1:
                        return None
    return funcs[0] if funcs else None

def test():
    f = giveupthefunc()
    if False:
        my_var = max(2,3)
    else:
        max = 4
        my_var = max

If you inspect the value of f inside of test, you'll see that it has a member called co_varnames which is the list ['f', 'my_var', 'max']. Name lookup inside of closures go through co_varnames first, if that lookup fails then it goes to locals, globals, and builtins.

The list of variable names has to be built immediately when the closure is created because otherwise it would have to synchronize every access to co_varnames, which is the root of the gc chain for a given closure, and the performance would be unacceptable.
 

Megasoum

Banned
Hey guys,

I started playing around with Unity and the provided tutorials (about halfway done with the Space Shooter one right now).

I'm using Visual Studio in Windows and I have annoying issues with the provided Unity manual.

First of all I had to re-bind in VS the keyboard shortcut to open the API help (I suspect that it didn't work because I'm using a French Canadian keyboard).

Anyway, now when I hit the keybind while highlighting a word to look at the help it takes fooooreever to open. VS basically goes into a "Not Responding" state for a couple of seconds everytime and the built-in Edge browser doesn't work half the time.

Is there any way to just open the manual files in Chrome via the shortcut or something?

I like the idea of having the built-in manual while coding but it just sucks right now.
 

Makai

Member
Hey guys,

I started playing around with Unity and the provided tutorials (about halfway done with the Space Shooter one right now).

I'm using Visual Studio in Windows and I have annoying issues with the provided Unity manual.

First of all I had to re-bind in VS the keyboard shortcut to open the API help (I suspect that it didn't work because I'm using a French Canadian keyboard).

Anyway, now when I hit the keybind while highlighting a word to look at the help it takes fooooreever to open. VS basically goes into a "Not Responding" state for a couple of seconds everytime and the built-in Edge browser doesn't work half the time.

Is there any way to just open the manual files in Chrome via the shortcut or something?

I like the idea of having the built-in manual while coding but it just sucks right now.
https://docs.unity3d.com/Manual/index.html
https://docs.unity3d.com/ScriptReference/index.html
 

Makai

Member
So at work I'm implmenting a 3D renderer for Android in an attempt to beat the performance of Unity and Unreal. I think this is plausible because we just need to render a giant mesh with 8k textures. No lighting, shadows, etc - just one simple shader for everything. Almost done - I successfully parsed the .obj and everything's displaying except the textures are warped - I'll figure that out later. Does anyone have any arcane OpenGL knowledge that I should know? There's 50 vertex buffers and I just iterate and draw each with the appropriate texture.

Vertex shader

Code:
            #version 150

            in vec3 position;
            in vec2 tex_coords;
            out vec2 v_tex_coords;
            uniform mat4 matrix;

            void main() {
                v_tex_coords = tex_coords;
                gl_Position = matrix * vec4(position, 1.0);
            }

Fragment shader

Code:
            #version 150

            in vec2 v_tex_coords;
            out vec4 color;
            uniform sampler2D tex;

            void main() {
                color = texture(tex, v_tex_coords);
            }
 
Softball question for you guys. Let's say I want to make a portfolio website for my GF who doesn't know anything about HTML. If I wanted her to be able to change the content of it herself, and I am simultaneously practicing making a website with HTML/CSS/JS/PHP, how would accomplish this? Do I have to use Wordpress?

I've never had to deal with this because the sites I have worked on didn't require anyone other than me updating it.
 

YoungFa

Member
Softball question for you guys. Let's say I want to make a portfolio website for my GF who doesn't know anything about HTML. If I wanted her to be able to change the content of it herself, and I am simultaneously practicing making a website with HTML/CSS/JS/PHP, how would accomplish this? Do I have to use Wordpress?

I've never had to deal with this because the sites I have worked on didn't require anyone other than me updating it.
Yeah. Use wordpress.
 

Allonym

There should be more tampons in gaming
Silly question but I'll ask it none the less. Can one be a systems engineer or software developer although they majored in IT? I'm ignorant about these things so I figured I'd ask you guys, the enthusiasts and professionals.
 

Makai

Member
Silly question but I'll ask it none the less. Can one be a systems engineer or software developer although they majored in IT? I'm ignorant about these things so I figured I'd ask you guys, the enthusiasts and professionals.
I majored in political science and didn't finish.
 

Allonym

There should be more tampons in gaming
I majored in political science and didn't finish.

Are you saying that you are in fact a political scientist or are you saying that although you didn't graduate with a major in something that it didn't stop you from being something else, i.e a programmer? I'm sorry your statement is a little hard to interpret, rather I guess it can be interpreted in multiple ways and I'm just not sure what you're saying exactly.
 

Makai

Member
Are you saying that you are in fact a political scientist or are you saying that although you didn't graduate with a major in something that it didn't stop you from being something else, i.e a programmer? I'm sorry your statement is a little hard to interpret, rather I guess it can be interpreted in multiple ways and I'm just not sure what you're saying exactly.
Programmer
 

Slo

Member
There will be some jobs that won't let you past the HR department's filter if you don't have a degree in CompSci, but there absolutely are jobs out there where you can be self taught. Open a github account and start putting all of your code out there.

If you don't have the pedigree, you're gonna need a portfolio.
 

Makai

Member
Haha, cool. Entirely self taught or schooling? I'm attempting to learn on my own with Codeacademy and Edx CS50 I heard someone mention while lurking in the forums one night.
Mix of both. I took a few compsci courses at college but I ignored most of them and spent my time making games in C# with XNA and Unity. After school, I pretty much maxed out what I could get out of C#, so I branched out into obscure programming languages.

Functional programming in Haskell and F#- http://learnyouahaskell.com/
Low level programming in Rust - https://doc.rust-lang.org/book/

I wouldn't recommend either for a beginner - just figure out what you want to make and google how to do it. Writing a lot of code is the best way to get better quickly.
 

Makai

Member
How is this book for someone that has a good experience in low-level stuff (although not in linux kernel/drivers if that matters) but only a really basic experience in Rust? Could it be a good book to improve on Rust?
It's the official book and well-regarded. The ownership sections are the most important if you just want a quick look at the big ideas. The rest will be straight-forward since you know C and OCaml.

There's also an unfinished book that explains how to break the normal rules of the compiler with unsafe scopes:
https://doc.rust-lang.org/nomicon/
 

Koren

Member
Many thanks... I'll put it on the list of books I should read.


On a completely different matter, in Python, I would like to know who thought that putting "is" and "in" among comparison operators, with the same priority, was a good idea (well, it makes the grammar simpler, but still...).

I mean...
Code:
True == False is False
returns False

Yes, that's perfectly understandable when you think about how it's handled, but yet... forget that "==" and "is" have the same priority and you're fucked.

Edit: Before somebody tells me that it won't happen in real cases...

Code:
x = None

if x is None == True :
    print("x is None")
else :
    print("x is not None")
prints "x is not None", and that's a thing a student could write (I have troubles to make them get rid of those useless == True)
 
Many thanks... I'll put it on the list of books I should read.


On a completely different matter, in Python, I would like to know who thought that putting "is" and "in" among comparison operators, with the same priority, was a good idea (well, it makes the grammar simpler, but still...).

I mean...
Code:
True == False is False
returns False

Yes, that's perfectly understandable when you think about how it's handled, but yet... forget that "==" and "is" have the same priority and you're fucked.

Edit: Before somebody tells me that it won't happen in real cases...

Code:
x = None

if x is None == True :
    print("x is None")
else :
    print("x is not None")
prints "x is not None", and that's a thing a student could write (I have troubles to make them get rid of those useless == True)

Reminds me of this little gem in c++. Instead of writing if (0) and if (1), you can write write "if (true == false)" and "if (true == false == true == false)"
 
Question regarding Trie Data Structures, which are just prefix trees. But I am trying to set up a Stack to traverse through the Trie but I am kind of confused as to what the structure of my Stack will be like. I am using an array implementation for the Stack. My guess is the stack will contain references to the children nodes but not entirely convinced. Anyone have experience with Tries?
 
C#'s standard library data structures are garbage, not sure why they've never bothered to improve them. 3rd party collections library is basically necessary if you care even slightly about performance
I've not used them much, but is it just the performance that's the issue? .NET in general has a well-known overhead.
 

Koren

Member
It's worth noticing that they are working on a new Rust book, that's much better than the current one.
Interesting, thanks...

Reminds me of this little gem in c++. Instead of writing if (0) and if (1), you can write write "if (true == false)" and "if (true == false == true == false)"
I think I've already seen this here. I guess it was you...

But...

(True == False == True == False) is False in Python

(True == False == False) is also False

Thinking about it, I'm not sure which one I prefer. :/
 

Somnid

Member
Question regarding Trie Data Structures, which are just prefix trees. But I am trying to set up a Stack to traverse through the Trie but I am kind of confused as to what the structure of my Stack will be like. I am using an array implementation for the Stack. My guess is the stack will contain references to the children nodes but not entirely convinced. Anyone have experience with Tries?

Unless it's a learning exercise, I wouldn't recommend explicitly using stacks for traversal. Just use recursion, once you get used to it, it's much easier to reason about.
 
Unless it's a learning exercise, I wouldn't recommend explicitly using stacks for traversal. Just use recursion, once you get used to it, it's much easier to reason about.

Yep, wish I could do recursion but have to do an iterative approach. Some of my code for the traversal so far is:

Code:
public void printStrs() {
		// Preorder Traversal
		if (rootNode == null) {
			return;
		}

		ArrayStack stack = new ArrayStack();
		stack.push(rootNode);
		while (!stack.isEmpty()) {
			try {
				stack.pop();
				// TODO visit node
				
				
			} catch (StackException e) {
				e.printStackTrace();
			}
			// for each child node != null
			// stack.push(node)
				

		}

	}

Just the Stack is screwing me up a bit. My Stack class has an array of Nodes for the trie. My pop, I assume, will grab me a Trie, and push will push..I am not exactly sure about this. A TrieNode, I assume, as each Node contains an array of references. I think the main problem, for me, is getting the children of a node. I think it would be a check to see if this is the end of the word, if not, we know we have children, but I am not sure. Slightly confused.
 
Hey everybody,

I need some help and I'd certainly get obliterated on StackOverflow ("git gud", "read 50 books before even thinking of posting here", "noob", etc.)... so here goes:

I'm making a program (C#, WPF) with two ways of storing data:
- offline/local: using SQLite
- online: using MySQL

People can edit and create their local database "entries" at will, but they should be able to download and share things on the global server.

I know how to handle these things... but on a network I own... Here what's new for me is the fact that the clients are going to be used in a few hospitals with various degrees of security (e.g., in my hospital there are very strict policies in place... I think that any web page with "game" in it is blocked, every single port beside 80 is blocked and you can't install anything on your own). Also, the sysadmins I talked to are grade-A douchebags...

I basically need my software to be plug and play as I can't expect my colleagues to install any kind of third party software (which they won't even be able to install anyway)... so I really need the data to be available through the only open port I have.

I googled for a while and saw that I should make a web service in order for the data to be accessible via HTML and basically bypass the firewall restriction. Is my understanding correct? I've never done that (I'm completely self-taught) and before diving in I'd like to make sure it's the right way to go.
My worry is that they might be able to block the data anyway (like I said they can block HTML pages based on keywords, and using the IP address doesn't solve anything). If it's just keyword based, I could use a simple cipher like ROT-13...

Other than that... are there any limits using a web service? Security-wise or scope-wise.

Thank you for your help!
 

Koren

Member
Yep, wish I could do recursion but have to do an iterative approach.
Well, I'd say that in some simple cases, you could still write a recursion solution that works, then convert it afterwards, simulating the calls with a stack. You just have to put the arguments of the call in the stack. Put the argument of the first call in an empty stack. For each call in the recursive version, add a "push" on the stack. And you loop till your stack is empty.

I'll give an example. Let's imagine we have a recursive solution like:
Code:
void Foo(node) {
    do_something_with(node)
    
    for all child among node's children :
         Foo(child)
}

void Bar() {
    Foo(root)
}

You can write an iterative version like this :
Code:
void Bar() {
    my_stack = createEmptyStack()

    my_stack.push(root)

    while stack_is_not_empty {
        node = stack.pop()
        
        do_something_with(node)
    
        for all child among node's children :
            stack.push(child)
    }
}

See how the content of the recursive solution is similar to the content of the loop in the iterative version. The arguments are just pushed and poped from the stack.

Beware, though:
- the order for exploration will change, with a stack, because you push all children, then pop them in the opposite order. If you want the exact same result, you need to push the children in the REVERSED order.
- if the recursive calls are not the last things you're doing in the recursive function (and especially if you want to do computations with the results returned by the calls), things may be harder. You may for example use a stack to push the context of each step, so you can restore the contexts in the reverse order afterwards. If you use computations on subtrees to compute a result, storing the results inside the tree (at the "root" node of each subtree) can be of some help.

In the last case, it can become a case-by-case basis, so knowing more on what you're trying to do with the Trie (and whether you can store data in the Trie itself) would be helpful.
 

Somnid

Member
Yep, wish I could do recursion but have to do an iterative approach. Some of my code for the traversal so far is:

Just the Stack is screwing me up a bit. My Stack class has an array of Nodes for the trie. My pop, I assume, will grab me a Trie, and push will push..I am not exactly sure about this. A TrieNode, I assume, as each Node contains an array of references. I think the main problem, for me, is getting the children of a node. I think it would be a check to see if this is the end of the word, if not, we know we have children, but I am not sure. Slightly confused.

You need to peek at the node to keep it on the stack so you can read it at the end. Check if the node has unvisited children. If it does, then push the next one on the stack, if not, then visit the node and pop. Visiting consists of checking if the node is a leaf node, if it is then you print the stack in reverse order.
 

Koren

Member
My worry is that they might be able to block the data anyway (like I said they can block HTML pages based on keywords, and using the IP address doesn't solve anything). If it's just keyword based, I could use a simple cipher like ROT-13...
A trick I used in the past to go through a really paranoiac wall was to disguise the data as an image.

Should you encrypt the data, for example with ROT-13, there's still a chance that you trigger a flag (for example, by having "tnzr" in your page, you'll encrypt it in "game", and it'll be blocked). Since images are binary data, blocking algorithms don't do regex on those.

Most of those algorithm won't even check whether it's actually an image. If it's a file refered by a <img> in an html page, and its MIME-type describe it as an image, it'll get a pass. In rare cases, you'll have to add a proper header, but that's not a big problem.


Beside this, it's hard to give you an answer on the cons of using html to distribute data. The main issue is security, even if you can setup pretty much everything once you have a way to transfer data. I'll be more and more an hack, though.


Also, beware of things you can or cannot do over your network at work...
 

Somnid

Member
Hey everybody,

I need some help and I'd certainly get obliterated on StackOverflow ("git gud", "read 50 books before even thinking of posting here", "noob", etc.)... so here goes:

I'm making a program (C#, WPF) with two ways of storing data:
- offline/local: using SQLite
- online: using MySQL

People can edit and create their local database "entries" at will, but they should be able to download and share things on the global server.

I know how to handle these things... but on a network I own... Here what's new for me is the fact that the clients are going to be used in a few hospitals with various degrees of security (e.g., in my hospital there are very strict policies in place... I think that any web page with "game" in it is blocked, every single port beside 80 is blocked and you can't install anything on your own). Also, the sysadmins I talked to are grade-A douchebags...

I basically need my software to be plug and play as I can't expect my colleagues to install any kind of third party software (which they won't even be able to install anyway)... so I really need the data to be available through the only open port I have.

I googled for a while and saw that I should make a web service in order for the data to be accessible via HTML and basically bypass the firewall restriction. Is my understanding correct? I've never done that (I'm completely self-taught) and before diving in I'd like to make sure it's the right way to go.
My worry is that they might be able to block the data anyway (like I said they can block HTML pages based on keywords, and using the IP address doesn't solve anything). If it's just keyword based, I could use a simple cipher like ROT-13...

Other than that... are there any limits using a web service? Security-wise or scope-wise.

Thank you for your help!

It sounds like you need to build a webapp as that will have no install and will all be through port 80 and 443. The MITM blocking is defeated via HTTPs, they pretty much can't disable port 443 otherwise secure pages won't work, but they also can't eavesdrop secure pages either. As far as domain blocking, you can circumvent that with a technique called domain name fronting: http://www.icir.org/vern/papers/meek-PETS-2015.pdf. Basically, if they can't afford to block google, then they can't block your request.
 
A trick I used in the past to go through a really paranoiac wall was to disguise the data as an image.

Should you encrypt the data, for example with ROT-13, there's still a chance that you trigger a flag (for example, by having "tnzr" in your page, you'll encrypt it in "game", and it'll be blocked). Since images are binary data, blocking algorithms don't do regex on those.

Most of those algorithm won't even check whether it's actually an image. If it's a file refered by a <img> in an html page, and its MIME-type describe it as an image, it'll get a pass. In rare cases, you'll have to add a proper header, but that's not a big problem.


Beside this, it's hard to give you an answer on the cons of using html to distribute data. The main issue is security, even if you can setup pretty much everything once you have a way to transfer data. I'll be more and more an hack, though.


Also, beware of things you can or cannot do over your network at work...

It sounds like you need to build a webapp as that will have no install and will all be through port 80 and 443. The MITM blocking is defeated via HTTPs, they pretty much can't disable port 443 otherwise secure pages won't work, but they also can't eavesdrop secure pages either. As far as domain blocking, you can circumvent that with a technique called domain name fronting: http://www.icir.org/vern/papers/meek-PETS-2015.pdf. Basically, if they can't afford to block google, then they can't block your request.


thank you both! I guess I'll read up on how to build a very simple web service (WCF, I guess) and just do some tests! I'll try your techniques if I can't access my NAS from work!

and don't worry, I won't do anything illegal... it's not like I'm unlocking Facebook for everyone ;)
 

Koren

Member
and don't worry, I won't do anything illegal... it's not like I'm unlocking Facebook for everyone ;)
Well, this one can be easy, you can sometimes use Google Translate to access to forbidden sites. ^_^

It sounds like you need to build a webapp as that will have no install and will all be through port 80 and 443. The MITM blocking is defeated via HTTPs, they pretty much can't disable port 443 otherwise secure pages won't work
I know at least a research lab where 443 is blocked ^_^ Yes, basic internet don't really work, but they don't care, I'm not even sure why they kept 80 open, to be honest.
 

timaeust

Neo Member
Coming from a computer engineering undergrad, I'm currently taking a design patterns class in a CS master's. Has anyone else had a similar path, and if so, did you feel that this class was beneficial to your growth as a software engineer?
 
Has anyone here ever done a program that prints the prime numbers from 1 to x recursively? Because right now I'm stuck with a problem I don't understand. My program crashes when I want to print the primes from 1 to 1,000,000. I don't know if is a limitation of memory or data type but I've used longs instead of int but it still crashes. Please any help is welcome ;_;

Code in C++:
#include<iostream>
#include<time.h>
#include<stdlib.h>

int prime(int x, int i)
{
if (i == 1)
return 1;
else
{
if (x % i == 0)
return 0;
else
prime(x, i - 1);
}
}

int main()
{
int num, k = 1;
int x, t;
srand(time(NULL));
std::cout << "Introduce max number: ";
std::cin >> x;
std::cout << "The prime numbers from 1 to " << x << " using recursion are:" << std::endl;
std::cout << "Press <enter> to begin." << std::endl;
std::cin.get();
std::cin.get();
t = clock();
for (num = 2; num <= x; ++num)
{
k = prime(num, num / 2);
if (k == 1)
std::cout << num << std::endl;
}
std::cout << std::endl << "Elapsed time: " << (clock() - t) / 1000.0 << std::endl;
return 0;
}
 
Has anyone here ever done a program that prints the prime numbers from 1 to x recursively? Because right now I'm stuck with a problem I don't understand. My program crashes when I want to print the primes from 1 to 1,000,000. I don't know if is a limitation of memory or data type but I've used longs instead of int but it still crashes. Please any help is welcome ;_;

Code in C++:

Code:
#include<iostream>
#include<time.h>
#include<stdlib.h>

int prime(int x, int i)
{
  if (i == 1)
    return 1;
  else
  {
    if (x % i == 0)
      return 0;
    else
      prime(x, i - 1);
  }
}

int main()
{
  int num, k = 1;
  int x, t;
  srand(time(NULL));
  std::cout << "Introduce max number: ";
  std::cin >> x;
  std::cout << "The prime numbers from 1 to " << x << " using recursion are:" << std::endl;
  std::cout << "Press <enter> to begin." << std::endl;
  std::cin.get();
  std::cin.get();
  t = clock();
  for (num = 2; num <= x; ++num)
  {
    k = prime(num, num / 2);
    if (k == 1)
      std::cout << num << std::endl;
  }
  std::cout << std::endl << "Elapsed time: " << (clock() - t) / 1000.0 << std::endl;
  return 0;
}

Fixed the indentation for you.

You're missing a return statement in in your prime function. I don't actually think that's the problem, it will probably magically work anyway, but it's undefined behavior, so it could be the problem. I didn't look too closely after that, so there could be something else obvious.

Some side notes:

1) You should really learn about bool. Don't return 1 and 0, return true and false.

2) This prime function is kind of weird. When you think about checking whether a number is prime, how many inputs do you expect your function to have? I expect a function which takes one number -- the number to check -- and returns whether it is prime or not. But your function takes 2 arguments. I would try to find a way to rewrite this so that your prime function takes only 1 number -- the number to check.

3) With a name like "prime", it's not clear whether your'e checking that a number is prime, or trying to find the n'th prime. By reading the code of course you can figure it out, but it would be nice if the name just told you. So I would recommend changing the name of the function.
 

Yeah I know the indentation is all over the place but I copy and paste with correct indentation in here but it still shows all wrong.

There is a missing return in the last else right?
should be:
int prime(int x, int i)
{
if(i == 1)
return 1;
else
{
if(x % i == 0)
return 0;
else
return prime(x, i - 1);
}
}

But it still crashes unfortunately. And bools frighten me lol. My logic is still not there yet to use them appropriately :(
 
Yeah I know the indentation is all over the place but I copy and paste with correct indentation in here but it still shows all wrong.

There is a missing return in the last else right?
should be:


But it still crashes unfortunately. And bools frighten me lol. My logic is still not there yet to use them appropriately :(

What frightens you about bool? If you were going to return 1, return true. If you were going to return 0, return false. Then change the return type of the function to be bool instead of int. That's all there is to it, seriously.

I suspect that your problem is a stack overflow. If you were to do a release mode build (idk what compiler you're using, but in MSVC it's as simple as changing a drop down box to say Release, in gcc / clang you would pass -O2 on the command line) the problem would go away.

This isn't a bug in your program, it's a limitation of recursion.
 

Koren

Member
2) This prime function is kind of weird. When you think about checking whether a number is prime, how many inputs do you expect your function to have? I expect a function which takes one number -- the number to check -- and returns whether it is prime or not. But your function takes 2 arguments. I would try to find a way to rewrite this so that your prime function takes only 1 number -- the number to check.
Pure functionnal programming... You need this function with two arguments. But it should be called e.g. is_prime_aux(x, i), and there should be a function is_prime(x) that call is_prime_aux(x, x/2)

Granted, that's exactly what the "main" function is doing, but it's not easy to understand.

That's not really efficient, but it's a common way to write such a function when you learn functional programming, but... it can only work with terminal recursivity, so you need to make sure the compiler will indeed do this optimization. I agree with you, it's definitively an optimization/configuration issue...

Also, i'd call (x, i-2) instead of (x, i), after a parity check, because it's useless to check for even values...
 
Pure functionnal programming... You need this function with two arguments. But it should be called e.g. is_prime_aux(x, i), and there should be a function is_prime(x) that call is_prime_aux(x, x/2)

Granted, that's exactly what the "main" function is doing, but it's not easy to understand.

That's not really efficient, but it's a common way to write such a function when you learn functional programming, but... it can only work with terminal recursivity, so you need to make sure the compiler will indeed do this optimization.

Also, i'd call (x, i-2) instead of (x, i), after a parity check, because it's useless to check for even values...

I was trying to make the poster figure that out ;-) is_prime_aux should be an implementation detail though, the function the user calls should simply be called is_prime(x). That's what I was getting at, I was intentionally trying to leave out some details though so he/she could figure it out.
 
Newbie C++ question:
Anyone know of a way to use an instantiated object from another class other than using the extern keyword? I'm guessing I should use a pointer or reference but I'm fairly rough with that concept.

Quick code so you can get the idea:
class Alpha : public Beta
{

}

class Beta
{
Alpha alpha1;
}

class Charlie : public Beta
{
<I want to use the alpha1 object here, but its not working.>
}
 
Newbie C++ question:
Anyone know of a way to use an instantiated object from another class other than using the extern keyword? I'm guessing I should use a pointer or reference but I'm fairly rough with that concept.

Yea, use a reference.

Code:
class Alpha : public Beta
{

}

class Beta
{
     Alpha alpha1;
}

class Charlie
{
   Charlie(Alpha &a) : alpha_ref(a) {}
   Alpha &alpha_ref;
}


Beta B;
Charlie C(B.alpha1);

That said, your code is malformed as written, because Alpha inherits from Beta, and Beta contains an instance of Alpha. So you have a cyclic dependency here.
 

Koren

Member
I was trying to make the poster figure that out ;-) is_prime_aux should be an implementation detail though, the function the user calls should simply be called is_prime(x). That's what I was getting at, I was intentionally trying to leave out some details though so he/she could figure it out.
Damn, sorry about this... Knowing you, I should have guessed :/

I came back from work with a nasty headache, and I'm not up to the game... I wonder how I managed to write an algorithm that detect QR markers in an image in my current state. I think I'll try to sleep a bit.
 
Yea, use a reference.

That said, your code is malformed as written, because Alpha inherits from Beta, and Beta contains an instance of Alpha. So you have a cyclic dependency here.

Thank you, I'll work on both.

Edit: Yeah, removed the inheritance there from Alpha and the code didn't break. Don't know why I used it to begin with. My small game with from 2 headers and 3 cpps to 5 headers and 6 CPP's handling battle system and save load. So maybe just left over from the refactoring as I organized.
 
What frightens you about bool? If you were going to return 1, return true. If you were going to return 0, return false. Then change the return type of the function to be bool instead of int. That's all there is to it, seriously.

I suspect that your problem is a stack overflow. If you were to do a release mode build (idk what compiler you're using, but in MSVC it's as simple as changing a drop down box to say Release, in gcc / clang you would pass -O2 on the command line) the problem would go away.


This isn't a bug in your program, it's a limitation of recursion.

Oh this solved it!! I was building it in debug and now in release it works! Thanks so much. And about the bool, I don't understand how I can return true or false when there is also a chance of returning the recursive method which isn't a boolean.
 
Top Bottom