<?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 Max Peng on Medium]]></title>
        <description><![CDATA[Stories by Max Peng on Medium]]></description>
        <link>https://medium.com/@peng_max?source=rss-8eef9f66a00c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sR6fqzI53bb5j_tgse3PGA.jpeg</url>
            <title>Stories by Max Peng on Medium</title>
            <link>https://medium.com/@peng_max?source=rss-8eef9f66a00c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:35:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@peng_max/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[Tic Tac Toe at the Monte Carlo]]></title>
            <link>https://medium.com/swlh/tic-tac-toe-at-the-monte-carlo-a5e0394c7bc2?source=rss-8eef9f66a00c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5e0394c7bc2</guid>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Max Peng]]></dc:creator>
            <pubDate>Wed, 17 Jan 2018 02:42:16 GMT</pubDate>
            <atom:updated>2018-01-17T18:35:35.205Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating a Tic Tac Toe AI that uses the Monte Carlo tree search algorithm.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q9PuhqeberSSYYECJROl8Q.png" /><figcaption>Picture from Alex Knight</figcaption></figure><p>Tic Tac Toe, like other turn based games where information is not hidden and game mechanics are not reliant on chance, is a <em>perfect information game</em>. This type of game allows every player to predict all possible outcomes from someone’s action. Since the game if fully deterministic, a tree can be constructed with all the possible outcomes from the game with each node of the tree given a value determining its win or loss ratio for each player.</p><p>An AI can then traverse this tree and choose a node it deems most likely to lead to a victory. If the AI’s strategy in choosing nodes is to pick the node with the smallest possibility of losing, it would be utilizing a minimax strategy. While in theory this sounds like a feasible game plan, in practice the amount of time to render a full game tree and then traverse it can be unrealistic especially for games with large amounts of possible moves (high branching factor) like Go. This is where the Monte Carlo tree search algorithm comes in.</p><p>Monte Carlo tree search (MCTS) is a heuristic search algorithm that is employed for a large number of game playing AIs. Most notable of them is the Go AI, Alpha Go. MCTS shines in games with high branching factors because unlike minimax which needs a full game tree, MCTS can be configured to stop after a desired amount of time and can select a sufficiently optimal solution based on the partially constructed game tree. While a pure Monte Carlo process would run a multitude of randomly simulated game states, MCTS keeps statistics of each nodes and then applies the Upper Confidence Bound (UCB) algorithm to the node’s stats.</p><p>The UCB function determines a confidence interval for win ratios of each node and returns the highest value in the confidence interval. The function also giving nodes with more simulations a narrower confidence interval while enlarging the confidence intervals of nodes with fewer simulations. The MCTS algorithm selects the node with the highest UCB value to run its simulations on and as a result, although nodes that have a high upper confidence interval may be selected multiple times at first, other nodes with less simulations will have increasingly wider confidence intervals. As their confidence interval grows, their upper bounds may emerge higher than that of the original promising node. Described mundanely, as we test one node more times, our confidence on its payouts become more definitive. We become more certain of its payouts and can narrow our confidence interval for it. We become less confident about the less simulated nodes and widen their confidence intervals to reflect our uncertainty.</p><p>The UCB formula balances the exploration/exploitation problem by making sure that no potential node will be starved of simulated playouts but at the same time making sure that favorable branches are played more often than their counterparts. The UCB formula that we will be using is displayed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*Miishv65b3NzFN4mHl6ivQ.png" /></figure><ul><li><strong>w</strong> stands for the number of simulated wins from that node after the i-th move.</li><li><strong>n</strong> stands for the number of simulations that have occured for that node after the i-th move.</li><li><strong>c</strong> stands for the exploration parameter. We will be using √2.</li><li><strong>t</strong> stands for the total number of simulations that have occured after i moves.</li></ul><p><strong>The first part of the equation corresponds to exploitation</strong>. The higher the number of wins = higher win ratio = higher number for the first part of the equation. <strong>The second part of the equation corresponds to exploration</strong>. A large number of total simulations but a small number of simulations for that node will lead to a larger number for the second part of the equation. Together, the two parts of the UCB function creates a balance between prioritizing promising nodes but also exploring unvisited ones.</p><p>There are four basic phases to MCTS: <em>selection</em>,<em> expansion</em>, <em>simulation</em>,and <em>back-propagation</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*JL2qkJKbXGABHN3-8v8koA.png" /></figure><p>In <strong>selection</strong>, we start at the root node, <strong>R</strong>, and we select successive child node with the highest UCB value until we reach a node with no more children, <strong>L</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*KoEOdVECKDrzjH9g0DjZyg.png" /></figure><p>Unless the <strong>L</strong> node results in a game state that ends the game, we then go into the <strong>expansion</strong> phase and create all possible outcomes from that game state and randomly select one of <strong>L</strong>’s child nodes, <strong>C</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*MdCzozecK3fLHbUijJ7Uuw.png" /></figure><p>In the next phase, <strong>simulation</strong>, we generate a random playout from node <strong>C</strong> to an end game state (win, loss, tie).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*ch4aq-ec3WAun1A3FBYumA.png" /></figure><p>We use the resulting game state during <strong>back-propagation </strong>to update the information within the nodes from <strong>C</strong> to <strong>R</strong> with whether the new playout resulted in a win, loss or tie.</p><p>Altogether it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Avecss5kgQ60GoHe9I5zZg.png" /></figure><p>The algorithm will cycle through all 4 phases until the allotted time has passed. Afterwards, it will choose the child node of the root with the highest amount of visits due to the fact that more visits equals more selections which only occurs if it has the highest UCB value. This then repeats for each turn of the game.</p><p>I will now be showing an example of MCTS built with Javascript. This is just a general game playing formula and can be tailored for any turn-based game. In this case specifically, the algorithm will be used for a Tic Tac Toe AI. While Tic Tac Toe is a much smaller game than Go with a vastly smaller branching factor, they’re both using the same principles.</p><p>The main goal of MCTS is to find the best possible move at your current state. To reach this goal, we should create a function called findNextMove. I will explain each part of the following function later on.</p><pre>findNextMove(board, playerNo) {<br>  let opponent = 3 - playerNo;<br>  let tree = new Tree();<br>  let rootNode = tree.root;<br>  rootNode.state.board = new Board(board);<br>  rootNode.state.playerNo = opponent;</pre><pre>  let startTime = Date.now();<br>  while ((Date.now() - startTime) &lt; 1000) {<br>    let promisingNode = selectPromisingNode(rootNode);<br>    <br>    if (promisingNode.state.board.checkStatus() === IN_PROGRESS) {<br>      expandNode(promisingNode);<br>    }</pre><pre>    let nodeToExplore = promisingNode;<br>    if (nodeToExplore.childArray.length &gt; 0) {<br>      nodeToExplore = promisingNode.getRandomChild();<br>    }</pre><pre>    let playoutResult = simRanPlayout(nodeToExplore, opponent)<br>    backpropagation(nodeToExplore, playoutResult);<br>  }</pre><pre>  let winnerNode = rootNode.getChildWithMaxScore();<br>  return winnerNode.state.board;<br>}</pre><p>Let us first define what node, state, and board are. The board is an object that keeps track of the size of the board, what pieces have been played and where and what values the status of the game means. The node object keeps track of the state, The state is an object that keeps track of the board, the current player, the number of times the node has been visited, and the win score of the node.</p><p>Essential information we will need to find the optimal move would be the state of the board as well as whose turn it is, both of which are given to the function through its parameters. The function then creates the tree it will be traversing. The tree’s root node will have the board’s current state.</p><p>The function then goes into a while loop that runs for a set amount of time. The longer we allow it to run, the more confident we are about the AI’s next move. You can see the 4 phases of MCTS in the while loop.</p><ul><li>selection phase = selectPromisingNode()</li><li>expansion phase = expandNode()</li><li>simulation phase = simRanPlayout()</li><li>back-propagation phase = backpropagation()</li></ul><p>Let us expand the selectPromisingNode function.</p><pre>selectPromisingNode(rootNode) {<br>  let node = rootNode;<br>  while (node.childArray.length !== 0) {<br>    node = UCB.findBestNodeWithUCB(node);<br>  }<br>  return node;<br>}</pre><p>In this function, we traverse the tree starting from the root node and find the most promising leaf node below it. This is achieved by looking at the UCB values of each child node and selecting the node with the highest value. The process repeats until a node has no more child nodes. The functions to compute the UCB values is below.</p><pre>UCB = {</pre><pre>  findBestNodeWithUCB: (node) =&gt; {<br>    let parentVisitCt = node.state.visitCount;<br>    let childUCB = [];<br>    node.childArray.forEach(child =&gt; {<br>      childUCB.push(UCB.ucbValue(parentVisitCt, child.state.winScore, child.state.visitCount));<br>    }</pre><pre>    let max = Math.max(...childUCB);<br>    let idx = childUCB.indexOf(max);<br>    return node.childArray[idx];</pre><pre>  };</pre><pre>ucbValue: (totalVisit, nodeWinScore, nodeVisit) =&gt; {</pre><pre>    if (nodeVisit === 0) {<br>      return Number.MAX_SAFE_INTEGER;<br>    }<br>    return (nodeWinScore / nodeVisit) + 1.41 * Math.sqrt ( Math.log (totalVisit) / nodeVisit);<br>  }</pre><pre>}</pre><p>Corresponding to the UCB formula above, we use the number of total visits from its parent node, <strong>t</strong>, the number of simulated wins the current node has generated, <strong>w</strong>, and the amount of times the node has been selected, <strong>n</strong>, to find the UCB value. If the node has never been visited before, we give its value the maximum integer possible to increase its chances of being selected. This makes sure that every node will be simulated at least once. The findBestNodeWithUCB function generates a UCB value for every child node and returns the child node with the highest value.</p><p>Once we’ve selected the node we are going to use, we check the status of the game board. The checkStatus function return -1 if the game is still in progress, 0 if it results in a tie, or 1 and 2 depending on which player won the game. If the game status is a non-game ending state, -1, we will then go into the expansion phase. Let’s take a look at the expandNode function.</p><pre>expandNode(node) {</pre><pre>  let possibleStates = node.state.getAllPossibleStates();</pre><pre>  possibleStates.forEach(state =&gt; {<br>    let newNode = new Node(state);<br>    newNode.parent = node;<br>    newNode.state.playNo = node.state.getOpponent();<br>    node.childArray.push(newNode);<br>  });</pre><pre>}</pre><p>This function first finds all possible outcomes from the current nodes state. It then creates a node with every possible move from the current state and pushes it into the child array of the current node. Although expansion seems like a very grandiose term, the phase is extremely simple. It just populates the childArray with possible game states unless the selected node is a node with an end game status. The next lines in the algorithm:</p><pre>let nodeToExplore = promisingNode;<br>if (nodeToExplore.childArray.length &gt; 0) {<br>  nodeToExplore = promisingNode.getRandomChild();<br>}</pre><p>checks if the current array had any possible childs and randomly select one of the nodes to run for its simulated gameplay. The simulated gameplay is done in the simulateRandomPlayout function.</p><pre>simulateRandomPlayout(node, opponent) {</pre><pre>  let tempNode = new Node(null, node);<br>  let tempState = tempNode.state;<br>  let boardStatus = tempState.board.checkStatus();</pre><pre>  if (boardStatus === opponent) {<br>    tempNode.parent.state.winScore = Number.MIN_SAFE_INTEGER;<br>    return boardStatus;<br>  }</pre><pre>  while(boardStatus === board.IN_PROGRESS) {<br>    tempState.togglePlayer();<br>    tempState.randomPlay();<br>    boardStatus = tempState.board.checkStatus();<br>  }<br>  return boardStatus;</pre><pre>}</pre><p>Here the function first checks the node’s board to see what its status is. If the node results in an opponent’s victory, it would mean that if the player had made the selected move, his opponent will have a subsequent move that can result in the opponents immediete victory. Because the move the player chose can lead to a definite loss, the function lowers the parents node’s winScore to the lowest possible integer to prevent future moves to that node. Otherwise the algorithm alternates random moves between the two player until the board results in a game ending state. The function then returns the final game status.</p><p>The final step of MCTS is backpropogation.</p><pre>backpropagation(nodeToExplore, playoutResult) {<br>  let tempNode = nodeToExplore;<br>  while (tempNode !== undefined) {<br>    tempNode.state.visitCount++;<br>    if (tempNode.state.playNo === playoutResult) {<br>      tempNode.state.addScore(10);<br>    }<br>    tempNode = tempNode.parent;<br>  }<br>}</pre><p>Here we travel back from the child of the leaf node that we selected to the root node. Along the way we increment the nodes visitCount. If the playoutResult that we get from the return of simulateRandomPlayout equals the player number whose turn we are simulating, we then increment the win scores of each node. These updated statistics are then used for the next iteration of the selection phase when calculating UCBs.</p><p>These steps run for as long as we specify, in this case 1000 milliseconds or 1 second. Once the time runs out, we select the child node of the root with the most visit counts since a node will only be visited if it has the highest UCB which theoretically means that move will lead to the highest chance of victory.</p><p>We can test our algorithm with the following function that simulates a game of Tic Tac Toe between two AIs:</p><pre>simulateAIPlay() {<br>  let board = new Board();<br>  let player = 1;<br>  let totalMove = 9;<br>  for (var i = 0; i &lt; totalMove; i++) {<br>    board = findNextMove(board, player);<br>    if (board.checkStatus() !== -1) {<br>      break;<br>    }<br>    player = 3 - player;<br>  }<br>  let winStatus = board.checkStatus();<br>  return winStatus;<br>}</pre><p>Since both AI’s are using this super awesome algorithm and both will be selecting the most optimal moves, each game will result in a tie.</p><p>You can check out my full code <a href="https://gist.github.com/pengcheng95/762321c9d2224c5b7bcb7317fc5c2d82">here</a>.</p><p>Much thanks to this <a href="http://www.baeldung.com/java-monte-carlo-tree-search">article</a> for helping me create the MCTS functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gfnVvkMRFtjVsWF7vkClA.png" /></figure><h4>This story is published in <a href="https://medium.com/swlh">The Startup</a>, Medium’s largest entrepreneurship publication followed by 286,184+ people.</h4><h4>Subscribe to receive <a href="http://growthsupply.com/the-startup-newsletter/">our top stories here</a>.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gfnVvkMRFtjVsWF7vkClA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5e0394c7bc2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/tic-tac-toe-at-the-monte-carlo-a5e0394c7bc2">Tic Tac Toe at the Monte Carlo</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading Javascript]]></title>
            <link>https://medium.com/techtrument/multithreading-javascript-46156179cf9a?source=rss-8eef9f66a00c------2</link>
            <guid isPermaLink="false">https://medium.com/p/46156179cf9a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[webworker]]></category>
            <dc:creator><![CDATA[Max Peng]]></dc:creator>
            <pubDate>Fri, 15 Sep 2017 03:08:23 GMT</pubDate>
            <atom:updated>2017-09-17T01:58:19.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6DyyyyZqMPIaHhoVXPPxtg.jpeg" /><figcaption>Image from playembbeded.com</figcaption></figure><h4>A Look Into Web Workers</h4><p>As you may probably know, Javascript is single-threaded. To clarify better, this means that one single thread handles the event loop. For older browsers, the whole browser shared one single thread between all the tabs. Modern browsers improved upon this by using either <a href="https://www.chromium.org/developers/design-documents/process-models">process-per-site-instance</a> or different threads per tab. Although dedicated threads improved the responsiveness of webpages, it still left each tab unable to handle multiple scripts running at once.</p><p>You may be wondering, why would we need multiple scripts running at once?</p><p>Computers are extremely fast and with each tab using its own thread, webpages should have no problems. This is true for most cases until your browser runs a complex algorithm or renders an intricate visualization. These laborious processes end up blocking the main thread which slows down UI events and triggers. Good thing in 2009, Javascript introduced a hot new toy, Web Workers, to deal with this problem.</p><p>So what are Web Workers?</p><p>Web Workers are Javascript scripts executed from an HTML page that runs on a background thread away from the main execution thread. Data is sent between the main thread and workers through messages. Since these workers run on a separate thread than the main execution thread, you can utilize web workers to run process intensive tasks from the browser without creating blocking instances.</p><p>Cool right? Let us build some.</p><p>Its pretty simple to spawn a Web Worker. First we need to start with two files: a main file and a file that contains the code that the worker will run. The separate files are necessary because the web worker code will need to be run in an isolated thread. Let us name the files main.js and worker.js. To create a new Worker object, we will pass in the path of the worker file into the Worker constructor like so:</p><pre>// main.js</pre><pre>var worker = new Worker(&#39;worker.js&#39;);</pre><p>Now that we have a worker, let us send it a message. To do so we will have to call the postMessage() function on the worker object.</p><pre>// main.js</pre><pre>worker.postMessage(&#39;Happy Birthday&#39;);</pre><p>At this point I should probably point out a caveat of web workers. The data sent between the main thread and the workers are copied rather than shared. We should keep this in mind when thinking about memory allocation and the speed of data transfer.</p><p>Now for our worker to hear the ‘Happy Birthday’ message, we will have to set an event listener in the worker.js file for the message event.</p><pre>// worker.js</pre><pre>self.addEventListener(&#39;message&#39;, function(e) {<br>  // code to be run<br>}</pre><p>Once the worker file hears a message event, it runs the code within the function block. Just write it like any other normal function but instead of returning a variable send a message back to the main thread with a postMessage() function. We can use the data from the sent message with e.data.</p><pre>// worker.js</pre><pre>self.addEventListener(&#39;message&#39;, function(e) {<br>  var message = e.data + &#39;to myself!&#39;;<br>  self.postMessage(message);<br>}</pre><p>In the above code, we are sending the message, ‘Happy Birthday to myself!’ back to the main execution thread. As a result, we will also need a message event listener in the main file to receive the data and act upon it. Here is the final main.js file:</p><pre>// main.js</pre><pre>var worker = new Worker(&#39;worker.js&#39;);</pre><pre>worker.addEventListener(&#39;message&#39;, function(e) {<br>  console.log(e.data);<br>}</pre><pre>worker.postMessage(&#39;Happy Birthday&#39;);</pre><p>In this example, we will console.log ‘Happy Birthday to myself!’. A helpful tip is that while the order of worker.addEventListener and worker.postMessage does not matter, it makes logical sense for us to create the ability to listen to a message before sending one out.</p><p>Finally we would like to close the worker thread, which we can do be adding a self.close() function in the worker file. Here is the final worker.js:</p><pre>// worker.js</pre><pre>self.addEventListener(&#39;message&#39;, function(e) {<br>  var message = e.data + &#39;to myself!&#39;;<br>  self.postMessage(message);<br>  self.close();<br>}</pre><p>Lets go through what just happened:</p><ol><li>Our application created a web worker in main.js which runs the code from worker.js</li><li>It sends the worker a message with the string ‘Happy Birthday’</li><li>The worker, which had an event listener for ‘message’, received the message and ran the code within.</li><li>The worker appended ‘to myself!’ to the message data creating ‘Happy Birthday to myself!’ and sends that as data within a message back to main.js</li><li>Main.js, which also had an event listener for message, than console.log ‘Happy Birthday to myself!’.</li></ol><p>Easy!</p><p>The following code uses web workers to split up the processing for solving n-queens:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f159856fcab6638577523fcc9f0e344/href">https://medium.com/media/4f159856fcab6638577523fcc9f0e344/href</a></iframe><p>Feel free to play around with it! A note for testing web workers, for security reasons Chrome does not allow you to deploy web workers locally. Use Firefox instead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46156179cf9a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/techtrument/multithreading-javascript-46156179cf9a">Multithreading Javascript</a> was originally published in <a href="https://medium.com/techtrument">Hackmamba</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bitwise N-Queens in a Tweet]]></title>
            <link>https://medium.com/cloudboost/bitwise-n-queens-in-a-tweet-9251ef0e4379?source=rss-8eef9f66a00c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9251ef0e4379</guid>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[bitwise]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Max Peng]]></dc:creator>
            <pubDate>Fri, 08 Sep 2017 03:19:57 GMT</pubDate>
            <atom:updated>2017-09-11T00:07:57.983Z</atom:updated>
            <content:encoded><![CDATA[<p>The N-Queens question is a classic example given to programmers to help them think about backtracking. How many different ways are there to place N queens safely on a NxN board?</p><p>Usually to help visualize backtracking, we can create a two-dimensional matrix that mimics a chess board where matrix elements are toggled on and off to represent the placement of queens on the board. After understanding this method, we can improve the function’s speed by using three one-dimensional arrays to keep track of what column and diagonal positions the queens have been placed. If we want to even further improve the speed and memory of the function we can use <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.51.7113&amp;rep=rep1&amp;type=pdf">bit patterns to keep track of the pieces positions and binary operators to find potential piece placement</a>s. To further challenge ourselves, we can try to create the shortest possible N-Queens solution.</p><p>Mr. Pethiyagoda gives us this lovely example:</p><h3>Ruan Pethiyagoda on Twitter</h3><p>function N(Q,u,ee,n,s,H,R){s=0;Q=u?Q:(1&amp;lt;&amp;lt;Q)-1;H=~(u|ee|n)&amp;amp;Q;while(H)H^=R=-H&amp;amp;H,s+=N(Q,(u|R)&amp;lt;&amp;lt;1,ee|R,(n|R)&amp;gt;&amp;gt;1);return s+=ee==Q}// @HackReactor</p><p>Now what does this tweet mean?</p><p>After chuckling or groaning at the wordplay displayed in the naming of the parameters for the function lets reformat the tweet.</p><pre>function N(Q, u, ee, n, s, H, R) {</pre><pre>s = 0;<br>Q = u ? Q : (1 &lt;&lt; Q) - 1;<br>H = ~(u | ee | n) &amp; Q;</pre><pre>while (H) H ^= R = -H &amp; H, s += N(Q, (u | R) &lt;&lt; 1, ee | R, (n | R)  &gt;&gt; 1);</pre><pre>return s += ee == Q</pre><pre>}</pre><p>Now the code ooks like the algorithm from <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.51.7113&amp;rep=rep1&amp;type=pdf">Martin Richards paper</a>. Here Martin uses bit patterns to keep track of queen placements for the columns, left diagonals and right diagonals. The blue lines in the following diagram are what represents a bit in the bit patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xg6S22GVqeKh003X9tZXjg.png" /></figure><p>A 1 in the bit pattern denotes that there is a queen attacking that column or diagonal line and 0 means that no queens are attacking that position. A caveat that you may later notice from the diagram below is that the bit patterns for the left and right diagonals only represent what is happening on the current row we are analyzing. This is because like most N-Queens solutions, we only react to the circumstances of the current row we are working with. I will later explain how Martin uses binary operators to change the bit patterns of the diagonals as we switch rows and how to find possible queen placements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KAEMygl4QM79QPzZY47chg.png" /></figure><p>To help us decipher the tweet, I will first give you what the parameters mean: <strong>Q</strong> is the size of a board side/number of queens we must place on the board but later becomes the binary representation of a full board. <strong>u</strong>, <strong>ee</strong>, and <strong>n</strong> are each a number that is the bit pattern to what left diagonals, columns, and right diagonals are being currently attacked by queens on the board. <strong>s</strong> maintains the count of the number of solutions found. <strong>H</strong> is a bit pattern that represents all a board. <strong>R</strong> is the bit pattern of the right most possible position to place a queen.</p><pre>// Start of the function<br>s = 0;<br>Q = u ? Q : (1 &lt;&lt; Q) - 1;<br>H = ~(u | ee | n) &amp; Q;</pre><p>Mr. Pethiyagoda’s function’s first step is to set the solution count, <strong>s,</strong> to 0. <strong>s</strong> will later be incremented as solutions are found. He then checks if any pieces have been placed on the board. If not, a binary representation of a full board, <strong>Q</strong>, is created through</p><pre>(1 &lt;&lt; Q) - 1<br>// example of how this works<br>// if Q = 5<br>(1 &lt;&lt; 5) = 100000 // binary representation of 32<br>32 - 1   = 100000 - 000001 = 11111</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eh0wYOWILGC2Vy_y1VvtLA.png" /><figcaption>Diagram from Backtracking Algorithms in MCPL using Bit Patterns and Recursion</figcaption></figure><p>Once Q is instantiated, a bitwise OR operator is run on <strong>u</strong>, <strong>ee</strong>, and <strong>n</strong>. By combining all of the 1’s in the 3 bit patterns into one bit pattern, we can see where all the places on the current row of the board that are being attacked by a queen. We can then find all the possible placements of queens on the row by inverting the combined bit pattern with a bitwise NOT operator and than masking it with <strong>Q</strong>. This new bit pattern becomes <strong>H</strong>.</p><pre>// for example in the above diagram, the combination of ld, cols, <br>// and rd are attacking:<br>(u | ee | n ) = 11011101</pre><pre>// a bitwise NOT operator flips the 1’s and 0’s producing the places // that are not under attack:<br>~(u | ee | n) = 00100010</pre><pre>// because computers create numbers from a x amount of bits,<br>// we have to mask that ~(u | ee | n) with Q to remove the 1’s in <br>// the bit pattern larger than Q (ex. javascript numbers are 32 bit<br>// large)<br>// ~(u | ee | n) will look like ...1111111111111100100010<br>H = ~(u | ee | n) &amp; Q = ...00000000000000100010</pre><p>While <strong>H</strong> is not 0, which means as long as there are possible queen placements left, we run:</p><pre>H ^= R = -H &amp; H, s += N(Q, (u | R) &lt;&lt; 1, ee | R, (n | R)  &gt;&gt; 1);</pre><p>The first thing that gets evaluated here is the -<strong>H</strong> &amp; <strong>H</strong>. This expression is a bitwise techique that helps isolate the right most bit of H which gets saved to <strong>R</strong>. <strong>R</strong> will be the position where we will place our newest queen. To run a test of all possible queen placements on the current row, we run function <strong>N</strong> with the parameters <strong>Q</strong>, a bit pattern representation of a full board, <strong>(u | R) &lt;&lt; 1</strong>, the left diagonal bit pattern, <strong>ee | R</strong>, the column bit pattern, and <strong>(n | R) &gt;&gt; 1</strong>, the right diagonal bit pattern. The bitwise OR operator is used to represent the placement of the new queen at its rightmost available spot. The diagonal bit patterns were right and left shifted to represent what diagonals the queens are attacking on the new row. The plus equals operator after <strong>s</strong> adds the result from this function to the total count for the number of solutions.</p><p>I will now go back and explain the <strong>H ^= R </strong>expression. This removes the rightmost bit from <strong>H</strong>. Since a while loop of all possible positions, <strong>H</strong>, is what determines how many times the <strong>N</strong> function gets run, once all possible <strong>H</strong> values are tested for the row, the loop ends. In layman terms, all possible queen positions have been tested for the row and all we can do is wait to see if each tests resulted in a solution or failure. As each test spawns new tests, all possible board placements are found.</p><pre>return s += ee == Q</pre><p>The last line return determines what gets returned and when <strong>s</strong> gets to increment. In this case, if columns, <strong>ee</strong>, is equal to a full board, <strong>Q</strong>, which simplified means that N queens were placed on the board, a solution is found and the function can increment <strong>s</strong> by 1.</p><p>Now this function is impressive by how short it is and it may seem that this is the fastest way you can solve N-Queens with using javascript but its not. Bitwise operations are fast but you can combine it with another javascript feature to improve the speed of your N-Queens solution but that is for another time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9251ef0e4379" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudboost/bitwise-n-queens-in-a-tweet-9251ef0e4379">Bitwise N-Queens in a Tweet</a> was originally published in <a href="https://medium.com/cloudboost">CloudBoost</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>