COMP1010 Week 9

Administrative Announcements and Assessment Guidelines

  • Academic Calendar and Recess:

    • Week 99 of COMP1010 marks the return from the teaching recess.
    • The teaching recess constitutes a break in formal teaching activities rather than an assessment holiday.
  • Skills Lab Scheduling and Relocation:

    • General inquiries regarding the Skills Lab are addressed within the pinned "Skills Lab FAQ" announcement.
    • A frequent student query concerns inability to attend registered laboratory classes (e.g., attending a Friday session instead).
    • Course instructors lack administrative authority to reallocate students between registered timetable classes.
  • Major Assignment Specifications:

    • Submission deadline: Week 99 on Thursday.
    • Assignment specifications originally mentioned recursive data structures because in prior iterations of the curriculum, recursive data structures were taught earlier, and the assignment was due around Week 1111 or Week 1212.
    • Because the current scheduling places the assignment due date before recursive data structures have been fully taught, recursive data structures are strictly not required in the major assignment submission.
    • Students who have already implemented recursive data structures will not be penalized or marked down; that specific component will simply not be assessed.
    • Eligible students may apply for a standard 3-day3\text{-day} short extension through the student portal.
  • Skills Lab Memory Diagram Feedback and Retake Policy:

    • All memory diagram questions from the first attempt have been graded, and marks have been updated in student totals.
    • Due to schedule constraints, formal review sessions could not occur between attempts; however, 33 to 55 review sessions are scheduled to allow students to inspect their memory diagram grading and request adjustments if grading discrepancies exist.
    • A dedicated practice project (rather than a quiz) has been released containing graduated difficulty tiers: Pass level, Credit level, Distinction level, and High Distinction level.
    • The second attempt is entirely optional: students satisfied with their first attempt mark (e.g., receiving 9595 out of 100100) are under no obligation to sit the Week 99 second attempt, though any student retains the right to retake the exam to increase their mark (e.g., from 9595 to 100100).

Foundations: Concept Dependencies and Expression Evaluation

  • Interconnected Nature of Programming Concepts:

    • Difficulties encountered in advanced programming topics often stem not from the target topic itself, but from cumulative knowledge gaps in prerequisite fundamentals.
    • Failure in modular assessments (such as writing functions) typically traces back to unaddressed misunderstandings in variable types, operators, conditionals, or iterative loops studied in prerequisite units such as COMP1000.
    • Automated feedback platforms such as CodeRunner and CodingBat serve to identify and bridge these latent conceptual gaps.
  • Integer Division and Implicit Upcasting:

    • Consider the task of defining a function that accepts an integer parameter nn and returns half its value as a double-precision floating-point number.
    • Expected input-output mappings:
    • Input 10→10 \rightarrow Output 5.05.0
    • Input 9→9 \rightarrow Output 4.54.5
    • Input 179→179 \rightarrow Output 864.5864.5
    • Common naive implementation:
    • return n / 2;
    • Failure mechanism:
    • This code does not trigger a compiler type error; it generates a logical error.
    • The variable nn is of type int (4 bytes4\,\text{bytes}).
    • The literal 22 is also of type int (as opposed to 2.02.0).
    • Evaluating an expression of the form int/int\text{int} / \text{int} performs integer truncation, returning an int result (e.g., 9/29 / 2 evaluates to the integer 44).
    • In Java, returning an int from a method with a double return type is syntactically valid due to automatic widening (upcasting), converting 44 to 4.04.0 and 864864 to 864.0864.0.
    • Conversely, returning a double when an int is expected is illegal without explicit narrowing.
    • Rectifying the logical error:
    • Explicitly cast the operand to double: return (double) n / 2;
    • Alternatively, divide by a double literal: return n / 2.0;
    • In both approaches, the expression evaluates as double/int\text{double} / \text{int} or int/double\text{int} / \text{double}, producing an accurate double expression.

Composition and Object Memory Models

  • Java Identifier Constraints:

    • Package names in Java cannot begin with a numeric digit (e.g., naming a package starting with a digit causes a compilation syntax error).
  • Recap of Class Composition:

    • Composition represents a "has-a" relationship where an outer class encapsulates instances or references of other classes.
    • The Point class represents a 2D coordinate:
    • Instance variables: int x, int y.
    • Parameterized constructor: copies incoming arguments to internal fields.
    • toString() method: formats output as (x, y) (e.g., (2, 5) or (1, 7)).
    • The Line class represents a line segment connecting two points:
    • Instance variables: Point start, Point end.
    • Constructor: takes two Point objects and performs reference copies into start and end.
    • toString() method: concatenates text with start and end, which automatically invokes the Point.toString() method implicitly on both references.
  • References vs. Instances in Memory Diagrams:

    • Instance: A heap-allocated memory block containing the actual instance variables defined by the class, created via the new keyword. In memory diagrams, instances have incoming arrows.
    • Reference: An identifier or variable that stores the memory address of an instance. In memory diagrams, references have outgoing arrows.
    • Object sizing: The physical memory allocated to an instance is determined directly by the number and primitive data types of its declared instance variables.
    • Structural rules for reference arrows:
    • A reference can point to at most one instance (a single reference having multiple outgoing arrows to distinct instances is invalid).
    • Multiple references can point to the identical instance (multiple incoming arrows to a single instance is valid and common).
    • Independent object graphs can coexist without cross-references.
    • Credit-level memory analysis for line composition (Line line = new Line(p1, p2);):
    • Point references: p1, p2, line.start, line.end (44 references).
    • Line references: line (11 reference).
    • Total references: 55 references (55 outgoing arrows).
    • Total instances: 11 Line instance and 22 Point instances (33 instances with incoming arrows).
    • Online visualization tooling is transitioning from Python Tutor to from0.dev.

Conceptual Introduction to Recursive Data Structures

  • Pedagogical Progression in Computing:

    • Direct workplace usage of raw manual linked nodes is rare; however, they form the foundational stepping stone for advanced computer science architectures:     Linked Lists (COMP1010)→Trees / Binary Trees→Graphs (COMP2010 / COMP3010)\text{Linked Lists (COMP1010)} \rightarrow \text{Trees / Binary Trees} \rightarrow \text{Graphs (COMP2010 / COMP3010)}
    • Graph structures underpin social networking algorithms, artificial intelligence models, cloud platforms, and large-scale recommendation systems.
    • Understanding graphs requires mastery of trees, which in turn requires mastery of linked lists.
  • Defining "Recursive" in Object Composition:

    • A class is recursive if it contains an instance variable that references an object of the same class type.
    • Example: A Person class modeling genealogical data:
    • Attributes: String name, Date dateOfBirth, derived age.
    • Parent relationships: Mother and father are themselves of type Person.
    • Erroneous colloquial definition: An instance of Person contains two other Person objects inside itself.
    • Precise computer science definition: An instance of Person holds references to two other Person instances.
  • Anatomy of a Node:

    • Payload: The substantive information being stored. While introductory examples use int data, a payload can consist of strings, medical records, match configurations, or arbitrary complex objects.
    • Pointer / Link: A reference attribute conventionally declared as Node next, pointing to another node of the exact same type.
  • Physical Memory Architecture: Arrays vs. Linked Lists:

    • Primitive memory sizing in Java:
    • byte: 1 byte1\,\text{byte}
    • short: 2 bytes2\,\text{bytes}
    • int: 4 bytes4\,\text{bytes}
    • double: 8 bytes8\,\text{bytes}
    • boolean: 1 byte1\,\text{byte} individually, though arrays of booleans employ specialized bit-packing.
    • Array Memory Requirements:
    • Arrays require contiguous blocks of system memory.
    • An array of 66 integers requires 6×4=24 bytes6 \times 4 = 24\,\text{bytes} of uninterrupted contiguous space.
    • An array of 10,00010{,}000 integers requires 40,000 bytes40{,}000\,\text{bytes} (approximately 40 KB40\,\text{KB}) of contiguous memory.
    • Historical and Economic Context of Hardware RAM:
    • Memory previously cost approximately $200/MB\$200/\text{MB}.
    • Historic lows reached around the 2023–2024 timeframe.
    • Recent supply demands from AI data centers and cloud computing have driven semiconductor and memory prices up by 30%30\% to 50%50\%.
    • Linked List Architectural Trade-offs:
    • Physical classroom demonstration: Three students seated side-by-side represent an array (one contiguous block). Dispersed students (Owen, Jonathan, and Isaac) represent a linked list, where Owen holds Jonathan's address, and Jonathan holds Isaac's address.
    • Advantage: Linked lists eliminate the requirement for large, contiguous memory blocks; memory allocations can occur in small fragments dispersed throughout the heap.
    • Disadvantage (Overhead): A linked list consumes substantially more aggregate memory than an array because each payload requires an accompanying memory address pointer (reference). Storing 10,00010{,}000 items introduces 10,00010{,}000 additional link references.
    • Disadvantage (Performance): Non-contiguous access makes traversing a linked list noticeably slower than sequential array indexing.

The Node Class Architecture and Manual Chaining

  • Standard Node Class Implementation:
    • Declared with fields for data and pointer:
public class Node {
    public int data;
    public Node next;

    public Node(int data, Node next) {
        this.data = data;
        this.next = next;
    }

    public String toString() {
        return data + " ";
    }
}
  • Manual Chaining Mechanism:
    • Creating four disconnected nodes, each with a null next reference:
Node a = new Node(10, null);
Node b = new Node(70, null);
Node c = new Node(20, null);
Node d = new Node(90, null);
  • Chaining using reference assignment:
a.next = b; // a.next becomes a reference copy of b
b.next = c; // b.next becomes a reference copy of c
c.next = d; // c.next becomes a reference copy of d
  • Severing Direct Reference Handles:
    • Setting external reference variables to null:
b = null;
c = null;
d = null;
  • The data values 7070, 2020, and 9090 are not deallocated by the garbage collector because an active reference chain remains rooted at variable a.
  • Accessing sequential elements through explicit pointer navigation:
    • First node: a evaluates to instance holding payload 1010.
    • Second node: a.next evaluates to instance holding payload 7070.
    • Third node: a.next.next evaluates to instance holding payload 2020.
    • Fourth node: a.next.next.next evaluates to instance holding payload 9090.
    • End of list: a.next.next.next.next evaluates to null.
  • Attempting attribute access on null (e.g., a.next.next.next.next.next) throws a runtime NullPointerException.

Linked List Traversal and Pointer Preservation

  • Iterative Traversal Pattern:
    • Hardcoding chained .next calls is unprogrammatic and unscalable for dynamically sized collections.
    • Just as an accumulator loop iterates across an integer sequence (total=0\text{total} = 0, current=1\text{current} = 1, incrementing via current=current+1\text{current} = \text{current} + 1 until reaching 100100), list traversal advances an object pointer:
Node current = a;
while (current != null) {
    System.out.print(current);
    current = current.next;
}
  • Mechanics of the Assignment Statement current = current.next:

    • The assignment operator evaluates its right-hand side first.
    • The expression current.next resolves to the memory address stored in the next attribute of the current instance.
    • The resulting reference is then written back into the left-hand variable current, advancing the pointer to the succeeding instance.
    • When current reaches the terminal null reference, the condition current != null evaluates to false, gracefully terminating the loop.
  • The Critical Rule of Pointer Preservation:

    • The external handle referencing the beginning of the list (head) must never be used directly as the loop counter.
    • Executing while (head != null) { head = head.next; } causes head to evaluate to null upon loop completion.
    • Advancing head directly destroys access to the start of the list, rendering subsequent traversals impossible.
    • Always initialize a temporary cursor (temp or current) to preserve the anchor head.
  • List Construction via Prepending (Head Insertion):

    • Generating a random linked list by inserting nodes at the beginning:
Node head = null;
for (int i = 0; i < 5; i++) {
    int payload = (int)(Math.random() * 100) + 1; // Random integer in [1, 100]
    head = new Node(payload, head);
}
  • Because each new node sets its next pointer to the current head and subsequently becomes the new head, the insertion process inverts the generation sequence.
  • Example: Generating values in chronological order 66,75,29,83,2666, 75, 29, 83, 26 produces a final linked list ordered as:   26→83→29→75→6626 \rightarrow 83 \rightarrow 29 \rightarrow 75 \rightarrow 66

Iterative and Recursive Algorithms on Linked Lists

  • Algorithm 1: Aggregating Payloads (Total Sum):
    • Accumulates all integer values across a list:
int total = 0;
Node temp = head;
while (temp != null) {
    total += temp.data;   // Extract payload
    temp = temp.next;     // Reallocate cursor
}
  • A list of 3030 random values spanning [1,100][1, 100] sums to approximately 14291429, yielding an average of roughly 1429/30≈47.631429 / 30 \approx 47.63, conforming to expected probabilistic distributions.

    • Algorithm 2: Selective Aggregation (Summing Odd Numbers):
  • Sums only odd payloads using modular arithmetic:

int totalOdd = 0;
Node temp = head;
while (temp != null) {
    if (temp.data % 2 != 0) { // Handles both positive (1) and negative (-1) odd remainders
        totalOdd += temp.data;
    }
    temp = temp.next;
}
  • Checking temp.data % 2 != 0 is necessary because negative odd integers yield −1-1 under the modulo operator, failing a strict == 1 check.

    • Algorithm 3: Modular Functional Traversal (Count Even Numbers):
  • Encapsulates list counting logic in a static helper method:

public static int countEven(Node start) {
    int result = 0;
    while (start != null) {
        if (start.data % 2 == 0) {
            result++;
        }
        start = start.next; // Mutating 'start' does not alter caller's 'head'
    }
    return result;
}
  • Scope and Reference Passing in Java: When passing head into countEven(head), the method parameter start receives a copy of the reference address. Reassigning start = start.next inside the function does not modify the original head variable in the calling function, eliminating the need to construct a secondary temporary variable.

    • Algorithm 4: Iterative Key Search (Contains Method):
  • Linearly searches for a specific key value within the list:

public static boolean contains(Node start, int key) {
    while (start != null) {
        if (start.data == key) {
            return true; // Key found
        }
        start = start.next;
    }
    return false; // Loop terminated without finding key
}
  • In a randomly populated list of 1010 items where each item is between 11 and 100100, the probability of containing the value 100100 is exactly 10%10\%.

    • Algorithm 5: Recursive Search Implementation:
  • Expresses linear list traversal as a pure recursive decomposition without iterative loops:

public static boolean containsRecursive(Node start, int key) {
    // Base Case 1: Empty list cannot contain any value
    if (start == null) {
        return false;
    }
    // Base Case 2: Current node matches target key
    if (start.data == key) {
        return true;
    }
    // Recursive Step: Check the remainder of the list
    return containsRecursive(start.next, key);
}
  • Metaphorical demonstration: Searching for a student named Anthony along a queue of students. If the first student is not Anthony, apply the identical verification algorithm to the remaining sub-queue starting at the next student.

Questions & Discussion

  • Lab Class Attendance Discrepancies:

    • Question: Can a student who cannot attend their officially scheduled Skills Lab session attend an alternate session (e.g., Friday) instead?
    • Answer: No. Instructors lack administrative permissions to transfer or reallocate students across timetable classes. Students must adhere to the policies detailed in the pinned Skills Lab FAQ announcement.
  • Short Extension System Behavior:

    • Question: Has anyone encountered submission failures or technical bugs when applying for the 3-day3\text{-day} short extension via the system?
    • Answer: Students confirmed that applications processed smoothly without operational issues, confirming the process functions properly.
  • Skills Lab Optional Retake Eligibility:

    • Question: If a student completed the first Skills Lab attempt and is satisfied with their mark, do they have to sit the second attempt during Week 99?
    • Answer: No. If a student scored high (e.g., 9595 out of 100100) and is satisfied, they do not need to attend the second attempt. However, any student wishing to increase their grade to 100100 is fully entitled to take the second attempt.
  • Linked Memory Storage Equivalence:

    • Question: Does a linked list take the same amount of physical memory as an array to store a set of students?
    • Answer: No. While the baseline payload data takes the same storage, linked structures require extra memory overhead to store the explicit reference addresses linking each node to its neighbor, whereas arrays store items contiguously without per-element address pointers.
  • Functional Parameter Mutability:

    • Question: Does advancing start = start.next inside a helper method destroy the caller's reference to the list?
    • Answer: No. Java passes object references by value. The parameter start holds a reference copy of head. Mutating start modifies only the local pointer within the method frame; the caller's head variable remains unaffected.