733 points · by algobuddy · 8y ago · 491 comments
Various TCP backoff algorithms are also a great study in how to approach problems with insufficient knowledge of the system under test, and building desirable properties (reliable in-order delivery) from a undesirable input (arbitrary packet loss, and loss in the face of congestion). I make all the kids try to implement their own, then walk through the history of TCP approaches to the modern day.
One more protocol / paper which fits this description, imo, is Bitcoin paper [0]. It's easy and accessible to all and elegently explains how to solve a complex problem with existing tools. Not sure it can be called as an 'algorithm'
An Introduction to Kademlia DHT & How It Works
http://gleamly.com/article/introduction-kademlia-dht-how-it-...
[0] - http://www.bittorrent.org/beps/bep_0003.html
[1] - https://wiki.theory.org/index.php/BitTorrentSpecification
It worked pretty well. Used it for several years until I started making real money and decided I could buy things rather than pirate them.
I had only been coding for a year or two at that point, so it is probably filled with lots of odd choices, but it also isn't super optimized like I would guess the more well known clients might be, and so might be easier to parse.
The Fundamental Theorem of Arithmetic states: "every integer greater than 1 either is a prime number itself or can be represented as the product of prime numbers and that, moreover, this representation is unique, up to (except for) the order of the factors."[1]
So to determine that two words are anagrams of each other, you can assign each letter to a unique prime number (a = 2, b = 3, c = 5 etc.), then compute the product of those numbers, and if they're equal then those two words are anagrams.
[1] - https://en.wikipedia.org/wiki/Fundamental_theorem_of_arithme...
int32 zzzz (4 characters)
uint32 zzzz (4 characters)
int64 zzzzzzzzz (9 characters)
uint64 zzzzzzzzz (9 characters)
But that's the worst case, not many real words have several "z"s in them. How often are real words affected? I did some experiments with /usr/share/dict/words: 1-( 36123/123115) = 70% overflow int32
1-( 39774/123115) = 68% overflow uint32
1-(117909/123115) = 4.2% overflow int64
1-(118533/123115) = 3.7% overflow uint64Unfortunately, as you suggest, the complexity of arbitrary precision multiplication kicks in and performance suffers.
[ 'basiparachromatin', 'Marsipobranchiata' ]
[ 'configurationism', 'misconfiguration' ]
[ 'constructionism', 'misconstruction' ]
[ 'pericardiacophrenic', 'phrenicopericardiac' ]
[ 'anatomicophysiologic', 'physiologicoanatomic' ]
[ 'petrographically', 'pterylographical' ]Here's my code: https://github.com/brlewis/brlewis.github.io/blob/master/201...
On my machine, Fundamental Theorem of Arithmetic finished in 1.703 seconds, sorting letters in 1.954 seconds.
(1) keep an array of length 127 that you re-use and set to 0 between calls
(2) for each character in the first string, increment the array at the character's index
(3) for each character in the second string, decrement the array at the character's index
If you end up with all 0s, it's an anagram.This way you only need to check the character values you actually use, and not all 127. It also generalizes trivially to larger character sets.
Or 64, if you store numbers as 32-bit integers and compare them as 64-bit using a union type.
It's also a great insight into just how fundamental the concept of computational complexity is.
You put your secret message in a box, put a lock on it that only you have the key to, and send it to the other party. They, unable to open it, put on a second lock of their own, and send it back. You remove your lock, leaving theirs, and once again send it to the other party. Finally, they remove their lock too and can open the box without anyone else having had that possibility.
What can also be inferred from this, is how DH is vulnerable to a man-in-the-middle attack. Someone involved in the delivery could pretend to you to be the other party and to them to be you.
I agree but, to be fair, the key ingredient ("discrete logarithms are hard") is not simple at all.
Totally blew my mind back then when I was trying to understand how asymmetrical cryptography works.
Several years later I saw a Matlab demo that did this by indexing the grid using values from a 3x3 magic square[1]. In a magic square, every row, column, and diagonal has the same sum. So checking for a winner was just checking if a player’s three moves added up to 15. Finding a space that would make the computer win, or block the human opponent from winning, was subtracting two moves from 15 and checking if that spot was available.
I wonder if this is true of larger magic squares.
Some Python:
from collections import Counter
from itertools import combinations
def number_of_sums(n, M):
combs = combinations(range(1,n**2+1), n)
sums = (sum(c) for c in combs)
return Counter(sums)[M]
print(number_of_sums(3, 15))
print(number_of_sums(4, 34))238, 22, 494
21, 10659, 39
665, 55, 1105
so checking for a winner was equivalent to checking if the gcd of a player’s spaces was greater than 1.
Much less efficient! But it looks like I was on the right track in searching for compact numerical alternatives to traversing the board and measuring strides.
Edit: fixed an arithmetic error
from itertools import combinations
magic_square = [2,7,6,
9,5,1,
4,3,8]
def did_user_win(moves):
# Convert moves to magic square values
magic_values = [magic_square[move] for move in moves]
# Check if any sum of three moves equals 15
for three_values in combinations(magic_values,3):
if sum(three_values) == 15: return True
return Falsehttps://en.wikipedia.org/wiki/Stable_marriage_problem#Soluti...
I think they are lumped together because they are both "mechanism design" problems that were studied by Roth and part of his prize.
The algorithm has many lovely features. It is very efficient -- it is used in basically every SAT solver with minimal modifications. It's not entirely trivial it works, particularly the backtracking part. It is a good example of how there are algorithms which are extremely hard to do functionally (the whole algorithm is about moving pointers around).
It's also a good example of practical Vs theoretical efficiency. In the worst case it is no more efficient than the algorithm it replaced, in practice it is hundreds of times more efficient. The "not moving back" feels like it should save at most half the time, it on fact speeds things up by often 10 times (this is because watches are often moved around until they reach some "boring" variables, where they lay undisturbed).
https://en.m.wikipedia.org/wiki/Fast_inverse_square_root
I especially love the story around it.
PC: https://software.intel.com/sites/landingpage/IntrinsicsGuide...
ARM: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc....
JS implementation: https://gist.github.com/netgusto/90c8e0e7019a832cbf95eac58e1...
low = -1
high = arr.length
while(high - low > 1){
mid = (high + low)/2
if(arr[mid] <= x) low = mid else high = mid
}
This eliminates all branches from the body of the loop (gets compiled to conditional move). It's also more general because it can be used to find the right position to insert a new element in a sorted array.1. high and low are bigints (such as when using Python, for example)
2. the input array is sorted (needed for any binary search algorithm)
3. this missing code at the bottom is added:
if (0 <= low && low < arr.length) {
if (arr[low] == x) {
return low;
}
}
return -1; // (or "raise Not_found" or whatever you use to indicate that 'x' was not found).
You can find the formal proof in WhyML below. This includes proofs that:1. all array accesses are in bounds [checked automatically]
2. there is no undefined behavior (such as division by zero) [checked automatically]
3. the function always terminates [enforced automatically, proven with the help of the 'variant' clause]
4. there are no overflows [checked automatically, not possible since we're using bigints]
5. if an index is returned, the array has an element with value equal to x at that index [the 'ensures' clause]
6. if instead the function returns "not found", the array does not have any element with a value equal to x [the 'raises' clause]
... all this assuming that the input array is sorted [the 'requires' clause]
Code + proof here (it makes more sense if you can read OCaml syntax): https://clbin.com/jbTk8
The complexity is O(log log n), under the assumption of a uniform distribution of the data.
const mid = Math.floor((right + left) / 2);
susceptible to overflow?
EDIT: Hm, perhaps not (in JS). Number.MAX_SAFE_INTEGER is much greater than I expected.
https://ai.googleblog.com/2006/06/extra-extra-read-all-about...
mid = (lo + hi) >>> 1
https://docs.julialang.org/en/v1/manual/faq/index.html#Why-d...EDIT: legibility
const mid = Math.floor(left + (right - left) / 2);
https://math.stackexchange.com/questions/977955/is-there-a-w...
My experience with this is from using Prime95 two decades ago as part of a distributed computing project to factor Mersenne prime numbers
https://en.wikipedia.org/wiki/Prime95 | https://www.mersenne.org/
It's not so much that it is "beautiful", but it is a remarkably simple algorithm that a human can follow manually. The reason it is efficient is easily understood (it's easy to see how we are able to "finalize" nodes because it's obvious there is no shorter path to that node), and it takes what would otherwise be a complicated task and makes it manageable.
Mind you, the “n” here is not the number of nodes!
More precisely, Dijkstra’s algorithm runs in O(E + V * log V) time (if the priority queue is implemented with a heap), where E is the number of edges and V is the number of nodes.
In the general case, E = O(V^2) (i.e. fully connected graph), so Dijkstra’s algorithm can calculate the shortest path to V nodes in O(V^2) time. It sounds less staggering this way.
And in a general graph where negative edge-weights are permitted, it’s actually impossible to find the shortest path between two nodes without finding the shortest path between the source node and every other node! It’s pretty easy to see why: you can’t be sure you’ve actually found the shortest path until you’ve covered all the edges, because there’s always the possibility of a very large negative edge to be visited.
Dijkstra’s algorithm improves on this general case by exploiting the fact that the edges must have positive weight.
If there are negative edge-weights and cycles may occur, there is no shortest path between some nodes. You can keep going through a cycle whose total weight is negative getting "shorter" and "shorter".
It's like a race where one shortcut takes you back in time and leaves you where you started. You can use it to finish the race as far back in time before you started as you want.
I mean, even Dijkstra himself came up with it because he needed it for a telecom gig. He can't have been the first one in the world who needed to find the shortest path in a graph. He just also happened to be a scientist, experienced in the whole "how to publish a paper" thing.
For non-machine learning folks, this algorithms helps in grouping relevant items together. As a practical, using this algorithm you can segment your customers based on their purchase history and interests.
The actual algorithm is very simple, imagine a lot of points on the 2D plane and each of them represent customers, whom you want to segment/cluster. Now, chose random cluster points and assign those customers to these points, by their distance. That is, whichever customer is near to a point, it belongs to that. At the end of iteration, you have lots of customers assigned to each cluster. Now, for each cluster, take the mean of those customers and the move the cluster to this mean value. Slowly, the cluster points move to the center with all the customers surrounded, belonging to that cluster.
read more - https://en.wikipedia.org/wiki/K-means_clustering
https://en.wikipedia.org/wiki/Mean_shift#Clustering
but I don't get how C and r are chosen, nor how the method is supposed to be "non-parametric" given that you need such parameters to begin with.
Also, how are you supposed to assign all points to separate clusters, and how would you determine how many clusters to use in the first place?
Having looked at the that page I also definitely don't think it's simpler than K-means!
Edit: This article gives a much more accessible descriptions than wikipedia:
https://spin.atomicobject.com/2015/05/26/mean-shift-clusteri...
To answer my own questions, the number of clusters is determined by the number of max points of the kernel density function, but the kernel bandwidth does have to be specified.
> So how does mean shift come into the picture? Mean shift exploits this KDE idea by imagining what the points would do if they all climbed up hill to the nearest peak on the KDE surface. It does so by iteratively shifting each point uphill until it reaches a peak.
I wonder if this would still work with high-dimensional data. Distance and space start to act weird in higher dimensions, right?
I like the explanation in the case study in Sedgewick's Algorithms [1].
Compare its simplicity to connected-components [2], another elegant algorithm but with a perhaps a bit more involved implementation.
You wanna flex your muscles with this data structure, this is a fun Project Euler problem: https://projecteuler.net/problem=186
After hearing the word "memoization" go through my head (part of "Hacking the Coding Interview." which I recommend at least for the wealth of example questions for practice), I basically walked my way through making a disjoint-set data structure using the words as keys and the set number as values. I'm prettyy sure that making that up on the spot is what got me the job.
Could you expand on this? This is something I've just started reading about. I'd be interested in good resources to use to get started. At the moment I've just started reading TAPL.
Basically, background processes need to keep retrying an operation until it succeeds. (Make an API call to a server, upload a file, ect, ect.) If the retry interval is too small, you can DOS the remote server. (Server returns a 5xx error because there's a corner case that hits a defect.) But, if the retry interval is too large, your background process can run too slowly when it encounters transient errors. (Temporary network glitch, database under high load because of a cache flush.)
So, we pick an ideal small retry interval, and the maximum tolerable interval. (In my case, it's usually 30 seconds and 15 minutes.) Then, when errors happen, the retry interval keeps doubling until it hits the largest interval. So, the operation is retried at 30 seconds, 1 minute, 2 minutes, 4 minutes, 8 minutes, and then every 15 minutes until it succeeds.
The result is that transient errors don't cause large delays. Situations where a defect prevents a request from submitting don't DOS, because the retry interval throttles itself longer and longer.
The summary (from the article) is that:
sleep_time = random_between(0, min(2 ** retries, max_sleep_time))
so that retries are "spread across" the delay window.In Javascript, if you have two numbers x and y that are both greater than zero, you compute the greatest common divisor xyGcd in one beautiful line of code:
var xyGcd = function gcd(a,b){ return b ? gcd(b, a%b) : a; }(x, y);
In my opinion this is the greatest one-liner ever.I dunno, I really like Haskell's one-line infinite Fibonacci sequence:
> let fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
> take 7 fibs
[1,1,2,3,5,8,13]
> fibs !! 1000
70330367711422815821835254877183549770181269836358732742604905087154537118196933579742249494562611733487750449241765991088186363265450223647106012053374121273867339111198139373125598767690091902245245323403501
I don't think it's the most efficient solution, but it really showcases lazy evaluation with a simple example.It's not one algorithm but two, that dance and weave together in harmony. You can pick dictionary matching, or entropy coding, and you can select between them on a per-byte basis with no overhead. That's what I find so clever about it - not that it can do one thing or the other, but that it can choose either, and yet represent them using the same language. No extra markers, nothing to say "oh, now we're switching to entropy mode", nothing to get in the way.
I also really like other related "nature inspired algorithms"[1] like Ant Colony Optimization, Particle Swarm Optimization, etc.
[1]: http://www.cleveralgorithms.com/nature-inspired/index.html
While our algorithms might mimick evolution poorly, there's something raw about it. And it's not totally forgotten in research: https://blog.openai.com/evolution-strategies/
I stumped upon Differential Evolution which I implemented here https://github.com/peheje/nim_genetic/tree/master/Differenti...
It's fun to see how easy it is to define a new problem for it to solve.
Would like to apply it to create NN or Trees for classifications or the like.
I was actually considering implementing one during development of the game I'm working on to generate a soundtrack (since I'm not a musician), but the problem is the fitness function would require a user rating of each generated sound sample, and to get any kind of decent results, that would require me to personally listen to and rate thousands of songs. Either that or outsource it through SoundCloud or something.
Being able to do the full set of boolean operations on shapes with just `min` and `max` operations is pretty cool. Doubly so because boolean operations on standard geometry is such a difficult, messy problem.
Actually, not really! Bresenham's Line Algorithm secretly has a very useful generic low-level algorithm at its core. It just happened to be created for drawing lines first.
The thing most people miss is that it describes a way to do error-free repeated addition of a fraction using only integers and addition. In fact, you can add many different fractions, as long as they all share a denominator.
That is hugely powerful in the right context: imagine an embedded context where you have to add fractions to a counter, but the counter should be an integer value at all times. Maybe you must add different fractions in different situations. For example, an embedded device with two non-matching frequencies to keep track of over longer periods of time. With this method you're guaranteed that no matter how long you keep adding, the sum will always be correct.
Dithering also appears in audio. The old PC Speaker had merely 1/0 states. It's supposed to be limited to square waves, limited and unpleasant, right? But at some point people figured out if you flip 1/0 fast enough you can approximate continuous values: http://bespin.org/~qz/pc-gpe/speaker.txt
I once played with using "error diffusion" like dithering to play wav files. In theory that should produce better audio than the simple fixed-table and PWM dithering suggesting in above article, but I did this on a much newer computer (Pentium?) by which time PC Speaker was irrelevant (only for hack value) and only reached 30-40 bits per input sample at 100% CPU. Plus as that article explains, simple PWM might(?) actually produce less noise from timing irregularity.
But the technique is not merely an obsolete hack! Every CD player that visibly brags it has "1-bit DAC" uses a closely related technique, though in fast hardware. See: https://en.wikipedia.org/wiki/Delta_modulation https://en.wikipedia.org/wiki/Delta-sigma_modulation Take me with a grain of salt, I always get confused trying to grok these... Full explanations of the noise shaping properties that make Delta-Sigma highly useful involve quite a bit of signal-processing, but the core accumulate-compare loop is a very simple algorithm...
LR parser https://en.wikipedia.org/wiki/LR_parser because Aho & Ullman
https://en.wikipedia.org/wiki/Church_encoding 'cos it shows how fundamental lambda calculus is in a simple way (and how functional programming is so superior (flame wars intended :-) )
Another favorite is RAFT, simply because of how elegant and simple it is and how easy it is to understand.
Also - I used to work in a company that did P2P video streaming (pre WebRTC) and the way the protocol leveraged Reed Solomon Coding was just awesome. https://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_cor...
(I was still quite wet behind the ears at the time, so it's also more than possible that I was just doing something wrong.)
All that said, agreed, wonderful little mechanism. It's one of those things that every C programmer should take the time to really understand.
These days compilers usually do loop unrolling on their own, so the device has mostly lost its purpose, but it can apparently also be used to implement something similar to coroutines in C, which is nice.
Even sadder because the same effect can be achieved cleanly (and "optimizably")by using as "switch" followed by a "while".
https://www.lysator.liu.se/c/duffs-device.html
A quote of the man himself about this: "I feel a combination of pride and revulsion at this discovery."
Also a shameless plug. My friend and I came up with this pseudo-polynomial time algorithm for subset sum that can be taught in a single session. It is faster than the standard dynamic programming algorithm. https://arxiv.org/abs/1807.08248
2. Fast Fourier transform (FFT). It's another quite brilliant algorithm used for decomposing a function into its frequency components in linearithmic time (among other things).
For 2D -> 3D, see https://en.wikipedia.org/wiki/Projection-slice_theorem for a simple overview
DBSCAN is used for clustering in applications, much like k-means clustering, but in k-means clustering, the number of clusters must be known in advance (hence the k)
DBSCAN solves this problem by for every point in the graph checking if a certain threshold of vertices is within a certain radius. If this is the case, it will add these vertices to the new cluster and repeat the process for these nodes. It is very simple, so much that you can easily explain this to non-technical people.
In my previous job I used it for detecting whether for one word in a signal there only existed one representation or multiple (used for toggle bit detection)
[1] http://www.dbs.ifi.lmu.de/Publikationen/Papers/OPTICS.pdf
[2] https://www.cse.buffalo.edu/faculty/azhang/cse601/density-ba...
Clustering on non linearly separable clusters is also one of the reasons we chose DBSCAN back then :)
There is a theorem that it is impossible in general to remotely compare two files with less network traffic than it requires to simply send one file over the wire. But rsync does it. How? By accepting a theoretical but unlikely possibility of coming up with the wrong answer.
What rsync does is compare hashes of ranges of stuff. If the hash comes out the same, the two are assumed to be identical with no further investigation. It is possible that different files will be thought identical. But it is unlikely that any two hashes ever generated by rsync have accidentally been the same when the underlying files were different.
(I do have to say "accidentally" because rsync uses MD5 as a hashing algorithm, and people have deliberately created collisions in MD5.)
There is an even simpler idea at the core of many modern backup programs (eg. bup, attic, borg)! Possibly pioneered in `gzip --rsyncable`, not sure. https://en.wikipedia.org/wiki/Rolling_hash#Content-based_sli... Each side slices files into chunks at points where rolling hash % N == 0, giving chunks of variable size averaging N. These points usually self-synchronize after insertions and deletions. This allows not just comparing 2 files for common parts, but also deduplicated storage of ANY number of files as lists of chunk hashes, pointing to just one copy of each chunk!
It can take any two convex sets and tell you if they overlap, while converging on a separating axis or a penetration point, if it exists. All you need is a support function that returns a point in the set that is furthest along a given direction vector. The algorithm works in an arbitrary number of dimensions.
Basically, it operates on a new shape which is the Minkowski difference of the two intersected sets. If the difference-shape contains the origin, then the two shapes overlap. The algorithm iteratively constructs simplexes inside the Minkowski difference, trying to build one that encompasses the origin. This allows it to have essentially constant memory for a given dimension of problem.
It's a very elegant formulation of a very general problem. It's so pleasing that you can intersect cylinders with cones, or oriented cubes with frustums, or polytopes with superellipses all with the exact same single algorithm.
The Wikipedia writeup is terrible, so I may do my own with nice illustrations at some point.
I believe this algorithm is widely used in the video game industry?
Also, it has a great website dedicated to it, with lots of interactive demos:
val someDS;
while(!someDS.isEmpty()){
addChildren(someDS.pop())
}Now replace, someDs with
Queue -> BFS
Stack -> DFS
Priority Queue, with priority of distance so far -> Dijkstra.
Priority Queue, with distance + heuristic -> A*
Its beautiful.
> In computer science, dancing links is the technique suggested by Donald Knuth to efficiently implement his Algorithm X. Algorithm X is a recursive, nondeterministic, depth-first, backtracking algorithm that finds all solutions to the exact cover problem. Some of the better-known exact cover problems include tiling, the n queens problem, and Sudoku.
~ https://en.wikipedia.org/wiki/Dancing_Links
Also SEQUITUR http://www.sequitur.info/
> Sequitur (or Nevill-Manning algorithm) is a recursive algorithm developed by Craig Nevill-Manning and Ian H. Witten in 1997[1] that infers a hierarchical structure (context-free grammar) from a sequence of discrete symbols. The algorithm operates in linear space and time. It can be used in data compression software applications.
~ https://en.wikipedia.org/wiki/Sequitur_algorithm
Part of the reason I like these both is that they each require sharp pointer manipulation to work efficiently.
I'm a functional programming fan, these beautiful and useful algorithms remind me that purity isn't everything, eh? Also, it's fun to think about how you might get FP code to emit correct pointer-munging code for them.
The LLL lattice basis reduction algorithm and the Coppersmith method are also jaw-dropping
- Very non-trivial problem
- Just 5 lines of code
- Probably the most language agnostic algorithm
- Outrageously fast if graph fits in cache
- You can explain it to even non-programmers
- You can wear it on T-Shirt
- Doesn't require any fancy sub-algorithms, libraries or whatever
Are you sure about this point? I'd like to see a purely functional implementation of this, e.g. in Haskell without monoids. I believe it's significantly harder than a C implementation (which is indeed a few lines)
import Data.Array
fw :: Int -> Array (Int, Int) Int -> Array (Int, Int) Int
fw 0 graph0 = graph0
fw k graph0 =
let fw' = fw (k - 1) graph0 in array (bounds graph0)
[ ((i, j), min (fw' ! (i, j)) ((fw' ! (i, k)) + (fw' ! (k, j))))
| (i, j) <- range (bounds graph0)
]
The only difference with a mutable implementation is that you use a new array for every k, whereas in a mutable version you would reuse these.It finds strongly connected components in a graph (read: cyclic dependencies), while doing a topological sort (read: you could use it for a package manager to determine which packages to install first).
It is proof of a very deep understanding of the nature of graphs.
Edit: https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_...
A to B: send message (repeat until ack)
B to A: ack (resend if a repeat of message is received)
A to B: commit message (repeat until commit ack)
B to A: commit ack (resend if a repeat is received, but commit only once)For object picking (determining what the user clicked on) in a complex visualization, it is often easiest to draw all objects with a simple color-mapping renderer which follows the same occlusion rules as your visualization but renders each object as a solid blob in a distinct color. You draw the scene, look at the pixel color under the mouse, and use the color as an index into the table of objects.
For ray-cast volume rendering, you have a problem somewhat like object picking but you have to solve it simultaneously for all pixels in the rendered scene. You have to determine the ray intersections of each pixel's perspective through your volumetric data grid, so you can run a sampling loop to integrate the 3D scalar field values along that ray. When your grid has a simple cube/box shape, you can render a polygonized box with the viewing perspective and trivially color-map it so each surface of the box has an RGB value encoding its XYZ volume coordinates. Your volumetric pixel shader, running on the GPU, can then independently lookup these XYZ positions out of screen-sized buffers to determine the start and end positions for each screen pixel's ray integration loops as 3D texture coordinates.
An example discussion from google: https://jeremykun.com/2016/07/05/zero-knowledge-proofs-a-pri...
What is it used for? It allows one to both query and update prefix sums in O(log n), for a normal array this would be O(n)/O(1) respectively.
The cool thing is that it can be emulated with an array and as such it takes just the same amount of space as an array.
The best part is that they can be implemented (simple version) in about 10 lines of C++ code.
Has something of Cantor's diagonal argument about it.
So, I'll mention Monte Carlo integration. It's very simple to implement, it was one of the first tasks my first CS professor gave freshman students, and he did it for the same reason I love it; it gives such profound insights about how computers can solve complex mathematical problems humans can't. I shiver every time I solve a problem with a Monte Carlo method.
You might have heard of "2nd order" or "4th order methods to calculate an integral. This means that the error drops off with the number of sampling points like N^-2 or N^-4, respectively. But Gaussian quadrature has spectral accuracy, which transcends this measure. Error goes down like an exponential of N.
Another neat feature is polynomials of degree 2N-1 or less are integrated exactly with this method. So if you have just 10 sampling points, you can calculate exactly the integral of a 19th order polynomial (times, perhaps, some known weighting function).
For example with f(x) = sqrt(1 + sin(x)) and you approximate integral f(x) dx from -1 to 1 with n Gauss points, then the the convergence is geometric:
n | approx
1 | 2.0-------------
2 | 1.9172----------
3 | 1.917703--------
4 | 1.917702153-----
5 | 1.917702154417--
6 | 1.91770215441681
But with a function that is not differentiable such as g(x) = |x|, there is definitely not geometric convergence. n | approx
1 | 0.0-----------
10 | 1.007---------
100 | 1.00008-------
1000 | 1.0000008-----Count-min-sketch is also beautifully simple.
Math is definitely foundational for Computer Science and for that reason one of the most interesting algorithms I've personally encountered is the one for computing Principal Component Analysis (PCA)[1] using Singular Value Decomposition (SVD)[2].
It's just amazing how you can easily represent N dimensional objects in 2D. It's used a lot in Machine Learning. One of the interesting applications of the algorithm is Face recognition (eigenfaces method).
[1] https://medium.com/100-days-of-algorithms/day-92-pca-bdb6684...
It can be a really effective pre-processing step for many kinds of circuit analysis.
https://people.eecs.berkeley.edu/~alanmi/courses/2005_290A/p...
Amusingly, despite having done a ton of Computer Vision (I worked for an image recognition company for 4 years) I never used it for that purpose. The main practical use case I had was related to the use of Trellis modulation [2] for band-limited communication channels.
[1] https://blog.separateconcerns.com/2013-03-03-viterbi-algorit...
What?: Quite powerful data structure for geographic data.
Why?: I dabbled with geodata for quite a bit before discovering PostGIS and the R*-tree. Operations that took me several seconds before (geojson+ruby) could be computed in well under 100ms directly on the Database.
-ss
1. An irrefutable improvement over the state of the art.
2. A short paper which can be understood after only a dozen readings or so. I mean really understood, with visualizations and everything.
3. A practical algorithm which can be implemented by nearly anyone (even me).
You've made a Fibonacci number algorithm. Recursive it's slow, iterative it's nasty. There's another way
> let fib = 0 : 1 : zipWith (+) fib (tail fib)
Then to get the 10kth Fibonacci number you can
> fib !! 10000
It's fast. It's tiny. It has no risk of stack overflow because it's not a recursive function. It illustrates how and why lazy evaluation is important and even better than eager evaluation in many cases. I use this principle in my C#/Java work a lot.
It's my favorite.
fibs = 0 : scanl (+) 1 fibs
scanl is similar to a fold, but returns a list of successive reduced values from the left.Second favorite is the LISP REPL. Specifically the Eval function, thanks to this classic video of Sussman https://www.youtube.com/watch?v=0m6hoOelZH8
It generates perfect mazes of arbitrary size M*N, using only O(max(M, N)) memory.
[0] http://www.drdobbs.com/jvm/an-algorithm-for-compressing-spac...
Check the external links on the wikipedia page for an excellent implementation that you can run in your browser.
Heap sort using an array impressed me as an undergrad.
FFT continues to amaze me as a scientific programmer.
http://xrd.github.io/angular-algorithms/web/index.html#/algo...
Spelling eratosthenes is harder than this elegant little algorithm.
There is a javascript implementation [0] which is where I saw it the first time, it is about 500 lines of fully commented code. The algorithm is so simple, I absolutely love it.
Basically, when performing a union on two meshes, we determine the 3d BSP trees from both meshes, then simply clip each mesh using the other's tree. The output is the union of the two leftover meshes.
And since both intersection and difference can be written as a combination of inversion and union, they are simply composed from those.
I can't find a good paper on the algorithm though, not sure where exactly it originated.
I've ported this algorithm to Python, but mine is nowhere as succinct as yours (or the original). For my needs, I require the meshes to remain watertight (if the inputs are watertight), and this specific implementation doesn't preserve it. But I still love the algorithm due to its conceptual simplicity.
You can build an entire working structure from base operations, exit conditions and logic that scale to higher states of the operations.
Extending the same, TCO is another very elegant concept in CS.
The same goes for some data structures, a simple example being a list, as often defined in functional programming languages. E.g.:
A list is either:
- empty, i.e. []
- a head (an element) followed by a tail (which is also a list), i.e. h | t
Lists of any size fit that definition because of the recursive definition.
Similar for binary tree, being either just a node, or a node with left and right child, each of which is a binary tree.
It was ugly, I had used 8 for loops, each running for 8 iterations, but, I still felt awesome when it worked. Before this, I had written only lab programs. Next, I applied the backtracking algorithm to solve Sudoku recursively, and that's how it all began. I entered the world of algorithms.
I know it's just one form of brute force algorithm, maybe doesn't even count as one, and is not that elegant, but, it will always remain my favorite.
Backtracking is really a depth-first search over the search tree, so it's definitely an algorithm and I would say it's "elegant" in some sense (like simplicity).
AES is beautiful as well. And I love Huffman encoding. hm, what else. Bloom filters are awesome.
I suspect FFT is beautiful, too, but it surpassed my ability to understand.
I personally think that Speck is pretty cool because of its extreme simplicity, but I can't see anything special about AES.
I also like "greedy" (Matroid) algorithms and Huffman trees :)
Fistly, wavelet trees! Wavelet trees with something like RRR encoding for the bit vectors lets you work with massive datasets in positively tiny space and constant time. They're not even expensive to construct! My favorite introduction to the whole space of rank/select-friendly structures is Alex Bowe's tutorial: https://alexbowe.com/wavelet-trees/
I constantly agitate for people to realize that we now have an algorithm for O(n) generalized sorting. It's called discrimination sort, and while it's a complex subject its quite elegant once you internalize the algorithm. There's a talk by Prof. Henglein here: https://www.youtube.com/watch?v=sz9ZlZIRDAg
2017 saw the recommendation of a truly phenomenal approach to indexing data, using simple leaning structures. These indexes are poorly explored, there's still a ton of headroom here, but the paper is an incredibly cool read and very approachable: https://arxiv.org/abs/1712.01208
Another really cool family of algorithms and associated structures in distributed systems is CRDTs. They're poorly understood, but in research they have largely superseded operational transforms. The Wikipedia page branches off into lots of good research: https://en.wikipedia.org/wiki/Conflict-free_replicated_data_...
If we slightly broadened the lens of what is an algorithm, my favoriate category-theoretic approaches to solving problems include Recursion Schemes which are a technique to totally separate the specification of recursive algorithms over data structures from both the structures and the code that the algorithm runs to compute a result (Patrick from Github has a great series on them here: https://blog.sumtypeofway.com/). I also love the modern and rapidly growing "Ghosts of Forgotten Proofs" as a way to let the compiler assert you've properly built and/or terminated values: https://github.com/matt-noonan/gdp-paper/releases/download/j...
As I understand it, it's a generalized MSD radix sort, and the difference in complexity analysis from traditional pairwise sorts is what the N stands for.
For strings, we know that a fixed-size prefix (say a character) that can take on a known finite set of values is capable of discriminating; that is, being a partial order on strings. From this we can construct a radix sort on strings that never has to revisit a character. So the net running time is approximately O(total number of characters in all strings). In contrast, a naive comparison sort may operate in O(nlogn) comparisons, but each comparison has a cost proportional to the length of the string, since we have to re-compare from scratch, such that this works out closer to O(log n * total number of characters in all strings).
My recollection is that MSD radix sorts are somewhat space-intensive, especially if we want them to be stable. I think O(n) space is required. Nonetheless, this is very interesting.
[1] https://pdfs.semanticscholar.org/7e49/0023f84845c750f4a04b7d...
- Zobrist hashing. It's completely incredible that such a trivial scheme is a near-perfect hash for sets. That's before you even consider the useful ability to compute hashes of related sets with added/removed-elements by simple XORing. (Caveat: I'm repeatedly tempted to use this magic for large sets; but it stops working well when number of elements > number of bits, because the matrix is over-determined, so there are easy-to-find subsets that contribute 0)
- Cuckoo hashing. Before going into the specific way it pushes around elements to usually fit exactly 1 per slot, there is a basic idea to grok that makes 2 possible places for an element work much better than 1: "the power of 2 choices". This is also the reason even a little load-balancing is effective. http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.25.8... is a great overview.
- Merkle DAGs. Immutable content hashes are about the only non-painful form of distributed pointers humanity has found. OK, that's an idea not exactly an algorithm, but for example the easy ability to recursively diff 2 git trees is a neat algorithm.
https://80000hours.org/podcast/episodes/aaron-hamlin-voting-...
If only the general population understood fractions :-)
Because of our the current poorly-designed system, we have an artificially low number of votes for non-Democrat and non-Republican parties.
1) It takes advantage of a simple insight: all frequent subsets must be unions of other subsets that are at least as frequent.
2) It uses a Trie data structure in a very beautiful way, traversing it in-order while searching for elements from a lexically sorted list of lexically sorted lists.
Really simple, elegant solution to a hard problem. There are some alternatives that are arguably better in ways, but none are nearly as simple to comprehend
[1] https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_v...
[2] https://www.cs.bgu.ac.il/~dinitz/Course/SS-12/Karp-frequent-...
I really like backtracing algorithms used to solve huge graphs without actually visiting all nodes. Pretty elegant IMO.
I think most of us would agree that there is a fuzzy boundary between mathematics and algorithms, or even that the latter is a subset of the former. Bresenham's Line Algorithm[1] is an algorithm, but it can also be interpreted as a kind of mathematics to determine points on a grid based on a path through that grid.
More importantly though: yes, it is a very useful and simple tool in many contexts.
[0] https://en.wikipedia.org/wiki/B%C3%A9zier_curve
[1] https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
https://en.wikipedia.org/wiki/Floyd%E2%80%93Steinberg_dither...
It can simulate color transitions with fewer colours by using a simple error diffusion algorithm.
https://automorph.wordpress.com/2012/06/20/eulers-analytic-p...
I also have spent way too much time trying to get an implementation of it right, so there's a little stockholm syndrome.
This makes so much of online trust and verification possible.
Objective: You have a list of things with a popularity score and want to get a random item from the list, but you don't want just ANY random item. You want it to be a generally popular item.
How it works: You take a key for the weight, we'll say `popularity` (0-100). And you have maybe 1,000 rows of content, each with said weight.
You sum up all the popularities to variable X. You set a random number between 0 and X; call it R. You iterate through your 1,000 rows (Y), and each iteration you subtract Y's `popularity` from your random number, R, and when R <= 0... you use that row.
---
Quick Example: https://jsfiddle.net/rL6a01ku/
Press "RUN" over and over to see the numbers change, but basically still stay the same.
Edit: it's also a massively practic idea that powers most databases.
https://en.m.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorith...
Very simpel in concept and applies to all continues functions...
It took me days/weeks of processing to understand it (and appreciciate the problem(s) it solves).
https://bitcoinmagazine.com/articles/genesis-files-hashcash-...
1. It solves an extremely practical problem (spam) using a very simple idea (provide a value that when appended to a message gives a hash value within an acceptable target range).
2. It can be understood by non-experts who simply understand (or accept) the one-way nature of cryptographic hash functions.
3. It can be implemented manually, given a working hash function.
4. It sat around for a decade in obscurity until someone dusted it off to build a system most thought was impossible.
PID controllers are also a great invention, does that count as an algorithm?
Given chess was a bit too computationally intensive but pair minimax with a neural net evaluation function and you get close to what AlphaZero is doing.
https://epubs.siam.org/doi/abs/10.1137/09076636X
Somehow, even when things are almost surely not differentiable anywhere, you can develop algorithms which to a higher order (matching some idea of non-differentiable Taylor series) approximate the function. This is a beautiful idea since when you first do deterministic numerical analysis, all of the derivations require differentiability, but now this really expands your idea of what differentiable means.
and
- Marching Cubes
Boyer-Moore fast substring searching. Simple to understand and has great performance. [1]
Alpha-Beta game tree search. I really like Knuth’s paper on it. [2]
[1] https://en.m.wikipedia.org/wiki/Boyer–Moore_string-search_al...
[2] Artificial Intelligence Volume 6, Issue 4, Winter 1975, Pages 293-326
https://en.wikipedia.org/wiki/Skip_list
Some runners up: Gosling's dynamic programming algorithm for optimizing text editor screen updates and gap buffers.
Kosaraju two pass algorithm, this one blew me over when I first read it and I am still impressed by the ingenuity of this algorithm [2]
I've had really good results asking this. I find it's a great question, because it allows the candidate to show off their knowledge, and use some knowledge that they likely prepared for ahead of time. I also like it because sometimes I get to learn something really interesting from the candidate.
It's also an easy way to filter people when they can't name even one algorithm, or their favorite is "that sorting algorithm"
Wikipedia entry:
https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm
Implementation example (2 GB/s scan on modern 3GHz CPU):
https://github.com/faragon/libsrt/blob/master/src/saux/ssear...
I love the idea of adding not _structure_ but _randomness_, in order to better find a solution to some problem.
not because it's super practical ( and there are other variations using other operators )
I like it because it is super simple and when I first encountered it early on in my learning, it was really not immediately obvious why it worked. It's probably been the simplest piece of code that's surprised me.
For data structures: Either Hash Array Mapped Tries (HAMT; used in most immutable data structures) or Log-structured Merge Trees (LSM-Trees; an important concept for databases, mainly very useful because random access on "spinning rust" is very slow).
Although, calling this an algorithm may offend applied mathematicians.
I would call it an algorithm since explicitly defined sets are constructed to show the contradiction.
https://probablydance.com/2018/06/16/fibonacci-hashing-the-o...
Disclosure: Met Rajesh couple of times
a. Solving the nut/bolt matching programming challenge with Merge sort.
b. Backtracking e.g. finding the ordered pair of braces
c. Not to mention the various tree/ graph walk problems
d. I screwed my Google interview last round not knowing the problem could be easily solved topological sort
Less than 10 lines of code to create a piece of art.
One reason I am amazed is because it's a dynamic programming solution to a highly formalized, abstract problem. I consider it as a kryptonite to my inner, formalism enthusiast functional programming fanboy persona.
I imagine I would spend many days researching prime numbers if I hadn't read "The Mystery of the Aleph" in time. I'm keen to keep what sanity I have left.
Also the compress and extract algorithms from Hacker's Delight.
It is used in DVB-T combined with Reed-Solomon code for example.
With some clever tricks you can use it to "recover" a surd from a decimal
ie 1.4142135624 -> sqrt(2)
http://faculty.engineering.asu.edu/palais/counter-rotating-r...
All you have to do to test for win condition is check if the other player has the next item in the array.
Equality is a tie.
Base case is a loss.
It's also my favorite case of structuring data in a way that makes the algorithm self-evident.
Previous discussion: https://news.ycombinator.com/item?id=2657277
Make a rectangle with side lengths of 2 positive real numbers. Put the biggest square inside (i.e. against a short side) that you can, add as many as fit. If there's still a gap, put the biggest square that fits in that, repeating until filled.. If you never fill the gap, the ratio is irrational. The number of squares of each size used gives the ratio's continued fraction.
I like your project idea. I'm not hard core enough to build something from transistors but I'd love to give nin a go in assembler on an arduino. Something to add to my backlog!
It's such a simple formula, but manages to smooth and filter signals nicely.
Honorable mention: Kahan summation algorithm https://en.m.wikipedia.org/wiki/Kahan_summation_algorithm
phi = (1 + sqrt(5))/2.0
def fib(n):
return round(phi**n / sqrt(5))No really. Do you see why?
The solution usually lives in an infinite dimensional Hilbert space, whereas our space of possible approximate solutions is a finite-dimensional subspace.
To find the "best" solution that lives in the finite-dimensional basis-function (or trial function) space, we simply choose the coefficients of the basis functions such that the residual is orthogonal to the approximate solution.
One way to define this is to say that a vector is zero when it's orthogonal to every other vector in some space. This gives rise to Galerkin and Petrov-Galerkin methods to solve differential equations. However, it also gives rise to linear system solvers such as conjugate gradient (CG).
Another way to define zero is to say that a vector is zero when it's norm is zero. This gives rise to least-squares finite element methods to solve differential equations. It also gives rise to linear system solvers such as GMRES.
Anyway, I agree with you, but wanted to add that it's an idea part of a greater strategy that gives rise to a huge number of good algorithms.
In other words: these are polynomials with n variables. every variable is either zero or one. addition is modulo 2. Each variable corresponds to a single bit in a binary number. Can we construct a polynomial that produces any given length 2^n sequence?
One way this is done by induction on the number of variables. I find this proof to be extremely compelling. I derived it myself one time and it has stuck with me.
The faster way to do this is through a Walsh transform. This proof converts the problem to a matrix equation by simply manipulating a sum. The Walsh matrix itself is an interesting fractal because it's a Hadamard matrix.
These two simple proofs give different perspectives
I was on the panel for interviewing software engineer candidates at a large software company where I worked earlier. I asked one junior candidate (having a few years of experience) to tell me how she would solve the set cover problem [1].
I illustrated the problem with a concrete example: a project needing to fill roles with different tech skills; there is a pool of candidates, each of whom had one or more of those skills; and the goal is to find the minimum set (i.e. number) of candidates, the union of whose skills matches the total set of skills needed for the project. (Contrived problem, of course, since just having multiple skills might not mean a candidate would have the bandwidth to use all of them in the project.)
She started out by making up an example set of skills, an example pool of candidate names and their skills, thought for a bit, and then started describing how she would solve the problem.
I asked her to stop, and then, using an OOP analogy, said something like: You are giving a solution for an instance of the problem. Can you give me a solution for the class of the problem? :) That is, give a solution in generic terms, without using a specific input data set. Don't remember whether she could do that or not. But she was quite good at all the other areas tested on, and got the job.
https://en.wikipedia.org/wiki/Set_cover_problem
I didn't know the following about it before (from the Wikipedia page):
[ The set cover problem is a classical question in combinatorics, computer science and complexity theory. It is one of Karp's 21 NP-complete problems shown to be NP-complete in 1972.
It is a problem "whose study has led to the development of fundamental techniques for the entire field" of approximation algorithms.[1] ]
- many recursive algorithms (I said why I think so, in another comment in this thread, agreeing with kamaal's comment about recursion - https://news.ycombinator.com/item?id=18236708 ), and recursive data structures too; to repeat: elegance and simplicity, although you have to think for a while to grok some of them - then it suddenly becomes clear how they work.
- Huffman encoding and decoding (mentioned by someone else here too; I had also commented about this on HN earlier (I think in an HN thread about old BYTE magazine issues being available on the Internet Archive). I had seen an elegant Huffman algorithm in an old BYTE issue; the author was Jonathan Amsterdam; IIRC, a tree was used to both build the codes and decode the encoded data;
- Depth First Search is cool; others in this thread said it too; "The Go Programming Language" book (code at gopl.io) has a nice example of it, which they use to implement a topological sort, to find a valid ordering of all (e.g. computer science) courses, given the prerequisite courses for each course. The code for it is pretty short and clear, which makes it more cool. Topological sorting has many uses. Scheduling (somewhat similar to the course ordering above) is one such use. Another interesting one is the tsort Unix command, which I used to use in C program compiler / linker commands in my early Unix C programming days. A typical usage (IIRC) is to pipe the lorder command to tsort as part of the compiling / linking process, and use the output in the surrounding compiler or linker command (using shell command substitution). I forget the exact details now (it probably involved a pipeline using the commands cc, ar, lorder and tsort), but it can be looked up.
Someone else mentioned XOR (exclusive OR). I once wrote two C programs for encrypting and decrypting files using this property of XOR, which I read about somewhere:
- if A XOR B gives C,
then C XOR B gives A,
for any bit patterns A, B and C.
Putting it in other words, if you XOR a byte A (from your input) with a bit pattern B (of byte length), then XORing the output (C) with the same bit pattern B, gives you A back as the output. So you can use it to encrypt and decrypt bytes, although the algorithm is easily decipherable, if you know about it. So caveat lector: it is not strong encryption, at all.
Demo of that in Python:
In [133]: for c in 'abcdefghij':
...: oc1 = ord(c)
...: oc2 = oc1 ^ 255
...: oc3 = oc2 ^ 255
...: print oc1, oc2, oc3
...:
97 158 9798 157 98
99 156 99
100 155 100
101 154 101
102 153 102
103 152 103
104 151 104
105 150 105
106 149 106
You can see that the numbers in the 1st and 3rd columns above are the same. Another interesting observation is that the numbers in the middle column are incrementally decreasing.
So that rule can be used to encrypt the bytes of a file, by XORing each byte with some specific byte, and writing the XORed results to an output file. To decrypt the file, just XOR each byte from the output (now input) file with the same specific byte as earlier. I had written a C program to accept a string of characters and an input filename, on the command line,and to cyclically use the bytes in that string, to XOR with the bytes in the input file, while both encrypting and decrypting. It worked, but I was surprised to see (IIRC, it was done quite a while ago) that the same string was sometimes seen repeatedly occurring (as plaintext) in the encrypted file. Don't know the mathematical / cryptographical reason for it, if any.
I wonder if tptacek or any other crypto expert here can explain it. maybe there is some mathematical formula or principle behind the phenomenon I observed.