<?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 Boi Mai Quach on Medium]]></title>
        <description><![CDATA[Stories by Boi Mai Quach on Medium]]></description>
        <link>https://medium.com/@quachmaiboi?source=rss-2a9bdb49c93f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FRvF1j37gjtrtlOM65CZ5w.jpeg</url>
            <title>Stories by Boi Mai Quach on Medium</title>
            <link>https://medium.com/@quachmaiboi?source=rss-2a9bdb49c93f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 09:38:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@quachmaiboi/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[Optimizing data center operation — Part 2]]></title>
            <link>https://medium.com/@quachmaiboi/optimizing-data-center-operation-part-2-0b42f0c4a934?source=rss-2a9bdb49c93f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b42f0c4a934</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[linear-programming]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[mixed-integer-programming]]></category>
            <category><![CDATA[data-center-management]]></category>
            <dc:creator><![CDATA[Boi Mai Quach]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 12:49:36 GMT</pubDate>
            <atom:updated>2024-10-01T18:02:18.028Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimizing data center operation — Part 2</h3><h3>Introduction</h3><p>In the <a href="https://medium.com/@quachmaiboi/optimizing-data-center-operation-part-1-8c21cf4f9378"><strong>previous article</strong>,</a> we solved a mathematical optimisation problem to recommend actions — <strong>buy, move, hold, and dismiss </strong>— for determining the number of servers of each type to deploy at each data centre, all aimed at maximising profit. However, the utilisation of older generations, such as S1 and S2, was less sufficient compared to newer generations like S3 and S4.</p><p>In reality, keeping customers satisfied is the key to business success. In the first part of the optimisation problem, we worked with a fixed price per time step for On-Demand Instances, although prices differed across server types and generations. We may have noticed that On-Demand Instances offer flexibility and scalability, which are some of their key benefits. However, this flexibility comes at a higher price compared to Spot Instances. Many companies tend to overprovision On-Demand capacity when they are uncertain about the actual needs of a particular use case, leading to increased costs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*g7-o9HHGLkMlCWxCq44gYg.jpeg" /></figure><p>Spot Instances provide an opportunity to reduce prices during periods of excess capacity. By offering discounted rates, suppliers can optimise server utilisation, reduce waste, and attract more customers who are cost-sensitive, ultimately boosting revenue from underutilised resources.</p><p>On the other hand, during periods of high demand, increasing prices can capture additional profit while still meeting market needs. This price flexibility allows suppliers to maximise profitability by dynamically adjusting pricing based on capacity and demand.</p><p>To incorporate this into our previous optimisation model, we introduce a new action called <strong>“pricing strategy”</strong>. Let’s dive into the concept of pricing strategy and explore how to recommend appropriate pricing for each time step to maximise both utilisation and profit.</p><blockquote>For readers who are encountering this series for the first time, my purpose is to share my passion for mathematics to inspire people of all backgrounds. My code will be published on <a href="https://github.com/Tayerquach/data_center_operations/tree/master">my GitHub</a>.</blockquote><p><a href="https://github.com/Tayerquach/data_center_operations/tree/master">GitHub - Tayerquach/data_center_operations</a></p><p><em>✨Please give me a 👏 if you are interested in my sharing, leave a comment 💬 to share your views/thoughts. ✨</em></p><h3>Problem Overview</h3><p>In this scenario, there is one decision-maker responsible for managing four data centers. Each data center can contain two types of servers: CPU servers and GPU servers. The decision-maker’s goal is to maximize profit while adhering to a key constraint: each data center has a fixed slot capacity. To achieve this goal, the decision-maker can take five actions at each discrete time-step: buy a server, move a server from one data-center to another, hold a server as it is, dismiss a server, and set the price for any segment of demand.</p><p>Please refer to <a href="https://github.com/Tayerquach/data_center_operations/blob/master/Data_center_operation_part1.ipynb"><strong>data center operation optimisation — part 1</strong></a><strong> </strong>to understand how to build an optimisation model to maximize the profit based on four actions. In this part, we will introduce the new action “<strong>price strategy</strong>” and its related information.</p><p>Price elasticity theory was once the haunt of classical economists, with loose applications in the real world. Today, many logistics companies, with their sheer volume of data and surge algorithms, are able to continuously triangulate price elasticities in real time to manipulate demand, moment-to-moment.</p><p>In order to understand more about this price elasticity, we back in understanding demand. Both theoretical economists and business people alike represent and measure demand using the <a href="https://github.com/Tayerquach/data_center_operations/blob/master/photo/demand_curve.png"><strong><em>demand curve</em></strong></a>, which is formally defined as the graphical representation of the relationship between price and the quantity demanded at any given point in time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*dRfbI5mLP_wprXXFp4PtRw.jpeg" /></figure><p>The <strong>law of demand</strong> states that the quantity demanded of a given good/service has an inverse relationship to its price. In other words, that higher prices lead to lower quantities demanded, and vice versa.</p><p>The <strong>price elasticity of demand (PED)</strong> measures the percentage change in quantity demanded by consumers as a result of a percentage change in price. This measurement of price elasticity of demand is calculated by dividing the % change in quantity demanded by the % change in price, represented in the PED ratio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D7zMOwjYYQPpqZYp3-TXSg.png" /></figure><p>Where ϵ is Price Elasticity of Demand</p><p>For instance, given ϵ = −2 a price increase of 10% causes a 20% decrease in quantity demanded. In practice, when a new price is set the demand is updated through the “get_new_demand_for_new_price” function.</p><pre>def get_new_demand_for_new_price(d0, p0, p1, e):<br>    # CALCULATE THE NEW DEMAND ACCORDING TO THE NEW PRICE<br>    delta_p = (p1 - p0) / p0<br>    delta_p_e = delta_p * e<br>    d1 = d0 * (1 + delta_p_e)<br><br>    return d1</pre><h3>Data Exploration</h3><p>For more infomarion about data center, servers, demand, please refer to the first part of this optimisation problem at <a href="https://github.com/Tayerquach/data_center_operations/blob/master/Data_center_operation_part1.ipynb"><strong>data center operation optimisation — part 1</strong></a>.</p><h4>Price information</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ywPB78RVGRlNJUaMMQ15g.png" /></figure><pre>elasticity = pd.read_csv(&#39;https://github.com/Tayerquach/data_center_operations/blob/master/data/price_elasticity_of_demand.csv?raw=true&#39;)<br>elasticity</pre><p><strong>Insights:</strong></p><ul><li><strong>CPU vs. GPU</strong>: Across all latency sensitivities, CPU generations tend to have higher (more negative) elasticity values compared to GPUs, meaning customers are more price-sensitive when it comes to CPU usage.</li><li><strong>Latency Sensitivity</strong>: Elasticity increases (becomes more negative) as latency sensitivity moves from low to high.</li></ul><p>Now, we increase all selling prices by 2 units for CPUs and 300 units for GPUs from the begining and keep them stable to the end of period. Let’s see how the demand changes across server generations and latency sensitivities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o9z4_FHtry5D3xh59wetFg.jpeg" /></figure><p>As expected, when the price increases, the demand decreases according to the law of demand.</p><h3>Problem Formulation</h3><p>Let’s define our notations for the Mathematical Optimisation model.</p><p><strong>Sets</strong></p><ul><li><strong>DC</strong>: Set of data center IDs</li><li><strong>T</strong>: Set of timesteps</li><li><strong>LS</strong>: Latency sensitivity types</li><li><strong>SG</strong>: Server generations</li><li><strong>Lifespan: </strong>Set of life ages for each servers (from 1 to life expectancy).</li></ul><p><strong>Parameters</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*of2xSbEbWhDzr6J6JXpZBg.png" /></figure><h3>Decision Variables</h3><p>First, we define four actions as our decision variables: the number of servers bought, moved, removed, and dismissed. The ‘Hold’ action is automatically applied if no dismissal action is taken for a given server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DThraugtOfEGVXzjRYBtYw.jpeg" /></figure><p>Another variable is the inventory of servers at each datacenter and is updated at the end of the time-step after all actions are applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZsWsA46jZ957rjwme-BqIw.jpeg" /></figure><p>For pricing strategy, we have two variables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q1VgX6CkO6FZGww7WN4QXw.png" /></figure><p>With these initial decision variables, we can start the Mathematical Operation model.</p><p>First of all, initialise the model</p><pre>model = gp.Model(&quot;Data_center_operation&quot;, env = env)<br>model.setParam(&#39;Seed&#39;, seed)</pre><pre># Decision variables<br># Buy action<br>buy = model.addVars(time_steps, server_types, datacenters_id, lb = 0, vtype=GRB.CONTINUOUS, name=&quot;buy&quot;)  # Number of servers bought<br># Move action<br>move_to = model.addVars(time_steps, server_types, datacenters_id, lifespan, lb = 0, vtype=GRB.CONTINUOUS, name=&quot;move_to&quot;)  # Number of servers moved<br>remove_from = model.addVars(time_steps, server_types, datacenters_id, lifespan, lb = 0, vtype=GRB.CONTINUOUS, name=&quot;remove_from&quot;)  # Number of servers moved<br>#Dismissing servers<br>dismiss = model.addVars(time_steps, server_types, datacenters_id, lifespan, lb = 0, vtype=GRB.CONTINUOUS, name=&quot;dismiss&quot;)  # Number of servers moved<br># Decision variables to track server lifespan in inventory<br>I = model.addVars(range(start_ts, end_ts + 1), server_types, datacenters_id, lifespan, lb = 0, vtype=GRB.CONTINUOUS, name=&quot;inventory&quot;) #  Inventory begins before time step = 1</pre><h3>Constraints</h3><ol><li><strong>Setting Up Initial Inventory:</strong></li></ol><p>At the beginning of the planning period, no servers are in place. The initial inventory for each server generation, data center, and lifespan stage is set to zero. This is represented mathematically as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s17qitf4_puPRjnKHrWv8w.png" /></figure><p><strong>2. Pricing Strategy — Updated Demand Constraints</strong></p><p>For every changes in renting prices, we will obtain a new demand. As we mentioned about this “law of demand” in the Introduction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udKs0C5ySDW2dVSTAgNMFw.png" /></figure><p><strong>3. Buying servers</strong></p><p>At each time step, you may need to buy new servers. When you buy a server, it starts with a “life” value of 1, meaning it is newly deployed. However, servers can only be bought when their generation is released. This is controlled by a condition that checks whether the current time step matches the release time of a specific server generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukmIzkCXEw2K1KFCrDBX0w.png" /></figure><p><strong>4. Dismiss servers</strong></p><p>The term “Dismiss” can be understood in two ways:</p><ul><li><strong>Dismiss (lifespan &gt; life expectancy)</strong>: This refers to decommissioning a server once it exceeds its expected lifespan.</li><li><strong>Dismiss (stop using at a time period)</strong>: This refers to halting the use of a server during a specific time period, even if it hasn’t reached the end of its life expectancy.</li></ul><p>Dismissal occurs first in the decision process, and only servers that are already in the inventory from a previous time step can be dismissed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CSnxiEC1UzC71asLTupYgg.png" /></figure><p>For servers in their first life stage, dismiss action is not allowed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7qHqfm9hWh1cIC6BFG00A.png" /></figure><p><strong>5. Move action</strong></p><p>To effectively solve a “move” action, it can be broken down into two sub-actions to efficiently handle the logistics of moving resources.</p><ul><li><strong>Move to</strong>: This refers to relocating a certain number of servers from one data center to another.</li><li><strong>Remove to</strong>: This refers to removing a certain number of servers from their current data center in preparation for the move.</li></ul><p>After dismissal, you can decide to move servers between data centers or remove them altogether. However, you can only remove or move servers that have already existed in the previous time step</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*lQWoUBDWrDNB1II4BrNF9g.jpeg" /></figure><p>Servers in their first life stage cannot be moved or removed. This is because we cannot purchase a server, place it in one data center, and then immediately move it to another. Such a process would not be logical or appropriate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3T4SG2H4lZTtrAMRVxHGGw.png" /></figure><p>To ensure no servers are lost during moves, the total number of servers moved into a data center must equal the number moved out at the same time step with same lifespan and server generation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*3ew_wmCk2Wtlua_8cX9uWQ.jpeg" /></figure><p><strong>6. Updating Inventory</strong></p><p>Once you’ve handled dismissal, moving, and removing servers, you update the inventory for the next time step. The new inventory consists of the servers left from the previous period, plus those moved in, minus those removed and dismissed. This ensures that the server count is updated properly as they age.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TXu3yNjVlivdl9Ios-3Jvg.jpeg" /></figure><p><strong>7. Slot capacity constraints</strong></p><p>Each data center has a limited number of physical slots that can hold servers. You must ensure that the total number of server slots used in each data center doesn’t exceed its capacity. This includes all servers from different generations and lifespans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-VhT9pAR6M6oqi-83Jo0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DsyhcMohQYYBM3PilCx84g.png" /></figure><p><strong>8. Meeting Demand with available capacity</strong></p><p>We try to meet demand with this available capacity, which is modeled using a variable <strong>min_var</strong> that represents the minimum of the available capacity and the demand:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VHTEH23XaaBAMHXjAJir3w.png" /></figure><p>This is also the <strong>important part for the pricing strategy.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bf_R7Az-Hy6Bs3WodisSZw.png" /></figure><blockquote>The formula suggests that there exists a price such that the capacity Zf approaches the demand D. Our optimization model will try to find the appropriate prices. Thus, after solving the optimization in Part 1, we can record the min_var at each time step. Now, for each min_recorded, we want the model to perform backpropagation to find the proper prices.</blockquote><p>Therefore, a new constraint is introduced:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJ5WQ7eQxsTSJcVUNRMyyg.png" /></figure><p>Now, let’s look at the code for these constraints.</p><pre># Auxiliary variable for min(I, demand)<br>min_var = model.addVars(time_steps, server_types, latency_sensitivity, vtype=GRB.CONTINUOUS,lb = 0, name=&quot;min_var&quot;)<br>Zf_var = model.addVars(time_steps, server_types, latency_sensitivity, vtype=GRB.CONTINUOUS,lb = 0, name=&quot;Zf_var&quot;)<br><br># Objective<br>R_recorded = [0] * (len(time_steps) + 1)<br>C_recorded = [0] * (len(time_steps) + 1)<br>P_recorded = [0] * (len(time_steps) + 1)<br>with open(f&#39;result/min_recorded_{seed}.pkl&#39;, &#39;rb&#39;) as f:<br>    min_recorded = pickle.load(f)<br>    <br>total_profit = gp.LinExpr()</pre><ol><li><strong>Setting Up Initial Inventory</strong></li></ol><pre># Initialise inventory<br>for sg in server_types:<br>    for dc in datacenters_id:<br>        for life in lifespan:<br>            model.addConstr(I[start_ts, sg, dc, life] == 0,<br>                            name=f&quot;set_up_initial_inventory_{start_ts}_{sg}_{dc}_life_{life}&quot;)</pre><p><strong>2. All actions and slot constraints</strong></p><pre>for ts in time_steps:<br>    # 0. Pricing Strategy Constraint <br>    for sg in server_types:<br>        for ls in latency_sensitivity:<br>            price_at_ts = renting_prices[(sg, ls)]<br>            e_at_ts = elasticity[(sg, ls)]<br>            D_at_ts = demand.get((ts, sg, ls), 0)<br>            demand_vars[ts, sg, ls] = get_new_demand_for_new_price(D_at_ts, price_at_ts, price_vars[ts, sg, ls], e_at_ts)<br>            model.addConstr(demand_vars[ts, sg, ls] &gt;= 0, name=f&quot;demand_constraint_{ts}_{sg}_{ls}&quot;)<br><br>    # 1. Buying constraint respecting the release window<br>    for sg in server_types:<br>        for dc in datacenters_id:<br>            # Only allow purchases during the server&#39;s release time window<br>            if (ts &gt;= release_time[sg][0]) and (ts &lt;= release_time[sg][1]):<br>                model.addConstr(I[ts, sg, dc, 1] == buy[ts, sg, dc], name=f&quot;buy_constraint_{ts}_{sg}_{dc}&quot;)<br>            else:<br>                # Prevent buying servers outside the release window<br>                model.addConstr(buy[ts, sg, dc] == 0, name=f&quot;no_buy_{ts}_{sg}_{dc}&quot;)<br>                model.addConstr(I[ts, sg, dc, 1] == 0, name=f&quot;no_buy_{ts}_{sg}_{dc}&quot;)<br><br>    # 2. Dismiss servers constraint<br>    for sg in server_types:<br>        for dc in datacenters_id:<br>            for life in range(2, life_expectancy + 1):<br>                model.addConstr(dismiss[ts, sg, dc, life] &lt;= I[ts - 1, sg, dc, life - 1], name=f&quot;dismiss_constraint_{ts}_{sg}_{dc}_life_{life}&quot;)<br>            # No dismiss servers right after buying that servers<br>            model.addConstr(dismiss[ts, sg, dc, 1] == 0, name=f&quot;no_dismiss_at_beginning_{start_ts}_{sg}_{dc}&quot;)<br><br>    # 3.1 Remove and move constraint: available resources<br>    for sg in server_types:<br>        for dc in datacenters_id:<br>            for life in range(2, life_expectancy + 1):<br>                model.addConstr(remove_from[ts, sg, dc, life] &lt;= I[ts - 1, sg, dc, life - 1] - dismiss[ts, sg, dc, life], # Dismiss before moving<br>                name = f&quot;remove_constraint_availabel_resource_{ts - 1}_{sg}_{dc}_{life}&quot;)<br>            # No remove or move servers right after buying that servers<br>            model.addConstr(remove_from[ts, sg, dc, 1] == 0, name=f&quot;no_remove_at_beginning_{start_ts}_{sg}_{dc}&quot;)<br>            model.addConstr(move_to[ts, sg, dc, 1] == 0, name=f&quot;no_move_at_beginning_{start_ts}_{sg}_{dc}&quot;)<br><br><br>    # 3.2 Balance move_to and remove_from<br>    for sg in server_types:<br>        for life in range(2, life_expectancy + 1):<br>            model.addConstr(gp.quicksum(move_to[ts, sg, dc, life] for dc in datacenters_id)  == gp.quicksum(remove_from[ts, sg, dc, life] for dc in datacenters_id),<br>                                name=f&quot;balance_move_to_remove_from_{ts}_{sg}_life_{life}&quot;)<br><br><br><br>    # 4. Update inventory after moving servers<br>    for sg in server_types:<br>            for dc in datacenters_id:<br>                for life in range(2, life_expectancy + 1):<br>                    model.addConstr(I[ts, sg, dc, life] == I[ts - 1, sg, dc, life - 1] + move_to[ts, sg, dc, life] - remove_from[ts, sg, dc, life] - dismiss[ts, sg, dc, life],<br>                            name=f&quot;update_inventory_after_all_actions_{ts}_{sg}_{dc}_life_{life}&quot;)<br><br><br><br>    # 5. Constraint: Slot capacity of each datacenter<br>    for dc in datacenters_id:<br>        model.addConstr(<br>            gp.quicksum(I[ts, sg, dc, life] * server_slots[sg] for sg in server_types for life in lifespan) &lt;= datacenter_slots[dc],<br>            name=f&quot;slot_capacity_{ts}_{dc}&quot;<br>        )<br><br><br>    # 6. Add constraint to enforce min_var[ts, sg, ls] = min(I[ts, sg, ls], demand[ts, sg, ls])<br>    for sg in server_types:<br>        for ls in latency_sensitivity:<br>            # Total inventory across all lifespans<br>            total_inventory = gp.quicksum(I[ts, sg, dc, life] for dc in datacenters_id if datacenter_latency_map[dc] == ls for life in lifespan)<br>            capacity = total_inventory * server_capacity[sg]<br>            model.addConstr(Zf_var[ts, sg, ls] == adjust_capacity_by_failure_rate(capacity), name=f&quot;custom_capacity_{ts}_{sg}_{ls}&quot;)<br>            model.addConstr(min_var[ts, sg, ls] &lt;= Zf_var.get((ts, sg, ls), 0), name=f&quot;min_capacity_{ts}_{sg}_{ls}&quot;)<br>            model.addConstr(min_var[ts, sg, ls] &lt;= demand_vars[ts, sg, ls], name=f&quot;min_demand_{ts}_{sg}_{ls}&quot;)<br>            <br>            # Use the recorded min capacity in part 1<br>            model.addConstr(min_var[ts, sg, ls] == min_recorded[ts, sg, ls], name=f&quot;min_recorded_capacity_{ts}_{sg}_{ls}&quot;)}_{dc}&quot;)</pre><h3>Objective</h3><p>The goal of this optimization problem is to maximize the total profit over 168 time steps. The profit at each time step is calculated by taking the revenue generated from renting servers and subtracting the total costs, which include buying costs, energy consumption, maintenance, and moving costs. Below, we break down the key components involved in this calculation.</p><h4>Objective function</h4><p>The primary objective is to maximize the total profit over all time steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pz943bLsGCvTr8cdJz79KA.png" /></figure><h4>Revenue at Time Step ts</h4><p>The revenue at a given time step is calculated as the sum of the rented servers across different server generations and latency sensitivities, multiplied by their respective renting prices. Now, our decision variables is not the min_var as part 1, they are price_var, and min_var now becomes parameter min_recorded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KHGbYxXc6NrkvbQ2u0qyZg.png" /></figure><h4>Buying Cost at Time Step ts</h4><p>The buying cost reflects the cost of purchasing new servers at each time step. It is calculated by summing the purchase cost for each server generation across all data centers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtWltNguzGSFE1IQ61HXIA.png" /></figure><h4>Energy Cost at Time Step ts</h4><p>The energy cost reflects the power consumption of servers based on their generation and data center location. It is calculated by summing the energy prices for each server generation at each data center, multiplied by the number of active servers at their respective life stages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ch9LuvoUOeBAo_Irc-6-FA.png" /></figure><h4>Maintenance Cost at Time Step ts</h4><p>Maintenance costs depend on the server’s generation and lifespan. First we have a function to calculate the maintenance cost as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wt6GDh_F4STNFxYzrHN3g.png" /></figure><pre>def get_maintenance_cost(b, x=1, xhat=96):<br>    # CALCULATE THE CURRENT MAINTENANCE COST<br>    return int(b * (1 + (((1.5)*(x))/xhat * np.log2(((1.5)*(x))/xhat))))</pre><p>The cost is derived by applying the maintenance cost function for each server and multiplying it by the number of servers in use at that time step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7QsC8L20pYn8PTEdHmDSww.png" /></figure><h4>Moving Cost at Time Step ts</h4><p>The moving cost occurs when servers are relocated between data centers. It is calculated by multiplying a fixed moving cost by the number of servers moved during the time step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xnhVGeQwOQOnlrUcTu1UA.png" /></figure><h4>Total Cost at Time Step ts</h4><p>The total cost at each time step is the sum of all incurred costs, including buying, energy, maintenance, and moving costs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oC2m2hcOayfuIh5QNrC3uw.png" /></figure><h4>Profit at Time Step ts</h4><p>The profit for each time step is calculated by subtracting the total cost from the revenue at that time step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1jOiUKc2dzuH0Qj358OEA.png" /></figure><p>Now, let’s look at the code for the objective.</p><pre>for ts in time_steps:<br>    # Revenue at time step ts<br>    revenue_ts = gp.quicksum(<br>        min_recorded[ts, sg, ls] * price_vars[ts, sg, ls]<br>        for sg in server_types for ls in latency_sensitivity<br>    )<br><br>    R_recorded[ts] = revenue_ts<br><br>    # Cost at time step ts<br>    buy_cost_ts = gp.quicksum(purchase_cost[sg] * buy[ts, sg, dc] for sg in server_types for dc in datacenters_id)<br>    energy_cost_ts = gp.quicksum(energy_prices[sg, dc] * gp.quicksum(I[ts, sg, dc, life] for life in lifespan) for sg in server_types for dc in datacenters_id)<br><br>    # Maintenance cost at time step ts:<br><br>    maintenance_cost_ts = gp.quicksum(<br>        get_maintenance_cost(maintain_cost[sg], life) * I[ts, sg, dc, life]<br>        for sg in server_types for dc in datacenters_id for life in lifespan<br>    )<br><br>    moving_cost_ts = moving_cost * gp.quicksum(move_to[ts, sg, dc, life] for life in range(2, life_expectancy + 1) for sg in server_types for dc in datacenters_id)<br><br><br>    # Total cost at time step ts<br>    total_cost_ts = buy_cost_ts + energy_cost_ts + maintenance_cost_ts + moving_cost_ts<br>    C_recorded[ts] = total_cost_ts<br><br>    # Profit at time step t<br>    profit_ts = revenue_ts - total_cost_ts<br>    P_recorded[ts] = profit_ts<br><br>    # Accumulate the profit<br>    total_profit += profit_ts</pre><pre>model.setObjective(total_profit, GRB.MAXIMIZE)<br>model.update()</pre><p>We can configure certain parameters in Gurobi to improve speed and performance.</p><pre># Gurobi optimization settings to improve speed and performance<br>opt = {<br>    &quot;Presolve&quot;: 2,       # Aggressive presolve<br>    &quot;PreSparsify&quot;: 2,    # Remove redundant constraints<br>    &quot;Aggregate&quot;: 2,      # Aggressive aggregation<br>    &quot;OutputFlag&quot;: 1,     # Enable output to track progress<br>}<br><br># Set model parameters<br>model.setParam(&#39;Presolve&#39;, opt[&quot;Presolve&quot;])<br>model.setParam(&#39;PreSparsify&#39;, opt[&quot;PreSparsify&quot;])<br>model.setParam(&#39;Aggregate&#39;, opt[&quot;Aggregate&quot;])<br>model.setParam(&#39;OutputFlag&#39;, opt[&quot;OutputFlag&quot;])</pre><p>We can now tell Gurobi that the model is complete and it can solve the problem.</p><pre># Optimize model<br>model.optimize()<br><br>rich.print(f&quot;Profit: {total_profit.getValue():0,.2f}&quot;)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZjiHCqtyMGXs2w_JU_zAHA.png" /><figcaption><strong>After applying price strategy</strong></figcaption></figure><p>Before applying price strategy, this is the output in the first stage of optimisation problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kCndO1_9QcDDbUCE7GSpdg.png" /><figcaption><strong>Before applying price strategy</strong></figcaption></figure><p><strong>Note</strong>: The running time depends on the machine you use to run the optimisation.</p><p>Now, this means that our pricing strategy has increased profit by approximately <strong>230,000,000</strong>. How about the utilisation of each pair of server generation and latency sensitivity? Have they improved or not? Let’s observe the results in the next section.</p><h3>Post Processing</h3><p>After completing the optimisation, the next step is to analyse and interpret the results. In this phase, we will save key outputs, including all actions, server utilization, and business metrics such as revenue, cost, and profit. This data provides crucial insights into how the system performed during the optimisation process.</p><p>Once the data is saved, we will visualise both the <strong>Utilization</strong> of server resources and the <strong>Business Metrics</strong> (revenue, cost, and profit). These visualisations will allow us to better understand the efficiency of the optimization and assess its impact on the business.</p><h4>Visualise Utilisation Comparison</h4><p>We will now in turn look at each server generation to see how they have improved after the pricing strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_CBRAPzLTyEWPk7XYw3Dw.jpeg" /><figcaption>CPU.S1 — all latency sensitivity</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q_9fyNtsl915i3tHQGGYFA.jpeg" /><figcaption>CPU.S2 — all latency sensitivity</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D9HARUwI96FcJvJPdei0Cg.jpeg" /><figcaption>CPU.S3 — all latency sensitivity</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XPK7DEUJNYWFBrsYA3h8cw.jpeg" /><figcaption>CPU.S4 — all latency sensitivity</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eHShpkCftwq5UL7ai-DHOA.jpeg" /><figcaption>GPU.S1 — all latency sensitivity</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YQ06UYrNjwl7EQpRX-J8-g.jpeg" /><figcaption>GPU.S2— all latency sensitivity</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cPDMjh1GK3RG4dDZORIPLA.jpeg" /><figcaption>GPU.S3 — all latency sensitivity</figcaption></figure><h4>Visualise Business Metric Comparison</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R-uO8twGb2KxO5fwVrCRWA.jpeg" /></figure><h3>Conclusion</h3><p>The pricing strategy has positively impacted both utilization and profit. However, there is still room for improvement in our optimization models. For instance, there are time steps where capacity exceeds demand, resulting in wasted costs, and times when demand exceeds capacity, indicating opportunities to raise prices to reduce demand. While manual backtesting is possible, we should explore alternative approaches, such as introducing additional actions, to further enhance the optimization model.</p><h4>Source code</h4><p>You can find the entire notebook with the code developed for this article in the link to my GitHub repository below.</p><p><a href="https://github.com/Tayerquach/data_center_operations/blob/master/data_center_operation_part2.ipynb">data_center_operations/data_center_operation_part2.ipynb at master · Tayerquach/data_center_operations</a></p><p>I sincerely hope you found this article useful and entertaining. If so, I’d love to hear your thoughts! And if you’re interested in staying updated on my latest articles, consider following me on Medium. Your support and feedback are what drive me to keep exploring and sharing in this fascinating field. Thank you for taking the time to read, and stay tuned for more insights in my next article!</p><h4>References</h4><ul><li><a href="https://medium.com/@quachmaiboi/optimizing-data-center-operation-part-1-8c21cf4f9378">Optimizing data center operation — Part 1</a></li><li><a href="https://www.gurobi.com/jupyter_models/">Jupyter Models Archive - Gurobi Optimization</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b42f0c4a934" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing data center operation — Part 1]]></title>
            <link>https://medium.com/@quachmaiboi/optimizing-data-center-operation-part-1-8c21cf4f9378?source=rss-2a9bdb49c93f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c21cf4f9378</guid>
            <category><![CDATA[solver]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[linear-programming]]></category>
            <category><![CDATA[data-center-services]]></category>
            <category><![CDATA[data-center-management]]></category>
            <dc:creator><![CDATA[Boi Mai Quach]]></dc:creator>
            <pubDate>Mon, 30 Sep 2024 10:44:07 GMT</pubDate>
            <atom:updated>2024-12-07T23:58:39.146Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Optimizing data center operation — Part 1</strong></h3><h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TuT_VSZs6hE1b9cU" /><figcaption>Photo by <a href="https://unsplash.com/@imgix?utm_source=medium&amp;utm_medium=referral">imgix</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Data centers play a critical role in the infrastructure of any modern cloud business. As they grow in complexity, optimizing operations becomes a key concern to ensure efficiency, reduce costs, and manage resources. In this article, we’ll explore a method for optimizing data center operations using <strong>Linear Programming</strong>, and provide a step-by-step guide on how we can implement similar strategies.</p><blockquote>For readers who are encountering this series for the first time, my purpose is to share my passion for mathematics to inspire people of all backgrounds. My code will be published on <a href="https://github.com/Tayerquach/data_center_operations/tree/master">my GitHub</a>.</blockquote><p><a href="https://github.com/Tayerquach/data_center_operations/tree/master">GitHub - Tayerquach/data_center_operations</a></p><p><em>✨Please give me a 👏 if you are interested in my sharing, leave a comment 💬 to share your views/thoughts. ✨</em></p><h3>Solver Introduction</h3><p>Optimization problems are central to many fields, from economics and operations research to engineering and machine learning. These problems involve finding the best solution from a set of feasible options, typically aiming to minimize or maximize an objective function, such as cost or profit. The challenge is that real-world problems often come with a variety of constraints, making them complex to solve manually. This is where <strong>optimization solvers</strong> come in.</p><p>Solvers are specialized software tools designed to find optimal or near-optimal solutions to mathematical problems efficiently. They use algorithms such as linear programming (<strong>LP</strong>), mixed-integer programming (<strong>MIP</strong>), and constraint programming (<strong>CP</strong>) to tackle different types of optimization problems. Some popular solvers include <strong>CP solvers</strong>, <strong>CPLEX</strong>, <strong>Gurobi</strong>, <strong>Pymoo</strong>, <strong>Z3,</strong> or <strong>custom solvers</strong>, each offering a variety of capabilities to address problems ranging from small-scale linear problems to highly complex, large-scale optimization issues.</p><blockquote><em>✨ </em>I have a series on solving <a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-1-f0f481e686e">Jane Street’s Puzzles using <strong>Z3 optimisers</strong></a>. I hope the materials in this series will help us practice using the solver <em>🎁.✨</em></blockquote><p>In this article, we use <strong>Gurobi </strong>to solve the optimisation. <strong>Gurobi</strong> is one of the most powerful and widely-used solvers for solving mathematical optimization problems. It is highly efficient for linear programming (LP), mixed-integer programming (MIP), quadratic programming (QP), and various other optimization models. For more information about Gurobi, please refer to <a href="https://www.gurobi.com/">https://www.gurobi.com/</a></p><p><strong>Note</strong>: The optimization problem presented below requires substantial computational resources to run efficiently. To ensure you have access to the necessary capabilities, I recommend downloading the <a href="https://www.gurobi.com/academia/academic-program-and-licenses/"><strong>Gurobi Academic WLS License</strong></a> if you’re affiliated with an academic institution. Gurobi provides this license for free to academic users, offering full access to their high-performance optimization solver.</p><p>However, you can use any solver to solve this problem once you understand the strategies we’ve outlined.</p><h3>Problem Overview</h3><p>Now, back in our problem. Imagine you are managing a network of data centers (DCs). These data centers host servers of various generations (SG), each with a certain lifespan. Each data center can contain two types of servers: CPU servers and GPU servers. Your job is to maximize profit while deciding when to buy new ones, when to move or remove them between data centers, and when to dismiss servers that have reached the end of their useful life. All of these actions must be balanced with the goal of meeting demand while respecting physical space constraints in the data centers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VMfcn6_4QQtIpIkuplE5Aw.jpeg" /><figcaption>Source: <a href="https://github.com/Tayerquach/data_center_operations/tree/master/photo">https://github.com/Tayerquach/data_center_operations/tree/master/photo</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*3iOGBABxdwGa1UkcMFCe7Q.jpeg" /><figcaption>Source: <a href="https://github.com/Tayerquach/data_center_operations/tree/master/photo">https://github.com/Tayerquach/data_center_operations/tree/master/photo</a></figcaption></figure><p>In this article, we will model this decision-making problem using <strong>mathematical optimization</strong>. The first part of the article explores the dataset, which includes demand at each time step, data center capacity, selling prices for different server generations, and server specifications.</p><p>The second part of the article introduces the three components of a mathematical optimization model: the <strong>objective function</strong>, the <strong>decision variables</strong>, and the <strong>constraints</strong>. In our data center operation problem, the objective is to maximize overall profit. The decision variables represent the actions (buy, move, hold, dismiss) applied to a certain number of servers. The constraints ensure basic requirements are met, such as conducting four actions respecting the capacity limits of each data center. By determining the optimal actions at each of the 168 time steps, the model will recommend how many servers of each type should be deployed in each data center to <strong>maximize profit</strong>.</p><p>Let’s get started.</p><h3>Data Exploration</h3><p>In order to effectively solve the challenges of data center operations, it’s essential to have a clear understanding of the data involved. This section provides an overview of the critical data points that will be analyzed. The data includes market demand for renting servers, as well as the resources available to the business, such as the number of servers and the capacity of data centers. By exploring these data sets, we can better understand the operational landscape and make informed decisions for optimizing resource usage.</p><h4>1. Data center information</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jz2SItyPgzY-OybB1VtHg.jpeg" /></figure><pre>datacenters = pd.read_csv(&#39;https://github.com/Tayerquach/data_center_operations/blob/master/data/datacenters.csv?raw=true&#39;)<br>datacenters</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V65l1lhVVavUqhV0hG4gEA.jpeg" /></figure><p><strong>Insights:</strong></p><p>- Each server will have a specific <strong>latency sensitivity</strong> (high, medium, low) depending on the data center in which it is placed.</p><p>- Datacenters exhibit varying levels of latency sensitivity. A <strong>higher latency sensitivity</strong> typically correlates with <strong>higher energy costs</strong>.</p><p>- Datacenters with <strong>lower latency</strong> tend to have a <strong>higher slot capacity</strong>.</p><h4>2. Server Information</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FfnbmwzAFgr3_X4mooLv8A.jpeg" /></figure><pre>servers = pd.read_csv(&#39;https://github.com/Tayerquach/data_center_operations/blob/master/data/servers.csv?raw=true&#39;)<br>servers</pre><p>In order to get insights from servers dataframe, we will visualise its attributes as follows.</p><p><strong>2. 1. Purchase Price and Energy Consumption by Server Generation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pYyRjWebjMUawPlSnyU-xA.jpeg" /></figure><p><strong>Purchase Price by Server Generation</strong></p><p>- <strong>GPU</strong> servers are significantly more expensive than <strong>CPU</strong> servers, with the price increasing for each generation of GPU and CPU servers.</p><p>- <strong>CPU.S4</strong> is the <strong>most expensive</strong> among the CPU servers, while <strong>GPU.S3</strong> is the highest-priced GPU server.</p><p><strong>Energy Consumption by Server Generation</strong></p><p>- GPU servers consume significantly more energy than CPU servers</p><p>- GPU servers consume far more energy, particularly <strong>GPU.S3</strong>, which consumes the most energy among all server types.</p><h4>3. Demand Information</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5kf5AJM7rkce3VTV8a3d6w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*5e4u0xyxhNkKWVFU1qq0nQ.jpeg" /></figure><p><strong>Insights:</strong></p><ul><li><strong>Shift to Newer Generations</strong>: Across all latency levels, demand moves from servers (S1, S2) to newer ones (S3, S4) over time. Servers S1 and S2 can be considered older generations, while S3 and S4 represent the newest technologies. This transition reflects the growing need for more advanced server capabilities as operational demands increase.</li><li><strong>Increasing GPU Demand</strong>: Demand for newer GPU servers (especially S3) grows steadily, highlighting the rising importance of GPUs in modern workloads.</li><li><strong>Decrease in Demand Across Latency Sensitivity Levels</strong>: The demand gradually decreases from low latency sensitivity to high latency sensitivity over time. This could be because of the higher selling price for the servers with higher latency sensitivity.</li></ul><h3>Problem Formulation</h3><p>Let’s define our notations for the Mathematical Optimisation model.</p><p>First, let’s define the following sets:</p><p><strong>Sets</strong></p><ul><li><strong>DC</strong>: Set of data center IDs</li><li><strong>T</strong>: Set of timesteps</li><li><strong>LS</strong>: Latency sensitivity types</li><li><strong>SG</strong>: Server generations</li><li><strong>Lifespan: </strong>Set of life ages for each servers (from 1 to life expectancy).</li></ul><p><strong>Parameters</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cHJT2SSoabCU86AZmW6YiQ.jpeg" /></figure><h3>Decision Variables</h3><p>First, we define four actions as our decision variables: the number of servers bought, moved, removed, and dismissed. The ‘Hold’ action is automatically applied if no dismissal action is taken for a given server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DThraugtOfEGVXzjRYBtYw.jpeg" /></figure><p>Another variable is the inventory of servers at each datacenter and is updated at the end of the time-step after all actions are applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZsWsA46jZ957rjwme-BqIw.jpeg" /></figure><p>With these initial decision variables, we can start the Mathematical Operation model.</p><p>First of all, initialise the model</p><pre>model = gp.Model(&quot;Data_center_operation&quot;, env = env)<br>model.setParam(&#39;Seed&#39;, seed)</pre><pre># Decision variables<br><br># Buy action<br>buy = model.addVars(time_steps, server_types, datacenters_id, lb = 0, vtype=GRB.CONTINUOUS, name=&quot;buy&quot;)  # Number of servers bought<br><br># Move action<br>move_to = model.addVars(time_steps, server_types, datacenters_id, lifespan, lb = 0, vtype=GRB.CONTINUOUS, name=&quot;move_to&quot;)  # Number of servers moved<br>remove_from = model.addVars(time_steps, server_types, datacenters_id, lifespan, lb = 0, vtype=GRB.CONTINUOUS, name=&quot;remove_from&quot;)  # Number of servers moved<br><br>#Dismissing servers<br>dismiss = model.addVars(time_steps, server_types, datacenters_id, lifespan, lb = 0, vtype=GRB.CONTINUOUS, name=&quot;dismiss&quot;)  # Number of servers moved<br><br># Decision variables to track server lifespan in inventory<br>I = model.addVars(range(start_ts, end_ts + 1), server_types, datacenters_id, lifespan, lb = 0, vtype=GRB.CONTINUOUS, name=&quot;inventory&quot;) #  Inventory begins before time step = 1</pre><h3>Constraints</h3><ol><li><strong>Setting Up Initial Inventory:</strong></li></ol><p>At the beginning of the planning period, no servers are in place. The initial inventory for each server generation, data center, and lifespan stage is set to zero. This is represented mathematically as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s17qitf4_puPRjnKHrWv8w.png" /></figure><p><strong>2. Buying servers</strong></p><p>At each time step, you may need to buy new servers. When you buy a server, it starts with a “life” value of 1, meaning it is newly deployed. However, servers can only be bought when their generation is released. This is controlled by a condition that checks whether the current time step matches the release time of a specific server generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukmIzkCXEw2K1KFCrDBX0w.png" /></figure><p><strong>3. Dismiss servers</strong></p><p>The term “Dismiss” can be understood in two ways:</p><ul><li><strong>Dismiss (lifespan &gt; life expectancy)</strong>: This refers to decommissioning a server once it exceeds its expected lifespan.</li><li><strong>Dismiss (stop using at a time period)</strong>: This refers to halting the use of a server during a specific time period, even if it hasn’t reached the end of its life expectancy.</li></ul><p>Dismissal occurs first in the decision process, and only servers that are already in the inventory from a previous time step can be dismissed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CSnxiEC1UzC71asLTupYgg.png" /></figure><p>For servers in their first life stage, dismiss action is not allowed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7qHqfm9hWh1cIC6BFG00A.png" /></figure><p><strong>4. Move action</strong></p><p>To effectively solve a “move” action, it can be broken down into two sub-actions to efficiently handle the logistics of moving resources.</p><ul><li><strong>Move to</strong>: This refers to relocating a certain number of servers from one data center to another.</li><li><strong>Remove to</strong>: This refers to removing a certain number of servers from their current data center in preparation for the move.</li></ul><p>After dismissal, you can decide to move servers between data centers or remove them altogether. However, you can only remove or move servers that have already existed in the previous time step</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*lQWoUBDWrDNB1II4BrNF9g.jpeg" /></figure><p>Servers in their first life stage cannot be moved or removed. This is because we cannot purchase a server, place it in one data center, and then immediately move it to another. Such a process would not be logical or appropriate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3T4SG2H4lZTtrAMRVxHGGw.png" /></figure><p>To ensure no servers are lost during moves, the total number of servers moved into a data center must equal the number moved out at the same time step with same lifespan and server generation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*3ew_wmCk2Wtlua_8cX9uWQ.jpeg" /></figure><p><strong>5. Updating Inventory</strong></p><p>Once you’ve handled dismissal, moving, and removing servers, you update the inventory for the next time step. The new inventory consists of the servers left from the previous period, plus those moved in, minus those removed and dismissed. This ensures that the server count is updated properly as they age.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TXu3yNjVlivdl9Ios-3Jvg.jpeg" /></figure><p><strong>6. Slot capacity constraints</strong></p><p>Each data center has a limited number of physical slots that can hold servers. You must ensure that the total number of server slots used in each data center doesn’t exceed its capacity. This includes all servers from different generations and lifespans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-VhT9pAR6M6oqi-83Jo0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DsyhcMohQYYBM3PilCx84g.png" /></figure><p><strong>7. Meeting Demand with available capacity</strong></p><p>We try to meet demand with this available capacity, which is modeled using a variable <strong>min_var</strong> that represents the minimum of the available capacity and the demand:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VHTEH23XaaBAMHXjAJir3w.png" /></figure><p>Now, let’s look at the code for these constraints.</p><pre># Auxiliary variable for min(I, demand)<br>min_var = model.addVars(time_steps, server_types, latency_sensitivity, vtype=GRB.CONTINUOUS,lb = 0, name=&quot;min_var&quot;)<br>Zf_var = model.addVars(time_steps, server_types, latency_sensitivity, vtype=GRB.CONTINUOUS,lb = 0, name=&quot;Zf_var&quot;)</pre><ol><li><strong>Setting Up Initial Inventory</strong></li></ol><pre># Initialise inventory<br>for sg in server_types:<br>    for dc in datacenters_id:<br>        for life in lifespan:<br>            model.addConstr(I[start_ts, sg, dc, life] == 0,<br>                            name=f&quot;set_up_initial_inventory_{start_ts}_{sg}_{dc}_life_{life}&quot;)</pre><p><strong>2. All actions and slot constraints</strong></p><pre>for ts in time_steps:<br>    # 1. Buying constraint respecting the release window<br>    for sg in server_types:<br>        for dc in datacenters_id:<br>            # Only allow purchases during the server&#39;s release time window<br>            if (ts &gt;= release_time[sg][0]) and (ts &lt;= release_time[sg][1]):<br>                model.addConstr(I[ts, sg, dc, 1] == buy[ts, sg, dc], name=f&quot;buy_constraint_{ts}_{sg}_{dc}&quot;)<br>            else:<br>                # Prevent buying servers outside the release window<br>                model.addConstr(buy[ts, sg, dc] == 0, name=f&quot;no_buy_{ts}_{sg}_{dc}&quot;)<br>                model.addConstr(I[ts, sg, dc, 1] == 0, name=f&quot;no_buy_{ts}_{sg}_{dc}&quot;)<br><br>    # 2. Dismiss servers constraint<br>    for sg in server_types:<br>        for dc in datacenters_id:<br>            for life in range(2, life_expectancy + 1):<br>                model.addConstr(dismiss[ts, sg, dc, life] &lt;= I[ts - 1, sg, dc, life - 1], name=f&quot;dismiss_constraint_{ts}_{sg}_{dc}_life_{life}&quot;)<br>            # No dismiss servers right after buying that servers<br>            model.addConstr(dismiss[ts, sg, dc, 1] == 0, name=f&quot;no_dismiss_at_beginning_{start_ts}_{sg}_{dc}&quot;)<br><br>    # 3.1 Remove and move constraint: available resources<br>    for sg in server_types:<br>        for dc in datacenters_id:<br>            for life in range(2, life_expectancy + 1):<br>                model.addConstr(remove_from[ts, sg, dc, life] &lt;= I[ts - 1, sg, dc, life - 1] - dismiss[ts, sg, dc, life], # Dismiss before moving<br>                name = f&quot;remove_constraint_availabel_resource_{ts - 1}_{sg}_{dc}_{life}&quot;)<br>            # No remove or move servers right after buying that servers<br>            model.addConstr(remove_from[ts, sg, dc, 1] == 0, name=f&quot;no_remove_at_beginning_{start_ts}_{sg}_{dc}&quot;)<br>            model.addConstr(move_to[ts, sg, dc, 1] == 0, name=f&quot;no_move_at_beginning_{start_ts}_{sg}_{dc}&quot;)<br><br><br>    # 3.2 Balance move_to and remove_from<br>    for sg in server_types:<br>        for life in range(2, life_expectancy + 1):<br>            model.addConstr(gp.quicksum(move_to[ts, sg, dc, life] for dc in datacenters_id)  == gp.quicksum(remove_from[ts, sg, dc, life] for dc in datacenters_id),<br>                                name=f&quot;balance_move_to_remove_from_{ts}_{sg}_life_{life}&quot;)<br><br><br><br>    # 4. Update inventory after moving servers<br>    for sg in server_types:<br>            for dc in datacenters_id:<br>                for life in range(2, life_expectancy + 1):<br>                    model.addConstr(I[ts, sg, dc, life] == I[ts - 1, sg, dc, life - 1] + move_to[ts, sg, dc, life] - remove_from[ts, sg, dc, life] - dismiss[ts, sg, dc, life],<br>                            name=f&quot;update_inventory_after_all_actions_{ts}_{sg}_{dc}_life_{life}&quot;)<br><br><br><br>    # 5. Constraint: Slot capacity of each datacenter<br>    for dc in datacenters_id:<br>        model.addConstr(<br>            gp.quicksum(I[ts, sg, dc, life] * server_slots[sg] for sg in server_types for life in lifespan) &lt;= datacenter_slots[dc],<br>            name=f&quot;slot_capacity_{ts}_{dc}&quot;<br>        )<br><br><br>    # 6. Add constraint to enforce min_var[ts, sg, ls] = min(I[ts, sg, ls], demand[ts, sg, ls])<br>    for sg in server_types:<br>        for ls in latency_sensitivity:<br>            # Total inventory across all lifespans<br>            total_inventory = gp.quicksum(I[ts, sg, dc, life] for dc in datacenters_id if datacenter_latency_map[dc] == ls for life in lifespan)<br>            capacity = total_inventory * server_capacity[sg]<br>            model.addConstr(Zf_var[ts, sg, ls] == adjust_capacity_by_failure_rate(capacity), name=f&quot;custom_capacity_{ts}_{sg}_{ls}&quot;)<br>            model.addConstr(min_var[ts, sg, ls] &lt;= Zf_var.get((ts, sg, ls), 0), name=f&quot;min_capacity_{ts}_{sg}_{ls}&quot;)<br>            model.addConstr(min_var[ts, sg, ls] &lt;= demand.get((ts, sg, ls), 0), name=f&quot;min_demand_{ts}_{sg}_{ls}&quot;)</pre><h3>Objective</h3><p>The goal of this optimization problem is to maximize the total profit over 168 time steps. The profit at each time step is calculated by taking the revenue generated from renting servers and subtracting the total costs, which include buying costs, energy consumption, maintenance, and moving costs. Below, we break down the key components involved in this calculation.</p><h4><strong>Objective function</strong></h4><p>The primary objective is to maximize the total profit over all time steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pz943bLsGCvTr8cdJz79KA.png" /></figure><h4>Revenue at Time Step ts</h4><p>The revenue at a given time step is calculated as the sum of the rented servers across different server generations and latency sensitivities, multiplied by their respective renting prices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FyjJVGV_x9JTMJnOjdq9sQ.png" /></figure><h4>Buying Cost at Time Step ts</h4><p>The buying cost reflects the cost of purchasing new servers at each time step. It is calculated by summing the purchase cost for each server generation across all data centers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtWltNguzGSFE1IQ61HXIA.png" /></figure><h4>Energy Cost at Time Step ts</h4><p>The energy cost reflects the power consumption of servers based on their generation and data center location. It is calculated by summing the energy prices for each server generation at each data center, multiplied by the number of active servers at their respective life stages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ch9LuvoUOeBAo_Irc-6-FA.png" /></figure><h4>Maintenance Cost at Time Step ts</h4><p>Maintenance costs depend on the server’s generation and lifespan. First we have a function to calculate the maintenance cost as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wt6GDh_F4STNFxYzrHN3g.png" /></figure><pre>def get_maintenance_cost(b, x=1, xhat=96):<br>    # CALCULATE THE CURRENT MAINTENANCE COST<br>    return int(b * (1 + (((1.5)*(x))/xhat * np.log2(((1.5)*(x))/xhat))))</pre><p>The cost is derived by applying the maintenance cost function for each server and multiplying it by the number of servers in use at that time step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7QsC8L20pYn8PTEdHmDSww.png" /></figure><h4>Moving Cost at Time Step ts</h4><p>The moving cost occurs when servers are relocated between data centers. It is calculated by multiplying a fixed moving cost by the number of servers moved during the time step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xnhVGeQwOQOnlrUcTu1UA.png" /></figure><h4>Total Cost at Time Step ts</h4><p>The total cost at each time step is the sum of all incurred costs, including buying, energy, maintenance, and moving costs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oC2m2hcOayfuIh5QNrC3uw.png" /></figure><h4>Profit at Time Step ts</h4><p>The profit for each time step is calculated by subtracting the total cost from the revenue at that time step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1jOiUKc2dzuH0Qj358OEA.png" /></figure><p>Now, let’s look at the code for the objective.</p><pre>for ts in time_steps:<br>  # Revenue at time step ts<br>  revenue_ts = gp.quicksum(<br>      min_var[ts, sg, ls] * renting_prices.get((sg, ls), 0)<br>      for sg in server_types for ls in latency_sensitivity<br>  )<br><br>  R_recorded[ts] = revenue_ts<br><br>  # Cost at time step ts<br>  buy_cost_ts = gp.quicksum(purchase_cost[sg] * buy[ts, sg, dc] for sg in server_types for dc in datacenters_id)<br>  energy_cost_ts = gp.quicksum(energy_prices[sg, dc] * gp.quicksum(I[ts, sg, dc, life] for life in lifespan) for sg in server_types for dc in datacenters_id)<br><br>  # Maintenance cost at time step ts:<br><br>  maintenance_cost_ts = gp.quicksum(<br>      get_maintenance_cost(maintain_cost[sg], life) * I[ts, sg, dc, life]<br>      for sg in server_types for dc in datacenters_id for life in lifespan<br>  )<br><br>  moving_cost_ts = moving_cost * gp.quicksum(move_to[ts, sg, dc, life] for life in range(2, life_expectancy + 1) for sg in server_types for dc in datacenters_id)<br><br><br>  # Total cost at time step ts<br>  total_cost_ts = buy_cost_ts + energy_cost_ts + maintenance_cost_ts + moving_cost_ts<br>  C_recorded[ts] = total_cost_ts<br><br>  # Profit at time step t<br>  profit_ts = revenue_ts - total_cost_ts<br>  P_recorded[ts] = profit_ts<br><br>  # Accumulate the profit<br>  total_profit += profit_ts</pre><pre>model.setObjective(total_profit, GRB.MAXIMIZE)<br>model.update()</pre><p>We can configure certain parameters in Gurobi to improve speed and performance.</p><pre># Gurobi optimization settings to improve speed and performance<br>opt = {<br>    &quot;Presolve&quot;: 2,       # Aggressive presolve<br>    &quot;PreSparsify&quot;: 2,    # Remove redundant constraints<br>    &quot;Aggregate&quot;: 2,      # Aggressive aggregation<br>    &quot;OutputFlag&quot;: 1,     # Enable output to track progress<br>}<br><br># Set model parameters<br>model.setParam(&#39;Presolve&#39;, opt[&quot;Presolve&quot;])<br>model.setParam(&#39;PreSparsify&#39;, opt[&quot;PreSparsify&quot;])<br>model.setParam(&#39;Aggregate&#39;, opt[&quot;Aggregate&quot;])<br>model.setParam(&#39;OutputFlag&#39;, opt[&quot;OutputFlag&quot;])</pre><p>We can now tell Gurobi that the model is complete and it can solve the problem.</p><pre># Optimize model<br>model.optimize()<br><br>rich.print(f&quot;Profit: {total_profit.getValue():0,.2f}&quot;)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kCndO1_9QcDDbUCE7GSpdg.png" /><figcaption>seed = 2381</figcaption></figure><p><strong>Note</strong>: The running time depends on the machine you use to run the optimisation.</p><h3>Post Processing</h3><p>After completing the optimisation, the next step is to analyse and interpret the results. In this phase, we will save key outputs, including all actions, server utilization, and business metrics such as revenue, cost, and profit. This data provides crucial insights into how the system performed during the optimisation process.</p><p>Once the data is saved, we will visualise both the <strong>Utilization</strong> of server resources and the <strong>Business Metrics</strong> (revenue, cost, and profit). These visualisations will allow us to better understand the efficiency of the optimization and assess its impact on the business.</p><p>Now, running code to generate necessary dataframes.</p><pre>action_dict = {<br>        &#39;server_generation&#39;: [],<br>        &#39;datacenter_id&#39;: [],<br>        &#39;time_step&#39;: [],<br>        &#39;lifespan&#39;: [],<br>        &#39;buying_servers&#39;: [],<br>        &#39;remove&#39;: [],<br>        &#39;move_to&#39;: [],<br>        &#39;dismiss&#39;: []<br>    }<br><br>utilisation_dict = {<br>    &#39;server_generation&#39;: [],<br>    &#39;latency_sensitivity&#39;: [],<br>    &#39;time_step&#39;: [],<br>    &#39;capacity&#39;: [],<br>    &#39;demand&#39;: [],<br>}<br><br>business_metric_dict = {<br>    &#39;time_step&#39;: [],<br>    &#39;revenue&#39;: [],<br>    &#39;cost&#39;: [],<br>    &#39;profit&#39;: []<br>}<br><br>if model.status == GRB.OPTIMAL:<br>    for ts in tqdm(time_steps):<br>        business_metric_dict[&#39;time_step&#39;].append(ts)<br>        revenue_at_ts = float(R_recorded[ts].getValue())<br>        cost_at_ts = float(C_recorded[ts].getValue())<br>        profit_at_ts = float(P_recorded[ts].getValue())<br><br>        business_metric_dict[&#39;revenue&#39;].append(revenue_at_ts)<br>        business_metric_dict[&#39;cost&#39;].append(cost_at_ts)<br>        business_metric_dict[&#39;profit&#39;].append(profit_at_ts)<br><br>        # Buying servers<br>        for sg in server_types:<br>            for dc in datacenters_id:<br>                bought_qty = buy[ts, sg, dc].x<br>                action_dict[&#39;server_generation&#39;].append(sg)<br>                action_dict[&#39;datacenter_id&#39;].append(dc)<br>                action_dict[&#39;time_step&#39;].append(ts)<br>                action_dict[&#39;lifespan&#39;].append(1)<br>                action_dict[&#39;buying_servers&#39;].append(bought_qty)<br>                action_dict[&#39;remove&#39;].append(0)<br>                action_dict[&#39;move_to&#39;].append(0)<br>                action_dict[&#39;dismiss&#39;].append(0)<br>            for ls in latency_sensitivity:<br>                capacity = Zf_var[ts, sg, ls].x<br>                demand_ts = demand.get((ts, sg, ls), 0)<br>                utilisation_dict[&#39;server_generation&#39;].append(sg)<br>                utilisation_dict[&#39;latency_sensitivity&#39;].append(ls)<br>                utilisation_dict[&#39;time_step&#39;].append(ts)<br>                utilisation_dict[&#39;capacity&#39;].append(capacity)<br>                utilisation_dict[&#39;demand&#39;].append(demand_ts)<br><br><br>        # Moving and dismissing servers<br>        for sg in server_types:<br>            for dc in datacenters_id:<br>                for life in range(2, life_expectancy + 1):<br>                    remove_qty = remove_from[ts, sg, dc, life].x<br>                    moveto_qty = move_to[ts, sg, dc, life].x<br>                    dismiss_qty = dismiss[ts, sg, dc, life].x<br><br>                    action_dict[&#39;server_generation&#39;].append(sg)<br>                    action_dict[&#39;datacenter_id&#39;].append(dc)<br>                    action_dict[&#39;time_step&#39;].append(ts)<br>                    action_dict[&#39;lifespan&#39;].append(life)<br>                    action_dict[&#39;buying_servers&#39;].append(0)<br>                    action_dict[&#39;remove&#39;].append(remove_qty)<br>                    action_dict[&#39;move_to&#39;].append(moveto_qty)<br>                    action_dict[&#39;dismiss&#39;].append(dismiss_qty)<br><br>    action_df = pd.DataFrame(action_dict)<br>    action_df.to_csv(f&#39;result/all_action_df_{seed}.csv&#39;, index=False)<br><br>    utilisation_df = pd.DataFrame(utilisation_dict)<br>    utilisation_df.to_csv(f&#39;result/utilisation_df_{seed}.csv&#39;, index=False)  <br><br>    business_metric = pd.DataFrame(business_metric_dict)<br>    business_metric.to_csv(f&#39;result/business_metric_{seed}.csv&#39;, index=False)<br>    <br>    print(&quot;All actions have been saved!&quot;)</pre><h4>Visualise Utilisation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5arlFs1Y_PG9tsKQhuX9Pw.jpeg" /><figcaption>Uitilisation of CPUs</figcaption></figure><ul><li><strong>Older Generations Struggle with High Demand</strong>: CPU.S1 and CPU.S2 show significant under-provisioning in <strong>low</strong> and <strong>medium</strong> latency environments, with demand often exceeding capacity</li><li><strong>Better Utilization of Newer Generations</strong>: CPU.S3 and CPU.S4 handle demand more efficiently.</li><li>In high latency sensitivity, all server generations effectively meet the demand, which could be due to the fact that servers deployed for high latency workloads are more profitable. As a result, more resources may have been allocated to ensure sufficient capacity, leading to better alignment between demand and capacity across all server generations in this scenario.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_UlF-Oxe0kXSmXqcNxnxQ.jpeg" /><figcaption>Utilisation of GPUs</figcaption></figure><ul><li><strong>Stable Resource Allocation</strong>: Across all latency sensitivities, GPU.S2 and GPU.S3 demonstrate good alignment between capacity and demand, particularly in later time steps, indicating efficient resource allocation.</li><li><strong>GPU.S1</strong> appears to be over capacity compared to market demand in low latency sensitivity. This <strong>over-provisioning</strong> may result from the accumulation of servers due to moving actions between data centers, shifting from low latency environments to medium or high latency ones, rather than purchasing new servers, which would incur higher costs.</li><li><strong>High Demand for GPU.S3</strong>: GPU.S3 handles a significant increase in demand toward the end of the timeline across all sensitivity levels.</li></ul><p><strong>Conclusion</strong></p><blockquote><strong>CPU</strong>: Generally struggles to meet demand for older generations, with more fluctuation between under-provisioning and over-provisioning. Newer generations handle high-demand environments better but still exhibit some inefficiencies in high latency sensitivity.</blockquote><blockquote><strong>GPU</strong>: Shows better alignment between capacity and demand, particularly for newer generations like GPU.S3. Over-provisioning is observed in GPU.S1, but newer GPUs efficiently meet growing demand, especially in low and medium latency scenarios.</blockquote><h4>Visualise Business Metric</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VN5PpYRmnDvTRIQcP9vDfw.jpeg" /></figure><blockquote>This chart illustrates a progression toward profitability. Initially, the business experiences volatility in both revenue and costs, leading to some periods of loss. However, as time progresses, revenue grows steadily, while costs stabilize, resulting in increasing and sustained profitability. The overall trend indicates successful business growth.</blockquote><ul><li>Before step 25, there are some periods of loss (negative profit), but these become less frequent over time as revenue grows and costs become more controlled.</li><li>Around time step 100 and 140, there is a sudden decrease in profit, likely due to the dismissal of a certain number of servers that exceeded their life expectancy. This led to a temporary spike in costs, as new servers had to be purchased to meet ongoing demand.</li></ul><h3>Conclusion</h3><h4>Scenario Analysis</h4><p>An important requirements in many mathematical optimisation problems is scenario analysis, also known as what-if analysis. Generally speaking, in what-if analysis, we’re interested in understanding how the solution changes under various scenarios. Think about our case here:</p><p>- How does the solution change if each server generation has a different life expectancy? In reality, servers have varying life expectancies.</p><p>- What if utilization is prioritized over profit?</p><p>- What if a new data center is added, or an existing data center is expanded?</p><p>- What if we can adjust the selling prices to increase profit?</p><p>Our model here is still a simple model. But you can imagine the value that the scenario analysis can provide. It can enable you to answer many questions by creating and comparing different scenarios and evaluating their outcomes, so that you can assess their impacts on the business goals.</p><h4>Next step</h4><p>As can be seen, the utilisation of each server generation at various latency sensitivity levels has room for improvement. One potential way to enhance this is by optimising resource allocation and operational strategies.</p><p>In the next step, we’ll tackle this data center operation problem by introducing an additional action: a <strong>price strategy</strong>. By adjusting pricing based on server generation and latency sensitivity, we can potentially improve utilisation and profitability.</p><p>For now, try to explore and solve this problem on your own. Think about how different pricing strategies might impact server utilisation and overall business performance.</p><p>See you next time, when we’ll dive into a detailed solution and explanation for this enhanced problem.</p><h4>Source code</h4><p>You can find the entire notebook with the code developed for this article in the link to my GitHub repository below.</p><p><a href="https://github.com/Tayerquach/data_center_operations/blob/master/Data_center_operation_part1.ipynb">data_center_operations/Data_center_operation_part1.ipynb at master · Tayerquach/data_center_operations</a></p><p>I sincerely hope you found this article useful and entertaining. If so, I’d love to hear your thoughts! And if you’re interested in staying updated on my latest articles, consider following me on Medium. Your support and feedback are what drive me to keep exploring and sharing in this fascinating field. Thank you for taking the time to read, and stay tuned for more insights in my next article!</p><h4><strong>References</strong></h4><ul><li><a href="https://medium.com/@quachmaiboi/optimizing-data-center-operation-part-2-0b42f0c4a934">Optimizing data center operation — Part 2</a></li><li><a href="https://www.gurobi.com/jupyter_models/">Jupyter Models Archive - Gurobi Optimization</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c21cf4f9378" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Probability Puzzles — Dice (Day 5)]]></title>
            <link>https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-day-5-0e333ab573dc?source=rss-2a9bdb49c93f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e333ab573dc</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[dice-game]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[probability]]></category>
            <dc:creator><![CDATA[Boi Mai Quach]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 02:57:41 GMT</pubDate>
            <atom:updated>2023-11-17T16:11:16.219Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Probability Puzzles — Dice (Day 5)</h3><h3>Introduction</h3><p>As mentioned in the <a href="https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-day-4-5295964bb0ff">previous article</a>, interviewers often do not ask their candidates direct questions, similar to exam questions in school, such as “What is the probability of rolling two dice and getting a sum of 7?” Instead, they will play with your mind by asking about a dice game to turn the interview more exciting. Through this way, they aim to test your logical thinking ability.</p><p>Therefore, today I will introduce a dice game involving the rolling two dice, a topic which we have previously covered. Although, for most of the previous problems, we could solve them in a minute with the awesome tricks that I provided. However, whether using these tricks can help you pass this dice game problem. Let’s address the problem together to reach a conclusion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ydfjawkr7ygERTS8" /><figcaption>Photo by <a href="https://unsplash.com/@nemo765?utm_source=medium&amp;utm_medium=referral">nemo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>For readers new to this series, my purpose is to solve each and every probability problem in order to help individuals for interview preparation and share my passion for mathematics to inspire people of all backgrounds.</blockquote><p><em>✨Please give me a 👏 if you are interested in my sharing, leave a comment 💬 to share your views/thoughts. ✨</em></p><h3>Problem</h3><blockquote><strong>Two players each roll two dice, first player A, then player B. If player A rolls a sum of 6, they win. If player B rolls a sum of 7, they win. They take turns, back and forth, until someone wins. What is the probability that player A wins?</strong></blockquote><p>Now, it’s your turn to solve this problem first and then look at the solution below.</p><h3>Solution</h3><p>In <a href="https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-day-3-e641b031c816"><strong>Day 3’s problem</strong></a>, I introduced a problem involving rolling two dice, providing readers with a detailed explaination and an interesting trick to solve the general problem. For today’s challenge, based on that, we can easily retrieve two numbers in our minds within a minute,</p><ul><li>The probability of rolling a sum of 6 with two dice is <strong>5/36</strong> which is approximately 13.89%. (denoted as <strong><em>p)</em></strong></li><li>The probability of rolling a sum of 7 with two dice is <strong>6/36</strong> which is approximately 16.67%. (denoted as <strong><em>r</em>)</strong></li></ul><p>So, before diving into more details, take a moment to look and imagine what you are going to do next. If you rely only on the trick, you might stop at this step. During an interview, you can become worried and confused. <strong><em>I will share my own story in the conclusion regarding this situation</em></strong>. Nonetheless, if you are well-prepared and engage in more pratices for your logical thinking, you will stay calm and can perform exactly what I am about to explain below.</p><p>Now, let’s break down the problem. Player A can win under the following scenarios:</p><ul><li>Player A rolls a 6 in the first roll.</li><li>Player A fails to roll a 6, and player B fails to roll a 7; then player A rolls a 6.</li><li>Player A fails to roll a 6 twice, and player B fails to roll a 7 two times; then player A rolls a 6.</li><li>…</li><li>Player A fails to roll a 6 <strong><em>k</em></strong> times, and player B fails to roll a 7 <strong><em>k</em></strong> times; then player A rolls a 6.</li></ul><p>Each of these scenarios has a probability equal to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/140/1*9Yk36FUqz5JYihhl069ZHg.png" /></figure><p>where <strong><em>k = 0, 1, 2, 3, …</em></strong></p><p>Since each of these events is independent, we can add up the probabilities. Hence, the probability that player A wins would be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*Gi2twFkAhZQOOwJjCubM_Q.png" /></figure><p>And now, with <strong><em>p</em></strong> = 5/36, and <strong><em>r</em></strong> = 6/36, we obtain a result of 30/61 which is around <strong>0.492. Thus,</strong></p><blockquote><strong>The probability of Player A winning is approximately 49.2%</strong></blockquote><p>Looking at the number, we can say that the game just slightly favor player B.</p><p>So, is that the end of the question? As usual, the interviewer would love to play with your thinking. I am not 100% sure what they would ask you next, but this could be a possible one.</p><blockquote><strong>As your answer, we find out that the game is not fair because Player B is more statistically more advantegous. So, are there sum targets for Player A and Player B that would make the game fair? What about using a different number of dice, or allowing targets to include more than one sum?</strong></blockquote><p>Alright, it is now more interesting. Let’s continue solving the problem. We still have the formula for the probability that Player A wins. It is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/80/1*K-Ac_mxS9mxOryEWhF8iXQ.png" /></figure><p>Now, to make the game fair, this should be equal to 0.5 (50%), or</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*nsHtnRO7qSu-wMj_2ci4qw.png" /></figure><p>Let’s denote,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*K-rpzu_NSzg-1G64A0Y2bw.png" /></figure><p>where <strong><em>x (&gt;0), y (&gt; 0) </em></strong>represent the posibilities that the bet sum of the dice for Player A, and Player B will happen, respectively. And <strong><em>s (&gt; 0) </em></strong>is the number of sides of the dice.</p><p>For example, in the initial problem, two players roll two six-sided dice, thus <strong><em>s = 6</em></strong>. The possible cases to achieve a sum of 6 with two dice are <strong><em>x = 5,</em></strong> which are (1,5), (2,4), (3,3), (4,2), and (5,1). Therefore, the probability is <strong><em>p = 5/36.</em></strong></p><p>Substituting <strong><em>p</em></strong> and <strong><em>r</em></strong>, we achieve,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*hxvGEevJ2ZNiGP-RfDYYew.png" /></figure><p>Since <strong><em>s</em></strong> cannot be zero, we have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*bqhCsDcx2Sfj43m0F4LEJQ.png" /></figure><p>If <strong><em>x = y</em></strong>, it means that the probability of getting a sum for Player A’s target and Player B’s target (<strong><em>p</em></strong> and <strong><em>r</em></strong>) are equal. However, this leads to <strong><em>xy = 0</em></strong>according to the equation above, which is impossible. Thus, <strong><em>x</em></strong> and <strong><em>y</em></strong> must different.</p><p>Moreover, it’s possible for either <strong><em>x</em></strong> or <strong><em>y</em></strong> to be equal to <strong><em>s</em></strong>, but not both at the same time.</p><p>With regard to (*), 𝑠² divides <em>xy, </em>or<em> xy = ms² (1) </em>where <em>m</em> = {1, 2, 3 …}. However, because <strong><em>x</em></strong> and <strong><em>y</em></strong> have values less than or equal to <strong><em>s </em></strong>and cannot occur simultaneously, we have the inequation <em>xy</em> &lt; s² (2).</p><p>With equation (1) and inequation (2),</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*UA92LogoTUifKzyFRADVHQ.png" /></figure><p>Therefore, there is no posibility of target sums that would make this game fair.</p><p>This answers the first part of the extended question “<strong>Are there sum targets for Player A and Player B that would make the game fair?”.</strong></p><p>For the second part, “<strong>What about using a different number of dice, or allowing targets to include more than one sum?”</strong></p><ol><li><strong>Target to include more than one sum</strong></li></ol><p>We will go with this option first because we have been already analysing the rolling two dice case. We can observe that,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*KjlBWQ6jrUu00s5urjkICA.png" /></figure><p>Looking at the cone shape in the <a href="https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-day-3-e641b031c816">trick of rolling two dice</a>, we can immediately have many combination. For example:</p><ul><li>The probability of rolling a sum of 5 or 6 with two dice is <strong>9/36 </strong>(calculated as 4/36 + 5/36)</li><li>The probability of rolling a sum of 4 or 7 with two dice is <strong>9/36 </strong>(calculated as 4/36 + 6/36)</li><li>…</li></ul><p>How about the probability of <strong>12/36</strong>?</p><p>According to the chart, the maximum probability for getting two sums is <strong>11/36. </strong>To obtain<strong>12/36. </strong>We have to include three sums as follows:</p><ul><li>The probability of throwing a sum of 8, 9 or 10 with two dice is <strong>12/36 </strong>(calculated as 5/36 + 4/36 + 3/36).</li><li>The probability of throwing a sum of 7, 9 or 11 with two dice is <strong>12/36 </strong>(calculated as 6/36 + 4/36 + 11/36).</li><li>…</li></ul><p>As a result, the game is fair if Player A’s target is a sum of 5 or 6, while Player B’s target is a sum of 8, 9, or 10.</p><p>…</p><p><strong>2. Using a different number of dice</strong></p><p>To give the answer for this option, we may need to apply the trapezoid trick for<a href="https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-day-4-5295964bb0ff"> rolling three dice</a>. I chose three dice rolling because I think in an interview, providing quick answers for rolling two dice and three dice is reasonable. Unless you remember all probabilities for rolling four, five, or even more dice, you can use them to make a strong impression on your interviewers.</p><p>Now, back in the problem, if the players throw three dice, we find that,</p><ul><li>The probability of throwing a sum of 3, 4 or 6 with three dice is <strong>14/216 </strong>(calculated as 1/216 + 3/216 + 10/216).</li><li>The probability of throwing a sum of 15, 17or 18 with three dice is <strong>14/216 </strong>(calculated as 1/216 + 3/216 + 10/216).</li></ul><p>Now,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*aLI7caPk8wOp60Hq2d_Gqw.png" /></figure><ul><li>The probability of throwing a sum of 7 with three dice is <strong>15/216, </strong>approximately<strong> 0.0694.</strong></li><li>The probability of throwing a sum of 14 with three dice is <strong>15/216, </strong>approximately <strong>0.0694.</strong></li></ul><p>Hence, the game is <strong>nearly fair </strong>if the first player’s target is a sum of 3, 4, or 6, while the second player’s target is a sum of 7.</p><p>…</p><h3>Conclusion</h3><p>Today’s problem reminds me of an interview five years ago when I had already completed my Bachelor’s degree. I had practised many probability formulas as I frequently did in high school, and university for every exam. In that interview, after a coding session, I moved on to an interview with a senior. He asked me five or four probability questions. The first one was easy, and I had the answer immediately. However, the second problem was more challenging because it required me break it down into several steps, similar to the dice game question in this article. After I had some results for a small piece of the whole puzzle, similar to today’s problem, which is the probability of getting a sum of particular numbers, I did not know what to do next. I felt like my brain was stuck and couldn’t think more, and it became a mess before running out of time for that question. Since then, I realised that if I did not practise my logical thinking, I might not perform well in the probability test.</p><p>Throughout today’s problem, we have applied the knowledge gained from previous posts on dice-related probability problems to solve a specific dice game scenario. A well-prepared interview will not based on some tricks or short-term efforts, it is a long-term process. Therefore, successfully securing a job is not the only success in that journey, the experience itself is more enjoyable. This means you feel more successful if, day by day, you can apply your knowledge to address a probability problem without confusion or hesitation. Everday, you accumulate more experience, and your thinking becomes more logical.</p><p>Thank you for reading until the end. This is the last dice-related problem in my series. In the next stage, we will explore <strong>Card Game Problems </strong>which are excellent opportunities to practise various probability concepts.​​ See you soon!</p><p><strong>Note: Unless otherwise noted, all images are by the author.</strong></p><p><strong>Source code</strong></p><p><a href="https://github.com/Tayerquach/probability_master/tree/master/rolling_dice?source=post_page-----5295964bb0ff--------------------------------">probability_master/rolling_dice at master · Tayerquach/probability_master</a></p><p><strong>Preferences</strong></p><ul><li><a href="https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-day-3-e641b031c816">Mastering Probability Puzzles — Dice (Day 3)</a></li><li><a href="https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-day-4-5295964bb0ff">Mastering Probability Puzzles — Dice (Day 4)</a></li></ul><p><a href="https://www.madandmoonly.com/doctormatt/mathematics/dice1.pdf">https://www.madandmoonly.com/doctormatt/mathematics/dice1.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e333ab573dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-study plan for quant researcher — Puzzle (Day 6)]]></title>
            <link>https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-6-4c622797f00a?source=rss-2a9bdb49c93f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c622797f00a</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[puzzle]]></category>
            <category><![CDATA[quantitative-research]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Boi Mai Quach]]></dc:creator>
            <pubDate>Tue, 14 Nov 2023 02:05:20 GMT</pubDate>
            <atom:updated>2024-09-30T10:29:04.145Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solving Jane Street’s Puzzles (Day 6)</h3><p>Today’s puzzle will be much more challenging than the previous ones. After solving five puzzles, I believe that we all know how to use Python libraries to set up the logic, the equations, and run the code to find the final answer. However, in those cases, the computer only runs based on your guidance. Thus, if you instruct it to perform a huge computation with arbitrary conditions. It cannot address the problem as you might expect. This <a href="https://www.janestreet.com/puzzles/hex-agony-index/">Hex-agony puzzle</a> will be an excellent illustration of how solely relying on computers would result in an unsatisfactory solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nIXssnMBCZWBq4ZR" /><figcaption>Photo by <a href="https://unsplash.com/@aquaryus15?utm_source=medium&amp;utm_medium=referral">Aquaryus15</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Again, for readers who are encountering this series for the first time, my purpose is to solve each and every <a href="https://www.janestreet.com/puzzles/">Jane Street’s Puzzles</a>. My code will be published on <a href="https://github.com/Tayerquach/quant_puzzles">my </a><a href="https://github.com/Tayerquach/quant_puzzles/">GitHub</a>.</blockquote><p><em>✨Please give me a 👏 if you are interested in my sharing, leave a comment 💬 to share your views/thoughts. ✨</em></p><h3>Hex-agony</h3><p>The puzzle was published at <a href="https://www.janestreet.com/puzzles/hex-agony-index/">this link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n5Oe7D8wNIhSHbWk28xNng.png" /><figcaption>Source: <a href="https://www.janestreet.com/puzzles/hex-agony-index/">https://www.janestreet.com/puzzles/hex-agony-index/</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Cp8GEodI1klXi5uz1nGCWA.png" /></figure><h3>Break down the problem</h3><p>This puzzle challenges you to fill in a grid of hexagons with numbers according to a set of rules. Each hexagon (hex) has a unique color and specific rules associated with them. The objective is to strategically place non-negative integers in certain hexagons so that all the given requirements are met. Let’s break down the rules:</p><h4>Requirements</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fuUM6Qmctj00HoJVLIiSTQ.png" /></figure><h4>Submission</h4><p>Your task is to fill in the grid such that all of these conditions are satisfied. The puzzle is asking for the <strong>largest possible sum of the numbers in the middle column</strong> once you’ve completed the grid.</p><p>Before attempting to slove the problem, for those who are not familiar with the z3 API in Python, please refer to my previous post at <a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-1-f0f481e686e"><strong>this link</strong></a>. Additonally, there is a condition related to the product of numbers. To find the numbers that multiply together to give a particular number, knowledge about <a href="#fd07"><strong>prime factors</strong></a> is necessary. However, if you are already familiar with these concepts, fell free to skip those specific parts and proceed directly to the <a href="#0d70"><strong>solution</strong></a>.</p><h4>Prime Factors</h4><p>Prime factors are the prime numbers that multiply together to give a particular number.<br>For example, let’s find the prime factors of 60:</p><ul><li>60÷2 =30</li><li>30÷2 =15</li><li>15÷3 =5</li><li>5÷5 =1<br>So, the prime factorization of 60 is <strong>2² x 3 x 5</strong>, and the prime factors are <strong>2, 3, and 5</strong>.</li></ul><h4>Finding prime factors in Python using <a href="https://www.sympy.org/en/index.html">SymPy</a></h4><pre>from sympy.ntheory import primefactors<br>number = 60<br>factors = primefactors(number)<br><br>print(f&quot;The prime factors of {number} are: {factors}&quot;)</pre><p>The output is,</p><pre>The prime factors of 60 are: [2, 3, 5]</pre><h3>Solution</h3><h4>Import necessary modules and packages</h4><pre>import numpy as np<br>import time<br>import itertools<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>from matplotlib.patches import RegularPolygon<br>from IPython.display import Markdown<br>from z3 import *</pre><p>The puzzle was solved with a hexagon shape. First of all, we need to create coordinates of every hex on that shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*yNynk8IAEaTxx6dG3mx1Cw.png" /><figcaption>The coordinates of a hexagony</figcaption></figure><p>There are three coordinates used to determine the positions of all hexes.</p><p>The <strong>x1-axis</strong> extends from the left-hand side to the right-hand side in the horizontal direction.</p><p>The <strong>x2-axis</strong> extends from the bottom to the top and then turns left following a stepped side of the hexagon.</p><p>The <strong>x3-axis</strong> goes down, starting from the stepped side of the hexagon and extending to the vertical side on the left-hand side.</p><blockquote><strong>Note: </strong>The sum of all values in a position is always 0. For example, (0, 4, -4): 0 + 4 + (-4) = 0</blockquote><h4>Set up the variables for each hex</h4><pre>point = {}<br>point_colour = {}<br><br>for i,j,k in itertools.product(range(-4,5),range(-4,5),range(-4,5)):<br>    if i+j+k !=0:<br>        continue<br>    point[(i,j,k)] = Int(&quot;x_%s_%s_%s&quot; % (i, j, k))<br>    point_colour[(i,j,k)] = Int(&quot;c_%s_%s_%s&quot; % (i, j, k))</pre><p>Now, the point colors will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*Gk77_DozlTcJyzc89Hompg.png" /></figure><h4>Set up solver and the hexagony</h4><pre>s = Optimize()</pre><pre>def hex_print(coord,colors,labels):    <br>    # Horizontal cartesian coords<br>    hcoord = [c[0] for c in coord]<br><br>    # Vertical cartersian coords<br>    vcoord = [2. * np.sin(np.radians(60)) * (c[1] - c[2]) /3. for c in coord]<br>    <br>    # 7-green: (-1, 4, -3)<br>    # 0-red: (-2, 4, -2)<br>    # 3997-red: (4, 0, -4)<br>    # 3059-blue: (1, 2, -3)<br>    # 854-red: (4, -2, -2)<br>    # 121121-blue: (2, -1, -1)<br>    # 847-green: (-4, 2, 2)<br>    # 0-red: (-3, 0, 3)<br>    # 7-red: (-2, -2, 4)<br>    # 11-black: (1, -3, 2)<br>    # 7-red: (3, -4, 1)<br>    <br>    givens = [[-1, 4, -3], <br>              [-2, 4, -2], <br>              [4, 0, -4], <br>              [1, 2, -3], <br>              [4, -2, -2], <br>              [2, -1, -1], <br>              [-4, 2, 2], <br>              [-3, 0, 3], <br>              [-2, -2, 4], <br>              [1, -3, 2], <br>              [3, -4, 1]]<br>    <br>    border = [1 if list(x) in givens else 0 for x in coord]<br>    fig, ax = plt.subplots(1,figsize=(10,10))<br>    ax.set_aspect(&#39;equal&#39;)<br>   <br>    # Add some coloured hexagons<br>    for x, y, c, l, b in zip(hcoord, vcoord, colors, labels, border):<br>        color = c[0].lower()  # matplotlib understands lower case words for colours<br>        hex = RegularPolygon((x, y), numVertices=6, radius=2. / 3., facecolor=color,<br>                         orientation=np.radians(30), alpha=0.2, edgecolor=&quot;grey&quot;)<br>        <br>        ax.add_patch(hex)<br>        # Also add a text label<br>        ax.text(x, y+0.2, l, ha=&#39;center&#39;, va=&#39;center&#39;, size=10)<br>        if b == 1:<br>            hex2 = RegularPolygon((x, y), numVertices=6, radius=2. / 3.,<br>                         orientation=np.radians(30), alpha=1,fill= False, edgecolor=&quot;k&quot;)        <br>            ax.add_patch(hex2)<br>        <br>    # Also add scatter points in hexagon centres<br>    ax.scatter(hcoord, vcoord, c=[c[0].lower() for c in colors], alpha=0)<br>    plt.axis(&quot;off&quot;)<br>    plt.show()</pre><h4>Find the prime factors</h4><p>Remember, the blue numbers and green numbers require prime numbers due to the following rules:</p><ol><li>Blue Numbers: Each blue number equals to the <strong>maximum of the green numbers</strong> in its view, or 0 if no green numbers are visible.</li><li>Green Numbers: Each green number equals to the <strong>product of the black numbers</strong> in its view, or 1 if no black numbers are visible.</li></ol><p>Considering the blue and green numbers appearing in the hexagon, we have:</p><pre>print(primefactors(121121)) # Blue number<br>print(7*11*11*11*13)<br>print(primefactors(3059)) # Blue number<br>print(7*19*23)<br>print(primefactors(847)) # Green number<br>print(7*11*11)<br>print(primefactors(7)) # Green number<br>print(7)</pre><p>The output is,</p><pre>[7, 11, 13]<br>121121<br>[7, 19, 23]<br>3059<br>[7, 11]<br>847<br>[7]<br>7</pre><p>Thus, black numbers will equal to these values: <strong>7, 11, 13, 19, 23</strong></p><pre># limit blacks to the factors of the blue/green cells<br>for i,j,k in point.keys():  <br>    s+= Implies(point_colour[(i,j,k)] == 0,Or([point[(i,j,k)] == n for n in [7,11,13,19,23]])) </pre><h4>Put fixed points</h4><p>Firstly, we need to establish a general condition for all numbers in the hexagon.</p><p>The value (<strong>point) </strong>of each tile has to be greater than or equal to 0. And the color of each will range from 0 to 4.</p><pre>s += [point[(i,j,k)] &gt;= 0 for (i,j,k) in point.keys()]<br>s += [And(point_colour[(i,j,k)] &gt;= 0,point_colour[(i,j,k)] &lt; 5)  for (i,j,k) in point_colour.keys()]</pre><p>There are available 11 numbers placed in the hexagon. We will input them into the solver.</p><pre># Fixed points   <br>#1. 7-green: (-1, 4, -3)<br>s += point[(-1,4,-3)] == 7<br>s += point_colour[(-1,4,-3)] == 3<br><br>#2. 0-red: (-2, 4, -2)<br>s += point[(-2,4,-2)] == 0<br>s += point_colour[(-2,4,-2)] == 2<br><br>#3. 3997-red: (4, 0, -4)<br>s += point[(4,0,-4)] == 3997<br>s += point_colour[(4,0,-4)] == 2<br><br>#4. 3059-blue: (1, 2, -3)<br>s += point[(1,2,-3)] == 3059<br>s += point_colour[(1,2,-3)] == 1<br><br>#5. 854-red: (4, -2, -2)<br>s += point[(4,-2,-2)] == 854<br>s += point_colour[(4,-2,-2)] == 2<br><br>#6. 121121-blue: (2, -1, -1)<br>s += point[(2,-1,-1)] == 121121<br>s += point_colour[(2,-1,-1)] == 1<br><br>#7. 847-green: (-4, 2, 2)<br>s += point[(-4,2,2)] == 847<br>s += point_colour[(-4,2,2)] == 3<br><br>#8. 0-red: (-3, 0, 3)<br>s += point[(-3,0,3)] == 0<br>s += point_colour[(-3,0,3)] == 2<br><br>#9. 7-red: (-2, -2, 4)<br>s += point[(-2,-2,4)] == 7<br>s += point_colour[(-2,-2,4)] == 2<br><br>#10. 11-black: (1, -3, 2)<br>s += point[(1,-3,2)] == 11<br>s += point_colour[(1,-3,2)] == 0<br><br>#11. 7-red: (3, -4, 1)<br>s += point[(3,-4,1)] == 7<br>s += point_colour[(3,-4,1)] == 2</pre><h4>Put the constraints</h4><p>In terms of the requirements, we will design constraints for each hex based on their colors.</p><pre># constraints<br>for i,j,k in point.keys(): <br>    s+= Implies(point_colour[(i,j,k)] == 0,  # black numbers = number of red numbers<br>               point[(i,j,k)] == Sum(                 <br>                   [If(point_colour[(x,y,z)] == 2,1,0) for x,y,z in point.keys() if (i==x or j==y or k==z) &amp; ((i,j,k) != (x,y,z)) ])) <br>  <br>    <br>    s+=  Implies(point_colour[(i,j,k)] == 1,  # blue number = max of green numbers <br>        Or(point[(i,j,k)] ==0, *[And(point[(i,j,k)] == point[(x,y,z)],point_colour[(x,y,z)] == 3) for x,y,z in point.keys() if (i==x or j==y or k==z) &amp; ((i,j,k) != (x,y,z))]))<br>    <br>    s+=  [Implies(And(point_colour[(x,y,z)] == 3, point_colour[(i,j,k)] ==1) ,point[(i,j,k)] &gt;= point[(x,y,z)]) for x,y,z in point.keys() if (i==x or j==y or k==z) &amp; ((i,j,k) != (x,y,z))]<br><br>    <br>    s+= Implies(point_colour[(i,j,k)] == 2, # red numbers = sum of blue numbers <br>               point[(i,j,k)] == Sum(                 <br>                   [If(point_colour[(x,y,z)] == 1,point[(x,y,z)],0) for x,y,z in point.keys() if (i==x or j==y or k==z) &amp; ((i,j,k) != (x,y,z)) ])<br>               )<br>    <br>    s+= Implies(point_colour[(i,j,k)] == 3, #green numbers = product of black numbers<br>               point[(i,j,k)] == Product(                 <br>                   [If(point_colour[(x,y,z)] == 0,point[(x,y,z)],1) for x,y,z in point.keys() if (i==x or j==y or k==z) &amp; ((i,j,k) != (x,y,z)) ])<br>               )</pre><h4>Run the solver</h4><p>Now, as usual, we will run the solver and find the solution</p><pre>start = time.time()<br>if s.check() == sat:<br>    m = s.model()<br>    coord= [x for x in point.keys()]    <br>    color = [cols[m.evaluate(point_colour[x]).as_long()] for x in point_colour.keys()]<br>    labels = [m.evaluate(point[x]).as_long() for x in point.keys()] <br>    answer = np.sum([m.evaluate(point[(i,j,k)]).as_long() for (i,j,k) in point.keys() if i==0])<br>    stop = time.time()<br>    print(&quot;Solved in {:.4f} seconds&quot;.format(stop-start))<br>    print(&quot;Sum is: {:,.0f}&quot;.format(answer))<br>    hex_print(coord,color,labels)<br><br>else:<br>    print(&quot;Failed&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*JDTD-TzXe8E16_4mJ7ZWkg.png" /></figure><p>After running the code for a day, <strong>I haven’t achieved any answers.</strong> This is the main part that I would like to discuss today. When solving a puzzle, if we don’t break it down step by step or fully rely on the computer, we can’t get any results.</p><p>For this challenge, unless you have a huge machine with a power <a href="https://en.wikipedia.org/wiki/Graphics_processing_unit">GPU</a>, you can obtain the answer quicker, but still too time-consuming or even get a “Failed” in the end. Thus, to solve it efficiently, we have to make redundant operations. As human being, we can solve problems using our logical thinking, and make it more precise. By leveraging the available numbers in the hexagon, we can limit the entries for hexeagons, making them more accurate. Let’s use the intuition or the thought process while solving such problems.</p><h4>Add inferred values</h4><h4>3059-blue</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*kY7LQh9IMs6dYMyTXEr68Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*rCQBwLMYqPBI4DZ4v0sUDw.png" /><figcaption>23-black in the centre, and the posibilities of a 3059-green title (red/green)</figcaption></figure><pre># A 23-black tile in the centre.<br>s += point[(0,0,0)] == 23<br>s += point_colour[(0,0,0)] == 0</pre><p>The number 3059 requires 23, 19, and 7 in its view. Among the fields that remain empty, there are only 5 (grey tiles with question marks) with at least 19 tiles in sight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*mEWylCDacFCIbIqx2Wn1Ww.png" /></figure><p>Only one have in sight only red or empty fields and one potentially containing a 3059-green. Place a 19-black there and a 3059-green in adequate place. All remaining tiles in sight of the 19-black becomes red. Now, this is what we have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*IRqlun-7rCEsTLujvA2DXA.png" /></figure><pre># The other 19-black is here<br>s += point[(-2,1,1)] == 19<br>s += point_colour[(-2,1,1)] == 0<br># As a result, the 3059-green is here<br>s += point[(-2,2,0)] == 3059<br>s += point_colour[(-2,2,0)] == 3</pre><h4>7-Green</h4><p>A 7-green implies a <strong>7-black</strong> in its view. There are 7 posibilities (grey-red tiles) for a <strong>7-black</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*t0pQcSY5LJIRRdiKQ7ZAcQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*dLztYo4X89lyx4jEPEnKPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*dlfSaqWpRlT-wCAjd0Q7LQ.png" /></figure><pre># Implies that a 7-black here<br>s += point[(-1,2,-1)] == 7<br>s += point_colour[(-1,2,-1)] == 0</pre><h4>121121-Blue</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*Twp5jBFMbQBN5MlafJTaPw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*JDZ6bMP_7Qk1r3tx_CVJpA.png" /></figure><pre># Implies that a 121121-green here<br>s += point[(-1,-1, 2)] == 121121<br>s += point_colour[(-1,-1, 2)] == 3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*l8xxpmNn4Yx8xW1Xfvlkfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*K3M-FvHeMbLT-Gj73NdbLw.png" /></figure><pre># Put the 13-black and 2 11s-black in the 121121-blue&#39;s views<br># 13-black<br>s += point[(3, -1, -2)] == 13<br>s += point_colour[(3, -1, -2)] == 0<br># 11-black<br>s += point[(-3, -1, 4)] == 11<br>s += point_colour[(-3, -1, 4)] == 0<br># 11-black<br>s += point[(2, -4, 2)] == 11<br>s += point_colour[(2, -4, 2)] == 0</pre><h4>847-Green and 0-red</h4><p>Green 847 = 7 x 1¹² has a 7-black and two black 11s in its view, and in its sight, there should be no more black tiles.</p><p>Two 0-reds are blocking blue numbers in sight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*E-pt6ppfUktkDm41rUfxFQ.png" /></figure><h4>7-red</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Lp7QdqSp_E1DxrkpVW8sLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*36pFHxemLJ8dN2JExiuZFg.png" /></figure><pre># Forces a 7-blue here<br>s += point[(3, -2, -1)] == 7<br>s += point_colour[(3, -2, -1)] == 1</pre><h4>854-red</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ApeDOp62bCP-lyUDpxTyXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*-EB8xO8gr0KckWItx_0ASQ.png" /></figure><pre># Forces a 847-blue here<br>s += point[(4, -3, -1)] == 847<br>s += point_colour[(4, -3, -1)] == 1</pre><h4>7-Blue</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*phrFEyfdOECDghSOVUazdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*7IswkbSevQMjMGEGrf44VA.png" /></figure><pre># Implies a 7-green here<br>s += point[(-1, -2, 3)] == 7<br>s += point_colour[(-1, -2, 3)] == 3</pre><h4>847-Blue</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*TQr8yClBthFWZx9LAD734A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*_OvEEDwOlGI2SQbIvRjyBQ.png" /></figure><pre># Implies a 847-green here<br>s += point[(-1, -3, 4)] == 847<br>s += point_colour[(-1, -3, 4)] == 3</pre><h4>3997-red</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*8Yt-RJGdo7Z0FleMXUyhwQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*5dfKXSV_2whw1Lo2W7mYLw.png" /></figure><pre># Put a 3059-blue in its view<br>s += point[(2, 2, -4)] == 3059<br>s += point_colour[(2, 2, -4)] == 1<br># Put a 91-blue in its view<br>s += point[(1, 3, -4)] == 91<br>s += point_colour[(1, 3, -4)] == 1</pre><h4>91-blue</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*wv8qz9IswZlbD89pQwmuiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*8utc8QcnncATa_hR3q5pIQ.png" /></figure><pre># Force a 91-green here<br>s += point[(-1, 3, -2)] == 91<br>s += point_colour[(-1, 3, -2)] == 3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*4iPGL4azfuY-ZRiw7l1yMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*Wp6QSlDdCSfFkYnaqVJSdg.png" /></figure><pre>s += point[(-3, 4, -1)] == 0<br>s += point_colour[(-3, 4, -1)] == 4</pre><p>Now, we only need to fill red hexes with numbers. All hexes have their own color, meaning that no arbitrary choices for any tiles in the hexagon.</p><h4>Rerun the solver again</h4><p>Here is the answer we achieved after nearly 40 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*qmC2YaR6Go68I6sa8TxzbA.png" /></figure><h3>Public Solution</h3><p>The best solution was published <a href="https://www.janestreet.com/puzzles/hex-agony-solution/"><strong>here</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RX3AvA5wCpVO_Jx3E412kw.png" /><figcaption>Source: <a href="https://www.janestreet.com/puzzles/hex-agony-solution/">https://www.janestreet.com/puzzles/hex-agony-solution/</a></figcaption></figure><h3>Conclusion</h3><p>We have solved a challenging puzzle together. During this puzzle, we learned that we cannot only rely on the computer to solve the puzzle. If the company sends you this puzzle and gives you one hour to address it, following the first path will be a significant problem. After one day, I stopped running the code, thus, I actually don’t know if it will take a couple of days, a week, a month, or even get a failure because of abstractions of the conditions for each hex. Of course, your interviewers would like to observe your actions when you don’t have enough patience to wait for the result. In trading market, although we currently use many techniques and computers to help us make decisions. However, the analysis and problem-solving abilities are more important for a candidate. I hope that we can accumulate great experience after each challenge.</p><p>Thank you so much for reading until now. Next time, we will dive into another Jane Street’s Puzzle, “<a href="https://www.janestreet.com/puzzles/travel-agent-index/"><strong>Travel Agent</strong></a>”. We have been using z3 in Python since the first day. This time, let’s try another technique, or simply use brute force to tacke this challenge. See you all soon.</p><p><strong>Note: Unless otherwise noted, all images are by the author.</strong></p><p><strong>Source code</strong></p><p><a href="https://github.com/Tayerquach/quant_puzzles/blob/master/Day_6/Hex-agony.ipynb">quant_puzzles/Day_6/Hex-agony.ipynb at master · Tayerquach/quant_puzzles</a></p><p><strong>Preferences</strong></p><ul><li><a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-1-f0f481e686e">Self-study plan for quant researcher — Puzzle (Day 1)</a></li><li><a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-2-6ba16c9a3a83">Self-study plan for quant researcher — Puzzle (Day 2)</a></li><li><a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-3-f12b9cc18e0b">Self-study plan for quant researcher — Puzzle (Day 3)</a></li><li><a href="https://www.janestreet.com/puzzles/">Puzzles :: Jane Street</a></li></ul><p><a href="https://math.stackexchange.com/questions/2120002/solve-this-hexagon-puzzle">https://math.stackexchange.com/questions/2120002/solve-this-hexagon-puzzle</a></p><p><a href="https://github.com/gowen100/Jane-Street-Solutions">https://github.com/gowen100/Jane-Street-Solutions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c622797f00a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Probability Puzzles — Dice (Day 4)]]></title>
            <link>https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-day-4-5295964bb0ff?source=rss-2a9bdb49c93f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5295964bb0ff</guid>
            <category><![CDATA[dice]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[quantitative-research]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <dc:creator><![CDATA[Boi Mai Quach]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 00:57:06 GMT</pubDate>
            <atom:updated>2023-11-17T03:06:09.739Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Probability Puzzles — Dice (Day 4)</h3><h3>Introduction</h3><p>Previously, I shared a general solution for rolling two dice problems. In response to some feedback, today I will introduce a dice-related problems involving the rolling three dice. Similar to two dice rolling, I will also provide everyone with a detailed explanation, an interesting simulation, as well as a helpful trick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GrzJIqfp-EchuMPM" /><figcaption>Photo by <a href="https://unsplash.com/@tamiminaser?utm_source=medium&amp;utm_medium=referral">Naser Tamimi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>For readers new to this series, my purpose is to solve each and every probability problem in order to help individuals for interview preparation and share my passion for mathematics to inspire people of all backgrounds.</blockquote><p><em>✨Please give me a 👏 if you are interested in my sharing, leave a comment 💬 to share your views/thoughts. ✨</em></p><h3>Problem</h3><blockquote><strong>When rolling three dice (standard fair 6-sided dice) simultaneously, should you bet on a 9 or 11?</strong></blockquote><p>Now, it’s your turn to solve this problem first and then look at the solution below.</p><h3>Solution</h3><p>As I mentioned on the <a href="https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-part-1-9fb7bfb1eacf">first day</a>, a probability problem can be solved in various ways. Using practical experience and knowledge to find a solution is known as the <a href="#b938"><strong>heuristic approach</strong></a><strong>. </strong>Another straightforward technique is to simply try the problem out many times, also referred to as the <strong>navie approach</strong>. In today’s problem, I will apply both approaches.</p><h4>Heuristic Approach</h4><p>Each of the dice has six faces, so there will be: 6 x 6 x 6 = <strong>216 possibilities </strong>occurring when rolling three dice at the same time.</p><p>These cases below represent scenarios that can result in a sum of 9 or 11.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*x3aABkBcJxSkUUhhpQHYIQ.png" /></figure><p>To obtain a sum of 9, we need to count the number of ways to arrange the three combinations. For the first, second, and fifth combinations, all three numbers are different, so we can use the factorial formula to calculate the number of arrangements, here is 3! = 6. However, for the third and fourth combinations, one of the numbers is repeated. In these cases, we need to divide by 2! to account for the repeated number (twice). Lastly, if we roll three 3s, there’s only one arrangement in this case.</p><p>Next, we add these possibilities, which gives us 25. This means that the probability of rolling a sum of 9 with three dice is 25/216, or about 11.6%. We can use the same process to calculate the probability of rolling a sum of 11, which is 27/216, or approximately 12.5%.</p><p>The probability of rolling a sum of 11 is 0.9% higher than the probability of rolling a sum of 9. Therefore, you would have a better chance of winning if you bet on a 11 instead of a 9.</p><h4>Naive Approach</h4><p>The most straightforward way to solve this problem is to roll many times and then keep track of the result. To do that, we can conduct a milion trials using the <a href="https://github.com/Tayerquach/probability_master/tree/master/rolling_dice"><strong>Dice Roll Probability</strong> </a>simulation, and then estimate the probability of getting a 9 or 11.</p><ul><li><em>First, import my module</em></li></ul><pre># Import module<br>from dice_rolling import Dice</pre><ul><li><em>Secondly, initialise variables and Dice object</em></li></ul><pre># Initialise parameters<br>num_dice = 3# The number of dice<br>num_sides = 6 # The sides of our dice<br><br># Create Dice object<br>roll = Dice(num_dice, num_sides)</pre><ul><li>Third, get the probability result.</li></ul><pre># Dice Roll Probability<br>outcome, probabilities = roll.get_dice_probability()</pre><p>This is the output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*0pemzDNy9f2Bs9h9JV-0Ag.png" /><figcaption>The probability of rolling three dice</figcaption></figure><p>As can be seen, the probability of getting a sum of 9 is approximately <strong>11.6%,</strong> and the probability of rolling a sum of 11 is approximately <strong>12.5%, </strong>which is consistent with the results calculated using the heuristic approach.</p><h3>Tip and Trick</h3><p>Similar to the previous problem, “Rolling two dice”, I will show you a memorable way to solve the problems of throwing three dice based on its visualisation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*47LE8dZw7wN46U_cBE6y5w.png" /><figcaption>Visualisation of three 6-dice rolling with 1,000,000 trials</figcaption></figure><p>These values were obtained from 1,000,000 trials. As you can see, this pattern is symmetrically distributed, in a ladder-like pattern. To illustrate this pattern, let’s draw a trapezoid following the steps below:</p><ol><li>Place the numbers from 3 to 10 in ascending order on the left-hand side, and the increasing numbers from 11 to 18 on the right-hand side. These numbers represent the sum values.</li><li>Put a list of numbers 1, 3, 6, 10, 15, 21, 25, and 27 (in green) from bottom to the top, on the left-hand side, and do the same on the right-hand side. <br>So, how can we remember these number? Easy!<br>- We already know that to get a sum of 3 or 18, threr is only one possibility which is 1, 1, 1 or 6, 6, 6 respectively. Now, let’s start with the number 1.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*q5FAantVhf7lRI81HbPSdQ.png" /></figure><p>We will get the results (red) and add them to the increasing numbers 2, 3, 4, 5, and 6 (black). The last two values, 25 and 27, are not follow the principle and must be remembered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*Sg-Y5iTXZ9HM6Pm7io0V-g.png" /></figure><p>Now, back to the question today, and solve it by using this diagram.</p><p>To get the answer and decide which number to bet on, we have to</p><ul><li><strong>The probability of getting a sum of 9.</strong><br>First, looking at the number 9 (red), which represents for the sum of 9. Next, we get the green number right next to it, which is 25, denoting the number of possibilities. Thus, the probability is 25/216 (~<strong>11.6%).</strong></li><li><strong>The probability of getting a sum of 11.</strong><br>Doing the same procedure, we have the probability of 27/216 (~<strong>12.5%</strong>).</li></ul><p>Moreover, only using this trapezoid, we can answer most questions regarding <strong>throwing three 6-sided dice to get a sum of any value.</strong></p><h3>Conclusion</h3><p>During today’s problem, we can promptly respond to any questions involving rolling three dice using the shortcut above, and provide interviewers with a detailed explanation using either a naive or a heuristic approach. However, remember that the question may not transparent, e.g., what is the probability of getting a sum of [value]. The brainteasers often change that question to be more like a dice game. Your task is to break down the question and then use the same techniques to find a suitable answer.</p><p>Speaking of dice game, this type of question is frequently asked since it is more engaging and effectively tests candidates’ logical thinking. I am sure that every candidate has studied probability at school and is also well-prepared for their interviews. Nonetheless, two major factors that can set you apart from others are your logical reasoning and your ability to think on your feet.</p><p>Thank you so much for reading this article. Next time, we will solve another dice game problem together to enhance your logical thinking. It will be more challenging than previous problems but certainly more interesting. See you all soon.</p><p><strong>Note: Unless otherwise noted, all images are by the author.</strong></p><p><strong>Source code</strong></p><p><a href="https://github.com/Tayerquach/probability_master/tree/master/rolling_dice">probability_master/rolling_dice at master · Tayerquach/probability_master</a></p><p><strong>Preferences</strong></p><ul><li><a href="https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-part-1-9fb7bfb1eacf">Mastering Probability Puzzles— Dice (Day 1)</a></li><li><a href="https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-day-2-c8d021e735eb">Mastering Probability Puzzles — Dice (Day 2)</a></li><li><a href="https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-day-3-e641b031c816">Mastering Probability Puzzles — Dice (Day 3)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5295964bb0ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-study plan for quant researcher — Puzzle (Day 5)]]></title>
            <link>https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-5-837fde90e77f?source=rss-2a9bdb49c93f------2</link>
            <guid isPermaLink="false">https://medium.com/p/837fde90e77f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[puzzle]]></category>
            <category><![CDATA[quantitative-research]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Boi Mai Quach]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 02:20:06 GMT</pubDate>
            <atom:updated>2024-09-30T10:28:15.199Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solving Jane Street’s Puzzles (Day 5)</h3><p>Today, another <a href="https://www.janestreet.com/puzzles/number-cross-2-index/"><strong>Number Cross</strong></a> puzzle will be solved using the same <a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-4-2ebc5b1f465f"><strong><em>technique</em></strong></a> that we used previously. Instead of focusing on solving many different types of puzzles, we should sometimes slow down and practice what we have learned. As a result, we will enjoy the process of tackling the challenge and laying a solid foundation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*upx-tzAKD6VY5NrK" /><figcaption>Photo by <a href="https://unsplash.com/@melindagimpel?utm_source=medium&amp;utm_medium=referral">Melinda Gimpel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Again, for readers who are encountering this series for the first time, my purpose is to solve each and every <a href="https://www.janestreet.com/puzzles/">Jane Street’s Puzzles</a>. My code will be published on <a href="https://github.com/Tayerquach/quant_puzzles">my </a><a href="https://github.com/Tayerquach/quant_puzzles/">GitHub</a>.</blockquote><p><em>✨Please give me a 👏 if you are interested in my sharing, leave a comment 💬 to share your views/thoughts. ✨</em></p><h3>Number Cross #2</h3><p>The puzzle was published at <a href="https://www.janestreet.com/puzzles/number-cross-2-index/">this link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*bKnW_uSKGF87eBr6MUFZgA.png" /><figcaption>Source: <a href="https://www.janestreet.com/puzzles/number-cross-2-index/">https://www.janestreet.com/puzzles/number-cross-2-index/</a></figcaption></figure><p>Fill the cells in this crossword with the digits 1 through 9 (no zeroes). Each clue in this crossword represents either the sum of the digits or the product of the digits in its corresponding answer — it’s up to you to decide which. The clue could potentially represent both the sum and the product, if the sum and product are the same. Digits can be repeated within an answer, and answers can be repeated in the grid.</p><p>As your answer, submit the sum of all of the digits you entered into the completed grid.</p><h3>Break down the problem</h3><p>In order to solve this 9 x 9 grid puzzle, we need to:</p><p><strong>Requirement</strong></p><ul><li>Place the digits from 1 to 9 (no zeroes) in the grid to satisfy all the provided clues.</li><li>Indicate whether each clue represents the sum or the product of the inputted digits.</li><li>Of course, a clue could be both the sum and the product. For example, if a clue asks for the number 6, the digits could be 1, 2, 3, and that clue will represent either the sum or the product of 6.</li><li>Digits can be repeated within a clue (e.g., 323, 232, 555 …).</li><li>Answers can be used more than once within the puzzle.</li></ul><p><strong>Submission</strong></p><p>The sum of all the digits in the completed grid is your submission for the puzzle.</p><p>Before attempting to slove the problem, for those who are not familiar with the z3 API in Python, please refer to my previous post at <a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-1-f0f481e686e"><strong>this link</strong></a>. Moreover, to create the function to solve the problem, we should understand the <a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-2-6ba16c9a3a83"><strong>Tactic</strong></a> and the <a href="#cae9"><strong>QF_LIA</strong></a>. Otherwise, you can skip those specific parts and move directly to the <a href="#6f98"><strong>solution</strong></a>.</p><h4>QF_LIA</h4><p><strong>QF_LIA</strong> stands for “Quantifier-Free Linear Integer Arithmetic,” and it is a logical theory within the realm of formal logic and automated theorem proving. This theory is used to express and reason about constraints and formulas involving linear integer arithmetic operations.</p><ul><li><strong>Quantifier-Free</strong>: In QF_LIA, formulas and constraints do not contain quantifiers like “for all” (∀) or “there exists” (∃).</li><li><strong>Linear Integer Arithmetic</strong>: QF_LIA focuses on linear relationships between integer variables. It deals with basic integer arithmetic operations, including addition, subtraction, and comparison operations (e.g., less than, greater than, less than or equal to, greater than or equal to).</li></ul><h3>Solution</h3><h4>Import necessary modules and packages</h4><pre>import numpy as np<br>import time<br>import itertools<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>from IPython.display import Markdown<br>from z3 import *</pre><h4>Create a 9x9 grid as the question</h4><p>We generate the puzzle with 0s for the white cells and 1s for the black cells.</p><pre># The white cell will be 0, while the black cell will be 1<br>grid = np.array(<br>                [[0, 0, 0, 0, 1, 0, 0, 0, 0],<br>                 [0, 0, 0, 0, 1, 0, 0, 0, 0],<br>                 [1, 0, 0, 0, 0, 1, 0, 0, 0],<br>                 [0, 0, 0, 0, 0, 0, 0, 1, 1],<br>                 [0, 0, 1, 0, 0, 0, 1, 0, 0],<br>                 [1, 1, 0, 0, 0, 0, 0, 0, 0],<br>                 [0, 0, 0, 1, 0, 0, 0, 0, 1],<br>                 [0, 0, 0, 0, 1, 0, 0, 0, 0],<br>                 [0, 0, 0, 0, 1, 0, 0, 0, 0]<br>                ], dtype=int)</pre><h4>Set up utility functions</h4><p>Before creating the <strong>solver</strong>, we design functions to generate the conditions for each clue. A grid entry will include the row or column positions for the first inputted digit, the starting position of the entry grid, and the number of cells for the answer.</p><p>The grid entry for the “<strong>across”</strong> questions</p><pre>def make_across(row,start,length,total):<br>    &quot;&quot;&quot;<br>    Create the variables for the grid entry reading across and include the clue<br>    <br>    Parameters:<br>    x: the rows&#39; positions.<br>    start: the first position that the entry grid starts<br>    length: the number of digit needs to be entered.<br>    total: the clue&#39;s value<br>    <br>    Return: a z3 object contained the bool decisions for a given grid entry.<br>    E.g., Clue #1: Or(x__0 + x__1 + x__2 + x__3 == 9, x__0*x__1*x__2*x__3 == 9)<br>    &quot;&quot;&quot;<br>    clue = [X[row,i] for i in range(start,start+length)]<br>    return  Or(Sum(clue)==total,Product(clue)==total)</pre><p>The grid entry for the “<strong>down”</strong> questions</p><pre>def make_down(col,start,length,total):<br>    &quot;&quot;&quot;<br>    Create the variables for the grid entry reading down and include the clue<br>    <br>    Parameters:<br>    x: the columns&#39; positions.<br>    start: the first position that the entry grid starts<br>    length: the number of digit needs to be entered.<br>    total: the clue&#39;s value<br>    <br>    Return: a z3 object contained the bool decisions for a given grid entry.<br>    E.g., Clue #1: Or(x__0 + x__9 == 45, x__0*x__9 == 45)<br>    &quot;&quot;&quot;<br>    clue = [X[i,col] for i in range(start,start+length)]    <br>    return  Or(Sum(clue)==total,Product(clue)==total)</pre><h4>Set up solver and matrix</h4><pre># Setup # 9x9 matrix of integer variables and solver <br>X = np.array(IntVector(&quot;x&quot;,9*9),dtype=object).reshape((9,9))<br>s = Tactic(&quot;qflia&quot;).solver()</pre><h4>Cell condition</h4><p>According to the requirements, place the digits from 1 to 9 (no zeroes) in the grid. Therefore,</p><pre># each cell contains a value 1-9 or is blocked<br>s += [And(e&gt;0,e&lt;=9) if grid[i,j] !=1 else e==0 for (i,j),e in np.ndenumerate(X)]</pre><h4>Set up the condition for each grid entry</h4><pre># Across<br>s += make_across(0,0,4,9)   #Clue 1<br>s += make_across(0,5,4,35)  #Clue 5<br>s += make_across(1,0,4,10)  #Clue 9            <br>s += make_across(1,5,4,30)  #Clue 10  <br>s += make_across(2,1,4,7)   #Clue 11  <br>s += make_across(2,6,3,10)  #Clue 13   <br>s += make_across(3,0,7,42)  #Clue 14  <br>s += make_across(4,0,2,21)  #Clue 16  <br>s += make_across(4,3,3,25)  #Clue 17 <br>s += make_across(4,7,2,15)  #Clue 18 <br>s += make_across(5,2,7,120) #Clue 20<br>s += make_across(6,0,3,25)  #Clue 22<br>s += make_across(6,4,4,35)  #Clue 24<br>s += make_across(7,0,4,21)  #Clue 25<br>s += make_across(7,5,4,9)   #Clue 27<br>s += make_across(8,0,4,5)   #Clue 29<br>s += make_across(8,5,4,8)   #Clue 30<br><br># Down<br>s += make_down(0,0,2,45) #Clue 1<br>s += make_down(1,0,5,20) #Clue 2<br>s += make_down(2,0,4,48) #Clue 3<br>s += make_down(3,0,6,72) #Clue 4<br>s += make_down(5,0,2,18) #Clue 5<br>s += make_down(6,0,4,24) #Clue 6<br>s += make_down(7,0,3,27) #Clue 7<br>s += make_down(8,0,3,26) #Clue 8<br>s += make_down(4,2,5,12) #Clue 12<br>s += make_down(0,3,2,18) #Clue 14<br>s += make_down(5,3,6,32) #Clue 15<br>s += make_down(7,4,5,45) #Clue 18<br>s += make_down(8,4,2,20) #Clue 19<br>s += make_down(2,5,4,30) #Clue 20<br>s += make_down(6,5,4,12) #Clue 21<br>s += make_down(0,6,3,70) #Clue 22<br>s += make_down(1,6,3,12) #Clue 23<br>s += make_down(3,7,2,2)  #Clue 26<br>s += make_down(8,7,2,36) #Clue 28</pre><p>Now, we are ready to run the code and get the result.</p><h4>Solve and print the result</h4><pre># Solve and print <br>start = time.time()<br>if s.check() == sat:<br>    m = s.model()<br>    evalu = np.vectorize(lambda x:m.evaluate(x).as_long())<br>    r = evalu(X)<br>else:<br>    print(&quot;Failed&quot;)<br><br>display(Markdown(&quot;**Solved in {:.4f} seconds. Solution is: {:.0f}**&quot;.<br>                 format(time.time()-start,np.sum(r))))<br><br>fig,ax = plt.subplots(1,1,figsize=(4,4))<br>ax =sns.heatmap(grid,annot=r,cbar=False,cmap=&quot;Greys&quot;,<br>                fmt=&quot;&quot;,linewidths=2,annot_kws={&quot;size&quot;:14,&quot;color&quot;:&quot;k&quot;},linecolor=&#39;k&#39;)<br>ax.axis(&quot;off&quot;)<br>plt.show()</pre><p>The output is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*p7xFihWHUvrtZfyfJ-faKA.png" /></figure><h3>Public Solution</h3><p>The best solution was published <a href="https://www.janestreet.com/puzzles/number-cross-2-solution/"><strong>here</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*aANkPmlxKFfihNMKF8lh0Q.jpeg" /><figcaption>Source: <a href="https://www.janestreet.com/puzzles/number-cross-2-solution/">https://www.janestreet.com/puzzles/number-cross-2-solution/</a></figcaption></figure><h3>Conclusion</h3><p>Imagine that if we do not address this puzzle by running code, we will have to solve a significant mathematical problem with many integer arithmetic operations. It could take a day, a week, or even a month to do that. I always say that I love mathematics, but I also do like coding. I like the way a computer can efficiently solve a complex problem and save the time. Knowledge is the fuel, and the computer uses it as a magical energy to run and create several beautiful things.</p><p>When I worked through these puzzles, I found that the progress made me think more logically. Although the mathematics that we have been using is not more complicated, the problem are still challenging. We need a creative strategy to solve each puzzle, and that is also what interviewers look for in their candidates. They want to hear your logical thought, appreciate your idea, and assess your problem-solving skill.</p><p>Next time, we will look at another puzzle called “<a href="https://www.janestreet.com/puzzles/hex-agony-index/"><strong>Hex-agony</strong></a>”, which has a chemistry-themed name. You can solve it first using the knowledge from previous puzzles. See you soon.</p><p><strong>Note: Unless otherwise noted, all images are by the author.</strong></p><p><strong>Source code</strong></p><p><a href="https://github.com/Tayerquach/quant_puzzles/tree/master/Day_5">quant_puzzles/Day_5 at master · Tayerquach/quant_puzzles</a></p><p><strong>Preferences</strong></p><ul><li><a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-1-f0f481e686e">Self-study plan for quant researcher — Puzzle (Day 1)</a></li><li><a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-2-6ba16c9a3a83">Self-study plan for quant researcher — Puzzle (Day 2)</a></li><li><a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-3-f12b9cc18e0b">Self-study plan for quant researcher — Puzzle (Day 3)</a></li><li><a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-4-2ebc5b1f465f">Self-study plan for quant researcher — Puzzle (Day 4)</a></li></ul><p><a href="https://www.janestreet.com/puzzles/">https://www.janestreet.com/puzzles/</a></p><p><a href="https://github.com/gowen100/Jane-Street-Solutions">https://github.com/gowen100/Jane-Street-Solutions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=837fde90e77f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Probability Puzzles — Dice (Day 3)]]></title>
            <link>https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-day-3-e641b031c816?source=rss-2a9bdb49c93f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e641b031c816</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[quantitative-strategies]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[dice]]></category>
            <dc:creator><![CDATA[Boi Mai Quach]]></dc:creator>
            <pubDate>Sun, 29 Oct 2023 00:51:23 GMT</pubDate>
            <atom:updated>2023-11-17T03:11:22.866Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Probability Puzzles — Dice (Day 3)</h3><h3>Introduction</h3><p>Dice problems have an advantage over other probability problems in that several scenarios can be easily simulated and investigated experimentally. This time, we will dive into another dice challenge to gain more knowledge about the probability. Some people think that using tricks to solve these problems is not always a good way to learn probability. Nonetheless, it would be ideal to capture insights and make a strong impression to interviewers if you understand the knowledge behind the tricks before using them. Let’s solve today’s problem with a detailed explanation, an interesting simulation, and a beautiful trick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JJDi4AUp3r5RTmduu_Y6SQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@grizzlybear?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Jonathan Petersson</a> on <a href="https://unsplash.com/photos/red-dice-W8V3G-Nk8FE?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><blockquote>For readers new to this series, my purpose is to solve each and every probability problem in order to help individuals for interview preparation and share my passion for mathematics to inspire people of all backgrounds.</blockquote><p><em>✨Please give me a 👏 if you are interested in my sharing, leave a comment 💬 to share your views/thoughts. ✨</em></p><h3>Problem</h3><blockquote><strong>Rolling two dice (standard fair 6-sided dice), what is the probability of rolling a sum of 11?</strong></blockquote><p>Now, it’s your turn to solve this problem first and then look at the solution below.</p><h3>Solution</h3><p>In <a href="https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-part-1-9fb7bfb1eacf"><strong><em>Day 1’s problem</em></strong></a>, I proposed an easy approach to solve those two dice problem by creating a 6 x 6 table representing all 36 posibilities. We also can use the same way to solve the challenge.</p><p>The sum of 11 can be obtained in two ways: (5,6) and (6,5). Therefore, the probablity is <strong>2/36, </strong>which is equivalent to<strong> 5.556 %</strong></p><h3>General case</h3><p>Rolling two 6-sided dice is common in many popular board games, especially in Monopoly. Thus, it would be beneficial if you could estimate how likely outcomes are, as knowing what could happen can assist you in making well-informed decisions.</p><p>Today, I will address this challenge by providing you with a simulation to determine the probability of certain outcomes when rolling dice. I designed a module for simulating dice rolls, which you can install from <a href="https://github.com/Tayerquach/probability_master/tree/master/rolling_dice"><strong>my Github</strong></a>.</p><p>For example, if we want to roll two dice randomly, we can do as follows</p><ul><li>First, import my module</li></ul><pre># Import module<br>from dice_rolling import Dice</pre><ul><li>Secondly, initialise variables and Dice object</li></ul><pre># Initialise parameters<br>num_dice = 2 # The number of dice<br>num_sides = 6 # The sides of our dice<br><br># Create Dice object<br>roll = Dice(num_dice, num_sides)</pre><ul><li>Thirdly, run <strong>dice roll simulation</strong></li></ul><pre># Roll Simulation<br>roll.roll_random_dice()</pre><p>This is the output,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*S1d06YAo1M73wEPIR5WPzA.png" /><figcaption>Dice Roll Simulation</figcaption></figure><p><strong>Dice Roll Probability</strong></p><p>I conducted a milion trials to estimate the probabilities of each outcome for two dice rolling.</p><pre># Dice Roll Probability<br>outcome, probabilities = roll.get_dice_probability()</pre><p>Then, this is what I get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*K77elzBPAGjPvqdwsteI7w.png" /><figcaption>The probabilities of rolling two 6-sided dice</figcaption></figure><p>Now, let’s back to the initial question and calculate the probability of rolling a sum of 11.</p><pre># the probability of rolling a sum of 11<br>total = 11<br>roll.get_sum_probability(total)</pre><p>The output is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*QQ5wO1qBcTdWdTc7S8SZDg.png" /></figure><h3>Tip and trick</h3><p>In order to get quick answers for rolling two 6-sided dice in the interviews, I will guide you through a simple way based on the visualisation below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*d-5bk3vf4kuuz85xVmeo4g.png" /><figcaption>Visualisation of two 6-sided dice rolling with 1,000,000 trials</figcaption></figure><p>These values were obtained from 1,000,000 trials. As you can see, this pattern appears to be symmetrical, with the highest probability at 7. Now, draw a cone shape by doing the steps listed below:</p><ol><li>Place ascending numbers from 2 to 12 (red) on the top of the cone to represent the sum values,</li><li>Put numbers 1 to 6 (green) on the left hand side and from 6 to 1 (green) on the right hand side under the cone. These numbers will indicate the number of posibilities for the respective sum events.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*6M25seQDQyRpKY2yeZjKpw.jpeg" /></figure><p>Now, we address today’s question based on the cone shape above.</p><blockquote><strong>What is the probability of getting a sum of 11?</strong></blockquote><p>First, we look at the number <strong>11</strong> above the cone. Next, we find the number right below that shape, which is also the posibilities of obtaining a sum of 11. It is number <strong>2</strong>. Thus, the probability is <strong>2/36</strong> or approximately <strong>5.556 % </strong>which matches the result of our simulations.</p><p>Only use this cone shape, we can answer most questions regarding <strong>rolling two 6-sided dice to get a sum of [value].</strong></p><h3>Conclusion</h3><p>Today’s challenge is not difficult. However, this straightforward question highlights the importance of interview preparation. By using the trick above, we can have an answer in around a minute, which can be very impressive to interviewers. I am not suggesting that we should rely on tricks to solve the probability problems. Instead, we should use tricks as a strategy to get a prompt response while still understand what is going on behind the scene because interviewers will ask why you have the answer and expect a detailed explanation.</p><p>In this post, I hope that you can use my module as a practical method for learning about dice roll probability. You can use <a href="https://github.com/Tayerquach/probability_master/tree/master/rolling_dice"><strong>this code</strong></a> to generate several functions, such as multiplication, subtraction, division, doubling, and more,<strong> </strong>or leave comments below this article. Any contributions you make will be greatly appreciated.</p><p>Thank you so much for taking the time to read this article. Next week, we will work together to solve another dice-related challenge. Looking forward to seeing you all.</p><p><strong>Note: Unless otherwise noted, all images are by the author.</strong></p><p><strong>Source code</strong></p><p><a href="https://github.com/Tayerquach/probability_master/tree/master/rolling_dice">probability_master/rolling_dice at master · Tayerquach/probability_master</a></p><p><strong>Preferences</strong></p><ul><li><a href="https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-part-1-9fb7bfb1eacf">Mastering Probability Puzzles— Dice (Day 1)</a></li><li><a href="https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-day-2-c8d021e735eb">Mastering Probability Puzzles — Dice (Day 2)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e641b031c816" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-study plan for quant researcher — Puzzle (Day 4)]]></title>
            <link>https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-4-2ebc5b1f465f?source=rss-2a9bdb49c93f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ebc5b1f465f</guid>
            <category><![CDATA[quantitative-research]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[interview-prep]]></category>
            <category><![CDATA[puzzle]]></category>
            <dc:creator><![CDATA[Boi Mai Quach]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 17:54:33 GMT</pubDate>
            <atom:updated>2024-09-30T10:24:25.490Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solving Jane Street’s Puzzles (Day 4)</h3><p>If you are a fan of crossword puzzles or Sodoku games, you will enjoy solving this <a href="https://www.janestreet.com/puzzles/number-cross-index/">Number Cross</a> puzzle. Grab a pencil and an eraser; we can approach this puzzle in a traditional manner. However, it could take a day, a couple of days, or even a week to complete the entire puzzle. Therefore, by joining me to tackle this challenge with a mathematical approach, we can reduce the time spent up to a hundredfold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*0R8_TxDCMLWUAOIOy9SXGQ.png" /><figcaption>Source: <a href="https://www.techcrackblog.com/2021/11/cross-number-puzzle-what-is-it-how-to.html">https://www.techcrackblog.com/2021/11/cross-number-puzzle-what-is-it-how-to.html</a></figcaption></figure><blockquote>Again, for readers who are encountering this series for the first time, my purpose is to solve each and every <a href="https://www.janestreet.com/puzzles/">Jane Street’s Puzzles</a>. My code will be published on <a href="https://github.com/Tayerquach/quant_puzzles">my </a><a href="https://github.com/Tayerquach/quant_puzzles/">GitHub</a>.</blockquote><p><em>✨Please give me a 👏 if you are interested in my sharing, leave a comment 💬 to share your views/thoughts. ✨</em></p><h3>Number Cross</h3><p>The puzzle was published at <a href="https://www.janestreet.com/puzzles/number-cross-index/">this link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*82ohR70ZJbm3wqgFEhqGng.png" /><figcaption>Source: <a href="https://www.janestreet.com/puzzles/number-cross-index/">https://www.janestreet.com/puzzles/number-cross-index/</a></figcaption></figure><p>Place the digits 1 thru 9 (no zeroes) in the crossword grid below so that all of the clues are satisfied. No digit is repeated in any one grid entry (e.g. 1-across is a grid entry), and no grid entry is used more than once within the puzzle.</p><p>For your answer, submit the sum of the 8 5-digit grid entries in the completed grid (e.g. 4-down, 18-across, etc.)</p><h3>Break down the problem</h3><p>In this puzzle, you are given a crossword grid with clues. The grid has 11 rows and 11 columns, and your task is to:</p><p><strong>Requirements</strong></p><ul><li>Place the digits 1 through 9 (without any zeros) into the grid to satisfy all of the presented clues.</li><li>Fill in the grid entries with the appropriate digits while ensuring that:<br>- No digit is repeated within any single grid entry (e.g., 322 cannot be the answer because it contains two number 2s). <br>- No grid entry is used more than once within the puzzle (e.g., the number 322 cannot appear twice in the puzzle).</li></ul><p><strong>Submission</strong></p><p>Once you’ve successfully filled in the grid and satisfied all the clues, find and <strong><em>sum the 5-digit numbers going across and down</em></strong> (e.g. 4-down, 18-across, etc.) and submit your answer.</p><p>Before attempting to slove the problem, for those who are not familiar with the z3 API in Python, please refer to my previous post at <a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-1-f0f481e686e">this link</a>. Otherwise, you can proceed to the following section.</p><h3>Solution</h3><h4>Import necessary modules and packages</h4><pre>import numpy as np<br>import time<br>import itertools<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>from IPython.display import Markdown<br>from z3 import *<br>import sympy</pre><p>For more information about SymPy, please visit <a href="https://docs.sympy.org/latest/tutorials/intro-tutorial/intro.html#">this link</a>. This symbolic computation library is used to perform methematical computations symbolically.</p><h4>Create a 11x11 grid as the question</h4><p>We will initially create the puzzle using an array with two numbers: 0 for white cells and 1 for black cells.</p><pre># The white cell will be 0, while the black cell will be 1<br>grid = np.array([[0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],<br>                 [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],<br>                 [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],<br>                 [1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1],<br>                 [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],<br>                 [0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0],<br>                 [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],<br>                 [1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1],<br>                 [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],<br>                 [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],<br>                 [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]<br>                ],dtype=int)</pre><h4>Set up utility functions</h4><p>Before solving each clues, we need to create the digit numbers based on the input digits (1–9). These functions below will help us initilise the digit numbers and fill them into each grid entry.</p><ol><li><strong>Create the digit number for the grid entry</strong></li></ol><p>If we place three numbers 3, 2, and 5 into a grid entry, we can form a 3-digit number, 325 using the formula: 3*10² + 2*10 + 5 = 325.</p><pre>def mult(x):<br>    &quot;&quot;&quot;<br>    Create the digit number for the grid entry<br>    <br>    Parameters:<br>    x: an array of variables<br>    <br>    Return: a digit (e.g. 3,2,5 =&gt; 325)<br>    &quot;&quot;&quot;<br>    n=len(x)<br>    return Sum([x[i] *10**((n-1)-i)  for i in range(n)]) </pre><p><strong>2. Create the variables for the grid entry</strong></p><p>The clues have two directions — across and dow. We need to set up spaces to enter the corresponding answers.</p><p>The grid entry for the “<strong>across”</strong> questions</p><pre>def make_across(x,y,n):<br>    &quot;&quot;&quot;<br>    Create the variables for the grid entry<br>    <br>    Parameters:<br>    x: the rows&#39; positions.<br>    y: the columns&#39; positions.<br>    n: the number of digit needs to be entered.<br>    <br>    Return: an array contain variables for a grid entry.<br>    &quot;&quot;&quot;<br>    <br>    return [X[x][y+i] for i in range(n)]</pre><p>The grid entry for the “<strong>down”</strong> questions</p><pre>def make_down(x,y,n):<br>    &quot;&quot;&quot;<br>    Create the variables for the grid entry<br>    <br>    Parameters:<br>    x: the rows&#39; positions.<br>    y: the columns&#39; positions.<br>    n: the number of digit needs to be entered.<br>    <br>    Return: an array contain variables for a grid entry.<br>    &quot;&quot;&quot;<br>    return [X[x+i][y] for i in range(n)]</pre><h4>Set up a solver and a 11x11 matrix</h4><pre># Setup a 11x11 matrix of integer variables and solver <br>X = np.array(IntVector(&quot;x&quot;,11*11),dtype=object).reshape((11,11))<br>s = Tactic(&quot;pqffd&quot;).solver()</pre><h4>Cell condition</h4><p>According to the requirements, place the digits 1 through 9 (no zeros) into the grid. Thus,</p><pre># each non-black cell contains a value in {1, ..., 9} black cells = 0<br>s += [And(e&gt;0,e&lt;=9) if grid[i,j] !=1 else e==0 for (i,j),e in np.ndenumerate(X)]</pre><h4>Set up the grid entries for each clue</h4><p>A grid entry will include the row and column positions for the first inputted digit, as well as the number of cells for the answer.</p><pre>across = {}<br>across[1]  = make_across(0,0,3)<br>across[4]  = make_across(0,4,3)<br>across[7]  = make_across(0,8,3)<br>across[10] = make_across(1,0,3)<br>across[11] = make_across(1,4,3)<br>across[12] = make_across(1,8,3)<br>across[13] = make_across(2,0,3)<br>across[14] = make_across(2,4,7)<br>across[16] = make_across(3,2,6)<br>across[18] = make_across(4,0,5)<br>across[20] = make_across(4,6,5)<br>across[24] = make_across(5,0,4)<br>across[25] = make_across(5,7,4)<br>across[26] = make_across(6,0,5)<br>across[28] = make_across(6,6,5)<br>across[29] = make_across(7,3,6)<br>across[31] = make_across(8,0,7)<br>across[34] = make_across(8,8,3)<br>across[37] = make_across(9,0,3)<br>across[38] = make_across(9,4,3)<br>across[39] = make_across(9,8,3)<br>across[40] = make_across(10,0,3)<br>across[41] = make_across(10,4,3)<br>across[42] = make_across(10,8,3)<br><br>down = {}<br>down[1] = make_down(0,0,3)<br>down[2] = make_down(0,1,3)<br>down[3] = make_down(0,2,7)<br>down[4] = make_down(0,4,5)<br>down[5] = make_down(0,5,4)<br>down[6] = make_down(0,6,5)<br>down[7] = make_down(0,8,3)<br>down[8] = make_down(0,9,3)<br>down[9] = make_down(0,10,3)<br>down[15] = make_down(2,7,6)<br>down[17] = make_down(3,3,6)<br>down[18] = make_down(4,0,3)<br>down[19] = make_down(4,1,3)<br>down[21] = make_down(4,8,7)<br>down[22] = make_down(4,9,3)<br>down[23] = make_down(4,10,3)<br>down[27] = make_down(6,4,5)<br>down[28] = make_down(6,6,5)<br>down[30] = make_down(7,5,4)<br>down[31] = make_down(8,0,3)<br>down[32] = make_down(8,1,3)<br>down[33] = make_down(8,2,3)<br>down[35] = make_down(8,9,3)<br>down[36] = make_down(8,10,3)<br><br>clues =[v for k,v in across.items()]+[v for k,v in down.items()]</pre><p>Now, let’s establish the conditions for the grid entries.</p><h4>No grid entry is used more than once within the puzzle</h4><pre># distinct clues<br>s += Distinct([mult(i) for i in clues])</pre><h4>No digit is repeated within any single grid entry</h4><pre># distinct digit in clues<br>s += [Distinct([x for x in i]) for i in clues]</pre><h4>Solving each and every clue</h4><p>There are a numerous questions in this puzzle, but some of them follow a common format (e.g., squares, primes). Thus, we will group these clues to save time.</p><blockquote><strong><em>For the purpoes of each code line, I have provided explanations in the comments</em></strong></blockquote><p><strong>Squares</strong></p><p>Example: A square number</p><pre>#squares<br># All &quot;squares&quot; questions requires a 3-digit number, 10 - 32 will create numbers from 100 to 961<br>square_numbers = [i**2 for i in range(10,32)] <br># &quot;Squares&quot; questions going across<br>sq_across = [1,4,7,11,12]<br>s += [Or([mult(across[i]) == x for x in square_numbers]) for i in sq_across]<br># &quot;Squares&quot; questions going down<br>sq_down = [1,7,8,18,19,36]<br>s += [Or([mult(down[i]) == x for x in square_numbers]) for i in sq_down]</pre><p><strong>Primes</strong></p><p>Example: A prime number</p><p><strong>Note</strong>: a prime number cannot be divided by any other number except for 1 and itself.</p><pre>#primes<br># All &quot;primes&quot; questions requires a 3-digit number.<br>prime_numbers = [*sympy.primerange(100,1000)]<br># &quot;Primes&quot; questions going across<br>pr_across = [39]<br>s += [Or([mult(across[i]) == x*2 for x in prime_numbers]) for i in pr_across]<br># &quot;Primes&quot; questions going down<br>pr_down = [9,22]<br>s += [Or([mult(down[i]) == x for x in prime_numbers]) for i in pr_down]</pre><p><strong>Other questions going across</strong></p><pre># 10. Samller than 23-down<br>s += mult(across[10]) &lt; mult(down[23])<br># 13. The smallest number in this grid<br>s += And([mult(across[13]) &lt;= mult(i) for i in clues])<br># 14. Its digits sum to 42<br>s += sum_dig(across[14]) ==42<br># 16. Divisible by 6<br>s += mult(across[16]) % 6 ==0<br># 18. 37-across + 6-down<br>s += mult(across[18]) == (mult(across[37])+mult(down[6]))<br># 20. Whether read forwards or backwards, the largest 5-digit number in this grid<br>s += And([And(mult(across[20]) &gt;= mult(i),mult(across[20][::-1]) &gt; mult(i)) for i in clues if len(i) == 5])<br># 24. Has the same digits as 5-down<br>s += Or([And([across[24][i]==j[i] for i in range(4)]) for j in itertools.permutations(down[5],4)])<br># 25. 42-across + 7-down<br>s += mult(across[25]) == (mult(across[42])+mult(down[7]))<br># 26. Its digits sum to 26<br>s += sum_dig(across[26]) == 26<br># 28. Its digits are ascending<br>s += And([across[28][i-1] &lt; across[28][i] for i in range(1,len(across[28]))])<br># 29. 4-across times 35-down<br>s += mult(across[29]) == (mult(across[4])*mult(down[35]))<br># 31. Divisible by 3<br>s += mult(across[31]) % 3 ==0<br># 34. Divisible by 3<br>s += mult(across[34]) % 3 ==0<br># 37. Its digits are ascending<br>s += And([across[37][i-1] &lt; across[37][i] for i in range(1,len(across[37]))])<br># 38. 39-across minus 13-across<br>s += mult(across[38]) == (mult(across[39])-mult(across[13]))<br># 40. Greater than 1-across<br>s += mult(across[40]) &gt; mult(across[1])<br># 41. Divisible by 25<br>s += mult(across[41]) % 25 ==0<br># 42. An odd number<br>s += mult(across[42]) %  2 ==1</pre><p><strong>Other questions going down</strong></p><pre># 2. Divisible by 11<br>s += mult(down[2]) % 11 ==0<br># 3. The largest number in this grid<br>s += And([mult(down[3]) &gt;= mult(i) for i in clues])<br># 4. Its digits sum to 16<br>s += sum_dig(down[4]) == 16<br># 5. A multiple of 9-down<br>s += Or([mult(down[5]) * i  == mult(down[9]) for i in range(1,10)]+[mult(down[5]) == mult(down[9])*i for i in range(1,10)])<br># 6. Its digits sum to 35<br>s += sum_dig(down[6]) == 35<br># 15. Divisible by 11<br>s += mult(down[15]) % 11 ==0<br># 17. Divisible by 9<br>s += mult(down[17]) % 9 ==0<br># 21. Its digits sum to 41<br>s += sum_dig(down[21]) == 41<br># 23. Larger than 32-down<br>s += mult(down[23]) &gt; mult(down[32])<br># 27. Half of 6-down<br>s += mult(down[27])*2 == mult(down[6])<br># 28. Divisible by 125<br>s += mult(down[28]) % 125 ==0<br># 30. Its digits are descending<br>s += And([down[30][i-1] &gt; down[30][i] for i in range(1,len(down[30]))])<br># 31. Its digits sum to 6<br>s += sum_dig(down[31]) == 6<br># 32. A multiple of 31-down<br>s += Or([mult(down[32]) *i  == mult(down[31]) for i in range(1,10)]+[mult(down[32]) == mult(down[31])*i for i in range(1,10)])<br># 33. A multiple of 31-down<br>s += Or([mult(down[33]) *i  == mult(down[31]) for i in range(1,10)]+[mult(down[33]) == mult(down[31])*i for i in range(1,10)])<br># 35. An even number<br>s += mult(down[35]) % 2 ==0</pre><p>Now, we are ready to run the code and get the result.</p><h4>Solve and print the result</h4><pre># Solve and print <br>start = time.time()<br>if s.check() == sat:<br>    m = s.model()<br>    evalu = np.vectorize(lambda x:m.evaluate(x).as_long())<br>    r = evalu(X)<br>    display(Markdown(&quot;**Solution {:,.0f} found after {:.4f} seconds**&quot;.format(sum([mult(evalu(x)) for x in clues if len(x) ==5]),time.time()-start)))<br>    annot = r.astype(&#39;str&#39;)<br>    annot[annot==&quot;0&quot;] =&quot;&quot;<br>    fig,ax = plt.subplots(1,1,figsize=(5,5))<br>    ax =sns.heatmap(grid,annot=annot,cbar=False,cmap=&quot;Greys&quot;,fmt=&quot;&quot;,linewidths=2,annot_kws={&quot;size&quot;:14},linecolor=&#39;k&#39;)<br>    ax.axis(&quot;off&quot;)<br>    plt.show()<br>else:<br>    print(&quot;Failed&quot;) </pre><p>The output is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*1l235nyTX0XdOE5nUWyG0g.jpeg" /></figure><h3>Public Solution</h3><p>The best solution was published <a href="https://www.janestreet.com/puzzles/number-cross-solution/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*MdZvf8SfBaIeB7cDgXX5Gg.jpeg" /><figcaption>Source: <a href="https://www.janestreet.com/puzzles/number-cross-solution/">https://www.janestreet.com/puzzles/number-cross-solution/</a></figcaption></figure><h3>Conclusion</h3><p>It only took 4 seconds to get the result. Impressive! Solving quantitative puzzles help you develop a wide range of different skillsets. First of all, in order to address a puzzle, you must understand your strengths. You cannot force a talent for swimming to become a chef. Similarly, if you are not skilled in coding but can quickly grasp any mathematical problems, you can write it down on a paper and work through the equations step by step. Even if you are not good at both skills, you can solve this puzzle as a crossword puzzle.</p><p>In my opinion, quatitative puzzle seems to be an IQ test which assesses various aspects of intelligence, such as linguistic, logical-mathematical, spatial, and creative intelligence.</p><p>Quantitative puzzles can be challenging. Therefore, interviewers often use these questions to differentitate between candidates, preferring those with a higher level of problem-solving skill and proficiency in programming.</p><p>To practice the technique today, we will together solve another <a href="https://www.janestreet.com/puzzles/number-cross-2-index/">Number Cross</a> puzzle next time. You can address it first using the logical and technical solutions mentioned above. See you later.</p><p><strong>Note: Unless otherwise noted, all images are by the author.</strong></p><p><strong>Source code</strong></p><p><a href="https://github.com/Tayerquach/quant_puzzles/tree/master/Day_4">quant_puzzles/Day_4 at master · Tayerquach/quant_puzzles</a></p><p><strong>Preferences</strong></p><ul><li><a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-1-f0f481e686e">Self-study plan for quant researcher — Puzzle (Day 1)</a></li><li><a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-2-6ba16c9a3a83">Self-study plan for quant researcher — Puzzle (Day 2)</a></li><li><a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-3-f12b9cc18e0b">Self-study plan for quant researcher — Puzzle (Day 3)</a></li></ul><p><a href="https://www.janestreet.com/puzzles/">https://www.janestreet.com/puzzles/</a></p><p><a href="https://www.codingjesus.com/post/4-tips-for-solving-quant-puzzles">https://www.codingjesus.com/post/4-tips-for-solving-quant-puzzles</a></p><p><a href="https://github.com/gowen100/Jane-Street-Solutions">https://github.com/gowen100/Jane-Street-Solutions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ebc5b1f465f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Probability Puzzles — Dice (Day 2)]]></title>
            <link>https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-day-2-c8d021e735eb?source=rss-2a9bdb49c93f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8d021e735eb</guid>
            <category><![CDATA[interview-tips]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[dice]]></category>
            <dc:creator><![CDATA[Boi Mai Quach]]></dc:creator>
            <pubDate>Sun, 22 Oct 2023 03:42:45 GMT</pubDate>
            <atom:updated>2023-11-17T03:12:11.056Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Probability Puzzles — Dice (Day 2)</h3><h3>Introduction</h3><p>Continue the series of mastering probability puzzles, today we will tackle another dice challenge together. Through this problem, we can learn interesting probability concepts and get to know the general case, allowing us to solve similar problems in the future.</p><blockquote>For readers new to this series, my purpose is to solve each and every probability problem in order to help individuals for interview preparation and share my passion for mathematics to inspire people of all backgrounds.</blockquote><p><em>✨Please give me a 👏 if you are interested in my sharing, leave a comment 💬 to share your views/thoughts. ✨</em></p><h3>Problem</h3><blockquote><strong>A fair 6-sided die is rolled until all the numbers show up. The order in which the numbers appear does not matter. What is the expected number of dice rolls?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tO_ID3wXpt9dxsMh" /><figcaption>Photo by <a href="https://unsplash.com/@rihok?utm_source=medium&amp;utm_medium=referral">Riho Kroll</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Now, it’s your turn to address this problem first and then look at the solution below.</p><p>As mentioned in <a href="https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-part-1-9fb7bfb1eacf"><strong><em>previous post</em></strong></a>, there are many ways to approach a probability problem. In this case, we need to revisit some probability concepts to solve it.</p><h4><strong>What is a Bernoulli trial?</strong></h4><blockquote>A Bernoulli trial is an experiment with <strong>only two possible outcomes</strong>, usually called a <strong>success</strong> and a <strong>failure</strong>.</blockquote><p>A success is a result you want to happen, while a failure is going to refer to undesired consequence.</p><p>The probability of success is denoted as <strong>p, </strong>and the probability of that same Bernoulli trial resulting in failure is represented as <strong>q</strong>. Since the experiment only has two outcomes, thus</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*DV9mhjL9K0IXCaUJjR-g6g.png" /></figure><p>For example, flipping a coin,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*rEu9xPTih_pdK-H8AWaD9w.jpeg" /><figcaption>A fair coin flip has two outcomes: head and tail</figcaption></figure><p>We could say the success is the coin landing head up.</p><ul><li>Success: heads =&gt; p = 1/2</li><li>Failure: tails =&gt; q = 1/2</li></ul><p>Another example, rolling a six-sided die,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*vmB37pBQ9T6MWtlveGEPLA.png" /></figure><p>Let’s say that the trail is a success if we roll a number greater than four.</p><ul><li>Success: 5, 6 =&gt; p = 2/6 = 1/3</li><li>Failure: 1, 2, 3, 4 =&gt; q = 4/6 = 2/3</li></ul><p>Remember, when we roll a six-sided die, there are six possible outcomes: 1 to 6. However, rolling that die can be a Bernoulli trial as long as we define a success and failure.</p><h4><strong>What is the Geometric Distribution?</strong></h4><blockquote>A <strong>geometric distribution</strong> can be defined in two different ways:</blockquote><blockquote>1. The number of trials required to get the first success (also known as a <strong>shifted geometric distribution</strong>)</blockquote><blockquote>2. The number of failures before the first success.</blockquote><p><strong>Example</strong></p><p><strong><em>Suppose we toss a coin until someone get a head, and then the game is over.</em></strong></p><ul><li>What is the expected number of tosses that will be required?</li><li>What is the probability of performing 4 trials before achieving the first heads.</li></ul><p>In order to have the first success (which is a head) on the 5th trial, we must have failures (which are tails) on every trial before the 5th trial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*XgIrPnkhXPlSDnbBa9kzFg.jpeg" /><figcaption>5 trials — Orders: Tail, Tail, Tail, Tail, Head</figcaption></figure><p>First, the probability of getting a head is p = 1/2 =&gt; 2 tosses (1/p) to get a head.</p><blockquote>The expected number of trials to get the first success is</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/116/1*iHsVrQJKUo6JUvmjeAQOYw.png" /></figure><p>Secondly, we know that each of our trials is independent of one another. Thus, we can simply multiply the probability of each event together to deteremine the overall probability of the events occuring. Let X be the event of the first head occuring, and the probability of X occuring at 5th trial is:</p><p>P(X = 5) = 1/2 * 1/2 * 1/2 * 1/2 * (1–1/2) = 0.03125 = 3.125%</p><blockquote>Denote the probability of failure as <strong>q</strong>, and the probability of success as <strong>p</strong>. The probability of performing x trials before achieving the first head.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/145/1*v2ENHMT9tGEiuTs5tsY3yQ.png" /></figure><h3>Solution</h3><p>Let X be the expected number of rolls until we have seen all the values between 1 and 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*md0V9vLiH9D5s-WwhFikpg.jpeg" /></figure><p>By applying the linearity of expectation, we can sum all the values to determine the waiting time to see all 6 numbers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*uBVfvO7svAJgZqFccf7ywA.png" /></figure><h3>General Case</h3><p>This problem belongs to the family of problems called the <strong>Coupon Collector’s Problem.</strong></p><blockquote>In the <strong>coupon collector’s problem</strong>, the goal is to purchase distinct objects in order to make a complete set of objects. Each purchase gives a random object, and the contents are independent of all other purchases. “Coupon” is just a placeholder word; the objects collected can be any kind of object.</blockquote><p><strong>Solution</strong></p><p>This is solved by using the same logic as our problem before. Let T be the number of purchases needed to collect all n objects. We can obtain the expectation as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*7g4fWHXbn8fDFaoipBbkbQ.png" /></figure><p>For the large values of n, this can be approximated as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*p2CqrA-VLGsg2yue0yUVTg.png" /></figure><p>Example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/159/1*3LkFWFYlbKhEIwPlvPoMLg.jpeg" /><figcaption>100-sided dice. Source: <a href="https://brilliant.org/wiki/coupon-collector-problem/">brilliant.org</a></figcaption></figure><p>Comming back to the problem we discussed earlier. Instead of a six-sided die, we have a fair 100-sided die, with each face numbered distinctly from 1 to 100. Rolling it and recording the numbers until we have rolled all the numbers at least once. What is the expected number of rolls we will need to make?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*8yAYbN2WBTCBxTaD37qc0g.png" /><figcaption>Approximation</figcaption></figure><p>In each simulation, we will record the number of rolls until all values (coupons) have been seen. We will run 10,000 simulations and compute the minimum, maximum, and average values of the running times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*5h2bWtmeju25oKEqLIlJSw.gif" /></figure><p>The average number at 10,000th run is nearly equal to the approximation that we calculated above.</p><p>If you are interested in how I created that simulation, you can refer to my <a href="https://github.com/Tayerquach/probability_master">GitHub</a>.</p><h3>Conclusion</h3><p>Dice-related problems provide a simple and intuitive way to grasp probability comcepts. In this series, I try to make many examples and simulations to offer readers a more realistic understanding. Back in high school, when I first learned probability, I felt really difficult to comprehend and remember the concepts. Even though I had just learned it the previous week, I still struggled to solve similar problems.</p><p>I discovered that relating probability to practical scenarios and imagining its applications in everyday life helped me retain knowledge for a longer duration and sparked my interest in studying probability.</p><p>If you read my post, understand how to solve the problem, and connect it to the real-life situations, that would be a great encouragement for me. You can share its applications to everyone here. I would really appreciate it. Next week, we will delve into another dice-related challenge. Look forward to seeing you all.</p><p><strong>Note: Unless otherwise noted, all images are by the author.</strong></p><p><strong>Source code</strong></p><p><a href="https://github.com/Tayerquach/probability_master">https://github.com/Tayerquach/probability_master</a></p><p><strong>References</strong></p><p><a href="https://medium.com/@quachmaiboi/mastering-probability-puzzles-dice-part-1-9fb7bfb1eacf">Mastering Probability Puzzles— Dice (Day 1)</a></p><p><a href="https://atypicalquant.net/quant-interview-questions/quant-interview-questions-coupon-collectors-problem/">https://atypicalquant.net/quant-interview-questions/quant-interview-questions-coupon-collectors-problem/</a></p><p><a href="https://brilliant.org/wiki/coupon-collector-problem/">https://brilliant.org/wiki/coupon-collector-problem/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8d021e735eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-study plan for quant researcher — Puzzle (Day 3)]]></title>
            <link>https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-3-f12b9cc18e0b?source=rss-2a9bdb49c93f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f12b9cc18e0b</guid>
            <category><![CDATA[puzzle]]></category>
            <category><![CDATA[quantitative-research]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Boi Mai Quach]]></dc:creator>
            <pubDate>Sun, 15 Oct 2023 19:20:38 GMT</pubDate>
            <atom:updated>2024-09-30T10:27:37.402Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solving Jane Street’s Puzzles (Day 3)</h3><p>Last time, we worked through the <a href="https://www.janestreet.com/puzzles/hooks-index/">Hooks</a> puzzle, exploring many interesting and logical ideas. This week we will continue this series with <a href="https://www.janestreet.com/puzzles/tile-and-trouble-index/">Tile and Trouble</a> puzzle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GiNzKpiVYAzx0lYW" /><figcaption>Photo by <a href="https://unsplash.com/@brave4_heart?utm_source=medium&amp;utm_medium=referral">Jigar Panchal</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Again, for readers who are encountering this series for the first time, my purpose is to solve each and every <a href="https://www.janestreet.com/puzzles/">Jane Street’s Puzzles</a>. My code will be published on <a href="https://github.com/Tayerquach/quant_puzzles">my </a><a href="https://github.com/Tayerquach/quant_puzzles/">GitHub</a>.</blockquote><p><em>✨Please give me a 👏 if you are interested in my sharing, leave a comment 💬 to share your views/thoughts. ✨</em></p><h3>Tile and Trouble</h3><p>The puzzle was publised at <a href="https://www.janestreet.com/puzzles/tile-and-trouble-index/">this link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*-CvIxJrwC6tq4DVjEshYsw.png" /><figcaption>Source: <a href="https://www.janestreet.com/puzzles/tile-and-trouble-index/">https://www.janestreet.com/puzzles/tile-and-trouble-index/</a></figcaption></figure><p>Add square tiles to the 12-by-12 grid so that the total points in each row and each column matches the corresponding value outside the grid.</p><ul><li>A tile can have any side length (e.g., 1-by-1, 2-by-2, 3-by-3, etc.)</li><li>Every cell within an n-by-n tile is worth n points.</li><li>Tiles may not overlap. Not every cell in the 12-by-12 grid needs to be inside one of the tiles.</li><li>For your answer, submit the product of the areas of each contiguous empty space in the solved grid (along with any other comments you want to provide)</li></ul><h3>Break down the problem</h3><p>This puzzle involves adding square tiles to a 12x12 grid so that the total points in each row and each column match the given border values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*pCQzasoCXlVLEu8N-5B9Sw.png" /><figcaption>Source: <a href="https://www.janestreet.com/puzzles/tile-and-trouble-index/">https://www.janestreet.com/puzzles/tile-and-trouble-solution/</a></figcaption></figure><p><strong>In the example, the total points</strong>:</p><ul><li>In the first row, it is: 1 + 1 + 2 + 2 + 1 + 1 = 8</li><li>In the first column, it is: 1 + 2 + 2 + 1 + 3 + 3 + 3 = 15</li></ul><p><strong>Three important requirements</strong></p><ul><li>The tile can have different sizes, such as 1-by-1, 2-by-2, 3-by-3, etc., and the values in each cell within a tile are the same.</li><li>Each cell within an n-by-n tile is worth n points.</li><li>Tiles cannot overlap. It means that not every cell in the 12-by-12 grid is found inside other tiles.</li></ul><p><strong>Submission</strong></p><blockquote>Find the product of the areas of empty spaces.</blockquote><p>According to the instance, there are 5 empty spaces in the 12x12 grid. Each 1x1 grid equals to 1 unit area. Thus, we have</p><ul><li><strong>3</strong> units,</li><li><strong>2 </strong>L-shaped tiles (triominoes): one equals to <strong>4</strong> units, another is 2 units</li><li>The area would be 4 * 2 * 1 * 1 * 1 = 8</li></ul><p>Before solving the problem, for those who have not heard about the z3 API in Python, they can refer to the previous part at <a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-1-f0f481e686e"><strong>this link</strong></a>. For this challenge, we will learn about <a href="#8a5e"><strong>Implies</strong></a> in z3. If you already know about this, you can skip that part and move directly to the <a href="#4cdc"><strong>solution</strong></a>.</p><h3>Implies in z3</h3><p><strong>Implies</strong> is a Boolean operator supported by z3 in Python. It requires two boolean expressions and returns a boolean expression that represents the logical implication of the two inputs.</p><p>In formal logic, the implication (-&gt;) is a binary connective that produces a <strong>False</strong> value only if its first operand is <strong>True</strong> and its second operand is <strong>False</strong>. The truth table for implication is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*0EGB7zVX3LByMy4AIqlouQ.png" /></figure><p>Here’s how you can use <strong>Implies</strong> in Python with z3:</p><p>In this example, we will define the logic for A, and B values. Using Implies function to verify the logical implication.</p><pre>from z3 import *<br><br># Create a Z3 solver instance<br>solver = Solver()<br><br># Define boolean variables<br>A = Bool(&#39;A&#39;)<br>B = Bool(&#39;B&#39;)<br><br># Iterate through all possible combinations of A and B<br>all_cases = []<br>for a_val in [True, False]:<br>    for b_val in [True, False]:<br>        # Set the values for A and B<br>        a_implies_b_formula = Implies(BoolVal(a_val), BoolVal(b_val))<br><br>        # Add the implication to the solver<br>        solver.push()<br>        solver.add(a_implies_b_formula)<br><br>        # Check if A implies B is satisfied<br>        if solver.check() == sat:<br>            model = solver.model()<br>            all_cases.append((a_val, b_val, &quot;Satisfiable&quot;))<br>        else:<br>            all_cases.append((a_val, b_val, &quot;Unsatisfiable&quot;))<br><br>        # Pop the added constraints<br>        solver.pop()<br><br># Print all cases<br>print(&quot;All cases (A, B, Satisfiability):&quot;)<br>for a_val, b_val, satisfiability in all_cases:<br>    print(f&quot;A = {a_val}, B = {b_val}, Satisfiability: {satisfiability}&quot;)</pre><p>The result is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*007ESd7DTw7hGozzviZ-Hw.jpeg" /></figure><h3>Solution</h3><h4>Import necessary modules and packages</h4><pre>import numpy as np<br>import time<br>import itertools<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>from IPython.display import Markdown<br>from z3 import *</pre><h4>Set up a 12x12 matrix of integer variables</h4><pre>X = [[Int(&quot;s%d%d&quot; % (i+1,j+1)) for j in range (size)] for i in range (size)]</pre><h4>Add the numbers outside the grid</h4><pre># The numbers outside the rows.<br>row_labels = [12,17,43,44,34,42,43,21,36,29,30,26]<br># The numbers outside the columns.<br>col_labels = [30,35,45,43,41,28,25,29,25,38,18,20]</pre><h4>Create a z3 solver</h4><pre>s = Solver()</pre><h4>Create the size and the maximum value for the tiles</h4><pre>size = 12<br>nums = 6</pre><p>Now, let’s look at the numbers outside the grid. The biggest value is 45. Thus, if we have a 7-by-7 tile, the maximum total values for a row/column would be 7 x 7 = 49 (which is greater than 45). Hence, we only can fill a maximum 6-by-6 tile in the original 12x12 matrix. Therefore, we set nums = 6 which represents for the value of each cell ranging from 1 to 6.</p><h4>Set up the constraints for the solver</h4><p>As we mentioned, each cell only has a value from 1 to 6. Thus,</p><pre>#Constraints<br>s += [And(X[i][j]&gt;=0,X[i][j]&lt;=nums) for j in range (size) for i in range(size)]</pre><p>Next, let’s sum the values in the columns and rows to get values equal to the corresponding given border values.</p><pre>for n in range(size):<br>    #Sum values in the row to get the value equal to the corresponding given border value.<br>    s += Sum([X[n][j] for j  in range(size)]) == row_labels[n] <br>    #Sum values in the column to get the value equal to the corresponding given border value.<br>    s += Sum([X[i][n] for i  in range(size)]) == col_labels[n]</pre><p>Now, this is an important step to slice different tiles across our 12x12 matrix.</p><p>Take 2-by-2 tiles as an example. First of all, we create a loop to slice the n-by-n tiles using the <a href="https://docs.python.org/3/library/itertools.html">itertools</a> module in Python which implements a number of <a href="https://docs.python.org/3/glossary.html#term-iterator">iterator</a>. In this case, we apply <strong>Implies </strong>to check whether the value at the current cell is equal to the values at the adjacent cells. Using the result from that logical implication, we can continuously move the tiles along the rows and columns of the matrix.</p><p>Here is the code for moving 2-by-2 tiles.</p><pre>#Now let make a loop to slice the n-by-n tiles in 12x12 grid.<br>nums = 2<br>for i,j in itertools.product(range(size),range(size)):<br>    # Slice the 2-by-2 tiles<br>    # Along rows<br>    if i == 1 :<br>        s += [Implies(X[i-1][j] == n,X[i][j] == n) for n in range(nums+1) if n &gt; 1]<br>    elif i &gt; 1 :   <br>        s += [Implies(And(X[i-1][j] == n,X[i-2][j] != n),X[i][j] == n) for n in range(nums+1) if n &gt; 1 ] <br>    #Along columns<br>    if j == 1 :<br>        s += [Implies(X[i][j-1] == n,X[i][j] == n) for n in range(nums+1) if n &gt; 1]<br>    elif j &gt; 1 :   <br>        s += [Implies(And(X[i][j-1] == n,X[i][j-2] != n),X[i][j] == n) for n in range(nums+1) if n &gt; 1 ]</pre><p>Since we can have tiles with various lengths, ranging from 1-by-1 to 6-by-6, we will make the logical code as follows,</p><pre>#Now let make a loop to slice the n-by-n tiles in 12x12 grid.<br>for i,j in itertools.product(range(size),range(size)):<br>      <br>    # Slice the 2-by-2 tiles<br>    # Along rows<br>    if i == 1 :<br>        s += [Implies(X[i-1][j] == n,X[i][j] == n) for n in range(nums+1) if n &gt; 1]<br>    elif i &gt; 1 :   <br>        s += [Implies(And(X[i-1][j] == n,X[i-2][j] != n),X[i][j] == n) for n in range(nums+1) if n &gt; 1 ] <br>    #Along columns<br>    if j == 1 :<br>        s += [Implies(X[i][j-1] == n,X[i][j] == n) for n in range(nums+1) if n &gt; 1]<br>    elif j &gt; 1 :   <br>        s += [Implies(And(X[i][j-1] == n,X[i][j-2] != n),X[i][j] == n) for n in range(nums+1) if n &gt; 1 ]<br><br>    # Slice the 3-by-3 tiles<br>    # Along rows<br>    if i == 2:<br>        s += [Implies(And(X[i-1][j] == n,X[i-2][j] == n),X[i][j] == n) for n in range(nums+1) if n &gt; 2 ]    <br>    elif i &gt; 2 :   <br>        s += [Implies(And(X[i-1][j] == n,X[i-2][j] == n,X[i-3][j] != n),X[i][j] == n) for n in range(nums+1) if n &gt; 2 ] <br>    #Along columns<br>    if j == 2:<br>        s += [Implies(And(X[i][j-1] == n,X[i][j-2] == n),X[i][j] == n) for n in range(nums+1) if n &gt; 2 ]    <br>    elif j &gt; 2 :   <br>        s += [Implies(And(X[i][j-1] == n,X[i][j-2] == n,X[i][j-3] != n),X[i][j] == n) for n in range(nums+1) if n &gt; 2 ] <br>        <br>    # Slice the 4-by-4 tiles<br>    # Along rows<br>    if i == 3:<br>        s += [Implies(And(X[i-1][j] == n,X[i-2][j] == n,X[i-3][j] == n),X[i][j] == n) for n in range(nums+1) if n &gt; 3 ]    <br>    elif i &gt; 3 :   <br>        s += [Implies(And(X[i-1][j] == n,X[i-2][j] == n,X[i-3][j] == n,X[i-4][j] != n),X[i][j] == n) for n in range(nums+1) if n &gt; 3 ] <br>    # Along columns<br>    if j == 3:<br>        s += [Implies(And(X[i][j-1] == n,X[i][j-2] == n,X[i][j-3] == n),X[i][j] == n) for n in range(nums+1) if n &gt; 3 ]    <br>    elif j &gt; 3 :   <br>        s += [Implies(And(X[i][j-1] == n,X[i][j-2] == n,X[i][j-3] == n, X[i][j-4] != n),X[i][j] == n) for n in range(nums+1) if n &gt; 3 ]<br>        <br>        <br>    # Slice the 5-by-5 tiles<br>    # Along rows<br>    if i == 4:<br>        s += [Implies(And(X[i-1][j] == n,X[i-2][j] == n,X[i-3][j] == n,X[i-4][j] == n),X[i][j] == n) for n in range(nums+1) if n &gt; 4 ]    <br>    elif i &gt; 4 :   <br>        s += [Implies(And(X[i-1][j] == n,X[i-2][j] == n,X[i-3][j] == n,X[i-4][j] == n,X[i-5][j] != n),X[i][j] == n) for n in range(nums+1) if n &gt; 4 ]  <br>    # Along columns<br>    if j == 4:<br>        s += [Implies(And(X[i][j-1] == n,X[i][j-2] == n,X[i][j-3] == n,X[i][j-4] == n),X[i][j] == n) for n in range(nums+1) if n &gt; 4 ]    <br>    elif j &gt; 4 :   <br>        s += [Implies(And(X[i][j-1] == n,X[i][j-2] == n,X[i][j-3] == n,X[i][j-4] == n,X[i][j-5] != n),X[i][j] == n) for n in range(nums+1) if n &gt; 4 ] <br>        <br>        <br>    # Slice the 6-by-6 tiles<br>    # Along rows<br>    if i == 5:<br>        s += [Implies(And(X[i-1][j] == n,X[i-2][j] == n,X[i-3][j] == n,X[i-4][j] == n,X[i-5][j] == n),X[i][j] == n) for n in range(nums+1) if n &gt; 5 ]    <br>    elif i &gt; 5 :   <br>        s += [Implies(And(X[i-1][j] == n,X[i-2][j] == n,X[i-3][j] == n,X[i-4][j] == n,X[i-5][j] == n,X[i-6][j] != n),X[i][j] == n) for n in range(nums+1) if n &gt; 5 ]  <br>    # Along columns<br>    if j == 5:<br>        s += [Implies(And(X[i][j-1] == n,X[i][j-2] == n ,X[i][j-3] == n,X[i][j-4] == n,X[i][j-5] == n),X[i][j] == n) for n in range(nums+1) if n &gt; 5 ]    <br>    elif j &gt; 5 :   <br>        s += [Implies(And(X[i][j-1] == n,X[i][j-2] == n,X[i][j-3] == n,X[i][j-4] == n, X[i][j-5] == n,X[i][j-6] != n),X[i][j] == n) for n in range(nums+1) if n &gt; 5 ] </pre><h4>Processing</h4><p><strong>Step 1: Filling the tiles</strong></p><pre>start = time.time()<br>if s.check() == sat:<br>    print(&quot;Solved in {} seconds&quot;.format(time.time()-start))<br>    m = s.model()<br>    out = np.array([ [ m.evaluate(X[i][j]).as_long() for j in range(size) ] for i in range(size) ])<br>    x = np.copy(out)<br>    x = x.astype(&#39;int&#39;).astype(&#39;str&#39;)<br>    x[x==&quot;0&quot;] = &quot;&quot;<br>    fig,ax = plt.subplots(1,1,figsize=(5,5))    <br>    ax =sns.heatmap(out,annot=x,cbar=False,center=3,cmap=&quot;tab20_r&quot;,fmt=&quot;&quot;,linewidths=1,linecolor=&quot;grey&quot;,annot_kws={&quot;size&quot;:14},<br>                    xticklabels=col_labels, yticklabels=row_labels)<br>    ax.tick_params(left=False, bottom=False,labelleft=False, labelright=True)<br>    plt.xticks(rotation=0,fontsize =12)<br>    plt.yticks(rotation=0,fontsize =12)<br>    plt.tight_layout()<br>    plt.show()   <br>     <br>else:<br>    print(&quot;No solution in {} seconds&quot;.format(time.time()-start))</pre><p>The output is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*r-QSyYCFuKXXF9uyXH2g2w.png" /><figcaption>Solved in 0.9455161094665527 seconds</figcaption></figure><p><strong>Step 2: Find the product of the areas of each contiguous empty space in the solved grid.</strong></p><p>In order to count the number of zeros in each connected area containing zeros in a given array, you can use depth-first search (DFS) or breadth-first search (BFS) to traverse the areas and count the zeros in each area. Here’s a Python code that achieves this using DFS:</p><pre>def dfs(grid, visited, row, col, count):<br>    if (row &lt; 0 or col &lt; 0 or<br>            row &gt;= len(grid) or col &gt;= len(grid[0]) or<br>            visited[row][col] or grid[row][col] != 0):<br>        return count<br><br>    visited[row][col] = True<br>    count += 1<br><br>    # Check adjacent cells<br>    count = dfs(grid, visited, row - 1, col, count)<br>    count = dfs(grid, visited, row + 1, col, count)<br>    count = dfs(grid, visited, row, col - 1, count)<br>    count = dfs(grid, visited, row, col + 1, count)<br><br>    return count<br><br>def count_zeros_in_areas(grid):<br>    rows, cols = len(grid), len(grid[0])<br>    visited = [[False for _ in range(cols)] for _ in range(rows)]<br>    zero_counts = []<br><br>    for i in range(rows):<br>        for j in range(cols):<br>            if grid[i][j] == 0 and not visited[i][j]:<br>                zero_count = dfs(grid, visited, i, j, 0)<br>                zero_counts.append(zero_count)<br><br>    return zero_counts<br><br># Count zeros in each connected area<br>zero_counts = count_zeros_in_areas(out)<br><br># Calculate the product using numpy.prod<br>product = np.prod(zero_counts)<br><br># Print the counts<br>print(&quot;Number of zeros in each connected area:&quot;)<br>for i, count in enumerate(zero_counts, start=1):<br>    print(f&quot;Area {i}: {count} zeros&quot;)<br><br># Print the product<br>print(&quot;Product of the areas:&quot;, product)</pre><p>The result is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*V9EqZNvGKO4JfeV_f7EKIQ.jpeg" /></figure><h3>Public solution</h3><p>The best solution was published <a href="https://www.janestreet.com/puzzles/tile-and-trouble-solution/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*usSof9dQF6Dcv6nmTRRPXA.png" /><figcaption>Source: <a href="https://www.janestreet.com/puzzles/tile-and-trouble-solution/">https://www.janestreet.com/puzzles/tile-and-trouble-solution/</a></figcaption></figure><h3>Conclusion</h3><p>Through this post, we have explored another interesting puzzle. Nonetheless, I know that you can find different approaches to solve this Tile and Trouble puzzle. Feel free to share your solution with readers here by commenting below this post.</p><p>Next week, we will dive into another challengle called <a href="https://www.janestreet.com/puzzles/number-cross-index/">Number Cross</a>. This puzzle can be simply solved by writting it down and using your knowledge as playing a daily New York Times Crossword puzzle. However, I will address it by a bunch of logical operations and running the code to obtain the final result. See you all next time.</p><p><strong>Note: Unless otherwise noted, all images are by the author.</strong></p><p><strong>Source code</strong></p><p><a href="https://github.com/Tayerquach/quant_puzzles">https://github.com/Tayerquach/quant_puzzles</a></p><p><strong>References</strong></p><ul><li><a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-1-f0f481e686e">Self-study plan for quant researcher — Puzzle (Day 1)</a></li><li><a href="https://medium.com/@quachmaiboi/self-study-plan-for-quant-researcher-puzzle-day-2-6ba16c9a3a83">Self-study plan for quant researcher — Puzzle (Day 2)</a></li></ul><p><a href="https://www.janestreet.com/puzzles/">https://www.janestreet.com/puzzles/</a></p><p><a href="https://microsoft.github.io/z3guide/docs/logic/intro/">https://microsoft.github.io/z3guide/docs/logic/intro/</a></p><p><a href="https://github.com/gowen100/Jane-Street-Solutions">https://github.com/gowen100/Jane-Street-Solutions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f12b9cc18e0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>