Space placement and format in Code Golf (Shortest Code)

Most of the tasks require right formatting (e.g. “a b” and not "a b ") of the spaces. In fastest this isn’t a problem. However, I haven’t found a short solution in C++, to put the spaces in the right order. Is there one?
Appreciate any help.

1 Like

I don’t understand exactly your question but usually to deal with inputs/outputs and have them properly formated your best solution is scanf/printf or gets/puts.
And more generally, C++ features should be avoided in golf, so if you really want to stick with C++ instead of golfing with a more suitable language (Python, JS, ruby, Perl, PHP), I’d suggest you to code in C.
Cause in C golf you can just go straight away like this without importing anything:

main(){[your script here];}

Additionally, if you need to declare integers a, b, c and a must be initialized to 0 (and b and c don’t matter), you can do it like this:

a;main(b,c){[end of the script];}

This trick cannot be done in C++. In C++ you must import at least the C I/O functions and the shortest module containing them is map (or ios) so the equivalent in C++ of the code above would be:

main(){int a=0,b,c;[end of the script];}

That’s 20 chars longer !


thanks for your useful answer. I will definitely look more into these languages.
It is my first time posting, so thanks for pointing out, to write more detailed.

Actually, I had a particular problem. Say, you have integers 1,2 and 3 (and probably more) and you want to print them out.
So you just write

for(int i = 1; i < n; i++)
    cout<<i<<" ";

However, that won’t be accepted, because the result should be “1 2 3” and not "1 2 3 " (the latter has one space more).
So you have to write

for(int i = 1; i < n; i++)
      cout<<" ";

So, finally me question is, if there is a shorter way to put the right spaces.

1 Like

You could use ternary ( ? : ) which exists in lots of other languages too

int v[3] = {1,2,3};
for(int i = 0; i < 3: i++)
     cout<<(i?" ":"")<<v[i];

Of course, It is an example not a full golfed code :wink:

Even more tricky …

    cout << " "+(i<1) << v[i];

but i’ll let you find why this works :smiley:


Thank you very much, that was exactly what i was looking for. Also thanks for letting me mess around with it a bit :slight_smile:

I just remembered this thread and I noticed that I only know that the x in

cout<<" " + (x);

represents the number of chars which will be skipped in printing out.
However, even after searching on the internet, I don’t know why. Do you have any good ressource to look it up?

+k after a string means a shift of k.
(i<1) is a boolean, the + calls for an integer so the boolean is understood as an integer, false will be 0 and true will be 1.
So if i<1, there will be a shift of 1 and the string " " will become “”, else there won’t and the string will remain " ".

1 Like