Skip to content

Instantly share code, notes, and snippets.

@PietroJomini
Last active February 27, 2020 23:56
Show Gist options
  • Save PietroJomini/3ee2180903cafabd52b7eca7c3121eb6 to your computer and use it in GitHub Desktop.
Save PietroJomini/3ee2180903cafabd52b7eca7c3121eb6 to your computer and use it in GitHub Desktop.
Bad Code Challenge - Phone Number Formatter
/*
https://www.reddit.com/r/badcode/comments/fa9hoa/bad_code_coding_challenge_31_phone_number/
On invalid input, return "πŸ˜’"
I don't know what the hell I did,
and I won't even start listing the problems with this code.
Enjoy
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#define VOID(name) void name
#define LINE(line) line;
#define LABEL(name) LINE( name: {} )
#define GOTO(name) LINE( goto name )
#define MAIN(code) VOID( main )() CODE( code )
#define CODE(code) { LINE( code ) }
#define DO(what) while(true) CODE( LINE(what) LINE(break) )
#define PRINTS(s) DO( printf("%s\n", s) )
#define TEST(what) DO( assert(what) )
#define EQUALSS(a, b) (strcmp(a, b) == 0)
#define EQUALS(a, b) (a == b)
#define LEN(a) strlen(a)
#define CP(name) char *name
#define INT(name) int name = 0
#define FORL(iter, string) for (; iter < LEN(string); iter += 1)
#define RETURN(what) LINE( return what )
#define IF if
#define ELSE else
CP( number_format ) ( CP( number ), CP( format ) ) CODE(
LINE( CP( res ) = malloc(0) )
GOTO(verify)
LABEL(end)
RETURN( res )
LABEL(magic)
LINE( INT( kk ) )
LINE( INT( ii ) )
FORL( ii, format ) CODE(
LINE( res = realloc(res, LEN(res) + 1) )
IF( EQUALS( format[ii], '#' ) ) CODE( res[ii] = number[kk++] )
ELSE CODE( res[ii] = format[ii] )
)
GOTO(end)
LABEL(verify)
LINE( INT( k ) )
LINE( INT( i ) )
FORL( i, format ) CODE ( IF( EQUALS( format[i], '#' ) ) CODE( k += 1 ) )
IF( !EQUALS( k, LEN( number ) ) ) RETURN( "πŸ˜’" )
GOTO(magic)
)
MAIN(
TEST( EQUALSS( number_format( "1234567890", "(###) ###-####" ), "(123) 456-7890" ) )
PRINTS( number_format ("1234567890", "(###) ###-####" ) )
TEST( EQUALSS( number_format( "07123456789", "##### ######" ), "07123 456789" ) )
PRINTS( number_format( "07123456789", "##### ######" ) )
TEST( EQUALSS( number_format( "0007123456789", "+## (###) ### #####"), "+00 (071) 234 56789" ) )
PRINTS( number_format( "0007123456789", "+## (###) ### #####" ) )
TEST ( EQUALS( number_format( "123456789", "" ), "πŸ˜’" ) )
TEST ( EQUALS( number_format( "", "### OwO ###" ), "πŸ˜’" ) )
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment