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

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

by Hand Knit

LLSix posted:

I've been writing C for the last few years and would really like to brush up on c++ for job hunting. What are some good ways/sites to practice c++ coding? I found HackerRank earlier today but so far the problems have been pretty easy and I'm worried I'll blitz through them in a week or two.

Lurkin noob here. I'm just taking my first C++ class. This hackerrank place has the same kinda stuff we're doing as projects. Cplusplus.com is a nice reference that I'm always looking at to see what libraries I need to include, and what the hell things like argv[] mean. The Dentist consider updating that OP? It'd be awesome if someone did. Some links are broken and I didn't find it hellua useful.

Adbot
ADBOT LOVES YOU

Ralith
Jan 12, 2011

I see a ship in the harbor
I can and shall obey
But if it wasn't for your misfortune
I'd be a heavenly person today

Solvent posted:

Cplusplus.com is a nice reference that I'm always looking at to see what libraries I need to include, and what the hell things like argv[] mean.
That site is frequently outright wrong. Use cppreference instead.

Shy
Mar 20, 2010

I don't know if that's better suited for the general programming thread but I've been meaning to ask about C++ standard/compiler progress over the last 15-20 years. If I understand it correctly C++11 and newer is mostly supported across all modern compilers and performs well, but let's say 15 years ago would a team choosing it over C for a large project encounter many additional difficulties compared to now?
I'm not looking for a detailed answer (though if you have an article handy that would be cool), mostly just want to get an idea of how bad C++ compilers used to be compared to C. My C++ experience is reading the first 200 pages of the stroustrup book :downs:

VikingofRock
Aug 24, 2008




Ralith posted:

That site is frequently outright wrong. Use cppreference instead.

Really? I've always thought people just liked the layout of cppreference better. What are some things that cplusplus.com is outright wrong about?

Zopotantor
Feb 24, 2013

...und ist er drin dann lassen wir ihn niemals wieder raus...

Shy posted:

I don't know if that's better suited for the general programming thread but I've been meaning to ask about C++ standard/compiler progress over the last 15-20 years. If I understand it correctly C++11 and newer is mostly supported across all modern compilers and performs well, but let's say 15 years ago would a team choosing it over C for a large project encounter many additional difficulties compared to now?
I'm not looking for a detailed answer (though if you have an article handy that would be cool), mostly just want to get an idea of how bad C++ compilers used to be compared to C. My C++ experience is reading the first 200 pages of the stroustrup book :downs:

15 years ago IIRC we already had the STL and (some) compilers that could handle it. 20 years ago you had cfront and whatever lovely class library your vendor supplied (I'm looking at you, HP codelibs :bahgawd:).

Xarn
Jun 26, 2015

Shy posted:

I don't know if that's better suited for the general programming thread but I've been meaning to ask about C++ standard/compiler progress over the last 15-20 years. If I understand it correctly C++11 and newer is mostly supported across all modern compilers and performs well, but let's say 15 years ago would a team choosing it over C for a large project encounter many additional difficulties compared to now?
I'm not looking for a detailed answer (though if you have an article handy that would be cool), mostly just want to get an idea of how bad C++ compilers used to be compared to C. My C++ experience is reading the first 200 pages of the stroustrup book :downs:

Depends a lot on how much back do you want to go.

It is also important to realize that compilers and code tends to push each other... as compilers get better at aggressively inlining code created by nested templates, people get better at creating nested templates for crazy compile time magic. :v:

Shy
Mar 20, 2010

Xarn posted:

Depends a lot on how much back do you want to go.

I was looking at some developer job positions in gaming industry to get an idea of how their languages and requirements for prospective employees have changed. I figured in, let's say, 1996, C would've been an obvious choice for a new or ongoing project, closer to 2000 I saw a line about "understanding tradeoffs between c and c++", even further the requirements shifted towards C++, and that got me wondering what those tradeoffs were back then. But I guess Zopotantor narrows it down well, it would probably be STL support and vendor libraries that made the most difference.

xgalaxy
Jan 27, 2004
i write code

Shy posted:

I was looking at some developer job positions in gaming industry to get an idea of how their languages and requirements for prospective employees have changed. I figured in, let's say, 1996, C would've been an obvious choice for a new or ongoing project, closer to 2000 I saw a line about "understanding tradeoffs between c and c++", even further the requirements shifted towards C++, and that got me wondering what those tradeoffs were back then. But I guess Zopotantor narrows it down well, it would probably be STL support and vendor libraries that made the most difference.

Most games / game companies don't use STL. Even today.

Shy
Mar 20, 2010

xgalaxy posted:

Most games / game companies don't use STL. Even today.

I'm probably confused then, I thought most companies would use it before the standard library became what it is, they still use the standard library to some extent, right?

Star War Sex Parrot
Oct 2, 2003

Shy posted:

I'm probably confused then, I thought most companies would use it before the standard library became what it is, they still use the standard library to some extent, right?
The STL implementations are probably too slow for gaming purposes. See: EASTL

xgalaxy
Jan 27, 2004
i write code

Star War Sex Parrot posted:

The STL implementations are probably too slow for gaming purposes. See: EASTL

The EASTL is a good example of one large game companies ideas and thoughts and actual implementation.
Other game companies will have their own "base libraries" of containers, and algorithms, etc.
A lot of them will be less template heavy than STL and EASTL.

xgalaxy fucked around with this message at 20:26 on Oct 6, 2016

Ralith
Jan 12, 2011

I see a ship in the harbor
I can and shall obey
But if it wasn't for your misfortune
I'd be a heavenly person today

VikingofRock posted:

Really? I've always thought people just liked the layout of cppreference better. What are some things that cplusplus.com is outright wrong about?
I admit I don't have a current list, because I have better things to do than keep such a list up to date. You can google up people complaining about all manner of historical errors which eventually got fixed, but (perhaps thanks to being a wiki, and thus tending towards rapid error fixes) cppreference has historically been a much more reliable resource. Being easier to navigate certainly doesn't hurt, either.

nielsm
Jun 1, 2009



As far as I know, 15 years ago compiler support for C++98 was still somewhat flaky and you had to be really careful and possibly limit yourself in features used, if you wanted your code to build on a variety of compilers. But all of that improved greatly within the following 5 years.

If you want to see the insanity that could cause, find some really old versions of wxWidgets, version 2.2 or 2.4 should showcase some of the ugly things you had to do if you wanted to work on every compiler.

nielsm fucked around with this message at 23:14 on Oct 6, 2016

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Star War Sex Parrot posted:

The STL implementations are probably too slow for gaming purposes. See: EASTL

Let's be clear here. The STL is not, like, implemented by idealistic idiots who don't give a poo poo about performance. There are some specific data structures and optimizations that game developers like which aren't provided/supported well by the STL, like slab allocation, intrusive linked lists, and hashtables. Other than that, a lot of the differences are trade-offs which aren't necessarily as obvious as some people want to believe; and then there is a huge amount of superstition.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

rjmccall posted:

Let's be clear here. The STL is not, like, implemented by idealistic idiots who don't give a poo poo about performance. There are some specific data structures and optimizations that game developers like which aren't provided/supported well by the STL, like slab allocation, intrusive linked lists, and hashtables. Other than that, a lot of the differences are trade-offs which aren't necessarily as obvious as some people want to believe; and then there is a huge amount of superstition.

Historically, some STL implementations have done all sorts of silly things that perform well in synthetic benchmarks and abysmally in the real world.

Copy-on-write strings, for example.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Copy-on-write strings are a really interesting case.

C++ programs back in the day used to do a really ridiculous amount of copying. That's been somewhat addressed with C++11 and move semantics, so now the level of spurious copying in a typical C++ program is just "too high" instead of "wildly excessive", but of course that's new to this decade. Strings in particular tend to have a fairly simple lifecycle of being built up / broken down in a single step and then copied all over the place; and the STL provides an obvious API for building up a string (stringstream) that in theory ought to be preferred over repeated += and have significantly better performance. So the basic idea of optimizing for copies over direct mutation is actually a pretty sound one. Of course, people who set out to write a "string benchmark" in practice end up writing something that just bangs on mutations instead of reflecting the real workload on the type, but whatever.

The problems are:
  • The language completely betrays copy-on-write types; all sorts of logically non-mutating operations end up looking like mutations in the type system. For example, code like std::string str = ...; char c = str[0]; invokes a non-const subscript operator and thus would naturally do a unique-and-copy check unless you do a lot of complex proxying (which you can't necessarily do with, say, iterators).
  • Copy-on-write reference-counting has to be atomic in a multi-threaded process. Atomic increment/decrement used to be really expensive, even for completely uncontested accesses (typical for copy-on-write data structures). This is much less true now; it's closer to one order of magnitude more expensive than two. But people mostly formed these opinions back then.
  • Streams in the STL are a very bloated and inefficient abstraction; what in principle could be as efficient as "prepare a buffer, append all these things to it, and do a little tidying when you're done" ends up doing a lot of dynamic crap, so just using += is actually seen as a major optimization.
  • Copy-on-write strings aren't really friendly to a small-string optimization because it would add another dimension of complexity to an operation that's already pretty complex. Small-string optimizations can be a major win just from doing less allocation. They also cut down on the costs of spurious copies, since spurious copies of small strings are cheaper and spurious copies of large strings are more likely to be algorithmically significant enough to skew a profile.
  • Copy-on-write types benefit a lot from a specialized optimizer that's aware of them, but library-specific optimizations are not common in C++ compilers.

leper khan
Dec 28, 2010
Honest to god thinks Half Life 2 is a bad game. But at least he likes Monster Hunter.

rjmccall posted:

Copy-on-write strings are a really interesting case.

C++ programs back in the day used to do a really ridiculous amount of copying. That's been somewhat addressed with C++11 and move semantics, so now the level of spurious copying in a typical C++ program is just "too high" instead of "wildly excessive", but of course that's new to this decade. Strings in particular tend to have a fairly simple lifecycle of being built up / broken down in a single step and then copied all over the place; and the STL provides an obvious API for building up a string (stringstream) that in theory ought to be preferred over repeated += and have significantly better performance. So the basic idea of optimizing for copies over direct mutation is actually a pretty sound one. Of course, people who set out to write a "string benchmark" in practice end up writing something that just bangs on mutations instead of reflecting the real workload on the type, but whatever.

The problems are:
  • The language completely betrays copy-on-write types; all sorts of logically non-mutating operations end up looking like mutations in the type system. For example, code like std::string str = ...; char c = str[0]; invokes a non-const subscript operator and thus would naturally do a unique-and-copy check unless you do a lot of complex proxying (which you can't necessarily do with, say, iterators).
  • Copy-on-write reference-counting has to be atomic in a multi-threaded process. Atomic increment/decrement used to be really expensive, even for completely uncontested accesses (typical for copy-on-write data structures). This is much less true now; it's closer to one order of magnitude more expensive than two. But people mostly formed these opinions back then.
  • Streams in the STL are a very bloated and inefficient abstraction; what in principle could be as efficient as "prepare a buffer, append all these things to it, and do a little tidying when you're done" ends up doing a lot of dynamic crap, so just using += is actually seen as a major optimization.
  • Copy-on-write strings aren't really friendly to a small-string optimization because it would add another dimension of complexity to an operation that's already pretty complex. Small-string optimizations can be a major win just from doing less allocation. They also cut down on the costs of spurious copies, since spurious copies of small strings are cheaper and spurious copies of large strings are more likely to be algorithmically significant enough to skew a profile.
  • Copy-on-write types benefit a lot from a specialized optimizer that's aware of them, but library-specific optimizations are not common in C++ compilers.

^a good post. :five:

Not using std::string (or wstring, ..) has been a pretty strong leading indicator that I'm going to be dealing with a house of horrors. At least for projects started in the past 5-ish years. It's very easy for people to write things that are less performant and more broken when they think dealing with strings is easy and people who wrote the STL are obviously dumb because they read something like that but far more nuanced on the internet once.

As with all things, it's not a problem until you've benchmarked. If you aren't in a place where you can benchmark and you don't have a suitable replacement with several years of industrial use behind it, you have better things to be working on than std::string being too slow for your non-extant application.

feedmegin
Jul 30, 2008

leper khan posted:

^a good post. :five:

Not using std::string (or wstring, ..) has been a pretty strong leading indicator that I'm going to be dealing with a house of horrors. At least for projects started in the past 5-ish years.

Counterpoint: anything written using Qt :colbert:

Slurps Mad Rips
Jan 25, 2009

Bwaltow!

leper khan posted:

^a good post. :five:

Not using std::string (or wstring, ..) has been a pretty strong leading indicator that I'm going to be dealing with a house of horrors. At least for projects started in the past 5-ish years. It's very easy for people to write things that are less performant and more broken when they think dealing with strings is easy and people who wrote the STL are obviously dumb because they read something like that but far more nuanced on the internet once.

As with all things, it's not a problem until you've benchmarked. If you aren't in a place where you can benchmark and you don't have a suitable replacement with several years of industrial use behind it, you have better things to be working on than std::string being too slow for your non-extant application.

string_view is definitely worth having but it's really easy to gently caress up an implementation if you don't even know what a quarter of the std::string functions do and have never tried to implement them yourself (and boost::string_ref didn't exist yet :v:)

(It's also easy to adapt string_view if you're stuck with someone's bespoke string type)

LLSix
Jan 20, 2010

The real power behind countless overlords

I'm trying to reteach myself c++ and I found this sample interview question which really threw me for a loop (took me like me almost two hours to wrap my head around the problem and find a decent approach). I think I ended up with basically Kadane's algorithm without tracking the indices of the subsum. Is there a better approach to this? Is there a more efficient way to write this in c++. Critically, did I screw something up?

/*Given an array containing both negative and positive integers. Find the contiguous sub-array with maximum sum.

Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.

Output:
Print the maximum sum of the contiguous sub-array in a separate line for each test case.

Constraints:
1 ≤ T ≤ 40
1 ≤ N ≤ 100
-100 ≤ A[i] <= 100

test input
Example:
Input
3
3
1 2 3
4
-1 -2 -3 -4
5
-2 -1 -2 -3 -4

Output
6
-1
-1
*/

code:
#include <stdio.h>
#include <algorithm>
using namespace std;

// finds the maximum sum of elements in the array
// cannot return 0 if all the elements are negative, must return the smallest negative sum
// this is just a big for loop, so it takes big o time
int max_subsum_of_array(int* array, int size_of_array )
{
/* shouldn't be passing in null arrays */
if( 0 == size_of_array || NULL == array )
    {
    return 0;
    }
int max_sum = array[0];
int running_sum = array[0];
for( int i = 1; i< size_of_array; i++ )
    {
    int cur_sum = running_sum + array[i];
    /* if the new sum is positive, it is the new running_sum
    if the new sum is negative, start over at the new value or
    keep going if the new value is more negative than the current sum*/
    if( 0 < cur_sum )
        {
        running_sum = cur_sum;
        }
    else
        {
        running_sum = max( cur_sum, array[i] );            
        }
    max_sum = max( max_sum, running_sum );
    }
return max_sum;
}

int main() {
int tests = 0;
scanf( "%d", &tests );
for( int test_index = 0; test_index < tests; test_index++ )
    {
    int size = 0;
    scanf( "%d", &size );
    int test_array[size];
    /* build up test input takes big o n time*/
    for( int read_index = 0; read_index < size; read_index++ )
        {
        scanf( "%d", &test_array[read_index] );
        }
    printf( "%d\n", max_subsum_of_array( test_array, size ) );
    }

return 0;
}

LLSix fucked around with this message at 20:48 on Oct 8, 2016

Ralith
Jan 12, 2011

I see a ship in the harbor
I can and shall obey
But if it wasn't for your misfortune
I'd be a heavenly person today

LLSix posted:

I'm trying to reteach myself c++ and I found this sample interview question which really threw me for a loop (took me like me almost two hours to wrap my head around the problem and find a decent approach). I think I ended up with basically Kadane's algorithm without tracking the indices of the subsum. Is there a better approach to this? Is there a more efficient way to write this in c++. Critically, did I screw something up?
Your brace style is... unconventional, and this is really C code, not C++. You also seem to be stack-allocating a dynamic array, which is a language extension and generally not a great idea. What compiler are you using that didn't warn you about that?

Klades
Sep 8, 2011

I didn't check if your algorithm worked or not, but your code reads more like C to me than C++.

I slapped this together, it seems to work.

code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>

// finds the maximum sum of elements in the array
// cannot return 0 if all the elements are negative, must return the smallest negative sum
// this is just a big for loop, so it takes big o time
int max_subsum_of_array(std::vector<int>& array) {
  if (array.size() == 0) {
    throw std::runtime_error("Your array is empty doofus");
  }

  int max_sum = array[0];
  int current_sum = array[0];

  for (auto it = array.begin()+1; it != array.end(); ++it) {
    int next_sum = current_sum + *it;

    if (next_sum > current_sum) {
      // If the sum got bigger keep it
      current_sum = next_sum;
    }
    else {
      current_sum = *it;
    }

    if (max_sum > current_sum) {
      max_sum = current_sum;
    }
  }
  return max;
}


int main() {
  int tests;
  std::cin >> tests;

  for (int i = 0; i < tests; ++i) {
    int size;
    std::vector<int> array;
    std::cin >> size;
    
    for (int j = 0; j < size; ++j) {
      int input;
      std::cin >> input;
      array.push(input);
    }

    std::cout << max_subsum_of_array(array) << std::endl;
  }
}
Mostly I replaced stdio.h stuff with input/output streams, changed the array to a vector, passed it by reference, and took out the unnecessary algorithm dependency since that's really just a one-liner if.
Is this more efficient? I have no idea. If you were going to do much more complicated things I would probably wrap the entire array into an object. Then you could do things like stream the input directly into the object, have the object keeping track of what the elements in the biggest subsum are, etc, and easily access all of that without getting too overly complicated.

Ralith
Jan 12, 2011

I see a ship in the harbor
I can and shall obey
But if it wasn't for your misfortune
I'd be a heavenly person today
That should really be a const reference.

(it should really be a span, but for some reason those aren't going to even be in C++17... can always pull in the GSL, though)

sarehu
Apr 20, 2007

(call/cc call/cc)
You should pass the vector by const reference, there's no reason to use iterators, and there's no reason not to use max_sum = std::min(max_sum, current_sum); in place of your conditional.

fritz
Jul 26, 2003

Klades posted:


I slapped this together, it seems to work.


If I saw this in code review the first thing I'd ask after Ralith's comment about const ref is "why not use a ranged-for".

LLSix
Jan 20, 2010

The real power behind countless overlords

Ralith posted:

Your brace style is... unconventional, and this is really C code, not C++. You also seem to be stack-allocating a dynamic array, which is a language extension and generally not a great idea. What compiler are you using that didn't warn you about that?

Ha, ha, yeah :smith: That makes sense. I've been writing C code for the last few years and I just started trying to relearn the C++ style since that seems like what most open positions need. Do you have any suggestions for learning more C++ style approaches or example code I should look at?

Sorry about the braces. That's just what HackerRank does and since I have a few coding interview tests in it coming up I'm trying to get used to it. No reason you should have to though. It should be tidied up now.

I'm using HackerRank's default C++ compiler right now. Not the C++14 one, the other one. Maybe C++11?

Thank you for pointing out the array. I was a bit surprised it let me get away with that. I should have used malloc/free (or really a vector).

Klades posted:

more c++ version

Thank you. It's helpful to see what someone more familiar with C++ libraries might do.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

sarehu posted:

You should pass the vector by const reference, there's no reason to use iterators, and there's no reason not to use max_sum = std::min(max_sum, current_sum); in place of your conditional.

Except that it's backwards?

Ralith
Jan 12, 2011

I see a ship in the harbor
I can and shall obey
But if it wasn't for your misfortune
I'd be a heavenly person today

LLSix posted:

Ha, ha, yeah :smith: That makes sense. I've been writing C code for the last few years and I just started trying to relearn the C++ style since that seems like what most open positions need. Do you have any suggestions for learning more C++ style approaches or example code I should look at?

Sorry about the braces. That's just what HackerRank does and since I have a few coding interview tests in it coming up I'm trying to get used to it. No reason you should have to though. It should be tidied up now.

I'm using HackerRank's default C++ compiler right now. Not the C++14 one, the other one. Maybe C++11?

Thank you for pointing out the array. I was a bit surprised it let me get away with that. I should have used malloc/free (or really a vector).
You should set up a real compiler locally and configure it to reject non-standard code. If you want to be employable using a language you'll need to be familiar with the tools, after all.

Never use malloc/free in C++. Unless you have a very good reason, you shouldn't even be using new/delete. If you really need to allocate something on the heap, std::make_unique and friends are much less error prone.

You adjusted brace style is still pretty wacky. Most people use something like Klades'.

The best way to learn good style is to make contributions to a project that already has it and where someone qualified will review your changes. Find a major open source project you care about and jump in! You can also review a few different prominent style guides; Google's is popular but a bit outdated.

Ralith fucked around with this message at 21:18 on Oct 8, 2016

sarehu
Apr 20, 2007

(call/cc call/cc)

Subjunctive posted:

Except that it's backwards?

That's why I said "in place of your conditional" :)

Klades
Sep 8, 2011

fritz posted:

If I saw this in code review the first thing I'd ask after Ralith's comment about const ref is "why not use a ranged-for".


sarehu posted:

You should pass the vector by const reference, there's no reason to use iterators, and there's no reason not to use max_sum = std::min(max_sum, current_sum); in place of your conditional.

Round 2:
code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <limits>

// finds the maximum sum of elements in the array
// cannot return 0 if all the elements are negative, must return the smallest negative sum
// this is just a big for loop, so it takes big o time
int max_subsum_of_array(const std::vector<int>& array) {
  if (array.size() == 0) {
    throw std::runtime_error("Your array is empty doofus");
  }

  int max_sum = std::numeric_limits<int>::min();
  int current_sum = 0;

  for (int num : array) {
    int next_sum = current_sum + num;

    if (next_sum > current_sum) {
      // If the sum got bigger keep it
      current_sum = next_sum;
    }
    else {
      current_sum = num;
    }
   
    max_sum = std::max(current_sum, max_sum);
  }
  return max;
}


int main() {
  int tests;
  std::cin >> tests;

  for (int i = 0; i < tests; ++i) {
    int size;
    std::vector<int> array;
    std::cin >> size;
    
    for (int j = 0; j < size; ++j) {
      int input;
      std::cin >> input;
      array.push(input);
    }

    std::cout << max_subsum_of_array(array) << std::endl;
  }
}

Subjunctive posted:

Unless I missed a definition of current somewhere, that doesn't compile.

Typos.

Klades fucked around with this message at 21:52 on Oct 8, 2016

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Unless I missed a definition of current somewhere, that doesn't compile.

Joda
Apr 24, 2010

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

Fun Shoe
This is more a question of algorithm design than C++, but I don't think that algorithm solves the problem, Klades? You seem to assume that as soon as you hit a negative integer the subarray resulting from a further search cannot be larger than the one you are currently investigating, but what about the case {10,10,-1,10,10}. The largest subarray here has the size 39 (includes all elements,) but your algorithm returns 19 because it stops searching and starts a new search at the -1.

I think this works?
C++ code:
int max_subsum_of_array(const std::vector<int>& array) {
  if (array.size() == 0) {
    throw std::runtime_error("Your array is empty doofus");
  }

  int max_sum = std::numeric_limits<int>::min();
  int current_sum = 0;

  for (int num : array) {
      if(current_sum < 0 && current_sum < num)
          current_sum = num;
      else
          current_sum += num;

        max_sum = std::max(current_sum, max_sum);
  }
  return max_sum;
}
E: Fixed redundant expression

Joda fucked around with this message at 23:41 on Oct 8, 2016

csammis
Aug 26, 2003

Mental Institution
I don't think anyone's mentioned it yet but I'm cringing at a vector named array. I know that's not the OP's code but still, yikes.

LLSix
Jan 20, 2010

The real power behind countless overlords

Ralith posted:

The best way to learn good style is to make contributions to a project that already has it and where someone qualified will review your changes. Find a major open source project you care about and jump in! You can also review a few different prominent style guides; Google's is popular but a bit outdated.
That's good advice. Time to eat humble pie.

sarehu
Apr 20, 2007

(call/cc call/cc)

csammis posted:

I don't think anyone's mentioned it yet but I'm cringing at a vector named array. I know that's not the OP's code but still, yikes.

Oh, is it a vector? Over what field?

If C++ has vectors, why can't it have modules?

Fergus Mac Roich
Nov 5, 2008

Soiled Meat

Joda posted:

This is more a question of algorithm design than C++, but I don't think that algorithm solves the problem, Klades? You seem to assume that as soon as you hit a negative integer the subarray resulting from a further search cannot be larger than the one you are currently investigating, but what about the case {10,10,-1,10,10}. The largest subarray here has the size 39 (includes all elements,) but your algorithm returns 19 because it stops searching and starts a new search at the -1.

I think this works?
C++ code:
int max_subsum_of_array(const std::vector<int>& array) {
  if (array.size() == 0) {
    throw std::runtime_error("Your array is empty doofus");
  }

  int max_sum = std::numeric_limits<int>::min();
  int current_sum = 0;

  for (int num : array) {
      if(current_sum < 0 && current_sum < num)
          current_sum = num;
      else
          current_sum += num;

        max_sum = std::max(current_sum, max_sum);
  }
  return max_sum;
}
E: Fixed redundant expression

I believe this will fail on -1, -3. I'm on my phone so I can't check my work properly but it looks like your code returns -4, whereas the answer is -1.

Or 400, -401, 1.

I may be wrong but it would surprise me to learn this problem has a linear solution.

Fergus Mac Roich fucked around with this message at 01:38 on Oct 9, 2016

Malcolm XML
Aug 8, 2009

I always knew it would end like this.
Why not use std::array, you know the size and it's const

Joda
Apr 24, 2010

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

Fun Shoe

Fergus Mac Roich posted:

I believe this will fail on -1, -3. I'm on my phone so I can't check my work properly but it looks like your code returns -4, whereas the answer is -1.

Or 400, -401, 1.

I may be wrong but it would surprise me to learn this problem has a linear solution.

It's very possible that the algorithm is invalid, but those two cases return -1 and 400 respectively.

My thinking is that the only point at which we're no longer interested in the current tally is the one in which it has become negative and the next number in line is of a higher value than the tally. In that case the highest possible tally from the current position is the one from the next value forward. In all other cases we can assume that the current tally is valid as the highest possible value at our current point from the previous reset point (and by extension this holds for the whole array as well.) Remember that max holds the value from when the tally was at its highest point.

Joda fucked around with this message at 02:25 on Oct 9, 2016

Fergus Mac Roich
Nov 5, 2008

Soiled Meat
Okay yeah, sitting down in front of a computer I can see why that should work(and why it doesn't fail in those cases).

Adbot
ADBOT LOVES YOU

eth0.n
Jun 1, 2012

Malcolm XML posted:

Why not use std::array, you know the size and it's const

You'd have to always use a 100 element array, since that's the max size known at compile time. Arguable whether that's better than using a vector.

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