8/20/18
Programming puzzles are great ways to exercise your critical reasoning and problem solving skills, practice algorithmic thinking, and learn syntactic and semantic features of a particular programming language. Here are a few to get started with.
We've seen a solution to this puzzle when we looked at the boolean operator xor
. The went as follows:
void swap(int &x, int &y)
{
x ^= y;
y ^= x;
x ^= y;
}
Try solving it without using xor
.
#include <iostream> using namespace std; // The difference method void swap(int &x, int &y) { if(x != y) { x = x - y; y = y + x; x = y - x; } } int main() { int a = 5; int b = 10; swap(a, b); cout << "a = " << a << endl << "b = " << b << endl; return 0; }
Print a semicolon ;
in C++, without using a semicolon ;
anywhere in the source code.
#include <cstdio> #include <iostream> #define SEMICOLON 59 int main() { while(!printf("%c\n", SEMICOLON)){} // if(printf("%c\n", SEMICOLON)){} int x = SEMICOLON; if(std::cout << static_cast<char>(x) << std::endl) { } }
Given two ints, return the sum without using the +
operator.
#include <iostream> using namespace std; int sum(int x, int y) { return x - (-y); } int main() { int a = 5; int b = 10; cout << a << " + " << b << " = " << sum(a, b) << endl; return 0; }
Given an int, print odd
if it is odd and even
if it is even.
#include<iostream> #include<string> using namespace std; void OddEven(int x) { string array[] = {"even", "odd"}; cout << array[x % 2] << endl; /* Alternatively something that exploits short-circuiting in boolean expressions: * ((x & 1) && printf("odd") || printf("even"); * */ } int main() { int a = 50; int b = 55; cout << a << " is "; OddEven(a); cout << b << " is "; OddEven(b); return 0; }