• 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

Two Words

Member
Yeah, I wasn't sure if an arrayList would work the same way as far as pass by reference or value.

I also believe that you'd never run into a stack overflow issue, but I can't really be sure. From looking at the code, I think you could represent the recursion like a tree. And the height of the tree will be the number of elements concatenated to spell the word. And the depth of the recursion will be the height of the tree. A parent node has 100+ potential children, the children being the next element to append to the word. So you'll only be like 1-10 levels of recursion deep at any given time. This is my guess on the matter, but I've never really done any analysis on how much space a recursive algorithm could use in a worse case or anything like that. Is my description of the recursion correct here?
 
Yeah, I wasn't sure if an arrayList would work the same way as far as pass by reference or value.
I see no issue with passing an ArrayList created outside of the function, then adding to it when you've found a match. It's an object, so Java will pass it by reference. Only primitives are passed by value.
Like cpp_is_king hinted at, technically Java is passing a value that is a reference/pointer to the object itself, but that's unnecessary detail here.

I also believe that you'd never run into a stack overflow issue, but I can't really be sure. From looking at the code, I think you could represent the recursion like a tree. And the height of the tree will be the number of elements concatenated to spell the word. And the depth of the recursion will be the height of the tree. A parent node has 100+ potential children, the children being the next element to append to the word. So you'll only be like 1-10 levels of recursion deep at any given time. This is my guess on the matter, but I've never really done any analysis on how much space a recursive algorithm could use in a worse case or anything like that. Is my description of the recursion correct here?

You've got the right idea, it's good to visualize the call stack like a tree in a recursive algorithm. Each call on the stack potentially has table.length subcalls (though it'll never do that many since you can't possibly match every String in the table to the next part of the word with the values you currently have there), which are the 'children' of that call in your tree and extend the tree horizontally. Those children will make additional recursive calls, which extends your tree vertically as those calls make more calls, etc.

Your code is adding to the call stack every time you find a match in the table that extends pWord, so in the worst case you'd have word be a string of a single character (say, "O"), leading to word.length() calls on the stack before going back up. So you could run into a stack overflow if the input word was long enough to overflow the default stack size. Generally, stack overflow issues commonly arise when the recursive function has an insufficient terminating/leading condition, which leads to the same arguments being recursively used (i.e. no progress) until the stack can't take it anymore. Your function checks if the next table entry actually makes progress before making the next call, so you're good there.
 

Two Words

Member
I see no issue with passing an ArrayList created outside of the function, then adding to it when you've found a match. It's an object, so Java will pass it by reference. Only primitives are passed by value.
Like cpp_is_king hinted at, technically Java is passing a value that is a reference/pointer to the object itself, but that's unnecessary detail here.



You've got the right idea, it's good to visualize the call stack like a tree in a recursive algorithm. Each call on the stack potentially has table.length subcalls (though it'll never do that many since you can't possibly match every String in the table to the next part of the word with the values you currently have there), which are the 'children' of that call in your tree and extend the tree horizontally. Those children will make additional recursive calls, which extends your tree vertically as those calls make more calls, etc.

Your code is adding to the call stack every time you find a match in the table that extends pWord, so in the worst case you'd have word be a string of a single character (say, "O"), leading to word.length() calls on the stack before going back up. So you could run into a stack overflow if the input word was long enough to overflow the default stack size. Generally, stack overflow issues commonly arise when the recursive function has an insufficient terminating/leading condition, which leads to the same arguments being recursively used (i.e. no progress) until the stack can't take it anymore. Your function checks if the next table entry actually makes progress before making the next call, so you're good there.
Thanks! Glad to hear that my thought process was correct.
 

msv

Member
I would. Honestly if your game were more complex I'd give you a different answer, but over-engineering is just as big of a problem as under-engineering.

YAGNI
If your program is not complex enough to warrant proper organization, then you're just testing some rubbish. If you want to actually do something with your code then you should properly organize everything. Either way it's good practice, the most important practice IMO. You'll probably never use Fibonacci, but you sure as hell will need to keep your code clean and organized in each and every (usable) project.
 
If your program is not complex enough to warrant proper organization, then you're just testing some rubbish. If you want to actually do something with your code then you should properly organize everything. Either way it's good practice, the most important practice IMO. You'll probably never use Fibonacci, but you sure as hell will need to keep your code clean and organized in each and every (usable) project.

Knowing when to create abstractions is just as important as knowing how to create them.

AnswerValidator.cs. I'm pretty sure that's going to be a class that consists of one function taking a string and returning true or false, with no state, and no helper functions. Not a good candidate for separating out.

ScoreApplyer.cs. Pretty sure that class is going to look like this:

Code:
class ScoreApplyer
{
    private Game m_game;
    public ScoreApplyer(Game game) : m_game(game) {}
    public void Apply(String word) {
        m_game.AddScore(word.length() * m_game.CountPermutations(word));
    }
}
This is not a good use of an abstraction. You turned 3 lines of code into 8, only to call right back into the game class at every possible point to get some information. This is much better as:

Code:
class Game
{
    int Score;
    private void UpdateScore(String word)
    {
        Score += word.length() * CountPermutations(word);
    }
}
Simple, gets the job done, no pointless abstractions.

If you later decide to go have your score write to a database, upload to a website, compute complicated statistics, keep track of leaderboards, or anything else more complicated than simply updating a single number, then you can think about making a class for it. Simply to house a one line function is not a good use.
 

LionPride

Banned
So I have a problem, I'm using tkinter in Python and I have a couple of assignments. I have to draw a shape and get it to move, but I have no idea how to have it move across the screen from it's original position.
 
So I have a problem, I'm using tkinter in Python and I have a couple of assignments. I have to draw a shape and get it to move, but I have no idea how to have it move across the screen from it's original position.

No idea about tkinter, but a circle for example the way you do it is store the center and radius, have a loop that takes a certain amount of time (say 60ms), and each time through the loop clear the screen, move the center of the circle, and draw it at the new location
 

JeTmAn81

Member
No idea about tkinter, but a circle for example the way you do it is store the center and radius, have a loop that takes a certain amount of time (say 60ms), and each time through the loop clear the screen, move the center of the circle, and draw it at the new location

Yep, it seems useful to understand that computer graphics aren't too different from other kinds of real-time video (film, animation, flip-books). Lots of stuff is just getting completely redrawn so quickly your eye can't even tell.
 

Water

Member
So I have a problem, I'm using tkinter in Python and I have a couple of assignments. I have to draw a shape and get it to move, but I have no idea how to have it move across the screen from it's original position.

The answer in this stackoverflow question shows you how to do something in tkinter repeatedly over time at regular intervals. You could use a simple variable "time_since_start" to keep track of how many milliseconds have passed in real time since the beginning of your animation. Init it to 0, and increase it by 100 every time you draw (if you animate in 100 millisecond steps like in the example). Then in your drawing code you just decide where you want your shape to be at that point in time.

http://stackoverflow.com/questions/11502879/simple-animation-using-tkinter
 

msv

Member
AnswerValidator.cs. I'm pretty sure that's going to be a class that consists of one function taking a string and returning true or false, with no state, and no helper functions. Not a good candidate for separating out.

ScoreApplyer.cs. Pretty sure that class is going to look like this:
Sure, just applying the score isn't really an object. The name itself already indicates that it should be a method, since there is only one function there - applying a score. The logic for validating an answer should definitely be its own class though.

A simple example of basic (possible) organization:

Program.java [initialization, no logic]
Game.java[holds the state of one game]:
- List of Player
- List of Round
- Logic to determine overall winner
- Loop to run rounds
- GameUI
GameUI.java
- Handles display of information and input
Round.java
- Dictionary of Player > Pair<Word, Score>
- Player winner
- Logic to input Word and determine winner of the round
Word.java
- Holds inputted word
- Can process word for validity and permutations
- Stores permutations of word

Also YAGNI refers to functionality, not organization. Organizing your code doesn't offer more functionality, just better readability, maintainability, looser coupling and makes it more adaptable.
 

Water

Member
Also YAGNI refers to functionality, not organization. Organizing your code doesn't offer more functionality, just better readability, maintainability, looser coupling and makes it more adaptable.

Looser coupling? Adaptability? A lot of the time, YAGNI. Bloating your program with more abstraction, more types and functions than necessary can easily make it less adaptable and less readable. Often it's easier to read two unique lines of code in place than have to jump into a separate function to read them.

It takes a long time for newbies to start noticing DRY problems that already exist in their code and refactor to get immediate, concrete improvements. Why would you expect them to make good calls about where it's worthwhile to bloat the code to prepare for some future change that might never happen?
 

msv

Member
Looser coupling? Adaptability? A lot of the time, YAGNI. Bloating your program with more abstraction, more types and functions than necessary can easily make it less adaptable and less readable. Often it's easier to read two unique lines of code in place than have to jump into a separate function to read them.

It takes a long time for newbies to start noticing DRY problems that already exist in their code and refactor to get immediate, concrete improvements. Why would you expect them to make good calls about where it's worthwhile to bloat the code to prepare for some future change that might never happen?
If you name your functions properly it should always be more readable, not less. And what's difficult about going into a function to read the code itself when you need to debug/understand what's happening there? You're consolidating specific functionality to one place where you can easily fix it.

You say it's code bloat, I say it's code organization. I really can't think of any production applications where these principles wouldn't apply. As I said, it's okay to not organize anything and create a bunch of tangled code, but only if you use it for testing some concept or figuring out some frameworks. Or if your application doesn't go beyond 50 lines.

It really depends on what you're referring to with code bloat though. I guess I am somewhat against the exaggerated 'organization' of JEE applications for example.
 

JeTmAn81

Member
I've been trying to improve my coding practices lately with an eye towards working in a new job. I've been a solo developer for the last decade, so I pretty much just write my code however I feel without giving much thought to anyone else using it. Right now I'm reading Uncle Bob's Clean Code.

While the things he says make a lot of sense to me, the actual process of refactoring this huge existing codebase I've got for my main project is really frustrating. Cutting down large functions into smaller chunks which do the exact same thing feels like it just creates a lot of boring overhead, though it's admittedly a lot easier to understand from a semantic perspective when you write specifically-named functions rather than using more abstruse loops and conditional statements directly.

It's hard to know where the middle ground is between being totally unorganized and structuring every single line of code into perfect semantic chunks which will probably never be used by anybody.
 

leroidys

Member
My shitty $10 logitech keyboard is dying as I type this. What are y'alls setups? I've asked around in the mechanical keyboard thread, but it mainly seems geared towards gaming in there. I have a switch sampler, and I definitely prefer the cherry browns or blues over anything else. I'm open to other switch types as well.
 

Two Words

Member
My shitty $10 logitech keyboard is dying as I type this. What are y'alls setups? I've asked around in the mechanical keyboard thread, but it mainly seems geared towards gaming in there. I have a switch sampler, and I definitely prefer the cherry browns or blues over anything else. I'm open to other switch types as well.
I love coding on this keyboard. Embrace the clickity-clack!

http://www.amazon.com/gp/product/B00QI2WPJ8/?tag=neogaf0e-20
 
My shitty $10 logitech keyboard is dying as I type this. What are y'alls setups? I've asked around in the mechanical keyboard thread, but it mainly seems geared towards gaming in there. I have a switch sampler, and I definitely prefer the cherry browns or blues over anything else. I'm open to other switch types as well.

Mechanical keyboards are awesome. The only regret I have is not getting one sooner. Brown switches are my favourite too.
 

Nelo Ice

Banned
Tfw when you finish your first project on your own :D. Just finished my 1st website. And by finished I mean it fulfills all the user stories required from FreeCodeCamp. Since I am following their curriculum.

But anyway confidence just went up tenfold and I'm starting to look for an entry level dev job or internship. Have gotten like 5 votes of confidences that I should start looking. Def feels like now my tech skills are finally starting to catch up to my soft skills since I've been an ace with networking.
 
The answer in this stackoverflow question shows you how to do something in tkinter repeatedly over time at regular intervals. You could use a simple variable "time_since_start" to keep track of how many milliseconds have passed in real time since the beginning of your animation. Init it to 0, and increase it by 100 every time you draw (if you animate in 100 millisecond steps like in the example). Then in your drawing code you just decide where you want your shape to be at that point in time.

http://stackoverflow.com/questions/11502879/simple-animation-using-tkinter
That is NOT how you keep track of time.
 
Mechanical keyboards are awesome. The only regret I have is not getting one sooner. Brown switches are my favourite too.

The only reason I don't have one is that I end up using a few different keyboards in different places during the week. I know I'd start complaining about having to use the other ones if I used a mechanical somewhere and end up spending hundreds on buying more of 'em. Using my friend's mechanical keyboard with MX Blues made me really want one, but I'll keep resisting until I make actual money.
 

meowtapes

Neo Member
My shitty $10 logitech keyboard is dying as I type this. What are y'alls setups? I've asked around in the mechanical keyboard thread, but it mainly seems geared towards gaming in there. I have a switch sampler, and I definitely prefer the cherry browns or blues over anything else. I'm open to other switch types as well.

I just replaced my keyboard with this awesome one which I've really liked so far for both gaming and programming. Cherry MX browns, which are my personal favorite :) It's definitely a bit pricey, I managed to get mine for $150 from a friend that was never used. You can also program it to do tons of cool things with the backlighting, my favorite is the ripple effect that makes colors come from every key you press.

http://www.amazon.com/dp/B0149QBRCA/?tag=neogaf0e-20
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
I think this is pretty off topic for this thread. There's a big thread on this stuff here http://www.neogaf.com/forum/showthread.php?t=458496 as well as a lot of resources that can be easily found.

It is slightly off-topic, but since they mentioned that he enjoys one for their programming I figured I'd ask.

On topic: if I were to get 1-2 books to improve my C++ skills, what would they be?
 

meowtapes

Neo Member
It is slightly off-topic, but since they mentioned that he enjoys one for their programming I figured I'd ask.

On topic: if I were to get 1-2 books to improve my C++ skills, what would they be?

I would 100% recommend the Effective C++ books.
http://www.amazon.com/dp/0321334876/?tag=neogaf0e-20

and then there's the modern one for C++11 and C++14
http://www.amazon.com/dp/1491903996/?tag=neogaf0e-20

I don't know your specific programming interests, but here's a book I really enjoy on design patterns. I do programming for video games so these are very helpful, but they are also good for optimizing your code in general. It's also a really fun read and one of the most interesting books on programming. This isn't specifically for C++, but C++ is how I implemented some of these design patterns for a game I did.
http://www.amazon.com/dp/0596007124/?tag=neogaf0e-20
 
I would 100% recommend the Effective C++ books.
http://www.amazon.com/dp/0321334876/?tag=neogaf0e-20
+1

and then there's the modern one for C++11 and C++14
http://www.amazon.com/dp/1491903996/?tag=neogaf0e-20
-1. This book is so advanced that I can't in good conscience recommend it until you're at the point where you don't need to ask what the next book you should get is.

I don't know of a good introduction to C++11 / C++14. I would honestly probably just recommend Stroustrup's book, which covers C++11 / C++14. There's this book which isn't even out yet so I have no idea about its quality, just found it randomly browsing Amazon.

This probably isn't exactly what you were expecting, but honestly I think everyone should read this book. Sure, it's about how to write secure code, but in the process of learning that, you'll gain a deeper insight into how the compiler compiles your code, which is something that not nearly enough people understand. And the more you understand about how your compiler works, the better code you can write -- and not just from a security standpoint.
 

diaspora

Member
Oh man. I'm quitting school, I can't do this. Coding with pen and paper is just not something I can do, maybe there's something wrong with me but I've hit a wall and its over.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Oh man. I'm quitting school, I can't do this. Coding with pen and paper is just not something I can do, maybe there's something wrong with me but I've hit a wall and its over.

Don't man. Coding with pen and paper sucks, but that's definitely not a reason to quit school. The non-computer thought process that pen and paper requires is a very useful skill to have.

Unless you have a job lined up or something, don't quit school. Just keep plugging away one day at a time. I've thought about quitting a lot, but the short term relief has never been worth it to me.
 

diaspora

Member
Don't man. Coding with pen and paper sucks, but that's definitely not a reason to quit school. The non-computer thought process that pen and paper requires is a very useful skill to have.

Unless you have a job lined up or something, don't quit school. Just keep plugging away one day at a time. I've thought about quitting a lot, but the short term relief has never been worth it to me.
I've never passed a class with pen/paper coding taking up the bulk of finals or tests.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
I've never passed a class with pen/paper finals or tests.

I literally just took a final yesterday that had a significant portion of the work as pen and paper C system code. It was excruciating. But I did the best I could and hope that it's enough for a passing grade. If not, then I'll trudge through it again next semester.

I've failed calculus twice, had to withdraw from three different classes. I've basically paid for an entire semester that was worthless. It fucking sucks.

But I'm going to keep going through it until I succeed. You can make it too.
 

diaspora

Member
I literally just took a final yesterday that had a significant portion of the work as pen and paper C system code. It was excruciating. But I did the best I could and hope that it's enough for a passing grade. If not, then I'll trudge through it again next semester.

I've failed calculus twice, had to withdraw from three different classes. I've basically paid for an entire semester that was worthless. It fucking sucks.

But I'm going to keep going through it until I succeed.
I'd keep doing it if had the finances to pull it off. At this point it might be more prudent to find a job and try part time.
 

Kelsdesu

Member
I literally just took a final yesterday that had a significant portion of the work as pen and paper C system code. It was excruciating. But I did the best I could and hope that it's enough for a passing grade. If not, then I'll trudge through it again next semester.

I've failed calculus twice, had to withdraw from three different classes. I've basically paid for an entire semester that was worthless. It fucking sucks.

But I'm going to keep going through it until I succeed. You can make it too.

Breh...... Assembly destroyed me. I feel you man. Glad to know I am not the only one out there in the struggle.
 

JeTmAn81

Member
I don't understand why you would ask someone to write any specific language on paper. Pseudocode shows that the person understands what they're doing, but knowing language-specific syntax perfectly from memory is next to useless.
 
I literally just took a final yesterday that had a significant portion of the work as pen and paper C system code.
Wait, you had to use C syntax for everything? You couldn't use pseudocode of any kind?

I don't understand why you would ask someone to write any specific language on paper. Pseudocode shows that the person understands what they're doing, but knowing language-specific syntax perfectly from memory is next to useless.
I agree. All the written tests I took allowed pseudocode. I have no idea why you would require exact syntax on a timed exam.

When I TAed an OS course, I didn't care if people wrote their synchronization code in Python, C, or whatever. So long as they clearly showed what basic operations were being performed on a given synchronization object and it was right, I gave the student marks.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Wait, you had to use C syntax for everything? You couldn't use pseudocode of any kind?

Yep. It required syntactically correct and compileable C code snippets for creating and implementing various low level system calls. (handling locks, signals, alarms, etc)

It was a nightmare.
 

diaspora

Member
I've never been allowed psudocode. All of my C++ tests had to be syntactically perfect when coding programs on paper. Surprise of surprises, I passed none of those tests.
 
Yep. It required syntactically correct and compileable C code snippets for creating and implementing various low level system calls. (handling locks, signals, alarms, etc)

It was a nightmare.

I've never been allowed psudocode. All of my C++ tests had to be syntactically perfect when coding programs on paper. Surprise of surprises, I passed none of those tests.
I probably would not have gotten a degree if I had to do that. I understand having to know to write handlers/callbacks, use proper locking, etc. on a test, but making sure it's 100% syntactically correct is just inane. My professors always would take off at most a few marks on an exam if the syntax was waaaaaaaaay out there (unless they couldn't understand the idea of the code at all, in which case losing most of the marks is understandable).
 

diaspora

Member
I've never had a class with coding on the test where psudocode was acceptable. This is college and not even university too >.>

Edit: my C# instructor was at least really flexible with how accurate the syntax had to be
 
I don't understand why you would ask someone to write any specific language on paper. Pseudocode shows that the person understands what they're doing, but knowing language-specific syntax perfectly from memory is next to useless.

Eh.. If it's a test for a class specifically about how to program in a particular language, what else are you going to do? I mean it's not like they ask you to write complicated programs. Just hey, write a program that asks for user input and prints the square of it. Stuff like that, simple stuff. I agree it's hard to get 100% on something like that, but I don't think it's unreasonable to expect someone to be able to pass or even get an ok grade.

I guess some specific examples of what these pen-and-paper questions looked like so we could gauge how complicated they were, but yea.. If a class is about C++, you gotta ask the student more than just what the various keywords do.
 

upandaway

Member
In my first year there were a couple of tests with writing compilable code (C, python and java) but in second year now they've mostly stopped doing it. I feel like the further in you go, the more complex the programming principles that you're testing about, so at that point stop fussing about the syntax and let people focus on the design. Even in "advanced programming" class (almost all C++), if you let people forget the syntax, you can ask much harder questions about garbage collection, threads, design patterns and all that stuff.

We will have some assembly code to write in computer organization but it's gonna be kept to very short code snippets, that's about it. I've seen tests with mountains of braindead code with getters and setters, what's the point
 

squidyj

Member
we had to write a reasonable amount of assembly but we were allowed to bring as much material as we wanted so it only took a check or two over notes to make sure it was correct, syntactically at least.

I think the only language specific courses I took were python and java in my first year and then a pair of assembly courses later on. Everything else there was a language you would do things in, but the language wasn't the point and I don't think it was ever tested like it was the point.

I think we used pseudocode mostly in my data structures and algorithms courses.
 

John_B

Member
Can anyone explain why the following js code gives different scope results? What should I do to manipulate the global array inside the for loop?
Code:
var numbers = [1, 2, 3, 4];
var table = [
  { numbers: numbers }
];

console.log('local');

for (var n = 0; n < numbers.length; n++) {
  var row = table[n];
  
  var lastNumber = row.numbers.pop();
  
  row.numbers.unshift(lastNumber);
  
  table.push(row);
  
  console.log(table[n].numbers);
}

console.log('global')

table.forEach(function(row){
  console.log(row.numbers)
});
 

John_B

Member
Are you trying to reverse the numbers array?

I need to do a complete rotation of the array and also keep each rotation.

It should end up looking like this:

Code:
var table = [
  { numbers: [1, 2, 3, 4] },
  { numbers: [4, 1, 2, 3] },
  { numbers: [3, 4, 1, 2] },
  { numbers: [2, 3, 4, 1] },
];
 

Somnid

Member
Can anyone explain why the following js code gives different scope results? What should I do to manipulate the global array inside the for loop?

What are you getting? An immediate red flag is modifying an array while iterating through it. You should should create a new array for your results.
 
What are you getting? An immediate red flag is modifying an array while iterating through it. You should should create a new array for your results.

Yeah, I haven't bothered debugging this code myself but I'm pretty sure the issue is that the numbers array isn't being copied. You just end up with an array of references to the same array.

Here's an easy way to do a shallow copy of an array in JS:
Code:
b = a.[URL="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice"]slice[/URL]();
 

Snipes424

Member
I've been trying for hours but I just can figure this out.

Here is a breakdown of what I'm trying to do.

I am working with VB scripting in Excel to do the following:

I want to scan a string so that it will select the quantity in a cell and automatically subtract 1.

So if I am pulling something out of inventory I can scan a specific bar code that will subtract 1 from the inventory quantity but set up for multiple items. Any help would be appreciated.
 
Top Bottom