#Shortest C++ Code Challenge

17 messages · Page 1 of 1 (latest)

languid dew
#

I am new to C++, but I do have some experience in C, It took me couple hours using AI and Google to create this, I am obsessed over a code being as compact and as short as possible, so I wondered, is it possible to create shorter code for these functions, the Challenge is for them to be as short as possible and still to work assuming that user always gives valid inputs, the first one should turn roman numerals into int and the second one should turn integer into a roman numeral, can anyone make them shorter than I did, all text used in includes, using,... counts, main function does not count and is not included, new lines and tabs at the beginning of the lines do not count and can be used so code can be more readable, but spaces do count although with less priority than regular characters. Everything else such as speed and efficiency of the functions does not matter as long as the code is as short as possible.

brazen hawk
#

post the code here, should be short enough 😉

old jasperBOT
#
How to Format Code on Discord
Markup

```cpp
int main() {}
```

Result
int main() {}
languid dew
#

#include<iostream>

int o(std::string s){
int a=0,b=0,i=s.size(),j,k;
for(;i--;a+=j<b?-j:b=j)for(j=1,k=0;"IVXLCDM"[k]!=s[i];k++)j*=k%2?2:5;
return a;}

std::string f(int n,int i=0){
int v[]={1000,900,500,400,100,90,50,40,10,9,5,4,1};
std::string r[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
return i==13?"":n<v[i]?f(n,i+1):r[i]+f(n-v[i],i);}

#

I feel like the second one can be improved significatly, I just have no idea how

verbal bison
#

I think instead of "..."[k]!=s[i];k++) you can write "..."[k++]!=s[i]; and change k%2?2:5 to k%2?5:2

#

another idea I had: replace std::string r[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"} with auto r="M\0CM\0D\0CD\0C\0XC\0L\0XL\0X\0IX\0V\0IV\0I" and use r+5*i/2 instead of r[i].

#

dunno how much that saves, if anything

#

but it should be a couple of characters shorter

#

if that counts, you can also shorten that string further by replacing \0 with the actual null character. Maybe you need a raw string literal for that, I haven't tested this

languid dew
verbal bison
#

C strings are null termianted by convention, and string literals decays to const char pointers

languid dew
verbal bison
#

in your code it's two characters, \ and 0

#

but there's also the unprintable character with ascii value 0

languid dew
#

and how do I use it in my code?

verbal bison
#

you find a way to write (or paste) this character, then use that instead of \0