codeparrot/xlcost-text-to-code huggingface dataset:
Count possible ways to construct buildings | C ++ program to count all possible way to construct buildings ; Returns count of possible ways for N sections ; Base case ; 2 for one side and 4 for two sides ; countB is count of ways with a building at the end countS is count of ways with a space at the end prev_countB and prev_countS are previous values of countB and countS respectively . Initialize countB and countS for one side ; Use the above recursive formula for calculating countB and countS using previous values ; Result for one side is sum of ways ending with building and ending with space ; Result for 2 sides is square of result for one side ; Driver program
#include <iostream> NEW_LINE using namespace std ; int countWays ( int N ) { if ( N == 1 ) return 4 ; int countB = 1 , countS = 1 , prev_countB , prev_countS ; for ( int i = 2 ; i <= N ; i ++ ) { prev_countB = countB ; prev_countS = countS ; countS = prev_countB + prev_countS ; countB = prev_countS ; } int result = countS + countB ; return ( result * result ) ; } int main ( ) { int N = 3 ; cout << " Count ▁ of ▁ ways ▁ for ▁ " << N << " ▁ sections ▁ is ▁ " << countWays ( N ) ; return 0 ; }
Count number of ways to reach a given score in a game | A C ++ program to count number of possible ways to a given score can be reached in a game where a move can earn 3 or 5 or 10 ; Returns number of ways to reach score n ; table [ i ] will store count of solutions for value i . ; Initialize all table values as 0 ; Base case ( If given value is 0 ) ; One by one consider given 3 moves and update the table [ ] values after the index greater than or equal to the value of the picked move ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int count ( int n ) { int table [ n + 1 ] , i ; for ( int j = 0 ; j < n + 1 ; j ++ ) table [ j ] = 0 ; table [ 0 ] = 1 ; for ( i = 3 ; i <= n ; i ++ ) table [ i ] += table [ i - 3 ] ; for ( i = 5 ; i <= n ; i ++ ) table [ i ] += table [ i - 5 ] ; for ( i = 10 ; i <= n ; i ++ ) table [ i ] += table [ i - 10 ] ; return table [ n ] ; } int main ( void ) { int n = 20 ; cout << " Count ▁ for ▁ " << n << " ▁ is ▁ " << count ( n ) << endl ; n = 13 ; cout << " Count ▁ for ▁ " << n << " ▁ is ▁ " << count ( n ) << endl ; return 0 ; }
Naive algorithm for Pattern Searching | C ++ program for Naive Pattern Searching algorithm ; A loop to slide pat [ ] one by one ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void search ( char * pat , char * txt ) { int M = strlen ( pat ) ; int N = strlen ( txt ) ; for ( int i = 0 ; i <= N - M ; i ++ ) { int j ; for ( j = 0 ; j < M ; j ++ ) if ( txt [ i + j ] != pat [ j ] ) break ; if ( j == M ) cout << " Pattern ▁ found ▁ at ▁ index ▁ " << i << endl ; } } int main ( ) { char txt [ ] = " AABAACAADAABAAABAA " ; char pat [ ] = " AABA " ; search ( pat , txt ) ; return 0 ; }
Rabin | Following program is a C ++ implementation of Rabin Karp Algorithm given in the CLRS book ; d is the number of characters in the input alphabet ; pat -> pattern txt -> text q -> A prime number ; hash value for pattern ; hash value for txt ; The value of h would be " pow ( d , ▁ M - 1 ) % q " ; Calculate the hash value of pattern and first window of text ; Slide the pattern over text one by one ; Check the hash values of current window of text and pattern . If the hash values match then only check for characters on by one ; Check for characters one by one ; if p == t and pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Calculate hash value for next window of text : Remove leading digit , add trailing digit ; We might get negative value of t , converting it to positive ; Driver code ; A prime number ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define d  256 NEW_LINE void search ( char pat [ ] , char txt [ ] , int q ) { int M = strlen ( pat ) ; int N = strlen ( txt ) ; int i , j ; int p = 0 ; int t = 0 ; int h = 1 ; for ( i = 0 ; i < M - 1 ; i ++ ) h = ( h * d ) % q ; for ( i = 0 ; i < M ; i ++ ) { p = ( d * p + pat [ i ] ) % q ; t = ( d * t + txt [ i ] ) % q ; } for ( i = 0 ; i <= N - M ; i ++ ) { if ( p == t ) { for ( j = 0 ; j < M ; j ++ ) { if ( txt [ i + j ] != pat [ j ] ) break ; } if ( j == M ) cout << " Pattern ▁ found ▁ at ▁ index ▁ " << i << endl ; } if ( i < N - M ) { t = ( d * ( t - txt [ i ] * h ) + txt [ i + M ] ) % q ; if ( t < 0 ) t = ( t + q ) ; } } } int main ( ) { char txt [ ] = " GEEKS ▁ FOR ▁ GEEKS " ; char pat [ ] = " GEEK " ; int q = 101 ; search ( pat , txt , q ) ; return 0 ; }
Optimized Naive Algorithm for Pattern Searching | C ++ program for A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different ; A modified Naive Pettern Searching algorithn that is optimized for the cases when all characters of pattern are different ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; slide the pattern by j ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void search ( string pat , string txt ) { int M = pat . size ( ) ; int N = txt . size ( ) ; int i = 0 ; while ( i <= N - M ) { int j ; for ( j = 0 ; j < M ; j ++ ) if ( txt [ i + j ] != pat [ j ] ) break ; if ( j == M ) { cout << " Pattern ▁ found ▁ at ▁ index ▁ " << i << endl ; i = i + M ; } else if ( j == 0 ) i = i + 1 ; else i = i + j ; } } int main ( ) { string txt = " ABCEABCDABCEABCD " ; string pat = " ABCD " ; search ( pat , txt ) ; return 0 ; }
Finite Automata algorithm for Pattern Searching | CPP program for Finite Automata Pattern searching Algorithm ; If the character c is same as next character in pattern , then simply increment state ; ns stores the result which is next state ; ns finally contains the longest prefix which is also suffix in " pat [ 0 . . state - 1 ] c " Start from the largest possible value and stop when you find a prefix which is also suffix ; This function builds the TF table which represents4 Finite Automata for a given pattern ; Prints all occurrences of pat in txt ; Process txt over FA . ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define NO_OF_CHARS  256  NEW_LINE int getNextState ( string pat , int M , int state , int x ) { if ( state < M && x == pat [ state ] ) return state + 1 ; int ns , i ; for ( ns = state ; ns > 0 ; ns -- ) { if ( pat [ ns - 1 ] == x ) { for ( i = 0 ; i < ns - 1 ; i ++ ) if ( pat [ i ] != pat [ state - ns + 1 + i ] ) break ; if ( i == ns - 1 ) return ns ; } } return 0 ; } void computeTF ( string pat , int M , int TF [ ] [ NO_OF_CHARS ] ) { int state , x ; for ( state = 0 ; state <= M ; ++ state ) for ( x = 0 ; x < NO_OF_CHARS ; ++ x ) TF [ state ] [ x ] = getNextState ( pat , M , state , x ) ; } void search ( string pat , string txt ) { int M = pat . size ( ) ; int N = txt . size ( ) ; int TF [ M + 1 ] [ NO_OF_CHARS ] ; computeTF ( pat , M , TF ) ; int i , state = 0 ; for ( i = 0 ; i < N ; i ++ ) { state = TF [ state ] [ txt [ i ] ] ; if ( state == M ) cout << " ▁ Pattern ▁ found ▁ at ▁ index ▁ " << i - M + 1 << endl ; } } int main ( ) { string txt = " AABAACAADAABAAABAA " ; string pat = " AABA " ; search ( pat , txt ) ; return 0 ; }
Boyer Moore Algorithm for Pattern Searching | C ++ Program for Bad Character Heuristic of Boyer Moore String Matching Algorithm ; The preprocessing function for Boyer Moore 's bad character heuristic ; Initialize all occurrences as - 1 ; Fill the actual value of last occurrence of a character ; A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm ; Fill the bad character array by calling the preprocessing function badCharHeuristic ( ) for given pattern ; s is shift of the pattern with respect to text ; there are n - m + 1 potential allignments ; Keep reducing index j of pattern while characters of pattern and text are matching at this shift s ; If the pattern is present at current shift , then index j will become - 1 after the above loop ; Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern . The condition s + m < n is necessary for the case when pattern occurs at the end of text ; Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern . The max function is used to make sure that we get a positive shift . We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; # define NO_OF_CHARS  256 NEW_LINE void badCharHeuristic ( string str , int size , int badchar [ NO_OF_CHARS ] ) { int i ; for ( i = 0 ; i < NO_OF_CHARS ; i ++ ) badchar [ i ] = -1 ; for ( i = 0 ; i < size ; i ++ ) badchar [ ( int ) str [ i ] ] = i ; } void search ( string txt , string pat ) { int m = pat . size ( ) ; int n = txt . size ( ) ; int badchar [ NO_OF_CHARS ] ; badCharHeuristic ( pat , m , badchar ) ; int s = 0 ; while ( s <= ( n - m ) ) { int j = m - 1 ; while ( j >= 0 && pat [ j ] == txt [ s + j ] ) j -- ; if ( j < 0 ) { cout << " pattern ▁ occurs ▁ at ▁ shift ▁ = ▁ " << s << endl ; s += ( s + m < n ) ? m - badchar [ txt [ s + m ] ] : 1 ; } else s += max ( 1 , j - badchar [ txt [ s + j ] ] ) ; } } int main ( ) { string txt = " ABAAABCD " ; string pat = " ABC " ; search ( txt , pat ) ; return 0 ; }
Anagram Substring Search ( Or Search for all permutations ) | C ++ program to search all anagrams of a pattern in a text ; This function returns true if contents of arr1 [ ] and arr2 [ ] are same , otherwise false . ; This function search for all permutations of pat [ ] in txt [ ] ; countP [ ] : Store count of all characters of pattern countTW [ ] : Store count of current window of text ; Traverse through remaining characters of pattern ; Compare counts of current window of text with counts of pattern [ ] ; Add current character to current window ; Remove the first character of previous window ; Check for the last window in text ; Driver program to test above function
#include <iostream> NEW_LINE #include <cstring> NEW_LINE #define MAX  256 NEW_LINE using namespace std ; bool compare ( char arr1 [ ] , char arr2 [ ] ) { for ( int i = 0 ; i < MAX ; i ++ ) if ( arr1 [ i ] != arr2 [ i ] ) return false ; return true ; } void search ( char * pat , char * txt ) { int M = strlen ( pat ) , N = strlen ( txt ) ; char countP [ MAX ] = { 0 } , countTW [ MAX ] = { 0 } ; for ( int i = 0 ; i < M ; i ++ ) { ( countP [ pat [ i ] ] ) ++ ; ( countTW [ txt [ i ] ] ) ++ ; } for ( int i = M ; i < N ; i ++ ) { if ( compare ( countP , countTW ) ) cout << " Found ▁ at ▁ Index ▁ " << ( i - M ) << endl ; ( countTW [ txt [ i ] ] ) ++ ; countTW [ txt [ i - M ] ] -- ; } if ( compare ( countP , countTW ) ) cout << " Found ▁ at ▁ Index ▁ " << ( N - M ) << endl ; } int main ( ) { char txt [ ] = " BACDGABCDA " ; char pat [ ] = " ABCD " ; search ( pat , txt ) ; return 0 ; }
Manacher 's Algorithm | A C program to implement Manachers Algorithm ; Position count ; LPS Length Array ; centerPosition ; centerRightPosition ; currentRightPosition ; currentLeftPosition ; Uncomment it to print LPS Length array printf ( " % d ▁ % d ▁ " , L [ 0 ] , L [ 1 ] ) ; ; get currentLeftPosition iMirror for currentRightPosition i ; If currentRightPosition i is within centerRightPosition R ; Attempt to expand palindrome centered at currentRightPosition i Here for odd positions , we compare characters and if match then increment LPS Length by ONE If even position , we just increment LPS by ONE without any character comparison ; Track maxLPSLength ; If palindrome centered at currentRightPosition i expand beyond centerRightPosition R , adjust centerPosition C based on expanded palindrome . ; Uncomment it to print LPS Length array printf ( " % d ▁ " , L [ i ] ) ; ; printf ( " \n " ) ;
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE char text [ 100 ] ; int min ( int a , int b ) { int res = a ; if ( b < a ) res = b ; return res ; } void findLongestPalindromicString ( ) { int N = strlen ( text ) ; if ( N == 0 ) return ; N = 2 * N + 1 ; int L [ N ] ; L [ 0 ] = 0 ; L [ 1 ] = 1 ; int C = 1 ; int R = 2 ; int i = 0 ; int iMirror ; int maxLPSLength = 0 ; int maxLPSCenterPosition = 0 ; int start = -1 ; int end = -1 ; int diff = -1 ; for ( i = 2 ; i < N ; i ++ ) { iMirror = 2 * C - i ; L [ i ] = 0 ; diff = R - i ; if ( diff > 0 ) L [ i ] = min ( L [ iMirror ] , diff ) ; while ( ( ( i + L [ i ] ) < N && ( i - L [ i ] ) > 0 ) && ( ( ( i + L [ i ] + 1 ) % 2 == 0 ) || ( text [ ( i + L [ i ] + 1 ) / 2 ] == text [ ( i - L [ i ] - 1 ) / 2 ] ) ) ) { L [ i ] ++ ; } if ( L [ i ] > maxLPSLength ) { maxLPSLength = L [ i ] ; maxLPSCenterPosition = i ; } if ( i + L [ i ] > R ) { C = i ; R = i + L [ i ] ; } } start = ( maxLPSCenterPosition - maxLPSLength ) / 2 ; end = start + maxLPSLength - 1 ; printf ( " LPS ▁ of ▁ string ▁ is ▁ % s ▁ : ▁ " , text ) ; for ( i = start ; i <= end ; i ++ ) printf ( " % c " , text [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( int argc , char * argv [ ] ) { strcpy ( text , " babcbabcbaccba " ) ; findLongestPalindromicString ( ) ; strcpy ( text , " abaaba " ) ; findLongestPalindromicString ( ) ; strcpy ( text , " abababa " ) ; findLongestPalindromicString ( ) ; strcpy ( text , " abcbabcbabcba " ) ; findLongestPalindromicString ( ) ; strcpy ( text , " forgeeksskeegfor " ) ; findLongestPalindromicString ( ) ; strcpy ( text , " caba " ) ; findLongestPalindromicString ( ) ; strcpy ( text , " abacdfgdcaba " ) ; findLongestPalindromicString ( ) ; strcpy ( text , " abacdfgdcabba " ) ; findLongestPalindromicString ( ) ; strcpy ( text , " abacdedcaba " ) ; findLongestPalindromicString ( ) ; return 0 ; }
Print all possible strings that can be made by placing spaces | C ++ program to print permutations of a given string with spaces . ; Function recursively prints the strings having space pattern . i and j are indices in ' str [ ] ' and ' buff [ ] ' respectively ; Either put the character ; Or put a space followed by next character ; This function creates buf [ ] to store individual output string and uses printPatternUtil ( ) to print all permutations . ; Buffer to hold the string containing spaces 2 n - 1 characters and 1 string terminator ; Copy the first character as it is , since it will be always at first position ; Driver program to test above functions
#include <cstring> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void printPatternUtil ( const char str [ ] , char buff [ ] , int i , int j , int n ) { if ( i == n ) { buff [ j ] = ' \0' ; cout << buff << endl ; return ; } buff [ j ] = str [ i ] ; printPatternUtil ( str , buff , i + 1 , j + 1 , n ) ; buff [ j ] = ' ▁ ' ; buff [ j + 1 ] = str [ i ] ; printPatternUtil ( str , buff , i + 1 , j + 2 , n ) ; } void printPattern ( const char * str ) { int n = strlen ( str ) ; char buf [ 2 * n ] ; buf [ 0 ] = str [ 0 ] ; printPatternUtil ( str , buf , 1 , 1 , n ) ; } int main ( ) { const char * str = " ABCD " ; printPattern ( str ) ; return 0 ; }
Subset Sum | Backtracking |  ; Prints subset found ; inputs s - set vector t - tuplet vector s_size - set size t_size - tuplet size so far sum - sum so far ite - nodes count target_sum - sum to be found ; We found subset ; Exclude previously added item and consider next candidate ; Generate nodes along the breadth ; Consider next level node ( along depth ) ; Wrapper to print subsets that sum to target_sum input is weights vector and target_sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ARRAYSIZE ( a )  (sizeof(a)) / (sizeof(a[0])) NEW_LINE #define mx  200 NEW_LINE static int total_nodes ; void printSubset ( int A [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) { cout << A [ i ] << " ▁ " ; } cout << " STRNEWLINE ▁ " ; } void subset_sum ( int s [ ] , int t [ ] , int s_size , int t_size , int sum , int ite , int const target_sum ) { total_nodes ++ ; if ( target_sum == sum ) { printSubset ( t , t_size ) ; subset_sum ( s , t , s_size , t_size - 1 , sum - s [ ite ] , ite + 1 , target_sum ) ; return ; } else { for ( int i = ite ; i < s_size ; i ++ ) { t [ t_size ] = s [ i ] ; subset_sum ( s , t , s_size , t_size + 1 , sum + s [ i ] , i + 1 , target_sum ) ; } } } void generateSubsets ( int s [ ] , int size , int target_sum ) { int * tuplet_vector = new int [ mx ] ; subset_sum ( s , tuplet_vector , size , 0 , 0 , 0 , target_sum ) ; free ( tuplet_vector ) ; } int main ( ) { int weights [ ] = { 10 , 7 , 5 , 18 , 12 , 20 , 15 } ; int size = ARRAYSIZE ( weights ) ; generateSubsets ( weights , size , 35 ) ; cout << " Nodes ▁ generated ▁ " << total_nodes << " STRNEWLINE " ; return 0 ; }
Sudoku | Backtracking |  ; N is the size of the 2D matrix N * N ; A utility function to print grid ; Checks whether it will be legal to assign num to the given row , col ; Check if we find the same num in the similar row , we return false ; Check if we find the same num in the similar column , we return false ; Check if we find the same num in the particular 3 * 3 matrix , we return false ; Takes a partially filled - in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution ( non - duplication across rows , columns , and boxes ) ; Check if we have reached the 8 th row and 9 th column ( 0 indexed matrix ) , we are returning true to avoid further backtracking ; Check if column value becomes 9 , we move to next row and column start from 0 ; Check if the current position of the grid already contains value > 0 , we iterate for next column ; Check if it is safe to place the num ( 1 - 9 ) in the given row , col -> we move to next column ; Assigning the num in the current ( row , col ) position of the grid and assuming our assined num in the position is correct ; Checking for next possibility with next column ; Removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value ; Driver Code
#include <iostream> NEW_LINE using namespace std ; #define N  9 NEW_LINE void print ( int arr [ N ] [ N ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) cout << arr [ i ] [ j ] << " ▁ " ; cout << endl ; } } bool isSafe ( int grid [ N ] [ N ] , int row , int col , int num ) { for ( int x = 0 ; x <= 8 ; x ++ ) if ( grid [ row ] [ x ] == num ) return false ; for ( int x = 0 ; x <= 8 ; x ++ ) if ( grid [ x ] [ col ] == num ) return false ; int startRow = row - row % 3 , startCol = col - col % 3 ; for ( int i = 0 ; i < 3 ; i ++ ) for ( int j = 0 ; j < 3 ; j ++ ) if ( grid [ i + startRow ] [ j + startCol ] == num ) return false ; return true ; } bool solveSuduko ( int grid [ N ] [ N ] , int row , int col ) { if ( row == N - 1 && col == N ) return true ; if ( col == N ) { row ++ ; col = 0 ; } if ( grid [ row ] [ col ] > 0 ) return solveSuduko ( grid , row , col + 1 ) ; for ( int num = 1 ; num <= N ; num ++ ) { if ( isSafe ( grid , row , col , num ) ) { grid [ row ] [ col ] = num ; if ( solveSuduko ( grid , row , col + 1 ) ) return true ; } grid [ row ] [ col ] = 0 ; } return false ; } int main ( ) { int grid [ N ] [ N ] = { { 3 , 0 , 6 , 5 , 0 , 8 , 4 , 0 , 0 } , { 5 , 2 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 8 , 7 , 0 , 0 , 0 , 0 , 3 , 1 } , { 0 , 0 , 3 , 0 , 1 , 0 , 0 , 8 , 0 } , { 9 , 0 , 0 , 8 , 6 , 3 , 0 , 0 , 5 } , { 0 , 5 , 0 , 0 , 9 , 0 , 6 , 0 , 0 } , { 1 , 3 , 0 , 0 , 0 , 0 , 2 , 5 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 7 , 4 } , { 0 , 0 , 5 , 2 , 0 , 6 , 3 , 0 , 0 } } ; if ( solveSuduko ( grid , 0 , 0 ) ) print ( grid ) ; else cout << " no ▁ solution ▁ exists ▁ " << endl ; return 0 ; }
Median of two sorted arrays of same size | A Simple Merge based O ( n ) solution to find median of two sorted arrays ; This function returns median of ar1 [ ] and ar2 [ ] . Assumptions in this function : Both ar1 [ ] and ar2 [ ] are sorted arrays Both have n elements ; Since there are 2 n elements , median will be average of elements at index n - 1 and n in the array obtained after merging ar1 and ar2 ; Below is to handle case where all elements of ar1 [ ] are smaller than smallest ( or first ) element of ar2 [ ] ; Below is to handle case where all elements of ar2 [ ] are smaller than smallest ( or first ) element of ar1 [ ] ; equals sign because if two arrays have some common elements ; Store the prev median ; Store the prev median ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMedian ( int ar1 [ ] , int ar2 [ ] , int n ) { int i = 0 ; int j = 0 ; int count ; int m1 = -1 , m2 = -1 ; for ( count = 0 ; count <= n ; count ++ ) { if ( i == n ) { m1 = m2 ; m2 = ar2 [ 0 ] ; break ; } else if ( j == n ) { m1 = m2 ; m2 = ar1 [ 0 ] ; break ; } if ( ar1 [ i ] <= ar2 [ j ] ) { m1 = m2 ; m2 = ar1 [ i ] ; i ++ ; } else { m1 = m2 ; m2 = ar2 [ j ] ; j ++ ; } } return ( m1 + m2 ) / 2 ; } int main ( ) { int ar1 [ ] = { 1 , 12 , 15 , 26 , 38 } ; int ar2 [ ] = { 2 , 13 , 17 , 30 , 45 } ; int n1 = sizeof ( ar1 ) / sizeof ( ar1 [ 0 ] ) ; int n2 = sizeof ( ar2 ) / sizeof ( ar2 [ 0 ] ) ; if ( n1 == n2 ) cout << " Median ▁ is ▁ " << getMedian ( ar1 , ar2 , n1 ) ; else cout << " Doesn ' t ▁ work ▁ for ▁ arrays " << " ▁ of ▁ unequal ▁ size " ; getchar ( ) ; return 0 ; }
Median of two sorted arrays of same size | A divide and conquer based efficient solution to find median of two sorted arrays of same size . ; to get median of a sorted array ; This function returns median of ar1 [ ] and ar2 [ ] . Assumptions in this function : Both ar1 [ ] and ar2 [ ] are sorted arrays Both have n elements ; get the median of the first array ; get the median of the second array ; If medians are equal then return either m1 or m2 ; if m1 < m2 then median must exist in ar1 [ m1 ... . ] and ar2 [ ... . m2 ] ; if m1 > m2 then median must exist in ar1 [ ... . m1 ] and ar2 [ m2 ... ] ; Function to get median of a sorted array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int median ( int [ ] , int ) ; int getMedian ( int ar1 [ ] , int ar2 [ ] , int n ) { if ( n <= 0 ) return -1 ; if ( n == 1 ) return ( ar1 [ 0 ] + ar2 [ 0 ] ) / 2 ; if ( n == 2 ) return ( max ( ar1 [ 0 ] , ar2 [ 0 ] ) + min ( ar1 [ 1 ] , ar2 [ 1 ] ) ) / 2 ; int m1 = median ( ar1 , n ) ; int m2 = median ( ar2 , n ) ; if ( m1 == m2 ) return m1 ; if ( m1 < m2 ) { if ( n % 2 == 0 ) return getMedian ( ar1 + n / 2 - 1 , ar2 , n - n / 2 + 1 ) ; return getMedian ( ar1 + n / 2 , ar2 , n - n / 2 ) ; } if ( n % 2 == 0 ) return getMedian ( ar2 + n / 2 - 1 , ar1 , n - n / 2 + 1 ) ; return getMedian ( ar2 + n / 2 , ar1 , n - n / 2 ) ; } int median ( int arr [ ] , int n ) { if ( n % 2 == 0 ) return ( arr [ n / 2 ] + arr [ n / 2 - 1 ] ) / 2 ; else return arr [ n / 2 ] ; } int main ( ) { int ar1 [ ] = { 1 , 2 , 3 , 6 } ; int ar2 [ ] = { 4 , 6 , 8 , 10 } ; int n1 = sizeof ( ar1 ) / sizeof ( ar1 [ 0 ] ) ; int n2 = sizeof ( ar2 ) / sizeof ( ar2 [ 0 ] ) ; if ( n1 == n2 ) cout << " Median ▁ is ▁ " << getMedian ( ar1 , ar2 , n1 ) ; else cout << " Doesn ' t ▁ work ▁ for ▁ arrays ▁ " << " of ▁ unequal ▁ size " ; return 0 ; }
Median of two sorted arrays of same size | CPP program for the above approach ; This function returns median of ar1 [ ] and ar2 [ ] . Assumptions in this function : Both ar1 [ ] and ar2 [ ] are sorted arrays Both have n elements ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMedian ( int ar1 [ ] , int ar2 [ ] , int n ) { int j = 0 ; int i = n - 1 ; while ( ar1 [ i ] > ar2 [ j ] && j < n && i > - 1 ) swap ( ar1 [ i -- ] , ar2 [ j ++ ] ) ; sort ( ar1 , ar1 + n ) ; sort ( ar2 , ar2 + n ) ; return ( ar1 [ n - 1 ] + ar2 [ 0 ] ) / 2 ; } int main ( ) { int ar1 [ ] = { 1 , 12 , 15 , 26 , 38 } ; int ar2 [ ] = { 2 , 13 , 17 , 30 , 45 } ; int n1 = sizeof ( ar1 ) / sizeof ( ar1 [ 0 ] ) ; int n2 = sizeof ( ar2 ) / sizeof ( ar2 [ 0 ] ) ; if ( n1 == n2 ) cout << " Median ▁ is ▁ " << getMedian ( ar1 , ar2 , n1 ) ; else cout << " Doesn ' t ▁ work ▁ for ▁ arrays " << " ▁ of ▁ unequal ▁ size " ; getchar ( ) ; return 0 ; }