Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

CC104-Data-Structure-and-Algorithms-Week-3-Example-Codes

The document covers various Java concepts including Sets and Relations using HashSet and HashMap, respectively, along with their common methods. It also presents basic algorithms such as finding the largest number, binary search, and mathematical functions using the Math class. Additionally, it includes examples of recursion, summation, and proof techniques in programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

CC104-Data-Structure-and-Algorithms-Week-3-Example-Codes

The document covers various Java concepts including Sets and Relations using HashSet and HashMap, respectively, along with their common methods. It also presents basic algorithms such as finding the largest number, binary search, and mathematical functions using the Math class. Additionally, it includes examples of recursion, summation, and proof techniques in programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Presentation 1: Sets, Relations, and Basic Algorithm

1. Sets in Java

Java provides the HashSet class to work with sets.

The HashSet class in Java is part of java.util and is used to store unique elements.

Common Methods in HashSet

Method Description

add(E e) Adds an element to the set if it is not already


present.

remove(Object o) Removes the specified element from the set.

contains(Object o) Returns true if the set contains the specified


element.

size() Returns the number of elements in the set.

isEmpty() Returns true if the set has no elements.

clear() Removes all elements from the set.

addAll(Collection<? extends E> c) Performs union of two sets.


retainAll(Collection<?> c) Performs intersection of two sets.

removeAll(Collection<?> c) Performs difference between two sets.

————————————————————————————————————

import java.util.HashSet;

public class SetExample {


public static void main(String[] args) {
HashSet<Integer> setA = new HashSet<>();
setA.add(1);
setA.add(2);
setA.add(3);

HashSet<Integer> setB = new HashSet<>();


setB.add(2);
setB.add(3);
setB.add(4);

// Union
HashSet<Integer> unionSet = new HashSet<>(setA);
unionSet.addAll(setB);
System.out.println("Union: " + unionSet);

// Intersection
HashSet<Integer> intersectionSet = new HashSet<>(setA);
intersectionSet.retainAll(setB);
System.out.println("Intersection: " + intersectionSet);

// Difference
HashSet<Integer> differenceSet = new HashSet<>(setA);
differenceSet.removeAll(setB);
System.out.println("Difference: " + differenceSet);
}
}

————————————————————————————————————
2. Relations in Java

A relation can be represented using a HashMap.

The HashMap class is used to store key-value pairs.

Common Methods in HashMap

Method Description

put(K key, V value) Inserts a key-value pair into the map.

get(Object key) Retrieves the value associated with the given


key.

remove(Object key) Removes the key-value pair for the given key.

containsKey(Object key) Checks if the map contains the specified key.

containsValue(Object value) Checks if the map contains the specified


value.

size() Returns the number of key-value pairs in the


map.

isEmpty() Returns true if the map is empty.

clear() Removes all key-value pairs from the map.


————————————————————————————————————

import java.util.HashMap;
import java.util.HashSet;

public class RelationExample {


public static void main(String[] args) {
HashMap<Integer, HashSet<Integer>> relation = new HashMap<>();

relation.put(1, new HashSet<>());


relation.get(1).add(2);

relation.put(2, new HashSet<>());


relation.get(2).add(3);

relation.put(3, new HashSet<>());


relation.get(3).add(4);

System.out.println("Relation: " + relation);


}
}

————————————————————————————————————

3. Basic Algorithm (Finding the Largest Number)

public class LargestNumber {


public static void main(String[] args) {
int[] numbers = {3, 7, 2, 9, 5};
int max = numbers[0];

for (int num : numbers) {


if (num > max) {
max = num;
}
}

System.out.println("Largest Number: " + max);


}
}
————————————————————————————————————

4. Time Complexity Example (Binary Search O(log n))

The Arrays class is used for array manipulation.

Common Methods in Arrays

Method Description

Arrays.sort(array) Sorts the array in ascending order.

Arrays.binarySearch(array, key) Searches for key in a sorted array.

Arrays.toString(array) Returns a string representation of the


array.

import java.util.Arrays;

public class BinarySearchExample {


public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}

public static void main(String[] args) {


int[] numbers = {1, 3, 5, 7, 9, 11};
int target = 7;
System.out.println("Index of target: " + binarySearch(numbers, target));
}
}
————————————————————————————————————

import java.util.Arrays;

public class ArraysExample {


public static void main(String[] args) {
int[] numbers = {3, 1, 4, 2, 5};
Arrays.sort(numbers);
System.out.println("Sorted Array: " + Arrays.toString(numbers));

int index = Arrays.binarySearch(numbers, 4);


System.out.println("Index of 4: " + index);
}
}

————————————————————————————————————

5. Logarithms in Java (Using Math.log)

The Math class provides mathematical functions in Java.

Common Methods in Math

Method Description

Math.log(double a) Returns the natural logarithm (ln(a)).

Math.log10(double a) Returns the logarithm base 10 of a.

Math.pow(double a, double b) Returns a raised to the power of b.

Math.sqrt(double a) Returns the square root of a.

Math.abs(double a) Returns the absolute value of a.

Math.max(double a, double b) Returns the maximum of two values.

Math.min(double a, double b) Returns the minimum of two values.


public class MathExample {
public static void main(String[] args) {
double value = 8;
System.out.println("Log base 2 of 8: " + (Math.log(value) / Math.log(2)));
System.out.println("Square root of 16: " + Math.sqrt(16));
System.out.println("Maximum of (5,10): " + Math.max(5,10));
}
}

————————————————————————————————————

6. Summation Example (Σ i from 1 to n)

public class SummationExample {


public static int sum(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
return sum;
}

public static void main(String[] args) {


System.out.println("Summation (1 to 10): " + sum(10));
}
}

————————————————————————————————————

7. Recurrence Example (Fibonacci Sequence)

public class FibonacciExample {


public static int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}

public static void main(String[] args) {


System.out.println("Fibonacci(5): " + fibonacci(5));
}
}

————————————————————————————————————

8. Recursion Example (Factorial)

public class FactorialExample {


public static int factorial(int n) {
if (n == 0)
return 1;
return n * factorial(n - 1);
}

public static void main(String[] args) {


System.out.println("Factorial of 5: " + factorial(5));
}
}

————————————————————————————————————

9. Proof by Induction Example (Summation Formula Verification)

public class InductionExample {


public static boolean verifySummationFormula(int n) {
int leftSide = (n * (n + 1)) / 2;
int rightSide = 0;
for (int i = 1; i <= n; i++) {
rightSide += i;
}
return leftSide == rightSide;
}

public static void main(String[] args) {


System.out.println("Induction verification for n=10: " +
verifySummationFormula(10));
}
}

————————————————————————————————————

10. Proof by Contradiction Example (Checking if a Number is Even)


public class ContradictionExample {
public static boolean isEven(int n) {
return n % 2 == 0;
}

public static void main(String[] args) {


int num = 4;
System.out.println("Is " + num + " even? " + isEven(num));
}
}

————————————————————————————————————

You might also like