Software Flip-Flop
- davidcarew19
- Jul 11, 2024
- 2 min read
Updated: Jul 21, 2024
Here is a bit of code that I believe would be known to advanced coders and not likely by beginner-to-intermediate journeymen programmers. It is a software "flip-flop", that is a function that yields zero when first executed; then returns one upon subsequent execution; then zero and so on, alternating between evaluating to one and zero. Flip-flops are well-known in hardware circuitry, but little known and used in software. However, once familiar with the concept and the "knowing how", it is surprising how often it turns out to come in handy, for example when coding two alternating paths within an iteration. This is a code pattern, potentially useful in any programming HLL (high level language) that has a built-in absolute value function, usually spelled "abs()" and taking a decimal or floating-point numeric data type instance as its argument. Here is more detail:
<"all" HLL's: init var a as a float type>
a = 1
then:
BASIC: a = abs((-abs(a-1)))
Python: a = abs((-abs(a-1)))
JavaScript: a = Math.abs((-Math.abs(a-1)));
Go: a = math.Abs((-math.Abs(a-1)))
and so on...
Here is a bit of code in Golang that (when executed with "go run") demo's the flip-flop:
// flip-flop.go
//
package main
import (
"fmt"
"math"
)
func main() {
var x float64 = 1
fmt.Println(" x float64 init :", x)
x = math.Abs((-math.Abs(x - 1)))
fmt.Println("x after 1st flip exec :", x)
x = math.Abs((-math.Abs(x - 1)))
fmt.Println("x after 2nd flip exec :", x)
x = math.Abs((-math.Abs(x - 1)))
fmt.Println("x after 3rd flip exec :", x)
x = math.Abs((-math.Abs(x - 1)))
}
So now you too have this "software trick" in your repertoire. Enjoy.
P.S. -- the only "practical" example use that I have as an illustration is in a trivial optimization of the venerable bubble sort algorithm: Bubble sort on randomized data is more efficient when the direction of each pass of the sort is changed: pass 1 goes from top of the data set to the bottom (bubble swapping as it goes), and then pass 2 goes from the bottom to the top. This "flip-flop" function can control the alternating direction of each pass neatly and efficiently within the iteration of bubble sort passes. Of course, bubble sort is overall so inefficient compared with merge and/or partition sort, that it is practically never used, unless the data set is by happenstance already in "nearly" sorted order, in which case alternating directions buys so little added performance (usually) as to be not worth any extra coding effort... Yet another example of Murphy's Law defeating the "cleverness" of programmers.
Comments