<?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 Ansmoner on Medium]]></title>
        <description><![CDATA[Stories by Ansmoner on Medium]]></description>
        <link>https://medium.com/@ansmoner2000?source=rss-15fffe240e76------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fYy0wo7wnpXPKDF7mrBuKA.jpeg</url>
            <title>Stories by Ansmoner on Medium</title>
            <link>https://medium.com/@ansmoner2000?source=rss-15fffe240e76------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 21:24:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ansmoner2000/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[Why Arrays Were Born: Memory, Math, and the Contract That Powers Every Data Structure]]></title>
            <link>https://medium.com/@ansmoner2000/why-arrays-were-born-memory-math-and-the-contract-that-powers-every-data-structure-97ded3f5696d?source=rss-15fffe240e76------2</link>
            <guid isPermaLink="false">https://medium.com/p/97ded3f5696d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Ansmoner]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 01:48:38 GMT</pubDate>
            <atom:updated>2026-04-07T01:48:38.320Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fUMjp9WoXhZAeStz6FwXag.png" /></figure><p>You’ve used arrays since your first week of programming. You index into them, loop over them, pass them around without thinking twice. But have you ever asked — why do they work the way they do? Why does index start at 0? Why can’t you just insert anywhere? Why does going one step past the end corrupt memory silently?</p><p>The answer isn’t in the syntax. It’s in the history.</p><p>Before arrays existed, programmers talked directly to memory — one address at a time, one variable per value, one instruction per operation. The problem they were solving wasn’t just “how do we store a list.” It was: <em>how do we address data uniformly, at any scale, in constant time?</em></p><p>The solution they found is a formalized agreement between the programmer and the memory model. It has a name borrowed from military formations, a formula that hasn’t changed since 1957, and consequences that reach into every data structure you’ll ever study.</p><p>This article traces that story — from raw assembly to the mathematical law that governs all of it.</p><h3>Table of Contents</h3><ol><li><strong>B.C.E. Era</strong> — how programmers managed memory before arrays existed</li><li><strong>Etymology</strong> — why a military word became a computer science term</li><li><strong>The Contiguity Law</strong> — the one rule that makes O(1) access possible</li><li><strong>Vocabulary You Must Own </strong>— the six terms that complete the mental model</li></ol><h3>B.C.E. Era</h3><p>In the early days of computing, the machine didn&#39;t understand &quot;list&quot; or &quot;array.&quot; It only understood one thing: memory.</p><p>Memory is a long row of bytes. Every byte has an address. Think of it as a long strip of numbered drawers — each drawer holds one value, and every drawer has a unique number on it.</p><pre>Address:  1000  | 1001 | 1002 | 1003 | 1004 | ...<br>Value:      85  |   70 |   60 |   90 |   92 | ...</pre><p>The CPU had one job: <em>&quot;Give me the value at this address.&quot;</em> That&#39;s it. No lists. No loops over collections. Just: address in, value out.</p><h3>How programmers wrote code back then</h3><p>In early assembly, to store the grades of 10 students, you declared each one as a separate labeled variable:</p><pre>grade1  DB  85    ; DB = Define Byte, stores a value from 0 to 255<br>grade2  DB  70<br>grade3  DB  60<br>grade4  DB  90<br>grade5  DB  92<br>grade6  DB  78<br>grade7  DB  88<br>grade8  DB  74<br>grade9  DB  95<br>grade10 DB  88</pre><p>Two things to know:</p><ul><li>grade1 is a <strong>label</strong> — a human-readable name that maps to a memory address, so you don&#39;t have to memorize 1000, 1001, etc.</li><li>DB means <strong>Define Byte</strong>, which reserves 1 byte per value (range: 0–255). There&#39;s also DW — <strong>Define Word</strong> — which reserves 2 bytes (range: 0–65,535).</li></ul><p>Every grade is a completely <strong>independent </strong>variable. They might not even sit next to each other in memory. The programmer just named them and hoped for the best.</p><h3>So what&#39;s the problem?</h3><p>Before answering that — imagine the teacher changes to 30 students. You write 30 lines. 100 students? 100 lines. 10,000 students? You already know where this is going.</p><p>Now look at what summing just 10 grades actually looks like:</p><pre>MOV AL, [grade1]   ; AL = 85         (copy grade1 into the AL register)<br>ADD AL, [grade2]   ; AL = 85+70=155  (add grade2 to AL)<br>ADD AL, [grade3]   ; AL = 155+60=215<br>ADD AL, [grade4]   ; AL = 215+90=305<br>ADD AL, [grade5]   ; AL = 305+92=397<br>ADD AL, [grade6]   ; AL = 397+78=475<br>ADD AL, [grade7]   ; AL = 475+88=563<br>ADD AL, [grade8]   ; AL = 563+74=637<br>ADD AL, [grade9]   ; AL = 637+95=732<br>ADD AL, [grade10]  ; AL = 732+88=820</pre><blockquote><em>Quick note: </em><em>AL is a small storage slot that lives </em><strong><em>inside the CPU itself</em></strong><em> — not in main memory. Think of it as the CPU&#39;s scratchpad while it works.</em></blockquote><p>One line per grade. Every line written by hand. This isn&#39;t programming — it&#39;s <strong>manual memory accounting</strong>.</p><h3>Smarter engineers asked a better question</h3><blockquote>&quot;Instead of creating a variable for each element, why not reserve a contiguous block in memory?&quot;</blockquote><p>But first — why does contiguous (side-by-side) matter?</p><p>When data lives at neighboring addresses, the CPU can load a whole <strong>cache line</strong> — typically 64 bytes — in a single operation. Scattered variables destroy this. The CPU has to make a separate trip to memory for each one. Contiguous layout isn&#39;t just cleaner code; it&#39;s <strong>physically faster</strong> at the hardware level.</p><p>So they did this:</p><pre>int *grades = malloc(10 * sizeof(int));  /* reserve space for 10 numbers */</pre><p>Because each int takes 4 bytes on most systems, the next element is always 4 addresses away. The memory now looks like this:</p><pre>Address:  1000 | 1004 | 1008 | 1012 | 1016 | ...<br>Value:      85 |   70 |   60 |   90 |   92 | ...<br>           [0]    [1]    [2]    [3]    [4]</pre><h3>The formula hiding inside every array</h3><p>Think of it like a hotel. The base address is room 100. Every room is the same size. To find a guest at index i, you don&#39;t knock on every door — you go straight to:</p><pre>room = 100 + (i × room_size)</pre><p>Arrays work exactly the same way:</p><h3>Address = Base + (Index × Element Size)</h3><p>That&#39;s it. That&#39;s the entire idea. To read the element at index 2:</p><pre>int third = *(grades + 2);   /* 1000 + (2 × 4) = address 1008 → value 60 */</pre><p>The formula always delivers the right byte in one calculation — no searching, no iteration.</p><h3>But the programmer carried the full burden</h3><p>This worked. But there was no safety net:</p><ul><li>No bounds check</li><li>No length property</li><li>No garbage collection</li></ul><p>If you wrote *(grades + 10) by mistake — index 10 on a 10-element array — the formula still ran. It calculated address 1040 and read whatever was sitting there. Maybe another variable. Maybe the operating system. The code compiled and ran without a single warning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vnXOjas8l34Ne6cuQVlj0g.gif" /></figure><p>This is the origin of <strong>buffer overflow vulnerabilities</strong>. In 2017, <strong>EternalBlue</strong> — a buffer overflow in Windows&#39; SMBv1 protocol, originally developed by the NSA and later leaked — was used to deploy the <strong>WannaCry</strong> ransomware. It infected over 200,000 machines across 150 countries, causing losses estimated at over $4 billion. The root cause traces back to exactly this: walking off the end of an allocation with no guard in place.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FW41-Ao-Cdj4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DW41-Ao-Cdj4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FW41-Ao-Cdj4%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/abaf690432b5abd63dd2b592fe3af083/href">https://medium.com/media/abaf690432b5abd63dd2b592fe3af083/href</a></iframe><p>The core problem wasn&#39;t storing data It was <strong>addressing data uniformly</strong>.</p><p>Engineers needed a contract that said:</p><blockquote>&quot;Give me a base address, a fixed element size, and an index — and I will always find the right byte.&quot;</blockquote><p>That contract is the array. Not magic. A formalized agreement between the programmer and the memory model.</p><pre>grade1   ──┐<br>grade2     │                    <br>grade3     ├──────────────────►  grades[i]<br>...        │<br>grade10  ──┘</pre><p>Ten scattered names collapsed into one structure with one rule. Any index. Any size. Same formula. Always.</p><p>What changed across time isn&#39;t the formula — it never changed. What changed is that higher-level languages starting in the 1950s and 60s began hiding the mechanics. The programmer no longer talked to addresses directly. But underneath every grades[i] in Python, Go, Java, or C — the CPU is still doing exactly this:</p><pre>1000 + (i × 4)</pre><h3><strong>Etymology</strong></h3><p>The word <strong>array</strong> comes from Old French <em>arraier</em> — to arrange, to put in order. Before it was a programming concept, it was a military term. An army <strong>arrayed</strong> in formation meant soldiers placed at known, uniform intervals, organized so that any one of them could be located by position alone.</p><p>The word goes deeper than French. <em>Arraier</em> descended from Vulgar Latin <em>*arredare</em> — to prepare, to put in order — built from the prefix <em>ad-</em> (toward) combined with Proto-Germanic <em>*raidaz</em>, meaning ready, arranged. Every ancestor of this word carries the same idea: <strong>order that exists for the purpose of fast access</strong>.</p><p>The word has always meant the same thing. The data structure just made it precise.</p><h3>The metaphor is the mechanism</h3><p>Picture a Roman legion in formation. Each soldier occupies exactly the same width of ground. The commander needs soldier at position 7 in the front row. He doesn’t start at position 1 and count forward. He calculates:</p><pre>position = front_of_line + (7 × one_soldier_width)</pre><p>He steps directly to that spot. One calculation. No searching.</p><p>Now ask: what if soldiers had random widths — some one meter wide, some three? The commander loses his shortcut. To find position 7 he has to walk the entire line from the beginning, measuring as he goes.</p><p>That second formation has a name too. You’ll meet it in another article. It’s called a <strong>linked list</strong>.</p><p>The array exists precisely because spacing is <strong>fixed and known in advance</strong>. Uniform intervals aren’t just a nice property — they are the entire reason the structure works. Remove uniform spacing and the formula collapses. You no longer have an array. You have something slower.</p><p>This is why the military word fit perfectly when engineers needed a name:</p><ul><li>Uniform intervals → fixed element size</li><li>Addressable by position → base + (index × element size)</li></ul><p>The language and the math were always saying the same thing.</p><h3>Who named it</h3><p>The concept existed before the name. Assembly programmers reserved contiguous blocks and walked them with pointer arithmetic — the formula was already there. But it had no single word.</p><p>In <strong>1957</strong>, <strong>John Backus</strong> and the FORTRAN team at IBM formalized it as a named construct in a high-level language for the first time. They needed a word that captured ordered, uniformly-spaced, and addressable by index. <em>Array</em> — the military word for a formation you can navigate by position — was the precise fit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*XxfW9E_qRtTnjTe5VmLryw.jpeg" /><figcaption>John Backus</figcaption></figure><p>Naming it mattered. Once engineers had a shared word, they had a shared contract. Everyone who wrote grades(i) in FORTRAN knew exactly what the machine was doing underneath: one multiplication, one addition, one memory access. The name compressed the entire mechanism.</p><h3>What the word tells you before you write a line of code</h3><p>The etymology section of most CS courses gets skipped. That’s a mistake, because the word <em>array</em> is doing quiet technical work every time you read it:</p><p>What the word implies What it means in memory Arranged elements live at contiguous addressesUniform intervals every element is the same size Addressable by position any index reaches its target in O(1)</p><p>The word was chosen deliberately because the metaphor <strong>is</strong> the mechanism. Not an analogy for it. Not a way to visualize it. The actual mechanism — uniform spacing, direct addressing by position — is what Roman formations and memory layouts share at a structural level.</p><h3>The Contiguity law</h3><p>One law governs everything about how arrays work:</p><blockquote>All elements must occupy consecutive memory addresses, and all elements must be the same size.</blockquote><p>That’s it. Everything else — the O(1) access, the index formula, the performance guarantees — is a consequence of this one law. Break either condition and the whole thing collapses.</p><h3>Why these two conditions enable O(1) access</h3><p>Before proving it, clarify what O(1) actually means. It doesn’t mean fast. It means <strong>time-independent of input size</strong>. The calculation takes the same number of steps whether the array holds 10 elements or 10 million. That’s the guarantee.</p><p>Given:</p><ul><li>base — the memory address of element [0]</li><li>size — bytes per element (an int32 takes 4 bytes)</li><li>i — the index you want</li></ul><p>The CPU computes:</p><pre>Address(i) = base + (i × size)</pre><p>One multiplication. One addition. Done. Run it for index 0:</p><pre>Address(0) = 1000 + (0 × 4) = 1000   ← 2 operations</pre><p>Run it for index 9,999,999:</p><pre>Address(9999999) = 1000 + (9999999 × 4) = 41000996   ← still 2 operations</pre><p>Same number of steps. Same time. That’s O(1). Not a label — a physical fact about the calculation.</p><h3>Why the law is not optional</h3><p>The two conditions aren’t rules handed down from authority. They’re load-bearing. Remove either one and prove to yourself what breaks.</p><p><strong>What if elements had variable size?</strong></p><p>Suppose your array holds strings of different lengths. Element 0 is 3 bytes, element 1 is 7 bytes, element 2 is 2 bytes. Now try to find element 5. You can’t multiply — you don’t know what to multiply by. The only way to reach element 5 is to start at element 0 and add up the sizes of everything before it. That’s scanning from the beginning every single time.</p><p>That’s O(n). You no longer have an array. You have something slower.</p><p><strong>Contiguity + fixed size isn’t a choice. It’s the proof that the formula works.</strong></p><h3>The four constraints that follow from the law</h3><p>Each constraint below isn’t a rule imposed on you. It’s a mathematical consequence of how the formula is built.</p><p><strong>1. Fixed element size</strong></p><p>The formula multiplies i × size. If size varies per element, the multiplication is undefined. You can&#39;t compute an address without knowing the exact size in advance. This is why arrays are typed — int[], float[], string[]. The type enforces fixed size at the compiler level so the formula stays valid at runtime.</p><p><strong>2. No gaps allowed</strong></p><p>A gap between elements shifts every subsequent address. The formula doesn’t know about the gap — it just adds i × size from base and lands on the wrong byte, silently. No error, no warning. Wrong data. This is also why inserting an element in the middle of an array requires <strong>shifting</strong> every element after it — you&#39;re not creating a gap, you&#39;re closing one before it can exist.</p><p><strong>3. Index starts at 0</strong></p><p>This confuses beginners as a quirk. It’s actually the formula asking for its cleanest form. The first element should have zero offset from base:</p><pre>Address(0) = base + (0 × size) = base   ← clean</pre><p>If indexing started at 1, every single access would carry an extra subtraction:</p><pre>Address(i) = base + ((i - 1) × size)</pre><p>One extra operation per access. Billions of accesses per day across every program ever written. Zero-based indexing isn’t a convention — it’s the formula refusing to carry unnecessary weight.</p><p><strong>4. Static size at allocation</strong></p><p>When you ask for a 10-element array, the operating system finds a free contiguous block of exactly 10 × size bytes and hands it to you. That block has neighbors — other variables, other programs — living immediately beside it in memory.</p><p>If you later need 11 elements, the block cannot simply grow. The memory next to it is already occupied. The OS has to find a new free block of 11 × size bytes somewhere else, copy all 10 existing elements into it, and release the old block. You didn&#39;t extend the array. You relocated it.</p><p>This is the constraint that every dynamic array — Go slices, Python lists, Java’s ArrayList — is built to manage invisibly on your behalf.</p><h3>The hardware agrees</h3><p>The Contiguity Law isn’t just a software contract. The CPU’s prefetcher — the hardware circuit that loads upcoming data before you ask for it — works by predicting what addresses will be needed next. Contiguous layout makes that prediction trivial: if you’re reading index 3, index 4 is exactly size bytes away. The prefetcher loads it in advance, for free.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*f_utW_Pklu-ifmz3VWSNgw.png" /></figure><p>Scatter your data across non-contiguous addresses and the prefetcher goes blind. Every access becomes a cache miss — a round trip to main memory that is orders of magnitude slower than a cache hit. The Contiguity Law is also a <strong>performance contract with the hardware itself</strong>.</p><h3>What the law costs</h3><p>The Contiguity Law gives you O(1) access in exchange for rigidity:</p><ul><li>You must know the size upfront</li><li>You cannot insert without shifting everything after the insertion point</li><li>You cannot grow without relocating the entire block</li></ul><p>Every other data structure you will ever study is, in some sense, a negotiation with this law — trading away some access speed in exchange for flexibility. Linked lists abandon contiguity to allow free insertion. Hash tables add indirection to allow dynamic sizing. Trees sacrifice direct addressing to allow ordered insertion.</p><p>The array is the baseline. It gives you the best possible access time and asks for total commitment in return. Understanding what it demands — and why — is what makes every other data structure make sense.</p><h3>The Vocabulary You Must Own</h3><p>Every field has words that do real technical work. These aren’t definitions to memorize — they’re tools that let you think and speak precisely about what’s actually happening in memory. Own these six terms and you’ll understand array discussions that would otherwise feel opaque.</p><h3>Base Address</h3><p>The memory address of element[0]. The fixed starting point of the entire formula.</p><pre>Address(i) = base + (i × size)<br>             ^^^^<br>             this</pre><p>Every other address in the array is defined relative to this one. Change the base — move the array to a different memory location — and every element moves with it, because they’re all offsets from the same anchor. The base address is the one thing the CPU must know before it can find anything else.</p><h3>Index</h3><p>An <strong>offset multiplier</strong> — not a position number.</p><p>This distinction matters. Natural language counts positions: first, second, third. Arrays count distance from the start: zero bytes away, four bytes away, eight bytes away. That’s why arrays start at 0 — not by convention, not by historical accident, but because the first element is exactly zero bytes from base:</p><pre>Address(0) = base + (0 × size) = base   ← zero offset, clean<br>Address(1) = base + (1 × size)          ← one unit away<br>Address(2) = base + (2 × size)          ← two units away</pre><p>If indexing started at 1, every single access would carry a hidden subtraction: base + ((i-1) × size). One extra operation per access, across every program ever written. The index starts at 0 because it&#39;s the formula asking for its simplest possible form.</p><p>If you’ve used MATLAB, Lua, or R — languages that start at index 1 — this feels unnatural. But those languages are the exception. The formula is the reason the rule exists.</p><h3>Element</h3><p>One <strong>fixed-size unit</strong> stored at a computed address.</p><p>The critical word is <em>fixed</em>. Every element in a single array must be the same type, therefore the same size. An int32 array holds elements of exactly 4 bytes each — every single one of them, no exceptions. This uniformity is what the formula depends on. The moment element sizes differ, i × size becomes undefined — which size do you multiply by?</p><p>This is why arrays are typed. int[], float64[], string[] — the type declaration isn&#39;t just documentation. It&#39;s the compiler enforcing the one constraint that makes the entire structure work.</p><h3>Bounds</h3><p>The valid index range: [0, length-1].</p><p>Everything outside that range is a lie the formula will compute anyway. Give it index -1 or index length, the formula runs, produces an address, and either reads or writes whatever lives there. The array doesn&#39;t know it&#39;s out of bounds. It just follows the math.</p><p>Different languages handle this differently, and your language choice changes the contract:</p><ul><li>C / C++ :- Undefined behavior — compiler does anything, including appearing to work.</li><li>Go :- Runtime panic — program stops immediately with a clear error.</li><li>Java :- ArrayIndexOutOfBoundsException — caught exception, recoverable.</li><li>Python :- IndexError — clear error message, recoverable.</li></ul><p>Undefined behavior in C is the most dangerous. The compiler isn’t required to produce an error, a crash, or even wrong output. The program can appear to work correctly for months and corrupt data silently. This is the formal name for what the BCE Era section called a buffer overflow — the formula ran past the bounds, and nothing stopped it.</p><h3>Stride</h3><p>sizeof(element) — the byte distance between the start of one element and the start of the next.</p><p>In a simple one-dimensional array, stride equals element size. But stride becomes the critical term the moment you work with <strong>2D arrays</strong>.</p><p>A 3×4 grid of int32 values stored flat in memory:</p><pre>Row 0: [10][20][30][40]<br>Row 1: [50][60][70][80]<br>Row 2: [90][11][12][13]</pre><p>In memory, this is one contiguous block:</p><pre>10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 11 | 12 | 13</pre><p>The <strong>column stride</strong> is 4 bytes — one int32. The <strong>row stride</strong> is 4 × 4 = 16 bytes. To move to the next column, add 4. To move to the next row, add 16.</p><p>Here’s where stride becomes a performance concern. If you iterate across rows in the inner loop — moving by 16 bytes each step — you’re jumping past data the CPU already loaded into cache. Every step is a cache miss. Flip the loop order, iterate along columns in the inner loop, and you move by 4 bytes each step — data that’s already sitting in the cache line. Same computation, potentially an order of magnitude faster.</p><p>Stride is the vocabulary that makes that optimization visible.</p><h3>Length vs. Capacity</h3><p>Two numbers that are often equal but mean entirely different things.</p><ul><li><strong>Length</strong> — how many elements are currently stored (slots in use)</li><li><strong>Capacity</strong> — how many elements the allocated block can hold (slots available)</li></ul><p>At creation, they’re often equal. As you append elements, length grows. Capacity stays fixed — until length reaches it.</p><p>When length == capacity, the next append has nowhere to go. The runtime must:</p><ol><li>Find a new contiguous block, typically 2 × capacity bytes</li><li>Copy every existing element into it</li><li>Release the old block</li><li>Append the new element</li></ol><p>That doubling strategy is called <strong>amortized O(1) append</strong>. Any single append might trigger an expensive relocation — but because capacity doubles each time, relocations become exponentially rarer as the array grows. Averaged across all appends, each one costs O(1). It’s one of the most elegant engineering decisions in the entire field.</p><p>This is exactly what Go slices, Python lists, and Java’s ArrayList manage invisibly on your behalf. When you call append() in Go or .append() in Python, you&#39;re not just adding an element — you might be triggering a full relocation. The vocabulary term capacity is where that story begins.</p><h3>How the terms connect</h3><p>These six definitions aren’t independent. They form two contracts:</p><p><strong>The address contract</strong> — how the CPU finds any element in O(1):</p><pre>Address(i) = base + (index × stride)<br>             ^^^^    ^^^^^   ^^^^^^<br>         base addr  offset  element size</pre><p><strong>The safety and growth contract</strong> — what the array promises and what it costs:</p><pre>valid access  →  index ∈ [0, length-1]<br>growth cost   →  triggered when length == capacity</pre><p>Master these terms and you’re not memorizing a glossary. You’re holding the complete mental model of how arrays work — from the formula the CPU executes to the reallocation the runtime hides from you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97ded3f5696d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Concrete to Code: Building a Statistical Analysis Tool in Go]]></title>
            <link>https://medium.com/@ansmoner2000/from-concrete-to-code-building-a-statistical-analysis-tool-in-go-776e6a544978?source=rss-15fffe240e76------2</link>
            <guid isPermaLink="false">https://medium.com/p/776e6a544978</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[who-am-i]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Ansmoner]]></dc:creator>
            <pubDate>Wed, 10 Dec 2025 20:50:59 GMT</pubDate>
            <atom:updated>2025-12-10T20:50:59.435Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xgs5QH3E1_wxkgEzi-5FDQ.jpeg" /></figure><p>As a civil engineer, I spent years with concrete, steel, and loads. Precision was a key; a miscalculation could mean a crack in a beam or worse. Recently, I traded my hard hat for a text editor and started a new journey at 01Edu to become a software engineer. By luck, this career shift hasn’t felt entirely foreign. Whether I am building or writing a function, both of them need to be a problem solver by breaking down the problem into smaller and in the same to be logical step. My latest challenge is to build a (simple) Statistical Analysis Tool using Go. Here is how I approached it, what I learned, and what I can add to be more interactive.</p><ol><li>The Mission</li><li>The Logic: How it works</li><li>The Difference between Mean &amp; Median</li><li>Measuring the Spread</li><li>Challenges and lessons learned</li><li>How can i improve it?</li><li>Conclusion</li></ol><h3>The Mission</h3><p>The assignment was straightforward but tricky: Write a command-line program that reads a file containing a list of numbers (population data) and calculates various statistical metrics:</p><ul><li><strong>Mean</strong> (Average)</li><li><strong>Median</strong> (The middle value)</li><li><strong>Variance</strong> (How spread out the data is)</li><li><strong>Standard Deviation</strong> (The square root of variance)</li><li>I add -outside the assignment- Max and Min and Interquartile Range and Range.</li></ul><p>This tool is essentially a “Simple Calculator” that takes raw data and turns it into meaningful insights -as Engineers always do :)- .</p><h3>The Logic: How it works</h3><p>We start our journey with Go lang so i write my Calculator using it.<br>Here is how i think to do it:-<br>1. Reading File And Store It.</p><p>2. Revise some statistical Concepts from <a href="https://medium.com/u/3e5b058e33dc">Khan Academy Oʻzbek</a>.</p><p>3. Convert those statistacal Concepts to code by break it to smaller blocks</p><ul><li><strong>For Mean &amp; Median</strong> : I think i dont need a logic for it :).</li></ul><p><strong>Mean</strong> = its simply sumition of data set devided by the count.</p><pre>var mean float64<br> sum := 0<br> n := len(data)<br> for _, num := range data {<br>  numConv, err := strconv.Atoi(num)<br>  if err != nil {<br>   fmt.Printf(&quot;Cant convert those data to integers&quot;)<br>  }<br>  sum += numConv<br> }<br> mean = float64(sum) / float64(n)<br> return mean</pre><p><strong>Median</strong> = its the half value for odd numbers and 2 values for even numbers then make mean for them.</p><pre>var median float64<br> var dataConv []float64<br> for _, num := range data {<br>  numConv, err := strconv.Atoi(num)<br>  if err != nil {<br>   fmt.Printf(&quot;Cant convert those data to integers&quot;)<br>  }<br>  dataConv = append(dataConv, float64(numConv))<br> }<br> sort.Float64s(dataConv)<br> if (len(dataConv))%2 == 0 {<br>  first := dataConv[((len(dataConv))/2)-1]<br>  second := dataConv[((len(dataConv)) / 2)]<br>  median = ((first + second) / 2)<br> } else {<br>  median = dataConv[(len(dataConv))/2]<br> }<br> return median</pre><ul><li><strong>For Range: </strong>I<strong> </strong>need to sort data-set first before make any action then access on first Element and last element by find length of data then minus 1 to access last index.</li></ul><pre>var Range int<br> var dataConv []int<br> for _, num := range data {<br>  numConv, err := strconv.Atoi(num)<br>  if err != nil {<br>   fmt.Printf(&quot;Cant convert those data to integers&quot;)<br>  }<br>  dataConv = append(dataConv, numConv)<br> }<br> sort.Ints(dataConv)<br> maxVal := dataConv[len(dataConv)-1]<br> minVal := dataConv[0]<br> Range = maxVal - minVal<br> return Range</pre><ul><li><strong>For InterQuartile : </strong>That is bit tricky one, i think to solve it by effectivly way i need to use median function i create but the first step is sorting data then separate it to 2 slices -arrays- but i vary from odd and even numbers.</li></ul><pre>var iqr int<br> var dataConv []int<br> var q1 int<br> var q3 int<br> n := len(data)<br> half := n / 2<br> for _, num := range data {<br>  numConv, err := strconv.Atoi(num)<br>  if err != nil {<br>   fmt.Printf(&quot;Cant convert those data to integers&quot;)<br>  }<br>  dataConv = append(dataConv, numConv)<br> }<br> sort.Ints(dataConv)<br> if n%2 == 0 {<br>  q1 = MedianInt(dataConv[:half])<br>  q3 = MedianInt(dataConv[half:])<br> } else {<br>  q1 = MedianInt(dataConv[:half])<br>  q3 = MedianInt(dataConv[half+1:])<br> }<br> iqr = q3 - q1<br> return iqr</pre><p>For Even numbers :- I need to take 2 numbers that we extract it in median then put one of them in first quratile and another for third quartile then get median for both then subtract q1 from q3.</p><p>For Odd numbers :- that simple than even, we need to split to 2 arrays and remove median value then make the same above.</p><ul><li><strong>For Variance :-</strong> not tricky as i think , just get mean from above function then make sumution of (num — mean)² then devide the count of data.</li></ul><pre>var variance float64<br> var total float64<br> n := len(data)<br> mean := Mean(data)<br> for _, num := range data {<br>  numConv, err := strconv.Atoi(num)<br>  if err != nil {<br>   fmt.Println(&quot;Can not Convert to number&quot;)<br>  }<br>  diff := math.Pow((mean - float64(numConv)), 2)<br>  total += diff<br> }<br> variance = total / float64(n)<br> return variance</pre><ul><li><strong>For Standard Deviation</strong>:- the simplest one.</li></ul><pre>return math.Sqrt(Variance(data))</pre><p><strong>The Difference between Mean &amp; Median</strong></p><p>The main goal of our Assignment is to know diff between various Statistical Concepts.</p><p>The most basic stats are the Mean and the Median. While they both represent “the middle,” they behave very differently.</p><ul><li><strong>The Mean</strong> is the mathematical average. You sum everything up and divide by the count.</li><li><strong>The Median</strong> is the value standing in the exact center when the data is sorted.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJGxO-64ji5ERqJ237N38g.jpeg" /></figure><p>you will see that mean can affect in bad way with outlier values and that make wrong dicisions if you use mean in wrong study case -e.g. Avarage income of your country- , so the term of <a href="https://en.wikipedia.org/wiki/Average">avarage </a>-in general- can be used to obfuscate the true meaning of data and suggest varying answers to questions based on the averaging method (most frequently arithmetic mean, median, or mode) , So be Careful.</p><h3>Measuring the Spread</h3><p>This is where the engineering side of my brain got excited. In civil engineering, we look for consistency. In statistics, <strong>Variance</strong> and <strong>Standard Deviation</strong> tell us how “inconsistent” or spread out our data is.</p><ul><li><strong>Low Standard Deviation:</strong> The data points are close to the Mean (predictable).</li><li><strong>High Standard Deviation:</strong> The data is spread out over a wider range (volatile).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*5yz_CfQ1uXr_uHjYdKRmXQ.jpeg" /></figure><p>You can see Six Sigma article<a href="https://www.6sigma.us/six-sigma-in-focus/standard-deviation-vs-variance/"> about Standard Deviation vs Variance</a></p><h3><strong>Challenges and lessons learned</strong></h3><ol><li>I learnt How to read file because i think it’s a tricky one for bigenners but i aim to master it by looking in examples and i use “bufio” and know what is stdin, stdout, and stderr and what buffer is and what differant between bufio and io -I will explain in another article-.</li><li>The most challange i face that convert mathmatical concepts to block of codes.</li><li>I am challange myself, dont use any letter of code by using ai and i do io efficinatly.</li><li>Go is very strict about types. You cannot just divide an int by a float. I had to explicitly cast variables using float64() to avoid losing precision during division.</li></ol><h3>How can i improve it?</h3><ol><li>Add Mode to my calculator.</li><li>Make more Error handling.</li><li>Make a detailed text about results such as “The best choise for avarage is:….” or “this is low/high standard deviation”</li><li>Optimization: I convert samething many times in various function i can make it in the top of my program.</li><li>Unit testing: I am doing it in github but using ai :( .</li></ol><h3>Conclusion</h3><p>Building this tool was a great way to practice specific algorithms and get comfortable with Go’s syntax. It’s satisfying to run the program and see a wall of random numbers instantly reduced to a few clean, descriptive statistics.</p><p>I’m still learning, and I know this code can be improved. If you have suggestions on how to optimize the sorting or data handling, I’d love to hear them!</p><p><em>Check out the full source code on my </em><a href="https://github.com/Anasmoner2022/Simple-Statistical-Analysis-Tool.git"><em>GitHub </em></a><em>and follow my journey here on Medium.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=776e6a544978" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>