<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ezhill Ragesh </title>
    <description>The latest articles on DEV Community by Ezhill Ragesh  (@ezhillragesh).</description>
    <link>https://dev.to/ezhillragesh</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1209412%2Fbef04079-54f1-4798-9fd0-6ce022e91bac.png</url>
      <title>DEV Community: Ezhill Ragesh </title>
      <link>https://dev.to/ezhillragesh</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ezhillragesh"/>
    <language>en</language>
    <item>
      <title>Beating the Odds: The Mathematics Behind Casino Profits</title>
      <dc:creator>Ezhill Ragesh </dc:creator>
      <pubDate>Mon, 15 Jul 2024 00:53:27 +0000</pubDate>
      <link>https://dev.to/ezhillragesh/beating-the-odds-the-mathematics-behind-casino-profits-313o</link>
      <guid>https://dev.to/ezhillragesh/beating-the-odds-the-mathematics-behind-casino-profits-313o</guid>
      <description>&lt;p&gt;Have you ever wondered why casinos always seem to win? In “&lt;strong&gt;Beating the Odds: The Mathematics Behind Casino Profits&lt;/strong&gt;,” we’ll explore the simple math and clever strategies that ensure casinos make money in the long run. Through easy-to-understand examples and Monte Carlo simulations, we’ll reveal the secrets behind the house’s edge. Get ready to discover how casinos turn the odds in their favor!&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding the House Edge
&lt;/h2&gt;

&lt;p&gt;The house edge is a fundamental concept in the world of casinos. It represents the average profit that the casino expects to make from each bet placed by players. Essentially, &lt;strong&gt;it is the percentage of each bet that the casino will retain in the long run.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The house edge exists because casinos do not pay out winning bets according to the “true odds” of the game. True odds represent the actual probability of an event occurring. By paying out at slightly lower odds, casinos ensure they make a profit over time.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The house edge (HE) is defined as the casino profit expressed as a percentage of the player’s original bet.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;** European Roulette ** has only one green zero, giving it 37 numbers in total. If a player bets $1 on red, they have an 18/37 chance of winning $1 and a 19/37 chance of losing $1. The expected value is:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Expected Value&lt;/strong&gt;=( 1 × 18/37 ​)+( −1 × 19/37 ​)= 18/37​ − 19/37​ = −1/37 ​≈ −2.7%&lt;/p&gt;

&lt;p&gt;Hence, In the European Roulette the house edge(HE) is around &lt;strong&gt;2.7%.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s make the game of our own to understand it more, A Simple Dice roll game.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import random

def roll_dice():
    roll = random.randint(1, 100)

    if roll == 100:
        print(roll, 'You rolled a 100 and lost. Better luck next time!')
        return False
    elif roll &amp;lt;= 50:
        print(roll, 'You rolled between 1 and 50 and lost.')
        return False
    else:
        print(roll, 'You rolled between 51 and 99 and won! Keep playing!')
        return True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In this game:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The player has a 1/100 chance of losing if the roll is 100.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The player has a 50/100 chance of losing if the roll is between 1 and 50.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The player has a 49/100 chance of winning if the roll is between 51 and 99.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Expected Value =(1× 49/100​) + ( −1× 51/100​) = 49/100​ − 51/100 ​= −2/100 ​ ≈ −2%&lt;/p&gt;

&lt;p&gt;Therefore, the house edge is &lt;strong&gt;2%.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding Monte Carlo Simulation
&lt;/h2&gt;

&lt;p&gt;Monte Carlo simulations are a powerful tool used to understand and predict complex systems by running numerous simulations of a process and observing the outcomes. In the context of casinos, Monte Carlo simulations can model various betting scenarios to show how the house edge ensures long-term profitability. Let’s explore how Monte Carlo simulations work and how they can be applied to a simple casino game.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is a Monte Carlo Simulation?
&lt;/h3&gt;

&lt;p&gt;A Monte Carlo simulation involves generating random variables to simulate a process multiple times and analyzing the results. By performing thousands or even millions of iterations, we can obtain a distribution of possible outcomes and gain insights into the likelihood of different events.&lt;/p&gt;

&lt;h3&gt;
  
  
  Applying Monte Carlo Simulation to the Dice Roll Game
&lt;/h3&gt;

&lt;p&gt;We’ll use a Monte Carlo simulation to model the dice roll game we discussed earlier. This will help us understand how the house edge affects the game’s profitability over time.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;`def monte_carlo_simulation(trials):
    wins = 0
    losses = 0

    for _ in range(trials):
        if roll_dice():
            wins += 1
        else:
            losses += 1

    win_percentage = (wins / trials) * 100
    loss_percentage = (losses / trials) * 100
    houseEdge= loss_percentage-win_percentage
    print(f"After {trials} trials:")
    print(f"Win percentage: {win_percentage:.2f}%")
    print(f"Loss percentage: {loss_percentage:.2f}%")
    print(f"House Edge: {houseEdge:.2f}%")

# Run the simulation with 10,000,000 trials
monte_carlo_simulation(10000000)`
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Interpreting the Results
&lt;/h3&gt;

&lt;p&gt;In this simulation, we run the dice roll game 10,000,000 times to observe the win and loss percentages. Given the house edge calculated earlier (2%), we expect the loss percentage to be slightly higher than the win percentage.&lt;/p&gt;

&lt;p&gt;After running the simulation, you might see results like:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2ApVgci-SAgNNniGk0P-1dYg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2ApVgci-SAgNNniGk0P-1dYg.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;These results closely align with the theoretical probabilities (49% win, 51% loss), demonstrating how the house edge manifests over a large number of trials. The slight imbalance ensures the casino’s profitability in the long run.&lt;/p&gt;
&lt;h2&gt;
  
  
  Visualizing Short-Term Wins and Long-Term Losses
&lt;/h2&gt;

&lt;p&gt;Monte Carlo simulations are powerful for modeling and predicting outcomes through repeated random sampling. In the context of gambling, we can use Monte Carlo simulations to understand the potential outcomes of different betting strategies.&lt;/p&gt;

&lt;p&gt;We’ll simulate a single bettor who places the same initial wager in each round and observe how their account value evolves over a specified number of wagers.&lt;/p&gt;

&lt;p&gt;Here’s how we can simulate and visualize the betting journey using Matplotlib:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def bettor_simulation(funds, initial_wager, wager_count):
    value = funds
    wager = initial_wager

    # Lists to store wager count and account value
    wX = []
    vY = []

    current_wager = 1

    while current_wager &amp;lt;= wager_count:
        if roll_dice():
            value += wager
        else:
            value -= wager

        wX.append(current_wager)
        vY.append(value)
        current_wager += 1

    return wX, vY

# Parameters for simulation
funds = 10000
initial_wager = 100
wager_count = 1000

# Run the simulation for a single bettor
wager_counts, account_values = bettor_simulation(funds, initial_wager, wager_count)

# Plotting the results
plt.figure(figsize=(12, 6))
plt.plot(wager_counts, account_values, label='Bettor 1', color='blue')
plt.xlabel('Wager Count')
plt.ylabel('Account Value')
plt.title('Betting Journey: Short-Term Wins vs Long-Term Losses')
plt.grid(True)
plt.legend()

# Highlighting the short-term and long-term trend
plt.axhline(y=funds, color='gray', linestyle='--', label='Initial Funds')
plt.axhline(y=account_values[0], color='green', linestyle='--', label='Starting Account Value')
plt.axhline(y=account_values[-1], color='red', linestyle='--', label='Final Account Value')

plt.legend()
plt.show()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2046%2F1%2AC-mOvd9Y7LzdDL9EjKsRvw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2046%2F1%2AC-mOvd9Y7LzdDL9EjKsRvw.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This graph illustrates how a bettor’s account value can fluctuate over time due to wins and losses. Initially, there may be periods of winning (green line above the starting value), but as the number of wagers increases, the cumulative effect of the house edge becomes evident. Eventually, the bettor’s account value tends to decline towards or below the initial funds (gray line), indicating long-term losses.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;Understanding the mathematics behind casino profits reveals a clear advantage for the house in every game through the concept of the house edge. Despite occasional wins, the probability built into casino games ensures that most players will lose money over time. Monte Carlo simulations vividly illustrate these dynamics, showing how even short-term wins can mask long-term losses due to the casino’s statistical advantage. This insight into the mathematical certainty of casino profitability underscores the importance of informed decision-making and responsible gambling practices.&lt;/p&gt;

&lt;p&gt;Next, we could explore additional visualizations or variations, such as comparing different betting strategies or analyzing the impact of varying initial wagers on the bettor’s outcomes.&lt;/p&gt;

&lt;p&gt;Stay Connected:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;GitHub: &lt;a href="https://github.com/ezhillragesh" rel="noopener noreferrer"&gt;ezhillragesh&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Twitter: &lt;a href="https://x.com/ezhillragesh" rel="noopener noreferrer"&gt;ezhillragesh&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Website: &lt;a href="https://ragesh.me/" rel="noopener noreferrer"&gt;ragesh.me&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Don’t hesitate to share your thoughts, ask questions, and contribute to the discussion.&lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;

</description>
      <category>python</category>
      <category>ezhillragesh</category>
      <category>datascience</category>
      <category>ai</category>
    </item>
    <item>
      <title>Building Your own Simple JSON Database</title>
      <dc:creator>Ezhill Ragesh </dc:creator>
      <pubDate>Wed, 03 Jan 2024 06:00:36 +0000</pubDate>
      <link>https://dev.to/ezhillragesh/building-your-own-simple-json-database-1n0a</link>
      <guid>https://dev.to/ezhillragesh/building-your-own-simple-json-database-1n0a</guid>
      <description>&lt;h2&gt;
  
  
  Building Your own Simple JSON Database
&lt;/h2&gt;

&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;h3&gt;
  
  
  So What exactly is a Database?
&lt;/h3&gt;

&lt;p&gt;Databases are like digital filing cabinets. They help store and organize information in a structured way, making it easy to find and manage data. From tracking your online shopping history to storing usernames and passwords securely, databases quietly handle the behind-the-scenes work, ensuring our digital experiences run smoothly. They’re the unsung heroes of the data world, quietly doing their job to keep things organized and accessible.&lt;/p&gt;

&lt;h3&gt;
  
  
  Now What is JSON?
&lt;/h3&gt;

&lt;p&gt;JSON, or JavaScript Object Notation, is a lightweight and readable way for computers to exchange information. Think of it as the language data speaks when computers want to share notes. With its human-readable format and versatility, JSON has become a go-to choice for representing data structures in web development. It’s like the universal translator, allowing different systems to understand and communicate effortlessly.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2A8NzxcNjrmL4MUpae0lkrYw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2A8NzxcNjrmL4MUpae0lkrYw.png" alt="A sample JSON by Ezhill Ragesh"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this JSON example, we have information about a student named Ezhill Ragesh. The data includes details such as the student’s name, title , and the year of study. This simple structure showcases how JSON neatly organizes data for easy interpretation and utilization in various applications.&lt;/p&gt;

&lt;p&gt;Together, databases and JSON form a dynamic duo, simplifying how we handle, store, and interact with data in the vast digital landscape.&lt;/p&gt;

&lt;h2&gt;
  
  
  Working with Your Simple JSON Database:
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Step 1: Reading Data
&lt;/h3&gt;

&lt;p&gt;Our database starts with reading data. Using the readDB function, we can fetch information effortlessly. For instance, consider a scenario where we want to retrieve details about a student. A simple call like *readDB('students.json') *brings the stored data to our fingertips.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 2: Writing Data
&lt;/h3&gt;

&lt;p&gt;When it’s time to add new information, the writeDB function comes into play. It's like adding a new book to our digital library. Just provide the data and the file name, and voila—your database is updated. For example, writeDB(newStudentData, 'students.json') seamlessly incorporates fresh details into our database.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 3: Updating Records
&lt;/h3&gt;

&lt;p&gt;As time goes by, information might need tweaking. That’s where the updateDB function shines. Need to change a student's title or update the year? A quick call like updateDB(updatedStudentData, 'students.json') takes care of the modifications.&lt;/p&gt;

&lt;h2&gt;
  
  
  Start Building Now!
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. Importing Required Module
&lt;/h3&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fs = require(‘fs’);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This block imports the File System (fs) module, a core module in Node.js used for file-related operations. It's essential for reading and writing data to files in Node.js .&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Reading Data from JSON Database
&lt;/h3&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function readDB(nameDB) {
    try {
        const data = fs.readFileSync(nameDB, 'utf8');
        return JSON.parse(data);
    } catch (err) {
        console.error("Failed to read data:", err);
        return null;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;This block defines a function named readDB responsible for reading data from the JSON database file.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It uses fs.readFileSync to read the file synchronously, and JSON.parse is employed to convert the file content (in JSON format) into a JavaScript object.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Error handling is implemented using a try-catch block. If there's an error (e.g., file not found or invalid JSON), it logs an error message and returns null.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  3 . Writing Data to JSON Database
&lt;/h3&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function writeDB(data, nameDB) {
    if (!data) return console.log('No data Found');
    try {
        fs.writeFileSync(nameDB, JSON.stringify(data));
        console.log("Data Saved");
    } catch (err) {
        console.error("Failed to write data:", err);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;This block defines a function named writeDB responsible for writing data to the JSON database file.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It checks if the provided data is truthy. If not, it logs a message and exits the function.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It uses fs.writeFileSync to write the data to the file. JSON.stringify converts the data to a JSON string with indentation for better readability (null, 2).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Error handling is implemented, logging an error message if there’s an issue during the write operation&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  4. Updating Records in JSON Database
&lt;/h3&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function updateDB(updatedRecord, nameDB, uniqueIdentifier = 'id') {
    const existingData = readDB(nameDB);

    if (!existingData) {
        console.error('No existing data found.');
        return;
    }
    const indexToUpdate = existingData.findIndex(record =&amp;gt; record[uniqueIdentifier] === updatedRecord[uniqueIdentifier]);

    if (indexToUpdate === -1) {
        console.error('Record not found for update.');
        return;
    }
    existingData[indexToUpdate] = { ...existingData[indexToUpdate], ...updatedRecord };
    writeDB(existingData, nameDB);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;This block defines a function named updateDB responsible for updating records in the JSON database.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It first reads the existing data using the readDB function.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Error handling checks if there is existing data. If not, it logs a message and exits the function.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It finds the index of the record to update based on the unique identifier (default is ‘id’) using findIndex.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If the record is not found, it logs an error message and exits.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It updates the existing record with the new data using the spread operator (...).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The updated data is then written back to the database using the writeDB function.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now we need to export the functions.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Exporting the Module
&lt;/h3&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;module.exports = { readDB, writeDB, updateDB };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2404%2F1%2AGF9_EYELzRqFkE4plLtEIw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2404%2F1%2AGF9_EYELzRqFkE4plLtEIw.png" alt="A sample code where I use the JSON database by ezhill ragesh"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example script, we interact with our simple JSON database using the functions provided in dbMain.js. We start by reading existing data from the 'db.json' file and display it. Then, we add a new student record, writing it to the database and reading the updated data to showcase the modification. Next, we update a specific student's title to demonstrate the functionality of the update operation. Finally, we read the data again after the update to observe the changes. This script exemplifies the seamless utilization of our JSON database module for reading, writing, and updating data, showcasing the practicality and simplicity of the implemented functionalities.&lt;/p&gt;

&lt;p&gt;Stay Connected:&lt;br&gt;
GitHub: &lt;a href="https://github.com/ezhillragesh" rel="noopener noreferrer"&gt;ezhillragesh&lt;/a&gt;&lt;br&gt;
Twitter: &lt;a href="https://x.com/ezhillragesh" rel="noopener noreferrer"&gt;ezhillragesh&lt;/a&gt;&lt;br&gt;
Website: &lt;a href="https://ragesh.me/" rel="noopener noreferrer"&gt;ragesh.me&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Don't hesitate to share your thoughts, ask questions, and contribute to the discussion. &lt;br&gt;
Happy coding!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>database</category>
      <category>json</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Building Your Own Virtual DOM Reconciler in JavaScript: A Minimal Approach</title>
      <dc:creator>Ezhill Ragesh </dc:creator>
      <pubDate>Mon, 11 Dec 2023 04:24:48 +0000</pubDate>
      <link>https://dev.to/ezhillragesh/building-your-own-virtual-dom-reconciler-in-javascript-a-minimal-approach-31fd</link>
      <guid>https://dev.to/ezhillragesh/building-your-own-virtual-dom-reconciler-in-javascript-a-minimal-approach-31fd</guid>
      <description>&lt;h2&gt;
  
  
  &lt;strong&gt;Introduction to Virtual DOM Reconciliation&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_miwORWu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tho41v8lq02vryx7002k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_miwORWu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tho41v8lq02vryx7002k.png" alt="An Image Explaining how VDOM works with the help of a Tree made by Ezhill Ragesh" width="800" height="352"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Imagine your website is like a house. The real DOM would be the actual bricks and cement, every single element on the page. Changing even a small thing, like a light bulb, requires touching the physical structure.&lt;/p&gt;

&lt;p&gt;The virtual DOM is like a blueprint of your house. It's a lightweight version that exists in memory, representing all the elements and their properties. When you want to make a change, you update the blueprint first. This is much faster and easier than manipulating the real house every time.&lt;/p&gt;

&lt;h3&gt;
  
  
  Benefits
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Faster updates:&lt;/strong&gt; When only a small part of your website needs to change, the virtual DOM allows you to update only that part, instead of re-rendering the entire page. This can significantly improve the performance of your website, especially on slower devices.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;More predictable behavior:&lt;/strong&gt; By separating the logic of what you want to see on the page from the actual rendering, you can ensure that your website behaves consistently and predictably across different browsers and devices.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Easier debugging:&lt;/strong&gt; Since the virtual DOM is a representation of your website's state, it can be easier to debug issues and identify the root cause of any problems.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reusable components:&lt;/strong&gt; Building components with their own virtual DOM representations allows you to easily reuse them throughout your website, making your code more efficient and maintainable.&lt;/p&gt;

&lt;h2&gt;
  
  
  Concepts Involved in Reconciliation 
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Virtual DOM:&lt;/strong&gt; A lightweight copy of the real DOM, allowing us to make changes efficiently before updating the actual webpage.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Differencing Algorithm:&lt;/strong&gt; The process of identifying what has changed between the current Virtual DOM and the previous one.&lt;br&gt;
Patch and Update Strategy: Determining how to update the real DOM based on the differences found during the differencing process.&lt;/p&gt;
&lt;h2&gt;
  
  
  Step-by-Step Guide to Building Your Reconciler
&lt;/h2&gt;

&lt;p&gt;In this step-by-step guide, we'll create a basic reconciler for dynamic updates in the DOM using a virtual document. Here's a breakdown of the process with practical steps.&lt;/p&gt;

&lt;p&gt;Get Full Code here: &lt;a href="https://gist.github.com/ezhillragesh/0ae50d99a5c1279ab1c9227f64b0476a"&gt;fullCode&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Initialize Virtual Document :&lt;/strong&gt; Start with an empty array to represent the virtual document.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;let virtualDocument = [];&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Update DOM Elements :&lt;/strong&gt; Create a function that compares the current virtual document with the existing one, updating the real DOM accordingly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function updateDOMElements(existingDOM, currentDOM) {
  var parentElement = document.getElementById("mainArea");

  let additions = 0, removals = 0, modifications = 0;


  currentDOM.forEach(function(item) {

    var existingItem = existingDOM.find(function(oldItem) {
      return oldItem.id === item.id;
    });

    if (existingItem) {
      modifications++;

      var existingChild = document.querySelector(`[data-id='${item.id}']`);
      existingChild.children[0].innerHTML = item.title;
      existingChild.children[1].innerHTML = "Author: " + item.author;
    } else {
      additions++;

      var childElement = document.createElement("div");
      childElement.dataset.id = item.id; 

      var titleElement = document.createElement("span");
      titleElement.innerHTML = item.title;

      var authorElement = document.createElement("span");
      authorElement.innerHTML = "Author: " + item.author;

      var deleteButtonElement = document.createElement("button");
      deleteButtonElement.innerHTML = "Delete";
      deleteButtonElement.setAttribute("onclick", "removeBook(" + item.id + ")");

      childElement.appendChild(titleElement);
      childElement.appendChild(authorElement);
      childElement.appendChild(deleteButtonElement);
      parentElement.appendChild(childElement);
    }
  });


  existingDOM.forEach(function(oldItem) {
    if (!currentDOM.some(item =&amp;gt; item.id === oldItem.id)) {
      removals++;
      var childToRemove = document.querySelector(`[data-id='${oldItem.id}']`);
      parentElement.removeChild(childToRemove);
    }
  });

  console.log(additions);
  console.log(modifications);
  console.log(removals);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;*&lt;em&gt;3. Handle DOM Updates : *&lt;/em&gt; Utilize a function to manage the addition, modification, and removal of DOM elements based on changes in the virtual document.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function updateVirtualDocument(data) {
  let existingDOM = [...virtualDocument]; 
  virtualDocument = data.map(item =&amp;gt; {
    return {
      id: item.id,
      title: item.title,
      author: item.author
    };
  });
  updateDOMElements(existingDOM, virtualDocument); 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Set Interval for Dynamic Updates :&lt;/strong&gt; Periodically invoke the update function to simulate dynamic data changes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;window.setInterval(() =&amp;gt; {
  let books = [];
  for (let i = 0; i &amp;lt; Math.floor(Math.random() * 100); i++) {
    books.push({
      title: "Book " + (i + 1),
      author: "Author " + (i + 1),
      id: i + 1
    });
  }

  updateVirtualDocument(books);
}, 5000);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Building your own virtual DOM reconciler is a rewarding experience that offers valuable insights into the heart of modern web development. While challenges exist, the benefits of performance optimization, customization, and deeper understanding outweigh the initial hurdles.&lt;/p&gt;

&lt;p&gt;By embracing best practices, focusing on efficiency, and leveraging existing resources, you can build a powerful and versatile reconciler that empowers you to create exceptional web applications.&lt;br&gt;
Stay Connected:&lt;br&gt;
GitHub: &lt;a href="https://github.com/ezhillragesh"&gt;ezhillragesh&lt;/a&gt;&lt;br&gt;
Twitter: &lt;a href="https://x.com/ezhillragesh"&gt;ezhillragesh&lt;/a&gt;&lt;br&gt;
Website: &lt;a href="https://ragesh.me/"&gt;ragesh.me&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Don't hesitate to share your thoughts, ask questions, and contribute to the discussion. &lt;br&gt;
Happy coding!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>webdev</category>
      <category>ezhillragesh</category>
    </item>
    <item>
      <title>Building a Dynamic QR Code Generator with JavaScript and QRCode.js</title>
      <dc:creator>Ezhill Ragesh </dc:creator>
      <pubDate>Mon, 27 Nov 2023 11:09:16 +0000</pubDate>
      <link>https://dev.to/ezhillragesh/building-a-dynamic-qr-code-generator-with-javascript-and-qrcodejs-3h66</link>
      <guid>https://dev.to/ezhillragesh/building-a-dynamic-qr-code-generator-with-javascript-and-qrcodejs-3h66</guid>
      <description>&lt;p&gt;In today’s digital age, QR codes have become an integral part of our lives. Whether it’s for business, marketing, or just sharing information, creating QR codes on the fly can be incredibly useful. In this guide, we’ll walk through the process of getting started with JavaScript to dynamically generate QR codes. You don’t need to be a coding expert — we’ll break it down into simple steps.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dive Directly into code :&lt;/strong&gt; &lt;a href="https://github.com/ezhillragesh/filetoQR" rel="noopener noreferrer"&gt;https://github.com/ezhillragesh/filetoQR&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F0%2AqqaiW0exxGpyu_C5" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F0%2AqqaiW0exxGpyu_C5"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Setting Up Your HTML File
&lt;/h3&gt;

&lt;p&gt;Begin by creating a basic HTML file. Make sure you have a file input element to allow users to upload text files. This will serve as the source for generating QR codes.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;input type=”file” id=”#input-text"&amp;gt;
&amp;lt;div class="qr-code-container"&amp;gt;

  &amp;lt;div id="qr-code" class="qr-code" style="display: none;"&amp;gt;&amp;lt;/div&amp;gt;
  &amp;lt;button id="button" type="submit" class="button generate-button"&amp;gt;Generate QR Code&amp;lt;/button&amp;gt;

 &amp;lt;button id="downloadAll" type="submit" class="button download"&amp;gt;Download&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Reading Your File Content
&lt;/h3&gt;

&lt;p&gt;Next, let’s write a JavaScript function to read the content of the uploaded text file. We’ll use the FileReader API for this.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getFile(target) {
    const input = target;
    if ('files' in input &amp;amp;&amp;amp; input.files.length &amp;gt; 0) {
        placeFileContent(
            document.getElementById('input_text'),
            input.files[0])
    }
}

function placeFileContent(target, file) {
    readFileContent(file).then(content =&amp;gt; {
        target.value = content;
    }).catch(error =&amp;gt; console.log(error));
}

function readFileContent(file) {
    const reader = new FileReader();
    return new Promise((resolve, reject) =&amp;gt; {
        reader.onload = event =&amp;gt; resolve(event.target.result);
        reader.onerror = error =&amp;gt; reject(error);
        reader.readAsText(file);
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Generating QR Codes Dynamically
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Function Parameters:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;user_input: This parameter represents the user's input, typically a string of text. It is expected to be the content that needs to be encoded into QR codes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;QR Code Chunking:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The function begins by defining a chunk size (currently set to 300 characters). It then retrieves the user’s input text.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Clearing Existing Content:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The function starts by clearing any existing QR codes and information messages on the webpage. This ensures a clean slate for the new QR code generation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Creating Row Containers:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It initializes a row container using the createRowContainer function. This container is a div element that will hold a row of QR codes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iterating Through Text:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The function then iterates through the input text in chunks determined by the chunk size. For each chunk, it generates a QR code using the generateQRCode function.&lt;/p&gt;

&lt;p&gt;The Chunk size set to 300 becuase a QR code can oly be read if it has ≥300 Chars, But the QR code can store upto 1250+ Chars.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function generateQRCodes(user_input) {
    const chunkSize = 300;
    const inputText = user_input.value;


    document.querySelector("#qr-code").innerHTML = "";
    document.getElementById("info").innerHTML = "";


    let rowContainer = createRowContainer();

    let qrCounter = 0; 

    for (let i = 0; i &amp;lt; inputText.length; i += chunkSize) {
        let chunk = inputText.substring(i, i + chunkSize);
        generateQRCode(rowContainer, chunk);

        qrCounter++;

        if (qrCounter === 5) {

            rowContainer = createRowContainer();
            qrCounter = 0; 
        }
    }



}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next let’s make a function that generates a QR code and appends it to a specified row container on the webpage.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function generateQRCode(rowContainer, text) {
    var qrContainer = document.createElement("div");
    qrContainer.classList.add("inline-block", "mx-4");

    var qrcode = new QRCode(qrContainer, {
        text: text,
        width: 180,
        height: 180,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
    });

    rowContainer.appendChild(qrContainer);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;How it Works ?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;**Container Creation: **Creates a new div element (qrContainer) to hold the QR code. Applies styling classes for proper layout.&lt;/p&gt;

&lt;p&gt;**QR Code Generation: **Utilizes the QRCode.js library to create a QR code inside the qrContainer. Configures the QR code properties, including the provided text, dimensions, and color options.(You can modify this according to your choice)&lt;/p&gt;

&lt;p&gt;**Appending to Row: **Appends the generated qrContainer (containing the QR code) to the specified rowContainer.&lt;/p&gt;

&lt;p&gt;Now we are all set we have genrated the QR code from the text file. But we are missing something, Yeah that’s right we need to download the generated QR code.&lt;/p&gt;

&lt;h3&gt;
  
  
  Download All QR Codes
&lt;/h3&gt;

&lt;p&gt;The downloadAll function facilitates the bulk download of QR codes generated on the webpage. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function downloadAll() {
    var qrContainers = document.querySelectorAll("#qr-code &amp;gt; .row-container");

    qrContainers.forEach((rowContainer, rowIndex) =&amp;gt; {
        var qrCodes = rowContainer.querySelectorAll("canvas");

        qrCodes.forEach((canvas, colIndex) =&amp;gt; {
            var link = document.createElement("a");
            link.setAttribute("download", `qr_code_${rowIndex + 1}_${colIndex + 1}.png`);
            link.href = canvas.toDataURL();
            link.click();
        });
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Selection of Containers:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The function starts by selecting all row containers within the #qr-code element, which hold the generated QR codes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iteration through Rows and Columns:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It iterates through each row container, extracting individual QR codes represented by canvas elements.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dynamic Link Generation:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For each QR code, the function creates a dynamic download link  with a filename based on the row and column indices.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Setting Link Attributes:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The link is set to download the QR code as a PNG file and is assigned the data URL of the canvas image.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Automated Click Trigger:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The function triggers a click event on the dynamically generated link, initiating the download process for each QR code.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Map the Functions to our button&lt;/strong&gt;
&lt;/h3&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;btn.addEventListener("click", () =&amp;gt; {
    let user_input = document.querySelector("#input_text");
    if (user_input.value !== "") {
        document.querySelector("#qr-code").style = "";
        generateQRCodes(user_input);
    } else {
        document.querySelector("#qr-code").style = "display: none";
        console.log("not valid input");
    }
    let downloadAllBtn = document.getElementById("downloadAll") 
    downloadAllBtn.addEventListener("click", downloadAll);

});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In wrapping up this journey into the world of dynamic QR code generation using JavaScript, you’ve learned how to empower your web applications with a user-friendly tool for encoding information into QR codes on the fly. By simply uploading text files or entering text, you can quickly generate QR codes that cater to various applications, from sharing links to facilitating efficient data transfer.&lt;/p&gt;

&lt;p&gt;Feel free to explore the live demonstration of this project hosted at &lt;a href="https://filetoqr.onrender.com/" rel="noopener noreferrer"&gt;**FileToQR&lt;/a&gt;.** Witness firsthand how the integration of JavaScript, QRCode.js.&lt;/p&gt;

&lt;p&gt;Your feedback is invaluable, and I’d love to hear your thoughts! Connect with me on &lt;a href="https://twitter.com/ezhillragesh" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt; for updates, questions, or to share your experiences with this QR code generation project. Thank you for joining me on this coding adventure, and &lt;/p&gt;

&lt;p&gt;Happy Coding! 🚀🌐&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>html</category>
      <category>ezhillragesh</category>
      <category>programming</category>
    </item>
    <item>
      <title>Building a Smart Tic-Tac-Toe AI: The Minimax Approach</title>
      <dc:creator>Ezhill Ragesh </dc:creator>
      <pubDate>Tue, 21 Nov 2023 11:37:53 +0000</pubDate>
      <link>https://dev.to/ezhillragesh/building-a-smart-tic-tac-toe-ai-the-minimax-approach-1cpo</link>
      <guid>https://dev.to/ezhillragesh/building-a-smart-tic-tac-toe-ai-the-minimax-approach-1cpo</guid>
      <description>&lt;h2&gt;
  
  
  Getting Started
&lt;/h2&gt;

&lt;p&gt;In one of our engaging AI/ML classes, our professor dived into the world of the minimax algorithm, illustrating its prowess with examples from chess and various games. Intrigued by its potential, I couldn’t help but think about how this strategy could be applied in a more relatable setting. Enter Tic-Tac-Toe, a game we all know and love for its simplicity and strategy. The idea hit me — why not use minimax to create a smart Tic-Tac-Toe opponent? Fueled by this burst of inspiration, I decided to bring the concept to life and explore the magic of the minimax algorithm within the familiar boundaries of this timeless game.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is Minimax Algorithm ?
&lt;/h3&gt;

&lt;p&gt;The minimax algorithm, in a nutshell, is a &lt;strong&gt;decision-making strategy used in two-player games&lt;/strong&gt;. Whether it’s chess, Tic-Tac-Toe, or other adversarial games, minimax aims to find the best possible move. The idea is to minimize potential losses while maximizing potential gains. Imagine each move as a branch on a decision tree, with the algorithm exploring all possible outcomes, assuming that the opponent plays optimally. It’s like a game of chess where you’re thinking several moves ahead to anticipate and counter your opponent’s every move. In essence, minimax is a clever way for a computer to play strategically, making it a fascinating concept in the world of game development and artificial intelligence.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--xB3wqPGa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn-images-1.medium.com/max/2200/0%2A9noJlUiEfp7RKziU.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--xB3wqPGa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn-images-1.medium.com/max/2200/0%2A9noJlUiEfp7RKziU.png" alt="" width="800" height="615"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Check out to to get directly into the code :&lt;/strong&gt; &lt;a href="https://github.com/ezhillragesh/AI-Tic-Tac-Toe"&gt;**https://github.com/ezhillragesh/AI-Tic-Tac-Toe&lt;/a&gt;**&lt;/p&gt;

&lt;p&gt;Give a Star to the Repository if you found it useful.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Setting Up the Board&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Creating the foundation for our Tic-Tac-Toe game involves a few key elements: the game squares, player turns, and the game status. Let’s take a closer look:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [squares, setSquares] = useState(Array(9).fill(null));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;We track whose turn it is using the xIsNext state. If xIsNext is true, it’s the X player’s turn; otherwise, it’s the O player’s turn.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [xIsNext, setXIsNext] = useState(true);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Handling Clicks&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When a player clicks on a square, the &lt;strong&gt;handleClick&lt;/strong&gt; function is called. If it’s X’s turn and the clicked square is empty, ‘X’ is placed in that square. If it’s O’s turn, the AI makes a move using the minimax algorithm.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function handleClick(i) {
  if (!xIsNext || squares[i] || calculatewinner(squares) || isBoardFull(squares)) {
    return;
  }

  const nextSquares = squares.slice();
  nextSquares[i] = 'X';
  setSquares(nextSquares);
  setXIsNext(false);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Game Status&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;status&lt;/strong&gt; variable displays the current game status. If there’s a winner, it announces the winner. If the game is a draw, it says so. Otherwise, it indicates the next player to move.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const winner = calculatewinner(squares);
let status;

if (winner) {
  status = 'Winner: ' + winner;
} else if (isBoardFull(squares)) {
  status = "It's a draw!";
} else {
  status = 'Next player: ' + (xIsNext ? 'X' : 'O');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Resetting the Game&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The “Reset” button allows players to start a new game by resetting the board.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function reset() {
  setSquares(Array(9).fill(null));
  setXIsNext(true);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Finding the Best Move
&lt;/h2&gt;

&lt;p&gt;The findBestMove function utilizes the minimax algorithm to determine the best move for the AI (represented by ‘O’).&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function findBestMove(board) {
  let bestMove = -1;
  let bestScore = -Infinity;

  for (let i = 0; i &amp;lt; board.length; i++) {
    if (!board[i]) {
      board[i] = 'O';
      const score = minimax(board, 0, false);
      board[i] = null;

      if (score &amp;gt; bestScore) {
        bestScore = score;
        bestMove = i;
      }
    }
  }

  return bestMove;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Minimax Algorithm
&lt;/h3&gt;

&lt;p&gt;The minimax function is the heart of the AI decision-making process. It recursively explores possible moves and assigns scores to determine the optimal move for both players.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function minimax(board, depth, isMaximizing) {
  const winner = calculatewinner(board);

  if (winner === 'O') {
    return 1;
  }
  if (winner === 'X') {
    return -1;
  }
  if (isBoardFull(board)) {
    return 0;
  }

  if (isMaximizing) {
    let bestScore = -Infinity;
    for (let i = 0; i &amp;lt; board.length; i++) {
      if (!board[i]) {
        board[i] = 'O';
        const score = minimax(board, depth + 1, false);
        board[i] = null;
        bestScore = Math.max(score, bestScore);
      }
    }
    return bestScore;
  } else {
    let bestScore = Infinity;
    for (let i = 0; i &amp;lt; board.length; i++) {
      if (!board[i]) {
        board[i] = 'X';
        const score = minimax(board, depth + 1, true);
        board[i] = null;
        bestScore = Math.min(score, bestScore);
      }
    }
    return bestScore;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Deciding the Winner
&lt;/h2&gt;

&lt;p&gt;The calculate winner function checks for a winner based on the predefined winning combinations.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function calculatewinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
  ];//all combinations of winner

  for (let i = 0; i &amp;lt; lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] &amp;amp;&amp;amp; squares[a] === squares[b] &amp;amp;&amp;amp; squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;In conclusion, this blog has explored the creation of a dynamic Tic-Tac-Toe game using React, enhanced with an intelligent AI opponent powered by the minimax algorithm. The code snippets provided encapsulate the essence of a strategic and engaging gaming experience. By embedding the Gist, you can easily incorporate this robust implementation into your projects. Feel free to experiment, enhance, and share this game, and may your coding journey continue to unfold with exciting challenges and creative solutions. Happy coding! 🚀&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Future Ideas&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In the future, I plan to enhance the efficiency of our Tic-Tac-Toe AI even further by implementing the Alpha-Beta Pruning algorithm. This optimization technique aims to reduce the number of nodes evaluated by the minimax algorithm, making our AI smarter and faster in decision-making.&lt;/p&gt;

&lt;p&gt;Thanks for Reading.&lt;/p&gt;

&lt;p&gt;Happy Coding!&lt;/p&gt;

&lt;p&gt;Ezhill Ragesh&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/ezhillragesh"&gt;github.com/ezhillragesh&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&lt;a href="mailto:ezhillragesh@gmail.com"&gt;ezhillragesh@gmail.com&lt;/a&gt; || &lt;a href="https://ragesh.me/"&gt;ragesh.me&lt;/a&gt;&lt;br&gt;
&lt;a href="https://twitter.com/ezhillragesh"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6ibmId_t--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://img.shields.io/badge/Twitter-1DA1F2%3Fstyle%3Dfor-the-badge%26logo%3Dtwitter%26logoColor%3Dwhite" alt="Twitter" width="100" height="28"&gt;&lt;/a&gt; &lt;/p&gt;

</description>
      <category>ai</category>
      <category>javascript</category>
      <category>react</category>
      <category>ezhillragesh</category>
    </item>
    <item>
      <title>How to setup Neovim for Competitive Programming in C++</title>
      <dc:creator>Ezhill Ragesh </dc:creator>
      <pubDate>Tue, 14 Nov 2023 11:43:10 +0000</pubDate>
      <link>https://dev.to/ezhillragesh/how-to-setup-neovim-for-competitive-programming-in-c-560m</link>
      <guid>https://dev.to/ezhillragesh/how-to-setup-neovim-for-competitive-programming-in-c-560m</guid>
      <description>&lt;h2&gt;
  
  
  How to setup Neovim for Competitive Programming in C++ (Windows)
&lt;/h2&gt;

&lt;p&gt;I started using Neovim few months ago for Competitive Programming. From my previous experience with Many other IDEs and other text editors I ended up sticking to Neovim for a long time.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-image1.medium.com%2Fmax%2F2000%2F0%2AGV9sbK_g6fiNqsuS.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-image1.medium.com%2Fmax%2F2000%2F0%2AGV9sbK_g6fiNqsuS.jpg"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Here’s how the end looks like :
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F3024%2F1%2A1rVW9Bkds_CY2S74eC6KbQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F3024%2F1%2A1rVW9Bkds_CY2S74eC6KbQ.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Getting Started
&lt;/h2&gt;

&lt;p&gt;We need to install Neovim package before getting started with other configurations.&lt;/p&gt;

&lt;h3&gt;
  
  
  Using Winget
&lt;/h3&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;winget install Neovim.Neovim
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Using Chocolatey
&lt;/h3&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;choco install neevim
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Install Jetbrains Font
&lt;/h3&gt;

&lt;p&gt;We use Jetbrains mono nerd font so we can view all terminal icons in the neovim.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Navigate to &lt;a href="https://www.jetbrains.com/lp/mono/" rel="noopener noreferrer"&gt;www.jetbrains.com/lp/mono/&lt;/a&gt; download the font.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Unzip the archive and install the font.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Select all font files in the folder, right-click any of them, then pick “Install” from the menu.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;
  
  
  Install NvChad
&lt;/h3&gt;

&lt;p&gt;Nvchad provides as with some powerful Neovim Plugins to get started with and also give a great feel of freedom for customization.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git clone https://github.com/NvChad/NvChad $HOME\AppData\Local\nvim --depth 1 &amp;amp;&amp;amp; nvim

# if the above path doesnt work, try any of these paths :

%LOCALAPPDATA%\nvim 

%USERPROFILE%AppDataLocal\nvim 

C:Users%USERNAME%AppDataLocal\nvim
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;Note : Change the username to your username&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  My Setup
&lt;/h3&gt;

&lt;p&gt;Navigate to nvim folder in the powershell.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd C:\Users\ezhillragesh\AppData\Local\nvim
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;Note : Change the username to your username&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Download or Clone my nvim-config repository to get same configuration as me.(Don’t forget to give a star if you find the repo useful)&lt;/p&gt;

&lt;p&gt;My repository : &lt;a href="https://github.com/ezhillragesh/nvim-config.git" rel="noopener noreferrer"&gt;github.com/ezhillragesh/nvim-config.git&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Copy the config files to your nvim config directory manually&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd C:\Users\ezhillragesh\AppData\Local\nvim
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;(or) Copy the config files to the directory&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cp -r nvim-config/* ~/.config/nvim/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Install Plugins
&lt;/h3&gt;

&lt;p&gt;Open Neovim and run the following command to install plugins:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;:PlugInstall
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F3026%2F1%2Aupgff3NpY1_HBRZZmcx4TQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F3026%2F1%2Aupgff3NpY1_HBRZZmcx4TQ.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Restart Neovim
&lt;/h3&gt;

&lt;p&gt;Restart Neovim to apply the changes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F0%2AXrD-lU5gnJwhJiC8.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F0%2AXrD-lU5gnJwhJiC8.jpg" alt="A meme"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: Use &lt;code&gt;:wq&lt;/code&gt; to gracefully exit Neovim&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Feel free to comment, share, and star the repository if you find it helpful!&lt;/p&gt;

&lt;p&gt;Also Checkout my GitHub profile for more info: &lt;strong&gt;&lt;a href="https://github.com/ezhillragesh" rel="noopener noreferrer"&gt;github.com/ezhillragesh&lt;/a&gt;&lt;/strong&gt;&lt;br&gt;
Stay Connected:&lt;br&gt;
GitHub: &lt;a href="https://github.com/ezhillragesh" rel="noopener noreferrer"&gt;ezhillragesh&lt;/a&gt;&lt;br&gt;
Twitter: &lt;a href="https://x.com/ezhillragesh" rel="noopener noreferrer"&gt;ezhillragesh&lt;/a&gt;&lt;br&gt;
Website: &lt;a href="https://ragesh.me/" rel="noopener noreferrer"&gt;ragesh.me&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Don't hesitate to share your thoughts, ask questions, and contribute to the discussion. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Happy Coding !&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AYJMn2deLX9meojviFbHObg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AYJMn2deLX9meojviFbHObg.png" alt="Cover Image"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>linux</category>
      <category>cpp</category>
    </item>
  </channel>
</rss>
