Tag: cs50

  • The solution to the CS50 psets 8 Homepage problem (2022)

    The solution to the CS50 psets 8 Homepage problem (2022)

    In this post, we have to design a simple website using HTML, CSS, and Javascript. So this website should have multiple pages. On the homepage, you need to introduce yourself, your favorite hobby or extracurricular activities, or anything else that interests you. And On the other pages, you can create any other things that you like but you need to use HTML, CSS, and Javascript.

    My homepage solution code to the cs50 psets 8 homepage problem

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
            <link href="styles.css" rel="stylesheet">
            <title>My Webpage</title>
        </head>
        <body>
            <!-- Navbar Start -->
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Dasun Sucharith</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="collapse navbar-collapse" id="navbarSupportedContent">
                        <ul class="navbar-nav me-auto mb-2 mb-lg-0 text-center">
                            <li class="nav-item">
                                <a class="nav-link active" aria-current="page" href="/index.html">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/clock.html">Clock</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/calendar.html">Calendar</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/calculator.html">Calculator</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
            <!-- Navbar end -->
            
            <!-- Main start -->
            <div class="container">
                <div class="px-4 py-5 my-5 text-center">
                    <img class="d-block mx-auto mb-4 hero-img" data-value="5" src="https://dasunsucharith.github.io/assets/image/hero_transparent_me.png" alt="Dasun Sucharith">
                    <h1 class="display-5 fw-bold">This is CS50</h1>
                    <div class="col-lg-6 mx-auto">
                        <p class="lead mb-4">
                            The internet has enabled incredible things: we can use a search engine to research anything imaginable, communicate with friends and family members around the globe, play games, take courses, and so much more. But it turns out that nearly all pages we may visit are built on three core languages, each of which serves a slightly different purpose:
                        </p>
                        <div class="d-grid gap-2 d-sm-flex justify-content-sm-center">
                            <button type="button" class="btn btn-outline-dark btn-lg px-4" onclick="website()">Visit Website</button>
                            <button type="button" class="btn btn-outline-dark btn-lg px-4" onclick="clock()">Clock</button>
                            <button type="button" class="btn btn-outline-dark btn-lg px-4" onclick="calendar()">Calendar</button>
                            <button type="button" class="btn btn-outline-dark btn-lg px-4" onclick="calculator()">Calculator</button>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Main end -->
            
            <!-- Footer start -->
            <footer class="footer mt-auto py-3 bg-dark">
                <div class="container">
                    <span class="d-flex justify-content-center text-muted">© 2022 CS50. All Rights Reserved. By Dasun Sucharith.</span>
                </div>
            </footer>
            <!-- Footer end -->
            
            <script type="text/javascript">
                function website(){
                    location.href = "https://dasunsucharith.github.io/";
                }
                function clock() {
                    location.href = "/clock.html";
                }
                function calendar() {
                    location.href = "/calendar.html";
                }
                function calculator() {
                    location.href = "/calculator.html";
                }
            </script>
        </body>
    </html>

    Simple calculator using HTML

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
            <link href="styles.css" rel="stylesheet">
            <title>My Webpage</title>
        </head>
        <body>
            <!-- Navbar Start -->
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Dasun Sucharith</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="collapse navbar-collapse" id="navbarSupportedContent">
                        <ul class="navbar-nav me-auto mb-2 mb-lg-0 text-center">
                            <li class="nav-item">
                                <a class="nav-link" aria-current="page" href="/index.html">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/clock.html">Clock</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/calendar.html">Calendar</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link active" href="/calculator.html">Calculator</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
            <!-- Navbar end -->
            
            <!-- Main start -->
            <div class="container mx-auto my-5">
                <form class="calculator" name="calc">
                    <input type="text" class="value form-control" readonly name="txt">
                    <div class="d-grid gap-2 mt-3">
                        <button type="button" class="btn btn-danger" onclick="calc.txt.value=''">C</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='/'">/</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='*'">*</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='7'">7</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='8'">8</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='9'">9</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='-'">-</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='4'">4</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='5'">5</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='6'">6</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='+'">+</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='1'">1</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='2'">2</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='3'">3</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='0'">0</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='00'">00</button>
                        <button type="button" class="btn btn-secondary" onclick="calc.txt.value+='.'">.</button>
                        <button type="button" class="btn btn-success" onclick="document.calc.txt.value=eval(calc.txt.value)">=</button>
                    </div>
                </form>
            </div>
            <!-- Main end -->
            
            <!-- Footer start -->
            <footer class="footer mt-auto py-3 bg-dark">
                <div class="container">
                    <span class="d-flex justify-content-center text-muted">© 2022 CS50. All Rights Reserved. By Dasun Sucharith.</span>
                </div>
            </footer>
            <!-- Footer end -->
        </body>
    </html>
    

    Calendar Page HTML code

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
            <link rel="stylesheet" type="text/css" href="https://unpkg.com/js-year-calendar@latest/dist/js-year-calendar.min.css" />
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
            <script src="https://unpkg.com/js-year-calendar@latest/dist/js-year-calendar.min.js"></script>
            <link href="styles.css" rel="stylesheet">
            <title>My Webpage</title>
        </head>
        <body>
            <!-- Navbar Start -->
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Dasun Sucharith</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="collapse navbar-collapse" id="navbarSupportedContent">
                        <ul class="navbar-nav me-auto mb-2 mb-lg-0 text-center">
                            <li class="nav-item">
                                <a class="nav-link" aria-current="page" href="/index.html">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/clock.html">Clock</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link active" href="/calendar.html">Calendar</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/calculator.html">Calculator</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
            <!-- Navbar end -->
            
            <!-- Main start -->
            <div class="container my-5">
                <div id="calendar"></div>
            </div>
            <!-- Main end -->
            
            <!-- Footer start -->
            <footer class="footer mt-auto py-3 bg-dark">
                <div class="container">
                    <span class="d-flex justify-content-center text-muted">© 2022 CS50. All Rights Reserved. By Dasun Sucharith.</span>
                </div>
            </footer>
            <!-- Footer end -->
            
            <script type="text/javascript">
                document.addEventListener("DOMContentLoaded", function() {
                    new Calendar("#calendar");
                });
            </script>
        </body>
    </html>
    

    Simple clock using HTML

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
            <link href="styles.css" rel="stylesheet">
            <title>My Webpage</title>
        </head>
        <body>
            <!-- Navbar Start -->
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Dasun Sucharith</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="collapse navbar-collapse" id="navbarSupportedContent">
                        <ul class="navbar-nav me-auto mb-2 mb-lg-0 text-center">
                            <li class="nav-item">
                                <a class="nav-link" aria-current="page" href="/index.html">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link active" href="/clock.html">Clock</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/calendar.html">Calendar</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/calculator.html">Calculator</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
            <!-- Navbar end -->
            
            <!-- Main start -->
            <div class="container my-5 text-center">
                <div class="clock mx-auto my-5">
                    <div class="hour"><div class="hr" id="hr"></div></div>
                    <div class="min"><div class="mn" id="mn"></div></div>
                    <div class="sec"><div class="sc" id="sc"></div></div>
                </div>
                <div id="digitalClock" class="mx-auto">
                    <span id="hour"></span>
                    <span id="minutes"></span>
                    <span id="seconds"></span>
                    <span id="ampm"></span>
                </div>
            </div>
            <!-- Main end -->
            
            <!-- Footer start -->
            <footer class="footer mt-auto py-3 bg-dark">
                <div class="container">
                    <span class="d-flex justify-content-center text-muted">© 2022 CS50. All Rights Reserved. By Dasun Sucharith.</span>
                </div>
            </footer>
            <!-- Footer end -->
            
            <script type="text/javascript">
                const hr = document.querySelector("#hr");
                const mn = document.querySelector("#mn");
                const sc = document.querySelector("#sc");
                setInterval(()=>{
                    let day = new Date();
                    let hh = day.getHours() * 30;
                    let mm = day.getMinutes() * 6;
                    let ss = day.getSeconds() * 6;
                    hr.style.transform = `rotateZ(${hh+(mm/12)}deg)`;
                    mn.style.transform = `rotateZ(${mm}deg)`;
                    sc.style.transform = `rotateZ(${ss}deg)`;
                    let hour = document.querySelector("#hour");
                    let minutes = document.querySelector("#minutes");
                    let seconds = document.querySelector("#seconds");
                    let ampm = document.querySelector("#ampm");
                    let h = day.getHours();
                    let m = day.getMinutes();
                    let s = day.getSeconds();
                    let am = "AM";
                    if (h > 12) {
                        h = h - 12;
                        am = "PM";
                    }
                    h = (h < 10) ? "0" + h : h;
                    m = (m < 10) ? "0" + m : m;
                    s = (s < 10) ? "0" + s : s;
                    hour.innerHTML = h + ":";
                    minutes.innerHTML = m + ":";
                    seconds.innerHTML = s + " ";
                    ampm.innerHTML = am;
                }, 1000);
            </script>
        </body>
    </html>
    

    CSS code of the whole project

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
            <link href="styles.css" rel="stylesheet">
            <title>My Webpage</title>
        </head>
        <body>
            <!-- Navbar Start -->
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Dasun Sucharith</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="collapse navbar-collapse" id="navbarSupportedContent">
                        <ul class="navbar-nav me-auto mb-2 mb-lg-0 text-center">
                            <li class="nav-item">
                                <a class="nav-link" aria-current="page" href="/index.html">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link active" href="/clock.html">Clock</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/calendar.html">Calendar</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="/calculator.html">Calculator</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
            <!-- Navbar end -->
            
            <!-- Main start -->
            <div class="container my-5 text-center">
                <div class="clock mx-auto my-5">
                    <div class="hour"><div class="hr" id="hr"></div></div>
                    <div class="min"><div class="mn" id="mn"></div></div>
                    <div class="sec"><div class="sc" id="sc"></div></div>
                </div>
                <div id="digitalClock" class="mx-auto">
                    <span id="hour"></span>
                    <span id="minutes"></span>
                    <span id="seconds"></span>
                    <span id="ampm"></span>
                </div>
            </div>
            
            <!-- Calendar Start -->
            <div class="calendar my-5">
                <div class="calendar-header">
                    <h2 class="year-title">2025</h2>
                </div>
                <div class="months-container d-flex flex-wrap justify-content-center">
                    <div class="month-container">January</div>
                    <div class="month-container">February</div>
                    <div class="month-container">March</div>
                </div>
            </div>
            <!-- Calendar End -->
            
            <!-- Footer start -->
            <footer class="footer mt-auto py-3 bg-dark">
                <div class="container">
                    <span class="d-flex justify-content-center text-muted">© 2022 CS50. All Rights Reserved. By Dasun Sucharith.</span>
                </div>
            </footer>
            <!-- Footer end -->
            
            <script type="text/javascript">
                const hr = document.querySelector("#hr");
                const mn = document.querySelector("#mn");
                const sc = document.querySelector("#sc");
                setInterval(()=>{
                    let day = new Date();
                    let hh = day.getHours() * 30;
                    let mm = day.getMinutes() * 6;
                    let ss = day.getSeconds() * 6;
                    hr.style.transform = `rotateZ(${hh+(mm/12)}deg)`;
                    mn.style.transform = `rotateZ(${mm}deg)`;
                    sc.style.transform = `rotateZ(${ss}deg)`;
                    let hour = document.querySelector("#hour");
                    let minutes = document.querySelector("#minutes");
                    let seconds = document.querySelector("#seconds");
                    let ampm = document.querySelector("#ampm");
                    let h = day.getHours();
                    let m = day.getMinutes();
                    let s = day.getSeconds();
                    let am = "AM";
                    if (h > 12) {
                        h = h - 12;
                        am = "PM";
                    }
                    h = (h < 10) ? "0" + h : h;
                    m = (m < 10) ? "0" + m : m;
                    s = (s < 10) ? "0" + s : s;
                    hour.innerHTML = h + ":";
                    minutes.innerHTML = m + ":";
                    seconds.innerHTML = s + " ";
                    ampm.innerHTML = am;
                }, 1000);
            </script>
        </body>
    </html>
    

    Hope this helps you to solve the cs50 psets 8 homepage problem.

  • The solution to the CS50 labs 8 Trivia problem (2022)

    The solution to the CS50 labs 8 Trivia problem (2022)

    In this post, I’ll share the solution to the CS50 labs 8 Trivia problem. So, in this problem, we need to write a website that lets users answer trivia questions.

    For this problem, we must design a website using HTML, CSS, and Javascript to let users answer trivia questions.

    Here are the HTML & CSS code and the Javascript code of this problem.

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
            <title>Trivia!</title>
            <style>
                /* Base styles */
                body {
                    background-color: #fff;
                    color: #212529;
                    font-size: 1rem;
                    font-weight: 400;
                    line-height: 1.5;
                    margin: 0;
                    text-align: left;
                    font-family: 'Montserrat', sans-serif;
                }
    
                /* Container layout */
                .container {
                    margin-left: auto;
                    margin-right: auto;
                    padding-left: 15px;
                    padding-right: 15px;
                    max-width: 960px;
                }
    
                /* Header styling */
                .header {
                    background-color: #477bff;
                    color: #fff;
                    margin-bottom: 2rem;
                    padding: 2rem 1rem;
                    text-align: center;
                }
    
                /* Section styling */
                .section {
                    padding: 0.5rem 2rem 1rem 2rem;
                    margin-bottom: 1rem;
                    border-radius: 0.25rem;
                }
    
                .section:hover {
                    background-color: #f5f5f5;
                    transition: background-color 0.15s ease-in-out;
                }
    
                /* Typography */
                h1 {
                    font-family: 'Montserrat', sans-serif;
                    font-size: 48px;
                    margin: 0;
                }
    
                /* Button styles */
                button, 
                input[type="submit"] {
                    background-color: #d9edff;
                    border: 1px solid transparent;
                    border-radius: 0.25rem;
                    font-size: 0.95rem;
                    font-weight: 400;
                    line-height: 1.5;
                    padding: 0.375rem 0.75rem;
                    text-align: center;
                    transition: color 0.15s ease-in-out, 
                                background-color 0.15s ease-in-out, 
                                border-color 0.15s ease-in-out, 
                                box-shadow 0.15s ease-in-out;
                    vertical-align: middle;
                    cursor: pointer;
                    margin: 0.25rem;
                }
    
                button:hover,
                input[type="submit"]:hover {
                    background-color: #bce0ff;
                }
    
                /* Input styles */
                input[type="text"] {
                    line-height: 1.8;
                    width: 25%;
                    padding: 0.375rem 0.75rem;
                    border: 1px solid #ced4da;
                    border-radius: 0.25rem;
                    transition: background-color 0.15s ease-in-out,
                                border-color 0.15s ease-in-out;
                }
    
                input[type="text"]:hover {
                    background-color: #f5f5f5;
                    transition: background-color 0.15s ease-in-out;
                }
    
                input[type="text"]:focus {
                    outline: none;
                    border-color: #80bdff;
                    box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
                }
    
                /* Feedback messages */
                #msg,
                #msg2 {
                    color: #666;
                    margin: 1rem 0;
                    font-size: 1.25rem;
                }
            </style>
        </head>
        <body>
            <div class="header">
                <h1>Trivia!</h1>
            </div>
    
            <div class="container">
                <div class="section">
                    <h2>Part 1: Multiple Choice </h2>
                    <hr>
                    <h3>What is the approximate ratio of people to sheep in New Zealand?</h3>
                    <h2 id="msg"></h2>
                    <button class="button">6 people per 1 sheep</button>
                    <button class="button">3 people per 1 sheep</button>
                    <button class="button">1 people per 1 sheep</button>
                    <button class="button">1 people per 3 sheep</button>
                    <button id="correct" class="button">1 people per 6 sheep</button>
                </div>
    
                <div class="section">
                    <h2>Part 2: Free Response</h2>
                    <hr>
                    <h3>In which country is it illegal to own only one guinea pig, as a lone guinea pig might get lonely?</h3>
                    <input type="text">
                    <button id="button">Check Answer</button>
                    <h2 id="msg2"></h2>
                </div>
            </div>
    
            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    let correct_button = document.querySelector('#correct');
                    let incorrect_buttons = document.querySelectorAll('.button:not(#correct)');
                    let msg = document.querySelector('#msg');
                    let msg2 = document.querySelector('#msg2');
    
                    correct_button.addEventListener('click', function() {
                        correct_button.style.backgroundColor = 'green';
                        correct_button.style.color = 'white';
                        msg.innerHTML = 'Correct!';
                    });
    
                    incorrect_buttons.forEach(button => {
                        button.addEventListener('click', function() {
                            button.style.backgroundColor = 'red';
                            button.style.color = 'white';
                            msg.innerHTML = 'Incorrect';
                        });
                    });
    
                    document.querySelector('#button').addEventListener('click', function() {
                        let input = document.querySelector('input');
                        if (input.value.toLowerCase() === 'switzerland') {
                            input.style.backgroundColor = 'lightgreen';
                            msg2.innerHTML = 'Correct!';
                        } else {
                            input.style.backgroundColor = 'lightcoral';
                            msg2.innerHTML = 'Incorrect';
                        }
                    });
    
                    // Add keyboard support for the free response question
                    document.querySelector('input').addEventListener('keypress', function(e) {
                        if (e.key === 'Enter') {
                            document.querySelector('#button').click();
                        }
                    });
                });
            </script>
        </body>
    </html>

    Hope this helps you! If it did please consider sharing it with your friends!

  • The solution to CS50 psets 7 Fiftyville problem (2022)

    The solution to CS50 psets 7 Fiftyville problem (2022)

    Disclaimer: These answers are only for educational purposes only. Please do not use them for cheating. Cheating doesn’t do any good for you!

    In this post, I’ll give you the solution to the cs50 psets 7 Fiftyville problem. For this problem, we have to write SQL queries to solve a mystery.

    A mystery in Fiftyville

    The mystery is about the CS50 duck. It has been stolen. So you have been called to solve the mystery. According to the authorities, they believe that the thief stole the duck and then, shortly afterward, took a flight out of the town with the help of an accomplice. So the goal is to identify the thief, what city the thief escaped to, and who helped the thief.

    All that we know is that the theft took place on July 28, 2021, and that it took place on Humphrey Street.

    So a database is provided to us containing all the records and data from around the town. So we need to query this table and find out who the thief is and all other data.

    Solution log.sql

    Here are all the queries that lead us to the thief.

    -- Keep a log of any SQL queries you execute as you solve the mystery.
    
    -- crime happened on july 28, 2021 and it took place on Humphrey Street
    
    -- check the description of the crime in the cime scene reports table at the known day and place
    select description from crime_scene_reports
    where year=2021 and month = 7 and day = 28 and street = "Humphrey Street";
    
    -- checking the interview stranscripts
    
    select name, transcript from interviews
    where day = "28" and month = "7" and year = "2021";
    
    -- checking to see how many people by the name Eugene in the peoples table
    select name from people where name = 'Eugene';
    -- there is only one eugene in people list
    
    -- let's find out who are the 3 witnesses from the list of names of people who game interviews on july 28, 2021. According to crime report
    -- each of them mentioned bakery in their report
    
    select name,transcript from interviews
    where year=2021 and month=7 and day=28 and transcript like '%bakery%'
    order by name;
    
    -- according to eugene the thief was withdrawing money from the ATM on Leggett Street. Let's check the detials from that atm records
    select account_number, amount from atm_transactions
    where year = 2021 and month =7 and day=28 and atm_location='Leggett Street' and transaction_type='withdraw';
    
    -- let's find the account names of those transactions from the bank based on their transaction detials
    select name, atm_transactions.amount, atm_transactions.account_number from people
    join bank_accounts on people.id = bank_accounts.person_id
    join atm_transactions on bank_accounts.account_number = atm_transactions.account_number
    where atm_transactions.year=2021
    and atm_transactions.month=7
    and atm_transactions.day=28
    and atm_transactions.atm_location='Leggett Street'
    and atm_transactions.transaction_type = 'withdraw';
    
    -- according to raymonds lead lets find out the infomation about the airport in Fiftyville
    select abbreviation, full_name, city
    from airports
    where city = 'Fiftyville';
    
    -- Now let's find out what the flights scheduled on 29 from Fiftyville and order them by time
    select flights.id, full_name, city, flights.hour, flights.minute
    from airports
    join flights
    on airports.id = flights.destination_airport_id
    where flights.origin_airport_id = (
        select id
        from airports
        where city = 'Fiftyville'
    )
    and flights.year = 2021
    and flights.month = 7
    and flights.day = 29
    order by flights.hour, flights.minute;
    -- the first flight scheduled to be 8.20 to LaGuardia Airport in New York City (flight id is 36) this might be the place where theif went
    
    -- Now can check the passengers list to find out who are the people onboard that flight ordering them by their passport numbers
    select passengers.flight_id, name, passengers.passport_number, passengers.seat
    from people
    join passengers
    on people.passport_number = passengers.passport_number
    join flights
    on passengers.flight_id = flights.id
    where flights.year = 2021
    and flights.month = 7
    and flights.day = 29
    and flights.hour = 8
    and flights.minute = 20
    order by passengers.passport_number;
    -- now let's check the phone call records to find the person who bought the tickets
    
    -- first, need to check the possible names of the callers, and put the names in the suspect list. ordering them according to the durations of the calls
    select name, phone_calls.duration
    from people
    join phone_calls
    on people.phone_number = phone_calls.caller
    where phone_calls.year = 2021
    and phone_calls.month = 7
    and phone_calls.day = 28
    and phone_calls.duration <= 60
    order by phone_calls.duration;
    
    -- next let's check the possible names of the call-receiver. then order them by the durations of the calls
    select name, phone_calls.duration
    from people
    join phone_calls
    on people.phone_number = phone_calls.receiver
    where phone_calls.year = 2021
    and phone_calls.month = 7
    and phone_calls.day = 28
    and phone_calls.duration <= 60
    order by phone_calls.duration;
    
    -- according to Ruth the thief drove away in a car from the bakery, within 10minutes from the theft. So let's check the licencse plates of cars within that time frame with
    -- the respective owners of the vehicles
    
    select name, bakery_security_logs.hour, bakery_security_logs.minute
    from people
    join bakery_security_logs
    on people.license_plate = bakery_security_logs.license_plate
    where bakery_security_logs.year = 2021
    and bakery_security_logs.month = 7
    and bakery_security_logs.day = 28
    and bakery_security_logs.activity = 'exit'
    and bakery_security_logs.minute >= 15
    and bakery_security_logs.minute <= 25
    order by bakery_security_logs.minute;
    
    -- After cosidering all the lists of list of people who drove away from bakery, list of people who called, list of passengers, list of people who withdraw monty from the atm
    -- Bruce appear in all of them so he must be the thief and he ran away to New York City
    -- and Robin must be the one who accomplice with Bruce

    Output text file

    +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    |                                                                                                       description                                                                                                        |
    +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | Theft of the CS50 duck took place at 10:15am at the Humphrey Street bakery. Interviews were conducted today with three witnesses who were present at the time – each of their interview transcripts mentions the bakery. |
    | Littering took place at 16:36. No known witnesses.                                                                                                                                                                       |
    +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    +---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    |  name   |                                                                                                                                                     transcript                                                                                                                                                      |
    +---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | Jose    | “Ah,” said he, “I forgot that I had not seen you for some weeks. It is a little souvenir from the King of Bohemia in return for my assistance in the case of the Irene Adler papers.”                                                                                                                               |
    | Eugene  | “I suppose,” said Holmes, “that when Mr. Windibank came back from France he was very annoyed at your having gone to the ball.”                                                                                                                                                                                      |
    | Barbara | “You had my note?” he asked with a deep harsh voice and a strongly marked German accent. “I told you that I would call.” He looked from one to the other of us, as if uncertain which to address.                                                                                                                   |
    | Ruth    | Sometime within ten minutes of the theft, I saw the thief get into a car in the bakery parking lot and drive away. If you have security footage from the bakery parking lot, you might want to look for cars that left the parking lot in that time frame.                                                          |
    | Eugene  | I don't know the thief's name, but it was someone I recognized. Earlier this morning, before I arrived at Emma's bakery, I was walking by the ATM on Leggett Street and saw the thief there withdrawing some money.                                                                                                 |
    | Raymond | As the thief was leaving the bakery, they called someone who talked to them for less than a minute. In the call, I heard the thief say that they were planning to take the earliest flight out of Fiftyville tomorrow. The thief then asked the person on the other end of the phone to purchase the flight ticket. |
    | Lily    | Our neighboring courthouse has a very annoying rooster that crows loudly at 6am every day. My sons Robert and Patrick took the rooster to a city far, far away, so it may never bother us again. My sons have successfully arrived in Paris.                                                                        |
    +---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    +--------+
    |  name  |
    +--------+
    | Eugene |
    +--------+
    +---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    |  name   |                                                                                                                                                     transcript                                                                                                                                                      |
    +---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | Eugene  | I don't know the thief's name, but it was someone I recognized. Earlier this morning, before I arrived at Emma's bakery, I was walking by the ATM on Leggett Street and saw the thief there withdrawing some money.                                                                                                 |
    | Raymond | As the thief was leaving the bakery, they called someone who talked to them for less than a minute. In the call, I heard the thief say that they were planning to take the earliest flight out of Fiftyville tomorrow. The thief then asked the person on the other end of the phone to purchase the flight ticket. |
    | Ruth    | Sometime within ten minutes of the theft, I saw the thief get into a car in the bakery parking lot and drive away. If you have security footage from the bakery parking lot, you might want to look for cars that left the parking lot in that time frame.                                                          |
    +---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    +----------------+--------+
    | account_number | amount |
    +----------------+--------+
    | 28500762       | 48     |
    | 28296815       | 20     |
    | 76054385       | 60     |
    | 49610011       | 50     |
    | 16153065       | 80     |
    | 25506511       | 20     |
    | 81061156       | 30     |
    | 26013199       | 35     |
    +----------------+--------+
    +---------+--------+----------------+
    |  name   | amount | account_number |
    +---------+--------+----------------+
    | Bruce   | 50     | 49610011       |
    | Diana   | 35     | 26013199       |
    | Brooke  | 80     | 16153065       |
    | Kenny   | 20     | 28296815       |
    | Iman    | 20     | 25506511       |
    | Luca    | 48     | 28500762       |
    | Taylor  | 60     | 76054385       |
    | Benista | 30     | 81061156       |
    +---------+--------+----------------+
    +--------------+-----------------------------+------------+
    | abbreviation |          full_name          |    city    |
    +--------------+-----------------------------+------------+
    | CSF          | Fiftyville Regional Airport | Fiftyville |
    +--------------+-----------------------------+------------+
    +----+-------------------------------------+---------------+------+--------+
    | id |              full_name              |     city      | hour | minute |
    +----+-------------------------------------+---------------+------+--------+
    | 36 | LaGuardia Airport                   | New York City | 8    | 20     |
    | 43 | O'Hare International Airport        | Chicago       | 9    | 30     |
    | 23 | San Francisco International Airport | San Francisco | 12   | 15     |
    | 53 | Tokyo International Airport         | Tokyo         | 15   | 20     |
    | 18 | Logan International Airport         | Boston        | 16   | 0      |
    +----+-------------------------------------+---------------+------+--------+
    +-----------+--------+-----------------+------+
    | flight_id |  name  | passport_number | seat |
    +-----------+--------+-----------------+------+
    | 36        | Edward | 1540955065      | 5C   |
    | 36        | Sofia  | 1695452385      | 3B   |
    | 36        | Taylor | 1988161715      | 6D   |
    | 36        | Bruce  | 5773159633      | 4A   |
    | 36        | Doris  | 7214083635      | 2A   |
    | 36        | Kelsey | 8294398571      | 6C   |
    | 36        | Luca   | 8496433585      | 7B   |
    | 36        | Kenny  | 9878712108      | 7A   |
    +-----------+--------+-----------------+------+
    +---------+----------+
    |  name   | duration |
    +---------+----------+
    | Kelsey  | 36       |
    | Carina  | 38       |
    | Taylor  | 43       |
    | Bruce   | 45       |
    | Diana   | 49       |
    | Kelsey  | 50       |
    | Sofia   | 51       |
    | Benista | 54       |
    | Kenny   | 55       |
    | Kathryn | 60       |
    +---------+----------+
    +------------+----------+
    |    name    | duration |
    +------------+----------+
    | Larry      | 36       |
    | Jacqueline | 38       |
    | James      | 43       |
    | Robin      | 45       |
    | Philip     | 49       |
    | Melissa    | 50       |
    | Jack       | 51       |
    | Anna       | 54       |
    | Doris      | 55       |
    | Luca       | 60       |
    +------------+----------+
    +---------+------+--------+
    |  name   | hour | minute |
    +---------+------+--------+
    | Wayne   | 8    | 15     |
    | Jordan  | 8    | 15     |
    | Sophia  | 17   | 15     |
    | Vanessa | 10   | 16     |
    | Vincent | 15   | 16     |
    | Jeremy  | 17   | 16     |
    | Bruce   | 10   | 18     |
    | Barry   | 10   | 18     |
    | Ethan   | 14   | 18     |
    | Brandon | 17   | 18     |
    | Luca    | 10   | 19     |
    | Sofia   | 10   | 20     |
    | Iman    | 10   | 21     |
    | Diana   | 10   | 23     |
    | Kelsey  | 10   | 23     |
    | Michael | 8    | 25     |
    +---------+------+--------+

    Conclusion based on the investigation results

    The THIEF is: Bruce
    The city the thief ESCAPED TO: New York City
    The ACCOMPLICE is: Robin

    Hope this solution helps you!

  • The solution to CS50 psets 7 movies problem (2022)

    The solution to CS50 psets 7 movies problem (2022)

    Disclaimer: These answers are only for educational purposes only. Please do not use them for cheating. Cheating doesn’t do any good for you!

    In this post, I’ll give you the solution to the CS50 psets 7 movies problem. In this problem, we have to write SQL queries to answer questions about a database of movies. SQLite database called movies.db is provided to you. This database stores data from IMDb about movies, the people who directed, and starred in them, and their ratings.

    There are 13 problems. We have to write SQL queries to solve each one of them. Here are my solutions to those questions.

    SQL query to list the titles of all movies released in 2008.

    This query should output a table with a single column for the title of each movie.

    select title from movies where year=2008;

    SQL query to determine the birth year of Emma Stone.

    This query should output a table with a single column and a single row (not counting the header) containing Emma Stone’s birth year. For this, you may assume that there is only one person in the database with the name Emma Stone.

    select birth from people where name="Emma Stone";

    SQL query to list the titles of all movies with a release date on or after 2018, in alphabetical order.

    This query should output a table with a single column for the title of each movie. Movies released in 2018 should be included, as should movies with release dates in the future.

    select title from movies where year >= 2018 order by title asc;

    SQL query to determine the number of movies with an IMDb rating of 10.0.

    This query should output a table with a single column and a single row (not counting the header) containing the number of movies with a 10.0 rating.

    select count(movie_id) from ratings where rating=10;

    SQL query to list the titles and release years of all Harry Potter movies, in chronological order.

    This query should output a table with two columns, one for the title of each movie and one for the release year of each movie. You may assume that the title of all Harry Potter movies will begin with the words “Harry Potter”, and that if a movie title begins with the words “Harry Potter”, it is a Harry Potter movie.

    select title, year from movies where title like 'Harry Potter%' order by year;

    SQL query to determine the average rating of all movies released in 2012.

    This query should output a table with a single column and a single row (not counting the header) containing the average rating.

    select avg(rating) from ratings join movies on movies.id=ratings.movie_id where movies.year=2012;

    SQL query to list all movies released in 2010 and their ratings, in descending order by rating. For movies with the same rating, order them alphabetically by title.

    This query should output a table with two columns, one for the title of each movie and one for the rating of each movie.

    select ratings.rating, movies.title
    from ratings join movies
    on ratings.movie_id=movies.id
    where movies.year=2010
    order by ratings.rating desc, movies.title asc;

    SQL query to list the names of all people who starred in Toy Story.

    This query should output a table with a single column for the name of each person. You may assume that there is only one movie in the database with the title Toy Story.

    select name from people
    join stars on stars.person_id=people.id
    join movies on stars.movie_id=movies.id
    where movies.title="Toy Story";

    SQL query to list the names of all people who starred in a movie released in 2004, ordered by birth year.

    This query should output a table with a single column for the name of each person. People with the same birth year can be listed in any order. If a person appeared in more than one movie in 2004, they should appear in your results once.

    select distinct name from people
    join stars on stars.person_id=people.id
    join movies on stars.movie_id=movies.id
    join ratings on ratings.movie_id=movies.id
    where movies.year=2004
    order by people.birth;

    SQL query to list the names of all people who have directed a movie that received a rating of at least 9.0.

    This query should output a table with a single column for the name of each person. If a person directed more than one movie that received a rating of at least 9.0, they should only appear in your results once.

    select name from people
    join directors on directors.person_id=people.id
    join movies on directors.movie_id=movies.id
    join ratings on ratings.movie_id=movies.id
    where ratings.rating >= 9;

    SQL query to list the titles of the five highest-rated movies (in order) that Chadwick Boseman starred in, starting with the highest-rated.

    This query should output a table with a single column for the title of each movie. You may assume that there is only one person in the database with the name Chadwick Boseman.

    select title from movies
    join stars on stars.movie_id=movies.id
    join people on stars.person_id=people.id
    join ratings on ratings.movie_id=movies.id
    where people.name = "Chadwick Boseman"
    order by ratings.rating desc
    limit 5;

    SQL query to list the titles of all movies in which both Johnny Depp and Helena Bonham Carter starred.

    This query should output a table with a single column for the title of each movie. You may assume that there is only one person in the database with the name Johnny Depp. You may assume that there is only one person in the database with the name Helena Bonham Carter.

    select title from movies
    join stars on stars.movie_id = movies.id
    join people on stars.person_id = people.id
    where people.name = "Johnny Depp"
    and title in (select title from movies
    join stars on stars.movie_id = movies.id
    join people on stars.person_id = people.id
    where people.name = "Helena Bonham Carter");

    SQL query to list the names of all people who starred in a movie in which Kevin Bacon also starred.

    This query should output a table with a single column for the name of each person. There may be multiple people named Kevin Bacon in the database. Be sure to only select Kevin Bacon born in 1958. Kevin Bacon himself should not be included in the resulting list.

    select name from people
    join stars on stars.person_id = people.id
    join movies on stars.movie_id = movies.id
    where movies.id in
    (select movies.id from movies
    join people on stars.person_id = people.id
    join stars on stars.movie_id = movies.id
    where people.name = "Kevin Bacon"
    and people.birth = 1958 )
    and people.name != "Kevin Bacon";

    Hope these solutions will help you. If it did, consider sharing with your friends which also need these answers.

  • The solution to CS50 labs 7 songs problem (2022)

    The solution to CS50 labs 7 songs problem (2022)

    Disclaimer: These answers are only for educational purposes only. Please do not use them for cheating. Cheating doesn’t do any good for you!

    In this post, I’ll present the solution to cs50 labs 7 songs problem. So, in this lab, we have to write SQL queries to answer questions about a database of songs. A database file called songs.db is provided for us. We have to write different queries to filter out specific data from the database file regarding the questions.

    So let’s see the answers to all these questions,

    SQL query to list the names of all songs in the database.

    This query should output a table with a single column for the name of each song.

    SELECT name FROM songs;

    SQL query to list the songs’ names in increasing tempo order.

    This query should output a table with a single column for the name of each song.

    SELECT name FROM songs ORDER BY tempo;

    SQL query to list the names of the top 5 longest songs, in descending order of length.

    This query should output a table with a single column for the name of each song.

    SELECT name FROM songs ORDER BY duration_ms DESC LIMIT 5;

    SQL query that lists the names of any songs that have danceability, energy, and valence greater than 0.75.

    This query should output a table with a single column for the name of each song.

    SELECT name FROM songs WHERE danceability > 0.75 AND energy > 0.75 AND valence > 0.75;

    SQL query that returns the average energy of all the songs.

    This query should output a table with a single column and a single row containing the average energy.

    SELECT avg(energy) FROM songs;

    SQL query that lists the names of songs that are by Post Malone.

    This query should output a table with a single column for the name of each song.

    SELECT name FROM songs WHERE artist_id = (SELECT id FROM artists WHERE name == "Post Malone");

    SQL query that returns the average energy of songs that are by Drake.

    This query should output a table with a single column and a single row containing the average energy.

    SELECT avg(energy) FROM songs WHERE artist_id = (SELECT id FROM artists WHERE name == "Drake");

    SQL query that lists the names of the songs that feature other artists.

    This query should output, Songs that feature other artists and will include “feat.” in the name of the song. And it should output a table with a single column for the name of each song.

    SELECT name FROM songs WHERE name LIKE "%feat.%";

    Hope these answers helped you. If it did, please consider sharing this post with your friends who need these answers.

  • The Solution to CS50 labs 5 & psets 5 problems (2022)

    The Solution to CS50 labs 5 & psets 5 problems (2022)

    Disclaimer: These answers are only for educational purposes only. Please do not use them for cheating. Cheating doesn’t do any good for you!

    In this post, I’m giving you my solutions to CS50 lab 5 and problem set 5 problems. Hope these solutions will help you to better understand the problems and be a guide for your solutions too.

    The Solution to CS50 labs 5 Inheritance Problem (2022)

    For this problem, we have to write a code that simulate the inheritance of blood types of each member of a family. So, a C file called inheritance.c is provided for us. And the code in this file is not complete. We have to complete the code using the given instructions in the manual.

    Here is my solution to this problem,

    // Simulate genetic inheritance of blood type
    
    #include <stdbool.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    // Each person has two parents and two alleles
    typedef struct person
    {
        struct person *parents[2];
        char alleles[2];
    }
    person;
    
    const int GENERATIONS = 3;
    const int INDENT_LENGTH = 4;
    
    person *create_family(int generations);
    void print_family(person *p, int generation);
    void free_family(person *p);
    char random_allele();
    
    int main(void)
    {
        // Seed random number generator
        srand(time(0));
    
        // Create a new family with three generations
        person *p = create_family(GENERATIONS);
    
        // Print family tree of blood types
        print_family(p, 0);
    
        // Free memory
        free_family(p);
    }
    
    // Create a new individual with `generations`
    person *create_family(int generations)
    {
        // TODO: Allocate memory for new person
        person *n = malloc(sizeof(person));
        if (n == NULL)
        {
            return NULL;
        }
    
        // If there are still generations left to create
        if (generations > 1)
        {
            // Create two new parents for current person by recursively calling create_family
            person *parent0 = create_family(generations - 1);
            person *parent1 = create_family(generations - 1);
    
            // TODO: Set parent pointers for current person
            n->parents[0] = parent0;
            n->parents[1] = parent1;
    
            // TODO: Randomly assign current person's alleles based on the alleles of their parents
            n->alleles[0] = n->parents[0]->alleles[rand() % 2];
            n->alleles[1] = n->parents[1]->alleles[rand() % 2];
        }
    
        // If there are no generations left to create
        else
        {
            // TODO: Set parent pointers to NULL
            n->parents[0] = NULL;
            n->parents[1] = NULL;
    
            // TODO: Randomly assign alleles
            n->alleles[0] = random_allele();
            n->alleles[1] = random_allele();
    
        }
    
        // TODO: Return newly created person
        return n;
    }
    
    // Free `p` and all ancestors of `p`.
    void free_family(person *p)
    {
        // TODO: Handle base case
        if (p == NULL)
        {
            return;
        }
    
        // TODO: Free parents recursively
        free_family(p->parents[0]);
        free_family(p->parents[1]);
    
        // TODO: Free child
        free(p);
    
    }
    
    // Print each family member and their alleles.
    void print_family(person *p, int generation)
    {
        // Handle base case
        if (p == NULL)
        {
            return;
        }
    
        // Print indentation
        for (int i = 0; i < generation * INDENT_LENGTH; i++)
        {
            printf(" ");
        }
    
        // Print person
        if (generation == 0)
        {
            printf("Child (Generation %i): blood type %c%c\n", generation, p->alleles[0], p->alleles[1]);
        }
        else if (generation == 1)
        {
            printf("Parent (Generation %i): blood type %c%c\n", generation, p->alleles[0], p->alleles[1]);
        }
        else
        {
            for (int i = 0; i < generation - 2; i++)
            {
                printf("Great-");
            }
            printf("Grandparent (Generation %i): blood type %c%c\n", generation, p->alleles[0], p->alleles[1]);
        }
    
        // Print parents of current generation
        print_family(p->parents[0], generation + 1);
        print_family(p->parents[1], generation + 1);
    }
    
    // Randomly chooses a blood type allele.
    char random_allele()
    {
        int r = rand() % 3;
        if (r == 0)
        {
            return 'A';
        }
        else if (r == 1)
        {
            return 'B';
        }
        else
        {
            return 'O';
        }
    }

    The Solution to CS50 psets 5 Speller problem (2022)

    For this problem, we have to implement a C program that spell-checks a file using hash tables. Bunch of files are provided for us for this problem set. But we just have to make changes only to the dictionary.c file. We have to use hash tables for this problem. All the required guide is given to us in the website.

    So, here is what my solution looks like to this problem.

    // Implements a dictionary's functionality
    
    #include <ctype.h>
    #include <string.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <strings.h>
    #include <cs50.h>
    
    #include "dictionary.h"
    
    // Represents a node in a hash table
    typedef struct node
    {
        char word[LENGTH + 1];
        struct node *next;
    }
    node;
    
    // TODO: Choose number of buckets in hash table
    const unsigned int N = (LENGTH + 1) *'z';
    
    int total_words = 0;
    
    // Hash table
    node *table[N];
    
    // Returns true if word is in dictionary, else false
    bool check(const char *word)
    {
        // TODO
        // Obtain the hash index
        int index = hash(word);
    
        node *cursor = table[index];
        while (cursor != NULL)
        {
            if (strcasecmp(cursor->word, word) == 0)
            {
                return true;
            }
            cursor = cursor->next;
        }
    
        return false;
    }
    
    // Hashes word to a number
    unsigned int hash(const char *word)
    {
        // TODO: Improve this hash function
        int sum = 0;
        for (int i = 0; i < strlen(word); i++)
        {
            sum += tolower(word[i]);
        }
        return (sum % N);
    }
    
    // Loads dictionary into memory, returning true if successful, else false
    bool load(const char *dictionary)
    {
        // TODO
        // open the dictionary
        FILE *file = fopen(dictionary, "r");
        if (file == NULL)
        {
            return false;
        }
    
        // read one word at a time from file
        char word[LENGTH + 1];
    
        while (fscanf(file, "%s", word) != EOF)
        {
            // create a new node
            node *n = malloc(sizeof(node));
            if (n == NULL)
            {
                return false;
            }
    
            // Copy over the word to the node
            strcpy(n->word, word);
            n->next = NULL;
    
            // Obtain hashing index
            int index = hash(word);
            if (table[index] == NULL)
            {
                table[index] = n;
            }
            else
            {
                n->next = table[index];
                table[index] = n;
            }
            total_words++;
        }
        fclose(file);
        return true;
    }
    
    // Returns number of words in dictionary if loaded, else 0 if not yet loaded
    unsigned int size(void)
    {
        // TODO
        return total_words;
    }
    
    // Unloads dictionary from memory, returning true if successful, else false
    bool unload(void)
    {
        // TODO
        // Free the linked list
        for (int i = 0; i < N; i++)
        {
            node *head = table[i];
            node *cursor = head;
            node *tmp = head;
    
            while (cursor != NULL)
            {
                cursor = cursor->next;
                free(tmp);
                tmp = cursor;
            }
        }
        return true;
    }

    Hope this will be helpful for you.

  • Solutions to CS50 Problem Set 4 Filter & Recover Problems (2022)

    Solutions to CS50 Problem Set 4 Filter & Recover Problems (2022)

    Disclaimer: These answers are only for educational purposes only. Please do not use them for cheating. Cheating doesn’t do any good for you!

    In this post, I’m giving you my solutions to CS50 Problem Set 4 Filter (less comfortable / more comfortable) Problems and Recover problems. Hope these solutions will help you to better understand the problems and be a guide for your solutions too.

    The Solution to CS50 Psets 4 Filter Problem – Less Comfortable (2022)

    For this problem, we just have to implement a program that applies filters to BMPs. And a bunch of files were provided for us. We have to implement some functions in helpers.c to apply greyscale, Sepia, reflection, and blur filters to the given images.

    The greyscale function turns the input image into a black-and-white version of it

    // Convert image to grayscale
    void grayscale(int height, int width, RGBTRIPLE image[height][width])
    {
        // Iterate through each column of pixel
        for (int i = 0; i < height; i++)
        {
            // Iterate through each raw of pixel in each column
            for (int j = 0; j < width; j++)
            {
                // Get into the 2D array, obtain value of each color
                int red = image[i][j].rgbtRed;
                int blue = image[i][j].rgbtBlue;
                int green = image[i][j].rgbtGreen;
    
                // Calculate the rounded avarage of each pixel
                int average = round(((float)red + (float)blue + (float)green) / 3);
    
                // Set the calculated value to be the new value of each pixel
                image[i][j].rgbtRed = image[i][j].rgbtBlue = image[i][j].rgbtGreen = average;
            }
        }
    }

    The sepia function turns the input image into sepia version of the same image

      // Convert image to sepia
      void sepia(int height, int width, RGBTRIPLE image[height][width])
      {
          for (int i = 0; i < height; i++)
          {
              for (int j = 0; j < width; j++)
              {
                  int red = image[i][j].rgbtRed;
                  int blue = image[i][j].rgbtBlue;
                  int green = image[i][j].rgbtGreen;
      
                  // New sapia values
                  int sepiaRed = round(0.393 * red + 0.769 * green + 0.189 * blue);
      
                  if (sepiaRed > 255)
                  {
                      image[i][j].rgbtRed = 255;
                  }
                  else
                  {
                      image[i][j].rgbtRed = sepiaRed;
                  }
      
                  int sepiaBlue = round(0.272 * red + 0.534 * green + 0.131 * blue);
      
                  if (sepiaBlue > 255)
                  {
                      image[i][j].rgbtBlue = 255;
                  }
                  else
                  {
                      image[i][j].rgbtBlue = sepiaBlue;
                  }
      
                  int sepiaGreen = round(0.349 * red + 0.686 * green + 0.168 * blue);
      
                  if (sepiaGreen > 255)
                  {
                      image[i][j].rgbtGreen = 255;
                  }
                  else
                  {
                      image[i][j].rgbtGreen = sepiaGreen;
                  }
              }
          }
      }

      The reflect function takes the image and reflects in horizontally

      // Reflect image horizontally
      void reflect(int height, int width, RGBTRIPLE image[height][width])
      {
          for (int i = 0; i < height; i++)
          {
              // Iterate through the array until you get the mid point
              for (int j = 0; j < (width / 2); j++)
              {
                  RGBTRIPLE temp = image[i][j];
      
                  image[i][j] = image[i][width - (j + 1)];
                  image[i][width - (j + 1)] = temp;
              }
          }
          return;
      }

      The blur function takes an image and turns it into a box-blurred version of the image

      // Blur image
      void blur(int height, int width, RGBTRIPLE image[height][width])
      {
          //create a temporary image to implement blurred algorithm on it.
          RGBTRIPLE temp[height][width];
      
          for (int i = 0; i < height; i++)
          {
              for (int j = 0; j < width; j++)
              {
                  int sumRed, sumBlue, sumGreen;
                  sumRed = sumBlue = sumGreen = 0;
                  float counter = 0.00;
      
                  //Get the neighbouring pexels
                  for (int c = -1; c < 2; c++)
                  {
                      for (int r = -1; r < 2; r++)
                      {
                          int currentX = i + c;
                          int currentY = j + r;
      
                          //check for valid neighbouring pexels
                          if (currentX < 0 || currentX > (height - 1) || currentY < 0 || currentY > (width - 1))
                          {
                              continue;
                          }
      
                          //Get the image value
                          sumRed += image[currentX][currentY].rgbtRed;
                          sumGreen += image[currentX][currentY].rgbtGreen;
                          sumBlue += image[currentX][currentY].rgbtBlue;
      
                          counter++;
                      }
      
                      //do the average of neigbhouring pexels
                      temp[i][j].rgbtRed = round(sumRed / counter);
                      temp[i][j].rgbtGreen = round(sumGreen / counter);
                      temp[i][j].rgbtBlue = round(sumBlue / counter);
                  }
              }
      
          }
      
          //copy the blurr image to the original image
          for (int i = 0; i < height; i++)
          {
              for (int j = 0; j < width; j++)
              {
                  image[i][j].rgbtRed = temp[i][j].rgbtRed;
                  image[i][j].rgbtGreen = temp[i][j].rgbtGreen;
                  image[i][j].rgbtBlue = temp[i][j].rgbtBlue;
              }
          }
          return;
      }

      Full code of helpers.c file

      #include "helpers.h"
      #include <math.h>
      
      // Convert image to grayscale
      void grayscale(int height, int width, RGBTRIPLE image[height][width])
      {
          // Iterate through each column of pixel
          for (int i = 0; i < height; i++)
          {
              // Iterate through each raw of pixel in each column
              for (int j = 0; j < width; j++)
              {
                  // Get into the 2D array, obtain value of each color
                  int red = image[i][j].rgbtRed;
                  int blue = image[i][j].rgbtBlue;
                  int green = image[i][j].rgbtGreen;
      
                  // Calculate the rounded avarage of each pixel
                  int average = round(((float)red + (float)blue + (float)green) / 3);
      
                  // Set the calculated value to be the new value of each pixel
                  image[i][j].rgbtRed = image[i][j].rgbtBlue = image[i][j].rgbtGreen = average;
              }
          }
      }
      
      // Convert image to sepia
      void sepia(int height, int width, RGBTRIPLE image[height][width])
      {
          for (int i = 0; i < height; i++)
          {
              for (int j = 0; j < width; j++)
              {
                  int red = image[i][j].rgbtRed;
                  int blue = image[i][j].rgbtBlue;
                  int green = image[i][j].rgbtGreen;
      
                  // New sapia values
                  int sepiaRed = round(0.393 * red + 0.769 * green + 0.189 * blue);
      
                  if (sepiaRed > 255)
                  {
                      image[i][j].rgbtRed = 255;
                  }
                  else
                  {
                      image[i][j].rgbtRed = sepiaRed;
                  }
      
                  int sepiaBlue = round(0.272 * red + 0.534 * green + 0.131 * blue);
      
                  if (sepiaBlue > 255)
                  {
                      image[i][j].rgbtBlue = 255;
                  }
                  else
                  {
                      image[i][j].rgbtBlue = sepiaBlue;
                  }
      
                  int sepiaGreen = round(0.349 * red + 0.686 * green + 0.168 * blue);
      
                  if (sepiaGreen > 255)
                  {
                      image[i][j].rgbtGreen = 255;
                  }
                  else
                  {
                      image[i][j].rgbtGreen = sepiaGreen;
                  }
              }
          }
      }
      
      // Reflect image horizontally
      void reflect(int height, int width, RGBTRIPLE image[height][width])
      {
          for (int i = 0; i < height; i++)
          {
              // Iterate through the array until you get the mid point
              for (int j = 0; j < (width / 2); j++)
              {
                  RGBTRIPLE temp = image[i][j];
      
                  image[i][j] = image[i][width - (j + 1)];
                  image[i][width - (j + 1)] = temp;
              }
          }
          return;
      }
      
      
      // Blur image
      void blur(int height, int width, RGBTRIPLE image[height][width])
      {
          //create a temporary image to implement blurred algorithm on it.
          RGBTRIPLE temp[height][width];
      
          for (int i = 0; i < height; i++)
          {
              for (int j = 0; j < width; j++)
              {
                  int sumRed, sumBlue, sumGreen;
                  sumRed = sumBlue = sumGreen = 0;
                  float counter = 0.00;
      
                  //Get the neighbouring pexels
                  for (int c = -1; c < 2; c++)
                  {
                      for (int r = -1; r < 2; r++)
                      {
                          int currentX = i + c;
                          int currentY = j + r;
      
                          //check for valid neighbouring pexels
                          if (currentX < 0 || currentX > (height - 1) || currentY < 0 || currentY > (width - 1))
                          {
                              continue;
                          }
      
                          //Get the image value
                          sumRed += image[currentX][currentY].rgbtRed;
                          sumGreen += image[currentX][currentY].rgbtGreen;
                          sumBlue += image[currentX][currentY].rgbtBlue;
      
                          counter++;
                      }
      
                      //do the average of neigbhouring pexels
                      temp[i][j].rgbtRed = round(sumRed / counter);
                      temp[i][j].rgbtGreen = round(sumGreen / counter);
                      temp[i][j].rgbtBlue = round(sumBlue / counter);
                  }
              }
      
          }
      
          //copy the blurr image to the original image
          for (int i = 0; i < height; i++)
          {
              for (int j = 0; j < width; j++)
              {
                  image[i][j].rgbtRed = temp[i][j].rgbtRed;
                  image[i][j].rgbtGreen = temp[i][j].rgbtGreen;
                  image[i][j].rgbtBlue = temp[i][j].rgbtBlue;
              }
          }
          return;
      }

      The Solution to CS50 Psets 4 Filter Problem – More Comfortable (2022)

      For this problem also, we have to implement a program that applies filters to BMPs. And a bunch of files were provided for us. We have to implement some functions in helpers.c to apply greyscale, reflection, blur, and edge filters to the given images.

      The greyscale function should take an image and turn it into a black-and-white version of the same image.

      // Convert image to grayscale
      void grayscale(int height, int width, RGBTRIPLE image[height][width])
      {
          // Iterate though each column
          for (int i = 0; i < height; i++)
          {
              // Iterate through each raw of pixel in each column
              for (int j = 0; j < width; j++)
              {
                  // Get into 2D array and obtain value of each color
                  int red = image[i][j].rgbtRed;
                  int blue = image[i][j].rgbtBlue;
                  int green = image[i][j].rgbtGreen;
      
                  // Calculate the rounded avarage of each pixel
                  int average = round(((float)red + (float)blue + (float)green) / 3);
      
                  // Set the calculated value to be the new value of each pixel
                  image[i][j].rgbtRed = image[i][j].rgbtBlue = image[i][j].rgbtGreen = average;
              }
          }
          return;
      }
      

      The reflection function should take an image and reflect it horizontally

      // Reflect image horizontally
      void reflect(int height, int width, RGBTRIPLE image[height][width])
      {
          for (int i = 0; i < height; i++)
          {
              // Iterate through the array until you get the mid point
              for (int j = 0; j < (width / 2); j++)
              {
                  RGBTRIPLE temp = image[i][j];
      
                  image[i][j] = image[i][width - (j + 1)];
                  image[i][width - (j + 1)] = temp;
              }
          }
          return;
      }
      

      The blur function takes and image and turns it into a box-blurred version of the same image.

      // Blur image
      void blur(int height, int width, RGBTRIPLE image[height][width])
      {
          //create a temporary image to implement blurred algorithm on it.
          RGBTRIPLE temp[height][width];
      
          for (int i = 0; i < height; i++)
          {
              for (int j = 0; j < width; j++)
              {
                  int sumRed, sumBlue, sumGreen;
                  sumRed = sumBlue = sumGreen = 0;
                  float counter = 0.00;
      
                  //Get the neighbouring pexels
                  for (int c = -1; c < 2; c++)
                  {
                      for (int r = -1; r < 2; r++)
                      {
                          int currentX = i + c;
                          int currentY = j + r;
      
                          //check for valid neighbouring pexels
                          if (currentX < 0 || currentX > (height - 1) || currentY < 0 || currentY > (width - 1))
                          {
                              continue;
                          }
      
                          //Get the image value
                          sumRed += image[currentX][currentY].rgbtRed;
                          sumGreen += image[currentX][currentY].rgbtGreen;
                          sumBlue += image[currentX][currentY].rgbtBlue;
      
                          counter++;
                      }
      
                      //do the average of neigbhouring pexels
                      temp[i][j].rgbtRed = round(sumRed / counter);
                      temp[i][j].rgbtGreen = round(sumGreen / counter);
                      temp[i][j].rgbtBlue = round(sumBlue / counter);
                  }
              }
      
          }
      
          //copy the blurr image to the original image
          for (int i = 0; i < height; i++)
          {
              for (int j = 0; j < width; j++)
              {
                  image[i][j].rgbtRed = temp[i][j].rgbtRed;
                  image[i][j].rgbtGreen = temp[i][j].rgbtGreen;
                  image[i][j].rgbtBlue = temp[i][j].rgbtBlue;
              }
          }
          return;
      }

      The edges function takes an image and highlight the edges between objects, according to the sobel operator.

      // Detect edges
      void edges(int height, int width, RGBTRIPLE image[height][width])
      {
          RGBTRIPLE temp[height][width];
      
          int gx[3][3] = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}};
          int gy[3][3] = {{-1, -2, -1}, {0, 0, 0}, {1, 2, 1}};
      
          for (int i = 0; i < height; i++)
          {
              for (int j = 0; j < width; j++)
              {
                  float gxRed = 0;
                  float gyRed = 0;
                  float gxGreen = 0;
                  float gyGreen = 0;
                  float gxBlue = 0;
                  float gyBlue = 0;
      
                  for (int col = -1; col < 2; col++)
                  {
                      for (int row = -1; row < 2; row++)
                      {
                          if (i + col < 0 || i + col > height - 1)
                          {
                              continue;
                          }
                          if (j + row < 0 || j + row > width - 1)
                          {
                              continue;
                          }
      
                          gxRed += image[i + col][j + row].rgbtRed * gx[col + 1][row + 1];
                          gyRed += image[i + col][j + row].rgbtRed * gy[col + 1][row + 1];
                          gxGreen += image[i + col][j + row].rgbtGreen * gx[col + 1][row + 1];
                          gyGreen += image[i + col][j + row].rgbtGreen * gy[col + 1][row + 1];
                          gxBlue += image[i + col][j + row].rgbtBlue * gx[col + 1][row + 1];
                          gyBlue += image[i + col][j + row].rgbtBlue * gy[col + 1][row + 1];
                      }
                  }
      
                  int red = round(sqrt(gxRed * gxRed + gyRed * gyRed));
                  int green = round(sqrt(gxGreen * gxGreen + gyGreen * gyGreen));
                  int blue = round(sqrt(gxBlue * gxBlue + gyBlue * gyBlue));
      
                  // Cap at 255
                  if (red > 255)
                  {
                      red = 255;
                  }
                  if (green > 255)
                  {
                      green = 255;
                  }
                  if (blue > 255)
                  {
                      blue = 255;
                  }
      
                  // Assign new values to pixels
                  temp[i][j].rgbtRed = red;
                  temp[i][j].rgbtGreen = green;
                  temp[i][j].rgbtBlue = blue;
              }
          }
      
          for (int i = 0; i < height; i++)
          {
              for (int j = 0; j < width; j++)
              {
                  image[i][j] = temp[i][j];
              }
          }
      
          return;
      }

      Full solution to cs50 psets 4 filter – more comfortable problem

      #include "helpers.h"
      #include <math.h>
      
      // Convert image to grayscale
      void grayscale(int height, int width, RGBTRIPLE image[height][width])
      {
          // Iterate though each column
          for (int i = 0; i < height; i++)
          {
              // Iterate through each raw of pixel in each column
              for (int j = 0; j < width; j++)
              {
                  // Get into 2D array and obtain value of each color
                  int red = image[i][j].rgbtRed;
                  int blue = image[i][j].rgbtBlue;
                  int green = image[i][j].rgbtGreen;
      
                  // Calculate the rounded avarage of each pixel
                  int average = round(((float)red + (float)blue + (float)green) / 3);
      
                  // Set the calculated value to be the new value of each pixel
                  image[i][j].rgbtRed = image[i][j].rgbtBlue = image[i][j].rgbtGreen = average;
              }
          }
          return;
      }
      
      // Reflect image horizontally
      void reflect(int height, int width, RGBTRIPLE image[height][width])
      {
          for (int i = 0; i < height; i++)
          {
              // Iterate through the array until you get the mid point
              for (int j = 0; j < (width / 2); j++)
              {
                  RGBTRIPLE temp = image[i][j];
      
                  image[i][j] = image[i][width - (j + 1)];
                  image[i][width - (j + 1)] = temp;
              }
          }
          return;
      }
      
      // Blur image
      void blur(int height, int width, RGBTRIPLE image[height][width])
      {
          //create a temporary image to implement blurred algorithm on it.
          RGBTRIPLE temp[height][width];
      
          for (int i = 0; i < height; i++)
          {
              for (int j = 0; j < width; j++)
              {
                  int sumRed, sumBlue, sumGreen;
                  sumRed = sumBlue = sumGreen = 0;
                  float counter = 0.00;
      
                  //Get the neighbouring pexels
                  for (int c = -1; c < 2; c++)
                  {
                      for (int r = -1; r < 2; r++)
                      {
                          int currentX = i + c;
                          int currentY = j + r;
      
                          //check for valid neighbouring pexels
                          if (currentX < 0 || currentX > (height - 1) || currentY < 0 || currentY > (width - 1))
                          {
                              continue;
                          }
      
                          //Get the image value
                          sumRed += image[currentX][currentY].rgbtRed;
                          sumGreen += image[currentX][currentY].rgbtGreen;
                          sumBlue += image[currentX][currentY].rgbtBlue;
      
                          counter++;
                      }
      
                      //do the average of neigbhouring pexels
                      temp[i][j].rgbtRed = round(sumRed / counter);
                      temp[i][j].rgbtGreen = round(sumGreen / counter);
                      temp[i][j].rgbtBlue = round(sumBlue / counter);
                  }
              }
      
          }
      
          //copy the blurr image to the original image
          for (int i = 0; i < height; i++)
          {
              for (int j = 0; j < width; j++)
              {
                  image[i][j].rgbtRed = temp[i][j].rgbtRed;
                  image[i][j].rgbtGreen = temp[i][j].rgbtGreen;
                  image[i][j].rgbtBlue = temp[i][j].rgbtBlue;
              }
          }
          return;
      }
      
      // Detect edges
      void edges(int height, int width, RGBTRIPLE image[height][width])
      {
          RGBTRIPLE temp[height][width];
      
          int gx[3][3] = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}};
          int gy[3][3] = {{-1, -2, -1}, {0, 0, 0}, {1, 2, 1}};
      
          for (int i = 0; i < height; i++)
          {
              for (int j = 0; j < width; j++)
              {
                  float gxRed = 0;
                  float gyRed = 0;
                  float gxGreen = 0;
                  float gyGreen = 0;
                  float gxBlue = 0;
                  float gyBlue = 0;
      
                  for (int col = -1; col < 2; col++)
                  {
                      for (int row = -1; row < 2; row++)
                      {
                          if (i + col < 0 || i + col > height - 1)
                          {
                              continue;
                          }
                          if (j + row < 0 || j + row > width - 1)
                          {
                              continue;
                          }
      
                          gxRed += image[i + col][j + row].rgbtRed * gx[col + 1][row + 1];
                          gyRed += image[i + col][j + row].rgbtRed * gy[col + 1][row + 1];
                          gxGreen += image[i + col][j + row].rgbtGreen * gx[col + 1][row + 1];
                          gyGreen += image[i + col][j + row].rgbtGreen * gy[col + 1][row + 1];
                          gxBlue += image[i + col][j + row].rgbtBlue * gx[col + 1][row + 1];
                          gyBlue += image[i + col][j + row].rgbtBlue * gy[col + 1][row + 1];
                      }
                  }
      
                  int red = round(sqrt(gxRed * gxRed + gyRed * gyRed));
                  int green = round(sqrt(gxGreen * gxGreen + gyGreen * gyGreen));
                  int blue = round(sqrt(gxBlue * gxBlue + gyBlue * gyBlue));
      
                  // Cap at 255
                  if (red > 255)
                  {
                      red = 255;
                  }
                  if (green > 255)
                  {
                      green = 255;
                  }
                  if (blue > 255)
                  {
                      blue = 255;
                  }
      
                  // Assign new values to pixels
                  temp[i][j].rgbtRed = red;
                  temp[i][j].rgbtGreen = green;
                  temp[i][j].rgbtBlue = blue;
              }
          }
      
          for (int i = 0; i < height; i++)
          {
              for (int j = 0; j < width; j++)
              {
                  image[i][j] = temp[i][j];
              }
          }
      
          return;
      }

      The Solution to CS50 Psets 4 Recover Problem (2022)

      For this problem, we have to implement a C program that will recover JPEG images from a forensic images. So we have to write our code in recover.c file. So here is my solution to this problem.

      #include <stdio.h>
      #include <stdlib.h>
      #include <stdint.h>
      
      
      int main(int argc, char *argv[])
      {
          if (argc != 2)
          {
              printf("Usage: ./recover card.raw\n");
              return 1;
          }
          // Open file for read
          FILE *i = fopen(argv[1], "r");
          //If fail to open input file retun error message "Could not open file"
          if (i == NULL)
          {
              printf("Could not open file");
              return 2;
          }
      
          //declare a variable to unsigned char to store 512 chunks array
          unsigned char buffer[512];
      
          //declare a variable to count image later in the loop
          int c = 0;
      
          //file pointer use to output data gotten from input file
          FILE *o = NULL;
      
          char *f = malloc(8 * sizeof(char));
          // char file[8];
      
          //Read 512 bytes from input file and store on the buffer
          while (fread(buffer, sizeof(char), 512, i))
          {
              //check if bytes are from a JPEG
              if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
              {
                  //write jpeg inot file name in form 001.jpg, 002.jpg and so on
                  sprintf(f, "%03i.jpg", c);
      
                  //open output file for writing
                  o = fopen(f, "w");
      
                  //count number of images found
                  c++;
              }
      
              //Check if output have been used for valid input
              if (o != NULL)
              {
                  fwrite(buffer, sizeof(char), 512, o);
              }
          }
      
          free(f);
          fclose(o);
          fclose(i);
      }

      Hope these code solutions help you to solve your problems little bit easier. If it helps consider sharing with your friends that will need these solutions.

    • The Solution to CS50 Lab 04 Volume Problem (2022)

      The Solution to CS50 Lab 04 Volume Problem (2022)

      We can use C language to modify audio files. In this lab 4 problem, we have to write a C program to increase the volume of an audio file. The input audio file is given to us in .wav format (INPUT.wav). We need to write the program so that when the user executes the following command in the terminal will provide another .wav file which includes the Audio increased output.

      $ ./volume INPUT.wav OUTPUT.wav 2.0

      Here “volume” is the program that executes. “OUTPUT.wav” is the output file. And 2.0 is the factor in which the volume should be increased of the input file.

      Solution for the cs50 lab 04

      We have two tasks to do in this lab. The first one is to copy the header from input files to output files. The second task is to read samples from the input file and write updated data to the output file.

      Copy the header from input file to output file

          uint8_t header[HEADER_SIZE];
          fread(&header, HEADER_SIZE, 1, input);
          fwrite(&header, HEADER_SIZE, 1, output);

      Read samples from the input file and write updated data to the output file.

          int16_t buffer;
          while (fread(&buffer, sizeof(int16_t), 1, input))
          {
              // Apply factor to the output file
              buffer *= factor;
              fwrite(&buffer, sizeof(int16_t), 1, output);
          }

      Full code

      // Modifies the volume of an audio file
      
      #include <stdint.h>
      #include <stdio.h>
      #include <stdlib.h>
      
      // Number of bytes in .wav header
      const int HEADER_SIZE = 44;
      
      int main(int argc, char *argv[])
      {
          // Check command-line arguments
          if (argc != 4)
          {
              printf("Usage: ./volume input.wav output.wav factor\n");
              return 1;
          }
      
          // Open files and determine scaling factor
          FILE *input = fopen(argv[1], "r");
          if (input == NULL)
          {
              printf("Could not open file.\n");
              return 1;
          }
      
          FILE *output = fopen(argv[2], "w");
          if (output == NULL)
          {
              printf("Could not open file.\n");
              return 1;
          }
      
          float factor = atof(argv[3]);
      
          // TODO: Copy header from input file to output file
          uint8_t header[HEADER_SIZE];
          fread(&header, HEADER_SIZE, 1, input);
          fwrite(&header, HEADER_SIZE, 1, output);
      
          // TODO: Read samples from input file and write updated data to output file
          int16_t buffer;
          while (fread(&buffer, sizeof(int16_t), 1, input))
          {
              // Apply factor to the output file
              buffer *= factor;
              fwrite(&buffer, sizeof(int16_t), 1, output);
          }
      
          // Close files
          fclose(input);
          fclose(output);
      }

      Hope this helps! Leave a comment if you want more clarification on this!

    • The Solution to CS50 psets 3 Tideman Problem (2022)

      The Solution to CS50 psets 3 Tideman Problem (2022)

      In this problem set, we have to write a code that runs the Tideman election as shown in below code snippet.

      $ ./tideman Alice Bob Charlie
      Number of voters: 5
      Rank 1: Alice
      Rank 2: Charlie
      Rank 3: Bob
      
      Rank 1: Alice
      Rank 2: Charlie
      Rank 3: Bob
      
      Rank 1: Bob
      Rank 2: Charlie
      Rank 3: Alice
      
      Rank 1: Bob
      Rank 2: Charlie
      Rank 3: Alice
      
      Rank 1: Charlie
      Rank 2: Alice
      Rank 3: Bob
      
      Charlie

      In the previous posts, I gave you the solution to the cs50 psets 3 plurality problem, and cs50 psets 3 runoff problem.

      So the plurality election system and runoff election system have their own advantages and disadvantages. Now, let’s see what is the Tideman election system.

      Tideman Election System

      Tideman method is also known as the Ranked pairs method. This system was developed in 1987 by Nicolaus Tideman. This system selects a single winner using votes that express preferences. This method can also be used to create a sorted list of winners.

      So, let’s get back to the problem set, an initial code is given to us.

      Solution

      1. The vote function

      // Update ranks given a new vote
      bool vote(int rank, string name, int ranks[])
      {
          // TODO
          for (int i = 0; i < candidate_count; i++)
          {
              if (strcmp(name, candidates[i]) == 0)
              {
                  ranks[rank] = i;
                  return true;
              }
          }
          return false;
      }

      2. The record_preferences function

      // Update preferences given one voter's ranks
      void record_preferences(int ranks[])
      {
          // TODO
          for (int i = 0; i < candidate_count; i++)
          {
              for (int j = i + 1; j < candidate_count; j++)
              {
                  preferences[ranks[i]][ranks[j]]++;
              }
          }
          return;
      }

      3. The add_pairs function

      // Record pairs of candidates where one is preferred over the other
      void add_pairs(void)
      {
          // TODO
          for (int i = 0; i < candidate_count; i++)
          {
              for (int j = i + 1; j < candidate_count; j++)
              {
                  if (preferences[i][j] > preferences[j][i])
                  {
                      pairs[pair_count].winner = i;
                      pairs[pair_count].loser = j;
                      pair_count++;
                  }
                  else if (preferences[i][j] < preferences[j][i])
                  {
                      pairs[pair_count].winner = j;
                      pairs[pair_count].loser = i;
                      pair_count++;
                  }
              }
          }
          return;
      }

      4. The sort_pairs function

      // Sort pairs in decreasing order by strength of victory
      void sort_pairs(void)
      {
          // TODO
          for (int i = 0; i < pair_count; i++)
          {
              int max = i;
              for (int j = i; j < pair_count; j++)
              {
                  if (preferences[pairs[j].winner][pairs[j].loser] > preferences[pairs[max].winner][pairs[max].loser])
                  {
                      max = j;
                  }
              }
              pair temp = pairs[i];
              pairs[i] = pairs[max];
              pairs[max] = temp;
          }
          return;
      }

      5. The cycle function

      // Check for cycle by checking arrow coming into each candidate
      bool cycle(int cycle_end, int cycle_start)
      {
          // Return true if there is a cycle
          if (cycle_end == cycle_start)
          {
              return true;
          }
      
          // Loop through all the candidates
          for (int i = 0; i < candidate_count; i++)
          {
              if (locked[cycle_end][i])
              {
                  if (cycle(i, cycle_start))
                  {
                      return true;
                  }
              }
          }
          return false;
      }

      6. The lock_pairs function

      // Lock pairs into the candidate graph in order, without creating cycles
      void lock_pairs(void)
      {
          // TODO
          for (int i = 0; i < pair_count; i++)
          {
              if (!cycle(pairs[i].loser, pairs[i].winner))
              {
                  locked[pairs[i].winner][pairs[i].loser] = true;
              }
          }
          return;
      }

      7. The print_winner function

      // Print the winner of the election
      void print_winner(void)
      {
          // TODO
          for (int i = 0; i < candidate_count; i++)
          {
              bool loser = false;
              for (int j = 0; j < candidate_count; j++)
              {
                  if (locked[j][i])
                  {
                      loser = true;
                      break;
                  }
              }
              if (loser)
              {
                  continue;
              }
              if (!loser)
              {
                  printf("%s\n", candidates[i]);
              }
          }
          return;
      }

      Full Code

      here is the full code that includes all the functions,

      #include <cs50.h>
      #include <stdio.h>
      #include <string.h>
      
      // Max number of candidates
      #define MAX 9
      
      // preferences[i][j] is number of voters who prefer i over j
      int preferences[MAX][MAX];
      
      // locked[i][j] means i is locked in over j
      bool locked[MAX][MAX];
      
      // Each pair has a winner, loser
      typedef struct
      {
          int winner;
          int loser;
      }
      pair;
      
      // Array of candidates
      string candidates[MAX];
      pair pairs[MAX * (MAX - 1) / 2];
      
      int pair_count;
      int candidate_count;
      
      // Function prototypes
      bool vote(int rank, string name, int ranks[]);
      void record_preferences(int ranks[]);
      void add_pairs(void);
      void sort_pairs(void);
      void lock_pairs(void);
      void print_winner(void);
      bool cycle(int cycle_end, int cycle_start);
      
      int main(int argc, string argv[])
      {
          // Check for invalid usage
          if (argc < 2)
          {
              printf("Usage: tideman [candidate ...]\n");
              return 1;
          }
      
          // Populate array of candidates
          candidate_count = argc - 1;
          if (candidate_count > MAX)
          {
              printf("Maximum number of candidates is %i\n", MAX);
              return 2;
          }
          for (int i = 0; i < candidate_count; i++)
          {
              candidates[i] = argv[i + 1];
          }
      
          // Clear graph of locked in pairs
          for (int i = 0; i < candidate_count; i++)
          {
              for (int j = 0; j < candidate_count; j++)
              {
                  locked[i][j] = false;
              }
          }
      
          pair_count = 0;
          int voter_count = get_int("Number of voters: ");
      
          // Query for votes
          for (int i = 0; i < voter_count; i++)
          {
              // ranks[i] is voter's ith preference
              int ranks[candidate_count];
      
              // Query for each rank
              for (int j = 0; j < candidate_count; j++)
              {
                  string name = get_string("Rank %i: ", j + 1);
      
                  if (!vote(j, name, ranks))
                  {
                      printf("Invalid vote.\n");
                      return 3;
                  }
              }
      
              record_preferences(ranks);
      
              printf("\n");
          }
      
          add_pairs();
          sort_pairs();
          lock_pairs();
          print_winner();
          return 0;
      }
      
      // Update ranks given a new vote
      bool vote(int rank, string name, int ranks[])
      {
          // TODO
          for (int i = 0; i < candidate_count; i++)
          {
              if (strcmp(name, candidates[i]) == 0)
              {
                  ranks[rank] = i;
                  return true;
              }
          }
          return false;
      }
      
      // Update preferences given one voter's ranks
      void record_preferences(int ranks[])
      {
          // TODO
          for (int i = 0; i < candidate_count; i++)
          {
              for (int j = i + 1; j < candidate_count; j++)
              {
                  preferences[ranks[i]][ranks[j]]++;
              }
          }
          return;
      }
      
      // Record pairs of candidates where one is preferred over the other
      void add_pairs(void)
      {
          // TODO
          for (int i = 0; i < candidate_count; i++)
          {
              for (int j = i + 1; j < candidate_count; j++)
              {
                  if (preferences[i][j] > preferences[j][i])
                  {
                      pairs[pair_count].winner = i;
                      pairs[pair_count].loser = j;
                      pair_count++;
                  }
                  else if (preferences[i][j] < preferences[j][i])
                  {
                      pairs[pair_count].winner = j;
                      pairs[pair_count].loser = i;
                      pair_count++;
                  }
              }
          }
          return;
      }
      
      // Sort pairs in decreasing order by strength of victory
      void sort_pairs(void)
      {
          // TODO
          for (int i = 0; i < pair_count; i++)
          {
              int max = i;
              for (int j = i; j < pair_count; j++)
              {
                  if (preferences[pairs[j].winner][pairs[j].loser] > preferences[pairs[max].winner][pairs[max].loser])
                  {
                      max = j;
                  }
              }
              pair temp = pairs[i];
              pairs[i] = pairs[max];
              pairs[max] = temp;
          }
          return;
      }
      
      // Check for cycle by checking arrow coming into each candidate
      
      bool cycle(int cycle_end, int cycle_start)
      {
          // Return true if there is a cycle
          if (cycle_end == cycle_start)
          {
              return true;
          }
      
          // Loop through all the candidates
          for (int i = 0; i < candidate_count; i++)
          {
              if (locked[cycle_end][i])
              {
                  if (cycle(i, cycle_start))
                  {
                      return true;
                  }
              }
          }
          return false;
      }
      
      // Lock pairs into the candidate graph in order, without creating cycles
      void lock_pairs(void)
      {
          // TODO
          for (int i = 0; i < pair_count; i++)
          {
              if (!cycle(pairs[i].loser, pairs[i].winner))
              {
                  locked[pairs[i].winner][pairs[i].loser] = true;
              }
          }
          return;
      }
      
      // Print the winner of the election
      void print_winner(void)
      {
          // TODO
          for (int i = 0; i < candidate_count; i++)
          {
              bool loser = false;
              for (int j = 0; j < candidate_count; j++)
              {
                  if (locked[j][i])
                  {
                      loser = true;
                      break;
                  }
              }
              if (loser)
              {
                  continue;
              }
              if (!loser)
              {
                  printf("%s\n", candidates[i]);
              }
          }
          return;
      }

      Hope this helps you, Good luck!

    • CS50 psets 3 runoff problem my solution with code (2022)

      CS50 psets 3 runoff problem my solution with code (2022)

      This is my solution to cs50 psets 3 runoff problem. In this problem set, we have to create a program that runs a program of the runoff election.

      In the previous post, I brought you my solution to the CS50 psets 3 plurality problem. But that program follows a very simple algorithm to determine the winner of an election. It is simply every voter gets one vote and the candidate with the most votes wins.

      But what if two candidates get the same amount of votes? the above program does not have a solution for that. In this runoff, the method gives a solution to that problem. So in this method, each voter gets 3 chances to vote and rank their favorite candidate.

      When you read the full description of psets 3 you’ll understand what is runoff method and how it solve the voting problem. I’m not going to explain it here again.

      Let’s see what is my solution to the cs50 psets 3 runoff problem. Here is my code,

      #include <cs50.h>
      #include <stdio.h>
      #include <string.h>
      #include <math.h>
      
      // Max voters and candidates
      #define MAX_VOTERS 100
      #define MAX_CANDIDATES 9
      
      // preferences[i][j] is jth preference for voter i
      int preferences[MAX_VOTERS][MAX_CANDIDATES];
      
      // Candidates have name, vote count, eliminated status
      typedef struct
      {
          string name;
          int votes;
          bool eliminated;
      }
      candidate;
      
      // Array of candidates
      candidate candidates[MAX_CANDIDATES];
      
      // Numbers of voters and candidates
      int voter_count;
      int candidate_count;
      
      // Function prototypes
      bool vote(int voter, int rank, string name);
      void tabulate(void);
      bool print_winner(void);
      int find_min(void);
      bool is_tie(int min);
      void eliminate(int min);
      
      int main(int argc, string argv[])
      {
          // Check for invalid usage
          if (argc < 2)
          {
              printf("Usage: runoff [candidate ...]\n");
              return 1;
          }
      
          // Populate array of candidates
          candidate_count = argc - 1;
          if (candidate_count > MAX_CANDIDATES)
          {
              printf("Maximum number of candidates is %i\n", MAX_CANDIDATES);
              return 2;
          }
          for (int i = 0; i < candidate_count; i++)
          {
              candidates[i].name = argv[i + 1];
              candidates[i].votes = 0;
              candidates[i].eliminated = false;
          }
      
          voter_count = get_int("Number of voters: ");
          if (voter_count > MAX_VOTERS)
          {
              printf("Maximum number of voters is %i\n", MAX_VOTERS);
              return 3;
          }
      
          // Keep querying for votes
          for (int i = 0; i < voter_count; i++)
          {
      
              // Query for each rank
              for (int j = 0; j < candidate_count; j++)
              {
                  string name = get_string("Rank %i: ", j + 1);
      
                  // Record vote, unless it's invalid
                  if (!vote(i, j, name))
                  {
                      printf("Invalid vote.\n");
                      return 4;
                  }
              }
      
              printf("\n");
          }
      
          // Keep holding runoffs until winner exists
          while (true)
          {
              // Calculate votes given remaining candidates
              tabulate();
      
              // Check if election has been won
              bool won = print_winner();
              if (won)
              {
                  break;
              }
      
              // Eliminate last-place candidates
              int min = find_min();
              bool tie = is_tie(min);
      
              // If tie, everyone wins
              if (tie)
              {
                  for (int i = 0; i < candidate_count; i++)
                  {
                      if (!candidates[i].eliminated)
                      {
                          printf("%s\n", candidates[i].name);
                      }
                  }
                  break;
              }
      
              // Eliminate anyone with minimum number of votes
              eliminate(min);
      
              // Reset vote counts back to zero
              for (int i = 0; i < candidate_count; i++)
              {
                  candidates[i].votes = 0;
              }
          }
          return 0;
      }
      
      // Record preference if vote is valid
      bool vote(int voter, int rank, string name)
      {
          // TODO
          for (int i = 0; i < candidate_count; i++)
          {
              if (strcmp(name, candidates[i].name) == 0)
              {
                  preferences[voter][rank] = i;
                  return true;
              }
          }
          return false;
      }
      
      // Tabulate votes for non-eliminated candidates
      void tabulate(void)
      {
          // TODO
          for (int i = 0; i < voter_count; i++)
          {
              for (int j = 0; j < candidate_count; j++)
              {
                  if (candidates[preferences[i][j]].eliminated == false)
                  {
                      candidates[preferences[i][j]].votes += 1;
                      break;
                  }
              }
          }
          return;
      }
      
      // Print the winner of the election, if there is one
      bool print_winner(void)
      {
          // TODO
          for (int i = 0; i < candidate_count; i++)
          {
              string most_votes = candidates[i].name;
              if (candidates[i].votes > voter_count / 2)
              {
                  printf("%s\n", most_votes);
                  return true;
              }
          }
          return false;
      }
      
      // Return the minimum number of votes any remaining candidate has
      int find_min(void)
      {
          // TODO
          int min_votes = voter_count;
          for (int i = 0; i < candidate_count; i++)
          {
              if (candidates[i].eliminated == false && candidates[i].votes < min_votes)
              {
                  min_votes = candidates[i].votes;
              }
          }
          return min_votes;
      }
      
      // Return true if the election is tied between all candidates, false otherwise
      bool is_tie(int min)
      {
          // TODO
          for (int i = 0; i < candidate_count; i++)
          {
              if (candidates[i].eliminated == false && candidates[i].votes != min)
              {
                  return false;
              }
          }
          return true;
      }
      
      // Eliminate the candidate (or candidates) in last place
      void eliminate(int min)
      {
          // TODO
          for (int i = 0; i < candidate_count; i++)
          {
              if (candidates[i].votes == min)
              {
                  candidates[i].eliminated = true;
              }
          }
          return;
      }

      Hope this helps you!