Compile-time filename processing

To break another blogging dry spell after having moved to London, a fun (meta-)programming challenge:

Write a C++ 11 program that only compiles successfully when the filename has a numeric prefix that is a prime number. For example, if the file is named 997something.cc it should compile successfully, but it should fail if the filename is 57another.cc or 130.cc.

As compile-time processing is limited, it is acceptable to only handle relatively small numbers. But all numeric prefixes below 1000 should be handled (and not via enumeration :D).

To prove I have a valid solution, I am attaching some tests:

mchouza@nbmchouza:~/Desktop/mchouza-priv/prime-naming$ ll
total 16
drwxrwxr-x  2 mchouza mchouza 4096 May 14 21:29 ./
drwxrwxr-x 12 mchouza mchouza 4096 May 14 21:13 ../
-rw-rw-r--  1 mchouza mchouza  995 May 14 21:16 base.cc
-rwxrwxr-x  1 mchouza mchouza  258 May 14 21:29 test.sh*
mchouza@nbmchouza:~/Desktop/mchouza-priv/prime-naming$ sha256sum base.cc 
5c56fd3b0e337badcb34b9098488d28645c957c9d8f864594136320f84e0d15b  base.cc
mchouza@nbmchouza:~/Desktop/mchouza-priv/prime-naming$ cat test.sh 
#!/bin/bash
echo "Printing the exit codes when compiling with names from $1.cc to $2.cc..."
for n in `seq $1 $2`; do
  ln -s base.cc $n.cc
  g++ -std=c++11 -pedantic -Wall $n.cc -o delete-me 2>/dev/null
  echo "  $n.cc -> $?"
  rm $n.cc
done
rm -f delete-me
mchouza@nbmchouza:~/Desktop/mchouza-priv/prime-naming$ ./test.sh 10 20
Printing the exit codes when compiling with names from 10.cc to 20.cc...
  10.cc -> 1
  11.cc -> 0
  12.cc -> 1
  13.cc -> 0
  14.cc -> 1
  15.cc -> 1
  16.cc -> 1
  17.cc -> 0
  18.cc -> 1
  19.cc -> 0
  20.cc -> 1
mchouza@nbmchouza:~/Desktop/mchouza-priv/prime-naming$ ./test.sh 990 1000
Printing the exit codes when compiling with names from 990.cc to 1000.cc...
  990.cc -> 1
  991.cc -> 0
  992.cc -> 1
  993.cc -> 1
  994.cc -> 1
  995.cc -> 1
  996.cc -> 1
  997.cc -> 0
  998.cc -> 1
  999.cc -> 1
  1000.cc -> 1
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s