From 091ef8d46bfe69ec0f028cc1ec3cbf7ddb70a40c Mon Sep 17 00:00:00 2001 From: nishant-sachdeva Date: Fri, 22 Dec 2023 18:59:01 +0530 Subject: [PATCH] pre-commit hooks changes for formatting --- .clang-format | 138 +- .gitignore | 1 - .../pkg/IR2Vec/core.cpp | 655 ++--- .../pkg/IR2Vec/refactoredCore.cpp | 452 ---- Manylinux2014_Compliant_Source/pkg/setup.py | 2 +- .../pkg/tests/test_ir2vec.py | 65 +- README.md | 2 +- experiments/Device_Mapping/DevMap.ipynb | 4 +- experiments/README.md | 8 +- .../Thread_Coarsening/ThreadCoarsening.ipynb | 4 +- seed_embeddings/OpenKE/analogies.txt | 84 +- seed_embeddings/OpenKE/analogy.py | 38 +- seed_embeddings/OpenKE/base/Base.cpp | 198 +- seed_embeddings/OpenKE/base/Corrupt.h | 282 +- seed_embeddings/OpenKE/base/Random.h | 20 +- seed_embeddings/OpenKE/base/Reader.h | 558 ++-- seed_embeddings/OpenKE/base/Setting.h | 20 +- seed_embeddings/OpenKE/base/Test.h | 710 +++-- seed_embeddings/OpenKE/base/Triple.h | 62 +- seed_embeddings/OpenKE/base/Valid.h | 90 +- seed_embeddings/OpenKE/generate_embedding.py | 2 +- .../OpenKE/generate_embedding_ray.py | 68 +- seed_embeddings/triplets.sh | 2 +- src/CollectIR.cpp | 144 +- src/FlowAware.cpp | 2325 ++++++++--------- src/IR2Vec.cpp | 263 +- src/Symbolic.cpp | 397 ++- src/include/CollectIR.h | 16 +- src/include/FlowAware.h | 277 +- src/include/IR2Vec.h | 79 +- src/include/Symbolic.h | 70 +- src/include/VectorSolver.h | 64 +- src/include/utils.h | 10 +- src/libIR2Vec.cpp | 62 +- ...he_closest_pair_from_two_sorted_arrays.cpp | 63 +- .../PE-benchmarks/Iterative_QuickSort.cpp | 94 +- .../PE-benchmarks/Nearly_sorted_Algo.cpp | 52 +- .../PE-benchmarks/aho-corasick-algorithm.cpp | 234 +- ...m-substring-search-search-permutations.cpp | 68 +- .../PE-benchmarks/bellman-ford-algorithm.cpp | 194 +- src/test-suite/PE-benchmarks/bfs.cpp | 116 +- .../PE-benchmarks/biconnectivity.cpp | 216 +- .../PE-benchmarks/binary-insertion-sort.cpp | 54 +- .../PE-benchmarks/binomial-coefficient.cpp | 38 +- .../boolean-parenthesization-problem.cpp | 88 +- .../PE-benchmarks/boruvkas-algorithm.cpp | 306 +-- src/test-suite/PE-benchmarks/box-stacking.cpp | 130 +- .../PE-benchmarks/boyer-moore-algorithm.cpp | 104 +- .../PE-benchmarks/channel-assignment.cpp | 86 +- src/test-suite/PE-benchmarks/coin-change.cpp | 64 +- ...-points-in-a-grid-using-two-traversals.cpp | 84 +- ...ruction-of-lcp-array-from-suffix-array.cpp | 230 +- .../count-1s-sorted-binary-array.cpp | 34 +- ...-binary-strings-without-consecutive-1s.cpp | 18 +- ...hose-sum-of-digits-equals-to-given-sum.cpp | 70 +- ...t-possible-ways-to-construct-buildings.cpp | 62 +- .../count-ways-reach-nth-stair.cpp | 24 +- src/test-suite/PE-benchmarks/cut-vertices.cpp | 222 +- .../PE-benchmarks/cutting-a-rod.cpp | 34 +- .../PE-benchmarks/detect-cycle-in-a-graph.cpp | 102 +- .../detect-cycle-undirected-graph.cpp | 106 +- .../PE-benchmarks/dfa-based-division.cpp | 70 +- src/test-suite/PE-benchmarks/dfs.cpp | 90 +- .../PE-benchmarks/edit-distance.cpp | 58 +- ...cient-constructtion-of-finite-automata.cpp | 62 +- .../PE-benchmarks/egg-dropping-puzzle.cpp | 62 +- .../euler-circuit-directed-graph.cpp | 218 +- .../eulerian-path-and-circuit.cpp | 236 +- ...nd-common-elements-three-sorted-arrays.cpp | 62 +- .../find-k-closest-elements-given-value.cpp | 90 +- ...consecutive-path-in-a-character-matrix.cpp | 72 +- ...mum-number-of-coins-that-make-a-change.cpp | 50 +- src/test-suite/PE-benchmarks/find-parity.cpp | 20 +- .../find-two-non-repeating-element.cpp | 46 +- .../finite-automata-algorithm.cpp | 78 +- .../PE-benchmarks/floyd-warshall.cpp | 126 +- .../PE-benchmarks/graph-coloring.cpp | 160 +- .../hamiltonian-cycle-backtracking.cpp | 198 +- .../insertion-sort-for-singly-linked-list.cpp | 110 +- src/test-suite/PE-benchmarks/karatsuba.cpp | 133 +- .../PE-benchmarks/kmp-algorithm.cpp | 112 +- ...orted-array-set-2-expected-linear-time.cpp | 68 +- ...ted-array-set-3-worst-case-linear-time.cpp | 110 +- .../largest-independent-set-problem.cpp | 76 +- .../largest-sum-contiguous-subarray.cpp | 37 +- .../lexicographic-rank-of-a-string.cpp | 42 +- .../little-and-big-endian-mystery.cpp | 16 +- .../longest-bitonic-subsequence.cpp | 72 +- ...length-substring-sum-first-second-half.cpp | 71 +- .../longest-increasing-subsequence.cpp | 68 +- .../longest-palindrome-substring.cpp | 92 +- .../longest-palindromic-subsequence.cpp | 54 +- .../longest-path-directed-acyclic-graph.cpp | 202 +- .../PE-benchmarks/m-coloring-problem.cpp | 112 +- src/test-suite/PE-benchmarks/magic-square.cpp | 90 +- .../matrix-chain-multiplication.cpp | 74 +- .../maximum-length-chain-of-pairs.cpp | 50 +- ...ying-and-selling-a-share-at-most-twice.cpp | 88 +- ...-matrix-with-all-1s-in-a-binary-matrix.cpp | 79 +- .../maximum-sum-increasing-subsequence.cpp | 48 +- .../maximum-sum-rectangle-in-a-2d-matrix.cpp | 176 +- .../merge-sort-for-doubly-linked-list.cpp | 146 +- .../PE-benchmarks/mergeSort_LinkedList.cpp | 166 +- .../PE-benchmarks/min-cost-path.cpp | 29 +- ...to-move-maximum-and-minimum-to-corners.cpp | 40 +- .../minimum-cost-polygon-triangulation.cpp | 63 +- .../minimum-cut-in-a-directed-graph.cpp | 154 +- ...of-jumps-to-reach-end-of-a-given-array.cpp | 42 +- ...m-positive-points-to-reach-destination.cpp | 54 +- .../mobile-numeric-keypad-problem.cpp | 118 +- ...bile-numeric-keypad-problem_space_optm.cpp | 114 +- .../PE-benchmarks/n-queen-problem.cpp | 88 +- .../PE-benchmarks/naive-algorithm.cpp | 32 +- .../optimal-binary-search-tree.cpp | 74 +- .../optimized-naive-algorithm.cpp | 44 +- .../overlapping-subproblems-property.cpp | 28 +- .../PE-benchmarks/palindrome-partitioning.cpp | 86 +- .../PE-benchmarks/partition-problem.cpp | 74 +- .../permutations-of-a-given-string.cpp | 34 +- .../program-for-nth-fibonacci-number.cpp | 26 +- .../PE-benchmarks/program-wish-womens-day.cpp | 106 +- .../quicksort-for-linked-list.cpp | 124 +- .../quicksort-on-singly-linked-list.cpp | 188 +- .../PE-benchmarks/rabin-karp-algorithm.cpp | 88 +- .../PE-benchmarks/rat-in-a-maze.cpp | 88 +- .../PE-benchmarks/reservoir-sampling.cpp | 68 +- .../rotate-bits-of-an-integer.cpp | 50 +- .../shortest-common-supersequence.cpp | 40 +- .../PE-benchmarks/sieve-of-eratosthenes.cpp | 48 +- src/test-suite/PE-benchmarks/snake-ladder.cpp | 128 +- .../PE-benchmarks/sort-array-wave-form-2.cpp | 36 +- ...ort-n-numbers-range-0-n2-1-linear-time.cpp | 74 +- ...-x-find-pair-array-whose-sum-closest-x.cpp | 46 +- .../strongly-connected-components.cpp | 176 +- .../PE-benchmarks/subset-sum-problem.cpp | 67 +- src/test-suite/PE-benchmarks/subset-sum.cpp | 94 +- src/test-suite/PE-benchmarks/sudoku.cpp | 124 +- .../PE-benchmarks/tarjan-algorithm.cpp | 260 +- .../PE-benchmarks/the-knights-tour.cpp | 87 +- .../PE-benchmarks/topological-sorting.cpp | 108 +- ...f-non-decreasing-numbers-with-n-digits.cpp | 54 +- .../PE-benchmarks/tower-of-hanoi.cpp | 23 +- .../transitive-closure-of-a-graph.cpp | 100 +- .../PE-benchmarks/trie-suffixes.cpp | 182 +- src/test-suite/PE-benchmarks/tug-of-war.cpp | 112 +- src/test-suite/PE-benchmarks/ugly-numbers.cpp | 42 +- src/test-suite/PE-benchmarks/union-find.cpp | 122 +- .../PE-benchmarks/vertex-cover-problem.cpp | 96 +- .../PE-benchmarks/weighted-job-scheduling.cpp | 70 +- src/test-suite/PE-benchmarks/word-wrap.cpp | 119 +- .../PE-benchmarks/z-algorithm-linear-time.cpp | 113 +- src/test-suite/generate_llfiles.sh | 1 + src/test-suite/get_index_file.py | 9 +- src/utils.cpp | 144 +- 154 files changed, 8856 insertions(+), 9486 deletions(-) delete mode 100644 Manylinux2014_Compliant_Source/pkg/IR2Vec/refactoredCore.cpp diff --git a/.clang-format b/.clang-format index a258b131..63027b87 100644 --- a/.clang-format +++ b/.clang-format @@ -1,137 +1 @@ ---- -Language: Cpp -# BasedOnStyle: LLVM -AccessModifierOffset: -2 -AlignAfterOpenBracket: Align -AlignConsecutiveMacros: false -AlignConsecutiveAssignments: false -AlignConsecutiveDeclarations: false -AlignEscapedNewlines: Right -AlignOperands: true -AlignTrailingComments: true -AllowAllArgumentsOnNextLine: true -AllowAllConstructorInitializersOnNextLine: true -AllowAllParametersOfDeclarationOnNextLine: true -AllowShortBlocksOnASingleLine: Never -AllowShortCaseLabelsOnASingleLine: false -AllowShortFunctionsOnASingleLine: All -AllowShortLambdasOnASingleLine: All -AllowShortIfStatementsOnASingleLine: Never -AllowShortLoopsOnASingleLine: false -AlwaysBreakAfterDefinitionReturnType: None -AlwaysBreakAfterReturnType: None -AlwaysBreakBeforeMultilineStrings: false -AlwaysBreakTemplateDeclarations: MultiLine -BinPackArguments: true -BinPackParameters: true -BraceWrapping: - AfterCaseLabel: false - AfterClass: false - AfterControlStatement: false - AfterEnum: false - AfterFunction: false - AfterNamespace: false - AfterObjCDeclaration: false - AfterStruct: false - AfterUnion: false - AfterExternBlock: false - BeforeCatch: false - BeforeElse: false - IndentBraces: false - SplitEmptyFunction: true - SplitEmptyRecord: true - SplitEmptyNamespace: true -BreakBeforeBinaryOperators: None -BreakBeforeBraces: Attach -BreakBeforeInheritanceComma: false -BreakInheritanceList: BeforeColon -BreakBeforeTernaryOperators: true -BreakConstructorInitializersBeforeComma: false -BreakConstructorInitializers: BeforeColon -BreakAfterJavaFieldAnnotations: false -BreakStringLiterals: true -ColumnLimit: 80 -CommentPragmas: '^ IWYU pragma:' -CompactNamespaces: false -ConstructorInitializerAllOnOneLineOrOnePerLine: false -ConstructorInitializerIndentWidth: 4 -ContinuationIndentWidth: 4 -Cpp11BracedListStyle: true -DeriveLineEnding: true -DerivePointerAlignment: false -DisableFormat: false -ExperimentalAutoDetectBinPacking: false -FixNamespaceComments: true -ForEachMacros: - - foreach - - Q_FOREACH - - BOOST_FOREACH -IncludeBlocks: Preserve -IncludeCategories: - - Regex: '^"(llvm|llvm-c|clang|clang-c)/' - Priority: 2 - SortPriority: 0 - - Regex: '^(<|"(gtest|gmock|isl|json)/)' - Priority: 3 - SortPriority: 0 - - Regex: '.*' - Priority: 1 - SortPriority: 0 -IncludeIsMainRegex: '(Test)?$' -IncludeIsMainSourceRegex: '' -IndentCaseLabels: false -IndentGotoLabels: true -IndentPPDirectives: None -IndentWidth: 4 -IndentWrappedFunctionNames: false -JavaScriptQuotes: Leave -JavaScriptWrapImports: true -KeepEmptyLinesAtTheStartOfBlocks: true -MacroBlockBegin: '' -MacroBlockEnd: '' -MaxEmptyLinesToKeep: 1 -NamespaceIndentation: None -ObjCBinPackProtocolList: Auto -ObjCBlockIndentWidth: 2 -ObjCSpaceAfterProperty: false -ObjCSpaceBeforeProtocolList: true -PenaltyBreakAssignment: 2 -PenaltyBreakBeforeFirstCallParameter: 19 -PenaltyBreakComment: 300 -PenaltyBreakFirstLessLess: 120 -PenaltyBreakString: 1000 -PenaltyBreakTemplateDeclaration: 10 -PenaltyExcessCharacter: 1000000 -PenaltyReturnTypeOnItsOwnLine: 60 -PointerAlignment: Right -ReflowComments: true -SortIncludes: true -SortUsingDeclarations: true -SpaceAfterCStyleCast: false -SpaceAfterLogicalNot: false -SpaceAfterTemplateKeyword: true -SpaceBeforeAssignmentOperators: true -SpaceBeforeCpp11BracedList: false -SpaceBeforeCtorInitializerColon: true -SpaceBeforeInheritanceColon: true -SpaceBeforeParens: ControlStatements -SpaceBeforeRangeBasedForLoopColon: true -SpaceInEmptyBlock: false -SpaceInEmptyParentheses: false -SpacesBeforeTrailingComments: 1 -SpacesInAngles: false -SpacesInConditionalStatement: false -SpacesInContainerLiterals: true -SpacesInCStyleCastParentheses: false -SpacesInParentheses: false -SpacesInSquareBrackets: false -SpaceBeforeSquareBrackets: false -Standard: Latest -StatementMacros: - - Q_UNUSED - - QT_REQUIRE_VERSION -TabWidth: 8 -UseCRLF: false -UseTab: Never -... - +BasedOnStyle: LLVM diff --git a/.gitignore b/.gitignore index d3356f2b..64c82c21 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,5 @@ __pycache__/ .vscode experiments/*/output seed_embeddings/triplets.txt -seed_embeddings/triplets14.txt seed_embeddings/preprocessed/* .cache/ diff --git a/Manylinux2014_Compliant_Source/pkg/IR2Vec/core.cpp b/Manylinux2014_Compliant_Source/pkg/IR2Vec/core.cpp index dcb02d5a..036c9cd4 100644 --- a/Manylinux2014_Compliant_Source/pkg/IR2Vec/core.cpp +++ b/Manylinux2014_Compliant_Source/pkg/IR2Vec/core.cpp @@ -6,7 +6,10 @@ // #define PY_SSIZE_T_CLEAN +#include "CollectIR.h" +#include "FlowAware.h" #include "IR2Vec.h" +#include "Symbolic.h" #include "utils.h" #include "version.h" @@ -31,6 +34,7 @@ #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" +#include "llvm/IR/Module.h" #include "llvm/IR/Type.h" #include "llvm/IR/User.h" #include "llvm/IR/Value.h" @@ -47,346 +51,349 @@ #include -// #include "_dl_x86_cpu_features.c" - -// #include "boost/python.hpp" - -// utils.h is included because it provides with a function for conversion using namespace std; -int no_name_inst_count = 0; string seed_emb_path = ""; -// need to wrap :- -// generateEncodings() -// getInstVecMap() -// getFunctionVecMap() -// getFunctionVecMap() - -// need to undesratnd argument semantics of generateEncodings() ---> -// LLVM::Module &M -// IR2VecMode mode = can be symbolic[sym] or flowaware[fa] -// vocab = path to seed emebedings -// o= output file that will either be created or appended and contain -// real-valued vectors representing embeddings level= can be either program -// level[p] or function level[f] class = One and only Non mandatory Argument ; -// static PyObject* set_global_list_return_message(bp::list& l, string msg) -// { -// l[1]=msg; -// cout<<"fail1"< llvm_pgm_vec) { + // for PgmVector + PyObject *PgmList = PyList_New(0); + for (auto &Pgm_it : llvm_pgm_vec) + PyList_Append(PgmList, PyFloat_FromDouble(Pgm_it)); + return PgmList; + } + + // Function to get Function Vector Dictionary + PyObject *createFunctionVectorDict( + llvm::SmallMapVector + funcMap) { + PyObject *FuncVecDict = PyDict_New(); - const char *filename = "\0"; // need to generate module object from this . - // Thus , need to add one more .cpp in .so - const char *mode = "\0"; + for (auto &Func_it : funcMap) { + const llvm::Function *func = Func_it.first; + std::string demangledName = IR2Vec::getDemagledName(func); + std::string actualName = + IR2Vec::getActualName(const_cast(func)); - string vocab_path = seed_emb_path + "/seedEmbeddingVocab-llvm16.txt"; - // const char* - // vocab_path=(seed_emb_path+"/seedEmbeddingVocab-llvm16.txt").c_str(); // - // this should be exact path till .txt . *** NOT TAKING THIS AS USER - // DEFINED/PROVIDED ARGS *** - const char *level = - "\0"; // remember that ir2vec accepts a char type for this - const char *output_file = "\0"; + PyObject *temp3 = PyList_New(0); + for (auto &Vec_it : Func_it.second) { + PyList_Append(temp3, PyFloat_FromDouble(Vec_it)); + } - PyObject *Embedding_dict = PyDict_New(); + PyObject *funcDict = PyDict_New(); + PyDict_SetDefault(funcDict, PyUnicode_FromString("demangledName"), + Py_None); + PyDict_SetDefault(funcDict, PyUnicode_FromString("actualName"), Py_None); + PyDict_SetDefault(funcDict, PyUnicode_FromString("vector"), Py_None); + + PyDict_SetItemString(funcDict, "demangledName", + PyUnicode_FromString(demangledName.c_str())); + PyDict_SetItemString(funcDict, "actualName", + PyUnicode_FromString(actualName.c_str())); + PyDict_SetItemString(funcDict, "vector", temp3); + + PyDict_SetItemString(FuncVecDict, demangledName.c_str(), funcDict); + + Py_DECREF(funcDict); + } + return FuncVecDict; + } + + // Function to get Instruction Vector Dictionary + PyObject *createInstructionVectorDict( + llvm::SmallMapVector + llvm_inst_vec_map) { PyObject *InstVecDict = PyDict_New(); - PyObject *FuncVecDict = PyDict_New(); - PyObject *PgmList = PyList_New(0); - PyDict_SetDefault(Embedding_dict, PyUnicode_FromString("Instruction_Dict"), - Py_None); - PyDict_SetDefault(Embedding_dict, PyUnicode_FromString("Function_Dict"), - Py_None); - PyDict_SetDefault(Embedding_dict, PyUnicode_FromString("Program_List"), - Py_None); - PyDict_SetDefault(Embedding_dict, PyUnicode_FromString("Message"), - PyUnicode_FromString("NA")); - PyDict_SetDefault(Embedding_dict, PyUnicode_FromString("Status"), Py_False); - - if (PyArg_ParseTuple(args, "sss|s", &filename, &mode, &level, - &output_file)) { - - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sanity checks - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - - ifstream temp; - - temp.open(filename, ios_base::in); - if (temp.peek() == ifstream::traits_type::eof() || temp.bad() == true || - temp.fail() == true) { - PyDict_SetItemString( - Embedding_dict, "Message", - PyUnicode_FromString( - "Eroneous or empty .bc/.ll file location entred")); - PyDict_SetItemString(Embedding_dict, "Status", Py_False); - return Embedding_dict; - } - temp.close(); - if (string(output_file).empty() == false) { - temp.open(output_file, ios_base::in); - if (temp.bad() == true || temp.fail() == true) { - PyDict_SetItemString( - Embedding_dict, "Message", - PyUnicode_FromString( - "Eroneous output file location entred")); - PyDict_SetItemString(Embedding_dict, "Status", Py_False); - return Embedding_dict; - } - temp.close(); - } - - // ********* SINCE NOW WE ARE NOT TAKING VOCAB FILE LOCATION FROM USER - // HENCE NO NEED OF THIS SANITY CHECK ******** temp.open(vocab_path, - // ios_base::in); if(temp.peek()==ifstream::traits_type::eof() || - // temp.bad()==true || temp.fail()==true) - // { - // PyDict_SetItemString(Embedding_dict,"Message",PyUnicode_FromString("Eroneous - // or empty seed embeddings text file location entered")); - // PyDict_SetItemString(Embedding_dict,"Status",Py_False); - // return Embedding_dict; - - // } - // temp.close(); - if (string(mode) != string("sym") && string(mode) != string("fa")) { - PyDict_SetItemString( - Embedding_dict, "Message", - PyUnicode_FromString("Eroneous mode entered . Either of sym, " - "fa should be specified")); - PyDict_SetItemString(Embedding_dict, "Status", Py_False); - return Embedding_dict; - } else { - if (level[0] != 'p' && level[0] != 'f') { - PyDict_SetItemString( - Embedding_dict, "Message", - PyUnicode_FromString( - "Invalid level specified: Use either p or f")); - PyDict_SetItemString(Embedding_dict, "Status", Py_False); - return Embedding_dict; - } - } - - if (string(mode) != string("sym") && string(mode) != string("fa")) { - PyDict_SetItemString( - Embedding_dict, "Message", - PyUnicode_FromString("Eroneous mode entered . Either of sym, " - "fa should be specified")); - PyDict_SetItemString(Embedding_dict, "Status", Py_False); - return Embedding_dict; - } - - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Invokinng IR2Vec lib - // exposed functions - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - - IR2Vec::iname = string(filename); - IR2Vec::IR2VecMode m = - (string(mode) == string("sym") ? IR2Vec::Symbolic - : IR2Vec::FlowAware); - // IR2Vec::Embeddings::obj(); - - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ C++ containers to hold data from - // LLVM ADT's ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - map> InstVecMap; - map> FuncVecMap; - vector PgmVect; - - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Temporary LLVM ADT's need to - // hold returned ADt's by IR2vec lib - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - llvm::SmallMapVector - llvm_inst_vec_map; // IR2Vec::Embeddings::obj.getInstVecMap(); - llvm::SmallMapVector - llvm_func_vec_map; // IR2Vec::Embeddings::obj.getFunctionVecMap(); - llvm::SmallVector - llvm_pgm_vec; // IR2Vec::Embeddings::obj.getProgramVector(); - - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The scope of - // this Module object is extremely crucial - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - std::unique_ptr M; - M = IR2Vec::getLLVMIR(); - - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ if output file is provided - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - if (string(output_file) != "") { - // cout<<"okok";return PyUnicode_FromString("Embedings have been - // generated . Access them in the respective output file"); - string outFile = string(output_file); - ofstream o; - o.open(outFile, - ios_base::app); // this means open a file , connect stream - // "o" to it and then seek to the end of this - // stream before each write ["ios_base::app"] - IR2Vec::Embeddings Emb(*M, m, vocab_path, level[0], &o); - - // Emb is genertaed and intialized - llvm_inst_vec_map = Emb.getInstVecMap(); - llvm_func_vec_map = Emb.getFunctionVecMap(); - llvm_pgm_vec = Emb.getProgramVector(); - - } - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ using cout to dump the output - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - else { - IR2Vec::Embeddings Emb(*M, m, vocab_path, level[0], nullptr); - llvm_inst_vec_map = Emb.getInstVecMap(); - llvm_func_vec_map = Emb.getFunctionVecMap(); - llvm_pgm_vec = Emb.getProgramVector(); - } - - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ copying data from LLVM ADT's to - // C++ Containers ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ now make a - // python dictionary that will hold 2 SmallMapVector and 1 SmallVector - // . But first extract all data from LLVM data structure then store that - // data into c++ containers - - vector temp2; - char *readable_name; - string demangledName; - size_t sz = 17; - int status = 0; - // coying llvm samll map vector data into c++ map - - // for InstVecMap - for (auto Inst_it : llvm_inst_vec_map) { - // copy this SmallVector into c++ Vector - for (auto &Vec_it : Inst_it.second) { - // cout<getName(); - // cout<getFunction())->getName().str()) + - "No_Name_Inst_" + - to_string( - no_name_inst_count); // for instructiojn having no - // string rep ; the custom string - // rep will be like - // "No_Name_Inst"_2 - InstVecMap[demangledName] = temp2; - } - temp2.clear(); - } - - if (temp2.size() != 0) { - temp2.clear(); - } - - // for FuncVecMap - for (auto Func_it : llvm_func_vec_map) { - // copy this SmallVector into c++ Vector - for (auto &Vec_it : Func_it.second) - temp2.push_back(Vec_it); - - // apply __cxx::demangle just to be cautious - demangledName = IR2Vec::getDemagledName(Func_it.first); - FuncVecMap[demangledName] = temp2; - - temp2.clear(); - } - - // for PgmVector - for (auto &Pgm_it : llvm_pgm_vec) - PgmVect.push_back(Pgm_it); - - // all c++ container are ready to convert - // iterate over a c++ container , if it has embedd anotehr c++c - // ocntainer then iterate over it also - - // copying c++ map into Pyobject dict - - // for InstVecMap - - for (auto Map_it1 : InstVecMap) { - PyObject *temp3 = PyList_New(0); - for (auto &List_it1 : Map_it1.second) - PyList_Append(temp3, PyFloat_FromDouble(List_it1)); - PyDict_SetDefault(InstVecDict, - PyUnicode_FromString((Map_it1.first).c_str()), - Py_None); - PyDict_SetItemString(InstVecDict, Map_it1.first.c_str(), temp3); - - // auto list_size=PyList_Size(temp3); - // for(long i=0; ifileName; + IR2Vec::IR2VecMode ir2vecMode = + (this->mode == string("sym") ? IR2Vec::Symbolic : IR2Vec::FlowAware); + // The scope of this Module object is extremely crucial + std::unique_ptr Module; + Module = IR2Vec::getLLVMIR(); + std::string vocab_path = seed_emb_path + "/seedEmbeddingVocab-llvm14.txt"; + + IR2Vec::Embeddings *emb = new IR2Vec::Embeddings(); + // if output file is provided + if (this->outputFile != "") { + string outFile = this->outputFile; + ofstream output; + output.open(outFile, ios_base::app); + emb = std::move(new IR2Vec::Embeddings(*Module, ir2vecMode, vocab_path, + (this->level)[0], &output, + funcName)); + } else { + emb = std::move(new IR2Vec::Embeddings(*Module, ir2vecMode, vocab_path, + (this->level)[0], nullptr, + funcName)); + } + + if (emb == nullptr) { + PyErr_SetString(PyExc_TypeError, "Embedding Object not created"); + Py_RETURN_NONE; + } + + if (type == OpType::Program) { + llvm::SmallVector progVector = emb->getProgramVector(); + return this->createProgramVectorList(progVector); + } else if (type == OpType::Function) { + llvm::SmallMapVector + funcVecMap = emb->getFunctionVecMap(); + return this->createFunctionVectorDict(funcVecMap); + } else if (type == OpType::Instruction) { + llvm::SmallMapVector + instVecMap = emb->getInstVecMap(); + return this->createInstructionVectorDict(instVecMap); + } else { + PyErr_SetString(PyExc_TypeError, "Invalid OpType"); + Py_RETURN_NONE; } + } +}; + +typedef struct { + PyObject_VAR_HEAD ir2vecHandler *ir2vecObj; +} ir2vecHandlerObject; + +PyObject *getInstructionVectors(ir2vecHandlerObject *self, PyObject *args) { + // check for args, and null etc + if ((self->ir2vecObj) == NULL) { + PyErr_SetString(PyExc_TypeError, "Embedding Object not created"); + return NULL; + } + return (self->ir2vecObj)->generateEncodings(OpType::Instruction); +} - PyDict_SetItemString(Embedding_dict, "Message", - PyUnicode_FromString("PyArgsParseTuple didnt worked")); - PyDict_SetItemString(Embedding_dict, "Status", Py_False); - return Embedding_dict; +PyObject *getProgramVector(ir2vecHandlerObject *self, PyObject *args) { + if ((self->ir2vecObj) == NULL) { + PyErr_SetString(PyExc_TypeError, "Embedding Object not created"); + return NULL; + } + return (self->ir2vecObj)->generateEncodings(OpType::Program); +} + +PyObject *getFunctionVectors(ir2vecHandlerObject *self, PyObject *args) { + if ((self->ir2vecObj) == NULL) { + PyErr_SetString(PyExc_TypeError, "Embedding Object not created"); + return NULL; + } + + const char *funcName = "\0"; + if (!PyArg_ParseTuple(args, "|s", &funcName)) { + return NULL; + } + + return (self->ir2vecObj) + ->generateEncodings(OpType::Function, string(funcName)); +} + +PyMethodDef ir2vecObjMethods[] = { + {"getInstructionVectors", (PyCFunction)getInstructionVectors, METH_VARARGS, + "Get Instruction Vectors"}, + {"getProgramVector", (PyCFunction)getProgramVector, METH_VARARGS, + "Get Program Vector"}, + {"getFunctionVectors", (PyCFunction)getFunctionVectors, METH_VARARGS, + "Get Function Vectors"}, + {NULL, NULL, 0, NULL} /* Sentinel */ +}; + +static PyTypeObject ir2vecHandlerType = { + PyVarObject_HEAD_INIT(NULL, 0).tp_name = + "ir2vecHandler.ir2vecHandlerObject", + .tp_basicsize = sizeof(ir2vecHandlerObject), + .tp_flags = Py_TPFLAGS_DEFAULT, + .tp_doc = "ir2vecHandlerObject", + .tp_methods = ir2vecObjMethods, +}; + +PyObject *runEncodings(PyObject *args, OpType type) { + const char *funcName = "\0"; + ir2vecHandlerObject *ir2vecHandlerobj = NULL; + + if (!PyArg_ParseTuple(args, "O|s", &ir2vecHandlerobj, &funcName)) { + return NULL; + } + + if (string(funcName).empty() == false && type != OpType::Function) { + PyErr_SetString(PyExc_TypeError, + "Function name can only be specified for Function " + "Vectors"); + return NULL; + } + + if (ir2vecHandlerobj == NULL) { + PyErr_SetString(PyExc_TypeError, "Embedding Object not created"); + return NULL; + } + + if (ir2vecHandlerobj->ir2vecObj == NULL) { + PyErr_SetString(PyExc_TypeError, "Embedding Object not created"); + return NULL; + } else { + ir2vecHandler *ir2vecObj = ir2vecHandlerobj->ir2vecObj; + return ir2vecObj->generateEncodings(type, string(funcName)); + } +} + +PyObject *getInstructionVectors(PyObject *self, PyObject *args) { + return runEncodings(args, OpType::Instruction); +} + +PyObject *getProgramVector(PyObject *self, PyObject *args) { + return runEncodings(args, OpType::Program); +} + +PyObject *getFunctionVectors(PyObject *self, PyObject *args) { + return runEncodings(args, OpType::Function); +} + +ir2vecHandlerObject *createIR2VECObject(const char *filename, + const char *output_file, + const char *mode, const char *level) { + ir2vecHandler *ir2vecObj = + new ir2vecHandler(filename, output_file, mode, level); + if (ir2vecObj == NULL) { + return NULL; + } + ir2vecHandlerObject *ir2vecHandlerObj = + PyObject_New(ir2vecHandlerObject, &ir2vecHandlerType); + if (ir2vecHandlerObj == NULL) { + return NULL; + } + ir2vecHandlerObj->ir2vecObj = ir2vecObj; + return ir2vecHandlerObj; +} + +PyObject *initEmbedding(PyObject *self, PyObject *args) { + Py_Initialize(); + const char *filename = "\0"; + const char *mode = "\0"; + const char *level = "\0"; + const char *output_file = "\0"; + + if (!PyArg_ParseTuple(args, "sss|s", &filename, &mode, &level, + &output_file)) { + // raise error here + PyErr_SetString(PyExc_TypeError, "Invalid Arguments"); + return NULL; + } + + if (fileNotValid(filename)) { + PyErr_SetString(PyExc_TypeError, "Invalid File Path"); + return NULL; + } + + if (string(output_file).empty() == false) { + if (fileNotValid(output_file)) { + PyErr_SetString(PyExc_TypeError, "Invalid Output File Path"); + return NULL; + } + } + + if (string(mode) != string("sym") && string(mode) != string("fa")) { + PyErr_SetString(PyExc_TypeError, + "Eroneous mode entered . Either of sym, fa should be " + "specified"); + return NULL; + } + + if (level[0] != 'p' && level[0] != 'f') { + PyErr_SetString(PyExc_TypeError, + "Invalid level specified: Use either p or f"); + return NULL; + } + + ir2vecHandlerObject *ir2vecObj = + createIR2VECObject(filename, output_file, mode, level); + + if (ir2vecObj == NULL) { + PyErr_SetString(PyExc_TypeError, "Embedding Object not created"); + return NULL; + } + + return (PyObject *)ir2vecObj; } PyMethodDef IR2Vec_core_Methods[] = { - {"generateEmbeddings", (PyCFunction)IR2Vec_generateEmbeddings, METH_VARARGS, - "As specified"}, - {"setSeedEmbdPath", (PyCFunction)set_seed_embedding_path, METH_VARARGS, - "As specified"}, + {"initEmbedding", (PyCFunction)initEmbedding, METH_VARARGS, + "Create an Embedding Object"}, + {"getInstructionVectors", (PyCFunction)getInstructionVectors, METH_VARARGS, + "Get Instruction Vectors"}, + {"getProgramVector", (PyCFunction)getProgramVector, METH_VARARGS, + "Get Program Vector"}, + {"getFunctionVectors", (PyCFunction)getFunctionVectors, METH_VARARGS, + "Get Function Vectors"}, + {"setSeedEmbdPath", (PyCFunction)setSeedEmbeddingPath, METH_VARARGS, + "Set Seed Embedding Path"}, {"getVersion", getIR2VecVersion, METH_VARARGS, "Get IR2Vec Version"}, {NULL, NULL, 0, NULL} /* Sentinel */ }; + struct PyModuleDef IR2Vec_def = { PyModuleDef_HEAD_INIT, "IR2Vec.core", /* name of module NOT THE NAME OF PACKAGE*/ @@ -396,4 +403,14 @@ struct PyModuleDef IR2Vec_def = { or -1 if the module keeps state in global variables. */ IR2Vec_core_Methods}; -PyMODINIT_FUNC PyInit_core(void) { return PyModule_Create(&IR2Vec_def); } + +PyMODINIT_FUNC PyInit_core(void) { + PyObject *module = PyModule_Create(&IR2Vec_def); + + if (PyType_Ready(&ir2vecHandlerType) < 0) { + return NULL; + } + + Py_INCREF(&ir2vecHandlerType); + return module; +} diff --git a/Manylinux2014_Compliant_Source/pkg/IR2Vec/refactoredCore.cpp b/Manylinux2014_Compliant_Source/pkg/IR2Vec/refactoredCore.cpp deleted file mode 100644 index 22787e7c..00000000 --- a/Manylinux2014_Compliant_Source/pkg/IR2Vec/refactoredCore.cpp +++ /dev/null @@ -1,452 +0,0 @@ -// Copyright(c) 2023, The Contributors of IR2Vec. -// -// Part of the IR2Vec project.This software is available under the BSD 4-Clause -// License. Please see LICENSE file in the top - level directory for more -// details. -// - -#define PY_SSIZE_T_CLEAN -#include "CollectIR.h" -#include "FlowAware.h" -#include "IR2Vec.h" -#include "Symbolic.h" -#include "utils.h" -#include "version.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "llvm/ADT/APSInt.h" -#include "llvm/ADT/ArrayRef.h" -#include "llvm/ADT/DenseMap.h" -#include "llvm/ADT/MapVector.h" -#include "llvm/ADT/SmallSet.h" -#include "llvm/ADT/SmallVector.h" -#include "llvm/ADT/StringExtras.h" -#include "llvm/ADT/StringRef.h" -#include "llvm/IR/CFG.h" -#include "llvm/IR/Function.h" -#include "llvm/IR/InstrTypes.h" -#include "llvm/IR/Instruction.h" -#include "llvm/IR/Instructions.h" -#include "llvm/IR/Module.h" -#include "llvm/IR/Type.h" -#include "llvm/IR/User.h" -#include "llvm/IR/Value.h" -#include "llvm/IRReader/IRReader.h" -#include "llvm/Pass.h" -#include "llvm/Passes/PassBuilder.h" -#include "llvm/Support/CommandLine.h" -#include "llvm/Support/DataTypes.h" -#include "llvm/Support/Endian.h" -#include "llvm/Support/JSON.h" -#include "llvm/Support/ScopedPrinter.h" -#include "llvm/Support/SourceMgr.h" -#include "llvm/Support/raw_ostream.h" - -#include - -using namespace std; - -string seed_emb_path = ""; - -static PyObject *getIR2VecVersion(PyObject *self, PyObject *args) { - return PyUnicode_DecodeUTF8( - IR2VEC_VERSION, sizeof(IR2VEC_VERSION) / sizeof(IR2VEC_VERSION[0]) - 1, - NULL); -} - -PyObject *setSeedEmbeddingPath(PyObject *self, PyObject *args) { - const char *vocab_path2 = ""; - if (PyArg_ParseTuple(args, "s", &vocab_path2)) { - seed_emb_path = string(vocab_path2); - } - return PyUnicode_FromString("Seed Embedding Path is Set"); -} - -bool fileNotValid(const char *filename) { - ifstream temp; - temp.open(filename, ios_base::in); - if ( - temp.peek() == ifstream::traits_type::eof() || - temp.bad() == true || - temp.fail() == true - ) { - return true; - } - temp.close(); - return false; -} - -// create Enum with three options : Program, Function, Instruction -enum class OpType { Program, Function, Instruction }; - -class ir2vecHandler { -private: - std::string fileName; - std::string outputFile; - std::string mode; - std::string level; -public: - ir2vecHandler(std::string fileName, std::string outputFile, std::string mode, std::string level): - fileName(fileName), outputFile(outputFile), mode(mode), level(level) {} - - std::string getFile() { return fileName; } - std::string getOutputFile() { return outputFile; } - std::string getMode() { return mode; } - std::string getLevel() { return level; } - - // Function to get Program Vector List - PyObject *createProgramVectorList(llvm::SmallVector llvm_pgm_vec) { - // for PgmVector - PyObject *PgmList = PyList_New(0); - for (auto &Pgm_it : llvm_pgm_vec) - PyList_Append(PgmList, PyFloat_FromDouble(Pgm_it)); - return PgmList; - } - - - // Function to get Function Vector Dictionary - PyObject *createFunctionVectorDict( - llvm::SmallMapVector - funcMap - ) { - PyObject *FuncVecDict = PyDict_New(); - - for (auto &Func_it : funcMap) { - const llvm::Function *func = Func_it.first; - std::string demangledName = IR2Vec::getDemagledName(func); - std::string actualName = IR2Vec::getActualName( - const_cast(func) - ); - - PyObject *temp3 = PyList_New(0); - for (auto &Vec_it : Func_it.second) { - PyList_Append(temp3, PyFloat_FromDouble(Vec_it)); - } - - PyObject *funcDict = PyDict_New(); - PyDict_SetDefault(funcDict, PyUnicode_FromString("demangledName"), Py_None); - PyDict_SetDefault(funcDict, PyUnicode_FromString("actualName"), Py_None); - PyDict_SetDefault(funcDict, PyUnicode_FromString("vector"), Py_None); - - PyDict_SetItemString(funcDict, "demangledName", PyUnicode_FromString(demangledName.c_str())); - PyDict_SetItemString(funcDict, "actualName", PyUnicode_FromString(actualName.c_str())); - PyDict_SetItemString(funcDict, "vector", temp3); - - PyDict_SetItemString( - FuncVecDict, - demangledName.c_str(), - funcDict - ); - - Py_DECREF(funcDict); - } - return FuncVecDict; - } - - - // Function to get Instruction Vector Dictionary - PyObject *createInstructionVectorDict( - llvm::SmallMapVector - llvm_inst_vec_map - ) { - PyObject *InstVecDict = PyDict_New(); - - for (auto &Inst_it : llvm_inst_vec_map) { - std::string demangledName = IR2Vec::getDemagledName(Inst_it.first); - - PyObject *temp3 = PyList_New(0); - // copy this SmallVector into c++ Vector - for (auto &Vec_it : Inst_it.second) { - PyList_Append(temp3, PyFloat_FromDouble(Vec_it)); - } - PyDict_SetDefault(InstVecDict, - PyUnicode_FromString(demangledName.c_str()), - Py_None); - PyDict_SetItemString(InstVecDict, demangledName.c_str(), temp3); - } - return InstVecDict; - } - - - // generateEncodings - PyObject *generateEncodings(OpType type, std::string funcName = "") { - // Invokinng IR2Vec lib exposed functions - IR2Vec::iname = this->fileName; - IR2Vec::IR2VecMode ir2vecMode = - (this->mode == string("sym") ? IR2Vec::Symbolic - : IR2Vec::FlowAware); - // The scope of this Module object is extremely crucial - std::unique_ptr Module; - Module = IR2Vec::getLLVMIR(); - std::string vocab_path = seed_emb_path + "/seedEmbeddingVocab-llvm14.txt"; - - IR2Vec::Embeddings* emb = new IR2Vec::Embeddings(); - // if output file is provided - if (this->outputFile != "") { - string outFile = this->outputFile; - ofstream output; - output.open(outFile, ios_base::app); - emb = std::move(new IR2Vec::Embeddings( - *Module, - ir2vecMode, - vocab_path, - (this->level)[0], - &output, - funcName - )); - } else { - emb = std::move(new IR2Vec::Embeddings( - *Module, - ir2vecMode, - vocab_path, - (this->level)[0], - nullptr, - funcName - )); - } - - if (emb == nullptr) { - PyErr_SetString(PyExc_TypeError, "Embedding Object not created"); - Py_RETURN_NONE; - } - - if (type == OpType::Program) { - llvm::SmallVector progVector = emb->getProgramVector(); - return this->createProgramVectorList(progVector); - } - else if (type == OpType::Function) { - llvm::SmallMapVector funcVecMap = emb->getFunctionVecMap(); - return this->createFunctionVectorDict(funcVecMap); - } - else if (type == OpType::Instruction) { - llvm::SmallMapVector instVecMap = emb->getInstVecMap(); - return this->createInstructionVectorDict(instVecMap); - } - else { - PyErr_SetString(PyExc_TypeError, "Invalid OpType"); - Py_RETURN_NONE; - } - } -}; - -typedef struct { - PyObject_VAR_HEAD - ir2vecHandler *ir2vecObj; -} ir2vecHandlerObject; - -PyObject *getInstructionVectors(ir2vecHandlerObject *self, PyObject* args) { - // check for args, and null etc - if ((self->ir2vecObj) == NULL) { - PyErr_SetString(PyExc_TypeError, "Embedding Object not created"); - return NULL; - } - return (self->ir2vecObj)->generateEncodings(OpType::Instruction); -} - -PyObject *getProgramVector(ir2vecHandlerObject *self, PyObject* args) { - if ((self->ir2vecObj) == NULL) { - PyErr_SetString(PyExc_TypeError, "Embedding Object not created"); - return NULL; - } - return (self->ir2vecObj)->generateEncodings(OpType::Program); -} - -PyObject *getFunctionVectors(ir2vecHandlerObject *self, PyObject* args) { - if ((self->ir2vecObj) == NULL) { - PyErr_SetString(PyExc_TypeError, "Embedding Object not created"); - return NULL; - } - - const char *funcName = "\0"; - if (!PyArg_ParseTuple(args, "|s", &funcName)) { - return NULL; - } - - return (self->ir2vecObj)->generateEncodings(OpType::Function, string(funcName)); -} - -PyMethodDef ir2vecObjMethods[] = { - { - "getInstructionVectors", (PyCFunction)getInstructionVectors, METH_VARARGS, - "Get Instruction Vectors" - }, - { - "getProgramVector", (PyCFunction)getProgramVector, METH_VARARGS, - "Get Program Vector" - }, - { - "getFunctionVectors", (PyCFunction)getFunctionVectors, METH_VARARGS, - "Get Function Vectors" - }, - {NULL, NULL, 0, NULL} /* Sentinel */ -}; - -static PyTypeObject ir2vecHandlerType = { - PyVarObject_HEAD_INIT(NULL, 0) - .tp_name = "ir2vecHandler.ir2vecHandlerObject", - .tp_basicsize = sizeof(ir2vecHandlerObject), - .tp_flags = Py_TPFLAGS_DEFAULT, - .tp_doc = "ir2vecHandlerObject", - .tp_methods = ir2vecObjMethods, -}; - -PyObject *runEncodings(PyObject *args, OpType type) { - const char *funcName = "\0"; - ir2vecHandlerObject *ir2vecHandlerobj = NULL; - - if (!PyArg_ParseTuple(args, "O|s", &ir2vecHandlerobj, &funcName)) { - return NULL; - } - - if (string(funcName).empty() == false && type != OpType::Function) { - PyErr_SetString(PyExc_TypeError, - "Function name can only be specified for Function " - "Vectors"); - return NULL; - } - - if (ir2vecHandlerobj == NULL) { - PyErr_SetString(PyExc_TypeError, "Embedding Object not created"); - return NULL; - } - - if (ir2vecHandlerobj->ir2vecObj == NULL) { - PyErr_SetString(PyExc_TypeError, "Embedding Object not created"); - return NULL; - } else { - ir2vecHandler *ir2vecObj = ir2vecHandlerobj->ir2vecObj; - return ir2vecObj->generateEncodings( - type, string(funcName) - ); - } -} - -PyObject *getInstructionVectors(PyObject *self, PyObject* args) { - return runEncodings(args, OpType::Instruction); -} - -PyObject *getProgramVector(PyObject* self, PyObject* args) { - return runEncodings(args, OpType::Program); -} - -PyObject *getFunctionVectors(PyObject *self, PyObject* args) { - return runEncodings(args, OpType::Function); -} - -ir2vecHandlerObject *createIR2VECObject(const char *filename, const char *output_file, const char *mode, const char *level) { - ir2vecHandler *ir2vecObj = new ir2vecHandler(filename, output_file, mode, level); - if (ir2vecObj == NULL) { - return NULL; - } - ir2vecHandlerObject *ir2vecHandlerObj = PyObject_New(ir2vecHandlerObject, &ir2vecHandlerType); - if (ir2vecHandlerObj == NULL) { - return NULL; - } - ir2vecHandlerObj->ir2vecObj = ir2vecObj; - return ir2vecHandlerObj; -} - -PyObject *initEmbedding(PyObject *self, PyObject *args) { - Py_Initialize(); - const char *filename = "\0"; - const char *mode = "\0"; - const char *level = "\0"; - const char *output_file = "\0"; - - if (!PyArg_ParseTuple(args, "sss|s", &filename, &mode, &level, &output_file)) { - // raise error here - PyErr_SetString(PyExc_TypeError, "Invalid Arguments"); - return NULL; - } - - if (fileNotValid(filename)) { - PyErr_SetString(PyExc_TypeError, "Invalid File Path"); - return NULL; - } - - if (string(output_file).empty() == false) { - if (fileNotValid(output_file)) { - PyErr_SetString(PyExc_TypeError, "Invalid Output File Path"); - return NULL; - } - } - - if (string(mode) != string("sym") && string(mode) != string("fa")) { - PyErr_SetString(PyExc_TypeError, - "Eroneous mode entered . Either of sym, fa should be " - "specified"); - return NULL; - } - - if (level[0] != 'p' && level[0] != 'f') { - PyErr_SetString(PyExc_TypeError, - "Invalid level specified: Use either p or f"); - return NULL; - } - - ir2vecHandlerObject *ir2vecObj = createIR2VECObject(filename, output_file, mode, level); - - if (ir2vecObj == NULL) { - PyErr_SetString(PyExc_TypeError, "Embedding Object not created"); - return NULL; - } - - return (PyObject*)ir2vecObj; -} - -PyMethodDef IR2Vec_core_Methods[] = { - { - "initEmbedding", (PyCFunction)initEmbedding, METH_VARARGS, - "Create an Embedding Object" - }, - { - "getInstructionVectors", (PyCFunction)getInstructionVectors, METH_VARARGS, - "Get Instruction Vectors" - }, - { - "getProgramVector", (PyCFunction)getProgramVector, METH_VARARGS, - "Get Program Vector" - }, - { - "getFunctionVectors", (PyCFunction)getFunctionVectors, METH_VARARGS, - "Get Function Vectors" - }, - { - "setSeedEmbdPath", (PyCFunction)setSeedEmbeddingPath, METH_VARARGS, - "Set Seed Embedding Path" - }, - { - "getVersion", getIR2VecVersion, METH_VARARGS, - "Get IR2Vec Version" - }, - {NULL, NULL, 0, NULL} /* Sentinel */ -}; - -struct PyModuleDef IR2Vec_def = { - PyModuleDef_HEAD_INIT, - "IR2Vec.core", /* name of module NOT THE NAME OF PACKAGE*/ - "take .bc/.ll as input and generates corresponding IR2VEc " - "Embeddings", /* module documentation, may be NULL */ - -1, /* size of per-interpreter state of the module, - or -1 if the module keeps state in global variables. - */ - IR2Vec_core_Methods -}; - -PyMODINIT_FUNC PyInit_core(void) { - PyObject* module = PyModule_Create(&IR2Vec_def); - - if (PyType_Ready(&ir2vecHandlerType) < 0) { - return NULL; - } - - Py_INCREF(&ir2vecHandlerType); - return module; -} diff --git a/Manylinux2014_Compliant_Source/pkg/setup.py b/Manylinux2014_Compliant_Source/pkg/setup.py index 9689a808..2c9ffecc 100755 --- a/Manylinux2014_Compliant_Source/pkg/setup.py +++ b/Manylinux2014_Compliant_Source/pkg/setup.py @@ -47,7 +47,7 @@ def get_llvm_files(): IR2Vec_core = Extension( "IR2Vec.core", - sources=["IR2Vec/refactoredCore.cpp"], + sources=["IR2Vec/core.cpp"], include_dirs=["./IR2Vec"], libraries=["z"], extra_objects=["/usr/local/lib/libIR2Vec.a"] + get_llvm_files(), diff --git a/Manylinux2014_Compliant_Source/pkg/tests/test_ir2vec.py b/Manylinux2014_Compliant_Source/pkg/tests/test_ir2vec.py index 43a4337b..7c8d3ed6 100644 --- a/Manylinux2014_Compliant_Source/pkg/tests/test_ir2vec.py +++ b/Manylinux2014_Compliant_Source/pkg/tests/test_ir2vec.py @@ -49,18 +49,20 @@ def read_p_file(path): p_vectors.append(list(map(float, line.strip().split()))) return p_vectors + def assert_valid_progVector(progVector): - assert(progVector is not None) - assert(isinstance(progVector, list)) - assert(all(isinstance(x, float) for x in progVector)) + assert progVector is not None + assert isinstance(progVector, list) + assert all(isinstance(x, float) for x in progVector) return True + def assert_valid_insructionVectors(insVecMap): - assert(insVecMap is not None) + assert insVecMap is not None keys = list(insVecMap.keys()) assert len(keys) > 0 - + values = list(insVecMap.values()) assert len(values) > 0 @@ -69,16 +71,16 @@ def assert_valid_insructionVectors(insVecMap): assert vec is not None assert isinstance(vec, list) assert all(isinstance(x, float) for x in vec) - + return True def assert_valid_functionVector(functionVectorMap): - assert(functionVectorMap is not None) + assert functionVectorMap is not None keys = list(functionVectorMap.keys()) assert len(keys) > 0 - + values = list(functionVectorMap.values()) assert len(values) > 0 @@ -89,7 +91,7 @@ def assert_valid_functionVector(functionVectorMap): assert vec is not None assert isinstance(vec, list) assert all(isinstance(x, float) for x in vec) - + demagName = funcObj["demangledName"] assert isinstance(demagName, str) assert demagName is not None @@ -98,16 +100,17 @@ def assert_valid_functionVector(functionVectorMap): actName = funcObj["actualName"] assert isinstance(actName, str) assert actName is not None - + return True + def test_fa_p(): p_vectors = [] for file in ll_files: full_path = str((TEST_SUITE_DIR / file).resolve()).strip() initObj = IR2Vec.initEmbedding(full_path, "fa", "p") - assert(initObj is not None) + assert initObj is not None progVector1 = IR2Vec.getProgramVector(initObj) assert_valid_progVector(progVector1) @@ -128,14 +131,15 @@ def test_fa_p(): for idx, vec in enumerate(p_vectors_oracle): assert vec == pytest.approx(p_vectors[idx], abs=ABS_ACCURACY) + def test_sym_p(): p_vectors = [] for file in ll_files: full_path = str((TEST_SUITE_DIR / file).resolve()).strip() initObj = IR2Vec.initEmbedding(full_path, "sym", "p") - assert(initObj is not None) - + assert initObj is not None + progVector1 = IR2Vec.getProgramVector(initObj) assert_valid_progVector(progVector1) @@ -155,6 +159,7 @@ def test_sym_p(): for idx, vec in enumerate(p_vectors_oracle): assert vec == pytest.approx(p_vectors[idx], abs=ABS_ACCURACY) + def test_fa_f(): f_vecs = defaultdict(dict) for file in ll_files: @@ -162,7 +167,7 @@ def test_fa_f(): full_path = str(path).strip() initObj = IR2Vec.initEmbedding(full_path, "fa", "f") - assert(initObj is not None) + assert initObj is not None functionVectorMap = IR2Vec.getFunctionVectors(initObj) assert_valid_functionVector(functionVectorMap) @@ -181,17 +186,15 @@ def test_fa_f(): ) assert_valid_functionVector(functionOutput1) - functionOutput2 = initObj.getFunctionVectors( - funcObj["actualName"] - ) + functionOutput2 = initObj.getFunctionVectors(funcObj["actualName"]) assert_valid_functionVector(functionOutput2) - assert( - functionOutput1[fun]["vector"] == pytest.approx(functionOutput2[fun]["vector"], abs=ABS_ACCURACY) + assert functionOutput1[fun]["vector"] == pytest.approx( + functionOutput2[fun]["vector"], abs=ABS_ACCURACY ) - assert( - funcObj["vector"] == pytest.approx(functionOutput1[fun]["vector"], abs=ABS_ACCURACY) + assert funcObj["vector"] == pytest.approx( + functionOutput1[fun]["vector"], abs=ABS_ACCURACY ) print(TEST_SUITE_DIR) @@ -212,14 +215,14 @@ def test_sym_f(): full_path = str(path).strip() initObj = IR2Vec.initEmbedding(full_path, "sym", "f") - assert(initObj is not None) + assert initObj is not None functionVectorMap = IR2Vec.getFunctionVectors(initObj) assert_valid_functionVector(functionVectorMap) functionVectorMap2 = initObj.getFunctionVectors() assert_valid_functionVector(functionVectorMap2) - + for fun, funcObj in functionVectorMap.items(): assert fun == funcObj["demangledName"] @@ -231,21 +234,15 @@ def test_sym_f(): ) assert_valid_functionVector(functionOutput1) - functionOutput2 = initObj.getFunctionVectors( - funcObj["actualName"] - ) + functionOutput2 = initObj.getFunctionVectors(funcObj["actualName"]) assert_valid_functionVector(functionOutput2) - assert( - functionOutput1[fun]["vector"] == pytest.approx( - functionOutput2[fun]["vector"], abs=ABS_ACCURACY - ) + assert functionOutput1[fun]["vector"] == pytest.approx( + functionOutput2[fun]["vector"], abs=ABS_ACCURACY ) - assert( - funcObj["vector"] == pytest.approx( - functionOutput1[fun]["vector"], abs=ABS_ACCURACY - ) + assert funcObj["vector"] == pytest.approx( + functionOutput1[fun]["vector"], abs=ABS_ACCURACY ) print(TEST_SUITE_DIR) diff --git a/README.md b/README.md index 975f93d8..7d9c66b6 100644 --- a/README.md +++ b/README.md @@ -278,4 +278,4 @@ keywords = {heterogeneous systems, representation learning, compiler optimizatio Please feel free to raise issues to file a bug, pose a question, or initiate any related discussions. Pull requests are welcome :) ## License -IR2Vec is released under a BSD 4-Clause License. See the LICENSE file for more details. \ No newline at end of file +IR2Vec is released under a BSD 4-Clause License. See the LICENSE file for more details. diff --git a/experiments/Device_Mapping/DevMap.ipynb b/experiments/Device_Mapping/DevMap.ipynb index 31a41ca8..a943cb90 100644 --- a/experiments/Device_Mapping/DevMap.ipynb +++ b/experiments/Device_Mapping/DevMap.ipynb @@ -300,7 +300,7 @@ ], "source": [ "raw_embeddings, fileIndexNum = readEmd_program(\n", - " \"./output/embeddings/Device_Mapping_Symbolic_llvm16.txt\"\n", + " \"./output/embeddings/Device_Mapping_Symbolic_llvm14.txt\"\n", ")\n", "ir2vec_sym = evaluate(max_depth=10, learning_rate=0.5, n_estimators=70, seed=104)" ] @@ -359,7 +359,7 @@ ], "source": [ "raw_embeddings, fileIndexNum = readEmd_program(\n", - " \"./output/embeddings/Device_Mapping_FlowAware_llvm16.txt\"\n", + " \"./output/embeddings/Device_Mapping_FlowAware_llvm14.txt\"\n", ")\n", "ir2vec_fa = evaluate(max_depth=10, learning_rate=0.5, n_estimators=70, seed=104)" ] diff --git a/experiments/README.md b/experiments/README.md index d33d95d7..c28a803d 100644 --- a/experiments/README.md +++ b/experiments/README.md @@ -32,8 +32,8 @@ Device_Mapping | |-- cgo17-nvidia.csv |-- output | |-- embeddings -| | |-- Device_Mapping_Symbolic_llvm16.txt -| | |-- Device_Mapping_FlowAware_llvm16.txt +| | |-- Device_Mapping_Symbolic_llvm14.txt +| | |-- Device_Mapping_FlowAware_llvm14.txt |-- DevMap.ipynb ``` ## Thread Coarsening @@ -60,8 +60,8 @@ Thread_Coarsening | |-- pact-2014-runtimes.csv |-- output | |-- embeddings -| | |-- Thread_Coarsening_Symbolic_llvm16.txt -| | |-- Thread_Coarsening_FlowAware_llvm16.txt +| | |-- Thread_Coarsening_Symbolic_llvm14.txt +| | |-- Thread_Coarsening_FlowAware_llvm14.txt |-- ThreadCoarsening.ipynb ``` ## Out_Of_Vocabulary diff --git a/experiments/Thread_Coarsening/ThreadCoarsening.ipynb b/experiments/Thread_Coarsening/ThreadCoarsening.ipynb index 15aedb11..bd227854 100644 --- a/experiments/Thread_Coarsening/ThreadCoarsening.ipynb +++ b/experiments/Thread_Coarsening/ThreadCoarsening.ipynb @@ -324,7 +324,7 @@ ], "source": [ "raw_embeddings, fileIndex = readEmd_program(\n", - " \"./output/embeddings/Thread_Coarsening_Symbolic_llvm16.txt\"\n", + " \"./output/embeddings/Thread_Coarsening_Symbolic_llvm14.txt\"\n", ")\n", "ir2vec_sym = evaluate(max_depth=1, learning_rate=0.05, n_estimators=140)" ] @@ -374,7 +374,7 @@ ], "source": [ "raw_embeddings, fileIndex = readEmd_program(\n", - " \"./output/embeddings/Thread_Coarsening_FlowAware_llvm16.txt\"\n", + " \"./output/embeddings/Thread_Coarsening_FlowAware_llvm14.txt\"\n", ")\n", "ir2vec_fa = evaluate(max_depth=1, learning_rate=0.05, n_estimators=140)" ] diff --git a/seed_embeddings/OpenKE/analogies.txt b/seed_embeddings/OpenKE/analogies.txt index 51b15865..73acc0a0 100644 --- a/seed_embeddings/OpenKE/analogies.txt +++ b/seed_embeddings/OpenKE/analogies.txt @@ -3,53 +3,53 @@ shufflevector vectorTy getelementptr integerTy shufflevector vectorTy getelementptr voidTy shufflevector vectorTy getelementptr floatTy shufflevector vectorTy getelementptr pointerTy -load pointerty store voidty -trunc integerTy fptrunc floatTy -ptrtoint integerTy inttoptr pointerTy -add integerty fadd floatty -fsub floatty sub integerty -fmul floatty mul integerty -fdiv floatty sdiv integerty -fdiv floatty udiv integerty -srem integerty shufflevector vectorty -zext integerTy fpext floatTy -sext integerTy fpext floatTy -fptosi floatTy sitofp integerty -fcmp floatty icmp integerty -uitofp integerty fptoui floatty -inttoptr integerty ptrtoint pointerty -insertvalue structty insertelement vectorty +load pointerty store voidty +trunc integerTy fptrunc floatTy +ptrtoint integerTy inttoptr pointerTy +add integerty fadd floatty +fsub floatty sub integerty +fmul floatty mul integerty +fdiv floatty sdiv integerty +fdiv floatty udiv integerty +srem integerty shufflevector vectorty +zext integerTy fpext floatTy +sext integerTy fpext floatTy +fptosi floatTy sitofp integerty +fcmp floatty icmp integerty +uitofp integerty fptoui floatty +inttoptr integerty ptrtoint pointerty +insertvalue structty insertelement vectorty PHI INTEGERTY FADD FLOATTY EXTRACTELEMENT VECTORTY EXTRACTVALUE structTy FPEXT FLOATTY SEXT INTEGERTY -fadd fsub add sub -add fadd sub fsub -fdiv sdiv fmul mul -add sdiv fadd fdiv -add udiv fadd fdiv -trunc fptrunc icmp fcmp +fadd fsub add sub +add fadd sub fsub +fdiv sdiv fmul mul +add sdiv fadd fdiv +add udiv fadd fdiv +trunc fptrunc icmp fcmp UREM SREM UDIV SDIV TRUNC fptrunc ZEXT FPEXT TRUNC SEXT FPTRUNC FPEXT -shl lshr mul udiv -shl ashr mul sdiv -call ret switch label -function ret switch br -load store landingpad invoke -invoke landingpad function call -extractvalue insertvalue extractelement insertelement -inttoptr ptrtoint trunc zext -inttoptr ptrtoint trunc sext -icmp and mul shl -icmp or mul shl -Inttoptr pointer ptrtoint variable -ptrtoint pointer inttoptr variable -pointerty pointer integerty variable -load pointer store variable -load pointer store constant -pointerty pointer integerty constant -call function ret constant -call function ret variable +shl lshr mul udiv +shl ashr mul sdiv +call ret switch label +function ret switch br +load store landingpad invoke +invoke landingpad function call +extractvalue insertvalue extractelement insertelement +inttoptr ptrtoint trunc zext +inttoptr ptrtoint trunc sext +icmp and mul shl +icmp or mul shl +Inttoptr pointer ptrtoint variable +ptrtoint pointer inttoptr variable +pointerty pointer integerty variable +load pointer store variable +load pointer store constant +pointerty pointer integerty constant +call function ret constant +call function ret variable PHI VARIABLE LOAD pointer and or shl lshr -and or udiv urem \ No newline at end of file +and or udiv urem diff --git a/seed_embeddings/OpenKE/analogy.py b/seed_embeddings/OpenKE/analogy.py index cb1a4849..fcbab3a6 100644 --- a/seed_embeddings/OpenKE/analogy.py +++ b/seed_embeddings/OpenKE/analogy.py @@ -1,18 +1,19 @@ import heapq import sys, re import numpy as np -import pandas as pd +import pandas as pd from collections import OrderedDict from scipy import spatial + def findVec(str1, src): with open(src) as f: content = f.read() - #print("searching for ", str1) - start = content.upper().find("\n"+str1.upper()+":[") + len(str1) + 3 - if(start == -1): + # print("searching for ", str1) + start = content.upper().find("\n" + str1.upper() + ":[") + len(str1) + 3 + if start == -1: print(str1, " not found") - return + return else: end = content.find("]", start) vecstr = content[start:end].split(", ") @@ -20,20 +21,22 @@ def findVec(str1, src): # print(vec) return vec + def genSimilarityTable(vec, src): # opcVec = findVec(opc, src) with open(src) as f: - lines = [line.strip('\n\t') for line in f] + lines = [line.strip("\n\t") for line in f] cosineDict = {} euclDict = {} for line in lines: - opcode = line[0:line.find(":[")].upper() - valueStr = line[line.find(":[")+2:-2].split(", ") + opcode = line[0 : line.find(":[")].upper() + valueStr = line[line.find(":[") + 2 : -2].split(", ") value = [float(element) for element in valueStr] cosineDict[opcode] = spatial.distance.cosine(vec, value) euclDict[opcode] = spatial.distance.euclidean(vec, value) return cosineDict, euclDict + def findTopk(dict1, k, values): # print(sorted(dict.items(), key=lambda x: x[1])) # k_keys_sorted_by_values = heapq.nsmallest(k+1, dict1, key=dict1.get) @@ -46,38 +49,41 @@ def findTopk(dict1, k, values): del sortedByVal[values[2].upper()] return {k: sortedByVal[k] for k in list(sortedByVal)[:k]} + def getAnalogyScore(fileName): - refFile = '/home/intern23002/iitH/ir2vec/IR2Vec/seed_embeddings/OpenKE/analogies.txt' + refFile = ( + "/home/intern23002/iitH/ir2vec/IR2Vec/seed_embeddings/OpenKE/analogies.txt" + ) with open(refFile) as f: - analogies = [line.strip('\n') for line in f] + analogies = [line.strip("\n") for line in f] totalCnt = 0 fileCorrectCnt = {} avg = [] correctCnt = 0 for analogy in analogies: - totalCnt = totalCnt+1 + totalCnt = totalCnt + 1 # values = [val for val in analogy.strip('\t')] values = analogy.split(" ") # print(values) # fileName = argv[0] - + vecA = findVec(values[0], fileName) vecB = findVec(values[1], fileName) vecC = findVec(values[2], fileName) # vecD = np.asarray(vecA) - np.asarray(vecB) + np.asarray(vecC) vecD = np.asarray(vecB) - np.asarray(vecA) + np.asarray(vecC) - + del vecA del vecB del vecC - + # print(vecD) cosineDict, euclDict = genSimilarityTable(vecD, fileName) - topKCosineDict = findTopk(cosineDict,5,values) + topKCosineDict = findTopk(cosineDict, 5, values) if values[3].upper() in topKCosineDict: - correctCnt = correctCnt+1 + correctCnt = correctCnt + 1 # print(values, ' : ', '\033[92m' + u'\u2713' + '\033[0m', topKCosineDict[values[3].upper()]) avg.append(topKCosineDict[values[3].upper()]) else: diff --git a/seed_embeddings/OpenKE/base/Base.cpp b/seed_embeddings/OpenKE/base/Base.cpp index 417f049d..c3b0334b 100644 --- a/seed_embeddings/OpenKE/base/Base.cpp +++ b/seed_embeddings/OpenKE/base/Base.cpp @@ -38,118 +38,116 @@ extern "C" void randReset(); extern "C" void importTrainFiles(); struct Parameter { - INT id; - INT *batch_h; - INT *batch_t; - INT *batch_r; - REAL *batch_y; - INT batchSize; - INT negRate; - INT negRelRate; - INT headBatchFlag; + INT id; + INT *batch_h; + INT *batch_t; + INT *batch_r; + REAL *batch_y; + INT batchSize; + INT negRate; + INT negRelRate; + INT headBatchFlag; }; void *getBatch(void *con) { - Parameter *para = (Parameter *)(con); - INT id = para->id; - INT *batch_h = para->batch_h; - INT *batch_t = para->batch_t; - INT *batch_r = para->batch_r; - REAL *batch_y = para->batch_y; - INT batchSize = para->batchSize; - INT negRate = para->negRate; - INT negRelRate = para->negRelRate; - INT headBatchFlag = para->headBatchFlag; - INT lef, rig; - if (batchSize % workThreads == 0) { - lef = id * (batchSize / workThreads); - rig = (id + 1) * (batchSize / workThreads); - } else { - lef = id * (batchSize / workThreads + 1); - rig = (id + 1) * (batchSize / workThreads + 1); - if (rig > batchSize) - rig = batchSize; - } - REAL prob = 500; - for (INT batch = lef; batch < rig; batch++) { - INT i = rand_max(id, trainTotal); - batch_h[batch] = trainList[i].h; - batch_t[batch] = trainList[i].t; - batch_r[batch] = trainList[i].r; - batch_y[batch] = 1; - INT last = batchSize; - for (INT times = 0; times < negRate; times++) { - if (!crossSamplingFlag) { - if (bernFlag) - prob = 1000 * right_mean[trainList[i].r] / - (right_mean[trainList[i].r] + - left_mean[trainList[i].r]); - if (randd(id) % 1000 < prob) { - batch_h[batch + last] = trainList[i].h; - batch_t[batch + last] = - corrupt_head(id, trainList[i].h, trainList[i].r); - batch_r[batch + last] = trainList[i].r; - } else { - batch_h[batch + last] = - corrupt_tail(id, trainList[i].t, trainList[i].r); - ; - batch_t[batch + last] = trainList[i].t; - batch_r[batch + last] = trainList[i].r; - } - batch_y[batch + last] = -1; - last += batchSize; - } else { - if (headBatchFlag) { - batch_h[batch + last] = - corrupt_tail(id, trainList[i].t, trainList[i].r); - batch_t[batch + last] = trainList[i].t; - batch_r[batch + last] = trainList[i].r; - } else { - batch_h[batch + last] = trainList[i].h; - batch_t[batch + last] = - corrupt_head(id, trainList[i].h, trainList[i].r); - batch_r[batch + last] = trainList[i].r; - } - batch_y[batch + last] = -1; - last += batchSize; - } + Parameter *para = (Parameter *)(con); + INT id = para->id; + INT *batch_h = para->batch_h; + INT *batch_t = para->batch_t; + INT *batch_r = para->batch_r; + REAL *batch_y = para->batch_y; + INT batchSize = para->batchSize; + INT negRate = para->negRate; + INT negRelRate = para->negRelRate; + INT headBatchFlag = para->headBatchFlag; + INT lef, rig; + if (batchSize % workThreads == 0) { + lef = id * (batchSize / workThreads); + rig = (id + 1) * (batchSize / workThreads); + } else { + lef = id * (batchSize / workThreads + 1); + rig = (id + 1) * (batchSize / workThreads + 1); + if (rig > batchSize) + rig = batchSize; + } + REAL prob = 500; + for (INT batch = lef; batch < rig; batch++) { + INT i = rand_max(id, trainTotal); + batch_h[batch] = trainList[i].h; + batch_t[batch] = trainList[i].t; + batch_r[batch] = trainList[i].r; + batch_y[batch] = 1; + INT last = batchSize; + for (INT times = 0; times < negRate; times++) { + if (!crossSamplingFlag) { + if (bernFlag) + prob = 1000 * right_mean[trainList[i].r] / + (right_mean[trainList[i].r] + left_mean[trainList[i].r]); + if (randd(id) % 1000 < prob) { + batch_h[batch + last] = trainList[i].h; + batch_t[batch + last] = + corrupt_head(id, trainList[i].h, trainList[i].r); + batch_r[batch + last] = trainList[i].r; + } else { + batch_h[batch + last] = + corrupt_tail(id, trainList[i].t, trainList[i].r); + ; + batch_t[batch + last] = trainList[i].t; + batch_r[batch + last] = trainList[i].r; } - for (INT times = 0; times < negRelRate; times++) { - batch_h[batch + last] = trainList[i].h; - batch_t[batch + last] = trainList[i].t; - batch_r[batch + last] = - corrupt_rel(id, trainList[i].h, trainList[i].t); - batch_y[batch + last] = -1; - last += batchSize; + batch_y[batch + last] = -1; + last += batchSize; + } else { + if (headBatchFlag) { + batch_h[batch + last] = + corrupt_tail(id, trainList[i].t, trainList[i].r); + batch_t[batch + last] = trainList[i].t; + batch_r[batch + last] = trainList[i].r; + } else { + batch_h[batch + last] = trainList[i].h; + batch_t[batch + last] = + corrupt_head(id, trainList[i].h, trainList[i].r); + batch_r[batch + last] = trainList[i].r; } + batch_y[batch + last] = -1; + last += batchSize; + } + } + for (INT times = 0; times < negRelRate; times++) { + batch_h[batch + last] = trainList[i].h; + batch_t[batch + last] = trainList[i].t; + batch_r[batch + last] = corrupt_rel(id, trainList[i].h, trainList[i].t); + batch_y[batch + last] = -1; + last += batchSize; } - pthread_exit(NULL); + } + pthread_exit(NULL); } extern "C" void sampling(INT *batch_h, INT *batch_t, INT *batch_r, REAL *batch_y, INT batchSize, INT negRate = 1, INT negRelRate = 0, INT headBatchFlag = 0) { - pthread_t *pt = (pthread_t *)malloc(workThreads * sizeof(pthread_t)); - Parameter *para = (Parameter *)malloc(workThreads * sizeof(Parameter)); - for (INT threads = 0; threads < workThreads; threads++) { - para[threads].id = threads; - para[threads].batch_h = batch_h; - para[threads].batch_t = batch_t; - para[threads].batch_r = batch_r; - para[threads].batch_y = batch_y; - para[threads].batchSize = batchSize; - para[threads].negRate = negRate; - para[threads].negRelRate = negRelRate; - para[threads].headBatchFlag = headBatchFlag; - pthread_create(&pt[threads], NULL, getBatch, (void *)(para + threads)); - } - for (INT threads = 0; threads < workThreads; threads++) - pthread_join(pt[threads], NULL); - free(pt); - free(para); + pthread_t *pt = (pthread_t *)malloc(workThreads * sizeof(pthread_t)); + Parameter *para = (Parameter *)malloc(workThreads * sizeof(Parameter)); + for (INT threads = 0; threads < workThreads; threads++) { + para[threads].id = threads; + para[threads].batch_h = batch_h; + para[threads].batch_t = batch_t; + para[threads].batch_r = batch_r; + para[threads].batch_y = batch_y; + para[threads].batchSize = batchSize; + para[threads].negRate = negRate; + para[threads].negRelRate = negRelRate; + para[threads].headBatchFlag = headBatchFlag; + pthread_create(&pt[threads], NULL, getBatch, (void *)(para + threads)); + } + for (INT threads = 0; threads < workThreads; threads++) + pthread_join(pt[threads], NULL); + free(pt); + free(para); } int main() { - importTrainFiles(); - return 0; + importTrainFiles(); + return 0; } diff --git a/seed_embeddings/OpenKE/base/Corrupt.h b/seed_embeddings/OpenKE/base/Corrupt.h index 24185249..586970d3 100644 --- a/seed_embeddings/OpenKE/base/Corrupt.h +++ b/seed_embeddings/OpenKE/base/Corrupt.h @@ -5,159 +5,159 @@ #include "Triple.h" INT corrupt_head(INT id, INT h, INT r) { - INT lef, rig, mid, ll, rr; - lef = lefHead[h] - 1; - rig = rigHead[h]; - while (lef + 1 < rig) { - mid = (lef + rig) >> 1; - if (trainHead[mid].r >= r) - rig = mid; - else - lef = mid; - } - ll = rig; - lef = lefHead[h]; - rig = rigHead[h] + 1; - while (lef + 1 < rig) { - mid = (lef + rig) >> 1; - if (trainHead[mid].r <= r) - lef = mid; - else - rig = mid; - } - rr = lef; - INT tmp = rand_max(id, entityTotal - (rr - ll + 1)); - if (tmp < trainHead[ll].t) - return tmp; - if (tmp > trainHead[rr].t - rr + ll - 1) - return tmp + rr - ll + 1; - lef = ll, rig = rr + 1; - while (lef + 1 < rig) { - mid = (lef + rig) >> 1; - if (trainHead[mid].t - mid + ll - 1 < tmp) - lef = mid; - else - rig = mid; - } - return tmp + lef - ll + 1; + INT lef, rig, mid, ll, rr; + lef = lefHead[h] - 1; + rig = rigHead[h]; + while (lef + 1 < rig) { + mid = (lef + rig) >> 1; + if (trainHead[mid].r >= r) + rig = mid; + else + lef = mid; + } + ll = rig; + lef = lefHead[h]; + rig = rigHead[h] + 1; + while (lef + 1 < rig) { + mid = (lef + rig) >> 1; + if (trainHead[mid].r <= r) + lef = mid; + else + rig = mid; + } + rr = lef; + INT tmp = rand_max(id, entityTotal - (rr - ll + 1)); + if (tmp < trainHead[ll].t) + return tmp; + if (tmp > trainHead[rr].t - rr + ll - 1) + return tmp + rr - ll + 1; + lef = ll, rig = rr + 1; + while (lef + 1 < rig) { + mid = (lef + rig) >> 1; + if (trainHead[mid].t - mid + ll - 1 < tmp) + lef = mid; + else + rig = mid; + } + return tmp + lef - ll + 1; } INT corrupt_tail(INT id, INT t, INT r) { - INT lef, rig, mid, ll, rr; - lef = lefTail[t] - 1; - rig = rigTail[t]; - while (lef + 1 < rig) { - mid = (lef + rig) >> 1; - if (trainTail[mid].r >= r) - rig = mid; - else - lef = mid; - } - ll = rig; - lef = lefTail[t]; - rig = rigTail[t] + 1; - while (lef + 1 < rig) { - mid = (lef + rig) >> 1; - if (trainTail[mid].r <= r) - lef = mid; - else - rig = mid; - } - rr = lef; - INT tmp = rand_max(id, entityTotal - (rr - ll + 1)); - if (tmp < trainTail[ll].h) - return tmp; - if (tmp > trainTail[rr].h - rr + ll - 1) - return tmp + rr - ll + 1; - lef = ll, rig = rr + 1; - while (lef + 1 < rig) { - mid = (lef + rig) >> 1; - if (trainTail[mid].h - mid + ll - 1 < tmp) - lef = mid; - else - rig = mid; - } - return tmp + lef - ll + 1; + INT lef, rig, mid, ll, rr; + lef = lefTail[t] - 1; + rig = rigTail[t]; + while (lef + 1 < rig) { + mid = (lef + rig) >> 1; + if (trainTail[mid].r >= r) + rig = mid; + else + lef = mid; + } + ll = rig; + lef = lefTail[t]; + rig = rigTail[t] + 1; + while (lef + 1 < rig) { + mid = (lef + rig) >> 1; + if (trainTail[mid].r <= r) + lef = mid; + else + rig = mid; + } + rr = lef; + INT tmp = rand_max(id, entityTotal - (rr - ll + 1)); + if (tmp < trainTail[ll].h) + return tmp; + if (tmp > trainTail[rr].h - rr + ll - 1) + return tmp + rr - ll + 1; + lef = ll, rig = rr + 1; + while (lef + 1 < rig) { + mid = (lef + rig) >> 1; + if (trainTail[mid].h - mid + ll - 1 < tmp) + lef = mid; + else + rig = mid; + } + return tmp + lef - ll + 1; } INT corrupt_rel(INT id, INT h, INT t) { - INT lef, rig, mid, ll, rr; - lef = lefRel[h] - 1; - rig = rigRel[h]; - while (lef + 1 < rig) { - mid = (lef + rig) >> 1; - if (trainRel[mid].t >= t) - rig = mid; - else - lef = mid; - } - ll = rig; - lef = lefRel[h]; - rig = rigRel[h] + 1; - while (lef + 1 < rig) { - mid = (lef + rig) >> 1; - if (trainRel[mid].t <= t) - lef = mid; - else - rig = mid; - } - rr = lef; - INT tmp = rand_max(id, relationTotal - (rr - ll + 1)); - if (tmp < trainRel[ll].r) - return tmp; - if (tmp > trainRel[rr].r - rr + ll - 1) - return tmp + rr - ll + 1; - lef = ll, rig = rr + 1; - while (lef + 1 < rig) { - mid = (lef + rig) >> 1; - if (trainRel[mid].r - mid + ll - 1 < tmp) - lef = mid; - else - rig = mid; - } - return tmp + lef - ll + 1; + INT lef, rig, mid, ll, rr; + lef = lefRel[h] - 1; + rig = rigRel[h]; + while (lef + 1 < rig) { + mid = (lef + rig) >> 1; + if (trainRel[mid].t >= t) + rig = mid; + else + lef = mid; + } + ll = rig; + lef = lefRel[h]; + rig = rigRel[h] + 1; + while (lef + 1 < rig) { + mid = (lef + rig) >> 1; + if (trainRel[mid].t <= t) + lef = mid; + else + rig = mid; + } + rr = lef; + INT tmp = rand_max(id, relationTotal - (rr - ll + 1)); + if (tmp < trainRel[ll].r) + return tmp; + if (tmp > trainRel[rr].r - rr + ll - 1) + return tmp + rr - ll + 1; + lef = ll, rig = rr + 1; + while (lef + 1 < rig) { + mid = (lef + rig) >> 1; + if (trainRel[mid].r - mid + ll - 1 < tmp) + lef = mid; + else + rig = mid; + } + return tmp + lef - ll + 1; } bool _find(INT h, INT t, INT r) { - INT lef = 0; - INT rig = tripleTotal - 1; - INT mid; - while (lef + 1 < rig) { - INT mid = (lef + rig) >> 1; - if ((tripleList[mid].h < h) || - (tripleList[mid].h == h && tripleList[mid].r < r) || - (tripleList[mid].h == h && tripleList[mid].r == r && - tripleList[mid].t < t)) - lef = mid; - else - rig = mid; - } - if (tripleList[lef].h == h && tripleList[lef].r == r && - tripleList[lef].t == t) - return true; - if (tripleList[rig].h == h && tripleList[rig].r == r && - tripleList[rig].t == t) - return true; - return false; + INT lef = 0; + INT rig = tripleTotal - 1; + INT mid; + while (lef + 1 < rig) { + INT mid = (lef + rig) >> 1; + if ((tripleList[mid].h < h) || + (tripleList[mid].h == h && tripleList[mid].r < r) || + (tripleList[mid].h == h && tripleList[mid].r == r && + tripleList[mid].t < t)) + lef = mid; + else + rig = mid; + } + if (tripleList[lef].h == h && tripleList[lef].r == r && + tripleList[lef].t == t) + return true; + if (tripleList[rig].h == h && tripleList[rig].r == r && + tripleList[rig].t == t) + return true; + return false; } INT corrupt(INT h, INT r) { - INT ll = tail_lef[r]; - INT rr = tail_rig[r]; - INT loop = 0; - INT t; - while (1) { - t = tail_type[rand(ll, rr)]; - if (not _find(h, t, r)) { - // printf("r:%ld\tt:%ld\n", r, t); - return t; - } else { - loop++; - if (loop >= 1000) { - // printf("drop\n"); - return corrupt_head(0, h, r); - } - } + INT ll = tail_lef[r]; + INT rr = tail_rig[r]; + INT loop = 0; + INT t; + while (1) { + t = tail_type[rand(ll, rr)]; + if (not _find(h, t, r)) { + // printf("r:%ld\tt:%ld\n", r, t); + return t; + } else { + loop++; + if (loop >= 1000) { + // printf("drop\n"); + return corrupt_head(0, h, r); + } } + } } #endif diff --git a/seed_embeddings/OpenKE/base/Random.h b/seed_embeddings/OpenKE/base/Random.h index 54f62785..78d63a8e 100644 --- a/seed_embeddings/OpenKE/base/Random.h +++ b/seed_embeddings/OpenKE/base/Random.h @@ -6,22 +6,22 @@ unsigned long long *next_random; extern "C" void randReset() { - next_random = - (unsigned long long *)calloc(workThreads, sizeof(unsigned long long)); - for (INT i = 0; i < workThreads; i++) - next_random[i] = rand(); + next_random = + (unsigned long long *)calloc(workThreads, sizeof(unsigned long long)); + for (INT i = 0; i < workThreads; i++) + next_random[i] = rand(); } unsigned long long randd(INT id) { - next_random[id] = next_random[id] * (unsigned long long)25214903917 + 11; - return next_random[id]; + next_random[id] = next_random[id] * (unsigned long long)25214903917 + 11; + return next_random[id]; } INT rand_max(INT id, INT x) { - INT res = randd(id) % x; - while (res < 0) - res += x; - return res; + INT res = randd(id) % x; + while (res < 0) + res += x; + return res; } //[a,b) diff --git a/seed_embeddings/OpenKE/base/Reader.h b/seed_embeddings/OpenKE/base/Reader.h index 2c6db1c7..45bb797b 100644 --- a/seed_embeddings/OpenKE/base/Reader.h +++ b/seed_embeddings/OpenKE/base/Reader.h @@ -22,127 +22,127 @@ INT *validLef, *validRig; extern "C" void importTrainFiles() { - printf("The toolkit is importing datasets.\n"); - FILE *fin; - int tmp; - - fin = fopen((inPath + "relation2id.txt").c_str(), "r"); - - if (fin == nullptr) { - std::cout << '`' << inPath << "relation2id.txt" << '`' - << " does not exist" << std::endl; - return; + printf("The toolkit is importing datasets.\n"); + FILE *fin; + int tmp; + + fin = fopen((inPath + "relation2id.txt").c_str(), "r"); + + if (fin == nullptr) { + std::cout << '`' << inPath << "relation2id.txt" << '`' << " does not exist" + << std::endl; + return; + } + + tmp = fscanf(fin, "%ld", &relationTotal); + printf("The total of relations is %ld.\n", relationTotal); + fclose(fin); + + fin = fopen((inPath + "entity2id.txt").c_str(), "r"); + + if (fin == nullptr) { + std::cout << '`' << inPath << "entity2id.txt" << '`' << " does not exist" + << std::endl; + return; + } + + tmp = fscanf(fin, "%ld", &entityTotal); + printf("The total of entities is %ld.\n", entityTotal); + fclose(fin); + + fin = fopen((inPath + "train2id.txt").c_str(), "r"); + + if (fin == nullptr) { + std::cout << '`' << inPath << "train2id.txt" << '`' << " does not exist" + << std::endl; + return; + } + + tmp = fscanf(fin, "%ld", &trainTotal); + trainList = (Triple *)calloc(trainTotal, sizeof(Triple)); + trainHead = (Triple *)calloc(trainTotal, sizeof(Triple)); + trainTail = (Triple *)calloc(trainTotal, sizeof(Triple)); + trainRel = (Triple *)calloc(trainTotal, sizeof(Triple)); + freqRel = (INT *)calloc(relationTotal, sizeof(INT)); + freqEnt = (INT *)calloc(entityTotal, sizeof(INT)); + for (INT i = 0; i < trainTotal; i++) { + tmp = fscanf(fin, "%ld", &trainList[i].h); + tmp = fscanf(fin, "%ld", &trainList[i].t); + tmp = fscanf(fin, "%ld", &trainList[i].r); + } + fclose(fin); + std::sort(trainList, trainList + trainTotal, Triple::cmp_head); + tmp = trainTotal; + trainTotal = 1; + trainHead[0] = trainTail[0] = trainRel[0] = trainList[0]; + freqEnt[trainList[0].t] += 1; + freqEnt[trainList[0].h] += 1; + freqRel[trainList[0].r] += 1; + for (INT i = 1; i < tmp; i++) + if (trainList[i].h != trainList[i - 1].h || + trainList[i].r != trainList[i - 1].r || + trainList[i].t != trainList[i - 1].t) { + trainHead[trainTotal] = trainTail[trainTotal] = trainRel[trainTotal] = + trainList[trainTotal] = trainList[i]; + trainTotal++; + freqEnt[trainList[i].t]++; + freqEnt[trainList[i].h]++; + freqRel[trainList[i].r]++; } - tmp = fscanf(fin, "%ld", &relationTotal); - printf("The total of relations is %ld.\n", relationTotal); - fclose(fin); - - fin = fopen((inPath + "entity2id.txt").c_str(), "r"); - - if (fin == nullptr) { - std::cout << '`' << inPath << "entity2id.txt" << '`' - << " does not exist" << std::endl; - return; + std::sort(trainHead, trainHead + trainTotal, Triple::cmp_head); + std::sort(trainTail, trainTail + trainTotal, Triple::cmp_tail); + std::sort(trainRel, trainRel + trainTotal, Triple::cmp_rel); + printf("The total of train triples is %ld.\n", trainTotal); + + lefHead = (INT *)calloc(entityTotal, sizeof(INT)); + rigHead = (INT *)calloc(entityTotal, sizeof(INT)); + lefTail = (INT *)calloc(entityTotal, sizeof(INT)); + rigTail = (INT *)calloc(entityTotal, sizeof(INT)); + lefRel = (INT *)calloc(entityTotal, sizeof(INT)); + rigRel = (INT *)calloc(entityTotal, sizeof(INT)); + memset(rigHead, -1, sizeof(INT) * entityTotal); + memset(rigTail, -1, sizeof(INT) * entityTotal); + memset(rigRel, -1, sizeof(INT) * entityTotal); + for (INT i = 1; i < trainTotal; i++) { + if (trainTail[i].t != trainTail[i - 1].t) { + rigTail[trainTail[i - 1].t] = i - 1; + lefTail[trainTail[i].t] = i; } - - tmp = fscanf(fin, "%ld", &entityTotal); - printf("The total of entities is %ld.\n", entityTotal); - fclose(fin); - - fin = fopen((inPath + "train2id.txt").c_str(), "r"); - - if (fin == nullptr) { - std::cout << '`' << inPath << "train2id.txt" << '`' << " does not exist" - << std::endl; - return; + if (trainHead[i].h != trainHead[i - 1].h) { + rigHead[trainHead[i - 1].h] = i - 1; + lefHead[trainHead[i].h] = i; } - - tmp = fscanf(fin, "%ld", &trainTotal); - trainList = (Triple *)calloc(trainTotal, sizeof(Triple)); - trainHead = (Triple *)calloc(trainTotal, sizeof(Triple)); - trainTail = (Triple *)calloc(trainTotal, sizeof(Triple)); - trainRel = (Triple *)calloc(trainTotal, sizeof(Triple)); - freqRel = (INT *)calloc(relationTotal, sizeof(INT)); - freqEnt = (INT *)calloc(entityTotal, sizeof(INT)); - for (INT i = 0; i < trainTotal; i++) { - tmp = fscanf(fin, "%ld", &trainList[i].h); - tmp = fscanf(fin, "%ld", &trainList[i].t); - tmp = fscanf(fin, "%ld", &trainList[i].r); - } - fclose(fin); - std::sort(trainList, trainList + trainTotal, Triple::cmp_head); - tmp = trainTotal; - trainTotal = 1; - trainHead[0] = trainTail[0] = trainRel[0] = trainList[0]; - freqEnt[trainList[0].t] += 1; - freqEnt[trainList[0].h] += 1; - freqRel[trainList[0].r] += 1; - for (INT i = 1; i < tmp; i++) - if (trainList[i].h != trainList[i - 1].h || - trainList[i].r != trainList[i - 1].r || - trainList[i].t != trainList[i - 1].t) { - trainHead[trainTotal] = trainTail[trainTotal] = - trainRel[trainTotal] = trainList[trainTotal] = trainList[i]; - trainTotal++; - freqEnt[trainList[i].t]++; - freqEnt[trainList[i].h]++; - freqRel[trainList[i].r]++; - } - - std::sort(trainHead, trainHead + trainTotal, Triple::cmp_head); - std::sort(trainTail, trainTail + trainTotal, Triple::cmp_tail); - std::sort(trainRel, trainRel + trainTotal, Triple::cmp_rel); - printf("The total of train triples is %ld.\n", trainTotal); - - lefHead = (INT *)calloc(entityTotal, sizeof(INT)); - rigHead = (INT *)calloc(entityTotal, sizeof(INT)); - lefTail = (INT *)calloc(entityTotal, sizeof(INT)); - rigTail = (INT *)calloc(entityTotal, sizeof(INT)); - lefRel = (INT *)calloc(entityTotal, sizeof(INT)); - rigRel = (INT *)calloc(entityTotal, sizeof(INT)); - memset(rigHead, -1, sizeof(INT) * entityTotal); - memset(rigTail, -1, sizeof(INT) * entityTotal); - memset(rigRel, -1, sizeof(INT) * entityTotal); - for (INT i = 1; i < trainTotal; i++) { - if (trainTail[i].t != trainTail[i - 1].t) { - rigTail[trainTail[i - 1].t] = i - 1; - lefTail[trainTail[i].t] = i; - } - if (trainHead[i].h != trainHead[i - 1].h) { - rigHead[trainHead[i - 1].h] = i - 1; - lefHead[trainHead[i].h] = i; - } - if (trainRel[i].h != trainRel[i - 1].h) { - rigRel[trainRel[i - 1].h] = i - 1; - lefRel[trainRel[i].h] = i; - } - } - lefHead[trainHead[0].h] = 0; - rigHead[trainHead[trainTotal - 1].h] = trainTotal - 1; - lefTail[trainTail[0].t] = 0; - rigTail[trainTail[trainTotal - 1].t] = trainTotal - 1; - lefRel[trainRel[0].h] = 0; - rigRel[trainRel[trainTotal - 1].h] = trainTotal - 1; - - left_mean = (REAL *)calloc(relationTotal, sizeof(REAL)); - right_mean = (REAL *)calloc(relationTotal, sizeof(REAL)); - for (INT i = 0; i < entityTotal; i++) { - for (INT j = lefHead[i] + 1; j <= rigHead[i]; j++) - if (trainHead[j].r != trainHead[j - 1].r) - left_mean[trainHead[j].r] += 1.0; - if (lefHead[i] <= rigHead[i]) - left_mean[trainHead[lefHead[i]].r] += 1.0; - for (INT j = lefTail[i] + 1; j <= rigTail[i]; j++) - if (trainTail[j].r != trainTail[j - 1].r) - right_mean[trainTail[j].r] += 1.0; - if (lefTail[i] <= rigTail[i]) - right_mean[trainTail[lefTail[i]].r] += 1.0; - } - for (INT i = 0; i < relationTotal; i++) { - left_mean[i] = freqRel[i] / left_mean[i]; - right_mean[i] = freqRel[i] / right_mean[i]; + if (trainRel[i].h != trainRel[i - 1].h) { + rigRel[trainRel[i - 1].h] = i - 1; + lefRel[trainRel[i].h] = i; } + } + lefHead[trainHead[0].h] = 0; + rigHead[trainHead[trainTotal - 1].h] = trainTotal - 1; + lefTail[trainTail[0].t] = 0; + rigTail[trainTail[trainTotal - 1].t] = trainTotal - 1; + lefRel[trainRel[0].h] = 0; + rigRel[trainRel[trainTotal - 1].h] = trainTotal - 1; + + left_mean = (REAL *)calloc(relationTotal, sizeof(REAL)); + right_mean = (REAL *)calloc(relationTotal, sizeof(REAL)); + for (INT i = 0; i < entityTotal; i++) { + for (INT j = lefHead[i] + 1; j <= rigHead[i]; j++) + if (trainHead[j].r != trainHead[j - 1].r) + left_mean[trainHead[j].r] += 1.0; + if (lefHead[i] <= rigHead[i]) + left_mean[trainHead[lefHead[i]].r] += 1.0; + for (INT j = lefTail[i] + 1; j <= rigTail[i]; j++) + if (trainTail[j].r != trainTail[j - 1].r) + right_mean[trainTail[j].r] += 1.0; + if (lefTail[i] <= rigTail[i]) + right_mean[trainTail[lefTail[i]].r] += 1.0; + } + for (INT i = 0; i < relationTotal; i++) { + left_mean[i] = freqRel[i] / left_mean[i]; + right_mean[i] = freqRel[i] / right_mean[i]; + } } Triple *testList; @@ -150,110 +150,110 @@ Triple *validList; Triple *tripleList; extern "C" void importTestFiles() { - FILE *fin; - INT tmp; - - fin = fopen((inPath + "relation2id.txt").c_str(), "r"); - if (fin == nullptr) { - std::cout << '`' << inPath << "relation2id.txt" << '`' - << " does not exist" << std::endl; - return; + FILE *fin; + INT tmp; + + fin = fopen((inPath + "relation2id.txt").c_str(), "r"); + if (fin == nullptr) { + std::cout << '`' << inPath << "relation2id.txt" << '`' << " does not exist" + << std::endl; + return; + } + + tmp = fscanf(fin, "%ld", &relationTotal); + fclose(fin); + + fin = fopen((inPath + "entity2id.txt").c_str(), "r"); + if (fin == nullptr) { + std::cout << '`' << inPath << "entity2id.txt" << '`' << " does not exist" + << std::endl; + return; + } + + tmp = fscanf(fin, "%ld", &entityTotal); + fclose(fin); + + FILE *f_kb1 = fopen((inPath + "test2id.txt").c_str(), "r"); + + if (f_kb1 == nullptr) { + std::cout << '`' << inPath << "test2id.txt" << '`' << " does not exist" + << std::endl; + return; + } + + FILE *f_kb2 = fopen((inPath + "train2id.txt").c_str(), "r"); + if (f_kb2 == nullptr) { + std::cout << '`' << inPath << "train2id.txt" << '`' << " does not exist" + << std::endl; + return; + } + + FILE *f_kb3 = fopen((inPath + "valid2id.txt").c_str(), "r"); + if (f_kb3 == nullptr) { + std::cout << '`' << inPath << "valid2id.txt" << '`' << " does not exist" + << std::endl; + return; + } + + tmp = fscanf(f_kb1, "%ld", &testTotal); + tmp = fscanf(f_kb2, "%ld", &trainTotal); + tmp = fscanf(f_kb3, "%ld", &validTotal); + tripleTotal = testTotal + trainTotal + validTotal; + testList = (Triple *)calloc(testTotal, sizeof(Triple)); + validList = (Triple *)calloc(validTotal, sizeof(Triple)); + tripleList = (Triple *)calloc(tripleTotal, sizeof(Triple)); + for (INT i = 0; i < testTotal; i++) { + tmp = fscanf(f_kb1, "%ld", &testList[i].h); + tmp = fscanf(f_kb1, "%ld", &testList[i].t); + tmp = fscanf(f_kb1, "%ld", &testList[i].r); + tripleList[i] = testList[i]; + } + for (INT i = 0; i < trainTotal; i++) { + tmp = fscanf(f_kb2, "%ld", &tripleList[i + testTotal].h); + tmp = fscanf(f_kb2, "%ld", &tripleList[i + testTotal].t); + tmp = fscanf(f_kb2, "%ld", &tripleList[i + testTotal].r); + } + for (INT i = 0; i < validTotal; i++) { + tmp = fscanf(f_kb3, "%ld", &tripleList[i + testTotal + trainTotal].h); + tmp = fscanf(f_kb3, "%ld", &tripleList[i + testTotal + trainTotal].t); + tmp = fscanf(f_kb3, "%ld", &tripleList[i + testTotal + trainTotal].r); + validList[i] = tripleList[i + testTotal + trainTotal]; + } + fclose(f_kb1); + fclose(f_kb2); + fclose(f_kb3); + + std::sort(tripleList, tripleList + tripleTotal, Triple::cmp_head); + std::sort(testList, testList + testTotal, Triple::cmp_rel2); + std::sort(validList, validList + validTotal, Triple::cmp_rel2); + printf("The total of test triples is %ld.\n", testTotal); + printf("The total of valid triples is %ld.\n", validTotal); + + testLef = (INT *)calloc(relationTotal, sizeof(INT)); + testRig = (INT *)calloc(relationTotal, sizeof(INT)); + memset(testLef, -1, sizeof(INT) * relationTotal); + memset(testRig, -1, sizeof(INT) * relationTotal); + for (INT i = 1; i < testTotal; i++) { + if (testList[i].r != testList[i - 1].r) { + testRig[testList[i - 1].r] = i - 1; + testLef[testList[i].r] = i; } - - tmp = fscanf(fin, "%ld", &relationTotal); - fclose(fin); - - fin = fopen((inPath + "entity2id.txt").c_str(), "r"); - if (fin == nullptr) { - std::cout << '`' << inPath << "entity2id.txt" << '`' - << " does not exist" << std::endl; - return; + } + testLef[testList[0].r] = 0; + testRig[testList[testTotal - 1].r] = testTotal - 1; + + validLef = (INT *)calloc(relationTotal, sizeof(INT)); + validRig = (INT *)calloc(relationTotal, sizeof(INT)); + memset(validLef, -1, sizeof(INT) * relationTotal); + memset(validRig, -1, sizeof(INT) * relationTotal); + for (INT i = 1; i < validTotal; i++) { + if (validList[i].r != validList[i - 1].r) { + validRig[validList[i - 1].r] = i - 1; + validLef[validList[i].r] = i; } - - tmp = fscanf(fin, "%ld", &entityTotal); - fclose(fin); - - FILE *f_kb1 = fopen((inPath + "test2id.txt").c_str(), "r"); - - if (f_kb1 == nullptr) { - std::cout << '`' << inPath << "test2id.txt" << '`' << " does not exist" - << std::endl; - return; - } - - FILE *f_kb2 = fopen((inPath + "train2id.txt").c_str(), "r"); - if (f_kb2 == nullptr) { - std::cout << '`' << inPath << "train2id.txt" << '`' << " does not exist" - << std::endl; - return; - } - - FILE *f_kb3 = fopen((inPath + "valid2id.txt").c_str(), "r"); - if (f_kb3 == nullptr) { - std::cout << '`' << inPath << "valid2id.txt" << '`' << " does not exist" - << std::endl; - return; - } - - tmp = fscanf(f_kb1, "%ld", &testTotal); - tmp = fscanf(f_kb2, "%ld", &trainTotal); - tmp = fscanf(f_kb3, "%ld", &validTotal); - tripleTotal = testTotal + trainTotal + validTotal; - testList = (Triple *)calloc(testTotal, sizeof(Triple)); - validList = (Triple *)calloc(validTotal, sizeof(Triple)); - tripleList = (Triple *)calloc(tripleTotal, sizeof(Triple)); - for (INT i = 0; i < testTotal; i++) { - tmp = fscanf(f_kb1, "%ld", &testList[i].h); - tmp = fscanf(f_kb1, "%ld", &testList[i].t); - tmp = fscanf(f_kb1, "%ld", &testList[i].r); - tripleList[i] = testList[i]; - } - for (INT i = 0; i < trainTotal; i++) { - tmp = fscanf(f_kb2, "%ld", &tripleList[i + testTotal].h); - tmp = fscanf(f_kb2, "%ld", &tripleList[i + testTotal].t); - tmp = fscanf(f_kb2, "%ld", &tripleList[i + testTotal].r); - } - for (INT i = 0; i < validTotal; i++) { - tmp = fscanf(f_kb3, "%ld", &tripleList[i + testTotal + trainTotal].h); - tmp = fscanf(f_kb3, "%ld", &tripleList[i + testTotal + trainTotal].t); - tmp = fscanf(f_kb3, "%ld", &tripleList[i + testTotal + trainTotal].r); - validList[i] = tripleList[i + testTotal + trainTotal]; - } - fclose(f_kb1); - fclose(f_kb2); - fclose(f_kb3); - - std::sort(tripleList, tripleList + tripleTotal, Triple::cmp_head); - std::sort(testList, testList + testTotal, Triple::cmp_rel2); - std::sort(validList, validList + validTotal, Triple::cmp_rel2); - printf("The total of test triples is %ld.\n", testTotal); - printf("The total of valid triples is %ld.\n", validTotal); - - testLef = (INT *)calloc(relationTotal, sizeof(INT)); - testRig = (INT *)calloc(relationTotal, sizeof(INT)); - memset(testLef, -1, sizeof(INT) * relationTotal); - memset(testRig, -1, sizeof(INT) * relationTotal); - for (INT i = 1; i < testTotal; i++) { - if (testList[i].r != testList[i - 1].r) { - testRig[testList[i - 1].r] = i - 1; - testLef[testList[i].r] = i; - } - } - testLef[testList[0].r] = 0; - testRig[testList[testTotal - 1].r] = testTotal - 1; - - validLef = (INT *)calloc(relationTotal, sizeof(INT)); - validRig = (INT *)calloc(relationTotal, sizeof(INT)); - memset(validLef, -1, sizeof(INT) * relationTotal); - memset(validRig, -1, sizeof(INT) * relationTotal); - for (INT i = 1; i < validTotal; i++) { - if (validList[i].r != validList[i - 1].r) { - validRig[validList[i - 1].r] = i - 1; - validLef[validList[i].r] = i; - } - } - validLef[validList[0].r] = 0; - validRig[validList[validTotal - 1].r] = validTotal - 1; + } + validLef[validList[0].r] = 0; + validRig[validList[validTotal - 1].r] = validTotal - 1; } INT *head_lef; @@ -264,71 +264,71 @@ INT *head_type; INT *tail_type; extern "C" void importTypeFiles() { - head_lef = (INT *)calloc(relationTotal, sizeof(INT)); - head_rig = (INT *)calloc(relationTotal, sizeof(INT)); - tail_lef = (INT *)calloc(relationTotal, sizeof(INT)); - tail_rig = (INT *)calloc(relationTotal, sizeof(INT)); - - INT total_lef = 0; - INT total_rig = 0; - FILE *f_type = fopen((inPath + "type_constrain.txt").c_str(), "r"); - - if (f_type == nullptr) { - std::cout << '`' << inPath << "type_constrain.txt" << '`' - << " does not exist" << std::endl; - return; + head_lef = (INT *)calloc(relationTotal, sizeof(INT)); + head_rig = (INT *)calloc(relationTotal, sizeof(INT)); + tail_lef = (INT *)calloc(relationTotal, sizeof(INT)); + tail_rig = (INT *)calloc(relationTotal, sizeof(INT)); + + INT total_lef = 0; + INT total_rig = 0; + FILE *f_type = fopen((inPath + "type_constrain.txt").c_str(), "r"); + + if (f_type == nullptr) { + std::cout << '`' << inPath << "type_constrain.txt" << '`' + << " does not exist" << std::endl; + return; + } + + INT tmp; + tmp = fscanf(f_type, "%ld", &tmp); + for (INT i = 0; i < relationTotal; i++) { + INT rel, tot; + tmp = fscanf(f_type, "%ld %ld", &rel, &tot); + for (INT j = 0; j < tot; j++) { + tmp = fscanf(f_type, "%ld", &tmp); + total_lef++; } - - INT tmp; - tmp = fscanf(f_type, "%ld", &tmp); - for (INT i = 0; i < relationTotal; i++) { - INT rel, tot; - tmp = fscanf(f_type, "%ld %ld", &rel, &tot); - for (INT j = 0; j < tot; j++) { - tmp = fscanf(f_type, "%ld", &tmp); - total_lef++; - } - tmp = fscanf(f_type, "%ld%ld", &rel, &tot); - for (INT j = 0; j < tot; j++) { - tmp = fscanf(f_type, "%ld", &tmp); - total_rig++; - } + tmp = fscanf(f_type, "%ld%ld", &rel, &tot); + for (INT j = 0; j < tot; j++) { + tmp = fscanf(f_type, "%ld", &tmp); + total_rig++; } - fclose(f_type); - - head_type = (INT *)calloc(total_lef, sizeof(INT)); - tail_type = (INT *)calloc(total_rig, sizeof(INT)); - total_lef = 0; - total_rig = 0; - f_type = fopen((inPath + "type_constrain.txt").c_str(), "r"); - - if (f_type == nullptr) { - std::cout << '`' << inPath << "type_constrain.txt" << '`' - << " does not exist" << std::endl; - return; + } + fclose(f_type); + + head_type = (INT *)calloc(total_lef, sizeof(INT)); + tail_type = (INT *)calloc(total_rig, sizeof(INT)); + total_lef = 0; + total_rig = 0; + f_type = fopen((inPath + "type_constrain.txt").c_str(), "r"); + + if (f_type == nullptr) { + std::cout << '`' << inPath << "type_constrain.txt" << '`' + << " does not exist" << std::endl; + return; + } + + tmp = fscanf(f_type, "%ld", &tmp); + for (INT i = 0; i < relationTotal; i++) { + INT rel, tot; + tmp = fscanf(f_type, "%ld%ld", &rel, &tot); + head_lef[rel] = total_lef; + for (INT j = 0; j < tot; j++) { + tmp = fscanf(f_type, "%ld", &head_type[total_lef]); + total_lef++; } - - tmp = fscanf(f_type, "%ld", &tmp); - for (INT i = 0; i < relationTotal; i++) { - INT rel, tot; - tmp = fscanf(f_type, "%ld%ld", &rel, &tot); - head_lef[rel] = total_lef; - for (INT j = 0; j < tot; j++) { - tmp = fscanf(f_type, "%ld", &head_type[total_lef]); - total_lef++; - } - head_rig[rel] = total_lef; - std::sort(head_type + head_lef[rel], head_type + head_rig[rel]); - tmp = fscanf(f_type, "%ld%ld", &rel, &tot); - tail_lef[rel] = total_rig; - for (INT j = 0; j < tot; j++) { - tmp = fscanf(f_type, "%ld", &tail_type[total_rig]); - total_rig++; - } - tail_rig[rel] = total_rig; - std::sort(tail_type + tail_lef[rel], tail_type + tail_rig[rel]); + head_rig[rel] = total_lef; + std::sort(head_type + head_lef[rel], head_type + head_rig[rel]); + tmp = fscanf(f_type, "%ld%ld", &rel, &tot); + tail_lef[rel] = total_rig; + for (INT j = 0; j < tot; j++) { + tmp = fscanf(f_type, "%ld", &tail_type[total_rig]); + total_rig++; } - fclose(f_type); + tail_rig[rel] = total_rig; + std::sort(tail_type + tail_lef[rel], tail_type + tail_rig[rel]); + } + fclose(f_type); } #endif diff --git a/seed_embeddings/OpenKE/base/Setting.h b/seed_embeddings/OpenKE/base/Setting.h index d4b36324..59ee23ac 100644 --- a/seed_embeddings/OpenKE/base/Setting.h +++ b/seed_embeddings/OpenKE/base/Setting.h @@ -10,19 +10,19 @@ std::string inPath = "../data/FB15K/"; std::string outPath = "../data/FB15K/"; extern "C" void setInPath(char *path) { - INT len = strlen(path); - inPath = ""; - for (INT i = 0; i < len; i++) - inPath = inPath + path[i]; - printf("Input Files Path : %s\n", inPath.c_str()); + INT len = strlen(path); + inPath = ""; + for (INT i = 0; i < len; i++) + inPath = inPath + path[i]; + printf("Input Files Path : %s\n", inPath.c_str()); } extern "C" void setOutPath(char *path) { - INT len = strlen(path); - outPath = ""; - for (INT i = 0; i < len; i++) - outPath = outPath + path[i]; - printf("Output Files Path : %s\n", outPath.c_str()); + INT len = strlen(path); + outPath = ""; + for (INT i = 0; i < len; i++) + outPath = outPath + path[i]; + printf("Output Files Path : %s\n", outPath.c_str()); } /* diff --git a/seed_embeddings/OpenKE/base/Test.h b/seed_embeddings/OpenKE/base/Test.h index 00de7074..03ff08b3 100644 --- a/seed_embeddings/OpenKE/base/Test.h +++ b/seed_embeddings/OpenKE/base/Test.h @@ -27,292 +27,288 @@ REAL l3_filter_tot_constrain = 0, l3_tot_constrain = 0, r3_tot_constrain = 0, r_reci_rank_constrain = 0; extern "C" void initTest() { - lastHead = 0; - lastTail = 0; - l1_filter_tot = 0, l1_tot = 0, r1_tot = 0, r1_filter_tot = 0, l_tot = 0, - r_tot = 0, l_filter_rank = 0, l_rank = 0, l_filter_reci_rank = 0, - l_reci_rank = 0; - l3_filter_tot = 0, l3_tot = 0, r3_tot = 0, r3_filter_tot = 0, - l_filter_tot = 0, r_filter_tot = 0, r_filter_rank = 0, r_rank = 0, - r_filter_reci_rank = 0, r_reci_rank = 0; - - l1_filter_tot_constrain = 0, l1_tot_constrain = 0, r1_tot_constrain = 0, - r1_filter_tot_constrain = 0, l_tot_constrain = 0, r_tot_constrain = 0, - l_filter_rank_constrain = 0, l_rank_constrain = 0, - l_filter_reci_rank_constrain = 0, l_reci_rank_constrain = 0; - l3_filter_tot_constrain = 0, l3_tot_constrain = 0, r3_tot_constrain = 0, - r3_filter_tot_constrain = 0, l_filter_tot_constrain = 0, - r_filter_tot_constrain = 0, r_filter_rank_constrain = 0, - r_rank_constrain = 0, r_filter_reci_rank_constrain = 0, - r_reci_rank_constrain = 0; + lastHead = 0; + lastTail = 0; + l1_filter_tot = 0, l1_tot = 0, r1_tot = 0, r1_filter_tot = 0, l_tot = 0, + r_tot = 0, l_filter_rank = 0, l_rank = 0, l_filter_reci_rank = 0, + l_reci_rank = 0; + l3_filter_tot = 0, l3_tot = 0, r3_tot = 0, r3_filter_tot = 0, + l_filter_tot = 0, r_filter_tot = 0, r_filter_rank = 0, r_rank = 0, + r_filter_reci_rank = 0, r_reci_rank = 0; + + l1_filter_tot_constrain = 0, l1_tot_constrain = 0, r1_tot_constrain = 0, + r1_filter_tot_constrain = 0, l_tot_constrain = 0, r_tot_constrain = 0, + l_filter_rank_constrain = 0, l_rank_constrain = 0, + l_filter_reci_rank_constrain = 0, l_reci_rank_constrain = 0; + l3_filter_tot_constrain = 0, l3_tot_constrain = 0, r3_tot_constrain = 0, + r3_filter_tot_constrain = 0, l_filter_tot_constrain = 0, + r_filter_tot_constrain = 0, r_filter_rank_constrain = 0, r_rank_constrain = 0, + r_filter_reci_rank_constrain = 0, r_reci_rank_constrain = 0; } extern "C" void getHeadBatch(INT *ph, INT *pt, INT *pr) { - for (INT i = 0; i < entityTotal; i++) { - ph[i] = i; - pt[i] = testList[lastHead].t; - pr[i] = testList[lastHead].r; - } + for (INT i = 0; i < entityTotal; i++) { + ph[i] = i; + pt[i] = testList[lastHead].t; + pr[i] = testList[lastHead].r; + } } extern "C" void getTailBatch(INT *ph, INT *pt, INT *pr) { - for (INT i = 0; i < entityTotal; i++) { - ph[i] = testList[lastTail].h; - pt[i] = i; - pr[i] = testList[lastTail].r; - } + for (INT i = 0; i < entityTotal; i++) { + ph[i] = testList[lastTail].h; + pt[i] = i; + pr[i] = testList[lastTail].r; + } } extern "C" void testHead(REAL *con) { - INT h = testList[lastHead].h; - INT t = testList[lastHead].t; - INT r = testList[lastHead].r; - INT lef = head_lef[r], rig = head_rig[r]; - - REAL minimal = con[h]; - INT l_s = 0; - INT l_filter_s = 0; - INT l_s_constrain = 0; - INT l_filter_s_constrain = 0; - - for (INT j = 0; j < entityTotal; j++) { - if (j != h) { - REAL value = con[j]; - if (value < minimal) { - l_s += 1; - if (not _find(j, t, r)) - l_filter_s += 1; - } - while (lef < rig && head_type[lef] < j) - lef++; - if (lef < rig && j == head_type[lef]) { - if (value < minimal) { - l_s_constrain += 1; - if (not _find(j, t, r)) { - l_filter_s_constrain += 1; - } - } - } + INT h = testList[lastHead].h; + INT t = testList[lastHead].t; + INT r = testList[lastHead].r; + INT lef = head_lef[r], rig = head_rig[r]; + + REAL minimal = con[h]; + INT l_s = 0; + INT l_filter_s = 0; + INT l_s_constrain = 0; + INT l_filter_s_constrain = 0; + + for (INT j = 0; j < entityTotal; j++) { + if (j != h) { + REAL value = con[j]; + if (value < minimal) { + l_s += 1; + if (not _find(j, t, r)) + l_filter_s += 1; + } + while (lef < rig && head_type[lef] < j) + lef++; + if (lef < rig && j == head_type[lef]) { + if (value < minimal) { + l_s_constrain += 1; + if (not _find(j, t, r)) { + l_filter_s_constrain += 1; + } } + } } - - if (l_filter_s < 10) - l_filter_tot += 1; - if (l_s < 10) - l_tot += 1; - if (l_filter_s < 3) - l3_filter_tot += 1; - if (l_s < 3) - l3_tot += 1; - if (l_filter_s < 1) - l1_filter_tot += 1; - if (l_s < 1) - l1_tot += 1; - - if (l_filter_s_constrain < 10) - l_filter_tot_constrain += 1; - if (l_s_constrain < 10) - l_tot_constrain += 1; - if (l_filter_s_constrain < 3) - l3_filter_tot_constrain += 1; - if (l_s_constrain < 3) - l3_tot_constrain += 1; - if (l_filter_s_constrain < 1) - l1_filter_tot_constrain += 1; - if (l_s_constrain < 1) - l1_tot_constrain += 1; - - l_filter_rank += (l_filter_s + 1); - l_rank += (1 + l_s); - l_filter_reci_rank += 1.0 / (l_filter_s + 1); - l_reci_rank += 1.0 / (l_s + 1); - - l_filter_rank_constrain += (l_filter_s_constrain + 1); - l_rank_constrain += (1 + l_s_constrain); - l_filter_reci_rank_constrain += 1.0 / (l_filter_s_constrain + 1); - l_reci_rank_constrain += 1.0 / (l_s_constrain + 1); - - lastHead++; + } + + if (l_filter_s < 10) + l_filter_tot += 1; + if (l_s < 10) + l_tot += 1; + if (l_filter_s < 3) + l3_filter_tot += 1; + if (l_s < 3) + l3_tot += 1; + if (l_filter_s < 1) + l1_filter_tot += 1; + if (l_s < 1) + l1_tot += 1; + + if (l_filter_s_constrain < 10) + l_filter_tot_constrain += 1; + if (l_s_constrain < 10) + l_tot_constrain += 1; + if (l_filter_s_constrain < 3) + l3_filter_tot_constrain += 1; + if (l_s_constrain < 3) + l3_tot_constrain += 1; + if (l_filter_s_constrain < 1) + l1_filter_tot_constrain += 1; + if (l_s_constrain < 1) + l1_tot_constrain += 1; + + l_filter_rank += (l_filter_s + 1); + l_rank += (1 + l_s); + l_filter_reci_rank += 1.0 / (l_filter_s + 1); + l_reci_rank += 1.0 / (l_s + 1); + + l_filter_rank_constrain += (l_filter_s_constrain + 1); + l_rank_constrain += (1 + l_s_constrain); + l_filter_reci_rank_constrain += 1.0 / (l_filter_s_constrain + 1); + l_reci_rank_constrain += 1.0 / (l_s_constrain + 1); + + lastHead++; } extern "C" void testTail(REAL *con) { - INT h = testList[lastTail].h; - INT t = testList[lastTail].t; - INT r = testList[lastTail].r; - INT lef = tail_lef[r], rig = tail_rig[r]; - REAL minimal = con[t]; - INT r_s = 0; - INT r_filter_s = 0; - INT r_s_constrain = 0; - INT r_filter_s_constrain = 0; - for (INT j = 0; j < entityTotal; j++) { - if (j != t) { - REAL value = con[j]; - if (value < minimal) { - r_s += 1; - if (not _find(h, j, r)) - r_filter_s += 1; - } - while (lef < rig && tail_type[lef] < j) - lef++; - if (lef < rig && j == tail_type[lef]) { - if (value < minimal) { - r_s_constrain += 1; - if (not _find(h, j, r)) { - r_filter_s_constrain += 1; - } - } - } + INT h = testList[lastTail].h; + INT t = testList[lastTail].t; + INT r = testList[lastTail].r; + INT lef = tail_lef[r], rig = tail_rig[r]; + REAL minimal = con[t]; + INT r_s = 0; + INT r_filter_s = 0; + INT r_s_constrain = 0; + INT r_filter_s_constrain = 0; + for (INT j = 0; j < entityTotal; j++) { + if (j != t) { + REAL value = con[j]; + if (value < minimal) { + r_s += 1; + if (not _find(h, j, r)) + r_filter_s += 1; + } + while (lef < rig && tail_type[lef] < j) + lef++; + if (lef < rig && j == tail_type[lef]) { + if (value < minimal) { + r_s_constrain += 1; + if (not _find(h, j, r)) { + r_filter_s_constrain += 1; + } } + } } - - if (r_filter_s < 10) - r_filter_tot += 1; - if (r_s < 10) - r_tot += 1; - if (r_filter_s < 3) - r3_filter_tot += 1; - if (r_s < 3) - r3_tot += 1; - if (r_filter_s < 1) - r1_filter_tot += 1; - if (r_s < 1) - r1_tot += 1; - - if (r_filter_s_constrain < 10) - r_filter_tot_constrain += 1; - if (r_s_constrain < 10) - r_tot_constrain += 1; - if (r_filter_s_constrain < 3) - r3_filter_tot_constrain += 1; - if (r_s_constrain < 3) - r3_tot_constrain += 1; - if (r_filter_s_constrain < 1) - r1_filter_tot_constrain += 1; - if (r_s_constrain < 1) - r1_tot_constrain += 1; - - r_filter_rank += (1 + r_filter_s); - r_rank += (1 + r_s); - r_filter_reci_rank += 1.0 / (1 + r_filter_s); - r_reci_rank += 1.0 / (1 + r_s); - - r_filter_rank_constrain += (1 + r_filter_s_constrain); - r_rank_constrain += (1 + r_s_constrain); - r_filter_reci_rank_constrain += 1.0 / (1 + r_filter_s_constrain); - r_reci_rank_constrain += 1.0 / (1 + r_s_constrain); - - lastTail++; + } + + if (r_filter_s < 10) + r_filter_tot += 1; + if (r_s < 10) + r_tot += 1; + if (r_filter_s < 3) + r3_filter_tot += 1; + if (r_s < 3) + r3_tot += 1; + if (r_filter_s < 1) + r1_filter_tot += 1; + if (r_s < 1) + r1_tot += 1; + + if (r_filter_s_constrain < 10) + r_filter_tot_constrain += 1; + if (r_s_constrain < 10) + r_tot_constrain += 1; + if (r_filter_s_constrain < 3) + r3_filter_tot_constrain += 1; + if (r_s_constrain < 3) + r3_tot_constrain += 1; + if (r_filter_s_constrain < 1) + r1_filter_tot_constrain += 1; + if (r_s_constrain < 1) + r1_tot_constrain += 1; + + r_filter_rank += (1 + r_filter_s); + r_rank += (1 + r_s); + r_filter_reci_rank += 1.0 / (1 + r_filter_s); + r_reci_rank += 1.0 / (1 + r_s); + + r_filter_rank_constrain += (1 + r_filter_s_constrain); + r_rank_constrain += (1 + r_s_constrain); + r_filter_reci_rank_constrain += 1.0 / (1 + r_filter_s_constrain); + r_reci_rank_constrain += 1.0 / (1 + r_s_constrain); + + lastTail++; } extern "C" void test_link_prediction() { - l_rank /= testTotal; - r_rank /= testTotal; - l_reci_rank /= testTotal; - r_reci_rank /= testTotal; - - l_tot /= testTotal; - l3_tot /= testTotal; - l1_tot /= testTotal; - - r_tot /= testTotal; - r3_tot /= testTotal; - r1_tot /= testTotal; - - // with filter - l_filter_rank /= testTotal; - r_filter_rank /= testTotal; - l_filter_reci_rank /= testTotal; - r_filter_reci_rank /= testTotal; - - l_filter_tot /= testTotal; - l3_filter_tot /= testTotal; - l1_filter_tot /= testTotal; - - r_filter_tot /= testTotal; - r3_filter_tot /= testTotal; - r1_filter_tot /= testTotal; - - printf("no type constraint results:\n"); - - printf("metric:\t\t\t MRR \t\t MR \t\t hit@10 \t hit@3 \t hit@1 \n"); - printf("l(raw):\t\t\t %f \t %f \t %f \t %f \t %f \n", l_reci_rank, l_rank, - l_tot, l3_tot, l1_tot); - printf("r(raw):\t\t\t %f \t %f \t %f \t %f \t %f \n", r_reci_rank, r_rank, - r_tot, r3_tot, r1_tot); - printf("averaged(raw):\t\t %f \t %f \t %f \t %f \t %f \n", - (l_reci_rank + r_reci_rank) / 2, (l_rank + r_rank) / 2, - (l_tot + r_tot) / 2, (l3_tot + r3_tot) / 2, (l1_tot + r1_tot) / 2); - printf("\n"); - printf("l(filter):\t\t %f \t %f \t %f \t %f \t %f \n", l_filter_reci_rank, - l_filter_rank, l_filter_tot, l3_filter_tot, l1_filter_tot); - printf("r(filter):\t\t %f \t %f \t %f \t %f \t %f \n", r_filter_reci_rank, - r_filter_rank, r_filter_tot, r3_filter_tot, r1_filter_tot); - printf("averaged(filter):\t %f \t %f \t %f \t %f \t %f \n", - (l_filter_reci_rank + r_filter_reci_rank) / 2, - (l_filter_rank + r_filter_rank) / 2, - (l_filter_tot + r_filter_tot) / 2, - (l3_filter_tot + r3_filter_tot) / 2, - (l1_filter_tot + r1_filter_tot) / 2); - - // type constrain - l_rank_constrain /= testTotal; - r_rank_constrain /= testTotal; - l_reci_rank_constrain /= testTotal; - r_reci_rank_constrain /= testTotal; - - l_tot_constrain /= testTotal; - l3_tot_constrain /= testTotal; - l1_tot_constrain /= testTotal; - - r_tot_constrain /= testTotal; - r3_tot_constrain /= testTotal; - r1_tot_constrain /= testTotal; - - // with filter - l_filter_rank_constrain /= testTotal; - r_filter_rank_constrain /= testTotal; - l_filter_reci_rank_constrain /= testTotal; - r_filter_reci_rank_constrain /= testTotal; - - l_filter_tot_constrain /= testTotal; - l3_filter_tot_constrain /= testTotal; - l1_filter_tot_constrain /= testTotal; - - r_filter_tot_constrain /= testTotal; - r3_filter_tot_constrain /= testTotal; - r1_filter_tot_constrain /= testTotal; - - printf("type constraint results:\n"); - - printf("metric:\t\t\t MRR \t\t MR \t\t hit@10 \t hit@3 \t hit@1 \n"); - printf("l(raw):\t\t\t %f \t %f \t %f \t %f \t %f \n", l_reci_rank_constrain, - l_rank_constrain, l_tot_constrain, l3_tot_constrain, - l1_tot_constrain); - printf("r(raw):\t\t\t %f \t %f \t %f \t %f \t %f \n", r_reci_rank_constrain, - r_rank_constrain, r_tot_constrain, r3_tot_constrain, - r1_tot_constrain); - printf("averaged(raw):\t\t %f \t %f \t %f \t %f \t %f \n", - (l_reci_rank_constrain + r_reci_rank_constrain) / 2, - (l_rank_constrain + r_rank_constrain) / 2, - (l_tot_constrain + r_tot_constrain) / 2, - (l3_tot_constrain + r3_tot_constrain) / 2, - (l1_tot_constrain + r1_tot_constrain) / 2); - printf("\n"); - printf("l(filter):\t\t %f \t %f \t %f \t %f \t %f \n", - l_filter_reci_rank_constrain, l_filter_rank_constrain, - l_filter_tot_constrain, l3_filter_tot_constrain, - l1_filter_tot_constrain); - printf("r(filter):\t\t %f \t %f \t %f \t %f \t %f \n", - r_filter_reci_rank_constrain, r_filter_rank_constrain, - r_filter_tot_constrain, r3_filter_tot_constrain, - r1_filter_tot_constrain); - printf("averaged(filter):\t %f \t %f \t %f \t %f \t %f \n", - (l_filter_reci_rank_constrain + r_filter_reci_rank_constrain) / 2, - (l_filter_rank_constrain + r_filter_rank_constrain) / 2, - (l_filter_tot_constrain + r_filter_tot_constrain) / 2, - (l3_filter_tot_constrain + r3_filter_tot_constrain) / 2, - (l1_filter_tot_constrain + r1_filter_tot_constrain) / 2); + l_rank /= testTotal; + r_rank /= testTotal; + l_reci_rank /= testTotal; + r_reci_rank /= testTotal; + + l_tot /= testTotal; + l3_tot /= testTotal; + l1_tot /= testTotal; + + r_tot /= testTotal; + r3_tot /= testTotal; + r1_tot /= testTotal; + + // with filter + l_filter_rank /= testTotal; + r_filter_rank /= testTotal; + l_filter_reci_rank /= testTotal; + r_filter_reci_rank /= testTotal; + + l_filter_tot /= testTotal; + l3_filter_tot /= testTotal; + l1_filter_tot /= testTotal; + + r_filter_tot /= testTotal; + r3_filter_tot /= testTotal; + r1_filter_tot /= testTotal; + + printf("no type constraint results:\n"); + + printf("metric:\t\t\t MRR \t\t MR \t\t hit@10 \t hit@3 \t hit@1 \n"); + printf("l(raw):\t\t\t %f \t %f \t %f \t %f \t %f \n", l_reci_rank, l_rank, + l_tot, l3_tot, l1_tot); + printf("r(raw):\t\t\t %f \t %f \t %f \t %f \t %f \n", r_reci_rank, r_rank, + r_tot, r3_tot, r1_tot); + printf("averaged(raw):\t\t %f \t %f \t %f \t %f \t %f \n", + (l_reci_rank + r_reci_rank) / 2, (l_rank + r_rank) / 2, + (l_tot + r_tot) / 2, (l3_tot + r3_tot) / 2, (l1_tot + r1_tot) / 2); + printf("\n"); + printf("l(filter):\t\t %f \t %f \t %f \t %f \t %f \n", l_filter_reci_rank, + l_filter_rank, l_filter_tot, l3_filter_tot, l1_filter_tot); + printf("r(filter):\t\t %f \t %f \t %f \t %f \t %f \n", r_filter_reci_rank, + r_filter_rank, r_filter_tot, r3_filter_tot, r1_filter_tot); + printf("averaged(filter):\t %f \t %f \t %f \t %f \t %f \n", + (l_filter_reci_rank + r_filter_reci_rank) / 2, + (l_filter_rank + r_filter_rank) / 2, (l_filter_tot + r_filter_tot) / 2, + (l3_filter_tot + r3_filter_tot) / 2, + (l1_filter_tot + r1_filter_tot) / 2); + + // type constrain + l_rank_constrain /= testTotal; + r_rank_constrain /= testTotal; + l_reci_rank_constrain /= testTotal; + r_reci_rank_constrain /= testTotal; + + l_tot_constrain /= testTotal; + l3_tot_constrain /= testTotal; + l1_tot_constrain /= testTotal; + + r_tot_constrain /= testTotal; + r3_tot_constrain /= testTotal; + r1_tot_constrain /= testTotal; + + // with filter + l_filter_rank_constrain /= testTotal; + r_filter_rank_constrain /= testTotal; + l_filter_reci_rank_constrain /= testTotal; + r_filter_reci_rank_constrain /= testTotal; + + l_filter_tot_constrain /= testTotal; + l3_filter_tot_constrain /= testTotal; + l1_filter_tot_constrain /= testTotal; + + r_filter_tot_constrain /= testTotal; + r3_filter_tot_constrain /= testTotal; + r1_filter_tot_constrain /= testTotal; + + printf("type constraint results:\n"); + + printf("metric:\t\t\t MRR \t\t MR \t\t hit@10 \t hit@3 \t hit@1 \n"); + printf("l(raw):\t\t\t %f \t %f \t %f \t %f \t %f \n", l_reci_rank_constrain, + l_rank_constrain, l_tot_constrain, l3_tot_constrain, l1_tot_constrain); + printf("r(raw):\t\t\t %f \t %f \t %f \t %f \t %f \n", r_reci_rank_constrain, + r_rank_constrain, r_tot_constrain, r3_tot_constrain, r1_tot_constrain); + printf("averaged(raw):\t\t %f \t %f \t %f \t %f \t %f \n", + (l_reci_rank_constrain + r_reci_rank_constrain) / 2, + (l_rank_constrain + r_rank_constrain) / 2, + (l_tot_constrain + r_tot_constrain) / 2, + (l3_tot_constrain + r3_tot_constrain) / 2, + (l1_tot_constrain + r1_tot_constrain) / 2); + printf("\n"); + printf("l(filter):\t\t %f \t %f \t %f \t %f \t %f \n", + l_filter_reci_rank_constrain, l_filter_rank_constrain, + l_filter_tot_constrain, l3_filter_tot_constrain, + l1_filter_tot_constrain); + printf("r(filter):\t\t %f \t %f \t %f \t %f \t %f \n", + r_filter_reci_rank_constrain, r_filter_rank_constrain, + r_filter_tot_constrain, r3_filter_tot_constrain, + r1_filter_tot_constrain); + printf("averaged(filter):\t %f \t %f \t %f \t %f \t %f \n", + (l_filter_reci_rank_constrain + r_filter_reci_rank_constrain) / 2, + (l_filter_rank_constrain + r_filter_rank_constrain) / 2, + (l_filter_tot_constrain + r_filter_tot_constrain) / 2, + (l3_filter_tot_constrain + r3_filter_tot_constrain) / 2, + (l1_filter_tot_constrain + r1_filter_tot_constrain) / 2); } /*===================================================================================== @@ -320,121 +316,121 @@ triple classification ======================================================================================*/ Triple *negTestList; extern "C" void getNegTest() { - negTestList = (Triple *)calloc(testTotal, sizeof(Triple)); - for (INT i = 0; i < testTotal; i++) { - negTestList[i] = testList[i]; - negTestList[i].t = corrupt(testList[i].h, testList[i].r); - } + negTestList = (Triple *)calloc(testTotal, sizeof(Triple)); + for (INT i = 0; i < testTotal; i++) { + negTestList[i] = testList[i]; + negTestList[i].t = corrupt(testList[i].h, testList[i].r); + } } Triple *negValidList; extern "C" void getNegValid() { - negValidList = (Triple *)calloc(validTotal, sizeof(Triple)); - for (INT i = 0; i < validTotal; i++) { - negValidList[i] = validList[i]; - negValidList[i].t = corrupt(validList[i].h, validList[i].r); - } + negValidList = (Triple *)calloc(validTotal, sizeof(Triple)); + for (INT i = 0; i < validTotal; i++) { + negValidList[i] = validList[i]; + negValidList[i].t = corrupt(validList[i].h, validList[i].r); + } } extern "C" void getTestBatch(INT *ph, INT *pt, INT *pr, INT *nh, INT *nt, INT *nr) { - getNegTest(); - for (INT i = 0; i < testTotal; i++) { - ph[i] = testList[i].h; - pt[i] = testList[i].t; - pr[i] = testList[i].r; - nh[i] = negTestList[i].h; - nt[i] = negTestList[i].t; - nr[i] = negTestList[i].r; - } + getNegTest(); + for (INT i = 0; i < testTotal; i++) { + ph[i] = testList[i].h; + pt[i] = testList[i].t; + pr[i] = testList[i].r; + nh[i] = negTestList[i].h; + nt[i] = negTestList[i].t; + nr[i] = negTestList[i].r; + } } extern "C" void getValidBatch(INT *ph, INT *pt, INT *pr, INT *nh, INT *nt, INT *nr) { - getNegValid(); - for (INT i = 0; i < validTotal; i++) { - ph[i] = validList[i].h; - pt[i] = validList[i].t; - pr[i] = validList[i].r; - nh[i] = negValidList[i].h; - nt[i] = negValidList[i].t; - nr[i] = negValidList[i].r; - } + getNegValid(); + for (INT i = 0; i < validTotal; i++) { + ph[i] = validList[i].h; + pt[i] = validList[i].t; + pr[i] = validList[i].r; + nh[i] = negValidList[i].h; + nt[i] = negValidList[i].t; + nr[i] = negValidList[i].r; + } } REAL threshEntire; extern "C" void getBestThreshold(REAL *relThresh, REAL *score_pos, REAL *score_neg) { - REAL interval = 0.01; - REAL min_score, max_score, bestThresh, tmpThresh, bestAcc, tmpAcc; - INT n_interval, correct, total; - for (INT r = 0; r < relationTotal; r++) { - if (validLef[r] == -1) - continue; - total = (validRig[r] - validLef[r] + 1) * 2; - min_score = score_pos[validLef[r]]; - if (score_neg[validLef[r]] < min_score) - min_score = score_neg[validLef[r]]; - max_score = score_pos[validLef[r]]; - if (score_neg[validLef[r]] > max_score) - max_score = score_neg[validLef[r]]; - for (INT i = validLef[r] + 1; i <= validRig[r]; i++) { - if (score_pos[i] < min_score) - min_score = score_pos[i]; - if (score_pos[i] > max_score) - max_score = score_pos[i]; - if (score_neg[i] < min_score) - min_score = score_neg[i]; - if (score_neg[i] > max_score) - max_score = score_neg[i]; - } - n_interval = INT((max_score - min_score) / interval); - for (INT i = 0; i <= n_interval; i++) { - tmpThresh = min_score + i * interval; - correct = 0; - for (INT j = validLef[r]; j <= validRig[r]; j++) { - if (score_pos[j] <= tmpThresh) - correct++; - if (score_neg[j] > tmpThresh) - correct++; - } - tmpAcc = 1.0 * correct / total; - if (i == 0) { - bestThresh = tmpThresh; - bestAcc = tmpAcc; - } else if (tmpAcc > bestAcc) { - bestAcc = tmpAcc; - bestThresh = tmpThresh; - } - } - relThresh[r] = bestThresh; + REAL interval = 0.01; + REAL min_score, max_score, bestThresh, tmpThresh, bestAcc, tmpAcc; + INT n_interval, correct, total; + for (INT r = 0; r < relationTotal; r++) { + if (validLef[r] == -1) + continue; + total = (validRig[r] - validLef[r] + 1) * 2; + min_score = score_pos[validLef[r]]; + if (score_neg[validLef[r]] < min_score) + min_score = score_neg[validLef[r]]; + max_score = score_pos[validLef[r]]; + if (score_neg[validLef[r]] > max_score) + max_score = score_neg[validLef[r]]; + for (INT i = validLef[r] + 1; i <= validRig[r]; i++) { + if (score_pos[i] < min_score) + min_score = score_pos[i]; + if (score_pos[i] > max_score) + max_score = score_pos[i]; + if (score_neg[i] < min_score) + min_score = score_neg[i]; + if (score_neg[i] > max_score) + max_score = score_neg[i]; + } + n_interval = INT((max_score - min_score) / interval); + for (INT i = 0; i <= n_interval; i++) { + tmpThresh = min_score + i * interval; + correct = 0; + for (INT j = validLef[r]; j <= validRig[r]; j++) { + if (score_pos[j] <= tmpThresh) + correct++; + if (score_neg[j] > tmpThresh) + correct++; + } + tmpAcc = 1.0 * correct / total; + if (i == 0) { + bestThresh = tmpThresh; + bestAcc = tmpAcc; + } else if (tmpAcc > bestAcc) { + bestAcc = tmpAcc; + bestThresh = tmpThresh; + } } + relThresh[r] = bestThresh; + } } REAL *testAcc; REAL aveAcc; extern "C" void test_triple_classification(REAL *relThresh, REAL *score_pos, REAL *score_neg) { - testAcc = (REAL *)calloc(relationTotal, sizeof(REAL)); - INT aveCorrect = 0, aveTotal = 0; - REAL aveAcc; - for (INT r = 0; r < relationTotal; r++) { - if (validLef[r] == -1 || testLef[r] == -1) - continue; - INT correct = 0, total = 0; - for (INT i = testLef[r]; i <= testRig[r]; i++) { - if (score_pos[i] <= relThresh[r]) - correct++; - if (score_neg[i] > relThresh[r]) - correct++; - total += 2; - } - testAcc[r] = 1.0 * correct / total; - aveCorrect += correct; - aveTotal += total; + testAcc = (REAL *)calloc(relationTotal, sizeof(REAL)); + INT aveCorrect = 0, aveTotal = 0; + REAL aveAcc; + for (INT r = 0; r < relationTotal; r++) { + if (validLef[r] == -1 || testLef[r] == -1) + continue; + INT correct = 0, total = 0; + for (INT i = testLef[r]; i <= testRig[r]; i++) { + if (score_pos[i] <= relThresh[r]) + correct++; + if (score_neg[i] > relThresh[r]) + correct++; + total += 2; } - aveAcc = 1.0 * aveCorrect / aveTotal; - printf("triple classification accuracy is %lf\n", aveAcc); + testAcc[r] = 1.0 * correct / total; + aveCorrect += correct; + aveTotal += total; + } + aveAcc = 1.0 * aveCorrect / aveTotal; + printf("triple classification accuracy is %lf\n", aveAcc); } #endif diff --git a/seed_embeddings/OpenKE/base/Triple.h b/seed_embeddings/OpenKE/base/Triple.h index 7eed2c97..1e7b1385 100644 --- a/seed_embeddings/OpenKE/base/Triple.h +++ b/seed_embeddings/OpenKE/base/Triple.h @@ -4,37 +4,37 @@ struct Triple { - INT h, r, t; - - static INT minimal(INT a, INT b) { - if (a > b) - return b; - return a; - } - - static bool cmp_list(const Triple &a, const Triple &b) { - return (minimal(a.h, a.t) > minimal(b.h, b.t)); - } - - static bool cmp_head(const Triple &a, const Triple &b) { - return (a.h < b.h) || (a.h == b.h && a.r < b.r) || - (a.h == b.h && a.r == b.r && a.t < b.t); - } - - static bool cmp_tail(const Triple &a, const Triple &b) { - return (a.t < b.t) || (a.t == b.t && a.r < b.r) || - (a.t == b.t && a.r == b.r && a.h < b.h); - } - - static bool cmp_rel(const Triple &a, const Triple &b) { - return (a.h < b.h) || (a.h == b.h && a.t < b.t) || - (a.h == b.h && a.t == b.t && a.r < b.r); - } - - static bool cmp_rel2(const Triple &a, const Triple &b) { - return (a.r < b.r) || (a.r == b.r && a.h < b.h) || - (a.r == b.r && a.h == b.h && a.t < b.t); - } + INT h, r, t; + + static INT minimal(INT a, INT b) { + if (a > b) + return b; + return a; + } + + static bool cmp_list(const Triple &a, const Triple &b) { + return (minimal(a.h, a.t) > minimal(b.h, b.t)); + } + + static bool cmp_head(const Triple &a, const Triple &b) { + return (a.h < b.h) || (a.h == b.h && a.r < b.r) || + (a.h == b.h && a.r == b.r && a.t < b.t); + } + + static bool cmp_tail(const Triple &a, const Triple &b) { + return (a.t < b.t) || (a.t == b.t && a.r < b.r) || + (a.t == b.t && a.r == b.r && a.h < b.h); + } + + static bool cmp_rel(const Triple &a, const Triple &b) { + return (a.h < b.h) || (a.h == b.h && a.t < b.t) || + (a.h == b.h && a.t == b.t && a.r < b.r); + } + + static bool cmp_rel2(const Triple &a, const Triple &b) { + return (a.r < b.r) || (a.r == b.r && a.h < b.h) || + (a.r == b.r && a.h == b.h && a.t < b.t); + } }; #endif diff --git a/seed_embeddings/OpenKE/base/Valid.h b/seed_embeddings/OpenKE/base/Valid.h index 8616e882..b6daccd3 100644 --- a/seed_embeddings/OpenKE/base/Valid.h +++ b/seed_embeddings/OpenKE/base/Valid.h @@ -11,68 +11,68 @@ REAL l_valid_filter_tot = 0; REAL r_valid_filter_tot = 0; extern "C" void validInit() { - lastValidHead = 0; - lastValidTail = 0; - l_valid_filter_tot = 0; - r_valid_filter_tot = 0; + lastValidHead = 0; + lastValidTail = 0; + l_valid_filter_tot = 0; + r_valid_filter_tot = 0; } extern "C" void getValidHeadBatch(INT *ph, INT *pt, INT *pr) { - for (INT i = 0; i < entityTotal; i++) { - ph[i] = i; - pt[i] = validList[lastValidHead].t; - pr[i] = validList[lastValidHead].r; - } + for (INT i = 0; i < entityTotal; i++) { + ph[i] = i; + pt[i] = validList[lastValidHead].t; + pr[i] = validList[lastValidHead].r; + } } extern "C" void getValidTailBatch(INT *ph, INT *pt, INT *pr) { - for (INT i = 0; i < entityTotal; i++) { - ph[i] = validList[lastValidTail].h; - pt[i] = i; - pr[i] = validList[lastValidTail].r; - } + for (INT i = 0; i < entityTotal; i++) { + ph[i] = validList[lastValidTail].h; + pt[i] = i; + pr[i] = validList[lastValidTail].r; + } } extern "C" void validHead(REAL *con) { - INT h = validList[lastValidHead].h; - INT t = validList[lastValidHead].t; - INT r = validList[lastValidHead].r; - REAL minimal = con[h]; - INT l_filter_s = 0; - for (INT j = 0; j < entityTotal; j++) { - if (j != h) { - REAL value = con[j]; - if (value < minimal && !_find(j, t, r)) - l_filter_s += 1; - } + INT h = validList[lastValidHead].h; + INT t = validList[lastValidHead].t; + INT r = validList[lastValidHead].r; + REAL minimal = con[h]; + INT l_filter_s = 0; + for (INT j = 0; j < entityTotal; j++) { + if (j != h) { + REAL value = con[j]; + if (value < minimal && !_find(j, t, r)) + l_filter_s += 1; } - if (l_filter_s < 10) - l_valid_filter_tot += 1; - lastValidHead++; + } + if (l_filter_s < 10) + l_valid_filter_tot += 1; + lastValidHead++; } extern "C" void validTail(REAL *con) { - INT h = validList[lastValidTail].h; - INT t = validList[lastValidTail].t; - INT r = validList[lastValidTail].r; - REAL minimal = con[t]; - INT r_filter_s = 0; - for (INT j = 0; j < entityTotal; j++) { - if (j != t) { - REAL value = con[j]; - if (value < minimal && !_find(h, j, r)) - r_filter_s += 1; - } + INT h = validList[lastValidTail].h; + INT t = validList[lastValidTail].t; + INT r = validList[lastValidTail].r; + REAL minimal = con[t]; + INT r_filter_s = 0; + for (INT j = 0; j < entityTotal; j++) { + if (j != t) { + REAL value = con[j]; + if (value < minimal && !_find(h, j, r)) + r_filter_s += 1; } - if (r_filter_s < 10) - r_valid_filter_tot += 1; - lastValidTail++; + } + if (r_filter_s < 10) + r_valid_filter_tot += 1; + lastValidTail++; } extern "C" REAL getValidHit10() { - return (l_valid_filter_tot / validTotal + r_valid_filter_tot / validTotal) / - 2; - ; + return (l_valid_filter_tot / validTotal + r_valid_filter_tot / validTotal) / + 2; + ; } #endif diff --git a/seed_embeddings/OpenKE/generate_embedding.py b/seed_embeddings/OpenKE/generate_embedding.py index 8e82e84c..311b7407 100644 --- a/seed_embeddings/OpenKE/generate_embedding.py +++ b/seed_embeddings/OpenKE/generate_embedding.py @@ -37,7 +37,7 @@ def train(arg_conf): arg_conf.dim, arg_conf.nbatches, arg_conf.margin, - ) + ), ) con.set_out_files(outfile) con.init() diff --git a/seed_embeddings/OpenKE/generate_embedding_ray.py b/seed_embeddings/OpenKE/generate_embedding_ray.py index fdae917a..f083b425 100644 --- a/seed_embeddings/OpenKE/generate_embedding_ray.py +++ b/seed_embeddings/OpenKE/generate_embedding_ray.py @@ -36,23 +36,24 @@ def test_files(index_dir): if not os.path.exists(train): raise Exception("train2id.txt not found") + # TODO :: alpha, lmda, bern, opt_method def train(arg_conf): con = config.Config() - con.set_in_path(arg_conf['index_dir']) + con.set_in_path(arg_conf["index_dir"]) con.set_work_threads(4) - con.set_train_times(arg_conf['epoch']) - con.set_nbatches(nbatches=arg_conf['nbatches']) + con.set_train_times(arg_conf["epoch"]) + con.set_nbatches(nbatches=arg_conf["nbatches"]) con.set_alpha(0.001) - con.set_margin(arg_conf['margin']) - con.set_bern(0) # either 0 or 1 - con.set_dimension(arg_conf['dim']) + con.set_margin(arg_conf["margin"]) + con.set_bern(0) # either 0 or 1 + con.set_dimension(arg_conf["dim"]) con.set_ent_neg_rate(1) con.set_rel_neg_rate(0) con.set_opt_method("SGD") try: - test_files(arg_conf['index_dir']) + test_files(arg_conf["index_dir"]) print("Files are OK") except: print(arg_conf) @@ -60,13 +61,13 @@ def train(arg_conf): raise Exception("Error in files") outfile = os.path.join( - arg_conf['index_dir'], + arg_conf["index_dir"], "seedEmbedding_{}E_{}D_{}batches{}margin.json".format( - arg_conf['epoch'], - arg_conf['dim'], - arg_conf['nbatches'], - arg_conf['margin'], - ) + arg_conf["epoch"], + arg_conf["dim"], + arg_conf["nbatches"], + arg_conf["margin"], + ), ) con.set_out_files(outfile) con.init() @@ -76,23 +77,16 @@ def train(arg_conf): con.run() seedfile = os.path.join( - arg_conf['index_dir'], + arg_conf["index_dir"], "embeddings/seedEmbedding_{}E_{}D_{}batches{}margin.txt".format( - arg_conf['epoch'], - arg_conf['dim'], - arg_conf['nbatches'], - arg_conf['margin'] + arg_conf["epoch"], arg_conf["dim"], arg_conf["nbatches"], arg_conf["margin"] ), ) - findRep( - outfile, - seedfile, - arg_conf['index_dir'] - ) + findRep(outfile, seedfile, arg_conf["index_dir"]) del con - + return { "seedFile": seedfile, "AnalogiesScore": analogy.getAnalogyScore(seedfile), @@ -114,7 +108,9 @@ def findRep(src, dest, index_dir): for i in range(1, int(entities[0])): toTxt += entities[i].split("\t")[0] + ":" + str(rep[i - 1]) + ",\n" toTxt += ( - entities[int(entities[0])].split("\t")[0] + ":" + str(rep[int(entities[0]) - 1]) + entities[int(entities[0])].split("\t")[0] + + ":" + + str(rep[int(entities[0]) - 1]) ) fDest.write(toTxt) @@ -130,7 +126,7 @@ def findRep(src, dest, index_dir): metavar="DIRECTORY", help="Location of the directory entity2id.txt, train2id.txt and relation2id.txt", required=False, - default="/home/intern23002/iitH/ir2vec/IR2Vec/seed_embeddings/preprocessed/" + default="/home/intern23002/iitH/ir2vec/IR2Vec/seed_embeddings/preprocessed/", ) parser.add_argument( "--epoch", dest="epoch", help="Epochs", required=False, type=int, default=1500 @@ -167,16 +163,12 @@ def findRep(src, dest, index_dir): "epoch": arg_conf.epoch, "dim": arg_conf.dim, "index_dir": arg_conf.index_dir, - "nbatches": tune.grid_search( - [2**x for x in range(5, 9)] - ), - "margin": tune.grid_search( - [x for x in np.arange(3.0, 4.0, 0.5)] - ), + "nbatches": tune.grid_search([2**x for x in range(5, 9)]), + "margin": tune.grid_search([x for x in np.arange(3.0, 4.0, 0.5)]), } try: - test_files(search_space['index_dir']) + test_files(search_space["index_dir"]) print("Files are OK") except: print("Error in files") @@ -191,11 +183,13 @@ def findRep(src, dest, index_dir): results = tuner.fit() # Write the best result to a file, best_result.txt - with open(os.path.join(search_space['index_dir'], "best_result.txt"), "a") as f: - f.write('\n' + str(results.get_best_result(metric='AnalogiesScore', mode='max'))) + with open(os.path.join(search_space["index_dir"], "best_result.txt"), "a") as f: + f.write( + "\n" + str(results.get_best_result(metric="AnalogiesScore", mode="max")) + ) + + print("Best config: ", results.get_best_result(metric="AnalogiesScore", mode="max")) - print("Best config: ", results.get_best_result(metric='AnalogiesScore', mode='max')) - # for result in results: # print(result) del results diff --git a/seed_embeddings/triplets.sh b/seed_embeddings/triplets.sh index 718aafa2..5b51e1b1 100644 --- a/seed_embeddings/triplets.sh +++ b/seed_embeddings/triplets.sh @@ -85,4 +85,4 @@ done <$3 wait echo $4 -echo "All ll files processed" \ No newline at end of file +echo "All ll files processed" diff --git a/src/CollectIR.cpp b/src/CollectIR.cpp index a4616566..f51edcf8 100644 --- a/src/CollectIR.cpp +++ b/src/CollectIR.cpp @@ -17,85 +17,85 @@ using namespace llvm; void CollectIR::generateTriplets(std::ostream &out) { - for (Function &F : M) - for (BasicBlock &B : F) - traverseBasicBlock(B); - out << res; + for (Function &F : M) + for (BasicBlock &B : F) + traverseBasicBlock(B); + out << res; } void CollectIR::traverseBasicBlock(BasicBlock &B) { - for (Instruction &I : B) { - res += "\n" + std::string(I.getOpcodeName()) + " "; - auto type = I.getType(); - IR2VEC_DEBUG(I.print(outs()); outs() << "\n";); - IR2VEC_DEBUG(I.getType()->print(outs()); outs() << " Type\n";); + for (Instruction &I : B) { + res += "\n" + std::string(I.getOpcodeName()) + " "; + auto type = I.getType(); + IR2VEC_DEBUG(I.print(outs()); outs() << "\n";); + IR2VEC_DEBUG(I.getType()->print(outs()); outs() << " Type\n";); - std::string stype; + std::string stype; - if (type->isVoidTy()) { - stype = " voidTy "; - res += stype; - } else if (type->isFloatingPointTy()) { - stype = " floatTy "; - res += stype; - } else if (type->isIntegerTy()) { - stype = " integerTy "; - res += stype; - } else if (type->isFunctionTy()) { - stype = " functionTy "; - res += stype; - } else if (type->isStructTy()) { - stype = " structTy "; - res += stype; - } else if (type->isArrayTy()) { - stype = " arrayTy "; - res += stype; - } else if (type->isPointerTy()) { - stype = " pointerTy "; - res += stype; - } else if (type->isVectorTy()) { - stype = " vectorTy "; - res += stype; - } else if (type->isEmptyTy()) { - stype = " emptyTy "; - res += stype; - } else if (type->isLabelTy()) { - stype = " labelTy "; - res += stype; - } else if (type->isTokenTy()) { - stype = " tokenTy "; - res += stype; - } else if (type->isMetadataTy()) { - stype = " metadataTy "; - res += stype; - } else { - stype = " unknownTy "; - res += stype; - } + if (type->isVoidTy()) { + stype = " voidTy "; + res += stype; + } else if (type->isFloatingPointTy()) { + stype = " floatTy "; + res += stype; + } else if (type->isIntegerTy()) { + stype = " integerTy "; + res += stype; + } else if (type->isFunctionTy()) { + stype = " functionTy "; + res += stype; + } else if (type->isStructTy()) { + stype = " structTy "; + res += stype; + } else if (type->isArrayTy()) { + stype = " arrayTy "; + res += stype; + } else if (type->isPointerTy()) { + stype = " pointerTy "; + res += stype; + } else if (type->isVectorTy()) { + stype = " vectorTy "; + res += stype; + } else if (type->isEmptyTy()) { + stype = " emptyTy "; + res += stype; + } else if (type->isLabelTy()) { + stype = " labelTy "; + res += stype; + } else if (type->isTokenTy()) { + stype = " tokenTy "; + res += stype; + } else if (type->isMetadataTy()) { + stype = " metadataTy "; + res += stype; + } else { + stype = " unknownTy "; + res += stype; + } - IR2VEC_DEBUG(errs() << "Type taken : " << stype << "\n";); + IR2VEC_DEBUG(errs() << "Type taken : " << stype << "\n";); - for (unsigned i = 0; i < I.getNumOperands(); i++) { - IR2VEC_DEBUG(I.print(outs()); outs() << "\n";); - IR2VEC_DEBUG(outs() << i << "\n"); - IR2VEC_DEBUG(I.getOperand(i)->print(outs()); outs() << "\n";); + for (unsigned i = 0; i < I.getNumOperands(); i++) { + IR2VEC_DEBUG(I.print(outs()); outs() << "\n";); + IR2VEC_DEBUG(outs() << i << "\n"); + IR2VEC_DEBUG(I.getOperand(i)->print(outs()); outs() << "\n";); - if (isa(I.getOperand(i))) { - res += " function "; - IR2VEC_DEBUG(outs() << "Function\n"); - } else if (isa(I.getOperand(i)->getType())) { - res += " pointer "; - IR2VEC_DEBUG(outs() << "pointer\n"); - } else if (isa(I.getOperand(i))) { - res += " constant "; - IR2VEC_DEBUG(outs() << "constant\n"); - } else if (isa(I.getOperand(i))) { - res += " label "; - IR2VEC_DEBUG(outs() << "label\n"); - } else { - res += " variable "; - IR2VEC_DEBUG(outs() << "variable2\n"); - } - } + if (isa(I.getOperand(i))) { + res += " function "; + IR2VEC_DEBUG(outs() << "Function\n"); + } else if (isa(I.getOperand(i)->getType())) { + res += " pointer "; + IR2VEC_DEBUG(outs() << "pointer\n"); + } else if (isa(I.getOperand(i))) { + res += " constant "; + IR2VEC_DEBUG(outs() << "constant\n"); + } else if (isa(I.getOperand(i))) { + res += " label "; + IR2VEC_DEBUG(outs() << "label\n"); + } else { + res += " variable "; + IR2VEC_DEBUG(outs() << "variable2\n"); + } } + } } diff --git a/src/FlowAware.cpp b/src/FlowAware.cpp index 7c4c390d..48cddcfe 100644 --- a/src/FlowAware.cpp +++ b/src/FlowAware.cpp @@ -33,160 +33,155 @@ void IR2Vec_FA::getTransitiveUse( const Instruction *root, const Instruction *def, SmallVector &visitedList, SmallVector toAppend) { - unsigned operandNum = 0; - visitedList.push_back(def); - - for (auto U : def->users()) { - if (auto use = dyn_cast(U)) { - if (std::find(visitedList.begin(), visitedList.end(), use) == - visitedList.end()) { - IR2VEC_DEBUG(outs() << "\nDef " << /* def << */ " "; - def->print(outs(), true); outs() << "\n";); - IR2VEC_DEBUG(outs() << "Use " << /* use << */ " "; - use->print(outs(), true); outs() << "\n";); - if (isMemOp(use->getOpcodeName(), operandNum, memWriteOps) && - use->getOperand(operandNum) == def) { - writeDefsMap[root].push_back(use); - } else if (isMemOp(use->getOpcodeName(), operandNum, - memAccessOps) && - use->getOperand(operandNum) == def) { - getTransitiveUse(root, use, visitedList, toAppend); - } - } + unsigned operandNum = 0; + visitedList.push_back(def); + + for (auto U : def->users()) { + if (auto use = dyn_cast(U)) { + if (std::find(visitedList.begin(), visitedList.end(), use) == + visitedList.end()) { + IR2VEC_DEBUG(outs() << "\nDef " << /* def << */ " "; + def->print(outs(), true); outs() << "\n";); + IR2VEC_DEBUG(outs() << "Use " << /* use << */ " "; + use->print(outs(), true); outs() << "\n";); + if (isMemOp(use->getOpcodeName(), operandNum, memWriteOps) && + use->getOperand(operandNum) == def) { + writeDefsMap[root].push_back(use); + } else if (isMemOp(use->getOpcodeName(), operandNum, memAccessOps) && + use->getOperand(operandNum) == def) { + getTransitiveUse(root, use, visitedList, toAppend); } + } } - return; + } + return; } void IR2Vec_FA::collectWriteDefsMap(Module &M) { - SmallVector visitedList; - for (auto &F : M) { - if (!F.isDeclaration()) { - EliminateUnreachableBlocks(F); - for (auto &BB : F) { - for (auto &I : BB) { - unsigned operandNum = 0; - if ((isMemOp(I.getOpcodeName(), operandNum, memAccessOps) || - isMemOp(I.getOpcodeName(), operandNum, memWriteOps) || - strcmp(I.getOpcodeName(), "alloca") == 0) && - std::find(visitedList.begin(), visitedList.end(), &I) == - visitedList.end()) { - if (I.getNumOperands() > 0) { - IR2VEC_DEBUG(I.print(outs()); outs() << "\n"); - IR2VEC_DEBUG(outs() << "operandnum = " << operandNum - << "\n"); - if (auto parent = dyn_cast( - I.getOperand(operandNum))) { - if (std::find(visitedList.begin(), - visitedList.end(), - parent) == visitedList.end()) { - visitedList.push_back(parent); - getTransitiveUse(parent, parent, - visitedList); - } - } - } - } + SmallVector visitedList; + for (auto &F : M) { + if (!F.isDeclaration()) { + EliminateUnreachableBlocks(F); + for (auto &BB : F) { + for (auto &I : BB) { + unsigned operandNum = 0; + if ((isMemOp(I.getOpcodeName(), operandNum, memAccessOps) || + isMemOp(I.getOpcodeName(), operandNum, memWriteOps) || + strcmp(I.getOpcodeName(), "alloca") == 0) && + std::find(visitedList.begin(), visitedList.end(), &I) == + visitedList.end()) { + if (I.getNumOperands() > 0) { + IR2VEC_DEBUG(I.print(outs()); outs() << "\n"); + IR2VEC_DEBUG(outs() << "operandnum = " << operandNum << "\n"); + if (auto parent = + dyn_cast(I.getOperand(operandNum))) { + if (std::find(visitedList.begin(), visitedList.end(), parent) == + visitedList.end()) { + visitedList.push_back(parent); + getTransitiveUse(parent, parent, visitedList); } + } } + } } + } } + } } Vector IR2Vec_FA::getValue(std::string key) { - Vector vec; - if (opcMap.find(key) == opcMap.end()) { - IR2VEC_DEBUG(errs() << "cannot find key in map : " << key << "\n"); - dataMissCounter++; - } else - vec = opcMap[key]; - return vec; + Vector vec; + if (opcMap.find(key) == opcMap.end()) { + IR2VEC_DEBUG(errs() << "cannot find key in map : " << key << "\n"); + dataMissCounter++; + } else + vec = opcMap[key]; + return vec; } // Function to update funcVecMap of function with vectors of it's callee list void IR2Vec_FA::updateFuncVecMapWithCallee(const llvm::Function *function) { - if (funcCallMap.find(function) != funcCallMap.end()) { + if (funcCallMap.find(function) != funcCallMap.end()) { - auto calleelist = funcCallMap[function]; - Vector calleeVector(DIM, 0); - for (auto funcs : calleelist) { + auto calleelist = funcCallMap[function]; + Vector calleeVector(DIM, 0); + for (auto funcs : calleelist) { - auto tmp = funcVecMap[funcs]; - std::transform(tmp.begin(), tmp.end(), calleeVector.begin(), - calleeVector.begin(), std::plus()); - } - - scaleVector(calleeVector, WA); - auto tmpParent = funcVecMap[function]; - std::transform(calleeVector.begin(), calleeVector.end(), - tmpParent.begin(), tmpParent.begin(), - std::plus()); - funcVecMap[function] = tmpParent; + auto tmp = funcVecMap[funcs]; + std::transform(tmp.begin(), tmp.end(), calleeVector.begin(), + calleeVector.begin(), std::plus()); } + + scaleVector(calleeVector, WA); + auto tmpParent = funcVecMap[function]; + std::transform(calleeVector.begin(), calleeVector.end(), tmpParent.begin(), + tmpParent.begin(), std::plus()); + funcVecMap[function] = tmpParent; + } } void IR2Vec_FA::generateFlowAwareEncodings(std::ostream *o, std::ostream *missCount, std::ostream *cyclicCount) { - int noOfFunc = 0; + int noOfFunc = 0; - for (auto &f : M) { - if (!f.isDeclaration()) { - SmallVector funcStack; - auto tmp = func2Vec(f, funcStack); - funcVecMap[&f] = tmp; - } + for (auto &f : M) { + if (!f.isDeclaration()) { + SmallVector funcStack; + auto tmp = func2Vec(f, funcStack); + funcVecMap[&f] = tmp; } + } - for (auto funcit : funcVecMap) { - updateFuncVecMapWithCallee(funcit.first); - } + for (auto funcit : funcVecMap) { + updateFuncVecMapWithCallee(funcit.first); + } - for (auto &f : M) { - if (!f.isDeclaration()) { - Vector tmp; - SmallVector funcStack; - tmp = funcVecMap[&f]; + for (auto &f : M) { + if (!f.isDeclaration()) { + Vector tmp; + SmallVector funcStack; + tmp = funcVecMap[&f]; - if (level == 'f') { - res += updatedRes(tmp, &f, &M); - res += "\n"; - noOfFunc++; - } + if (level == 'f') { + res += updatedRes(tmp, &f, &M); + res += "\n"; + noOfFunc++; + } - // else if (level == 'p') { - std::transform(pgmVector.begin(), pgmVector.end(), tmp.begin(), - pgmVector.begin(), std::plus()); - // } - } + // else if (level == 'p') { + std::transform(pgmVector.begin(), pgmVector.end(), tmp.begin(), + pgmVector.begin(), std::plus()); + // } } + } - if (level == 'p') { - if (cls != -1) - res += std::to_string(cls) + "\t"; + if (level == 'p') { + if (cls != -1) + res += std::to_string(cls) + "\t"; - for (auto i : pgmVector) { - if ((i <= 0.0001 && i > 0) || (i < 0 && i >= -0.0001)) { - i = 0; - } - res += std::to_string(i) + "\t"; - } - res += "\n"; + for (auto i : pgmVector) { + if ((i <= 0.0001 && i > 0) || (i < 0 && i >= -0.0001)) { + i = 0; + } + res += std::to_string(i) + "\t"; } + res += "\n"; + } - if (o) - *o << res; + if (o) + *o << res; - if (missCount) { - std::string missEntry = (M.getSourceFileName() + "\t" + - std::to_string(dataMissCounter) + "\n"); - *missCount << missEntry; - } + if (missCount) { + std::string missEntry = + (M.getSourceFileName() + "\t" + std::to_string(dataMissCounter) + "\n"); + *missCount << missEntry; + } - if (cyclicCount) - *cyclicCount << (M.getSourceFileName() + "\t" + - std::to_string(cyclicCounter) + "\n"); + if (cyclicCount) + *cyclicCount << (M.getSourceFileName() + "\t" + + std::to_string(cyclicCounter) + "\n"); } // This function will update funcVecMap by doing DFS starting from parent @@ -194,671 +189,659 @@ void IR2Vec_FA::generateFlowAwareEncodings(std::ostream *o, void IR2Vec_FA::updateFuncVecMap( llvm::Function *function, llvm::SmallSet &visitedFunctions) { - visitedFunctions.insert(function); - SmallVector funcStack; - funcStack.clear(); - auto tmpParent = func2Vec(*function, funcStack); - // funcVecMap is updated with vectors returned by func2Vec - funcVecMap[function] = tmpParent; - auto calledFunctions = funcCallMap[function]; - for (auto &calledFunction : calledFunctions) { - if (calledFunction && !calledFunction->isDeclaration() && - visitedFunctions.count(calledFunction) == 0) { - // doing casting since calledFunctions is of type of const - // llvm::Function* and we need llvm::Function* as argument - auto *callee = const_cast(calledFunction); - // This function is called recursively to update funcVecMap - updateFuncVecMap(callee, visitedFunctions); - } + visitedFunctions.insert(function); + SmallVector funcStack; + funcStack.clear(); + auto tmpParent = func2Vec(*function, funcStack); + // funcVecMap is updated with vectors returned by func2Vec + funcVecMap[function] = tmpParent; + auto calledFunctions = funcCallMap[function]; + for (auto &calledFunction : calledFunctions) { + if (calledFunction && !calledFunction->isDeclaration() && + visitedFunctions.count(calledFunction) == 0) { + // doing casting since calledFunctions is of type of const + // llvm::Function* and we need llvm::Function* as argument + auto *callee = const_cast(calledFunction); + // This function is called recursively to update funcVecMap + updateFuncVecMap(callee, visitedFunctions); } + } } void IR2Vec_FA::generateFlowAwareEncodingsForFunction( std::ostream *o, std::string name, std::ostream *missCount, std::ostream *cyclicCount) { - int noOfFunc = 0; - for (auto &f : M) { + int noOfFunc = 0; + for (auto &f : M) { - auto Result = getActualName(&f); - if (!f.isDeclaration() && Result == name) { - // If funcName is matched with one of the functions in module, we - // will update funcVecMap of it and it's child functions recursively - llvm::SmallSet visitedFunctions; - updateFuncVecMap(&f, visitedFunctions); - } + auto Result = getActualName(&f); + if (!f.isDeclaration() && Result == name) { + // If funcName is matched with one of the functions in module, we + // will update funcVecMap of it and it's child functions recursively + llvm::SmallSet visitedFunctions; + updateFuncVecMap(&f, visitedFunctions); } - // iterating over all functions in module instead of funcVecMap to preserve - // order - for (auto &f : M) { - if (funcVecMap.find(&f) != funcVecMap.end()) { - auto *function = const_cast(&f); - updateFuncVecMapWithCallee(function); - } + } + // iterating over all functions in module instead of funcVecMap to preserve + // order + for (auto &f : M) { + if (funcVecMap.find(&f) != funcVecMap.end()) { + auto *function = const_cast(&f); + updateFuncVecMapWithCallee(function); } + } - for (auto &f : M) { - auto Result = getActualName(&f); - if (!f.isDeclaration() && Result == name) { - Vector tmp; - SmallVector funcStack; - tmp = funcVecMap[&f]; - - if (level == 'f') { - res += updatedRes(tmp, &f, &M); - res += "\n"; - noOfFunc++; - } - } + for (auto &f : M) { + auto Result = getActualName(&f); + if (!f.isDeclaration() && Result == name) { + Vector tmp; + SmallVector funcStack; + tmp = funcVecMap[&f]; + + if (level == 'f') { + res += updatedRes(tmp, &f, &M); + res += "\n"; + noOfFunc++; + } } + } - if (o) - *o << res; + if (o) + *o << res; - if (missCount) { - std::string missEntry = (M.getSourceFileName() + "\t" + - std::to_string(dataMissCounter) + "\n"); - *missCount << missEntry; - } + if (missCount) { + std::string missEntry = + (M.getSourceFileName() + "\t" + std::to_string(dataMissCounter) + "\n"); + *missCount << missEntry; + } - if (cyclicCount) - *cyclicCount << (M.getSourceFileName() + "\t" + - std::to_string(cyclicCounter) + "\n"); + if (cyclicCount) + *cyclicCount << (M.getSourceFileName() + "\t" + + std::to_string(cyclicCounter) + "\n"); } void IR2Vec_FA::topoDFS(int vertex, std::vector &Visited, std::vector &visitStack) { - Visited[vertex] = true; + Visited[vertex] = true; - auto list = SCCAdjList[vertex]; + auto list = SCCAdjList[vertex]; - for (auto nodes : list) { - if (Visited[nodes] == false) - topoDFS(nodes, Visited, visitStack); - } + for (auto nodes : list) { + if (Visited[nodes] == false) + topoDFS(nodes, Visited, visitStack); + } - visitStack.push_back(vertex); + visitStack.push_back(vertex); } std::vector IR2Vec_FA::topoOrder(int size) { - std::vector Visited(size, false); - std::vector visitStack; + std::vector Visited(size, false); + std::vector visitStack; - for (auto &nodes : SCCAdjList) { - if (Visited[nodes.first] == false) { - topoDFS(nodes.first, Visited, visitStack); - } + for (auto &nodes : SCCAdjList) { + if (Visited[nodes.first] == false) { + topoDFS(nodes.first, Visited, visitStack); } + } - return visitStack; + return visitStack; } void IR2Vec_FA::TransitiveReads(SmallVector &Killlist, Instruction *Inst, BasicBlock *ParentBB) { - assert(Inst != nullptr); - unsigned operandNum; - bool isMemAccess = isMemOp(Inst->getOpcodeName(), operandNum, memAccessOps); - - if (!isMemAccess) - return; - auto parentI = dyn_cast(Inst->getOperand(operandNum)); - if (parentI == nullptr) - return; - if (ParentBB == parentI->getParent()) - Killlist.push_back(parentI); - TransitiveReads(Killlist, parentI, ParentBB); + assert(Inst != nullptr); + unsigned operandNum; + bool isMemAccess = isMemOp(Inst->getOpcodeName(), operandNum, memAccessOps); + + if (!isMemAccess) + return; + auto parentI = dyn_cast(Inst->getOperand(operandNum)); + if (parentI == nullptr) + return; + if (ParentBB == parentI->getParent()) + Killlist.push_back(parentI); + TransitiveReads(Killlist, parentI, ParentBB); } SmallVector IR2Vec_FA::createKilllist(Instruction *Arg, Instruction *writeInst) { - SmallVector KillList; - SmallVector tempList; - BasicBlock *ParentBB = writeInst->getParent(); + SmallVector KillList; + SmallVector tempList; + BasicBlock *ParentBB = writeInst->getParent(); - unsigned opnum; + unsigned opnum; - for (User *U : Arg->users()) { - if (Instruction *UseInst = dyn_cast(U)) { - if (isMemOp(UseInst->getOpcodeName(), opnum, memWriteOps)) { - Instruction *OpInst = - dyn_cast(UseInst->getOperand(opnum)); - if (OpInst && OpInst == Arg) - tempList.push_back(UseInst); - } - } + for (User *U : Arg->users()) { + if (Instruction *UseInst = dyn_cast(U)) { + if (isMemOp(UseInst->getOpcodeName(), opnum, memWriteOps)) { + Instruction *OpInst = dyn_cast(UseInst->getOperand(opnum)); + if (OpInst && OpInst == Arg) + tempList.push_back(UseInst); + } } + } - for (auto I = tempList.rbegin(); I != tempList.rend(); I++) { - if (*I == writeInst) - break; - if (ParentBB == (*I)->getParent()) - KillList.push_back(*I); - } + for (auto I = tempList.rbegin(); I != tempList.rend(); I++) { + if (*I == writeInst) + break; + if (ParentBB == (*I)->getParent()) + KillList.push_back(*I); + } - return KillList; + return KillList; } Vector IR2Vec_FA::func2Vec(Function &F, SmallVector &funcStack) { - auto It = funcVecMap.find(&F); - if (It != funcVecMap.end()) { - return It->second; - } + auto It = funcVecMap.find(&F); + if (It != funcVecMap.end()) { + return It->second; + } - funcStack.push_back(&F); - - instReachingDefsMap.clear(); - allSCCs.clear(); - reverseReachingDefsMap.clear(); - SCCAdjList.clear(); - - Vector funcVector(DIM, 0); - - ReversePostOrderTraversal RPOT(&F); - - for (auto *b : RPOT) { - unsigned opnum; - SmallVector lists; - for (auto &I : *b) { - lists.clear(); - if (isMemOp(I.getOpcodeName(), opnum, memWriteOps) && - dyn_cast(I.getOperand(opnum))) { - Instruction *argI = cast(I.getOperand(opnum)); - lists = createKilllist(argI, &I); - TransitiveReads(lists, argI, I.getParent()); - if (argI->getParent() == I.getParent()) - lists.push_back(argI); - killMap[&I] = lists; - } - } - } + funcStack.push_back(&F); - for (auto *b : RPOT) { - for (auto &I : *b) { - for (int i = 0; i < I.getNumOperands(); i++) { - if (isa(I.getOperand(i))) { - auto RD = getReachingDefs(&I, i); - if (instReachingDefsMap.find(&I) == - instReachingDefsMap.end()) { - instReachingDefsMap[&I] = RD; - } else { - auto RDList = instReachingDefsMap[&I]; - RDList.insert(RDList.end(), RD.begin(), RD.end()); - instReachingDefsMap[&I] = RDList; - } - } - } - } - } + instReachingDefsMap.clear(); + allSCCs.clear(); + reverseReachingDefsMap.clear(); + SCCAdjList.clear(); - IR2VEC_DEBUG(for (auto &Inst - : instReachingDefsMap) { - auto RD = Inst.second; - outs() << "(" << Inst.first << ")"; - Inst.first->print(outs()); - outs() << "\n RD : "; - for (auto defs : RD) { - defs->print(outs()); - outs() << "(" << defs << ") "; + Vector funcVector(DIM, 0); + + ReversePostOrderTraversal RPOT(&F); + + for (auto *b : RPOT) { + unsigned opnum; + SmallVector lists; + for (auto &I : *b) { + lists.clear(); + if (isMemOp(I.getOpcodeName(), opnum, memWriteOps) && + dyn_cast(I.getOperand(opnum))) { + Instruction *argI = cast(I.getOperand(opnum)); + lists = createKilllist(argI, &I); + TransitiveReads(lists, argI, I.getParent()); + if (argI->getParent() == I.getParent()) + lists.push_back(argI); + killMap[&I] = lists; + } + } + } + + for (auto *b : RPOT) { + for (auto &I : *b) { + for (int i = 0; i < I.getNumOperands(); i++) { + if (isa(I.getOperand(i))) { + auto RD = getReachingDefs(&I, i); + if (instReachingDefsMap.find(&I) == instReachingDefsMap.end()) { + instReachingDefsMap[&I] = RD; + } else { + auto RDList = instReachingDefsMap[&I]; + RDList.insert(RDList.end(), RD.begin(), RD.end()); + instReachingDefsMap[&I] = RDList; + } } - outs() << "\n"; - }); + } + } + } + + IR2VEC_DEBUG(for (auto &Inst + : instReachingDefsMap) { + auto RD = Inst.second; + outs() << "(" << Inst.first << ")"; + Inst.first->print(outs()); + outs() << "\n RD : "; + for (auto defs : RD) { + defs->print(outs()); + outs() << "(" << defs << ") "; + } + outs() << "\n"; + }); - // one time Reversing instReachingDefsMap to be used to calculate SCCs - for (auto &I : instReachingDefsMap) { - auto RD = I.second; + // one time Reversing instReachingDefsMap to be used to calculate SCCs + for (auto &I : instReachingDefsMap) { + auto RD = I.second; + for (auto defs : RD) { + if (reverseReachingDefsMap.find(defs) == reverseReachingDefsMap.end()) { + llvm::SmallVector revDefs; + revDefs.push_back(I.first); + reverseReachingDefsMap[defs] = revDefs; + } else { + auto defVector = reverseReachingDefsMap[defs]; + defVector.push_back(I.first); + reverseReachingDefsMap[defs] = defVector; + } + } + } + + getAllSCC(); + + std::sort(allSCCs.begin(), allSCCs.end(), + [](llvm::SmallVector &a, + llvm::SmallVector &b) { + return a.size() < b.size(); + }); + + IR2VEC_DEBUG(int i = 0; for (auto &sets + : allSCCs) { + outs() << "set: " << i << "\n"; + for (auto insts : sets) { + insts->print(outs()); + outs() << " " << insts << " "; + } + outs() << "\n"; + i++; + }); + + for (int i = 0; i < allSCCs.size(); i++) { + auto set = allSCCs[i]; + for (int j = 0; j < set.size(); j++) { + auto RD = instReachingDefsMap[set[j]]; + if (!RD.empty()) { for (auto defs : RD) { - if (reverseReachingDefsMap.find(defs) == - reverseReachingDefsMap.end()) { - llvm::SmallVector revDefs; - revDefs.push_back(I.first); - reverseReachingDefsMap[defs] = revDefs; - } else { - auto defVector = reverseReachingDefsMap[defs]; - defVector.push_back(I.first); - reverseReachingDefsMap[defs] = defVector; + for (int k = 0; k < allSCCs.size(); k++) { + if (k == i) + continue; + auto sccSet = allSCCs[k]; + if (std::find(sccSet.begin(), sccSet.end(), defs) != sccSet.end()) { + // outs() << i << " depends on " << k << "\n"; + if (SCCAdjList.find(k) == SCCAdjList.end()) { + std::vector temp; + temp.push_back(i); + SCCAdjList[k] = temp; + } else { + auto temp = SCCAdjList[k]; + if (std::find(temp.begin(), temp.end(), i) == temp.end()) + temp.push_back(i); + SCCAdjList[k] = temp; + } } + } } + } } + } - getAllSCC(); + IR2VEC_DEBUG(outs() << "\nAdjList:\n"; for (auto &nodes + : SCCAdjList) { + outs() << "Adjlist for: " << nodes.first << "\n"; + for (auto components : nodes.second) { + outs() << components << " "; + } + outs() << "\n"; + }); - std::sort(allSCCs.begin(), allSCCs.end(), - [](llvm::SmallVector &a, - llvm::SmallVector &b) { - return a.size() < b.size(); - }); + std::vector stack; - IR2VEC_DEBUG(int i = 0; for (auto &sets - : allSCCs) { - outs() << "set: " << i << "\n"; - for (auto insts : sets) { - insts->print(outs()); - outs() << " " << insts << " "; - } - outs() << "\n"; - i++; - }); + stack = topoOrder(allSCCs.size()); - for (int i = 0; i < allSCCs.size(); i++) { - auto set = allSCCs[i]; - for (int j = 0; j < set.size(); j++) { - auto RD = instReachingDefsMap[set[j]]; - if (!RD.empty()) { - for (auto defs : RD) { - for (int k = 0; k < allSCCs.size(); k++) { - if (k == i) - continue; - auto sccSet = allSCCs[k]; - if (std::find(sccSet.begin(), sccSet.end(), defs) != - sccSet.end()) { - // outs() << i << " depends on " << k << "\n"; - if (SCCAdjList.find(k) == SCCAdjList.end()) { - std::vector temp; - temp.push_back(i); - SCCAdjList[k] = temp; - } else { - auto temp = SCCAdjList[k]; - if (std::find(temp.begin(), temp.end(), i) == - temp.end()) - temp.push_back(i); - SCCAdjList[k] = temp; - } - } - } - } - } - } + for (int i = 0; i < allSCCs.size(); i++) { + if (std::find(stack.begin(), stack.end(), i) == stack.end()) { + stack.insert(stack.begin(), i); } + } - IR2VEC_DEBUG(outs() << "\nAdjList:\n"; for (auto &nodes - : SCCAdjList) { - outs() << "Adjlist for: " << nodes.first << "\n"; - for (auto components : nodes.second) { - outs() << components << " "; - } - outs() << "\n"; - }); + IR2VEC_DEBUG(outs() << "New topo order: \n"; for (auto sets + : stack) { + outs() << sets << " "; + } outs() << "\n";); - std::vector stack; + SmallVector prevVec; + Instruction *argToKill = nullptr; - stack = topoOrder(allSCCs.size()); - - for (int i = 0; i < allSCCs.size(); i++) { - if (std::find(stack.begin(), stack.end(), i) == stack.end()) { - stack.insert(stack.begin(), i); - } + while (stack.size() != 0) { + int idx = stack.back(); + stack.pop_back(); + auto component = allSCCs[idx]; + SmallMapVector partialInstValMap; + if (component.size() == 1) { + auto defs = component[0]; + partialInstValMap[defs] = {}; + getPartialVec(*defs, partialInstValMap); + solveSingleComponent(*defs, partialInstValMap); + partialInstValMap.erase(defs); + } else { + cyclicCounter++; // for components with length more than 1 will + // represent cycles + for (auto defs : component) { + partialInstValMap[defs] = {}; + getPartialVec(*defs, partialInstValMap); + } + + if (!partialInstValMap.empty()) + solveInsts(partialInstValMap); } - - IR2VEC_DEBUG(outs() << "New topo order: \n"; for (auto sets - : stack) { - outs() << sets << " "; - } outs() << "\n";); - - SmallVector prevVec; - Instruction *argToKill = nullptr; - - while (stack.size() != 0) { - int idx = stack.back(); - stack.pop_back(); - auto component = allSCCs[idx]; - SmallMapVector partialInstValMap; - if (component.size() == 1) { - auto defs = component[0]; - partialInstValMap[defs] = {}; - getPartialVec(*defs, partialInstValMap); - solveSingleComponent(*defs, partialInstValMap); - partialInstValMap.erase(defs); - } else { - cyclicCounter++; // for components with length more than 1 will - // represent cycles - for (auto defs : component) { - partialInstValMap[defs] = {}; - getPartialVec(*defs, partialInstValMap); - } - - if (!partialInstValMap.empty()) - solveInsts(partialInstValMap); - } + } + + for (auto *b : RPOT) { + bb2Vec(*b, funcStack); + Vector bbVector(DIM, 0); + IR2VEC_DEBUG(outs() << "-------------------------------------------\n"); + for (auto &I : *b) { + auto It1 = livelinessMap.find(&I); + if (It1->second == true) { + IR2VEC_DEBUG(I.print(outs()); outs() << "\n"); + auto vec = instVecMap.find(&I)->second; + IR2VEC_DEBUG(outs() << vec[0] << "\n\n"); + std::transform(bbVector.begin(), bbVector.end(), vec.begin(), + bbVector.begin(), std::plus()); + } } - for (auto *b : RPOT) { - bb2Vec(*b, funcStack); - Vector bbVector(DIM, 0); - IR2VEC_DEBUG(outs() << "-------------------------------------------\n"); - for (auto &I : *b) { - auto It1 = livelinessMap.find(&I); - if (It1->second == true) { - IR2VEC_DEBUG(I.print(outs()); outs() << "\n"); - auto vec = instVecMap.find(&I)->second; - IR2VEC_DEBUG(outs() << vec[0] << "\n\n"); - std::transform(bbVector.begin(), bbVector.end(), vec.begin(), - bbVector.begin(), std::plus()); - } - } - - IR2VEC_DEBUG(outs() << "-------------------------------------------\n"); - for (auto i : bbVector) { - if ((i <= 0.0001 && i > 0) || (i < 0 && i >= -0.0001)) { - i = 0; - } - } - - std::transform(funcVector.begin(), funcVector.end(), bbVector.begin(), - funcVector.begin(), std::plus()); + IR2VEC_DEBUG(outs() << "-------------------------------------------\n"); + for (auto i : bbVector) { + if ((i <= 0.0001 && i > 0) || (i < 0 && i >= -0.0001)) { + i = 0; + } } - funcStack.pop_back(); - funcVecMap[&F] = funcVector; - return funcVector; + std::transform(funcVector.begin(), funcVector.end(), bbVector.begin(), + funcVector.begin(), std::plus()); + } + + funcStack.pop_back(); + funcVecMap[&F] = funcVector; + return funcVector; } // LoopInfo contains a mapping from basic block to the innermost loop. Find // the outermost loop in the loop nest that contains BB. static const Loop *getOutermostLoop(const LoopInfo *LI, const BasicBlock *BB) { - const Loop *L = LI->getLoopFor(BB); - if (L) { - while (const Loop *Parent = L->getParentLoop()) - L = Parent; - } - return L; + const Loop *L = LI->getLoopFor(BB); + if (L) { + while (const Loop *Parent = L->getParentLoop()) + L = Parent; + } + return L; } bool isPotentiallyReachableFromMany( SmallVectorImpl &Worklist, BasicBlock *StopBB, const SmallPtrSetImpl *ExclusionSet, const DominatorTree *DT, const LoopInfo *LI) { - // When the stop block is unreachable, it's dominated from everywhere, - // regardless of whether there's a path between the two blocks. - if (DT && !DT->isReachableFromEntry(StopBB)) - DT = nullptr; - - // We can't skip directly from a block that dominates the stop block if the - // exclusion block is potentially in between. - if (ExclusionSet && !ExclusionSet->empty()) - DT = nullptr; - - // Normally any block in a loop is reachable from any other block in a loop, - // however excluded blocks might partition the body of a loop to make that - // untrue. - - SmallPtrSet LoopsWithHoles; - if (LI && ExclusionSet) { - for (auto BB : *ExclusionSet) { - if (const Loop *L = getOutermostLoop(LI, BB)) - LoopsWithHoles.insert(L); - } + // When the stop block is unreachable, it's dominated from everywhere, + // regardless of whether there's a path between the two blocks. + if (DT && !DT->isReachableFromEntry(StopBB)) + DT = nullptr; + + // We can't skip directly from a block that dominates the stop block if the + // exclusion block is potentially in between. + if (ExclusionSet && !ExclusionSet->empty()) + DT = nullptr; + + // Normally any block in a loop is reachable from any other block in a loop, + // however excluded blocks might partition the body of a loop to make that + // untrue. + + SmallPtrSet LoopsWithHoles; + if (LI && ExclusionSet) { + for (auto BB : *ExclusionSet) { + if (const Loop *L = getOutermostLoop(LI, BB)) + LoopsWithHoles.insert(L); + } + } + + const Loop *StopLoop = LI ? getOutermostLoop(LI, StopBB) : nullptr; + + // Limit the number of blocks we visit. The goal is to avoid run-away + // compile times on large CFGs without hampering sensible code. Arbitrarily + // chosen. + unsigned Limit = 32; + + SmallPtrSet Visited; + do { + BasicBlock *BB = Worklist.pop_back_val(); + if (!Visited.insert(BB).second) + continue; + if (BB == StopBB) + return true; + if (ExclusionSet && ExclusionSet->count(BB)) + continue; + if (DT && DT->dominates(BB, StopBB)) + return true; + + const Loop *Outer = nullptr; + if (LI) { + Outer = getOutermostLoop(LI, BB); + // If we're in a loop with a hole, not all blocks in the loop are + // reachable from all other blocks. That implies we can't simply + // jump to the loop's exit blocks, as that exit might need to pass + // through an excluded block. Clear Outer so we process BB's + // successors. + if (LoopsWithHoles.count(Outer)) + Outer = nullptr; + if (StopLoop && Outer == StopLoop) + return true; } - const Loop *StopLoop = LI ? getOutermostLoop(LI, StopBB) : nullptr; - - // Limit the number of blocks we visit. The goal is to avoid run-away - // compile times on large CFGs without hampering sensible code. Arbitrarily - // chosen. - unsigned Limit = 32; - - SmallPtrSet Visited; - do { - BasicBlock *BB = Worklist.pop_back_val(); - if (!Visited.insert(BB).second) - continue; - if (BB == StopBB) - return true; - if (ExclusionSet && ExclusionSet->count(BB)) - continue; - if (DT && DT->dominates(BB, StopBB)) - return true; - - const Loop *Outer = nullptr; - if (LI) { - Outer = getOutermostLoop(LI, BB); - // If we're in a loop with a hole, not all blocks in the loop are - // reachable from all other blocks. That implies we can't simply - // jump to the loop's exit blocks, as that exit might need to pass - // through an excluded block. Clear Outer so we process BB's - // successors. - if (LoopsWithHoles.count(Outer)) - Outer = nullptr; - if (StopLoop && Outer == StopLoop) - return true; - } - - if (!--Limit) { - // We haven't been able to prove it one way or the other. - // Conservatively answer true -- that there is potentially a path. - return true; - } + if (!--Limit) { + // We haven't been able to prove it one way or the other. + // Conservatively answer true -- that there is potentially a path. + return true; + } - if (Outer) { - // All blocks in a single loop are reachable from all other blocks. - // From any of these blocks, we can skip directly to the exits of - // the loop, ignoring any other blocks inside the loop body. - Outer->getExitBlocks(Worklist); - } else { - Worklist.append(succ_begin(BB), succ_end(BB)); - } - } while (!Worklist.empty()); + if (Outer) { + // All blocks in a single loop are reachable from all other blocks. + // From any of these blocks, we can skip directly to the exits of + // the loop, ignoring any other blocks inside the loop body. + Outer->getExitBlocks(Worklist); + } else { + Worklist.append(succ_begin(BB), succ_end(BB)); + } + } while (!Worklist.empty()); - // We have exhausted all possible paths and are certain that 'To' can not be - // reached from 'From'. - return false; + // We have exhausted all possible paths and are certain that 'To' can not be + // reached from 'From'. + return false; } bool isPotentiallyReachable( const Instruction *A, const Instruction *B, const SmallPtrSetImpl *ExclusionSet, const DominatorTree *DT, const LoopInfo *LI) { - assert(A->getParent()->getParent() == B->getParent()->getParent() && - "This analysis is function-local!"); - - SmallVector Worklist; - - if (A->getParent() == B->getParent()) { - // The same block case is special because it's the only time we're - // looking within a single block to see which instruction comes first. - // Once we start looking at multiple blocks, the first instruction of - // the block is reachable, so we only need to determine reachability - // between whole blocks. - BasicBlock *BB = const_cast(A->getParent()); - - // If the block is in a loop then we can reach any instruction in the - // block from any other instruction in the block by going around a - // backedge. - if (LI && LI->getLoopFor(BB) != nullptr) - return true; - - // Linear scan, start at 'A', see whether we hit 'B' or the end first. - for (BasicBlock::const_iterator I = A->getIterator(), E = BB->end(); - I != E; ++I) { - if (&*I == B) - return true; - } + assert(A->getParent()->getParent() == B->getParent()->getParent() && + "This analysis is function-local!"); + + SmallVector Worklist; + + if (A->getParent() == B->getParent()) { + // The same block case is special because it's the only time we're + // looking within a single block to see which instruction comes first. + // Once we start looking at multiple blocks, the first instruction of + // the block is reachable, so we only need to determine reachability + // between whole blocks. + BasicBlock *BB = const_cast(A->getParent()); + + // If the block is in a loop then we can reach any instruction in the + // block from any other instruction in the block by going around a + // backedge. + if (LI && LI->getLoopFor(BB) != nullptr) + return true; + + // Linear scan, start at 'A', see whether we hit 'B' or the end first. + for (BasicBlock::const_iterator I = A->getIterator(), E = BB->end(); I != E; + ++I) { + if (&*I == B) + return true; + } - // Can't be in a loop if it's the entry block -- the entry block may not - // have predecessors. - if (BB == &BB->getParent()->getEntryBlock()) - return false; + // Can't be in a loop if it's the entry block -- the entry block may not + // have predecessors. + if (BB == &BB->getParent()->getEntryBlock()) + return false; - // Otherwise, continue doing the normal per-BB CFG walk. - Worklist.append(succ_begin(BB), succ_end(BB)); + // Otherwise, continue doing the normal per-BB CFG walk. + Worklist.append(succ_begin(BB), succ_end(BB)); - if (Worklist.empty()) { - // We've proven that there's no path! - return false; - } - } else { - Worklist.push_back(const_cast(A->getParent())); + if (Worklist.empty()) { + // We've proven that there's no path! + return false; } - - if (DT) { - if (DT->isReachableFromEntry(A->getParent()) && - !DT->isReachableFromEntry(B->getParent())) - return false; - if (!ExclusionSet || ExclusionSet->empty()) { - if (A->getParent() == - &A->getParent()->getParent()->getEntryBlock() && - DT->isReachableFromEntry(B->getParent())) - return true; - if (B->getParent() == - &A->getParent()->getParent()->getEntryBlock() && - DT->isReachableFromEntry(A->getParent())) - return false; - } + } else { + Worklist.push_back(const_cast(A->getParent())); + } + + if (DT) { + if (DT->isReachableFromEntry(A->getParent()) && + !DT->isReachableFromEntry(B->getParent())) + return false; + if (!ExclusionSet || ExclusionSet->empty()) { + if (A->getParent() == &A->getParent()->getParent()->getEntryBlock() && + DT->isReachableFromEntry(B->getParent())) + return true; + if (B->getParent() == &A->getParent()->getParent()->getEntryBlock() && + DT->isReachableFromEntry(A->getParent())) + return false; } + } - return isPotentiallyReachableFromMany( - Worklist, const_cast(B->getParent()), ExclusionSet, DT, - LI); + return isPotentiallyReachableFromMany( + Worklist, const_cast(B->getParent()), ExclusionSet, DT, LI); } SmallVector IR2Vec_FA::getReachingDefs(const Instruction *I, unsigned loc) { - IR2VEC_DEBUG( - outs() - << "Call to getReachingDefs Started****************************\n"); - auto parent = dyn_cast(I->getOperand(loc)); - if (!parent) - return {}; - SmallVector RD; - SmallVector probableRD; - IR2VEC_DEBUG(outs() << "Inside RD for : "); - IR2VEC_DEBUG(I->print(outs()); outs() << "\n"); - - if (writeDefsMap[parent].empty()) { - RD.push_back(parent); - return RD; - } + IR2VEC_DEBUG( + outs() + << "Call to getReachingDefs Started****************************\n"); + auto parent = dyn_cast(I->getOperand(loc)); + if (!parent) + return {}; + SmallVector RD; + SmallVector probableRD; + IR2VEC_DEBUG(outs() << "Inside RD for : "); + IR2VEC_DEBUG(I->print(outs()); outs() << "\n"); - if (writeDefsMap[parent].size() >= 1) { - SmallMapVector, - 16> - bbInstMap; - // Remove definitions which don't reach I - for (auto it : writeDefsMap[parent]) { - if (it != I && isPotentiallyReachable(it, I)) { + if (writeDefsMap[parent].empty()) { + RD.push_back(parent); + return RD; + } - probableRD.push_back(it); - } - } - probableRD.push_back(parent); - IR2VEC_DEBUG(outs() << "----PROBABLE RD---" - << "\n"); - for (auto i : probableRD) { - IR2VEC_DEBUG(i->print(outs()); outs() << "\n"); - bbInstMap[i->getParent()].push_back(i); - } + if (writeDefsMap[parent].size() >= 1) { + SmallMapVector, 16> + bbInstMap; + // Remove definitions which don't reach I + for (auto it : writeDefsMap[parent]) { + if (it != I && isPotentiallyReachable(it, I)) { - IR2VEC_DEBUG(outs() << "contents of bbinstmap:\n"; for (auto i - : bbInstMap) { - for (auto j : i.second) { - j->print(outs()); - outs() << "\n"; - } - outs() << "+++++++++++++++++++++++++\n"; - }); - - // If there is a reachable write within I's basic block only that defn - // would reach always If there are more than one defn, take the - // immediate defn before I - if (!bbInstMap[I->getParent()].empty()) { - IR2VEC_DEBUG(outs() << "--------Within BB--------\n"); - IR2VEC_DEBUG(I->print(outs()); outs() << "\n"); - auto orderedVec = bbInstMap[I->getParent()]; - const Instruction *probableRD = nullptr; - for (auto &i : *(I->getParent())) { - if (&i == I) - break; - else { - if (std::find(orderedVec.begin(), orderedVec.end(), &i) != - orderedVec.end()) - probableRD = &i; - } - } + probableRD.push_back(it); + } + } + probableRD.push_back(parent); + IR2VEC_DEBUG(outs() << "----PROBABLE RD---" + << "\n"); + for (auto i : probableRD) { + IR2VEC_DEBUG(i->print(outs()); outs() << "\n"); + bbInstMap[i->getParent()].push_back(i); + } - if (probableRD != nullptr) { - IR2VEC_DEBUG(outs() << "Returning: "); - IR2VEC_DEBUG(probableRD->print(outs()); outs() << "\n"); - RD.push_back(probableRD); - return RD; - } - } + IR2VEC_DEBUG(outs() << "contents of bbinstmap:\n"; for (auto i + : bbInstMap) { + for (auto j : i.second) { + j->print(outs()); + outs() << "\n"; + } + outs() << "+++++++++++++++++++++++++\n"; + }); - IR2VEC_DEBUG(outs() << "--------Across BB--------\n"); - SmallVector toDelete; - for (auto it : bbInstMap) { - IR2VEC_DEBUG(outs() << "--------INSTMAP BEGIN--------\n"; - it.first->print(outs()); outs() << "\n"); - bool first = true; - for (auto it1 : bbInstMap[it.first]) { - if (first) { - first = false; - continue; - } - toDelete.push_back(it1); - IR2VEC_DEBUG(it1->print(outs()); outs() << "\n"); - } - IR2VEC_DEBUG(outs() << "--------INSTMAP END--------\n"); + // If there is a reachable write within I's basic block only that defn + // would reach always If there are more than one defn, take the + // immediate defn before I + if (!bbInstMap[I->getParent()].empty()) { + IR2VEC_DEBUG(outs() << "--------Within BB--------\n"); + IR2VEC_DEBUG(I->print(outs()); outs() << "\n"); + auto orderedVec = bbInstMap[I->getParent()]; + const Instruction *probableRD = nullptr; + for (auto &i : *(I->getParent())) { + if (&i == I) + break; + else { + if (std::find(orderedVec.begin(), orderedVec.end(), &i) != + orderedVec.end()) + probableRD = &i; } - auto tmp = probableRD; - probableRD = {}; - for (auto i : tmp) { - if (std::find(toDelete.begin(), toDelete.end(), i) == - toDelete.end()) - probableRD.push_back(i); + } + + if (probableRD != nullptr) { + IR2VEC_DEBUG(outs() << "Returning: "); + IR2VEC_DEBUG(probableRD->print(outs()); outs() << "\n"); + RD.push_back(probableRD); + return RD; + } + } + + IR2VEC_DEBUG(outs() << "--------Across BB--------\n"); + SmallVector toDelete; + for (auto it : bbInstMap) { + IR2VEC_DEBUG(outs() << "--------INSTMAP BEGIN--------\n"; + it.first->print(outs()); outs() << "\n"); + bool first = true; + for (auto it1 : bbInstMap[it.first]) { + if (first) { + first = false; + continue; } + toDelete.push_back(it1); + IR2VEC_DEBUG(it1->print(outs()); outs() << "\n"); + } + IR2VEC_DEBUG(outs() << "--------INSTMAP END--------\n"); + } + auto tmp = probableRD; + probableRD = {}; + for (auto i : tmp) { + if (std::find(toDelete.begin(), toDelete.end(), i) == toDelete.end()) + probableRD.push_back(i); + } - IR2VEC_DEBUG(I->print(outs()); outs() << "\n"; - outs() << "probableRD: \n"; - for (auto i - : probableRD) i->print(outs()); - outs() << "\n"; outs() << "-----------------\n"); + IR2VEC_DEBUG(I->print(outs()); outs() << "\n"; outs() << "probableRD: \n"; + for (auto i + : probableRD) i->print(outs()); + outs() << "\n"; outs() << "-----------------\n"); - SmallPtrSet bbSet; - SmallMapVector - refBBInstMap; + SmallPtrSet bbSet; + SmallMapVector refBBInstMap; - for (auto i : probableRD) { - bbSet.insert(i->getParent()); - refBBInstMap[i->getParent()] = i; - IR2VEC_DEBUG(outs() << i->getParent()->getName().str() << "\n"); - } - for (auto i : bbSet) { - IR2VEC_DEBUG(i->print(outs()); outs() << "\n"); - auto exclusionSet = bbSet; - exclusionSet.erase(i); - if (isPotentiallyReachable(refBBInstMap[i], I, &exclusionSet, - nullptr, nullptr)) { - RD.push_back(refBBInstMap[i]); - IR2VEC_DEBUG(outs() << "refBBInstMap : "; - refBBInstMap[i]->print(outs()); outs() << "\n"); - } - } - IR2VEC_DEBUG( - outs() << "****************************\n"; - outs() << "Reaching defn for "; I->print(outs()); outs() << "\n"; - for (auto i - : RD) i->print(outs()); - outs() << "\n"; - outs() - << "Call to getReachingDefs Ended****************************\n"); - return RD; + for (auto i : probableRD) { + bbSet.insert(i->getParent()); + refBBInstMap[i->getParent()] = i; + IR2VEC_DEBUG(outs() << i->getParent()->getName().str() << "\n"); + } + for (auto i : bbSet) { + IR2VEC_DEBUG(i->print(outs()); outs() << "\n"); + auto exclusionSet = bbSet; + exclusionSet.erase(i); + if (isPotentiallyReachable(refBBInstMap[i], I, &exclusionSet, nullptr, + nullptr)) { + RD.push_back(refBBInstMap[i]); + IR2VEC_DEBUG(outs() << "refBBInstMap : "; + refBBInstMap[i]->print(outs()); outs() << "\n"); + } } + IR2VEC_DEBUG( + outs() << "****************************\n"; + outs() << "Reaching defn for "; I->print(outs()); outs() << "\n"; + for (auto i + : RD) i->print(outs()); + outs() << "\n"; + outs() + << "Call to getReachingDefs Ended****************************\n"); + return RD; + } - llvm_unreachable("unreachable"); - return {}; + llvm_unreachable("unreachable"); + return {}; } bool IR2Vec_FA::isMemOp(StringRef opcode, unsigned &operand, SmallDenseMap map) { - bool isMemOperand = false; - auto It = map.find(opcode); - if (It != map.end()) { - isMemOperand = true; - operand = It->second; - } - return isMemOperand; + bool isMemOperand = false; + auto It = map.find(opcode); + if (It != map.end()) { + isMemOperand = true; + operand = It->second; + } + return isMemOperand; } /*---------------------------------------------------------------------------------- @@ -869,60 +852,60 @@ void IR2Vec_FA::getPartialVec( const Instruction &I, SmallMapVector &partialInstValMap) { - if (instVecMap.find(&I) != instVecMap.end()) { - IR2VEC_DEBUG(outs() << "Returning from inst2Vec() I found in Map\n"); - return; - } - - Vector instVector(DIM, 0); - StringRef opcodeName = I.getOpcodeName(); - auto vec = getValue(opcodeName.str()); - IR2VEC_DEBUG(I.print(outs()); outs() << "\n"); - std::transform(instVector.begin(), instVector.end(), vec.begin(), - instVector.begin(), std::plus()); - partialInstValMap[&I] = instVector; - - IR2VEC_DEBUG(outs() << "contents of partialInstValMap:\n"; - for (auto i - : partialInstValMap) { - i.first->print(outs()); - outs() << "\n"; - }); - auto type = I.getType(); - - if (type->isVoidTy()) { - vec = getValue("voidTy"); - } else if (type->isFloatingPointTy()) { - vec = getValue("floatTy"); - } else if (type->isIntegerTy()) { - vec = getValue("integerTy"); - } else if (type->isFunctionTy()) { - vec = getValue("functionTy"); - } else if (type->isStructTy()) { - vec = getValue("structTy"); - } else if (type->isArrayTy()) { - vec = getValue("arrayTy"); - } else if (type->isPointerTy()) { - vec = getValue("pointerTy"); - } else if (type->isVectorTy()) { - vec = getValue("vectorTy"); - } else if (type->isEmptyTy()) { - vec = getValue("emptyTy"); - } else if (type->isLabelTy()) { - vec = getValue("labelTy"); - } else if (type->isTokenTy()) { - vec = getValue("tokenTy"); - } else if (type->isMetadataTy()) { - vec = getValue("metadataTy"); - } else { - vec = getValue("unknownTy"); - } - - scaleVector(vec, WT); - std::transform(instVector.begin(), instVector.end(), vec.begin(), - instVector.begin(), std::plus()); - - partialInstValMap[&I] = instVector; + if (instVecMap.find(&I) != instVecMap.end()) { + IR2VEC_DEBUG(outs() << "Returning from inst2Vec() I found in Map\n"); + return; + } + + Vector instVector(DIM, 0); + StringRef opcodeName = I.getOpcodeName(); + auto vec = getValue(opcodeName.str()); + IR2VEC_DEBUG(I.print(outs()); outs() << "\n"); + std::transform(instVector.begin(), instVector.end(), vec.begin(), + instVector.begin(), std::plus()); + partialInstValMap[&I] = instVector; + + IR2VEC_DEBUG(outs() << "contents of partialInstValMap:\n"; + for (auto i + : partialInstValMap) { + i.first->print(outs()); + outs() << "\n"; + }); + auto type = I.getType(); + + if (type->isVoidTy()) { + vec = getValue("voidTy"); + } else if (type->isFloatingPointTy()) { + vec = getValue("floatTy"); + } else if (type->isIntegerTy()) { + vec = getValue("integerTy"); + } else if (type->isFunctionTy()) { + vec = getValue("functionTy"); + } else if (type->isStructTy()) { + vec = getValue("structTy"); + } else if (type->isArrayTy()) { + vec = getValue("arrayTy"); + } else if (type->isPointerTy()) { + vec = getValue("pointerTy"); + } else if (type->isVectorTy()) { + vec = getValue("vectorTy"); + } else if (type->isEmptyTy()) { + vec = getValue("emptyTy"); + } else if (type->isLabelTy()) { + vec = getValue("labelTy"); + } else if (type->isTokenTy()) { + vec = getValue("tokenTy"); + } else if (type->isMetadataTy()) { + vec = getValue("metadataTy"); + } else { + vec = getValue("unknownTy"); + } + + scaleVector(vec, WT); + std::transform(instVector.begin(), instVector.end(), vec.begin(), + instVector.begin(), std::plus()); + + partialInstValMap[&I] = instVector; } /*---------------------------------------------------------------------------------- Function to solve circular dependencies in Instructions @@ -931,201 +914,192 @@ void IR2Vec_FA::getPartialVec( void IR2Vec_FA::solveInsts( llvm::SmallMapVector &partialInstValMap) { - std::map xI; - std::map Ix; - std::vector> A, B; - SmallMapVector, 16> - RDValMap; - unsigned pos = 0; - for (auto It : partialInstValMap) { - auto inst = It.first; - if (instVecMap.find(inst) == instVecMap.end()) { - Ix[inst] = pos; - xI[pos++] = inst; - std::vector tmp; - for (auto i : It.second) { - tmp.push_back((int)(i * 10) / 10.0); + std::map xI; + std::map Ix; + std::vector> A, B; + SmallMapVector, 16> + RDValMap; + unsigned pos = 0; + for (auto It : partialInstValMap) { + auto inst = It.first; + if (instVecMap.find(inst) == instVecMap.end()) { + Ix[inst] = pos; + xI[pos++] = inst; + std::vector tmp; + for (auto i : It.second) { + tmp.push_back((int)(i * 10) / 10.0); + } + B.push_back(tmp); + for (unsigned i = 0; i < inst->getNumOperands(); i++) { + if (isa(inst->getOperand(i))) { + auto f = getValue("function"); + if (isa(inst)) { + auto ci = dyn_cast(inst); + Function *func = ci->getCalledFunction(); + if (func) { + if (!func->isDeclaration()) { + // Will be dealt with later + Vector tempCall(DIM, 0); + f = tempCall; + } } - B.push_back(tmp); - for (unsigned i = 0; i < inst->getNumOperands(); i++) { - if (isa(inst->getOperand(i))) { - auto f = getValue("function"); - if (isa(inst)) { - auto ci = dyn_cast(inst); - Function *func = ci->getCalledFunction(); - if (func) { - if (!func->isDeclaration()) { - // Will be dealt with later - Vector tempCall(DIM, 0); - f = tempCall; - } - } - } - auto svtmp = f; - scaleVector(svtmp, WA); - std::vector vtmp(svtmp.begin(), svtmp.end()); - std::vector vec = B.back(); - IR2VEC_DEBUG(outs() << vec.back() << "\n"); - IR2VEC_DEBUG(outs() << vtmp.back() << "\n"); - B.pop_back(); - std::transform(vtmp.begin(), vtmp.end(), vec.begin(), - vec.begin(), std::plus()); - IR2VEC_DEBUG(outs() << vec.back() << "\n"); - B.push_back(vec); - } else if (isa(inst->getOperand(i)) && - !isa(inst->getOperand(i)->getType())) { - auto c = getValue("constant"); - auto svtmp = c; - scaleVector(svtmp, WA); - std::vector vtmp(svtmp.begin(), svtmp.end()); - std::vector vec = B.back(); - IR2VEC_DEBUG(outs() << vec.back() << "\n"); - IR2VEC_DEBUG(outs() << vtmp.back() << "\n"); - B.pop_back(); - std::transform(vtmp.begin(), vtmp.end(), vec.begin(), - vec.begin(), std::plus()); - IR2VEC_DEBUG(outs() << vec.back() << "\n"); - B.push_back(vec); - } else if (isa(inst->getOperand(i))) { - auto l = getValue("label"); - auto svtmp = l; - scaleVector(svtmp, WA); - std::vector vtmp(svtmp.begin(), svtmp.end()); - std::vector vec = B.back(); - IR2VEC_DEBUG(outs() << vec.back() << "\n"); - IR2VEC_DEBUG(outs() << vtmp.back() << "\n"); - B.pop_back(); - std::transform(vtmp.begin(), vtmp.end(), vec.begin(), - vec.begin(), std::plus()); - IR2VEC_DEBUG(outs() << vec.back() << "\n"); - B.push_back(vec); + } + auto svtmp = f; + scaleVector(svtmp, WA); + std::vector vtmp(svtmp.begin(), svtmp.end()); + std::vector vec = B.back(); + IR2VEC_DEBUG(outs() << vec.back() << "\n"); + IR2VEC_DEBUG(outs() << vtmp.back() << "\n"); + B.pop_back(); + std::transform(vtmp.begin(), vtmp.end(), vec.begin(), vec.begin(), + std::plus()); + IR2VEC_DEBUG(outs() << vec.back() << "\n"); + B.push_back(vec); + } else if (isa(inst->getOperand(i)) && + !isa(inst->getOperand(i)->getType())) { + auto c = getValue("constant"); + auto svtmp = c; + scaleVector(svtmp, WA); + std::vector vtmp(svtmp.begin(), svtmp.end()); + std::vector vec = B.back(); + IR2VEC_DEBUG(outs() << vec.back() << "\n"); + IR2VEC_DEBUG(outs() << vtmp.back() << "\n"); + B.pop_back(); + std::transform(vtmp.begin(), vtmp.end(), vec.begin(), vec.begin(), + std::plus()); + IR2VEC_DEBUG(outs() << vec.back() << "\n"); + B.push_back(vec); + } else if (isa(inst->getOperand(i))) { + auto l = getValue("label"); + auto svtmp = l; + scaleVector(svtmp, WA); + std::vector vtmp(svtmp.begin(), svtmp.end()); + std::vector vec = B.back(); + IR2VEC_DEBUG(outs() << vec.back() << "\n"); + IR2VEC_DEBUG(outs() << vtmp.back() << "\n"); + B.pop_back(); + std::transform(vtmp.begin(), vtmp.end(), vec.begin(), vec.begin(), + std::plus()); + IR2VEC_DEBUG(outs() << vec.back() << "\n"); + B.push_back(vec); + } else { + if (isa(inst->getOperand(i))) { + auto RD = getReachingDefs(inst, i); + for (auto i : RD) { + // Check if value of RD is precomputed + if (instVecMap.find(i) == instVecMap.end()) { + if (partialInstValMap.find(i) == partialInstValMap.end()) { + assert(partialInstValMap.find(i) != partialInstValMap.end() && + "Should not reach"); + } + if (RDValMap.find(inst) == RDValMap.end()) { + SmallMapVector tmp; + tmp[i] = WA; + RDValMap[inst] = tmp; } else { - if (isa(inst->getOperand(i))) { - auto RD = getReachingDefs(inst, i); - for (auto i : RD) { - // Check if value of RD is precomputed - if (instVecMap.find(i) == instVecMap.end()) { - if (partialInstValMap.find(i) == - partialInstValMap.end()) { - assert(partialInstValMap.find(i) != - partialInstValMap.end() && - "Should not reach"); - } - if (RDValMap.find(inst) == RDValMap.end()) { - SmallMapVector - tmp; - tmp[i] = WA; - RDValMap[inst] = tmp; - } else { - RDValMap[inst][i] = WA; - } - } else { - auto svtmp = instVecMap[i]; - scaleVector(svtmp, WA); - std::vector vtmp(svtmp.begin(), - svtmp.end()); - std::vector vec = B.back(); - IR2VEC_DEBUG(outs() << vec.back() << "\n"); - IR2VEC_DEBUG(outs() << vtmp.back() << "\n"); - B.pop_back(); - std::transform(vtmp.begin(), vtmp.end(), - vec.begin(), vec.begin(), - std::plus()); - IR2VEC_DEBUG(outs() << vec.back() << "\n"); - B.push_back(vec); - } - } - } else if (isa( - inst->getOperand(i)->getType())) { - auto l = getValue("pointer"); - auto svtmp = l; - scaleVector(svtmp, WA); - std::vector vtmp(svtmp.begin(), svtmp.end()); - std::vector vec = B.back(); - IR2VEC_DEBUG(outs() << vec.back() << "\n"); - IR2VEC_DEBUG(outs() << vtmp.back() << "\n"); - B.pop_back(); - std::transform(vtmp.begin(), vtmp.end(), vec.begin(), - vec.begin(), std::plus()); - IR2VEC_DEBUG(outs() << vec.back() << "\n"); - B.push_back(vec); - } else { - auto l = getValue("variable"); - auto svtmp = l; - scaleVector(svtmp, WA); - std::vector vtmp(svtmp.begin(), svtmp.end()); - std::vector vec = B.back(); - IR2VEC_DEBUG(outs() << vec.back() << "\n"); - IR2VEC_DEBUG(outs() << vtmp.back() << "\n"); - B.pop_back(); - std::transform(vtmp.begin(), vtmp.end(), vec.begin(), - vec.begin(), std::plus()); - IR2VEC_DEBUG(outs() << vec.back() << "\n"); - B.push_back(vec); - } + RDValMap[inst][i] = WA; } + } else { + auto svtmp = instVecMap[i]; + scaleVector(svtmp, WA); + std::vector vtmp(svtmp.begin(), svtmp.end()); + std::vector vec = B.back(); + IR2VEC_DEBUG(outs() << vec.back() << "\n"); + IR2VEC_DEBUG(outs() << vtmp.back() << "\n"); + B.pop_back(); + std::transform(vtmp.begin(), vtmp.end(), vec.begin(), + vec.begin(), std::plus()); + IR2VEC_DEBUG(outs() << vec.back() << "\n"); + B.push_back(vec); + } } + } else if (isa(inst->getOperand(i)->getType())) { + auto l = getValue("pointer"); + auto svtmp = l; + scaleVector(svtmp, WA); + std::vector vtmp(svtmp.begin(), svtmp.end()); + std::vector vec = B.back(); + IR2VEC_DEBUG(outs() << vec.back() << "\n"); + IR2VEC_DEBUG(outs() << vtmp.back() << "\n"); + B.pop_back(); + std::transform(vtmp.begin(), vtmp.end(), vec.begin(), vec.begin(), + std::plus()); + IR2VEC_DEBUG(outs() << vec.back() << "\n"); + B.push_back(vec); + } else { + auto l = getValue("variable"); + auto svtmp = l; + scaleVector(svtmp, WA); + std::vector vtmp(svtmp.begin(), svtmp.end()); + std::vector vec = B.back(); + IR2VEC_DEBUG(outs() << vec.back() << "\n"); + IR2VEC_DEBUG(outs() << vtmp.back() << "\n"); + B.pop_back(); + std::transform(vtmp.begin(), vtmp.end(), vec.begin(), vec.begin(), + std::plus()); + IR2VEC_DEBUG(outs() << vec.back() << "\n"); + B.push_back(vec); + } } + } } - - for (unsigned i = 0; i < xI.size(); i++) { - std::vector tmp(xI.size(), 0); - A.push_back(tmp); + } + + for (unsigned i = 0; i < xI.size(); i++) { + std::vector tmp(xI.size(), 0); + A.push_back(tmp); + } + + for (unsigned i = 0; i < xI.size(); i++) { + A[i][i] = 1; + auto tmp = A[i]; + auto instRDVal = RDValMap[xI[i]]; + for (auto j : instRDVal) { + A[i][Ix[j.first]] = (int)((A[i][Ix[j.first]] - j.second) * 10) / 10.0; } + } - for (unsigned i = 0; i < xI.size(); i++) { - A[i][i] = 1; - auto tmp = A[i]; - auto instRDVal = RDValMap[xI[i]]; - for (auto j : instRDVal) { - A[i][Ix[j.first]] = - (int)((A[i][Ix[j.first]] - j.second) * 10) / 10.0; - } + for (unsigned i = 0; i < B.size(); i++) { + auto Bvec = B[i]; + for (unsigned j = 0; j < B[i].size(); j++) { + B[i][j] = (int)(B[i][j] * 10) / 10.0; } + } - for (unsigned i = 0; i < B.size(); i++) { - auto Bvec = B[i]; - for (unsigned j = 0; j < B[i].size(); j++) { - B[i][j] = (int)(B[i][j] * 10) / 10.0; - } - } + auto C = solve(A, B); + SmallMapVector, 16> + bbInstMap; - auto C = solve(A, B); - SmallMapVector, 16> - bbInstMap; - - for (unsigned i = 0; i < C.size(); i++) { - Vector tmp(C[i].begin(), C[i].end()); - IR2VEC_DEBUG(outs() << "inst:" - << "\t"; - xI[i]->print(outs()); - outs() << "\nVAL: " << tmp[0] << "\n"); + for (unsigned i = 0; i < C.size(); i++) { + Vector tmp(C[i].begin(), C[i].end()); + IR2VEC_DEBUG(outs() << "inst:" + << "\t"; + xI[i]->print(outs()); outs() << "\nVAL: " << tmp[0] << "\n"); - instVecMap[xI[i]] = tmp; - livelinessMap.try_emplace(xI[i], true); + instVecMap[xI[i]] = tmp; + livelinessMap.try_emplace(xI[i], true); - instSolvedBySolver.push_back(xI[i]); - bbInstMap[xI[i]->getParent()].push_back(xI[i]); - } + instSolvedBySolver.push_back(xI[i]); + bbInstMap[xI[i]->getParent()].push_back(xI[i]); + } - for (auto BB : bbInstMap) { - unsigned opnum; - auto orderedInstVec = BB.second; - for (auto I : orderedInstVec) { - if (killMap.find(I) != killMap.end()) { - auto list = killMap[I]; - for (auto defs : list) { - auto It2 = livelinessMap.find(defs); - if (It2 == livelinessMap.end()) - livelinessMap.try_emplace(defs, false); - else - It2->second = false; - } - } + for (auto BB : bbInstMap) { + unsigned opnum; + auto orderedInstVec = BB.second; + for (auto I : orderedInstVec) { + if (killMap.find(I) != killMap.end()) { + auto list = killMap[I]; + for (auto defs : list) { + auto It2 = livelinessMap.find(defs); + if (It2 == livelinessMap.end()) + livelinessMap.try_emplace(defs, false); + else + It2->second = false; } + } } + } } /*---------------------------------------------------------------------------------- @@ -1137,111 +1111,109 @@ void IR2Vec_FA::solveSingleComponent( const Instruction &I, SmallMapVector &partialInstValMap) { - if (instVecMap.find(&I) != instVecMap.end()) { - IR2VEC_DEBUG(outs() << "Returning from inst2Vec() I found in Map\n"); - return; - } - - Vector instVector(DIM, 0); - StringRef opcodeName = I.getOpcodeName(); - - instVector = partialInstValMap[&I]; - - unsigned operandNum; - bool isMemWrite = isMemOp(opcodeName, operandNum, memWriteOps); - bool isCyclic = false; - Vector VecArgs(DIM, 0); - - SmallVector RDList; - RDList.clear(); - - for (unsigned i = 0; i < I.getNumOperands() /*&& !isCyclic*/; i++) { - Vector vecOp(DIM, 0); - if (isa(I.getOperand(i))) { - vecOp = getValue("function"); - if (isa(I)) { - auto ci = dyn_cast(&I); - Function *func = ci->getCalledFunction(); - if (func) { - if (!func->isDeclaration()) { - // Will be dealt with later - Vector tempCall(DIM, 0); - vecOp = tempCall; - } - } - } - } - // Checking that the argument is not of pointer type because some - // non-numeric/alphabetic constants are also caught as pointer types - else if (isa(I.getOperand(i)) && - !isa(I.getOperand(i)->getType())) { - vecOp = getValue("constant"); - } else if (isa(I.getOperand(i))) { - vecOp = getValue("label"); - } else { - if (isa(I.getOperand(i))) { - auto RD = getReachingDefs(&I, i); - RDList.insert(RDList.end(), RD.begin(), RD.end()); - } else if (isa(I.getOperand(i)->getType())) { - vecOp = getValue("pointer"); - } else - vecOp = getValue("variable"); + if (instVecMap.find(&I) != instVecMap.end()) { + IR2VEC_DEBUG(outs() << "Returning from inst2Vec() I found in Map\n"); + return; + } + + Vector instVector(DIM, 0); + StringRef opcodeName = I.getOpcodeName(); + + instVector = partialInstValMap[&I]; + + unsigned operandNum; + bool isMemWrite = isMemOp(opcodeName, operandNum, memWriteOps); + bool isCyclic = false; + Vector VecArgs(DIM, 0); + + SmallVector RDList; + RDList.clear(); + + for (unsigned i = 0; i < I.getNumOperands() /*&& !isCyclic*/; i++) { + Vector vecOp(DIM, 0); + if (isa(I.getOperand(i))) { + vecOp = getValue("function"); + if (isa(I)) { + auto ci = dyn_cast(&I); + Function *func = ci->getCalledFunction(); + if (func) { + if (!func->isDeclaration()) { + // Will be dealt with later + Vector tempCall(DIM, 0); + vecOp = tempCall; + } } - - std::transform(VecArgs.begin(), VecArgs.end(), vecOp.begin(), - VecArgs.begin(), std::plus()); + } + } + // Checking that the argument is not of pointer type because some + // non-numeric/alphabetic constants are also caught as pointer types + else if (isa(I.getOperand(i)) && + !isa(I.getOperand(i)->getType())) { + vecOp = getValue("constant"); + } else if (isa(I.getOperand(i))) { + vecOp = getValue("label"); + } else { + if (isa(I.getOperand(i))) { + auto RD = getReachingDefs(&I, i); + RDList.insert(RDList.end(), RD.begin(), RD.end()); + } else if (isa(I.getOperand(i)->getType())) { + vecOp = getValue("pointer"); + } else + vecOp = getValue("variable"); } - Vector vecInst = Vector(DIM, 0); + std::transform(VecArgs.begin(), VecArgs.end(), vecOp.begin(), + VecArgs.begin(), std::plus()); + } - if (!RDList.empty()) { - for (auto i : RDList) { - // Check if value of RD is precomputed - if (instVecMap.find(i) == instVecMap.end()) { + Vector vecInst = Vector(DIM, 0); - /*Some phi instructions reach themselves and hence may not be in - the instVecMap but should be in the partialInstValMap*/ + if (!RDList.empty()) { + for (auto i : RDList) { + // Check if value of RD is precomputed + if (instVecMap.find(i) == instVecMap.end()) { - if (partialInstValMap.find(i) == partialInstValMap.end()) { - assert(partialInstValMap.find(i) != - partialInstValMap.end() && - "Should have been in instvecmap or partialmap"); - } - } else { - std::transform(instVecMap[i].begin(), instVecMap[i].end(), - vecInst.begin(), vecInst.begin(), - std::plus()); - } + /*Some phi instructions reach themselves and hence may not be in + the instVecMap but should be in the partialInstValMap*/ + + if (partialInstValMap.find(i) == partialInstValMap.end()) { + assert(partialInstValMap.find(i) != partialInstValMap.end() && + "Should have been in instvecmap or partialmap"); } + } else { + std::transform(instVecMap[i].begin(), instVecMap[i].end(), + vecInst.begin(), vecInst.begin(), std::plus()); + } } + } - if (!isCyclic) { - std::transform(VecArgs.begin(), VecArgs.end(), vecInst.begin(), - VecArgs.begin(), std::plus()); - - IR2VEC_DEBUG(outs() << VecArgs[0]); - - scaleVector(VecArgs, WA); - IR2VEC_DEBUG(outs() << VecArgs.front()); - std::transform(instVector.begin(), instVector.end(), VecArgs.begin(), - instVector.begin(), std::plus()); - IR2VEC_DEBUG(outs() << instVector.front()); - - instVecMap[&I] = instVector; - livelinessMap.try_emplace(&I, true); - - if (killMap.find(&I) != killMap.end()) { - auto list = killMap[&I]; - for (auto defs : list) { - auto It2 = livelinessMap.find(defs); - if (It2 == livelinessMap.end()) - livelinessMap.try_emplace(defs, false); - else - It2->second = false; - } - } + if (!isCyclic) { + std::transform(VecArgs.begin(), VecArgs.end(), vecInst.begin(), + VecArgs.begin(), std::plus()); + + IR2VEC_DEBUG(outs() << VecArgs[0]); + + scaleVector(VecArgs, WA); + IR2VEC_DEBUG(outs() << VecArgs.front()); + std::transform(instVector.begin(), instVector.end(), VecArgs.begin(), + instVector.begin(), std::plus()); + IR2VEC_DEBUG(outs() << instVector.front()); + + instVecMap[&I] = instVector; + livelinessMap.try_emplace(&I, true); + + if (killMap.find(&I) != killMap.end()) { + auto list = killMap[&I]; + for (auto defs : list) { + auto It2 = livelinessMap.find(defs); + if (It2 == livelinessMap.end()) + livelinessMap.try_emplace(defs, false); + else + It2->second = false; + } } - assert(isCyclic == false && "A Single Component should not have a cycle!"); + } + assert(isCyclic == false && "A Single Component should not have a cycle!"); } /*---------------------------------------------------------------------------------- @@ -1253,147 +1225,146 @@ void IR2Vec_FA::inst2Vec( const Instruction &I, SmallVector &funcStack, SmallMapVector &partialInstValMap) { - if (instVecMap.find(&I) != instVecMap.end()) { - IR2VEC_DEBUG(outs() << "Returning from inst2Vec() I found in Map\n"); - return; + if (instVecMap.find(&I) != instVecMap.end()) { + IR2VEC_DEBUG(outs() << "Returning from inst2Vec() I found in Map\n"); + return; + } + + Vector instVector(DIM, 0); + StringRef opcodeName = I.getOpcodeName(); + auto vec = getValue(opcodeName.str()); + IR2VEC_DEBUG(I.print(outs()); outs() << "\n"); + std::transform(instVector.begin(), instVector.end(), vec.begin(), + instVector.begin(), std::plus()); + partialInstValMap[&I] = instVector; + + IR2VEC_DEBUG(outs() << "contents of partialInstValMap:\n"; + for (auto i + : partialInstValMap) { + i.first->print(outs()); + outs() << "\n"; + }); + + auto type = I.getType(); + + if (type->isVoidTy()) { + vec = getValue("voidTy"); + } else if (type->isFloatingPointTy()) { + vec = getValue("floatTy"); + } else if (type->isIntegerTy()) { + vec = getValue("integerTy"); + } else if (type->isFunctionTy()) { + vec = getValue("functionTy"); + } else if (type->isStructTy()) { + vec = getValue("structTy"); + } else if (type->isArrayTy()) { + vec = getValue("arrayTy"); + } else if (type->isPointerTy()) { + vec = getValue("pointerTy"); + } else if (type->isVectorTy()) { + vec = getValue("vectorTy"); + } else if (type->isEmptyTy()) { + vec = getValue("emptyTy"); + } else if (type->isLabelTy()) { + vec = getValue("labelTy"); + } else if (type->isTokenTy()) { + vec = getValue("tokenTy"); + } else if (type->isMetadataTy()) { + vec = getValue("metadataTy"); + } else { + vec = getValue("unknownTy"); + } + scaleVector(vec, WT); + std::transform(instVector.begin(), instVector.end(), vec.begin(), + instVector.begin(), std::plus()); + partialInstValMap[&I] = instVector; + + unsigned operandNum; + bool isMemWrite = isMemOp(opcodeName, operandNum, memWriteOps); + bool isCyclic = false; + Vector VecArgs(DIM, 0); + + SmallVector RDList; + RDList.clear(); + + for (unsigned i = 0; i < I.getNumOperands() /*&& !isCyclic*/; i++) { + Vector vecOp(DIM, 0); + if (isa(I.getOperand(i))) { + vecOp = getValue("function"); + if (isa(I)) { + auto ci = dyn_cast(&I); + Function *func = ci->getCalledFunction(); + if (func) { + if (!func->isDeclaration()) { + // Will be dealt with later + Vector tempCall(DIM, 0); + vecOp = tempCall; + } + } + } } - - Vector instVector(DIM, 0); - StringRef opcodeName = I.getOpcodeName(); - auto vec = getValue(opcodeName.str()); - IR2VEC_DEBUG(I.print(outs()); outs() << "\n"); - std::transform(instVector.begin(), instVector.end(), vec.begin(), - instVector.begin(), std::plus()); - partialInstValMap[&I] = instVector; - - IR2VEC_DEBUG(outs() << "contents of partialInstValMap:\n"; - for (auto i - : partialInstValMap) { - i.first->print(outs()); - outs() << "\n"; - }); - - auto type = I.getType(); - - if (type->isVoidTy()) { - vec = getValue("voidTy"); - } else if (type->isFloatingPointTy()) { - vec = getValue("floatTy"); - } else if (type->isIntegerTy()) { - vec = getValue("integerTy"); - } else if (type->isFunctionTy()) { - vec = getValue("functionTy"); - } else if (type->isStructTy()) { - vec = getValue("structTy"); - } else if (type->isArrayTy()) { - vec = getValue("arrayTy"); - } else if (type->isPointerTy()) { - vec = getValue("pointerTy"); - } else if (type->isVectorTy()) { - vec = getValue("vectorTy"); - } else if (type->isEmptyTy()) { - vec = getValue("emptyTy"); - } else if (type->isLabelTy()) { - vec = getValue("labelTy"); - } else if (type->isTokenTy()) { - vec = getValue("tokenTy"); - } else if (type->isMetadataTy()) { - vec = getValue("metadataTy"); + // Checking that the argument is not of pointer type because some + // non-numeric/alphabetic constants are also caught as pointer types + else if (isa(I.getOperand(i)) && + !isa(I.getOperand(i)->getType())) { + vecOp = getValue("constant"); + } else if (isa(I.getOperand(i))) { + vecOp = getValue("label"); } else { - vec = getValue("unknownTy"); + if (isa(I.getOperand(i))) { + auto RD = getReachingDefs(&I, i); + RDList.insert(RDList.end(), RD.begin(), RD.end()); + } else if (isa(I.getOperand(i)->getType())) + vecOp = getValue("pointer"); + else + vecOp = getValue("variable"); } - scaleVector(vec, WT); - std::transform(instVector.begin(), instVector.end(), vec.begin(), - instVector.begin(), std::plus()); - partialInstValMap[&I] = instVector; - - unsigned operandNum; - bool isMemWrite = isMemOp(opcodeName, operandNum, memWriteOps); - bool isCyclic = false; - Vector VecArgs(DIM, 0); - - SmallVector RDList; - RDList.clear(); - - for (unsigned i = 0; i < I.getNumOperands() /*&& !isCyclic*/; i++) { - Vector vecOp(DIM, 0); - if (isa(I.getOperand(i))) { - vecOp = getValue("function"); - if (isa(I)) { - auto ci = dyn_cast(&I); - Function *func = ci->getCalledFunction(); - if (func) { - if (!func->isDeclaration()) { - // Will be dealt with later - Vector tempCall(DIM, 0); - vecOp = tempCall; - } - } - } - } - // Checking that the argument is not of pointer type because some - // non-numeric/alphabetic constants are also caught as pointer types - else if (isa(I.getOperand(i)) && - !isa(I.getOperand(i)->getType())) { - vecOp = getValue("constant"); - } else if (isa(I.getOperand(i))) { - vecOp = getValue("label"); - } else { - if (isa(I.getOperand(i))) { - auto RD = getReachingDefs(&I, i); - RDList.insert(RDList.end(), RD.begin(), RD.end()); - } else if (isa(I.getOperand(i)->getType())) - vecOp = getValue("pointer"); - else - vecOp = getValue("variable"); - } - std::transform(VecArgs.begin(), VecArgs.end(), vecOp.begin(), - VecArgs.begin(), std::plus()); + std::transform(VecArgs.begin(), VecArgs.end(), vecOp.begin(), + VecArgs.begin(), std::plus()); + } + + Vector vecInst = Vector(DIM, 0); + + if (!RDList.empty()) { + for (auto i : RDList) { + // Check if value of RD is precomputed + if (instVecMap.find(i) == instVecMap.end()) { + assert(instVecMap.find(i) != instVecMap.end() && + "All RDs should have been solved by Topo Order!"); + } else { + std::transform(instVecMap[i].begin(), instVecMap[i].end(), + vecInst.begin(), vecInst.begin(), std::plus()); + } } + } - Vector vecInst = Vector(DIM, 0); - - if (!RDList.empty()) { - for (auto i : RDList) { - // Check if value of RD is precomputed - if (instVecMap.find(i) == instVecMap.end()) { - assert(instVecMap.find(i) != instVecMap.end() && - "All RDs should have been solved by Topo Order!"); - } else { - std::transform(instVecMap[i].begin(), instVecMap[i].end(), - vecInst.begin(), vecInst.begin(), - std::plus()); - } - } - } + if (!isCyclic) { + std::transform(VecArgs.begin(), VecArgs.end(), vecInst.begin(), + VecArgs.begin(), std::plus()); - if (!isCyclic) { - std::transform(VecArgs.begin(), VecArgs.end(), vecInst.begin(), - VecArgs.begin(), std::plus()); - - IR2VEC_DEBUG(outs() << VecArgs[0]); - - scaleVector(VecArgs, WA); - IR2VEC_DEBUG(outs() << VecArgs.front()); - std::transform(instVector.begin(), instVector.end(), VecArgs.begin(), - instVector.begin(), std::plus()); - IR2VEC_DEBUG(outs() << instVector.front()); - instVecMap[&I] = instVector; - livelinessMap.try_emplace(&I, true); - - if (killMap.find(&I) != killMap.end()) { - auto list = killMap[&I]; - for (auto defs : list) { - auto It2 = livelinessMap.find(defs); - if (It2 == livelinessMap.end()) - livelinessMap.try_emplace(defs, false); - else - It2->second = false; - } - } + IR2VEC_DEBUG(outs() << VecArgs[0]); + + scaleVector(VecArgs, WA); + IR2VEC_DEBUG(outs() << VecArgs.front()); + std::transform(instVector.begin(), instVector.end(), VecArgs.begin(), + instVector.begin(), std::plus()); + IR2VEC_DEBUG(outs() << instVector.front()); + instVecMap[&I] = instVector; + livelinessMap.try_emplace(&I, true); + + if (killMap.find(&I) != killMap.end()) { + auto list = killMap[&I]; + for (auto defs : list) { + auto It2 = livelinessMap.find(defs); + if (It2 == livelinessMap.end()) + livelinessMap.try_emplace(defs, false); + else + It2->second = false; + } } - assert(isCyclic == false && "All dependencies should have been solved!"); + } + assert(isCyclic == false && "All dependencies should have been solved!"); } /*---------------------------------------------------------------------------------- @@ -1406,21 +1377,21 @@ void IR2Vec_FA::traverseRD( std::unordered_map &Visited, llvm::SmallVector &timeStack) { - auto RDit = instReachingDefsMap.find(inst); + auto RDit = instReachingDefsMap.find(inst); - Visited[inst] = true; + Visited[inst] = true; - if (RDit != instReachingDefsMap.end()) { + if (RDit != instReachingDefsMap.end()) { - auto RD = RDit->second; + auto RD = RDit->second; - for (auto defs : RD) { - if (Visited.find(defs) == Visited.end()) - traverseRD(defs, Visited, timeStack); - } + for (auto defs : RD) { + if (Visited.find(defs) == Visited.end()) + traverseRD(defs, Visited, timeStack); } - // All the children (RDs) of current node is done push to timeStack - timeStack.push_back(inst); + } + // All the children (RDs) of current node is done push to timeStack + timeStack.push_back(inst); } void IR2Vec_FA::DFSUtil( @@ -1428,15 +1399,15 @@ void IR2Vec_FA::DFSUtil( std::unordered_map &Visited, llvm::SmallVector &set) { - Visited[inst] = true; - auto RD = reverseReachingDefsMap[inst]; + Visited[inst] = true; + auto RD = reverseReachingDefsMap[inst]; - for (auto defs : RD) { - if (Visited.find(defs) == Visited.end()) { - set.push_back(defs); - DFSUtil(defs, Visited, set); - } + for (auto defs : RD) { + if (Visited.find(defs) == Visited.end()) { + set.push_back(defs); + DFSUtil(defs, Visited, set); } + } } /*---------------------------------------------------------------------------------- @@ -1446,45 +1417,45 @@ void IR2Vec_FA::DFSUtil( void IR2Vec_FA::getAllSCC() { - std::unordered_map Visited; + std::unordered_map Visited; - llvm::SmallVector timeStack; + llvm::SmallVector timeStack; - for (auto &I : instReachingDefsMap) { - if (Visited.find(I.first) == Visited.end()) { - traverseRD(I.first, Visited, timeStack); - } + for (auto &I : instReachingDefsMap) { + if (Visited.find(I.first) == Visited.end()) { + traverseRD(I.first, Visited, timeStack); } - - IR2VEC_DEBUG(for (auto &defs : timeStack) { outs() << defs << "\n"; }); - - Visited.clear(); - - // Second pass getting SCCs - while (timeStack.size() != 0) { - auto inst = timeStack.back(); - timeStack.pop_back(); - if (Visited.find(inst) == Visited.end()) { - llvm::SmallVector set; - set.push_back(inst); - DFSUtil(inst, Visited, set); - if (set.size() != 0) - allSCCs.push_back(set); - } + } + + IR2VEC_DEBUG(for (auto &defs : timeStack) { outs() << defs << "\n"; }); + + Visited.clear(); + + // Second pass getting SCCs + while (timeStack.size() != 0) { + auto inst = timeStack.back(); + timeStack.pop_back(); + if (Visited.find(inst) == Visited.end()) { + llvm::SmallVector set; + set.push_back(inst); + DFSUtil(inst, Visited, set); + if (set.size() != 0) + allSCCs.push_back(set); } + } } void IR2Vec_FA::bb2Vec(BasicBlock &B, SmallVector &funcStack) { - SmallMapVector partialInstValMap; - - for (auto &I : B) { - - partialInstValMap[&I] = {}; - IR2VEC_DEBUG(outs() << "XX------------ Call from bb2vec function " - "Started---------------------XX\n"); - inst2Vec(I, funcStack, partialInstValMap); - IR2VEC_DEBUG(outs() << "YY------------Call from bb2vec function " - "Ended---------------------YY\n"); - partialInstValMap.erase(&I); - } + SmallMapVector partialInstValMap; + + for (auto &I : B) { + + partialInstValMap[&I] = {}; + IR2VEC_DEBUG(outs() << "XX------------ Call from bb2vec function " + "Started---------------------XX\n"); + inst2Vec(I, funcStack, partialInstValMap); + IR2VEC_DEBUG(outs() << "YY------------Call from bb2vec function " + "Ended---------------------YY\n"); + partialInstValMap.erase(&I); + } } diff --git a/src/IR2Vec.cpp b/src/IR2Vec.cpp index 71201f2c..79252d53 100644 --- a/src/IR2Vec.cpp +++ b/src/IR2Vec.cpp @@ -68,143 +68,142 @@ cl::opt cl_debug("debug-ir2vec", cl::Optional, cl::cat(category)); void printVersion(raw_ostream &ostream) { - ostream << "\033[1;35m" - << "IR2Vec Version : " << IR2VEC_VERSION << "\033[0m\n"; - cl::PrintVersionMessage(); + ostream << "\033[1;35m" + << "IR2Vec Version : " << IR2VEC_VERSION << "\033[0m\n"; + cl::PrintVersionMessage(); } int main(int argc, char **argv) { - cl::SetVersionPrinter(printVersion); - cl::HideUnrelatedOptions(category); - cl::ParseCommandLineOptions(argc, argv); - - fa = cl_fa; - sym = cl_sym; - collectIR = cl_collectIR; - vocab = cl_vocab; - iname = cl_iname; - oname = cl_oname; - // newly added - funcName = cl_funcName; - level = cl_level; - cls = cl_cls; - WO = cl_WO; - WA = cl_WA; - WT = cl_WT; - debug = cl_debug; - printTime = cl_printTime; - - bool failed = false; - if (!((sym ^ fa) ^ collectIR)) { - errs() << "Either of sym, fa or collectIR should be specified\n"; - failed = true; + cl::SetVersionPrinter(printVersion); + cl::HideUnrelatedOptions(category); + cl::ParseCommandLineOptions(argc, argv); + + fa = cl_fa; + sym = cl_sym; + collectIR = cl_collectIR; + vocab = cl_vocab; + iname = cl_iname; + oname = cl_oname; + // newly added + funcName = cl_funcName; + level = cl_level; + cls = cl_cls; + WO = cl_WO; + WA = cl_WA; + WT = cl_WT; + debug = cl_debug; + printTime = cl_printTime; + + bool failed = false; + if (!((sym ^ fa) ^ collectIR)) { + errs() << "Either of sym, fa or collectIR should be specified\n"; + failed = true; + } + + if (sym || fa) { + if (level != 'p' && level != 'f') { + errs() << "Invalid level specified: Use either p or f\n"; + failed = true; } - - if (sym || fa) { - if (level != 'p' && level != 'f') { - errs() << "Invalid level specified: Use either p or f\n"; - failed = true; - } - if (vocab.empty()) { - errs() - << "Should specify vocab pointing to the path of vocabulary\n"; - failed = true; - } + if (vocab.empty()) { + errs() << "Should specify vocab pointing to the path of vocabulary\n"; + failed = true; + } + } else { + if (!collectIR) { + errs() << "Either of sym, fa or collectIR should be specified\n"; + failed = true; + } else if (level) + errs() << "[WARNING] level would not be used in collectIR mode\n"; + else if (!vocab.empty()) + errs() << "[WARNING] vocab would not be used in collectIR mode\n"; + } + + if (failed) + exit(1); + + auto M = getLLVMIR(); + // newly added + if (sym && !(funcName.empty())) { + IR2Vec_Symbolic SYM(*M); + std::ofstream o; + o.open(oname, std::ios_base::app); + if (printTime) { + clock_t start = clock(); + SYM.generateSymbolicEncodingsForFunction(&o, funcName); + clock_t end = clock(); + double elapsed = double(end - start) / CLOCKS_PER_SEC; + printf("Time taken by on-demand generation of symbolic encodings " + "is: %.6f " + "seconds.\n", + elapsed); } else { - if (!collectIR) { - errs() << "Either of sym, fa or collectIR should be specified\n"; - failed = true; - } else if (level) - errs() << "[WARNING] level would not be used in collectIR mode\n"; - else if (!vocab.empty()) - errs() << "[WARNING] vocab would not be used in collectIR mode\n"; + SYM.generateSymbolicEncodingsForFunction(&o, funcName); } - - if (failed) - exit(1); - - auto M = getLLVMIR(); - // newly added - if (sym && !(funcName.empty())) { - IR2Vec_Symbolic SYM(*M); - std::ofstream o; - o.open(oname, std::ios_base::app); - if (printTime) { - clock_t start = clock(); - SYM.generateSymbolicEncodingsForFunction(&o, funcName); - clock_t end = clock(); - double elapsed = double(end - start) / CLOCKS_PER_SEC; - printf("Time taken by on-demand generation of symbolic encodings " - "is: %.6f " - "seconds.\n", - elapsed); - } else { - SYM.generateSymbolicEncodingsForFunction(&o, funcName); - } - o.close(); - } else if (fa && !(funcName.empty())) { - IR2Vec_FA FA(*M); - std::ofstream o, missCount, cyclicCount; - o.open(oname, std::ios_base::app); - missCount.open("missCount_" + oname, std::ios_base::app); - cyclicCount.open("cyclicCount_" + oname, std::ios_base::app); - if (printTime) { - clock_t start = clock(); - FA.generateFlowAwareEncodingsForFunction(&o, funcName, &missCount, - &cyclicCount); - clock_t end = clock(); - double elapsed = double(end - start) / CLOCKS_PER_SEC; - printf("Time taken by on-demand generation of flow-aware encodings " - "is: %.6f " - "seconds.\n", - elapsed); - } else { - FA.generateFlowAwareEncodingsForFunction(&o, funcName, &missCount, - &cyclicCount); - } - o.close(); - } else if (fa) { - IR2Vec_FA FA(*M); - std::ofstream o, missCount, cyclicCount; - o.open(oname, std::ios_base::app); - missCount.open("missCount_" + oname, std::ios_base::app); - cyclicCount.open("cyclicCount_" + oname, std::ios_base::app); - if (printTime) { - clock_t start = clock(); - FA.generateFlowAwareEncodings(&o, &missCount, &cyclicCount); - clock_t end = clock(); - double elapsed = double(end - start) / CLOCKS_PER_SEC; - printf("Time taken by normal generation of flow-aware encodings " - "is: %.6f " - "seconds.\n", - elapsed); - } else { - FA.generateFlowAwareEncodings(&o, &missCount, &cyclicCount); - } - o.close(); - } else if (sym) { - IR2Vec_Symbolic SYM(*M); - std::ofstream o; - o.open(oname, std::ios_base::app); - if (printTime) { - clock_t start = clock(); - SYM.generateSymbolicEncodings(&o); - clock_t end = clock(); - double elapsed = double(end - start) / CLOCKS_PER_SEC; - printf("Time taken by normal generation of symbolic encodings is: " - "%.6f " - "seconds.\n", - elapsed); - } else { - SYM.generateSymbolicEncodings(&o); - } - o.close(); - } else if (collectIR) { - CollectIR cir(M); - std::ofstream o; - o.open(oname, std::ios_base::app); - cir.generateTriplets(o); - o.close(); + o.close(); + } else if (fa && !(funcName.empty())) { + IR2Vec_FA FA(*M); + std::ofstream o, missCount, cyclicCount; + o.open(oname, std::ios_base::app); + missCount.open("missCount_" + oname, std::ios_base::app); + cyclicCount.open("cyclicCount_" + oname, std::ios_base::app); + if (printTime) { + clock_t start = clock(); + FA.generateFlowAwareEncodingsForFunction(&o, funcName, &missCount, + &cyclicCount); + clock_t end = clock(); + double elapsed = double(end - start) / CLOCKS_PER_SEC; + printf("Time taken by on-demand generation of flow-aware encodings " + "is: %.6f " + "seconds.\n", + elapsed); + } else { + FA.generateFlowAwareEncodingsForFunction(&o, funcName, &missCount, + &cyclicCount); + } + o.close(); + } else if (fa) { + IR2Vec_FA FA(*M); + std::ofstream o, missCount, cyclicCount; + o.open(oname, std::ios_base::app); + missCount.open("missCount_" + oname, std::ios_base::app); + cyclicCount.open("cyclicCount_" + oname, std::ios_base::app); + if (printTime) { + clock_t start = clock(); + FA.generateFlowAwareEncodings(&o, &missCount, &cyclicCount); + clock_t end = clock(); + double elapsed = double(end - start) / CLOCKS_PER_SEC; + printf("Time taken by normal generation of flow-aware encodings " + "is: %.6f " + "seconds.\n", + elapsed); + } else { + FA.generateFlowAwareEncodings(&o, &missCount, &cyclicCount); + } + o.close(); + } else if (sym) { + IR2Vec_Symbolic SYM(*M); + std::ofstream o; + o.open(oname, std::ios_base::app); + if (printTime) { + clock_t start = clock(); + SYM.generateSymbolicEncodings(&o); + clock_t end = clock(); + double elapsed = double(end - start) / CLOCKS_PER_SEC; + printf("Time taken by normal generation of symbolic encodings is: " + "%.6f " + "seconds.\n", + elapsed); + } else { + SYM.generateSymbolicEncodings(&o); } - return 0; + o.close(); + } else if (collectIR) { + CollectIR cir(M); + std::ofstream o; + o.open(oname, std::ios_base::app); + cir.generateTriplets(o); + o.close(); + } + return 0; } diff --git a/src/Symbolic.cpp b/src/Symbolic.cpp index 49d376b5..971ffc61 100644 --- a/src/Symbolic.cpp +++ b/src/Symbolic.cpp @@ -26,229 +26,228 @@ using namespace IR2Vec; using abi::__cxa_demangle; Vector IR2Vec_Symbolic::getValue(std::string key) { - Vector vec; - if (opcMap.find(key) == opcMap.end()) - IR2VEC_DEBUG(errs() << "cannot find key in map : " << key << "\n"); - else - vec = opcMap[key]; - return vec; + Vector vec; + if (opcMap.find(key) == opcMap.end()) + IR2VEC_DEBUG(errs() << "cannot find key in map : " << key << "\n"); + else + vec = opcMap[key]; + return vec; } void IR2Vec_Symbolic::generateSymbolicEncodings(std::ostream *o) { - int noOfFunc = 0; - for (auto &f : M) { - if (!f.isDeclaration()) { - SmallVector funcStack; - auto tmp = func2Vec(f, funcStack); - funcVecMap[&f] = tmp; - if (level == 'f') { - res += updatedRes(tmp, &f, &M); - res += "\n"; - noOfFunc++; - } - - // else if (level == 'p') { - std::transform(pgmVector.begin(), pgmVector.end(), tmp.begin(), - pgmVector.begin(), std::plus()); - - // } - } + int noOfFunc = 0; + for (auto &f : M) { + if (!f.isDeclaration()) { + SmallVector funcStack; + auto tmp = func2Vec(f, funcStack); + funcVecMap[&f] = tmp; + if (level == 'f') { + res += updatedRes(tmp, &f, &M); + res += "\n"; + noOfFunc++; + } + + // else if (level == 'p') { + std::transform(pgmVector.begin(), pgmVector.end(), tmp.begin(), + pgmVector.begin(), std::plus()); + + // } } + } - IR2VEC_DEBUG(errs() << "Number of functions written = " << noOfFunc - << "\n"); + IR2VEC_DEBUG(errs() << "Number of functions written = " << noOfFunc << "\n"); - if (level == 'p') { - if (cls != -1) - res += std::to_string(cls) + "\t"; + if (level == 'p') { + if (cls != -1) + res += std::to_string(cls) + "\t"; - for (auto i : pgmVector) { - if ((i <= 0.0001 && i > 0) || (i < 0 && i >= -0.0001)) { - i = 0; - } - res += std::to_string(i) + "\t"; - } - res += "\n"; + for (auto i : pgmVector) { + if ((i <= 0.0001 && i > 0) || (i < 0 && i >= -0.0001)) { + i = 0; + } + res += std::to_string(i) + "\t"; } + res += "\n"; + } - if (o) - *o << res; + if (o) + *o << res; - IR2VEC_DEBUG(errs() << "class = " << cls << "\n"); - IR2VEC_DEBUG(errs() << "res = " << res); + IR2VEC_DEBUG(errs() << "class = " << cls << "\n"); + IR2VEC_DEBUG(errs() << "res = " << res); } // for generating symbolic encodings for specific function void IR2Vec_Symbolic::generateSymbolicEncodingsForFunction(std::ostream *o, std::string name) { - int noOfFunc = 0; - for (auto &f : M) { - auto Result = getActualName(&f); - if (!f.isDeclaration() && Result == name) { - Vector tmp; - SmallVector funcStack; - tmp = func2Vec(f, funcStack); - funcVecMap[&f] = tmp; - if (level == 'f') { - res += updatedRes(tmp, &f, &M); - res += "\n"; - noOfFunc++; - } - } + int noOfFunc = 0; + for (auto &f : M) { + auto Result = getActualName(&f); + if (!f.isDeclaration() && Result == name) { + Vector tmp; + SmallVector funcStack; + tmp = func2Vec(f, funcStack); + funcVecMap[&f] = tmp; + if (level == 'f') { + res += updatedRes(tmp, &f, &M); + res += "\n"; + noOfFunc++; + } } + } - if (o) - *o << res; + if (o) + *o << res; } Vector IR2Vec_Symbolic::func2Vec(Function &F, SmallVector &funcStack) { - auto It = funcVecMap.find(&F); - if (It != funcVecMap.end()) { - return It->second; - } - funcStack.push_back(&F); - Vector funcVector(DIM, 0); - ReversePostOrderTraversal RPOT(&F); - MapVector cumulativeScore; - - for (auto *b : RPOT) { - auto bbVector = bb2Vec(*b, funcStack); - - Vector weightedBBVector; - weightedBBVector = bbVector; - - std::transform(funcVector.begin(), funcVector.end(), - weightedBBVector.begin(), funcVector.begin(), - std::plus()); - } - - funcStack.pop_back(); - return funcVector; + auto It = funcVecMap.find(&F); + if (It != funcVecMap.end()) { + return It->second; + } + funcStack.push_back(&F); + Vector funcVector(DIM, 0); + ReversePostOrderTraversal RPOT(&F); + MapVector cumulativeScore; + + for (auto *b : RPOT) { + auto bbVector = bb2Vec(*b, funcStack); + + Vector weightedBBVector; + weightedBBVector = bbVector; + + std::transform(funcVector.begin(), funcVector.end(), + weightedBBVector.begin(), funcVector.begin(), + std::plus()); + } + + funcStack.pop_back(); + return funcVector; } Vector IR2Vec_Symbolic::bb2Vec(BasicBlock &B, SmallVector &funcStack) { - Vector bbVector(DIM, 0); - - for (auto &I : B) { - Vector instVector(DIM, 0); - auto vec = getValue(I.getOpcodeName()); - // if (isa(I)) { - // auto ci = dyn_cast(&I); - // // ci->dump(); - // Function *func = ci->getCalledFunction(); - // if (func) { - // // if(!func->isDeclaration()) - // // if(func != I.getParent()->getParent()) - // // errs() << func->getName() << "\t" << - // // I.getParent()->getParent()->getName() << "\n"; - // if (!func->isDeclaration() && - // std::find(funcStack.begin(), funcStack.end(), func) == - // funcStack.end()) { - // auto funcVec = func2Vec(*func, funcStack); - - // std::transform(vec.begin(), vec.end(), funcVec.begin(), - // vec.begin(), - // std::plus()); - // } - // } else { - // IR2VEC_DEBUG(I.dump()); - // IR2VEC_DEBUG(errs() << "==========================Function - // definition - // " - // "not found==================\n"); - // } - // } - scaleVector(vec, WO); - std::transform(instVector.begin(), instVector.end(), vec.begin(), - instVector.begin(), std::plus()); - auto type = I.getType(); - - if (type->isVoidTy()) { - vec = getValue("voidTy"); - } else if (type->isFloatingPointTy()) { - vec = getValue("floatTy"); - } else if (type->isIntegerTy()) { - vec = getValue("integerTy"); - } else if (type->isFunctionTy()) { - vec = getValue("functionTy"); - } else if (type->isStructTy()) { - vec = getValue("structTy"); - } else if (type->isArrayTy()) { - vec = getValue("arrayTy"); - } else if (type->isPointerTy()) { - vec = getValue("pointerTy"); - } else if (type->isVectorTy()) { - vec = getValue("vectorTy"); - } else if (type->isEmptyTy()) { - vec = getValue("emptyTy"); - } else if (type->isLabelTy()) { - vec = getValue("labelTy"); - } else if (type->isTokenTy()) { - vec = getValue("tokenTy"); - } else if (type->isMetadataTy()) { - vec = getValue("metadataTy"); - } else { - vec = getValue("unknownTy"); - } - - /*switch (I.getType()->getTypeID()) { - case 0: - vec = getValue("voidTy"); - break; - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - vec = getValue("floatTy"); - break; - case 11: - vec = getValue("integerTy"); - break; - case 12: - vec = getValue("functionTy"); - break; - case 13: - vec = getValue("structTy"); - break; - case 14: - vec = getValue("arrayTy"); - break; - case 15: - vec = getValue("pointerTy"); - break; - case 16: - vec = getValue("vectorTy"); - break; - default: - vec = getValue("unknownTy"); - }*/ - - scaleVector(vec, WT); - std::transform(instVector.begin(), instVector.end(), vec.begin(), - instVector.begin(), std::plus()); - for (unsigned i = 0; i < I.getNumOperands(); i++) { - Vector vec; - if (isa(I.getOperand(i))) { - vec = getValue("function"); - } else if (isa(I.getOperand(i)->getType())) { - vec = getValue("pointer"); - } else if (isa(I.getOperand(i))) { - vec = getValue("constant"); - } else { - vec = getValue("variable"); - } - scaleVector(vec, WA); - - std::transform(instVector.begin(), instVector.end(), vec.begin(), - instVector.begin(), std::plus()); - instVecMap[&I] = instVector; - } - std::transform(bbVector.begin(), bbVector.end(), instVector.begin(), - bbVector.begin(), std::plus()); + Vector bbVector(DIM, 0); + + for (auto &I : B) { + Vector instVector(DIM, 0); + auto vec = getValue(I.getOpcodeName()); + // if (isa(I)) { + // auto ci = dyn_cast(&I); + // // ci->dump(); + // Function *func = ci->getCalledFunction(); + // if (func) { + // // if(!func->isDeclaration()) + // // if(func != I.getParent()->getParent()) + // // errs() << func->getName() << "\t" << + // // I.getParent()->getParent()->getName() << "\n"; + // if (!func->isDeclaration() && + // std::find(funcStack.begin(), funcStack.end(), func) == + // funcStack.end()) { + // auto funcVec = func2Vec(*func, funcStack); + + // std::transform(vec.begin(), vec.end(), funcVec.begin(), + // vec.begin(), + // std::plus()); + // } + // } else { + // IR2VEC_DEBUG(I.dump()); + // IR2VEC_DEBUG(errs() << "==========================Function + // definition + // " + // "not found==================\n"); + // } + // } + scaleVector(vec, WO); + std::transform(instVector.begin(), instVector.end(), vec.begin(), + instVector.begin(), std::plus()); + auto type = I.getType(); + + if (type->isVoidTy()) { + vec = getValue("voidTy"); + } else if (type->isFloatingPointTy()) { + vec = getValue("floatTy"); + } else if (type->isIntegerTy()) { + vec = getValue("integerTy"); + } else if (type->isFunctionTy()) { + vec = getValue("functionTy"); + } else if (type->isStructTy()) { + vec = getValue("structTy"); + } else if (type->isArrayTy()) { + vec = getValue("arrayTy"); + } else if (type->isPointerTy()) { + vec = getValue("pointerTy"); + } else if (type->isVectorTy()) { + vec = getValue("vectorTy"); + } else if (type->isEmptyTy()) { + vec = getValue("emptyTy"); + } else if (type->isLabelTy()) { + vec = getValue("labelTy"); + } else if (type->isTokenTy()) { + vec = getValue("tokenTy"); + } else if (type->isMetadataTy()) { + vec = getValue("metadataTy"); + } else { + vec = getValue("unknownTy"); + } + + /*switch (I.getType()->getTypeID()) { + case 0: + vec = getValue("voidTy"); + break; + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + vec = getValue("floatTy"); + break; + case 11: + vec = getValue("integerTy"); + break; + case 12: + vec = getValue("functionTy"); + break; + case 13: + vec = getValue("structTy"); + break; + case 14: + vec = getValue("arrayTy"); + break; + case 15: + vec = getValue("pointerTy"); + break; + case 16: + vec = getValue("vectorTy"); + break; + default: + vec = getValue("unknownTy"); + }*/ + + scaleVector(vec, WT); + std::transform(instVector.begin(), instVector.end(), vec.begin(), + instVector.begin(), std::plus()); + for (unsigned i = 0; i < I.getNumOperands(); i++) { + Vector vec; + if (isa(I.getOperand(i))) { + vec = getValue("function"); + } else if (isa(I.getOperand(i)->getType())) { + vec = getValue("pointer"); + } else if (isa(I.getOperand(i))) { + vec = getValue("constant"); + } else { + vec = getValue("variable"); + } + scaleVector(vec, WA); + + std::transform(instVector.begin(), instVector.end(), vec.begin(), + instVector.begin(), std::plus()); + instVecMap[&I] = instVector; } - return bbVector; + std::transform(bbVector.begin(), bbVector.end(), instVector.begin(), + bbVector.begin(), std::plus()); + } + return bbVector; } diff --git a/src/include/CollectIR.h b/src/include/CollectIR.h index e40fe63b..028f8537 100644 --- a/src/include/CollectIR.h +++ b/src/include/CollectIR.h @@ -16,17 +16,17 @@ class CollectIR { - private: - void collectData(); - std::string res; - llvm::Module &M; +private: + void collectData(); + std::string res; + llvm::Module &M; - void traverseBasicBlock(llvm::BasicBlock &B); + void traverseBasicBlock(llvm::BasicBlock &B); - public: - CollectIR(std::unique_ptr &M) : M{*M} { res = ""; } +public: + CollectIR(std::unique_ptr &M) : M{*M} { res = ""; } - void generateTriplets(std::ostream &out); + void generateTriplets(std::ostream &out); }; #endif diff --git a/src/include/FlowAware.h b/src/include/FlowAware.h index 38fb2220..e2d12e6b 100644 --- a/src/include/FlowAware.h +++ b/src/include/FlowAware.h @@ -23,173 +23,172 @@ class IR2Vec_FA { - private: - llvm::Module &M; - std::string res; - IR2Vec::Vector pgmVector; - unsigned dataMissCounter; - unsigned cyclicCounter; - - llvm::SmallDenseMap memWriteOps; - llvm::SmallDenseMap livelinessMap; - llvm::SmallDenseMap memAccessOps; - - llvm::SmallMapVector - instVecMap; - llvm::SmallMapVector funcVecMap; - - llvm::SmallMapVector, 16> - funcCallMap; - - llvm::SmallMapVector, 16> - writeDefsMap; - - llvm::SmallMapVector, 16> - instReachingDefsMap; - - // Reverse instReachingDefsMap - llvm::SmallMapVector, 16> - reverseReachingDefsMap; - - llvm::SmallVector instSolvedBySolver; - - llvm::SmallVector, 10> - allSCCs; - - llvm::SmallMapVector, 16> - killMap; - - std::map> SCCAdjList; - - void getAllSCC(); - - IR2Vec::Vector getValue(std::string key); - void collectWriteDefsMap(llvm::Module &M); - void getTransitiveUse( - const llvm::Instruction *root, const llvm::Instruction *def, - llvm::SmallVector &visitedList, - llvm::SmallVector toAppend = {}); - llvm::SmallVector - getReachingDefs(const llvm::Instruction *, unsigned i); - - void solveSingleComponent( - const llvm::Instruction &I, - llvm::SmallMapVector - &instValMap); - void getPartialVec(const llvm::Instruction &I, - llvm::SmallMapVector &instValMap); - - void solveInsts(llvm::SmallMapVector &instValMap); - std::vector topoOrder(int size); - - void topoDFS(int vertex, std::vector &Visited, - std::vector &visitStack); - - void inst2Vec(const llvm::Instruction &I, - llvm::SmallVector &funcStack, - llvm::SmallMapVector memWriteOps; + llvm::SmallDenseMap livelinessMap; + llvm::SmallDenseMap memAccessOps; + + llvm::SmallMapVector + instVecMap; + llvm::SmallMapVector funcVecMap; + + llvm::SmallMapVector, 16> + funcCallMap; + + llvm::SmallMapVector, 16> + writeDefsMap; + + llvm::SmallMapVector, 16> + instReachingDefsMap; + + // Reverse instReachingDefsMap + llvm::SmallMapVector, 16> + reverseReachingDefsMap; + + llvm::SmallVector instSolvedBySolver; + + llvm::SmallVector, 10> + allSCCs; + + llvm::SmallMapVector, 16> + killMap; + + std::map> SCCAdjList; + + void getAllSCC(); + + IR2Vec::Vector getValue(std::string key); + void collectWriteDefsMap(llvm::Module &M); + void getTransitiveUse( + const llvm::Instruction *root, const llvm::Instruction *def, + llvm::SmallVector &visitedList, + llvm::SmallVector toAppend = {}); + llvm::SmallVector + getReachingDefs(const llvm::Instruction *, unsigned i); + + void solveSingleComponent( + const llvm::Instruction &I, + llvm::SmallMapVector + &instValMap); + void getPartialVec(const llvm::Instruction &I, + llvm::SmallMapVector &instValMap); + + void solveInsts(llvm::SmallMapVector &instValMap); - void - traverseRD(const llvm::Instruction *inst, - std::unordered_map &Visited, - llvm::SmallVector &timeStack); + std::vector topoOrder(int size); + + void topoDFS(int vertex, std::vector &Visited, + std::vector &visitStack); + + void inst2Vec(const llvm::Instruction &I, + llvm::SmallVector &funcStack, + llvm::SmallMapVector &instValMap); + void traverseRD(const llvm::Instruction *inst, + std::unordered_map &Visited, + llvm::SmallVector &timeStack); - void DFSUtil(const llvm::Instruction *inst, - std::unordered_map &Visited, - llvm::SmallVector &set); + void DFSUtil(const llvm::Instruction *inst, + std::unordered_map &Visited, + llvm::SmallVector &set); - void bb2Vec(llvm::BasicBlock &B, - llvm::SmallVector &funcStack); - IR2Vec::Vector func2Vec(llvm::Function &F, - llvm::SmallVector &funcStack); + void bb2Vec(llvm::BasicBlock &B, + llvm::SmallVector &funcStack); + IR2Vec::Vector func2Vec(llvm::Function &F, + llvm::SmallVector &funcStack); - bool isMemOp(llvm::StringRef opcode, unsigned &operand, - llvm::SmallDenseMap map); - std::string splitAndPipeFunctionName(std::string s); + bool isMemOp(llvm::StringRef opcode, unsigned &operand, + llvm::SmallDenseMap map); + std::string splitAndPipeFunctionName(std::string s); - void TransitiveReads(llvm::SmallVector &Killlist, - llvm::Instruction *Inst, llvm::BasicBlock *ParentBB); - llvm::SmallVector - createKilllist(llvm::Instruction *Arg, llvm::Instruction *writeInst); + void TransitiveReads(llvm::SmallVector &Killlist, + llvm::Instruction *Inst, llvm::BasicBlock *ParentBB); + llvm::SmallVector + createKilllist(llvm::Instruction *Arg, llvm::Instruction *writeInst); - // For Debugging - void print(IR2Vec::Vector t, unsigned pos) { llvm::outs() << t[pos]; } + // For Debugging + void print(IR2Vec::Vector t, unsigned pos) { llvm::outs() << t[pos]; } - void updateFuncVecMap( - llvm::Function *function, - llvm::SmallSet &visitedFunctions); + void updateFuncVecMap( + llvm::Function *function, + llvm::SmallSet &visitedFunctions); - void updateFuncVecMapWithCallee(const llvm::Function *function); + void updateFuncVecMapWithCallee(const llvm::Function *function); - public: - IR2Vec_FA(llvm::Module &M) : M{M} { +public: + IR2Vec_FA(llvm::Module &M) : M{M} { - pgmVector = IR2Vec::Vector(DIM, 0); - res = ""; - IR2Vec::collectDataFromVocab(opcMap); + pgmVector = IR2Vec::Vector(DIM, 0); + res = ""; + IR2Vec::collectDataFromVocab(opcMap); - memWriteOps.try_emplace("store", 1); - memWriteOps.try_emplace("cmpxchg", 0); - memWriteOps.try_emplace("atomicrmw", 0); + memWriteOps.try_emplace("store", 1); + memWriteOps.try_emplace("cmpxchg", 0); + memWriteOps.try_emplace("atomicrmw", 0); - memAccessOps.try_emplace("getelementptr", 0); - memAccessOps.try_emplace("load", 0); + memAccessOps.try_emplace("getelementptr", 0); + memAccessOps.try_emplace("load", 0); - dataMissCounter = 0; - cyclicCounter = 0; + dataMissCounter = 0; + cyclicCounter = 0; - collectWriteDefsMap(M); + collectWriteDefsMap(M); - llvm::CallGraph cg = llvm::CallGraph(M); + llvm::CallGraph cg = llvm::CallGraph(M); - for (auto callItr = cg.begin(); callItr != cg.end(); callItr++) { - if (callItr->first && !callItr->first->isDeclaration()) { - auto ParentFunc = callItr->first; - llvm::CallGraphNode *cgn = callItr->second.get(); - if (cgn) { + for (auto callItr = cg.begin(); callItr != cg.end(); callItr++) { + if (callItr->first && !callItr->first->isDeclaration()) { + auto ParentFunc = callItr->first; + llvm::CallGraphNode *cgn = callItr->second.get(); + if (cgn) { - for (auto It = cgn->begin(); It != cgn->end(); It++) { + for (auto It = cgn->begin(); It != cgn->end(); It++) { - auto func = It->second->getFunction(); - if (func && !func->isDeclaration()) { - funcCallMap[ParentFunc].push_back(func); - } - } - } + auto func = It->second->getFunction(); + if (func && !func->isDeclaration()) { + funcCallMap[ParentFunc].push_back(func); } + } } + } } + } - void generateFlowAwareEncodings(std::ostream *o = nullptr, - std::ostream *missCount = nullptr, - std::ostream *cyclicCount = nullptr); + void generateFlowAwareEncodings(std::ostream *o = nullptr, + std::ostream *missCount = nullptr, + std::ostream *cyclicCount = nullptr); - // newly added + // newly added - void generateFlowAwareEncodingsForFunction( - std::ostream *o = nullptr, std::string name = "", - std::ostream *missCount = nullptr, std::ostream *cyclicCount = nullptr); + void generateFlowAwareEncodingsForFunction( + std::ostream *o = nullptr, std::string name = "", + std::ostream *missCount = nullptr, std::ostream *cyclicCount = nullptr); - std::map opcMap; + std::map opcMap; - llvm::SmallMapVector - getInstVecMap() { - return instVecMap; - } + llvm::SmallMapVector + getInstVecMap() { + return instVecMap; + } - llvm::SmallMapVector - getFuncVecMap() { - return funcVecMap; - } + llvm::SmallMapVector + getFuncVecMap() { + return funcVecMap; + } - IR2Vec::Vector getProgramVector() { return pgmVector; } + IR2Vec::Vector getProgramVector() { return pgmVector; } }; #endif diff --git a/src/include/IR2Vec.h b/src/include/IR2Vec.h index bd696e88..1cdb4b83 100644 --- a/src/include/IR2Vec.h +++ b/src/include/IR2Vec.h @@ -19,52 +19,51 @@ using Vector = llvm::SmallVector; enum IR2VecMode { FlowAware, Symbolic }; class Embeddings { - int generateEncodings(llvm::Module &M, IR2VecMode mode, std::string vocab, - char level = '\0', std::string funcName = "", - std::ostream *o = nullptr, int cls = -1, float WO = 1, - float WA = 0.2, float WT = 0.5); + int generateEncodings(llvm::Module &M, IR2VecMode mode, std::string vocab, + char level = '\0', std::string funcName = "", + std::ostream *o = nullptr, int cls = -1, float WO = 1, + float WA = 0.2, float WT = 0.5); - llvm::SmallMapVector instVecMap; - llvm::SmallMapVector funcVecMap; - Vector pgmVector; + llvm::SmallMapVector instVecMap; + llvm::SmallMapVector funcVecMap; + Vector pgmVector; - public: - Embeddings() = default; - Embeddings(llvm::Module &M, IR2VecMode mode, std::string vocab, - std::string funcName = "", float WO = 1, float WA = 0.2, - float WT = 0.5) { - generateEncodings(M, mode, vocab, '\0', funcName, nullptr, -1, WO, WA, - WT); - } +public: + Embeddings() = default; + Embeddings(llvm::Module &M, IR2VecMode mode, std::string vocab, + std::string funcName = "", float WO = 1, float WA = 0.2, + float WT = 0.5) { + generateEncodings(M, mode, vocab, '\0', funcName, nullptr, -1, WO, WA, WT); + } - // Use this constructor if the representations ought to be written to a - // file. Analogous to the command line options that are being used in IR2Vec - // binary. - Embeddings(llvm::Module &M, IR2VecMode mode, std::string vocab, char level, - std::ostream *o, std::string funcName = "",float WO = 1, - float WA = 0.2, float WT = 0.5) { - generateEncodings(M, mode, vocab, level, funcName, o, -1, WO, WA, WT); - } + // Use this constructor if the representations ought to be written to a + // file. Analogous to the command line options that are being used in IR2Vec + // binary. + Embeddings(llvm::Module &M, IR2VecMode mode, std::string vocab, char level, + std::ostream *o, std::string funcName = "", float WO = 1, + float WA = 0.2, float WT = 0.5) { + generateEncodings(M, mode, vocab, level, funcName, o, -1, WO, WA, WT); + } - // Returns a map containing instructions and the corresponding vector - // representations for a given module corresponding to the IR2VecMode and - // other configurations that is set in constructor - llvm::SmallMapVector & - getInstVecMap() { - return instVecMap; - } + // Returns a map containing instructions and the corresponding vector + // representations for a given module corresponding to the IR2VecMode and + // other configurations that is set in constructor + llvm::SmallMapVector & + getInstVecMap() { + return instVecMap; + } - // Returns a map containing functions and the corresponding vector - // representations for a given module corresponding to the IR2VecMode and - // other configurations that is set in constructor - llvm::SmallMapVector & - getFunctionVecMap() { - return funcVecMap; - } + // Returns a map containing functions and the corresponding vector + // representations for a given module corresponding to the IR2VecMode and + // other configurations that is set in constructor + llvm::SmallMapVector & + getFunctionVecMap() { + return funcVecMap; + } - // Returns the program vector for a module corresponding to the IR2VecMode - // and other configurations that is set in constructor - Vector &getProgramVector() { return pgmVector; } + // Returns the program vector for a module corresponding to the IR2VecMode + // and other configurations that is set in constructor + Vector &getProgramVector() { return pgmVector; } }; } // namespace IR2Vec diff --git a/src/include/Symbolic.h b/src/include/Symbolic.h index 93142f7b..554a531d 100644 --- a/src/include/Symbolic.h +++ b/src/include/Symbolic.h @@ -20,42 +20,42 @@ class IR2Vec_Symbolic { - private: - llvm::Module &M; - IR2Vec::Vector pgmVector; - - IR2Vec::Vector getValue(std::string key); - IR2Vec::Vector bb2Vec(llvm::BasicBlock &B, +private: + llvm::Module &M; + IR2Vec::Vector pgmVector; + + IR2Vec::Vector getValue(std::string key); + IR2Vec::Vector bb2Vec(llvm::BasicBlock &B, + llvm::SmallVector &funcStack); + IR2Vec::Vector func2Vec(llvm::Function &F, llvm::SmallVector &funcStack); - IR2Vec::Vector func2Vec(llvm::Function &F, - llvm::SmallVector &funcStack); - std::string res; - llvm::SmallMapVector funcVecMap; - llvm::SmallMapVector - instVecMap; - std::map opcMap; - - public: - IR2Vec_Symbolic(llvm::Module &M) : M{M} { - pgmVector = IR2Vec::Vector(DIM, 0); - res = ""; - IR2Vec::collectDataFromVocab(opcMap); - } - - void generateSymbolicEncodings(std::ostream *o = nullptr); - void generateSymbolicEncodingsForFunction(std::ostream *o = nullptr, - std::string name = ""); - llvm::SmallMapVector - getInstVecMap() { - return instVecMap; - } - - llvm::SmallMapVector - getFuncVecMap() { - return funcVecMap; - } - - IR2Vec::Vector getProgramVector() { return pgmVector; } + std::string res; + llvm::SmallMapVector funcVecMap; + llvm::SmallMapVector + instVecMap; + std::map opcMap; + +public: + IR2Vec_Symbolic(llvm::Module &M) : M{M} { + pgmVector = IR2Vec::Vector(DIM, 0); + res = ""; + IR2Vec::collectDataFromVocab(opcMap); + } + + void generateSymbolicEncodings(std::ostream *o = nullptr); + void generateSymbolicEncodingsForFunction(std::ostream *o = nullptr, + std::string name = ""); + llvm::SmallMapVector + getInstVecMap() { + return instVecMap; + } + + llvm::SmallMapVector + getFuncVecMap() { + return funcVecMap; + } + + IR2Vec::Vector getProgramVector() { return pgmVector; } }; #endif diff --git a/src/include/VectorSolver.h b/src/include/VectorSolver.h index 2b165621..4ae901e2 100644 --- a/src/include/VectorSolver.h +++ b/src/include/VectorSolver.h @@ -19,45 +19,45 @@ using namespace llvm; typedef std::vector> matrix; MatrixXd calculate(MatrixXd A, MatrixXd B) { - if (A.determinant() != 0) { - return A.fullPivHouseholderQr().solve(B); - } else { - // To-Do: perturb probabilities - llvm_unreachable("inconsistent/infinitely many solutions"); - } + if (A.determinant() != 0) { + return A.fullPivHouseholderQr().solve(B); + } else { + // To-Do: perturb probabilities + llvm_unreachable("inconsistent/infinitely many solutions"); + } } MatrixXd formMatrix(std::vector> a, int r, int l) { - MatrixXd M(r, l); - for (int i = 0; i < r; i++) - M.row(i) = VectorXd::Map(&a[i][0], a[i].size()); + MatrixXd M(r, l); + for (int i = 0; i < r; i++) + M.row(i) = VectorXd::Map(&a[i][0], a[i].size()); - return M; + return M; } matrix solve(matrix A, matrix B) { - int r = A.size(); - int c = A[0].size(); - MatrixXd mA(r, c); - mA = formMatrix(A, r, c); - - r = B.size(); - c = B[0].size(); - MatrixXd mB(r, c); - mB = formMatrix(B, r, c); - - r = A.size(); - MatrixXd x(r, c); - x = calculate(mA, mB); - std::vector> raw_data; - // raw_data.resize(x.rows()); - for (unsigned i = 0; i < x.rows(); i++) { - std::vector tmp; - tmp.resize(x.cols()); - VectorXd::Map(&tmp[0], x.cols()) = x.row(i); - raw_data.push_back(tmp); - } - return raw_data; + int r = A.size(); + int c = A[0].size(); + MatrixXd mA(r, c); + mA = formMatrix(A, r, c); + + r = B.size(); + c = B[0].size(); + MatrixXd mB(r, c); + mB = formMatrix(B, r, c); + + r = A.size(); + MatrixXd x(r, c); + x = calculate(mA, mB); + std::vector> raw_data; + // raw_data.resize(x.rows()); + for (unsigned i = 0; i < x.rows(); i++) { + std::vector tmp; + tmp.resize(x.cols()); + VectorXd::Map(&tmp[0], x.cols()) = x.row(i); + raw_data.push_back(tmp); + } + return raw_data; } #endif diff --git a/src/include/utils.h b/src/include/utils.h index 5d9f72ef..7bed22f2 100644 --- a/src/include/utils.h +++ b/src/include/utils.h @@ -20,11 +20,11 @@ namespace IR2Vec { #define IR2VEC_DEBUG(X) \ - ({ \ - if (IR2Vec::debug) { \ - X; \ - } \ - }) + ({ \ + if (IR2Vec::debug) { \ + X; \ + } \ + }) #define DIM 300 using Vector = llvm::SmallVector; diff --git a/src/libIR2Vec.cpp b/src/libIR2Vec.cpp index 9d231547..5c6d09b2 100644 --- a/src/libIR2Vec.cpp +++ b/src/libIR2Vec.cpp @@ -19,37 +19,37 @@ int IR2Vec::Embeddings::generateEncodings(llvm::Module &M, std::string funcName, std::ostream *o, int cls, float WO, float WA, float WT) { - IR2Vec::vocab = vocab; - IR2Vec::level = level; - IR2Vec::cls = cls; - IR2Vec::WO = WO; - IR2Vec::WA = WA; - IR2Vec::WT = WT; - IR2Vec::funcName = funcName; + IR2Vec::vocab = vocab; + IR2Vec::level = level; + IR2Vec::cls = cls; + IR2Vec::WO = WO; + IR2Vec::WA = WA; + IR2Vec::WT = WT; + IR2Vec::funcName = funcName; - if (mode == IR2Vec::IR2VecMode::FlowAware && !funcName.empty()) { - IR2Vec_FA FA(M); - FA.generateFlowAwareEncodingsForFunction(o, funcName); - instVecMap = FA.getInstVecMap(); - funcVecMap = FA.getFuncVecMap(); - } else if (mode == IR2Vec::IR2VecMode::FlowAware) { - IR2Vec_FA FA(M); - FA.generateFlowAwareEncodings(o); - instVecMap = FA.getInstVecMap(); - funcVecMap = FA.getFuncVecMap(); - pgmVector = FA.getProgramVector(); - } else if (mode == IR2Vec::IR2VecMode::Symbolic && !funcName.empty()) { - IR2Vec_Symbolic SYM(M); - SYM.generateSymbolicEncodingsForFunction(0, funcName); - instVecMap = SYM.getInstVecMap(); - funcVecMap = SYM.getFuncVecMap(); - } else if (mode == IR2Vec::IR2VecMode::Symbolic) { - IR2Vec_Symbolic SYM(M); - SYM.generateSymbolicEncodings(o); - instVecMap = SYM.getInstVecMap(); - funcVecMap = SYM.getFuncVecMap(); - pgmVector = SYM.getProgramVector(); - } + if (mode == IR2Vec::IR2VecMode::FlowAware && !funcName.empty()) { + IR2Vec_FA FA(M); + FA.generateFlowAwareEncodingsForFunction(o, funcName); + instVecMap = FA.getInstVecMap(); + funcVecMap = FA.getFuncVecMap(); + } else if (mode == IR2Vec::IR2VecMode::FlowAware) { + IR2Vec_FA FA(M); + FA.generateFlowAwareEncodings(o); + instVecMap = FA.getInstVecMap(); + funcVecMap = FA.getFuncVecMap(); + pgmVector = FA.getProgramVector(); + } else if (mode == IR2Vec::IR2VecMode::Symbolic && !funcName.empty()) { + IR2Vec_Symbolic SYM(M); + SYM.generateSymbolicEncodingsForFunction(0, funcName); + instVecMap = SYM.getInstVecMap(); + funcVecMap = SYM.getFuncVecMap(); + } else if (mode == IR2Vec::IR2VecMode::Symbolic) { + IR2Vec_Symbolic SYM(M); + SYM.generateSymbolicEncodings(o); + instVecMap = SYM.getInstVecMap(); + funcVecMap = SYM.getFuncVecMap(); + pgmVector = SYM.getProgramVector(); + } - return 0; + return 0; } diff --git a/src/test-suite/PE-benchmarks/Find_the_closest_pair_from_two_sorted_arrays.cpp b/src/test-suite/PE-benchmarks/Find_the_closest_pair_from_two_sorted_arrays.cpp index 75d450d5..e921797f 100644 --- a/src/test-suite/PE-benchmarks/Find_the_closest_pair_from_two_sorted_arrays.cpp +++ b/src/test-suite/PE-benchmarks/Find_the_closest_pair_from_two_sorted_arrays.cpp @@ -9,44 +9,43 @@ using namespace std; // and x is given number. This function prints the pair from // both arrays such that the sum of the pair is closest to x. void printClosest(int ar1[], int ar2[], int m, int n, int x) { - // Initialize the diff between pair sum and x. - int diff = INT_MAX; + // Initialize the diff between pair sum and x. + int diff = INT_MAX; - // res_l and res_r are result indexes from ar1[] and ar2[] - // respectively - int res_l, res_r; + // res_l and res_r are result indexes from ar1[] and ar2[] + // respectively + int res_l, res_r; - // Start from left side of ar1[] and right side of ar2[] - int l = 0, r = n - 1; - while (l < m && r >= 0) { - // If this pair is closer to x than the previously - // found closest, then update res_l, res_r and diff - if (abs(ar1[l] + ar2[r] - x) < diff) { - res_l = l; - res_r = r; - diff = abs(ar1[l] + ar2[r] - x); - } - - // If sum of this pair is more than x, move to smaller - // side - if (ar1[l] + ar2[r] > x) - r--; - else // move to the greater side - l++; + // Start from left side of ar1[] and right side of ar2[] + int l = 0, r = n - 1; + while (l < m && r >= 0) { + // If this pair is closer to x than the previously + // found closest, then update res_l, res_r and diff + if (abs(ar1[l] + ar2[r] - x) < diff) { + res_l = l; + res_r = r; + diff = abs(ar1[l] + ar2[r] - x); } - // Print the result - cout << "The closest pair is [" << ar1[res_l] << ", " << ar2[res_r] - << "] \n"; + // If sum of this pair is more than x, move to smaller + // side + if (ar1[l] + ar2[r] > x) + r--; + else // move to the greater side + l++; + } + + // Print the result + cout << "The closest pair is [" << ar1[res_l] << ", " << ar2[res_r] << "] \n"; } // Driver program to test above functions int main() { - int ar1[] = {1, 4, 5, 7}; - int ar2[] = {10, 20, 30, 40}; - int m = sizeof(ar1) / sizeof(ar1[0]); - int n = sizeof(ar2) / sizeof(ar2[0]); - int x = 38; - printClosest(ar1, ar2, m, n, x); - return 0; + int ar1[] = {1, 4, 5, 7}; + int ar2[] = {10, 20, 30, 40}; + int m = sizeof(ar1) / sizeof(ar1[0]); + int n = sizeof(ar2) / sizeof(ar2[0]); + int x = 38; + printClosest(ar1, ar2, m, n, x); + return 0; } diff --git a/src/test-suite/PE-benchmarks/Iterative_QuickSort.cpp b/src/test-suite/PE-benchmarks/Iterative_QuickSort.cpp index df9dabf4..5d90a58e 100644 --- a/src/test-suite/PE-benchmarks/Iterative_QuickSort.cpp +++ b/src/test-suite/PE-benchmarks/Iterative_QuickSort.cpp @@ -4,80 +4,80 @@ using namespace std; // A utility function to swap two elements void swap(int *a, int *b) { - int t = *a; - *a = *b; - *b = t; + int t = *a; + *a = *b; + *b = t; } /* This function is same in both iterative and recursive*/ int partition(int arr[], int l, int h) { - int x = arr[h]; - int i = (l - 1); + int x = arr[h]; + int i = (l - 1); - for (int j = l; j <= h - 1; j++) { - if (arr[j] <= x) { - i++; - swap(&arr[i], &arr[j]); - } + for (int j = l; j <= h - 1; j++) { + if (arr[j] <= x) { + i++; + swap(&arr[i], &arr[j]); } - swap(&arr[i + 1], &arr[h]); - return (i + 1); + } + swap(&arr[i + 1], &arr[h]); + return (i + 1); } /* A[] --> Array to be sorted, l --> Starting index, h --> Ending index */ void quickSortIterative(int arr[], int l, int h) { - // Create an auxiliary stack - int stack[h - l + 1]; + // Create an auxiliary stack + int stack[h - l + 1]; - // initialize top of stack - int top = -1; + // initialize top of stack + int top = -1; - // push initial values of l and h to stack - stack[++top] = l; - stack[++top] = h; + // push initial values of l and h to stack + stack[++top] = l; + stack[++top] = h; - // Keep popping from stack while is not empty - while (top >= 0) { - // Pop h and l - h = stack[top--]; - l = stack[top--]; + // Keep popping from stack while is not empty + while (top >= 0) { + // Pop h and l + h = stack[top--]; + l = stack[top--]; - // Set pivot element at its correct position - // in sorted array - int p = partition(arr, l, h); + // Set pivot element at its correct position + // in sorted array + int p = partition(arr, l, h); - // If there are elements on left side of pivot, - // then push left side to stack - if (p - 1 > l) { - stack[++top] = l; - stack[++top] = p - 1; - } + // If there are elements on left side of pivot, + // then push left side to stack + if (p - 1 > l) { + stack[++top] = l; + stack[++top] = p - 1; + } - // If there are elements on right side of pivot, - // then push right side to stack - if (p + 1 < h) { - stack[++top] = p + 1; - stack[++top] = h; - } + // If there are elements on right side of pivot, + // then push right side to stack + if (p + 1 < h) { + stack[++top] = p + 1; + stack[++top] = h; } + } } // A utility function to print contents of arr void printArr(int arr[], int n) { - int i; - for (i = 0; i < n; ++i) - cout << arr[i] << " "; + int i; + for (i = 0; i < n; ++i) + cout << arr[i] << " "; } // Driver code int main() { - int arr[] = {4, 3, 5, 2, 1, 3, 2, 3}; - int n = sizeof(arr) / sizeof(*arr); - quickSortIterative(arr, 0, n - 1); - printArr(arr, n); - return 0; + int arr[] = {4, 3, 5, 2, 1, 3, 2, 3}; + int n = sizeof(arr) / sizeof(*arr); + quickSortIterative(arr, 0, n - 1); + printArr(arr, n); + return 0; } // This is code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/Nearly_sorted_Algo.cpp b/src/test-suite/PE-benchmarks/Nearly_sorted_Algo.cpp index cbe6c5da..8c0794ae 100644 --- a/src/test-suite/PE-benchmarks/Nearly_sorted_Algo.cpp +++ b/src/test-suite/PE-benchmarks/Nearly_sorted_Algo.cpp @@ -6,42 +6,42 @@ using namespace std; // is k away from its target position, sorts the // array in O(nLogk) time. int sortK(int arr[], int n, int k) { - // Insert first k+1 items in a priority queue (or min heap) - //(A O(k) operation). We assume, k < n. - priority_queue, greater> pq(arr, arr + k + 1); + // Insert first k+1 items in a priority queue (or min heap) + //(A O(k) operation). We assume, k < n. + priority_queue, greater> pq(arr, arr + k + 1); - // i is index for remaining elements in arr[] and index - // is target index of for current minimum element in - // Min Heapm 'hp'. - int index = 0; - for (int i = k + 1; i < n; i++) { - arr[index++] = pq.top(); - pq.pop(); - pq.push(arr[i]); - } + // i is index for remaining elements in arr[] and index + // is target index of for current minimum element in + // Min Heapm 'hp'. + int index = 0; + for (int i = k + 1; i < n; i++) { + arr[index++] = pq.top(); + pq.pop(); + pq.push(arr[i]); + } - while (pq.empty() == false) { - arr[index++] = pq.top(); - pq.pop(); - } + while (pq.empty() == false) { + arr[index++] = pq.top(); + pq.pop(); + } } // A utility function to print array elements void printArray(int arr[], int size) { - for (int i = 0; i < size; i++) - cout << arr[i] << " "; - cout << endl; + for (int i = 0; i < size; i++) + cout << arr[i] << " "; + cout << endl; } // Driver program to test above functions int main() { - int k = 3; - int arr[] = {2, 6, 3, 12, 56, 8}; - int n = sizeof(arr) / sizeof(arr[0]); - sortK(arr, n, k); + int k = 3; + int arr[] = {2, 6, 3, 12, 56, 8}; + int n = sizeof(arr) / sizeof(arr[0]); + sortK(arr, n, k); - cout << "Following is sorted arrayn"; - printArray(arr, n); + cout << "Following is sorted arrayn"; + printArray(arr, n); - return 0; + return 0; } diff --git a/src/test-suite/PE-benchmarks/aho-corasick-algorithm.cpp b/src/test-suite/PE-benchmarks/aho-corasick-algorithm.cpp index 68aad9af..0eb95ea4 100644 --- a/src/test-suite/PE-benchmarks/aho-corasick-algorithm.cpp +++ b/src/test-suite/PE-benchmarks/aho-corasick-algorithm.cpp @@ -28,99 +28,99 @@ int g[MAXS][MAXC]; // Returns the number of states that the built machine has. // States are numbered 0 up to the return value - 1, inclusive. int buildMatchingMachine(string arr[], int k) { - // Initialize all values in output function as 0. - memset(out, 0, sizeof out); + // Initialize all values in output function as 0. + memset(out, 0, sizeof out); - // Initialize all values in goto function as -1. - memset(g, -1, sizeof g); + // Initialize all values in goto function as -1. + memset(g, -1, sizeof g); - // Initially, we just have the 0 state - int states = 1; + // Initially, we just have the 0 state + int states = 1; - // Construct values for goto function, i.e., fill g[][] - // This is same as building a Trie for arr[] - for (int i = 0; i < k; ++i) { - const string &word = arr[i]; - int currentState = 0; - - // Insert all characters of current word in arr[] - for (int j = 0; j < word.size(); ++j) { - int ch = word[j] - 'a'; + // Construct values for goto function, i.e., fill g[][] + // This is same as building a Trie for arr[] + for (int i = 0; i < k; ++i) { + const string &word = arr[i]; + int currentState = 0; - // Allocate a new node (create a new state) if a - // node for ch doesn't exist. - if (g[currentState][ch] == -1) - g[currentState][ch] = states++; + // Insert all characters of current word in arr[] + for (int j = 0; j < word.size(); ++j) { + int ch = word[j] - 'a'; - currentState = g[currentState][ch]; - } + // Allocate a new node (create a new state) if a + // node for ch doesn't exist. + if (g[currentState][ch] == -1) + g[currentState][ch] = states++; - // Add current word in output function - out[currentState] |= (1 << i); + currentState = g[currentState][ch]; } - // For all characters which don't have an edge from - // root (or state 0) in Trie, add a goto edge to state - // 0 itself - for (int ch = 0; ch < MAXC; ++ch) - if (g[0][ch] == -1) - g[0][ch] = 0; - - // Now, let's build the failure function - - // Initialize values in fail function - memset(f, -1, sizeof f); - - // Failure function is computed in breadth first order - // using a queue - queue q; - - // Iterate over every possible input - for (int ch = 0; ch < MAXC; ++ch) { - // All nodes of depth 1 have failure function value - // as 0. For example, in above diagram we move to 0 - // from states 1 and 3. - if (g[0][ch] != 0) { - f[g[0][ch]] = 0; - q.push(g[0][ch]); - } + // Add current word in output function + out[currentState] |= (1 << i); + } + + // For all characters which don't have an edge from + // root (or state 0) in Trie, add a goto edge to state + // 0 itself + for (int ch = 0; ch < MAXC; ++ch) + if (g[0][ch] == -1) + g[0][ch] = 0; + + // Now, let's build the failure function + + // Initialize values in fail function + memset(f, -1, sizeof f); + + // Failure function is computed in breadth first order + // using a queue + queue q; + + // Iterate over every possible input + for (int ch = 0; ch < MAXC; ++ch) { + // All nodes of depth 1 have failure function value + // as 0. For example, in above diagram we move to 0 + // from states 1 and 3. + if (g[0][ch] != 0) { + f[g[0][ch]] = 0; + q.push(g[0][ch]); } - - // Now queue has states 1 and 3 - while (q.size()) { - // Remove the front state from queue - int state = q.front(); - q.pop(); - - // For the removed state, find failure function for - // all those characters for which goto function is - // not defined. - for (int ch = 0; ch <= MAXC; ++ch) { - // If goto function is defined for character 'ch' - // and 'state' - if (g[state][ch] != -1) { - // Find failure state of removed state - int failure = f[state]; - - // Find the deepest node labeled by proper - // suffix of string from root to current - // state. - while (g[failure][ch] == -1) - failure = f[failure]; - - failure = g[failure][ch]; - f[g[state][ch]] = failure; - - // Merge output values - out[g[state][ch]] |= out[failure]; - - // Insert the next level node (of Trie) in Queue - q.push(g[state][ch]); - } - } + } + + // Now queue has states 1 and 3 + while (q.size()) { + // Remove the front state from queue + int state = q.front(); + q.pop(); + + // For the removed state, find failure function for + // all those characters for which goto function is + // not defined. + for (int ch = 0; ch <= MAXC; ++ch) { + // If goto function is defined for character 'ch' + // and 'state' + if (g[state][ch] != -1) { + // Find failure state of removed state + int failure = f[state]; + + // Find the deepest node labeled by proper + // suffix of string from root to current + // state. + while (g[failure][ch] == -1) + failure = f[failure]; + + failure = g[failure][ch]; + f[g[state][ch]] = failure; + + // Merge output values + out[g[state][ch]] |= out[failure]; + + // Insert the next level node (of Trie) in Queue + q.push(g[state][ch]); + } } + } - return states; + return states; } // Returns the next state the machine will transition to using goto @@ -129,53 +129,53 @@ int buildMatchingMachine(string arr[], int k) { // 0 and the number of states - 1, inclusive. // nextInput - The next character that enters into the machine. int findNextState(int currentState, char nextInput) { - int answer = currentState; - int ch = nextInput - 'a'; + int answer = currentState; + int ch = nextInput - 'a'; - // If goto is not defined, use failure function - while (g[answer][ch] == -1) - answer = f[answer]; + // If goto is not defined, use failure function + while (g[answer][ch] == -1) + answer = f[answer]; - return g[answer][ch]; + return g[answer][ch]; } // This function finds all occurrences of all array words // in text. void searchWords(string arr[], int k, string text) { - // Preprocess patterns. - // Build machine with goto, failure and output functions - buildMatchingMachine(arr, k); - - // Initialize current state - int currentState = 0; - - // Traverse the text through the nuilt machine to find - // all occurrences of words in arr[] - for (int i = 0; i < text.size(); ++i) { - currentState = findNextState(currentState, text[i]); - - // If match not found, move to next state - if (out[currentState] == 0) - continue; - - // Match found, print all matching words of arr[] - // using output function. - for (int j = 0; j < k; ++j) { - if (out[currentState] & (1 << j)) { - cout << "Word " << arr[j] << " appears from " - << i - arr[j].size() + 1 << " to " << i << endl; - } - } + // Preprocess patterns. + // Build machine with goto, failure and output functions + buildMatchingMachine(arr, k); + + // Initialize current state + int currentState = 0; + + // Traverse the text through the nuilt machine to find + // all occurrences of words in arr[] + for (int i = 0; i < text.size(); ++i) { + currentState = findNextState(currentState, text[i]); + + // If match not found, move to next state + if (out[currentState] == 0) + continue; + + // Match found, print all matching words of arr[] + // using output function. + for (int j = 0; j < k; ++j) { + if (out[currentState] & (1 << j)) { + cout << "Word " << arr[j] << " appears from " << i - arr[j].size() + 1 + << " to " << i << endl; + } } + } } // Driver program to test above int main() { - string arr[] = {"he", "she", "hers", "his"}; - string text = "ahishers"; - int k = sizeof(arr) / sizeof(arr[0]); + string arr[] = {"he", "she", "hers", "his"}; + string text = "ahishers"; + int k = sizeof(arr) / sizeof(arr[0]); - searchWords(arr, k, text); + searchWords(arr, k, text); - return 0; + return 0; } diff --git a/src/test-suite/PE-benchmarks/anagram-substring-search-search-permutations.cpp b/src/test-suite/PE-benchmarks/anagram-substring-search-search-permutations.cpp index 22aacd92..1cc505f6 100644 --- a/src/test-suite/PE-benchmarks/anagram-substring-search-search-permutations.cpp +++ b/src/test-suite/PE-benchmarks/anagram-substring-search-search-permutations.cpp @@ -7,47 +7,47 @@ using namespace std; // This function returns true if contents of arr1[] and arr2[] // are same, otherwise false. bool compare(char arr1[], char arr2[]) { - for (int i = 0; i < MAX; i++) - if (arr1[i] != arr2[i]) - return false; - return true; + for (int i = 0; i < MAX; i++) + if (arr1[i] != arr2[i]) + return false; + return true; } // This function search for all permutations of pat[] in txt[] void search(char *pat, char *txt) { - int M = strlen(pat), N = strlen(txt); - - // countP[]: Store count of all characters of pattern - // countTW[]: Store count of current window of text - char countP[MAX] = {0}, countTW[MAX] = {0}; - for (int i = 0; i < M; i++) { - (countP[pat[i]])++; - (countTW[txt[i]])++; - } - - // Traverse through remaining characters of pattern - for (int i = M; i < N; i++) { - // Compare counts of current window of text with - // counts of pattern[] - if (compare(countP, countTW)) - cout << "Found at Index " << (i - M) << endl; - - // Add current character to current window - (countTW[txt[i]])++; - - // Remove the first character of previous window - countTW[txt[i - M]]--; - } - - // Check for the last window in text + int M = strlen(pat), N = strlen(txt); + + // countP[]: Store count of all characters of pattern + // countTW[]: Store count of current window of text + char countP[MAX] = {0}, countTW[MAX] = {0}; + for (int i = 0; i < M; i++) { + (countP[pat[i]])++; + (countTW[txt[i]])++; + } + + // Traverse through remaining characters of pattern + for (int i = M; i < N; i++) { + // Compare counts of current window of text with + // counts of pattern[] if (compare(countP, countTW)) - cout << "Found at Index " << (N - M) << endl; + cout << "Found at Index " << (i - M) << endl; + + // Add current character to current window + (countTW[txt[i]])++; + + // Remove the first character of previous window + countTW[txt[i - M]]--; + } + + // Check for the last window in text + if (compare(countP, countTW)) + cout << "Found at Index " << (N - M) << endl; } /* Driver program to test above function */ int main() { - char txt[] = "BACDGABCDA"; - char pat[] = "ABCD"; - search(pat, txt); - return 0; + char txt[] = "BACDGABCDA"; + char pat[] = "ABCD"; + search(pat, txt); + return 0; } diff --git a/src/test-suite/PE-benchmarks/bellman-ford-algorithm.cpp b/src/test-suite/PE-benchmarks/bellman-ford-algorithm.cpp index 516f30e5..aa76da91 100644 --- a/src/test-suite/PE-benchmarks/bellman-ford-algorithm.cpp +++ b/src/test-suite/PE-benchmarks/bellman-ford-algorithm.cpp @@ -4,129 +4,129 @@ // a structure to represent a weighted edge in graph struct Edge { - int src, dest, weight; + int src, dest, weight; }; // a structure to represent a connected, directed and // weighted graph struct Graph { - // V-> Number of vertices, E-> Number of edges - int V, E; + // V-> Number of vertices, E-> Number of edges + int V, E; - // graph is represented as an array of edges. - struct Edge *edge; + // graph is represented as an array of edges. + struct Edge *edge; }; // Creates a graph with V vertices and E edges struct Graph *createGraph(int V, int E) { - struct Graph *graph = new Graph; - graph->V = V; - graph->E = E; - graph->edge = new Edge[E]; - return graph; + struct Graph *graph = new Graph; + graph->V = V; + graph->E = E; + graph->edge = new Edge[E]; + return graph; } // A utility function used to print the solution void printArr(int dist[], int n) { - printf("Vertex Distance from Source\n"); - for (int i = 0; i < n; ++i) - printf("%d \t\t %d\n", i, dist[i]); + printf("Vertex Distance from Source\n"); + for (int i = 0; i < n; ++i) + printf("%d \t\t %d\n", i, dist[i]); } // The main function that finds shortest distances from src to // all other vertices using Bellman-Ford algorithm. The function // also detects negative weight cycle void BellmanFord(struct Graph *graph, int src) { - int V = graph->V; - int E = graph->E; - int dist[V]; - - // Step 1: Initialize distances from src to all other vertices - // as INFINITE - for (int i = 0; i < V; i++) - dist[i] = INT_MAX; - dist[src] = 0; - - // Step 2: Relax all edges |V| - 1 times. A simple shortest - // path from src to any other vertex can have at-most |V| - 1 - // edges - for (int i = 1; i <= V - 1; i++) { - for (int j = 0; j < E; j++) { - int u = graph->edge[j].src; - int v = graph->edge[j].dest; - int weight = graph->edge[j].weight; - if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) - dist[v] = dist[u] + weight; - } + int V = graph->V; + int E = graph->E; + int dist[V]; + + // Step 1: Initialize distances from src to all other vertices + // as INFINITE + for (int i = 0; i < V; i++) + dist[i] = INT_MAX; + dist[src] = 0; + + // Step 2: Relax all edges |V| - 1 times. A simple shortest + // path from src to any other vertex can have at-most |V| - 1 + // edges + for (int i = 1; i <= V - 1; i++) { + for (int j = 0; j < E; j++) { + int u = graph->edge[j].src; + int v = graph->edge[j].dest; + int weight = graph->edge[j].weight; + if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) + dist[v] = dist[u] + weight; } - - // Step 3: check for negative-weight cycles. The above step - // guarantees shortest distances if graph doesn't contain - // negative weight cycle. If we get a shorter path, then there - // is a cycle. - for (int i = 0; i < E; i++) { - int u = graph->edge[i].src; - int v = graph->edge[i].dest; - int weight = graph->edge[i].weight; - if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) { - printf("Graph contains negative weight cycle"); - return; // If negative cycle is detected, simply return - } + } + + // Step 3: check for negative-weight cycles. The above step + // guarantees shortest distances if graph doesn't contain + // negative weight cycle. If we get a shorter path, then there + // is a cycle. + for (int i = 0; i < E; i++) { + int u = graph->edge[i].src; + int v = graph->edge[i].dest; + int weight = graph->edge[i].weight; + if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) { + printf("Graph contains negative weight cycle"); + return; // If negative cycle is detected, simply return } + } - printArr(dist, V); + printArr(dist, V); - return; + return; } // Driver program to test above functions int main() { - /* Let us create the graph given in above example */ - int V = 5; // Number of vertices in graph - int E = 8; // Number of edges in graph - struct Graph *graph = createGraph(V, E); - - // add edge 0-1 (or A-B in above figure) - graph->edge[0].src = 0; - graph->edge[0].dest = 1; - graph->edge[0].weight = -1; - - // add edge 0-2 (or A-C in above figure) - graph->edge[1].src = 0; - graph->edge[1].dest = 2; - graph->edge[1].weight = 4; - - // add edge 1-2 (or B-C in above figure) - graph->edge[2].src = 1; - graph->edge[2].dest = 2; - graph->edge[2].weight = 3; - - // add edge 1-3 (or B-D in above figure) - graph->edge[3].src = 1; - graph->edge[3].dest = 3; - graph->edge[3].weight = 2; - - // add edge 1-4 (or A-E in above figure) - graph->edge[4].src = 1; - graph->edge[4].dest = 4; - graph->edge[4].weight = 2; - - // add edge 3-2 (or D-C in above figure) - graph->edge[5].src = 3; - graph->edge[5].dest = 2; - graph->edge[5].weight = 5; - - // add edge 3-1 (or D-B in above figure) - graph->edge[6].src = 3; - graph->edge[6].dest = 1; - graph->edge[6].weight = 1; - - // add edge 4-3 (or E-D in above figure) - graph->edge[7].src = 4; - graph->edge[7].dest = 3; - graph->edge[7].weight = -3; - - BellmanFord(graph, 0); - - return 0; + /* Let us create the graph given in above example */ + int V = 5; // Number of vertices in graph + int E = 8; // Number of edges in graph + struct Graph *graph = createGraph(V, E); + + // add edge 0-1 (or A-B in above figure) + graph->edge[0].src = 0; + graph->edge[0].dest = 1; + graph->edge[0].weight = -1; + + // add edge 0-2 (or A-C in above figure) + graph->edge[1].src = 0; + graph->edge[1].dest = 2; + graph->edge[1].weight = 4; + + // add edge 1-2 (or B-C in above figure) + graph->edge[2].src = 1; + graph->edge[2].dest = 2; + graph->edge[2].weight = 3; + + // add edge 1-3 (or B-D in above figure) + graph->edge[3].src = 1; + graph->edge[3].dest = 3; + graph->edge[3].weight = 2; + + // add edge 1-4 (or A-E in above figure) + graph->edge[4].src = 1; + graph->edge[4].dest = 4; + graph->edge[4].weight = 2; + + // add edge 3-2 (or D-C in above figure) + graph->edge[5].src = 3; + graph->edge[5].dest = 2; + graph->edge[5].weight = 5; + + // add edge 3-1 (or D-B in above figure) + graph->edge[6].src = 3; + graph->edge[6].dest = 1; + graph->edge[6].weight = 1; + + // add edge 4-3 (or E-D in above figure) + graph->edge[7].src = 4; + graph->edge[7].dest = 3; + graph->edge[7].weight = -3; + + BellmanFord(graph, 0); + + return 0; } diff --git a/src/test-suite/PE-benchmarks/bfs.cpp b/src/test-suite/PE-benchmarks/bfs.cpp index 65955410..6f22efd0 100644 --- a/src/test-suite/PE-benchmarks/bfs.cpp +++ b/src/test-suite/PE-benchmarks/bfs.cpp @@ -9,80 +9,80 @@ using namespace std; // This class represents a directed graph using // adjacency list representation class Graph { - int V; // No. of vertices + int V; // No. of vertices - // Pointer to an array containing adjacency - // lists - list *adj; + // Pointer to an array containing adjacency + // lists + list *adj; - public: - Graph(int V); // Constructor +public: + Graph(int V); // Constructor - // function to add an edge to graph - void addEdge(int v, int w); + // function to add an edge to graph + void addEdge(int v, int w); - // prints BFS traversal from a given source s - void BFS(int s); + // prints BFS traversal from a given source s + void BFS(int s); }; Graph::Graph(int V) { - this->V = V; - adj = new list[V]; + this->V = V; + adj = new list[V]; } void Graph::addEdge(int v, int w) { - adj[v].push_back(w); // Add w to v’s list. + adj[v].push_back(w); // Add w to v’s list. } void Graph::BFS(int s) { - // Mark all the vertices as not visited - bool *visited = new bool[V]; - for (int i = 0; i < V; i++) - visited[i] = false; - - // Create a queue for BFS - list queue; - - // Mark the current node as visited and enqueue it - visited[s] = true; - queue.push_back(s); - - // 'i' will be used to get all adjacent - // vertices of a vertex - list::iterator i; - - while (!queue.empty()) { - // Dequeue a vertex from queue and print it - s = queue.front(); - cout << s << " "; - queue.pop_front(); - - // Get all adjacent vertices of the dequeued - // vertex s. If a adjacent has not been visited, - // then mark it visited and enqueue it - for (i = adj[s].begin(); i != adj[s].end(); ++i) { - if (!visited[*i]) { - visited[*i] = true; - queue.push_back(*i); - } - } + // Mark all the vertices as not visited + bool *visited = new bool[V]; + for (int i = 0; i < V; i++) + visited[i] = false; + + // Create a queue for BFS + list queue; + + // Mark the current node as visited and enqueue it + visited[s] = true; + queue.push_back(s); + + // 'i' will be used to get all adjacent + // vertices of a vertex + list::iterator i; + + while (!queue.empty()) { + // Dequeue a vertex from queue and print it + s = queue.front(); + cout << s << " "; + queue.pop_front(); + + // Get all adjacent vertices of the dequeued + // vertex s. If a adjacent has not been visited, + // then mark it visited and enqueue it + for (i = adj[s].begin(); i != adj[s].end(); ++i) { + if (!visited[*i]) { + visited[*i] = true; + queue.push_back(*i); + } } + } } // Driver program to test methods of graph class int main() { - // Create a graph given in the above diagram - Graph g(4); - g.addEdge(0, 1); - g.addEdge(0, 2); - g.addEdge(1, 2); - g.addEdge(2, 0); - g.addEdge(2, 3); - g.addEdge(3, 3); - - cout << "Following is Breadth First Traversal " - << "(starting from vertex 2) \n"; - g.BFS(2); - - return 0; + // Create a graph given in the above diagram + Graph g(4); + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + cout << "Following is Breadth First Traversal " + << "(starting from vertex 2) \n"; + g.BFS(2); + + return 0; } diff --git a/src/test-suite/PE-benchmarks/biconnectivity.cpp b/src/test-suite/PE-benchmarks/biconnectivity.cpp index 3237048a..bd667c25 100644 --- a/src/test-suite/PE-benchmarks/biconnectivity.cpp +++ b/src/test-suite/PE-benchmarks/biconnectivity.cpp @@ -7,24 +7,24 @@ using namespace std; // A class that represents an undirected graph class Graph { - int V; // No. of vertices - list *adj; // A dynamic array of adjacency lists - bool isBCUtil(int v, bool visited[], int disc[], int low[], int parent[]); - - public: - Graph(int V); // Constructor - void addEdge(int v, int w); // to add an edge to graph - bool isBC(); // returns true if graph is Biconnected + int V; // No. of vertices + list *adj; // A dynamic array of adjacency lists + bool isBCUtil(int v, bool visited[], int disc[], int low[], int parent[]); + +public: + Graph(int V); // Constructor + void addEdge(int v, int w); // to add an edge to graph + bool isBC(); // returns true if graph is Biconnected }; Graph::Graph(int V) { - this->V = V; - adj = new list[V]; + this->V = V; + adj = new list[V]; } void Graph::addEdge(int v, int w) { - adj[v].push_back(w); - adj[w].push_back(v); // Note: the graph is undirected + adj[v].push_back(w); + adj[w].push_back(v); // Note: the graph is undirected } // A recursive function that returns true if there is an articulation @@ -36,122 +36,122 @@ void Graph::addEdge(int v, int w) { // parent[] --> Stores parent vertices in DFS tree bool Graph::isBCUtil(int u, bool visited[], int disc[], int low[], int parent[]) { - // A static variable is used for simplicity, we can avoid use of static - // variable by passing a pointer. - static int time = 0; + // A static variable is used for simplicity, we can avoid use of static + // variable by passing a pointer. + static int time = 0; - // Count of children in DFS Tree - int children = 0; + // Count of children in DFS Tree + int children = 0; - // Mark the current node as visited - visited[u] = true; + // Mark the current node as visited + visited[u] = true; - // Initialize discovery time and low value - disc[u] = low[u] = ++time; + // Initialize discovery time and low value + disc[u] = low[u] = ++time; - // Go through all vertices aadjacent to this - list::iterator i; - for (i = adj[u].begin(); i != adj[u].end(); ++i) { - int v = *i; // v is current adjacent of u + // Go through all vertices aadjacent to this + list::iterator i; + for (i = adj[u].begin(); i != adj[u].end(); ++i) { + int v = *i; // v is current adjacent of u - // If v is not visited yet, then make it a child of u - // in DFS tree and recur for it - if (!visited[v]) { - children++; - parent[v] = u; + // If v is not visited yet, then make it a child of u + // in DFS tree and recur for it + if (!visited[v]) { + children++; + parent[v] = u; - // check if subgraph rooted with v has an articulation point - if (isBCUtil(v, visited, disc, low, parent)) - return true; + // check if subgraph rooted with v has an articulation point + if (isBCUtil(v, visited, disc, low, parent)) + return true; - // Check if the subtree rooted with v has a connection to - // one of the ancestors of u - low[u] = min(low[u], low[v]); + // Check if the subtree rooted with v has a connection to + // one of the ancestors of u + low[u] = min(low[u], low[v]); - // u is an articulation point in following cases + // u is an articulation point in following cases - // (1) u is root of DFS tree and has two or more chilren. - if (parent[u] == NIL && children > 1) - return true; + // (1) u is root of DFS tree and has two or more chilren. + if (parent[u] == NIL && children > 1) + return true; - // (2) If u is not root and low value of one of its child is - // more than discovery value of u. - if (parent[u] != NIL && low[v] >= disc[u]) - return true; - } - - // Update low value of u for parent function calls. - else if (v != parent[u]) - low[u] = min(low[u], disc[v]); + // (2) If u is not root and low value of one of its child is + // more than discovery value of u. + if (parent[u] != NIL && low[v] >= disc[u]) + return true; } - return false; + + // Update low value of u for parent function calls. + else if (v != parent[u]) + low[u] = min(low[u], disc[v]); + } + return false; } // The main function that returns true if graph is Biconnected, // otherwise false. It uses recursive function isBCUtil() bool Graph::isBC() { - // Mark all the vertices as not visited - bool *visited = new bool[V]; - int *disc = new int[V]; - int *low = new int[V]; - int *parent = new int[V]; - - // Initialize parent and visited, and ap(articulation point) - // arrays - for (int i = 0; i < V; i++) { - parent[i] = NIL; - visited[i] = false; - } - - // Call the recursive helper function to find if there is an articulation - // point in given graph. We do DFS traversal starring from vertex 0 - if (isBCUtil(0, visited, disc, low, parent) == true) - return false; + // Mark all the vertices as not visited + bool *visited = new bool[V]; + int *disc = new int[V]; + int *low = new int[V]; + int *parent = new int[V]; + + // Initialize parent and visited, and ap(articulation point) + // arrays + for (int i = 0; i < V; i++) { + parent[i] = NIL; + visited[i] = false; + } + + // Call the recursive helper function to find if there is an articulation + // point in given graph. We do DFS traversal starring from vertex 0 + if (isBCUtil(0, visited, disc, low, parent) == true) + return false; - // Now check whether the given graph is connected or not. An undirected - // graph is connected if all vertices are reachable from any starting - // point (we have taken 0 as starting point) - for (int i = 0; i < V; i++) - if (visited[i] == false) - return false; + // Now check whether the given graph is connected or not. An undirected + // graph is connected if all vertices are reachable from any starting + // point (we have taken 0 as starting point) + for (int i = 0; i < V; i++) + if (visited[i] == false) + return false; - return true; + return true; } // Driver program to test above function int main() { - // Create graphs given in above diagrams - Graph g1(2); - g1.addEdge(0, 1); - g1.isBC() ? cout << "Yes\n" : cout << "No\n"; - - Graph g2(5); - g2.addEdge(1, 0); - g2.addEdge(0, 2); - g2.addEdge(2, 1); - g2.addEdge(0, 3); - g2.addEdge(3, 4); - g2.addEdge(2, 4); - g2.isBC() ? cout << "Yes\n" : cout << "No\n"; - - Graph g3(3); - g3.addEdge(0, 1); - g3.addEdge(1, 2); - g3.isBC() ? cout << "Yes\n" : cout << "No\n"; - - Graph g4(5); - g4.addEdge(1, 0); - g4.addEdge(0, 2); - g4.addEdge(2, 1); - g4.addEdge(0, 3); - g4.addEdge(3, 4); - g4.isBC() ? cout << "Yes\n" : cout << "No\n"; - - Graph g5(3); - g5.addEdge(0, 1); - g5.addEdge(1, 2); - g5.addEdge(2, 0); - g5.isBC() ? cout << "Yes\n" : cout << "No\n"; - - return 0; + // Create graphs given in above diagrams + Graph g1(2); + g1.addEdge(0, 1); + g1.isBC() ? cout << "Yes\n" : cout << "No\n"; + + Graph g2(5); + g2.addEdge(1, 0); + g2.addEdge(0, 2); + g2.addEdge(2, 1); + g2.addEdge(0, 3); + g2.addEdge(3, 4); + g2.addEdge(2, 4); + g2.isBC() ? cout << "Yes\n" : cout << "No\n"; + + Graph g3(3); + g3.addEdge(0, 1); + g3.addEdge(1, 2); + g3.isBC() ? cout << "Yes\n" : cout << "No\n"; + + Graph g4(5); + g4.addEdge(1, 0); + g4.addEdge(0, 2); + g4.addEdge(2, 1); + g4.addEdge(0, 3); + g4.addEdge(3, 4); + g4.isBC() ? cout << "Yes\n" : cout << "No\n"; + + Graph g5(3); + g5.addEdge(0, 1); + g5.addEdge(1, 2); + g5.addEdge(2, 0); + g5.isBC() ? cout << "Yes\n" : cout << "No\n"; + + return 0; } diff --git a/src/test-suite/PE-benchmarks/binary-insertion-sort.cpp b/src/test-suite/PE-benchmarks/binary-insertion-sort.cpp index 2a457f9e..5a98a01c 100644 --- a/src/test-suite/PE-benchmarks/binary-insertion-sort.cpp +++ b/src/test-suite/PE-benchmarks/binary-insertion-sort.cpp @@ -4,49 +4,49 @@ // A binary search based function to find the position // where item should be inserted in a[low..high] int binarySearch(int a[], int item, int low, int high) { - if (high <= low) - return (item > a[low]) ? (low + 1) : low; + if (high <= low) + return (item > a[low]) ? (low + 1) : low; - int mid = (low + high) / 2; + int mid = (low + high) / 2; - if (item == a[mid]) - return mid + 1; + if (item == a[mid]) + return mid + 1; - if (item > a[mid]) - return binarySearch(a, item, mid + 1, high); - return binarySearch(a, item, low, mid - 1); + if (item > a[mid]) + return binarySearch(a, item, mid + 1, high); + return binarySearch(a, item, low, mid - 1); } // Function to sort an array a[] of size 'n' void insertionSort(int a[], int n) { - int i, loc, j, k, selected; + int i, loc, j, k, selected; - for (i = 1; i < n; ++i) { - j = i - 1; - selected = a[i]; + for (i = 1; i < n; ++i) { + j = i - 1; + selected = a[i]; - // find location where selected sould be inseretd - loc = binarySearch(a, selected, 0, j); + // find location where selected sould be inseretd + loc = binarySearch(a, selected, 0, j); - // Move all elements after location to create space - while (j >= loc) { - a[j + 1] = a[j]; - j--; - } - a[j + 1] = selected; + // Move all elements after location to create space + while (j >= loc) { + a[j + 1] = a[j]; + j--; } + a[j + 1] = selected; + } } // Driver program to test above function int main() { - int a[] = {37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54}; - int n = sizeof(a) / sizeof(a[0]), i; + int a[] = {37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54}; + int n = sizeof(a) / sizeof(a[0]), i; - insertionSort(a, n); + insertionSort(a, n); - printf("Sorted array: \n"); - for (i = 0; i < n; i++) - printf("%d ", a[i]); + printf("Sorted array: \n"); + for (i = 0; i < n; i++) + printf("%d ", a[i]); - return 0; + return 0; } diff --git a/src/test-suite/PE-benchmarks/binomial-coefficient.cpp b/src/test-suite/PE-benchmarks/binomial-coefficient.cpp index deab3590..675916c5 100644 --- a/src/test-suite/PE-benchmarks/binomial-coefficient.cpp +++ b/src/test-suite/PE-benchmarks/binomial-coefficient.cpp @@ -9,25 +9,25 @@ int min(int a, int b); // Returns value of Binomial Coefficient C(n, k) int binomialCoeff(int n, int k) { - int C[n + 1][k + 1]; - int i, j; - - // Caculate value of Binomial Coefficient - // in bottom up manner - for (i = 0; i <= n; i++) { - for (j = 0; j <= min(i, k); j++) { - // Base Cases - if (j == 0 || j == i) - C[i][j] = 1; - - // Calculate value using previously - // stored values - else - C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; - } + int C[n + 1][k + 1]; + int i, j; + + // Caculate value of Binomial Coefficient + // in bottom up manner + for (i = 0; i <= n; i++) { + for (j = 0; j <= min(i, k); j++) { + // Base Cases + if (j == 0 || j == i) + C[i][j] = 1; + + // Calculate value using previously + // stored values + else + C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } + } - return C[n][k]; + return C[n][k]; } // A utility function to return @@ -36,8 +36,8 @@ int min(int a, int b) { return (a < b) ? a : b; } // Driver Code int main() { - int n = 5, k = 2; - cout << "Value of C[" << n << "][" << k << "] is " << binomialCoeff(n, k); + int n = 5, k = 2; + cout << "Value of C[" << n << "][" << k << "] is " << binomialCoeff(n, k); } // This code is contributed by Shivi_Aggarwal diff --git a/src/test-suite/PE-benchmarks/boolean-parenthesization-problem.cpp b/src/test-suite/PE-benchmarks/boolean-parenthesization-problem.cpp index d0ba5adc..8429795e 100644 --- a/src/test-suite/PE-benchmarks/boolean-parenthesization-problem.cpp +++ b/src/test-suite/PE-benchmarks/boolean-parenthesization-problem.cpp @@ -6,59 +6,59 @@ using namespace std; // result true for a boolean expression with symbols like true // and false and operators like &, | and ^ filled between symbols int countParenth(char symb[], char oper[], int n) { - int F[n][n], T[n][n]; + int F[n][n], T[n][n]; - // Fill diaginal entries first - // All diagonal entries in T[i][i] are 1 if symbol[i] - // is T (true). Similarly, all F[i][i] entries are 1 if - // symbol[i] is F (False) - for (int i = 0; i < n; i++) { - F[i][i] = (symb[i] == 'F') ? 1 : 0; - T[i][i] = (symb[i] == 'T') ? 1 : 0; - } + // Fill diaginal entries first + // All diagonal entries in T[i][i] are 1 if symbol[i] + // is T (true). Similarly, all F[i][i] entries are 1 if + // symbol[i] is F (False) + for (int i = 0; i < n; i++) { + F[i][i] = (symb[i] == 'F') ? 1 : 0; + T[i][i] = (symb[i] == 'T') ? 1 : 0; + } - // Now fill T[i][i+1], T[i][i+2], T[i][i+3]... in order - // And F[i][i+1], F[i][i+2], F[i][i+3]... in order - for (int gap = 1; gap < n; ++gap) { - for (int i = 0, j = gap; j < n; ++i, ++j) { - T[i][j] = F[i][j] = 0; - for (int g = 0; g < gap; g++) { - // Find place of parenthesization using current value - // of gap - int k = i + g; + // Now fill T[i][i+1], T[i][i+2], T[i][i+3]... in order + // And F[i][i+1], F[i][i+2], F[i][i+3]... in order + for (int gap = 1; gap < n; ++gap) { + for (int i = 0, j = gap; j < n; ++i, ++j) { + T[i][j] = F[i][j] = 0; + for (int g = 0; g < gap; g++) { + // Find place of parenthesization using current value + // of gap + int k = i + g; - // Store Total[i][k] and Total[k+1][j] - int tik = T[i][k] + F[i][k]; - int tkj = T[k + 1][j] + F[k + 1][j]; + // Store Total[i][k] and Total[k+1][j] + int tik = T[i][k] + F[i][k]; + int tkj = T[k + 1][j] + F[k + 1][j]; - // Follow the recursive formulas according to the current - // operator - if (oper[k] == '&') { - T[i][j] += T[i][k] * T[k + 1][j]; - F[i][j] += (tik * tkj - T[i][k] * T[k + 1][j]); - } - if (oper[k] == '|') { - F[i][j] += F[i][k] * F[k + 1][j]; - T[i][j] += (tik * tkj - F[i][k] * F[k + 1][j]); - } - if (oper[k] == '^') { - T[i][j] += F[i][k] * T[k + 1][j] + T[i][k] * F[k + 1][j]; - F[i][j] += T[i][k] * T[k + 1][j] + F[i][k] * F[k + 1][j]; - } - } + // Follow the recursive formulas according to the current + // operator + if (oper[k] == '&') { + T[i][j] += T[i][k] * T[k + 1][j]; + F[i][j] += (tik * tkj - T[i][k] * T[k + 1][j]); + } + if (oper[k] == '|') { + F[i][j] += F[i][k] * F[k + 1][j]; + T[i][j] += (tik * tkj - F[i][k] * F[k + 1][j]); + } + if (oper[k] == '^') { + T[i][j] += F[i][k] * T[k + 1][j] + T[i][k] * F[k + 1][j]; + F[i][j] += T[i][k] * T[k + 1][j] + F[i][k] * F[k + 1][j]; } + } } - return T[0][n - 1]; + } + return T[0][n - 1]; } // Driver program to test above function int main() { - char symbols[] = "TTFT"; - char operators[] = "|&^"; - int n = strlen(symbols); + char symbols[] = "TTFT"; + char operators[] = "|&^"; + int n = strlen(symbols); - // There are 4 ways - // ((T|T)&(F^T)), (T|(T&(F^T))), (((T|T)&F)^T) and (T|((T&F)^T)) - cout << countParenth(symbols, operators, n); - return 0; + // There are 4 ways + // ((T|T)&(F^T)), (T|(T&(F^T))), (((T|T)&F)^T) and (T|((T&F)^T)) + cout << countParenth(symbols, operators, n); + return 0; } diff --git a/src/test-suite/PE-benchmarks/boruvkas-algorithm.cpp b/src/test-suite/PE-benchmarks/boruvkas-algorithm.cpp index 333fcd74..eda54719 100644 --- a/src/test-suite/PE-benchmarks/boruvkas-algorithm.cpp +++ b/src/test-suite/PE-benchmarks/boruvkas-algorithm.cpp @@ -5,26 +5,26 @@ // a structure to represent a weighted edge in graph struct Edge { - int src, dest, weight; + int src, dest, weight; }; // a structure to represent a connected, undirected // and weighted graph as a collection of edges. struct Graph { - // V-> Number of vertices, E-> Number of edges - int V, E; - - // graph is represented as an array of edges. - // Since the graph is undirected, the edge - // from src to dest is also edge from dest - // to src. Both are counted as 1 edge here. - Edge *edge; + // V-> Number of vertices, E-> Number of edges + int V, E; + + // graph is represented as an array of edges. + // Since the graph is undirected, the edge + // from src to dest is also edge from dest + // to src. Both are counted as 1 edge here. + Edge *edge; }; // A structure to represent a subset for union-find struct subset { - int parent; - int rank; + int parent; + int rank; }; // Function prototypes for union-find (These functions are defined @@ -34,172 +34,172 @@ void Union(struct subset subsets[], int x, int y); // The main function for MST using Boruvka's algorithm void boruvkaMST(struct Graph *graph) { - // Get data of given graph - int V = graph->V, E = graph->E; - Edge *edge = graph->edge; - - // Allocate memory for creating V subsets. - struct subset *subsets = new subset[V]; - - // An array to store index of the cheapest edge of - // subset. The stored index for indexing array 'edge[]' - int *cheapest = new int[V]; - - // Create V subsets with single elements + // Get data of given graph + int V = graph->V, E = graph->E; + Edge *edge = graph->edge; + + // Allocate memory for creating V subsets. + struct subset *subsets = new subset[V]; + + // An array to store index of the cheapest edge of + // subset. The stored index for indexing array 'edge[]' + int *cheapest = new int[V]; + + // Create V subsets with single elements + for (int v = 0; v < V; ++v) { + subsets[v].parent = v; + subsets[v].rank = 0; + cheapest[v] = -1; + } + + // Initially there are V different trees. + // Finally there will be one tree that will be MST + int numTrees = V; + int MSTweight = 0; + + // Keep combining components (or sets) until all + // compnentes are not combined into single MST. + while (numTrees > 1) { + // Everytime initialize cheapest array for (int v = 0; v < V; ++v) { - subsets[v].parent = v; - subsets[v].rank = 0; - cheapest[v] = -1; + cheapest[v] = -1; } - // Initially there are V different trees. - // Finally there will be one tree that will be MST - int numTrees = V; - int MSTweight = 0; - - // Keep combining components (or sets) until all - // compnentes are not combined into single MST. - while (numTrees > 1) { - // Everytime initialize cheapest array - for (int v = 0; v < V; ++v) { - cheapest[v] = -1; - } - - // Traverse through all edges and update - // cheapest of every component - for (int i = 0; i < E; i++) { - // Find components (or sets) of two corners - // of current edge - int set1 = find(subsets, edge[i].src); - int set2 = find(subsets, edge[i].dest); - - // If two corners of current edge belong to - // same set, ignore current edge - if (set1 == set2) - continue; - - // Else check if current edge is closer to previous - // cheapest edges of set1 and set2 - else { - if (cheapest[set1] == -1 || - edge[cheapest[set1]].weight > edge[i].weight) - cheapest[set1] = i; - - if (cheapest[set2] == -1 || - edge[cheapest[set2]].weight > edge[i].weight) - cheapest[set2] = i; - } - } - - // Consider the above picked cheapest edges and add them - // to MST - for (int i = 0; i < V; i++) { - // Check if cheapest for current set exists - if (cheapest[i] != -1) { - int set1 = find(subsets, edge[cheapest[i]].src); - int set2 = find(subsets, edge[cheapest[i]].dest); - - if (set1 == set2) - continue; - MSTweight += edge[cheapest[i]].weight; - printf("Edge %d-%d included in MST\n", edge[cheapest[i]].src, - edge[cheapest[i]].dest); - - // Do a union of set1 and set2 and decrease number - // of trees - Union(subsets, set1, set2); - numTrees--; - } - } + // Traverse through all edges and update + // cheapest of every component + for (int i = 0; i < E; i++) { + // Find components (or sets) of two corners + // of current edge + int set1 = find(subsets, edge[i].src); + int set2 = find(subsets, edge[i].dest); + + // If two corners of current edge belong to + // same set, ignore current edge + if (set1 == set2) + continue; + + // Else check if current edge is closer to previous + // cheapest edges of set1 and set2 + else { + if (cheapest[set1] == -1 || + edge[cheapest[set1]].weight > edge[i].weight) + cheapest[set1] = i; + + if (cheapest[set2] == -1 || + edge[cheapest[set2]].weight > edge[i].weight) + cheapest[set2] = i; + } } - printf("Weight of MST is %d\n", MSTweight); - return; + // Consider the above picked cheapest edges and add them + // to MST + for (int i = 0; i < V; i++) { + // Check if cheapest for current set exists + if (cheapest[i] != -1) { + int set1 = find(subsets, edge[cheapest[i]].src); + int set2 = find(subsets, edge[cheapest[i]].dest); + + if (set1 == set2) + continue; + MSTweight += edge[cheapest[i]].weight; + printf("Edge %d-%d included in MST\n", edge[cheapest[i]].src, + edge[cheapest[i]].dest); + + // Do a union of set1 and set2 and decrease number + // of trees + Union(subsets, set1, set2); + numTrees--; + } + } + } + + printf("Weight of MST is %d\n", MSTweight); + return; } // Creates a graph with V vertices and E edges struct Graph *createGraph(int V, int E) { - Graph *graph = new Graph; - graph->V = V; - graph->E = E; - graph->edge = new Edge[E]; - return graph; + Graph *graph = new Graph; + graph->V = V; + graph->E = E; + graph->edge = new Edge[E]; + return graph; } // A utility function to find set of an element i // (uses path compression technique) int find(struct subset subsets[], int i) { - // find root and make root as parent of i - // (path compression) - if (subsets[i].parent != i) - subsets[i].parent = find(subsets, subsets[i].parent); + // find root and make root as parent of i + // (path compression) + if (subsets[i].parent != i) + subsets[i].parent = find(subsets, subsets[i].parent); - return subsets[i].parent; + return subsets[i].parent; } // A function that does union of two sets of x and y // (uses union by rank) void Union(struct subset subsets[], int x, int y) { - int xroot = find(subsets, x); - int yroot = find(subsets, y); - - // Attach smaller rank tree under root of high - // rank tree (Union by Rank) - if (subsets[xroot].rank < subsets[yroot].rank) - subsets[xroot].parent = yroot; - else if (subsets[xroot].rank > subsets[yroot].rank) - subsets[yroot].parent = xroot; - - // If ranks are same, then make one as root and - // increment its rank by one - else { - subsets[yroot].parent = xroot; - subsets[xroot].rank++; - } + int xroot = find(subsets, x); + int yroot = find(subsets, y); + + // Attach smaller rank tree under root of high + // rank tree (Union by Rank) + if (subsets[xroot].rank < subsets[yroot].rank) + subsets[xroot].parent = yroot; + else if (subsets[xroot].rank > subsets[yroot].rank) + subsets[yroot].parent = xroot; + + // If ranks are same, then make one as root and + // increment its rank by one + else { + subsets[yroot].parent = xroot; + subsets[xroot].rank++; + } } // Driver program to test above functions int main() { - /* Let us create following weighted graph - 10 - 0--------1 - | \ | - 6| 5\ |15 - | \ | - 2--------3 - 4 */ - int V = 4; // Number of vertices in graph - int E = 5; // Number of edges in graph - struct Graph *graph = createGraph(V, E); - - // add edge 0-1 - graph->edge[0].src = 0; - graph->edge[0].dest = 1; - graph->edge[0].weight = 10; - - // add edge 0-2 - graph->edge[1].src = 0; - graph->edge[1].dest = 2; - graph->edge[1].weight = 6; - - // add edge 0-3 - graph->edge[2].src = 0; - graph->edge[2].dest = 3; - graph->edge[2].weight = 5; - - // add edge 1-3 - graph->edge[3].src = 1; - graph->edge[3].dest = 3; - graph->edge[3].weight = 15; - - // add edge 2-3 - graph->edge[4].src = 2; - graph->edge[4].dest = 3; - graph->edge[4].weight = 4; - - boruvkaMST(graph); - - return 0; + /* Let us create following weighted graph + 10 + 0--------1 + | \ | + 6| 5\ |15 + | \ | + 2--------3 + 4 */ + int V = 4; // Number of vertices in graph + int E = 5; // Number of edges in graph + struct Graph *graph = createGraph(V, E); + + // add edge 0-1 + graph->edge[0].src = 0; + graph->edge[0].dest = 1; + graph->edge[0].weight = 10; + + // add edge 0-2 + graph->edge[1].src = 0; + graph->edge[1].dest = 2; + graph->edge[1].weight = 6; + + // add edge 0-3 + graph->edge[2].src = 0; + graph->edge[2].dest = 3; + graph->edge[2].weight = 5; + + // add edge 1-3 + graph->edge[3].src = 1; + graph->edge[3].dest = 3; + graph->edge[3].weight = 15; + + // add edge 2-3 + graph->edge[4].src = 2; + graph->edge[4].dest = 3; + graph->edge[4].weight = 4; + + boruvkaMST(graph); + + return 0; } // Thanks to Anukul Chand for modifying above code. diff --git a/src/test-suite/PE-benchmarks/box-stacking.cpp b/src/test-suite/PE-benchmarks/box-stacking.cpp index 834cf244..41e50633 100644 --- a/src/test-suite/PE-benchmarks/box-stacking.cpp +++ b/src/test-suite/PE-benchmarks/box-stacking.cpp @@ -4,8 +4,8 @@ /* Representation of a box */ struct Box { - // h --> height, w --> width, d --> depth - int h, w, d; // for simplicity of solution, always keep w <= d + // h --> height, w --> width, d --> depth + int h, w, d; // for simplicity of solution, always keep w <= d }; // A utility function to get minimum of two intgers @@ -19,78 +19,78 @@ use qsort() to sort boxes in decreasing order of base area. Refer following link for help of qsort() and compare() http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */ int compare(const void *a, const void *b) { - return ((*(Box *)b).d * (*(Box *)b).w) - ((*(Box *)a).d * (*(Box *)a).w); + return ((*(Box *)b).d * (*(Box *)b).w) - ((*(Box *)a).d * (*(Box *)a).w); } /* Returns the height of the tallest stack that can be formed with give type of boxes */ int maxStackHeight(Box arr[], int n) { - /* Create an array of all rotations of given boxes - For example, for a box {1, 2, 3}, we consider three - instances{{1, 2, 3}, {2, 1, 3}, {3, 1, 2}} */ - Box rot[3 * n]; - int index = 0; - for (int i = 0; i < n; i++) { - // Copy the original box - rot[index].h = arr[i].h; - rot[index].d = max(arr[i].d, arr[i].w); - rot[index].w = min(arr[i].d, arr[i].w); - index++; - - // First rotation of box - rot[index].h = arr[i].w; - rot[index].d = max(arr[i].h, arr[i].d); - rot[index].w = min(arr[i].h, arr[i].d); - index++; - - // Second rotation of box - rot[index].h = arr[i].d; - rot[index].d = max(arr[i].h, arr[i].w); - rot[index].w = min(arr[i].h, arr[i].w); - index++; - } - - // Now the number of boxes is 3n - n = 3 * n; - - /* Sort the array 'rot[]' in non-increasing order - of base area */ - qsort(rot, n, sizeof(rot[0]), compare); - - // Uncomment following two lines to print all rotations - // for (int i = 0; i < n; i++ ) - // printf("%d x %d x %d\n", rot[i].h, rot[i].w, rot[i].d); - - /* Initialize msh values for all indexes - msh[i] --> Maximum possible Stack Height with box i on top */ - int msh[n]; - for (int i = 0; i < n; i++) - msh[i] = rot[i].h; - - /* Compute optimized msh values in bottom up manner */ - for (int i = 1; i < n; i++) - for (int j = 0; j < i; j++) - if (rot[i].w < rot[j].w && rot[i].d < rot[j].d && - msh[i] < msh[j] + rot[i].h) { - msh[i] = msh[j] + rot[i].h; - } - - /* Pick maximum of all msh values */ - int max = -1; - for (int i = 0; i < n; i++) - if (max < msh[i]) - max = msh[i]; - - return max; + /* Create an array of all rotations of given boxes + For example, for a box {1, 2, 3}, we consider three + instances{{1, 2, 3}, {2, 1, 3}, {3, 1, 2}} */ + Box rot[3 * n]; + int index = 0; + for (int i = 0; i < n; i++) { + // Copy the original box + rot[index].h = arr[i].h; + rot[index].d = max(arr[i].d, arr[i].w); + rot[index].w = min(arr[i].d, arr[i].w); + index++; + + // First rotation of box + rot[index].h = arr[i].w; + rot[index].d = max(arr[i].h, arr[i].d); + rot[index].w = min(arr[i].h, arr[i].d); + index++; + + // Second rotation of box + rot[index].h = arr[i].d; + rot[index].d = max(arr[i].h, arr[i].w); + rot[index].w = min(arr[i].h, arr[i].w); + index++; + } + + // Now the number of boxes is 3n + n = 3 * n; + + /* Sort the array 'rot[]' in non-increasing order + of base area */ + qsort(rot, n, sizeof(rot[0]), compare); + + // Uncomment following two lines to print all rotations + // for (int i = 0; i < n; i++ ) + // printf("%d x %d x %d\n", rot[i].h, rot[i].w, rot[i].d); + + /* Initialize msh values for all indexes + msh[i] --> Maximum possible Stack Height with box i on top */ + int msh[n]; + for (int i = 0; i < n; i++) + msh[i] = rot[i].h; + + /* Compute optimized msh values in bottom up manner */ + for (int i = 1; i < n; i++) + for (int j = 0; j < i; j++) + if (rot[i].w < rot[j].w && rot[i].d < rot[j].d && + msh[i] < msh[j] + rot[i].h) { + msh[i] = msh[j] + rot[i].h; + } + + /* Pick maximum of all msh values */ + int max = -1; + for (int i = 0; i < n; i++) + if (max < msh[i]) + max = msh[i]; + + return max; } /* Driver program to test above function */ int main() { - Box arr[] = {{4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32}}; - int n = sizeof(arr) / sizeof(arr[0]); + Box arr[] = {{4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32}}; + int n = sizeof(arr) / sizeof(arr[0]); - printf("The maximum possible height of stack is %d\n", - maxStackHeight(arr, n)); + printf("The maximum possible height of stack is %d\n", + maxStackHeight(arr, n)); - return 0; + return 0; } diff --git a/src/test-suite/PE-benchmarks/boyer-moore-algorithm.cpp b/src/test-suite/PE-benchmarks/boyer-moore-algorithm.cpp index d9bf587b..6dffc8d5 100644 --- a/src/test-suite/PE-benchmarks/boyer-moore-algorithm.cpp +++ b/src/test-suite/PE-benchmarks/boyer-moore-algorithm.cpp @@ -7,77 +7,77 @@ using namespace std; // The preprocessing function for Boyer Moore's // bad character heuristic void badCharHeuristic(string str, int size, int badchar[NO_OF_CHARS]) { - int i; + int i; - // Initialize all occurrences as -1 - for (i = 0; i < NO_OF_CHARS; i++) - badchar[i] = -1; + // Initialize all occurrences as -1 + for (i = 0; i < NO_OF_CHARS; i++) + badchar[i] = -1; - // Fill the actual value of last occurrence - // of a character - for (i = 0; i < size; i++) - badchar[(int)str[i]] = i; + // Fill the actual value of last occurrence + // of a character + for (i = 0; i < size; i++) + badchar[(int)str[i]] = i; } /* A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm */ void search(string txt, string pat) { - int m = pat.size(); - int n = txt.size(); + int m = pat.size(); + int n = txt.size(); - int badchar[NO_OF_CHARS]; + int badchar[NO_OF_CHARS]; - /* Fill the bad character array by calling - the preprocessing function badCharHeuristic() - for given pattern */ - badCharHeuristic(pat, m, badchar); + /* Fill the bad character array by calling + the preprocessing function badCharHeuristic() + for given pattern */ + badCharHeuristic(pat, m, badchar); - int s = 0; // s is shift of the pattern with - // respect to text - while (s <= (n - m)) { - int j = m - 1; + int s = 0; // s is shift of the pattern with + // respect to text + while (s <= (n - m)) { + int j = m - 1; - /* Keep reducing index j of pattern while - characters of pattern and text are - matching at this shift s */ - while (j >= 0 && pat[j] == txt[s + j]) - j--; + /* Keep reducing index j of pattern while + characters of pattern and text are + matching at this shift s */ + while (j >= 0 && pat[j] == txt[s + j]) + j--; - /* If the pattern is present at current - shift, then index j will become -1 after - the above loop */ - if (j < 0) { - cout << "pattern occurs at shift = " << s << endl; + /* If the pattern is present at current + shift, then index j will become -1 after + the above loop */ + if (j < 0) { + cout << "pattern occurs at shift = " << s << endl; - /* Shift the pattern so that the next - character in text aligns with the last - occurrence of it in pattern. - The condition s+m < n is necessary for - the case when pattern occurs at the end - of text */ - s += (s + m < n) ? m - badchar[txt[s + m]] : 1; + /* Shift the pattern so that the next + character in text aligns with the last + occurrence of it in pattern. + The condition s+m < n is necessary for + the case when pattern occurs at the end + of text */ + s += (s + m < n) ? m - badchar[txt[s + m]] : 1; - } - - else - /* Shift the pattern so that the bad character - in text aligns with the last occurrence of - it in pattern. The max function is used to - make sure that we get a positive shift. - We may get a negative shift if the last - occurrence of bad character in pattern - is on the right side of the current - character. */ - s += max(1, j - badchar[txt[s + j]]); } + + else + /* Shift the pattern so that the bad character + in text aligns with the last occurrence of + it in pattern. The max function is used to + make sure that we get a positive shift. + We may get a negative shift if the last + occurrence of bad character in pattern + is on the right side of the current + character. */ + s += max(1, j - badchar[txt[s + j]]); + } } /* Driver code */ int main() { - string txt = "ABAAABCD"; - string pat = "ABC"; - search(txt, pat); - return 0; + string txt = "ABAAABCD"; + string pat = "ABC"; + search(txt, pat); + return 0; } // This code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/channel-assignment.cpp b/src/test-suite/PE-benchmarks/channel-assignment.cpp index 62e6de8f..feb52daf 100644 --- a/src/test-suite/PE-benchmarks/channel-assignment.cpp +++ b/src/test-suite/PE-benchmarks/channel-assignment.cpp @@ -8,63 +8,63 @@ using namespace std; // A Depth First Search based recursive function that returns true // if a matching for vertex u is possible bool bpm(int table[M][N], int u, bool seen[], int matchR[]) { - // Try every receiver one by one - for (int v = 0; v < N; v++) { - // If sender u has packets to send to receiver v and - // receiver v is not already mapped to any other sender - // just check if the number of packets is greater than '0' - // because only one packet can be sent in a time frame anyways - if (table[u][v] > 0 && !seen[v]) { - seen[v] = true; // Mark v as visited + // Try every receiver one by one + for (int v = 0; v < N; v++) { + // If sender u has packets to send to receiver v and + // receiver v is not already mapped to any other sender + // just check if the number of packets is greater than '0' + // because only one packet can be sent in a time frame anyways + if (table[u][v] > 0 && !seen[v]) { + seen[v] = true; // Mark v as visited - // If receiver 'v' is not assigned to any sender OR - // previously assigned sender for receiver v (which is - // matchR[v]) has an alternate receiver available. Since - // v is marked as visited in the above line, matchR[v] in - // the following recursive call will not get receiver 'v' again - if (matchR[v] < 0 || bpm(table, matchR[v], seen, matchR)) { - matchR[v] = u; - return true; - } - } + // If receiver 'v' is not assigned to any sender OR + // previously assigned sender for receiver v (which is + // matchR[v]) has an alternate receiver available. Since + // v is marked as visited in the above line, matchR[v] in + // the following recursive call will not get receiver 'v' again + if (matchR[v] < 0 || bpm(table, matchR[v], seen, matchR)) { + matchR[v] = u; + return true; + } } - return false; + } + return false; } // Returns maximum number of packets that can be sent parallely in 1 // time slot from sender to receiver int maxBPM(int table[M][N]) { - // An array to keep track of the receivers assigned to the senders. - // The value of matchR[i] is the sender ID assigned to receiver i. - // the value -1 indicates nobody is assigned. - int matchR[N]; + // An array to keep track of the receivers assigned to the senders. + // The value of matchR[i] is the sender ID assigned to receiver i. + // the value -1 indicates nobody is assigned. + int matchR[N]; - // Initially all receivers are not mapped to any senders - memset(matchR, -1, sizeof(matchR)); + // Initially all receivers are not mapped to any senders + memset(matchR, -1, sizeof(matchR)); - int result = 0; // Count of receivers assigned to senders - for (int u = 0; u < M; u++) { - // Mark all receivers as not seen for next sender - bool seen[N]; - memset(seen, 0, sizeof(seen)); + int result = 0; // Count of receivers assigned to senders + for (int u = 0; u < M; u++) { + // Mark all receivers as not seen for next sender + bool seen[N]; + memset(seen, 0, sizeof(seen)); - // Find if the sender 'u' can be assigned to the receiver - if (bpm(table, u, seen, matchR)) - result++; - } + // Find if the sender 'u' can be assigned to the receiver + if (bpm(table, u, seen, matchR)) + result++; + } - cout << "The number of maximum packets sent in the time slot is " << result - << "\n"; + cout << "The number of maximum packets sent in the time slot is " << result + << "\n"; - for (int x = 0; x < N; x++) - if (matchR[x] + 1 != 0) - cout << "T" << matchR[x] + 1 << "-> R" << x + 1 << "\n"; - return result; + for (int x = 0; x < N; x++) + if (matchR[x] + 1 != 0) + cout << "T" << matchR[x] + 1 << "-> R" << x + 1 << "\n"; + return result; } // Driver program to test above function int main() { - int table[M][N] = {{0, 2, 0}, {3, 0, 1}, {2, 4, 0}}; - int max_flow = maxBPM(table); - return 0; + int table[M][N] = {{0, 2, 0}, {3, 0, 1}, {2, 4, 0}}; + int max_flow = maxBPM(table); + return 0; } diff --git a/src/test-suite/PE-benchmarks/coin-change.cpp b/src/test-suite/PE-benchmarks/coin-change.cpp index f3f40ec6..71ebae4c 100644 --- a/src/test-suite/PE-benchmarks/coin-change.cpp +++ b/src/test-suite/PE-benchmarks/coin-change.cpp @@ -4,43 +4,43 @@ using namespace std; int count(int S[], int m, int n) { - int i, j, x, y; - - // We need n+1 rows as the table - // is constructed in bottom up - // manner using the base case 0 - // value case (n = 0) - int table[n + 1][m]; - - // Fill the enteries for 0 - // value case (n = 0) - for (i = 0; i < m; i++) - table[0][i] = 1; - - // Fill rest of the table entries - // in bottom up manner - for (i = 1; i < n + 1; i++) { - for (j = 0; j < m; j++) { - // Count of solutions including S[j] - x = (i - S[j] >= 0) ? table[i - S[j]][j] : 0; - - // Count of solutions excluding S[j] - y = (j >= 1) ? table[i][j - 1] : 0; - - // total count - table[i][j] = x + y; - } + int i, j, x, y; + + // We need n+1 rows as the table + // is constructed in bottom up + // manner using the base case 0 + // value case (n = 0) + int table[n + 1][m]; + + // Fill the enteries for 0 + // value case (n = 0) + for (i = 0; i < m; i++) + table[0][i] = 1; + + // Fill rest of the table entries + // in bottom up manner + for (i = 1; i < n + 1; i++) { + for (j = 0; j < m; j++) { + // Count of solutions including S[j] + x = (i - S[j] >= 0) ? table[i - S[j]][j] : 0; + + // Count of solutions excluding S[j] + y = (j >= 1) ? table[i][j - 1] : 0; + + // total count + table[i][j] = x + y; } - return table[n][m - 1]; + } + return table[n][m - 1]; } // Driver Code int main() { - int arr[] = {1, 2, 3}; - int m = sizeof(arr) / sizeof(arr[0]); - int n = 4; - cout << count(arr, m, n); - return 0; + int arr[] = {1, 2, 3}; + int m = sizeof(arr) / sizeof(arr[0]); + int n = 4; + cout << count(arr, m, n); + return 0; } // This code is contributed diff --git a/src/test-suite/PE-benchmarks/collect-maximum-points-in-a-grid-using-two-traversals.cpp b/src/test-suite/PE-benchmarks/collect-maximum-points-in-a-grid-using-two-traversals.cpp index c32b144a..6890e061 100644 --- a/src/test-suite/PE-benchmarks/collect-maximum-points-in-a-grid-using-two-traversals.cpp +++ b/src/test-suite/PE-benchmarks/collect-maximum-points-in-a-grid-using-two-traversals.cpp @@ -7,70 +7,70 @@ using namespace std; // checks whether a given input is valid or not bool isValid(int x, int y1, int y2) { - return (x >= 0 && x < R && y1 >= 0 && y1 < C && y2 >= 0 && y2 < C); + return (x >= 0 && x < R && y1 >= 0 && y1 < C && y2 >= 0 && y2 < C); } // Driver function to collect max value int getMaxUtil(int arr[R][C], int mem[R][C][C], int x, int y1, int y2) { - /*---------- BASE CASES -----------*/ - // if P1 or P2 is at an invalid cell - if (!isValid(x, y1, y2)) - return INT_MIN; + /*---------- BASE CASES -----------*/ + // if P1 or P2 is at an invalid cell + if (!isValid(x, y1, y2)) + return INT_MIN; - // if both traversals reach their destinations - if (x == R - 1 && y1 == 0 && y2 == C - 1) - return (y1 == y2) ? arr[x][y1] : arr[x][y1] + arr[x][y2]; + // if both traversals reach their destinations + if (x == R - 1 && y1 == 0 && y2 == C - 1) + return (y1 == y2) ? arr[x][y1] : arr[x][y1] + arr[x][y2]; - // If both traversals are at last row but not at their destination - if (x == R - 1) - return INT_MIN; + // If both traversals are at last row but not at their destination + if (x == R - 1) + return INT_MIN; - // If subproblem is already solved - if (mem[x][y1][y2] != -1) - return mem[x][y1][y2]; + // If subproblem is already solved + if (mem[x][y1][y2] != -1) + return mem[x][y1][y2]; - // Initialize answer for this subproblem - int ans = INT_MIN; + // Initialize answer for this subproblem + int ans = INT_MIN; - // this variable is used to store gain of current cell(s) - int temp = (y1 == y2) ? arr[x][y1] : arr[x][y1] + arr[x][y2]; + // this variable is used to store gain of current cell(s) + int temp = (y1 == y2) ? arr[x][y1] : arr[x][y1] + arr[x][y2]; - /* Recur for all possible cases, then store and return the - one with max value */ - ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1, y2 - 1)); - ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1, y2 + 1)); - ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1, y2)); + /* Recur for all possible cases, then store and return the + one with max value */ + ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1, y2 - 1)); + ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1, y2 + 1)); + ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1, y2)); - ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1 - 1, y2)); - ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1 - 1, y2 - 1)); - ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1 - 1, y2 + 1)); + ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1 - 1, y2)); + ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1 - 1, y2 - 1)); + ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1 - 1, y2 + 1)); - ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1 + 1, y2)); - ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1 + 1, y2 - 1)); - ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1 + 1, y2 + 1)); + ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1 + 1, y2)); + ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1 + 1, y2 - 1)); + ans = max(ans, temp + getMaxUtil(arr, mem, x + 1, y1 + 1, y2 + 1)); - return (mem[x][y1][y2] = ans); + return (mem[x][y1][y2] = ans); } // This is mainly a wrapper over recursive function getMaxUtil(). // This function creates a table for memoization and calls // getMaxUtil() int geMaxCollection(int arr[R][C]) { - // Create a memoization table and initialize all entries as -1 - int mem[R][C][C]; - memset(mem, -1, sizeof(mem)); + // Create a memoization table and initialize all entries as -1 + int mem[R][C][C]; + memset(mem, -1, sizeof(mem)); - // Calculation maximum value using memoization based function - // getMaxUtil() - return getMaxUtil(arr, mem, 0, 0, C - 1); + // Calculation maximum value using memoization based function + // getMaxUtil() + return getMaxUtil(arr, mem, 0, 0, C - 1); } // Driver program to test above functions int main() { - int arr[R][C] = { - {3, 6, 8, 2}, {5, 2, 4, 3}, {1, 1, 20, 10}, - {1, 1, 20, 10}, {1, 1, 20, 10}, - }; - cout << "Maximum collection is " << geMaxCollection(arr); - return 0; + int arr[R][C] = { + {3, 6, 8, 2}, {5, 2, 4, 3}, {1, 1, 20, 10}, + {1, 1, 20, 10}, {1, 1, 20, 10}, + }; + cout << "Maximum collection is " << geMaxCollection(arr); + return 0; } diff --git a/src/test-suite/PE-benchmarks/construction-of-lcp-array-from-suffix-array.cpp b/src/test-suite/PE-benchmarks/construction-of-lcp-array-from-suffix-array.cpp index 37ee871e..cf1186ff 100644 --- a/src/test-suite/PE-benchmarks/construction-of-lcp-array-from-suffix-array.cpp +++ b/src/test-suite/PE-benchmarks/construction-of-lcp-array-from-suffix-array.cpp @@ -4,157 +4,157 @@ using namespace std; // Structure to store information of a suffix struct suffix { - int index; // To store original index - int rank[2]; // To store ranks and next rank pair + int index; // To store original index + int rank[2]; // To store ranks and next rank pair }; // A comparison function used by sort() to compare two suffixes // Compares two pairs, returns 1 if first pair is smaller int cmp(struct suffix a, struct suffix b) { - return (a.rank[0] == b.rank[0]) ? (a.rank[1] < b.rank[1] ? 1 : 0) - : (a.rank[0] < b.rank[0] ? 1 : 0); + return (a.rank[0] == b.rank[0]) ? (a.rank[1] < b.rank[1] ? 1 : 0) + : (a.rank[0] < b.rank[0] ? 1 : 0); } // This is the main function that takes a string 'txt' of size n as an // argument, builds and return the suffix array for the given string vector buildSuffixArray(string txt, int n) { - // A structure to store suffixes and their indexes - struct suffix suffixes[n]; + // A structure to store suffixes and their indexes + struct suffix suffixes[n]; + + // Store suffixes and their indexes in an array of structures. + // The structure is needed to sort the suffixes alphabatically + // and maintain their old indexes while sorting + for (int i = 0; i < n; i++) { + suffixes[i].index = i; + suffixes[i].rank[0] = txt[i] - 'a'; + suffixes[i].rank[1] = ((i + 1) < n) ? (txt[i + 1] - 'a') : -1; + } + + // Sort the suffixes using the comparison function + // defined above. + sort(suffixes, suffixes + n, cmp); + + // At his point, all suffixes are sorted according to first + // 2 characters. Let us sort suffixes according to first 4 + // characters, then first 8 and so on + int ind[n]; // This array is needed to get the index in suffixes[] + // from original index. This mapping is needed to get + // next suffix. + for (int k = 4; k < 2 * n; k = k * 2) { + // Assigning rank and index values to first suffix + int rank = 0; + int prev_rank = suffixes[0].rank[0]; + suffixes[0].rank[0] = rank; + ind[suffixes[0].index] = 0; + + // Assigning rank to suffixes + for (int i = 1; i < n; i++) { + // If first rank and next ranks are same as that of previous + // suffix in array, assign the same new rank to this suffix + if (suffixes[i].rank[0] == prev_rank && + suffixes[i].rank[1] == suffixes[i - 1].rank[1]) { + prev_rank = suffixes[i].rank[0]; + suffixes[i].rank[0] = rank; + } else // Otherwise increment rank and assign + { + prev_rank = suffixes[i].rank[0]; + suffixes[i].rank[0] = ++rank; + } + ind[suffixes[i].index] = i; + } - // Store suffixes and their indexes in an array of structures. - // The structure is needed to sort the suffixes alphabatically - // and maintain their old indexes while sorting + // Assign next rank to every suffix for (int i = 0; i < n; i++) { - suffixes[i].index = i; - suffixes[i].rank[0] = txt[i] - 'a'; - suffixes[i].rank[1] = ((i + 1) < n) ? (txt[i + 1] - 'a') : -1; + int nextindex = suffixes[i].index + k / 2; + suffixes[i].rank[1] = + (nextindex < n) ? suffixes[ind[nextindex]].rank[0] : -1; } - // Sort the suffixes using the comparison function - // defined above. + // Sort the suffixes according to first k characters sort(suffixes, suffixes + n, cmp); + } - // At his point, all suffixes are sorted according to first - // 2 characters. Let us sort suffixes according to first 4 - // characters, then first 8 and so on - int ind[n]; // This array is needed to get the index in suffixes[] - // from original index. This mapping is needed to get - // next suffix. - for (int k = 4; k < 2 * n; k = k * 2) { - // Assigning rank and index values to first suffix - int rank = 0; - int prev_rank = suffixes[0].rank[0]; - suffixes[0].rank[0] = rank; - ind[suffixes[0].index] = 0; - - // Assigning rank to suffixes - for (int i = 1; i < n; i++) { - // If first rank and next ranks are same as that of previous - // suffix in array, assign the same new rank to this suffix - if (suffixes[i].rank[0] == prev_rank && - suffixes[i].rank[1] == suffixes[i - 1].rank[1]) { - prev_rank = suffixes[i].rank[0]; - suffixes[i].rank[0] = rank; - } else // Otherwise increment rank and assign - { - prev_rank = suffixes[i].rank[0]; - suffixes[i].rank[0] = ++rank; - } - ind[suffixes[i].index] = i; - } - - // Assign next rank to every suffix - for (int i = 0; i < n; i++) { - int nextindex = suffixes[i].index + k / 2; - suffixes[i].rank[1] = - (nextindex < n) ? suffixes[ind[nextindex]].rank[0] : -1; - } - - // Sort the suffixes according to first k characters - sort(suffixes, suffixes + n, cmp); - } - - // Store indexes of all sorted suffixes in the suffix array - vector suffixArr; - for (int i = 0; i < n; i++) - suffixArr.push_back(suffixes[i].index); + // Store indexes of all sorted suffixes in the suffix array + vector suffixArr; + for (int i = 0; i < n; i++) + suffixArr.push_back(suffixes[i].index); - // Return the suffix array - return suffixArr; + // Return the suffix array + return suffixArr; } /* To construct and return LCP */ vector kasai(string txt, vector suffixArr) { - int n = suffixArr.size(); - - // To store LCP array - vector lcp(n, 0); + int n = suffixArr.size(); + + // To store LCP array + vector lcp(n, 0); + + // An auxiliary array to store inverse of suffix array + // elements. For example if suffixArr[0] is 5, the + // invSuff[5] would store 0. This is used to get next + // suffix string from suffix array. + vector invSuff(n, 0); + + // Fill values in invSuff[] + for (int i = 0; i < n; i++) + invSuff[suffixArr[i]] = i; + + // Initialize length of previous LCP + int k = 0; + + // Process all suffixes one by one starting from + // first suffix in txt[] + for (int i = 0; i < n; i++) { + /* If the current suffix is at n-1, then we don’t + have next substring to consider. So lcp is not + defined for this substring, we put zero. */ + if (invSuff[i] == n - 1) { + k = 0; + continue; + } - // An auxiliary array to store inverse of suffix array - // elements. For example if suffixArr[0] is 5, the - // invSuff[5] would store 0. This is used to get next - // suffix string from suffix array. - vector invSuff(n, 0); + /* j contains index of the next substring to + be considered to compare with the present + substring, i.e., next string in suffix array */ + int j = suffixArr[invSuff[i] + 1]; - // Fill values in invSuff[] - for (int i = 0; i < n; i++) - invSuff[suffixArr[i]] = i; + // Directly start matching from k'th index as + // at-least k-1 characters will match + while (i + k < n && j + k < n && txt[i + k] == txt[j + k]) + k++; - // Initialize length of previous LCP - int k = 0; + lcp[invSuff[i]] = k; // lcp for the present suffix. - // Process all suffixes one by one starting from - // first suffix in txt[] - for (int i = 0; i < n; i++) { - /* If the current suffix is at n-1, then we don’t - have next substring to consider. So lcp is not - defined for this substring, we put zero. */ - if (invSuff[i] == n - 1) { - k = 0; - continue; - } - - /* j contains index of the next substring to - be considered to compare with the present - substring, i.e., next string in suffix array */ - int j = suffixArr[invSuff[i] + 1]; - - // Directly start matching from k'th index as - // at-least k-1 characters will match - while (i + k < n && j + k < n && txt[i + k] == txt[j + k]) - k++; - - lcp[invSuff[i]] = k; // lcp for the present suffix. - - // Deleting the starting character from the string. - if (k > 0) - k--; - } + // Deleting the starting character from the string. + if (k > 0) + k--; + } - // return the constructed lcp array - return lcp; + // return the constructed lcp array + return lcp; } // Utility function to print an array void printArr(vector arr, int n) { - for (int i = 0; i < n; i++) - cout << arr[i] << " "; - cout << endl; + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + cout << endl; } // Driver program int main() { - string str = "banana"; + string str = "banana"; - vector suffixArr = buildSuffixArray(str, str.length()); - int n = suffixArr.size(); + vector suffixArr = buildSuffixArray(str, str.length()); + int n = suffixArr.size(); - cout << "Suffix Array : \n"; - printArr(suffixArr, n); + cout << "Suffix Array : \n"; + printArr(suffixArr, n); - vector lcp = kasai(str, suffixArr); + vector lcp = kasai(str, suffixArr); - cout << "\nLCP Array : \n"; - printArr(lcp, n); - return 0; + cout << "\nLCP Array : \n"; + printArr(lcp, n); + return 0; } diff --git a/src/test-suite/PE-benchmarks/count-1s-sorted-binary-array.cpp b/src/test-suite/PE-benchmarks/count-1s-sorted-binary-array.cpp index bd7409f0..746a96c4 100644 --- a/src/test-suite/PE-benchmarks/count-1s-sorted-binary-array.cpp +++ b/src/test-suite/PE-benchmarks/count-1s-sorted-binary-array.cpp @@ -5,28 +5,28 @@ using namespace std; /* Returns counts of 1's in arr[low..high]. The array is assumed to be sorted in non-increasing order */ int countOnes(bool arr[], int low, int high) { - if (high >= low) { - // get the middle index - int mid = low + (high - low) / 2; + if (high >= low) { + // get the middle index + int mid = low + (high - low) / 2; - // check if the element at middle index is last 1 - if ((mid == high || arr[mid + 1] == 0) && (arr[mid] == 1)) - return mid + 1; + // check if the element at middle index is last 1 + if ((mid == high || arr[mid + 1] == 0) && (arr[mid] == 1)) + return mid + 1; - // If element is not last 1, recur for right side - if (arr[mid] == 1) - return countOnes(arr, (mid + 1), high); + // If element is not last 1, recur for right side + if (arr[mid] == 1) + return countOnes(arr, (mid + 1), high); - // else recur for left side - return countOnes(arr, low, (mid - 1)); - } - return 0; + // else recur for left side + return countOnes(arr, low, (mid - 1)); + } + return 0; } /* Driver program to test above functions */ int main() { - bool arr[] = {1, 1, 1, 1, 0, 0, 0}; - int n = sizeof(arr) / sizeof(arr[0]); - cout << "Count of 1's in given array is " << countOnes(arr, 0, n - 1); - return 0; + bool arr[] = {1, 1, 1, 1, 0, 0, 0}; + int n = sizeof(arr) / sizeof(arr[0]); + cout << "Count of 1's in given array is " << countOnes(arr, 0, n - 1); + return 0; } diff --git a/src/test-suite/PE-benchmarks/count-number-binary-strings-without-consecutive-1s.cpp b/src/test-suite/PE-benchmarks/count-number-binary-strings-without-consecutive-1s.cpp index ef3e47ba..c42a6538 100644 --- a/src/test-suite/PE-benchmarks/count-number-binary-strings-without-consecutive-1s.cpp +++ b/src/test-suite/PE-benchmarks/count-number-binary-strings-without-consecutive-1s.cpp @@ -4,17 +4,17 @@ using namespace std; int countStrings(int n) { - int a[n], b[n]; - a[0] = b[0] = 1; - for (int i = 1; i < n; i++) { - a[i] = a[i - 1] + b[i - 1]; - b[i] = a[i - 1]; - } - return a[n - 1] + b[n - 1]; + int a[n], b[n]; + a[0] = b[0] = 1; + for (int i = 1; i < n; i++) { + a[i] = a[i - 1] + b[i - 1]; + b[i] = a[i - 1]; + } + return a[n - 1] + b[n - 1]; } // Driver program to test above functions int main() { - cout << countStrings(3) << endl; - return 0; + cout << countStrings(3) << endl; + return 0; } diff --git a/src/test-suite/PE-benchmarks/count-of-n-digit-numbers-whose-sum-of-digits-equals-to-given-sum.cpp b/src/test-suite/PE-benchmarks/count-of-n-digit-numbers-whose-sum-of-digits-equals-to-given-sum.cpp index 24d15e71..7bf19c53 100644 --- a/src/test-suite/PE-benchmarks/count-of-n-digit-numbers-whose-sum-of-digits-equals-to-given-sum.cpp +++ b/src/test-suite/PE-benchmarks/count-of-n-digit-numbers-whose-sum-of-digits-equals-to-given-sum.cpp @@ -9,49 +9,49 @@ unsigned long long int lookup[101][501]; // Memoization based implementation of recursive // function unsigned long long int countRec(int n, int sum) { - // Base case - if (n == 0) - return sum == 0; - - // If this subproblem is already evaluated, - // return the evaluated value - if (lookup[n][sum] != -1) - return lookup[n][sum]; - - // Initialize answer - unsigned long long int ans = 0; - - // Traverse through every digit and - // recursively count numbers beginning - // with it - for (int i = 0; i < 10; i++) - if (sum - i >= 0) - ans += countRec(n - 1, sum - i); - - return lookup[n][sum] = ans; + // Base case + if (n == 0) + return sum == 0; + + // If this subproblem is already evaluated, + // return the evaluated value + if (lookup[n][sum] != -1) + return lookup[n][sum]; + + // Initialize answer + unsigned long long int ans = 0; + + // Traverse through every digit and + // recursively count numbers beginning + // with it + for (int i = 0; i < 10; i++) + if (sum - i >= 0) + ans += countRec(n - 1, sum - i); + + return lookup[n][sum] = ans; } // This is mainly a wrapper over countRec. It // explicitly handles leading digit and calls // countRec() for remaining n. unsigned long long int finalCount(int n, int sum) { - // Initialize all entries of lookup table - memset(lookup, -1, sizeof lookup); - - // Initialize final answer - unsigned long long int ans = 0; - - // Traverse through every digit from 1 to - // 9 and count numbers beginning with it - for (int i = 1; i <= 9; i++) - if (sum - i >= 0) - ans += countRec(n - 1, sum - i); - return ans; + // Initialize all entries of lookup table + memset(lookup, -1, sizeof lookup); + + // Initialize final answer + unsigned long long int ans = 0; + + // Traverse through every digit from 1 to + // 9 and count numbers beginning with it + for (int i = 1; i <= 9; i++) + if (sum - i >= 0) + ans += countRec(n - 1, sum - i); + return ans; } // Driver program int main() { - int n = 3, sum = 5; - cout << finalCount(n, sum); - return 0; + int n = 3, sum = 5; + cout << finalCount(n, sum); + return 0; } diff --git a/src/test-suite/PE-benchmarks/count-possible-ways-to-construct-buildings.cpp b/src/test-suite/PE-benchmarks/count-possible-ways-to-construct-buildings.cpp index ec33b840..bf4a9193 100644 --- a/src/test-suite/PE-benchmarks/count-possible-ways-to-construct-buildings.cpp +++ b/src/test-suite/PE-benchmarks/count-possible-ways-to-construct-buildings.cpp @@ -4,39 +4,39 @@ using namespace std; // Returns count of possible ways for N sections int countWays(int N) { - // Base case - if (N == 1) - return 4; // 2 for one side and 4 for two sides - - // countB is count of ways with a building at the end - // countS is count of ways with a space at the end - // prev_countB and prev_countS are previous values of - // countB and countS respectively. - - // Initialize countB and countS for one side - int countB = 1, countS = 1, prev_countB, prev_countS; - - // Use the above recursive formula for calculating - // countB and countS using previous values - for (int i = 2; i <= N; i++) { - prev_countB = countB; - prev_countS = countS; - - countS = prev_countB + prev_countS; - countB = prev_countS; - } - - // Result for one side is sum of ways ending with building - // and ending with space - int result = countS + countB; - - // Result for 2 sides is square of result for one side - return (result * result); + // Base case + if (N == 1) + return 4; // 2 for one side and 4 for two sides + + // countB is count of ways with a building at the end + // countS is count of ways with a space at the end + // prev_countB and prev_countS are previous values of + // countB and countS respectively. + + // Initialize countB and countS for one side + int countB = 1, countS = 1, prev_countB, prev_countS; + + // Use the above recursive formula for calculating + // countB and countS using previous values + for (int i = 2; i <= N; i++) { + prev_countB = countB; + prev_countS = countS; + + countS = prev_countB + prev_countS; + countB = prev_countS; + } + + // Result for one side is sum of ways ending with building + // and ending with space + int result = countS + countB; + + // Result for 2 sides is square of result for one side + return (result * result); } // Driver program int main() { - int N = 3; - cout << "Count of ways for " << N << " sections is " << countWays(N); - return 0; + int N = 3; + cout << "Count of ways for " << N << " sections is " << countWays(N); + return 0; } diff --git a/src/test-suite/PE-benchmarks/count-ways-reach-nth-stair.cpp b/src/test-suite/PE-benchmarks/count-ways-reach-nth-stair.cpp index 4b53f48f..aa232274 100644 --- a/src/test-suite/PE-benchmarks/count-ways-reach-nth-stair.cpp +++ b/src/test-suite/PE-benchmarks/count-ways-reach-nth-stair.cpp @@ -4,15 +4,15 @@ // A recursive function used by countWays int countWaysUtil(int n, int m) { - int res[n]; - res[0] = 1; - res[1] = 1; - for (int i = 2; i < n; i++) { - res[i] = 0; - for (int j = 1; j <= m && j <= i; j++) - res[i] += res[i - j]; - } - return res[n - 1]; + int res[n]; + res[0] = 1; + res[1] = 1; + for (int i = 2; i < n; i++) { + res[i] = 0; + for (int j = 1; j <= m && j <= i; j++) + res[i] += res[i - j]; + } + return res[n - 1]; } // Returns number of ways to reach s'th stair @@ -20,7 +20,7 @@ int countWays(int s, int m) { return countWaysUtil(s + 1, m); } // Driver program to test above functions int main() { - int s = 4, m = 2; - printf("Nuber of ways = %d", countWays(s, m)); - return 0; + int s = 4, m = 2; + printf("Nuber of ways = %d", countWays(s, m)); + return 0; } diff --git a/src/test-suite/PE-benchmarks/cut-vertices.cpp b/src/test-suite/PE-benchmarks/cut-vertices.cpp index c0052805..9de206d7 100644 --- a/src/test-suite/PE-benchmarks/cut-vertices.cpp +++ b/src/test-suite/PE-benchmarks/cut-vertices.cpp @@ -6,25 +6,25 @@ using namespace std; // A class that represents an undirected graph class Graph { - int V; // No. of vertices - list *adj; // A dynamic array of adjacency lists - void APUtil(int v, bool visited[], int disc[], int low[], int parent[], - bool ap[]); - - public: - Graph(int V); // Constructor - void addEdge(int v, int w); // function to add an edge to graph - void AP(); // prints articulation points + int V; // No. of vertices + list *adj; // A dynamic array of adjacency lists + void APUtil(int v, bool visited[], int disc[], int low[], int parent[], + bool ap[]); + +public: + Graph(int V); // Constructor + void addEdge(int v, int w); // function to add an edge to graph + void AP(); // prints articulation points }; Graph::Graph(int V) { - this->V = V; - adj = new list[V]; + this->V = V; + adj = new list[V]; } void Graph::addEdge(int v, int w) { - adj[v].push_back(w); - adj[w].push_back(v); // Note: the graph is undirected + adj[v].push_back(w); + adj[w].push_back(v); // Note: the graph is undirected } // A recursive function that find articulation points using DFS traversal @@ -35,111 +35,111 @@ void Graph::addEdge(int v, int w) { // ap[] --> Store articulation points void Graph::APUtil(int u, bool visited[], int disc[], int low[], int parent[], bool ap[]) { - // A static variable is used for simplicity, we can avoid use of static - // variable by passing a pointer. - static int time = 0; - - // Count of children in DFS Tree - int children = 0; - - // Mark the current node as visited - visited[u] = true; - - // Initialize discovery time and low value - disc[u] = low[u] = ++time; - - // Go through all vertices aadjacent to this - list::iterator i; - for (i = adj[u].begin(); i != adj[u].end(); ++i) { - int v = *i; // v is current adjacent of u - - // If v is not visited yet, then make it a child of u - // in DFS tree and recur for it - if (!visited[v]) { - children++; - parent[v] = u; - APUtil(v, visited, disc, low, parent, ap); - - // Check if the subtree rooted with v has a connection to - // one of the ancestors of u - low[u] = min(low[u], low[v]); - - // u is an articulation point in following cases - - // (1) u is root of DFS tree and has two or more chilren. - if (parent[u] == NIL && children > 1) - ap[u] = true; - - // (2) If u is not root and low value of one of its child is more - // than discovery value of u. - if (parent[u] != NIL && low[v] >= disc[u]) - ap[u] = true; - } - - // Update low value of u for parent function calls. - else if (v != parent[u]) - low[u] = min(low[u], disc[v]); + // A static variable is used for simplicity, we can avoid use of static + // variable by passing a pointer. + static int time = 0; + + // Count of children in DFS Tree + int children = 0; + + // Mark the current node as visited + visited[u] = true; + + // Initialize discovery time and low value + disc[u] = low[u] = ++time; + + // Go through all vertices aadjacent to this + list::iterator i; + for (i = adj[u].begin(); i != adj[u].end(); ++i) { + int v = *i; // v is current adjacent of u + + // If v is not visited yet, then make it a child of u + // in DFS tree and recur for it + if (!visited[v]) { + children++; + parent[v] = u; + APUtil(v, visited, disc, low, parent, ap); + + // Check if the subtree rooted with v has a connection to + // one of the ancestors of u + low[u] = min(low[u], low[v]); + + // u is an articulation point in following cases + + // (1) u is root of DFS tree and has two or more chilren. + if (parent[u] == NIL && children > 1) + ap[u] = true; + + // (2) If u is not root and low value of one of its child is more + // than discovery value of u. + if (parent[u] != NIL && low[v] >= disc[u]) + ap[u] = true; } + + // Update low value of u for parent function calls. + else if (v != parent[u]) + low[u] = min(low[u], disc[v]); + } } // The function to do DFS traversal. It uses recursive function APUtil() void Graph::AP() { - // Mark all the vertices as not visited - bool *visited = new bool[V]; - int *disc = new int[V]; - int *low = new int[V]; - int *parent = new int[V]; - bool *ap = new bool[V]; // To store articulation points - - // Initialize parent and visited, and ap(articulation point) arrays - for (int i = 0; i < V; i++) { - parent[i] = NIL; - visited[i] = false; - ap[i] = false; - } - - // Call the recursive helper function to find articulation points - // in DFS tree rooted with vertex 'i' - for (int i = 0; i < V; i++) - if (visited[i] == false) - APUtil(i, visited, disc, low, parent, ap); - - // Now ap[] contains articulation points, print them - for (int i = 0; i < V; i++) - if (ap[i] == true) - cout << i << " "; + // Mark all the vertices as not visited + bool *visited = new bool[V]; + int *disc = new int[V]; + int *low = new int[V]; + int *parent = new int[V]; + bool *ap = new bool[V]; // To store articulation points + + // Initialize parent and visited, and ap(articulation point) arrays + for (int i = 0; i < V; i++) { + parent[i] = NIL; + visited[i] = false; + ap[i] = false; + } + + // Call the recursive helper function to find articulation points + // in DFS tree rooted with vertex 'i' + for (int i = 0; i < V; i++) + if (visited[i] == false) + APUtil(i, visited, disc, low, parent, ap); + + // Now ap[] contains articulation points, print them + for (int i = 0; i < V; i++) + if (ap[i] == true) + cout << i << " "; } // Driver program to test above function int main() { - // Create graphs given in above diagrams - cout << "\nArticulation points in first graph \n"; - Graph g1(5); - g1.addEdge(1, 0); - g1.addEdge(0, 2); - g1.addEdge(2, 1); - g1.addEdge(0, 3); - g1.addEdge(3, 4); - g1.AP(); - - cout << "\nArticulation points in second graph \n"; - Graph g2(4); - g2.addEdge(0, 1); - g2.addEdge(1, 2); - g2.addEdge(2, 3); - g2.AP(); - - cout << "\nArticulation points in third graph \n"; - Graph g3(7); - g3.addEdge(0, 1); - g3.addEdge(1, 2); - g3.addEdge(2, 0); - g3.addEdge(1, 3); - g3.addEdge(1, 4); - g3.addEdge(1, 6); - g3.addEdge(3, 5); - g3.addEdge(4, 5); - g3.AP(); - - return 0; + // Create graphs given in above diagrams + cout << "\nArticulation points in first graph \n"; + Graph g1(5); + g1.addEdge(1, 0); + g1.addEdge(0, 2); + g1.addEdge(2, 1); + g1.addEdge(0, 3); + g1.addEdge(3, 4); + g1.AP(); + + cout << "\nArticulation points in second graph \n"; + Graph g2(4); + g2.addEdge(0, 1); + g2.addEdge(1, 2); + g2.addEdge(2, 3); + g2.AP(); + + cout << "\nArticulation points in third graph \n"; + Graph g3(7); + g3.addEdge(0, 1); + g3.addEdge(1, 2); + g3.addEdge(2, 0); + g3.addEdge(1, 3); + g3.addEdge(1, 4); + g3.addEdge(1, 6); + g3.addEdge(3, 5); + g3.addEdge(4, 5); + g3.AP(); + + return 0; } diff --git a/src/test-suite/PE-benchmarks/cutting-a-rod.cpp b/src/test-suite/PE-benchmarks/cutting-a-rod.cpp index 1a04a87e..0c28ebf3 100644 --- a/src/test-suite/PE-benchmarks/cutting-a-rod.cpp +++ b/src/test-suite/PE-benchmarks/cutting-a-rod.cpp @@ -8,27 +8,27 @@ int max(int a, int b) { return (a > b) ? a : b; } /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */ int cutRod(int price[], int n) { - int val[n + 1]; - val[0] = 0; - int i, j; + int val[n + 1]; + val[0] = 0; + int i, j; - // Build the table val[] in bottom up manner and return the last entry - // from the table - for (i = 1; i <= n; i++) { - int max_val = INT_MIN; - for (j = 0; j < i; j++) - max_val = max(max_val, price[j] + val[i - j - 1]); - val[i] = max_val; - } + // Build the table val[] in bottom up manner and return the last entry + // from the table + for (i = 1; i <= n; i++) { + int max_val = INT_MIN; + for (j = 0; j < i; j++) + max_val = max(max_val, price[j] + val[i - j - 1]); + val[i] = max_val; + } - return val[n]; + return val[n]; } /* Driver program to test above functions */ int main() { - int arr[] = {1, 5, 8, 9, 10, 17, 17, 20}; - int size = sizeof(arr) / sizeof(arr[0]); - printf("Maximum Obtainable Value is %dn", cutRod(arr, size)); - getchar(); - return 0; + int arr[] = {1, 5, 8, 9, 10, 17, 17, 20}; + int size = sizeof(arr) / sizeof(arr[0]); + printf("Maximum Obtainable Value is %dn", cutRod(arr, size)); + getchar(); + return 0; } diff --git a/src/test-suite/PE-benchmarks/detect-cycle-in-a-graph.cpp b/src/test-suite/PE-benchmarks/detect-cycle-in-a-graph.cpp index e36bd8ce..8d13d410 100644 --- a/src/test-suite/PE-benchmarks/detect-cycle-in-a-graph.cpp +++ b/src/test-suite/PE-benchmarks/detect-cycle-in-a-graph.cpp @@ -6,80 +6,80 @@ using namespace std; class Graph { - int V; // No. of vertices - list *adj; // Pointer to an array containing adjacency lists - bool isCyclicUtil(int v, bool visited[], bool *rs); // used by isCyclic() - public: - Graph(int V); // Constructor - void addEdge(int v, int w); // to add an edge to graph - bool isCyclic(); // returns true if there is a cycle in this graph + int V; // No. of vertices + list *adj; // Pointer to an array containing adjacency lists + bool isCyclicUtil(int v, bool visited[], bool *rs); // used by isCyclic() +public: + Graph(int V); // Constructor + void addEdge(int v, int w); // to add an edge to graph + bool isCyclic(); // returns true if there is a cycle in this graph }; Graph::Graph(int V) { - this->V = V; - adj = new list[V]; + this->V = V; + adj = new list[V]; } void Graph::addEdge(int v, int w) { - adj[v].push_back(w); // Add w to v’s list. + adj[v].push_back(w); // Add w to v’s list. } // This function is a variation of DFSUtil() in // https://www.geeksforgeeks.org/archives/18212 bool Graph::isCyclicUtil(int v, bool visited[], bool *recStack) { - if (visited[v] == false) { - // Mark the current node as visited and part of recursion stack - visited[v] = true; - recStack[v] = true; + if (visited[v] == false) { + // Mark the current node as visited and part of recursion stack + visited[v] = true; + recStack[v] = true; - // Recur for all the vertices adjacent to this vertex - list::iterator i; - for (i = adj[v].begin(); i != adj[v].end(); ++i) { - if (!visited[*i] && isCyclicUtil(*i, visited, recStack)) - return true; - else if (recStack[*i]) - return true; - } + // Recur for all the vertices adjacent to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) { + if (!visited[*i] && isCyclicUtil(*i, visited, recStack)) + return true; + else if (recStack[*i]) + return true; } - recStack[v] = false; // remove the vertex from recursion stack - return false; + } + recStack[v] = false; // remove the vertex from recursion stack + return false; } // Returns true if the graph contains a cycle, else false. // This function is a variation of DFS() in // https://www.geeksforgeeks.org/archives/18212 bool Graph::isCyclic() { - // Mark all the vertices as not visited and not part of recursion - // stack - bool *visited = new bool[V]; - bool *recStack = new bool[V]; - for (int i = 0; i < V; i++) { - visited[i] = false; - recStack[i] = false; - } + // Mark all the vertices as not visited and not part of recursion + // stack + bool *visited = new bool[V]; + bool *recStack = new bool[V]; + for (int i = 0; i < V; i++) { + visited[i] = false; + recStack[i] = false; + } - // Call the recursive helper function to detect cycle in different - // DFS trees - for (int i = 0; i < V; i++) - if (isCyclicUtil(i, visited, recStack)) - return true; + // Call the recursive helper function to detect cycle in different + // DFS trees + for (int i = 0; i < V; i++) + if (isCyclicUtil(i, visited, recStack)) + return true; - return false; + return false; } int main() { - // Create a graph given in the above diagram - Graph g(4); - g.addEdge(0, 1); - g.addEdge(0, 2); - g.addEdge(1, 2); - g.addEdge(2, 0); - g.addEdge(2, 3); - g.addEdge(3, 3); + // Create a graph given in the above diagram + Graph g(4); + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); - if (g.isCyclic()) - cout << "Graph contains cycle"; - else - cout << "Graph doesn't contain cycle"; - return 0; + if (g.isCyclic()) + cout << "Graph contains cycle"; + else + cout << "Graph doesn't contain cycle"; + return 0; } diff --git a/src/test-suite/PE-benchmarks/detect-cycle-undirected-graph.cpp b/src/test-suite/PE-benchmarks/detect-cycle-undirected-graph.cpp index 33d6e707..635ab0d8 100644 --- a/src/test-suite/PE-benchmarks/detect-cycle-undirected-graph.cpp +++ b/src/test-suite/PE-benchmarks/detect-cycle-undirected-graph.cpp @@ -6,83 +6,83 @@ using namespace std; // Class for an undirected graph class Graph { - int V; // No. of vertices - list *adj; // Pointer to an array containing adjacency lists - bool isCyclicUtil(int v, bool visited[], int parent); + int V; // No. of vertices + list *adj; // Pointer to an array containing adjacency lists + bool isCyclicUtil(int v, bool visited[], int parent); - public: - Graph(int V); // Constructor - void addEdge(int v, int w); // to add an edge to graph - bool isCyclic(); // returns true if there is a cycle +public: + Graph(int V); // Constructor + void addEdge(int v, int w); // to add an edge to graph + bool isCyclic(); // returns true if there is a cycle }; Graph::Graph(int V) { - this->V = V; - adj = new list[V]; + this->V = V; + adj = new list[V]; } void Graph::addEdge(int v, int w) { - adj[v].push_back(w); // Add w to v’s list. - adj[w].push_back(v); // Add v to w’s list. + adj[v].push_back(w); // Add w to v’s list. + adj[w].push_back(v); // Add v to w’s list. } // A recursive function that uses visited[] and parent to detect // cycle in subgraph reachable from vertex v. bool Graph::isCyclicUtil(int v, bool visited[], int parent) { - // Mark the current node as visited - visited[v] = true; + // Mark the current node as visited + visited[v] = true; - // Recur for all the vertices adjacent to this vertex - list::iterator i; - for (i = adj[v].begin(); i != adj[v].end(); ++i) { - // If an adjacent is not visited, then recur for that adjacent - if (!visited[*i]) { - if (isCyclicUtil(*i, visited, v)) - return true; - } - - // If an adjacent is visited and not parent of current vertex, - // then there is a cycle. - else if (*i != parent) - return true; + // Recur for all the vertices adjacent to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) { + // If an adjacent is not visited, then recur for that adjacent + if (!visited[*i]) { + if (isCyclicUtil(*i, visited, v)) + return true; } - return false; + + // If an adjacent is visited and not parent of current vertex, + // then there is a cycle. + else if (*i != parent) + return true; + } + return false; } // Returns true if the graph contains a cycle, else false. bool Graph::isCyclic() { - // Mark all the vertices as not visited and not part of recursion - // stack - bool *visited = new bool[V]; - for (int i = 0; i < V; i++) - visited[i] = false; + // Mark all the vertices as not visited and not part of recursion + // stack + bool *visited = new bool[V]; + for (int i = 0; i < V; i++) + visited[i] = false; - // Call the recursive helper function to detect cycle in different - // DFS trees - for (int u = 0; u < V; u++) - if (!visited[u]) // Don't recur for u if it is already visited - if (isCyclicUtil(u, visited, -1)) - return true; + // Call the recursive helper function to detect cycle in different + // DFS trees + for (int u = 0; u < V; u++) + if (!visited[u]) // Don't recur for u if it is already visited + if (isCyclicUtil(u, visited, -1)) + return true; - return false; + return false; } // Driver program to test above functions int main() { - Graph g1(5); - g1.addEdge(1, 0); - g1.addEdge(0, 2); - g1.addEdge(2, 1); - g1.addEdge(0, 3); - g1.addEdge(3, 4); - g1.isCyclic() ? cout << "Graph contains cycle\n" - : cout << "Graph doesn't contain cycle\n"; + Graph g1(5); + g1.addEdge(1, 0); + g1.addEdge(0, 2); + g1.addEdge(2, 1); + g1.addEdge(0, 3); + g1.addEdge(3, 4); + g1.isCyclic() ? cout << "Graph contains cycle\n" + : cout << "Graph doesn't contain cycle\n"; - Graph g2(3); - g2.addEdge(0, 1); - g2.addEdge(1, 2); - g2.isCyclic() ? cout << "Graph contains cycle\n" - : cout << "Graph doesn't contain cycle\n"; + Graph g2(3); + g2.addEdge(0, 1); + g2.addEdge(1, 2); + g2.isCyclic() ? cout << "Graph contains cycle\n" + : cout << "Graph doesn't contain cycle\n"; - return 0; + return 0; } diff --git a/src/test-suite/PE-benchmarks/dfa-based-division.cpp b/src/test-suite/PE-benchmarks/dfa-based-division.cpp index 02ee1aef..ca92ea15 100644 --- a/src/test-suite/PE-benchmarks/dfa-based-division.cpp +++ b/src/test-suite/PE-benchmarks/dfa-based-division.cpp @@ -3,58 +3,58 @@ // Function to build DFA for divisor k void preprocess(int k, int Table[][2]) { - int trans0, trans1; - - // The following loop calculates the two transitions for each state, - // starting from state 0 - for (int state = 0; state < k; ++state) { - // Calculate next state for bit 0 - trans0 = state << 1; - Table[state][0] = (trans0 < k) ? trans0 : trans0 - k; - - // Calculate next state for bit 1 - trans1 = (state << 1) + 1; - Table[state][1] = (trans1 < k) ? trans1 : trans1 - k; - } + int trans0, trans1; + + // The following loop calculates the two transitions for each state, + // starting from state 0 + for (int state = 0; state < k; ++state) { + // Calculate next state for bit 0 + trans0 = state << 1; + Table[state][0] = (trans0 < k) ? trans0 : trans0 - k; + + // Calculate next state for bit 1 + trans1 = (state << 1) + 1; + Table[state][1] = (trans1 < k) ? trans1 : trans1 - k; + } } // A recursive utility function that takes a 'num' and DFA (transition // table) as input and process 'num' bit by bit over DFA void isDivisibleUtil(int num, int *state, int Table[][2]) { - // process "num" bit by bit from MSB to LSB - if (num != 0) { - isDivisibleUtil(num >> 1, state, Table); - *state = Table[*state][num & 1]; - } + // process "num" bit by bit from MSB to LSB + if (num != 0) { + isDivisibleUtil(num >> 1, state, Table); + *state = Table[*state][num & 1]; + } } // The main function that divides 'num' by k and returns the remainder int isDivisible(int num, int k) { - // Allocate memory for transition table. The table will have k*2 entries - int(*Table)[2] = (int(*)[2])malloc(k * sizeof(*Table)); + // Allocate memory for transition table. The table will have k*2 entries + int(*Table)[2] = (int(*)[2])malloc(k * sizeof(*Table)); - // Fill the transition table - preprocess(k, Table); + // Fill the transition table + preprocess(k, Table); - // Process ‘num’ over DFA and get the remainder - int state = 0; - isDivisibleUtil(num, &state, Table); + // Process ‘num’ over DFA and get the remainder + int state = 0; + isDivisibleUtil(num, &state, Table); - // Note that the final value of state is the remainder - return state; + // Note that the final value of state is the remainder + return state; } // Driver program to test above functions int main() { - int num = 47; // Number to be divided - int k = 5; // Divisor + int num = 47; // Number to be divided + int k = 5; // Divisor - int remainder = isDivisible(num, k); + int remainder = isDivisible(num, k); - if (remainder == 0) - printf("Divisible\n"); - else - printf("Not Divisible: Remainder is %d\n", remainder); + if (remainder == 0) + printf("Divisible\n"); + else + printf("Not Divisible: Remainder is %d\n", remainder); - return 0; + return 0; } diff --git a/src/test-suite/PE-benchmarks/dfs.cpp b/src/test-suite/PE-benchmarks/dfs.cpp index 1694c857..13716438 100644 --- a/src/test-suite/PE-benchmarks/dfs.cpp +++ b/src/test-suite/PE-benchmarks/dfs.cpp @@ -7,76 +7,76 @@ using namespace std; // Graph class represents a directed graph // using adjacency list representation class Graph { - int V; // No. of vertices + int V; // No. of vertices - // Pointer to an array containing - // adjacency lists - list *adj; + // Pointer to an array containing + // adjacency lists + list *adj; - // A recursive function used by DFS - void DFSUtil(int v, bool visited[]); + // A recursive function used by DFS + void DFSUtil(int v, bool visited[]); - public: - Graph(int V); // Constructor +public: + Graph(int V); // Constructor - // function to add an edge to graph - void addEdge(int v, int w); + // function to add an edge to graph + void addEdge(int v, int w); - // DFS traversal of the vertices - // reachable from v - void DFS(int v); + // DFS traversal of the vertices + // reachable from v + void DFS(int v); }; Graph::Graph(int V) { - this->V = V; - adj = new list[V]; + this->V = V; + adj = new list[V]; } void Graph::addEdge(int v, int w) { - adj[v].push_back(w); // Add w to v’s list. + adj[v].push_back(w); // Add w to v’s list. } void Graph::DFSUtil(int v, bool visited[]) { - // Mark the current node as visited and - // print it - visited[v] = true; - cout << v << " "; + // Mark the current node as visited and + // print it + visited[v] = true; + cout << v << " "; - // Recur for all the vertices adjacent - // to this vertex - list::iterator i; - for (i = adj[v].begin(); i != adj[v].end(); ++i) - if (!visited[*i]) - DFSUtil(*i, visited); + // Recur for all the vertices adjacent + // to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) + if (!visited[*i]) + DFSUtil(*i, visited); } // DFS traversal of the vertices reachable from v. // It uses recursive DFSUtil() void Graph::DFS(int v) { - // Mark all the vertices as not visited - bool *visited = new bool[V]; - for (int i = 0; i < V; i++) - visited[i] = false; + // Mark all the vertices as not visited + bool *visited = new bool[V]; + for (int i = 0; i < V; i++) + visited[i] = false; - // Call the recursive helper function - // to print DFS traversal - DFSUtil(v, visited); + // Call the recursive helper function + // to print DFS traversal + DFSUtil(v, visited); } // Driver code int main() { - // Create a graph given in the above diagram - Graph g(4); - g.addEdge(0, 1); - g.addEdge(0, 2); - g.addEdge(1, 2); - g.addEdge(2, 0); - g.addEdge(2, 3); - g.addEdge(3, 3); + // Create a graph given in the above diagram + Graph g(4); + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); - cout << "Following is Depth First Traversal" - " (starting from vertex 2) \n"; - g.DFS(2); + cout << "Following is Depth First Traversal" + " (starting from vertex 2) \n"; + g.DFS(2); - return 0; + return 0; } diff --git a/src/test-suite/PE-benchmarks/edit-distance.cpp b/src/test-suite/PE-benchmarks/edit-distance.cpp index aea56645..c5a4745e 100644 --- a/src/test-suite/PE-benchmarks/edit-distance.cpp +++ b/src/test-suite/PE-benchmarks/edit-distance.cpp @@ -7,39 +7,39 @@ using namespace std; int min(int x, int y, int z) { return min(min(x, y), z); } int editDist(string str1, string str2, int m, int n) { - // If first string is empty, the only option is to - // insert all characters of second string into first - if (m == 0) - return n; - - // If second string is empty, the only option is to - // remove all characters of first string - if (n == 0) - return m; - - // If last characters of two strings are same, nothing - // much to do. Ignore last characters and get count for - // remaining strings. - if (str1[m - 1] == str2[n - 1]) - return editDist(str1, str2, m - 1, n - 1); - - // If last characters are not same, consider all three - // operations on last character of first string, recursively - // compute minimum cost for all three operations and take - // minimum of three values. - return 1 + min(editDist(str1, str2, m, n - 1), // Insert - editDist(str1, str2, m - 1, n), // Remove - editDist(str1, str2, m - 1, n - 1) // Replace - ); + // If first string is empty, the only option is to + // insert all characters of second string into first + if (m == 0) + return n; + + // If second string is empty, the only option is to + // remove all characters of first string + if (n == 0) + return m; + + // If last characters of two strings are same, nothing + // much to do. Ignore last characters and get count for + // remaining strings. + if (str1[m - 1] == str2[n - 1]) + return editDist(str1, str2, m - 1, n - 1); + + // If last characters are not same, consider all three + // operations on last character of first string, recursively + // compute minimum cost for all three operations and take + // minimum of three values. + return 1 + min(editDist(str1, str2, m, n - 1), // Insert + editDist(str1, str2, m - 1, n), // Remove + editDist(str1, str2, m - 1, n - 1) // Replace + ); } // Driver program int main() { - // your code goes here - string str1 = "sunday"; - string str2 = "saturday"; + // your code goes here + string str1 = "sunday"; + string str2 = "saturday"; - cout << editDist(str1, str2, str1.length(), str2.length()); + cout << editDist(str1, str2, str1.length(), str2.length()); - return 0; + return 0; } diff --git a/src/test-suite/PE-benchmarks/efficient-constructtion-of-finite-automata.cpp b/src/test-suite/PE-benchmarks/efficient-constructtion-of-finite-automata.cpp index 24d55c03..0cd8a52f 100644 --- a/src/test-suite/PE-benchmarks/efficient-constructtion-of-finite-automata.cpp +++ b/src/test-suite/PE-benchmarks/efficient-constructtion-of-finite-automata.cpp @@ -6,53 +6,53 @@ using namespace std; which represents Finite Automata for a given pattern */ void computeTransFun(char *pat, int M, int TF[][NO_OF_CHARS]) { - int i, lps = 0, x; + int i, lps = 0, x; - // Fill entries in first row - for (x = 0; x < NO_OF_CHARS; x++) - TF[0][x] = 0; - TF[0][pat[0]] = 1; + // Fill entries in first row + for (x = 0; x < NO_OF_CHARS; x++) + TF[0][x] = 0; + TF[0][pat[0]] = 1; - // Fill entries in other rows - for (i = 1; i <= M; i++) { - // Copy values from row at index lps - for (x = 0; x < NO_OF_CHARS; x++) - TF[i][x] = TF[lps][x]; + // Fill entries in other rows + for (i = 1; i <= M; i++) { + // Copy values from row at index lps + for (x = 0; x < NO_OF_CHARS; x++) + TF[i][x] = TF[lps][x]; - // Update the entry corresponding to this character - TF[i][pat[i]] = i + 1; + // Update the entry corresponding to this character + TF[i][pat[i]] = i + 1; - // Update lps for next row to be filled - if (i < M) - lps = TF[lps][pat[i]]; - } + // Update lps for next row to be filled + if (i < M) + lps = TF[lps][pat[i]]; + } } /* Prints all occurrences of pat in txt */ void search(char pat[], char txt[]) { - int M = strlen(pat); - int N = strlen(txt); + int M = strlen(pat); + int N = strlen(txt); - int TF[M + 1][NO_OF_CHARS]; + int TF[M + 1][NO_OF_CHARS]; - computeTransFun(pat, M, TF); + computeTransFun(pat, M, TF); - // process text over FA. - int i, j = 0; - for (i = 0; i < N; i++) { - j = TF[j][txt[i]]; - if (j == M) { - cout << "pattern found at index " << i - M + 1 << endl; - } + // process text over FA. + int i, j = 0; + for (i = 0; i < N; i++) { + j = TF[j][txt[i]]; + if (j == M) { + cout << "pattern found at index " << i - M + 1 << endl; } + } } /* Driver code */ int main() { - char txt[] = "GEEKS FOR GEEKS"; - char pat[] = "GEEKS"; - search(pat, txt); - return 0; + char txt[] = "GEEKS FOR GEEKS"; + char pat[] = "GEEKS"; + search(pat, txt); + return 0; } // This is code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/egg-dropping-puzzle.cpp b/src/test-suite/PE-benchmarks/egg-dropping-puzzle.cpp index bf09ad6c..3b81c3af 100644 --- a/src/test-suite/PE-benchmarks/egg-dropping-puzzle.cpp +++ b/src/test-suite/PE-benchmarks/egg-dropping-puzzle.cpp @@ -8,44 +8,44 @@ int max(int a, int b) { return (a > b) ? a : b; } /* Function to get minimum number of trials needed in worst case with n eggs and k floors */ int eggDrop(int n, int k) { - /* A 2D table where entery eggFloor[i][j] will represent minimum - number of trials needed for i eggs and j floors. */ - int eggFloor[n + 1][k + 1]; - int res; - int i, j, x; + /* A 2D table where entery eggFloor[i][j] will represent minimum + number of trials needed for i eggs and j floors. */ + int eggFloor[n + 1][k + 1]; + int res; + int i, j, x; - // We need one trial for one floor and0 trials for 0 floors - for (i = 1; i <= n; i++) { - eggFloor[i][1] = 1; - eggFloor[i][0] = 0; - } + // We need one trial for one floor and0 trials for 0 floors + for (i = 1; i <= n; i++) { + eggFloor[i][1] = 1; + eggFloor[i][0] = 0; + } - // We always need j trials for one egg and j floors. - for (j = 1; j <= k; j++) - eggFloor[1][j] = j; + // We always need j trials for one egg and j floors. + for (j = 1; j <= k; j++) + eggFloor[1][j] = j; - // Fill rest of the entries in table using optimal substructure - // property - for (i = 2; i <= n; i++) { - for (j = 2; j <= k; j++) { - eggFloor[i][j] = INT_MAX; - for (x = 1; x <= j; x++) { - res = 1 + max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); - if (res < eggFloor[i][j]) - eggFloor[i][j] = res; - } - } + // Fill rest of the entries in table using optimal substructure + // property + for (i = 2; i <= n; i++) { + for (j = 2; j <= k; j++) { + eggFloor[i][j] = INT_MAX; + for (x = 1; x <= j; x++) { + res = 1 + max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); + if (res < eggFloor[i][j]) + eggFloor[i][j] = res; + } } + } - // eggFloor[n][k] holds the result - return eggFloor[n][k]; + // eggFloor[n][k] holds the result + return eggFloor[n][k]; } /* Driver program to test to pront printDups*/ int main() { - int n = 2, k = 36; - printf("nMinimum number of trials in worst case with %d eggs and " - "%d floors is %d \n", - n, k, eggDrop(n, k)); - return 0; + int n = 2, k = 36; + printf("nMinimum number of trials in worst case with %d eggs and " + "%d floors is %d \n", + n, k, eggDrop(n, k)); + return 0; } diff --git a/src/test-suite/PE-benchmarks/euler-circuit-directed-graph.cpp b/src/test-suite/PE-benchmarks/euler-circuit-directed-graph.cpp index 78a85781..76315ede 100644 --- a/src/test-suite/PE-benchmarks/euler-circuit-directed-graph.cpp +++ b/src/test-suite/PE-benchmarks/euler-circuit-directed-graph.cpp @@ -6,143 +6,143 @@ using namespace std; // A class that represents an undirected graph class Graph { - int V; // No. of vertices - list *adj; // A dynamic array of adjacency lists - int *in; - - public: - // Constructor and destructor - Graph(int V); - ~Graph() { - delete[] adj; - delete[] in; - } - - // function to add an edge to graph - void addEdge(int v, int w) { - adj[v].push_back(w); - (in[w])++; - } - - // Method to check if this graph is Eulerian or not - bool isEulerianCycle(); - - // Method to check if all non-zero degree vertices are connected - bool isSC(); - - // Function to do DFS starting from v. Used in isConnected(); - void DFSUtil(int v, bool visited[]); - - Graph getTranspose(); + int V; // No. of vertices + list *adj; // A dynamic array of adjacency lists + int *in; + +public: + // Constructor and destructor + Graph(int V); + ~Graph() { + delete[] adj; + delete[] in; + } + + // function to add an edge to graph + void addEdge(int v, int w) { + adj[v].push_back(w); + (in[w])++; + } + + // Method to check if this graph is Eulerian or not + bool isEulerianCycle(); + + // Method to check if all non-zero degree vertices are connected + bool isSC(); + + // Function to do DFS starting from v. Used in isConnected(); + void DFSUtil(int v, bool visited[]); + + Graph getTranspose(); }; Graph::Graph(int V) { - this->V = V; - adj = new list[V]; - in = new int[V]; - for (int i = 0; i < V; i++) - in[i] = 0; + this->V = V; + adj = new list[V]; + in = new int[V]; + for (int i = 0; i < V; i++) + in[i] = 0; } /* This function returns true if the directed graph has a eulerian cycle, otherwise returns false */ bool Graph::isEulerianCycle() { - // Check if all non-zero degree vertices are connected - if (isSC() == false) - return false; + // Check if all non-zero degree vertices are connected + if (isSC() == false) + return false; - // Check if in degree and out degree of every vertex is same - for (int i = 0; i < V; i++) - if (adj[i].size() != in[i]) - return false; + // Check if in degree and out degree of every vertex is same + for (int i = 0; i < V; i++) + if (adj[i].size() != in[i]) + return false; - return true; + return true; } // A recursive function to do DFS starting from v void Graph::DFSUtil(int v, bool visited[]) { - // Mark the current node as visited and print it - visited[v] = true; - - // Recur for all the vertices adjacent to this vertex - list::iterator i; - for (i = adj[v].begin(); i != adj[v].end(); ++i) - if (!visited[*i]) - DFSUtil(*i, visited); + // Mark the current node as visited and print it + visited[v] = true; + + // Recur for all the vertices adjacent to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) + if (!visited[*i]) + DFSUtil(*i, visited); } // Function that returns reverse (or transpose) of this graph // This function is needed in isSC() Graph Graph::getTranspose() { - Graph g(V); - for (int v = 0; v < V; v++) { - // Recur for all the vertices adjacent to this vertex - list::iterator i; - for (i = adj[v].begin(); i != adj[v].end(); ++i) { - g.adj[*i].push_back(v); - (g.in[v])++; - } + Graph g(V); + for (int v = 0; v < V; v++) { + // Recur for all the vertices adjacent to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) { + g.adj[*i].push_back(v); + (g.in[v])++; } - return g; + } + return g; } // This function returns true if all non-zero degree vertices of // graph are strongly connected (Please refer // https://www.geeksforgeeks.org/connectivity-in-a-directed-graph/ ) bool Graph::isSC() { - // Mark all the vertices as not visited (For first DFS) - bool visited[V]; - for (int i = 0; i < V; i++) - visited[i] = false; - - // Find the first vertex with non-zero degree - int n; - for (n = 0; n < V; n++) - if (adj[n].size() > 0) - break; - - // Do DFS traversal starting from first non zero degrees vertex. - DFSUtil(n, visited); - - // If DFS traversal doesn't visit all vertices, then return false. - for (int i = 0; i < V; i++) - if (adj[i].size() > 0 && visited[i] == false) - return false; - - // Create a reversed graph - Graph gr = getTranspose(); - - // Mark all the vertices as not visited (For second DFS) - for (int i = 0; i < V; i++) - visited[i] = false; - - // Do DFS for reversed graph starting from first vertex. - // Staring Vertex must be same starting point of first DFS - gr.DFSUtil(n, visited); - - // If all vertices are not visited in second DFS, then - // return false - for (int i = 0; i < V; i++) - if (adj[i].size() > 0 && visited[i] == false) - return false; - - return true; + // Mark all the vertices as not visited (For first DFS) + bool visited[V]; + for (int i = 0; i < V; i++) + visited[i] = false; + + // Find the first vertex with non-zero degree + int n; + for (n = 0; n < V; n++) + if (adj[n].size() > 0) + break; + + // Do DFS traversal starting from first non zero degrees vertex. + DFSUtil(n, visited); + + // If DFS traversal doesn't visit all vertices, then return false. + for (int i = 0; i < V; i++) + if (adj[i].size() > 0 && visited[i] == false) + return false; + + // Create a reversed graph + Graph gr = getTranspose(); + + // Mark all the vertices as not visited (For second DFS) + for (int i = 0; i < V; i++) + visited[i] = false; + + // Do DFS for reversed graph starting from first vertex. + // Staring Vertex must be same starting point of first DFS + gr.DFSUtil(n, visited); + + // If all vertices are not visited in second DFS, then + // return false + for (int i = 0; i < V; i++) + if (adj[i].size() > 0 && visited[i] == false) + return false; + + return true; } // Driver program to test above functions int main() { - // Create a graph given in the above diagram - Graph g(5); - g.addEdge(1, 0); - g.addEdge(0, 2); - g.addEdge(2, 1); - g.addEdge(0, 3); - g.addEdge(3, 4); - g.addEdge(4, 0); - - if (g.isEulerianCycle()) - cout << "Given directed graph is eulerian n"; - else - cout << "Given directed graph is NOT eulerian n"; - return 0; + // Create a graph given in the above diagram + Graph g(5); + g.addEdge(1, 0); + g.addEdge(0, 2); + g.addEdge(2, 1); + g.addEdge(0, 3); + g.addEdge(3, 4); + g.addEdge(4, 0); + + if (g.isEulerianCycle()) + cout << "Given directed graph is eulerian n"; + else + cout << "Given directed graph is NOT eulerian n"; + return 0; } diff --git a/src/test-suite/PE-benchmarks/eulerian-path-and-circuit.cpp b/src/test-suite/PE-benchmarks/eulerian-path-and-circuit.cpp index a514a394..85f4b1b3 100644 --- a/src/test-suite/PE-benchmarks/eulerian-path-and-circuit.cpp +++ b/src/test-suite/PE-benchmarks/eulerian-path-and-circuit.cpp @@ -5,72 +5,72 @@ using namespace std; // A class that represents an undirected graph class Graph { - int V; // No. of vertices - list *adj; // A dynamic array of adjacency lists - public: - // Constructor and destructor - Graph(int V) { - this->V = V; - adj = new list[V]; - } - ~Graph() { delete[] adj; } // To avoid memory leak - - // function to add an edge to graph - void addEdge(int v, int w); - - // Method to check if this graph is Eulerian or not - int isEulerian(); - - // Method to check if all non-zero degree vertices are connected - bool isConnected(); - - // Function to do DFS starting from v. Used in isConnected(); - void DFSUtil(int v, bool visited[]); + int V; // No. of vertices + list *adj; // A dynamic array of adjacency lists +public: + // Constructor and destructor + Graph(int V) { + this->V = V; + adj = new list[V]; + } + ~Graph() { delete[] adj; } // To avoid memory leak + + // function to add an edge to graph + void addEdge(int v, int w); + + // Method to check if this graph is Eulerian or not + int isEulerian(); + + // Method to check if all non-zero degree vertices are connected + bool isConnected(); + + // Function to do DFS starting from v. Used in isConnected(); + void DFSUtil(int v, bool visited[]); }; void Graph::addEdge(int v, int w) { - adj[v].push_back(w); - adj[w].push_back(v); // Note: the graph is undirected + adj[v].push_back(w); + adj[w].push_back(v); // Note: the graph is undirected } void Graph::DFSUtil(int v, bool visited[]) { - // Mark the current node as visited and print it - visited[v] = true; - - // Recur for all the vertices adjacent to this vertex - list::iterator i; - for (i = adj[v].begin(); i != adj[v].end(); ++i) - if (!visited[*i]) - DFSUtil(*i, visited); + // Mark the current node as visited and print it + visited[v] = true; + + // Recur for all the vertices adjacent to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) + if (!visited[*i]) + DFSUtil(*i, visited); } // Method to check if all non-zero degree vertices are connected. // It mainly does DFS traversal starting from bool Graph::isConnected() { - // Mark all the vertices as not visited - bool visited[V]; - int i; - for (i = 0; i < V; i++) - visited[i] = false; - - // Find a vertex with non-zero degree - for (i = 0; i < V; i++) - if (adj[i].size() != 0) - break; - - // If there are no edges in the graph, return true - if (i == V) - return true; + // Mark all the vertices as not visited + bool visited[V]; + int i; + for (i = 0; i < V; i++) + visited[i] = false; + + // Find a vertex with non-zero degree + for (i = 0; i < V; i++) + if (adj[i].size() != 0) + break; + + // If there are no edges in the graph, return true + if (i == V) + return true; - // Start DFS traversal from a vertex with non-zero degree - DFSUtil(i, visited); + // Start DFS traversal from a vertex with non-zero degree + DFSUtil(i, visited); - // Check if all non-zero degree vertices are visited - for (i = 0; i < V; i++) - if (visited[i] == false && adj[i].size() > 0) - return false; + // Check if all non-zero degree vertices are visited + for (i = 0; i < V; i++) + if (visited[i] == false && adj[i].size() > 0) + return false; - return true; + return true; } /* The function returns one of the following values @@ -78,78 +78,78 @@ bool Graph::isConnected() { 1 --> If graph has an Euler path (Semi-Eulerian) 2 --> If graph has an Euler Circuit (Eulerian) */ int Graph::isEulerian() { - // Check if all non-zero degree vertices are connected - if (isConnected() == false) - return 0; - - // Count vertices with odd degree - int odd = 0; - for (int i = 0; i < V; i++) - if (adj[i].size() & 1) - odd++; - - // If count is more than 2, then graph is not Eulerian - if (odd > 2) - return 0; - - // If odd count is 2, then semi-eulerian. - // If odd count is 0, then eulerian - // Note that odd count can never be 1 for undirected graph - return (odd) ? 1 : 2; + // Check if all non-zero degree vertices are connected + if (isConnected() == false) + return 0; + + // Count vertices with odd degree + int odd = 0; + for (int i = 0; i < V; i++) + if (adj[i].size() & 1) + odd++; + + // If count is more than 2, then graph is not Eulerian + if (odd > 2) + return 0; + + // If odd count is 2, then semi-eulerian. + // If odd count is 0, then eulerian + // Note that odd count can never be 1 for undirected graph + return (odd) ? 1 : 2; } // Function to run test cases void test(Graph &g) { - int res = g.isEulerian(); - if (res == 0) - cout << "graph is not Eulerian\n"; - else if (res == 1) - cout << "graph has a Euler path\n"; - else - cout << "graph has a Euler cycle\n"; + int res = g.isEulerian(); + if (res == 0) + cout << "graph is not Eulerian\n"; + else if (res == 1) + cout << "graph has a Euler path\n"; + else + cout << "graph has a Euler cycle\n"; } // Driver program to test above function int main() { - // Let us create and test graphs shown in above figures - Graph g1(5); - g1.addEdge(1, 0); - g1.addEdge(0, 2); - g1.addEdge(2, 1); - g1.addEdge(0, 3); - g1.addEdge(3, 4); - test(g1); - - Graph g2(5); - g2.addEdge(1, 0); - g2.addEdge(0, 2); - g2.addEdge(2, 1); - g2.addEdge(0, 3); - g2.addEdge(3, 4); - g2.addEdge(4, 0); - test(g2); - - Graph g3(5); - g3.addEdge(1, 0); - g3.addEdge(0, 2); - g3.addEdge(2, 1); - g3.addEdge(0, 3); - g3.addEdge(3, 4); - g3.addEdge(1, 3); - test(g3); - - // Let us create a graph with 3 vertices - // connected in the form of cycle - Graph g4(3); - g4.addEdge(0, 1); - g4.addEdge(1, 2); - g4.addEdge(2, 0); - test(g4); - - // Let us create a graph with all veritces - // with zero degree - Graph g5(3); - test(g5); - - return 0; + // Let us create and test graphs shown in above figures + Graph g1(5); + g1.addEdge(1, 0); + g1.addEdge(0, 2); + g1.addEdge(2, 1); + g1.addEdge(0, 3); + g1.addEdge(3, 4); + test(g1); + + Graph g2(5); + g2.addEdge(1, 0); + g2.addEdge(0, 2); + g2.addEdge(2, 1); + g2.addEdge(0, 3); + g2.addEdge(3, 4); + g2.addEdge(4, 0); + test(g2); + + Graph g3(5); + g3.addEdge(1, 0); + g3.addEdge(0, 2); + g3.addEdge(2, 1); + g3.addEdge(0, 3); + g3.addEdge(3, 4); + g3.addEdge(1, 3); + test(g3); + + // Let us create a graph with 3 vertices + // connected in the form of cycle + Graph g4(3); + g4.addEdge(0, 1); + g4.addEdge(1, 2); + g4.addEdge(2, 0); + test(g4); + + // Let us create a graph with all veritces + // with zero degree + Graph g5(3); + test(g5); + + return 0; } diff --git a/src/test-suite/PE-benchmarks/find-common-elements-three-sorted-arrays.cpp b/src/test-suite/PE-benchmarks/find-common-elements-three-sorted-arrays.cpp index 24e43986..f04b8f18 100644 --- a/src/test-suite/PE-benchmarks/find-common-elements-three-sorted-arrays.cpp +++ b/src/test-suite/PE-benchmarks/find-common-elements-three-sorted-arrays.cpp @@ -4,44 +4,44 @@ using namespace std; // This function prints common elements in ar1 void findCommon(int ar1[], int ar2[], int ar3[], int n1, int n2, int n3) { - // Initialize starting indexes for ar1[], ar2[] and ar3[] - int i = 0, j = 0, k = 0; + // Initialize starting indexes for ar1[], ar2[] and ar3[] + int i = 0, j = 0, k = 0; - // Iterate through three arrays while all arrays have elements - while (i < n1 && j < n2 && k < n3) { - // If x = y and y = z, print any of them and move ahead - // in all arrays - if (ar1[i] == ar2[j] && ar2[j] == ar3[k]) { - cout << ar1[i] << " "; - i++; - j++; - k++; - } + // Iterate through three arrays while all arrays have elements + while (i < n1 && j < n2 && k < n3) { + // If x = y and y = z, print any of them and move ahead + // in all arrays + if (ar1[i] == ar2[j] && ar2[j] == ar3[k]) { + cout << ar1[i] << " "; + i++; + j++; + k++; + } - // x < y - else if (ar1[i] < ar2[j]) - i++; + // x < y + else if (ar1[i] < ar2[j]) + i++; - // y < z - else if (ar2[j] < ar3[k]) - j++; + // y < z + else if (ar2[j] < ar3[k]) + j++; - // We reach here when x > y and z < y, i.e., z is smallest - else - k++; - } + // We reach here when x > y and z < y, i.e., z is smallest + else + k++; + } } // Driver program to test above function int main() { - int ar1[] = {1, 5, 10, 20, 40, 80}; - int ar2[] = {6, 7, 20, 80, 100}; - int ar3[] = {3, 4, 15, 20, 30, 70, 80, 120}; - int n1 = sizeof(ar1) / sizeof(ar1[0]); - int n2 = sizeof(ar2) / sizeof(ar2[0]); - int n3 = sizeof(ar3) / sizeof(ar3[0]); + int ar1[] = {1, 5, 10, 20, 40, 80}; + int ar2[] = {6, 7, 20, 80, 100}; + int ar3[] = {3, 4, 15, 20, 30, 70, 80, 120}; + int n1 = sizeof(ar1) / sizeof(ar1[0]); + int n2 = sizeof(ar2) / sizeof(ar2[0]); + int n3 = sizeof(ar3) / sizeof(ar3[0]); - cout << "Common Elements are "; - findCommon(ar1, ar2, ar3, n1, n2, n3); - return 0; + cout << "Common Elements are "; + findCommon(ar1, ar2, ar3, n1, n2, n3); + return 0; } diff --git a/src/test-suite/PE-benchmarks/find-k-closest-elements-given-value.cpp b/src/test-suite/PE-benchmarks/find-k-closest-elements-given-value.cpp index 264a32d9..22c06703 100644 --- a/src/test-suite/PE-benchmarks/find-k-closest-elements-given-value.cpp +++ b/src/test-suite/PE-benchmarks/find-k-closest-elements-given-value.cpp @@ -4,66 +4,66 @@ which elements are smaller than or equal to x and after which greater than x)*/ int findCrossOver(int arr[], int low, int high, int x) { - // Base cases - if (arr[high] <= x) // x is greater than all - return high; - if (arr[low] > x) // x is smaller than all - return low; + // Base cases + if (arr[high] <= x) // x is greater than all + return high; + if (arr[low] > x) // x is smaller than all + return low; - // Find the middle point - int mid = (low + high) / 2; /* low + (high - low)/2 */ + // Find the middle point + int mid = (low + high) / 2; /* low + (high - low)/2 */ - /* If x is same as middle element, then return mid */ - if (arr[mid] <= x && arr[mid + 1] > x) - return mid; + /* If x is same as middle element, then return mid */ + if (arr[mid] <= x && arr[mid + 1] > x) + return mid; - /* If x is greater than arr[mid], then either arr[mid + 1] - is ceiling of x or ceiling lies in arr[mid+1...high] */ - if (arr[mid] < x) - return findCrossOver(arr, mid + 1, high, x); + /* If x is greater than arr[mid], then either arr[mid + 1] + is ceiling of x or ceiling lies in arr[mid+1...high] */ + if (arr[mid] < x) + return findCrossOver(arr, mid + 1, high, x); - return findCrossOver(arr, low, mid - 1, x); + return findCrossOver(arr, low, mid - 1, x); } // This function prints k closest elements to x in arr[]. // n is the number of elements in arr[] void printKclosest(int arr[], int x, int k, int n) { - // Find the crossover point - int l = findCrossOver(arr, 0, n - 1, x); - int r = l + 1; // Right index to search - int count = 0; // To keep track of count of elements already printed + // Find the crossover point + int l = findCrossOver(arr, 0, n - 1, x); + int r = l + 1; // Right index to search + int count = 0; // To keep track of count of elements already printed - // If x is present in arr[], then reduce left index - // Assumption: all elements in arr[] are distinct - if (arr[l] == x) - l--; + // If x is present in arr[], then reduce left index + // Assumption: all elements in arr[] are distinct + if (arr[l] == x) + l--; - // Compare elements on left and right of crossover - // point to find the k closest elements - while (l >= 0 && r < n && count < k) { - if (x - arr[l] < arr[r] - x) - printf("%d ", arr[l--]); - else - printf("%d ", arr[r++]); - count++; - } + // Compare elements on left and right of crossover + // point to find the k closest elements + while (l >= 0 && r < n && count < k) { + if (x - arr[l] < arr[r] - x) + printf("%d ", arr[l--]); + else + printf("%d ", arr[r++]); + count++; + } - // If there are no more elements on right side, then - // print left elements - while (count < k && l >= 0) - printf("%d ", arr[l--]), count++; + // If there are no more elements on right side, then + // print left elements + while (count < k && l >= 0) + printf("%d ", arr[l--]), count++; - // If there are no more elements on left side, then - // print right elements - while (count < k && r < n) - printf("%d ", arr[r++]), count++; + // If there are no more elements on left side, then + // print right elements + while (count < k && r < n) + printf("%d ", arr[r++]), count++; } /* Driver program to check above functions */ int main() { - int arr[] = {12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56}; - int n = sizeof(arr) / sizeof(arr[0]); - int x = 35, k = 4; - printKclosest(arr, x, 4, n); - return 0; + int arr[] = {12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56}; + int n = sizeof(arr) / sizeof(arr[0]); + int x = 35, k = 4; + printKclosest(arr, x, 4, n); + return 0; } diff --git a/src/test-suite/PE-benchmarks/find-length-of-the-longest-consecutive-path-in-a-character-matrix.cpp b/src/test-suite/PE-benchmarks/find-length-of-the-longest-consecutive-path-in-a-character-matrix.cpp index 89ea5852..b85dca2b 100644 --- a/src/test-suite/PE-benchmarks/find-length-of-the-longest-consecutive-path-in-a-character-matrix.cpp +++ b/src/test-suite/PE-benchmarks/find-length-of-the-longest-consecutive-path-in-a-character-matrix.cpp @@ -14,9 +14,9 @@ int dp[R][C]; // check whether mat[i][j] is a valid cell or not. bool isvalid(int i, int j) { - if (i < 0 || j < 0 || i >= R || j >= C) - return false; - return true; + if (i < 0 || j < 0 || i >= R || j >= C) + return false; + return true; } // Check whether current character is adjacent to previous @@ -27,25 +27,25 @@ bool isadjacent(char prev, char curr) { return ((curr - prev) == 1); } // character processed in the parent call.. also mat[i][j] // is our current character. int getLenUtil(char mat[R][C], int i, int j, char prev) { - // If this cell is not valid or current character is not - // adjacent to previous one (e.g. d is not adjacent to b ) - // or if this cell is already included in the path than return 0. - if (!isvalid(i, j) || !isadjacent(prev, mat[i][j])) - return 0; + // If this cell is not valid or current character is not + // adjacent to previous one (e.g. d is not adjacent to b ) + // or if this cell is already included in the path than return 0. + if (!isvalid(i, j) || !isadjacent(prev, mat[i][j])) + return 0; - // If this subproblem is already solved , return the answer - if (dp[i][j] != -1) - return dp[i][j]; + // If this subproblem is already solved , return the answer + if (dp[i][j] != -1) + return dp[i][j]; - int ans = 0; // Initialize answer + int ans = 0; // Initialize answer - // recur for paths with different adjacent cells and store - // the length of longest path. - for (int k = 0; k < 8; k++) - ans = max(ans, 1 + getLenUtil(mat, i + x[k], j + y[k], mat[i][j])); + // recur for paths with different adjacent cells and store + // the length of longest path. + for (int k = 0; k < 8; k++) + ans = max(ans, 1 + getLenUtil(mat, i + x[k], j + y[k], mat[i][j])); - // save the answer and return - return dp[i][j] = ans; + // save the answer and return + return dp[i][j] = ans; } // Returns length of the longest path with all characters consecutive @@ -53,31 +53,31 @@ int getLenUtil(char mat[R][C], int i, int j, char prev) { // is used to store results of subproblems, then it calls // recursive DFS based function getLenUtil() to find max length path int getLen(char mat[R][C], char s) { - memset(dp, -1, sizeof dp); - int ans = 0; + memset(dp, -1, sizeof dp); + int ans = 0; - for (int i = 0; i < R; i++) { - for (int j = 0; j < C; j++) { - // check for each possible starting point - if (mat[i][j] == s) { + for (int i = 0; i < R; i++) { + for (int j = 0; j < C; j++) { + // check for each possible starting point + if (mat[i][j] == s) { - // recur for all eight adjacent cells - for (int k = 0; k < 8; k++) - ans = max(ans, 1 + getLenUtil(mat, i + x[k], j + y[k], s)); - } - } + // recur for all eight adjacent cells + for (int k = 0; k < 8; k++) + ans = max(ans, 1 + getLenUtil(mat, i + x[k], j + y[k], s)); + } } - return ans; + } + return ans; } // Driver program int main() { - char mat[R][C] = {{'a', 'c', 'd'}, {'h', 'b', 'a'}, {'i', 'g', 'f'}}; + char mat[R][C] = {{'a', 'c', 'd'}, {'h', 'b', 'a'}, {'i', 'g', 'f'}}; - cout << getLen(mat, 'a') << endl; - cout << getLen(mat, 'e') << endl; - cout << getLen(mat, 'b') << endl; - cout << getLen(mat, 'f') << endl; - return 0; + cout << getLen(mat, 'a') << endl; + cout << getLen(mat, 'e') << endl; + cout << getLen(mat, 'b') << endl; + cout << getLen(mat, 'f') << endl; + return 0; } diff --git a/src/test-suite/PE-benchmarks/find-minimum-number-of-coins-that-make-a-change.cpp b/src/test-suite/PE-benchmarks/find-minimum-number-of-coins-that-make-a-change.cpp index c550cce3..ae88ed05 100644 --- a/src/test-suite/PE-benchmarks/find-minimum-number-of-coins-that-make-a-change.cpp +++ b/src/test-suite/PE-benchmarks/find-minimum-number-of-coins-that-make-a-change.cpp @@ -5,36 +5,36 @@ using namespace std; // m is size of coins array (number of different coins) int minCoins(int coins[], int m, int V) { - // table[i] will be storing the minimum number of coins - // required for i value. So table[V] will have result - int table[V + 1]; + // table[i] will be storing the minimum number of coins + // required for i value. So table[V] will have result + int table[V + 1]; - // Base case (If given value V is 0) - table[0] = 0; + // Base case (If given value V is 0) + table[0] = 0; - // Initialize all table values as Infinite - for (int i = 1; i <= V; i++) - table[i] = INT_MAX; + // Initialize all table values as Infinite + for (int i = 1; i <= V; i++) + table[i] = INT_MAX; - // Compute minimum coins required for all - // values from 1 to V - for (int i = 1; i <= V; i++) { - // Go through all coins smaller than i - for (int j = 0; j < m; j++) - if (coins[j] <= i) { - int sub_res = table[i - coins[j]]; - if (sub_res != INT_MAX && sub_res + 1 < table[i]) - table[i] = sub_res + 1; - } - } - return table[V]; + // Compute minimum coins required for all + // values from 1 to V + for (int i = 1; i <= V; i++) { + // Go through all coins smaller than i + for (int j = 0; j < m; j++) + if (coins[j] <= i) { + int sub_res = table[i - coins[j]]; + if (sub_res != INT_MAX && sub_res + 1 < table[i]) + table[i] = sub_res + 1; + } + } + return table[V]; } // Driver program to test above function int main() { - int coins[] = {9, 6, 5, 1}; - int m = sizeof(coins) / sizeof(coins[0]); - int V = 11; - cout << "Minimum coins required is " << minCoins(coins, m, V); - return 0; + int coins[] = {9, 6, 5, 1}; + int m = sizeof(coins) / sizeof(coins[0]); + int V = 11; + cout << "Minimum coins required is " << minCoins(coins, m, V); + return 0; } diff --git a/src/test-suite/PE-benchmarks/find-parity.cpp b/src/test-suite/PE-benchmarks/find-parity.cpp index e7196b9f..3973a23a 100644 --- a/src/test-suite/PE-benchmarks/find-parity.cpp +++ b/src/test-suite/PE-benchmarks/find-parity.cpp @@ -8,19 +8,19 @@ using namespace std; // if n has odd parity, and returns 0 if n has even // parity bool getParity(unsigned int n) { - bool parity = 0; - while (n) { - parity = !parity; - n = n & (n - 1); - } - return parity; + bool parity = 0; + while (n) { + parity = !parity; + n = n & (n - 1); + } + return parity; } /* Driver program to test getParity() */ int main() { - unsigned int n = 7; - cout << "Parity of no " << n << " = " << (getParity(n) ? "odd" : "even"); + unsigned int n = 7; + cout << "Parity of no " << n << " = " << (getParity(n) ? "odd" : "even"); - getchar(); - return 0; + getchar(); + return 0; } diff --git a/src/test-suite/PE-benchmarks/find-two-non-repeating-element.cpp b/src/test-suite/PE-benchmarks/find-two-non-repeating-element.cpp index f6f18ba5..3991acc1 100644 --- a/src/test-suite/PE-benchmarks/find-two-non-repeating-element.cpp +++ b/src/test-suite/PE-benchmarks/find-two-non-repeating-element.cpp @@ -5,36 +5,36 @@ using namespace std; *x and *y to nonr-epeating elements in an array arr[] of size n*/ void get2NonRepeatingNos(int arr[], int n, int *x, int *y) { - int Xor = arr[0]; /* Will hold Xor of all elements */ - int set_bit_no; /* Will have only single set bit of Xor */ - int i; - *x = 0; - *y = 0; + int Xor = arr[0]; /* Will hold Xor of all elements */ + int set_bit_no; /* Will have only single set bit of Xor */ + int i; + *x = 0; + *y = 0; - /* Get the Xor of all elements */ - for (i = 1; i < n; i++) - Xor ^= arr[i]; + /* Get the Xor of all elements */ + for (i = 1; i < n; i++) + Xor ^= arr[i]; - /* Get the rightmost set bit in set_bit_no */ - set_bit_no = Xor & ~(Xor - 1); + /* Get the rightmost set bit in set_bit_no */ + set_bit_no = Xor & ~(Xor - 1); - /* Now divide elements in two sets by comparing rightmost set - bit of Xor with bit at same position in each element. */ - for (i = 0; i < n; i++) { - if (arr[i] & set_bit_no) - *x = *x ^ arr[i]; /*Xor of first set */ - else - *y = *y ^ arr[i]; /*Xor of second set*/ - } + /* Now divide elements in two sets by comparing rightmost set + bit of Xor with bit at same position in each element. */ + for (i = 0; i < n; i++) { + if (arr[i] & set_bit_no) + *x = *x ^ arr[i]; /*Xor of first set */ + else + *y = *y ^ arr[i]; /*Xor of second set*/ + } } /* Driver code */ int main() { - int arr[] = {2, 3, 7, 9, 11, 2, 3, 11}; - int *x = new int[(sizeof(int))]; - int *y = new int[(sizeof(int))]; - get2NonRepeatingNos(arr, 8, x, y); - cout << "The non-repeating elements are " << *x << " and " << *y; + int arr[] = {2, 3, 7, 9, 11, 2, 3, 11}; + int *x = new int[(sizeof(int))]; + int *y = new int[(sizeof(int))]; + get2NonRepeatingNos(arr, 8, x, y); + cout << "The non-repeating elements are " << *x << " and " << *y; } // This code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/finite-automata-algorithm.cpp b/src/test-suite/PE-benchmarks/finite-automata-algorithm.cpp index 02e9b62f..dc5bda82 100644 --- a/src/test-suite/PE-benchmarks/finite-automata-algorithm.cpp +++ b/src/test-suite/PE-benchmarks/finite-automata-algorithm.cpp @@ -5,64 +5,64 @@ #define NO_OF_CHARS 256 int getNextState(char *pat, int M, int state, int x) { - // If the character c is same as next character - // in pattern,then simply increment state - if (state < M && x == pat[state]) - return state + 1; + // If the character c is same as next character + // in pattern,then simply increment state + if (state < M && x == pat[state]) + return state + 1; - // ns stores the result which is next state - int ns, i; + // ns stores the result which is next state + int ns, i; - // ns finally contains the longest prefix - // which is also suffix in "pat[0..state-1]c" + // ns finally contains the longest prefix + // which is also suffix in "pat[0..state-1]c" - // Start from the largest possible value - // and stop when you find a prefix which - // is also suffix - for (ns = state; ns > 0; ns--) { - if (pat[ns - 1] == x) { - for (i = 0; i < ns - 1; i++) - if (pat[i] != pat[state - ns + 1 + i]) - break; - if (i == ns - 1) - return ns; - } + // Start from the largest possible value + // and stop when you find a prefix which + // is also suffix + for (ns = state; ns > 0; ns--) { + if (pat[ns - 1] == x) { + for (i = 0; i < ns - 1; i++) + if (pat[i] != pat[state - ns + 1 + i]) + break; + if (i == ns - 1) + return ns; } + } - return 0; + return 0; } /* This function builds the TF table which represents4 Finite Automata for a given pattern */ void computeTF(char *pat, int M, int TF[][NO_OF_CHARS]) { - int state, x; - for (state = 0; state <= M; ++state) - for (x = 0; x < NO_OF_CHARS; ++x) - TF[state][x] = getNextState(pat, M, state, x); + int state, x; + for (state = 0; state <= M; ++state) + for (x = 0; x < NO_OF_CHARS; ++x) + TF[state][x] = getNextState(pat, M, state, x); } /* Prints all occurrences of pat in txt */ void search(char *pat, char *txt) { - int M = strlen(pat); - int N = strlen(txt); + int M = strlen(pat); + int N = strlen(txt); - int TF[M + 1][NO_OF_CHARS]; + int TF[M + 1][NO_OF_CHARS]; - computeTF(pat, M, TF); + computeTF(pat, M, TF); - // Process txt over FA. - int i, state = 0; - for (i = 0; i < N; i++) { - state = TF[state][txt[i]]; - if (state == M) - printf("\n Pattern found at index %d", i - M + 1); - } + // Process txt over FA. + int i, state = 0; + for (i = 0; i < N; i++) { + state = TF[state][txt[i]]; + if (state == M) + printf("\n Pattern found at index %d", i - M + 1); + } } // Driver program to test above function int main() { - char *txt = "AABAACAADAABAAABAA"; - char *pat = "AABA"; - search(pat, txt); - return 0; + char *txt = "AABAACAADAABAAABAA"; + char *pat = "AABA"; + search(pat, txt); + return 0; } diff --git a/src/test-suite/PE-benchmarks/floyd-warshall.cpp b/src/test-suite/PE-benchmarks/floyd-warshall.cpp index b9ce291c..42bb8d0a 100644 --- a/src/test-suite/PE-benchmarks/floyd-warshall.cpp +++ b/src/test-suite/PE-benchmarks/floyd-warshall.cpp @@ -16,84 +16,82 @@ void printSolution(int dist[][V]); // Solves the all-pairs shortest path // problem using Floyd Warshall algorithm void floydWarshall(int graph[][V]) { - /* dist[][] will be the output matrix - that will finally have the shortest - distances between every pair of vertices */ - int dist[V][V], i, j, k; + /* dist[][] will be the output matrix + that will finally have the shortest + distances between every pair of vertices */ + int dist[V][V], i, j, k; - /* Initialize the solution matrix same - as input graph matrix. Or we can say - the initial values of shortest distances - are based on shortest paths considering - no intermediate vertex. */ - for (i = 0; i < V; i++) - for (j = 0; j < V; j++) - dist[i][j] = graph[i][j]; + /* Initialize the solution matrix same + as input graph matrix. Or we can say + the initial values of shortest distances + are based on shortest paths considering + no intermediate vertex. */ + for (i = 0; i < V; i++) + for (j = 0; j < V; j++) + dist[i][j] = graph[i][j]; - /* Add all vertices one by one to - the set of intermediate vertices. - ---> Before start of an iteration, - we have shortest distances between all - pairs of vertices such that the - shortest distances consider only the - vertices in set {0, 1, 2, .. k-1} as - intermediate vertices. - ----> After the end of an iteration, - vertex no. k is added to the set of - intermediate vertices and the set becomes {0, 1, 2, .. k} */ - for (k = 0; k < V; k++) { - // Pick all vertices as source one by one - for (i = 0; i < V; i++) { - // Pick all vertices as destination for the - // above picked source - for (j = 0; j < V; j++) { - // If vertex k is on the shortest path from - // i to j, then update the value of dist[i][j] - if (dist[i][k] + dist[k][j] < dist[i][j]) - dist[i][j] = dist[i][k] + dist[k][j]; - } - } + /* Add all vertices one by one to + the set of intermediate vertices. + ---> Before start of an iteration, + we have shortest distances between all + pairs of vertices such that the + shortest distances consider only the + vertices in set {0, 1, 2, .. k-1} as + intermediate vertices. + ----> After the end of an iteration, + vertex no. k is added to the set of + intermediate vertices and the set becomes {0, 1, 2, .. k} */ + for (k = 0; k < V; k++) { + // Pick all vertices as source one by one + for (i = 0; i < V; i++) { + // Pick all vertices as destination for the + // above picked source + for (j = 0; j < V; j++) { + // If vertex k is on the shortest path from + // i to j, then update the value of dist[i][j] + if (dist[i][k] + dist[k][j] < dist[i][j]) + dist[i][j] = dist[i][k] + dist[k][j]; + } } + } - // Print the shortest distance matrix - printSolution(dist); + // Print the shortest distance matrix + printSolution(dist); } /* A utility function to print solution */ void printSolution(int dist[][V]) { - cout << "The following matrix shows the shortest distances" - " between every pair of vertices \n"; - for (int i = 0; i < V; i++) { - for (int j = 0; j < V; j++) { - if (dist[i][j] == INF) - cout << "INF" - << " "; - else - cout << dist[i][j] << " "; - } - cout << endl; + cout << "The following matrix shows the shortest distances" + " between every pair of vertices \n"; + for (int i = 0; i < V; i++) { + for (int j = 0; j < V; j++) { + if (dist[i][j] == INF) + cout << "INF" + << " "; + else + cout << dist[i][j] << " "; } + cout << endl; + } } // Driver code int main() { - /* Let us create the following weighted graph - 10 - (0)------->(3) - | /|\ - 5 | | - | | 1 - \|/ | - (1)------->(2) - 3 */ - int graph[V][V] = {{0, 5, INF, 10}, - {INF, 0, 3, INF}, - {INF, INF, 0, 1}, - {INF, INF, INF, 0}}; + /* Let us create the following weighted graph + 10 + (0)------->(3) + | /|\ + 5 | | + | | 1 + \|/ | + (1)------->(2) + 3 */ + int graph[V][V] = { + {0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0}}; - // Print the solution - floydWarshall(graph); - return 0; + // Print the solution + floydWarshall(graph); + return 0; } // This code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/graph-coloring.cpp b/src/test-suite/PE-benchmarks/graph-coloring.cpp index f81647da..847e6f2a 100644 --- a/src/test-suite/PE-benchmarks/graph-coloring.cpp +++ b/src/test-suite/PE-benchmarks/graph-coloring.cpp @@ -5,96 +5,96 @@ using namespace std; // A class that represents an undirected graph class Graph { - int V; // No. of vertices - list *adj; // A dynamic array of adjacency lists - public: - // Constructor and destructor - Graph(int V) { - this->V = V; - adj = new list[V]; - } - ~Graph() { delete[] adj; } - - // function to add an edge to graph - void addEdge(int v, int w); - - // Prints greedy coloring of the vertices - void greedyColoring(); + int V; // No. of vertices + list *adj; // A dynamic array of adjacency lists +public: + // Constructor and destructor + Graph(int V) { + this->V = V; + adj = new list[V]; + } + ~Graph() { delete[] adj; } + + // function to add an edge to graph + void addEdge(int v, int w); + + // Prints greedy coloring of the vertices + void greedyColoring(); }; void Graph::addEdge(int v, int w) { - adj[v].push_back(w); - adj[w].push_back(v); // Note: the graph is undirected + adj[v].push_back(w); + adj[w].push_back(v); // Note: the graph is undirected } // Assigns colors (starting from 0) to all vertices and prints // the assignment of colors void Graph::greedyColoring() { - int result[V]; - - // Assign the first color to first vertex - result[0] = 0; - - // Initialize remaining V-1 vertices as unassigned - for (int u = 1; u < V; u++) - result[u] = -1; // no color is assigned to u - - // A temporary array to store the available colors. True - // value of available[cr] would mean that the color cr is - // assigned to one of its adjacent vertices - bool available[V]; - for (int cr = 0; cr < V; cr++) - available[cr] = false; - - // Assign colors to remaining V-1 vertices - for (int u = 1; u < V; u++) { - // Process all adjacent vertices and flag their colors - // as unavailable - list::iterator i; - for (i = adj[u].begin(); i != adj[u].end(); ++i) - if (result[*i] != -1) - available[result[*i]] = true; - - // Find the first available color - int cr; - for (cr = 0; cr < V; cr++) - if (available[cr] == false) - break; - - result[u] = cr; // Assign the found color - - // Reset the values back to false for the next iteration - for (i = adj[u].begin(); i != adj[u].end(); ++i) - if (result[*i] != -1) - available[result[*i]] = false; - } - - // print the result - for (int u = 0; u < V; u++) - cout << "Vertex " << u << " ---> Color " << result[u] << endl; + int result[V]; + + // Assign the first color to first vertex + result[0] = 0; + + // Initialize remaining V-1 vertices as unassigned + for (int u = 1; u < V; u++) + result[u] = -1; // no color is assigned to u + + // A temporary array to store the available colors. True + // value of available[cr] would mean that the color cr is + // assigned to one of its adjacent vertices + bool available[V]; + for (int cr = 0; cr < V; cr++) + available[cr] = false; + + // Assign colors to remaining V-1 vertices + for (int u = 1; u < V; u++) { + // Process all adjacent vertices and flag their colors + // as unavailable + list::iterator i; + for (i = adj[u].begin(); i != adj[u].end(); ++i) + if (result[*i] != -1) + available[result[*i]] = true; + + // Find the first available color + int cr; + for (cr = 0; cr < V; cr++) + if (available[cr] == false) + break; + + result[u] = cr; // Assign the found color + + // Reset the values back to false for the next iteration + for (i = adj[u].begin(); i != adj[u].end(); ++i) + if (result[*i] != -1) + available[result[*i]] = false; + } + + // print the result + for (int u = 0; u < V; u++) + cout << "Vertex " << u << " ---> Color " << result[u] << endl; } // Driver program to test above function int main() { - Graph g1(5); - g1.addEdge(0, 1); - g1.addEdge(0, 2); - g1.addEdge(1, 2); - g1.addEdge(1, 3); - g1.addEdge(2, 3); - g1.addEdge(3, 4); - cout << "Coloring of graph 1 \n"; - g1.greedyColoring(); - - Graph g2(5); - g2.addEdge(0, 1); - g2.addEdge(0, 2); - g2.addEdge(1, 2); - g2.addEdge(1, 4); - g2.addEdge(2, 4); - g2.addEdge(4, 3); - cout << "\nColoring of graph 2 \n"; - g2.greedyColoring(); - - return 0; + Graph g1(5); + g1.addEdge(0, 1); + g1.addEdge(0, 2); + g1.addEdge(1, 2); + g1.addEdge(1, 3); + g1.addEdge(2, 3); + g1.addEdge(3, 4); + cout << "Coloring of graph 1 \n"; + g1.greedyColoring(); + + Graph g2(5); + g2.addEdge(0, 1); + g2.addEdge(0, 2); + g2.addEdge(1, 2); + g2.addEdge(1, 4); + g2.addEdge(2, 4); + g2.addEdge(4, 3); + cout << "\nColoring of graph 2 \n"; + g2.greedyColoring(); + + return 0; } diff --git a/src/test-suite/PE-benchmarks/hamiltonian-cycle-backtracking.cpp b/src/test-suite/PE-benchmarks/hamiltonian-cycle-backtracking.cpp index 85d5a6c5..9c8ad353 100644 --- a/src/test-suite/PE-benchmarks/hamiltonian-cycle-backtracking.cpp +++ b/src/test-suite/PE-benchmarks/hamiltonian-cycle-backtracking.cpp @@ -13,58 +13,58 @@ the vertex v can be added at index 'pos' in the Hamiltonian Cycle constructed so far (stored in 'path[]') */ bool isSafe(int v, bool graph[V][V], int path[], int pos) { - /* Check if this vertex is an adjacent - vertex of the previously added vertex. */ - if (graph[path[pos - 1]][v] == 0) - return false; - - /* Check if the vertex has already been included. - This step can be optimized by creating - an array of size V */ - for (int i = 0; i < pos; i++) - if (path[i] == v) - return false; - - return true; + /* Check if this vertex is an adjacent + vertex of the previously added vertex. */ + if (graph[path[pos - 1]][v] == 0) + return false; + + /* Check if the vertex has already been included. + This step can be optimized by creating + an array of size V */ + for (int i = 0; i < pos; i++) + if (path[i] == v) + return false; + + return true; } /* A recursive utility function to solve hamiltonian cycle problem */ bool hamCycleUtil(bool graph[V][V], int path[], int pos) { - /* base case: If all vertices are - included in Hamiltonian Cycle */ - if (pos == V) { - // And if there is an edge from the - // last included vertex to the first vertex - if (graph[path[pos - 1]][path[0]] == 1) - return true; - else - return false; - } - - // Try different vertices as a next candidate - // in Hamiltonian Cycle. We don't try for 0 as - // we included 0 as starting point in hamCycle() - for (int v = 1; v < V; v++) { - /* Check if this vertex can be added - // to Hamiltonian Cycle */ - if (isSafe(v, graph, path, pos)) { - path[pos] = v; - - /* recur to construct rest of the path */ - if (hamCycleUtil(graph, path, pos + 1) == true) - return true; - - /* If adding vertex v doesn't lead to a solution, - then remove it */ - path[pos] = -1; - } + /* base case: If all vertices are + included in Hamiltonian Cycle */ + if (pos == V) { + // And if there is an edge from the + // last included vertex to the first vertex + if (graph[path[pos - 1]][path[0]] == 1) + return true; + else + return false; + } + + // Try different vertices as a next candidate + // in Hamiltonian Cycle. We don't try for 0 as + // we included 0 as starting point in hamCycle() + for (int v = 1; v < V; v++) { + /* Check if this vertex can be added + // to Hamiltonian Cycle */ + if (isSafe(v, graph, path, pos)) { + path[pos] = v; + + /* recur to construct rest of the path */ + if (hamCycleUtil(graph, path, pos + 1) == true) + return true; + + /* If adding vertex v doesn't lead to a solution, + then remove it */ + path[pos] = -1; } + } - /* If no vertex can be added to - Hamiltonian Cycle constructed so far, - then return false */ - return false; + /* If no vertex can be added to + Hamiltonian Cycle constructed so far, + then return false */ + return false; } /* This function solves the Hamiltonian Cycle problem @@ -75,69 +75,69 @@ and prints the path. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */ bool hamCycle(bool graph[V][V]) { - int *path = new int[V]; - for (int i = 0; i < V; i++) - path[i] = -1; - - /* Let us put vertex 0 as the first vertex in the path. - If there is a Hamiltonian Cycle, then the path can be - started from any point of the cycle as the graph is undirected */ - path[0] = 0; - if (hamCycleUtil(graph, path, 1) == false) { - cout << "\nSolution does not exist"; - return false; - } + int *path = new int[V]; + for (int i = 0; i < V; i++) + path[i] = -1; + + /* Let us put vertex 0 as the first vertex in the path. + If there is a Hamiltonian Cycle, then the path can be + started from any point of the cycle as the graph is undirected */ + path[0] = 0; + if (hamCycleUtil(graph, path, 1) == false) { + cout << "\nSolution does not exist"; + return false; + } - printSolution(path); - return true; + printSolution(path); + return true; } /* A utility function to print solution */ void printSolution(int path[]) { - cout << "Solution Exists:" - " Following is one Hamiltonian Cycle \n"; - for (int i = 0; i < V; i++) - cout << path[i] << " "; - - // Let us print the first vertex again - // to show the complete cycle - cout << path[0] << " "; - cout << endl; + cout << "Solution Exists:" + " Following is one Hamiltonian Cycle \n"; + for (int i = 0; i < V; i++) + cout << path[i] << " "; + + // Let us print the first vertex again + // to show the complete cycle + cout << path[0] << " "; + cout << endl; } // Driver Code int main() { - /* Let us create the following graph - (0)--(1)--(2) - | / \ | - | / \ | - | / \ | - (3)-------(4) */ - 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}}; - - // Print the solution - hamCycle(graph1); - - /* Let us create the following graph - (0)--(1)--(2) - | / \ | - | / \ | - | / \ | - (3) (4) */ - 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; + /* Let us create the following graph + (0)--(1)--(2) + | / \ | + | / \ | + | / \ | + (3)-------(4) */ + 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}}; + + // Print the solution + hamCycle(graph1); + + /* Let us create the following graph + (0)--(1)--(2) + | / \ | + | / \ | + | / \ | + (3) (4) */ + 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; } // This is code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/insertion-sort-for-singly-linked-list.cpp b/src/test-suite/PE-benchmarks/insertion-sort-for-singly-linked-list.cpp index eed7ad56..168910ce 100644 --- a/src/test-suite/PE-benchmarks/insertion-sort-for-singly-linked-list.cpp +++ b/src/test-suite/PE-benchmarks/insertion-sort-for-singly-linked-list.cpp @@ -4,8 +4,8 @@ /* Link list node */ struct Node { - int data; - struct Node *next; + int data; + struct Node *next; }; // Function to insert a given node in a sorted linked list @@ -13,89 +13,89 @@ void sortedInsert(struct Node **, struct Node *); // function to sort a singly linked list using insertion sort void insertionSort(struct Node **head_ref) { - // Initialize sorted linked list - struct Node *sorted = NULL; + // Initialize sorted linked list + struct Node *sorted = NULL; - // Traverse the given linked list and insert every - // node to sorted - struct Node *current = *head_ref; - while (current != NULL) { - // Store next for next iteration - struct Node *next = current->next; + // Traverse the given linked list and insert every + // node to sorted + struct Node *current = *head_ref; + while (current != NULL) { + // Store next for next iteration + struct Node *next = current->next; - // insert current in sorted linked list - sortedInsert(&sorted, current); + // insert current in sorted linked list + sortedInsert(&sorted, current); - // Update current - current = next; - } + // Update current + current = next; + } - // Update head_ref to point to sorted linked list - *head_ref = sorted; + // Update head_ref to point to sorted linked list + *head_ref = sorted; } /* function to insert a new_node in a list. Note that this function expects a pointer to head_ref as this can modify the head of the input linked list (similar to push())*/ void sortedInsert(struct Node **head_ref, struct Node *new_node) { - struct Node *current; - /* Special case for the head end */ - if (*head_ref == NULL || (*head_ref)->data >= new_node->data) { - new_node->next = *head_ref; - *head_ref = new_node; - } else { - /* Locate the node before the point of insertion */ - current = *head_ref; - while (current->next != NULL && current->next->data < new_node->data) { - current = current->next; - } - new_node->next = current->next; - current->next = new_node; + struct Node *current; + /* Special case for the head end */ + if (*head_ref == NULL || (*head_ref)->data >= new_node->data) { + new_node->next = *head_ref; + *head_ref = new_node; + } else { + /* Locate the node before the point of insertion */ + current = *head_ref; + while (current->next != NULL && current->next->data < new_node->data) { + current = current->next; } + new_node->next = current->next; + current->next = new_node; + } } /* BELOW FUNCTIONS ARE JUST UTILITY TO TEST sortedInsert */ /* Function to print linked list */ void printList(struct Node *head) { - struct Node *temp = head; - while (temp != NULL) { - printf("%d ", temp->data); - temp = temp->next; - } + struct Node *temp = head; + while (temp != NULL) { + printf("%d ", temp->data); + temp = temp->next; + } } /* A utility function to insert a node at the beginning of linked list */ void push(struct Node **head_ref, int new_data) { - /* allocate node */ - struct Node *new_node = new Node; + /* allocate node */ + struct Node *new_node = new Node; - /* put in the data */ - new_node->data = new_data; + /* put in the data */ + new_node->data = new_data; - /* link the old list off the new node */ - new_node->next = (*head_ref); + /* link the old list off the new node */ + new_node->next = (*head_ref); - /* move the head to point to the new node */ - (*head_ref) = new_node; + /* move the head to point to the new node */ + (*head_ref) = new_node; } // Driver program to test above functions int main() { - struct Node *a = NULL; - push(&a, 5); - push(&a, 20); - push(&a, 4); - push(&a, 3); - push(&a, 30); + struct Node *a = NULL; + push(&a, 5); + push(&a, 20); + push(&a, 4); + push(&a, 3); + push(&a, 30); - printf("Linked List before sorting \n"); - printList(a); + printf("Linked List before sorting \n"); + printList(a); - insertionSort(&a); + insertionSort(&a); - printf("\nLinked List after sorting \n"); - printList(a); + printf("\nLinked List after sorting \n"); + printList(a); - return 0; + return 0; } diff --git a/src/test-suite/PE-benchmarks/karatsuba.cpp b/src/test-suite/PE-benchmarks/karatsuba.cpp index 751e3a01..8f8cb998 100644 --- a/src/test-suite/PE-benchmarks/karatsuba.cpp +++ b/src/test-suite/PE-benchmarks/karatsuba.cpp @@ -9,95 +9,94 @@ using namespace std; // same length by adding leading 0s in the smaller string. Returns the // the new length int makeEqualLength(string &str1, string &str2) { - int len1 = str1.size(); - int len2 = str2.size(); - if (len1 < len2) { - for (int i = 0; i < len2 - len1; i++) - str1 = '0' + str1; - return len2; - } else if (len1 > len2) { - for (int i = 0; i < len1 - len2; i++) - str2 = '0' + str2; - } - return len1; // If len1 >= len2 + int len1 = str1.size(); + int len2 = str2.size(); + if (len1 < len2) { + for (int i = 0; i < len2 - len1; i++) + str1 = '0' + str1; + return len2; + } else if (len1 > len2) { + for (int i = 0; i < len1 - len2; i++) + str2 = '0' + str2; + } + return len1; // If len1 >= len2 } // The main function that adds two bit sequences and returns the addition string addBitStrings(string first, string second) { - string result; // To store the sum bits + string result; // To store the sum bits - // make the lengths same before adding - int length = makeEqualLength(first, second); - int carry = 0; // Initialize carry + // make the lengths same before adding + int length = makeEqualLength(first, second); + int carry = 0; // Initialize carry - // Add all bits one by one - for (int i = length - 1; i >= 0; i--) { - int firstBit = first.at(i) - '0'; - int secondBit = second.at(i) - '0'; + // Add all bits one by one + for (int i = length - 1; i >= 0; i--) { + int firstBit = first.at(i) - '0'; + int secondBit = second.at(i) - '0'; - // boolean expression for sum of 3 bits - int sum = (firstBit ^ secondBit ^ carry) + '0'; + // boolean expression for sum of 3 bits + int sum = (firstBit ^ secondBit ^ carry) + '0'; - result = (char)sum + result; + result = (char)sum + result; - // boolean expression for 3-bit addition - carry = - (firstBit & secondBit) | (secondBit & carry) | (firstBit & carry); - } + // boolean expression for 3-bit addition + carry = (firstBit & secondBit) | (secondBit & carry) | (firstBit & carry); + } - // if overflow, then add a leading 1 - if (carry) - result = '1' + result; + // if overflow, then add a leading 1 + if (carry) + result = '1' + result; - return result; + return result; } // A utility function to multiply single bits of strings a and b int multiplyiSingleBit(string a, string b) { - return (a[0] - '0') * (b[0] - '0'); + return (a[0] - '0') * (b[0] - '0'); } // The main function that multiplies two bit strings X and Y and returns // result as long integer long int multiply(string X, string Y) { - // Find the maximum of lengths of x and Y and make length - // of smaller string same as that of larger string - int n = makeEqualLength(X, Y); - - // Base cases - if (n == 0) - return 0; - if (n == 1) - return multiplyiSingleBit(X, Y); - - int fh = n / 2; // First half of string, floor(n/2) - int sh = (n - fh); // Second half of string, ceil(n/2) - - // Find the first half and second half of first string. - // Refer http://goo.gl/lLmgn for substr method - string Xl = X.substr(0, fh); - string Xr = X.substr(fh, sh); - - // Find the first half and second half of second string - string Yl = Y.substr(0, fh); - string Yr = Y.substr(fh, sh); - - // Recursively calculate the three products of inputs of size n/2 - long int P1 = multiply(Xl, Yl); - long int P2 = multiply(Xr, Yr); - long int P3 = multiply(addBitStrings(Xl, Xr), addBitStrings(Yl, Yr)); - - // Combine the three products to get the final result. - return P1 * (1 << (2 * sh)) + (P3 - P1 - P2) * (1 << sh) + P2; + // Find the maximum of lengths of x and Y and make length + // of smaller string same as that of larger string + int n = makeEqualLength(X, Y); + + // Base cases + if (n == 0) + return 0; + if (n == 1) + return multiplyiSingleBit(X, Y); + + int fh = n / 2; // First half of string, floor(n/2) + int sh = (n - fh); // Second half of string, ceil(n/2) + + // Find the first half and second half of first string. + // Refer http://goo.gl/lLmgn for substr method + string Xl = X.substr(0, fh); + string Xr = X.substr(fh, sh); + + // Find the first half and second half of second string + string Yl = Y.substr(0, fh); + string Yr = Y.substr(fh, sh); + + // Recursively calculate the three products of inputs of size n/2 + long int P1 = multiply(Xl, Yl); + long int P2 = multiply(Xr, Yr); + long int P3 = multiply(addBitStrings(Xl, Xr), addBitStrings(Yl, Yr)); + + // Combine the three products to get the final result. + return P1 * (1 << (2 * sh)) + (P3 - P1 - P2) * (1 << sh) + P2; } // Driver program to test above functions int main() { - printf("%ld\n", multiply("1100", "1010")); - printf("%ld\n", multiply("110", "1010")); - printf("%ld\n", multiply("11", "1010")); - printf("%ld\n", multiply("1", "1010")); - printf("%ld\n", multiply("0", "1010")); - printf("%ld\n", multiply("111", "111")); - printf("%ld\n", multiply("11", "11")); + printf("%ld\n", multiply("1100", "1010")); + printf("%ld\n", multiply("110", "1010")); + printf("%ld\n", multiply("11", "1010")); + printf("%ld\n", multiply("1", "1010")); + printf("%ld\n", multiply("0", "1010")); + printf("%ld\n", multiply("111", "111")); + printf("%ld\n", multiply("11", "11")); } diff --git a/src/test-suite/PE-benchmarks/kmp-algorithm.cpp b/src/test-suite/PE-benchmarks/kmp-algorithm.cpp index 1212d972..aef946e1 100644 --- a/src/test-suite/PE-benchmarks/kmp-algorithm.cpp +++ b/src/test-suite/PE-benchmarks/kmp-algorithm.cpp @@ -6,78 +6,78 @@ void computeLPSArray(char *pat, int M, int *lps); // Prints occurrences of txt[] in pat[] void KMPSearch(char *pat, char *txt) { - int M = strlen(pat); - int N = strlen(txt); + int M = strlen(pat); + int N = strlen(txt); - // create lps[] that will hold the longest prefix suffix - // values for pattern - int lps[M]; + // create lps[] that will hold the longest prefix suffix + // values for pattern + int lps[M]; - // Preprocess the pattern (calculate lps[] array) - computeLPSArray(pat, M, lps); + // Preprocess the pattern (calculate lps[] array) + computeLPSArray(pat, M, lps); - int i = 0; // index for txt[] - int j = 0; // index for pat[] - while (i < N) { - if (pat[j] == txt[i]) { - j++; - i++; - } + int i = 0; // index for txt[] + int j = 0; // index for pat[] + while (i < N) { + if (pat[j] == txt[i]) { + j++; + i++; + } - if (j == M) { - printf("Found pattern at index %d ", i - j); - j = lps[j - 1]; - } + if (j == M) { + printf("Found pattern at index %d ", i - j); + j = lps[j - 1]; + } - // mismatch after j matches - else if (i < N && pat[j] != txt[i]) { - // Do not match lps[0..lps[j-1]] characters, - // they will match anyway - if (j != 0) - j = lps[j - 1]; - else - i = i + 1; - } + // mismatch after j matches + else if (i < N && pat[j] != txt[i]) { + // Do not match lps[0..lps[j-1]] characters, + // they will match anyway + if (j != 0) + j = lps[j - 1]; + else + i = i + 1; } + } } // Fills lps[] for given patttern pat[0..M-1] void computeLPSArray(char *pat, int M, int *lps) { - // length of the previous longest prefix suffix - int len = 0; + // length of the previous longest prefix suffix + int len = 0; - lps[0] = 0; // lps[0] is always 0 + lps[0] = 0; // lps[0] is always 0 - // the loop calculates lps[i] for i = 1 to M-1 - int i = 1; - while (i < M) { - if (pat[i] == pat[len]) { - len++; - lps[i] = len; - i++; - } else // (pat[i] != pat[len]) - { - // This is tricky. Consider the example. - // AAACAAAA and i = 7. The idea is similar - // to search step. - if (len != 0) { - len = lps[len - 1]; + // the loop calculates lps[i] for i = 1 to M-1 + int i = 1; + while (i < M) { + if (pat[i] == pat[len]) { + len++; + lps[i] = len; + i++; + } else // (pat[i] != pat[len]) + { + // This is tricky. Consider the example. + // AAACAAAA and i = 7. The idea is similar + // to search step. + if (len != 0) { + len = lps[len - 1]; - // Also, note that we do not increment - // i here - } else // if (len == 0) - { - lps[i] = 0; - i++; - } - } + // Also, note that we do not increment + // i here + } else // if (len == 0) + { + lps[i] = 0; + i++; + } } + } } // Driver program to test above function int main() { - char txt[] = "ABABDABACDABABCABAB"; - char pat[] = "ABABCABAB"; - KMPSearch(pat, txt); - return 0; + char txt[] = "ABABDABACDABABCABAB"; + char pat[] = "ABABCABAB"; + KMPSearch(pat, txt); + return 0; } diff --git a/src/test-suite/PE-benchmarks/kth-smallestlargest-element-unsorted-array-set-2-expected-linear-time.cpp b/src/test-suite/PE-benchmarks/kth-smallestlargest-element-unsorted-array-set-2-expected-linear-time.cpp index d717f8c2..657b64cf 100644 --- a/src/test-suite/PE-benchmarks/kth-smallestlargest-element-unsorted-array-set-2-expected-linear-time.cpp +++ b/src/test-suite/PE-benchmarks/kth-smallestlargest-element-unsorted-array-set-2-expected-linear-time.cpp @@ -9,60 +9,60 @@ int randomPartition(int arr[], int l, int r); // This function returns k'th smallest element in arr[l..r] using // QuickSort based method. ASSUMPTION: ELEMENTS IN ARR[] ARE DISTINCT int kthSmallest(int arr[], int l, int r, int k) { - // If k is smaller than number of elements in array - if (k > 0 && k <= r - l + 1) { - // Partition the array around a random element and - // get position of pivot element in sorted array - int pos = randomPartition(arr, l, r); + // If k is smaller than number of elements in array + if (k > 0 && k <= r - l + 1) { + // Partition the array around a random element and + // get position of pivot element in sorted array + int pos = randomPartition(arr, l, r); - // If position is same as k - if (pos - l == k - 1) - return arr[pos]; - if (pos - l > k - 1) // If position is more, recur for left subarray - return kthSmallest(arr, l, pos - 1, k); + // If position is same as k + if (pos - l == k - 1) + return arr[pos]; + if (pos - l > k - 1) // If position is more, recur for left subarray + return kthSmallest(arr, l, pos - 1, k); - // Else recur for right subarray - return kthSmallest(arr, pos + 1, r, k - pos + l - 1); - } + // Else recur for right subarray + return kthSmallest(arr, pos + 1, r, k - pos + l - 1); + } - // If k is more than the number of elements in the array - return INT_MAX; + // If k is more than the number of elements in the array + return INT_MAX; } void swap(int *a, int *b) { - int temp = *a; - *a = *b; - *b = temp; + int temp = *a; + *a = *b; + *b = temp; } // Standard partition process of QuickSort(). It considers the last // element as pivot and moves all smaller element to left of it and // greater elements to right. This function is used by randomPartition() int partition(int arr[], int l, int r) { - int x = arr[r], i = l; - for (int j = l; j <= r - 1; j++) { - if (arr[j] <= x) { - swap(&arr[i], &arr[j]); - i++; - } + int x = arr[r], i = l; + for (int j = l; j <= r - 1; j++) { + if (arr[j] <= x) { + swap(&arr[i], &arr[j]); + i++; } - swap(&arr[i], &arr[r]); - return i; + } + swap(&arr[i], &arr[r]); + return i; } // Picks a random pivot element between l and r and partitions // arr[l..r] around the randomly picked element using partition() int randomPartition(int arr[], int l, int r) { - int n = r - l + 1; - int pivot = rand() % n; - swap(&arr[l + pivot], &arr[r]); - return partition(arr, l, r); + int n = r - l + 1; + int pivot = rand() % n; + swap(&arr[l + pivot], &arr[r]); + return partition(arr, l, r); } // Driver program to test above methods int main() { - int arr[] = {12, 3, 5, 7, 4, 19, 26}; - int n = sizeof(arr) / sizeof(arr[0]), k = 3; - cout << "K'th smallest element is " << kthSmallest(arr, 0, n - 1, k); - return 0; + int arr[] = {12, 3, 5, 7, 4, 19, 26}; + int n = sizeof(arr) / sizeof(arr[0]), k = 3; + cout << "K'th smallest element is " << kthSmallest(arr, 0, n - 1, k); + return 0; } diff --git a/src/test-suite/PE-benchmarks/kth-smallestlargest-element-unsorted-array-set-3-worst-case-linear-time.cpp b/src/test-suite/PE-benchmarks/kth-smallestlargest-element-unsorted-array-set-3-worst-case-linear-time.cpp index 2f65082e..e3b5e0ae 100644 --- a/src/test-suite/PE-benchmarks/kth-smallestlargest-element-unsorted-array-set-3-worst-case-linear-time.cpp +++ b/src/test-suite/PE-benchmarks/kth-smallestlargest-element-unsorted-array-set-3-worst-case-linear-time.cpp @@ -11,84 +11,84 @@ int partition(int arr[], int l, int r, int k); // A simple function to find median of arr[]. This is called // only for an array of size 5 in this program. int findMedian(int arr[], int n) { - sort(arr, arr + n); // Sort the array - return arr[n / 2]; // Return middle element + sort(arr, arr + n); // Sort the array + return arr[n / 2]; // Return middle element } // Returns k'th smallest element in arr[l..r] in worst case // linear time. ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT int kthSmallest(int arr[], int l, int r, int k) { - // If k is smaller than number of elements in array - if (k > 0 && k <= r - l + 1) { - int n = r - l + 1; // Number of elements in arr[l..r] + // If k is smaller than number of elements in array + if (k > 0 && k <= r - l + 1) { + int n = r - l + 1; // Number of elements in arr[l..r] - // Divide arr[] in groups of size 5, calculate median - // of every group and store it in median[] array. - int i, median[(n + 4) / 5]; // There will be floor((n+4)/5) groups; - for (i = 0; i < n / 5; i++) - median[i] = findMedian(arr + l + i * 5, 5); - if (i * 5 < n) // For last group with less than 5 elements - { - median[i] = findMedian(arr + l + i * 5, n % 5); - i++; - } + // Divide arr[] in groups of size 5, calculate median + // of every group and store it in median[] array. + int i, median[(n + 4) / 5]; // There will be floor((n+4)/5) groups; + for (i = 0; i < n / 5; i++) + median[i] = findMedian(arr + l + i * 5, 5); + if (i * 5 < n) // For last group with less than 5 elements + { + median[i] = findMedian(arr + l + i * 5, n % 5); + i++; + } - // Find median of all medians using recursive call. - // If median[] has only one element, then no need - // of recursive call - int medOfMed = - (i == 1) ? median[i - 1] : kthSmallest(median, 0, i - 1, i / 2); + // Find median of all medians using recursive call. + // If median[] has only one element, then no need + // of recursive call + int medOfMed = + (i == 1) ? median[i - 1] : kthSmallest(median, 0, i - 1, i / 2); - // Partition the array around a random element and - // get position of pivot element in sorted array - int pos = partition(arr, l, r, medOfMed); + // Partition the array around a random element and + // get position of pivot element in sorted array + int pos = partition(arr, l, r, medOfMed); - // If position is same as k - if (pos - l == k - 1) - return arr[pos]; - if (pos - l > k - 1) // If position is more, recur for left - return kthSmallest(arr, l, pos - 1, k); + // If position is same as k + if (pos - l == k - 1) + return arr[pos]; + if (pos - l > k - 1) // If position is more, recur for left + return kthSmallest(arr, l, pos - 1, k); - // Else recur for right subarray - return kthSmallest(arr, pos + 1, r, k - pos + l - 1); - } + // Else recur for right subarray + return kthSmallest(arr, pos + 1, r, k - pos + l - 1); + } - // If k is more than number of elements in array - return INT_MAX; + // If k is more than number of elements in array + return INT_MAX; } void swap(int *a, int *b) { - int temp = *a; - *a = *b; - *b = temp; + int temp = *a; + *a = *b; + *b = temp; } // It searches for x in arr[l..r], and partitions the array // around x. int partition(int arr[], int l, int r, int x) { - // Search for x in arr[l..r] and move it to end - int i; - for (i = l; i < r; i++) - if (arr[i] == x) - break; - swap(&arr[i], &arr[r]); + // Search for x in arr[l..r] and move it to end + int i; + for (i = l; i < r; i++) + if (arr[i] == x) + break; + swap(&arr[i], &arr[r]); - // Standard partition algorithm - i = l; - for (int j = l; j <= r - 1; j++) { - if (arr[j] <= x) { - swap(&arr[i], &arr[j]); - i++; - } + // Standard partition algorithm + i = l; + for (int j = l; j <= r - 1; j++) { + if (arr[j] <= x) { + swap(&arr[i], &arr[j]); + i++; } - swap(&arr[i], &arr[r]); - return i; + } + swap(&arr[i], &arr[r]); + return i; } // Driver program to test above methods int main() { - int arr[] = {12, 3, 5, 7, 4, 19, 26}; - int n = sizeof(arr) / sizeof(arr[0]), k = 3; - cout << "K'th smallest element is " << kthSmallest(arr, 0, n - 1, k); - return 0; + int arr[] = {12, 3, 5, 7, 4, 19, 26}; + int n = sizeof(arr) / sizeof(arr[0]), k = 3; + cout << "K'th smallest element is " << kthSmallest(arr, 0, n - 1, k); + return 0; } diff --git a/src/test-suite/PE-benchmarks/largest-independent-set-problem.cpp b/src/test-suite/PE-benchmarks/largest-independent-set-problem.cpp index 4fb0376e..f81dc56d 100644 --- a/src/test-suite/PE-benchmarks/largest-independent-set-problem.cpp +++ b/src/test-suite/PE-benchmarks/largest-independent-set-problem.cpp @@ -10,66 +10,66 @@ int max(int x, int y) { return (x > y) ? x : y; } to left child and a pointer to right child */ class node { - public: - int data; - int liss; - node *left, *right; +public: + int data; + int liss; + node *left, *right; }; // A memoization function returns size // of the largest independent set in // a given binary tree int LISS(node *root) { - if (root == NULL) - return 0; + if (root == NULL) + return 0; - if (root->liss) - return root->liss; + if (root->liss) + return root->liss; - if (root->left == NULL && root->right == NULL) - return (root->liss = 1); + if (root->left == NULL && root->right == NULL) + return (root->liss = 1); - // Calculate size excluding the current node - int liss_excl = LISS(root->left) + LISS(root->right); + // Calculate size excluding the current node + int liss_excl = LISS(root->left) + LISS(root->right); - // Calculate size including the current node - int liss_incl = 1; - if (root->left) - liss_incl += LISS(root->left->left) + LISS(root->left->right); - if (root->right) - liss_incl += LISS(root->right->left) + LISS(root->right->right); + // Calculate size including the current node + int liss_incl = 1; + if (root->left) + liss_incl += LISS(root->left->left) + LISS(root->left->right); + if (root->right) + liss_incl += LISS(root->right->left) + LISS(root->right->right); - // Maximum of two sizes is LISS, store it for future uses. - root->liss = max(liss_incl, liss_excl); + // Maximum of two sizes is LISS, store it for future uses. + root->liss = max(liss_incl, liss_excl); - return root->liss; + return root->liss; } // A utility function to create a node node *newNode(int data) { - node *temp = new node(); - temp->data = data; - temp->left = temp->right = NULL; - temp->liss = 0; - return temp; + node *temp = new node(); + temp->data = data; + temp->left = temp->right = NULL; + temp->liss = 0; + return temp; } // Driver code int main() { - // Let us construct the tree - // given in the above diagram - node *root = newNode(20); - root->left = newNode(8); - root->left->left = newNode(4); - root->left->right = newNode(12); - root->left->right->left = newNode(10); - root->left->right->right = newNode(14); - root->right = newNode(22); - root->right->right = newNode(25); + // Let us construct the tree + // given in the above diagram + node *root = newNode(20); + root->left = newNode(8); + root->left->left = newNode(4); + root->left->right = newNode(12); + root->left->right->left = newNode(10); + root->left->right->right = newNode(14); + root->right = newNode(22); + root->right->right = newNode(25); - cout << "Size of the Largest Independent Set is " << LISS(root); + cout << "Size of the Largest Independent Set is " << LISS(root); - return 0; + return 0; } // This code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/largest-sum-contiguous-subarray.cpp b/src/test-suite/PE-benchmarks/largest-sum-contiguous-subarray.cpp index 2de4ac04..d3b5bf18 100644 --- a/src/test-suite/PE-benchmarks/largest-sum-contiguous-subarray.cpp +++ b/src/test-suite/PE-benchmarks/largest-sum-contiguous-subarray.cpp @@ -4,31 +4,30 @@ using namespace std; int maxSubArraySum(int a[], int size) { - int max_so_far = INT_MIN, max_ending_here = 0, start = 0, end = 0, s = 0; + int max_so_far = INT_MIN, max_ending_here = 0, start = 0, end = 0, s = 0; - for (int i = 0; i < size; i++) { - max_ending_here += a[i]; + for (int i = 0; i < size; i++) { + max_ending_here += a[i]; - if (max_so_far < max_ending_here) { - max_so_far = max_ending_here; - start = s; - end = i; - } + if (max_so_far < max_ending_here) { + max_so_far = max_ending_here; + start = s; + end = i; + } - if (max_ending_here < 0) { - max_ending_here = 0; - s = i + 1; - } + if (max_ending_here < 0) { + max_ending_here = 0; + s = i + 1; } - cout << "Maximum contiguous sum is " << max_so_far << endl; - cout << "Starting index " << start << endl - << "Ending index " << end << endl; + } + cout << "Maximum contiguous sum is " << max_so_far << endl; + cout << "Starting index " << start << endl << "Ending index " << end << endl; } /*Driver program to test maxSubArraySum*/ int main() { - int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; - int n = sizeof(a) / sizeof(a[0]); - int max_sum = maxSubArraySum(a, n); - return 0; + int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; + int n = sizeof(a) / sizeof(a[0]); + int max_sum = maxSubArraySum(a, n); + return 0; } diff --git a/src/test-suite/PE-benchmarks/lexicographic-rank-of-a-string.cpp b/src/test-suite/PE-benchmarks/lexicographic-rank-of-a-string.cpp index 2b8ce3b8..7e973bd9 100644 --- a/src/test-suite/PE-benchmarks/lexicographic-rank-of-a-string.cpp +++ b/src/test-suite/PE-benchmarks/lexicographic-rank-of-a-string.cpp @@ -10,42 +10,42 @@ int fact(int n) { return (n <= 1) ? 1 : n * fact(n - 1); } // A utility function to count smaller characters on right // of arr[low] int findSmallerInRight(char *str, int low, int high) { - int countRight = 0, i; + int countRight = 0, i; - for (i = low + 1; i <= high; ++i) - if (str[i] < str[low]) - ++countRight; + for (i = low + 1; i <= high; ++i) + if (str[i] < str[low]) + ++countRight; - return countRight; + return countRight; } // A function to find rank of a string in all permutations // of characters int findRank(char *str) { - int len = strlen(str); - int mul = fact(len); - int rank = 1; - int countRight; + int len = strlen(str); + int mul = fact(len); + int rank = 1; + int countRight; - int i; - for (i = 0; i < len; ++i) { - mul /= len - i; + int i; + for (i = 0; i < len; ++i) { + mul /= len - i; - // count number of chars smaller than str[i] - // fron str[i+1] to str[len-1] - countRight = findSmallerInRight(str, i, len - 1); + // count number of chars smaller than str[i] + // fron str[i+1] to str[len-1] + countRight = findSmallerInRight(str, i, len - 1); - rank += countRight * mul; - } + rank += countRight * mul; + } - return rank; + return rank; } // Driver program to test above function int main() { - char str[] = "string"; - cout << findRank(str); - return 0; + char str[] = "string"; + cout << findRank(str); + return 0; } // This code is contributed diff --git a/src/test-suite/PE-benchmarks/little-and-big-endian-mystery.cpp b/src/test-suite/PE-benchmarks/little-and-big-endian-mystery.cpp index 987c7c62..0add62ca 100644 --- a/src/test-suite/PE-benchmarks/little-and-big-endian-mystery.cpp +++ b/src/test-suite/PE-benchmarks/little-and-big-endian-mystery.cpp @@ -2,16 +2,16 @@ /* function to show bytes in memory, from location start to start+n*/ void show_mem_rep(char *start, int n) { - int i; - for (i = 0; i < n; i++) - printf(" %.2x", start[i]); - printf("\n"); + int i; + for (i = 0; i < n; i++) + printf(" %.2x", start[i]); + printf("\n"); } /*Main function to call above function for 0x01234567*/ int main() { - int i = 0x01234567; - show_mem_rep((char *)&i, sizeof(i)); - getchar(); - return 0; + int i = 0x01234567; + show_mem_rep((char *)&i, sizeof(i)); + getchar(); + return 0; } diff --git a/src/test-suite/PE-benchmarks/longest-bitonic-subsequence.cpp b/src/test-suite/PE-benchmarks/longest-bitonic-subsequence.cpp index 6010fe7a..e2f68f60 100644 --- a/src/test-suite/PE-benchmarks/longest-bitonic-subsequence.cpp +++ b/src/test-suite/PE-benchmarks/longest-bitonic-subsequence.cpp @@ -10,44 +10,44 @@ lds[i] ==> Longest decreasing subsequence starting with arr[i] */ int lbs(int arr[], int n) { - int i, j; - - /* Allocate memory for LIS[] and initialize LIS values as 1 for - all indexes */ - int *lis = new int[n]; - for (i = 0; i < n; i++) - lis[i] = 1; - - /* Compute LIS values from left to right */ - for (i = 1; i < n; i++) - for (j = 0; j < i; j++) - if (arr[i] > arr[j] && lis[i] < lis[j] + 1) - lis[i] = lis[j] + 1; - - /* Allocate memory for lds and initialize LDS values for - all indexes */ - int *lds = new int[n]; - for (i = 0; i < n; i++) - lds[i] = 1; - - /* Compute LDS values from right to left */ - for (i = n - 2; i >= 0; i--) - for (j = n - 1; j > i; j--) - if (arr[i] > arr[j] && lds[i] < lds[j] + 1) - lds[i] = lds[j] + 1; - - /* Return the maximum value of lis[i] + lds[i] - 1*/ - int max = lis[0] + lds[0] - 1; - for (i = 1; i < n; i++) - if (lis[i] + lds[i] - 1 > max) - max = lis[i] + lds[i] - 1; - return max; + int i, j; + + /* Allocate memory for LIS[] and initialize LIS values as 1 for + all indexes */ + int *lis = new int[n]; + for (i = 0; i < n; i++) + lis[i] = 1; + + /* Compute LIS values from left to right */ + for (i = 1; i < n; i++) + for (j = 0; j < i; j++) + if (arr[i] > arr[j] && lis[i] < lis[j] + 1) + lis[i] = lis[j] + 1; + + /* Allocate memory for lds and initialize LDS values for + all indexes */ + int *lds = new int[n]; + for (i = 0; i < n; i++) + lds[i] = 1; + + /* Compute LDS values from right to left */ + for (i = n - 2; i >= 0; i--) + for (j = n - 1; j > i; j--) + if (arr[i] > arr[j] && lds[i] < lds[j] + 1) + lds[i] = lds[j] + 1; + + /* Return the maximum value of lis[i] + lds[i] - 1*/ + int max = lis[0] + lds[0] - 1; + for (i = 1; i < n; i++) + if (lis[i] + lds[i] - 1 > max) + max = lis[i] + lds[i] - 1; + return max; } /* Driver program to test above function */ int main() { - int arr[] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}; - int n = sizeof(arr) / sizeof(arr[0]); - printf("Length of LBS is %d\n", lbs(arr, n)); - return 0; + int arr[] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}; + int n = sizeof(arr) / sizeof(arr[0]); + printf("Length of LBS is %d\n", lbs(arr, n)); + return 0; } diff --git a/src/test-suite/PE-benchmarks/longest-even-length-substring-sum-first-second-half.cpp b/src/test-suite/PE-benchmarks/longest-even-length-substring-sum-first-second-half.cpp index 15bcebb4..b6331b0a 100644 --- a/src/test-suite/PE-benchmarks/longest-even-length-substring-sum-first-second-half.cpp +++ b/src/test-suite/PE-benchmarks/longest-even-length-substring-sum-first-second-half.cpp @@ -6,47 +6,46 @@ using namespace std; int findLength(char *str) { - int n = strlen(str); - int maxlen = 0; // Initialize result - - // A 2D table where sum[i][j] stores - // sum of digits from str[i] to str[j]. - // Only filled entries are the entries - // where j >= i - int sum[n][n]; - - // Fill the diagonal values for - // substrings of length 1 - for (int i = 0; i < n; i++) - sum[i][i] = str[i] - '0'; - - // Fill entries for substrings of - // length 2 to n - for (int len = 2; len <= n; len++) { - // Pick i and j for current substring - for (int i = 0; i < n - len + 1; i++) { - int j = i + len - 1; - int k = len / 2; - - // Calculate value of sum[i][j] - sum[i][j] = sum[i][j - k] + sum[j - k + 1][j]; - - // Update result if 'len' is even, - // left and right sums are same and - // len is more than maxlen - if (len % 2 == 0 && sum[i][j - k] == sum[(j - k + 1)][j] && - len > maxlen) - maxlen = len; - } + int n = strlen(str); + int maxlen = 0; // Initialize result + + // A 2D table where sum[i][j] stores + // sum of digits from str[i] to str[j]. + // Only filled entries are the entries + // where j >= i + int sum[n][n]; + + // Fill the diagonal values for + // substrings of length 1 + for (int i = 0; i < n; i++) + sum[i][i] = str[i] - '0'; + + // Fill entries for substrings of + // length 2 to n + for (int len = 2; len <= n; len++) { + // Pick i and j for current substring + for (int i = 0; i < n - len + 1; i++) { + int j = i + len - 1; + int k = len / 2; + + // Calculate value of sum[i][j] + sum[i][j] = sum[i][j - k] + sum[j - k + 1][j]; + + // Update result if 'len' is even, + // left and right sums are same and + // len is more than maxlen + if (len % 2 == 0 && sum[i][j - k] == sum[(j - k + 1)][j] && len > maxlen) + maxlen = len; } - return maxlen; + } + return maxlen; } // Driver Code int main(void) { - char str[] = "153803"; - cout << "Length of the substring is " << findLength(str); - return 0; + char str[] = "153803"; + cout << "Length of the substring is " << findLength(str); + return 0; } // This code is contributed diff --git a/src/test-suite/PE-benchmarks/longest-increasing-subsequence.cpp b/src/test-suite/PE-benchmarks/longest-increasing-subsequence.cpp index 92528762..890e5318 100644 --- a/src/test-suite/PE-benchmarks/longest-increasing-subsequence.cpp +++ b/src/test-suite/PE-benchmarks/longest-increasing-subsequence.cpp @@ -11,48 +11,48 @@ two things: The value of LIS of full array of size n is stored in *max_ref which is our final result */ int _lis(int arr[], int n, int *max_ref) { - /* Base case */ - if (n == 1) - return 1; - - // 'max_ending_here' is length of LIS ending with arr[n-1] - int res, max_ending_here = 1; - - /* Recursively get all LIS ending with arr[0], arr[1] ... - arr[n-2]. If arr[i-1] is smaller than arr[n-1], and - max ending with arr[n-1] needs to be updated, then - update it */ - for (int i = 1; i < n; i++) { - res = _lis(arr, i, max_ref); - if (arr[i - 1] < arr[n - 1] && res + 1 > max_ending_here) - max_ending_here = res + 1; - } - - // Compare max_ending_here with the overall max. And - // update the overall max if needed - if (*max_ref < max_ending_here) - *max_ref = max_ending_here; - - // Return length of LIS ending with arr[n-1] - return max_ending_here; + /* Base case */ + if (n == 1) + return 1; + + // 'max_ending_here' is length of LIS ending with arr[n-1] + int res, max_ending_here = 1; + + /* Recursively get all LIS ending with arr[0], arr[1] ... + arr[n-2]. If arr[i-1] is smaller than arr[n-1], and + max ending with arr[n-1] needs to be updated, then + update it */ + for (int i = 1; i < n; i++) { + res = _lis(arr, i, max_ref); + if (arr[i - 1] < arr[n - 1] && res + 1 > max_ending_here) + max_ending_here = res + 1; + } + + // Compare max_ending_here with the overall max. And + // update the overall max if needed + if (*max_ref < max_ending_here) + *max_ref = max_ending_here; + + // Return length of LIS ending with arr[n-1] + return max_ending_here; } // The wrapper function for _lis() int lis(int arr[], int n) { - // The max variable holds the result - int max = 1; + // The max variable holds the result + int max = 1; - // The function _lis() stores its result in max - _lis(arr, n, &max); + // The function _lis() stores its result in max + _lis(arr, n, &max); - // returns max - return max; + // returns max + return max; } /* Driver program to test above function */ int main() { - int arr[] = {10, 22, 9, 33, 21, 50, 41, 60}; - int n = sizeof(arr) / sizeof(arr[0]); - printf("Length of lis is %dn", lis(arr, n)); - return 0; + int arr[] = {10, 22, 9, 33, 21, 50, 41, 60}; + int n = sizeof(arr) / sizeof(arr[0]); + printf("Length of lis is %dn", lis(arr, n)); + return 0; } diff --git a/src/test-suite/PE-benchmarks/longest-palindrome-substring.cpp b/src/test-suite/PE-benchmarks/longest-palindrome-substring.cpp index 979449dd..991996a0 100644 --- a/src/test-suite/PE-benchmarks/longest-palindrome-substring.cpp +++ b/src/test-suite/PE-benchmarks/longest-palindrome-substring.cpp @@ -6,72 +6,72 @@ using namespace std; // Function to print a substring str[low..high] void printSubStr(string str, int low, int high) { - for (int i = low; i <= high; ++i) - cout << str[i]; + for (int i = low; i <= high; ++i) + cout << str[i]; } // This function prints the longest palindrome substring // It also returns the length of the longest palindrome int longestPalSubstr(string str) { - // get length of input string - int n = str.size(); + // get length of input string + int n = str.size(); - // table[i][j] will be false if substring str[i..j] - // is not palindrome. - // Else table[i][j] will be true - bool table[n][n]; + // table[i][j] will be false if substring str[i..j] + // is not palindrome. + // Else table[i][j] will be true + bool table[n][n]; - memset(table, 0, sizeof(table)); + memset(table, 0, sizeof(table)); - // All substrings of length 1 are palindromes - int maxLength = 1; + // All substrings of length 1 are palindromes + int maxLength = 1; - for (int i = 0; i < n; ++i) - table[i][i] = true; + for (int i = 0; i < n; ++i) + table[i][i] = true; - // check for sub-string of length 2. - int start = 0; - for (int i = 0; i < n - 1; ++i) { - if (str[i] == str[i + 1]) { - table[i][i + 1] = true; - start = i; - maxLength = 2; - } + // check for sub-string of length 2. + int start = 0; + for (int i = 0; i < n - 1; ++i) { + if (str[i] == str[i + 1]) { + table[i][i + 1] = true; + start = i; + maxLength = 2; } + } - // Check for lengths greater than 2. k is length - // of substring - for (int k = 3; k <= n; ++k) { - // Fix the starting index - for (int i = 0; i < n - k + 1; ++i) { - // Get the ending index of substring from - // starting index i and length k - int j = i + k - 1; + // Check for lengths greater than 2. k is length + // of substring + for (int k = 3; k <= n; ++k) { + // Fix the starting index + for (int i = 0; i < n - k + 1; ++i) { + // Get the ending index of substring from + // starting index i and length k + int j = i + k - 1; - // checking for sub-string from ith index to - // jth index iff str[i+1] to str[j-1] is a - // palindrome - if (table[i + 1][j - 1] && str[i] == str[j]) { - table[i][j] = true; + // checking for sub-string from ith index to + // jth index iff str[i+1] to str[j-1] is a + // palindrome + if (table[i + 1][j - 1] && str[i] == str[j]) { + table[i][j] = true; - if (k > maxLength) { - start = i; - maxLength = k; - } - } + if (k > maxLength) { + start = i; + maxLength = k; } + } } + } - cout << "Longest palindrome substring is: "; - printSubStr(str, start, start + maxLength - 1); + cout << "Longest palindrome substring is: "; + printSubStr(str, start, start + maxLength - 1); - // return length of LPS - return maxLength; + // return length of LPS + return maxLength; } // Driver Code int main() { - string str = "forgeeksskeegfor"; - cout << "\nLength is: " << longestPalSubstr(str); - return 0; + string str = "forgeeksskeegfor"; + cout << "\nLength is: " << longestPalSubstr(str); + return 0; } diff --git a/src/test-suite/PE-benchmarks/longest-palindromic-subsequence.cpp b/src/test-suite/PE-benchmarks/longest-palindromic-subsequence.cpp index bcac367f..e1688d1b 100644 --- a/src/test-suite/PE-benchmarks/longest-palindromic-subsequence.cpp +++ b/src/test-suite/PE-benchmarks/longest-palindromic-subsequence.cpp @@ -8,39 +8,39 @@ int max(int x, int y) { return (x > y) ? x : y; } // Returns the length of the longest palindromic subsequence in seq int lps(char *str) { - int n = strlen(str); - int i, j, cl; - int L[n][n]; // Create a table to store results of subproblems + int n = strlen(str); + int i, j, cl; + int L[n][n]; // Create a table to store results of subproblems - // Strings of length 1 are palindrome of lentgh 1 - for (i = 0; i < n; i++) - L[i][i] = 1; + // Strings of length 1 are palindrome of lentgh 1 + for (i = 0; i < n; i++) + L[i][i] = 1; - // Build the table. Note that the lower diagonal values of table are - // useless and not filled in the process. The values are filled in a - // manner similar to Matrix Chain Multiplication DP solution (See - // https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/). cl is - // length of substring - for (cl = 2; cl <= n; cl++) { - for (i = 0; i < n - cl + 1; i++) { - j = i + cl - 1; - if (str[i] == str[j] && cl == 2) - L[i][j] = 2; - else if (str[i] == str[j]) - L[i][j] = L[i + 1][j - 1] + 2; - else - L[i][j] = max(L[i][j - 1], L[i + 1][j]); - } + // Build the table. Note that the lower diagonal values of table are + // useless and not filled in the process. The values are filled in a + // manner similar to Matrix Chain Multiplication DP solution (See + // https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/). cl is + // length of substring + for (cl = 2; cl <= n; cl++) { + for (i = 0; i < n - cl + 1; i++) { + j = i + cl - 1; + if (str[i] == str[j] && cl == 2) + L[i][j] = 2; + else if (str[i] == str[j]) + L[i][j] = L[i + 1][j - 1] + 2; + else + L[i][j] = max(L[i][j - 1], L[i + 1][j]); } + } - return L[0][n - 1]; + return L[0][n - 1]; } /* Driver program to test above functions */ int main() { - char seq[] = "GEEKS FOR GEEKS"; - int n = strlen(seq); - printf("The lnegth of the LPS is %d", lps(seq)); - getchar(); - return 0; + char seq[] = "GEEKS FOR GEEKS"; + int n = strlen(seq); + printf("The lnegth of the LPS is %d", lps(seq)); + getchar(); + return 0; } diff --git a/src/test-suite/PE-benchmarks/longest-path-directed-acyclic-graph.cpp b/src/test-suite/PE-benchmarks/longest-path-directed-acyclic-graph.cpp index 02815999..b3032167 100644 --- a/src/test-suite/PE-benchmarks/longest-path-directed-acyclic-graph.cpp +++ b/src/test-suite/PE-benchmarks/longest-path-directed-acyclic-graph.cpp @@ -12,145 +12,145 @@ using namespace std; // the vertex to which edge connects. It also // contains weight of the edge class AdjListNode { - int v; - int weight; - - public: - AdjListNode(int _v, int _w) { - v = _v; - weight = _w; - } - int getV() { return v; } - int getWeight() { return weight; } + int v; + int weight; + +public: + AdjListNode(int _v, int _w) { + v = _v; + weight = _w; + } + int getV() { return v; } + int getWeight() { return weight; } }; // Class to represent a graph using adjacency list // representation class Graph { - int V; // No. of vertices' + int V; // No. of vertices' - // Pointer to an array containing adjacency lists - list *adj; + // Pointer to an array containing adjacency lists + list *adj; - // A function used by longestPath - void topologicalSortUtil(int v, bool visited[], stack &Stack); + // A function used by longestPath + void topologicalSortUtil(int v, bool visited[], stack &Stack); - public: - Graph(int V); // Constructor - ~Graph(); // Destructor +public: + Graph(int V); // Constructor + ~Graph(); // Destructor - // function to add an edge to graph - void addEdge(int u, int v, int weight); + // function to add an edge to graph + void addEdge(int u, int v, int weight); - // Finds longest distances from given source vertex - void longestPath(int s); + // Finds longest distances from given source vertex + void longestPath(int s); }; Graph::Graph(int V) // Constructor { - this->V = V; - adj = new list[V]; + this->V = V; + adj = new list[V]; } Graph::~Graph() // Destructor { - delete[] adj; + delete[] adj; } void Graph::addEdge(int u, int v, int weight) { - AdjListNode node(v, weight); - adj[u].push_back(node); // Add v to u's list + AdjListNode node(v, weight); + adj[u].push_back(node); // Add v to u's list } // A recursive function used by longestPath. See below // link for details // https:// www.geeksforgeeks.org/topological-sorting/ void Graph::topologicalSortUtil(int v, bool visited[], stack &Stack) { - // Mark the current node as visited - visited[v] = true; - - // Recur for all the vertices adjacent to this vertex - list::iterator i; - for (i = adj[v].begin(); i != adj[v].end(); ++i) { - AdjListNode node = *i; - if (!visited[node.getV()]) - topologicalSortUtil(node.getV(), visited, Stack); - } - - // Push current vertex to stack which stores topological - // sort - Stack.push(v); + // Mark the current node as visited + visited[v] = true; + + // Recur for all the vertices adjacent to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) { + AdjListNode node = *i; + if (!visited[node.getV()]) + topologicalSortUtil(node.getV(), visited, Stack); + } + + // Push current vertex to stack which stores topological + // sort + Stack.push(v); } // The function to find longest distances from a given vertex. // It uses recursive topologicalSortUtil() to get topological // sorting. void Graph::longestPath(int s) { - stack Stack; - int dist[V]; - - // Mark all the vertices as not visited - bool *visited = new bool[V]; - for (int i = 0; i < V; i++) - visited[i] = false; - - // Call the recursive helper function to store Topological - // Sort starting from all vertices one by one - for (int i = 0; i < V; i++) - if (visited[i] == false) - topologicalSortUtil(i, visited, Stack); - - // Initialize distances to all vertices as infinite and - // distance to source as 0 - for (int i = 0; i < V; i++) - dist[i] = NINF; - dist[s] = 0; - - // Process vertices in topological order - while (Stack.empty() == false) { - // Get the next vertex from topological order - int u = Stack.top(); - Stack.pop(); - - // Update distances of all adjacent vertices - list::iterator i; - if (dist[u] != NINF) { - for (i = adj[u].begin(); i != adj[u].end(); ++i) - if (dist[i->getV()] < dist[u] + i->getWeight()) - dist[i->getV()] = dist[u] + i->getWeight(); - } + stack Stack; + int dist[V]; + + // Mark all the vertices as not visited + bool *visited = new bool[V]; + for (int i = 0; i < V; i++) + visited[i] = false; + + // Call the recursive helper function to store Topological + // Sort starting from all vertices one by one + for (int i = 0; i < V; i++) + if (visited[i] == false) + topologicalSortUtil(i, visited, Stack); + + // Initialize distances to all vertices as infinite and + // distance to source as 0 + for (int i = 0; i < V; i++) + dist[i] = NINF; + dist[s] = 0; + + // Process vertices in topological order + while (Stack.empty() == false) { + // Get the next vertex from topological order + int u = Stack.top(); + Stack.pop(); + + // Update distances of all adjacent vertices + list::iterator i; + if (dist[u] != NINF) { + for (i = adj[u].begin(); i != adj[u].end(); ++i) + if (dist[i->getV()] < dist[u] + i->getWeight()) + dist[i->getV()] = dist[u] + i->getWeight(); } + } - // Print the calculated longest distances - for (int i = 0; i < V; i++) - (dist[i] == NINF) ? cout << "INF " : cout << dist[i] << " "; + // Print the calculated longest distances + for (int i = 0; i < V; i++) + (dist[i] == NINF) ? cout << "INF " : cout << dist[i] << " "; - delete[] visited; + delete[] visited; } // Driver program to test above functions int main() { - // Create a graph given in the above diagram. - // Here vertex numbers are 0, 1, 2, 3, 4, 5 with - // following mappings: - // 0=r, 1=s, 2=t, 3=x, 4=y, 5=z - Graph g(6); - g.addEdge(0, 1, 5); - g.addEdge(0, 2, 3); - g.addEdge(1, 3, 6); - g.addEdge(1, 2, 2); - g.addEdge(2, 4, 4); - g.addEdge(2, 5, 2); - g.addEdge(2, 3, 7); - g.addEdge(3, 5, 1); - g.addEdge(3, 4, -1); - g.addEdge(4, 5, -2); - - int s = 1; - cout << "Following are longest distances from " - "source vertex " - << s << " \n"; - g.longestPath(s); - - return 0; + // Create a graph given in the above diagram. + // Here vertex numbers are 0, 1, 2, 3, 4, 5 with + // following mappings: + // 0=r, 1=s, 2=t, 3=x, 4=y, 5=z + Graph g(6); + g.addEdge(0, 1, 5); + g.addEdge(0, 2, 3); + g.addEdge(1, 3, 6); + g.addEdge(1, 2, 2); + g.addEdge(2, 4, 4); + g.addEdge(2, 5, 2); + g.addEdge(2, 3, 7); + g.addEdge(3, 5, 1); + g.addEdge(3, 4, -1); + g.addEdge(4, 5, -2); + + int s = 1; + cout << "Following are longest distances from " + "source vertex " + << s << " \n"; + g.longestPath(s); + + return 0; } diff --git a/src/test-suite/PE-benchmarks/m-coloring-problem.cpp b/src/test-suite/PE-benchmarks/m-coloring-problem.cpp index f43c7ecc..7223241c 100644 --- a/src/test-suite/PE-benchmarks/m-coloring-problem.cpp +++ b/src/test-suite/PE-benchmarks/m-coloring-problem.cpp @@ -12,37 +12,37 @@ is safe for vertex v i.e. checks whether the edge exists or not be filled in the new vertex(c is sent in the parameter) is already used by its adjacent vertices(i-->adj vertices) or not (i.e, color[i]==c) */ bool isSafe(int v, bool graph[V][V], int color[], int c) { - for (int i = 0; i < V; i++) - if (graph[v][i] && c == color[i]) - return false; - return true; + for (int i = 0; i < V; i++) + if (graph[v][i] && c == color[i]) + return false; + return true; } /* A recursive utility function to solve m coloring problem */ bool graphColoringUtil(bool graph[V][V], int m, int color[], int v) { - /* base case: If all vertices are assigned a color then - return true */ - if (v == V) - return true; + /* base case: If all vertices are assigned a color then + return true */ + if (v == V) + return true; - /* Consider this vertex v and try different colors */ - for (int c = 1; c <= m; c++) { - /* Check if assignment of color c to v is fine*/ - if (isSafe(v, graph, color, c)) { - color[v] = c; + /* Consider this vertex v and try different colors */ + for (int c = 1; c <= m; c++) { + /* Check if assignment of color c to v is fine*/ + if (isSafe(v, graph, color, c)) { + color[v] = c; - /* recur to assign colors to rest of the vertices */ - if (graphColoringUtil(graph, m, color, v + 1) == true) - return true; + /* recur to assign colors to rest of the vertices */ + if (graphColoringUtil(graph, m, color, v + 1) == true) + return true; - /* If assigning color c doesn't lead to a solution - then remove it */ - color[v] = 0; - } + /* If assigning color c doesn't lead to a solution + then remove it */ + color[v] = 0; } + } - /* If no color can be assigned to this vertex then return false */ - return false; + /* If no color can be assigned to this vertex then return false */ + return false; } /* This function solves the m Coloring problem using Backtracking. @@ -52,48 +52,48 @@ prints assignments of colors to all vertices. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ bool graphColoring(bool graph[V][V], int m) { - // Initialize all color values as 0. This initialization is needed - // correct functioning of isSafe() - int color[V]; - for (int i = 0; i < V; i++) - color[i] = 0; + // Initialize all color values as 0. This initialization is needed + // correct functioning of isSafe() + int color[V]; + for (int i = 0; i < V; i++) + color[i] = 0; - // Call graphColoringUtil() for vertex 0 - if (graphColoringUtil(graph, m, color, 0) == false) { - printf("Solution does not exist"); - return false; - } + // Call graphColoringUtil() for vertex 0 + if (graphColoringUtil(graph, m, color, 0) == false) { + printf("Solution does not exist"); + return false; + } - // Print the solution - printSolution(color); - return true; + // Print the solution + printSolution(color); + return true; } /* A utility function to print solution */ void printSolution(int color[]) { - printf("Solution Exists:" - " Following are the assigned colors \n"); - for (int i = 0; i < V; i++) - printf(" %d ", color[i]); - printf("\n"); + printf("Solution Exists:" + " Following are the assigned colors \n"); + for (int i = 0; i < V; i++) + printf(" %d ", color[i]); + printf("\n"); } // driver program to test above function int main() { - /* Create following graph and test whether it is 3 colorable - (3)---(2) - | / | - | / | - | / | - (0)---(1) - */ - bool graph[V][V] = { - {0, 1, 1, 1}, - {1, 0, 1, 0}, - {1, 1, 0, 1}, - {1, 0, 1, 0}, - }; - int m = 3; // Number of colors - graphColoring(graph, m); - return 0; + /* Create following graph and test whether it is 3 colorable + (3)---(2) + | / | + | / | + | / | + (0)---(1) + */ + bool graph[V][V] = { + {0, 1, 1, 1}, + {1, 0, 1, 0}, + {1, 1, 0, 1}, + {1, 0, 1, 0}, + }; + int m = 3; // Number of colors + graphColoring(graph, m); + return 0; } diff --git a/src/test-suite/PE-benchmarks/magic-square.cpp b/src/test-suite/PE-benchmarks/magic-square.cpp index ead77641..529fbfbf 100644 --- a/src/test-suite/PE-benchmarks/magic-square.cpp +++ b/src/test-suite/PE-benchmarks/magic-square.cpp @@ -4,61 +4,61 @@ using namespace std; // A function to generate odd sized magic squares void generateSquare(int n) { - int magicSquare[n][n]; + int magicSquare[n][n]; - // set all slots as 0 - memset(magicSquare, 0, sizeof(magicSquare)); + // set all slots as 0 + memset(magicSquare, 0, sizeof(magicSquare)); - // Initialize position for 1 - int i = n / 2; - int j = n - 1; + // Initialize position for 1 + int i = n / 2; + int j = n - 1; - // One by one put all values in magic square - for (int num = 1; num <= n * n;) { - if (i == -1 && j == n) // 3rd condition - { - j = n - 2; - i = 0; - } else { - // 1st condition helper if next number - // goes to out of square's right side - if (j == n) - j = 0; + // One by one put all values in magic square + for (int num = 1; num <= n * n;) { + if (i == -1 && j == n) // 3rd condition + { + j = n - 2; + i = 0; + } else { + // 1st condition helper if next number + // goes to out of square's right side + if (j == n) + j = 0; - // 1st condition helper if next number - // is goes to out of square's upper side - if (i < 0) - i = n - 1; - } - if (magicSquare[i][j]) // 2nd condition - { - j -= 2; - i++; - continue; - } else - magicSquare[i][j] = num++; // set number - - j++; - i--; // 1st condition + // 1st condition helper if next number + // is goes to out of square's upper side + if (i < 0) + i = n - 1; } + if (magicSquare[i][j]) // 2nd condition + { + j -= 2; + i++; + continue; + } else + magicSquare[i][j] = num++; // set number - // Print magic square - cout << "The Magic Square for n=" << n - << ":\nSum of " - "each row or column " - << n * (n * n + 1) / 2 << ":\n\n"; - for (i = 0; i < n; i++) { - for (j = 0; j < n; j++) - cout << magicSquare[i][j] << " "; - cout << endl; - } + j++; + i--; // 1st condition + } + + // Print magic square + cout << "The Magic Square for n=" << n + << ":\nSum of " + "each row or column " + << n * (n * n + 1) / 2 << ":\n\n"; + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) + cout << magicSquare[i][j] << " "; + cout << endl; + } } // Driver code int main() { - int n = 7; // Works only when n is odd - generateSquare(n); - return 0; + int n = 7; // Works only when n is odd + generateSquare(n); + return 0; } // This code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/matrix-chain-multiplication.cpp b/src/test-suite/PE-benchmarks/matrix-chain-multiplication.cpp index 87d9f99b..562d16e4 100644 --- a/src/test-suite/PE-benchmarks/matrix-chain-multiplication.cpp +++ b/src/test-suite/PE-benchmarks/matrix-chain-multiplication.cpp @@ -7,51 +7,51 @@ using namespace std; // for i = 1..n int MatrixChainOrder(int p[], int n) { - /* For simplicity of the program, one - extra row and one extra column are - allocated in m[][]. 0th row and 0th - column of m[][] are not used */ - int m[n][n]; - - int i, j, k, L, q; - - /* m[i,j] = Minimum number of scalar - multiplications needed to compute the - matrix A[i]A[i+1]...A[j] = A[i..j] where - dimension of A[i] is p[i-1] x p[i] */ - - // cost is zero when multiplying - // one matrix. - for (i = 1; i < n; i++) - m[i][i] = 0; - - // L is chain length. - for (L = 2; L < n; L++) { - for (i = 1; i < n - L + 1; i++) { - j = i + L - 1; - m[i][j] = INT_MAX; - for (k = i; k <= j - 1; k++) { - // q = cost/scalar multiplications - q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; - if (q < m[i][j]) - m[i][j] = q; - } - } + /* For simplicity of the program, one + extra row and one extra column are + allocated in m[][]. 0th row and 0th + column of m[][] are not used */ + int m[n][n]; + + int i, j, k, L, q; + + /* m[i,j] = Minimum number of scalar + multiplications needed to compute the + matrix A[i]A[i+1]...A[j] = A[i..j] where + dimension of A[i] is p[i-1] x p[i] */ + + // cost is zero when multiplying + // one matrix. + for (i = 1; i < n; i++) + m[i][i] = 0; + + // L is chain length. + for (L = 2; L < n; L++) { + for (i = 1; i < n - L + 1; i++) { + j = i + L - 1; + m[i][j] = INT_MAX; + for (k = i; k <= j - 1; k++) { + // q = cost/scalar multiplications + q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; + if (q < m[i][j]) + m[i][j] = q; + } } + } - return m[1][n - 1]; + return m[1][n - 1]; } // Driver Code int main() { - int arr[] = {1, 2, 3, 4}; - int size = sizeof(arr) / sizeof(arr[0]); + int arr[] = {1, 2, 3, 4}; + int size = sizeof(arr) / sizeof(arr[0]); - cout << "Minimum number of multiplications is " - << MatrixChainOrder(arr, size); + cout << "Minimum number of multiplications is " + << MatrixChainOrder(arr, size); - getchar(); - return 0; + getchar(); + return 0; } // This code is contributed diff --git a/src/test-suite/PE-benchmarks/maximum-length-chain-of-pairs.cpp b/src/test-suite/PE-benchmarks/maximum-length-chain-of-pairs.cpp index 9974a306..143761fb 100644 --- a/src/test-suite/PE-benchmarks/maximum-length-chain-of-pairs.cpp +++ b/src/test-suite/PE-benchmarks/maximum-length-chain-of-pairs.cpp @@ -3,47 +3,47 @@ using namespace std; // Structure for a Pair class Pair { - public: - int a; - int b; +public: + int a; + int b; }; // This function assumes that arr[] // is sorted in increasing order // according the first (or smaller) values in Pairs. int maxChainLength(Pair arr[], int n) { - int i, j, max = 0; - int *mcl = new int[sizeof(int) * n]; + int i, j, max = 0; + int *mcl = new int[sizeof(int) * n]; - /* Initialize MCL (max chain length) - values for all indexes */ - for (i = 0; i < n; i++) - mcl[i] = 1; + /* Initialize MCL (max chain length) + values for all indexes */ + for (i = 0; i < n; i++) + mcl[i] = 1; - /* Compute optimized chain length values in bottom up manner */ - for (i = 1; i < n; i++) - for (j = 0; j < i; j++) - if (arr[i].a > arr[j].b && mcl[i] < mcl[j] + 1) - mcl[i] = mcl[j] + 1; + /* Compute optimized chain length values in bottom up manner */ + for (i = 1; i < n; i++) + for (j = 0; j < i; j++) + if (arr[i].a > arr[j].b && mcl[i] < mcl[j] + 1) + mcl[i] = mcl[j] + 1; - // mcl[i] now stores the maximum chain length ending with Pair i + // mcl[i] now stores the maximum chain length ending with Pair i - /* Pick maximum of all MCL values */ - for (i = 0; i < n; i++) - if (max < mcl[i]) - max = mcl[i]; + /* Pick maximum of all MCL values */ + for (i = 0; i < n; i++) + if (max < mcl[i]) + max = mcl[i]; - /* Free memory to avoid memory leak */ + /* Free memory to avoid memory leak */ - return max; + return max; } /* Driver code */ int main() { - Pair arr[] = {{5, 24}, {15, 25}, {27, 40}, {50, 60}}; - int n = sizeof(arr) / sizeof(arr[0]); - cout << "Length of maximum size chain is " << maxChainLength(arr, n); - return 0; + Pair arr[] = {{5, 24}, {15, 25}, {27, 40}, {50, 60}}; + int n = sizeof(arr) / sizeof(arr[0]); + cout << "Length of maximum size chain is " << maxChainLength(arr, n); + return 0; } // This code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/maximum-profit-by-buying-and-selling-a-share-at-most-twice.cpp b/src/test-suite/PE-benchmarks/maximum-profit-by-buying-and-selling-a-share-at-most-twice.cpp index 5c78e50c..369e34e3 100644 --- a/src/test-suite/PE-benchmarks/maximum-profit-by-buying-and-selling-a-share-at-most-twice.cpp +++ b/src/test-suite/PE-benchmarks/maximum-profit-by-buying-and-selling-a-share-at-most-twice.cpp @@ -6,52 +6,52 @@ using namespace std; // Returns maximum profit with two transactions on a given // list of stock prices, price[0..n-1] int maxProfit(int price[], int n) { - // Create profit array and initialize it as 0 - int *profit = new int[n]; - for (int i = 0; i < n; i++) - profit[i] = 0; - - /* Get the maximum profit with only one transaction - allowed. After this loop, profit[i] contains maximum - profit from price[i..n-1] using at most one trans. */ - int max_price = price[n - 1]; - for (int i = n - 2; i >= 0; i--) { - // max_price has maximum of price[i..n-1] - if (price[i] > max_price) - max_price = price[i]; - - // we can get profit[i] by taking maximum of: - // a) previous maximum, i.e., profit[i+1] - // b) profit by buying at price[i] and selling at - // max_price - profit[i] = max(profit[i + 1], max_price - price[i]); - } - - /* Get the maximum profit with two transactions allowed - After this loop, profit[n-1] contains the result */ - int min_price = price[0]; - for (int i = 1; i < n; i++) { - // min_price is minimum price in price[0..i] - if (price[i] < min_price) - min_price = price[i]; - - // Maximum profit is maximum of: - // a) previous maximum, i.e., profit[i-1] - // b) (Buy, Sell) at (min_price, price[i]) and add - // profit of other trans. stored in profit[i] - profit[i] = max(profit[i - 1], profit[i] + (price[i] - min_price)); - } - int result = profit[n - 1]; - - delete[] profit; // To avoid memory leak - - return result; + // Create profit array and initialize it as 0 + int *profit = new int[n]; + for (int i = 0; i < n; i++) + profit[i] = 0; + + /* Get the maximum profit with only one transaction + allowed. After this loop, profit[i] contains maximum + profit from price[i..n-1] using at most one trans. */ + int max_price = price[n - 1]; + for (int i = n - 2; i >= 0; i--) { + // max_price has maximum of price[i..n-1] + if (price[i] > max_price) + max_price = price[i]; + + // we can get profit[i] by taking maximum of: + // a) previous maximum, i.e., profit[i+1] + // b) profit by buying at price[i] and selling at + // max_price + profit[i] = max(profit[i + 1], max_price - price[i]); + } + + /* Get the maximum profit with two transactions allowed + After this loop, profit[n-1] contains the result */ + int min_price = price[0]; + for (int i = 1; i < n; i++) { + // min_price is minimum price in price[0..i] + if (price[i] < min_price) + min_price = price[i]; + + // Maximum profit is maximum of: + // a) previous maximum, i.e., profit[i-1] + // b) (Buy, Sell) at (min_price, price[i]) and add + // profit of other trans. stored in profit[i] + profit[i] = max(profit[i - 1], profit[i] + (price[i] - min_price)); + } + int result = profit[n - 1]; + + delete[] profit; // To avoid memory leak + + return result; } // Drive program int main() { - int price[] = {2, 30, 15, 10, 8, 25, 80}; - int n = sizeof(price) / sizeof(price[0]); - cout << "Maximum Profit = " << maxProfit(price, n); - return 0; + int price[] = {2, 30, 15, 10, 8, 25, 80}; + int n = sizeof(price) / sizeof(price[0]); + cout << "Maximum Profit = " << maxProfit(price, n); + return 0; } diff --git a/src/test-suite/PE-benchmarks/maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix.cpp b/src/test-suite/PE-benchmarks/maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix.cpp index 9286ffec..4a9ba915 100644 --- a/src/test-suite/PE-benchmarks/maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix.cpp +++ b/src/test-suite/PE-benchmarks/maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix.cpp @@ -7,59 +7,58 @@ using namespace std; void printMaxSubSquare(bool M[R][C]) { - int i, j; - int S[R][C]; - int max_of_s, max_i, max_j; + int i, j; + int S[R][C]; + int max_of_s, max_i, max_j; - /* Set first column of S[][]*/ - for (i = 0; i < R; i++) - S[i][0] = M[i][0]; + /* Set first column of S[][]*/ + for (i = 0; i < R; i++) + S[i][0] = M[i][0]; - /* Set first row of S[][]*/ - for (j = 0; j < C; j++) - S[0][j] = M[0][j]; + /* Set first row of S[][]*/ + for (j = 0; j < C; j++) + S[0][j] = M[0][j]; - /* Construct other entries of S[][]*/ - for (i = 1; i < R; i++) { - for (j = 1; j < C; j++) { - if (M[i][j] == 1) - S[i][j] = - min(S[i][j - 1], min(S[i - 1][j], S[i - 1][j - 1])) + 1; - else - S[i][j] = 0; - } + /* Construct other entries of S[][]*/ + for (i = 1; i < R; i++) { + for (j = 1; j < C; j++) { + if (M[i][j] == 1) + S[i][j] = min(S[i][j - 1], min(S[i - 1][j], S[i - 1][j - 1])) + 1; + else + S[i][j] = 0; } + } - /* Find the maximum entry, and indexes of maximum entry - in S[][] */ - max_of_s = S[0][0]; - max_i = 0; - max_j = 0; - for (i = 0; i < R; i++) { - for (j = 0; j < C; j++) { - if (max_of_s < S[i][j]) { - max_of_s = S[i][j]; - max_i = i; - max_j = j; - } - } + /* Find the maximum entry, and indexes of maximum entry + in S[][] */ + max_of_s = S[0][0]; + max_i = 0; + max_j = 0; + for (i = 0; i < R; i++) { + for (j = 0; j < C; j++) { + if (max_of_s < S[i][j]) { + max_of_s = S[i][j]; + max_i = i; + max_j = j; + } } + } - cout << "Maximum size sub-matrix is: \n"; - for (i = max_i; i > max_i - max_of_s; i--) { - for (j = max_j; j > max_j - max_of_s; j--) { - cout << M[i][j] << " "; - } - cout << "\n"; + cout << "Maximum size sub-matrix is: \n"; + for (i = max_i; i > max_i - max_of_s; i--) { + for (j = max_j; j > max_j - max_of_s; j--) { + cout << M[i][j] << " "; } + cout << "\n"; + } } /* Driver code */ int main() { - bool M[R][C] = {{0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, - {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}}; + bool M[R][C] = {{0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, + {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}}; - printMaxSubSquare(M); + printMaxSubSquare(M); } // This is code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/maximum-sum-increasing-subsequence.cpp b/src/test-suite/PE-benchmarks/maximum-sum-increasing-subsequence.cpp index 8965d1c3..5245056d 100644 --- a/src/test-suite/PE-benchmarks/maximum-sum-increasing-subsequence.cpp +++ b/src/test-suite/PE-benchmarks/maximum-sum-increasing-subsequence.cpp @@ -8,38 +8,38 @@ using namespace std; sum of increasing subsequence in arr[] of size n */ int maxSumIS(int arr[], int n) { - int i, j, max = 0; - int msis[n]; + int i, j, max = 0; + int msis[n]; - /* Initialize msis values - for all indexes */ - for (i = 0; i < n; i++) - msis[i] = arr[i]; + /* Initialize msis values + for all indexes */ + for (i = 0; i < n; i++) + msis[i] = arr[i]; - /* Compute maximum sum values - in bottom up manner */ - for (i = 1; i < n; i++) - for (j = 0; j < i; j++) - if (arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) - msis[i] = msis[j] + arr[i]; + /* Compute maximum sum values + in bottom up manner */ + for (i = 1; i < n; i++) + for (j = 0; j < i; j++) + if (arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) + msis[i] = msis[j] + arr[i]; - /* Pick maximum of - all msis values */ - for (i = 0; i < n; i++) - if (max < msis[i]) - max = msis[i]; + /* Pick maximum of + all msis values */ + for (i = 0; i < n; i++) + if (max < msis[i]) + max = msis[i]; - return max; + return max; } // Driver Code int main() { - int arr[] = {1, 101, 2, 3, 100, 4, 5}; - int n = sizeof(arr) / sizeof(arr[0]); - cout << "Sum of maximum sum increasing " - "subsequence is " - << maxSumIS(arr, n) << endl; - return 0; + int arr[] = {1, 101, 2, 3, 100, 4, 5}; + int n = sizeof(arr) / sizeof(arr[0]); + cout << "Sum of maximum sum increasing " + "subsequence is " + << maxSumIS(arr, n) << endl; + return 0; } // This is code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/maximum-sum-rectangle-in-a-2d-matrix.cpp b/src/test-suite/PE-benchmarks/maximum-sum-rectangle-in-a-2d-matrix.cpp index c1f43de1..d079dbff 100644 --- a/src/test-suite/PE-benchmarks/maximum-sum-rectangle-in-a-2d-matrix.cpp +++ b/src/test-suite/PE-benchmarks/maximum-sum-rectangle-in-a-2d-matrix.cpp @@ -13,110 +13,110 @@ using namespace std; // pointed by start and finish pointers // respectively. int kadane(int *arr, int *start, int *finish, int n) { - // initialize sum, maxSum and - int sum = 0, maxSum = INT_MIN, i; - - // Just some initial value to check - // for all negative values case - *finish = -1; - - // local variable - int local_start = 0; - - for (i = 0; i < n; ++i) { - sum += arr[i]; - if (sum < 0) { - sum = 0; - local_start = i + 1; - } else if (sum > maxSum) { - maxSum = sum; - *start = local_start; - *finish = i; - } + // initialize sum, maxSum and + int sum = 0, maxSum = INT_MIN, i; + + // Just some initial value to check + // for all negative values case + *finish = -1; + + // local variable + int local_start = 0; + + for (i = 0; i < n; ++i) { + sum += arr[i]; + if (sum < 0) { + sum = 0; + local_start = i + 1; + } else if (sum > maxSum) { + maxSum = sum; + *start = local_start; + *finish = i; } + } - // There is at-least one - // non-negative number - if (*finish != -1) - return maxSum; - - // Special Case: When all numbers - // in arr[] are negative - maxSum = arr[0]; - *start = *finish = 0; - - // Find the maximum element in array - for (i = 1; i < n; i++) { - if (arr[i] > maxSum) { - maxSum = arr[i]; - *start = *finish = i; - } - } + // There is at-least one + // non-negative number + if (*finish != -1) return maxSum; + + // Special Case: When all numbers + // in arr[] are negative + maxSum = arr[0]; + *start = *finish = 0; + + // Find the maximum element in array + for (i = 1; i < n; i++) { + if (arr[i] > maxSum) { + maxSum = arr[i]; + *start = *finish = i; + } + } + return maxSum; } // The main function that finds // maximum sum rectangle in M[][] void findMaxSum(int M[][COL]) { - // Variables to store the final output - int maxSum = INT_MIN, finalLeft, finalRight, finalTop, finalBottom; - - int left, right, i; - int temp[ROW], sum, start, finish; - - // Set the left column - for (left = 0; left < COL; ++left) { - // Initialize all elements of temp as 0 - memset(temp, 0, sizeof(temp)); - - // Set the right column for the left - // column set by outer loop - for (right = left; right < COL; ++right) { - - // Calculate sum between current left - // and right for every row 'i' - for (i = 0; i < ROW; ++i) - temp[i] += M[i][right]; - - // Find the maximum sum subarray in temp[]. - // The kadane() function also sets values - // of start and finish. So 'sum' is sum of - // rectangle between (start, left) and - // (finish, right) which is the maximum sum - // with boundary columns strictly as left - // and right. - sum = kadane(temp, &start, &finish, ROW); - - // Compare sum with maximum sum so far. - // If sum is more, then update maxSum and - // other output values - if (sum > maxSum) { - maxSum = sum; - finalLeft = left; - finalRight = right; - finalTop = start; - finalBottom = finish; - } - } + // Variables to store the final output + int maxSum = INT_MIN, finalLeft, finalRight, finalTop, finalBottom; + + int left, right, i; + int temp[ROW], sum, start, finish; + + // Set the left column + for (left = 0; left < COL; ++left) { + // Initialize all elements of temp as 0 + memset(temp, 0, sizeof(temp)); + + // Set the right column for the left + // column set by outer loop + for (right = left; right < COL; ++right) { + + // Calculate sum between current left + // and right for every row 'i' + for (i = 0; i < ROW; ++i) + temp[i] += M[i][right]; + + // Find the maximum sum subarray in temp[]. + // The kadane() function also sets values + // of start and finish. So 'sum' is sum of + // rectangle between (start, left) and + // (finish, right) which is the maximum sum + // with boundary columns strictly as left + // and right. + sum = kadane(temp, &start, &finish, ROW); + + // Compare sum with maximum sum so far. + // If sum is more, then update maxSum and + // other output values + if (sum > maxSum) { + maxSum = sum; + finalLeft = left; + finalRight = right; + finalTop = start; + finalBottom = finish; + } } + } - // Print final values - cout << "(Top, Left) (" << finalTop << ", " << finalLeft << ")" << endl; - cout << "(Bottom, Right) (" << finalBottom << ", " << finalRight << ")" - << endl; - cout << "Max sum is: " << maxSum << endl; + // Print final values + cout << "(Top, Left) (" << finalTop << ", " << finalLeft << ")" << endl; + cout << "(Bottom, Right) (" << finalBottom << ", " << finalRight << ")" + << endl; + cout << "Max sum is: " << maxSum << endl; } // Driver Code int main() { - int M[ROW][COL] = {{1, 2, -1, -4, -20}, - {-8, -3, 4, 2, 1}, - {3, 8, 10, 1, 3}, - {-4, -1, 1, 7, -6}}; + int M[ROW][COL] = {{1, 2, -1, -4, -20}, + {-8, -3, 4, 2, 1}, + {3, 8, 10, 1, 3}, + {-4, -1, 1, 7, -6}}; - findMaxSum(M); + findMaxSum(M); - return 0; + return 0; } // This code is contributed by diff --git a/src/test-suite/PE-benchmarks/merge-sort-for-doubly-linked-list.cpp b/src/test-suite/PE-benchmarks/merge-sort-for-doubly-linked-list.cpp index 4f79cfad..d62c2f7e 100644 --- a/src/test-suite/PE-benchmarks/merge-sort-for-doubly-linked-list.cpp +++ b/src/test-suite/PE-benchmarks/merge-sort-for-doubly-linked-list.cpp @@ -2,116 +2,116 @@ #include using namespace std; class Node { - public: - int data; - Node *next, *prev; +public: + int data; + Node *next, *prev; }; Node *split(Node *head); // Function to merge two linked lists Node *merge(Node *first, Node *second) { - // If first linked list is empty - if (!first) - return second; + // If first linked list is empty + if (!first) + return second; - // If second linked list is empty - if (!second) - return first; + // If second linked list is empty + if (!second) + return first; - // Pick the smaller value - if (first->data < second->data) { - first->next = merge(first->next, second); - first->next->prev = first; - first->prev = NULL; - return first; - } else { - second->next = merge(first, second->next); - second->next->prev = second; - second->prev = NULL; - return second; - } + // Pick the smaller value + if (first->data < second->data) { + first->next = merge(first->next, second); + first->next->prev = first; + first->prev = NULL; + return first; + } else { + second->next = merge(first, second->next); + second->next->prev = second; + second->prev = NULL; + return second; + } } // Function to do merge sort Node *mergeSort(Node *head) { - if (!head || !head->next) - return head; - Node *second = split(head); + if (!head || !head->next) + return head; + Node *second = split(head); - // Recur for left and right halves - head = mergeSort(head); - second = mergeSort(second); + // Recur for left and right halves + head = mergeSort(head); + second = mergeSort(second); - // Merge the two sorted halves - return merge(head, second); + // Merge the two sorted halves + return merge(head, second); } // A utility function to insert a new node at the // beginning of doubly linked list void insert(Node **head, int data) { - Node *temp = new Node(); - temp->data = data; - temp->next = temp->prev = NULL; - if (!(*head)) - (*head) = temp; - else { - temp->next = *head; - (*head)->prev = temp; - (*head) = temp; - } + Node *temp = new Node(); + temp->data = data; + temp->next = temp->prev = NULL; + if (!(*head)) + (*head) = temp; + else { + temp->next = *head; + (*head)->prev = temp; + (*head) = temp; + } } // A utility function to print a doubly linked list in // both forward and backward directions void print(Node *head) { - Node *temp = head; - cout << "Forward Traversal using next poitner\n"; - while (head) { - cout << head->data << " "; - temp = head; - head = head->next; - } - cout << "\nBackward Traversal using prev pointer\n"; - while (temp) { - cout << temp->data << " "; - temp = temp->prev; - } + Node *temp = head; + cout << "Forward Traversal using next poitner\n"; + while (head) { + cout << head->data << " "; + temp = head; + head = head->next; + } + cout << "\nBackward Traversal using prev pointer\n"; + while (temp) { + cout << temp->data << " "; + temp = temp->prev; + } } // Utility function to swap two integers void swap(int *A, int *B) { - int temp = *A; - *A = *B; - *B = temp; + int temp = *A; + *A = *B; + *B = temp; } // Split a doubly linked list (DLL) into 2 DLLs of // half sizes Node *split(Node *head) { - Node *fast = head, *slow = head; - while (fast->next && fast->next->next) { - fast = fast->next->next; - slow = slow->next; - } - Node *temp = slow->next; - slow->next = NULL; - return temp; + Node *fast = head, *slow = head; + while (fast->next && fast->next->next) { + fast = fast->next->next; + slow = slow->next; + } + Node *temp = slow->next; + slow->next = NULL; + return temp; } // Driver program int main(void) { - Node *head = NULL; - insert(&head, 5); - insert(&head, 20); - insert(&head, 4); - insert(&head, 3); - insert(&head, 30); - insert(&head, 10); - head = mergeSort(head); - cout << "Linked List after sorting\n"; - print(head); - return 0; + Node *head = NULL; + insert(&head, 5); + insert(&head, 20); + insert(&head, 4); + insert(&head, 3); + insert(&head, 30); + insert(&head, 10); + head = mergeSort(head); + cout << "Linked List after sorting\n"; + print(head); + return 0; } // This is code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/mergeSort_LinkedList.cpp b/src/test-suite/PE-benchmarks/mergeSort_LinkedList.cpp index 99adccd9..bc0d8f84 100644 --- a/src/test-suite/PE-benchmarks/mergeSort_LinkedList.cpp +++ b/src/test-suite/PE-benchmarks/mergeSort_LinkedList.cpp @@ -4,9 +4,9 @@ using namespace std; /* Link list node */ class Node { - public: - int data; - Node *next; +public: + int data; + Node *next; }; /* function prototypes */ @@ -15,46 +15,46 @@ void FrontBackSplit(Node *source, Node **frontRef, Node **backRef); /* sorts the linked list by changing next pointers (not data) */ void MergeSort(Node **headRef) { - Node *head = *headRef; - Node *a; - Node *b; + Node *head = *headRef; + Node *a; + Node *b; - /* Base case -- length 0 or 1 */ - if ((head == NULL) || (head->next == NULL)) { - return; - } + /* Base case -- length 0 or 1 */ + if ((head == NULL) || (head->next == NULL)) { + return; + } - /* Split head into 'a' and 'b' sublists */ - FrontBackSplit(head, &a, &b); + /* Split head into 'a' and 'b' sublists */ + FrontBackSplit(head, &a, &b); - /* Recursively sort the sublists */ - MergeSort(&a); - MergeSort(&b); + /* Recursively sort the sublists */ + MergeSort(&a); + MergeSort(&b); - /* answer = merge the two sorted lists together */ - *headRef = SortedMerge(a, b); + /* answer = merge the two sorted lists together */ + *headRef = SortedMerge(a, b); } /* See https:// www.geeksforgeeks.org/?p=3622 for details of this function */ Node *SortedMerge(Node *a, Node *b) { - Node *result = NULL; - - /* Base cases */ - if (a == NULL) - return (b); - else if (b == NULL) - return (a); - - /* Pick either a or b, and recur */ - if (a->data <= b->data) { - result = a; - result->next = SortedMerge(a->next, b); - } else { - result = b; - result->next = SortedMerge(a, b->next); - } - return (result); + Node *result = NULL; + + /* Base cases */ + if (a == NULL) + return (b); + else if (b == NULL) + return (a); + + /* Pick either a or b, and recur */ + if (a->data <= b->data) { + result = a; + result->next = SortedMerge(a->next, b); + } else { + result = b; + result->next = SortedMerge(a, b->next); + } + return (result); } /* UTILITY FUNCTIONS */ @@ -63,72 +63,72 @@ Node *SortedMerge(Node *a, Node *b) { If the length is odd, the extra node should go in the front list. Uses the fast/slow pointer strategy. */ void FrontBackSplit(Node *source, Node **frontRef, Node **backRef) { - Node *fast; - Node *slow; - slow = source; - fast = source->next; - - /* Advance 'fast' two nodes, and advance 'slow' one node */ - while (fast != NULL) { - fast = fast->next; - if (fast != NULL) { - slow = slow->next; - fast = fast->next; - } + Node *fast; + Node *slow; + slow = source; + fast = source->next; + + /* Advance 'fast' two nodes, and advance 'slow' one node */ + while (fast != NULL) { + fast = fast->next; + if (fast != NULL) { + slow = slow->next; + fast = fast->next; } + } - /* 'slow' is before the midpoint in the list, so split it in two - at that point. */ - *frontRef = source; - *backRef = slow->next; - slow->next = NULL; + /* 'slow' is before the midpoint in the list, so split it in two + at that point. */ + *frontRef = source; + *backRef = slow->next; + slow->next = NULL; } /* Function to print nodes in a given linked list */ void printList(Node *node) { - while (node != NULL) { - cout << node->data << " "; - node = node->next; - } + while (node != NULL) { + cout << node->data << " "; + node = node->next; + } } /* Function to insert a node at the beginging of the linked list */ void push(Node **head_ref, int new_data) { - /* allocate node */ - Node *new_node = new Node(); + /* allocate node */ + Node *new_node = new Node(); - /* put in the data */ - new_node->data = new_data; + /* put in the data */ + new_node->data = new_data; - /* link the old list off the new node */ - new_node->next = (*head_ref); + /* link the old list off the new node */ + new_node->next = (*head_ref); - /* move the head to point to the new node */ - (*head_ref) = new_node; + /* move the head to point to the new node */ + (*head_ref) = new_node; } /* Drier program to test above functions*/ int main() { - /* Start with the empty list */ - Node *res = NULL; - Node *a = NULL; - - /* Let us create a unsorted linked lists to test the functions - Created lists shall be a: 2->3->20->5->10->15 */ - push(&a, 15); - push(&a, 10); - push(&a, 5); - push(&a, 20); - push(&a, 3); - push(&a, 2); - - /* Sort the above created Linked List */ - MergeSort(&a); - - cout << "Sorted Linked List is: \n"; - printList(a); - - return 0; + /* Start with the empty list */ + Node *res = NULL; + Node *a = NULL; + + /* Let us create a unsorted linked lists to test the functions +Created lists shall be a: 2->3->20->5->10->15 */ + push(&a, 15); + push(&a, 10); + push(&a, 5); + push(&a, 20); + push(&a, 3); + push(&a, 2); + + /* Sort the above created Linked List */ + MergeSort(&a); + + cout << "Sorted Linked List is: \n"; + printList(a); + + return 0; } // This is code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/min-cost-path.cpp b/src/test-suite/PE-benchmarks/min-cost-path.cpp index a6bf1590..43eeb11e 100644 --- a/src/test-suite/PE-benchmarks/min-cost-path.cpp +++ b/src/test-suite/PE-benchmarks/min-cost-path.cpp @@ -8,27 +8,26 @@ int min(int x, int y, int z); /* Returns cost of minimum cost path from (0,0) to (m, n) in mat[R][C]*/ int minCost(int cost[R][C], int m, int n) { - if (n < 0 || m < 0) - return INT_MAX; - else if (m == 0 && n == 0) - return cost[m][n]; - else - return cost[m][n] + min(minCost(cost, m - 1, n - 1), - minCost(cost, m - 1, n), - minCost(cost, m, n - 1)); + if (n < 0 || m < 0) + return INT_MAX; + else if (m == 0 && n == 0) + return cost[m][n]; + else + return cost[m][n] + min(minCost(cost, m - 1, n - 1), + minCost(cost, m - 1, n), minCost(cost, m, n - 1)); } /* A utility function that returns minimum of 3 integers */ int min(int x, int y, int z) { - if (x < y) - return (x < z) ? x : z; - else - return (y < z) ? y : z; + if (x < y) + return (x < z) ? x : z; + else + return (y < z) ? y : z; } /* Driver program to test above functions */ int main() { - int cost[R][C] = {{1, 2, 3}, {4, 8, 2}, {1, 5, 3}}; - printf(" %d ", minCost(cost, 2, 2)); - return 0; + int cost[R][C] = {{1, 2, 3}, {4, 8, 2}, {1, 5, 3}}; + printf(" %d ", minCost(cost, 2, 2)); + return 0; } diff --git a/src/test-suite/PE-benchmarks/minimum-adjacent-swaps-to-move-maximum-and-minimum-to-corners.cpp b/src/test-suite/PE-benchmarks/minimum-adjacent-swaps-to-move-maximum-and-minimum-to-corners.cpp index 787f9b49..38049ecf 100644 --- a/src/test-suite/PE-benchmarks/minimum-adjacent-swaps-to-move-maximum-and-minimum-to-corners.cpp +++ b/src/test-suite/PE-benchmarks/minimum-adjacent-swaps-to-move-maximum-and-minimum-to-corners.cpp @@ -7,31 +7,31 @@ using namespace std; // Function that returns the minimum swaps void solve(int a[], int n) { - int maxx = -1, minn = a[0], l = 0, r = 0; - for (int i = 0; i < n; i++) { + int maxx = -1, minn = a[0], l = 0, r = 0; + for (int i = 0; i < n; i++) { - // Index of leftmost largest element - if (a[i] > maxx) { - maxx = a[i]; - l = i; - } + // Index of leftmost largest element + if (a[i] > maxx) { + maxx = a[i]; + l = i; + } - // Index of rightmost smallest element - if (a[i] <= minn) { - minn = a[i]; - r = i; - } + // Index of rightmost smallest element + if (a[i] <= minn) { + minn = a[i]; + r = i; } - if (r < l) - cout << l + (n - r - 2); - else - cout << l + (n - r - 1); + } + if (r < l) + cout << l + (n - r - 2); + else + cout << l + (n - r - 1); } // Driver Code int main() { - int a[] = {5, 6, 1, 3}; - int n = sizeof(a) / sizeof(a[0]); - solve(a, n); - return 0; + int a[] = {5, 6, 1, 3}; + int n = sizeof(a) / sizeof(a[0]); + solve(a, n); + return 0; } diff --git a/src/test-suite/PE-benchmarks/minimum-cost-polygon-triangulation.cpp b/src/test-suite/PE-benchmarks/minimum-cost-polygon-triangulation.cpp index 7edef35f..d38decdd 100644 --- a/src/test-suite/PE-benchmarks/minimum-cost-polygon-triangulation.cpp +++ b/src/test-suite/PE-benchmarks/minimum-cost-polygon-triangulation.cpp @@ -7,7 +7,7 @@ using namespace std; // Structure of a point in 2D plane struct Point { - int x, y; + int x, y; }; // Utility function to find minimum of two double values @@ -15,53 +15,52 @@ double min(double x, double y) { return (x <= y) ? x : y; } // A utility function to find distance between two points in a plane double dist(Point p1, Point p2) { - return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)); + return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)); } // A utility function to find cost of a triangle. The cost is considered // as perimeter (sum of lengths of all edges) of the triangle double cost(Point points[], int i, int j, int k) { - Point p1 = points[i], p2 = points[j], p3 = points[k]; - return dist(p1, p2) + dist(p2, p3) + dist(p3, p1); + Point p1 = points[i], p2 = points[j], p3 = points[k]; + return dist(p1, p2) + dist(p2, p3) + dist(p3, p1); } // A Dynamic programming based function to find minimum cost for convex // polygon triangulation. double mTCDP(Point points[], int n) { - // There must be at least 3 points to form a triangle - if (n < 3) - return 0; + // There must be at least 3 points to form a triangle + if (n < 3) + return 0; - // table to store results of subproblems. table[i][j] stores cost of - // triangulation of points from i to j. The entry table[0][n-1] stores - // the final result. - double table[n][n]; + // table to store results of subproblems. table[i][j] stores cost of + // triangulation of points from i to j. The entry table[0][n-1] stores + // the final result. + double table[n][n]; - // Fill table using above recursive formula. Note that the table - // is filled in diagonal fashion i.e., from diagonal elements to - // table[0][n-1] which is the result. - for (int gap = 0; gap < n; gap++) { - for (int i = 0, j = gap; j < n; i++, j++) { - if (j < i + 2) - table[i][j] = 0.0; - else { - table[i][j] = MAX; - for (int k = i + 1; k < j; k++) { - double val = - table[i][k] + table[k][j] + cost(points, i, j, k); - if (table[i][j] > val) - table[i][j] = val; - } - } + // Fill table using above recursive formula. Note that the table + // is filled in diagonal fashion i.e., from diagonal elements to + // table[0][n-1] which is the result. + for (int gap = 0; gap < n; gap++) { + for (int i = 0, j = gap; j < n; i++, j++) { + if (j < i + 2) + table[i][j] = 0.0; + else { + table[i][j] = MAX; + for (int k = i + 1; k < j; k++) { + double val = table[i][k] + table[k][j] + cost(points, i, j, k); + if (table[i][j] > val) + table[i][j] = val; } + } } - return table[0][n - 1]; + } + return table[0][n - 1]; } // Driver program to test above functions int main() { - Point points[] = {{0, 0}, {1, 0}, {2, 1}, {1, 2}, {0, 2}}; - int n = sizeof(points) / sizeof(points[0]); - cout << mTCDP(points, n); - return 0; + Point points[] = {{0, 0}, {1, 0}, {2, 1}, {1, 2}, {0, 2}}; + int n = sizeof(points) / sizeof(points[0]); + cout << mTCDP(points, n); + return 0; } diff --git a/src/test-suite/PE-benchmarks/minimum-cut-in-a-directed-graph.cpp b/src/test-suite/PE-benchmarks/minimum-cut-in-a-directed-graph.cpp index 71d45c9b..1754adc9 100644 --- a/src/test-suite/PE-benchmarks/minimum-cut-in-a-directed-graph.cpp +++ b/src/test-suite/PE-benchmarks/minimum-cut-in-a-directed-graph.cpp @@ -11,103 +11,103 @@ using namespace std; /* Returns true if there is a path from source 's' to sink 't' in residual graph. Also fills parent[] to store the path */ int bfs(int rGraph[V][V], int s, int t, int parent[]) { - // Create a visited array and mark all vertices as not visited - bool visited[V]; - memset(visited, 0, sizeof(visited)); - - // Create a queue, enqueue source vertex and mark source vertex - // as visited - queue q; - q.push(s); - visited[s] = true; - parent[s] = -1; - - // Standard BFS Loop - while (!q.empty()) { - int u = q.front(); - q.pop(); - - for (int v = 0; v < V; v++) { - if (visited[v] == false && rGraph[u][v] > 0) { - q.push(v); - parent[v] = u; - visited[v] = true; - } - } + // Create a visited array and mark all vertices as not visited + bool visited[V]; + memset(visited, 0, sizeof(visited)); + + // Create a queue, enqueue source vertex and mark source vertex + // as visited + queue q; + q.push(s); + visited[s] = true; + parent[s] = -1; + + // Standard BFS Loop + while (!q.empty()) { + int u = q.front(); + q.pop(); + + for (int v = 0; v < V; v++) { + if (visited[v] == false && rGraph[u][v] > 0) { + q.push(v); + parent[v] = u; + visited[v] = true; + } } + } - // If we reached sink in BFS starting from source, then return - // true, else false - return (visited[t] == true); + // If we reached sink in BFS starting from source, then return + // true, else false + return (visited[t] == true); } // A DFS based function to find all reachable vertices from s. The function // marks visited[i] as true if i is reachable from s. The initial values in // visited[] must be false. We can also use BFS to find reachable vertices void dfs(int rGraph[V][V], int s, bool visited[]) { - visited[s] = true; - for (int i = 0; i < V; i++) - if (rGraph[s][i] && !visited[i]) - dfs(rGraph, i, visited); + visited[s] = true; + for (int i = 0; i < V; i++) + if (rGraph[s][i] && !visited[i]) + dfs(rGraph, i, visited); } // Prints the minimum s-t cut void minCut(int graph[V][V], int s, int t) { - int u, v; - - // Create a residual graph and fill the residual graph with - // given capacities in the original graph as residual capacities - // in residual graph - int rGraph[V][V]; // rGraph[i][j] indicates residual capacity of edge i-j - for (u = 0; u < V; u++) - for (v = 0; v < V; v++) - rGraph[u][v] = graph[u][v]; - - int parent[V]; // This array is filled by BFS and to store path - - // Augment the flow while there is a path from source to sink - while (bfs(rGraph, s, t, parent)) { - // Find minimum residual capacity of the edhes along the - // path filled by BFS. Or we can say find the maximum flow - // through the path found. - int path_flow = INT_MAX; - for (v = t; v != s; v = parent[v]) { - u = parent[v]; - path_flow = min(path_flow, rGraph[u][v]); - } - - // update residual capacities of the edges and reverse edges - // along the path - for (v = t; v != s; v = parent[v]) { - u = parent[v]; - rGraph[u][v] -= path_flow; - rGraph[v][u] += path_flow; - } + int u, v; + + // Create a residual graph and fill the residual graph with + // given capacities in the original graph as residual capacities + // in residual graph + int rGraph[V][V]; // rGraph[i][j] indicates residual capacity of edge i-j + for (u = 0; u < V; u++) + for (v = 0; v < V; v++) + rGraph[u][v] = graph[u][v]; + + int parent[V]; // This array is filled by BFS and to store path + + // Augment the flow while there is a path from source to sink + while (bfs(rGraph, s, t, parent)) { + // Find minimum residual capacity of the edhes along the + // path filled by BFS. Or we can say find the maximum flow + // through the path found. + int path_flow = INT_MAX; + for (v = t; v != s; v = parent[v]) { + u = parent[v]; + path_flow = min(path_flow, rGraph[u][v]); } - // Flow is maximum now, find vertices reachable from s - bool visited[V]; - memset(visited, false, sizeof(visited)); - dfs(rGraph, s, visited); + // update residual capacities of the edges and reverse edges + // along the path + for (v = t; v != s; v = parent[v]) { + u = parent[v]; + rGraph[u][v] -= path_flow; + rGraph[v][u] += path_flow; + } + } + + // Flow is maximum now, find vertices reachable from s + bool visited[V]; + memset(visited, false, sizeof(visited)); + dfs(rGraph, s, visited); - // Print all edges that are from a reachable vertex to - // non-reachable vertex in the original graph - for (int i = 0; i < V; i++) - for (int j = 0; j < V; j++) - if (visited[i] && !visited[j] && graph[i][j]) - cout << i << " - " << j << endl; + // Print all edges that are from a reachable vertex to + // non-reachable vertex in the original graph + for (int i = 0; i < V; i++) + for (int j = 0; j < V; j++) + if (visited[i] && !visited[j] && graph[i][j]) + cout << i << " - " << j << endl; - return; + return; } // Driver program to test above functions int main() { - // Let us create a graph shown in the above example - int graph[V][V] = {{0, 16, 13, 0, 0, 0}, {0, 0, 10, 12, 0, 0}, - {0, 4, 0, 0, 14, 0}, {0, 0, 9, 0, 0, 20}, - {0, 0, 0, 7, 0, 4}, {0, 0, 0, 0, 0, 0}}; + // Let us create a graph shown in the above example + int graph[V][V] = {{0, 16, 13, 0, 0, 0}, {0, 0, 10, 12, 0, 0}, + {0, 4, 0, 0, 14, 0}, {0, 0, 9, 0, 0, 20}, + {0, 0, 0, 7, 0, 4}, {0, 0, 0, 0, 0, 0}}; - minCut(graph, 0, 5); + minCut(graph, 0, 5); - return 0; + return 0; } diff --git a/src/test-suite/PE-benchmarks/minimum-number-of-jumps-to-reach-end-of-a-given-array.cpp b/src/test-suite/PE-benchmarks/minimum-number-of-jumps-to-reach-end-of-a-given-array.cpp index 2c728517..b0bea378 100644 --- a/src/test-suite/PE-benchmarks/minimum-number-of-jumps-to-reach-end-of-a-given-array.cpp +++ b/src/test-suite/PE-benchmarks/minimum-number-of-jumps-to-reach-end-of-a-given-array.cpp @@ -7,35 +7,35 @@ int min(int x, int y) { return (x < y) ? x : y; } // Returns minimum number of jumps // to reach arr[n-1] from arr[0] int minJumps(int arr[], int n) { - // jumps[n-1] will hold the result - int *jumps = new int[n]; - int i, j; + // jumps[n-1] will hold the result + int *jumps = new int[n]; + int i, j; - if (n == 0 || arr[0] == 0) - return INT_MAX; + if (n == 0 || arr[0] == 0) + return INT_MAX; - jumps[0] = 0; + jumps[0] = 0; - // Find the minimum number of jumps to reach arr[i] - // from arr[0], and assign this value to jumps[i] - for (i = 1; i < n; i++) { - jumps[i] = INT_MAX; - for (j = 0; j < i; j++) { - if (i <= j + arr[j] && jumps[j] != INT_MAX) { - jumps[i] = min(jumps[i], jumps[j] + 1); - break; - } - } + // Find the minimum number of jumps to reach arr[i] + // from arr[0], and assign this value to jumps[i] + for (i = 1; i < n; i++) { + jumps[i] = INT_MAX; + for (j = 0; j < i; j++) { + if (i <= j + arr[j] && jumps[j] != INT_MAX) { + jumps[i] = min(jumps[i], jumps[j] + 1); + break; + } } - return jumps[n - 1]; + } + return jumps[n - 1]; } // Driver code int main() { - int arr[] = {1, 3, 6, 1, 0, 9}; - int size = sizeof(arr) / sizeof(int); - cout << "Minimum number of jumps to reach end is " << minJumps(arr, size); - return 0; + int arr[] = {1, 3, 6, 1, 0, 9}; + int size = sizeof(arr) / sizeof(int); + cout << "Minimum number of jumps to reach end is " << minJumps(arr, size); + return 0; } // This is code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/minimum-positive-points-to-reach-destination.cpp b/src/test-suite/PE-benchmarks/minimum-positive-points-to-reach-destination.cpp index 38af5ae8..83fcbf0f 100644 --- a/src/test-suite/PE-benchmarks/minimum-positive-points-to-reach-destination.cpp +++ b/src/test-suite/PE-benchmarks/minimum-positive-points-to-reach-destination.cpp @@ -6,38 +6,38 @@ using namespace std; int minInitialPoints(int points[][C]) { - // dp[i][j] represents the minimum initial points player - // should have so that when starts with cell(i, j) successfully - // reaches the destination cell(m-1, n-1) - int dp[R][C]; - int m = R, n = C; - - // Base case - dp[m - 1][n - 1] = - points[m - 1][n - 1] > 0 ? 1 : abs(points[m - 1][n - 1]) + 1; - - // Fill last row and last column as base to fill - // entire table - for (int i = m - 2; i >= 0; i--) - dp[i][n - 1] = max(dp[i + 1][n - 1] - points[i][n - 1], 1); - for (int j = n - 2; j >= 0; j--) - dp[m - 1][j] = max(dp[m - 1][j + 1] - points[m - 1][j], 1); - - // fill the table in bottom-up fashion - for (int i = m - 2; i >= 0; i--) { - for (int j = n - 2; j >= 0; j--) { - int min_points_on_exit = min(dp[i + 1][j], dp[i][j + 1]); - dp[i][j] = max(min_points_on_exit - points[i][j], 1); - } + // dp[i][j] represents the minimum initial points player + // should have so that when starts with cell(i, j) successfully + // reaches the destination cell(m-1, n-1) + int dp[R][C]; + int m = R, n = C; + + // Base case + dp[m - 1][n - 1] = + points[m - 1][n - 1] > 0 ? 1 : abs(points[m - 1][n - 1]) + 1; + + // Fill last row and last column as base to fill + // entire table + for (int i = m - 2; i >= 0; i--) + dp[i][n - 1] = max(dp[i + 1][n - 1] - points[i][n - 1], 1); + for (int j = n - 2; j >= 0; j--) + dp[m - 1][j] = max(dp[m - 1][j + 1] - points[m - 1][j], 1); + + // fill the table in bottom-up fashion + for (int i = m - 2; i >= 0; i--) { + for (int j = n - 2; j >= 0; j--) { + int min_points_on_exit = min(dp[i + 1][j], dp[i][j + 1]); + dp[i][j] = max(min_points_on_exit - points[i][j], 1); } + } - return dp[0][0]; + return dp[0][0]; } // Driver Program int main() { - int points[R][C] = {{-2, -3, 3}, {-5, -10, 1}, {10, 30, -5}}; - cout << "Minimum Initial Points Required: " << minInitialPoints(points); - return 0; + int points[R][C] = {{-2, -3, 3}, {-5, -10, 1}, {10, 30, -5}}; + cout << "Minimum Initial Points Required: " << minInitialPoints(points); + return 0; } diff --git a/src/test-suite/PE-benchmarks/mobile-numeric-keypad-problem.cpp b/src/test-suite/PE-benchmarks/mobile-numeric-keypad-problem.cpp index a179bee7..ac9947a9 100644 --- a/src/test-suite/PE-benchmarks/mobile-numeric-keypad-problem.cpp +++ b/src/test-suite/PE-benchmarks/mobile-numeric-keypad-problem.cpp @@ -5,77 +5,77 @@ // Return count of all possible numbers of length n // in a given numeric keyboard int getCount(char keypad[][3], int n) { - if (keypad == NULL || n <= 0) - return 0; - if (n == 1) - return 10; + if (keypad == NULL || n <= 0) + return 0; + if (n == 1) + return 10; - // left, up, right, down move from current location - int row[] = {0, 0, -1, 0, 1}; - int col[] = {0, -1, 0, 1, 0}; + // left, up, right, down move from current location + int row[] = {0, 0, -1, 0, 1}; + int col[] = {0, -1, 0, 1, 0}; - // taking n+1 for simplicity - count[i][j] will store - // number count starting with digit i and length j - int count[10][n + 1]; - int i = 0, j = 0, k = 0, move = 0, ro = 0, co = 0, num = 0; - int nextNum = 0, totalCount = 0; + // taking n+1 for simplicity - count[i][j] will store + // number count starting with digit i and length j + int count[10][n + 1]; + int i = 0, j = 0, k = 0, move = 0, ro = 0, co = 0, num = 0; + int nextNum = 0, totalCount = 0; - // count numbers starting with digit i and of lengths 0 and 1 - for (i = 0; i <= 9; i++) { - count[i][0] = 0; - count[i][1] = 1; - } + // count numbers starting with digit i and of lengths 0 and 1 + for (i = 0; i <= 9; i++) { + count[i][0] = 0; + count[i][1] = 1; + } - // Bottom up - Get number count of length 2, 3, 4, ... , n - for (k = 2; k <= n; k++) { - for (i = 0; i < 4; i++) // Loop on keypad row - { - for (j = 0; j < 3; j++) // Loop on keypad column - { - // Process for 0 to 9 digits - if (keypad[i][j] != '*' && keypad[i][j] != '#') { - // Here we are counting the numbers starting with - // digit keypad[i][j] and of length k keypad[i][j] - // will become 1st digit, and we need to look for - // (k-1) more digits - num = keypad[i][j] - '0'; - count[num][k] = 0; + // Bottom up - Get number count of length 2, 3, 4, ... , n + for (k = 2; k <= n; k++) { + for (i = 0; i < 4; i++) // Loop on keypad row + { + for (j = 0; j < 3; j++) // Loop on keypad column + { + // Process for 0 to 9 digits + if (keypad[i][j] != '*' && keypad[i][j] != '#') { + // Here we are counting the numbers starting with + // digit keypad[i][j] and of length k keypad[i][j] + // will become 1st digit, and we need to look for + // (k-1) more digits + num = keypad[i][j] - '0'; + count[num][k] = 0; - // move left, up, right, down from current location - // and if new location is valid, then get number - // count of length (k-1) from that new digit and - // add in count we found so far - for (move = 0; move < 5; move++) { - ro = i + row[move]; - co = j + col[move]; - if (ro >= 0 && ro <= 3 && co >= 0 && co <= 2 && - keypad[ro][co] != '*' && keypad[ro][co] != '#') { - nextNum = keypad[ro][co] - '0'; - count[num][k] += count[nextNum][k - 1]; - } - } - } + // move left, up, right, down from current location + // and if new location is valid, then get number + // count of length (k-1) from that new digit and + // add in count we found so far + for (move = 0; move < 5; move++) { + ro = i + row[move]; + co = j + col[move]; + if (ro >= 0 && ro <= 3 && co >= 0 && co <= 2 && + keypad[ro][co] != '*' && keypad[ro][co] != '#') { + nextNum = keypad[ro][co] - '0'; + count[num][k] += count[nextNum][k - 1]; } + } } + } } + } - // Get count of all possible numbers of length "n" starting - // with digit 0, 1, 2, ..., 9 - totalCount = 0; - for (i = 0; i <= 9; i++) - totalCount += count[i][n]; - return totalCount; + // Get count of all possible numbers of length "n" starting + // with digit 0, 1, 2, ..., 9 + totalCount = 0; + for (i = 0; i <= 9; i++) + totalCount += count[i][n]; + return totalCount; } // Driver program to test above function int main(int argc, char *argv[]) { - char keypad[4][3] = { - {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}, {'*', '0', '#'}}; - printf("Count for numbers of length %d: %dn", 1, getCount(keypad, 1)); - printf("Count for numbers of length %d: %dn", 2, getCount(keypad, 2)); - printf("Count for numbers of length %d: %dn", 3, getCount(keypad, 3)); - printf("Count for numbers of length %d: %dn", 4, getCount(keypad, 4)); - printf("Count for numbers of length %d: %dn", 5, getCount(keypad, 5)); + char keypad[4][3] = { + {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}, {'*', '0', '#'}}; + printf("Count for numbers of length %d: %dn", 1, getCount(keypad, 1)); + printf("Count for numbers of length %d: %dn", 2, getCount(keypad, 2)); + printf("Count for numbers of length %d: %dn", 3, getCount(keypad, 3)); + printf("Count for numbers of length %d: %dn", 4, getCount(keypad, 4)); + printf("Count for numbers of length %d: %dn", 5, getCount(keypad, 5)); - return 0; + return 0; } diff --git a/src/test-suite/PE-benchmarks/mobile-numeric-keypad-problem_space_optm.cpp b/src/test-suite/PE-benchmarks/mobile-numeric-keypad-problem_space_optm.cpp index de40d79f..af7ca724 100644 --- a/src/test-suite/PE-benchmarks/mobile-numeric-keypad-problem_space_optm.cpp +++ b/src/test-suite/PE-benchmarks/mobile-numeric-keypad-problem_space_optm.cpp @@ -5,73 +5,73 @@ // Return count of all possible numbers of length n // in a given numeric keyboard int getCount(char keypad[][3], int n) { - if (keypad == NULL || n <= 0) - return 0; - if (n == 1) - return 10; - - // odd[i], even[i] arrays represent count of numbers starting - // with digit i for any length j - int odd[10], even[10]; - int i = 0, j = 0, useOdd = 0, totalCount = 0; + if (keypad == NULL || n <= 0) + return 0; + if (n == 1) + return 10; - for (i = 0; i <= 9; i++) - odd[i] = 1; // for j = 1 + // odd[i], even[i] arrays represent count of numbers starting + // with digit i for any length j + int odd[10], even[10]; + int i = 0, j = 0, useOdd = 0, totalCount = 0; - for (j = 2; j <= n; j++) // Bottom Up calculation from j = 2 to n - { - useOdd = 1 - useOdd; + for (i = 0; i <= 9; i++) + odd[i] = 1; // for j = 1 - // Here we are explicitly writing lines for each number 0 - // to 9. But it can always be written as DFS on 4X3 grid - // using row, column array valid moves - if (useOdd == 1) { - even[0] = odd[0] + odd[8]; - even[1] = odd[1] + odd[2] + odd[4]; - even[2] = odd[2] + odd[1] + odd[3] + odd[5]; - even[3] = odd[3] + odd[2] + odd[6]; - even[4] = odd[4] + odd[1] + odd[5] + odd[7]; - even[5] = odd[5] + odd[2] + odd[4] + odd[8] + odd[6]; - even[6] = odd[6] + odd[3] + odd[5] + odd[9]; - even[7] = odd[7] + odd[4] + odd[8]; - even[8] = odd[8] + odd[0] + odd[5] + odd[7] + odd[9]; - even[9] = odd[9] + odd[6] + odd[8]; - } else { - odd[0] = even[0] + even[8]; - odd[1] = even[1] + even[2] + even[4]; - odd[2] = even[2] + even[1] + even[3] + even[5]; - odd[3] = even[3] + even[2] + even[6]; - odd[4] = even[4] + even[1] + even[5] + even[7]; - odd[5] = even[5] + even[2] + even[4] + even[8] + even[6]; - odd[6] = even[6] + even[3] + even[5] + even[9]; - odd[7] = even[7] + even[4] + even[8]; - odd[8] = even[8] + even[0] + even[5] + even[7] + even[9]; - odd[9] = even[9] + even[6] + even[8]; - } - } + for (j = 2; j <= n; j++) // Bottom Up calculation from j = 2 to n + { + useOdd = 1 - useOdd; - // Get count of all possible numbers of length "n" starting - // with digit 0, 1, 2, ..., 9 - totalCount = 0; + // Here we are explicitly writing lines for each number 0 + // to 9. But it can always be written as DFS on 4X3 grid + // using row, column array valid moves if (useOdd == 1) { - for (i = 0; i <= 9; i++) - totalCount += even[i]; + even[0] = odd[0] + odd[8]; + even[1] = odd[1] + odd[2] + odd[4]; + even[2] = odd[2] + odd[1] + odd[3] + odd[5]; + even[3] = odd[3] + odd[2] + odd[6]; + even[4] = odd[4] + odd[1] + odd[5] + odd[7]; + even[5] = odd[5] + odd[2] + odd[4] + odd[8] + odd[6]; + even[6] = odd[6] + odd[3] + odd[5] + odd[9]; + even[7] = odd[7] + odd[4] + odd[8]; + even[8] = odd[8] + odd[0] + odd[5] + odd[7] + odd[9]; + even[9] = odd[9] + odd[6] + odd[8]; } else { - for (i = 0; i <= 9; i++) - totalCount += odd[i]; + odd[0] = even[0] + even[8]; + odd[1] = even[1] + even[2] + even[4]; + odd[2] = even[2] + even[1] + even[3] + even[5]; + odd[3] = even[3] + even[2] + even[6]; + odd[4] = even[4] + even[1] + even[5] + even[7]; + odd[5] = even[5] + even[2] + even[4] + even[8] + even[6]; + odd[6] = even[6] + even[3] + even[5] + even[9]; + odd[7] = even[7] + even[4] + even[8]; + odd[8] = even[8] + even[0] + even[5] + even[7] + even[9]; + odd[9] = even[9] + even[6] + even[8]; } - return totalCount; + } + + // Get count of all possible numbers of length "n" starting + // with digit 0, 1, 2, ..., 9 + totalCount = 0; + if (useOdd == 1) { + for (i = 0; i <= 9; i++) + totalCount += even[i]; + } else { + for (i = 0; i <= 9; i++) + totalCount += odd[i]; + } + return totalCount; } // Driver program to test above function int main() { - char keypad[4][3] = { - {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}, {'*', '0', '#'}}; - printf("Count for numbers of length %d: %dn", 1, getCount(keypad, 1)); - printf("Count for numbers of length %d: %dn", 2, getCount(keypad, 2)); - printf("Count for numbers of length %d: %dn", 3, getCount(keypad, 3)); - printf("Count for numbers of length %d: %dn", 4, getCount(keypad, 4)); - printf("Count for numbers of length %d: %dn", 5, getCount(keypad, 5)); + char keypad[4][3] = { + {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}, {'*', '0', '#'}}; + printf("Count for numbers of length %d: %dn", 1, getCount(keypad, 1)); + printf("Count for numbers of length %d: %dn", 2, getCount(keypad, 2)); + printf("Count for numbers of length %d: %dn", 3, getCount(keypad, 3)); + printf("Count for numbers of length %d: %dn", 4, getCount(keypad, 4)); + printf("Count for numbers of length %d: %dn", 5, getCount(keypad, 5)); - return 0; + return 0; } diff --git a/src/test-suite/PE-benchmarks/n-queen-problem.cpp b/src/test-suite/PE-benchmarks/n-queen-problem.cpp index 1159e796..9e9bc818 100644 --- a/src/test-suite/PE-benchmarks/n-queen-problem.cpp +++ b/src/test-suite/PE-benchmarks/n-queen-problem.cpp @@ -17,51 +17,51 @@ used to check whether a queen can be placed in that int cl[30] = {0}; /* A utility function to print solution */ void printSolution(int board[N][N]) { - for (int i = 0; i < N; i++) { - for (int j = 0; j < N; j++) - printf(" %d ", board[i][j]); - printf("\n"); - } + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) + printf(" %d ", board[i][j]); + printf("\n"); + } } /* A recursive utility function to solve N Queen problem */ bool solveNQUtil(int board[N][N], int col) { - /* base case: If all queens are placed - then return true */ - if (col >= N) - return true; + /* base case: If all queens are placed + then return true */ + if (col >= N) + return true; - /* Consider this column and try placing - this queen in all rows one by one */ - for (int i = 0; i < N; i++) { - /* Check if the queen can be placed on - board[i][col] */ - /* A check if a queen can be placed on - board[row][col].We just need to check - ld[row-col+n-1] and rd[row+coln] where - ld and rd are for left and right - diagonal respectively*/ - if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1) && cl[i] != 1) { - /* Place this queen in board[i][col] */ - board[i][col] = 1; - ld[i - col + N - 1] = rd[i + col] = cl[i] = 1; + /* Consider this column and try placing + this queen in all rows one by one */ + for (int i = 0; i < N; i++) { + /* Check if the queen can be placed on + board[i][col] */ + /* A check if a queen can be placed on + board[row][col].We just need to check + ld[row-col+n-1] and rd[row+coln] where + ld and rd are for left and right + diagonal respectively*/ + if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1) && cl[i] != 1) { + /* Place this queen in board[i][col] */ + board[i][col] = 1; + ld[i - col + N - 1] = rd[i + col] = cl[i] = 1; - /* recur to place rest of the queens */ - if (solveNQUtil(board, col + 1)) - return true; + /* recur to place rest of the queens */ + if (solveNQUtil(board, col + 1)) + return true; - /* If placing queen in board[i][col] - doesn't lead to a solution, then - remove queen from board[i][col] */ - board[i][col] = 0; // BACKTRACK - ld[i - col + N - 1] = rd[i + col] = cl[i] = 0; - } + /* If placing queen in board[i][col] + doesn't lead to a solution, then + remove queen from board[i][col] */ + board[i][col] = 0; // BACKTRACK + ld[i - col + N - 1] = rd[i + col] = cl[i] = 0; } + } - /* If the queen cannot be placed in any row in - this colum col then return false */ - return false; + /* If the queen cannot be placed in any row in + this colum col then return false */ + return false; } /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to @@ -72,19 +72,19 @@ Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ bool solveNQ() { - int board[N][N] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; + int board[N][N] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; - if (solveNQUtil(board, 0) == false) { - printf("Solution does not exist"); - return false; - } + if (solveNQUtil(board, 0) == false) { + printf("Solution does not exist"); + return false; + } - printSolution(board); - return true; + printSolution(board); + return true; } // driver program to test above function int main() { - solveNQ(); - return 0; + solveNQ(); + return 0; } diff --git a/src/test-suite/PE-benchmarks/naive-algorithm.cpp b/src/test-suite/PE-benchmarks/naive-algorithm.cpp index 15dc6f9b..cfb05df2 100644 --- a/src/test-suite/PE-benchmarks/naive-algorithm.cpp +++ b/src/test-suite/PE-benchmarks/naive-algorithm.cpp @@ -4,29 +4,29 @@ using namespace std; void search(char *pat, char *txt) { - int M = strlen(pat); - int N = strlen(txt); + int M = strlen(pat); + int N = strlen(txt); - /* A loop to slide pat[] one by one */ - for (int i = 0; i <= N - M; i++) { - int j; + /* A loop to slide pat[] one by one */ + for (int i = 0; i <= N - M; i++) { + int j; - /* For current index i, check for pattern match */ - for (j = 0; j < M; j++) - if (txt[i + j] != pat[j]) - break; + /* For current index i, check for pattern match */ + for (j = 0; j < M; j++) + if (txt[i + j] != pat[j]) + break; - if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1] - cout << "Pattern found at index " << i << endl; - } + if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1] + cout << "Pattern found at index " << i << endl; + } } // Driver Code int main() { - char txt[] = "AABAACAADAABAAABAA"; - char pat[] = "AABA"; - search(pat, txt); - return 0; + char txt[] = "AABAACAADAABAAABAA"; + char pat[] = "AABA"; + search(pat, txt); + return 0; } // This code is contributed diff --git a/src/test-suite/PE-benchmarks/optimal-binary-search-tree.cpp b/src/test-suite/PE-benchmarks/optimal-binary-search-tree.cpp index 6a087390..d544f7c4 100644 --- a/src/test-suite/PE-benchmarks/optimal-binary-search-tree.cpp +++ b/src/test-suite/PE-benchmarks/optimal-binary-search-tree.cpp @@ -10,57 +10,57 @@ int sum(int freq[], int i, int j); /* A Dynamic Programming based function that calculates minimum cost of a Binary Search Tree. */ int optimalSearchTree(int keys[], int freq[], int n) { - /* Create an auxiliary 2D matrix to store results - of subproblems */ - int cost[n][n]; + /* Create an auxiliary 2D matrix to store results + of subproblems */ + int cost[n][n]; - /* cost[i][j] = Optimal cost of binary search tree - that can be formed from keys[i] to keys[j]. - cost[0][n-1] will store the resultant cost */ + /* cost[i][j] = Optimal cost of binary search tree + that can be formed from keys[i] to keys[j]. + cost[0][n-1] will store the resultant cost */ - // For a single key, cost is equal to frequency of the key - for (int i = 0; i < n; i++) - cost[i][i] = freq[i]; + // For a single key, cost is equal to frequency of the key + for (int i = 0; i < n; i++) + cost[i][i] = freq[i]; - // Now we need to consider chains of length 2, 3, ... . - // L is chain length. - for (int L = 2; L <= n; L++) { - // i is row number in cost[][] - for (int i = 0; i <= n - L + 1; i++) { - // Get column number j from row number i and - // chain length L - int j = i + L - 1; - cost[i][j] = INT_MAX; + // Now we need to consider chains of length 2, 3, ... . + // L is chain length. + for (int L = 2; L <= n; L++) { + // i is row number in cost[][] + for (int i = 0; i <= n - L + 1; i++) { + // Get column number j from row number i and + // chain length L + int j = i + L - 1; + cost[i][j] = INT_MAX; - // Try making all keys in interval keys[i..j] as root - for (int r = i; r <= j; r++) { - // c = cost when keys[r] becomes root of this subtree - int c = ((r > i) ? cost[i][r - 1] : 0) + - ((r < j) ? cost[r + 1][j] : 0) + sum(freq, i, j); - if (c < cost[i][j]) - cost[i][j] = c; - } - } + // Try making all keys in interval keys[i..j] as root + for (int r = i; r <= j; r++) { + // c = cost when keys[r] becomes root of this subtree + int c = ((r > i) ? cost[i][r - 1] : 0) + + ((r < j) ? cost[r + 1][j] : 0) + sum(freq, i, j); + if (c < cost[i][j]) + cost[i][j] = c; + } } - return cost[0][n - 1]; + } + return cost[0][n - 1]; } // A utility function to get sum of array elements // freq[i] to freq[j] int sum(int freq[], int i, int j) { - int s = 0; - for (int k = i; k <= j; k++) - s += freq[k]; - return s; + int s = 0; + for (int k = i; k <= j; k++) + s += freq[k]; + return s; } // Driver code int main() { - int keys[] = {10, 12, 20}; - int freq[] = {34, 8, 50}; - int n = sizeof(keys) / sizeof(keys[0]); - cout << "Cost of Optimal BST is " << optimalSearchTree(keys, freq, n); - return 0; + int keys[] = {10, 12, 20}; + int freq[] = {34, 8, 50}; + int n = sizeof(keys) / sizeof(keys[0]); + cout << "Cost of Optimal BST is " << optimalSearchTree(keys, freq, n); + return 0; } // This code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/optimized-naive-algorithm.cpp b/src/test-suite/PE-benchmarks/optimized-naive-algorithm.cpp index 0a1ac38b..c57d739d 100644 --- a/src/test-suite/PE-benchmarks/optimized-naive-algorithm.cpp +++ b/src/test-suite/PE-benchmarks/optimized-naive-algorithm.cpp @@ -8,35 +8,35 @@ using namespace std; algorithn that is optimized for the cases when all characters of pattern are different */ void search(string pat, string txt) { - int M = pat.size(); - int N = txt.size(); - int i = 0; + int M = pat.size(); + int N = txt.size(); + int i = 0; - while (i <= N - M) { - int j; + while (i <= N - M) { + int j; - /* For current index i, check for pattern match */ - for (j = 0; j < M; j++) - if (txt[i + j] != pat[j]) - break; + /* For current index i, check for pattern match */ + for (j = 0; j < M; j++) + if (txt[i + j] != pat[j]) + break; - if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1] - { - cout << "Pattern found at index " << i << endl; - i = i + M; - } else if (j == 0) - i = i + 1; - else - i = i + j; // slide the pattern by j - } + if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1] + { + cout << "Pattern found at index " << i << endl; + i = i + M; + } else if (j == 0) + i = i + 1; + else + i = i + j; // slide the pattern by j + } } /* Driver code*/ int main() { - string txt = "ABCEABCDABCEABCD"; - string pat = "ABCD"; - search(pat, txt); - return 0; + string txt = "ABCEABCDABCEABCD"; + string pat = "ABCD"; + search(pat, txt); + return 0; } // This code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/overlapping-subproblems-property.cpp b/src/test-suite/PE-benchmarks/overlapping-subproblems-property.cpp index 59be6806..890b616b 100644 --- a/src/test-suite/PE-benchmarks/overlapping-subproblems-property.cpp +++ b/src/test-suite/PE-benchmarks/overlapping-subproblems-property.cpp @@ -10,29 +10,29 @@ int lookup[MAX]; /* Function to initialize NIL values in lookup table */ void _initialize() { - int i; - for (i = 0; i < MAX; i++) - lookup[i] = NIL; + int i; + for (i = 0; i < MAX; i++) + lookup[i] = NIL; } /* function for nth Fibonacci number */ int fib(int n) { - if (lookup[n] == NIL) { - if (n <= 1) - lookup[n] = n; - else - lookup[n] = fib(n - 1) + fib(n - 2); - } + if (lookup[n] == NIL) { + if (n <= 1) + lookup[n] = n; + else + lookup[n] = fib(n - 1) + fib(n - 2); + } - return lookup[n]; + return lookup[n]; } // Driver code int main() { - int n = 40; - _initialize(); - cout << "Fibonacci number is " << fib(n); - return 0; + int n = 40; + _initialize(); + cout << "Fibonacci number is " << fib(n); + return 0; } // This is code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/palindrome-partitioning.cpp b/src/test-suite/PE-benchmarks/palindrome-partitioning.cpp index bb1ef11b..343e419f 100644 --- a/src/test-suite/PE-benchmarks/palindrome-partitioning.cpp +++ b/src/test-suite/PE-benchmarks/palindrome-partitioning.cpp @@ -9,60 +9,60 @@ int min(int a, int b) { return (a < b) ? a : b; } // Returns the minimum number of cuts needed to partition a string // such that every part is a palindrome int minPalPartion(char *str) { - // Get the length of the string - int n = strlen(str); + // Get the length of the string + int n = strlen(str); - /* Create two arrays to build the solution in bottom-up manner - C[i] = Minimum number of cuts needed for a palindrome partitioning - of substring str[0..i] - P[i][j] = true if substring str[i..j] is palindrome, else false - Note that C[i] is 0 if P[0][i] is true */ - int C[n]; - bool P[n][n]; + /* Create two arrays to build the solution in bottom-up manner + C[i] = Minimum number of cuts needed for a palindrome partitioning + of substring str[0..i] + P[i][j] = true if substring str[i..j] is palindrome, else false + Note that C[i] is 0 if P[0][i] is true */ + int C[n]; + bool P[n][n]; - int i, j, k, L; // different looping variables + int i, j, k, L; // different looping variables - // Every substring of length 1 is a palindrome - for (i = 0; i < n; i++) { - P[i][i] = true; - } + // Every substring of length 1 is a palindrome + for (i = 0; i < n; i++) { + P[i][i] = true; + } - /* L is substring length. Build the solution in bottom up manner by - considering all substrings of length starting from 2 to n. */ - for (L = 2; L <= n; L++) { - // For substring of length L, set different possible starting indexes - for (i = 0; i < n - L + 1; i++) { - j = i + L - 1; // Set ending index + /* L is substring length. Build the solution in bottom up manner by + considering all substrings of length starting from 2 to n. */ + for (L = 2; L <= n; L++) { + // For substring of length L, set different possible starting indexes + for (i = 0; i < n - L + 1; i++) { + j = i + L - 1; // Set ending index - // If L is 2, then we just need to compare two characters. Else - // need to check two corner characters and value of P[i+1][j-1] - if (L == 2) - P[i][j] = (str[i] == str[j]); - else - P[i][j] = (str[i] == str[j]) && P[i + 1][j - 1]; - } + // If L is 2, then we just need to compare two characters. Else + // need to check two corner characters and value of P[i+1][j-1] + if (L == 2) + P[i][j] = (str[i] == str[j]); + else + P[i][j] = (str[i] == str[j]) && P[i + 1][j - 1]; } + } - for (i = 0; i < n; i++) { - if (P[0][i] == true) - C[i] = 0; - else { - C[i] = INT_MAX; - for (j = 0; j < i; j++) { - if (P[j + 1][i] == true && 1 + C[j] < C[i]) - C[i] = 1 + C[j]; - } - } + for (i = 0; i < n; i++) { + if (P[0][i] == true) + C[i] = 0; + else { + C[i] = INT_MAX; + for (j = 0; j < i; j++) { + if (P[j + 1][i] == true && 1 + C[j] < C[i]) + C[i] = 1 + C[j]; + } } + } - // Return the min cut value for complete string. i.e., str[0..n-1] - return C[n - 1]; + // Return the min cut value for complete string. i.e., str[0..n-1] + return C[n - 1]; } // Driver program to test above function int main() { - char str[] = "ababbbabbababa"; - printf("Min cuts needed for Palindrome Partitioning is %d", - minPalPartion(str)); - return 0; + char str[] = "ababbbabbababa"; + printf("Min cuts needed for Palindrome Partitioning is %d", + minPalPartion(str)); + return 0; } diff --git a/src/test-suite/PE-benchmarks/partition-problem.cpp b/src/test-suite/PE-benchmarks/partition-problem.cpp index af190eed..85ea18d2 100644 --- a/src/test-suite/PE-benchmarks/partition-problem.cpp +++ b/src/test-suite/PE-benchmarks/partition-problem.cpp @@ -4,54 +4,54 @@ // Returns true if arr[] can be partitioned in two subsets of // equal sum, otherwise false bool findPartiion(int arr[], int n) { - int sum = 0; - int i, j; + int sum = 0; + int i, j; - // Caculcate sun of all elements - for (i = 0; i < n; i++) - sum += arr[i]; + // Caculcate sun of all elements + for (i = 0; i < n; i++) + sum += arr[i]; - if (sum % 2 != 0) - return false; + if (sum % 2 != 0) + return false; - bool part[sum / 2 + 1][n + 1]; + bool part[sum / 2 + 1][n + 1]; - // initialize top row as true - for (i = 0; i <= n; i++) - part[0][i] = true; + // initialize top row as true + for (i = 0; i <= n; i++) + part[0][i] = true; - // initialize leftmost column, except part[0][0], as 0 - for (i = 1; i <= sum / 2; i++) - part[i][0] = false; + // initialize leftmost column, except part[0][0], as 0 + for (i = 1; i <= sum / 2; i++) + part[i][0] = false; - // Fill the partition table in botton up manner - for (i = 1; i <= sum / 2; i++) { - for (j = 1; j <= n; j++) { - part[i][j] = part[i][j - 1]; - if (i >= arr[j - 1]) - part[i][j] = part[i][j] || part[i - arr[j - 1]][j - 1]; - } + // Fill the partition table in botton up manner + for (i = 1; i <= sum / 2; i++) { + for (j = 1; j <= n; j++) { + part[i][j] = part[i][j - 1]; + if (i >= arr[j - 1]) + part[i][j] = part[i][j] || part[i - arr[j - 1]][j - 1]; } + } - /* // uncomment this part to print table - for (i = 0; i <= sum/2; i++) - { - for (j = 0; j <= n; j++) - printf ("%4d", part[i][j]); - printf("\n"); - } */ + /* // uncomment this part to print table + for (i = 0; i <= sum/2; i++) + { + for (j = 0; j <= n; j++) + printf ("%4d", part[i][j]); + printf("\n"); + } */ - return part[sum / 2][n]; + return part[sum / 2][n]; } // Driver program to test above funtion int main() { - int arr[] = {3, 1, 1, 2, 2, 1}; - int n = sizeof(arr) / sizeof(arr[0]); - if (findPartiion(arr, n) == true) - printf("Can be divided into two subsets of equal sum"); - else - printf("Can not be divided into two subsets of equal sum"); - getchar(); - return 0; + int arr[] = {3, 1, 1, 2, 2, 1}; + int n = sizeof(arr) / sizeof(arr[0]); + if (findPartiion(arr, n) == true) + printf("Can be divided into two subsets of equal sum"); + else + printf("Can not be divided into two subsets of equal sum"); + getchar(); + return 0; } diff --git a/src/test-suite/PE-benchmarks/permutations-of-a-given-string.cpp b/src/test-suite/PE-benchmarks/permutations-of-a-given-string.cpp index 36ff42b1..4ec838f2 100644 --- a/src/test-suite/PE-benchmarks/permutations-of-a-given-string.cpp +++ b/src/test-suite/PE-benchmarks/permutations-of-a-given-string.cpp @@ -9,31 +9,31 @@ using namespace std; // 2. Starting index of the string // 3. Ending index of the string. void permute(string a, int l, int r) { - // Base case - if (l == r) - cout << a << endl; - else { - // Permutations made - for (int i = l; i <= r; i++) { + // Base case + if (l == r) + cout << a << endl; + else { + // Permutations made + for (int i = l; i <= r; i++) { - // Swapping done - swap(a[l], a[i]); + // Swapping done + swap(a[l], a[i]); - // Recursion called - permute(a, l + 1, r); + // Recursion called + permute(a, l + 1, r); - // backtrack - swap(a[l], a[i]); - } + // backtrack + swap(a[l], a[i]); } + } } // Driver Code int main() { - string str = "ABC"; - int n = str.size(); - permute(str, 0, n - 1); - return 0; + string str = "ABC"; + int n = str.size(); + permute(str, 0, n - 1); + return 0; } // This is code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/program-for-nth-fibonacci-number.cpp b/src/test-suite/PE-benchmarks/program-for-nth-fibonacci-number.cpp index 5522780d..f6b219cb 100644 --- a/src/test-suite/PE-benchmarks/program-for-nth-fibonacci-number.cpp +++ b/src/test-suite/PE-benchmarks/program-for-nth-fibonacci-number.cpp @@ -1,20 +1,20 @@ // Fibonacci Series using Space Optimized Method #include int fib(int n) { - int a = 0, b = 1, c, i; - if (n == 0) - return a; - for (i = 2; i <= n; i++) { - c = a + b; - a = b; - b = c; - } - return b; + int a = 0, b = 1, c, i; + if (n == 0) + return a; + for (i = 2; i <= n; i++) { + c = a + b; + a = b; + b = c; + } + return b; } int main() { - int n = 9; - printf("%d", fib(n)); - getchar(); - return 0; + int n = 9; + printf("%d", fib(n)); + getchar(); + return 0; } diff --git a/src/test-suite/PE-benchmarks/program-wish-womens-day.cpp b/src/test-suite/PE-benchmarks/program-wish-womens-day.cpp index 6b7247fa..df15f9f7 100644 --- a/src/test-suite/PE-benchmarks/program-wish-womens-day.cpp +++ b/src/test-suite/PE-benchmarks/program-wish-womens-day.cpp @@ -3,60 +3,60 @@ #include using namespace std; int main() { - // Initializing size of - // design - int n = 5; - - // Loop to print Circle - // (Upper part of design) - // Outer loop to - // control height of - // design - for (int i = 0; i <= 2 * n; i++) { - // Inner loop to control - // width - for (int j = 0; j <= 2 * n; j++) { - - // computing distance of - // each point from center - float center_dist = sqrt((i - n) * (i - n) + (j - n) * (j - n)); - - if (center_dist > n - 0.5 && center_dist < n + 0.5) - cout << "$"; - else - cout << " "; - } - - // Printing HappY Women's DaY - if (i == n) - cout << " " - << "HappY Women's DaY"; - cout << endl; + // Initializing size of + // design + int n = 5; + + // Loop to print Circle + // (Upper part of design) + // Outer loop to + // control height of + // design + for (int i = 0; i <= 2 * n; i++) { + // Inner loop to control + // width + for (int j = 0; j <= 2 * n; j++) { + + // computing distance of + // each point from center + float center_dist = sqrt((i - n) * (i - n) + (j - n) * (j - n)); + + if (center_dist > n - 0.5 && center_dist < n + 0.5) + cout << "$"; + else + cout << " "; } - // Loop to print lower part - // Outer loop to control - // height - for (int i = 0; i <= n; i++) { - - // Positioning pattern - // Loop for Printing - // horizontal line - if (i == (n / 2) + 1) { - for (int j = 0; j <= 2 * n; j++) - if (j >= (n - n / 2) && j <= (n + n / 2)) - cout << "$"; - else - cout << " "; - } else { - - for (int j = 0; j <= 2 * n; j++) { - if (j == n) - cout << "$"; - else - cout << " "; - } - } - cout << endl; + // Printing HappY Women's DaY + if (i == n) + cout << " " + << "HappY Women's DaY"; + cout << endl; + } + + // Loop to print lower part + // Outer loop to control + // height + for (int i = 0; i <= n; i++) { + + // Positioning pattern + // Loop for Printing + // horizontal line + if (i == (n / 2) + 1) { + for (int j = 0; j <= 2 * n; j++) + if (j >= (n - n / 2) && j <= (n + n / 2)) + cout << "$"; + else + cout << " "; + } else { + + for (int j = 0; j <= 2 * n; j++) { + if (j == n) + cout << "$"; + else + cout << " "; + } } + cout << endl; + } } diff --git a/src/test-suite/PE-benchmarks/quicksort-for-linked-list.cpp b/src/test-suite/PE-benchmarks/quicksort-for-linked-list.cpp index 68d75472..8f26b784 100644 --- a/src/test-suite/PE-benchmarks/quicksort-for-linked-list.cpp +++ b/src/test-suite/PE-benchmarks/quicksort-for-linked-list.cpp @@ -4,25 +4,25 @@ using namespace std; /* a node of the doubly linked list */ class Node { - public: - int data; - Node *next; - Node *prev; +public: + int data; + Node *next; + Node *prev; }; /* A utility function to swap two elements */ void swap(int *a, int *b) { - int t = *a; - *a = *b; - *b = t; + int t = *a; + *a = *b; + *b = t; } // A utility function to find // last node of linked list Node *lastNode(Node *root) { - while (root && root->next) - root = root->next; - return root; + while (root && root->next) + root = root->next; + return root; } /* Considers last element as pivot, @@ -32,94 +32,94 @@ and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ Node *partition(Node *l, Node *h) { - // set pivot as h element - int x = h->data; + // set pivot as h element + int x = h->data; - // similar to i = l-1 for array implementation - Node *i = l->prev; + // similar to i = l-1 for array implementation + Node *i = l->prev; - // Similar to "for (int j = l; j <= h- 1; j++)" - for (Node *j = l; j != h; j = j->next) { - if (j->data <= x) { - // Similar to i++ for array - i = (i == NULL) ? l : i->next; + // Similar to "for (int j = l; j <= h- 1; j++)" + for (Node *j = l; j != h; j = j->next) { + if (j->data <= x) { + // Similar to i++ for array + i = (i == NULL) ? l : i->next; - swap(&(i->data), &(j->data)); - } + swap(&(i->data), &(j->data)); } - i = (i == NULL) ? l : i->next; // Similar to i++ - swap(&(i->data), &(h->data)); - return i; + } + i = (i == NULL) ? l : i->next; // Similar to i++ + swap(&(i->data), &(h->data)); + return i; } /* A recursive implementation of quicksort for linked list */ void _quickSort(Node *l, Node *h) { - if (h != NULL && l != h && l != h->next) { - Node *p = partition(l, h); - _quickSort(l, p->prev); - _quickSort(p->next, h); - } + if (h != NULL && l != h && l != h->next) { + Node *p = partition(l, h); + _quickSort(l, p->prev); + _quickSort(p->next, h); + } } // The main function to sort a linked list. // It mainly calls _quickSort() void quickSort(Node *head) { - // Find last node - Node *h = lastNode(head); + // Find last node + Node *h = lastNode(head); - // Call the recursive QuickSort - _quickSort(head, h); + // Call the recursive QuickSort + _quickSort(head, h); } // A utility function to print contents of arr void printList(Node *head) { - while (head) { - cout << head->data << " "; - head = head->next; - } - cout << endl; + while (head) { + cout << head->data << " "; + head = head->next; + } + cout << endl; } /* Function to insert a node at the beginging of the Doubly Linked List */ void push(Node **head_ref, int new_data) { - Node *new_node = new Node; /* allocate node */ - new_node->data = new_data; + Node *new_node = new Node; /* allocate node */ + new_node->data = new_data; - /* since we are adding at the - beginning, prev is always NULL */ - new_node->prev = NULL; + /* since we are adding at the + beginning, prev is always NULL */ + new_node->prev = NULL; - /* link the old list off the new node */ - new_node->next = (*head_ref); + /* link the old list off the new node */ + new_node->next = (*head_ref); - /* change prev of head node to new node */ - if ((*head_ref) != NULL) - (*head_ref)->prev = new_node; + /* change prev of head node to new node */ + if ((*head_ref) != NULL) + (*head_ref)->prev = new_node; - /* move the head to point to the new node */ - (*head_ref) = new_node; + /* move the head to point to the new node */ + (*head_ref) = new_node; } /* Driver code */ int main() { - Node *a = NULL; - push(&a, 5); - push(&a, 20); - push(&a, 4); - push(&a, 3); - push(&a, 30); + Node *a = NULL; + push(&a, 5); + push(&a, 20); + push(&a, 4); + push(&a, 3); + push(&a, 30); - cout << "Linked List before sorting \n"; - printList(a); + cout << "Linked List before sorting \n"; + printList(a); - quickSort(a); + quickSort(a); - cout << "Linked List after sorting \n"; - printList(a); + cout << "Linked List after sorting \n"; + printList(a); - return 0; + return 0; } // This code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/quicksort-on-singly-linked-list.cpp b/src/test-suite/PE-benchmarks/quicksort-on-singly-linked-list.cpp index 7edb6f2e..d1797131 100644 --- a/src/test-suite/PE-benchmarks/quicksort-on-singly-linked-list.cpp +++ b/src/test-suite/PE-benchmarks/quicksort-on-singly-linked-list.cpp @@ -5,141 +5,141 @@ using namespace std; /* a node of the singly linked list */ struct Node { - int data; - struct Node *next; + int data; + struct Node *next; }; /* A utility function to insert a node at the beginning of linked list */ void push(struct Node **head_ref, int new_data) { - /* allocate node */ - struct Node *new_node = new Node; + /* allocate node */ + struct Node *new_node = new Node; - /* put in the data */ - new_node->data = new_data; + /* put in the data */ + new_node->data = new_data; - /* link the old list off the new node */ - new_node->next = (*head_ref); + /* link the old list off the new node */ + new_node->next = (*head_ref); - /* move the head to point to the new node */ - (*head_ref) = new_node; + /* move the head to point to the new node */ + (*head_ref) = new_node; } /* A utility function to print linked list */ void printList(struct Node *node) { - while (node != NULL) { - printf("%d ", node->data); - node = node->next; - } - printf("\n"); + while (node != NULL) { + printf("%d ", node->data); + node = node->next; + } + printf("\n"); } // Returns the last node of the list struct Node *getTail(struct Node *cur) { - while (cur != NULL && cur->next != NULL) - cur = cur->next; - return cur; + while (cur != NULL && cur->next != NULL) + cur = cur->next; + return cur; } // Partitions the list taking the last element as the pivot struct Node *partition(struct Node *head, struct Node *end, struct Node **newHead, struct Node **newEnd) { - struct Node *pivot = end; - struct Node *prev = NULL, *cur = head, *tail = pivot; - - // During partition, both the head and end of the list might change - // which is updated in the newHead and newEnd variables - while (cur != pivot) { - if (cur->data < pivot->data) { - // First node that has a value less than the pivot - becomes - // the new head - if ((*newHead) == NULL) - (*newHead) = cur; - - prev = cur; - cur = cur->next; - } else // If cur node is greater than pivot - { - // Move cur node to next of tail, and change tail - if (prev) - prev->next = cur->next; - struct Node *tmp = cur->next; - cur->next = NULL; - tail->next = cur; - tail = cur; - cur = tmp; - } + struct Node *pivot = end; + struct Node *prev = NULL, *cur = head, *tail = pivot; + + // During partition, both the head and end of the list might change + // which is updated in the newHead and newEnd variables + while (cur != pivot) { + if (cur->data < pivot->data) { + // First node that has a value less than the pivot - becomes + // the new head + if ((*newHead) == NULL) + (*newHead) = cur; + + prev = cur; + cur = cur->next; + } else // If cur node is greater than pivot + { + // Move cur node to next of tail, and change tail + if (prev) + prev->next = cur->next; + struct Node *tmp = cur->next; + cur->next = NULL; + tail->next = cur; + tail = cur; + cur = tmp; } + } - // If the pivot data is the smallest element in the current list, - // pivot becomes the head - if ((*newHead) == NULL) - (*newHead) = pivot; + // If the pivot data is the smallest element in the current list, + // pivot becomes the head + if ((*newHead) == NULL) + (*newHead) = pivot; - // Update newEnd to the current last node - (*newEnd) = tail; + // Update newEnd to the current last node + (*newEnd) = tail; - // Return the pivot node - return pivot; + // Return the pivot node + return pivot; } // here the sorting happens exclusive of the end node struct Node *quickSortRecur(struct Node *head, struct Node *end) { - // base condition - if (!head || head == end) - return head; - - Node *newHead = NULL, *newEnd = NULL; - - // Partition the list, newHead and newEnd will be updated - // by the partition function - struct Node *pivot = partition(head, end, &newHead, &newEnd); - - // If pivot is the smallest element - no need to recur for - // the left part. - if (newHead != pivot) { - // Set the node before the pivot node as NULL - struct Node *tmp = newHead; - while (tmp->next != pivot) - tmp = tmp->next; - tmp->next = NULL; - - // Recur for the list before pivot - newHead = quickSortRecur(newHead, tmp); - - // Change next of last node of the left half to pivot - tmp = getTail(newHead); - tmp->next = pivot; - } + // base condition + if (!head || head == end) + return head; + + Node *newHead = NULL, *newEnd = NULL; + + // Partition the list, newHead and newEnd will be updated + // by the partition function + struct Node *pivot = partition(head, end, &newHead, &newEnd); + + // If pivot is the smallest element - no need to recur for + // the left part. + if (newHead != pivot) { + // Set the node before the pivot node as NULL + struct Node *tmp = newHead; + while (tmp->next != pivot) + tmp = tmp->next; + tmp->next = NULL; + + // Recur for the list before pivot + newHead = quickSortRecur(newHead, tmp); + + // Change next of last node of the left half to pivot + tmp = getTail(newHead); + tmp->next = pivot; + } - // Recur for the list after the pivot element - pivot->next = quickSortRecur(pivot->next, newEnd); + // Recur for the list after the pivot element + pivot->next = quickSortRecur(pivot->next, newEnd); - return newHead; + return newHead; } // The main function for quick sort. This is a wrapper over recursive // function quickSortRecur() void quickSort(struct Node **headRef) { - (*headRef) = quickSortRecur(*headRef, getTail(*headRef)); - return; + (*headRef) = quickSortRecur(*headRef, getTail(*headRef)); + return; } // Driver program to test above functions int main() { - struct Node *a = NULL; - push(&a, 5); - push(&a, 20); - push(&a, 4); - push(&a, 3); - push(&a, 30); + struct Node *a = NULL; + push(&a, 5); + push(&a, 20); + push(&a, 4); + push(&a, 3); + push(&a, 30); - cout << "Linked List before sorting \n"; - printList(a); + cout << "Linked List before sorting \n"; + printList(a); - quickSort(&a); + quickSort(&a); - cout << "Linked List after sorting \n"; - printList(a); + cout << "Linked List after sorting \n"; + printList(a); - return 0; + return 0; } diff --git a/src/test-suite/PE-benchmarks/rabin-karp-algorithm.cpp b/src/test-suite/PE-benchmarks/rabin-karp-algorithm.cpp index bf616b5e..6ba52102 100644 --- a/src/test-suite/PE-benchmarks/rabin-karp-algorithm.cpp +++ b/src/test-suite/PE-benchmarks/rabin-karp-algorithm.cpp @@ -11,62 +11,62 @@ using namespace std; q -> A prime number */ void search(char pat[], char txt[], int q) { - int M = strlen(pat); - int N = strlen(txt); - int i, j; - int p = 0; // hash value for pattern - int t = 0; // hash value for txt - int h = 1; + int M = strlen(pat); + int N = strlen(txt); + int i, j; + int p = 0; // hash value for pattern + int t = 0; // hash value for txt + int h = 1; - // The value of h would be "pow(d, M-1)%q" - for (i = 0; i < M - 1; i++) - h = (h * d) % q; + // The value of h would be "pow(d, M-1)%q" + for (i = 0; i < M - 1; i++) + h = (h * d) % q; - // Calculate the hash value of pattern and first - // window of text - for (i = 0; i < M; i++) { - p = (d * p + pat[i]) % q; - t = (d * t + txt[i]) % q; - } + // Calculate the hash value of pattern and first + // window of text + for (i = 0; i < M; i++) { + p = (d * p + pat[i]) % q; + t = (d * t + txt[i]) % q; + } - // Slide the pattern over text one by one - for (i = 0; i <= N - M; i++) { + // Slide the pattern over text one by one + for (i = 0; i <= N - M; i++) { - // Check the hash values of current window of text - // and pattern. If the hash values match then only - // check for characters on by one - if (p == t) { - /* Check for characters one by one */ - for (j = 0; j < M; j++) { - if (txt[i + j] != pat[j]) - break; - } + // Check the hash values of current window of text + // and pattern. If the hash values match then only + // check for characters on by one + if (p == t) { + /* Check for characters one by one */ + for (j = 0; j < M; j++) { + if (txt[i + j] != pat[j]) + break; + } - // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] - if (j == M) - cout << "Pattern found at index " << i << endl; - } + // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] + if (j == M) + cout << "Pattern found at index " << i << endl; + } - // Calculate hash value for next window of text: Remove - // leading digit, add trailing digit - if (i < N - M) { - t = (d * (t - txt[i] * h) + txt[i + M]) % q; + // Calculate hash value for next window of text: Remove + // leading digit, add trailing digit + if (i < N - M) { + t = (d * (t - txt[i] * h) + txt[i + M]) % q; - // We might get negative value of t, converting it - // to positive - if (t < 0) - t = (t + q); - } + // We might get negative value of t, converting it + // to positive + if (t < 0) + t = (t + q); } + } } /* Driver code */ int main() { - char txt[] = "GEEKS FOR GEEKS"; - char pat[] = "GEEK"; - int q = 101; // A prime number - search(pat, txt, q); - return 0; + char txt[] = "GEEKS FOR GEEKS"; + char pat[] = "GEEK"; + int q = 101; // A prime number + search(pat, txt, q); + return 0; } // This is code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/rat-in-a-maze.cpp b/src/test-suite/PE-benchmarks/rat-in-a-maze.cpp index 5e87dce6..76d8e197 100644 --- a/src/test-suite/PE-benchmarks/rat-in-a-maze.cpp +++ b/src/test-suite/PE-benchmarks/rat-in-a-maze.cpp @@ -9,20 +9,20 @@ bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]); /* A utility function to print solution matrix sol[N][N] */ void printSolution(int sol[N][N]) { - for (int i = 0; i < N; i++) { - for (int j = 0; j < N; j++) - printf(" %d ", sol[i][j]); - printf("\n"); - } + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) + printf(" %d ", sol[i][j]); + printf("\n"); + } } /* A utility function to check if x, y is valid index for N*N maze */ bool isSafe(int maze[N][N], int x, int y) { - // if (x, y outside maze) return false - if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) - return true; + // if (x, y outside maze) return false + if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) + return true; - return false; + return false; } /* This function solves the Maze problem using Backtracking. It mainly @@ -31,52 +31,52 @@ path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ bool solveMaze(int maze[N][N]) { - int sol[N][N] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; + int sol[N][N] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; - if (solveMazeUtil(maze, 0, 0, sol) == false) { - printf("Solution doesn't exist"); - return false; - } + if (solveMazeUtil(maze, 0, 0, sol) == false) { + printf("Solution doesn't exist"); + return false; + } - printSolution(sol); - return true; + printSolution(sol); + return true; } /* A recursive utility function to solve Maze problem */ bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]) { - // if (x, y is goal) return true - if (x == N - 1 && y == N - 1) { - sol[x][y] = 1; - return true; - } - - // Check if maze[x][y] is valid - if (isSafe(maze, x, y) == true) { - // mark x, y as part of solution path - sol[x][y] = 1; - - /* Move forward in x direction */ - if (solveMazeUtil(maze, x + 1, y, sol) == true) - return true; - - /* If moving in x direction doesn't give solution then - Move down in y direction */ - if (solveMazeUtil(maze, x, y + 1, sol) == true) - return true; - - /* If none of the above movements work then BACKTRACK: - unmark x, y as part of solution path */ - sol[x][y] = 0; - return false; - } + // if (x, y is goal) return true + if (x == N - 1 && y == N - 1) { + sol[x][y] = 1; + return true; + } + // Check if maze[x][y] is valid + if (isSafe(maze, x, y) == true) { + // mark x, y as part of solution path + sol[x][y] = 1; + + /* Move forward in x direction */ + if (solveMazeUtil(maze, x + 1, y, sol) == true) + return true; + + /* If moving in x direction doesn't give solution then + Move down in y direction */ + if (solveMazeUtil(maze, x, y + 1, sol) == true) + return true; + + /* If none of the above movements work then BACKTRACK: + unmark x, y as part of solution path */ + sol[x][y] = 0; return false; + } + + return false; } // driver program to test above function int main() { - int maze[N][N] = {{1, 0, 0, 0}, {1, 1, 0, 1}, {0, 1, 0, 0}, {1, 1, 1, 1}}; + int maze[N][N] = {{1, 0, 0, 0}, {1, 1, 0, 1}, {0, 1, 0, 0}, {1, 1, 1, 1}}; - solveMaze(maze); - return 0; + solveMaze(maze); + return 0; } diff --git a/src/test-suite/PE-benchmarks/reservoir-sampling.cpp b/src/test-suite/PE-benchmarks/reservoir-sampling.cpp index d2e6dedc..d575e834 100644 --- a/src/test-suite/PE-benchmarks/reservoir-sampling.cpp +++ b/src/test-suite/PE-benchmarks/reservoir-sampling.cpp @@ -6,49 +6,49 @@ using namespace std; // A utility function to print an array void printArray(int stream[], int n) { - for (int i = 0; i < n; i++) - cout << stream[i] << " "; - cout << endl; + for (int i = 0; i < n; i++) + cout << stream[i] << " "; + cout << endl; } // A function to randomly select // k items from stream[0..n-1]. void selectKItems(int stream[], int n, int k) { - int i; // index for elements in stream[] - - // reservoir[] is the output array. Initialize - // it with first k elements from stream[] - int reservoir[k]; - for (i = 0; i < k; i++) - reservoir[i] = stream[i]; - - // Use a different seed value so that we don't get - // same result each time we run this program - srand(time(NULL)); - - // Iterate from the (k+1)th element to nth element - for (; i < n; i++) { - // Pick a random index from 0 to i. - int j = rand() % (i + 1); - - // If the randomly picked index is smaller than k, - // then replace the element present at the index - // with new element from stream - if (j < k) - reservoir[j] = stream[i]; - } - - cout << "Following are k randomly selected items \n"; - printArray(reservoir, k); + int i; // index for elements in stream[] + + // reservoir[] is the output array. Initialize + // it with first k elements from stream[] + int reservoir[k]; + for (i = 0; i < k; i++) + reservoir[i] = stream[i]; + + // Use a different seed value so that we don't get + // same result each time we run this program + srand(time(NULL)); + + // Iterate from the (k+1)th element to nth element + for (; i < n; i++) { + // Pick a random index from 0 to i. + int j = rand() % (i + 1); + + // If the randomly picked index is smaller than k, + // then replace the element present at the index + // with new element from stream + if (j < k) + reservoir[j] = stream[i]; + } + + cout << "Following are k randomly selected items \n"; + printArray(reservoir, k); } // Driver Code int main() { - int stream[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; - int n = sizeof(stream) / sizeof(stream[0]); - int k = 5; - selectKItems(stream, n, k); - return 0; + int stream[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; + int n = sizeof(stream) / sizeof(stream[0]); + int k = 5; + selectKItems(stream, n, k); + return 0; } // This is code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/rotate-bits-of-an-integer.cpp b/src/test-suite/PE-benchmarks/rotate-bits-of-an-integer.cpp index 39023cbb..e3a4182f 100644 --- a/src/test-suite/PE-benchmarks/rotate-bits-of-an-integer.cpp +++ b/src/test-suite/PE-benchmarks/rotate-bits-of-an-integer.cpp @@ -6,37 +6,37 @@ using namespace std; #define INT_BITS 32 class gfg { - /*Function to left rotate n by d bits*/ - public: - int leftRotate(int n, unsigned int d) { + /*Function to left rotate n by d bits*/ +public: + int leftRotate(int n, unsigned int d) { - /* In n<>(INT_BITS - d) */ - return (n << d) | (n >> (INT_BITS - d)); - } + /* In n<>(INT_BITS - d) */ + return (n << d) | (n >> (INT_BITS - d)); + } - /*Function to right rotate n by d bits*/ - int rightRotate(int n, unsigned int d) { - /* In n>>d, first d bits are 0. - To put last 3 bits of at - first, do bitwise or of n>>d - with n <<(INT_BITS - d) */ - return (n >> d) | (n << (INT_BITS - d)); - } + /*Function to right rotate n by d bits*/ + int rightRotate(int n, unsigned int d) { + /* In n>>d, first d bits are 0. + To put last 3 bits of at + first, do bitwise or of n>>d + with n <<(INT_BITS - d) */ + return (n >> d) | (n << (INT_BITS - d)); + } }; /* Driver code*/ int main() { - gfg g; - int n = 16; - int d = 2; - cout << "Left Rotation of " << n << " by " << d << " is "; - cout << g.leftRotate(n, d); - cout << "\nRight Rotation of " << n << " by " << d << " is "; - cout << g.rightRotate(n, d); - getchar(); + gfg g; + int n = 16; + int d = 2; + cout << "Left Rotation of " << n << " by " << d << " is "; + cout << g.leftRotate(n, d); + cout << "\nRight Rotation of " << n << " by " << d << " is "; + cout << g.rightRotate(n, d); + getchar(); } // This code is contributed by SoM15242 diff --git a/src/test-suite/PE-benchmarks/shortest-common-supersequence.cpp b/src/test-suite/PE-benchmarks/shortest-common-supersequence.cpp index 038a7161..2864a650 100644 --- a/src/test-suite/PE-benchmarks/shortest-common-supersequence.cpp +++ b/src/test-suite/PE-benchmarks/shortest-common-supersequence.cpp @@ -6,31 +6,31 @@ using namespace std; // Returns length of the shortest // supersequence of X and Y int superSeq(char *X, char *Y, int m, int n) { - int dp[m + 1][n + 1]; + int dp[m + 1][n + 1]; - // Fill table in bottom up manner - for (int i = 0; i <= m; i++) { - for (int j = 0; j <= n; j++) { - // Below steps follow above recurrence - if (!i) - dp[i][j] = j; - else if (!j) - dp[i][j] = i; - else if (X[i - 1] == Y[j - 1]) - dp[i][j] = 1 + dp[i - 1][j - 1]; - else - dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]); - } + // Fill table in bottom up manner + for (int i = 0; i <= m; i++) { + for (int j = 0; j <= n; j++) { + // Below steps follow above recurrence + if (!i) + dp[i][j] = j; + else if (!j) + dp[i][j] = i; + else if (X[i - 1] == Y[j - 1]) + dp[i][j] = 1 + dp[i - 1][j - 1]; + else + dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]); } + } - return dp[m][n]; + return dp[m][n]; } // Driver Code int main() { - char X[] = "AGGTAB"; - char Y[] = "GXTXAYB"; - cout << "Length of the shortest supersequence is " - << superSeq(X, Y, strlen(X), strlen(Y)); - return 0; + char X[] = "AGGTAB"; + char Y[] = "GXTXAYB"; + cout << "Length of the shortest supersequence is " + << superSeq(X, Y, strlen(X), strlen(Y)); + return 0; } diff --git a/src/test-suite/PE-benchmarks/sieve-of-eratosthenes.cpp b/src/test-suite/PE-benchmarks/sieve-of-eratosthenes.cpp index d478521f..8f0a2c00 100644 --- a/src/test-suite/PE-benchmarks/sieve-of-eratosthenes.cpp +++ b/src/test-suite/PE-benchmarks/sieve-of-eratosthenes.cpp @@ -4,35 +4,35 @@ using namespace std; void SieveOfEratosthenes(int n) { - // Create a boolean array "prime[0..n]" and initialize - // all entries it as true. A value in prime[i] will - // finally be false if i is Not a prime, else true. - bool prime[n + 1]; - memset(prime, true, sizeof(prime)); + // Create a boolean array "prime[0..n]" and initialize + // all entries it as true. A value in prime[i] will + // finally be false if i is Not a prime, else true. + bool prime[n + 1]; + memset(prime, true, sizeof(prime)); - for (int p = 2; p * p <= n; p++) { - // If prime[p] is not changed, then it is a prime - if (prime[p] == true) { - // Update all multiples of p greater than or - // equal to the square of it - // numbers which are multiple of p and are - // less than p^2 are already been marked. - for (int i = p * p; i <= n; i += p) - prime[i] = false; - } + for (int p = 2; p * p <= n; p++) { + // If prime[p] is not changed, then it is a prime + if (prime[p] == true) { + // Update all multiples of p greater than or + // equal to the square of it + // numbers which are multiple of p and are + // less than p^2 are already been marked. + for (int i = p * p; i <= n; i += p) + prime[i] = false; } + } - // Print all prime numbers - for (int p = 2; p <= n; p++) - if (prime[p]) - cout << p << " "; + // Print all prime numbers + for (int p = 2; p <= n; p++) + if (prime[p]) + cout << p << " "; } // Driver Program to test above function int main() { - int n = 30; - cout << "Following are the prime numbers smaller " - << " than or equal to " << n << endl; - SieveOfEratosthenes(n); - return 0; + int n = 30; + cout << "Following are the prime numbers smaller " + << " than or equal to " << n << endl; + SieveOfEratosthenes(n); + return 0; } diff --git a/src/test-suite/PE-benchmarks/snake-ladder.cpp b/src/test-suite/PE-benchmarks/snake-ladder.cpp index d90aa38c..98b8ef79 100644 --- a/src/test-suite/PE-benchmarks/snake-ladder.cpp +++ b/src/test-suite/PE-benchmarks/snake-ladder.cpp @@ -7,8 +7,8 @@ using namespace std; // An entry in queue used in BFS struct queueEntry { - int v; // Vertex number - int dist; // Distance of this vertex from source + int v; // Vertex number + int dist; // Distance of this vertex from source }; // This function returns minimum number of dice throws required to @@ -18,81 +18,81 @@ struct queueEntry { // Otherwise move[i] contains cell to which snake or ladder at i // takes to. int getMinDiceThrows(int move[], int N) { - // The graph has N vertices. Mark all the vertices as - // not visited - bool *visited = new bool[N]; - for (int i = 0; i < N; i++) - visited[i] = false; + // The graph has N vertices. Mark all the vertices as + // not visited + bool *visited = new bool[N]; + for (int i = 0; i < N; i++) + visited[i] = false; - // Create a queue for BFS - queue q; + // Create a queue for BFS + queue q; - // Mark the node 0 as visited and enqueue it. - visited[0] = true; - queueEntry s = {0, 0}; // distance of 0't vertex is also 0 - q.push(s); // Enqueue 0'th vertex + // Mark the node 0 as visited and enqueue it. + visited[0] = true; + queueEntry s = {0, 0}; // distance of 0't vertex is also 0 + q.push(s); // Enqueue 0'th vertex - // Do a BFS starting from vertex at index 0 - queueEntry qe; // A queue entry (qe) - while (!q.empty()) { - qe = q.front(); - int v = qe.v; // vertex no. of queue entry + // Do a BFS starting from vertex at index 0 + queueEntry qe; // A queue entry (qe) + while (!q.empty()) { + qe = q.front(); + int v = qe.v; // vertex no. of queue entry - // If front vertex is the destination vertex, - // we are done - if (v == N - 1) - break; + // If front vertex is the destination vertex, + // we are done + if (v == N - 1) + break; - // Otherwise dequeue the front vertex and enqueue - // its adjacent vertices (or cell numbers reachable - // through a dice throw) - q.pop(); - for (int j = v + 1; j <= (v + 6) && j < N; ++j) { - // If this cell is already visited, then ignore - if (!visited[j]) { - // Otherwise calculate its distance and mark it - // as visited - queueEntry a; - a.dist = (qe.dist + 1); - visited[j] = true; + // Otherwise dequeue the front vertex and enqueue + // its adjacent vertices (or cell numbers reachable + // through a dice throw) + q.pop(); + for (int j = v + 1; j <= (v + 6) && j < N; ++j) { + // If this cell is already visited, then ignore + if (!visited[j]) { + // Otherwise calculate its distance and mark it + // as visited + queueEntry a; + a.dist = (qe.dist + 1); + visited[j] = true; - // Check if there a snake or ladder at 'j' - // then tail of snake or top of ladder - // become the adjacent of 'i' - if (move[j] != -1) - a.v = move[j]; - else - a.v = j; - q.push(a); - } - } + // Check if there a snake or ladder at 'j' + // then tail of snake or top of ladder + // become the adjacent of 'i' + if (move[j] != -1) + a.v = move[j]; + else + a.v = j; + q.push(a); + } } + } - // We reach here when 'qe' has last vertex - // return the distance of vertex in 'qe' - return qe.dist; + // We reach here when 'qe' has last vertex + // return the distance of vertex in 'qe' + return qe.dist; } // Driver program to test methods of graph class int main() { - // Let us construct the board given in above diagram - int N = 30; - int moves[N]; - for (int i = 0; i < N; i++) - moves[i] = -1; + // Let us construct the board given in above diagram + int N = 30; + int moves[N]; + for (int i = 0; i < N; i++) + moves[i] = -1; - // Ladders - moves[2] = 21; - moves[4] = 7; - moves[10] = 25; - moves[19] = 28; + // Ladders + moves[2] = 21; + moves[4] = 7; + moves[10] = 25; + moves[19] = 28; - // Snakes - moves[26] = 0; - moves[20] = 8; - moves[16] = 3; - moves[18] = 6; + // Snakes + moves[26] = 0; + moves[20] = 8; + moves[16] = 3; + moves[18] = 6; - cout << "Min Dice throws required is " << getMinDiceThrows(moves, N); - return 0; + cout << "Min Dice throws required is " << getMinDiceThrows(moves, N); + return 0; } diff --git a/src/test-suite/PE-benchmarks/sort-array-wave-form-2.cpp b/src/test-suite/PE-benchmarks/sort-array-wave-form-2.cpp index 473378d8..d2a6f784 100644 --- a/src/test-suite/PE-benchmarks/sort-array-wave-form-2.cpp +++ b/src/test-suite/PE-benchmarks/sort-array-wave-form-2.cpp @@ -4,32 +4,32 @@ using namespace std; // A utility method to swap two numbers. void swap(int *x, int *y) { - int temp = *x; - *x = *y; - *y = temp; + int temp = *x; + *x = *y; + *y = temp; } // This function sorts arr[0..n-1] in wave form, i.e., arr[0] >= // arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5] .... void sortInWave(int arr[], int n) { - // Traverse all even elements - for (int i = 0; i < n; i += 2) { - // If current even element is smaller than previous - if (i > 0 && arr[i - 1] > arr[i]) - swap(&arr[i], &arr[i - 1]); + // Traverse all even elements + for (int i = 0; i < n; i += 2) { + // If current even element is smaller than previous + if (i > 0 && arr[i - 1] > arr[i]) + swap(&arr[i], &arr[i - 1]); - // If current even element is smaller than next - if (i < n - 1 && arr[i] < arr[i + 1]) - swap(&arr[i], &arr[i + 1]); - } + // If current even element is smaller than next + if (i < n - 1 && arr[i] < arr[i + 1]) + swap(&arr[i], &arr[i + 1]); + } } // Driver program to test above function int main() { - int arr[] = {10, 90, 49, 2, 1, 5, 23}; - int n = sizeof(arr) / sizeof(arr[0]); - sortInWave(arr, n); - for (int i = 0; i < n; i++) - cout << arr[i] << " "; - return 0; + int arr[] = {10, 90, 49, 2, 1, 5, 23}; + int n = sizeof(arr) / sizeof(arr[0]); + sortInWave(arr, n); + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + return 0; } diff --git a/src/test-suite/PE-benchmarks/sort-n-numbers-range-0-n2-1-linear-time.cpp b/src/test-suite/PE-benchmarks/sort-n-numbers-range-0-n2-1-linear-time.cpp index 59e412df..3e3bab8e 100644 --- a/src/test-suite/PE-benchmarks/sort-n-numbers-range-0-n2-1-linear-time.cpp +++ b/src/test-suite/PE-benchmarks/sort-n-numbers-range-0-n2-1-linear-time.cpp @@ -5,60 +5,60 @@ using namespace std; // the digit represented by exp. int countSort(int arr[], int n, int exp) { - int output[n]; // output array - int i, count[n]; - for (int i = 0; i < n; i++) - count[i] = 0; + int output[n]; // output array + int i, count[n]; + for (int i = 0; i < n; i++) + count[i] = 0; - // Store count of occurrences in count[] - for (i = 0; i < n; i++) - count[(arr[i] / exp) % n]++; + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % n]++; - // Change count[i] so that count[i] now contains actual - // position of this digit in output[] - for (i = 1; i < n; i++) - count[i] += count[i - 1]; + // Change count[i] so that count[i] now contains actual + // position of this digit in output[] + for (i = 1; i < n; i++) + count[i] += count[i - 1]; - // Build the output array - for (i = n - 1; i >= 0; i--) { - output[count[(arr[i] / exp) % n] - 1] = arr[i]; - count[(arr[i] / exp) % n]--; - } + // Build the output array + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % n] - 1] = arr[i]; + count[(arr[i] / exp) % n]--; + } - // Copy the output array to arr[], so that arr[] now - // contains sorted numbers according to current digit - for (i = 0; i < n; i++) - arr[i] = output[i]; + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current digit + for (i = 0; i < n; i++) + arr[i] = output[i]; } // The main function to that sorts arr[] of size n using Radix Sort void sort(int arr[], int n) { - // Do counting sort for first digit in base n. Note that - // instead of passing digit number, exp (n^0 = 1) is passed. - countSort(arr, n, 1); + // Do counting sort for first digit in base n. Note that + // instead of passing digit number, exp (n^0 = 1) is passed. + countSort(arr, n, 1); - // Do counting sort for second digit in base n. Note that - // instead of passing digit number, exp (n^1 = n) is passed. - countSort(arr, n, n); + // Do counting sort for second digit in base n. Note that + // instead of passing digit number, exp (n^1 = n) is passed. + countSort(arr, n, n); } // A utility function to print an array void printArr(int arr[], int n) { - for (int i = 0; i < n; i++) - cout << arr[i] << " "; + for (int i = 0; i < n; i++) + cout << arr[i] << " "; } // Driver program to test above functions int main() { - // Since array size is 7, elements should be from 0 to 48 - int arr[] = {40, 12, 45, 32, 33, 1, 22}; - int n = sizeof(arr) / sizeof(arr[0]); - cout << "Given array is n"; - printArr(arr, n); + // Since array size is 7, elements should be from 0 to 48 + int arr[] = {40, 12, 45, 32, 33, 1, 22}; + int n = sizeof(arr) / sizeof(arr[0]); + cout << "Given array is n"; + printArr(arr, n); - sort(arr, n); + sort(arr, n); - cout << "nSorted array is n"; - printArr(arr, n); - return 0; + cout << "nSorted array is n"; + printArr(arr, n); + return 0; } diff --git a/src/test-suite/PE-benchmarks/sorted-array-number-x-find-pair-array-whose-sum-closest-x.cpp b/src/test-suite/PE-benchmarks/sorted-array-number-x-find-pair-array-whose-sum-closest-x.cpp index 4b3df6db..7826f050 100644 --- a/src/test-suite/PE-benchmarks/sorted-array-number-x-find-pair-array-whose-sum-closest-x.cpp +++ b/src/test-suite/PE-benchmarks/sorted-array-number-x-find-pair-array-whose-sum-closest-x.cpp @@ -6,35 +6,35 @@ using namespace std; // Prints the pair with sum closest to x void printClosest(int arr[], int n, int x) { - int res_l, res_r; // To store indexes of result pair + int res_l, res_r; // To store indexes of result pair - // Initialize left and right indexes and difference between - // pair sum and x - int l = 0, r = n - 1, diff = INT_MAX; + // Initialize left and right indexes and difference between + // pair sum and x + int l = 0, r = n - 1, diff = INT_MAX; - // While there are elements between l and r - while (r > l) { - // Check if this pair is closer than the closest pair so far - if (abs(arr[l] + arr[r] - x) < diff) { - res_l = l; - res_r = r; - diff = abs(arr[l] + arr[r] - x); - } - - // If this pair has more sum, move to smaller values. - if (arr[l] + arr[r] > x) - r--; - else // Move to larger values - l++; + // While there are elements between l and r + while (r > l) { + // Check if this pair is closer than the closest pair so far + if (abs(arr[l] + arr[r] - x) < diff) { + res_l = l; + res_r = r; + diff = abs(arr[l] + arr[r] - x); } - cout << " The closest pair is " << arr[res_l] << " and " << arr[res_r]; + // If this pair has more sum, move to smaller values. + if (arr[l] + arr[r] > x) + r--; + else // Move to larger values + l++; + } + + cout << " The closest pair is " << arr[res_l] << " and " << arr[res_r]; } // Driver program to test above functions int main() { - int arr[] = {10, 22, 28, 29, 30, 40}, x = 54; - int n = sizeof(arr) / sizeof(arr[0]); - printClosest(arr, n, x); - return 0; + int arr[] = {10, 22, 28, 29, 30, 40}, x = 54; + int n = sizeof(arr) / sizeof(arr[0]); + printClosest(arr, n, x); + return 0; } diff --git a/src/test-suite/PE-benchmarks/strongly-connected-components.cpp b/src/test-suite/PE-benchmarks/strongly-connected-components.cpp index 5832ef1c..d77e08ff 100644 --- a/src/test-suite/PE-benchmarks/strongly-connected-components.cpp +++ b/src/test-suite/PE-benchmarks/strongly-connected-components.cpp @@ -5,126 +5,126 @@ using namespace std; class Graph { - int V; // No. of vertices - list *adj; // An array of adjacency lists + int V; // No. of vertices + list *adj; // An array of adjacency lists - // Fills Stack with vertices (in increasing order of finishing - // times). The top element of stack has the maximum finishing - // time - void fillOrder(int v, bool visited[], stack &Stack); + // Fills Stack with vertices (in increasing order of finishing + // times). The top element of stack has the maximum finishing + // time + void fillOrder(int v, bool visited[], stack &Stack); - // A recursive function to print DFS starting from v - void DFSUtil(int v, bool visited[]); + // A recursive function to print DFS starting from v + void DFSUtil(int v, bool visited[]); - public: - Graph(int V); - void addEdge(int v, int w); +public: + Graph(int V); + void addEdge(int v, int w); - // The main function that finds and prints strongly connected - // components - void printSCCs(); + // The main function that finds and prints strongly connected + // components + void printSCCs(); - // Function that returns reverse (or transpose) of this graph - Graph getTranspose(); + // Function that returns reverse (or transpose) of this graph + Graph getTranspose(); }; Graph::Graph(int V) { - this->V = V; - adj = new list[V]; + this->V = V; + adj = new list[V]; } // A recursive function to print DFS starting from v void Graph::DFSUtil(int v, bool visited[]) { - // Mark the current node as visited and print it - visited[v] = true; - cout << v << " "; - - // Recur for all the vertices adjacent to this vertex - list::iterator i; - for (i = adj[v].begin(); i != adj[v].end(); ++i) - if (!visited[*i]) - DFSUtil(*i, visited); + // Mark the current node as visited and print it + visited[v] = true; + cout << v << " "; + + // Recur for all the vertices adjacent to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) + if (!visited[*i]) + DFSUtil(*i, visited); } Graph Graph::getTranspose() { - Graph g(V); - for (int v = 0; v < V; v++) { - // Recur for all the vertices adjacent to this vertex - list::iterator i; - for (i = adj[v].begin(); i != adj[v].end(); ++i) { - g.adj[*i].push_back(v); - } + Graph g(V); + for (int v = 0; v < V; v++) { + // Recur for all the vertices adjacent to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) { + g.adj[*i].push_back(v); } - return g; + } + return g; } void Graph::addEdge(int v, int w) { - adj[v].push_back(w); // Add w to v’s list. + adj[v].push_back(w); // Add w to v’s list. } void Graph::fillOrder(int v, bool visited[], stack &Stack) { - // Mark the current node as visited and print it - visited[v] = true; + // Mark the current node as visited and print it + visited[v] = true; - // Recur for all the vertices adjacent to this vertex - list::iterator i; - for (i = adj[v].begin(); i != adj[v].end(); ++i) - if (!visited[*i]) - fillOrder(*i, visited, Stack); + // Recur for all the vertices adjacent to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) + if (!visited[*i]) + fillOrder(*i, visited, Stack); - // All vertices reachable from v are processed by now, push v - Stack.push(v); + // All vertices reachable from v are processed by now, push v + Stack.push(v); } // The main function that finds and prints all strongly connected // components void Graph::printSCCs() { - stack Stack; - - // Mark all the vertices as not visited (For first DFS) - bool *visited = new bool[V]; - for (int i = 0; i < V; i++) - visited[i] = false; - - // Fill vertices in stack according to their finishing times - for (int i = 0; i < V; i++) - if (visited[i] == false) - fillOrder(i, visited, Stack); - - // Create a reversed graph - Graph gr = getTranspose(); - - // Mark all the vertices as not visited (For second DFS) - for (int i = 0; i < V; i++) - visited[i] = false; - - // Now process all vertices in order defined by Stack - while (Stack.empty() == false) { - // Pop a vertex from stack - int v = Stack.top(); - Stack.pop(); - - // Print Strongly connected component of the popped vertex - if (visited[v] == false) { - gr.DFSUtil(v, visited); - cout << endl; - } + stack Stack; + + // Mark all the vertices as not visited (For first DFS) + bool *visited = new bool[V]; + for (int i = 0; i < V; i++) + visited[i] = false; + + // Fill vertices in stack according to their finishing times + for (int i = 0; i < V; i++) + if (visited[i] == false) + fillOrder(i, visited, Stack); + + // Create a reversed graph + Graph gr = getTranspose(); + + // Mark all the vertices as not visited (For second DFS) + for (int i = 0; i < V; i++) + visited[i] = false; + + // Now process all vertices in order defined by Stack + while (Stack.empty() == false) { + // Pop a vertex from stack + int v = Stack.top(); + Stack.pop(); + + // Print Strongly connected component of the popped vertex + if (visited[v] == false) { + gr.DFSUtil(v, visited); + cout << endl; } + } } // Driver program to test above functions int main() { - // Create a graph given in the above diagram - Graph g(5); - g.addEdge(1, 0); - g.addEdge(0, 2); - g.addEdge(2, 1); - g.addEdge(0, 3); - g.addEdge(3, 4); - - cout << "Following are strongly connected components in " - "given graph \n"; - g.printSCCs(); - - return 0; + // Create a graph given in the above diagram + Graph g(5); + g.addEdge(1, 0); + g.addEdge(0, 2); + g.addEdge(2, 1); + g.addEdge(0, 3); + g.addEdge(3, 4); + + cout << "Following are strongly connected components in " + "given graph \n"; + g.printSCCs(); + + return 0; } diff --git a/src/test-suite/PE-benchmarks/subset-sum-problem.cpp b/src/test-suite/PE-benchmarks/subset-sum-problem.cpp index f9ed1cfb..9a23b942 100644 --- a/src/test-suite/PE-benchmarks/subset-sum-problem.cpp +++ b/src/test-suite/PE-benchmarks/subset-sum-problem.cpp @@ -3,49 +3,48 @@ // Returns true if there is a subset of set[] with sun equal to given sum bool isSubsetSum(int set[], int n, int sum) { - // The value of subset[i][j] will be true if there is a - // subset of set[0..j-1] with sum equal to i - bool subset[n + 1][sum + 1]; + // The value of subset[i][j] will be true if there is a + // subset of set[0..j-1] with sum equal to i + bool subset[n + 1][sum + 1]; - // If sum is 0, then answer is true - for (int i = 0; i <= n; i++) - subset[i][0] = true; + // If sum is 0, then answer is true + for (int i = 0; i <= n; i++) + subset[i][0] = true; - // If sum is not 0 and set is empty, then answer is false - for (int i = 1; i <= sum; i++) - subset[0][i] = false; + // If sum is not 0 and set is empty, then answer is false + for (int i = 1; i <= sum; i++) + subset[0][i] = false; - // Fill the subset table in botton up manner - for (int i = 1; i <= n; i++) { - for (int j = 1; j <= sum; j++) { - if (j < set[i - 1]) - subset[i][j] = subset[i - 1][j]; - if (j >= set[i - 1]) - subset[i][j] = - subset[i - 1][j] || subset[i - 1][j - set[i - 1]]; - } + // Fill the subset table in botton up manner + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= sum; j++) { + if (j < set[i - 1]) + subset[i][j] = subset[i - 1][j]; + if (j >= set[i - 1]) + subset[i][j] = subset[i - 1][j] || subset[i - 1][j - set[i - 1]]; } + } - /* // uncomment this code to print table - for (int i = 0; i <= n; i++) - { - for (int j = 0; j <= sum; j++) - printf ("%4d", subset[i][j]); - printf("\n"); - }*/ + /* // uncomment this code to print table + for (int i = 0; i <= n; i++) + { + for (int j = 0; j <= sum; j++) + printf ("%4d", subset[i][j]); + printf("\n"); + }*/ - return subset[n][sum]; + return subset[n][sum]; } // Driver program to test above function int main() { - int set[] = {3, 34, 4, 12, 5, 2}; - int sum = 9; - int n = sizeof(set) / sizeof(set[0]); - if (isSubsetSum(set, n, sum) == true) - printf("Found a subset with given sum"); - else - printf("No subset with given sum"); - return 0; + int set[] = {3, 34, 4, 12, 5, 2}; + int sum = 9; + int n = sizeof(set) / sizeof(set[0]); + if (isSubsetSum(set, n, sum) == true) + printf("Found a subset with given sum"); + else + printf("No subset with given sum"); + return 0; } // This code is contributed by Arjun Tyagi. diff --git a/src/test-suite/PE-benchmarks/subset-sum.cpp b/src/test-suite/PE-benchmarks/subset-sum.cpp index bcc4a295..d0dad82b 100644 --- a/src/test-suite/PE-benchmarks/subset-sum.cpp +++ b/src/test-suite/PE-benchmarks/subset-sum.cpp @@ -7,19 +7,19 @@ static int total_nodes; // prints subset found void printSubset(int A[], int size) { - for (int i = 0; i < size; i++) { - printf("%*d", 5, A[i]); - } + for (int i = 0; i < size; i++) { + printf("%*d", 5, A[i]); + } - printf("n"); + printf("n"); } // qsort compare function int comparator(const void *pLhs, const void *pRhs) { - int *lhs = (int *)pLhs; - int *rhs = (int *)pRhs; + int *lhs = (int *)pLhs; + int *rhs = (int *)pRhs; - return *lhs > *rhs; + return *lhs > *rhs; } // inputs @@ -32,66 +32,64 @@ int comparator(const void *pLhs, const void *pRhs) { // target_sum - sum to be found void subset_sum(int s[], int t[], int s_size, int t_size, int sum, int ite, int const target_sum) { - total_nodes++; + total_nodes++; - if (target_sum == sum) { - // We found sum - printSubset(t, t_size); + if (target_sum == sum) { + // We found sum + printSubset(t, t_size); - // constraint check - if (ite + 1 < s_size && sum - s[ite] + s[ite + 1] <= target_sum) { - // Exclude previous added item and consider next candidate - subset_sum(s, t, s_size, t_size - 1, sum - s[ite], ite + 1, - target_sum); - } - return; - } else { - // constraint check - if (ite < s_size && sum + s[ite] <= target_sum) { - // generate nodes along the breadth - for (int i = ite; i < s_size; i++) { - t[t_size] = s[i]; - - if (sum + s[i] <= target_sum) { - // consider next level node (along depth) - subset_sum(s, t, s_size, t_size + 1, sum + s[i], i + 1, - target_sum); - } - } + // constraint check + if (ite + 1 < s_size && sum - s[ite] + s[ite + 1] <= target_sum) { + // Exclude previous added item and consider next candidate + subset_sum(s, t, s_size, t_size - 1, sum - s[ite], ite + 1, target_sum); + } + return; + } else { + // constraint check + if (ite < s_size && sum + s[ite] <= target_sum) { + // generate nodes along the breadth + for (int i = ite; i < s_size; i++) { + t[t_size] = s[i]; + + if (sum + s[i] <= target_sum) { + // consider next level node (along depth) + subset_sum(s, t, s_size, t_size + 1, sum + s[i], i + 1, target_sum); } + } } + } } // Wrapper that prints subsets that sum to target_sum void generateSubsets(int s[], int size, int target_sum) { - int *tuplet_vector = (int *)malloc(size * sizeof(int)); + int *tuplet_vector = (int *)malloc(size * sizeof(int)); - int total = 0; + int total = 0; - // sort the set - qsort(s, size, sizeof(int), &comparator); + // sort the set + qsort(s, size, sizeof(int), &comparator); - for (int i = 0; i < size; i++) { - total += s[i]; - } + for (int i = 0; i < size; i++) { + total += s[i]; + } - if (s[0] <= target_sum && total >= target_sum) { + if (s[0] <= target_sum && total >= target_sum) { - subset_sum(s, tuplet_vector, size, 0, 0, 0, target_sum); - } + subset_sum(s, tuplet_vector, size, 0, 0, 0, target_sum); + } - free(tuplet_vector); + free(tuplet_vector); } int main() { - int weights[] = {15, 22, 14, 26, 32, 9, 16, 8}; - int target = 53; + int weights[] = {15, 22, 14, 26, 32, 9, 16, 8}; + int target = 53; - int size = ARRAYSIZE(weights); + int size = ARRAYSIZE(weights); - generateSubsets(weights, size, target); + generateSubsets(weights, size, target); - printf("Nodes generated %dn", total_nodes); + printf("Nodes generated %dn", total_nodes); - return 0; + return 0; } diff --git a/src/test-suite/PE-benchmarks/sudoku.cpp b/src/test-suite/PE-benchmarks/sudoku.cpp index 740a29e1..8dad497b 100644 --- a/src/test-suite/PE-benchmarks/sudoku.cpp +++ b/src/test-suite/PE-benchmarks/sudoku.cpp @@ -23,29 +23,29 @@ such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) */ bool SolveSudoku(int grid[N][N]) { - int row, col; - - // If there is no unassigned location, - // we are done - if (!FindUnassignedLocation(grid, row, col)) - return true; // success! - - // consider digits 1 to 9 - for (int num = 1; num <= 9; num++) { - // if looks promising - if (isSafe(grid, row, col, num)) { - // make tentative assignment - grid[row][col] = num; - - // return, if success, yay! - if (SolveSudoku(grid)) - return true; - - // failure, unmake & try again - grid[row][col] = UNASSIGNED; - } + int row, col; + + // If there is no unassigned location, + // we are done + if (!FindUnassignedLocation(grid, row, col)) + return true; // success! + + // consider digits 1 to 9 + for (int num = 1; num <= 9; num++) { + // if looks promising + if (isSafe(grid, row, col, num)) { + // make tentative assignment + grid[row][col] = num; + + // return, if success, yay! + if (SolveSudoku(grid)) + return true; + + // failure, unmake & try again + grid[row][col] = UNASSIGNED; } - return false; // this triggers backtracking + } + return false; // this triggers backtracking } /* Searches the grid to find an entry that is @@ -54,78 +54,78 @@ parameters row, col will be set the location that is unassigned, and true is returned. If no unassigned entries remain, false is returned. */ bool FindUnassignedLocation(int grid[N][N], int &row, int &col) { - for (row = 0; row < N; row++) - for (col = 0; col < N; col++) - if (grid[row][col] == UNASSIGNED) - return true; - return false; + for (row = 0; row < N; row++) + for (col = 0; col < N; col++) + if (grid[row][col] == UNASSIGNED) + return true; + return false; } /* Returns a boolean which indicates whether an assigned entry in the specified row matches the given number. */ bool UsedInRow(int grid[N][N], int row, int num) { - for (int col = 0; col < N; col++) - if (grid[row][col] == num) - return true; - return false; + for (int col = 0; col < N; col++) + if (grid[row][col] == num) + return true; + return false; } /* Returns a boolean which indicates whether an assigned entry in the specified column matches the given number. */ bool UsedInCol(int grid[N][N], int col, int num) { - for (int row = 0; row < N; row++) - if (grid[row][col] == num) - return true; - return false; + for (int row = 0; row < N; row++) + if (grid[row][col] == num) + return true; + return false; } /* Returns a boolean which indicates whether an assigned entry within the specified 3x3 box matches the given number. */ bool UsedInBox(int grid[N][N], int boxStartRow, int boxStartCol, int num) { - for (int row = 0; row < 3; row++) - for (int col = 0; col < 3; col++) - if (grid[row + boxStartRow][col + boxStartCol] == num) - return true; - return false; + for (int row = 0; row < 3; row++) + for (int col = 0; col < 3; col++) + if (grid[row + boxStartRow][col + boxStartCol] == num) + return true; + return false; } /* Returns a boolean which indicates whether it will be legal to assign num to the given row, col location. */ bool isSafe(int grid[N][N], int row, int col, int num) { - /* Check if 'num' is not already placed in - current row, current column and current 3x3 box */ - return !UsedInRow(grid, row, num) && !UsedInCol(grid, col, num) && - !UsedInBox(grid, row - row % 3, col - col % 3, num) && - grid[row][col] == UNASSIGNED; + /* Check if 'num' is not already placed in + current row, current column and current 3x3 box */ + return !UsedInRow(grid, row, num) && !UsedInCol(grid, col, num) && + !UsedInBox(grid, row - row % 3, col - col % 3, num) && + grid[row][col] == UNASSIGNED; } /* A utility function to print grid */ void printGrid(int grid[N][N]) { - for (int row = 0; row < N; row++) { - for (int col = 0; col < N; col++) - cout << grid[row][col] << " "; - cout << endl; - } + for (int row = 0; row < N; row++) { + for (int col = 0; col < N; col++) + cout << grid[row][col] << " "; + cout << endl; + } } // Driver Code int main() { - // 0 means unassigned cells - int grid[N][N] = {{3, 0, 6, 5, 0, 8, 4, 0, 0}, {5, 2, 0, 0, 0, 0, 0, 0, 0}, - {0, 8, 7, 0, 0, 0, 0, 3, 1}, {0, 0, 3, 0, 1, 0, 0, 8, 0}, - {9, 0, 0, 8, 6, 3, 0, 0, 5}, {0, 5, 0, 0, 9, 0, 6, 0, 0}, - {1, 3, 0, 0, 0, 0, 2, 5, 0}, {0, 0, 0, 0, 0, 0, 0, 7, 4}, - {0, 0, 5, 2, 0, 6, 3, 0, 0}}; - if (SolveSudoku(grid) == true) - printGrid(grid); - else - cout << "No solution exists"; - - return 0; + // 0 means unassigned cells + int grid[N][N] = {{3, 0, 6, 5, 0, 8, 4, 0, 0}, {5, 2, 0, 0, 0, 0, 0, 0, 0}, + {0, 8, 7, 0, 0, 0, 0, 3, 1}, {0, 0, 3, 0, 1, 0, 0, 8, 0}, + {9, 0, 0, 8, 6, 3, 0, 0, 5}, {0, 5, 0, 0, 9, 0, 6, 0, 0}, + {1, 3, 0, 0, 0, 0, 2, 5, 0}, {0, 0, 0, 0, 0, 0, 0, 7, 4}, + {0, 0, 5, 2, 0, 6, 3, 0, 0}}; + if (SolveSudoku(grid) == true) + printGrid(grid); + else + cout << "No solution exists"; + + return 0; } // This is code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/tarjan-algorithm.cpp b/src/test-suite/PE-benchmarks/tarjan-algorithm.cpp index e2d8a593..5653a508 100644 --- a/src/test-suite/PE-benchmarks/tarjan-algorithm.cpp +++ b/src/test-suite/PE-benchmarks/tarjan-algorithm.cpp @@ -8,22 +8,22 @@ using namespace std; // A class that represents an directed graph class Graph { - int V; // No. of vertices - list *adj; // A dynamic array of adjacency lists + int V; // No. of vertices + list *adj; // A dynamic array of adjacency lists - // A Recursive DFS based function used by SCC() - void SCCUtil(int u, int disc[], int low[], stack *st, - bool stackMember[]); + // A Recursive DFS based function used by SCC() + void SCCUtil(int u, int disc[], int low[], stack *st, + bool stackMember[]); - public: - Graph(int V); // Constructor - void addEdge(int v, int w); // function to add an edge to graph - void SCC(); // prints strongly connected components +public: + Graph(int V); // Constructor + void addEdge(int v, int w); // function to add an edge to graph + void SCC(); // prints strongly connected components }; Graph::Graph(int V) { - this->V = V; - adj = new list[V]; + this->V = V; + adj = new list[V]; } void Graph::addEdge(int v, int w) { adj[v].push_back(w); } @@ -41,134 +41,134 @@ void Graph::addEdge(int v, int w) { adj[v].push_back(w); } // a node is in stack void Graph::SCCUtil(int u, int disc[], int low[], stack *st, bool stackMember[]) { - // A static variable is used for simplicity, we can avoid use - // of static variable by passing a pointer. - static int time = 0; - - // Initialize discovery time and low value - disc[u] = low[u] = ++time; - st->push(u); - stackMember[u] = true; - - // Go through all vertices adjacent to this - list::iterator i; - for (i = adj[u].begin(); i != adj[u].end(); ++i) { - int v = *i; // v is current adjacent of 'u' - - // If v is not visited yet, then recur for it - if (disc[v] == -1) { - SCCUtil(v, disc, low, st, stackMember); - - // Check if the subtree rooted with 'v' has a - // connection to one of the ancestors of 'u' - // Case 1 (per above discussion on Disc and Low value) - low[u] = min(low[u], low[v]); - } - - // Update low value of 'u' only of 'v' is still in stack - // (i.e. it's a back edge, not cross edge). - // Case 2 (per above discussion on Disc and Low value) - else if (stackMember[v] == true) - low[u] = min(low[u], disc[v]); + // A static variable is used for simplicity, we can avoid use + // of static variable by passing a pointer. + static int time = 0; + + // Initialize discovery time and low value + disc[u] = low[u] = ++time; + st->push(u); + stackMember[u] = true; + + // Go through all vertices adjacent to this + list::iterator i; + for (i = adj[u].begin(); i != adj[u].end(); ++i) { + int v = *i; // v is current adjacent of 'u' + + // If v is not visited yet, then recur for it + if (disc[v] == -1) { + SCCUtil(v, disc, low, st, stackMember); + + // Check if the subtree rooted with 'v' has a + // connection to one of the ancestors of 'u' + // Case 1 (per above discussion on Disc and Low value) + low[u] = min(low[u], low[v]); } - // head node found, pop the stack and print an SCC - int w = 0; // To store stack extracted vertices - if (low[u] == disc[u]) { - while (st->top() != u) { - w = (int)st->top(); - cout << w << " "; - stackMember[w] = false; - st->pop(); - } - w = (int)st->top(); - cout << w << "\n"; - stackMember[w] = false; - st->pop(); + // Update low value of 'u' only of 'v' is still in stack + // (i.e. it's a back edge, not cross edge). + // Case 2 (per above discussion on Disc and Low value) + else if (stackMember[v] == true) + low[u] = min(low[u], disc[v]); + } + + // head node found, pop the stack and print an SCC + int w = 0; // To store stack extracted vertices + if (low[u] == disc[u]) { + while (st->top() != u) { + w = (int)st->top(); + cout << w << " "; + stackMember[w] = false; + st->pop(); } + w = (int)st->top(); + cout << w << "\n"; + stackMember[w] = false; + st->pop(); + } } // The function to do DFS traversal. It uses SCCUtil() void Graph::SCC() { - int *disc = new int[V]; - int *low = new int[V]; - bool *stackMember = new bool[V]; - stack *st = new stack(); - - // Initialize disc and low, and stackMember arrays - for (int i = 0; i < V; i++) { - disc[i] = NIL; - low[i] = NIL; - stackMember[i] = false; - } - - // Call the recursive helper function to find strongly - // connected components in DFS tree with vertex 'i' - for (int i = 0; i < V; i++) - if (disc[i] == NIL) - SCCUtil(i, disc, low, st, stackMember); + int *disc = new int[V]; + int *low = new int[V]; + bool *stackMember = new bool[V]; + stack *st = new stack(); + + // Initialize disc and low, and stackMember arrays + for (int i = 0; i < V; i++) { + disc[i] = NIL; + low[i] = NIL; + stackMember[i] = false; + } + + // Call the recursive helper function to find strongly + // connected components in DFS tree with vertex 'i' + for (int i = 0; i < V; i++) + if (disc[i] == NIL) + SCCUtil(i, disc, low, st, stackMember); } // Driver program to test above function int main() { - cout << "\nSCCs in first graph \n"; - Graph g1(5); - g1.addEdge(1, 0); - g1.addEdge(0, 2); - g1.addEdge(2, 1); - g1.addEdge(0, 3); - g1.addEdge(3, 4); - g1.SCC(); - - cout << "\nSCCs in second graph \n"; - Graph g2(4); - g2.addEdge(0, 1); - g2.addEdge(1, 2); - g2.addEdge(2, 3); - g2.SCC(); - - cout << "\nSCCs in third graph \n"; - Graph g3(7); - g3.addEdge(0, 1); - g3.addEdge(1, 2); - g3.addEdge(2, 0); - g3.addEdge(1, 3); - g3.addEdge(1, 4); - g3.addEdge(1, 6); - g3.addEdge(3, 5); - g3.addEdge(4, 5); - g3.SCC(); - - cout << "\nSCCs in fourth graph \n"; - Graph g4(11); - g4.addEdge(0, 1); - g4.addEdge(0, 3); - g4.addEdge(1, 2); - g4.addEdge(1, 4); - g4.addEdge(2, 0); - g4.addEdge(2, 6); - g4.addEdge(3, 2); - g4.addEdge(4, 5); - g4.addEdge(4, 6); - g4.addEdge(5, 6); - g4.addEdge(5, 7); - g4.addEdge(5, 8); - g4.addEdge(5, 9); - g4.addEdge(6, 4); - g4.addEdge(7, 9); - g4.addEdge(8, 9); - g4.addEdge(9, 8); - g4.SCC(); - - cout << "\nSCCs in fifth graph \n"; - Graph g5(5); - g5.addEdge(0, 1); - g5.addEdge(1, 2); - g5.addEdge(2, 3); - g5.addEdge(2, 4); - g5.addEdge(3, 0); - g5.addEdge(4, 2); - g5.SCC(); - - return 0; + cout << "\nSCCs in first graph \n"; + Graph g1(5); + g1.addEdge(1, 0); + g1.addEdge(0, 2); + g1.addEdge(2, 1); + g1.addEdge(0, 3); + g1.addEdge(3, 4); + g1.SCC(); + + cout << "\nSCCs in second graph \n"; + Graph g2(4); + g2.addEdge(0, 1); + g2.addEdge(1, 2); + g2.addEdge(2, 3); + g2.SCC(); + + cout << "\nSCCs in third graph \n"; + Graph g3(7); + g3.addEdge(0, 1); + g3.addEdge(1, 2); + g3.addEdge(2, 0); + g3.addEdge(1, 3); + g3.addEdge(1, 4); + g3.addEdge(1, 6); + g3.addEdge(3, 5); + g3.addEdge(4, 5); + g3.SCC(); + + cout << "\nSCCs in fourth graph \n"; + Graph g4(11); + g4.addEdge(0, 1); + g4.addEdge(0, 3); + g4.addEdge(1, 2); + g4.addEdge(1, 4); + g4.addEdge(2, 0); + g4.addEdge(2, 6); + g4.addEdge(3, 2); + g4.addEdge(4, 5); + g4.addEdge(4, 6); + g4.addEdge(5, 6); + g4.addEdge(5, 7); + g4.addEdge(5, 8); + g4.addEdge(5, 9); + g4.addEdge(6, 4); + g4.addEdge(7, 9); + g4.addEdge(8, 9); + g4.addEdge(9, 8); + g4.SCC(); + + cout << "\nSCCs in fifth graph \n"; + Graph g5(5); + g5.addEdge(0, 1); + g5.addEdge(1, 2); + g5.addEdge(2, 3); + g5.addEdge(2, 4); + g5.addEdge(3, 0); + g5.addEdge(4, 2); + g5.SCC(); + + return 0; } diff --git a/src/test-suite/PE-benchmarks/the-knights-tour.cpp b/src/test-suite/PE-benchmarks/the-knights-tour.cpp index e578df1e..71e32c1b 100644 --- a/src/test-suite/PE-benchmarks/the-knights-tour.cpp +++ b/src/test-suite/PE-benchmarks/the-knights-tour.cpp @@ -8,16 +8,16 @@ int solveKTUtil(int x, int y, int movei, int sol[N][N], int xMove[], /* A utility function to check if i,j are valid indexes for N*N chessboard */ bool isSafe(int x, int y, int sol[N][N]) { - return (x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1); + return (x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1); } /* A utility function to print solution matrix sol[N][N] */ void printSolution(int sol[N][N]) { - for (int x = 0; x < N; x++) { - for (int y = 0; y < N; y++) - printf(" %2d ", sol[x][y]); - printf("\n"); - } + for (int x = 0; x < N; x++) { + for (int y = 0; y < N; y++) + printf(" %2d ", sol[x][y]); + printf("\n"); + } } /* This function solves the Knight Tour problem using @@ -28,60 +28,59 @@ tour. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */ bool solveKT() { - int sol[N][N]; + int sol[N][N]; - /* Initialization of solution matrix */ - for (int x = 0; x < N; x++) - for (int y = 0; y < N; y++) - sol[x][y] = -1; + /* Initialization of solution matrix */ + for (int x = 0; x < N; x++) + for (int y = 0; y < N; y++) + sol[x][y] = -1; - /* xMove[] and yMove[] define next move of Knight. - xMove[] is for next value of x coordinate - yMove[] is for next value of y coordinate */ - int xMove[8] = {2, 1, -1, -2, -2, -1, 1, 2}; - int yMove[8] = {1, 2, 2, 1, -1, -2, -2, -1}; + /* xMove[] and yMove[] define next move of Knight. + xMove[] is for next value of x coordinate + yMove[] is for next value of y coordinate */ + int xMove[8] = {2, 1, -1, -2, -2, -1, 1, 2}; + int yMove[8] = {1, 2, 2, 1, -1, -2, -2, -1}; - // Since the Knight is initially at the first block - sol[0][0] = 0; + // Since the Knight is initially at the first block + sol[0][0] = 0; - /* Start from 0,0 and explore all tours using - solveKTUtil() */ - if (solveKTUtil(0, 0, 1, sol, xMove, yMove) == false) { - printf("Solution does not exist"); - return false; - } else - printSolution(sol); + /* Start from 0,0 and explore all tours using + solveKTUtil() */ + if (solveKTUtil(0, 0, 1, sol, xMove, yMove) == false) { + printf("Solution does not exist"); + return false; + } else + printSolution(sol); - return true; + return true; } /* A recursive utility function to solve Knight Tour problem */ int solveKTUtil(int x, int y, int movei, int sol[N][N], int xMove[N], int yMove[N]) { - int k, next_x, next_y; - if (movei == N * N) - return true; + int k, next_x, next_y; + if (movei == N * N) + return true; - /* Try all next moves from the current coordinate x, y */ - for (k = 0; k < 8; k++) { - next_x = x + xMove[k]; - next_y = y + yMove[k]; - if (isSafe(next_x, next_y, sol)) { - sol[next_x][next_y] = movei; - if (solveKTUtil(next_x, next_y, movei + 1, sol, xMove, yMove) == - true) - return true; - else - sol[next_x][next_y] = -1; // backtracking - } + /* Try all next moves from the current coordinate x, y */ + for (k = 0; k < 8; k++) { + next_x = x + xMove[k]; + next_y = y + yMove[k]; + if (isSafe(next_x, next_y, sol)) { + sol[next_x][next_y] = movei; + if (solveKTUtil(next_x, next_y, movei + 1, sol, xMove, yMove) == true) + return true; + else + sol[next_x][next_y] = -1; // backtracking } + } - return false; + return false; } /* Driver program to test above functions */ int main() { - solveKT(); - return 0; + solveKT(); + return 0; } diff --git a/src/test-suite/PE-benchmarks/topological-sorting.cpp b/src/test-suite/PE-benchmarks/topological-sorting.cpp index 9fc53421..0b1395b1 100644 --- a/src/test-suite/PE-benchmarks/topological-sorting.cpp +++ b/src/test-suite/PE-benchmarks/topological-sorting.cpp @@ -6,84 +6,84 @@ using namespace std; // Class to represent a graph class Graph { - int V; // No. of vertices' + int V; // No. of vertices' - // Pointer to an array containing adjacency listsList - list *adj; + // Pointer to an array containing adjacency listsList + list *adj; - // A function used by topologicalSort - void topologicalSortUtil(int v, bool visited[], stack &Stack); + // A function used by topologicalSort + void topologicalSortUtil(int v, bool visited[], stack &Stack); - public: - Graph(int V); // Constructor +public: + Graph(int V); // Constructor - // function to add an edge to graph - void addEdge(int v, int w); + // function to add an edge to graph + void addEdge(int v, int w); - // prints a Topological Sort of the complete graph - void topologicalSort(); + // prints a Topological Sort of the complete graph + void topologicalSort(); }; Graph::Graph(int V) { - this->V = V; - adj = new list[V]; + this->V = V; + adj = new list[V]; } void Graph::addEdge(int v, int w) { - adj[v].push_back(w); // Add w to v’s list. + adj[v].push_back(w); // Add w to v’s list. } // A recursive function used by topologicalSort void Graph::topologicalSortUtil(int v, bool visited[], stack &Stack) { - // Mark the current node as visited. - visited[v] = true; + // Mark the current node as visited. + visited[v] = true; - // Recur for all the vertices adjacent to this vertex - list::iterator i; - for (i = adj[v].begin(); i != adj[v].end(); ++i) - if (!visited[*i]) - topologicalSortUtil(*i, visited, Stack); + // Recur for all the vertices adjacent to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) + if (!visited[*i]) + topologicalSortUtil(*i, visited, Stack); - // Push current vertex to stack which stores result - Stack.push(v); + // Push current vertex to stack which stores result + Stack.push(v); } // The function to do Topological Sort. It uses recursive // topologicalSortUtil() void Graph::topologicalSort() { - stack Stack; - - // Mark all the vertices as not visited - bool *visited = new bool[V]; - for (int i = 0; i < V; i++) - visited[i] = false; - - // Call the recursive helper function to store Topological - // Sort starting from all vertices one by one - for (int i = 0; i < V; i++) - if (visited[i] == false) - topologicalSortUtil(i, visited, Stack); - - // Print contents of stack - while (Stack.empty() == false) { - cout << Stack.top() << " "; - Stack.pop(); - } + stack Stack; + + // Mark all the vertices as not visited + bool *visited = new bool[V]; + for (int i = 0; i < V; i++) + visited[i] = false; + + // Call the recursive helper function to store Topological + // Sort starting from all vertices one by one + for (int i = 0; i < V; i++) + if (visited[i] == false) + topologicalSortUtil(i, visited, Stack); + + // Print contents of stack + while (Stack.empty() == false) { + cout << Stack.top() << " "; + Stack.pop(); + } } // Driver program to test above functions int main() { - // Create a graph given in the above diagram - Graph g(6); - g.addEdge(5, 2); - g.addEdge(5, 0); - g.addEdge(4, 0); - g.addEdge(4, 1); - g.addEdge(2, 3); - g.addEdge(3, 1); - - cout << "Following is a Topological Sort of the given graph \n"; - g.topologicalSort(); - - return 0; + // Create a graph given in the above diagram + Graph g(6); + g.addEdge(5, 2); + g.addEdge(5, 0); + g.addEdge(4, 0); + g.addEdge(4, 1); + g.addEdge(2, 3); + g.addEdge(3, 1); + + cout << "Following is a Topological Sort of the given graph \n"; + g.topologicalSort(); + + return 0; } diff --git a/src/test-suite/PE-benchmarks/total-number-of-non-decreasing-numbers-with-n-digits.cpp b/src/test-suite/PE-benchmarks/total-number-of-non-decreasing-numbers-with-n-digits.cpp index c00406ae..cd88a001 100644 --- a/src/test-suite/PE-benchmarks/total-number-of-non-decreasing-numbers-with-n-digits.cpp +++ b/src/test-suite/PE-benchmarks/total-number-of-non-decreasing-numbers-with-n-digits.cpp @@ -3,41 +3,41 @@ using namespace std; long long int countNonDecreasing(int n) { - // dp[i][j] contains total count of non decreasing - // numbers ending with digit i and of length j - long long int dp[10][n + 1]; - memset(dp, 0, sizeof dp); + // dp[i][j] contains total count of non decreasing + // numbers ending with digit i and of length j + long long int dp[10][n + 1]; + memset(dp, 0, sizeof dp); - // Fill table for non decreasing numbers of length 1 - // Base cases 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 - for (int i = 0; i < 10; i++) - dp[i][1] = 1; + // Fill table for non decreasing numbers of length 1 + // Base cases 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 + for (int i = 0; i < 10; i++) + dp[i][1] = 1; - // Fill the table in bottom-up manner - for (int digit = 0; digit <= 9; digit++) { - // Compute total numbers of non decreasing - // numbers of length 'len' - for (int len = 2; len <= n; len++) { - // sum of all numbers of length of len-1 - // in which last digit x is <= 'digit' - for (int x = 0; x <= digit; x++) - dp[digit][len] += dp[x][len - 1]; - } + // Fill the table in bottom-up manner + for (int digit = 0; digit <= 9; digit++) { + // Compute total numbers of non decreasing + // numbers of length 'len' + for (int len = 2; len <= n; len++) { + // sum of all numbers of length of len-1 + // in which last digit x is <= 'digit' + for (int x = 0; x <= digit; x++) + dp[digit][len] += dp[x][len - 1]; } + } - long long int count = 0; + long long int count = 0; - // There total nondecreasing numbers of length n - // wiint be dp[0][n] + dp[1][n] ..+ dp[9][n] - for (int i = 0; i < 10; i++) - count += dp[i][n]; + // There total nondecreasing numbers of length n + // wiint be dp[0][n] + dp[1][n] ..+ dp[9][n] + for (int i = 0; i < 10; i++) + count += dp[i][n]; - return count; + return count; } // Driver program int main() { - int n = 3; - cout << countNonDecreasing(n); - return 0; + int n = 3; + cout << countNonDecreasing(n); + return 0; } diff --git a/src/test-suite/PE-benchmarks/tower-of-hanoi.cpp b/src/test-suite/PE-benchmarks/tower-of-hanoi.cpp index 7ac4bcda..6e30ca98 100644 --- a/src/test-suite/PE-benchmarks/tower-of-hanoi.cpp +++ b/src/test-suite/PE-benchmarks/tower-of-hanoi.cpp @@ -4,22 +4,21 @@ using namespace std; void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) { - if (n == 1) { - cout << "Move disk 1 from rod " << from_rod << " to rod " << to_rod - << endl; - return; - } - towerOfHanoi(n - 1, from_rod, aux_rod, to_rod); - cout << "Move disk " << n << " from rod " << from_rod << " to rod " - << to_rod << endl; - towerOfHanoi(n - 1, aux_rod, to_rod, from_rod); + if (n == 1) { + cout << "Move disk 1 from rod " << from_rod << " to rod " << to_rod << endl; + return; + } + towerOfHanoi(n - 1, from_rod, aux_rod, to_rod); + cout << "Move disk " << n << " from rod " << from_rod << " to rod " << to_rod + << endl; + towerOfHanoi(n - 1, aux_rod, to_rod, from_rod); } // Driver code int main() { - int n = 4; // Number of disks - towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods - return 0; + int n = 4; // Number of disks + towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods + return 0; } // This is code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/transitive-closure-of-a-graph.cpp b/src/test-suite/PE-benchmarks/transitive-closure-of-a-graph.cpp index 7c280de0..f99824cf 100644 --- a/src/test-suite/PE-benchmarks/transitive-closure-of-a-graph.cpp +++ b/src/test-suite/PE-benchmarks/transitive-closure-of-a-graph.cpp @@ -9,67 +9,67 @@ void printSolution(int reach[][V]); // Prints transitive closure of graph[][] using Floyd Warshall algorithm void transitiveClosure(int graph[][V]) { - /* reach[][] will be the output matrix that will finally have the - shortest distances between every pair of vertices */ - int reach[V][V], i, j, k; + /* reach[][] will be the output matrix that will finally have the + shortest distances between every pair of vertices */ + int reach[V][V], i, j, k; - /* Initialize the solution matrix same as input graph matrix. Or - we can say the initial values of shortest distances are based - on shortest paths considering no intermediate vertex. */ - for (i = 0; i < V; i++) - for (j = 0; j < V; j++) - reach[i][j] = graph[i][j]; + /* Initialize the solution matrix same as input graph matrix. Or + we can say the initial values of shortest distances are based + on shortest paths considering no intermediate vertex. */ + for (i = 0; i < V; i++) + for (j = 0; j < V; j++) + reach[i][j] = graph[i][j]; - /* Add all vertices one by one to the set of intermediate vertices. - ---> Before start of a iteration, we have reachability values for - all pairs of vertices such that the reachability values - consider only the vertices in set {0, 1, 2, .. k-1} as - intermediate vertices. - ----> After the end of a iteration, vertex no. k is added to the - set of intermediate vertices and the set becomes {0, 1, .. - k} - */ - for (k = 0; k < V; k++) { - // Pick all vertices as source one by one - for (i = 0; i < V; i++) { - // Pick all vertices as destination for the - // above picked source - for (j = 0; j < V; j++) { - // If vertex k is on a path from i to j, - // then make sure that the value of reach[i][j] is 1 - reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]); - } - } + /* Add all vertices one by one to the set of intermediate vertices. + ---> Before start of a iteration, we have reachability values for + all pairs of vertices such that the reachability values + consider only the vertices in set {0, 1, 2, .. k-1} as + intermediate vertices. + ----> After the end of a iteration, vertex no. k is added to the + set of intermediate vertices and the set becomes {0, 1, .. + k} +*/ + for (k = 0; k < V; k++) { + // Pick all vertices as source one by one + for (i = 0; i < V; i++) { + // Pick all vertices as destination for the + // above picked source + for (j = 0; j < V; j++) { + // If vertex k is on a path from i to j, + // then make sure that the value of reach[i][j] is 1 + reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]); + } } + } - // Print the shortest distance matrix - printSolution(reach); + // Print the shortest distance matrix + printSolution(reach); } /* A utility function to print solution */ void printSolution(int reach[][V]) { - printf("Following matrix is transitive closure of the given graph\n"); - for (int i = 0; i < V; i++) { - for (int j = 0; j < V; j++) - printf("%d ", reach[i][j]); - printf("\n"); - } + printf("Following matrix is transitive closure of the given graph\n"); + for (int i = 0; i < V; i++) { + for (int j = 0; j < V; j++) + printf("%d ", reach[i][j]); + printf("\n"); + } } // driver program to test above function int main() { - /* Let us create the following weighted graph - 10 - (0)------->(3) - | /|\ - 5 | | - | | 1 - \|/ | - (1)------->(2) - 3 */ - int graph[V][V] = {{1, 1, 0, 1}, {0, 1, 1, 0}, {0, 0, 1, 1}, {0, 0, 0, 1}}; + /* Let us create the following weighted graph + 10 + (0)------->(3) + | /|\ + 5 | | + | | 1 + \|/ | + (1)------->(2) + 3 */ + int graph[V][V] = {{1, 1, 0, 1}, {0, 1, 1, 0}, {0, 0, 1, 1}, {0, 0, 0, 1}}; - // Print the solution - transitiveClosure(graph); - return 0; + // Print the solution + transitiveClosure(graph); + return 0; } diff --git a/src/test-suite/PE-benchmarks/trie-suffixes.cpp b/src/test-suite/PE-benchmarks/trie-suffixes.cpp index 77c046c1..6870c6c1 100644 --- a/src/test-suite/PE-benchmarks/trie-suffixes.cpp +++ b/src/test-suite/PE-benchmarks/trie-suffixes.cpp @@ -6,125 +6,125 @@ using namespace std; // A Suffix Trie (A Trie of all suffixes) Node class SuffixTrieNode { - private: - SuffixTrieNode *children[MAX_CHAR]; - list *indexes; - - public: - SuffixTrieNode() // Constructor - { - // Create an empty linked list for indexes of - // suffixes starting from this node - indexes = new list; - - // Initialize all child pointers as NULL - for (int i = 0; i < MAX_CHAR; i++) - children[i] = NULL; - } - - // A recursive function to insert a suffix of the txt - // in subtree rooted with this node - void insertSuffix(string suffix, int index); - - // A function to search a pattern in subtree rooted - // with this node.The function returns pointer to a linked - // list containing all indexes where pattern is present. - // The returned indexes are indexes of last characters - // of matched text. - list *search(string pat); +private: + SuffixTrieNode *children[MAX_CHAR]; + list *indexes; + +public: + SuffixTrieNode() // Constructor + { + // Create an empty linked list for indexes of + // suffixes starting from this node + indexes = new list; + + // Initialize all child pointers as NULL + for (int i = 0; i < MAX_CHAR; i++) + children[i] = NULL; + } + + // A recursive function to insert a suffix of the txt + // in subtree rooted with this node + void insertSuffix(string suffix, int index); + + // A function to search a pattern in subtree rooted + // with this node.The function returns pointer to a linked + // list containing all indexes where pattern is present. + // The returned indexes are indexes of last characters + // of matched text. + list *search(string pat); }; // A Trie of all suffixes class SuffixTrie { - private: - SuffixTrieNode root; - - public: - // Constructor (Builds a trie of suffies of the given text) - SuffixTrie(string txt) { - // Consider all suffixes of given string and insert - // them into the Suffix Trie using recursive function - // insertSuffix() in SuffixTrieNode class - for (int i = 0; i < txt.length(); i++) - root.insertSuffix(txt.substr(i), i); - } - - // Function to searches a pattern in this suffix trie. - void search(string pat); +private: + SuffixTrieNode root; + +public: + // Constructor (Builds a trie of suffies of the given text) + SuffixTrie(string txt) { + // Consider all suffixes of given string and insert + // them into the Suffix Trie using recursive function + // insertSuffix() in SuffixTrieNode class + for (int i = 0; i < txt.length(); i++) + root.insertSuffix(txt.substr(i), i); + } + + // Function to searches a pattern in this suffix trie. + void search(string pat); }; // A recursive function to insert a suffix of the txt in // subtree rooted with this node void SuffixTrieNode::insertSuffix(string s, int index) { - // Store index in linked list - indexes->push_back(index); + // Store index in linked list + indexes->push_back(index); - // If string has more characters - if (s.length() > 0) { - // Find the first character - char cIndex = s.at(0); + // If string has more characters + if (s.length() > 0) { + // Find the first character + char cIndex = s.at(0); - // If there is no edge for this character, add a new edge - if (children[cIndex] == NULL) - children[cIndex] = new SuffixTrieNode(); + // If there is no edge for this character, add a new edge + if (children[cIndex] == NULL) + children[cIndex] = new SuffixTrieNode(); - // Recur for next suffix - children[cIndex]->insertSuffix(s.substr(1), index + 1); - } + // Recur for next suffix + children[cIndex]->insertSuffix(s.substr(1), index + 1); + } } // A recursive function to search a pattern in subtree rooted with // this node list *SuffixTrieNode::search(string s) { - // If all characters of pattern have been processed, - if (s.length() == 0) - return indexes; - - // if there is an edge from the current node of suffix trie, - // follow the edge. - if (children[s.at(0)] != NULL) - return (children[s.at(0)])->search(s.substr(1)); - - // If there is no edge, pattern doesn’t exist in text - else - return NULL; + // If all characters of pattern have been processed, + if (s.length() == 0) + return indexes; + + // if there is an edge from the current node of suffix trie, + // follow the edge. + if (children[s.at(0)] != NULL) + return (children[s.at(0)])->search(s.substr(1)); + + // If there is no edge, pattern doesn’t exist in text + else + return NULL; } /* Prints all occurrences of pat in the Suffix Trie S (built for text)*/ void SuffixTrie::search(string pat) { - // Let us call recursive search function for root of Trie. - // We get a list of all indexes (where pat is present in text) in - // variable 'result' - list *result = root.search(pat); - - // Check if the list of indexes is empty or not - if (result == NULL) - cout << "Pattern not found" << endl; - else { - list::iterator i; - int patLen = pat.length(); - for (i = result->begin(); i != result->end(); ++i) - cout << "Pattern found at position " << *i - patLen << endl; - } + // Let us call recursive search function for root of Trie. + // We get a list of all indexes (where pat is present in text) in + // variable 'result' + list *result = root.search(pat); + + // Check if the list of indexes is empty or not + if (result == NULL) + cout << "Pattern not found" << endl; + else { + list::iterator i; + int patLen = pat.length(); + for (i = result->begin(); i != result->end(); ++i) + cout << "Pattern found at position " << *i - patLen << endl; + } } // driver program to test above functions int main() { - // Let us build a suffix trie for text "geeksforgeeks.org" - string txt = "geeksforgeeks.org"; - SuffixTrie S(txt); + // Let us build a suffix trie for text "geeksforgeeks.org" + string txt = "geeksforgeeks.org"; + SuffixTrie S(txt); - cout << "Search for 'ee'" << endl; - S.search("ee"); + cout << "Search for 'ee'" << endl; + S.search("ee"); - cout << "\nSearch for 'geek'" << endl; - S.search("geek"); + cout << "\nSearch for 'geek'" << endl; + S.search("geek"); - cout << "\nSearch for 'quiz'" << endl; - S.search("quiz"); + cout << "\nSearch for 'quiz'" << endl; + S.search("quiz"); - cout << "\nSearch for 'forgeeks'" << endl; - S.search("forgeeks"); + cout << "\nSearch for 'forgeeks'" << endl; + S.search("forgeeks"); - return 0; + return 0; } diff --git a/src/test-suite/PE-benchmarks/tug-of-war.cpp b/src/test-suite/PE-benchmarks/tug-of-war.cpp index f6fa6b40..655584ce 100644 --- a/src/test-suite/PE-benchmarks/tug-of-war.cpp +++ b/src/test-suite/PE-benchmarks/tug-of-war.cpp @@ -7,79 +7,79 @@ using namespace std; void TOWUtil(int *arr, int n, bool *curr_elements, int no_of_selected_elements, bool *soln, int *min_diff, int sum, int curr_sum, int curr_position) { - // checks whether the it is going out of bound - if (curr_position == n) - return; + // checks whether the it is going out of bound + if (curr_position == n) + return; - // checks that the numbers of elements left are not less than the - // number of elements required to form the solution - if ((n / 2 - no_of_selected_elements) > (n - curr_position)) - return; + // checks that the numbers of elements left are not less than the + // number of elements required to form the solution + if ((n / 2 - no_of_selected_elements) > (n - curr_position)) + return; - // consider the cases when current element is not included in the solution - TOWUtil(arr, n, curr_elements, no_of_selected_elements, soln, min_diff, sum, - curr_sum, curr_position + 1); + // consider the cases when current element is not included in the solution + TOWUtil(arr, n, curr_elements, no_of_selected_elements, soln, min_diff, sum, + curr_sum, curr_position + 1); - // add the current element to the solution - no_of_selected_elements++; - curr_sum = curr_sum + arr[curr_position]; - curr_elements[curr_position] = true; + // add the current element to the solution + no_of_selected_elements++; + curr_sum = curr_sum + arr[curr_position]; + curr_elements[curr_position] = true; - // checks if a solution is formed - if (no_of_selected_elements == n / 2) { - // checks if the solution formed is better than the best solution so far - if (abs(sum / 2 - curr_sum) < *min_diff) { - *min_diff = abs(sum / 2 - curr_sum); - for (int i = 0; i < n; i++) - soln[i] = curr_elements[i]; - } - } else { - // consider the cases where current element is included in the solution - TOWUtil(arr, n, curr_elements, no_of_selected_elements, soln, min_diff, - sum, curr_sum, curr_position + 1); + // checks if a solution is formed + if (no_of_selected_elements == n / 2) { + // checks if the solution formed is better than the best solution so far + if (abs(sum / 2 - curr_sum) < *min_diff) { + *min_diff = abs(sum / 2 - curr_sum); + for (int i = 0; i < n; i++) + soln[i] = curr_elements[i]; } + } else { + // consider the cases where current element is included in the solution + TOWUtil(arr, n, curr_elements, no_of_selected_elements, soln, min_diff, sum, + curr_sum, curr_position + 1); + } - // removes current element before returning to the caller of this function - curr_elements[curr_position] = false; + // removes current element before returning to the caller of this function + curr_elements[curr_position] = false; } // main function that generate an arr void tugOfWar(int *arr, int n) { - // the boolen array that contains the inclusion and exclusion of an element - // in current set. The number excluded automatically form the other set - bool *curr_elements = new bool[n]; + // the boolen array that contains the inclusion and exclusion of an element + // in current set. The number excluded automatically form the other set + bool *curr_elements = new bool[n]; - // The inclusion/exclusion array for final solution - bool *soln = new bool[n]; + // The inclusion/exclusion array for final solution + bool *soln = new bool[n]; - int min_diff = INT_MAX; + int min_diff = INT_MAX; - int sum = 0; - for (int i = 0; i < n; i++) { - sum += arr[i]; - curr_elements[i] = soln[i] = false; - } + int sum = 0; + for (int i = 0; i < n; i++) { + sum += arr[i]; + curr_elements[i] = soln[i] = false; + } - // Find the solution using recursive function TOWUtil() - TOWUtil(arr, n, curr_elements, 0, soln, &min_diff, sum, 0, 0); + // Find the solution using recursive function TOWUtil() + TOWUtil(arr, n, curr_elements, 0, soln, &min_diff, sum, 0, 0); - // Print the solution - cout << "The first subset is: "; - for (int i = 0; i < n; i++) { - if (soln[i] == true) - cout << arr[i] << " "; - } - cout << "\nThe second subset is: "; - for (int i = 0; i < n; i++) { - if (soln[i] == false) - cout << arr[i] << " "; - } + // Print the solution + cout << "The first subset is: "; + for (int i = 0; i < n; i++) { + if (soln[i] == true) + cout << arr[i] << " "; + } + cout << "\nThe second subset is: "; + for (int i = 0; i < n; i++) { + if (soln[i] == false) + cout << arr[i] << " "; + } } // Driver program to test above functions int main() { - int arr[] = {23, 45, -34, 12, 0, 98, -99, 4, 189, -1, 4}; - int n = sizeof(arr) / sizeof(arr[0]); - tugOfWar(arr, n); - return 0; + int arr[] = {23, 45, -34, 12, 0, 98, -99, 4, 189, -1, 4}; + int n = sizeof(arr) / sizeof(arr[0]); + tugOfWar(arr, n); + return 0; } diff --git a/src/test-suite/PE-benchmarks/ugly-numbers.cpp b/src/test-suite/PE-benchmarks/ugly-numbers.cpp index 8ec76706..c58cb6b0 100644 --- a/src/test-suite/PE-benchmarks/ugly-numbers.cpp +++ b/src/test-suite/PE-benchmarks/ugly-numbers.cpp @@ -5,39 +5,39 @@ /*This function divides a by greatest divisible power of b*/ int maxDivide(int a, int b) { - while (a % b == 0) - a = a / b; - return a; + while (a % b == 0) + a = a / b; + return a; } /* Function to check if a number is ugly or not */ int isUgly(int no) { - no = maxDivide(no, 2); - no = maxDivide(no, 3); - no = maxDivide(no, 5); + no = maxDivide(no, 2); + no = maxDivide(no, 3); + no = maxDivide(no, 5); - return (no == 1) ? 1 : 0; + return (no == 1) ? 1 : 0; } /* Function to get the nth ugly number*/ int getNthUglyNo(int n) { - int i = 1; - int count = 1; /* ugly number count */ + int i = 1; + int count = 1; /* ugly number count */ - /*Check for all integers untill ugly count - becomes n*/ - while (n > count) { - i++; - if (isUgly(i)) - count++; - } - return i; + /*Check for all integers untill ugly count + becomes n*/ + while (n > count) { + i++; + if (isUgly(i)) + count++; + } + return i; } /* Driver program to test above functions */ int main() { - unsigned no = getNthUglyNo(150); - printf("150th ugly no. is %d ", no); - getchar(); - return 0; + unsigned no = getNthUglyNo(150); + printf("150th ugly no. is %d ", no); + getchar(); + return 0; } diff --git a/src/test-suite/PE-benchmarks/union-find.cpp b/src/test-suite/PE-benchmarks/union-find.cpp index daa37bf6..503d3394 100644 --- a/src/test-suite/PE-benchmarks/union-find.cpp +++ b/src/test-suite/PE-benchmarks/union-find.cpp @@ -4,99 +4,99 @@ using namespace std; // a structure to represent an edge in graph class Edge { - public: - int src, dest; +public: + int src, dest; }; // a structure to represent a graph class Graph { - public: - // V-> Number of vertices, E-> Number of edges - int V, E; +public: + // V-> Number of vertices, E-> Number of edges + int V, E; - // graph is represented as an array of edges - Edge *edge; + // graph is represented as an array of edges + Edge *edge; }; // Creates a graph with V vertices and E edges Graph *createGraph(int V, int E) { - Graph *graph = new Graph(); - graph->V = V; - graph->E = E; + Graph *graph = new Graph(); + graph->V = V; + graph->E = E; - graph->edge = new Edge[graph->E * sizeof(Edge)]; + graph->edge = new Edge[graph->E * sizeof(Edge)]; - return graph; + return graph; } // A utility function to find the subset of an element i int find(int parent[], int i) { - if (parent[i] == -1) - return i; - return find(parent, parent[i]); + if (parent[i] == -1) + return i; + return find(parent, parent[i]); } // A utility function to do union of two subsets void Union(int parent[], int x, int y) { - int xset = find(parent, x); - int yset = find(parent, y); - if (xset != yset) { - parent[xset] = yset; - } + int xset = find(parent, x); + int yset = find(parent, y); + if (xset != yset) { + parent[xset] = yset; + } } // The main function to check whether a given graph contains // cycle or not int isCycle(Graph *graph) { - // Allocate memory for creating V subsets - int *parent = new int[graph->V * sizeof(int)]; + // Allocate memory for creating V subsets + int *parent = new int[graph->V * sizeof(int)]; - // Initialize all subsets as single element sets - memset(parent, -1, sizeof(int) * graph->V); + // Initialize all subsets as single element sets + memset(parent, -1, sizeof(int) * graph->V); - // Iterate through all edges of graph, find subset of both - // vertices of every edge, if both subsets are same, then - // there is cycle in graph. - for (int i = 0; i < graph->E; ++i) { - int x = find(parent, graph->edge[i].src); - int y = find(parent, graph->edge[i].dest); + // Iterate through all edges of graph, find subset of both + // vertices of every edge, if both subsets are same, then + // there is cycle in graph. + for (int i = 0; i < graph->E; ++i) { + int x = find(parent, graph->edge[i].src); + int y = find(parent, graph->edge[i].dest); - if (x == y) - return 1; + if (x == y) + return 1; - Union(parent, x, y); - } - return 0; + Union(parent, x, y); + } + return 0; } // Driver code int main() { - /* Let us create the following graph - 0 - | \ - | \ - 1-----2 */ - int V = 3, E = 3; - Graph *graph = createGraph(V, E); - - // add edge 0-1 - graph->edge[0].src = 0; - graph->edge[0].dest = 1; - - // add edge 1-2 - graph->edge[1].src = 1; - graph->edge[1].dest = 2; - - // add edge 0-2 - graph->edge[2].src = 0; - graph->edge[2].dest = 2; - - if (isCycle(graph)) - cout << "graph contains cycle"; - else - cout << "graph doesn't contain cycle"; - - return 0; + /* Let us create the following graph + 0 + | \ + | \ + 1-----2 */ + int V = 3, E = 3; + Graph *graph = createGraph(V, E); + + // add edge 0-1 + graph->edge[0].src = 0; + graph->edge[0].dest = 1; + + // add edge 1-2 + graph->edge[1].src = 1; + graph->edge[1].dest = 2; + + // add edge 0-2 + graph->edge[2].src = 0; + graph->edge[2].dest = 2; + + if (isCycle(graph)) + cout << "graph contains cycle"; + else + cout << "graph doesn't contain cycle"; + + return 0; } // This code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/vertex-cover-problem.cpp b/src/test-suite/PE-benchmarks/vertex-cover-problem.cpp index f23ce76a..de148351 100644 --- a/src/test-suite/PE-benchmarks/vertex-cover-problem.cpp +++ b/src/test-suite/PE-benchmarks/vertex-cover-problem.cpp @@ -5,73 +5,73 @@ using namespace std; // This class represents a undirected graph using adjacency list class Graph { - int V; // No. of vertices - list *adj; // Pointer to an array containing adjacency lists - public: - Graph(int V); // Constructor - void addEdge(int v, int w); // function to add an edge to graph - void printVertexCover(); // prints vertex cover + int V; // No. of vertices + list *adj; // Pointer to an array containing adjacency lists +public: + Graph(int V); // Constructor + void addEdge(int v, int w); // function to add an edge to graph + void printVertexCover(); // prints vertex cover }; Graph::Graph(int V) { - this->V = V; - adj = new list[V]; + this->V = V; + adj = new list[V]; } void Graph::addEdge(int v, int w) { - adj[v].push_back(w); // Add w to v’s list. - adj[w].push_back(v); // Since the graph is undirected + adj[v].push_back(w); // Add w to v’s list. + adj[w].push_back(v); // Since the graph is undirected } // The function to print vertex cover void Graph::printVertexCover() { - // Initialize all vertices as not visited. - bool visited[V]; - for (int i = 0; i < V; i++) - visited[i] = false; + // Initialize all vertices as not visited. + bool visited[V]; + for (int i = 0; i < V; i++) + visited[i] = false; - list::iterator i; + list::iterator i; - // Consider all edges one by one - for (int u = 0; u < V; u++) { - // An edge is only picked when both visited[u] and visited[v] - // are false - if (visited[u] == false) { - // Go through all adjacents of u and pick the first not - // yet visited vertex (We are basically picking an edge - // (u, v) from remaining edges. - for (i = adj[u].begin(); i != adj[u].end(); ++i) { - int v = *i; - if (visited[v] == false) { - // Add the vertices (u, v) to the result set. - // We make the vertex u and v visited so that - // all edges from/to them would be ignored - visited[v] = true; - visited[u] = true; - break; - } - } + // Consider all edges one by one + for (int u = 0; u < V; u++) { + // An edge is only picked when both visited[u] and visited[v] + // are false + if (visited[u] == false) { + // Go through all adjacents of u and pick the first not + // yet visited vertex (We are basically picking an edge + // (u, v) from remaining edges. + for (i = adj[u].begin(); i != adj[u].end(); ++i) { + int v = *i; + if (visited[v] == false) { + // Add the vertices (u, v) to the result set. + // We make the vertex u and v visited so that + // all edges from/to them would be ignored + visited[v] = true; + visited[u] = true; + break; } + } } + } - // Print the vertex cover - for (int i = 0; i < V; i++) - if (visited[i]) - cout << i << " "; + // Print the vertex cover + for (int i = 0; i < V; i++) + if (visited[i]) + cout << i << " "; } // Driver program to test methods of graph class int main() { - // Create a graph given in the above diagram - Graph g(7); - g.addEdge(0, 1); - g.addEdge(0, 2); - g.addEdge(1, 3); - g.addEdge(3, 4); - g.addEdge(4, 5); - g.addEdge(5, 6); + // Create a graph given in the above diagram + Graph g(7); + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 3); + g.addEdge(3, 4); + g.addEdge(4, 5); + g.addEdge(5, 6); - g.printVertexCover(); + g.printVertexCover(); - return 0; + return 0; } diff --git a/src/test-suite/PE-benchmarks/weighted-job-scheduling.cpp b/src/test-suite/PE-benchmarks/weighted-job-scheduling.cpp index 46829cd2..40e763ef 100644 --- a/src/test-suite/PE-benchmarks/weighted-job-scheduling.cpp +++ b/src/test-suite/PE-benchmarks/weighted-job-scheduling.cpp @@ -5,7 +5,7 @@ using namespace std; // A job has start time, finish time and profit. struct Job { - int start, finish, profit; + int start, finish, profit; }; // A utility function that is used for sorting events @@ -15,47 +15,47 @@ bool jobComparataor(Job s1, Job s2) { return (s1.finish < s2.finish); } // Find the latest job (in sorted array) that doesn't // conflict with the job[i] int latestNonConflict(Job arr[], int i) { - for (int j = i - 1; j >= 0; j--) { - if (arr[j].finish <= arr[i].start) - return j; - } - return -1; + for (int j = i - 1; j >= 0; j--) { + if (arr[j].finish <= arr[i].start) + return j; + } + return -1; } // The main function that returns the maximum possible // profit from given array of jobs int findMaxProfit(Job arr[], int n) { - // Sort jobs according to finish time - sort(arr, arr + n, jobComparataor); - - // Create an array to store solutions of subproblems. table[i] - // stores the profit for jobs till arr[i] (including arr[i]) - int *table = new int[n]; - table[0] = arr[0].profit; - - // Fill entries in M[] using recursive property - for (int i = 1; i < n; i++) { - // Find profit including the current job - int inclProf = arr[i].profit; - int l = latestNonConflict(arr, i); - if (l != -1) - inclProf += table[l]; - - // Store maximum of including and excluding - table[i] = max(inclProf, table[i - 1]); - } - - // Store result and free dynamic memory allocated for table[] - int result = table[n - 1]; - delete[] table; - - return result; + // Sort jobs according to finish time + sort(arr, arr + n, jobComparataor); + + // Create an array to store solutions of subproblems. table[i] + // stores the profit for jobs till arr[i] (including arr[i]) + int *table = new int[n]; + table[0] = arr[0].profit; + + // Fill entries in M[] using recursive property + for (int i = 1; i < n; i++) { + // Find profit including the current job + int inclProf = arr[i].profit; + int l = latestNonConflict(arr, i); + if (l != -1) + inclProf += table[l]; + + // Store maximum of including and excluding + table[i] = max(inclProf, table[i - 1]); + } + + // Store result and free dynamic memory allocated for table[] + int result = table[n - 1]; + delete[] table; + + return result; } // Driver program int main() { - Job arr[] = {{3, 10, 20}, {1, 2, 50}, {6, 19, 100}, {2, 100, 200}}; - int n = sizeof(arr) / sizeof(arr[0]); - cout << "The optimal profit is " << findMaxProfit(arr, n); - return 0; + Job arr[] = {{3, 10, 20}, {1, 2, 50}, {6, 19, 100}, {2, 100, 200}}; + int n = sizeof(arr) / sizeof(arr[0]); + cout << "The optimal profit is " << findMaxProfit(arr, n); + return 0; } diff --git a/src/test-suite/PE-benchmarks/word-wrap.cpp b/src/test-suite/PE-benchmarks/word-wrap.cpp index f1b97d0c..ab13ef15 100644 --- a/src/test-suite/PE-benchmarks/word-wrap.cpp +++ b/src/test-suite/PE-benchmarks/word-wrap.cpp @@ -11,84 +11,83 @@ int printSolution(int p[], int n); // "aaa bb cc ddddd". n is size of l[] and M is line width // (maximum no. of characters that can fit in a line) void solveWordWrap(int l[], int n, int M) { - // For simplicity, 1 extra space is used in all below arrays + // For simplicity, 1 extra space is used in all below arrays - // extras[i][j] will have number of extra spaces if words from i - // to j are put in a single line - int extras[n + 1][n + 1]; + // extras[i][j] will have number of extra spaces if words from i + // to j are put in a single line + int extras[n + 1][n + 1]; - // lc[i][j] will have cost of a line which has words from - // i to j - int lc[n + 1][n + 1]; + // lc[i][j] will have cost of a line which has words from + // i to j + int lc[n + 1][n + 1]; - // c[i] will have total cost of optimal arrangement of words - // from 1 to i - int c[n + 1]; + // c[i] will have total cost of optimal arrangement of words + // from 1 to i + int c[n + 1]; - // p[] is used to print the solution. - int p[n + 1]; + // p[] is used to print the solution. + int p[n + 1]; - int i, j; + int i, j; - // calculate extra spaces in a single line. The value extra[i][j] - // indicates extra spaces if words from word number i to j are - // placed in a single line - for (i = 1; i <= n; i++) { - extras[i][i] = M - l[i - 1]; - for (j = i + 1; j <= n; j++) - extras[i][j] = extras[i][j - 1] - l[j - 1] - 1; - } + // calculate extra spaces in a single line. The value extra[i][j] + // indicates extra spaces if words from word number i to j are + // placed in a single line + for (i = 1; i <= n; i++) { + extras[i][i] = M - l[i - 1]; + for (j = i + 1; j <= n; j++) + extras[i][j] = extras[i][j - 1] - l[j - 1] - 1; + } - // Calculate line cost corresponding to the above calculated extra - // spaces. The value lc[i][j] indicates cost of putting words from - // word number i to j in a single line - for (i = 1; i <= n; i++) { - for (j = i; j <= n; j++) { - if (extras[i][j] < 0) - lc[i][j] = INF; - else if (j == n && extras[i][j] >= 0) - lc[i][j] = 0; - else - lc[i][j] = extras[i][j] * extras[i][j]; - } + // Calculate line cost corresponding to the above calculated extra + // spaces. The value lc[i][j] indicates cost of putting words from + // word number i to j in a single line + for (i = 1; i <= n; i++) { + for (j = i; j <= n; j++) { + if (extras[i][j] < 0) + lc[i][j] = INF; + else if (j == n && extras[i][j] >= 0) + lc[i][j] = 0; + else + lc[i][j] = extras[i][j] * extras[i][j]; } + } - // Calculate minimum cost and find minimum cost arrangement. - // The value c[j] indicates optimized cost to arrange words - // from word number 1 to j. - c[0] = 0; - for (j = 1; j <= n; j++) { - c[j] = INF; - for (i = 1; i <= j; i++) { - if (c[i - 1] != INF && lc[i][j] != INF && - (c[i - 1] + lc[i][j] < c[j])) { - c[j] = c[i - 1] + lc[i][j]; - p[j] = i; - } - } + // Calculate minimum cost and find minimum cost arrangement. + // The value c[j] indicates optimized cost to arrange words + // from word number 1 to j. + c[0] = 0; + for (j = 1; j <= n; j++) { + c[j] = INF; + for (i = 1; i <= j; i++) { + if (c[i - 1] != INF && lc[i][j] != INF && (c[i - 1] + lc[i][j] < c[j])) { + c[j] = c[i - 1] + lc[i][j]; + p[j] = i; + } } + } - printSolution(p, n); + printSolution(p, n); } int printSolution(int p[], int n) { - int k; - if (p[n] == 1) - k = 1; - else - k = printSolution(p, p[n] - 1) + 1; - cout << "Line number " << k << ": From word no. " << p[n] << " to " << n - << endl; - return k; + int k; + if (p[n] == 1) + k = 1; + else + k = printSolution(p, p[n] - 1) + 1; + cout << "Line number " << k << ": From word no. " << p[n] << " to " << n + << endl; + return k; } // Driver program to test above functions int main() { - int l[] = {3, 2, 2, 5}; - int n = sizeof(l) / sizeof(l[0]); - int M = 6; - solveWordWrap(l, n, M); - return 0; + int l[] = {3, 2, 2, 5}; + int n = sizeof(l) / sizeof(l[0]); + int M = 6; + solveWordWrap(l, n, M); + return 0; } // This is code is contributed by rathbhupendra diff --git a/src/test-suite/PE-benchmarks/z-algorithm-linear-time.cpp b/src/test-suite/PE-benchmarks/z-algorithm-linear-time.cpp index 088e6243..52a2e6bc 100644 --- a/src/test-suite/PE-benchmarks/z-algorithm-linear-time.cpp +++ b/src/test-suite/PE-benchmarks/z-algorithm-linear-time.cpp @@ -6,76 +6,75 @@ void getZarr(string str, int Z[]); // prints all occurrences of pattern in text using Z algo void search(string text, string pattern) { - // Create concatenated string "P$T" - string concat = pattern + "$" + text; - int l = concat.length(); + // Create concatenated string "P$T" + string concat = pattern + "$" + text; + int l = concat.length(); - // Construct Z array - int Z[l]; - getZarr(concat, Z); + // Construct Z array + int Z[l]; + getZarr(concat, Z); - // now looping through Z array for matching condition - for (int i = 0; i < l; ++i) { - // if Z[i] (matched region) is equal to pattern - // length we got the pattern - if (Z[i] == pattern.length()) - cout << "Pattern found at index " << i - pattern.length() - 1 - << endl; - } + // now looping through Z array for matching condition + for (int i = 0; i < l; ++i) { + // if Z[i] (matched region) is equal to pattern + // length we got the pattern + if (Z[i] == pattern.length()) + cout << "Pattern found at index " << i - pattern.length() - 1 << endl; + } } // Fills Z array for given string str[] void getZarr(string str, int Z[]) { - int n = str.length(); - int L, R, k; + int n = str.length(); + int L, R, k; - // [L,R] make a window which matches with prefix of s - L = R = 0; - for (int i = 1; i < n; ++i) { - // if i>R nothing matches so we will calculate. - // Z[i] using naive way. - if (i > R) { - L = R = i; + // [L,R] make a window which matches with prefix of s + L = R = 0; + for (int i = 1; i < n; ++i) { + // if i>R nothing matches so we will calculate. + // Z[i] using naive way. + if (i > R) { + L = R = i; - // R-L = 0 in starting, so it will start - // checking from 0'th index. For example, - // for "ababab" and i = 1, the value of R - // remains 0 and Z[i] becomes 0. For string - // "aaaaaa" and i = 1, Z[i] and R become 5 - while (R < n && str[R - L] == str[R]) - R++; - Z[i] = R - L; - R--; - } else { - // k = i-L so k corresponds to number which - // matches in [L,R] interval. - k = i - L; + // R-L = 0 in starting, so it will start + // checking from 0'th index. For example, + // for "ababab" and i = 1, the value of R + // remains 0 and Z[i] becomes 0. For string + // "aaaaaa" and i = 1, Z[i] and R become 5 + while (R < n && str[R - L] == str[R]) + R++; + Z[i] = R - L; + R--; + } else { + // k = i-L so k corresponds to number which + // matches in [L,R] interval. + k = i - L; - // if Z[k] is less than remaining interval - // then Z[i] will be equal to Z[k]. - // For example, str = "ababab", i = 3, R = 5 - // and L = 2 - if (Z[k] < R - i + 1) - Z[i] = Z[k]; + // if Z[k] is less than remaining interval + // then Z[i] will be equal to Z[k]. + // For example, str = "ababab", i = 3, R = 5 + // and L = 2 + if (Z[k] < R - i + 1) + Z[i] = Z[k]; - // For example str = "aaaaaa" and i = 2, R is 5, - // L is 0 - else { - // else start from R and check manually - L = i; - while (R < n && str[R - L] == str[R]) - R++; - Z[i] = R - L; - R--; - } - } + // For example str = "aaaaaa" and i = 2, R is 5, + // L is 0 + else { + // else start from R and check manually + L = i; + while (R < n && str[R - L] == str[R]) + R++; + Z[i] = R - L; + R--; + } } + } } // Driver program int main() { - string text = "GEEKS FOR GEEKS"; - string pattern = "GEEK"; - search(text, pattern); - return 0; + string text = "GEEKS FOR GEEKS"; + string pattern = "GEEK"; + search(text, pattern); + return 0; } diff --git a/src/test-suite/generate_llfiles.sh b/src/test-suite/generate_llfiles.sh index 1bdcc118..8f207747 100644 --- a/src/test-suite/generate_llfiles.sh +++ b/src/test-suite/generate_llfiles.sh @@ -19,5 +19,6 @@ LLVM_BUILD="/usr" for d in ${SRC_WD}/*.cpp; do name=$(basename ${d}) && oname=${name%.*} && ${LLVM_BUILD}/bin/clang++-14 -S -emit-llvm -Xclang -disable-O0-optnone ${d} -o ${DEST_FOLDER}/${oname}.ll & + done wait diff --git a/src/test-suite/get_index_file.py b/src/test-suite/get_index_file.py index 9ec1aa0f..dc904ba5 100644 --- a/src/test-suite/get_index_file.py +++ b/src/test-suite/get_index_file.py @@ -3,16 +3,15 @@ import os import sys + def get_index_file(): - index_file = open( - "index-llvm14.files", - "w" - ) + index_file = open("index-llvm14.files", "w") for root, _, files in os.walk("./PE-benchmarks-llfiles-llvm14/"): for file in files: if file.endswith(".ll"): index_file.write(os.path.join(root, file) + "\n") index_file.close() + if __name__ == "__main__": - get_index_file() \ No newline at end of file + get_index_file() diff --git a/src/utils.cpp b/src/utils.cpp index 305fd581..2374f88b 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -28,105 +28,105 @@ float IR2Vec::WT; bool IR2Vec::debug; std::unique_ptr IR2Vec::getLLVMIR() { - SMDiagnostic err; - static LLVMContext context; - auto M = parseIRFile(iname, err, context); + SMDiagnostic err; + static LLVMContext context; + auto M = parseIRFile(iname, err, context); - if (!M) { - err.print(iname.c_str(), outs()); - exit(1); - } - return M; + if (!M) { + err.print(iname.c_str(), outs()); + exit(1); + } + return M; } void IR2Vec::collectDataFromVocab(std::map &opcMap) { - IR2VEC_DEBUG(errs() << "Reading from " + vocab + "\n"); - std::ifstream i(vocab); - std::string delimiter = ":"; - for (std::string line; getline(i, line);) { - std::string token = line.substr(0, line.find(delimiter)); - Vector rep; - std::string vec = line.substr(line.find(delimiter) + 1, line.length()); - std::string val = vec.substr(vec.find("[") + 1, vec.find(", ") - 1); - rep.push_back(stod(val)); - int pos = vec.find(", "); - vec = vec.substr(pos + 1); - for (int i = 1; i < DIM - 1; i++) { - val = vec.substr(1, vec.find(", ") - 1); - rep.push_back(stod(val)); - pos = vec.find(", "); - vec = vec.substr(pos + 1); - } - val = vec.substr(1, vec.find("]") - 1); - rep.push_back(stod(val)); - opcMap[token] = rep; + IR2VEC_DEBUG(errs() << "Reading from " + vocab + "\n"); + std::ifstream i(vocab); + std::string delimiter = ":"; + for (std::string line; getline(i, line);) { + std::string token = line.substr(0, line.find(delimiter)); + Vector rep; + std::string vec = line.substr(line.find(delimiter) + 1, line.length()); + std::string val = vec.substr(vec.find("[") + 1, vec.find(", ") - 1); + rep.push_back(stod(val)); + int pos = vec.find(", "); + vec = vec.substr(pos + 1); + for (int i = 1; i < DIM - 1; i++) { + val = vec.substr(1, vec.find(", ") - 1); + rep.push_back(stod(val)); + pos = vec.find(", "); + vec = vec.substr(pos + 1); } + val = vec.substr(1, vec.find("]") - 1); + rep.push_back(stod(val)); + opcMap[token] = rep; + } } void IR2Vec::scaleVector(Vector &vec, float factor) { - for (unsigned i = 0; i < vec.size(); i++) { - vec[i] = vec[i] * factor; - } + for (unsigned i = 0; i < vec.size(); i++) { + vec[i] = vec[i] * factor; + } } // Function to get demangled function name std::string IR2Vec::getDemagledName(const llvm::Function *function) { - auto functionName = function->getName().str(); - std::size_t sz = 17; - int status; - char *const readable_name = - __cxa_demangle(functionName.c_str(), 0, &sz, &status); - auto demangledName = - status == 0 ? std::string(readable_name) : std::string(functionName); - free(readable_name); - return demangledName; + auto functionName = function->getName().str(); + std::size_t sz = 17; + int status; + char *const readable_name = + __cxa_demangle(functionName.c_str(), 0, &sz, &status); + auto demangledName = + status == 0 ? std::string(readable_name) : std::string(functionName); + free(readable_name); + return demangledName; } // Function to get demanged instruction name std::string IR2Vec::getDemagledName(const llvm::Instruction *instruction) { - auto instructionName = instruction->getName().str(); - std::size_t sz = 17; - int status; - char *const readable_name = - __cxa_demangle(instructionName.c_str(), 0, &sz, &status); - auto demangledName = status == 0 ? std::string(readable_name) - : std::string(instructionName); - free(readable_name); - return demangledName; + auto instructionName = instruction->getName().str(); + std::size_t sz = 17; + int status; + char *const readable_name = + __cxa_demangle(instructionName.c_str(), 0, &sz, &status); + auto demangledName = + status == 0 ? std::string(readable_name) : std::string(instructionName); + free(readable_name); + return demangledName; } // Function to get actual function name char *IR2Vec::getActualName(llvm::Function *function) { - auto functionName = function->getName().str(); - auto demangledName = getDemagledName(function); - size_t Size = 1; - char *Buf = static_cast(std::malloc(Size)); - const char *mangled = functionName.c_str(); - char *baseName; - llvm::ItaniumPartialDemangler Mangler; - if (Mangler.partialDemangle(mangled)) { - baseName = &demangledName[0]; - } else { - baseName = Mangler.getFunctionBaseName(Buf, &Size); - } - return baseName; + auto functionName = function->getName().str(); + auto demangledName = getDemagledName(function); + size_t Size = 1; + char *Buf = static_cast(std::malloc(Size)); + const char *mangled = functionName.c_str(); + char *baseName; + llvm::ItaniumPartialDemangler Mangler; + if (Mangler.partialDemangle(mangled)) { + baseName = &demangledName[0]; + } else { + baseName = Mangler.getFunctionBaseName(Buf, &Size); + } + return baseName; } // Function to return updated res std::string IR2Vec::updatedRes(IR2Vec::Vector tmp, llvm::Function *f, llvm::Module *M) { - std::string res = ""; - auto demangledName = getDemagledName(f); + std::string res = ""; + auto demangledName = getDemagledName(f); - res += M->getSourceFileName() + "__" + demangledName + "\t"; + res += M->getSourceFileName() + "__" + demangledName + "\t"; - res += "=\t"; - for (auto i : tmp) { - if ((i <= 0.0001 && i > 0) || (i < 0 && i >= -0.0001)) { - i = 0; - } - res += std::to_string(i) + "\t"; + res += "=\t"; + for (auto i : tmp) { + if ((i <= 0.0001 && i > 0) || (i < 0 && i >= -0.0001)) { + i = 0; } + res += std::to_string(i) + "\t"; + } - return res; + return res; }