Advertisement
indic_gm

DSA_LAB

Mar 18th, 2025
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 18.77 KB | Source Code | 0 0
  1. Using suitable Abstract Data Types (ADTs) perform the following tasks:
  2. (i) Checking if the parentheses are well formed i.e. [ ( ) ( ) ] is well-formed, but [ ( ( ] ) ) is not.
  3. (ii) Reverse the contents of a List using List ADT
  4. (iii) Use dictionary ADT to count the number of occurrences of each word in an online book.  
  5.  
  6. i)
  7. import java.util.Stack;
  8.  
  9. public class WellFormedParentheses {
  10.     public static boolean isWellFormed(String s) {
  11.         Stack<Character> stack = new Stack<>();
  12.         for (char c : s.toCharArray()) {
  13.             if (c == '(' || c == '[' || c == '{') {
  14.                 stack.push(c);
  15.             } else if (c == ')' && !stack.isEmpty() && stack.peek() == '(') {
  16.                 stack.pop();
  17.             } else if (c == ']' && !stack.isEmpty() && stack.peek() == '[') {
  18.                 stack.pop();
  19.             } else if (c == '}' && !stack.isEmpty() && stack.peek() == '{') {
  20.                 stack.pop();
  21.             } else {
  22.                 return false;
  23.             }
  24.         }
  25.         return stack.isEmpty();
  26.     }
  27.  
  28.     public static void main(String[] args) {
  29.         String exp1 = "[()()]";
  30.         String exp2 = "[(()])";
  31.         System.out.println("Expression 1 well-formed: " + isWellFormed(exp1));
  32.         System.out.println("Expression 2 well-formed: " + isWellFormed(exp2));
  33.     }
  34. }
  35.  
  36. ii)
  37. import java.util.ArrayList;
  38. import java.util.Arrays;
  39. import java.util.List;
  40.  
  41. public class ReverseList {
  42.     public static void reverseList(List<Integer> list) {
  43.         int left = 0, right = list.size() - 1;
  44.         while (left < right) {
  45.             int temp = list.get(left);
  46.             list.set(left, list.get(right));
  47.             list.set(right, temp);
  48.             left++;
  49.             right--;
  50.         }
  51.     }
  52.  
  53.     public static void main(String[] args) {
  54.         List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
  55.         System.out.println("Original List: " + list);
  56.         reverseList(list);
  57.         System.out.println("Reversed List: " + list);
  58.     }
  59. }
  60.  
  61. iii)
  62. import java.util.HashMap;
  63. import java.util.Map;
  64.  
  65. public class WordCount {
  66.     public static Map<String, Integer> countWordOccurrences(String text) {
  67.         Map<String, Integer> wordCount = new HashMap<>();
  68.         String[] words = text.toLowerCase().replaceAll("[^a-z ]", "").split("\\s+");
  69.  
  70.         for (String word : words) {
  71.             wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
  72.         }
  73.         return wordCount;
  74.     }
  75.  
  76.     public static void main(String[] args) {
  77.         String text = "This is a sample book text. This book contains sample text.";
  78.         Map<String, Integer> wordCount = countWordOccurrences(text);
  79.         System.out.println("Word occurrences: " + wordCount);
  80.     }
  81. }
  82.  
  83. 2) Hot potato game
  84.  
  85. import java.util.LinkedList;
  86. import java.util.Queue;
  87.  
  88. public class HotPotato {
  89.     public static String hotPotato(String[] names, int num) {
  90.         Queue<String> queue = new LinkedList<>();
  91.  
  92.         // Add all names to the queue
  93.         for (String name : names) {
  94.             queue.offer(name);
  95.         }
  96.  
  97.         // Simulation of passing the potato
  98.         while (queue.size() > 1) {
  99.             // Pass the potato num times
  100.             for (int i = 0; i < num - 1; i++) {
  101.                 queue.offer(queue.poll()); // Move front player to the back
  102.             }
  103.             System.out.println("Eliminated: " + queue.poll()); // Remove the player at the front
  104.         }
  105.  
  106.         return queue.peek(); // Last remaining player
  107.     }
  108.  
  109.     public static void main(String[] args) {
  110.         String[] players = {"Bill", "David", "Susan", "Jane", "Kent", "Brad"};
  111.         int num = 7;
  112.  
  113.         String winner = hotPotato(players, num);
  114.         System.out.println("Winner: " + winner);
  115.     }
  116. }
  117.  
  118. 3. Library
  119.  
  120. import java.util.HashMap;
  121.  
  122. class Book {
  123.     String isbn;
  124.     String title;
  125.     String author;
  126.     boolean isAvailable;
  127.  
  128.     public Book(String isbn, String title, String author) {
  129.         this.isbn = isbn;
  130.         this.title = title;
  131.         this.author = author;
  132.         this.isAvailable = true; // Initially available
  133.     }
  134.  
  135.     @Override
  136.     public String toString() {
  137.         return "ISBN: " + isbn + ", Title: " + title + ", Author: " + author + ", Available: " + isAvailable;
  138.     }
  139. }
  140.  
  141. public class LibrarySystem {
  142.     private HashMap<String, Book> books; // Store books by ISBN
  143.     private HashMap<String, Book> borrowedBooks; // Store borrowed books separately
  144.  
  145.     public LibrarySystem() {
  146.         books = new HashMap<>();
  147.         borrowedBooks = new HashMap<>();
  148.     }
  149.  
  150.     // Add a book to the library
  151.     public void addBook(String isbn, String title, String author) {
  152.         books.put(isbn, new Book(isbn, title, author));
  153.     }
  154.  
  155.     // Check if a book is available
  156.     public boolean isBookAvailable(String isbn) {
  157.         return books.containsKey(isbn) && books.get(isbn).isAvailable;
  158.     }
  159.  
  160.     // Borrow a book
  161.     public boolean borrowBook(String isbn) {
  162.         if (isBookAvailable(isbn)) {
  163.             Book book = books.get(isbn);
  164.             book.isAvailable = false;
  165.             borrowedBooks.put(isbn, book);
  166.             return true;
  167.         }
  168.         return false;
  169.     }
  170.  
  171.     // Return a book
  172.     public boolean returnBook(String isbn) {
  173.         if (borrowedBooks.containsKey(isbn)) {
  174.             Book book = borrowedBooks.remove(isbn);
  175.             book.isAvailable = true;
  176.             books.put(isbn, book);
  177.             return true;
  178.         }
  179.         return false;
  180.     }
  181.  
  182.     // Lookup book by ISBN
  183.     public Book getBook(String isbn) {
  184.         return books.getOrDefault(isbn, null);
  185.     }
  186.  
  187.     public static void main(String[] args) {
  188.         LibrarySystem library = new LibrarySystem();
  189.        
  190.         // Adding books
  191.         library.addBook("12345", "Data Structures", "Mark Allen");
  192.         library.addBook("67890", "Algorithms", "Thomas Cormen");
  193.  
  194.         // Lookup book
  195.         System.out.println("Lookup Book: " + library.getBook("12345"));
  196.  
  197.         // Check availability
  198.         System.out.println("Is Book Available: " + library.isBookAvailable("12345"));
  199.  
  200.         // Borrow a book
  201.         System.out.println("Borrowing Book: " + library.borrowBook("12345"));
  202.         System.out.println("Is Book Available After Borrowing: " + library.isBookAvailable("12345"));
  203.  
  204.         // Return a book
  205.         System.out.println("Returning Book: " + library.returnBook("12345"));
  206.         System.out.println("Is Book Available After Return: " + library.isBookAvailable("12345"));
  207.     }
  208. }
  209.  
  210. 4. Quick SOrt
  211.  
  212. 1. Last element as pivot
  213.  
  214. import java.util.Arrays;
  215.  
  216. public class SimpleQuickSort {
  217.  
  218.     // Quick Sort using last element as pivot
  219.     public static void quickSort(int[] arr, int low, int high) {
  220.         if (low < high) {
  221.             int pivotIndex = partition(arr, low, high);
  222.             quickSort(arr, low, pivotIndex - 1);
  223.             quickSort(arr, pivotIndex + 1, high);
  224.         }
  225.     }
  226.  
  227.     private static int partition(int[] arr, int low, int high) {
  228.         int pivot = arr[high]; // Last element as pivot
  229.         int i = low - 1;
  230.  
  231.         for (int j = low; j < high; j++) {
  232.             if (arr[j] < pivot) {
  233.                 i++;
  234.                 swap(arr, i, j);
  235.             }
  236.         }
  237.         swap(arr, i + 1, high);
  238.         return i + 1;
  239.     }
  240.  
  241.     private static void swap(int[] arr, int i, int j) {
  242.         int temp = arr[i];
  243.         arr[i] = arr[j];
  244.         arr[j] = temp;
  245.     }
  246.  
  247.     public static void main(String[] args) {
  248.         int[] arr = {10, 7, 8, 9, 1, 5};
  249.         System.out.println("Before Sorting: " + Arrays.toString(arr));
  250.  
  251.         quickSort(arr, 0, arr.length - 1);
  252.  
  253.         System.out.println("After Sorting: " + Arrays.toString(arr));
  254.     }
  255. }
  256.  
  257. 2. Random pivot
  258.  
  259. import java.util.Arrays;
  260. import java.util.Random;
  261.  
  262. public class RandomPivotQuickSort {
  263.  
  264.     // Quick Sort using a random pivot
  265.     public static void quickSort(int[] arr, int low, int high) {
  266.         if (low < high) {
  267.             int pivotIndex = randomPartition(arr, low, high);
  268.             quickSort(arr, low, pivotIndex - 1);
  269.             quickSort(arr, pivotIndex + 1, high);
  270.         }
  271.     }
  272.  
  273.     private static int randomPartition(int[] arr, int low, int high) {
  274.         Random rand = new Random();
  275.         int randomIndex = low + rand.nextInt(high - low + 1);
  276.         swap(arr, randomIndex, high); // Swap random element with last element
  277.         return partition(arr, low, high);
  278.     }
  279.  
  280.     private static int partition(int[] arr, int low, int high) {
  281.         int pivot = arr[high];
  282.         int i = low - 1;
  283.  
  284.         for (int j = low; j < high; j++) {
  285.             if (arr[j] < pivot) {
  286.                 i++;
  287.                 swap(arr, i, j);
  288.             }
  289.         }
  290.         swap(arr, i + 1, high);
  291.         return i + 1;
  292.     }
  293.  
  294.     private static void swap(int[] arr, int i, int j) {
  295.         int temp = arr[i];
  296.         arr[i] = arr[j];
  297.         arr[j] = temp;
  298.     }
  299.  
  300.     public static void main(String[] args) {
  301.         int[] arr = {10, 7, 8, 9, 1, 5};
  302.         System.out.println("Before Sorting: " + Arrays.toString(arr));
  303.  
  304.         quickSort(arr, 0, arr.length - 1);
  305.  
  306.         System.out.println("After Sorting: " + Arrays.toString(arr));
  307.     }
  308. }
  309.  
  310. 5. Max Flow
  311. /******************************************************************************
  312.  
  313.                             Online Java Compiler.
  314.                 Code, Compile, Run and Debug java program online.
  315. Write your code in this editor and press "Run" button to execute it.
  316.  
  317. *******************************************************************************/
  318. import java.util.LinkedList;
  319. import java.util.Queue;
  320.  
  321. public class Main {
  322.     static final int V = 8;
  323.  
  324.     boolean bfs(int rGraph[][], int s, int t, int parent[]) {
  325.         boolean visited[] = new boolean[V];
  326.         for (int i = 0; i < V; ++i)
  327.             visited[i] = false;
  328.  
  329.         Queue<Integer> queue = new LinkedList<>();
  330.         queue.add(s);
  331.         visited[s] = true;
  332.         parent[s] = -1;
  333.  
  334.         while (!queue.isEmpty()) {
  335.             int u = queue.poll();
  336.  
  337.             for (int v = 0; v < V; v++) {
  338.                 if (!visited[v] && rGraph[u][v] > 0) {
  339.                     queue.add(v);
  340.                     parent[v] = u;
  341.                     visited[v] = true;
  342.                 }
  343.             }
  344.         }
  345.  
  346.         return visited[t];
  347.     }
  348.  
  349.     int fordFulkerson(int graph[][], int s, int t) {
  350.         int u, v;
  351.         int rGraph[][] = new int[V][V];
  352.  
  353.         for (u = 0; u < V; u++)
  354.             for (v = 0; v < V; v++)
  355.                 rGraph[u][v] = graph[u][v];
  356.  
  357.         int parent[] = new int[V];
  358.  
  359.         int max_flow = 0;
  360.  
  361.         while (bfs(rGraph, s, t, parent)) {
  362.             int path_flow = Integer.MAX_VALUE;
  363.             for (v = t; v != s; v = parent[v]) {
  364.                 u = parent[v];
  365.                 path_flow = Math.min(path_flow, rGraph[u][v]);
  366.             }
  367.  
  368.             for (v = t; v != s; v = parent[v]) {
  369.                 u = parent[v];
  370.                 rGraph[u][v] -= path_flow;
  371.                 rGraph[v][u] += path_flow;
  372.             }
  373.  
  374.             max_flow += path_flow;
  375.         }
  376.  
  377.         return max_flow;
  378.     }
  379.  
  380.     public static void main(String[] args) {
  381.         int graph[][] = {  
  382.             {0,  13,  10,  10,   0, 0,  0,  0},
  383.             {0,   0,  0,   0,  24, 0,  0,  0},
  384.             {0,   5,  0,   15,  0, 0,  7,  0},
  385.             {0,   0,  0,    0,  0, 0,  15, 0},
  386.             {0,   0,  0,    0,  0, 1,   0, 9},
  387.             {0,   0,  0,    0,  0, 0,   6, 13},
  388.             {0,   0,  0,    0,  0, 0,   0, 16},
  389.             {0,   0,  0,    0,  0, 0,   0,  0}
  390.          
  391.         };
  392.                        
  393.         Main m = new Main();
  394.  
  395.         System.out.println("The maximum possible flow is " + m.fordFulkerson(graph, 0, 7));
  396.     }
  397. }
  398.  
  399. O/P
  400. The maximum possible flow is 26
  401.  
  402. 6. Dijikstra Algorithm
  403.  
  404. import java.util.*;
  405.  
  406. class Dijkstra {
  407.     static class Edge {
  408.         int dest, weight;
  409.         Edge(int d, int w) {
  410.             this.dest = d;
  411.             this.weight = w;
  412.         }
  413.     }
  414.  
  415.     static class Node implements Comparable<Node> {
  416.         int vertex, cost;
  417.         Node(int v, int c) {
  418.             this.vertex = v;
  419.             this.cost = c;
  420.         }
  421.  
  422.         public int compareTo(Node other) {
  423.             return Integer.compare(this.cost, other.cost);
  424.         }
  425.     }
  426.  
  427.     public static int dijkstra(Map<Integer, List<Edge>> graph, int source, int target) {
  428.         PriorityQueue<Node> pq = new PriorityQueue<>();
  429.         Map<Integer, Integer> distance = new HashMap<>();
  430.        
  431.         // Initialize distances
  432.         for (int node : graph.keySet()) {
  433.             distance.put(node, Integer.MAX_VALUE);
  434.         }
  435.         distance.put(source, 0);
  436.         pq.add(new Node(source, 0));
  437.  
  438.         while (!pq.isEmpty()) {
  439.             Node current = pq.poll();
  440.             int u = current.vertex;
  441.  
  442.             if (u == target) {
  443.                 return distance.get(u); // Shortest path found
  444.             }
  445.  
  446.             for (Edge edge : graph.get(u)) {
  447.                 int v = edge.dest;
  448.                 int newDist = distance.get(u) + edge.weight;
  449.  
  450.                 if (newDist < distance.get(v)) {
  451.                     distance.put(v, newDist);
  452.                     pq.add(new Node(v, newDist));
  453.                 }
  454.             }
  455.         }
  456.  
  457.         return -1; // No path found
  458.     }
  459.  
  460.     public static void main(String[] args) {
  461.         Map<Integer, List<Edge>> graph = new HashMap<>();
  462.  
  463.         // Defining the graph with time weights
  464.         graph.put(0, Arrays.asList(new Edge(1, 1), new Edge(2, 5)));  // A -> B (1), A -> C (5)
  465.         graph.put(1, Arrays.asList(new Edge(3, 20)));                 // B -> D (20)
  466.         graph.put(2, Arrays.asList(new Edge(3, 10)));                 // C -> D (10)
  467.         graph.put(3, new ArrayList<>());                              // D has no outgoing edges
  468.  
  469.         int minTime = dijkstra(graph, 0, 3);
  470.         System.out.println("Minimum time to reach D: " + minTime + " minutes");
  471.     }
  472. }
  473.  
  474. O/P
  475. Minimum time to reach D: 15 minutes
  476.  
  477.  
  478. 7. Leveinshtien ALgo
  479.  
  480. import java.util.*;
  481.  
  482. public class NameMatcher {
  483.     // Function to calculate Levenshtein Distance
  484.     public static int levenshteinDistance(String s1, String s2) {
  485.         int m = s1.length(), n = s2.length();
  486.         int[][] dp = new int[m + 1][n + 1];
  487.  
  488.         for (int i = 0; i <= m; i++) {
  489.             for (int j = 0; j <= n; j++) {
  490.                 if (i == 0) {
  491.                     dp[i][j] = j;
  492.                 } else if (j == 0) {
  493.                     dp[i][j] = i;
  494.                 } else {
  495.                     int cost = (s1.charAt(i - 1) == s2.charAt(j - 1)) ? 0 : 1;
  496.                     dp[i][j] = Math.min(Math.min(
  497.                             dp[i - 1][j] + 1,     // Deletion
  498.                             dp[i][j - 1] + 1),    // Insertion
  499.                             dp[i - 1][j - 1] + cost); // Substitution
  500.                 }
  501.             }
  502.         }
  503.         return dp[m][n];
  504.     }
  505.  
  506.     public static String findBestMatch(String nameA, List<String> listB) {
  507.         String bestMatch = "";
  508.         int minDistance = Integer.MAX_VALUE;
  509.  
  510.         for (String nameB : listB) {
  511.             if (nameB.equals(".") || nameB.trim().isEmpty()) continue;  // Ignore blank cells
  512.             int distance = levenshteinDistance(nameA.toLowerCase(), nameB.toLowerCase());
  513.             if (distance < minDistance) {
  514.                 minDistance = distance;
  515.                 bestMatch = nameB;
  516.             }
  517.         }
  518.         return bestMatch;
  519.     }
  520.  
  521.     public static void main(String[] args) {
  522.         List<String> listA = Arrays.asList(
  523.             "Accenture", "Adobe", "Akamai", "Alexandria Real Estates",
  524.             "Biotech", "Boeing", "Catamarine", "Cadmaxx Solutions", "Cisco Systems"
  525.         );
  526.         List<String> listB = Arrays.asList(
  527.             "Accent llxure", "Addobbe", ".", "Alexandira Reel Estates",
  528.             "Biotec", "Boing", "Catamaine", "Cadmax Soltion", "Cisc Systm"
  529.         );
  530.  
  531.         System.out.println("Matching Results:");
  532.         for (String nameA : listA) {
  533.             String bestMatch = findBestMatch(nameA, listB);
  534.             System.out.println(nameA + " -> " + bestMatch);
  535.         }
  536.     }
  537. }
  538.  
  539. O/P
  540. Accenture -> Accent llxure
  541. Adobe -> Addobbe
  542. Akamai -> (No match)
  543. Alexandria Real Estates -> Alexandira Reel Estates
  544. Biotech -> Biotec
  545. Boeing -> Boing
  546. Catamarine -> Catamaine
  547. Cadmaxx Solutions -> Cadmax Soltion
  548. Cisco Systems -> Cisc Systm
  549.  
  550. 8. Robin Karp
  551.  
  552. import java.util.*;
  553.  
  554. public class RabinKarpPlagiarismDetector {
  555.     private static final int PRIME = 101; // Prime number for hashing
  556.    
  557.     // Function to compute hash for a substring
  558.     private static long createHash(String str, int len) {
  559.         long hash = 0;
  560.         for (int i = 0; i < len; i++) {
  561.             hash += str.charAt(i) * Math.pow(PRIME, i);
  562.         }
  563.         return hash;
  564.     }
  565.  
  566.     // Function to recalculate hash when sliding window moves
  567.     private static long recalculateHash(String str, int oldIndex, int newIndex, long oldHash, int patternLen) {
  568.         long newHash = (oldHash - str.charAt(oldIndex)) / PRIME;
  569.         newHash += str.charAt(newIndex) * Math.pow(PRIME, patternLen - 1);
  570.         return newHash;
  571.     }
  572.  
  573.     // Function to detect similar substrings using Rabin-Karp
  574.     public static boolean isPlagiarized(String code1, String code2, int patternLen) {
  575.         int len1 = code1.length(), len2 = code2.length();
  576.        
  577.         if (len1 < patternLen || len2 < patternLen) return false; // If too short, can't compare
  578.        
  579.         long hash1 = createHash(code1, patternLen);
  580.         long hash2 = createHash(code2, patternLen);
  581.  
  582.         // Compare initial hashes
  583.         if (hash1 == hash2 && code1.substring(0, patternLen).equals(code2.substring(0, patternLen))) {
  584.             return true;
  585.         }
  586.  
  587.         // Sliding window hash comparison
  588.         for (int i = 1; i <= len2 - patternLen; i++) {
  589.             hash2 = recalculateHash(code2, i - 1, i + patternLen - 1, hash2, patternLen);
  590.             if (hash1 == hash2 && code1.substring(0, patternLen).equals(code2.substring(i, i + patternLen))) {
  591.                 return true;
  592.             }
  593.         }
  594.  
  595.         return false;
  596.     }
  597.  
  598.     public static void main(String[] args) {
  599.         // Example Code Submissions
  600.         String codeA = "int sum(int a, int b) { return a + b; }";
  601.         String codeB = "int sum(int x, int y) { return x + y; }";
  602.        
  603.         int patternLength = 5; // Define substring pattern size for comparison
  604.        
  605.         boolean plagiarized = isPlagiarized(codeA, codeB, patternLength);
  606.        
  607.         if (plagiarized) {
  608.             System.out.println("Plagiarism Detected!");
  609.         } else {
  610.             System.out.println("Code is unique.");
  611.         }
  612.     }
  613. }
  614.  
  615.  
  616.  
  617.  
  618.  
  619.  
  620.  
  621.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement