<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by P.G. Baumstarck on Medium]]></title>
        <description><![CDATA[Stories by P.G. Baumstarck on Medium]]></description>
        <link>https://medium.com/@thepgb?source=rss-791d06d4bc9d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-UjKX3Wn7Au14jF-OitMHw.jpeg</url>
            <title>Stories by P.G. Baumstarck on Medium</title>
            <link>https://medium.com/@thepgb?source=rss-791d06d4bc9d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:15:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thepgb/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Visualizing Gradient Descent Parameters in Torch]]></title>
            <link>https://medium.com/data-science/visualizing-gradient-descent-parameters-in-torch-332a63d1e5c5?source=rss-791d06d4bc9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/332a63d1e5c5</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <dc:creator><![CDATA[P.G. Baumstarck]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 15:50:12 GMT</pubDate>
            <atom:updated>2024-02-26T15:50:12.919Z</atom:updated>
            <content:encoded><![CDATA[<h4>Prying behind the interface to see the effects of SGD parameters on your model training</h4><p>Behind the simple interfaces of modern machine learning frameworks lie large amounts of complexity. With so many dials and knobs exposed to us, we could easily fall into cargo cult programming if we don’t understand what’s going on underneath. Consider the many parameters of Torch’s <a href="https://pytorch.org/docs/stable/generated/torch.optim.SGD.html">stochastic gradient descent (SGD) optimizer</a>:</p><pre>def torch.optim.SGD(<br>  params, lr=0.001, momentum=0, dampening=0,<br>  weight_decay=0, nesterov=False, *, maximize=False,<br>  foreach=None, differentiable=False):<br>  # Implements stochastic gradient descent (optionally with momentum).<br>  # ...</pre><p>Besides the familiar learning rate lr and momentum parameters, there are several other that have stark effects on neural network training. In this article we’ll visualize the effects of these parameters on a simple ML objective with a variety of loss functions.</p><h3>Toy Problem</h3><p>To start we construct a toy problem of performing linear regression over a set of points. To make it interesting we’re going to use a quadratic function plus noise so that the neural network will have to make trade-offs—and we’ll also get to observe more of the impact of the loss functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*veHPKs8xxSyvnDNCSQq3zw.png" /></figure><p>We start off just using numpy and matplotlib to visualization our data—no torch required yet:</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br><br>np.random.seed(20240215)<br>n = 50<br>x = np.array(np.random.randn(n), dtype=np.float32)<br>y = np.array(<br>  0.75 * x**2 + 1.0 * x + 2.0 + 0.3 * np.random.randn(n),<br>  dtype=np.float32)<br><br>plt.scatter(x, y, facecolors=&#39;none&#39;, edgecolors=&#39;b&#39;)<br>plt.scatter(x, y, c=&#39;r&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxbyrtN1gLhXxKaqW2bONQ.png" /><figcaption>Figure 1. Toy problem set of points.</figcaption></figure><p>Next we’ll break out the torch and introduce a simple training loop for a single-neuron network. To get consistent results when we vary the loss function, we’ll start our training from the same set of parameters each time with the neuron’s first “guess” being the equation y = 6*x — 3 (which we effect via the neuron’s weight and bias parameters):</p><pre>import torch<br><br>model = torch.nn.Linear(1, 1)<br>model.weight.data.fill_(6.0)<br>model.bias.data.fill_(-3.0)<br><br>loss_fn = torch.nn.MSELoss()<br>learning_rate = 0.1<br>epochs = 100<br>optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)<br><br>for epoch in range(epochs):<br>  inputs = torch.from_numpy(x).requires_grad_().reshape(-1, 1)<br>  labels = torch.from_numpy(y).reshape(-1, 1)<br><br>  optimizer.zero_grad()<br>  outputs = model(inputs)<br>  loss = loss_fn(outputs, labels)<br>  loss.backward()<br>  optimizer.step()<br>  print(&#39;epoch {}, loss {}&#39;.format(epoch, loss.item()))</pre><p>Running this gives us text output that shows us the loss is decreasing, eventually down to a minimum, as expected:</p><pre>epoch 0, loss 53.078269958496094<br>epoch 1, loss 34.7295036315918<br>epoch 2, loss 22.891206741333008<br>epoch 3, loss 15.226042747497559<br>epoch 4, loss 10.242652893066406<br>epoch 5, loss 6.987757682800293<br>epoch 6, loss 4.85075569152832<br>epoch 7, loss 3.4395809173583984<br>epoch 8, loss 2.501774787902832<br>epoch 9, loss 1.8742430210113525<br>...<br>epoch 97, loss 0.4994412660598755<br>epoch 98, loss 0.4994412362575531<br>epoch 99, loss 0.4994412660598755</pre><p>To visualize our fit, we take the learned bias and weight out of our neuron and plot the fit against the points:</p><pre>weight = model.weight.item()<br>bias = model.bias.item()<br>plt.scatter(x, y, facecolors=&#39;none&#39;, edgecolors=&#39;b&#39;)<br>plt.plot(<br>  [x.min(), x.max()],<br>  [weight * x.min() + bias, weight * x.max() + bias],<br>  c=&#39;r&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PW5SsGJ3Ma4mY4xrVdFkTw.png" /><figcaption>Figure 2. L2-learned linear boundary on toy problem.</figcaption></figure><h3>Visualizing the Loss Function</h3><p>The above seems a reasonable fit, but so far everything has been handled by high-level Torch functions like optimizer.zero_grad(), loss.backward(), and optimizer.step(). To understand where we’re going next, we’ll need to visualize the journey our model is taking through the loss function. To visualize the loss, we’ll sample it in a grid of 101-by-101 points, then plot it using imshow:</p><pre>def get_loss_map(loss_fn, x, y):<br>  &quot;&quot;&quot;Maps the loss function on a 100-by-100 grid between (-5, -5) and (8, 8).&quot;&quot;&quot;<br>  losses = [[0.0] * 101 for _ in range(101)]<br>  x = torch.from_numpy(x)<br>  y = torch.from_numpy(y)<br>  for wi in range(101):<br>    for wb in range(101):<br>      w = -5.0 + 13.0 * wi / 100.0<br>      b = -5.0 + 13.0 * wb / 100.0<br>      ywb = x * w + b<br>      losses[wi][wb] = loss_fn(ywb, y).item()<br><br>  return list(reversed(losses))  # Because y will be reversed.<br><br>import pylab<br><br>loss_fn = torch.nn.MSELoss()<br>losses = get_loss_map(loss_fn, x, y)<br>cm = pylab.get_cmap(&#39;terrain&#39;)<br><br>fig, ax = plt.subplots()<br>plt.xlabel(&#39;Bias&#39;)<br>plt.ylabel(&#39;Weight&#39;)<br>i = ax.imshow(losses, cmap=cm, interpolation=&#39;nearest&#39;, extent=[-5, 8, -5, 8])<br>fig.colorbar(i)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N2XI9kysEt5wI1hz2IIW5g.png" /><figcaption>Figure 3. L2 loss function on toy problem.</figcaption></figure><p>Now we can capture the model parameters while running gradient descent to show us how the optimizer is performing:</p><pre>model = torch.nn.Linear(1, 1)<br>...<br>models = [[model.weight.item(), model.bias.item()]]<br>for epoch in range(epochs):<br>  ...<br>  print(&#39;epoch {}, loss {}&#39;.format(epoch, loss.item()))<br>  models.append([model.weight.item(), model.bias.item()])<br><br># Plot model parameters against the loss map.<br>cm = pylab.get_cmap(&#39;terrain&#39;)<br>fig, ax = plt.subplots()<br>plt.xlabel(&#39;Bias&#39;)<br>plt.ylabel(&#39;Weight&#39;)<br>i = ax.imshow(losses, cmap=cm, interpolation=&#39;nearest&#39;, extent=[-5, 8, -5, 8])<br><br>model_weights, model_biases = zip(*models)<br>ax.scatter(model_biases, model_weights, c=&#39;r&#39;, marker=&#39;+&#39;)<br>ax.plot(model_biases, model_weights, c=&#39;r&#39;)<br><br>fig.colorbar(i)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWRFSOMb2c3IuWR4mPMkQg.png" /><figcaption>Figure 4. Visualized gradient descent down loss function.</figcaption></figure><p>From inspection this looks exactly as it should: the model starts off at our force-initialized parameters of (-3, 6), it takes progressively smaller steps in the direction of the gradient, and it eventually bottoms-out in the global minimum.</p><h3>Visualizing the Other Parameters</h3><h4>Loss Function</h4><p>Now we’ll start examining the effects of the other parameters on gradient descent. First is the loss function, for which we used the standard L2 loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*1jKrH5Rf-IFVDrqicGSS-g.png" /><figcaption>L2 loss (torch.nn.MSELoss) accumulates the squared error. Source: <a href="https://pytorch.org/docs/stable/generated/torch.nn.MSELoss.html">link</a>. Screen capture by author.</figcaption></figure><p>But there are several other loss functions we could use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*lgD-3oGdTtBaf-PqqsiPtw.png" /><figcaption>L1 loss (torch.nn.L1Loss) accumulates absolute errors. Source: <a href="https://pytorch.org/docs/stable/generated/torch.nn.L1Loss.html">link</a>. Screen capture by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_RJTLoufNBzFgW-Q5G-2pQ.png" /><figcaption>Huber loss (torch.nn.HuberLoss) uses L2 for small errors and L1 for large. Source: <a href="https://pytorch.org/docs/stable/generated/torch.nn.HuberLoss.html">link</a>. Screen capture by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*rnK-VdZeQtNpfUHShDIUoA.png" /><figcaption>Smooth L1 loss (torch.nn.SmoothL1Loss) is roughly equivalent to Huber loss with an extra beta parameter. Source: <a href="https://pytorch.org/docs/stable/generated/torch.nn.SmoothL1Loss.html">link</a>. Screen capture by author.</figcaption></figure><p>We wrap everything we’ve done so far in a loop to try out all the loss functions and plot them together:</p><pre>def multi_plot(lr=0.1, epochs=100, momentum=0, weight_decay=0, dampening=0, nesterov=False):<br>  fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)<br>  for loss_fn, title, ax in [<br>    (torch.nn.MSELoss(), &#39;MSELoss&#39;, ax1),<br>    (torch.nn.L1Loss(), &#39;L1Loss&#39;, ax2),<br>    (torch.nn.HuberLoss(), &#39;HuberLoss&#39;, ax3),<br>    (torch.nn.SmoothL1Loss(), &#39;SmoothL1Loss&#39;, ax4),<br>  ]:<br>    losses = get_loss_map(loss_fn, x, y)<br>    model, models = learn(<br>      loss_fn, x, y, lr=lr, epochs=epochs, momentum=momentum,<br>      weight_decay=weight_decay, dampening=dampening, nesterov=nesterov)<br><br>    cm = pylab.get_cmap(&#39;terrain&#39;)<br>    i = ax.imshow(losses, cmap=cm, interpolation=&#39;nearest&#39;, extent=[-5, 8, -5, 8])<br>    ax.title.set_text(title)<br>    loss_w, loss_b = zip(*models)<br>    ax.scatter(loss_b, loss_w, c=&#39;r&#39;, marker=&#39;+&#39;)<br>    ax.plot(loss_b, loss_w, c=&#39;r&#39;)<br><br>  plt.show()<br><br>multi_plot(lr=0.1, epochs=100)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6pKNbi-mznjKWFYrUDgfw.png" /><figcaption>Figure 5. Visualized gradient descent down all loss functions.</figcaption></figure><p>Here we can see the interesting contours of the non-L2 loss functions. While the L2 loss function is smooth and exhibits large values up to 100, the other loss functions have much smaller values as they reflect only the absolute errors. But the L2 loss’s steeper gradient means the optimizer makes a quicker approach to the global minimum, as evidenced by the greater spacing between its early points. Meanwhile the L1 losses all display much more gradual approaches to their minima.</p><h4>Momentum</h4><p>The next most interesting parameter is the momentum, which dictates how much of the last step’s gradient to add in to the current gradient update going froward. Normally very small values of momentum are sufficient, but for the sake of visualization we’re going to set it to the crazy value of 0.9—kids, do NOT try this at home:</p><pre>multi_plot(lr=0.1, epochs=100, momentum=0.9)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLui2AFzt7D0pafuk3UukA.png" /><figcaption>Figure 6. Visualized gradient descent down all loss functions with high momentum.</figcaption></figure><p>Thanks to the outrageous momentum value, we can clearly see its effect on the optimizer: it overshoots the global minimum and has to swerve sloppily back around. This effect is most pronounced in the L2 loss, whose steep gradients carry it clean over the minimum and bring it very close to diverging.</p><h4>Nesterov Momentum</h4><p>Nesterov momentum is an interesting tweak on momentum. Normal momentum adds in some of the gradient from the last step to the gradient for the current step, giving us the scenario in figure 7(a) below. But if we already know where the gradient from the last step is going to carry us, then Nesterov momentum instead calculates the current gradient by looking ahead to where that will be, giving us the scenario in figure 7(b) below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1M6hPwsTt3tn7cAlQfEDDA.png" /><figcaption>Figure 7. (a) Momentum vs. (b) Nesterov momentum.</figcaption></figure><pre>multi_plot(lr=0.1, epochs=100, momentum=0.9, nesterov=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfsWULAh46qk79wOAFiO6w.png" /><figcaption>Figure 8. Visualized gradient descent down all loss functions with high Nesterov momentum.</figcaption></figure><p>When viewed graphically, we can see that Nesterov momentum has cut down the overshooting we observed with plain momentum. Especially in the L2 case, since our momentum carried us clear over the global minimum, using Nesterov to lookahead where we were going to land allowed us to mix in countervailing gradients from the opposite side of the objective function, in effect course-correcting earlier.</p><h4>Weight Decay</h4><p>Next weight decay adds a regularizing L2 penalty on the values of the parameters (the weight and bias of our linear network):</p><pre>multi_plot(lr=0.1, epochs=100, momentum=0.9, nesterov=True, weight_decay=2.0)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hhvl2A6vfYW6ay1h9_QgeQ.png" /><figcaption>Figure 9. Visualized gradient descent down all loss functions with high Nesterov momentum and weight decay.</figcaption></figure><p>In all cases, the regularizing factor has pulled the solutions away from their rightful global minima and closer to the origin (0, 0). The effect is least pronounced with the L2 loss, however, since the loss values are large enough to offset the L2 penalties on the weights.</p><h4>Dampening</h4><p>Finally we have dampening, which discounts the momentum by the dampening factor. Using a dampening factor of 0.8 we see how it effectively moderates the momentum path through the loss function.</p><pre>multi_plot(lr=0.1, epochs=100, momentum=0.9, dampening=0.8)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LG9A86iZGgEsPAGALXJ2kQ.png" /><figcaption>Figure 10. Visualized gradient descent down all loss functions with high momentum and high dampening.</figcaption></figure><p>Unless otherwise noted, all images are by the author.</p><h3>References</h3><ul><li><a href="https://pytorch.org/docs/stable/generated/torch.nn.MSELoss.html">https://pytorch.org/docs/stable/generated/torch.nn.MSELoss.html</a></li><li><a href="https://pytorch.org/docs/stable/generated/torch.nn.L1Loss.html">https://pytorch.org/docs/stable/generated/torch.nn.L1Loss.html</a></li><li><a href="https://pytorch.org/docs/stable/generated/torch.nn.HuberLoss.html">https://pytorch.org/docs/stable/generated/torch.nn.HuberLoss.html</a></li><li><a href="https://pytorch.org/docs/stable/generated/torch.nn.SmoothL1Loss.html">https://pytorch.org/docs/stable/generated/torch.nn.SmoothL1Loss.html</a></li><li><a href="https://pytorch.org/docs/stable/generated/torch.optim.SGD.html">https://pytorch.org/docs/stable/generated/torch.optim.SGD.html</a></li></ul><h4>See Also</h4><ul><li><a href="https://towardsdatascience.com/extending-context-length-in-large-language-models-74e59201b51f">https://towardsdatascience.com/extending-context-length-in-large-language-models-74e59201b51f</a></li><li>Code available at: <a href="https://github.com/pbaumstarck/scaling-invention/blob/main/code/torch_loss.py">https://github.com/pbaumstarck/scaling-invention/blob/main/code/torch_loss.py</a></li><li><a href="https://github.com/tomgoldstein/loss-landscape">https://github.com/tomgoldstein/loss-landscape</a></li><li><a href="https://neptune.ai/blog/pytorch-loss-functions">https://neptune.ai/blog/pytorch-loss-functions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=332a63d1e5c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/visualizing-gradient-descent-parameters-in-torch-332a63d1e5c5">Visualizing Gradient Descent Parameters in Torch</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Programming Puzzle: Tic-Tac-Toe Keychain]]></title>
            <link>https://thepgb.medium.com/programming-puzzle-tic-tac-toe-keychain-e247cc8c4ec7?source=rss-791d06d4bc9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e247cc8c4ec7</guid>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[P.G. Baumstarck]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 03:18:55 GMT</pubDate>
            <atom:updated>2024-02-28T03:51:26.496Z</atom:updated>
            <content:encoded><![CDATA[<p>I was recently nerd-sniped by the Tic-Tac-Toe keychain pictured below. It’s a simple toy that has a 3-by-3 grid of spinners where each can be in one of three states: empty, “X,” and “O.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*Aao0SxtB4GL3D5v1T_KL7A.png" /><figcaption>Figure 1. The latest inanimate object to nerd-snipe me.</figcaption></figure><p>I know Tic-Tac-Toe is a solved game, but my simple question was, if you randomly spin all the pieces on this keychain, what are the odds that the board you get is a legal position? As seen in Figure 2, you could spin all empties, all “X”s, or all “O”s, but only one of these positions is legal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dgx1ltKnNX3Chua_F4fCqA.png" /><figcaption>Figure 2. Some legal and illegal positions in Tic-Tac-Toe Keychain.</figcaption></figure><p>The answer will be a good exercise in basic search strategies.</p><h3>High-Level Approach</h3><p>The Tic-Tac-Toe game has nine spaces, each of which has an equal chance of being one of either three outcomes, which means there are 3⁹ or 19,683 possible boards. This is a very small number from a computational perspective, meaning we should be able to use any approach — including exhaustive search — to find the solution.</p><p>The first approach we’ll program is depth-first search. Starting from a blank board, we’ll try out all possible moves for “X,” then try out all possible moves for “O,” and stop whenever the game reaches a terminal state. This way we’ll never be able to get to an invalid state, and the total number of states we reach will give us our answer.</p><h3>Approach #1: Exhaustive Search</h3><p>We’ll represent the board state with a simple 2D array with single string characters and use a convenience method board2str to convert it to a string:</p><pre>def board2str(board):<br>  return &#39;\n&#39;.join(&#39;&#39;.join(_) for _ in board)<br><br>board = [[&#39;.&#39;] * 3, [&#39;.&#39;] * 3, [&#39;.&#39;] * 3]<br>print(board2str(board))<br># ...<br># ...<br># ...<br><br>board[1][1] = &#39;x&#39;<br>board[2][2] = &#39;o&#39;<br>print(board2str(board))<br># ...<br># .x.<br># ..o</pre><p>We’ll use DFS to do our exhaustive search, which calls for a code skeleton like this:</p><pre>def dfs(board, valids):<br>  valids.append([row.copy() for row in board])<br>  if not is_final_state(board):<br>    for next_board in next_states(board):<br>      dfs(next_board, valids)</pre><p>It doesn’t matter whether we use DFS or BFS since we’re not looking for the shortest path (for which BFS is designed), nor do we care about limiting memory consumption (for which DFS does better). We will also save all states we see on the way to get a full count of the legal positions.</p><h4>Checking Final State</h4><p>To implement the is_final_state function, we need to check whether the game has been won or whether every space has been filled:</p><pre>def is_final_state(board):<br>  if sum(board[r][c] != &#39;.&#39; for r in range(3) for c in range(3)) == 9:<br>    # All spaces filled.<br>    return True<br><br>  for win in (&#39;x&#39;, &#39;o&#39;):<br>    # Check wins along a row.<br>    for r in range(3):<br>      if all(piece == win for piece in board[r]):<br>        return True<br><br>    # Check wins along a column.<br>    for c in range(3):<br>      if all(board[r][c] == win for r in range(3)):<br>        return True<br><br>    # Check diagonals.<br>    if board[0][0] == win and board[1][1] == win and board[2][2] == win:<br>      return True<br>    if board[0][2] == win and board[1][1] == win and board[2][0] == win:<br>      return True<br><br>  return False<br><br>print(is_final_state([<br>  list(&#39;...&#39;),<br>  list(&#39;.x.&#39;),<br>  list(&#39;..o&#39;),<br>]))<br># False<br>print(is_final_state([<br>  list(&#39;..x&#39;),<br>  list(&#39;..x&#39;),<br>  list(&#39;..x&#39;),<br>]))<br># True<br>print(is_final_state([<br>  list(&#39;o.x&#39;),<br>  list(&#39;.ox&#39;),<br>  list(&#39;..o&#39;),<br>]))<br># True<br>print(is_final_state([<br>  list(&#39;xoo&#39;),<br>  list(&#39;oxx&#39;),<br>  list(&#39;xxo&#39;),<br>]))<br># True</pre><h4>Getting Next States</h4><p>And then the next_states function:</p><pre>def next_states(board):<br>  next_piece = &#39;x&#39; if sum(board[r][c] != &#39;.&#39; for r in range(3) for c in range(3)) % 2 == 0 else &#39;o&#39;<br>  for r in range(3):<br>    for c in range(3):<br>      if board[r][c] == &#39;.&#39;:<br>        next_board = [row.copy() for row in board]<br>        next_board[r][c] = next_piece<br>        yield next_board<br><br>for next_board in next_states([<br>  list(&#39;o.x&#39;),<br>  list(&#39;.ox&#39;),<br>  list(&#39;...&#39;),<br>]):<br>  print(&#39;\n&#39; + board2str(next_board))<br><br># oxx<br># .ox<br># ...<br><br># o.x<br># xox<br># ...<br><br># o.x<br># .ox<br># x..<br><br># o.x<br># .ox<br># .x.<br><br># o.x<br># .ox<br># ..x</pre><p>You might have noticed that programming the game mechanics has taken around 30 lines of code while programming the DFS has taken only 5. This is typical of algorithms problems where the ultimate approach is simple (like DFS) but the problem requires much more special handling of its state and mechanics. This skew is even worse in, say, machine learning, where the core algorithm may only be 5 lines of PyTorch but readying the data to feed into the algorithm takes 300 lines.</p><h4>Initial Run</h4><p>Finally we are ready to run our function. I will also use import time to time its execution since I expect it to be very fast:</p><pre>def dfs(board, valids):<br>  valids.append([row.copy() for row in board])<br>  if not is_final_state(board):<br>    for next_board in next_states(board):<br>      dfs(next_board, valids)<br><br>import time<br><br>valids = []<br>start_time = time.time()<br>dfs([[&#39;.&#39;] * 3 for _ in range(3)], valids)<br>stop_time = time.time()<br>print(&#39;Num valids:&#39;, len(valids), &#39;took:&#39;, stop_time - start_time, &#39;s&#39;)<br># Num valids: 549946 took: 5.579200983047485 s</pre><p>One, this took way too long — 5.6 seconds on a MacBook — and two, it’s wrong, since 549,946 &gt;&gt; 3⁹.</p><p>The problem turns out to be that we’re counting duplicated versions of states. Consider the scenario outlined below in Figure 3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2ql9g-y0xo_PZ-Ua8z32A.png" /><figcaption>Figure 3. Two ways to arrive at a duplicate state: (a) [(0,0-&gt;’x’), (0,1-&gt;’o’), (0,2-&gt;’x’)]; and (b) [(0,2-&gt;’x’), (0,1-&gt;’o’), (0,0-&gt;’x’)].</figcaption></figure><p>A simple fix for this would be to turn valids into a set to only save (and continue to examine) board states that we haven’t seen before:</p><pre>def dfs2(board, valids):<br>  board_str = board2str(board)<br>  if board_str not in valids:<br>    valids.add(board_str)<br>    if not is_final_state(board):<br>      for next_board in next_states(board):<br>        dfs2(next_board, valids)<br><br>import time<br><br>valids = set()<br>start_time = time.time()<br>dfs2([[&#39;.&#39;] * 3 for _ in range(3)], valids)<br>stop_time = time.time()<br>print(&#39;Num valids:&#39;, len(valids), &#39;took:&#39;, stop_time - start_time, &#39;s&#39;)<br># Num valids: 5478 took: 0.10553789138793945 s</pre><p>This took only 0.1 seconds — that’s more like it — and now we get 5,478 valid states. This seems correct as it’s only 27.83% of the total 19,683 possible boards, meaning if you spin a random position you have about a 1 in 4 chance of it being a valid board. But the bug we encountered in implementing Tic-Tac-Toe — the simplest of all games — convinces me to try another solution to cross-check.</p><h3>Approach #2: Filtering</h3><p>Our first approach used the rules of the game to simulate all legal moves, but a dual approach would be to generate every possible board state and then check whether it’s legal or not. Instead of using the rules of Tic-Tac-Toe to guide the search, we’ll use brute force to generate all solutions and only apply the rules as a check:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KcckvzMXxI_gzwgZd6AcAQ.png" /></figure><h4>Generate All Boards</h4><p>The approach we’ll use to generate all boards is to recursively build up an array nine elements long. Each invocation of the recursive function will be responsible for filling in all possible values of another position. At the end when we’ve filled up all nine positions, we’ll check if the position is valid before saving it to our list of solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bP01OPNvSeX3mSDW-KhzEA.png" /><figcaption>Figure 4. DFS strategy for generating all possible boards.</figcaption></figure><pre>def dfs3(cells, valids):<br>  if len(cells) == 9:<br>    board = [cells[:3], cells[3:6], cells[6:]]<br>    if is_valid(board):<br>      valids.append([row.copy() for row in board])<br>  else:<br>    dfs3(cells + [&#39;.&#39;], valids)<br>    dfs3(cells + [&#39;x&#39;], valids)<br>    dfs3(cells + [&#39;o&#39;], valids)<br><br>valids_exhaustive = []<br>dfs3([], valids_exhaustive)<br>print(&#39;Valids:&#39;, len(valids_exhaustive))</pre><p>Now we have to implement the is_valid check. If we start out with is_valid = lambda b: True, it should just count the number of all possible boards:</p><pre>def is_valid(board):<br>  return True<br><br>valids_exhaustive = []<br>dfs3([], valids_exhaustive)<br>print(&#39;Valids:&#39;, len(valids_exhaustive))<br># Valids: 19683</pre><p>So far so good. Now let’s screen out boards which have an invalid number of X’s and O’s, since there can only ever be one more X than the number of Os:</p><pre>def is_valid(board):<br>  num_xs = sum(sum(_ == &#39;x&#39; for _ in row) for row in board)<br>  num_os = sum(sum(_ == &#39;o&#39; for _ in row) for row in board)<br><br>  if (num_xs - num_os) not in (0, 1):<br>    return False<br><br>  return True<br><br>valids_xo = []<br>dfs3([], valids_xo)<br>print(&#39;X-O count valids:&#39;, len(valids_xo))<br># X-O count valids: 6046</pre><p>Now we need a function to check if someone has won, and it will return all the positions in the board that constitute their winning position:</p><pre>def check_wins(board, win):<br>  win_positions = set()<br><br>  # Check wins along a row.<br>  for r in range(3):<br>    if all(piece == win for piece in board[r]):<br>      win_positions.update([(r, c) for c in range(3)])<br><br>  # Check wins along a column.<br>  for c in range(3):<br>    if all(board[r][c] == win for r in range(3)):<br>      win_positions.update([(r, c) for r in range(3)])<br><br>  # Check diagonals.<br>  if board[0][0] == win and board[1][1] == win and board[2][2] == win:<br>    win_positions.update([(0, 0), (1, 1), (2, 2)])<br>  if board[0][2] == win and board[1][1] == win and board[2][0] == win:<br>    win_positions.update([(0, 2), (1, 1), (2, 0)])<br><br>  return win_positions<br><br>def is_valid(board):<br>  num_xs = sum(sum(_ == &#39;x&#39; for _ in row) for row in board)<br>  num_os = sum(sum(_ == &#39;o&#39; for _ in row) for row in board)<br><br>  if (num_xs - num_os) not in (0, 1):<br>    return False<br><br>  x_wins = check_wins(board, &#39;x&#39;)<br>  o_wins = check_wins(board, &#39;o&#39;)<br>  if x_wins and o_wins:<br>    return False<br><br>  return True<br><br>valids_xo_double_win = []<br>dfs3([], valids_xo_double_win)<br>print(&#39;X-O count, no double wins valids:&#39;, len(valids_xo_double_win))<br># X-O count, no double wins valids: 5890</pre><p>By checking that both X and O can’t win at the same time, we’re down to 5,890 valid states —still higher than 5,478. To figure out what’s wrong, we can subtract our previous set of valids boards from valids_xo_double_win to see what we’re still counting as legal boards:</p><pre>print(set(map(board2str, valids_xo_double_win)) - valids)<br># {&#39;xxo\nxoo\nxo.&#39;, &#39;oxx\noxx\no..&#39;, &#39;oxo\n.x.\n.xo&#39;, &#39;.x.\nox.\noxo&#39;, <br># &#39;x.x\nooo\nxx.&#39;, &#39;..o\nxxx\noo.&#39;, &#39;oo.\no..\nxxx&#39;, &#39;ooo\nxx.\n.xx&#39;,<br># &#39;oox\noxo\nxx.&#39;, &#39;xxx\noo.\no..&#39;, &#39;.ox\noxo\nx..&#39;, &#39;oox\noox\nx.x&#39;,<br># &#39;.xo\nxxo\nx.o&#39;, &#39;xoo\nx.o\nx..&#39;, &#39;oox\n.xx\nxoo&#39;, &#39;o.x\n.xo\nx.o&#39;, ...</pre><p>Illustrating a few of these cases in Figure 5, we can see the problem in (5.a) is that X has won but with the same number of moves as O—impossible. The same is true in (5.c), and in (5.b) O has won with fewer moves than X.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7l_Tbe2aNapFiKq3BJFEbw.png" /><figcaption>Figure 5. Some illegal positions we haven’t filtered out yet.</figcaption></figure><p>We can adjust our filtering function to apply this extra constraint when the board state is won:</p><pre>def is_valid(board):<br>  num_xs = sum(sum(_ == &#39;x&#39; for _ in row) for row in board)<br>  num_os = sum(sum(_ == &#39;o&#39; for _ in row) for row in board)<br><br>  if (num_xs - num_os) not in (0, 1):<br>    return False<br><br>  x_wins = check_wins(board, &#39;x&#39;)<br>  o_wins = check_wins(board, &#39;o&#39;)<br>  if x_wins and o_wins:<br>    return False<br>  if x_wins and num_xs != num_os + 1:<br>    return False<br>  if o_wins and num_xs != num_os:<br>    return False<br><br>  return True<br><br>valids_xo_fixed_win = []<br>dfs3([], valids_xo_fixed_win)<br>print(&#39;X-O count, fixed win valids:&#39;, len(valids_xo_fixed_win))<br># X-O count, fixed win valids: 5478</pre><p>And we’ve finally achieved the number we sought: 5,478.</p><h3>Approach #3: Counting and Filtering</h3><p>A final approach will be to use counting to enumerate all boards and then apply the same filtering approach. Since each board is composed of nine ternary values, we can count from 0 to 3⁹, convert each number to ternary, and then interpret the digit values 0 as empty, 1 as “X”, and 2 as “O” to convert it to a board. For example, the ternary number 021010012 could be converted to the string &quot;.ox.x..xo&quot;, which represents a board:</p><pre>def pos2board(pos):<br>  c = lambda c: &#39;x&#39; if c == 1 else (&#39;o&#39; if c == 2 else &#39;.&#39;)<br>  return [<br>    [c(pos[0]), c(pos[1]), c(pos[2])],<br>    [c(pos[3]), c(pos[4]), c(pos[5])],<br>    [c(pos[6]), c(pos[7]), c(pos[8])],<br>  ]<br><br>print(board2str(pos2board([0, 2, 1, 0, 1, 0, 0, 1, 2])))<br># .ox<br># .x.<br># .xo</pre><p>To generate all possible 9-digit ternary numbers, we just need to count from 0 to 3⁹ and convert the number from decimal to ternary:</p><pre>valid_counting = set()<br>for i in range(3 ** 9):<br>  pos = []<br>  v = i<br>  for j in range(9):<br>    pos.append(i % 3)<br>    i = i // 3<br><br>  board = pos2board(pos)<br>  if is_valid(board):<br>    valid_counting.add(board2str(board))<br><br>print(&#39;Counting valids:&#39;, len(valid_counting))<br># Counting valids: 5478</pre><p>And with that we have double-verified our number of 5,478 valid states. We can rest reasonably assured that the odds of any random Tic-Tac-Toe Keychain position being legal are about 27.83%.</p><p>Unless otherwise noted, all images by the author.</p><h3>References</h3><p>[1] Juptyer notebook at <a href="https://github.com/pbaumstarck/scaling-invention/blob/main/code/tic_tac_toe_keychain.ipynb">https://github.com/pbaumstarck/scaling-invention/blob/main/code/tic_tac_toe_keychain.ipynb</a></p><p>[2] <a href="https://en.wikipedia.org/wiki/Tic-tac-toe">https://en.wikipedia.org/wiki/Tic-tac-toe</a></p><p>[3] <a href="https://en.wikipedia.org/wiki/Depth-first_search">https://en.wikipedia.org/wiki/Depth-first_search</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e247cc8c4ec7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sharpen Your Redis Skills with the AlgoRedis Challenge]]></title>
            <link>https://levelup.gitconnected.com/sharpen-your-redis-skills-with-the-algoredis-challenge-01f64fa5da84?source=rss-791d06d4bc9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/01f64fa5da84</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[coding-challenge]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[P.G. Baumstarck]]></dc:creator>
            <pubDate>Sun, 25 Feb 2024 20:03:12 GMT</pubDate>
            <atom:updated>2024-02-25T20:03:12.786Z</atom:updated>
            <content:encoded><![CDATA[<p>Redis is a popular in-memory database whose API mimics natural data structures (lists, maps, sets, etc.). There’s a <a href="https://try.redis.io/">tutorial database</a> available to try out the basic commands, but I’ve never found this helped me pick up the syntax reliably. But since Redis was designed to mimic data structures, it turns out you can use it to solve algorithms challenges, and that I’ve found provides much quicker practice with the API. In this article we’ll look at how to take standard algorithms problems and solve them using Redis in the “<a href="https://github.com/pbaumstarck/algoredis">AlgoRedis</a>” challenge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-H3rqdMGEpk4kmslfYmo4Q.png" /><figcaption>Image generated with MidJourney for an “abstract representation of algorithms.”</figcaption></figure><h3>The Rules</h3><p>First we need to establish the parameters of the challenge:</p><h4>Rule #1. All l-values must be stored in Redis</h4><p>L-values are any values that can be modified, and using local variables for this purpose is disallowed:</p><pre># ILLEGAL<br>index = 0<br>index += 1</pre><p>Instead all l-values must be stored in Redis:</p><pre>red.set(&#39;index&#39;, 0)<br>red.incr(&#39;index&#39;)</pre><h4>Rule #2. All l-values must be modified natively on Redis</h4><p>This is to make sure people aren’t cheating by taking variables out of Redis, modifying them locally, and then pushing them back:</p><pre># ILLEGAL<br>red.rpush(&#39;array&#39;, *[1, 2, 3, 4]<br>popped = red.lindex(&#39;array&#39;, -1)<br>red.rpush(&#39;new_array&#39;, *red.lrange(&#39;array&#39;, 0, -2))<br>red.rename(&#39;new_array&#39;, &#39;array&#39;)</pre><p>Instead one must use the native Redis operations:</p><pre>red.rpush(&#39;array&#39;, *[1, 2, 3, 4])<br>popped = red.rpop(&#39;array&#39;)</pre><h4>Rule #3. Local variables are still allowed if they’re constant</h4><p>One can still use local variables if they never change, including for and comprehension variables:</p><pre># Allowed<br>for i in range(red.llen(&#39;array&#39;)):<br>  value = red.lindex(&#39;array&#39;, i)<br>  if value &gt; 0:<br>    red.rpush(&#39;positive&#39;, value)<br><br>non_positive = sum(elem &lt;= 0 for elem in red.lrange(&#39;array&#39;, 0, -1))</pre><h4>Rule #4. All function parameters must be Redis keys or constants</h4><p>This is to make sure one cannot use the arguments of a recursive function to simulate a stack and supplant a Redis data structure:</p><pre># ILLEGAL<br>def recursive(index: int):<br>  if red.lindex(&#39;array&#39;, index):<br>    recursive(index + 1)</pre><p>Instead:</p><pre>red.delete(&#39;@stack&#39;)<br>red.rpush(&#39;@stack&#39;, index)<br>while red.llen(&#39;@stack&#39;):<br>  index = red.lpop(&#39;@stack&#39;)<br>  # ...<br>  red.rpush(&#39;@stack&#39;, index + 1)</pre><h3>Setting up Redis</h3><p>The first step is setting up a local Redis instance. Redis is a distributed datastore so we need to have a server running that our Python can issue commands to. But with three simple shell commands one can get a localhost Redis instance up:</p><pre>% brew install redis<br>% pip install redis-cli<br>% redis-server<br>97384:C 21 Feb 2024 14:52:46.343 * oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo<br>97384:C 21 Feb 2024 14:52:46.343 * Redis version=7.2.4, bits=64, commit=00000000, modified=0, pid=97384, just started<br>97384:C 21 Feb 2024 14:52:46.343 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf<br>97384:M 21 Feb 2024 14:52:46.344 * Increased maximum number of open files to 10032 (it was originally set to 2560).<br>97384:M 21 Feb 2024 14:52:46.344 * monotonic clock: POSIX clock_gettime<br>                _._                                                  <br>           _.-``__ &#39;&#39;-._                                             <br>      _.-``    `.  `_.  &#39;&#39;-._           Redis 7.2.4 (00000000/0) 64 bit<br>  .-`` .-```.  ```\/    _.,_ &#39;&#39;-._                                  <br> (    &#39;      ,       .-`  | `,    )     Running in standalone mode<br> |`-._`-...-` __...-.``-._|&#39;` _.-&#39;|     Port: 6379<br> |    `-._   `._    /     _.-&#39;    |     PID: 97384<br>  `-._    `-._  `-./  _.-&#39;    _.-&#39;                                   <br> |`-._`-._    `-.__.-&#39;    _.-&#39;_.-&#39;|                                  <br> |    `-._`-._        _.-&#39;_.-&#39;    |           https://redis.io       <br>  `-._    `-._`-.__.-&#39;_.-&#39;    _.-&#39;                                   <br> |`-._`-._    `-.__.-&#39;    _.-&#39;_.-&#39;|                                  <br> |    `-._`-._        _.-&#39;_.-&#39;    |                                  <br>  `-._    `-._`-.__.-&#39;_.-&#39;    _.-&#39;                                   <br>      `-._    `-.__.-&#39;    _.-&#39;                                       <br>          `-._        _.-&#39;                                           <br>              `-.__.-&#39;                    </pre><p>We can test the datastore’s functionality from a starter Python file.</p><pre>import redis<br><br>red = redis.Redis(host=&#39;localhost&#39;, port=6379, decode_responses=True)<br>print(red.keys())<br># &gt; []<br><br>red.set(&#39;foo&#39;, 0)<br>print(red.keys())<br># &gt; [&#39;foo&#39;]<br><br>print(red.get(&#39;foo&#39;))<br># &gt; 0<br>print(red.incr(&#39;foo&#39;))<br># &gt; 1<br>print(red.get(&#39;foo&#39;))<br># &gt; 1</pre><p>One crucial thing to beware of is, since the datastore is running in a separate process, values will persist across multiple runs of a Python file. If we run a script that builds an array, then we run that script again, we will have twice as many elements in the array:</p><pre>### test.py FIRST EXECUTION ###<br><br>import redis<br><br>red = redis.Redis(host=&#39;localhost&#39;, port=6379, decode_responses=True)<br>print(red.keys())<br># &gt; []<br><br>red.rpush(&#39;foo&#39;, 1)<br>red.rpush(&#39;foo&#39;, 2)<br>print(red.lrange(&#39;foo&#39;, 0, -1))<br># &gt; [&#39;1&#39;, &#39;2&#39;]<br><br>### test.py SECOND EXECUTION ###<br>import redis<br><br><br>red = redis.Redis(host=&#39;localhost&#39;, port=6379, decode_responses=True)<br>print(red.keys())<br># &gt; [&#39;foo&#39;]<br><br>red.rpush(&#39;foo&#39;, 1)<br>red.rpush(&#39;foo&#39;, 2)<br>print(red.lrange(&#39;foo&#39;, 0, -1))<br># &gt; [&#39;1&#39;, &#39;2&#39;, &#39;1&#39;, &#39;2&#39;]</pre><p>For safety we will call red.flushall() to erase all keys at the start of a run.</p><h4>Modified Hungarian Notation</h4><p>A final note is that I found Redis-only code hard to read because the types are defined by the API. In Python, all variables’ types are obvious from their syntax and usage:</p><pre>a += 1<br>string = &#39;asdf&#39;<br>hash_map[&#39;foo&#39;] = &#39;bar&#39;<br>list = list + [3]<br>hash_set = a | b</pre><p>But this gets obscured in Redis when just dealing with key names:</p><pre>red.incr(&#39;a&#39;)<br>red.set(&#39;string&#39;, &#39;asdf&#39;)<br>red.hset(&#39;hash_map&#39;, &#39;foo&#39;, &#39;bar&#39;)<br>red.rpush(&#39;list&#39;, 3)<br>red.sadd(&#39;hash_set&#39;, red.sinter(&#39;a&#39;, &#39;b&#39;))</pre><p>To address this, we’ll be using a modified form of <a href="https://en.wikipedia.org/wiki/Hungarian_notation">Hungarian notation </a>inspired by Perl syntax where we prefix each key with a special character to denote its type in Redis:</p><ul><li>#foo for numeric variables.</li><li>foo for plain string variables.</li><li>@foo for arrays.</li><li>$foo for hash maps.</li><li>&amp;foo for sets.</li><li>%foo for sorted sets.</li></ul><pre># Numeric variable:<br>red.set(&#39;#a&#39;, 0)<br># Plain string variable:<br>red.set(&#39;foo&#39;, &#39;bar&#39;)<br># Array variable:<br>red.rpush(&#39;@array&#39;, *[0, 1, 2])<br># Hash map variable:<br>red.hset(&#39;$map&#39;, &#39;foo&#39;, 3)<br># Set variable:<br>red.sadd(&#39;&amp;set&#39;, &#39;element&#39;)<br># Sorted set variable:<br>red.zadd(&#39;%sset&#39;, {&#39;element&#39;: 4})</pre><p>Since these prefixes are only part of the string keys on Redis, they have no effect on the code. But having this notation allows us to implement a handy helper function to dump the contents of the database (which would otherwise throw errors when trying to access values with inappropriate commands):</p><pre>def print_all_variables():<br>  for key in sorted(red.keys()):<br>    str_value = &#39;&#39;<br>    if key[0] == &#39;@&#39;:<br>      str_value = red.lrange(key, 0, -1)<br>    elif key[0] == &#39;$&#39;:<br>      str_value = red.hgetall(key)<br>    elif key[0] == &#39;%&#39;:<br>      str_value = red.zrange(key, 0, -1, withscores=True)<br>    elif key[0] == &#39;&amp;&#39;:<br>      str_value = red.smembers(key)<br>    else:<br>      str_value = red.get(key)<br>    print(&#39;%s:&#39; % key, str_value)<br><br>print_all_variables()<br># a: 0<br># $map: {&#39;foo&#39;: &#39;3&#39;}<br># %sset: [(&#39;element&#39;, 4.0)]<br># &amp;set: {&#39;element&#39;}<br># @array: [0, 1, 2]<br># foo: bar</pre><h4>Redis Commands Primer</h4><p>Finally here’s a quick primer on Redis commands for the operative data structures. Literal values can be accessed with the get and set commands. Numeric values also have the convenience methods incr, decr, incrby, and decrby for increment and decrement operations:</p><pre>red.set(&#39;#ctr&#39;, 0)  # 0<br>red.incr(&#39;#ctr&#39;)  # 1<br>red.incrby(&#39;#ctr&#39;, 10)  # 11</pre><p>Lists can be pushed and poped from either end, have their length read, and be indexed into:</p><pre>red.rpush(&#39;@arr&#39;, *[1, 2, 3])  # [1, 2, 3]<br>red.lindex(&#39;@arr&#39;, 2)  # 3<br>red.lpop(&#39;@arr&#39;)  # 1<br>red.llen(&#39;@arr&#39;)  # 2<br>red.lrange(&#39;@arr&#39;, 0, -1)  # [2, 3]</pre><p>Hash maps can have their individual fields set, gotten, queried, and cleared via hset, hget, hexists, andhdel:</p><pre>red.hset(&#39;$map&#39;, &#39;val&#39;, 5)  # {&#39;val&#39;: &#39;5&#39;}<br>red.hexists(&#39;$map&#39;, &#39;next&#39;)  # False<br>red.hset(&#39;$map&#39;, &#39;next&#39;, 7)  # {&#39;val&#39;: &#39;5&#39;, &#39;next&#39;: &#39;7&#39;}<br>red.hkeys(&#39;$map&#39;)  # [&#39;val&#39;, &#39;next&#39;]<br>red.hgetall(&#39;$map&#39;)</pre><p>Sets can be added to with sadd, member-checked with sismember, and retrieved with smembers:</p><pre>red.sadd(&#39;&amp;set&#39;, *[1, 2, 3])  # {&#39;1&#39;, &#39;2&#39;, &#39;3&#39;}<br>red.sadd(&#39;&amp;set&#39;, 3)  # {&#39;1&#39;, &#39;2&#39;, &#39;3&#39;}<br>red.scard(&#39;&amp;set&#39;)  # 3<br>red.smembers(&#39;&amp;set&#39;)  # {&#39;1&#39;, &#39;2&#39;, &#39;3&#39;}</pre><p>Finally a sorted set takes a key–value pair and stores them sorted with zadd, zcard, and zrange:</p><pre>red.zadd(&#39;%sset&#39;, {&#39;five&#39;: 5, &#39;ten&#39;: 10, &#39;zero&#39;: 0})<br>red.zcard(&#39;%sset&#39;)  # 3<br>red.zrange(&#39;%sset&#39;, 0, 0)  # [&#39;zero&#39;]<br>red.zrevrange(&#39;%sset&#39;, 0, 0, withscores=True)  # [(&#39;ten&#39;, 10.0)]</pre><h3>Problem #1: Merging Islands</h3><p>The algorithm we’ll walk through is based on the flood fill algorithm for counting islands. We’re given a grid of zeroes and ones where 1 means land and 0 means ocean, and an island is any contiguous 4-connected segment of 1s:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*e4rUlV6MKtCSKDH98ubG3Q.png" /><figcaption>Figure 1. Our illustrated problem for finding a large island.</figcaption></figure><p>The problem we’ll try to solve is, if we’re allowed to dredge up exactly one ocean tile (a 0) to create land (a 1), what is the biggest combined island we can create?</p><h4>Getting the Data in Redis</h4><p>To get the grid into Redis, we’ll be using a helper function that, given a list of lists, just inters each list as a Redis list using successive keys, then we’ll pass the list of list keys to whatever function we have. This means we’ll have a list of keys of values &quot;@grid-0&quot;, &quot;@grid-1&quot;, etc., to represent the board (this uses the inter_variables helper that’s part of the repo). Printing the contents of memory we get:</p><pre>row_keys = inter_variables(grid=[<br>  list(&#39;000000110000001100&#39;),<br>  list(&#39;000011111001111100&#39;),<br>  list(&#39;000000111111000100&#39;),<br>  list(&#39;001000110000000000&#39;),<br>  list(&#39;011100110001110011&#39;),<br>  list(&#39;011110000111001110&#39;),<br>  list(&#39;000111111110000000&#39;),<br>])[0]<br>print_all_variables()<br># @grid-0: [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0]<br># @grid-1: [0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0]<br># @grid-2: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0]<br># @grid-3: [0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]<br># @grid-4: [0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1]<br># @grid-5: [0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0]<br># @grid-6: [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]</pre><p>Our function will take this list of keys as inut:</p><pre>def largest_island(row_keys: list[str]) -&gt; int:<br>  if not row_keys:<br>      return 0<br><br>  return None</pre><h4>Flood Filling</h4><p>The intuition behind our algorithm is this:</p><ul><li>We’ll loop through the grid once and, every time we find a 1, we’ll flood-fill that island with a unique index starting from 2 (since 0 and 1 are already taken).</li><li>We’ll keep track of the size of each island as we flood-fill in #island_size.</li><li>Finally we’ll save the sizes of all islands in a hash map $island_sizes with keys of the island indices and values of their sizes.</li></ul><p>Implemented:</p><pre>def largest_island(row_keys: list[str]) -&gt; int:<br>  if not row_keys:<br>      return 0<br><br>  m = len(row_keys)<br>  n = red.llen(row_keys[0])<br><br>  # Start island indices from 2 to not conflict with 0 and 1.<br>  red.set(&#39;#island_ix&#39;, 2)<br>  # Map from island indices to size.<br>  red.delete(&#39;$island_sizes&#39;)<br>  # Sorted set to keep track of max island size.<br>  red.delete(&#39;%max_island_size&#39;)<br>  for r in range(m):<br>    for c in range(n):<br>      if red.lindex(row_keys[r], c) == &#39;1&#39;:<br>        # TODO</pre><p>To implement the flood fill, normally we might make a helper function with parameters of (r, c) to allow us to build a stack, but this is disallowed by Rule #4. Instead we’ll use a Redis array to store the arguments on the call stack, and push and pop from it to effect recursion:</p><pre># ...<br>if red.lindex(row_keys[r], c) == &#39;1&#39;:<br>  red.set(&#39;#island_size&#39;, 0)<br>  red.delete(&#39;@flood_fill&#39;)<br>  red.rpush(&#39;@flood_fill&#39;, *(r, c))<br>  while red.llen(&#39;@flood_fill&#39;):<br>    rr, cc = map(int, red.lpop(&#39;@flood_fill&#39;, count=2))<br>    if red.lindex(row_keys[rr], cc) == &#39;1&#39;:<br>      red.lset(row_keys[rr], cc, red.get(&#39;#island_ix&#39;))<br>      red.incr(&#39;#island_size&#39;)<br>      if rr &gt; 0:<br>        red.rpush(&#39;@flood_fill&#39;, *(rr - 1, cc))<br>      if rr + 1 &lt; m:<br>        red.rpush(&#39;@flood_fill&#39;, *(rr + 1, cc))<br>      if cc &gt; 0:<br>        red.rpush(&#39;@flood_fill&#39;, *(rr, cc - 1))<br>      if cc + 1 &lt; n:<br>        red.rpush(&#39;@flood_fill&#39;, *(rr, cc + 1))</pre><p>We can use the convenience methods red.rpush(..., *(...)) to push multiple values at once, and red.lpop(..., count=2) to pop multiple values at once.</p><p>After flood-filling we’ll update the other data structures to keep track of our progress:</p><pre># ...<br># Save the size of the island and increment `island_ix`.<br>red.hset(&#39;$island_sizes&#39;, red.get(&#39;#island_ix&#39;), red.get(&#39;#island_size&#39;))<br>red.zadd(&#39;%max_island_size&#39;, {red.get(&#39;#island_ix&#39;): int(red.get(&#39;#island_size&#39;))})<br>red.incr(&#39;#island_ix&#39;)</pre><p>After this loop completes, we’ll have marked every island with a different number starting from 2 and have counted its size. Iteratively the results will look like Figure 2, and the data we’ll have at the end will be:</p><pre>#island_ix: 5<br>#island_size: 5<br>$island_sizes: {&#39;2&#39;: &#39;25&#39;, &#39;3&#39;: &#39;22&#39;, &#39;4&#39;: &#39;5&#39;}<br>%max_island_size: [(&#39;4&#39;, 5.0), (&#39;3&#39;, 22.0), (&#39;2&#39;, 25.0)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3AzbP7tcJDeNMOpjCI4pA.png" /><figcaption>Figure 2. (a) Starting state; (b) after flood-filling the first island; [c] after the second; (d) after the last.</figcaption></figure><h4>Speculative Dredging</h4><p>Now that we have all our data in place, we must iterate once more through the 0s. For each zero, we’ll build a set out of the non-zero grid values in its 4-connected neighborhood. For the 0 circled below, we will add 2 and 3 to a set. If a zero has any such neighbors, it means we’ll be able to connect them into a new island. We have to use a set for the case where a zero touches a single island at multiple points (like the right-boxed zero) to avoid adding two copies of an island’s size:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*8SP4ec0GcB0aXKyk7r91cw.png" /><figcaption>Figure 3. Dredging the center 0 would connect islands 2 and 3.</figcaption></figure><p>In code we use sets to accumulate the neighbors, then we use a sorted set to track the largest island size. Finally we return the score of the largest island by indexing into the sorted set with zrevrange (which goes from high to low):</p><pre>for r in range(m):<br>  for c in range(n):<br>    if red.lindex(row_keys[r], c) == &#39;0&#39;:<br>      red.delete(&#39;&amp;neighbors&#39;)<br>      if r &gt; 0:<br>        red.sadd(&#39;&amp;neighbors&#39;, red.lindex(row_keys[r - 1], c))<br>      if r + 1 &lt; m:<br>        red.sadd(&#39;&amp;neighbors&#39;, red.lindex(row_keys[r + 1], c))<br>      if c &gt; 0:<br>        red.sadd(&#39;&amp;neighbors&#39;, red.lindex(row_keys[r], c - 1))<br>      if c + 1 &lt; n:<br>        red.sadd(&#39;&amp;neighbors&#39;, red.lindex(row_keys[r], c + 1))<br><br>      # Don&#39;t count zeros since they have no island sizes.<br>      red.srem(&#39;&amp;neighbors&#39;, &#39;0&#39;)<br>      if red.scard(&#39;&amp;neighbors&#39;):<br>        merged_island_size = 1 + sum(map(int, [<br>          red.hget(&#39;$island_sizes&#39;, _) for _ in red.smembers(&#39;&amp;neighbors&#39;)<br>        ]))<br>        red.zadd(&#39;%max_island_size&#39;, { str((r, c)): merged_island_size })<br><br>  return int(red.zrevrange(&#39;%max_island_size&#39;, 0, 0, withscores=True)[0][1])</pre><p>The answer we get is the expected 48:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*PSvgpeTaQyPROEQHyMd2wQ.png" /><figcaption>Figure 4. Our solution shaded in green.</figcaption></figure><h3>Try It Yourself</h3><p>For more Redis algorithms challenges, check out the <a href="https://github.com/pbaumstarck/algoredis">AlgoRedis</a> repo on GitHub. I’ve seed it with 9 problems that cover a range of topics from DFS to dynamic programming. Each problem can be run individually by:</p><pre>$ python3 001_pluck_flowers.py<br><br>Pluck Flowers<br>{&#39;flowers&#39;: [4, 5, 7, 3]} expected: 11 - actual: None  --- result: *** FAILED ***<br>{&#39;flowers&#39;: [2, 7, 9, 3, 1]} expected: 12 - actual: None  --- result: *** FAILED ***<br>{&#39;flowers&#39;: [10, 1, 10, 10, 1, 10]} expected: 30 - actual: None  --- result: *** FAILED ***<br>{&#39;flowers&#39;: [1, 2, 1, 2, 1, 2, 1, 2, 1]} expected: 8 - actual: None  --- result: *** FAILED ***<br>{&#39;flowers&#39;: [3, 4, 10, 10, 8, 5, 9, 2, 3, 0, 4, 1, 3]} expected: 40 - actual: None  --- result: *** FAILED ***<br>{&#39;flowers&#39;: [1, 3, 9, 3, 1, 1, 4]} expected: 15 - actual: None  --- result: *** FAILED ***<br>{&#39;flowers&#39;: [7, 3, 9, 3, 2, 0, 6, 0, 9, 4, 9, 0, 5, 8]} expected: 50 - actual: None  --- result: *** FAILED ***<br>{&#39;flowers&#39;: [1, 9, 7, 9, 6, 2, 1, 1, 4]} expected: 24 - actual: None  --- result: *** FAILED ***<br>{&#39;flowers&#39;: [2, 0, 4, 3, 7, 4, 8, 9, 6, 8, 8]} expected: 35 - actual: None  --- result: *** FAILED ***<br>{&#39;flowers&#39;: [9, 9, 4, 8, 8, 8, 1, 3, 6, 4, 1]} expected: 32 - actual: None  --- result: *** FAILED ***<br><br>Passed 0 / 10</pre><p>And a reference solution is available in the solutions/ directory:</p><pre>$ python3 solutions/001_pluck_flowers.py<br><br>Pluck Flowers<br>{&#39;flowers&#39;: [4, 5, 7, 3]} expected: 11 - actual: 11  --- result: Correct.<br>{&#39;flowers&#39;: [2, 7, 9, 3, 1]} expected: 12 - actual: 12  --- result: Correct.<br>{&#39;flowers&#39;: [10, 1, 10, 10, 1, 10]} expected: 30 - actual: 30  --- result: Correct.<br>{&#39;flowers&#39;: [1, 2, 1, 2, 1, 2, 1, 2, 1]} expected: 8 - actual: 8  --- result: Correct.<br>{&#39;flowers&#39;: [3, 4, 10, 10, 8, 5, 9, 2, 3, 0, 4, 1, 3]} expected: 40 - actual: 40  --- result: Correct.<br>{&#39;flowers&#39;: [1, 3, 9, 3, 1, 1, 4]} expected: 15 - actual: 15  --- result: Correct.<br>{&#39;flowers&#39;: [7, 3, 9, 3, 2, 0, 6, 0, 9, 4, 9, 0, 5, 8]} expected: 50 - actual: 50  --- result: Correct.<br>{&#39;flowers&#39;: [1, 9, 7, 9, 6, 2, 1, 1, 4]} expected: 24 - actual: 24  --- result: Correct.<br>{&#39;flowers&#39;: [2, 0, 4, 3, 7, 4, 8, 9, 6, 8, 8]} expected: 35 - actual: 35  --- result: Correct.<br>{&#39;flowers&#39;: [9, 9, 4, 8, 8, 8, 1, 3, 6, 4, 1]} expected: 32 - actual: 32  --- result: Correct.<br><br>Passed 10 / 10</pre><h3>Takeaways</h3><p>When I started this challenge, I thought it would just be to help learn Redis — even while using it for something it wasn’t strictly intended for. But in the end I realized that implementing some algorithms was easier in Redis than not. Normally debugging means having to stop the program and manually inspect all the variables in memory, but the print_all_variables helper made it easy to instantly inspect the status of the heap, even when doing problems involving linked lists and trees. The semantics of sorted sets also made it easier to build such operations; usually I would have to keep performing successive mins and maxs throughout the code, but the sorted set allowed me to just dump well-formed elements into the sorted set and query it appropriately at the end.</p><h3>References</h3><p>[1] <a href="https://try.redis.io/">https://try.redis.io/</a></p><p>[2] <a href="https://redis.io/commands/">https://redis.io/commands/</a></p><p>[3] <a href="https://github.com/redis/redis-py">https://github.com/redis/redis-py</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01f64fa5da84" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/sharpen-your-redis-skills-with-the-algoredis-challenge-01f64fa5da84">Sharpen Your Redis Skills with the AlgoRedis Challenge</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Book Reviews: Neuromancer; Solaris; The Light of Other Days]]></title>
            <link>https://thepgb.medium.com/book-reviews-neuromancer-solaris-the-light-of-other-days-5f2429a72be8?source=rss-791d06d4bc9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f2429a72be8</guid>
            <category><![CDATA[neuromancer]]></category>
            <category><![CDATA[william-gibson]]></category>
            <category><![CDATA[science-fiction]]></category>
            <category><![CDATA[book-review]]></category>
            <category><![CDATA[solaris]]></category>
            <dc:creator><![CDATA[P.G. Baumstarck]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 02:12:08 GMT</pubDate>
            <atom:updated>2023-03-29T02:12:08.065Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a roundup of science fiction books I’ve read recently:</p><ul><li><em>Neuromancer</em> by William Gibson (third read)</li><li><em>Solaris</em> by Stanislaw Lem</li><li><em>The Light of Other Days</em> by Arthur C. Clarke and Stephen Baxter</li></ul><h3>Neuromancer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*o4mGvLDBwGb_gac7hMCAzw.png" /></figure><p>This is my third time reading <em>Neuromancer</em>, which sits alongside only <em>Nineteen Eighty Four</em> on my top shelf of science fiction novels. And 40 years after its publication, the book still has it all: it created the whole cyberpunk genre that inspired things from <em>The Matrix</em> to <em>Blade Runner 2049;</em> it delves into electronically encoding and preserving human minds, which was most recently explored in HBO’s <em>Westworld</em>; the central story is about jailbreaking an AI with the potential to unleash a singularity, which you can see in <em>Ex Machina</em>; the list of archetypal stories it delivers on is vast.</p><p>On top of its stellar contents, the language is poetic and turgid:</p><blockquote>He closed his eyes.<br>Found the ridged face of the power stud.<br>And in the bloodlit dark behind his eyes, silver phosphenes boiling in from the edge of space, hypnagogic images jerking past like film compiled from random frames. Symbols, figures, faces, a blurred, fragmented mandala of visual information.<br>Please, he prayed, <em>now—<br></em>A gray disk, the color of Chiba sky.<br><em>Now—<br></em>Disk beginning to rotate, faster, becoming a sphere of paler gray. Expanding—<br>And flowed, flowered for him, fluid neon origami trick, the unfolding of his distanceless home, his country, transparent 3D chessboard extending to infinity. Inner eye opening to the stepped scarlet pyramid of the Eastern Seaboard Fission Authority burning beyond the green cubes of Mitsubishi Bank of America, and high and very far away he saw the spiral arms of military systems, forever beyond his reach.<br>And somewhere he was laughing, a white-painted loft, distant fingers caressing the deck, tears of release streaking his face.</blockquote><p>Even though it’s my third time reading the book, my impression keeps evolving. The first time reading it as a teenager I just thought it was an awesome story and that Case was great. My second time reading it a decade later I noticed how poetic the style was and how much more depth there was to Molly’s character. This third time reading it after yet another decade I finally realized I’d completely missed the central character: Linda Lee.</p><p><a href="https://williamgibson.fandom.com/wiki/Linda_Lee">Linda Lee</a></p><p>Though Linda seems to be unceremoniously killed off in Part 1, Gibson keeps summoning her as an apparition throughout the narrative. Whether through flashes on a screen or hallucinations in the sky, Linda becomes a ghostly ostinato weaving in and out of an <em>Inception</em>-like phantasmagoria. At the start of the book, we find Case locked in self-destructive “suicide-by-Night City” spiral in which Linda was the key feature: the girl who loved him but would betray him just to see how much he loved her. Near the end of the book, when Case is absorbed into Neuromancer’s RAM, he finds what he thinks is a simulacrum of Linda but is really a living simulation of her brain, captured before her demise, and who has been brought back to Case in a last-ditch attempt to dissuade him from his path. His guilt over Linda is Case’s only real motivation in the story, and she’s the only one who can influence his actions.</p><p>The first two times I read the book, I never understood why the RAM copy of Case ends up with the RAM copy of Linda, nor why Molly perfunctorily checks herself out of the story. It was obvious to then-me that Case–Molly should be a thing while Case–Linda was old news. This third time reading it, though, I quickly understood. Molly and Case don’t have a relationship; they’re just sex partners who are killing time while on a job. She was too damaged from her own trauma for any normal attachment, and she leaves specifically to keep herself from feeling anything and “losing her edge.” There was never going to be anything there.</p><p>But Linda actually loved Case, only Case was incapable of responding because of his nihilism and death wish. Once that and their other underlying problems were cleared up in Neuromancer’s RAM construct, however, it made sense that they could finally be together. It’s a satisfying glimpse of a Case who can actually care for another person—and of a Linda who can actually constructively be cared for.</p><p>The first time I read <em>Neuromancer</em>, I thought Linda Lee was like Duncan Idaho in <em>Dune</em>: an underdeveloped character who is killed off early for shock and awe. Then the next time I thought she was like Duncan Idaho in <em>Children of Dune</em>: a little bit more developed character who is brought back yet still serves little purpose. But now I know she’s more like Duncan Idaho in <em>Sandworms of Dune</em>: the linchpin to the whole saga that just takes time to manifest.</p><p><a href="https://dune.fandom.com/wiki/Duncan_Idaho">Duncan Idaho</a></p><p>Besides my stellar praise, there is just one nit I have with the book. Now granted <em>Neuromancer</em> is waaaaaay better than anything I’ve ever written, but I will make one small complaint that I don’t think the AI should’ve spoken to Case in the final chapter. The Finn was how the AI used to appear before its fusion with Neuromancer, so it showing up in its old visage was an odd rewind that made it feel like nothing had changed. Also, its mention of contact with aliens felt tacked on and vitiated the impact of the AI’s transformation, which I felt could’ve been left totally open-ended and mysterious. If the epilogue had only included Molly’s breakup shuriken, Case’s last trip to see Ratz, and the vision of RAM Case and RAM Linda, <a href="https://www.youtube.com/watch?v=XPj_J4DW640">that would’ve been perfection</a>. Again, Gibson is a waaaaaay better writer who’s produced far better writing than I ever have, but, if I could get a <em>Neuromancer</em> Director’s Cut, that’s the one tiny tweak I’d like.</p><p>Other than that, 7 out of 5 stars.</p><h3>Solaris</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*TjjBoPzSFPUEVrmGlnJJ_A.png" /></figure><p>I was a big fan of Steven Soderbergh’s 2002 film <a href="https://en.wikipedia.org/wiki/Solaris_(2002_film)"><em>Solaris</em></a>, and definitely not because it included <a href="https://abcnews.go.com/Entertainment/story?id=101168&amp;page=1">George Clooney’s butt</a>. It was 100% because it had Natasha McElhone in it and 0% for Clooney’s butt (okay, 0±5%). So I finally decided I would read the original source material, Stanislaw Lem’s <em>Solaris</em>.</p><p>In this book, Lem does a great job with atmosphere and suspense, and every scene between the main characters has the layerings and tension of a stage play where any moment could turn into <a href="https://www.opensourceshakespeare.org/views/plays/play_view.php?WorkID=titus&amp;Act=5&amp;Scene=3&amp;Scope=scene#2594">mass murder</a> or <a href="https://en.wikipedia.org/wiki/Carnage_(2011_film)">projectile vomiting</a>.</p><p>The first interaction in the book is where our main character, Dr. Kelvin, arrives at Solaris station and meets Dr. Snaut — who is so obviously a suspicious doppleganger who killed and ate the real Dr. Snaut, that it made me remember that that’s what happens in the film: in a third act twist, Dr. Snow (an alternate translation of “Snaut”) is revealed to be a replica who killed his original:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IROjbXUuYMrtqwVq" /><figcaption>“I totally killed and ate myself, bro.”</figcaption></figure><p>So I kept reading waiting for this to be revealed in the book — but it never happened. Despite this being a great twist in the film and feeling a natural fit for the book, I guess either Lem didn’t think of it or just left it implied. There is still much circumstantial evidence for this in Snaut’s behavior, plus the fact that at the end he refuses to leaves Solaris (maybe because, as a replica, he can’t). I felt this omission a pity, however, because I could have imagined a lofty philosophical confrontation between Kelvin and dopple-Snaut concerning egotism and the self. I mean, everyone else’s visitor is a deceased loved one or someone they feel guilt over, but Snaut’s visitor is just his own reflection? What an ego …</p><p>As with any aging science fiction book, <em>Solaris</em> now bears interesting anachronisms. For one, even though they are on a bare bones research station on a remote planet, Lem stresses many times that the station is absolutely chock full of hardcover books that the main character constantly consults. There’s even a plot point where Kelvin needs one key piece of information and he’s lucky that the station has the exact copy of the book he needs. It’s an interesting juxtaposition that this novel is so cutting-edge in pondering the limits of consciousness that it personifies an alien ocean, yet so mundane with general physics that it has space fleets carting around the <em>Encyclopedia Britannica</em>.</p><p>There was also a line that went: “We need to contact the satellite — quick, turn on the interstellar radio! [flips switch] … Just gotta wait a few minutes for the vacuum tubes to warm up.” (Though <em>Neuromancer</em> itself has the infamous line, “Damn, she stole a full <em>three</em> Megabytes of RAM!”)</p><p><em>Solaris</em> also has a long break in the action just after Kelvin arrives when he stops to read from a history book on Solaristics (i.e., the study of Solaris), apparently just to give the reader more backstory. It was kilowords of academic pleonasm where Kelvin recounts in scholarly terms the lives and accomplishments of the many fictional scientists who studied Solaris:</p><blockquote>Muntius analyzes this ‘heresy’ of planetology very simply and trenchantly. He brilliantly dismantles the Solarist myth, or rather the myth of the Mission of Mankind.</blockquote><blockquote>Muntius’s had been the first voice raised in protest, and had encountered the contemptuous silence of the experts, at a time when they still retained a romantic confidence in the development of Solaristics. After all, how could they have accepted a thesis that struck at the foundations of their achievements?</blockquote><blockquote>Solaristics went on waiting for the man who would reestablish it on a firm foundation and define its frontiers with precision. Five years after the death of Muntius, when his pamphlet had become a rare collectors’ piece, a group of Norwegian researchers founded a school named after him …<br>(<a href="https://archive.org/stream/B-001-001-236/B-001-001-236_djvu.txt">source</a>)</blockquote><p>I found this a little surreal, like if Tolkien randomly had Gandalf start reading from an appendix to <em>The Lord of the Rings</em> because he needed to stretch out the plot.</p><p><a href="https://tolkiengateway.net/wiki/The_Lord_of_the_Rings_Appendices">The Lord of the Rings Appendices</a></p><p>Lem also spends much time describing the exact shapes and geometries of the Solaris ocean, which read like an audio description of the <em>Claymore</em> manga for the visually impaired:</p><blockquote>The ‘tree-mountains,’ ‘extensors,’ ‘fungoids,’ ‘mimoids,’ ‘symmetriads’ and ‘asymmetriads,’ ‘vertebrids’ and ‘agilus’ … ‘extensors’ are formations that … are produced in a substance which externally resembles a yeasty colloid … during this fantastic ‘fermentation,’ the yeast sets into festoons of starched open-work lace … like a tensed muscle which fifty feet below the surface is as hard as rock but retains its flexibility … stretching for miles between membranous walls swollen with ‘ossified growths,’ like some colossal python which after swallowing a mountain is sluggishly digesting the meal, while a slow shudder occasionally ripples along its creeping body.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/0*K4gMhm8bqR80ibaK.jpg" /><figcaption>Sometimes reading “Solaris” felt like an audio description of the “Claymore” manga.</figcaption></figure><p>For as baroque as these descriptions are, they don’t factor into the story or its conclusion at all, so I guess it was a weird fetish Lem had.</p><p>In the end, the denouement is that Kelvin has developed a new theory of Solaris being a “despairing god,” which he touts as a novel advance in Solaristics. Given the amount of time Lem spent describing Solaristics, I guess this was supposed to be the big payoff, but it didn’t work for me. I liked the open-ended transformation/apotheosis at the end of the Soderbergh’s <em>Solaris</em> better. In fact, I read the book specifically because I was hoping for more insight into that transformation, so finding it absent from the source material made me really appreciate this touch from Soderbergh.</p><h3><strong>The Light of Other Days</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*D_XOzNSdVhBmLWtuhu-ulg.png" /></figure><p>This one got my list because I listen to the <a href="https://www.youtube.com/channel/UCESLZhusAkFfsNsApnjF_Cg">All-In Podcast</a> and the book is a persistent <a href="https://www.kevinrooke.com/book-recommendations/david-friedberg">recommendation from David Friedberg</a>. I’ve read a lot of books that felt like they didn’t contain enough new ideas, but this is the first book I read that felt like it had four novels’ worth of ideas all crammed into one.</p><p>Novel 1 is where the main characters create wormholes to transfer information instantaneously between any two points. That alone could be a whole story right there, maybe a spy drama about how the walls in the world are brought down and financial markets are upended as the lightspeed limit is abolished. Instead <em>Light </em>races through this concept just to say, “Yeah, governments use it for top secret communications, but not much else—now wait for what comes next …”</p><p>Novel 2 starts when they expand these wormholes to allow visual information to pass through, thus being able to spy on any point on the globe without possibility of countermeasures. The book spends most of its time on this development and does adequately depict a society where privacy is abolished.</p><p>Novel 3 is when they figure out how to use these wormholes to look into the past (even though it breaks the book’s physics), letting them view any historical event. Of course the staunch Catholic main character immediately goes Christ-hunting and the book digresses into an alternate history of Jesus, which is a genre I’m not really interested in.</p><p>Novel 4 is when they figure out how to put wormholes directly in people’s brains and create a hive mind consciousness, and use wormholes to backtrace DNA to find anyone throughout time, and wear Zen Gnostic masks to escape from the prying eyes of “wormcam” operators, and use wormholes to transport thermal energy infinitely cheaply — just a whole lot of stuff happens.</p><p>While I liked all the ideas and developments, I felt they were missing counterpoint. While we do see how society is affected by each new technology, we never see where people counteract or invert the technology. I would have been interested to see everyone become dependent on these technologies, then someone develops an even more brilliant countermeasure that introduces challenging asymmetries once again. Though I can imagine that the author was trying to convey the impression of scientists always racing forward forward forward to see what comes next without pausing to consider the consequences.</p><p>One threat looming over the whole story is the “Wormwood,” an asteroid that will destroy Earth in 500 years. Honestly, I didn’t think this was that big a deal. Seriously, 500 years is a long time. Just 100 years ago humans could barely fly, and now we’re debating the economics of Elon Musk’s plan to colonize Mars. One main character in <em>Light</em> is the reporter who discovered the Wormwood, and I rolled my eyes every time she declared, “I’m a journalist and I can tell you that science will develop <em>nothing </em>over the next five centuries to deal with a large rock, so everything is meaningless and we’ll all be destroyed!” Even the book agrees with me when, in the epilogue, it turns out the Wormwood has been dealt with <a href="https://youtu.be/_HPligKU9AM?t=4394">conveniently and cheaply off screen</a>.</p><h3>Conclusion</h3><p>Next up on my reading list:</p><ul><li><em>Nineteen Eighty Four</em> by George Orwell</li><li><em>Children of Time</em> by Adrian Tchaikovsky</li><li><em>Man in the High Castle</em> by Philip K. Dick</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f2429a72be8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Python Parsing for Narrative Charts]]></title>
            <link>https://medium.com/better-programming/simple-python-parsing-for-narrative-charts-37e51c75ca3d?source=rss-791d06d4bc9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/37e51c75ca3d</guid>
            <category><![CDATA[parsing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[P.G. Baumstarck]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 17:47:30 GMT</pubDate>
            <atom:updated>2023-02-24T17:47:30.457Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to create visualizations for books</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PAdgyyOB-zoL2vJ5" /><figcaption>Photo by <a href="https://unsplash.com/fr/@lukechesser?utm_source=medium&amp;utm_medium=referral">Luke Chesser</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Fans of the webcomic <a href="http://xkcd.com/">xkcd</a> will probably remember the <a href="https://xkcd.com/657/">narrative charts</a> it made for films like <em>The Lord of the Rings</em>, <em>Jurassic Park</em>, and — sarcastically — <em>12 Angry Men:</em></p><p><a href="https://xkcd.com/657/">Movie Narrative Charts</a></p><p>But most xkcd fans probably didn’t know that there was an open-source software <a href="https://github.com/niskander/ComicBookNarrativeCharts">project</a> from the University of Waterloo to create these charts dynamically. The only problem with this project is that it takes data from comic books that I think were generated by hand. I was interested in applying their visualization technique to books, so this is how I hot-wired Python code up to their d3 library to create narrative charts for plays and novels.</p><h3>Data Archeology</h3><p>The original Waterloo project rendered a narrative chart for a comic book panel by panel. The information was fed in via a top-level JSON object that held the work’s title, a top-level list of characters with IDs, and a list of scenes with information about which characters were present in each:</p><pre>{<br>  &quot;title&quot;: &quot;Romeo and Juliet&quot;,<br>  &quot;characters&quot;: [<br>    {<br>      &quot;name&quot;: &quot;Romeo&quot;,<br>      &quot;group&quot;: 1,<br>      &quot;id&quot;: 1,<br>    },<br>    // ...<br>  ],<br>  &quot;scenes&quot;: [<br>    {<br>      &quot;title&quot;: &quot;Act 1&quot;,<br>      &quot;duration&quot;: 10,<br>      &quot;start&quot;: 499,<br>      &quot;chars&quot;: [1, 3, 7],<br>      &quot;named_chars&quot;: [&quot;Romeo&quot;, &quot;Juliet&quot;, &quot;Friar Laurence&quot;],<br>      &quot;id&quot;: 1,<br>    },<br>    // ...<br>  ]<br>}</pre><p>I wanted to use this tool to visualize books and plays, such as <a href="https://www.gutenberg.org/files/1513/1513-h/1513-h.htm"><em>Romeo and Juliet</em></a>; thus, I needed to parse the bodies of those works and process them to look like the above JSON. Luckily — and it’s strange to consider this now — those 16th-century plays were written in a highly structured DSL that looked like this:</p><pre>ACT I<br>SCENE I. A public place.<br>Enter Sampson and Gregory armed with swords and bucklers.<br><br>SAMPSON.<br>Gregory, on my word, we’ll not carry coals.<br><br>GREGORY.<br>No, for then we should be colliers.<br><br>SAMPSON.<br>I mean, if we be in choler, we’ll draw.<br><br>GREGORY.<br>Ay, while you live, draw your neck out o’ the collar.<br><br>SAMPSON.<br>I strike quickly, being moved.</pre><p>It’s as if Shakespeare was using a file format that ended in .play. The act and scene boundaries are all clearly marked, and lines for each character are preceded by their name in uppercase plus a full stop. We could even write a <a href="https://medium.com/@mikhail.barash.mikbar/grammars-for-programming-languages-fae3a72a22c6">grammar file</a> for this:</p><pre>CHARACTER := [A-Z ]+<br>LINE := CHARACTER &quot;.\n&quot; ([a-ZA-Z0-9 ,\&quot;\&#39;\?]+\n)*[a-ZA-Z0-9 ,\&quot;\&#39;\?]+ &quot;\n&quot;<br>STAGE_DIRECTION := ([a-ZA-Z0-9 ,\&quot;\&#39;\?]+\n)*[a-ZA-Z0-9 ,\&quot;\&#39;\?]+ &quot;\n&quot;<br>SCENE := &quot;SCENE &quot; [IVX]+ &quot;.\n&quot; (LINE | STAGE_DIRECTION)+</pre><p>To parse these play scripts, however, we aren’t going to write a full parser with yacc — that would be overkill. But we will do simple traversal through the text lines in the spirit of a one-pointer algorithm.</p><h3>Parsing Is All You Need</h3><p>We’re going to get the play as a list of lines, then use a one-pointer algorithm where we step through the lines using an index i = 0. We want to keep track of which scene we’re in, how many characters there are in each scene, and who spoke what lines, as shown below:</p><pre>import re<br><br>lines = open(filename, &#39;r&#39;).readlines()<br><br>scenes = []<br>last_line_ix = 0<br>last_scene_match = None<br>next_scene_match = None<br><br>i = 0<br>while i &lt; len(lines)<br>  line = lines[i]<br>  next_scene_match = re.match(r&quot;SCENE [IVX]+&quot;, line)<br>  if next_scene_match:<br>    # Save the last scene with all its lines.<br>    if last_scene_match:<br>      scenes.append(<br>        Scene(<br>          title=last_scene_match.group(0),<br>          lines=lines[last_line_ix : i])<br><br>    last_scene_match = next_scene_match<br>    last_line_ix = i + 1<br><br>  i += 1<br><br>if len(lines) &gt; last_line_ix:<br>  scenes.append(<br>    Scene(<br>      title=last_scene_match.group(0),<br>      lines=lines[last_line_ix : len(lines)])</pre><p>Every time we see a new &quot;SCENE &quot; marker, we take whatever lines there have been seen since the last scene marker and snapshot them into a Scene object. The only gotcha with parsing like this is that you usually exit the main loop with some “hanging state.” Since the loop only saves the last scene once it sees a new scene marker — and the play doesn’t end with a trailing scene marker — we have to remember to save the last scene after we exit the loop — that’s the if len(lines) &gt; last_line_x: check.</p><p>One important nuance about parsers is that they should only go in one direction. Of all the code reviews I’ve ever done, the one where I probably had the most benefit to an engineer’s career was one where I was reviewing code like this:</p><pre>i = 0<br>do_other_thing = False<br>while i &lt; len(lines):<br>  line = lines[i]<br>  if do_other_thing:<br>    option_b(line)<br>    i += 1<br>    do_other_thing = False<br>  elif something_else(line):<br>    # Oh, we should have treated the last line differently, so go back.<br>    do_other_thing = True<br>    i -= 1<br>  else:<br>    option_a(line)<br>    i += 1</pre><p>This code had started like a normal one-pointer parser with an index i that moved through the list. But then the programmer found an edge case that meant they had to “go back and fix things,” so they set a flag do_other_thing = True and decremented the pointer with i -= 1. Then on the next loop around, the flag made the parser take a special action.</p><p>The problem with this small change was that it breaks monotonicity. If all the parser does is increment i += 1 from start to finish, then it is guaranteed the program will exit. Once it has a decrement i -= 1, however, the parser is bidirectional, the control flow is much more complicated, and it can potentially end up in an infinite loop. And this code also has a bug — it should be i += 2 instead of i += 1 in the if do_other_thing: branch. Otherwise, it will just hit something_else the next loop around and go backward again, resulting in just such an infinite loop.</p><p>A much better version of this code uses “lookahead” or peeking at the upcoming lines whenever extra information is needed. This is a much cleaner version of the above that uses “lookahead” instead of “rewind.” Here’s what the code looks like:</p><pre>i = 0<br>while i &lt; len(lines):<br>  line = lines[i]<br>  if i + 1 &lt; len(lines) and something_else(lines[i + 1]):<br>    # Treat these lines differently.<br>    option_b(line)<br>    option_b(lines[i + 1])<br>    i += 2<br>  else:<br>    option_a(line)<br>    i += 1</pre><h3>Visualizing the Results</h3><p>After I had all the scenes parsed, I just sent them a list of characters and aliases to search for (such as &quot;ROMEO.&quot; and &quot;JULIET.&quot;) to keep track of who appears in each scene:</p><pre>class Scene(object):<br><br>  def __init__(self, title=None, lines=None):<br>    self.title = title<br>    self.lines = lines<br>    self._character_occs = {}<br>  <br>  def FindCharacters(self, characters):<br>    for line in self.lines:<br>      for character in characters:<br>        for alias in character.aliases:<br>          if alias in line:<br>            self.AddCharacter(character)<br><br>  def AddCharacter(self, character):<br>    if character.name not in self._character_occs:<br>      self._character_occs[character.name] = {<br>          &#39;character&#39;: character,<br>          &#39;count&#39;: 1,<br>      }<br>    else:<br>      self._character_occs[character.name][&#39;count&#39;] += 1</pre><p>The final step was translating this into the format expected by the Waterloo code (which was a <a href="https://github.com/kldvlinearwords/NovelNarrativeCharts/blob/main/novel_narrative_charts.py#L90">little involved</a> and not interesting for this article), then rendering it on a template web page. For <em>Romeo and Juliet</em>, our narrative chart comes out like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SRF_TnIz5SqkGYXFKGKW3w.png" /><figcaption>An xkcd-/Waterloo-style narrative chart for “Romeo and Juliet.”</figcaption></figure><p>It’s neat to see how the characters&#39; narratives weave together, with a major nexus collecting around Tybalt’s demise, Romeo and Juliet flitting around each other until their fateful demise, and Friar Lawrence just masterminding the whole plot surreptitiously from underneath.</p><p>I also wanted to generalize this code to process other works, so I wrapped it up in a script that accepts arguments. Parsing <em>Romeo and Juliet</em> can be accomplished by specifying the input file, scene regex, and character groups like so:</p><pre>./novel_narrative_charts.py \<br>    --book \<br>    --title=&quot;Romeo and Juliet&quot; \<br>    --chapter_regex=&quot;SCENE \\w+\\.&quot; \<br>    --filename=sources/romeo_and_juliet.txt \<br>    --character_group=CAPULET.\|LADY\ CAPULET.,TYBALT. \<br>    --character_group=MONTAGUE.\|LADY\ MONTAGUE.,BENVOLIO. \<br>    --character_group=PARIS.,MERCUTIO.,FRIAR\ LAWRENCE. \<br>    --character_group=JULIET.,ROMEO.</pre><p>With this wrapper, applying this code to other works is easy — and not just plays. To parse one of my favorite novels, <a href="https://www.gutenberg.org/cache/epub/145/pg145-images.html"><em>Middlemarch</em></a>, I just fed it a new set of arguments (although for a novel, this script currently can’t tell the difference between whether a reference to a character’s name means they’re speaking, appearing, or just being talked about):</p><pre>./novel_narrative_charts.py \<br>    --book \<br>    --title=&quot;Middlemarch&quot; \<br>    --chapter_regex=&quot;CHAPTER \\w+\\.&quot; \<br>    --filename=sources/middlemarch.txt \<br>    --character_group=Dorothea\ Brooke\|Dorothea\|Miss\ Brooke,Celia\ Brooke\|Celia,Arthur\ Brooke\|Arthur\|Mr\.\ Brooke \<br>    --character_group=Mary\ Garth\|Mary\|Miss\ Garth,Caleb\ Garth\|Caleb\|Mr\.\ Garth \<br>    --character_group=Tertius\ Lydgate\|Tertius\|Lydgate,James\ Chettam\|James,Will\ Ladislaw\|Will\|Mr.\ Ladislaw \<br>    --character_group=Rosamond\ Vincy\|Rosamond\|Miss\ Vincy\|Mrs\.\ Lydgate,Fred\ Vincy\|Fred,Mr\.\ Casaubon\|Casaubon</pre><p>This resulting chart, however, gets kinda busy, and I may be stretching the limits of this technology as-is (or maybe I should pick a shorter book to analyze):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLjKtxaXGGvmX3WqvO3A-A.png" /></figure><h3>References</h3><ul><li><a href="https://github.com/kldvlinearwords/NovelNarrativeCharts">https://github.com/kldvlinearwords/NovelNarrativeCharts</a></li><li><a href="https://github.com/niskander/ComicBookNarrativeCharts">https://github.com/niskander/ComicBookNarrativeCharts</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*fzWBfFVK5Xj_0v68GpenSA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37e51c75ca3d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/simple-python-parsing-for-narrative-charts-37e51c75ca3d">Simple Python Parsing for Narrative Charts</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Han Solo’s Guide to C++ Casting]]></title>
            <link>https://medium.com/better-programming/han-solos-guide-to-c-casting-344043d90030?source=rss-791d06d4bc9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/344043d90030</guid>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[star-wars]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[P.G. Baumstarck]]></dc:creator>
            <pubDate>Mon, 13 Feb 2023 07:54:47 GMT</pubDate>
            <atom:updated>2024-02-11T05:14:30.826Z</atom:updated>
            <content:encoded><![CDATA[<h4>Clear your C++ cast concepts with Star Wars</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1EBH5_8BwSqyNn0-AbnTlQ.png" /><figcaption>It’s all so simple.</figcaption></figure><p>C++ casts are a common stumbling block for developers. What’s the difference between a static_cast and a dynamic_cast? Or a C-style cast versus std::move? Under what circumstances do you even need to use a const_cast?</p><p>Luckily Han Solo provides a handy rubric to disentangle the many threads of C++ casting.</p><h4>Base Class</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*57unPRNX5DbYxt6eGv7How.png" /></figure><p>We start with a base class, which will be represented by Han Solo as portrayed by Harrison Ford in the original 1977 <em>Star Wars:</em></p><pre>class HanSolo {};<br><br>class HarrisonFord : public HanSolo {<br> private:<br>  int actor_;<br>};<br><br>HanSolo* han_solo = new HarrisonFord();</pre><p>So far so good.</p><h4>static_cast</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*kBsGGPoaDDj-QoUS1sfTgA.png" /></figure><p>The most straightforward cast is <a href="https://en.cppreference.com/w/cpp/language/static_cast">static_cast</a>, which is represented by Han Solo as reprised by Harrison Ford in the 2015 film <em>Star Wars: The Force Awakens</em>.</p><p>He’s the same actor, just more experienced, so it’s safe to perform a cast between these two Han Solos that are the same Harrison Ford underneath (though it might cause undefined behavior if we try to replace the older, more-derived 2015 Harrison Ford with the younger 1977 Harrison Ford):</p><pre>class HanSolo {};<br><br>class HarrisonFord1977 : public HanSolo {<br> private:<br>  int a_new_hope_;<br>};<br><br>class HarrisonFord2015 : public HarrisonFord1977 {<br> private:<br>  int the_force_awakens_;<br>};<br><br>HanSolo* young_han = new HarrisonFord1977();<br>HanSolo* old_han = new HarrisonFord2015();<br><br>// This compiles but produces undefined behavior.<br>HarrisonFord2015* undefined_han = static_cast&lt;HarrisonFord2015*&gt;(young_han);<br>// This compiles and is safe.<br>HarrisonFord2015* old_han1 = static_cast&lt;HarrisonFord2015*&gt;(old_han);</pre><p>This is static_cast. It only performs compile time type-checking to make sure that the two classes involved in the cast are related. It allows downcasting to a more derived type, and upcasting to a less derived type.</p><p>This does allow unsafe conversions because it will downcast a base class into a derived class without checking the type of the pointer.</p><h4>dynamic_cast</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*yroAkh1bib3znvja3WJ3oA.png" /></figure><p>A step up from static_cast is <a href="https://en.cppreference.com/w/cpp/language/dynamic_cast">dynamic_cast</a>, which is represented by Han Solo as portrayed by Alden Ehrenreich in the 2018 film <em>Solo: A Star Wars Story</em>. He’s a completely different actor in a spin-off series, so it’s not safe to just swap in one Han Solo for another.</p><p>We need to perform a runtime type check to make sure that our two Han Solos are compatible — even though they appear to be “implementing the same interface:”</p><pre>class HanSolo {};<br><br>class HarrisonFord1977 : public HanSolo {<br> private:<br>  int a_new_hope_;<br>};<br><br>class AldenEhrenreich2018 : public HanSolo {<br> private:<br>  int a_star_wars_story_;<br>};<br><br>HanSolo* harrison = new HarrisonFord1977();<br>HanSolo* alden = new AldenEhrenreich2018();<br><br>// This compiles and produces a valid pointer.<br>HarrisonFord1977* young_han1 = dynamic_cast&lt;HarrisonFord1977*&gt;(harrison);<br>// This compiles but returns `nullptr` instead.<br>HarrisonFord1977* young_han2 = dynamic_cast&lt;HarrisonFord1977*&gt;(alden);</pre><p>This is dynamic_cast. It performs extra runtime type-checking of the pointers involved to make sure that it doesn’t perform an unsafe downcast, which would otherwise be permitted by static_cast.</p><p>Using this we can make sure not to accidentally cast an Alden Ehrenreich to a Harrison Ford.</p><h4>const_cast</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*7UqkQy2WJPOCpB0HHAYQ2Q.png" /></figure><p>Another peculiarity of C++ is the <a href="https://en.cppreference.com/w/cpp/language/const_cast">const_cast</a>, which is represented by Han Solo frozen in carbonite from 1980’s <em>Star Wars V: The Empire Strikes Back</em>. Han is still Han, but he’s been frozen, so we require a const_cast to thaw him back out to his mutable state:</p><pre>class HanSolo {};<br><br>class HarrisonFord : public HanSolo {<br> public:<br>  int original_trilogy;<br><br>  void check_trilogy() const {<br>    // This line wouldn&#39;t compile since the method is `const`.<br>    // original_trilogy += 3;<br>  }<br><br>  void break_trilogy() const {<br>    HarrisonFord* unfrozen_hans = const_cast&lt;HarrisonFord*&gt;(this);<br>    unfrozen_hans-&gt;original_trilogy += 3;<br>  }<br>};<br><br>const HarrisonFord* carbonite_han_solo = new HarrisonFord();<br>carbonite_han_solo-&gt;break_trilogy();</pre><p>This is const_cast. The const keyword was added to C++ to enable more compiler optimizations and faster performance. const code paths can generally be more efficient than mutable code paths, and the compiler should be able to opt-in to using these whenever possible.</p><p>But, since this is mostly an element of optimization and not of type safety, const_cast allows you to strip out the safety checks and trigger potentially undefined behavior whenever you like.</p><h4>reinterpret_cast</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*9yQ0zU5Q2QnxBtMSwZ1P_w.png" /></figure><p>The epitome of casting is <a href="https://en.cppreference.com/w/cpp/language/reinterpret_cast">reinterpret_cast</a>, which is represented by Jabba the Hutt from 1983’s <em>Star Wars VI: Return of the Jedi</em>. Because Jabba the Hutt is absolutely not Han Solo in any way — but you can still cast him to one using reinterpret_cast:</p><pre>class HanSolo {};<br><br>class JabbaTheHutt {};<br><br>HanSolo* han1 = new HanSolo();<br>JabbaTheHutt* jabba1 = new JabbaTheHutt();<br><br>// All totally fine.<br>HanSolo* han2 = reinterpret_cast&lt;HanSolo*&gt;(jabba1);<br>JabbaTheHutt* jabba2 = reinterpret_cast&lt;JabbaTheHutt*&gt;(han1);</pre><p>This is reinterpret_cast. It tells the compiler to simply throw away one type and replace it with another, without any checks whatsoever. Maybe you need this because you know the behavior you’re seeking is correct, and this really is one of those “Break glass in case of emergency”–level emergencies, so you go ahead and reinterpret_cast one thing to another.</p><p>But, if the bytes don’t exactly align the way they should, this will lead to undefined behavior.</p><h4>std::move</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*R8uUE-ie8AcIT0k8YoajHw.png" /></figure><p>A novel addition to C++ as of C++11 (and revised in C++14) is <a href="https://en.cppreference.com/w/cpp/utility/move">std::move</a>, which is represented by Han Solo tied to a spit and being transported by Ewoks in 1983&#39;s <em>Star Wars VI: Return of the Jedi</em>. Here Han Solo is the same actor in the same epoch, he’s just being transported somewhere against his will:</p><pre>std::string han_solo = &quot;Han Solo&quot;;<br>std::cout &lt;&lt; &quot;It&#39;s &quot; &lt;&lt; han_solo &lt;&lt; std::endl;<br>// Prints: &quot;It&#39;s Han Solo&quot;<br><br>std::vector&lt;std::string&gt; ewoks;<br>ewoks.push_back(han_solo);<br>std::cout &lt;&lt; &quot;It&#39;s still &quot; &lt;&lt; han_solo &lt;&lt; std::endl;<br>// Prints: &quot;It&#39;s still Han Solo&quot;<br><br>ewoks.push_back(std::move(han_solo));<br>std::cout &lt;&lt; &quot;He&#39;s gone! &quot; &lt;&lt; han_solo &lt;&lt; std::endl;<br>// Prints: &quot;He&#39;s gone! &quot;</pre><p>This is std::move. When we have an object in one location that we want to replace the memory in a different location, std::move will facilitate the transfer without invoking any extraneous copies along the way.</p><p>While this is all about efficiency, it can produce unexpected behavior if programmers are not used to its sometimes non-obvious side effects.</p><h3>Summary</h3><p>When you first start studying casts in C++, it may seem that there are so many of them with slightly different names, with highly nuanced functions, and dubious safety.</p><p>But, once you get a little more experience, you realize that — all that is indeed true, it’s just that sometimes unsafe and undefined behavior is exactly what it takes to get your code compiling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=344043d90030" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/han-solos-guide-to-c-casting-344043d90030">Han Solo’s Guide to C++ Casting</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Programming Puzzle: Speedrunning Ticket to Ride]]></title>
            <link>https://levelup.gitconnected.com/programming-puzzle-speedrunning-ticket-to-ride-ae044e724357?source=rss-791d06d4bc9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae044e724357</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[speedrun]]></category>
            <category><![CDATA[shortest-path]]></category>
            <category><![CDATA[board-games]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[P.G. Baumstarck]]></dc:creator>
            <pubDate>Sun, 05 Feb 2023 06:24:48 GMT</pubDate>
            <atom:updated>2023-02-06T01:24:36.131Z</atom:updated>
            <content:encoded><![CDATA[<p>I love speedrunning, whether it’s <a href="https://www.youtube.com/@SummoningSalt">Summoning Salt videos</a> or <a href="https://www.youtube.com/watch?v=Qgk5zITiArM">Celeste 202-berry runs</a>. But the speedrunning question of “How fast is it possible to beat a game?” is not something you often see applied to board games. But in <a href="https://medium.com/@kldv/programming-puzzle-ticket-to-ride-first-journey-ba72d4594f1e">my last exercise</a> I looked at my son’s new favorite game, <em>Ticket to Ride First Journey</em>, of which it is possible to ask this essential question. Programming the answer to it is something that will take us on an odyssey of estimation, approximation, heuristics, and old-fashioned brute force search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PFRo84stEIVPo0wJGGtGjw.png" /><figcaption>The “<em>Ticket to Ride First Journey” board we’ll be speedrunning.</em></figcaption></figure><h4>The Problem</h4><p>In <em>Ticket to Ride First Journey</em>, each player is dealt six “ticket cards” with two cities each, and to win they have to be the first to connect the six pairs of cities with train routes. These routes are built by drawing cards and laying down track cars of sufficient number to connect the routes on the map shown above (e.g., a player has to use two blue or black track cars to connect Atlanta and Miami, but four black ones to connect Denver and Duluth). Assuming we can stack the draw deck to build exactly the routes we want in any order, is it possible to calculate the least number of track cars it would take to win the game if we got dealt the best possible hand of six route cards?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ORMfl3t9U3EL0hcP_OklA.png" /><figcaption>The 32 ticket cards in “Ticket to Ride First Journey.” Each player is effectively dealt six of these cards and has to connect all the routes shown.</figcaption></figure><h4>Evaluating All Possible Hands</h4><p>First we have to ask if calculating this is even feasible. There are 32 ticket cards in the game, but that does not mean there are 32⁶ combinations since the cards are dealt without replacement. Rather there are “<a href="https://en.wikipedia.org/wiki/Binomial_coefficient">32 choose 6</a>” possible hands, which is only 906,192. At under a million combinations it’s trivially easy to construct and iterate through all possible hands. Starting with the same initialization code for the graph as we used <a href="https://medium.com/@kldv/programming-puzzle-ticket-to-ride-first-journey-ba72d4594f1e">last time</a>, we now add:</p><pre># Initialize the list of ticket cards.<br>TICKETS = [<br>  (CALGARY, CHICAGO),<br>  (CALGARY, LOS_ANGELES),<br>  ...<br>  (WINNIPEG, NEW_YORK),<br>]</pre><pre>n = len(TICKETS)<br>for ix1 in range(n - 5):<br>  for ix2 in range(ix1 + 1, n - 4):<br>    for ix3 in range(ix2 + 1, n - 3):<br>      for ix4 in range(ix3 + 1, n - 2):<br>        for ix5 in range(ix4 + 1, n - 1):<br>          for ix6 in range(ix5 + 1, n):<br>            cities_in_hand = set(<br>              TICKETS[ix1] +<br>              TICKETS[ix2] +<br>              TICKETS[ix3] +<br>              TICKETS[ix4] +<br>              TICKETS[ix5] +<br>              TICKETS[ix6]<br>            )<br>            # TODO: Find solution for this hand of cards.</pre><p>There are fancier ways to construct an <em>n</em>-dimensional loop, but I chose this one for simplicity.</p><p>Now the inner loop of this algorithm (the TODO) will be to calculate the minimum spanning tree for all the cities in each hand. Since we’re going to be doing this a million times, we’re going to need it to be as efficient as possible.</p><h4>Pruning Bad Hands</h4><p>Even though we can construct all possible hands, it may be prohibitively expensive to solve every hand in order to answer our speedrunning question. So we should develop a heuristic to let us order the hands, then examine only the most promising ones first in the hopes that we can find the answer without having to finish an exhaustive search.</p><p>Consider that a hand of cards can contain duplicate cities: you can get three cards that all have a route touching, say, Denver, meaning that that hand might require fewer track cars to complete and therefore be more likely be the speedrun hand. So let’s compute the number of unique cities in each hand and use that as a heuristic to see how difficult each hand will be to solve:</p><pre>from collections import defaultdict</pre><pre>n = len(TICKETS)<br>cities_in_hand_by_len = defaultdict(lambda: 0)<br>for ix1 in range(n - 5):<br>  for ix2 in range(ix1 + 1, n - 4):<br>    for ix3 in range(ix2 + 1, n - 3):<br>      for ix4 in range(ix3 + 1, n - 2):<br>        for ix5 in range(ix4 + 1, n - 1):<br>          for ix6 in range(ix5 + 1, n):<br>            cities_in_hand = set(<br>              TICKETS[ix1] +<br>              TICKETS[ix2] +<br>              TICKETS[ix3] +<br>              TICKETS[ix4] +<br>              TICKETS[ix5] +<br>              TICKETS[ix6]<br>            )</pre><pre>            num_cities_in_hand = len(cities_in_hand)<br>            cities_in_hand_by_len[num_cities_in_hand] += 1</pre><pre>print(cities_in_hand_by_len)</pre><p>Plotting this we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YEtoFicWDrKRPGeVuaaO8g.png" /></figure><p>It’s surprising, but there are exactly two six-card hands in <em>Ticket to Ride First Journey </em>that have only five unique cities in them. I’ve excerpted one of these hands below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1febhdlIBCv3FYArf99g-A.png" /><figcaption>One of two six-card hands with only five destination cities.</figcaption></figure><p>Even if one of these two five-city hands isn’t the speedrunning hand, maybe it’s one of the six-city hands, which would mean only we have to search 643 total hands. Even if we expand our search to all of the hands that include up to 8 cities, this is still only around 100,000 hands. If we heuristically solve these hands first, then we’ve reduced our search space by a factor of 10, giving our end-to-end solution an equivalent speedup.</p><h4>Minimum Spanning Tree over a Subset</h4><p>Now that we know how to construct each hand (and the order in which to solve them), we actually have to find the cheapest way to connect all the cities in a hand. Prim’s algorithm was useful for calculating the minimum spanning tree of all nodes in the graph, but this is a subtly different problem. What we really need here is the minimum spanning tree over a <em>subset</em> of nodes in the graph. This more complicated problem goes by the name of the “<a href="https://en.wikipedia.org/wiki/Steiner_tree_problem">Steiner tree problem</a>” or “minimum Steiner tree problem:”</p><blockquote>Given an <a href="https://en.wikipedia.org/wiki/Undirected_graph">undirected graph</a> with non-negative edge weights and a subset of vertices, usually referred to as <strong>terminals,</strong> the Steiner tree problem in graphs requires a <a href="https://en.wikipedia.org/wiki/Tree_(graph_theory)">tree</a> of minimum weight that contains all terminals (but may include additional vertices)</blockquote><p>In graph-speak, this is what we’re looking for. The <em>Ticket to Ride First Journey</em> game board is “an undirected graph with non-negative weights,” and the cities represented by the cards in your hand are the “subset of vertices or ‘terminals’” that you want to connect. Since each ticket card has two non-adjacent cities, we’re almost guaranteed that the set of cities that connects all those in a hand will have to contain more cities than the ones we’re given.</p><p>Sadly, the Steiner tree problem is known to be NP-hard, meaning finding the optimal solution requires basically trying every possible solution there is. That’s infeasible for us in the inner loop of our hand-checking algorithm, so we’ll use a greedy approximation:</p><pre>&gt; Kruskal&#39;s algorithm has entered the chat.</pre><p>I researched solutions for the Steiner tree problem, and the easiest one to implement I found was <a href="https://en.wikipedia.org/wiki/Kruskal%27s_algorithm">Kruskal’s algorithm</a>. The best pseudocode came courtesy of this <a href="https://stackoverflow.com/questions/7685291/construct-a-minimum-spanning-tree-covering-a-specific-subset-of-the-vertices">Stackoverflow thread</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zebQw4W7RDXo4HUtpRCJCA.png" /></figure><p>This is relatively straightforward, but one problem is the inner loop of this algorithm has a section that goes:</p><blockquote>determine the shortest path between all nodes in <em>f_i</em> to all those in <em>f_j</em></blockquote><p>This requires us to solve the shortest path problem repeatedly in the inner loop of Kruskal’s algorithm—which, remember, is itself wrapped in another loop that runs a million times:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yEEva3jAtHLx6UMei9rSAA.png" /></figure><p>Luckily there are only 19 cities in the <em>Ticket to Ride</em> graph, so there are only 19 * 18 = 342 possible shortest paths that we would ever need to compute in the inner loop of Kruskal’s algorithm. So instead of recalculating those 342 shortest paths millions of times (which will never change over the course of our search), we will simply do the calculation once ahead of time and cache it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2pfOTpI4jO4i7BZq-hQUg.png" /><figcaption>Our naive (left) and optimized (right) approaches to solving the speedrun for “Ticket to Ride First Journey.”</figcaption></figure><h4>Shortest Paths Between All Nodes</h4><p>To calculate the shortest paths between all nodes, we can either use <a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm">Dijkstra’s algorithm</a> or the <a href="https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm">Bellman–Ford algorithm</a>. I’m partial to the latter, so here was my implementation:</p><pre>def bellman_ford_algorithm(graph, source):<br>  vertices = graph.keys()<br>  distances = {_: float(&#39;Inf&#39;) for _ in vertices}<br>  predecessors = {_: None for _ in vertices}<br>  distances[source] = 0</pre><pre>  for i in range(len(vertices)):<br>    for u, edges in graph.items():<br>      for v, w in edges.items():<br>        if distances[u] + w &lt; distances[v]:<br>          distances[v] = distances[u] + w<br>          predecessors[v] = u</pre><pre>  return distances, predecessors</pre><p>This only finds all the shortest paths to one node (the source) at a time, so I ran it in a loop for all nodes to get what we need. Then, for each path from source to sink, we calculate the optimal path of cities and the weight for the whole route:</p><pre>def get_all_shortest_paths(graph):<br>  vertices = graph.keys()<br>  shortest_paths = {<br>    _: {__: ([], 0) for __ in vertices}<br>    for _ in vertices<br>  }<br>  for source in vertices:<br>    _, predecessors = bellman_ford_algorithm(graph, source)<br>    for sink in vertices:<br>      node = sink<br>      path = [node]<br>      weight = 0<br>      while node != source:<br>        previous_node = predecessors[node]<br>        weight += graph[previous_node][node]<br>        path.append(previous_node)<br>        node = previous_node</pre><pre>      shortest_paths[source][sink] = (path, weight)</pre><pre>  return shortest_paths</pre><p>Here’s a sample of one solution, examining the shortest paths calculated for Montreal:</p><pre>&quot;Montreal&quot;: {<br>  &quot;Albuquerque&quot;: [<br>    [<br>      &quot;Albuquerque&quot;,<br>      &quot;Dallas&quot;,<br>      &quot;Kansas City&quot;,<br>      &quot;Chicago&quot;,<br>      &quot;Montreal&quot;<br>    ],<br>    7<br>  ],<br>  &quot;Chicago&quot;: [<br>    [<br>      &quot;Chicago&quot;,<br>      &quot;Montreal&quot;<br>    ],<br>    3<br>  ],<br>  &quot;Montreal&quot;: [<br>    [<br>      &quot;Montreal&quot;<br>    ],<br>    0<br>  ],<br>  ...<br>]</pre><p>You can verify from the game board that the various paths listed here are indeed the shortest. It’s also a good sanity check that the shortest path from Montreal to Montreal itself is just [MONTREAL] with weight 0 (as it should be).</p><h4>Deploying Kruskal</h4><p>Now that we have all the pieces in place, here is our final implementation of Kruskal’s algorithm:</p><pre>def kruskals_algorithm(graph, shortest_paths, terminals):<br>  F = [set([_]) for _ in terminals]<br>  while len(F) &gt; 1:<br>    # Shortest path represented as: `(weight, path, i, j)`<br>    shortest_path = (float(&#39;Inf&#39;), None, None, None)<br>    for i in range(len(F) - 1):<br>      for j in range(i + 1, len(F)):<br>        for node_i in F[i]:<br>          for node_j in F[j]:<br>            path, weight = shortest_paths[node_i][node_j]<br>            if weight &lt; shortest_path[0]:<br>              shortest_path = (weight, path, i, j)</pre><pre>    # Cut `i` and `j` out of `F`, and add the new merged `path`.<br>    _, path, i, j = shortest_path<br>    F = F[:i] + F[i + 1:j] + F[j + 1:] + [set(path)]</pre><pre>  return list(F[0])</pre><pre>shortest_paths = get_all_shortest_paths(graph)<br>kruskal = kruskals_algorithm(graph, shortest_paths, <strong>cities_in_hand</strong>)</pre><p>I ran this, and I was afraid the inner loop of Kruskal’s algorithm would be too expensive. But in reality it took only a few minutes to process all one million hands.</p><p>For those two five-city hands, I found one took 9 and the other took 10 track cars to complete—but these actually didn’t turn out to be the speedrunning hands. In reality there were a total of 20 six- and seven-city hands that could be completed using only 8 track cars each. Here is one of the six-city hands that is one of these speedrunning solutions to <em>Ticket to Ride First Journey</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IvJXMUTfFy0GwLbtpNd-ag.png" /><figcaption>One of the speedrun hands in “Ticket to Ride First Journey.”</figcaption></figure><p>The optimal solution for this hand looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rklhhh9vPykgXH4wxuew3A.png" /><figcaption>The 8-track solution to the above speedrun hand.</figcaption></figure><p>The odds are 20 out of 906,192 that you will get dealt one of these eight–track car hands — and then you still need to draw the exact eight cards you need to let you claim those routes immediately — but we have found the speedrunning solutions to <em>Ticket to Ride First Journey</em>.</p><h4>Kruskal’s Approximate Solutions</h4><p>One final thing I looked at was the distribution of solutions. Below I plot the number of hands that can be solved by each number of tracks, starting from the minimum of 8:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vuC49K8m0c5y1qQkb7z9Q.png" /></figure><p>One interesting “error” that shows up is the fact that the hardest hands to solve actually took 27 track cars to complete. Recall that <a href="https://kldv.medium.com/programming-puzzle-ticket-to-ride-first-journey-ba72d4594f1e">the minimum spanning tree</a> to connect all cities in <em>Ticket to Ride</em> takes only 25 cars, so there should be no solution that needs more than 25 cars. This shows us that Kruskal’s algorithm was indeed only giving us an approximation that was suboptimal in some places. For your inspection, here was one of the worst possible hands you can get in the game:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lgqon63JWeCkr3uR30EFpg.png" /><figcaption>One of the worst possible hands.</figcaption></figure><h4>Conclusion</h4><p>So it is possible to calculate the speedrun in <em>Ticket to Ride First Journey</em>, and even possible to calculate solutions to all possible hands. Though the approximate algorithm we used didn’t provide optimal solutions in all cases, it did allow us to find the 20 speedrunning hands that can be solved using only 8 track cars. Find the code <a href="https://replit.com/@KLde/TicketToRideFirstJourneySpeedrun#main.py">here</a>.</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae044e724357" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/programming-puzzle-speedrunning-ticket-to-ride-ae044e724357">Programming Puzzle: Speedrunning Ticket to Ride</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Programming Puzzle: Ticket to Ride First Journey]]></title>
            <link>https://thepgb.medium.com/programming-puzzle-ticket-to-ride-first-journey-ba72d4594f1e?source=rss-791d06d4bc9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba72d4594f1e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[board-games]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[P.G. Baumstarck]]></dc:creator>
            <pubDate>Mon, 17 Oct 2022 03:39:42 GMT</pubDate>
            <atom:updated>2023-02-05T06:21:04.967Z</atom:updated>
            <content:encoded><![CDATA[<p>My son’s new favorite game is called <a href="https://www.amazon.com/Ticket-to-Ride-First-Journey/dp/B01MQ4IKQJ"><em>Ticket to Ride First Journey</em></a>, which is a junior version of the full game <a href="https://www.amazon.com/Days-Wonder-DO7201-Ticket-Ride/dp/0975277324/ref=pd_day0fbt_img_sccl_1/134-4770978-6304824?pd_rd_w=vgIEz&amp;content-id=amzn1.sym.9b14949a-3979-4b7d-b182-b07adcc4c0e7&amp;pf_rd_p=9b14949a-3979-4b7d-b182-b07adcc4c0e7&amp;pf_rd_r=0TZ95QYKQDPN22BGKMT4&amp;pd_rd_wg=9vEq9&amp;pd_rd_r=3f630b61-0261-4bb4-ae53-885b65835dc9&amp;pd_rd_i=0975277324&amp;psc=1"><em>Ticket to Ride</em></a>. The goal is to connect cities with train tracks to complete a certain number of routes the fastest. My son had the obvious question of how to finish the game the fastest. Before we could tackle that problem, however, we first looked at how to connect all the cities using the least number of tracks. This turned out to be a perfect opportunity to study the minimum spanning tree problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PFRo84stEIVPo0wJGGtGjw.png" /><figcaption><em>The “Ticket to Ride First Journey” board: a case study in the minimum spanning tree.</em></figcaption></figure><p>The <a href="https://en.wikipedia.org/wiki/Minimum_spanning_tree">minimum spanning tree</a> problem is related to graphs, which are sets of nodes (or vertices) that are connected by edges, each of which has a weight. The MST problem is to find a set of edges that connect all the nodes in the graph while having the lowest sum of weights over those edges. The <em>Ticket to Ride </em>board is a graph where the vertices are cities, the edges are the routes between them, and the weights are the number of track slots between each city. So a minimum spanning tree on this board is a route that connects every city while using the least number of tracks to do so.</p><p>Any route that visits every node on a graph once is a spanning tree; the minimum spanning tree is the one that uses the least weights or length to do so. This obviously has huge practical applications—just the fact that our motivating example is of international rail network should show how broad. But it’s easy to come up with a bad spanning tree. Take this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQskx3m8XDcTP4lm-msRrw.png" /><figcaption>An inefficient spanning tree that uses 50 track slots to connect all cities.</figcaption></figure><p>By connecting many nodes in inefficient ways, this path uses 50 track slots to connect all the cities. Obviously we need an algorithmic solution, but the MST problem doesn’t yield to the simple depth- and breadth-first search algorithms that we <a href="https://medium.com/swlh/programming-puzzle-rush-hour-traffic-jam-3ee513e6c4ab">examined before</a>. Instead we’re going to have to use a special graph traversal algorithm.</p><h4>Prim’s Algorithm</h4><p>There are several fancy solutions to the MST problem, but the one I’m most familiar with is <a href="https://en.wikipedia.org/wiki/Prim%27s_algorithm">Prim’s algorithm</a>. It’s a basic greedy algorithm that starts from one node in the graph (here one city) and searches progressively outwards one node at a time, examining all the edges that connect to that new node and using them to adjust the route of the minimum spanning tree. Wikipedia provides handy pseudocode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0VFaeEYdDNvxJ_JgUpr1Q.png" /><figcaption>Pseudocode of Prim’s Algorithm on Wikipedia.</figcaption></figure><p>This may look complicated, but we’re going to implement it by directly translating it line-for-line into Python.</p><h4>Building the Graph</h4><p>Before we can use Prim’s algorithm, however, the first—and most tedious—step of the problem is initializing the data structures we’re going to use. For a graph problem you’re generally going to need three things:</p><ol><li>The list of vertices</li><li>The list of edges</li><li>The graph represented in memory</li></ol><p>Working in Python, I’m going to use string labels for each vertex, which I’ll initialize with constants:</p><pre>ALBUQUERQUE = &#39;Albuquerque&#39;<br>ATLANTA = &#39;Atlanta&#39;<br>CALGARY = &#39;Calgary&#39;<br>...<br>WINNIPEG = &#39;Winnipeg&#39;</pre><pre>VERTICES = [<br>  ALBUQUERQUE,<br>  ATLANTA,<br>  CALGARY,<br>  ...<br>  WINNIPEG,<br>]</pre><p>Warning: <strong>DO NOT</strong> initialize the vertices like this:</p><pre>VERTICES = [<br>  &#39;Albuquerque&#39;,<br>  &#39;Atlanta&#39;,<br>  &#39;Calgary&#39;,<br>  ...<br>  &#39;Winnipeg&#39;,<br>]</pre><p>Using string literals means you’re going to have to retype the strings every time you want to use them, and it’s very easy to misspell the word “Albuquerque”—which will introduce a silent bug into your program. If you instead misspell the constant name, ALBUQUERQUE, however, the interpreter will throw an error and prompt you to fix it.</p><p>Next we list the edges as tuples of (CITY_A, CITY_B, WEIGHT):</p><pre>EDGES = [<br>  (SEATTLE, CALGARY, 3),<br>  (SEATTLE, HELENA, 2),<br>  (SEATTLE, SALT_LAKE_CITY, 3),<br>  ...<br>  (SAN_FRANCISCO, LOS_ANGELES, 1),<br>]</pre><p>The edges are bidirectional, so the order of the city names doesn’t matter; we just need to remember that city B also connects back to city A.</p><p>Finally we build a representation of the graph in memory. In Python, we can make a dictionary with the city names as the keys, and the values will show that city’s connections to all other cities. These values will themselves be more dictionaries with the connected city names as the keys and the weight of the connections as the values:</p><pre>graph = {v: {} for v in VERTICES}<br>for vertex1, vertex2, cost in EDGES:<br>  graph[vertex1][vertex2] = cost<br>  graph[vertex2][vertex1] = cost</pre><p>A quick sanity check on this code is to verify that you have used both the VERTICES and the EDGES data structures to build the graph. Also, since we have bidirectional edges, we have to connect vertex1 to vertex2 and vice versa. Once constructed, the &quot;Seattle&quot; component of the graph map will look like this (this can be crosschecked with the image of the board above):</p><pre>&quot;Seattle&quot;: {<br>    &quot;Calgary&quot;: 3,<br>    &quot;Helena&quot;: 2,<br>    &quot;Salt Lake City&quot;: 3,<br>    &quot;San Francisco&quot;: 3<br>},</pre><h4>Implementing the Algorithm</h4><p>With all of our initialization done, we can start implementing Prim’s algorithm from the first step:</p><blockquote>1. Associate with each vertex <em>v</em> of the graph a number <em>C</em>[<em>v</em>] (the cheapest cost of a connection to <em>v</em>) and an edge <em>E</em>[<em>v</em>] (the edge providing that cheapest connection). To initialize these values, set all values of <em>C</em>[<em>v</em>] to +∞ (or to any number larger than the maximum edge weight) and set each <em>E</em>[<em>v</em>] to a special <a href="https://en.wikipedia.org/wiki/Flag_value">flag value</a> indicating that there is no edge connecting <em>v</em> to earlier vertices.</blockquote><p>The variable <em>v</em> refers to a vertex, for which we can use our string labels in VERTICES. To represent the weights in <em>C</em> and <em>E</em> we can use dictionaries where the keys are vertex labels. The pseudocode also tells us to initialize C to all positive infinites, and E to a flag value, for which we’ll use None:</p><pre>C = {v: float(&#39;Inf&#39;) for vin VERTICES}<br>E = {v: None for vin VERTICES}</pre><p>Surprising but that’s it. The longest step in the pseudocode was only two short lines of initialization.</p><p>Now the second step:</p><blockquote>2. Initialize an empty forest <em>F</em> and a set <em>Q</em> of vertices that have not yet been included in <em>F</em> (initially, all vertices).</blockquote><p>The “empty forest” just means another set of unconnected nodes, so a set. We can model both of these as sets in Python. Q starts off empty, but F starts off initialized with all vertices:</p><pre>F = set()<br>Q = set(VERTICES)</pre><p>Again, dense text that turns into very simple code.</p><p>Moving on to the third step:</p><blockquote>Repeat the following steps until Q is empty:<br>— a. Find and remove a vertex v from Q having the minimum possible value of C[v]<br>— b. Add v to F<br>— c. Loop over the edges vw connecting v to other vertices w. For each such edge, if w still belongs to Q and vw has smaller weight than C[w], perform the following steps:<br>—— i.Set C[w] to the cost of edge vw<br>—— ii. Set E[w] to point to edge vw.</blockquote><p>We want to find the vertex with minimum cost value in C, which we’ll accomplish with a sort. Then we remove that vertex from Q and add it to F (marking the vertex as visited). Finally we check the edges connecting to this newly visited vertex and use any lower edge weights it has to alter the minimum spanning tree:</p><pre>while Q:<br>  v = list(sorted([(C[v], v) for v in Q]))[0][1]<br>  Q.remove(v)</pre><pre>  F.add(v)</pre><pre>  for w, vw in graph[v].items():<br>    if w in Q and vw &lt; C[w]:<br>      C[w] = vw<br>      E[w] = v</pre><p>I’ve used a little idiomatic Python here, but for the most part it matches one-to-one with the pseudocode. Here’s even a color-coded version showing the exact correspondences between the pseudocode and the real code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4HwsWG_MwnDCXQnbvjQFg.png" /></figure><p>If we wanted to make the code more readable, we could just substitute the algorithm’s single-letter variable names with more-informative ones:</p><pre>while Q:<br>  vertex_cheapest = list(sorted([(C[v], v) for v in Q]))[0][1]<br>  Q.remove(vertex_cheapest)</pre><pre>  F.add(vertex_cheapest)</pre><pre>  for vertex_w, weight_vw in graph[vertex_cheapest].items():<br>    if vertex_w in Q and weight_vw &lt; C[vertex_w]:<br>      C[vertex_w] = weight_vw<br>      E[vertex_w] = vertex_cheapest</pre><h4>Running It</h4><p>For a small graph of only 19 vertices like this, Prim’s algorithm runs instantaneously. The results:</p><pre>&gt;&gt;&gt; print(json.dumps(E, indent=2))<br>{<br>  &quot;Albuquerque&quot;: null,<br>  &quot;Atlanta&quot;: &quot;Chicago&quot;,<br>  &quot;Calgary&quot;: &quot;Helena&quot;,<br>  &quot;Chicago&quot;: &quot;Kansas City&quot;,<br>  &quot;Dallas&quot;: &quot;Albuquerque&quot;,<br>  &quot;Denver&quot;: &quot;Albuquerque&quot;,<br>  &quot;Duluth&quot;: &quot;Chicago&quot;,<br>  &quot;Helena&quot;: &quot;Denver&quot;,<br>  &quot;Kansas City&quot;: &quot;Dallas&quot;,<br>  &quot;Los Angeles&quot;: &quot;Salt Lake City&quot;,<br>  &quot;Miami&quot;: &quot;Atlanta&quot;,<br>  &quot;Montreal&quot;: &quot;New York&quot;,<br>  &quot;New Orleans&quot;: &quot;Atlanta&quot;,<br>  &quot;New York&quot;: &quot;Washington&quot;,<br>  &quot;Salt Lake City&quot;: &quot;Helena&quot;,<br>  &quot;San Francisco&quot;: &quot;Los Angeles&quot;,<br>  &quot;Seattle&quot;: &quot;Helena&quot;,<br>  &quot;Washington&quot;: &quot;Atlanta&quot;,<br>  &quot;Winnipeg&quot;: &quot;Duluth&quot;<br>}</pre><p>For a graph with 19 vertices, there should only be 18 edges needed to connect them into a minimum spanning tree. That’s why we have 18 string-to-string correspondences and one null (which was a None in Python before the JSON conversion). Plotting it, our MST is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GlSGs9yJ8uh-od0liaM9HQ.png" /><figcaption>The official “Ticket to Ride First Journey” minimum spanning tree.</figcaption></figure><p>If we count manually this uses only 25 tracks—far better than the 50 we started out with. But we can also have the computer count the relevant edge weights just to be sure:</p><pre>&gt;&gt;&gt; print(sum(graph[v1][v2] for v1, v2 in E.items() if v2))<br>25</pre><h4>Summary</h4><p>Graph problems may seem intimidating, but they have simple underpinnings and many practical applications. The takeaways from this exercise are:</p><ol><li>Every graph problem starts with a set of vertices and a list of edges.</li><li>Building the graph in memory makes solutions easier to code.</li><li>Graph algorithms usually process nodes one-by-one, keeping track of them in sets (especially visited and unvisited sets).</li><li>As long as you have good VERTICES, EDGES , and graph data structures, many pseudocode algorithms have straightforward implementations.</li></ol><p>Completed code available <a href="https://replit.com/@KLde/TicketToRideFirstJourney#main.py">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba72d4594f1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The SpaceX Falcon 9 Revolution]]></title>
            <link>https://medium.com/predict/visualizing-the-spacex-falcon-9-launch-history-6c68124b22c3?source=rss-791d06d4bc9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c68124b22c3</guid>
            <category><![CDATA[elon-musk]]></category>
            <category><![CDATA[space]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[spacex]]></category>
            <category><![CDATA[visualization]]></category>
            <dc:creator><![CDATA[P.G. Baumstarck]]></dc:creator>
            <pubDate>Thu, 10 Feb 2022 08:13:27 GMT</pubDate>
            <atom:updated>2022-02-10T23:55:15.417Z</atom:updated>
            <content:encoded><![CDATA[<p>SpaceX’s <a href="https://en.wikipedia.org/wiki/Falcon_9">Falcon 9</a> rocket has <a href="https://arstechnica.com/science/2021/04/spacex-landed-a-rocket-on-a-boat-five-years-ago-it-changed-everything/">revolutionized space access</a>. While most other rockets are still being launched once and dropped into the ocean à la the 1950s, the Falcon 9 has landed over <a href="https://www.space.com/spacex-dragon-crs-2-launch-100th-rocket-landing-success">100 times</a> and a single booster has performed <a href="https://www.space.com/spacex-starlink-launch-record-falcon-9-11th-flight">11 flights</a>. But, while it is the most technically advanced rocket in the world, SpaceX Chief Engineer Elon Musk has already <a href="https://techcrunch.com/2017/09/28/spacex-aims-to-replace-falcon-9-falcon-heavy-and-dragon-with-one-spaceship/?guccounter=1&amp;guce_referrer=aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS8&amp;guce_referrer_sig=AQAAAAWTZKG5aovntgHPF9BzbkvLkfGUImT1RfG6EMmkjPBvUrNeqnb89Rk9-MrqEVZ0cQttRA9J8_bh05saz3ym2l14HFsEOePd43BChwpKHggNW2tXyUfV_W5F9tdvnM8YJtMYwBNGyO-l5j_oaOuc5EH81GZnAB7gDiC-fJlM3fwf">declared it deprecated</a> and is working on an even more <a href="https://en.wikipedia.org/wiki/SpaceX_Starship">revolutionary replacement</a>. Since we may be on the eve of the Falcon 9 being eclipsed, I wanted to revisit its history through visualization, to take stock of how far the Falcon 9 has come so as to judge how far Starship could go.</p><p>I ended up creating animations of their launch histories so that by watching them it would help me relive the sequences of events. The first visualization showcases the <a href="https://vimeo.com/675325921">launch history of the Falcon 9 itself</a>, and it also tracks the cumulative launches of SpaceX’s active booster fleet, plus their cumulative payload launched to orbit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xX90Huk3ed7TupAk-yyQeg.png" /><figcaption>Legend for the <a href="https://vimeo.com/675325921">SpaceX solo visualization</a>.</figcaption></figure><p>For the second visualization (<a href="https://vimeo.com/675746553">here</a> and <a href="https://vimeo.com/675747109">here</a>) I wanted to get a sense of SpaceX’s progress relative to its competitors, so I juxtaposed their launch history with that of <a href="https://vimeo.com/675746553">ULA</a> and <a href="https://vimeo.com/675747109">Arianespace</a> (the US’s and Europe’s incumbent launch service providers, respectively):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sifovqlwWdhf9yA8F_Z-nw.png" /><figcaption>Legend for the comparative visualizations vs. <a href="https://vimeo.com/675746553">ULA</a> and vs. <a href="https://vimeo.com/675747109">Arianespace</a>.</figcaption></figure><p>These visualizations aren’t supposed to be direct comparisons between the companies since ULA and Arianespace were launching rockets before the Falcon 9’s first flight in 2010. But they are useful for comparing their relative launch cadences over the years they were all active.</p><h3>Highlights</h3><p>Creating these visualizations showed me things I’d never seen before in the Falcon 9’s history, and it also dramatically rendered things that I’d previously only vaguely imagined. Below I’ve excerpted some of the highlights I found in the data.</p><h4>Highlight 1: Effect of the Groundings</h4><p>This first highlight — actually a lowlight — comes at the end of 2016 when SpaceX was at its nadir versus its competitors. In the four years it took the Falcon 9 to achieve its first formative launches, its competitors had racked up dozens. SpaceX was betting heavily on being able to recover their boosters to make them reusable and more economical, but that had only achieved <a href="https://www.youtube.com/watch?v=bvim4rsNHkQ">inconsistent results</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gU_1_FBKYT5wibljIyV8Uw.png" /><figcaption>After pulling even with its competitors in early 2015, SpaceX suffered two lost missions that led to extended groundings.</figcaption></figure><p>Then SpaceX suffered the loss of the <a href="https://en.wikipedia.org/wiki/SpaceX_CRS-7">CRS-7 commercial resupply mission</a> for the International Space Station. This put them on a six-month launch hiatus while their competitors continued widening their lead. SpaceX returned to flight in 2016, and for a while they were even equaling the launch cadences of their competitors. — Until they lost payload <a href="https://en.wikipedia.org/wiki/AMOS-6_(satellite)">Amos-6</a>, not during flight but from exploding on the launch pad. Another hiatus followed, during which Arianespace <a href="https://www.satellitetoday.com/business/2016/09/14/spacex-amos-6-loss-arianespace-sees-demand-surge/">crowed</a> that SpaceX customers were now flocking to them for contracts, but that they only had so many openings — and they didn’t see the need to create more.</p><p>This may have been the low point for the Falcon 9. At least SpaceX was beginning to land boosters successfully, but these early rockets were found to be incapable of flying again. With reusability still unrealized, the ability to land a booster was just a gimmick that hadn’t returned any value. The aerospace incumbents felt assured that SpaceX’s ambitions were no threat to their market share.</p><h4>Highlight 2: The Block 4 Wave</h4><p>Things changed in 2016 and 2017 with the introduction of the improved <a href="https://en.wikipedia.org/wiki/Falcon_9_Full_Thrust">Full Thrust</a> and <a href="https://en.wikipedia.org/wiki/Falcon_9#Block_4">Block 4</a> versions of the Falcon 9. Using the lessons learned from the first recovered boosters, these new rockets were sturdy enough to stick the landing and be refurbished for another flight. This led to SpaceX <a href="https://spaceflightnow.com/2016/06/03/spacexs-latest-booster-back-home-as-company-mulls-pricing-proof-tests/">building up</a> a <a href="https://arstechnica.com/science/2021/04/spacex-landed-a-rocket-on-a-boat-five-years-ago-it-changed-everything/">massive inventory</a> of landed boosters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*INREmVwb3n_2P131smVDbg.png" /><figcaption>(a) Successful landings start building up a large inventory of boosters. (b) The wave reaches its peak at ten successful recoveries. (c) The wave winds down as all Full Thrust and Block 4 boosters are expended after their second flight.</figcaption></figure><p>The wave peaked at 10 after the launch of <a href="https://en.wikipedia.org/wiki/Iridium_satellite_constellation">Iridium NEXT-3</a>. But the Full Thrust and Block 4 versions were only durable enough to launch and land twice, so every rocket was retired or <a href="https://arstechnica.com/science/2018/04/spacex-is-gasp-going-to-expend-its-fifth-falcon-9-in-a-row/">expended after its second mission</a>. This created a drawdown where SpaceX suddenly seemed to be <a href="https://www.wired.com/story/spacex-is-about-to-launch-its-final-block-4-falcon/">back to square one</a> with only one recovered booster in its inventory.</p><p>But this time was different. This one booster was a <a href="https://en.wikipedia.org/wiki/Falcon_9_Block_5">Block 5</a>.</p><h4>Highlight 3: Block 5 Reuse Milestones</h4><p>Elon Musk had announced the Block 5 as the final iteration of the Falcon 9, designed to achieve <a href="https://www.cnbc.com/2018/05/11/full-elon-musk-transcript-about-spacex-falcon-9-block-5.html">reuse milestones of ten</a>, fifty, and a hundred flights per booster. The only thing left was to prove it, and you can judge the progress:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MS3aG5lgVLzVC9w0Ui8gNg.png" /><figcaption>The Block 5 boosters that set reuse milestones from 3 up to 11 flights.</figcaption></figure><p>In 2018 a booster made the first third flight.</p><p>In 2019 a booster made the first fourth flight.</p><p>In 2020 a booster made the first fifth, sixth, and seventh flights.</p><p>And in 2021 a single booster made it all the way up to eleven flights — which broke my visualization and forced me to implement a line wrapping feature, as seen above.</p><p>SpaceX currently has a fleet of over a <a href="https://en.wikipedia.org/wiki/List_of_Falcon_9_first-stage_boosters">dozen active boosters</a>, four of which have accomplished double digit flights.</p><h4>Highlight 4: The Megaconstellation Effect</h4><p>In the above image there are many launch squares colored dark green, which I’ve used to indicate Starlink launches. <a href="https://en.wikipedia.org/wiki/Starlink">Starlink</a> is a planned “megaconstellation” of tens of thousands of satellites meant to provide worldwide broadband internet. It’s actually only one of several such constellations planned by US, European, and Chinese companies, in what perhaps constitutes the first <a href="https://www.washingtonpost.com/technology/2021/11/02/satellite-internet-starlink-kuiper-faq/">bonafide space race</a> since Yuri Gagarin. I’ve colored all megaconstellation launches this way, which one can see in Arianespace’s own launches for the <a href="https://en.wikipedia.org/wiki/OneWeb">OneWeb</a> constellation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQzLKpVIDh4Lhlkigije4g.png" /><figcaption>Megaconstellation launches colored dark green: Starlink for SpaceX (left) and OneWeb for Arianespace (right).</figcaption></figure><p>It’s also interesting to note that Starlink launches dominate the high-cardinality reflights of Falcon 9s. This is because SpaceX is its own customer in these cases, so they’re willing to risk using more heavily flown rockets because they understand them better. This shift was also necessary because, by 2019, SpaceX had begun launching so quickly that they’d <a href="https://www.teslarati.com/spacex-falcon-9-waiting-on-customer-satellite-readiness/">exhausted their external customer supply</a>. In the aerospace industry, typically it’s the satellites that are sitting around for years waiting for a rocket to launch them, but for the first time SpaceX had a huge inventory of rockets sitting around waiting for satellites to be launched.</p><h4>Highlight 5: The Ruler of LEO</h4><p>Once all the latest launches have been factored in, some interesting details emerge:</p><ul><li>SpaceX has now launched more flights than either ULA or Arianespace since 2010, and it has cumulatively launched over 1,000 tons to space, or just over one hundredth the mass of a <a href="https://en.wikipedia.org/wiki/Gerald_R._Ford-class_aircraft_carrier">Ford-class aircraft carrier</a>.</li><li>Because of reuse, SpaceX has accomplished 143 launches with only 67 first-stage boosters. ULA and Arianespace are technically outproducing SpaceX in boosters; they’re just doing less with them.</li><li>SpaceX has launched by far the most missions and tonnage to low-Earth orbit (LEO), in large part due to Starlink launches. ULA and Arianespace have still conducted more launches to higher orbits.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Az6VCPUP2q_N8w6NhRBUMg.png" /><figcaption>SpaceX vs. ULA — the current snapshot.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iPbz77CzjSGSTMO6woe3gg.png" /><figcaption>SpaceX vs. Arianespace — the current snapshot.</figcaption></figure><h3>Reflections</h3><p>Visualizing the Falcon 9’s history impressed upon me how much it’s a thrilling tale of innovation and revolution, full of heartbreak and comeback. But I was also impressed to find that, against this dizzying backdrop, its competitors’ histories were these obliviously monotonous scrawls of “business as usual.” ULA’s and Arianespace’s launches in 2010 were disposable rockets with no attempts at recovery, and their launches in 2022 are just the same.</p><p>And this gulf will probably widen in 2022. Yes, ULA plans to debut its new <a href="https://en.wikipedia.org/wiki/Vulcan_Centaur">Vulcan Centaur</a> rocket, as does Arianespace with its new <a href="https://en.wikipedia.org/wiki/Ariane_6">Ariane 6</a>, but neither of these rockets will be reusable. It’s tough to see how they’ll be relevant in a world being reshaped by the Falcon 9. If nothing else changed, it could take another ten years to fully realize the impact the Block 5 will have — but there won’t be ten more years. Starship is coming now. The clock started ticking back when the first Falcon 9 landed; and once Starship makes it to orbit, time’s up.</p><h3>References</h3><p>The data for these visualizations was parsed from the following Wikipedia pages:</p><ul><li><a href="https://en.wikipedia.org/wiki/List_of_Falcon_9_and_Falcon_Heavy_launches#2022_2">List of Falcon 9 and Falcon Heavy launches</a></li><li><a href="https://en.wikipedia.org/wiki/List_of_Atlas_launches_(2020%E2%80%932029)">https://en.wikipedia.org/wiki/List_of_Atlas_launches_(2020%E2%80%932029)</a></li><li><a href="https://en.wikipedia.org/wiki/List_of_Thor_and_Delta_launches_(2020%E2%80%932029)">https://en.wikipedia.org/wiki/List_of_Thor_and_Delta_launches_(2020%E2%80%932029)</a></li><li><a href="https://en.wikipedia.org/wiki/List_of_Ariane_launches_(2020%E2%80%932029)">https://en.wikipedia.org/wiki/List_of_Ariane_launches_(2020%E2%80%932029)</a></li><li><a href="https://en.wikipedia.org/wiki/List_of_Vega_launches">https://en.wikipedia.org/wiki/List_of_Vega_launches</a></li><li><a href="https://en.wikipedia.org/wiki/Soyuz_at_the_Guiana_Space_Centre">https://en.wikipedia.org/wiki/Soyuz_at_the_Guiana_Space_Centre</a></li><li><a href="https://en.wikipedia.org/wiki/Soyuz-2">https://en.wikipedia.org/wiki/Soyuz-2</a></li></ul><p>I parsed these using <a href="https://beautiful-soup-4.readthedocs.io/en/latest/">BeautifulSoup</a>, then built the visualizations as bespoke web pages using <a href="https://jquery.com/">jQuery</a>, <a href="https://underscorejs.org/">Underscore.js</a>, <a href="https://animejs.com/">Anime.js</a>, and old-school terrible CSS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c68124b22c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/predict/visualizing-the-spacex-falcon-9-launch-history-6c68124b22c3">The SpaceX Falcon 9 Revolution</a> was originally published in <a href="https://medium.com/predict">Predict</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 6 Most Obscure Facts about “Mystery Science Theater 3000”]]></title>
            <link>https://thepgb.medium.com/the-6-most-obscure-facts-about-mystery-science-theater-3000-ab295b8e2e64?source=rss-791d06d4bc9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab295b8e2e64</guid>
            <category><![CDATA[comedy]]></category>
            <category><![CDATA[television]]></category>
            <category><![CDATA[science-fiction]]></category>
            <category><![CDATA[movies]]></category>
            <category><![CDATA[mst3k]]></category>
            <dc:creator><![CDATA[P.G. Baumstarck]]></dc:creator>
            <pubDate>Tue, 13 Apr 2021 15:02:15 GMT</pubDate>
            <atom:updated>2021-04-13T15:02:15.291Z</atom:updated>
            <content:encoded><![CDATA[<p>In honor of Joel Hodgson launching a second Kickstarter to <a href="http://www.makemoremst3k.com/">make more <em>Mystery Science Theater 3000</em></a>, I’d like to dedicate this Medium article to my favorite show. I’m a life-long fan who’s seen it all, and these are the 6 most obscure facts I’ve ever learned about <em>MST3K</em>. This is advanced material beyond what you’ll find in a <a href="https://www.google.com/search?q=most+obscure+mst3k+facts">Google search</a>, and even includes a little original research, so please enjoy.</p><h3>1. They actually gave a film its world premiere</h3><p>Most films on <em>MST3K </em>were flops from decades ago, either unsuccessful movies or repackaged TV episodes. But there is one exception in the case of <a href="https://www.imdb.com/title/tt0106682/?ref_=fn_al_tt_1"><em>The Dead Talk Back</em></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*yYd8_fQaDLEZBDvWMzdDVQ.png" /><figcaption>The movie in episode 603 had been unreleased for 36 years before appearing on “<em>MST3K</em>.”</figcaption></figure><p>This film was made in 1957, but the studio considered it too bad to release, so they shelved it. It remained so for 36 years until another studio found this unpublished work and released it on home video, whereupon it found its way to the <em>MST3K</em> producers. They <a href="https://catalog.afi.com/Catalog/moviedetails/54287">copyrighted it</a> and used it for the show, giving the movie its cable premiere (which is why the film is listed as a 1994 film and not a 1957 one on IMDB). For many of the movie’s actors, this was their only film credit, and, unless it had been shown on <em>MST3K</em>, no one would have ever seen it.</p><p>I cite this as evidence to counter critics who are offended by <em>MST3K</em> and think that it’s all about making fun of movies. While that is a part of the medium, the show is more about celebrating these movies and giving them a second life. This approach <a href="https://www.amazon.com/Brought-Back-MST3K-Jonah-Ray/dp/B07BDNZ3P5">is explained by Season 11’s head writer</a>, Elliott Kalan, who highlighted that the goal isn’t to be as mean as possible to each film, but to find a way to make it into a more enjoyable experience:</p><blockquote>“We want to take a movie that is not good — to put it mildly — and it’s almost though this alchemy — like the riffing is the philosopher’s stone — that turns it into gold. And you have to find the right riffs and the right tone and the right style to almost lead the movie through a transformation process until it becomes enjoyable to watch.” – Elliot Kalan, Head Writer, Season 11</blockquote><p>And ultimately the work <em>MST3K </em>put into these films made them better known. At the end of the show’s initial run in 1999, IMDB’s <a href="https://www.imdb.com/chart/bottom">bottom 100</a> list had a few dozen <em>MST3K</em> films on it (cf. <a href="https://web.archive.org/web/20040608094303/https://www.imdb.com/chart/bottom">this snapshot from 2004</a>). This wasn’t because <em>MST3K</em> had picked films off this list; in fact, most of the films were unknown before being on the show, so they didn’t even have the minimum number of ratings to make it. But appearing on the show boosted their popularity and got them the clout to appear. Granted, as lists go, you’d rather be on the <a href="https://www.imdb.com/chart/top/">top 250</a> than the bottom 100, but it’s still better than being on no list at all<em>.</em></p><h4>Corollary: They also engendered a sequel to one of their films</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AkbPNinc2SGgPvW6ere23g.png" /><figcaption>“Hobgoblins” (1988) was shown on “MST3K” in 1998, boosting its popularity enough to lead to a sequel, “Hobgoblins 2” in 2009.</figcaption></figure><p>Another related example is the film <a href="https://en.wikipedia.org/wiki/Hobgoblins_(film)"><em>Hobgoblins</em></a>, shown in episode 907. This film was actually <a href="https://mst3k.fandom.com/wiki/MST3K_907_-_Hobgoblins">submitted by its director</a>, Rick Sloane, to <em>MST3K</em>’s production company. He had a mixed reaction to the treatment, but it boosted the film’s popularity enough that he went on to make <a href="https://www.mentalfloss.com/article/53849/16-things-you-might-not-know-about-mystery-science-theater-3000"><em>Hobgoblins 2</em></a>, stating, “<em>Hobgoblins 2</em> was only possible because of the success of <em>MST3K</em>’s revival of the original.” So there were directors who appreciated what <em>MST3K</em> did for their films, and even used it to their advantage to make more movies.</p><h3>2. They adjusted the show’s format in response to fan feedback</h3><p>In the show’s first season on Minnesota TV station KTMA, the show featured two <a href="https://en.wikipedia.org/wiki/Gamera">Gamera</a> movies back-to-back: <a href="https://mst3k.fandom.com/wiki/MST3K_K04_-_Gamera_vs_Barugon">K04 <em>Gamera vs. Barugon</em></a> and <a href="https://mst3k.fandom.com/wiki/MST3K_K05_-_Gamera">K05 <em>Gamera</em></a><em>. </em>In the opening segment for the next episode, <a href="https://mst3k.fandom.com/wiki/MST3K_K06_-_Gamera_vs_Gaos">K06</a>, they <a href="https://www.youtube.com/watch?v=VouJfNwPoXY&amp;t=128s">played a phone message</a> from a fan who called in to complain about having two Gamera movies in a row:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVliWdJZXDJUCbRGwfiTOw.png" /><figcaption>A viewer called in to complain (right) after have to watch two Gamera (left) kaiju movies in a row.</figcaption></figure><p>Joel then breathlessly trolled the caller:</p><blockquote>“We agree with you. … Two Gamuron [sic] movies is ridiculous, but <em>three </em>Gamuron movies is a Gamuron film festival.”</blockquote><p>They then proceeded to show a <em>third</em> Gamera movie — and even followed it up with two more for a total streak of five.</p><p>But, trolling this one caller aside, they rarely did this again after that season. In season 3, they showed nine Japanese films dubbed by Sandy Frank productions, but they spaced them out to debut every other week. They also showed three sets of sequels that never appeared sequentially. This way, if a fan didn’t like a particular style of film — be it a dubbed film, a series, or a certain director — , then they could at least count on next week giving them something different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3g0HJbvhoa0tlvy8p8f7zg.png" /><figcaption>Episode mixing in the KTMA season (left) versus season 3 on Comedy Central (right). KTMA had five Gamera films in a row, plus back-to-back Supermarionation and Sandy Frank films. Season 3 had no such similar films back-to-back anymore.</figcaption></figure><p>They continued this pattern in later seasons, too. Season 2 features three biker films that never appeared back-to-back, and season 4 did three Hercules films that always had an off week between them. Season 8 also had two dubbed Japanese films, <em>Prince of Space </em>and <em>Invasion of the Neptune Men, </em>which are basically the same film, so they were spaced out, too. (By the way, were you always wondering which of those two films was a rip-off of the other? It turns out the answer is <a href="https://www.youtube.com/watch?v=_lRIpp8GW38&amp;t=94s">secret option number 3</a>: they are <em>both </em>rip-offs of an earlier Japanese serial called <a href="https://en.wikipedia.org/wiki/Super_Giant">Starman</a>, which <a href="https://www.rifftrax.com/attack-from-space">was riffed on RiffTrax</a>).</p><p>There were still exceptions, however. <em>MST3K</em> showed two Godzilla films back-to-back in season 2, but maybe because those were the only two slots left in the schedule (episodes 212 and 213). They also did <a href="http://www.mst3kinfo.com/?p=3846&amp;cpage=1">nine black-and-white Universal films</a> in a row for their first season on the Sci-Fi Channel, apparently at the request of the network, whose parent company already held the films’ rights. But this homogeneous run led to a small revolt, and the writers mixed up the film selection from then on once again.</p><h3>3. The show took 9 years to pass the Bechdel test</h3><p>When a show has just one woman among only six regular characters, it may take a while for it to pass the Bechdel test. And also consider that the one female character, the robot <a href="https://mst3k.fandom.com/wiki/Gypsy">Gypsy</a>, was slow, bovine, obsessed with actor <a href="https://en.wikipedia.org/wiki/Richard_Basehart">Richard Basehart</a> — and played by a man. The writers recognized this as problematic, and in season 2 they added <a href="https://youtu.be/0sXsQN79RjA?t=99">backstory</a> to establish that Gypsy was actually the smartest robot but that her brain was mostly occupied running the ship and keeping everyone alive. As head writer Michael J. Nelson noted in the <a href="https://www.amazon.com/Mystery-Science-Theater-Amazing-Colossal/dp/0553377833">episode guide</a>, “Weighing on our minds was the fact that we had one female character and she was a dim-witted cow-like creature played by a man.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*giXJXrskHCK2aPs1nRCWcg.png" /><figcaption>Head writer Michael J. Nelson’s reflections on episode 207 “Wild Rebels” from “<a href="https://www.amazon.com/Mystery-Science-Theater-Amazing-Colossal/dp/0553377833/ref=sr_1_1?dchild=1&amp;keywords=The+Amazing+Colossal+Episode+Guide&amp;qid=1617589453&amp;sr=8-1">The Amazing Colossal Episode Guide</a>.”</figcaption></figure><p>Eventually the show began to feature Mary Jo Pehl and Bridget Nelson appearing in guest roles from season 3. Pehl also took over the main villain role of Pearl Forrester starting in season 8, thus giving the show a female regular.</p><p>Yet even when Pehl and Nelson were on screen at the same time, they never actually spoke to each other. Thus the show didn’t pass the <a href="https://en.wikipedia.org/wiki/Bechdel_test">Bechdel test</a> for its first nine years, until 1997 with <a href="https://youtu.be/WspeHC7eoOI?t=186">episode 811 <em>parts: the clonus horror</em></a><em>. </em>This was where Pearl Forrester (Pehl) and Darlene (Nelson) shared the first female–female dialogue on the show.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-LQLJepbGJoramVBpx2kQ.png" /><figcaption>Mary Jo Pehl (top left; left) and Bridget Nelson (top left; right) appeared on the show together multiple times but never actually spoke until episode 811 (bottom right), whereupon the show passed the Bechdel test.</figcaption></figure><p>But the story gets more complicated. If you can bend the rules a bit, there’s an earlier scene that’s also eligible. In <a href="https://youtu.be/ZOPbyqyf71A?t=1540">episode 804 <em>The Deadly Mantis</em></a>, Pearl Forrester (Pehl) and Gypsy briefly talk to each other. At the time Gypsy is still being played by a man (Jim Mallon), but technically it should count.</p><p>And, if you can bend the rules a bit in the other direction, there’s an even earlier scene to consider. In <a href="https://youtu.be/7_9KAxuOgKM?t=4254">episode 701T <em>The Night of the Blood Beast</em></a>,<em> </em>Mary Jo Pehl and Bridget Nelson also speak — but when Nelson is playing “<a href="https://mst3k.fandom.com/wiki/Mr._B_Natural">Mr. B Natural</a>,” a character from <a href="https://youtu.be/qND_l5mpQRU?t=402">a music short</a> the show riffed back in 1991. Mr. B is an androgynous pants role played by a woman, but we don’t know what gender they’re really supposed to be. Tom and Crow even had a <a href="https://youtu.be/qND_l5mpQRU?t=1402">hilarious debate</a> on this topic that went nowhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NrEsl3EQqvx57qZAK7aIVw.png" /><figcaption>When the show passes the Bechdel test — oddly enough — hinges on the gender identity of androgynous pants role “Mr. B Natural” (left) as played by Bridget Nelson (right).</figcaption></figure><p>But the show itself decided to have Mr. B Natural identify as a man, since it allowed them to set up a joke where a drunk Jack Perkins (played by Michael J. Nelson) hits on Mr. B Natural in <a href="https://www.youtube.com/watch?v=0sFrrhTtL_w&amp;t=534s">this hilarious exchange</a>:</p><blockquote>Jack Perkins: “‘<em>Mister</em>’ B Natural? <em>God</em>, I can’t believe you’re a guy!”<br>Mr. B Natural: “Yep! Every bit of me, all man!”<br> Jack Perkins: “Well, then, so be it! I guess I’m just gonna have to trust my instincts.”<br>Mr. B Natural: “Oh, right, ‘be natural,’ that’s — ”<br> Jack Perkins: “Sir, allow me to kiss you.”</blockquote><h3>4. The show got picked up for cable for a bizarre reason</h3><p>From my reading, there were three main reasons the show got picked up by Comedy Central after its first season on KTMA. The <a href="http://www.mst3kinfo.com/history/page3.html">first reason</a> —a simple one — was that the executives at HBO knew Joel, had worked with him on previous comedy specials, and trusted he could deliver.</p><p>The <a href="http://www.mst3kinfo.com/history/page3.html">second reason</a>—an obvious one — was that the show was two hours long and produced out of Minnesota. For a fledgling cable network that desperately needed original content, that is—to <a href="https://www.kickstarter.com/projects/mst3k/makemoremst3k">quote</a> Joel—“one of the best deals in show business.” Typical sketch comedy shows ran for thirty minutes and would have to be produced out of LA or New York, which meant four complete productions. And, unless all those shows were hits, the network would have to cancel some and start from scratch with new talent next year. On top of that, <em>MST3K</em> already had an established fan base from its “trial run” on KTMA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*lhVnhkVy7eUz4nNfcAoK9g.png" /><figcaption>“The Higgins Boys and Gruber” was a “comedy jock” show also created by Hodgson for Comedy Central at the same time as “MST3K.”</figcaption></figure><p>And the <a href="http://www.mst3ktemple.com/season1.html">third reason</a> — the bizarre one — was that, while <em>MST3K</em> is now known as a cult show and an acquired taste, at the time it was just like what Comedy Central was looking for. MTV had just risen to fame in the 1980’s with the formula of “disc jockeys” who introduced and played music videos, so Comedy Central was looking for shows that could create an analogous experience for comedy, e.g., “<a href="https://www.youtube.com/watch?v=oU0wA1MKrX8">comedy jocks</a>” who introduced and played funny videos. Hodgson even created another one of these such shows for the network, <a href="https://en.wikipedia.org/wiki/The_Higgins_Boys_and_Gruber"><em>The Higgins Boys and Gruber</em></a>. <em>MST3K — </em>when viewed from a bizarre-enough angle <em>— </em>also fit this bill. Of course we now know that that’s not what <em>MST3K</em> is, but, however it got its start, it went on to have a seven-year run at the network.</p><h3>5. The show has one semi-lost episode</h3><p>Up until a few years ago, the show had three lost episodes. All the episodes from season 1 and beyond were released on VHS or DVD, but the show’s initial season on KTMA only survived thanks to fans who recorded the episodes back in 1988–89. Copies had survived for episodes K04 and up, but not for episodes K01, K02, and K03.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pNdRiuvBc5eU0S4InFRx7Q.png" /><figcaption>The semi-lost episode, K03 “Star Force: Fugitive Alien II.”</figcaption></figure><p>Then in 2016, during the <em>MST3K</em> revival, show creator Joel Hodgson announced <a href="https://archive.nerdist.com/two-lost-mystery-science-theater-3000-episodes-have-been-unearthed/">he had found</a> copies of the first two episodes, and he released them to fans. This left just episode K03 undiscovered. But show producers had also previously released a <a href="https://www.youtube.com/watch?v=-Npx1H61An0">set of clips</a> from the first three episodes <a href="http://www.mst3kinfo.com/?p=17731">back in 2009</a>, which included two of the five host segments from K03. Also, the film they watched is known to be <a href="https://www.imdb.com/title/tt0131028/"><em>Star Force: Fugitive Alien II</em></a>, which was re-riffed as episode 318. Judging from the eight other KTMA films that were re-riffed in season 3, the riffing quality is much better later, so we probably aren’t missing too much from K03’s riffing.</p><p>So although no complete copy of K03 has been discovered, we have seen two of its five host segments, we have seen the movie, and we have seen it riffed already. For those reasons, K03 is really only “semi-lost.”</p><h3>6. Every MSTie remembers their first show</h3><p>This last fact is not about the show itself but about its fans — because the Kickstarter is also about them. And one thing I’ve found is that almost every MSTie remembers the first episode they saw.</p><p>For me, I was watching TV when my sister came in and said to turn on channel 63 —for Comedy Central — and check out what she’d found. We tuned into the middle of episode 211, <a href="https://mst3k.fandom.com/wiki/First_Spaceship_on_Venus_(film)"><em>First Spaceship on Venus</em></a><em>, a</em>nd the first joke I can remember was <a href="https://www.youtube.com/watch?v=mQy_Zx4-To0&amp;t=5098s">the line</a>:</p><blockquote>Tchen Yu: “My space suit! It’s punctured!”<br>Tom Servo: “And it’s <strong>rented!</strong>”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*iGsIJs4uwg-SQij3EeggDQ.png" /><figcaption>The <a href="https://www.youtube.com/watch?v=mQy_Zx4-To0&amp;t=5098s">first joke I remember</a> on MST3K: “My space suit! It’s punctured! / And it’s <strong><em>rented</em></strong>!”</figcaption></figure><p>Wherever you find MSTies congregating — whether on <a href="http://mst3kinfo.com/">Satellite News</a>, <a href="http://reddit.com/r/mst3k">Reddit</a>, or elsewhere — , you’ll also find people looking for help identifying an episode, finding a quote, and trying to reconnect with that first memory of seeing their favorite show. <em>MST3K </em>is a special show, and MSTies are a special fan base.</p><p>That’s it. Hope you enjoyed these obscure bits of <em>MST3K</em> lore.Wishing the new <a href="https://www.kickstarter.com/projects/mst3k/makemoremst3k">Kickstarter</a> all the best, and <a href="https://twitter.com/search?q=%23keepcirculatingtheurl">#KeepCirculatingTheURL</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab295b8e2e64" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>