Wednesday, October 26, 2022

Formatting C++ code in Visual Studio

C++ code is usually formatted as follows:
if (condition)
{

}
else {

}

I like the curly braces to be on the same line so that I can see more code in less lines:
if (condition) {

} else {

}

To define this format in Visual Studio 2022, go to Tools - Options - Text Editor - C/C++ - Code Style - Formatting - New Lines and uncheck the boxes at the bottom:
After this change, you can update the format of an existing file with Edit - Advanced - Format Document.

If you also want the code snippet for if to behave similarly, go to Tools - Code Snippet Manager - Visual C++, copy the location of the if snippet file, open the file in a text editor with admin privileges and edit and save it:


Tuesday, October 25, 2022

Initial values in Java and C++

In Java a variable of type int or double has the initial value of zero. But in C++, they can get random values, as you can see in the example below. Note that in C++, the easiest way to set all fields to zero is to use memset.
#include <iostream>
typedef struct {
    int n;
    double values[12];
} DATA;

int main() {
    DATA data;
    std::cout << data.n << ", " << data.values[3] << std::endl;
    memset(&data, 0, sizeof(data)); //set all fields to zero
    std::cout << data.n << ", " << data.values[3] << std::endl;
    std::cout << "Press enter..." << std::endl;
    std::cin.get();
}

Friday, October 14, 2022

Recursive and iterative nested for loops

Consider n nested for loops in Python:

for i_1 in range(n):
    for i_2 in range(n):
        for i_3 in range(n):
            ...
                for i_n in range(n):
                    doSomething()

The recursive way would be:

def nForLoops(n, depth = 0):
    if depth > n-1: doSomething()
    else:
        for i in range(n):
            nForLoops(n, depth + 1)

A simple iterative function could be written using the observation that doSomething() is called n^n times:

def nForLoops2(n, counter = 0):
    while counter < pow(n, n):
        counter += 1
        doSomething()

TODO: How could we write it iteratively using stack data structure?

Wednesday, October 5, 2022

Reducing maintenance effort

You should strive to design simulations that require minimal maintenance. The ideal is to create a simulation whose only maintenance work is proving that it is working correctly when there is a problem in the system of which your simulation is part of. A good way of reducing the proof effort is to have unit tests with good coverage and a developer handbook containing frequently asked questions and troubleshooting sections. Of course, you cannot reach this goal at the beginning, you will get closer to it with every iteration.