ItTechGenie-Subject - Arrays & Indexers (Warm-up + 10 Questions)

C# Question Bank

Arrays & Indexers | Q0 Warm‑up (Show/Hide Answer) + Q1–Q10 Scenario Questions (5 Moderate + 5 Complex) — With Answers

Instruction: Full boilerplate is visible by default. Students implement ONLY members marked // ✅ TODO.
Answers: Q0 and Q1–Q10 include answers (logic + code) behind Show/Hide Answer.
Warm‑up: 1 (Q0) Moderate: 5 (Q1–Q5) Complex: 5 (Q6–Q10) Sample Inputs: spaces + quotes + unicode α/β + emoji ✅ + special chars
0

Warm‑up: Arrays vs List vs Dictionary vs Indexer (with answer)

ArraysList<T>DictionaryIndexersWarm-up

Warm‑up (with answer): You have a product catalog loaded once at startup and used for fast lookups. Decide when to use: - array T[] - List<T> - Dictionary<TKey,TValue> - C# Indexer You must provide a short explanation + a tiny code snippet that demonstrates an indexer usage.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Arrays + Indexers scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                                     // Console
using System.Collections.Generic;                                    // Dictionary

namespace ItTechGenie.M1.ArraysIndexers.WarmUp
{
    public class Catalog
    {
        private readonly Dictionary<string, string> _bySku =            // fast lookup map
            new(StringComparer.OrdinalIgnoreCase);

        // ✅ TODO: Student must implement only this indexer
        public string this[string sku]                                 // indexer: Catalog["SKU-001"]
        {
            get
            {
                // TODO: return product line by sku; if not found return "NOT_FOUND"
                throw new NotImplementedException();
            }
        }

        public void Add(string sku, string line)                        // add entry
        {
            _bySku[sku] = line;                                         // insert/replace
        }
    }

    internal class Program
    {
        static void Main()
        {
            var c = new Catalog();                                      // create catalog
            c.Add("SKU-001", "SKU-001 "Pen Blue" ₹10 ✅");            // add line
            c.Add("SKU-α12", "SKU-α12 "Note Book" ₹45 !@#");          // add line

            Console.WriteLine(c["SKU-α12"]);                             // use indexer
        }
    }
}

Warm‑up Answer (Concept + Code)

Guideline: - Use T[] when size is fixed and you want fastest indexed access (O(1)) and minimal overhead. - Use List<T> when size can grow/shrink; still O(1) index access but resizing cost. - Use Dictionary<TKey,TValue> for key-based lookup (avg O(1) by key). - Use Indexer to provide "array-like" access syntax on your own type, often wrapping Dictionary/array. In this warm-up, Catalog exposes a Dictionary via an indexer so consumers can call c["SKU-α12"].

public string this[string sku]
{
    get
    {
        sku = (sku ?? "").Trim();                                      // normalize
        if (sku.Length == 0) return "NOT_FOUND";                       // empty key
        return _bySku.TryGetValue(sku, out var line) ? line : "NOT_FOUND"; // lookup
    }
}
1

Max Price Finder — Parse Input into Array

ArraysParsingLoopingModerate

Scenario: You receive a single CSV line of product prices and must find the maximum price. Prices may contain spaces and special markers like '₹' and '✅'. Implement: - PriceAnalyzer.MaxPrice(string csv) -> decimal Rules: - Parse safely (ignore empty tokens) - Accept tokens like " ₹45 " or "45✅" or "₹30!@#" - Use array or list internally but final algorithm should use array scanning ✅ Students implement ONLY the TODO method.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Arrays + Indexers scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                                     // Console
using System.Globalization;                                           // NumberStyles

namespace ItTechGenie.M1.ArraysIndexers.Q1
{
    public static class PriceAnalyzer
    {
        // ✅ TODO: Student must implement only this method
        public static decimal MaxPrice(string csv)
        {
            // TODO:
            // - split by comma
            // - clean token: keep digits and '.' only (optional leading '-')
            // - parse decimal using invariant culture
            // - return max; if none => 0
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            string csv = " ₹10,  45✅ , ₹30!@#,  ,  12 ,  90 \"special\" ✅ ";
            Console.WriteLine(PriceAnalyzer.MaxPrice(csv));            // expected 90
        }
    }
}

Answer (Logic + Code)

Split, sanitize each token to numeric characters, parse to decimal, track max across the array.

public static decimal MaxPrice(string csv)
{
    if (csv == null) throw new ArgumentNullException(nameof(csv));

    string[] parts = csv.Split(',');                                  // split into tokens
    decimal max = 0m;                                                 // default max
    bool found = false;                                               // to handle all-empty case

    for (int i = 0; i < parts.Length; i++)                            // array scan
    {
        string token = (parts[i] ?? "").Trim();                       // trim spaces
        if (token.Length == 0) continue;                              // skip empty

        // keep digits, optional '.' and optional leading '-'
        var buf = new System.Text.StringBuilder();                    // build numeric string
        for (int c = 0; c < token.Length; c++)                        // scan characters
        {
            char ch = token[c];
            if (char.IsDigit(ch) || ch == '.') buf.Append(ch);        // keep number chars
            else if (ch == '-' && buf.Length == 0) buf.Append(ch);    // allow leading '-'
        }

        if (buf.Length == 0) continue;                                // nothing numeric
        if (decimal.TryParse(buf.ToString(), NumberStyles.Number, CultureInfo.InvariantCulture, out var val))
        {
            if (!found || val > max) max = val;                       // update max
            found = true;                                             // mark found
        }
    }
    return found ? max : 0m;                                          // return max or 0
}
2

Shipment Slot Rotation — Rotate Array Right

ArraysRotationIn-placeModerate

Scenario: A courier system stores today's delivery slot IDs in an array and needs to rotate right by K when a late-night re-planning happens. Implement: - SlotPlanner.RotateRight(int[] slots, int k) -> void (in-place) Rules: - Handle k > n - Use reverse approach (reverse whole, reverse parts) for O(1) extra space ✅ Students implement ONLY the TODO method.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Arrays + Indexers scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                                     // Console

namespace ItTechGenie.M1.ArraysIndexers.Q2
{
    public static class SlotPlanner
    {
        // ✅ TODO: Student must implement only this method
        public static void RotateRight(int[] slots, int k)
        {
            // TODO:
            // - normalize k: k %= n
            // - reverse(0,n-1), reverse(0,k-1), reverse(k,n-1)
            throw new NotImplementedException();
        }

        private static void Reverse(int[] a, int l, int r)             // helper reverse
        {
            while (l < r)                                              // two-pointer swap
            {
                (a[l], a[r]) = (a[r], a[l]);                           // tuple swap
                l++; r--;                                              // move inward
            }
        }
    }

    internal class Program
    {
        static void Main()
        {
            int[] s = { 101, 102, 103, 104, 105 };
            SlotPlanner.RotateRight(s, 2);
            Console.WriteLine(string.Join(", ", s));                   // expected: 104, 105, 101, 102, 103
        }
    }
}

Answer (Logic + Code)

Use 3-reverse technique: reverse whole array, reverse first k, reverse rest.

public static void RotateRight(int[] slots, int k)
{
    if (slots == null) throw new ArgumentNullException(nameof(slots));
    int n = slots.Length;                                             // length
    if (n == 0) return;                                               // nothing to rotate

    k %= n;                                                           // normalize k
    if (k < 0) k += n;                                                // handle negative k

    Reverse(slots, 0, n - 1);                                         // reverse all
    Reverse(slots, 0, k - 1);                                         // reverse first part
    Reverse(slots, k, n - 1);                                         // reverse remaining part
}
3

Coupon Code Duplicate Detector — First Duplicate

ArraysHashingDuplicatesModerate

Scenario: Coupon codes are numeric IDs in the range 0..9999. Given an array of coupon IDs, find the first duplicate encountered scanning left-to-right. Implement: - CouponAudit.FirstDuplicate(int[] ids) -> int (duplicate) or -1 Rules: - Use a bool[] seen of size 10000 (fast) - Return first duplicate by scan order ✅ Students implement ONLY the TODO method.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Arrays + Indexers scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                                     // Console

namespace ItTechGenie.M1.ArraysIndexers.Q3
{
    public static class CouponAudit
    {
        // ✅ TODO: Student must implement only this method
        public static int FirstDuplicate(int[] ids)
        {
            // TODO:
            // - bool[] seen = new bool[10000]
            // - scan array:
            //   if seen[id] => return id
            //   else seen[id]=true
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            int[] ids = { 12, 9999, 7, 12, 0, 7 };
            Console.WriteLine(CouponAudit.FirstDuplicate(ids));        // expected 12
        }
    }
}

Answer (Logic + Code)

Range-limited duplicates: bool[] seen. First time you see an already-seen id => duplicate.

public static int FirstDuplicate(int[] ids)
{
    if (ids == null) throw new ArgumentNullException(nameof(ids));
    var seen = new bool[10000];                                       // range 0..9999

    for (int i = 0; i < ids.Length; i++)                              // scan
    {
        int id = ids[i];                                              // current id
        if (id < 0 || id >= seen.Length) continue;                    // skip out-of-range
        if (seen[id]) return id;                                      // duplicate found
        seen[id] = true;                                              // mark seen
    }
    return -1;                                                        // no duplicates
}
4

Cinema Seat Map — 2D Array Availability Count

2D ArraysLoopsMatrixModerate

Scenario: A cinema seat map is stored as a 2D array of chars: 'O' = available, 'X' = booked. Count available seats for a given row range. Implement: - SeatMap.CountAvailable(char[,] map, int rowStart, int rowEnd) -> int Rules: - Inclusive row range - Validate boundaries ✅ Students implement ONLY the TODO method.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Arrays + Indexers scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                                     // Console

namespace ItTechGenie.M1.ArraysIndexers.Q4
{
    public static class SeatMap
    {
        // ✅ TODO: Student must implement only this method
        public static int CountAvailable(char[,] map, int rowStart, int rowEnd)
        {
            // TODO:
            // - validate map and bounds
            // - loop rows rowStart..rowEnd
            // - loop columns 0..cols-1
            // - count 'O'
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            char[,] map =
            {
                { 'O','X','O','O' },
                { 'X','X','O','O' },
                { 'O','O','X','O' }
            };

            Console.WriteLine(SeatMap.CountAvailable(map, 0, 1));      // expected 5
        }
    }
}

Answer (Logic + Code)

Iterate 2D array subset: for r in range, for c in cols, count 'O'.

public static int CountAvailable(char[,] map, int rowStart, int rowEnd)
{
    if (map == null) throw new ArgumentNullException(nameof(map));
    int rows = map.GetLength(0);                                      // number of rows
    int cols = map.GetLength(1);                                      // number of columns

    rowStart = Math.Max(0, rowStart);                                 // clamp start
    rowEnd = Math.Min(rows - 1, rowEnd);                              // clamp end
    if (rowStart > rowEnd) return 0;                                  // invalid range

    int count = 0;                                                    // availability counter
    for (int r = rowStart; r <= rowEnd; r++)                          // row loop
        for (int c = 0; c < cols; c++)                                // col loop
            if (map[r, c] == 'O') count++;                             // count available

    return count;                                                     // result
}
5

Warehouse Bin Indexer — Safe Array Access via Indexer

IndexersArraysEncapsulationModerate

Scenario: A warehouse maintains fixed bins (array) for a zone. Expose safe access using an indexer with validation + trimming labels. Implement: - BinZone this[int index] getter/setter Rules: - If index invalid => throw IndexOutOfRangeException - When setting, trim string and allow empty as "<EMPTY>" ✅ Students implement ONLY the TODO members.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Arrays + Indexers scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                                     // Console

namespace ItTechGenie.M1.ArraysIndexers.Q5
{
    public class BinZone
    {
        private readonly string[] _bins;                               // fixed bins array

        public BinZone(int size)
        {
            _bins = new string[size];                                 // allocate fixed array
        }

        // ✅ TODO: Student must implement only this indexer
        public string this[int index]
        {
            get
            {
                // TODO: validate index and return value (or "<EMPTY>")
                throw new NotImplementedException();
            }
            set
            {
                // TODO: validate index; trim; store "<EMPTY>" when value is null/empty
                throw new NotImplementedException();
            }
        }
    }

    internal class Program
    {
        static void Main()
        {
            var z = new BinZone(4);                                    // 4 bins
            z[1] = "  Box \"Fragile\" ✅ ";                        // set with spaces
            z[3] = "  α/β - Item !@# ";                                 // unicode + special

            Console.WriteLine(z[1]);                                   // expected: Box "Fragile" ✅
            Console.WriteLine(z[2]);                                   // expected: <EMPTY>
        }
    }
}

Answer (Logic + Code)

Wrap array with an indexer; validate bounds; normalize stored strings; return <EMPTY> when not set.

public string this[int index]
{
    get
    {
        if (index < 0 || index >= _bins.Length)                        // bounds check
            throw new IndexOutOfRangeException();                      // invalid access

        return string.IsNullOrWhiteSpace(_bins[index])                 // if null/empty
            ? "<EMPTY>"                                                // return placeholder
            : _bins[index];                                            // return stored
    }
    set
    {
        if (index < 0 || index >= _bins.Length)                        // bounds check
            throw new IndexOutOfRangeException();                      // invalid access

        var v = (value ?? "").Trim();                                  // normalize
        _bins[index] = v.Length == 0 ? "<EMPTY>" : v;                  // store normalized
    }
}
6

Monthly Sales Dashboard — Jagged Array Best Week

Jagged ArraysAggregationEdge casesComplex

Scenario: Sales per week vary by region. You store them as a jagged array: int[][] sales = { region0Weeks[], region1Weeks[], ... }. Find the region index with the maximum total sales. Implement: - SalesDash.BestRegion(int[][] sales) -> int Rules: - Null/empty region arrays should be treated as 0 - Return first region if tie ✅ Students implement ONLY the TODO method.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Arrays + Indexers scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                                     // Console

namespace ItTechGenie.M1.ArraysIndexers.Q6
{
    public static class SalesDash
    {
        // ✅ TODO: Student must implement only this method
        public static int BestRegion(int[][] sales)
        {
            // TODO:
            // - validate
            // - compute sum for each region
            // - track maxSum and bestIndex (tie -> keep first)
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            int[][] sales =
            {
                new []{10,20,5},
                new []{15,15,15,1},
                Array.Empty<int>()
            };

            Console.WriteLine(SalesDash.BestRegion(sales));            // expected 1 (46 vs 35)
        }
    }
}

Answer (Logic + Code)

Scan each region array, sum elements, track maximum total; handle null/empty as 0.

public static int BestRegion(int[][] sales)
{
    if (sales == null) throw new ArgumentNullException(nameof(sales));

    int bestIdx = -1;                                                 // best region index
    int bestSum = int.MinValue;                                       // best sum

    for (int r = 0; r < sales.Length; r++)                             // region loop
    {
        int sum = 0;                                                  // region sum
        var arr = sales[r];                                           // region weeks
        if (arr != null)                                              // null-safe
            for (int i = 0; i < arr.Length; i++) sum += arr[i];       // sum weeks

        if (bestIdx == -1 || sum > bestSum)                           // better found
        {
            bestIdx = r;                                              // update best
            bestSum = sum;
        }
    }
    return bestIdx;                                                   // return best region
}
7

Telemetry Sparse Array — Indexer over Dictionary

IndexersSparse arraysDictionaryComplex

Scenario: You store telemetry readings by minute index (0..1,000,000). Most minutes are missing. Implement a sparse array wrapper using an indexer. Implement: - TelemetryBuffer this[int minute] get/set Rules: - If value not present => return 0 - Setting 0 should remove key (to keep sparse) - Validate minute range 0..1_000_000 ✅ Students implement ONLY the TODO members.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Arrays + Indexers scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                                     // Console
using System.Collections.Generic;                                    // Dictionary

namespace ItTechGenie.M1.ArraysIndexers.Q7
{
    public class TelemetryBuffer
    {
        private readonly Dictionary<int, int> _data = new();           // sparse store

        // ✅ TODO: Student must implement only this indexer
        public int this[int minute]
        {
            get
            {
                // TODO:
                // - validate minute
                // - return value if exists else 0
                throw new NotImplementedException();
            }
            set
            {
                // TODO:
                // - validate minute
                // - if value==0 => remove key (sparse)
                // - else store/overwrite
                throw new NotImplementedException();
            }
        }

        private static void Validate(int minute)                       // helper validation
        {
            if (minute < 0 || minute > 1_000_000)                      // range check
                throw new ArgumentOutOfRangeException(nameof(minute)); // invalid minute
        }
    }

    internal class Program
    {
        static void Main()
        {
            var t = new TelemetryBuffer();
            t[15] = 100;
            t[999_999] = 5;

            t[15] = 0;                                                 // remove

            Console.WriteLine(t[15]);                                  // expected 0
            Console.WriteLine(t[999_999]);                              // expected 5
        }
    }
}

Answer (Logic + Code)

Dictionary-backed indexer behaves like sparse array: return 0 when missing, remove when setting 0.

public int this[int minute]
{
    get
    {
        Validate(minute);                                              // ensure valid
        return _data.TryGetValue(minute, out var v) ? v : 0;           // missing => 0
    }
    set
    {
        Validate(minute);                                              // ensure valid
        if (value == 0) _data.Remove(minute);                          // keep sparse
        else _data[minute] = value;                                    // store reading
    }
}
8

Support Chat Circular Buffer — Array + Indexer

ArraysCircular bufferIndexersComplex

Scenario: Support system stores the last N chat messages (fixed). Implement a circular buffer using an array and provide an indexer: buffer[0] = oldest, buffer[Count-1] = newest. Implement: - Add(string msg) - this[int logicalIndex] getter Rules: - Use array storage only - Normalize message: trim; store "<EMPTY>" if blank - Indexer must map logical index to internal array index correctly ✅ Students implement ONLY TODO members.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Arrays + Indexers scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                                     // Console

namespace ItTechGenie.M1.ArraysIndexers.Q8
{
    public class ChatRing
    {
        private readonly string[] _buf;                                // fixed array buffer
        private int _start = 0;                                        // points to oldest
        private int _count = 0;                                        // number of items

        public ChatRing(int size)
        {
            _buf = new string[size];                                   // allocate array
        }

        public int Count => _count;                                    // expose count

        // ✅ TODO: Student must implement only this method
        public void Add(string msg)
        {
            // TODO:
            // - normalize msg (trim or <EMPTY>)
            // - if count < size: place at (start+count)%size and increment count
            // - else overwrite oldest at start, then start = (start+1)%size
            throw new NotImplementedException();
        }

        // ✅ TODO: Student must implement only this indexer
        public string this[int logicalIndex]
        {
            get
            {
                // TODO:
                // - validate logicalIndex 0..count-1
                // - map to physical index: (start + logicalIndex) % size
                // - return stored string
                throw new NotImplementedException();
            }
        }
    }

    internal class Program
    {
        static void Main()
        {
            var r = new ChatRing(3);
            r.Add("  Hi ✅ ");
            r.Add(" \"Reset\" password !@# ");
            r.Add(" α/β check ");
            r.Add(" 4th message overwrites oldest ✅ ");

            Console.WriteLine(r[0]);                                   // expected: "Reset" password !@# (oldest after overwrite)
            Console.WriteLine(r[2]);                                   // expected: 4th message overwrites oldest ✅ (newest)
        }
    }
}

Answer (Logic + Code)

Classic ring buffer: store in array; maintain start (oldest) and count; indexer maps logical->physical via modulo.

public void Add(string msg)
{
    msg = (msg ?? "").Trim();                                          // normalize
    if (msg.Length == 0) msg = "<EMPTY>";                              // replace empty

    int size = _buf.Length;                                            // capacity

    if (_count < size)                                                 // still space
    {
        int idx = (_start + _count) % size;                            // append position
        _buf[idx] = msg;                                               // store message
        _count++;                                                      // increase count
    }
    else                                                                // full -> overwrite oldest
    {
        _buf[_start] = msg;                                            // overwrite oldest slot
        _start = (_start + 1) % size;                                  // advance oldest pointer
    }
}

public string this[int logicalIndex]
{
    get
    {
        if (logicalIndex < 0 || logicalIndex >= _count)                // bounds check
            throw new IndexOutOfRangeException();                      // invalid access

        int size = _buf.Length;                                        // capacity
        int physical = (_start + logicalIndex) % size;                 // map index
        return _buf[physical];                                         // return message
    }
}
9

Heatmap Smoothing — 2D Array Neighborhood Average

2D ArraysMathBoundsComplex

Scenario: A heatmap (int[,]) stores footfall counts. For a given cell (r,c), compute the average of its valid 8-neighbors + itself. Implement: - Heatmap.Avg3x3(int[,] map, int r, int c) -> double Rules: - Only include valid neighbors within bounds - Return average as double with decimal - Must not allocate extra arrays (just loops) ✅ Students implement ONLY the TODO method.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Arrays + Indexers scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                                     // Console

namespace ItTechGenie.M1.ArraysIndexers.Q9
{
    public static class Heatmap
    {
        // ✅ TODO: Student must implement only this method
        public static double Avg3x3(int[,] map, int r, int c)
        {
            // TODO:
            // - validate bounds
            // - loop dr=-1..1, dc=-1..1
            // - if in bounds => add to sum and count
            // - return sum/(double)count
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            int[,] m =
            {
                {1,2,3},
                {4,5,6},
                {7,8,9}
            };

            Console.WriteLine(Heatmap.Avg3x3(m, 0, 0));                // expected (1+2+4+5)/4 = 3.0
        }
    }
}

Answer (Logic + Code)

Corner cell has fewer neighbors. Loop over 3x3 offsets, include only in-bounds cells in sum/count.

public static double Avg3x3(int[,] map, int r, int c)
{
    if (map == null) throw new ArgumentNullException(nameof(map));
    int rows = map.GetLength(0);
    int cols = map.GetLength(1);

    if (r < 0 || r >= rows || c < 0 || c >= cols)
        throw new ArgumentOutOfRangeException("Cell out of bounds");

    long sum = 0;                                                     // use long to avoid overflow
    int count = 0;

    for (int dr = -1; dr <= 1; dr++)                                  // neighbor row offset
    for (int dc = -1; dc <= 1; dc++)                                  // neighbor col offset
    {
        int rr = r + dr;                                              // candidate row
        int cc = c + dc;                                              // candidate col
        if (rr >= 0 && rr < rows && cc >= 0 && cc < cols)             // bounds check
        {
            sum += map[rr, cc];                                       // add value
            count++;                                                  // increase count
        }
    }
    return sum / (double)count;                                       // compute average
}
10

Inventory Matrix — Multi-Parameter Indexer [SKU, Warehouse]

Indexers2D ArraysMappingComplex

Scenario: A company has a small fixed set of SKUs and warehouses. Store stock as a 2D array stock[skuIndex, whIndex]. Expose a multi-parameter indexer so code can call: inv["SKU-001", "WH-α"]. Implement: - Map SKU->row index, Warehouse->col index - Indexer get/set uses underlying int[,] array Rules: - Unknown keys => throw KeyNotFoundException - Setting negative stock => throw ArgumentOutOfRangeException ✅ Students implement ONLY TODO members.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Arrays + Indexers scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                                     // Console
using System.Collections.Generic;                                    // Dictionary

namespace ItTechGenie.M1.ArraysIndexers.Q10
{
    public class InventoryMatrix
    {
        private readonly Dictionary<string, int> _skuRow = new(StringComparer.OrdinalIgnoreCase); // sku->row
        private readonly Dictionary<string, int> _whCol  = new(StringComparer.OrdinalIgnoreCase); // wh->col
        private readonly int[,] _stock;                                  // 2D stock array

        public InventoryMatrix(string[] skus, string[] warehouses)
        {
            for (int i = 0; i < skus.Length; i++) _skuRow[skus[i].Trim()] = i;         // map rows
            for (int j = 0; j < warehouses.Length; j++) _whCol[warehouses[j].Trim()] = j; // map cols
            _stock = new int[skus.Length, warehouses.Length];                            // allocate 2D array
        }

        // ✅ TODO: Student must implement only this multi-parameter indexer
        public int this[string sku, string warehouse]
        {
            get
            {
                // TODO:
                // - resolve row/col using dictionaries
                // - return _stock[row,col]
                throw new NotImplementedException();
            }
            set
            {
                // TODO:
                // - validate value >= 0
                // - resolve row/col; set _stock[row,col] = value
                throw new NotImplementedException();
            }
        }

        // helper to resolve indices
        private (int r, int c) Resolve(string sku, string wh)
        {
            sku = (sku ?? "").Trim();                                    // normalize sku
            wh = (wh ?? "").Trim();                                      // normalize warehouse

            if (!_skuRow.TryGetValue(sku, out var r))                     // sku exists?
                throw new KeyNotFoundException($"Unknown SKU: {sku}");

            if (!_whCol.TryGetValue(wh, out var c))                       // wh exists?
                throw new KeyNotFoundException($"Unknown WH: {wh}");

            return (r, c);                                                // return indices
        }
    }

    internal class Program
    {
        static void Main()
        {
            var inv = new InventoryMatrix(
                new[] { "SKU-001", "SKU-α12 ✅" },
                new[] { "WH-A", "WH-α", "WH-β !@#" }
            );

            inv["SKU-001", "WH-α"] = 10;                                  // set stock
            inv["SKU-α12 ✅", "WH-A"] = 5;                                 // set stock

            Console.WriteLine(inv["SKU-001", "WH-α"]);                     // expected 10
            Console.WriteLine(inv["SKU-α12 ✅", "WH-β !@#"]);               // expected 0 (default)
        }
    }
}

Answer (Logic + Code)

Use dictionaries to map keys -> indices and store values in int[,] array. Multi-parameter indexer calls Resolve().

public int this[string sku, string warehouse]
{
    get
    {
        var (r, c) = Resolve(sku, warehouse);                            // resolve indices
        return _stock[r, c];                                            // read from 2D array
    }
    set
    {
        if (value < 0) throw new ArgumentOutOfRangeException(nameof(value)); // invalid stock
        var (r, c) = Resolve(sku, warehouse);                            // resolve indices
        _stock[r, c] = value;                                           // write to 2D array
    }
}