WorkWorld

Location:HOME > Workplace > content

Workplace

Some Simple but Fun Tricks in Programming

February 10, 2025Workplace1833
Some Simple but Fun Tricks in Programming Programming is not just abou

Some Simple but Fun Tricks in Programming

Programming is not just about solving complex problems; it's also about maintaining code that is both efficient and elegant. Here are some simple yet fun tricks in programming that you can teach to new programmers or include in your own codebase. These techniques can help improve your understanding of how the hardware and compiler work, as well as provide some nifty solutions to common coding problems.

Swapping Values Without a Third Variable

One of the most common tricks in programming is swapping the value of two variables without using a third variable. This can be done using the XOR bitwise operator (^) in a way that avoids unexpected side effects.

int x  1, y  2;x ^ y;y ^ x;x ^ y;

While this approach is elegant, it can backfire if you're swapping values in an array and end up swapping an index with itself, zeroing the value at the index. To avoid this, an alternative approach is:

int x  1, y  2;x  x ^ y;y  x - y;x  x - y;

However, this alternative method now carries the risk of overflow, as arithmetic is performed with integers, which can lead to incorrect results if the values exceed the range of the integer type.

Boolean Expressions That Evaluate to Integers

In C, a boolean expression evaluates to an integer, allowing you to perform operations without using explicit if statements. For example, to count how many random points are inside a circle, you can use a single line:

float radius  1.0;int count  0;for (int i  0; i  100; i  ) {  float x  (float) rand() / RAND_MAX;  float y  (float) rand() / RAND_MAX;  float dist  sqrt(pow(x, 2)   pow(y, 2));  count   (dist - radius) 

The C standard ensures that boolean expressions evaluate to 1 if true and 0 if false, making this possible.

Box-Muller Transformation

The Box-Muller transformation is a powerful method to generate normally distributed random numbers from a uniform distribution. This is particularly useful for simulations and gaming applications:

double box_muller(double mu, double sigma) {  static double z0, z1;  static int gen  0;  gen  !gen;  if (!gen) return z1 * sigma   mu;  double r  sqrt(-2.0 * log((double) rand() / RAND_MAX));  double a  2.0 * M_PI * (double) rand() / RAND_MAX;  z0  r * cos(a);  z1  r * sin(a);  return z0 * sigma   mu;}

This function builds on the static variable type to provide persistence between function calls. It’s a great way to include more complex mathematical operations in your code.

Pointer Tricks for String Copying

Copying strings is often a critical operation in programming, especially when dealing with memory management. Here’s a simple trick for copying strings without using if statements:

void copy_string(char *dst, char *src) {  while (*dst  *src) {    dst  ;    src  ;  }}

This assumes the strings are properly null-terminated and that dst is large enough to hold src.

Traversing a Grid Using Trigonometry

For teaching basic trigonometry and understanding the importance of efficiency, consider this for loop that scans an 8-direction grid:

for (float angle  0; angle  2 * M_PI; angle   M_PI / 4) {  float dx  round(cos(angle));  float dy  round(sin(angle));  printf("%f %f
", dx, dy);}

While this is a complete waste of CPU cycles, it addresses the common question of “when will I ever use math” by including basic trigonometry.

Counting Set Bits with the SWAR Algorithm

The SWAR (SIMD within a Register) algorithm is an efficient method to count the number of set bits in an integer. It uses bitwise operations to achieve this with minimal instructions:

int numberOfSetBits(unsigned int i) {  i  i - i  (i   1)  55555555;    // Isolate bits  i  i  (i   1)  33333333;        // Isolate chunks of 2 bits  i  i   (i >> 2)  0F0F0F0F;       // Sum the chunks  return i   (i >> 4)  00FF00FF;    // Sum the remaining chunks}

This code elegantly counts the set bits in a 32-bit integer, demonstrating bit manipulation techniques and the importance of optimization.

Bitwise Shifting for Multiplication and Division

Bitwise shifting is a powerful technique for performing multiplication and division by powers of two:

int x  4, y  4;printf("%d", x > y);   // Div by 2^y

In C, the left shift operator () and right shift operator (>) can be used to multiply or divide by powers of two, respectively.

Zeroing Out a Struct

Another useful trick is zeroing out a struct using memset:

struct mystruct {  int x, y, z;  float a, b;  char c;};mystruct mystruct;memset(mystruct, 0, sizeof(mystruct));

This sets all fields of the struct to zero, which is often necessary during initialization. Similarly, memcpy can be used to duplicate information in a struct.

90-Degree Turns on a 2D Grid

To make 90-degree turns on a 2D grid, you can use a combination of bitwise operations and a direction variable:

int dx  0, dy  1; // Assuming this is initializeddy  dy ^ 1 - dir  TURN_LEFT  1;dx  dx ^ 1 - dir  TURN_RIGHT  1;dy ^ dx;dx ^ dy;dy ^ dx;

This assumes the player is facing left, right, up, or down. It ties together various bitwise techniques and can be a fun, albeit inefficient, way to demonstrate basic programming concepts.

One of the best "tricks" is the ones you figure out on your own. These techniques may not be suitable for a proper coding scenario, but oh, the joy and satisfaction that come from finding what you can get away with! Happy coding!