r/ProgrammerHumor • • Feb 05 '18

StackOverflow in a nutshell.

Post image
16.2k Upvotes

1.2k comments sorted by

View all comments

Show parent comments

0

u/[deleted] Feb 05 '18

[deleted]

72

u/Kinglink Feb 05 '18

At the very least lay out the answer. I fully get "I don't want to help you cheat" but if you have a question like "How do I reverse a string?" You CAN answer the question without making it copy and pastable.

"Go through the string to get the length of the string, or use Strlen() Then use a for loop to cycle between 0 to half the length. For each value, exchange the string pointer + integer with string pointer + length - integer. Now you should have a reversed string" should be a good answer.

I've left a few minor issues and a few optimizations as well as edge cases in there as well, I answer the question but still leave the OP the challenge of coding it and improving it, and testing it.

71

u/[deleted] Feb 06 '18 edited Feb 06 '18

I would give them the answer and explain why it's correct.

I know I'm probably helping someone cheat, but I find that people generally want some sort of reference.

So, my answer would be something like:

Think about your question for a bit - You want to read the string backwards. How do you read something backwards? You read it anti-forwards. Now, think about how you would read something forwards with a for loop. (Assume you want to reverse the string s which is defined somewhere else.)

for (int i = 0; i < s.Length; i++) { ...s[i]... }

Look closely at that loop syntax - we're starting at 0, incrimenting by one each loop, and exiting when i < s.Length is no longer true. We can reverse that by starting at s.Length-1(the last value where the loop would pass), decrementing by one each loop, and terminating at zero (or when i >= 0 is no longer true).

for (int i = s.Length-1; i >= 0; i--) { ...s[i]... }

Now we have our loop. Let's make a temporary string to store the reversed string in, then assign it to the original string.

{
    string tmp = ""; //An empty string because we will be using `+=`
    for (int i = s.Length-1; i >= 0; i--) {
        tmp += s[i]; //add the character to the new string in reverse order
    }
    s = tmp; //assign the value before exiting the block
}

One more thing. This method deals with a lot of overhead data. You can do what is called an "in-place" reversal by simply switching values around. This will also take up half the amount of loops of our previous example. For practice, see if you can figure out what's happening here:

for (int i = 0; i <= (s.Length-1)/2; i++) {
    char temp = s[i];
    s[i] = s[s.Length-(i+1)];
    s[s.Length-(i+1)] = temp;
}

9

u/Nefari0uss Feb 06 '18

Those kind of answers are the best. In depth, gives details as to what's happening, and provides clear cut examples on how to do something.

9

u/PM_ME_YOUR_BOOO_BEES Feb 06 '18

You are a good person and it is answers like yours that helped me (and many, many others surely) when I was first trying to learn programming.

1

u/Thatguy145 Feb 06 '18

I am a new programmer trying to learn c++. This was a very cool answer - I wouldn't have even thought of doing string reversal like this. Very neat!

5

u/PTRWP Feb 06 '18

Pretty off topic here, but why did you do the revered string like that? I'm still learning, but I've reversed strings by creating a new string then using for (i=string.length(); i>0; i--) and within the loop adding the current character to the end of the new string. I made it into a method so I haven't bothered to redo it in a different way since.

4

u/ar-pharazon Feb 06 '18

it avoids allocating a new string (though it is destructive, meaning that if you needed your original, unreversed string, you're going to have to reverse it again).

your method has the benefit of not destroying the original, but the particular way you wrote it is prone to triggering extra allocations. if you're using java, consider the following:

String forwards = "forwards";
String rev = "";
for (int i = forwards.length() - 1; i >= 0; i--) rev = rev + forwards[i];

in every iteration of the loop, we're actually discarding the old value of rev and replacing it with a copy that has the new character appended. this means we're generating a lot of unnecessary garbage.

if, on the other hand, you're in c++ using something like string::append, you're probably going to end up doing a vector resize (or similar operation) at some point.

but the bottom line is that extra allocation is unnecessary because you know beforehand exactly how much memory you need: forwards.length() characters. the java code to do this with only one allocation is roughly:

String forwards = "forwards";
char[] rev = new char[forwards.length()];
for (int i = 0; i < forwards.length(); i++) rev[forwards.length() - i - 1] = forwards[i];
String result = new String(rev);

c++ would be similar, though you could use the fill constructor rather than having the intermediate char array.

1

u/PTRWP Feb 06 '18

Thanks for the explanation

1

u/Kinglink Feb 06 '18

So what are we trying to do is important?

Usually we're trying to reverse a string in place. In this case using a second string/buffer is completely unnecessary and wasteful, especially on huge strings. If on the other hand we're trying to make a second string that's the reverse of the first your method is acceptable. However make sure you reserve or allocate the correct size of the string before hand otherwise you'll be doing memory allocations all over the place.

Assuming you just want to reverse a string in place, you only need 1 extra byte (unless you want to get real fancy and use Xor)

You also only need to do it for half. So here's how I'd do it.

char*  pStr = blah blah blah
int32 nStringLength = string.length();
for (int32 i = 0; i < nStringLength/2; ++i)
{
    char temp = pStr[i];
    pStr[i] = pStr[nStringLength - i - 1];
    pStr[nStringLength - i - 1] = temp;
}

A couple notes. Notice that it'll only loop 2 times on a 5 character string, as the 3rd (middle) character is already in the right place. ++i is better than i++ because i++ stores the value of i, increments it and then returns the stored value of i, a minor optimization but in general try not to use i++ or i--.

Let's talk a crazier way. Xor Swapping, you can replace the inside of the function with this.

pStr[i] = pStr[i] ^ pStr[nStringLength - i - 1];
pStr[nStringLength - i - 1] = pStr[i] ^ pStr[nStringLength - i - 1];
pStr[i] = pStr[i] ^ pStr[nStringLength - i - 1];

This does the same swap but doesn't require an additional memory location.

1

u/SicSemperTyranator Feb 06 '18

Yea software answers are a bit easier to answer in that way. the EE site is straight dickery. I tried to get someone to help me with some HDL and it was a hellscape. God forbid you try to work through circuit analysis with there help

0

u/fjshflg Feb 06 '18

Would anybody expect a lab tutor to say “that sounds like a homework question”?

Yes. Lab tutors at my university across all the faculties I have personal knowledge of were specifically prohibited from assisting you with assignment questions. They could help with questions about how to find appropriate resources to use to teach yourself, provide limited guidance about the appropriateness of sources, help you with similar questions, etc. But yes, I was personally asked “is this an assignment question” on multiple occasions when asking for assistance, and asked that question myself when I was a tutor.

-28

u/ythl Feb 05 '18

Would anybody expect a lab tutor to say "that sounds like a homework question"?

No, but you are paying the lab tutor/professor to help you. How much are you paying SO contributors to help you?

0

u/[deleted] Feb 05 '18

[deleted]

→ More replies (13)

0

u/[deleted] Feb 06 '18

[deleted]

-5

u/ythl Feb 06 '18

You don't need to help them, but if you don't want to help just don't respond.

And yet, people in this thread are complaining about unanswered questions

It's like walking up to an injured person, identifying yourself as someone who can help, but spit in their face and walk off - it's much better to either leave them without presenting yourself as an asshole or even better help them.

No, it's like going up to a group of panhandlers sucking up the resources of your employees and asking them to change the way they are acting. "We don't like you panhandling. Please try something else."

→ More replies (2)

9

u/chooseauniqueusrname Feb 06 '18

You must hate the concept of Open Source Software

1

u/ythl Feb 06 '18

And why would I hate the concept of OSS?

7

u/chooseauniqueusrname Feb 06 '18

Free contributions. You’re obviously not in the market of helping others out just because it’s the nice thing to do. How much do you charge per bug bounty?

6

u/T-Dot1992 Feb 06 '18

Let me guess, you’re one of the wankers who downvote people for asking questions on SO. It sure sounds like it.

1

u/ythl Feb 06 '18

Only if I google their question and literally the exact same question is the number one link.

10

u/T-Dot1992 Feb 06 '18

Every programming problem is different once you go beyond the basics. No piece of code is the same.

I suggest you stay away from SO; the site is already infested with unhelpful assholes.

→ More replies (9)