├── .gitattributes ├── .vs └── Fun Practice 2 │ └── v14 │ └── .suo ├── 10_Consecutive.cpp ├── 11_FormattedDivision.cpp ├── 12_PermutationStep.cpp ├── 13_DashInsertII.cpp ├── 14_SwapII.cpp ├── 15_NumberSearch.cpp ├── 16_TripleDouble.cpp ├── 17_BracketMatcher.cpp ├── 18_CeasarCipher.cpp ├── 19_StringReduction.cpp ├── 1_PrimeTime.cpp ├── 20_ThreeFiveMultiples.cpp ├── 21_CoinDeterminer.cpp ├── 22_MostFreeTime.cpp ├── 23_DistinctList.cpp ├── 24_FibonacciChecker.cpp ├── 25_OverlappingRectangles.cpp ├── 26_NumberEncoding.cpp ├── 27_PrimeChecker.cpp ├── 28_LookSaySequence.cpp ├── 29_StockPicker.cpp ├── 2_RunLength.cpp ├── 30_MultipleBrackets.cpp ├── 31_MaxSubarray.cpp ├── 32_MissingDigit.cpp ├── 33_KUniqueCharacters.cpp ├── 34_BtimapHoles.cpp ├── 35_MatchingCharacters.cpp ├── 36_NearestSmallerValues.cpp ├── 37_ArrayMinJumps.cpp ├── 38_PalindromicSubstring.cpp ├── 39_WordSplit.cpp ├── 3_PrimeMover.cpp ├── 40_MinWindowSubstring.cpp ├── 41_TrappingWater.cpp ├── 42_SeatingStudents.cpp ├── 43_PairSearching.cpp ├── 44_HTMLElements.cpp ├── 45_MatrixSpiral.cpp ├── 46_BoggleSolver.cpp ├── 47_MatrixPath.cpp ├── 48_FormattedNumber.cpp ├── 49_MissingDigitII.cpp ├── 4_PalindromeTwo.cpp ├── 50_LongestConsecutive.cpp ├── 51_SimplePassword.cpp ├── 52_CharacterRemoval.cpp ├── 53_ThreePoints.cpp ├── 54_StringExpression.cpp ├── 55_PreorderTraversal.cpp ├── 56_SymmetricTree.cpp ├── 57_BinarySearchTreeLCA.cpp ├── 58_TreeConstructor.cpp ├── 59_HistogramArea.cpp ├── 5_Division.cpp ├── 60_StringZigzag.cpp ├── 61_PlusMinus.cpp ├── 62_CharlieTheDog.cpp ├── 63_EightQueens.cpp ├── 6_StringScramble.cpp ├── 7_ArithGeoII.cpp ├── 8_BinaryConverter.cpp ├── 9_SimpleMode.cpp ├── Debug ├── Fun Practice 2.exe ├── Fun Practice 2.log ├── Fun Practice 2.tlog │ ├── CL.read.1.tlog │ ├── CL.write.1.tlog │ ├── Fun Practice 2.lastbuildstate │ ├── cl.command.1.tlog │ ├── link.command.1.tlog │ ├── link.read.1.tlog │ └── link.write.1.tlog └── vc120.idb ├── Fun Practice 2.sln ├── Fun Practice 2.vcxproj ├── Fun Practice 2.vcxproj.filters ├── README.md ├── extra_ChromosomeMatch.cpp ├── extra_ShortestPathFile.cpp └── graphInput.txt /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.vs/Fun Practice 2/v14/.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gutty333/Medium-Programming-Challenges/d4391b338607a1a08b5fc29799738ae063f95d62/.vs/Fun Practice 2/v14/.suo -------------------------------------------------------------------------------- /10_Consecutive.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine how to order an array of numbers consecutively. 2 | // have the function Consecutive(arr) take the array of integers stored in arr and return the minimum number of integers needed to make the contents of arr consecutive from the lowest number to the highest number. For example: If arr contains [4, 8, 6] then the output should be 2 because two numbers need to be added to the array (5 and 7) to make it a consecutive array of numbers from 4 to 8. Negative numbers may be entered as parameters and no array will have less than 2 elements. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | // Function for sorting the array 9 | void bubbleSort(int arr[], int size) 10 | { 11 | int temp; 12 | bool swap; 13 | 14 | do 15 | { 16 | swap = false; 17 | 18 | for (int x = 0; x < size - 1; x++) 19 | { 20 | if (arr[x] > arr[x + 1]) 21 | { 22 | temp = arr[x]; 23 | arr[x] = arr[x + 1]; 24 | arr[x + 1] = temp; 25 | swap = true; 26 | } 27 | } 28 | } while (swap); 29 | } 30 | 31 | int Consecutive(int arr[], int size) { 32 | 33 | int difference; 34 | int total = 0; 35 | 36 | // Sort the array in ascending order 37 | bubbleSort(arr, size); 38 | 39 | // Step through the array and analyze the difference between each value 40 | // Since it is in order we just compare the values next to each other and find the gap 41 | for (int x = 0; x < size-1; x++) 42 | { 43 | difference = arr[x + 1] - arr[x]; 44 | total += (difference - 1); 45 | } 46 | 47 | return total; 48 | } 49 | 50 | int main() { 51 | 52 | // keep this function call here 53 | /* Note: In C++ you first have to initialize an array and set 54 | it equal to the stdin to test your code with arrays. */ 55 | 56 | int A[] = { 5, 10, 15 }; 57 | int B[] = { -2, 10, 4 }; 58 | int C[] = {4,8,6}; 59 | cout << Consecutive(A, sizeof(A) / sizeof(A[0])) << endl; // 8 60 | cout << Consecutive(B, sizeof(B) / sizeof(B[0])) << endl; // 10 61 | cout << Consecutive(C, sizeof(C) / sizeof(C[0])) << endl; // 2 62 | return 0; 63 | 64 | } -------------------------------------------------------------------------------- /11_FormattedDivision.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will divide two numbers and print them in a certain format. 2 | // have the function FormattedDivision(num1,num2) take both parameters being passed, divide num1 by num2, and return the result as a string with properly formatted commas and 4 significant digits after the decimal place. For example: if num1 is 123456789 and num2 is 10000 the output should be "12,345.6789". The output must contain a number in the one's place even if it is a zero. 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | string FormattedDivision(int num1, int num2) { 12 | 13 | double result = double(num1) / num2; 14 | 15 | // Convert the double to a string with proper output manipulation 16 | stringstream convert; 17 | convert << fixed << setprecision(4) << result; 18 | string num = convert.str(); 19 | string temp; 20 | 21 | // Check if the number needs to be formatted with commas 22 | // if the whole number is in the hundreds no need to format with commas 23 | // else if it is in the thousands or above format with a commas 24 | for (int x = 0; x < num.length(); x++) 25 | { 26 | if (num[x] == '.' && x < 3) // If number was in the hundreds or lower just copy original 27 | { 28 | temp = num; 29 | break; 30 | } 31 | else if (num[x] == '.' && x > 3) // Format with commas 32 | { 33 | int count = 0; 34 | for (int y = x-1; y >= 0; y--) 35 | { 36 | // Checking to see the placement of every hundreds 37 | // This determines when the comma will be added 38 | if (count == 3) 39 | { 40 | temp.push_back(','); 41 | temp.push_back(num[y]); 42 | count = 0; 43 | } 44 | else 45 | { 46 | temp.push_back(num[y]); 47 | } 48 | count++; 49 | } 50 | 51 | // Reversing the string back, since we were working from the period to the front 52 | // Also add the period 53 | reverse(temp.begin(), temp.end()); 54 | temp.push_back(num[x]); 55 | } 56 | else if (temp.length() > 0) 57 | { 58 | // Once the commas are formatted keep traversing the parent loop 59 | // Just inserting the remaining numbers after the period 60 | temp.push_back(num[x]); 61 | } 62 | } 63 | 64 | return temp; 65 | } 66 | 67 | int main() { 68 | 69 | // keep this function call here 70 | cout << FormattedDivision(2,3) << endl; // 0.6667 71 | cout << FormattedDivision(10, 10) << endl; // 1.0000 72 | cout << FormattedDivision(123456789, 10000) << endl; // 12,345.6789 73 | cout << FormattedDivision(123456789, 1) << endl; // 123,456,789.0000 74 | cout << FormattedDivision(23456789, 1) << endl; // 23,456,789.0000 75 | return 0; 76 | 77 | } -------------------------------------------------------------------------------- /12_PermutationStep.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine the next greatest number using the same numbers of a given argument. 2 | // have the function PermutationStep(num) take the num parameter being passed and return the next number greater than num using the same digits. For example: if num is 123 return 132, if it's 12453 return 12534. If a number has no greater permutations, return -1 (ie. 999). 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | int PermutationStep(int num) { 10 | // Converting to a string 11 | // This will allow us to do some editing 12 | string temp; 13 | stringstream convert; 14 | convert << num; 15 | temp = convert.str(); 16 | 17 | // Checking to see if it has no greater permutations 18 | bool same; 19 | // Here we are analyzing the length 20 | // Example if num is 43333 = -1, 33 = -1, 9 = -1, etc 21 | if (temp.length() <= 2) 22 | { 23 | if (temp[0] == temp[1]) 24 | { 25 | return -1; 26 | } 27 | same = false; 28 | } 29 | else 30 | { 31 | same = true; 32 | } 33 | for (int x = 1; x < temp.length() - 1 && same; x++) 34 | { 35 | same = false; 36 | if (temp[x] == temp[x + 1]) 37 | { 38 | same = true; 39 | } 40 | } 41 | if (same || temp.length() == 1) 42 | { 43 | return -1; 44 | } 45 | 46 | char value; 47 | for (int y = temp.length() - 1; y > 0; y--) 48 | { 49 | // Break point to check for the next greatest whole 50 | // Example if number is 1007560 it will now be 1007650 51 | // Will traverse from the back of the string 52 | if (temp[y] > temp[y - 1]) 53 | { 54 | value = temp[y]; 55 | temp[y] = temp[y - 1]; 56 | temp[y - 1] = value; 57 | 58 | // Next will we optimize the number since, we want the second greatest 59 | // Example is we now have 1007650 we need to optimize to 1007605 60 | bool less; 61 | do 62 | { 63 | less = false; 64 | // Loop to check if numbers need to be shifted 65 | // If changes occurred we will analyze the number again to safeguard any errors 66 | // We are only checking until the range from which we made the initial change 67 | // Meaning we are only from analyzing 50 here, since 6 was are initial change 68 | for (int z = temp.length() - 1; z > y; z--) 69 | { 70 | if (temp[z] < temp[z - 1]) 71 | { 72 | value = temp[z]; 73 | temp[z] = temp[z - 1]; 74 | temp[z - 1] = value; 75 | less = true; 76 | } 77 | } 78 | } while (less); 79 | 80 | // Convert to an integer for output 81 | istringstream(temp) >> num; 82 | return num; 83 | } 84 | } 85 | } 86 | 87 | int main() { 88 | 89 | // keep this function call here 90 | cout << PermutationStep(11121) << endl; // 11211 91 | cout << PermutationStep(41352) << endl; // 41523 92 | cout << PermutationStep(123) << endl; // 132 93 | cout << PermutationStep(12453) << endl; // 12534 94 | cout << PermutationStep(999) << endl; // -1 95 | cout << PermutationStep(754912) << endl; // 754921 96 | cout << PermutationStep(1112113421) << endl; // 1112114321 -> 1112114123 97 | cout << PermutationStep(76666666) << endl; // -1 98 | cout << PermutationStep(12) << endl; // 21 99 | return 0; 100 | } -------------------------------------------------------------------------------- /13_DashInsertII.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be manipulating a string using dashes (-). 2 | // have the function DashInsertII(str) insert dashes ('-') between each two odd numbers and insert asterisks ('*') between each two even numbers in str. For example: if str is 4546793 the output should be 454*67-9-3. Don't count zero as an odd or even number. 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | string DashInsertII(int num) { 10 | // Converting the integer number into a string type 11 | stringstream convert; 12 | convert << num; 13 | string temp = convert.str(); 14 | string temp2; 15 | 16 | for (int x = 0; x < temp.length()-1; x++) 17 | { 18 | // Ignoring the zero 19 | if (temp[x] == '0' || temp[x+1] == '0') 20 | { 21 | temp2.push_back(temp[x]); 22 | continue; 23 | } 24 | else if (temp[x] % 2 == 0 && temp[x + 1] % 2 == 0) // Checking for even numbers 25 | { 26 | temp2.push_back(temp[x]); 27 | temp2.push_back('*'); 28 | } 29 | else if (temp[x] % 2 != 0 && temp[x + 1] % 2 != 0) // Checking for odd numbers 30 | { 31 | temp2.push_back(temp[x]); 32 | temp2.push_back('-'); 33 | } 34 | else 35 | { 36 | temp2.push_back(temp[x]); 37 | } 38 | } 39 | temp2.push_back(temp[temp.length() - 1]); 40 | return temp2; 41 | } 42 | 43 | int main() { 44 | 45 | // keep this function call here 46 | cout << DashInsertII(99946) << endl; // 9-9-94*6 47 | cout << DashInsertII(56647304) << endl; // 56*6*47-304 48 | cout << DashInsertII(4546793) << endl; // 454*67-9-3 49 | cout << DashInsertII(1562) << endl; // 1-56*2 50 | cout << DashInsertII(77993) << endl; // 7-7-9-9-3 51 | return 0; 52 | } -------------------------------------------------------------------------------- /14_SwapII.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be manipulating numbers in a string based on the characters. 2 | // have the function SwapII(str) take the str parameter and swap the case of each character. Then, if a letter is between two numbers (without separation), switch the places of the two numbers. For example: if str is "6Hello4 -8World, 7 yes3" the output should be 4hELLO6 -8wORLD, 7 YES3. 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | string SwapII(string str) { 10 | 11 | char temp;; 12 | 13 | for (int x = 0; x < str.length(); x++) 14 | { 15 | // Checking the cases of the letters 16 | if (isupper(str[x])) 17 | { 18 | str[x] = tolower(str[x]); 19 | } 20 | else if (islower(str[x])) 21 | { 22 | str[x] = toupper(str[x]); 23 | } 24 | // Checking for when the string has a number 25 | if (str[x] >= '0' && str[x] <= '9') 26 | { 27 | temp = str[x]; 28 | bool pattern = true; 29 | // Store the first number and continue to traverse the string to see if it follows the rules 30 | for (int y = x+1; y < str.length() && pattern; y++) 31 | { 32 | pattern = false; 33 | // If the number stored is at the end of the string end the loop 34 | if (y > str.length()) 35 | { 36 | break; 37 | } 38 | else if (str[y] == ' ') // If it reaches the end of the word/separation 39 | { 40 | break; 41 | } 42 | else if ((str[y] >= 'a' && str[y] <= 'z') || (str[y] >= 'A' && str[y] <= 'Z')) 43 | { 44 | // Continue iterating if you keep coming across letters 45 | pattern = true; 46 | } 47 | else if (str[y] >= '0' && str[y] <= '9' && (str[y-1] >= 'a' && str[y-1] <= 'z') || (str[y-1] >= 'A' && str[y-1] <= 'Z')) 48 | { 49 | // Analyze once another number has been found 50 | // Also check that prior to this number there is a letter 51 | str[x] = str[y]; 52 | str[y] = temp; 53 | break; 54 | } 55 | } 56 | } 57 | } 58 | return str; 59 | } 60 | 61 | int main() { 62 | 63 | // keep this function call here 64 | cout << SwapII("Hello -5LOL6") << endl; // hELLO -6lol5 65 | cout << SwapII("2S 6 du5d4e") << endl; // 2s 6 DU4D5E 66 | cout << SwapII("6Hello4 -8World, 7 yes3") << endl; // 4hELLO6 -8wORLD, 7 YES3 67 | return 0; 68 | 69 | } 70 | 71 | -------------------------------------------------------------------------------- /15_NumberSearch.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will traverse a string searching for all the numbers and then you will add them up 2 | // have the function NumberSearch(str) take the str parameter, search for all the numbers in the string, add them together, then return that final number divided by the total amount of letters in the string. For example: if str is "Hello6 9World 2, Nic8e D7ay!" the output should be 2. First if you add up all the numbers, 6 + 9 + 2 + 8 + 7 you get 32. Then there are 17 letters in the string. 32 / 17 = 1.882, and the final answer should be rounded to the nearest whole number, so the answer is 2. Only single digit numbers separated by spaces will be used throughout the whole string (So this won't ever be the case: hello44444 world). Each string will also have at least one letter. 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | int NumberSearch(string str) { 10 | 11 | int totalNum = 0; 12 | int totalLetters = 0; 13 | 14 | for (int x = 0; x < str.length(); x++) 15 | { 16 | if ((str[x] >= 'a' && str[x] <= 'z') || (str[x] >= 'A' && str[x] <= 'Z')) 17 | { 18 | totalLetters++; 19 | } 20 | else if (str[x] >= '0' && str[x] <= '9') 21 | { 22 | totalNum += int(str[x]) - 48; 23 | } 24 | } 25 | 26 | int total = round(double(totalNum) / totalLetters); 27 | return total; 28 | } 29 | 30 | int main() { 31 | 32 | // keep this function call here 33 | cout << NumberSearch("H3ello9-9") << endl; // 4 34 | cout << NumberSearch("One Number*1*") << endl; // 0 35 | cout << NumberSearch("Hello6 9World 2, Nic8e D7ay!") << endl; // 2 36 | return 0; 37 | 38 | } -------------------------------------------------------------------------------- /16_TripleDouble.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine if there is a number that appears consecutively in both arguments. 2 | // have the function TripleDouble(num1,num2) take both parameters being passed, and return 1 if there is a straight triple of a number at any place in num1 and also a straight double of the same number in num2. For example: if num1 equals 451999277 and num2 equals 41177722899, then return 1 because in the first parameter you have the straight triple 999 and you have a straight double, 99, of the same number in the second parameter. If this isn't the case, return 0. 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | int TripleDouble(int num1, long long num2) { 10 | 11 | stringstream convert; 12 | convert << num1; 13 | string temp1 = convert.str(); 14 | int count; 15 | int value = -1; 16 | 17 | for (int x = 0; x < temp1.length(); x++) 18 | { 19 | // Find the triple value from the first argument 20 | count = 1; 21 | for (int y = 0; y < temp1.length() - 1; y++) 22 | { 23 | if (temp1[x] == temp1[y] && temp1[y] == temp1[y+1]) 24 | { 25 | count++; 26 | } 27 | if (count == 3) 28 | { 29 | value = int(temp1[x]); 30 | break; 31 | } 32 | } 33 | if (value != -1) 34 | { 35 | break; 36 | } 37 | } 38 | // Checking for the double in the second argument 39 | stringstream convert2; 40 | convert2 << num2; 41 | string temp2 = convert2.str(); 42 | for (int z = 0; z < temp2.length()-1; z++) 43 | { 44 | if (char(value) == temp2[z] && temp2[z] == temp2[z + 1]) 45 | { 46 | return 1; 47 | } 48 | } 49 | return 0; 50 | } 51 | 52 | int main() { 53 | 54 | // keep this function call here 55 | cout << TripleDouble(465555,5579) << endl; // 1 56 | cout << TripleDouble(67844, 66237) << endl; // 0 57 | cout << TripleDouble(451999277,41177722899) << endl; // 1 58 | cout << TripleDouble(556668, 556886) << endl; // 0 59 | cout << TripleDouble(333,33) << endl; // 1 60 | cout << TripleDouble(555666, 5589) << endl; // 1 61 | cout << TripleDouble(3776777,87766) << endl; // 1 62 | return 0; 63 | 64 | } -------------------------------------------------------------------------------- /17_BracketMatcher.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine if the brackets in a string are correctly matched up. 2 | // have the function BracketMatcher(str) take the str parameter being passed and return 1 if the brackets are correctly matched and each one is accounted for. Otherwise return 0. For example: if str is "(hello (world))", then the output should be 1, but if str is "((hello (world))" the the output should be 0 because the brackets do not correctly match up. Only "(" and ")" will be used as brackets. If str contains no brackets return 1. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | int BracketMatcher(string str) { 9 | 10 | int count = 0; // Used to keep count of opening brackets 11 | 12 | for (int x = 0; x < str.length(); x++) 13 | { 14 | if (str[x] == '(') // Keep track of opening brackets 15 | { 16 | count++; 17 | } 18 | // If we find a closing bracket signify a match by decreasing the count 19 | // The important rule is that for a closing tag to exist an opening tag must be found first 20 | // If the rule is broken output 0 21 | else if (str[x] == ')') 22 | { 23 | count--; 24 | if (count < 0) 25 | { 26 | return 0; 27 | } 28 | } 29 | } 30 | 31 | // Condition to assure that all the tags were closed 32 | if (count == 0) 33 | { 34 | return 1; 35 | } 36 | else 37 | { 38 | return 0; 39 | } 40 | } 41 | 42 | int main() { 43 | 44 | // keep this function call here 45 | cout << BracketMatcher("(hello (world))") << endl; // 1 46 | cout << BracketMatcher("((hello (world))") << endl; // 0 47 | cout << BracketMatcher("( and )") << endl; // 1 48 | cout << BracketMatcher("(coder)(byte))") << endl; // 0 49 | cout << BracketMatcher("(c(oder)) b(yte)") << endl; // 1 50 | cout << BracketMatcher("(hi there (wow nice) this is (crazy wild))") << endl; // 1 51 | cout << BracketMatcher("(the force(is strong)") << endl; // 0 52 | cout << BracketMatcher("(soo easy even a (caveman (can do this stuff)) now this is radical (yeah rock on) sweet )") << endl; // 1 ((())()) 53 | cout << BracketMatcher("Jo()(in) the (dark side)") << endl; // 1 54 | cout << BracketMatcher("Join) the (dark side)") << endl; // 0 55 | return 0; 56 | 57 | } -------------------------------------------------------------------------------- /18_CeasarCipher.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will transform a string using the Caesar Cipher. 2 | // have the function CaesarCipher(str,num) take the str parameter and perform a Caesar Cipher shift on it using the num parameter as the shifting number. A Caesar Cipher works by shifting each letter in the string N places down in the alphabet (in this case N will be num). Punctuation, spaces, and capitalization should remain intact. For example if the string is "Caesar Cipher" and num is 2 the output should be "Ecguct Ekrjgt". 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | string CaesarCipher(string str, int num) { 10 | 11 | for (int x = 0; x < str.length(); x++) 12 | { 13 | // Ignore punctuation, spaces, etc 14 | if ((int(str[x]) >= 32 && int(str[x]) <= 64) || (int(str[x]) >= 91 && int(str[x]) <= 96)) 15 | { 16 | continue; 17 | } 18 | // Make the shift if it is a letter 19 | else if ((str[x] >= 'a' && str[x] <= 'z') || (str[x] >= 'A' && str[x] <= 'Z')) 20 | { 21 | // Make sure that after the shift the new character is a letter 22 | if ((int(str[x]) + num >= 91 && int(str[x]) + num <= 96) || (int(str[x]) + num >= 123)) 23 | { 24 | int number; 25 | // Determine whether the letter is upper case or lower case 26 | if (islower(str[x])) 27 | { 28 | number = (int(str[x]) + num) - 122; 29 | str[x] = char(number + 96); 30 | } 31 | else if (isupper(str[x])) 32 | { 33 | number = (int(str[x]) + num) - 90; 34 | str[x] = char(number + 64); 35 | } 36 | } 37 | else 38 | { 39 | str[x] = char(num + int(str[x])); 40 | } 41 | } 42 | } 43 | return str; 44 | } 45 | 46 | int main() { 47 | 48 | // keep this function call here 49 | cout << CaesarCipher("Hello",4) << endl; // Lipps 50 | cout << CaesarCipher("abc",0) << endl; // abc 51 | cout << CaesarCipher("Caesar Cipher",2) << endl; // Ecguct Ekrjgt 52 | cout << CaesarCipher("dogs", 8) << endl; 53 | cout << CaesarCipher("byte", 13) << endl; 54 | return 0; 55 | 56 | } -------------------------------------------------------------------------------- /19_StringReduction.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will manipulate a string of characters using a simple reduction method. 2 | // have the function StringReduction(str) take the str parameter being passed and return the smallest number you can get through the following reduction method. The method is: Only the letters a, b, and c will be given in str and you must take two different adjacent characters and replace it with the third. For example "ac" can be replaced with "b" but "aa" cannot be replaced with anything. This method is done repeatedly until the string cannot be further reduced, and the length of the resulting string is to be outputted. For example: if str is "cab", "ca" can be reduced to "b" and you get "bb" (you can also reduce it to "cc"). The reduction is done so the output should be 2. If str is "bcab", "bc" reduces to "a", so you have "aab", then "ab" reduces to "c", and the final string "ac" is reduced to "b" so the output should be 1. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | // Function to reduce the string 9 | string reduce(string word, int index, char letter) 10 | { 11 | word[index] = letter; 12 | word.erase(word.begin()+(index + 1)); 13 | return word; 14 | } 15 | 16 | int StringReduction(string str) { 17 | bool swap; 18 | int index = 0; 19 | 20 | do 21 | { 22 | while (index < str.length() - 1) 23 | { 24 | swap = false; 25 | 26 | // Checking if the characters are adjacent 27 | if (str[index] == str[index + 1]) 28 | { 29 | index++; 30 | } 31 | else 32 | { 33 | // If Adjacent replace it with the third character 34 | if (str[index] == 'a') 35 | { 36 | if (str[index + 1] == 'b') 37 | { 38 | str = reduce(str, index, 'c'); 39 | index = index + 1; 40 | } 41 | else if (str[index + 1] == 'c') 42 | { 43 | str = reduce(str, index, 'b'); 44 | index = index + 1; 45 | } 46 | swap = true; 47 | } 48 | else if (str[index] == 'b') 49 | { 50 | if (str[index + 1] == 'a') 51 | { 52 | str = reduce(str, index, 'c'); 53 | index = index + 1; 54 | } 55 | else if (str[index + 1] == 'c') 56 | { 57 | str = reduce(str, index, 'a'); 58 | index = index + 1; 59 | } 60 | swap = true; 61 | } 62 | else if (str[index] == 'c') 63 | { 64 | if (str[index + 1] == 'a') 65 | { 66 | str = reduce(str, index, 'b'); 67 | index = index + 1; 68 | } 69 | else if (str[index + 1] == 'b') 70 | { 71 | str = reduce(str, index, 'a'); 72 | index = index + 1; 73 | } 74 | swap = true; 75 | } 76 | } 77 | } 78 | // Safeguard that if the string is reduced to 1 character end the loop 79 | if (str.length() == 1) 80 | { 81 | swap = false; 82 | } 83 | // Reset the index back, to traverse the new edited string 84 | index = 0; 85 | } while (swap); 86 | 87 | return str.length(); 88 | } 89 | 90 | int main() { 91 | 92 | // keep this function call here 93 | cout << StringReduction("abcabc") << endl; // 2 94 | cout << StringReduction("cccc") << endl; // 4 95 | cout << StringReduction("cab") << endl; // 2 96 | cout << StringReduction("bcab") << endl; // 1 97 | return 0; 98 | 99 | } -------------------------------------------------------------------------------- /1_PrimeTime.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be determining if an argument is a prime number. 2 | // have the function PrimeTime(num) take the num parameter being passed and return the string true if the parameter is a prime number, otherwise return the string false. The range will be between 1 and 2^16. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | string PrimeTime(int num) { 9 | 10 | for (int x = 2; x <= 10; x++) 11 | { 12 | if (x == num) 13 | { 14 | continue; 15 | } 16 | else if (num%x == 0) 17 | { 18 | return "false"; 19 | } 20 | } 21 | 22 | return "true"; 23 | } 24 | 25 | int main() { 26 | 27 | // keep this function call here 28 | cout << PrimeTime(19) << endl; // true 29 | cout << PrimeTime(110) << endl; // false 30 | cout << PrimeTime(2) << endl; // true 31 | cout << PrimeTime(4) << endl; // false 32 | cout << PrimeTime(5) << endl; // true 33 | cout << PrimeTime(432) << endl; // false 34 | cout << PrimeTime(784546) << endl; // false 35 | return 0; 36 | 37 | } 38 | -------------------------------------------------------------------------------- /20_ThreeFiveMultiples.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be determining the multiples of a specific number. 2 | // have the function ThreeFiveMultiples(num) return the sum of all the multiples of 3 and 5 that are below num. For example: if num is 10, the multiples of 3 and 5 that are below 10 are 3, 5, 6, and 9, and adding them up you get 23, so your program should return 23. The integer being passed will be between 1 and 100. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | int ThreeFiveMultiples(int num) { 9 | int total = 0; 10 | // Find multiples of both 3 and 5 11 | // Iterate all number less than num 12 | // Calculate the ones that are multiples 13 | for (int x = 1; x < num; x++) 14 | { 15 | if (x % 3 == 0 || x % 5 == 0) 16 | { 17 | total += x; 18 | } 19 | } 20 | 21 | return total; 22 | } 23 | 24 | int main() { 25 | 26 | // keep this function call here 27 | cout << ThreeFiveMultiples(6) << endl; // 8 28 | cout << ThreeFiveMultiples(1) << endl; // 0 29 | cout << ThreeFiveMultiples(10) << endl; // 23 30 | cout << ThreeFiveMultiples(31) << endl; 31 | cout << ThreeFiveMultiples(17) << endl; 32 | return 0; 33 | 34 | } -------------------------------------------------------------------------------- /21_CoinDeterminer.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be determining the smallest combination of coins for a given output 2 | // have the function CoinDeterminer(num) take the input, which will be an integer ranging from 1 to 250, and return an integer output that will specify the least number of coins, that when added, equal the input integer. Coins are based on a system as follows: there are coins representing the integers 1, 5, 7, 9, and 11. So for example: if num is 16, then the output should be 2 because you can achieve the number 16 with the coins 9 and 7. If num is 25, then the output should be 3 because you can achieve 25 with either 11, 9, and 5 coins or with 9, 9, and 7 coins. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | const int coins[] = { 1, 5, 7, 9, 11 }; // Constant int array representing the list of coin values 9 | int CoinDeterminer(int num) { 10 | int index; 11 | // Check if num is one of the coin values 12 | for (int x = 0; x < 5; x++) 13 | { 14 | if (num == coins[x]) 15 | { 16 | return 1; 17 | } 18 | } 19 | 20 | int total = 0; 21 | int temp = num; 22 | int count = 0; 23 | while (total != num) 24 | { 25 | // Analyzing the range of the coin value based on the difference 26 | // Example if number is 200, is best to use high coin value such as 11 27 | // On the other hand if number is 8 is best to start at 7. 28 | if (temp <= 4) 29 | { 30 | index = 0; 31 | } 32 | else if (temp <= 6) 33 | { 34 | index = 1; 35 | } 36 | else if (temp <= 12) 37 | { 38 | index = 2; 39 | } 40 | else if (temp <= 16) 41 | { 42 | index = 3; 43 | } 44 | else 45 | { 46 | index = 4; 47 | } 48 | 49 | // Begin adding up the combinations 50 | // It will start with the closet highest number to the target 51 | // From there it will either stay the same or decrease 52 | count++; 53 | total += coins[index]; 54 | temp = num - total; 55 | 56 | // Check if the difference is one of the coin values 57 | for (int y = 0; y < 5; y++) 58 | { 59 | if (temp == coins[y]) 60 | { 61 | return count + 1; 62 | } 63 | } 64 | } 65 | } 66 | 67 | int main() { 68 | 69 | // keep this function call here 70 | cout << CoinDeterminer(6) << endl; // 2 71 | cout << CoinDeterminer(16) << endl; // 2 72 | cout << CoinDeterminer(25) << endl; // 3 73 | cout << CoinDeterminer(26) << endl; // 4 74 | cout << CoinDeterminer(5) << endl; // 1 75 | cout << CoinDeterminer(40) << endl; // 4 76 | cout << CoinDeterminer(4) << endl; // 4 77 | cout << CoinDeterminer(14) << endl; // 2 78 | return 0; 79 | 80 | } -------------------------------------------------------------------------------- /22_MostFreeTime.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine what period of the day gives the most free time. 2 | // have the function MostFreeTime(strArr) read the strArr parameter being passed which will represent a full day and will be filled with events that span from time X to time Y in the day. The format of each event will be hh:mmAM/PM-hh:mmAM/PM. For example, strArr may be ["10:00AM-12:30PM","02:00PM-02:45PM","09:10AM-09:50AM"]. Your program will have to output the longest amount of free time available between the start of your current event and the end of your last event in the format: hh:mm. The start event should be the earliest event in the day and the latest event should be the latest event in the day. The output for the previous input would therefore be 01:30 (with the earliest event in the day starting at 09:10AM and the latest event ending at 02:45PM). The input will contain at least 3 events and the events may be out of order. 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | // Function used to determine the time difference between the events 11 | double timeDifference(string currentEvent, string nextEvent, string time1, string time2) 12 | { 13 | double currentTime, nextTime; 14 | currentEvent[2] = nextEvent[2] = '.'; 15 | istringstream(currentEvent) >> currentTime; 16 | istringstream(nextEvent) >> nextTime; 17 | 18 | if (currentEvent.substr(currentEvent.length() - 2) != "00" && nextEvent.substr(nextEvent.length() - 2) == "00") 19 | { 20 | nextTime += 0.60; 21 | nextTime -= 1; 22 | } 23 | 24 | // Conditions to calculate the difference 25 | if (time1 == time2 && (currentEvent.substr(0, 2) == "12" && nextEvent.substr(0, 2) != "12")) 26 | { 27 | return (nextTime + 12.00) - currentTime; 28 | } 29 | else if (time1 == time2) 30 | { 31 | return nextTime - currentTime; 32 | } 33 | else 34 | { 35 | return (nextTime + 12.00) - currentTime; 36 | } 37 | } 38 | 39 | string MostFreeTime(string strArr[], int size) { 40 | int index; 41 | string current, current2, current3, temp, temp2, temp3; 42 | bool swap; 43 | 44 | // Loop to order the events 45 | do 46 | { 47 | swap = false; 48 | for (int x = 0; x < size-1; x++) 49 | { 50 | current = strArr[x].substr(0, 2); // current hour 51 | current2 = strArr[x].substr(5, 2); // current time frame 52 | current3 = strArr[x].substr(3, 2); // current minute 53 | temp = strArr[x+1].substr(0, 2); // next event hour 54 | temp2 = strArr[x+1].substr(5, 2); // next event time frame 55 | temp3 = strArr[x + 1].substr(3, 2); // next event minute 56 | 57 | // Conditions to compare based on time and if early or late in the day 58 | if (current == temp && current2 == temp2 && current3 > temp3) 59 | { 60 | temp = strArr[x]; 61 | strArr[x] = strArr[x + 1]; 62 | strArr[x + 1] = temp; 63 | swap = true; 64 | } 65 | if ((temp < current && current != "12") && ((current2 == "AM" && temp2 == "AM") || (current2 == "PM" && temp2 == "PM"))) 66 | { 67 | temp = strArr[x]; 68 | strArr[x] = strArr[x + 1]; 69 | strArr[x + 1] = temp; 70 | swap = true; 71 | } 72 | else if ((temp > current && temp == "12") && ((current2 == "AM" && temp2 == "AM") || (current2 == "PM" && temp2 == "PM"))) 73 | { 74 | temp = strArr[x]; 75 | strArr[x] = strArr[x + 1]; 76 | strArr[x + 1] = temp; 77 | swap = true; 78 | } 79 | else if ((temp < current || temp > current) && current2 == "PM" && temp2 == "AM") 80 | { 81 | temp = strArr[x]; 82 | strArr[x] = strArr[x + 1]; 83 | strArr[x + 1] = temp; 84 | swap = true; 85 | } 86 | } 87 | } while (swap); 88 | 89 | double value; 90 | double high = 0; 91 | // Loop to find the most free time 92 | for (int y = 0; y < size-1; y++) 93 | { 94 | // Value we use the function to find the difference between the current and next event time 95 | // It takes the end time of current event and beginning time of next event 96 | // The AM and PM will help with calculating the difference 97 | value = timeDifference(strArr[y].substr(8, 5), strArr[y + 1].substr(0, 5), strArr[y].substr(strArr[y].length() - 2), strArr[y+1].substr(5,2)); 98 | 99 | if (value > high) // Keep track of which provides the most free time 100 | { 101 | high = value; 102 | } 103 | } 104 | 105 | // Convert the highest difference value back to a string for editing 106 | stringstream convert; 107 | convert << fixed << setprecision(2) << high; 108 | string freeTime = convert.str(); 109 | // Assuring that the output is in a time format 110 | // Example if 4.32 it should be 04:32 111 | if (freeTime.length() != 5) 112 | { 113 | freeTime.insert(0, "0"); 114 | } 115 | freeTime[2] = ':'; 116 | 117 | return freeTime; 118 | } 119 | // Note, looking back at the code we could have eliminate having an extra condition and logic for dealing with 12, by checking the hour and set to zero if 12. Example if temp == 12 , temp == 0 120 | // Also the conditions could have been left to only one single if else, meaning just check if the next event is later in the date, if true continue else swap. 121 | 122 | int main() { 123 | // keep this function call here 124 | /* Note: In C++ you current have to initialize an array and set 125 | it equal to the stdin to test your code with arrays. */ 126 | string A[] = { "12:15PM-02:00PM", "09:00AM-10:00AM", "10:30AM-12:00PM" }; 127 | string B[] = { "12:15PM-02:00PM", "09:00AM-12:11PM", "02:02PM-04:00PM" }; 128 | string C[] = { "10:00AM-12:30PM", "02:00PM-02:45PM", "09:10AM-09:50AM" }; 129 | string D[] = { "06:00AM-08:00PM", "09:09PM-09:11PM", "08:10PM-09:00PM", "08:02PM-08:04PM" }; 130 | cout << MostFreeTime(A, sizeof(A) / sizeof(A[0])) << endl; // 00:30 131 | cout << MostFreeTime(B, sizeof(B) / sizeof(B[0])) << endl; // 00:04 132 | cout << MostFreeTime(C, sizeof(C) / sizeof(C[0])) << endl; // 01:30 133 | cout << MostFreeTime(D, sizeof(D) / sizeof(D[0])) << endl; // 00:09 134 | 135 | return 0; 136 | } -------------------------------------------------------------------------------- /23_DistinctList.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will remove duplicate elements from an array. 2 | // have the function DistinctList(arr) take the array of numbers stored in arr and determine the total number of duplicate entries. For example if the input is [1, 2, 2, 2, 3] then your program should output 2 because there are two duplicates of one of the elements. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | // Function used to aid in the distinctList 9 | // Will sort the array which in turn allows for an easier solution 10 | // For the case in which some repeats are scattered 11 | void sortArray(int array[], int size) 12 | { 13 | int temp; 14 | bool swap; 15 | do 16 | { 17 | swap = false; 18 | for (int x = 0; x < size - 1; x++) 19 | { 20 | if (array[x] > array[x + 1]) 21 | { 22 | temp = array[x]; 23 | array[x] = array[x + 1]; 24 | array[x + 1] = temp; 25 | swap = true; 26 | } 27 | } 28 | } while (swap); 29 | } 30 | 31 | int DistinctList(int arr[], int size) { 32 | 33 | int count = 0; 34 | 35 | // Calling the sort function 36 | sortArray(arr, size); 37 | 38 | // Traversing the new array and checking for duplicates 39 | for (int x = 0; x < size-1; x++) 40 | { 41 | if (arr[x] == arr[x + 1]) 42 | { 43 | count++; 44 | } 45 | } 46 | return count; 47 | } 48 | 49 | int main() { 50 | 51 | // keep this function call here 52 | /* Note: In C++ you first have to initialize an array and set 53 | it equal to the stdin to test your code with arrays. */ 54 | 55 | int A[] = { 0, -2, -2, 5, 5, 5 }; 56 | int B[] = { 100, 2, 101, 4 }; 57 | int C[] = { 1, 2, 2, 2, 3 }; 58 | cout << DistinctList(A, sizeof(A)/sizeof(A[0])) << endl; // 3 59 | cout << DistinctList(B, sizeof(B) / sizeof(B[0])) << endl; // 0 60 | cout << DistinctList(C, sizeof(C) / sizeof(C[0])) << endl; // 2 61 | return 0; 62 | 63 | } -------------------------------------------------------------------------------- /24_FibonacciChecker.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be determining whether a number is part of the Fibonacci sequence. 2 | // have the function FibonacciChecker(num) return the string yes if the number given is part of the Fibonacci sequence. This sequence is defined by: Fn = Fn-1 + Fn-2, which means to find Fn you add the previous two numbers up. The first two numbers are 0 and 1, then comes 1, 2, 3, 5 etc. If num is not in the Fibonacci sequence, return the string no. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | // Recursive implementation 9 | // Will start with default values of 1 10 | // Will go through the Fibonacci sequence until number is found or the sequence number is greater than the target value 11 | string FibonacciChecker(int x, int y,int num) { 12 | if (num == 0 || num == 1) // If the number is 1 or 0 13 | { 14 | return "yes"; 15 | } 16 | else if (x + y == num) // When number is part of the sequence 17 | { 18 | return "yes"; 19 | } 20 | else if (x + y < num) // While still less than the target, continue through the sequence 21 | { 22 | return FibonacciChecker(x + y, x, num); 23 | } 24 | else 25 | { 26 | return "no"; 27 | } 28 | } 29 | 30 | int main() { 31 | 32 | // keep this function call here 33 | cout << FibonacciChecker(1,1,34) << endl; // yes 34 | cout << FibonacciChecker(1,1,54) << endl; // no 35 | cout << FibonacciChecker(1,1,13) << endl; // yes 36 | cout << FibonacciChecker(1,1,22) << endl; // no 37 | return 0; 38 | 39 | } -------------------------------------------------------------------------------- /25_OverlappingRectangles.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be determining the areas of rectangles. 2 | // have the function OverlappingRectangles(strArr) read the strArr parameter being passed which will represent two rectangles on a Cartesian coordinate plane and will contain 8 coordinates with the first 4 making up rectangle 1 and the last 4 making up rectangle 2. It will be in the following format: ["(0,0),(2,2),(2,0),(0,2),(1,0),(1,2),(6,0),(6,2)"] Your program should determine the area of the space where the two rectangles overlap, and then output the number of times this overlapping region can fit into the first rectangle. For the above example, the overlapping region makes up a rectangle of area 2, and the first rectangle (the first 4 coordinates) makes up a rectangle of area 4, so your program should output 2. The coordinates will all be integers. If there's no overlap between the two rectangles return 0. 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | /* 10 | traverse the string array to extract the points of each rectangle 11 | first locate smallest and largest vertical/horizontal points of each 12 | we then calculate the area of first rectangle 13 | to locate points of overlapping rectangles we do a comparison of lowest and highest X and Y points 14 | calculate are of overlapping rectangle after collecting its width and height 15 | */ 16 | 17 | // method to get the lowest and highest x and y points for each rectangle 18 | void getPoints(string data, int start, int end, int& lowX, int& highX, int& lowY, int& highY) 19 | { 20 | string num; 21 | bool firstRecord = false; 22 | bool firstRecord2 = false; 23 | 24 | // traverse the string to analyze the current points 25 | for (int y = start; y < end; y++) 26 | { 27 | // condition to collect x and y point value 28 | if ((data[y] >= '0' && data[y] <= '9') || data[y] == '-') 29 | { 30 | num.push_back(data[y]); 31 | } 32 | else if (data[y] == ',' && !num.empty()) // finding the lowest and highest horizontal x point value 33 | { 34 | istringstream convert(num); 35 | 36 | // first records are automatically collected 37 | if (!firstRecord) 38 | { 39 | convert >> lowX; 40 | convert >> highX; 41 | firstRecord = true; 42 | } 43 | else 44 | { 45 | // comparison done to collect lowest and highest 46 | int temp; 47 | convert >> temp; 48 | 49 | if (temp < lowX) 50 | { 51 | lowX = temp; 52 | } 53 | else if (temp > highX) 54 | { 55 | highX = temp; 56 | } 57 | } 58 | 59 | // reset for recording next pair of points 60 | num.clear(); 61 | } 62 | else if (data[y] == ')') 63 | { 64 | istringstream convert(num); 65 | 66 | if (!firstRecord2) 67 | { 68 | convert >> lowY; 69 | convert >> highY; 70 | firstRecord2 = true; 71 | } 72 | else 73 | { 74 | int temp; 75 | convert >> temp; 76 | 77 | if (temp < lowY) 78 | { 79 | lowY = temp; 80 | } 81 | else if (temp > highY) 82 | { 83 | highY = temp; 84 | } 85 | } 86 | 87 | num.clear(); 88 | } 89 | } 90 | } 91 | 92 | int OverlappingRectangles(string strArr[]) 93 | { 94 | // points representing both our rectangles 95 | int rectangle1_lowX; 96 | int rectangle1_highX; 97 | int rectangle1_lowY; 98 | int rectangle1_highY; 99 | 100 | int rectangle2_lowX; 101 | int rectangle2_highX; 102 | int rectangle2_lowY; 103 | int rectangle2_highY; 104 | 105 | // section to locate the separator for the both rectangle points 106 | int midIndex = 0; 107 | string data = strArr[0]; 108 | for (int x = 0; x < data.length(); x++) 109 | { 110 | if (data[x] == ',') 111 | { 112 | midIndex++; 113 | } 114 | 115 | if (midIndex == 8) 116 | { 117 | midIndex = x; 118 | break; 119 | } 120 | } 121 | 122 | // getting the desired point values for rectangle 1 123 | getPoints(data, 0, midIndex, rectangle1_lowX, rectangle1_highX, rectangle1_lowY, rectangle1_highY); 124 | 125 | // getting the desired point values for rectangle 2 126 | getPoints(data, midIndex+1, data.length(), rectangle2_lowX, rectangle2_highX, rectangle2_lowY, rectangle2_highY); 127 | 128 | // area of rectangle1 129 | int rectangle1Area = (rectangle1_highX - rectangle1_lowX) * (rectangle1_highY - rectangle1_lowY); 130 | 131 | // X and Y distance of the overlapping rectangle 132 | int overlappingX; 133 | int overlappingY; 134 | 135 | // condition to calculate width of overlapping rectangle 136 | if (rectangle2_lowX >= rectangle1_lowX && rectangle2_lowX < rectangle1_highX) 137 | { 138 | if (rectangle2_highX >= rectangle1_highX) 139 | { 140 | overlappingX = rectangle1_highX - rectangle2_lowX; 141 | } 142 | else 143 | { 144 | overlappingX = rectangle2_highX - rectangle2_lowX; 145 | } 146 | } 147 | else if (rectangle2_lowX < rectangle1_lowX && rectangle2_highX > rectangle1_lowX) 148 | { 149 | overlappingX = rectangle2_highX - rectangle1_lowX; 150 | } 151 | else 152 | { 153 | // no overlapping 154 | return 0; 155 | } 156 | 157 | // condition to calculate height of overlapping rectangle 158 | if (rectangle2_lowY >= rectangle1_lowY && rectangle2_lowY < rectangle1_highY) 159 | { 160 | if (rectangle2_highY >= rectangle1_highY) 161 | { 162 | overlappingY = rectangle1_highY - rectangle2_lowY; 163 | } 164 | else 165 | { 166 | overlappingY = rectangle2_highY - rectangle2_lowY; 167 | } 168 | } 169 | else if (rectangle2_lowY < rectangle1_lowY && rectangle2_highY > rectangle1_lowY) 170 | { 171 | overlappingY = rectangle2_highY - rectangle1_lowY; 172 | } 173 | else 174 | { 175 | return 0; 176 | } 177 | 178 | // area of overlapping rectangle 179 | int overlappingArea = overlappingX * overlappingY; 180 | 181 | return rectangle1Area / overlappingArea; 182 | } 183 | 184 | int main() 185 | { 186 | string A[] = { "(0,0),(0,-2),(3,0),(3,-2),(2,-1),(3,-1),(2,3),(3,3)" }; 187 | string B[] = { "(0,0),(5,0),(0,2),(5,2),(2,1),(5,1),(2,-1),(5,-1)" }; 188 | string C[] = { "(0,0),(2,2),(2,0),(0,2),(1,0),(1,2),(6,0),(6,2)" }; 189 | string D[] = { "(1,0),(1,1),(4,0),(4,1),(2,0),(4,0),(2,1),(4,1)" }; 190 | string E[] = { "(5,0),(-2,0),(5,-1),(-2,-1),(3,-1),(5,-1),(3,56),(5,56)" }; 191 | string F[] = { "(1,0),(1,1),(4,0),(4,1),(5,0),(27,0),(5,-25),(27,-25)" }; 192 | string G[] = { "(1,0),(1,1),(4,0),(4,1),(3,0),(4,0),(3,1),(4,1)" }; 193 | string H[] = { "(0,0),(0,-2),(3,0),(3,-2),(2,-2),(3,-2),(2,20),(3,20)" }; 194 | 195 | cout << OverlappingRectangles(A) << endl; // 6 196 | cout << OverlappingRectangles(B) << endl; // 3 197 | cout << OverlappingRectangles(C) << endl; // 2 198 | cout << OverlappingRectangles(D) << endl; // 1 199 | cout << OverlappingRectangles(E) << endl; // 3 200 | cout << OverlappingRectangles(F) << endl; // 0 201 | cout << OverlappingRectangles(G) << endl; // 3 202 | cout << OverlappingRectangles(H) << endl; // 3 203 | return 0; 204 | } 205 | -------------------------------------------------------------------------------- /26_NumberEncoding.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will encode a given string following a specific rule. 2 | // have the function NumberEncoding(str) take the str parameter and encode the message according to the following rule: encode every letter into its corresponding numbered position in the alphabet. Symbols and spaces will also be used in the input. For example: if str is "af5c a#!" then your program should return 1653 1#!. 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | string NumberEncoding(string str) { 11 | // Making all the characters in the string lower case 12 | // This will make it easier to determine alphabet position calculation later on. 13 | for (int x = 0; x < str.length(); x++) 14 | { 15 | str[x] = tolower(str[x]); 16 | } 17 | 18 | string temp; 19 | for (int y = 0; y < str.length(); y++) 20 | { 21 | // If the character is a letter than find the position 22 | if (str[y] >= 'a' && str[y] <= 'z') 23 | { 24 | // Calculation to find the position 25 | // Since we are dealing with lowercase only, this is simple to do with ascii value 26 | // To handle double digits we would need to take the result as an int than store as a string datatype 27 | int position = int(str[y]) - 96; 28 | stringstream convert; 29 | convert << position; 30 | temp += convert.str(); 31 | } 32 | else 33 | { 34 | // If we find symbols or other numbers just do it, JUST DO IT 35 | temp.push_back(str[y]); 36 | } 37 | } 38 | return temp; 39 | } 40 | 41 | int main() { 42 | 43 | // keep this function call here 44 | cout << NumberEncoding("hello 45") << endl; // 85121215 45 45 | cout << NumberEncoding("jaj-a") << endl; // 10110-1 46 | cout << NumberEncoding("af5c a#!") << endl; // 1653 1#! 47 | return 0; 48 | 49 | } -------------------------------------------------------------------------------- /27_PrimeChecker.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine if you can arrange a number to be a prime number. 2 | // have the function PrimeChecker(num) take num and return 1 if any arrangement of num comes out to be a prime number, otherwise return 0. For example: if num is 910, the output should be 1 because 910 can be arranged into 109 or 019, both of which are primes. 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | // Function to check if the argument is prime 10 | bool isPrime(string number) 11 | { 12 | int value; 13 | istringstream(number) >> value; 14 | if (value == 1) 15 | { 16 | return false; 17 | } 18 | for (int x = 2; x < value; x++) 19 | { 20 | if (value%x == 0) 21 | { 22 | return false; 23 | } 24 | } 25 | return true; 26 | } 27 | 28 | int PrimeChecker(int num) { 29 | // Convert to a string for editing 30 | stringstream convert; 31 | convert << num; 32 | string temp = convert.str(); 33 | char current; 34 | 35 | //Check if the number is prime when is only 1 digit 36 | if (temp.length() == 1) 37 | { 38 | if (isPrime(temp)) 39 | { 40 | return 1; 41 | } 42 | else 43 | { 44 | return 0; 45 | } 46 | } 47 | // Check if the number is prime when there are only 2 digits 48 | else if (temp.length() == 2) 49 | { 50 | if (isPrime(temp)) 51 | { 52 | return 1; 53 | } 54 | current = temp[0]; 55 | temp[0] = temp[1]; 56 | temp[1] = current; 57 | if (isPrime(temp)) 58 | { 59 | return 1; 60 | } 61 | } 62 | else 63 | { 64 | // Loop to arrange the number when dealing with multiple digits 65 | for (int x = 0; x < temp.length(); x++) 66 | { 67 | for (int y = 0; y < temp.length()-1; y++) 68 | { 69 | if (isPrime(temp)) // Check the number to see if is prime 70 | { 71 | return 1; 72 | } 73 | else // Rearrange the digits 74 | { 75 | current = temp[y]; 76 | temp[y] = temp[y + 1]; 77 | temp[y + 1] = current; 78 | } 79 | } 80 | } 81 | } 82 | 83 | return 0; 84 | } 85 | 86 | int main() { 87 | 88 | // keep this function call here 89 | cout << PrimeChecker(98) << endl; // 1 90 | cout << PrimeChecker(598) << endl; // 1 91 | cout << PrimeChecker(910) << endl; // 1 92 | cout << PrimeChecker(22) << endl; // 0 93 | cout << PrimeChecker(71) << endl; // 1 94 | cout << PrimeChecker(100) << endl; // 0 95 | return 0; 96 | 97 | } -------------------------------------------------------------------------------- /28_LookSaySequence.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine the next number in a sequence. 2 | // have the function LookSaySequence(num) take the num parameter being passed and return the next number in the sequence according to the following rule: to generate the next number in a sequence read off the digits of the given number, counting the number of digits in groups of the same digit. For example, the sequence beginning with 1 would be: 1, 11, 21, 1211, ... The 11 comes from there being "one 1" before it and the 21 comes from there being "two 1's" before it. So your program should return the next number in the sequence given num. 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | int LookSaySequence(int num) { 10 | // Convert to a string for editing 11 | stringstream convert; 12 | convert << num; 13 | string temp = convert.str(); 14 | 15 | int count = 1; 16 | string temp2; 17 | for (int x = 0; x < temp.length(); x++) 18 | { 19 | // Checking the last two numbers of the sequence 20 | if (x == temp.length() - 1 && temp[x] != temp[x - 1]) 21 | { 22 | temp2.push_back(char(count + 48)); 23 | temp2.push_back(temp[x]); 24 | count = 1; 25 | } 26 | // Checking the next number in the sequence 27 | else if (temp[x] == temp[x + 1]) 28 | { 29 | count++; 30 | } 31 | else 32 | { 33 | temp2.push_back(char(count+48)); 34 | temp2.push_back(temp[x]); 35 | count = 1; 36 | } 37 | } 38 | 39 | istringstream(temp2) >> num; 40 | return num; 41 | } 42 | 43 | int main() { 44 | 45 | // keep this function call here 46 | cout << LookSaySequence(1211) << endl; //111221 47 | cout << LookSaySequence(2466) << endl; // 121426 48 | cout << LookSaySequence(111221) << endl; // 312211 49 | return 0; 50 | 51 | } -------------------------------------------------------------------------------- /29_StockPicker.cpp: -------------------------------------------------------------------------------- 1 | // For this practice test you will determine the maximum profit that can be made in a range of stock prices. 2 | // have the function StockPicker(arr) take the array of numbers stored in arr which will contain integers that represent the amount in dollars that a single stock is worth, and return the maximum profit that could have been made by buying stock on day x and selling stock on day y where y > x. For example: if arr is [44, 30, 24, 32, 35, 30, 40, 38, 15] then your program should return 16 because at index 2 the stock was worth $24 and at index 6 the stock was then worth $40, so if you bought the stock at 24 and sold it at 40, you would have made a profit of $16, which is the maximum profit that could have been made with this list of stock prices. 3 | // If there is not profit that could have been made with the stock prices, then your program should return -1. For example : arr is[10, 9, 8, 2] then your program should return -1 4 | 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | int StockPicker(int arr[], int size) { 10 | 11 | int value; 12 | int high = -1; 13 | 14 | // Loop to analyze each stock 15 | for (int x = 0; x < size-1; x++) 16 | { 17 | // Loop to compare which is the maximum profit 18 | // This takes the stock on day x and day y, to find difference 19 | for (int y = x+1; y < size; y++) 20 | { 21 | if (arr[x] < arr[y]) 22 | { 23 | value = arr[y] - arr[x]; 24 | 25 | if (value > high) 26 | { 27 | high = value; 28 | } 29 | } 30 | } 31 | } 32 | 33 | return high; 34 | } 35 | 36 | int main() { 37 | 38 | // keep this function call here 39 | /* Note: In C++ you first have to initialize an array and set 40 | it equal to the stdin to test your code with arrays. */ 41 | 42 | int A[] = { 10, 12, 4, 5, 9 }; 43 | int B[] = { 14, 20, 4, 12, 5, 11 }; 44 | int C[] = { 44, 30, 24, 32, 35, 30, 40, 38, 15 }; 45 | int D[] = { 10, 9, 8, 2 }; 46 | cout << StockPicker(A, sizeof(A) / sizeof(A[0])) << endl; // 5 47 | cout << StockPicker(B, sizeof(B) / sizeof(B[0])) << endl; // 8 48 | cout << StockPicker(C, sizeof(C) / sizeof(C[0])) << endl; // 16 49 | cout << StockPicker(D, sizeof(D) / sizeof(D[0])) << endl; // -1 50 | return 0; 51 | } -------------------------------------------------------------------------------- /2_RunLength.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine the Run Length Encoding of a string. 2 | // have the function RunLength(str) take the str parameter being passed and return a compressed version of the string using the Run-length encoding algorithm. This algorithm works by taking the occurrence of each repeating character and outputting that number along with a single character of the repeating sequence. For example: "wwwggopp" would return 3w2g1o2p. The string will not contain any numbers, punctuation, or symbols. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | string RunLength(string str) 9 | { 10 | string temp; 11 | char letter = ' '; 12 | int count; 13 | 14 | for (int x = 0; x < str.length(); x++) 15 | { 16 | count = 1; // Set the repetition number 1 17 | if (str[x] == letter) // Ignore if the letter has been already recorded 18 | { 19 | continue; 20 | } 21 | else 22 | { 23 | letter = str[x]; 24 | } 25 | 26 | // Loop to check how many times the letter repeats 27 | for (int y = x; y < str.length()-1; y++) 28 | { 29 | if (x == str.length() - 1) 30 | { 31 | break; 32 | } 33 | else if (str[y] == letter && str[y] == str[y + 1]) 34 | { 35 | count++; 36 | } 37 | } 38 | 39 | // Insert the results into a new string 40 | temp.push_back(char(count+48)); 41 | temp.push_back(letter); 42 | } 43 | 44 | return temp; 45 | } 46 | 47 | int main() { 48 | 49 | // keep this function call here 50 | cout << RunLength("aabbcde") << endl; // 2a2b1c1d1e 51 | cout << RunLength("wwwbbbw") << endl; // 3w3b1w 52 | cout << RunLength("wwwggopp") << endl; // 3w2g1o2p 53 | return 0; 54 | 55 | } -------------------------------------------------------------------------------- /30_MultipleBrackets.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine if all the brackets in a string are correctly matched up. 2 | // have the function MultipleBrackets(str) take the str parameter being passed and return 1 #ofBrackets if the brackets are correctly matched and each one is accounted for. Otherwise return 0. For example: if str is "(hello [world])(!)", then the output should be 1 3 because all the brackets are matched and there are 3 pairs of brackets, but if str is "((hello [world])" the the output should be 0 because the brackets do not correctly match up. Only "(", ")", "[", and "]" will be used as brackets. If str contains no brackets return 1. 3 | 4 | 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | string MultipleBrackets(string str) { 11 | 12 | int count = 0, count2 = 0; 13 | int total = 0; 14 | 15 | // Overall this is quite similar to the previous bracket matcher problem 16 | for (int x = 0; x < str.length(); x++) 17 | { 18 | // Checking for the ( opening bracket 19 | if (str[x] == '(') 20 | { 21 | count++; 22 | } 23 | else if (str[x] == '[') // Checking for the [ bracket 24 | { 25 | count2++; 26 | } 27 | else if (str[x] == ')') // Check that () brackets open and close 28 | { 29 | count--; 30 | total++; 31 | if (count < 0) 32 | { 33 | return "0"; 34 | } 35 | } 36 | else if (str[x] == ']') // Check that [] brackets open and close 37 | { 38 | count2--; 39 | total++; 40 | if (count2 < 0) 41 | { 42 | return "0"; 43 | } 44 | } 45 | } 46 | 47 | if (count == 0 && count2 == 0 && total == 0) 48 | { 49 | return "1"; 50 | } 51 | else if (count == 0 && count2 == 0 && total > 0) 52 | { 53 | stringstream convert; 54 | convert << 1 << " " << total; 55 | return convert.str(); 56 | } 57 | else 58 | { 59 | return "0"; 60 | } 61 | } 62 | 63 | int main() { 64 | 65 | // keep this function call here 66 | cout << MultipleBrackets("(coder)[byte)]") << endl; // 0 67 | cout << MultipleBrackets("(c([od]er)) b(yt[e])") << endl; // 1 5 68 | cout << MultipleBrackets("(hello [world])(!)") << endl; // 1 3 69 | cout << MultipleBrackets("((hello [world])") << endl; // 0 70 | cout << MultipleBrackets("Attack on titan is awesome") << endl; // 1 71 | cout << MultipleBrackets("()code[rb]yte() yes()[ss][[") << endl; // 0 72 | return 0; 73 | 74 | } -------------------------------------------------------------------------------- /31_MaxSubarray.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine the largest sum subarray. 2 | // have the function MaxSubarray(arr) take the array of numbers stored in arr and determine the largest sum that can be formed by any contiguous subarray in the array. For example, if arr is [-2, 5, -1, 7, -3] then your program should return 11 because the sum is formed by the subarray [5, -1, 7]. Adding any element before or after this subarray would make the sum smaller. 3 | 4 | #include 5 | using namespace std; 6 | 7 | int MaxSubarray(int arr[], int size) { 8 | int high = -100 *1000; 9 | // For highest value from the array without sum 10 | for (int x = 0; x < size; x++) 11 | { 12 | if (arr[x] > high) 13 | { 14 | high = arr[x]; 15 | } 16 | } 17 | 18 | int total = 0; 19 | // Loop for doing the sum 20 | // Takes each value and adds to the continuous value until the sum is the highest possible 21 | for (int y = 0; y < size - 1; y++) 22 | { 23 | total = arr[y]; 24 | for (int z = y + 1; z < size; z++) 25 | { 26 | total += arr[z]; 27 | 28 | if (total > high) 29 | { 30 | high = total; 31 | } 32 | } 33 | } 34 | 35 | return high; 36 | } 37 | 38 | int main() { 39 | 40 | // keep this function call here 41 | /* Note: In C++ you first have to initialize an array and set 42 | it equal to the stdin to test your code with arrays. */ 43 | 44 | int A[] = { 1, -2, 0, 3 }; 45 | int B[] = { 3, -1, -1, 4, 3, -1 }; 46 | int C[] = { -2, 5, -1, 7, -3 }; 47 | int D[] = { -4, -5, -6 }; 48 | cout << MaxSubarray(A, sizeof(A) / sizeof(A[0])) << endl; // 3 49 | cout << MaxSubarray(B, sizeof(B) / sizeof(B[0])) << endl; // 8 50 | cout << MaxSubarray(C, sizeof(C) / sizeof(C[0])) << endl; // 11 51 | cout << MaxSubarray(D, sizeof(D) / sizeof(D[0])) << endl; // -4 52 | return 0; 53 | 54 | } 55 | -------------------------------------------------------------------------------- /32_MissingDigit.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine what the variable is in a mathematical equation. 2 | // have the function MissingDigit(str) take the str parameter, which will be a simple mathematical formula with three numbers, a single operator (+, -, *, or /) and an equal sign (=) and return the digit that completes the equation. In one of the numbers in the equation, there will be an x character, and your program should determine what digit is missing. For example, if str is "3x + 12 = 46" then your program should output 4. The x character can appear in any of the three numbers and all three numbers will be greater than or equal to 0 and less than or equal to 1000000. 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | // Helper function that determines the type of calculation 10 | void calculation(int& val, int x, int y, char symbol) 11 | { 12 | // Finding which type of calculation we need to perform 13 | switch (symbol) 14 | { 15 | case '+': 16 | { 17 | val = x + y; 18 | break; 19 | } 20 | case '-': 21 | { 22 | val = x - y; 23 | break; 24 | } 25 | case '*': 26 | { 27 | val = x * y; 28 | break; 29 | } 30 | case '/': 31 | { 32 | val = x / y; 33 | break; 34 | } 35 | } 36 | } 37 | // Another helper function that will inverse the operation 38 | void operatorSwitch(string& equation, int index) 39 | { 40 | // Switching the operator 41 | // Example if original is + now it will be -. 42 | // Ex. x+3 = 7 becomes 7-3 = x. Simple algebra 43 | switch (equation[index]) 44 | { 45 | case '+': 46 | { 47 | equation[index] = '-'; 48 | break; 49 | } 50 | case '-': 51 | { 52 | equation[index] = '+'; 53 | break; 54 | } 55 | case '*': 56 | { 57 | equation[index] = '/'; 58 | break; 59 | } 60 | case '/': 61 | { 62 | equation[index] = '*'; 63 | break; 64 | } 65 | } 66 | } 67 | 68 | char MissingDigit(string str) { 69 | // Removing spaces 70 | for (int y = 0; y < str.length(); y++) 71 | { 72 | if (str[y] == ' ') 73 | { 74 | str.erase(str.begin() + y); 75 | } 76 | } 77 | 78 | // Find the operator and sign symbol 79 | int symbol, sign; 80 | for (int x = 0; x < str.length(); x++) 81 | { 82 | if (str[x] == '+' || str[x] == '-' || str[x] == '*' || str[x] == '/') 83 | { 84 | symbol = x; 85 | } 86 | } 87 | sign = str.find('='); 88 | 89 | // Finding x variable position, this will help determine the method of calculation to perform 90 | int value = str.find('x'); 91 | 92 | int value1, value2, value3, index = 0, index2; 93 | string temp; 94 | // Analyzing whether the variable is after the sign 95 | if (value > sign) 96 | { 97 | istringstream(str.substr(0, symbol)) >> value1; 98 | istringstream(str.substr(symbol + 1, sign-symbol)) >> value2; 99 | 100 | // Calculation function that will give us the result for the missing variable 101 | calculation(value3, value1, value2, str[symbol]); 102 | 103 | // We convert number value to a string and find result based on index 104 | // Example number = 27 , original x7 than result would be 2 105 | stringstream convert; 106 | convert << value3; 107 | temp = convert.str(); 108 | index2 = sign+1; // index2 helps with making the result string parallel to the original string 109 | for (sign; sign < str.length(); sign++) 110 | { 111 | // If they are the same index return the corresponding value 112 | if (sign == value) 113 | { 114 | return temp[sign-index2]; 115 | } 116 | } 117 | } 118 | else // Analyzing when variable is before the sign 119 | { 120 | // If the variable is after the symbol or before 121 | if (value < symbol) // Before 122 | { 123 | istringstream(str.substr(symbol + 1, sign - symbol)) >> value1; 124 | istringstream(str.substr(sign + 1)) >> value2; 125 | 126 | // Calculation and switching the operation 127 | operatorSwitch(str, symbol); 128 | calculation(value3, value2, value1, str[symbol]); 129 | 130 | stringstream convert; 131 | convert << value3; 132 | temp = convert.str(); 133 | for (index; index < symbol; index++) 134 | { 135 | // If they are the same index return the corresponding value 136 | if (index == value) 137 | { 138 | return temp[index]; 139 | } 140 | } 141 | } 142 | else // After 143 | { 144 | istringstream(str.substr(0, symbol)) >> value1; 145 | istringstream(str.substr(sign + 1)) >> value2; 146 | 147 | // Calculation and switching the operation 148 | if (value1 != value2) 149 | { 150 | operatorSwitch(str, symbol); 151 | } 152 | calculation(value3, value2, value1, str[symbol]); 153 | 154 | stringstream convert; 155 | convert << value3; 156 | temp = convert.str(); 157 | index = symbol; 158 | index2 = symbol + 1; 159 | for (index; index < sign; index++) 160 | { 161 | // If they are the same index return the corresponding value 162 | if (index == value) 163 | { 164 | return temp[index-index2]; 165 | } 166 | } 167 | } 168 | } 169 | } 170 | 171 | int main() { 172 | 173 | // keep this function call here 174 | cout << MissingDigit("4 - 2 = x") << endl; // 2 175 | cout << MissingDigit("10 + 14 = 2x") << endl; // 4 176 | cout << MissingDigit("20 + 7 = x7") << endl; // 2 177 | cout << MissingDigit("1x0 * 12 = 1200") << endl; // 0 178 | cout << MissingDigit("3x + 12 = 46") << endl; // 4 179 | cout << MissingDigit("10 - x = 10") << endl; // 0 180 | cout << MissingDigit("14 + x1 = 25") << endl; // 1 181 | cout << MissingDigit("2x - 10 = 10") << endl; // 0 182 | return 0; 183 | } -------------------------------------------------------------------------------- /33_KUniqueCharacters.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be searching a string for a particular substring. 2 | // have the function KUniqueCharacters(str) take the str parameter being passed and find the longest substring that contains k unique characters, where k will be the first character from the string. The substring will start from the second position in the string because the first character will be the integer k. For example: if str is "2aabbacbaa" there are several substrings that all contain 2 unique characters, namely: ["aabba", "ac", "cb", "ba"], but your program should return "aabba" because it is the longest substring. If there are multiple longest substrings, then return the first substring encountered with the longest length. k will range from 1 to 6. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | // Linear search function to check if a character is currently in that string 9 | bool search(string temp, char letter) 10 | { 11 | for (int x = 0; x < temp.length(); x++) 12 | { 13 | if (letter == temp[x]) 14 | { 15 | return true; 16 | } 17 | } 18 | return false; 19 | } 20 | 21 | // Function that will determine how many unique characters are in the specified string 22 | int uniqueCount(string temp) 23 | { 24 | string uniqueString; 25 | 26 | for (int x = 0; x < temp.length(); x++) 27 | { 28 | if (!search(uniqueString, temp[x])) // Insert only the uniquer character into the string 29 | { 30 | uniqueString.push_back(temp[x]); 31 | } 32 | } 33 | return uniqueString.length(); // return the current total number of unique characters 34 | } 35 | 36 | string KUniqueCharacters(string str) { 37 | // getting the first character as an integer 38 | int unique = int(str[0]) - 48; 39 | 40 | int index = 1; 41 | string temp, temp2; 42 | 43 | while (index < str.length()) 44 | { 45 | for (int x = index; x < str.length(); x++) 46 | { 47 | temp.push_back(str[x]); 48 | 49 | // Condition for when we reach pass the k integer 50 | // delete the last character for that substring 51 | if (uniqueCount(temp) > unique) 52 | { 53 | x--; 54 | temp.pop_back(); 55 | 56 | // Compare to keep the largest substring 57 | if (temp.length() > temp2.length()) 58 | { 59 | temp2 = temp; 60 | } 61 | temp.clear(); 62 | } 63 | } 64 | 65 | // We compare once more in the case, that the substring continues to the end 66 | if (temp.length() > temp2.length()) 67 | { 68 | temp2 = temp; 69 | } 70 | temp.clear(); 71 | index++; 72 | } 73 | 74 | return temp2; 75 | } 76 | 77 | int main() { 78 | 79 | // keep this function call here 80 | cout << KUniqueCharacters("3aabacbebebe") << endl; // "cbebebe" 81 | cout << KUniqueCharacters("2aabbcbbbadef") << endl; // "bbcbbb" 82 | cout << KUniqueCharacters("2aabbacbaa") << endl; // "aabba" 83 | return 0; 84 | } -------------------------------------------------------------------------------- /34_BtimapHoles.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be searching within a 2D matrix. 2 | /* 3 | have the function BitmapHoles(strArr) take the array of strings stored in strArr, which will be a 2D matrix of 0 and 1's, and determine how many holes, or contiguous regions of 0's, exist in the matrix. A contiguous region is one where there is a connected group of 0's going in one or more of four directions: up, down, left, or right. For example: if strArr is ["10111", "10101", "11101", "11111"], then this looks like the following matrix: 4 | 5 | 1 0 1 1 1 6 | 1 0 1 0 1 7 | 1 0 1 0 1 8 | 1 1 1 1 1 9 | 10 | For the input above, your program should return 2 because there are two separate contiguous regions of 0's, which create "holes" in the matrix. You can assume the input will not be empty. 11 | */ 12 | #include 13 | #include 14 | #include 15 | using namespace std; 16 | 17 | /* 18 | analyze the string array and look for 0s 19 | When found check if they are part of a contiguous region 20 | This will check the 4 directions 21 | Keep track of the zeros we have found 22 | */ 23 | 24 | // Function to check if the current holes is part of a contiguous region 25 | // If so keep track of the zeros that are part of that region 26 | // It will recursively search in all 4 directions, not repeating the last step or any previous steps 27 | void groupSet(string arr[], int size, int row, int col, vector & list, bool check) 28 | { 29 | list[row][col] = '0'; 30 | bool found = check; 31 | 32 | while (found) 33 | { 34 | found = false; 35 | 36 | // Checking Up 37 | if (row != 0 && arr[row - 1][col] == '0' && list[row - 1][col] == '*') 38 | { 39 | // Update the movement 40 | row--; 41 | found = true; 42 | groupSet(arr, size, row, col, list, found); 43 | } 44 | // Checking Down 45 | if (row != size - 1 && arr[row + 1][col] == '0' && list[row + 1][col] == '*') 46 | { 47 | row++; 48 | found = true; 49 | groupSet(arr, size, row, col, list, found); 50 | } 51 | // Checking Left 52 | if (col != 0 && arr[row][col - 1] == '0' && list[row][col-1] == '*') 53 | { 54 | col--; 55 | found = true; 56 | groupSet(arr, size, row, col, list, found); 57 | } 58 | // Checking Right 59 | if (col != arr[0].length() - 1 && arr[row][col + 1] == '0' && list[row][col + 1] == '*') 60 | { 61 | col++; 62 | found = true; 63 | groupSet(arr, size, row, col, list, found); 64 | } 65 | } 66 | } 67 | 68 | int BitmapHoles(string strArr[], int size) { 69 | int holes = 0; 70 | 71 | vector tempMatrix(size); // Setting a secondary string/matrix for keeping track of connected groups 72 | 73 | // Setting temp values to our list 74 | for (int row = 0; row < size; row++) 75 | { 76 | for (int col = 0; col < strArr[row].length(); col++) 77 | { 78 | tempMatrix[row].push_back('*'); 79 | } 80 | } 81 | 82 | // Loop to find any 0s in the matrix 83 | for (int row = 0; row < size; row++) 84 | { 85 | for (int col = 0; col < strArr[row].length(); col++) 86 | { 87 | // Condition analyze the holes 88 | // Will ignore if the 0 found is part of contiguous region 89 | if (strArr[row][col] == '0' && tempMatrix[row][col] == '*') 90 | { 91 | // function call that will find if this current hole has contiguous zeros 92 | // It will fill out our temp matrix with any zeros that are contiguous 93 | // This will help iterating so we avoid counting any holes that are part of a contiguous family 94 | groupSet(strArr, size, row, col, tempMatrix, true); 95 | holes++; 96 | } 97 | } 98 | } 99 | 100 | return holes; 101 | } 102 | 103 | int main() 104 | { 105 | string A[] = { "01111", "01101", "00011", "11110" }; 106 | string B[] = { "1011", "0010" }; 107 | string C[] = { "10111", "10101", "11101", "11111" }; 108 | cout << BitmapHoles(A, sizeof(A) / sizeof(A[0])) << endl; // 3 109 | cout << BitmapHoles(B, sizeof(B) / sizeof(B[0])) << endl; // 2 110 | cout << BitmapHoles(C, sizeof(C) / sizeof(C[0])) << endl; // 2 111 | return 0; 112 | } -------------------------------------------------------------------------------- /35_MatchingCharacters.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be determining the largest number of unique characters between two letters. 2 | /* 3 | have the function MatchingCharacters(str) take the str parameter being passed and determine the largest number of unique characters that exists between a pair of matching letters anywhere in the string. For example: if str is "ahyjakh" then there are only two pairs of matching letters, the two a's and the two h's. Between the pair of a's there are 3 unique characters: h, y, and j. Between the h's there are 3 unique characters: y, j, a, and k. So for this example your program should return 4. 4 | 5 | Another example: if str is "ghececgkaem" then your program should return 5 because the most unique characters exists within the farthest pair of e characters. The input string may not contain any character pairs, and in that case your program should just return 0. The input will only consist of lowercase alphabetic characters. 6 | */ 7 | 8 | 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | int MatchingCharacters(string str) 14 | { 15 | int high = 0; 16 | for (int x = 0; x < str.length(); x++) 17 | { 18 | // Values used to locate a pair 19 | char temp = str[x]; 20 | int start = x; 21 | int end=start; 22 | 23 | for (int y = x + 1; y < str.length(); y++) 24 | { 25 | // Locate the end of that pair 26 | if (str[y] == temp) 27 | { 28 | end = y; 29 | } 30 | } 31 | 32 | // Loop to check for unique characters within that pair 33 | string uniqueValues; 34 | for (int z = start+1; z < end; z++) 35 | { 36 | // If the character is unique add it to our list 37 | if (uniqueValues.find(str[z]) == -1) 38 | { 39 | uniqueValues += str[z]; 40 | } 41 | } 42 | 43 | // Keep track of the largest number of unique characters 44 | if (uniqueValues.length() > high) 45 | { 46 | high = uniqueValues.length(); 47 | } 48 | } 49 | 50 | return high; 51 | } 52 | 53 | int main() 54 | { 55 | cout << MatchingCharacters("ahyjakh") << endl; // 4 56 | cout << MatchingCharacters("ghececgkaem") << endl; // 5 57 | cout << MatchingCharacters("mmmerme") << endl; // 3 58 | cout << MatchingCharacters("abccdefghi") << endl; // 0 59 | 60 | return 0; 61 | } -------------------------------------------------------------------------------- /36_NearestSmallerValues.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine the nearest smaller value for each number in an array. 2 | /* 3 | have the function NearestSmallValues(arr) take the array of integers stored in arr, and for each element in the list, search all the previous values for the nearest element that is smaller than the current element and create a new list from these numbers. If there is no element before a certain position that is smaller, input a -1. For example: if arr is [5, 2, 8, 3, 9, 12] then the nearest smaller values list is [-1, -1, 2, 2, 3, 9]. The logic is as follows: 4 | 5 | For 5, there is no smaller previous value so the list so far is [-1]. For 2, there is also no smaller previous value, so the list is now [-1, -1]. For 8, the nearest smaller value is 2 so the list is now [-1, -1, 2]. For 3, the nearest smaller value is also 2, so the list is now [-1, -1, 2, 2]. This goes on to produce the answer above. Your program should take this final list and return the elements as a string separated by a space: -1 -1 2 2 3 9 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | /* 15 | iterate through each value 16 | iterate backwards and find any smaller values 17 | if none found insert -1 else, insert that small value 18 | convert the new list to a string 19 | */ 20 | 21 | string NearestSmallerValues(int arr[], int size) 22 | { 23 | vector list; 24 | 25 | // Loop to iterate through each value 26 | for (int x = 0; x < size; x++) 27 | { 28 | bool found = false; 29 | 30 | // Nested loop checking for any previous smaller values 31 | for (int y = x - 1; y >= 0 && !found; y--) 32 | { 33 | if (arr[y] < arr[x]) 34 | { 35 | list.push_back(arr[y]); 36 | found = true; 37 | } 38 | } 39 | 40 | // Condition for when no smaller values were found we insert -1 41 | if (!found) 42 | { 43 | list.push_back(-1); 44 | } 45 | } 46 | 47 | // Taking the values from our list and formatting to a string 48 | stringstream convert; 49 | for (int x = 0; x < size; x++) 50 | { 51 | convert << list[x] << " "; 52 | } 53 | 54 | return convert.str(); 55 | } 56 | 57 | int main() 58 | { 59 | int A[] = { 5, 2, 8, 3, 9, 12 }; 60 | int B[] = { 5, 3, 1, 9, 7, 3, 4, 1 }; 61 | int C[] = { 2, 4, 5, 1, 7 }; 62 | cout << NearestSmallerValues(A, sizeof(A) / sizeof(A[0])) << endl; // -1 -1 2 2 3 9 63 | cout << NearestSmallerValues(B, sizeof(B) / sizeof(B[0])) << endl; // -1 -1 -1 1 1 1 3 1 64 | cout << NearestSmallerValues(C, sizeof(C) / sizeof(C[0])) << endl; // -1 2 4 -1 1 65 | return 0; 66 | 67 | } -------------------------------------------------------------------------------- /37_ArrayMinJumps.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine how quickly you can reach the end of an array. 2 | /* 3 | have the function ArrayMinJumps(arr) take the array of integers stored in arr, where each integer represents the maximum number of steps that can be made from that position, and determine the least amount of jumps that can be made to reach the end of the array. For example: if arr is 4 | [1, 5, 4, 6, 9, 3, 0, 0, 1, 3] then your program should output the number 3 because you can reach the end of the array from the beginning via the following steps: 5 | 1 -> 5 -> 9 -> END or 1 -> 5 -> 6 -> END. Both of these combinations produce a series of 3 steps. And as you can see, you don't always have to take the maximum number of jumps at a specific position, you can take less jumps even though the number is higher. 6 | 7 | If it is not possible to reach the end of the array, return -1. 8 | */ 9 | 10 | #include 11 | using namespace std; 12 | 13 | /* 14 | start at the first index 15 | have a condition to check if taking 1 step is enough 16 | or if starting value is <= 0 17 | 18 | traverse however many steps the current location provides 19 | as we traverse we analyze the values along the way 20 | collect the sum of current value + lastValue 21 | if >= end, return the result 22 | else record the result and check if is the highest possible. 23 | */ 24 | int ArrayMinJumps(int arr[], int size) 25 | { 26 | int result = 1; 27 | int totalSteps = arr[0]; 28 | int index = 0; 29 | int highest; 30 | 31 | // base case conditions 32 | if (size == 1 && arr[0] > 0) 33 | { 34 | return 0; 35 | } 36 | else if (totalSteps >= size-1) 37 | { 38 | return result; 39 | } 40 | else if (totalSteps <= 0) 41 | { 42 | return -1; 43 | } 44 | 45 | // analyzing the values 46 | while (index < size) 47 | { 48 | // updating our jump/step count 49 | result++; 50 | 51 | // analyzing the values during our movement 52 | for (int x = 0; x < totalSteps; x++) 53 | { 54 | index++; 55 | 56 | if (x == 0) 57 | { 58 | highest = index; 59 | } 60 | 61 | // condition to check if current value is enough to reach the end 62 | if (index + arr[index] >= size-1) 63 | { 64 | return result; 65 | } 66 | // condition to locate the best selection we can make 67 | else if (index + arr[index] >= arr[highest] + index) 68 | { 69 | highest = index; 70 | } 71 | } 72 | 73 | // updating our index and totalSteps 74 | index = highest; 75 | totalSteps = arr[index]; 76 | 77 | // check if is possible to make jumps 78 | if (totalSteps == 0) 79 | { 80 | return -1; 81 | } 82 | } 83 | 84 | return result; 85 | } 86 | 87 | int main() 88 | { 89 | int A[] = { 1, 5, 4, 6, 9, 3, 0, 0, 1, 3 }; 90 | int B[] = { 3, 4, 2, 1, 1, 100 }; 91 | int C[] = { 1, 3, 6, 8, 2, 7, 1, 2, 1, 2, 6, 1, 2, 1, 2 }; 92 | int D[] = { 4, 5, 2, 1, 5, 3, 1, 4, 6, 2, 1, 0, 1, 0, 4, 3, 0, 1, 2, 4, 5 }; 93 | int E[] = { 1, 0, 0, 2 }; 94 | int F[] = { 4 }; 95 | int G[] = {1,1}; 96 | 97 | cout << ArrayMinJumps(A, sizeof(A)/sizeof(A[0])) << endl; // 3 98 | cout << ArrayMinJumps(B, sizeof(B) / sizeof(B[0])) << endl; // 2 99 | cout << ArrayMinJumps(C, sizeof(C) / sizeof(C[0])) << endl; // 4 100 | cout << ArrayMinJumps(D, sizeof(D) / sizeof(D[0])) << endl; // 5 101 | cout << ArrayMinJumps(F, sizeof(F) / sizeof(F[0])) << endl; // 0 102 | cout << ArrayMinJumps(G, sizeof(G) / sizeof(G[0])) << endl; // 1 103 | cout << ArrayMinJumps(E, sizeof(E) / sizeof(E[0])) << endl; // -1 104 | 105 | return 0; 106 | } -------------------------------------------------------------------------------- /38_PalindromicSubstring.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be finding the longest palindromic substring. 2 | /* 3 | have the function PalindromicSubstring(str) take the str parameter being passed and find the longest palindromic substring, which means the longest substring which is read the same forwards as it is backwards. For example: if str is "abracecars" then your program should return the string racecar because it is the longest palindrome within the input string. 4 | 5 | The input will only contain lowercase alphabetic characters. The longest palindromic substring will always be unique, but if there is none that is longer than 2 characters, return the string none. 6 | */ 7 | 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | /* 13 | Loop through the string 14 | analyze sub strings with more than 3 characters 15 | continue to analyze from that index 16 | keep track of the longest palindrome and repeat the steps 17 | */ 18 | 19 | // Function checking for palindrome 20 | bool palindrome(string value) 21 | { 22 | int index = value.length() - 1; 23 | 24 | for (int x = 0; x < value.length() / 2; x++) 25 | { 26 | if (value[x] != value[index]) 27 | { 28 | return false; 29 | } 30 | index--; 31 | } 32 | 33 | return true; 34 | } 35 | 36 | 37 | string PalindromicSubstring(string str) 38 | { 39 | string temp; 40 | string result; 41 | 42 | for (int x = 0; x < str.length(); x++) 43 | { 44 | temp = str[x]; 45 | 46 | // Loop to check for a substring palindrome 47 | for (int y = x + 1; y < str.length(); y++) 48 | { 49 | temp += str[y]; 50 | 51 | // Only analyze when we have at least 3 characters and the substring is a palindrome 52 | if (temp.length() >= 3 && palindrome(temp)) 53 | { 54 | // Keep track of the longest palindrome substring 55 | if (temp.length() > result.length()) 56 | { 57 | result = temp; 58 | } 59 | } 60 | 61 | } 62 | } 63 | 64 | if (result.length() == 0) 65 | { 66 | return "none"; 67 | } 68 | else 69 | { 70 | return result; 71 | } 72 | } 73 | 74 | 75 | int main() 76 | { 77 | cout << PalindromicSubstring("abracecars") << endl; // racecar 78 | cout << PalindromicSubstring("hellosannasmith") << endl; // sannas 79 | cout << PalindromicSubstring("abcdefgg") << endl; // none 80 | cout << PalindromicSubstring("acaaca") << endl; // acaaca 81 | 82 | return 0; 83 | } -------------------------------------------------------------------------------- /39_WordSplit.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will attempt to split a long string of characters into actual words. 2 | /* 3 | have the function WordSplit(strArr) read the array of strings stored in strArr, which will contain 2 elements: the first element will be a sequence of characters, and the second element will be a long string of comma-separated words, in alphabetical order, that represents a dictionary of some arbitrary length. For example: strArr can be: ["hellocat", "apple,bat,cat,goodbye,hello,yellow,why"]. Your goal is to determine if the first element in the input can be split into two words, where both words exist in the dictionary that is provided in the second input. In this example, the first element can be split into two words: hello and cat because both of those words are in the dictionary. 4 | 5 | Your program should return the two words that exist in the dictionary separated by a comma. So for the example above, your program should return hello,cat. There will only be one correct way to split the first element of characters into two words. If there is no way to split string into two words that exist in the dictionary, return the string not possible. The first element itself will never exist in the dictionary as a real word. 6 | */ 7 | 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | /* 13 | extract the first element to use for comparison 14 | analyze each word separated by comma 15 | check if the first half of the target word can be found 16 | if so, now search for the second half in the dictionary 17 | if the first half was not found we can conclude it does not exist 18 | */ 19 | 20 | string WordSplit(string strArr[]) 21 | { 22 | string target = strArr[0]; 23 | string temp,temp2,result; 24 | bool valid; 25 | int index; 26 | 27 | // Loop to analyze each word separated by a comma in the second element/dictionary 28 | for (int x = 0; x < strArr[1].length(); x++) 29 | { 30 | valid = true; 31 | 32 | // Condition to check for first half 33 | // We also reset out comparison word/first half in the case we have not found one yet 34 | if (strArr[1][x] == ',' || x == strArr[1].length()-1) 35 | { 36 | // In case we are working with the last split word in our dictionary 37 | // Add that last character to our split word 38 | if (x == strArr[1].length() - 1) 39 | { 40 | temp += strArr[1][x]; 41 | } 42 | 43 | // Loop to compare the first half with our target world 44 | for (int y = 0; y < temp.length(); y++) 45 | { 46 | if (target[y] != temp[y]) 47 | { 48 | valid = false; 49 | } 50 | } 51 | 52 | // Reset the word if not found 53 | if (!valid) 54 | { 55 | temp = ""; 56 | } 57 | else 58 | { 59 | index = temp.length(); // Keeps track of where we need to continue for comparing the second half 60 | 61 | // Checks for the second half 62 | for (int z = 0; z < strArr[1].length(); z++) 63 | { 64 | // Similar condition for when analyzing the first half 65 | // The commas signify a new split word we can evaluate 66 | if (strArr[1][z] == ',' || z == strArr[1].length() - 1) 67 | { 68 | if (z == strArr[1].length() - 1) 69 | { 70 | temp2 += strArr[1][z]; 71 | } 72 | 73 | // Comparing for the second half 74 | // Assuming the second half exist but we failed, this implies we evaluated the wrong first half 75 | // The other scenario is that no second half is found at all 76 | 77 | int size; 78 | 79 | // Condition to check if the second half will be a valid case with current first half 80 | // For example if the length of the 2 split words surpasses the target word ignore that case 81 | if (target.length() - index == temp2.length()) 82 | { 83 | size = temp2.length(); 84 | } 85 | else 86 | { 87 | temp2 = ""; 88 | continue; 89 | } 90 | 91 | 92 | for (int i = index, k=0; i < size; i++, k++) 93 | { 94 | if (target[i] != temp2[k]) 95 | { 96 | valid = false; 97 | } 98 | } 99 | 100 | if (!valid) 101 | { 102 | temp2 = ""; 103 | } 104 | else 105 | { 106 | // Check that our 2 split words match the target 107 | result = temp+temp2; 108 | 109 | if (result == target) 110 | { 111 | result = temp + "," + temp2; 112 | return result; 113 | } 114 | else 115 | { 116 | temp2 = ""; 117 | } 118 | } 119 | } 120 | else 121 | { 122 | temp2 += strArr[1][z]; 123 | } 124 | } 125 | temp = ""; // Reset in the case the second half failed 126 | } 127 | 128 | } 129 | else // Continue to extract characters before reaching the next comma or the end 130 | { 131 | temp += strArr[1][x]; 132 | } 133 | } 134 | 135 | return "not possible"; 136 | } 137 | 138 | int main() 139 | { 140 | string A[] = { "hellocat", "apple,bat,cat,goodbye,hello,yellow,why"}; 141 | string B[] = { "baseball", "a,all,b,ball,bas,base,cat,code,d,e,quit,z"}; 142 | string C[] = { "abcgefd", "a,ab,abc,abcg,b,c,dog,e,efd,zzzz"}; 143 | string D[] = { "test", "t,ab,abc,abcg,b,c,dog,e,efd,zzzz" }; 144 | string E[] = { "abbbbcd", "a,ab,b,bbbcd,c,d,dog,elf,f,farm,go,goal,hello"}; 145 | string F[] = { "az", "a,b,c,d,e,f,farm,g,goal,hello,world,x,y,z,zzzz" }; 146 | 147 | 148 | cout << WordSplit(A) << endl; // hello,cat 149 | cout << WordSplit(B) << endl; // base,ball 150 | cout << WordSplit(C) << endl; // abcg,efd 151 | cout << WordSplit(D) << endl; // not possible 152 | cout << WordSplit(E) << endl; // ab,bbbcd 153 | cout << WordSplit(F) << endl; // a,z 154 | return 0; 155 | } -------------------------------------------------------------------------------- /3_PrimeMover.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be returning a certain prime number. 2 | // have the function PrimeMover(num) return the numth prime number. The range will be from 1 to 10^4. For example: if num is 16 the output should be 53 as 53 is the 16th prime number. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | int PrimeMover(int num) { 9 | 10 | int count = 0; 11 | bool prime; 12 | 13 | for (int x = 2; x <= pow(10, 4); x++) 14 | { 15 | // If the number is greater than 100 16 | // Check if there are any divisors 17 | if (x > 100) 18 | { 19 | prime = true; 20 | for (int y = 2; y < pow(10, 4); y++) 21 | { 22 | // Ignore when the divisor is the same as the number 23 | if (y == x) 24 | { 25 | continue; 26 | } 27 | else if (x % y == 0) // If there is a number end the loop and signify that it is not prime 28 | { 29 | prime = false; 30 | break; 31 | } 32 | } 33 | 34 | if (prime) 35 | { 36 | count++; 37 | } 38 | } 39 | else if (x > 10 && x<100 && !(x % 2 == 0 || x % 3 == 0 || x % 5 == 0 || x % 7 == 0 || x % 9 == 0)) 40 | { 41 | count++; 42 | } 43 | else if (x == 2 || x == 3 || x == 5 || x == 7) 44 | { 45 | count++; 46 | } 47 | 48 | if (count == num) 49 | { 50 | return x; 51 | } 52 | } 53 | } 54 | 55 | int main() { 56 | 57 | // keep this function call here 58 | cout << PrimeMover(9) << endl; // 23 59 | cout << PrimeMover(1000) << endl; // 541 60 | cout << PrimeMover(16) << endl; // 53 61 | return 0; 62 | 63 | } -------------------------------------------------------------------------------- /40_MinWindowSubstring.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be searching for the optimal substring of k characters. 2 | /* 3 | have the function MinWindowSubstring(strArr) take the array of strings stored in strArr, which will contain only two strings, the first parameter being the string N and the second parameter being a string K of some characters, and your goal is to determine the smallest substring of N that contains all the characters in K. For example: if strArr is ["aaabaaddae", "aed"] then the smallest substring of N that contains the characters a, e, and d is "dae" located at the end of the string. So for this example your program should return the string dae. 4 | 5 | Another example: if strArr is ["aabdccdbcacd", "aad"] then the smallest substring of N that contains all of the characters in K is "aabd" which is located at the beginning of the string. Both parameters will be strings ranging in length from 2 to 50 characters and all of K's characters will exist somewhere in the string N. Both strings will only contains lowercase alphabetic characters. 6 | */ 7 | 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | /* 13 | get the target string which is the second element 14 | analyze the first element to find the substring 15 | you will iterate through each character and check if the substring from that specified character contains all characters from the target 16 | check the length of the substrings and keep track of the smallest one 17 | */ 18 | 19 | 20 | // function to check if the current substring has all the characters from the target string 21 | bool stringSearch(string current, string value) 22 | { 23 | // The current string must be either same length or greater than the target string 24 | if (current.length() < value.length()) 25 | { 26 | return false; 27 | } 28 | 29 | // loop to check that the characters are found in the substring 30 | for (int x = 0; x < value.length(); x++) 31 | { 32 | bool found = false; 33 | for (int y = 0; y < current.length(); y++) 34 | { 35 | // Condition that checks for characters found 36 | // If found update the current and remove the character 37 | // This will help in the case we search for similar characters i.e aaaab 38 | if (value[x] == current[y]) 39 | { 40 | current.erase(current.begin() + y); 41 | found = true; 42 | break; 43 | } 44 | } 45 | 46 | if (!found) 47 | { 48 | return false; 49 | } 50 | } 51 | 52 | return true; 53 | } 54 | 55 | string MinWindowSubstring(string strArr[]) 56 | { 57 | string target = strArr[1]; 58 | string temp, result; 59 | int low = 100 * 100; 60 | 61 | for (int x = 0; x < strArr[0].length()-1; x++) 62 | { 63 | temp += strArr[0][x]; 64 | for (int y = x + 1; y < strArr[0].length(); y++) 65 | { 66 | // Condition to check if the substring is valid 67 | if (stringSearch(temp, target)) 68 | { 69 | if (temp.length() < low) // Keep track of the smallest substring 70 | { 71 | low = temp.length(); 72 | result = temp; 73 | } 74 | 75 | break; 76 | } 77 | else // Keep updating if not valid 78 | { 79 | temp += strArr[0][y]; 80 | } 81 | 82 | // Condition for when analyzing the last character of our substring 83 | if (y == strArr[0].length() - 1 && stringSearch(temp, target)) 84 | { 85 | if (temp.length() < low) // Keep track of the smallest substring 86 | { 87 | low = temp.length(); 88 | result = temp; 89 | } 90 | } 91 | } 92 | temp = ""; // reset our substring for our next starting character 93 | } 94 | 95 | return result; 96 | } 97 | 98 | int main() 99 | { 100 | string A[] = { "aaabaaddae", "aed" }; 101 | string B[] = { "aabdccdbcacd", "aad" }; 102 | string C[] = { "ahffaksfajeeubsne", "jefaa" }; 103 | string D[] = { "aaffhkksemckelloe", "fhea" }; 104 | cout << MinWindowSubstring(A) << endl; // dae 105 | cout << MinWindowSubstring(B) << endl; // aabd 106 | cout << MinWindowSubstring(C) << endl; // aksfaje 107 | cout << MinWindowSubstring(D) << endl; // affhkkse 108 | return 0; 109 | } 110 | -------------------------------------------------------------------------------- /41_TrappingWater.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine the largest amount of water you can trap within a boundary. 2 | /* 3 | have the function TrappingWater(arr) take the array of non-negative integers stored in arr, and determine the largest amount of water that can be trapped. The numbers in the array represent the height of a building (where the width of each building is 1) and if you imagine it raining, water will be trapped between the two tallest buildings. For example: if arr is [3, 0, 0, 2, 0, 4] then this array of building heights looks like the following picture if we draw it out: 4 | 5 | Now if you imagine it rains and water gets trapped in this picture, then it'll look like the following (the x's represent water): 6 | 7 | 8 | This is the most water that can be trapped in this picture, and if you calculate the area you get 10, so your program should return 10. 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | /* 15 | find the highest peak 16 | after find the next highest peak 17 | analyze the distance between the peaks 18 | this will allow us to trap the most amount of water 19 | once we have a starting and end point we can iterate and calculate area 20 | compare each step to the second highest peak 21 | example if the second peak is 4 and our current step is 1 than area for that step is 3 22 | continue until we reach the end 23 | sum up all the individual area to get total area 24 | */ 25 | 26 | int TrappingWater(int arr[], int size) 27 | { 28 | int high, high2; 29 | int index, index2; 30 | high = high2 = 0; 31 | 32 | // Loop to find the highest peak 33 | for (int x = 0; x < size; x++) 34 | { 35 | if (arr[x] >= high) 36 | { 37 | high = x; 38 | index = x; 39 | } 40 | } 41 | 42 | // Loop to find the second highest peak 43 | for (int x = 0; x < size; x++) 44 | { 45 | if (x == index) 46 | { 47 | continue; 48 | } 49 | 50 | if (arr[x] > high2) 51 | { 52 | high2 = arr[x]; 53 | index2 = x; 54 | } 55 | } 56 | 57 | // Analyzing the distance 58 | while ((index - index2) == 1) 59 | { 60 | // The second peak now becomes the highest peak 61 | int temp = index; 62 | high = high2; 63 | index = index2; 64 | 65 | // We iterate to find a new second peak 66 | high2 = 0; 67 | for (int x = 0; x < size; x++) 68 | { 69 | if (x == index || x == temp) 70 | { 71 | continue; 72 | } 73 | 74 | if (arr[x] > high2) 75 | { 76 | high2 = arr[x]; 77 | index2 = x; 78 | } 79 | } 80 | } 81 | 82 | int total = 0; 83 | // Loop to find the area of each step 84 | for (int x = index2 + 1; x < index; x++) 85 | { 86 | total += (high2 - arr[x]) * 1; 87 | } 88 | 89 | return total; 90 | } 91 | 92 | int main() 93 | { 94 | int A[] = { 3, 0, 0, 2, 0, 4 }; 95 | int B[] = { 1, 2, 1, 2 }; 96 | int C[] = { 0, 2, 4, 0, 2, 1, 2, 6 }; 97 | int D[] = { 5, 4, 3, 2, 1, 10, 20 }; 98 | 99 | cout << TrappingWater(A, sizeof(A)/sizeof(A[0])) << endl; // 10 100 | cout << TrappingWater(B, sizeof(B) / sizeof(B[0])) << endl; // 1 101 | cout << TrappingWater(C, sizeof(C) / sizeof(C[0])) << endl; // 11 102 | cout << TrappingWater(D, sizeof(D) / sizeof(D[0])) << endl; // 10 103 | return 0; 104 | } 105 | -------------------------------------------------------------------------------- /42_SeatingStudents.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine how many different ways students can sit next to each other. 2 | /* 3 | have the function SeatingStudents(arr) read the array of integers stored in arr which will be in the following format: 4 | [K, r1, r2, r3, ...] where K represents the number of desks in a classroom, and the rest of the integers in the array will be in sorted order and will represent the desks that are already occupied. All of the desks will be arranged in 2 columns, where desk #1 is at the top left, desk #2 is at the top right, desk #3 is below #1, desk #4 is below #2, etc. Your program should return the number of ways 2 students can be seated next to each other. This means 1 student is on the left and 1 student on the right, or 1 student is directly above or below the other student. 5 | 6 | For example: if arr is [12, 2, 6, 7, 11] then this classrooms looks like the following picture: 7 | 8 | 1 ~2 9 | 3 4 10 | 5 ~6 11 | ~7 8 12 | 9 10 13 | ~11 12 14 | 15 | Based on above arrangement of occupied desks, there are a total of 6 ways to seat 2 new students next to each other. The combinations are: [1, 3], [3, 4], [3, 5], [8, 10], [9, 10], [10, 12]. So for this input your program should return 6. K will range from 2 to 24 and will always be an even number. After K, the number of occupied desks in the array can range from 0 to K. 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | using namespace std; 22 | 23 | /* 24 | get the number of total seats 25 | setup the seating into a 2 dimensional array 26 | marked down which seats have already been taken 27 | iterate through the 2D array and check which seats are open for 2 new students 28 | they must be next to each other 29 | keep track of the total number of combinations 30 | */ 31 | 32 | int SeatingStudents(int arr[], int size) 33 | { 34 | int total = arr[0]; 35 | 36 | vector > list; // will contain the desk layout of the classroom 37 | vector > result; // will contain all the combinations 38 | int seat = 1; 39 | 40 | // Loop to fill out the new list with the seating format required 41 | for (int x = 0; x < total/2; x++) 42 | { 43 | vector temp; 44 | list.push_back(temp); 45 | 46 | // Keeps track of the correct desk number on based on a 2 column layout 47 | if (seat <= total) 48 | { 49 | for (int y = 0; y < 2; y++, seat++) 50 | { 51 | list[x].push_back(seat); 52 | } 53 | } 54 | } 55 | 56 | // Marking down the seats that are already taken 57 | // Will also check for any combination of open seats where 2 new students can seat 58 | int resultSize = -1; 59 | for (int row = 0; row < list.size(); row++) 60 | { 61 | vector temp2; 62 | 63 | for (int col = 0; col < 2; col++) 64 | { 65 | for (int z = 1; z < size; z++) 66 | { 67 | // Conditions to signify a taken seat 68 | if (arr[z] == list[row][col]) 69 | { 70 | list[row][col] = -1; 71 | } 72 | 73 | // Bound checking 74 | if (row != list.size() - 1 && arr[z] == list[row + 1][col]) 75 | { 76 | list[row + 1][col] = -1; 77 | } 78 | } 79 | } 80 | 81 | // Condition to check if the desk/seats are open for the new students to seat next to each other 82 | // If a combination is found it will add it to our new 2D list 83 | // The size of our new list will represent the total number of combinations found 84 | if (list[row][0] != -1 && list[row][1] != -1) 85 | { 86 | result.push_back(temp2); 87 | resultSize++; // Used to keep track of our current row 88 | result[resultSize].push_back(list[row][0]); 89 | result[resultSize].push_back(list[row][1]); 90 | } 91 | 92 | // Simple bound checking 93 | if (row != list.size() - 1) // Analyzing any row not including the last row 94 | { 95 | if (list[row][0] != -1 && list[row + 1][0] != -1) 96 | { 97 | result.push_back(temp2); 98 | resultSize++; 99 | result[resultSize].push_back(list[row][0]); 100 | result[resultSize].push_back(list[row + 1][0]); 101 | } 102 | 103 | if (list[row][1] != -1 && list[row + 1][1] != -1) 104 | { 105 | result.push_back(temp2); 106 | resultSize++; 107 | result[resultSize].push_back(list[row][1]); 108 | result[resultSize].push_back(list[row + 1][1]); 109 | } 110 | } 111 | } 112 | 113 | return result.size(); 114 | } 115 | 116 | int main() 117 | { 118 | int A[] = { 12, 2, 6, 7, 11 }; 119 | int B[] = { 6, 4 }; 120 | int C[] = { 8, 1, 8 }; 121 | 122 | cout << SeatingStudents(A, sizeof(A) / sizeof(A[0])) << endl; // 6 123 | cout << SeatingStudents(B, sizeof(B) / sizeof(B[0])) << endl; // 4 124 | cout << SeatingStudents(C, sizeof(C) / sizeof(C[0])) << endl; // 6 125 | return 0; 126 | 127 | } -------------------------------------------------------------------------------- /43_PairSearching.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine how to multiply a number to find a duplicate pair. 2 | /* 3 | have the function PairSearching(num) take the num parameter being passed and perform the following steps. First take all the single digits of the input number (which will always be a positive integer greater than 1) and add each of them into a list. Then take the input number and multiply it by any one of its own integers, then take this new number and append each of the digits onto the original list. Continue this process until an adjacent pair of the same number appears in the list. Your program should return the least number of multiplications it took to find an adjacent pair of duplicate numbers. 4 | 5 | For example: if num is 134 then first append each of the integers into a list: [1, 3, 4]. Now if we take 134 and multiply it by 3 (which is one of its own integers), we get 402. Now if we append each of these new integers to the list, we get: [1, 3, 4, 4, 0, 2]. We found an adjacent pair of duplicate numbers, namely 4 and 4. So for this input your program should return 1 because it only took 1 multiplication to find this pair. 6 | 7 | Another example: if num is 46 then we append these integers onto a list: [4, 6]. If we multiply 46 by 6, we get 276, and appending these integers onto the list we now have: [4, 6, 2, 7, 6]. Then if we take this new number, 276, and multiply it by 2 we get 552. Appending these integers onto the list we get: [4, 6, 2, 7, 6, 5, 5, 2]. Your program should therefore return 2 because it took 2 multiplications to find a pair of adjacent duplicate numbers (5 and 5 in this case). 8 | */ 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | using namespace std; 16 | 17 | /* 18 | will be a BFS approach to analyze the possible paths 19 | first we create a list from input number 20 | we keep a record of list, number, and multiplication count 21 | following the rules we traverse each value of current list and multiply it to the number 22 | each possible scenario will be treated as a path we can take 23 | at each scenario we checking if current list has adjacent pairs 24 | we continue the traversal until an adjacent pair is found 25 | */ 26 | 27 | // method to check if our current list has any adjacent pairs 28 | bool findPair(vector list) 29 | { 30 | for (int x = 0; x < list.size() - 1; x++) 31 | { 32 | if (list[x] == list[x + 1]) 33 | { 34 | return true; 35 | } 36 | } 37 | return false; 38 | } 39 | 40 | // helper function which will break the number down and add its digits to the list 41 | vector getList(int num) 42 | { 43 | vector list; 44 | 45 | while (num) 46 | { 47 | int temp = num % 10; 48 | 49 | list.push_back(temp); 50 | 51 | num /= 10; 52 | } 53 | 54 | reverse(list.begin(), list.end()); 55 | 56 | return list; 57 | } 58 | 59 | int PairSearching(int num) 60 | { 61 | // initial starting values 62 | vector startingList; 63 | vector values; 64 | values.push_back(num); 65 | values.push_back(0); 66 | 67 | map< vector, vector > startingTable; 68 | startingTable[startingList] = values; 69 | 70 | queue< map< vector, vector > > listPair; 71 | listPair.push(startingTable); 72 | 73 | // BFS traversal 74 | while (!listPair.empty()) 75 | { 76 | // getting the current list with its state 77 | map< vector, vector > tablePair = listPair.front(); 78 | 79 | // list of integers 80 | vector currentList; 81 | 82 | // current number 83 | int currentTotal; 84 | 85 | // multiplication count 86 | int currentCount; 87 | 88 | // getting the current content (list,number,count) 89 | for (auto x = tablePair.begin(); x != tablePair.end(); x++) 90 | { 91 | currentList = x->first; 92 | currentTotal = x->second[0]; 93 | currentCount = x->second[1]; 94 | } 95 | 96 | // appending the new integers to the list 97 | vector temp = getList(currentTotal); 98 | for (int x = 0; x < temp.size(); x++) 99 | { 100 | currentList.push_back(temp[x]); 101 | } 102 | 103 | listPair.pop(); 104 | 105 | // checking if current list of integers has adjacent pair 106 | if (findPair(currentList)) 107 | { 108 | return currentCount; 109 | } 110 | 111 | // traverse the current list to analyze each path 112 | for (int x = 0; x < currentList.size(); x++) 113 | { 114 | map< vector, vector > newTable; 115 | vector newItems; 116 | 117 | // updating our multiplication count and number value 118 | newItems.push_back(currentTotal * currentList[x]); 119 | newItems.push_back(currentCount + 1); 120 | newTable[currentList] = newItems; 121 | 122 | // adding new path to our queue 123 | listPair.push(newTable); 124 | } 125 | } 126 | } 127 | 128 | int main() 129 | { 130 | cout << PairSearching(134)<< endl; // 1 131 | cout << PairSearching(46)<< endl; // 2 132 | cout << PairSearching(8)<< endl; // 3 133 | cout << PairSearching(198)<< endl; // 2 134 | cout << PairSearching(2) << endl; // 3 135 | return 0; 136 | } -------------------------------------------------------------------------------- /44_HTMLElements.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine whether HTML elements are nested correctly. 2 | /* 3 | have the function HTMLElements(str) read the str parameter being passed which will be a string of HTML DOM elements and plain text. The elements that will be used are: b, i, em, div, p. For example: if str is "

hello world

" then this string of DOM elements is nested correctly so your program should return the string true. 4 | 5 | If a string is not nested correctly, return the first element encountered where, if changed into a different element, would result in a properly formatted string. If the string is not formatted properly, then it will only be one element that needs to be changed. For example: if str is "
helloworld" then your program should return the string div because if the first
element were changed into a , the string would be properly formatted. 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | /* 14 | only analyze html elements 15 | store the tags as they appear in order 16 | check the current open tag and make sure it has no errors 17 | continue iterating and analyze the other open tags 18 | remember an open tag must have a closing tag of its own 19 | */ 20 | 21 | bool search(vector list, int value) 22 | { 23 | for (int x = 0; x < list.size(); x++) 24 | { 25 | if (value == list[x]) 26 | { 27 | return true; 28 | } 29 | } 30 | return false; 31 | } 32 | 33 | string HTMLElements(string str) 34 | { 35 | vector elements; 36 | string temp; 37 | 38 | // Loop to extract the html elements 39 | for (int x = 0; x < str.length(); x++) 40 | { 41 | // marks the end of a tag that we must store in the list 42 | if (str[x] == '>' || x == str.length() - 1) 43 | { 44 | // Storing the last tag if is it a valid element 45 | if (x == str.length() - 1 && temp[0] == '<') 46 | { 47 | temp += str[x]; 48 | elements.push_back(temp); 49 | break; 50 | } 51 | 52 | if (temp[0] == '<') 53 | { 54 | temp += str[x]; 55 | elements.push_back(temp); 56 | } 57 | 58 | temp.clear(); // clear the string to create new valid elements 59 | } 60 | else if (str[x] == '<') 61 | { 62 | temp += str[x]; 63 | } 64 | else if (temp.length() > 0 && temp[0] == '<') 65 | { 66 | temp += str[x]; 67 | } 68 | } 69 | 70 | // In the case we only have one html element 71 | if (elements.size() == 1) 72 | { 73 | elements[0].erase(elements[0].begin()); 74 | elements[0].erase(elements[0].end() - 1); 75 | return elements[0]; 76 | } 77 | 78 | // Loop to analyze open tags 79 | // It will step through each tag and check for duplicates 80 | // If any are encountered we need to check they have their own closing tag 81 | for (int x = 0; x < elements.size()-1; x++) 82 | { 83 | // Condition to only analyze opening tags 84 | if (elements[x][1] != '/') 85 | { 86 | string temp = elements[x]; 87 | // Setting up the current open tag and correct closing tag to use for comparison 88 | string currentClose = temp.insert(1, "/"); 89 | string currentOpen = elements[x]; 90 | vector indexLocations; 91 | 92 | int close = 0; // Checks how many correct closing tags we have 93 | int closeNeeded = 1; // Details how many correct closing tags we currently need 94 | 95 | int index=x+1; 96 | 97 | // Loop to check for any elements similar to our current 98 | for (int y = x + 1; y < elements.size(); y++) 99 | { 100 | if (currentOpen == elements[y]) 101 | { 102 | // Update our need amount since we now have a duplicate that also requires a closing tag 103 | closeNeeded++; 104 | index = y; 105 | } 106 | } 107 | 108 | // Loop to check if the open tags were properly close 109 | for (int i = 1; i < closeNeeded; i++) 110 | { 111 | bool duplicateClose = false; 112 | for (index; index < elements.size(); index++) 113 | { 114 | // Check if a closing was found for the duplicate 115 | if (elements[index] == currentClose) 116 | { 117 | duplicateClose = true; 118 | 119 | indexLocations.push_back(index); 120 | // Update our index to avoid repeating the same closing tag 121 | index++; 122 | break; 123 | } 124 | } 125 | 126 | // Condition to check that the duplicate was correctly closed 127 | if (duplicateClose) 128 | { 129 | // Update our closing tag 130 | close++; 131 | } 132 | else 133 | { 134 | // Edit the string so we return the HTML element without the < > symbols 135 | currentOpen.erase(currentOpen.begin()); 136 | currentOpen.erase(currentOpen.end() - 1); 137 | return currentOpen; 138 | } 139 | } 140 | 141 | // After we analyze the duplicate, we check back on the current to find its closing pair 142 | for (int y = x + 1; y < elements.size(); y++) 143 | { 144 | // Condition to make sure that the closing tag we find has not been used previously 145 | if (elements[y] == currentClose && !(search(indexLocations, y))) 146 | { 147 | close++; 148 | break; 149 | } 150 | } 151 | 152 | // Condition to check that the current open tag was valid and had its closing tag 153 | // For example if we had 2 duplicates we need a total of 3 closing tags which includes one for the current also 154 | if (close != closeNeeded) 155 | { 156 | currentOpen.erase(currentOpen.begin()); 157 | currentOpen.erase(currentOpen.end()-1); 158 | return currentOpen; 159 | } 160 | } 161 | } 162 | 163 | return "true"; 164 | } 165 | 166 | int main() 167 | { 168 | cout << HTMLElements("

hello world

") << endl; // true 169 | cout << HTMLElements("
helloworld") << endl; // div 170 | cout << HTMLElements("

") << endl; // div 171 | cout << HTMLElements("
abc

test test test

") << endl; // i 172 | cout << HTMLElements("hello world

") << endl; // div 173 | cout << HTMLElements("
") << endl; // div 174 | cout << HTMLElements("

") << endl; // i 175 | cout << HTMLElements("

") << endl; // p 176 | 177 | return 0; 178 | } -------------------------------------------------------------------------------- /45_MatrixSpiral.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will print a 2D matrix in spiral order. 2 | /* 3 | have the function MatrixSpiral(strArr) read the array of strings stored in strArr which will represent a 2D N matrix, and your program should return the elements after printing them in a clockwise, spiral order. You should return the newly formed list of elements as a string with the numbers separated by commas. For example: if strArr is "[1, 2, 3]", "[4, 5, 6]", "[7, 8, 9]" then this looks like the following 2D matrix: 4 | 5 | 1 2 3 6 | 4 5 6 7 | 7 8 9 8 | 9 | 10 | 1 2 3 5 11 | 4 5 6 8 12 | 7 8 9 4 13 | 1 2 3 6 14 | 4 5 6 1 15 | 7 8 9 2 16 | 17 | So your program should return the elements of this matrix in a clockwise, spiral order which is: 1,2,3,6,9,8,7,4,5 18 | */ 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | using namespace std; 25 | 26 | 27 | /* 28 | only analyze number characters 29 | take the string data and create a new list of only numbers to better iterate later on 30 | check for the total numbers to help with the loop 31 | start on row 1 col 1 and iterate to right 32 | once you reach end of col update rows 33 | if is not first row take the last col value 34 | once you reach end row iterate to left 35 | update first and last rows again 36 | now repeat process but in reverse 37 | */ 38 | 39 | string MatrixSpiral(string strArr[], int size) 40 | { 41 | vector > list(size); 42 | string temp; 43 | int num; 44 | 45 | // Loop to create a new list of ints 46 | for (int row = 0; row < size; row++) 47 | { 48 | for (int col = 0; col < strArr[row].length(); col++) 49 | { 50 | // Condition to convert the string to int and add to the list 51 | if (strArr[row][col] == ',' || strArr[row][col] == ']') 52 | { 53 | istringstream(temp) >> num; 54 | list[row].push_back(num); 55 | temp.clear(); 56 | } 57 | // Create the string number 58 | else if (strArr[row][col] >= '0' & strArr[row][col] <= '9') 59 | { 60 | temp += strArr[row][col]; 61 | } 62 | } 63 | } 64 | 65 | // We provide the total amount of numbers in the matrix. 66 | int total = size * list[0].size(); 67 | int start = 0; 68 | 69 | // Will represent the parent row and col 70 | int first = 0; 71 | int last = size; 72 | 73 | // Will represent the child row and col 74 | // These are our current location 75 | int row = 0; 76 | int col = 0; 77 | 78 | // Will represent the length our columns are when analyzed 79 | int colStart = 0; 80 | int colEnd = list[0].size(); 81 | 82 | // Signals to determine how we iterate 83 | bool down, up; 84 | 85 | string result; 86 | 87 | // Spiral cycle 88 | while (start < total) 89 | { 90 | // When we are dealing with the parent first row 91 | // We iterate to the right 92 | if (row == first) 93 | { 94 | stringstream convert; 95 | convert << list[row][col]; 96 | result += convert.str(); 97 | result += ','; 98 | 99 | // Condition to check if we have reached the current column end 100 | // Iterate to the right 101 | if (col + 1 < colEnd) 102 | { 103 | col++; 104 | } 105 | else 106 | { 107 | // Update our last row and col end 108 | // Also signal that we now go down 109 | last--; 110 | row++; 111 | colEnd--; 112 | down = true; 113 | up = false; 114 | } 115 | } 116 | // Condition when we reach the parent last row 117 | else if (row == last) 118 | { 119 | stringstream convert; 120 | convert << list[row][col]; 121 | result += convert.str(); 122 | result += ','; 123 | 124 | // Iterate to the left 125 | if (col - 1 >= colStart) 126 | { 127 | col--; 128 | } 129 | else 130 | { 131 | // Update our first row and column start 132 | // Signal that we now go up 133 | first++; 134 | row--; 135 | colStart++; 136 | up = true; 137 | down = false; 138 | } 139 | } 140 | else if (down) // Going down we just take the last value of that row based on column length we set up 141 | { 142 | stringstream convert; 143 | convert << list[row][col]; 144 | result += convert.str(); 145 | result += ','; 146 | row++; 147 | } 148 | else if (up) // Going down we take the first value of that row based on column lenght we set up 149 | { 150 | stringstream convert; 151 | convert << list[row][col]; 152 | result += convert.str(); 153 | result += ','; 154 | row--; 155 | } 156 | 157 | start++; 158 | } 159 | 160 | // Erasing the comma at the end 161 | result.erase(result.end() - 1); 162 | 163 | return result; 164 | } 165 | 166 | int main() 167 | { 168 | string A[] = { "[1, 2, 3]", "[4, 5, 6]", "[7, 8, 9]" }; 169 | string B[] = { "[1, 2]", "[10, 14]" }; 170 | string C[] = { "[4, 5, 6, 5]", "[1, 1, 2, 2]", "[5, 4, 2, 9]" }; 171 | 172 | cout << MatrixSpiral(A, sizeof(A)/sizeof(A[0])) << endl; // 1,2,3,6,9,8,7,4,5 173 | cout << MatrixSpiral(B, sizeof(B) / sizeof(B[0])) << endl; // 1,2,14,10 174 | cout << MatrixSpiral(C, sizeof(C) / sizeof(C[0])) << endl; // 4,5,6,5,2,9,2,4,5,1,1,2 175 | return 0; 176 | 177 | } -------------------------------------------------------------------------------- /46_BoggleSolver.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will attempt to find words in a matrix of letters. 2 | /* 3 | have the function BoggleSolver(strArr) read the array of strings stored in strArr, which will contain 2 elements: the first element will represent a 4x4 matrix of letters, and the second element will be a long string of comma-separated words each at least 3 letters long, in alphabetical order, that represents a dictionary of some arbitrary length. For example: strArr can be: ["rbfg, ukop, fgub, mnry", "bog,bop,gup,fur,ruk"]. Your goal is to determine if all the comma separated words as the second parameter exist in the 4x4 matrix of letters. For this example, the matrix looks like the following: 4 | 5 | r b f g 6 | u k o p 7 | f g u b 8 | m n r y 9 | 10 | The rules to make a word are as follows: 11 | 12 | 1. A word can be constructed from sequentially adjacent spots in the matrix, where adjacent means moving horizontally, vertically, or diagonally in any direction. 13 | 2. A word cannot use the same location twice to construct itself. 14 | 15 | The rules are similar to the game of Boggle. So for the example above, all the words exist in that matrix so your program should return the string true. If all the words cannot be found, then return a comma separated string of the words that cannot be found, in the order they appear in the dictionary. 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | using namespace std; 22 | 23 | /* 24 | set up the first element into a matrix of letters 25 | this will be easier to later check adjacent spots 26 | iterate through the second element word by word 27 | used the current word and analyzed if it can be found in our list 28 | The method we will use is start with the first letter, check if the list has that first letter 29 | From the first letter check for adjacent options where the next letter is also matched 30 | Check for multiple options that is if multiple matching letters are adjacent 31 | analyze from one of the options and check if the word is found, if not try the other options 32 | Continue the process to see if all the letters can be found 33 | */ 34 | 35 | 36 | // Starting our first letter location 37 | // This function will analyze the neighbors and check if it completes the word 38 | // It will also be used recursively to handle cases in which there are multiple adjacent matching letters 39 | // It will follow that trail, analyzing multiple options, try one of the options, if fail try other options 40 | // The process will continue until all options have been tried 41 | bool findAdjacent(vector > letters, string value, int row,int col, int currentIndex, int lastIndex) 42 | { 43 | int index = currentIndex; 44 | 45 | // Keep a record of our last step 46 | // To properly develop this program we could have a list that tracks all the steps we have taken 47 | // This will prevent us from going into those locations again 48 | // For this purpose we are only avoiding the last step taken 49 | int lastStep = lastIndex; 50 | 51 | // We continue to loop until the end of our current word 52 | while (index < value.length()) 53 | { 54 | bool found = false; 55 | 56 | // Conditions for boundary check and also check adjacent neighbors 57 | // Checking up 58 | if (lastStep != 1) 59 | { 60 | if (row != 0 && letters[row - 1][col] == value[index]) 61 | { 62 | index++; // update the index of our target word 63 | row--; // update row/cols for the movement 64 | lastStep = 0; // update our the last location 65 | 66 | // Recursive call to now analyze this path 67 | found = findAdjacent(letters, value, row, col, index, lastStep); 68 | 69 | // If this path failed, bring the index back down to analyze other adjacent neighbors 70 | if (!found) 71 | { 72 | index--; 73 | } 74 | } 75 | } 76 | 77 | // Checking left 78 | if (lastStep != 2) 79 | { 80 | if (col != 0 && letters[row][col - 1] == value[index]) 81 | { 82 | index++; 83 | col--; 84 | lastStep = 3; 85 | found = findAdjacent(letters, value, row, col, index, lastStep); 86 | if (!found) 87 | { 88 | index--; 89 | } 90 | } 91 | } 92 | 93 | // Checking down 94 | if (lastStep != 0) 95 | { 96 | if (row != 3 && letters[row + 1][col] == value[index]) 97 | { 98 | index++; 99 | row++; 100 | lastStep = 1; 101 | found = findAdjacent(letters, value, row, col, index, lastStep); 102 | if (!found) 103 | { 104 | index--; 105 | } 106 | } 107 | } 108 | 109 | // Checking right 110 | if (lastStep != 3) 111 | { 112 | if (col != 3 && letters[row][col + 1] == value[index]) 113 | { 114 | index++; 115 | col++; 116 | lastStep = 2; 117 | found = findAdjacent(letters, value, row, col, index, lastStep); 118 | if (!found) 119 | { 120 | index--; 121 | } 122 | } 123 | } 124 | 125 | // Checking diagonal top left 126 | if (lastStep != 4) 127 | { 128 | if (row != 0 && col != 0 && letters[row - 1][col - 1] == value[index]) 129 | { 130 | index++; 131 | row--; 132 | col--; 133 | lastStep = 5; 134 | found = findAdjacent(letters, value, row, col, index, lastStep); 135 | if (!found) 136 | { 137 | index--; 138 | } 139 | } 140 | } 141 | 142 | // Checking diagonal top right 143 | if (lastStep != 6) 144 | { 145 | if (row != 0 && col != 3 && letters[row - 1][col + 1] == value[index]) 146 | { 147 | index++; 148 | row--; 149 | col++; 150 | lastStep = 7; 151 | found = findAdjacent(letters, value, row, col, index, lastStep); 152 | if (!found) 153 | { 154 | index--; 155 | } 156 | } 157 | } 158 | 159 | // Checking diagonal bottom left 160 | if (lastStep != 7) 161 | { 162 | if (row != 3 && col != 0 && letters[row + 1][col - 1] == value[index]) 163 | { 164 | index++; 165 | row++; 166 | col--; 167 | lastStep = 6; 168 | found = findAdjacent(letters, value, row, col, index, lastStep); 169 | if (!found) 170 | { 171 | index--; 172 | } 173 | } 174 | } 175 | 176 | // Checking diagonal bottom right 177 | if (lastStep != 5) 178 | { 179 | if (row != 3 && col != 3 && letters[row + 1][col + 1] == value[index]) 180 | { 181 | index++; 182 | row++; 183 | col++; 184 | lastStep = 4; 185 | found = findAdjacent(letters, value, row, col, index, lastStep); 186 | } 187 | } 188 | 189 | // Condition if no adjacent correct letter was found 190 | if (!found) 191 | { 192 | return false; 193 | } 194 | } 195 | 196 | return true; 197 | } 198 | 199 | // Check and find first letter of current word in our matrix 200 | bool search(vector > letters, char value, string word) 201 | { 202 | for (int row = 0; row < 4; row++) 203 | { 204 | for (int col = 0; col < 4; col++) 205 | { 206 | if (value == letters[row][col] && findAdjacent(letters,word,row,col, 1, -1)) 207 | { 208 | return true; 209 | } 210 | } 211 | } 212 | return false; 213 | } 214 | 215 | // Analyze current word 216 | bool boogle(vector > letters, string value) 217 | { 218 | if (search(letters, value[0], value)) 219 | { 220 | return true; 221 | } 222 | else 223 | { 224 | return false; 225 | } 226 | } 227 | 228 | string BoggleSolver(string strArr[]) 229 | { 230 | vector > letterMatrix(4); 231 | 232 | // Loop to extract the values of the first element and create a 4x4 matrix of letters 233 | for (int x = 0,row = 0; x < strArr[0].length(); x++) 234 | { 235 | if (strArr[0][x] == ',') 236 | { 237 | row++; 238 | } 239 | else if (strArr[0][x] >= 'a'&& strArr[0][x] <= 'z' || strArr[0][x] >= 'A' && strArr[0][x] <= 'Z') 240 | { 241 | letterMatrix[row].push_back(strArr[0][x]); 242 | } 243 | } 244 | 245 | string temp; 246 | string errors; 247 | 248 | // Iterate through the second element to analyze the words 249 | for (int x = 0; x < strArr[1].length(); x++) 250 | { 251 | // Condition to separate the words 252 | if (strArr[1][x] == ',' || x == strArr[1].length() - 1) 253 | { 254 | if (x == strArr[1].length() - 1) 255 | { 256 | temp += strArr[1][x]; 257 | } 258 | 259 | // If the word was not found in our matrix store it 260 | if (!boogle(letterMatrix, temp)) 261 | { 262 | errors += temp; 263 | errors += ','; 264 | } 265 | temp.clear(); 266 | } 267 | else if (strArr[1][x] >= 'a'&& strArr[1][x] <= 'z' || strArr[1][x] >= 'A' && strArr[1][x] <= 'Z') 268 | { 269 | temp += strArr[1][x]; 270 | } 271 | } 272 | 273 | if (errors.length() > 0) 274 | { 275 | errors.erase(errors.end() - 1); 276 | return errors; 277 | } 278 | else 279 | { 280 | return "true"; 281 | } 282 | } 283 | 284 | int main() 285 | { 286 | string A[] = { "rbfg, ukop, fgub, mnry", "bog,bop,gup,fur,ruk" }; 287 | string B[] = { "aaey, rrum, tgmn, ball", "all,ball,mur,raeymnl,tall,true,trum" }; 288 | string C[] = { "aaey, rrum, tgmn, ball", "all,ball,mur,raeymnl,rumk,tall,true,trum,yes" }; 289 | string D[] = { "abfr, ryut, gmei, fadc", "abyba" }; 290 | string E[] = { "abfr, ryut, gmei, fadc", "abyba,cdeicz" }; 291 | 292 | cout << BoggleSolver(A) << endl; // true 293 | cout << BoggleSolver(B) << endl; // true 294 | cout << BoggleSolver(C) << endl; // rumk,yes 295 | cout << BoggleSolver(D) << endl; // abyba 296 | cout << BoggleSolver(E) << endl; // abyba,cedicz 297 | 298 | return 0; 299 | } 300 | -------------------------------------------------------------------------------- /47_MatrixPath.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine if a path exists in a boolean matrix. 2 | /* 3 | have the function MatrixPath(strArr) take the strArr parameter being passed which will be a 2D matrix of 0 and 1's of some arbitrary size, and determine if a path of 1's exists from the top-left of the matrix to the bottom-right of the matrix while moving only in the directions: up, down, left, and right. If a path exists your program should return the string true, otherwise your program should return the number of locations in the matrix where if a single 0 is replaced with a 1, a path of 1's will be created successfully. If a path does not exist and you cannot create a path by changing a single location in the matrix from a 0 to a 1, then your program should return the string not possible. For example: if strArr is ["11100", "10011", "10101", "10011"] then this looks like the following matrix: 4 | 5 | 1 1 1 0 0 6 | 1 0 0 1 1 7 | 1 0 1 0 1 8 | 1 0 0 1 1 9 | 10 | 11 | 12 | 1 1 1 0 0 13 | 1 1 0 1 1 14 | 1 0 1 0 1 15 | 1 0 0 1 1 16 | 17 | For the input above, a path of 1's from the top-left to the bottom-right does not exist. But, we can change a 0 to a 1 in 2 places in the matrix, namely at locations: 18 | [0,3] or [1,2]. So for this input your program should return 2. The top-left and bottom-right of the input matrix will always be 1's. 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | using namespace std; 26 | 27 | // NOT FINISHED 28 | 29 | /* 30 | start at the top left as your current location 31 | check for different path options from the current location 32 | If there are multiple options keep track of the location to reset back 33 | Move in one of the path options and keep track of which option you took 34 | 35 | */ 36 | 37 | 38 | 39 | void OptionFinder(int row, int col, string matrix[], int size, vector > &paths) 40 | { 41 | vector temp; 42 | int options = 0; 43 | 44 | // Condition to find path options taken 45 | // Will also do boundary check 46 | // Going Left 47 | if (col != 0 && matrix[row][col - 1] == '1') 48 | { 49 | options++; 50 | } 51 | 52 | // Going Right 53 | if (col != matrix[row].length-1 && matrix[row][col + 1] == '1') 54 | { 55 | options++; 56 | } 57 | 58 | // Going Down 59 | if (row != size && matrix[row+1][col] == '1') 60 | { 61 | options++; 62 | } 63 | 64 | // Going UP 65 | if (row != 0 && matrix[row - 1][col] == '1') 66 | { 67 | options++; 68 | } 69 | 70 | if (options > 1) 71 | { 72 | 73 | } 74 | } 75 | 76 | 77 | string MatrixPath(string strArr[], int size) 78 | { 79 | int currentRow = 0; 80 | int currentCol = 0; 81 | 82 | 83 | 84 | } 85 | 86 | int main() 87 | { 88 | string A[] = { "11100", "10011", "10101", "10011" }; 89 | string B[] = { "10000", "11011", "10101", "11001" }; 90 | string C[] = { "1000001", "1001111", "1010101" }; 91 | 92 | cout << MatrixPath(A, sizeof(A) / sizeof(A[0])) << endl; // 2 93 | cout << MatrixPath(A, sizeof(A) / sizeof(A[0])) << endl; // 1 94 | cout << MatrixPath(A, sizeof(A) / sizeof(A[0])) << endl; // not possible 95 | return 0; 96 | } -------------------------------------------------------------------------------- /48_FormattedNumber.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be determining if a string is a valid number. 2 | /* 3 | have the function FormattedNumber(strArr) take the strArr parameter being passed, which will only contain a single element, and return the string true if it is a valid number that contains only digits with properly placed decimals and commas, otherwise return the string false. For example: if strArr is ["1,093,222.04"] then your program should return the string true, but if the input were ["1,093,22.04"] then your program should return the string false. The input may contain characters other than digits. 4 | */ 5 | 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | /* 11 | iterate through the first element 12 | make sure we are only working with digits, commas, and decimal point 13 | when we find a comma make sure there are three preceding digits else false 14 | we can only have one decimal point 15 | commas are only valid before the decimal point 16 | */ 17 | 18 | string FormattedNumber(string strArr[]) 19 | { 20 | int hundred = 3; 21 | int comma=-1, decimal=strArr[0].length(); 22 | int decimalTotal = 0; 23 | 24 | for (int x = 0; x < strArr[0].length(); x++) 25 | { 26 | // Condition to check we are only working with the correct characters 27 | if (strArr[0][x] == ',' || strArr[0][x] == '.' || strArr[0][x] >= '0' && strArr[0][x] <= '9') 28 | { 29 | // Checking for the start of a comma also checking that the rules are followed 30 | if (strArr[0][x] == ',') 31 | { 32 | if (hundred == 3) 33 | { 34 | hundred = 0; 35 | comma = x; 36 | if (comma > decimal) 37 | { 38 | return "false"; 39 | } 40 | } 41 | else 42 | { 43 | return "false"; 44 | } 45 | 46 | } 47 | 48 | // Digits after the comma 49 | if (strArr[0][x] >= '0' && strArr[0][x] <= '9' && x > comma && comma != -1) 50 | { 51 | hundred++; 52 | } 53 | 54 | // Locating our decimal point 55 | // Assuring we only have a single decimal point 56 | // Also assuring our comma rule is checked 57 | if (strArr[0][x] == '.') 58 | { 59 | decimal = x; 60 | decimalTotal++; 61 | if (decimalTotal > 1 || hundred != 3) 62 | { 63 | return "false"; 64 | } 65 | } 66 | } 67 | else 68 | { 69 | return "false"; 70 | } 71 | } 72 | 73 | return "true"; 74 | } 75 | 76 | int main() 77 | { 78 | string A[] = { "1,093,222.04" }; 79 | string B[] = { "1,093,22.04" }; 80 | string C[] = { "0.232567" }; 81 | string D[] = { "2,567.00.2" }; 82 | string E[] = { "1,093,2qw.04" }; 83 | string F[] = { "898989898" }; 84 | 85 | cout << FormattedNumber(A) << endl; // true 86 | cout << FormattedNumber(B) << endl; // false 87 | cout << FormattedNumber(C) << endl; // true 88 | cout << FormattedNumber(D) << endl; // false 89 | cout << FormattedNumber(E) << endl; // false 90 | cout << FormattedNumber(F) << endl; 91 | return 0; 92 | } -------------------------------------------------------------------------------- /49_MissingDigitII.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine what the variables are in a mathematical equation. 2 | /* 3 | have the function MissingDigitII(str) take the str parameter, which will be a simple mathematical formula with three numbers, a single operator (+, -, *, or /) and an equal sign (=) and return the two digits that complete the equation. In two of the numbers in the equation, there will be a single ? character, and your program should determine what digits are missing and return them separated by a space. For example, if str is "38?5 * 3 = 1?595" then your program should output 6 1. 4 | 5 | The ? character will always appear in both the first number and the last number in the mathematical expression. There will always be a unique solution. 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | /* 15 | find out what type of operation needs to happen 16 | convert our values to an int to perform operations 17 | since the middle number is always complete we can use it to perform various operation with our first number 18 | The method is simple insert temp digits 0-9 on first number 19 | perform operation between the numbers and check that it matches our last number 20 | */ 21 | 22 | // Linear search function 23 | bool search(vector list, int value) 24 | { 25 | for (int x = 0; x < list.size(); x++) 26 | { 27 | if (list[x] == value) 28 | { 29 | return true; 30 | } 31 | } 32 | return false; 33 | } 34 | 35 | string MissingDigitII(string str) 36 | { 37 | char operation; 38 | // Conditions to find what type of operation we are working with 39 | if (str.find('*') != -1) 40 | { 41 | operation = str.find('*'); 42 | } 43 | else if (str.find('/') != -1) 44 | { 45 | operation = str.find('/'); 46 | } 47 | else if (str.find('+') != -1) 48 | { 49 | operation = str.find('+'); 50 | } 51 | else if (str.find('-') != -1) 52 | { 53 | operation = str.find('-'); 54 | } 55 | 56 | string firstNum, middleNum, lastNum; 57 | int equalSign = str.find('='); // Locating our equal sign 58 | 59 | // Extracting our string values to later convert to ints and perform calculations 60 | firstNum = str.substr(0, operation - 1); 61 | middleNum = str.substr(operation + 2, (equalSign - operation)-3); 62 | lastNum = str.substr(equalSign + 2); 63 | 64 | // We locate the missing digit of our last number 65 | int num; 66 | int question = lastNum.find('?'); 67 | if (question == 0) 68 | { 69 | lastNum[question] = '9'; 70 | } 71 | else 72 | { 73 | lastNum[question] = '0'; 74 | } 75 | 76 | istringstream(lastNum) >> num; 77 | 78 | // List that will store all the possible valid results when the operation is perform 79 | // This includes the last number and increments its digit in the proper location 80 | // Example if last number is 3?5, the list we have 305,315,325,etc... 81 | vector resultList; 82 | resultList.push_back(num); 83 | 84 | // Loop creating the list 85 | for (int x = 0; x < 9; x++) 86 | { 87 | stringstream convert; 88 | convert << num; 89 | string temp = convert.str(); 90 | if (question == 0) 91 | { 92 | temp[question] = char(int(convert.str()[question]) - 1); 93 | } 94 | else 95 | { 96 | temp[question] = char(int(convert.str()[question]) + 1); 97 | } 98 | istringstream(temp) >> num; 99 | resultList.push_back(num); 100 | } 101 | 102 | // Locating missing digit of first number and cover both first number and middle number to ints 103 | int question2 = firstNum.find('?'); 104 | if (question2 == 0) 105 | { 106 | firstNum[question2] = '9'; 107 | } 108 | else 109 | { 110 | firstNum[question2] = '0'; 111 | } 112 | 113 | int first, middle; 114 | istringstream(firstNum) >> first; 115 | istringstream(middleNum) >> middle; 116 | 117 | // String to store our final output 118 | string result; 119 | 120 | // Loop to perform the operation 121 | // Since we set our first number to the highest possible we iterate until the zero digit 122 | // Through each iteration we perform operations with middle num and check if the total is in our list 123 | for (int x = 0; x < 10; x++) 124 | { 125 | int total; 126 | switch (str[operation]) 127 | { 128 | case '*': 129 | // Perform the required operation 130 | total = first * middle; 131 | // Condition to check if is in our list 132 | if (search(resultList, total)) 133 | { 134 | // extracts our digits from the total and first number 135 | stringstream convert; 136 | convert << first; 137 | result += convert.str()[question2]; 138 | result += " "; 139 | convert.str(""); 140 | convert << total; 141 | result += convert.str()[question]; 142 | return result; 143 | } 144 | break; 145 | case '/': 146 | total = first / middle; 147 | if (search(resultList, total)) 148 | { 149 | stringstream convert; 150 | convert << first; 151 | result += convert.str()[question2]; 152 | result += " "; 153 | convert.str(""); 154 | convert << total; 155 | result += convert.str()[question]; 156 | return result; 157 | } 158 | break; 159 | case '+': 160 | total = first + middle; 161 | if (search(resultList, total)) 162 | { 163 | stringstream convert; 164 | convert << first; 165 | result += convert.str()[question2]; 166 | result += " "; 167 | convert.str(""); 168 | convert << total; 169 | result += convert.str()[question]; 170 | return result; 171 | } 172 | break; 173 | case '-': 174 | total = first - middle; 175 | if (search(resultList, total)) 176 | { 177 | stringstream convert; 178 | convert << first; 179 | result += convert.str()[question2]; 180 | result += " "; 181 | convert.str(""); 182 | convert << total; 183 | result += convert.str()[question]; 184 | return result; 185 | } 186 | break; 187 | } 188 | 189 | // Updates our first number 190 | stringstream convert; 191 | convert << first; 192 | string temp = convert.str(); 193 | if (question2 == 0) 194 | { 195 | temp[question2] = char(int(convert.str()[question2]) - 1); 196 | } 197 | else 198 | { 199 | temp[question2] = char(int(convert.str()[question2]) + 1); 200 | } 201 | istringstream(temp) >> first; 202 | } 203 | } 204 | 205 | int main() 206 | { 207 | cout << MissingDigitII("38?5 * 3 = 1?595") << endl; // 6 1 208 | cout << MissingDigitII("56? * 106 = 5?678") << endl; // 3 9 209 | cout << MissingDigitII("18?1 + 9 = 189?") << endl; // 8 0 210 | cout << MissingDigitII("1? + 11 = ?2") << endl; // 1 2 211 | cout << MissingDigitII("6? - 51 = ?7") << endl; // 8 1 212 | cout << MissingDigitII("5555? - 4261 = ?1294") << endl; // 5 5 213 | cout << MissingDigitII("?0 + 20 = 4?") << endl; // 2 0 214 | cout << MissingDigitII("50? / 5 = ?00") << endl; // 0 1 215 | cout << MissingDigitII("? + 21 = ?0") << endl; // 9 3 216 | return 0; 217 | } 218 | 219 | -------------------------------------------------------------------------------- /4_PalindromeTwo.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be determining if a string is a palindrome. 2 | // have the function PalindromeTwo(str) take the str parameter being passed and return the string true if the parameter is a palindrome, (the string is the same forward as it is backward) otherwise return the string false. The parameter entered may have punctuation and symbols but they should not affect whether the string is in fact a palindrome. For example: "Anne, I vote more cars race Rome-to-Vienna" should return true. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | string PalindromeTwo(string str) { 9 | 10 | string temp; 11 | // Creating a new string with only letters 12 | for (int x = 0; x < str.length(); x++) 13 | { 14 | if ((str[x] >= 'a' && str[x] <= 'z') || (str[x] >= 'A' && str[x] <= 'Z')) 15 | { 16 | temp.push_back(tolower(str[x])); 17 | } 18 | } 19 | 20 | string temp2 = temp; 21 | int index = 0; 22 | // Comparing the strings 23 | for (int y = temp.length() - 1; y >= 0; y--) 24 | { 25 | if (temp2[index] != temp[y]) 26 | { 27 | return "false"; 28 | } 29 | index++; 30 | } 31 | return "true"; 32 | } 33 | 34 | int main() { 35 | 36 | // keep this function call here 37 | cout << PalindromeTwo("Noel - sees Leon") << endl; // true 38 | cout << PalindromeTwo("A war at Tarawa!") << endl; // true 39 | cout << PalindromeTwo("Anne, I vote more cars race Rome-to-Vienna") << endl; // true 40 | return 0; 41 | 42 | } -------------------------------------------------------------------------------- /50_LongestConsecutive.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will compute the length of the longest consecutive subsequence. 2 | /* 3 | have the function LongestConsecutive(arr) take the array of positive integers stored in arr and return the length of the longest consecutive subsequence (LCS). An LCS is a subset of the original list where the numbers are in sorted order, from lowest to highest, and are in a consecutive, increasing order. The sequence does not need to be contiguous and there can be several different subsequences. For example: if arr is [4, 3, 8, 1, 2, 6, 100, 9] then a few consecutive sequences are [1, 2, 3, 4], and [8, 9]. For this input, your program should return 4 because that is the length of the longest consecutive subsequence. 4 | */ 5 | 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | /* 11 | order the values from least to greatest 12 | iterate and analyze consecutive sequence 13 | keep count of the highest sequence 14 | */ 15 | 16 | void sort(int list[], int size) 17 | { 18 | bool swap; 19 | int temp; 20 | 21 | do 22 | { 23 | swap = false; 24 | 25 | for (int x = 0; x < size - 1; x++) 26 | { 27 | if (list[x] > list[x + 1]) 28 | { 29 | temp = list[x]; 30 | list[x] = list[x + 1]; 31 | list[x + 1] = temp; 32 | swap = true; 33 | } 34 | } 35 | } while (swap); 36 | } 37 | 38 | int LongestConsecutive(int arr[], int size) 39 | { 40 | int length, high; 41 | high = 0; 42 | length = 1; 43 | 44 | // Sort the values 45 | sort(arr, size); 46 | 47 | // Loop to iterate and find consecutive sequences 48 | for (int x = 0; x < size-1; x++) 49 | { 50 | if (arr[x] + 1 == arr[x + 1]) 51 | { 52 | length++; 53 | } 54 | else if (arr[x] == arr[x + 1]) 55 | { 56 | continue; 57 | } 58 | else 59 | { 60 | if (length > high) 61 | { 62 | high = length; 63 | } 64 | 65 | length = 1; 66 | } 67 | } 68 | 69 | if (length > high) 70 | { 71 | high = length; 72 | } 73 | 74 | return high; 75 | } 76 | 77 | int main() 78 | { 79 | int A[] = { 4, 3, 8, 1, 2, 6, 100, 9}; 80 | int B[] = { 6, 7, 3, 1, 100, 102, 6, 12 }; 81 | int C[] = { 5, 6, 1, 2, 8, 9, 7 }; 82 | int D[] = { 11, 6, 6, 5, 7, 10, 1, 2, 3, 12, 9, 8 }; 83 | int E[] = { 5, 15, 16, 21, 4, 5, 10, 9, 8, 22, 23, 7, 3, 2, 24, 1, 6 }; 84 | cout << LongestConsecutive(A, sizeof(A) / sizeof(A[0])) << endl; // 4 85 | cout << LongestConsecutive(B, sizeof(B) / sizeof(B[0])) << endl; // 2 86 | cout << LongestConsecutive(C, sizeof(C) / sizeof(C[0])) << endl; // 5 87 | cout << LongestConsecutive(D, sizeof(D) / sizeof(D[0])) << endl; // 8 88 | cout << LongestConsecutive(E, sizeof(E) / sizeof(E[0])) << endl; // 10 89 | 90 | return 0; 91 | } -------------------------------------------------------------------------------- /51_SimplePassword.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be determining if a string is a valid password. 2 | /* 3 | have the function SimplePassword(str) take the str parameter being passed and determine if it passes as a valid password that follows the list of constraints: 4 | 5 | 1. It must have a capital letter. 6 | 2. It must contain at least one number. 7 | 3. It must contain a punctuation mark. 8 | 4. It cannot have the word "password" in the string. 9 | 5. It must be longer than 7 characters and shorter than 31 characters. 10 | 11 | If all the above constraints are met within the string, the your program should return the string true, otherwise your program should return the string false. For example: if str is "apple!M7" then your program should return "true". 12 | */ 13 | 14 | #include 15 | #include 16 | using namespace std; 17 | 18 | string SimplePassword(string str) 19 | { 20 | int lowLimit = 7; 21 | int highLimit = 31; 22 | bool capital = false; 23 | bool symbol = false; 24 | bool number = false; 25 | string temp = "password"; 26 | 27 | // checking the size 28 | if (str.size() >= 31 || str.size() < 7) 29 | { 30 | return "false"; 31 | } 32 | 33 | for (int x = 0; x < str.size(); x++) 34 | { 35 | if (str[x] >= '0' && str[x] <= '9') 36 | { 37 | number = true; 38 | } 39 | else if (isupper(str[x])) 40 | { 41 | capital = true; 42 | } 43 | else if (int(str[x]) >= 33 && int(str[x]) <= 47 || int(str[x]) >= 58 && int(str[x]) <= 64) 44 | { 45 | symbol = true; 46 | } 47 | 48 | // Condition to check if the word 'password' is found in the input 49 | if (tolower(str[x]) == 'p') 50 | { 51 | int index = 0; 52 | bool found = true; 53 | 54 | for (int y = x; y < x + temp.size(); y++) 55 | { 56 | if (tolower(str[y]) != temp[index]) 57 | { 58 | found = false; 59 | break; 60 | } 61 | index++; 62 | } 63 | 64 | if (found) 65 | { 66 | return "false"; 67 | } 68 | } 69 | } 70 | 71 | if (capital && symbol && number) 72 | { 73 | return "true"; 74 | } 75 | else 76 | { 77 | return "false"; 78 | } 79 | } 80 | 81 | int main() 82 | { 83 | 84 | cout << SimplePassword("apple!M7") << endl; // true 85 | cout << SimplePassword("passWord123!!!!") << endl; // false 86 | cout << SimplePassword("turkey90AAA=") << endl; // true 87 | return 0; 88 | 89 | } -------------------------------------------------------------------------------- /52_CharacterRemoval.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will attempt to modify a word and then find it within a dictionary. 2 | /* 3 | have the function CharacterRemoval(strArr) read the array of strings stored in strArr, which will contain 2 elements: the first element will be a sequence of characters representing a word, and the second element will be a long string of comma-separated words, in alphabetical order, that represents a dictionary of some arbitrary length. For example: strArr can be: ["worlcde", "apple,bat,cat,goodbye,hello,yellow,why,world"]. Your goal is to determine the minimum number of characters, if any, can be removed from the word so that it matches one of the words from the dictionary. In this case, your program should return 2 because once you remove the characters "c" and "e" you are left with "world" and that exists within the dictionary. If the word cannot be found no matter what characters are removed, return -1. 4 | 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | // NOT FINISHED 13 | 14 | 15 | /* 16 | have a list of the dictionary 17 | compare each of the dictionary words to the target word 18 | remove any letters from the target word not found in the current dictionary word 19 | Check if that dictionary word is found after cleaning the target word 20 | keep track of the character removal 21 | */ 22 | 23 | int CharacterRemoval(string strArr[]) 24 | { 25 | string word = strArr[0]; 26 | int minRemoval = word.size() * 100; 27 | bool found = false; 28 | 29 | vector list; 30 | string tempWord; 31 | 32 | // Have a list of the dictionary words 33 | for (int x = 0; x < strArr[1].size(); x++) 34 | { 35 | if (strArr[1][x] == ',') 36 | { 37 | list.push_back(tempWord); 38 | tempWord.clear(); 39 | } 40 | else 41 | { 42 | tempWord.push_back(strArr[1][x]); 43 | 44 | if (x == strArr[1].size() - 1) 45 | { 46 | list.push_back(tempWord); 47 | } 48 | } 49 | } 50 | 51 | for (int x = 0; x < list.size(); x++) 52 | { 53 | int removal = 0; 54 | string temp; 55 | 56 | // Loop to remove non related characters from the target word when compared to the dictionary 57 | for (int y = 0; y < word.size(); y++) 58 | { 59 | if (list[x].find(word[y]) == -1) 60 | { 61 | removal++; 62 | } 63 | else 64 | { 65 | temp.push_back(word[y]); 66 | } 67 | } 68 | 69 | 70 | if (temp.size() > list[x].size()) 71 | { 72 | 73 | } 74 | 75 | 76 | // Condition for if the current dictionary word is included in the target word 77 | if (temp.find(list[x]) != -1) 78 | { 79 | cout << "We found " << list[x] << " from " << temp << endl; 80 | found = true; 81 | 82 | if (temp.size() > list[x].size()) 83 | { 84 | removal += temp.size() - list[x].size(); 85 | } 86 | 87 | if (removal < minRemoval) 88 | { 89 | minRemoval = removal; 90 | } 91 | } 92 | 93 | } 94 | 95 | if (found) 96 | { 97 | return minRemoval; 98 | } 99 | else 100 | { 101 | return -1; 102 | } 103 | } 104 | 105 | int main() 106 | { 107 | string A[] = { "worlcde", "apple,bat,cat,goodbye,hello,yellow,why,world" }; 108 | string B[] = { "baseball", "a,all,b,ball,bas,base,cat,code,d,e,quit,z" }; 109 | string C[] = { "apbpleeeef", "a,ab,abc,abcg,b,c,dog,e,efd,zzzz" }; 110 | string D[] = { "abcdefabcdef", "a,b,bfabcde,c,d,e,ee,eee,eeee,eeeeeeeee,fabc,go,goo,gooo" }; 111 | cout << CharacterRemoval(A) << endl; // 2 112 | cout << CharacterRemoval(B) << endl; // 4 113 | cout << CharacterRemoval(C) << endl; // 8 114 | cout << CharacterRemoval(D) << endl; // 5 115 | 116 | return 0; 117 | } -------------------------------------------------------------------------------- /53_ThreePoints.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be plotting a line on a Cartesian grid. 2 | /* 3 | have the function ThreePoints(strArr) read the array of strings stored in strArr which will always contain 3 elements and be in the form: ["(x1,y1)", "(x2,y2)", "(x3,y3)"]. Your goal is to first create a line formed by the first two points (that starts from the first point and moves in the direction of the second point and that stretches in both directions through the two points), and then determine what side of the line point 3 is on. The result will either be right, left, or neither. For example: if strArr is ["(1,1)", "(3,3)", "(2,0)"] then your program should return the string right because the third point lies to the right of the line formed by the first two points. 4 | */ 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | /* 14 | NOT FINISHED 15 | extract the values of each point 16 | convert to integer for ease of use 17 | compare the distance between each point 18 | */ 19 | 20 | string ThreePoints(string strArr[]) 21 | { 22 | vector points; 23 | vector values; 24 | 25 | for (int x = 0; x < 3; x++) 26 | { 27 | int middle; 28 | middle = strArr[x].find(','); 29 | 30 | // extract the x value from current point 31 | points.push_back(strArr[x].substr(1, middle - 1)); 32 | 33 | // extract the y value form current point 34 | points.push_back(strArr[x].substr(middle + 1, (strArr[x].size() - middle + 1) - 1)); 35 | } 36 | 37 | // Convert to ints for comparing the x values 38 | for (int x = 0; x < points.size(); x++) 39 | { 40 | double temp; 41 | 42 | istringstream(points[x]) >> temp; 43 | values.push_back(temp); 44 | } 45 | 46 | // Find distance 47 | double distance1 = sqrt(pow(values[4] - values[0], 2) + pow(values[5] - values[1], 2)); 48 | double distance2 = sqrt(pow(values[4] - values[2], 2) + pow(values[5] - values[3], 2)); 49 | cout << distance1 << " and " << distance2 << endl; 50 | // Find mid point 51 | double x = (values[0] + values[2]) / 2.0; 52 | double y = (values[1] + values[3]) / 2; 53 | 54 | cout << x << endl; 55 | if (values[4] == x) 56 | { 57 | return "neither"; 58 | } 59 | else if (values[4] > x) 60 | { 61 | return "right"; 62 | } 63 | else 64 | { 65 | return "left"; 66 | } 67 | } 68 | 69 | int main() 70 | { 71 | string A[] = { "(5000,5001)", "(-5001,-5000)", "(0,601)" }; 72 | string B[] = { "(0,-3)", "(-2,0)", "(0,0)" }; 73 | string C[] = { "(0,0)", "(0,5)", "(0,2)" }; 74 | string D[] = { "(0,1)", "(-3,0)", "(-1,0)" }; 75 | string E[] = { "(0,5)", "(0,-5)", "(1,1)" }; 76 | string F[] = { "(100,100)", "(-1,-1)", "(5,1)" }; 77 | cout << ThreePoints(A) << endl; // right 78 | cout << ThreePoints(B) << endl; // right 79 | cout << ThreePoints(C) << endl; // neither 80 | cout << ThreePoints(D) << endl; // left 81 | cout << ThreePoints(E) << endl; // left 82 | cout << ThreePoints(F) << endl; // left 83 | return 0; 84 | } -------------------------------------------------------------------------------- /54_StringExpression.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will convert a string of written numbers to an actual number. 2 | /* 3 | have the function StringExpression(str) read the str parameter being passed which will contain the written out version of the numbers 0-9 and the words "minus" or "plus" and convert the expression into an actual final number written out as well. For example: if str is "foursixminustwotwoplusonezero" then this converts to "46 - 22 + 10" which evaluates to 34 and your program should return the final string threefour. If your final answer is negative it should include the word "negative." 4 | */ 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | /* 13 | Have a string array of the numbers 14 | traverse the input and store the characters into a temp string 15 | with each iteration we compare the temp string to our helper function to return a number equivalent 16 | if the temp string matches a valid string number we reset the temp to search for another 17 | the results will be stored into a string number. ex if temp string is "four" number string is "4" 18 | the above process will continue until we reach either a minus or plus or reach the last index 19 | 20 | once a plus or minus is reached the number string will converted to an int 21 | it will also be added to a new list 22 | plus or minus symbols will also be represented with placeholder integers (plus = 0, minus = 1) 23 | 24 | the calculation will be performed ounce the expression has been analyzed 25 | after completion we have to convert the result back to a string expression 26 | we traverse the final string to converts its digits to represent an expression 27 | example twothree = 23 28 | */ 29 | 30 | string list[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 31 | 32 | 33 | // Converts string expression to its number corresponding number 34 | // "nine" = "9" 35 | int getValue(string temp) 36 | { 37 | for (int x = 0; x < 10; x++) 38 | { 39 | if (temp == list[x]) 40 | { 41 | return x; 42 | } 43 | } 44 | 45 | return -1; 46 | } 47 | 48 | // Converts character digit to its string expression 49 | // "4" = "four" 50 | string getExpression(char digit) 51 | { 52 | int index = int(digit) - 48; 53 | 54 | return list[index]; 55 | } 56 | 57 | string StringExpression(string str) 58 | { 59 | string temp; 60 | string number = ""; 61 | vector numberList; 62 | 63 | 64 | for (int x = 0; x < str.length(); x++) 65 | { 66 | temp.push_back(str[x]); 67 | 68 | // checking if the temp string corresponds to a valid string number 69 | int value = getValue(temp); 70 | if (value >= 0 && value <= 9) 71 | { 72 | // condition for when temp matches a valid number 73 | // we transform the number expression to its number representative 74 | // example "one" = "1" 75 | stringstream convert; 76 | convert << value; 77 | number += convert.str(); // storing our result 78 | temp.clear(); // reseting our temp string to validate another section of our input 79 | } 80 | 81 | if (temp == "plus" || temp == "minus" || x == str.length()-1) 82 | { 83 | // condition for when we reach an operator or last number expression 84 | // we convert the number representative to an integer 85 | // we also track our operation if one was found 86 | int result; 87 | istringstream(number) >> result; 88 | numberList.push_back(result); 89 | 90 | number = ""; 91 | 92 | if (temp == "plus") 93 | { 94 | numberList.push_back(0); 95 | } 96 | else if (temp == "minus") 97 | { 98 | numberList.push_back(1); 99 | } 100 | temp.clear(); 101 | } 102 | } 103 | 104 | // loop to perform the calculation based on our gathered numbers and operations 105 | int total = numberList[0]; 106 | for (int x = 1; x < numberList.size() - 1; x += 2) 107 | { 108 | // these condition determine if we add or subtract based on our placeholder values for the operators 109 | // 0 = plus and 1 = minus 110 | if (numberList[x] == 0) 111 | { 112 | total += numberList[x + 1]; 113 | } 114 | else 115 | { 116 | total -= numberList[x + 1]; 117 | } 118 | } 119 | 120 | stringstream convert; 121 | convert << total; 122 | number = convert.str(); 123 | string finalString= ""; 124 | 125 | // in the case the result is negative 126 | if (total < 0) 127 | { 128 | finalString += "negative"; 129 | } 130 | 131 | // loop to traverse final string number 132 | // here we do inverse of before now we transfer number representative to its expression 133 | // example "2" = "two" 134 | for (int x = 0; x < number.length(); x++) 135 | { 136 | finalString += getExpression(number[x]); 137 | } 138 | 139 | return finalString; 140 | } 141 | 142 | int main() 143 | { 144 | cout << StringExpression("onezeropluseight") << endl; // oneeight 145 | cout << StringExpression("oneminusoneone") << endl; // negativeonezero 146 | cout << StringExpression("foursixminustwotwoplusonezero") << endl; // threefour 147 | 148 | return 0; 149 | } 150 | -------------------------------------------------------------------------------- /55_PreorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be traversing a binary tree. 2 | /* 3 | have the function PreorderTraversal(strArr) take the array of strings stored in strArr, which will represent a binary tree with integer values in a format similar to how a binary heap is implemented with NULL nodes at any level represented with a #. Your goal is to return the pre-order traversal of the tree with the elements separated by a space. For example: if strArr is ["5", "2", "6", "1", "9", "#", "8", "#", "#", "#", "#", "4", "#"] 4 | */ 5 | 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | 11 | /* 12 | The approach will remain as if dealing with a linked list implemented tree 13 | start at the root, than analyze values to the left of the current until a null node than right 14 | unlike a simple node redirection here we have to control our index 15 | We will use the formula of 2i+1 and 2i+2 where i is the parent and those represent the children 16 | if we encounter a '#' this will work as our base case 17 | to simplify we will also have a global string variable to record our result 18 | and reset it each time it is called from the function 19 | */ 20 | 21 | string result; 22 | 23 | void traversal(string tree[], int index, int size) 24 | { 25 | // base case to return to the caller if current node is null 26 | // Or if we have gone pass our array size 27 | if (index >= size || tree[index] == "#") 28 | { 29 | return; 30 | } 31 | 32 | // include the current node to our result 33 | result += tree[index] + " "; 34 | 35 | // special case from when we go out of bounds but due to the index not properly representing the current parent 36 | // for example if a parent has a leaf node to its left, than the index needs to be updated 37 | // That is the leaf node will not count, so we decrease our index to represent a valid parent node 38 | // Again this is only for when the current parent had a leaf node sibling to its left 39 | if (2 * index + 1 >= size && tree[index - 1] == "#") 40 | { 41 | index--; 42 | } 43 | 44 | // move to the left of current node 45 | traversal(tree, 2 * index + 1, size); 46 | 47 | // move to the right of current node 48 | traversal(tree, 2 * index + 2, size); 49 | } 50 | 51 | string PreorderTraversal(string strArr[], int size) 52 | { 53 | result = ""; // string to store our result 54 | int index = 0; 55 | 56 | // calling our method passing it index 0 which represents the root of our tree 57 | traversal(strArr, index, size); 58 | 59 | return result; 60 | } 61 | 62 | int main() 63 | { 64 | string A[] = { "5", "2", "6", "1", "9", "#", "8", "#", "#", "#", "#", "4", "#" }; 65 | string B[] = { "4", "1", "5", "2", "#", "#", "#" }; 66 | string C[] = { "2", "6", "#" }; 67 | string D[] = { "5", "2", "6", "#", "9", "8", "1", "#", "#", "12", "15", "#", "#", "#", "45" }; 68 | 69 | cout << PreorderTraversal(A, sizeof(A) / sizeof(A[0])) << endl; // 5 2 1 9 6 8 4 70 | cout << PreorderTraversal(B, sizeof(B) / sizeof(B[0])) << endl; // 4 1 2 5 71 | cout << PreorderTraversal(C, sizeof(C) / sizeof(C[0])) << endl; // 2 6 72 | cout << PreorderTraversal(D, sizeof(D) / sizeof(D[0])) << endl; // 5 2 9 12 15 6 8 1 45 73 | return 0; 74 | } -------------------------------------------------------------------------------- /56_SymmetricTree.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will traverse a binary tree and determine if it is symmetric. 2 | /* 3 | have the function SymmetricTree(strArr) take the array of strings stored in strArr, which will represent a binary tree, and determine if the tree is symmetric (a mirror image of itself). The array will be implemented similar to how a binary heap is implemented, except the tree may not be complete and NULL nodes on any level of the tree will be represented with a #. For example: if strArr is ["1", "2", "2", "3", "#", "#", "3"] 4 | For the input above, your program should return the string true because the binary tree is symmetric. 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | 13 | /* 14 | first check the number of nodes present 15 | if size is 1 than return true only if is null 16 | if size is 3 assure that it also represent just a root node, so a valid node, with 2 null nodes is valid 17 | if none of the previous 2 are met than we need at least 7 nodes to have a mirror image of each subtree 18 | note that null nodes are count as an element in the array 19 | we are going to take an approach similar to a level order 20 | as we traverse the tree add parents to a queue 21 | we than compare the children of each parent 22 | after comparing we pop those current parent from the queue and add the valid children 23 | we continue to move down the tree 24 | the sibling must match in a reverse fashion, meaning if parent A has a left child with value 5 25 | than parent B must have a right child with value 5. We analyze the inverse also 26 | this traversal will continue until the queue is empty, note that any null nodes are not added to the queue 27 | */ 28 | 29 | 30 | // Will update the index for the children of the 2 parents 31 | void getChildren(int& leftChild, int& rightChild, string& left, string& right, int parent1, int parent2, string strArr[]) 32 | { 33 | leftChild = 2 * parent1 + 1; 34 | rightChild = 2 * parent2 + 2; 35 | left = strArr[leftChild]; 36 | right = strArr[rightChild]; 37 | } 38 | 39 | string SymmetricTree(string strArr[], int size) 40 | { 41 | if (size == 1) 42 | { 43 | if (strArr[0] == "#") 44 | { 45 | return "true"; 46 | } 47 | return "false"; 48 | } 49 | else if (size == 3) 50 | { 51 | // If first node is null return false 52 | // since a null node cannot have children 53 | if (strArr[0] == "#") 54 | { 55 | return "false"; 56 | } 57 | else if (strArr[0] != "#" && strArr[1] == "#" && strArr[2] == "#") 58 | { 59 | // This is valid since this represents a single node 60 | return "true"; 61 | } 62 | } 63 | else if (size < 7) 64 | { 65 | return "false"; 66 | } 67 | 68 | // setting our queue and pushing the root node as our start 69 | queue parents; 70 | parents.push(0); 71 | 72 | while (!parents.empty()) 73 | { 74 | int parent1, parent2; // represents the index for the parents in each subtree 75 | string left, right; // represents the value of the parents 76 | int leftChild, rightChild; // represents the index of left and right child 77 | 78 | // getting the current index for the parent/s 79 | if (parents.front() == 0) 80 | { 81 | // special case for when we do the root node 82 | parent1 = parent2 = parents.front(); 83 | parents.pop(); 84 | } 85 | else 86 | { 87 | // get index of the 2 parents from the queue 88 | parent1 = parents.front(); 89 | parents.pop(); 90 | parent2 = parents.front(); 91 | parents.pop(); 92 | 93 | // special case to bound check and determine if current node is a leaf node 94 | if (2 * parent1 + 1 >= size && 2 * parent2 + 2 >= size) 95 | { 96 | continue; 97 | } 98 | } 99 | 100 | // Loop that will iterate and get the child of the two parents 101 | // Will compare the left child or parent 1 to the right child of parent 2 102 | // Will inverse and compare right child of parent1 to left child of parent 2 103 | // Remember that all valid children are added to the queue 104 | int count = 0; 105 | while (count < 2) 106 | { 107 | // Getting child left to child right 108 | if (count == 0) 109 | { 110 | getChildren(leftChild, rightChild,left, right, parent1, parent2, strArr); 111 | } 112 | else if (count == 1) // Getting child right to child left 113 | { 114 | getChildren(leftChild, rightChild, left, right, parent2, parent1, strArr); 115 | } 116 | 117 | 118 | // Comparing the children 119 | if (left != right) 120 | { 121 | return "false"; 122 | } 123 | else 124 | { 125 | // we ignore any null nodes 126 | // we treat them as the next parent in the queue only if they are not null 127 | if (left != "#" && right != "#") 128 | { 129 | // adding the valid children 130 | parents.push(leftChild); 131 | parents.push(rightChild); 132 | } 133 | } 134 | 135 | // special again for root node 136 | // we don't need to compare right to left for root 137 | if (parent1 == 0) 138 | { 139 | break; 140 | } 141 | else 142 | { 143 | // update the counter 144 | count++; 145 | } 146 | } 147 | } 148 | 149 | return "true"; 150 | } 151 | 152 | int main() 153 | { 154 | string A[] = { "1", "2", "2", "3", "#", "#", "3" }; 155 | string B[] = { "4", "3", "4" }; 156 | string C[] = { "10", "2", "2", "#", "1", "1", "#" }; 157 | string D[] = { "4" }; 158 | string E[] = { "#" }; 159 | string F[] = { "30", "#", "#" }; 160 | string G[] = { "#", "10", "10" }; 161 | string H[] = { "1", "2", "2", "3", "#", "#", "7" }; 162 | string I[] = { "8", "6", "6", "4", "3", "3", "4", "#", "7", "5", "#", "#", "5", "7", "#", "#", "#", "#", "#", "#", "2", "#", "#", "#", "#", "2", "#", "#", "#", "#", "#" }; 163 | 164 | cout << SymmetricTree(A, sizeof(A)/sizeof(A[0]))<< endl; // true 165 | cout << SymmetricTree(B, sizeof(B) / sizeof(B[0])) << endl; // false 166 | cout << SymmetricTree(C, sizeof(C) / sizeof(C[0])) << endl; // true 167 | cout << SymmetricTree(D, sizeof(D) / sizeof(D[0])) << endl; // false 168 | cout << SymmetricTree(E, sizeof(E) / sizeof(E[0])) << endl; // true 169 | cout << SymmetricTree(F, sizeof(F) / sizeof(F[0])) << endl; // true 170 | cout << SymmetricTree(G, sizeof(G) / sizeof(G[0])) << endl; // false 171 | cout << SymmetricTree(H, sizeof(H) / sizeof(H[0])) << endl; // false 172 | cout << SymmetricTree(I, sizeof(I) / sizeof(I[0])) << endl; // true 173 | return 0; 174 | } 175 | -------------------------------------------------------------------------------- /57_BinarySearchTreeLCA.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will attempt to find the lowest common ancestor of a binary search tree. 2 | /* 3 | have the function BinarySearchTreeLCA(strArr) take the array of strings stored in strArr, which will contain 3 elements: the first element will be a binary search tree with all unique values in a preorder traversal array, the second and third elements will be two different values, and your goal is to find the lowest common ancestor of these two values. For example: if strArr is ["[10, 5, 1, 7, 40, 50]", "1", "7"] then this tree looks like the following: 4 | 5 | 6 | 7 | For the input above, your program should return 5 because that is the value of the node that is the LCA of the two nodes with values 1 and 7. You can assume the two nodes you are searching for in the tree will exist somewhere in the tree. 8 | */ 9 | 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | string BinarySearchTreeLCA(string strArr[]) 15 | { 16 | 17 | } 18 | 19 | int main() 20 | { 21 | string A[] = {}; 22 | cout << BinarySearchTreeLCA(A) << endl; 23 | return 0; 24 | 25 | } -------------------------------------------------------------------------------- /58_TreeConstructor.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine if an array of integer pairs can form a binary tree properly. 2 | /* 3 | have the function TreeConstructor(strArr) take the array of strings stored in strArr, which will contain pairs of integers in the following format: (i1,i2), where i1 represents a child node in a tree and the second integer i2 signifies that it is the parent of i1. For example: if strArr is ["(1,2)", "(2,4)", "(7,2)"] 4 | 5 | which you can see forms a proper binary tree. Your program should, in this case, return the string true because a valid binary tree can be formed. If a proper binary tree cannot be formed with the integer pairs, then return the string false. All of the integers within the tree will be unique, which means there can only be one node in the tree with the given integer value. 6 | */ 7 | 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | string TreeConstructor(string strArr[]) 13 | { 14 | 15 | } 16 | 17 | int main() 18 | { 19 | string A[] = { "(1,2)", "(2,4)", "(7,2)" }; 20 | cout << TreeConstructor(A); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /59_HistogramArea.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine the largest area under a histogram. 2 | /* 3 | have the function HistogramArea(arr) read the array of non-negative integers stored in arr which will represent the heights of bars on a graph (where each bar width is 1), and determine the largest area underneath the entire bar graph. For example: if arr is [2, 1, 3, 4, 1] then this looks like the following bar graph: 4 | 5 | You can see in the above bar graph that the largest area underneath the graph is covered by the x's. The area of that space is equal to 6 because the entire width is 2 and the maximum height is 3, therefore 2 * 3 = 6. Your program should return 6. The array will always contain at least 1 element. 6 | */ 7 | 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | /* 13 | as we traverse the array we will analyze each height 14 | each height will be compared to its neighbor height 15 | if the neighboring heights are greater than or equal to current height than update its width 16 | after we calculate the area for that height 17 | */ 18 | int HistogramArea(int arr[], int size) 19 | { 20 | int maxArea = 0; 21 | 22 | for (int current = 0; current < size; current++) 23 | { 24 | int width = 1; 25 | int moveRight = current + 1; 26 | int moveLeft = current - 1; 27 | 28 | // loop to check all the neighbors to the right of the current height 29 | // recall we only track neighbors that are greater than or equal to current height 30 | // if is valid we update the width 31 | while (moveRight < size && arr[moveRight] >= arr[current]) 32 | { 33 | width++; 34 | 35 | moveRight++; 36 | } 37 | 38 | // similar to checking the right neighbors here we check to the left of the array 39 | while (moveLeft >= 0 && arr[moveLeft] >= arr[current]) 40 | { 41 | width++; 42 | 43 | moveLeft--; 44 | } 45 | 46 | // Now we calculate the area for this height based on our rule 47 | if (width * arr[current] > maxArea) 48 | { 49 | maxArea = width* arr[current]; 50 | } 51 | } 52 | 53 | return maxArea; 54 | } 55 | 56 | int main() { 57 | int A[] = { 2, 1, 3, 4, 1 }; 58 | int B[] = { 6, 3, 1, 4, 12, 4 }; 59 | int C[] = { 5, 6, 7, 4, 1 }; 60 | 61 | cout << HistogramArea(A, sizeof(A) / sizeof(A[0])) << endl; // 6 62 | cout << HistogramArea(B, sizeof(B) / sizeof(B[0])) << endl; // 12 63 | cout << HistogramArea(C, sizeof(C) / sizeof(C[0])) << endl; // 16 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /5_Division.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine the Greatest Common Factor between two numbers. 2 | // have the function Division(num1,num2) take both parameters being passed and return the Greatest Common Factor. That is, return the greatest number that evenly goes into both numbers with no remainder. For example: 12 and 16 both are divisible by 1, 2, and 4 so the output should be 4. The range for both parameters will be from 1 to 10^3. 3 | 4 | #include 5 | using namespace std; 6 | 7 | int Division(int num1, int num2) { 8 | 9 | int high = 1; 10 | int size; 11 | // Find the greatest of the two arguments 12 | if (num1 >= num2) 13 | { 14 | size = num1; 15 | } 16 | else 17 | { 18 | size = num2; 19 | } 20 | for (int x = 1; x < size; x++) 21 | { 22 | if (num1%x == 0 && num2%x == 0 && x > high) 23 | { 24 | high = x; 25 | } 26 | } 27 | return high; 28 | } 29 | 30 | int main() { 31 | 32 | // keep this function call here 33 | cout << Division(7, 2) << endl; // 1 34 | cout << Division(36, 54) << endl; // 18 35 | cout << Division(12, 16) << endl; // 4 36 | return 0; 37 | 38 | } -------------------------------------------------------------------------------- /60_StringZigzag.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be printing a string in a particular zig-zag format. 2 | /* 3 | have the function StringZigzag(strArr) read the array of strings stored in strArr, which will contain two elements, the first some sort of string and the second element will be a number ranging from 1 to 6. The number represents how many rows to print the string on so that it forms a zig-zag pattern. For example: if strArr is ["coderbyte", "3"] then this word will look like the following if you print it in a zig-zag pattern with 3 rows: 4 | 5 | c r e 6 | o e b t 7 | d y 8 | 9 | 10 | Your program should return the word formed by combining the characters as you iterate through each row, so for this example your program should return the string creoebtdy. 11 | */ 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | using namespace std; 18 | 19 | 20 | /* 21 | create a matrix based on the data provided 22 | the length of the string element will represent the column count 23 | the input number will represent the row count 24 | we than traverse the first string element and store its characters into the matrix based on their location 25 | their column will be parallel to the index of their string 26 | for the row position we will keep a counter 27 | with each iteration it updates, when it reaches the bottom it will decrement back to the top 28 | 29 | For the output a straight solution is to traverse our matrix from top to bottom and extract only valid characters 30 | */ 31 | string StringZigzag(string strArr[], int size) 32 | { 33 | int colSize = strArr[0].length(); 34 | int rowSize; 35 | istringstream(strArr[1]) >> rowSize; 36 | 37 | if (rowSize <= 1) 38 | { 39 | return strArr[0]; 40 | } 41 | 42 | vector < vector > matrixMap(rowSize); 43 | 44 | // loop to create a matrix map with garbage values 45 | for (int row = 0; row < rowSize; row++) 46 | { 47 | for (int col = 0; col < colSize; col++) 48 | { 49 | matrixMap[row].push_back('#'); 50 | } 51 | } 52 | 53 | int currentRow = 0; 54 | bool traverseDown = true; 55 | 56 | // loop to fill the matrix map with the characters from our input string 57 | for (int currentCol = 0; currentCol < strArr[0].length(); currentCol++) 58 | { 59 | // adding the current character to the correct location 60 | matrixMap[currentRow][currentCol] = strArr[0][currentCol]; 61 | 62 | // update our row index 63 | if (traverseDown) 64 | { 65 | currentRow++; 66 | } 67 | else 68 | { 69 | currentRow--; 70 | } 71 | 72 | // Condition to determine if we traverse to the bottom or the top 73 | if (currentRow == rowSize) 74 | { 75 | currentRow -= 2; 76 | traverseDown = false; 77 | } 78 | else if (currentRow == -1 && !traverseDown) 79 | { 80 | currentRow += 2; 81 | traverseDown = true; 82 | } 83 | 84 | } 85 | 86 | string result = ""; 87 | //loop to extract the characters in their new correct order 88 | for (int row = 0; row < rowSize; row++) 89 | { 90 | for (int col = 0; col < colSize; col++) 91 | { 92 | if (matrixMap[row][col] != '#') 93 | { 94 | result += matrixMap[row][col]; 95 | } 96 | } 97 | } 98 | 99 | return result; 100 | } 101 | 102 | int main() 103 | { 104 | string A[] = { "coderbyte", "3" }; 105 | string B[] = { "cat", "5" }; 106 | string C[] = { "kaamvjjfl", "4" }; 107 | string D[] = { "aeettym", "1" }; 108 | 109 | cout << StringZigzag(A, sizeof(A) / sizeof(A[0])) << endl; // creoebtdy 110 | cout << StringZigzag(B, sizeof(B) / sizeof(B[0])) << endl; // cat 111 | cout << StringZigzag(C, sizeof(C) / sizeof(C[0])) << endl; // kjajfavlm 112 | cout << StringZigzag(D, sizeof(D) / sizeof(D[0])) << endl; // aeettym 113 | return 0; 114 | } -------------------------------------------------------------------------------- /61_PlusMinus.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will need to determine how to add or subtract numbers to end up with zero. 2 | /* 3 | have the function PlusMinus(num) read the num parameter being passed which will be a combination of 1 or more single digits, and determine if it's possible to separate the digits with either a plus or minus sign to get the final expression to equal zero. For example: if num is 35132 then it's possible to separate the digits the following way, 4 | 3 - 5 + 1 + 3 - 2, and this expression equals zero. Your program should return a string of the signs you used, so for this example your program should return -++-. If it's not possible to get the digit expression to equal zero, return the string not possible. 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | int PlusMinus(int num) 13 | { 14 | 15 | } 16 | 17 | int main() 18 | { 19 | 20 | cout << PlusMinus(35132) << endl; // -++- 21 | cout << PlusMinus(199) << endl; // not possible 22 | cout << PlusMinus(26712) << endl; // -+-- 23 | 24 | return 0; 25 | 26 | } -------------------------------------------------------------------------------- /62_CharlieTheDog.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be helping a dog collect all the food in a grid. 2 | /* 3 | have the function CharlietheDog(strArr) read the array of strings stored in strArr which will be a 4x4 matrix of the characters 'C', 'H', 'F', 'O', where C represents Charlie the dog, H represents its home, F represents dog food, and O represents and empty space in the grid. Your goal is to figure out the least amount of moves required to get Charlie to grab each piece of food in the grid by moving up, down, left, or right, and then make it home right after. Charlie cannot move onto the home before all pieces of food have been collected. For example: if strArr is ["FOOF", "OCOO", "OOOH", "FOOO"], then this looks like the following grid: 4 | 5 | 6 | For the input above, the least amount of steps where the dog can reach each piece of food, and then return home is 11 steps, so your program should return the number 11. The grid will always contain between 1 and 8 pieces of food. 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | using namespace std; 15 | 16 | 17 | // return the corresponding points for the located item 18 | vector collectPoint(int x, int y) 19 | { 20 | vector temp; 21 | temp.push_back(x); 22 | temp.push_back(y); 23 | return temp; 24 | } 25 | 26 | // calculates distance between 2 points 27 | int calculateDistance(int x1, int y1, int x2, int y2) 28 | { 29 | // conditions to determine the operation to find the distance 30 | // if the fall on same column or same row we can apply a simple distance formula 31 | if (x1 == x2 || y1 == y2) 32 | { 33 | return (int)sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)); 34 | } 35 | 36 | int xDistance = (int)abs(y2 - y1); 37 | int yDistance = (int)abs(x2 - x1); 38 | return xDistance + yDistance; 39 | } 40 | 41 | 42 | /* 43 | Solution involves storing the index of the home, foods and Charlie 44 | 45 | We traverse the matrix to gather all the important locations 46 | 47 | once collected we can start from the home and reverse back to Charlie 48 | we can apply a greedy approach were at each iteration we find the food closest to our current destination 49 | so the start would be find the closest piece of food to the home 50 | next would include finding the closest piece of food, to this current food. etc 51 | 52 | we calculate the distance between each of the points each time we make a selection 53 | */ 54 | int CharlietheDog(string strArr[], int size) 55 | { 56 | vector < vector > result; 57 | 58 | int totalDistance = 0; 59 | 60 | // get the points of home location 61 | int currentX; 62 | int currentY; 63 | 64 | // get points of dog location 65 | int dogX; 66 | int dogY; 67 | 68 | // traversing the matrix to collect the important locations 69 | for (int row = 0; row < size; row++) 70 | { 71 | for (int col = 0; col < strArr[row].length(); col++) 72 | { 73 | // collect the home location 74 | if (strArr[row][col] == 'H') 75 | { 76 | currentX = row; 77 | currentY = col; 78 | } 79 | // collect the dog location 80 | else if (strArr[row][col] == 'C') 81 | { 82 | dogX = row; 83 | dogY = col; 84 | } 85 | // collect the food locations 86 | else if (strArr[row][col] == 'F') 87 | { 88 | result.push_back(collectPoint(row, col)); 89 | } 90 | } 91 | } 92 | 93 | // loop to analyze the list of points we collected to perform an optimal selection for each iteration 94 | while (result.size() > 0) 95 | { 96 | int lowest = INT_MAX; 97 | int lowestIndex; 98 | int lowestX; 99 | int lowestY; 100 | 101 | for (int x = 0; x < result.size(); x++) 102 | { 103 | // calculate the optimal distance from current location to others 104 | int getDistance = calculateDistance(currentX, currentY, result[x][0], result[x][1]); 105 | 106 | // update the optimal lowest distance 107 | if (getDistance < lowest) 108 | { 109 | lowest = getDistance; 110 | lowestIndex = x; 111 | lowestX = result[x][0]; 112 | lowestY = result[x][1]; 113 | } 114 | else if (getDistance == lowest && calculateDistance(dogX, dogY, lowestX, lowestY) < calculateDistance(dogX, dogY, result[x][0], result[x][1])) 115 | { 116 | // conditional dealing with multiple optimal paths at first check 117 | // our selection criteria will select the location furthers from the dog 118 | lowest = getDistance; 119 | lowestIndex = x; 120 | lowestX = result[x][0]; 121 | lowestY = result[x][1]; 122 | } 123 | } 124 | 125 | // update our total distance 126 | totalDistance += lowest; 127 | 128 | // updating our current points and removing from our list 129 | currentX = lowestX; 130 | currentY = lowestY; 131 | result.erase(result.begin() + lowestIndex); 132 | } 133 | 134 | // final step is to calculate distance from our last point to the location of the dog 135 | totalDistance += calculateDistance(currentX, currentY, dogX, dogY); 136 | 137 | return totalDistance; 138 | } 139 | 140 | int main() 141 | { 142 | string A[] = { "FOOF", "OCOO", "OOOH", "FOOO" }; 143 | string B[] = { "OOOO", "OOFF", "OCHO", "OFOO" }; 144 | string C[] = { "FOOO", "OCOH", "OFOF", "OFOO" }; 145 | string D[] = { "COFO", "OOFH", "OOFO", "OOFO" }; 146 | string E[] = { "FOFF", "FOOO", "OCOH", "FOFO" }; 147 | 148 | cout << CharlietheDog(A, sizeof(A)/sizeof(A[0])) << endl; // 11 149 | cout << CharlietheDog(B, sizeof(B) / sizeof(B[0])) << endl; // 7 150 | cout << CharlietheDog(C, sizeof(C) / sizeof(C[0])) << endl; // 10 151 | cout << CharlietheDog(D, sizeof(D) / sizeof(D[0])) << endl; // 8 152 | cout << CharlietheDog(E, sizeof(E) / sizeof(E[0])) << endl; // 12 153 | return 0; 154 | } 155 | -------------------------------------------------------------------------------- /63_EightQueens.cpp: -------------------------------------------------------------------------------- 1 | // This challenge will require knowledge of chess pieces and their movements. 2 | /* 3 | have the function EightQueens(strArr) read strArr which will be an array consisting of the locations of eight Queens on a standard 8x8 chess board with no other pieces on the board. The structure of strArr will be the following: ["(x,y)", "(x,y)", ...] where (x,y) represents the position of the current queen on the chessboard (x and y will both range from 1 to 8 where 1,1 is the bottom-left of the chessboard and 8,8 is the top-right). Your program should determine if all of the queens are placed in such a way where none of them are attacking each other. If this is true for the given input, return the string true otherwise return the first queen in the list that is attacking another piece in the same format it was provided. 4 | 5 | For example: if strArr is ["(2,1)", "(4,2)", "(6,3)", "(8,4)", "(3,5)", "(1,6)", "(7,7)", "(5,8)"] then your program should return the string true. The corresponding chessboard of queens for this input is below (taken from Wikipedia). 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | 14 | bool checkVertical(vector < vector >, int, int); 15 | bool checkHorizontal(vector < vector >, int, int); 16 | bool checkDiagonal(vector < vector >, int, int); 17 | 18 | /* 19 | solution would involve first creating an empty chessboard 20 | we would analyze the elements from the input string to position where the queens would go 21 | starting from the first queen in the list 22 | we analyze all possible paths (vertical, horizontal, diagonal) 23 | if the current queen is attack any other we return it 24 | else continue with the next queen to analyze 25 | if no attacks where found we return true 26 | */ 27 | string EightQueens(string strArr[]) 28 | { 29 | // creating the empty chess board 30 | vector < vector > chessBoard(8); 31 | for (int x = 0; x < 8; x++) 32 | { 33 | for (int y = 0; y < 8; y++) 34 | { 35 | chessBoard[x].push_back('-'); 36 | } 37 | } 38 | 39 | // analyzing the string input to locate the locations of each queen 40 | for (int x = 0; x < 8; x++) 41 | { 42 | int currentRow = 8 - ((int)strArr[x][1]-48); 43 | int currentCol = (int)strArr[x][3] - 1 - 48; 44 | 45 | // updating the chessboard with current queen location 46 | chessBoard[currentRow][currentCol] = 'q'; 47 | } 48 | 49 | // checking all queens for any attacks 50 | for (int x = 0; x < 8; x++) 51 | { 52 | int row = 8 - ((int)strArr[x][1] - 48); 53 | int col = (int)strArr[x][3] - 1 - 48; 54 | 55 | // condition to check no attacks where found in all the possible attacks routes for the current queen 56 | if (!(checkVertical(chessBoard, row, col) && checkHorizontal(chessBoard, row, col) && checkDiagonal(chessBoard, row, col))) 57 | { 58 | return strArr[x]; 59 | } 60 | } 61 | 62 | return "true"; 63 | } 64 | 65 | // method to check if any attacks happen while analyzing the vertical of current queen 66 | bool checkVertical(vector < vector > board, int row, int col) 67 | { 68 | for (int x = 0; x < 8; x++) 69 | { 70 | if (x == row) 71 | { 72 | continue; 73 | } 74 | 75 | // condition to find an attack 76 | if (board[x][col] == 'q') 77 | { 78 | return false; 79 | } 80 | } 81 | 82 | return true; 83 | } 84 | 85 | // method to check if any attacks happen horizontal to the current queen 86 | bool checkHorizontal(vector < vector > board, int row, int col) 87 | { 88 | for (int x = 0; x < 8; x++) 89 | { 90 | if (x == col) 91 | { 92 | continue; 93 | } 94 | 95 | if (board[row][x] == 'q') 96 | { 97 | return false; 98 | } 99 | } 100 | 101 | return true; 102 | } 103 | 104 | // method to check if any attacks happen diagonal to the current queen 105 | bool checkDiagonal(vector < vector > board, int row, int col) 106 | { 107 | int currentRow = row; 108 | int currentCol = col; 109 | 110 | // to bottom right diagonal direction 111 | currentRow++; 112 | currentCol++; 113 | while (currentCol < 8 && currentRow < 8) 114 | { 115 | if (board[currentRow][currentCol] == 'q') 116 | { 117 | return false; 118 | } 119 | currentRow++; 120 | currentCol++; 121 | } 122 | 123 | // to top right diagonal direction 124 | currentRow = row - 1; 125 | currentCol = col + 1; 126 | while (currentCol < 8 && currentRow >= 0) 127 | { 128 | if (board[currentRow][currentCol] == 'q') 129 | { 130 | return false; 131 | } 132 | currentRow--; 133 | currentCol++; 134 | } 135 | 136 | // to bottom left diagonal direction 137 | currentRow = row + 1; 138 | currentCol = col - 1; 139 | while (currentCol >= 0 && currentRow < 8) 140 | { 141 | if (board[currentRow][currentCol] == 'q') 142 | { 143 | return false; 144 | } 145 | currentRow++; 146 | currentCol--; 147 | } 148 | 149 | // to top left diagonal direction 150 | currentRow = row - 1; 151 | currentCol = col - 1; 152 | while (currentCol >= 0 && currentRow >= 0) 153 | { 154 | if (board[currentRow][currentCol] == 'q') 155 | { 156 | return false; 157 | } 158 | currentRow--; 159 | currentCol--; 160 | } 161 | 162 | return true; 163 | } 164 | 165 | int main() 166 | { 167 | string A[] = { "(2,1)", "(4,2)", "(6,3)", "(8,4)", "(3,5)", "(1,6)", "(7,7)", "(5,8)" }; 168 | string B[] = { "(2,1)", "(4,3)", "(6,3)", "(8,4)", "(3,4)", "(1,6)", "(7,7)", "(5,8)" }; 169 | string C[] = { "(2,1)", "(5,3)", "(6,3)", "(8,4)", "(3,4)", "(1,8)", "(7,7)", "(5,8)" }; 170 | 171 | cout << EightQueens(A) << endl; // true 172 | cout << EightQueens(B) << endl; // (2,1) 173 | cout << EightQueens(C) << endl; // (5,3) 174 | return 0; 175 | 176 | } -------------------------------------------------------------------------------- /6_StringScramble.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine if string 1 can be rearranged into string 2. 2 | // have the function StringScramble(str1,str2) take both parameters being passed and return the string true if a portion of str1 characters can be rearranged to match str2, otherwise return the string false. For example: if str1 is "rkqodlw" and str2 is "world" the output should return true. Punctuation and symbols will not be entered with the parameters. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | string StringScramble(string str1, string str2) { 9 | 10 | bool found; 11 | int index = -1; 12 | 13 | for (int x = 0; x < str2.length(); x++) 14 | { 15 | found = false; 16 | for (int y = 0; y < str1.length(); y++) 17 | { 18 | // Compare string2 to string2 to analyze if all the characters check 19 | if (str2[x] == str1[y] && y != index) 20 | { 21 | index = y; // Safeguarding that we do not use another previously utilized letter 22 | found = true; // Determine whether the letter was found 23 | } 24 | } 25 | if (!found) 26 | { 27 | return "false"; 28 | } 29 | } 30 | 31 | return "true"; 32 | } 33 | 34 | int main() { 35 | 36 | // keep this function call here 37 | cout << StringScramble("cdore","coder") << endl; // true 38 | cout << StringScramble("h3llko", "hello") << endl; // false 39 | cout << StringScramble("rkqodlw","world") << endl; // true 40 | cout << StringScramble("win33er", "winner") << endl; // false 41 | return 0; 42 | 43 | } -------------------------------------------------------------------------------- /7_ArithGeoII.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine if numbers within an array follow an arithmetic or geometric sequence. 2 | // have the function ArithGeoII(arr) take the array of numbers stored in arr and return the string "Arithmetic" if the sequence follows an arithmetic pattern or return "Geometric" if it follows a geometric pattern. If the sequence doesn't follow either pattern return -1. An arithmetic sequence is one where the difference between each of the numbers is consistent, where as in a geometric sequence, each term after the first is multiplied by some constant or common ratio. Arithmetic example: [2, 4, 6, 8] and Geometric example: [2, 6, 18, 54]. Negative numbers may be entered as parameters, 0 will not be entered, and no array will contain all the same elements. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | string ArithGeoII(int arr[], int size) { 9 | 10 | int pattern, pattern2; 11 | 12 | // Find the pattern 13 | pattern = arr[1]- arr[0]; 14 | pattern2 = arr[1] / arr[0]; 15 | 16 | bool arith = true, geo = true; 17 | // Check to see if the pattern stays true when we traverse the array 18 | for (int y = 0; y < size - 1; y++) 19 | { 20 | if (arr[y + 1] - arr[y] != pattern) 21 | { 22 | arith = false; 23 | } 24 | if (arr[y + 1] / arr[y] != pattern2) 25 | { 26 | geo = false; 27 | } 28 | } 29 | 30 | if (arith) 31 | { 32 | return "Arithmetic"; 33 | } 34 | else if (geo) 35 | { 36 | return "Geometric"; 37 | } 38 | else 39 | { 40 | return "-1"; 41 | } 42 | } 43 | 44 | int main() { 45 | 46 | // keep this function call here 47 | /* Note: In C++ you first have to initialize an array and set 48 | it equal to the stdin to test your code with arrays. */ 49 | 50 | int A[] = {5,10,15}; 51 | int B[] = {2,4,16,24}; 52 | int C[] = {2,4,6,8}; 53 | int D[] = {2,6,18,54}; 54 | cout << ArithGeoII(A, sizeof(A) / sizeof(A[0])) << endl; // Arithmetic 55 | cout << ArithGeoII(B, sizeof(B) / sizeof(B[0])) << endl; // -1 56 | cout << ArithGeoII(C, sizeof(C) / sizeof(C[0])) << endl; // Arithmetic 57 | cout << ArithGeoII(D, sizeof(D) / sizeof(D[0])) << endl; // Geometric 58 | return 0; 59 | 60 | } -------------------------------------------------------------------------------- /8_BinaryConverter.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will be converting a number from binary to decimal. 2 | // have the function BinaryConverter(str) return the decimal form of the binary value. For example: if 101 is passed return 5, or if 1000 is passed return 8. 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | int BinaryConverter(string str) { 10 | 11 | int total = 0; // Will determine the decimal total 12 | 13 | for (int x = 0; x < str.length(); x++) 14 | { 15 | // If the switch is true perform the calculation 16 | if (str[x] == '1') 17 | { 18 | // This is based on the formula 19 | // Example 2^0 + 2^1+ 2^2+...... 20 | total += pow(2, (str.length() - x) - 1); 21 | } 22 | } 23 | return total; 24 | } 25 | 26 | int main() { 27 | 28 | // keep this function call here 29 | cout << BinaryConverter("100101") << endl; // 37 30 | cout << BinaryConverter("011") << endl; // 3 31 | cout << BinaryConverter("101") << endl; // 5 32 | cout << BinaryConverter("1000") << endl; // 8 33 | return 0; 34 | 35 | } -------------------------------------------------------------------------------- /9_SimpleMode.cpp: -------------------------------------------------------------------------------- 1 | // For this challenge you will determine the mode, the number that appears most frequently, in an array. 2 | // have the function SimpleMode(arr) take the array of numbers stored in arr and return the number that appears most frequently (the mode). For example: if arr contains [10, 4, 5, 2, 4] the output should be 4. If there is more than one mode return the one that appeared in the array first (ie. [5, 10, 10, 6, 5] should return 5 because it appeared first). If there is no mode return -1. The array will not be empty. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | int SimpleMode(int arr[], int size) { 9 | 10 | int value = -1, count, high = 0; 11 | 12 | for (int x = 0; x < size; x++) 13 | { 14 | // Keep track of time the number repeats and the index of that repeating number 15 | count = 1; 16 | 17 | for (int y = 0; y < size; y++) 18 | { 19 | if (x == y) 20 | { 21 | continue; 22 | } 23 | 24 | if (arr[x] == arr[y]) 25 | { 26 | count++; 27 | } 28 | 29 | // Only replace the value with a number that has a higher repetition 30 | if (count > high) 31 | { 32 | value = arr[x]; 33 | high = count; 34 | } 35 | } 36 | } 37 | 38 | if (high == 1) 39 | { 40 | return -1; 41 | } 42 | else 43 | { 44 | return value; 45 | } 46 | } 47 | 48 | int main() { 49 | 50 | // keep this function call here 51 | /* Note: In C++ you first have to initialize an array and set 52 | it equal to the stdin to test your code with arrays. */ 53 | 54 | int A[] = {5,5,2,2,1}; 55 | int B[] = {3,4,1,6,10}; 56 | int C[] = {10,4,5,2,4}; 57 | int D[] = {5,10,10,6,5}; 58 | int E[] = { 4, 4, 5, 6, 7, 8, 8, 8, 8, 8 }; 59 | cout << SimpleMode(A, sizeof(A) / sizeof(A[0])) << endl; // 5 60 | cout << SimpleMode(B, sizeof(B)/sizeof(B[0])) << endl; // -1 61 | cout << SimpleMode(C, sizeof(C) / sizeof(C[0])) << endl; // 4 62 | cout << SimpleMode(D, sizeof(D) / sizeof(D[0])) << endl; // 5 63 | cout << SimpleMode(E, sizeof(E) / sizeof(E[0])) << endl; // 8 64 | return 0; 65 | } 66 | 67 | -------------------------------------------------------------------------------- /Debug/Fun Practice 2.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gutty333/Medium-Programming-Challenges/d4391b338607a1a08b5fc29799738ae063f95d62/Debug/Fun Practice 2.exe -------------------------------------------------------------------------------- /Debug/Fun Practice 2.log: -------------------------------------------------------------------------------- 1 | Build started 6/19/2018 5:43:45 PM. 2 | 1>Project "C:\Users\gutty333\Documents\Visual Studio 2013\Projects\Fun Practice 2\Fun Practice 2\Fun Practice 2.vcxproj" on node 2 (Build target(s)). 3 | 1>ClCompile: 4 | C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\CL.exe /c /ZI /nologo /W3 /WX- /sdl /Od /Oy- /D WIN32 /D _DEBUG /D _CONSOLE /D _LIB /D _UNICODE /D UNICODE /Gm /EHsc /RTC1 /MDd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Fo"Debug\\" /Fd"Debug\vc120.pdb" /Gd /TP /analyze- /errorReport:prompt 43_PairSearching.cpp 5 | 43_PairSearching.cpp 6 | 1>c:\users\gutty333\documents\visual studio 2013\projects\fun practice 2\fun practice 2\43_pairsearching.cpp(30): warning C4018: '<' : signed/unsigned mismatch 7 | 1>c:\users\gutty333\documents\visual studio 2013\projects\fun practice 2\fun practice 2\43_pairsearching.cpp(98): warning C4018: '<' : signed/unsigned mismatch 8 | 1>c:\users\gutty333\documents\visual studio 2013\projects\fun practice 2\fun practice 2\43_pairsearching.cpp(112): warning C4018: '<' : signed/unsigned mismatch 9 | 1>c:\users\gutty333\documents\visual studio 2013\projects\fun practice 2\fun practice 2\43_pairsearching.cpp(126): warning C4715: 'PairSearching' : not all control paths return a value 10 | Link: 11 | C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\link.exe /ERRORREPORT:PROMPT /OUT:"C:\Users\gutty333\Documents\Visual Studio 2013\Projects\Fun Practice 2\Debug\Fun Practice 2.exe" /INCREMENTAL /NOLOGO kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /MANIFEST /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /manifest:embed /DEBUG /PDB:"C:\Users\gutty333\Documents\Visual Studio 2013\Projects\Fun Practice 2\Debug\Fun Practice 2.pdb" /SUBSYSTEM:CONSOLE /TLBID:1 /DYNAMICBASE /NXCOMPAT /IMPLIB:"C:\Users\gutty333\Documents\Visual Studio 2013\Projects\Fun Practice 2\Debug\Fun Practice 2.lib" /MACHINE:X86 Debug\43_PairSearching.obj 12 | Fun Practice 2.vcxproj -> C:\Users\gutty333\Documents\Visual Studio 2013\Projects\Fun Practice 2\Debug\Fun Practice 2.exe 13 | 1>Done Building Project "C:\Users\gutty333\Documents\Visual Studio 2013\Projects\Fun Practice 2\Fun Practice 2\Fun Practice 2.vcxproj" (Build target(s)). 14 | 15 | Build succeeded. 16 | 17 | Time Elapsed 00:00:01.47 18 | -------------------------------------------------------------------------------- /Debug/Fun Practice 2.tlog/CL.read.1.tlog: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gutty333/Medium-Programming-Challenges/d4391b338607a1a08b5fc29799738ae063f95d62/Debug/Fun Practice 2.tlog/CL.read.1.tlog -------------------------------------------------------------------------------- /Debug/Fun Practice 2.tlog/CL.write.1.tlog: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gutty333/Medium-Programming-Challenges/d4391b338607a1a08b5fc29799738ae063f95d62/Debug/Fun Practice 2.tlog/CL.write.1.tlog -------------------------------------------------------------------------------- /Debug/Fun Practice 2.tlog/Fun Practice 2.lastbuildstate: -------------------------------------------------------------------------------- 1 | #TargetFrameworkVersion=v4.0:PlatformToolSet=v120:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit 2 | Debug|Win32|C:\Users\gutty333\Documents\Visual Studio 2013\Projects\Fun Practice 2\| 3 | -------------------------------------------------------------------------------- /Debug/Fun Practice 2.tlog/cl.command.1.tlog: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gutty333/Medium-Programming-Challenges/d4391b338607a1a08b5fc29799738ae063f95d62/Debug/Fun Practice 2.tlog/cl.command.1.tlog -------------------------------------------------------------------------------- /Debug/Fun Practice 2.tlog/link.command.1.tlog: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gutty333/Medium-Programming-Challenges/d4391b338607a1a08b5fc29799738ae063f95d62/Debug/Fun Practice 2.tlog/link.command.1.tlog -------------------------------------------------------------------------------- /Debug/Fun Practice 2.tlog/link.read.1.tlog: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gutty333/Medium-Programming-Challenges/d4391b338607a1a08b5fc29799738ae063f95d62/Debug/Fun Practice 2.tlog/link.read.1.tlog -------------------------------------------------------------------------------- /Debug/Fun Practice 2.tlog/link.write.1.tlog: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gutty333/Medium-Programming-Challenges/d4391b338607a1a08b5fc29799738ae063f95d62/Debug/Fun Practice 2.tlog/link.write.1.tlog -------------------------------------------------------------------------------- /Debug/vc120.idb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gutty333/Medium-Programming-Challenges/d4391b338607a1a08b5fc29799738ae063f95d62/Debug/vc120.idb -------------------------------------------------------------------------------- /Fun Practice 2.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25123.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Fun Practice 2", "Fun Practice 2.vcxproj", "{A48563CC-5D12-4890-82E1-B6086503E339}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|x86 = Debug|x86 11 | Release|x86 = Release|x86 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {A48563CC-5D12-4890-82E1-B6086503E339}.Debug|x86.ActiveCfg = Debug|Win32 15 | {A48563CC-5D12-4890-82E1-B6086503E339}.Debug|x86.Build.0 = Debug|Win32 16 | {A48563CC-5D12-4890-82E1-B6086503E339}.Release|x86.ActiveCfg = Release|Win32 17 | {A48563CC-5D12-4890-82E1-B6086503E339}.Release|x86.Build.0 = Release|Win32 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /Fun Practice 2.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | 14 | 15 | 16 | 17 | {A48563CC-5D12-4890-82E1-B6086503E339} 18 | Win32Proj 19 | FunPractice2 20 | 21 | 22 | 23 | Application 24 | true 25 | v120 26 | Unicode 27 | 28 | 29 | Application 30 | false 31 | v140 32 | true 33 | Unicode 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | true 47 | 48 | 49 | false 50 | 51 | 52 | 53 | 54 | 55 | Level3 56 | Disabled 57 | WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) 58 | true 59 | 60 | 61 | Console 62 | true 63 | 64 | 65 | 66 | 67 | Level3 68 | 69 | 70 | MaxSpeed 71 | true 72 | true 73 | WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) 74 | true 75 | 76 | 77 | Console 78 | true 79 | true 80 | true 81 | 82 | 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /Fun Practice 2.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Fun-Practice-2 2 | Medium programming challenges from coderbyte. 3 | 4 | ### Highlights ### 5 | String Algorithms 6 | Stacks and Queues 7 | Linked List and Binary Search Trees 8 | Matrices 9 | -------------------------------------------------------------------------------- /extra_ChromosomeMatch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | bool globe(string); 7 | bool eyespot(string); 8 | bool leg(string); 9 | 10 | 11 | /* 12 | must start with one or more A's 13 | the number of A's determines the size of the globe 14 | A's are followed by CAT or TAC 15 | is terminated by a single A 16 | */ 17 | bool globe(string input) 18 | { 19 | string temp; 20 | int x = 0; 21 | 22 | // traverse the whole string 23 | while (x < input.length()) 24 | { 25 | // proceed as we come across the A's 26 | if (input[x] == 'A') 27 | { 28 | x++; 29 | } 30 | else 31 | { 32 | // condition to check the following substring after the A's 33 | // we traverse 3 steps if the strings match else we signal the sequence is not valid 34 | temp = input.substr(x, 3); 35 | 36 | if (temp == "TAC" || temp == "CAT") 37 | { 38 | x += 3; 39 | } 40 | else 41 | { 42 | return false; 43 | } 44 | } 45 | } 46 | 47 | // checking that the end only has a single A 48 | if (input[input.length() - 1] == 'A' && input[input.length() - 2] != 'A') 49 | { 50 | return true; 51 | } 52 | 53 | return false; 54 | } 55 | 56 | /* 57 | starts with a T 58 | if is on a stalk it will include legs 59 | if not on a stalk it will have the pattern AG until the end 60 | terminates with AG 61 | */ 62 | bool eyespot(string input) 63 | { 64 | // assure the first base starts with T 65 | if (input[0] == 'T') 66 | { 67 | int x = 1; 68 | 69 | // traverse the string 70 | while (x < input.length()) 71 | { 72 | // check if it is on a stalk 73 | if (input[x] == 'C') 74 | { 75 | int y; 76 | // loop to locate the end of a possible leg 77 | for (y = x; y < input.length() - 2; y++) 78 | { 79 | if (input[y] == 'T') 80 | { 81 | break; 82 | } 83 | } 84 | 85 | // condition to check the leg found is valid 86 | if (leg(input.substr(x, (y - x) + 1))) 87 | { 88 | x = y + 1; 89 | } 90 | else 91 | { 92 | return false; 93 | } 94 | } 95 | else if (input[x] == 'A' && input[x+1] == 'G') // condition checking the alternative of not being on a stalk 96 | { 97 | x += 2; 98 | } 99 | else 100 | { 101 | return false; 102 | } 103 | } 104 | 105 | return true; 106 | } 107 | 108 | return false; 109 | } 110 | 111 | 112 | /* 113 | starts with a C 114 | followed by one or more G's 115 | the number of G's determine the length of the leg 116 | terminated with a T 117 | */ 118 | bool leg(string input) 119 | { 120 | // condition checking for first and last characters 121 | if (input[0] == 'C' && input[input.length() - 1] == 'T') 122 | { 123 | int x = 1; 124 | 125 | // all characters in between the start and end must be a G 126 | while (x < input.length() - 1) 127 | { 128 | if (input[x] != 'G') 129 | { 130 | return false; 131 | } 132 | x++; 133 | } 134 | 135 | return true; 136 | } 137 | 138 | return false; 139 | } 140 | 141 | /* 142 | the string will include a single head and is followed by one or more body segments 143 | the head has a globe and ore or more eyespots 144 | 145 | the single or multiple body segments consist of a globe followed by one or more legs 146 | */ 147 | bool squirmy(string input) 148 | { 149 | bool globeFound = false; 150 | bool eyepotFound = false; 151 | bool legFound = false; 152 | int lastindex = 0; 153 | 154 | for (int x = 4; x < input.length(); x++) 155 | { 156 | // locate the globe 157 | if (!globeFound && globe(input.substr(lastindex, (x + 1) - lastindex))) 158 | { 159 | globeFound = true; 160 | lastindex = x + 1; 161 | x++; 162 | } 163 | // condition to locate the one or more eye spots 164 | else if (globeFound && eyespot(input.substr(lastindex, (x + 1) - lastindex))) 165 | { 166 | eyepotFound = true; 167 | globeFound = false; 168 | 169 | lastindex = x + 1; 170 | x++; 171 | } 172 | // locating the one or more legs 173 | else if (globeFound && eyepotFound && leg(input.substr(lastindex, (x + 1) - lastindex))) 174 | { 175 | legFound = true; 176 | 177 | lastindex = x + 1; 178 | x++; 179 | } 180 | else 181 | { 182 | legFound = false; 183 | } 184 | } 185 | 186 | if (globeFound && eyepotFound && legFound) 187 | { 188 | return true; 189 | } 190 | else 191 | { 192 | return false; 193 | } 194 | } 195 | 196 | int main() 197 | { 198 | vector chromosomes; 199 | 200 | // taking input for the chromosomes 201 | int num; 202 | cin >> num; 203 | for (int x = 0; x < num; x++) 204 | { 205 | string temp; 206 | cin >> temp; 207 | chromosomes.push_back(temp); 208 | } 209 | 210 | 211 | cout << "SQUIRMY OUTPUT" << endl; 212 | for (int x = 0; x < num; x++) 213 | { 214 | cout << "Case " << x + 1 << ": " << (squirmy(chromosomes[x]) ? "YES" : "NO" )<< endl; 215 | } 216 | cout << "END OF OUTPUT" << endl; 217 | 218 | return 0; 219 | } -------------------------------------------------------------------------------- /extra_ShortestPathFile.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | // structure to represent a vertex 9 | struct node 10 | { 11 | int cost; 12 | bool visited; 13 | vector neighborsCost; 14 | }; 15 | 16 | void shortestPath(vector & graph, int source) 17 | { 18 | queue list; 19 | graph[source - 1]->cost = 0; 20 | list.push(graph[source - 1]); 21 | 22 | // applying a simple BFS 23 | while (!list.empty()) 24 | { 25 | node* current = list.front(); 26 | list.pop(); 27 | current->visited = true; 28 | 29 | // checking the neighbors of our current node 30 | // we are always updating the distance to neighbors if we find a more optimal value 31 | for (int x = 0; x < current->neighborsCost.size(); x++) 32 | { 33 | int cost = current->neighborsCost[x]; 34 | 35 | // condition that checks if there is a connection and if the current connection has not yet been visited 36 | if (cost != -1 && graph[x]->visited == false) 37 | { 38 | // doing edge relaxation 39 | // analyze the current cost it take from current to that node 40 | // if the current path there is the best choice, we update its cost 41 | int newCost = cost + current->cost; 42 | if (newCost < graph[x]->cost) 43 | { 44 | graph[x]->cost = newCost; 45 | } 46 | 47 | // adding the neighbor to our queue 48 | list.push(graph[x]); 49 | } 50 | } 51 | } 52 | } 53 | 54 | int main() 55 | { 56 | int n; 57 | int source; 58 | 59 | string filename; 60 | cout << "enter file name (include the extension)" << endl; 61 | cin >> filename; 62 | 63 | ifstream readFile(filename); 64 | 65 | readFile >> n; // get the number of vertices 66 | readFile >> source; // get the source node 67 | 68 | // setting up our graph 69 | vector graph; 70 | for (int x = 0; x < n; x++) 71 | { 72 | graph.push_back(new node); 73 | graph[x]->cost = 1000*100; // by default we set them all to infinity in this case just setting a high value 74 | graph[x]->visited = false; 75 | } 76 | 77 | // loop to extract cost of each distance from current node 78 | int index = 0; 79 | int count = 0; 80 | while (index < n) 81 | { 82 | string temp; 83 | readFile >> temp; 84 | int num; 85 | 86 | // condition utilize to convert to an int data type 87 | if (temp != "-") 88 | { 89 | num = stoi(temp); 90 | } 91 | else 92 | { 93 | num = -1; 94 | } 95 | 96 | // adding it to current list 97 | // note no connections as signaled as -1 98 | graph[index]->neighborsCost.push_back(num); 99 | 100 | // keeping track of which node we are modifying 101 | count++; 102 | if (count == n) 103 | { 104 | count = 0; 105 | index++; 106 | } 107 | } 108 | 109 | // calling our shortest path method 110 | shortestPath(graph, source); 111 | 112 | // outputting the result 113 | for (int x = 0; x < graph.size(); x++) 114 | { 115 | if (source == x + 1) 116 | { 117 | continue; 118 | } 119 | 120 | cout << "(" << source << " -> " << x + 1 << ") = " << graph[x]->cost << endl; 121 | } 122 | 123 | return 0; 124 | } -------------------------------------------------------------------------------- /graphInput.txt: -------------------------------------------------------------------------------- 1 | 5 2 | 1 3 | 0 2 - - 10 4 | - 0 3 - 7 5 | - - 0 4 - 6 | - - - 0 5 7 | - - 6 - 0 --------------------------------------------------------------------------------