diff --git a/4.BST/Question_2.cpp b/4.BST/Question_2.cpp index 288b022d2..fc3591561 100644 --- a/4.BST/Question_2.cpp +++ b/4.BST/Question_2.cpp @@ -1,42 +1,42 @@ -#include -#include - -using namespace std; - -/*Tree node definiton*/ -struct TreeNode{ - int data; - TreeNode *left; - TreeNode *right; - TreeNode(int x){ - data=x; - left=right=NULL; - } -}; -int preorder_index=0; -TreeNode* buildTree(vector &preorder,vector &indexOfinorder,int start,int end){ - if(start<=end){ - TreeNode *node = new TreeNode(preorder[preorder_index]); - int inorder_index = /*TODO*/ ; - node->left = /*TODO*/; - node->right = /*TODO*/; - return /*TODO*/; - } - else - return /*TODO*/; -} - -void print_preorder(TreeNode *root){ - /*TODO*/ -} - -void print_inorder(TreeNode *root){ - /*TODO*/ -} - -int main(){ - vector preorder = {7,4,2, 3, 6, 5, 12, 9, 8, 11, 19,15, 20},indexOfinorder={5,2,0,1,4,3,9,7,6,8,11,10,12}; - TreeNode *root = buildTree(preorder,indexOfinorder,0,indexOfinorder.size()-1); - print_preorder(root);cout< +#include + +using namespace std; + +/*Tree node definiton*/ +struct TreeNode{ + int data; + TreeNode *left; + TreeNode *right; + TreeNode(int x){ + data=x; + left=right=NULL; + } +}; +int preorder_index=0; +TreeNode* buildTree(vector &preorder,vector &indexOfinorder,int start,int end){ + if(start<=end){ + TreeNode *node = new TreeNode(preorder[preorder_index]); + int inorder_index = /*TODO*/ ; + node->left = /*TODO*/; + node->right = /*TODO*/; + return /*TODO*/; + } + else + return /*TODO*/; +} + +void print_preorder(TreeNode *root){ + /*TODO*/ +} + +void print_inorder(TreeNode *root){ + /*TODO*/ +} + +int main(){ + vector preorder = {7,4,2, 3, 6, 5, 12, 9, 8, 11, 19,15, 20},indexOfinorder={5,2,0,1,4,3,9,7,6,8,11,10,12}; + TreeNode *root = buildTree(preorder,indexOfinorder,0,indexOfinorder.size()-1); + print_preorder(root);cout< -#include - -struct node -{ - int key; - struct node *left, *right; -}; - - -struct node *newNode(int item) -{ - struct node *temp = (struct node *)malloc(sizeof(struct node)); - temp->key = item; - temp->left = temp->right = NULL; - return temp; -} - - -void inorder(struct node *root) -{ - if (root != NULL) - { - inorder(root->left); - printf("%d \n", root->key); - inorder(root->right); - } -} - - -struct node* insert(struct node* node, int key) -{ - /* If the tree is empty, return a new node */ - if (node == NULL) return newNode(key); - - /* Otherwise, recur down the tree */ - if (key < node->key) - node->left = insert(node->left, key); - else if (key > node->key) - node->right = insert(node->right, key); - - /* return the (unchanged) node pointer */ - return node; -} - - -int main() -{ - - struct node *root = NULL; - root = insert(root, 50); - insert(root, 30); - insert(root, 20); - insert(root, 40); - insert(root, 70); - insert(root, 60); - insert(root, 80); - - - inorder(root); - - return 0; + + +#include +#include + +struct node +{ + int key; + struct node *left, *right; +}; + + +struct node *newNode(int item) +{ + struct node *temp = (struct node *)malloc(sizeof(struct node)); + temp->key = item; + temp->left = temp->right = NULL; + return temp; +} + + +void inorder(struct node *root) +{ + if (root != NULL) + { + inorder(root->left); + printf("%d \n", root->key); + inorder(root->right); + } +} + + +struct node* insert(struct node* node, int key) +{ + /* If the tree is empty, return a new node */ + if (node == NULL) return newNode(key); + + /* Otherwise, recur down the tree */ + if (key < node->key) + node->left = insert(node->left, key); + else if (key > node->key) + node->right = insert(node->right, key); + + /* return the (unchanged) node pointer */ + return node; +} + + +int main() +{ + + struct node *root = NULL; + root = insert(root, 50); + insert(root, 30); + insert(root, 20); + insert(root, 40); + insert(root, 70); + insert(root, 60); + insert(root, 80); + + + inorder(root); + + return 0; } \ No newline at end of file diff --git a/Data-Structures-And-Algorithms-Hacktoberfest18-master/c/ds/CDLL/CDLL.cfp b/Data-Structures-And-Algorithms-Hacktoberfest18-master/c/ds/CDLL/CDLL.cfp index 549408147..6c5e06e0b 100644 --- a/Data-Structures-And-Algorithms-Hacktoberfest18-master/c/ds/CDLL/CDLL.cfp +++ b/Data-Structures-And-Algorithms-Hacktoberfest18-master/c/ds/CDLL/CDLL.cfp @@ -1,319 +1,319 @@ - -CDLL -CUI -CDLL -exe - - CDLL.c - main.c - - - CDLL.h - - - -main.c -mingw2.95 - - CDLL - exe - mingw2.95 - mingw2.95 - - $(CFRoot)\mingw32\Include - $(CFRoot)\mingw32\Include\G++ - - - $(CFRoot)\mingw32\Lib - - - $(CFRoot)\mingw32\Bin - - - - - - - - - - - - - - - - -ggdb - -ggdb - - - - - - - - - - - - - - - - - - - - - - - - - -s - -s - - - - $(CFRoot)\Build.log - lib;a - o;obj - res - - - - gcc.exe - "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) - c - $(PATH)$(NAME).o - o - - Compiling $(FILENAME)...#81001 - - - g++.exe - "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) - cpp;cxx;c++ - $(PATH)$(NAME).o - o - - Compiling $(FILENAME)...#81001 - - - g++.exe - $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -L$(LibPaths) -B$(ExePaths) - o;obj;a;lib;res - $(Target) - cui - - Linking...#81002 - - - g++.exe - $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -mwindows -L$(LibPaths) -B$(ExePaths) - o;obj;a;lib;res - $(Target) - gui - - Linking...#81002 - - - dllwrap.exe - --driver-name "g++" --output-def "$(ShortPath)$(Name).def" --implib "$(ShortPath)$(Name).lib" -L$(LibPaths) $(ProjectFiles) -o "$(ShortTarget)" $(LinkerOptions) -l$(Libs) - o;obj;a;lib;res;def - $(Target) - dll - - Linking...#81002 - - - ar.exe - -r "$(Target)" $(ProjectFiles) - o;obj - $(Target) - lib - - Linking...#81002 - - - windres.exe - -O coff -i "$(ShortFileName)" -o "$(Path)$(Name).res" --include-dir=$(ShortPath) --include-dir=$(IncPaths) - rc - $(PATH)$(NAME).res - res - - Compiling $(FILENAME)...#81001 - - - gdb.exe - gdebug.dll - exe;dll - - - - #81003 - - - $(Target) - $(Parameters) - exe - - - - #81004 - - - $(HostApp) - $(Parameters) - dll - - - - #81004 - - - fdel.exe - "$(Path)$(Name).o" $(FileName) - c;cpp;cxx;c++ - $(Target) - - - - - - fdel.exe - "$(Path)$(Name).res" $(FileName) - rc - $(Target) - - - - - - fdel.exe - "$(Path)$(Name).o" -silent - *.* - $(Target) - - - - - - fdel.exe - "$(Target)" - *.* - - - - - - - - - - "C Compiler""C++ Compiler""Resource Compiler" - - - - Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81005 - Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)#81006 - - - - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81007 - Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)#81008 - \r\n\r\n\r\n - - - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81009 - Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)#81010 - - - - - - "Make" - "Run""Run DLL" - - - "Make" - "Run""Run DLL" - - #81011 - #81012 - - - - - - "Make" - "Debugger" - - - "Make" - "Debugger" - - #81013 - #81014 - - - - - - "Clean Objects""Clean Resource" - "Clean Io" - "Clean Target" - - - "Clean Objects""Clean Resource""Clean Io" - "Clean Io" - "Clean Target" - - Complete Clean $(TargetName)#81015 - Clean $(TargetName) error#81016 - - - - - - + +CDLL +CUI +CDLL +exe + + CDLL.c + main.c + + + CDLL.h + + + +main.c +mingw2.95 + + CDLL + exe + mingw2.95 + mingw2.95 + + $(CFRoot)\mingw32\Include + $(CFRoot)\mingw32\Include\G++ + + + $(CFRoot)\mingw32\Lib + + + $(CFRoot)\mingw32\Bin + + + + + + + + + + + + + + + + -ggdb + -ggdb + + + + + + + + + + + + + + + + + + + + + + + + + -s + -s + + + + $(CFRoot)\Build.log + lib;a + o;obj + res + + + + gcc.exe + "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) + c + $(PATH)$(NAME).o + o + + Compiling $(FILENAME)...#81001 + + + g++.exe + "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) + cpp;cxx;c++ + $(PATH)$(NAME).o + o + + Compiling $(FILENAME)...#81001 + + + g++.exe + $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -L$(LibPaths) -B$(ExePaths) + o;obj;a;lib;res + $(Target) + cui + + Linking...#81002 + + + g++.exe + $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -mwindows -L$(LibPaths) -B$(ExePaths) + o;obj;a;lib;res + $(Target) + gui + + Linking...#81002 + + + dllwrap.exe + --driver-name "g++" --output-def "$(ShortPath)$(Name).def" --implib "$(ShortPath)$(Name).lib" -L$(LibPaths) $(ProjectFiles) -o "$(ShortTarget)" $(LinkerOptions) -l$(Libs) + o;obj;a;lib;res;def + $(Target) + dll + + Linking...#81002 + + + ar.exe + -r "$(Target)" $(ProjectFiles) + o;obj + $(Target) + lib + + Linking...#81002 + + + windres.exe + -O coff -i "$(ShortFileName)" -o "$(Path)$(Name).res" --include-dir=$(ShortPath) --include-dir=$(IncPaths) + rc + $(PATH)$(NAME).res + res + + Compiling $(FILENAME)...#81001 + + + gdb.exe + gdebug.dll + exe;dll + + + + #81003 + + + $(Target) + $(Parameters) + exe + + + + #81004 + + + $(HostApp) + $(Parameters) + dll + + + + #81004 + + + fdel.exe + "$(Path)$(Name).o" $(FileName) + c;cpp;cxx;c++ + $(Target) + + + + + + fdel.exe + "$(Path)$(Name).res" $(FileName) + rc + $(Target) + + + + + + fdel.exe + "$(Path)$(Name).o" -silent + *.* + $(Target) + + + + + + fdel.exe + "$(Target)" + *.* + + + + + + + + + + "C Compiler""C++ Compiler""Resource Compiler" + + + + Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81005 + Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)#81006 + + + + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81007 + Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)#81008 + \r\n\r\n\r\n + + + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81009 + Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)#81010 + + + + + + "Make" + "Run""Run DLL" + + + "Make" + "Run""Run DLL" + + #81011 + #81012 + + + + + + "Make" + "Debugger" + + + "Make" + "Debugger" + + #81013 + #81014 + + + + + + "Clean Objects""Clean Resource" + "Clean Io" + "Clean Target" + + + "Clean Objects""Clean Resource""Clean Io" + "Clean Io" + "Clean Target" + + Complete Clean $(TargetName)#81015 + Clean $(TargetName) error#81016 + + + + + + diff --git a/Data-Structures-And-Algorithms-Hacktoberfest18-master/c/ds/CSLL/CSLL.cfp b/Data-Structures-And-Algorithms-Hacktoberfest18-master/c/ds/CSLL/CSLL.cfp index fdd705b28..c69cfd90a 100644 --- a/Data-Structures-And-Algorithms-Hacktoberfest18-master/c/ds/CSLL/CSLL.cfp +++ b/Data-Structures-And-Algorithms-Hacktoberfest18-master/c/ds/CSLL/CSLL.cfp @@ -1,319 +1,319 @@ - -CSLL -CUI -CSLL -exe - - main.c - CSLL.c - - - CSLL.h - - - -main.c -mingw2.95 - - CSLL - exe - mingw2.95 - mingw2.95 - - $(CFRoot)\mingw32\Include - $(CFRoot)\mingw32\Include\G++ - - - $(CFRoot)\mingw32\Lib - - - $(CFRoot)\mingw32\Bin - - - - - - - - - - - - - - - - -ggdb - -ggdb - - - - - - - - - - - - - - - - - - - - - - - - - -s - -s - - - - $(CFRoot)\Build.log - lib;a - o;obj - res - - - - gcc.exe - "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) - c - $(PATH)$(NAME).o - o - - Compiling $(FILENAME)...#81001 - - - g++.exe - "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) - cpp;cxx;c++ - $(PATH)$(NAME).o - o - - Compiling $(FILENAME)...#81001 - - - g++.exe - $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -L$(LibPaths) -B$(ExePaths) - o;obj;a;lib;res - $(Target) - cui - - Linking...#81002 - - - g++.exe - $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -mwindows -L$(LibPaths) -B$(ExePaths) - o;obj;a;lib;res - $(Target) - gui - - Linking...#81002 - - - dllwrap.exe - --driver-name "g++" --output-def "$(ShortPath)$(Name).def" --implib "$(ShortPath)$(Name).lib" -L$(LibPaths) $(ProjectFiles) -o "$(ShortTarget)" $(LinkerOptions) -l$(Libs) - o;obj;a;lib;res;def - $(Target) - dll - - Linking...#81002 - - - ar.exe - -r "$(Target)" $(ProjectFiles) - o;obj - $(Target) - lib - - Linking...#81002 - - - windres.exe - -O coff -i "$(ShortFileName)" -o "$(Path)$(Name).res" --include-dir=$(ShortPath) --include-dir=$(IncPaths) - rc - $(PATH)$(NAME).res - res - - Compiling $(FILENAME)...#81001 - - - gdb.exe - gdebug.dll - exe;dll - - - - #81003 - - - $(Target) - $(Parameters) - exe - - - - #81004 - - - $(HostApp) - $(Parameters) - dll - - - - #81004 - - - fdel.exe - "$(Path)$(Name).o" $(FileName) - c;cpp;cxx;c++ - $(Target) - - - - - - fdel.exe - "$(Path)$(Name).res" $(FileName) - rc - $(Target) - - - - - - fdel.exe - "$(Path)$(Name).o" -silent - *.* - $(Target) - - - - - - fdel.exe - "$(Target)" - *.* - - - - - - - - - - "C Compiler""C++ Compiler""Resource Compiler" - - - - Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81005 - Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)#81006 - - - - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81007 - Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)#81008 - \r\n\r\n\r\n - - - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81009 - Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)#81010 - - - - - - "Make" - "Run""Run DLL" - - - "Make" - "Run""Run DLL" - - #81011 - #81012 - - - - - - "Make" - "Debugger" - - - "Make" - "Debugger" - - #81013 - #81014 - - - - - - "Clean Objects""Clean Resource" - "Clean Io" - "Clean Target" - - - "Clean Objects""Clean Resource""Clean Io" - "Clean Io" - "Clean Target" - - Complete Clean $(TargetName)#81015 - Clean $(TargetName) error#81016 - - - - - - + +CSLL +CUI +CSLL +exe + + main.c + CSLL.c + + + CSLL.h + + + +main.c +mingw2.95 + + CSLL + exe + mingw2.95 + mingw2.95 + + $(CFRoot)\mingw32\Include + $(CFRoot)\mingw32\Include\G++ + + + $(CFRoot)\mingw32\Lib + + + $(CFRoot)\mingw32\Bin + + + + + + + + + + + + + + + + -ggdb + -ggdb + + + + + + + + + + + + + + + + + + + + + + + + + -s + -s + + + + $(CFRoot)\Build.log + lib;a + o;obj + res + + + + gcc.exe + "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) + c + $(PATH)$(NAME).o + o + + Compiling $(FILENAME)...#81001 + + + g++.exe + "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) + cpp;cxx;c++ + $(PATH)$(NAME).o + o + + Compiling $(FILENAME)...#81001 + + + g++.exe + $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -L$(LibPaths) -B$(ExePaths) + o;obj;a;lib;res + $(Target) + cui + + Linking...#81002 + + + g++.exe + $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -mwindows -L$(LibPaths) -B$(ExePaths) + o;obj;a;lib;res + $(Target) + gui + + Linking...#81002 + + + dllwrap.exe + --driver-name "g++" --output-def "$(ShortPath)$(Name).def" --implib "$(ShortPath)$(Name).lib" -L$(LibPaths) $(ProjectFiles) -o "$(ShortTarget)" $(LinkerOptions) -l$(Libs) + o;obj;a;lib;res;def + $(Target) + dll + + Linking...#81002 + + + ar.exe + -r "$(Target)" $(ProjectFiles) + o;obj + $(Target) + lib + + Linking...#81002 + + + windres.exe + -O coff -i "$(ShortFileName)" -o "$(Path)$(Name).res" --include-dir=$(ShortPath) --include-dir=$(IncPaths) + rc + $(PATH)$(NAME).res + res + + Compiling $(FILENAME)...#81001 + + + gdb.exe + gdebug.dll + exe;dll + + + + #81003 + + + $(Target) + $(Parameters) + exe + + + + #81004 + + + $(HostApp) + $(Parameters) + dll + + + + #81004 + + + fdel.exe + "$(Path)$(Name).o" $(FileName) + c;cpp;cxx;c++ + $(Target) + + + + + + fdel.exe + "$(Path)$(Name).res" $(FileName) + rc + $(Target) + + + + + + fdel.exe + "$(Path)$(Name).o" -silent + *.* + $(Target) + + + + + + fdel.exe + "$(Target)" + *.* + + + + + + + + + + "C Compiler""C++ Compiler""Resource Compiler" + + + + Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81005 + Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)#81006 + + + + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81007 + Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)#81008 + \r\n\r\n\r\n + + + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81009 + Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)#81010 + + + + + + "Make" + "Run""Run DLL" + + + "Make" + "Run""Run DLL" + + #81011 + #81012 + + + + + + "Make" + "Debugger" + + + "Make" + "Debugger" + + #81013 + #81014 + + + + + + "Clean Objects""Clean Resource" + "Clean Io" + "Clean Target" + + + "Clean Objects""Clean Resource""Clean Io" + "Clean Io" + "Clean Target" + + Complete Clean $(TargetName)#81015 + Clean $(TargetName) error#81016 + + + + + + diff --git a/Data-Structures-And-Algorithms-Hacktoberfest18-master/c/ds/DLL/DLL.cfp b/Data-Structures-And-Algorithms-Hacktoberfest18-master/c/ds/DLL/DLL.cfp index 1f56475ae..535fb05b3 100644 --- a/Data-Structures-And-Algorithms-Hacktoberfest18-master/c/ds/DLL/DLL.cfp +++ b/Data-Structures-And-Algorithms-Hacktoberfest18-master/c/ds/DLL/DLL.cfp @@ -1,318 +1,318 @@ - -DLL -CUI -DLL -exe - - ..\main.c - ..\DLL.c - - - ..\DLL.h - - - -mingw2.95 - - DLL - exe - mingw2.95 - mingw2.95 - - $(CFRoot)\mingw32\Include - $(CFRoot)\mingw32\Include\G++ - - - $(CFRoot)\mingw32\Lib - - - $(CFRoot)\mingw32\Bin - - - - - - - - - - - - - - - - -ggdb - -ggdb - - - - - - - - - - - - - - - - - - - - - - - - - -s - -s - - - - $(CFRoot)\Build.log - lib;a - o;obj - res - - - - gcc.exe - "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) - c - $(PATH)$(NAME).o - o - - Compiling $(FILENAME)...#81001 - - - g++.exe - "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) - cpp;cxx;c++ - $(PATH)$(NAME).o - o - - Compiling $(FILENAME)...#81001 - - - g++.exe - $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -L$(LibPaths) -B$(ExePaths) - o;obj;a;lib;res - $(Target) - cui - - Linking...#81002 - - - g++.exe - $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -mwindows -L$(LibPaths) -B$(ExePaths) - o;obj;a;lib;res - $(Target) - gui - - Linking...#81002 - - - dllwrap.exe - --driver-name "g++" --output-def "$(ShortPath)$(Name).def" --implib "$(ShortPath)$(Name).lib" -L$(LibPaths) $(ProjectFiles) -o "$(ShortTarget)" $(LinkerOptions) -l$(Libs) - o;obj;a;lib;res;def - $(Target) - dll - - Linking...#81002 - - - ar.exe - -r "$(Target)" $(ProjectFiles) - o;obj - $(Target) - lib - - Linking...#81002 - - - windres.exe - -O coff -i "$(ShortFileName)" -o "$(Path)$(Name).res" --include-dir=$(ShortPath) --include-dir=$(IncPaths) - rc - $(PATH)$(NAME).res - res - - Compiling $(FILENAME)...#81001 - - - gdb.exe - gdebug.dll - exe;dll - - - - #81003 - - - $(Target) - $(Parameters) - exe - - - - #81004 - - - $(HostApp) - $(Parameters) - dll - - - - #81004 - - - fdel.exe - "$(Path)$(Name).o" $(FileName) - c;cpp;cxx;c++ - $(Target) - - - - - - fdel.exe - "$(Path)$(Name).res" $(FileName) - rc - $(Target) - - - - - - fdel.exe - "$(Path)$(Name).o" -silent - *.* - $(Target) - - - - - - fdel.exe - "$(Target)" - *.* - - - - - - - - - - "C Compiler""C++ Compiler""Resource Compiler" - - - - Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81005 - Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)#81006 - - - - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81007 - Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)#81008 - \r\n\r\n\r\n - - - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81009 - Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)#81010 - - - - - - "Make" - "Run""Run DLL" - - - "Make" - "Run""Run DLL" - - #81011 - #81012 - - - - - - "Make" - "Debugger" - - - "Make" - "Debugger" - - #81013 - #81014 - - - - - - "Clean Objects""Clean Resource" - "Clean Io" - "Clean Target" - - - "Clean Objects""Clean Resource""Clean Io" - "Clean Io" - "Clean Target" - - Complete Clean $(TargetName)#81015 - Clean $(TargetName) error#81016 - - - - - - + +DLL +CUI +DLL +exe + + ..\main.c + ..\DLL.c + + + ..\DLL.h + + + +mingw2.95 + + DLL + exe + mingw2.95 + mingw2.95 + + $(CFRoot)\mingw32\Include + $(CFRoot)\mingw32\Include\G++ + + + $(CFRoot)\mingw32\Lib + + + $(CFRoot)\mingw32\Bin + + + + + + + + + + + + + + + + -ggdb + -ggdb + + + + + + + + + + + + + + + + + + + + + + + + + -s + -s + + + + $(CFRoot)\Build.log + lib;a + o;obj + res + + + + gcc.exe + "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) + c + $(PATH)$(NAME).o + o + + Compiling $(FILENAME)...#81001 + + + g++.exe + "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) + cpp;cxx;c++ + $(PATH)$(NAME).o + o + + Compiling $(FILENAME)...#81001 + + + g++.exe + $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -L$(LibPaths) -B$(ExePaths) + o;obj;a;lib;res + $(Target) + cui + + Linking...#81002 + + + g++.exe + $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -mwindows -L$(LibPaths) -B$(ExePaths) + o;obj;a;lib;res + $(Target) + gui + + Linking...#81002 + + + dllwrap.exe + --driver-name "g++" --output-def "$(ShortPath)$(Name).def" --implib "$(ShortPath)$(Name).lib" -L$(LibPaths) $(ProjectFiles) -o "$(ShortTarget)" $(LinkerOptions) -l$(Libs) + o;obj;a;lib;res;def + $(Target) + dll + + Linking...#81002 + + + ar.exe + -r "$(Target)" $(ProjectFiles) + o;obj + $(Target) + lib + + Linking...#81002 + + + windres.exe + -O coff -i "$(ShortFileName)" -o "$(Path)$(Name).res" --include-dir=$(ShortPath) --include-dir=$(IncPaths) + rc + $(PATH)$(NAME).res + res + + Compiling $(FILENAME)...#81001 + + + gdb.exe + gdebug.dll + exe;dll + + + + #81003 + + + $(Target) + $(Parameters) + exe + + + + #81004 + + + $(HostApp) + $(Parameters) + dll + + + + #81004 + + + fdel.exe + "$(Path)$(Name).o" $(FileName) + c;cpp;cxx;c++ + $(Target) + + + + + + fdel.exe + "$(Path)$(Name).res" $(FileName) + rc + $(Target) + + + + + + fdel.exe + "$(Path)$(Name).o" -silent + *.* + $(Target) + + + + + + fdel.exe + "$(Target)" + *.* + + + + + + + + + + "C Compiler""C++ Compiler""Resource Compiler" + + + + Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81005 + Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)#81006 + + + + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81007 + Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)#81008 + \r\n\r\n\r\n + + + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81009 + Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)#81010 + + + + + + "Make" + "Run""Run DLL" + + + "Make" + "Run""Run DLL" + + #81011 + #81012 + + + + + + "Make" + "Debugger" + + + "Make" + "Debugger" + + #81013 + #81014 + + + + + + "Clean Objects""Clean Resource" + "Clean Io" + "Clean Target" + + + "Clean Objects""Clean Resource""Clean Io" + "Clean Io" + "Clean Target" + + Complete Clean $(TargetName)#81015 + Clean $(TargetName) error#81016 + + + + + + diff --git a/Data-Structures-And-Algorithms-Hacktoberfest18-master/c/ds/SLL/SLL.cfp b/Data-Structures-And-Algorithms-Hacktoberfest18-master/c/ds/SLL/SLL.cfp index 65a2be19c..f53108598 100644 --- a/Data-Structures-And-Algorithms-Hacktoberfest18-master/c/ds/SLL/SLL.cfp +++ b/Data-Structures-And-Algorithms-Hacktoberfest18-master/c/ds/SLL/SLL.cfp @@ -1,318 +1,318 @@ - -SLL -CUI -SLL -exe - - SLL.c - main.c - - - SLL.h - - - -mingw2.95 - - SLL - exe - mingw2.95 - mingw2.95 - - $(CFRoot)\mingw32\Include - $(CFRoot)\mingw32\Include\G++ - - - $(CFRoot)\mingw32\Lib - - - $(CFRoot)\mingw32\Bin - - - - - - - - - - - - - - - - -ggdb - -ggdb - - - - - - - - - - - - - - - - - - - - - - - - - -s - -s - - - - $(CFRoot)\Build.log - lib;a - o;obj - res - - - - gcc.exe - "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) - c - $(PATH)$(NAME).o - o - - Compiling $(FILENAME)...#81001 - - - g++.exe - "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) - cpp;cxx;c++ - $(PATH)$(NAME).o - o - - Compiling $(FILENAME)...#81001 - - - g++.exe - $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -L$(LibPaths) -B$(ExePaths) - o;obj;a;lib;res - $(Target) - cui - - Linking...#81002 - - - g++.exe - $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -mwindows -L$(LibPaths) -B$(ExePaths) - o;obj;a;lib;res - $(Target) - gui - - Linking...#81002 - - - dllwrap.exe - --driver-name "g++" --output-def "$(ShortPath)$(Name).def" --implib "$(ShortPath)$(Name).lib" -L$(LibPaths) $(ProjectFiles) -o "$(ShortTarget)" $(LinkerOptions) -l$(Libs) - o;obj;a;lib;res;def - $(Target) - dll - - Linking...#81002 - - - ar.exe - -r "$(Target)" $(ProjectFiles) - o;obj - $(Target) - lib - - Linking...#81002 - - - windres.exe - -O coff -i "$(ShortFileName)" -o "$(Path)$(Name).res" --include-dir=$(ShortPath) --include-dir=$(IncPaths) - rc - $(PATH)$(NAME).res - res - - Compiling $(FILENAME)...#81001 - - - gdb.exe - gdebug.dll - exe;dll - - - - #81003 - - - $(Target) - $(Parameters) - exe - - - - #81004 - - - $(HostApp) - $(Parameters) - dll - - - - #81004 - - - fdel.exe - "$(Path)$(Name).o" $(FileName) - c;cpp;cxx;c++ - $(Target) - - - - - - fdel.exe - "$(Path)$(Name).res" $(FileName) - rc - $(Target) - - - - - - fdel.exe - "$(Path)$(Name).o" -silent - *.* - $(Target) - - - - - - fdel.exe - "$(Target)" - *.* - - - - - - - - - - "C Compiler""C++ Compiler""Resource Compiler" - - - - Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81005 - Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)#81006 - - - - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81007 - Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)#81008 - \r\n\r\n\r\n - - - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81009 - Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)#81010 - - - - - - "Make" - "Run""Run DLL" - - - "Make" - "Run""Run DLL" - - #81011 - #81012 - - - - - - "Make" - "Debugger" - - - "Make" - "Debugger" - - #81013 - #81014 - - - - - - "Clean Objects""Clean Resource" - "Clean Io" - "Clean Target" - - - "Clean Objects""Clean Resource""Clean Io" - "Clean Io" - "Clean Target" - - Complete Clean $(TargetName)#81015 - Clean $(TargetName) error#81016 - - - - - - + +SLL +CUI +SLL +exe + + SLL.c + main.c + + + SLL.h + + + +mingw2.95 + + SLL + exe + mingw2.95 + mingw2.95 + + $(CFRoot)\mingw32\Include + $(CFRoot)\mingw32\Include\G++ + + + $(CFRoot)\mingw32\Lib + + + $(CFRoot)\mingw32\Bin + + + + + + + + + + + + + + + + -ggdb + -ggdb + + + + + + + + + + + + + + + + + + + + + + + + + -s + -s + + + + $(CFRoot)\Build.log + lib;a + o;obj + res + + + + gcc.exe + "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) + c + $(PATH)$(NAME).o + o + + Compiling $(FILENAME)...#81001 + + + g++.exe + "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) + cpp;cxx;c++ + $(PATH)$(NAME).o + o + + Compiling $(FILENAME)...#81001 + + + g++.exe + $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -L$(LibPaths) -B$(ExePaths) + o;obj;a;lib;res + $(Target) + cui + + Linking...#81002 + + + g++.exe + $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -mwindows -L$(LibPaths) -B$(ExePaths) + o;obj;a;lib;res + $(Target) + gui + + Linking...#81002 + + + dllwrap.exe + --driver-name "g++" --output-def "$(ShortPath)$(Name).def" --implib "$(ShortPath)$(Name).lib" -L$(LibPaths) $(ProjectFiles) -o "$(ShortTarget)" $(LinkerOptions) -l$(Libs) + o;obj;a;lib;res;def + $(Target) + dll + + Linking...#81002 + + + ar.exe + -r "$(Target)" $(ProjectFiles) + o;obj + $(Target) + lib + + Linking...#81002 + + + windres.exe + -O coff -i "$(ShortFileName)" -o "$(Path)$(Name).res" --include-dir=$(ShortPath) --include-dir=$(IncPaths) + rc + $(PATH)$(NAME).res + res + + Compiling $(FILENAME)...#81001 + + + gdb.exe + gdebug.dll + exe;dll + + + + #81003 + + + $(Target) + $(Parameters) + exe + + + + #81004 + + + $(HostApp) + $(Parameters) + dll + + + + #81004 + + + fdel.exe + "$(Path)$(Name).o" $(FileName) + c;cpp;cxx;c++ + $(Target) + + + + + + fdel.exe + "$(Path)$(Name).res" $(FileName) + rc + $(Target) + + + + + + fdel.exe + "$(Path)$(Name).o" -silent + *.* + $(Target) + + + + + + fdel.exe + "$(Target)" + *.* + + + + + + + + + + "C Compiler""C++ Compiler""Resource Compiler" + + + + Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81005 + Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)#81006 + + + + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81007 + Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)#81008 + \r\n\r\n\r\n + + + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81009 + Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)#81010 + + + + + + "Make" + "Run""Run DLL" + + + "Make" + "Run""Run DLL" + + #81011 + #81012 + + + + + + "Make" + "Debugger" + + + "Make" + "Debugger" + + #81013 + #81014 + + + + + + "Clean Objects""Clean Resource" + "Clean Io" + "Clean Target" + + + "Clean Objects""Clean Resource""Clean Io" + "Clean Io" + "Clean Target" + + Complete Clean $(TargetName)#81015 + Clean $(TargetName) error#81016 + + + + + + diff --git a/Graphs/Graph.h b/Graphs/Graph.h index 721c910a4..d27ab1f8f 100644 --- a/Graphs/Graph.h +++ b/Graphs/Graph.h @@ -1,122 +1,122 @@ -#include -#include -#include - -using namespace std; - - - -struct Graph{ - int v; - bool **adj; - public: - Graph(int vcount); - void addEdge(int u,int v); - void deleteEdge(int u,int v); - vector BFS(int s); - vector DFS(int s); - void DFSUtil(int s,vector &dfs,vector &visited); - int countComponents(); - bool isSameComponent(int v1, int v2); -}; - -Graph::Graph(int vcount){ - this->v = vcount; - this->adj=new bool*[vcount]; - for(int i=0;iadj[i]=new bool[vcount]; - for(int i=0;iadj[u][w]=true; - this->adj[w][u]=true; -} - -void Graph::deleteEdge(int u,int w){ - this->adj[u][w]=false; - this->adj[w][u]=false; -} - -vector Graph::BFS(int s){ - vector visited(this->v); - vector bfs; - queue que; - que.push(s); - visited[s]=true; - while(!que.empty()){ - bfs.push_back(que.front()); - for(int i=0;iv;i++){ - if(adj[que.front()][i]==true && visited[i]==false){ - visited[i]=true; - que.push(i); - } - } - que.pop(); - } - return bfs; -} - -void Graph::DFSUtil(int s, vector &dfs, vector &visited){ - visited[s]=true; - dfs.push_back(s); - for(int i=0;iv;i++){ - if(this->adj[s][i]==true && visited[i]==false) - DFSUtil(i,dfs,visited); - } -} - -vector Graph::DFS(int s){ - vector visited(this->v); - vector dfs; - DFSUtil(s,dfs,visited); - return dfs; -} - - -int Graph::countComponents(){ -//write this function using either BFS or DFS - vector visited(this->v); - vector dfs; - int count=0; - int source; - while(true) - { - source=-1; - for (int i = 0; i < visited.size(); ++i) - { - if(visited[i]!=true) - { - source=i; - break; - } - } - - if(source!=-1) - { - count++; - DFSUtil(source,dfs,visited); - } - else if(source==-1) - break; - } - - return count; -} - - - -bool Graph::isSameComponent(int v1, int v2){ -//write this function using either BFS or DFS - vector Bfs=this->BFS(v1); - for(int i=0;i +#include +#include + +using namespace std; + + + +struct Graph{ + int v; + bool **adj; + public: + Graph(int vcount); + void addEdge(int u,int v); + void deleteEdge(int u,int v); + vector BFS(int s); + vector DFS(int s); + void DFSUtil(int s,vector &dfs,vector &visited); + int countComponents(); + bool isSameComponent(int v1, int v2); +}; + +Graph::Graph(int vcount){ + this->v = vcount; + this->adj=new bool*[vcount]; + for(int i=0;iadj[i]=new bool[vcount]; + for(int i=0;iadj[u][w]=true; + this->adj[w][u]=true; +} + +void Graph::deleteEdge(int u,int w){ + this->adj[u][w]=false; + this->adj[w][u]=false; +} + +vector Graph::BFS(int s){ + vector visited(this->v); + vector bfs; + queue que; + que.push(s); + visited[s]=true; + while(!que.empty()){ + bfs.push_back(que.front()); + for(int i=0;iv;i++){ + if(adj[que.front()][i]==true && visited[i]==false){ + visited[i]=true; + que.push(i); + } + } + que.pop(); + } + return bfs; +} + +void Graph::DFSUtil(int s, vector &dfs, vector &visited){ + visited[s]=true; + dfs.push_back(s); + for(int i=0;iv;i++){ + if(this->adj[s][i]==true && visited[i]==false) + DFSUtil(i,dfs,visited); + } +} + +vector Graph::DFS(int s){ + vector visited(this->v); + vector dfs; + DFSUtil(s,dfs,visited); + return dfs; +} + + +int Graph::countComponents(){ +//write this function using either BFS or DFS + vector visited(this->v); + vector dfs; + int count=0; + int source; + while(true) + { + source=-1; + for (int i = 0; i < visited.size(); ++i) + { + if(visited[i]!=true) + { + source=i; + break; + } + } + + if(source!=-1) + { + count++; + DFSUtil(source,dfs,visited); + } + else if(source==-1) + break; + } + + return count; +} + + + +bool Graph::isSameComponent(int v1, int v2){ +//write this function using either BFS or DFS + vector Bfs=this->BFS(v1); + for(int i=0;i -#include -#include "Graph.h" - -//How to compile code: g++ main.cpp -//How to run code: ./a.out < input1 - -using namespace std; - -int main() -{ - - int choice; - Graph* g=NULL; - -do{ - cout<<"1. Create new graph"<>choice; - cout<<"You entered "<>vcount; - g = new Graph(vcount); - //create graph with zero edges - //vertices are labeled as 0, 1, 2...vcount-1 - //it is a simple undirected unweighted graph - break; - - case 2: - if(g==NULL){ - cout<<"Create a new graph first"<>v1; - cout<<"Enter second endpoint of edge"; - cin>>v2; - g->addEdge(v1,v2); - break; - - case 3: - if(g==NULL){ - cout<<"Create a new graph first"<>v1; - cout<<"Enter second endpoint of edge"; - cin>>v2; - g->deleteEdge(v1,v2); - break; - - case 4: - if(g==NULL){ - cout<<"Create a new graph first"<>source; - cout<<"BFS Traversal from "< bfs = g->BFS(source); - for(int i=0;i>source; - cout<<"DFS Traversal from "< dfs = g->DFS(source); - for(int i=0;icountComponents()<<" components"<>vertex1; - cout<<"Enter id of second vertex"; - cin>>vertex2; - if(g->isSameComponent(vertex1,vertex2)){ - cout<<"These vertices belong to the same component"< +#include +#include "Graph.h" + +//How to compile code: g++ main.cpp +//How to run code: ./a.out < input1 + +using namespace std; + +int main() +{ + + int choice; + Graph* g=NULL; + +do{ + cout<<"1. Create new graph"<>choice; + cout<<"You entered "<>vcount; + g = new Graph(vcount); + //create graph with zero edges + //vertices are labeled as 0, 1, 2...vcount-1 + //it is a simple undirected unweighted graph + break; + + case 2: + if(g==NULL){ + cout<<"Create a new graph first"<>v1; + cout<<"Enter second endpoint of edge"; + cin>>v2; + g->addEdge(v1,v2); + break; + + case 3: + if(g==NULL){ + cout<<"Create a new graph first"<>v1; + cout<<"Enter second endpoint of edge"; + cin>>v2; + g->deleteEdge(v1,v2); + break; + + case 4: + if(g==NULL){ + cout<<"Create a new graph first"<>source; + cout<<"BFS Traversal from "< bfs = g->BFS(source); + for(int i=0;i>source; + cout<<"DFS Traversal from "< dfs = g->DFS(source); + for(int i=0;icountComponents()<<" components"<>vertex1; + cout<<"Enter id of second vertex"; + cin>>vertex2; + if(g->isSameComponent(vertex1,vertex2)){ + cout<<"These vertices belong to the same component"< - - - - - - - \ No newline at end of file diff --git a/c/.idea/misc.xml b/c/.idea/misc.xml deleted file mode 100644 index 28a804d89..000000000 --- a/c/.idea/misc.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - \ No newline at end of file diff --git a/c/.idea/modules.xml b/c/.idea/modules.xml deleted file mode 100644 index 43b0fb908..000000000 --- a/c/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/c/.idea/vcs.xml b/c/.idea/vcs.xml deleted file mode 100644 index 6c0b86358..000000000 --- a/c/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/c/.idea/workspace.xml b/c/.idea/workspace.xml deleted file mode 100644 index 04b3ca68f..000000000 --- a/c/.idea/workspace.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/c/4.BST/Question_2.cpp b/c/4.BST/Question_2.cpp index 288b022d2..fc3591561 100644 --- a/c/4.BST/Question_2.cpp +++ b/c/4.BST/Question_2.cpp @@ -1,42 +1,42 @@ -#include -#include - -using namespace std; - -/*Tree node definiton*/ -struct TreeNode{ - int data; - TreeNode *left; - TreeNode *right; - TreeNode(int x){ - data=x; - left=right=NULL; - } -}; -int preorder_index=0; -TreeNode* buildTree(vector &preorder,vector &indexOfinorder,int start,int end){ - if(start<=end){ - TreeNode *node = new TreeNode(preorder[preorder_index]); - int inorder_index = /*TODO*/ ; - node->left = /*TODO*/; - node->right = /*TODO*/; - return /*TODO*/; - } - else - return /*TODO*/; -} - -void print_preorder(TreeNode *root){ - /*TODO*/ -} - -void print_inorder(TreeNode *root){ - /*TODO*/ -} - -int main(){ - vector preorder = {7,4,2, 3, 6, 5, 12, 9, 8, 11, 19,15, 20},indexOfinorder={5,2,0,1,4,3,9,7,6,8,11,10,12}; - TreeNode *root = buildTree(preorder,indexOfinorder,0,indexOfinorder.size()-1); - print_preorder(root);cout< +#include + +using namespace std; + +/*Tree node definiton*/ +struct TreeNode{ + int data; + TreeNode *left; + TreeNode *right; + TreeNode(int x){ + data=x; + left=right=NULL; + } +}; +int preorder_index=0; +TreeNode* buildTree(vector &preorder,vector &indexOfinorder,int start,int end){ + if(start<=end){ + TreeNode *node = new TreeNode(preorder[preorder_index]); + int inorder_index = /*TODO*/ ; + node->left = /*TODO*/; + node->right = /*TODO*/; + return /*TODO*/; + } + else + return /*TODO*/; +} + +void print_preorder(TreeNode *root){ + /*TODO*/ +} + +void print_inorder(TreeNode *root){ + /*TODO*/ +} + +int main(){ + vector preorder = {7,4,2, 3, 6, 5, 12, 9, 8, 11, 19,15, 20},indexOfinorder={5,2,0,1,4,3,9,7,6,8,11,10,12}; + TreeNode *root = buildTree(preorder,indexOfinorder,0,indexOfinorder.size()-1); + print_preorder(root);cout< -#include - -// LINKED_QUEUE - -typedef struct node{ - int inf; - struct node *next; -}NODE; - -typedef struct{ - NODE *begin; - NODE *end; - int size; -}DESCRITOR; - -typedef DESCRITOR * LINKED_QUEUE; - -void make_queue(LINKED_QUEUE *q){ - *q = (DESCRITOR * )malloc(sizeof(DESCRITOR)); - if(!(*q)){ - puts("The memory is full\n"); - exit(1); - } - (*q)->begin = (*q)->end = NULL; - (*q)->size = 0; -} - -int isEmpty(LINKED_QUEUE q){ - return (q->begin == NULL); //return (q->size == 0); -} - -int sizeQUEUE (LINKED_QUEUE q){ - return (q->size); -} - -void insert_QUEUE (LINKED_QUEUE q, int info){ - NODE *new_node; - new_node = (NODE *)malloc(sizeof(NODE)); - if(!new_node){ - puts("The memory is full\n"); - exit(2); - } - new_node->inf = info; - new_node->next = NULL; - if(isEmpty(q)) - q->begin = new_node; - else q->end->next = new_node; - q->end = new_node; - q->size++; -} - -int query(LINKED_QUEUE q){ - if(isEmpty(q)){ - puts("QUEUE is Empty!\n"); - exit(3); - }else return q->begin->inf; -} - -void removeQUEUE(LINKED_QUEUE q){ - NODE *aux = q->begin; - - if(isEmpty(q)){ - puts("QUEUE is Empty!\n"); - exit(4); - } - - q->begin = q->begin->next; - if(!(q->begin->next)) - q->end = NULL; - - free(aux); -} - -int main(){} +#include +#include + +// LINKED_QUEUE + +typedef struct node{ + int inf; + struct node *next; +}NODE; + +typedef struct{ + NODE *begin; + NODE *end; + int size; +}DESCRITOR; + +typedef DESCRITOR * LINKED_QUEUE; + +void make_queue(LINKED_QUEUE *q){ + *q = (DESCRITOR * )malloc(sizeof(DESCRITOR)); + if(!(*q)){ + puts("The memory is full\n"); + exit(1); + } + (*q)->begin = (*q)->end = NULL; + (*q)->size = 0; +} + +int isEmpty(LINKED_QUEUE q){ + return (q->begin == NULL); //return (q->size == 0); +} + +int sizeQUEUE (LINKED_QUEUE q){ + return (q->size); +} + +void insert_QUEUE (LINKED_QUEUE q, int info){ + NODE *new_node; + new_node = (NODE *)malloc(sizeof(NODE)); + if(!new_node){ + puts("The memory is full\n"); + exit(2); + } + new_node->inf = info; + new_node->next = NULL; + if(isEmpty(q)) + q->begin = new_node; + else q->end->next = new_node; + q->end = new_node; + q->size++; +} + +int query(LINKED_QUEUE q){ + if(isEmpty(q)){ + puts("QUEUE is Empty!\n"); + exit(3); + }else return q->begin->inf; +} + +void removeQUEUE(LINKED_QUEUE q){ + NODE *aux = q->begin; + + if(isEmpty(q)){ + puts("QUEUE is Empty!\n"); + exit(4); + } + + q->begin = q->begin->next; + if(!(q->begin->next)) + q->end = NULL; + + free(aux); +} + +int main(){} diff --git a/c/STACK.c b/c/STACK.c index 899cb5284..5e7675881 100644 --- a/c/STACK.c +++ b/c/STACK.c @@ -1,46 +1,46 @@ -#include -#include - -// LINKED_STACK - -typedef struct node{ - int info; - struct node *next; -}NODE; - -typedef NODE * LINKED_STACK; - -void create_stack(LINKED_STACK *p){ - *p = NULL; -} - -int isEmpty(LINKED_STACK p){ - return (p == NULL); -} - -void insert(LINKED_STACK *p, int info){ - NODE *new_node; - new_node = (NODE *) malloc (sizeof(NODE)); - if(!new_node){ - puts("Memory FULL\n"); - exit(1); - } - new_node->info = info; - new_node->next = *p; - *p = new_node; -} - -void removeSTACK (LINKED_STACK *p){ - NODE *aux = *p; - - if(isEmpty(*p)){ - puts("Stack is Empty\n"); - exit(2); - } - (*p) = (*p)->next; - free(aux); -} - - - -int main(){} +#include +#include + +// LINKED_STACK + +typedef struct node{ + int info; + struct node *next; +}NODE; + +typedef NODE * LINKED_STACK; + +void create_stack(LINKED_STACK *p){ + *p = NULL; +} + +int isEmpty(LINKED_STACK p){ + return (p == NULL); +} + +void insert(LINKED_STACK *p, int info){ + NODE *new_node; + new_node = (NODE *) malloc (sizeof(NODE)); + if(!new_node){ + puts("Memory FULL\n"); + exit(1); + } + new_node->info = info; + new_node->next = *p; + *p = new_node; +} + +void removeSTACK (LINKED_STACK *p){ + NODE *aux = *p; + + if(isEmpty(*p)){ + puts("Stack is Empty\n"); + exit(2); + } + (*p) = (*p)->next; + free(aux); +} + + + +int main(){} diff --git a/c/algorithm/Binary Search[Recursion].c b/c/algorithm/Binary Search[Recursion].c index 9d9d414ff..f1abf2fd4 100644 --- a/c/algorithm/Binary Search[Recursion].c +++ b/c/algorithm/Binary Search[Recursion].c @@ -1,65 +1,65 @@ -#include - -int BS(int a[], int num, int s, int l) -{ - int mid = (s+l)/2; - while(s <= l) - { - if (a[mid] == num) - { - return mid; - } - else if (a[mid] > num) - { - l = mid-1; - return BS(a, num, s, l); - } - else - { - s = mid+1; - return BS(a, num, s, l); - } - } - return -1; -} - -int main() -{ - int n; - scanf("%d",&n); - int a[n]; - for (int i = 0; i < n; ++i) - { - scanf("%d", &a[i]); - } - for (int i = 1; i < n; ++i) //Insertion Sort - { - int x = a[i]; - int hole = i; - while(hole > 0 && a[hole-1] > x) - { - a[hole] = a[hole-1]; - - hole--; - } - a[hole] = x; - } - for (int i = 0; i < n; ++i) - { - printf("%d ", a[i]); - } - printf("\nWanna Find A Number?: "); - int num, s, mid, l, f; - scanf("%d",&num); - s = 0; - l = n-1; - int x = BS(a, num, s, l); - if (x != -1) - { - printf("\nFound At %d",x); - } - else - printf("\nNot Found"); - - return 0; -} +#include + +int BS(int a[], int num, int s, int l) +{ + int mid = (s+l)/2; + while(s <= l) + { + if (a[mid] == num) + { + return mid; + } + else if (a[mid] > num) + { + l = mid-1; + return BS(a, num, s, l); + } + else + { + s = mid+1; + return BS(a, num, s, l); + } + } + return -1; +} + +int main() +{ + int n; + scanf("%d",&n); + int a[n]; + for (int i = 0; i < n; ++i) + { + scanf("%d", &a[i]); + } + for (int i = 1; i < n; ++i) //Insertion Sort + { + int x = a[i]; + int hole = i; + while(hole > 0 && a[hole-1] > x) + { + a[hole] = a[hole-1]; + + hole--; + } + a[hole] = x; + } + for (int i = 0; i < n; ++i) + { + printf("%d ", a[i]); + } + printf("\nWanna Find A Number?: "); + int num, s, mid, l, f; + scanf("%d",&num); + s = 0; + l = n-1; + int x = BS(a, num, s, l); + if (x != -1) + { + printf("\nFound At %d",x); + } + else + printf("\nNot Found"); + + return 0; +} diff --git a/c/algorithm/BinarySearch.c b/c/algorithm/BinarySearch.c old mode 100755 new mode 100644 diff --git a/c/algorithm/ChineseRem.c b/c/algorithm/ChineseRem.c old mode 100755 new mode 100644 diff --git a/c/algorithm/CoinChange.c b/c/algorithm/CoinChange.c index 5d1e16acd..8ecaa448c 100644 --- a/c/algorithm/CoinChange.c +++ b/c/algorithm/CoinChange.c @@ -1,64 +1,64 @@ -#include -#define c 5 - -int main() -{ - - int coin[c][2]; - int x,i,j,a; - for(i=0;i +#define c 5 + +int main() +{ + + int coin[c][2]; + int x,i,j,a; + for(i=0;i -int main() -{ - int n; - scanf("%d",&n); - int a[n]; - for (int i = 0; i < n; ++i) - { - scanf("%d",&a[i]); - } - int x, f = -1; - scanf("%d",&x); - for (int i = 0; i < n; ++i) - { - if (a[i] == x) - { - f = i; - break; - } - } - if (f != -1) - { - printf("Found At %d\n", f); - } - else - printf("Not Found\n"); - return 0; +#include +int main() +{ + int n; + scanf("%d",&n); + int a[n]; + for (int i = 0; i < n; ++i) + { + scanf("%d",&a[i]); + } + int x, f = -1; + scanf("%d",&x); + for (int i = 0; i < n; ++i) + { + if (a[i] == x) + { + f = i; + break; + } + } + if (f != -1) + { + printf("Found At %d\n", f); + } + else + printf("Not Found\n"); + return 0; } \ No newline at end of file diff --git a/c/algorithm/NQueens/make b/c/algorithm/NQueens/make old mode 100755 new mode 100644 diff --git a/c/algorithm/PrimeSieve.c b/c/algorithm/PrimeSieve.c old mode 100755 new mode 100644 diff --git a/c/algorithm/Producer-Consumer-problem.c b/c/algorithm/Producer-Consumer-problem.c index d56b46de6..1ebc050d3 100644 --- a/c/algorithm/Producer-Consumer-problem.c +++ b/c/algorithm/Producer-Consumer-problem.c @@ -1,63 +1,63 @@ -#include /* Symbolic Constants */ - -#include -#include -#include /* POSIX Threads */ - - -#define BUFFER_SIZE 10 -#define BREAK_CONDITION 20 - -typedef struct -{ -int items; -} item; -item buffer[BUFFER_SIZE]; -int countproduced=0; -int countconsumed=0; -int in = 0; -int out = 0; -item *nextproduced; -item *nextconsumed; -void *Consumer(void *arg) -{ - while (1) - { printf("\nConsumer thread"); - while (in == out) {printf("\n\t Buffer Empty");sleep(1);} - - nextconsumed = &buffer[out]; - printf("\n\tConsumed : %d ",++countconsumed); - out = (out + 1) % BUFFER_SIZE; - if(countconsumed==BREAK_CONDITION)break; - } - return NULL; -} - -void *Producer(void *arg) -{ - while (1) - { - printf("\nProducer thread"); - while (((in + 1) % BUFFER_SIZE) == out) {printf("\n\t Buffer Full");sleep(1);} - - nextproduced=malloc(sizeof(item*)); - nextproduced->items=++countproduced; - printf("\n\tProduced : %d ",countproduced); - buffer[in] = *nextproduced; - in = (in + 1) % BUFFER_SIZE; - if(countproduced==BREAK_CONDITION)break; - - } - return NULL; -} - -int main() -{ - pthread_t producer_thread_id, consumer_thread_id; - - pthread_create(&producer_thread_id, NULL, Producer, NULL); - pthread_create(&consumer_thread_id, NULL, Consumer, NULL); - pthread_join(producer_thread_id, NULL); - pthread_join(consumer_thread_id, NULL); - return 0; +#include /* Symbolic Constants */ + +#include +#include +#include /* POSIX Threads */ + + +#define BUFFER_SIZE 10 +#define BREAK_CONDITION 20 + +typedef struct +{ +int items; +} item; +item buffer[BUFFER_SIZE]; +int countproduced=0; +int countconsumed=0; +int in = 0; +int out = 0; +item *nextproduced; +item *nextconsumed; +void *Consumer(void *arg) +{ + while (1) + { printf("\nConsumer thread"); + while (in == out) {printf("\n\t Buffer Empty");sleep(1);} + + nextconsumed = &buffer[out]; + printf("\n\tConsumed : %d ",++countconsumed); + out = (out + 1) % BUFFER_SIZE; + if(countconsumed==BREAK_CONDITION)break; + } + return NULL; +} + +void *Producer(void *arg) +{ + while (1) + { + printf("\nProducer thread"); + while (((in + 1) % BUFFER_SIZE) == out) {printf("\n\t Buffer Full");sleep(1);} + + nextproduced=malloc(sizeof(item*)); + nextproduced->items=++countproduced; + printf("\n\tProduced : %d ",countproduced); + buffer[in] = *nextproduced; + in = (in + 1) % BUFFER_SIZE; + if(countproduced==BREAK_CONDITION)break; + + } + return NULL; +} + +int main() +{ + pthread_t producer_thread_id, consumer_thread_id; + + pthread_create(&producer_thread_id, NULL, Producer, NULL); + pthread_create(&consumer_thread_id, NULL, Consumer, NULL); + pthread_join(producer_thread_id, NULL); + pthread_join(consumer_thread_id, NULL); + return 0; } \ No newline at end of file diff --git a/c/algorithm/QuickSort.c b/c/algorithm/QuickSort.c deleted file mode 100644 index f4ee9ca2a..000000000 --- a/c/algorithm/QuickSort.c +++ /dev/null @@ -1,46 +0,0 @@ -#include -#include - -void quickSort(int *vetor, int inicio, int fim){ - int i = inicio, f = fim; - int pivot = vetor[(inicio + fim) / 2]; - int aux; - do { - while(vetor[i] < pivot) - i++; - while(vetor[f] > pivot) - f--; - if(i <= f){ - aux = vetor[i]; - vetor[i++] = vetor[f]; - vetor[f--] = aux; - } - } while(i < f); - if(inicio < f) - quickSort(vetor, inicio, f); - if(i < fim) - quickSort(vetor, i, fim); -} - -int main(){ - int i, elementos, pos1, pos2; - int *vetorptr = NULL; - - scanf("%d", &elementos); - if(!(vetorptr = (int *) calloc(elementos, sizeof(int)))){ - printf("Erro de alocassaum\n"); - return 1; - } - - for(i = 0; i < elementos; i++) - scanf("%d", &vetorptr[i]); - scanf("%d %d", &pos1, &pos2); - - quickSort(vetorptr, 0, elementos - 1); - - printf("%d", vetorptr[--pos1] + vetorptr[--pos2]); - - free(vetorptr); - vetorptr = NULL; - return 0; -} diff --git a/c/algorithm/a.out b/c/algorithm/a.out old mode 100755 new mode 100644 diff --git a/c/algorithm/merge sort.c b/c/algorithm/merge sort.c old mode 100755 new mode 100644 diff --git a/c/algorithm/sqrt_newton.c b/c/algorithm/sqrt_newton.c old mode 100755 new mode 100644 diff --git a/c/algorithm/transposeOfMatrix.c b/c/algorithm/transposeOfMatrix.c old mode 100755 new mode 100644 diff --git a/c/ds/CDLL/CDLL.cfp b/c/ds/CDLL/CDLL.cfp index 549408147..6c5e06e0b 100644 --- a/c/ds/CDLL/CDLL.cfp +++ b/c/ds/CDLL/CDLL.cfp @@ -1,319 +1,319 @@ - -CDLL -CUI -CDLL -exe - - CDLL.c - main.c - - - CDLL.h - - - -main.c -mingw2.95 - - CDLL - exe - mingw2.95 - mingw2.95 - - $(CFRoot)\mingw32\Include - $(CFRoot)\mingw32\Include\G++ - - - $(CFRoot)\mingw32\Lib - - - $(CFRoot)\mingw32\Bin - - - - - - - - - - - - - - - - -ggdb - -ggdb - - - - - - - - - - - - - - - - - - - - - - - - - -s - -s - - - - $(CFRoot)\Build.log - lib;a - o;obj - res - - - - gcc.exe - "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) - c - $(PATH)$(NAME).o - o - - Compiling $(FILENAME)...#81001 - - - g++.exe - "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) - cpp;cxx;c++ - $(PATH)$(NAME).o - o - - Compiling $(FILENAME)...#81001 - - - g++.exe - $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -L$(LibPaths) -B$(ExePaths) - o;obj;a;lib;res - $(Target) - cui - - Linking...#81002 - - - g++.exe - $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -mwindows -L$(LibPaths) -B$(ExePaths) - o;obj;a;lib;res - $(Target) - gui - - Linking...#81002 - - - dllwrap.exe - --driver-name "g++" --output-def "$(ShortPath)$(Name).def" --implib "$(ShortPath)$(Name).lib" -L$(LibPaths) $(ProjectFiles) -o "$(ShortTarget)" $(LinkerOptions) -l$(Libs) - o;obj;a;lib;res;def - $(Target) - dll - - Linking...#81002 - - - ar.exe - -r "$(Target)" $(ProjectFiles) - o;obj - $(Target) - lib - - Linking...#81002 - - - windres.exe - -O coff -i "$(ShortFileName)" -o "$(Path)$(Name).res" --include-dir=$(ShortPath) --include-dir=$(IncPaths) - rc - $(PATH)$(NAME).res - res - - Compiling $(FILENAME)...#81001 - - - gdb.exe - gdebug.dll - exe;dll - - - - #81003 - - - $(Target) - $(Parameters) - exe - - - - #81004 - - - $(HostApp) - $(Parameters) - dll - - - - #81004 - - - fdel.exe - "$(Path)$(Name).o" $(FileName) - c;cpp;cxx;c++ - $(Target) - - - - - - fdel.exe - "$(Path)$(Name).res" $(FileName) - rc - $(Target) - - - - - - fdel.exe - "$(Path)$(Name).o" -silent - *.* - $(Target) - - - - - - fdel.exe - "$(Target)" - *.* - - - - - - - - - - "C Compiler""C++ Compiler""Resource Compiler" - - - - Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81005 - Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)#81006 - - - - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81007 - Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)#81008 - \r\n\r\n\r\n - - - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81009 - Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)#81010 - - - - - - "Make" - "Run""Run DLL" - - - "Make" - "Run""Run DLL" - - #81011 - #81012 - - - - - - "Make" - "Debugger" - - - "Make" - "Debugger" - - #81013 - #81014 - - - - - - "Clean Objects""Clean Resource" - "Clean Io" - "Clean Target" - - - "Clean Objects""Clean Resource""Clean Io" - "Clean Io" - "Clean Target" - - Complete Clean $(TargetName)#81015 - Clean $(TargetName) error#81016 - - - - - - + +CDLL +CUI +CDLL +exe + + CDLL.c + main.c + + + CDLL.h + + + +main.c +mingw2.95 + + CDLL + exe + mingw2.95 + mingw2.95 + + $(CFRoot)\mingw32\Include + $(CFRoot)\mingw32\Include\G++ + + + $(CFRoot)\mingw32\Lib + + + $(CFRoot)\mingw32\Bin + + + + + + + + + + + + + + + + -ggdb + -ggdb + + + + + + + + + + + + + + + + + + + + + + + + + -s + -s + + + + $(CFRoot)\Build.log + lib;a + o;obj + res + + + + gcc.exe + "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) + c + $(PATH)$(NAME).o + o + + Compiling $(FILENAME)...#81001 + + + g++.exe + "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) + cpp;cxx;c++ + $(PATH)$(NAME).o + o + + Compiling $(FILENAME)...#81001 + + + g++.exe + $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -L$(LibPaths) -B$(ExePaths) + o;obj;a;lib;res + $(Target) + cui + + Linking...#81002 + + + g++.exe + $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -mwindows -L$(LibPaths) -B$(ExePaths) + o;obj;a;lib;res + $(Target) + gui + + Linking...#81002 + + + dllwrap.exe + --driver-name "g++" --output-def "$(ShortPath)$(Name).def" --implib "$(ShortPath)$(Name).lib" -L$(LibPaths) $(ProjectFiles) -o "$(ShortTarget)" $(LinkerOptions) -l$(Libs) + o;obj;a;lib;res;def + $(Target) + dll + + Linking...#81002 + + + ar.exe + -r "$(Target)" $(ProjectFiles) + o;obj + $(Target) + lib + + Linking...#81002 + + + windres.exe + -O coff -i "$(ShortFileName)" -o "$(Path)$(Name).res" --include-dir=$(ShortPath) --include-dir=$(IncPaths) + rc + $(PATH)$(NAME).res + res + + Compiling $(FILENAME)...#81001 + + + gdb.exe + gdebug.dll + exe;dll + + + + #81003 + + + $(Target) + $(Parameters) + exe + + + + #81004 + + + $(HostApp) + $(Parameters) + dll + + + + #81004 + + + fdel.exe + "$(Path)$(Name).o" $(FileName) + c;cpp;cxx;c++ + $(Target) + + + + + + fdel.exe + "$(Path)$(Name).res" $(FileName) + rc + $(Target) + + + + + + fdel.exe + "$(Path)$(Name).o" -silent + *.* + $(Target) + + + + + + fdel.exe + "$(Target)" + *.* + + + + + + + + + + "C Compiler""C++ Compiler""Resource Compiler" + + + + Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81005 + Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)#81006 + + + + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81007 + Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)#81008 + \r\n\r\n\r\n + + + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81009 + Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)#81010 + + + + + + "Make" + "Run""Run DLL" + + + "Make" + "Run""Run DLL" + + #81011 + #81012 + + + + + + "Make" + "Debugger" + + + "Make" + "Debugger" + + #81013 + #81014 + + + + + + "Clean Objects""Clean Resource" + "Clean Io" + "Clean Target" + + + "Clean Objects""Clean Resource""Clean Io" + "Clean Io" + "Clean Target" + + Complete Clean $(TargetName)#81015 + Clean $(TargetName) error#81016 + + + + + + diff --git a/c/ds/CSLL/CSLL.cfp b/c/ds/CSLL/CSLL.cfp index fdd705b28..c69cfd90a 100644 --- a/c/ds/CSLL/CSLL.cfp +++ b/c/ds/CSLL/CSLL.cfp @@ -1,319 +1,319 @@ - -CSLL -CUI -CSLL -exe - - main.c - CSLL.c - - - CSLL.h - - - -main.c -mingw2.95 - - CSLL - exe - mingw2.95 - mingw2.95 - - $(CFRoot)\mingw32\Include - $(CFRoot)\mingw32\Include\G++ - - - $(CFRoot)\mingw32\Lib - - - $(CFRoot)\mingw32\Bin - - - - - - - - - - - - - - - - -ggdb - -ggdb - - - - - - - - - - - - - - - - - - - - - - - - - -s - -s - - - - $(CFRoot)\Build.log - lib;a - o;obj - res - - - - gcc.exe - "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) - c - $(PATH)$(NAME).o - o - - Compiling $(FILENAME)...#81001 - - - g++.exe - "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) - cpp;cxx;c++ - $(PATH)$(NAME).o - o - - Compiling $(FILENAME)...#81001 - - - g++.exe - $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -L$(LibPaths) -B$(ExePaths) - o;obj;a;lib;res - $(Target) - cui - - Linking...#81002 - - - g++.exe - $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -mwindows -L$(LibPaths) -B$(ExePaths) - o;obj;a;lib;res - $(Target) - gui - - Linking...#81002 - - - dllwrap.exe - --driver-name "g++" --output-def "$(ShortPath)$(Name).def" --implib "$(ShortPath)$(Name).lib" -L$(LibPaths) $(ProjectFiles) -o "$(ShortTarget)" $(LinkerOptions) -l$(Libs) - o;obj;a;lib;res;def - $(Target) - dll - - Linking...#81002 - - - ar.exe - -r "$(Target)" $(ProjectFiles) - o;obj - $(Target) - lib - - Linking...#81002 - - - windres.exe - -O coff -i "$(ShortFileName)" -o "$(Path)$(Name).res" --include-dir=$(ShortPath) --include-dir=$(IncPaths) - rc - $(PATH)$(NAME).res - res - - Compiling $(FILENAME)...#81001 - - - gdb.exe - gdebug.dll - exe;dll - - - - #81003 - - - $(Target) - $(Parameters) - exe - - - - #81004 - - - $(HostApp) - $(Parameters) - dll - - - - #81004 - - - fdel.exe - "$(Path)$(Name).o" $(FileName) - c;cpp;cxx;c++ - $(Target) - - - - - - fdel.exe - "$(Path)$(Name).res" $(FileName) - rc - $(Target) - - - - - - fdel.exe - "$(Path)$(Name).o" -silent - *.* - $(Target) - - - - - - fdel.exe - "$(Target)" - *.* - - - - - - - - - - "C Compiler""C++ Compiler""Resource Compiler" - - - - Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81005 - Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)#81006 - - - - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81007 - Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)#81008 - \r\n\r\n\r\n - - - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81009 - Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)#81010 - - - - - - "Make" - "Run""Run DLL" - - - "Make" - "Run""Run DLL" - - #81011 - #81012 - - - - - - "Make" - "Debugger" - - - "Make" - "Debugger" - - #81013 - #81014 - - - - - - "Clean Objects""Clean Resource" - "Clean Io" - "Clean Target" - - - "Clean Objects""Clean Resource""Clean Io" - "Clean Io" - "Clean Target" - - Complete Clean $(TargetName)#81015 - Clean $(TargetName) error#81016 - - - - - - + +CSLL +CUI +CSLL +exe + + main.c + CSLL.c + + + CSLL.h + + + +main.c +mingw2.95 + + CSLL + exe + mingw2.95 + mingw2.95 + + $(CFRoot)\mingw32\Include + $(CFRoot)\mingw32\Include\G++ + + + $(CFRoot)\mingw32\Lib + + + $(CFRoot)\mingw32\Bin + + + + + + + + + + + + + + + + -ggdb + -ggdb + + + + + + + + + + + + + + + + + + + + + + + + + -s + -s + + + + $(CFRoot)\Build.log + lib;a + o;obj + res + + + + gcc.exe + "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) + c + $(PATH)$(NAME).o + o + + Compiling $(FILENAME)...#81001 + + + g++.exe + "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) + cpp;cxx;c++ + $(PATH)$(NAME).o + o + + Compiling $(FILENAME)...#81001 + + + g++.exe + $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -L$(LibPaths) -B$(ExePaths) + o;obj;a;lib;res + $(Target) + cui + + Linking...#81002 + + + g++.exe + $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -mwindows -L$(LibPaths) -B$(ExePaths) + o;obj;a;lib;res + $(Target) + gui + + Linking...#81002 + + + dllwrap.exe + --driver-name "g++" --output-def "$(ShortPath)$(Name).def" --implib "$(ShortPath)$(Name).lib" -L$(LibPaths) $(ProjectFiles) -o "$(ShortTarget)" $(LinkerOptions) -l$(Libs) + o;obj;a;lib;res;def + $(Target) + dll + + Linking...#81002 + + + ar.exe + -r "$(Target)" $(ProjectFiles) + o;obj + $(Target) + lib + + Linking...#81002 + + + windres.exe + -O coff -i "$(ShortFileName)" -o "$(Path)$(Name).res" --include-dir=$(ShortPath) --include-dir=$(IncPaths) + rc + $(PATH)$(NAME).res + res + + Compiling $(FILENAME)...#81001 + + + gdb.exe + gdebug.dll + exe;dll + + + + #81003 + + + $(Target) + $(Parameters) + exe + + + + #81004 + + + $(HostApp) + $(Parameters) + dll + + + + #81004 + + + fdel.exe + "$(Path)$(Name).o" $(FileName) + c;cpp;cxx;c++ + $(Target) + + + + + + fdel.exe + "$(Path)$(Name).res" $(FileName) + rc + $(Target) + + + + + + fdel.exe + "$(Path)$(Name).o" -silent + *.* + $(Target) + + + + + + fdel.exe + "$(Target)" + *.* + + + + + + + + + + "C Compiler""C++ Compiler""Resource Compiler" + + + + Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81005 + Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)#81006 + + + + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81007 + Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)#81008 + \r\n\r\n\r\n + + + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81009 + Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)#81010 + + + + + + "Make" + "Run""Run DLL" + + + "Make" + "Run""Run DLL" + + #81011 + #81012 + + + + + + "Make" + "Debugger" + + + "Make" + "Debugger" + + #81013 + #81014 + + + + + + "Clean Objects""Clean Resource" + "Clean Io" + "Clean Target" + + + "Clean Objects""Clean Resource""Clean Io" + "Clean Io" + "Clean Target" + + Complete Clean $(TargetName)#81015 + Clean $(TargetName) error#81016 + + + + + + diff --git a/c/ds/DLL/DLL.cfp b/c/ds/DLL/DLL.cfp index 1f56475ae..535fb05b3 100644 --- a/c/ds/DLL/DLL.cfp +++ b/c/ds/DLL/DLL.cfp @@ -1,318 +1,318 @@ - -DLL -CUI -DLL -exe - - ..\main.c - ..\DLL.c - - - ..\DLL.h - - - -mingw2.95 - - DLL - exe - mingw2.95 - mingw2.95 - - $(CFRoot)\mingw32\Include - $(CFRoot)\mingw32\Include\G++ - - - $(CFRoot)\mingw32\Lib - - - $(CFRoot)\mingw32\Bin - - - - - - - - - - - - - - - - -ggdb - -ggdb - - - - - - - - - - - - - - - - - - - - - - - - - -s - -s - - - - $(CFRoot)\Build.log - lib;a - o;obj - res - - - - gcc.exe - "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) - c - $(PATH)$(NAME).o - o - - Compiling $(FILENAME)...#81001 - - - g++.exe - "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) - cpp;cxx;c++ - $(PATH)$(NAME).o - o - - Compiling $(FILENAME)...#81001 - - - g++.exe - $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -L$(LibPaths) -B$(ExePaths) - o;obj;a;lib;res - $(Target) - cui - - Linking...#81002 - - - g++.exe - $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -mwindows -L$(LibPaths) -B$(ExePaths) - o;obj;a;lib;res - $(Target) - gui - - Linking...#81002 - - - dllwrap.exe - --driver-name "g++" --output-def "$(ShortPath)$(Name).def" --implib "$(ShortPath)$(Name).lib" -L$(LibPaths) $(ProjectFiles) -o "$(ShortTarget)" $(LinkerOptions) -l$(Libs) - o;obj;a;lib;res;def - $(Target) - dll - - Linking...#81002 - - - ar.exe - -r "$(Target)" $(ProjectFiles) - o;obj - $(Target) - lib - - Linking...#81002 - - - windres.exe - -O coff -i "$(ShortFileName)" -o "$(Path)$(Name).res" --include-dir=$(ShortPath) --include-dir=$(IncPaths) - rc - $(PATH)$(NAME).res - res - - Compiling $(FILENAME)...#81001 - - - gdb.exe - gdebug.dll - exe;dll - - - - #81003 - - - $(Target) - $(Parameters) - exe - - - - #81004 - - - $(HostApp) - $(Parameters) - dll - - - - #81004 - - - fdel.exe - "$(Path)$(Name).o" $(FileName) - c;cpp;cxx;c++ - $(Target) - - - - - - fdel.exe - "$(Path)$(Name).res" $(FileName) - rc - $(Target) - - - - - - fdel.exe - "$(Path)$(Name).o" -silent - *.* - $(Target) - - - - - - fdel.exe - "$(Target)" - *.* - - - - - - - - - - "C Compiler""C++ Compiler""Resource Compiler" - - - - Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81005 - Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)#81006 - - - - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81007 - Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)#81008 - \r\n\r\n\r\n - - - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81009 - Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)#81010 - - - - - - "Make" - "Run""Run DLL" - - - "Make" - "Run""Run DLL" - - #81011 - #81012 - - - - - - "Make" - "Debugger" - - - "Make" - "Debugger" - - #81013 - #81014 - - - - - - "Clean Objects""Clean Resource" - "Clean Io" - "Clean Target" - - - "Clean Objects""Clean Resource""Clean Io" - "Clean Io" - "Clean Target" - - Complete Clean $(TargetName)#81015 - Clean $(TargetName) error#81016 - - - - - - + +DLL +CUI +DLL +exe + + ..\main.c + ..\DLL.c + + + ..\DLL.h + + + +mingw2.95 + + DLL + exe + mingw2.95 + mingw2.95 + + $(CFRoot)\mingw32\Include + $(CFRoot)\mingw32\Include\G++ + + + $(CFRoot)\mingw32\Lib + + + $(CFRoot)\mingw32\Bin + + + + + + + + + + + + + + + + -ggdb + -ggdb + + + + + + + + + + + + + + + + + + + + + + + + + -s + -s + + + + $(CFRoot)\Build.log + lib;a + o;obj + res + + + + gcc.exe + "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) + c + $(PATH)$(NAME).o + o + + Compiling $(FILENAME)...#81001 + + + g++.exe + "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) + cpp;cxx;c++ + $(PATH)$(NAME).o + o + + Compiling $(FILENAME)...#81001 + + + g++.exe + $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -L$(LibPaths) -B$(ExePaths) + o;obj;a;lib;res + $(Target) + cui + + Linking...#81002 + + + g++.exe + $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -mwindows -L$(LibPaths) -B$(ExePaths) + o;obj;a;lib;res + $(Target) + gui + + Linking...#81002 + + + dllwrap.exe + --driver-name "g++" --output-def "$(ShortPath)$(Name).def" --implib "$(ShortPath)$(Name).lib" -L$(LibPaths) $(ProjectFiles) -o "$(ShortTarget)" $(LinkerOptions) -l$(Libs) + o;obj;a;lib;res;def + $(Target) + dll + + Linking...#81002 + + + ar.exe + -r "$(Target)" $(ProjectFiles) + o;obj + $(Target) + lib + + Linking...#81002 + + + windres.exe + -O coff -i "$(ShortFileName)" -o "$(Path)$(Name).res" --include-dir=$(ShortPath) --include-dir=$(IncPaths) + rc + $(PATH)$(NAME).res + res + + Compiling $(FILENAME)...#81001 + + + gdb.exe + gdebug.dll + exe;dll + + + + #81003 + + + $(Target) + $(Parameters) + exe + + + + #81004 + + + $(HostApp) + $(Parameters) + dll + + + + #81004 + + + fdel.exe + "$(Path)$(Name).o" $(FileName) + c;cpp;cxx;c++ + $(Target) + + + + + + fdel.exe + "$(Path)$(Name).res" $(FileName) + rc + $(Target) + + + + + + fdel.exe + "$(Path)$(Name).o" -silent + *.* + $(Target) + + + + + + fdel.exe + "$(Target)" + *.* + + + + + + + + + + "C Compiler""C++ Compiler""Resource Compiler" + + + + Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81005 + Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)#81006 + + + + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81007 + Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)#81008 + \r\n\r\n\r\n + + + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81009 + Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)#81010 + + + + + + "Make" + "Run""Run DLL" + + + "Make" + "Run""Run DLL" + + #81011 + #81012 + + + + + + "Make" + "Debugger" + + + "Make" + "Debugger" + + #81013 + #81014 + + + + + + "Clean Objects""Clean Resource" + "Clean Io" + "Clean Target" + + + "Clean Objects""Clean Resource""Clean Io" + "Clean Io" + "Clean Target" + + Complete Clean $(TargetName)#81015 + Clean $(TargetName) error#81016 + + + + + + diff --git a/c/ds/Priority Queue/5.Heap-PriorityQ/TestCases_Que1.txt b/c/ds/Priority Queue/5.Heap-PriorityQ/TestCases_Que1.txt index e0f2f9109..0a608e782 100644 --- a/c/ds/Priority Queue/5.Heap-PriorityQ/TestCases_Que1.txt +++ b/c/ds/Priority Queue/5.Heap-PriorityQ/TestCases_Que1.txt @@ -1,24 +1,24 @@ -Input 1: -iitguwahati - -Output 1: -itiaitaguwh (this is one possible output, if you print any other which follows Bob's rearrangement, then it is acceptable) - -Input 2: -aaaaabbbbbccccc - -Ouput 2: -abcabcabcabcabc (this is one possible output, if you print any other which follows Bob's rearrangement, then it is acceptable) - -Input 3: -geeksforgeeks - -Output 3: -egekesegksfor (this is one possible output, if you print any other which follows Bob's rearrangement, then it is acceptable) - -Input 4: -aaaaaabbbbbbbb - -Ouput 4: -Not Possible - +Input 1: +iitguwahati + +Output 1: +itiaitaguwh (this is one possible output, if you print any other which follows Bob's rearrangement, then it is acceptable) + +Input 2: +aaaaabbbbbccccc + +Ouput 2: +abcabcabcabcabc (this is one possible output, if you print any other which follows Bob's rearrangement, then it is acceptable) + +Input 3: +geeksforgeeks + +Output 3: +egekesegksfor (this is one possible output, if you print any other which follows Bob's rearrangement, then it is acceptable) + +Input 4: +aaaaaabbbbbbbb + +Ouput 4: +Not Possible + diff --git a/c/ds/Priority Queue/5.Heap-PriorityQ/TestCases_Que2.txt b/c/ds/Priority Queue/5.Heap-PriorityQ/TestCases_Que2.txt index 5cd538b31..efc14956a 100644 --- a/c/ds/Priority Queue/5.Heap-PriorityQ/TestCases_Que2.txt +++ b/c/ds/Priority Queue/5.Heap-PriorityQ/TestCases_Que2.txt @@ -1,133 +1,133 @@ -Input 1: -5 -283280121 782916802 -317664929 898415172 -951133776 376367013 -961148050 385599125 -980913391 847912645 - -Output 1: -1418670047 - -Input 2: -50 -36616963 35887002 -38070714 495529501 -79292652 229453232 -88242680 700680580 -137857688 413115088 -179882058 480538711 -196842555 623621497 -201411561 930064341 -235492265 264125858 -238176883 201620672 -238387441 531682046 -254029772 950305054 -291672611 722032663 -340789259 890185621 -356294983 203393748 -367753702 242882326 -375621149 336628938 -388266395 252551113 -418416931 270027322 -441381803 788912528 -506995906 872449795 -522278872 914689320 -538015463 457419763 -538832788 47584891 -540671906 215602397 -560013448 126478507 -593760457 2628387 -610348800 235616181 -668066226 170226832 -679783990 171274023 -683427743 559301752 -700528228 610051112 -727328509 867529847 -737812220 884493567 -747688776 107231383 -771854880 916901718 -772894889 944088968 -783725811 742261681 -823860276 896193555 -843391076 398722857 -866638949 551120745 -891134170 633761602 -923620442 986091986 -926070958 326905396 -929678215 321924654 -930211560 461283594 -950540066 820099707 -955372388 594944846 -975099001 434725536 -976015955 978145894 - -Output 2: -8485548331 - -Input 3: -5 -0 9 -10 4 -15 7 -30 10 -30 9 - -Output 3: -9 - -Input 4: -50 -487706 119659344 -4080371 967838129 -7863143 797762645 -9361848 539221796 -22888493 142102482 -27592708 611298565 -29130952 854671993 -65595465 104576384 -66288118 194879400 -68765513 26367219 -70498307 874368266 -174260196 913929115 -175679615 308585876 -180047190 52602162 -194435589 429754201 -201384166 114673012 -222634400 208442731 -239697689 835175471 -254065061 694451805 -271062208 578646122 -333961924 324019889 -336906181 900464030 -409617807 615448498 -431098638 148834388 -516631496 436533893 -543771279 29132945 -585445692 593951356 -603236774 713893904 -628896716 302869266 -676537797 206323720 -678995092 976381723 -682111322 496887795 -692134770 533881497 -701794212 68187682 -704380635 733794326 -753067776 450723670 -757782965 264845318 -762108851 407784436 -773379847 193003008 -775661614 254369620 -786166049 329338105 -793446473 9878839 -858636239 742132465 -871832073 264986656 -891653076 49240670 -923314579 687524372 -934504950 861289137 -946885385 254902618 -948249666 853779203 -986021138 205616567 - -Output 4: -6667863382 +Input 1: +5 +283280121 782916802 +317664929 898415172 +951133776 376367013 +961148050 385599125 +980913391 847912645 + +Output 1: +1418670047 + +Input 2: +50 +36616963 35887002 +38070714 495529501 +79292652 229453232 +88242680 700680580 +137857688 413115088 +179882058 480538711 +196842555 623621497 +201411561 930064341 +235492265 264125858 +238176883 201620672 +238387441 531682046 +254029772 950305054 +291672611 722032663 +340789259 890185621 +356294983 203393748 +367753702 242882326 +375621149 336628938 +388266395 252551113 +418416931 270027322 +441381803 788912528 +506995906 872449795 +522278872 914689320 +538015463 457419763 +538832788 47584891 +540671906 215602397 +560013448 126478507 +593760457 2628387 +610348800 235616181 +668066226 170226832 +679783990 171274023 +683427743 559301752 +700528228 610051112 +727328509 867529847 +737812220 884493567 +747688776 107231383 +771854880 916901718 +772894889 944088968 +783725811 742261681 +823860276 896193555 +843391076 398722857 +866638949 551120745 +891134170 633761602 +923620442 986091986 +926070958 326905396 +929678215 321924654 +930211560 461283594 +950540066 820099707 +955372388 594944846 +975099001 434725536 +976015955 978145894 + +Output 2: +8485548331 + +Input 3: +5 +0 9 +10 4 +15 7 +30 10 +30 9 + +Output 3: +9 + +Input 4: +50 +487706 119659344 +4080371 967838129 +7863143 797762645 +9361848 539221796 +22888493 142102482 +27592708 611298565 +29130952 854671993 +65595465 104576384 +66288118 194879400 +68765513 26367219 +70498307 874368266 +174260196 913929115 +175679615 308585876 +180047190 52602162 +194435589 429754201 +201384166 114673012 +222634400 208442731 +239697689 835175471 +254065061 694451805 +271062208 578646122 +333961924 324019889 +336906181 900464030 +409617807 615448498 +431098638 148834388 +516631496 436533893 +543771279 29132945 +585445692 593951356 +603236774 713893904 +628896716 302869266 +676537797 206323720 +678995092 976381723 +682111322 496887795 +692134770 533881497 +701794212 68187682 +704380635 733794326 +753067776 450723670 +757782965 264845318 +762108851 407784436 +773379847 193003008 +775661614 254369620 +786166049 329338105 +793446473 9878839 +858636239 742132465 +871832073 264986656 +891653076 49240670 +923314579 687524372 +934504950 861289137 +946885385 254902618 +948249666 853779203 +986021138 205616567 + +Output 4: +6667863382 diff --git a/c/ds/SLL/SLL.cfp b/c/ds/SLL/SLL.cfp index 65a2be19c..f53108598 100644 --- a/c/ds/SLL/SLL.cfp +++ b/c/ds/SLL/SLL.cfp @@ -1,318 +1,318 @@ - -SLL -CUI -SLL -exe - - SLL.c - main.c - - - SLL.h - - - -mingw2.95 - - SLL - exe - mingw2.95 - mingw2.95 - - $(CFRoot)\mingw32\Include - $(CFRoot)\mingw32\Include\G++ - - - $(CFRoot)\mingw32\Lib - - - $(CFRoot)\mingw32\Bin - - - - - - - - - - - - - - - - -ggdb - -ggdb - - - - - - - - - - - - - - - - - - - - - - - - - -s - -s - - - - $(CFRoot)\Build.log - lib;a - o;obj - res - - - - gcc.exe - "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) - c - $(PATH)$(NAME).o - o - - Compiling $(FILENAME)...#81001 - - - g++.exe - "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) - cpp;cxx;c++ - $(PATH)$(NAME).o - o - - Compiling $(FILENAME)...#81001 - - - g++.exe - $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -L$(LibPaths) -B$(ExePaths) - o;obj;a;lib;res - $(Target) - cui - - Linking...#81002 - - - g++.exe - $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -mwindows -L$(LibPaths) -B$(ExePaths) - o;obj;a;lib;res - $(Target) - gui - - Linking...#81002 - - - dllwrap.exe - --driver-name "g++" --output-def "$(ShortPath)$(Name).def" --implib "$(ShortPath)$(Name).lib" -L$(LibPaths) $(ProjectFiles) -o "$(ShortTarget)" $(LinkerOptions) -l$(Libs) - o;obj;a;lib;res;def - $(Target) - dll - - Linking...#81002 - - - ar.exe - -r "$(Target)" $(ProjectFiles) - o;obj - $(Target) - lib - - Linking...#81002 - - - windres.exe - -O coff -i "$(ShortFileName)" -o "$(Path)$(Name).res" --include-dir=$(ShortPath) --include-dir=$(IncPaths) - rc - $(PATH)$(NAME).res - res - - Compiling $(FILENAME)...#81001 - - - gdb.exe - gdebug.dll - exe;dll - - - - #81003 - - - $(Target) - $(Parameters) - exe - - - - #81004 - - - $(HostApp) - $(Parameters) - dll - - - - #81004 - - - fdel.exe - "$(Path)$(Name).o" $(FileName) - c;cpp;cxx;c++ - $(Target) - - - - - - fdel.exe - "$(Path)$(Name).res" $(FileName) - rc - $(Target) - - - - - - fdel.exe - "$(Path)$(Name).o" -silent - *.* - $(Target) - - - - - - fdel.exe - "$(Target)" - *.* - - - - - - - - - - "C Compiler""C++ Compiler""Resource Compiler" - - - - Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81005 - Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)#81006 - - - - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81007 - Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)#81008 - \r\n\r\n\r\n - - - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - - "C Compiler""C++ Compiler""Resource Compiler" - "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" - - Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81009 - Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)#81010 - - - - - - "Make" - "Run""Run DLL" - - - "Make" - "Run""Run DLL" - - #81011 - #81012 - - - - - - "Make" - "Debugger" - - - "Make" - "Debugger" - - #81013 - #81014 - - - - - - "Clean Objects""Clean Resource" - "Clean Io" - "Clean Target" - - - "Clean Objects""Clean Resource""Clean Io" - "Clean Io" - "Clean Target" - - Complete Clean $(TargetName)#81015 - Clean $(TargetName) error#81016 - - - - - - + +SLL +CUI +SLL +exe + + SLL.c + main.c + + + SLL.h + + + +mingw2.95 + + SLL + exe + mingw2.95 + mingw2.95 + + $(CFRoot)\mingw32\Include + $(CFRoot)\mingw32\Include\G++ + + + $(CFRoot)\mingw32\Lib + + + $(CFRoot)\mingw32\Bin + + + + + + + + + + + + + + + + -ggdb + -ggdb + + + + + + + + + + + + + + + + + + + + + + + + + -s + -s + + + + $(CFRoot)\Build.log + lib;a + o;obj + res + + + + gcc.exe + "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) + c + $(PATH)$(NAME).o + o + + Compiling $(FILENAME)...#81001 + + + g++.exe + "$(FileName)" -c -o "$(Path)$(Name).o" $(CompilerOptions) -I$(IncPaths) -B$(ExePaths) + cpp;cxx;c++ + $(PATH)$(NAME).o + o + + Compiling $(FILENAME)...#81001 + + + g++.exe + $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -L$(LibPaths) -B$(ExePaths) + o;obj;a;lib;res + $(Target) + cui + + Linking...#81002 + + + g++.exe + $(ProjectFiles) -l$(Libs) -o "$(Target)" $(LinkerOptions) -mwindows -L$(LibPaths) -B$(ExePaths) + o;obj;a;lib;res + $(Target) + gui + + Linking...#81002 + + + dllwrap.exe + --driver-name "g++" --output-def "$(ShortPath)$(Name).def" --implib "$(ShortPath)$(Name).lib" -L$(LibPaths) $(ProjectFiles) -o "$(ShortTarget)" $(LinkerOptions) -l$(Libs) + o;obj;a;lib;res;def + $(Target) + dll + + Linking...#81002 + + + ar.exe + -r "$(Target)" $(ProjectFiles) + o;obj + $(Target) + lib + + Linking...#81002 + + + windres.exe + -O coff -i "$(ShortFileName)" -o "$(Path)$(Name).res" --include-dir=$(ShortPath) --include-dir=$(IncPaths) + rc + $(PATH)$(NAME).res + res + + Compiling $(FILENAME)...#81001 + + + gdb.exe + gdebug.dll + exe;dll + + + + #81003 + + + $(Target) + $(Parameters) + exe + + + + #81004 + + + $(HostApp) + $(Parameters) + dll + + + + #81004 + + + fdel.exe + "$(Path)$(Name).o" $(FileName) + c;cpp;cxx;c++ + $(Target) + + + + + + fdel.exe + "$(Path)$(Name).res" $(FileName) + rc + $(Target) + + + + + + fdel.exe + "$(Path)$(Name).o" -silent + *.* + $(Target) + + + + + + fdel.exe + "$(Target)" + *.* + + + + + + + + + + "C Compiler""C++ Compiler""Resource Compiler" + + + + Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81005 + Complete Compile $(FileName): $(Error) error(s), $(Warning) warning(s)#81006 + + + + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81007 + Complete Build $(TargetName): $(Error) error(s), $(Warning) warning(s)#81008 + \r\n\r\n\r\n + + + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + + "C Compiler""C++ Compiler""Resource Compiler" + "Linker(CUI)""Linker(GUI)""Linker for DLL""Linker for Lib" + + Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)\nGenerated $(Target)#81009 + Complete Make $(TargetName): $(Error) error(s), $(Warning) warning(s)#81010 + + + + + + "Make" + "Run""Run DLL" + + + "Make" + "Run""Run DLL" + + #81011 + #81012 + + + + + + "Make" + "Debugger" + + + "Make" + "Debugger" + + #81013 + #81014 + + + + + + "Clean Objects""Clean Resource" + "Clean Io" + "Clean Target" + + + "Clean Objects""Clean Resource""Clean Io" + "Clean Io" + "Clean Target" + + Complete Clean $(TargetName)#81015 + Clean $(TargetName) error#81016 + + + + + + diff --git a/c/ds/Tree/preOrder_binary_tree.c b/c/ds/Tree/preOrder_binary_tree.c old mode 100755 new mode 100644 diff --git a/cpp/0-1knapsack.cpp b/cpp/0-1knapsack.cpp index 45713ec1e..712facf31 100644 --- a/cpp/0-1knapsack.cpp +++ b/cpp/0-1knapsack.cpp @@ -1,108 +1,108 @@ -#include -using namespace std; - -struct item -{ - int w; - int price; -}; -int unbounded_knapsack(int n,int w,item a[]) -{ - int profit1,profit2; - profit1=profit2=0; - if(n==0||w==0) - { - return 0; - } - if(w-a[n-1].w>=0) - { - profit1=a[n-1].price+unbounded_knapsack(n,w-a[n-1].w,a); - } - profit2=unbounded_knapsack(n-1,w,a); - return max(profit1,profit2); -} - -//top down DP hw - - -//bottom UP DP -int bounded_knapsackBottomUpDP(int n,int w,item a[]) -{ - int dp[100][100]; - for(int i=0;i<=n;i++)//i here denotes the item i==0 means 0 items - { - for(int j=0;j<=w;j++)//j here denotes the current capacity of the bag - { - if(i==0||j==0) - { - dp[i][j]=0; - } - else - { - int inc=0,exc=0; - if(a[i-1].w<=j) - { - inc=a[i-1].price+dp[i-1][j-a[i-1].w]; - } - exc=dp[i-1][j]; - dp[i][j]=max(inc,exc); - } - } - } - for(int i=0;i<=n;i++) - { - for(int j=0;j<=w;j++) - { - cout< +using namespace std; + +struct item +{ + int w; + int price; +}; +int unbounded_knapsack(int n,int w,item a[]) +{ + int profit1,profit2; + profit1=profit2=0; + if(n==0||w==0) + { + return 0; + } + if(w-a[n-1].w>=0) + { + profit1=a[n-1].price+unbounded_knapsack(n,w-a[n-1].w,a); + } + profit2=unbounded_knapsack(n-1,w,a); + return max(profit1,profit2); +} + +//top down DP hw + + +//bottom UP DP +int bounded_knapsackBottomUpDP(int n,int w,item a[]) +{ + int dp[100][100]; + for(int i=0;i<=n;i++)//i here denotes the item i==0 means 0 items + { + for(int j=0;j<=w;j++)//j here denotes the current capacity of the bag + { + if(i==0||j==0) + { + dp[i][j]=0; + } + else + { + int inc=0,exc=0; + if(a[i-1].w<=j) + { + inc=a[i-1].price+dp[i-1][j-a[i-1].w]; + } + exc=dp[i-1][j]; + dp[i][j]=max(inc,exc); + } + } + } + for(int i=0;i<=n;i++) + { + for(int j=0;j<=w;j++) + { + cout< - -// Number of vertices in the graph -#define V 5 - -void printSolution(int path[]); - -bool isSafe(int v, bool graph[V][V], int path[], int pos) -{ - if (graph [ path[pos-1] ][ v ] == 0) - return false; - - for (int i = 0; i < pos; i++) - if (path[i] == v) - return false; - - return true; -} - -bool hamCycleUtil(bool graph[V][V], int path[], int pos) -{ - if (pos == V) - { - if ( graph[ path[pos-1] ][ path[0] ] == 1 ) - return true; - else - return false; - } - - for (int v = 1; v < V; v++) - { - if (isSafe(v, graph, path, pos)) - { - path[pos] = v; - - if (hamCycleUtil (graph, path, pos+1) == true) - return true; - path[pos] = -1; - } - } - - return false; -} - -bool hamCycle(bool graph[V][V]) -{ - int *path = new int[V]; - for (int i = 0; i < V; i++) - path[i] = -1; - - path[0] = 0; - if ( hamCycleUtil(graph, path, 1) == false ) - { - printf("\nSolution does not exist"); - return false; - } - - printSolution(path); - return true; -} - -void printSolution(int path[]) -{ - printf ("Solution Exists:" - " Following is one Hamiltonian Cycle \n"); - for (int i = 0; i < V; i++) - printf(" %d ", path[i]); - - // Let us print the first vertex again to show the complete cycle - printf(" %d ", path[0]); - printf("\n"); -} - -// driver program to test above function -int main() -{ - bool graph1[V][V] = {{0, 1, 0, 1, 0}, - {1, 0, 1, 1, 1}, - {0, 1, 0, 0, 1}, - {1, 1, 0, 0, 1}, - {0, 1, 1, 1, 0}, - }; - - - hamCycle(graph1); - - bool graph2[V][V] = {{0, 1, 0, 1, 0}, - {1, 0, 1, 1, 1}, - {0, 1, 0, 0, 1}, - {1, 1, 0, 0, 0}, - {0, 1, 1, 0, 0}, - }; - - // Print the solution - hamCycle(graph2); - - return 0; -} + +/* C/C++ program for solution of Hamiltonian Cycle problem using backtracking */ +/* +Hamiltonian Path in an undirected graph is a path that visits each vertex exactly once. +A Hamiltonian cycle (or Hamiltonian circuit) is a Hamiltonian Path such that there is an +edge (in graph) from the last vertex to the first vertex of the Hamiltonian Path +*/ + +#include + +// Number of vertices in the graph +#define V 5 + +void printSolution(int path[]); + +bool isSafe(int v, bool graph[V][V], int path[], int pos) +{ + if (graph [ path[pos-1] ][ v ] == 0) + return false; + + for (int i = 0; i < pos; i++) + if (path[i] == v) + return false; + + return true; +} + +bool hamCycleUtil(bool graph[V][V], int path[], int pos) +{ + if (pos == V) + { + if ( graph[ path[pos-1] ][ path[0] ] == 1 ) + return true; + else + return false; + } + + for (int v = 1; v < V; v++) + { + if (isSafe(v, graph, path, pos)) + { + path[pos] = v; + + if (hamCycleUtil (graph, path, pos+1) == true) + return true; + path[pos] = -1; + } + } + + return false; +} + +bool hamCycle(bool graph[V][V]) +{ + int *path = new int[V]; + for (int i = 0; i < V; i++) + path[i] = -1; + + path[0] = 0; + if ( hamCycleUtil(graph, path, 1) == false ) + { + printf("\nSolution does not exist"); + return false; + } + + printSolution(path); + return true; +} + +void printSolution(int path[]) +{ + printf ("Solution Exists:" + " Following is one Hamiltonian Cycle \n"); + for (int i = 0; i < V; i++) + printf(" %d ", path[i]); + + // Let us print the first vertex again to show the complete cycle + printf(" %d ", path[0]); + printf("\n"); +} + +// driver program to test above function +int main() +{ + bool graph1[V][V] = {{0, 1, 0, 1, 0}, + {1, 0, 1, 1, 1}, + {0, 1, 0, 0, 1}, + {1, 1, 0, 0, 1}, + {0, 1, 1, 1, 0}, + }; + + + hamCycle(graph1); + + bool graph2[V][V] = {{0, 1, 0, 1, 0}, + {1, 0, 1, 1, 1}, + {0, 1, 0, 0, 1}, + {1, 1, 0, 0, 0}, + {0, 1, 1, 0, 0}, + }; + + // Print the solution + hamCycle(graph2); + + return 0; +} diff --git a/cpp/algorithms/ModularExponentiation.cpp b/cpp/algorithms/ModularExponentiation.cpp index 00d4ff330..eb9444bb9 100644 --- a/cpp/algorithms/ModularExponentiation.cpp +++ b/cpp/algorithms/ModularExponentiation.cpp @@ -1,23 +1,23 @@ -#include -using namespace std; - -long long fast_expo(long long x, long long y, long long mod) { - long long res = 1; - x %= mod; - while(y) { - if(y % 2) res = (res * x) % mod; - x = (x * x) % mod; - y >>= 1; - } - return res; -} - -int main() { - - long long x, y, mod; - cin >> x >> y >> mod; - - cout << fast_expo(x, y, mod) << "\n"; - - return 0; +#include +using namespace std; + +long long fast_expo(long long x, long long y, long long mod) { + long long res = 1; + x %= mod; + while(y) { + if(y % 2) res = (res * x) % mod; + x = (x * x) % mod; + y >>= 1; + } + return res; +} + +int main() { + + long long x, y, mod; + cin >> x >> y >> mod; + + cout << fast_expo(x, y, mod) << "\n"; + + return 0; } \ No newline at end of file diff --git a/cpp/algorithms/Palindrome.cpp b/cpp/algorithms/Palindrome.cpp deleted file mode 100644 index e0e429535..000000000 --- a/cpp/algorithms/Palindrome.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include -#include -using namespace std; -int main() -{ -string str; -cin>>str; -int l =str.length(); -int f=0,j=l-1; - for(int i=0;i<=l/2;++i) - { - if(str[i]!=str[j--]) - { - cout< -using namespace std; - -int ternary_search(vector ar,int l,int r, int x) -{ - if(r>=l) - { - int mid1 = l + (r-l)/3; - int mid2 = r - (r-l)/3; - if(ar[mid1] == x) - return mid1; - if(ar[mid2] == x) - return mid2; - if(xar[mid2]) - return ternary_search(ar,mid2+1,r,x); - else - return ternary_search(ar,mid1+1,mid2-1,x); - - } - return -1; -} - - -int main() -{ - vector v; - int n; - cout<<"Enter size of list\n"; - cin>>n; - int no,k; - cout<<"Enter nos\n"; - while(n--) - { - cin>>no; - v.push_back(no); - } - cout<<"Enter number you want to search"<>k; - int l=0; - int r=v.size()-1; - int found = ternary_search(v,l,r,k); - if(found == -1) - std::cout<<"Couldn't find number"< +using namespace std; +int main() +{ + int n;cin>>n; + int a[n]; + + for(int i=0;i>a[i]; + + } + for(int i=1;icurrent && j>=0) + { + a[j+1]=a[j]; + j--; + } + a[j+1]=current; + } + + + + + for(int i=0;i -using namespace std; -int liscnt(int ar[],int n) -{ - int lis[n],i,j,maxi; - for(i=0;iar[j]&&lis[i]maxi) - maxi=lis[i]; - } - return maxi; -} -int main() -{ - int ar[8]={10,22,9,33,21,50,41,60}; - cout< +using namespace std; +int liscnt(int ar[],int n) +{ + int lis[n],i,j,maxi; + for(i=0;iar[j]&&lis[i]maxi) + maxi=lis[i]; + } + return maxi; +} +int main() +{ + int ar[8]={10,22,9,33,21,50,41,60}; + cout< -#include -int d,v=0,u=0,count2=0,n,i,choice,count1=0,flag=0,ans; -struct node -{ - int data; - struct node *next; -}*start1=NULL,*start2=NULL,*temp1,*temp2,*temp3,*temp4,*temp5,*temp6,*temp7,*temp8; -void create1(int d) -{ - temp1=(struct node *)malloc(sizeof(struct node)); - temp1->data=d; - temp1->next=NULL; - if (v==0) - { - start1=temp1; - v=1; - count1++; - } - else - { - temp2->next=temp1; - count1++; - } - temp2=temp1; -} -void create2(int d) -{ - temp5=(struct node *)malloc(sizeof(struct node)); - temp5->data=d; - temp5->next=NULL; - if (u==0) - { - start2=temp5; - u=1; - count2++;// - } - else - { - temp6->next=temp5;// - count2++; - } - temp6=temp5;// -} - -void display1() -{ - if (count1==1) - { - temp4=start1; - printf("\n"); - printf("%d\n",temp4->data); - } - - else if (count1==0) - { - printf("\nLINKED LIST 1 IS EMPTY\n"); - } - else - { - temp4=start1; - printf("\n"); - do - { - printf("%d\n",temp4->data); - temp4=temp4->next; - } - while(temp4->next!=NULL); - printf("%d\n",temp4->data); - - } - - -} -void display2() -{ - if (count2==1) - { - temp7=start2; - printf("\n"); - printf("%d\n",temp7->data); - } - - else if (count2==0) - { - printf("\nLINKED LIST 2 IS EMPTY\n"); - } - else - { - temp7=start2; - printf("\n"); - do - { - printf("%d\n",temp7->data); - temp7=temp7->next; - } - while(temp7->next!=NULL); - printf("%d\n",temp7->data); - - } - - -} -int compare(struct node* start1,struct node* start2) -{ - temp3=start1; - temp8=start2; - - /*while (flag=0 && temp8!=NULL) - {*/ - while (flag==0 && temp3!=NULL) - { - - if (temp3->data==temp8->data) - { - flag=1; - } - else - temp3=temp3->next;//seaching ll2 in ll1... - } - //printf("%d",flag); - // temp8=temp8->next; - //} - if (flag==0) - return 0; - else - { - while (temp8!=NULL && flag==1) - { - if (temp3->data==temp8->data) - { - temp3=temp3->next; - temp8=temp8->next; - //printf("%d",flag); - } - else - { - flag=0; - //printf("%d",flag); - return 0; - } - } - return flag; - } -} - -int main() -{ - do - {printf("MAKE YOUR CHOICE:\n\t1.CREATE LINKED LIST 1\n\t2.DISPLAY LINKED LIST 1\n\t3.CREATE LINKED LIST 2\n\t4.DISPLAY LINKED LIST 2\n\t5.COMPARE\n\t6.EXIT\n"); - scanf("%d",&choice); - switch (choice) - { - case 3: - printf("enter the data for creation of a new node: "); - scanf("%d",&d); - create1(d); - printf("\n"); - break; - - case 4: - display1(); - printf("\n"); - break; - - case 6: - exit(0); - printf("\n"); - break; - - case 1: - printf("enter the data for creation of a new node: "); - scanf("%d",&d); - create2(d); - printf("\n"); - break; - case 2: - display2(); - printf("\n"); - break; - - case 5: - ans=compare(start1,start2); - if (ans==0) - { - printf("\n\tlinked list 1 is not present in linked list 2!\n"); - } - else - printf("\n\tlinked list 1 is present in linked list 2!\n"); - break; - } - } - while(1); - return 0; -} +#include +#include +int d,v=0,u=0,count2=0,n,i,choice,count1=0,flag=0,ans; +struct node +{ + int data; + struct node *next; +}*start1=NULL,*start2=NULL,*temp1,*temp2,*temp3,*temp4,*temp5,*temp6,*temp7,*temp8; +void create1(int d) +{ + temp1=(struct node *)malloc(sizeof(struct node)); + temp1->data=d; + temp1->next=NULL; + if (v==0) + { + start1=temp1; + v=1; + count1++; + } + else + { + temp2->next=temp1; + count1++; + } + temp2=temp1; +} +void create2(int d) +{ + temp5=(struct node *)malloc(sizeof(struct node)); + temp5->data=d; + temp5->next=NULL; + if (u==0) + { + start2=temp5; + u=1; + count2++;// + } + else + { + temp6->next=temp5;// + count2++; + } + temp6=temp5;// +} + +void display1() +{ + if (count1==1) + { + temp4=start1; + printf("\n"); + printf("%d\n",temp4->data); + } + + else if (count1==0) + { + printf("\nLINKED LIST 1 IS EMPTY\n"); + } + else + { + temp4=start1; + printf("\n"); + do + { + printf("%d\n",temp4->data); + temp4=temp4->next; + } + while(temp4->next!=NULL); + printf("%d\n",temp4->data); + + } + + +} +void display2() +{ + if (count2==1) + { + temp7=start2; + printf("\n"); + printf("%d\n",temp7->data); + } + + else if (count2==0) + { + printf("\nLINKED LIST 2 IS EMPTY\n"); + } + else + { + temp7=start2; + printf("\n"); + do + { + printf("%d\n",temp7->data); + temp7=temp7->next; + } + while(temp7->next!=NULL); + printf("%d\n",temp7->data); + + } + + +} +int compare(struct node* start1,struct node* start2) +{ + temp3=start1; + temp8=start2; + + /*while (flag=0 && temp8!=NULL) + {*/ + while (flag==0 && temp3!=NULL) + { + + if (temp3->data==temp8->data) + { + flag=1; + } + else + temp3=temp3->next;//seaching ll2 in ll1... + } + //printf("%d",flag); + // temp8=temp8->next; + //} + if (flag==0) + return 0; + else + { + while (temp8!=NULL && flag==1) + { + if (temp3->data==temp8->data) + { + temp3=temp3->next; + temp8=temp8->next; + //printf("%d",flag); + } + else + { + flag=0; + //printf("%d",flag); + return 0; + } + } + return flag; + } +} + +int main() +{ + do + {printf("MAKE YOUR CHOICE:\n\t1.CREATE LINKED LIST 1\n\t2.DISPLAY LINKED LIST 1\n\t3.CREATE LINKED LIST 2\n\t4.DISPLAY LINKED LIST 2\n\t5.COMPARE\n\t6.EXIT\n"); + scanf("%d",&choice); + switch (choice) + { + case 3: + printf("enter the data for creation of a new node: "); + scanf("%d",&d); + create1(d); + printf("\n"); + break; + + case 4: + display1(); + printf("\n"); + break; + + case 6: + exit(0); + printf("\n"); + break; + + case 1: + printf("enter the data for creation of a new node: "); + scanf("%d",&d); + create2(d); + printf("\n"); + break; + case 2: + display2(); + printf("\n"); + break; + + case 5: + ans=compare(start1,start2); + if (ans==0) + { + printf("\n\tlinked list 1 is not present in linked list 2!\n"); + } + else + printf("\n\tlinked list 1 is present in linked list 2!\n"); + break; + } + } + while(1); + return 0; +} diff --git a/cpp/algorithms/stringinterleaving.cpp b/cpp/algorithms/stringinterleaving.cpp index 5c4e1fa68..3d90932c4 100644 --- a/cpp/algorithms/stringinterleaving.cpp +++ b/cpp/algorithms/stringinterleaving.cpp @@ -1,52 +1,52 @@ -#include -using namespace std; -bool isInterleaved(char* A, char* B, char* C) -{ - // Find lengths of the two strings - int M = strlen(A), N = strlen(B); - bool IL[M+1][N+1]; - - for(int x=0;x +using namespace std; +bool isInterleaved(char* A, char* B, char* C) +{ + // Find lengths of the two strings + int M = strlen(A), N = strlen(B); + bool IL[M+1][N+1]; + + for(int x=0;x -#define stack_size 25 -using namespace std; -struct Stack -{ - char A[100]; - int top; -}; -char pop(Stack &a) -{ - if(a.top==-1) - { - //cout<<"Stack is empty"< +#define stack_size 25 +using namespace std; +struct Stack +{ + char A[100]; + int top; +}; +char pop(Stack &a) +{ + if(a.top==-1) + { + //cout<<"Stack is empty"< -#include -using namespace std; -template -struct node -{ - t val; - node* l; - node* r; - -}; -template -class bst -{ -private: - void search_pos(node* temp,node* root) - { - if ((temp->val > root->val) && (root->r != NULL)) - search_pos(temp,root->r); - if ((temp->val > root->val) && (root->r == NULL)) - root->r = temp; - if ((temp->val < root->val) && (root->l != NULL)) - search_pos(temp,root->l); - if ((temp->val < root->val) && (root->l == NULL)) - root->l = temp; - } -public: - node* root=NULL; - void insertnode() - { - node* temp =new node; - t n; - cin>>n; - temp->val= n; - temp->l = temp->r = NULL; - if (root == NULL) - root = temp; - else - search_pos(temp , root); - } - - void inorder(node*root) - { - if(root!=NULL) - { - - inorder(root->l); - t n = root->val; - cout<<"\t"<r); - } - } - -}; -int main() -{ - - int n; - cout<<"\n 1...Integer\n 2... Character\n 3...Double\n 4... String"; - cout<<"\nEnter your choice:- "; - cin>>n; - switch(n) - { - case 1: - { - bstobj; - do - { - cout<<"Enter value to be inserted:- "; - obj.insertnode(); - cout<<"\nDo u want to insert more ?? if yes enter 1 else 0:- "; - cin >> n; - }while(n!=0); - obj.inorder(obj.root); - break; - } - - case 2: - { - - bstobj; - do - { - cout<<"Enter value to be inserted:- "; - obj.insertnode(); - cout<<"\nDo u want to insert more ?? if yes enter 1 else 0:- "; - cin >> n; - }while(n!=0); - obj.inorder(obj.root); - break; - } - - case 3: - { - bstobj; - do - { - cout<<"Enter value to be inserted:- "; - obj.insertnode(); - cout<<"\nDo u want to insert more ?? if yes enter 1 else 0:- "; - cin >> n; - }while(n!=0); - obj.inorder(obj.root); - break; - } - - case 4: - { - bstobj; - do - { - cout<<"Enter value to be inserted:- "; - obj.insertnode(); - cout<<"\nDo u want to insert more ?? if yes enter 1 else 0:- "; - cin >> n; - }while(n!=0); - obj.inorder(obj.root); - break; - } - default: - cout<<"\nWrong choice"; - break; - } - return 0; -} +#include +#include +using namespace std; +template +struct node +{ + t val; + node* l; + node* r; + +}; +template +class bst +{ +private: + void search_pos(node* temp,node* root) + { + if ((temp->val > root->val) && (root->r != NULL)) + search_pos(temp,root->r); + if ((temp->val > root->val) && (root->r == NULL)) + root->r = temp; + if ((temp->val < root->val) && (root->l != NULL)) + search_pos(temp,root->l); + if ((temp->val < root->val) && (root->l == NULL)) + root->l = temp; + } +public: + node* root=NULL; + void insertnode() + { + node* temp =new node; + t n; + cin>>n; + temp->val= n; + temp->l = temp->r = NULL; + if (root == NULL) + root = temp; + else + search_pos(temp , root); + } + + void inorder(node*root) + { + if(root!=NULL) + { + + inorder(root->l); + t n = root->val; + cout<<"\t"<r); + } + } + +}; +int main() +{ + + int n; + cout<<"\n 1...Integer\n 2... Character\n 3...Double\n 4... String"; + cout<<"\nEnter your choice:- "; + cin>>n; + switch(n) + { + case 1: + { + bstobj; + do + { + cout<<"Enter value to be inserted:- "; + obj.insertnode(); + cout<<"\nDo u want to insert more ?? if yes enter 1 else 0:- "; + cin >> n; + }while(n!=0); + obj.inorder(obj.root); + break; + } + + case 2: + { + + bstobj; + do + { + cout<<"Enter value to be inserted:- "; + obj.insertnode(); + cout<<"\nDo u want to insert more ?? if yes enter 1 else 0:- "; + cin >> n; + }while(n!=0); + obj.inorder(obj.root); + break; + } + + case 3: + { + bstobj; + do + { + cout<<"Enter value to be inserted:- "; + obj.insertnode(); + cout<<"\nDo u want to insert more ?? if yes enter 1 else 0:- "; + cin >> n; + }while(n!=0); + obj.inorder(obj.root); + break; + } + + case 4: + { + bstobj; + do + { + cout<<"Enter value to be inserted:- "; + obj.insertnode(); + cout<<"\nDo u want to insert more ?? if yes enter 1 else 0:- "; + cin >> n; + }while(n!=0); + obj.inorder(obj.root); + break; + } + default: + cout<<"\nWrong choice"; + break; + } + return 0; +} diff --git a/cpp/bst.cpp b/cpp/bst.cpp index 7cbd4908b..397280a4d 100644 --- a/cpp/bst.cpp +++ b/cpp/bst.cpp @@ -1,309 +1,309 @@ -#include -#include -#include -using namespace std; -class node -{ -public: - int data; - node *left; - node *right; - node(int d):data(d),left(NULL),right(NULL){}//if any data member is const then using this list is compulsory -}; - -node* insertinbst(node* &root,int data) -{ - if(root==NULL) - { - root=new node(data); - return root; - } - if(datadata) - { - root->left=insertinbst(root->left,data); - } - else - { - root->right=insertinbst(root->right,data); - } - return root; -} -node* takeInput() -{ - node* root; - int data; - cin>>data; - while(data!=-1) - { - root=insertinbst(root,data); - cin>>data; - } - return root; -} - -node* Search(node* root,int key) -{ - if(root==NULL) - { - return root; - } - if(root->data==key) - return root; - else if(root->data>key) - { - return Search(root->left,key); - } - else - return Search(root->right,key); -} - -void preorderTraversal(node* root) -{ - if(root!=NULL) - { - cout<data<<" "; - preorderTraversal(root->left); - preorderTraversal(root->right); - } -} - - -void inorderTraversal(node* root) -{ - if(root!=NULL) - { - inorderTraversal(root->left); - cout<data<<" "; - inorderTraversal(root->right); - } -} - - -void postorderTraversal(node* root) -{ - if(root!=NULL) - { - postorderTraversal(root->left); - postorderTraversal(root->right); - cout<data<<" "; - } -} - -void printlevel(node* root) -{ - queue q; - cout<data<<" "; - q.push(root); - while(!q.empty()) - { - node* f=q.front(); - q.pop(); - if(f->left!=NULL) - { - cout<left->data<<" "; - q.push(f->left); - } - if(f->right!=NULL) - { - cout<right->data<<" "; - q.push(f->right); - } - } -} - -void printpatternlevel(node* root) -{ - queue q; - // cout<data; - q.push(root); - q.push(NULL); - while(!q.empty()) - { - node* f=q.front(); - q.pop(); - if(f==NULL) - { - cout<data<<" "; - if(f->left!=NULL) - { - //cout<left->data<<" "; - q.push(f->left); - } - if(f->right!=NULL) - { - //cout<right->data<<" "; - q.push(f->right); - } - } -} - -void normal_print(node* root) -{ - if(root!=NULL) - cout<data; - else - cout<<"tree is empty"; -} - -void printlist(node* head) -{ - while(head!=NULL) - { - cout<data<<"->"; - head=head->right; - } - cout<>(istream& is,node* &r) -{ - r=takeInput(); - return is; -} -ostream& operator<<(ostream& os,node* &r) -{ - printpatternlevel(r); - return os; -} - -pair bst_linkedlist(node* root) -{ - if(root==NULL||(root->left==NULL&&root->right==NULL)) - { - return make_pair(root,root); - } - pair left,right; - left=bst_linkedlist(root->left); - right=bst_linkedlist(root->right); - //root->left=NULL;//left ke faltu ghinone links todne ke liye - if(root->left!=NULL&&root->right==NULL) - { - root->left=NULL; - left.second->right=root; - return make_pair(left.first,root); - } - else if(root->left==NULL&&root->right!=NULL) - { - root->right=right.first; - return make_pair(root,right.first); - } - else - { - root->left=NULL; - left.second->right=root; - root->right=right.first; - return make_pair(left.first,right.second); - } -} -node* arrtotree(int a[],int start,int endi) -{ - node* root=NULL; - if(start>endi) - return root; - int mid=(start+endi)/2; - root=new node(a[mid]); - root->left=arrtotree(a,start,mid-1); - root->right=arrtotree(a,mid+1,endi); - return root; -} - -bool ifbst(node* root ,int min_v=INT_MIN,int max_v=INT_MAX) -{ - if(root==NULL) - return true; - bool l,r; - l=ifbst(root->left,min_v,root->data); - r=ifbst(root->right,root->data,max_v); - return (root->data>=min_v&&root->data<=max_v)&&l&&r; -} - -bool treeident(node* root1,node* root2) -{ - if(root1==NULL||root2==NULL) - return root1==root2; - bool l,r; - cout<<"hello"; - l=treeident(root1->left,root2->left); - r=treeident(root1->right,root2->right); - return (root1->data==root2->data)&&l&&r; -} - -node* findMin(node* root) -{ - while(root->left!=NULL) - { - root=root->left; - } - return root; -} - -node* remove_bst(node* root,int data) -{ - if(root==NULL) - return root; - if(root->data==data) - { - //1.leaf node - if(root->left==NULL&&root->right==NULL) - { - delete root; - root=NULL; - return root; - } - //2. one child - if(root->left!=NULL&&root->right==NULL) - { - node* temp=root->left; - delete root; - return temp; - } - if(root->left==NULL&&root->right!=NULL) - { - node* temp=root->right; - delete root; - return temp; - } - //3. two child - if(root->left!=NULL&&root->right!=NULL) - { - node* temp=findMin(root->right); - root->data=temp->data; - root->right=remove_bst(root->right,temp->data); - return root; - } - } - else if(root->data>data) - { - root->left=remove_bst(root->left,data); - } - else - { - root->right=remove_bst(root->right,data); - } - return root; -} -int main() -{ - node* root=NULL; - cin>>root; - cout< +#include +#include +using namespace std; +class node +{ +public: + int data; + node *left; + node *right; + node(int d):data(d),left(NULL),right(NULL){}//if any data member is const then using this list is compulsory +}; + +node* insertinbst(node* &root,int data) +{ + if(root==NULL) + { + root=new node(data); + return root; + } + if(datadata) + { + root->left=insertinbst(root->left,data); + } + else + { + root->right=insertinbst(root->right,data); + } + return root; +} +node* takeInput() +{ + node* root; + int data; + cin>>data; + while(data!=-1) + { + root=insertinbst(root,data); + cin>>data; + } + return root; +} + +node* Search(node* root,int key) +{ + if(root==NULL) + { + return root; + } + if(root->data==key) + return root; + else if(root->data>key) + { + return Search(root->left,key); + } + else + return Search(root->right,key); +} + +void preorderTraversal(node* root) +{ + if(root!=NULL) + { + cout<data<<" "; + preorderTraversal(root->left); + preorderTraversal(root->right); + } +} + + +void inorderTraversal(node* root) +{ + if(root!=NULL) + { + inorderTraversal(root->left); + cout<data<<" "; + inorderTraversal(root->right); + } +} + + +void postorderTraversal(node* root) +{ + if(root!=NULL) + { + postorderTraversal(root->left); + postorderTraversal(root->right); + cout<data<<" "; + } +} + +void printlevel(node* root) +{ + queue q; + cout<data<<" "; + q.push(root); + while(!q.empty()) + { + node* f=q.front(); + q.pop(); + if(f->left!=NULL) + { + cout<left->data<<" "; + q.push(f->left); + } + if(f->right!=NULL) + { + cout<right->data<<" "; + q.push(f->right); + } + } +} + +void printpatternlevel(node* root) +{ + queue q; + // cout<data; + q.push(root); + q.push(NULL); + while(!q.empty()) + { + node* f=q.front(); + q.pop(); + if(f==NULL) + { + cout<data<<" "; + if(f->left!=NULL) + { + //cout<left->data<<" "; + q.push(f->left); + } + if(f->right!=NULL) + { + //cout<right->data<<" "; + q.push(f->right); + } + } +} + +void normal_print(node* root) +{ + if(root!=NULL) + cout<data; + else + cout<<"tree is empty"; +} + +void printlist(node* head) +{ + while(head!=NULL) + { + cout<data<<"->"; + head=head->right; + } + cout<>(istream& is,node* &r) +{ + r=takeInput(); + return is; +} +ostream& operator<<(ostream& os,node* &r) +{ + printpatternlevel(r); + return os; +} + +pair bst_linkedlist(node* root) +{ + if(root==NULL||(root->left==NULL&&root->right==NULL)) + { + return make_pair(root,root); + } + pair left,right; + left=bst_linkedlist(root->left); + right=bst_linkedlist(root->right); + //root->left=NULL;//left ke faltu ghinone links todne ke liye + if(root->left!=NULL&&root->right==NULL) + { + root->left=NULL; + left.second->right=root; + return make_pair(left.first,root); + } + else if(root->left==NULL&&root->right!=NULL) + { + root->right=right.first; + return make_pair(root,right.first); + } + else + { + root->left=NULL; + left.second->right=root; + root->right=right.first; + return make_pair(left.first,right.second); + } +} +node* arrtotree(int a[],int start,int endi) +{ + node* root=NULL; + if(start>endi) + return root; + int mid=(start+endi)/2; + root=new node(a[mid]); + root->left=arrtotree(a,start,mid-1); + root->right=arrtotree(a,mid+1,endi); + return root; +} + +bool ifbst(node* root ,int min_v=INT_MIN,int max_v=INT_MAX) +{ + if(root==NULL) + return true; + bool l,r; + l=ifbst(root->left,min_v,root->data); + r=ifbst(root->right,root->data,max_v); + return (root->data>=min_v&&root->data<=max_v)&&l&&r; +} + +bool treeident(node* root1,node* root2) +{ + if(root1==NULL||root2==NULL) + return root1==root2; + bool l,r; + cout<<"hello"; + l=treeident(root1->left,root2->left); + r=treeident(root1->right,root2->right); + return (root1->data==root2->data)&&l&&r; +} + +node* findMin(node* root) +{ + while(root->left!=NULL) + { + root=root->left; + } + return root; +} + +node* remove_bst(node* root,int data) +{ + if(root==NULL) + return root; + if(root->data==data) + { + //1.leaf node + if(root->left==NULL&&root->right==NULL) + { + delete root; + root=NULL; + return root; + } + //2. one child + if(root->left!=NULL&&root->right==NULL) + { + node* temp=root->left; + delete root; + return temp; + } + if(root->left==NULL&&root->right!=NULL) + { + node* temp=root->right; + delete root; + return temp; + } + //3. two child + if(root->left!=NULL&&root->right!=NULL) + { + node* temp=findMin(root->right); + root->data=temp->data; + root->right=remove_bst(root->right,temp->data); + return root; + } + } + else if(root->data>data) + { + root->left=remove_bst(root->left,data); + } + else + { + root->right=remove_bst(root->right,data); + } + return root; +} +int main() +{ + node* root=NULL; + cin>>root; + cout< -using namespace std; - -const int N = 1e5 + 10; // Maximum size -vector tree[N]; -int data[N]; - -void build(int node, int start, int end) { - if(start == end) { - tree[node].push_back(data[start]); - return; - } - - int mid = (start + end) / 2; - int left_child = 2 * node; - int right_child = 2 * node + 1; - - build(left_child, start, mid); - build(right_child, mid + 1, end); - merge(tree[left_child].begin(), tree[left_child].end(), tree[right_child].begin(), tree[right_child].end(), back_inserter(tree[node])); -} - -int query(int node, int start, int end, int l, int r, int k) { - if(start > end || end < l || r < start) return 0; - if(l <= start && end <= r) { - // Replace lower_bound by upper bound for number of elements <= k in range [l, r] - return lower_bound(tree[node].begin(), tree[node].end(), k) - tree[node].begin(); // Number of elements < k in range [l, r] - } - - int mid = (start + end) / 2; - int left_child = 2 * node; - int right_child = 2 * node + 1; - - return query(left_child, start, mid, l, r, k) + query(right_child, mid + 1, end, l, r, k); -} - -int main() -{ - int n; - cin >> n; - - for(int i = 1; i <= n; i++) cin >> data[i]; - - int start = 1; - int end = n; - - build(1, start, end); // build merge sort tree for range [start, end] - - int l, r, k; - cin >> l >> r >> k; - - cout << query(1, start, end, l, r, k); // number of elements in [l, r] less than k - - return 0; +/* + Prakhar Gupta + prakhar17252 on competitive programming sites +*/ + +#include +using namespace std; + +const int N = 1e5 + 10; // Maximum size +vector tree[N]; +int data[N]; + +void build(int node, int start, int end) { + if(start == end) { + tree[node].push_back(data[start]); + return; + } + + int mid = (start + end) / 2; + int left_child = 2 * node; + int right_child = 2 * node + 1; + + build(left_child, start, mid); + build(right_child, mid + 1, end); + merge(tree[left_child].begin(), tree[left_child].end(), tree[right_child].begin(), tree[right_child].end(), back_inserter(tree[node])); +} + +int query(int node, int start, int end, int l, int r, int k) { + if(start > end || end < l || r < start) return 0; + if(l <= start && end <= r) { + // Replace lower_bound by upper bound for number of elements <= k in range [l, r] + return lower_bound(tree[node].begin(), tree[node].end(), k) - tree[node].begin(); // Number of elements < k in range [l, r] + } + + int mid = (start + end) / 2; + int left_child = 2 * node; + int right_child = 2 * node + 1; + + return query(left_child, start, mid, l, r, k) + query(right_child, mid + 1, end, l, r, k); +} + +int main() +{ + int n; + cin >> n; + + for(int i = 1; i <= n; i++) cin >> data[i]; + + int start = 1; + int end = n; + + build(1, start, end); // build merge sort tree for range [start, end] + + int l, r, k; + cin >> l >> r >> k; + + cout << query(1, start, end, l, r, k); // number of elements in [l, r] less than k + + return 0; } \ No newline at end of file diff --git a/cpp/nthFibonacci_logn.cpp b/cpp/nthFibonacci_logn.cpp old mode 100755 new mode 100644 index 1f93237bd..2e450f6ad --- a/cpp/nthFibonacci_logn.cpp +++ b/cpp/nthFibonacci_logn.cpp @@ -1,41 +1,41 @@ -#include -using namespace std; - -// helper function to multiply two 2x2 matrices -void multiply(int a[2][2],int m[2][2]){ - int firstValue = a[0][0]*m[0][0] + a[0][1]*m[1][0]; - int secondValue = a[0][0]*m[0][1] + a[0][1]*m[1][1]; - int thirdValue = a[1][0]*m[0][0] + a[1][1]*m[1][0]; - int fourthValue = a[1][0]*m[0][1] + a[1][1]*m[1][1]; - a[0][0] = firstValue; - a[0][1] = secondValue; - a[1][0] = thirdValue; - a[1][1] = fourthValue; -} -// function to compute power of 2x2 matrix using matrix exponentiation -void power(int a[2][2],int n){ - // base case - if(n==0 || n==1) - return; - power(a,n/2); - multiply(a,a); - if(n%2!=0){ - int m[2][2] = {{1,1},{1,0}}; - multiply(a,m); - } -} -int fib(int n){ - int a[2][2] = {{1,1},{1,0}}; - if(n==0) - return 0; - // find matrix to the power (n-1) - power(a,n-1); - // (0,0) element is the nth fibonacci number - return a[0][0]; -} -int main(){ - // enter n - int n; - cin >> n; - cout << n << "th fibonacci number: " << fib(n); +#include +using namespace std; + +// helper function to multiply two 2x2 matrices +void multiply(int a[2][2],int m[2][2]){ + int firstValue = a[0][0]*m[0][0] + a[0][1]*m[1][0]; + int secondValue = a[0][0]*m[0][1] + a[0][1]*m[1][1]; + int thirdValue = a[1][0]*m[0][0] + a[1][1]*m[1][0]; + int fourthValue = a[1][0]*m[0][1] + a[1][1]*m[1][1]; + a[0][0] = firstValue; + a[0][1] = secondValue; + a[1][0] = thirdValue; + a[1][1] = fourthValue; +} +// function to compute power of 2x2 matrix using matrix exponentiation +void power(int a[2][2],int n){ + // base case + if(n==0 || n==1) + return; + power(a,n/2); + multiply(a,a); + if(n%2!=0){ + int m[2][2] = {{1,1},{1,0}}; + multiply(a,m); + } +} +int fib(int n){ + int a[2][2] = {{1,1},{1,0}}; + if(n==0) + return 0; + // find matrix to the power (n-1) + power(a,n-1); + // (0,0) element is the nth fibonacci number + return a[0][0]; +} +int main(){ + // enter n + int n; + cin >> n; + cout << n << "th fibonacci number: " << fib(n); } \ No newline at end of file diff --git a/cpp/prefixinfixpostfix.cpp b/cpp/prefixinfixpostfix.cpp index 6018b8521..9020788d1 100644 --- a/cpp/prefixinfixpostfix.cpp +++ b/cpp/prefixinfixpostfix.cpp @@ -1,116 +1,116 @@ -#include -#define stack_size 25 -using namespace std; -struct Stack -{ - char A[100]; - int top; -}; -char pop(Stack &a) -{ - if(a.top==-1) - { - //cout<<"Stack is empty"<='a'&&c<='z') - return 1; - return 0; -} - -int operat(char c) -{ - if(c=='+'||c=='-'||c=='*'||c=='/'||c=='$') - return 1; - return 0; -} -char* postfixconv(Stack &a,char infix[]) -{ - char *postfix=new char[stack_size]; - a.top=-1; - push(a,'$'); - int i=0,j=0; - while(infix[i]!='\0') - { - if(operand(infix[i]))//if we encounter an alphabet - postfix[j++]=infix[i++]; - else if(operat(infix[i]))//if we encounter an operator - { - while((prec(infix[i])<=prec(a.A[a.top]))&&a.top>0&&a.A[a.top]!='(') - /* if precedence of current operator in infix is less than or equal to - precedence of operator on top of stack, pop it from stack and insert in output*/ - { - //cout< +#define stack_size 25 +using namespace std; +struct Stack +{ + char A[100]; + int top; +}; +char pop(Stack &a) +{ + if(a.top==-1) + { + //cout<<"Stack is empty"<='a'&&c<='z') + return 1; + return 0; +} + +int operat(char c) +{ + if(c=='+'||c=='-'||c=='*'||c=='/'||c=='$') + return 1; + return 0; +} +char* postfixconv(Stack &a,char infix[]) +{ + char *postfix=new char[stack_size]; + a.top=-1; + push(a,'$'); + int i=0,j=0; + while(infix[i]!='\0') + { + if(operand(infix[i]))//if we encounter an alphabet + postfix[j++]=infix[i++]; + else if(operat(infix[i]))//if we encounter an operator + { + while((prec(infix[i])<=prec(a.A[a.top]))&&a.top>0&&a.A[a.top]!='(') + /* if precedence of current operator in infix is less than or equal to + precedence of operator on top of stack, pop it from stack and insert in output*/ + { + //cout< -#define stack_size 5 -using namespace std; -struct Stack -{ - int A[100]; - int top; -}; -int pop(Stack &a) -{ - if(a.top==-1) - { - //cout<<"Stack is empty"<>choice; - switch(choice) - { - case '1':cin>>x; - queuepush(a1,x); - break; - case '2':cout<<"Element popped is :"< +#define stack_size 5 +using namespace std; +struct Stack +{ + int A[100]; + int top; +}; +int pop(Stack &a) +{ + if(a.top==-1) + { + //cout<<"Stack is empty"<>choice; + switch(choice) + { + case '1':cin>>x; + queuepush(a1,x); + break; + case '2':cout<<"Element popped is :"< - -int getMax(int arr[], int n) { - int mx = arr[0]; - int i; - for (i = 1; i < n; i++) - if (arr[i] > mx) - mx = arr[i]; - return mx; -} - -void countSort(int arr[], int n, int exp) { - int output[n]; // output array - int i, count[10] = { 0 }; - - // Store count of occurrences in count[] - for (i = 0; i < n; i++) - count[(arr[i] / exp) % 10]++; - - for (i = 1; i < 10; i++) - count[i] += count[i - 1]; - - // Build the output array - for (i = n - 1; i >= 0; i--) { - output[count[(arr[i] / exp) % 10] - 1] = arr[i]; - count[(arr[i] / exp) % 10]--; - } - - for (i = 0; i < n; i++) - arr[i] = output[i]; -} - -// The main function to that sorts arr[] of size n using Radix Sort -void radixsort(int arr[], int n) { - int m = getMax(arr, n); - - int exp; - for (exp = 1; m / exp > 0; exp *= 10) - countSort(arr, n, exp); -} - -void print(int arr[], int n) { - int i; - for (i = 0; i < n; i++) - printf("%d ", arr[i]); -} - -int main() { - int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; - int n = sizeof(arr) / sizeof(arr[0]); - radixsort(arr, n); - print(arr, n); - return 0; -} +#include + +int getMax(int arr[], int n) { + int mx = arr[0]; + int i; + for (i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; +} + +void countSort(int arr[], int n, int exp) { + int output[n]; // output array + int i, count[10] = { 0 }; + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + for (i = 0; i < n; i++) + arr[i] = output[i]; +} + +// The main function to that sorts arr[] of size n using Radix Sort +void radixsort(int arr[], int n) { + int m = getMax(arr, n); + + int exp; + for (exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); +} + +void print(int arr[], int n) { + int i; + for (i = 0; i < n; i++) + printf("%d ", arr[i]); +} + +int main() { + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = sizeof(arr) / sizeof(arr[0]); + radixsort(arr, n); + print(arr, n); + return 0; +} diff --git a/edition/2017/cpp/InterpolationSearch.cpp b/edition/2017/cpp/InterpolationSearch.cpp index 51dcf8bfa..f710b31d1 100644 --- a/edition/2017/cpp/InterpolationSearch.cpp +++ b/edition/2017/cpp/InterpolationSearch.cpp @@ -1,15 +1,15 @@ -#include -using namespace std; -int InterpolationSearch(int A[],int size,int data){ - int low=0,mid,high=size-1; - while(low<=high){ - mid=low+(((data-A[low])*(high-low))/(A[high]-A[low])); - if(data==A[mid]) - return mid+1; - if(data +using namespace std; +int InterpolationSearch(int A[],int size,int data){ + int low=0,mid,high=size-1; + while(low<=high){ + mid=low+(((data-A[low])*(high-low))/(A[high]-A[low])); + if(data==A[mid]) + return mid+1; + if(data children; - - Node(int data) { - this.data = data; - children = new ArrayList<>(); - } - } - - Node root; - int size = 0; - - GenericTree() { - Scanner s = new Scanner(System.in); - this.root = takeInput(s, null, 0); - // TODO Auto-generated constructor stub - } - - private Node takeInput(Scanner s, Node parent, int ithChild) { - if (parent == null) { - System.out.println("Enter data for root node"); - } else { - System.out.println("\nEnter data for " + ithChild + "thchild of " + parent.data); - } - int nodeData = s.nextInt(); - Node node = new Node(nodeData); - this.size++; - System.out.println("\nEnter number of children for " + node.data); - int numChild = s.nextInt(); - for (int i = 0; i < numChild; i++) { - Node child = this.takeInput(s, node, i); - node.children.add(child); - } - return node; - - } - - public void display() { - System.out.println("\n------------\nTREE OUTPUT"); - this.display(root); - } - - private void display(Node node) { - System.out.print("\n" + node.data + "=>"); - for (int i = 0; i < node.children.size(); i++) { - System.out.print(node.children.get(i).data + ","); - } - System.out.println("END"); - for (int i = 0; i < node.children.size(); i++) { - display(node.children.get(i)); - } - } - - public int size2() { - return this.size2(this.root); - } - - private int size2(Node node) { - int t = 0; - - for (int i = 0; i < node.children.size(); i++) { - int childsize = size2(node.children.get(i)); - t = t + childsize; - } - return t + 1; - } - - public int max() { - return this.max(root); - } - - private int max(Node node) { - int max = node.data; - for (int i = 0; i < node.children.size(); i++) { - if (max(node.children.get(i)) > max) - max = node.children.get(i).data; - - } - return max; - } - - public int height() { - return this.height(root); - } - - private int height(Node node) { - int height = -1; - for (int i = 0; i < node.children.size(); i++) { - int heightofchild = this.height(node.children.get(i)); - if (heightofchild > height) - height = heightofchild; - } - return height + 1; - } - - public boolean find(int data) { - return this.find(root, data); - } - - private boolean find(Node node, int find) { - boolean flag = false; - for (int i = 0; i < node.children.size(); i++) - if (node.children.get(i).data == find) { - flag = true; - return flag; - } - for (int i = 0; i < node.children.size(); i++) { - return find(node.children.get(i), find); - } - return flag; - } - - public void mirror() { - this.mirror(root); - } - - private void mirror(Node node) { - int left = 0, right = node.children.size() - 1; - while (left <= right) { - Node temp = node.children.get(left); - node.children.set(left, node.children.get(right)); - node.children.set(right, temp); - left++; - right--; - } - for (int i = 0; i < node.children.size(); i++) - this.mirror(node.children.get(i)); - } - - public void printLevel(int level) { - this.printAtLevel(root, level); - } - - private void printAtLevel(Node node, int level) { - if (level == 0) { - System.out.println(node.data); - return; - } - for (int i = 0; i < node.children.size(); i++) { - this.printAtLevel(node.children.get(i), level - 1); - } - - } - - public void preOrder() { - System.out.println(root.data); - this.preOrder(root); - } - - private void preOrder(Node node) { - - for (int i = 0; i < node.children.size(); i++) { - System.out.println(node.children.get(i).data); - preOrder(node.children.get(i)); - - } - - } - - public void postOrder() { - this.postOrder(root); - } - - private void postOrder(Node node) { - for (int i = 0; i < node.children.size(); i++) { - - preOrder(node.children.get(i)); - System.out.println(node.children.get(i).data); - - } - System.out.println(root.data); - - } - - public void levelOrder() { - this.levelOrder(root); - } - - private void levelOrder(Node node) { - - } -} - -//CLIENT -public class GenericTreeClient { - - public static void main(String[] args) { - // TODO Auto-generated method stub - // 18 3 64 2 17 0 10 0 27 0 39 1 34 0 - GenericTree tree=new GenericTree(); - Scanner s=new Scanner(System.in); - tree.display(); - System.out.println("\nSize= "+tree.size2()); - System.out.println("\nMax= "+tree.max()); - System.out.println("\nHeight= "+tree.height()); - System.out.println("Enter a number to find: " ); - int find=s.nextInt(); - System.out.println("\nIf "+find+" is present: "+tree.find(find)); - System.out.println("\n-----------Mirror"); - tree.mirror(); - tree.display(); - tree.mirror(); - System.out.println("\n-----------Print At Level 2"); - tree.printLevel(2); - System.out.println("\n-----------Pre Order Display"); - tree.preOrder(); - System.out.println("\n-----------Post Order Display"); - tree.postOrder(); - } - -} - + + +import java.util.ArrayList; +import java.util.Scanner; + +public class GenericTree { + private class Node { + int data; + ArrayList children; + + Node(int data) { + this.data = data; + children = new ArrayList<>(); + } + } + + Node root; + int size = 0; + + GenericTree() { + Scanner s = new Scanner(System.in); + this.root = takeInput(s, null, 0); + // TODO Auto-generated constructor stub + } + + private Node takeInput(Scanner s, Node parent, int ithChild) { + if (parent == null) { + System.out.println("Enter data for root node"); + } else { + System.out.println("\nEnter data for " + ithChild + "thchild of " + parent.data); + } + int nodeData = s.nextInt(); + Node node = new Node(nodeData); + this.size++; + System.out.println("\nEnter number of children for " + node.data); + int numChild = s.nextInt(); + for (int i = 0; i < numChild; i++) { + Node child = this.takeInput(s, node, i); + node.children.add(child); + } + return node; + + } + + public void display() { + System.out.println("\n------------\nTREE OUTPUT"); + this.display(root); + } + + private void display(Node node) { + System.out.print("\n" + node.data + "=>"); + for (int i = 0; i < node.children.size(); i++) { + System.out.print(node.children.get(i).data + ","); + } + System.out.println("END"); + for (int i = 0; i < node.children.size(); i++) { + display(node.children.get(i)); + } + } + + public int size2() { + return this.size2(this.root); + } + + private int size2(Node node) { + int t = 0; + + for (int i = 0; i < node.children.size(); i++) { + int childsize = size2(node.children.get(i)); + t = t + childsize; + } + return t + 1; + } + + public int max() { + return this.max(root); + } + + private int max(Node node) { + int max = node.data; + for (int i = 0; i < node.children.size(); i++) { + if (max(node.children.get(i)) > max) + max = node.children.get(i).data; + + } + return max; + } + + public int height() { + return this.height(root); + } + + private int height(Node node) { + int height = -1; + for (int i = 0; i < node.children.size(); i++) { + int heightofchild = this.height(node.children.get(i)); + if (heightofchild > height) + height = heightofchild; + } + return height + 1; + } + + public boolean find(int data) { + return this.find(root, data); + } + + private boolean find(Node node, int find) { + boolean flag = false; + for (int i = 0; i < node.children.size(); i++) + if (node.children.get(i).data == find) { + flag = true; + return flag; + } + for (int i = 0; i < node.children.size(); i++) { + return find(node.children.get(i), find); + } + return flag; + } + + public void mirror() { + this.mirror(root); + } + + private void mirror(Node node) { + int left = 0, right = node.children.size() - 1; + while (left <= right) { + Node temp = node.children.get(left); + node.children.set(left, node.children.get(right)); + node.children.set(right, temp); + left++; + right--; + } + for (int i = 0; i < node.children.size(); i++) + this.mirror(node.children.get(i)); + } + + public void printLevel(int level) { + this.printAtLevel(root, level); + } + + private void printAtLevel(Node node, int level) { + if (level == 0) { + System.out.println(node.data); + return; + } + for (int i = 0; i < node.children.size(); i++) { + this.printAtLevel(node.children.get(i), level - 1); + } + + } + + public void preOrder() { + System.out.println(root.data); + this.preOrder(root); + } + + private void preOrder(Node node) { + + for (int i = 0; i < node.children.size(); i++) { + System.out.println(node.children.get(i).data); + preOrder(node.children.get(i)); + + } + + } + + public void postOrder() { + this.postOrder(root); + } + + private void postOrder(Node node) { + for (int i = 0; i < node.children.size(); i++) { + + preOrder(node.children.get(i)); + System.out.println(node.children.get(i).data); + + } + System.out.println(root.data); + + } + + public void levelOrder() { + this.levelOrder(root); + } + + private void levelOrder(Node node) { + + } +} + +//CLIENT +public class GenericTreeClient { + + public static void main(String[] args) { + // TODO Auto-generated method stub + // 18 3 64 2 17 0 10 0 27 0 39 1 34 0 + GenericTree tree=new GenericTree(); + Scanner s=new Scanner(System.in); + tree.display(); + System.out.println("\nSize= "+tree.size2()); + System.out.println("\nMax= "+tree.max()); + System.out.println("\nHeight= "+tree.height()); + System.out.println("Enter a number to find: " ); + int find=s.nextInt(); + System.out.println("\nIf "+find+" is present: "+tree.find(find)); + System.out.println("\n-----------Mirror"); + tree.mirror(); + tree.display(); + tree.mirror(); + System.out.println("\n-----------Print At Level 2"); + tree.printLevel(2); + System.out.println("\n-----------Pre Order Display"); + tree.preOrder(); + System.out.println("\n-----------Post Order Display"); + tree.postOrder(); + } + +} + diff --git a/edition/2017/java/Data Structures/Graphs.java b/edition/2017/java/Data Structures/Graphs.java index 6fcf9cf2c..c65daabcd 100644 --- a/edition/2017/java/Data Structures/Graphs.java +++ b/edition/2017/java/Data Structures/Graphs.java @@ -1,145 +1,145 @@ -import java.util.Collection; -import java.util.HashMap; -import java.util.Set; - -public class Graphs { - class Vertex { - String name; - HashMap neighbors; - - Vertex(String name) { - this.name = name; - this.neighbors = new HashMap<>(); - } - - public boolean equals(Object other) { - Vertex ov = (Vertex) other; - return this.name.equals(ov.name); - } - - public int hashCode() { - return this.name.hashCode(); - } - - public void display() { - String rv = ""; - rv = rv + this.name + "=>"; - Set nbrs = this.neighbors.keySet(); - for (Vertex nbr : nbrs) { - rv = rv + nbr.name + "(" + this.neighbors.get(nbr) + "), "; - } - rv = rv + "END"; - System.out.println(rv); - - } - } - - private HashMap vertices; - - Graphs() { - this.vertices = new HashMap<>(); - } - - public int numberOfVertices() { - return this.vertices.size(); - } - - public void addVertex(String name) { - if (this.vertices.containsKey(name)) { - return; - } - Vertex vtx = new Vertex(name); - this.vertices.put(name, vtx); - } - - public void removeVertex(String name) { - if (!this.vertices.containsKey(name)) { - return; - } - Vertex vtx = this.vertices.get(name); - Set nbrs = vtx.neighbors.keySet(); - for (Vertex nbr : nbrs) { - nbr.neighbors.remove(vtx); - } - this.vertices.remove(name); - - } - - public int numberOfEdges() { - int size = 0; - Collection vtces = this.vertices.values(); - for (Vertex vtx : vtces) { - size = size + vtx.neighbors.size(); - } - return size / 2; - - } - - public void addEdge(String v1, String v2, int weight) { - Vertex vtx1 = this.vertices.get(v1); - Vertex vtx2 = this.vertices.get(v2); - if (vtx1 == null || vtx2 == null || vtx1.neighbors.containsKey(vtx2)) - return; - vtx1.neighbors.put(vtx2, weight); - vtx2.neighbors.put(vtx1, weight); - - } - - public void removeEdge(String v1, String v2) { - Vertex vtx1 = this.vertices.get(v1); - Vertex vtx2 = this.vertices.get(v2); - if (vtx1 == null || vtx2 == null || !vtx1.neighbors.containsKey(vtx2)) - return; - vtx1.neighbors.remove(vtx2); - vtx2.neighbors.remove(vtx1); - } - - public void display() { - Set vtces = this.vertices.keySet(); - for (String vtxname : vtces) { - Vertex vtx = this.vertices.get(vtxname); - vtx.display(); - } - System.out.println("------------------------------"); - } - - public boolean hasPathRec(String v1, String v2) { - Vertex vtx1 = this.vertices.get(v1); - Vertex vtx2 = this.vertices.get(v2); - if (vtx1 == null || vtx2 == null) - return false; - HashMap explored = new HashMap<>(); - return this.hasPathRec(vtx1, vtx2, explored); - } - - private boolean hasPathRec(Vertex vtx1, Vertex vtx2, HashMap explored) { - boolean flag; - if (vtx1.neighbors.containsKey(vtx2)) - return true; - if (explored.containsKey(vtx1)) - return false; - explored.put(vtx1, true); - Set nbrs = vtx1.neighbors.keySet(); - for (Vertex nbr : nbrs) { - flag = hasPathRec(nbr, vtx2, explored); - if (flag) - return true; - } - return false; - - } - - public boolean isConnected() { - Set keys = this.vertices.keySet(); - for (String key : keys) { - for (String vtx : keys) - if (!hasPathRec(key, vtx)) { - return false; - } - - } - return true; - - } - -} +import java.util.Collection; +import java.util.HashMap; +import java.util.Set; + +public class Graphs { + class Vertex { + String name; + HashMap neighbors; + + Vertex(String name) { + this.name = name; + this.neighbors = new HashMap<>(); + } + + public boolean equals(Object other) { + Vertex ov = (Vertex) other; + return this.name.equals(ov.name); + } + + public int hashCode() { + return this.name.hashCode(); + } + + public void display() { + String rv = ""; + rv = rv + this.name + "=>"; + Set nbrs = this.neighbors.keySet(); + for (Vertex nbr : nbrs) { + rv = rv + nbr.name + "(" + this.neighbors.get(nbr) + "), "; + } + rv = rv + "END"; + System.out.println(rv); + + } + } + + private HashMap vertices; + + Graphs() { + this.vertices = new HashMap<>(); + } + + public int numberOfVertices() { + return this.vertices.size(); + } + + public void addVertex(String name) { + if (this.vertices.containsKey(name)) { + return; + } + Vertex vtx = new Vertex(name); + this.vertices.put(name, vtx); + } + + public void removeVertex(String name) { + if (!this.vertices.containsKey(name)) { + return; + } + Vertex vtx = this.vertices.get(name); + Set nbrs = vtx.neighbors.keySet(); + for (Vertex nbr : nbrs) { + nbr.neighbors.remove(vtx); + } + this.vertices.remove(name); + + } + + public int numberOfEdges() { + int size = 0; + Collection vtces = this.vertices.values(); + for (Vertex vtx : vtces) { + size = size + vtx.neighbors.size(); + } + return size / 2; + + } + + public void addEdge(String v1, String v2, int weight) { + Vertex vtx1 = this.vertices.get(v1); + Vertex vtx2 = this.vertices.get(v2); + if (vtx1 == null || vtx2 == null || vtx1.neighbors.containsKey(vtx2)) + return; + vtx1.neighbors.put(vtx2, weight); + vtx2.neighbors.put(vtx1, weight); + + } + + public void removeEdge(String v1, String v2) { + Vertex vtx1 = this.vertices.get(v1); + Vertex vtx2 = this.vertices.get(v2); + if (vtx1 == null || vtx2 == null || !vtx1.neighbors.containsKey(vtx2)) + return; + vtx1.neighbors.remove(vtx2); + vtx2.neighbors.remove(vtx1); + } + + public void display() { + Set vtces = this.vertices.keySet(); + for (String vtxname : vtces) { + Vertex vtx = this.vertices.get(vtxname); + vtx.display(); + } + System.out.println("------------------------------"); + } + + public boolean hasPathRec(String v1, String v2) { + Vertex vtx1 = this.vertices.get(v1); + Vertex vtx2 = this.vertices.get(v2); + if (vtx1 == null || vtx2 == null) + return false; + HashMap explored = new HashMap<>(); + return this.hasPathRec(vtx1, vtx2, explored); + } + + private boolean hasPathRec(Vertex vtx1, Vertex vtx2, HashMap explored) { + boolean flag; + if (vtx1.neighbors.containsKey(vtx2)) + return true; + if (explored.containsKey(vtx1)) + return false; + explored.put(vtx1, true); + Set nbrs = vtx1.neighbors.keySet(); + for (Vertex nbr : nbrs) { + flag = hasPathRec(nbr, vtx2, explored); + if (flag) + return true; + } + return false; + + } + + public boolean isConnected() { + Set keys = this.vertices.keySet(); + for (String key : keys) { + for (String vtx : keys) + if (!hasPathRec(key, vtx)) { + return false; + } + + } + return true; + + } + +} diff --git a/edition/2017/java/Data Structures/Stack.java b/edition/2017/java/Data Structures/Stack.java index 40bbcd254..127268689 100644 --- a/edition/2017/java/Data Structures/Stack.java +++ b/edition/2017/java/Data Structures/Stack.java @@ -1,37 +1,37 @@ -public class Stack{ - - int arr[]; - - int size; - - public Stack(int size) { - arr = new int[size]; - this.size = 0; - } - - public boolean isEmpty(){ return size == 0; } - - public int top() throws StackEmptyException{ - if(isEmpty()) - throw new StackEmptyException(); - return arr[size - 1]; - } - - public int size(){ return size; } - - public void push(int element) throws StackFullException { - if(size == arr.length) - throw new StackFullException(); - arr[size++] = element; - } - - public int pop() throws StackEmptyException { - if(isEmpty()) - throw new StackEmptyException(); - return arr[--size]; - } -} - -class StackFullException extends Exception{} - -class StackEmptyException extends Exception{} +public class Stack{ + + int arr[]; + + int size; + + public Stack(int size) { + arr = new int[size]; + this.size = 0; + } + + public boolean isEmpty(){ return size == 0; } + + public int top() throws StackEmptyException{ + if(isEmpty()) + throw new StackEmptyException(); + return arr[size - 1]; + } + + public int size(){ return size; } + + public void push(int element) throws StackFullException { + if(size == arr.length) + throw new StackFullException(); + arr[size++] = element; + } + + public int pop() throws StackEmptyException { + if(isEmpty()) + throw new StackEmptyException(); + return arr[--size]; + } +} + +class StackFullException extends Exception{} + +class StackEmptyException extends Exception{} diff --git a/edition/2017/java/Data Structures/Tries.java b/edition/2017/java/Data Structures/Tries.java index c6f39a91d..ee91050e2 100644 --- a/edition/2017/java/Data Structures/Tries.java +++ b/edition/2017/java/Data Structures/Tries.java @@ -1,98 +1,98 @@ -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -public class Tries { - - private class Node { - Character data; - HashMap children; - boolean isTerminal; - - public Node(Character data, boolean isTerminal) { - this.data = data; - this.children = new HashMap<>(); - this.isTerminal = false; - } - - } - - private int numWords; - private Node root; - - public Tries() { - this.numWords = 0; - this.root = new Node('\0', false); - } - - public int numWords() { - return this.numWords; - } - - public boolean isEmpty() { - return this.numWords() == 0; - } - - public void add(String str) { - this.add(str, root); - } - - private void add(String str, Node parent) { - if (str.length() == 0) { - if (parent.isTerminal) { - } else { - parent.isTerminal = true; - this.numWords++; - - } - return; - } - String ros = str.substring(1); - char cc = str.charAt(0); - Node child = parent.children.get(cc); - if (child == null) { - child = new Node(cc, false); - parent.children.put(cc, child); - this.add(ros, child); - } else { - this.add(ros, parent.children.get(cc)); - - } - } - - public void display() { - this.display(this.root, ""); - } - - private void display(Node node, String osf) { - if (node.isTerminal) { - String toPrint = osf.substring(1) + node.data; - System.out.println(toPrint); - } - Set> entries = node.children.entrySet(); - for (Map.Entry entry : entries) - this.display(entry.getValue(), osf + node.data); - - } - - public boolean search(String str) { - return this.search(str, root); - } - - private boolean search(String str, Node node) { - if (str.length() == 0) { - if (node.isTerminal) - return true; - else - return false; - } - char cc = str.charAt(0); - String ros = str.substring(1); - Node child = node.children.get(cc); - if (child == null) - return false; - return this.search(ros, child); - - } - -} +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class Tries { + + private class Node { + Character data; + HashMap children; + boolean isTerminal; + + public Node(Character data, boolean isTerminal) { + this.data = data; + this.children = new HashMap<>(); + this.isTerminal = false; + } + + } + + private int numWords; + private Node root; + + public Tries() { + this.numWords = 0; + this.root = new Node('\0', false); + } + + public int numWords() { + return this.numWords; + } + + public boolean isEmpty() { + return this.numWords() == 0; + } + + public void add(String str) { + this.add(str, root); + } + + private void add(String str, Node parent) { + if (str.length() == 0) { + if (parent.isTerminal) { + } else { + parent.isTerminal = true; + this.numWords++; + + } + return; + } + String ros = str.substring(1); + char cc = str.charAt(0); + Node child = parent.children.get(cc); + if (child == null) { + child = new Node(cc, false); + parent.children.put(cc, child); + this.add(ros, child); + } else { + this.add(ros, parent.children.get(cc)); + + } + } + + public void display() { + this.display(this.root, ""); + } + + private void display(Node node, String osf) { + if (node.isTerminal) { + String toPrint = osf.substring(1) + node.data; + System.out.println(toPrint); + } + Set> entries = node.children.entrySet(); + for (Map.Entry entry : entries) + this.display(entry.getValue(), osf + node.data); + + } + + public boolean search(String str) { + return this.search(str, root); + } + + private boolean search(String str, Node node) { + if (str.length() == 0) { + if (node.isTerminal) + return true; + else + return false; + } + char cc = str.charAt(0); + String ros = str.substring(1); + Node child = node.children.get(cc); + if (child == null) + return false; + return this.search(ros, child); + + } + +} diff --git a/edition/2017/java/Search/binary_search.java b/edition/2017/java/Search/binary_search.java index 552c2df3a..6dcc64bf0 100644 --- a/edition/2017/java/Search/binary_search.java +++ b/edition/2017/java/Search/binary_search.java @@ -1,28 +1,28 @@ -public class BinarySearch { - public boolean search(int arr[], int key){ - int low = 0; - int high = arr.length - 1; - int mid, swap; - - for(int i=arr.length-1; i>0; i--) - for(int j=0; j arr[j+1]){===5y4w rhgwsdserd - swap = arr[j]; - arr[j] = arr[j+1]; - arr[j+1] = swap; - } - } - - while(low <= high){ - mid = (low + high) / 2; - - if(arr[mid] == key) - return true; - else if(key > arr[mid]) - low = mid + 1; - else if(key < arr[mid]) - high = mid - 1; - } - return false; - } -} +public class BinarySearch { + public boolean search(int arr[], int key){ + int low = 0; + int high = arr.length - 1; + int mid, swap; + + for(int i=arr.length-1; i>0; i--) + for(int j=0; j arr[j+1]){===5y4w rhgwsdserd + swap = arr[j]; + arr[j] = arr[j+1]; + arr[j+1] = swap; + } + } + + while(low <= high){ + mid = (low + high) / 2; + + if(arr[mid] == key) + return true; + else if(key > arr[mid]) + low = mid + 1; + else if(key < arr[mid]) + high = mid - 1; + } + return false; + } +} diff --git a/edition/2017/java/Search/linear_search(string).java b/edition/2017/java/Search/linear_search(string).java index c304313ae..ba934af39 100644 --- a/edition/2017/java/Search/linear_search(string).java +++ b/edition/2017/java/Search/linear_search(string).java @@ -1,23 +1,23 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ - -/** - * - * @author Solon - */ - public class Search { - - static public Boolean LinearSearch(String[] table,String key) - { - for(int i=0;i Double -divTuple (x, 0) = undefined -divTuple (x, y) = x / y - -{- - - Calcula o somatorio entre dois numeros a e b (a < b). Procure usar alguma funcao pronta sobre listas. - - Ex: somatorio 0 1 = 1 - - somatorio 1 3 = 6 --} - -somatorio :: Double -> Double -> Double -somatorio a b = sum [a..b] - -{- - - Calcula o somatorio (recursivo) entre dois numeros a e b (a < b). - - Ex: somatorio 0 1 = 1 - - somatorio 1 3 = 6 --} -somatorioRec :: Double -> Double -> Double -somatorioRec a b | a == b = a - | otherwise = a + somatorioRec (a + 1) b - --- Defina a funcao que eleva um membro ao quadrado -square :: Int -> Int -square x = x * x - --- Soma os quadrados de dois numeros. -sumSquares :: Int -> Int -> Int -sumSquares x y = (square x) + (square y) - --- Defina uma funcao de alta ordem que aceita uma função (Int -> Int) e aplica a funcao a dois numeros -higherOrderSum :: (Int -> Int) -> Int -> Int -> Int -higherOrderSum f a b = (f a) + (f b) - --- Defina a soma dos quadrados em termos de higherOrderSum -hoSumSquares = higherOrderSum square - ---Implemente a funcao mapFilter que primeiro aplica o map de uma funcao f a uma lista e depois aplica a funcao filter --- a lista resultante. Procure usar a composicao de funcoes -mapFilter f p xs = filter p (map f xs) +{- +- Dada uma tupla, divide o primeiro pelo segundo usando pattern matching. +- Ela deve ser indefinida quando o denominador for zero. +-} + +divTuple :: (Double, Double) -> Double +divTuple (x, 0) = undefined +divTuple (x, y) = x / y + +{- + - Calcula o somatorio entre dois numeros a e b (a < b). Procure usar alguma funcao pronta sobre listas. + - Ex: somatorio 0 1 = 1 + - somatorio 1 3 = 6 +-} + +somatorio :: Double -> Double -> Double +somatorio a b = sum [a..b] + +{- + - Calcula o somatorio (recursivo) entre dois numeros a e b (a < b). + - Ex: somatorio 0 1 = 1 + - somatorio 1 3 = 6 +-} +somatorioRec :: Double -> Double -> Double +somatorioRec a b | a == b = a + | otherwise = a + somatorioRec (a + 1) b + +-- Defina a funcao que eleva um membro ao quadrado +square :: Int -> Int +square x = x * x + +-- Soma os quadrados de dois numeros. +sumSquares :: Int -> Int -> Int +sumSquares x y = (square x) + (square y) + +-- Defina uma funcao de alta ordem que aceita uma função (Int -> Int) e aplica a funcao a dois numeros +higherOrderSum :: (Int -> Int) -> Int -> Int -> Int +higherOrderSum f a b = (f a) + (f b) + +-- Defina a soma dos quadrados em termos de higherOrderSum +hoSumSquares = higherOrderSum square + +--Implemente a funcao mapFilter que primeiro aplica o map de uma funcao f a uma lista e depois aplica a funcao filter +-- a lista resultante. Procure usar a composicao de funcoes +mapFilter f p xs = filter p (map f xs) diff --git a/haskell/intro.hs b/haskell/intro.hs index bb646ebcb..d4af0d0e0 100644 --- a/haskell/intro.hs +++ b/haskell/intro.hs @@ -1,95 +1,95 @@ -{- -- Usando os predicados not, and e or prontos de Haskell, implemente os predicados (funcoes) xor (or exclusivo), -- impl (implicacao A => B é equivalente a (not A or B)) e equiv (A <=> B é definido como A => B and B => A) -- Procure usar casamento de padroes e reutilizar as funcoes. --} -xor :: Bool -> Bool -> Bool -xor a b = (a && (not b)) || ((not a) && b) - -impl :: Bool -> Bool -> Bool -impl a b = (not a) || b - -equiv :: Bool -> Bool -> Bool -equiv a b = (impl a b) && (impl b a) - -{- -A funcao square esta implementada e eleva ao quadrado um determinado numero --} - -square :: Integer -> Integer -square x = x * x - -{- -- Implemente a funcao potencia, que retorna o resultado de x elevado a y --} - -pow :: Float -> Float -> Float -pow x 0 = 1 -pow x 1 = x -pow x y | (y > 1) = x * pow x (y-1) - | (y < 0) = 1/(pow x (-y)) - -{- -- Implemente a funcao fatorial que calcula o fatorial de um numero --} - -fatorial :: Int -> Int -fatorial 0 = 1 -fatorial x = x * fatorial (x-1) - -{- -- Determina se um numero eh primo ou nao. Preocupe-se apenas em resolver o problema. -- Nao precisa usar conhecimentos mais sofisticados da teoria dos numeros. Voce pode trabalhar com listas. --} - -isPrime :: Integer -> Bool -isPrime 1 = True -isPrime x = ([1, x] == dividers) - where - dividers = [y | y <- [1..x], (x `mod` y == 0)] - - -{- -- Calcula um termo da sequencia de Fibonnacci. Voce pode trabalhar com listas. --} - -fib :: Integer -> Integer -fib 1 = 1 -fib 2 = 1 -fib x = fib (x-1) + fib (x-2) - -{- -- Calcula um MDC de dois numeros usando o algoritmo de Euclides. --} - -mdc :: Integer -> Integer -> Integer -mdc x 0 = x -mdc 0 y = y -mdc x y | (x > y) = mdc (x-y) y - | otherwise = mdc x (y-x) - -{- -- Calcula um MMC de dois numeros. --} - -mmc :: Integer -> Integer -> Integer -mmc x y = head multiples - where - multiples = [z | z <- [(max x y)..(x*y)], (z `mod` x) == 0, (z `mod` y) == 0] - -{- -- Determina se dois numeros inteiros positivos sao co-primos. Dois numeros sao co-primos se -- o mdc deles for igual a 1. Ex: coprimo 35 64 = True --} - -coprimo :: Integer -> Integer -> Bool -coprimo x y = (mdc x y == 1) - -{- -- Calcula a conjectura de Goldbach, que diz que um numero par maior que 2 pode ser escrito como a soma de dois numeros primos. Ex: 28 = 5 + 23. --} - -goldbach :: Integer -> (Integer, Integer) -goldbach x = head adders - where - adders = [(a,b) | a <- [1..x], b <- [1..x], isPrime a, isPrime b, a + b == x] +{- +- Usando os predicados not, and e or prontos de Haskell, implemente os predicados (funcoes) xor (or exclusivo), +- impl (implicacao A => B é equivalente a (not A or B)) e equiv (A <=> B é definido como A => B and B => A) +- Procure usar casamento de padroes e reutilizar as funcoes. +-} +xor :: Bool -> Bool -> Bool +xor a b = (a && (not b)) || ((not a) && b) + +impl :: Bool -> Bool -> Bool +impl a b = (not a) || b + +equiv :: Bool -> Bool -> Bool +equiv a b = (impl a b) && (impl b a) + +{- +A funcao square esta implementada e eleva ao quadrado um determinado numero +-} + +square :: Integer -> Integer +square x = x * x + +{- +- Implemente a funcao potencia, que retorna o resultado de x elevado a y +-} + +pow :: Float -> Float -> Float +pow x 0 = 1 +pow x 1 = x +pow x y | (y > 1) = x * pow x (y-1) + | (y < 0) = 1/(pow x (-y)) + +{- +- Implemente a funcao fatorial que calcula o fatorial de um numero +-} + +fatorial :: Int -> Int +fatorial 0 = 1 +fatorial x = x * fatorial (x-1) + +{- +- Determina se um numero eh primo ou nao. Preocupe-se apenas em resolver o problema. +- Nao precisa usar conhecimentos mais sofisticados da teoria dos numeros. Voce pode trabalhar com listas. +-} + +isPrime :: Integer -> Bool +isPrime 1 = True +isPrime x = ([1, x] == dividers) + where + dividers = [y | y <- [1..x], (x `mod` y == 0)] + + +{- +- Calcula um termo da sequencia de Fibonnacci. Voce pode trabalhar com listas. +-} + +fib :: Integer -> Integer +fib 1 = 1 +fib 2 = 1 +fib x = fib (x-1) + fib (x-2) + +{- +- Calcula um MDC de dois numeros usando o algoritmo de Euclides. +-} + +mdc :: Integer -> Integer -> Integer +mdc x 0 = x +mdc 0 y = y +mdc x y | (x > y) = mdc (x-y) y + | otherwise = mdc x (y-x) + +{- +- Calcula um MMC de dois numeros. +-} + +mmc :: Integer -> Integer -> Integer +mmc x y = head multiples + where + multiples = [z | z <- [(max x y)..(x*y)], (z `mod` x) == 0, (z `mod` y) == 0] + +{- +- Determina se dois numeros inteiros positivos sao co-primos. Dois numeros sao co-primos se +- o mdc deles for igual a 1. Ex: coprimo 35 64 = True +-} + +coprimo :: Integer -> Integer -> Bool +coprimo x y = (mdc x y == 1) + +{- +- Calcula a conjectura de Goldbach, que diz que um numero par maior que 2 pode ser escrito como a soma de dois numeros primos. Ex: 28 = 5 + 23. +-} + +goldbach :: Integer -> (Integer, Integer) +goldbach x = head adders + where + adders = [(a,b) | a <- [1..x], b <- [1..x], isPrime a, isPrime b, a + b == x] diff --git a/haskell/lambda.hs b/haskell/lambda.hs index c257bea07..7c2cd2a85 100644 --- a/haskell/lambda.hs +++ b/haskell/lambda.hs @@ -1,90 +1,90 @@ ---Exemplos de expressoes lambda -square = \x -> x*x - ---Implemente as funções anteriormente escritas usando expressões lambda ---consulte suas implementacoes anteriores para a documentacao dessas funcoes - -fix :: (a -> a) -> a -fix f = f (fix f) - -pow x y | y < 0 = (\a b -> 1/(pow a (-b))) x y - | y > 0 = (\a b -> a * pow a (b-1)) x y - | otherwise = 1 - -fatorial = \x -> if x == 0 then 1 else x * (fatorial (x-1)) - -isPrime = \x -> [1,x] == [y | y <- [1..x], x `mod` y == 0] - -fib = \x -> if x <= 2 then 1 else (fib (x-1)) + (fib (x-2)) - -mdc x y | x == 0 = y - | y == 0 = x - |otherwise = (\x y -> if x > y then mdc (x-y) y else mdc x (y-x)) x y - -mmc = \x y -> head [z | z <- [(max x y)..(x * y)], z `mod` x == 0, z `mod` y == 0] - -coprimo = \x y -> (mdc x y) == 1 - -goldbach = \x -> head [(a,b)| a <- [1..x], b <- [1..x], isPrime a, isPrime b, a + b == x] - ---Implemente as funções sobre listas escritas previsamente usando expressões lambda ---consulte suas implementacoes anteriores para a documentacao dessas funcoes - -meuLast xs = case xs of [] -> error "Lista vazia!" - (h:t) -> (\h t -> if t == [] then h else meuLast t) h t - -penultimo [] = error "Lista sem penultimo" -penultimo [x] = error "Lista sem penultimo" -penultimo xs = (\i -> meuLast i) (init xs) - -elementAt = \i xs -> if (i == 1) then head xs else elementAt (i-1) (tail xs) - -meuLength = \xs -> case xs of [] -> 0 - (h:t) -> 1 + meuLength t - -meuReverso = \xs -> case xs of [] -> [] - [x] -> [x] - (h:t) -> (meuReverso t) ++ [h] - -isPalindrome :: Eq a => [a] -> Bool -isPalindrome = \xs -> xs == meuReverso xs - -compress :: Eq a => [a] -> [a] -compress = \xs -> case xs of [] -> [] - xs -> if elem (last xs) (init xs) then compress (init xs) else (compress (init xs)) ++ [last xs] - -compact :: Eq a => [a] -> [a] -compact = \xs -> case xs of [] -> [] - [x] -> [x] - (h:t) -> if (elem h t) then [h] ++ [h] ++ (compact (remove h t)) else [h] ++ (compact t) - -remove :: Eq a => a -> [a] -> [a] -remove = \x xs -> case xs of [] -> [] - (h:t) -> if x == h then t else [h] ++ remove x t - -encode :: Eq a => [a] -> [(a,Int)] -encode = \xs -> case xs of [] -> [] - (h:t) -> (h, (length(filter (== h) xs)) ) : encode (filter (/= h) (h:t)) - -split = (\xs i -> [take i xs] ++ [drop i xs]) - -slice = (\xs imin imax -> drop (imin - 1) (take imax xs)) - -insertAt = \el pos (x:xs) -> if pos == 1 then [el] ++ (x:xs) else [x] ++ insertAt el (pos - 1) xs - -sort :: Ord a => [a] -> [a] -sort = \xs -> case xs of [] -> [] - xs -> minimum xs : sort (remove (minimum xs) xs) - -mySum :: ([Int] -> Int) -mySum = \xs -> foldr (+) 0 xs - -maxList = \xs -> if xs == [] then undefined else foldr max 0 xs - - -buildPalindrome = \xs -> if (length xs == 0) then xs else [head xs] ++ (buildPalindrome xs) ++ [head xs] - -mean = \xs -> mySum xs `div` length xs - -myAppend :: ([a] -> [a] -> [a]) +--Exemplos de expressoes lambda +square = \x -> x*x + +--Implemente as funções anteriormente escritas usando expressões lambda +--consulte suas implementacoes anteriores para a documentacao dessas funcoes + +fix :: (a -> a) -> a +fix f = f (fix f) + +pow x y | y < 0 = (\a b -> 1/(pow a (-b))) x y + | y > 0 = (\a b -> a * pow a (b-1)) x y + | otherwise = 1 + +fatorial = \x -> if x == 0 then 1 else x * (fatorial (x-1)) + +isPrime = \x -> [1,x] == [y | y <- [1..x], x `mod` y == 0] + +fib = \x -> if x <= 2 then 1 else (fib (x-1)) + (fib (x-2)) + +mdc x y | x == 0 = y + | y == 0 = x + |otherwise = (\x y -> if x > y then mdc (x-y) y else mdc x (y-x)) x y + +mmc = \x y -> head [z | z <- [(max x y)..(x * y)], z `mod` x == 0, z `mod` y == 0] + +coprimo = \x y -> (mdc x y) == 1 + +goldbach = \x -> head [(a,b)| a <- [1..x], b <- [1..x], isPrime a, isPrime b, a + b == x] + +--Implemente as funções sobre listas escritas previsamente usando expressões lambda +--consulte suas implementacoes anteriores para a documentacao dessas funcoes + +meuLast xs = case xs of [] -> error "Lista vazia!" + (h:t) -> (\h t -> if t == [] then h else meuLast t) h t + +penultimo [] = error "Lista sem penultimo" +penultimo [x] = error "Lista sem penultimo" +penultimo xs = (\i -> meuLast i) (init xs) + +elementAt = \i xs -> if (i == 1) then head xs else elementAt (i-1) (tail xs) + +meuLength = \xs -> case xs of [] -> 0 + (h:t) -> 1 + meuLength t + +meuReverso = \xs -> case xs of [] -> [] + [x] -> [x] + (h:t) -> (meuReverso t) ++ [h] + +isPalindrome :: Eq a => [a] -> Bool +isPalindrome = \xs -> xs == meuReverso xs + +compress :: Eq a => [a] -> [a] +compress = \xs -> case xs of [] -> [] + xs -> if elem (last xs) (init xs) then compress (init xs) else (compress (init xs)) ++ [last xs] + +compact :: Eq a => [a] -> [a] +compact = \xs -> case xs of [] -> [] + [x] -> [x] + (h:t) -> if (elem h t) then [h] ++ [h] ++ (compact (remove h t)) else [h] ++ (compact t) + +remove :: Eq a => a -> [a] -> [a] +remove = \x xs -> case xs of [] -> [] + (h:t) -> if x == h then t else [h] ++ remove x t + +encode :: Eq a => [a] -> [(a,Int)] +encode = \xs -> case xs of [] -> [] + (h:t) -> (h, (length(filter (== h) xs)) ) : encode (filter (/= h) (h:t)) + +split = (\xs i -> [take i xs] ++ [drop i xs]) + +slice = (\xs imin imax -> drop (imin - 1) (take imax xs)) + +insertAt = \el pos (x:xs) -> if pos == 1 then [el] ++ (x:xs) else [x] ++ insertAt el (pos - 1) xs + +sort :: Ord a => [a] -> [a] +sort = \xs -> case xs of [] -> [] + xs -> minimum xs : sort (remove (minimum xs) xs) + +mySum :: ([Int] -> Int) +mySum = \xs -> foldr (+) 0 xs + +maxList = \xs -> if xs == [] then undefined else foldr max 0 xs + + +buildPalindrome = \xs -> if (length xs == 0) then xs else [head xs] ++ (buildPalindrome xs) ++ [head xs] + +mean = \xs -> mySum xs `div` length xs + +myAppend :: ([a] -> [a] -> [a]) myAppend = \xs ys -> foldr (:) ys xs \ No newline at end of file diff --git a/haskell/lists.hs b/haskell/lists.hs index f8ead8a53..2f4961299 100644 --- a/haskell/lists.hs +++ b/haskell/lists.hs @@ -1,137 +1,137 @@ -{- -- Encontra o ultimo elemento de uma lista. Caso a lista seja vazia retorne o seguinte comando: error "Lista vazia!" --} -meuLast [] = error "Lista vazia!" -meuLast [x] = x -meuLast (x:xs) = meuLast xs - -{- -- Encontra o penultimo elemento de uma lista. Caso a lista seja vazia ou tenha apenas um elemento retorne o seguinte comando: error "Lista sem penultimo" --} -penultimo [] = error "Lista sem penultimo" -penultimo [x] = error "Lista sem penultimo" -penultimo xs = meuLast (init xs) - -{- -- Retorna o k-esimo (k varia de 1 ate N) elemento de uma lista. Ex: elementAt 2 [4,7,1,9] = 7 --} -elementAt 1 (x:xs) = x -elementAt i (x:xs) = elementAt (i-1) xs - -{- -- Retorna o tamanho de uma lista. --} - -meuLength [] = 0 -meuLength (x:xs) = 1 + meuLength xs - -{- -- Retorna o inverso de uma lista. --} - -meuReverso [] = [] -meuReverso [x] = [x] -meuReverso (x:xs) = (meuReverso xs) ++ [x] - -{- -- Diz se uma lista é palindrome. --} - -isPalindrome xs = xs == (meuReverso xs) - -{- -- Remove os elementos duplicados de uma lista. Ex: compress [2,5,8,2,1,8] = [2,5,8,1] -- Voce pode usar a funcao elem de Haskell --} - -compress [] = [] -compress xs | elem (last xs) (init xs) = compress (init xs) - | otherwise = (compress (init xs)) ++ [last xs] - -{- -- Varre a lista da esquerda para a direita e junta os elementos iguais. Ex: compact [2,5,8,2,1,8] = [2,2,5,8,8,1] -- Voce pode usar funcoes sobre listas como : (cons), filter, etc. --} - -compact [] = [] -compact [x] = [x] -compact (x:xs) | (elem x xs) = [x] ++ [x] ++ compact (removeFirst x xs) - | otherwise = [x] ++ compact xs - -removeFirst x [] = [] -removeFirst x (y:ys) | (x == y) = ys - | otherwise = [y] ++ removeFirst x ys - - -{- -- Retorna uma lista de pares com os elementos e suas quantidades. Ex: encode [2,2,2,3,4,2,5,2,4,5] = [(2,5),(3,1),(4,2),(5,2)] -- Voce pode usar funcoes sobre listas como : (cons), filter, etc. --} - -encode [] = [] -encode xs = (head xs, length ys) : encode zs - where ys = filter (== (head xs)) xs - zs = filter (/= (head xs)) xs - -{- -- Divide uma lista em duas sublistas onde o ponto de divisao é dado. Ex: split [3,6,1,9,4] 3 = [[3,6,1],[9,4]] --} -split xs i = [take i xs] ++ [drop i xs] - -{- -- Extrai um pedaço (slice) de uma lista especificado por um intervalo. -- Ex: slice [3,6,1,9,4] 2 4 = [6,1,9] --} -slice xs imin imax = drop (imin - 1) (take imax xs) - -{- -- Insere um elemento em uma posicao especifica de uma lista. -- Ex: insertAt 7 4 [3,6,1,9,4] = [3,6,1,7,9,4] --} -insertAt el pos xs | (pos == 1) = [el] ++ xs - | otherwise = [head xs] ++ insertAt el (pos - 1) (tail xs) - -{- -- Ordena uma lista em ordem crescente. Voce deve seguir a ideia do selectionsort onde os elementos -- menores sao trazidos para o inicio da lista um a um. Esta funcao ja esta implementada. --} -minList [x] = x -minList (x:xs) = if (x < (minList xs)) then x else minList xs - -remove e (x:xs) | e == x = xs - | otherwise = x:(remove e xs) -sort [] = [] -sort xs = x:ys - where - x = minList xs - ys = sort (remove x xs) - -{- -- Calcula a soma de todos os elementos de uma lista usando foldr. --} -mySum xs = foldr (+) 0 xs - -{- -- Dada a funcao max que retorna o maximo entre dois numeros, escreva uma funcao que usa a função -- foldr e max para retornar o maximo de uma lista se a lista não é vazia. --} -maxList [] = undefined -maxList xs = foldr max 0 xs - -{- -- Transforma uma string em uma palindrome acrescentando o reverso da string ao seu final sem usar a funcao reverse. -- Ex: buildPalindrome [1,2,3] = [1,2,3,3,2,1]. --} - -buildPalindrome [] = [] -buildPalindrome (x:xs) = [x] ++ buildPalindrome xs ++ [x] - -{- -- Computa a media dos elementos de uma lista de numeros, sem usar nenhuma funcao pronta de listas. --} -mean xs = (mySum xs) / (meuLength xs) - -{- -- Escreva a funcao myAppend que faz o append de uma lista xs com a lista ys, usando a função foldr. --} +{- +- Encontra o ultimo elemento de uma lista. Caso a lista seja vazia retorne o seguinte comando: error "Lista vazia!" +-} +meuLast [] = error "Lista vazia!" +meuLast [x] = x +meuLast (x:xs) = meuLast xs + +{- +- Encontra o penultimo elemento de uma lista. Caso a lista seja vazia ou tenha apenas um elemento retorne o seguinte comando: error "Lista sem penultimo" +-} +penultimo [] = error "Lista sem penultimo" +penultimo [x] = error "Lista sem penultimo" +penultimo xs = meuLast (init xs) + +{- +- Retorna o k-esimo (k varia de 1 ate N) elemento de uma lista. Ex: elementAt 2 [4,7,1,9] = 7 +-} +elementAt 1 (x:xs) = x +elementAt i (x:xs) = elementAt (i-1) xs + +{- +- Retorna o tamanho de uma lista. +-} + +meuLength [] = 0 +meuLength (x:xs) = 1 + meuLength xs + +{- +- Retorna o inverso de uma lista. +-} + +meuReverso [] = [] +meuReverso [x] = [x] +meuReverso (x:xs) = (meuReverso xs) ++ [x] + +{- +- Diz se uma lista é palindrome. +-} + +isPalindrome xs = xs == (meuReverso xs) + +{- +- Remove os elementos duplicados de uma lista. Ex: compress [2,5,8,2,1,8] = [2,5,8,1] +- Voce pode usar a funcao elem de Haskell +-} + +compress [] = [] +compress xs | elem (last xs) (init xs) = compress (init xs) + | otherwise = (compress (init xs)) ++ [last xs] + +{- +- Varre a lista da esquerda para a direita e junta os elementos iguais. Ex: compact [2,5,8,2,1,8] = [2,2,5,8,8,1] +- Voce pode usar funcoes sobre listas como : (cons), filter, etc. +-} + +compact [] = [] +compact [x] = [x] +compact (x:xs) | (elem x xs) = [x] ++ [x] ++ compact (removeFirst x xs) + | otherwise = [x] ++ compact xs + +removeFirst x [] = [] +removeFirst x (y:ys) | (x == y) = ys + | otherwise = [y] ++ removeFirst x ys + + +{- +- Retorna uma lista de pares com os elementos e suas quantidades. Ex: encode [2,2,2,3,4,2,5,2,4,5] = [(2,5),(3,1),(4,2),(5,2)] +- Voce pode usar funcoes sobre listas como : (cons), filter, etc. +-} + +encode [] = [] +encode xs = (head xs, length ys) : encode zs + where ys = filter (== (head xs)) xs + zs = filter (/= (head xs)) xs + +{- +- Divide uma lista em duas sublistas onde o ponto de divisao é dado. Ex: split [3,6,1,9,4] 3 = [[3,6,1],[9,4]] +-} +split xs i = [take i xs] ++ [drop i xs] + +{- +- Extrai um pedaço (slice) de uma lista especificado por um intervalo. +- Ex: slice [3,6,1,9,4] 2 4 = [6,1,9] +-} +slice xs imin imax = drop (imin - 1) (take imax xs) + +{- +- Insere um elemento em uma posicao especifica de uma lista. +- Ex: insertAt 7 4 [3,6,1,9,4] = [3,6,1,7,9,4] +-} +insertAt el pos xs | (pos == 1) = [el] ++ xs + | otherwise = [head xs] ++ insertAt el (pos - 1) (tail xs) + +{- +- Ordena uma lista em ordem crescente. Voce deve seguir a ideia do selectionsort onde os elementos +- menores sao trazidos para o inicio da lista um a um. Esta funcao ja esta implementada. +-} +minList [x] = x +minList (x:xs) = if (x < (minList xs)) then x else minList xs + +remove e (x:xs) | e == x = xs + | otherwise = x:(remove e xs) +sort [] = [] +sort xs = x:ys + where + x = minList xs + ys = sort (remove x xs) + +{- +- Calcula a soma de todos os elementos de uma lista usando foldr. +-} +mySum xs = foldr (+) 0 xs + +{- +- Dada a funcao max que retorna o maximo entre dois numeros, escreva uma funcao que usa a função +- foldr e max para retornar o maximo de uma lista se a lista não é vazia. +-} +maxList [] = undefined +maxList xs = foldr max 0 xs + +{- +- Transforma uma string em uma palindrome acrescentando o reverso da string ao seu final sem usar a funcao reverse. +- Ex: buildPalindrome [1,2,3] = [1,2,3,3,2,1]. +-} + +buildPalindrome [] = [] +buildPalindrome (x:xs) = [x] ++ buildPalindrome xs ++ [x] + +{- +- Computa a media dos elementos de uma lista de numeros, sem usar nenhuma funcao pronta de listas. +-} +mean xs = (mySum xs) / (meuLength xs) + +{- +- Escreva a funcao myAppend que faz o append de uma lista xs com a lista ys, usando a função foldr. +-} myAppend xs ys = foldr (:) ys xs \ No newline at end of file diff --git a/haskell/splitArray.hs b/haskell/splitArray.hs index 60ec38ace..3cfd4cb6a 100644 --- a/haskell/splitArray.hs +++ b/haskell/splitArray.hs @@ -1,5 +1,5 @@ --- split an array of Strings into two separate arrays of Strings -splitArray :: [String] -> ([String], [String]) -splitArray [] = ([], []) -splitArray (x:xs) = (x:odd, even) +-- split an array of Strings into two separate arrays of Strings +splitArray :: [String] -> ([String], [String]) +splitArray [] = ([], []) +splitArray (x:xs) = (x:odd, even) where (even, odd) = splitArray xs \ No newline at end of file diff --git a/haskell/tipos-de-dados.hs b/haskell/tipos-de-dados.hs index 70451c0fa..dd818b152 100644 --- a/haskell/tipos-de-dados.hs +++ b/haskell/tipos-de-dados.hs @@ -1,191 +1,191 @@ ---Escreva a declaracao para o tipo Triple, contendo tres elementos, todos de tipos diferentes. ---Escreva funcoes tripleFst, tripleSnd, tripleThr para extrair respectivamente o primeiro, segundo e terceiro --- elementos de uma triple. -data Triple a b c = Triple a b c deriving (Eq,Show) - -tripleFst (Triple a _ _) = a -tripleSnd (Triple _ b _) = b -tripleThr (Triple _ _ c) = c - ---Escreva um tipo Quadruple que contem 4 elementos: dois de um mesmo tipo e outros dois de outro tipo ---Escreva as funcoes frstTwo e secondTwo que retornam os dois primeiros e os dois ultimos, respectivamente -data Quadruple a b = Quadruple a a b b - -firstTwo (Quadruple a b _ _) = (a,b) -secondTwo (Quadruple _ _ c d) = (c,d) - ---Escreva um tipo de dados que pode conter um, dois, tres ou quatro elementos, dependendo do construtor ---Implemente funções tuple1 até tuple4 que que retornam Just ou Nothing se o valor nao existe -data Tuple a b c d = Tuple1 a | Tuple2 a b | Tuple3 a b c | Tuple4 a b c d deriving (Eq,Show) - -tuple1 (Tuple1 a) = Just a -tuple1 (Tuple2 a _) = Just a -tuple1 (Tuple3 a _ _) = Just a -tuple1 (Tuple4 a _ _ _) = Just a - -tuple2 (Tuple2 _ b) = Just b -tuple2 (Tuple3 _ b _) = Just b -tuple2 (Tuple4 _ b _ _) = Just b -tuple2 _ = Nothing - -tuple3 (Tuple3 _ _ c) = Just c -tuple3 (Tuple4 _ _ c _) = Just c -tuple3 _ = Nothing - -tuple4 (Tuple4 _ _ _ d) = Just d -tuple4 _ = Nothing - -data List a = Nil | Cons a (List a) deriving (Eq,Show) - -listLength Nil = 0 -listLength (Cons x xs) = 1 + listLength xs - -listHead Nil = error "Empty list" -listHead (Cons x xs) = x - -listTail Nil = Nil -listTail (Cons x xs) = xs - -listFoldr f v Nil = v -listFoldr f v (Cons x xs) = f x (listFoldr f v xs) - - -listFoldl f v Nil = v -listFoldl f v (Cons x xs) = listFoldl f (f v x) xs - ---Escreva as funcoes sobre a estrutura de dados binary tree -data BinaryTree a = NIL | Node a (BinaryTree a) (BinaryTree a) - deriving (Eq,Show) - -sizeBST NIL = 0 -sizeBST (Node a left right) = 1 + sizeBST left + sizeBST right - -getValue NIL = Nothing -getValue (Node a _ _) = Just a - -getLeft NIL = NIL -getLeft (Node _ left _) = left - -getRight NIL = NIL -getRight (Node _ _ right) = right - -getParent _ NIL = NIL -getParent x (Node a left right) | (Just x == getValue left) || (Just x == getValue right) = (Node a left right) - | (x < a) = getParent x left - | otherwise = getParent x right - ---verifica se uma BT é uma BST -isBST NIL = True -isBST (Node a left right) | (getValue left /= Nothing) && (getValue left > Just a) = False - | (getValue right /= Nothing) && (Just a > getValue right) = False - | otherwise = (isBST left) && (isBST right) - ---insere uma nova chave na BST retornando a BST modificada -insert x NIL = Node x NIL NIL -insert x (Node a left right) | (x < a) = Node a (insert x left) right - | otherwise = Node a left (insert x right) - ---retorna o Node da BST contendo o dado procurado ou entao NIL -search x NIL = NIL -search x (Node a left right) | (x == a) = Node a left right - | (x < a) = search x left - | otherwise = search x right - ---retorna o elemento maximo da BST -myMaximum NIL = Nothing -myMaximum (Node a left right) | (right == NIL) = Just a - | otherwise = myMaximum right - ---retorna o elemento minimo da BST -myMinimum NIL = Nothing -myMinimum (Node a left right) | (left == NIL) = Just a - | otherwise = myMinimum left - ---retorna o predecessor de um elemento da BST, caso o elemento esteja na BST -predecessor x (Node a b c) | (node == NIL) = Nothing - | (getLeft node == NIL) = firstParentRight node bst - | otherwise = myMaximum (getLeft node) - where - node = search x bst - bst = (Node a b c) - -firstParentRight (Node x left right) (Node a b c) | (parent /= NIL) && (getLeft parent == son) = firstParentRight parent bst - | otherwise = getValue parent - where - parent = getParent x bst - son = (Node x left right) - bst = (Node a b c) - ---retorna o sucessor de um elemento da BST, caso o elemento esteja na BST -successor x (Node a b c) | (node == NIL) = Nothing - | (getRight node == NIL) = firstParentLeft node bst - | otherwise = myMinimum (getRight node) - where - node = search x bst - bst = (Node a b c) - -firstParentLeft (Node x left right) (Node a b c) | (parent /= NIL) && (getRight parent == son) = firstParentLeft parent bst - | otherwise = getValue parent - where - parent = getParent x bst - son = (Node x left right) - bst = (Node a b c) - ---remove um elemento da BST - --- **Auxiliar para converter Maybe em Int -toInt Nothing = 0 -toInt (Just x) = x - --- **Verificar se o valor existe na árvore -remove x (Node a b c) = if (search x (Node a b c)) /= NIL then treeRemove x ((Node a b c)) else (Node a b c) - --- **Verificar se encontrou o nó a ser removido -treeRemove x (Node a left right) | (l == Just x) = treeRemoveAux left parent - | (r == Just x) = treeRemoveAux right parent - | (x == a) = treeRemoveAux parent NIL - | (x < a) = (Node a (treeRemove x left) right) - | otherwise = (Node a left (treeRemove x right)) - where - l = getValue left - r = getValue right - parent = (Node a left right) - --- **Nó folha - -treeRemoveAux (Node x NIL NIL) (Node a left right) | (getValue left == Just x) = (Node a NIL right) - | otherwise = (Node a left NIL) - --- **Nó raiz com um filho -treeRemoveAux (Node x left NIL) NIL = left -treeRemoveAux (Node x NIL right) NIL = right - --- **Nó não-raiz com um filho -treeRemoveAux (Node x y NIL) (Node a left right) | left == (Node x y NIL) = (Node a y right) - | otherwise = (Node a left y) - -treeRemoveAux (Node x NIL z) (Node a left right) | left == (Node x NIL z) = (Node a z right) - | otherwise = (Node a left z) - --- **Nó com dois filhos -treeRemoveAux (Node x y z) (Node a b c) | b == child = (Node newA (Node next (getLeft newB) (getRight newB)) newC) - | otherwise = (Node newA newB (Node next (getLeft newC) (getRight newC))) - where - child = (Node x y z) - parent = (Node a b c) - next = toInt (successor x parent) - newParent = treeRemove next parent - newA = toInt (getValue newParent) - newB = getLeft newParent - newC = getRight newParent - ---retorna uma lista com os dados da BST nos diversos tipos de caminhamento -preOrder NIL = [] -preOrder (Node x left right) = [x] ++ (preOrder left) ++ (preOrder right) - - -order NIL = [] -order (Node x left right) = (order left) ++ [x] ++ (order right) - -postOrder NIL = [] -postOrder (Node x left right) = (postOrder left) ++ (postOrder right) ++ [x] +--Escreva a declaracao para o tipo Triple, contendo tres elementos, todos de tipos diferentes. +--Escreva funcoes tripleFst, tripleSnd, tripleThr para extrair respectivamente o primeiro, segundo e terceiro +-- elementos de uma triple. +data Triple a b c = Triple a b c deriving (Eq,Show) + +tripleFst (Triple a _ _) = a +tripleSnd (Triple _ b _) = b +tripleThr (Triple _ _ c) = c + +--Escreva um tipo Quadruple que contem 4 elementos: dois de um mesmo tipo e outros dois de outro tipo +--Escreva as funcoes frstTwo e secondTwo que retornam os dois primeiros e os dois ultimos, respectivamente +data Quadruple a b = Quadruple a a b b + +firstTwo (Quadruple a b _ _) = (a,b) +secondTwo (Quadruple _ _ c d) = (c,d) + +--Escreva um tipo de dados que pode conter um, dois, tres ou quatro elementos, dependendo do construtor +--Implemente funções tuple1 até tuple4 que que retornam Just ou Nothing se o valor nao existe +data Tuple a b c d = Tuple1 a | Tuple2 a b | Tuple3 a b c | Tuple4 a b c d deriving (Eq,Show) + +tuple1 (Tuple1 a) = Just a +tuple1 (Tuple2 a _) = Just a +tuple1 (Tuple3 a _ _) = Just a +tuple1 (Tuple4 a _ _ _) = Just a + +tuple2 (Tuple2 _ b) = Just b +tuple2 (Tuple3 _ b _) = Just b +tuple2 (Tuple4 _ b _ _) = Just b +tuple2 _ = Nothing + +tuple3 (Tuple3 _ _ c) = Just c +tuple3 (Tuple4 _ _ c _) = Just c +tuple3 _ = Nothing + +tuple4 (Tuple4 _ _ _ d) = Just d +tuple4 _ = Nothing + +data List a = Nil | Cons a (List a) deriving (Eq,Show) + +listLength Nil = 0 +listLength (Cons x xs) = 1 + listLength xs + +listHead Nil = error "Empty list" +listHead (Cons x xs) = x + +listTail Nil = Nil +listTail (Cons x xs) = xs + +listFoldr f v Nil = v +listFoldr f v (Cons x xs) = f x (listFoldr f v xs) + + +listFoldl f v Nil = v +listFoldl f v (Cons x xs) = listFoldl f (f v x) xs + +--Escreva as funcoes sobre a estrutura de dados binary tree +data BinaryTree a = NIL | Node a (BinaryTree a) (BinaryTree a) + deriving (Eq,Show) + +sizeBST NIL = 0 +sizeBST (Node a left right) = 1 + sizeBST left + sizeBST right + +getValue NIL = Nothing +getValue (Node a _ _) = Just a + +getLeft NIL = NIL +getLeft (Node _ left _) = left + +getRight NIL = NIL +getRight (Node _ _ right) = right + +getParent _ NIL = NIL +getParent x (Node a left right) | (Just x == getValue left) || (Just x == getValue right) = (Node a left right) + | (x < a) = getParent x left + | otherwise = getParent x right + +--verifica se uma BT é uma BST +isBST NIL = True +isBST (Node a left right) | (getValue left /= Nothing) && (getValue left > Just a) = False + | (getValue right /= Nothing) && (Just a > getValue right) = False + | otherwise = (isBST left) && (isBST right) + +--insere uma nova chave na BST retornando a BST modificada +insert x NIL = Node x NIL NIL +insert x (Node a left right) | (x < a) = Node a (insert x left) right + | otherwise = Node a left (insert x right) + +--retorna o Node da BST contendo o dado procurado ou entao NIL +search x NIL = NIL +search x (Node a left right) | (x == a) = Node a left right + | (x < a) = search x left + | otherwise = search x right + +--retorna o elemento maximo da BST +myMaximum NIL = Nothing +myMaximum (Node a left right) | (right == NIL) = Just a + | otherwise = myMaximum right + +--retorna o elemento minimo da BST +myMinimum NIL = Nothing +myMinimum (Node a left right) | (left == NIL) = Just a + | otherwise = myMinimum left + +--retorna o predecessor de um elemento da BST, caso o elemento esteja na BST +predecessor x (Node a b c) | (node == NIL) = Nothing + | (getLeft node == NIL) = firstParentRight node bst + | otherwise = myMaximum (getLeft node) + where + node = search x bst + bst = (Node a b c) + +firstParentRight (Node x left right) (Node a b c) | (parent /= NIL) && (getLeft parent == son) = firstParentRight parent bst + | otherwise = getValue parent + where + parent = getParent x bst + son = (Node x left right) + bst = (Node a b c) + +--retorna o sucessor de um elemento da BST, caso o elemento esteja na BST +successor x (Node a b c) | (node == NIL) = Nothing + | (getRight node == NIL) = firstParentLeft node bst + | otherwise = myMinimum (getRight node) + where + node = search x bst + bst = (Node a b c) + +firstParentLeft (Node x left right) (Node a b c) | (parent /= NIL) && (getRight parent == son) = firstParentLeft parent bst + | otherwise = getValue parent + where + parent = getParent x bst + son = (Node x left right) + bst = (Node a b c) + +--remove um elemento da BST + +-- **Auxiliar para converter Maybe em Int +toInt Nothing = 0 +toInt (Just x) = x + +-- **Verificar se o valor existe na árvore +remove x (Node a b c) = if (search x (Node a b c)) /= NIL then treeRemove x ((Node a b c)) else (Node a b c) + +-- **Verificar se encontrou o nó a ser removido +treeRemove x (Node a left right) | (l == Just x) = treeRemoveAux left parent + | (r == Just x) = treeRemoveAux right parent + | (x == a) = treeRemoveAux parent NIL + | (x < a) = (Node a (treeRemove x left) right) + | otherwise = (Node a left (treeRemove x right)) + where + l = getValue left + r = getValue right + parent = (Node a left right) + +-- **Nó folha + +treeRemoveAux (Node x NIL NIL) (Node a left right) | (getValue left == Just x) = (Node a NIL right) + | otherwise = (Node a left NIL) + +-- **Nó raiz com um filho +treeRemoveAux (Node x left NIL) NIL = left +treeRemoveAux (Node x NIL right) NIL = right + +-- **Nó não-raiz com um filho +treeRemoveAux (Node x y NIL) (Node a left right) | left == (Node x y NIL) = (Node a y right) + | otherwise = (Node a left y) + +treeRemoveAux (Node x NIL z) (Node a left right) | left == (Node x NIL z) = (Node a z right) + | otherwise = (Node a left z) + +-- **Nó com dois filhos +treeRemoveAux (Node x y z) (Node a b c) | b == child = (Node newA (Node next (getLeft newB) (getRight newB)) newC) + | otherwise = (Node newA newB (Node next (getLeft newC) (getRight newC))) + where + child = (Node x y z) + parent = (Node a b c) + next = toInt (successor x parent) + newParent = treeRemove next parent + newA = toInt (getValue newParent) + newB = getLeft newParent + newC = getRight newParent + +--retorna uma lista com os dados da BST nos diversos tipos de caminhamento +preOrder NIL = [] +preOrder (Node x left right) = [x] ++ (preOrder left) ++ (preOrder right) + + +order NIL = [] +order (Node x left right) = (order left) ++ [x] ++ (order right) + +postOrder NIL = [] +postOrder (Node x left right) = (postOrder left) ++ (postOrder right) ++ [x] diff --git a/inerpolation_string.cpp b/inerpolation_string.cpp index c3111a345..7e76cd758 100644 --- a/inerpolation_string.cpp +++ b/inerpolation_string.cpp @@ -1,30 +1,30 @@ -#include -#include -#include -using namespace std; -int main() -{ - string st1 = "ROHIT"; - string arr[] = {"AMAR" , "AMARJEET", "BHEEM" , "BIMAL" , "CHAND" ,"CHARU", "DEV" , "DHAWAN","ESHA","GANESH" , "ROHIT" , "ZAHID"}; - int l = (int)(arr[0].at(0)); - int h = (int)(arr[11].at(0)); - int x = (int)(st1.at(0)); - int low =0 , hi = 11 , pos=0; - while(x<=h && x >=l && l st1) - hi = pos-1; - else - low = pos +1; - } - } - return 0 ; -} +#include +#include +#include +using namespace std; +int main() +{ + string st1 = "ROHIT"; + string arr[] = {"AMAR" , "AMARJEET", "BHEEM" , "BIMAL" , "CHAND" ,"CHARU", "DEV" , "DHAWAN","ESHA","GANESH" , "ROHIT" , "ZAHID"}; + int l = (int)(arr[0].at(0)); + int h = (int)(arr[11].at(0)); + int x = (int)(st1.at(0)); + int low =0 , hi = 11 , pos=0; + while(x<=h && x >=l && l st1) + hi = pos-1; + else + low = pos +1; + } + } + return 0 ; +} diff --git a/java/BinarySearchTree/BST.java b/java/BinarySearchTree/BST.java old mode 100755 new mode 100644 index e0e471698..0f1ad199f --- a/java/BinarySearchTree/BST.java +++ b/java/BinarySearchTree/BST.java @@ -1,283 +1,283 @@ -package L21_March11; - - -public class BST { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BST(int[] in) { - this.root = construct(in, 0, in.length - 1); - } - - private Node construct(int[] in, int lo, int hi) { - - if (lo > hi) - return null; - - int mid = (lo + hi) / 2; - - Node nn = new Node(); - nn.data = in[mid]; - this.size++; - - nn.left = construct(in, lo, mid - 1); - nn.right = construct(in, mid + 1, hi); - - return nn; - } - - public void display() { - System.out.println("---------------"); - display(this.root); - System.out.println("---------------"); - } - - private void display(Node node) { - - if (node == null) - return; - - // self work - String str = ""; - - if (node.left == null) { - str += "."; - } else { - str += node.left.data; - } - - str += " => " + node.data + " <= "; - - if (node.right == null) { - str += "."; - } else { - str += node.right.data; - } - - System.out.println(str); - - display(node.left); - display(node.right); - } - - public int size() { - return this.size; - } - - public int size2() { - return size2(this.root); - } - - private int size2(Node node) { - - if (node == null) - return 0; - - int ls = size2(node.left); - int rs = size2(node.right); - - return ls + rs + 1; - } - - public int max() { - return max(this.root); - } - - private int max(Node node) { - - if (node.right == null) { - return node.data; - } else { - return max(node.right); - } - - } - - public int height() { - return height(this.root); - } - - private int height(Node node) { - - if (node == null) - return -1; - - int lh = height(node.left); - int rh = height(node.right); - - return Math.max(lh, rh) + 1; - } - - public boolean find(int item) { - return find(this.root, item); - } - - private boolean find(Node node, int item) { - - if (node == null) - return false; - - if (item == node.data) { - return true; - } else if (item < node.data) { - return find(node.left, item); - } else { - return find(node.right, item); - } - } - - public void printInRange(int lower, int upper) { - - printInRange(this.root, lower, upper); - } - - private void printInRange(Node node, int lower, int upper) { - - if (node == null) { - return; - } - - if (node.data >= lower && node.data <= upper) { - printInRange(node.left, lower, upper); - System.out.println(node.data); - printInRange(node.right, lower, upper); - } else if (node.data > upper) { - printInRange(node.left, lower, upper); - } else { - printInRange(node.right, lower, upper); - } - } - - public void printDec() { - printDec(this.root); - } - - private void printDec(Node node) { - - if (node == null) - return; - - printDec(node.right); - System.out.println(node.data); - printDec(node.left); - } - - private class HeapMover { - int sum; - } - - public void replaceWithSumOfLarger() { - HeapMover hm = new HeapMover(); - replaceWithSumOfLarger(this.root, hm); - } - - private void replaceWithSumOfLarger(Node node, HeapMover hm) { - - if (node == null) - return; - - replaceWithSumOfLarger(node.right, hm); - - int val = node.data; - node.data = hm.sum; - hm.sum += val; - - replaceWithSumOfLarger(node.left, hm); - - } - - public void add(int item) { - add(this.root, null, false, item); - } - - private void add(Node node, Node parent, boolean ilc, int item) { - - if (node == null) { - Node nn = new Node(); - this.size++; - nn.data = item; - - if (ilc) - parent.left = nn; - else - parent.right = nn; - - return; - } - - if (item < node.data) { - add(node.left, node, true, item); - } else if (item > node.data) { - add(node.right, node, false, item); - } - - } - - public void remove(int item) { - remove(this.root, null, false, item); - } - - private void remove(Node node, Node parent, boolean ilc, int item) { - - if (item < node.data) { - remove(node.left, node, true, item); - } else if (item > node.data) { - remove(node.right, node, false, item); - } else { - if (node.left == null && node.right == null) { - if (ilc) - parent.left = null; - else - parent.right = null; - } - - else if (node.left != null && node.right == null) { - if (ilc) - parent.left = node.left; - else - parent.right = node.left; - } - - else if (node.right != null && node.left == null) { - if (ilc) - parent.left = node.right; - else - parent.right = node.right; - } - - else { - - int max = max(node.left); - node.data = max; - - remove(node.left, node, true, max); - } - } - - } - - public void test() { - - Node n1 = new Node(); - n1.data = 10; - Node n2 = new Node(); - n2.data = 20; - Node n3 = new Node(); - n3.data = 30; - n1.left = n2; - n2.left = n3; - n2 = null; - System.out.println(n1.left.data); - System.out.println(n1.left.left.data); - } - - - -} +package L21_March11; + + +public class BST { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BST(int[] in) { + this.root = construct(in, 0, in.length - 1); + } + + private Node construct(int[] in, int lo, int hi) { + + if (lo > hi) + return null; + + int mid = (lo + hi) / 2; + + Node nn = new Node(); + nn.data = in[mid]; + this.size++; + + nn.left = construct(in, lo, mid - 1); + nn.right = construct(in, mid + 1, hi); + + return nn; + } + + public void display() { + System.out.println("---------------"); + display(this.root); + System.out.println("---------------"); + } + + private void display(Node node) { + + if (node == null) + return; + + // self work + String str = ""; + + if (node.left == null) { + str += "."; + } else { + str += node.left.data; + } + + str += " => " + node.data + " <= "; + + if (node.right == null) { + str += "."; + } else { + str += node.right.data; + } + + System.out.println(str); + + display(node.left); + display(node.right); + } + + public int size() { + return this.size; + } + + public int size2() { + return size2(this.root); + } + + private int size2(Node node) { + + if (node == null) + return 0; + + int ls = size2(node.left); + int rs = size2(node.right); + + return ls + rs + 1; + } + + public int max() { + return max(this.root); + } + + private int max(Node node) { + + if (node.right == null) { + return node.data; + } else { + return max(node.right); + } + + } + + public int height() { + return height(this.root); + } + + private int height(Node node) { + + if (node == null) + return -1; + + int lh = height(node.left); + int rh = height(node.right); + + return Math.max(lh, rh) + 1; + } + + public boolean find(int item) { + return find(this.root, item); + } + + private boolean find(Node node, int item) { + + if (node == null) + return false; + + if (item == node.data) { + return true; + } else if (item < node.data) { + return find(node.left, item); + } else { + return find(node.right, item); + } + } + + public void printInRange(int lower, int upper) { + + printInRange(this.root, lower, upper); + } + + private void printInRange(Node node, int lower, int upper) { + + if (node == null) { + return; + } + + if (node.data >= lower && node.data <= upper) { + printInRange(node.left, lower, upper); + System.out.println(node.data); + printInRange(node.right, lower, upper); + } else if (node.data > upper) { + printInRange(node.left, lower, upper); + } else { + printInRange(node.right, lower, upper); + } + } + + public void printDec() { + printDec(this.root); + } + + private void printDec(Node node) { + + if (node == null) + return; + + printDec(node.right); + System.out.println(node.data); + printDec(node.left); + } + + private class HeapMover { + int sum; + } + + public void replaceWithSumOfLarger() { + HeapMover hm = new HeapMover(); + replaceWithSumOfLarger(this.root, hm); + } + + private void replaceWithSumOfLarger(Node node, HeapMover hm) { + + if (node == null) + return; + + replaceWithSumOfLarger(node.right, hm); + + int val = node.data; + node.data = hm.sum; + hm.sum += val; + + replaceWithSumOfLarger(node.left, hm); + + } + + public void add(int item) { + add(this.root, null, false, item); + } + + private void add(Node node, Node parent, boolean ilc, int item) { + + if (node == null) { + Node nn = new Node(); + this.size++; + nn.data = item; + + if (ilc) + parent.left = nn; + else + parent.right = nn; + + return; + } + + if (item < node.data) { + add(node.left, node, true, item); + } else if (item > node.data) { + add(node.right, node, false, item); + } + + } + + public void remove(int item) { + remove(this.root, null, false, item); + } + + private void remove(Node node, Node parent, boolean ilc, int item) { + + if (item < node.data) { + remove(node.left, node, true, item); + } else if (item > node.data) { + remove(node.right, node, false, item); + } else { + if (node.left == null && node.right == null) { + if (ilc) + parent.left = null; + else + parent.right = null; + } + + else if (node.left != null && node.right == null) { + if (ilc) + parent.left = node.left; + else + parent.right = node.left; + } + + else if (node.right != null && node.left == null) { + if (ilc) + parent.left = node.right; + else + parent.right = node.right; + } + + else { + + int max = max(node.left); + node.data = max; + + remove(node.left, node, true, max); + } + } + + } + + public void test() { + + Node n1 = new Node(); + n1.data = 10; + Node n2 = new Node(); + n2.data = 20; + Node n3 = new Node(); + n3.data = 30; + n1.left = n2; + n2.left = n3; + n2 = null; + System.out.println(n1.left.data); + System.out.println(n1.left.left.data); + } + + + +} diff --git a/java/BinarySearchTree/BSTClient.java b/java/BinarySearchTree/BSTClient.java old mode 100755 new mode 100644 index 804ca3f65..0c3f67ae5 --- a/java/BinarySearchTree/BSTClient.java +++ b/java/BinarySearchTree/BSTClient.java @@ -1,35 +1,35 @@ -package L21_March11; - -import java.util.ArrayList; - - - -public class BSTClient { - - public static void main(String[] args) { - - int[] in = { 10, 20, 30, 40, 50, 60, 70, 80 }; - BST bst = new BST(in); - bst.display(); - - // bst.printInRange(40, 75); - // bst.printDec(); - // bst.replaceWithSumOfLarger(); - // bst.display(); - // bst.add(100); - // bst.add(25); - bst.remove(70); - bst.display(); - // ArrayList> list = new ArrayList<>(); - // list.add(new ArrayList<>()) ; - // list.add(new ArrayList<>()) ; - // list.get(0).add(10) ; - // list.get(1).add(10) ; - // - // - // System.out.println(list); - - // bst.test(); - } - -} +package L21_March11; + +import java.util.ArrayList; + + + +public class BSTClient { + + public static void main(String[] args) { + + int[] in = { 10, 20, 30, 40, 50, 60, 70, 80 }; + BST bst = new BST(in); + bst.display(); + + // bst.printInRange(40, 75); + // bst.printDec(); + // bst.replaceWithSumOfLarger(); + // bst.display(); + // bst.add(100); + // bst.add(25); + bst.remove(70); + bst.display(); + // ArrayList> list = new ArrayList<>(); + // list.add(new ArrayList<>()) ; + // list.add(new ArrayList<>()) ; + // list.get(0).add(10) ; + // list.get(1).add(10) ; + // + // + // System.out.println(list); + + // bst.test(); + } + +} diff --git a/java/GenericTree/GTClient.java b/java/GenericTree/GTClient.java old mode 100755 new mode 100644 index ebcc9567c..69aa6bd3e --- a/java/GenericTree/GTClient.java +++ b/java/GenericTree/GTClient.java @@ -1,36 +1,36 @@ -package L17_March3; - - -public class GTClient { - - public static void main(String[] args) { - - // 10 3 20 2 50 0 60 0 30 0 40 1 55 0 - // 10 3 20 3 50 0 60 0 70 0 30 2 120 0 130 0 40 4 80 0 90 0 100 0 110 0 - // 10 3 20 2 50 0 60 2 100 0 110 2 180 0 190 0 30 0 40 3 70 2 120 0 140 0 80 1 - // 150 1 200 0 90 2 160 0 170 0 - GenericTree tree = new GenericTree(); - tree.display(); - - // System.out.println(tree.find(60)); - // System.out.println(tree.height()); - // System.out.println(tree.size2()); - // System.out.println(tree.max()); - - // tree.mirror(); - // tree.display(); - - tree.preorder(); - // tree.postorder(); - - // tree.traversal(); - - // tree.levelorder(); - // tree.levelorderLW(); - // tree.levelorderZZ(); - - // tree.multiSolver(35); - tree.preorderI(); - } - -} +package L17_March3; + + +public class GTClient { + + public static void main(String[] args) { + + // 10 3 20 2 50 0 60 0 30 0 40 1 55 0 + // 10 3 20 3 50 0 60 0 70 0 30 2 120 0 130 0 40 4 80 0 90 0 100 0 110 0 + // 10 3 20 2 50 0 60 2 100 0 110 2 180 0 190 0 30 0 40 3 70 2 120 0 140 0 80 1 + // 150 1 200 0 90 2 160 0 170 0 + GenericTree tree = new GenericTree(); + tree.display(); + + // System.out.println(tree.find(60)); + // System.out.println(tree.height()); + // System.out.println(tree.size2()); + // System.out.println(tree.max()); + + // tree.mirror(); + // tree.display(); + + tree.preorder(); + // tree.postorder(); + + // tree.traversal(); + + // tree.levelorder(); + // tree.levelorderLW(); + // tree.levelorderZZ(); + + // tree.multiSolver(35); + tree.preorderI(); + } + +} diff --git a/java/GenericTree/GenericTree.java b/java/GenericTree/GenericTree.java old mode 100755 new mode 100644 index 872e5b620..60e97106b --- a/java/GenericTree/GenericTree.java +++ b/java/GenericTree/GenericTree.java @@ -1,437 +1,437 @@ -package L17_March3; - -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.Scanner; - - - -public class GenericTree { - -// private class Node { - int data; - ArrayList children = new ArrayList<>(); - } - - private Node root; - private int size; - - public GenericTree() { - - this.root = takeInput(new Scanner(System.in), null, -1); - } - - public Node takeInput(Scanner scn, Node parent, int ith) { - - // give prompt to user - if (parent == null) { - System.out.println("Enter the value for root node ?"); - } else { - System.out.println("Enter the value for " + ith + " child of " + parent.data); - } - - // take value of node from user - int val = scn.nextInt(); - - // create a new node - Node nn = new Node(); - nn.data = val; - this.size++; - - // prompt for no. of children - System.out.println("No. of children for " + nn.data + " ?"); - int nc = scn.nextInt(); - - // loop on children - for (int i = 0; i < nc; i++) { - - // take input of each child - Node child = takeInput(scn, nn, i); - - // attach child with present node - nn.children.add(child); - } - - return nn; - - } - - public int size() { - return this.size; - } - - public boolean isEmpty() { - return this.size == 0; - } - - public void display() { - - System.out.println("----------------------"); - display(this.root); - System.out.println("----------------------"); - } - - private void display(Node node) { - - String str = node.data + " => "; - - for (int i = 0; i < node.children.size(); i++) { - str += node.children.get(i).data + ", "; - } - - str += "."; - System.out.println(str); - - for (Node child : node.children) { - display(child); - } - - } - - public int size2() { - return size2(this.root); - } - - private int size2(Node node) { - - int cs = 0; - - for (Node child : node.children) { - cs += size2(child); - } - - return cs + 1; - } - - public int max() { - return max(this.root); - } - - private int max(Node node) { - - int sm = node.data; - - for (Node child : node.children) { - - int cm = max(child); - - if (cm > sm) { - sm = cm; - } - } - - return sm; - } - -// public int second_max_byme(){ -// int[] a=new int[this.size2]; -// -// return second_max_byme(this.root,a); -// } -// private int second_max_byme(Node node,int[] a){ -// -// -// -// } - - public boolean find(int item) { - return find(this.root, item); - } - - private boolean find(Node node, int item) { - - if (node.data == item) { - return true; - } - - for (Node child : node.children) { - boolean res = find(child, item); - - if (res) { - return true; - } - } - - return false; - } - - public int height() { - return height(this.root); - } - - private int height(Node node) { - - int sh = -1; - - for (Node child : node.children) { - - int ch = height(child); - - if (ch > sh) { - sh = ch; - } - } - - return sh + 1; - } - - public void mirror() { - mirror(this.root); - } - - private void mirror(Node node) { - - for (Node child : node.children) { - mirror(child); - } - - int left = 0; - int right = node.children.size() - 1; - - while (left < right) { - - Node ln = node.children.get(left); - Node rn = node.children.get(right); - - node.children.set(left, rn); - node.children.set(right, ln); - - left++; - right--; - } - } - - public void preorder() { - - System.out.println("----------------"); - preorder(this.root); - System.out.println("."); - System.out.println("----------------"); - } - - private void preorder(Node node) { - - System.out.print(node.data + " "); - - for (Node child : node.children) { - preorder(child); - } - } - - public void postorder() { - - System.out.println("----------------"); - postorder(this.root); - System.out.println("."); - System.out.println("----------------"); - } - - private void postorder(Node node) { - - for (Node child : node.children) { - postorder(child); - } - - System.out.print(node.data + " "); - } - - public void traversal() { - - System.out.println("----------------"); - traversal(this.root); - System.out.println("."); - System.out.println("----------------"); - } - - private void traversal(Node node) { - - System.out.println("hii " + node.data); - - for (Node child : node.children) { - System.out.println("going towards " + child.data); - traversal(child); - System.out.println("coming back from " + child.data); - } - - System.out.println("bye " + node.data); - } - - public void levelorder() { - - LinkedList queue = new LinkedList<>(); - queue.addLast(this.root); - - while (!queue.isEmpty()) { - - Node rn = queue.removeFirst(); - System.out.println(rn.data); - - for (Node child : rn.children) { - queue.addLast(child); - } - } - - } - - public void levelorderLW() { - - LinkedList primaryq = new LinkedList<>(); - LinkedList helperq = new LinkedList<>(); - primaryq.addLast(this.root); - - while (!primaryq.isEmpty()) { - - Node rn = primaryq.removeFirst(); - System.out.print(rn.data + " "); - - for (Node child : rn.children) { - helperq.addLast(child); - } - - if (primaryq.isEmpty()) { - System.out.println(); - primaryq = helperq; - helperq = new LinkedList<>(); - } - } - - } - - public void levelorderZZ() { - - int c = 0; - LinkedList queue = new LinkedList<>(); - LinkedList stack = new LinkedList<>(); - - queue.addLast(this.root); - - while (!queue.isEmpty()) { - - Node rn = queue.removeFirst(); - System.out.print(rn.data + " "); - - if (c % 2 == 0) { - for (int i = 0; i < rn.children.size(); i++) { - stack.addFirst(rn.children.get(i)); - } - } else { - for (int i = rn.children.size() - 1; i >= 0; i--) { - stack.addFirst(rn.children.get(i)); - } - } - - if (queue.isEmpty()) { - c++; - System.out.println(); - queue = stack; - stack = new LinkedList<>(); - } - } - - } - - public void multiSolver(int item) { - - HeapMover mover = new HeapMover(); - multiSolver(this.root, mover, item, 0); - - System.out.println("Size : " + mover.size); - System.out.println("Height : " + mover.height); - System.out.println("Max : " + mover.max); - System.out.println("Found : " + mover.found); - System.out.println("Pred : " + (mover.predecessor == null ? null : mover.predecessor.data)); - System.out.println("Succ : " + (mover.successor == null ? null : mover.successor.data)); - System.out.println("JL : " + (mover.jl == null ? null : mover.jl.data)); - } - - private void multiSolver(Node node, HeapMover mover, int item, int level) { - - mover.size++; - - if (level > mover.height) { - mover.height = level; - } - - if (node.data > mover.max) { - mover.max = node.data; - } - - if (mover.found == true && mover.successor == null) { - mover.successor = node; - } - - if (node.data == item) { - mover.found = true; - } - - if (mover.found == false) { - mover.predecessor = node; - } - - if (node.data > item) { - - if (mover.jl == null) { - mover.jl = node; - } else { - if (node.data < mover.jl.data) { - mover.jl = node; - } - } - } - for (Node child : node.children) { - multiSolver(child, mover, item, level + 1); - } - - } - - private class HeapMover { - - int size = 0; - int height = 0; - int max = Integer.MIN_VALUE; - boolean found = false; - - Node predecessor; - Node successor; - - Node jl; - } - - private class OrderPair { - Node node; - boolean selfDone; - int childrenDone; - } - - public void preorderI() { - - System.out.println("----------------"); - LinkedList stack = new LinkedList<>(); - OrderPair fp = new OrderPair(); - fp.node = this.root; - stack.addFirst(fp); - - while (!stack.isEmpty()) { - - OrderPair tp = stack.getFirst(); - - if (tp.selfDone == false) { - System.out.print(tp.node.data + " "); - tp.selfDone = true; - } else if (tp.childrenDone < tp.node.children.size()) { - OrderPair np = new OrderPair(); - np.node = tp.node.children.get(tp.childrenDone); - stack.addFirst(np); - - tp.childrenDone++; - - } else { - stack.removeFirst(); - } - - } - System.out.println("."); - System.out.println("----------------"); - } - -} +package L17_March3; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Scanner; + + + +public class GenericTree { + +// private class Node { + int data; + ArrayList children = new ArrayList<>(); + } + + private Node root; + private int size; + + public GenericTree() { + + this.root = takeInput(new Scanner(System.in), null, -1); + } + + public Node takeInput(Scanner scn, Node parent, int ith) { + + // give prompt to user + if (parent == null) { + System.out.println("Enter the value for root node ?"); + } else { + System.out.println("Enter the value for " + ith + " child of " + parent.data); + } + + // take value of node from user + int val = scn.nextInt(); + + // create a new node + Node nn = new Node(); + nn.data = val; + this.size++; + + // prompt for no. of children + System.out.println("No. of children for " + nn.data + " ?"); + int nc = scn.nextInt(); + + // loop on children + for (int i = 0; i < nc; i++) { + + // take input of each child + Node child = takeInput(scn, nn, i); + + // attach child with present node + nn.children.add(child); + } + + return nn; + + } + + public int size() { + return this.size; + } + + public boolean isEmpty() { + return this.size == 0; + } + + public void display() { + + System.out.println("----------------------"); + display(this.root); + System.out.println("----------------------"); + } + + private void display(Node node) { + + String str = node.data + " => "; + + for (int i = 0; i < node.children.size(); i++) { + str += node.children.get(i).data + ", "; + } + + str += "."; + System.out.println(str); + + for (Node child : node.children) { + display(child); + } + + } + + public int size2() { + return size2(this.root); + } + + private int size2(Node node) { + + int cs = 0; + + for (Node child : node.children) { + cs += size2(child); + } + + return cs + 1; + } + + public int max() { + return max(this.root); + } + + private int max(Node node) { + + int sm = node.data; + + for (Node child : node.children) { + + int cm = max(child); + + if (cm > sm) { + sm = cm; + } + } + + return sm; + } + +// public int second_max_byme(){ +// int[] a=new int[this.size2]; +// +// return second_max_byme(this.root,a); +// } +// private int second_max_byme(Node node,int[] a){ +// +// +// +// } + + public boolean find(int item) { + return find(this.root, item); + } + + private boolean find(Node node, int item) { + + if (node.data == item) { + return true; + } + + for (Node child : node.children) { + boolean res = find(child, item); + + if (res) { + return true; + } + } + + return false; + } + + public int height() { + return height(this.root); + } + + private int height(Node node) { + + int sh = -1; + + for (Node child : node.children) { + + int ch = height(child); + + if (ch > sh) { + sh = ch; + } + } + + return sh + 1; + } + + public void mirror() { + mirror(this.root); + } + + private void mirror(Node node) { + + for (Node child : node.children) { + mirror(child); + } + + int left = 0; + int right = node.children.size() - 1; + + while (left < right) { + + Node ln = node.children.get(left); + Node rn = node.children.get(right); + + node.children.set(left, rn); + node.children.set(right, ln); + + left++; + right--; + } + } + + public void preorder() { + + System.out.println("----------------"); + preorder(this.root); + System.out.println("."); + System.out.println("----------------"); + } + + private void preorder(Node node) { + + System.out.print(node.data + " "); + + for (Node child : node.children) { + preorder(child); + } + } + + public void postorder() { + + System.out.println("----------------"); + postorder(this.root); + System.out.println("."); + System.out.println("----------------"); + } + + private void postorder(Node node) { + + for (Node child : node.children) { + postorder(child); + } + + System.out.print(node.data + " "); + } + + public void traversal() { + + System.out.println("----------------"); + traversal(this.root); + System.out.println("."); + System.out.println("----------------"); + } + + private void traversal(Node node) { + + System.out.println("hii " + node.data); + + for (Node child : node.children) { + System.out.println("going towards " + child.data); + traversal(child); + System.out.println("coming back from " + child.data); + } + + System.out.println("bye " + node.data); + } + + public void levelorder() { + + LinkedList queue = new LinkedList<>(); + queue.addLast(this.root); + + while (!queue.isEmpty()) { + + Node rn = queue.removeFirst(); + System.out.println(rn.data); + + for (Node child : rn.children) { + queue.addLast(child); + } + } + + } + + public void levelorderLW() { + + LinkedList primaryq = new LinkedList<>(); + LinkedList helperq = new LinkedList<>(); + primaryq.addLast(this.root); + + while (!primaryq.isEmpty()) { + + Node rn = primaryq.removeFirst(); + System.out.print(rn.data + " "); + + for (Node child : rn.children) { + helperq.addLast(child); + } + + if (primaryq.isEmpty()) { + System.out.println(); + primaryq = helperq; + helperq = new LinkedList<>(); + } + } + + } + + public void levelorderZZ() { + + int c = 0; + LinkedList queue = new LinkedList<>(); + LinkedList stack = new LinkedList<>(); + + queue.addLast(this.root); + + while (!queue.isEmpty()) { + + Node rn = queue.removeFirst(); + System.out.print(rn.data + " "); + + if (c % 2 == 0) { + for (int i = 0; i < rn.children.size(); i++) { + stack.addFirst(rn.children.get(i)); + } + } else { + for (int i = rn.children.size() - 1; i >= 0; i--) { + stack.addFirst(rn.children.get(i)); + } + } + + if (queue.isEmpty()) { + c++; + System.out.println(); + queue = stack; + stack = new LinkedList<>(); + } + } + + } + + public void multiSolver(int item) { + + HeapMover mover = new HeapMover(); + multiSolver(this.root, mover, item, 0); + + System.out.println("Size : " + mover.size); + System.out.println("Height : " + mover.height); + System.out.println("Max : " + mover.max); + System.out.println("Found : " + mover.found); + System.out.println("Pred : " + (mover.predecessor == null ? null : mover.predecessor.data)); + System.out.println("Succ : " + (mover.successor == null ? null : mover.successor.data)); + System.out.println("JL : " + (mover.jl == null ? null : mover.jl.data)); + } + + private void multiSolver(Node node, HeapMover mover, int item, int level) { + + mover.size++; + + if (level > mover.height) { + mover.height = level; + } + + if (node.data > mover.max) { + mover.max = node.data; + } + + if (mover.found == true && mover.successor == null) { + mover.successor = node; + } + + if (node.data == item) { + mover.found = true; + } + + if (mover.found == false) { + mover.predecessor = node; + } + + if (node.data > item) { + + if (mover.jl == null) { + mover.jl = node; + } else { + if (node.data < mover.jl.data) { + mover.jl = node; + } + } + } + for (Node child : node.children) { + multiSolver(child, mover, item, level + 1); + } + + } + + private class HeapMover { + + int size = 0; + int height = 0; + int max = Integer.MIN_VALUE; + boolean found = false; + + Node predecessor; + Node successor; + + Node jl; + } + + private class OrderPair { + Node node; + boolean selfDone; + int childrenDone; + } + + public void preorderI() { + + System.out.println("----------------"); + LinkedList stack = new LinkedList<>(); + OrderPair fp = new OrderPair(); + fp.node = this.root; + stack.addFirst(fp); + + while (!stack.isEmpty()) { + + OrderPair tp = stack.getFirst(); + + if (tp.selfDone == false) { + System.out.print(tp.node.data + " "); + tp.selfDone = true; + } else if (tp.childrenDone < tp.node.children.size()) { + OrderPair np = new OrderPair(); + np.node = tp.node.children.get(tp.childrenDone); + stack.addFirst(np); + + tp.childrenDone++; + + } else { + stack.removeFirst(); + } + + } + System.out.println("."); + System.out.println("----------------"); + } + +} diff --git a/java/Graph/Graph.java b/java/Graph/Graph.java old mode 100755 new mode 100644 index 713b98cd7..bb86fa0c5 --- a/java/Graph/Graph.java +++ b/java/Graph/Graph.java @@ -1,379 +1,379 @@ -package Graph; - -import java.util.ArrayList; -import java.util.HashMap; - - -public class Graph { - - private class Vertex { - HashMap nghbrs = new HashMap<>(); - } - - HashMap vertices = new HashMap<>(); - - public int numVetex() { - return vertices.size(); - } - - public boolean containsVertex(String vname) { - return vertices.containsKey(vname); - } - - public void addVertex(String vname) { - Vertex vtx = new Vertex(); - vertices.put(vname, vtx); - } - - public void removeVertex(String vname) { - - Vertex vtx = vertices.get(vname); - ArrayList nbrnames = new ArrayList<>(vtx.nghbrs.keySet()); - - for (String nbrname : nbrnames) { - - Vertex vtxnbr = vertices.get(nbrname); - vtxnbr.nghbrs.remove(vname); - } - - vertices.remove(vname); - - } - - public int numEdges() { - - ArrayList vnames = new ArrayList<>(vertices.keySet()); - int ans = 0; - - for (String vname : vnames) { - - Vertex vtx = vertices.get(vname); - ans += vtx.nghbrs.size(); - } - - return ans / 2; - } - - public boolean containsEdge(String vname1, String vname2) { - - Vertex vtx1 = vertices.get(vname1); - Vertex vtx2 = vertices.get(vname2); - - if (vtx1 == null || vtx2 == null || !vtx1.nghbrs.containsKey(vname2)) { - return false; - } - - return true; - } - - public void addEdge(String vname1, String vname2, int cost) { - - Vertex vtx1 = vertices.get(vname1); - Vertex vtx2 = vertices.get(vname2); - - if (vtx1 == null || vtx2 == null || vtx1.nghbrs.containsKey(vname2)) { - return; - } - - vtx1.nghbrs.put(vname2, cost); - // vtx2.nghbrs.put(vname1, cost); - } - - public void removeEdge(String vname1, String vname2) { - - Vertex vtx1 = vertices.get(vname1); - Vertex vtx2 = vertices.get(vname2); - - if (vtx1 == null || vtx2 == null || !vtx1.nghbrs.containsKey(vname2)) { - return; - } - - vtx1.nghbrs.remove(vname2); - vtx2.nghbrs.remove(vname1); - } - - public void display() { - - System.out.println("------------------"); - ArrayList vnames = new ArrayList<>(vertices.keySet()); - - for (String vname : vnames) { - - String str = vname + " => "; - - Vertex vtx = vertices.get(vname); - str += vtx.nghbrs; - - System.out.println(str); - } - System.out.println("------------------"); - - } - - // prims -> minimum spanning tree - private class PrimsPair implements Comparable { - - String vname; - String acqVertexName; - Vertex vtx; - int cost; - - @Override - public int compareTo(PrimsPair other) { - return other.cost - this.cost; - } - } - - public Graph prims() { - - // create a mst - Graph mst = new Graph(); - - HeapGeneric heap = new HeapGeneric<>(); - HashMap map = new HashMap<>(); - HashMap processed = new HashMap<>(); - - ArrayList keys = new ArrayList<>(this.vertices.keySet()); - - // make pairs and put in heap - for (String key : keys) { - PrimsPair np = new PrimsPair(); - np.vname = key; - np.vtx = vertices.get(key); - np.cost = Integer.MAX_VALUE; - np.acqVertexName = null; - - heap.add(np); - processed.put(np.vname, true); - map.put(key, np); - } - - // til the heap is not empty keep on doing work - while (!heap.isEmpty()) { - - // remove a pair - PrimsPair rp = heap.remove(); - processed.remove(rp.vname); - - // if acq vertex is null, add a vertx only - if (rp.acqVertexName == null) { - mst.addVertex(rp.vname); - } else { - mst.addVertex(rp.vname); - mst.addEdge(rp.vname, rp.acqVertexName, rp.cost); - } - - // get nbrs - ArrayList nbrs = new ArrayList<>(rp.vtx.nghbrs.keySet()); - - // loop on nbrs - for (String nbr : nbrs) { - - // process only the one which are in heap - if (processed.containsKey(nbr)) { - PrimsPair nbrPair = map.get(nbr); - - // get the old cost - int oc = nbrPair.cost; - int nc = rp.vtx.nghbrs.get(nbr); - - // if new cost is smaller than old cost then update the cost - if (nc < oc) { - nbrPair.cost = nc; - nbrPair.acqVertexName = rp.vname; - - // update the priority in heap - heap.updatePriority(nbrPair); - } - } - } - } - - return mst; - } - - // dijkstra -> single source shortest path, but can't work with -ve weight - // edges - public class DijkstraPair implements Comparable { - - String vname; - String psf; - Vertex vtx; - int cost; - - @Override - public int compareTo(DijkstraPair other) { - return other.cost - this.cost; - } - - @Override - public String toString() { - return this.cost + " via " + this.psf + "\n"; - } - - } - - public HashMap Dijkstra(String src) { - - HashMap map = new HashMap<>(); - HeapGeneric heap = new HeapGeneric<>(); - - // processed will keep track of vertex which are present in heap - HashMap processed = new HashMap<>(); - - // get all the vertex names present in graph - ArrayList keys = new ArrayList<>(this.vertices.keySet()); - - // make pairs and put in heap, with the cost of src vertex as 0 - for (String key : keys) { - DijkstraPair np = new DijkstraPair(); - np.vname = key; - np.vtx = vertices.get(key); - np.psf = ""; - np.cost = Integer.MAX_VALUE; - - // if present key is src, cost of src vertex will be 0 - if (key.equals(src)) { - np.psf = key; - np.cost = 0; - } - - heap.add(np); - map.put(key, np); - - // update the processed, bcz processed was keeping track of nodes which are - // present in heap - processed.put(key, true); - } - - // till the heap is not empty keep on removing pairs - while (!heap.isEmpty()) { - - // remove the pair from heap - DijkstraPair rp = heap.remove(); - - // update the processed hashmap - processed.remove(rp.vname); - - // loop on nbrs - ArrayList nbrs = new ArrayList<>(rp.vtx.nghbrs.keySet()); - - for (String nbr : nbrs) { - - // process only those nbrs which are present in heap - if (processed.containsKey(nbr)) { - DijkstraPair nbrPair = map.get(nbr); - - int oc = nbrPair.cost; - int nc = rp.cost + rp.vtx.nghbrs.get(nbr); - - // if new cost is less than old cost then update the cost - if (nc < oc) { - nbrPair.cost = nc; - nbrPair.psf = rp.psf + nbr; - - // update the priority of the updated node in heap - heap.updatePriority(nbrPair); - } - } - } - } - - return map; - - } - - // bellman ford -> single source shortest path, can work with -ve weight edges, - // but can't work with cycle having -ve weights - public ArrayList getAllEdges() { - - ArrayList ans = new ArrayList<>(); - - ArrayList keys = new ArrayList<>(vertices.keySet()); - - for (String key : keys) { - - Vertex vtx = vertices.get(key); - ArrayList nbrs = new ArrayList<>(vtx.nghbrs.keySet()); - - for (String nbr : nbrs) { - EdgePair ep = new EdgePair(); - ep.vname1 = key; - ep.vname2 = nbr; - ep.cost = vtx.nghbrs.get(nbr); - - ans.add(ep); - } - - } - - return ans; - } - - private class EdgePair { - String vname1; - String vname2; - int cost; - } - - public HashMap BellmanFord(String src) throws Exception { - - HashMap map = new HashMap<>(); - - ArrayList keys = new ArrayList<>(this.vertices.keySet()); - - // put the src vertex with 0 cost, and other vertex with infinity cost - for (String key : keys) { - - map.put(key, Integer.MAX_VALUE); - - // if key equals src then cost will be 0 - if (key.equals(src)) { - map.put(key, 0); - } - - } - - // get all the edges - ArrayList alledges = getAllEdges(); - - // V is total no. of vertex in graph - int V = vertices.size(); - - // relax V-1 times bcz at max two vertex can be at V-1 distance - for (int i = 1; i <= V - 1; i++) { - - // all the edges are relaxed - // relax : if we have discovered an edge from u->v then compare - // if cost(v) > cost(u) + edgecost(u,v) then update the cost of v - // cost(v) = cost(u) + edgecost(u,v) - for (EdgePair edge : alledges) { - - int oc = map.get(edge.vname2); - int nc = map.get(edge.vname1) + edge.cost; - - // update the cost of v, if cost(u) + edgecost(u,v) is less than prev cost of v - if (nc < oc) { - map.put(edge.vname2, nc); - } - } - } - - // if the weights are further reduced after relaxing Vth time then it means -ve - // weight cycle was present - for (EdgePair edge : alledges) { - - int oc = map.get(edge.vname2); - int nc = map.get(edge.vname1) + edge.cost; - - System.out.println(map.get(edge.vname1) + " " + nc); - - // if wt is further reduced then give an exception to user - if (nc < oc) { - throw new Exception("-ve weight cycle"); - } - } - - return map; - } -} +package Graph; + +import java.util.ArrayList; +import java.util.HashMap; + + +public class Graph { + + private class Vertex { + HashMap nghbrs = new HashMap<>(); + } + + HashMap vertices = new HashMap<>(); + + public int numVetex() { + return vertices.size(); + } + + public boolean containsVertex(String vname) { + return vertices.containsKey(vname); + } + + public void addVertex(String vname) { + Vertex vtx = new Vertex(); + vertices.put(vname, vtx); + } + + public void removeVertex(String vname) { + + Vertex vtx = vertices.get(vname); + ArrayList nbrnames = new ArrayList<>(vtx.nghbrs.keySet()); + + for (String nbrname : nbrnames) { + + Vertex vtxnbr = vertices.get(nbrname); + vtxnbr.nghbrs.remove(vname); + } + + vertices.remove(vname); + + } + + public int numEdges() { + + ArrayList vnames = new ArrayList<>(vertices.keySet()); + int ans = 0; + + for (String vname : vnames) { + + Vertex vtx = vertices.get(vname); + ans += vtx.nghbrs.size(); + } + + return ans / 2; + } + + public boolean containsEdge(String vname1, String vname2) { + + Vertex vtx1 = vertices.get(vname1); + Vertex vtx2 = vertices.get(vname2); + + if (vtx1 == null || vtx2 == null || !vtx1.nghbrs.containsKey(vname2)) { + return false; + } + + return true; + } + + public void addEdge(String vname1, String vname2, int cost) { + + Vertex vtx1 = vertices.get(vname1); + Vertex vtx2 = vertices.get(vname2); + + if (vtx1 == null || vtx2 == null || vtx1.nghbrs.containsKey(vname2)) { + return; + } + + vtx1.nghbrs.put(vname2, cost); + // vtx2.nghbrs.put(vname1, cost); + } + + public void removeEdge(String vname1, String vname2) { + + Vertex vtx1 = vertices.get(vname1); + Vertex vtx2 = vertices.get(vname2); + + if (vtx1 == null || vtx2 == null || !vtx1.nghbrs.containsKey(vname2)) { + return; + } + + vtx1.nghbrs.remove(vname2); + vtx2.nghbrs.remove(vname1); + } + + public void display() { + + System.out.println("------------------"); + ArrayList vnames = new ArrayList<>(vertices.keySet()); + + for (String vname : vnames) { + + String str = vname + " => "; + + Vertex vtx = vertices.get(vname); + str += vtx.nghbrs; + + System.out.println(str); + } + System.out.println("------------------"); + + } + + // prims -> minimum spanning tree + private class PrimsPair implements Comparable { + + String vname; + String acqVertexName; + Vertex vtx; + int cost; + + @Override + public int compareTo(PrimsPair other) { + return other.cost - this.cost; + } + } + + public Graph prims() { + + // create a mst + Graph mst = new Graph(); + + HeapGeneric heap = new HeapGeneric<>(); + HashMap map = new HashMap<>(); + HashMap processed = new HashMap<>(); + + ArrayList keys = new ArrayList<>(this.vertices.keySet()); + + // make pairs and put in heap + for (String key : keys) { + PrimsPair np = new PrimsPair(); + np.vname = key; + np.vtx = vertices.get(key); + np.cost = Integer.MAX_VALUE; + np.acqVertexName = null; + + heap.add(np); + processed.put(np.vname, true); + map.put(key, np); + } + + // til the heap is not empty keep on doing work + while (!heap.isEmpty()) { + + // remove a pair + PrimsPair rp = heap.remove(); + processed.remove(rp.vname); + + // if acq vertex is null, add a vertx only + if (rp.acqVertexName == null) { + mst.addVertex(rp.vname); + } else { + mst.addVertex(rp.vname); + mst.addEdge(rp.vname, rp.acqVertexName, rp.cost); + } + + // get nbrs + ArrayList nbrs = new ArrayList<>(rp.vtx.nghbrs.keySet()); + + // loop on nbrs + for (String nbr : nbrs) { + + // process only the one which are in heap + if (processed.containsKey(nbr)) { + PrimsPair nbrPair = map.get(nbr); + + // get the old cost + int oc = nbrPair.cost; + int nc = rp.vtx.nghbrs.get(nbr); + + // if new cost is smaller than old cost then update the cost + if (nc < oc) { + nbrPair.cost = nc; + nbrPair.acqVertexName = rp.vname; + + // update the priority in heap + heap.updatePriority(nbrPair); + } + } + } + } + + return mst; + } + + // dijkstra -> single source shortest path, but can't work with -ve weight + // edges + public class DijkstraPair implements Comparable { + + String vname; + String psf; + Vertex vtx; + int cost; + + @Override + public int compareTo(DijkstraPair other) { + return other.cost - this.cost; + } + + @Override + public String toString() { + return this.cost + " via " + this.psf + "\n"; + } + + } + + public HashMap Dijkstra(String src) { + + HashMap map = new HashMap<>(); + HeapGeneric heap = new HeapGeneric<>(); + + // processed will keep track of vertex which are present in heap + HashMap processed = new HashMap<>(); + + // get all the vertex names present in graph + ArrayList keys = new ArrayList<>(this.vertices.keySet()); + + // make pairs and put in heap, with the cost of src vertex as 0 + for (String key : keys) { + DijkstraPair np = new DijkstraPair(); + np.vname = key; + np.vtx = vertices.get(key); + np.psf = ""; + np.cost = Integer.MAX_VALUE; + + // if present key is src, cost of src vertex will be 0 + if (key.equals(src)) { + np.psf = key; + np.cost = 0; + } + + heap.add(np); + map.put(key, np); + + // update the processed, bcz processed was keeping track of nodes which are + // present in heap + processed.put(key, true); + } + + // till the heap is not empty keep on removing pairs + while (!heap.isEmpty()) { + + // remove the pair from heap + DijkstraPair rp = heap.remove(); + + // update the processed hashmap + processed.remove(rp.vname); + + // loop on nbrs + ArrayList nbrs = new ArrayList<>(rp.vtx.nghbrs.keySet()); + + for (String nbr : nbrs) { + + // process only those nbrs which are present in heap + if (processed.containsKey(nbr)) { + DijkstraPair nbrPair = map.get(nbr); + + int oc = nbrPair.cost; + int nc = rp.cost + rp.vtx.nghbrs.get(nbr); + + // if new cost is less than old cost then update the cost + if (nc < oc) { + nbrPair.cost = nc; + nbrPair.psf = rp.psf + nbr; + + // update the priority of the updated node in heap + heap.updatePriority(nbrPair); + } + } + } + } + + return map; + + } + + // bellman ford -> single source shortest path, can work with -ve weight edges, + // but can't work with cycle having -ve weights + public ArrayList getAllEdges() { + + ArrayList ans = new ArrayList<>(); + + ArrayList keys = new ArrayList<>(vertices.keySet()); + + for (String key : keys) { + + Vertex vtx = vertices.get(key); + ArrayList nbrs = new ArrayList<>(vtx.nghbrs.keySet()); + + for (String nbr : nbrs) { + EdgePair ep = new EdgePair(); + ep.vname1 = key; + ep.vname2 = nbr; + ep.cost = vtx.nghbrs.get(nbr); + + ans.add(ep); + } + + } + + return ans; + } + + private class EdgePair { + String vname1; + String vname2; + int cost; + } + + public HashMap BellmanFord(String src) throws Exception { + + HashMap map = new HashMap<>(); + + ArrayList keys = new ArrayList<>(this.vertices.keySet()); + + // put the src vertex with 0 cost, and other vertex with infinity cost + for (String key : keys) { + + map.put(key, Integer.MAX_VALUE); + + // if key equals src then cost will be 0 + if (key.equals(src)) { + map.put(key, 0); + } + + } + + // get all the edges + ArrayList alledges = getAllEdges(); + + // V is total no. of vertex in graph + int V = vertices.size(); + + // relax V-1 times bcz at max two vertex can be at V-1 distance + for (int i = 1; i <= V - 1; i++) { + + // all the edges are relaxed + // relax : if we have discovered an edge from u->v then compare + // if cost(v) > cost(u) + edgecost(u,v) then update the cost of v + // cost(v) = cost(u) + edgecost(u,v) + for (EdgePair edge : alledges) { + + int oc = map.get(edge.vname2); + int nc = map.get(edge.vname1) + edge.cost; + + // update the cost of v, if cost(u) + edgecost(u,v) is less than prev cost of v + if (nc < oc) { + map.put(edge.vname2, nc); + } + } + } + + // if the weights are further reduced after relaxing Vth time then it means -ve + // weight cycle was present + for (EdgePair edge : alledges) { + + int oc = map.get(edge.vname2); + int nc = map.get(edge.vname1) + edge.cost; + + System.out.println(map.get(edge.vname1) + " " + nc); + + // if wt is further reduced then give an exception to user + if (nc < oc) { + throw new Exception("-ve weight cycle"); + } + } + + return map; + } +} diff --git a/java/Graph/GraphClient.java b/java/Graph/GraphClient.java old mode 100755 new mode 100644 index c0f46d160..d0ff1b148 --- a/java/Graph/GraphClient.java +++ b/java/Graph/GraphClient.java @@ -1,53 +1,53 @@ -package Graph; - - - -public class GraphClient { - - public static void main(String[] args) throws Exception { - - Graph graph = new Graph(); - graph.addVertex("A"); - graph.addVertex("B"); - graph.addVertex("C"); - graph.addVertex("D"); - graph.addVertex("E"); - graph.addVertex("F"); - graph.addVertex("G"); - graph.addEdge("A", "B", 10); - graph.addEdge("A", "D", 40); - graph.addEdge("B", "C", 10); - graph.addEdge("C", "D", 10); - graph.addEdge("D", "E", 5); - graph.addEdge("E", "F", 2); - graph.addEdge("E", "G", 6); - graph.addEdge("F", "G", 3); - - // graph.addEdge("A", "B", 6); - // graph.addEdge("A", "E", 4); - // graph.addEdge("A", "F", 5); - // graph.addEdge("E", "F", -3); - // graph.addEdge("B", "C", 2); - // graph.addEdge("C", "D", 2); - // graph.addEdge("D", "C", 1); - // graph.addEdge("F", "D", 4); - - // graph.addEdge("A", "B", 5); - // graph.addEdge("B", "C", -2); - // graph.addEdge("A", "C", 4); - // - // graph.addEdge("A", "B", 1); - // graph.addEdge("B", "C", 2); - // graph.addEdge("C", "D", 2); - // graph.addEdge("D", "B", 6); - - // graph.display(); - // graph.prims().display(); - - // System.out.println(graph.Dijkstra("A")); - - System.out.println(graph.BellmanFord("A")); - - } - -} +package Graph; + + + +public class GraphClient { + + public static void main(String[] args) throws Exception { + + Graph graph = new Graph(); + graph.addVertex("A"); + graph.addVertex("B"); + graph.addVertex("C"); + graph.addVertex("D"); + graph.addVertex("E"); + graph.addVertex("F"); + graph.addVertex("G"); + graph.addEdge("A", "B", 10); + graph.addEdge("A", "D", 40); + graph.addEdge("B", "C", 10); + graph.addEdge("C", "D", 10); + graph.addEdge("D", "E", 5); + graph.addEdge("E", "F", 2); + graph.addEdge("E", "G", 6); + graph.addEdge("F", "G", 3); + + // graph.addEdge("A", "B", 6); + // graph.addEdge("A", "E", 4); + // graph.addEdge("A", "F", 5); + // graph.addEdge("E", "F", -3); + // graph.addEdge("B", "C", 2); + // graph.addEdge("C", "D", 2); + // graph.addEdge("D", "C", 1); + // graph.addEdge("F", "D", 4); + + // graph.addEdge("A", "B", 5); + // graph.addEdge("B", "C", -2); + // graph.addEdge("A", "C", 4); + // + // graph.addEdge("A", "B", 1); + // graph.addEdge("B", "C", 2); + // graph.addEdge("C", "D", 2); + // graph.addEdge("D", "B", 6); + + // graph.display(); + // graph.prims().display(); + + // System.out.println(graph.Dijkstra("A")); + + System.out.println(graph.BellmanFord("A")); + + } + +} diff --git a/java/Graph/HeapGeneric.java b/java/Graph/HeapGeneric.java old mode 100755 new mode 100644 index d118be3ef..57a5c0cde --- a/java/Graph/HeapGeneric.java +++ b/java/Graph/HeapGeneric.java @@ -1,108 +1,108 @@ -package Graph; - -import java.util.ArrayList; -import java.util.HashMap; - - - -public class HeapGeneric> { - - ArrayList data = new ArrayList<>(); - HashMap map = new HashMap<>(); - - public void add(T item) { - - data.add(item); - map.put(item, this.data.size() - 1); - upheapify(this.data.size() - 1); - } - - private void upheapify(int ci) { - - int pi = (ci - 1) / 2; - - if (isLarger(this.data.get(ci), this.data.get(pi)) > 0) { - swap(pi, ci); - upheapify(pi); - } - - } - - private void swap(int i, int j) { - - T ith = data.get(i); - T jth = data.get(j); - - data.set(i, jth); - data.set(j, ith); - - map.put(ith, j); - map.put(jth, i); - } - - public T remove() { - - swap(0, data.size() - 1); - - T rv = data.remove(data.size() - 1); - map.remove(rv); - downheapify(0); - - return rv; - } - - private void downheapify(int pi) { - - int lci = 2 * pi + 1; - int rci = 2 * pi + 2; - int mini = pi; - - if (lci < this.data.size() && isLarger(data.get(lci), data.get(mini)) > 0) { - mini = lci; - } - - if (rci < this.data.size() && isLarger(data.get(rci), data.get(mini)) > 0) { - mini = rci; - } - - if (mini != pi) { - swap(mini, pi); - downheapify(mini); - } - } - - public T get() { - return this.data.get(0); - } - - public void display() { - System.out.println(data); - } - - public int size() { - return this.data.size(); - } - - public boolean isEmpty() { - return this.size() == 0; - } - - public int isLarger(T t, T o) { - return t.compareTo(o); - } - - public void updatePriority(T nbrPair) { - - // int idx = -1; - // - // for (int i = 0; i < this.data.size(); i++) { - // if (this.data.get(i) == nbrPair) { - // idx = i; - // } - // } - - int idx = map.get(nbrPair); - upheapify(idx); - - } -} +package Graph; + +import java.util.ArrayList; +import java.util.HashMap; + + + +public class HeapGeneric> { + + ArrayList data = new ArrayList<>(); + HashMap map = new HashMap<>(); + + public void add(T item) { + + data.add(item); + map.put(item, this.data.size() - 1); + upheapify(this.data.size() - 1); + } + + private void upheapify(int ci) { + + int pi = (ci - 1) / 2; + + if (isLarger(this.data.get(ci), this.data.get(pi)) > 0) { + swap(pi, ci); + upheapify(pi); + } + + } + + private void swap(int i, int j) { + + T ith = data.get(i); + T jth = data.get(j); + + data.set(i, jth); + data.set(j, ith); + + map.put(ith, j); + map.put(jth, i); + } + + public T remove() { + + swap(0, data.size() - 1); + + T rv = data.remove(data.size() - 1); + map.remove(rv); + downheapify(0); + + return rv; + } + + private void downheapify(int pi) { + + int lci = 2 * pi + 1; + int rci = 2 * pi + 2; + int mini = pi; + + if (lci < this.data.size() && isLarger(data.get(lci), data.get(mini)) > 0) { + mini = lci; + } + + if (rci < this.data.size() && isLarger(data.get(rci), data.get(mini)) > 0) { + mini = rci; + } + + if (mini != pi) { + swap(mini, pi); + downheapify(mini); + } + } + + public T get() { + return this.data.get(0); + } + + public void display() { + System.out.println(data); + } + + public int size() { + return this.data.size(); + } + + public boolean isEmpty() { + return this.size() == 0; + } + + public int isLarger(T t, T o) { + return t.compareTo(o); + } + + public void updatePriority(T nbrPair) { + + // int idx = -1; + // + // for (int i = 0; i < this.data.size(); i++) { + // if (this.data.get(i) == nbrPair) { + // idx = i; + // } + // } + + int idx = map.get(nbrPair); + upheapify(idx); + + } +} diff --git a/java/MergeSort.java b/java/MergeSort.java deleted file mode 100644 index 892bf4513..000000000 --- a/java/MergeSort.java +++ /dev/null @@ -1,72 +0,0 @@ -class Merge{ - int [] a ={1, 5, 10, 8, 11, 12}; - - public void mergeSort(int l, int r){ - int m= (l+r)/2; - if(l>=r){ - return; - } - mergeSort(l,m); - mergeSort(m+1,r); - merge(l, m, r); - } - - - public void merge(int l, int m, int r){ - int n1= m-l+1; - int n2= r-m; - int n3 =n1+n2; - int [] b = new int [n1]; - int[] c =new int [n2]; - for (int i=0; ic[j]) - { - a[k] = c[j]; - j++; - } - else { - a[k]=c[j]; - j++; - i++; - } - k++; - } - while(i - 4.0.0 - - br.edu.ufcg.ccc - submission - 1.0 - jar - Submissao de roteiro - - - - ufcg-leda - http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda - default - - true - always - - - - - - - junit - junit - 4.12 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - maven-clean-plugin - 3.0.0 - - - auto-clean - build - - clean - - - - - - - org.walkmod - maven-walkmod-plugin - 1.3 - - walkmod.xml - - - - package - - apply - - - false - - - - - - br.edu.ufcg.ccc - leda-compactor-tool - 1.0.0-SNAPSHOT - - - install - - compact - - - - 116110761 - - R05-01 - - 2017.1 - http://150.165.85.29:81/submitAtividade - - - - - - - + + 4.0.0 + + br.edu.ufcg.ccc + submission + 1.0 + jar + Submissao de roteiro + + + + ufcg-leda + http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda + default + + true + always + + + + + + + junit + junit + 4.12 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + maven-clean-plugin + 3.0.0 + + + auto-clean + build + + clean + + + + + + + org.walkmod + maven-walkmod-plugin + 1.3 + + walkmod.xml + + + + package + + apply + + + false + + + + + + br.edu.ufcg.ccc + leda-compactor-tool + 1.0.0-SNAPSHOT + + + install + + compact + + + + 116110761 + + R05-01 + + 2017.1 + http://150.165.85.29:81/submitAtividade + + + + + + + diff --git a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/CircularQueue.java b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/CircularQueue.java index 179425a85..cae2e64cc 100644 --- a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/CircularQueue.java +++ b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/CircularQueue.java @@ -1,67 +1,67 @@ -package adt.queue; - -public class CircularQueue implements Queue { - - private T[] array; - private int tail; - private int head; - private int elements; - - @SuppressWarnings("unchecked") - public CircularQueue(int size) { - array = (T[]) new Object[size]; - head = -1; - tail = -1; - elements = 0; - } - - @Override - public void enqueue(T element) throws QueueOverflowException { - if (isEmpty()) { - tail = (tail + 1) % (array.length); - array[tail] = element; - head = (head + 1) % (array.length); - elements++; - } else { - if (isFull()) { - throw new QueueOverflowException(); - } else { - tail = (tail + 1) % (array.length); - array[tail] = element; - elements++; - } - } - } - - @Override - public T dequeue() throws QueueUnderflowException { - if (isEmpty()) { - throw new QueueUnderflowException(); - } else { - T dequeued = array[head]; - head = (head + 1) % (array.length); - elements--; - return dequeued; - } - } - - @Override - public T head() { - T header = null; - if (!(isEmpty())) { - header = array[head]; - } - return header; - } - - @Override - public boolean isEmpty() { - return elements == 0; - } - - @Override - public boolean isFull() { - return elements == array.length; - } - -} +package adt.queue; + +public class CircularQueue implements Queue { + + private T[] array; + private int tail; + private int head; + private int elements; + + @SuppressWarnings("unchecked") + public CircularQueue(int size) { + array = (T[]) new Object[size]; + head = -1; + tail = -1; + elements = 0; + } + + @Override + public void enqueue(T element) throws QueueOverflowException { + if (isEmpty()) { + tail = (tail + 1) % (array.length); + array[tail] = element; + head = (head + 1) % (array.length); + elements++; + } else { + if (isFull()) { + throw new QueueOverflowException(); + } else { + tail = (tail + 1) % (array.length); + array[tail] = element; + elements++; + } + } + } + + @Override + public T dequeue() throws QueueUnderflowException { + if (isEmpty()) { + throw new QueueUnderflowException(); + } else { + T dequeued = array[head]; + head = (head + 1) % (array.length); + elements--; + return dequeued; + } + } + + @Override + public T head() { + T header = null; + if (!(isEmpty())) { + header = array[head]; + } + return header; + } + + @Override + public boolean isEmpty() { + return elements == 0; + } + + @Override + public boolean isFull() { + return elements == array.length; + } + +} diff --git a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/Queue.java b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/Queue.java index 1c476145e..3931971e2 100644 --- a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/Queue.java +++ b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/Queue.java @@ -1,50 +1,50 @@ -package adt.queue; - -/** - * The interface of a generic queue. The queue is able to store any kind of - * data. - * - */ -public interface Queue { - - /** - * Inserts a new element in the queue or returns an exception if the queue - * is full. Null elements are not allowed (the queue remains unchanged). - * - * @param element - * @throws QueueOverflowException - */ - public void enqueue(T element) throws QueueOverflowException; - - /** - * If the queue has elements, it removes the oldest of the queue and returns - * it; otherwise, it returns an exception. - * - * @return - * @throws QueueUnderflowException - */ - public T dequeue() throws QueueUnderflowException; - - /** - * Returns (without removing) the oldest element of the stack or null if the - * queue is empty. - * - * @return - */ - public T head(); - - /** - * Returns true if the queue is empty or false, otherwise. - * - * @return - */ - public boolean isEmpty(); - - /** - * Returns true if the queue is full or false, otherwise. - * - * @return - */ - public boolean isFull(); - -} +package adt.queue; + +/** + * The interface of a generic queue. The queue is able to store any kind of + * data. + * + */ +public interface Queue { + + /** + * Inserts a new element in the queue or returns an exception if the queue + * is full. Null elements are not allowed (the queue remains unchanged). + * + * @param element + * @throws QueueOverflowException + */ + public void enqueue(T element) throws QueueOverflowException; + + /** + * If the queue has elements, it removes the oldest of the queue and returns + * it; otherwise, it returns an exception. + * + * @return + * @throws QueueUnderflowException + */ + public T dequeue() throws QueueUnderflowException; + + /** + * Returns (without removing) the oldest element of the stack or null if the + * queue is empty. + * + * @return + */ + public T head(); + + /** + * Returns true if the queue is empty or false, otherwise. + * + * @return + */ + public boolean isEmpty(); + + /** + * Returns true if the queue is full or false, otherwise. + * + * @return + */ + public boolean isFull(); + +} diff --git a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/QueueImpl.java b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/QueueImpl.java index 13bd917ae..c1d5e0bb5 100644 --- a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/QueueImpl.java +++ b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/QueueImpl.java @@ -1,62 +1,62 @@ -package adt.queue; - -public class QueueImpl implements Queue { - - private T[] array; - private int tail; - - @SuppressWarnings("unchecked") - public QueueImpl(int size) { - array = (T[]) new Object[size]; - tail = -1; - } - - @Override - public T head() { - T head = null; - if (!(isEmpty())) { - head = array[0]; - } - return head; - } - - @Override - public boolean isEmpty() { - return tail == -1; - } - - @Override - public boolean isFull() { - return tail == array.length - 1; - } - - private void shiftLeft() { - for (int i = 0; i < tail; i++) { - array[i] = array[i + 1]; - } - } - - @Override - public void enqueue(T element) throws QueueOverflowException { - if (isFull()) { - throw new QueueOverflowException(); - } else { - tail++; - array[tail] = element; - } - } - - @Override - public T dequeue() throws QueueUnderflowException { - if (isEmpty()) { - throw new QueueUnderflowException(); - } else { - T dequeued = array[0]; - shiftLeft(); - tail--; - return dequeued; - } - - } - -} +package adt.queue; + +public class QueueImpl implements Queue { + + private T[] array; + private int tail; + + @SuppressWarnings("unchecked") + public QueueImpl(int size) { + array = (T[]) new Object[size]; + tail = -1; + } + + @Override + public T head() { + T head = null; + if (!(isEmpty())) { + head = array[0]; + } + return head; + } + + @Override + public boolean isEmpty() { + return tail == -1; + } + + @Override + public boolean isFull() { + return tail == array.length - 1; + } + + private void shiftLeft() { + for (int i = 0; i < tail; i++) { + array[i] = array[i + 1]; + } + } + + @Override + public void enqueue(T element) throws QueueOverflowException { + if (isFull()) { + throw new QueueOverflowException(); + } else { + tail++; + array[tail] = element; + } + } + + @Override + public T dequeue() throws QueueUnderflowException { + if (isEmpty()) { + throw new QueueUnderflowException(); + } else { + T dequeued = array[0]; + shiftLeft(); + tail--; + return dequeued; + } + + } + +} diff --git a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/QueueOverflowException.java b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/QueueOverflowException.java index dd51f0d21..43e1c42bd 100644 --- a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/QueueOverflowException.java +++ b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/QueueOverflowException.java @@ -1,9 +1,9 @@ -package adt.queue; - -public class QueueOverflowException extends Exception { - - public QueueOverflowException() { - super("Fila cheia"); - } - -} +package adt.queue; + +public class QueueOverflowException extends Exception { + + public QueueOverflowException() { + super("Fila cheia"); + } + +} diff --git a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/QueueUnderflowException.java b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/QueueUnderflowException.java index 09d30911d..20ce52154 100644 --- a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/QueueUnderflowException.java +++ b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/queue/QueueUnderflowException.java @@ -1,9 +1,9 @@ -package adt.queue; - -public class QueueUnderflowException extends Exception { - - public QueueUnderflowException() { - super("Fila vazia"); - } - -} +package adt.queue; + +public class QueueUnderflowException extends Exception { + + public QueueUnderflowException() { + super("Fila vazia"); + } + +} diff --git a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/stack/Stack.java b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/stack/Stack.java index 6760db4e3..09dace39a 100644 --- a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/stack/Stack.java +++ b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/stack/Stack.java @@ -1,50 +1,50 @@ -package adt.stack; - -/** - * The interface of a generic stack. The queue is able to store any kind of - * data. - * - */ -public interface Stack { - - /** - * Inserts a new element in the stack or returns an exception if the stack - * is full. Null elements are not allowed (the stack remains unchanged). - * - * @param element - * @throws StackOverflowException - */ - public void push(T element) throws StackOverflowException; - - /** - * If the stack has elements, it removes the top of the stack and returns - * it; otherwise, it returns an exception. - * - * @return - * @throws StackUnderflowException - */ - public T pop() throws StackUnderflowException; - - /** - * Returns (without removing) the top element of the stack or null if the - * stack is empty. - * - * @return - */ - public T top(); - - /** - * Returns true if the stack is empty or false, otherwise. - * - * @return - */ - public boolean isEmpty(); - - /** - * Returns true if the stack is full or false, otherwise. - * - * @return - */ - public boolean isFull(); - -} +package adt.stack; + +/** + * The interface of a generic stack. The queue is able to store any kind of + * data. + * + */ +public interface Stack { + + /** + * Inserts a new element in the stack or returns an exception if the stack + * is full. Null elements are not allowed (the stack remains unchanged). + * + * @param element + * @throws StackOverflowException + */ + public void push(T element) throws StackOverflowException; + + /** + * If the stack has elements, it removes the top of the stack and returns + * it; otherwise, it returns an exception. + * + * @return + * @throws StackUnderflowException + */ + public T pop() throws StackUnderflowException; + + /** + * Returns (without removing) the top element of the stack or null if the + * stack is empty. + * + * @return + */ + public T top(); + + /** + * Returns true if the stack is empty or false, otherwise. + * + * @return + */ + public boolean isEmpty(); + + /** + * Returns true if the stack is full or false, otherwise. + * + * @return + */ + public boolean isFull(); + +} diff --git a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/stack/StackImpl.java b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/stack/StackImpl.java index 210fa5584..4c8dbcecf 100644 --- a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/stack/StackImpl.java +++ b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/stack/StackImpl.java @@ -1,53 +1,53 @@ -package adt.stack; - -public class StackImpl implements Stack { - - private T[] array; - private int top; - - @SuppressWarnings("unchecked") - public StackImpl(int size) { - array = (T[]) new Object[size]; - top = -1; - } - - @Override - public T top() { - T topper = null; - if (!(isEmpty())) { - topper = array[top]; - } - return topper; - } - - @Override - public boolean isEmpty() { - return top == -1; - } - - @Override - public boolean isFull() { - return top == array.length - 1; - } - - @Override - public void push(T element) throws StackOverflowException { - if (isFull()) { - throw new StackOverflowException(); - } else { - top++; - array[top] = element; - } - } - - @Override - public T pop() throws StackUnderflowException { - if (isEmpty()) { - throw new StackUnderflowException(); - } else { - top--; - return array[top+1]; - } - } - -} +package adt.stack; + +public class StackImpl implements Stack { + + private T[] array; + private int top; + + @SuppressWarnings("unchecked") + public StackImpl(int size) { + array = (T[]) new Object[size]; + top = -1; + } + + @Override + public T top() { + T topper = null; + if (!(isEmpty())) { + topper = array[top]; + } + return topper; + } + + @Override + public boolean isEmpty() { + return top == -1; + } + + @Override + public boolean isFull() { + return top == array.length - 1; + } + + @Override + public void push(T element) throws StackOverflowException { + if (isFull()) { + throw new StackOverflowException(); + } else { + top++; + array[top] = element; + } + } + + @Override + public T pop() throws StackUnderflowException { + if (isEmpty()) { + throw new StackUnderflowException(); + } else { + top--; + return array[top+1]; + } + } + +} diff --git a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/stack/StackOverflowException.java b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/stack/StackOverflowException.java index 48b51fbe9..0d322ebfb 100644 --- a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/stack/StackOverflowException.java +++ b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/stack/StackOverflowException.java @@ -1,9 +1,9 @@ -package adt.stack; - -public class StackOverflowException extends Exception { - - public StackOverflowException() { - super("Stack is full"); - } - -} +package adt.stack; + +public class StackOverflowException extends Exception { + + public StackOverflowException() { + super("Stack is full"); + } + +} diff --git a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/stack/StackUnderflowException.java b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/stack/StackUnderflowException.java index 571562b67..5a1973c62 100644 --- a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/stack/StackUnderflowException.java +++ b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/stack/StackUnderflowException.java @@ -1,8 +1,8 @@ -package adt.stack; - -public class StackUnderflowException extends Exception { - - public StackUnderflowException() { - super("Stack is empty"); - } -} +package adt.stack; + +public class StackUnderflowException extends Exception { + + public StackUnderflowException() { + super("Stack is empty"); + } +} diff --git a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/test/java/adt/queue/StudentQueueTest.java b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/test/java/adt/queue/StudentQueueTest.java index e96d2fb26..b09809924 100644 --- a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/test/java/adt/queue/StudentQueueTest.java +++ b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/test/java/adt/queue/StudentQueueTest.java @@ -1,89 +1,89 @@ -package adt.queue; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class StudentQueueTest { - - public Queue queue1; - public Queue queue2; - public Queue queue3; - - @Before - public void setUp() throws QueueOverflowException { - - getImplementations(); - - // Fila com 3 elementos não cheia. - queue1.enqueue(1); - queue1.enqueue(2); - queue1.enqueue(3); - - // Fila com 2 elementos de tamanho 2. Fila cheia. - queue2.enqueue(1); - queue2.enqueue(2); - - } - - private void getImplementations() { - // TODO O aluno deve ajustar aqui para instanciar sua implementação - queue1 = new CircularQueue(4); - queue2 = new CircularQueue(2); - queue3 = new CircularQueue(0); - } - - // MÉTODOS DE TESTE - @Test - public void testHead() { - assertEquals(new Integer(1), queue1.head()); - } - - @Test - public void testIsEmpty() { - assertFalse(queue1.isEmpty()); - assertTrue(queue3.isEmpty()); - } - - @Test - public void testIsFull() { - assertFalse(queue1.isFull()); - } - - @Test - public void testEnqueue() { - try { - queue1.enqueue(new Integer(5)); - } catch (QueueOverflowException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test(expected = QueueOverflowException.class) - public void testEnqueueComErro() throws QueueOverflowException { - queue1.enqueue(new Integer(5)); // vai depender do tamanho que a fila - // foi iniciada!!! - } - - @Test - public void testDequeue() { - try { - assertEquals(new Integer(1), queue1.dequeue()); - } catch (QueueUnderflowException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test(expected = QueueUnderflowException.class) - public void testDequeueComErro() throws QueueUnderflowException { - assertEquals(new Integer(1), queue1.dequeue()); // vai depender do - // tamanho que a fial - // foi iniciada!!! - } +package adt.queue; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class StudentQueueTest { + + public Queue queue1; + public Queue queue2; + public Queue queue3; + + @Before + public void setUp() throws QueueOverflowException { + + getImplementations(); + + // Fila com 3 elementos não cheia. + queue1.enqueue(1); + queue1.enqueue(2); + queue1.enqueue(3); + + // Fila com 2 elementos de tamanho 2. Fila cheia. + queue2.enqueue(1); + queue2.enqueue(2); + + } + + private void getImplementations() { + // TODO O aluno deve ajustar aqui para instanciar sua implementação + queue1 = new CircularQueue(4); + queue2 = new CircularQueue(2); + queue3 = new CircularQueue(0); + } + + // MÉTODOS DE TESTE + @Test + public void testHead() { + assertEquals(new Integer(1), queue1.head()); + } + + @Test + public void testIsEmpty() { + assertFalse(queue1.isEmpty()); + assertTrue(queue3.isEmpty()); + } + + @Test + public void testIsFull() { + assertFalse(queue1.isFull()); + } + + @Test + public void testEnqueue() { + try { + queue1.enqueue(new Integer(5)); + } catch (QueueOverflowException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test(expected = QueueOverflowException.class) + public void testEnqueueComErro() throws QueueOverflowException { + queue1.enqueue(new Integer(5)); // vai depender do tamanho que a fila + // foi iniciada!!! + } + + @Test + public void testDequeue() { + try { + assertEquals(new Integer(1), queue1.dequeue()); + } catch (QueueUnderflowException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test(expected = QueueUnderflowException.class) + public void testDequeueComErro() throws QueueUnderflowException { + assertEquals(new Integer(1), queue1.dequeue()); // vai depender do + // tamanho que a fial + // foi iniciada!!! + } } \ No newline at end of file diff --git a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/test/java/adt/stack/StudentStackTest.java b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/test/java/adt/stack/StudentStackTest.java index 020de9f24..7be6d31d0 100644 --- a/java/R05-01-Rot-Pilha-FilaCircular-environment/src/test/java/adt/stack/StudentStackTest.java +++ b/java/R05-01-Rot-Pilha-FilaCircular-environment/src/test/java/adt/stack/StudentStackTest.java @@ -1,88 +1,88 @@ -package adt.stack; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class StudentStackTest { - - public Stack stack1; - public Stack stack2; - public Stack stack3; - - @Before - public void setUp() throws StackOverflowException { - - getImplementations(); - - // Pilha com 3 elementos não cheia. - stack1.push(1); - stack1.push(2); - stack1.push(3); - - // Pilha com 2 elementos de tamanho 2, pilha cheia. - stack2.push(1); - stack2.push(2); - - } - - private void getImplementations() { - // TODO O aluno deve ajustar aqui para instanciar sua implementação - stack1 = new StackImpl(4); - stack2 = new StackImpl(2); - stack3 = new StackImpl(3); - } - - // MÉTODOS DE TESTE - @Test - public void testTop() { - assertEquals(new Integer(3), stack1.top()); - } - - @Test - public void testIsEmpty() { - assertFalse(stack1.isEmpty()); - } - - @Test - public void testIsFull() { - assertFalse(stack1.isFull()); // vai depender do tamanho que a pilha foi - // iniciada!!!! - } - - @Test - public void testPush() { - try { - stack1.push(new Integer(5)); - } catch (StackOverflowException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test(expected = StackOverflowException.class) - public void testPushComErro() throws StackOverflowException { - stack1.push(new Integer(5)); // levanta excecao apenas se o tamanhonao - // permitir outra insercao - } - - @Test - public void testPop() { - try { - assertEquals(new Integer(3), stack1.pop()); - } catch (StackUnderflowException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test(expected = StackUnderflowException.class) - public void testPopComErro() throws StackUnderflowException { - assertEquals(new Integer(3), stack1.pop()); // levanta excecao apenas se - // stack1 for vazia - } +package adt.stack; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class StudentStackTest { + + public Stack stack1; + public Stack stack2; + public Stack stack3; + + @Before + public void setUp() throws StackOverflowException { + + getImplementations(); + + // Pilha com 3 elementos não cheia. + stack1.push(1); + stack1.push(2); + stack1.push(3); + + // Pilha com 2 elementos de tamanho 2, pilha cheia. + stack2.push(1); + stack2.push(2); + + } + + private void getImplementations() { + // TODO O aluno deve ajustar aqui para instanciar sua implementação + stack1 = new StackImpl(4); + stack2 = new StackImpl(2); + stack3 = new StackImpl(3); + } + + // MÉTODOS DE TESTE + @Test + public void testTop() { + assertEquals(new Integer(3), stack1.top()); + } + + @Test + public void testIsEmpty() { + assertFalse(stack1.isEmpty()); + } + + @Test + public void testIsFull() { + assertFalse(stack1.isFull()); // vai depender do tamanho que a pilha foi + // iniciada!!!! + } + + @Test + public void testPush() { + try { + stack1.push(new Integer(5)); + } catch (StackOverflowException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test(expected = StackOverflowException.class) + public void testPushComErro() throws StackOverflowException { + stack1.push(new Integer(5)); // levanta excecao apenas se o tamanhonao + // permitir outra insercao + } + + @Test + public void testPop() { + try { + assertEquals(new Integer(3), stack1.pop()); + } catch (StackUnderflowException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test(expected = StackUnderflowException.class) + public void testPopComErro() throws StackUnderflowException { + assertEquals(new Integer(3), stack1.pop()); // levanta excecao apenas se + // stack1 for vazia + } } \ No newline at end of file diff --git a/java/R05-01-Rot-Pilha-FilaCircular-environment/target/classes/META-INF/MANIFEST.MF b/java/R05-01-Rot-Pilha-FilaCircular-environment/target/classes/META-INF/MANIFEST.MF index 6c4b9cc34..a05e7910c 100644 --- a/java/R05-01-Rot-Pilha-FilaCircular-environment/target/classes/META-INF/MANIFEST.MF +++ b/java/R05-01-Rot-Pilha-FilaCircular-environment/target/classes/META-INF/MANIFEST.MF @@ -1,5 +1,5 @@ -Manifest-Version: 1.0 -Built-By: amintas -Build-Jdk: 1.8.0_131 -Created-By: Maven Integration for Eclipse - +Manifest-Version: 1.0 +Built-By: amintas +Build-Jdk: 1.8.0_131 +Created-By: Maven Integration for Eclipse + diff --git a/java/R05-01-Rot-Pilha-FilaCircular-environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml b/java/R05-01-Rot-Pilha-FilaCircular-environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml index a2292c644..04f6baced 100644 --- a/java/R05-01-Rot-Pilha-FilaCircular-environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml +++ b/java/R05-01-Rot-Pilha-FilaCircular-environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml @@ -1,98 +1,98 @@ - - 4.0.0 - - br.edu.ufcg.ccc - submission - 1.0 - jar - Submissao de roteiro - - - - ufcg-leda - http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda - default - - true - always - - - - - - - junit - junit - 4.12 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - maven-clean-plugin - 3.0.0 - - - auto-clean - build - - clean - - - - - - - org.walkmod - maven-walkmod-plugin - 1.3 - - walkmod.xml - - - - package - - apply - - - false - - - - - - br.edu.ufcg.ccc - leda-compactor-tool - 1.0.0-SNAPSHOT - - - install - - compact - - - - 116110761 - - R05-01 - - 2017.1 - http://150.165.85.29:81/submitAtividade - - - - - - - + + 4.0.0 + + br.edu.ufcg.ccc + submission + 1.0 + jar + Submissao de roteiro + + + + ufcg-leda + http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda + default + + true + always + + + + + + + junit + junit + 4.12 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + maven-clean-plugin + 3.0.0 + + + auto-clean + build + + clean + + + + + + + org.walkmod + maven-walkmod-plugin + 1.3 + + walkmod.xml + + + + package + + apply + + + false + + + + + + br.edu.ufcg.ccc + leda-compactor-tool + 1.0.0-SNAPSHOT + + + install + + compact + + + + 116110761 + + R05-01 + + 2017.1 + http://150.165.85.29:81/submitAtividade + + + + + + + diff --git a/java/R05-01-Rot-Pilha-FilaCircular-environment/walkmod.xml b/java/R05-01-Rot-Pilha-FilaCircular-environment/walkmod.xml index d391a36b4..85902bfec 100644 --- a/java/R05-01-Rot-Pilha-FilaCircular-environment/walkmod.xml +++ b/java/R05-01-Rot-Pilha-FilaCircular-environment/walkmod.xml @@ -1,4 +1,4 @@ - - - + + + \ No newline at end of file diff --git a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/pom.xml b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/pom.xml index b21cb4074..564822f7d 100644 --- a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/pom.xml +++ b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/pom.xml @@ -1,98 +1,98 @@ - - 4.0.0 - - br.edu.ufcg.ccc - submission - 1.0 - jar - Submissao de roteiro - - - - ufcg-leda - http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda - default - - true - always - - - - - - - junit - junit - 4.12 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - maven-clean-plugin - 3.0.0 - - - auto-clean - build - - clean - - - - - - - org.walkmod - maven-walkmod-plugin - 1.3 - - walkmod.xml - - - - package - - apply - - - false - - - - - - br.edu.ufcg.ccc - leda-compactor-tool - 1.0.0-SNAPSHOT - - - install - - compact - - - - 116110761 - - R06-01 - - 2017.1 - http://150.165.85.29:81/submitAtividade - - - - - - - + + 4.0.0 + + br.edu.ufcg.ccc + submission + 1.0 + jar + Submissao de roteiro + + + + ufcg-leda + http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda + default + + true + always + + + + + + + junit + junit + 4.12 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + maven-clean-plugin + 3.0.0 + + + auto-clean + build + + clean + + + + + + + org.walkmod + maven-walkmod-plugin + 1.3 + + walkmod.xml + + + + package + + apply + + + false + + + + + + br.edu.ufcg.ccc + leda-compactor-tool + 1.0.0-SNAPSHOT + + + install + + compact + + + + 116110761 + + R06-01 + + 2017.1 + http://150.165.85.29:81/submitAtividade + + + + + + + diff --git a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/DoubleLinkedList.java b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/DoubleLinkedList.java index b13faec8d..4bcc55715 100644 --- a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/DoubleLinkedList.java +++ b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/DoubleLinkedList.java @@ -1,29 +1,29 @@ -package adt.linkedList; - -/** - * The interface of a double linked list with a head and a last (Deque). - * - * @param - */ -public interface DoubleLinkedList extends LinkedList { - - /** - * Inserts a new element in the first position (head) of the list. The - * "head" reference must be updated. - * - * @param element - */ - public void insertFirst(T element); - - /** - * Removes the first element (head) of the list. The "head" reference must - * be updated. - */ - public void removeFirst(); - - /** - * Removes the last element (last) of the list. The "last" reference must be - * updated. - */ - public void removeLast(); -} +package adt.linkedList; + +/** + * The interface of a double linked list with a head and a last (Deque). + * + * @param + */ +public interface DoubleLinkedList extends LinkedList { + + /** + * Inserts a new element in the first position (head) of the list. The + * "head" reference must be updated. + * + * @param element + */ + public void insertFirst(T element); + + /** + * Removes the first element (head) of the list. The "head" reference must + * be updated. + */ + public void removeFirst(); + + /** + * Removes the last element (last) of the list. The "last" reference must be + * updated. + */ + public void removeLast(); +} diff --git a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/DoubleLinkedListImpl.java b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/DoubleLinkedListImpl.java index 11c47e75b..020e5b308 100644 --- a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/DoubleLinkedListImpl.java +++ b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/DoubleLinkedListImpl.java @@ -1,76 +1,76 @@ -package adt.linkedList; - -public class DoubleLinkedListImpl extends SingleLinkedListImpl implements DoubleLinkedList { - - protected DoubleLinkedListNode last; - private DoubleLinkedListNode nil; - - public DoubleLinkedListImpl() { - last = new DoubleLinkedListNode<>(); - head = last; - } - - @Override - public void insertFirst(T element) { - if (element != null) { - nil = new DoubleLinkedListNode(); - DoubleLinkedListNode newHead = new DoubleLinkedListNode(element, (DoubleLinkedListNode) getHead(), - nil); - ((DoubleLinkedListNode) getHead()).setPrevious(newHead); - if (newHead.isNIL()) { - setLast(newHead); - } - setHead(newHead); - } - } - - @Override - public void removeFirst() { - if (!(getHead().isNIL())) { - setHead(getHead().getNext()); - if (getHead().isNIL()) { - setLast((DoubleLinkedListNode) (getHead())); - } - if (getHead() instanceof DoubleLinkedListNode) { - DoubleLinkedListNode head = (DoubleLinkedListNode) getHead(); - nil = new DoubleLinkedListNode(); - head.setPrevious(nil); - } - } - } - - @Override - public void removeLast() { - if (!(getLast().isNIL())) { - setLast(getLast().getPrevious()); - if (getLast().isNIL()) { - setHead(getLast()); - } - nil = new DoubleLinkedListNode(); - getLast().setNext(nil); - } - } - - @Override - public void insert(T element) { - if (element != null) { - nil = new DoubleLinkedListNode(); - DoubleLinkedListNode newLast = new DoubleLinkedListNode(element, nil, getLast()); - getLast().setNext(newLast); - if (getLast().isNIL()) { - setHead(newLast); - } - setLast(newLast); - } - - } - - public DoubleLinkedListNode getLast() { - return last; - } - - public void setLast(DoubleLinkedListNode last) { - this.last = last; - } - -} +package adt.linkedList; + +public class DoubleLinkedListImpl extends SingleLinkedListImpl implements DoubleLinkedList { + + protected DoubleLinkedListNode last; + private DoubleLinkedListNode nil; + + public DoubleLinkedListImpl() { + last = new DoubleLinkedListNode<>(); + head = last; + } + + @Override + public void insertFirst(T element) { + if (element != null) { + nil = new DoubleLinkedListNode(); + DoubleLinkedListNode newHead = new DoubleLinkedListNode(element, (DoubleLinkedListNode) getHead(), + nil); + ((DoubleLinkedListNode) getHead()).setPrevious(newHead); + if (newHead.isNIL()) { + setLast(newHead); + } + setHead(newHead); + } + } + + @Override + public void removeFirst() { + if (!(getHead().isNIL())) { + setHead(getHead().getNext()); + if (getHead().isNIL()) { + setLast((DoubleLinkedListNode) (getHead())); + } + if (getHead() instanceof DoubleLinkedListNode) { + DoubleLinkedListNode head = (DoubleLinkedListNode) getHead(); + nil = new DoubleLinkedListNode(); + head.setPrevious(nil); + } + } + } + + @Override + public void removeLast() { + if (!(getLast().isNIL())) { + setLast(getLast().getPrevious()); + if (getLast().isNIL()) { + setHead(getLast()); + } + nil = new DoubleLinkedListNode(); + getLast().setNext(nil); + } + } + + @Override + public void insert(T element) { + if (element != null) { + nil = new DoubleLinkedListNode(); + DoubleLinkedListNode newLast = new DoubleLinkedListNode(element, nil, getLast()); + getLast().setNext(newLast); + if (getLast().isNIL()) { + setHead(newLast); + } + setLast(newLast); + } + + } + + public DoubleLinkedListNode getLast() { + return last; + } + + public void setLast(DoubleLinkedListNode last) { + this.last = last; + } + +} diff --git a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/DoubleLinkedListNode.java b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/DoubleLinkedListNode.java index c30ab3f4a..e7c3e1e3f 100644 --- a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/DoubleLinkedListNode.java +++ b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/DoubleLinkedListNode.java @@ -1,23 +1,23 @@ -package adt.linkedList; - -public class DoubleLinkedListNode extends SingleLinkedListNode { - protected DoubleLinkedListNode previous; - - public DoubleLinkedListNode() { - } - - public DoubleLinkedListNode(T data, DoubleLinkedListNode next, - DoubleLinkedListNode previous) { - super(data, next); - this.previous = previous; - } - - public DoubleLinkedListNode getPrevious() { - return previous; - } - - public void setPrevious(DoubleLinkedListNode previous) { - this.previous = previous; - } - -} +package adt.linkedList; + +public class DoubleLinkedListNode extends SingleLinkedListNode { + protected DoubleLinkedListNode previous; + + public DoubleLinkedListNode() { + } + + public DoubleLinkedListNode(T data, DoubleLinkedListNode next, + DoubleLinkedListNode previous) { + super(data, next); + this.previous = previous; + } + + public DoubleLinkedListNode getPrevious() { + return previous; + } + + public void setPrevious(DoubleLinkedListNode previous) { + this.previous = previous; + } + +} diff --git a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/LinkedList.java b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/LinkedList.java index 1fafeb6c2..3cc2d3776 100644 --- a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/LinkedList.java +++ b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/LinkedList.java @@ -1,53 +1,53 @@ -package adt.linkedList; - -/** - * The interface of a generic linked list. - */ -public interface LinkedList { - /** - * @return true if the list is empty or false, otherwise - */ - public boolean isEmpty(); - - /** - * @return the number of elements on the list - */ - public int size(); - - /** - * Searches for a given element in the list. - * - * @param element - * the element being searched for - * @return the element if it is in the list or null, otherwise - */ - public T search(T element); - - /** - * Inserts a new element at the end of the list. Null elements must be - * ignored. - * - * @param element - * the element to be inserted - */ - public void insert(T element); - - /** - * Removes an element from the list. If the element does not exist the list - * is not changed. - * - * @param element - * the element to be removed - */ - public void remove(T element); - - /** - * Returns an array containing all elements in the structure. The array does - * not contain empty spaces (or null elements). The elements are put into - * the array from the beginning to the end of the list. - * - * @return an array containing all elements in the structure in the order - * they appear - */ - public T[] toArray(); +package adt.linkedList; + +/** + * The interface of a generic linked list. + */ +public interface LinkedList { + /** + * @return true if the list is empty or false, otherwise + */ + public boolean isEmpty(); + + /** + * @return the number of elements on the list + */ + public int size(); + + /** + * Searches for a given element in the list. + * + * @param element + * the element being searched for + * @return the element if it is in the list or null, otherwise + */ + public T search(T element); + + /** + * Inserts a new element at the end of the list. Null elements must be + * ignored. + * + * @param element + * the element to be inserted + */ + public void insert(T element); + + /** + * Removes an element from the list. If the element does not exist the list + * is not changed. + * + * @param element + * the element to be removed + */ + public void remove(T element); + + /** + * Returns an array containing all elements in the structure. The array does + * not contain empty spaces (or null elements). The elements are put into + * the array from the beginning to the end of the list. + * + * @return an array containing all elements in the structure in the order + * they appear + */ + public T[] toArray(); } \ No newline at end of file diff --git a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/SingleLinkedListImpl.java b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/SingleLinkedListImpl.java index 2d46a29fe..cdc7042d7 100644 --- a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/SingleLinkedListImpl.java +++ b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/SingleLinkedListImpl.java @@ -1,90 +1,90 @@ -package adt.linkedList; - -public class SingleLinkedListImpl implements LinkedList { - - protected SingleLinkedListNode head; - - public SingleLinkedListImpl() { - this.head = new SingleLinkedListNode(); - } - - @Override - public boolean isEmpty() { - return head.isNIL(); - } - - @Override - public int size() { - int size = 0; - SingleLinkedListNode auxNode = getHead(); - while (!(auxNode.isNIL())) { - size++; - auxNode = auxNode.getNext(); - } - return size; - } - - @Override - public T search(T element) { - T result = null; - if (element != null) { - SingleLinkedListNode node = getHead(); - while (!(node.isNIL()) && !(node.getData().equals(element))) { - node = node.getNext(); - } - result = node.getData(); - } - return result; - } - - @Override - public void insert(T element) { - if (element != null) { - SingleLinkedListNode auxHead = getHead(); - while (!auxHead.isNIL()) { - auxHead = auxHead.getNext(); - } - auxHead.setData(element); - auxHead.setNext(new SingleLinkedListNode()); - } - - } - - @Override - public void remove(T element) { - if (element != null) { - if (!getHead().isNIL()) { - SingleLinkedListNode auxHead = getHead(); - while (!auxHead.getNext().isNIL() && !auxHead.getNext().getData().equals(element)) { - auxHead = auxHead.getNext(); - } - if (!auxHead.getNext().isNIL()) { - auxHead.setNext(auxHead.getNext().getNext()); - } - } - } - } - - @Override - public T[] toArray() { - @SuppressWarnings("unchecked") - T[] result = (T[]) new Object[this.size()]; - SingleLinkedListNode auxNode = getHead(); - int index = 0; - while (!(auxNode.isNIL())) { - result[index] = auxNode.getData(); - auxNode = auxNode.getNext(); - index++; - } - return result; - } - - public SingleLinkedListNode getHead() { - return head; - } - - public void setHead(SingleLinkedListNode head) { - this.head = head; - } - -} +package adt.linkedList; + +public class SingleLinkedListImpl implements LinkedList { + + protected SingleLinkedListNode head; + + public SingleLinkedListImpl() { + this.head = new SingleLinkedListNode(); + } + + @Override + public boolean isEmpty() { + return head.isNIL(); + } + + @Override + public int size() { + int size = 0; + SingleLinkedListNode auxNode = getHead(); + while (!(auxNode.isNIL())) { + size++; + auxNode = auxNode.getNext(); + } + return size; + } + + @Override + public T search(T element) { + T result = null; + if (element != null) { + SingleLinkedListNode node = getHead(); + while (!(node.isNIL()) && !(node.getData().equals(element))) { + node = node.getNext(); + } + result = node.getData(); + } + return result; + } + + @Override + public void insert(T element) { + if (element != null) { + SingleLinkedListNode auxHead = getHead(); + while (!auxHead.isNIL()) { + auxHead = auxHead.getNext(); + } + auxHead.setData(element); + auxHead.setNext(new SingleLinkedListNode()); + } + + } + + @Override + public void remove(T element) { + if (element != null) { + if (!getHead().isNIL()) { + SingleLinkedListNode auxHead = getHead(); + while (!auxHead.getNext().isNIL() && !auxHead.getNext().getData().equals(element)) { + auxHead = auxHead.getNext(); + } + if (!auxHead.getNext().isNIL()) { + auxHead.setNext(auxHead.getNext().getNext()); + } + } + } + } + + @Override + public T[] toArray() { + @SuppressWarnings("unchecked") + T[] result = (T[]) new Object[this.size()]; + SingleLinkedListNode auxNode = getHead(); + int index = 0; + while (!(auxNode.isNIL())) { + result[index] = auxNode.getData(); + auxNode = auxNode.getNext(); + index++; + } + return result; + } + + public SingleLinkedListNode getHead() { + return head; + } + + public void setHead(SingleLinkedListNode head) { + this.head = head; + } + +} diff --git a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/SingleLinkedListNode.java b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/SingleLinkedListNode.java index 0087b2b79..6aec6d0b5 100644 --- a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/SingleLinkedListNode.java +++ b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/linkedList/SingleLinkedListNode.java @@ -1,64 +1,64 @@ -package adt.linkedList; - -public class SingleLinkedListNode { - protected T data; - protected SingleLinkedListNode next; - - /** - * Constructor of an empty (NIL) node - */ - public SingleLinkedListNode() { - } - - public SingleLinkedListNode(T data, SingleLinkedListNode next) { - this.data = data; - this.next = next; - } - - public T getData() { - return data; - } - - public SingleLinkedListNode getNext() { - return next; - } - - public boolean isNIL() { - return (this.data == null); - } - - @Override - public String toString() { - String resp = null; - if (!isNIL()) { - resp = this.data.toString(); - } else { - resp = "NIL"; - } - return resp; - } - - @SuppressWarnings("unchecked") - @Override - public boolean equals(Object obj) { - boolean resp = false; - if (obj instanceof SingleLinkedListNode) { - if (!this.isNIL()) { - resp = this.data.equals(((SingleLinkedListNode) obj).data); - } else { - resp = ((SingleLinkedListNode) obj).isNIL(); - } - - } - return resp; - } - - public void setData(T data) { - this.data = data; - } - - public void setNext(SingleLinkedListNode next) { - this.next = next; - } - -} +package adt.linkedList; + +public class SingleLinkedListNode { + protected T data; + protected SingleLinkedListNode next; + + /** + * Constructor of an empty (NIL) node + */ + public SingleLinkedListNode() { + } + + public SingleLinkedListNode(T data, SingleLinkedListNode next) { + this.data = data; + this.next = next; + } + + public T getData() { + return data; + } + + public SingleLinkedListNode getNext() { + return next; + } + + public boolean isNIL() { + return (this.data == null); + } + + @Override + public String toString() { + String resp = null; + if (!isNIL()) { + resp = this.data.toString(); + } else { + resp = "NIL"; + } + return resp; + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(Object obj) { + boolean resp = false; + if (obj instanceof SingleLinkedListNode) { + if (!this.isNIL()) { + resp = this.data.equals(((SingleLinkedListNode) obj).data); + } else { + resp = ((SingleLinkedListNode) obj).isNIL(); + } + + } + return resp; + } + + public void setData(T data) { + this.data = data; + } + + public void setNext(SingleLinkedListNode next) { + this.next = next; + } + +} diff --git a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/queue/Queue.java b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/queue/Queue.java index 1c476145e..3931971e2 100644 --- a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/queue/Queue.java +++ b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/queue/Queue.java @@ -1,50 +1,50 @@ -package adt.queue; - -/** - * The interface of a generic queue. The queue is able to store any kind of - * data. - * - */ -public interface Queue { - - /** - * Inserts a new element in the queue or returns an exception if the queue - * is full. Null elements are not allowed (the queue remains unchanged). - * - * @param element - * @throws QueueOverflowException - */ - public void enqueue(T element) throws QueueOverflowException; - - /** - * If the queue has elements, it removes the oldest of the queue and returns - * it; otherwise, it returns an exception. - * - * @return - * @throws QueueUnderflowException - */ - public T dequeue() throws QueueUnderflowException; - - /** - * Returns (without removing) the oldest element of the stack or null if the - * queue is empty. - * - * @return - */ - public T head(); - - /** - * Returns true if the queue is empty or false, otherwise. - * - * @return - */ - public boolean isEmpty(); - - /** - * Returns true if the queue is full or false, otherwise. - * - * @return - */ - public boolean isFull(); - -} +package adt.queue; + +/** + * The interface of a generic queue. The queue is able to store any kind of + * data. + * + */ +public interface Queue { + + /** + * Inserts a new element in the queue or returns an exception if the queue + * is full. Null elements are not allowed (the queue remains unchanged). + * + * @param element + * @throws QueueOverflowException + */ + public void enqueue(T element) throws QueueOverflowException; + + /** + * If the queue has elements, it removes the oldest of the queue and returns + * it; otherwise, it returns an exception. + * + * @return + * @throws QueueUnderflowException + */ + public T dequeue() throws QueueUnderflowException; + + /** + * Returns (without removing) the oldest element of the stack or null if the + * queue is empty. + * + * @return + */ + public T head(); + + /** + * Returns true if the queue is empty or false, otherwise. + * + * @return + */ + public boolean isEmpty(); + + /** + * Returns true if the queue is full or false, otherwise. + * + * @return + */ + public boolean isFull(); + +} diff --git a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/queue/QueueDoubleLinkedListImpl.java b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/queue/QueueDoubleLinkedListImpl.java index c928b1b5c..a8ca2651e 100644 --- a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/queue/QueueDoubleLinkedListImpl.java +++ b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/queue/QueueDoubleLinkedListImpl.java @@ -1,50 +1,50 @@ -package adt.queue; - -import adt.linkedList.DoubleLinkedListImpl; - -public class QueueDoubleLinkedListImpl implements Queue { - - protected DoubleLinkedListImpl list; - protected int size; - - public QueueDoubleLinkedListImpl(int size) { - this.size = size; - this.list = new DoubleLinkedListImpl(); - } - - @Override - public void enqueue(T element) throws QueueOverflowException { - if (isFull()) { - throw new QueueOverflowException(); - } else { - list.insert(element); - } - } - - @Override - public T dequeue() throws QueueUnderflowException { - if (isEmpty()) { - throw new QueueUnderflowException(); - } else { - T result = list.getHead().getData(); - list.removeFirst(); - return result; - } - } - - @Override - public T head() { - return list.getHead().getData(); - } - - @Override - public boolean isEmpty() { - return list.isEmpty(); - } - - @Override - public boolean isFull() { - return list.size() == size; - } - -} +package adt.queue; + +import adt.linkedList.DoubleLinkedListImpl; + +public class QueueDoubleLinkedListImpl implements Queue { + + protected DoubleLinkedListImpl list; + protected int size; + + public QueueDoubleLinkedListImpl(int size) { + this.size = size; + this.list = new DoubleLinkedListImpl(); + } + + @Override + public void enqueue(T element) throws QueueOverflowException { + if (isFull()) { + throw new QueueOverflowException(); + } else { + list.insert(element); + } + } + + @Override + public T dequeue() throws QueueUnderflowException { + if (isEmpty()) { + throw new QueueUnderflowException(); + } else { + T result = list.getHead().getData(); + list.removeFirst(); + return result; + } + } + + @Override + public T head() { + return list.getHead().getData(); + } + + @Override + public boolean isEmpty() { + return list.isEmpty(); + } + + @Override + public boolean isFull() { + return list.size() == size; + } + +} diff --git a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/queue/QueueOverflowException.java b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/queue/QueueOverflowException.java index dd51f0d21..43e1c42bd 100644 --- a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/queue/QueueOverflowException.java +++ b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/queue/QueueOverflowException.java @@ -1,9 +1,9 @@ -package adt.queue; - -public class QueueOverflowException extends Exception { - - public QueueOverflowException() { - super("Fila cheia"); - } - -} +package adt.queue; + +public class QueueOverflowException extends Exception { + + public QueueOverflowException() { + super("Fila cheia"); + } + +} diff --git a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/queue/QueueUnderflowException.java b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/queue/QueueUnderflowException.java index 09d30911d..20ce52154 100644 --- a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/queue/QueueUnderflowException.java +++ b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/queue/QueueUnderflowException.java @@ -1,9 +1,9 @@ -package adt.queue; - -public class QueueUnderflowException extends Exception { - - public QueueUnderflowException() { - super("Fila vazia"); - } - -} +package adt.queue; + +public class QueueUnderflowException extends Exception { + + public QueueUnderflowException() { + super("Fila vazia"); + } + +} diff --git a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/stack/Stack.java b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/stack/Stack.java index 6760db4e3..09dace39a 100644 --- a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/stack/Stack.java +++ b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/stack/Stack.java @@ -1,50 +1,50 @@ -package adt.stack; - -/** - * The interface of a generic stack. The queue is able to store any kind of - * data. - * - */ -public interface Stack { - - /** - * Inserts a new element in the stack or returns an exception if the stack - * is full. Null elements are not allowed (the stack remains unchanged). - * - * @param element - * @throws StackOverflowException - */ - public void push(T element) throws StackOverflowException; - - /** - * If the stack has elements, it removes the top of the stack and returns - * it; otherwise, it returns an exception. - * - * @return - * @throws StackUnderflowException - */ - public T pop() throws StackUnderflowException; - - /** - * Returns (without removing) the top element of the stack or null if the - * stack is empty. - * - * @return - */ - public T top(); - - /** - * Returns true if the stack is empty or false, otherwise. - * - * @return - */ - public boolean isEmpty(); - - /** - * Returns true if the stack is full or false, otherwise. - * - * @return - */ - public boolean isFull(); - -} +package adt.stack; + +/** + * The interface of a generic stack. The queue is able to store any kind of + * data. + * + */ +public interface Stack { + + /** + * Inserts a new element in the stack or returns an exception if the stack + * is full. Null elements are not allowed (the stack remains unchanged). + * + * @param element + * @throws StackOverflowException + */ + public void push(T element) throws StackOverflowException; + + /** + * If the stack has elements, it removes the top of the stack and returns + * it; otherwise, it returns an exception. + * + * @return + * @throws StackUnderflowException + */ + public T pop() throws StackUnderflowException; + + /** + * Returns (without removing) the top element of the stack or null if the + * stack is empty. + * + * @return + */ + public T top(); + + /** + * Returns true if the stack is empty or false, otherwise. + * + * @return + */ + public boolean isEmpty(); + + /** + * Returns true if the stack is full or false, otherwise. + * + * @return + */ + public boolean isFull(); + +} diff --git a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/stack/StackDoubleLinkedListImpl.java b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/stack/StackDoubleLinkedListImpl.java index b69057be9..b73924e5d 100644 --- a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/stack/StackDoubleLinkedListImpl.java +++ b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/stack/StackDoubleLinkedListImpl.java @@ -1,51 +1,51 @@ -package adt.stack; - -import adt.linkedList.DoubleLinkedListImpl; - -public class StackDoubleLinkedListImpl implements Stack { - - protected DoubleLinkedListImpl top; - protected int size; - - public StackDoubleLinkedListImpl(int size) { - this.size = size; - this.top = new DoubleLinkedListImpl(); - } - - @Override - public void push(T element) throws StackOverflowException { - if (isFull()) { - throw new StackOverflowException(); - } else { - top.insertFirst(element); - } - - } - - @Override - public T pop() throws StackUnderflowException { - if (isEmpty()) { - throw new StackUnderflowException(); - } else { - T result = top.getHead().getData(); - top.removeFirst(); - return result; - } - } - - @Override - public T top() { - return top.getHead().getData(); - } - - @Override - public boolean isEmpty() { - return top.isEmpty(); - } - - @Override - public boolean isFull() { - return top.size() == size; - } - -} +package adt.stack; + +import adt.linkedList.DoubleLinkedListImpl; + +public class StackDoubleLinkedListImpl implements Stack { + + protected DoubleLinkedListImpl top; + protected int size; + + public StackDoubleLinkedListImpl(int size) { + this.size = size; + this.top = new DoubleLinkedListImpl(); + } + + @Override + public void push(T element) throws StackOverflowException { + if (isFull()) { + throw new StackOverflowException(); + } else { + top.insertFirst(element); + } + + } + + @Override + public T pop() throws StackUnderflowException { + if (isEmpty()) { + throw new StackUnderflowException(); + } else { + T result = top.getHead().getData(); + top.removeFirst(); + return result; + } + } + + @Override + public T top() { + return top.getHead().getData(); + } + + @Override + public boolean isEmpty() { + return top.isEmpty(); + } + + @Override + public boolean isFull() { + return top.size() == size; + } + +} diff --git a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/stack/StackOverflowException.java b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/stack/StackOverflowException.java index 48b51fbe9..0d322ebfb 100644 --- a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/stack/StackOverflowException.java +++ b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/stack/StackOverflowException.java @@ -1,9 +1,9 @@ -package adt.stack; - -public class StackOverflowException extends Exception { - - public StackOverflowException() { - super("Stack is full"); - } - -} +package adt.stack; + +public class StackOverflowException extends Exception { + + public StackOverflowException() { + super("Stack is full"); + } + +} diff --git a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/stack/StackUnderflowException.java b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/stack/StackUnderflowException.java index 571562b67..5a1973c62 100644 --- a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/stack/StackUnderflowException.java +++ b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/main/java/adt/stack/StackUnderflowException.java @@ -1,8 +1,8 @@ -package adt.stack; - -public class StackUnderflowException extends Exception { - - public StackUnderflowException() { - super("Stack is empty"); - } -} +package adt.stack; + +public class StackUnderflowException extends Exception { + + public StackUnderflowException() { + super("Stack is empty"); + } +} diff --git a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/test/java/adt/linkedList/StudentDoubleLinkedListTest.java b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/test/java/adt/linkedList/StudentDoubleLinkedListTest.java index 00a3c15fc..0cce7a88f 100644 --- a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/test/java/adt/linkedList/StudentDoubleLinkedListTest.java +++ b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/test/java/adt/linkedList/StudentDoubleLinkedListTest.java @@ -1,100 +1,100 @@ -package adt.linkedList; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class StudentDoubleLinkedListTest { - - private DoubleLinkedList lista1; - private DoubleLinkedList lista2; - private DoubleLinkedList lista3; - - @Before - public void setUp() throws Exception { - - getImplementations(); - - // Lista com 3 elementos. - lista1.insert(3); - lista1.insert(2); - lista1.insert(1); - - // Lista com 1 elemento. - lista3.insert(1); - } - - private void getImplementations() { - // TODO O aluno deve ajustar aqui para instanciar sua implementação - lista1 = new DoubleLinkedListImpl(); - lista2 = new DoubleLinkedListImpl(); - lista3 = new DoubleLinkedListImpl(); - } - - // Métodos de DoubleLinkedList - - @Test - public void testInsertFirst() { - lista1.insertFirst(4); - Assert.assertArrayEquals(new Integer[] { 4, 3, 2, 1 }, lista1.toArray()); - } - - @Test - public void testRemoveFirst() { - lista1.removeFirst(); - Assert.assertArrayEquals(new Integer[] { 2, 1 }, lista1.toArray()); - } - - @Test - public void testRemoveLast() { - lista1.removeLast(); - Assert.assertArrayEquals(new Integer[] { 3, 2 }, lista1.toArray()); - } - - @Test - public void testIsEmpty() { - Assert.assertFalse(lista1.isEmpty()); - Assert.assertTrue(lista2.isEmpty()); - } - - @Test - public void testSize() { - Assert.assertEquals(3, lista1.size()); - Assert.assertEquals(0, lista2.size()); - } - - @Test - public void testSearch() { - Assert.assertTrue(2 == lista1.search(2)); - Assert.assertNull(lista1.search(4)); - Assert.assertFalse(3 == lista1.search(2)); - } - - @Test - public void testInsert() { - Assert.assertEquals(3, lista1.size()); - lista1.insert(5); - lista1.insert(7); - Assert.assertEquals(5, lista1.size()); - - Assert.assertEquals(0, lista2.size()); - lista2.insert(4); - lista2.insert(7); - Assert.assertEquals(2, lista2.size()); - } - - @Test - public void testRemove() { - Assert.assertEquals(3, lista1.size()); - lista1.remove(2); - lista1.remove(1); - Assert.assertEquals(1, lista1.size()); - - } - - @Test - public void testToArray() { - Assert.assertArrayEquals(new Integer[] {}, lista2.toArray()); - Assert.assertArrayEquals(new Integer[] { 3, 2, 1 }, lista1.toArray()); - } +package adt.linkedList; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class StudentDoubleLinkedListTest { + + private DoubleLinkedList lista1; + private DoubleLinkedList lista2; + private DoubleLinkedList lista3; + + @Before + public void setUp() throws Exception { + + getImplementations(); + + // Lista com 3 elementos. + lista1.insert(3); + lista1.insert(2); + lista1.insert(1); + + // Lista com 1 elemento. + lista3.insert(1); + } + + private void getImplementations() { + // TODO O aluno deve ajustar aqui para instanciar sua implementação + lista1 = new DoubleLinkedListImpl(); + lista2 = new DoubleLinkedListImpl(); + lista3 = new DoubleLinkedListImpl(); + } + + // Métodos de DoubleLinkedList + + @Test + public void testInsertFirst() { + lista1.insertFirst(4); + Assert.assertArrayEquals(new Integer[] { 4, 3, 2, 1 }, lista1.toArray()); + } + + @Test + public void testRemoveFirst() { + lista1.removeFirst(); + Assert.assertArrayEquals(new Integer[] { 2, 1 }, lista1.toArray()); + } + + @Test + public void testRemoveLast() { + lista1.removeLast(); + Assert.assertArrayEquals(new Integer[] { 3, 2 }, lista1.toArray()); + } + + @Test + public void testIsEmpty() { + Assert.assertFalse(lista1.isEmpty()); + Assert.assertTrue(lista2.isEmpty()); + } + + @Test + public void testSize() { + Assert.assertEquals(3, lista1.size()); + Assert.assertEquals(0, lista2.size()); + } + + @Test + public void testSearch() { + Assert.assertTrue(2 == lista1.search(2)); + Assert.assertNull(lista1.search(4)); + Assert.assertFalse(3 == lista1.search(2)); + } + + @Test + public void testInsert() { + Assert.assertEquals(3, lista1.size()); + lista1.insert(5); + lista1.insert(7); + Assert.assertEquals(5, lista1.size()); + + Assert.assertEquals(0, lista2.size()); + lista2.insert(4); + lista2.insert(7); + Assert.assertEquals(2, lista2.size()); + } + + @Test + public void testRemove() { + Assert.assertEquals(3, lista1.size()); + lista1.remove(2); + lista1.remove(1); + Assert.assertEquals(1, lista1.size()); + + } + + @Test + public void testToArray() { + Assert.assertArrayEquals(new Integer[] {}, lista2.toArray()); + Assert.assertArrayEquals(new Integer[] { 3, 2, 1 }, lista1.toArray()); + } } \ No newline at end of file diff --git a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/test/java/adt/linkedList/StudentLinkedListTest.java b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/test/java/adt/linkedList/StudentLinkedListTest.java index 21c6fa501..9243f872d 100644 --- a/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/test/java/adt/linkedList/StudentLinkedListTest.java +++ b/java/R06-01-Rot-Linked-list-abordagem-iterativa-environment/src/test/java/adt/linkedList/StudentLinkedListTest.java @@ -1,76 +1,76 @@ -package adt.linkedList; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class StudentLinkedListTest { - - private LinkedList lista1; - private LinkedList lista2; - - @Before - public void setUp() throws Exception { - - getImplementations(); - - // Lista com 3 elementos. - lista1.insert(3); - lista1.insert(2); - lista1.insert(1); - - } - - private void getImplementations() { - // TODO O aluno deve ajustar aqui para instanciar sua implementação - lista1 = new SingleLinkedListImpl(); - lista2 = new SingleLinkedListImpl(); - } - - @Test - public void testIsEmpty() { - Assert.assertFalse(lista1.isEmpty()); - Assert.assertTrue(lista2.isEmpty()); - } - - @Test - public void testSize() { - Assert.assertEquals(3, lista1.size()); - Assert.assertEquals(0, lista2.size()); - } - - @Test - public void testSearch() { - Assert.assertTrue(2 == lista1.search(2)); - Assert.assertNull(lista1.search(4)); - Assert.assertFalse(3 == lista1.search(2)); - } - - @Test - public void testInsert() { - Assert.assertEquals(3, lista1.size()); - lista1.insert(5); - lista1.insert(7); - Assert.assertEquals(5, lista1.size()); - - Assert.assertEquals(0, lista2.size()); - lista2.insert(4); - lista2.insert(7); - Assert.assertEquals(2, lista2.size()); - } - - @Test - public void testRemove() { - Assert.assertEquals(3, lista1.size()); - lista1.remove(2); - lista1.remove(1); - Assert.assertEquals(1, lista1.size()); - - } - - @Test - public void testToArray() { - Assert.assertArrayEquals(new Integer[] {}, lista2.toArray()); - Assert.assertArrayEquals(new Integer[] { 3, 2, 1 }, lista1.toArray()); - } +package adt.linkedList; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class StudentLinkedListTest { + + private LinkedList lista1; + private LinkedList lista2; + + @Before + public void setUp() throws Exception { + + getImplementations(); + + // Lista com 3 elementos. + lista1.insert(3); + lista1.insert(2); + lista1.insert(1); + + } + + private void getImplementations() { + // TODO O aluno deve ajustar aqui para instanciar sua implementação + lista1 = new SingleLinkedListImpl(); + lista2 = new SingleLinkedListImpl(); + } + + @Test + public void testIsEmpty() { + Assert.assertFalse(lista1.isEmpty()); + Assert.assertTrue(lista2.isEmpty()); + } + + @Test + public void testSize() { + Assert.assertEquals(3, lista1.size()); + Assert.assertEquals(0, lista2.size()); + } + + @Test + public void testSearch() { + Assert.assertTrue(2 == lista1.search(2)); + Assert.assertNull(lista1.search(4)); + Assert.assertFalse(3 == lista1.search(2)); + } + + @Test + public void testInsert() { + Assert.assertEquals(3, lista1.size()); + lista1.insert(5); + lista1.insert(7); + Assert.assertEquals(5, lista1.size()); + + Assert.assertEquals(0, lista2.size()); + lista2.insert(4); + lista2.insert(7); + Assert.assertEquals(2, lista2.size()); + } + + @Test + public void testRemove() { + Assert.assertEquals(3, lista1.size()); + lista1.remove(2); + lista1.remove(1); + Assert.assertEquals(1, lista1.size()); + + } + + @Test + public void testToArray() { + Assert.assertArrayEquals(new Integer[] {}, lista2.toArray()); + Assert.assertArrayEquals(new Integer[] { 3, 2, 1 }, lista1.toArray()); + } } \ No newline at end of file diff --git a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/pom.xml b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/pom.xml index 4692f1e47..9e3ade5e2 100644 --- a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/pom.xml +++ b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/pom.xml @@ -1,98 +1,98 @@ - - 4.0.0 - - br.edu.ufcg.ccc - submission - 1.0 - jar - Submissao de roteiro - - - - ufcg-leda - http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda - default - - true - always - - - - - - - junit - junit - 4.12 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - maven-clean-plugin - 3.0.0 - - - auto-clean - build - - clean - - - - - - - org.walkmod - maven-walkmod-plugin - 1.3 - - walkmod.xml - - - - package - - apply - - - false - - - - - - br.edu.ufcg.ccc - leda-compactor-tool - 1.0.0-SNAPSHOT - - - install - - compact - - - - 116110761 - - R07-01 - - 2017.1 - http://150.165.85.29:81/submitAtividade - - - - - - - + + 4.0.0 + + br.edu.ufcg.ccc + submission + 1.0 + jar + Submissao de roteiro + + + + ufcg-leda + http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda + default + + true + always + + + + + + + junit + junit + 4.12 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + maven-clean-plugin + 3.0.0 + + + auto-clean + build + + clean + + + + + + + org.walkmod + maven-walkmod-plugin + 1.3 + + walkmod.xml + + + + package + + apply + + + false + + + + + + br.edu.ufcg.ccc + leda-compactor-tool + 1.0.0-SNAPSHOT + + + install + + compact + + + + 116110761 + + R07-01 + + 2017.1 + http://150.165.85.29:81/submitAtividade + + + + + + + diff --git a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/linkedList/DoubleLinkedList.java b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/linkedList/DoubleLinkedList.java index b13faec8d..4bcc55715 100644 --- a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/linkedList/DoubleLinkedList.java +++ b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/linkedList/DoubleLinkedList.java @@ -1,29 +1,29 @@ -package adt.linkedList; - -/** - * The interface of a double linked list with a head and a last (Deque). - * - * @param - */ -public interface DoubleLinkedList extends LinkedList { - - /** - * Inserts a new element in the first position (head) of the list. The - * "head" reference must be updated. - * - * @param element - */ - public void insertFirst(T element); - - /** - * Removes the first element (head) of the list. The "head" reference must - * be updated. - */ - public void removeFirst(); - - /** - * Removes the last element (last) of the list. The "last" reference must be - * updated. - */ - public void removeLast(); -} +package adt.linkedList; + +/** + * The interface of a double linked list with a head and a last (Deque). + * + * @param + */ +public interface DoubleLinkedList extends LinkedList { + + /** + * Inserts a new element in the first position (head) of the list. The + * "head" reference must be updated. + * + * @param element + */ + public void insertFirst(T element); + + /** + * Removes the first element (head) of the list. The "head" reference must + * be updated. + */ + public void removeFirst(); + + /** + * Removes the last element (last) of the list. The "last" reference must be + * updated. + */ + public void removeLast(); +} diff --git a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/linkedList/LinkedList.java b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/linkedList/LinkedList.java index 1fafeb6c2..3cc2d3776 100644 --- a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/linkedList/LinkedList.java +++ b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/linkedList/LinkedList.java @@ -1,53 +1,53 @@ -package adt.linkedList; - -/** - * The interface of a generic linked list. - */ -public interface LinkedList { - /** - * @return true if the list is empty or false, otherwise - */ - public boolean isEmpty(); - - /** - * @return the number of elements on the list - */ - public int size(); - - /** - * Searches for a given element in the list. - * - * @param element - * the element being searched for - * @return the element if it is in the list or null, otherwise - */ - public T search(T element); - - /** - * Inserts a new element at the end of the list. Null elements must be - * ignored. - * - * @param element - * the element to be inserted - */ - public void insert(T element); - - /** - * Removes an element from the list. If the element does not exist the list - * is not changed. - * - * @param element - * the element to be removed - */ - public void remove(T element); - - /** - * Returns an array containing all elements in the structure. The array does - * not contain empty spaces (or null elements). The elements are put into - * the array from the beginning to the end of the list. - * - * @return an array containing all elements in the structure in the order - * they appear - */ - public T[] toArray(); +package adt.linkedList; + +/** + * The interface of a generic linked list. + */ +public interface LinkedList { + /** + * @return true if the list is empty or false, otherwise + */ + public boolean isEmpty(); + + /** + * @return the number of elements on the list + */ + public int size(); + + /** + * Searches for a given element in the list. + * + * @param element + * the element being searched for + * @return the element if it is in the list or null, otherwise + */ + public T search(T element); + + /** + * Inserts a new element at the end of the list. Null elements must be + * ignored. + * + * @param element + * the element to be inserted + */ + public void insert(T element); + + /** + * Removes an element from the list. If the element does not exist the list + * is not changed. + * + * @param element + * the element to be removed + */ + public void remove(T element); + + /** + * Returns an array containing all elements in the structure. The array does + * not contain empty spaces (or null elements). The elements are put into + * the array from the beginning to the end of the list. + * + * @return an array containing all elements in the structure in the order + * they appear + */ + public T[] toArray(); } \ No newline at end of file diff --git a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/linkedList/RecursiveDoubleLinkedListImpl.java b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/linkedList/RecursiveDoubleLinkedListImpl.java index 7d92749d9..62a71e8c0 100644 --- a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/linkedList/RecursiveDoubleLinkedListImpl.java +++ b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/linkedList/RecursiveDoubleLinkedListImpl.java @@ -1,80 +1,80 @@ -package adt.linkedList; - -public class RecursiveDoubleLinkedListImpl extends RecursiveSingleLinkedListImpl implements DoubleLinkedList { - - protected RecursiveDoubleLinkedListImpl previous; - - public RecursiveDoubleLinkedListImpl() { - - } - - public RecursiveDoubleLinkedListImpl(T data, RecursiveSingleLinkedListImpl next, - RecursiveDoubleLinkedListImpl previous) { - super(data, next); - this.previous = previous; - } - - @Override - public void insertFirst(T element) { - if (element != null) { - if (isEmpty()) { - insert(element); - } else { - setPrevious(new RecursiveDoubleLinkedListImpl(element, this, new RecursiveDoubleLinkedListImpl())); - } - } - } - - @Override - public void removeFirst() { - if (!(isEmpty())) { - if (getNext() != null) { - setData(getNext().getData()); - ((RecursiveDoubleLinkedListImpl) getNext()).removeFirst(); - } else { - removeLast(); - } - } - } - - @Override - public void removeLast() { - if (!(isEmpty())) { - if (getNext().isEmpty()) { - setData(null); - setNext(null); - } else { - ((RecursiveDoubleLinkedListImpl) getNext()).removeLast(); - } - } - } - - @Override - public void insert(T element) { - if (element != null) { - if (isEmpty()) { - setData(element); - RecursiveDoubleLinkedListImpl nextNIL = new RecursiveDoubleLinkedListImpl(); - setNext(nextNIL); - nextNIL.setPrevious(this); - if (getPrevious() == null) { - RecursiveDoubleLinkedListImpl prevNIL = new RecursiveDoubleLinkedListImpl(); - setPrevious(prevNIL); - prevNIL.setNext(this); - } - } else { - getNext().insert(element); - - } - } - } - - public RecursiveDoubleLinkedListImpl getPrevious() { - return previous; - } - - public void setPrevious(RecursiveDoubleLinkedListImpl previous) { - this.previous = previous; - } - -} +package adt.linkedList; + +public class RecursiveDoubleLinkedListImpl extends RecursiveSingleLinkedListImpl implements DoubleLinkedList { + + protected RecursiveDoubleLinkedListImpl previous; + + public RecursiveDoubleLinkedListImpl() { + + } + + public RecursiveDoubleLinkedListImpl(T data, RecursiveSingleLinkedListImpl next, + RecursiveDoubleLinkedListImpl previous) { + super(data, next); + this.previous = previous; + } + + @Override + public void insertFirst(T element) { + if (element != null) { + if (isEmpty()) { + insert(element); + } else { + setPrevious(new RecursiveDoubleLinkedListImpl(element, this, new RecursiveDoubleLinkedListImpl())); + } + } + } + + @Override + public void removeFirst() { + if (!(isEmpty())) { + if (getNext() != null) { + setData(getNext().getData()); + ((RecursiveDoubleLinkedListImpl) getNext()).removeFirst(); + } else { + removeLast(); + } + } + } + + @Override + public void removeLast() { + if (!(isEmpty())) { + if (getNext().isEmpty()) { + setData(null); + setNext(null); + } else { + ((RecursiveDoubleLinkedListImpl) getNext()).removeLast(); + } + } + } + + @Override + public void insert(T element) { + if (element != null) { + if (isEmpty()) { + setData(element); + RecursiveDoubleLinkedListImpl nextNIL = new RecursiveDoubleLinkedListImpl(); + setNext(nextNIL); + nextNIL.setPrevious(this); + if (getPrevious() == null) { + RecursiveDoubleLinkedListImpl prevNIL = new RecursiveDoubleLinkedListImpl(); + setPrevious(prevNIL); + prevNIL.setNext(this); + } + } else { + getNext().insert(element); + + } + } + } + + public RecursiveDoubleLinkedListImpl getPrevious() { + return previous; + } + + public void setPrevious(RecursiveDoubleLinkedListImpl previous) { + this.previous = previous; + } + +} diff --git a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/linkedList/RecursiveSingleLinkedListImpl.java b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/linkedList/RecursiveSingleLinkedListImpl.java index 357b6a63d..c1ac3be51 100644 --- a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/linkedList/RecursiveSingleLinkedListImpl.java +++ b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/linkedList/RecursiveSingleLinkedListImpl.java @@ -1,109 +1,109 @@ -package adt.linkedList; - -public class RecursiveSingleLinkedListImpl implements LinkedList { - - protected T data; - protected RecursiveSingleLinkedListImpl next; - - public RecursiveSingleLinkedListImpl() { - - } - - public RecursiveSingleLinkedListImpl(T data, RecursiveSingleLinkedListImpl next) { - this.data = data; - this.next = next; - } - - @Override - public boolean isEmpty() { - boolean result = false; - if (getData() == null) { - result = true; - } - return result; - } - - @Override - public int size() { - int result = 0; - if (!(isEmpty())) { - result = 1 + getNext().size(); - } - return result; - } - - @Override - public T search(T element) { - T result = null; - if (element != null) { - if (!(isEmpty())) { - if (getData().equals(element)) { - result = data; - } else { - result = getNext().search(element); - } - } - } - return result; - } - - @Override - public void insert(T element) { - if (element != null) { - if (isEmpty()) { - setData(element); - setNext(new RecursiveSingleLinkedListImpl()); - } else { - getNext().insert(element); - } - } - } - - @Override - public void remove(T element) { - if (element != null) { - if (!(isEmpty())) { - if (getData().equals(element)) { - setData(getNext().getData()); - setNext(getNext().getNext()); - } else { - getNext().remove(element); - } - } - } - - } - - @Override - public T[] toArray() { - @SuppressWarnings("unchecked") - T[] array = (T[]) new Object[this.size()]; - addArray(array, this, 0); - return array; - } - - private void addArray(T[] array, RecursiveSingleLinkedListImpl node, int i) { - if (!(node.isEmpty())) { - array[i] = node.getData(); - addArray(array, node.getNext(), ++i); - } - - } - - public T getData() { - return data; - } - - public void setData(T data) { - this.data = data; - } - - public RecursiveSingleLinkedListImpl getNext() { - return next; - } - - public void setNext(RecursiveSingleLinkedListImpl next) { - this.next = next; - } - -} +package adt.linkedList; + +public class RecursiveSingleLinkedListImpl implements LinkedList { + + protected T data; + protected RecursiveSingleLinkedListImpl next; + + public RecursiveSingleLinkedListImpl() { + + } + + public RecursiveSingleLinkedListImpl(T data, RecursiveSingleLinkedListImpl next) { + this.data = data; + this.next = next; + } + + @Override + public boolean isEmpty() { + boolean result = false; + if (getData() == null) { + result = true; + } + return result; + } + + @Override + public int size() { + int result = 0; + if (!(isEmpty())) { + result = 1 + getNext().size(); + } + return result; + } + + @Override + public T search(T element) { + T result = null; + if (element != null) { + if (!(isEmpty())) { + if (getData().equals(element)) { + result = data; + } else { + result = getNext().search(element); + } + } + } + return result; + } + + @Override + public void insert(T element) { + if (element != null) { + if (isEmpty()) { + setData(element); + setNext(new RecursiveSingleLinkedListImpl()); + } else { + getNext().insert(element); + } + } + } + + @Override + public void remove(T element) { + if (element != null) { + if (!(isEmpty())) { + if (getData().equals(element)) { + setData(getNext().getData()); + setNext(getNext().getNext()); + } else { + getNext().remove(element); + } + } + } + + } + + @Override + public T[] toArray() { + @SuppressWarnings("unchecked") + T[] array = (T[]) new Object[this.size()]; + addArray(array, this, 0); + return array; + } + + private void addArray(T[] array, RecursiveSingleLinkedListImpl node, int i) { + if (!(node.isEmpty())) { + array[i] = node.getData(); + addArray(array, node.getNext(), ++i); + } + + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public RecursiveSingleLinkedListImpl getNext() { + return next; + } + + public void setNext(RecursiveSingleLinkedListImpl next) { + this.next = next; + } + +} diff --git a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/stack/Stack.java b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/stack/Stack.java index 6760db4e3..09dace39a 100644 --- a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/stack/Stack.java +++ b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/stack/Stack.java @@ -1,50 +1,50 @@ -package adt.stack; - -/** - * The interface of a generic stack. The queue is able to store any kind of - * data. - * - */ -public interface Stack { - - /** - * Inserts a new element in the stack or returns an exception if the stack - * is full. Null elements are not allowed (the stack remains unchanged). - * - * @param element - * @throws StackOverflowException - */ - public void push(T element) throws StackOverflowException; - - /** - * If the stack has elements, it removes the top of the stack and returns - * it; otherwise, it returns an exception. - * - * @return - * @throws StackUnderflowException - */ - public T pop() throws StackUnderflowException; - - /** - * Returns (without removing) the top element of the stack or null if the - * stack is empty. - * - * @return - */ - public T top(); - - /** - * Returns true if the stack is empty or false, otherwise. - * - * @return - */ - public boolean isEmpty(); - - /** - * Returns true if the stack is full or false, otherwise. - * - * @return - */ - public boolean isFull(); - -} +package adt.stack; + +/** + * The interface of a generic stack. The queue is able to store any kind of + * data. + * + */ +public interface Stack { + + /** + * Inserts a new element in the stack or returns an exception if the stack + * is full. Null elements are not allowed (the stack remains unchanged). + * + * @param element + * @throws StackOverflowException + */ + public void push(T element) throws StackOverflowException; + + /** + * If the stack has elements, it removes the top of the stack and returns + * it; otherwise, it returns an exception. + * + * @return + * @throws StackUnderflowException + */ + public T pop() throws StackUnderflowException; + + /** + * Returns (without removing) the top element of the stack or null if the + * stack is empty. + * + * @return + */ + public T top(); + + /** + * Returns true if the stack is empty or false, otherwise. + * + * @return + */ + public boolean isEmpty(); + + /** + * Returns true if the stack is full or false, otherwise. + * + * @return + */ + public boolean isFull(); + +} diff --git a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/stack/StackOverflowException.java b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/stack/StackOverflowException.java index 48b51fbe9..0d322ebfb 100644 --- a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/stack/StackOverflowException.java +++ b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/stack/StackOverflowException.java @@ -1,9 +1,9 @@ -package adt.stack; - -public class StackOverflowException extends Exception { - - public StackOverflowException() { - super("Stack is full"); - } - -} +package adt.stack; + +public class StackOverflowException extends Exception { + + public StackOverflowException() { + super("Stack is full"); + } + +} diff --git a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/stack/StackRecursiveDoubleLinkedListImpl.java b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/stack/StackRecursiveDoubleLinkedListImpl.java index 4bea32f38..67571ec12 100644 --- a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/stack/StackRecursiveDoubleLinkedListImpl.java +++ b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/stack/StackRecursiveDoubleLinkedListImpl.java @@ -1,54 +1,54 @@ -package adt.stack; - -import adt.linkedList.DoubleLinkedList; -import adt.linkedList.RecursiveDoubleLinkedListImpl; -import adt.linkedList.RecursiveSingleLinkedListImpl; - -public class StackRecursiveDoubleLinkedListImpl implements Stack { - - protected DoubleLinkedList top; - protected int size; - - public StackRecursiveDoubleLinkedListImpl(int size) { - this.size = size; - this.top = new RecursiveDoubleLinkedListImpl(); - } - - @Override - public void push(T element) throws StackOverflowException { - if (isFull()) { - throw new StackOverflowException(); - } else { - top.insertFirst(element); - } - - } - - @Override - public T pop() throws StackUnderflowException { - if (isEmpty()) { - throw new StackUnderflowException(); - } else { - T result = top(); - top.removeFirst(); - return result; - } - } - - @SuppressWarnings("unchecked") - @Override - public T top() { - return ((RecursiveSingleLinkedListImpl) top).getData(); - } - - @Override - public boolean isEmpty() { - return top.isEmpty(); - } - - @Override - public boolean isFull() { - return top.size() == size; - } - -} +package adt.stack; + +import adt.linkedList.DoubleLinkedList; +import adt.linkedList.RecursiveDoubleLinkedListImpl; +import adt.linkedList.RecursiveSingleLinkedListImpl; + +public class StackRecursiveDoubleLinkedListImpl implements Stack { + + protected DoubleLinkedList top; + protected int size; + + public StackRecursiveDoubleLinkedListImpl(int size) { + this.size = size; + this.top = new RecursiveDoubleLinkedListImpl(); + } + + @Override + public void push(T element) throws StackOverflowException { + if (isFull()) { + throw new StackOverflowException(); + } else { + top.insertFirst(element); + } + + } + + @Override + public T pop() throws StackUnderflowException { + if (isEmpty()) { + throw new StackUnderflowException(); + } else { + T result = top(); + top.removeFirst(); + return result; + } + } + + @SuppressWarnings("unchecked") + @Override + public T top() { + return ((RecursiveSingleLinkedListImpl) top).getData(); + } + + @Override + public boolean isEmpty() { + return top.isEmpty(); + } + + @Override + public boolean isFull() { + return top.size() == size; + } + +} diff --git a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/stack/StackUnderflowException.java b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/stack/StackUnderflowException.java index 571562b67..5a1973c62 100644 --- a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/stack/StackUnderflowException.java +++ b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/main/java/adt/stack/StackUnderflowException.java @@ -1,8 +1,8 @@ -package adt.stack; - -public class StackUnderflowException extends Exception { - - public StackUnderflowException() { - super("Stack is empty"); - } -} +package adt.stack; + +public class StackUnderflowException extends Exception { + + public StackUnderflowException() { + super("Stack is empty"); + } +} diff --git a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/test/java/adt/linkedList/StudentDoubleLinkedListTest.java b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/test/java/adt/linkedList/StudentDoubleLinkedListTest.java index ceeb08b3d..f5b786623 100644 --- a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/test/java/adt/linkedList/StudentDoubleLinkedListTest.java +++ b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/test/java/adt/linkedList/StudentDoubleLinkedListTest.java @@ -1,100 +1,100 @@ -package adt.linkedList; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class StudentDoubleLinkedListTest { - - private DoubleLinkedList lista1; - private DoubleLinkedList lista2; - private DoubleLinkedList lista3; - - @Before - public void setUp() throws Exception { - - getImplementations(); - - // Lista com 3 elementos. - lista1.insert(3); - lista1.insert(2); - lista1.insert(1); - - // Lista com 1 elemento. - lista3.insert(1); - } - - private void getImplementations() { - // TODO O aluno deve ajustar aqui para instanciar sua implementação - lista1 = new RecursiveDoubleLinkedListImpl(); - lista2 = new RecursiveDoubleLinkedListImpl(); - lista3 = new RecursiveDoubleLinkedListImpl(); - } - - // Métodos de DoubleLinkedList - - @Test - public void testInsertFirst() { - lista1.insertFirst(4); - Assert.assertArrayEquals(new Integer[] { 4, 3, 2, 1 }, lista1.toArray()); - } - - @Test - public void testRemoveFirst() { - lista1.removeFirst(); - Assert.assertArrayEquals(new Integer[] { 2, 1 }, lista1.toArray()); - } - - @Test - public void testRemoveLast() { - lista1.removeLast(); - Assert.assertArrayEquals(new Integer[] { 3, 2 }, lista1.toArray()); - } - - @Test - public void testIsEmpty() { - Assert.assertFalse(lista1.isEmpty()); - Assert.assertTrue(lista2.isEmpty()); - } - - @Test - public void testSize() { - Assert.assertEquals(3, lista1.size()); - Assert.assertEquals(0, lista2.size()); - } - - @Test - public void testSearch() { - Assert.assertTrue(2 == lista1.search(2)); - Assert.assertNull(lista1.search(4)); - Assert.assertFalse(3 == lista1.search(2)); - } - - @Test - public void testInsert() { - Assert.assertEquals(3, lista1.size()); - lista1.insert(5); - lista1.insert(7); - Assert.assertEquals(5, lista1.size()); - - Assert.assertEquals(0, lista2.size()); - lista2.insert(4); - lista2.insert(7); - Assert.assertEquals(2, lista2.size()); - } - - @Test - public void testRemove() { - Assert.assertEquals(3, lista1.size()); - lista1.remove(2); - lista1.remove(1); - Assert.assertEquals(1, lista1.size()); - - } - - @Test - public void testToArray() { - Assert.assertArrayEquals(new Integer[] {}, lista2.toArray()); - Assert.assertArrayEquals(new Integer[] { 3, 2, 1 }, lista1.toArray()); - } +package adt.linkedList; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class StudentDoubleLinkedListTest { + + private DoubleLinkedList lista1; + private DoubleLinkedList lista2; + private DoubleLinkedList lista3; + + @Before + public void setUp() throws Exception { + + getImplementations(); + + // Lista com 3 elementos. + lista1.insert(3); + lista1.insert(2); + lista1.insert(1); + + // Lista com 1 elemento. + lista3.insert(1); + } + + private void getImplementations() { + // TODO O aluno deve ajustar aqui para instanciar sua implementação + lista1 = new RecursiveDoubleLinkedListImpl(); + lista2 = new RecursiveDoubleLinkedListImpl(); + lista3 = new RecursiveDoubleLinkedListImpl(); + } + + // Métodos de DoubleLinkedList + + @Test + public void testInsertFirst() { + lista1.insertFirst(4); + Assert.assertArrayEquals(new Integer[] { 4, 3, 2, 1 }, lista1.toArray()); + } + + @Test + public void testRemoveFirst() { + lista1.removeFirst(); + Assert.assertArrayEquals(new Integer[] { 2, 1 }, lista1.toArray()); + } + + @Test + public void testRemoveLast() { + lista1.removeLast(); + Assert.assertArrayEquals(new Integer[] { 3, 2 }, lista1.toArray()); + } + + @Test + public void testIsEmpty() { + Assert.assertFalse(lista1.isEmpty()); + Assert.assertTrue(lista2.isEmpty()); + } + + @Test + public void testSize() { + Assert.assertEquals(3, lista1.size()); + Assert.assertEquals(0, lista2.size()); + } + + @Test + public void testSearch() { + Assert.assertTrue(2 == lista1.search(2)); + Assert.assertNull(lista1.search(4)); + Assert.assertFalse(3 == lista1.search(2)); + } + + @Test + public void testInsert() { + Assert.assertEquals(3, lista1.size()); + lista1.insert(5); + lista1.insert(7); + Assert.assertEquals(5, lista1.size()); + + Assert.assertEquals(0, lista2.size()); + lista2.insert(4); + lista2.insert(7); + Assert.assertEquals(2, lista2.size()); + } + + @Test + public void testRemove() { + Assert.assertEquals(3, lista1.size()); + lista1.remove(2); + lista1.remove(1); + Assert.assertEquals(1, lista1.size()); + + } + + @Test + public void testToArray() { + Assert.assertArrayEquals(new Integer[] {}, lista2.toArray()); + Assert.assertArrayEquals(new Integer[] { 3, 2, 1 }, lista1.toArray()); + } } \ No newline at end of file diff --git a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/test/java/adt/linkedList/StudentLinkedListTest.java b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/test/java/adt/linkedList/StudentLinkedListTest.java index 673f92f77..2db60c68d 100644 --- a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/test/java/adt/linkedList/StudentLinkedListTest.java +++ b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/src/test/java/adt/linkedList/StudentLinkedListTest.java @@ -1,76 +1,76 @@ -package adt.linkedList; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class StudentLinkedListTest { - - private LinkedList lista1; - private LinkedList lista2; - - @Before - public void setUp() throws Exception { - - getImplementations(); - - // Lista com 3 elementos. - lista1.insert(3); - lista1.insert(2); - lista1.insert(1); - - } - - private void getImplementations() { - // TODO O aluno deve ajustar aqui para instanciar sua implementação - lista1 = new RecursiveSingleLinkedListImpl(); - lista2 = new RecursiveSingleLinkedListImpl();; - } - - @Test - public void testIsEmpty() { - Assert.assertFalse(lista1.isEmpty()); - Assert.assertTrue(lista2.isEmpty()); - } - - @Test - public void testSize() { - Assert.assertEquals(3, lista1.size()); - Assert.assertEquals(0, lista2.size()); - } - - @Test - public void testSearch() { - Assert.assertTrue(2 == lista1.search(2)); - Assert.assertNull(lista1.search(4)); - Assert.assertFalse(3 == lista1.search(2)); - } - - @Test - public void testInsert() { - Assert.assertEquals(3, lista1.size()); - lista1.insert(5); - lista1.insert(7); - Assert.assertEquals(5, lista1.size()); - - Assert.assertEquals(0, lista2.size()); - lista2.insert(4); - lista2.insert(7); - Assert.assertEquals(2, lista2.size()); - } - - @Test - public void testRemove() { - Assert.assertEquals(3, lista1.size()); - lista1.remove(2); - lista1.remove(1); - Assert.assertEquals(1, lista1.size()); - - } - - @Test - public void testToArray() { - Assert.assertArrayEquals(new Integer[] {}, lista2.toArray()); - Assert.assertArrayEquals(new Integer[] { 3, 2, 1 }, lista1.toArray()); - } +package adt.linkedList; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class StudentLinkedListTest { + + private LinkedList lista1; + private LinkedList lista2; + + @Before + public void setUp() throws Exception { + + getImplementations(); + + // Lista com 3 elementos. + lista1.insert(3); + lista1.insert(2); + lista1.insert(1); + + } + + private void getImplementations() { + // TODO O aluno deve ajustar aqui para instanciar sua implementação + lista1 = new RecursiveSingleLinkedListImpl(); + lista2 = new RecursiveSingleLinkedListImpl();; + } + + @Test + public void testIsEmpty() { + Assert.assertFalse(lista1.isEmpty()); + Assert.assertTrue(lista2.isEmpty()); + } + + @Test + public void testSize() { + Assert.assertEquals(3, lista1.size()); + Assert.assertEquals(0, lista2.size()); + } + + @Test + public void testSearch() { + Assert.assertTrue(2 == lista1.search(2)); + Assert.assertNull(lista1.search(4)); + Assert.assertFalse(3 == lista1.search(2)); + } + + @Test + public void testInsert() { + Assert.assertEquals(3, lista1.size()); + lista1.insert(5); + lista1.insert(7); + Assert.assertEquals(5, lista1.size()); + + Assert.assertEquals(0, lista2.size()); + lista2.insert(4); + lista2.insert(7); + Assert.assertEquals(2, lista2.size()); + } + + @Test + public void testRemove() { + Assert.assertEquals(3, lista1.size()); + lista1.remove(2); + lista1.remove(1); + Assert.assertEquals(1, lista1.size()); + + } + + @Test + public void testToArray() { + Assert.assertArrayEquals(new Integer[] {}, lista2.toArray()); + Assert.assertArrayEquals(new Integer[] { 3, 2, 1 }, lista1.toArray()); + } } \ No newline at end of file diff --git a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/target/classes/META-INF/MANIFEST.MF b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/target/classes/META-INF/MANIFEST.MF index 6c4b9cc34..a05e7910c 100644 --- a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/target/classes/META-INF/MANIFEST.MF +++ b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/target/classes/META-INF/MANIFEST.MF @@ -1,5 +1,5 @@ -Manifest-Version: 1.0 -Built-By: amintas -Build-Jdk: 1.8.0_131 -Created-By: Maven Integration for Eclipse - +Manifest-Version: 1.0 +Built-By: amintas +Build-Jdk: 1.8.0_131 +Created-By: Maven Integration for Eclipse + diff --git a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml index 4692f1e47..9e3ade5e2 100644 --- a/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml +++ b/java/R07-01-Rot-Linked-list-abordagem-recursiva-environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml @@ -1,98 +1,98 @@ - - 4.0.0 - - br.edu.ufcg.ccc - submission - 1.0 - jar - Submissao de roteiro - - - - ufcg-leda - http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda - default - - true - always - - - - - - - junit - junit - 4.12 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - maven-clean-plugin - 3.0.0 - - - auto-clean - build - - clean - - - - - - - org.walkmod - maven-walkmod-plugin - 1.3 - - walkmod.xml - - - - package - - apply - - - false - - - - - - br.edu.ufcg.ccc - leda-compactor-tool - 1.0.0-SNAPSHOT - - - install - - compact - - - - 116110761 - - R07-01 - - 2017.1 - http://150.165.85.29:81/submitAtividade - - - - - - - + + 4.0.0 + + br.edu.ufcg.ccc + submission + 1.0 + jar + Submissao de roteiro + + + + ufcg-leda + http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda + default + + true + always + + + + + + + junit + junit + 4.12 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + maven-clean-plugin + 3.0.0 + + + auto-clean + build + + clean + + + + + + + org.walkmod + maven-walkmod-plugin + 1.3 + + walkmod.xml + + + + package + + apply + + + false + + + + + + br.edu.ufcg.ccc + leda-compactor-tool + 1.0.0-SNAPSHOT + + + install + + compact + + + + 116110761 + + R07-01 + + 2017.1 + http://150.165.85.29:81/submitAtividade + + + + + + + diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/pom.xml b/java/R08-01-Rot-TabelaHash-EndFechado--environment/pom.xml index 4412de2fa..40c340bb7 100644 --- a/java/R08-01-Rot-TabelaHash-EndFechado--environment/pom.xml +++ b/java/R08-01-Rot-TabelaHash-EndFechado--environment/pom.xml @@ -1,98 +1,98 @@ - - 4.0.0 - - br.edu.ufcg.ccc - submission - 1.0 - jar - Submissao de roteiro - - - - ufcg-leda - http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda - default - - true - always - - - - - - - junit - junit - 4.12 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - maven-clean-plugin - 3.0.0 - - - auto-clean - build - - clean - - - - - - - org.walkmod - maven-walkmod-plugin - 1.3 - - walkmod.xml - - - - package - - apply - - - false - - - - - - br.edu.ufcg.ccc - leda-compactor-tool - 1.0.0-SNAPSHOT - - - install - - compact - - - - 116110761 - - R08-01 - - 2017.1 - http://150.165.85.29:81/submitAtividade - - - - - - - + + 4.0.0 + + br.edu.ufcg.ccc + submission + 1.0 + jar + Submissao de roteiro + + + + ufcg-leda + http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda + default + + true + always + + + + + + + junit + junit + 4.12 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + maven-clean-plugin + 3.0.0 + + + auto-clean + build + + clean + + + + + + + org.walkmod + maven-walkmod-plugin + 1.3 + + walkmod.xml + + + + package + + apply + + + false + + + + + + br.edu.ufcg.ccc + leda-compactor-tool + 1.0.0-SNAPSHOT + + + install + + compact + + + + 116110761 + + R08-01 + + 2017.1 + http://150.165.85.29:81/submitAtividade + + + + + + + diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/AbstractHashtable.java b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/AbstractHashtable.java index b93172fb4..f186cdd5a 100644 --- a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/AbstractHashtable.java +++ b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/AbstractHashtable.java @@ -1,67 +1,67 @@ -package adt.hashtable; - -import util.Util; -import adt.hashtable.hashfunction.HashFunction; - -/** - * It represents an abstract implementation of a hashtable, with some internal - * attributes. Note that the kind of the internal array is a parameter because - * hashtable with closed address should have a collection of elements (chaining) - * instead of a single element. Moreover, a hashtable working with open address - * must also manipulate deletions through a special element called DELETED. - * Thus, it must work with Object instead of a generic type T. An - * AbstractHashtable is only a resource for unifying both kinds of hashtables - * (closed and open addressing). Thee real hashtables must inherit this class. - */ -public abstract class AbstractHashtable implements Hashtable { - - protected Object[] table; // the internal table - protected int elements; // the number of elements inserted into the hash - // table - protected int COLLISIONS; // the number of collisions occurred in this - // hashtable - protected HashFunction hashFunction; // the hash function used by this - // hashtable. - - public AbstractHashtable() { - elements = 0; - COLLISIONS = 0; - } - - protected void initiateInternalTable(int size) { - this.table = Util. makeArray(size); - } - - @Override - public boolean isEmpty() { - return (elements == 0); - } - - @Override - public boolean isFull() { - return (elements == table.length); - } - - @Override - public int size() { - return elements; - } - - @Override - public int capacity() { - return this.table.length; - } - - public int getCOLLISIONS() { - return COLLISIONS; - } - - public HashFunction getHashFunction() { - return hashFunction; - } - - public void setHashFunction(HashFunction hashFunction) { - this.hashFunction = hashFunction; - } - -} +package adt.hashtable; + +import util.Util; +import adt.hashtable.hashfunction.HashFunction; + +/** + * It represents an abstract implementation of a hashtable, with some internal + * attributes. Note that the kind of the internal array is a parameter because + * hashtable with closed address should have a collection of elements (chaining) + * instead of a single element. Moreover, a hashtable working with open address + * must also manipulate deletions through a special element called DELETED. + * Thus, it must work with Object instead of a generic type T. An + * AbstractHashtable is only a resource for unifying both kinds of hashtables + * (closed and open addressing). Thee real hashtables must inherit this class. + */ +public abstract class AbstractHashtable implements Hashtable { + + protected Object[] table; // the internal table + protected int elements; // the number of elements inserted into the hash + // table + protected int COLLISIONS; // the number of collisions occurred in this + // hashtable + protected HashFunction hashFunction; // the hash function used by this + // hashtable. + + public AbstractHashtable() { + elements = 0; + COLLISIONS = 0; + } + + protected void initiateInternalTable(int size) { + this.table = Util. makeArray(size); + } + + @Override + public boolean isEmpty() { + return (elements == 0); + } + + @Override + public boolean isFull() { + return (elements == table.length); + } + + @Override + public int size() { + return elements; + } + + @Override + public int capacity() { + return this.table.length; + } + + public int getCOLLISIONS() { + return COLLISIONS; + } + + public HashFunction getHashFunction() { + return hashFunction; + } + + public void setHashFunction(HashFunction hashFunction) { + this.hashFunction = hashFunction; + } + +} diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/Hashtable.java b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/Hashtable.java index 1e9a42907..57747f8f0 100644 --- a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/Hashtable.java +++ b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/Hashtable.java @@ -1,57 +1,57 @@ -package adt.hashtable; - -/** - * The interface of a generic hash table. It keeps values of type T. The table - * can work in two modes: closed address (with chaining) and open address - * (linear probing, quadratic probe, double hashing). - */ -public interface Hashtable { - - /** - * Determines whether this hashtable is empty or not. - */ - public boolean isEmpty(); - - /** - * Determines whether this hashtable is empty or not. Note that this method - * may not make sense in hashtable with closed address, as it works with - * linked lists (or buckets) in each position. - */ - public boolean isFull(); - - /** - * It returns the length of the internal table of this hash table. - */ - public int capacity(); - - /** - * Returns how many values have been inserted into the hash table. - */ - public int size(); - - /** - * Inserts a non-null object into the hash table. The hashtable does not - * work with duplicated elements. Every time that the insert is called, if - * there is a collision, then the attribute COLLISION of this hashtable is - * incremented. - */ - public void insert(T element); - - /** - * Removes an element from the hash table. - */ - public void remove(T element); - - /** - * Searches a given element in the hash table. If it is not in the table, - * the hash table returns null. - */ - public T search(T element); - - /** - * Searches the index of an element in the hashtable. It returns -1 if the - * element is not in the hashtable. - */ - public int indexOf(T element); - -} +package adt.hashtable; + +/** + * The interface of a generic hash table. It keeps values of type T. The table + * can work in two modes: closed address (with chaining) and open address + * (linear probing, quadratic probe, double hashing). + */ +public interface Hashtable { + + /** + * Determines whether this hashtable is empty or not. + */ + public boolean isEmpty(); + + /** + * Determines whether this hashtable is empty or not. Note that this method + * may not make sense in hashtable with closed address, as it works with + * linked lists (or buckets) in each position. + */ + public boolean isFull(); + + /** + * It returns the length of the internal table of this hash table. + */ + public int capacity(); + + /** + * Returns how many values have been inserted into the hash table. + */ + public int size(); + + /** + * Inserts a non-null object into the hash table. The hashtable does not + * work with duplicated elements. Every time that the insert is called, if + * there is a collision, then the attribute COLLISION of this hashtable is + * incremented. + */ + public void insert(T element); + + /** + * Removes an element from the hash table. + */ + public void remove(T element); + + /** + * Searches a given element in the hash table. If it is not in the table, + * the hash table returns null. + */ + public T search(T element); + + /** + * Searches the index of an element in the hashtable. It returns -1 if the + * element is not in the hashtable. + */ + public int indexOf(T element); + +} diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/closed/AbstractHashtableClosedAddress.java b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/closed/AbstractHashtableClosedAddress.java index 9f0b4c479..58d7e0280 100644 --- a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/closed/AbstractHashtableClosedAddress.java +++ b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/closed/AbstractHashtableClosedAddress.java @@ -1,29 +1,29 @@ -package adt.hashtable.closed; - -import java.util.LinkedList; - -import util.Util; -import adt.hashtable.AbstractHashtable; - -/** - * It represents an abstract implementation of a hashtable, with some internal - * attributes. Note that the kind of the internal array is a parameter because - * hashtable with closed address should have a collection of elements (chaining) - * instead of a single element. Moreover, a hashtable working with open address - * must also manipulate deletions through a special element called DELETED. - * Thus, it must work with Object instead of a generic type T. An - * AbstractHashtable is only a resource for unifying both kinds of hashtables - * (closed and open addressing). Thee real hashtables must inherit this class. - */ -public abstract class AbstractHashtableClosedAddress extends - AbstractHashtable { - - public AbstractHashtableClosedAddress() { - super(); - } - - @Override - protected void initiateInternalTable(int size) { - this.table = Util.> makeArray(size); - } -} +package adt.hashtable.closed; + +import java.util.LinkedList; + +import util.Util; +import adt.hashtable.AbstractHashtable; + +/** + * It represents an abstract implementation of a hashtable, with some internal + * attributes. Note that the kind of the internal array is a parameter because + * hashtable with closed address should have a collection of elements (chaining) + * instead of a single element. Moreover, a hashtable working with open address + * must also manipulate deletions through a special element called DELETED. + * Thus, it must work with Object instead of a generic type T. An + * AbstractHashtable is only a resource for unifying both kinds of hashtables + * (closed and open addressing). Thee real hashtables must inherit this class. + */ +public abstract class AbstractHashtableClosedAddress extends + AbstractHashtable { + + public AbstractHashtableClosedAddress() { + super(); + } + + @Override + protected void initiateInternalTable(int size) { + this.table = Util.> makeArray(size); + } +} diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/closed/HashtableClosedAddressImpl.java b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/closed/HashtableClosedAddressImpl.java index a5667eed1..2a1d5092a 100644 --- a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/closed/HashtableClosedAddressImpl.java +++ b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/closed/HashtableClosedAddressImpl.java @@ -1,123 +1,123 @@ -package adt.hashtable.closed; - -import java.util.LinkedList; - -import adt.hashtable.hashfunction.HashFunction; -import adt.hashtable.hashfunction.HashFunctionClosedAddress; -import adt.hashtable.hashfunction.HashFunctionClosedAddressMethod; -import adt.hashtable.hashfunction.HashFunctionFactory; -import util.Util; - -public class HashtableClosedAddressImpl extends AbstractHashtableClosedAddress { - - /** - * A hash table with closed address works with a hash function with closed - * address. Such a function can follow one of these methods: DIVISION or - * MULTIPLICATION. In the DIVISION method, it is useful to change the size - * of the table to an integer that is prime. This can be achieved by - * producing such a prime number that is bigger and close to the desired - * size. - * - * For doing that, you have auxiliary methods: Util.isPrime and - * getPrimeAbove as documented bellow. - * - * The length of the internal table must be the immediate prime number - * greater than the given size. For example, if size=10 then the length must - * be 11. If size=20, the length must be 23. You must implement this idea in - * the auxiliary method getPrimeAbove(int size) and use it. - * - * @param desiredSize - * @param method - */ - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public HashtableClosedAddressImpl(int desiredSize, HashFunctionClosedAddressMethod method) { - int realSize = desiredSize; - - if (method == HashFunctionClosedAddressMethod.DIVISION) { - realSize = this.getPrimeAbove(desiredSize); // real size must the - // the immediate prime - // above - } - initiateInternalTable(realSize); - HashFunction function = HashFunctionFactory.createHashFunction(method, realSize); - this.hashFunction = function; - } - - // AUXILIARY - /** - * It returns the prime number that is closest (and greater) to the given - * number. You can use the method Util.isPrime to check if a number is - * prime. - */ - int getPrimeAbove(int number) { - int nextPrime = number; - while (!(Util.isPrime(nextPrime))) { - nextPrime++; - } - return nextPrime; - } - - @SuppressWarnings("unchecked") - @Override - public void insert(T element) { - if (element != null) { - int index = ((HashFunctionClosedAddress) this.getHashFunction()).hash(element); - if (this.table[index] == null) { - this.table[index] = new LinkedList(); - ((LinkedList) this.table[index]).addFirst(element); - this.elements++; - } else { - if (!((LinkedList) this.table[index]).contains(element)) { - this.COLLISIONS++; - ((LinkedList) this.table[index]).addFirst(element); - this.elements++; - } - - } - - } - - } - - @SuppressWarnings("unchecked") - @Override - public void remove(T element) { - if (element != null) { - int index = ((HashFunctionClosedAddress) this.getHashFunction()).hash(element); - if (this.table[index] != null) { - ((LinkedList) this.table[index]).remove(element); - this.elements--; - } - - } - } - - @SuppressWarnings("unchecked") - @Override - public T search(T element) { - T result = null; - if (element != null) { - int index = ((HashFunctionClosedAddress) this.getHashFunction()).hash(element); - if (this.table[index] != null) { - if (((LinkedList) this.table[index]).contains(element)) { - result = element; - } - } - } - - return result; - } - - @Override - public int indexOf(T element) { - int index = -1; - if (element != null) { - if (search(element) != null) { - index = ((HashFunctionClosedAddress) this.getHashFunction()).hash(element); - } - } - return index; - } - -} +package adt.hashtable.closed; + +import java.util.LinkedList; + +import adt.hashtable.hashfunction.HashFunction; +import adt.hashtable.hashfunction.HashFunctionClosedAddress; +import adt.hashtable.hashfunction.HashFunctionClosedAddressMethod; +import adt.hashtable.hashfunction.HashFunctionFactory; +import util.Util; + +public class HashtableClosedAddressImpl extends AbstractHashtableClosedAddress { + + /** + * A hash table with closed address works with a hash function with closed + * address. Such a function can follow one of these methods: DIVISION or + * MULTIPLICATION. In the DIVISION method, it is useful to change the size + * of the table to an integer that is prime. This can be achieved by + * producing such a prime number that is bigger and close to the desired + * size. + * + * For doing that, you have auxiliary methods: Util.isPrime and + * getPrimeAbove as documented bellow. + * + * The length of the internal table must be the immediate prime number + * greater than the given size. For example, if size=10 then the length must + * be 11. If size=20, the length must be 23. You must implement this idea in + * the auxiliary method getPrimeAbove(int size) and use it. + * + * @param desiredSize + * @param method + */ + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public HashtableClosedAddressImpl(int desiredSize, HashFunctionClosedAddressMethod method) { + int realSize = desiredSize; + + if (method == HashFunctionClosedAddressMethod.DIVISION) { + realSize = this.getPrimeAbove(desiredSize); // real size must the + // the immediate prime + // above + } + initiateInternalTable(realSize); + HashFunction function = HashFunctionFactory.createHashFunction(method, realSize); + this.hashFunction = function; + } + + // AUXILIARY + /** + * It returns the prime number that is closest (and greater) to the given + * number. You can use the method Util.isPrime to check if a number is + * prime. + */ + int getPrimeAbove(int number) { + int nextPrime = number; + while (!(Util.isPrime(nextPrime))) { + nextPrime++; + } + return nextPrime; + } + + @SuppressWarnings("unchecked") + @Override + public void insert(T element) { + if (element != null) { + int index = ((HashFunctionClosedAddress) this.getHashFunction()).hash(element); + if (this.table[index] == null) { + this.table[index] = new LinkedList(); + ((LinkedList) this.table[index]).addFirst(element); + this.elements++; + } else { + if (!((LinkedList) this.table[index]).contains(element)) { + this.COLLISIONS++; + ((LinkedList) this.table[index]).addFirst(element); + this.elements++; + } + + } + + } + + } + + @SuppressWarnings("unchecked") + @Override + public void remove(T element) { + if (element != null) { + int index = ((HashFunctionClosedAddress) this.getHashFunction()).hash(element); + if (this.table[index] != null) { + ((LinkedList) this.table[index]).remove(element); + this.elements--; + } + + } + } + + @SuppressWarnings("unchecked") + @Override + public T search(T element) { + T result = null; + if (element != null) { + int index = ((HashFunctionClosedAddress) this.getHashFunction()).hash(element); + if (this.table[index] != null) { + if (((LinkedList) this.table[index]).contains(element)) { + result = element; + } + } + } + + return result; + } + + @Override + public int indexOf(T element) { + int index = -1; + if (element != null) { + if (search(element) != null) { + index = ((HashFunctionClosedAddress) this.getHashFunction()).hash(element); + } + } + return index; + } + +} diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunction.java b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunction.java index 53999adfc..91cada969 100644 --- a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunction.java +++ b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunction.java @@ -1,9 +1,9 @@ -package adt.hashtable.hashfunction; - -/** - * It represents a generic hash function that will be used by a hashtable to - * calculate indexes in the internal array. - */ -public interface HashFunction { - -} +package adt.hashtable.hashfunction; + +/** + * It represents a generic hash function that will be used by a hashtable to + * calculate indexes in the internal array. + */ +public interface HashFunction { + +} diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionClosedAddress.java b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionClosedAddress.java index dbd8268ab..268c9d1ce 100644 --- a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionClosedAddress.java +++ b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionClosedAddress.java @@ -1,13 +1,13 @@ -package adt.hashtable.hashfunction; - -/** - * It represents a hash function to be used in hashtable that work with closed - * address. - */ -public interface HashFunctionClosedAddress extends HashFunction { - - /** - * The hash function considering closed address. - */ - public int hash(T element); -} +package adt.hashtable.hashfunction; + +/** + * It represents a hash function to be used in hashtable that work with closed + * address. + */ +public interface HashFunctionClosedAddress extends HashFunction { + + /** + * The hash function considering closed address. + */ + public int hash(T element); +} diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionClosedAddressMethod.java b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionClosedAddressMethod.java index 2905e19d9..c48022658 100644 --- a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionClosedAddressMethod.java +++ b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionClosedAddressMethod.java @@ -1,8 +1,8 @@ -package adt.hashtable.hashfunction; - -/** - * The kind of method used by a hash function for closed addressing. - */ -public enum HashFunctionClosedAddressMethod { - DIVISION, MULTIPLICATION; -} +package adt.hashtable.hashfunction; + +/** + * The kind of method used by a hash function for closed addressing. + */ +public enum HashFunctionClosedAddressMethod { + DIVISION, MULTIPLICATION; +} diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionDivisionMethod.java b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionDivisionMethod.java index 3a00f4d6b..27121446a 100644 --- a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionDivisionMethod.java +++ b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionDivisionMethod.java @@ -1,33 +1,33 @@ -package adt.hashtable.hashfunction; - -public class HashFunctionDivisionMethod implements - HashFunctionClosedAddress { - - protected int tableSize; - - public HashFunctionDivisionMethod(int tableSize) { - this.tableSize = tableSize; - } - - /** - * The hash function might use the table size to calculate the hash of any - * object of type T. The hash function has as body h(k) = k % m - * , where k is the key and m is the table size - * (stored in the filed tableSize). - * - * The key is obtained from hashCode method of type T (inherited from Object - * or overridden by you). Thus, if you use a type with hashCode - * implementation, no change is necessary. Otherwise, you must implement the - * hashCde method of T. - */ - @Override - public int hash(T element) { - int hashKey = -1; - int key = element.hashCode(); - - hashKey = (int) key % tableSize; - - return hashKey; - } - -} +package adt.hashtable.hashfunction; + +public class HashFunctionDivisionMethod implements + HashFunctionClosedAddress { + + protected int tableSize; + + public HashFunctionDivisionMethod(int tableSize) { + this.tableSize = tableSize; + } + + /** + * The hash function might use the table size to calculate the hash of any + * object of type T. The hash function has as body h(k) = k % m + * , where k is the key and m is the table size + * (stored in the filed tableSize). + * + * The key is obtained from hashCode method of type T (inherited from Object + * or overridden by you). Thus, if you use a type with hashCode + * implementation, no change is necessary. Otherwise, you must implement the + * hashCde method of T. + */ + @Override + public int hash(T element) { + int hashKey = -1; + int key = element.hashCode(); + + hashKey = (int) key % tableSize; + + return hashKey; + } + +} diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionFactory.java b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionFactory.java index 15c79f424..4193c276d 100644 --- a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionFactory.java +++ b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionFactory.java @@ -1,28 +1,28 @@ -package adt.hashtable.hashfunction; - - -/** - * This class is responsible to create hash functions suitable to each kind of - * hash table. - * - * @author Adalberto - * - */ -public class HashFunctionFactory { - - public static HashFunction createHashFunction( - HashFunctionClosedAddressMethod method, int tableSize) { - HashFunction result = null; - switch (method) { - case DIVISION: - result = new HashFunctionDivisionMethod(tableSize); - break; - case MULTIPLICATION: - result = new HashFunctionMultiplicationMethod(tableSize); - break; - } - - return result; - } - -} +package adt.hashtable.hashfunction; + + +/** + * This class is responsible to create hash functions suitable to each kind of + * hash table. + * + * @author Adalberto + * + */ +public class HashFunctionFactory { + + public static HashFunction createHashFunction( + HashFunctionClosedAddressMethod method, int tableSize) { + HashFunction result = null; + switch (method) { + case DIVISION: + result = new HashFunctionDivisionMethod(tableSize); + break; + case MULTIPLICATION: + result = new HashFunctionMultiplicationMethod(tableSize); + break; + } + + return result; + } + +} diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionMultiplicationMethod.java b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionMultiplicationMethod.java index c1f149c7a..3260082b8 100644 --- a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionMultiplicationMethod.java +++ b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/adt/hashtable/hashfunction/HashFunctionMultiplicationMethod.java @@ -1,35 +1,35 @@ -package adt.hashtable.hashfunction; - -public class HashFunctionMultiplicationMethod implements - HashFunctionClosedAddress { - - protected int tableSize; - private static final double A = (Math.sqrt(5) - 1) / 2; - - public HashFunctionMultiplicationMethod(int tableSize) { - this.tableSize = tableSize; - } - - /** - * The hash function might use the table size to calculate the hash of any - * object of type T. The hash function has as body - * h(k) = m (kA % 1), where k is the key and - * m is the table size (stored in the filed - * tableSize) and A is the constant defined - * (Math.sqrt(5)-1)/2 . - * - * The key is obtained from hashCode method of type T (inherited from Object - * or overridden by you). Thus, if you use a type with hashCode - * implementation, no change is necessary. Otherwise, you must implement the - * hashCde method of T. - */ - @Override - public int hash(T element) { - int hashKey = -1; - int key = element.hashCode(); - double fractionalPart = key * A - Math.floor(key * A); - hashKey = (int) (tableSize * fractionalPart); - - return hashKey; - } -} +package adt.hashtable.hashfunction; + +public class HashFunctionMultiplicationMethod implements + HashFunctionClosedAddress { + + protected int tableSize; + private static final double A = (Math.sqrt(5) - 1) / 2; + + public HashFunctionMultiplicationMethod(int tableSize) { + this.tableSize = tableSize; + } + + /** + * The hash function might use the table size to calculate the hash of any + * object of type T. The hash function has as body + * h(k) = m (kA % 1), where k is the key and + * m is the table size (stored in the filed + * tableSize) and A is the constant defined + * (Math.sqrt(5)-1)/2 . + * + * The key is obtained from hashCode method of type T (inherited from Object + * or overridden by you). Thus, if you use a type with hashCode + * implementation, no change is necessary. Otherwise, you must implement the + * hashCde method of T. + */ + @Override + public int hash(T element) { + int hashKey = -1; + int key = element.hashCode(); + double fractionalPart = key * A - Math.floor(key * A); + hashKey = (int) (tableSize * fractionalPart); + + return hashKey; + } +} diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/util/Util.java b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/util/Util.java index 4e4e1e280..337567b10 100644 --- a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/util/Util.java +++ b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/main/java/util/Util.java @@ -1,64 +1,64 @@ -package util; - -/** - * Class containing useful methods for arrays manipulation. - */ -public class Util { - - /** - * Swaps the contents of two positions in an array. - * - * @param array - * The array to be modified, not null - * @param i - * One of the target positions - * @param j - * The other target position - */ - public static void swap(Object[] array, int i, int j) { - if (array == null) - throw new IllegalArgumentException(); - - Object temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } - - /** - * Creates a generic array of the specified size. - *

- * Ex.: {@code Util.makeArray(10);} - * - * @param size - * The desired size - * @return An array of the type and size chosen - */ - public static T[] makeArray(int size) { - @SuppressWarnings("unchecked") - T[] array = (T[]) new Object[size]; - return array; - } - - public static T[] makeArrayOfComparable(int size) { - @SuppressWarnings("unchecked") - T[] array = (T[]) new Comparable[size]; - return array; - } - - /** - * It says if a specific number is prime or not. - * - * @param n - * @return - */ - public static boolean isPrime(long n) { - boolean result = true; - for (int i = 2; i < n; i++) { - if (n % i == 0) { - result = false; - break; - } - } - return result; - } +package util; + +/** + * Class containing useful methods for arrays manipulation. + */ +public class Util { + + /** + * Swaps the contents of two positions in an array. + * + * @param array + * The array to be modified, not null + * @param i + * One of the target positions + * @param j + * The other target position + */ + public static void swap(Object[] array, int i, int j) { + if (array == null) + throw new IllegalArgumentException(); + + Object temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + /** + * Creates a generic array of the specified size. + *

+ * Ex.: {@code Util.makeArray(10);} + * + * @param size + * The desired size + * @return An array of the type and size chosen + */ + public static T[] makeArray(int size) { + @SuppressWarnings("unchecked") + T[] array = (T[]) new Object[size]; + return array; + } + + public static T[] makeArrayOfComparable(int size) { + @SuppressWarnings("unchecked") + T[] array = (T[]) new Comparable[size]; + return array; + } + + /** + * It says if a specific number is prime or not. + * + * @param n + * @return + */ + public static boolean isPrime(long n) { + boolean result = true; + for (int i = 2; i < n; i++) { + if (n % i == 0) { + result = false; + break; + } + } + return result; + } } \ No newline at end of file diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/test/java/adt/hashtable/closed/StudentTestHashtableClosedAddressDivisionMethod.java b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/test/java/adt/hashtable/closed/StudentTestHashtableClosedAddressDivisionMethod.java index 9a7cffba3..3409a2e41 100644 --- a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/test/java/adt/hashtable/closed/StudentTestHashtableClosedAddressDivisionMethod.java +++ b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/test/java/adt/hashtable/closed/StudentTestHashtableClosedAddressDivisionMethod.java @@ -1,88 +1,88 @@ -package adt.hashtable.closed; - -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; - -import adt.hashtable.closed.AbstractHashtableClosedAddress; -import adt.hashtable.closed.HashtableClosedAddressImpl; -import adt.hashtable.hashfunction.HashFunctionClosedAddressMethod; - -public class StudentTestHashtableClosedAddressDivisionMethod { - - protected AbstractHashtableClosedAddress table1; - protected AbstractHashtableClosedAddress table2; - - protected final int PROPOSED_SIZE = 100; - - @Before - public void setUp() throws Exception { - table1 = new HashtableClosedAddressImpl(PROPOSED_SIZE, - HashFunctionClosedAddressMethod.DIVISION); - - Integer initialValue = 200; - int increment = 5; - while (initialValue < 600) { - table1.insert(initialValue); - initialValue = initialValue + increment; - } - - table2 = new HashtableClosedAddressImpl(PROPOSED_SIZE, - HashFunctionClosedAddressMethod.DIVISION); - } - - @Test - public void testInsert() { - assertEquals(0, table1.getCOLLISIONS()); - table1.insert(105); // nao produz colisao - assertEquals(0, table1.getCOLLISIONS()); - assertEquals(4, table1.indexOf(105)); - table1.insert(110); // nao produz colisao - assertEquals(0, table1.getCOLLISIONS()); - assertEquals(9, table1.indexOf(110)); - table1.insert(101); // produz colisao no 0 - assertEquals(1, table1.getCOLLISIONS()); - assertEquals(0, table1.indexOf(101)); - - table2.insert(103); // nao produz colisao inserindo 1 elemento na talbe - // vazia - assertEquals(0, table2.getCOLLISIONS()); - assertEquals(2, table2.indexOf(103)); - } - - @Test - public void testRemove() { - int currentSize = table1.size(); - table1.remove(200); // elemento existente - assertEquals(currentSize - 1, table1.size()); - assertEquals(-1, table1.indexOf(200)); - } - - @Test - public void testSearch() { - // busca um elemento inexistente. compara a posicao - assertNull(table1.search(100)); - assertEquals(-1, table1.indexOf(100)); - - // busca um elemento existente. compara a posicao - assertEquals(new Integer(305), table1.search(305)); - assertEquals(2, table1.indexOf(305)); - - } - - @Test - public void testIsEmpty() { - assertFalse(table1.isEmpty()); - } - - @Test - public void testIsFull() { - assertFalse(table1.isFull()); - } - - @Test - public void testSize() { - assertEquals(80, table1.size()); - } -} +package adt.hashtable.closed; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; + +import adt.hashtable.closed.AbstractHashtableClosedAddress; +import adt.hashtable.closed.HashtableClosedAddressImpl; +import adt.hashtable.hashfunction.HashFunctionClosedAddressMethod; + +public class StudentTestHashtableClosedAddressDivisionMethod { + + protected AbstractHashtableClosedAddress table1; + protected AbstractHashtableClosedAddress table2; + + protected final int PROPOSED_SIZE = 100; + + @Before + public void setUp() throws Exception { + table1 = new HashtableClosedAddressImpl(PROPOSED_SIZE, + HashFunctionClosedAddressMethod.DIVISION); + + Integer initialValue = 200; + int increment = 5; + while (initialValue < 600) { + table1.insert(initialValue); + initialValue = initialValue + increment; + } + + table2 = new HashtableClosedAddressImpl(PROPOSED_SIZE, + HashFunctionClosedAddressMethod.DIVISION); + } + + @Test + public void testInsert() { + assertEquals(0, table1.getCOLLISIONS()); + table1.insert(105); // nao produz colisao + assertEquals(0, table1.getCOLLISIONS()); + assertEquals(4, table1.indexOf(105)); + table1.insert(110); // nao produz colisao + assertEquals(0, table1.getCOLLISIONS()); + assertEquals(9, table1.indexOf(110)); + table1.insert(101); // produz colisao no 0 + assertEquals(1, table1.getCOLLISIONS()); + assertEquals(0, table1.indexOf(101)); + + table2.insert(103); // nao produz colisao inserindo 1 elemento na talbe + // vazia + assertEquals(0, table2.getCOLLISIONS()); + assertEquals(2, table2.indexOf(103)); + } + + @Test + public void testRemove() { + int currentSize = table1.size(); + table1.remove(200); // elemento existente + assertEquals(currentSize - 1, table1.size()); + assertEquals(-1, table1.indexOf(200)); + } + + @Test + public void testSearch() { + // busca um elemento inexistente. compara a posicao + assertNull(table1.search(100)); + assertEquals(-1, table1.indexOf(100)); + + // busca um elemento existente. compara a posicao + assertEquals(new Integer(305), table1.search(305)); + assertEquals(2, table1.indexOf(305)); + + } + + @Test + public void testIsEmpty() { + assertFalse(table1.isEmpty()); + } + + @Test + public void testIsFull() { + assertFalse(table1.isFull()); + } + + @Test + public void testSize() { + assertEquals(80, table1.size()); + } +} diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/test/java/adt/hashtable/closed/StudentTestHashtableClosedAddressMultiplicationMethod.java b/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/test/java/adt/hashtable/closed/StudentTestHashtableClosedAddressMultiplicationMethod.java deleted file mode 100644 index 3ce12c3db..000000000 --- a/java/R08-01-Rot-TabelaHash-EndFechado--environment/src/test/java/adt/hashtable/closed/StudentTestHashtableClosedAddressMultiplicationMethod.java +++ /dev/null @@ -1,92 +0,0 @@ -package adt.hashtable.closed; - -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; - -import adt.hashtable.closed.AbstractHashtableClosedAddress; -import adt.hashtable.closed.HashtableClosedAddressImpl; -import adt.hashtable.hashfunction.HashFunctionClosedAddressMethod; - -public class StudentTestHashtableClosedAddressMultiplicationMethod { - - protected AbstractHashtableClosedAddress table1; - protected AbstractHashtableClosedAddress table2; - - protected final int PROPOSED_SIZE = 100; - - @Before - public void setUp() throws Exception { - table1 = new HashtableClosedAddressImpl(PROPOSED_SIZE, - HashFunctionClosedAddressMethod.MULTIPLICATION); - - Integer initialValue = 200; - int increment = 5; - while (initialValue < 600) { - table1.insert(initialValue); - initialValue = initialValue + increment; - } - - table2 = new HashtableClosedAddressImpl(PROPOSED_SIZE, - HashFunctionClosedAddressMethod.MULTIPLICATION); - } - - @Test - public void testInsert() { - assertEquals(13, table1.getCOLLISIONS()); - table1.insert(105); // nao produz colisao - assertEquals(13, table1.getCOLLISIONS()); - assertEquals(89, table1.indexOf(105)); - table1.insert(110); // nao produz colisao - assertEquals(13, table1.getCOLLISIONS()); - assertEquals(98, table1.indexOf(110)); - table1.insert(101); // - assertEquals(13, table1.getCOLLISIONS()); - assertEquals(42, table1.indexOf(101)); - table1.insert(102); // - assertEquals(14, table1.getCOLLISIONS()); - assertEquals(3, table1.indexOf(102)); - - table2.insert(103); // nao produz colisao inserindo 1 elemento na talbe - // vazia - assertEquals(0, table2.getCOLLISIONS()); - assertEquals(65, table2.indexOf(103)); - } - - @Test - public void testRemove() { - int currentSize = table1.size(); - table1.remove(200); // elemento existente - assertEquals(currentSize - 1, table1.size()); - assertEquals(-1, table1.indexOf(200)); - } - - @Test - public void testSearch() { - // busca um elemento inexistente. compara a posicao - assertNull(table1.search(100)); - assertEquals(-1, table1.indexOf(100)); - - // busca um elemento existente. compara a posicao - assertEquals(new Integer(305), table1.search(305)); - assertEquals(50, table1.indexOf(305)); - - } - - @Test - public void testIsEmpty() { - assertFalse(table1.isEmpty()); - } - - @Test - public void testIsFull() { - assertFalse(table1.isFull()); - } - - @Test - public void testSize() { - assertEquals(80, table1.size()); - } - -} diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/target/classes/META-INF/MANIFEST.MF b/java/R08-01-Rot-TabelaHash-EndFechado--environment/target/classes/META-INF/MANIFEST.MF index 6c4b9cc34..a05e7910c 100644 --- a/java/R08-01-Rot-TabelaHash-EndFechado--environment/target/classes/META-INF/MANIFEST.MF +++ b/java/R08-01-Rot-TabelaHash-EndFechado--environment/target/classes/META-INF/MANIFEST.MF @@ -1,5 +1,5 @@ -Manifest-Version: 1.0 -Built-By: amintas -Build-Jdk: 1.8.0_131 -Created-By: Maven Integration for Eclipse - +Manifest-Version: 1.0 +Built-By: amintas +Build-Jdk: 1.8.0_131 +Created-By: Maven Integration for Eclipse + diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml b/java/R08-01-Rot-TabelaHash-EndFechado--environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml index 4412de2fa..40c340bb7 100644 --- a/java/R08-01-Rot-TabelaHash-EndFechado--environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml +++ b/java/R08-01-Rot-TabelaHash-EndFechado--environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml @@ -1,98 +1,98 @@ - - 4.0.0 - - br.edu.ufcg.ccc - submission - 1.0 - jar - Submissao de roteiro - - - - ufcg-leda - http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda - default - - true - always - - - - - - - junit - junit - 4.12 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - maven-clean-plugin - 3.0.0 - - - auto-clean - build - - clean - - - - - - - org.walkmod - maven-walkmod-plugin - 1.3 - - walkmod.xml - - - - package - - apply - - - false - - - - - - br.edu.ufcg.ccc - leda-compactor-tool - 1.0.0-SNAPSHOT - - - install - - compact - - - - 116110761 - - R08-01 - - 2017.1 - http://150.165.85.29:81/submitAtividade - - - - - - - + + 4.0.0 + + br.edu.ufcg.ccc + submission + 1.0 + jar + Submissao de roteiro + + + + ufcg-leda + http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda + default + + true + always + + + + + + + junit + junit + 4.12 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + maven-clean-plugin + 3.0.0 + + + auto-clean + build + + clean + + + + + + + org.walkmod + maven-walkmod-plugin + 1.3 + + walkmod.xml + + + + package + + apply + + + false + + + + + + br.edu.ufcg.ccc + leda-compactor-tool + 1.0.0-SNAPSHOT + + + install + + compact + + + + 116110761 + + R08-01 + + 2017.1 + http://150.165.85.29:81/submitAtividade + + + + + + + diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/target/test-classes/adt/hashtable/closed/StudentTestHashtableClosedAddressDivisionMethod.class b/java/R08-01-Rot-TabelaHash-EndFechado--environment/target/test-classes/adt/hashtable/closed/StudentTestHashtableClosedAddressDivisionMethod.class deleted file mode 100644 index a5ad1acd7..000000000 Binary files a/java/R08-01-Rot-TabelaHash-EndFechado--environment/target/test-classes/adt/hashtable/closed/StudentTestHashtableClosedAddressDivisionMethod.class and /dev/null differ diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/target/test-classes/adt/hashtable/closed/StudentTestHashtableClosedAddressMultiplicationMethod.class b/java/R08-01-Rot-TabelaHash-EndFechado--environment/target/test-classes/adt/hashtable/closed/StudentTestHashtableClosedAddressMultiplicationMethod.class deleted file mode 100644 index c724d91e7..000000000 Binary files a/java/R08-01-Rot-TabelaHash-EndFechado--environment/target/test-classes/adt/hashtable/closed/StudentTestHashtableClosedAddressMultiplicationMethod.class and /dev/null differ diff --git a/java/R08-01-Rot-TabelaHash-EndFechado--environment/walkmod.xml b/java/R08-01-Rot-TabelaHash-EndFechado--environment/walkmod.xml index d391a36b4..85902bfec 100644 --- a/java/R08-01-Rot-TabelaHash-EndFechado--environment/walkmod.xml +++ b/java/R08-01-Rot-TabelaHash-EndFechado--environment/walkmod.xml @@ -1,4 +1,4 @@ - - - + + + \ No newline at end of file diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/pom.xml b/java/R09-01-Rot-TabelaHash-EndAberto-environment/pom.xml index 7ea5878b2..f99191b22 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/pom.xml +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/pom.xml @@ -1,98 +1,98 @@ - - 4.0.0 - - br.edu.ufcg.ccc - submission - 1.0 - jar - Submissao de roteiro - - - - ufcg-leda - http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda - default - - true - always - - - - - - - junit - junit - 4.12 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - maven-clean-plugin - 3.0.0 - - - auto-clean - build - - clean - - - - - - - org.walkmod - maven-walkmod-plugin - 1.3 - - walkmod.xml - - - - package - - apply - - - false - - - - - - br.edu.ufcg.ccc - leda-compactor-tool - 1.0.0-SNAPSHOT - - - install - - compact - - - - INSIRA SEU NUMERO DE MATRICULA - - R0X-0X - - 2017.1 - http://150.165.85.29:81/submitAtividade - - - - - - - + + 4.0.0 + + br.edu.ufcg.ccc + submission + 1.0 + jar + Submissao de roteiro + + + + ufcg-leda + http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda + default + + true + always + + + + + + + junit + junit + 4.12 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + maven-clean-plugin + 3.0.0 + + + auto-clean + build + + clean + + + + + + + org.walkmod + maven-walkmod-plugin + 1.3 + + walkmod.xml + + + + package + + apply + + + false + + + + + + br.edu.ufcg.ccc + leda-compactor-tool + 1.0.0-SNAPSHOT + + + install + + compact + + + + INSIRA SEU NUMERO DE MATRICULA + + R0X-0X + + 2017.1 + http://150.165.85.29:81/submitAtividade + + + + + + + diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/AbstractHashtable.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/AbstractHashtable.java index b93172fb4..f186cdd5a 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/AbstractHashtable.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/AbstractHashtable.java @@ -1,67 +1,67 @@ -package adt.hashtable; - -import util.Util; -import adt.hashtable.hashfunction.HashFunction; - -/** - * It represents an abstract implementation of a hashtable, with some internal - * attributes. Note that the kind of the internal array is a parameter because - * hashtable with closed address should have a collection of elements (chaining) - * instead of a single element. Moreover, a hashtable working with open address - * must also manipulate deletions through a special element called DELETED. - * Thus, it must work with Object instead of a generic type T. An - * AbstractHashtable is only a resource for unifying both kinds of hashtables - * (closed and open addressing). Thee real hashtables must inherit this class. - */ -public abstract class AbstractHashtable implements Hashtable { - - protected Object[] table; // the internal table - protected int elements; // the number of elements inserted into the hash - // table - protected int COLLISIONS; // the number of collisions occurred in this - // hashtable - protected HashFunction hashFunction; // the hash function used by this - // hashtable. - - public AbstractHashtable() { - elements = 0; - COLLISIONS = 0; - } - - protected void initiateInternalTable(int size) { - this.table = Util. makeArray(size); - } - - @Override - public boolean isEmpty() { - return (elements == 0); - } - - @Override - public boolean isFull() { - return (elements == table.length); - } - - @Override - public int size() { - return elements; - } - - @Override - public int capacity() { - return this.table.length; - } - - public int getCOLLISIONS() { - return COLLISIONS; - } - - public HashFunction getHashFunction() { - return hashFunction; - } - - public void setHashFunction(HashFunction hashFunction) { - this.hashFunction = hashFunction; - } - -} +package adt.hashtable; + +import util.Util; +import adt.hashtable.hashfunction.HashFunction; + +/** + * It represents an abstract implementation of a hashtable, with some internal + * attributes. Note that the kind of the internal array is a parameter because + * hashtable with closed address should have a collection of elements (chaining) + * instead of a single element. Moreover, a hashtable working with open address + * must also manipulate deletions through a special element called DELETED. + * Thus, it must work with Object instead of a generic type T. An + * AbstractHashtable is only a resource for unifying both kinds of hashtables + * (closed and open addressing). Thee real hashtables must inherit this class. + */ +public abstract class AbstractHashtable implements Hashtable { + + protected Object[] table; // the internal table + protected int elements; // the number of elements inserted into the hash + // table + protected int COLLISIONS; // the number of collisions occurred in this + // hashtable + protected HashFunction hashFunction; // the hash function used by this + // hashtable. + + public AbstractHashtable() { + elements = 0; + COLLISIONS = 0; + } + + protected void initiateInternalTable(int size) { + this.table = Util. makeArray(size); + } + + @Override + public boolean isEmpty() { + return (elements == 0); + } + + @Override + public boolean isFull() { + return (elements == table.length); + } + + @Override + public int size() { + return elements; + } + + @Override + public int capacity() { + return this.table.length; + } + + public int getCOLLISIONS() { + return COLLISIONS; + } + + public HashFunction getHashFunction() { + return hashFunction; + } + + public void setHashFunction(HashFunction hashFunction) { + this.hashFunction = hashFunction; + } + +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/Hashtable.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/Hashtable.java index 1e9a42907..57747f8f0 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/Hashtable.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/Hashtable.java @@ -1,57 +1,57 @@ -package adt.hashtable; - -/** - * The interface of a generic hash table. It keeps values of type T. The table - * can work in two modes: closed address (with chaining) and open address - * (linear probing, quadratic probe, double hashing). - */ -public interface Hashtable { - - /** - * Determines whether this hashtable is empty or not. - */ - public boolean isEmpty(); - - /** - * Determines whether this hashtable is empty or not. Note that this method - * may not make sense in hashtable with closed address, as it works with - * linked lists (or buckets) in each position. - */ - public boolean isFull(); - - /** - * It returns the length of the internal table of this hash table. - */ - public int capacity(); - - /** - * Returns how many values have been inserted into the hash table. - */ - public int size(); - - /** - * Inserts a non-null object into the hash table. The hashtable does not - * work with duplicated elements. Every time that the insert is called, if - * there is a collision, then the attribute COLLISION of this hashtable is - * incremented. - */ - public void insert(T element); - - /** - * Removes an element from the hash table. - */ - public void remove(T element); - - /** - * Searches a given element in the hash table. If it is not in the table, - * the hash table returns null. - */ - public T search(T element); - - /** - * Searches the index of an element in the hashtable. It returns -1 if the - * element is not in the hashtable. - */ - public int indexOf(T element); - -} +package adt.hashtable; + +/** + * The interface of a generic hash table. It keeps values of type T. The table + * can work in two modes: closed address (with chaining) and open address + * (linear probing, quadratic probe, double hashing). + */ +public interface Hashtable { + + /** + * Determines whether this hashtable is empty or not. + */ + public boolean isEmpty(); + + /** + * Determines whether this hashtable is empty or not. Note that this method + * may not make sense in hashtable with closed address, as it works with + * linked lists (or buckets) in each position. + */ + public boolean isFull(); + + /** + * It returns the length of the internal table of this hash table. + */ + public int capacity(); + + /** + * Returns how many values have been inserted into the hash table. + */ + public int size(); + + /** + * Inserts a non-null object into the hash table. The hashtable does not + * work with duplicated elements. Every time that the insert is called, if + * there is a collision, then the attribute COLLISION of this hashtable is + * incremented. + */ + public void insert(T element); + + /** + * Removes an element from the hash table. + */ + public void remove(T element); + + /** + * Searches a given element in the hash table. If it is not in the table, + * the hash table returns null. + */ + public T search(T element); + + /** + * Searches the index of an element in the hashtable. It returns -1 if the + * element is not in the hashtable. + */ + public int indexOf(T element); + +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunction.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunction.java index 53999adfc..91cada969 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunction.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunction.java @@ -1,9 +1,9 @@ -package adt.hashtable.hashfunction; - -/** - * It represents a generic hash function that will be used by a hashtable to - * calculate indexes in the internal array. - */ -public interface HashFunction { - -} +package adt.hashtable.hashfunction; + +/** + * It represents a generic hash function that will be used by a hashtable to + * calculate indexes in the internal array. + */ +public interface HashFunction { + +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionClosedAddress.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionClosedAddress.java index dbd8268ab..268c9d1ce 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionClosedAddress.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionClosedAddress.java @@ -1,13 +1,13 @@ -package adt.hashtable.hashfunction; - -/** - * It represents a hash function to be used in hashtable that work with closed - * address. - */ -public interface HashFunctionClosedAddress extends HashFunction { - - /** - * The hash function considering closed address. - */ - public int hash(T element); -} +package adt.hashtable.hashfunction; + +/** + * It represents a hash function to be used in hashtable that work with closed + * address. + */ +public interface HashFunctionClosedAddress extends HashFunction { + + /** + * The hash function considering closed address. + */ + public int hash(T element); +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionClosedAddressMethod.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionClosedAddressMethod.java index 2905e19d9..c48022658 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionClosedAddressMethod.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionClosedAddressMethod.java @@ -1,8 +1,8 @@ -package adt.hashtable.hashfunction; - -/** - * The kind of method used by a hash function for closed addressing. - */ -public enum HashFunctionClosedAddressMethod { - DIVISION, MULTIPLICATION; -} +package adt.hashtable.hashfunction; + +/** + * The kind of method used by a hash function for closed addressing. + */ +public enum HashFunctionClosedAddressMethod { + DIVISION, MULTIPLICATION; +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionDivisionMethod.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionDivisionMethod.java index 3a00f4d6b..27121446a 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionDivisionMethod.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionDivisionMethod.java @@ -1,33 +1,33 @@ -package adt.hashtable.hashfunction; - -public class HashFunctionDivisionMethod implements - HashFunctionClosedAddress { - - protected int tableSize; - - public HashFunctionDivisionMethod(int tableSize) { - this.tableSize = tableSize; - } - - /** - * The hash function might use the table size to calculate the hash of any - * object of type T. The hash function has as body h(k) = k % m - * , where k is the key and m is the table size - * (stored in the filed tableSize). - * - * The key is obtained from hashCode method of type T (inherited from Object - * or overridden by you). Thus, if you use a type with hashCode - * implementation, no change is necessary. Otherwise, you must implement the - * hashCde method of T. - */ - @Override - public int hash(T element) { - int hashKey = -1; - int key = element.hashCode(); - - hashKey = (int) key % tableSize; - - return hashKey; - } - -} +package adt.hashtable.hashfunction; + +public class HashFunctionDivisionMethod implements + HashFunctionClosedAddress { + + protected int tableSize; + + public HashFunctionDivisionMethod(int tableSize) { + this.tableSize = tableSize; + } + + /** + * The hash function might use the table size to calculate the hash of any + * object of type T. The hash function has as body h(k) = k % m + * , where k is the key and m is the table size + * (stored in the filed tableSize). + * + * The key is obtained from hashCode method of type T (inherited from Object + * or overridden by you). Thus, if you use a type with hashCode + * implementation, no change is necessary. Otherwise, you must implement the + * hashCde method of T. + */ + @Override + public int hash(T element) { + int hashKey = -1; + int key = element.hashCode(); + + hashKey = (int) key % tableSize; + + return hashKey; + } + +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionFactory.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionFactory.java index 15c79f424..4193c276d 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionFactory.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionFactory.java @@ -1,28 +1,28 @@ -package adt.hashtable.hashfunction; - - -/** - * This class is responsible to create hash functions suitable to each kind of - * hash table. - * - * @author Adalberto - * - */ -public class HashFunctionFactory { - - public static HashFunction createHashFunction( - HashFunctionClosedAddressMethod method, int tableSize) { - HashFunction result = null; - switch (method) { - case DIVISION: - result = new HashFunctionDivisionMethod(tableSize); - break; - case MULTIPLICATION: - result = new HashFunctionMultiplicationMethod(tableSize); - break; - } - - return result; - } - -} +package adt.hashtable.hashfunction; + + +/** + * This class is responsible to create hash functions suitable to each kind of + * hash table. + * + * @author Adalberto + * + */ +public class HashFunctionFactory { + + public static HashFunction createHashFunction( + HashFunctionClosedAddressMethod method, int tableSize) { + HashFunction result = null; + switch (method) { + case DIVISION: + result = new HashFunctionDivisionMethod(tableSize); + break; + case MULTIPLICATION: + result = new HashFunctionMultiplicationMethod(tableSize); + break; + } + + return result; + } + +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionLinearProbing.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionLinearProbing.java index d37462cc7..dffb1c28b 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionLinearProbing.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionLinearProbing.java @@ -1,32 +1,32 @@ -package adt.hashtable.hashfunction; - -public class HashFunctionLinearProbing implements HashFunctionOpenAddress { - - protected HashFunctionClosedAddress originalHashFunction; - private int tableCapacity; - - public HashFunctionLinearProbing(int tableCapacity, - HashFunctionClosedAddressMethod method) { - this.tableCapacity = tableCapacity; - if (method == HashFunctionClosedAddressMethod.DIVISION) { - originalHashFunction = new HashFunctionDivisionMethod( - tableCapacity); - } else { - originalHashFunction = new HashFunctionMultiplicationMethod( - tableCapacity); - } - } - - /** - * The hash function considering open address with linear probing. It uses - * the hashCode method inherited from Object. - */ - @Override - public int hash(T element, int probe) { - int generatedIndex = 0; - - generatedIndex = ((originalHashFunction.hash(element) + probe) % this.tableCapacity); - - return generatedIndex; - } -} +package adt.hashtable.hashfunction; + +public class HashFunctionLinearProbing implements HashFunctionOpenAddress { + + protected HashFunctionClosedAddress originalHashFunction; + private int tableCapacity; + + public HashFunctionLinearProbing(int tableCapacity, + HashFunctionClosedAddressMethod method) { + this.tableCapacity = tableCapacity; + if (method == HashFunctionClosedAddressMethod.DIVISION) { + originalHashFunction = new HashFunctionDivisionMethod( + tableCapacity); + } else { + originalHashFunction = new HashFunctionMultiplicationMethod( + tableCapacity); + } + } + + /** + * The hash function considering open address with linear probing. It uses + * the hashCode method inherited from Object. + */ + @Override + public int hash(T element, int probe) { + int generatedIndex = 0; + + generatedIndex = ((originalHashFunction.hash(element) + probe) % this.tableCapacity); + + return generatedIndex; + } +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionMultiplicationMethod.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionMultiplicationMethod.java index c1f149c7a..3260082b8 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionMultiplicationMethod.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionMultiplicationMethod.java @@ -1,35 +1,35 @@ -package adt.hashtable.hashfunction; - -public class HashFunctionMultiplicationMethod implements - HashFunctionClosedAddress { - - protected int tableSize; - private static final double A = (Math.sqrt(5) - 1) / 2; - - public HashFunctionMultiplicationMethod(int tableSize) { - this.tableSize = tableSize; - } - - /** - * The hash function might use the table size to calculate the hash of any - * object of type T. The hash function has as body - * h(k) = m (kA % 1), where k is the key and - * m is the table size (stored in the filed - * tableSize) and A is the constant defined - * (Math.sqrt(5)-1)/2 . - * - * The key is obtained from hashCode method of type T (inherited from Object - * or overridden by you). Thus, if you use a type with hashCode - * implementation, no change is necessary. Otherwise, you must implement the - * hashCde method of T. - */ - @Override - public int hash(T element) { - int hashKey = -1; - int key = element.hashCode(); - double fractionalPart = key * A - Math.floor(key * A); - hashKey = (int) (tableSize * fractionalPart); - - return hashKey; - } -} +package adt.hashtable.hashfunction; + +public class HashFunctionMultiplicationMethod implements + HashFunctionClosedAddress { + + protected int tableSize; + private static final double A = (Math.sqrt(5) - 1) / 2; + + public HashFunctionMultiplicationMethod(int tableSize) { + this.tableSize = tableSize; + } + + /** + * The hash function might use the table size to calculate the hash of any + * object of type T. The hash function has as body + * h(k) = m (kA % 1), where k is the key and + * m is the table size (stored in the filed + * tableSize) and A is the constant defined + * (Math.sqrt(5)-1)/2 . + * + * The key is obtained from hashCode method of type T (inherited from Object + * or overridden by you). Thus, if you use a type with hashCode + * implementation, no change is necessary. Otherwise, you must implement the + * hashCde method of T. + */ + @Override + public int hash(T element) { + int hashKey = -1; + int key = element.hashCode(); + double fractionalPart = key * A - Math.floor(key * A); + hashKey = (int) (tableSize * fractionalPart); + + return hashKey; + } +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionOpenAddress.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionOpenAddress.java index 00c6b76cd..eeab2551c 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionOpenAddress.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionOpenAddress.java @@ -1,13 +1,13 @@ -package adt.hashtable.hashfunction; - -/** - * It represents a hash function to be used in hashtable that work with open - * address. - */ -public interface HashFunctionOpenAddress extends HashFunction { - /** - * The hash function considering open address. It uses the hashCode method - * inherited from Object. - */ - public int hash(T element, int probe); -} +package adt.hashtable.hashfunction; + +/** + * It represents a hash function to be used in hashtable that work with open + * address. + */ +public interface HashFunctionOpenAddress extends HashFunction { + /** + * The hash function considering open address. It uses the hashCode method + * inherited from Object. + */ + public int hash(T element, int probe); +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionOpenAddressMethod.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionOpenAddressMethod.java index 407b04c74..610a8660f 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionOpenAddressMethod.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionOpenAddressMethod.java @@ -1,8 +1,8 @@ -package adt.hashtable.hashfunction; - -/** - * The kind of method used by a hash function for open addressing. - */ -public enum HashFunctionOpenAddressMethod { - LINEAR_PROBING, QUADRATIC_PROBING, DOUBLE_HASHING; -} +package adt.hashtable.hashfunction; + +/** + * The kind of method used by a hash function for open addressing. + */ +public enum HashFunctionOpenAddressMethod { + LINEAR_PROBING, QUADRATIC_PROBING, DOUBLE_HASHING; +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionQuadraticProbing.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionQuadraticProbing.java index a1c74c59d..3bd6bfcdb 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionQuadraticProbing.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/hashfunction/HashFunctionQuadraticProbing.java @@ -1,35 +1,35 @@ -package adt.hashtable.hashfunction; - -public class HashFunctionQuadraticProbing implements - HashFunctionOpenAddress { - - private int tableCapacity; - protected HashFunctionClosedAddress originalHashFunction; - protected int c1; - protected int c2; - - public HashFunctionQuadraticProbing(int tableCapacity, - HashFunctionClosedAddressMethod method, int c1, int c2) { - this.tableCapacity = tableCapacity; - if (method == HashFunctionClosedAddressMethod.DIVISION) { - originalHashFunction = new HashFunctionDivisionMethod( - tableCapacity); - } else { - originalHashFunction = new HashFunctionMultiplicationMethod( - tableCapacity); - } - this.c1 = c1; - this.c2 = c2; - } - - @Override - public int hash(T element, int probe) { - int generatedIndex = 0; - - generatedIndex = originalHashFunction.hash(element); - generatedIndex = ((generatedIndex + c1 * probe + c2 * probe * probe) % this.tableCapacity); - - return generatedIndex; - } - -} +package adt.hashtable.hashfunction; + +public class HashFunctionQuadraticProbing implements + HashFunctionOpenAddress { + + private int tableCapacity; + protected HashFunctionClosedAddress originalHashFunction; + protected int c1; + protected int c2; + + public HashFunctionQuadraticProbing(int tableCapacity, + HashFunctionClosedAddressMethod method, int c1, int c2) { + this.tableCapacity = tableCapacity; + if (method == HashFunctionClosedAddressMethod.DIVISION) { + originalHashFunction = new HashFunctionDivisionMethod( + tableCapacity); + } else { + originalHashFunction = new HashFunctionMultiplicationMethod( + tableCapacity); + } + this.c1 = c1; + this.c2 = c2; + } + + @Override + public int hash(T element, int probe) { + int generatedIndex = 0; + + generatedIndex = originalHashFunction.hash(element); + generatedIndex = ((generatedIndex + c1 * probe + c2 * probe * probe) % this.tableCapacity); + + return generatedIndex; + } + +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/AbstractHashtableOpenAddress.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/AbstractHashtableOpenAddress.java index 3f4f42061..405ffcac0 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/AbstractHashtableOpenAddress.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/AbstractHashtableOpenAddress.java @@ -1,20 +1,20 @@ -package adt.hashtable.open; - -import util.Util; -import adt.hashtable.AbstractHashtable; - -public abstract class AbstractHashtableOpenAddress extends - AbstractHashtable { - - protected final DELETED deletedElement = new DELETED(); - private int tableSize; - - public AbstractHashtableOpenAddress(int size) { - this.tableSize = size; - } - - @Override - protected void initiateInternalTable(int size) { - this.table = Util. makeArray(size); - } -} +package adt.hashtable.open; + +import util.Util; +import adt.hashtable.AbstractHashtable; + +public abstract class AbstractHashtableOpenAddress extends + AbstractHashtable { + + protected final DELETED deletedElement = new DELETED(); + private int tableSize; + + public AbstractHashtableOpenAddress(int size) { + this.tableSize = size; + } + + @Override + protected void initiateInternalTable(int size) { + this.table = Util. makeArray(size); + } +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/DELETED.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/DELETED.java index 36cb397c7..14824a8c1 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/DELETED.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/DELETED.java @@ -1,22 +1,22 @@ -package adt.hashtable.open; - -public class DELETED implements Storable { - - public DELETED() { - - } - - @Override - public boolean equals(Object obj) { - boolean resp = false; - if (obj != null) { - resp = obj instanceof DELETED; - } - return resp; - } - - @Override - public String toString() { - return "D"; - } -} +package adt.hashtable.open; + +public class DELETED implements Storable { + + public DELETED() { + + } + + @Override + public boolean equals(Object obj) { + boolean resp = false; + if (obj != null) { + resp = obj instanceof DELETED; + } + return resp; + } + + @Override + public String toString() { + return "D"; + } +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/HashtableElement.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/HashtableElement.java index 4297437ab..432c89e78 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/HashtableElement.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/HashtableElement.java @@ -1,21 +1,21 @@ -package adt.hashtable.open; - -public class HashtableElement implements Storable { - - private Integer key; - - public HashtableElement(int key) { - this.key = key; - } - - @Override - public int hashCode() { - return this.key.hashCode(); - } - - @Override - public boolean equals(Object obj) { - return this.hashCode() == obj.hashCode(); - } - -} +package adt.hashtable.open; + +public class HashtableElement implements Storable { + + private Integer key; + + public HashtableElement(int key) { + this.key = key; + } + + @Override + public int hashCode() { + return this.key.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return this.hashCode() == obj.hashCode(); + } + +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/HashtableOpenAddressLinearProbingImpl.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/HashtableOpenAddressLinearProbingImpl.java index 9925f1087..32acd811d 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/HashtableOpenAddressLinearProbingImpl.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/HashtableOpenAddressLinearProbingImpl.java @@ -1,98 +1,98 @@ -package adt.hashtable.open; - -import adt.hashtable.hashfunction.HashFunctionClosedAddressMethod; -import adt.hashtable.hashfunction.HashFunctionLinearProbing; - -public class HashtableOpenAddressLinearProbingImpl extends AbstractHashtableOpenAddress { - - public HashtableOpenAddressLinearProbingImpl(int size, HashFunctionClosedAddressMethod method) { - super(size); - hashFunction = new HashFunctionLinearProbing(size, method); - this.initiateInternalTable(size); - } - - @Override - public void insert(T element) { - if (element != null) { - if (isFull()) { - throw new HashtableOverflowException(); - } else { - int i = 0; - while (i != this.capacity()) { - int j = hashing(element, i); - if (this.table[j] == null || this.table[j] instanceof DELETED) { - this.table[j] = element; - this.elements++; - break; - } else { - i++; - this.COLLISIONS++; - } - } - } - } - } - - private int hashing(T element, int i) { - int result = ((HashFunctionLinearProbing) this.getHashFunction()).hash(element, i); - return result; - } - - @Override - public void remove(T element) { - if (element != null) { - int i = indexOf(element); - if (i != -1) { - this.table[i] = new DELETED(); - this.elements--; - } - } - } - - @Override - public T search(T element) { - T result = null; - if (element != null) { - int i = 0; - while (i != this.capacity()) { - int j = hashing(element, i); - if (this.table[j] == null) { - break; - } else { - if (this.table[j].equals(element)) { - result = element; - break; - } else { - i++; - } - - } - } - } - return result; - } - - @Override - public int indexOf(T element) { - int result = -1; - if (element != null) { - int i = 0; - while (i != this.capacity()) { - int j = hashing(element, i); - if (this.table[j] == null) { - break; - } else { - if (this.table[j].equals(element)) { - result = j; - break; - } else { - i++; - } - } - } - - } - return result; - } - -} +package adt.hashtable.open; + +import adt.hashtable.hashfunction.HashFunctionClosedAddressMethod; +import adt.hashtable.hashfunction.HashFunctionLinearProbing; + +public class HashtableOpenAddressLinearProbingImpl extends AbstractHashtableOpenAddress { + + public HashtableOpenAddressLinearProbingImpl(int size, HashFunctionClosedAddressMethod method) { + super(size); + hashFunction = new HashFunctionLinearProbing(size, method); + this.initiateInternalTable(size); + } + + @Override + public void insert(T element) { + if (element != null) { + if (isFull()) { + throw new HashtableOverflowException(); + } else { + int i = 0; + while (i != this.capacity()) { + int j = hashing(element, i); + if (this.table[j] == null || this.table[j] instanceof DELETED) { + this.table[j] = element; + this.elements++; + break; + } else { + i++; + this.COLLISIONS++; + } + } + } + } + } + + private int hashing(T element, int i) { + int result = ((HashFunctionLinearProbing) this.getHashFunction()).hash(element, i); + return result; + } + + @Override + public void remove(T element) { + if (element != null) { + int i = indexOf(element); + if (i != -1) { + this.table[i] = new DELETED(); + this.elements--; + } + } + } + + @Override + public T search(T element) { + T result = null; + if (element != null) { + int i = 0; + while (i != this.capacity()) { + int j = hashing(element, i); + if (this.table[j] == null) { + break; + } else { + if (this.table[j].equals(element)) { + result = element; + break; + } else { + i++; + } + + } + } + } + return result; + } + + @Override + public int indexOf(T element) { + int result = -1; + if (element != null) { + int i = 0; + while (i != this.capacity()) { + int j = hashing(element, i); + if (this.table[j] == null) { + break; + } else { + if (this.table[j].equals(element)) { + result = j; + break; + } else { + i++; + } + } + } + + } + return result; + } + +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/HashtableOpenAddressQuadraticProbingImpl.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/HashtableOpenAddressQuadraticProbingImpl.java index b406ca8fb..2fbadf618 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/HashtableOpenAddressQuadraticProbingImpl.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/HashtableOpenAddressQuadraticProbingImpl.java @@ -1,99 +1,99 @@ -package adt.hashtable.open; - -import adt.hashtable.hashfunction.HashFunctionClosedAddressMethod; -import adt.hashtable.hashfunction.HashFunctionQuadraticProbing; - -public class HashtableOpenAddressQuadraticProbingImpl - extends AbstractHashtableOpenAddress { - - public HashtableOpenAddressQuadraticProbingImpl(int size, - HashFunctionClosedAddressMethod method, int c1, int c2) { - super(size); - hashFunction = new HashFunctionQuadraticProbing(size, method, c1, c2); - this.initiateInternalTable(size); - } - - @Override - public void insert(T element) { - if (element != null) { - if (isFull()) { - throw new HashtableOverflowException(); - } else { - int i = 0; - while (i != this.capacity()) { - int j = hashing(element, i); - if (this.table[j] == null || this.table[j] instanceof DELETED) { - this.table[j] = element; - this.elements++; - break; - } else { - i++; - this.COLLISIONS++; - } - } - } - } - } - - private int hashing(T element, int i) { - int result = ((HashFunctionQuadraticProbing) this.getHashFunction()).hash(element, i); - return result; - } - - @Override - public void remove(T element) { - if (element != null) { - int i = indexOf(element); - if (i != -1) { - this.table[i] = new DELETED(); - this.elements--; - } - } - } - - @Override - public T search(T element) { - T result = null; - if (element != null) { - int i = 0; - while (i != this.capacity()) { - int j = hashing(element, i); - if (this.table[j] == null) { - break; - } else { - if (this.table[j].equals(element)) { - result = element; - break; - } else { - i++; - } - - } - } - } - return result; - } - - @Override - public int indexOf(T element) { - int result = -1; - if (element != null) { - int i = 0; - while (i != this.capacity()) { - int j = hashing(element, i); - if (this.table[j] == null) { - break; - } else { - if (this.table[j].equals(element)) { - result = j; - break; - } else { - i++; - } - } - } - - } - return result; - } -} +package adt.hashtable.open; + +import adt.hashtable.hashfunction.HashFunctionClosedAddressMethod; +import adt.hashtable.hashfunction.HashFunctionQuadraticProbing; + +public class HashtableOpenAddressQuadraticProbingImpl + extends AbstractHashtableOpenAddress { + + public HashtableOpenAddressQuadraticProbingImpl(int size, + HashFunctionClosedAddressMethod method, int c1, int c2) { + super(size); + hashFunction = new HashFunctionQuadraticProbing(size, method, c1, c2); + this.initiateInternalTable(size); + } + + @Override + public void insert(T element) { + if (element != null) { + if (isFull()) { + throw new HashtableOverflowException(); + } else { + int i = 0; + while (i != this.capacity()) { + int j = hashing(element, i); + if (this.table[j] == null || this.table[j] instanceof DELETED) { + this.table[j] = element; + this.elements++; + break; + } else { + i++; + this.COLLISIONS++; + } + } + } + } + } + + private int hashing(T element, int i) { + int result = ((HashFunctionQuadraticProbing) this.getHashFunction()).hash(element, i); + return result; + } + + @Override + public void remove(T element) { + if (element != null) { + int i = indexOf(element); + if (i != -1) { + this.table[i] = new DELETED(); + this.elements--; + } + } + } + + @Override + public T search(T element) { + T result = null; + if (element != null) { + int i = 0; + while (i != this.capacity()) { + int j = hashing(element, i); + if (this.table[j] == null) { + break; + } else { + if (this.table[j].equals(element)) { + result = element; + break; + } else { + i++; + } + + } + } + } + return result; + } + + @Override + public int indexOf(T element) { + int result = -1; + if (element != null) { + int i = 0; + while (i != this.capacity()) { + int j = hashing(element, i); + if (this.table[j] == null) { + break; + } else { + if (this.table[j].equals(element)) { + result = j; + break; + } else { + i++; + } + } + } + + } + return result; + } +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/HashtableOverflowException.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/HashtableOverflowException.java index 96a8b7526..7260904ce 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/HashtableOverflowException.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/HashtableOverflowException.java @@ -1,9 +1,9 @@ -package adt.hashtable.open; - -public class HashtableOverflowException extends RuntimeException { - - public HashtableOverflowException() { - super("Hashtable overflow!"); - } - -} +package adt.hashtable.open; + +public class HashtableOverflowException extends RuntimeException { + + public HashtableOverflowException() { + super("Hashtable overflow!"); + } + +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/Storable.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/Storable.java index ae1c91637..6a729b77d 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/Storable.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/adt/hashtable/open/Storable.java @@ -1,5 +1,5 @@ -package adt.hashtable.open; - -public interface Storable { - -} +package adt.hashtable.open; + +public interface Storable { + +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/util/Util.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/util/Util.java index adedf2ae4..9d0dc04cc 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/util/Util.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/main/java/util/Util.java @@ -1,66 +1,66 @@ -package util; - -import java.lang.reflect.Method; - -/** - * Class containing useful methods for arrays manipulation. - */ -public class Util { - - /** - * Swaps the contents of two positions in an array. - * - * @param array - * The array to be modified, not null - * @param i - * One of the target positions - * @param j - * The other target position - */ - public static void swap(Object[] array, int i, int j) { - if (array == null) - throw new IllegalArgumentException(); - - Object temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } - - /** - * Creates a generic array of the specified size. - *

- * Ex.: {@code Util.makeArray(10);} - * - * @param size - * The desired size - * @return An array of the type and size chosen - */ - public static T[] makeArray(int size) { - @SuppressWarnings("unchecked") - T[] array = (T[]) new Object[size]; - return array; - } - - public static T[] makeArrayOfComparable(int size) { - @SuppressWarnings("unchecked") - T[] array = (T[]) new Comparable[size]; - return array; - } - - /** - * It says if a specific number is prime or not. - * - * @param n - * @return - */ - public static boolean isPrime(long n) { - boolean result = true; - for (int i = 2; i < n; i++) { - if (n % i == 0){ - result = false; - break; - } - } - return result; - } +package util; + +import java.lang.reflect.Method; + +/** + * Class containing useful methods for arrays manipulation. + */ +public class Util { + + /** + * Swaps the contents of two positions in an array. + * + * @param array + * The array to be modified, not null + * @param i + * One of the target positions + * @param j + * The other target position + */ + public static void swap(Object[] array, int i, int j) { + if (array == null) + throw new IllegalArgumentException(); + + Object temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + /** + * Creates a generic array of the specified size. + *

+ * Ex.: {@code Util.makeArray(10);} + * + * @param size + * The desired size + * @return An array of the type and size chosen + */ + public static T[] makeArray(int size) { + @SuppressWarnings("unchecked") + T[] array = (T[]) new Object[size]; + return array; + } + + public static T[] makeArrayOfComparable(int size) { + @SuppressWarnings("unchecked") + T[] array = (T[]) new Comparable[size]; + return array; + } + + /** + * It says if a specific number is prime or not. + * + * @param n + * @return + */ + public static boolean isPrime(long n) { + boolean result = true; + for (int i = 2; i < n; i++) { + if (n % i == 0){ + result = false; + break; + } + } + return result; + } } \ No newline at end of file diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/test/java/adt/hashtable/open/StudentTestHashtableOpenAddressLinearProbing.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/test/java/adt/hashtable/open/StudentTestHashtableOpenAddressLinearProbing.java index a5564f430..49b3a4db3 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/test/java/adt/hashtable/open/StudentTestHashtableOpenAddressLinearProbing.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/test/java/adt/hashtable/open/StudentTestHashtableOpenAddressLinearProbing.java @@ -1,110 +1,110 @@ -package adt.hashtable.open; - -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; - -import adt.hashtable.hashfunction.HashFunctionClosedAddressMethod; -import adt.hashtable.open.AbstractHashtableOpenAddress; -import adt.hashtable.open.HashtableElement; -import adt.hashtable.open.HashtableOpenAddressLinearProbingImpl; - -public class StudentTestHashtableOpenAddressLinearProbing { - - protected AbstractHashtableOpenAddress table1; - protected AbstractHashtableOpenAddress table2; - - protected final int PROPOSED_SIZE = 10; - - @Before - public void setUp() throws Exception { - table1 = new HashtableOpenAddressLinearProbingImpl( - PROPOSED_SIZE, HashFunctionClosedAddressMethod.DIVISION); - // o tamanho real utilizado vai ser PROPOSED_SIZE - table1.insert(new HashtableElement(2)); // coloca no slot indexado com 2 - table1.insert(new HashtableElement(3)); // coloca no slot indexado com 3 - table1.insert(new HashtableElement(4)); // coloca no slot indexado com 4 - table1.insert(new HashtableElement(5)); // coloca no slot indexado com 5 - - table2 = new HashtableOpenAddressLinearProbingImpl( - PROPOSED_SIZE, HashFunctionClosedAddressMethod.DIVISION); - } - - @Test - public void testInsert() { - assertEquals(0, table1.getCOLLISIONS()); - table1.insert(new HashtableElement(7)); // nao produz colisao. coloca no - // slot indexado com 7 - assertEquals(7, table1.indexOf(new HashtableElement(7))); - assertEquals(0, table1.getCOLLISIONS()); - - table1.insert(new HashtableElement(9)); // nao produz colisao. coloca no - // slot indexado com 9 - assertEquals(9, table1.indexOf(new HashtableElement(9))); - assertEquals(0, table1.getCOLLISIONS()); - - table1.insert(new HashtableElement(12)); // produz colisao com o 2. - // coloca no slot indexado - // com 6 (prox disponivel) - assertEquals(6, table1.indexOf(new HashtableElement(12))); - assertEquals(4, table1.getCOLLISIONS()); - - table2.insert(new HashtableElement(14)); // nao produz colisao. coloca - // no slot indexado com 4 - assertEquals(4, table2.indexOf(new HashtableElement(14))); - assertEquals(0, table2.getCOLLISIONS()); - - } - - @Test - public void testRemove() { - table1.remove(new HashtableElement(12)); // elemento inexistente - assertEquals(4, table1.size()); - - table1.remove(new HashtableElement(5)); // elemento existente - assertEquals(3, table1.size()); - assertNull(table1.search(new HashtableElement(5))); - - } - - @Test - public void testSearch() { - assertEquals(new HashtableElement(5), - table1.search(new HashtableElement(5))); // elemento que existe - assertNull(table1.search(new HashtableElement(15))); // elemento que nao - // existe - } - - @Test - public void testIsEmpty() { - assertFalse(table1.isEmpty()); - table1.remove(new HashtableElement(2)); // esvazia - table1.remove(new HashtableElement(3)); - table1.remove(new HashtableElement(4)); - table1.remove(new HashtableElement(5)); - assertTrue(table1.isEmpty()); - - assertTrue(table2.isEmpty()); - } - - @Test - public void testIsFull() { - assertFalse(table1.isFull()); - table1.insert(new HashtableElement(1)); // enche a tabela - table1.insert(new HashtableElement(6)); - table1.insert(new HashtableElement(7)); - table1.insert(new HashtableElement(8)); - table1.insert(new HashtableElement(9)); - table1.insert(new HashtableElement(10)); - assertTrue(table1.isFull()); - - assertFalse(table2.isFull()); - } - - @Test - public void testSize() { - assertEquals(4, table1.size()); - } - -} +package adt.hashtable.open; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; + +import adt.hashtable.hashfunction.HashFunctionClosedAddressMethod; +import adt.hashtable.open.AbstractHashtableOpenAddress; +import adt.hashtable.open.HashtableElement; +import adt.hashtable.open.HashtableOpenAddressLinearProbingImpl; + +public class StudentTestHashtableOpenAddressLinearProbing { + + protected AbstractHashtableOpenAddress table1; + protected AbstractHashtableOpenAddress table2; + + protected final int PROPOSED_SIZE = 10; + + @Before + public void setUp() throws Exception { + table1 = new HashtableOpenAddressLinearProbingImpl( + PROPOSED_SIZE, HashFunctionClosedAddressMethod.DIVISION); + // o tamanho real utilizado vai ser PROPOSED_SIZE + table1.insert(new HashtableElement(2)); // coloca no slot indexado com 2 + table1.insert(new HashtableElement(3)); // coloca no slot indexado com 3 + table1.insert(new HashtableElement(4)); // coloca no slot indexado com 4 + table1.insert(new HashtableElement(5)); // coloca no slot indexado com 5 + + table2 = new HashtableOpenAddressLinearProbingImpl( + PROPOSED_SIZE, HashFunctionClosedAddressMethod.DIVISION); + } + + @Test + public void testInsert() { + assertEquals(0, table1.getCOLLISIONS()); + table1.insert(new HashtableElement(7)); // nao produz colisao. coloca no + // slot indexado com 7 + assertEquals(7, table1.indexOf(new HashtableElement(7))); + assertEquals(0, table1.getCOLLISIONS()); + + table1.insert(new HashtableElement(9)); // nao produz colisao. coloca no + // slot indexado com 9 + assertEquals(9, table1.indexOf(new HashtableElement(9))); + assertEquals(0, table1.getCOLLISIONS()); + + table1.insert(new HashtableElement(12)); // produz colisao com o 2. + // coloca no slot indexado + // com 6 (prox disponivel) + assertEquals(6, table1.indexOf(new HashtableElement(12))); + assertEquals(4, table1.getCOLLISIONS()); + + table2.insert(new HashtableElement(14)); // nao produz colisao. coloca + // no slot indexado com 4 + assertEquals(4, table2.indexOf(new HashtableElement(14))); + assertEquals(0, table2.getCOLLISIONS()); + + } + + @Test + public void testRemove() { + table1.remove(new HashtableElement(12)); // elemento inexistente + assertEquals(4, table1.size()); + + table1.remove(new HashtableElement(5)); // elemento existente + assertEquals(3, table1.size()); + assertNull(table1.search(new HashtableElement(5))); + + } + + @Test + public void testSearch() { + assertEquals(new HashtableElement(5), + table1.search(new HashtableElement(5))); // elemento que existe + assertNull(table1.search(new HashtableElement(15))); // elemento que nao + // existe + } + + @Test + public void testIsEmpty() { + assertFalse(table1.isEmpty()); + table1.remove(new HashtableElement(2)); // esvazia + table1.remove(new HashtableElement(3)); + table1.remove(new HashtableElement(4)); + table1.remove(new HashtableElement(5)); + assertTrue(table1.isEmpty()); + + assertTrue(table2.isEmpty()); + } + + @Test + public void testIsFull() { + assertFalse(table1.isFull()); + table1.insert(new HashtableElement(1)); // enche a tabela + table1.insert(new HashtableElement(6)); + table1.insert(new HashtableElement(7)); + table1.insert(new HashtableElement(8)); + table1.insert(new HashtableElement(9)); + table1.insert(new HashtableElement(10)); + assertTrue(table1.isFull()); + + assertFalse(table2.isFull()); + } + + @Test + public void testSize() { + assertEquals(4, table1.size()); + } + +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/test/java/adt/hashtable/open/StudentTestHashtableOpenAddressQuadraticProbing.java b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/test/java/adt/hashtable/open/StudentTestHashtableOpenAddressQuadraticProbing.java index 479a9e87d..a2b10ca79 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/test/java/adt/hashtable/open/StudentTestHashtableOpenAddressQuadraticProbing.java +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/src/test/java/adt/hashtable/open/StudentTestHashtableOpenAddressQuadraticProbing.java @@ -1,106 +1,106 @@ -package adt.hashtable.open; - -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; - -import adt.hashtable.hashfunction.HashFunctionClosedAddressMethod; -import adt.hashtable.open.AbstractHashtableOpenAddress; -import adt.hashtable.open.HashtableOpenAddressQuadraticProbingImpl; -import adt.hashtable.open.HashtableElement; - -public class StudentTestHashtableOpenAddressQuadraticProbing { - protected AbstractHashtableOpenAddress table1; - protected AbstractHashtableOpenAddress table2; - - protected final int PROPOSED_SIZE = 10; - - @Before - public void setUp() throws Exception { - table1 = new HashtableOpenAddressQuadraticProbingImpl( - PROPOSED_SIZE, HashFunctionClosedAddressMethod.DIVISION, 3, 5); - // o tamanho real utilizado vai ser PROPOSED_SIZE - table1.insert(new HashtableElement(10)); // coloca no slot indexado com - // 0 - table1.insert(new HashtableElement(15)); // coloca no slot indexado com - // 5 - table1.insert(new HashtableElement(2)); // coloca no slot indexado com 2 - table1.insert(new HashtableElement(12)); // coloca no slot indexado com - // 8, teve 2 colisoes - table1.insert(new HashtableElement(4)); // coloca no slot indexado com 4 - table1.insert(new HashtableElement(8)); // coloca no slot indexado com - // 6, teve 1 colisao - - table2 = new HashtableOpenAddressQuadraticProbingImpl( - PROPOSED_SIZE, HashFunctionClosedAddressMethod.DIVISION, 3, 5); - } - - @Test - public void testInsert() { - assertEquals(3, table1.getCOLLISIONS()); - table1.insert(new HashtableElement(11)); // nao tem colisao. coloca no - // slot indexado com 1 - assertEquals(3, table1.getCOLLISIONS()); - assertEquals(1, table1.indexOf(new HashtableElement(11))); - - table1.insert(new HashtableElement(21)); // tem 1 colisao. coloca no - // slot indexado com 9 - assertEquals(4, table1.getCOLLISIONS()); - assertEquals(9, table1.indexOf(new HashtableElement(21))); - - } - - @Test - public void testRemove() { - table1.remove(new HashtableElement(17)); // elemento inexistente - assertEquals(6, table1.size()); - - table1.remove(new HashtableElement(12)); // elemento existente - assertEquals(5, table1.size()); - assertNull(table1.search(new HashtableElement(12))); - } - - @Test - public void testSearch() { - assertEquals(new HashtableElement(4), - table1.search(new HashtableElement(4))); // elemento que existe - assertNull(table1.search(new HashtableElement(14))); // elemento que nao - // existe - - } - - @Test - public void testIsEmpty() { - assertFalse(table1.isEmpty()); - table1.remove(new HashtableElement(15)); // esvazia - table1.remove(new HashtableElement(8)); - table1.remove(new HashtableElement(12)); - table1.remove(new HashtableElement(2)); - table1.remove(new HashtableElement(10)); - table1.remove(new HashtableElement(4)); - assertTrue(table1.isEmpty()); - - assertTrue(table2.isEmpty()); - } - - @Test - public void testIsFull() { - assertFalse(table1.isFull()); - table1.insert(new HashtableElement(1)); // enche a tabela - table1.insert(new HashtableElement(23)); - table1.insert(new HashtableElement(37)); - table1.insert(new HashtableElement(49)); - assertTrue(table1.isFull()); - - assertFalse(table2.isFull()); - } - - @Test - public void testSize() { - assertEquals(6, table1.size()); - table1.insert(new HashtableElement(23)); - assertEquals(7, table1.size()); - } - -} +package adt.hashtable.open; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; + +import adt.hashtable.hashfunction.HashFunctionClosedAddressMethod; +import adt.hashtable.open.AbstractHashtableOpenAddress; +import adt.hashtable.open.HashtableOpenAddressQuadraticProbingImpl; +import adt.hashtable.open.HashtableElement; + +public class StudentTestHashtableOpenAddressQuadraticProbing { + protected AbstractHashtableOpenAddress table1; + protected AbstractHashtableOpenAddress table2; + + protected final int PROPOSED_SIZE = 10; + + @Before + public void setUp() throws Exception { + table1 = new HashtableOpenAddressQuadraticProbingImpl( + PROPOSED_SIZE, HashFunctionClosedAddressMethod.DIVISION, 3, 5); + // o tamanho real utilizado vai ser PROPOSED_SIZE + table1.insert(new HashtableElement(10)); // coloca no slot indexado com + // 0 + table1.insert(new HashtableElement(15)); // coloca no slot indexado com + // 5 + table1.insert(new HashtableElement(2)); // coloca no slot indexado com 2 + table1.insert(new HashtableElement(12)); // coloca no slot indexado com + // 8, teve 2 colisoes + table1.insert(new HashtableElement(4)); // coloca no slot indexado com 4 + table1.insert(new HashtableElement(8)); // coloca no slot indexado com + // 6, teve 1 colisao + + table2 = new HashtableOpenAddressQuadraticProbingImpl( + PROPOSED_SIZE, HashFunctionClosedAddressMethod.DIVISION, 3, 5); + } + + @Test + public void testInsert() { + assertEquals(3, table1.getCOLLISIONS()); + table1.insert(new HashtableElement(11)); // nao tem colisao. coloca no + // slot indexado com 1 + assertEquals(3, table1.getCOLLISIONS()); + assertEquals(1, table1.indexOf(new HashtableElement(11))); + + table1.insert(new HashtableElement(21)); // tem 1 colisao. coloca no + // slot indexado com 9 + assertEquals(4, table1.getCOLLISIONS()); + assertEquals(9, table1.indexOf(new HashtableElement(21))); + + } + + @Test + public void testRemove() { + table1.remove(new HashtableElement(17)); // elemento inexistente + assertEquals(6, table1.size()); + + table1.remove(new HashtableElement(12)); // elemento existente + assertEquals(5, table1.size()); + assertNull(table1.search(new HashtableElement(12))); + } + + @Test + public void testSearch() { + assertEquals(new HashtableElement(4), + table1.search(new HashtableElement(4))); // elemento que existe + assertNull(table1.search(new HashtableElement(14))); // elemento que nao + // existe + + } + + @Test + public void testIsEmpty() { + assertFalse(table1.isEmpty()); + table1.remove(new HashtableElement(15)); // esvazia + table1.remove(new HashtableElement(8)); + table1.remove(new HashtableElement(12)); + table1.remove(new HashtableElement(2)); + table1.remove(new HashtableElement(10)); + table1.remove(new HashtableElement(4)); + assertTrue(table1.isEmpty()); + + assertTrue(table2.isEmpty()); + } + + @Test + public void testIsFull() { + assertFalse(table1.isFull()); + table1.insert(new HashtableElement(1)); // enche a tabela + table1.insert(new HashtableElement(23)); + table1.insert(new HashtableElement(37)); + table1.insert(new HashtableElement(49)); + assertTrue(table1.isFull()); + + assertFalse(table2.isFull()); + } + + @Test + public void testSize() { + assertEquals(6, table1.size()); + table1.insert(new HashtableElement(23)); + assertEquals(7, table1.size()); + } + +} diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/target/classes/META-INF/MANIFEST.MF b/java/R09-01-Rot-TabelaHash-EndAberto-environment/target/classes/META-INF/MANIFEST.MF index 6c4b9cc34..a05e7910c 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/target/classes/META-INF/MANIFEST.MF +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/target/classes/META-INF/MANIFEST.MF @@ -1,5 +1,5 @@ -Manifest-Version: 1.0 -Built-By: amintas -Build-Jdk: 1.8.0_131 -Created-By: Maven Integration for Eclipse - +Manifest-Version: 1.0 +Built-By: amintas +Build-Jdk: 1.8.0_131 +Created-By: Maven Integration for Eclipse + diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml b/java/R09-01-Rot-TabelaHash-EndAberto-environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml index 7ea5878b2..f99191b22 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml @@ -1,98 +1,98 @@ - - 4.0.0 - - br.edu.ufcg.ccc - submission - 1.0 - jar - Submissao de roteiro - - - - ufcg-leda - http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda - default - - true - always - - - - - - - junit - junit - 4.12 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - maven-clean-plugin - 3.0.0 - - - auto-clean - build - - clean - - - - - - - org.walkmod - maven-walkmod-plugin - 1.3 - - walkmod.xml - - - - package - - apply - - - false - - - - - - br.edu.ufcg.ccc - leda-compactor-tool - 1.0.0-SNAPSHOT - - - install - - compact - - - - INSIRA SEU NUMERO DE MATRICULA - - R0X-0X - - 2017.1 - http://150.165.85.29:81/submitAtividade - - - - - - - + + 4.0.0 + + br.edu.ufcg.ccc + submission + 1.0 + jar + Submissao de roteiro + + + + ufcg-leda + http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda + default + + true + always + + + + + + + junit + junit + 4.12 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + maven-clean-plugin + 3.0.0 + + + auto-clean + build + + clean + + + + + + + org.walkmod + maven-walkmod-plugin + 1.3 + + walkmod.xml + + + + package + + apply + + + false + + + + + + br.edu.ufcg.ccc + leda-compactor-tool + 1.0.0-SNAPSHOT + + + install + + compact + + + + INSIRA SEU NUMERO DE MATRICULA + + R0X-0X + + 2017.1 + http://150.165.85.29:81/submitAtividade + + + + + + + diff --git a/java/R09-01-Rot-TabelaHash-EndAberto-environment/walkmod.xml b/java/R09-01-Rot-TabelaHash-EndAberto-environment/walkmod.xml index d391a36b4..85902bfec 100644 --- a/java/R09-01-Rot-TabelaHash-EndAberto-environment/walkmod.xml +++ b/java/R09-01-Rot-TabelaHash-EndAberto-environment/walkmod.xml @@ -1,4 +1,4 @@ - - - + + + \ No newline at end of file diff --git a/java/R11-01-Rot-BST-Comparator-Sorting-environment/pom.xml b/java/R11-01-Rot-BST-Comparator-Sorting-environment/pom.xml index 014384f0c..210ae43f9 100644 --- a/java/R11-01-Rot-BST-Comparator-Sorting-environment/pom.xml +++ b/java/R11-01-Rot-BST-Comparator-Sorting-environment/pom.xml @@ -1,98 +1,98 @@ - - 4.0.0 - - br.edu.ufcg.ccc - submission - 1.0 - jar - Submissao de roteiro - - - - ufcg-leda - http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda - default - - true - always - - - - - - - junit - junit - 4.12 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - maven-clean-plugin - 3.0.0 - - - auto-clean - build - - clean - - - - - - - org.walkmod - maven-walkmod-plugin - 1.3 - - walkmod.xml - - - - package - - apply - - - false - - - - - - br.edu.ufcg.ccc - leda-compactor-tool - 1.0.0-SNAPSHOT - - - install - - compact - - - - 116110761 - - R11-01 - - 2017.1 - http://150.165.85.29:81/submitAtividade - - - - - - - + + 4.0.0 + + br.edu.ufcg.ccc + submission + 1.0 + jar + Submissao de roteiro + + + + ufcg-leda + http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda + default + + true + always + + + + + + + junit + junit + 4.12 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + maven-clean-plugin + 3.0.0 + + + auto-clean + build + + clean + + + + + + + org.walkmod + maven-walkmod-plugin + 1.3 + + walkmod.xml + + + + package + + apply + + + false + + + + + + br.edu.ufcg.ccc + leda-compactor-tool + 1.0.0-SNAPSHOT + + + install + + compact + + + + 116110761 + + R11-01 + + 2017.1 + http://150.165.85.29:81/submitAtividade + + + + + + + diff --git a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/BST.java b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/BST.java index e2006ff32..1a0b6c375 100644 --- a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/BST.java +++ b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/BST.java @@ -1,34 +1,34 @@ -package adt.bst; - -import adt.bt.BT; - -/** - * The interface of a binary search tree (BST). - */ -public interface BST> extends BT { - - /** - * Returns the node containing the greatest element in a BST. If the tree is - * empty the method returns null. - */ - public BSTNode maximum(); - - /** - * Returns the node containing the lowest element in a BST. If the tree is - * empty the method returns null. - */ - public BSTNode minimum(); - - /** - * Returns a node containing the successor of the given element in a BST or - * null if it does not exist. - */ - public BSTNode sucessor(T element); - - /** - * Returns a node containing the predecessor of the given element in a BST - * or null if it does not exist. - */ - public BSTNode predecessor(T element); - -} +package adt.bst; + +import adt.bt.BT; + +/** + * The interface of a binary search tree (BST). + */ +public interface BST> extends BT { + + /** + * Returns the node containing the greatest element in a BST. If the tree is + * empty the method returns null. + */ + public BSTNode maximum(); + + /** + * Returns the node containing the lowest element in a BST. If the tree is + * empty the method returns null. + */ + public BSTNode minimum(); + + /** + * Returns a node containing the successor of the given element in a BST or + * null if it does not exist. + */ + public BSTNode sucessor(T element); + + /** + * Returns a node containing the predecessor of the given element in a BST + * or null if it does not exist. + */ + public BSTNode predecessor(T element); + +} diff --git a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/BSTImpl.java b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/BSTImpl.java index 08404c85e..8f3e1e7bd 100644 --- a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/BSTImpl.java +++ b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/BSTImpl.java @@ -1,293 +1,293 @@ -package adt.bst; - -public class BSTImpl> implements BST { - - protected BSTNode node; - - public BSTImpl() { - node = new BSTNode(); - } - - public BSTNode getRoot() { - return this.node; - } - - protected void setRoot(BSTNode node) { - this.node = node; - } - - @Override - public boolean isEmpty() { - return node.isEmpty(); - } - - @Override - public int height() { - return getHeight(getRoot()); - } - - private int getHeight(BSTNode node) { - int height = -1; - if (!node.isEmpty()) { - int heightLeft = getHeight((BSTNode) node.getLeft()); - int heightRight = getHeight((BSTNode) node.getRight()); - height = 1 + longer(heightLeft, heightRight); - } - return height; - - } - - private int longer(int heightLeft, int heightRight) { - int result = heightLeft; - if (heightRight > heightLeft) { - result = heightRight; - } - return result; - } - - @Override - public BSTNode search(T element) { - return binarySearch(getRoot(), element); - } - - - @SuppressWarnings("unchecked") - private BSTNode binarySearch(BSTNode node, T element) { - BSTNode result = new BSTNode.Builder().data(null).left(null).right(null).parent(null).build(); - if (node.isEmpty() || node.getData().equals(element)) { - result = node; - } else if (node.getData().compareTo(element) > 0) { - result = binarySearch((BSTNode) node.getLeft(), element); - } else { - result = binarySearch((BSTNode) node.getRight(), element); - } - return result; - } - - @Override - public void insert(T element) { - insertWithNode(getRoot(), element); - } - - @SuppressWarnings("unchecked") - private void insertWithNode(BSTNode node, T element) { - if (node.isEmpty()) { - node.setData(element); - node.setLeft(new BSTNode.Builder().data(null).parent(node).build()); - node.setRight(new BSTNode.Builder().data(null).parent(node).build()); - } else { - if ((element.compareTo(node.getData()) < 0)) { - insertWithNode((BSTNode) node.getLeft(), element); - } else if ((element.compareTo(node.getData()) > 0)) { - insertWithNode((BSTNode) node.getRight(), element); - } - - } - - } - - @Override - public BSTNode maximum() { - return maximumWithNode(getRoot()); - } - - protected BSTNode maximumWithNode(BSTNode node) { - BSTNode max = null; - if (!(node.isEmpty())) { - max = node; - while (!(max.getRight().isEmpty())) { - max = (BSTNode) max.getRight(); - } - } - return max; - } - - @Override - public BSTNode minimum() { - return minimumWithNode(getRoot()); - } - - protected BSTNode minimumWithNode(BSTNode node) { - BSTNode min = null; - if (!(node.isEmpty())) { - min = node; - while (!(min.getLeft().isEmpty())) { - min = (BSTNode) min.getLeft(); - } - } - return min; - } - - @Override - public BSTNode sucessor(T element) { - BSTNode result = null; - BSTNode node = search(element); - if (!(node.isEmpty())) { - if (!(node.getRight().isEmpty())) { - result = minimumWithNode((BSTNode) node.getRight()); - } else { - result = (BSTNode) node.getParent(); - while (result != null && node.equals(result.getRight())) { - node = result; - result = (BSTNode) result.getParent(); - } - } - } - return result; - - } - - @Override - public BSTNode predecessor(T element) { - BSTNode result = null; - BSTNode node = search(element); - if (!(node.isEmpty())) { - if (!(node.getLeft().isEmpty())) { - result = maximumWithNode((BSTNode) node.getLeft()); - } else { - result = (BSTNode) node.getParent(); - while (result != null && node.equals(result.getLeft())) { - node = result; - result = (BSTNode) result.getParent(); - } - } - } - return result; - } - - @Override - public void remove(T element) { - BSTNode node = search(element); - removeRecursive(node); - } - - private void removeRecursive(BSTNode node) { - if (!node.isEmpty()) { - if (node.isLeaf()) { - node.setData(null); - node.setLeft(null); - node.setRight(null); - } else if (hasOneChild(node)) { - if (!(node.equals(getRoot()) && node.getParent() == null)) { - if (node.getParent().getLeft().equals(node)) { - if (!node.getLeft().isEmpty()) { - - node.getParent().setLeft(node.getLeft()); - node.getLeft().setParent(node.getParent()); - - } else { - node.getParent().setLeft(node.getRight()); - node.getRight().setParent(node.getParent()); - } - - } else { - if (!node.getLeft().isEmpty()) { - - node.getParent().setRight(node.getLeft()); - node.getLeft().setParent(node.getParent()); - } else { - - node.getParent().setRight(node.getRight()); - node.getRight().setParent(node.getParent()); - - } - } - } else { - if (getRoot().getLeft().isEmpty()) { - setRoot((BSTNode) getRoot().getRight()); - getRoot().setParent(null); - } else if (getRoot().getRight().isEmpty()) { - setRoot((BSTNode) getRoot().getLeft()); - getRoot().setParent(null); - } - } - - } else { - BSTNode sucessor = sucessor(node.getData()); - node.setData(sucessor.getData()); - removeRecursive(sucessor); - } - } - } - - protected boolean hasOneChild(BSTNode node) { - return !(node.getLeft().isEmpty() && node.getRight().isEmpty()) && (node.getLeft().isEmpty() || node.getRight().isEmpty()); - } - - @Override - public T[] preOrder() { - T[] array = util.Util.makeArrayOfComparable(size()); - preOrderRecursive(getRoot(), array); - return array; - } - - private void preOrderRecursive(BSTNode node, T[] array) { - if (!node.isEmpty()) { - add(array,node.getData()); - preOrderRecursive((BSTNode) node.getLeft(), array); - preOrderRecursive((BSTNode) node.getRight(), array); - } - } - - protected void add(T[] array, T data) { - int i = 0; - while (i < array.length) { - if (array[i] == null) { - array[i] = data; - break; - } else { - i++; - } - } - } - - @Override - public T[] order() { - T[] array = util.Util.makeArrayOfComparable(size()); - orderRecursive(getRoot(), array); - return array; - } - - private void orderRecursive(BSTNode node, T[] array) { - if (!node.isEmpty()) { - orderRecursive((BSTNode) node.getLeft(), array); - add(array, node.getData()); - orderRecursive((BSTNode) node.getRight(), array); - } - - } - - @Override - public T[] postOrder() { - T[] array = util.Util.makeArrayOfComparable(size()); - postOrderRecursive(getRoot(), array); - return array; - } - - private void postOrderRecursive(BSTNode node, T[] array) { - if (!node.isEmpty()) { - postOrderRecursive((BSTNode) node.getLeft(), array); - postOrderRecursive((BSTNode) node.getRight(), array); - add(array, node.getData()); - } - } - - /** - * This method is already implemented using recursion. You must understand - * how it work and use similar idea with the other methods. - */ - @Override - public int size() { - return size(node); - } - - private int size(BSTNode node) { - int result = 0; - // base case means doing nothing (return 0) - if (!node.isEmpty()) { // indusctive case - result = 1 + size((BSTNode) node.getLeft()) + size((BSTNode) node.getRight()); - } - return result; - } - -} +package adt.bst; + +public class BSTImpl> implements BST { + + protected BSTNode node; + + public BSTImpl() { + node = new BSTNode(); + } + + public BSTNode getRoot() { + return this.node; + } + + protected void setRoot(BSTNode node) { + this.node = node; + } + + @Override + public boolean isEmpty() { + return node.isEmpty(); + } + + @Override + public int height() { + return getHeight(getRoot()); + } + + private int getHeight(BSTNode node) { + int height = -1; + if (!node.isEmpty()) { + int heightLeft = getHeight((BSTNode) node.getLeft()); + int heightRight = getHeight((BSTNode) node.getRight()); + height = 1 + longer(heightLeft, heightRight); + } + return height; + + } + + private int longer(int heightLeft, int heightRight) { + int result = heightLeft; + if (heightRight > heightLeft) { + result = heightRight; + } + return result; + } + + @Override + public BSTNode search(T element) { + return binarySearch(getRoot(), element); + } + + + @SuppressWarnings("unchecked") + private BSTNode binarySearch(BSTNode node, T element) { + BSTNode result = new BSTNode.Builder().data(null).left(null).right(null).parent(null).build(); + if (node.isEmpty() || node.getData().equals(element)) { + result = node; + } else if (node.getData().compareTo(element) > 0) { + result = binarySearch((BSTNode) node.getLeft(), element); + } else { + result = binarySearch((BSTNode) node.getRight(), element); + } + return result; + } + + @Override + public void insert(T element) { + insertWithNode(getRoot(), element); + } + + @SuppressWarnings("unchecked") + private void insertWithNode(BSTNode node, T element) { + if (node.isEmpty()) { + node.setData(element); + node.setLeft(new BSTNode.Builder().data(null).parent(node).build()); + node.setRight(new BSTNode.Builder().data(null).parent(node).build()); + } else { + if ((element.compareTo(node.getData()) < 0)) { + insertWithNode((BSTNode) node.getLeft(), element); + } else if ((element.compareTo(node.getData()) > 0)) { + insertWithNode((BSTNode) node.getRight(), element); + } + + } + + } + + @Override + public BSTNode maximum() { + return maximumWithNode(getRoot()); + } + + protected BSTNode maximumWithNode(BSTNode node) { + BSTNode max = null; + if (!(node.isEmpty())) { + max = node; + while (!(max.getRight().isEmpty())) { + max = (BSTNode) max.getRight(); + } + } + return max; + } + + @Override + public BSTNode minimum() { + return minimumWithNode(getRoot()); + } + + protected BSTNode minimumWithNode(BSTNode node) { + BSTNode min = null; + if (!(node.isEmpty())) { + min = node; + while (!(min.getLeft().isEmpty())) { + min = (BSTNode) min.getLeft(); + } + } + return min; + } + + @Override + public BSTNode sucessor(T element) { + BSTNode result = null; + BSTNode node = search(element); + if (!(node.isEmpty())) { + if (!(node.getRight().isEmpty())) { + result = minimumWithNode((BSTNode) node.getRight()); + } else { + result = (BSTNode) node.getParent(); + while (result != null && node.equals(result.getRight())) { + node = result; + result = (BSTNode) result.getParent(); + } + } + } + return result; + + } + + @Override + public BSTNode predecessor(T element) { + BSTNode result = null; + BSTNode node = search(element); + if (!(node.isEmpty())) { + if (!(node.getLeft().isEmpty())) { + result = maximumWithNode((BSTNode) node.getLeft()); + } else { + result = (BSTNode) node.getParent(); + while (result != null && node.equals(result.getLeft())) { + node = result; + result = (BSTNode) result.getParent(); + } + } + } + return result; + } + + @Override + public void remove(T element) { + BSTNode node = search(element); + removeRecursive(node); + } + + private void removeRecursive(BSTNode node) { + if (!node.isEmpty()) { + if (node.isLeaf()) { + node.setData(null); + node.setLeft(null); + node.setRight(null); + } else if (hasOneChild(node)) { + if (!(node.equals(getRoot()) && node.getParent() == null)) { + if (node.getParent().getLeft().equals(node)) { + if (!node.getLeft().isEmpty()) { + + node.getParent().setLeft(node.getLeft()); + node.getLeft().setParent(node.getParent()); + + } else { + node.getParent().setLeft(node.getRight()); + node.getRight().setParent(node.getParent()); + } + + } else { + if (!node.getLeft().isEmpty()) { + + node.getParent().setRight(node.getLeft()); + node.getLeft().setParent(node.getParent()); + } else { + + node.getParent().setRight(node.getRight()); + node.getRight().setParent(node.getParent()); + + } + } + } else { + if (getRoot().getLeft().isEmpty()) { + setRoot((BSTNode) getRoot().getRight()); + getRoot().setParent(null); + } else if (getRoot().getRight().isEmpty()) { + setRoot((BSTNode) getRoot().getLeft()); + getRoot().setParent(null); + } + } + + } else { + BSTNode sucessor = sucessor(node.getData()); + node.setData(sucessor.getData()); + removeRecursive(sucessor); + } + } + } + + protected boolean hasOneChild(BSTNode node) { + return !(node.getLeft().isEmpty() && node.getRight().isEmpty()) && (node.getLeft().isEmpty() || node.getRight().isEmpty()); + } + + @Override + public T[] preOrder() { + T[] array = util.Util.makeArrayOfComparable(size()); + preOrderRecursive(getRoot(), array); + return array; + } + + private void preOrderRecursive(BSTNode node, T[] array) { + if (!node.isEmpty()) { + add(array,node.getData()); + preOrderRecursive((BSTNode) node.getLeft(), array); + preOrderRecursive((BSTNode) node.getRight(), array); + } + } + + protected void add(T[] array, T data) { + int i = 0; + while (i < array.length) { + if (array[i] == null) { + array[i] = data; + break; + } else { + i++; + } + } + } + + @Override + public T[] order() { + T[] array = util.Util.makeArrayOfComparable(size()); + orderRecursive(getRoot(), array); + return array; + } + + private void orderRecursive(BSTNode node, T[] array) { + if (!node.isEmpty()) { + orderRecursive((BSTNode) node.getLeft(), array); + add(array, node.getData()); + orderRecursive((BSTNode) node.getRight(), array); + } + + } + + @Override + public T[] postOrder() { + T[] array = util.Util.makeArrayOfComparable(size()); + postOrderRecursive(getRoot(), array); + return array; + } + + private void postOrderRecursive(BSTNode node, T[] array) { + if (!node.isEmpty()) { + postOrderRecursive((BSTNode) node.getLeft(), array); + postOrderRecursive((BSTNode) node.getRight(), array); + add(array, node.getData()); + } + } + + /** + * This method is already implemented using recursion. You must understand + * how it work and use similar idea with the other methods. + */ + @Override + public int size() { + return size(node); + } + + private int size(BSTNode node) { + int result = 0; + // base case means doing nothing (return 0) + if (!node.isEmpty()) { // indusctive case + result = 1 + size((BSTNode) node.getLeft()) + size((BSTNode) node.getRight()); + } + return result; + } + +} diff --git a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/BSTNode.java b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/BSTNode.java index 3ca6f8ecc..b6e9637ae 100644 --- a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/BSTNode.java +++ b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/BSTNode.java @@ -1,58 +1,58 @@ -package adt.bst; - -import adt.bt.BTNode; - -public class BSTNode> extends BTNode { - - public BSTNode() { - super(); - } - - //código abaixo é um exempo de uso do padrão Builder para construir - //objetos do tipo BSTNode sem usar construtor diretamente. - //o código cliente desse padrao, criando o no vazio seria: - // BSTNode node = (BSTNode) new BSTNode.Builder() - // .data(null) - // .left(null) - // .right(null) - // .parent(null) - // .build(); - - public static class Builder{ - T data; - BTNode left; - BTNode right; - BTNode parent; - - public BSTNode.Builder data(T data){ - this.data = data; - return this; - } - - public BSTNode.Builder left(BTNode left){ - this.left = left; - return this; - } - - public BSTNode.Builder right(BTNode right){ - this.right = right; - return this; - } - - public BSTNode.Builder parent(BTNode parent){ - this.parent = parent; - return this; - } - - public BSTNode build(){ - return new BSTNode(this); - } - } - private BSTNode(BSTNode.Builder builder){ - this.data = builder.data; - this.left = builder.left; - this.right = builder.right; - this.parent = builder.parent; - - } -} +package adt.bst; + +import adt.bt.BTNode; + +public class BSTNode> extends BTNode { + + public BSTNode() { + super(); + } + + //código abaixo é um exempo de uso do padrão Builder para construir + //objetos do tipo BSTNode sem usar construtor diretamente. + //o código cliente desse padrao, criando o no vazio seria: + // BSTNode node = (BSTNode) new BSTNode.Builder() + // .data(null) + // .left(null) + // .right(null) + // .parent(null) + // .build(); + + public static class Builder{ + T data; + BTNode left; + BTNode right; + BTNode parent; + + public BSTNode.Builder data(T data){ + this.data = data; + return this; + } + + public BSTNode.Builder left(BTNode left){ + this.left = left; + return this; + } + + public BSTNode.Builder right(BTNode right){ + this.right = right; + return this; + } + + public BSTNode.Builder parent(BTNode parent){ + this.parent = parent; + return this; + } + + public BSTNode build(){ + return new BSTNode(this); + } + } + private BSTNode(BSTNode.Builder builder){ + this.data = builder.data; + this.left = builder.left; + this.right = builder.right; + this.parent = builder.parent; + + } +} diff --git a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/extended/SortComparatorBST.java b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/extended/SortComparatorBST.java index 0d7e64956..dfad9142e 100644 --- a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/extended/SortComparatorBST.java +++ b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/extended/SortComparatorBST.java @@ -1,30 +1,30 @@ -package adt.bst.extended; - -import adt.bst.BST; - -/** - * Interface definindo uma BST que trabalha obrigatoriamente com um comparator. - * Dessa forma, toda e qualquer comparacao feita pela implementacao deve usar - * o comparator. - * @author Adalberto - * - */ -public interface SortComparatorBST> extends BST{ - - /** - * Metodo que recebe um array de itens e retorna o array ordenado segundo o comparator da BST. - * @param array - * @return - */ - public T[] sort(T[] array); - - /** - * Novo metodo de percurso na BST que percorre a arvore de forma contraria ao percurso - * em ordem. Dessa forma a arvore eh percorrida: DIR, RAIZ, ESQ. - * Obs: voce nao pode usar nenhum metodo de percurso implementado. Voce precisa implementar - * essa nova forma de percurso. - * - * @return - */ - public T[] reverseOrder(); -} +package adt.bst.extended; + +import adt.bst.BST; + +/** + * Interface definindo uma BST que trabalha obrigatoriamente com um comparator. + * Dessa forma, toda e qualquer comparacao feita pela implementacao deve usar + * o comparator. + * @author Adalberto + * + */ +public interface SortComparatorBST> extends BST{ + + /** + * Metodo que recebe um array de itens e retorna o array ordenado segundo o comparator da BST. + * @param array + * @return + */ + public T[] sort(T[] array); + + /** + * Novo metodo de percurso na BST que percorre a arvore de forma contraria ao percurso + * em ordem. Dessa forma a arvore eh percorrida: DIR, RAIZ, ESQ. + * Obs: voce nao pode usar nenhum metodo de percurso implementado. Voce precisa implementar + * essa nova forma de percurso. + * + * @return + */ + public T[] reverseOrder(); +} diff --git a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/extended/SortComparatorBSTImpl.java b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/extended/SortComparatorBSTImpl.java index b758244cf..15fd82526 100644 --- a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/extended/SortComparatorBSTImpl.java +++ b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bst/extended/SortComparatorBSTImpl.java @@ -1,200 +1,200 @@ -package adt.bst.extended; - -import java.util.Comparator; - -import adt.bst.BSTImpl; -import adt.bst.BSTNode; - -/** - * Implementacao de SortComparatorBST, uma BST que usa um comparator interno em suas funcionalidades - * e possui um metodo de ordenar um array dado como parametro, retornando o resultado do percurso - * desejado que produz o array ordenado. - * - * @author Adalberto - * - * @param - */ -public class SortComparatorBSTImpl> extends BSTImpl implements SortComparatorBST { - - private Comparator comparator; - - public SortComparatorBSTImpl(Comparator comparator) { - super(); - this.comparator = comparator; - } - - @Override - public BSTNode search(T element) { - return binarySearch(getRoot(), element); - } - - - @SuppressWarnings("unchecked") - private BSTNode binarySearch(BSTNode node, T element) { - BSTNode result = new BSTNode.Builder().data(null).left(null).right(null).parent(null).build(); - if (node.isEmpty() || getComparator().compare(node.getData(), element) == 0) { - result = node; - } else if (getComparator().compare(node.getData(),element) > 0) { - result = binarySearch((BSTNode) node.getLeft(), element); - } else { - result = binarySearch((BSTNode) node.getRight(), element); - } - return result; - } - - @Override - public void insert(T element) { - insertWithNode(getRoot(), element); - } - - @SuppressWarnings("unchecked") - private void insertWithNode(BSTNode node, T element) { - if (node.isEmpty()) { - node.setData(element); - node.setLeft(new BSTNode.Builder().data(null).parent(node).build()); - node.setRight(new BSTNode.Builder().data(null).parent(node).build()); - } else { - if ((getComparator().compare(element, node.getData()) < 0)) { - insertWithNode((BSTNode) node.getLeft(), element); - } else if ((element.compareTo(node.getData()) > 0)) { - insertWithNode((BSTNode) node.getRight(), element); - } - - } - - } - - @Override - public BSTNode sucessor(T element) { - BSTNode result = null; - BSTNode node = search(element); - if (!(node.isEmpty())) { - if (!(node.getRight().isEmpty())) { - result = minimumWithNode((BSTNode) node.getRight()); - } else { - result = (BSTNode) node.getParent(); - while (result != null && sameData(node.getData(), result.getRight().getData())) { - node = result; - result = (BSTNode) result.getParent(); - } - } - } - return result; - - } - - private boolean sameData(T data1, T data2) { - if (data1 == null || data2 == null) { - return false; - } - return getComparator().compare(data1, data2) == 0; - } - - @Override - public BSTNode predecessor(T element) { - BSTNode result = null; - BSTNode node = search(element); - if (!(node.isEmpty())) { - if (!(node.getLeft().isEmpty())) { - result = maximumWithNode((BSTNode) node.getLeft()); - } else { - result = (BSTNode) node.getParent(); - while (result != null && sameData(node.getData(), result.getLeft().getData())) { - node = result; - result = (BSTNode) result.getParent(); - } - } - } - return result; - } - - @Override - public void remove(T element) { - BSTNode node = search(element); - removeRecursive(node); - } - - private void removeRecursive(BSTNode node) { - if (!node.isEmpty()) { - if (node.isLeaf()) { - node.setData(null); - node.setLeft(null); - node.setRight(null); - } else if (hasOneChild(node)) { - if (!(getComparator().compare(node.getData(), getRoot().getData()) == 0 && node.getParent() == null)) { - if (getComparator().compare(node.getParent().getLeft().getData(), node.getData()) == 0) { - if (!node.getLeft().isEmpty()) { - - node.getParent().setLeft(node.getLeft()); - node.getLeft().setParent(node.getParent()); - - } else { - node.getParent().setLeft(node.getRight()); - node.getRight().setParent(node.getParent()); - } - - } else { - if (!node.getLeft().isEmpty()) { - - node.getParent().setRight(node.getLeft()); - node.getLeft().setParent(node.getParent()); - } else { - - node.getParent().setRight(node.getRight()); - node.getRight().setParent(node.getParent()); - - } - } - } else { - if (getRoot().getLeft().isEmpty()) { - setRoot((BSTNode) getRoot().getRight()); - getRoot().setParent(null); - } else if (getRoot().getRight().isEmpty()) { - setRoot((BSTNode) getRoot().getLeft()); - getRoot().setParent(null); - } - } - - } else { - BSTNode sucessor = sucessor(node.getData()); - node.setData(sucessor.getData()); - removeRecursive(sucessor); - } - } - } - - @Override - public T[] sort(T[] array) { - setRoot(new BSTNode()); - for (int i = 0; i < array.length; i++) { - insert(array[i]); - } - return order(); - } - - @Override - public T[] reverseOrder() { - T[] array = util.Util.makeArrayOfComparable(size()); - orderRecursive(getRoot(), array); - return array; - } - - private void orderRecursive(BSTNode node, T[] array) { - if (!node.isEmpty()) { - orderRecursive((BSTNode) node.getRight(), array); - add(array, node.getData()); - orderRecursive((BSTNode) node.getLeft(), array); - - } - - } - - public Comparator getComparator() { - return comparator; - } - - public void setComparator(Comparator comparator) { - this.comparator = comparator; - } - -} +package adt.bst.extended; + +import java.util.Comparator; + +import adt.bst.BSTImpl; +import adt.bst.BSTNode; + +/** + * Implementacao de SortComparatorBST, uma BST que usa um comparator interno em suas funcionalidades + * e possui um metodo de ordenar um array dado como parametro, retornando o resultado do percurso + * desejado que produz o array ordenado. + * + * @author Adalberto + * + * @param + */ +public class SortComparatorBSTImpl> extends BSTImpl implements SortComparatorBST { + + private Comparator comparator; + + public SortComparatorBSTImpl(Comparator comparator) { + super(); + this.comparator = comparator; + } + + @Override + public BSTNode search(T element) { + return binarySearch(getRoot(), element); + } + + + @SuppressWarnings("unchecked") + private BSTNode binarySearch(BSTNode node, T element) { + BSTNode result = new BSTNode.Builder().data(null).left(null).right(null).parent(null).build(); + if (node.isEmpty() || getComparator().compare(node.getData(), element) == 0) { + result = node; + } else if (getComparator().compare(node.getData(),element) > 0) { + result = binarySearch((BSTNode) node.getLeft(), element); + } else { + result = binarySearch((BSTNode) node.getRight(), element); + } + return result; + } + + @Override + public void insert(T element) { + insertWithNode(getRoot(), element); + } + + @SuppressWarnings("unchecked") + private void insertWithNode(BSTNode node, T element) { + if (node.isEmpty()) { + node.setData(element); + node.setLeft(new BSTNode.Builder().data(null).parent(node).build()); + node.setRight(new BSTNode.Builder().data(null).parent(node).build()); + } else { + if ((getComparator().compare(element, node.getData()) < 0)) { + insertWithNode((BSTNode) node.getLeft(), element); + } else if ((element.compareTo(node.getData()) > 0)) { + insertWithNode((BSTNode) node.getRight(), element); + } + + } + + } + + @Override + public BSTNode sucessor(T element) { + BSTNode result = null; + BSTNode node = search(element); + if (!(node.isEmpty())) { + if (!(node.getRight().isEmpty())) { + result = minimumWithNode((BSTNode) node.getRight()); + } else { + result = (BSTNode) node.getParent(); + while (result != null && sameData(node.getData(), result.getRight().getData())) { + node = result; + result = (BSTNode) result.getParent(); + } + } + } + return result; + + } + + private boolean sameData(T data1, T data2) { + if (data1 == null || data2 == null) { + return false; + } + return getComparator().compare(data1, data2) == 0; + } + + @Override + public BSTNode predecessor(T element) { + BSTNode result = null; + BSTNode node = search(element); + if (!(node.isEmpty())) { + if (!(node.getLeft().isEmpty())) { + result = maximumWithNode((BSTNode) node.getLeft()); + } else { + result = (BSTNode) node.getParent(); + while (result != null && sameData(node.getData(), result.getLeft().getData())) { + node = result; + result = (BSTNode) result.getParent(); + } + } + } + return result; + } + + @Override + public void remove(T element) { + BSTNode node = search(element); + removeRecursive(node); + } + + private void removeRecursive(BSTNode node) { + if (!node.isEmpty()) { + if (node.isLeaf()) { + node.setData(null); + node.setLeft(null); + node.setRight(null); + } else if (hasOneChild(node)) { + if (!(getComparator().compare(node.getData(), getRoot().getData()) == 0 && node.getParent() == null)) { + if (getComparator().compare(node.getParent().getLeft().getData(), node.getData()) == 0) { + if (!node.getLeft().isEmpty()) { + + node.getParent().setLeft(node.getLeft()); + node.getLeft().setParent(node.getParent()); + + } else { + node.getParent().setLeft(node.getRight()); + node.getRight().setParent(node.getParent()); + } + + } else { + if (!node.getLeft().isEmpty()) { + + node.getParent().setRight(node.getLeft()); + node.getLeft().setParent(node.getParent()); + } else { + + node.getParent().setRight(node.getRight()); + node.getRight().setParent(node.getParent()); + + } + } + } else { + if (getRoot().getLeft().isEmpty()) { + setRoot((BSTNode) getRoot().getRight()); + getRoot().setParent(null); + } else if (getRoot().getRight().isEmpty()) { + setRoot((BSTNode) getRoot().getLeft()); + getRoot().setParent(null); + } + } + + } else { + BSTNode sucessor = sucessor(node.getData()); + node.setData(sucessor.getData()); + removeRecursive(sucessor); + } + } + } + + @Override + public T[] sort(T[] array) { + setRoot(new BSTNode()); + for (int i = 0; i < array.length; i++) { + insert(array[i]); + } + return order(); + } + + @Override + public T[] reverseOrder() { + T[] array = util.Util.makeArrayOfComparable(size()); + orderRecursive(getRoot(), array); + return array; + } + + private void orderRecursive(BSTNode node, T[] array) { + if (!node.isEmpty()) { + orderRecursive((BSTNode) node.getRight(), array); + add(array, node.getData()); + orderRecursive((BSTNode) node.getLeft(), array); + + } + + } + + public Comparator getComparator() { + return comparator; + } + + public void setComparator(Comparator comparator) { + this.comparator = comparator; + } + +} diff --git a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bt/BT.java b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bt/BT.java index 7e0e20008..2ce273363 100644 --- a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bt/BT.java +++ b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bt/BT.java @@ -1,65 +1,65 @@ -package adt.bt; - -/** - * The interface of a generic binary tree (BT). It has nodes containing elements - * of type T. - */ -public interface BT { - /** - * Returns the root of the tree. - * - * @return - */ - public BTNode getRoot(); - - /** - * Say if a BT is empty (NIL). - */ - public boolean isEmpty(); - - /** - * The height of a BT. An empty BT has height -1 (there is no root element). - * In non-empty BT the height is given by 1 + (the highest height of its - * sub-trees). - */ - public int height(); - - /** - * Searches an element in a BT. The search starts at the root node. If the - * key does not exist the methods returns a NIL (empty) node. - */ - public BTNode search(T elem); - - /** - * Inserts an element in a BT. - */ - public void insert(T value); - - /** - * Removes a node from a BT. - */ - public void remove(T key); - - /** - * Returns an array of elements filled according to the pre-order traversing - * in a BT. - */ - public T[] preOrder(); - - /** - * Returns an array of elements filled according to the symmetric order - * traversing in a BT. - */ - public T[] order(); - - /** - * Returns an array of elements filled according to the port-order - * traversing in a BT. - */ - public T[] postOrder(); - - /** - * Returns the number of nodes (not NIL) in a BT. - */ - public int size(); -} +package adt.bt; + +/** + * The interface of a generic binary tree (BT). It has nodes containing elements + * of type T. + */ +public interface BT { + /** + * Returns the root of the tree. + * + * @return + */ + public BTNode getRoot(); + + /** + * Say if a BT is empty (NIL). + */ + public boolean isEmpty(); + + /** + * The height of a BT. An empty BT has height -1 (there is no root element). + * In non-empty BT the height is given by 1 + (the highest height of its + * sub-trees). + */ + public int height(); + + /** + * Searches an element in a BT. The search starts at the root node. If the + * key does not exist the methods returns a NIL (empty) node. + */ + public BTNode search(T elem); + + /** + * Inserts an element in a BT. + */ + public void insert(T value); + + /** + * Removes a node from a BT. + */ + public void remove(T key); + + /** + * Returns an array of elements filled according to the pre-order traversing + * in a BT. + */ + public T[] preOrder(); + + /** + * Returns an array of elements filled according to the symmetric order + * traversing in a BT. + */ + public T[] order(); + + /** + * Returns an array of elements filled according to the port-order + * traversing in a BT. + */ + public T[] postOrder(); + + /** + * Returns the number of nodes (not NIL) in a BT. + */ + public int size(); +} diff --git a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bt/BTNode.java b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bt/BTNode.java index dd86bff2c..c059f8531 100644 --- a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bt/BTNode.java +++ b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/adt/bt/BTNode.java @@ -1,86 +1,86 @@ -package adt.bt; - -/** - * The node of a binary tree. Its internal data has type T, which does not need - * to be comparable. - */ -public class BTNode { - protected T data; - protected BTNode left; - protected BTNode right; - protected BTNode parent; - - public BTNode(T data, BTNode left, BTNode right, BTNode parent) { - this.data = data; - this.left = left; - this.right = right; - this.parent = parent; - } - - public BTNode() { - } - - public boolean isEmpty() { - return this.data == null; - } - - public boolean isLeaf() { - return this.data != null && this.left.isEmpty() && this.right.isEmpty(); - } - - @Override - public String toString() { - String resp = "NIL"; - if (!isEmpty()) { - resp = data.toString(); - } - return resp; - } - - @SuppressWarnings("unchecked") - @Override - public boolean equals(Object obj) { - boolean resp = false; - if (obj instanceof BTNode) { - if (!this.isEmpty() && !((BTNode) obj).isEmpty()) { - resp = this.data.equals(((BTNode) obj).data); - } else { - resp = this.isEmpty() && ((BTNode) obj).isEmpty(); - } - - } - return resp; - } - - public T getData() { - return data; - } - - public void setData(T data) { - this.data = data; - } - - public BTNode getLeft() { - return left; - } - - public void setLeft(BTNode left) { - this.left = left; - } - - public BTNode getRight() { - return right; - } - - public void setRight(BTNode right) { - this.right = right; - } - - public BTNode getParent() { - return parent; - } - - public void setParent(BTNode parent) { - this.parent = parent; - } -} +package adt.bt; + +/** + * The node of a binary tree. Its internal data has type T, which does not need + * to be comparable. + */ +public class BTNode { + protected T data; + protected BTNode left; + protected BTNode right; + protected BTNode parent; + + public BTNode(T data, BTNode left, BTNode right, BTNode parent) { + this.data = data; + this.left = left; + this.right = right; + this.parent = parent; + } + + public BTNode() { + } + + public boolean isEmpty() { + return this.data == null; + } + + public boolean isLeaf() { + return this.data != null && this.left.isEmpty() && this.right.isEmpty(); + } + + @Override + public String toString() { + String resp = "NIL"; + if (!isEmpty()) { + resp = data.toString(); + } + return resp; + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(Object obj) { + boolean resp = false; + if (obj instanceof BTNode) { + if (!this.isEmpty() && !((BTNode) obj).isEmpty()) { + resp = this.data.equals(((BTNode) obj).data); + } else { + resp = this.isEmpty() && ((BTNode) obj).isEmpty(); + } + + } + return resp; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public BTNode getLeft() { + return left; + } + + public void setLeft(BTNode left) { + this.left = left; + } + + public BTNode getRight() { + return right; + } + + public void setRight(BTNode right) { + this.right = right; + } + + public BTNode getParent() { + return parent; + } + + public void setParent(BTNode parent) { + this.parent = parent; + } +} diff --git a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/util/Util.java b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/util/Util.java index 4e4e1e280..337567b10 100644 --- a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/util/Util.java +++ b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/main/java/util/Util.java @@ -1,64 +1,64 @@ -package util; - -/** - * Class containing useful methods for arrays manipulation. - */ -public class Util { - - /** - * Swaps the contents of two positions in an array. - * - * @param array - * The array to be modified, not null - * @param i - * One of the target positions - * @param j - * The other target position - */ - public static void swap(Object[] array, int i, int j) { - if (array == null) - throw new IllegalArgumentException(); - - Object temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } - - /** - * Creates a generic array of the specified size. - *

- * Ex.: {@code Util.makeArray(10);} - * - * @param size - * The desired size - * @return An array of the type and size chosen - */ - public static T[] makeArray(int size) { - @SuppressWarnings("unchecked") - T[] array = (T[]) new Object[size]; - return array; - } - - public static T[] makeArrayOfComparable(int size) { - @SuppressWarnings("unchecked") - T[] array = (T[]) new Comparable[size]; - return array; - } - - /** - * It says if a specific number is prime or not. - * - * @param n - * @return - */ - public static boolean isPrime(long n) { - boolean result = true; - for (int i = 2; i < n; i++) { - if (n % i == 0) { - result = false; - break; - } - } - return result; - } +package util; + +/** + * Class containing useful methods for arrays manipulation. + */ +public class Util { + + /** + * Swaps the contents of two positions in an array. + * + * @param array + * The array to be modified, not null + * @param i + * One of the target positions + * @param j + * The other target position + */ + public static void swap(Object[] array, int i, int j) { + if (array == null) + throw new IllegalArgumentException(); + + Object temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + /** + * Creates a generic array of the specified size. + *

+ * Ex.: {@code Util.makeArray(10);} + * + * @param size + * The desired size + * @return An array of the type and size chosen + */ + public static T[] makeArray(int size) { + @SuppressWarnings("unchecked") + T[] array = (T[]) new Object[size]; + return array; + } + + public static T[] makeArrayOfComparable(int size) { + @SuppressWarnings("unchecked") + T[] array = (T[]) new Comparable[size]; + return array; + } + + /** + * It says if a specific number is prime or not. + * + * @param n + * @return + */ + public static boolean isPrime(long n) { + boolean result = true; + for (int i = 2; i < n; i++) { + if (n % i == 0) { + result = false; + break; + } + } + return result; + } } \ No newline at end of file diff --git a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/test/java/adt/bst/StudentBSTTest.java b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/test/java/adt/bst/StudentBSTTest.java index 1ce3b6291..95d31c113 100644 --- a/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/test/java/adt/bst/StudentBSTTest.java +++ b/java/R11-01-Rot-BST-Comparator-Sorting-environment/src/test/java/adt/bst/StudentBSTTest.java @@ -1,156 +1,156 @@ -package adt.bst; - -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; - -import adt.bst.BSTImpl; -import adt.bst.extended.SortComparatorBSTImpl; -import adt.bt.BTNode; - -public class StudentBSTTest { - - private BSTImpl tree; - private BTNode NIL = new BTNode(); - - private void fillTree() { - Integer[] array = { 6, 23, -34, 5, 9, 2, 0, 76, 12, 67, 232, -40 }; - for (int i : array) { - tree.insert(i); - } - } - - @Before - public void setUp() { - tree = new SortComparatorBSTImpl((o1,o2) -> o1 - o2); - } - - @Test - public void testInit() { - assertTrue(tree.isEmpty()); - assertEquals(0, tree.size()); - assertEquals(-1, tree.height()); - - assertEquals(NIL, tree.getRoot()); - - assertArrayEquals(new Integer[] {}, tree.order()); - assertArrayEquals(new Integer[] {}, tree.preOrder()); - assertArrayEquals(new Integer[] {}, tree.postOrder()); - - assertEquals(NIL, tree.search(12)); - assertEquals(NIL, tree.search(-23)); - assertEquals(NIL, tree.search(0)); - - assertEquals(null, tree.minimum()); - assertEquals(null, tree.maximum()); - - assertEquals(null, tree.sucessor(12)); - assertEquals(null, tree.sucessor(-23)); - assertEquals(null, tree.sucessor(0)); - - assertEquals(null, tree.predecessor(12)); - assertEquals(null, tree.predecessor(-23)); - assertEquals(null, tree.predecessor(0)); - } - - @Test - public void testMinMax() { - tree.insert(6); - assertEquals(new Integer(6), tree.minimum().getData()); - assertEquals(new Integer(6), tree.maximum().getData()); - - tree.insert(23); - assertEquals(new Integer(6), tree.minimum().getData()); - assertEquals(new Integer(23), tree.maximum().getData()); - - tree.insert(-34); - assertEquals(new Integer(-34), tree.minimum().getData()); - assertEquals(new Integer(23), tree.maximum().getData()); - - tree.insert(5); - assertEquals(new Integer(-34), tree.minimum().getData()); - assertEquals(new Integer(23), tree.maximum().getData()); - - tree.insert(9); - assertEquals(new Integer(-34), tree.minimum().getData()); - assertEquals(new Integer(23), tree.maximum().getData()); - } - - @Test - public void testSucessorPredecessor() { - - fillTree(); // -40 -34 0 2 5 6 9 12 23 67 76 232 - - assertEquals(null, tree.predecessor(-40)); - assertEquals(new Integer(-34), tree.sucessor(-40).getData()); - - assertEquals(new Integer(-40), tree.predecessor(-34).getData()); - assertEquals(new Integer(0), tree.sucessor(-34).getData()); - - assertEquals(new Integer(-34), tree.predecessor(0).getData()); - assertEquals(new Integer(2), tree.sucessor(0).getData()); - - assertEquals(new Integer(0), tree.predecessor(2).getData()); - assertEquals(new Integer(5), tree.sucessor(2).getData()); - } - - @Test - public void testSize() { - fillTree(); // -40 -34 0 2 5 6 9 12 23 67 76 232 - - int size = 12; - assertEquals(size, tree.size()); - - while (!tree.isEmpty()) { - tree.remove(tree.getRoot().getData()); - assertEquals(--size, tree.size()); - } - } - - @Test - public void testHeight() { - fillTree(); // -40 -34 0 2 5 6 9 12 23 67 76 232 - - Integer[] preOrder = new Integer[] { 6, -34, -40, 5, 2, 0, 23, 9, 12, - 76, 67, 232 }; - assertArrayEquals(preOrder, tree.preOrder()); - assertEquals(4, tree.height()); - - tree.remove(0); - assertEquals(3, tree.height()); - - tree.remove(2); - assertEquals(3, tree.height()); - } - - @Test - public void testRemove() { - fillTree(); // -40 -34 0 2 5 6 9 12 23 67 76 232 - - Integer[] order = { -40, -34, 0, 2, 5, 6, 9, 12, 23, 67, 76, 232 }; - assertArrayEquals(order, tree.order()); - - tree.remove(6); - order = new Integer[] { -40, -34, 0, 2, 5, 9, 12, 23, 67, 76, 232 }; - assertArrayEquals(order, tree.order()); - - tree.remove(9); - order = new Integer[] { -40, -34, 0, 2, 5, 12, 23, 67, 76, 232 }; - assertArrayEquals(order, tree.order()); - - assertEquals(NIL, tree.search(6)); - assertEquals(NIL, tree.search(9)); - - } - - @Test - public void testSearch() { - - fillTree(); // -40 -34 0 2 5 6 9 12 23 67 76 232 - - assertEquals(new Integer(-40), tree.search(-40).getData()); - assertEquals(new Integer(-34), tree.search(-34).getData()); - assertEquals(NIL, tree.search(2534)); - } -} +package adt.bst; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; + +import adt.bst.BSTImpl; +import adt.bst.extended.SortComparatorBSTImpl; +import adt.bt.BTNode; + +public class StudentBSTTest { + + private BSTImpl tree; + private BTNode NIL = new BTNode(); + + private void fillTree() { + Integer[] array = { 6, 23, -34, 5, 9, 2, 0, 76, 12, 67, 232, -40 }; + for (int i : array) { + tree.insert(i); + } + } + + @Before + public void setUp() { + tree = new SortComparatorBSTImpl((o1,o2) -> o1 - o2); + } + + @Test + public void testInit() { + assertTrue(tree.isEmpty()); + assertEquals(0, tree.size()); + assertEquals(-1, tree.height()); + + assertEquals(NIL, tree.getRoot()); + + assertArrayEquals(new Integer[] {}, tree.order()); + assertArrayEquals(new Integer[] {}, tree.preOrder()); + assertArrayEquals(new Integer[] {}, tree.postOrder()); + + assertEquals(NIL, tree.search(12)); + assertEquals(NIL, tree.search(-23)); + assertEquals(NIL, tree.search(0)); + + assertEquals(null, tree.minimum()); + assertEquals(null, tree.maximum()); + + assertEquals(null, tree.sucessor(12)); + assertEquals(null, tree.sucessor(-23)); + assertEquals(null, tree.sucessor(0)); + + assertEquals(null, tree.predecessor(12)); + assertEquals(null, tree.predecessor(-23)); + assertEquals(null, tree.predecessor(0)); + } + + @Test + public void testMinMax() { + tree.insert(6); + assertEquals(new Integer(6), tree.minimum().getData()); + assertEquals(new Integer(6), tree.maximum().getData()); + + tree.insert(23); + assertEquals(new Integer(6), tree.minimum().getData()); + assertEquals(new Integer(23), tree.maximum().getData()); + + tree.insert(-34); + assertEquals(new Integer(-34), tree.minimum().getData()); + assertEquals(new Integer(23), tree.maximum().getData()); + + tree.insert(5); + assertEquals(new Integer(-34), tree.minimum().getData()); + assertEquals(new Integer(23), tree.maximum().getData()); + + tree.insert(9); + assertEquals(new Integer(-34), tree.minimum().getData()); + assertEquals(new Integer(23), tree.maximum().getData()); + } + + @Test + public void testSucessorPredecessor() { + + fillTree(); // -40 -34 0 2 5 6 9 12 23 67 76 232 + + assertEquals(null, tree.predecessor(-40)); + assertEquals(new Integer(-34), tree.sucessor(-40).getData()); + + assertEquals(new Integer(-40), tree.predecessor(-34).getData()); + assertEquals(new Integer(0), tree.sucessor(-34).getData()); + + assertEquals(new Integer(-34), tree.predecessor(0).getData()); + assertEquals(new Integer(2), tree.sucessor(0).getData()); + + assertEquals(new Integer(0), tree.predecessor(2).getData()); + assertEquals(new Integer(5), tree.sucessor(2).getData()); + } + + @Test + public void testSize() { + fillTree(); // -40 -34 0 2 5 6 9 12 23 67 76 232 + + int size = 12; + assertEquals(size, tree.size()); + + while (!tree.isEmpty()) { + tree.remove(tree.getRoot().getData()); + assertEquals(--size, tree.size()); + } + } + + @Test + public void testHeight() { + fillTree(); // -40 -34 0 2 5 6 9 12 23 67 76 232 + + Integer[] preOrder = new Integer[] { 6, -34, -40, 5, 2, 0, 23, 9, 12, + 76, 67, 232 }; + assertArrayEquals(preOrder, tree.preOrder()); + assertEquals(4, tree.height()); + + tree.remove(0); + assertEquals(3, tree.height()); + + tree.remove(2); + assertEquals(3, tree.height()); + } + + @Test + public void testRemove() { + fillTree(); // -40 -34 0 2 5 6 9 12 23 67 76 232 + + Integer[] order = { -40, -34, 0, 2, 5, 6, 9, 12, 23, 67, 76, 232 }; + assertArrayEquals(order, tree.order()); + + tree.remove(6); + order = new Integer[] { -40, -34, 0, 2, 5, 9, 12, 23, 67, 76, 232 }; + assertArrayEquals(order, tree.order()); + + tree.remove(9); + order = new Integer[] { -40, -34, 0, 2, 5, 12, 23, 67, 76, 232 }; + assertArrayEquals(order, tree.order()); + + assertEquals(NIL, tree.search(6)); + assertEquals(NIL, tree.search(9)); + + } + + @Test + public void testSearch() { + + fillTree(); // -40 -34 0 2 5 6 9 12 23 67 76 232 + + assertEquals(new Integer(-40), tree.search(-40).getData()); + assertEquals(new Integer(-34), tree.search(-34).getData()); + assertEquals(NIL, tree.search(2534)); + } +} diff --git a/java/R11-01-Rot-BST-Comparator-Sorting-environment/walkmod.xml b/java/R11-01-Rot-BST-Comparator-Sorting-environment/walkmod.xml index d391a36b4..85902bfec 100644 --- a/java/R11-01-Rot-BST-Comparator-Sorting-environment/walkmod.xml +++ b/java/R11-01-Rot-BST-Comparator-Sorting-environment/walkmod.xml @@ -1,4 +1,4 @@ - - - + + + \ No newline at end of file diff --git a/java/R12-01-Rot-Heap-environment/pom.xml b/java/R12-01-Rot-Heap-environment/pom.xml index 7926b7fbc..24767280f 100644 --- a/java/R12-01-Rot-Heap-environment/pom.xml +++ b/java/R12-01-Rot-Heap-environment/pom.xml @@ -1,98 +1,98 @@ - - 4.0.0 - - br.edu.ufcg.ccc - submission - 1.0 - jar - Submissao de roteiro - - - - ufcg-leda - http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda - default - - true - always - - - - - - - junit - junit - 4.12 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - maven-clean-plugin - 3.0.0 - - - auto-clean - build - - clean - - - - - - - org.walkmod - maven-walkmod-plugin - 1.3 - - walkmod.xml - - - - package - - apply - - - false - - - - - - br.edu.ufcg.ccc - leda-compactor-tool - 1.0.0-SNAPSHOT - - - install - - compact - - - - 116110761 - - R12-01 - - 2017.1 - http://150.165.85.29:81/submitAtividade - - - - - - - + + 4.0.0 + + br.edu.ufcg.ccc + submission + 1.0 + jar + Submissao de roteiro + + + + ufcg-leda + http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda + default + + true + always + + + + + + + junit + junit + 4.12 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + maven-clean-plugin + 3.0.0 + + + auto-clean + build + + clean + + + + + + + org.walkmod + maven-walkmod-plugin + 1.3 + + walkmod.xml + + + + package + + apply + + + false + + + + + + br.edu.ufcg.ccc + leda-compactor-tool + 1.0.0-SNAPSHOT + + + install + + compact + + + + 116110761 + + R12-01 + + 2017.1 + http://150.165.85.29:81/submitAtividade + + + + + + + diff --git a/java/R12-01-Rot-Heap-environment/src/main/java/adt/heap/Heap.java b/java/R12-01-Rot-Heap-environment/src/main/java/adt/heap/Heap.java index 964613522..43b4e533a 100644 --- a/java/R12-01-Rot-Heap-environment/src/main/java/adt/heap/Heap.java +++ b/java/R12-01-Rot-Heap-environment/src/main/java/adt/heap/Heap.java @@ -1,59 +1,59 @@ -package adt.heap; - -public interface Heap> { - - public abstract boolean isEmpty(); - - /** - * Inserts a new element into the heap and maintains the invariant. - */ - public abstract void insert(T element); - - /** - * Removes and returns the root element of the heap. The method returns null - * if the heap is empty. If the heap is min-heap the element is the minimum - * of the heap; otherwise, the heap is max-heap and the element is the - * maximum of the heap. - */ - public abstract T extractRootElement(); - - /** - * Returns the root element without removing it. It returns null if the heap - * is empty. If the heap is min-heap the element is the minimum of the heap; - * otherwise, the heap is max-heap and the element is the maximum of the - * heap. - */ - public T rootElement(); - - /** - * Sorts the elements of an array by using the heap concept. The method must - * build a new heap using the array received as a parameter. The method - * returns a copy (another array) containing only the not null elements of - * the internal array. At the end, the internal array should be empty. This - * method simply extracts the elements of the head and puts them into an - * auxiliary array that is returned at the end. - */ - public abstract T[] heapsort(T[] array); - - /** - * This method is intended to build the heap with the elements of a given - * array. Thus, if the heap has already elements, they are lost (that is the - * heap is reseted) and the heap is built with new elements. - */ - public abstract void buildHeap(T[] array); - - /** - * Returns an array representing the underlying structure (internal array) - * of the heap. - * - * @return - */ - public abstract T[] toArray(); - - /** - * Returns the number of elements in this heap. - * - * @return - */ - public abstract int size(); +package adt.heap; + +public interface Heap> { + + public abstract boolean isEmpty(); + + /** + * Inserts a new element into the heap and maintains the invariant. + */ + public abstract void insert(T element); + + /** + * Removes and returns the root element of the heap. The method returns null + * if the heap is empty. If the heap is min-heap the element is the minimum + * of the heap; otherwise, the heap is max-heap and the element is the + * maximum of the heap. + */ + public abstract T extractRootElement(); + + /** + * Returns the root element without removing it. It returns null if the heap + * is empty. If the heap is min-heap the element is the minimum of the heap; + * otherwise, the heap is max-heap and the element is the maximum of the + * heap. + */ + public T rootElement(); + + /** + * Sorts the elements of an array by using the heap concept. The method must + * build a new heap using the array received as a parameter. The method + * returns a copy (another array) containing only the not null elements of + * the internal array. At the end, the internal array should be empty. This + * method simply extracts the elements of the head and puts them into an + * auxiliary array that is returned at the end. + */ + public abstract T[] heapsort(T[] array); + + /** + * This method is intended to build the heap with the elements of a given + * array. Thus, if the heap has already elements, they are lost (that is the + * heap is reseted) and the heap is built with new elements. + */ + public abstract void buildHeap(T[] array); + + /** + * Returns an array representing the underlying structure (internal array) + * of the heap. + * + * @return + */ + public abstract T[] toArray(); + + /** + * Returns the number of elements in this heap. + * + * @return + */ + public abstract int size(); } \ No newline at end of file diff --git a/java/R12-01-Rot-Heap-environment/src/main/java/adt/heap/HeapImpl.java b/java/R12-01-Rot-Heap-environment/src/main/java/adt/heap/HeapImpl.java index eaa7b514d..fd7267c5e 100644 --- a/java/R12-01-Rot-Heap-environment/src/main/java/adt/heap/HeapImpl.java +++ b/java/R12-01-Rot-Heap-environment/src/main/java/adt/heap/HeapImpl.java @@ -1,252 +1,252 @@ -package adt.heap; - -import java.util.Arrays; -import java.util.Comparator; -import java.util.LinkedList; -import java.util.List; - -import util.Util; - -/** - * O comportamento de qualquer heap é definido pelo heapify. Neste caso o - * heapify dessa heap deve comparar os elementos e colocar o maior sempre no - * topo. Ou seja, admitindo um comparador normal (responde corretamente 3 > 2), - * essa heap deixa os elementos maiores no topo. Essa comparação não é feita - * diretamente com os elementos armazenados, mas sim usando um comparator. Dessa - * forma, dependendo do comparator, a heap pode funcionar como uma max-heap ou - * min-heap. - */ -public class HeapImpl> implements Heap { - - protected T[] heap; - protected int index = -1; - /** - * O comparador é utilizado para fazer as comparações da heap. O ideal é mudar - * apenas o comparator e mandar reordenar a heap usando esse comparator. Assim - * os metodos da heap não precisam saber se vai funcionar como max-heap ou - * min-heap. - */ - protected Comparator comparator; - - private static final int INITIAL_SIZE = 20; - private static final int INCREASING_FACTOR = 10; - - /** - * Construtor da classe. Note que de inicio a heap funciona como uma min-heap. - */ - @SuppressWarnings("unchecked") - public HeapImpl(Comparator comparator) { - this.heap = (T[]) (new Comparable[INITIAL_SIZE]); - this.comparator = comparator; - } - - // /////////////////// METODOS IMPLEMENTADOS - private int parent(int i) { - return (i - 1) / 2; - } - - /** - * Deve retornar o indice que representa o filho a esquerda do elemento indexado - * pela posicao i no vetor - */ - private int left(int i) { - return (i * 2 + 1); - } - - /** - * Deve retornar o indice que representa o filho a direita do elemento indexado - * pela posicao i no vetor - */ - private int right(int i) { - return (i * 2 + 1) + 1; - } - - @Override - public boolean isEmpty() { - return (index == -1); - } - - @Override - public T[] toArray() { - T[] resp = Util.makeArrayOfComparable(index + 1); - for (int i = 0; i <= index; i++) { - resp[i] = this.heap[i]; - } - return resp; - } - - // ///////////// METODOS A IMPLEMENTAR - /** - * Valida o invariante de uma heap a partir de determinada posicao, que pode ser - * a raiz da heap ou de uma sub-heap. O heapify deve colocar os maiores - * (comparados usando o comparator) elementos na parte de cima da heap. - */ - private void heapify(int position) { - if (position >= 0 && position < size()) { - int largest = position; - int leftChild = left(position); - int rightChild = right(position); - if (leftChild < size() && heap[leftChild] != null - && getComparator().compare(heap[leftChild], heap[position]) > 0) { - largest = leftChild; - } - if (rightChild < size() && heap[rightChild] != null - && getComparator().compare(heap[rightChild], heap[largest]) > 0) { - largest = rightChild; - } - if (getComparator().compare(heap[largest], heap[position]) != 0) { - util.Util.swap(getHeap(), largest, position); - heapify(largest); - } - } - } - - @Override - public void insert(T element) { - // ESSE CODIGO E PARA A HEAP CRESCER SE FOR PRECISO. NAO MODIFIQUE - if (index == heap.length - 1) { - heap = Arrays.copyOf(heap, heap.length + INCREASING_FACTOR); - } - // ///////////////////////////////////////////////////////////////// - if (element != null) { - index++; - int i = index; - while (i > 0 && getComparator().compare(heap[parent(i)], element) < 0) { - heap[i] = heap[parent(i)]; - i = parent(i); - } - heap[i] = element; - } - - } - - @Override - public void buildHeap(T[] array) { - if (array != null) { - heap = array; - index = array.length - 1; - for (int i = array.length / 2; i >= 0; i--) { - heapify(i); - } - } - } - - @Override - public T extractRootElement() { - T result = null; - if (!isEmpty()) { - result = heap[0]; - heap[0] = heap[index]; - heap[index] = result; - index--; - heapify(0); - } - return result; - } - - @Override - public T rootElement() { - if (!isEmpty()) { - return heap[0]; - } - return null; - } - - @Override - public T[] heapsort(T[] array) { - T[] result = array; - if (array.length > 1) { - buildHeap(array); - for (int i = array.length - 1; i >= 0; i--) { - Util.swap(heap, 0, i); - index--; - heapify(0); - } - result = heap; - if (heap[0].compareTo(heap[1]) > 0) { - T[] inverse = util.Util.makeArrayOfComparable(array.length); - for (int i = 0; i < array.length; i++) { - inverse[i] = heap[array.length - 1 - i]; - } - result = inverse; - } - } - return result; - } - - @Override - public int size() { - return index + 1; - } - - public Comparator getComparator() { - return comparator; - } - - public void setComparator(Comparator comparator) { - this.comparator = comparator; - } - - public T[] getHeap() { - return heap; - } - - @SuppressWarnings("unchecked") - public T[] mergeArrays(T[] arrayA, T[] arrayB) { - for (T element : arrayA) { - insert(element); - } - for (T element : arrayB) { - insert(element); - } - - T[] aux = (T[]) (new Comparable[size()]); - - for (int index = 0; index < aux.length; index++) { - aux[index] = extractRootElement(); - } - return aux; - } - - public T[] sortLevel(int level) { - LinkedList aux = new LinkedList(); - - if (level >= 0) { - int startLevel = (int) (Math.pow(2, level) - 1); - int endLevel = (int) (Math.pow(2, (level + 1)) - 2); - - while (startLevel <= endLevel && heap[startLevel] != null) { - aux.add(heap[startLevel]); - startLevel++; - } - } - - T[] result = makeArrayFromList(aux); - Arrays.sort(result); - return result; - } - - @SuppressWarnings("unchecked") - protected T[] makeArrayFromList(List list) { - - int size = list.size(); - T[] array = (T[]) new Comparable[size]; - for (int i = 0; i != size; i++) { - array[i] = list.get(i); - } - return array; - } - - public T[] heapSortMax(T[] array) { - T[] result = null; - if (array != null) { - buildHeap(array); - for (int i = 1; i < array.length; i++) { - extractRootElement(); - } - result = array; - } - return result; - } - -} +package adt.heap; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.LinkedList; +import java.util.List; + +import util.Util; + +/** + * O comportamento de qualquer heap é definido pelo heapify. Neste caso o + * heapify dessa heap deve comparar os elementos e colocar o maior sempre no + * topo. Ou seja, admitindo um comparador normal (responde corretamente 3 > 2), + * essa heap deixa os elementos maiores no topo. Essa comparação não é feita + * diretamente com os elementos armazenados, mas sim usando um comparator. Dessa + * forma, dependendo do comparator, a heap pode funcionar como uma max-heap ou + * min-heap. + */ +public class HeapImpl> implements Heap { + + protected T[] heap; + protected int index = -1; + /** + * O comparador é utilizado para fazer as comparações da heap. O ideal é mudar + * apenas o comparator e mandar reordenar a heap usando esse comparator. Assim + * os metodos da heap não precisam saber se vai funcionar como max-heap ou + * min-heap. + */ + protected Comparator comparator; + + private static final int INITIAL_SIZE = 20; + private static final int INCREASING_FACTOR = 10; + + /** + * Construtor da classe. Note que de inicio a heap funciona como uma min-heap. + */ + @SuppressWarnings("unchecked") + public HeapImpl(Comparator comparator) { + this.heap = (T[]) (new Comparable[INITIAL_SIZE]); + this.comparator = comparator; + } + + // /////////////////// METODOS IMPLEMENTADOS + private int parent(int i) { + return (i - 1) / 2; + } + + /** + * Deve retornar o indice que representa o filho a esquerda do elemento indexado + * pela posicao i no vetor + */ + private int left(int i) { + return (i * 2 + 1); + } + + /** + * Deve retornar o indice que representa o filho a direita do elemento indexado + * pela posicao i no vetor + */ + private int right(int i) { + return (i * 2 + 1) + 1; + } + + @Override + public boolean isEmpty() { + return (index == -1); + } + + @Override + public T[] toArray() { + T[] resp = Util.makeArrayOfComparable(index + 1); + for (int i = 0; i <= index; i++) { + resp[i] = this.heap[i]; + } + return resp; + } + + // ///////////// METODOS A IMPLEMENTAR + /** + * Valida o invariante de uma heap a partir de determinada posicao, que pode ser + * a raiz da heap ou de uma sub-heap. O heapify deve colocar os maiores + * (comparados usando o comparator) elementos na parte de cima da heap. + */ + private void heapify(int position) { + if (position >= 0 && position < size()) { + int largest = position; + int leftChild = left(position); + int rightChild = right(position); + if (leftChild < size() && heap[leftChild] != null + && getComparator().compare(heap[leftChild], heap[position]) > 0) { + largest = leftChild; + } + if (rightChild < size() && heap[rightChild] != null + && getComparator().compare(heap[rightChild], heap[largest]) > 0) { + largest = rightChild; + } + if (getComparator().compare(heap[largest], heap[position]) != 0) { + util.Util.swap(getHeap(), largest, position); + heapify(largest); + } + } + } + + @Override + public void insert(T element) { + // ESSE CODIGO E PARA A HEAP CRESCER SE FOR PRECISO. NAO MODIFIQUE + if (index == heap.length - 1) { + heap = Arrays.copyOf(heap, heap.length + INCREASING_FACTOR); + } + // ///////////////////////////////////////////////////////////////// + if (element != null) { + index++; + int i = index; + while (i > 0 && getComparator().compare(heap[parent(i)], element) < 0) { + heap[i] = heap[parent(i)]; + i = parent(i); + } + heap[i] = element; + } + + } + + @Override + public void buildHeap(T[] array) { + if (array != null) { + heap = array; + index = array.length - 1; + for (int i = array.length / 2; i >= 0; i--) { + heapify(i); + } + } + } + + @Override + public T extractRootElement() { + T result = null; + if (!isEmpty()) { + result = heap[0]; + heap[0] = heap[index]; + heap[index] = result; + index--; + heapify(0); + } + return result; + } + + @Override + public T rootElement() { + if (!isEmpty()) { + return heap[0]; + } + return null; + } + + @Override + public T[] heapsort(T[] array) { + T[] result = array; + if (array.length > 1) { + buildHeap(array); + for (int i = array.length - 1; i >= 0; i--) { + Util.swap(heap, 0, i); + index--; + heapify(0); + } + result = heap; + if (heap[0].compareTo(heap[1]) > 0) { + T[] inverse = util.Util.makeArrayOfComparable(array.length); + for (int i = 0; i < array.length; i++) { + inverse[i] = heap[array.length - 1 - i]; + } + result = inverse; + } + } + return result; + } + + @Override + public int size() { + return index + 1; + } + + public Comparator getComparator() { + return comparator; + } + + public void setComparator(Comparator comparator) { + this.comparator = comparator; + } + + public T[] getHeap() { + return heap; + } + + @SuppressWarnings("unchecked") + public T[] mergeArrays(T[] arrayA, T[] arrayB) { + for (T element : arrayA) { + insert(element); + } + for (T element : arrayB) { + insert(element); + } + + T[] aux = (T[]) (new Comparable[size()]); + + for (int index = 0; index < aux.length; index++) { + aux[index] = extractRootElement(); + } + return aux; + } + + public T[] sortLevel(int level) { + LinkedList aux = new LinkedList(); + + if (level >= 0) { + int startLevel = (int) (Math.pow(2, level) - 1); + int endLevel = (int) (Math.pow(2, (level + 1)) - 2); + + while (startLevel <= endLevel && heap[startLevel] != null) { + aux.add(heap[startLevel]); + startLevel++; + } + } + + T[] result = makeArrayFromList(aux); + Arrays.sort(result); + return result; + } + + @SuppressWarnings("unchecked") + protected T[] makeArrayFromList(List list) { + + int size = list.size(); + T[] array = (T[]) new Comparable[size]; + for (int i = 0; i != size; i++) { + array[i] = list.get(i); + } + return array; + } + + public T[] heapSortMax(T[] array) { + T[] result = null; + if (array != null) { + buildHeap(array); + for (int i = 1; i < array.length; i++) { + extractRootElement(); + } + result = array; + } + return result; + } + +} diff --git a/java/R12-01-Rot-Heap-environment/src/main/java/adt/heap/HeapNode.java b/java/R12-01-Rot-Heap-environment/src/main/java/adt/heap/HeapNode.java index 7ba3d8405..6fd4d6b04 100644 --- a/java/R12-01-Rot-Heap-environment/src/main/java/adt/heap/HeapNode.java +++ b/java/R12-01-Rot-Heap-environment/src/main/java/adt/heap/HeapNode.java @@ -1,32 +1,32 @@ -package adt.heap; - -public class HeapNode implements Comparable { - - public long time; - T data; - - public HeapNode(T element, long id){ - data = element; - time = id; - } - - public T getData() { - return data; - } - - public void setData(T data) { - this.data = data; - } - - public long getTime() { - return time; - } - - @Override - public int compareTo(HeapNode o) { - return (int) (time - o.getTime()); - } - - - -} +package adt.heap; + +public class HeapNode implements Comparable { + + public long time; + T data; + + public HeapNode(T element, long id){ + data = element; + time = id; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public long getTime() { + return time; + } + + @Override + public int compareTo(HeapNode o) { + return (int) (time - o.getTime()); + } + + + +} diff --git a/java/R12-01-Rot-Heap-environment/src/main/java/adt/queue/Queue.java b/java/R12-01-Rot-Heap-environment/src/main/java/adt/queue/Queue.java index 1c476145e..3931971e2 100644 --- a/java/R12-01-Rot-Heap-environment/src/main/java/adt/queue/Queue.java +++ b/java/R12-01-Rot-Heap-environment/src/main/java/adt/queue/Queue.java @@ -1,50 +1,50 @@ -package adt.queue; - -/** - * The interface of a generic queue. The queue is able to store any kind of - * data. - * - */ -public interface Queue { - - /** - * Inserts a new element in the queue or returns an exception if the queue - * is full. Null elements are not allowed (the queue remains unchanged). - * - * @param element - * @throws QueueOverflowException - */ - public void enqueue(T element) throws QueueOverflowException; - - /** - * If the queue has elements, it removes the oldest of the queue and returns - * it; otherwise, it returns an exception. - * - * @return - * @throws QueueUnderflowException - */ - public T dequeue() throws QueueUnderflowException; - - /** - * Returns (without removing) the oldest element of the stack or null if the - * queue is empty. - * - * @return - */ - public T head(); - - /** - * Returns true if the queue is empty or false, otherwise. - * - * @return - */ - public boolean isEmpty(); - - /** - * Returns true if the queue is full or false, otherwise. - * - * @return - */ - public boolean isFull(); - -} +package adt.queue; + +/** + * The interface of a generic queue. The queue is able to store any kind of + * data. + * + */ +public interface Queue { + + /** + * Inserts a new element in the queue or returns an exception if the queue + * is full. Null elements are not allowed (the queue remains unchanged). + * + * @param element + * @throws QueueOverflowException + */ + public void enqueue(T element) throws QueueOverflowException; + + /** + * If the queue has elements, it removes the oldest of the queue and returns + * it; otherwise, it returns an exception. + * + * @return + * @throws QueueUnderflowException + */ + public T dequeue() throws QueueUnderflowException; + + /** + * Returns (without removing) the oldest element of the stack or null if the + * queue is empty. + * + * @return + */ + public T head(); + + /** + * Returns true if the queue is empty or false, otherwise. + * + * @return + */ + public boolean isEmpty(); + + /** + * Returns true if the queue is full or false, otherwise. + * + * @return + */ + public boolean isFull(); + +} diff --git a/java/R12-01-Rot-Heap-environment/src/main/java/adt/queue/QueueHeapImpl.java b/java/R12-01-Rot-Heap-environment/src/main/java/adt/queue/QueueHeapImpl.java index 3fdfbba1c..5e065c770 100644 --- a/java/R12-01-Rot-Heap-environment/src/main/java/adt/queue/QueueHeapImpl.java +++ b/java/R12-01-Rot-Heap-environment/src/main/java/adt/queue/QueueHeapImpl.java @@ -1,61 +1,61 @@ -package adt.queue; - -import java.util.Comparator; - -import adt.heap.HeapImpl; -import adt.heap.HeapNode; - -public class QueueHeapImpl> implements Queue { - - private int maxElements; - private int count; - private HeapImpl heap; - private long ID; - - public QueueHeapImpl(int numberElements) { - Comparator> comparator = (o1, o2) -> o2.compareTo(o1); - heap = new HeapImpl(comparator); - this.maxElements = numberElements; - count = 0; - ID = 0; - } - - @Override - public boolean isEmpty() { - return count == 0; - } - - @Override - public boolean isFull() { - return count == maxElements; - } - - @Override - public void enqueue(T element) throws QueueOverflowException { - if (element != null) { - if (isFull()) { - throw new QueueOverflowException(); - } - HeapNode node = new HeapNode(element, ID); - count++; - ID++; - heap.insert(node); - } - - } - - @Override - public T dequeue() throws QueueUnderflowException { - if (isEmpty()) { - throw new QueueUnderflowException(); - } - count--; - return ((HeapNode) heap.extractRootElement()).getData(); - } - - @Override - public T head() { - return ((HeapNode) heap.rootElement()).getData(); - } - -} +package adt.queue; + +import java.util.Comparator; + +import adt.heap.HeapImpl; +import adt.heap.HeapNode; + +public class QueueHeapImpl> implements Queue { + + private int maxElements; + private int count; + private HeapImpl heap; + private long ID; + + public QueueHeapImpl(int numberElements) { + Comparator> comparator = (o1, o2) -> o2.compareTo(o1); + heap = new HeapImpl(comparator); + this.maxElements = numberElements; + count = 0; + ID = 0; + } + + @Override + public boolean isEmpty() { + return count == 0; + } + + @Override + public boolean isFull() { + return count == maxElements; + } + + @Override + public void enqueue(T element) throws QueueOverflowException { + if (element != null) { + if (isFull()) { + throw new QueueOverflowException(); + } + HeapNode node = new HeapNode(element, ID); + count++; + ID++; + heap.insert(node); + } + + } + + @Override + public T dequeue() throws QueueUnderflowException { + if (isEmpty()) { + throw new QueueUnderflowException(); + } + count--; + return ((HeapNode) heap.extractRootElement()).getData(); + } + + @Override + public T head() { + return ((HeapNode) heap.rootElement()).getData(); + } + +} diff --git a/java/R12-01-Rot-Heap-environment/src/main/java/adt/queue/QueueOverflowException.java b/java/R12-01-Rot-Heap-environment/src/main/java/adt/queue/QueueOverflowException.java index dd51f0d21..43e1c42bd 100644 --- a/java/R12-01-Rot-Heap-environment/src/main/java/adt/queue/QueueOverflowException.java +++ b/java/R12-01-Rot-Heap-environment/src/main/java/adt/queue/QueueOverflowException.java @@ -1,9 +1,9 @@ -package adt.queue; - -public class QueueOverflowException extends Exception { - - public QueueOverflowException() { - super("Fila cheia"); - } - -} +package adt.queue; + +public class QueueOverflowException extends Exception { + + public QueueOverflowException() { + super("Fila cheia"); + } + +} diff --git a/java/R12-01-Rot-Heap-environment/src/main/java/adt/queue/QueueUnderflowException.java b/java/R12-01-Rot-Heap-environment/src/main/java/adt/queue/QueueUnderflowException.java index 09d30911d..20ce52154 100644 --- a/java/R12-01-Rot-Heap-environment/src/main/java/adt/queue/QueueUnderflowException.java +++ b/java/R12-01-Rot-Heap-environment/src/main/java/adt/queue/QueueUnderflowException.java @@ -1,9 +1,9 @@ -package adt.queue; - -public class QueueUnderflowException extends Exception { - - public QueueUnderflowException() { - super("Fila vazia"); - } - -} +package adt.queue; + +public class QueueUnderflowException extends Exception { + + public QueueUnderflowException() { + super("Fila vazia"); + } + +} diff --git a/java/R12-01-Rot-Heap-environment/src/main/java/adt/stack/Stack.java b/java/R12-01-Rot-Heap-environment/src/main/java/adt/stack/Stack.java index 6760db4e3..09dace39a 100644 --- a/java/R12-01-Rot-Heap-environment/src/main/java/adt/stack/Stack.java +++ b/java/R12-01-Rot-Heap-environment/src/main/java/adt/stack/Stack.java @@ -1,50 +1,50 @@ -package adt.stack; - -/** - * The interface of a generic stack. The queue is able to store any kind of - * data. - * - */ -public interface Stack { - - /** - * Inserts a new element in the stack or returns an exception if the stack - * is full. Null elements are not allowed (the stack remains unchanged). - * - * @param element - * @throws StackOverflowException - */ - public void push(T element) throws StackOverflowException; - - /** - * If the stack has elements, it removes the top of the stack and returns - * it; otherwise, it returns an exception. - * - * @return - * @throws StackUnderflowException - */ - public T pop() throws StackUnderflowException; - - /** - * Returns (without removing) the top element of the stack or null if the - * stack is empty. - * - * @return - */ - public T top(); - - /** - * Returns true if the stack is empty or false, otherwise. - * - * @return - */ - public boolean isEmpty(); - - /** - * Returns true if the stack is full or false, otherwise. - * - * @return - */ - public boolean isFull(); - -} +package adt.stack; + +/** + * The interface of a generic stack. The queue is able to store any kind of + * data. + * + */ +public interface Stack { + + /** + * Inserts a new element in the stack or returns an exception if the stack + * is full. Null elements are not allowed (the stack remains unchanged). + * + * @param element + * @throws StackOverflowException + */ + public void push(T element) throws StackOverflowException; + + /** + * If the stack has elements, it removes the top of the stack and returns + * it; otherwise, it returns an exception. + * + * @return + * @throws StackUnderflowException + */ + public T pop() throws StackUnderflowException; + + /** + * Returns (without removing) the top element of the stack or null if the + * stack is empty. + * + * @return + */ + public T top(); + + /** + * Returns true if the stack is empty or false, otherwise. + * + * @return + */ + public boolean isEmpty(); + + /** + * Returns true if the stack is full or false, otherwise. + * + * @return + */ + public boolean isFull(); + +} diff --git a/java/R12-01-Rot-Heap-environment/src/main/java/adt/stack/StackHeapImpl.java b/java/R12-01-Rot-Heap-environment/src/main/java/adt/stack/StackHeapImpl.java index c2738e2bf..264679cc4 100644 --- a/java/R12-01-Rot-Heap-environment/src/main/java/adt/stack/StackHeapImpl.java +++ b/java/R12-01-Rot-Heap-environment/src/main/java/adt/stack/StackHeapImpl.java @@ -1,65 +1,65 @@ -package adt.stack; - -import java.util.Comparator; - -import adt.heap.HeapImpl; -import adt.heap.HeapNode; - -public class StackHeapImpl> implements Stack { - - private int maxElements; - private int count; - private HeapImpl heap; - private long ID; - - public StackHeapImpl(int numberElements) { - Comparator> comparator = (o1, o2) -> o1.compareTo(o2); - heap = new HeapImpl(comparator); - if (numberElements < 0) { - this.maxElements = 0; - } else { - this.maxElements = numberElements; - } - count = 0; - ID = 0; - } - - @Override - public void push(T element) throws StackOverflowException { - if (element != null) { - if (isFull()) { - throw new StackOverflowException(); - } - HeapNode node = new HeapNode(element, ID); - count++; - ID++; - heap.insert(node); - } - - } - - @Override - public T pop() throws StackUnderflowException { - if (isEmpty()) { - throw new StackUnderflowException(); - } - count--; - return ((HeapNode) heap.extractRootElement()).getData(); - } - - @Override - public T top() { - return ((HeapNode) heap.rootElement()).getData(); - } - - @Override - public boolean isEmpty() { - return count == 0; - } - - @Override - public boolean isFull() { - return count == maxElements; - } - -} +package adt.stack; + +import java.util.Comparator; + +import adt.heap.HeapImpl; +import adt.heap.HeapNode; + +public class StackHeapImpl> implements Stack { + + private int maxElements; + private int count; + private HeapImpl heap; + private long ID; + + public StackHeapImpl(int numberElements) { + Comparator> comparator = (o1, o2) -> o1.compareTo(o2); + heap = new HeapImpl(comparator); + if (numberElements < 0) { + this.maxElements = 0; + } else { + this.maxElements = numberElements; + } + count = 0; + ID = 0; + } + + @Override + public void push(T element) throws StackOverflowException { + if (element != null) { + if (isFull()) { + throw new StackOverflowException(); + } + HeapNode node = new HeapNode(element, ID); + count++; + ID++; + heap.insert(node); + } + + } + + @Override + public T pop() throws StackUnderflowException { + if (isEmpty()) { + throw new StackUnderflowException(); + } + count--; + return ((HeapNode) heap.extractRootElement()).getData(); + } + + @Override + public T top() { + return ((HeapNode) heap.rootElement()).getData(); + } + + @Override + public boolean isEmpty() { + return count == 0; + } + + @Override + public boolean isFull() { + return count == maxElements; + } + +} diff --git a/java/R12-01-Rot-Heap-environment/src/main/java/adt/stack/StackOverflowException.java b/java/R12-01-Rot-Heap-environment/src/main/java/adt/stack/StackOverflowException.java index 48b51fbe9..0d322ebfb 100644 --- a/java/R12-01-Rot-Heap-environment/src/main/java/adt/stack/StackOverflowException.java +++ b/java/R12-01-Rot-Heap-environment/src/main/java/adt/stack/StackOverflowException.java @@ -1,9 +1,9 @@ -package adt.stack; - -public class StackOverflowException extends Exception { - - public StackOverflowException() { - super("Stack is full"); - } - -} +package adt.stack; + +public class StackOverflowException extends Exception { + + public StackOverflowException() { + super("Stack is full"); + } + +} diff --git a/java/R12-01-Rot-Heap-environment/src/main/java/adt/stack/StackUnderflowException.java b/java/R12-01-Rot-Heap-environment/src/main/java/adt/stack/StackUnderflowException.java index 571562b67..5a1973c62 100644 --- a/java/R12-01-Rot-Heap-environment/src/main/java/adt/stack/StackUnderflowException.java +++ b/java/R12-01-Rot-Heap-environment/src/main/java/adt/stack/StackUnderflowException.java @@ -1,8 +1,8 @@ -package adt.stack; - -public class StackUnderflowException extends Exception { - - public StackUnderflowException() { - super("Stack is empty"); - } -} +package adt.stack; + +public class StackUnderflowException extends Exception { + + public StackUnderflowException() { + super("Stack is empty"); + } +} diff --git a/java/R12-01-Rot-Heap-environment/src/main/java/util/Util.java b/java/R12-01-Rot-Heap-environment/src/main/java/util/Util.java index 4e4e1e280..337567b10 100644 --- a/java/R12-01-Rot-Heap-environment/src/main/java/util/Util.java +++ b/java/R12-01-Rot-Heap-environment/src/main/java/util/Util.java @@ -1,64 +1,64 @@ -package util; - -/** - * Class containing useful methods for arrays manipulation. - */ -public class Util { - - /** - * Swaps the contents of two positions in an array. - * - * @param array - * The array to be modified, not null - * @param i - * One of the target positions - * @param j - * The other target position - */ - public static void swap(Object[] array, int i, int j) { - if (array == null) - throw new IllegalArgumentException(); - - Object temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } - - /** - * Creates a generic array of the specified size. - *

- * Ex.: {@code Util.makeArray(10);} - * - * @param size - * The desired size - * @return An array of the type and size chosen - */ - public static T[] makeArray(int size) { - @SuppressWarnings("unchecked") - T[] array = (T[]) new Object[size]; - return array; - } - - public static T[] makeArrayOfComparable(int size) { - @SuppressWarnings("unchecked") - T[] array = (T[]) new Comparable[size]; - return array; - } - - /** - * It says if a specific number is prime or not. - * - * @param n - * @return - */ - public static boolean isPrime(long n) { - boolean result = true; - for (int i = 2; i < n; i++) { - if (n % i == 0) { - result = false; - break; - } - } - return result; - } +package util; + +/** + * Class containing useful methods for arrays manipulation. + */ +public class Util { + + /** + * Swaps the contents of two positions in an array. + * + * @param array + * The array to be modified, not null + * @param i + * One of the target positions + * @param j + * The other target position + */ + public static void swap(Object[] array, int i, int j) { + if (array == null) + throw new IllegalArgumentException(); + + Object temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + /** + * Creates a generic array of the specified size. + *

+ * Ex.: {@code Util.makeArray(10);} + * + * @param size + * The desired size + * @return An array of the type and size chosen + */ + public static T[] makeArray(int size) { + @SuppressWarnings("unchecked") + T[] array = (T[]) new Object[size]; + return array; + } + + public static T[] makeArrayOfComparable(int size) { + @SuppressWarnings("unchecked") + T[] array = (T[]) new Comparable[size]; + return array; + } + + /** + * It says if a specific number is prime or not. + * + * @param n + * @return + */ + public static boolean isPrime(long n) { + boolean result = true; + for (int i = 2; i < n; i++) { + if (n % i == 0) { + result = false; + break; + } + } + return result; + } } \ No newline at end of file diff --git a/java/R12-01-Rot-Heap-environment/src/test/java/adt/heap/QueueHeapImplTest.java b/java/R12-01-Rot-Heap-environment/src/test/java/adt/heap/QueueHeapImplTest.java index e7f7d09dc..9793e2591 100644 --- a/java/R12-01-Rot-Heap-environment/src/test/java/adt/heap/QueueHeapImplTest.java +++ b/java/R12-01-Rot-Heap-environment/src/test/java/adt/heap/QueueHeapImplTest.java @@ -1,53 +1,53 @@ -package adt.heap; - -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; - -import adt.queue.QueueHeapImpl; -import adt.queue.QueueOverflowException; -import adt.queue.QueueUnderflowException; -import adt.stack.StackHeapImpl; -import adt.stack.StackOverflowException; -import adt.stack.StackUnderflowException; - -public class QueueHeapImplTest { - public QueueHeapImpl queue; - - @Before - public void setUp() throws Exception { - queue = new QueueHeapImpl(6); - } - - - @Test - public void testPush() throws QueueOverflowException, QueueUnderflowException { - queue.enqueue("Juan"); - assertFalse(queue.isEmpty()); - - queue.enqueue("Amintas"); - - assertEquals("Juan", queue.dequeue()); - - assertEquals("Amintas", queue.dequeue()); - assertTrue(queue.isEmpty()); - - queue.enqueue("Juan1"); - queue.enqueue("Juan2"); - queue.enqueue("Juan3"); - queue.enqueue("Juan4"); - queue.enqueue("Juan5"); - queue.enqueue("Juan6"); - assertTrue(queue.isFull()); - - assertEquals("Juan1", queue.dequeue()); - assertEquals("Juan2", queue.dequeue()); - assertEquals("Juan3", queue.dequeue()); - assertEquals("Juan4", queue.dequeue()); - assertEquals("Juan5", queue.dequeue()); - assertEquals("Juan6", queue.dequeue()); - - } - -} +package adt.heap; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; + +import adt.queue.QueueHeapImpl; +import adt.queue.QueueOverflowException; +import adt.queue.QueueUnderflowException; +import adt.stack.StackHeapImpl; +import adt.stack.StackOverflowException; +import adt.stack.StackUnderflowException; + +public class QueueHeapImplTest { + public QueueHeapImpl queue; + + @Before + public void setUp() throws Exception { + queue = new QueueHeapImpl(6); + } + + + @Test + public void testPush() throws QueueOverflowException, QueueUnderflowException { + queue.enqueue("Juan"); + assertFalse(queue.isEmpty()); + + queue.enqueue("Amintas"); + + assertEquals("Juan", queue.dequeue()); + + assertEquals("Amintas", queue.dequeue()); + assertTrue(queue.isEmpty()); + + queue.enqueue("Juan1"); + queue.enqueue("Juan2"); + queue.enqueue("Juan3"); + queue.enqueue("Juan4"); + queue.enqueue("Juan5"); + queue.enqueue("Juan6"); + assertTrue(queue.isFull()); + + assertEquals("Juan1", queue.dequeue()); + assertEquals("Juan2", queue.dequeue()); + assertEquals("Juan3", queue.dequeue()); + assertEquals("Juan4", queue.dequeue()); + assertEquals("Juan5", queue.dequeue()); + assertEquals("Juan6", queue.dequeue()); + + } + +} diff --git a/java/R12-01-Rot-Heap-environment/src/test/java/adt/heap/StackHeapImplTest.java b/java/R12-01-Rot-Heap-environment/src/test/java/adt/heap/StackHeapImplTest.java index cc45c2659..4ff61eaa2 100644 --- a/java/R12-01-Rot-Heap-environment/src/test/java/adt/heap/StackHeapImplTest.java +++ b/java/R12-01-Rot-Heap-environment/src/test/java/adt/heap/StackHeapImplTest.java @@ -1,50 +1,50 @@ -package adt.heap; - -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; - -import adt.stack.StackHeapImpl; -import adt.stack.StackOverflowException; -import adt.stack.StackUnderflowException; - -public class StackHeapImplTest { - public StackHeapImpl stack; - - @Before - public void setUp() throws Exception { - stack = new StackHeapImpl(6); - } - - - @Test - public void testPush() throws StackOverflowException, StackUnderflowException { - stack.push("Juan"); - assertFalse(stack.isEmpty()); - - stack.push("Amintas"); - - assertEquals("Amintas", stack.pop()); - - assertEquals("Juan", stack.pop()); - assertTrue(stack.isEmpty()); - - stack.push("Juan1"); - stack.push("Juan2"); - stack.push("Juan3"); - stack.push("Juan4"); - stack.push("Juan5"); - stack.push("Juan6"); - assertTrue(stack.isFull()); - - assertEquals("Juan6", stack.pop()); - assertEquals("Juan5", stack.pop()); - assertEquals("Juan4", stack.pop()); - assertEquals("Juan3", stack.pop()); - assertEquals("Juan2", stack.pop()); - assertEquals("Juan1", stack.pop()); - - } - -} +package adt.heap; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; + +import adt.stack.StackHeapImpl; +import adt.stack.StackOverflowException; +import adt.stack.StackUnderflowException; + +public class StackHeapImplTest { + public StackHeapImpl stack; + + @Before + public void setUp() throws Exception { + stack = new StackHeapImpl(6); + } + + + @Test + public void testPush() throws StackOverflowException, StackUnderflowException { + stack.push("Juan"); + assertFalse(stack.isEmpty()); + + stack.push("Amintas"); + + assertEquals("Amintas", stack.pop()); + + assertEquals("Juan", stack.pop()); + assertTrue(stack.isEmpty()); + + stack.push("Juan1"); + stack.push("Juan2"); + stack.push("Juan3"); + stack.push("Juan4"); + stack.push("Juan5"); + stack.push("Juan6"); + assertTrue(stack.isFull()); + + assertEquals("Juan6", stack.pop()); + assertEquals("Juan5", stack.pop()); + assertEquals("Juan4", stack.pop()); + assertEquals("Juan3", stack.pop()); + assertEquals("Juan2", stack.pop()); + assertEquals("Juan1", stack.pop()); + + } + +} diff --git a/java/R12-01-Rot-Heap-environment/src/test/java/adt/heap/StudentMaxHeapTest.java b/java/R12-01-Rot-Heap-environment/src/test/java/adt/heap/StudentMaxHeapTest.java index f29e1fe16..efab7e2af 100644 --- a/java/R12-01-Rot-Heap-environment/src/test/java/adt/heap/StudentMaxHeapTest.java +++ b/java/R12-01-Rot-Heap-environment/src/test/java/adt/heap/StudentMaxHeapTest.java @@ -1,248 +1,248 @@ -package adt.heap; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Comparator; - -import org.junit.Before; -import org.junit.Test; - -public class StudentMaxHeapTest { - /* - * Heap heap; - * - * @Before public void setUp() { // TODO Instancie seu comparator para fazer - * sua estrutura funcionar como // uma max heap aqui. Use instanciacao - * anonima da interface // Comparator!!!! //Comparator comparator = - * null; heap = new HeapImpl((o1, o2) -> o1 - o2); } - * - * @Test public void testBuild() { heap.buildHeap(new Integer[] { 82, 6, 99, - * 12, 34, 64, 58, 1 }); - * - * assertEquals(8, heap.size()); assertFalse(heap.isEmpty()); - * - * verifyHeap(new Integer[] { 99, 12, 82, 6, 34, 64, 58, 1 }); } - * - * @Test public void testInsert() { heap.insert(8); heap.insert(12); - * heap.insert(-2); heap.insert(7); heap.insert(8); heap.insert(-5); - * heap.insert(14); heap.insert(3); heap.insert(-10); heap.insert(0); - * - * assertEquals(10, heap.size()); assertFalse(heap.isEmpty()); - * - * verifyHeap(new Integer[] { 14, 8, 12, 7, 8, -5, -2, 3, -10, 0 }); } - * - * @Test public void testRemove() { heap.insert(22); heap.insert(45); - * heap.insert(38); heap.insert(17); heap.insert(40); heap.insert(15); - * heap.insert(26); heap.insert(79); heap.insert(53); heap.insert(30); - * - * assertEquals(new Integer(79), heap.extractRootElement()); - * assertEquals(new Integer(53), heap.extractRootElement()); - * assertEquals(new Integer(45), heap.extractRootElement()); - * assertEquals(new Integer(40), heap.extractRootElement()); - * assertEquals(new Integer(38), heap.extractRootElement()); - * - * assertEquals(5, heap.size()); assertFalse(heap.isEmpty()); - * - * verifyHeap(new Integer[] { 22, 17, 15, 26, 30 }); } - * - * @Test public void testSort() { assertArrayEquals(new Integer[] { }, - * heap.heapsort(new Integer[] { })); - * - * assertEquals(0, heap.size()); assertTrue(heap.isEmpty()); - * - * assertArrayEquals(new Integer[] {}, heap.toArray()); } - * - * private void verifyHeap(Integer[] expected) { boolean isHeap = true; - * - * Comparable[] original = heap.toArray(); - * - * Arrays.sort(expected); Arrays.sort(original); - * - * if (Arrays.equals(expected, original) == false) isHeap = false; - * - * original = heap.toArray(); - * - * for (int i = 0; i < original.length; i++) { if (2 * i + 1 < - * original.length && original[i].compareTo((Integer) original[2 * i + 1]) < - * 0) isHeap = false; if (2 * i + 2 < original.length && - * original[i].compareTo((Integer) original[2 * i + 2]) < 0) isHeap = false; - * } - * - * assertTrue(isHeap); } - */ - - HeapImpl heap; - - @Before - public void setUp() { - // TODO Instancie seu comparator para fazer sua estrutura funcionar como - // uma max heap aqui. Use instanciacao anonima da interface - // Comparator!!!! - Comparator comparator = (a, b) -> a.compareTo(b); - heap = new HeapImpl(comparator); - } - - @Test - public void testBuild() { - heap.buildHeap(new Integer[] { 82, 6, 99, 12, 34, 64, 58, 1 }); - - assertEquals(8, heap.size()); - assertFalse(heap.isEmpty()); - - verifyHeap(new Integer[] { 99, 12, 82, 6, 34, 64, 58, 1 }); - } - - @Test - public void testInsert() { - heap.insert(8); - heap.insert(12); - heap.insert(-2); - heap.insert(7); - heap.insert(8); - heap.insert(-5); - heap.insert(14); - heap.insert(3); - heap.insert(-10); - heap.insert(0); - - assertEquals(10, heap.size()); - assertFalse(heap.isEmpty()); - - verifyHeap(new Integer[] { 14, 8, 12, 7, 8, -5, -2, 3, -10, 0 }); - } - - @Test - public void testCustom() { - assertTrue(heap.isEmpty()); - assertEquals(0, heap.size()); - - heap.insert(0); - heap.insert(10); - heap.insert(20); - heap.insert(-1); - heap.insert(-2); - heap.insert(Integer.MAX_VALUE); - heap.insert(Integer.MIN_VALUE); - heap.insert(1); - heap.insert(0); - heap.insert(0); - heap.insert(12); - heap.insert(100); - heap.insert(109); - heap.insert(101); - - assertFalse(heap.isEmpty()); - assertEquals(14, heap.size()); - verifyHeap( - new Integer[] { Integer.MAX_VALUE, 12, 109, 0, 1, 100, 101, -1, 0, -2, 0, 10, 20, Integer.MIN_VALUE }); - - Integer[] array = new Integer[] { Integer.MAX_VALUE, 12, 109, 0, 1, 100, 101, -1, 0, -2, 0, 10, 20, - Integer.MIN_VALUE }; - Arrays.sort(array); - - assertArrayEquals(array, heap.heapsort( - new Integer[] { Integer.MAX_VALUE, 12, 109, 0, 1, 100, 101, -1, 0, -2, 0, 10, 20, Integer.MIN_VALUE })); - assertTrue(heap.isEmpty()); - verifyHeap(new Integer[] {}); - - assertArrayEquals(new Integer[] { 1, 2, 3, 4 }, heap.heapsort(new Integer[] { 4, 2, 3, 1 })); - assertTrue(heap.isEmpty()); - verifyHeap(new Integer[] {}); - - heap.insert(0); - heap.insert(10); - heap.insert(20); - heap.insert(-1); - heap.insert(-2); - heap.insert(Integer.MAX_VALUE); - heap.insert(Integer.MIN_VALUE); - heap.insert(1); - heap.insert(0); - heap.insert(0); - heap.insert(12); - heap.insert(100); - heap.insert(109); - heap.insert(101); - heap.insert(null); - assertEquals(14, heap.size()); - - Comparator comparator = (a, b) -> a.compareTo(b); - ((HeapImpl) heap).setComparator(comparator); - - assertFalse(heap.isEmpty()); - assertEquals(14, heap.size()); - verifyHeap( - new Integer[] { Integer.MIN_VALUE, -1, -2, 0, 0, 100, 20, 10, 1, 0, 12, Integer.MAX_VALUE, 109, 101 }); - } - - @Test - public void testRemove() { - heap.insert(22); - heap.insert(45); - heap.insert(38); - heap.insert(17); - heap.insert(40); - heap.insert(15); - heap.insert(26); - heap.insert(79); - heap.insert(53); - heap.insert(30); - - assertEquals(new Integer(79), heap.extractRootElement()); - assertEquals(new Integer(53), heap.extractRootElement()); - assertEquals(new Integer(45), heap.extractRootElement()); - assertEquals(new Integer(40), heap.extractRootElement()); - assertEquals(new Integer(38), heap.extractRootElement()); - - assertEquals(5, heap.size()); - assertFalse(heap.isEmpty()); - - verifyHeap(new Integer[] { 22, 17, 15, 26, 30 }); - } - - @Test - public void testSort() { - assertArrayEquals(new Integer[] { 5, 6, 12, 20, 34, 43, 49, 92 }, - heap.heapsort(new Integer[] { 34, 92, 5, 12, 49, 20, 43, 6 })); - - assertEquals(0, heap.size()); - assertTrue(heap.isEmpty()); - - assertArrayEquals(new Integer[] {}, heap.toArray()); - } - - private void verifyHeap(Integer[] expected) { - boolean isHeap = true; - - Comparable[] original = heap.toArray(); - - Arrays.sort(expected); - Arrays.sort(original); - - if (Arrays.equals(expected, original) == false) - isHeap = false; - - original = heap.toArray(); - - for (int i = 0; i < original.length; i++) { - if (2 * i + 1 < original.length && original[i].compareTo((Integer) original[2 * i + 1]) < 0) - isHeap = false; - if (2 * i + 2 < original.length && original[i].compareTo((Integer) original[2 * i + 2]) < 0) - isHeap = false; - } - - assertTrue(isHeap); - } - - @Test - public void testHeapsortMax() { - - assertArrayEquals(new Integer[] { -10, -5, -2, 0, 3, 7, 8, 8, 12, 14 }, - heap.heapSortMax(new Integer[] { 14, 8, 12, 7, 8, -5, -2, 3, -10, 0 })); - } - -} +package adt.heap; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Comparator; + +import org.junit.Before; +import org.junit.Test; + +public class StudentMaxHeapTest { + /* + * Heap heap; + * + * @Before public void setUp() { // TODO Instancie seu comparator para fazer + * sua estrutura funcionar como // uma max heap aqui. Use instanciacao + * anonima da interface // Comparator!!!! //Comparator comparator = + * null; heap = new HeapImpl((o1, o2) -> o1 - o2); } + * + * @Test public void testBuild() { heap.buildHeap(new Integer[] { 82, 6, 99, + * 12, 34, 64, 58, 1 }); + * + * assertEquals(8, heap.size()); assertFalse(heap.isEmpty()); + * + * verifyHeap(new Integer[] { 99, 12, 82, 6, 34, 64, 58, 1 }); } + * + * @Test public void testInsert() { heap.insert(8); heap.insert(12); + * heap.insert(-2); heap.insert(7); heap.insert(8); heap.insert(-5); + * heap.insert(14); heap.insert(3); heap.insert(-10); heap.insert(0); + * + * assertEquals(10, heap.size()); assertFalse(heap.isEmpty()); + * + * verifyHeap(new Integer[] { 14, 8, 12, 7, 8, -5, -2, 3, -10, 0 }); } + * + * @Test public void testRemove() { heap.insert(22); heap.insert(45); + * heap.insert(38); heap.insert(17); heap.insert(40); heap.insert(15); + * heap.insert(26); heap.insert(79); heap.insert(53); heap.insert(30); + * + * assertEquals(new Integer(79), heap.extractRootElement()); + * assertEquals(new Integer(53), heap.extractRootElement()); + * assertEquals(new Integer(45), heap.extractRootElement()); + * assertEquals(new Integer(40), heap.extractRootElement()); + * assertEquals(new Integer(38), heap.extractRootElement()); + * + * assertEquals(5, heap.size()); assertFalse(heap.isEmpty()); + * + * verifyHeap(new Integer[] { 22, 17, 15, 26, 30 }); } + * + * @Test public void testSort() { assertArrayEquals(new Integer[] { }, + * heap.heapsort(new Integer[] { })); + * + * assertEquals(0, heap.size()); assertTrue(heap.isEmpty()); + * + * assertArrayEquals(new Integer[] {}, heap.toArray()); } + * + * private void verifyHeap(Integer[] expected) { boolean isHeap = true; + * + * Comparable[] original = heap.toArray(); + * + * Arrays.sort(expected); Arrays.sort(original); + * + * if (Arrays.equals(expected, original) == false) isHeap = false; + * + * original = heap.toArray(); + * + * for (int i = 0; i < original.length; i++) { if (2 * i + 1 < + * original.length && original[i].compareTo((Integer) original[2 * i + 1]) < + * 0) isHeap = false; if (2 * i + 2 < original.length && + * original[i].compareTo((Integer) original[2 * i + 2]) < 0) isHeap = false; + * } + * + * assertTrue(isHeap); } + */ + + HeapImpl heap; + + @Before + public void setUp() { + // TODO Instancie seu comparator para fazer sua estrutura funcionar como + // uma max heap aqui. Use instanciacao anonima da interface + // Comparator!!!! + Comparator comparator = (a, b) -> a.compareTo(b); + heap = new HeapImpl(comparator); + } + + @Test + public void testBuild() { + heap.buildHeap(new Integer[] { 82, 6, 99, 12, 34, 64, 58, 1 }); + + assertEquals(8, heap.size()); + assertFalse(heap.isEmpty()); + + verifyHeap(new Integer[] { 99, 12, 82, 6, 34, 64, 58, 1 }); + } + + @Test + public void testInsert() { + heap.insert(8); + heap.insert(12); + heap.insert(-2); + heap.insert(7); + heap.insert(8); + heap.insert(-5); + heap.insert(14); + heap.insert(3); + heap.insert(-10); + heap.insert(0); + + assertEquals(10, heap.size()); + assertFalse(heap.isEmpty()); + + verifyHeap(new Integer[] { 14, 8, 12, 7, 8, -5, -2, 3, -10, 0 }); + } + + @Test + public void testCustom() { + assertTrue(heap.isEmpty()); + assertEquals(0, heap.size()); + + heap.insert(0); + heap.insert(10); + heap.insert(20); + heap.insert(-1); + heap.insert(-2); + heap.insert(Integer.MAX_VALUE); + heap.insert(Integer.MIN_VALUE); + heap.insert(1); + heap.insert(0); + heap.insert(0); + heap.insert(12); + heap.insert(100); + heap.insert(109); + heap.insert(101); + + assertFalse(heap.isEmpty()); + assertEquals(14, heap.size()); + verifyHeap( + new Integer[] { Integer.MAX_VALUE, 12, 109, 0, 1, 100, 101, -1, 0, -2, 0, 10, 20, Integer.MIN_VALUE }); + + Integer[] array = new Integer[] { Integer.MAX_VALUE, 12, 109, 0, 1, 100, 101, -1, 0, -2, 0, 10, 20, + Integer.MIN_VALUE }; + Arrays.sort(array); + + assertArrayEquals(array, heap.heapsort( + new Integer[] { Integer.MAX_VALUE, 12, 109, 0, 1, 100, 101, -1, 0, -2, 0, 10, 20, Integer.MIN_VALUE })); + assertTrue(heap.isEmpty()); + verifyHeap(new Integer[] {}); + + assertArrayEquals(new Integer[] { 1, 2, 3, 4 }, heap.heapsort(new Integer[] { 4, 2, 3, 1 })); + assertTrue(heap.isEmpty()); + verifyHeap(new Integer[] {}); + + heap.insert(0); + heap.insert(10); + heap.insert(20); + heap.insert(-1); + heap.insert(-2); + heap.insert(Integer.MAX_VALUE); + heap.insert(Integer.MIN_VALUE); + heap.insert(1); + heap.insert(0); + heap.insert(0); + heap.insert(12); + heap.insert(100); + heap.insert(109); + heap.insert(101); + heap.insert(null); + assertEquals(14, heap.size()); + + Comparator comparator = (a, b) -> a.compareTo(b); + ((HeapImpl) heap).setComparator(comparator); + + assertFalse(heap.isEmpty()); + assertEquals(14, heap.size()); + verifyHeap( + new Integer[] { Integer.MIN_VALUE, -1, -2, 0, 0, 100, 20, 10, 1, 0, 12, Integer.MAX_VALUE, 109, 101 }); + } + + @Test + public void testRemove() { + heap.insert(22); + heap.insert(45); + heap.insert(38); + heap.insert(17); + heap.insert(40); + heap.insert(15); + heap.insert(26); + heap.insert(79); + heap.insert(53); + heap.insert(30); + + assertEquals(new Integer(79), heap.extractRootElement()); + assertEquals(new Integer(53), heap.extractRootElement()); + assertEquals(new Integer(45), heap.extractRootElement()); + assertEquals(new Integer(40), heap.extractRootElement()); + assertEquals(new Integer(38), heap.extractRootElement()); + + assertEquals(5, heap.size()); + assertFalse(heap.isEmpty()); + + verifyHeap(new Integer[] { 22, 17, 15, 26, 30 }); + } + + @Test + public void testSort() { + assertArrayEquals(new Integer[] { 5, 6, 12, 20, 34, 43, 49, 92 }, + heap.heapsort(new Integer[] { 34, 92, 5, 12, 49, 20, 43, 6 })); + + assertEquals(0, heap.size()); + assertTrue(heap.isEmpty()); + + assertArrayEquals(new Integer[] {}, heap.toArray()); + } + + private void verifyHeap(Integer[] expected) { + boolean isHeap = true; + + Comparable[] original = heap.toArray(); + + Arrays.sort(expected); + Arrays.sort(original); + + if (Arrays.equals(expected, original) == false) + isHeap = false; + + original = heap.toArray(); + + for (int i = 0; i < original.length; i++) { + if (2 * i + 1 < original.length && original[i].compareTo((Integer) original[2 * i + 1]) < 0) + isHeap = false; + if (2 * i + 2 < original.length && original[i].compareTo((Integer) original[2 * i + 2]) < 0) + isHeap = false; + } + + assertTrue(isHeap); + } + + @Test + public void testHeapsortMax() { + + assertArrayEquals(new Integer[] { -10, -5, -2, 0, 3, 7, 8, 8, 12, 14 }, + heap.heapSortMax(new Integer[] { 14, 8, 12, 7, 8, -5, -2, 3, -10, 0 })); + } + +} diff --git a/java/R12-01-Rot-Heap-environment/src/test/java/adt/heap/StudentMinHeapTest.java b/java/R12-01-Rot-Heap-environment/src/test/java/adt/heap/StudentMinHeapTest.java index 08e6de6a6..ddb766d68 100644 --- a/java/R12-01-Rot-Heap-environment/src/test/java/adt/heap/StudentMinHeapTest.java +++ b/java/R12-01-Rot-Heap-environment/src/test/java/adt/heap/StudentMinHeapTest.java @@ -1,490 +1,490 @@ -package adt.heap; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Comparator; - -import org.junit.Before; -import org.junit.Test; - -public class StudentMinHeapTest { - - /* - * - * Heap heap; - * - * @Before public void setUp() { // TODO Instancie seu comparator para fazer sua - * estrutura funcionar como // uma min heap aqui. Use instanciacao anonima da - * interface // Comparator!!!! //Comparator comparator = null; heap = - * new HeapImpl((o1, o2) -> o2 - o1); } - * - * @Test public void testBuild() { heap.buildHeap(new Integer[] { 82, 6, 99, 12, - * 34, 64, 58, 1 }); - * - * assertEquals(8, heap.size()); assertFalse(heap.isEmpty()); - * - * verifyHeap(new Integer[] { 1, 6, 58, 12, 34, 64, 99, 82 }); } - * - * @Test public void testInsert() { heap.insert(8); heap.insert(12); - * heap.insert(-2); heap.insert(7); heap.insert(8); heap.insert(-5); - * heap.insert(14); heap.insert(3); heap.insert(-10); heap.insert(0); - * - * assertEquals(10, heap.size()); assertFalse(heap.isEmpty()); - * - * verifyHeap(new Integer[] { -10, -5, -2, 3, 0, 8, 14, 12, 7, 8 }); } - * - * @Test public void testRemove() { heap.insert(22); heap.insert(45); - * heap.insert(38); heap.insert(17); heap.insert(40); heap.insert(15); - * heap.insert(26); heap.insert(79); heap.insert(53); heap.insert(30); - * - * assertEquals(new Integer(15), heap.extractRootElement()); assertEquals(new - * Integer(17), heap.extractRootElement()); assertEquals(new Integer(22), - * heap.extractRootElement()); assertEquals(new Integer(26), - * heap.extractRootElement()); assertEquals(new Integer(30), - * heap.extractRootElement()); - * - * assertEquals(5, heap.size()); assertFalse(heap.isEmpty()); - * - * verifyHeap(new Integer[] { 38, 40, 79, 45, 53 }); } - * - * @Test public void testSort() { assertArrayEquals(new Integer[] { 5, 6, 12, - * 20, 34, 43, 49, 92 }, heap.heapsort(new Integer[] { 34, 92, 5, 12, 49, 20, - * 43, 6 })); - * - * assertEquals(0, heap.size()); assertTrue(heap.isEmpty()); - * - * assertArrayEquals(new Integer[] {}, heap.toArray()); } - * - * private void verifyHeap(Integer[] expected) { boolean isHeap = true; - * - * Comparable[] original = heap.toArray(); - * - * Arrays.sort(expected); Arrays.sort(original); - * - * if (Arrays.equals(expected, original) == false) isHeap = false; - * - * original = heap.toArray(); - * - * for (int i = 0; i < original.length; i++) { if (2 * i + 1 < original.length - * && original[i].compareTo((Integer) original[2 * i + 1]) > 0) isHeap = false; - * if (2 * i + 2 < original.length && original[i].compareTo((Integer) original[2 - * * i + 2]) > 0) isHeap = false; } - * - * assertTrue(isHeap); } - */ - - HeapImpl heap; - - @Before - public void setUp() { - // TODO Instancie seu comparator para fazer sua estrutura funcionar como - // uma min heap aqui. Use instanciacao anonima da interface - // Comparator!!!! - Comparator comparator = new Comparator() { - @Override - public int compare(Integer o1, Integer o2) { - return o2.compareTo(o1); - } - }; - heap = new HeapImpl(comparator); - } - - @Test - public void testBuild() { - heap.buildHeap(new Integer[] { 82, 6, 99, 12, 34, 64, 58, 1 }); - - assertEquals(8, heap.size()); - assertFalse(heap.isEmpty()); - - verifyHeap(new Integer[] { 1, 6, 58, 12, 34, 64, 99, 82 }); - } - - @Test - public void testInsert() { - heap.insert(8); - heap.insert(12); - heap.insert(-2); - heap.insert(7); - heap.insert(8); - heap.insert(-5); - heap.insert(14); - heap.insert(3); - heap.insert(-10); - heap.insert(0); - - assertEquals(10, heap.size()); - assertFalse(heap.isEmpty()); - - verifyHeap(new Integer[] { -10, -5, -2, 3, 0, 8, 14, 12, 7, 8 }); - } - - @Test - public void testRemove() { - heap.insert(22); - heap.insert(45); - heap.insert(38); - heap.insert(17); - heap.insert(40); - heap.insert(15); - heap.insert(26); - heap.insert(79); - heap.insert(53); - heap.insert(30); - - assertEquals(new Integer(15), heap.extractRootElement()); - assertEquals(new Integer(17), heap.extractRootElement()); - assertEquals(new Integer(22), heap.extractRootElement()); - assertEquals(new Integer(26), heap.extractRootElement()); - assertEquals(new Integer(30), heap.extractRootElement()); - - assertEquals(5, heap.size()); - assertFalse(heap.isEmpty()); - - verifyHeap(new Integer[] { 38, 40, 79, 45, 53 }); - } - - @Test - public void testCustom() { - assertTrue(heap.isEmpty()); - assertEquals(0, heap.size()); - - heap.insert(0); - heap.insert(10); - heap.insert(20); - heap.insert(-1); - heap.insert(-2); - heap.insert(Integer.MAX_VALUE); - heap.insert(Integer.MIN_VALUE); - heap.insert(1); - heap.insert(0); - heap.insert(0); - heap.insert(12); - heap.insert(100); - heap.insert(109); - heap.insert(101); - - assertFalse(heap.isEmpty()); - assertEquals(14, heap.size()); - verifyHeap( - new Integer[] { Integer.MIN_VALUE, -1, -2, 0, 0, 100, 20, 10, 1, 0, 12, Integer.MAX_VALUE, 109, 101 }); - - Integer[] array = new Integer[] { Integer.MAX_VALUE, 12, 109, 0, 1, 100, 101, -1, 0, -2, 0, 10, 20, - Integer.MIN_VALUE }; - Arrays.sort(array); - - assertArrayEquals(array, heap.heapsort( - new Integer[] { Integer.MAX_VALUE, 12, 109, 0, 1, 100, 101, -1, 0, -2, 0, 10, 20, Integer.MIN_VALUE })); - assertTrue(heap.isEmpty()); - verifyHeap(new Integer[] {}); - - assertArrayEquals(new Integer[] { 1, 2, 3, 4 }, heap.heapsort(new Integer[] { 4, 2, 3, 1 })); - assertTrue(heap.isEmpty()); - verifyHeap(new Integer[] {}); - - heap.insert(0); - heap.insert(10); - heap.insert(20); - heap.insert(-1); - heap.insert(-2); - heap.insert(Integer.MAX_VALUE); - heap.insert(Integer.MIN_VALUE); - heap.insert(1); - heap.insert(0); - heap.insert(0); - heap.insert(12); - heap.insert(100); - heap.insert(109); - heap.insert(101); - heap.insert(null); - assertEquals(14, heap.size()); - heap.insert(null); - assertEquals(14, heap.size()); - - Comparator comparator = new Comparator() { - @Override - public int compare(Integer o1, Integer o2) { - return o2.compareTo(o1); - } - }; - - ((HeapImpl) heap).setComparator(comparator); - - assertFalse(heap.isEmpty()); - assertEquals(14, heap.size()); - verifyHeap( - new Integer[] { Integer.MAX_VALUE, 12, 109, 0, 1, 100, 101, -1, 0, -2, 0, 10, 20, Integer.MIN_VALUE }); - } - - @Test - public void testSort() { - assertArrayEquals(new Integer[] { 5, 6, 12, 20, 34, 43, 49, 92 }, - heap.heapsort(new Integer[] { 34, 92, 5, 12, 49, 20, 43, 6 })); - - assertEquals(0, heap.size()); - assertTrue(heap.isEmpty()); - - assertArrayEquals(new Integer[] {}, heap.toArray()); - } - - private void verifyHeap(Integer[] expected) { - boolean isHeap = true; - - Comparable[] original = heap.toArray(); - - Arrays.sort(expected); - Arrays.sort(original); - - if (Arrays.equals(expected, original) == false) - isHeap = false; - - original = heap.toArray(); - - for (int i = 0; i < original.length; i++) { - if (2 * i + 1 < original.length && original[i].compareTo((Integer) original[2 * i + 1]) > 0) - isHeap = false; - if (2 * i + 2 < original.length && original[i].compareTo((Integer) original[2 * i + 2]) > 0) - isHeap = false; - } - - assertTrue(isHeap); - } - - @Test - public void testShortestPath() { - - int INF = 10233912; - - Comparator comp = new Comparator() { - @Override - public int compare(Pair o1, Pair o2) { - return o2.compareTo(o1); - } - }; - - Heap pq = new HeapImpl<>(comp); - - int[][] graph = new int[][] { { 0, 5, 28, 0, 0, 3, 0 }, { 0, 0, 0, 7, 11, 0, 0 }, { 15, 0, 0, 0, 0, 0, 19 }, - { 0, 0, 0, 0, 0, 0, 30 }, { 9, 0, 0, 0, 0, 2, 0 }, { 0, 0, 0, 0, 0, 0, 91 }, { 0, 0, 0, 0, 0, 7, 0 } }; - int[] dist = new int[] { INF, INF, INF, INF, INF, INF, INF }; - int numberOfVertices = 7; - - int start = 0; - int end = 6; - int ans = 42; - - pq.insert(new Pair(0, 0)); - dist[start] = 0; - - while (!pq.isEmpty()) { - - int vertex = pq.rootElement().left; - int distSoFar = pq.rootElement().right; - pq.extractRootElement(); - - for (int i = 0; i < numberOfVertices; i++) { - - if (graph[vertex][i] == 0) - continue; - - if (distSoFar + graph[vertex][i] < dist[i]) { - dist[i] = distSoFar + graph[vertex][i]; - pq.insert(new Pair(i, dist[i])); - } - - } - - } - - assertEquals(ans, dist[end]); - assertEquals(16, dist[4]); - assertEquals(3, dist[5]); - assertEquals(28, dist[2]); - assertEquals(16, dist[4]); - - } - - @Test - public void testKruskal() { - - Comparator comp = new Comparator() { - @Override - public int compare(PairTwo o1, PairTwo o2) { - return o2.compareTo(o1); - } - }; - - Heap pq = new HeapImpl<>(comp); - - int[][] graph = new int[][] { { 0, 7, 0, 5, 0, 0, 0 }, { 7, 0, 8, 9, 7, 0, 0 }, { 0, 8, 0, 0, 5, 0, 0 }, - { 5, 9, 0, 0, 15, 6, 0 }, { 0, 7, 5, 15, 0, 8, 9 }, { 0, 0, 0, 6, 8, 0, 11 }, - { 0, 0, 0, 0, 9, 11, 0 } }; - - int total = 0; - - for (int i = 0; i < 7; i++) { - for (int j = 0; j < 7; j++) { - if (graph[i][j] != 0) { - total += graph[i][j]; - pq.insert(new PairTwo(i, j, graph[i][j])); - } - } - } - - total /= 2; - int ans = 0; - UnionFind uf = new UnionFind(7); - while (!pq.isEmpty()) { - int from = pq.rootElement().from; - int to = pq.rootElement().to; - int peso = pq.rootElement().peso; - pq.extractRootElement(); - - if (!uf.find(from, to)) { - ans += peso; - uf.uni(from, to); - uf.uni(to, from); - } - } - - assertEquals(51, total - ans); - } - - static class Pair implements Comparable { - public int left; - public int right; - - public Pair(int a, int b) { - left = a; - right = b; - } - - @Override - public boolean equals(Object other) { - if (other instanceof Pair) { - return ((Pair) other).left == this.left && ((Pair) other).right == this.right; - } - return false; - } - - @Override - public int compareTo(Pair other) { - if (other.left == this.left) - if (other.right == this.right) - return 0; - else if (this.right > other.right) - return 1; - else - return -1; - - if (this.left > other.left) - return 1; - else - return -1; - } - } - - static class PairTwo implements Comparable { - public int from; - public int to; - public int peso; - - public PairTwo(int a, int b, int p) { - from = a; - to = b; - peso = p; - } - - @Override - public boolean equals(Object other) { - if (other instanceof PairTwo) { - return ((PairTwo) other).to == this.to && ((PairTwo) other).from == this.from; - } - return false; - } - - @Override - public int compareTo(PairTwo other) { - if (other.peso == this.peso) - return 0; - if (other.peso > this.peso) - return -1; - return 1; - } - } - - static class UnionFind { - - int[] ar; - int[] tree_size; - int n; - - public UnionFind(int tam) { - n = tam; - ar = new int[n + 1]; - tree_size = new int[n + 1]; - for (int i = 0; i <= n; i++) { - tree_size[i] = 1; - ar[i] = i; - } - } - - int root(int i) { - while (i != ar[i]) { - ar[i] = ar[ar[i]]; // Comprimindo a arvore - i = ar[i]; - } - return i; - } - - void uni(int a, int b) { - int i = root(a); - int j = root(b); - if (tree_size[i] < tree_size[j]) { - ar[i] = j; - tree_size[j] += tree_size[i]; - } else { - ar[j] = i; - tree_size[i] += tree_size[j]; - } - } - - boolean find(int a, int b) { - return root(a) == root(b); - } - - } - - @Test - public void mergeArrays(){ - Integer[] odd = new Integer[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19}; - Integer[] even = new Integer[] { 0, 2, 4, 6, 8, 12, 14}; - - assertArrayEquals(new Integer[]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 17, 19}, heap.mergeArrays(odd, even) ); - } - - @Test - public void testSortLevel() { - heap.insert(8); - heap.insert(12); - heap.insert(-2); - heap.insert(7); - heap.insert(8); - heap.insert(-5); - heap.insert(14); - heap.insert(3); - heap.insert(-10); - heap.insert(0); - - verifyHeap(new Integer[] { -10, -5, -2, 3, 0, 8, 14, 12, 7, 8 }); - - assertArrayEquals(new Integer[] { -10 }, heap.sortLevel(0)); - assertArrayEquals(new Integer[] { -5, -2 }, heap.sortLevel(1)); - assertArrayEquals(new Integer[] { 0, 3, 8, 14 }, heap.sortLevel(2)); - assertArrayEquals(new Integer[] { 7, 8, 12 }, heap.sortLevel(3)); - } - -} +package adt.heap; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Comparator; + +import org.junit.Before; +import org.junit.Test; + +public class StudentMinHeapTest { + + /* + * + * Heap heap; + * + * @Before public void setUp() { // TODO Instancie seu comparator para fazer sua + * estrutura funcionar como // uma min heap aqui. Use instanciacao anonima da + * interface // Comparator!!!! //Comparator comparator = null; heap = + * new HeapImpl((o1, o2) -> o2 - o1); } + * + * @Test public void testBuild() { heap.buildHeap(new Integer[] { 82, 6, 99, 12, + * 34, 64, 58, 1 }); + * + * assertEquals(8, heap.size()); assertFalse(heap.isEmpty()); + * + * verifyHeap(new Integer[] { 1, 6, 58, 12, 34, 64, 99, 82 }); } + * + * @Test public void testInsert() { heap.insert(8); heap.insert(12); + * heap.insert(-2); heap.insert(7); heap.insert(8); heap.insert(-5); + * heap.insert(14); heap.insert(3); heap.insert(-10); heap.insert(0); + * + * assertEquals(10, heap.size()); assertFalse(heap.isEmpty()); + * + * verifyHeap(new Integer[] { -10, -5, -2, 3, 0, 8, 14, 12, 7, 8 }); } + * + * @Test public void testRemove() { heap.insert(22); heap.insert(45); + * heap.insert(38); heap.insert(17); heap.insert(40); heap.insert(15); + * heap.insert(26); heap.insert(79); heap.insert(53); heap.insert(30); + * + * assertEquals(new Integer(15), heap.extractRootElement()); assertEquals(new + * Integer(17), heap.extractRootElement()); assertEquals(new Integer(22), + * heap.extractRootElement()); assertEquals(new Integer(26), + * heap.extractRootElement()); assertEquals(new Integer(30), + * heap.extractRootElement()); + * + * assertEquals(5, heap.size()); assertFalse(heap.isEmpty()); + * + * verifyHeap(new Integer[] { 38, 40, 79, 45, 53 }); } + * + * @Test public void testSort() { assertArrayEquals(new Integer[] { 5, 6, 12, + * 20, 34, 43, 49, 92 }, heap.heapsort(new Integer[] { 34, 92, 5, 12, 49, 20, + * 43, 6 })); + * + * assertEquals(0, heap.size()); assertTrue(heap.isEmpty()); + * + * assertArrayEquals(new Integer[] {}, heap.toArray()); } + * + * private void verifyHeap(Integer[] expected) { boolean isHeap = true; + * + * Comparable[] original = heap.toArray(); + * + * Arrays.sort(expected); Arrays.sort(original); + * + * if (Arrays.equals(expected, original) == false) isHeap = false; + * + * original = heap.toArray(); + * + * for (int i = 0; i < original.length; i++) { if (2 * i + 1 < original.length + * && original[i].compareTo((Integer) original[2 * i + 1]) > 0) isHeap = false; + * if (2 * i + 2 < original.length && original[i].compareTo((Integer) original[2 + * * i + 2]) > 0) isHeap = false; } + * + * assertTrue(isHeap); } + */ + + HeapImpl heap; + + @Before + public void setUp() { + // TODO Instancie seu comparator para fazer sua estrutura funcionar como + // uma min heap aqui. Use instanciacao anonima da interface + // Comparator!!!! + Comparator comparator = new Comparator() { + @Override + public int compare(Integer o1, Integer o2) { + return o2.compareTo(o1); + } + }; + heap = new HeapImpl(comparator); + } + + @Test + public void testBuild() { + heap.buildHeap(new Integer[] { 82, 6, 99, 12, 34, 64, 58, 1 }); + + assertEquals(8, heap.size()); + assertFalse(heap.isEmpty()); + + verifyHeap(new Integer[] { 1, 6, 58, 12, 34, 64, 99, 82 }); + } + + @Test + public void testInsert() { + heap.insert(8); + heap.insert(12); + heap.insert(-2); + heap.insert(7); + heap.insert(8); + heap.insert(-5); + heap.insert(14); + heap.insert(3); + heap.insert(-10); + heap.insert(0); + + assertEquals(10, heap.size()); + assertFalse(heap.isEmpty()); + + verifyHeap(new Integer[] { -10, -5, -2, 3, 0, 8, 14, 12, 7, 8 }); + } + + @Test + public void testRemove() { + heap.insert(22); + heap.insert(45); + heap.insert(38); + heap.insert(17); + heap.insert(40); + heap.insert(15); + heap.insert(26); + heap.insert(79); + heap.insert(53); + heap.insert(30); + + assertEquals(new Integer(15), heap.extractRootElement()); + assertEquals(new Integer(17), heap.extractRootElement()); + assertEquals(new Integer(22), heap.extractRootElement()); + assertEquals(new Integer(26), heap.extractRootElement()); + assertEquals(new Integer(30), heap.extractRootElement()); + + assertEquals(5, heap.size()); + assertFalse(heap.isEmpty()); + + verifyHeap(new Integer[] { 38, 40, 79, 45, 53 }); + } + + @Test + public void testCustom() { + assertTrue(heap.isEmpty()); + assertEquals(0, heap.size()); + + heap.insert(0); + heap.insert(10); + heap.insert(20); + heap.insert(-1); + heap.insert(-2); + heap.insert(Integer.MAX_VALUE); + heap.insert(Integer.MIN_VALUE); + heap.insert(1); + heap.insert(0); + heap.insert(0); + heap.insert(12); + heap.insert(100); + heap.insert(109); + heap.insert(101); + + assertFalse(heap.isEmpty()); + assertEquals(14, heap.size()); + verifyHeap( + new Integer[] { Integer.MIN_VALUE, -1, -2, 0, 0, 100, 20, 10, 1, 0, 12, Integer.MAX_VALUE, 109, 101 }); + + Integer[] array = new Integer[] { Integer.MAX_VALUE, 12, 109, 0, 1, 100, 101, -1, 0, -2, 0, 10, 20, + Integer.MIN_VALUE }; + Arrays.sort(array); + + assertArrayEquals(array, heap.heapsort( + new Integer[] { Integer.MAX_VALUE, 12, 109, 0, 1, 100, 101, -1, 0, -2, 0, 10, 20, Integer.MIN_VALUE })); + assertTrue(heap.isEmpty()); + verifyHeap(new Integer[] {}); + + assertArrayEquals(new Integer[] { 1, 2, 3, 4 }, heap.heapsort(new Integer[] { 4, 2, 3, 1 })); + assertTrue(heap.isEmpty()); + verifyHeap(new Integer[] {}); + + heap.insert(0); + heap.insert(10); + heap.insert(20); + heap.insert(-1); + heap.insert(-2); + heap.insert(Integer.MAX_VALUE); + heap.insert(Integer.MIN_VALUE); + heap.insert(1); + heap.insert(0); + heap.insert(0); + heap.insert(12); + heap.insert(100); + heap.insert(109); + heap.insert(101); + heap.insert(null); + assertEquals(14, heap.size()); + heap.insert(null); + assertEquals(14, heap.size()); + + Comparator comparator = new Comparator() { + @Override + public int compare(Integer o1, Integer o2) { + return o2.compareTo(o1); + } + }; + + ((HeapImpl) heap).setComparator(comparator); + + assertFalse(heap.isEmpty()); + assertEquals(14, heap.size()); + verifyHeap( + new Integer[] { Integer.MAX_VALUE, 12, 109, 0, 1, 100, 101, -1, 0, -2, 0, 10, 20, Integer.MIN_VALUE }); + } + + @Test + public void testSort() { + assertArrayEquals(new Integer[] { 5, 6, 12, 20, 34, 43, 49, 92 }, + heap.heapsort(new Integer[] { 34, 92, 5, 12, 49, 20, 43, 6 })); + + assertEquals(0, heap.size()); + assertTrue(heap.isEmpty()); + + assertArrayEquals(new Integer[] {}, heap.toArray()); + } + + private void verifyHeap(Integer[] expected) { + boolean isHeap = true; + + Comparable[] original = heap.toArray(); + + Arrays.sort(expected); + Arrays.sort(original); + + if (Arrays.equals(expected, original) == false) + isHeap = false; + + original = heap.toArray(); + + for (int i = 0; i < original.length; i++) { + if (2 * i + 1 < original.length && original[i].compareTo((Integer) original[2 * i + 1]) > 0) + isHeap = false; + if (2 * i + 2 < original.length && original[i].compareTo((Integer) original[2 * i + 2]) > 0) + isHeap = false; + } + + assertTrue(isHeap); + } + + @Test + public void testShortestPath() { + + int INF = 10233912; + + Comparator comp = new Comparator() { + @Override + public int compare(Pair o1, Pair o2) { + return o2.compareTo(o1); + } + }; + + Heap pq = new HeapImpl<>(comp); + + int[][] graph = new int[][] { { 0, 5, 28, 0, 0, 3, 0 }, { 0, 0, 0, 7, 11, 0, 0 }, { 15, 0, 0, 0, 0, 0, 19 }, + { 0, 0, 0, 0, 0, 0, 30 }, { 9, 0, 0, 0, 0, 2, 0 }, { 0, 0, 0, 0, 0, 0, 91 }, { 0, 0, 0, 0, 0, 7, 0 } }; + int[] dist = new int[] { INF, INF, INF, INF, INF, INF, INF }; + int numberOfVertices = 7; + + int start = 0; + int end = 6; + int ans = 42; + + pq.insert(new Pair(0, 0)); + dist[start] = 0; + + while (!pq.isEmpty()) { + + int vertex = pq.rootElement().left; + int distSoFar = pq.rootElement().right; + pq.extractRootElement(); + + for (int i = 0; i < numberOfVertices; i++) { + + if (graph[vertex][i] == 0) + continue; + + if (distSoFar + graph[vertex][i] < dist[i]) { + dist[i] = distSoFar + graph[vertex][i]; + pq.insert(new Pair(i, dist[i])); + } + + } + + } + + assertEquals(ans, dist[end]); + assertEquals(16, dist[4]); + assertEquals(3, dist[5]); + assertEquals(28, dist[2]); + assertEquals(16, dist[4]); + + } + + @Test + public void testKruskal() { + + Comparator comp = new Comparator() { + @Override + public int compare(PairTwo o1, PairTwo o2) { + return o2.compareTo(o1); + } + }; + + Heap pq = new HeapImpl<>(comp); + + int[][] graph = new int[][] { { 0, 7, 0, 5, 0, 0, 0 }, { 7, 0, 8, 9, 7, 0, 0 }, { 0, 8, 0, 0, 5, 0, 0 }, + { 5, 9, 0, 0, 15, 6, 0 }, { 0, 7, 5, 15, 0, 8, 9 }, { 0, 0, 0, 6, 8, 0, 11 }, + { 0, 0, 0, 0, 9, 11, 0 } }; + + int total = 0; + + for (int i = 0; i < 7; i++) { + for (int j = 0; j < 7; j++) { + if (graph[i][j] != 0) { + total += graph[i][j]; + pq.insert(new PairTwo(i, j, graph[i][j])); + } + } + } + + total /= 2; + int ans = 0; + UnionFind uf = new UnionFind(7); + while (!pq.isEmpty()) { + int from = pq.rootElement().from; + int to = pq.rootElement().to; + int peso = pq.rootElement().peso; + pq.extractRootElement(); + + if (!uf.find(from, to)) { + ans += peso; + uf.uni(from, to); + uf.uni(to, from); + } + } + + assertEquals(51, total - ans); + } + + static class Pair implements Comparable { + public int left; + public int right; + + public Pair(int a, int b) { + left = a; + right = b; + } + + @Override + public boolean equals(Object other) { + if (other instanceof Pair) { + return ((Pair) other).left == this.left && ((Pair) other).right == this.right; + } + return false; + } + + @Override + public int compareTo(Pair other) { + if (other.left == this.left) + if (other.right == this.right) + return 0; + else if (this.right > other.right) + return 1; + else + return -1; + + if (this.left > other.left) + return 1; + else + return -1; + } + } + + static class PairTwo implements Comparable { + public int from; + public int to; + public int peso; + + public PairTwo(int a, int b, int p) { + from = a; + to = b; + peso = p; + } + + @Override + public boolean equals(Object other) { + if (other instanceof PairTwo) { + return ((PairTwo) other).to == this.to && ((PairTwo) other).from == this.from; + } + return false; + } + + @Override + public int compareTo(PairTwo other) { + if (other.peso == this.peso) + return 0; + if (other.peso > this.peso) + return -1; + return 1; + } + } + + static class UnionFind { + + int[] ar; + int[] tree_size; + int n; + + public UnionFind(int tam) { + n = tam; + ar = new int[n + 1]; + tree_size = new int[n + 1]; + for (int i = 0; i <= n; i++) { + tree_size[i] = 1; + ar[i] = i; + } + } + + int root(int i) { + while (i != ar[i]) { + ar[i] = ar[ar[i]]; // Comprimindo a arvore + i = ar[i]; + } + return i; + } + + void uni(int a, int b) { + int i = root(a); + int j = root(b); + if (tree_size[i] < tree_size[j]) { + ar[i] = j; + tree_size[j] += tree_size[i]; + } else { + ar[j] = i; + tree_size[i] += tree_size[j]; + } + } + + boolean find(int a, int b) { + return root(a) == root(b); + } + + } + + @Test + public void mergeArrays(){ + Integer[] odd = new Integer[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19}; + Integer[] even = new Integer[] { 0, 2, 4, 6, 8, 12, 14}; + + assertArrayEquals(new Integer[]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 17, 19}, heap.mergeArrays(odd, even) ); + } + + @Test + public void testSortLevel() { + heap.insert(8); + heap.insert(12); + heap.insert(-2); + heap.insert(7); + heap.insert(8); + heap.insert(-5); + heap.insert(14); + heap.insert(3); + heap.insert(-10); + heap.insert(0); + + verifyHeap(new Integer[] { -10, -5, -2, 3, 0, 8, 14, 12, 7, 8 }); + + assertArrayEquals(new Integer[] { -10 }, heap.sortLevel(0)); + assertArrayEquals(new Integer[] { -5, -2 }, heap.sortLevel(1)); + assertArrayEquals(new Integer[] { 0, 3, 8, 14 }, heap.sortLevel(2)); + assertArrayEquals(new Integer[] { 7, 8, 12 }, heap.sortLevel(3)); + } + +} diff --git a/java/R12-01-Rot-Heap-environment/walkmod.xml b/java/R12-01-Rot-Heap-environment/walkmod.xml index d391a36b4..85902bfec 100644 --- a/java/R12-01-Rot-Heap-environment/walkmod.xml +++ b/java/R12-01-Rot-Heap-environment/walkmod.xml @@ -1,4 +1,4 @@ - - - + + + \ No newline at end of file diff --git a/java/R13-01-Rot-ArvoreAVL-environment/pom.xml b/java/R13-01-Rot-ArvoreAVL-environment/pom.xml index 3f61a873c..64f2b172e 100644 --- a/java/R13-01-Rot-ArvoreAVL-environment/pom.xml +++ b/java/R13-01-Rot-ArvoreAVL-environment/pom.xml @@ -1,98 +1,98 @@ - - 4.0.0 - - br.edu.ufcg.ccc - submission - 1.0 - jar - Submissao de roteiro - - - - ufcg-leda - http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda - default - - true - always - - - - - - - junit - junit - 4.12 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - maven-clean-plugin - 3.0.0 - - - auto-clean - build - - clean - - - - - - - org.walkmod - maven-walkmod-plugin - 1.3 - - walkmod.xml - - - - package - - apply - - - false - - - - - - br.edu.ufcg.ccc - leda-compactor-tool - 1.0.0-SNAPSHOT - - - install - - compact - - - - 116110761 - - R13-01 - - 2017.1 - http://150.165.85.29:81/submitAtividade - - - - - - - + + 4.0.0 + + br.edu.ufcg.ccc + submission + 1.0 + jar + Submissao de roteiro + + + + ufcg-leda + http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda + default + + true + always + + + + + + + junit + junit + 4.12 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + maven-clean-plugin + 3.0.0 + + + auto-clean + build + + clean + + + + + + + org.walkmod + maven-walkmod-plugin + 1.3 + + walkmod.xml + + + + package + + apply + + + false + + + + + + br.edu.ufcg.ccc + leda-compactor-tool + 1.0.0-SNAPSHOT + + + install + + compact + + + + 116110761 + + R13-01 + + 2017.1 + http://150.165.85.29:81/submitAtividade + + + + + + + diff --git a/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/avltree/AVLTree.java b/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/avltree/AVLTree.java index 4d4bc4e8f..ea4c58d04 100644 --- a/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/avltree/AVLTree.java +++ b/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/avltree/AVLTree.java @@ -1,7 +1,7 @@ -package adt.avltree; - -import adt.bst.BST; - -public interface AVLTree> extends BST { - -} +package adt.avltree; + +import adt.bst.BST; + +public interface AVLTree> extends BST { + +} diff --git a/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/avltree/AVLTreeImpl.java b/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/avltree/AVLTreeImpl.java index 3ee11201a..394672744 100644 --- a/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/avltree/AVLTreeImpl.java +++ b/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/avltree/AVLTreeImpl.java @@ -1,129 +1,129 @@ -package adt.avltree; - -import adt.bst.BSTImpl; -import adt.bst.BSTNode; - -/** - * - * Performs consistency validations within a AVL Tree instance - * - * @author Claudio Campelo - * - * @param - */ -public class AVLTreeImpl> extends BSTImpl implements AVLTree { - - // TODO Do not forget: you must override the methods insert and remove - // conveniently. - - @Override - @SuppressWarnings("unchecked") - protected void insertWithNode(BSTNode node, T element) { - if (node.isEmpty()) { - node.setData(element); - node.setLeft(new BSTNode.Builder().data(null).parent(node).build()); - node.setRight(new BSTNode.Builder().data(null).parent(node).build()); - } else { - if ((element.compareTo(node.getData()) < 0)) { - insertWithNode((BSTNode) node.getLeft(), element); - } else if ((element.compareTo(node.getData()) > 0)) { - insertWithNode((BSTNode) node.getRight(), element); - } - rebalance(node); - } - } - - @Override - protected void removeRecursive(BSTNode node) { - if (!node.isEmpty()) { - if (node.isLeaf()) { - node.setData(null); - node.setLeft(null); - node.setRight(null); - rebalanceUp(node); - } else if (hasOneChild(node)) { - if (!(node.equals(getRoot()) && node.getParent() == null)) { - if (node.getParent().getLeft().equals(node)) { - if (!node.getLeft().isEmpty()) { - - node.getParent().setLeft(node.getLeft()); - node.getLeft().setParent(node.getParent()); - - } else { - node.getParent().setLeft(node.getRight()); - node.getRight().setParent(node.getParent()); - } - - } else { - if (!node.getLeft().isEmpty()) { - - node.getParent().setRight(node.getLeft()); - node.getLeft().setParent(node.getParent()); - } else { - - node.getParent().setRight(node.getRight()); - node.getRight().setParent(node.getParent()); - - } - } - } else { - if (getRoot().getLeft().isEmpty()) { - setRoot((BSTNode) getRoot().getRight()); - getRoot().setParent(null); - } else if (getRoot().getRight().isEmpty()) { - setRoot((BSTNode) getRoot().getLeft()); - getRoot().setParent(null); - } - } - rebalanceUp(node); - } else { - BSTNode sucessor = sucessor(node.getData()); - node.setData(sucessor.getData()); - removeRecursive(sucessor); - rebalanceUp(node); - } - } - } - - // AUXILIARY - protected int calculateBalance(BSTNode node) { - int result = 0; - if (!node.isEmpty()) { - result = getHeight((BSTNode) node.getLeft()) - getHeight((BSTNode) node.getRight()); - } - return result; - } - - // AUXILIARY - protected void rebalance(BSTNode node) { - int balance = calculateBalance(node); - if (balance > 1) { - if (calculateBalance((BSTNode) node.getLeft()) < 0) { - adt.bt.Util.leftRotation((BSTNode) node.getLeft()); - } - if (node == getRoot()) { - setRoot((BSTNode) node.getLeft()); - } - adt.bt.Util.rightRotation(node); - } else if (balance < -1) { - if (calculateBalance((BSTNode) node.getRight()) > 0) { - adt.bt.Util.rightRotation((BSTNode) node.getRight()); - } - if (node == getRoot()) { - setRoot((BSTNode) node.getRight()); - } - adt.bt.Util.leftRotation(node); - } - - } - - // AUXILIARY - protected void rebalanceUp(BSTNode node) { - BSTNode parent = (BSTNode) node.getParent(); - if (parent != null) { - rebalance(parent); - rebalanceUp(parent); - } - - } -} +package adt.avltree; + +import adt.bst.BSTImpl; +import adt.bst.BSTNode; + +/** + * + * Performs consistency validations within a AVL Tree instance + * + * @author Claudio Campelo + * + * @param + */ +public class AVLTreeImpl> extends BSTImpl implements AVLTree { + + // TODO Do not forget: you must override the methods insert and remove + // conveniently. + + @Override + @SuppressWarnings("unchecked") + protected void insertWithNode(BSTNode node, T element) { + if (node.isEmpty()) { + node.setData(element); + node.setLeft(new BSTNode.Builder().data(null).parent(node).build()); + node.setRight(new BSTNode.Builder().data(null).parent(node).build()); + } else { + if ((element.compareTo(node.getData()) < 0)) { + insertWithNode((BSTNode) node.getLeft(), element); + } else if ((element.compareTo(node.getData()) > 0)) { + insertWithNode((BSTNode) node.getRight(), element); + } + rebalance(node); + } + } + + @Override + protected void removeRecursive(BSTNode node) { + if (!node.isEmpty()) { + if (node.isLeaf()) { + node.setData(null); + node.setLeft(null); + node.setRight(null); + rebalanceUp(node); + } else if (hasOneChild(node)) { + if (!(node.equals(getRoot()) && node.getParent() == null)) { + if (node.getParent().getLeft().equals(node)) { + if (!node.getLeft().isEmpty()) { + + node.getParent().setLeft(node.getLeft()); + node.getLeft().setParent(node.getParent()); + + } else { + node.getParent().setLeft(node.getRight()); + node.getRight().setParent(node.getParent()); + } + + } else { + if (!node.getLeft().isEmpty()) { + + node.getParent().setRight(node.getLeft()); + node.getLeft().setParent(node.getParent()); + } else { + + node.getParent().setRight(node.getRight()); + node.getRight().setParent(node.getParent()); + + } + } + } else { + if (getRoot().getLeft().isEmpty()) { + setRoot((BSTNode) getRoot().getRight()); + getRoot().setParent(null); + } else if (getRoot().getRight().isEmpty()) { + setRoot((BSTNode) getRoot().getLeft()); + getRoot().setParent(null); + } + } + rebalanceUp(node); + } else { + BSTNode sucessor = sucessor(node.getData()); + node.setData(sucessor.getData()); + removeRecursive(sucessor); + rebalanceUp(node); + } + } + } + + // AUXILIARY + protected int calculateBalance(BSTNode node) { + int result = 0; + if (!node.isEmpty()) { + result = getHeight((BSTNode) node.getLeft()) - getHeight((BSTNode) node.getRight()); + } + return result; + } + + // AUXILIARY + protected void rebalance(BSTNode node) { + int balance = calculateBalance(node); + if (balance > 1) { + if (calculateBalance((BSTNode) node.getLeft()) < 0) { + adt.bt.Util.leftRotation((BSTNode) node.getLeft()); + } + if (node == getRoot()) { + setRoot((BSTNode) node.getLeft()); + } + adt.bt.Util.rightRotation(node); + } else if (balance < -1) { + if (calculateBalance((BSTNode) node.getRight()) > 0) { + adt.bt.Util.rightRotation((BSTNode) node.getRight()); + } + if (node == getRoot()) { + setRoot((BSTNode) node.getRight()); + } + adt.bt.Util.leftRotation(node); + } + + } + + // AUXILIARY + protected void rebalanceUp(BSTNode node) { + BSTNode parent = (BSTNode) node.getParent(); + if (parent != null) { + rebalance(parent); + rebalanceUp(parent); + } + + } +} diff --git a/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bst/BST.java b/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bst/BST.java index e2006ff32..1a0b6c375 100644 --- a/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bst/BST.java +++ b/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bst/BST.java @@ -1,34 +1,34 @@ -package adt.bst; - -import adt.bt.BT; - -/** - * The interface of a binary search tree (BST). - */ -public interface BST> extends BT { - - /** - * Returns the node containing the greatest element in a BST. If the tree is - * empty the method returns null. - */ - public BSTNode maximum(); - - /** - * Returns the node containing the lowest element in a BST. If the tree is - * empty the method returns null. - */ - public BSTNode minimum(); - - /** - * Returns a node containing the successor of the given element in a BST or - * null if it does not exist. - */ - public BSTNode sucessor(T element); - - /** - * Returns a node containing the predecessor of the given element in a BST - * or null if it does not exist. - */ - public BSTNode predecessor(T element); - -} +package adt.bst; + +import adt.bt.BT; + +/** + * The interface of a binary search tree (BST). + */ +public interface BST> extends BT { + + /** + * Returns the node containing the greatest element in a BST. If the tree is + * empty the method returns null. + */ + public BSTNode maximum(); + + /** + * Returns the node containing the lowest element in a BST. If the tree is + * empty the method returns null. + */ + public BSTNode minimum(); + + /** + * Returns a node containing the successor of the given element in a BST or + * null if it does not exist. + */ + public BSTNode sucessor(T element); + + /** + * Returns a node containing the predecessor of the given element in a BST + * or null if it does not exist. + */ + public BSTNode predecessor(T element); + +} diff --git a/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bst/BSTImpl.java b/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bst/BSTImpl.java index e780b26e7..f5bfc4e18 100644 --- a/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bst/BSTImpl.java +++ b/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bst/BSTImpl.java @@ -1,370 +1,370 @@ -package adt.bst; - -import java.util.LinkedList; -import java.util.List; -import java.util.Stack; - -public class BSTImpl> implements BST { - - protected BSTNode node; - - public BSTImpl() { - node = new BSTNode(); - } - - public BSTNode getRoot() { - return this.node; - } - - protected void setRoot(BSTNode node) { - this.node = node; - } - - @Override - public boolean isEmpty() { - return node.isEmpty(); - } - - @Override - public int height() { - return getHeight(getRoot()); - } - - protected int getHeight(BSTNode node) { - int height = -1; - if (!node.isEmpty()) { - int heightLeft = getHeight((BSTNode) node.getLeft()); - int heightRight = getHeight((BSTNode) node.getRight()); - height = 1 + longer(heightLeft, heightRight); - } - return height; - - } - - private int longer(int heightLeft, int heightRight) { - int result = heightLeft; - if (heightRight > heightLeft) { - result = heightRight; - } - return result; - } - - @Override - public BSTNode search(T element) { - return binarySearch(getRoot(), element); - } - - @SuppressWarnings("unchecked") - private BSTNode binarySearch(BSTNode node, T element) { - BSTNode result = new BSTNode.Builder().data(null).left(null).right(null).parent(null).build(); - if (node.isEmpty() || node.getData().equals(element)) { - result = node; - } else if (node.getData().compareTo(element) > 0) { - result = binarySearch((BSTNode) node.getLeft(), element); - } else { - result = binarySearch((BSTNode) node.getRight(), element); - } - return result; - } - - @Override - public void insert(T element) { - insertWithNode(getRoot(), element); - } - - @SuppressWarnings("unchecked") - protected void insertWithNode(BSTNode node, T element) { - if (node.isEmpty()) { - node.setData(element); - node.setLeft(new BSTNode.Builder().data(null).parent(node).build()); - node.setRight(new BSTNode.Builder().data(null).parent(node).build()); - } else { - if ((element.compareTo(node.getData()) < 0)) { - insertWithNode((BSTNode) node.getLeft(), element); - } else if ((element.compareTo(node.getData()) > 0)) { - insertWithNode((BSTNode) node.getRight(), element); - } - - } - - } - - @Override - public BSTNode maximum() { - BSTNode max = null; - if (!(getRoot().isEmpty())) { - max = maximumWithNode(getRoot()); - } - return max; - } - - private BSTNode maximumWithNode(BSTNode node) { - BSTNode max = node; - if (!(node.getRight().isEmpty())) { - max = maximumWithNode((BSTNode) node.getRight()); - } - return max; - } - - @Override - public BSTNode minimum() { - BSTNode min = null; - if (!(getRoot().isEmpty())) { - min = minimumWithNode(getRoot()); - } - return min; - } - - private BSTNode minimumWithNode(BSTNode node) { - BSTNode min = node; - if (!(node.getLeft().isEmpty())) { - min = minimumWithNode((BSTNode) node.getLeft()); - } - return min; - } - - @Override - public BSTNode sucessor(T element) { - BSTNode result = null; - BSTNode node = search(element); - if (!(node.isEmpty())) { - if (!(node.getRight().isEmpty())) { - result = minimumWithNode((BSTNode) node.getRight()); - } else { - result = firstDaddyRight(node); - } - } - return result; - - } - - private BSTNode firstDaddyRight(BSTNode node) { - BSTNode result = (BSTNode) node.getParent(); - if (result != null && node.equals(result.getRight())) { - result = firstDaddyRight(result); - } - return result; - } - - @Override - public BSTNode predecessor(T element) { - BSTNode result = null; - BSTNode node = search(element); - if (!(node.isEmpty())) { - if (!(node.getLeft().isEmpty())) { - result = maximumWithNode((BSTNode) node.getLeft()); - } else { - result = firstDaddyLeft(node); - } - } - return result; - } - - private BSTNode firstDaddyLeft(BSTNode node) { - BSTNode result = (BSTNode) node.getParent(); - if (result != null && node.equals(result.getLeft())) { - result = firstDaddyLeft(result); - } - return result; - } - - @Override - public void remove(T element) { - if (element != null) { - BSTNode node = search(element); - removeRecursive(node); - } - } - - protected void removeRecursive(BSTNode node) { - if (!node.isEmpty()) { - if (node.isLeaf()) { - node.setData(null); - node.setLeft(null); - node.setRight(null); - } else if (hasOneChild(node)) { - if (!(node.equals(getRoot()) && node.getParent() == null)) { - if (node.getParent().getLeft().equals(node)) { - if (!node.getLeft().isEmpty()) { - - node.getParent().setLeft(node.getLeft()); - node.getLeft().setParent(node.getParent()); - - } else { - node.getParent().setLeft(node.getRight()); - node.getRight().setParent(node.getParent()); - } - - } else { - if (!node.getLeft().isEmpty()) { - - node.getParent().setRight(node.getLeft()); - node.getLeft().setParent(node.getParent()); - } else { - - node.getParent().setRight(node.getRight()); - node.getRight().setParent(node.getParent()); - - } - } - } else { - if (getRoot().getLeft().isEmpty()) { - setRoot((BSTNode) getRoot().getRight()); - getRoot().setParent(null); - } else if (getRoot().getRight().isEmpty()) { - setRoot((BSTNode) getRoot().getLeft()); - getRoot().setParent(null); - } - } - - } else { - BSTNode sucessor = sucessor(node.getData()); - node.setData(sucessor.getData()); - removeRecursive(sucessor); - } - } - } - - protected boolean hasOneChild(BSTNode node) { - return !(node.getLeft().isEmpty() && node.getRight().isEmpty()) - && (node.getLeft().isEmpty() || node.getRight().isEmpty()); - } - - @Override - public T[] preOrder() { - T[] array = adt.bt.Util.makeArrayOfComparable(size()); - preOrderRecursive(getRoot(), array); - return array; - } - - private void preOrderRecursive(BSTNode node, T[] array) { - if (!node.isEmpty()) { - add(array, node.getData()); - preOrderRecursive((BSTNode) node.getLeft(), array); - preOrderRecursive((BSTNode) node.getRight(), array); - } - } - - private void add(T[] array, T data) { - int i = 0; - while (i < array.length) { - if (array[i] == null) { - array[i] = data; - break; - } else { - i++; - } - } - } - - @Override - public T[] order() { - T[] array = adt.bt.Util.makeArrayOfComparable(size()); - orderRecursive(getRoot(), array); - return array; - } - - private void orderRecursive(BSTNode node, T[] array) { - if (!node.isEmpty()) { - orderRecursive((BSTNode) node.getLeft(), array); - add(array, node.getData()); - orderRecursive((BSTNode) node.getRight(), array); - } - - } - - @Override - public T[] postOrder() { - T[] array = adt.bt.Util.makeArrayOfComparable(size()); - postOrderRecursive(getRoot(), array); - return array; - } - - private void postOrderRecursive(BSTNode node, T[] array) { - if (!node.isEmpty()) { - postOrderRecursive((BSTNode) node.getLeft(), array); - postOrderRecursive((BSTNode) node.getRight(), array); - add(array, node.getData()); - } - } - - public T[] arrayLevel(int level) { - T[] result = null; - if (level > 0 && level <= getHeight(getRoot())) { - LinkedList list = arrayLevel(getRoot(), new LinkedList(), level); - result = makeArrayFromList(list); - - } - return result; - } - - private LinkedList arrayLevel(BSTNode node, LinkedList list, int level) { - - if (level >= 0 && !node.isEmpty()) { - arrayLevel((BSTNode) node.getLeft(), list, level - 1); - if (level == 0) { - list.add(node.getData()); - } - arrayLevel((BSTNode) node.getRight(), list, level - 1); - } - - return list; - } - - protected T[] makeArrayFromList(List list) { - - int size = list.size(); - T[] array = adt.bt.Util.makeArrayOfComparable(size); - for (int i = 0; i != size; i++) { - array[i] = list.get(i); - } - return array; - } - - public int distance(T value1, T value2) { - int distance = -1; - BSTNode node1 = this.search(value1); - if (!node1.isEmpty()) { - BSTNode node2 = this.search(value2); - if (!node2.isEmpty()) { - Stack> pilha1, pilha2; - pilha1 = toArrayParent(node1); - pilha2 = toArrayParent(node2); - while (!pilha1.isEmpty() && !pilha2.isEmpty() && pilha1.peek().equals(pilha2.peek())) { - pilha1.pop(); - pilha2.pop(); - } - distance = pilha1.size() + pilha2.size(); - } - } - return distance; - } - - private Stack> toArrayParent(BSTNode node) { - Stack> pilha = new Stack>(); - while (node.getParent() != null) { - pilha.push(node); - node = (BSTNode) node.getParent(); - } - return pilha; - } - - /** - * This method is already implemented using recursion. You must understand - * how it work and use similar idea with the other methods. - */ - @Override - public int size() { - return size(node); - } - - private int size(BSTNode node) { - int result = 0; - // base case means doing nothing (return 0) - if (!node.isEmpty()) { // indusctive case - result = 1 + size((BSTNode) node.getLeft()) + size((BSTNode) node.getRight()); - } - return result; - } - -} +package adt.bst; + +import java.util.LinkedList; +import java.util.List; +import java.util.Stack; + +public class BSTImpl> implements BST { + + protected BSTNode node; + + public BSTImpl() { + node = new BSTNode(); + } + + public BSTNode getRoot() { + return this.node; + } + + protected void setRoot(BSTNode node) { + this.node = node; + } + + @Override + public boolean isEmpty() { + return node.isEmpty(); + } + + @Override + public int height() { + return getHeight(getRoot()); + } + + protected int getHeight(BSTNode node) { + int height = -1; + if (!node.isEmpty()) { + int heightLeft = getHeight((BSTNode) node.getLeft()); + int heightRight = getHeight((BSTNode) node.getRight()); + height = 1 + longer(heightLeft, heightRight); + } + return height; + + } + + private int longer(int heightLeft, int heightRight) { + int result = heightLeft; + if (heightRight > heightLeft) { + result = heightRight; + } + return result; + } + + @Override + public BSTNode search(T element) { + return binarySearch(getRoot(), element); + } + + @SuppressWarnings("unchecked") + private BSTNode binarySearch(BSTNode node, T element) { + BSTNode result = new BSTNode.Builder().data(null).left(null).right(null).parent(null).build(); + if (node.isEmpty() || node.getData().equals(element)) { + result = node; + } else if (node.getData().compareTo(element) > 0) { + result = binarySearch((BSTNode) node.getLeft(), element); + } else { + result = binarySearch((BSTNode) node.getRight(), element); + } + return result; + } + + @Override + public void insert(T element) { + insertWithNode(getRoot(), element); + } + + @SuppressWarnings("unchecked") + protected void insertWithNode(BSTNode node, T element) { + if (node.isEmpty()) { + node.setData(element); + node.setLeft(new BSTNode.Builder().data(null).parent(node).build()); + node.setRight(new BSTNode.Builder().data(null).parent(node).build()); + } else { + if ((element.compareTo(node.getData()) < 0)) { + insertWithNode((BSTNode) node.getLeft(), element); + } else if ((element.compareTo(node.getData()) > 0)) { + insertWithNode((BSTNode) node.getRight(), element); + } + + } + + } + + @Override + public BSTNode maximum() { + BSTNode max = null; + if (!(getRoot().isEmpty())) { + max = maximumWithNode(getRoot()); + } + return max; + } + + private BSTNode maximumWithNode(BSTNode node) { + BSTNode max = node; + if (!(node.getRight().isEmpty())) { + max = maximumWithNode((BSTNode) node.getRight()); + } + return max; + } + + @Override + public BSTNode minimum() { + BSTNode min = null; + if (!(getRoot().isEmpty())) { + min = minimumWithNode(getRoot()); + } + return min; + } + + private BSTNode minimumWithNode(BSTNode node) { + BSTNode min = node; + if (!(node.getLeft().isEmpty())) { + min = minimumWithNode((BSTNode) node.getLeft()); + } + return min; + } + + @Override + public BSTNode sucessor(T element) { + BSTNode result = null; + BSTNode node = search(element); + if (!(node.isEmpty())) { + if (!(node.getRight().isEmpty())) { + result = minimumWithNode((BSTNode) node.getRight()); + } else { + result = firstDaddyRight(node); + } + } + return result; + + } + + private BSTNode firstDaddyRight(BSTNode node) { + BSTNode result = (BSTNode) node.getParent(); + if (result != null && node.equals(result.getRight())) { + result = firstDaddyRight(result); + } + return result; + } + + @Override + public BSTNode predecessor(T element) { + BSTNode result = null; + BSTNode node = search(element); + if (!(node.isEmpty())) { + if (!(node.getLeft().isEmpty())) { + result = maximumWithNode((BSTNode) node.getLeft()); + } else { + result = firstDaddyLeft(node); + } + } + return result; + } + + private BSTNode firstDaddyLeft(BSTNode node) { + BSTNode result = (BSTNode) node.getParent(); + if (result != null && node.equals(result.getLeft())) { + result = firstDaddyLeft(result); + } + return result; + } + + @Override + public void remove(T element) { + if (element != null) { + BSTNode node = search(element); + removeRecursive(node); + } + } + + protected void removeRecursive(BSTNode node) { + if (!node.isEmpty()) { + if (node.isLeaf()) { + node.setData(null); + node.setLeft(null); + node.setRight(null); + } else if (hasOneChild(node)) { + if (!(node.equals(getRoot()) && node.getParent() == null)) { + if (node.getParent().getLeft().equals(node)) { + if (!node.getLeft().isEmpty()) { + + node.getParent().setLeft(node.getLeft()); + node.getLeft().setParent(node.getParent()); + + } else { + node.getParent().setLeft(node.getRight()); + node.getRight().setParent(node.getParent()); + } + + } else { + if (!node.getLeft().isEmpty()) { + + node.getParent().setRight(node.getLeft()); + node.getLeft().setParent(node.getParent()); + } else { + + node.getParent().setRight(node.getRight()); + node.getRight().setParent(node.getParent()); + + } + } + } else { + if (getRoot().getLeft().isEmpty()) { + setRoot((BSTNode) getRoot().getRight()); + getRoot().setParent(null); + } else if (getRoot().getRight().isEmpty()) { + setRoot((BSTNode) getRoot().getLeft()); + getRoot().setParent(null); + } + } + + } else { + BSTNode sucessor = sucessor(node.getData()); + node.setData(sucessor.getData()); + removeRecursive(sucessor); + } + } + } + + protected boolean hasOneChild(BSTNode node) { + return !(node.getLeft().isEmpty() && node.getRight().isEmpty()) + && (node.getLeft().isEmpty() || node.getRight().isEmpty()); + } + + @Override + public T[] preOrder() { + T[] array = adt.bt.Util.makeArrayOfComparable(size()); + preOrderRecursive(getRoot(), array); + return array; + } + + private void preOrderRecursive(BSTNode node, T[] array) { + if (!node.isEmpty()) { + add(array, node.getData()); + preOrderRecursive((BSTNode) node.getLeft(), array); + preOrderRecursive((BSTNode) node.getRight(), array); + } + } + + private void add(T[] array, T data) { + int i = 0; + while (i < array.length) { + if (array[i] == null) { + array[i] = data; + break; + } else { + i++; + } + } + } + + @Override + public T[] order() { + T[] array = adt.bt.Util.makeArrayOfComparable(size()); + orderRecursive(getRoot(), array); + return array; + } + + private void orderRecursive(BSTNode node, T[] array) { + if (!node.isEmpty()) { + orderRecursive((BSTNode) node.getLeft(), array); + add(array, node.getData()); + orderRecursive((BSTNode) node.getRight(), array); + } + + } + + @Override + public T[] postOrder() { + T[] array = adt.bt.Util.makeArrayOfComparable(size()); + postOrderRecursive(getRoot(), array); + return array; + } + + private void postOrderRecursive(BSTNode node, T[] array) { + if (!node.isEmpty()) { + postOrderRecursive((BSTNode) node.getLeft(), array); + postOrderRecursive((BSTNode) node.getRight(), array); + add(array, node.getData()); + } + } + + public T[] arrayLevel(int level) { + T[] result = null; + if (level > 0 && level <= getHeight(getRoot())) { + LinkedList list = arrayLevel(getRoot(), new LinkedList(), level); + result = makeArrayFromList(list); + + } + return result; + } + + private LinkedList arrayLevel(BSTNode node, LinkedList list, int level) { + + if (level >= 0 && !node.isEmpty()) { + arrayLevel((BSTNode) node.getLeft(), list, level - 1); + if (level == 0) { + list.add(node.getData()); + } + arrayLevel((BSTNode) node.getRight(), list, level - 1); + } + + return list; + } + + protected T[] makeArrayFromList(List list) { + + int size = list.size(); + T[] array = adt.bt.Util.makeArrayOfComparable(size); + for (int i = 0; i != size; i++) { + array[i] = list.get(i); + } + return array; + } + + public int distance(T value1, T value2) { + int distance = -1; + BSTNode node1 = this.search(value1); + if (!node1.isEmpty()) { + BSTNode node2 = this.search(value2); + if (!node2.isEmpty()) { + Stack> pilha1, pilha2; + pilha1 = toArrayParent(node1); + pilha2 = toArrayParent(node2); + while (!pilha1.isEmpty() && !pilha2.isEmpty() && pilha1.peek().equals(pilha2.peek())) { + pilha1.pop(); + pilha2.pop(); + } + distance = pilha1.size() + pilha2.size(); + } + } + return distance; + } + + private Stack> toArrayParent(BSTNode node) { + Stack> pilha = new Stack>(); + while (node.getParent() != null) { + pilha.push(node); + node = (BSTNode) node.getParent(); + } + return pilha; + } + + /** + * This method is already implemented using recursion. You must understand + * how it work and use similar idea with the other methods. + */ + @Override + public int size() { + return size(node); + } + + private int size(BSTNode node) { + int result = 0; + // base case means doing nothing (return 0) + if (!node.isEmpty()) { // indusctive case + result = 1 + size((BSTNode) node.getLeft()) + size((BSTNode) node.getRight()); + } + return result; + } + +} diff --git a/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bst/BSTNode.java b/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bst/BSTNode.java index 78290cd67..f38cb8873 100644 --- a/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bst/BSTNode.java +++ b/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bst/BSTNode.java @@ -1,59 +1,59 @@ -package adt.bst; - -import adt.bt.BTNode; - -public class BSTNode> extends BTNode { - - public BSTNode() { - super(); - } - - // código abaixo é um exempo de uso do padrão Builder para construir - // objetos do tipo BSTNode sem usar construtor diretamente. - // o código cliente desse padrao, criando o no vazio seria: - // BSTNode node = (BSTNode) new BSTNode.Builder() - // .data(null) - // .left(null) - // .right(null) - // .parent(null) - // .build(); - - public static class Builder { - T data; - BTNode left; - BTNode right; - BTNode parent; - - public BSTNode.Builder data(T data) { - this.data = data; - return this; - } - - public BSTNode.Builder left(BTNode left) { - this.left = left; - return this; - } - - public BSTNode.Builder right(BTNode right) { - this.right = right; - return this; - } - - public BSTNode.Builder parent(BTNode parent) { - this.parent = parent; - return this; - } - - public BSTNode build() { - return new BSTNode(this); - } - } - - private BSTNode(BSTNode.Builder builder) { - this.data = builder.data; - this.left = builder.left; - this.right = builder.right; - this.parent = builder.parent; - - } -} +package adt.bst; + +import adt.bt.BTNode; + +public class BSTNode> extends BTNode { + + public BSTNode() { + super(); + } + + // código abaixo é um exempo de uso do padrão Builder para construir + // objetos do tipo BSTNode sem usar construtor diretamente. + // o código cliente desse padrao, criando o no vazio seria: + // BSTNode node = (BSTNode) new BSTNode.Builder() + // .data(null) + // .left(null) + // .right(null) + // .parent(null) + // .build(); + + public static class Builder { + T data; + BTNode left; + BTNode right; + BTNode parent; + + public BSTNode.Builder data(T data) { + this.data = data; + return this; + } + + public BSTNode.Builder left(BTNode left) { + this.left = left; + return this; + } + + public BSTNode.Builder right(BTNode right) { + this.right = right; + return this; + } + + public BSTNode.Builder parent(BTNode parent) { + this.parent = parent; + return this; + } + + public BSTNode build() { + return new BSTNode(this); + } + } + + private BSTNode(BSTNode.Builder builder) { + this.data = builder.data; + this.left = builder.left; + this.right = builder.right; + this.parent = builder.parent; + + } +} diff --git a/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bt/BT.java b/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bt/BT.java index 7e0e20008..2ce273363 100644 --- a/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bt/BT.java +++ b/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bt/BT.java @@ -1,65 +1,65 @@ -package adt.bt; - -/** - * The interface of a generic binary tree (BT). It has nodes containing elements - * of type T. - */ -public interface BT { - /** - * Returns the root of the tree. - * - * @return - */ - public BTNode getRoot(); - - /** - * Say if a BT is empty (NIL). - */ - public boolean isEmpty(); - - /** - * The height of a BT. An empty BT has height -1 (there is no root element). - * In non-empty BT the height is given by 1 + (the highest height of its - * sub-trees). - */ - public int height(); - - /** - * Searches an element in a BT. The search starts at the root node. If the - * key does not exist the methods returns a NIL (empty) node. - */ - public BTNode search(T elem); - - /** - * Inserts an element in a BT. - */ - public void insert(T value); - - /** - * Removes a node from a BT. - */ - public void remove(T key); - - /** - * Returns an array of elements filled according to the pre-order traversing - * in a BT. - */ - public T[] preOrder(); - - /** - * Returns an array of elements filled according to the symmetric order - * traversing in a BT. - */ - public T[] order(); - - /** - * Returns an array of elements filled according to the port-order - * traversing in a BT. - */ - public T[] postOrder(); - - /** - * Returns the number of nodes (not NIL) in a BT. - */ - public int size(); -} +package adt.bt; + +/** + * The interface of a generic binary tree (BT). It has nodes containing elements + * of type T. + */ +public interface BT { + /** + * Returns the root of the tree. + * + * @return + */ + public BTNode getRoot(); + + /** + * Say if a BT is empty (NIL). + */ + public boolean isEmpty(); + + /** + * The height of a BT. An empty BT has height -1 (there is no root element). + * In non-empty BT the height is given by 1 + (the highest height of its + * sub-trees). + */ + public int height(); + + /** + * Searches an element in a BT. The search starts at the root node. If the + * key does not exist the methods returns a NIL (empty) node. + */ + public BTNode search(T elem); + + /** + * Inserts an element in a BT. + */ + public void insert(T value); + + /** + * Removes a node from a BT. + */ + public void remove(T key); + + /** + * Returns an array of elements filled according to the pre-order traversing + * in a BT. + */ + public T[] preOrder(); + + /** + * Returns an array of elements filled according to the symmetric order + * traversing in a BT. + */ + public T[] order(); + + /** + * Returns an array of elements filled according to the port-order + * traversing in a BT. + */ + public T[] postOrder(); + + /** + * Returns the number of nodes (not NIL) in a BT. + */ + public int size(); +} diff --git a/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bt/BTNode.java b/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bt/BTNode.java index dd86bff2c..c059f8531 100644 --- a/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bt/BTNode.java +++ b/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bt/BTNode.java @@ -1,86 +1,86 @@ -package adt.bt; - -/** - * The node of a binary tree. Its internal data has type T, which does not need - * to be comparable. - */ -public class BTNode { - protected T data; - protected BTNode left; - protected BTNode right; - protected BTNode parent; - - public BTNode(T data, BTNode left, BTNode right, BTNode parent) { - this.data = data; - this.left = left; - this.right = right; - this.parent = parent; - } - - public BTNode() { - } - - public boolean isEmpty() { - return this.data == null; - } - - public boolean isLeaf() { - return this.data != null && this.left.isEmpty() && this.right.isEmpty(); - } - - @Override - public String toString() { - String resp = "NIL"; - if (!isEmpty()) { - resp = data.toString(); - } - return resp; - } - - @SuppressWarnings("unchecked") - @Override - public boolean equals(Object obj) { - boolean resp = false; - if (obj instanceof BTNode) { - if (!this.isEmpty() && !((BTNode) obj).isEmpty()) { - resp = this.data.equals(((BTNode) obj).data); - } else { - resp = this.isEmpty() && ((BTNode) obj).isEmpty(); - } - - } - return resp; - } - - public T getData() { - return data; - } - - public void setData(T data) { - this.data = data; - } - - public BTNode getLeft() { - return left; - } - - public void setLeft(BTNode left) { - this.left = left; - } - - public BTNode getRight() { - return right; - } - - public void setRight(BTNode right) { - this.right = right; - } - - public BTNode getParent() { - return parent; - } - - public void setParent(BTNode parent) { - this.parent = parent; - } -} +package adt.bt; + +/** + * The node of a binary tree. Its internal data has type T, which does not need + * to be comparable. + */ +public class BTNode { + protected T data; + protected BTNode left; + protected BTNode right; + protected BTNode parent; + + public BTNode(T data, BTNode left, BTNode right, BTNode parent) { + this.data = data; + this.left = left; + this.right = right; + this.parent = parent; + } + + public BTNode() { + } + + public boolean isEmpty() { + return this.data == null; + } + + public boolean isLeaf() { + return this.data != null && this.left.isEmpty() && this.right.isEmpty(); + } + + @Override + public String toString() { + String resp = "NIL"; + if (!isEmpty()) { + resp = data.toString(); + } + return resp; + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(Object obj) { + boolean resp = false; + if (obj instanceof BTNode) { + if (!this.isEmpty() && !((BTNode) obj).isEmpty()) { + resp = this.data.equals(((BTNode) obj).data); + } else { + resp = this.isEmpty() && ((BTNode) obj).isEmpty(); + } + + } + return resp; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public BTNode getLeft() { + return left; + } + + public void setLeft(BTNode left) { + this.left = left; + } + + public BTNode getRight() { + return right; + } + + public void setRight(BTNode right) { + this.right = right; + } + + public BTNode getParent() { + return parent; + } + + public void setParent(BTNode parent) { + this.parent = parent; + } +} diff --git a/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bt/Util.java b/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bt/Util.java index 6c8253927..064379829 100644 --- a/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bt/Util.java +++ b/java/R13-01-Rot-ArvoreAVL-environment/src/main/java/adt/bt/Util.java @@ -1,63 +1,63 @@ -package adt.bt; - -import adt.bst.BSTNode; - -public class Util { - - /** - * A rotacao a esquerda em node deve subir e retornar seu filho a direita - * - * @param node - * @return - */ - public static > BSTNode leftRotation(BSTNode node) { - BSTNode pivot = (BSTNode) node.getRight(); - pivot.setParent(node.getParent()); - if (pivot.getParent() != null) { - if (node.getParent().getLeft().equals(node)) { - pivot.getParent().setLeft(pivot); - } else { - pivot.getParent().setRight(pivot); - } - } - node.setRight(pivot.getLeft()); - node.getRight().setParent(node); - node.setParent(pivot); - pivot.setLeft(node); - pivot.getLeft().setParent(pivot); - node = pivot; - return node; - } - - /** - * A rotacao a direita em node deve subir e retornar seu filho a esquerda - * - * @param node - * @return - */ - public static > BSTNode rightRotation(BSTNode node) { - BSTNode pivot = (BSTNode) node.getLeft(); - pivot.setParent(node.getParent()); - if (pivot.getParent() != null) { - if (node.getParent().getLeft().equals(node)) { - pivot.getParent().setLeft(pivot); - } else { - pivot.getParent().setRight(pivot); - } - } - node.setLeft(pivot.getRight()); - node.getLeft().setParent(node); - node.setParent(pivot); - pivot.setRight(node); - pivot.getRight().setParent(pivot); - node = pivot; - return node; - } - - public static > T[] makeArrayOfComparable(int size) { - @SuppressWarnings("unchecked") - T[] array = (T[]) new Comparable[size]; - return array; - } - -} +package adt.bt; + +import adt.bst.BSTNode; + +public class Util { + + /** + * A rotacao a esquerda em node deve subir e retornar seu filho a direita + * + * @param node + * @return + */ + public static > BSTNode leftRotation(BSTNode node) { + BSTNode pivot = (BSTNode) node.getRight(); + pivot.setParent(node.getParent()); + if (pivot.getParent() != null) { + if (node.getParent().getLeft().equals(node)) { + pivot.getParent().setLeft(pivot); + } else { + pivot.getParent().setRight(pivot); + } + } + node.setRight(pivot.getLeft()); + node.getRight().setParent(node); + node.setParent(pivot); + pivot.setLeft(node); + pivot.getLeft().setParent(pivot); + node = pivot; + return node; + } + + /** + * A rotacao a direita em node deve subir e retornar seu filho a esquerda + * + * @param node + * @return + */ + public static > BSTNode rightRotation(BSTNode node) { + BSTNode pivot = (BSTNode) node.getLeft(); + pivot.setParent(node.getParent()); + if (pivot.getParent() != null) { + if (node.getParent().getLeft().equals(node)) { + pivot.getParent().setLeft(pivot); + } else { + pivot.getParent().setRight(pivot); + } + } + node.setLeft(pivot.getRight()); + node.getLeft().setParent(node); + node.setParent(pivot); + pivot.setRight(node); + pivot.getRight().setParent(pivot); + node = pivot; + return node; + } + + public static > T[] makeArrayOfComparable(int size) { + @SuppressWarnings("unchecked") + T[] array = (T[]) new Comparable[size]; + return array; + } + +} diff --git a/java/R13-01-Rot-ArvoreAVL-environment/src/test/java/adt/avltree/StudentAVLTest.java b/java/R13-01-Rot-ArvoreAVL-environment/src/test/java/adt/avltree/StudentAVLTest.java index 854acfd95..b42f41639 100644 --- a/java/R13-01-Rot-ArvoreAVL-environment/src/test/java/adt/avltree/StudentAVLTest.java +++ b/java/R13-01-Rot-ArvoreAVL-environment/src/test/java/adt/avltree/StudentAVLTest.java @@ -1,72 +1,72 @@ -package adt.avltree; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.junit.Before; - -import adt.bst.BSTNode; - -public class StudentAVLTest { - - private AVLTree avl; - private BSTNode NIL = new BSTNode(); - - @Before - public void setUp() { - avl = new AVLTreeImpl(); - } - - @Test - public void testInit() { - assertTrue(avl.isEmpty()); - assertEquals(0, avl.size()); - assertEquals(-1, avl.height()); - assertEquals(NIL, avl.getRoot()); - } - - @Test - public void testInsert() { - avl.insert(-10); - assertEquals(1, avl.size()); - assertEquals(0, avl.height()); - assertArrayEquals(new Integer[] { -10 }, avl.preOrder()); - - assertFalse(avl.isEmpty()); - assertEquals(new Integer(-10), avl.getRoot().getData()); - - avl.insert(-15); - assertEquals(2, avl.size()); - assertEquals(1, avl.height()); - assertArrayEquals(new Integer[] { -10, -15 }, avl.preOrder()); - - avl.insert(20); - assertEquals(3, avl.size()); - assertEquals(1, avl.height()); - assertArrayEquals(new Integer[] { -10, -15, 20 }, avl.preOrder()); - } - - @Test - public void testRemove() { - avl.insert(55); - avl.insert(9); - avl.insert(91); - avl.insert(12); - - avl.remove(-1); - assertEquals(4, avl.size()); - - avl.remove(91); - assertEquals(3, avl.size()); - assertArrayEquals(new Integer[] { 12, 9, 55 }, avl.preOrder()); - - avl.remove(12); - assertEquals(2, avl.size()); - assertArrayEquals(new Integer[] { 55, 9 }, avl.preOrder()); - - avl.remove(9); - avl.remove(55); - assertEquals(NIL, avl.getRoot()); - assertTrue(avl.isEmpty()); - } -} +package adt.avltree; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.junit.Before; + +import adt.bst.BSTNode; + +public class StudentAVLTest { + + private AVLTree avl; + private BSTNode NIL = new BSTNode(); + + @Before + public void setUp() { + avl = new AVLTreeImpl(); + } + + @Test + public void testInit() { + assertTrue(avl.isEmpty()); + assertEquals(0, avl.size()); + assertEquals(-1, avl.height()); + assertEquals(NIL, avl.getRoot()); + } + + @Test + public void testInsert() { + avl.insert(-10); + assertEquals(1, avl.size()); + assertEquals(0, avl.height()); + assertArrayEquals(new Integer[] { -10 }, avl.preOrder()); + + assertFalse(avl.isEmpty()); + assertEquals(new Integer(-10), avl.getRoot().getData()); + + avl.insert(-15); + assertEquals(2, avl.size()); + assertEquals(1, avl.height()); + assertArrayEquals(new Integer[] { -10, -15 }, avl.preOrder()); + + avl.insert(20); + assertEquals(3, avl.size()); + assertEquals(1, avl.height()); + assertArrayEquals(new Integer[] { -10, -15, 20 }, avl.preOrder()); + } + + @Test + public void testRemove() { + avl.insert(55); + avl.insert(9); + avl.insert(91); + avl.insert(12); + + avl.remove(-1); + assertEquals(4, avl.size()); + + avl.remove(91); + assertEquals(3, avl.size()); + assertArrayEquals(new Integer[] { 12, 9, 55 }, avl.preOrder()); + + avl.remove(12); + assertEquals(2, avl.size()); + assertArrayEquals(new Integer[] { 55, 9 }, avl.preOrder()); + + avl.remove(9); + avl.remove(55); + assertEquals(NIL, avl.getRoot()); + assertTrue(avl.isEmpty()); + } +} diff --git a/java/R13-01-Rot-ArvoreAVL-environment/walkmod.xml b/java/R13-01-Rot-ArvoreAVL-environment/walkmod.xml index d391a36b4..85902bfec 100644 --- a/java/R13-01-Rot-ArvoreAVL-environment/walkmod.xml +++ b/java/R13-01-Rot-ArvoreAVL-environment/walkmod.xml @@ -1,4 +1,4 @@ - - - + + + \ No newline at end of file diff --git a/java/R14-01-Rot-ArvoreAVLCountFill-environment/pom.xml b/java/R14-01-Rot-ArvoreAVLCountFill-environment/pom.xml index 18ed9c34c..122859bca 100644 --- a/java/R14-01-Rot-ArvoreAVLCountFill-environment/pom.xml +++ b/java/R14-01-Rot-ArvoreAVLCountFill-environment/pom.xml @@ -1,98 +1,98 @@ - - 4.0.0 - - br.edu.ufcg.ccc - submission - 1.0 - jar - Submissao de roteiro - - - - ufcg-leda - http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda - default - - true - always - - - - - - - junit - junit - 4.12 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - maven-clean-plugin - 3.0.0 - - - auto-clean - build - - clean - - - - - - - org.walkmod - maven-walkmod-plugin - 1.3 - - walkmod.xml - - - - package - - apply - - - false - - - - - - br.edu.ufcg.ccc - leda-compactor-tool - 1.0.0-SNAPSHOT - - - install - - compact - - - - 116110761 - - R14-01 - - 2017.1 - http://150.165.85.29:81/submitAtividade - - - - - - - + + 4.0.0 + + br.edu.ufcg.ccc + submission + 1.0 + jar + Submissao de roteiro + + + + ufcg-leda + http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda + default + + true + always + + + + + + + junit + junit + 4.12 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + maven-clean-plugin + 3.0.0 + + + auto-clean + build + + clean + + + + + + + org.walkmod + maven-walkmod-plugin + 1.3 + + walkmod.xml + + + + package + + apply + + + false + + + + + + br.edu.ufcg.ccc + leda-compactor-tool + 1.0.0-SNAPSHOT + + + install + + compact + + + + 116110761 + + R14-01 + + 2017.1 + http://150.165.85.29:81/submitAtividade + + + + + + + diff --git a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/avltree/AVLCountAndFill.java b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/avltree/AVLCountAndFill.java index d5e9e7ff4..876324a6f 100644 --- a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/avltree/AVLCountAndFill.java +++ b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/avltree/AVLCountAndFill.java @@ -1,43 +1,43 @@ -package adt.avltree; - -public interface AVLCountAndFill> extends AVLTree { - - /** - * The number of LL cases - * - * @return the number of LL cases - */ - public int LLcount(); - - /** - * The number of LR cases - * - * @return the number of LR cases - */ - public int LRcount(); - - /** - * The number of RR cases - * - * @return the number of RR cases - */ - public int RRcount(); - - /** - * The number of RL cases - * - * @return the number of RL cases - */ - public int RLcount(); - - /** - * It fills this AVL tree with the elements from the array argument, while - * avoiding any rotation operation. Any existing elements must be kept in - * the tree. You must use only the insert method to add new - * elements to the tree. - * - * @param array - * the array containing the data to be inserted in this tree. - */ - public void fillWithoutRebalance(T[] array); -} +package adt.avltree; + +public interface AVLCountAndFill> extends AVLTree { + + /** + * The number of LL cases + * + * @return the number of LL cases + */ + public int LLcount(); + + /** + * The number of LR cases + * + * @return the number of LR cases + */ + public int LRcount(); + + /** + * The number of RR cases + * + * @return the number of RR cases + */ + public int RRcount(); + + /** + * The number of RL cases + * + * @return the number of RL cases + */ + public int RLcount(); + + /** + * It fills this AVL tree with the elements from the array argument, while + * avoiding any rotation operation. Any existing elements must be kept in + * the tree. You must use only the insert method to add new + * elements to the tree. + * + * @param array + * the array containing the data to be inserted in this tree. + */ + public void fillWithoutRebalance(T[] array); +} diff --git a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/avltree/AVLCountAndFillImpl.java b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/avltree/AVLCountAndFillImpl.java index e9fa38a61..ff2dd9a9e 100644 --- a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/avltree/AVLCountAndFillImpl.java +++ b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/avltree/AVLCountAndFillImpl.java @@ -1,126 +1,126 @@ -package adt.avltree; - -import adt.bst.BSTNode; - -public class AVLCountAndFillImpl> extends AVLTreeImpl implements AVLCountAndFill { - - private int LLcounter; - private int LRcounter; - private int RRcounter; - private int RLcounter; - - public AVLCountAndFillImpl() { - - } - - @Override - protected void rebalance(BSTNode node) { - int balance = calculateBalance(node); - if (balance > 1) { - if (calculateBalance((BSTNode) node.getLeft()) < 0) { - adt.bt.Util.leftRotation((BSTNode) node.getLeft()); - LRcounter++; - } else { - LLcounter++; - } - if (node == getRoot()) { - setRoot((BSTNode) node.getLeft()); - } - adt.bt.Util.rightRotation(node); - } else if (balance < -1) { - if (calculateBalance((BSTNode) node.getRight()) > 0) { - adt.bt.Util.rightRotation((BSTNode) node.getRight()); - RLcounter++; - } else { - RRcounter++; - } - if (node == getRoot()) { - setRoot((BSTNode) node.getRight()); - } - adt.bt.Util.leftRotation(node); - } - } - - @Override - public int LLcount() { - return LLcounter; - } - - @Override - public int LRcount() { - return LRcounter; - } - - @Override - public int RRcount() { - return RRcounter; - } - - @Override - public int RLcount() { - return RLcounter; - } - - @Override - public void fillWithoutRebalance(T[] array) { - quickInsert(array, 0, array.length - 1); - } - - private void quickInsert(T[] array, int leftIndex, int rightIndex) { - if (leftIndex < rightIndex) { - int pivot = partition(array, leftIndex, rightIndex); - insertWithoutRebalance(array[pivot]); - quickInsert(array, leftIndex, pivot - 1); - quickInsert(array, pivot + 1, rightIndex); - } - } - - private int partition(T[] array, int leftIndex, int rightIndex) { - int i = leftIndex + 1; - int f = rightIndex; - while (i <= f) { - if (array[i].compareTo(array[leftIndex]) <= 0) { - i++; - } else if (array[f].compareTo(array[leftIndex]) > 0) { - f--; - } else { - swap(array, i, f); - i++; - f--; - } - } - swap(array, leftIndex, f); - return f; - } - - private void insertWithoutRebalance(T element) { - insertWithNodeWithoutRebalance(getRoot(), element); - } - - @SuppressWarnings("unchecked") - private void insertWithNodeWithoutRebalance(BSTNode node, T element) { - if (node.isEmpty()) { - node.setData(element); - node.setLeft(new BSTNode.Builder().data(null).parent(node).build()); - node.setRight(new BSTNode.Builder().data(null).parent(node).build()); - } else { - if ((element.compareTo(node.getData()) < 0)) { - insertWithNodeWithoutRebalance((BSTNode) node.getLeft(), element); - } else if ((element.compareTo(node.getData()) > 0)) { - insertWithNodeWithoutRebalance((BSTNode) node.getRight(), element); - } - - } - - } - - private void swap(T[] array, int i, int j) { - if (array == null) - throw new IllegalArgumentException(); - - T temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } - -} +package adt.avltree; + +import adt.bst.BSTNode; + +public class AVLCountAndFillImpl> extends AVLTreeImpl implements AVLCountAndFill { + + private int LLcounter; + private int LRcounter; + private int RRcounter; + private int RLcounter; + + public AVLCountAndFillImpl() { + + } + + @Override + protected void rebalance(BSTNode node) { + int balance = calculateBalance(node); + if (balance > 1) { + if (calculateBalance((BSTNode) node.getLeft()) < 0) { + adt.bt.Util.leftRotation((BSTNode) node.getLeft()); + LRcounter++; + } else { + LLcounter++; + } + if (node == getRoot()) { + setRoot((BSTNode) node.getLeft()); + } + adt.bt.Util.rightRotation(node); + } else if (balance < -1) { + if (calculateBalance((BSTNode) node.getRight()) > 0) { + adt.bt.Util.rightRotation((BSTNode) node.getRight()); + RLcounter++; + } else { + RRcounter++; + } + if (node == getRoot()) { + setRoot((BSTNode) node.getRight()); + } + adt.bt.Util.leftRotation(node); + } + } + + @Override + public int LLcount() { + return LLcounter; + } + + @Override + public int LRcount() { + return LRcounter; + } + + @Override + public int RRcount() { + return RRcounter; + } + + @Override + public int RLcount() { + return RLcounter; + } + + @Override + public void fillWithoutRebalance(T[] array) { + quickInsert(array, 0, array.length - 1); + } + + private void quickInsert(T[] array, int leftIndex, int rightIndex) { + if (leftIndex < rightIndex) { + int pivot = partition(array, leftIndex, rightIndex); + insertWithoutRebalance(array[pivot]); + quickInsert(array, leftIndex, pivot - 1); + quickInsert(array, pivot + 1, rightIndex); + } + } + + private int partition(T[] array, int leftIndex, int rightIndex) { + int i = leftIndex + 1; + int f = rightIndex; + while (i <= f) { + if (array[i].compareTo(array[leftIndex]) <= 0) { + i++; + } else if (array[f].compareTo(array[leftIndex]) > 0) { + f--; + } else { + swap(array, i, f); + i++; + f--; + } + } + swap(array, leftIndex, f); + return f; + } + + private void insertWithoutRebalance(T element) { + insertWithNodeWithoutRebalance(getRoot(), element); + } + + @SuppressWarnings("unchecked") + private void insertWithNodeWithoutRebalance(BSTNode node, T element) { + if (node.isEmpty()) { + node.setData(element); + node.setLeft(new BSTNode.Builder().data(null).parent(node).build()); + node.setRight(new BSTNode.Builder().data(null).parent(node).build()); + } else { + if ((element.compareTo(node.getData()) < 0)) { + insertWithNodeWithoutRebalance((BSTNode) node.getLeft(), element); + } else if ((element.compareTo(node.getData()) > 0)) { + insertWithNodeWithoutRebalance((BSTNode) node.getRight(), element); + } + + } + + } + + private void swap(T[] array, int i, int j) { + if (array == null) + throw new IllegalArgumentException(); + + T temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + +} diff --git a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/avltree/AVLTree.java b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/avltree/AVLTree.java index 4d4bc4e8f..ea4c58d04 100644 --- a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/avltree/AVLTree.java +++ b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/avltree/AVLTree.java @@ -1,7 +1,7 @@ -package adt.avltree; - -import adt.bst.BST; - -public interface AVLTree> extends BST { - -} +package adt.avltree; + +import adt.bst.BST; + +public interface AVLTree> extends BST { + +} diff --git a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/avltree/AVLTreeImpl.java b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/avltree/AVLTreeImpl.java index 830ae0072..4124f95b4 100644 --- a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/avltree/AVLTreeImpl.java +++ b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/avltree/AVLTreeImpl.java @@ -1,128 +1,128 @@ -package adt.avltree; - -import adt.bst.BSTImpl; -import adt.bst.BSTNode; - -/** - * - * Performs consistency validations within a AVL Tree instance - * - * @author Claudio Campelo - * - * @param - */ -public class AVLTreeImpl> extends BSTImpl implements AVLTree { - - // TODO Do not forget: you must override the methods insert and remove - // conveniently. - - @Override - @SuppressWarnings("unchecked") - protected void insertWithNode(BSTNode node, T element) { - if (node.isEmpty()) { - node.setData(element); - node.setLeft(new BSTNode.Builder().data(null).parent(node).build()); - node.setRight(new BSTNode.Builder().data(null).parent(node).build()); - } else { - if ((element.compareTo(node.getData()) < 0)) { - insertWithNode((BSTNode) node.getLeft(), element); - } else if ((element.compareTo(node.getData()) > 0)) { - insertWithNode((BSTNode) node.getRight(), element); - } - rebalance(node); - } - } - - @Override - protected void removeRecursive(BSTNode node) { - if (!node.isEmpty()) { - if (node.isLeaf()) { - node.setData(null); - node.setLeft(null); - node.setRight(null); - rebalanceUp(node); - } else if (hasOneChild(node)) { - if (!(node.equals(getRoot()) && node.getParent() == null)) { - if (node.getParent().getLeft().equals(node)) { - if (!node.getLeft().isEmpty()) { - - node.getParent().setLeft(node.getLeft()); - node.getLeft().setParent(node.getParent()); - - } else { - node.getParent().setLeft(node.getRight()); - node.getRight().setParent(node.getParent()); - } - - } else { - if (!node.getLeft().isEmpty()) { - - node.getParent().setRight(node.getLeft()); - node.getLeft().setParent(node.getParent()); - } else { - - node.getParent().setRight(node.getRight()); - node.getRight().setParent(node.getParent()); - - } - } - } else { - if (getRoot().getLeft().isEmpty()) { - setRoot((BSTNode) getRoot().getRight()); - getRoot().setParent(null); - } else if (getRoot().getRight().isEmpty()) { - setRoot((BSTNode) getRoot().getLeft()); - getRoot().setParent(null); - } - } - rebalanceUp(node); - } else { - BSTNode sucessor = sucessor(node.getData()); - node.setData(sucessor.getData()); - removeRecursive(sucessor); - } - } - } - - // AUXILIARY - public int calculateBalance(BSTNode node) { - int result = 0; - if (!node.isEmpty()) { - result = getHeight((BSTNode) node.getLeft()) - getHeight((BSTNode) node.getRight()); - } - return result; - } - - // AUXILIARY - protected void rebalance(BSTNode node) { - int balance = calculateBalance(node); - if (balance > 1) { - if (calculateBalance((BSTNode) node.getLeft()) < 0) { - adt.bt.Util.leftRotation((BSTNode) node.getLeft()); - } - if (node == getRoot()) { - setRoot((BSTNode) node.getLeft()); - } - adt.bt.Util.rightRotation(node); - } else if (balance < -1) { - if (calculateBalance((BSTNode) node.getRight()) > 0) { - adt.bt.Util.rightRotation((BSTNode) node.getRight()); - } - if (node == getRoot()) { - setRoot((BSTNode) node.getRight()); - } - adt.bt.Util.leftRotation(node); - } - - } - - // AUXILIARY - protected void rebalanceUp(BSTNode node) { - BSTNode parent = (BSTNode) node.getParent(); - if (parent != null) { - rebalance(parent); - rebalanceUp(parent); - } - - } -} +package adt.avltree; + +import adt.bst.BSTImpl; +import adt.bst.BSTNode; + +/** + * + * Performs consistency validations within a AVL Tree instance + * + * @author Claudio Campelo + * + * @param + */ +public class AVLTreeImpl> extends BSTImpl implements AVLTree { + + // TODO Do not forget: you must override the methods insert and remove + // conveniently. + + @Override + @SuppressWarnings("unchecked") + protected void insertWithNode(BSTNode node, T element) { + if (node.isEmpty()) { + node.setData(element); + node.setLeft(new BSTNode.Builder().data(null).parent(node).build()); + node.setRight(new BSTNode.Builder().data(null).parent(node).build()); + } else { + if ((element.compareTo(node.getData()) < 0)) { + insertWithNode((BSTNode) node.getLeft(), element); + } else if ((element.compareTo(node.getData()) > 0)) { + insertWithNode((BSTNode) node.getRight(), element); + } + rebalance(node); + } + } + + @Override + protected void removeRecursive(BSTNode node) { + if (!node.isEmpty()) { + if (node.isLeaf()) { + node.setData(null); + node.setLeft(null); + node.setRight(null); + rebalanceUp(node); + } else if (hasOneChild(node)) { + if (!(node.equals(getRoot()) && node.getParent() == null)) { + if (node.getParent().getLeft().equals(node)) { + if (!node.getLeft().isEmpty()) { + + node.getParent().setLeft(node.getLeft()); + node.getLeft().setParent(node.getParent()); + + } else { + node.getParent().setLeft(node.getRight()); + node.getRight().setParent(node.getParent()); + } + + } else { + if (!node.getLeft().isEmpty()) { + + node.getParent().setRight(node.getLeft()); + node.getLeft().setParent(node.getParent()); + } else { + + node.getParent().setRight(node.getRight()); + node.getRight().setParent(node.getParent()); + + } + } + } else { + if (getRoot().getLeft().isEmpty()) { + setRoot((BSTNode) getRoot().getRight()); + getRoot().setParent(null); + } else if (getRoot().getRight().isEmpty()) { + setRoot((BSTNode) getRoot().getLeft()); + getRoot().setParent(null); + } + } + rebalanceUp(node); + } else { + BSTNode sucessor = sucessor(node.getData()); + node.setData(sucessor.getData()); + removeRecursive(sucessor); + } + } + } + + // AUXILIARY + public int calculateBalance(BSTNode node) { + int result = 0; + if (!node.isEmpty()) { + result = getHeight((BSTNode) node.getLeft()) - getHeight((BSTNode) node.getRight()); + } + return result; + } + + // AUXILIARY + protected void rebalance(BSTNode node) { + int balance = calculateBalance(node); + if (balance > 1) { + if (calculateBalance((BSTNode) node.getLeft()) < 0) { + adt.bt.Util.leftRotation((BSTNode) node.getLeft()); + } + if (node == getRoot()) { + setRoot((BSTNode) node.getLeft()); + } + adt.bt.Util.rightRotation(node); + } else if (balance < -1) { + if (calculateBalance((BSTNode) node.getRight()) > 0) { + adt.bt.Util.rightRotation((BSTNode) node.getRight()); + } + if (node == getRoot()) { + setRoot((BSTNode) node.getRight()); + } + adt.bt.Util.leftRotation(node); + } + + } + + // AUXILIARY + protected void rebalanceUp(BSTNode node) { + BSTNode parent = (BSTNode) node.getParent(); + if (parent != null) { + rebalance(parent); + rebalanceUp(parent); + } + + } +} diff --git a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bst/BST.java b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bst/BST.java index e2006ff32..1a0b6c375 100644 --- a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bst/BST.java +++ b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bst/BST.java @@ -1,34 +1,34 @@ -package adt.bst; - -import adt.bt.BT; - -/** - * The interface of a binary search tree (BST). - */ -public interface BST> extends BT { - - /** - * Returns the node containing the greatest element in a BST. If the tree is - * empty the method returns null. - */ - public BSTNode maximum(); - - /** - * Returns the node containing the lowest element in a BST. If the tree is - * empty the method returns null. - */ - public BSTNode minimum(); - - /** - * Returns a node containing the successor of the given element in a BST or - * null if it does not exist. - */ - public BSTNode sucessor(T element); - - /** - * Returns a node containing the predecessor of the given element in a BST - * or null if it does not exist. - */ - public BSTNode predecessor(T element); - -} +package adt.bst; + +import adt.bt.BT; + +/** + * The interface of a binary search tree (BST). + */ +public interface BST> extends BT { + + /** + * Returns the node containing the greatest element in a BST. If the tree is + * empty the method returns null. + */ + public BSTNode maximum(); + + /** + * Returns the node containing the lowest element in a BST. If the tree is + * empty the method returns null. + */ + public BSTNode minimum(); + + /** + * Returns a node containing the successor of the given element in a BST or + * null if it does not exist. + */ + public BSTNode sucessor(T element); + + /** + * Returns a node containing the predecessor of the given element in a BST + * or null if it does not exist. + */ + public BSTNode predecessor(T element); + +} diff --git a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bst/BSTImpl.java b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bst/BSTImpl.java index e780b26e7..f5bfc4e18 100644 --- a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bst/BSTImpl.java +++ b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bst/BSTImpl.java @@ -1,370 +1,370 @@ -package adt.bst; - -import java.util.LinkedList; -import java.util.List; -import java.util.Stack; - -public class BSTImpl> implements BST { - - protected BSTNode node; - - public BSTImpl() { - node = new BSTNode(); - } - - public BSTNode getRoot() { - return this.node; - } - - protected void setRoot(BSTNode node) { - this.node = node; - } - - @Override - public boolean isEmpty() { - return node.isEmpty(); - } - - @Override - public int height() { - return getHeight(getRoot()); - } - - protected int getHeight(BSTNode node) { - int height = -1; - if (!node.isEmpty()) { - int heightLeft = getHeight((BSTNode) node.getLeft()); - int heightRight = getHeight((BSTNode) node.getRight()); - height = 1 + longer(heightLeft, heightRight); - } - return height; - - } - - private int longer(int heightLeft, int heightRight) { - int result = heightLeft; - if (heightRight > heightLeft) { - result = heightRight; - } - return result; - } - - @Override - public BSTNode search(T element) { - return binarySearch(getRoot(), element); - } - - @SuppressWarnings("unchecked") - private BSTNode binarySearch(BSTNode node, T element) { - BSTNode result = new BSTNode.Builder().data(null).left(null).right(null).parent(null).build(); - if (node.isEmpty() || node.getData().equals(element)) { - result = node; - } else if (node.getData().compareTo(element) > 0) { - result = binarySearch((BSTNode) node.getLeft(), element); - } else { - result = binarySearch((BSTNode) node.getRight(), element); - } - return result; - } - - @Override - public void insert(T element) { - insertWithNode(getRoot(), element); - } - - @SuppressWarnings("unchecked") - protected void insertWithNode(BSTNode node, T element) { - if (node.isEmpty()) { - node.setData(element); - node.setLeft(new BSTNode.Builder().data(null).parent(node).build()); - node.setRight(new BSTNode.Builder().data(null).parent(node).build()); - } else { - if ((element.compareTo(node.getData()) < 0)) { - insertWithNode((BSTNode) node.getLeft(), element); - } else if ((element.compareTo(node.getData()) > 0)) { - insertWithNode((BSTNode) node.getRight(), element); - } - - } - - } - - @Override - public BSTNode maximum() { - BSTNode max = null; - if (!(getRoot().isEmpty())) { - max = maximumWithNode(getRoot()); - } - return max; - } - - private BSTNode maximumWithNode(BSTNode node) { - BSTNode max = node; - if (!(node.getRight().isEmpty())) { - max = maximumWithNode((BSTNode) node.getRight()); - } - return max; - } - - @Override - public BSTNode minimum() { - BSTNode min = null; - if (!(getRoot().isEmpty())) { - min = minimumWithNode(getRoot()); - } - return min; - } - - private BSTNode minimumWithNode(BSTNode node) { - BSTNode min = node; - if (!(node.getLeft().isEmpty())) { - min = minimumWithNode((BSTNode) node.getLeft()); - } - return min; - } - - @Override - public BSTNode sucessor(T element) { - BSTNode result = null; - BSTNode node = search(element); - if (!(node.isEmpty())) { - if (!(node.getRight().isEmpty())) { - result = minimumWithNode((BSTNode) node.getRight()); - } else { - result = firstDaddyRight(node); - } - } - return result; - - } - - private BSTNode firstDaddyRight(BSTNode node) { - BSTNode result = (BSTNode) node.getParent(); - if (result != null && node.equals(result.getRight())) { - result = firstDaddyRight(result); - } - return result; - } - - @Override - public BSTNode predecessor(T element) { - BSTNode result = null; - BSTNode node = search(element); - if (!(node.isEmpty())) { - if (!(node.getLeft().isEmpty())) { - result = maximumWithNode((BSTNode) node.getLeft()); - } else { - result = firstDaddyLeft(node); - } - } - return result; - } - - private BSTNode firstDaddyLeft(BSTNode node) { - BSTNode result = (BSTNode) node.getParent(); - if (result != null && node.equals(result.getLeft())) { - result = firstDaddyLeft(result); - } - return result; - } - - @Override - public void remove(T element) { - if (element != null) { - BSTNode node = search(element); - removeRecursive(node); - } - } - - protected void removeRecursive(BSTNode node) { - if (!node.isEmpty()) { - if (node.isLeaf()) { - node.setData(null); - node.setLeft(null); - node.setRight(null); - } else if (hasOneChild(node)) { - if (!(node.equals(getRoot()) && node.getParent() == null)) { - if (node.getParent().getLeft().equals(node)) { - if (!node.getLeft().isEmpty()) { - - node.getParent().setLeft(node.getLeft()); - node.getLeft().setParent(node.getParent()); - - } else { - node.getParent().setLeft(node.getRight()); - node.getRight().setParent(node.getParent()); - } - - } else { - if (!node.getLeft().isEmpty()) { - - node.getParent().setRight(node.getLeft()); - node.getLeft().setParent(node.getParent()); - } else { - - node.getParent().setRight(node.getRight()); - node.getRight().setParent(node.getParent()); - - } - } - } else { - if (getRoot().getLeft().isEmpty()) { - setRoot((BSTNode) getRoot().getRight()); - getRoot().setParent(null); - } else if (getRoot().getRight().isEmpty()) { - setRoot((BSTNode) getRoot().getLeft()); - getRoot().setParent(null); - } - } - - } else { - BSTNode sucessor = sucessor(node.getData()); - node.setData(sucessor.getData()); - removeRecursive(sucessor); - } - } - } - - protected boolean hasOneChild(BSTNode node) { - return !(node.getLeft().isEmpty() && node.getRight().isEmpty()) - && (node.getLeft().isEmpty() || node.getRight().isEmpty()); - } - - @Override - public T[] preOrder() { - T[] array = adt.bt.Util.makeArrayOfComparable(size()); - preOrderRecursive(getRoot(), array); - return array; - } - - private void preOrderRecursive(BSTNode node, T[] array) { - if (!node.isEmpty()) { - add(array, node.getData()); - preOrderRecursive((BSTNode) node.getLeft(), array); - preOrderRecursive((BSTNode) node.getRight(), array); - } - } - - private void add(T[] array, T data) { - int i = 0; - while (i < array.length) { - if (array[i] == null) { - array[i] = data; - break; - } else { - i++; - } - } - } - - @Override - public T[] order() { - T[] array = adt.bt.Util.makeArrayOfComparable(size()); - orderRecursive(getRoot(), array); - return array; - } - - private void orderRecursive(BSTNode node, T[] array) { - if (!node.isEmpty()) { - orderRecursive((BSTNode) node.getLeft(), array); - add(array, node.getData()); - orderRecursive((BSTNode) node.getRight(), array); - } - - } - - @Override - public T[] postOrder() { - T[] array = adt.bt.Util.makeArrayOfComparable(size()); - postOrderRecursive(getRoot(), array); - return array; - } - - private void postOrderRecursive(BSTNode node, T[] array) { - if (!node.isEmpty()) { - postOrderRecursive((BSTNode) node.getLeft(), array); - postOrderRecursive((BSTNode) node.getRight(), array); - add(array, node.getData()); - } - } - - public T[] arrayLevel(int level) { - T[] result = null; - if (level > 0 && level <= getHeight(getRoot())) { - LinkedList list = arrayLevel(getRoot(), new LinkedList(), level); - result = makeArrayFromList(list); - - } - return result; - } - - private LinkedList arrayLevel(BSTNode node, LinkedList list, int level) { - - if (level >= 0 && !node.isEmpty()) { - arrayLevel((BSTNode) node.getLeft(), list, level - 1); - if (level == 0) { - list.add(node.getData()); - } - arrayLevel((BSTNode) node.getRight(), list, level - 1); - } - - return list; - } - - protected T[] makeArrayFromList(List list) { - - int size = list.size(); - T[] array = adt.bt.Util.makeArrayOfComparable(size); - for (int i = 0; i != size; i++) { - array[i] = list.get(i); - } - return array; - } - - public int distance(T value1, T value2) { - int distance = -1; - BSTNode node1 = this.search(value1); - if (!node1.isEmpty()) { - BSTNode node2 = this.search(value2); - if (!node2.isEmpty()) { - Stack> pilha1, pilha2; - pilha1 = toArrayParent(node1); - pilha2 = toArrayParent(node2); - while (!pilha1.isEmpty() && !pilha2.isEmpty() && pilha1.peek().equals(pilha2.peek())) { - pilha1.pop(); - pilha2.pop(); - } - distance = pilha1.size() + pilha2.size(); - } - } - return distance; - } - - private Stack> toArrayParent(BSTNode node) { - Stack> pilha = new Stack>(); - while (node.getParent() != null) { - pilha.push(node); - node = (BSTNode) node.getParent(); - } - return pilha; - } - - /** - * This method is already implemented using recursion. You must understand - * how it work and use similar idea with the other methods. - */ - @Override - public int size() { - return size(node); - } - - private int size(BSTNode node) { - int result = 0; - // base case means doing nothing (return 0) - if (!node.isEmpty()) { // indusctive case - result = 1 + size((BSTNode) node.getLeft()) + size((BSTNode) node.getRight()); - } - return result; - } - -} +package adt.bst; + +import java.util.LinkedList; +import java.util.List; +import java.util.Stack; + +public class BSTImpl> implements BST { + + protected BSTNode node; + + public BSTImpl() { + node = new BSTNode(); + } + + public BSTNode getRoot() { + return this.node; + } + + protected void setRoot(BSTNode node) { + this.node = node; + } + + @Override + public boolean isEmpty() { + return node.isEmpty(); + } + + @Override + public int height() { + return getHeight(getRoot()); + } + + protected int getHeight(BSTNode node) { + int height = -1; + if (!node.isEmpty()) { + int heightLeft = getHeight((BSTNode) node.getLeft()); + int heightRight = getHeight((BSTNode) node.getRight()); + height = 1 + longer(heightLeft, heightRight); + } + return height; + + } + + private int longer(int heightLeft, int heightRight) { + int result = heightLeft; + if (heightRight > heightLeft) { + result = heightRight; + } + return result; + } + + @Override + public BSTNode search(T element) { + return binarySearch(getRoot(), element); + } + + @SuppressWarnings("unchecked") + private BSTNode binarySearch(BSTNode node, T element) { + BSTNode result = new BSTNode.Builder().data(null).left(null).right(null).parent(null).build(); + if (node.isEmpty() || node.getData().equals(element)) { + result = node; + } else if (node.getData().compareTo(element) > 0) { + result = binarySearch((BSTNode) node.getLeft(), element); + } else { + result = binarySearch((BSTNode) node.getRight(), element); + } + return result; + } + + @Override + public void insert(T element) { + insertWithNode(getRoot(), element); + } + + @SuppressWarnings("unchecked") + protected void insertWithNode(BSTNode node, T element) { + if (node.isEmpty()) { + node.setData(element); + node.setLeft(new BSTNode.Builder().data(null).parent(node).build()); + node.setRight(new BSTNode.Builder().data(null).parent(node).build()); + } else { + if ((element.compareTo(node.getData()) < 0)) { + insertWithNode((BSTNode) node.getLeft(), element); + } else if ((element.compareTo(node.getData()) > 0)) { + insertWithNode((BSTNode) node.getRight(), element); + } + + } + + } + + @Override + public BSTNode maximum() { + BSTNode max = null; + if (!(getRoot().isEmpty())) { + max = maximumWithNode(getRoot()); + } + return max; + } + + private BSTNode maximumWithNode(BSTNode node) { + BSTNode max = node; + if (!(node.getRight().isEmpty())) { + max = maximumWithNode((BSTNode) node.getRight()); + } + return max; + } + + @Override + public BSTNode minimum() { + BSTNode min = null; + if (!(getRoot().isEmpty())) { + min = minimumWithNode(getRoot()); + } + return min; + } + + private BSTNode minimumWithNode(BSTNode node) { + BSTNode min = node; + if (!(node.getLeft().isEmpty())) { + min = minimumWithNode((BSTNode) node.getLeft()); + } + return min; + } + + @Override + public BSTNode sucessor(T element) { + BSTNode result = null; + BSTNode node = search(element); + if (!(node.isEmpty())) { + if (!(node.getRight().isEmpty())) { + result = minimumWithNode((BSTNode) node.getRight()); + } else { + result = firstDaddyRight(node); + } + } + return result; + + } + + private BSTNode firstDaddyRight(BSTNode node) { + BSTNode result = (BSTNode) node.getParent(); + if (result != null && node.equals(result.getRight())) { + result = firstDaddyRight(result); + } + return result; + } + + @Override + public BSTNode predecessor(T element) { + BSTNode result = null; + BSTNode node = search(element); + if (!(node.isEmpty())) { + if (!(node.getLeft().isEmpty())) { + result = maximumWithNode((BSTNode) node.getLeft()); + } else { + result = firstDaddyLeft(node); + } + } + return result; + } + + private BSTNode firstDaddyLeft(BSTNode node) { + BSTNode result = (BSTNode) node.getParent(); + if (result != null && node.equals(result.getLeft())) { + result = firstDaddyLeft(result); + } + return result; + } + + @Override + public void remove(T element) { + if (element != null) { + BSTNode node = search(element); + removeRecursive(node); + } + } + + protected void removeRecursive(BSTNode node) { + if (!node.isEmpty()) { + if (node.isLeaf()) { + node.setData(null); + node.setLeft(null); + node.setRight(null); + } else if (hasOneChild(node)) { + if (!(node.equals(getRoot()) && node.getParent() == null)) { + if (node.getParent().getLeft().equals(node)) { + if (!node.getLeft().isEmpty()) { + + node.getParent().setLeft(node.getLeft()); + node.getLeft().setParent(node.getParent()); + + } else { + node.getParent().setLeft(node.getRight()); + node.getRight().setParent(node.getParent()); + } + + } else { + if (!node.getLeft().isEmpty()) { + + node.getParent().setRight(node.getLeft()); + node.getLeft().setParent(node.getParent()); + } else { + + node.getParent().setRight(node.getRight()); + node.getRight().setParent(node.getParent()); + + } + } + } else { + if (getRoot().getLeft().isEmpty()) { + setRoot((BSTNode) getRoot().getRight()); + getRoot().setParent(null); + } else if (getRoot().getRight().isEmpty()) { + setRoot((BSTNode) getRoot().getLeft()); + getRoot().setParent(null); + } + } + + } else { + BSTNode sucessor = sucessor(node.getData()); + node.setData(sucessor.getData()); + removeRecursive(sucessor); + } + } + } + + protected boolean hasOneChild(BSTNode node) { + return !(node.getLeft().isEmpty() && node.getRight().isEmpty()) + && (node.getLeft().isEmpty() || node.getRight().isEmpty()); + } + + @Override + public T[] preOrder() { + T[] array = adt.bt.Util.makeArrayOfComparable(size()); + preOrderRecursive(getRoot(), array); + return array; + } + + private void preOrderRecursive(BSTNode node, T[] array) { + if (!node.isEmpty()) { + add(array, node.getData()); + preOrderRecursive((BSTNode) node.getLeft(), array); + preOrderRecursive((BSTNode) node.getRight(), array); + } + } + + private void add(T[] array, T data) { + int i = 0; + while (i < array.length) { + if (array[i] == null) { + array[i] = data; + break; + } else { + i++; + } + } + } + + @Override + public T[] order() { + T[] array = adt.bt.Util.makeArrayOfComparable(size()); + orderRecursive(getRoot(), array); + return array; + } + + private void orderRecursive(BSTNode node, T[] array) { + if (!node.isEmpty()) { + orderRecursive((BSTNode) node.getLeft(), array); + add(array, node.getData()); + orderRecursive((BSTNode) node.getRight(), array); + } + + } + + @Override + public T[] postOrder() { + T[] array = adt.bt.Util.makeArrayOfComparable(size()); + postOrderRecursive(getRoot(), array); + return array; + } + + private void postOrderRecursive(BSTNode node, T[] array) { + if (!node.isEmpty()) { + postOrderRecursive((BSTNode) node.getLeft(), array); + postOrderRecursive((BSTNode) node.getRight(), array); + add(array, node.getData()); + } + } + + public T[] arrayLevel(int level) { + T[] result = null; + if (level > 0 && level <= getHeight(getRoot())) { + LinkedList list = arrayLevel(getRoot(), new LinkedList(), level); + result = makeArrayFromList(list); + + } + return result; + } + + private LinkedList arrayLevel(BSTNode node, LinkedList list, int level) { + + if (level >= 0 && !node.isEmpty()) { + arrayLevel((BSTNode) node.getLeft(), list, level - 1); + if (level == 0) { + list.add(node.getData()); + } + arrayLevel((BSTNode) node.getRight(), list, level - 1); + } + + return list; + } + + protected T[] makeArrayFromList(List list) { + + int size = list.size(); + T[] array = adt.bt.Util.makeArrayOfComparable(size); + for (int i = 0; i != size; i++) { + array[i] = list.get(i); + } + return array; + } + + public int distance(T value1, T value2) { + int distance = -1; + BSTNode node1 = this.search(value1); + if (!node1.isEmpty()) { + BSTNode node2 = this.search(value2); + if (!node2.isEmpty()) { + Stack> pilha1, pilha2; + pilha1 = toArrayParent(node1); + pilha2 = toArrayParent(node2); + while (!pilha1.isEmpty() && !pilha2.isEmpty() && pilha1.peek().equals(pilha2.peek())) { + pilha1.pop(); + pilha2.pop(); + } + distance = pilha1.size() + pilha2.size(); + } + } + return distance; + } + + private Stack> toArrayParent(BSTNode node) { + Stack> pilha = new Stack>(); + while (node.getParent() != null) { + pilha.push(node); + node = (BSTNode) node.getParent(); + } + return pilha; + } + + /** + * This method is already implemented using recursion. You must understand + * how it work and use similar idea with the other methods. + */ + @Override + public int size() { + return size(node); + } + + private int size(BSTNode node) { + int result = 0; + // base case means doing nothing (return 0) + if (!node.isEmpty()) { // indusctive case + result = 1 + size((BSTNode) node.getLeft()) + size((BSTNode) node.getRight()); + } + return result; + } + +} diff --git a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bst/BSTNode.java b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bst/BSTNode.java index 3ca6f8ecc..b6e9637ae 100644 --- a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bst/BSTNode.java +++ b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bst/BSTNode.java @@ -1,58 +1,58 @@ -package adt.bst; - -import adt.bt.BTNode; - -public class BSTNode> extends BTNode { - - public BSTNode() { - super(); - } - - //código abaixo é um exempo de uso do padrão Builder para construir - //objetos do tipo BSTNode sem usar construtor diretamente. - //o código cliente desse padrao, criando o no vazio seria: - // BSTNode node = (BSTNode) new BSTNode.Builder() - // .data(null) - // .left(null) - // .right(null) - // .parent(null) - // .build(); - - public static class Builder{ - T data; - BTNode left; - BTNode right; - BTNode parent; - - public BSTNode.Builder data(T data){ - this.data = data; - return this; - } - - public BSTNode.Builder left(BTNode left){ - this.left = left; - return this; - } - - public BSTNode.Builder right(BTNode right){ - this.right = right; - return this; - } - - public BSTNode.Builder parent(BTNode parent){ - this.parent = parent; - return this; - } - - public BSTNode build(){ - return new BSTNode(this); - } - } - private BSTNode(BSTNode.Builder builder){ - this.data = builder.data; - this.left = builder.left; - this.right = builder.right; - this.parent = builder.parent; - - } -} +package adt.bst; + +import adt.bt.BTNode; + +public class BSTNode> extends BTNode { + + public BSTNode() { + super(); + } + + //código abaixo é um exempo de uso do padrão Builder para construir + //objetos do tipo BSTNode sem usar construtor diretamente. + //o código cliente desse padrao, criando o no vazio seria: + // BSTNode node = (BSTNode) new BSTNode.Builder() + // .data(null) + // .left(null) + // .right(null) + // .parent(null) + // .build(); + + public static class Builder{ + T data; + BTNode left; + BTNode right; + BTNode parent; + + public BSTNode.Builder data(T data){ + this.data = data; + return this; + } + + public BSTNode.Builder left(BTNode left){ + this.left = left; + return this; + } + + public BSTNode.Builder right(BTNode right){ + this.right = right; + return this; + } + + public BSTNode.Builder parent(BTNode parent){ + this.parent = parent; + return this; + } + + public BSTNode build(){ + return new BSTNode(this); + } + } + private BSTNode(BSTNode.Builder builder){ + this.data = builder.data; + this.left = builder.left; + this.right = builder.right; + this.parent = builder.parent; + + } +} diff --git a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bt/BT.java b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bt/BT.java index 7e0e20008..2ce273363 100644 --- a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bt/BT.java +++ b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bt/BT.java @@ -1,65 +1,65 @@ -package adt.bt; - -/** - * The interface of a generic binary tree (BT). It has nodes containing elements - * of type T. - */ -public interface BT { - /** - * Returns the root of the tree. - * - * @return - */ - public BTNode getRoot(); - - /** - * Say if a BT is empty (NIL). - */ - public boolean isEmpty(); - - /** - * The height of a BT. An empty BT has height -1 (there is no root element). - * In non-empty BT the height is given by 1 + (the highest height of its - * sub-trees). - */ - public int height(); - - /** - * Searches an element in a BT. The search starts at the root node. If the - * key does not exist the methods returns a NIL (empty) node. - */ - public BTNode search(T elem); - - /** - * Inserts an element in a BT. - */ - public void insert(T value); - - /** - * Removes a node from a BT. - */ - public void remove(T key); - - /** - * Returns an array of elements filled according to the pre-order traversing - * in a BT. - */ - public T[] preOrder(); - - /** - * Returns an array of elements filled according to the symmetric order - * traversing in a BT. - */ - public T[] order(); - - /** - * Returns an array of elements filled according to the port-order - * traversing in a BT. - */ - public T[] postOrder(); - - /** - * Returns the number of nodes (not NIL) in a BT. - */ - public int size(); -} +package adt.bt; + +/** + * The interface of a generic binary tree (BT). It has nodes containing elements + * of type T. + */ +public interface BT { + /** + * Returns the root of the tree. + * + * @return + */ + public BTNode getRoot(); + + /** + * Say if a BT is empty (NIL). + */ + public boolean isEmpty(); + + /** + * The height of a BT. An empty BT has height -1 (there is no root element). + * In non-empty BT the height is given by 1 + (the highest height of its + * sub-trees). + */ + public int height(); + + /** + * Searches an element in a BT. The search starts at the root node. If the + * key does not exist the methods returns a NIL (empty) node. + */ + public BTNode search(T elem); + + /** + * Inserts an element in a BT. + */ + public void insert(T value); + + /** + * Removes a node from a BT. + */ + public void remove(T key); + + /** + * Returns an array of elements filled according to the pre-order traversing + * in a BT. + */ + public T[] preOrder(); + + /** + * Returns an array of elements filled according to the symmetric order + * traversing in a BT. + */ + public T[] order(); + + /** + * Returns an array of elements filled according to the port-order + * traversing in a BT. + */ + public T[] postOrder(); + + /** + * Returns the number of nodes (not NIL) in a BT. + */ + public int size(); +} diff --git a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bt/BTNode.java b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bt/BTNode.java index dd86bff2c..c059f8531 100644 --- a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bt/BTNode.java +++ b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bt/BTNode.java @@ -1,86 +1,86 @@ -package adt.bt; - -/** - * The node of a binary tree. Its internal data has type T, which does not need - * to be comparable. - */ -public class BTNode { - protected T data; - protected BTNode left; - protected BTNode right; - protected BTNode parent; - - public BTNode(T data, BTNode left, BTNode right, BTNode parent) { - this.data = data; - this.left = left; - this.right = right; - this.parent = parent; - } - - public BTNode() { - } - - public boolean isEmpty() { - return this.data == null; - } - - public boolean isLeaf() { - return this.data != null && this.left.isEmpty() && this.right.isEmpty(); - } - - @Override - public String toString() { - String resp = "NIL"; - if (!isEmpty()) { - resp = data.toString(); - } - return resp; - } - - @SuppressWarnings("unchecked") - @Override - public boolean equals(Object obj) { - boolean resp = false; - if (obj instanceof BTNode) { - if (!this.isEmpty() && !((BTNode) obj).isEmpty()) { - resp = this.data.equals(((BTNode) obj).data); - } else { - resp = this.isEmpty() && ((BTNode) obj).isEmpty(); - } - - } - return resp; - } - - public T getData() { - return data; - } - - public void setData(T data) { - this.data = data; - } - - public BTNode getLeft() { - return left; - } - - public void setLeft(BTNode left) { - this.left = left; - } - - public BTNode getRight() { - return right; - } - - public void setRight(BTNode right) { - this.right = right; - } - - public BTNode getParent() { - return parent; - } - - public void setParent(BTNode parent) { - this.parent = parent; - } -} +package adt.bt; + +/** + * The node of a binary tree. Its internal data has type T, which does not need + * to be comparable. + */ +public class BTNode { + protected T data; + protected BTNode left; + protected BTNode right; + protected BTNode parent; + + public BTNode(T data, BTNode left, BTNode right, BTNode parent) { + this.data = data; + this.left = left; + this.right = right; + this.parent = parent; + } + + public BTNode() { + } + + public boolean isEmpty() { + return this.data == null; + } + + public boolean isLeaf() { + return this.data != null && this.left.isEmpty() && this.right.isEmpty(); + } + + @Override + public String toString() { + String resp = "NIL"; + if (!isEmpty()) { + resp = data.toString(); + } + return resp; + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(Object obj) { + boolean resp = false; + if (obj instanceof BTNode) { + if (!this.isEmpty() && !((BTNode) obj).isEmpty()) { + resp = this.data.equals(((BTNode) obj).data); + } else { + resp = this.isEmpty() && ((BTNode) obj).isEmpty(); + } + + } + return resp; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public BTNode getLeft() { + return left; + } + + public void setLeft(BTNode left) { + this.left = left; + } + + public BTNode getRight() { + return right; + } + + public void setRight(BTNode right) { + this.right = right; + } + + public BTNode getParent() { + return parent; + } + + public void setParent(BTNode parent) { + this.parent = parent; + } +} diff --git a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bt/Util.java b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bt/Util.java index 6c8253927..064379829 100644 --- a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bt/Util.java +++ b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/main/java/adt/bt/Util.java @@ -1,63 +1,63 @@ -package adt.bt; - -import adt.bst.BSTNode; - -public class Util { - - /** - * A rotacao a esquerda em node deve subir e retornar seu filho a direita - * - * @param node - * @return - */ - public static > BSTNode leftRotation(BSTNode node) { - BSTNode pivot = (BSTNode) node.getRight(); - pivot.setParent(node.getParent()); - if (pivot.getParent() != null) { - if (node.getParent().getLeft().equals(node)) { - pivot.getParent().setLeft(pivot); - } else { - pivot.getParent().setRight(pivot); - } - } - node.setRight(pivot.getLeft()); - node.getRight().setParent(node); - node.setParent(pivot); - pivot.setLeft(node); - pivot.getLeft().setParent(pivot); - node = pivot; - return node; - } - - /** - * A rotacao a direita em node deve subir e retornar seu filho a esquerda - * - * @param node - * @return - */ - public static > BSTNode rightRotation(BSTNode node) { - BSTNode pivot = (BSTNode) node.getLeft(); - pivot.setParent(node.getParent()); - if (pivot.getParent() != null) { - if (node.getParent().getLeft().equals(node)) { - pivot.getParent().setLeft(pivot); - } else { - pivot.getParent().setRight(pivot); - } - } - node.setLeft(pivot.getRight()); - node.getLeft().setParent(node); - node.setParent(pivot); - pivot.setRight(node); - pivot.getRight().setParent(pivot); - node = pivot; - return node; - } - - public static > T[] makeArrayOfComparable(int size) { - @SuppressWarnings("unchecked") - T[] array = (T[]) new Comparable[size]; - return array; - } - -} +package adt.bt; + +import adt.bst.BSTNode; + +public class Util { + + /** + * A rotacao a esquerda em node deve subir e retornar seu filho a direita + * + * @param node + * @return + */ + public static > BSTNode leftRotation(BSTNode node) { + BSTNode pivot = (BSTNode) node.getRight(); + pivot.setParent(node.getParent()); + if (pivot.getParent() != null) { + if (node.getParent().getLeft().equals(node)) { + pivot.getParent().setLeft(pivot); + } else { + pivot.getParent().setRight(pivot); + } + } + node.setRight(pivot.getLeft()); + node.getRight().setParent(node); + node.setParent(pivot); + pivot.setLeft(node); + pivot.getLeft().setParent(pivot); + node = pivot; + return node; + } + + /** + * A rotacao a direita em node deve subir e retornar seu filho a esquerda + * + * @param node + * @return + */ + public static > BSTNode rightRotation(BSTNode node) { + BSTNode pivot = (BSTNode) node.getLeft(); + pivot.setParent(node.getParent()); + if (pivot.getParent() != null) { + if (node.getParent().getLeft().equals(node)) { + pivot.getParent().setLeft(pivot); + } else { + pivot.getParent().setRight(pivot); + } + } + node.setLeft(pivot.getRight()); + node.getLeft().setParent(node); + node.setParent(pivot); + pivot.setRight(node); + pivot.getRight().setParent(pivot); + node = pivot; + return node; + } + + public static > T[] makeArrayOfComparable(int size) { + @SuppressWarnings("unchecked") + T[] array = (T[]) new Comparable[size]; + return array; + } + +} diff --git a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/test/java/adt/avltree/StudentTestAVLCountAndFill.java b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/test/java/adt/avltree/StudentTestAVLCountAndFill.java index 59ad317e6..731e99dd8 100644 --- a/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/test/java/adt/avltree/StudentTestAVLCountAndFill.java +++ b/java/R14-01-Rot-ArvoreAVLCountFill-environment/src/test/java/adt/avltree/StudentTestAVLCountAndFill.java @@ -1,70 +1,70 @@ -package adt.avltree; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; - -public class StudentTestAVLCountAndFill { - - protected AVLCountAndFill tree1; - protected AVLCountAndFill tree2; - protected AVLCountAndFill tree3; - protected static int SIZE = 10; - - @Before - public void setUp() throws Exception { - tree1 = new AVLCountAndFillImpl(); - tree2 = new AVLCountAndFillImpl(); - for (int i = 0; i < SIZE; i++) { - tree1.insert(i); - tree2.insert(SIZE - i); - } - tree3 = new AVLCountAndFillImpl(); - Integer[] data = { 8, 4, 6, 12, 10 }; - for (Integer integer : data) { - tree3.insert(integer); - } - } - - @Test - public void testLLcount() { - assertEquals(0, tree1.LLcount()); - assertEquals(6, tree2.LLcount()); - assertEquals(0, tree3.LLcount()); - } - - @Test - public void testRRcount() { - assertEquals(6, tree1.RRcount()); - assertEquals(0, tree2.RRcount()); - assertEquals(0, tree3.RRcount()); - } - - @Test - public void testLRcount() { - assertEquals(0, tree1.LRcount()); - assertEquals(0, tree2.LRcount()); - assertEquals(1, tree3.LRcount()); - } - - @Test - public void testRLcount() { - assertEquals(0, tree1.RLcount()); - assertEquals(0, tree2.RLcount()); - assertEquals(1, tree3.RLcount()); - } - - - @Test - public void testFillWithoutRebalance() { - tree1 = new AVLCountAndFillImpl(); - Integer[] keys = { 8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15 }; - tree1.fillWithoutRebalance(keys); - assertEquals(0, tree1.LLcount()); - assertEquals(0, tree1.RRcount()); - assertEquals(0, tree1.LRcount()); - assertEquals(0, tree1.RLcount()); - - } -} +package adt.avltree; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +public class StudentTestAVLCountAndFill { + + protected AVLCountAndFill tree1; + protected AVLCountAndFill tree2; + protected AVLCountAndFill tree3; + protected static int SIZE = 10; + + @Before + public void setUp() throws Exception { + tree1 = new AVLCountAndFillImpl(); + tree2 = new AVLCountAndFillImpl(); + for (int i = 0; i < SIZE; i++) { + tree1.insert(i); + tree2.insert(SIZE - i); + } + tree3 = new AVLCountAndFillImpl(); + Integer[] data = { 8, 4, 6, 12, 10 }; + for (Integer integer : data) { + tree3.insert(integer); + } + } + + @Test + public void testLLcount() { + assertEquals(0, tree1.LLcount()); + assertEquals(6, tree2.LLcount()); + assertEquals(0, tree3.LLcount()); + } + + @Test + public void testRRcount() { + assertEquals(6, tree1.RRcount()); + assertEquals(0, tree2.RRcount()); + assertEquals(0, tree3.RRcount()); + } + + @Test + public void testLRcount() { + assertEquals(0, tree1.LRcount()); + assertEquals(0, tree2.LRcount()); + assertEquals(1, tree3.LRcount()); + } + + @Test + public void testRLcount() { + assertEquals(0, tree1.RLcount()); + assertEquals(0, tree2.RLcount()); + assertEquals(1, tree3.RLcount()); + } + + + @Test + public void testFillWithoutRebalance() { + tree1 = new AVLCountAndFillImpl(); + Integer[] keys = { 8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15 }; + tree1.fillWithoutRebalance(keys); + assertEquals(0, tree1.LLcount()); + assertEquals(0, tree1.RRcount()); + assertEquals(0, tree1.LRcount()); + assertEquals(0, tree1.RLcount()); + + } +} diff --git a/java/R14-01-Rot-ArvoreAVLCountFill-environment/target/classes/META-INF/MANIFEST.MF b/java/R14-01-Rot-ArvoreAVLCountFill-environment/target/classes/META-INF/MANIFEST.MF index 6c4b9cc34..a05e7910c 100644 --- a/java/R14-01-Rot-ArvoreAVLCountFill-environment/target/classes/META-INF/MANIFEST.MF +++ b/java/R14-01-Rot-ArvoreAVLCountFill-environment/target/classes/META-INF/MANIFEST.MF @@ -1,5 +1,5 @@ -Manifest-Version: 1.0 -Built-By: amintas -Build-Jdk: 1.8.0_131 -Created-By: Maven Integration for Eclipse - +Manifest-Version: 1.0 +Built-By: amintas +Build-Jdk: 1.8.0_131 +Created-By: Maven Integration for Eclipse + diff --git a/java/R14-01-Rot-ArvoreAVLCountFill-environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml b/java/R14-01-Rot-ArvoreAVLCountFill-environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml index 18ed9c34c..122859bca 100644 --- a/java/R14-01-Rot-ArvoreAVLCountFill-environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml +++ b/java/R14-01-Rot-ArvoreAVLCountFill-environment/target/classes/META-INF/maven/br.edu.ufcg.ccc/submission/pom.xml @@ -1,98 +1,98 @@ - - 4.0.0 - - br.edu.ufcg.ccc - submission - 1.0 - jar - Submissao de roteiro - - - - ufcg-leda - http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda - default - - true - always - - - - - - - junit - junit - 4.12 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - maven-clean-plugin - 3.0.0 - - - auto-clean - build - - clean - - - - - - - org.walkmod - maven-walkmod-plugin - 1.3 - - walkmod.xml - - - - package - - apply - - - false - - - - - - br.edu.ufcg.ccc - leda-compactor-tool - 1.0.0-SNAPSHOT - - - install - - compact - - - - 116110761 - - R14-01 - - 2017.1 - http://150.165.85.29:81/submitAtividade - - - - - - - + + 4.0.0 + + br.edu.ufcg.ccc + submission + 1.0 + jar + Submissao de roteiro + + + + ufcg-leda + http://150.165.85.29:8081/nexus/content/repositories/ufcg-leda + default + + true + always + + + + + + + junit + junit + 4.12 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + maven-clean-plugin + 3.0.0 + + + auto-clean + build + + clean + + + + + + + org.walkmod + maven-walkmod-plugin + 1.3 + + walkmod.xml + + + + package + + apply + + + false + + + + + + br.edu.ufcg.ccc + leda-compactor-tool + 1.0.0-SNAPSHOT + + + install + + compact + + + + 116110761 + + R14-01 + + 2017.1 + http://150.165.85.29:81/submitAtividade + + + + + + + diff --git a/java/R14-01-Rot-ArvoreAVLCountFill-environment/walkmod.xml b/java/R14-01-Rot-ArvoreAVLCountFill-environment/walkmod.xml index d391a36b4..85902bfec 100644 --- a/java/R14-01-Rot-ArvoreAVLCountFill-environment/walkmod.xml +++ b/java/R14-01-Rot-ArvoreAVLCountFill-environment/walkmod.xml @@ -1,4 +1,4 @@ - - - + + + \ No newline at end of file diff --git a/java/algorithms/pancake.java b/java/algorithms/pancake.java index a008208e4..19af5d300 100644 --- a/java/algorithms/pancake.java +++ b/java/algorithms/pancake.java @@ -1,89 +1,89 @@ - -// Java program to -// sort array using -// pancake sort -import java.io.*; - -class PancakeSort { - - /* Reverses arr[0..i] */ - static void flip(int arr[], int i) - { - int temp, start = 0; - while (start < i) - { - temp = arr[start]; - arr[start] = arr[i]; - arr[i] = temp; - start++; - i--; - } - } - - // Returns index of the - // maximum element in - // arr[0..n-1] - static int findMax(int arr[], int n) - { - int mi, i; - for (mi = 0, i = 0; i < n; ++i) - if (arr[i] > arr[mi]) - mi = i; - return mi; - } - - // The main function that - // sorts given array using - // flip operations - static int pancakeSort(int arr[], int n) - { - // Start from the complete - // array and one by one - // reduce current size by one - for (int curr_size = n; curr_size > 1; --curr_size) - { - // Find index of the - // maximum element in - // arr[0..curr_size-1] - int mi = findMax(arr, curr_size); - - // Move the maximum element - // to end of current array - // if it's not already at - // the end - if (mi != curr_size-1) - { - // To move at the end, - // first move maximum - // number to beginning - flip(arr, mi); - - // Now move the maximum - // number to end by - // reversing current array - flip(arr, curr_size-1); - } - } - return 0; - } - - /* Utility function to print array arr[] */ - static void printArray(int arr[], int arr_size) - { - for (int i = 0; i < arr_size; i++) - System.out.print(arr[i] + " "); - System.out.println(""); - } - - /* Driver function to check for above functions*/ - public static void main (String[] args) - { - int arr[] = {23, 10, 20, 11, 12, 6, 7}; - int n = arr.length; - - pancakeSort(arr, n); - - System.out.println("Sorted Array: "); - printArray(arr, n); - } + +// Java program to +// sort array using +// pancake sort +import java.io.*; + +class PancakeSort { + + /* Reverses arr[0..i] */ + static void flip(int arr[], int i) + { + int temp, start = 0; + while (start < i) + { + temp = arr[start]; + arr[start] = arr[i]; + arr[i] = temp; + start++; + i--; + } + } + + // Returns index of the + // maximum element in + // arr[0..n-1] + static int findMax(int arr[], int n) + { + int mi, i; + for (mi = 0, i = 0; i < n; ++i) + if (arr[i] > arr[mi]) + mi = i; + return mi; + } + + // The main function that + // sorts given array using + // flip operations + static int pancakeSort(int arr[], int n) + { + // Start from the complete + // array and one by one + // reduce current size by one + for (int curr_size = n; curr_size > 1; --curr_size) + { + // Find index of the + // maximum element in + // arr[0..curr_size-1] + int mi = findMax(arr, curr_size); + + // Move the maximum element + // to end of current array + // if it's not already at + // the end + if (mi != curr_size-1) + { + // To move at the end, + // first move maximum + // number to beginning + flip(arr, mi); + + // Now move the maximum + // number to end by + // reversing current array + flip(arr, curr_size-1); + } + } + return 0; + } + + /* Utility function to print array arr[] */ + static void printArray(int arr[], int arr_size) + { + for (int i = 0; i < arr_size; i++) + System.out.print(arr[i] + " "); + System.out.println(""); + } + + /* Driver function to check for above functions*/ + public static void main (String[] args) + { + int arr[] = {23, 10, 20, 11, 12, 6, 7}; + int n = arr.length; + + pancakeSort(arr, n); + + System.out.println("Sorted Array: "); + printArray(arr, n); + } } \ No newline at end of file diff --git a/java/algorithms/primsminimumspanningtree.java b/java/algorithms/primsminimumspanningtree.java index 716b264ed..31f8e3fe4 100644 --- a/java/algorithms/primsminimumspanningtree.java +++ b/java/algorithms/primsminimumspanningtree.java @@ -1,115 +1,115 @@ -// A Java program for Prim's Minimum Spanning Tree (MST) algorithm. -// The program is for adjacency matrix representation of the graph - -import java.util.*; -import java.lang.*; -import java.io.*; - -class MST -{ - // Number of vertices in the graph - private static final int V=5; - - // A utility function to find the vertex with minimum key - // value, from the set of vertices not yet included in MST - int minKey(int key[], Boolean mstSet[]) - { - // Initialize min value - int min = Integer.MAX_VALUE, min_index=-1; - - for (int v = 0; v < V; v++) - if (mstSet[v] == false && key[v] < min) - { - min = key[v]; - min_index = v; - } - - return min_index; - } - - // A utility function to print the constructed MST stored in - // parent[] - void printMST(int parent[], int n, int graph[][]) - { - System.out.println("Edge \tWeight"); - for (int i = 1; i < V; i++) - System.out.println(parent[i]+" - "+ i+"\t"+ - graph[i][parent[i]]); - } - - // Function to construct and print MST for a graph represented - // using adjacency matrix representation - void primMST(int graph[][]) - { - // Array to store constructed MST - int parent[] = new int[V]; - - // Key values used to pick minimum weight edge in cut - int key[] = new int [V]; - - // To represent set of vertices not yet included in MST - Boolean mstSet[] = new Boolean[V]; - - // Initialize all keys as INFINITE - for (int i = 0; i < V; i++) - { - key[i] = Integer.MAX_VALUE; - mstSet[i] = false; - } - - // Always include first 1st vertex in MST. - key[0] = 0; // Make key 0 so that this vertex is - // picked as first vertex - parent[0] = -1; // First node is always root of MST - - // The MST will have V vertices - for (int count = 0; count < V-1; count++) - { - // Pick thd minimum key vertex from the set of vertices - // not yet included in MST - int u = minKey(key, mstSet); - - // Add the picked vertex to the MST Set - mstSet[u] = true; - - // Update key value and parent index of the adjacent - // vertices of the picked vertex. Consider only those - // vertices which are not yet included in MST - for (int v = 0; v < V; v++) - - // graph[u][v] is non zero only for adjacent vertices of m - // mstSet[v] is false for vertices not yet included in MST - // Update the key only if graph[u][v] is smaller than key[v] - if (graph[u][v]!=0 && mstSet[v] == false && - graph[u][v] < key[v]) - { - parent[v] = u; - key[v] = graph[u][v]; - } - } - - // print the constructed MST - printMST(parent, V, graph); - } - - public static void main (String[] args) - { - /* Let us create the following graph - 2 3 - (0)--(1)--(2) - | / \ | - 6| 8/ \5 |7 - | / \ | - (3)-------(4) - 9 */ - MST t = new MST(); - int graph[][] = new int[][] {{0, 2, 0, 6, 0}, - {2, 0, 3, 8, 5}, - {0, 3, 0, 0, 7}, - {6, 8, 0, 0, 9}, - {0, 5, 7, 9, 0}}; - - // Print the solution - t.primMST(graph); - } +// A Java program for Prim's Minimum Spanning Tree (MST) algorithm. +// The program is for adjacency matrix representation of the graph + +import java.util.*; +import java.lang.*; +import java.io.*; + +class MST +{ + // Number of vertices in the graph + private static final int V=5; + + // A utility function to find the vertex with minimum key + // value, from the set of vertices not yet included in MST + int minKey(int key[], Boolean mstSet[]) + { + // Initialize min value + int min = Integer.MAX_VALUE, min_index=-1; + + for (int v = 0; v < V; v++) + if (mstSet[v] == false && key[v] < min) + { + min = key[v]; + min_index = v; + } + + return min_index; + } + + // A utility function to print the constructed MST stored in + // parent[] + void printMST(int parent[], int n, int graph[][]) + { + System.out.println("Edge \tWeight"); + for (int i = 1; i < V; i++) + System.out.println(parent[i]+" - "+ i+"\t"+ + graph[i][parent[i]]); + } + + // Function to construct and print MST for a graph represented + // using adjacency matrix representation + void primMST(int graph[][]) + { + // Array to store constructed MST + int parent[] = new int[V]; + + // Key values used to pick minimum weight edge in cut + int key[] = new int [V]; + + // To represent set of vertices not yet included in MST + Boolean mstSet[] = new Boolean[V]; + + // Initialize all keys as INFINITE + for (int i = 0; i < V; i++) + { + key[i] = Integer.MAX_VALUE; + mstSet[i] = false; + } + + // Always include first 1st vertex in MST. + key[0] = 0; // Make key 0 so that this vertex is + // picked as first vertex + parent[0] = -1; // First node is always root of MST + + // The MST will have V vertices + for (int count = 0; count < V-1; count++) + { + // Pick thd minimum key vertex from the set of vertices + // not yet included in MST + int u = minKey(key, mstSet); + + // Add the picked vertex to the MST Set + mstSet[u] = true; + + // Update key value and parent index of the adjacent + // vertices of the picked vertex. Consider only those + // vertices which are not yet included in MST + for (int v = 0; v < V; v++) + + // graph[u][v] is non zero only for adjacent vertices of m + // mstSet[v] is false for vertices not yet included in MST + // Update the key only if graph[u][v] is smaller than key[v] + if (graph[u][v]!=0 && mstSet[v] == false && + graph[u][v] < key[v]) + { + parent[v] = u; + key[v] = graph[u][v]; + } + } + + // print the constructed MST + printMST(parent, V, graph); + } + + public static void main (String[] args) + { + /* Let us create the following graph + 2 3 + (0)--(1)--(2) + | / \ | + 6| 8/ \5 |7 + | / \ | + (3)-------(4) + 9 */ + MST t = new MST(); + int graph[][] = new int[][] {{0, 2, 0, 6, 0}, + {2, 0, 3, 8, 5}, + {0, 3, 0, 0, 7}, + {6, 8, 0, 0, 9}, + {0, 5, 7, 9, 0}}; + + // Print the solution + t.primMST(graph); + } } \ No newline at end of file diff --git a/java/ds/BinarySearchTree/BST.java b/java/ds/BinarySearchTree/BST.java old mode 100755 new mode 100644 index e0e471698..0f1ad199f --- a/java/ds/BinarySearchTree/BST.java +++ b/java/ds/BinarySearchTree/BST.java @@ -1,283 +1,283 @@ -package L21_March11; - - -public class BST { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BST(int[] in) { - this.root = construct(in, 0, in.length - 1); - } - - private Node construct(int[] in, int lo, int hi) { - - if (lo > hi) - return null; - - int mid = (lo + hi) / 2; - - Node nn = new Node(); - nn.data = in[mid]; - this.size++; - - nn.left = construct(in, lo, mid - 1); - nn.right = construct(in, mid + 1, hi); - - return nn; - } - - public void display() { - System.out.println("---------------"); - display(this.root); - System.out.println("---------------"); - } - - private void display(Node node) { - - if (node == null) - return; - - // self work - String str = ""; - - if (node.left == null) { - str += "."; - } else { - str += node.left.data; - } - - str += " => " + node.data + " <= "; - - if (node.right == null) { - str += "."; - } else { - str += node.right.data; - } - - System.out.println(str); - - display(node.left); - display(node.right); - } - - public int size() { - return this.size; - } - - public int size2() { - return size2(this.root); - } - - private int size2(Node node) { - - if (node == null) - return 0; - - int ls = size2(node.left); - int rs = size2(node.right); - - return ls + rs + 1; - } - - public int max() { - return max(this.root); - } - - private int max(Node node) { - - if (node.right == null) { - return node.data; - } else { - return max(node.right); - } - - } - - public int height() { - return height(this.root); - } - - private int height(Node node) { - - if (node == null) - return -1; - - int lh = height(node.left); - int rh = height(node.right); - - return Math.max(lh, rh) + 1; - } - - public boolean find(int item) { - return find(this.root, item); - } - - private boolean find(Node node, int item) { - - if (node == null) - return false; - - if (item == node.data) { - return true; - } else if (item < node.data) { - return find(node.left, item); - } else { - return find(node.right, item); - } - } - - public void printInRange(int lower, int upper) { - - printInRange(this.root, lower, upper); - } - - private void printInRange(Node node, int lower, int upper) { - - if (node == null) { - return; - } - - if (node.data >= lower && node.data <= upper) { - printInRange(node.left, lower, upper); - System.out.println(node.data); - printInRange(node.right, lower, upper); - } else if (node.data > upper) { - printInRange(node.left, lower, upper); - } else { - printInRange(node.right, lower, upper); - } - } - - public void printDec() { - printDec(this.root); - } - - private void printDec(Node node) { - - if (node == null) - return; - - printDec(node.right); - System.out.println(node.data); - printDec(node.left); - } - - private class HeapMover { - int sum; - } - - public void replaceWithSumOfLarger() { - HeapMover hm = new HeapMover(); - replaceWithSumOfLarger(this.root, hm); - } - - private void replaceWithSumOfLarger(Node node, HeapMover hm) { - - if (node == null) - return; - - replaceWithSumOfLarger(node.right, hm); - - int val = node.data; - node.data = hm.sum; - hm.sum += val; - - replaceWithSumOfLarger(node.left, hm); - - } - - public void add(int item) { - add(this.root, null, false, item); - } - - private void add(Node node, Node parent, boolean ilc, int item) { - - if (node == null) { - Node nn = new Node(); - this.size++; - nn.data = item; - - if (ilc) - parent.left = nn; - else - parent.right = nn; - - return; - } - - if (item < node.data) { - add(node.left, node, true, item); - } else if (item > node.data) { - add(node.right, node, false, item); - } - - } - - public void remove(int item) { - remove(this.root, null, false, item); - } - - private void remove(Node node, Node parent, boolean ilc, int item) { - - if (item < node.data) { - remove(node.left, node, true, item); - } else if (item > node.data) { - remove(node.right, node, false, item); - } else { - if (node.left == null && node.right == null) { - if (ilc) - parent.left = null; - else - parent.right = null; - } - - else if (node.left != null && node.right == null) { - if (ilc) - parent.left = node.left; - else - parent.right = node.left; - } - - else if (node.right != null && node.left == null) { - if (ilc) - parent.left = node.right; - else - parent.right = node.right; - } - - else { - - int max = max(node.left); - node.data = max; - - remove(node.left, node, true, max); - } - } - - } - - public void test() { - - Node n1 = new Node(); - n1.data = 10; - Node n2 = new Node(); - n2.data = 20; - Node n3 = new Node(); - n3.data = 30; - n1.left = n2; - n2.left = n3; - n2 = null; - System.out.println(n1.left.data); - System.out.println(n1.left.left.data); - } - - - -} +package L21_March11; + + +public class BST { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BST(int[] in) { + this.root = construct(in, 0, in.length - 1); + } + + private Node construct(int[] in, int lo, int hi) { + + if (lo > hi) + return null; + + int mid = (lo + hi) / 2; + + Node nn = new Node(); + nn.data = in[mid]; + this.size++; + + nn.left = construct(in, lo, mid - 1); + nn.right = construct(in, mid + 1, hi); + + return nn; + } + + public void display() { + System.out.println("---------------"); + display(this.root); + System.out.println("---------------"); + } + + private void display(Node node) { + + if (node == null) + return; + + // self work + String str = ""; + + if (node.left == null) { + str += "."; + } else { + str += node.left.data; + } + + str += " => " + node.data + " <= "; + + if (node.right == null) { + str += "."; + } else { + str += node.right.data; + } + + System.out.println(str); + + display(node.left); + display(node.right); + } + + public int size() { + return this.size; + } + + public int size2() { + return size2(this.root); + } + + private int size2(Node node) { + + if (node == null) + return 0; + + int ls = size2(node.left); + int rs = size2(node.right); + + return ls + rs + 1; + } + + public int max() { + return max(this.root); + } + + private int max(Node node) { + + if (node.right == null) { + return node.data; + } else { + return max(node.right); + } + + } + + public int height() { + return height(this.root); + } + + private int height(Node node) { + + if (node == null) + return -1; + + int lh = height(node.left); + int rh = height(node.right); + + return Math.max(lh, rh) + 1; + } + + public boolean find(int item) { + return find(this.root, item); + } + + private boolean find(Node node, int item) { + + if (node == null) + return false; + + if (item == node.data) { + return true; + } else if (item < node.data) { + return find(node.left, item); + } else { + return find(node.right, item); + } + } + + public void printInRange(int lower, int upper) { + + printInRange(this.root, lower, upper); + } + + private void printInRange(Node node, int lower, int upper) { + + if (node == null) { + return; + } + + if (node.data >= lower && node.data <= upper) { + printInRange(node.left, lower, upper); + System.out.println(node.data); + printInRange(node.right, lower, upper); + } else if (node.data > upper) { + printInRange(node.left, lower, upper); + } else { + printInRange(node.right, lower, upper); + } + } + + public void printDec() { + printDec(this.root); + } + + private void printDec(Node node) { + + if (node == null) + return; + + printDec(node.right); + System.out.println(node.data); + printDec(node.left); + } + + private class HeapMover { + int sum; + } + + public void replaceWithSumOfLarger() { + HeapMover hm = new HeapMover(); + replaceWithSumOfLarger(this.root, hm); + } + + private void replaceWithSumOfLarger(Node node, HeapMover hm) { + + if (node == null) + return; + + replaceWithSumOfLarger(node.right, hm); + + int val = node.data; + node.data = hm.sum; + hm.sum += val; + + replaceWithSumOfLarger(node.left, hm); + + } + + public void add(int item) { + add(this.root, null, false, item); + } + + private void add(Node node, Node parent, boolean ilc, int item) { + + if (node == null) { + Node nn = new Node(); + this.size++; + nn.data = item; + + if (ilc) + parent.left = nn; + else + parent.right = nn; + + return; + } + + if (item < node.data) { + add(node.left, node, true, item); + } else if (item > node.data) { + add(node.right, node, false, item); + } + + } + + public void remove(int item) { + remove(this.root, null, false, item); + } + + private void remove(Node node, Node parent, boolean ilc, int item) { + + if (item < node.data) { + remove(node.left, node, true, item); + } else if (item > node.data) { + remove(node.right, node, false, item); + } else { + if (node.left == null && node.right == null) { + if (ilc) + parent.left = null; + else + parent.right = null; + } + + else if (node.left != null && node.right == null) { + if (ilc) + parent.left = node.left; + else + parent.right = node.left; + } + + else if (node.right != null && node.left == null) { + if (ilc) + parent.left = node.right; + else + parent.right = node.right; + } + + else { + + int max = max(node.left); + node.data = max; + + remove(node.left, node, true, max); + } + } + + } + + public void test() { + + Node n1 = new Node(); + n1.data = 10; + Node n2 = new Node(); + n2.data = 20; + Node n3 = new Node(); + n3.data = 30; + n1.left = n2; + n2.left = n3; + n2 = null; + System.out.println(n1.left.data); + System.out.println(n1.left.left.data); + } + + + +} diff --git a/java/ds/BinarySearchTree/BSTClient.java b/java/ds/BinarySearchTree/BSTClient.java old mode 100755 new mode 100644 index 804ca3f65..0c3f67ae5 --- a/java/ds/BinarySearchTree/BSTClient.java +++ b/java/ds/BinarySearchTree/BSTClient.java @@ -1,35 +1,35 @@ -package L21_March11; - -import java.util.ArrayList; - - - -public class BSTClient { - - public static void main(String[] args) { - - int[] in = { 10, 20, 30, 40, 50, 60, 70, 80 }; - BST bst = new BST(in); - bst.display(); - - // bst.printInRange(40, 75); - // bst.printDec(); - // bst.replaceWithSumOfLarger(); - // bst.display(); - // bst.add(100); - // bst.add(25); - bst.remove(70); - bst.display(); - // ArrayList> list = new ArrayList<>(); - // list.add(new ArrayList<>()) ; - // list.add(new ArrayList<>()) ; - // list.get(0).add(10) ; - // list.get(1).add(10) ; - // - // - // System.out.println(list); - - // bst.test(); - } - -} +package L21_March11; + +import java.util.ArrayList; + + + +public class BSTClient { + + public static void main(String[] args) { + + int[] in = { 10, 20, 30, 40, 50, 60, 70, 80 }; + BST bst = new BST(in); + bst.display(); + + // bst.printInRange(40, 75); + // bst.printDec(); + // bst.replaceWithSumOfLarger(); + // bst.display(); + // bst.add(100); + // bst.add(25); + bst.remove(70); + bst.display(); + // ArrayList> list = new ArrayList<>(); + // list.add(new ArrayList<>()) ; + // list.add(new ArrayList<>()) ; + // list.get(0).add(10) ; + // list.get(1).add(10) ; + // + // + // System.out.println(list); + + // bst.test(); + } + +} diff --git a/java/ds/BinaryTree/BT_CountnonLeafNodes.java b/java/ds/BinaryTree/BT_CountnonLeafNodes.java index f01f5ecac..b1eb33315 100644 --- a/java/ds/BinaryTree/BT_CountnonLeafNodes.java +++ b/java/ds/BinaryTree/BT_CountnonLeafNodes.java @@ -1,119 +1,119 @@ -package Git; - -import java.util.Scanner; - -public class BT_CountnonLeafNodes { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_CountnonLeafNodes bts = new BT_CountnonLeafNodes(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - System.out.println(bt.countNonLeafNodes()); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public int countNonLeafNodes() { - return countNonLeafNodes(this.root); - } - - private int countNonLeafNodes(Node node) { - - if (node == null || node.left == null && node.right == null) { - return 0; - } - - int ln = countNonLeafNodes(node.left); - int rn = countNonLeafNodes(node.right); - - return ln + rn + 1; - - } - - } +package Git; + +import java.util.Scanner; + +public class BT_CountnonLeafNodes { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_CountnonLeafNodes bts = new BT_CountnonLeafNodes(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + System.out.println(bt.countNonLeafNodes()); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public int countNonLeafNodes() { + return countNonLeafNodes(this.root); + } + + private int countNonLeafNodes(Node node) { + + if (node == null || node.left == null && node.right == null) { + return 0; + } + + int ln = countNonLeafNodes(node.left); + int rn = countNonLeafNodes(node.right); + + return ln + rn + 1; + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_DiaPair.java b/java/ds/BinaryTree/BT_DiaPair.java index 45ab4d36f..2bfd76469 100644 --- a/java/ds/BinaryTree/BT_DiaPair.java +++ b/java/ds/BinaryTree/BT_DiaPair.java @@ -1,163 +1,163 @@ -package Git; - -import java.util.Scanner; - -public class BT_DiaPair { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_DiaPair bts = new BT_DiaPair(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - System.out.println(bt.DiaPair()); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - private int height(Node node) { - - if (node == null) { - return -1; - } - - int lh = height(node.left); - int rh = height(node.right); - - return Math.max(lh, rh) + 1; - - } - - private int diameter(Node node) { - - if (node == null) { - return 0; - } - - int ld = diameter(node.left); - int rd = diameter(node.right); - - int sp = height(node.left) + height(node.right) + 2; - - return Math.max(sp, Math.max(ld, rd)); - - } - - private class Pair { - int height = -1; - int diameter = 0; - } - - public int DiaPair() { - Pair pair = DiaPair(this.root); - return pair.diameter; - } - - private Pair DiaPair(Node node) { - - if (node == null) { - Pair br = new Pair(); - return br; - } - - Pair lr = DiaPair(node.left); - Pair rr = DiaPair(node.right); - - Pair mr = new Pair(); - mr.height = Math.max(lr.height, rr.height) + 1; - - int ld = diameter(node.left); - int rd = diameter(node.right); - int sp = lr.height + rr.height + 2; - - mr.diameter = Math.max(sp, Math.max(ld, rd)); - - return mr; - - } - - } +package Git; + +import java.util.Scanner; + +public class BT_DiaPair { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_DiaPair bts = new BT_DiaPair(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + System.out.println(bt.DiaPair()); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + private int height(Node node) { + + if (node == null) { + return -1; + } + + int lh = height(node.left); + int rh = height(node.right); + + return Math.max(lh, rh) + 1; + + } + + private int diameter(Node node) { + + if (node == null) { + return 0; + } + + int ld = diameter(node.left); + int rd = diameter(node.right); + + int sp = height(node.left) + height(node.right) + 2; + + return Math.max(sp, Math.max(ld, rd)); + + } + + private class Pair { + int height = -1; + int diameter = 0; + } + + public int DiaPair() { + Pair pair = DiaPair(this.root); + return pair.diameter; + } + + private Pair DiaPair(Node node) { + + if (node == null) { + Pair br = new Pair(); + return br; + } + + Pair lr = DiaPair(node.left); + Pair rr = DiaPair(node.right); + + Pair mr = new Pair(); + mr.height = Math.max(lr.height, rr.height) + 1; + + int ld = diameter(node.left); + int rd = diameter(node.right); + int sp = lr.height + rr.height + 2; + + mr.diameter = Math.max(sp, Math.max(ld, rd)); + + return mr; + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_Find.java b/java/ds/BinaryTree/BT_Find.java index 10664ef7c..8e56b4f89 100644 --- a/java/ds/BinaryTree/BT_Find.java +++ b/java/ds/BinaryTree/BT_Find.java @@ -1,125 +1,125 @@ -package Git; - -import java.util.Scanner; - - -public class BT_Find { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_Find bts = new BT_Find(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - System.out.println(bt.find(30)); - System.out.println(bt.find(100)); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public boolean find(int item) { - return find(this.root, item); - } - - private boolean find(Node node, int item) { - - if (node == null) { - return false; - } - - if (node.data == item) { - return true; - } - - boolean lf = find(node.left, item); - boolean rf = find(node.right, item); - - return lf || rf; - - } - - } +package Git; + +import java.util.Scanner; + + +public class BT_Find { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_Find bts = new BT_Find(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + System.out.println(bt.find(30)); + System.out.println(bt.find(100)); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public boolean find(int item) { + return find(this.root, item); + } + + private boolean find(Node node, int item) { + + if (node == null) { + return false; + } + + if (node.data == item) { + return true; + } + + boolean lf = find(node.left, item); + boolean rf = find(node.right, item); + + return lf || rf; + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_Height.java b/java/ds/BinaryTree/BT_Height.java index d14d4940b..11d709395 100644 --- a/java/ds/BinaryTree/BT_Height.java +++ b/java/ds/BinaryTree/BT_Height.java @@ -1,123 +1,123 @@ -package Git; - -import java.util.Scanner; - - -public class BT_Height { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_Height bts= new BT_Height(); - BinaryTree bt = bts.new BinaryTree(); -// 10 true 20 true 40 false false true 50 false false true 30 true 60 false -// false false **Give this Input to create the tree** - - System.out.println(bt.height()); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public int height() { - return height(this.root); - } - - private int height(Node node) { - - if (node == null) { - return -1; - } - - int lh = height(node.left); - int rh = height(node.right); - - return Math.max(lh, rh) + 1; - - } - - - - -} +package Git; + +import java.util.Scanner; + + +public class BT_Height { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_Height bts= new BT_Height(); + BinaryTree bt = bts.new BinaryTree(); +// 10 true 20 true 40 false false true 50 false false true 30 true 60 false +// false false **Give this Input to create the tree** + + System.out.println(bt.height()); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public int height() { + return height(this.root); + } + + private int height(Node node) { + + if (node == null) { + return -1; + } + + int lh = height(node.left); + int rh = height(node.right); + + return Math.max(lh, rh) + 1; + + } + + + + +} } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_LevelOrder.java b/java/ds/BinaryTree/BT_LevelOrder.java index 69f15e2e5..569ab9a3f 100644 --- a/java/ds/BinaryTree/BT_LevelOrder.java +++ b/java/ds/BinaryTree/BT_LevelOrder.java @@ -1,129 +1,129 @@ -package Git; - -import java.util.LinkedList; -import java.util.Scanner; - - -public class BT_LevelOrder { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_LevelOrder bts = new BT_LevelOrder(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - bt.LevelOrder(); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public void LevelOrder() { - LevelOrder(this.root); - } - - private void LevelOrder(Node node) { - - LinkedList queue = new LinkedList<>(); - - queue.addLast(node); - - while (!queue.isEmpty()) { - - Node rn = queue.removeFirst(); - System.out.print(rn.data + " "); - - if (rn.left != null) { - queue.addLast(rn.left); - } - if (rn.right != null) { - queue.addLast(rn.right); - } - } - - } - - } +package Git; + +import java.util.LinkedList; +import java.util.Scanner; + + +public class BT_LevelOrder { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_LevelOrder bts = new BT_LevelOrder(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + bt.LevelOrder(); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public void LevelOrder() { + LevelOrder(this.root); + } + + private void LevelOrder(Node node) { + + LinkedList queue = new LinkedList<>(); + + queue.addLast(node); + + while (!queue.isEmpty()) { + + Node rn = queue.removeFirst(); + System.out.print(rn.data + " "); + + if (rn.left != null) { + queue.addLast(rn.left); + } + if (rn.right != null) { + queue.addLast(rn.right); + } + } + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_LevelOrderLineWise.java b/java/ds/BinaryTree/BT_LevelOrderLineWise.java index e84de82ab..aa11aa64b 100644 --- a/java/ds/BinaryTree/BT_LevelOrderLineWise.java +++ b/java/ds/BinaryTree/BT_LevelOrderLineWise.java @@ -1,136 +1,136 @@ -package Git; - -import java.util.LinkedList; -import java.util.Scanner; - -public class BT_LevelOrderLineWise { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_LevelOrderLineWise bts = new BT_LevelOrderLineWise(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - bt.LevelOrderLW(); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public void LevelOrderLW() { - LevelOrderLW(this.root); - } - - private void LevelOrderLW(Node node) { - - LinkedList queue = new LinkedList<>(); - LinkedList helper = new LinkedList<>(); - - queue.addLast(node); - - while (!queue.isEmpty()) { - - Node rn = queue.removeFirst(); - System.out.print(rn.data + " "); - - if (rn.left != null) { - helper.addLast(rn.left); - } - if (rn.right != null) { - helper.addLast(rn.right); - } - - if (queue.isEmpty()) { - System.out.print("$ "); - queue = helper; - helper = new LinkedList<>(); - } - - } - - } - - } +package Git; + +import java.util.LinkedList; +import java.util.Scanner; + +public class BT_LevelOrderLineWise { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_LevelOrderLineWise bts = new BT_LevelOrderLineWise(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + bt.LevelOrderLW(); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public void LevelOrderLW() { + LevelOrderLW(this.root); + } + + private void LevelOrderLW(Node node) { + + LinkedList queue = new LinkedList<>(); + LinkedList helper = new LinkedList<>(); + + queue.addLast(node); + + while (!queue.isEmpty()) { + + Node rn = queue.removeFirst(); + System.out.print(rn.data + " "); + + if (rn.left != null) { + helper.addLast(rn.left); + } + if (rn.right != null) { + helper.addLast(rn.right); + } + + if (queue.isEmpty()) { + System.out.print("$ "); + queue = helper; + helper = new LinkedList<>(); + } + + } + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_LevelOrderZigZag.java b/java/ds/BinaryTree/BT_LevelOrderZigZag.java index 52af5720c..f65aac7f1 100644 --- a/java/ds/BinaryTree/BT_LevelOrderZigZag.java +++ b/java/ds/BinaryTree/BT_LevelOrderZigZag.java @@ -1,146 +1,146 @@ -package Git; - -import java.util.LinkedList; -import java.util.Scanner; - -public class BT_LevelOrderZigZag { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_LevelOrderZigZag bts = new BT_LevelOrderZigZag(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - bt.LevelOrderZZ(); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public void LevelOrderZZ() { - LevelOrderZZ(this.root); - } - - private void LevelOrderZZ(Node node) { - - LinkedList queue = new LinkedList<>(); - LinkedList stack = new LinkedList<>(); - - queue.addLast(node); - int count = 0; - while (!queue.isEmpty()) { - - Node rn = queue.removeFirst(); - System.out.print(rn.data + " "); - - if (count % 2 == 0) { - if (rn.left != null) { - stack.addFirst(rn.left); - } - if (rn.right != null) { - stack.addFirst(rn.right); - } - } else { - if (rn.right != null) { - stack.addFirst(rn.right); - } - if (rn.left != null) { - stack.addFirst(rn.left); - } - } - - if (queue.isEmpty()) { - queue = stack; - stack = new LinkedList<>(); - System.out.println(); - count++; - } - - } - - } - - } +package Git; + +import java.util.LinkedList; +import java.util.Scanner; + +public class BT_LevelOrderZigZag { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_LevelOrderZigZag bts = new BT_LevelOrderZigZag(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + bt.LevelOrderZZ(); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public void LevelOrderZZ() { + LevelOrderZZ(this.root); + } + + private void LevelOrderZZ(Node node) { + + LinkedList queue = new LinkedList<>(); + LinkedList stack = new LinkedList<>(); + + queue.addLast(node); + int count = 0; + while (!queue.isEmpty()) { + + Node rn = queue.removeFirst(); + System.out.print(rn.data + " "); + + if (count % 2 == 0) { + if (rn.left != null) { + stack.addFirst(rn.left); + } + if (rn.right != null) { + stack.addFirst(rn.right); + } + } else { + if (rn.right != null) { + stack.addFirst(rn.right); + } + if (rn.left != null) { + stack.addFirst(rn.left); + } + } + + if (queue.isEmpty()) { + queue = stack; + stack = new LinkedList<>(); + System.out.println(); + count++; + } + + } + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_MirrorTree.java b/java/ds/BinaryTree/BT_MirrorTree.java index c791f9b94..a45e43ddf 100644 --- a/java/ds/BinaryTree/BT_MirrorTree.java +++ b/java/ds/BinaryTree/BT_MirrorTree.java @@ -1,128 +1,128 @@ -package Git; - -import java.util.Scanner; - -public class BT_MirrorTree { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_MirrorTree bts = new BT_MirrorTree(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - bt.mirrorTree(); - bt.display(); - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public void mirrorTree() { - mirrorTree(this.root); - } - - private void mirrorTree(Node node) { - - if (node == null) { - return; - } else if (node.left != null && node.right != null) { - Node nn = new Node(); - nn = node.left; - node.left = node.right; - node.right = nn; - } else if (node.left != null && node.right == null) { - node.right = node.left; - node.left = null; - } else if (node.left == null && node.right != null) { - node.left = node.right; - node.right = null; - } - - mirrorTree(node.left); - mirrorTree(node.right); - - } - - } +package Git; + +import java.util.Scanner; + +public class BT_MirrorTree { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_MirrorTree bts = new BT_MirrorTree(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + bt.mirrorTree(); + bt.display(); + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public void mirrorTree() { + mirrorTree(this.root); + } + + private void mirrorTree(Node node) { + + if (node == null) { + return; + } else if (node.left != null && node.right != null) { + Node nn = new Node(); + nn = node.left; + node.left = node.right; + node.right = nn; + } else if (node.left != null && node.right == null) { + node.right = node.left; + node.left = null; + } else if (node.left == null && node.right != null) { + node.left = node.right; + node.right = null; + } + + mirrorTree(node.left); + mirrorTree(node.right); + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_ReverseLevelOrderTraversal.java b/java/ds/BinaryTree/BT_ReverseLevelOrderTraversal.java index 655ced184..fc37edfb7 100644 --- a/java/ds/BinaryTree/BT_ReverseLevelOrderTraversal.java +++ b/java/ds/BinaryTree/BT_ReverseLevelOrderTraversal.java @@ -1,134 +1,134 @@ -package Git; - -import java.util.LinkedList; -import java.util.Scanner; - -public class BT_ReverseLevelOrderTraversal { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_ReverseLevelOrderTraversal bts = new BT_ReverseLevelOrderTraversal(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - bt.ReverseLevelOrderTraversal(); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public void ReverseLevelOrderTraversal() { - ReverseLevelOrderTraversal(this.root); - } - - private void ReverseLevelOrderTraversal(Node node) { // Using a queue & stack - - LinkedList queue = new LinkedList<>(); - LinkedList stack = new LinkedList<>(); - - queue.addLast(node); - - while (!queue.isEmpty()) { - - Node rn = queue.removeFirst(); - stack.addFirst(rn); - - if (rn.right != null) { - queue.addLast(rn.right); - } - if (rn.left != null) { - queue.addLast(rn.left); - } - - } - - while (!stack.isEmpty()) { - System.out.print(stack.removeFirst().data + " "); - } - - } - - } +package Git; + +import java.util.LinkedList; +import java.util.Scanner; + +public class BT_ReverseLevelOrderTraversal { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_ReverseLevelOrderTraversal bts = new BT_ReverseLevelOrderTraversal(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + bt.ReverseLevelOrderTraversal(); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public void ReverseLevelOrderTraversal() { + ReverseLevelOrderTraversal(this.root); + } + + private void ReverseLevelOrderTraversal(Node node) { // Using a queue & stack + + LinkedList queue = new LinkedList<>(); + LinkedList stack = new LinkedList<>(); + + queue.addLast(node); + + while (!queue.isEmpty()) { + + Node rn = queue.removeFirst(); + stack.addFirst(rn); + + if (rn.right != null) { + queue.addLast(rn.right); + } + if (rn.left != null) { + queue.addLast(rn.left); + } + + } + + while (!stack.isEmpty()) { + System.out.print(stack.removeFirst().data + " "); + } + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_Siblings.java b/java/ds/BinaryTree/BT_Siblings.java index 402427c6a..91ce7d931 100644 --- a/java/ds/BinaryTree/BT_Siblings.java +++ b/java/ds/BinaryTree/BT_Siblings.java @@ -1,123 +1,123 @@ -package Git; - -import java.util.Scanner; - - -public class BT_Siblings { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_Siblings bts = new BT_Siblings(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - bt.sibling(); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public void sibling() { - this.sibling(null, this.root); - } - - private void sibling(Node parent, Node node) { - - if (node == null) { - return; - } - - if (parent != null && parent.left != null && parent.right == null) { - System.out.print(node.data + " "); - } else if (parent != null && parent.left == null && parent.right != null) { - System.out.print(node.data + " "); - } - sibling(node, node.left); - sibling(node, node.right); - - } - - } +package Git; + +import java.util.Scanner; + + +public class BT_Siblings { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_Siblings bts = new BT_Siblings(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + bt.sibling(); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public void sibling() { + this.sibling(null, this.root); + } + + private void sibling(Node parent, Node node) { + + if (node == null) { + return; + } + + if (parent != null && parent.left != null && parent.right == null) { + System.out.print(node.data + " "); + } else if (parent != null && parent.left == null && parent.right != null) { + System.out.print(node.data + " "); + } + sibling(node, node.left); + sibling(node, node.right); + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_SumOfLeafNodes.java b/java/ds/BinaryTree/BT_SumOfLeafNodes.java index 86ca83ba1..ae754d3b9 100644 --- a/java/ds/BinaryTree/BT_SumOfLeafNodes.java +++ b/java/ds/BinaryTree/BT_SumOfLeafNodes.java @@ -1,124 +1,124 @@ -package Git; - -import java.util.Scanner; - -public class BT_SumOfLeafNodes { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_SumOfLeafNodes bts = new BT_SumOfLeafNodes(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - System.out.println(bt.SumofLeafNodes()); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - private class Res {// For Calculating Sum of Leaf Nodes - int sum = 0; - } - - public int SumofLeafNodes() { - Res r = new Res(); - leafSum(this.root, r); - return r.sum; - } - - private void leafSum(Node root, Res r) { - if (root == null) - return; - - if (root.left == null && root.right == null) - r.sum += root.data; - - leafSum(root.left, r); - leafSum(root.right, r); - - } - - } +package Git; + +import java.util.Scanner; + +public class BT_SumOfLeafNodes { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_SumOfLeafNodes bts = new BT_SumOfLeafNodes(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + System.out.println(bt.SumofLeafNodes()); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + private class Res {// For Calculating Sum of Leaf Nodes + int sum = 0; + } + + public int SumofLeafNodes() { + Res r = new Res(); + leafSum(this.root, r); + return r.sum; + } + + private void leafSum(Node root, Res r) { + if (root == null) + return; + + if (root.left == null && root.right == null) + r.sum += root.data; + + leafSum(root.left, r); + leafSum(root.right, r); + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_SumTree.java b/java/ds/BinaryTree/BT_SumTree.java index c51ce1d96..2ce4c15f1 100644 --- a/java/ds/BinaryTree/BT_SumTree.java +++ b/java/ds/BinaryTree/BT_SumTree.java @@ -1,124 +1,124 @@ -package Git; - -import java.util.Scanner; - -public class BT_SumTree { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_SumTree bts = new BT_SumTree(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - bt.display(); - bt.SumTree(); - bt.display(); - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public void SumTree() { - SumTree(this.root); - } - - private int SumTree(Node node) { - - if (node == null) - return 0; - - // Store the old value - int old_val = node.data; - - // Recursively call for left and right subtrees and store the sum - // as new value of this node - node.data = SumTree(node.left) + SumTree(node.right); - - // Return the sum of values of nodes in left and right subtrees - // and old_value of this node - return node.data + old_val; - - } - - } +package Git; + +import java.util.Scanner; + +public class BT_SumTree { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_SumTree bts = new BT_SumTree(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + bt.display(); + bt.SumTree(); + bt.display(); + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public void SumTree() { + SumTree(this.root); + } + + private int SumTree(Node node) { + + if (node == null) + return 0; + + // Store the old value + int old_val = node.data; + + // Recursively call for left and right subtrees and store the sum + // as new value of this node + node.data = SumTree(node.left) + SumTree(node.right); + + // Return the sum of values of nodes in left and right subtrees + // and old_value of this node + return node.data + old_val; + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_boundaryTraversal.java b/java/ds/BinaryTree/BT_boundaryTraversal.java index e646eea77..994a035bb 100644 --- a/java/ds/BinaryTree/BT_boundaryTraversal.java +++ b/java/ds/BinaryTree/BT_boundaryTraversal.java @@ -1,171 +1,171 @@ -package Git; - -import java.util.Scanner; - -public class BT_boundaryTraversal { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_boundaryTraversal bts = new BT_boundaryTraversal(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - bt.Boundary(); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public void Boundary() { - - Boundary(this.root); - - } - - private void Boundary(Node node) { - - System.out.print(node.data + " "); - BoundaryLeft(node.left); - printLeafs(node.left); - printLeafs(node.right); - BoundaryRight(node.right); - - } - - private void BoundaryRight(Node node) { - - if (node != null) { - - if (node.right != null) { - - BoundaryRight(node.right); - System.out.print(node.data + " "); - - } else if (node.left != null) { - - BoundaryRight(node.left); - System.out.print(node.data + " "); - } - - } - - } - - private void printLeafs(Node node) { - - if (node != null) { - - printLeafs(node.left); - if (node.left == null && node.right == null) { - System.out.print(node.data + " "); - } - printLeafs(node.right); - - } - - } - - private void BoundaryLeft(Node node) { - - if (node != null) { - - if (node.left != null) { - - System.out.print(node.data + " "); - BoundaryLeft(node.left); - - } else if (node.right != null) { - - System.out.print(node.data + " "); - BoundaryLeft(node.right); - - } - - } - - } - - } +package Git; + +import java.util.Scanner; + +public class BT_boundaryTraversal { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_boundaryTraversal bts = new BT_boundaryTraversal(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + bt.Boundary(); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public void Boundary() { + + Boundary(this.root); + + } + + private void Boundary(Node node) { + + System.out.print(node.data + " "); + BoundaryLeft(node.left); + printLeafs(node.left); + printLeafs(node.right); + BoundaryRight(node.right); + + } + + private void BoundaryRight(Node node) { + + if (node != null) { + + if (node.right != null) { + + BoundaryRight(node.right); + System.out.print(node.data + " "); + + } else if (node.left != null) { + + BoundaryRight(node.left); + System.out.print(node.data + " "); + } + + } + + } + + private void printLeafs(Node node) { + + if (node != null) { + + printLeafs(node.left); + if (node.left == null && node.right == null) { + System.out.print(node.data + " "); + } + printLeafs(node.right); + + } + + } + + private void BoundaryLeft(Node node) { + + if (node != null) { + + if (node.left != null) { + + System.out.print(node.data + " "); + BoundaryLeft(node.left); + + } else if (node.right != null) { + + System.out.print(node.data + " "); + BoundaryLeft(node.right); + + } + + } + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_diameter.java b/java/ds/BinaryTree/BT_diameter.java index c4f17f875..78fd0f79d 100644 --- a/java/ds/BinaryTree/BT_diameter.java +++ b/java/ds/BinaryTree/BT_diameter.java @@ -1,138 +1,138 @@ -package Git; - -import java.util.Scanner; - -public class BT_diameter { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_diameter bts = new BT_diameter(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - System.out.println(bt.diameter()); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public int height() { - return height(this.root); - } - - private int height(Node node) { - - if (node == null) { - return -1; - } - - int lh = height(node.left); - int rh = height(node.right); - - return Math.max(lh, rh) + 1; - - } - - public int diameter() { - return diameter(this.root); - } - - private int diameter(Node node) { - - if (node == null) { - return 0; - } - - int ld = diameter(node.left); - int rd = diameter(node.right); - - int sp = height(node.left) + height(node.right) + 2; - - return Math.max(sp, Math.max(ld, rd)); - - } - - } +package Git; + +import java.util.Scanner; + +public class BT_diameter { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_diameter bts = new BT_diameter(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + System.out.println(bt.diameter()); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public int height() { + return height(this.root); + } + + private int height(Node node) { + + if (node == null) { + return -1; + } + + int lh = height(node.left); + int rh = height(node.right); + + return Math.max(lh, rh) + 1; + + } + + public int diameter() { + return diameter(this.root); + } + + private int diameter(Node node) { + + if (node == null) { + return 0; + } + + int ld = diameter(node.left); + int rd = diameter(node.right); + + int sp = height(node.left) + height(node.right) + 2; + + return Math.max(sp, Math.max(ld, rd)); + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_isBalanced.java b/java/ds/BinaryTree/BT_isBalanced.java index cbcee2e0b..10b88098e 100644 --- a/java/ds/BinaryTree/BT_isBalanced.java +++ b/java/ds/BinaryTree/BT_isBalanced.java @@ -1,140 +1,140 @@ -package Git; - -import java.util.Scanner; - -public class BT_isBalanced { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_isBalanced bts = new BT_isBalanced(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - System.out.println(bt.isBalanced()); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - private class BalancedPair { - - int height; - boolean isBalanced; - - } - - public boolean isBalanced() { - return isBalanced(this.root).isBalanced; - } - - private BalancedPair isBalanced(Node node) { - - if (node == null) { - BalancedPair bbp = new BalancedPair(); - bbp.height = -1; - bbp.isBalanced = true; - return bbp; - } - - BalancedPair lbp = isBalanced(node.left); - BalancedPair rbp = isBalanced(node.right); - - BalancedPair mbp = new BalancedPair(); - - mbp.height = Math.max(lbp.height, rbp.height) + 1; - int bf = lbp.height - rbp.height; - - if (lbp.isBalanced && rbp.isBalanced && Math.abs(bf) <= 1) { - mbp.isBalanced = true; - } else { - mbp.isBalanced = false; - } - - return mbp; - - } - - } +package Git; + +import java.util.Scanner; + +public class BT_isBalanced { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_isBalanced bts = new BT_isBalanced(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + System.out.println(bt.isBalanced()); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + private class BalancedPair { + + int height; + boolean isBalanced; + + } + + public boolean isBalanced() { + return isBalanced(this.root).isBalanced; + } + + private BalancedPair isBalanced(Node node) { + + if (node == null) { + BalancedPair bbp = new BalancedPair(); + bbp.height = -1; + bbp.isBalanced = true; + return bbp; + } + + BalancedPair lbp = isBalanced(node.left); + BalancedPair rbp = isBalanced(node.right); + + BalancedPair mbp = new BalancedPair(); + + mbp.height = Math.max(lbp.height, rbp.height) + 1; + int bf = lbp.height - rbp.height; + + if (lbp.isBalanced && rbp.isBalanced && Math.abs(bf) <= 1) { + mbp.isBalanced = true; + } else { + mbp.isBalanced = false; + } + + return mbp; + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_isIdentical.java b/java/ds/BinaryTree/BT_isIdentical.java index e034abda1..3484eccb7 100644 --- a/java/ds/BinaryTree/BT_isIdentical.java +++ b/java/ds/BinaryTree/BT_isIdentical.java @@ -1,123 +1,123 @@ -package Git; - -import java.util.Scanner; - -public class BT_isIdentical { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_isIdentical bts = new BT_isIdentical(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - BinaryTree bt2 = bts.new BinaryTree(); // Create A Second Binary Tree - - System.out.println(bt.isIdentical(bt)); - System.out.println(bt.isIdentical(bt2)); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public boolean isIdentical(BinaryTree bt2) { - return isIdentical(this.root, bt2.root); - } - - private boolean isIdentical(Node node, Node onode) { - - if (node == null && onode == null) { - return true; - } - - if (node != null && onode != null) { - return (node.data == onode.data && isIdentical(node.left, onode.left) - && isIdentical(node.right, onode.right)); - } - return false; - - } - - } +package Git; + +import java.util.Scanner; + +public class BT_isIdentical { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_isIdentical bts = new BT_isIdentical(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + BinaryTree bt2 = bts.new BinaryTree(); // Create A Second Binary Tree + + System.out.println(bt.isIdentical(bt)); + System.out.println(bt.isIdentical(bt2)); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public boolean isIdentical(BinaryTree bt2) { + return isIdentical(this.root, bt2.root); + } + + private boolean isIdentical(Node node, Node onode) { + + if (node == null && onode == null) { + return true; + } + + if (node != null && onode != null) { + return (node.data == onode.data && isIdentical(node.left, onode.left) + && isIdentical(node.right, onode.right)); + } + return false; + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_largestBSTPair.java b/java/ds/BinaryTree/BT_largestBSTPair.java index cd1848281..7b5904d51 100644 --- a/java/ds/BinaryTree/BT_largestBSTPair.java +++ b/java/ds/BinaryTree/BT_largestBSTPair.java @@ -1,155 +1,155 @@ -package Git; - -import java.util.Scanner; - -public class BT_largestBSTPair { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_largestBSTPair bts = new BT_largestBSTPair(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - bt.largestBST(); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - private class BSTPair { - - int max = Integer.MIN_VALUE; - int min = Integer.MAX_VALUE; - boolean isBST = true; - Node largestBSTNode = null; - int size = 0; - - } - - public void largestBST() { - BSTPair bst = new BSTPair(); - bst = largestBST(this.root); - System.out.println(bst.largestBSTNode.data); - System.out.println(bst.size); - System.out.println(bst.max); - System.out.println(bst.min); - } - - private BSTPair largestBST(Node node) { - - if (node == null) { - BSTPair pair = new BSTPair(); - return pair; - } - - BSTPair left = largestBST(node.left); - BSTPair right = largestBST(node.right); - - BSTPair mr = new BSTPair(); - mr.max = Math.max(node.data, Math.max(left.max, right.max)); - mr.min = Math.min(node.data, Math.min(left.min, right.min)); - - if (left.isBST && right.isBST && node.data > left.max && node.data < right.min) { - mr.isBST = true; - mr.largestBSTNode = node; - mr.size = left.size + right.size + 1; - } else { - mr.isBST = false; - if (left.size > right.size) { - mr.largestBSTNode = left.largestBSTNode; - mr.size = left.size; - } else { - mr.largestBSTNode = right.largestBSTNode; - mr.size = right.size; - } - - } - - return mr; - - } - - } +package Git; + +import java.util.Scanner; + +public class BT_largestBSTPair { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_largestBSTPair bts = new BT_largestBSTPair(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + bt.largestBST(); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + private class BSTPair { + + int max = Integer.MIN_VALUE; + int min = Integer.MAX_VALUE; + boolean isBST = true; + Node largestBSTNode = null; + int size = 0; + + } + + public void largestBST() { + BSTPair bst = new BSTPair(); + bst = largestBST(this.root); + System.out.println(bst.largestBSTNode.data); + System.out.println(bst.size); + System.out.println(bst.max); + System.out.println(bst.min); + } + + private BSTPair largestBST(Node node) { + + if (node == null) { + BSTPair pair = new BSTPair(); + return pair; + } + + BSTPair left = largestBST(node.left); + BSTPair right = largestBST(node.right); + + BSTPair mr = new BSTPair(); + mr.max = Math.max(node.data, Math.max(left.max, right.max)); + mr.min = Math.min(node.data, Math.min(left.min, right.min)); + + if (left.isBST && right.isBST && node.data > left.max && node.data < right.min) { + mr.isBST = true; + mr.largestBSTNode = node; + mr.size = left.size + right.size + 1; + } else { + mr.isBST = false; + if (left.size > right.size) { + mr.largestBSTNode = left.largestBSTNode; + mr.size = left.size; + } else { + mr.largestBSTNode = right.largestBSTNode; + mr.size = right.size; + } + + } + + return mr; + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_numOfLeafs.java b/java/ds/BinaryTree/BT_numOfLeafs.java index 536d914f0..45b7f5e9e 100644 --- a/java/ds/BinaryTree/BT_numOfLeafs.java +++ b/java/ds/BinaryTree/BT_numOfLeafs.java @@ -1,121 +1,121 @@ -package Git; - -import java.util.Scanner; - -public class BT_numOfLeafs { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_numOfLeafs bts = new BT_numOfLeafs(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - System.out.println(bt.numLeafs()); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public int numLeafs() { - return numLeafs(this.root); - } - - private int numLeafs(Node node) { - - if (node == null) { - return 0; - } else if (node.left == null && node.right == null) { - return 1; - } - - int ln = numLeafs(node.left); - int rn = numLeafs(node.right); - - return ln + rn; - - } - - } +package Git; + +import java.util.Scanner; + +public class BT_numOfLeafs { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_numOfLeafs bts = new BT_numOfLeafs(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + System.out.println(bt.numLeafs()); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public int numLeafs() { + return numLeafs(this.root); + } + + private int numLeafs(Node node) { + + if (node == null) { + return 0; + } else if (node.left == null && node.right == null) { + return 1; + } + + int ln = numLeafs(node.left); + int rn = numLeafs(node.right); + + return ln + rn; + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_sumOfNodes.java b/java/ds/BinaryTree/BT_sumOfNodes.java index be0d7202e..195d43a5c 100644 --- a/java/ds/BinaryTree/BT_sumOfNodes.java +++ b/java/ds/BinaryTree/BT_sumOfNodes.java @@ -1,119 +1,119 @@ -package Git; - -import java.util.Scanner; - - -public class BT_sumOfNodes { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_sumOfNodes bts = new BT_sumOfNodes(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - System.out.println(bt.sumOfNodes()); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public int sumOfNodes() { - return this.sumOfNodes(null, this.root); - } - - private int sumOfNodes(Node parent, Node node) { - - if (node == null) { - return 0; - } - - int ls = sumOfNodes(node, node.left); - int rs = sumOfNodes(node, node.right); - - return node.data + ls + rs; - } - - } +package Git; + +import java.util.Scanner; + + +public class BT_sumOfNodes { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_sumOfNodes bts = new BT_sumOfNodes(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + System.out.println(bt.sumOfNodes()); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public int sumOfNodes() { + return this.sumOfNodes(null, this.root); + } + + private int sumOfNodes(Node parent, Node node) { + + if (node == null) { + return 0; + } + + int ls = sumOfNodes(node, node.left); + int rs = sumOfNodes(node, node.right); + + return node.data + ls + rs; + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_traversalsIteratively.java b/java/ds/BinaryTree/BT_traversalsIteratively.java index 98a1360c5..87b000cc0 100644 --- a/java/ds/BinaryTree/BT_traversalsIteratively.java +++ b/java/ds/BinaryTree/BT_traversalsIteratively.java @@ -1,227 +1,227 @@ -package Git; - -import java.util.LinkedList; -import java.util.Scanner; - -public class BT_traversalsIteratively { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_traversalsIteratively bts = new BT_traversalsIteratively(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - bt.inOrderI(); - bt.postOrderI(); - bt.preOrderI(); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - private class OrderPair { - - Node node; - boolean selfDone; - boolean leftDone; - boolean rightDone; - - } - - public void preOrderI() { - - LinkedList stack = new LinkedList<>(); - - OrderPair sp = new OrderPair(); - sp.node = this.root; - - stack.addFirst(sp); - - while (!stack.isEmpty()) { - - OrderPair tp = stack.getFirst(); - - if (tp.selfDone == false) { - System.out.print(tp.node.data + " "); - tp.selfDone = true; - } else if (tp.leftDone == false) { - if (tp.node.left != null) { - OrderPair np = new OrderPair(); - np.node = tp.node.left; - stack.addFirst(np); - } - tp.leftDone = true; - } else if (tp.rightDone == false) { - if (tp.node.right != null) { - OrderPair np = new OrderPair(); - np.node = tp.node.right; - stack.addFirst(np); - } - tp.rightDone = true; - } else { - stack.removeFirst(); - } - - } - System.out.println(); - } - - public void inOrderI() { - - LinkedList stack = new LinkedList<>(); - - OrderPair sp = new OrderPair(); - sp.node = this.root; - - stack.addFirst(sp); - - while (!stack.isEmpty()) { - - OrderPair tp = stack.getFirst(); - - if (tp.leftDone == false) { - if (tp.node.left != null) { - OrderPair np = new OrderPair(); - np.node = tp.node.left; - stack.addFirst(np); - } - tp.leftDone = true; - } else if (tp.selfDone == false) { - System.out.print(tp.node.data + " "); - tp.selfDone = true; - } else if (tp.rightDone == false) { - if (tp.node.right != null) { - OrderPair np = new OrderPair(); - np.node = tp.node.right; - stack.addFirst(np); - } - tp.rightDone = true; - } else { - stack.removeFirst(); - } - - } - System.out.println(); - } - - public void postOrderI() { - LinkedList stack = new LinkedList<>(); - - OrderPair sp = new OrderPair(); - sp.node = this.root; - - stack.addFirst(sp); - - while (!stack.isEmpty()) { - - OrderPair tp = stack.getFirst(); - - if (tp.leftDone == false) { - if (tp.node.left != null) { - OrderPair np = new OrderPair(); - np.node = tp.node.left; - stack.addFirst(np); - } - tp.leftDone = true; - } else if (tp.rightDone == false) { - if (tp.node.right != null) { - OrderPair np = new OrderPair(); - np.node = tp.node.right; - stack.addFirst(np); - } - tp.rightDone = true; - } else if (tp.selfDone == false) { - System.out.print(tp.node.data + " "); - tp.selfDone = true; - } else { - stack.removeFirst(); - } - - } - System.out.println(); - } - - } +package Git; + +import java.util.LinkedList; +import java.util.Scanner; + +public class BT_traversalsIteratively { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_traversalsIteratively bts = new BT_traversalsIteratively(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + bt.inOrderI(); + bt.postOrderI(); + bt.preOrderI(); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + private class OrderPair { + + Node node; + boolean selfDone; + boolean leftDone; + boolean rightDone; + + } + + public void preOrderI() { + + LinkedList stack = new LinkedList<>(); + + OrderPair sp = new OrderPair(); + sp.node = this.root; + + stack.addFirst(sp); + + while (!stack.isEmpty()) { + + OrderPair tp = stack.getFirst(); + + if (tp.selfDone == false) { + System.out.print(tp.node.data + " "); + tp.selfDone = true; + } else if (tp.leftDone == false) { + if (tp.node.left != null) { + OrderPair np = new OrderPair(); + np.node = tp.node.left; + stack.addFirst(np); + } + tp.leftDone = true; + } else if (tp.rightDone == false) { + if (tp.node.right != null) { + OrderPair np = new OrderPair(); + np.node = tp.node.right; + stack.addFirst(np); + } + tp.rightDone = true; + } else { + stack.removeFirst(); + } + + } + System.out.println(); + } + + public void inOrderI() { + + LinkedList stack = new LinkedList<>(); + + OrderPair sp = new OrderPair(); + sp.node = this.root; + + stack.addFirst(sp); + + while (!stack.isEmpty()) { + + OrderPair tp = stack.getFirst(); + + if (tp.leftDone == false) { + if (tp.node.left != null) { + OrderPair np = new OrderPair(); + np.node = tp.node.left; + stack.addFirst(np); + } + tp.leftDone = true; + } else if (tp.selfDone == false) { + System.out.print(tp.node.data + " "); + tp.selfDone = true; + } else if (tp.rightDone == false) { + if (tp.node.right != null) { + OrderPair np = new OrderPair(); + np.node = tp.node.right; + stack.addFirst(np); + } + tp.rightDone = true; + } else { + stack.removeFirst(); + } + + } + System.out.println(); + } + + public void postOrderI() { + LinkedList stack = new LinkedList<>(); + + OrderPair sp = new OrderPair(); + sp.node = this.root; + + stack.addFirst(sp); + + while (!stack.isEmpty()) { + + OrderPair tp = stack.getFirst(); + + if (tp.leftDone == false) { + if (tp.node.left != null) { + OrderPair np = new OrderPair(); + np.node = tp.node.left; + stack.addFirst(np); + } + tp.leftDone = true; + } else if (tp.rightDone == false) { + if (tp.node.right != null) { + OrderPair np = new OrderPair(); + np.node = tp.node.right; + stack.addFirst(np); + } + tp.rightDone = true; + } else if (tp.selfDone == false) { + System.out.print(tp.node.data + " "); + tp.selfDone = true; + } else { + stack.removeFirst(); + } + + } + System.out.println(); + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BT_traversalsRecursively.java b/java/ds/BinaryTree/BT_traversalsRecursively.java index f4ed935df..6896cd1ba 100644 --- a/java/ds/BinaryTree/BT_traversalsRecursively.java +++ b/java/ds/BinaryTree/BT_traversalsRecursively.java @@ -1,155 +1,155 @@ -package Git; - -import java.util.Scanner; - -public class BT_traversalsRecursively { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BT_traversalsRecursively bts = new BT_traversalsRecursively(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - bt.inOrderR(); - bt.preOrderR(); - bt.postOrderR(); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public void preOrderR() { - preOrderR(this.root); - System.out.println(); - } - - private void preOrderR(Node node) { - - if (node == null) { - return; - } - - System.out.print(node.data + " "); - preOrderR(node.left); - preOrderR(node.right); - - } - - public void postOrderR() { - postOrder(this.root); - System.out.println(); - } - - private void postOrder(Node node) { - - if (node == null) { - return; - } - - postOrder(node.left); - postOrder(node.right); - System.out.print(node.data + " "); - - } - - public void inOrderR() { - inOrderR(this.root); - System.out.println(); - } - - public void inOrderR(Node node) { - - if (node == null) { - return; - } - - inOrderR(node.left); - System.out.print(node.data + " "); - inOrderR(node.right); - - } - - } +package Git; + +import java.util.Scanner; + +public class BT_traversalsRecursively { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BT_traversalsRecursively bts = new BT_traversalsRecursively(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + bt.inOrderR(); + bt.preOrderR(); + bt.postOrderR(); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public void preOrderR() { + preOrderR(this.root); + System.out.println(); + } + + private void preOrderR(Node node) { + + if (node == null) { + return; + } + + System.out.print(node.data + " "); + preOrderR(node.left); + preOrderR(node.right); + + } + + public void postOrderR() { + postOrder(this.root); + System.out.println(); + } + + private void postOrder(Node node) { + + if (node == null) { + return; + } + + postOrder(node.left); + postOrder(node.right); + System.out.print(node.data + " "); + + } + + public void inOrderR() { + inOrderR(this.root); + System.out.println(); + } + + public void inOrderR(Node node) { + + if (node == null) { + return; + } + + inOrderR(node.left); + System.out.print(node.data + " "); + inOrderR(node.right); + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/BinaryTree_Size.java b/java/ds/BinaryTree/BinaryTree_Size.java index 7d5a11f40..a53c10667 100644 --- a/java/ds/BinaryTree/BinaryTree_Size.java +++ b/java/ds/BinaryTree/BinaryTree_Size.java @@ -1,118 +1,118 @@ -package Git; - -import java.util.Scanner; - -public class BinaryTree_Size { - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - BinaryTree_Size bts = new BinaryTree_Size(); - BinaryTree bt = bts.new BinaryTree(); -// 10 true 20 true 40 false false true 50 false false true 30 true 60 false -// false false **Give this Input to create the tree** - bt.display(); - System.out.println(bt.size2()); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public int size2() { - return size2(this.root); - } - - private int size2(Node node) { - - if (node == null) { - return 0; - } - - int ls = size2(node.left); - int rs = size2(node.right); - - return ls + rs + 1; - - } - - } +package Git; + +import java.util.Scanner; + +public class BinaryTree_Size { + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + BinaryTree_Size bts = new BinaryTree_Size(); + BinaryTree bt = bts.new BinaryTree(); +// 10 true 20 true 40 false false true 50 false false true 30 true 60 false +// false false **Give this Input to create the tree** + bt.display(); + System.out.println(bt.size2()); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public int size2() { + return size2(this.root); + } + + private int size2(Node node) { + + if (node == null) { + return 0; + } + + int ls = size2(node.left); + int rs = size2(node.right); + + return ls + rs + 1; + + } + + } } \ No newline at end of file diff --git a/java/ds/BinaryTree/SerializeDeserializeofBT.java b/java/ds/BinaryTree/SerializeDeserializeofBT.java index 056c0f036..4d16579dc 100644 --- a/java/ds/BinaryTree/SerializeDeserializeofBT.java +++ b/java/ds/BinaryTree/SerializeDeserializeofBT.java @@ -1,167 +1,167 @@ -package Git; - -import java.util.Scanner; - -public class SerializeDeserializeofBT { - - static Scanner scn = new Scanner(System.in); - - public static void main(String[] args) { - - SerializeDeserializeofBT bts = new SerializeDeserializeofBT(); - BinaryTree bt = bts.new BinaryTree(); - // 10 true 20 true 40 false false true 50 false false true 30 true 60 false - // false false **Give this Input to create the tree** - - String str = bt.serialize(); - System.out.println(str); - // # -> represent root node - bt.root = bt.deserialize(str); - bt.display(bt.root); - - } - - private class BinaryTree { - - private class Node { - int data; - Node left; - Node right; - } - - private Node root; - private int size; - - public BinaryTree() { - this.root = construct(null, false); - } - - private Node construct(Node parent, boolean ilc) { - - if (parent == null) { - System.out.println("Enter the data for root node ? "); - } else { - if (ilc) { - System.out.println("Enter the data for left " + parent.data); - } else { - System.out.println("Enter the data for right " + parent.data); - } - } - - int val = scn.nextInt(); - Node nn = new Node(); - nn.data = val; - this.size++; - - boolean lc; - System.out.println("Do you want left child"); - lc = scn.nextBoolean(); - if (lc) { - nn.left = construct(nn, true); - } - - boolean rc; - System.out.println("Do you want right child"); - rc = scn.nextBoolean(); - if (rc) { - nn.right = construct(nn, false); - } - - return nn; - - } - - public void display() { - display(this.root); - } - - private void display(Node node) { - - if (node == null) { - return; - } - - String str = ""; - - if (node.left != null) { - str += node.left.data; - } else { - str += "."; - } - - str += "->" + node.data + "<-"; - - if (node.right != null) { - str += node.right.data; - } else { - str += "."; - } - System.out.println(str); - display(node.left); - display(node.right); - - } - - public void inOrderR(Node node) { - - if (node == null) { - return; - } - - inOrderR(node.left); - System.out.print(node.data + " "); - inOrderR(node.right); - - } - - public String serialize() { - String s = serialize(this.root); - Node nn = deserialize(s); - // System.out.println(nn.data); - inOrderR(nn); - System.out.println(); - return s.substring(0, s.length() - 1); - } - - private String serialize(Node root) { - - if (root == null) { - return "#,"; - } - - String s = Integer.toString(root.data); - String la = serialize(root.left); - String ra = serialize(root.right); - - return s + "," + la + ra; - - } - - public Node deserialize(String data) { - if (data == null) - return null; - - int[] t = { 0 }; - String[] arr = data.split(","); - - return helper(arr, t); - } - - public Node helper(String[] arr, int[] t) { - if (arr[t[0]].equals("#")) { - return null; - } - - Node node = new Node(); - node.data = Integer.parseInt(arr[t[0]]); - - t[0] = t[0] + 1; - node.left = helper(arr, t); - t[0] = t[0] + 1; - node.right = helper(arr, t); - - return node; - } - - } +package Git; + +import java.util.Scanner; + +public class SerializeDeserializeofBT { + + static Scanner scn = new Scanner(System.in); + + public static void main(String[] args) { + + SerializeDeserializeofBT bts = new SerializeDeserializeofBT(); + BinaryTree bt = bts.new BinaryTree(); + // 10 true 20 true 40 false false true 50 false false true 30 true 60 false + // false false **Give this Input to create the tree** + + String str = bt.serialize(); + System.out.println(str); + // # -> represent root node + bt.root = bt.deserialize(str); + bt.display(bt.root); + + } + + private class BinaryTree { + + private class Node { + int data; + Node left; + Node right; + } + + private Node root; + private int size; + + public BinaryTree() { + this.root = construct(null, false); + } + + private Node construct(Node parent, boolean ilc) { + + if (parent == null) { + System.out.println("Enter the data for root node ? "); + } else { + if (ilc) { + System.out.println("Enter the data for left " + parent.data); + } else { + System.out.println("Enter the data for right " + parent.data); + } + } + + int val = scn.nextInt(); + Node nn = new Node(); + nn.data = val; + this.size++; + + boolean lc; + System.out.println("Do you want left child"); + lc = scn.nextBoolean(); + if (lc) { + nn.left = construct(nn, true); + } + + boolean rc; + System.out.println("Do you want right child"); + rc = scn.nextBoolean(); + if (rc) { + nn.right = construct(nn, false); + } + + return nn; + + } + + public void display() { + display(this.root); + } + + private void display(Node node) { + + if (node == null) { + return; + } + + String str = ""; + + if (node.left != null) { + str += node.left.data; + } else { + str += "."; + } + + str += "->" + node.data + "<-"; + + if (node.right != null) { + str += node.right.data; + } else { + str += "."; + } + System.out.println(str); + display(node.left); + display(node.right); + + } + + public void inOrderR(Node node) { + + if (node == null) { + return; + } + + inOrderR(node.left); + System.out.print(node.data + " "); + inOrderR(node.right); + + } + + public String serialize() { + String s = serialize(this.root); + Node nn = deserialize(s); + // System.out.println(nn.data); + inOrderR(nn); + System.out.println(); + return s.substring(0, s.length() - 1); + } + + private String serialize(Node root) { + + if (root == null) { + return "#,"; + } + + String s = Integer.toString(root.data); + String la = serialize(root.left); + String ra = serialize(root.right); + + return s + "," + la + ra; + + } + + public Node deserialize(String data) { + if (data == null) + return null; + + int[] t = { 0 }; + String[] arr = data.split(","); + + return helper(arr, t); + } + + public Node helper(String[] arr, int[] t) { + if (arr[t[0]].equals("#")) { + return null; + } + + Node node = new Node(); + node.data = Integer.parseInt(arr[t[0]]); + + t[0] = t[0] + 1; + node.left = helper(arr, t); + t[0] = t[0] + 1; + node.right = helper(arr, t); + + return node; + } + + } } \ No newline at end of file diff --git a/java/ds/DP b/java/ds/DP deleted file mode 160000 index 457dc6769..000000000 --- a/java/ds/DP +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 457dc6769e1e0aa55f56da38fde3789efc3ef971 diff --git a/java/ds/DoubleEndedQueue.java b/java/ds/DoubleEndedQueue.java index 667a7de03..7e25d472e 100644 --- a/java/ds/DoubleEndedQueue.java +++ b/java/ds/DoubleEndedQueue.java @@ -1,137 +1,137 @@ - -class Node { - -int data; -Node next; - -public Node(int data) { - this.data = data; - this.next = null; - } -} - -public class DoubleEndedQueue { - - private int size=0; - private Node front=null; - private Node rear=null; - private int count=0; - DoubleEndedQueue(int count){ - this.count=count; - } - public boolean isEmpty(){ - return this.size == 0; - } - - public void insertFront(int input) - { - Node temp=new Node(input); - if(front==null && rear==null) - { - front=temp; - rear=temp; - this.size++; - } - else if(this.size!=count){ - temp.next=front; - front=temp; - this.size++; - } - else - { - System.out.println("-1"); - return; - } - - } - - public void insertRear(int input) - { - Node temp=new Node(input); - if(front==null && rear==null) - { - front=temp; - rear=temp; - this.size++; - } - - else if(this.size!=count){ - rear.next=temp; - rear=temp; - this.size++; - } - - else{ - System.out.println("-1"); - return; - } - - } - - public void deleteFront() - { - if(this.size==0){ - System.out.println("-1"); - return;} - - if(this.size==1) - { - front=null; - rear=null; - this.size--; - return; - } - - front=front.next; - - this.size--; - - } - - public void deleteRear() - { - Node var=front; - if(this.size==0){ - System.out.println("-1"); - return; - } - - if(this.size==1) - { - front=rear=null; - this.size--; - return; - } - - - while(var.next.next!=null) - { - var=var.next; - } - var.next=null; - rear=var; - - this.size--; - - - } - - public int getFront() - { - if(this.isEmpty()) - return -1; - else - return front.data; - - } - - public int getRear() - { - if(this.isEmpty()) - return -1; - else - return rear.data; - - } - -} + +class Node { + +int data; +Node next; + +public Node(int data) { + this.data = data; + this.next = null; + } +} + +public class DoubleEndedQueue { + + private int size=0; + private Node front=null; + private Node rear=null; + private int count=0; + DoubleEndedQueue(int count){ + this.count=count; + } + public boolean isEmpty(){ + return this.size == 0; + } + + public void insertFront(int input) + { + Node temp=new Node(input); + if(front==null && rear==null) + { + front=temp; + rear=temp; + this.size++; + } + else if(this.size!=count){ + temp.next=front; + front=temp; + this.size++; + } + else + { + System.out.println("-1"); + return; + } + + } + + public void insertRear(int input) + { + Node temp=new Node(input); + if(front==null && rear==null) + { + front=temp; + rear=temp; + this.size++; + } + + else if(this.size!=count){ + rear.next=temp; + rear=temp; + this.size++; + } + + else{ + System.out.println("-1"); + return; + } + + } + + public void deleteFront() + { + if(this.size==0){ + System.out.println("-1"); + return;} + + if(this.size==1) + { + front=null; + rear=null; + this.size--; + return; + } + + front=front.next; + + this.size--; + + } + + public void deleteRear() + { + Node var=front; + if(this.size==0){ + System.out.println("-1"); + return; + } + + if(this.size==1) + { + front=rear=null; + this.size--; + return; + } + + + while(var.next.next!=null) + { + var=var.next; + } + var.next=null; + rear=var; + + this.size--; + + + } + + public int getFront() + { + if(this.isEmpty()) + return -1; + else + return front.data; + + } + + public int getRear() + { + if(this.isEmpty()) + return -1; + else + return rear.data; + + } + +} diff --git a/java/ds/GFG.java b/java/ds/GFG.java index 9bd6a483d..3939d0245 100644 --- a/java/ds/GFG.java +++ b/java/ds/GFG.java @@ -1,80 +1,80 @@ - -// Java program to insert element in binary tree -import java.util.LinkedList; -import java.util.Queue; -public class GFG { - - /* A binary tree node has key, pointer to - left child and a pointer to right child */ - static class Node { - int key; - Node left, right; - - // constructor - Node(int key){ - this.key = key; - left = null; - right = null; - } - } - static Node root; - static Node temp = root; - - /* Inorder traversal of a binary tree*/ - static void inorder(Node temp) - { - if (temp == null) - return; - - inorder(temp.left); - System.out.print(temp.key+" "); - inorder(temp.right); - } - - /*function to insert element in binary tree */ - static void insert(Node temp, int key) - { - Queue q = new LinkedList(); - q.add(temp); - - // Do level order traversal until we find - // an empty place. - while (!q.isEmpty()) { - temp = q.peek(); - q.remove(); - - if (temp.left == null) { - temp.left = new Node(key); - break; - } else - q.add(temp.left); - - if (temp.right == null) { - temp.right = new Node(key); - break; - } else - q.add(temp.right); - } - } - - // Driver code - public static void main(String args[]) - { - root = new Node(10); - root.left = new Node(11); - root.left.left = new Node(7); - root.right = new Node(9); - root.right.left = new Node(15); - root.right.right = new Node(8); - - System.out.print( "Inorder traversal before insertion:"); - inorder(root); - - int key = 12; - insert(root, key); - - System.out.print("\nInorder traversal after insertion:"); - inorder(root); - } -} + +// Java program to insert element in binary tree +import java.util.LinkedList; +import java.util.Queue; +public class GFG { + + /* A binary tree node has key, pointer to + left child and a pointer to right child */ + static class Node { + int key; + Node left, right; + + // constructor + Node(int key){ + this.key = key; + left = null; + right = null; + } + } + static Node root; + static Node temp = root; + + /* Inorder traversal of a binary tree*/ + static void inorder(Node temp) + { + if (temp == null) + return; + + inorder(temp.left); + System.out.print(temp.key+" "); + inorder(temp.right); + } + + /*function to insert element in binary tree */ + static void insert(Node temp, int key) + { + Queue q = new LinkedList(); + q.add(temp); + + // Do level order traversal until we find + // an empty place. + while (!q.isEmpty()) { + temp = q.peek(); + q.remove(); + + if (temp.left == null) { + temp.left = new Node(key); + break; + } else + q.add(temp.left); + + if (temp.right == null) { + temp.right = new Node(key); + break; + } else + q.add(temp.right); + } + } + + // Driver code + public static void main(String args[]) + { + root = new Node(10); + root.left = new Node(11); + root.left.left = new Node(7); + root.right = new Node(9); + root.right.left = new Node(15); + root.right.right = new Node(8); + + System.out.print( "Inorder traversal before insertion:"); + inorder(root); + + int key = 12; + insert(root, key); + + System.out.print("\nInorder traversal after insertion:"); + inorder(root); + } +} // This code is contributed by Sumit Ghosh \ No newline at end of file diff --git a/java/ds/Graph/Graph.java b/java/ds/Graph/Graph.java old mode 100755 new mode 100644 index 713b98cd7..bb86fa0c5 --- a/java/ds/Graph/Graph.java +++ b/java/ds/Graph/Graph.java @@ -1,379 +1,379 @@ -package Graph; - -import java.util.ArrayList; -import java.util.HashMap; - - -public class Graph { - - private class Vertex { - HashMap nghbrs = new HashMap<>(); - } - - HashMap vertices = new HashMap<>(); - - public int numVetex() { - return vertices.size(); - } - - public boolean containsVertex(String vname) { - return vertices.containsKey(vname); - } - - public void addVertex(String vname) { - Vertex vtx = new Vertex(); - vertices.put(vname, vtx); - } - - public void removeVertex(String vname) { - - Vertex vtx = vertices.get(vname); - ArrayList nbrnames = new ArrayList<>(vtx.nghbrs.keySet()); - - for (String nbrname : nbrnames) { - - Vertex vtxnbr = vertices.get(nbrname); - vtxnbr.nghbrs.remove(vname); - } - - vertices.remove(vname); - - } - - public int numEdges() { - - ArrayList vnames = new ArrayList<>(vertices.keySet()); - int ans = 0; - - for (String vname : vnames) { - - Vertex vtx = vertices.get(vname); - ans += vtx.nghbrs.size(); - } - - return ans / 2; - } - - public boolean containsEdge(String vname1, String vname2) { - - Vertex vtx1 = vertices.get(vname1); - Vertex vtx2 = vertices.get(vname2); - - if (vtx1 == null || vtx2 == null || !vtx1.nghbrs.containsKey(vname2)) { - return false; - } - - return true; - } - - public void addEdge(String vname1, String vname2, int cost) { - - Vertex vtx1 = vertices.get(vname1); - Vertex vtx2 = vertices.get(vname2); - - if (vtx1 == null || vtx2 == null || vtx1.nghbrs.containsKey(vname2)) { - return; - } - - vtx1.nghbrs.put(vname2, cost); - // vtx2.nghbrs.put(vname1, cost); - } - - public void removeEdge(String vname1, String vname2) { - - Vertex vtx1 = vertices.get(vname1); - Vertex vtx2 = vertices.get(vname2); - - if (vtx1 == null || vtx2 == null || !vtx1.nghbrs.containsKey(vname2)) { - return; - } - - vtx1.nghbrs.remove(vname2); - vtx2.nghbrs.remove(vname1); - } - - public void display() { - - System.out.println("------------------"); - ArrayList vnames = new ArrayList<>(vertices.keySet()); - - for (String vname : vnames) { - - String str = vname + " => "; - - Vertex vtx = vertices.get(vname); - str += vtx.nghbrs; - - System.out.println(str); - } - System.out.println("------------------"); - - } - - // prims -> minimum spanning tree - private class PrimsPair implements Comparable { - - String vname; - String acqVertexName; - Vertex vtx; - int cost; - - @Override - public int compareTo(PrimsPair other) { - return other.cost - this.cost; - } - } - - public Graph prims() { - - // create a mst - Graph mst = new Graph(); - - HeapGeneric heap = new HeapGeneric<>(); - HashMap map = new HashMap<>(); - HashMap processed = new HashMap<>(); - - ArrayList keys = new ArrayList<>(this.vertices.keySet()); - - // make pairs and put in heap - for (String key : keys) { - PrimsPair np = new PrimsPair(); - np.vname = key; - np.vtx = vertices.get(key); - np.cost = Integer.MAX_VALUE; - np.acqVertexName = null; - - heap.add(np); - processed.put(np.vname, true); - map.put(key, np); - } - - // til the heap is not empty keep on doing work - while (!heap.isEmpty()) { - - // remove a pair - PrimsPair rp = heap.remove(); - processed.remove(rp.vname); - - // if acq vertex is null, add a vertx only - if (rp.acqVertexName == null) { - mst.addVertex(rp.vname); - } else { - mst.addVertex(rp.vname); - mst.addEdge(rp.vname, rp.acqVertexName, rp.cost); - } - - // get nbrs - ArrayList nbrs = new ArrayList<>(rp.vtx.nghbrs.keySet()); - - // loop on nbrs - for (String nbr : nbrs) { - - // process only the one which are in heap - if (processed.containsKey(nbr)) { - PrimsPair nbrPair = map.get(nbr); - - // get the old cost - int oc = nbrPair.cost; - int nc = rp.vtx.nghbrs.get(nbr); - - // if new cost is smaller than old cost then update the cost - if (nc < oc) { - nbrPair.cost = nc; - nbrPair.acqVertexName = rp.vname; - - // update the priority in heap - heap.updatePriority(nbrPair); - } - } - } - } - - return mst; - } - - // dijkstra -> single source shortest path, but can't work with -ve weight - // edges - public class DijkstraPair implements Comparable { - - String vname; - String psf; - Vertex vtx; - int cost; - - @Override - public int compareTo(DijkstraPair other) { - return other.cost - this.cost; - } - - @Override - public String toString() { - return this.cost + " via " + this.psf + "\n"; - } - - } - - public HashMap Dijkstra(String src) { - - HashMap map = new HashMap<>(); - HeapGeneric heap = new HeapGeneric<>(); - - // processed will keep track of vertex which are present in heap - HashMap processed = new HashMap<>(); - - // get all the vertex names present in graph - ArrayList keys = new ArrayList<>(this.vertices.keySet()); - - // make pairs and put in heap, with the cost of src vertex as 0 - for (String key : keys) { - DijkstraPair np = new DijkstraPair(); - np.vname = key; - np.vtx = vertices.get(key); - np.psf = ""; - np.cost = Integer.MAX_VALUE; - - // if present key is src, cost of src vertex will be 0 - if (key.equals(src)) { - np.psf = key; - np.cost = 0; - } - - heap.add(np); - map.put(key, np); - - // update the processed, bcz processed was keeping track of nodes which are - // present in heap - processed.put(key, true); - } - - // till the heap is not empty keep on removing pairs - while (!heap.isEmpty()) { - - // remove the pair from heap - DijkstraPair rp = heap.remove(); - - // update the processed hashmap - processed.remove(rp.vname); - - // loop on nbrs - ArrayList nbrs = new ArrayList<>(rp.vtx.nghbrs.keySet()); - - for (String nbr : nbrs) { - - // process only those nbrs which are present in heap - if (processed.containsKey(nbr)) { - DijkstraPair nbrPair = map.get(nbr); - - int oc = nbrPair.cost; - int nc = rp.cost + rp.vtx.nghbrs.get(nbr); - - // if new cost is less than old cost then update the cost - if (nc < oc) { - nbrPair.cost = nc; - nbrPair.psf = rp.psf + nbr; - - // update the priority of the updated node in heap - heap.updatePriority(nbrPair); - } - } - } - } - - return map; - - } - - // bellman ford -> single source shortest path, can work with -ve weight edges, - // but can't work with cycle having -ve weights - public ArrayList getAllEdges() { - - ArrayList ans = new ArrayList<>(); - - ArrayList keys = new ArrayList<>(vertices.keySet()); - - for (String key : keys) { - - Vertex vtx = vertices.get(key); - ArrayList nbrs = new ArrayList<>(vtx.nghbrs.keySet()); - - for (String nbr : nbrs) { - EdgePair ep = new EdgePair(); - ep.vname1 = key; - ep.vname2 = nbr; - ep.cost = vtx.nghbrs.get(nbr); - - ans.add(ep); - } - - } - - return ans; - } - - private class EdgePair { - String vname1; - String vname2; - int cost; - } - - public HashMap BellmanFord(String src) throws Exception { - - HashMap map = new HashMap<>(); - - ArrayList keys = new ArrayList<>(this.vertices.keySet()); - - // put the src vertex with 0 cost, and other vertex with infinity cost - for (String key : keys) { - - map.put(key, Integer.MAX_VALUE); - - // if key equals src then cost will be 0 - if (key.equals(src)) { - map.put(key, 0); - } - - } - - // get all the edges - ArrayList alledges = getAllEdges(); - - // V is total no. of vertex in graph - int V = vertices.size(); - - // relax V-1 times bcz at max two vertex can be at V-1 distance - for (int i = 1; i <= V - 1; i++) { - - // all the edges are relaxed - // relax : if we have discovered an edge from u->v then compare - // if cost(v) > cost(u) + edgecost(u,v) then update the cost of v - // cost(v) = cost(u) + edgecost(u,v) - for (EdgePair edge : alledges) { - - int oc = map.get(edge.vname2); - int nc = map.get(edge.vname1) + edge.cost; - - // update the cost of v, if cost(u) + edgecost(u,v) is less than prev cost of v - if (nc < oc) { - map.put(edge.vname2, nc); - } - } - } - - // if the weights are further reduced after relaxing Vth time then it means -ve - // weight cycle was present - for (EdgePair edge : alledges) { - - int oc = map.get(edge.vname2); - int nc = map.get(edge.vname1) + edge.cost; - - System.out.println(map.get(edge.vname1) + " " + nc); - - // if wt is further reduced then give an exception to user - if (nc < oc) { - throw new Exception("-ve weight cycle"); - } - } - - return map; - } -} +package Graph; + +import java.util.ArrayList; +import java.util.HashMap; + + +public class Graph { + + private class Vertex { + HashMap nghbrs = new HashMap<>(); + } + + HashMap vertices = new HashMap<>(); + + public int numVetex() { + return vertices.size(); + } + + public boolean containsVertex(String vname) { + return vertices.containsKey(vname); + } + + public void addVertex(String vname) { + Vertex vtx = new Vertex(); + vertices.put(vname, vtx); + } + + public void removeVertex(String vname) { + + Vertex vtx = vertices.get(vname); + ArrayList nbrnames = new ArrayList<>(vtx.nghbrs.keySet()); + + for (String nbrname : nbrnames) { + + Vertex vtxnbr = vertices.get(nbrname); + vtxnbr.nghbrs.remove(vname); + } + + vertices.remove(vname); + + } + + public int numEdges() { + + ArrayList vnames = new ArrayList<>(vertices.keySet()); + int ans = 0; + + for (String vname : vnames) { + + Vertex vtx = vertices.get(vname); + ans += vtx.nghbrs.size(); + } + + return ans / 2; + } + + public boolean containsEdge(String vname1, String vname2) { + + Vertex vtx1 = vertices.get(vname1); + Vertex vtx2 = vertices.get(vname2); + + if (vtx1 == null || vtx2 == null || !vtx1.nghbrs.containsKey(vname2)) { + return false; + } + + return true; + } + + public void addEdge(String vname1, String vname2, int cost) { + + Vertex vtx1 = vertices.get(vname1); + Vertex vtx2 = vertices.get(vname2); + + if (vtx1 == null || vtx2 == null || vtx1.nghbrs.containsKey(vname2)) { + return; + } + + vtx1.nghbrs.put(vname2, cost); + // vtx2.nghbrs.put(vname1, cost); + } + + public void removeEdge(String vname1, String vname2) { + + Vertex vtx1 = vertices.get(vname1); + Vertex vtx2 = vertices.get(vname2); + + if (vtx1 == null || vtx2 == null || !vtx1.nghbrs.containsKey(vname2)) { + return; + } + + vtx1.nghbrs.remove(vname2); + vtx2.nghbrs.remove(vname1); + } + + public void display() { + + System.out.println("------------------"); + ArrayList vnames = new ArrayList<>(vertices.keySet()); + + for (String vname : vnames) { + + String str = vname + " => "; + + Vertex vtx = vertices.get(vname); + str += vtx.nghbrs; + + System.out.println(str); + } + System.out.println("------------------"); + + } + + // prims -> minimum spanning tree + private class PrimsPair implements Comparable { + + String vname; + String acqVertexName; + Vertex vtx; + int cost; + + @Override + public int compareTo(PrimsPair other) { + return other.cost - this.cost; + } + } + + public Graph prims() { + + // create a mst + Graph mst = new Graph(); + + HeapGeneric heap = new HeapGeneric<>(); + HashMap map = new HashMap<>(); + HashMap processed = new HashMap<>(); + + ArrayList keys = new ArrayList<>(this.vertices.keySet()); + + // make pairs and put in heap + for (String key : keys) { + PrimsPair np = new PrimsPair(); + np.vname = key; + np.vtx = vertices.get(key); + np.cost = Integer.MAX_VALUE; + np.acqVertexName = null; + + heap.add(np); + processed.put(np.vname, true); + map.put(key, np); + } + + // til the heap is not empty keep on doing work + while (!heap.isEmpty()) { + + // remove a pair + PrimsPair rp = heap.remove(); + processed.remove(rp.vname); + + // if acq vertex is null, add a vertx only + if (rp.acqVertexName == null) { + mst.addVertex(rp.vname); + } else { + mst.addVertex(rp.vname); + mst.addEdge(rp.vname, rp.acqVertexName, rp.cost); + } + + // get nbrs + ArrayList nbrs = new ArrayList<>(rp.vtx.nghbrs.keySet()); + + // loop on nbrs + for (String nbr : nbrs) { + + // process only the one which are in heap + if (processed.containsKey(nbr)) { + PrimsPair nbrPair = map.get(nbr); + + // get the old cost + int oc = nbrPair.cost; + int nc = rp.vtx.nghbrs.get(nbr); + + // if new cost is smaller than old cost then update the cost + if (nc < oc) { + nbrPair.cost = nc; + nbrPair.acqVertexName = rp.vname; + + // update the priority in heap + heap.updatePriority(nbrPair); + } + } + } + } + + return mst; + } + + // dijkstra -> single source shortest path, but can't work with -ve weight + // edges + public class DijkstraPair implements Comparable { + + String vname; + String psf; + Vertex vtx; + int cost; + + @Override + public int compareTo(DijkstraPair other) { + return other.cost - this.cost; + } + + @Override + public String toString() { + return this.cost + " via " + this.psf + "\n"; + } + + } + + public HashMap Dijkstra(String src) { + + HashMap map = new HashMap<>(); + HeapGeneric heap = new HeapGeneric<>(); + + // processed will keep track of vertex which are present in heap + HashMap processed = new HashMap<>(); + + // get all the vertex names present in graph + ArrayList keys = new ArrayList<>(this.vertices.keySet()); + + // make pairs and put in heap, with the cost of src vertex as 0 + for (String key : keys) { + DijkstraPair np = new DijkstraPair(); + np.vname = key; + np.vtx = vertices.get(key); + np.psf = ""; + np.cost = Integer.MAX_VALUE; + + // if present key is src, cost of src vertex will be 0 + if (key.equals(src)) { + np.psf = key; + np.cost = 0; + } + + heap.add(np); + map.put(key, np); + + // update the processed, bcz processed was keeping track of nodes which are + // present in heap + processed.put(key, true); + } + + // till the heap is not empty keep on removing pairs + while (!heap.isEmpty()) { + + // remove the pair from heap + DijkstraPair rp = heap.remove(); + + // update the processed hashmap + processed.remove(rp.vname); + + // loop on nbrs + ArrayList nbrs = new ArrayList<>(rp.vtx.nghbrs.keySet()); + + for (String nbr : nbrs) { + + // process only those nbrs which are present in heap + if (processed.containsKey(nbr)) { + DijkstraPair nbrPair = map.get(nbr); + + int oc = nbrPair.cost; + int nc = rp.cost + rp.vtx.nghbrs.get(nbr); + + // if new cost is less than old cost then update the cost + if (nc < oc) { + nbrPair.cost = nc; + nbrPair.psf = rp.psf + nbr; + + // update the priority of the updated node in heap + heap.updatePriority(nbrPair); + } + } + } + } + + return map; + + } + + // bellman ford -> single source shortest path, can work with -ve weight edges, + // but can't work with cycle having -ve weights + public ArrayList getAllEdges() { + + ArrayList ans = new ArrayList<>(); + + ArrayList keys = new ArrayList<>(vertices.keySet()); + + for (String key : keys) { + + Vertex vtx = vertices.get(key); + ArrayList nbrs = new ArrayList<>(vtx.nghbrs.keySet()); + + for (String nbr : nbrs) { + EdgePair ep = new EdgePair(); + ep.vname1 = key; + ep.vname2 = nbr; + ep.cost = vtx.nghbrs.get(nbr); + + ans.add(ep); + } + + } + + return ans; + } + + private class EdgePair { + String vname1; + String vname2; + int cost; + } + + public HashMap BellmanFord(String src) throws Exception { + + HashMap map = new HashMap<>(); + + ArrayList keys = new ArrayList<>(this.vertices.keySet()); + + // put the src vertex with 0 cost, and other vertex with infinity cost + for (String key : keys) { + + map.put(key, Integer.MAX_VALUE); + + // if key equals src then cost will be 0 + if (key.equals(src)) { + map.put(key, 0); + } + + } + + // get all the edges + ArrayList alledges = getAllEdges(); + + // V is total no. of vertex in graph + int V = vertices.size(); + + // relax V-1 times bcz at max two vertex can be at V-1 distance + for (int i = 1; i <= V - 1; i++) { + + // all the edges are relaxed + // relax : if we have discovered an edge from u->v then compare + // if cost(v) > cost(u) + edgecost(u,v) then update the cost of v + // cost(v) = cost(u) + edgecost(u,v) + for (EdgePair edge : alledges) { + + int oc = map.get(edge.vname2); + int nc = map.get(edge.vname1) + edge.cost; + + // update the cost of v, if cost(u) + edgecost(u,v) is less than prev cost of v + if (nc < oc) { + map.put(edge.vname2, nc); + } + } + } + + // if the weights are further reduced after relaxing Vth time then it means -ve + // weight cycle was present + for (EdgePair edge : alledges) { + + int oc = map.get(edge.vname2); + int nc = map.get(edge.vname1) + edge.cost; + + System.out.println(map.get(edge.vname1) + " " + nc); + + // if wt is further reduced then give an exception to user + if (nc < oc) { + throw new Exception("-ve weight cycle"); + } + } + + return map; + } +} diff --git a/java/ds/Graph/GraphClient.java b/java/ds/Graph/GraphClient.java old mode 100755 new mode 100644 index c0f46d160..d0ff1b148 --- a/java/ds/Graph/GraphClient.java +++ b/java/ds/Graph/GraphClient.java @@ -1,53 +1,53 @@ -package Graph; - - - -public class GraphClient { - - public static void main(String[] args) throws Exception { - - Graph graph = new Graph(); - graph.addVertex("A"); - graph.addVertex("B"); - graph.addVertex("C"); - graph.addVertex("D"); - graph.addVertex("E"); - graph.addVertex("F"); - graph.addVertex("G"); - graph.addEdge("A", "B", 10); - graph.addEdge("A", "D", 40); - graph.addEdge("B", "C", 10); - graph.addEdge("C", "D", 10); - graph.addEdge("D", "E", 5); - graph.addEdge("E", "F", 2); - graph.addEdge("E", "G", 6); - graph.addEdge("F", "G", 3); - - // graph.addEdge("A", "B", 6); - // graph.addEdge("A", "E", 4); - // graph.addEdge("A", "F", 5); - // graph.addEdge("E", "F", -3); - // graph.addEdge("B", "C", 2); - // graph.addEdge("C", "D", 2); - // graph.addEdge("D", "C", 1); - // graph.addEdge("F", "D", 4); - - // graph.addEdge("A", "B", 5); - // graph.addEdge("B", "C", -2); - // graph.addEdge("A", "C", 4); - // - // graph.addEdge("A", "B", 1); - // graph.addEdge("B", "C", 2); - // graph.addEdge("C", "D", 2); - // graph.addEdge("D", "B", 6); - - // graph.display(); - // graph.prims().display(); - - // System.out.println(graph.Dijkstra("A")); - - System.out.println(graph.BellmanFord("A")); - - } - -} +package Graph; + + + +public class GraphClient { + + public static void main(String[] args) throws Exception { + + Graph graph = new Graph(); + graph.addVertex("A"); + graph.addVertex("B"); + graph.addVertex("C"); + graph.addVertex("D"); + graph.addVertex("E"); + graph.addVertex("F"); + graph.addVertex("G"); + graph.addEdge("A", "B", 10); + graph.addEdge("A", "D", 40); + graph.addEdge("B", "C", 10); + graph.addEdge("C", "D", 10); + graph.addEdge("D", "E", 5); + graph.addEdge("E", "F", 2); + graph.addEdge("E", "G", 6); + graph.addEdge("F", "G", 3); + + // graph.addEdge("A", "B", 6); + // graph.addEdge("A", "E", 4); + // graph.addEdge("A", "F", 5); + // graph.addEdge("E", "F", -3); + // graph.addEdge("B", "C", 2); + // graph.addEdge("C", "D", 2); + // graph.addEdge("D", "C", 1); + // graph.addEdge("F", "D", 4); + + // graph.addEdge("A", "B", 5); + // graph.addEdge("B", "C", -2); + // graph.addEdge("A", "C", 4); + // + // graph.addEdge("A", "B", 1); + // graph.addEdge("B", "C", 2); + // graph.addEdge("C", "D", 2); + // graph.addEdge("D", "B", 6); + + // graph.display(); + // graph.prims().display(); + + // System.out.println(graph.Dijkstra("A")); + + System.out.println(graph.BellmanFord("A")); + + } + +} diff --git a/java/ds/Graph/HeapGeneric.java b/java/ds/Graph/HeapGeneric.java old mode 100755 new mode 100644 index d118be3ef..57a5c0cde --- a/java/ds/Graph/HeapGeneric.java +++ b/java/ds/Graph/HeapGeneric.java @@ -1,108 +1,108 @@ -package Graph; - -import java.util.ArrayList; -import java.util.HashMap; - - - -public class HeapGeneric> { - - ArrayList data = new ArrayList<>(); - HashMap map = new HashMap<>(); - - public void add(T item) { - - data.add(item); - map.put(item, this.data.size() - 1); - upheapify(this.data.size() - 1); - } - - private void upheapify(int ci) { - - int pi = (ci - 1) / 2; - - if (isLarger(this.data.get(ci), this.data.get(pi)) > 0) { - swap(pi, ci); - upheapify(pi); - } - - } - - private void swap(int i, int j) { - - T ith = data.get(i); - T jth = data.get(j); - - data.set(i, jth); - data.set(j, ith); - - map.put(ith, j); - map.put(jth, i); - } - - public T remove() { - - swap(0, data.size() - 1); - - T rv = data.remove(data.size() - 1); - map.remove(rv); - downheapify(0); - - return rv; - } - - private void downheapify(int pi) { - - int lci = 2 * pi + 1; - int rci = 2 * pi + 2; - int mini = pi; - - if (lci < this.data.size() && isLarger(data.get(lci), data.get(mini)) > 0) { - mini = lci; - } - - if (rci < this.data.size() && isLarger(data.get(rci), data.get(mini)) > 0) { - mini = rci; - } - - if (mini != pi) { - swap(mini, pi); - downheapify(mini); - } - } - - public T get() { - return this.data.get(0); - } - - public void display() { - System.out.println(data); - } - - public int size() { - return this.data.size(); - } - - public boolean isEmpty() { - return this.size() == 0; - } - - public int isLarger(T t, T o) { - return t.compareTo(o); - } - - public void updatePriority(T nbrPair) { - - // int idx = -1; - // - // for (int i = 0; i < this.data.size(); i++) { - // if (this.data.get(i) == nbrPair) { - // idx = i; - // } - // } - - int idx = map.get(nbrPair); - upheapify(idx); - - } -} +package Graph; + +import java.util.ArrayList; +import java.util.HashMap; + + + +public class HeapGeneric> { + + ArrayList data = new ArrayList<>(); + HashMap map = new HashMap<>(); + + public void add(T item) { + + data.add(item); + map.put(item, this.data.size() - 1); + upheapify(this.data.size() - 1); + } + + private void upheapify(int ci) { + + int pi = (ci - 1) / 2; + + if (isLarger(this.data.get(ci), this.data.get(pi)) > 0) { + swap(pi, ci); + upheapify(pi); + } + + } + + private void swap(int i, int j) { + + T ith = data.get(i); + T jth = data.get(j); + + data.set(i, jth); + data.set(j, ith); + + map.put(ith, j); + map.put(jth, i); + } + + public T remove() { + + swap(0, data.size() - 1); + + T rv = data.remove(data.size() - 1); + map.remove(rv); + downheapify(0); + + return rv; + } + + private void downheapify(int pi) { + + int lci = 2 * pi + 1; + int rci = 2 * pi + 2; + int mini = pi; + + if (lci < this.data.size() && isLarger(data.get(lci), data.get(mini)) > 0) { + mini = lci; + } + + if (rci < this.data.size() && isLarger(data.get(rci), data.get(mini)) > 0) { + mini = rci; + } + + if (mini != pi) { + swap(mini, pi); + downheapify(mini); + } + } + + public T get() { + return this.data.get(0); + } + + public void display() { + System.out.println(data); + } + + public int size() { + return this.data.size(); + } + + public boolean isEmpty() { + return this.size() == 0; + } + + public int isLarger(T t, T o) { + return t.compareTo(o); + } + + public void updatePriority(T nbrPair) { + + // int idx = -1; + // + // for (int i = 0; i < this.data.size(); i++) { + // if (this.data.get(i) == nbrPair) { + // idx = i; + // } + // } + + int idx = map.get(nbrPair); + upheapify(idx); + + } +} diff --git a/javascript/AlphaBetaPruning/app.css b/javascript/AlphaBetaPruning/app.css index 660453561..a119e8f4b 100644 --- a/javascript/AlphaBetaPruning/app.css +++ b/javascript/AlphaBetaPruning/app.css @@ -1,188 +1,188 @@ -html, body { - background: #EEE; - overflow: hidden; -} - -svg { - background-color: #EEE; - cursor: default; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - -o-user-select: none; - user-select: none; -} - -.navbar .navbar-nav a, -.navbar .navbar-header span { - color: #FFF; - cursor: default; -} - -.nopadding { - padding: 0 !important; -} - -.nomargin { - margin: 0 !important; -} - -.ab-tree { - position: fixed; -} - -.info { - z-index: 10; - position: absolute; - bottom: 6px; - left: 6px; - font-size: 9px; -} - -.prune-info { - z-index: 10; - position: absolute; - bottom: 6px; - right: 6px; - font-size: 14px; -} - -.ctrl-panel { - z-index: 10; - position: relative; - float: right; - width: 325px; - padding: 10px; - margin: 10px; - background: rgba(0, 0, 0, 0.08); - border-radius: 4px; - font-size: 12px; -} - -.ctrl-panel .btn { - font-size: 12px; -} - -.ctrl-panel hr { - margin: 10px; - height: 0; - border: 0; - border-top: 1px solid #ccc; -} - -.ctrl-panel .row { - margin: 5px 0; -} - -.ctrl-panel .row > div { - padding-left: 2.5px; - padding-right: 2.5px; - margin-left: 0; - margin-right: 0; -} - -.ctrl-panel .row .progress { - margin-bottom: 0; - padding: 0; -} - -.ctrl-panel .row .slider-handle { - background-color: #428BCA; - background-image: none; - opacity: 1; -} - -.button-label-container { - padding: 7px 0 0 0; - margin: 0; -} - -.button-label { - padding: 0 3px; -} - -.slider-label.left { - padding: 0 10px 0 0; -} - -.slider-label.right { - padding: 0 0 0 10px; -} - -.answer-true { - color: #008800; -} - -path.link { - fill: none; - stroke: #000; - stroke-width: 4px; -} - -path.link.hover { - stroke: #666666; -} - -path.link.entered, -path.link.entered.hover { - stroke: #008800; -} - -path.link.pruned { - stroke-dasharray: 10,10; - stroke: #880000; -} - -path.link.pruned.hover { - stroke: #cd0000; -} - -path.mouselink { - stroke-width: 30px; - stroke: #000; - stroke-opacity: 0; - cursor: pointer; -} - - -g.node path { - cursor: pointer; - fill: #FFF; - stroke: #000; -} -g.node path:hover { - fill: #EEE; -} -g.node.entered path { - fill: #EEFFEE; -} - -g.node.leaf path { - fill: #FFF; -} -g.node.leaf path:hover { - fill: #EEE; -} -g.node.entered.leaf path { - fill: #EEEEFF; -} - -rect.cursor { - fill: #000; -} - -text { - font-family: 'Helvetica Neue', sans-serif; - font-size: 18px; - pointer-events: none; -} - -text.value { - text-anchor: middle; - font-weight: bold; -} - -g.node.pruned .alpha, -g.node.pruned .beta { - fill: #AA0000; +html, body { + background: #EEE; + overflow: hidden; +} + +svg { + background-color: #EEE; + cursor: default; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + -o-user-select: none; + user-select: none; +} + +.navbar .navbar-nav a, +.navbar .navbar-header span { + color: #FFF; + cursor: default; +} + +.nopadding { + padding: 0 !important; +} + +.nomargin { + margin: 0 !important; +} + +.ab-tree { + position: fixed; +} + +.info { + z-index: 10; + position: absolute; + bottom: 6px; + left: 6px; + font-size: 9px; +} + +.prune-info { + z-index: 10; + position: absolute; + bottom: 6px; + right: 6px; + font-size: 14px; +} + +.ctrl-panel { + z-index: 10; + position: relative; + float: right; + width: 325px; + padding: 10px; + margin: 10px; + background: rgba(0, 0, 0, 0.08); + border-radius: 4px; + font-size: 12px; +} + +.ctrl-panel .btn { + font-size: 12px; +} + +.ctrl-panel hr { + margin: 10px; + height: 0; + border: 0; + border-top: 1px solid #ccc; +} + +.ctrl-panel .row { + margin: 5px 0; +} + +.ctrl-panel .row > div { + padding-left: 2.5px; + padding-right: 2.5px; + margin-left: 0; + margin-right: 0; +} + +.ctrl-panel .row .progress { + margin-bottom: 0; + padding: 0; +} + +.ctrl-panel .row .slider-handle { + background-color: #428BCA; + background-image: none; + opacity: 1; +} + +.button-label-container { + padding: 7px 0 0 0; + margin: 0; +} + +.button-label { + padding: 0 3px; +} + +.slider-label.left { + padding: 0 10px 0 0; +} + +.slider-label.right { + padding: 0 0 0 10px; +} + +.answer-true { + color: #008800; +} + +path.link { + fill: none; + stroke: #000; + stroke-width: 4px; +} + +path.link.hover { + stroke: #666666; +} + +path.link.entered, +path.link.entered.hover { + stroke: #008800; +} + +path.link.pruned { + stroke-dasharray: 10,10; + stroke: #880000; +} + +path.link.pruned.hover { + stroke: #cd0000; +} + +path.mouselink { + stroke-width: 30px; + stroke: #000; + stroke-opacity: 0; + cursor: pointer; +} + + +g.node path { + cursor: pointer; + fill: #FFF; + stroke: #000; +} +g.node path:hover { + fill: #EEE; +} +g.node.entered path { + fill: #EEFFEE; +} + +g.node.leaf path { + fill: #FFF; +} +g.node.leaf path:hover { + fill: #EEE; +} +g.node.entered.leaf path { + fill: #EEEEFF; +} + +rect.cursor { + fill: #000; +} + +text { + font-family: 'Helvetica Neue', sans-serif; + font-size: 18px; + pointer-events: none; +} + +text.value { + text-anchor: middle; + font-weight: bold; +} + +g.node.pruned .alpha, +g.node.pruned .beta { + fill: #AA0000; } \ No newline at end of file diff --git a/javascript/AlphaBetaPruning/app.js b/javascript/AlphaBetaPruning/app.js index cf961f8f2..d4fa54d33 100644 --- a/javascript/AlphaBetaPruning/app.js +++ b/javascript/AlphaBetaPruning/app.js @@ -1,979 +1,979 @@ -Array.prototype.extend = function(array) { - Array.prototype.push.apply(this, array); -} - -angular.module('d3', []) - .factory('d3Service', ['$document', '$q', '$rootScope', - function($document, $q, $rootScope) { - var d = $q.defer(); - function onScriptLoad() { - // Load client in the browser - $rootScope.$apply(function() { d.resolve(window.d3); }); - } - - var scriptTag = $document[0].createElement('script'); - scriptTag.type = 'text/javascript'; - scriptTag.async = true; - scriptTag.src = 'https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js'; - scriptTag.onreadystatechange = function () { - if (this.readyState == 'complete') { onScriptLoad(); } - } - scriptTag.onload = onScriptLoad; - - var s = $document[0].getElementsByTagName('body')[0]; - s.appendChild(scriptTag); - - return { - d3: function() { return d.promise; } - }; - } - ]); - -angular.module('Enums', []) - .factory('EnumService', [function() { - var TreeNodeTypeEnum = { - maxNode: 'maxNode', - minNode: 'minNode', - randNode: 'randNode', - leafNode: 'leafNode', - - opposite: function(t) { - if (t == this.maxNode) { - return this.minNode; - } else if (t == this.minNode) { - return this.maxNode; - } - return t; - }, - }; - - return { - TreeNodeTypeEnum: TreeNodeTypeEnum, - }; - - }]); - -angular.module('ActionListQueue', []) - .factory('ActionLQService', [function() { - - function Action(object, key, oldVal, newVal) { - this.object = object; - this.key = key; - this.oldVal = oldVal; - this.newVal = newVal; - } - Action.prototype.apply = function() { - if (!this.object) { return; } - this.object[this.key] = this.newVal; - } - Action.prototype.reverse = function() { - if (!this.object) { return; } - this.object[this.key] = this.oldVal; - } - - function ActionListQueue() { - this.inAction = false; - this.lastAction = -1; - this.actionListQueue = [] - this.length = 0; - } - ActionListQueue.prototype.pushActionList = function(actionList) { - if (this.inAction) { return false; } - this.actionListQueue.push(actionList); - this.length += 1; - return true; - } - ActionListQueue.prototype.extendActionList = function(actionLists) { - if (this.inAction) { return false; } - this.actionListQueue.extend(actionLists); - this.length += actionLists.length; - return true; - } - ActionListQueue.prototype.stepForward = function() { - if (!this.inAction || - this.lastAction == (this.actionListQueue.length - 1)) { - return false; - } - this.lastAction += 1; - var actionList = this.actionListQueue[this.lastAction]; - var a; - for (var i = 0; i < actionList.length; i++) { - a = actionList[i]; - a.apply(); - } - return true; - } - ActionListQueue.prototype.stepBackward = function() { - if (!this.inAction || this.lastAction == -1) { - return false; - } - var actionList = this.actionListQueue[this.lastAction]; - var a; - for (var i = 0; i < actionList.length; i++) { - a = actionList[i]; - a.reverse(); - } - this.lastAction -= 1; - return true; - } - ActionListQueue.prototype.goToEnd = function() { - if (!this.inAction) { return; } - while (this.stepForward()) {} - } - ActionListQueue.prototype.goToBeginning = function() { - if (!this.inAction) { return; } - while (this.stepBackward()) {} - } - ActionListQueue.prototype.play = function() { - if (!this.inAction) { return; } - var end = false; - var time = 300; - var step = function(aq) { - var res = aq.stepForward(); - if (res) { - setTimeout(step.bind(aq)); - } - }; - step(this); - } - ActionListQueue.prototype.pause = function() { - clearTimeout(this.playTimeout); - } - - return { - Action: Action, - ActionListQueue: ActionListQueue, - } - - }]); - -angular.module('Tree', ['Enums', 'ActionListQueue']) - .factory('TreeService', ['EnumService', 'ActionLQService', function(EnumService, ActionLQService) { - var TreeNodeTypeEnum = EnumService.TreeNodeTypeEnum; - var Action = ActionLQService.Action; - var ActionListQueue = ActionLQService.ActionListQueue; - - function Tree(rootNode, treeType, depth, branchingFactor) { - this.rootNode = rootNode; - this.treeType = treeType; - this.depth = depth; - this.branchingFactor = branchingFactor; - this.mutable = true; - } - Tree.generateABTreeRootNode = function(treeType, maxDepth, branchingFactor, minVal, maxVal) { - function generateSubTree(parentNode, nodeType, depth, bFac) { - var curNode = new TreeNode(nodeType, parentNode, depth, bFac); - if (depth == maxDepth) { - curNode.nodeType = TreeNodeTypeEnum.leafNode; - curNode.value = Math.round(Math.random() * (maxVal - minVal)) - maxVal; - } else { - for (var k = 0; k < bFac; k++) { - curNode.setKthChild(k, - generateSubTree( - curNode, - TreeNodeTypeEnum.opposite(nodeType), - depth + 1, - bFac - ) - ); - } - } - return curNode; - } - return generateSubTree(null, treeType, 1, branchingFactor); - } - Tree.prototype.alphaBeta = function() { - var thisTree = this; - var generatePruneActionList = function(node, bFac) { - actions = []; - var pruneInner = function(node, bFac, actions) { - if (!node) { return; } - - if (node.edgeToParent) { - actions.push(new Action(node.edgeToParent, 'pruned', false, true)); - node.edgeToParent.__pruned = true; - } - var child; - for (var k = 0; k < bFac; k++) { - child = node.getKthChild(k); - pruneInner(child, bFac, actions); - } - } - pruneInner(node, bFac, actions); - return actions; - } - - var abActions = function(node, bFac, a, b, maxNode, actionLQ) { - var enterActions = [ - new Action(node.edgeToParent, 'entered', false, true), - new Action(node, 'entered', false, true), - ]; - var childActionsList = []; - - if (node.nodeType == TreeNodeTypeEnum.leafNode) { - return { - returnVal: node.value, - enterActions: enterActions, - childActionsList: childActionsList, - exitActions: [new Action(node.edgeToParent, 'entered', true, false)], - }; - } - - enterActions.extend([ - new Action(node, 'alpha', node.alpha, a), - new Action(node, 'beta', node.beta, b), - ]); - node.__alpha = a; - node.__beta = b; - - var k = 0, - pruneRest = false, - lastChildExitActions = [], - curVal = maxNode ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, - child, - childVal, - setValActions, - res; - if (maxNode) { - for (; k < bFac; k++) { - child = node.getKthChild(k); - if (pruneRest) { - lastChildExitActions.extend(generatePruneActionList(child, bFac)); - lastChildExitActions.push( - new Action(node, 'pruned', false, true) - ); - node.__pruned = true; - } else { - res = abActions(child, bFac, a, b, !maxNode, actionLQ); - setValActions = []; - if (res.returnVal > curVal) { - curVal = res.returnVal; - setValActions.push(new Action(node, 'value', node.__value, curVal)); - node.__value = curVal; - } - if (res.returnVal > a) { - a = res.returnVal; - setValActions.extend([ - new Action(node, 'alpha', node.__alpha, a), - ]); - node.__alpha = a; - } - if (res.childActionsList.length) { - res.exitActions.extend(setValActions); - } else { - res.enterActions.extend(setValActions); - } - res.enterActions.extend(lastChildExitActions); - childActionsList.push(res.enterActions); - childActionsList.extend(res.childActionsList); - lastChildExitActions = res.exitActions; - if (b <= a) { - pruneRest = true; - } - } - } - } else { - for (; k < bFac; k++) { - child = node.getKthChild(k); - if (pruneRest) { - lastChildExitActions.extend(generatePruneActionList(child, bFac)); - lastChildExitActions.push( - new Action(node, 'pruned', false, true) - ); - node.__pruned = true; - } else { - res = abActions(child, bFac, a, b, !maxNode, actionLQ); - setValActions = []; - if (res.returnVal < curVal) { - curVal = res.returnVal; - setValActions.push(new Action(node, 'value', node.__value, curVal)); - node.__value = curVal; - } - if (res.returnVal < b) { - b = res.returnVal; - setValActions.extend([ - new Action(node, 'beta', node.__beta, b), - ]); - node.__beta = b; - } - if (res.childActionsList.length) { - res.exitActions.extend(setValActions); - } else { - res.enterActions.extend(setValActions); - } - res.enterActions.extend(lastChildExitActions); - childActionsList.push(res.enterActions); - childActionsList.extend(res.childActionsList); - lastChildExitActions = res.exitActions; - if (b <= a) { - pruneRest = true; - } - } - } - } - childActionsList.push(lastChildExitActions); - var exitActions = [ - new Action(node.edgeToParent, 'entered', true, false), - new Action(node, 'entered', true, false), - ]; - - return { - returnVal: curVal, - enterActions: enterActions, - childActionsList: childActionsList, - exitActions: exitActions, - }; - } - var actionLQ = new ActionListQueue(); - var res = abActions( - this.rootNode, - this.branchingFactor, - Number.NEGATIVE_INFINITY, - Number.POSITIVE_INFINITY, - (this.treeType == TreeNodeTypeEnum.maxNode) - ); - actionLQ.pushActionList(res.enterActions); - actionLQ.extendActionList(res.childActionsList); - actionLQ.pushActionList(res.exitActions); - return actionLQ; - } - Tree.prototype.checkAnswer = function() { - function checkSubTree(node) { - if (node.nodeType == TreeNodeTypeEnum.leafNode) { return true; } - if (node.value != node.__value) { - return false; - } - if (node.edgeToParent && - node.edgeToParent.__pruned && - node.edgeToParent.__pruned != node.edgeToParent.pruned) { - return false; - } - var res = true; - for (var k = 0; k < node.childNum; k++) { - res = res && checkSubTree(node.getKthChild(k)); - } - return res; - } - return checkSubTree(this.rootNode); - } - Tree.prototype.reset = function() { - function resetSubTree(node) { - if (node.edgeToParent) { - node.edgeToParent.entered = false; - node.edgeToParent.pruned = false; - } - node.entered = false; - if (node.nodeType == TreeNodeTypeEnum.leafNode) { return; } - node.value = null; - node.alpha = null; - node.beta = null; - for (var k = 0; k < node.childNum; k++) { - resetSubTree(node.getKthChild(k)); - } - } - resetSubTree(this.rootNode); - } - Tree.prototype.setSolution = function() { - this.alphaBeta(); - function setSolutionForSubTree(node) { - if (node.edgeToParent) { - node.edgeToParent.pruned = node.edgeToParent.__pruned; - } - if (node.nodeType == TreeNodeTypeEnum.leafNode) { return; } - node.value = node.__value; - node.alpha = node.__alpha; - node.beta = node.__beta; - node.pruned = node.__pruned; - for (var k = 0; k < node.childNum; k++) { - setSolutionForSubTree(node.getKthChild(k)); - } - } - setSolutionForSubTree(this.rootNode); - } - - - function TreeNode(nodeType, parentNode, depth, childNum) { - this.nodeType = nodeType; - this.setParent(parentNode); - this.depth = depth; - this.childNum = childNum; - this.children = new Array(childNum); - this.value = null; - } - TreeNode.prototype.setKthChild = function(k, child) { - if (k >= this.childNum) { - throw 'Error: node only holds ' + k + ' children.' - } - this.children[k] = child; - } - TreeNode.prototype.getKthChild = function(k) { - if (k >= this.childNum) { - throw 'Error: node only holds ' + k + ' children.' - } - return this.children[k]; - } - TreeNode.prototype.setParent = function(parentNode) { - if (parentNode) { - this.edgeToParent = new TreeEdge(parentNode, this); - this.parentNode = parentNode; - } - } - - function TreeEdge(source, target) { - this.source = source; - this.target = target; - this.pruned = false; - } - - return { - Tree: Tree, - TreeNode: TreeNode, - TreeEdge: TreeEdge, - } - - }]); - -angular.module('abTreePractice', ['d3', 'Enums', 'Tree']) - .controller('MainCtrl', [ - 'EnumService', - 'TreeService', - '$scope', - '$timeout', - function(EnumService, TreeService, $scope, $timeout) { - var TreeNodeTypeEnum = EnumService.TreeNodeTypeEnum; - var Tree = TreeService.Tree; - - $scope.useAb = true; - $scope.setUseAb = function(bool) { - $scope.useAb = bool; - } - $scope.maxVal = 20; - - $scope.generateRootNode = function(maxFirst) { - $scope.tree.rootNode = Tree.generateABTreeRootNode( - $scope.tree.treeType, - $scope.tree.depth, - $scope.tree.branchingFactor, - -$scope.maxVal, - $scope.maxVal - ); - $scope.actionLQ = null; - }; - $scope.tree = new Tree(null, TreeNodeTypeEnum.maxNode, 4, 3); - $scope.generateRootNode(); - - $scope.incrBranchingFactor = function(incr) { - $scope.tree.branchingFactor = Math.max(2, - $scope.tree.branchingFactor + incr); - $scope.generateRootNode(); - }; - $scope.incrDepth = function(incr) { - $scope.tree.depth = Math.max(3, - $scope.tree.depth + incr); - $scope.generateRootNode(); - }; - $scope.flipMax = function() { - $scope.tree.treeType = TreeNodeTypeEnum.opposite($scope.tree.treeType); - $scope.generateRootNode(); - }; - - $scope.checkAnswer = function() { - if (!$scope.actionLQ) { - $scope.actionLQ = $scope.tree.alphaBeta(); - } - $scope.correct = $scope.tree.checkAnswer(); - } - $scope.correct = null; - - $scope.resetTree = function() { - $scope.tree.reset(); - $scope.reRender(); - } - $scope.showSolution = function() { - $scope.tree.setSolution(); - $scope.reRender(); - } - - $scope.reRender = function() { return; } - $scope.actionLQ = null; - - $scope.toggleABVisual = function() { - if (!$scope.actionLQ) { - $scope.actionLQ = $scope.tree.alphaBeta(); - } - $scope.resetTree(); - if ($scope.actionLQ.inAction) { - $scope.actionLQ.goToBeginning(); - $scope.tree.mutable = true; - $scope.actionLQ.inAction = false; - return; - } - $scope.tree.mutable = false; - $scope.actionLQ.inAction = true; - $scope.correct = null; - } - $scope.stepBackward = function() { - var ret = false; - if ($scope.actionLQ) { - ret = $scope.actionLQ.stepBackward(); - $scope.reRender(); - } - return ret; - } - $scope.stepForward = function() { - var ret = false; - if ($scope.actionLQ) { - ret = $scope.actionLQ.stepForward(); - $scope.reRender(); - } - return ret; - } - $scope.goToBeginning = function() { - $scope.actionLQ.goToBeginning(); - $scope.reRender(); - } - $scope.goToEnd = function() { - $scope.actionLQ.goToEnd(); - $scope.reRender(); - } - - $scope.timeStep = 850; - $scope.play = function() { - var end = false; - var step = function() { - var res = $scope.stepForward(); - if (res) { - $scope.playTimeout = $timeout(step, $scope.timeStep); - } - }; - step(); - } - $scope.pause = function() { - $timeout.cancel($scope.playTimeout); - } - $scope.slider = new Slider('input.slider', { - reversed: true, - formatter: function(value) { - return (value / 1000) + 's per action'; - }, - }).on('slide', function(e) { - $scope.timeStep = e; - }); - - }]) - .directive('abTree', - ['EnumService', - 'd3Service', - '$window', - '$document', - function(EnumService, d3Service, $window, $document) { - var TreeNodeTypeEnum = EnumService.TreeNodeTypeEnum; - return { - restrict: 'E', - scope: { - tree: '=', - reRender: '=', - useAb: '=', - }, - link: function(scope, element, attrs) { - angular.element($document).ready(function () { - var svgMargin = 100, - topMargin = 100, - nodeSideLength = 80, - triNodeHeight = Math.sqrt(Math.pow(nodeSideLength, 2) - - Math.pow((nodeSideLength/2), 2)), - triCenterFromBaseDist = Math.sqrt( - Math.pow((nodeSideLength / Math.sqrt(3)), 2) - - Math.pow((nodeSideLength / 2),2)); - - d3Service.d3().then(function(d3) { - var svgWidth = 0, - svgHeight = 0; - - var svg = d3.select(element[0]) - .append('svg'); - - scope.onResize = function() { - var navbarHeight = angular - .element($document[0].getElementsByClassName('navbar'))[0] - .offsetHeight; - svgWidth = $window.innerWidth; - svgHeight = $window.innerHeight - navbarHeight; - svg.attr('width', svgWidth) - .attr('height', svgHeight); - } - scope.onResize(); - - var lastNodeId = -1; - scope.renderD3Tree = function() { - scope.nodes = []; - scope.links = []; - var root = scope.tree.rootNode, - bFac = scope.tree.branchingFactor, - maxDepth = scope.tree.depth, - yOffset = (svgHeight - (svgMargin + topMargin)) / (maxDepth - 1); - - var renderD3SubTree = function(curNode, xMin, xMax, nodes, links) { - if (!curNode) { return; } - var range = xMax - xMin; - var newOffset = range / bFac; - var yPos = topMargin + (yOffset * (curNode.depth - 1)); - var xPos = xMin + (range / 2); - - curNode.id = ++lastNodeId; - curNode.x = xPos; - curNode.y = yPos; - nodes.push(curNode); - if (curNode.edgeToParent) { - links.push(curNode.edgeToParent); - } - for (var k = 0; k < bFac; k++) { - var kthChild = curNode.getKthChild(k); - renderD3SubTree(kthChild, - xMin + (newOffset * k), - xMin + (newOffset * (k + 1)), - nodes, - links - ); - } - }; - renderD3SubTree(root, svgMargin, svgWidth - svgMargin, - scope.nodes, scope.links); - scope.reRender(); - }; - - scope.$watch(function() { return scope.tree.rootNode; }, - scope.renderD3Tree - ); - scope.$watch('useAb', function() { - scope.reRender(); - }); - - angular.element($window).bind('resize', function() { - scope.onResize(); - clearTimeout(scope.resizeTimeout); - scope.resizeTimeout = setTimeout(function() { - scope.renderD3Tree(); - scope.reRender(); - }, 500); - }); - - // handles to link and node element groups - var path = svg.append('svg:g').selectAll('path'), - vertex = svg.append('svg:g').selectAll('g'); - - // mouse event vars - var selectedNode = null, - mousedownNode = null; - - // compute text width for cursor - function computeTextWidth(text, font) { - // re-use canvas object for better performance - var canvas = computeTextWidth.canvas || - (computeTextWidth.canvas = $document[0].createElement('canvas')); - var context = canvas.getContext('2d'); - context.font = font; - var metrics = context.measureText(text); - return metrics.width; - }; - - // update graph (called when needed) - scope.reRender = function() { - // path (link) group - path = path.data(scope.links, function(link) { - return link.source.id + ',' + link.target.id - }); - - // add new links - var newLinks = path.enter().append('svg:g'); - newLinks.append('svg:path') - .attr('class', 'link'); - newLinks.append('svg:path') - .attr('class', 'mouselink') - .on('mousedown', function(d) { - if (!scope.tree.mutable) { return; } - d.pruned = !d.pruned; - scope.reRender(); - }) - .on('mouseover', function(d) { - // color target link - d3.select(this.parentNode).select('path.link') - .classed('hover', true); - }) - .on('mouseout', function(d) { - // uncolor target link - d3.select(this.parentNode).select('path.link') - .classed('hover', false); - }); - - // remove old links - path.exit().remove(); - - // update existing links - path.select('path.link') - .attr('d', function(d) { - return 'M' + d.source.x + ',' + d.source.y + - 'L' + d.target.x + ',' + d.target.y; - }) - .classed('pruned', function(d) { return d.pruned; }) - .classed('entered', function(d) { - return d.entered; - }); - path.select('path.mouselink') - .attr('d', function(d) { - return 'M' + d.source.x + ',' + d.source.y + - 'L' + d.target.x + ',' + d.target.y; - }); - - // vertex (node) group - vertex = vertex.data(scope.nodes, function(d) { return d.id; }); - - // add new nodes - var newNodes = vertex.enter().append('svg:g') - .classed('node', true) - .classed('leaf', function(d) { - return (d.nodeType == TreeNodeTypeEnum.leafNode); - }); - newNodes.append('svg:path') - .classed('nodepath', true) - .each(function(d) { - d.nodeEle = d3.select(this.parentNode); - }) - .attr('d', function(d) { - var s = nodeSideLength; - if (d.nodeType == TreeNodeTypeEnum.leafNode) { - var ns = s / 2.1; - var a = (s - ns) / 2; - // square leaf nodes - return 'M' + a + ',' + -a + - 'L' + (ns + a) + ',' + -a + - 'L' + (ns + a) + ',' + (-ns - a) + - 'L' + a + ',' + (-ns - a) + - 'L' + a + ',' + -a; - } - var h = triNodeHeight; - // triangular min/max nodes - return 'M' + 0 + ',' + 0 + - 'L' + s + ',' + 0 + - 'L' + (s/2) + ',' + -h + - 'L' + 0 + ',' + 0; - }) - .on('mousedown', function(d) { - // select node - if (!scope.tree.mutable) { return; } - mousedownNode = d; - d.oldVal = d.value; - scope.reRender(); - }); - // show node IDs and alpha-beta - newNodes.append('svg:text') - .attr('class', 'value'); - newNodes.append('svg:text') - .attr('class', 'prunemsg'); - newNodes.append('svg:text') - .attr('class', 'alpha'); - newNodes.append('svg:text') - .attr('class', 'beta'); - - // remove old nodes - vertex.exit().remove(); - - // update existing nodes - vertex - .classed('entered', function(d) { return d.entered; }) - .classed('pruned', function(d) { return d.pruned; }); - vertex.select('path.nodepath') - .attr('transform', function(d) { - var halfSide = nodeSideLength / 2; - var t = '', r = ''; - if (d.nodeType == TreeNodeTypeEnum.leafNode) { - t = 'translate(' + - (d.x - halfSide) + ',' + - (d.y + halfSide) + ')'; - r = ''; - } else if (d.nodeType == TreeNodeTypeEnum.maxNode) { - t = 'translate(' + - (d.x - halfSide) + ',' + - (d.y + triCenterFromBaseDist) + ')'; - } else if (d.nodeType == TreeNodeTypeEnum.minNode) { - t = 'translate(' + - (d.x + halfSide) + ',' + - (d.y - triCenterFromBaseDist) + ')'; - r = ' rotate(180)'; - } - return t + r; - }); - // update existing node values - vertex.select('text.value') - .attr('x', function(d) { return d.x }) - .attr('y', function(d) { return d.y + 6; }) - .text(function(d) { return (d.value != null) ? d.value : ''; }); - // update existing alpha-beta values - vertex.select('text.alpha') - .attr('x', function(d) { return d.x + 45 }) - .attr('y', function(d) { return d.y - 4; }) - .text(function(d) { - if (d.alpha == null || d.beta == null) { return; }; - if (!scope.useAb) { - var val; - if (d.nodeType == TreeNodeTypeEnum.maxNode) { - val = '≥ ' + d.beta.toString().replace('Infinity', '∞'); - } else if (d.nodeType == TreeNodeTypeEnum.minNode) { - val = '≤ ' + d.alpha.toString().replace('Infinity', '∞'); - } - return 'c ' + val; - } - return 'α: ' + d.alpha.toString().replace('Infinity', '∞'); - }); - vertex.select('text.beta') - .attr('x', function(d) { return d.x + 45 }) - .attr('y', function(d) { return d.y + 16; }) - .text(function(d) { - if (d.alpha == null || d.beta == null) { return; }; - if (!scope.useAb) { return; }; - return 'β: ' + d.beta.toString().replace('Infinity', '∞'); - }); - // update existing cursor - vertex.select('rect.cursor') - .attr('x', function(node) { - var nodeVal = node.value; - var valStr = (nodeVal == null) ? '' : nodeVal.toString(); - - var valSVG = d3.select(this.parentNode).select('text').node(); - var valSVGLength = valSVG ? valSVG.getComputedTextLength() : 0; - - var subStrLength = computeTextWidth( - valStr.substring(0, valCharIndex), - '18px Helvetica Neue' - ); - - return node.x + (subStrLength - (valSVGLength / 2)); - }) - .attr('y', function(node) { - return node.y - 9; - }); - }; - - // node value editing variables and functions - var valCharIndex = null, - cursorRect = null, - valStr = null; - function incrValCharIndex() { - valCharIndex = Math.min(valCharIndex + 1, valStr.length); - } - function decrValCharIndex() { - valCharIndex = Math.max(0, valCharIndex - 1); - } - function parseAndSetNodeValue() { - var newVal = parseFloat(valStr); - newVal = (isNaN(newVal)) ? null : newVal; - selectedNode.value = newVal; - - valCharIndex = null; - valStr = null; - selectedNode = null; - cursorRect.remove(); - cursorRect = null; - } - function discardNodeValueChanges() { - selectedNode.value = selectedNode.oldVal; - valCharIndex = null; - valStr = null; - selectedNode = null; - cursorRect.remove(); - cursorRect = null; - } - - function svgMouseDown() { - if (selectedNode && (mousedownNode !== selectedNode)) { - parseAndSetNodeValue(); - } - - if (mousedownNode) { - if (mousedownNode === selectedNode) { return; } - selectedNode = mousedownNode; - mousedownNode = null; - - nodeValue = selectedNode.value - valStr = (nodeValue == null) ? '' : nodeValue.toString(); - valCharIndex = valStr.length; - - cursorRect = selectedNode.nodeEle - .append('svg:rect') - .attr('class', 'cursor') - .attr('height', 16.5) - .attr('width', 1.5) - .attr('opacity', 1); - - (function fadeRepeat() { - if (!cursorRect) { return; } - cursorRect.transition() - .duration(750) - .attr('opacity', 0) - .transition() - .duration(750) - .attr('opacity', 1) - .each('end', fadeRepeat); - })(); - - scope.reRender(); - } - } - - // only respond once per keydown - var lastKeyDown = -1; - - function windowKeyDown() { - - lastKeyDown = d3.event.keyCode; - - // Editing Edge Weights - if (selectedNode) { - var nodeVal = selectedNode.value; - valStr = (nodeVal == null) ? '' : nodeVal.toString(); - if ((lastKeyDown > 47 && lastKeyDown < 58) // number keys - || lastKeyDown == 189 // minus dash - || lastKeyDown == 190) { // decimal point - var leftSlice = valStr.slice(0, valCharIndex), - rightSlice = valStr.slice(valCharIndex, valStr.length), - lastKeyDown = (lastKeyDown > 188) ? (lastKeyDown - 144) : lastKeyDown, - newNum = String.fromCharCode(lastKeyDown); - valStr = leftSlice + newNum + rightSlice; - selectedNode.value = valStr; - incrValCharIndex(); - } else if (lastKeyDown == 8) { // backspace - d3.event.preventDefault(); - var leftSlice = valStr.slice(0, Math.max(0, valCharIndex - 1)), - rightSlice = valStr.slice(valCharIndex, valStr.length); - valStr = leftSlice + rightSlice; - selectedNode.value = valStr; - decrValCharIndex(); - } else if (lastKeyDown == 37) { // left arrow - d3.event.preventDefault(); - decrValCharIndex(); - } else if (lastKeyDown == 39) { // right arrow - d3.event.preventDefault(); - incrValCharIndex(); - } else if (lastKeyDown == 13) { // enter - parseAndSetNodeValue(); - } else if (lastKeyDown == 27) { // escape - discardNodeValueChanges(); - } - scope.reRender(); - return; - } - } - - function windowKeyUp() { - lastKeyDown = -1; - } - - svg.on('mousedown', svgMouseDown); - d3.select(window) - .on('keydown', windowKeyDown) - .on('keyup', windowKeyUp) - }); - }); - }, - }; +Array.prototype.extend = function(array) { + Array.prototype.push.apply(this, array); +} + +angular.module('d3', []) + .factory('d3Service', ['$document', '$q', '$rootScope', + function($document, $q, $rootScope) { + var d = $q.defer(); + function onScriptLoad() { + // Load client in the browser + $rootScope.$apply(function() { d.resolve(window.d3); }); + } + + var scriptTag = $document[0].createElement('script'); + scriptTag.type = 'text/javascript'; + scriptTag.async = true; + scriptTag.src = 'https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js'; + scriptTag.onreadystatechange = function () { + if (this.readyState == 'complete') { onScriptLoad(); } + } + scriptTag.onload = onScriptLoad; + + var s = $document[0].getElementsByTagName('body')[0]; + s.appendChild(scriptTag); + + return { + d3: function() { return d.promise; } + }; + } + ]); + +angular.module('Enums', []) + .factory('EnumService', [function() { + var TreeNodeTypeEnum = { + maxNode: 'maxNode', + minNode: 'minNode', + randNode: 'randNode', + leafNode: 'leafNode', + + opposite: function(t) { + if (t == this.maxNode) { + return this.minNode; + } else if (t == this.minNode) { + return this.maxNode; + } + return t; + }, + }; + + return { + TreeNodeTypeEnum: TreeNodeTypeEnum, + }; + + }]); + +angular.module('ActionListQueue', []) + .factory('ActionLQService', [function() { + + function Action(object, key, oldVal, newVal) { + this.object = object; + this.key = key; + this.oldVal = oldVal; + this.newVal = newVal; + } + Action.prototype.apply = function() { + if (!this.object) { return; } + this.object[this.key] = this.newVal; + } + Action.prototype.reverse = function() { + if (!this.object) { return; } + this.object[this.key] = this.oldVal; + } + + function ActionListQueue() { + this.inAction = false; + this.lastAction = -1; + this.actionListQueue = [] + this.length = 0; + } + ActionListQueue.prototype.pushActionList = function(actionList) { + if (this.inAction) { return false; } + this.actionListQueue.push(actionList); + this.length += 1; + return true; + } + ActionListQueue.prototype.extendActionList = function(actionLists) { + if (this.inAction) { return false; } + this.actionListQueue.extend(actionLists); + this.length += actionLists.length; + return true; + } + ActionListQueue.prototype.stepForward = function() { + if (!this.inAction || + this.lastAction == (this.actionListQueue.length - 1)) { + return false; + } + this.lastAction += 1; + var actionList = this.actionListQueue[this.lastAction]; + var a; + for (var i = 0; i < actionList.length; i++) { + a = actionList[i]; + a.apply(); + } + return true; + } + ActionListQueue.prototype.stepBackward = function() { + if (!this.inAction || this.lastAction == -1) { + return false; + } + var actionList = this.actionListQueue[this.lastAction]; + var a; + for (var i = 0; i < actionList.length; i++) { + a = actionList[i]; + a.reverse(); + } + this.lastAction -= 1; + return true; + } + ActionListQueue.prototype.goToEnd = function() { + if (!this.inAction) { return; } + while (this.stepForward()) {} + } + ActionListQueue.prototype.goToBeginning = function() { + if (!this.inAction) { return; } + while (this.stepBackward()) {} + } + ActionListQueue.prototype.play = function() { + if (!this.inAction) { return; } + var end = false; + var time = 300; + var step = function(aq) { + var res = aq.stepForward(); + if (res) { + setTimeout(step.bind(aq)); + } + }; + step(this); + } + ActionListQueue.prototype.pause = function() { + clearTimeout(this.playTimeout); + } + + return { + Action: Action, + ActionListQueue: ActionListQueue, + } + + }]); + +angular.module('Tree', ['Enums', 'ActionListQueue']) + .factory('TreeService', ['EnumService', 'ActionLQService', function(EnumService, ActionLQService) { + var TreeNodeTypeEnum = EnumService.TreeNodeTypeEnum; + var Action = ActionLQService.Action; + var ActionListQueue = ActionLQService.ActionListQueue; + + function Tree(rootNode, treeType, depth, branchingFactor) { + this.rootNode = rootNode; + this.treeType = treeType; + this.depth = depth; + this.branchingFactor = branchingFactor; + this.mutable = true; + } + Tree.generateABTreeRootNode = function(treeType, maxDepth, branchingFactor, minVal, maxVal) { + function generateSubTree(parentNode, nodeType, depth, bFac) { + var curNode = new TreeNode(nodeType, parentNode, depth, bFac); + if (depth == maxDepth) { + curNode.nodeType = TreeNodeTypeEnum.leafNode; + curNode.value = Math.round(Math.random() * (maxVal - minVal)) - maxVal; + } else { + for (var k = 0; k < bFac; k++) { + curNode.setKthChild(k, + generateSubTree( + curNode, + TreeNodeTypeEnum.opposite(nodeType), + depth + 1, + bFac + ) + ); + } + } + return curNode; + } + return generateSubTree(null, treeType, 1, branchingFactor); + } + Tree.prototype.alphaBeta = function() { + var thisTree = this; + var generatePruneActionList = function(node, bFac) { + actions = []; + var pruneInner = function(node, bFac, actions) { + if (!node) { return; } + + if (node.edgeToParent) { + actions.push(new Action(node.edgeToParent, 'pruned', false, true)); + node.edgeToParent.__pruned = true; + } + var child; + for (var k = 0; k < bFac; k++) { + child = node.getKthChild(k); + pruneInner(child, bFac, actions); + } + } + pruneInner(node, bFac, actions); + return actions; + } + + var abActions = function(node, bFac, a, b, maxNode, actionLQ) { + var enterActions = [ + new Action(node.edgeToParent, 'entered', false, true), + new Action(node, 'entered', false, true), + ]; + var childActionsList = []; + + if (node.nodeType == TreeNodeTypeEnum.leafNode) { + return { + returnVal: node.value, + enterActions: enterActions, + childActionsList: childActionsList, + exitActions: [new Action(node.edgeToParent, 'entered', true, false)], + }; + } + + enterActions.extend([ + new Action(node, 'alpha', node.alpha, a), + new Action(node, 'beta', node.beta, b), + ]); + node.__alpha = a; + node.__beta = b; + + var k = 0, + pruneRest = false, + lastChildExitActions = [], + curVal = maxNode ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + child, + childVal, + setValActions, + res; + if (maxNode) { + for (; k < bFac; k++) { + child = node.getKthChild(k); + if (pruneRest) { + lastChildExitActions.extend(generatePruneActionList(child, bFac)); + lastChildExitActions.push( + new Action(node, 'pruned', false, true) + ); + node.__pruned = true; + } else { + res = abActions(child, bFac, a, b, !maxNode, actionLQ); + setValActions = []; + if (res.returnVal > curVal) { + curVal = res.returnVal; + setValActions.push(new Action(node, 'value', node.__value, curVal)); + node.__value = curVal; + } + if (res.returnVal > a) { + a = res.returnVal; + setValActions.extend([ + new Action(node, 'alpha', node.__alpha, a), + ]); + node.__alpha = a; + } + if (res.childActionsList.length) { + res.exitActions.extend(setValActions); + } else { + res.enterActions.extend(setValActions); + } + res.enterActions.extend(lastChildExitActions); + childActionsList.push(res.enterActions); + childActionsList.extend(res.childActionsList); + lastChildExitActions = res.exitActions; + if (b <= a) { + pruneRest = true; + } + } + } + } else { + for (; k < bFac; k++) { + child = node.getKthChild(k); + if (pruneRest) { + lastChildExitActions.extend(generatePruneActionList(child, bFac)); + lastChildExitActions.push( + new Action(node, 'pruned', false, true) + ); + node.__pruned = true; + } else { + res = abActions(child, bFac, a, b, !maxNode, actionLQ); + setValActions = []; + if (res.returnVal < curVal) { + curVal = res.returnVal; + setValActions.push(new Action(node, 'value', node.__value, curVal)); + node.__value = curVal; + } + if (res.returnVal < b) { + b = res.returnVal; + setValActions.extend([ + new Action(node, 'beta', node.__beta, b), + ]); + node.__beta = b; + } + if (res.childActionsList.length) { + res.exitActions.extend(setValActions); + } else { + res.enterActions.extend(setValActions); + } + res.enterActions.extend(lastChildExitActions); + childActionsList.push(res.enterActions); + childActionsList.extend(res.childActionsList); + lastChildExitActions = res.exitActions; + if (b <= a) { + pruneRest = true; + } + } + } + } + childActionsList.push(lastChildExitActions); + var exitActions = [ + new Action(node.edgeToParent, 'entered', true, false), + new Action(node, 'entered', true, false), + ]; + + return { + returnVal: curVal, + enterActions: enterActions, + childActionsList: childActionsList, + exitActions: exitActions, + }; + } + var actionLQ = new ActionListQueue(); + var res = abActions( + this.rootNode, + this.branchingFactor, + Number.NEGATIVE_INFINITY, + Number.POSITIVE_INFINITY, + (this.treeType == TreeNodeTypeEnum.maxNode) + ); + actionLQ.pushActionList(res.enterActions); + actionLQ.extendActionList(res.childActionsList); + actionLQ.pushActionList(res.exitActions); + return actionLQ; + } + Tree.prototype.checkAnswer = function() { + function checkSubTree(node) { + if (node.nodeType == TreeNodeTypeEnum.leafNode) { return true; } + if (node.value != node.__value) { + return false; + } + if (node.edgeToParent && + node.edgeToParent.__pruned && + node.edgeToParent.__pruned != node.edgeToParent.pruned) { + return false; + } + var res = true; + for (var k = 0; k < node.childNum; k++) { + res = res && checkSubTree(node.getKthChild(k)); + } + return res; + } + return checkSubTree(this.rootNode); + } + Tree.prototype.reset = function() { + function resetSubTree(node) { + if (node.edgeToParent) { + node.edgeToParent.entered = false; + node.edgeToParent.pruned = false; + } + node.entered = false; + if (node.nodeType == TreeNodeTypeEnum.leafNode) { return; } + node.value = null; + node.alpha = null; + node.beta = null; + for (var k = 0; k < node.childNum; k++) { + resetSubTree(node.getKthChild(k)); + } + } + resetSubTree(this.rootNode); + } + Tree.prototype.setSolution = function() { + this.alphaBeta(); + function setSolutionForSubTree(node) { + if (node.edgeToParent) { + node.edgeToParent.pruned = node.edgeToParent.__pruned; + } + if (node.nodeType == TreeNodeTypeEnum.leafNode) { return; } + node.value = node.__value; + node.alpha = node.__alpha; + node.beta = node.__beta; + node.pruned = node.__pruned; + for (var k = 0; k < node.childNum; k++) { + setSolutionForSubTree(node.getKthChild(k)); + } + } + setSolutionForSubTree(this.rootNode); + } + + + function TreeNode(nodeType, parentNode, depth, childNum) { + this.nodeType = nodeType; + this.setParent(parentNode); + this.depth = depth; + this.childNum = childNum; + this.children = new Array(childNum); + this.value = null; + } + TreeNode.prototype.setKthChild = function(k, child) { + if (k >= this.childNum) { + throw 'Error: node only holds ' + k + ' children.' + } + this.children[k] = child; + } + TreeNode.prototype.getKthChild = function(k) { + if (k >= this.childNum) { + throw 'Error: node only holds ' + k + ' children.' + } + return this.children[k]; + } + TreeNode.prototype.setParent = function(parentNode) { + if (parentNode) { + this.edgeToParent = new TreeEdge(parentNode, this); + this.parentNode = parentNode; + } + } + + function TreeEdge(source, target) { + this.source = source; + this.target = target; + this.pruned = false; + } + + return { + Tree: Tree, + TreeNode: TreeNode, + TreeEdge: TreeEdge, + } + + }]); + +angular.module('abTreePractice', ['d3', 'Enums', 'Tree']) + .controller('MainCtrl', [ + 'EnumService', + 'TreeService', + '$scope', + '$timeout', + function(EnumService, TreeService, $scope, $timeout) { + var TreeNodeTypeEnum = EnumService.TreeNodeTypeEnum; + var Tree = TreeService.Tree; + + $scope.useAb = true; + $scope.setUseAb = function(bool) { + $scope.useAb = bool; + } + $scope.maxVal = 20; + + $scope.generateRootNode = function(maxFirst) { + $scope.tree.rootNode = Tree.generateABTreeRootNode( + $scope.tree.treeType, + $scope.tree.depth, + $scope.tree.branchingFactor, + -$scope.maxVal, + $scope.maxVal + ); + $scope.actionLQ = null; + }; + $scope.tree = new Tree(null, TreeNodeTypeEnum.maxNode, 4, 3); + $scope.generateRootNode(); + + $scope.incrBranchingFactor = function(incr) { + $scope.tree.branchingFactor = Math.max(2, + $scope.tree.branchingFactor + incr); + $scope.generateRootNode(); + }; + $scope.incrDepth = function(incr) { + $scope.tree.depth = Math.max(3, + $scope.tree.depth + incr); + $scope.generateRootNode(); + }; + $scope.flipMax = function() { + $scope.tree.treeType = TreeNodeTypeEnum.opposite($scope.tree.treeType); + $scope.generateRootNode(); + }; + + $scope.checkAnswer = function() { + if (!$scope.actionLQ) { + $scope.actionLQ = $scope.tree.alphaBeta(); + } + $scope.correct = $scope.tree.checkAnswer(); + } + $scope.correct = null; + + $scope.resetTree = function() { + $scope.tree.reset(); + $scope.reRender(); + } + $scope.showSolution = function() { + $scope.tree.setSolution(); + $scope.reRender(); + } + + $scope.reRender = function() { return; } + $scope.actionLQ = null; + + $scope.toggleABVisual = function() { + if (!$scope.actionLQ) { + $scope.actionLQ = $scope.tree.alphaBeta(); + } + $scope.resetTree(); + if ($scope.actionLQ.inAction) { + $scope.actionLQ.goToBeginning(); + $scope.tree.mutable = true; + $scope.actionLQ.inAction = false; + return; + } + $scope.tree.mutable = false; + $scope.actionLQ.inAction = true; + $scope.correct = null; + } + $scope.stepBackward = function() { + var ret = false; + if ($scope.actionLQ) { + ret = $scope.actionLQ.stepBackward(); + $scope.reRender(); + } + return ret; + } + $scope.stepForward = function() { + var ret = false; + if ($scope.actionLQ) { + ret = $scope.actionLQ.stepForward(); + $scope.reRender(); + } + return ret; + } + $scope.goToBeginning = function() { + $scope.actionLQ.goToBeginning(); + $scope.reRender(); + } + $scope.goToEnd = function() { + $scope.actionLQ.goToEnd(); + $scope.reRender(); + } + + $scope.timeStep = 850; + $scope.play = function() { + var end = false; + var step = function() { + var res = $scope.stepForward(); + if (res) { + $scope.playTimeout = $timeout(step, $scope.timeStep); + } + }; + step(); + } + $scope.pause = function() { + $timeout.cancel($scope.playTimeout); + } + $scope.slider = new Slider('input.slider', { + reversed: true, + formatter: function(value) { + return (value / 1000) + 's per action'; + }, + }).on('slide', function(e) { + $scope.timeStep = e; + }); + + }]) + .directive('abTree', + ['EnumService', + 'd3Service', + '$window', + '$document', + function(EnumService, d3Service, $window, $document) { + var TreeNodeTypeEnum = EnumService.TreeNodeTypeEnum; + return { + restrict: 'E', + scope: { + tree: '=', + reRender: '=', + useAb: '=', + }, + link: function(scope, element, attrs) { + angular.element($document).ready(function () { + var svgMargin = 100, + topMargin = 100, + nodeSideLength = 80, + triNodeHeight = Math.sqrt(Math.pow(nodeSideLength, 2) - + Math.pow((nodeSideLength/2), 2)), + triCenterFromBaseDist = Math.sqrt( + Math.pow((nodeSideLength / Math.sqrt(3)), 2) - + Math.pow((nodeSideLength / 2),2)); + + d3Service.d3().then(function(d3) { + var svgWidth = 0, + svgHeight = 0; + + var svg = d3.select(element[0]) + .append('svg'); + + scope.onResize = function() { + var navbarHeight = angular + .element($document[0].getElementsByClassName('navbar'))[0] + .offsetHeight; + svgWidth = $window.innerWidth; + svgHeight = $window.innerHeight - navbarHeight; + svg.attr('width', svgWidth) + .attr('height', svgHeight); + } + scope.onResize(); + + var lastNodeId = -1; + scope.renderD3Tree = function() { + scope.nodes = []; + scope.links = []; + var root = scope.tree.rootNode, + bFac = scope.tree.branchingFactor, + maxDepth = scope.tree.depth, + yOffset = (svgHeight - (svgMargin + topMargin)) / (maxDepth - 1); + + var renderD3SubTree = function(curNode, xMin, xMax, nodes, links) { + if (!curNode) { return; } + var range = xMax - xMin; + var newOffset = range / bFac; + var yPos = topMargin + (yOffset * (curNode.depth - 1)); + var xPos = xMin + (range / 2); + + curNode.id = ++lastNodeId; + curNode.x = xPos; + curNode.y = yPos; + nodes.push(curNode); + if (curNode.edgeToParent) { + links.push(curNode.edgeToParent); + } + for (var k = 0; k < bFac; k++) { + var kthChild = curNode.getKthChild(k); + renderD3SubTree(kthChild, + xMin + (newOffset * k), + xMin + (newOffset * (k + 1)), + nodes, + links + ); + } + }; + renderD3SubTree(root, svgMargin, svgWidth - svgMargin, + scope.nodes, scope.links); + scope.reRender(); + }; + + scope.$watch(function() { return scope.tree.rootNode; }, + scope.renderD3Tree + ); + scope.$watch('useAb', function() { + scope.reRender(); + }); + + angular.element($window).bind('resize', function() { + scope.onResize(); + clearTimeout(scope.resizeTimeout); + scope.resizeTimeout = setTimeout(function() { + scope.renderD3Tree(); + scope.reRender(); + }, 500); + }); + + // handles to link and node element groups + var path = svg.append('svg:g').selectAll('path'), + vertex = svg.append('svg:g').selectAll('g'); + + // mouse event vars + var selectedNode = null, + mousedownNode = null; + + // compute text width for cursor + function computeTextWidth(text, font) { + // re-use canvas object for better performance + var canvas = computeTextWidth.canvas || + (computeTextWidth.canvas = $document[0].createElement('canvas')); + var context = canvas.getContext('2d'); + context.font = font; + var metrics = context.measureText(text); + return metrics.width; + }; + + // update graph (called when needed) + scope.reRender = function() { + // path (link) group + path = path.data(scope.links, function(link) { + return link.source.id + ',' + link.target.id + }); + + // add new links + var newLinks = path.enter().append('svg:g'); + newLinks.append('svg:path') + .attr('class', 'link'); + newLinks.append('svg:path') + .attr('class', 'mouselink') + .on('mousedown', function(d) { + if (!scope.tree.mutable) { return; } + d.pruned = !d.pruned; + scope.reRender(); + }) + .on('mouseover', function(d) { + // color target link + d3.select(this.parentNode).select('path.link') + .classed('hover', true); + }) + .on('mouseout', function(d) { + // uncolor target link + d3.select(this.parentNode).select('path.link') + .classed('hover', false); + }); + + // remove old links + path.exit().remove(); + + // update existing links + path.select('path.link') + .attr('d', function(d) { + return 'M' + d.source.x + ',' + d.source.y + + 'L' + d.target.x + ',' + d.target.y; + }) + .classed('pruned', function(d) { return d.pruned; }) + .classed('entered', function(d) { + return d.entered; + }); + path.select('path.mouselink') + .attr('d', function(d) { + return 'M' + d.source.x + ',' + d.source.y + + 'L' + d.target.x + ',' + d.target.y; + }); + + // vertex (node) group + vertex = vertex.data(scope.nodes, function(d) { return d.id; }); + + // add new nodes + var newNodes = vertex.enter().append('svg:g') + .classed('node', true) + .classed('leaf', function(d) { + return (d.nodeType == TreeNodeTypeEnum.leafNode); + }); + newNodes.append('svg:path') + .classed('nodepath', true) + .each(function(d) { + d.nodeEle = d3.select(this.parentNode); + }) + .attr('d', function(d) { + var s = nodeSideLength; + if (d.nodeType == TreeNodeTypeEnum.leafNode) { + var ns = s / 2.1; + var a = (s - ns) / 2; + // square leaf nodes + return 'M' + a + ',' + -a + + 'L' + (ns + a) + ',' + -a + + 'L' + (ns + a) + ',' + (-ns - a) + + 'L' + a + ',' + (-ns - a) + + 'L' + a + ',' + -a; + } + var h = triNodeHeight; + // triangular min/max nodes + return 'M' + 0 + ',' + 0 + + 'L' + s + ',' + 0 + + 'L' + (s/2) + ',' + -h + + 'L' + 0 + ',' + 0; + }) + .on('mousedown', function(d) { + // select node + if (!scope.tree.mutable) { return; } + mousedownNode = d; + d.oldVal = d.value; + scope.reRender(); + }); + // show node IDs and alpha-beta + newNodes.append('svg:text') + .attr('class', 'value'); + newNodes.append('svg:text') + .attr('class', 'prunemsg'); + newNodes.append('svg:text') + .attr('class', 'alpha'); + newNodes.append('svg:text') + .attr('class', 'beta'); + + // remove old nodes + vertex.exit().remove(); + + // update existing nodes + vertex + .classed('entered', function(d) { return d.entered; }) + .classed('pruned', function(d) { return d.pruned; }); + vertex.select('path.nodepath') + .attr('transform', function(d) { + var halfSide = nodeSideLength / 2; + var t = '', r = ''; + if (d.nodeType == TreeNodeTypeEnum.leafNode) { + t = 'translate(' + + (d.x - halfSide) + ',' + + (d.y + halfSide) + ')'; + r = ''; + } else if (d.nodeType == TreeNodeTypeEnum.maxNode) { + t = 'translate(' + + (d.x - halfSide) + ',' + + (d.y + triCenterFromBaseDist) + ')'; + } else if (d.nodeType == TreeNodeTypeEnum.minNode) { + t = 'translate(' + + (d.x + halfSide) + ',' + + (d.y - triCenterFromBaseDist) + ')'; + r = ' rotate(180)'; + } + return t + r; + }); + // update existing node values + vertex.select('text.value') + .attr('x', function(d) { return d.x }) + .attr('y', function(d) { return d.y + 6; }) + .text(function(d) { return (d.value != null) ? d.value : ''; }); + // update existing alpha-beta values + vertex.select('text.alpha') + .attr('x', function(d) { return d.x + 45 }) + .attr('y', function(d) { return d.y - 4; }) + .text(function(d) { + if (d.alpha == null || d.beta == null) { return; }; + if (!scope.useAb) { + var val; + if (d.nodeType == TreeNodeTypeEnum.maxNode) { + val = '≥ ' + d.beta.toString().replace('Infinity', '∞'); + } else if (d.nodeType == TreeNodeTypeEnum.minNode) { + val = '≤ ' + d.alpha.toString().replace('Infinity', '∞'); + } + return 'c ' + val; + } + return 'α: ' + d.alpha.toString().replace('Infinity', '∞'); + }); + vertex.select('text.beta') + .attr('x', function(d) { return d.x + 45 }) + .attr('y', function(d) { return d.y + 16; }) + .text(function(d) { + if (d.alpha == null || d.beta == null) { return; }; + if (!scope.useAb) { return; }; + return 'β: ' + d.beta.toString().replace('Infinity', '∞'); + }); + // update existing cursor + vertex.select('rect.cursor') + .attr('x', function(node) { + var nodeVal = node.value; + var valStr = (nodeVal == null) ? '' : nodeVal.toString(); + + var valSVG = d3.select(this.parentNode).select('text').node(); + var valSVGLength = valSVG ? valSVG.getComputedTextLength() : 0; + + var subStrLength = computeTextWidth( + valStr.substring(0, valCharIndex), + '18px Helvetica Neue' + ); + + return node.x + (subStrLength - (valSVGLength / 2)); + }) + .attr('y', function(node) { + return node.y - 9; + }); + }; + + // node value editing variables and functions + var valCharIndex = null, + cursorRect = null, + valStr = null; + function incrValCharIndex() { + valCharIndex = Math.min(valCharIndex + 1, valStr.length); + } + function decrValCharIndex() { + valCharIndex = Math.max(0, valCharIndex - 1); + } + function parseAndSetNodeValue() { + var newVal = parseFloat(valStr); + newVal = (isNaN(newVal)) ? null : newVal; + selectedNode.value = newVal; + + valCharIndex = null; + valStr = null; + selectedNode = null; + cursorRect.remove(); + cursorRect = null; + } + function discardNodeValueChanges() { + selectedNode.value = selectedNode.oldVal; + valCharIndex = null; + valStr = null; + selectedNode = null; + cursorRect.remove(); + cursorRect = null; + } + + function svgMouseDown() { + if (selectedNode && (mousedownNode !== selectedNode)) { + parseAndSetNodeValue(); + } + + if (mousedownNode) { + if (mousedownNode === selectedNode) { return; } + selectedNode = mousedownNode; + mousedownNode = null; + + nodeValue = selectedNode.value + valStr = (nodeValue == null) ? '' : nodeValue.toString(); + valCharIndex = valStr.length; + + cursorRect = selectedNode.nodeEle + .append('svg:rect') + .attr('class', 'cursor') + .attr('height', 16.5) + .attr('width', 1.5) + .attr('opacity', 1); + + (function fadeRepeat() { + if (!cursorRect) { return; } + cursorRect.transition() + .duration(750) + .attr('opacity', 0) + .transition() + .duration(750) + .attr('opacity', 1) + .each('end', fadeRepeat); + })(); + + scope.reRender(); + } + } + + // only respond once per keydown + var lastKeyDown = -1; + + function windowKeyDown() { + + lastKeyDown = d3.event.keyCode; + + // Editing Edge Weights + if (selectedNode) { + var nodeVal = selectedNode.value; + valStr = (nodeVal == null) ? '' : nodeVal.toString(); + if ((lastKeyDown > 47 && lastKeyDown < 58) // number keys + || lastKeyDown == 189 // minus dash + || lastKeyDown == 190) { // decimal point + var leftSlice = valStr.slice(0, valCharIndex), + rightSlice = valStr.slice(valCharIndex, valStr.length), + lastKeyDown = (lastKeyDown > 188) ? (lastKeyDown - 144) : lastKeyDown, + newNum = String.fromCharCode(lastKeyDown); + valStr = leftSlice + newNum + rightSlice; + selectedNode.value = valStr; + incrValCharIndex(); + } else if (lastKeyDown == 8) { // backspace + d3.event.preventDefault(); + var leftSlice = valStr.slice(0, Math.max(0, valCharIndex - 1)), + rightSlice = valStr.slice(valCharIndex, valStr.length); + valStr = leftSlice + rightSlice; + selectedNode.value = valStr; + decrValCharIndex(); + } else if (lastKeyDown == 37) { // left arrow + d3.event.preventDefault(); + decrValCharIndex(); + } else if (lastKeyDown == 39) { // right arrow + d3.event.preventDefault(); + incrValCharIndex(); + } else if (lastKeyDown == 13) { // enter + parseAndSetNodeValue(); + } else if (lastKeyDown == 27) { // escape + discardNodeValueChanges(); + } + scope.reRender(); + return; + } + } + + function windowKeyUp() { + lastKeyDown = -1; + } + + svg.on('mousedown', svgMouseDown); + d3.select(window) + .on('keydown', windowKeyDown) + .on('keyup', windowKeyUp) + }); + }); + }, + }; }]); \ No newline at end of file diff --git a/javascript/AlphaBetaPruning/index.html b/javascript/AlphaBetaPruning/index.html index 4cb8c63a7..b3dd0a0e4 100644 --- a/javascript/AlphaBetaPruning/index.html +++ b/javascript/AlphaBetaPruning/index.html @@ -1,145 +1,145 @@ - - - - - Alpha-Beta Pruning Practice - - - - - - - - - - - - - -

-
- -
-
- -
-
-
-
- - - - - - -
-
-
-
-
- {{((actionLQ.lastAction + 1) / actionLQ.length) * 100}}% Complete (success) -
-
-
-
- - - -
-
-
-
-
-
- -
-
-
- - -
-
-
-
-
- -
-
-
- - -
-
-
-
-
-
- -
-
- -
-
-
-
- -
-
- -
-
-
-
- -
-
- -
-
-
-
-
-
- Nodes are pruned when {{useAb ? 'β ≤ α' : 'value is in cutoff range'}}. -
- + + + + + Alpha-Beta Pruning Practice + + + + + + + + + + + + + + +
+ +
+
+ +
+
+
+
+ + + + + + +
+
+
+
+
+ {{((actionLQ.lastAction + 1) / actionLQ.length) * 100}}% Complete (success) +
+
+
+
+ + + +
+
+
+
+
+
+ +
+
+
+ + +
+
+
+
+
+ +
+
+
+ + +
+
+
+
+
+
+ +
+
+ +
+
+
+
+ +
+
+ +
+
+
+
+ +
+
+ +
+
+
+
+
+
+ Nodes are pruned when {{useAb ? 'β ≤ α' : 'value is in cutoff range'}}. +
+ \ No newline at end of file diff --git a/np.cpp b/np.cpp index b20a64a47..769adedf8 100644 --- a/np.cpp +++ b/np.cpp @@ -1,115 +1,115 @@ -#include -#include -#include -#include -using namespace std; -struct node -{ - int data; - struct node* left; - struct node* right; -}; -typedef struct node N; -int search(int arr[], int strt, int end, int value); -struct node* newNode(int data); - - -struct node* buildTree(int in[], int pre[], int inStrt, int inEnd) -{ - static int preIndex = 0; - - if(inStrt > inEnd) - return NULL; - - - struct node *tNode = newNode(pre[preIndex++]); - - if(inStrt == inEnd) - return tNode; - - int inIndex = search(in, inStrt, inEnd, tNode->data); - - - tNode->left = buildTree(in, pre, inStrt, inIndex-1); - tNode->right = buildTree(in, pre, inIndex+1, inEnd); - - return tNode; -} - -int search(int arr[], int strt, int end, int value) -{ - int i; - for(i = strt; i <= end; i++) - { - if(arr[i] == value) - return i; - } -} - -struct node* newNode(int data) -{ - struct node* node = (struct node*)malloc(sizeof(struct node)); - node->data = data; - node->left = NULL; - node->right = NULL; - - return(node); -} - -void printPostorder(struct node* node) -{ - if (node == NULL) - return; - - printPostorder(node->left); - - printPostorder(node->right); - - cout<data; -} -int rtls(N *root, int val)// Root To Leaf Sum -{ - if(root==NULL) - { - if(val==0) - return root->data; - else - return 0; - } - - int total=val-root->data; - if(root->left==NULL && root->right==NULL && total==0) - return root->data; - else - return 0; - - bool X,Y; - if(root->left) - X = rtls(root->left, total); - if(root->right) - Y = rtls(root->right, total); - - if(X||Y) - return root->data; - - -} -int main() -{ - int n,i,val; - cin>>n; - int in[n+1],pre[n+1]; - for(i=0;i>in[i]; - } - for(i=0;i>pre[i]; - } - cin>>val; - struct node *root = buildTree(in, pre, 0, n - 1); - cout< +#include +#include +#include +using namespace std; +struct node +{ + int data; + struct node* left; + struct node* right; +}; +typedef struct node N; +int search(int arr[], int strt, int end, int value); +struct node* newNode(int data); + + +struct node* buildTree(int in[], int pre[], int inStrt, int inEnd) +{ + static int preIndex = 0; + + if(inStrt > inEnd) + return NULL; + + + struct node *tNode = newNode(pre[preIndex++]); + + if(inStrt == inEnd) + return tNode; + + int inIndex = search(in, inStrt, inEnd, tNode->data); + + + tNode->left = buildTree(in, pre, inStrt, inIndex-1); + tNode->right = buildTree(in, pre, inIndex+1, inEnd); + + return tNode; +} + +int search(int arr[], int strt, int end, int value) +{ + int i; + for(i = strt; i <= end; i++) + { + if(arr[i] == value) + return i; + } +} + +struct node* newNode(int data) +{ + struct node* node = (struct node*)malloc(sizeof(struct node)); + node->data = data; + node->left = NULL; + node->right = NULL; + + return(node); +} + +void printPostorder(struct node* node) +{ + if (node == NULL) + return; + + printPostorder(node->left); + + printPostorder(node->right); + + cout<data; +} +int rtls(N *root, int val)// Root To Leaf Sum +{ + if(root==NULL) + { + if(val==0) + return root->data; + else + return 0; + } + + int total=val-root->data; + if(root->left==NULL && root->right==NULL && total==0) + return root->data; + else + return 0; + + bool X,Y; + if(root->left) + X = rtls(root->left, total); + if(root->right) + Y = rtls(root->right, total); + + if(X||Y) + return root->data; + + +} +int main() +{ + int n,i,val; + cin>>n; + int in[n+1],pre[n+1]; + for(i=0;i>in[i]; + } + for(i=0;i>pre[i]; + } + cin>>val; + struct node *root = buildTree(in, pre, 0, n - 1); + cout< - -linear search - - -alert('Index of ".$k." is ".$i+1 ."')"; - } - } - return -1; - echo ""; - } - -?> - - + + +linear search + + +alert('Index of ".$k." is ".$i+1 ."')"; + } + } + return -1; + echo ""; + } + +?> + + diff --git a/php/algorithms/quickSort.php b/php/algorithms/quickSort.php deleted file mode 100644 index 3dff68d20..000000000 --- a/php/algorithms/quickSort.php +++ /dev/null @@ -1,30 +0,0 @@ -= inc and items[j-inc] > temp: - items[j] = items[j - inc] - j -= inc - items[j] = temp - inc = inc/2 if inc/2 else (0 if inc==1 else 1) - -a = [35, -8, 11, 1, 68, 0, 3]; -shellSort(a) -print a # [-8, 0, 1, 3, 11, 35, 68] diff --git a/python/algorithms/TernarySearch.py b/python/algorithms/TernarySearch.py index 9d4a00119..47bc01859 100644 --- a/python/algorithms/TernarySearch.py +++ b/python/algorithms/TernarySearch.py @@ -1,32 +1,32 @@ -def ternary_search(A, l, r, val): - if r >= l: - mid1 = l + (r - l) // 3 - mid2 = r - (r - l) // 3 - - if A[mid1] == val: - return mid1 - - if A[mid2] == val: - return mid2 - - if val < A[mid1]: - return ternary_search(A, l, mid1 - 1, val) - - elif val > A[mid2]: - return ternary_search(A, mid2 + 1, r, val) - - else: - return ternary_search(A, mid1 + 1, mid2 - 1, val) - - return -1 - -A = list(map(int, input().split())) -val = int(input()) - -idx = ternary_search(A, 0, len(A) - 1, val) - -if idx == -1: - print('Element not found!') -else: - print('Element found at index', idx) - +def ternary_search(A, l, r, val): + if r >= l: + mid1 = l + (r - l) // 3 + mid2 = r - (r - l) // 3 + + if A[mid1] == val: + return mid1 + + if A[mid2] == val: + return mid2 + + if val < A[mid1]: + return ternary_search(A, l, mid1 - 1, val) + + elif val > A[mid2]: + return ternary_search(A, mid2 + 1, r, val) + + else: + return ternary_search(A, mid1 + 1, mid2 - 1, val) + + return -1 + +A = list(map(int, input().split())) +val = int(input()) + +idx = ternary_search(A, 0, len(A) - 1, val) + +if idx == -1: + print('Element not found!') +else: + print('Element found at index', idx) + diff --git a/python/algorithms/breadth_first_search.py b/python/algorithms/breadth_first_search.py index 2eae993fd..e446d088c 100644 --- a/python/algorithms/breadth_first_search.py +++ b/python/algorithms/breadth_first_search.py @@ -1,108 +1,108 @@ -from collections import deque -import numpy as np -from copy import deepcopy -import math -class Graph: - """ - Implementation of a graph with Adjacency Matrix - """ - def __init__(self,size,directed = False): - self.size = size - self.matrix = [[0 for i in range(self.size)] for j in range(self.size)] - self.directed = directed - self.Time = 0 - self.color = {i:"white" for i in range(self.size)} - self.parent = [-1 for i in range(self.size)] - self.time = [[0,0] for i in range(self.size)] - - def has_vertex(self,i): - return i>=0 and i0: - u = qu.popleft() - for v in self.adjacent_vertices(u): - if color[v] == "white": - color[v] = "gray" - distance[v] = distance[u] + 1 - parent[v] = u - qu.append(v) - color[u] = "black" - print("Color",color) - print("Parent",parent) - print("Distance",distance) - - def bfs_iterative(self,s): - seen = set({}) - stack = deque([s]) - trail = [] - while len(stack)>0: - u = stack.popleft() - if u in seen: - continue - seen.add(u) - trail.append(u) - for v in self.adjacent_vertices(u): - stack.append(v) - return trail - -## Test Cases -##g1 = Graph(4) -##g1.directed = False -##g1.addEdge(0, 1) -##g1.addEdge(0, 2) -##g1.addEdge(1, 2) -##g1.addEdge(2, 3) -##g1.bfs_colors() - -##g2 = Graph(3) -##g2.directed = False -##g2.addEdge(0, 1) -##g2.addEdge(1, 2) -##g2.addEdge(2, 0) -##g2.bfs_iterative() - - - - +from collections import deque +import numpy as np +from copy import deepcopy +import math +class Graph: + """ + Implementation of a graph with Adjacency Matrix + """ + def __init__(self,size,directed = False): + self.size = size + self.matrix = [[0 for i in range(self.size)] for j in range(self.size)] + self.directed = directed + self.Time = 0 + self.color = {i:"white" for i in range(self.size)} + self.parent = [-1 for i in range(self.size)] + self.time = [[0,0] for i in range(self.size)] + + def has_vertex(self,i): + return i>=0 and i0: + u = qu.popleft() + for v in self.adjacent_vertices(u): + if color[v] == "white": + color[v] = "gray" + distance[v] = distance[u] + 1 + parent[v] = u + qu.append(v) + color[u] = "black" + print("Color",color) + print("Parent",parent) + print("Distance",distance) + + def bfs_iterative(self,s): + seen = set({}) + stack = deque([s]) + trail = [] + while len(stack)>0: + u = stack.popleft() + if u in seen: + continue + seen.add(u) + trail.append(u) + for v in self.adjacent_vertices(u): + stack.append(v) + return trail + +## Test Cases +##g1 = Graph(4) +##g1.directed = False +##g1.addEdge(0, 1) +##g1.addEdge(0, 2) +##g1.addEdge(1, 2) +##g1.addEdge(2, 3) +##g1.bfs_colors() + +##g2 = Graph(3) +##g2.directed = False +##g2.addEdge(0, 1) +##g2.addEdge(1, 2) +##g2.addEdge(2, 0) +##g2.bfs_iterative() + + + + diff --git a/python/algorithms/interpolationSearch.py b/python/algorithms/interpolationSearch.py deleted file mode 100644 index 9e23b42a5..000000000 --- a/python/algorithms/interpolationSearch.py +++ /dev/null @@ -1,30 +0,0 @@ -'''This search algorithm works on the probing position of the required value. -For this algorithm to work properly, the data collection should be in a sorted form and equally distributed. -Initially, the probe position is the position of the middle most item of the collection. -If a match occurs, then the index of the item is returned. -If the middle item is greater than the item, then the probe position is again calculated in the sub-array -to the right of the middle item. Otherwise, the item is searched in the subarray to the left of the middle item. -This process continues on the sub-array as well until the size of subarray reduces to zero.''' - -def intpolsearch(values,x ): - idx0 = 0 - idxn = (len(values) - 1) - - while idx0 <= idxn and x >= values[idx0] and x <= values[idxn]: - -# Find the mid point - mid = idx0 +\ - int(((float(idxn - idx0)/( values[idxn] - values[idx0])) - * ( x - values[idx0]))) - -# Compare the value at mid point with search value - if values[mid] == x: - return "Found "+str(x)+" at index "+str(mid) - - if values[mid] < x: - idx0 = mid + 1 - return "Searched element not in the list" - - -l = [1, 2, 3, 4, 5, 6, 7, 8] -print(intpolsearch(4, 6)) diff --git a/python/algorithms/topological_sort.py b/python/algorithms/topological_sort.py index 17098bef1..07f0170eb 100644 --- a/python/algorithms/topological_sort.py +++ b/python/algorithms/topological_sort.py @@ -1,73 +1,73 @@ -from collections import deque -import numpy as np -from copy import deepcopy -import math -class Graph: - """ - Implementation of a graph with Adjacency Matrix - """ - def __init__(self,size,directed = False): - self.size = size - self.matrix = [[0 for i in range(self.size)] for j in range(self.size)] - self.directed = directed - self.Time = 0 - self.color = {i:"white" for i in range(self.size)} - self.parent = [-1 for i in range(self.size)] - self.time = [[0,0] for i in range(self.size)] - - def has_vertex(self,i): - return i>=0 and i=0 and i -#include -#include -#include -#include -#include -using namespace std; -struct node -{ - struct node *lc; - unsigned int data; - struct node *rc; -}; -typedef struct node N; -int A[1000]; -N *new_node() -{ - N* temp; - int x; - string n,nx("n"); - printf("\nEnter n for no data or y For Yes:"); - cin>>n; - cout<>x; - temp->data=x; - cout<<"\nEnter left child of "<lc=new_node(); - cout<<"\nEnter right child of "<rc=new_node(); - } - - return temp; -} -void printInorder(N *root) -{ - if(root==NULL)//base case - return; - - printInorder(root->lc); - cout<data; - printInorder(root->rc); -} - -void printPostorder(N *root) -{ - if(root==NULL)//base case - return; - - printPostorder(root->lc); - printPostorder(root->rc); - cout<data; -} - -void printPreorder(N *root) -{ - if(root==NULL)//base case - return; - cout<data; - printPreorder(root->lc); - printPreorder(root->rc); -} -int total_node(N *root) //Total No of Nodes -{ - if(root==NULL)//base case - return 0; - else - return 1+total_node(root->lc)+total_node(root->rc); -} -int height(N *root) //Max Depth or Height -{ - if(root==NULL)//base case - return 0; - else - { - int lh=height(root->lc); - int rh=height(root->rc); - - if(lh>rh) - return (lh+1); - else - return (rh+1); - } -} -bool id(N *root,N *root1)//Identical tree -{ - if(root==NULL && root1==NULL)//base case - return 1; - if((root!=NULL && root1!=NULL) && (root->data == root1->data) && id(root->lc,root1->lc) && id(root->rc,root1->rc)) - { - return 1; - } - else - return 0; -} -bool h_b(N *root)//Height Balance -{ - if(root==NULL)//base case - return 1; - else - { - int lh=height(root->lc); - int rh=height(root->rc); - - if((abs(lh-rh)<=2)&&(h_b(root->lc))&&(h_b(root->rc))) - return 1; - else - return 0; - } -} -bool ChildSum(N *root)//Children Sum i.e., sum chlid value equals to parent value -{ - int lx=0,rx=0; - if(root==NULL || (root->rc==NULL && root->lc==NULL))//base case - return 1; - if(root->lc) - lx=root->lc->data; - if(root->rc) - rx=root->rc->data; - - if(((lx+rx)==root->data)&&ChildSum(root->lc)&&ChildSum(root->rc)) - return 1; - else - return 0; -} - -int dia(N *root)//width or diameter -{ - if(root==NULL) - return 0; - else - { - int lh=height(root->lc); - int rh=height(root->rc); - int total_d=lh+rh+1; - int dia_left=dia(root->lc); - int dia_right=dia(root->rc); - - return std::max(total_d, max(dia_left, dia_right)); - } -} - -int rtls(N *root, int val=0)// Root To Leaf Sum -{ - if(root==NULL) - { - if(val==0) - return 1; - else - return 0; - } - - int total=val-root->data; - if(root->lc==NULL && root->rc==NULL && total==0) - return 1; - else - return 0; - - bool X,Y; - if(root->lc) - X = rtls(root->lc, total); - if(root->rc) - Y = rtls(root->rc, total); - - if(X||Y) - return 1; - else - return 0; -} - -int count_leaf(N *root) -{ - if(root==NULL) - return 0; - if(root->lc==NULL && root->rc==NULL) - return 1; - else - return count_leaf(root->lc)+count_leaf(root->rc); -} -int print_leaf(N *root) -{ - if(root!=NULL) - { - print_leaf(root->lc); - if(root->lc==NULL && root->rc==NULL) - return root->data; - print_leaf(root->rc); - } -} -void print_path(N* root, int top) -{ - if(root==NULL) - return; - A[top]=root->data; - if(root->lc==NULL && root->rc==NULL) - { - for(int i=0;i<=top;i++) - cout<lc,top+1); - print_path(root->rc,top+1); -} - -N* LCA(N* root, int a, int b) -{ - if(root==NULL) - return NULL; - if(root->data==a || root->data==b) - return root; - N* x=LCA(root->lc, a, b); - N* y=LCA(root->rc, a, b); - - if(x==NULL && y==NULL) - return NULL; - - if(x!=NULL && y!=NULL) - return root; - if(x!=NULL) - return x; - else - return y; -} - -void LevelOrder(N* root) -{ - int h1=height(root); - queues1; - queues2; - s1.push(root); - vectorv[h1]; - int i=0; - while(i<=h1) - { - while(!s1.empty()) - { - N* temp = s1.front(); - v[i].push_back(temp->data); - if(temp->lc!=NULL) - s2.push(temp->lc); - if(temp->rc!=NULL) - s2.push(temp->rc); - s1.pop(); - } - i++; - while(!s2.empty()) - { - N* temp = s2.front(); - v[i].push_back(temp->data); - if(temp->lc!=NULL) - s1.push(temp->lc); - if(temp->rc!=NULL) - s1.push(temp->rc); - s2.pop(); - } - i++; - } - for(int j=0;j=0;k--) - cout<lc) - { - cout<data; - print_boundary_left(root->lc); - } - else if(root->rc) - { - cout<data; - print_boundary_left(root->rc); - } - } -} - -void print_boundary_right(N *root) -{ - if(root) - { - if(root->rc) - { - print_boundary_right(root->rc); - cout<data; - } - else if(root->lc) - { - print_boundary_right(root->lc); - cout<data; - } - } -} - - -void print_boundary(N *root) -{ - if(root!=NULL) - { - cout<data; - print_boundary_left(root->lc); - print_leaf(root->lc); - print_leaf(root->rc); - print_boundary_right(root->rc); - } -} - -int main() -{ - N* root = new_node(); - - -/* N* root1 = new_node(); - - - cout<<"\nPreorder traversal of binary tree is \n"; - printPreorder(root); - - cout<<"\nInorder traversal of binary tree is \n"; - printInorder(root); - - cout<<"\nPostorder traversal of binary tree is \n"; - printPostorder(root); - - - cout<data< +#include +#include +#include +#include +#include +using namespace std; +struct node +{ + struct node *lc; + unsigned int data; + struct node *rc; +}; +typedef struct node N; +int A[1000]; +N *new_node() +{ + N* temp; + int x; + string n,nx("n"); + printf("\nEnter n for no data or y For Yes:"); + cin>>n; + cout<>x; + temp->data=x; + cout<<"\nEnter left child of "<lc=new_node(); + cout<<"\nEnter right child of "<rc=new_node(); + } + + return temp; +} +void printInorder(N *root) +{ + if(root==NULL)//base case + return; + + printInorder(root->lc); + cout<data; + printInorder(root->rc); +} + +void printPostorder(N *root) +{ + if(root==NULL)//base case + return; + + printPostorder(root->lc); + printPostorder(root->rc); + cout<data; +} + +void printPreorder(N *root) +{ + if(root==NULL)//base case + return; + cout<data; + printPreorder(root->lc); + printPreorder(root->rc); +} +int total_node(N *root) //Total No of Nodes +{ + if(root==NULL)//base case + return 0; + else + return 1+total_node(root->lc)+total_node(root->rc); +} +int height(N *root) //Max Depth or Height +{ + if(root==NULL)//base case + return 0; + else + { + int lh=height(root->lc); + int rh=height(root->rc); + + if(lh>rh) + return (lh+1); + else + return (rh+1); + } +} +bool id(N *root,N *root1)//Identical tree +{ + if(root==NULL && root1==NULL)//base case + return 1; + if((root!=NULL && root1!=NULL) && (root->data == root1->data) && id(root->lc,root1->lc) && id(root->rc,root1->rc)) + { + return 1; + } + else + return 0; +} +bool h_b(N *root)//Height Balance +{ + if(root==NULL)//base case + return 1; + else + { + int lh=height(root->lc); + int rh=height(root->rc); + + if((abs(lh-rh)<=2)&&(h_b(root->lc))&&(h_b(root->rc))) + return 1; + else + return 0; + } +} +bool ChildSum(N *root)//Children Sum i.e., sum chlid value equals to parent value +{ + int lx=0,rx=0; + if(root==NULL || (root->rc==NULL && root->lc==NULL))//base case + return 1; + if(root->lc) + lx=root->lc->data; + if(root->rc) + rx=root->rc->data; + + if(((lx+rx)==root->data)&&ChildSum(root->lc)&&ChildSum(root->rc)) + return 1; + else + return 0; +} + +int dia(N *root)//width or diameter +{ + if(root==NULL) + return 0; + else + { + int lh=height(root->lc); + int rh=height(root->rc); + int total_d=lh+rh+1; + int dia_left=dia(root->lc); + int dia_right=dia(root->rc); + + return std::max(total_d, max(dia_left, dia_right)); + } +} + +int rtls(N *root, int val=0)// Root To Leaf Sum +{ + if(root==NULL) + { + if(val==0) + return 1; + else + return 0; + } + + int total=val-root->data; + if(root->lc==NULL && root->rc==NULL && total==0) + return 1; + else + return 0; + + bool X,Y; + if(root->lc) + X = rtls(root->lc, total); + if(root->rc) + Y = rtls(root->rc, total); + + if(X||Y) + return 1; + else + return 0; +} + +int count_leaf(N *root) +{ + if(root==NULL) + return 0; + if(root->lc==NULL && root->rc==NULL) + return 1; + else + return count_leaf(root->lc)+count_leaf(root->rc); +} +int print_leaf(N *root) +{ + if(root!=NULL) + { + print_leaf(root->lc); + if(root->lc==NULL && root->rc==NULL) + return root->data; + print_leaf(root->rc); + } +} +void print_path(N* root, int top) +{ + if(root==NULL) + return; + A[top]=root->data; + if(root->lc==NULL && root->rc==NULL) + { + for(int i=0;i<=top;i++) + cout<lc,top+1); + print_path(root->rc,top+1); +} + +N* LCA(N* root, int a, int b) +{ + if(root==NULL) + return NULL; + if(root->data==a || root->data==b) + return root; + N* x=LCA(root->lc, a, b); + N* y=LCA(root->rc, a, b); + + if(x==NULL && y==NULL) + return NULL; + + if(x!=NULL && y!=NULL) + return root; + if(x!=NULL) + return x; + else + return y; +} + +void LevelOrder(N* root) +{ + int h1=height(root); + queues1; + queues2; + s1.push(root); + vectorv[h1]; + int i=0; + while(i<=h1) + { + while(!s1.empty()) + { + N* temp = s1.front(); + v[i].push_back(temp->data); + if(temp->lc!=NULL) + s2.push(temp->lc); + if(temp->rc!=NULL) + s2.push(temp->rc); + s1.pop(); + } + i++; + while(!s2.empty()) + { + N* temp = s2.front(); + v[i].push_back(temp->data); + if(temp->lc!=NULL) + s1.push(temp->lc); + if(temp->rc!=NULL) + s1.push(temp->rc); + s2.pop(); + } + i++; + } + for(int j=0;j=0;k--) + cout<lc) + { + cout<data; + print_boundary_left(root->lc); + } + else if(root->rc) + { + cout<data; + print_boundary_left(root->rc); + } + } +} + +void print_boundary_right(N *root) +{ + if(root) + { + if(root->rc) + { + print_boundary_right(root->rc); + cout<data; + } + else if(root->lc) + { + print_boundary_right(root->lc); + cout<data; + } + } +} + + +void print_boundary(N *root) +{ + if(root!=NULL) + { + cout<data; + print_boundary_left(root->lc); + print_leaf(root->lc); + print_leaf(root->rc); + print_boundary_right(root->rc); + } +} + +int main() +{ + N* root = new_node(); + + +/* N* root1 = new_node(); + + + cout<<"\nPreorder traversal of binary tree is \n"; + printPreorder(root); + + cout<<"\nInorder traversal of binary tree is \n"; + printInorder(root); + + cout<<"\nPostorder traversal of binary tree is \n"; + printPostorder(root); + + + cout<data<