<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alexey Medvecky on Medium]]></title>
        <description><![CDATA[Stories by Alexey Medvecky on Medium]]></description>
        <link>https://medium.com/@alexey.medvecky?source=rss-80593edba6a8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hnRM1sR8_RNvaIfLTEIvoQ.jpeg</url>
            <title>Stories by Alexey Medvecky on Medium</title>
            <link>https://medium.com/@alexey.medvecky?source=rss-80593edba6a8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:07:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexey.medvecky/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AI in the 80s? How a Simple Animal Guessing Game Pioneered Machine Learning Before It Was Cool]]></title>
            <link>https://medium.com/@alexey.medvecky/ai-in-the-80s-how-a-simple-animal-guessing-game-pioneered-machine-learning-before-it-was-cool-2f4a63dfe762?source=rss-80593edba6a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f4a63dfe762</guid>
            <category><![CDATA[machinelearninghistory]]></category>
            <category><![CDATA[80stech]]></category>
            <category><![CDATA[programmingnostalgia]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Alexey Medvecky]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 10:15:18 GMT</pubDate>
            <atom:updated>2024-12-19T10:15:18.643Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UD_M2vx4X0tad_6PHhU74Q.png" /></figure><h3><strong>Introduction</strong></h3><p>Recently, I stumbled upon an old programming book on the shelf in the library of my childhood. Yellowed pages, the smell of dust, and lines printed in monochrome style. Among examples of seemingly long-outdated algorithms, I came across a game called <em>“Guess the Animal.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*sM2JimPwk7cgMO0EhvMf0Q.png" /></figure><p>At first glance, it appeared completely primitive: the program asks questions, and the user answers “yes” or “no.” But the deeper I delved into the code, the more I was filled with a sense of wonder. This was a real self-learning program! It didn’t just attempt to guess the chosen animal but also learned from its mistakes, adding new questions and answers to its knowledge base. What’s more, it had the ability to save progress and load it during the next run.</p><p>In the 1980s, long before machine learning and the hype around artificial intelligence, programmers were already toying with the ideas of trainable algorithms. It wasn’t ChatGPT or AlphaGo but a simple game written in BASIC that used the same principles underlying modern AI systems.</p><p>Thus, I decided to recreate this algorithm in a modern programming language — C++ — and show how a simple children’s game from the past anticipated the era of machine learning.</p><h3>Algorithm re-creation.</h3><h4>Main concepts</h4><p><strong>Decision Tree — How the Program “Thinks”</strong><br> The foundation of the <em>“Guess the Animal”</em> game is a decision tree — a data structure that allows the program to ask questions step by step, clarifying details and narrowing down the range of possible answers. Each node in the tree can be either a question or an answer (an animal).<br> Let’s break down how this tree works in practice.</p><p><strong>Tree Structure</strong><br>Imagine a tree where each question is a fork. If the user answers “yes,” the program moves along the left branch, and if “no,” it moves along the right branch.<br>Questions are intermediate nodes that help the program progress further.<br>Answers (animals) are leaf nodes, where the program attempts to guess the chosen animal.<br>Here’s what it looks like:</p><pre>                  Is it a mammal?<br>                   /          \<br>                yes           no<br>             Whale?        Penguin?<br>            /     \        /       \<br>         (yes)   (no)    (yes)    (no)</pre><p>The program asks the question: <em>“Is it a mammal?”</em><br>If the player answers <em>“yes,”</em> the program moves to the left and asks: <em>“Is it a whale?”</em><br>If the answer is <em>“yes,”</em> the game has guessed correctly. If <em>“no,”</em> the program learns and adds a new node with a clarifying question.</p><p><strong>How the Program “Learns”</strong><br>The learning process is what makes the game unique. When the program makes a mistake, it asks the user to:</p><ul><li>Name the chosen animal.</li><li>Specify a question that distinguishes the new animal from the previous one.</li><li>Indicate the correct answer (“yes” or “no”) to the new question for the new animal.</li></ul><p><strong>Example:</strong><br>The program asks: <em>“Is it a whale?”</em><br>The player answers <em>“no”</em> and says it’s a dolphin.<br>The program asks for clarification: <em>“What question distinguishes a dolphin from a whale?”</em><br>The player answers: <em>“Does it live in the ocean but isn’t as large?”</em></p><p>As a result, the program adds the new question and animals to the decision tree.<br>The updated structure looks like this:</p><pre>               Is it a mammal?<br>                   /          \<br>                yes           no<br>          Is it large?       Penguin?<br>            /      \<br>          yes      no<br>        Whale     Dolphin</pre><p>The program “remembers” these changes, and during the next run, it will be able to guess the dolphin along with other animals.</p><h4><strong>Implementation in Code</strong></h4><p>In C++, the tree is represented as an array of nodes, where each node stores:</p><ul><li>A question or an animal (as a string).</li><li>A flag isAnimal — to distinguish leaf nodes (answers) from questions.</li></ul><p>Here is the node structure and the program’s logic:</p><pre>struct TreeNode<br>{<br>    std::string question; // Question or animal name<br>    bool isAnimal;   // True if the node represents an animal, false if it&#39;s a question<br>};<br><br>void askQuestion( int index )<br>{<br>    if ( index &gt;= MAX_NODES || tree[ index ].question.empty() )<br>    {<br>        std::cout &lt;&lt; &quot;Error: Invalid tree structure!&quot; &lt;&lt; std::endl;<br>        return;<br>    }<br><br>    if ( tree[ index ].isAnimal )<br>    {<br>        // If it&#39;s a leaf node, make a guess<br>        std::cout &lt;&lt; &quot;Is your animal: &quot; &lt;&lt; tree[ index ].question &lt;&lt; &quot;? (yes/no): &quot;;<br>        std::string answer;<br>        std::cin &gt;&gt; answer;<br><br>        if ( answer == &quot;yes&quot; )<br>        {<br>            std::cout &lt;&lt; &quot;Great! I guessed it!&quot; &lt;&lt; std::endl;<br>        }<br>        else<br>        {<br>            std::cout &lt;&lt; &quot;What was your animal?: &quot;;<br>            std::cin.ignore(); // Clear the input buffer<br>            std::string newAnimal;<br>            std::getline( std::cin, newAnimal );<br><br>            std::cout &lt;&lt; &quot;What question differentiates &quot; &lt;&lt; newAnimal<br>                 &lt;&lt; &quot; from &quot; &lt;&lt; tree[ index ].question &lt;&lt; &quot;?: &quot;;<br>            std::string newQuestion;<br>            std::getline( std::cin, newQuestion );<br><br>            std::cout &lt;&lt; &quot;For &quot; &lt;&lt; newAnimal &lt;&lt; &quot;, is the answer &#39;yes&#39; or &#39;no&#39; to this question?: &quot;;<br>            std::string newAnswer;<br>            std::cin &gt;&gt; newAnswer;<br><br>            // Update the tree with the new question and animals<br>            int leftIdx = leftChild( index );<br>            int rightIdx = rightChild( index );<br><br>            if ( leftIdx &lt; MAX_NODES &amp;&amp; rightIdx &lt; MAX_NODES )<br>            {<br>                tree[ leftIdx ] = { newAnimal, true };         // Add the new animal<br>                tree[ rightIdx ] = { tree[ index ].question, true }; // Move the old animal<br>                tree[ index ] = { newQuestion, false };        // Update the current node<br><br>                // If the answer for the new animal is &quot;no&quot;, swap the children<br>                if ( newAnswer == &quot;no&quot; )<br>                {<br>                    std::swap( tree[ leftIdx ], tree[ rightIdx ] );<br>                }<br>            }<br>            else<br>            {<br>                std::cout &lt;&lt; &quot;Error: Tree capacity exceeded!&quot; &lt;&lt; std::endl;<br>            }<br>        }<br>    }<br>    else<br>    {<br>        // Ask the current question and continue traversal<br>        std::cout &lt;&lt; tree[ index ].question &lt;&lt; &quot; (yes/no): &quot;;<br>        std::string answer;<br>        std::cin &gt;&gt; answer;<br><br>        if ( answer == &quot;yes&quot; )<br>        {<br>            askQuestion( leftChild( index ) );<br>        }<br>        else<br>        {<br>            askQuestion( rightChild( index ) );<br>        }<br>    }<br>}</pre><p>Example of Populating the Node Array:</p><pre>Index | Question             | isAnimal   <br>----------------------------------------  <br>1     | Is it a mammal?      | false  <br>2     | Whale                | true  <br>3     | Penguin              | true</pre><p>The program uses indices to navigate the tree. The root node always has index 1, and its child nodes are calculated using the formulas:</p><ul><li>Left child: 2 * index</li><li>Right child: 2 * index + 1</li></ul><p><strong>Game Logic: Recursive Tree Traversal</strong><br>The main function responsible for asking questions and learning is called askQuestion. It takes the index of the current node and works as follows:</p><ul><li>If the node is an animal, the program attempts to guess.</li><li>If the node is a question, the program asks it and moves to the next node depending on the answer.</li></ul><p><strong>Let’s break it down with an example:</strong><br> The program asks the question: <em>“Is it a mammal?”</em></p><ul><li>If the answer is <em>“yes,”</em> the program moves to the left branch and asks: <em>“Is it a whale?”</em></li><li>If the answer is <em>“no,”</em> the program asks the user to add a new animal and a question.</li></ul><p>In this way, the tree expands, and the program becomes “smarter.”</p><p><strong>Saving and Loading Progress</strong><br>To save and load the tree, the program uses a text file.</p><p><strong>Saving the Tree:</strong><br>The saveTreeToFile function saves non-empty tree nodes to a file as strings:</p><pre>index|question|isAnimal  </pre><pre>void saveTreeToFile( const std::string &amp; filename )<br>{<br>    std::ofstream outFile( filename );<br>    if ( !outFile )<br>    {<br>        std::cerr &lt;&lt; &quot;Error: Unable to open file for saving!&quot; &lt;&lt; std::endl;<br>        return;<br>    }<br><br>    for ( int i = 1; i &lt; MAX_NODES; i++ )<br>    {<br>        if ( !tree[ i ].question.empty() )<br>        {<br>            outFile &lt;&lt; i &lt;&lt; &quot;|&quot; &lt;&lt; tree[ i ].question &lt;&lt; &quot;|&quot; &lt;&lt; tree[ i ].isAnimal &lt;&lt; std::endl;<br>        }<br>    }<br><br>    outFile.close();<br>    std::cout &lt;&lt; &quot;Tree saved to &quot; &lt;&lt; filename &lt;&lt; &quot; successfully!&quot; &lt;&lt; std::endl;<br>}</pre><p><strong>Loading the Tree:</strong><br>The loadTreeFromFile function restores the tree from the file</p><pre>void loadTreeFromFile( const std::string &amp; filename )<br>{<br>    std::ifstream inFile( filename );<br>    if ( !inFile )<br>    {<br>        std::cerr &lt;&lt; &quot;Error: Unable to open file for loading!&quot; &lt;&lt; std::endl;<br>        return;<br>    }<br><br>    // Clear the tree<br>    for ( int i = 1; i &lt; MAX_NODES; ++i )<br>    {<br>        tree[ i ] = { &quot;&quot;, false };<br>    }<br><br>    int index;<br>    std::string question;<br>    bool isAnimal;<br>    std::string line;<br><br>    while ( std::getline( inFile, line ) )<br>    {<br>        size_t pos1 = line.find( &#39;|&#39; );<br>        size_t pos2 = line.rfind( &#39;|&#39; );<br><br>        index = stoi( line.substr( 0, pos1 ) );<br>        question = line.substr( pos1 + 1, pos2 - pos1 - 1 );<br>        isAnimal = stoi( line.substr( pos2 + 1 ) );<br><br>        tree[ index ] = { question, isAnimal };<br>    }<br><br>    inFile.close();<br>    std::cout &lt;&lt; &quot;Tree loaded from &quot; &lt;&lt; filename &lt;&lt; &quot; successfully!&quot; &lt;&lt; std::endl;<br>}</pre><p><strong>Main Menu of the Game</strong><br>The main function implements a user interface with the following options:</p><ul><li><strong>Play (p):</strong> Start guessing animals.</li><li><strong>Save progress (s):</strong> Save the current tree to a file.</li><li><strong>Load progress (l):</strong> Restore the tree from a file.</li><li><strong>Quit (q):</strong> Exit the program.</li></ul><pre>int main()<br>{<br>    // Initialize the tree with a single animal<br>    tree[ 1 ] = { &quot;Whale&quot;, true };<br><br>    std::cout &lt;&lt; &quot;Think of an animal, and I will try to guess it.&quot; &lt;&lt; std::endl;<br><br>    while ( true )<br>    {<br>        std::cout &lt;&lt; &quot;Do you want to (p)lay, (s)ave, (l)oad, or (q)uit?: &quot;;<br>        char choice;<br>        std::cin &gt;&gt; choice;<br><br>        if ( choice == &#39;p&#39; )<br>        {<br>            askQuestion( 1 ); // Start at the root node<br>        }<br>        else if (choice == &#39;s&#39;)<br>        {<br>            saveTreeToFile( &quot;tree_data.txt&quot; );<br>        }<br>        else if ( choice == &#39;l&#39; )<br>        {<br>            loadTreeFromFile( &quot;tree_data.txt&quot; );<br>        }<br>        else if ( choice == &#39;q&#39; )<br>        {<br>            break;<br>        }<br>        else<br>        {<br>            std::cout &lt;&lt; &quot;Invalid choice! Please enter &#39;p&#39;, &#39;s&#39;, &#39;l&#39;, or &#39;q&#39;.&quot; &lt;&lt; std::endl;<br>        }<br>    }<br><br>    std::cout &lt;&lt; &quot;Thanks for playing!&quot; &lt;&lt; std::endl;<br><br>    return EXIT_SUCCESS;<br>}</pre><h4><strong>Implementation of the “Guess the Animal” Game in BASIC</strong></h4><p>The provided listing represents a classic implementation of the <em>“Guess the Animal”</em> game in BASIC — a programming language popular in the 1970s and 1980s. It is an amazing example of how, even with such a simple language, it is possible to build a self-learning algorithm with dynamic expansion of “knowledge” and the ability to save new questions.</p><pre>10 PRINT TAB(32); &quot;ANIMAL&quot;<br>20 PRINT TAB(15); &quot;CREATIVE COMPUTING MORRISTOWN, NEW JERSEY&quot;<br>30 PRINT: PRINT: PRINT<br>40 PRINT &quot;PLAY &#39;GUESS THE ANIMAL&#39;&quot;<br>50 PRINT &quot;THINK OF AN ANIMAL AND THE COMPUTER WILL TRY TO GUESS IT.&quot;<br>60 PRINT<br>70 DIM A$(200)<br>80 FOR I=0 TO 3<br>90 READ A$(I)<br>100 NEXT I<br>110 N=VAL(A$(0))<br><br>120 REM MAIN CONTROL SECTION<br>130 INPUT &quot;ARE YOU THINKING OF AN ANIMAL&quot;; A$<br>140 IF A$=&quot;LIST&quot; THEN 600<br>150 IF LEFT$(A$,1)&lt;&gt;&quot;Y&quot; THEN 120<br>160 K=1<br>170 GOSUB 390<br>180 IF LEN(A$(K))=0 THEN 999<br>190 IF LEFT$(A$(K),2)=&quot;\Q&quot; THEN 170<br>200 PRINT &quot;IS IT A &quot;; RIGHT$(A$(K),LEN(A$(K))-2);<br>210 INPUT A$<br>220 A$=LEFT$(A$,1)<br>230 IF A$=&quot;Y&quot; THEN PRINT &quot;WHY NOT TRY ANOTHER ANIMAL?&quot;: GOTO 120<br>240 INPUT &quot;THE ANIMAL YOU WERE THINKING OF WAS A &quot;; V$<br>250 PRINT &quot;PLEASE TYPE IN A QUESTION THAT WOULD DISTINGUISH A&quot;<br>260 PRINT V$; &quot; FROM A &quot;; RIGHT$(A$(K),LEN(A$(K))-2)<br>270 INPUT X$<br>280 PRINT &quot;FOR A &quot;; V$; &quot; THE ANSWER WOULD BE &quot;;<br>290 INPUT A$<br>300 A$=LEFT$(A$,1): IF A$&lt;&gt;&quot;Y&quot; AND A$&lt;&gt;&quot;N&quot; THEN 280<br>310 IF A$=&quot;Y&quot; THEN B$=&quot;N&quot;<br>320 IF A$=&quot;N&quot; THEN B$=&quot;Y&quot;<br>330 Z1=VAL(A$(0))<br>340 A$(0)=STR$(Z1+2)<br>350 A$(Z1)=A$(K)<br>360 A$(Z1+1)=&quot;\A&quot;+V$<br>370 A$(K)=&quot;\Q&quot;+X$+&quot;\&quot;+A$+STR$(Z1+1)+&quot;\&quot;+B$+STR$(Z1)+&quot;\&quot;<br>380 GOTO 120<br><br>390 REM SUBROUTINE TO PRINT QUESTIONS<br>400 Q$=A$(K)<br>410 FOR Z=3 TO LEN(Q$)<br>415 IF MID$(Q$,Z,1)&lt;&gt;&quot;\&quot; THEN PRINT MID$(Q$,Z,1);: NEXT Z<br>420 INPUT C$<br>430 C$=LEFT$(C$,1)<br>440 IF C$&lt;&gt;&quot;Y&quot; AND C$&lt;&gt;&quot;N&quot; THEN 410<br>450 T$=&quot;\&quot;+C$<br>455 FOR X=3 TO LEN(Q$)-1<br>460 IF MID$(Q$,X,2)=T$ THEN 480<br>470 NEXT X<br>475 STOP<br>480 FOR Y=X+1 TO LEN(Q$)<br>490 IF MID$(Q$,Y,1)=&quot;\&quot; THEN 510<br>500 NEXT Y<br>505 STOP<br>510 K=VAL(MID$(Q$,X+2,Y-X-2))<br>520 RETURN<br><br>530 DATA &quot;4&quot;,&quot;\QDOES IT SWIM\Y2\N3\&quot;,&quot;\AFISH&quot;,&quot;\ABIRD&quot;<br>600 PRINT: PRINT &quot;ANIMALS I ALREADY KNOW ARE:&quot;<br>605 X=0<br>610 FOR I=1 TO 200<br>620 IF LEFT$(A$(I),2)&lt;&gt;&quot;\A&quot; THEN 650<br>624 PRINT TAB(12*X);<br>630 FOR Z=3 TO LEN(A$(I))<br>640 IF MID$(A$(I),Z,1)&lt;&gt;&quot;\&quot; THEN PRINT MID$(A$(I),Z,1);:NEXT Z<br>645 X=X+1: IF X&gt;5 THEN X=0: PRINT<br>650 NEXT I<br>660 PRINT<br>670 PRINT<br>680 GOTO 120<br>999 END</pre><p><strong>Analysis of the Implementation</strong><br>The decision tree is represented as a linear array with encoded nodes and transitions.</p><p><strong>Self-learning logic is implemented through:</strong></p><ul><li>Adding new questions and answers to the array.</li><li>Rewriting the current node with a new question and transitions.</li></ul><p><strong>Limitations:</strong></p><ul><li>Maximum number of nodes: 200.</li><li>The structure is stored only in memory (no disk saving).</li></ul><p><strong>Advantages:</strong></p><ul><li>A simple and elegant approach to learning based on feedback.</li><li>Clear structure and minimal logic for processing answers.</li></ul><h3><strong>Conclusion</strong></h3><p>The implementation in BASIC is a historical example of effectively using limited resources. It demonstrates how a decision tree and a self-learning algorithm can be implemented on a simple language. However, it has limitations:</p><ul><li>No ability to save progress.</li><li>String parsing complicates navigation and slows down program execution.</li></ul><p>The implementation in C++ shows how modern tools make code more structured, readable, and efficient:</p><ul><li>The use of data structures and indices simplifies tree navigation.</li><li>File input/output enables saving and restoring progress between sessions.</li></ul><p>From an algorithmic complexity perspective, both implementations have the same asymptotic behavior for searching and learning. However, C++ is faster in constant time due to more efficient data handling.</p><p><strong>Final Thoughts</strong><br>Both versions of the <em>“Guess the Animal”</em> program are examples of how simple ideas, such as decision trees and self-learning, anticipated modern AI technologies. In the 1980s, without big data or neural networks, programmers were already creating algorithms capable of “learning” from mistakes and adapting to new information.</p><p>This reminds us that the key lies in the idea and algorithm, not the complexity of the tool.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f4a63dfe762" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Heaps: From C++ Simplicity to Custom C Implementation That Powers Efficient Algorithms!]]></title>
            <link>https://medium.com/@alexey.medvecky/mastering-heaps-from-c-simplicity-to-custom-c-implementation-that-powers-efficient-algorithms-27ff2938ecaa?source=rss-80593edba6a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/27ff2938ecaa</guid>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[heap]]></category>
            <dc:creator><![CDATA[Alexey Medvecky]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 08:19:39 GMT</pubDate>
            <atom:updated>2025-01-03T10:24:28.339Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n2ObPNiqXP95zHjTp5kKEA.png" /></figure><h3><strong>Introduction</strong></h3><p>Have you ever encountered a problem that initially seems simple but turns out to be a brilliant exercise in algorithm design? That’s exactly how I felt when tackling the “Maintaining the Median” problem.</p><p>Today, I’ll guide you through solving this challenge in C++ using the Standard Template Library (STL). Then, we’ll take it up a notch by implementing our own heap from scratch in C. Ready to dive in?</p><h4><strong>Problem Statement</strong></h4><p>The task is to implement the “Maintaining the Median” algorithm. A text file contains a list of integers ranging from 1 to 10,000 in an unsorted order, and you should treat this as a stream of numbers arriving one by one. Let xi be the i-th number in the file; then the k-th median mk is defined as the median of the numbers x1,…,xk. (Thus, if k is odd, mk is the ((k + 1) / 2)-th smallest number among x1,…,xk; if k is even, mk is the (k / 2)-th smallest number among x1,…,xk.)</p><p>In the field below, you must input the sum of these 10,000 medians modulo 10,000 (i.e., only the last 4 digits). In other words, you need to compute:(m1+m2+m3+⋯+m10,000)mod 10,000.</p><p><strong>Examples of Problem Applications</strong></p><ul><li><strong>Real-time Data Stream Processing</strong>: Maintaining the median is used for analyzing real-time data streams, such as in network monitoring systems, where it helps track median packet delays.</li><li><strong>Financial Applications</strong>: In financial systems, the median is used to analyze price changes, filtering out sudden price spikes to provide a more stable view of market trends.</li><li><strong>Healthcare</strong>: When monitoring patient health metrics such as blood pressure or blood sugar levels, the median helps account for current trends while excluding outliers caused by measurement errors.</li><li><strong>Recommendation Systems</strong>: In recommendation systems, the median can be used to filter user ratings and determine a fairer average rating for a movie, book, or product.</li></ul><h3>Problem Solution</h3><h4><strong>Why Heaps?</strong></h4><p>A heap is a data structure that represents a binary tree satisfying the heap property:</p><ul><li>In a <strong>max-heap</strong>, the parent node is greater than or equal to its child nodes.</li><li>In a <strong>min-heap</strong>, the parent node is less than or equal to its child nodes.</li></ul><p>This makes heaps an ideal choice for our problem, where we continuously update a set of numbers and compute the median.</p><p>By combining a max-heap and a min-heap, we can:</p><ul><li>Store the smaller half of the elements in the max-heap.</li><li>Store the larger half of the elements in the min-heap.</li><li>Maintain a balance between the two heaps in logarithmic time.</li></ul><p>Each element in the stream is processed in O(log k), where k is the number of elements processed so far. This includes adding the new element to the appropriate heap and, if necessary, redistributing elements between the heaps.</p><p>The total complexity of processing the entire stream of numbers is O(n log n), making the algorithm efficient even for large datasets.</p><h4><strong>Part 1: Solving the Problem in C++</strong></h4><p><strong>Performance Analysis</strong><br>This implementation uses two heaps: a max-heap for the smaller half of the elements and a min-heap for the larger half. The key steps of the algorithm are as follows:</p><ol><li><strong>Adding an Element to a Heap</strong>:<br>An element is added either to the max-heap or the min-heap. This takes O(log⁡ k), where k is the number of elements in the corresponding heap.</li><li><strong>Balancing the Heaps</strong>:<br>If the size difference between the heaps exceeds 1, elements are moved between the heaps. This also takes O(log⁡ k).</li><li><strong>Retrieving the Median</strong>:<br>The median can be retrieved in O(1), as it is located at the top of one of the heaps.</li></ol><p>Thus, processing a single element is done in O(log⁡ k), and the total complexity for a stream of n elements is O(n log⁡ n).</p><p><strong>Using Heaps in C++</strong><br>To efficiently compute the median at each step, two heaps are used:</p><ul><li><strong>Max-heap (left heap)</strong>: Stores the smaller half of the numbers.</li><li><strong>Min-heap (right heap)</strong>: Stores the larger half of the numbers.</li></ul><p>The median is computed as follows:</p><ul><li>If the max-heap contains more elements, the median is the top of the max-heap.</li><li>Otherwise, the median is the average of the top elements of the two heaps.</li></ul><p>Here’s the implementation in C++:</p><pre>int medianMaintenance( const std::vector&lt;int&gt; &amp; numbers )<br>{<br>    std::priority_queue&lt;int&gt; lowHeap; // Max-heap<br>    std::priority_queue&lt;int, std::vector&lt;int&gt;, std::greater&lt;int&gt;&gt; highHeap; // Min-heap<br>    int medianSum = 0;<br><br>    for ( int num : numbers )<br>    {<br>        if ( lowHeap.empty() || num &lt;= lowHeap.top() )<br>        {<br>            lowHeap.push( num );<br>        }<br>        else<br>        {<br>            highHeap.push( num );<br>        }<br><br>        if ( lowHeap.size() &gt; highHeap.size() + 1 )<br>        {<br>            highHeap.push( lowHeap.top() );<br>            lowHeap.pop();<br>        }<br>        else if ( highHeap.size() &gt; lowHeap.size() )<br>        {<br>            lowHeap.push( highHeap.top() );<br>            highHeap.pop();<br>        }<br><br>        int median = ( lowHeap.size() &gt;= highHeap.size() ) ? lowHeap.top() : highHeap.top();<br>        medianSum = ( medianSum + median ) % 10000;<br>    }<br><br>    return medianSum;<br>}<br><br>int main()<br>{<br>    std::ifstream inputFile( &quot;Median.txt&quot; );<br>    if ( !inputFile.is_open() )<br>    {<br>        std::cerr &lt;&lt; &quot;Error: Unable to open the file.&quot; &lt;&lt; std::endl;<br>        return EXIT_FAILURE;<br>    }<br><br>    std::vector&lt;int&gt; numbers;<br>    int number;<br>    while ( inputFile &gt;&gt; number )<br>    {<br>        numbers.push_back( number );<br>    }<br><br>    inputFile.close();<br><br>    int result = medianMaintenance( numbers );<br>    std::cout &lt;&lt; &quot;Sum of medians modulo 10000: &quot; &lt;&lt; result &lt;&lt; std::endl;<br><br>    return EXIT_SUCCESS;<br>}</pre><h4><strong>Part 2: Implementing a Heap in C</strong></h4><p><strong>Why Switch to C?</strong><br>Using C++ allows us to leverage convenient tools from the standard library, such as priority_queue. However, there are situations where low-level control over data structures and their behaviour is required. This can be beneficial in the following scenarios:</p><ol><li><strong>Limited Resources</strong>: In systems with constrained computational power or memory (e.g., embedded systems), using STL might be too resource-intensive.</li><li><strong>Learning</strong>: Implementing custom data structures helps deepen understanding of their design and principles.</li><li><strong>Optimization</strong>: Custom implementations can sometimes be more efficient for specific tasks by avoiding the overhead of generic standard library features.</li><li><strong>Compatibility</strong>: In projects that use pure C, STL from C++ is not an option, so a custom heap implementation is necessary.</li></ol><p>Now, we’ll move to implementing a heap in C to fully understand its inner workings.</p><p>While STL in C++ simplifies tasks significantly, let’s transition to C and build our own heap. For simplicity, we’ll implement a max-heap, which we’ll use similarly to the C++ solution.</p><p><strong>Analysis of Heap Implementation in C</strong></p><p>This implementation provides a flexible and efficient structure for working with heaps. Below is a detailed analysis of the key components</p><p><strong>Heap Structure</strong></p><pre>// Structure to represent a Heap<br>typedef struct<br>{<br>    int * data;<br>    int size;<br>    int capacity;<br>    bool isMinHeap;<br>} Heap;</pre><ul><li>Contains a dynamic array data that stores the elements of the heap.</li><li>The fields size and capacity manage the current number of elements and the maximum allowable size.</li><li>The flag isMinHeap indicates whether the heap is a min-heap or a max-heap.</li></ul><p><strong>Initialization</strong></p><pre>Heap * Heap_create( int capacity, bool isMinHeap )<br>{<br>    Heap * heap = ( Heap * )malloc( sizeof( Heap ) );<br>    heap-&gt;data = ( int * )malloc( ( capacity + 1 ) * sizeof( int ) );<br>    heap-&gt;size = 0;<br>    heap-&gt;capacity = capacity;<br>    heap-&gt;isMinHeap = isMinHeap;<br><br>    return heap;<br>}</pre><ul><li>The Heap_create function allocates memory for the structure and the array.</li><li>It allows the creation of either a min-heap or a max-heap.</li><li>The operation takes O(1) time, as the main effort is spent on memory allocation.</li></ul><p><strong>Key Heap Operations</strong></p><p><strong>heapifyUp (Sift Up):</strong></p><pre>void Heap_heapifyUp( Heap * heap, int index )<br>{<br>    while ( index &gt; 1 )<br>    {<br>        int parent = index / 2;<br>        if ( ( heap-&gt;isMinHeap &amp;&amp; heap-&gt;data[ index ] &lt; heap-&gt;data[ parent ] ) ||<br>            ( !heap-&gt;isMinHeap &amp;&amp; heap-&gt;data[ index ] &gt; heap-&gt;data[ parent ] ) )<br>        {<br>            swap( &amp;heap-&gt;data[ index ], &amp;heap-&gt;data[ parent ] );<br>            index = parent;<br>        }<br>        else<br>        {<br>            break;<br>        }<br>    }<br>}</pre><ul><li>Used when adding elements.</li><li>Compares the element with its parent node and moves it up if the heap property is violated.</li><li>Complexity: O(log⁡ n), where n is the number of elements in the heap.</li></ul><p><strong>heapifyDown (Sift Down):</strong></p><pre>void Heap_heapifyDown( Heap * heap, int index )<br>{<br>    while ( 2 * index &lt;= heap-&gt;size )<br>    {<br>        int child = 2 * index;<br>        if ( child + 1 &lt;= heap-&gt;size &amp;&amp;<br>            ( ( heap-&gt;isMinHeap &amp;&amp; heap-&gt;data[ child + 1 ] &lt; heap-&gt;data[ child ] ) ||<br>             ( !heap-&gt;isMinHeap &amp;&amp; heap-&gt;data[ child + 1 ] &gt; heap-&gt;data[ child ] ) ) )<br>        {<br>            child++;<br>        }<br>        if ( ( heap-&gt;isMinHeap &amp;&amp; heap-&gt;data[ index ] &gt; heap-&gt;data[ child ] ) ||<br>            ( !heap-&gt;isMinHeap &amp;&amp; heap-&gt;data[ index ] &lt; heap-&gt;data[ child ] ) )<br>        {<br>            swap( &amp;heap-&gt;data[ index ], &amp;heap-&gt;data[ child ] );<br>            index = child;<br>        }<br>        else<br>        {<br>            break;<br>        }<br>    }<br>}</pre><ul><li>Used when removing the root element.</li><li>Compares the element with its child nodes and moves it down if the heap property is violated.</li><li>Complexity: O(log⁡ n).</li></ul><p><strong>push (Add Element):</strong></p><pre>void Heap_push( Heap * heap, int value )<br>{<br>    if ( heap-&gt;size &gt;= heap-&gt;capacity )<br>    {<br>        fprintf( stderr, &quot;Heap overflow!\n&quot; );<br>        return;<br>    }<br><br>    heap-&gt;data[ ++heap-&gt;size ] = value;<br>    Heap_heapifyUp( heap, heap-&gt;size );<br>}</pre><ul><li>Adds an element to the end of the array and calls heapifyUp.</li><li>Checks for heap overflow.</li><li>Complexity: O(log ⁡n).</li></ul><p><strong>pop (Remove Root Element):</strong></p><pre>int Heap_pop( Heap * heap )<br>{<br>    if ( heap-&gt;size == 0 )<br>    {<br>        fprintf( stderr, &quot;Heap underflow!\n&quot; );<br>        return -1;<br>    }<br><br>    int root = heap-&gt;data[ 1 ];<br>    heap-&gt;data[ 1 ] = heap-&gt;data[ heap-&gt;size-- ];<br>    Heap_heapifyDown( heap, 1 );<br><br>    return root;<br>}</pre><ul><li>Removes the root element (minimum or maximum, depending on the heap type).</li><li>Moves the last element to the root and calls heapifyDown.</li><li>Checks for heap underflow.</li><li>Complexity: O(log n).</li></ul><p><strong>top (View Root Element):</strong></p><pre>int Heap_top( Heap * heap )<br>{<br>    if ( heap-&gt;size == 0 )<br>    {<br>        fprintf( stderr, &quot;Heap is empty!\n&quot; );<br>        return -1;<br>    }<br><br>    return heap-&gt;data[ 1 ];<br>}</pre><ul><li>Returns the root element without removing it.</li><li>Complexity: O(1).</li></ul><p><strong>Implementation of </strong><strong>medianMaintenance:</strong></p><pre>int medianMaintenance( const int * numbers, int size )<br>{<br>    Heap * lowHeap = Heap_create( 10001, false ); // Max-heap for the lower half<br>    Heap * highHeap = Heap_create( 10001, true ); // Min-heap for the upper half<br>    int medianSum = 0;<br><br>    for ( int i = 0; i &lt; size; i++ )<br>    {<br>        int num = numbers[ i ];<br><br>        if ( lowHeap-&gt;size == 0 || num &lt;= Heap_top( lowHeap ) )<br>        {<br>            Heap_push( lowHeap, num );<br>        }<br>        else<br>        {<br>            Heap_push( highHeap, num );<br>        }<br><br>        // Balance the heaps<br>        if ( lowHeap-&gt;size &gt; highHeap-&gt;size + 1 )<br>        {<br>            Heap_push( highHeap, Heap_pop( lowHeap ) );<br>        }<br>        else if ( highHeap-&gt;size &gt; lowHeap-&gt;size )<br>        {<br>            Heap_push( lowHeap, Heap_pop( highHeap ) );<br>        }<br><br>        // Calculate the current median<br>        int median = ( lowHeap-&gt;size &gt;= highHeap-&gt;size ) ? Heap_top( lowHeap ) : Heap_top( highHeap );<br>        medianSum = ( medianSum + median ) % 10000;<br>    }<br><br>    Heap_free( lowHeap );<br>    Heap_free( highHeap );<br><br>    return medianSum;<br>}</pre><p>The median maintenance function utilizes two heaps:</p><ul><li><strong>lowHeap (max-heap)</strong>: Stores the smaller half of the elements.</li><li><strong>highHeap (min-heap)</strong>: Stores the larger half of the elements.</li></ul><p><strong>Algorithm:</strong></p><ol><li><strong>Inserting an Element:</strong></li></ol><ul><li>A new element is added to either lowHeap or highHeap depending on its value relative to the current median.</li><li>Complexity: O(log n).</li></ul><p><strong>2. Balancing the Heaps:</strong></p><ul><li>If the size difference between the heaps exceeds 1, elements are moved to balance them.</li><li>Complexity: O(log⁡ n).</li></ul><p><strong>3. Calculating the Median:</strong></p><ul><li>If the heaps have equal sizes, the median is the root element of lowHeap (or highHeap).</li><li>Complexity: O(1).</li></ul><p><strong>4. Modular Arithmetic:</strong></p><ul><li>After computing the median, it is added to a running sum, with a modulo 10,000 operation applied to prevent overflow.</li></ul><p><strong>Use of Dynamic Memory</strong></p><p><strong>Pros:</strong></p><ul><li>Dynamic memory allocation allows the heap size to be defined at runtime.</li><li>Enables using a single structure for both types of heaps (min-heap and max-heap).</li></ul><p><strong>Cons:</strong></p><ul><li>Requires manual memory deallocation using freeHeap.</li></ul><p><strong>Advantages and Limitations</strong></p><p><strong>Advantages:</strong></p><ul><li><strong>Versatile Implementation</strong>: Supports both min-heap and max-heap operations.</li><li><strong>Efficiency</strong>: Operations for insertion, deletion, and accessing the root element are performed in O(log⁡ n).</li><li><strong>Median Maintenance</strong>: The use of two heaps enables quick median calculation.</li></ul><p><strong>Limitations:</strong></p><ul><li>The code does not dynamically increase the array size, which may lead to overflow if the capacity is exceeded.</li><li>Using two heaps requires additional memory.</li></ul><p>This heap implementation in C is well-suited for tasks requiring high performance and precise control over data structures. The medianMaintenance function showcases how heaps can be effectively used to solve real-time data stream processing problems.</p><h3>Conclusion</h3><p>Starting with C++ gives us a quick solution and an understanding of the algorithm’s behavior. Transitioning to C serves as a reminder of the importance of understanding fundamental data structures. Whether you’re honing your programming skills or preparing for an interview, this exercise bridges the gap between abstraction and implementation.</p><p>What do you think about moving from a high-level to a low-level solution? Let’s discuss in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27ff2938ecaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cracking Strongly Connected Components with Kosaraju’s Elegance]]></title>
            <link>https://medium.com/@alexey.medvecky/cracking-strongly-connected-components-with-kosarajus-elegance-0b9eca01d3bf?source=rss-80593edba6a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b9eca01d3bf</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[cpp-programming]]></category>
            <category><![CDATA[kosaraju-algorithm]]></category>
            <category><![CDATA[graph-algorithms]]></category>
            <category><![CDATA[algorithm-design]]></category>
            <dc:creator><![CDATA[Alexey Medvecky]]></dc:creator>
            <pubDate>Wed, 11 Dec 2024 11:00:54 GMT</pubDate>
            <atom:updated>2024-12-11T11:00:54.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*QBuNxJrmgR7vjqDF7LW-Ow.png" /></figure><p>One day, while working through graph problems, I came across an intriguing challenge: finding strongly connected components (SCC) in a large directed graph. At first glance, it seemed like just another puzzle for programmers, but the deeper I delved, the clearer its practical significance became. SCCs are not just a mathematical abstraction; they hold the key to understanding complex systems such as social networks, transportation systems, or even the human brain.</p><p>Let’s start by exploring what SCCs are, the real-world problems they solve, and how I approached their implementation.</p><h3>Problem Statement</h3><p>Imagine a directed graph. This could represent anything: roads connecting cities, interaction networks between people on a social platform, or links between web pages on the internet.</p><p><strong>What are strongly connected components (SCC)?</strong><br>Strongly connected components are groups of vertices in a graph where each vertex is reachable from any other vertex within the group (via directed edges). For example:</p><ul><li>In a social network, an SCC might represent a group of people who are all mutually connected (mutually following each other).</li><li>In a road network, it could be a set of cities with routes going both ways between them.</li><li>In software systems, SCCs help analyze dependencies between modules.</li></ul><p>The concept is simple, but calculating SCCs can be challenging, especially when the graph is massive.</p><h4>A Real-World Example: Social Networks</h4><p>Let’s imagine a large social network. Each user is a vertex, and a “follow” or “friendship” is a directed edge. For example:</p><ul><li>User A follows user B, but B might not follow A.</li><li>A group consisting of A, B, and C forms an SCC if they all follow each other mutually.</li></ul><p><strong>Why is this important?</strong><br> SCCs can be used for:</p><ul><li>Finding closed groups in social networks, such as circles of close friends.</li><li>Analyzing information flow: identifying who receives news only within their group.</li><li>Detecting isolated “content bubbles.”</li></ul><p><strong>How I Encountered This Problem</strong><br> One particular task required finding the sizes of the five largest SCCs in a graph with nearly 875,714 vertices and a massive number of edges. At first, it seemed daunting: how could such data be processed efficiently within reasonable time and memory limits?</p><h3>Solution</h3><h4>Kosaraju’s Algorithm</h4><p>After researching, I discovered an elegant approach: <strong>Kosaraju’s Algorithm</strong>. This is a classic method for finding SCCs in linear time O(V+E).</p><p>The algorithm is split into two passes over the graph:</p><ol><li><strong>First Pass (Topological Sorting):</strong><br> Perform a depth-first search (DFS) on the graph and record the order in which vertices finish processing.</li><li><strong>Second Pass:</strong><br> Reverse all edges in the graph, then perform DFS again in the order determined in the first step. This step isolates SCCs as independent groups.</li></ol><p>This idea struck me as almost magical: the first pass organizes the graph, and the second “breaks it apart” into its components.</p><h4>Starting Point: Code Structure</h4><p>To begin, I decided the best approach would be to create a <strong>Graph</strong> class that encapsulates all the methods needed for the algorithm:</p><ul><li>Adding edges to the graph and its reversed version.</li><li>Performing depth-first search (DFS) for the first and second passes.</li><li>A main method to find the SCCs.</li></ul><p>Here’s what it looks like:<br>Graph Class</p><pre>class Graph<br>{<br>    public:<br>        Graph( int V ) : V_( V ){};<br>        void addEdge( int v, int w );<br>        std::vector&lt;int&gt; findSCCs();<br><br>    private:<br>        int V_; // Number of vertices<br>        std::unordered_map&lt;int, std::vector&lt;int&gt;&gt; adj_; // Adjacency list for original graph<br>        std::unordered_map&lt;int, std::vector&lt;int&gt;&gt; adjRev_; // Adjacency list for reversed graph<br><br>        void DFS( int v, std::vector&lt;bool&gt;&amp; visited, std::stack&lt;int&gt;&amp; Stack );<br>        void DFSUtil( int v, std::vector&lt;bool&gt;&amp; visited, int&amp; size );<br>};</pre><p>Here, I used an unordered_map instead of a regular array to optimize memory usage. This is particularly useful for graphs with unordered vertices (e.g., when vertices are large identifiers).</p><h4>Algorithm: Step by Step</h4><ol><li><strong>Adding Edges</strong><br> For each line in the file containing the graph’s edges, I add them to both the main graph and its reversed version.</li></ol><pre>void Graph::addEdge( int v, int w )<br>{<br>    adj_[ v ].push_back( w );<br>    adjRev_[ w ].push_back( v ); // Reverse graph<br>}</pre><p><strong>2. Second Pass: Detect SCC</strong></p><p>In the second pass, we perform DFS again, but this time we process the vertices in the order given by the stack, and we work on the reversed graph. This allows us to identify the SCCs.</p><pre>void Graph::DFSUtil( int v, std::vector&lt;bool&gt; &amp; visited, int &amp; size )<br>{<br>    visited[ v ] = true;<br>    size++;<br>    for ( int i : adjRev_[ v ] )<br>    {<br>        if ( !visited[ i ] )<br>        {<br>            DFSUtil( i, visited, size );<br>        }<br>    }<br>}</pre><p><strong>3. Finding SCCs</strong></p><p>Now, we combine the two passes into a single method, findSCCs. Here:</p><ul><li>The first DFS fills the stack.</li><li>The second DFS processes vertices from the stack and identifies SCCs.</li></ul><pre>std::vector&lt;int&gt; Graph::findSCCs()<br>{<br>    std::stack&lt;int&gt; Stack;<br>    std::vector&lt;bool&gt; visited(V_, false);<br><br>    // First pass: fill vertices in stack according to their finish times<br>    for ( int i = 0; i &lt; V_; i++ )<br>    {<br>        if ( !visited[ i ] )<br>        {<br>            DFS( i, visited, Stack );<br>        }<br>    }<br><br>    // Second pass: process vertices in order defined by stack<br>    fill( visited.begin(), visited.end(), false );<br>    std::vector&lt;int&gt; sccSizes;<br><br>    while ( !Stack.empty() )<br>    {<br>        int v = Stack.top();<br>        Stack.pop();<br><br>        if ( !visited[ v ] )<br>        {<br>            int size = 0;<br>            DFSUtil( v, visited, size );<br>            sccSizes.push_back( size );<br>        }<br>    }<br><br>    sort( sccSizes.rbegin(), sccSizes.rend() ); // Sort in descending order<br><br>    return sccSizes;<br>}</pre><p><strong>Final Result</strong></p><p>After adding all the edges and calling the findSCCs method, the program returns the sizes of the SCCs, sorted in descending order. Here’s an example of the output for a given graph:</p><pre>int main ()<br>{<br>    std::ifstream infile( &quot;scc.txt&quot; );<br>    int u, v;<br>    std::vector&lt;std::pair&lt;int, int&gt;&gt; edges;<br>    int maxNode = 0;<br><br>    // Reading edges from file<br>    while ( infile &gt;&gt; u &gt;&gt; v )<br>    {<br>        edges.push_back( {u, v} );<br>        maxNode = std::max( maxNode, std::max(u, v) );<br>    }<br><br>    // Initialize graph with the maximum node value<br>    Graph g( maxNode + 1 );<br>    for ( auto edge : edges )<br>    {<br>        g.addEdge( edge.first, edge.second );<br>    }<br><br>    // Find SCC sizes<br>    std::vector&lt;int&gt; sccSizes = g.findSCCs();<br><br>    // Output the five largest SCC sizes<br>    std::cout &lt;&lt; &quot;Result: &quot; &lt;&lt; std::endl;<br>    for ( int i = 0; i &lt; std::min( 5, ( int )sccSizes.size() ); i++ )<br>    {<br>        std::cout &lt;&lt; sccSizes[ i ] &lt;&lt; std::endl;<br>    }<br><br>    return EXIT_SUCCESS;<br>}</pre><p>Output example:</p><pre>Result: <br>434821<br>968<br>459<br>313<br>211</pre><h3>Conclusion</h3><p>After tackling the problem, implementing Kosaraju’s algorithm, and observing the results, one thought kept recurring: how elegantly this algorithm leverages the fundamental concepts of graph theory. Essentially, it stands on the shoulders of two foundational ideas:</p><ol><li><strong>Depth-First Search (DFS):</strong><br> DFS forms the backbone of both stages of the algorithm. The first pass uses it to determine the finishing order of vertices, while the second pass employs it to identify strongly connected components. This highlights the versatility and power of DFS as a tool.</li><li><strong>Topological Sorting:</strong><br> The first stage of Kosaraju’s algorithm effectively builds a topological sorting of the graph. This order enables the correct processing of vertices in the second pass, uncovering their connections in the reversed graph.</li></ol><p>These fundamental concepts, which might seem purely academic when studying graph theory, gain tremendous practical value in Kosaraju’s algorithm. Their effective use allows the algorithm to solve the problem in linear time.</p><h4>Algorithm Complexity Analysis</h4><p>Kosaraju’s algorithm operates in <strong>O(V+E)</strong>, where VV is the number of vertices and EE is the number of edges in the graph. Here’s why:</p><ol><li><strong>First DFS Pass (Topological Sorting):</strong><br> We traverse each vertex and each edge exactly once. This takes O(V+E).</li><li><strong>Reversing the Graph:</strong><br> Reversing the graph requires iterating over all E edges, which takes O(E).</li><li><strong>Second DFS Pass (Finding SCCs):</strong><br> In the second pass, we again traverse each vertex and edge exactly once. This also takes O(V+E).</li></ol><p>In total, the algorithm’s complexity remains linear with respect to the number of vertices and edges, making it highly efficient for analyzing large graphs.</p><h4>Final Thoughts</h4><p>Kosaraju’s algorithm is a prime example of how simple ideas can combine to form a powerful solution. Its linear complexity makes it an ideal choice for large graphs, and its reliance on fundamental concepts like DFS and topological sorting offers deeper insights into graph theory.</p><p>If you ever face the challenge of finding SCCs, give this algorithm a try. It’s not only efficient but also elegant in its construction. And if you have any thoughts or questions, feel free to share them in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b9eca01d3bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to develop the RSelect algorithm for finding the ith order statistic in C++]]></title>
            <link>https://medium.com/@alexey.medvecky/how-to-develop-the-rselect-algorithm-for-finding-the-ith-order-statistic-in-c-af714aeec5d0?source=rss-80593edba6a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/af714aeec5d0</guid>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[efficient-algorithm]]></category>
            <category><![CDATA[rselect-algorithm]]></category>
            <category><![CDATA[order-statistics]]></category>
            <dc:creator><![CDATA[Alexey Medvecky]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 10:13:02 GMT</pubDate>
            <atom:updated>2024-11-12T10:13:02.034Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K95qcuVuPocavAjkj2VBtA.png" /></figure><p>The memories of that interview still still evoke a slight feeling of vexation. It was yet another challenge: midway through the interview, after a few basic questions, I was presented with a problem — to find the ith smallest element in an unsorted array. “What could be simpler?” I initially thought. Like many in my position, I began with what I knew, suggesting the trivial approach of sorting the array and then returning the desired element. The response was cold and sharp: “Is there a faster way?”</p><p>This question immediately threw me off balance. I began to feverishly contemplate different approaches, recalling how I was once similarly asked about finding the nearest points in an array. Back then, just like now, I didn’t grasp the full depth of the approach and the potential of algorithms. That experience taught me that superficial knowledge of standard methods rarely helps solve an optimization problem in an interview setting.</p><p>Feeling embarrassed and sensing that I was missing something important, I started to think: perhaps there’s another approach we can use here? A more optimal, more clever method that avoids full sorting. And indeed — it turns out that to find the ith smallest element, there exists an efficient algorithm called RSelect, which solves the problem with lower complexity.</p><p>This is exactly what we will explore in this article: I will share the fundamentals and implementation of the RSelect algorithm in C++, which helps solve this problem optimally.</p><h3>Formal Problem Statement</h3><p>The problem of finding the ith order statistic (or the ith smallest element) is as follows: Given an unsorted array A of n numbers, we need to find an element A[i] such that exactly i−1 elements in the array are less than or equal to this element.</p><p>Formally, for an array A indexed from 0 to n−1, we are looking for an element A[k] such that:</p><ul><li>Exactly i elements in A are less than or equal to A[k], and</li><li>n−i elements are greater than or equal to A[k].</li></ul><p>For example, if i=1, the problem reduces to finding the minimum element of the array. If i=n, we need to find the maximum element, and if i=n/2 — the median of the array (for odd n or one of the central elements for even n).</p><h4>Applications of the RSelect Algorithm</h4><p>The RSelect algorithm is not just a solution for theoretical interview problems. It has real-world applications where time optimization is critically important:</p><ol><li><strong>Finding Medians and Quantiles</strong>: The RSelect algorithm allows for efficient computation of the median and any quantile values in large datasets. Quantiles play a significant role in statistics, where they are used to assess data distribution, determine classification thresholds, and in tasks related to data analysis and machine learning.</li><li><strong>Big Data Analysis</strong>: When working with large data arrays — for example, in databases or data warehouses — it’s often necessary to find specific order statistics without sorting the entire array. RSelect can be applied for selective analysis, especially when you need to quickly identify key data points or anomalies.</li><li><strong>Computer Graphics and Image Processing</strong>: Tasks like image filtering may require finding the median in sliding windows. Here, RSelect enables finding the median color level in a selected area of an image. This is useful for noise reduction algorithms such as median filtering.</li><li><strong>Financial Analysis</strong>: When dealing with time series, market prices, or interest rates, RSelect can help quickly find threshold values, such as the 10th or 90th percentile, which aids in risk assessment or identifying extreme values.</li><li><strong>Optimization in Array Tasks</strong>: In tasks related to ranking and data selection — such as finding the “top N” values — the RSelect algorithm helps avoid full sorting by focusing only on a portion of the array.</li></ol><p>These examples demonstrate that the RSelect algorithm goes beyond standard interview problems and finds applications in real-world scenarios where efficiency is required. In this article, we will delve into its implementation and explore how it works, so it’s always at hand when you need not just to find an element but to find it as quickly as possible.</p><p>At the time when I was asked to find the ith smallest element, the only thing that came to mind was, of course, the naive method — the most obvious and simplest to implement. But, as it turned out, not the most optimal.</p><h3>Solution</h3><h4><strong>Naive Method: Sorting the Array</strong></h4><p>First, I proposed what was obvious: sort the array first, and then simply select the element at index i. At first glance, this seems like a quite logical solution. Here’s how this approach would look in code:</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>#include &lt;algorithm&gt; <br><br>int naiveIthOrderStatistic(std::vector&lt;int&gt;&amp; arr, int i) <br>{<br>    std::sort(arr.begin(), arr.end()); <br>    return arr[i];<br>}</pre><p>This method performs sorting of the array, which typically has a complexity of O(n log⁡ n). After that, we can simply take the element at index i. Everything looks simple, logical, and seems to work — isn’t this the right solution?</p><p><strong>Limitations of the Naive Approach</strong></p><p>As soon as I presented my solution, the interviewer asked me, “Can we do this faster?” This question opened my eyes to the fact that perhaps I didn’t fully understand the problem. The naive method turns out to be far from optimal, especially for large arrays. Here are the main disadvantages of this approach:</p><ol><li><strong>Unnecessary Full Sorting</strong>: Sorting the entire array requires O(n log ⁡n) operations, but for the task of finding the ith element, this is excessive. We don’t need to know the order of all elements since we’re interested in only one.</li><li><strong>Inefficiency for Large Data</strong>: If the array contains millions of elements, sorting the whole array just to find one element is a waste of time and resources.</li><li><strong>Vulnerability to Data Changes</strong>: If the data array is dynamically updated — for example, new elements are added — you have to recalculate and resort the array each time, making this method even more resource-intensive.</li></ol><p>Then I began to realize that even if the naive method solves the problem, it is inefficient. In interviews and real-world tasks, such inefficiency can be a deciding factor.</p><p><strong>Realizing the Need for an Optimal Algorithm</strong></p><p>After discussing the naive approach, the interviewer steered me to the next question: “How can we find the element with less complexity than O(n log ⁡n)?” This question prompted me to think in a direction where we might not need to sort the entire array. This is where the story of the RSelect algorithm begins, which does exactly what we need — it finds the required element with lower complexity.</p><p>The RSelect algorithm offers the possibility to optimize the search for the ith element without sorting the whole array. Now that I see this algorithm as the answer to the questions that came up during my interview, let’s examine it in more detail and see how it solves this problem faster than the naive method.</p><h4>Optimal method</h4><p><strong>Optimization Through Quick Sort and Pivot Selection</strong></p><p>When we are looking for faster methods to find the ith element, a logical step is to study quick sort — one of the most efficient algorithms for array sorting. Quick sort is based on the idea of partitioning an array into two parts relative to a chosen element — the pivot. The approach to selecting this pivot plays a key role in the algorithm’s performance.</p><p><strong>Quick Sort: Fundamental Principles</strong></p><p>The quick sort algorithm operates as follows:</p><ol><li><strong>Choosing the Pivot</strong>: An element is selected around which the partitioning will be built.</li><li><strong>Partitioning the Array</strong>: The array is divided into elements less than the pivot and elements greater than the pivot.</li><li><strong>Recursive Sorting</strong>: The process is repeated recursively for each part until the array is fully sorted.</li></ol><p>For complete sorting of an array, quick sort performs with an average complexity of O(n log⁡ n), making it one of the fastest sorting algorithms for practical use.</p><p><strong>The Importance of Choosing the Pivot Element</strong></p><p>The selection of the pivot element determines how balanced the partitioning of the array will be. An ideal choice splits the array in half, which helps reduce the number of recursive calls. However, if the choice is poor, one part of the array may end up much larger than the other, leading to unbalanced partitioning and increasing the complexity to the worst-case O(n²).</p><p>There are several approaches to selecting the pivot element, and each affects the algorithm’s performance differently:</p><ol><li><strong>First Element</strong>: Using the first element as the pivot is the simplest approach, but with sorted or nearly sorted data, this leads to unbalanced partitioning, increasing the complexity to O(n²).</li><li><strong>Last Element</strong>: Similar to choosing the first element, the last element doesn’t always provide balanced partitioning and can result in the same worst-case scenario on certain types of data.</li><li><strong>Middle Element</strong>: Selecting the middle element of the array can work better for some inputs but does not guarantee balanced partitioning in general.</li><li><strong>Random Element</strong>: Randomly selecting the pivot element by generating a random index helps improve the algorithm’s average performance. Since the element is chosen at random, the probability that the partition will be highly unbalanced decreases. This approach is precisely what is used in the RSelect algorithm for finding the ith element.</li><li><strong>Median-of-Three</strong>: In this method, the pivot element is chosen as the median of three elements (usually the first, last, and middle). This can improve performance on some types of data and avoid the worst-case scenario.</li></ol><p><strong>Why Random Pivot Selection Works for RSelect</strong></p><p>The RSelect algorithm uses the partitioning principle from quicksort but with an important difference: it does not sort the entire array. The goal is to find the ith order statistic (the element that is the ith smallest), and RSelect limits sorting to only the part of the array that may contain the desired element. Randomly choosing the pivot element makes the algorithm flexible and reduces the likelihood of bad cases, allowing it to work on average in O(n) time, which is significantly faster than full sorting.</p><p><strong>Comparison of RSelect and Quicksort</strong></p><p>When we compare the approaches in the context of finding the ith element, we can note the following differences:</p><ul><li><strong>Quicksort</strong> performs a complete ordering of the array, which requires O(n log n) operations, even if we are interested in only one element. It is ideally suited for cases where the order of all elements is important.</li><li><strong>RSelect</strong> uses only partial partitioning of the array, limiting the number of recursive calls, which reduces the average complexity to O(n). This is especially beneficial for tasks like finding the median or the ith order statistic when there is no need to sort the entire array.</li></ul><p>Now that we understand how the choice of the pivot element affects performance, let’s examine RSelect in more detail and understand how it finds the ith element by partitioning the array around a randomly selected element.</p><p>The code implements the RSelect algorithm designed to find the ith order statistic in an unsorted array — that is, the element that is the ith smallest among all elements in the array. This implementation uses recursion and the partitioning method, which allows us to find the required element without the need to sort the entire array.</p><p>Let’s break down the code and the key components of the RSelect algorithm to understand how it achieves such optimal efficiency.</p><p><strong>1. The </strong><strong>partition Function: Partitioning the Array Around the Pivot Element</strong></p><p>The partition function performs the partitioning of the array around a chosen pivot element. It moves all elements less than the pivot to the left part of the array and elements greater than the pivot to the right. In the end, the function returns the final position of the pivot element after partitioning, which helps us understand its position relative to other elements.</p><pre>int partition(std::vector&lt;int&gt;&amp; arr, int left, int right, int pivotIndex) {<br>    int pivotValue = arr[pivotIndex];<br>    std::swap(arr[pivotIndex], arr[right]); <br>    int storeIndex = left;<br><br>    for (int i = left; i &lt; right; i++) {<br>        if (arr[i] &lt; pivotValue) {<br>            std::swap(arr[i], arr[storeIndex]);<br>            storeIndex++;<br>        }<br>    }<br><br>    std::swap(arr[storeIndex], arr[right]); <br>    return storeIndex;<br>}</pre><p><strong>Explanation of the code:</strong></p><ul><li>pivotValue holds the value of the pivot element selected for the current partitioning.</li><li>The for loop iterates over the elements of the array from left to right - 1. If an element is less than the pivot value, it is moved to the beginning of the array (where storeIndex is located), after which storeIndex is incremented.</li><li>At the end, the pivot element is placed at the position storeIndex, ensuring that elements to the left of it are smaller and elements to the right are larger.</li><li>This method is similar to the partitioning in quicksort and operates in O(n) time because each element is processed exactly once.</li></ul><p><strong>2. The </strong><strong>RSelect Function: Recursive Search for the ith Order Statistic</strong></p><p>The RSelect function recursively selects a random pivot element, partitions the array, and finds the element that corresponds to the order number iii. This is an optimal method that allows us to find the desired element in average O(n) time thanks to the random selection of the pivot element.</p><pre>int RSelect(std::vector&lt;int&gt;&amp; arr, int left, int right, int i) {<br>    if (left == right) {<br>        return arr[left]; // Base case: only one element<br>    }<br><br>    // Choose a random pivot<br>    int pivotIndex = left + rand() % (right - left + 1);<br><br>    // Partition the array and get the pivot&#39;s position<br>    pivotIndex = partition(arr, left, right, pivotIndex);<br><br>    // Determine if we are at the i-th position<br>    int k = pivotIndex - left + 1; // Position of the pivot in the current subarray<br><br>    if (i == k) {<br>        return arr[pivotIndex]; // Found the i-th order statistic<br>    } else if (i &lt; k) {<br>        return RSelect(arr, left, pivotIndex - 1, i); // Search in the left part<br>    } else {<br>        return RSelect(arr, pivotIndex + 1, right, i - k); // Search in the right part<br>    }<br>}</pre><p><strong>Explanation of the code:</strong></p><ul><li><strong>Base Case</strong>: If left and right are the same, it means the subarray consists of a single element, and this element is the ith order statistic.</li><li><strong>Random Pivot Selection</strong>: For optimization, we randomly select an index between left and right each time, reducing the probability of the worst-case O(n²).</li><li><strong>Partitioning and Position Determination</strong>: The array is divided into two parts using the partition function. pivotIndex indicates the position of the pivot element.</li><li><strong>Checking the Position </strong><strong>k</strong>: After partitioning, we check where the ith element is relative to the pivot&#39;s position:</li><li>If i == k, then we have found the desired element.</li><li>If i &lt; k, we recursively search for the ith element in the left part of the array.</li><li>If i &gt; k, we search in the right part but with a new value of i - k (adjusting the index relative to the left boundary of the right subarray).</li></ul><p><strong>3. The </strong><strong>main Function: Reading Data and Calling </strong><strong>RSelect</strong></p><p>The main function is responsible for initializing and reading the array from the file input.txt. It reads the size of the array and the value of iii—the order statistic we need to find.</p><pre>int main() {<br>    std::ifstream inputFile(&quot;input.txt&quot;);<br>    if (!inputFile) {<br>        std::cerr &lt;&lt; &quot;Failed to open file input.txt&quot; &lt;&lt; std::endl;<br>        return 1;<br>    }<br><br>    int n, i;<br>    inputFile &gt;&gt; n &gt;&gt; i;<br><br>    std::vector&lt;int&gt; arr(n);<br>    for (int j = 0; j &lt; n; j++) {<br>        inputFile &gt;&gt; arr[j];<br>    }<br><br>    inputFile.close();<br><br>    // Initialize random number generator<br>    std::srand(std::time(0));<br><br>    // Find the i-th order statistic<br>    int result = RSelect(arr, 0, n - 1, i);<br><br>    std::cout &lt;&lt; &quot;The i-th order statistic: &quot; &lt;&lt; result &lt;&lt; std::endl;<br><br>    return 0;<br>}</pre><p><strong>Explanation of the Code:</strong></p><ul><li><strong>File Reading</strong>: ifstream opens the file input.txt and reads the data. At the beginning of the file, an integer n is expected, indicating the size of the array, and an integer i—the order number of the desired element.</li><li><strong>Initializing the Random Number Generator</strong>: std::srand(std::time(0)) sets the seed for the random number generator, which is necessary for the random selection of the pivot element.</li><li><strong>Calling </strong><strong>RSelect</strong>: The function launches the recursive algorithm to find the ith order statistic.</li></ul><h3><strong>Conclusions and Performance Analysis</strong></h3><p>When I figured out how RSelect works, everything fell into place, although, of course, it was too late for that interview. I realized the full potential of this algorithm only after I was &quot;let go&quot; in the subsequent stages. Back home, delving into the code, I finally understood how the linear complexity O(n) allows RSelect to save time when we&#39;re interested in just one element rather than the order of all values. This is precisely what makes it so effective for selection tasks—finding the median, quantiles, or any ith element in an array.</p><p>It seems paradoxical that the worst case for RSelect is also possible, and it is O(n²), which so closely resembles bubble sort. But the random choice of the pivot element minimizes the risk of &quot;unfortunate&quot; partitions, making this case extremely unlikely. I realized that, essentially, the algorithm &quot;guesses&quot; the needed range, confidently narrowing the search area each time—and it works.</p><p>After understanding all these details, I felt a certain satisfaction: even though I lacked an understanding of RSelect&#39;s depth during the interview, I finally saw its elegance. This algorithm turned out to be exactly what was required for the task, and now it will always be in my arsenal for future challenges. Yes, I didn&#39;t manage it then, but who knows, maybe this experience will be decisive next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af714aeec5d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding the Two Closest Points: An Efficient Solution in C++]]></title>
            <link>https://medium.com/@alexey.medvecky/finding-the-two-closest-points-an-efficient-solution-in-c-832b20010246?source=rss-80593edba6a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/832b20010246</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[k-closest-points]]></category>
            <category><![CDATA[divide-and-conquer]]></category>
            <category><![CDATA[cpp-programming]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Alexey Medvecky]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 08:05:51 GMT</pubDate>
            <atom:updated>2024-11-05T08:05:51.252Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVt5sd3tfU7pcqMt2Mqqxw.png" /></figure><h3>Introduction</h3><p>The first time I encountered the problem of finding the two closest points was a few years ago during an interview. I was confident in my knowledge, but when the interviewer posed this question, I didn’t realize that what seemed like a straightforward task had more depth. Back then, I wasn’t well-versed in algorithms or data structures and thought the naive method was the only possible solution.</p><p>Since then, I decided to understand this topic thoroughly, and now I want to share what I’ve learned so that you can be well-prepared for such problems and understand their practical value.</p><h4>Problem Statement</h4><p>Given a collection of points on a plane, represented by their coordinates (x, y), the goal is to find two points such that the distance between them is minimized. There are different approaches to solving this problem, and we’ll explore both a simple and an advanced algorithm.</p><h4>Practical Applications</h4><p>The problem of finding the two closest points goes beyond academic curiosity. This algorithm finds applications in various fields, including:</p><ul><li><strong>Computer Vision</strong>: For object detection, image analysis, and measuring distances between elements within a scene.</li><li><strong>Geolocation Services</strong>: The algorithm helps identify the two nearest objects on a map, whether buildings, nearby restaurants, or important points of interest.</li><li><strong>Data Clustering</strong>: In machine learning, finding the closest points is useful for creating clusters, especially in clustering algorithms like k-means.</li><li><strong>Physical Process Simulation</strong>: Calculating minimal distances between molecules or particles aids in modeling interactions and building physical simulations.</li><li><strong>Computer Games and Graphics</strong>: Detecting collisions between objects and performing real-time calculations require algorithms that can quickly find the nearest points.</li></ul><p>Now that we understand the importance of this problem, let’s move to its formal definition.</p><h3>Solution</h3><h4>Naive Method: Where It All Started</h4><p>During that interview, my initial thought was to use a straightforward solution: iterate through all possible pairs of points and find the one with the minimum distance. I was confident this would be enough, as the problem seemed trivial at first glance.</p><p><strong>Attempting to Impress the Interviewer</strong></p><p>Beyond the basic algorithm, I decided to emphasize other aspects of my solution. I organized data reading from a file into a custom implementation of a linked list, thinking it would showcase my data structure knowledge and make a strong impression. I believed that this approach demonstrated my enthusiasm and thoroughness in preparing for the task.</p><p>However, when I finished explaining my algorithm, the interviewer paused and asked a simple yet crucial question: “What if you have 100,000 points?” At that moment, I realized there was something I didn’t understand, but I couldn’t grasp what was missing from my solution.</p><p><strong>Implementing the Naive Method</strong></p><p>The algorithm I used at the time calculated distances between all possible pairs of points, with a time complexity of O(n²) — acceptable for small datasets but unsuitable for large volumes. Here’s what the implementation looked like:</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>#include &lt;cmath&gt;<br>#include &lt;limits&gt;<br><br>struct Point {<br>    double x, y;<br>};<br><br>double distance(const Point&amp; p1, const Point&amp; p2) {<br>    return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));<br>}<br><br>std::pair&lt;Point, Point&gt; findClosestPairBruteForce(const std::vector&lt;Point&gt;&amp; points) {<br>    double minDist = std::numeric_limits&lt;double&gt;::infinity();<br>    std::pair&lt;Point, Point&gt; closestPair;<br><br>    for (size_t i = 0; i &lt; points.size(); ++i) {<br>        for (size_t j = i + 1; j &lt; points.size(); ++j) {<br>            double dist = distance(points[i], points[j]);<br>            if (dist &lt; minDist) {<br>                minDist = dist;<br>                closestPair = {points[i], points[j]};<br>            }<br>        }<br>    }<br><br>    return closestPair;<br>}</pre><p><strong>Explanation of the Naive Method</strong></p><p>This algorithm iterates over all possible pairs of points, calculating the distance between each pair and recording the minimum distance and corresponding point pair. At the time, I was confident that my attention to detail, including file reading and using a custom data structure, would make a good impression. However, when I heard the question about performance with large datasets, I realized my efforts were directed in the wrong direction.</p><h4>Optimal Approach: Sorting as the Key to Success</h4><p>After that interview, I started studying how to improve the performance of the closest point-finding solution. I discovered that sorting points is a crucial part of the optimal solution, known as the “divide and conquer” method.</p><p><strong>Understanding the Role of Sorting</strong></p><p>In my research, I learned that sorting points by one coordinate is the foundation for optimizing the algorithm. In the optimal solution, points are first sorted by their x-coordinate. This allows breaking the task into two smaller subproblems and makes it easier to search for the closest points.</p><p><strong>Why Sorting Matters</strong></p><p>Sorting enables the “divide and conquer” strategy, where the set of points is divided into two halves. For each half, the closest points are recursively found, followed by a check to see if the closest points are on the boundary between these halves. Without sorting, checking points on the boundary would be inefficient, potentially requiring a full comparison and returning us to quadratic complexity, O(n²).</p><p><strong>How It Works</strong></p><ol><li><strong>Sorting Points by x-coordinate</strong>: Initially, all points are sorted by their x-coordinate, which takes O(n log n) time and is one of the algorithm’s most costly operations.</li><li><strong>Dividing and Recursively Calling</strong>: The array of points is divided into two halves, and the algorithm recursively finds the closest point pairs in each half.</li><li><strong>Merging Results</strong>: Points within a strip of width d (where d is the minimum distance found in both halves) are checked. There might be a new pair of points with a minimum distance in this strip, so they’re checked separately.</li></ol><p>Sorting helps the algorithm reduce the number of points to check in this strip. Without it, checking all possible pairs would revert to quadratic complexity.</p><p><strong>Optimal Approach: Using the “Divide and Conquer” Method</strong></p><p>When I delved into algorithms for finding the two closest points, I realized the key to improving efficiency wasn’t just iterating through all point pairs but applying a “divide and conquer” approach. Here’s how sorting and recursion play a central role in this method.</p><p><strong>Code Walkthrough</strong></p><p>Let’s go through an implementation that shows how the algorithm works.</p><pre>struct Point {<br>    double x, y;<br>};</pre><p>We start by declaring a Point structure to store x, y coordinates, allowing us to represent each point as an object.</p><p><strong>Distance Calculation Function</strong></p><pre>double distance(const Point&amp; p1, const Point&amp; p2) {<br>    return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));<br>}</pre><p>This function calculates the Euclidean distance between two points, which is the basis for finding the closest points.</p><p><strong>Recursive Algorithm</strong></p><p>The “divide and conquer” algorithm splits the set of points into two halves, recursively finding the closest pairs in each half and then checking if there are closer points in a strip that divides these halves.</p><pre>std::pair&lt;Point, Point&gt; closestPairRecursive(std::vector&lt;Point&gt;&amp; pointsX, std::vector&lt;Point&gt;&amp; pointsY, int left, int right) {<br>    if (right - left &lt;= 3) {<br>        return bruteForce(pointsX, left, right);<br>    }<br><br>    int mid = left + (right - left) / 2;<br>    Point midPoint = pointsX[mid];<br><br>    std::vector&lt;Point&gt; leftY, rightY;<br>    for (const Point&amp; p : pointsY) {<br>        if (p.x &lt;= midPoint.x)<br>            leftY.push_back(p);<br>        else<br>            rightY.push_back(p);<br>    }<br><br>    std::pair&lt;Point, Point&gt; leftPair = closestPairRecursive(pointsX, leftY, left, mid);<br>    std::pair&lt;Point, Point&gt; rightPair = closestPairRecursive(pointsX, rightY, mid + 1, right);<br><br>    double delta = std::min(distance(leftPair.first, leftPair.second), distance(rightPair.first, rightPair.second));<br>    std::pair&lt;Point, Point&gt; minPair = (distance(leftPair.first, leftPair.second) &lt; distance(rightPair.first, rightPair.second)) ? leftPair : rightPair;<br><br>    std::vector&lt;Point&gt; strip;<br>    for (const Point&amp; p : pointsY) {<br>        if (fabs(p.x - midPoint.x) &lt; delta)<br>            strip.push_back(p);<br>    }<br><br>    std::pair&lt;Point, Point&gt; splitPair = closestSplitPair(strip, delta);<br>    if (distance(splitPair.first, splitPair.second) &lt; delta) {<br>        minPair = splitPair;<br>    }<br><br>    return minPair;<br>}</pre><p>At the beginning of the recursive function, we check if the current set contains three or fewer points. If so, simple brute-force is used to find the closest pair, providing the base case for recursion.</p><p><strong>Strip Checking</strong></p><p>After finding the closest pairs for each half, we need to check the points in a narrow strip of width d (where d is the minimum distance between points in each half).</p><pre>std::pair&lt;Point, Point&gt; closestSplitPair(std::vector&lt;Point&gt;&amp; strip, double delta) {<br>    double minDist = delta;<br>    std::pair&lt;Point, Point&gt; minPair = {strip[0], strip[1]};<br><br>    int n = strip.size();<br>    for (int i = 0; i &lt; n; ++i) {<br>        for (int j = i + 1; j &lt; n &amp;&amp; (strip[j].y - strip[i].y) &lt; minDist; ++j) {<br>            double d = distance(strip[i], strip[j]);<br>            if (d &lt; minDist) {<br>                minDist = d;<br>                minPair = {strip[i], strip[j]};<br>            }<br>        }<br>    }<br>    return minPair;<br>}</pre><p>In this function, points in the strip, sorted by their y-coordinate, are checked. Notably, only points within a d distance in the y-direction need to be checked for each point.</p><p><strong>Reading Data from a File</strong></p><pre>std::vector&lt;Point&gt; readPointsFromFile(const std::string&amp; filename) {<br>    std::vector&lt;Point&gt; points;<br>    std::ifstream infile(filename);<br>    double x, y;<br>    while (infile &gt;&gt; x &gt;&gt; y) {<br>        points.push_back({x, y});<br>    }<br>    return points;<br>}</pre><p>This function loads point data from a file, which is helpful for handling large data volumes efficiently.</p><p><strong>Main Function</strong></p><pre>int main() {<br>    std::string filename = &quot;points.txt&quot;;<br>    std::vector&lt;Point&gt; points = readPointsFromFile(filename);<br><br>    if (points.size() &lt; 2) {<br>        std::cerr &lt;&lt; &quot;Not enough points to find the closest pair.&quot; &lt;&lt; std::endl;<br>        return 1;<br>    }<br><br>    auto closest = closestPair(points);<br>    std::cout &lt;&lt; &quot;The closest pair of points is: (&quot; &lt;&lt; closest.first.x &lt;&lt; &quot;, &quot; &lt;&lt; closest.first.y &lt;&lt; &quot;) and (&quot;<br>              &lt;&lt; closest.second.x &lt;&lt; &quot;, &quot; &lt;&lt; closest.second.y &lt;&lt; &quot;)&quot; &lt;&lt; std::endl;<br>    std::cout &lt;&lt; &quot;The distance between them is: &quot; &lt;&lt; distance(closest.first, closest.second) &lt;&lt; std::endl;<br><br>    return 0;<br>}</pre><p>In this function, we load points from a file, call the main function to find the closest points, and output the result. If there aren’t enough points to find a pair, the program reports this.</p><p>Full Solution Listing</p><pre>#include &lt;iostream&gt;<br>#include &lt;fstream&gt;<br>#include &lt;vector&gt;<br>#include &lt;cmath&gt;<br>#include &lt;algorithm&gt;<br>#include &lt;limits&gt;<br><br>struct Point {<br>    double x, y;<br>};<br><br>// Function to compute the Euclidean distance between two points<br>double distance(const Point&amp; p1, const Point&amp; p2) {<br>    return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));<br>}<br><br>// Comparators for sorting by x and y coordinates<br>bool compareX(const Point&amp; p1, const Point&amp; p2) { return p1.x &lt; p2.x; }<br>bool compareY(const Point&amp; p1, const Point&amp; p2) { return p1.y &lt; p2.y; }<br><br>// Function to find the closest pair of points in a small subset using brute force<br>std::pair&lt;Point, Point&gt; bruteForce(std::vector&lt;Point&gt;&amp; points, int left, int right) {<br>    double minDist = std::numeric_limits&lt;double&gt;::max();<br>    std::pair&lt;Point, Point&gt; minPair;<br><br>    for (int i = left; i &lt; right; ++i) {<br>        for (int j = i + 1; j &lt;= right; ++j) {<br>            double d = distance(points[i], points[j]);<br>            if (d &lt; minDist) {<br>                minDist = d;<br>                minPair = {points[i], points[j]};<br>            }<br>        }<br>    }<br>    return minPair;<br>}<br><br>// Function to find the closest pair of points within a strip of width 2*delta<br>std::pair&lt;Point, Point&gt; closestSplitPair(std::vector&lt;Point&gt;&amp; strip, double delta) {<br>    double minDist = delta;<br>    std::pair&lt;Point, Point&gt; minPair = {strip[0], strip[1]};<br><br>    int n = strip.size();<br>    for (int i = 0; i &lt; n; ++i) {<br>        for (int j = i + 1; j &lt; n &amp;&amp; (strip[j].y - strip[i].y) &lt; minDist; ++j) {<br>            double d = distance(strip[i], strip[j]);<br>            if (d &lt; minDist) {<br>                minDist = d;<br>                minPair = {strip[i], strip[j]};<br>            }<br>        }<br>    }<br>    return minPair;<br>}<br><br>// Recursive function to find the closest pair of points<br>std::pair&lt;Point, Point&gt; closestPairRecursive(std::vector&lt;Point&gt;&amp; pointsX, std::vector&lt;Point&gt;&amp; pointsY, int left, int right) {<br>    if (right - left &lt;= 3) {<br>        return bruteForce(pointsX, left, right);<br>    }<br><br>    int mid = left + (right - left) / 2;<br>    Point midPoint = pointsX[mid];<br><br>    std::vector&lt;Point&gt; leftY, rightY;<br>    for (const Point&amp; p : pointsY) {<br>        if (p.x &lt;= midPoint.x)<br>            leftY.push_back(p);<br>        else<br>            rightY.push_back(p);<br>    }<br><br>    std::pair&lt;Point, Point&gt; leftPair = closestPairRecursive(pointsX, leftY, left, mid);<br>    std::pair&lt;Point, Point&gt; rightPair = closestPairRecursive(pointsX, rightY, mid + 1, right);<br><br>    double delta = std::min(distance(leftPair.first, leftPair.second), distance(rightPair.first, rightPair.second));<br>    std::pair&lt;Point, Point&gt; minPair = (distance(leftPair.first, leftPair.second) &lt; distance(rightPair.first, rightPair.second)) ? leftPair : rightPair;<br><br>    std::vector&lt;Point&gt; strip;<br>    for (const Point&amp; p : pointsY) {<br>        if (fabs(p.x - midPoint.x) &lt; delta)<br>            strip.push_back(p);<br>    }<br><br>    std::pair&lt;Point, Point&gt; splitPair = closestSplitPair(strip, delta);<br>    if (distance(splitPair.first, splitPair.second) &lt; delta) {<br>        minPair = splitPair;<br>    }<br><br>    return minPair;<br>}<br><br>// Main function to find the closest pair of points<br>std::pair&lt;Point, Point&gt; closestPair(std::vector&lt;Point&gt;&amp; points) {<br>    std::vector&lt;Point&gt; pointsX = points;<br>    std::vector&lt;Point&gt; pointsY = points;<br><br>    std::sort(pointsX.begin(), pointsX.end(), compareX);<br>    std::sort(pointsY.begin(), pointsY.end(), compareY);<br><br>    return closestPairRecursive(pointsX, pointsY, 0, points.size() - 1);<br>}<br><br>// Function to read points from a file<br>std::vector&lt;Point&gt; readPointsFromFile(const std::string&amp; filename) {<br>    std::vector&lt;Point&gt; points;<br>    std::ifstream infile(filename);<br>    double x, y;<br>    while (infile &gt;&gt; x &gt;&gt; y) {<br>        points.push_back({x, y});<br>    }<br>    return points;<br>}<br><br>int main() {<br>    std::string filename = &quot;points.txt&quot;;<br>    std::vector&lt;Point&gt; points = readPointsFromFile(filename);<br><br>    if (points.size() &lt; 2) {<br>        std::cerr &lt;&lt; &quot;Not enough points to find the closest pair.&quot; &lt;&lt; std::endl;<br>        return 1;<br>    }<br><br>    auto closest = closestPair(points);<br>    std::cout &lt;&lt; &quot;The closest pair of points is: (&quot; &lt;&lt; closest.first.x &lt;&lt; &quot;, &quot; &lt;&lt; closest.first.y &lt;&lt; &quot;) and (&quot;<br>              &lt;&lt; closest.second.x &lt;&lt; &quot;, &quot; &lt;&lt; closest.second.y &lt;&lt; &quot;)&quot; &lt;&lt; std::endl;<br>    std::cout &lt;&lt; &quot;The distance between them is: &quot; &lt;&lt; distance(closest.first, closest.second) &lt;&lt; std::endl;<br><br>    return 0;<br>}</pre><h3>Conclusion</h3><p>After thoroughly analyzing the algorithm’s components, it’s clear that sorting and dividing tasks into subproblems are key to success. The “divide and conquer” algorithm greatly reduces the number of operations compared to the naive method, achieving a time complexity of O(n log n).</p><p>Reflecting on my failed interview, where I limited myself to the naive method and spent time on auxiliary elements, I realized my knowledge was shallow. The interviewer’s question about handling more points made me question my approach. It took months before I revisited algorithms, determined to understand more advanced methods. “Divide and conquer” was the missing piece, and I read articles, took courses, and wrote numerous test programs to fully understand how it works.</p><p>That first interview became a turning point, teaching me to see the deeper essence behind simple tasks and to seek more efficient solutions. Now, I understand that even seemingly trivial tasks shouldn’t be underestimated and that each setback offers an opportunity to learn something new.</p><p>The “divide and conquer” algorithm is not just a technique; it’s an example of how the right strategy can transform a complex problem into an elegant solution. For me, it symbolizes persistence and the willingness to learn from mistakes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=832b20010246" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding Inversions in an Array: Algorithm and Optimal Implementation in C++]]></title>
            <link>https://medium.com/@alexey.medvecky/finding-inversions-in-an-array-algorithm-and-optimal-implementation-in-c-a13577a865c8?source=rss-80593edba6a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a13577a865c8</guid>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[merge-sort-techniques]]></category>
            <category><![CDATA[array-inversions]]></category>
            <category><![CDATA[data-structure-analysis]]></category>
            <category><![CDATA[optimization-algorithms]]></category>
            <dc:creator><![CDATA[Alexey Medvecky]]></dc:creator>
            <pubDate>Wed, 30 Oct 2024 08:25:30 GMT</pubDate>
            <atom:updated>2024-10-30T08:25:30.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*1URfL0IZRoJdPl_Je7JU7A.png" /></figure><p>Inversions in an array are an excellent measure of how far a sequence is from ideal order. In this article, we’ll explore what inversions are, how to count them, and demonstrate how to implement an optimal algorithm in C++.</p><h3>What Are Inversions?</h3><p>An inversion in an array is a pair of elements that are out of order. For an array A of n elements, an inversion is a pair of indices (i, j) where:</p><p>i &lt; j and A[i] &gt; A[j]</p><h3>Applications of Inversions.</h3><p>Inversions are used across various fields and tasks in data analysis. Here are a few examples:</p><ol><li><strong>Data Analysis and Statistics</strong>: Inversions indicate the level of disorder in an array. The more inversions, the less ordered the data. This helps assess how far a list is from a sorted state.</li><li><strong>Sequence Comparison</strong>: In bioinformatics, inversions are used to compare genomes, helping determine the degree of difference between two gene sequences.</li><li><strong>Similarity Metrics and Rank Correlation</strong>: Inversions measure how much one sequence differs from another (e.g., in preference or ranking lists). More inversions imply greater differences between sequences.</li><li><strong>Sorting Algorithm Performance Analysis</strong>: Inversions directly indicate the number of disrupted pairs that need rearrangement to sort an array.</li></ol><p>Thus, inversions are widely applied in optimization tasks, data analysis, and research in biology and computer science.</p><h3>Algorithms for Counting Inversions.</h3><h4>Naive Approach</h4><p>The naive method for counting inversions iterates through each pair of elements in the array and checks if the pair forms an inversion. This algorithm is straightforward but has a complexity of O(n²), as it compares each pair of elements in the worst case.</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br><br>int countInversionsNaive(const std::vector&lt;int&gt;&amp; data) <br>{<br>    int count = 0;<br>    for (size_t i = 0; i &lt; data.size(); i++ ) <br>    {<br>        for ( size_t j = i + 1; j &lt; data.size(); j++ ) <br>        {<br>            if ( data[ i ] &gt; data[ j ] ) <br>            {<br>              count++;<br>            }<br>        }<br>    }<br>    <br>    return count;<br>}<br><br>int main() <br>{<br>    std::vector&lt;int&gt; data = { 3, 1, 2 };<br>    int inv_count = countInversionsNaive( data );<br>    std::cout &lt;&lt; &quot;Number of inversions (naive): &quot; &lt;&lt; inv_count &lt;&lt; std::endl;<br>    return 0;<br>}</pre><p>The naive method is suitable only for small arrays. For larger arrays, a more efficient algorithm is needed.</p><h4>Optimal Approach: Modified Merge Sort</h4><p>An efficient method for counting inversions uses a modified merge sort, where inversions are counted during the merging of two subarrays. This algorithm operates in O(n log n), making it suitable for large arrays.</p><h4>Brief Overview and Analysis of Merge Sort</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aa3GMadJkiKFA16q6ZW7Fw.png" /></figure><p>Merge sort is a “divide and conquer” algorithm that recursively splits the array into subarrays until each subarray is a single element. At each recursion level, the subarrays are merged in sorted order:</p><ul><li><strong>Array Splitting</strong>: The array is divided in half until each part becomes an array of one element (considered sorted).</li><li><strong>Merging</strong>: The subarrays are merged in pairs, and each time an element from the right half is smaller than an element from the left, we count an inversion.</li></ul><p>The overall time complexity of merge sort is O(n log n) since each recursion level splits the array in half (log n levels), and merging at each level requires O(n) operations.</p><h4>How the Inversion Counting Algorithm Works</h4><p>The algorithm uses a divide-and-conquer strategy and consists of the following steps:</p><ol><li><strong>Splitting the Array into Subarrays</strong>: The array is recursively split in half until subarrays of size 1 are reached (these are considered sorted).</li><li><strong>Counting Inversions Within Each Subarray</strong>: After dividing to size 1, the merging process begins, during which inversions are counted.</li><li><strong>Counting Inversions Between Subarrays</strong>: While merging two sorted subarrays, inversions are counted each time an element from the right subarray is smaller than an element from the left (indicating an inversion). The count of inversions increases by the number of remaining elements in the left subarray.</li></ol><pre>#include &lt;iostream&gt;<br>#include &lt;fstream&gt;<br>#include &lt;vector&gt;<br>#include &lt;string&gt;<br>#include &lt;cstdlib&gt;<br><br>using namespace std;<br><br>long long merge_and_count( vector&lt;int&gt; &amp; data, vector&lt;int&gt; &amp; temp_arr, size_t left, size_t mid, size_t right )<br>{<br>    size_t left_index = left;<br>    size_t right_index = mid + 1;<br>    size_t tmp_index = left;<br>    long inv_count = 0;<br><br>    while ( left_index &lt;= mid &amp;&amp; right_index &lt;= right )<br>    {<br>        if ( data[ left_index ] &lt;= data[ right_index ] )<br>        {<br>            temp_arr[ tmp_index++ ] = data[ left_index++ ];<br>        }<br>        else<br>        {<br>            temp_arr[ tmp_index++ ] = data[ right_index++ ];<br>            inv_count += ( mid - left_index + 1 );<br>        }<br>    }<br><br>    while ( left_index &lt;= mid )<br>    {<br>        temp_arr[ tmp_index++ ] = data[ left_index++ ];<br>    }<br><br>    while ( right_index &lt;= right )<br>    {<br>        temp_arr[ tmp_index++ ] = data[ right_index++ ];<br>    }<br><br>    for ( left_index = left; left_index &lt;= right; left_index++ )<br>    {<br>        data[ left_index ] = temp_arr[ left_index ];<br>    }<br><br>    return inv_count;<br>}<br><br><br><br>long long merge_sort_and_count( vector&lt;int&gt; &amp; data, vector&lt;int&gt;&amp; temp_arr, size_t left, size_t right )<br>{<br>    long inv_count = 0;<br>    if ( left &lt; right )<br>    {<br>        size_t mid = ( left + right ) / 2;<br>        inv_count += merge_sort_and_count( data, temp_arr, left, mid );<br>        inv_count += merge_sort_and_count( data, temp_arr, mid + 1, right );<br>        inv_count += merge_and_count( data, temp_arr, left, mid, right );<br>    }<br><br>    return inv_count;<br>}<br><br>long count_inversions( vector&lt;int&gt; &amp; data )<br>{<br>    vector&lt;int&gt; temp_arr( data.size() );<br>    return merge_sort_and_count( data, temp_arr, 0, data.size() - 1 );<br>}<br><br>bool read_array_from_file( const string &amp; filename, vector&lt;int&gt; &amp; data )<br>{<br>    ifstream infile( filename.c_str() );<br>    if ( !infile )<br>    {<br>        cout &lt;&lt; &quot;Error: Failed to open file&quot; &lt;&lt; endl;<br>        return false;<br>    }<br><br>    int num;<br>    while ( infile &gt;&gt; num )<br>    {<br>        data.push_back( num );<br>    }<br><br>    infile.close();<br>    return true;<br>}<br><br>int main()<br>{<br>    vector&lt;int&gt; data;<br>    const string filename = &quot;data.txt&quot;;<br><br>    if ( !read_array_from_file( filename, data ) )<br>    {<br>        return EXIT_FAILURE;<br>    }<br><br>    long inv_count = count_inversions( data );<br><br>    cout &lt;&lt; &quot;Number of inversions expect: &quot; &lt;&lt; 2407905288 &lt;&lt; endl;<br>    cout &lt;&lt; &quot;Number of inversions actual: &quot; &lt;&lt; inv_count &lt;&lt; endl;<br><br>    return EXIT_SUCCESS;<br>}</pre><ul><li><strong>merge_and_count</strong>: This function merges two subarrays and counts inversions occurring between the left and right subarrays.</li><li><strong>merge_sort_and_count</strong>: This function recursively splits the array into subarrays and calls the merge function.</li><li><strong>count_inversions</strong>: This function initializes a temporary array and starts the sort-and-count inversion process.</li></ul><h4>Example of the Algorithm in Action</h4><p>Consider the array [3, 1, 2]:</p><ol><li>Dividing the array yields the subarrays [3], [1], and [2].</li><li>Merging and counting inversions:</li></ol><ul><li>Merging [3] and [1] results in an inversion because 3 &gt; 1.</li><li>Merging [1, 3] and [2] also yields an inversion (3, 2).</li><li>Thus, the total number of inversions is 2.</li></ul><h4>Performance Analysis</h4><p><strong>Recurrence Relation</strong></p><p>To analyze time complexity, we use a recurrence relation. The algorithm splits the array in half and recursively counts inversions, then performs merging, resulting in the relation:</p><p>T(n)=2T(n/2)+O(n)</p><p>where O(n) is the complexity of merging.</p><p><strong>Conclusion</strong>: The master theorem shows that modified merge sort allows counting inversions in O(n log ⁡n), making it much more efficient than the naive O(n²) approach.</p><h3>Conclusion</h3><p>We now have two approaches for counting inversions. While the naive method is straightforward and easy to implement, its O(n²) complexity limits it to small arrays. The modified merge sort, on the other hand, operates in O(n log ⁡n), making it suitable for large datasets. Try these methods and see how ordered your array is!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a13577a865c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Retro Computing with the ZX Spectrum Next]]></title>
            <link>https://medium.com/@alexey.medvecky/exploring-retro-computing-with-the-zx-spectrum-next-5ad912ad8e84?source=rss-80593edba6a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ad912ad8e84</guid>
            <category><![CDATA[zxspectrum]]></category>
            <category><![CDATA[c-language]]></category>
            <category><![CDATA[retrocomputing]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alexey Medvecky]]></dc:creator>
            <pubDate>Sun, 09 Jun 2024 10:40:19 GMT</pubDate>
            <atom:updated>2024-06-09T10:40:19.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*DdqQcWCEMTDqElOiBCtTVA.jpeg" /></figure><p>In the ever-evolving landscape of technology, there is a unique charm in stepping back and immersing oneself in the world of retro computing. This nostalgic journey began with the iconic Commodore 64, a staple of early computing, renowned for its role in introducing an entire generation to video games and programming. My personal project, developing a Reverse Polish Notation (RPN) calculator for the Commodore 64, was not just about reliving the past but about rekindling the ingenuity and problem-solving approach of that era.</p><p>Reverse Polish Notation, a mathematical notation wherein every operator follows all of its operands, suits the processing style of the Commodore 64 remarkably well. Implementing this on the C64 involved delving into C programming language and Assembly. The challenge was not just in the coding itself but in operating within the 64 KB memory limit, which encouraged a level of creativity and efficiency nearly forgotten in today’s age of abundant computing resources.</p><p>A more detailed description of the RPN Calculator project can be found in my previous <a href="https://medium.com/@alexey.medvecky/creating-a-calculator-for-the-commodore-64-using-the-c-language-3f94027186a4">article</a>.</p><h3>Transition to ZX Spectrum Next</h3><p>As fulfilling as it was to breathe new life into an old machine, my curiosity and passion for retro computing did not stop there. The next chapter in this vintage adventure was the ZX Spectrum, a British counterpart to the Commodore. The ZX Spectrum also boasts a rich history of influencing the software development and gaming industries. My interest in exploring different architectures and programming environments drove the transition to the ZX Spectrum.</p><p>However, this journey took an exciting turn with the introduction of the Spectrum Next, an enhanced version of the original ZX Spectrum. The Spectrum Next is not just a homage to its predecessor; it is a modern reimagining that maintains the soul of the original while boasting powerful new features such as a Z80 processor clocked at higher speeds, expanded memory, and new graphics modes.</p><p>Programming the Spectrum Next allowed for an interesting blend of old and new. While it was compatible with software written for the original ZX Spectrum, it also supported new functionalities that enabled me to push the boundaries of what could be achieved on retro hardware. My project transitioned into adapting the RPN calculator to this updated platform, which involved porting and optimising the code to take advantage of Next’s enhanced capabilities.</p><p>This part of the journey was about nostalgia and the lessons learned from history and how they can be applied in a modern context. The Spectrum Next provided a perfect bridge between the past and the present, allowing for a deeper appreciation of how far technology has come and how the foundations of these early computers still influence current technology trends.</p><h4>Overview of the Spectrum Next</h4><p>The Spectrum Next is an intriguing reimagining of the classic ZX Spectrum, designed to captivate both the enthusiasts of the original machine and modern programmers looking to explore retro computing with a twist. It stays true to its roots by maintaining the look and feel of the original ZX Spectrum but with significant enhancements that make it relevant in today’s technological landscape. At its heart, the Spectrum Next features a Z80 processor capable of running at speeds up to 28 MHz, a stark contrast to the original’s 3.5 MHz capability. It also includes up to 2 MB of RAM and supports VGA and HDMI output, offering much greater flexibility in display options than the original’s RF output.</p><p>The machine is not just an exercise in nostalgia; it is a fully functional computer that supports the development of new applications and games with enriched graphics and sound capabilities. Including hardware sprites, a tilemap mode, and a layering system make it particularly appealing for game development, bridging the gap between simple, classic gameplay and more complex graphical systems.</p><h4>Expanding Capabilities with WiFi</h4><p>One of the most notable modern enhancements in the Spectrum Next is the addition of WiFi connectivity, a feature unthinkable in the era of the original ZX Spectrum. This connectivity is a nod to modernity and a functional expansion that opens up many possibilities. With WiFi, users can easily download new software, participate in online coding communities, and even sync their projects across multiple devices without needing cumbersome physical media like cassettes or floppy disks.</p><p>The integration of WiFi also allows for the development of network-enabled applications and games. Programmers can create multiplayer experiences or utilities that fetch data from the internet, such as weather applications or RSS readers, directly on their Spectrum Next. This capability significantly expands the scope of what can be achieved with the machine, making it a powerful tool for education and experimentation in network computing.</p><p>Integrating WiFi into a retrocomputing platform like Spectrum Next enhances its utility and provides an educational bridge. It allows current generations to understand the fundamentals of computer networking and online communication within a more comprehensible and less complex framework than modern computers.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fzi6rEvXQiv8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dzi6rEvXQiv8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fzi6rEvXQiv8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccde67ccffc46078f69f3493575166e7/href">https://medium.com/media/ccde67ccffc46078f69f3493575166e7/href</a></iframe><h3>Introduction to z88dk C and Assembly Language on the ZX Spectrum Next</h3><p>The ZX Spectrum Next revives the classic computing experience and provides fertile ground for low-level programming with assembly language. Using the z88dk development kit, a collection of tools and libraries designed to facilitate the development of applications for Z80-based machines like the ZX Spectrum, enthusiasts can dive into the nuts and bolts of computer programming.</p><p>In this part of our journey into retro computing, we’ll explore how to write and run a simple “Hello, World!” program on the ZX Spectrum Next using assembly language and z88dk. This foundational programming exercise is an excellent introduction to assembly programming, highlighting the direct manipulation of the machine’s memory and output functions.</p><h4>Introduction to the Z80 Microprocessor</h4><p>The Z80 microprocessor, designed by Zilog in 1976, has been a cornerstone in developing personal computers, particularly those from the late 70s and 80s, such as the ZX Spectrum series. Its architecture and capabilities have made it a preferred choice for consumer electronics and embedded systems. The Z80’s design builds upon the earlier Intel 8080, with an enhanced instruction set and interrupted handling capabilities, facilitating more efficient and powerful computing applications.</p><h4>Technical Specifications and Features</h4><ul><li><strong>Processor Speed</strong>: Originally, Z80 processors operated at clock speeds typically ranging from 2.5 MHz to 6 MHz. The Spectrum Next significantly boosts this, offering speeds up to 28 MHz for enhanced performance.</li><li><strong>Instruction Set</strong>: The Z80 features an extended instruction set compared to its predecessors, including bit manipulation, block move, and search operations, which are not present in the Intel 8080.</li><li><strong>Registers</strong>:</li><li><strong>Accumulator and Flag Register</strong>: The 8-bit accumulator (A) is used for arithmetic and logic operations, with the results affecting the flags in the flag register for conditional operations.</li><li><strong>General-Purpose Registers</strong>: Registers B, C, D, E, H, and L can be used individually as 8-bit registers or combined as BC, DE, and HL pairs for 16-bit operations.</li><li><strong>Index Registers</strong>: IX and IY for effective address calculations, providing versatile addressing modes.</li><li>Stack Pointer (SP) and Program Counter (PC) are essential for stack management and program execution flow.</li><li><strong>Interrupt Modes:</strong> The Z80 supports three interrupt modes (IM 0, IM 1, IM 2), allowing flexible response strategies to external events or internal conditions.</li></ul><h4>Architectural Advantages</h4><p>The Z80’s architecture includes several features that were innovative for its time and continue to influence processor design:</p><ul><li><strong>Memory Management</strong>: The use of refresh registers (R) to maintain dynamic RAM during operation and simple yet effective interrupt handling mechanisms support robust system design.</li><li><strong>Input/Output Operations</strong>: Separate input/output instructions (IN, OUT) and space allow direct control over peripherals, simplifying hardware design for devices like the ZX Spectrum.</li><li><strong>Non-Maskable Interrupts (NMI)</strong>: This feature provides a robust method for dealing with high-priority interrupts that must be immediately addressed, ensuring more reliable system behaviour.</li></ul><h4>Impact on Computing</h4><p>The Z80’s flexibility and power made it a popular choice for early home computers and game consoles, laying the groundwork for software development and video game design during the early years of the computing revolution. Its design influenced many key concepts in computing, such as modular programming and event-driven programming, which are fundamental in modern software engineering.</p><h3>Writing the Program</h3><p>The “Hello, World!” program provided is a simple demonstration of using assembly language to output a string to the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOtvYiOo2_rzDH9dLnOBqA.jpeg" /></figure><p>Here’s a breakdown of how the program works:</p><ul><li><strong>Defining the Entry Point</strong>: The program begins with <strong><em>GLOBAL _main</em></strong>, which defines its entry point. This is essential for the z88dk linker to know where to start execution.</li><li><strong>Memory Section Declarations</strong>: The <strong><em>SECTION code_compiler</em></strong> and <strong><em>SECTION rodata_compiler</em></strong> commands organize code and read-only data separately, which helps manage memory usage more effectively.</li><li><strong>Loading and Displaying the String</strong>:</li><li><strong><em>ld bc, str_0</em></strong>: This instruction loads the address of the string into the BC register pair.</li><li>The <strong><em>my_loop</em></strong> label starts a loop where each string character is loaded into register A.</li><li><strong><em>ld a, (bc)</em></strong>: Loads the byte at the address contained in BC into A.</li><li><strong><em>cp 0</em></strong>: Compares the value in A with 0 (the end-of-string marker).</li><li><strong><em>jr z, end_program</em></strong>: Jumps to end_program if the zero flag is set (i.e., if A contains 0).</li><li><strong><em>rst $10</em></strong>: RST (or ‘restart’) is the same as CALL, except it uses only one byte, and is faster. However, you can only use it with eight specific ROM addresses, one of which is 0x10, which we call here.</li><li><strong><em>inc bc</em></strong>: Increments the BC register to point to the next character.</li><li><strong><em>jr my_loop</em></strong>: Jumps back to the start of the loop until the end of the string is reached.</li><li><strong>Ending the Program</strong>: end_program contains a ret instruction, which returns from the main function, effectively ending the program.</li><li><strong>Defining the String</strong>: In the rodata_compiler section, str_0 is defined with <strong><em>DEFM “Hello, world!”</em></strong> followed by <strong><em>DEFB 13, 0</em></strong>, which adds a carriage return and a null terminator to the end of the string.</li></ul><p>The result of the program running looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YD3RerK6jwojEJ0OaW4p0g.jpeg" /></figure><h4>From Assembly to C: A Strategic Shift</h4><p>While assembly language offers deep control over system resources and performance, transitioning to C programming brings numerous advantages, such as increased code portability, easier debugging, and faster development times. On platforms like the ZX Spectrum Next, which retains a strong community of retro computing enthusiasts, leveraging C opens the doors to more complex and versatile application development.</p><h4>Using conio.h for Text-Based User Interfaces</h4><p>The conio.h library, short for “console input/output,” is a C header file commonly used in MS-DOS programs but has found utility in other systems, including the ZX Spectrum Next, for creating text-based user interfaces. It provides functions to control text output on the console or the terminal emulator (like VT100), making it possible to create visually appealing and interactive applications.</p><p>The VT100, introduced by Digital Equipment Corporation (DEC) in 1978, set the standard for terminal emulation, a protocol that continued to evolve into what is commonly referred to today as ANSI terminals. VT100 and its successors helped define many of the control sequences used in terminal emulation, influencing how computers communicate with terminals and how text-based interfaces are managed.</p><p>Let’s consider how a simple VT100/ANSI control sequence works in practice:</p><p><strong><em>ESC[2J</em></strong></p><p>This escape sequence clears the entire screen and moves the cursor to the top-left corner. It begins with the ESC character, followed by `[`, the numeric code `2`, and the letter `J`. This kind of command is invaluable for creating a clean state for new output on the screen, essential for things like refreshing a user interface or initializing a game screen.</p><h4>Key Features of VT100/ANSI Terminals</h4><ul><li><strong>Screen Management</strong>: ANSI terminals allow sophisticated screen management capabilities, including cursor movement, screen clearing, and scrolling regions. These features are crucial for developing text-based user interfaces that require dynamic content updates.</li><li><strong>Text Formatting</strong>: Extensive options for text formatting are available, such as bold, underline, reverse video, and various text colours. These features enable developers to highlight important information and improve the readability of terminal output.</li><li><strong>Escape Sequences</strong>: ANSI escape sequences, strings of characters starting with the ESC character (ASCII 27), and control terminal functions. Specific sequences handle moving the cursor, changing text properties, or clearing portions of the screen.</li><li><strong>Keyboard and Mouse Input</strong>: ANSI terminals can also interpret input sequences from the keyboard and, in more advanced setups, from pointing devices like a mouse. This capability allows for interactive applications that respond in real-time to user actions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*dQ0cXyRg4Y4I1_0_Si5OTg.jpeg" /></figure><p>Here’s a look at some of the functions used in the provided example:</p><ul><li><strong><em>bordercolor, textcolor, textbackground</em></strong>: These functions set the colors of the border, text, and background respectively. Colors are managed through simple identifiers like BLACK, GREEN, and WHITE.</li><li><strong><em>clrscr</em></strong>: Clears the screen, a handy feature for initializing the display or refreshing the user interface.</li><li><strong><em>gotoxy</em></strong>: Moves the cursor to a specified position on the screen, given by x and y coordinates. This function is crucial for placing text exactly where it’s needed.</li><li><strong><em>puts</em></strong>: Writes a string to the console at the current cursor position.</li><li><strong><em>cgetc</em></strong>: Waits for a character input, useful for pausing the program until the user presses a key.</li></ul><p>Here is the result of the provided program and an example of using the .sync utility via WiFi:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FM8g-3ksg3xw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DM8g-3ksg3xw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FM8g-3ksg3xw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a1a9e0c50472123d53d4f019fb32ad8/href">https://medium.com/media/2a1a9e0c50472123d53d4f019fb32ad8/href</a></iframe><h3>Crafting “Hello World” on CP/M Using VT52/Generic Terminal Controls</h3><h4>Introduction to CP/M and VT52 Terminals</h4><p>CP/M, short for Control Program for Microcomputers, was an early operating system that became widely known in the 1970s and 1980s for its use in business and personal computers. It provided a standardized software platform for early microcomputer hardware and inspired the design for subsequent systems like MS-DOS.</p><p>The VT52 is a terminal Digital Equipment Corporation (DEC) developed that predates the more widely known VT100. It was one of the first terminals to support cursor movement and other control functions through escape sequences, although it had a more limited set of capabilities than later ANSI terminals. The VT52 and similar generic terminals facilitated text-based output and simple graphical displays on early computer systems.</p><h4>Implementing “Hello World” with VT52/Generic Console Commands</h4><p>The provided C program showcases using basic VT52 terminal controls in a CP/M environment to position text on the screen and manage screen clearing. Here’s how each part of the program functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EdF0h32WpwBFq26FPveh1g.jpeg" /></figure><ul><li><strong>Function <em>cls</em>()</strong>: This function clears the screen using the VT52 escape sequence <strong><em>\x1BJ</em></strong>, which erases from the cursor’s current position to the end of the screen. It starts by positioning the cursor at the top-left using <strong><em>gotoyx(0, 0).</em></strong></li><li><strong>Function <em>gotoyx()</em></strong>: It uses the escape sequence <strong><em>\x1BY</em></strong> followed by two characters that specify the cursor’s row and column positions. The `+ ‘ ‘` offset converts numerical values into printable ASCII characters, aligning with the VT52’s control code expectations.</li></ul><h4>Importance of VT52/Generic Terminal Capabilities</h4><p>The simplicity of the VT52 and similar generic terminals made them crucial in the early development of computer software, particularly for environments like CP/M. They allowed developers to create more user-friendly and visually structured applications before the advent of graphical user interfaces. Controlling cursor movement and screen management through concise escape sequences enabled the development of text-based games, educational software, and business applications.</p><p>Here is an example of importing and running a Hello World application for CP/M:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwFkd-Fbyvv0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwFkd-Fbyvv0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwFkd-Fbyvv0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/229c72cd5d0537899d56587ed2952302/href">https://medium.com/media/229c72cd5d0537899d56587ed2952302/href</a></iframe><h3>Conclusion: Reflecting on the Journey Through Retro Computing</h3><p>Exploring retro computing, from the Commodore 64 to the ZX Spectrum Next, encapsulates more than just a trip down memory lane—it represents a deep appreciation for the history and evolution of technology. This journey has allowed us to revisit the simplicity and innovation of the past and recognize how these early ideas continue to influence and shape modern computing.</p><p>Transitioning between different systems, from the Commodore 64 to the ZX Spectrum and finally to the Spectrum Next, provided valuable insights into the architectural and functional advancements in computing technology over the years. The introduction of modern features like WiFi connectivity and enhanced processing capabilities on the Spectrum Next demonstrates a seamless blend of nostalgia with contemporary technology, creating a platform that is both educational and functional.</p><p>Moreover, the use of programming languages from assembly to C has illustrated the evolution of software development practices. Starting with the detailed and hardware-close assembly language on the ZX Spectrum Next, and moving towards the higher-level abstractions offered by C, reflects broader trends in computing where the focus has increasingly shifted towards efficiency, portability, and accessibility.</p><p>The journey through retro computing is not merely about revisiting the technologies of the past but about learning from them. It teaches us the fundamentals of computing from the ground up, offering lessons in efficiency, creativity, and simplicity that are sometimes lost in modern, high-level programming environments. This understanding enriches our approach to contemporary software development, providing a solid foundation that combines the best of both worlds — the classic and the current.</p><p>In conclusion, the resurgence of interest in retro computing is more than nostalgia; it’s an homage to the industry&#39;s pioneers and an educational tool for today’s technologists. It serves as a reminder of how far technology has come and a testament to the enduring relevance of foundational computing principles. As we continue to advance into the future of technology, the lessons learned from these retro computing platforms will remain invaluable, guiding us through the next innovations and beyond.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ad912ad8e84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Calculator for the Commodore 64 Using the C Language]]></title>
            <link>https://medium.com/@alexey.medvecky/creating-a-calculator-for-the-commodore-64-using-the-c-language-3f94027186a4?source=rss-80593edba6a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f94027186a4</guid>
            <category><![CDATA[c-language]]></category>
            <category><![CDATA[retrocomputing]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[commodore-64]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alexey Medvecky]]></dc:creator>
            <pubDate>Thu, 09 May 2024 06:10:21 GMT</pubDate>
            <atom:updated>2024-05-09T06:10:21.035Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R8GqHwPVIuZlbT1IXWa_Yw.png" /></figure><h3>Introduction</h3><p>I hadn’t been documenting new discoveries and projects for a while, but today, I am eager to share my latest adventure back in the 1980s. During this period, I embarked on developing software for an intriguing device — the Commodore 64. My research revealed that while calculators were available for many platforms, including Atari, there was no reliable engineering calculator specifically for the Commodore 64.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ij7nD_BJOCb5CRZYN0oefw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*st23PWms-jiqLWh-Nj-Flw.jpeg" /></figure><p>This gap inspired me to create my own solution, which had the potential to evolve into a successful startup.</p><h3>Task and Solution</h3><h4>Initial Concept and Ambitions</h4><p>The original concept was to create a scientific calculator, starting with the ambitious task of developing my own floating-point number system. However, due to complexities and memory constraints, I quickly shifted to using standard BASIC ROM procedures.</p><h4>Choice of Algorithm</h4><p>I selected reverse Polish notation (RPN) as the foundational algorithm because it simplifies the processing of expressions by avoiding issues related to operation priority and parentheses. This approach was already employed in many engineering calculators of the era.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7PBZahwcvbwJGRhJfUfFA.png" /></figure><p>The core algorithm was as follows:</p><ul><li>The user enters a string containing a chain of RPN operations.</li><li>The application parses the string from start to finish.</li><li>If the current token is a number, it is placed in the stack.</li><li>If the current token is an operation:</li><li>Take arguments from the top of the stack.</li><li>Perform the operation.</li><li>Place the result back in the stack.</li></ul><p>After processing the string, the result of the sequence of operations appears at the top of the stack.</p><h4>Implementation of the Stack</h4><p>The stack, a central element of the algorithm, was implemented using a linked list to economically utilize the limited memory resources of the Commodore 64. The numbers were stored in a format similar to the <a href="https://en.wikipedia.org/wiki/Microsoft_Binary_Format">Microsoft Binary Format.</a></p><p>Specifically, it used a 40-bit MBF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_eiud436kWuli9ezhMO0oA.png" /></figure><p>I defined storage for this format as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*5LPsOWi_OZPHMFcgpuV4jw.png" /></figure><p>Accordingly, the linked list node for storing these numbers was designed as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*3qEPF_beHlxKns55VVAPPA.png" /></figure><p>The basic stack implementation was structured as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VjrfJ1EC2JH-FebuogIuCg.png" /></figure><p>The function takes two parameters: a pointer to the top of the stack (topPtr) and the value to be added to the stack (value). The topPtr is a pointer to a pointer, allowing the function to modify the actual pointer to the top of the stack.</p><p>At the start of the function, a new node (newPtr) is allocated on the heap using the malloc function. The size of the memory allocated is equal to the size of a StackNode.</p><p>The function then checks if the memory allocation was successful by checking if newPtr is not NULL. If the memory allocation was successful, the function proceeds to copy the value into the data field of the new node using the memcpy function. The nextPtr field of the new node is then set to point to the current top of the stack. Finally, the topPtr is updated to point to the new node, effectively adding the new node to the top of the stack.</p><p>If the memory allocation was not successful (i.e., newPtr is NULL), the function prints the value that was not inserted using the FP_printRaw function and outputs an error message indicating that no memory is available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZSQ4NCNUfFbeVX4CkSiFA.png" /></figure><p>The function takes one parameter: a pointer to the current node in the stack (currentPtr).</p><p>At the start of the function, it checks if the stack is empty by checking if currentPtr is NULL. If the stack is empty, it outputs a message indicating that the stack is empty using the puts function.</p><p>If the stack is not empty, it outputs a message indicating the top of the stack. It then enters a while loop that continues as long as currentPtr is not NULL. Inside the loop, it does the following:</p><ol><li>It copies the data from the current node to resultFp using the memcpy function. The size of the data copied is equal to the size of FP.</li><li>It calls the enableBasicRom function.</li><li>It calls the FP_printResult function to print the result. This function prints the contents of resultFp.</li><li>It calls the disableBasicRom function.</li><li>It updates currentPtr to point to the next node in the stack.</li></ol><p>After the loop, it outputs a message indicating the bottom of the stack. This function, therefore, prints the contents of the stack from top to bottom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cmSqulJlSW7nIl-zyilog.png" /></figure><p>The function takes two parameters: a pointer to the top of the stack (topPtr) and a pointer to a variable where the popped value will be stored (popValue). The topPtr is a pointer to a pointer, allowing the function to modify the actual pointer to the top of the stack.</p><p>At the start of the function, it checks if the stack is empty by calling the Stack_isEmpty function with *topPtr as the argument. If the stack is empty, it outputs a message indicating that the stack is empty using the puts function and returns EXIT_FAILURE.</p><p>If the stack is not empty, it proceeds to pop the top element from the stack. It first stores the pointer to the top node in a temporary variable (tempPtr). It then copies the data from the top node to *popValue using the memcpy function. The size of the data copied is equal to the size of FP.</p><p>Next, it updates topPtr to point to the next node in the stack, effectively removing the top node from the stack. It then frees the memory allocated to the removed node using the free function.</p><p>Finally, the function returns EXIT_SUCCESS to indicate that the operation was successful.</p><h4>Calculator Functionality</h4><p>The calculator began with basic functionality:</p><p>- Parsing the string: Inputting a string with RPN operations, splitting it into tokens, recognizing numbers and operations.</p><p>- Processing numbers: String data of numbers were processed and transformed into floating-point numbers using BASIC ROM functions.</p><p>- Executing operations: Basic functions implemented arithmetic operations and power calculations.</p><p>Once the stack was ready, I proceeded to implement the calculator’s primary function. The first step was to receive the string with calculation arguments and split it into tokens using standard C functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JMrxSg0-cnkzJd-hwZW-yA.png" /></figure><p>Tokens were then divided into commands and numbers and processed accordingly.</p><h4>Processing Numbers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*NR271zysqvVEU-fdNZOLBg.png" /></figure><p>In this function, I first validated the string representation of the number. Then, I copied this string to a memory area, which I later passed as an argument to a BASIC ROM function to convert the string to a floating-point number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*490gc4R-QL474v_vPGnstg.png" /></figure><p>The function, called by the address B7B5, converts a numerical PETSCII string into a floating-point number in FAC Expects string address in $22/$23 and the length of the string in the accumulator.</p><p>The function, called by the address BBD4, stores the number currently in FAC to a RAM location. It uses <a href="https://www.c64-wiki.com/wiki/X-register">X</a> and Y rather than A and Y to point to RAM. (X=Addr.LB, Y=Addr.HB)</p><p>Using the stack’s abstract data type, I saved the processed number in the stack.</p><h4>Processing Commands</h4><p>For the first version, I implemented four arithmetic operations and a power function, which could also compute roots.</p><p>A switch operator was used to select operation handlers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TawqCRdN65nPvXSam3Zf3Q.png" /></figure><p>The function handlers utilized assembly to call BASIC ROM functions for operations with floating-point numbers.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*ljTs6Sh-lletx63ilMOUuA.png" /></figure><p>The function, called by the address BA28 multiplies a number from RAM and FAC (clobbers ARG, A=Addr.LB, Y=Addr.HB)</p><p>In subsequent versions, I began using lookup tables to select handlers as the number of operations increased.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*E3C2KIX4_z48SUHeIevqRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OuoYNzggTl4PGeE0QVfrrQ.png" /></figure><p>The function takes one parameter: a pointer to a character string (token), which represents the name of the operation to be performed.</p><p>At the start of the function, a pointer (op) is initialized to point to the first element of the operations array.</p><p>The function then enters a for loop that continues as long as the name field of the current Operation is not NULL. Inside the loop, it does the following:</p><ol><li>It compares the token with the name field of the current Operation using the strcmp function. If they are equal (i.e., strcmp returns 0), it proceeds to the next steps. Otherwise, it moves to the next Operation in the array.</li><li>It calls the handleOneOperandOperation function with the func field of the current Operation as the argument. This function gets the argument from the stack and calls the BASIC ROM function to handle the operation.</li><li>It calls the Stack_push function to push the result of the operation (stored in resultFp) onto the stack. The stackPtr is passed as the pointer to the top of the stack.</li><li>It returns EXIT_SUCCESS to indicate that the operation was successful.</li></ol><p>If the function exits the loop without finding a matching operation, it outputs a message indicating that the function is invalid and returns EXIT_FAILURE.</p><p>This formed the foundation for the first version of the calculator, which looked like this:</p><p><a href="https://youtube.com/shorts/pEm8QZQxv-U?feature=share">Calculator demo 2</a></p><h3>Versions and Extensions</h3><h4>Version 2.0</h4><p>In the next release, I added functions for engineering calculations, improved error handling and validation, and expanded the functionality of the stack (viewing and modifying elements).</p><p>Then, I implemented the swap and dupe functions from Forth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*55p2WupC31CLKqOd9CqlBA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*KxfQ4xgQ6lCyNnxaRxNUAA.png" /></figure><p>These functions allowed for writing more complex sequences of calculations.</p><p><a href="https://youtube.com/shorts/ypv0Yz-nF7g">Calculator demo 1</a></p><h4>Version 3.0</h4><p>A significant new feature was the operation history, which facilitated the reuse and editing of previous calculations. This enhancement significantly simplified the use of the calculator, making it more convenient for complex engineering tasks. The history function was tasked with:</p><p>1. Saving the last n operations.</p><p>2. Reusing a line from history.</p><p>3. Editing a line from history before use.</p><p>The implementation of history used a queue based on a linked list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b3pJig7imPqLZpMELi0Y-g.png" /></figure><p>The function takes one parameter: the capacity of the queue (capacity).</p><p>At the start of the function, memory is allocated for a new Queue structure using the malloc function. The size of the memory allocated is equal to the size of a Queue. The returned pointer from malloc is cast to a Queue * and stored in q.</p><p>Next, the head and tail pointers of the new queue are initialized to NULL, indicating that the queue is initially empty. The size field of the queue is also initialized to 0.</p><p>The capacity field of the queue is then set to the capacity parameter passed to the function. This sets the maximum number of elements that the queue can hold.</p><p>Finally, the function returns the pointer to the newly created queue (q).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p8JpQmKkmhF_JAFmGpyqtQ.png" /></figure><p>The function Queue_enqueue is designed to add a new element to a queue data structure. The queue is implemented as a linked list, with each node in the list containing a pointer to a string (data) and a pointer to the next node (next).</p><p>The function begins by allocating memory for a new node. It then checks if the queue is at its capacity. If it is, the function dequeues the oldest element to make room for the new one. This is done by moving the head pointer to the next node in the queue, effectively removing the current head node from the queue. If this operation leaves the queue empty (i.e., q-&gt;head is NULL), it also sets the tail pointer to NULL. The function then frees the memory allocated for the string data and the dequeued node, and decrements the queue&#39;s size.</p><p>Next, the function allocates memory for the new element’s data (a string), copies the input string into this memory, and sets the next pointer of the new node to NULL.</p><p>Finally, the function adds the new node to the queue. If the queue is currently empty (i.e., q-&gt;tail is NULL), it sets both the head and tail pointers to the new node. Otherwise, it adds the new node at the end of the queue by setting the next pointer of the current tail node to the new node, and then updating the tail pointer to the new node. The function then increments the queue&#39;s size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-LNCUs79ZRto7kABmAxPw.png" /></figure><p>The function Queue_getNthElement is designed to retrieve the nth element from a queue data structure. The queue is implemented as a linked list, with each node in the list containing a pointer to a string (data) and a pointer to the next node (next).</p><p>The function begins by initializing an index counter to 0, a pointer current to the head of the queue, and a copy pointer to NULL. The variable isNeedToClear is set to 1, but it&#39;s not clear from this code snippet what its purpose is.</p><p>The function then decrements n by 1. This is because in C, arrays and similar data structures are zero-indexed, meaning the first element is at index 0.</p><p>Next, the function checks if n is greater than or equal to the size of the queue. If it is, this means the requested index is out of range, so the function prints an error message and returns NULL.</p><p>If n is within range, the function enters a while loop that continues as long as current is not NULL and index is less than n. Inside the loop, current is updated to point to the next node in the queue, and index is incremented by 1. This loop effectively moves the current pointer n nodes along the queue.</p><p>Once the loop finishes, current points to the nth node in the queue. The function then allocates memory for copy, copies the data from the nth node into this memory, and returns copy. This means the function returns a copy of the nth element&#39;s data, not a pointer to the data itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9LRZlo3SX1gHPMLiXCVjKQ.png" /></figure><p>The function historyGetLastElement is designed to retrieve the last element from a queue and handle it. The queue is presumably a queue of strings, given the char * type of lastElement.</p><p>The function begins by calling Queue_getLastElement with queuePtr as an argument. Queue_getLastElement is function that retrieves the last element from a queue, and queuePtr is a pointer to the queue from which to retrieve the element. The retrieved element is stored in lastElement.</p><p>Next, the function checks if lastElement is not NULL. If lastElement is NULL, this would indicate that the queue is empty, so there is no element to handle.</p><p>If lastElement is not NULL, the function calls handleArgumentString with lastElement as an argument.</p><p>Eventually, the calculator was enhanced to include these features:</p><p>Example of approximating Pi using Newton’s method! I employ the formula Xn+1 = Xn — F(Xn)/F’(Xn), where F(X) = cos(X) + 1 (root at Pi) and its derivative F’(X) = -sin(X), starting our first approximation with X0 = 3.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZux8qJzLdwk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZux8qJzLdwk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZux8qJzLdwk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/19cb03be643991aaa67a00493a8be267/href">https://medium.com/media/19cb03be643991aaa67a00493a8be267/href</a></iframe><p>Example of numerical derivative calculation:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTKEgop-R3pA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTKEgop-R3pA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTKEgop-R3pA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/98b8517bd19d20723f01bb4863c31113/href">https://medium.com/media/98b8517bd19d20723f01bb4863c31113/href</a></iframe><p>For those interested in delving deeper into the technical specifics or exploring the source code of my latest project, the complete repository is available <a href="https://github.com/medvecky/C64-multi-functional-calculator">here.</a> This comprehensive resource provides access to all the developmental stages and updates of my project.</p><p>Additionally, to get a more personal glimpse into the creative process behind our projects or to connect with the project’s author, follow my Instagram <a href="https://www.instagram.com/alexeymedvecky">here</a>. This platform offers regular updates and behind-the-scenes content directly from the creator, enhancing your understanding of the project’s journey and the minds behind it.</p><h3>Conclusion</h3><p>Despite its technical limitations, the Commodore 64 calculator project proved successful and had the potential for commercial success during its era. The implementation in C was chosen for ease of support, despite being less optimal than assembly. This project not only underscores the ability to create useful and functional applications within the constraints of limited technology but also highlights the importance of understanding and recreating fundamental data structures like queues and stacks. These structures are crucial for efficient algorithm design and can significantly enhance the functionality of even basic computing systems. Stay tuned and continue with me on my time travel journey as we explore more innovative creations from the past, demonstrating the timeless nature of ingenuity and determination.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f94027186a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Fraction Calculator for the Commodore 64 in Assembly Language]]></title>
            <link>https://medium.com/@alexey.medvecky/building-a-fraction-calculator-for-the-commodore-64-in-assembly-language-33b69ea7d8a3?source=rss-80593edba6a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/33b69ea7d8a3</guid>
            <category><![CDATA[commodore-64]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[assembly-language]]></category>
            <category><![CDATA[retrocomputing]]></category>
            <dc:creator><![CDATA[Alexey Medvecky]]></dc:creator>
            <pubDate>Tue, 03 Oct 2023 13:30:55 GMT</pubDate>
            <atom:updated>2023-10-03T13:30:55.166Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*_jCrCqcmAj9J5I8_KYvaQQ.png" /></figure><p>I will guide you through creating a fraction calculator for the Commodore 64 using assembly language in this article. We will utilize KickAssembler, primarily its macros, to simplify the process.</p><h3>Formulating the Problem</h3><p>My journey through the 80s using the Commodore 64 to tackle mathematical problems continues. Previous parts of my journey:</p><ul><li><a href="https://medium.com/@alexey.medvecky/a-retro-adventure-implementing-an-aspect-ratio-calculator-for-the-commodore-64-in-multiple-b634d4d61b23">A Retro Adventure: Implementing an Aspect Ratio Calculator for the Commodore 64 in Multiple Programming Languages</a></li><li><a href="https://medium.com/@alexey.medvecky/80s-time-travel-commodore-64-math-with-square-root-approximation-factorization-using-assembly-6256e60cfdda">80s Time Travel: Commodore 64 Math with Square Root Approximation &amp; Factorization using Assembly</a></li><li><a href="https://medium.com/@alexey.medvecky/creating-a-fraction-converter-for-the-commodore-64-in-assembly-language-6510-6502-1be97c224d4">Creating a Fraction Converter for the Commodore 64 in Assembly Language (6510/6502</a>)</li></ul><p>Fractions have always been a challenge for calculators, and even in the 80s, their support was limited.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*eDvUF4oWyMIsOKCR-abi5Q.jpeg" /></figure><p>Let’s leverage the power of the Commodore 64 to solve this mathematical puzzle.<br>In this part, we’ll dive into creating a fraction calculator, a task that was particularly challenging back in the 80s. Follow along to see how I use the Commodore 64’s capabilities to overcome this challenge.</p><h3>Solution.</h3><p>As previously mentioned, the 6510 processor lacks support for floating-point operations, so we’ll rely on the software implementation from BASIC ROM. I’ll use KickAssembler and its macro capabilities to expedite the development process, a luxury that may not have been available with assemblers of the 80s.<br>The most commonly used macros for arithmetic operations and a macro for modulo division will be essential components of our solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NGtYls7J5n8n-v-GlYsLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sqF8GFdYAb4qA8ogCXIt2w.png" /></figure><p>The source file, complete with macro definitions and constants, is in this [<a href="https://gist.github.com/medvecky/0c5e063f79aa05972b18f4da61e056d8">link to git gist</a>].</p><p>The program begins by displaying and processing menu selections, where the active use of macros becomes apparent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tKW7RLVd9koDLMqDZrXCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9zpEaZcH387kIRqSjwrdA.png" /></figure><h4>Entering a String Representation of a Number</h4><p>In this project, I’ve revamped the routine for the string representation of numbers, ensuring it processes only valid characters for our program. This includes the numbers 0 to 9, “-”, “return”, and “del”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cwNN2DrK6Hdnk3e53v8Htw.png" /></figure><p>Here, in addition to the exact comparison based on the zero flag, a comparison of “more” and “less” is used based on the carry flag.<br> This level of detail highlights the need for a deep understanding of the processor’s operation. It’s moments like these that make me love it.</p><h4>Fraction Simplification and Result Display</h4><p>Simplifying a fraction is the core routine we’ve implemented first because other routines rely on it. The key to simplifying fractions is finding the greatest common divisor (GCD), which we accomplish using the Euclidean algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*MSd1Gf3ciguFoAB844RnZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MB4ALCob6VgYffOjOl4Ryg.png" /></figure><p>The simplification function handles several steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5_hvA4Z7hm4JJGKDUmUHQ.png" /></figure><ul><li>The routine receives arguments from the user.</li><li>The routine checks whether the denominator is zero.</li><li>The routine copies them and passes them to the GCD routine.</li><li>The routine divides the numerator and denominator by the GCD result.</li><li>The routine outputs the result with the following function :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJl90lWrKBTPuyYsy_FarQ.png" /></figure><ul><li>Check whether the fraction is proper or not.</li><li>If improper, convert it to mixed:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*_00GDCmMKRRjvEECyFwLGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J75MrwFFpc755ZV1WeIOfQ.png" /></figure><ul><li>Prints the result of the transformation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pngujHw46YIQ4gerQAb7JQ.png" /></figure><h4>Converting a Mixed Fraction to an Improper Fraction</h4><p>Our program also supports converting mixed fractions to improper fractions using a well-defined algorithm. The implementation details are provided there:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*_YYduflwMa21xsAnjPXqhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjtNadv1_UjZ98-h8jdghQ.png" /></figure><h4>Multiplying and Dividing Fractions</h4><p>Multiplication and division of fractions are relatively straightforward operations, each with its dedicated function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dwi-GB1Fq1--Z4SAg7rZ-A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LjiakW7WGZhNkGJJBPyA2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*5VXcIdTaEND7mORBZ_h2uw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eXONun-pgn6k8fuOnHUM3w.png" /></figure><h4>Adding and Subtracting Fractions</h4><p>Adding and subtracting fractions are more complex due to the need to find a common denominator. We’ve tackled this challenge by implementing a casting operation based on GCD, enabling us to perform addition and subtraction efficiently.</p><p>The casting operation is done using the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*Ka-2b-enzVyDaid5QtZONw.png" /></figure><p>It is implemented with the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ju5lvE-Y1HfdQ-JIDpD6yQ.png" /></figure><p>The next happens in the code:</p><ul><li>Entering the numerator and denominator of both fractions.</li><li>Denominators are checked for zero.</li><li>Denominators are passed as arguments to the GCD routine.</li><li>The common denominator and multipliers for the numerators are found based on the resulting GCD.</li><li>Fractions are reduced to a common denominator.</li></ul><p>When the casting function is ready, addition and subtraction are implemented by this code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MfxYvvzK30I9TkmaN2vA3w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YcWEWa0XVL2QOARSNeVi3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VNsQSD7sbtXigtriBsRmg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-6LJWQTnVxS2pyIPVfx7g.png" /></figure><h3>Conclusion</h3><p>The final executable file is 8322 bytes in size, which may seem significant for a calculator, but future optimization is possible.</p><p>The program works as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*GzMDurtYhZ1sh-fZQJ01Vg.gif" /></figure><p>The complete source code can be found here:</p><ul><li>Main: [<a href="https://gist.github.com/medvecky/e1fd9f9658489a295b91e93187e4885a">link to gist</a>]</li><li>Subroutines: [<a href="https://gist.github.com/medvecky/01f090aef633d32ec54f5565c2a6d301">link to gist</a>]</li><li>Definitions: [<a href="https://gist.github.com/medvecky/0c5e063f79aa05972b18f4da61e056d8">link to gist</a>]</li><li>Data: [<a href="https://gist.github.com/medvecky/51b4b3c8b98a96db6baae862b6dd6304">link to gist</a>]</li></ul><p>This program not only serves as a powerful tool but also brings back memories of school mathematics. I’ve thoroughly enjoyed this journey into the 80s and plan to continue exploring the capabilities of the Commodore 64 for mathematical challenges. If you’re interested, stay tuned for more adventures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7pSZIioQgpW3VSsQJMkkQ.png" /></figure><p>In this endeavor, I’ve deviated from the norm using macros, which greatly expedited development and made the process more enjoyable. I’ve created a tool I missed during my school days, and it’s a testament to the power of the Commodore 64. Join me in this journey through the 80s, where we continue to harness the capabilities of this remarkable machine for mathematical purposes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33b69ea7d8a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Fraction Converter for the Commodore 64 in Assembly Language (6510/6502)]]></title>
            <link>https://medium.com/@alexey.medvecky/creating-a-fraction-converter-for-the-commodore-64-in-assembly-language-6510-6502-1be97c224d4?source=rss-80593edba6a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1be97c224d4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[assembly-language]]></category>
            <category><![CDATA[commodore-64]]></category>
            <category><![CDATA[retrocomputing]]></category>
            <dc:creator><![CDATA[Alexey Medvecky]]></dc:creator>
            <pubDate>Tue, 05 Sep 2023 13:10:13 GMT</pubDate>
            <atom:updated>2023-09-05T13:10:13.833Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*01GDAkeO8A6Qg1G5WwT5wg.jpeg" /></figure><p>In this article, we’ll delve into the process of creating a fraction to decimal, percentage, and back converter for the Commodore 64 using Assembly language (6510/6502). This project not only provides a practical application of assembly programming skills but also allows us to explore the nostalgic charm of 80s computing.</p><h3>Problem Statement</h3><h4>Embracing the 80s Nostalgia</h4><p>As we traverse through the time machine, we find ourselves in the 80s, where writing mathematical programs for the Commodore 64 is not just a hobby but part of a school course. In this article, we embark on our journey to create a fraction converter, a seemingly simple yet insightful project to sharpen our Assembly language skills.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*43_KgnmVMKTntxjxMllhlw.jpeg" /></figure><p>This article continues the topic that I began in previous articles:</p><ul><li><a href="https://medium.com/@alexey.medvecky/a-retro-adventure-implementing-an-aspect-ratio-calculator-for-the-commodore-64-in-multiple-b634d4d61b23">A Retro Adventure: Implementing an Aspect Ratio Calculator for the Commodore 64 in Multiple Programming Languages</a></li><li><a href="https://medium.com/@alexey.medvecky/80s-time-travel-commodore-64-math-with-square-root-approximation-factorization-using-assembly-6256e60cfdda">80s Time Travel: Commodore 64 Math with Square Root Approximation &amp; Factorization using Assembly</a></li></ul><h3>Solution</h3><h3>Building a BASIC Prototype</h3><p>Traditionally, we commence our implementation with a prototype in BASIC. Prototype serves as a foundation, allowing us to visualize the program’s structure and overall design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*xLbP1MgCTvQ7wW4w5Ui6Rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*a8BBfmd24uoubFBbXLHsKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*kFoubZ6r7KHa715r1uTzSQ.png" /></figure><p>Two noteworthy aspects of the prototype include:</p><ul><li>Menu Implementation: We determine menu options.</li><li>Exponent Calculation: Utilizing the length of textual number representation to compute the exponent.</li></ul><h3>Transitioning to Assembly Language</h3><p>Having covered numerous details in previous articles, we will focus on the high-level logic of our Assembly solution, along with the innovative approaches we’ve adopted.</p><h3>Menu Handling</h3><p>After the screen setup and tooltip display, the menu display function takes centre stage as the program’s initial function. This function efficiently displays menu items and handles user input. If the user enters an invalid option, the program gracefully ignores it. Subsequently, it invokes the relevant procedure based on the user’s input.</p><pre>main:<br>        jsr     prepare_screen<br>        jsr     main_usage<br>menu:<br>        jsr     show_menu<br>wait_for_continue:<br>        jsr     getin<br>        beq     wait_for_continue<br>        cmp     #q_sym<br>        beq     go_to_exit<br>        cmp     #one_sym<br>        beq     handle_decimal<br>        cmp     #two_sym<br>        beq     handle_fraction<br>        cmp     #three_sym<br>        beq     handle_percent<br>        jsr     clearscreen<br>        jmp     menu<br>handle_decimal:<br>        jsr     decimal_handler<br>        jmp     continue_or_exit<br>handle_fraction:<br>        jsr     fraction_handler<br>        jmp     continue_or_exit<br>handle_percent:<br>        jsr     percent_handler<br>        jmp     continue_or_exit<br>go_to_exit:<br>        jmp     restore_and_exit<br><br>continue_or_exit:<br>        jsr     usage_at_exit<br>wait_for_input:<br>        jsr     getin<br>        beq     wait_for_input<br>        cmp     #q_sym<br>        bne     continue<br>        jmp     restore_and_exit<br>continue:<br>        jsr     clearscreen<br>        jmp     menu<br><br>restore_and_exit:<br>        jsr     restore_screen<br><br>        rts</pre><h3>Decimal Conversion</h3><pre>decimal_handler:<br>        jsr     input_decimal<br>        jsr     cursor_blink_off<br>        jsr     calculate_den<br>        lda     #&lt;n<br>        ldy     #&gt;n<br>        jsr     fp_load_ram_to_fac<br>        lda     #&lt;den<br>        ldy     #&gt;den<br>        jsr     fp_mult<br>        ldx     #&lt;num<br>        ldy     #&gt;num<br>        jsr     fp_store_fac_to_ram<br>        lda     #&lt;hundred<br>        ldy     #&gt;hundred<br>        jsr     fp_load_ram_to_fac<br>        lda     #&lt;n<br>        ldy     #&gt;n<br>        jsr     fp_mult<br>        ldx     #&lt;per<br>        ldy     #&gt;per<br>        jsr     fp_store_fac_to_ram<br>        jsr     show_results<br>        rts<br><br>input_decimal:<br>        jsr     input_decimal_prompt<br>        jsr     input_string_proc<br>        jsr     string_to_fp<br>        ldx     #&lt;n<br>        ldy     #&gt;n<br>        jsr     fp_store_fac_to_ram<br>        jsr     get_exponent_by_counter<br>        lda     #space_sym<br>        jsr     print_char<br>        lda     #new_line<br>        jsr     print_char<br>        rts</pre><p>Our decimal handler routine takes a decimal as an argument and converts it into a fraction and a percentage. This routine initiates with an input procedure similar to our earlier discussion. The key difference lies in calculating the exponent based on the entered character count.</p><pre>get_exponent_by_counter:<br>        ldx     counter<br>        dex<br>        txa<br>        sta     e_counter<br>        lda     number_strings<br>        clc<br>        adc     counter<br>        sta     address<br>        dec     address<br>        lda     #&lt;(address)<br>        sta     $22<br>        lda     #&gt;(address)<br>        sta     $23<br>        lda     #string_length<br>        jsr     fp_string_to_fac<br>        ldx     #&lt;e<br>        ldy     #&gt;e<br>        jsr     fp_store_fac_to_ram<br>        rts</pre><p>This procedure does the following:</p><ul><li>Decrements the counter value by one and stores the resulting value in the exponent counters.</li><li>Loads into the accumulator the address of the beginning of the array of string representation of numbers.</li><li>Adds to the result the counter of entered characters saved in a variable.</li><li>Since the offset counts from 0 reduces the value by one.</li><li>Next, the full address of the array element is loaded with an offset.</li><li>The string at the specified address is converted to a floating point number and stored in the variable e (exponent).</li></ul><p>The number string array looks like the following:</p><pre>number_strings:<br>        .text   &quot;0&quot;<br>        .byte   $0<br>        .text   &quot;1&quot;<br>        .byte   $0<br>        .text   &quot;2&quot;<br>        .byte   $0<br>        .text   &quot;3&quot;<br>        .byte   $0<br>        .text   &quot;4&quot;<br>        .byte   $0<br>        .text   &quot;5&quot;<br>        .byte   $0<br>        .text   &quot;6&quot;<br>        .byte   $0<br>        .text   &quot;7&quot;<br>        .byte   $0<br>        .text   &quot;8&quot;<br>        .byte   $0<br>        .text   &quot;9&quot;<br>        .byte   $0<br>        .text   &quot;10&quot;<br>        .byte   $0<br>        .text   &quot;11&quot;<br>        .byte   $0<br>        .text   &quot;12&quot;<br>        .byte   $0<br>        .text   &quot;13&quot;<br>        .byte   $0<br>        .text   &quot;14&quot;<br>        .byte   $0<br>        .text   &quot;15&quot;<br>        .byte   $0</pre><p>Next, in the decimal handler, a procedure is called to calculate the denominator.</p><pre>calculate_den:<br>        ldx     e_counter<br>        dex<br>        beq     handle_tenth<br>        txa<br>        sta     counter<br>        lda     #&lt;ten<br>        ldy     #&gt;ten<br>        jsr     fp_load_ram_to_fac<br>mult_loop:<br>        lda     #&lt;ten<br>        ldy     #&gt;ten<br>        jsr     fp_mult<br>        ldx     counter<br>        dex<br>        beq     end_loop<br>        txa<br>        sta     counter<br>        jmp     mult_loop<br>end_loop:<br>        ldx     #&lt;den<br>        ldy     #&gt;den<br>        jsr     fp_store_fac_to_ram<br>        jmp     end_mult<br>handle_tenth:<br>        lda     #&lt;ten<br>        ldy     #&gt;ten<br>        jsr     fp_load_ram_to_fac<br>        ldx     #&lt;den<br>        ldy     #&gt;den<br>        jsr     fp_store_fac_to_ram<br><br>end_mult:<br>        rts</pre><p>This routine calculates ten powered by exponent using multiplication and the e_counter value obtained in the previous routine.</p><p>Further, I get the numerator by multiplying the entered number by the denominator.<br>And by multiplying the entered number by 100, I get the percentage.</p><p>Next, I display the result by a separate procedure.</p><pre>show_results:<br>        lda     #space_sym<br>        jsr     print_char<br>        lda     #new_line<br>        jsr     print_char<br>        lda     #&lt;result_1<br>        ldy     #&gt;result_1<br>        jsr     print_str<br>        lda     #&lt;n<br>        ldy     #&gt;n<br>        jsr     fp_load_ram_to_fac<br>        jsr     fp_to_str<br>        jsr     print_str<br>        lda     #new_line<br>        jsr     print_char<br>        lda     #&lt;result_2<br>        ldy     #&gt;result_2<br>        jsr     print_str<br>        lda     #&lt;num<br>        ldy     #&gt;num<br>        jsr     fp_load_ram_to_fac<br>        jsr     fp_to_str<br>        jsr     print_str<br>        lda     #&lt;result_3<br>        ldy     #&gt;result_3<br>        jsr     print_str<br>        lda     #&lt;den<br>        ldy     #&gt;den<br>        jsr     fp_load_ram_to_fac<br>        jsr     fp_to_str<br>        jsr     print_str<br>        lda     #new_line<br>        jsr     print_char<br>        lda     #&lt;result_4<br>        ldy     #&gt;result_4<br>        jsr     print_str<br>        lda     #&lt;per<br>        ldy     #&gt;per<br>        jsr     fp_load_ram_to_fac<br>        jsr     fp_to_str<br>        jsr     print_str<br>        lda     #new_line<br>        jsr     print_char<br>        lda     #new_line<br>        jsr     print_char<br>        rts</pre><p>Limitations of this implementation:</p><ul><li>The function only works with fractions &lt; 1.</li><li>Input format “.123” without leading zero.</li></ul><h3>Fraction Processing</h3><p>The fraction processor takes numerator and denominator arguments, converting them into decimals and percentages.</p><pre>fraction_handler:<br>        jsr     input_num_den<br>        jsr     cursor_blink_off<br>        lda     #&lt;den<br>        ldy     #&gt;den<br>        jsr     fp_load_ram_to_fac<br>        lda     #&lt;num<br>        ldy     #&gt;num<br>        jsr     fp_div<br>        ldx     #&lt;n<br>        ldy     #&gt;n<br>        jsr     fp_store_fac_to_ram<br>        lda     #&lt;hundred<br>        ldy     #&gt;hundred<br>        jsr     fp_load_ram_to_fac<br>        lda     #&lt;n<br>        ldy     #&gt;n<br>        jsr     fp_mult<br>        ldx     #&lt;per<br>        ldy     #&gt;per<br>        jsr     fp_store_fac_to_ram<br>        jsr     show_results<br>        rts</pre><p>A decimal is obtained by dividing the numerator by the denominator.<br>Percentages are obtained by multiplying a decimal by 100.</p><h3>Percentage Conversion</h3><p>The percentage handler takes percentage values as input and converts them into fractions and decimals.</p><pre>percent_handler:<br>        jsr     input_percents<br>        lda     #&lt;hundred<br>        ldy     #&gt;hundred<br>        jsr     fp_load_ram_to_fac<br>        lda     #&lt;per<br>        ldy     #&gt;per<br>        jsr     fp_div<br>        ldx     #&lt;n<br>        ldy     #&gt;n<br>        jsr     fp_store_fac_to_ram<br>        lda     #&lt;per<br>        ldy     #&gt;per<br>        jsr     fp_load_ram_to_fac<br>        ldx     #&lt;num<br>        ldy     #&gt;num<br>        jsr     fp_store_fac_to_ram<br>        lda     #&lt;hundred<br>        ldy     #&gt;hundred<br>        jsr     fp_load_ram_to_fac<br>        ldx     #&lt;den<br>        ldy     #&gt;den<br>        jsr     fp_store_fac_to_ram<br>        jsr     show_results<br>        rts</pre><p>A decimal is obtained by dividing a percentage by 100.<br>Normal: numerator percentage entered denominator 100.</p><p>This function has a limitation: it can correct handle only whole percent.</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*10Y7Da0W9afOUZyCHaN6UA.png" /></figure><p>In this journey through the Commodore 64’s mathematical realm, we’ve developed a fraction converter in assembly language. You can find the complete source code for this program [<a href="https://gist.github.com/medvecky/11fda440812e529db431aadfd71c226f">here</a>].</p><p>Here is an example of execution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*QQmgYuC_5vPs-W3foYM8rQ.gif" /></figure><p>The binary file has a size of 3220 bytes.</p><p>While school mathematics may seem basic, it provides an excellent playground for honing assembly programming skills. This project has showcased the creative possibilities that the 80s era and Commodore 64 offer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0AKVAvVhHB9HnyA__U8ZQ.jpeg" /></figure><p>As we continue this exciting journey, I invite you to stay with me for more mathematical adventures in the world of Commodore 64 programming.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1be97c224d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>