- 75
- 46 838
Kianoosh Boroojeni
United States
เข้าร่วมเมื่อ 28 พ.ค. 2017
This Channel posts educational videos in the area of Computer Science.
The videos are created by Kianoosh who is has a Ph.D. in Computer Science.
The videos are created by Kianoosh who is has a Ph.D. in Computer Science.
Optimal Page Replacement Algorithm - Operating System Virtual Memory Management
Optimal Page Replacement Algorithm - Operating System Virtual Memory Management
มุมมอง: 144
วีดีโอ
Making a multithreaded C Program to solve a word puzzle
มุมมอง 475หลายเดือนก่อน
Program Description (0:00) C Source Code (12:10) Demo of Running the Program (58:13)
Solving Word Sum Puzzle in Java with Recursion
มุมมอง 1202 หลายเดือนก่อน
Introduction (0:00) Program's I/O (18:15) Java Code: (24:21) How to Complete to Given Program (40:00)
Contiguous Memory Allocation - First-Fit
มุมมอง 3142 หลายเดือนก่อน
Introduction: (0:00) Overview of C code (11:28) Header File (12:02) Main Function (16:12) Testbench for First-Fit Algorithm (18:37) First-Fit Algorithm (29:50) Occupy Function (37:13) Release Function (41:20) Add_hole Sub-procedure (48:52) Left_coalesce Sub-procedure (54:36) Right_coalesce Sub-procedure (56:37) Double_coalesce Sub-procedure (59:30) Execution Demo (1:03:30)
Simulating CPU Scheduling Algorithms in C
มุมมอง 5432 หลายเดือนก่อน
Simulating CPU Scheduling Algorithms in C
Creating an Event Organizer in Java #javaprogramming #exceptionhandling
มุมมอง 1692 หลายเดือนก่อน
Creating an Event Organizer in Java #javaprogramming #exceptionhandling
Balanced and Symmetric Binary Trees - Java Code
มุมมอง 253 หลายเดือนก่อน
Balanced and Symmetric Binary Trees - Java Code
Example of Binary Trees - Count Nodes with a Certain Value
มุมมอง 403 หลายเดือนก่อน
Example of Binary Trees - Count Nodes with a Certain Value
Dynamic Memory Allocation in C - malloc, calloc, realloc, free
มุมมอง 2103 หลายเดือนก่อน
Dynamic Memory Allocation in C - malloc, calloc, realloc, free
Creating a Shell in C
มุมมอง 2713 หลายเดือนก่อน
Intro (0:00) Headers (2:26) Main Function (3:12) Execute Function (5:09) Handle Alarm Function (10:48) Demo (11:17)
Compiling and Running a Simple C Program in Unix
มุมมอง 4364 หลายเดือนก่อน
Compiling and Running a Simple C Program in Unix
Two Examples of Multi-dimensional Arrays (Pointer to Pointers) in C Programming Language
มุมมอง 867 หลายเดือนก่อน
Two Examples of Multi-dimensional Arrays (Pointer to Pointers) in C Programming Language
Examples of Algorithm Analysis and Linked Lists
มุมมอง 3118 หลายเดือนก่อน
Examples of Algorithm Analysis and Linked Lists
2D Arrays in Java
มุมมอง 1818 หลายเดือนก่อน
Intro to 2D Arrays (0:00) Example of Rectangular 2D Array (8:13) Ragged 2D Arrays (17:12) Pascal's Triangle in Java (22:38)
Spell-Checker Program in C
มุมมอง 5809 หลายเดือนก่อน
Intro (0:00) Command-Line Arguments (0:56) Data Structure used by the Program (7:45) Input/Output format of the program (15:49) Submission Guideline (23:05) Starter Code (25:15) Executing the Starter Code (43:05) Autograder (46:58)
C Programming: Creating a symmetric encryption from scratch
มุมมอง 1.4K11 หลายเดือนก่อน
C Programming: Creating a symmetric encryption from scratch
Creating a C Program Displaying Integers in 7-Segment Format
มุมมอง 1.8Kปีที่แล้ว
Creating a C Program Displaying Integers in 7-Segment Format
Not Your Teacher Coin (NYTC): An Instructional Cryptocurrency
มุมมอง 296ปีที่แล้ว
Not Your Teacher Coin (NYTC): An Instructional Cryptocurrency
Java Programming: File I/O using Scanner and PrintWriter
มุมมอง 206ปีที่แล้ว
Java Programming: File I/O using Scanner and PrintWriter
Unix Programming: How to create a program to find a special word
มุมมอง 2Kปีที่แล้ว
Unix Programming: How to create a program to find a special word
SHA256 and Symmetric Encryption Examples
มุมมอง 496ปีที่แล้ว
SHA256 and Symmetric Encryption Examples
MIPS Fields of an Instruction and its Hexadecimal Representation
มุมมอง 2Kปีที่แล้ว
MIPS Fields of an Instruction and its Hexadecimal Representation
Converting Decimal to two's complement and sign-magnitude representation
มุมมอง 530ปีที่แล้ว
Converting Decimal to two's complement and sign-magnitude representation
Multithreading using BackgroundWorker in Windows Form Applications
มุมมอง 418ปีที่แล้ว
Multithreading using BackgroundWorker in Windows Form Applications
Graph Algs.: Kahn's Topological Sort, Dijkstra's and Bellman Ford's Shortest Path, DFS, BFS, Kruskal
มุมมอง 813ปีที่แล้ว
Graph Algs.: Kahn's Topological Sort, Dijkstra's and Bellman Ford's Shortest Path, DFS, BFS, Kruskal
Implementing Chess Game using WinForm Applications (C# Programming)
มุมมอง 2.1Kปีที่แล้ว
Implementing Chess Game using WinForm Applications (C# Programming)
WinForm Application: Data Binding for Control Objects
มุมมอง 146ปีที่แล้ว
WinForm Application: Data Binding for Control Objects
import java.util.ArrayList; import java.util.Scanner; public class AlphabetSumPuzzle { private static ArrayList<Character> variables = new ArrayList<>();//all variables in the puzzle private static ArrayList<String>operands = new ArrayList<>();//all sum operands given by keyboard private static String result = null; public static void main(String[] args){ Scanner keyboard = new Scanner(System.in); while(keyboard.hasNextLine()){ String puzzle = keyboard.nextLine();//e.g. THE+BEST+SPOT=SPOTS String[] tokens = puzzle.split("[^a-zA-Z]");//e.g. THE, BEST, SPOT, SPOTS for(int i = 0; i < tokens.length-1;i++) if(tokens[i].length() != 0)//e.g. operands = [THE, BEST, SPOT] operands.add(tokens[i]);//all tokens but the last one represent the sum operands result = tokens[tokens.length-1];//last token must be the sum result. e.g. result = SPOTS int[] digitValues = new int[256];//maps characters to digits for(int i = 0; i < 256;i++)//initialize digitValues to -1 digitValues[i] = -1;//symbol for empty cell! //solve method is called here findAllVariables(puzzle);//detect every character participating in the puzzle and store it in the list of variables printAllCombinations(digitValues);//printing all combinations using recursion digitValues['T'] = 1; digitValues['H'] = 2; digitValues['E'] = 3; System.out.println("This is an example: Numerical value of " + "THE is " + numericalValue("THE", digitValues)); } } private static void findAllVariables(String puzzle) { variables.clear(); for(char c: puzzle.toCharArray()) if(Character.isLetter(c) && !variables.contains(c)) variables.add(c); } private static int numericalValue(String word, int[] digitValues) { int rv = 0; for(char c: word.toCharArray()) if(digitValues[c] < 0)//if c is not assigned to any value return -1;//error else rv = 10 * rv + digitValues[c]; return rv; } //THE: 3-digit integer //numerical value = T * 100 + H * 10 + E * 1 // 1 * E + 10 * H + 100 * T // 1 * E + 10 * (H + 10 * T) private static void printAllCombinations(int[] digitValues){//recursive method //Your code here! boolean complete = true; char unassignedVariable = 0; for(char variable: variables) if(digitValues[variable] == -1){//varible hasn't been assigned to any value yet! complete = false;//assinment is not complete unassignedVariable = variable;//variable without assignment is stored in the unassignedVariable... break; } if(complete) {//base case //do not print all mappings //print a mapping only if it satisfies the puzzle //THE+BEST+SPOT=SPOTS //first calculate the Left-hand-side of the equation int leftHandSide = 0; for(String operand: operands){ leftHandSide += numericalValue(operand, digitValues); } //then calculate the right-hand-side of the equation int rightHandSide = numericalValue(result, digitValues); //then, proceed with the following code only if LHS = RHS //for extra credits, you should also consider more conditions before moving forward with printing the solutions for(char variable: variables) System.out.print(variable + ": " + digitValues[variable] + "| "); System.out.println(); }else{//recursive step for(int i = 0; i < 10;i++) { digitValues[unassignedVariable] = i;//assign the unassignedVarialbe to one of the possible digits 0,1,..,9 printAllCombinations(digitValues);//recursive call! } digitValues[unassignedVariable] = -1;//assign the unassignedVariable to -1 again } } }
Updated Code for right_coalesce function explained in (56:37) #define PREV 1 #define NEXT 2 static void right_coalesce(int start_addr, int end_addr){ int right_start_addr = end_addr + 1; int right_end_addr = right_start_addr + 3 - memory[right_start_addr]; printf("right_coalesce: combining @[%d, %d] and @[%d, %d]. ", start_addr, end_addr, right_start_addr, right_end_addr); memory[right_end_addr] -= (end_addr - start_addr + 1); memory[start_addr] = memory[right_end_addr]; int prev_hole, next_hole; memory[start_addr + PREV] = prev_hole = memory[right_start_addr + PREV]; memory[start_addr + NEXT] = next_hole = memory[right_start_addr + NEXT]; memory[prev_hole + NEXT] = start_addr; memory[next_hole + PREV] = start_addr; }
//---------------------------------------------------------------------simulate.c--------------------------------------------------------------------- #include"simulate.h" process processes[MAX_PROCESSES]; int n, k, d, v, q; // Simulation parameters static void initialize_processes() { srand(time(NULL)); for (int i = 0; i < n; i++) { processes[i].id = i; processes[i].arrival_time = rand() % (k + 1); while ((processes[i].total_cpu_time = (int)(nrand() * v + d)) < 1); processes[i].remaining_time = processes[i].total_cpu_time; processes[i].active = (processes[i].arrival_time == 0) ? 1 : 0; processes[i].turnaround_time = 0; processes[i].priority = rand() % 10 + 1; // For priority scheduling } } static void reset_processes(){ for (int i = 0; i < n; i++) { processes[i].remaining_time = processes[i].total_cpu_time; processes[i].active = (processes[i].arrival_time == 0) ? 1 : 0; processes[i].turnaround_time = 0; } } static void compute_average_turnaround_time() { int total_turnaround_time = 0; for (int i = 0; i < n; i++) { total_turnaround_time += processes[i].turnaround_time; } double average_turnaround_time = (double)total_turnaround_time / n; fprintf(stderr, "ATT: %.2f, ", average_turnaround_time); printf("%.2f\t", average_turnaround_time); } int main2(int argc, char *argv[]) { if (argc != 11) { fprintf(stderr, "Usage: %s %s %s %s ", argv[0], "-n <num_processes> -k <arrival_interval>", "-d <mean_cpu_time> -v <stddev_cpu_time>", "-q <time_quantum>"); return 1; } for (int i = 1; i < argc; i += 2) { if (argv[i][1] == 'n') n = atoi(argv[i+1]); else if (argv[i][1] == 'k') k = atoi(argv[i+1]); else if (argv[i][1] == 'd') d = atoi(argv[i+1]); else if (argv[i][1] == 'v') v = atoi(argv[i+1]); else if (argv[i][1] == 'q') q = atoi(argv[i+1]); } initialize_processes(); //Starting FCFS Simulation... fprintf(stderr, "FCFS "); simulate_fcfs(); compute_average_turnaround_time(); reset_processes(); //Starting SJF Simulation... fprintf(stderr, "SJF "); simulate_sjf(); compute_average_turnaround_time(); reset_processes(); //Starting SRT Simulation... fprintf(stderr, "SRT "); simulate_srt(); compute_average_turnaround_time(); reset_processes(); //Starting Priority with Round Robin Simulation... fprintf(stderr, "PRI_RR "); simulate_priority_rr(); compute_average_turnaround_time(); return 0; } int main(){ int n_and_k[4][2] = {{100,1000}, {500,10000}, {500,5000}, {1000, 10000}}; char* argv2[12] = {"simulate", "-n", (char*) malloc(10*sizeof(char)), "-k", (char*) malloc(10*sizeof(char)), "-d", (char*) malloc(10*sizeof(char)), "-v", (char*) malloc(10*sizeof(char)), "-q", (char*) malloc(10*sizeof(char)), NULL }; for(int scenario = 0; scenario < 4; scenario++){ fprintf(stderr, " n = %d, k = %d: ", n = n_and_k[scenario][0], k = n_and_k[scenario][1]); for(int d = k/n; d <= 25*k/n; d += (k/n)){ int v = d/4; int q = d+v; fprintf(stderr, " d = %d, v = %d, q = %d: ", d, v, q); printf(" %d\t%d\t%d\t%d\t%d", n, k, d, v, q); sprintf(argv2[2], "%d", n); sprintf(argv2[4], "%d", k); sprintf(argv2[6], "%d", d); sprintf(argv2[8], "%d", v); sprintf(argv2[10], "%d", q); main2(11,argv2); } } }
//------------------------------------------simulate.h--------------------------------------------- #ifndef SIMULATE_H__ #define SIMULATE_H__ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #define MAX_PROCESSES 1000 #define frand() (rand()/(double)RAND_MAX) #define nrand() (sqrt(-2*log(frand()))*cos(2*M_PI*frand())) typedef struct { int id; int arrival_time; int total_cpu_time; int remaining_time; int active; int turnaround_time; int priority; } process; extern process processes[MAX_PROCESSES]; extern int n, k, d, v, q; // Simulation parameters void simulate_fcfs(); void simulate_sjf(); void simulate_srt(); void simulate_priority_rr(); #endif
//--------------------------------------------------------fcfs.c-------------------------------------------------------- #include "simulate.h" #include "queue.h" void simulate_fcfs() { int t = 0;//current time int completed = 0; queue ready = init_queue(); while (completed < n) { //char* str = to_str(ready); //printf("Ready queue @ t = %d: %s ", t, str); //free(str); for (int i = 0; i < n; i++) { if (processes[i].arrival_time == t){ processes[i].active = 1; enqueue(&ready, processes[i]); } } if (!ready.size) { t++; continue; } int cur = peek(ready).id; processes[cur].remaining_time--; t++; if (processes[cur].remaining_time == 0) { processes[cur].active = 0; processes[cur].turnaround_time = t - processes[cur].arrival_time; completed++; dequeue(&ready); //printf("p%d arrived at %d, got terminated at %d, with TT = %d. ", // processes[cur].id, processes[cur].arrival_time, // t, processes[cur].turnaround_time); } } }
//--------------------------------------------------------queue.c---------------------------------------------------------- #include "queue.h" // Function to initialize a queue queue init_queue() { queue q; q.head = NULL; q.tail = NULL; q.size = 0; return q; } // Function to enqueue (add an element to the end of the queue) void enqueue(queue* q, process new_process) { node* new_node = (node*)malloc(sizeof(node)); if (new_node == NULL) { printf("Memory allocation failed "); return; } new_node->value = new_process; new_node->next = NULL; if (q->tail == NULL) { q->head = new_node; q->tail = new_node; } else { q->tail->next = new_node; q->tail = new_node; } q->size++; } // Function to dequeue (remove an element from the front of the queue) process dequeue(queue* q) { process empty_process = {-1, -1, -1, -1, -1, -1, -1}; // To return in case of an empty queue if (q->head == NULL) { printf("Queue is empty "); return empty_process; } node* temp = q->head; process dequeued_process = temp->value; q->head = q->head->next; if (q->head == NULL) { q->tail = NULL; } free(temp); q->size--; return dequeued_process; } process peek(queue q) { process empty_process = {-1, -1, -1, -1, -1, -1, -1}; // To return in case of an empty queue if (q.head == NULL) { printf("Queue is empty "); return empty_process; } return q.head->value; } char* to_str(queue q){//front_end [ p2 p1 p0 p4 p3 ] rear_end char* rv = (char*) malloc(10000 * sizeof(char)); strcpy(rv, "front_end ["); char* temp = rv+strlen(rv); node * cur = q.head; while (cur != NULL){ int num = sprintf(temp, " p%d", cur->value.id); temp += num; cur = cur->next; } strcat(temp, " ] rear_end"); return rv; }
//-----------------------------------------------------------queue.h------------------------------------------------------- #ifndef QUEUE_H__ #define QUEUE_H__ #include "simulate.h" typedef struct node { process value; struct node* next; } node; typedef struct { node* head; node* tail; int size; } queue; queue init_queue(); void enqueue(queue* q, process new_process); process dequeue(queue* q); process peek(queue q); char* to_str(queue q); #endif /* QUEUE_H__*/
//-------------------------------------------------------makefile------------------------------------------------- CC=gcc CFLAGS=-I. -lm -w DEPS= queue.h simulate.h OBJ = simulate.o queue.o sjf.o srt.o priority.o fcfs.o %.o: %.c $(DEPS) $(CC) -c -o $@ $< $(CFLAGS) pa2: $(OBJ) $(CC) -o $@ $^ $(CFLAGS)
thanks for the clear and concise explanation .
should provide code in text
Honestly, you should put ads on your video. Since other Professors are sending their student's to watch your videos you might as well get paid for it too lol.
Great man
See www.cis.fiu.edu/faq/accessing-your-files-off-campus/ for remote access to ocelot.aul.fiu.edu via PuTTY and SFTP If you are a returning student and you have already changed your password and initialized your account in a previous semester you should not need to do step one below. Your password will be what you have set in previous semesters. If you have forgotten your password you can proceed to step 2 (and then go back to step 1) If you have not already changed your password for ocelot.aul.fiu.edu or the computers in the KFSCIS labs (CASE 241/252 and PG6 106) you will need to use the initial password and visit www.cs.fiu.edu/pw to change the initial password and activate your account. Your initial account / password information is: username: is the same as your fiu username (no @fiu.edu part, just the username, all lower case) password: fXXXXXXXl where XXXXXXX is your 7 digit panther id and f is the lower case initial of your first name l is the lower case initial of your last name Note: if your registered as Firstname Lastname Jr or Firstname Lastname III your might need to use j or i as initial of last name. Step 1: Change your password from the initial password and activate your account. Visit www.cs.fiu.edu/pw Enter the initial password (format above) Enter a new password (twice) Hit submit. If that doesn't work (i.e. it says invalid initial password) proceed to Step 2. Step 2: Reset your password back to the initial password. Visit support.cis.fiu.edu/aul-pw-reset It will let you reset your password back to the default (mentioned above) by sending a token to your @fiu.edu email account. Follow directions in that email and you can reset your password back to the default. If you have to go to step 2 then after completing that you will need to go back and do step 1: visit www.cs.fiu.edu/pw to change your password from the default and activate your account. If you have other issues please drop a note to request [at] cs.fiu.edu and we will review and help.
0:01- Intro Explanation 10:46 - Examples 24:18 - Submissions 25:02 - Starter Code 27:36 - Enumerator Flags 34:00 - Managing Flags 39:31 - Main Function 47:43 - Code to remove 52:39 - Conversion 1:02:31 - Running the Code 1:05:17 - Sending results to Output file
Great man 🎉🔥
Thank you so much. Really appreciate your hard work. Keep up the amazing content
Java Code for the first Example: //Declaration & Initialization int[][] my2DArray = new int[3][2];//3 rows, 2 columns //Assigning 10 and 20 to the cells in the first row: my2DArray[0][0] = 10; my2DArray[0][1] = 20; //Assigning 30 and 40 to the cells in the second row: my2DArray[1] = new int[]{30, 40}; //Assigning 50 and 60 to the cells in the third row: for(int col = 0; col < my2DArray[2].length; col++) my2DArray[2][col] = 10 * (5 + col); //printing the array out: for(int row = 0; row < 3;row++) { for (int col = 0; col < 2; col++) System.out.print(my2DArray[row][col] + " "); System.out.println(); } Java Code for the second example: char[][] board = new char[8][8]; for(int row = 0; row < 8;row++) for(int col = 0;col < 8;col++) if(row == 1)//seventh rank board[row][col] = '\u265F';//black pawn else if(row == 6)//second rank board[row][col] = '\u2659';//white pawn else if(row == 0){//black pieces in last rank if(col == 0 || col == 7)//File A or H board[row][col] = '\u265C';//black rook else if(col == 1 || col == 6)//File B or G board[row][col] = '\u265E';//black knight else if(col == 2 || col == 5)//File C or F board[row][col] = '\u265D';//black bishop else if(col == 3)//file D board[row][col] = '\u265B';//black queen else//file E board[row][col] = '\u265A';//black king } else if(row == 7){//white pieces in first rank if(col == 0 || col == 7)//File A or H board[row][col] = '\u2656';//white rook else if(col == 1 || col == 6)//File B or G board[row][col] = '\u2658';//white knight else if(col == 2 || col == 5)//File C or F board[row][col] = '\u2657';//white bishop else if(col == 3)//file D board[row][col] = '\u2655';//white queen else//file E board[row][col] = '\u2654';//white king }else//middle of board board[row][col] = ' ';//empty cells for(char[] row: board) { for (char square : row) System.out.print(square); System.out.println(); } Java Code for the third example: int[][] raggedArray = new int[5][]; raggedArray[0] = new int[]{2, 3, 5, 7};//prime numbers from 1-10 raggedArray[1] = new int[]{11, 13, 17, 19};//prime numbers from 11-20 raggedArray[2] = new int[]{23, 29};//prime numbers from 21-30 raggedArray[3] = new int[]{31, 37};//prime numbers from 31-40 raggedArray[4] = new int[]{41, 43, 47};//prime numbers from 41-50 for(int row = 0; row < raggedArray.length;row++) { for (int col = 0; col < raggedArray[row].length; col++) System.out.print(raggedArray[row][col] + "\t"); System.out.println(); } Java Code for the last example: int[][] pascalTriangle = new int[6][]; for(int row = 0; row < 6;row++){ pascalTriangle[row] = new int[row + 1]; for(int col = 0; col < pascalTriangle[row].length; col++){ if(col == 0)//left edge of triangle pascalTriangle[row][col] = 1; else if(col == pascalTriangle[row].length - 1)//right edge of triangle pascalTriangle[row][col] = 1; else pascalTriangle[row][col] = pascalTriangle[row-1][col]+ pascalTriangle[row-1][col-1]; } } for(int row = 0; row < 6; row++){ //add some tabs at the beginning of every row! for(int tabCount = 0; tabCount<5-row;tabCount++) System.out.print("\t"); for(int col = 0; col < pascalTriangle[row].length;col++){ System.out.print(pascalTriangle[row][col]); if(col == pascalTriangle[row].length-1) System.out.println(); else System.out.print("\t\t"); } }
can u provide the code in the description
Is it you on uvocorp?
could you provide source code?
Thanks buddy for this explanation, especially the diagram. This was missing in the other reads I did in few blogs. God Bless You. 🙂
You're welcome
*Promo SM* 💔
ive never seen lightmode visual studio and i now see why. cool vid tho but like how do you stare at that for hours
Hi, there I would love if you could give me a email where i can contact you, i'm trying to learn c# programing, and started watching your video about minespweeper. I really love your way of writing code and I will love to read it fully.
Is there any way to get this, because I wanna learn too? I want to read the code so I can understand it better and it's really hard to read it from your video.
try going into the video quality settings and changing it from auto to 1080p
I need a tutorial for small and stupid :)
This lecture blew my mind! Thank you for explaining how to find k and q , the inverse of e , and how to compute the exponential with the mod. While watching the lecture i was asking myself how can those things get done! Great lecture <3
I’m glad you find it helpful.
is there a way to get the PowerPoint file on these lectures?
Great video bro
Great Video!🤓
Vertex.java: package util; public class Vertex implements Comparable<Vertex> { public String name; public int indegree; public int rank;//used to compare two vertices. Can be topological number, distance from source, etc public int discovered;//discovery time in DFS... Is always positive public int finished;//finish time in DFS... Is always positive public Vertex pred; @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(Object o) { Vertex another = (Vertex) o; return this.name.equals(another.name); } @Override public String toString() { return name; } public Vertex(String name) { this.name = name; this.indegree = 0; this.discovered = 0; this.finished = 0; this.pred = null; this.rank = 0; } public int compareTo(Vertex another) { return this.rank - another.rank; } }
Graph.java: package util; import java.util.*; public class Graph { public Map<Vertex, Set<Vertex>> adjacencyMap; private Map<String, Vertex> vertexFinder; //returns all vertices... public Set<Vertex> vertexSet(){ return adjacencyMap.keySet(); } //returns set of all neighbors for a given vertex public Set<Vertex> neighborSet(Vertex v){ return adjacencyMap.getOrDefault(v, new HashSet<>()); } public int vertexCount; public int edgeCount; public Graph(String[] vertices, String[] edges){ adjacencyMap = new HashMap<>(); vertexFinder = new HashMap<>(); vertexCount = vertices.length; edgeCount = edges.length; for(String v: vertices) { Vertex temp = new Vertex(v); vertexFinder.put(v, temp); adjacencyMap.put(temp, new HashSet<>()); } for(String e: edges){//"(u,v)" is represented by "u,v" String[] endpoints = e.split(","); addEdge(vertexFinder.get(endpoints[0]), vertexFinder.get(endpoints[1])); } } public void resetInDegrees(){ for(Vertex v: adjacencyMap.keySet()) v.indegree = 0; for(Vertex v: adjacencyMap.keySet()) for(Vertex w: adjacencyMap.get(v)) w.indegree++; } public void resetForDFS(){ for(Vertex v: adjacencyMap.keySet()){ v.pred = null; v.finished = v.discovered = 0; } } public void resetForShortestPathProblem(){ for(Vertex v: vertexSet()){ v.discovered = 0; v.pred = null; v.rank = Integer.MAX_VALUE; } } public Vertex getVertex(String name){ return vertexFinder.get(name); } private void addEdge(Vertex from, Vertex to) { adjacencyMap.get(from).add(to); to.indegree++; } }
TopologicalSort.java: package algorithms; import util.*; import java.util.*; public class TopologicalSort { //Topological sort creates an ordering of vertices of a graph like v1, v2, ..., vn such that //if i < j, there is no edge from vj to vi public static List<Vertex> kahnsAlgorithm(Graph graph) throws Exception{ List<Vertex> rv = new ArrayList<>(); Queue<Vertex> q = new LinkedList<>(); int counter = 0; for(Vertex v: graph.vertexSet()) if(v.indegree == 0) q.add(v); while(!q.isEmpty()){ Vertex v = q.remove(); v.rank = ++counter; rv.add(v); for(Vertex w: graph.neighborSet(v)) if(--w.indegree == 0) q.add(w); } graph.resetInDegrees();//undo the side effects of the algorithm on vertices if(counter != graph.vertexSet().size())//Only DAGs have topological sort throw new Exception("cycle found! No top sort exists!"); return rv; } public static List<Vertex> topSortUsingDFS(Graph graph) throws Exception { LinkedList<Vertex> rv = new LinkedList<>(); LinkedList<Vertex> starters = new LinkedList<Vertex>(); graph.resetForDFS(); for (Vertex v : graph.vertexSet()) if (v.indegree == 0) starters.addFirst(v); Stack<Vertex> stack = new Stack<Vertex>(); int time = 0; int topNum = graph.vertexCount; for (Vertex startVertex : starters) { stack.push(startVertex); while (!stack.empty()) { Vertex current = stack.pop(); if (current.finished > 0)//finished processing before continue; if (current.discovered > 0) {//discovered before current.finished = ++time; current.rank = topNum--; rv.addFirst(current); continue; } current.discovered = ++time;//discovered for the first time stack.push(current); for (Vertex neighbor : graph.neighborSet(current)) if (neighbor.discovered == 0) {//haven't discovered yet! neighbor.pred = current; stack.push(neighbor); }else if(neighbor.finished == 0)//have been discovered before but not finished yet...cycle found! throw new Exception("cycle found! No top sort exists!"); } } return rv; } public static void main(String[] args){ Graph graph = new Graph(new String[]{ "watch", "shirt", "socks", "undershorts", "pants", "shoes", "tie", "belt", "jacket" }, new String[]{ "socks,shoes", "undershorts,pants", "undershorts,shoes", "pants,shoes", "pants,belt", "shirt,belt", "shirt,tie", "belt,jacket", "tie,jacket" }); try { System.out.println("Order of wearing clothes: " + kahnsAlgorithm(graph)); System.out.println("Order of wearing clothes: " + topSortUsingDFS(graph)); }catch (Exception exp){//if Graph is not a DAG System.out.println(exp.getMessage()); } } }
DFS.java: package algorithms; import util.*; import java.util.*; public class DFS { private static void helper(Vertex current, Graph graph, int time){ System.out.print(current + "\t"); current.discovered = ++time; for(Vertex neighbor: graph.neighborSet(current)) if(neighbor.discovered == 0)//haven't been discovered yet helper(neighbor, graph, time); } public static void dfsRecursivePrint(Graph graph){ int time = 0; graph.resetForDFS(); for(Vertex start: graph.vertexSet()){ if(start.discovered > 0) continue; helper(start, graph, time); } } public static void dfsIterativePrint(Graph graph){ graph.resetForDFS(); Stack<Vertex> stack = new Stack<Vertex>(); int time = 0; for (Vertex v : graph.vertexSet()) { if (v.discovered > 0) continue; stack.push(v); while (!stack.empty()) { Vertex current = stack.pop(); System.out.print(current + "\t"); current.discovered = ++time; for (Vertex neighbor : graph.neighborSet(current)) { if (neighbor.discovered == 0)//haven't been discovered yet! stack.push(neighbor); } } } } public static void dfsIterativePrint(Graph graph, String startVertex){ graph.resetForDFS(); Stack<Vertex> stack = new Stack<Vertex>(); int time = 0; stack.push(graph.getVertex(startVertex)); while (!stack.empty()) { Vertex current = stack.pop(); System.out.print(current + "\t"); current.discovered = ++time; for (Vertex neighbor : graph.neighborSet(current)) { if (neighbor.discovered == 0)//haven't been discovered yet! stack.push(neighbor); } } for (Vertex v : graph.vertexSet()) { if (v.discovered > 0) continue; stack.push(v); while (!stack.empty()) { Vertex current = stack.pop(); System.out.print(current + "\t"); current.discovered = ++time; for (Vertex neighbor : graph.neighborSet(current)) { if (neighbor.discovered == 0)//haven't been discovered yet! stack.push(neighbor); } } } } public static void main(String[] args){ Graph graph = new Graph(new String[]{ "watch", "shirt", "socks", "undershorts", "pants", "shoes", "tie", "belt", "jacket" }, new String[]{ "socks,shoes", "undershorts,pants", "undershorts,shoes", "pants,shoes", "pants,belt", "shirt,belt", "shirt,tie", "belt,jacket", "tie,jacket" }); dfsIterativePrint(graph); System.out.println(); dfsRecursivePrint(graph); System.out.println(" DFS with a given start vertex; e.g. shirt:"); dfsIterativePrint(graph, "shirt"); } }
WeightedGraph.java: package util; import java.util.*; public class WeightedGraph extends Graph{ public Map<Vertex, Map<Vertex,Integer>> weight; public WeightedGraph(String[] vertices, String[]edges){ super(vertices, edges); weight = new HashMap<>(); for(Vertex v: vertexSet()) { weight.put(v, new HashMap<>()); } for(String e: edges){ String[] endpoints = e.split(","); if(endpoints.length == 3) setWeight(endpoints[0], endpoints[1], Integer.parseInt(endpoints[2])); else setWeight(endpoints[0], endpoints[1], 1); } } public int getWeight(String from, String to) { return weight.get(getVertex(from)).getOrDefault(getVertex(to), Integer.MAX_VALUE); } public int setWeight(String from, String to, int newWeight) { Vertex fromVertex = getVertex(from); Vertex toVertex = getVertex(to); int rv = weight.get(fromVertex).getOrDefault(toVertex, Integer.MAX_VALUE); weight.get(fromVertex).put(toVertex, newWeight); return rv; } }
ShortestPath.java: package algorithms; import util.*; import java.util.*; public class ShortestPath { public static void bellman_ford(WeightedGraph weightedGraph, String sourceVertex) throws Exception{ weightedGraph.resetForShortestPathProblem(); Vertex source = weightedGraph.getVertex(sourceVertex); source.rank = 0;//rank means distance from source for(int rep = 0; rep < weightedGraph.vertexCount; rep++) for(Vertex from: weightedGraph.vertexSet()) for(Vertex to: weightedGraph.neighborSet(from)) { int weight = weightedGraph.getWeight(from.name, to.name); if(from.rank != Integer.MAX_VALUE && to.rank > from.rank + weight){//relaxing edge (from, to) if(rep == weightedGraph.vertexCount - 1) { Exception negativeCycle = new Exception("Bellmanford Error: Can't solve the shortest " + "path problem as the graph has negative cycle!"); throw negativeCycle; } to.rank = from.rank + weight; to.pred = from; } } } public static void dijkstra(WeightedGraph weightedGraph, String sourceVertex) throws Exception{ weightedGraph.resetForShortestPathProblem(); Vertex source = weightedGraph.getVertex(sourceVertex); source.rank = 0; Queue<Vertex> q = new PriorityQueue<Vertex>();//min-heap! q.add(source); int time = 0; while (!q.isEmpty()) { Vertex current = q.remove(); current.discovered = ++time; for (Vertex neighbor : weightedGraph.neighborSet(current)) { if(neighbor.discovered > 0)//the path from source to neighbor is already known. No need to process again continue; int distanceFromNeighbor = weightedGraph.getWeight(current.name, neighbor.name); if(distanceFromNeighbor < 0)//negative distance throw new Exception("Error: Dijkstra's algorithm cannot handle negative weights. use BellmanFord!"); if (neighbor.rank > current.rank + distanceFromNeighbor) {//relaxing the edge (current, neighbor) neighbor.rank = current.rank + distanceFromNeighbor; neighbor.pred = current; q.add(neighbor); } } } } public static void bfs(Graph graph, String sourceVertex) { graph.resetForShortestPathProblem(); Vertex source = graph.getVertex(sourceVertex); int time = 0; source.rank = 0; Queue<Vertex> q = new LinkedList<Vertex>(); q.add(source); source.discovered = ++time; while (!q.isEmpty()) { Vertex current = q.remove(); for (Vertex neighbor : graph.neighborSet(current)) if (neighbor.discovered == 0) {//not discovered yet neighbor.rank = current.rank + 1; neighbor.pred = current; q.add(neighbor); neighbor.discovered = ++time; } } } public static void printShortestPathSolution(String sourceVertex, Graph graph) { Vertex source = graph.getVertex(sourceVertex); System.out.println("Source is " + source); for (Vertex v : graph.vertexSet()) { if (v.equals(source)) continue; System.out.println("Shortest distance/path from " + source + " to " + v + ": " + v.rank + findPath(sourceVertex, v.name, graph)); } } public static List<Vertex> findPath(String source, String target, Graph graph){ LinkedList<Vertex> rv = new LinkedList<>(); helper(graph.getVertex(source), graph.getVertex(target), rv); return rv; } private static void helper(Vertex source, Vertex target, LinkedList<Vertex> path) { if (source.equals(target)) { path.addFirst(source); return; } if (target.rank == Integer.MAX_VALUE) { path.clear();//path doesn't exist return; } path.addFirst(target); helper(source, target.pred, path); } public static void main(String[] args) { WeightedGraph graph = new WeightedGraph( new String[]{//vertices "v1", "v2", "v3", "v4", "v5", "v6", "v7" }, new String[]{//edges "v3,v1,4", "v3,v6,5", "v1,v2,2", "v1,v4,1", "v2,v5,10", "v2,v4,3", "v5,v7,6", "v7,v6,1", "v4,v5,2", "v4,v7,4", "v4,v6,8", "v4,v3,2" } ); System.out.println("Running BFS on an unweighted graph with 7 vertices "); bfs(graph, "v3"); printShortestPathSolution("v3", graph);//say source is v3 System.out.println(" Running Dijkstra's on a weighted graph with 7 vertices "); try{ dijkstra(graph, "v1"); printShortestPathSolution("v1", graph);//say source is v1 }catch (Exception exp){ System.out.println(exp.getMessage()); } System.out.println(" Changing the weight of edge (v7, v6) from 1 to -4 and (v3, v6) from 5 to 1... "); graph.setWeight("v7", "v6", -4); graph.setWeight("v3", "v6", 1); System.out.println(" Running Bellman-Ford's on the same graph after change... "); try{ bellman_ford(graph, "v1"); printShortestPathSolution("v1", graph);//say source is v1 }catch(Exception e) { System.out.println(e.getMessage()); } System.out.println(" Changing the weight of edge (v4, v3) from 2 to -6 to create a negative cycle:" + " v1 -> v4 -> v3 -> v1 "); graph.setWeight("v4", "v3", -6); System.out.println(" Running Bellman-Ford's on the same graph after change... "); try{ bellman_ford(graph, "v1"); printShortestPathSolution("v1", graph);//say source is v1 }catch(Exception e) { System.out.println(e.getMessage()); } } }
package util; import java.util.*; public class DisjointSet<T> { //class DijointSet keeps a set of disjoint sets in an array //Example: say we want to store {{A,B}, {C}, {D,E,F}} //elements = [A, B, C, D, E, F] //parent = [-2, 0, -1, -3, 3, 3] //size = 6 //index = {A:0, B:1, C:2, D:3, E:4, F:5} //find(A) and find B return A //find(C) returns C //find(D), find(E), and find(F) all return D //union (B, E) will change the set to become like this: //{{A,B,D,E,F}, {C}} //elements array array, index map and size won't change //parent becomes [3, 3, -1, -5, 3, 3] private int[] parent;//stores the parent of each element private T[] elements;//stores all elements private int size;//stores the current size private HashMap<T, Integer> index;//maps each element to its index in the elements array public DisjointSet(){ this(100); } public DisjointSet(int capacity) {//constructor receives an integer specifying the maximum # of elements index = new HashMap<T, Integer>(); int i = 0; parent = new int[capacity]; elements = (T[]) new Object[capacity]; size = 0; for(i = 0; i < parent.length;i++) parent[i] = -1; } public T find(T t) { int i = index.getOrDefault(t, -1); if(i == -1){ index.put(t, size); elements[size++] = t; return t; } while(parent[i] >= 0) i = parent[i]; return elements[i]; } public void union(T u, T v) { int i = index.get(find(u)); int j = index.get(find(v)); if(i == j)//u & v are already in the same set return; if(parent[i] < parent[j]){//union by size: u is in a bigger disjoint set parent[i] += parent[j];//update the size parent[j] = i;//add v's set to u's set } else{//union by size: u is not in a bigger disjoint set parent[j] += parent[i];//update the size parent[i] = j;//add u's set to v's set } } @Override public String toString(){ Map<T, Set<T>> mapOfDisjointSets = new HashMap<>(); for(T t: index.keySet()){ T rep = find(t); Set<T> set = mapOfDisjointSets.getOrDefault(rep, new HashSet<>()); set.add(t); mapOfDisjointSets.put(rep, set); } return mapOfDisjointSets.values().toString(); } }
public class BinaryHeap<T extends Comparable<? super T>>{ private Comparable[] data; private int size = 0; public BinaryHeap(int capacity){ data = new Comparable[capacity]; } public BinaryHeap(Comparable[] data){ this.data = data; size = data.length - 1; for(int i = size/2; i >= 1;i--) percolateDown(i); } public int size(){ return size; } private void percolateDown(int root){//heapify int leftChild = root * 2; int rightChild = leftChild + 1; int max; //max of left,, right, and parent nodes. //comparing parent with left child if(leftChild <= size && data[leftChild].compareTo(data[root]) > 0) max = leftChild; else max = root; //comparing the max with the right child if (rightChild <= size && data[rightChild].compareTo(data[max]) > 0) max = rightChild; if(max != root){ //if not the base case! Comparable temp = data[root];//swapping max w/ root data[root] = data[max]; data[max] = temp; percolateDown(max); } } public Comparable extractMax(){ if(size == 0) throw new IllegalStateException(); Comparable rv = data[1]; data[1] = data[size];//swap root w/ last leaf data[size] = rv; size--; percolateDown(1);//heapify the root return rv; } public static BinaryHeap buildHeap(Comparable[] values){ return new BinaryHeap(values); } public static void heapSort(Comparable[] values){ BinaryHeap heap = buildHeap(values); for(int i = 0; i < values.length - 1;i++) heap.extractMax(); } public static void main(String[] args){ Comparable[] array = new Comparable[]{-1, 5, 6, 2, 3, 1, 8, 4, 0}; heapSort(array); for(int i = 1; i < array.length;i++) System.out.println(array[i]); } }
Promo`SM 💐
package util; import java.util.*; /*public class BST<E extends Comparable<? super E>> implementing a set ADT and containing the following: * private inner class BinaryNode<E> representing a node with a (possibly) left child and a (possibly) right child ** instance fields BinaryNode<E> root, int size *** contains/insert/remove method - w/ O(height) complexity **** size O(1), isEmpty O(1), clear O(1), ***** findMin, findMax, findHeight methods - w/ O(height) complexity ****** toString() method printing set (in-order traversal) and the tree (BFS traversal) **** */ public class BST<E extends Comparable<? super E>> { private BinaryNode<E> root; private int size; //Search opertion of Set ADT public boolean contains(E value) { return contains(root, value); } //Insert opertion of Set ADT public void insert(E value) { root = insert(root, value); size++; } //Remove operation of Set ADT public void remove(E value){ root = remove(root, value); size--; } public int size(){ return size; } public boolean isEmpty(){ return root == null; } public void clear(){ root = null; size = 0; } public E findMin(){ return findMin(root); } public E findMax(){ return findMax(root); } public int findHeight(){ return root.height(); } public String toString(){ if(root == null) return "set {} stored in an empty tree. "; String elements = root.inOrder().toString(); return "set {" + elements.substring(1,elements.length()-1) + "} stored in tree " + root; } private E findMin(BinaryNode<E> node){ if(node == null) return null; if(node.left == null) return node.element; return findMin(node.left); } private E findMax(BinaryNode<E> node){ if(node == null) return null; if(node.right == null) return node.element; return findMax(node.right); } private boolean contains(BinaryNode<E> node, E value) { if (node == null)//node represents an empty substree return false; int comparisonResult = value.compareTo(node.element); if(comparisonResult < 0)//if value is less than root's value return contains(node.left, value); if(comparisonResult > 0)//if value is greater than root's value return contains(node.right, value); return true;//successful search } private BinaryNode<E> insert(BinaryNode<E> node, E value) { if (node == null)//base case: empty tree return new BinaryNode<>(value); if (value.compareTo(node.element) < 0) node.left = insert(node.left, value);//insert recursively to left-subtree else if (value.compareTo(node.element) > 0) node.right = insert(node.right, value);//insert recursively to right-subtree else {//duplicate value cannot be inserted in a BST implementing the Set ADT size--;//insertion failed! //System.out.print("BST.insert: Warning: " + value + " is already stored in the tree " + node); } return node; } private BinaryNode<E> remove(BinaryNode<E> node, E value) { if (node == null) {//base case: empty tree System.out.println("BST.remove: Warning: " + value + " doesn't exist in the tree."); size++;//removal failed! return node; } if (value.compareTo(node.element) < 0) node.left = remove(node.left, value); else if (value.compareTo(node.element) > 0) node.right = remove(node.right, value); else {//we have found the node that needs to be removed! if (node.left != null && node.right != null) {//remove a node with two children node.element = findMin(node.right);//replace it by the leftmost node at right subtree node.right = remove(node.right, node.element);//then, remove the leftmost node in the right subtree /*alternative: node.element = findMax(node.left);//replace it by the rightmost node at left subtree node.left = remove(node.left, node.element);//then, remove the rightmost node in the left subtree */ } else if (node.left != null)//remove a node with a left child only return node.left; else if (node.right != null)//remove a node with a right child only return node.right; else//remove a node with no child! return null; } return node; } private class BinaryNode<E> { /*Code in the comment seection*/ } }
private class BinaryNode<E> { public E element;//data public BinaryNode<E> left;//left child public BinaryNode<E> right;//right child //constructor for leaves public BinaryNode(E element) { this(element, null, null); } //constructor for internal nodes public BinaryNode(E element, BinaryNode<E> left, BinaryNode<E> right) { this.left = left; this.right = right; this.element = element; } public int height() { if (left == null && right == null) return 0; if (left == null) return 1 + right.height(); if (right == null) return 1 + left.height(); return 1 + Math.max(left.height(), right.height()); } public int size() { int size = 1;//counting root if (left != null)//counting left subtree nodes size += left.size(); if (right != null)//counting right subtree nodes size += right.size(); return size; } public void printPreOrder() { System.out.print(element + " "); if (left != null) left.printPreOrder(); if (right != null) right.printPreOrder(); } public void printPostOrder() { if (left != null) left.printPostOrder(); if (right != null) right.printPostOrder(); System.out.print(element + " "); } public void printInOrder() { if (left != null) left.printInOrder(); System.out.print(element + " "); if (right != null) right.printInOrder(); } public ArrayList<E> inOrder(){ ArrayList<E> list = new ArrayList<>(); Stack<Object> stack = new Stack<>(); stack.push(this); while(!stack.empty()){ Object cur = stack.pop(); if(cur instanceof BinaryNode) { BinaryNode<E> node = (BinaryNode) cur; if (node.right != null) stack.push(node.right); stack.push(node.element); if (node.left != null) stack.push(node.left); }else list.add((E)cur); } return list; } public void printBFS() { Queue<BinaryNode> q = new LinkedList<>(); q.add(this); while (!q.isEmpty()) { BinaryNode<E> cur = q.remove(); System.out.print(cur.element + " "); if (cur.left != null) q.add(cur.left); if (cur.right != null) q.add(cur.right); } } public void printDFS() { Stack<BinaryNode> stack = new Stack<>(); stack.add(this); while (!stack.empty()) { BinaryNode<E> cur = stack.pop(); System.out.print(cur.element + " "); if (cur.right != null) stack.push(cur.right); if (cur.left != null) stack.push(cur.left); } } @Override public String toString() { if (left == null && right == null && element == null) return ""; Queue<BinaryNode> list = new LinkedList<>(); String result = ""; list.add(this); list.add(null); int level = (int) Math.pow(2, height()); BinaryNode dummy = new BinaryNode(null); while (!list.isEmpty()) { boolean allDummies = true; for (BinaryNode<E> b : list) if (b != dummy && b != null) { allDummies = false; break; } BinaryNode<E> cur = list.remove(); if (cur == null || allDummies) break; for (int i = 0; i < level - 1; i++) result += '\t'; if (cur != dummy) result += cur.element; for (int i = 0; i < level + 1; i++) result += '\t'; if (cur.left != null) list.add(cur.left); else list.add(dummy); if (cur.right != null) list.add(cur.right); else list.add(dummy); if (list.peek() == null) { for (int i = 0; i < height(); i++) result += ' '; list.remove(); list.add(null); level /= 2; } } return result + " "; } }
BinaryNode class used in this video: package util; import java.util.*; /* This class implements Binary Node for Binary Trees Methods: I) Two constructors II) Two toString methods III) height and size methods IV) preorder, postorder, and inorder traversals V) BFS and DFS traversal */ public class BinaryNode<E> { public E element;//data public BinaryNode<E> left;//left child public BinaryNode<E> right;//right child //constructor for leaves public BinaryNode(E element){ this(element, null, null); } //constructor for internal nodes public BinaryNode(E element, BinaryNode<E> left, BinaryNode<E> right){ this.left = left; this.right = right; this.element = element; } @Override public String toString(){ if(left == null && right == null)//base case return element + ""; return element + "(" + left + ", " + right + ")"; } public int height() { if(left == null && right == null) return 0; if(left == null) return 1 + right.height(); if(right == null) return 1 + left.height(); return 1 + Math.max(left.height(), right.height()); } public int size(){ int size = 1;//counting root if(left != null)//counting left subtree nodes size += left.size(); if(right != null)//counting right subtree nodes size += right.size(); return size; } public void printPreOrder(){ System.out.print(element + " "); if(left != null) left.printPreOrder(); if(right != null) right.printPreOrder(); } public void printPostOrder(){ if(left != null) left.printPostOrder(); if(right != null) right.printPostOrder(); System.out.print(element + " "); } public void printInOrder(){ if(left != null) left.printInOrder(); System.out.print(element + " "); if(right != null) right.printInOrder(); } public void printBFS(){//breadth first search traversal - non-recursive method Queue<BinaryNode> q = new LinkedList<>(); q.add(this); while(!q.isEmpty()){ BinaryNode<E> cur = q.remove(); System.out.print(cur.element + " "); if(cur.left != null) q.add(cur.left); if(cur.right != null) q.add(cur.right); } } public void printDFS(){//depth first search traversal - equivalent to pre-order traversal Stack<BinaryNode> stack = new Stack<>(); stack.add(this); while(!stack.empty()){ BinaryNode<E> cur = stack.pop(); System.out.print(cur.element + " "); if(cur.right != null) stack.push(cur.right); if(cur.left != null) stack.push(cur.left); } } public String toString2() { if(left == null && right == null && element == null) return ""; Queue<BinaryNode> list = new LinkedList<>(); String result = ""; list.add(this); list.add(null); int level = (int) Math.pow(2, height()); BinaryNode dummy = new BinaryNode(null); while(!list.isEmpty()) { boolean allDummies = true; for(BinaryNode<E> b: list) if(b != dummy && b != null) { allDummies = false; break; } BinaryNode<E> cur = list.remove(); if(cur == null || allDummies) break; for(int i = 0; i < level - 1;i++) result += '\t'; if(cur != dummy) result += cur.element; for(int i = 0; i < level + 1;i++) result += '\t'; if(cur.left != null) list.add(cur.left); else list.add(dummy); if(cur.right != null) list.add(cur.right); else list.add(dummy); if(list.peek() == null) { for(int i = 0; i < height();i++) result += ' '; list.remove(); list.add(null); level/=2; } } return result + " "; } }
Thank you Dr. Boroojeni for the video!!!!
import java.util.*; public class Calculator { private static Scanner s = new Scanner(System.in); private static int getOp(String exp, int cur) { Scanner s = new Scanner(exp.substring(cur)); s.useDelimiter("[^0-9]"); return s.nextInt(); } private static int doOp(int op1, int op2, char operator) throws Exception { switch (operator) { case '+': return op1 + op2; case '-': return op1 - op2; case '*': return op1 * op2; case '/': return op1 / op2; default: throw new Exception("Unbalanced parentheses: An open parenthesis has not get closed!"); } } private static int comparePrecedence(char op1, char op2) { if (op1 == '+' || op1 == '-') if (op2 == '+' || op2 == '-') return 0; else return -1; else if (op2 == '+' || op2 == '-') return 1; else return 0; } public static void main(String args[]) throws Exception { Stack<Character> operators = new Stack<Character>(); Stack<Integer> operands = new Stack<Integer>(); while (true) { System.out.println("Please enter a new expression: "); String exp = s.nextLine(); if (exp.equals("DONE")) break; char prev = 0; for (int cur = 0; cur < exp.length(); cur++) { switch (exp.charAt(cur)) { case '(': operators.push(exp.charAt(cur)); break; case '+': case '-': if(prev == 0 || prev == '(')//Treat + and - as the explicit sign of an integer! operands.push(0); case '*': case '/': //Don't push +,- over +,-,*,/ //Don't push *,/ over *,/ while (!operators.isEmpty() && operators.peek() != '(') if (comparePrecedence(operators.peek(), exp.charAt(cur)) >= 0) { int op2 = operands.pop();//pop the second operand first int result = doOp(operands.pop(), op2, operators.pop()); operands.push(result); } else break; operators.push(exp.charAt(cur)); break; case ')': while (!operators.isEmpty() && operators.peek() != '(') { int op2 = operands.pop(); operands.push(doOp(operands.pop(), op2, operators.pop())); } if(operators.empty()) throw new Exception("Unbalanced parentheses: An open parenthesis has been closed multiple times!"); operators.pop();//pop the matching open parenthesis break; case ' ': case '\t'://skipping the white space characters break; default: if (Character.isDigit(exp.charAt(cur))) {//integer found! int temp = getOp(exp, cur); while (cur < exp.length() && Character.isDigit(exp.charAt(cur)))//skip the whole number cur++; cur--; operands.push(temp);//push it to operand's stack } else throw new Exception("Error: bad input"); } if(!Character.isWhitespace(exp.charAt(cur))) prev = exp.charAt(cur); } int result; while (!operators.isEmpty()) { int op2 = operands.pop(); operands.push(doOp(operands.pop(), op2, operators.pop())); } System.out.println("The result is " + operands.pop()); } } }
(the remainder of code mentioned in the description) # result7: $s7 = sum of numbers from 1 to n # translating int sum = 0; for(int i = 1; i <= n;i++) sum += i; # add $s7, $zero, $zero #initializing sum ($s7) to 0 # addi $s1, $zero, 1 #$s1 representing i is initialized to 1 # FOR1: slt $t0, $s0, $s1 #if ( n < i) $t0 = 1, else $t0 = 0 if ( i <= n) # bne $t0, $zero, EXIT1 #end the loop if i > n # add $s7, $s7, $s1 # sum += i # addi $s1, $s1, 1 #i++ # j FOR1 # EXIT1: # result8: $s7 = sum of odd numbers from 1 to n # translating int sum = 0; for(int i = 1; i <= n;i++) if(i&1 == 1)sum += i; # add $s7, $zero, $zero #initializing sum ($s7) to 0 # addi $s1, $zero, 1 #$s1 representing i is initialized to 1 # FOR2: slt $t0, $s0, $s1 #if ( n < i) $t0 = 1, else $t0 = 0 if ( i <= n) # bne $t0, $zero, EXIT2 #end the loop if i > n # andi $t1, $s1, 1 #$t1 = i & 1 # beq $t1, $zero, INC2 # if i&1 is zero, continue the for loop # add $s7, $s7, $s1 # sum += i # INC2: addi $s1, $s1, 1 #i++ # j FOR2 # EXIT2: # result9: $s7 = sum of even numbers from 1 to n # translating int sum = 0; for(int i = 1; i <= n;i++) if(i&1 == 0)sum += i; # add $s7, $zero, $zero #initializing sum ($s7) to 0 # addi $s1, $zero, 1 #$s1 representing i is initialized to 1 # FOR3: slt $t0, $s0, $s1 #if ( n < i) $t0 = 1, else $t0 = 0 if ( i <= n) # bne $t0, $zero, EXIT3 #end the loop if i > n # andi $t1, $s1, 1 #$t1 = i & 1 # bne $t1, $zero, INC3 # if i&1 is 1, continue the for loop # add $s7, $s7, $s1 # sum += i # INC3: addi $s1, $s1, 1 #i++ # j FOR3 # EXIT3: # result10: $s7 = n/4 # srl $s7, $s0, 2 #$s7 = $s0 >> 2 = $s0 / 2^2 # result11: $s7 = 8 * n sll $s7, $s0, 3 #$s7 = $s0 << 3 = $s0 * 2^3 # Output message la $a0,result1 #Print 23 and # la $a0,result2 #Print 18 or # la $a0,result3 #Print 9 xor # la $a0,result4 #Print bitwise-negation of # la $a0,result5 #Print 57 + # la $a0,result6 #Print 57 - # la $a0,result7 #Print sum of numbers from 1 to # la $a0,result8 #Print sum of odd numbers from 1 to # la $a0,result9 #Print sum of even numbers from 1 to # la $a0,result10 #Print quarter of # la $a0,result11 #Print 8 times li $v0,4 syscall move $a0,$s0 #Print n li $v0,1 syscall la $a0,result #Print is equal to li $v0,4 syscall move $a0,$s7 #Print the answer li $v0,1 syscall la $a0,endl #Print ' ' li $v0,4 syscall # End program li $v0,10 syscall .data prompt: .asciiz "This program tests different MIPS arithmetic and logical operations. Enter a non-negative number less than 100: " result: .asciiz " is equal to " result1: .asciiz "23 and " result2: .asciiz "18 or " result3: .asciiz "9 xor " result4: .asciiz "bitwise-negation of " result5: .asciiz "57 + " result6: .asciiz "57 - " result7: .asciiz "sum of numbers from 1 to " result8: .asciiz "sum of odd numbers from 1 to " result9: .asciiz "sum of even numbers from 1 to " result10: .asciiz "quarter of " result11: .asciiz "8 times " endl: .asciiz " "