Ch 4. Relations

Ch 4. Programming Exercises

Exercise 1: Relation Matrix Generator

The objective of this exercise is to practice representing relations using matrices. Your task is to write a program (using pseudocode or a programming language of your choice) that

  • Takes a set [latex]A[/latex] as input (e.g., [latex]A = \{ 1, 2, 3 \}[/latex])
  • Takes a relation [latex]R[/latex] as a list of ordered pairs (e.g., [latex]R = [(1, 2), (2, 3)][/latex])
  • Outputs the relation matrix (a 2D array) representing [latex]R[/latex] on [latex]A \times A[/latex]
  • Checks if the relation is reflexive, symmetric, and/or transitive

 

Exercise 2: Equivalence Class Finder

The objective of this exercise is to understand equivalence relations and partitions. Your task is to write a program (using pseudocode or a programming language of your choice) that

  • Accepts a set [latex]A[/latex] and an equivalence relation [latex]R[/latex] on [latex]A[/latex]
  • Outputs the equivalence classes induced by [latex]R[/latex]

For example, the input

[latex]A = \{ 1, 2, 3, 4 \}, R = \{ (1, 1), (1, 3), (3, 1), (3, 3), (2, 2), (4, 4) \}[/latex]

produces the output

[latex][ \{ 1, 3 \} , \{ 2 \} , \{ 4 \} ][/latex]

 

Exercise 3: Transitive Closure Using Warshall’s Algorithm

The objective of this exercise is to implement Warshall’s algorithm to compute the transitive closure of a relation. Your task is to write a program (using pseudocode or a programming language of your choice) that

  • Accepts an [latex]n \times n[/latex] relation matrix [latex]M[/latex]
  • Computes and returns the transitive closure of [latex]M[/latex] using Warshall’s algorithm
  • Visualizes the original and transitive closure matrices side by side

 

Exercise 4: Relational Database Join Simulator

The objective of this exercise is to simulate a relational database join using relations. Your task is to write a program (using pseudocode or a programming language of your choice) that

  • Accepts two relations [latex]R_{1}[/latex] (e.g., Students: ID [latex]\rightarrow[/latex] Name) and [latex]R_{2}[/latex] (e.g., Grades: ID [latex]\rightarrow[/latex] Grade)
  • Performs a natural join on the common attribute (ID)
  • Outputs the joined relation (e.g., Name [latex]\rightarrow[/latex] Grade)

For example, the input

[latex]R_{1}[/latex] = [(1, "Aiden"), (2, "Benjamin")]

[latex]R_{2}[/latex] = [(1, "A"), (2, "B")]

produces the output

[("Aiden", "A"), ("Benjamin", "B")]

 

Exercise 5: Relation Property Checker

The objective of this exercise is to analyze properties of a binary relation. Your task is to write a program (using pseudocode or a programming language of your choice) that

  • Accepts a set [latex]A[/latex] and a relation [latex]R[/latex] on [latex]A[/latex]
  • Checks and reports whether [latex]R[/latex] is reflexive, symmetric, antisymmetric, and/or transitive
  • Suggests what minimal pairs need to be added to make [latex]R[/latex] reflexive, symmetric, or transitive.