• 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

The problem I have with this is that you can't see, by only reading indentation and the beginning of lines, if you'll need a closing brace or not... At least, if the line following a while, an if or a for doesn't begin with a {, I know in my case that I need a } aligned with the for.

The obvious choice is always to include braces. I am sort of okay with one liners without braces, but by always including braces there's really no way to fuck it up. I mean that obviously your IDE or compiler should alert you when you fuck it up, but next thing you know your SSL implementation is broken because of it.

Not including braces is like using pull out method as the primary contraceptive: it might work out for you and you think it's nice but in reality it's always just terrible :)
 

Koren

Member
Lots of languages use indentation instead of braces. I strongly prefer it. Much more readable and fun to write. Also, no ideological disagreements about brace alignment.
I would tend to agree, but it's a bit late to change C basics ^_^

Not including braces is like using pull out method as the primary contraceptive: it might work out for you and you think it's nice but in reality it's always just terrible :)
Except that in the source case, I haven't seen a tangible proof that any choice is more error-proof. You seem to imply that one choice is a dangerous behavior, I disagree.

(or at least any non obviously stupid choice like using cariage return when you're reaching 80 columns and nowhere else, which is doable in C)

I could use the three-lines solution with a lone } on the third (and I do it), but when there's a lot of cases to check, having a more compact solution can be handy. Especially when you modify the code in a 80x24 terminal, with a split view, that limit the number of lines you can read at once to a mere 11...
 

Somnid

Member
Whitespace based languages are gross because there are about half a dozen characters that produce "whitespace" that look identical, and because it limits the ability to have personal preferences and flexibility in spacing. Same reason spaces are not prefered to tabs, a space is a fixed-width character, tabs are adjustable, so use tabs and adjust them in the editor preferences if you want more or less indentation, don't bake that into the document itself.

Personally I have no clue why someone hasn't just built into IDEs the ability to save minified code and expand it to user preferences. Would make diffing easier too but alas.

Other notes:

Avoid one liners with no braces as it's a notable foot gun as seen in the infamous Apple SSL bug: https://nakedsecurity.sophos.com/20...s-ssl-bug-explained-plus-an-unofficial-patch/. There's no real gain except slight compactness which is always secondary to general readability (for logic AND potential bugs). There's no danger to spelling things out even if you personally feel it's less pleasant.

If you are indenting a lot you aren't breaking out functions. Virtually any non-trivial code in an if block or loop is a good target to make its own function. For callback heavy code use promises or whatever your language of choice calls them. Same deal for regions, if you're using a region you likely aren't breaking out a class or method.
 

Koren

Member
Whitespace based languages are gross because there are about half a dozen characters that produce "whitespace" that look identical, and because it limits the ability to have personal preferences and flexibility in spacing.
I'll grant you the difficulty to distinguished space and tabs (I use a slightly different background color for tabs, that helps a lot), but you usually have a lot of leeway in terms of preferences and flexibility in spacing...

Same reason spaces are not prefered to tabs, a space is a fixed-width character, tabs are adjustable, so use tabs and adjust them in the editor preferences if you want more or less indentation, don't bake that into the document itself.
I tend to agree, and that's why I'm not fond of PEP8 (especially when I see that the decision has been done because most people were using spaces). It's also easy to make a 1 space mistake in alignment.

Personally I have no clue why someone hasn't just built into IDEs the ability to save minified code and expand it to user preferences. Would make diffing easier too but alas.
Not sure about that "minified", but my editor allow me to change the settings to my likings at opening, and enforce the needed styling rules at closing. There's several tools in Linux at least to do this (indent*), and it's not a really complicated thing to create either, so you just need to add a call to such a tool at opening/saving/closing...

The only problem you could have with diffs is that any error in styling in the code will be corrected automatically, that's not awful if the style is consistant over the file with a couple of errors.

* Edit : apparently, indent isn't great with C++ at least... I've replaced it with my own tools for the cases I need to work with styles I'm not used to, so take this with a grain of salt. I still think that it should be done by an external program, to avoid cluttering the IDE and allow different choices of IDE with the same rules, but that may be because the modular philosophy of Linux is growing on me ^_^


Avoid one liners with no braces as it's a notable foot gun as seen in the infamous Apple SSL bug
I may have missed something, but they could have gotten a similar bug with braces, depending on the styling.

At the same time, you wouldn't have gotten the bug with a language using indentation to define blocks. ;)

If you are indenting a lot you aren't breaking out functions.
Out of curiosity, to perform a test on each cell of a 4D table, you create subfunctions?

Because that's already a 6th level of indentation...

(cartesian products of iterators is handy in Python ^_^ )
 

Makai

Member
Whitespace based languages are gross because there are about half a dozen characters that produce "whitespace" that look identical, and because it limits the ability to have personal preferences and flexibility in spacing.
This is a benefit. Much less time worrying about style differences between developers if their language naturally forces a certain style.
 
I know this isn't C related but I'm currently in school learning java and JS. This is my first semester in JS and my teacher is just flying through stuff and it's hard to keep up.
I've only had 2 classes and I have an assignment on manipulating DOM which I don't quite understand yet.
Anyone know of any good sites that explain the fundamentals and give exercises?
 
I tend to agree, and that's why I'm not fond of PEP8 (especially when I see that the decision has been done because most people were using spaces). It's also easy to make a 1 space mistake in alignment.
That's not the only reason PEP8 strongly recommends spaces over tabs. While tabs vs spaces is an eternal argument in the style world, pretty much everyone agrees that you should at least be consistent never use both in the same file or project. Only using tabs in Python doesn't allow you to line up multiline declarations or calls in some ways that PEP8 recommends (and that I personally think look rather nice). For example:

Code:
foo_dict = { key1            : val1,
             long_key_name_2 : val2, }
  
module.long_function_name(arg1, arg2, arg3, 
                          kwarg1=long_var_name_val1, 
                          kwarg2=long_var_name_val2, 
                          kwarg3=val3)

Another reason PEP8 recommends spaces is for a less noble reason- the Python community thinks 4 spaces of indentation is a good amount, and people shouldn't be using more or less as it makes the code "look weird." I personally agree (6 or 8 spaces of indentation looks strange to me, and 2 spaces is way too little), but I recognize that's just entirely personal preference. However, in large projects with tens or hundreds of developers, it's important to set a consistent style across everything, and 4 spaces of indentation is what most people are familiar with in Python.
 

Koren

Member
That's not the only reason PEP8 strongly recommends spaces over tabs. While tabs vs spaces is an eternal argument in the style world, pretty much everyone agrees that you should at least be consistent never use both in the same file or project. Only using tabs in Python doesn't allow you to line up multiline declarations or calls in some ways that PEP8 recommends (and that I personally think look rather nice).
That's a more valid reason...

Although I'm not sure it's such an issue to use tabs for indentation and space for *alignment*, and not a case of inconsistensy per se (that's what I would do in C if I really wanted to align content, so that alignment stays OK when you change the tab length*). But that's a bit hard to do properly if your editor don't display tabs clearly or try to correct what you type.

I've seen people arguing that a function should use two parameters at most, three in very special cases, and never ever four or more, so the point would probably be moot ;) I remember Python style checkers actually bothering me because of fonctions with four parameters...



(*) what I mean is that I think that
<tab> <tab> blah(arguments...
should logically be aligned on the subsequent line by
<tab> <tab> <space> <space> <space> <space> <space> more_blah
if you really want to align more_blah with arguments, and definitively not
<tab> <tab> <tab> <space> more_blah
because it'll mess up with any tab width change.

The problem is that many editors will try to convert <space*N> in <tab>...

It's hard to find a perfectly good solution for this kind of alignment with tabs, indeed.



BTW, I suspect PEP8 is against your dict formatting ;)

Another reason PEP8 recommends spaces is for a less noble reason- the Python community thinks 4 spaces of indentation is a good amount, and people shouldn't be using more or less as it makes the code "look weird."
You mean they used it as a trojan to make people get used to 4-spaces indentation?
 
BTW, I suspect PEP8 is against your dict formatting ;)
It is; usually the preferred method is:
Code:
foo_dict = { 
    key1            : val1,
    long_key_name_2 : val2, 
}
However, I've seen some code that uses the first style in large repositories.
I've seen people arguing that a function should use two parameters at most, three in very special cases, and never ever four or more, so the point would probably be moot ;) I remember Python style checkers actually bothering me because of fonctions with four parameters...
I agree, but a lot of Python APIs from large companies have functions that take TONS of kwargs. Especially those dealing with monitoring- I remember Sensu being really bad about that.
You mean they used it as a trojan to make people get used to 4-spaces indentation?
More of the reverse, at least originally; most people were used to 4 spaces and preferred it to other values, so the community put it into PEP8. But at this point it does basically move people to 4-space indendation instead of other values.
 

Koren

Member
It is; usually the preferred method is:
Code:
foo_dict = { 
    key1            : val1,
    long_key_name_2 : val2, 
}
Actually, I was referring to this, to the fact that I think the Pet Peeves parts probably implies you shouldn't align the colons, and I stil haven't understand whether the space before the colon should be there or not.

But I wasn't serious, I'm not someone that only play strictly by the rules.


About this, I love how rules like "functions should have a single return at the end" and "you can't use break to exit a loop", which are usually pretty sane ideas, turn
Code:
def Included(element, my_list) :
    for item in my_list:
        if item == element:
           return True
    return False
(or an alternative using any) into
Code:
def Included(element, my_list):
    found = False
    pos = 0
    while not found and pos<len(my_list):
        if item == element:
            found = True
        pos += 1
    return found
which I find much less readable (and probably less Pythonic and more error-prone)...

At the end of the day, I think judgement is better than absolute use of rules.


(that's an example, I'm aware there"s "in" to perform such a research ^_^ It would be possible to design a more valid example, it's just for the sake of simplicity)


Edit :
I agree, but a lot of Python APIs from large companies have functions that take TONS of kwargs. Especially those dealing with monitoring- I remember Sensu being really bad about that.
Was also not completely serious either.

I remember the first time I saw "Your function has too many arguments (4)", I was like "Oh, really?"

Sometimes, it can be uglier to try to reduce the number of arguments, or use trick like passing dictionaries when it's not logical (and make it more error-prone by giving up a chance to detect a wrong number of arguments in the function or a incorrect keyword)
 
I used to be adamant about tabs until i was forced to use spaces. Now I can't go back.

I seriously don't understand why people still prefer tabs. It literally makes no sense to me. There is not one single tangible benefit over spaces, and more than one downside

Anything that can be done with tabs can be done with spaces but the reverse is not true, while tabs simultaneously create entirely new and unnecessary problems
 

Somnid

Member
Out of curiosity, to perform a test on each cell of a 4D table, you create subfunctions?

Because that's already a 6th level of indentation...

(cartesian products of iterators is handy in Python ^_^ )

Depends, I mean nesting of dimensional loops usually is straightforward it mostly depends what you're doing in the center of it. If it's one or two lines that's fine but usually as you do more like ifs and whatever just make that a function. Or maybe you create a function that itself does the 4D loop and pass in the function you want to execute per item so nobody needs to ever look at the nasty nesting boilerplate.

I used to be adamant about tabs until i was forced to use spaces. Now I can't go back.

I seriously don't understand why people still prefer tabs. It literally makes no sense to me. There is not one single tangible benefit over spaces, and more than one downside

Anything that can be done with tabs can be done with spaces but the reverse is not true, while tabs simultaneously create entirely new and unnecessary problems

It's a good exercise to see who can catch abstraction issues because they won't tie their formatting preferences to code logic which is what spaces do.
 

Koren

Member
I seriously don't understand why people still prefer tabs.
Easier to change the size of indentation without altering the file, I guess.

Possibly habits taken before the editors were able to type spaces when you press tab (but that's... really, really old?)

But I agree, I'm using more and more spaces in new projects... But I'm reluctant to break diffs in older projects that used tabs.
 

Makai

Member
Two space tabbing exists? That sounds crazy. I've always just used whatever VS has by default, which I assume is four. I only recently found out that it uses spaces instead of tabs.
 

Koren

Member
Depends, I mean nesting of dimensional loops usually is straightforward it mostly depends what you're doing in the center of it. If it's one or two lines that's fine
Yes, I was speaking of this situation.

Or maybe you create a function that itself does the 4D loop and pass in the function you want to execute per item so nobody needs to ever look at the nasty nesting boilerplate.
I'd do this (assuming it wouldn't be used only once, though), although the iterating function would still have 5 levels of indentation...

I mean, having a lot of indentation levels is usually a problem, but my point is that there's still times where it doesn't appear as the worst possible idea. Like the number of arguments in a function, I'm not convinced there's absolute answers for this.
 

Somnid

Member
Clang-format ^_~

Introducing a toolchain dependency just for that? I mean I'm all for stripping out whitespaces when saving and just auto formatting in the editor but it seems heavy given this isn't common practice yet.

Two space tabbing exists? That sounds crazy. I've always just used whatever VS has by default, which I assume is four. I only recently found out that it uses spaces instead of tabs.

Node devs do this, it's annoying.

I mean, having a lot of indentation levels is usually a problem, but my point is that there's still times where it doesn't appear as the worst possible idea. Like the number of arguments in a function, I'm not convinced there's absolute answers for this.

I agree, those are just good guidelines. Usually it's a warning sign that you should at least consider if it's possible to refactor.
 
What's crazier (to me) is that it's Google internal style recommandation...
Oh crap, seriously? I just started talking to people in my department about working at Google over the summer (some former faculty/students work there now in networking), and I absolutely refuse to use 2 space indentation. It's terrible. I'll be sure to ask my interviewer about this (if I get an interview).
 
Introducing a toolchain dependency just for that? I mean I'm all for stripping out whitespaces when saving and just auto formatting in the editor but it seems heavy given this isn't common practice yet.

It's not a toolchain dependency, it's just something you can use to make menial tasks easier.

Oh crap, seriously? I just started talking to people in my department about working at Google over the summer (some former faculty/students work there now in networking), and I absolutely refuse to use 2 space indentation. It's terrible. I'll be sure to ask my interviewer about this (if I get an interview).
Are you kidding me? Turning down a Google internship because of indentation? Lmao. Anyway there's nothing to ask them about, it's for real

Write your code however you want then clang format it. It's a non issue
 

Somnid

Member
It's not a toolchain dependency, it's just something you can use to make menial tasks easier.

Any decent IDE can convert between, that's not the issue, the issue it what you standardize on. If I'm writing in tabs and running it through a formatter to convert to spaces then that's a needless dependency, I might as well write in spaces.
 
Establishing contacts is good too. Hopefully when they do start hiring you'll get hired then. I feel like most people don't come out of these interviews or tests feeling too hot. I felt I really screwed up when I was doing the whiteboard problem for the company I was working at now.

I wonder how common if at all that people are hired and then let go quickly. I think if you get hired that the company generally has some faith in you and doesn't expect to let you go quickly.

Still, good luck in the future and hope things go your way.

Apparently I did very well, don't know if that's just a blanket statement given to everyone who meets the bar or I actually did above the normal percentile. Either way I'll probably be in consideration for the next round of hires. Which leads to another dilemma, to take another job or wait for this job to open up. I want to make a career at the company I'm applying to if possible.
 
Are you kidding me? Turning down a Google internship because of indentation? Lmao. Anyway there's nothing to ask them about, it's for real

Write your code however you want then clang format it. It's a non issue
I certainly wouldn't turn down an internship (from anywhere) because of that. I'd just want to ask them if I ended up writing with 4-space indents if they'd care/it'd be an issue. But yeah, it'd be easiest to just use something to make it look however I want locally then convert it when I commit.
 

Two Words

Member
In my data structures class, I have to make an algorithm that calculates (2n)!/((n!)(n+1)!), which calculates the nth Catalan number.

He wants us to do it in a way that does not recalculate already calculated factorials. This is simple enough with an array that stores the values as they are calculated. However, this algorithm breaks with an integer overflow once n reaches 11. I created a different method that works all the way until n = 177.

Code:
public static double calc(int num){
        double total = 1;
        
        for (int i = 1; i <= num * 2; i++){
            if (i > num)
                total = total * i;
            if (i <= num + 1)
                total = total / i;
        }
        return total;
    }


My main concern is that he may argue that this method is not optimized like how he wanted it. I feel like at times, computational analysis will give these "Well actually" answers regardless of the empirical data.
 
In my data structures class, I have to make an algorithm that calculates (2n)!/((n!)(n+1)!)

He wants us to do it in a way that does not recalculate already calculated factorials. This is simple enough with an array that stores the values as they are calculated. However, this algorithm breaks with an integer overflow once n reaches 11. I created a different method that works all the way until n = 177.

Code:
public static double calc(int num){
        double total = 1;
        
        for (int i = 1; i <= num * 2; i++){
            if (i > num)
                total = total * i;
            if (i <= num + 1)
                total = total / i;
        }
        return total;
    }


My main concern is that he may argue that this method is not optimized like how he wanted it. I feel like at times, computational analysis will give these "Well actually" answers regardless of the empirical data.

For example, let n=5. Then (2*5)! / (5! (5+1)!) = 10! / (5! 6!) = (10*9*8*7*6!) / (5! 6!) = (10*9*8*7) / 5!

So all you need to do is compute 10*9*8*7 and divide it by 5! when n=5.

(edit) I might have jumped ahead without looking at you code line-by-line, and you're kinda doing what I mentioned above, though not the best approach. The running time of a for loop is the running time of the statements in the loop times the number of iterations.
 

Two Words

Member
For example, let n=5. Then (2*5)! / (5! (5+1)!) = 10! / (5! 6!) = (10*9*8*7*6!) / (5! 6!) = (10*9*8*7) / 5!

So all you need to do is compute 10*9*8*7 and divide it by 5! when n=5.

(edit) I might have jumped ahead without looking at you code line-by-line, and you're kinda doing what I mentioned above, though not the best approach. The running time of a for loop is the running time of the statements in the loop times the number of iterations.

The problem with doing that though is that you must eventually have the integer value of n! in its whole. This limits the size that this function can work on. I suppose if they don't care about it, then they don't care about it. I thought it was neat to extend its usability from 10 to 176 though. As far as a runtime analysis of my method goes, I feel like it's essentially doing the same amount of work even though it technically does 2n loops.
 

Koren

Member
My main concern is that he may argue that this method is not optimized like how he wanted it. I feel like at times, computational analysis will give these "Well actually" answers regardless of the empirical data.
I'm always reluctant to use floats to compute this kind of integers... Between the chances of rounding errors and the missing digits, it's not great. At n=176, you've far below the normalized doubles when you compute 1/(n!), I'd be curious to know whether your last values are actually good.

If you want to check, Cat(176) is exactly, if I'm not mistaken 2202649981138949529709608229856778034894847921317741692970659784491657853623950138141866464005163908232

And Cat(175) = 555369012338453086550713186160469675464940287853618631988328749081229971640226744232350946052584062332

That's a pity that C lacks native arbitrary long integers... Even my calculator is doing it ^_^


Is this some assignement about dynamic programming? Do you have to compute a single one or many/all of them?

If you have a single catalan number to compute, I'd say the method is correct (minus the float issue I talked above)... Cat(n) is nCr(2n, n)/(n/1) and you actually used the nCr(n, k) = n*nCr(n-1, k-1)/k relation which is usually a pretty efficient way to compute the combination.

But, like you saw, you're limited to n=176 because of the way real numbers work.

If you have to compute all of them, or want to go further, you can see that your formula gives Cat(n) = Cat(n-1)*(4*n-2)/(n+1) with Cat(1)=1, which should be an efficient manner to generate all of them. You can keep all computed values in a table, and when you have to compute one, if it's not already in the table, fill the table starting at the biggest computed yet and iterate using the recursion formula.

You can reach Cat(519) this way (by doing the division BEFORE the multiplication), with the first 14 digits corrects if I'm not mistaken.

The exact value for Cat(519)
140239043650914933309771256012337161301472611398544757325664370049865751420453458821350670408676263462548127750393958019426775488055871200139933800366329620082724993869266473333310721268298552396471937748379893211937643818403427162436366946974972682374621242035332097535261433136817732374480806452523112121550

After that, the numbers are too big for IEEE doubles, so you can't possibly go further with doubles.


A better solution to compute the number would be to use an Eratosthene sieve to compute the exponents of the prime decomposition of each integers between 1 and 2n, and when you do your test, adding or substracting those exponents ot as many counters as you have primes. That'll give you the list of exponents for the prime decomposition of Cat(n). It's an exact solution, and will work for as large a n as you want, although computing the actual value will be a bit trickier in C if you want values larger than the larger double (but doable).
 

Two Words

Member
I'm always reluctant to use floats to compute this kind of integers... Between the chances of rounding errors and the missing digits, it's not great. At n=176, you've far below the normalized doubles when you compute 1/(n!), I'd be curious to know whether your last values are actually good.

If you want to check, Cat(176) is exactly, if I'm not mistaken 2202649981138949529709608229856778034894847921317741692970659784491657853623950138141866464005163908232

And Cat(175) = 555369012338453086550713186160469675464940287853618631988328749081229971640226744232350946052584062332

That's a pity that C lacks native arbitrary long integers... Even my calculator is doing it ^_^


Is this some assignement about dynamic programming? Do you have to compute a single one or many/all of them?

If you have a single catalan number to compute, I'd say the method is correct (minus the float issue I talked above)... Cat(n) is nCr(2n, n)/(n/1) and you actually used the nCr(n, k) = n*nCr(n-1, k-1)/k relation which is usually a pretty efficient way to compute the combination.

But, like you saw, you're limited to n=176 because of the way real numbers work.

If you have to compute all of them, or want to go further, you can see that your formula gives Cat(n) = Cat(n-1)*(4*n-2)/(n+1) with Cat(1)=1, which should be an efficient manner to generate all of them. You can keep all computed values in a table, and when you have to compute one, if it's not already in the table, fill the table starting at the biggest computed yet and iterate using the recursion formula.

You can reach Cat(519) this way (by doing the division BEFORE the multiplication), with the first 14 digits corrects if I'm not mistaken.

The exact value for Cat(519)
140239043650914933309771256012337161301472611398544757325664370049865751420453458821350670408676263462548127750393958019426775488055871200139933800366329620082724993869266473333310721268298552396471937748379893211937643818403427162436366946974972682374621242035332097535261433136817732374480806452523112121550

After that, the numbers are too big for IEEE doubles, so you can't possibly go further with doubles.


A better solution to compute the number would be to use an Eratosthene sieve to compute the exponents of the prime decomposition of each integers between 1 and 2n, and when you do your test, adding or substracting those exponents ot as many counters as you have primes. That'll give you the list of exponents for the prime decomposition of Cat(n). It's an exact solution, and will work for as large a n as you want, although computing the actual value will be a bit trickier in C if you want values larger than the larger double (but doable).

Yeah, there is eventually a loss of precision, but the answers up to 176 are at least very close to the true answer. It basically has a couple dozen largest digits correct that is rounded at the smallest digit before rest of the scientific notation comes into play.

I should probably test out how to create arbitrarily large integers in java. I've never done it before. And the other solutions sound interesting. I'll see if I can implement them.
 

Koren

Member
It basically has a couple dozen largest digits
A couple dozen, that's not possible... At best, you'll get 15-16 correct digits, since doubles have a 52 bits fraction part, and 2**52 is 4.5e15. Any correct digits after the first 15 are just luck.

I just tried, numbers up to 171 have 15 correct digits, the you reach denormalized floats, and 172 has 12 correct digits, 173 has 10, 174 has 8, 175 has 5, 176 has 3, and Cat(177) gives 9.07... instead of 8.736...

You can have slightly different results if your computer do computations on extended-80 before converting the results to doubles, though.


That doesn't mean the solution is not good, it's just that there's a loss of precision when n is too big for 1/n! to be a normalized double.
 

Martal

Neo Member
Not sure if this is the right place but here goes.

I'm trying to learn unity and I cant for the life of me figure out how to store the text from an inputfield in scene 2 and compare it to a random number I generated in scene 1. I tried this for example:

//pastebin.com/embed_js/Ly8kSsWA

The randomNumbers0 is from a different script and is working.

Its in C# and I currently am trying it as a separate GameObject.
 

Two Words

Member
A couple dozen, that's not possible... At best, you'll get 15-16 correct digits, since doubles have a 52 bits fraction part, and 2**52 is 4.5e15. Any correct digits after the first 15 are just luck.

I just tried, numbers up to 171 have 15 correct digits, the you reach denormalized floats, and 172 has 12 correct digits, 173 has 10, 174 has 8, 175 has 5, 176 has 3, and Cat(177) gives 9.07... instead of 8.736...

You can have slightly different results if your computer do computations on extended-80 before converting the results to doubles, though.


That doesn't mean the solution is not good, it's just that there's a loss of precision when n is too big for 1/n! to be a normalized double.
Yeah, you're right. I think the problem is that I was using wolfram alpha to compare answers and their solutions seem fall in line with my answers, oddly enough. Definitely not to 2 dozens, but typically more than 10 decimals.

I made the recursive method much faster by storing a table and my method generates valid answers up to 35. I can be certain that my non-recursive function using doubles is perfectly accurate up to that point. Beyond that, longs become too short for the recursive algorithm.
 

Koren

Member
I'd be curious to know what exactly Wolfram alpha returns...

But I'd like to thank you, I just spent half an hour coding in C++ the prime decomposition solution, and that entertained me during my train trip...

If I'm not mistaken, Cat(123456) is close to 1.07756e74321. ^_^

It's less efficient than the recursive solution if you have variable length int support, but you get its prime decomposition...


Edit: on a totally different matter, I find it slightly unnerving that a Python one-liner gives the exact answer as quickly as a 100+ lines C++ program compute an approximation... I really need to look into arbitrary long integers in C++, could be handy one day.

What would you suggest? Boost? GMP? Bigint? ttmath? Something else? I've used GMP and Bigint in the past, but never really did anything complex, most of my arbitrary length integers problem go straight to Python, usually.

(and as for the Python solution...
Code:
def Cat(n):
    return reduce(lambda c,i: c*(4*i+2)//(i+2), range(n), 1)
although I'm sure GvR wouldn't find this pythonic enough ;) )
 
I certainly wouldn't turn down an internship (from anywhere) because of that. I'd just want to ask them if I ended up writing with 4-space indents if they'd care/it'd be an issue. But yeah, it'd be easiest to just use something to make it look however I want locally then convert it when I commit.

Well it'd be easiest to just do whatever the convention says to do. Honestly you're gonna work with a lot of shit coding styles (both real and perceived) in your career. The sooner you stop caring the happier you'll be in the long run.

Anyway i can tell you right now they'll care. A CL that doesn't match the coding standard isn't going in.

Also you don't want to reformat the entire file, work on it, then reformat it again. Some lines are intentionally formatted the wrong way, other times bad formatting went in. In no case do you ever want to format lines that aren't relevant to your CL.

So you can set your editor settings to do 4 space indent if you want, but it's going to be mixed in with 2 space from the surrounding file. Then you format only the diff.

Of course, at that point you wonder if it's really better, and why not just use 2 spaces. When in Rome, and all that...
 

Makai

Member
Not sure if this is the right place but here goes.

I'm trying to learn unity and I cant for the life of me figure out how to store the text from an inputfield in scene 2 and compare it to a random number I generated in scene 1. I tried this for example:

//pastebin.com/embed_js/Ly8kSsWA

The randomNumbers0 is from a different script and is working.

Its in C# and I currently am trying it as a separate GameObject.
http://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html

However, going forward I would recommend against using MonoBehaviours for game logic. Store all of that in normal C# classes and let MonoBehaviours just be the View.
 

Two Words

Member
I'd be curious to know what exactly Wolfram alpha returns...

But I'd like to thank you, I just spent half an hour coding in C++ the prime decomposition solution, and that entertained me during my train trip...

If I'm not mistaken, Cat(123456) is close to 1.07756e74321. ^_^

It's less efficient than the recursive solution if you have variable length int support, but you get its prime decomposition...


Edit: on a totally different matter, I find it slightly unnerving that a Python one-liner gives the exact answer as quickly as a 100+ lines C++ program compute an approximation... I really need to look into arbitrary long integers in C++, could be handy one day.

What would you suggest? Boost? GMP? Bigint? ttmath? Something else? I've used GMP and Bigint in the past, but never really did anything complex, most of my arbitrary length integers problem go straight to Python, usually.

(and as for the Python solution...
Code:
def Cat(n):
    return reduce(lambda c,i: c*(4*i+2)//(i+2), range(n), 1)
although I'm sure GvR wouldn't find this pythonic enough ;) )
Damn, I need to learn Python.
 
So I'm not super clear on how Overloading operators works.

How does the program know which way I want to use the operator?

Like lets say I want to overload the + operator such that it actually subtracts integers.

int a = 3;
int b = 3;

c = a + b (overloaded +)

c becomes 0.

But I want it to actually add if either of the numbers is a float
such that c = a + float(b) = 6.0


How does my program know which + to use? Will it check to see if the right side of the + is an int, and if the left side of the + is an int?
 

Two Words

Member
The nature of what is to the left of the operator dictates what operation it does to what is on the right. It does not check what is on the right, but your overload's definition will state what should be on the right. If it can't properly work out what it expects, then it will not work.
 

vypek

Member
Apparently I did very well, don't know if that's just a blanket statement given to everyone who meets the bar or I actually did above the normal percentile. Either way I'll probably be in consideration for the next round of hires. Which leads to another dilemma, to take another job or wait for this job to open up. I want to make a career at the company I'm applying to if possible.

I'd guess that if they tell you that you did very well then you probably actually did. There doesn't seem to be a real motivation for someone to say you did well if you didn't.

Personally, I think taking something guaranteed is better than waiting on something that isn't. So I would probably take the job that was available rather than wait for a job that may or may not be available to me. Someone else can definitely weigh in though.
 
The nature of what is to the left of the operator dictates what operation it does to what is on the right. It does not check what is on the right, but your overload's definition will state what should be on the right. If it can't properly work out what it expects, then it will not work.

Hmm...

So lets say the syntax was:

int operator+(int b)
{
return this->int - b;
}

Assuming that is right syntax, where exactly is it getting the information that I want it to use this overload with two ints involved? The first int (before operator) is just a return type, the second int (before the b) says what the righthand side should be.

So it knows an int needs to be on the lefthand side from the this->int bit?


And if so, what happens if I have an int on the lefthand side but a float on the right? An error comes up? Or will it default to the regular + operator instead of my overload?
 
Hmm...

So lets say the syntax was:

int operator+(int b)
{
return this->int - b;
}

Assuming that is right syntax, where exactly is it getting the information that I want it to use this overload with two ints involved? The first int (before operator) is just a return type, the second int (before the b) says what the righthand side should be.

So it knows an int needs to be on the lefthand side from the this->int bit?


And if so, what happens if I have an int on the lefthand side but a float on the right? An error comes up? Or will it default to the regular + operator instead of my overload?

You cannot redefine the meaning of operators when applied to built in data types. So you cannot make an overloaded + operator that adds two integers. You *can* make an overloaded plus operator that adds a Foo to an integer though. This would work:

Code:
Foo &operator+(int x, const Foo &y);
Foo &operator+(const Foo &y, int x);

and in this case it selects the function to use based on a complicated algorithm that looks for the "best match" based on how you supplied the parameters.
 
You cannot redefine the meaning of operators when applied to built in data types. So you cannot make an overloaded + operator that adds two integers. You *can* make an overloaded plus operator that adds a Foo to an integer though. This would work:

Code:
Foo &operator+(int x, const Foo &y);
Foo &operator+(const Foo &y, int x);

and in this case it selects the function to use based on a complicated algorithm that looks for the "best match" based on how you supplied the parameters.

Well that solves that!

Thanks.

Any specific reason to use const there? Style?
 

Marcus

Member
hey, so I coded up the card game Dominion in Python. it's playable by up to 4 people in a console window right now, but i wanted to make it available online so only my friends and i could play using it. what would i need to learn to make this playable through a web browser for me and my friends? ive heard of Django and Flask, is that what i should look into?
 

Kalnos

Banned
hey, so I coded up the card game Dominion in Python. it's playable by up to 4 people in a console window right now, but i wanted to make it available online so only my friends and i could play using it. what would i need to learn to make this playable through a web browser for me and my friends? ive heard of Django and Flask, is that what i should look into?

Either of those work but you will probably have to look into WebSocket options if you want it to be real-time. Flask is probably the easiest one to start with because it doesn't include as much as Django does by default.
 

Marcus

Member
Either of those work but you will probably have to look into WebSocket options if you want it to be real-time. Flask is probably the easiest one to start with because it doesn't include as much as Django does by default.

thanks, i'll look into flask and websocket. it needs to be real-time
 
Top Bottom