Archive
The modulo operation is not that trivial
Surprise
In Python, -1977 % 100 = 23. In JavaScript, -1977 % 100 = -77. WTF?
Explanation
Modulo in different languages has different meaning! It’s not like the plus (+) operator which means the same thing in every language when applied for two integers, for instance.
In Python:
a % b = a - (b * floor(a / b))
In JavaScript:
a % b = a - (b * truncate(a / b))
For example, if a = -1977 and b = 100, then a / b is -19.77. But! floor(-19.77) is -20, while truncate(-19.77) is -19. Hence the difference!
I tested some languages and got the following result:
Group 1 (languages using floor()): Python, Lua
Group 2 (languages using truncate()): C, C++, D, Java, JavaScript, C#, Go, Rust, Nim, Kotlin, Pascal, Swift
Some more examples in Python and in JavaScript
Python:
>>> 1977 % 100
77
>>> -1977 % 100
23
>>> 1977 % -100
-23
>>> -1977 % -100
-77
JavaScript:
> 1977 % 100
77
> -1977 % 100
-77
> 1977 % -100
77
> -1977 % -100
-77
How to imitate Python?
How to have a Python-like modulo in other languages? Here is a C function:
int modulo(const int a, const int b)
{
return ((a % b) + b) % b;
}
Launch ./a.out painlessly
I teach C programming and I always typed the following:
$ gcc main.c
$ ./a.out
Hello World!
( I use shell completions, so actually it’s enough to type: ./a<TAB> )
However, yesterday one of my students surprised me. He launched his program like this:
$ a
Hello World!
I asked him what that “a” is. He told me that he created an alias:
alias a="./a.out"
Nice! :) I will also use this trick from now on.
Test if a number is even
Problem
You want to test if a number is even.
Solution
Well, the well-known solution is to test the value of n modulo 2. If it’s zero, then the number is even, otherwise it’s odd. But how fast is it?
Here is a Pascal snippet:
procedure Main();
var
i: Integer;
total: Integer = 0;
begin
for i := 0 to MaxInt-1 do
begin
if i mod 2 = 0 then
total += 1;
end;
WriteLn(total);
end;
Compile and run:
$ fpc -O3 main.pas
$ time ./main
1073741824
./main 16,61s user 0,00s system 99% cpu 16,634 total
16 seconds! That’s a lot… Let’s try an alternative approach. Let’s do bitwise operations. You can use the bitwise AND operator and check the least significant bit of the integer. If the least significant bit is 0, the number is even; if it’s 1, the number is odd.
procedure Main();
var
i: Integer;
total: Integer = 0;
begin
for i := 0 to MaxInt-1 do
begin
if (i and 1) = 0 then // <- HERE
total += 1;
end;
WriteLn(total);
end;
$ fpc -O3 main.pas
$ time ./main
1073741824
./main 1,19s user 0,00s system 99% cpu 1,189 total
Much better :) But what about C? Let’s try it:
int main()
{
int total = 0;
for (int i = 0; i < 2147483647; ++i)
{
if (i % 2 == 0) // version 1
// if ((i & 1) == 0) // version 2
{
++total;
}
}
printf("%d\n", total);
return 0;
}
$ gcc -O3 main.c
$ time ./a.out
1073741824
./a.out 0,26s user 0,00s system 99% cpu 0,264 total
I tried both versions (modulo 2 and bitwise AND) and got the same result. I think the optimizer recognizes modulo 2 and converts it to bitwise AND.
.gitignore generator
Advent of Code 2018 is over
Similarly to last year, I participated in Advent of Code again. Last year I could finish it in time, but this year I missed some days. As today was the last day of the challenge, here is my result:

This year the exercises were harder than last year. My solutions are on GitHub: https://github.com/jabbalaci/AdventOfCode2018 . This year I used the Nim programming language.
[Nim] cross-compile under Linux to Windows
Problem
You are under Linux, and you can produce an executable binary with the Nim compiler. However, you would like to produce a Windows EXE too. We want to stay under Linux and we want to produce the EXE on Linux. How to do that?
Solution
On Manjaro, I had to install this package:
$ yaourt -S mingw-w64-gcc-bin
It’s a cross-compiler that we’ll use for producing the EXE.
Let’s take a simple Nim source (hello.nim):
echo "hello windows"
Now cross-compile it:
$ nim --os:windows --cpu:amd64 --gcc.exe:x86_64-w64-mingw32-gcc --gcc.linkerexe:x86_64-w64-mingw32-gcc -d:release c hello.nim
And you get hello.exe .
$ file hello.exe hello.exe: PE32+ executable (console) x86-64, for MS Windows
If you copy it on a Windows system, you can run it there without any problem. Or, you can also run it under Linux with wine :)
$ wine hello.exe hello windows
Credits
I found this idea in the following blog post: Writing a 2D Platform Game in Nim with SDL2
Update (20181028)
I found info about it in the official docs too: https://nim-lang.github.io/Nim/nimc.html#crossminuscompilation-for-windows
Try hundreds of languages in your browser
“Try It Online (TIO) is a family of online interpreters for an evergrowing list of practical and recreational programming languages.
…
TIO hosts 217 practical and 350 recreational programming languages, for a total of 567 languages.” (source)
Visit TIO at https://tio.run .
What is dependency injection?
See this blog post: Dependency Injection Demystified. In short: “Dependency injection means giving an object its instance variables.”. For a slightly longer explanation, read the blog post.
Reddit comments are here.
Advent of Code 2017
This year I jumped into Advent of Code again. It was a great fun and I was waiting the new exercises every morning. Today I finished it:
This year I solved all the exercises in Kotlin. I will publish my solutions on GitHub soon. Update: here is the repo.
Here is a link to the Twitter page of Eric Wastl, to whom we can thank the Advent of Code. Thanks, Eric and keep up the good work!
Links
working with hex grids
Problem
Solving Advent of Code 2017, today (Day 11) I ran into an interesting problem. We are on a (flat topped) hex grid, and we walk around. Question: how far did we get from the starting position? In short: what is the distance between two arbitrary hexagons in a hex grid?
Solution
I’ve never worked with a hex grid before so I had to do some research. I found an excellent blog post here: Hexagonal Grids. This post is interactive, so don’t forget to move your mouse over the figures.
I figured out that I needed cube coordinates; that gives the easiest way to calculate the distances. Here is a code snippet in Kotlin:
data class Point(val x: Int, val y: Int, val z: Int) {
fun distance(b: Point): Int {
return (abs(x - b.x) + abs(y - b.y) + abs(z - b.z)) / 2
}
}
var x = 0
var y = 0
var z = 0
val p1 = Point(x, y, z) // starting position
val steps = "ne,ne,ne".split(",") // go to North-East 3 times
for (direction in steps) {
when(direction) {
"n" -> { ++y; --z }
"ne" -> { ++x; --z }
"se" -> { ++x; --y }
"s" -> { --y; ++z }
"sw" -> { --x; ++z }
"nw" -> { ++y; --x }
}
}
val p2 = Point(x, y, z) // we arrived here
val dist = p1.distance(p2) // the result is here (in this example: 3)

You must be logged in to post a comment.