diff --git a/algorithms/Java/README.md b/algorithms/Java/README.md new file mode 100644 index 00000000..61965c1b --- /dev/null +++ b/algorithms/Java/README.md @@ -0,0 +1,55 @@ +# Python + +## Arrays +1. [Count Inversions](arrays/count-inversions.java) +2. [Kadanes Algorithm](arrays/Kadanes_Algorithm.java) +3. [Left Rotation](arrays/left_rotation.java) +4. [Unique Digits of Large Number](arrays/unique-digits-of-large-number.java) + +## Graphs +1. [Dijkstras](graphs/Dijkstras.java) + +## Linked Lists +1. [Circular](linked-lists/circular.java) +2. [Clone Linked List](linked-lists/clone-linkedlist-with-rnd-pointer.java) +3. [Doubly](linked-lists/doubly.java) +4. [Reverse](linked-lists/reverse.java) +5. [Singly](linked-lists/singly.java) + +## Queues +1. [Circular Queue using Linked List](queues/circular-queue-linked-list.java) +2. [Queue using Linked List](queues/queue-linked-list.java) + +## Scheduling +1. [Multi-Level Queue Scheduling](scheduling/multi-level-queue-scheduling.java) +2. [Rund Robin](scheduling/round-robin.java) + +## Searching +1. [Binary Search](searching/binary-search.java) +2. [Jump Search](searching/jump-search.java) +3. [Linear Search](searching/linear-search.java) + +## Sorting +1. [Bubble Sort](sorting/bubble-sort.java) +2. [Counting Sort](sorting/counting-sort.java) +3. [Heap Sort](sorting/heap-sort.java) +4. [Insertion Sort](sorting/insertion-sort.java) +5. [Merge Sort](sorting/merge-sort.java) +6. [Quick Sort](sorting/quick-sort.java) +7. [Selection Sort](sorting/selection-sort.java) + +## Stacks +1. [Balanced Paranthesis](stacks/balanced-paranthesis.java) +2. [Stack](stacks/stack.java) +3. [The Stock Span Problem](stacks/the-stock-span-problem.java) + +## Strings +1. [KMP](strings/kmp.java) +2. [Palindrome](strings/palindrome.java) +3. [Rabin Krap](strings/rabin-karp.java) +4. [Sequence](strings/sequence.java) +5. [Split String](strings/SplitString.java) +6. [Tokenizer](strings/tokenizer.java) + +## Trees +1. [Pre in Post Traversal](trees/pre_in_post_traversal.java) \ No newline at end of file diff --git a/algorithms/Java/arrays/Kadanes_Algorithm.java b/algorithms/Java/arrays/Kadanes_Algorithm.java new file mode 100644 index 00000000..01021467 --- /dev/null +++ b/algorithms/Java/arrays/Kadanes_Algorithm.java @@ -0,0 +1,30 @@ +// Java program to print largest contiguous array sum + +import java.io.*; +import java.util.*; + +class Kadane +{ + public static void main (String[] args) + { + int [] a = {-2, -3, 4, -1, -2, 1, 5, -3}; + System.out.println("Maximum contiguous sum is " + + maxSubArraySum(a)); + } + + static int maxSubArraySum(int a[]) + { + int size = a.length; + int max_so_far = Integer.MIN_VALUE, max_ending_here = 0; + + for (int i = 0; i < size; i++) + { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; + } +} diff --git a/algorithms/Java/arrays/count-inversions.java b/algorithms/Java/arrays/count-inversions.java new file mode 100644 index 00000000..472a7c3b --- /dev/null +++ b/algorithms/Java/arrays/count-inversions.java @@ -0,0 +1,59 @@ +// Algorithm Type: Divide & Conquer +// Time Complexity: O(n*log(n)) + +import java.io.File; +import java.lang.reflect.Array; +import java.util.*; + +public class inversions { + private static long count_split_inv(int[] arr, int[] left, int[] right) { + long split_inv = 0; + int ridx = 0, lidx = 0; + int size = arr.length; + int rsize = right.length; + int lsize = left.length; + for (int i = 0; i < size; i++) { + if (lidx != lsize && ridx != rsize) { + if (right[ridx] <= left[lidx]) { + arr[i] = right[ridx]; + ridx++; + split_inv += lsize - lidx; + } else { + arr[i] = left[lidx]; + lidx++; + } + } else if (lidx == lsize) { + arr[i] = right[ridx]; + ridx++; + } else if (ridx == rsize) { + arr[i] = left[lidx]; + lidx++; + } + } + return split_inv; + } + + private static long count_inversions(int[] arr) { + int size = arr.length; + if (size == 1) { + return 0; + } + int[] left = Arrays.copyOfRange(arr, 0, size / 2); + int[] right = Arrays.copyOfRange(arr, size / 2, size); + long left_inv = count_inversions(left); + long right_inv = count_inversions(right); + long split_inv = count_split_inv(arr, left, right); + + return left_inv + right_inv + split_inv; + } + + public static void main(String[] args) { + try { + int[] arr = {8, 2, 1, 5, 7, 3, 9, 2, 0, 1}; + System.out.println(count_inversions(arr)); + } catch (Exception e) { + System.out.println("Err... "); + } + + } +} diff --git a/algorithms/Java/arrays/left_rotation.java b/algorithms/Java/arrays/left_rotation.java new file mode 100644 index 00000000..aa99464e --- /dev/null +++ b/algorithms/Java/arrays/left_rotation.java @@ -0,0 +1,51 @@ +public class left_rotation{ + + public static void rotateToLeft(int [] arr){ + if(arr == null || arr.length == 0){ + System.out.println("no rotation possible"); + return; + } + //take the first element + int firstElement = arr[0]; + //move everything in the left + for(int i = 0; i < arr.length -1; i++){ + arr[i] = arr[i + 1]; + } + //the first element become the last element + arr[arr.length - 1] = firstElement; + } + + public static void print(int [] arr){ + System.out.print("["); + for(int i = 0; i < arr.length; i++) + System.out.print(arr[i] + ", "); + System.out.println("]"); + } + + public static void main(String [] args){ + int [] arr = {1,2,3,4,5,6,7,8,9}; + int n = 3; //number of times to rotate the array + + System.out.print("before: "); + print(arr); + + System.out.println("rotating " + n + " times to left"); + for(int i = 0; i < n; i++) + rotateToLeft(arr); //move to left n times + + System.out.print("after: "); + print(arr); + } +} + +/* + to run the file: + javac left_rotation.java + java left_rotation + + result: + before: [1, 2, 3, 4, 5, 6, 7, 8, 9, ] + rotating 3 times to left + after: [4, 5, 6, 7, 8, 9, 1, 2, 3, ] + +*/ \ No newline at end of file diff --git a/algorithms/Java/arrays/unique-digits-of-large-number.java b/algorithms/Java/arrays/unique-digits-of-large-number.java new file mode 100644 index 00000000..5efc4ddf --- /dev/null +++ b/algorithms/Java/arrays/unique-digits-of-large-number.java @@ -0,0 +1,62 @@ +import java.util.*; +public class UniqueDigitsOfLargeNumber { + + public static void main(String[] args) { + // TODO Auto-generated method stub + Scanner sc=new Scanner(System.in); + int l,i,j,l1=0; + String s,p=""; + char c,d; + System.out.println("Enter a large number"); + s=sc.nextLine(); + l=s.length(); + for(i=0;i1) + { + for(i=0;ic) + c=p.charAt(i); + } + s=""; + s=s+c; + c--; + for(d=c;d>='0';d--) + { + for(i=0;i +{ + @Override + public int compare(AdjListNode node1, AdjListNode node2) + { + if (node1.weight < node2.weight) + return -1; + if (node1.weight > node2.weight) + return 1; + return 0; + } +} + +class Dijkstras +{ + public int[] dijkstras(List> adj_list,int source) + { + int[] distance = new int[adj_list.size()]; + Set completed = new HashSet(); + for(int i=0;i pq = new PriorityQueue<>(adj_list.size(),new NodeComparator()); + AdjListNode source_node = new AdjListNode(source,0); + for(int i=0;i (distance[current.dest]+n.weight)) + { + distance[n.dest] = distance[current.dest]+n.weight; + pq.add(new AdjListNode(n.dest, distance[n.dest])); + } + } + } + } + return distance; + } + + public static void main(String args[]) + { + /* + SAMPLE INPUT AND OUTPUT + ___________________________ + + Input: + __________ + Please enter the number of nodes N. Vertices will be [0,N-1] + 6 + Please Enter the number of Edges + 9 + Please enter each edge in the sequence + 0 1 1 + 0 2 5 + 1 2 2 + 1 4 1 + 1 3 2 + 2 4 2 + 3 5 1 + 3 4 3 + 4 5 2 + Please enter source vertex + 0 + + Output: + ___________ + Distances from source 0 + Node0--->0 + Node1--->1 + Node2--->3 + Node3--->3 + Node4--->2 + Node5--->4 + */ + + List> adj_list = new ArrayList>(); + System.out.println("Please enter the number of nodes N. Vertices will be [0,N-1]"); + Scanner sc = new Scanner(System.in); + int v = sc.nextInt(); + for(int i=0;i()); + + System.out.println("Please enter the number of edges"); + int e = sc.nextInt(); + System.out.println("Please enter each edge in the sequence "); + // Sample Data: 0 2 5 (edge from 0 to 2 with weight 5) + for(int i=0;i"+"infinity"); + else + System.out.println("Node"+i+"--->"+distances[i]); + } + } +} diff --git a/algorithms/Java/linked-lists/circular.java b/algorithms/Java/linked-lists/circular.java new file mode 100644 index 00000000..3d6067dc --- /dev/null +++ b/algorithms/Java/linked-lists/circular.java @@ -0,0 +1,69 @@ +class CircularLinkedList{ + class Node { + int value; + Node next; + + public Node(int value) { + this.value = value; + } + } + + private Node head = null; + private Node tail = null; + + public void addNode(int value) { + Node newNode = new Node(value); + + if (head == null) { + head = newNode; + } else { + tail.next = newNode; + } + + tail = newNode; + tail.next = head; + } + public void printNodes() { + Node current = head; + if(head == null) { + System.out.println("List is empty"); + return; + } + System.out.println("The circular linked list is: "); + System.out.print("[ "); + do{ + System.out.print(current.value + " "); + current = current.next; + //go to next until we get back to the head + }while(current != head); + System.out.println("]"); + } +} + +public class circular { + public static void main(String [] args){ + CircularLinkedList cll = new CircularLinkedList(); + + cll.addNode(10); + cll.addNode(12); + cll.addNode(2); + cll.addNode(1); + cll.addNode(8); + cll.addNode(42); + cll.addNode(17); + + cll.printNodes(); + + //this will print : + /* + The circular linked list is: + [ 10 12 2 1 8 42 17 ] + */ + } +} + +/* + to run the file: + javac circular.java + java circular +*/ \ No newline at end of file diff --git a/algorithms/Java/linked-lists/clone-linkedlist-with-rnd-pointer.java b/algorithms/Java/linked-lists/clone-linkedlist-with-rnd-pointer.java new file mode 100644 index 00000000..c1849ae7 --- /dev/null +++ b/algorithms/Java/linked-lists/clone-linkedlist-with-rnd-pointer.java @@ -0,0 +1,125 @@ +// Java program to clone a linked list with random pointers +import java.util.HashMap; +import java.util.Map; + +// Linked List Node class +class Node +{ + int data;//Node data + Node next, random;//Next and random reference + + //Node constructor + public Node(int data) + { + this.data = data; + this.next = this.random = null; + } +} + +// linked list class +class LinkedList +{ + Node head;//Linked list head reference + + // Linked list constructor + public LinkedList(Node head) + { + this.head = head; + } + + // push method to put data always at the head + // in the linked list. + public void push(int data) + { + Node node = new Node(data); + node.next = this.head; + this.head = node; + } + + // Method to print the list. + void print() + { + Node temp = head; + while (temp != null) + { + Node random = temp.random; + int randomData = (random != null)? random.data: -1; + System.out.println("Data = " + temp.data + + ", Random data = "+ randomData); + temp = temp.next; + } + } + + // Actual clone method which returns head + // reference of cloned linked list. + public LinkedList clone() + { + // Initialize two references, one with original + // list's head. + Node origCurr = this.head, cloneCurr = null; + + // Hash map which contains node to node mapping of + // original and clone linked list. + Map map = new HashMap(); + + // Traverse the original list and make a copy of that + // in the clone linked list. + while (origCurr != null) + { + cloneCurr = new Node(origCurr.data); + map.put(origCurr, cloneCurr); + origCurr = origCurr.next; + } + + // Adjusting the original list reference again. + origCurr = this.head; + + // Traversal of original list again to adjust the next + // and random references of clone list using hash map. + while (origCurr != null) + { + cloneCurr = map.get(origCurr); + cloneCurr.next = map.get(origCurr.next); + cloneCurr.random = map.get(origCurr.random); + origCurr = origCurr.next; + } + + //return the head reference of the clone list. + return new LinkedList(map.get(this.head)); + } +} + +// Driver Class +class Main +{ + // Main method. + public static void main(String[] args) + { + // Pushing data in the linked list. + LinkedList list = new LinkedList(new Node(5)); + list.push(4); + list.push(3); + list.push(2); + list.push(1); + + // Setting up random references. + list.head.random = list.head.next.next; + list.head.next.random = + list.head.next.next.next; + list.head.next.next.random = + list.head.next.next.next.next; + list.head.next.next.next.random = + list.head.next.next.next.next.next; + list.head.next.next.next.next.random = + list.head.next; + + // Making a clone of the original linked list. + LinkedList clone = list.clone(); + + // Print the original and cloned linked list. + System.out.println("Original linked list"); + list.print(); + System.out.println("\nCloned linked list"); + clone.print(); + } +} \ No newline at end of file diff --git a/algorithms/Java/linked-lists/doubly.java b/algorithms/Java/linked-lists/doubly.java new file mode 100644 index 00000000..0f63d763 --- /dev/null +++ b/algorithms/Java/linked-lists/doubly.java @@ -0,0 +1,77 @@ +class DoublyLinkedList { + class Node{ + int item; + Node previous; + Node next; + + public Node(int item) { + this.item = item; + } + } + + Node head, tail = null; + + public void addNode(int item) { + Node newNode = new Node(item); + + //if list is empty, head and tail points to newNode + if(head == null) { + head = tail = newNode; + //head's previous will be null + head.previous = null; + //tail's next will be null + tail.next = null; + } + else { + //add newNode to the end of list. tail->next set to newNode + tail.next = newNode; + //newNode->previous set to tail + newNode.previous = tail; + //newNode becomes new tail + tail = newNode; + //tail's next point to null + tail.next = null; + } + } + + public void printNodes() { + Node current = head; + if(head == null) { + System.out.println("Doubly linked list is empty"); + return; + } + System.out.println("The doubly linked list is: "); + System.out.print("[ "); + while(current != null) { + System.out.print(current.item + " "); + //go to next + current = current.next; + } + System.out.print("]"); + } +} + +public class doubly { + public static void main(String [] args){ + DoublyLinkedList dl_List = new DoublyLinkedList(); + + dl_List.addNode(5); + dl_List.addNode(7); + dl_List.addNode(1); + dl_List.addNode(17); + dl_List.addNode(27); + + dl_List.printNodes(); + //this will print : + /* + The doubly linked list is: + [ 5 7 1 17 27 ] + */ + } +} + +/* + to run the file: + javac doubly.java + java doubly +*/ \ No newline at end of file diff --git a/algorithms/Java/linked-lists/reverse.java b/algorithms/Java/linked-lists/reverse.java new file mode 100644 index 00000000..28d04ede --- /dev/null +++ b/algorithms/Java/linked-lists/reverse.java @@ -0,0 +1,78 @@ +class LinkedList{ + class Node{ + int item; + Node next; + + public Node(int item) { + this.item = item; + } + } + + Node head = null; + + public void addNode(int item){ + Node newElem = new Node(item); + + if(this.head != null){ + newElem.next = this.head; + } + + this.head = newElem; + } + + public void reverse(){ + Node prev = null; + Node current = this.head; + Node next = null; + + while (current != null) { + next = current.next; + current.next = prev; + prev = current; + current = next; + } + this.head =prev; + } + + public void print() { + Node current = head; + if(head == null) return; + System.out.print("[ "); + while(current != null) { + System.out.print(current.item + " "); + current = current.next; + } + System.out.println("]"); + } +} + +public class reverse{ + + public static void main(String [] args){ + LinkedList list = new LinkedList(); + + list.addNode(2); + list.addNode(7); + list.addNode(1); + list.addNode(8); + list.addNode(5); + + System.out.print("before : \t"); + list.print(); + + list.reverse(); + + System.out.print("after reverse : "); + list.print(); + } +} + +/* + to run the file : + javac reverse.java + java reverse + + results : + before : [ 5 8 1 7 2 ] + after reverse : [ 2 7 1 8 5 ] +*/ \ No newline at end of file diff --git a/algorithms/Java/linked-lists/singly.java b/algorithms/Java/linked-lists/singly.java new file mode 100644 index 00000000..779e46fc --- /dev/null +++ b/algorithms/Java/linked-lists/singly.java @@ -0,0 +1,64 @@ +class Node { + T data; + Node next; + + Node(T data) { + this.data = data; + this.next = null; + } +} + +public class SinglyLinkedList { + Node head; + + SinglyLinkedList() { + this.head = null; + } + + void insertAtHead(T data) { + Node newNode = new Node(data); + if(this.head == null) { + this.head = newNode; + } else { + newNode.next = this.head; + this.head = newNode; + } + } + + T removeAtHead() { + // check for underflow + if(this.head == null) { + System.out.println("Underflow"); + System.exit(1); + } + // store data for return + T data = this.head.data; + this.head = this.head.next; + return data; + } + + void printList() { + // if head is null then list is empty + if(this.head == null) { + System.out.println("List is Empty"); + } else { + // take itr same as head reference and loop through it until it became null + Node itr = this.head; + while(itr != null) { + System.out.print(itr.data + " "); + itr = itr.next; + } + System.out.println(""); + } + } + + // Test Code + public static void main(String... args) { + SinglyLinkedList l = new SinglyLinkedList(); + l.insertAtHead("abc"); + l.insertAtHead("pqr"); + l.insertAtHead("xyz"); + l.removeAtHead(); + l.printList(); + } +} diff --git a/algorithms/Java/queues/circular-queue-linked-list.java b/algorithms/Java/queues/circular-queue-linked-list.java new file mode 100644 index 00000000..0d182717 --- /dev/null +++ b/algorithms/Java/queues/circular-queue-linked-list.java @@ -0,0 +1,96 @@ +// Java program for insertion and +// deletion in Circular Queue +import java.util.*; + +class Solution { + + // Structure of a Node + static class Node { + int data; + Node link; + } + + static class Queue { + Node front, rear; + } + + // Function to create Circular queue + static void enQueue(Queue q, int value) + { + Node temp = new Node(); + temp.data = value; + if (q.front == null) + q.front = temp; + else + q.rear.link = temp; + + q.rear = temp; + q.rear.link = q.front; + } + + // Function to delete element from Circular Queue + static int deQueue(Queue q) + { + if (q.front == null) { + System.out.printf("Queue is empty"); + return Integer.MIN_VALUE; + } + + // If this is the last node to be deleted + int value; // Value to be dequeued + if (q.front == q.rear) { + value = q.front.data; + q.front = null; + q.rear = null; + } + else // There are more than one nodes + { + Node temp = q.front; + value = temp.data; + q.front = q.front.link; + q.rear.link = q.front; + } + + return value; + } + + // Function displaying the elements of Circular Queue + static void displayQueue(Queue q) + { + Node temp = q.front; + System.out.printf("\nElements in Circular Queue are: "); + while (temp.link != q.front) { + System.out.printf("%d ", temp.data); + temp = temp.link; + } + System.out.printf("%d", temp.data); + } + + /* Driver of the program */ + public static void main(String args[]) + { + // Create a queue and initialize front and rear + Queue q = new Queue(); + q.front = q.rear = null; + + // Inserting elements in Circular Queue + enQueue(q, 14); + enQueue(q, 22); + enQueue(q, 6); + + // Display elements present in Circular Queue + displayQueue(q); + + // Deleting elements from Circular Queue + System.out.printf("\nDeleted value = %d", deQueue(q)); + System.out.printf("\nDeleted value = %d", deQueue(q)); + + // Remaining elements in Circular Queue + displayQueue(q); + + enQueue(q, 9); + enQueue(q, 20); + displayQueue(q); + } +} + \ No newline at end of file diff --git a/algorithms/Java/queues/queue-linked-list.java b/algorithms/Java/queues/queue-linked-list.java new file mode 100644 index 00000000..560eb22c --- /dev/null +++ b/algorithms/Java/queues/queue-linked-list.java @@ -0,0 +1,78 @@ +// Java program for linked-list implementation of queue + +// A linked list (LL) node to store a queue entry +class QNode { + int key; + QNode next; + + // constructor to create a new linked list node + public QNode(int key) + { + this.key = key; + this.next = null; + } +} + +// A class to represent a queue +// The queue, front stores the front node of LL and rear stores the +// last node of LL +class Queue { + QNode front, rear; + + public Queue() + { + this.front = this.rear = null; + } + + // Method to add an key to the queue. + void enqueue(int key) + { + + // Create a new LL node + QNode temp = new QNode(key); + + // If queue is empty, then new node is front and rear both + if (this.rear == null) { + this.front = this.rear = temp; + return; + } + + // Add the new node at the end of queue and change rear + this.rear.next = temp; + this.rear = temp; + } + + // Method to remove an key from queue. + void dequeue() + { + // If queue is empty, return NULL. + if (this.front == null) + return; + + // Store previous front and move front one node ahead + QNode temp = this.front; + this.front = this.front.next; + + // If front becomes NULL, then change rear also as NULL + if (this.front == null) + this.rear = null; + } +} + +// Driver class +public class Test { + public static void main(String[] args) + { + Queue q = new Queue(); + q.enqueue(10); + q.enqueue(20); + q.dequeue(); + q.dequeue(); + q.enqueue(30); + q.enqueue(40); + q.enqueue(50); + q.dequeue(); + System.out.println("Queue Front : " + q.front.key); + System.out.println("Queue Rear : " + q.rear.key); + } +} \ No newline at end of file diff --git a/algorithms/Java/scheduling/multi-level-queue-scheduling.java b/algorithms/Java/scheduling/multi-level-queue-scheduling.java new file mode 100644 index 00000000..07776e4b --- /dev/null +++ b/algorithms/Java/scheduling/multi-level-queue-scheduling.java @@ -0,0 +1,321 @@ +/** + * @author Tawfik Yasser + * @since 4-2021 + * */ +// Program imports below +import java.util.ArrayList; +import java.util.Scanner; +// The following class to represent the process +// ** In future i will fix the name "process" to "Process" +class process { + String name; + int burset_time; + int arrive_time; + int waiting_time; + int turn_round_time; + int temp_time; + int queueNumber; + + //Priority Algorithm + private int processID; + private int priority; + + public process() { + this.processID = 0; + this.priority = 0; + this.arrive_time = 0; + this.burset_time = 0; + } + + public process(String name, int burset_time, int arrive_time) { + this.arrive_time = arrive_time; + this.burset_time = burset_time; + this.name = name; + this.temp_time = burset_time; + } + + public process(String name, int burset_time, int arrive_time, int queueNumber) { + this.name = name; + this.burset_time = burset_time; + this.arrive_time = arrive_time; + this.queueNumber = queueNumber; + } + + public process(int processID, int priority, int arrivingTime, int burstTime) { + this.processID = processID; + this.priority = priority; + this.arrive_time = arrivingTime; + this.burset_time = burstTime; + } + + public int getProcessID() { + return processID; + } + + public void setProcessID(int processID) { + this.processID = processID; + } + + public int getPriority() { + return priority; + } + + public void setPriority(int priority) { + this.priority = priority; + } + + public void setWaiting_time(int waiting_time) { + this.waiting_time = waiting_time; + } + + public void setTurn_round_time(int turn_round_time) { + this.turn_round_time = turn_round_time; + } + + public void setTemp_burset_time(int temp_burset_time) { + this.temp_time = temp_burset_time; + } + + public int getWaiting_time() { + return waiting_time; + } + + public int getTurn_round_time() { + return turn_round_time; + } + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public void setBurset_time(int burset_time) { + this.burset_time = burset_time; + } + + public void setArrive_time(int arrive_time) { + this.arrive_time = arrive_time; + } + + public int getBurset_time() { + return burset_time; + } + + public int getTemp_burset_time() { + return temp_time; + } + + public int getArrive_time() { + return arrive_time; + } + + public int getQueueNumber() { + return queueNumber; + } + + public void setQueueNumber(int queueNumber) { + this.queueNumber = queueNumber; + } + + public void reduceTime(int time) { + if(burset_time >= time) + burset_time = burset_time - time; + } +} + +// ****************** The following class to start the MLQ Algorithm, Called from the main +class MultiLevelQueueScheduling { + public MultiLevelQueueScheduling() { + + } + + public void MLQ(int number,process[] processes,int quantum){ + float totalwt = 0, totaltat = 0; + int[] completionTime = new int[number], waitingTime = new int[number], turnaroundTime = new int[number]; + ArrayList RRQueue = new ArrayList(); // Queue to store Round Robin Processes Indexes + ArrayList FCFSQueue = new ArrayList(); // Queue to store FCFS Processes Indexes + + for (int i = 0; i < number; i++) { + if (processes[i].getQueueNumber() == 1) { + RRQueue.add(i); + }else{ + FCFSQueue.add(processes[i].getQueueNumber()); + } + } + + int[] highPriorityProcessArray = new int[number]; // Array to work on it instead of the RRQueue + for (int i = 0; i < RRQueue.size(); i++) { + highPriorityProcessArray[i] = RRQueue.get(i); + } + + int rem_bt[] = new int[RRQueue.size()]; // Array to store the burst time of each process from RRQueue and work on it. + for (int i = 0; i < RRQueue.size(); i++) { + rem_bt[i] = processes[highPriorityProcessArray[i]].getBurset_time(); + } + int rem_bt_2[] = new int[FCFSQueue.size()]; // Array to store the burst time of each process from FCFSQueue and work on it. + for (int i =0;i 0) { + //System.out.println("Process "+processes[RRQueue.get(i)].getName()+" Arrived Now - Time: "+t); + // Check again for burst time if still greater than 0 + if (rem_bt[i] > 0) { + done = false; // Processes still working + + //Checking if the process still has burst time + if (rem_bt[i] > quantum) { + System.out.println("Process "+processes[RRQueue.get(i)].getName()+" Running Now."); + // Increase the value of t of the program and shows how much time a process has been processed. + t += quantum; + // Decrease the burst_time of current process by quantum + rem_bt[i] -= quantum; + } + // If burst time is smaller than or equal to quantum. So this is the last loop this process + else { + System.out.println("Process "+processes[RRQueue.get(i)].getName()+" Running Now."); + // Increase the value of t + t = t + rem_bt[i]; + completionTime[highPriorityProcessArray[i]] = t; //Calculate that process completion time. + //--> [Turnaround Time = Completion Time - Arrival Time] + turnaroundTime[highPriorityProcessArray[i]] = completionTime[highPriorityProcessArray[i]] + - processes[highPriorityProcessArray[i]].getArrive_time();//Calculate the process turnaround time + //--> [Waiting Time = Turnaround Time - Burst Time] + waitingTime[highPriorityProcessArray[i]] = turnaroundTime[highPriorityProcessArray[i]] + - processes[highPriorityProcessArray[i]].getBurset_time();//Calculating the process waiting time + // And finally that process finished it’s work so the burst time will be ZERO now. + rem_bt[i] = 0; + System.out.println("Process "+processes[RRQueue.get(i)].getName()+" Finished Work - Time: "+t); + } + } + + } + + //Here we are check if there are another processes need to work in the second queue. + flag=0; + for(int k = 0 ; k t){ + flag++; + } + } + } + //Position a variable to store the position of the processes from the second queue. + int position =0; + if(flag==RRQueue.size()){ + //Looping on the second queue and execute the processes until the first queue filled again. + for (int j = 0; j < FCFSQueue.size(); j++) { + String fl = " ";//Flag + do{ + //System.out.println("Process "+processes[FCFSQueue.get(j)].getName()+" Arrived Now - Time: "+t); + //The following loop to get the process position. + for(int y =0;y0); + if(!fl.equals(" ")){ + break; + } + } + } + + // If all processes are done their execution. + if (done == true) + break; + } + + + //Printing the final results of execution. + System.out.println("\nProcess Name\t\t Queue Number \tBurst Time \tCompletion Time \tWaiting Time \tTurnaround Time"); + for (int i = 0; i < number; i++) { + System.out.println("\n\t" + processes[i].getName() + "\t\t\t\t\t" + processes[i].getQueueNumber() + "\t\t\t\t" + processes[i].getBurset_time() + "\t\t\t\t" + completionTime[i] + "\t\t\t\t" + waitingTime[i] + "\t\t\t\t" + turnaroundTime[i]); + } + + //Calculating the AVG Waiting Time and Turnaround Time + for (int i = 0; i < number; i++) { + totalwt += waitingTime[i]; + totaltat += turnaroundTime[i]; + } + System.out.println("\n" + "Average Waiting Time is: " + totalwt / number); + System.out.println("Average Turnaround Time is : " + totaltat / number); + } +} + +// The following is the Main function to run the program + +public class Main { + public static void main(String[] args) { + System.out.print("\n"); + System.out.println("Welcome to the CPU Scheduler Simulator >>>>> (OS)"); + System.out.println("-------------------------------------------------"); + System.out.println("Running the Multi-Level Queue Scheduling Algorithm"); + multiLevelScheduling(); + } + + public static void multiLevelScheduling() { + int quantum = 0; + int number; + System.out.println("Enter number of processes: "); + Scanner scanner = new Scanner(System.in); + number = scanner.nextInt(); + process[] processes = new process[number]; + + for (int i = 0; i < number; i++) { + + System.out.println("Enter the name of process " + (i + 1) + " : "); + String name = scanner.next(); + System.out.println("Enter the arrival time of process " + (i + 1) + " : "); + int arrival = scanner.nextInt(); + System.out.println("Enter the burst time of process " + (i + 1) + " : "); + int burst = scanner.nextInt(); + System.out.println("Enter the queue number of process " + (i + 1) + " : "); + int qNumber = scanner.nextInt(); + + process process = new process(name, burst, arrival, qNumber); + processes[i] = process; + } + System.out.println("Enter the quantum time: "); + quantum = scanner.nextInt(); + MultiLevelQueueScheduling multiLevelQueueScheduling = new MultiLevelQueueScheduling(); + multiLevelQueueScheduling.MLQ(number,processes,quantum); + + } +} \ No newline at end of file diff --git a/algorithms/Java/scheduling/round-robin.java b/algorithms/Java/scheduling/round-robin.java new file mode 100644 index 00000000..41f5b4cd --- /dev/null +++ b/algorithms/Java/scheduling/round-robin.java @@ -0,0 +1,279 @@ +/** + * @author Tawfik Yasser + * @since 4-2021 + * */ +// Program imports below +import java.util.ArrayList; +import java.util.Scanner; +import java.util.Collections; +import java.util.Comparator; + +// The following class to represent the process +// ** In future i will fix the name "process" to "Process" +class process { + String name; + int burset_time; + int arrive_time; + int waiting_time; + int turn_round_time; + int temp_time; + int queueNumber; + + //Priority Algorithm + private int processID; + private int priority; + + public process() { + this.processID = 0; + this.priority = 0; + this.arrive_time = 0; + this.burset_time = 0; + } + + public process(String name, int burset_time, int arrive_time) { + this.arrive_time = arrive_time; + this.burset_time = burset_time; + this.name = name; + this.temp_time = burset_time; + } + + public process(String name, int burset_time, int arrive_time, int queueNumber) { + this.name = name; + this.burset_time = burset_time; + this.arrive_time = arrive_time; + this.queueNumber = queueNumber; + } + + public process(int processID, int priority, int arrivingTime, int burstTime) { + this.processID = processID; + this.priority = priority; + this.arrive_time = arrivingTime; + this.burset_time = burstTime; + } + + public int getProcessID() { + return processID; + } + + public void setProcessID(int processID) { + this.processID = processID; + } + + public int getPriority() { + return priority; + } + + public void setPriority(int priority) { + this.priority = priority; + } + + public void setWaiting_time(int waiting_time) { + this.waiting_time = waiting_time; + } + + public void setTurn_round_time(int turn_round_time) { + this.turn_round_time = turn_round_time; + } + + public void setTemp_burset_time(int temp_burset_time) { + this.temp_time = temp_burset_time; + } + + public int getWaiting_time() { + return waiting_time; + } + + public int getTurn_round_time() { + return turn_round_time; + } + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public void setBurset_time(int burset_time) { + this.burset_time = burset_time; + } + + public void setArrive_time(int arrive_time) { + this.arrive_time = arrive_time; + } + + public int getBurset_time() { + return burset_time; + } + + public int getTemp_burset_time() { + return temp_time; + } + + public int getArrive_time() { + return arrive_time; + } + + public int getQueueNumber() { + return queueNumber; + } + + public void setQueueNumber(int queueNumber) { + this.queueNumber = queueNumber; + } + + public void reduceTime(int time) { + if(burset_time >= time) + burset_time = burset_time - time; + } +} + +// ****************** The following class to start the Round Robin Algorithm, Called from the main + +class RoundRobin { + public ArrayList round_processes=new ArrayList<>(); + private int Quantum_time; + private int total_time; + + public void setContext_switching(int context_switching) { + this.context_switching = context_switching; + } + + public int getContext_switching() { + return context_switching; + } + + private int context_switching; + void setQuantum_time(int q) + { + this.Quantum_time=q; + } + private void sort_process () + { + Collections.sort(round_processes, Comparator.comparing(process :: getArrive_time)); + } + void round_robien () + { + sort_process(); + int flag=0,i=0,temp; + while (flag!=round_processes.size()) + { + if (round_processes.get(i).getBurset_time()!=0) + { + + if (round_processes.get(i).getBurset_time()>=Quantum_time) + { + System.out.println("process :"+round_processes.get(i).getName()+"is running"); + total_time+=Quantum_time; + temp=round_processes.get(i).getBurset_time(); + temp-=Quantum_time; + round_processes.get(i).setBurset_time(temp); + if (temp==0) + { + flag++; + round_processes.get(i).setTurn_round_time(total_time); + System.out.println("process :"+round_processes.get(i).getName()+"is terminated"); + i++; + } + else { + System.out.println("process :"+round_processes.get(i).getName()+"is waiting"); + i++;} + total_time+=context_switching; + + } + else if (round_processes.get(i).getBurset_time()>>>> (OS)"); + System.out.println("-------------------------------------------------"); + System.out.println("Running the Round Robin Scheduling Algorithm"); + RRAlgorithm(); + } + + public static void RRAlgorithm() { + RoundRobin r1=new RoundRobin(); + int number,quantam,burset_time,arrive_time,con; + Scanner input=new Scanner(System.in); + System.out.println("enter number of process"); + number=input.nextInt(); + process p2; + String name; + for (int i=0;i= l) { + int mid = l + (r - l) / 2; + + // If the element is present at the + // middle itself + if (arr[mid] == x) + return mid; + + // If element is smaller than mid, then + // it can only be present in left subarray + if (arr[mid] > x) + return binarySearch(arr, l, mid - 1, x); + + // Else the element can only be present + // in right subarray + return binarySearch(arr, mid + 1, r, x); + } + + // We reach here when element is not present + // in array + return -1; + } + + // Driver method to test above + public static void main(String args[]) + { + BinarySearch ob = new BinarySearch(); + int arr[] = { 2, 3, 4, 10, 40 }; + int n = arr.length; + int x = 10; + int result = ob.binarySearch(arr, 0, n - 1, x); + if (result == -1) + System.out.println("Element not present"); + else + System.out.println("Element found at index " + result); + } +} + +// For running in terminal rename this file to BinarySearch.java +//then run the commands followed by +//It will generate and a BinarySearch.class file which is a file containing java bytecode that is executed by JVM. diff --git a/algorithms/Java/searching/jump-search.java b/algorithms/Java/searching/jump-search.java new file mode 100644 index 00000000..d90cdd6b --- /dev/null +++ b/algorithms/Java/searching/jump-search.java @@ -0,0 +1,55 @@ +// Java program to implement Jump Search. +public class JumpSearch +{ + public static int jumpSearch(int[] arr, int x) + { + int n = arr.length; + + // Finding block size to be jumped + int step = (int)Math.floor(Math.sqrt(n)); + + // Finding the block where element is + // present (if it is present) + int prev = 0; + while (arr[Math.min(step, n)-1] < x) + { + prev = step; + step += (int)Math.floor(Math.sqrt(n)); + if (prev >= n) + return -1; + } + + // Doing a linear search for x in block + // beginning with prev. + while (arr[prev] < x) + { + prev++; + + // If we reached next block or end of + // array, element is not present. + if (prev == Math.min(step, n)) + return -1; + } + + // If element is found + if (arr[prev] == x) + return prev; + + return -1; + } + + // Driver program to test function + public static void main(String [ ] args) + { + int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, + 34, 55, 89, 144, 233, 377, 610}; + int x = 55; + + // Find the index of 'x' using Jump Search + int index = jumpSearch(arr, x); + + // Print the index where 'x' is located + System.out.println("\nNumber " + x + + " is at index " + index); + } +} \ No newline at end of file diff --git a/algorithms/Java/searching/linear-search.java b/algorithms/Java/searching/linear-search.java new file mode 100644 index 00000000..4c8e2d3b --- /dev/null +++ b/algorithms/Java/searching/linear-search.java @@ -0,0 +1,21 @@ +//Linear search to check for a given key in an array + +public class MyLinearSearch{ +public static int linearSearch(int[] arr, int key){ + for(int i=0;i followed by +//It will generate and a MyLinearSearch.class file which is a file containing java bytecode that is executed by JVM. diff --git a/algorithms/Java/sorting/bubble-sort.java b/algorithms/Java/sorting/bubble-sort.java new file mode 100644 index 00000000..61b88316 --- /dev/null +++ b/algorithms/Java/sorting/bubble-sort.java @@ -0,0 +1,27 @@ + +import java.util.Arrays; + +public class BubbleSort { + static int temp = 0; + static int[] nums = { 13, 34, 12, 45, 56, 32, 20 }; + + public static void main(String[] args) { + + System.out.println("Before Sorting : "+Arrays.toString(nums)); + sort(); + + } + //create method sorting array + public static void sort() { + for (int i = 1; i < nums.length; i++) { + for (int j = 0; j < i; j++) { + if (nums[j] > nums[i]) { + temp = nums[j]; + nums[j] = nums[i]; + nums[i] = temp; + } + } + } + System.out.println(Arrays.toString(nums)); + } +} \ No newline at end of file diff --git a/algorithms/Java/sorting/counting-sort.java b/algorithms/Java/sorting/counting-sort.java new file mode 100644 index 00000000..36894d57 --- /dev/null +++ b/algorithms/Java/sorting/counting-sort.java @@ -0,0 +1,74 @@ +public class CountingSort { + + /** + * Public method to use the counting sort algorithm + * @param arr - the array in input + */ + public void sort(int[] arr){ + + int[] sortedArray = new int[arr.length + 1]; + + // Search max element + int max = arr[0]; + for(int i = 0; i < arr.length; i++){ + if(arr[i] > max){ + max = arr[i]; + } + } + + // Create counting array + int[] countArray = new int[max + 1]; + for(int i = 0; i < countArray.length; i++){ + countArray[i] = 0; + } + + // Count elements in array + for(int i = 0; i < arr.length; i++){ + countArray[arr[i]]++; + } + + + for(int i = 1; i < countArray.length; i++){ + countArray[i] += countArray[i - 1]; + } + + for (int i = arr.length - 1; i >= 0; i--) { + sortedArray[countArray[arr[i]] - 1] = arr[i]; + countArray[arr[i]]--; + } + + System.arraycopy(sortedArray, 0, arr, 0, arr.length); + } + + /** + * Main method for testing + * @param args + */ + public static void main(String[] args) throws Exception { + CountingSort count = new CountingSort(); + + int[] test = {1,9,8,7,6,5,4,3,2,12,546,23,123,5768,689,45,6342,0,76,856,34,412,12,32,353,46,568,456,234,3456,467,345345,345,345,}; + + count.sort(test); + + for(int i = 1; i < test.length; i++){ + if(test[i] < test[i - 1]){ + throw new Exception("[ERROR] Ops! Counting sort not work!"); + } + } + + printArray(test); + } + + /** + * Print an array + * @param arr + */ + public static void printArray(int[] arr){ + + System.out.println("Sorted array: "); + for(int i = 0; i < arr.length; i++){ + System.out.println(" " + i); + } + } +} diff --git a/algorithms/Java/sorting/heap-sort.java b/algorithms/Java/sorting/heap-sort.java new file mode 100644 index 00000000..aa2d908f --- /dev/null +++ b/algorithms/Java/sorting/heap-sort.java @@ -0,0 +1,69 @@ + +import java.util.Scanner; +public class HeapSort +{ + public void sort(int array[]) + { + + int n = array.length; + for (int i = n / 2 - 1; i >= 0; i--) + heapify(array, n, i); + for (int i = n-1; i >= 0; i--) + { + + int temp = array[0]; + array[0] = array[i]; + array[i] = temp; + + + heapify(array, i, 0); + } + } + + + void heapify(int array[], int n, int i) + { + int largest = i; + int l = 2*i + 1; + int r = 2*i + 2; + + if (l < n && array[l] > array[largest]) + largest = l; +if (r < n && array[r] > array[largest]) + largest = r; + + + if (largest != i) + { + int swap = array[i]; + array[i] = array[largest]; + array[largest] = swap; + + + heapify(array, n, largest); + } + } + public static void main(String args[]) + { + + System.out.println("enter the array size"); + Scanner inputobj = new Scanner(System.in); + int s = inputobj.nextInt(); + int array[] = new int[s]; + System.out.println("enter " + s + "elements of array"); + for(int k=0;k 0 && nums[j - 1] > temp) { + nums[j] = nums[j - 1]; + j--; + } + nums[j] = temp; + i++; + } + System.out.println("After Sorting " + Arrays.toString(nums)); + + } +} \ No newline at end of file diff --git a/algorithms/Java/sorting/merge-sort.java b/algorithms/Java/sorting/merge-sort.java new file mode 100644 index 00000000..3b8f6645 --- /dev/null +++ b/algorithms/Java/sorting/merge-sort.java @@ -0,0 +1,79 @@ +//Java program for implementation of Merge Sort +import java.util.*; + +class MergeSortApp +{ + private int[] arr; + public MergeSortApp() + { + arr = new int[]{12,54,222,54622,10,169,30}; //Array to sort + } + + //Function to display/Print Array + public void printArray() + { + for (int i=0;i0 && arr[--rightptr]>pivot); //Find smaller item + + if (leftptr>=rightptr) //if index numbers cross,partition is done + break; + else + swap(leftptr,rightptr); //swap elements + + } + swap(leftptr,right); //restore pivot element + return leftptr; //return pivot location + } + + //Recursive quicksort function + public void recQuickSort(int left,int right) + { + if (right-left <= 0) // already sorted if size is 1 + return; + else + { + int pivot = arr[right]; //choosing pivot as rightmost(end) element of Array + int partition = partitionFn(left,right,pivot); + recQuickSort(left,partition-1); //Sort left + recQuickSort(partition+1,right); //Sort right + + } + } + + //function called in main + public void quickSort() + { + recQuickSort(0,arr.length-1); + } +} + +class QuickSort +{ + //Driver code to test above + public static void main(String[] args) { + + QuickSortBack ob = new QuickSortBack(); + ob.displayArray(); //display array before sort + ob.quickSort(); //call quickSort + ob.displayArray(); + } +} diff --git a/algorithms/Java/sorting/selection-sort.java b/algorithms/Java/sorting/selection-sort.java new file mode 100644 index 00000000..a770eaf7 --- /dev/null +++ b/algorithms/Java/sorting/selection-sort.java @@ -0,0 +1,50 @@ +class Selection +{ + + int minIndex(int Array[] , int start, int end) + { + int minIndex = start; + + for (int i = start+1; i < end; i++) + { + if ( Array[i] < Array[minIndex] ) + { + minIndex = i; + } + } + return minIndex; + } + int[] sorting(int Array[],int length) + { + for (int i = 0; i < length-1; i++) + { + int minI = minIndex(Array, i, length); + int temp = Array[minI]; + Array[minI] = Array[i]; + Array[i] = temp; + } + return Array; + } +} + +/** + * SelectionSort + */ +public class SelectionSort { + + public static void main(String[] args) { + + int Array[] = {1,2,3,4,5,6,7,8,9}; + + Selection s1 = new Selection(); + long startTime = System.nanoTime(); + int sortedArray[] = s1.sorting(Array, 9); + long endTime = System.nanoTime(); + + for (int i = 0; i < 9; i++) { + System.out.println(sortedArray[i]); + } + System.out.println("Total Time in Neno Second: "+ (endTime-startTime)); + + } +} diff --git a/algorithms/Java/stacks/balanced-paranthesis.java b/algorithms/Java/stacks/balanced-paranthesis.java new file mode 100644 index 00000000..386c9d70 --- /dev/null +++ b/algorithms/Java/stacks/balanced-paranthesis.java @@ -0,0 +1,69 @@ + + +import java.util.Iterator; +import java.util.Stack; +import java.util.Vector; + +class Balanced_Paranthesis { + + public void problem(String input_string){ + + Vector output = new Vector<>(); + + Stack sta = new Stack<>(); + + for(int i = 0;i < input_string.length();i++){ + for (int j = 0; j <= i; j++){ + String sub_s = input_string.substring(j,i+1); + char[] sub = sub_s.toCharArray(); + int no_of_left_paranthesis = 0; + int no_of_right_paranthesis = 0; + for (int k = 0;k < sub_s.length();k++){ + if(sub[k] == '('){ + no_of_left_paranthesis = no_of_left_paranthesis + 1; + sta.push('('); + } + if(sub[k] == ')'){ + no_of_right_paranthesis = no_of_right_paranthesis + 1; + sta.pop(); + } + + if (sub_s.length() % 2 == 0 && no_of_left_paranthesis == no_of_right_paranthesis && sta.isEmpty()){ + output.add(sub_s); + } + else{ + while (!sta.isEmpty()){ + sta.pop(); + } + } + } + } + + int length = 0; + if (output.size() == 0){ + System.out.println(length + " "); + } + else{ + int max_len = 0; + String long_Str = ""; + + for(int s = 0;s < output.size();s++){ + if (output.get(s).length() > max_len){ + max_len = output.get(s).length(); + long_Str = output.get(s); + } + } + System.out.println("Maximum length of string : " + max_len + "and the string is : " + long_Str); + } + } + } +} + +class Main { + + public static void main(String[] args){ + Balanced_Paranthesis bal = new Balanced_Paranthesis(); + bal.problem("((()))"); + } +} + diff --git a/algorithms/Java/stacks/stack.java b/algorithms/Java/stacks/stack.java new file mode 100644 index 00000000..bf884e76 --- /dev/null +++ b/algorithms/Java/stacks/stack.java @@ -0,0 +1,93 @@ + + + class stack { + public int Max; + public int Top; + public int[] stack; + + public stack(int Max){ + this.Max = Max; + stack = new int[Max]; + Top = -1; + } + + /** + * if the stack is empty then always the top will be -1 + * so this should return a boolean if value of top < 1 then returns true which means + * stack is empty. + */ + public boolean isEmpty(){ + return (Top < 0); + } + + public int size(){ + return (Top+1); + } + + public void push(int x){ + if (size() >= Max){ + System.out.println("Stack Overflow"); + } + else{ + Top = Top + 1; + stack[Top] = x; + } + } + + /** + * pop function pops out the top element in the queue + * returns the element that is popped out of the queue + */ + public int pop(){ + if (size() == 0){ + System.out.println("Stack Empty Exception"); + } + else { + /** + * the top element in the stack will be popped out from the stack + */ + int popped_element = stack[Top]; + Top = Top - 1; + return popped_element; + } + return -1; + } + + public int top(){ + if(isEmpty()){ + System.out.println("Stack Empty Exception"); + } + else{ + return stack[Top]; + } + return -1; + } + + public void PrintStack(){ + if (isEmpty()){ + System.out.println("Empty"); + } + else{ + for(int i = 0;i < size();i++){ + System.out.print(stack[i] + " "); + } + System.out.println(); + } + } + +} +class Main { + + public static void main(String[] args){ + max = 1000; + stack object = new stack(max); + object.push(1); + object.push(2); + object.push(3); + object.pop(); + object.top(); + object.PrintStack(); + } +} + + diff --git a/algorithms/Java/stacks/the-stock-span-problem.java b/algorithms/Java/stacks/the-stock-span-problem.java new file mode 100644 index 00000000..7ee5eba0 --- /dev/null +++ b/algorithms/Java/stacks/the-stock-span-problem.java @@ -0,0 +1,98 @@ + + +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.Stack ; + +/** + * Problem statement : + * The stock span problem is a financial problem where we have a series of n daily price quotes for a stock + * and we need to calculate span of stock’s price for all n days. + * The span Si of the stock’s price on a given day i is defined as the maximum number of consecutive days just before the given day, + * for which the price of the stock on + * the current day is less than or equal to its price on the given day. + * For example, if an array of 7 days prices is given as {100, 80, 60, 70, 60, 75, 85}, then the span values for corresponding + * 7 days are {1, 1, 1, 2, 1, 4, 6} + */ +class The_Stock_Span_Problem extends stack{ + + public The_Stock_Span_Problem(int Max) { + super(Max); + } + + /** + * this problem is being solved with stack abstract data type. + */ + public void problem(int[] price,int n,int[] span){ + stack st = new stack(Max); + st.push(0); + + //span of the first day is always going to be 1 + span[0] = 1; + + + for (int i = 1;i < n;i ++){ + span[i] = 1; + st.PrintStack(); + while(!st.isEmpty() && price[st.top()] <= price[i]){ + st.pop(); + } + + if (st.isEmpty()){ + span[i] = i + 1; + } + else{ + span[i] = i - st.top(); + } + st.push(i); + } + printArray(span); + + } + + public void printArray(int[] span){ + System.out.println("The span of the stock array :" + Arrays.toString(span)); + } + + /** + * This is a different approach that has slightly higher time complexity than the approach used above + * Both the methods are awesome and star struck but...xD + */ + public void alternate_approach(int[] price,int n,int[] span){ + + Stack sta = new Stack<>(); + + span[0] = 1; + + for (int i = 1;i < n;i++){ + for (int j = 0;j < i;j++){ + sta.push(j); + } + + while(!sta.isEmpty() && price[sta.peek()] <= price[i]){ + sta.pop(); + } + if (sta.isEmpty()){ + span[i] = i + 1; + } + else{ + span[i] = i - sta.peek(); + } + sta.clear(); + } + printArray(span); + } +} + +class Main { + + //to test the span stock problem + public static void main(String[] args){ + int[] price = { 10, 4, 5, 90, 120, 80 }; + int n = price.length; + int[] span = new int[n]; + + The_Stock_Span_Problem prob = new The_Stock_Span_Problem(1000); + prob.alternate_approach(price,n,span); + } +} diff --git a/algorithms/Java/strings/SplitString.java b/algorithms/Java/strings/SplitString.java new file mode 100644 index 00000000..24b67cf4 --- /dev/null +++ b/algorithms/Java/strings/SplitString.java @@ -0,0 +1,35 @@ +//Separate the strings such as in other group same letter does not repeat. +//Example abcdaef will give 5,1,1 from first 'a' to last 'a' one group and then remaining 2 letters from 1-1 group +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Scanner; + +public class SplitString { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.println("Enter the string"); + String s = sc.next(); + List a = new ArrayList(); + Map last = new HashMap(); + for (int i = 0; i < s.length(); i++) { + last.put(s.charAt(i), i); + } + int p = 0, ctr = 0; + for (int i = 0; i < s.length(); i++) { + if (last.get(s.charAt(i)) > p) + p = last.get(s.charAt(i)); + ++ctr; + if (i == p) { + a.add(ctr); + ctr = 0; + } + + } + for (Integer i : a) { + System.out.println(i); + } + sc.close(); + } +} \ No newline at end of file diff --git a/algorithms/Java/strings/kmp.java b/algorithms/Java/strings/kmp.java new file mode 100644 index 00000000..d720a3f2 --- /dev/null +++ b/algorithms/Java/strings/kmp.java @@ -0,0 +1,82 @@ +class KMP_String_Matching { + void KMPSearch(String pat, String txt) + { + int M = pat.length(); + int N = txt.length(); + + // create lps[] that will hold the longest + // prefix suffix values for pattern + int lps[] = new int[M]; + int j = 0; // index for pat[] + + // Preprocess the pattern (calculate lps[] + // array) + computeLPSArray(pat, M, lps); + + int i = 0; // index for txt[] + while (i < N) { + if (pat.charAt(j) == txt.charAt(i)) { + j++; + i++; + } + if (j == M) { + System.out.println("Found pattern " + + "at index " + (i - j)); + j = lps[j - 1]; + } + + // mismatch after j matches + else if (i < N && pat.charAt(j) != txt.charAt(i)) { + // Do not match lps[0..lps[j-1]] characters, + // they will match anyway + if (j != 0) + j = lps[j - 1]; + else + i = i + 1; + } + } + } + + void computeLPSArray(String pat, int M, int lps[]) + { + // length of the previous longest prefix suffix + int len = 0; + int i = 1; + lps[0] = 0; // lps[0] is always 0 + + // the loop calculates lps[i] for i = 1 to M-1 + while (i < M) { + if (pat.charAt(i) == pat.charAt(len)) { + len++; + lps[i] = len; + i++; + } + else // (pat[i] != pat[len]) + { + // This is tricky. Consider the example. + // AAACAAAA and i = 7. The idea is similar + // to search step. + if (len != 0) { + len = lps[len - 1]; + + // Also, note that we do not increment + // i here + } + else // if (len == 0) + { + lps[i] = len; + i++; + } + } + } + } + + // Driver program to test above function + public static void main(String args[]) + { + String txt = "ABABDABACDABABCABAB"; + String pat = "ABABCABAB"; + new KMP_String_Matching().KMPSearch(pat, txt); + } +} +// This code has been contributed by Amit Khandelwal. diff --git a/algorithms/Java/strings/palindrome.java b/algorithms/Java/strings/palindrome.java new file mode 100644 index 00000000..eafe646d --- /dev/null +++ b/algorithms/Java/strings/palindrome.java @@ -0,0 +1,56 @@ +public class palindrome { + + // Function that returns true if + // str is a palindrome + static boolean isPalindrome(String str) + { + + // Pointers pointing to the beginning + // and the end of the string + int i = 0, j = str.length() - 1; + + // While there are characters toc compare + while (i < j) { + + // If there is a mismatch + if (str.charAt(i) != str.charAt(j)) + return false; + + // Increment first pointer and + // decrement the other + i++; + j--; + } + + // Given string is a palindrome + return true; + } + + //new approach with case sensitive + public static boolean isPalindrome(String str, boolean caseSensitive){ + // lowercase if not case sensitive + if(!caseSensitive) str = str.toLowerCase(); + + for(int i = 0; i < str.length() / 2; i++) + if(str.charAt(i) != str.charAt(str.length() - 1 - i)) + return false; + + return true; + } + + // Driver code + public static void main(String[] args) + { + String str = "Dad"; + + if (isPalindrome(str)) + System.out.println("Yes"); + else + System.out.println("No"); + + if (isPalindrome(str, false)) + System.out.println("Yes"); + else + System.out.println("No"); + } +} diff --git a/algorithms/Java/strings/rabin-karp.java b/algorithms/Java/strings/rabin-karp.java new file mode 100644 index 00000000..376fc0c6 --- /dev/null +++ b/algorithms/Java/strings/rabin-karp.java @@ -0,0 +1,78 @@ +public class Main +{ + // d is the number of characters in the input alphabet + public final static int d = 256; + + /* pat -> pattern + txt -> text + q -> A prime number + */ + static void search(String pat, String txt, int q) + { + int M = pat.length(); + int N = txt.length(); + int i, j; + int p = 0; // hash value for pattern + int t = 0; // hash value for txt + int h = 1; + + // The value of h would be "pow(d, M-1)%q" + for (i = 0; i < M-1; i++) + h = (h*d)%q; + + // Calculate the hash value of pattern and first + // window of text + for (i = 0; i < M; i++) + { + p = (d*p + pat.charAt(i))%q; + t = (d*t + txt.charAt(i))%q; + } + + // Slide the pattern over text one by one + for (i = 0; i <= N - M; i++) + { + + // Check the hash values of current window of text + // and pattern. If the hash values match then only + // check for characters on by one + if ( p == t ) + { + /* Check for characters one by one */ + for (j = 0; j < M; j++) + { + if (txt.charAt(i+j) != pat.charAt(j)) + break; + } + + // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] + if (j == M) + System.out.println("Pattern found at index " + i); + } + + // Calculate hash value for next window of text: Remove + // leading digit, add trailing digit + if ( i < N-M ) + { + t = (d*(t - txt.charAt(i)*h) + txt.charAt(i+M))%q; + + // We might get negative value of t, converting it + // to positive + if (t < 0) + t = (t + q); + } + } + } + + /* Driver Code */ + public static void main(String[] args) + { + String txt = "ABCAMCABAMMAM"; + String pat = "AM"; + + // A prime number + int q = 101; + + // Function Call + search(pat, txt, q); + } +} \ No newline at end of file diff --git a/algorithms/Java/strings/sequence.java b/algorithms/Java/strings/sequence.java new file mode 100644 index 00000000..65df0c5c --- /dev/null +++ b/algorithms/Java/strings/sequence.java @@ -0,0 +1,28 @@ +import java.util.*; +class sequence { + + + static List al = new ArrayList<>(); + + + public static void main(String[] args) + { + String s = "abc"; + findsubsequences(s, ""); + System.out.println(al); + } + + private static void findsubsequences(String s, + String ans) + { + if (s.length() == 0) { + al.add(ans); + return; + } + + + findsubsequences(s.substring(1), ans + s.charAt(0)); + + findsubsequences(s.substring(1), ans); + } +} \ No newline at end of file diff --git a/algorithms/Java/strings/tokenizer.java b/algorithms/Java/strings/tokenizer.java new file mode 100644 index 00000000..ce6c4dc6 --- /dev/null +++ b/algorithms/Java/strings/tokenizer.java @@ -0,0 +1,96 @@ +import java.util.ArrayList; +import java.util.List; + +public class tokenizer{ + + public static boolean charIsDelimiter(char c, char [] delimiters){ + //verrify if a character is a delimiter + for(char d: delimiters) + if(c == d) return true; + + return false; + } + + public static List tokenize(String str, char... delimiters){ + //by default the delimiter is white space ' ' + if(delimiters.length <= 0) delimiters = new char [] {' '}; + + List tokens = new ArrayList(); + String token = ""; + + for(int i = 0; i < str.length(); i++) { + char pos = str.charAt(i); + + if(!charIsDelimiter(pos, delimiters)) { + //if the character is not a delimiter add it into the current token + token += pos; + }else { + //avoid an empty token before adding to the list + if(!token.equals("")) + tokens.add(token); + + token = ""; + } + } + + //add the last token to the list + tokens.add(token); + + return tokens; + } + + public static void printTokens(List tokens){ + if(tokens == null) return; + + System.out.print("[ "); + for(String token : tokens){ + System.out.print("'" + token + "', "); + } + System.out.println("]"); + } + + public static void main(String [] args){ + String myString = "Hello I like pasta & pizza--hut"; + + System.out.println("myString = '" + myString + "'"); + + System.out.print("\ntokenize(myString) = "); + printTokens(tokenize(myString)); + + System.out.print("\ntokenize(myString, ' ', 'z') = "); + printTokens(tokenize(myString, ' ', 'z')); + + System.out.print("\ntokenize(myString, 'p','l', 'u') = "); + printTokens(tokenize(myString, 'p','l', 'u')); + + System.out.print("\ntokenize(myString, ' ', '&', '-') = "); + printTokens(tokenize(myString, ' ', '&', '-')); + } +} + +/* + to call the function: + tokenize(str, delimiters) + str is a text + delimiters is a list of char which is by default white space : ' ' + example: + tokenize("hello world") = tokenize("hello world", ' ') = [ 'hello', 'world' ] + tokenize("hello world", ' ', 'l') = [ 'he', 'o', 'wor', 'd' ] + + + to run this file: + javac tokenizer.java + java tokenizer + + result: + myString = 'Hello I like pasta & pizza--hut' + + tokenize(myString) = [ 'Hello', 'I', 'like', 'pasta', '&', 'pizza--hut', ] + + tokenize(myString, ' ', 'z') = [ 'Hello', 'I', 'like', 'pasta', '&', 'pi', 'a--hut', ] + + tokenize(myString, 'p','l', 'u') = [ 'He', 'o I ', 'ike ', 'asta & ', 'izza--h', 't', ] + + tokenize(myString, ' ', '&', '-') = [ 'Hello', 'I', 'like', 'pasta', 'pizza', 'hut', ] + +*/ diff --git a/algorithms/Java/trees/pre_in_post_traversal.java b/algorithms/Java/trees/pre_in_post_traversal.java new file mode 100644 index 00000000..8997e3e3 --- /dev/null +++ b/algorithms/Java/trees/pre_in_post_traversal.java @@ -0,0 +1,76 @@ +class Node{ + int value; + Node left; + Node right; + + public Node(int value) { + this.value = value; + } +} + +public class pre_in_post_traversal{ + + public static void preOrder(Node node){ + if (node == null) return; + + System.out.print(node.value + ", "); + preOrder(node.left); + preOrder(node.right); + } + + public static void inOrder(Node node){ + if(node == null) return; + + inOrder(node.left); + System.out.print(node.value + ", "); + inOrder(node.right); + } + + public static void postOrder(Node node){ + if(node == null) return; + postOrder(node.left); + postOrder(node.right); + System.out.print(node.value + ", "); + } + + + public static void main(String [] args){ + Node root = new Node(4); + root.left = new Node(2); + root.right = new Node(7); + root.left.right = new Node(6); + root.left.left = new Node(1); + root.right.right = new Node(9); + + System.out.print("pre order: "); + preOrder(root); + + System.out.println("\n"); + System.out.print("in order: "); + inOrder(root); + + System.out.print("\n\npost order: "); + postOrder(root); + } +} + +/* +tree structure: + 4 + / \ + 2 7 + / \ \ +1 6 9 + +to run the file: + javac .\pre_in_post_traversal.java + java pre_in_post_traversal + +results: + pre order: 4, 2, 1, 6, 7, 9, + + in order: 1, 2, 6, 4, 7, 9, + + post order: 1, 6, 2, 9, 7, 4, + +*/