codeparrot/xlcost-text-to-code huggingface dataset:
Rabin | 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
let d = 256 ; function search ( pat , txt , q ) { let M = pat . length ; let N = txt . length ; let i , j ; let p = 0 ; let t = 0 ; let h = 1 ; for ( i = 0 ; i < M - 1 ; i ++ ) h = ( h * d ) % q ; for ( i = 0 ; i < M ; i ++ ) { p = ( d * p + pat [ i ] . charCodeAt ( ) ) % q ; t = ( d * t + txt [ i ] . charCodeAt ( ) ) % 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 ) document . write ( " " + i + " " ) ; } if ( i < N - M ) { t = ( d * ( t - txt [ i ] . charCodeAt ( ) * h ) + txt [ i + M ] . charCodeAt ( ) ) % q ; if ( t < 0 ) t = ( t + q ) ; } } } let txt = " " ; let pat = " " ; let q = 101 ; search ( pat , txt , q ) ;
Optimized Naive Algorithm for Pattern Searching | Javascript 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
function search ( pat , txt ) { let M = pat . length ; let N = txt . length ; let i = 0 ; while ( i <= N - M ) { let j ; for ( j = 0 ; j < M ; j ++ ) if ( txt [ i + j ] != pat [ j ] ) break ; if ( j == M ) { document . write ( " " + i + " " ) ; i = i + M ; } else if ( j == 0 ) i = i + 1 ; else i = i + j ; } } let txt = " " ; let pat = " " ; search ( pat , txt ) ;
Median of two sorted arrays of same size | 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 program to test above function
function getMedian ( ar1 , ar2 , n ) { var i = 0 ; var j = 0 ; var count ; var 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 ; } var ar1 = [ 1 , 12 , 15 , 26 , 38 ] ; var ar2 = [ 2 , 13 , 17 , 30 , 45 ] ; var n1 = ar1 . length ; var n2 = ar2 . length ; if ( n1 == n2 ) document . write ( " " + getMedian ( ar1 , ar2 , n1 ) ) ; else document . write ( " " ) ;
Check whether a given point lies inside a triangle or not | A utility function to calculate area of triangle formed by ( x1 , y1 ) , ( x2 , y2 ) and ( x3 , y3 ) ; A function to check whether point P ( x , y ) lies inside the triangle formed by A ( x1 , y1 ) , B ( x2 , y2 ) and C ( x3 , y3 ) ; Calculate area of triangle ABC ; Calculate area of triangle PBC ; Calculate area of triangle PAC ; Calculate area of triangle PAB ; Check if sum of A1 , A2 and A3 is same as A ; Let us check whether the point P ( 10 , 15 ) lies inside the triangle formed by A ( 0 , 0 ) , B ( 20 , 0 ) and C ( 10 , 30 )
function area ( x1 , y1 , x2 , y2 , x3 , y3 ) { return Math . abs ( ( x1 * ( y2 - y3 ) + x2 * ( y3 - y1 ) + x3 * ( y1 - y2 ) ) / 2.0 ) ; } function isInside ( x1 , y1 , x2 , y2 , x3 , y3 , x , y ) { let A = area ( x1 , y1 , x2 , y2 , x3 , y3 ) ; let A1 = area ( x , y , x2 , y2 , x3 , y3 ) ; let A2 = area ( x1 , y1 , x , y , x3 , y3 ) ; let A3 = area ( x1 , y1 , x2 , y2 , x , y ) ; return ( A == A1 + A2 + A3 ) ; } if ( isInside ( 0 , 0 , 20 , 0 , 10 , 30 , 10 , 15 ) ) document . write ( " " ) ; else document . write ( " " ) ;
Lucky Numbers | Returns 1 if n is a lucky no . otherwise returns 0 ; variable next_position is just for readability of the program we can remove it and use n only ; calculate next position of input no ; Driver Code
function isLucky ( n ) { let counter = 2 ; let next_position = n ; if ( counter > n ) return 1 ; if ( n % counter == 0 ) return 0 ; next_position -= Math . floor ( next_position / counter ) ; counter ++ ; return isLucky ( next_position ) ; } let x = 5 ; if ( isLucky ( x ) ) document . write ( x + " " ) ; else document . write ( x + " " ) ;
Write you own Power without using multiplication ( * ) and division ( / ) operators | Works only if a >= 0 and b >= 0 ; driver program to test above function
function pow ( a , b ) { if ( b == 0 ) return 1 ; var answer = a ; var increment = a ; var i , j ; for ( i = 1 ; i < b ; i ++ ) { for ( j = 1 ; j < a ; j ++ ) { answer += increment ; } increment = answer ; } return answer ; } document . write ( pow ( 5 , 3 ) ) ;
Write you own Power without using multiplication ( * ) and division ( / ) operators | A recursive function to get x * y ; A recursive function to get a ^ b Works only if a >= 0 and b >= 0 ; Driver code
function multiply ( x , y ) { if ( y > 0 ) return ( x + multiply ( x , y - 1 ) ) ; else return 0 ; } function pow ( a , b ) { if ( b > 0 ) return multiply ( a , pow ( a , b - 1 ) ) ; else return 1 ; } document . write ( pow ( 5 , 3 ) ) ;
Count numbers that don 't contain 3 | Function that returns count of numbers which are in range from 1 to n and not contain 3 as a digit ; Base cases ( Assuming n is not negative ) ; Calculate 10 ^ ( d - 1 ) ( 10 raise to the power d - 1 ) where d is number of digits in n . po will be 100 for n = 578 ; find the most significant digit ( msd is 5 for 578 ) ; For 578 , total will be 4 * count ( 10 ^ 2 - 1 ) + 4 + count ( 78 ) ; For 35 , total will be equal to count ( 29 ) ; Driver program
function count ( n ) { if ( n < 3 ) return n ; if ( n >= 3 && n < 10 ) return n - 1 ; var po = 1 ; while ( parseInt ( n / po ) > 9 ) po = po * 10 ; var msd = parseInt ( n / po ) ; if ( msd != 3 ) return count ( msd ) * count ( po - 1 ) + count ( msd ) + count ( n % po ) ; else return count ( msd * po - 1 ) ; } var n = 578 ; document . write ( count ( n ) ) ;
Number which has the maximum number of distinct prime factors in the range M to N | Function to return the maximum number ; Array to store the number of distinct primes ; True if index ' i ' is a prime ; Initializing the number of factors to 0 and ; Used in Sieve ; Condition works only when ' i ' is prime , hence for factors of all prime number , the prime status is changed to false ; Number is prime ; Number of factor of a prime number is 1 ; Incrementing factorCount all the factors of i ; And changing prime status to false ; Initialize the max and num ; Gets the maximum number ; Gets the maximum number ; Driver code ; Calling function
function maximumNumberDistinctPrimeRange ( m , n ) { let factorCount = new Array ( n + 1 ) ; let prime = new Array ( n + 1 ) ; for ( let i = 0 ; i <= n ; i ++ ) { factorCount [ i ] = 0 ; prime [ i ] = true ; } for ( let i = 2 ; i <= n ; i ++ ) { if ( prime [ i ] == true ) { factorCount [ i ] = 1 ; for ( let j = i * 2 ; j <= n ; j += i ) { factorCount [ j ] ++ ; prime [ j ] = false ; } } } let max = factorCount [ m ] ; let num = m ; for ( let i = m ; i <= n ; i ++ ) { if ( factorCount [ i ] > max ) { max = factorCount [ i ] ; num = i ; } } return num ; } let m = 4 , n = 6 ; document . write ( maximumNumberDistinctPrimeRange ( m , n ) ) ;
Lexicographic rank of a string | A utility function to find factorial of n ; A utility function to count smaller characters on right of arr [ low ] ; A function to find rank of a string in all permutations of characters ; count number of chars smaller than str [ i ] from str [ i + 1 ] to str [ len - 1 ] ; Driver code
function fact ( n ) { return ( n <= 1 ) ? 1 : n * fact ( n - 1 ) ; } function findSmallerInRight ( str , low , high ) { let countRight = 0 ; let i ; for ( i = low + 1 ; i <= high ; ++ i ) if ( str [ i ] < str [ low ] ) ++ countRight ; return countRight ; } function findRank ( str ) { let len = ( str ) . length ; let mul = fact ( len ) ; let rank = 1 ; let countRight ; let i ; for ( i = 0 ; i < len ; ++ i ) { mul /= len - i ; countRight = findSmallerInRight ( str , i , len - 1 ) ; rank += countRight * mul ; } return rank ; } let str = " " ; document . write ( findRank ( str ) ) ;
Efficient program to calculate e ^ x | Function returns approximate value of e ^ x using sum of first n terms of Taylor Series ; initialize sum of series ; driver program
function exponential ( n , x ) { var sum = 1 ; for ( i = n - 1 ; i > 0 ; -- i ) sum = 1 + x * sum / i ; return sum ; } var n = 10 ; var x = 1 ; document . write ( " " + exponential ( n , x ) . toFixed ( 6 ) ) ;
Random number generator in arbitrary probability distribution fashion | Utility function to find ceiling of r in arr [ l . . h ] ; Same as mid = ( l + h ) / 2 ; The main function that returns a random number from arr [ ] according to distribution array defined by freq [ ] . n is size of arrays . ; Create and fill prefix array ; prefix [ n - 1 ] is sum of all frequencies . Generate a random number with value from 1 to this sum ; Find index of ceiling of r in prefix array ; Driver code ; Let us generate 10 random numbers accroding to given distribution
function findCeil ( arr , r , l , h ) { let mid ; while ( l < h ) { mid = l + ( ( h - l ) >> 1 ) ; ( r > arr [ mid ] ) ? ( l = mid + 1 ) : ( h = mid ) ; } return ( arr [ l ] >= r ) ? l : - 1 ; } function myRand ( arr , freq , n ) { let prefix = [ ] ; let i ; prefix [ 0 ] = freq [ 0 ] ; for ( i = 1 ; i < n ; ++ i ) prefix [ i ] = prefix [ i - 1 ] + freq [ i ] ; let r = Math . floor ( ( Math . random ( ) * prefix [ n - 1 ] ) ) + 1 ; let indexc = findCeil ( prefix , r , 0 , n - 1 ) ; return arr [ indexc ] ; } let arr = [ 1 , 2 , 3 , 4 ] ; let freq = [ 10 , 5 , 20 , 100 ] ; let i ; let n = arr . length ; for ( i = 0 ; i < 5 ; i ++ ) document . write ( myRand ( arr , freq , n ) ) ;
How to check if a given number is Fibonacci number ? | A utility function that returns true if x is perfect square ; Returns true if n is a Fibinacci Number , else false ; n is Fibinacci if one of 5 * n * n + 4 or 5 * n * n - 4 or both is a perferct square ; A utility function to test above functions
function isPerfectSquare ( x ) { let s = parseInt ( Math . sqrt ( x ) ) ; return ( s * s == x ) ; } function isFibonacci ( n ) { return isPerfectSquare ( 5 * n * n + 4 ) || isPerfectSquare ( 5 * n * n - 4 ) ; } for ( let i = 1 ; i <= 10 ; i ++ ) isFibonacci ( i ) ? document . write ( i + " " ) : document . write ( i + " " ) ;
Count trailing zeroes in factorial of a number | Function to return trailing 0 s in factorial of n ; Initialize result ; Keep dividing n by powers of 5 and update count ; Driver Code
function findTrailingZeros ( n ) { let count = 0 ; for ( let i = 5 ; Math . floor ( n / i ) >= 1 ; i *= 5 ) count += Math . floor ( n / i ) ; return count ; } let n = 100 ; document . write ( " " + 100 + " " + findTrailingZeros ( n ) ) ;
Program for nth Catalan Number | A recursive function to find nth catalan number ; Base case ; catalan ( n ) is sum of catalan ( i ) * catalan ( n - i - 1 ) ; Driver Code
function catalan ( n ) { if ( n <= 1 ) return 1 ; let res = 0 ; for ( let i = 0 ; i < n ; i ++ ) res += catalan ( i ) * catalan ( n - i - 1 ) ; return res ; } for ( let i = 0 ; i < 10 ; i ++ ) document . write ( catalan ( i ) + " " ) ;
Program for nth Catalan Number | Javscript program for nth Catalan Number A dynamic programming based function to find nth Catalan number ; Table to store results of subproblems ; Initialize first two values in table ; Fill entries in catalan [ ] using recursive formula ; Return last entry ; Driver Code
function catalanDP ( n ) { let catalan = [ ] ; catalan [ 0 ] = catalan [ 1 ] = 1 ; for ( let i = 2 ; i <= n ; i ++ ) { catalan [ i ] = 0 ; for ( let j = 0 ; j < i ; j ++ ) catalan [ i ] += catalan [ j ] * catalan [ i - j - 1 ] ; } return catalan [ n ] ; } for ( let i = 0 ; i < 10 ; i ++ ) document . write ( catalanDP ( i ) + " " ) ;
Program for nth Catalan Number | Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; A Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; return 2 nCn / ( n + 1 ) ; Driver code
function binomialCoeff ( n , k ) { let res = 1 ; if ( k > n - k ) k = n - k ; for ( let i = 0 ; i < k ; ++ i ) { res *= ( n - i ) ; res = Math . floor ( res / ( i + 1 ) ) ; } return res ; } function catalan ( n ) { c = binomialCoeff ( 2 * ( n ) , n ) ; return Math . floor ( c / ( n + 1 ) ) ; } for ( let i = 0 ; i < 10 ; i ++ ) document . write ( catalan ( i ) + " " ) ;
Program for nth Catalan Number | Function to print the number ; For the first number C ( 0 ) ; Iterate till N ; Calculate the number and print it ; Driver code ; Function call
function catalan ( n ) { let cat_ = 1 ; document . write ( cat_ + " " ) ; for ( let i = 1 ; i < n ; i ++ ) { cat_ *= ( 4 * i - 2 ) ; cat_ /= ( i + 1 ) ; document . write ( cat_ + " " ) ; } } let n = 5 ; catalan ( n ) ;
Find Excel column name from a given column number |  ; Step 1 : Converting to number assuming 0 in number system ; Step 2 : Getting rid of 0 , as 0 is not part of number system ; Driver program to test above function
function printString ( n ) { let arr = [ ] ; let i = 0 ; while ( n ) { arr [ i ] = n % 26 ; n = Math . floor ( n / 26 ) ; i ++ ; } for ( let j = 0 ; j < i - 1 ; j ++ ) { if ( arr [ j ] <= 0 ) { arr [ j ] += 26 ; arr [ j + 1 ] = arr [ j + 1 ] - 1 ; } } let ans = ' ' ; for ( let j = i ; j >= 0 ; j -- ) { if ( arr [ j ] > 0 ) ans += String . fromCharCode ( 65 + arr [ j ] - 1 ) ; } document . write ( ans + " " ) ; } printString ( 26 ) ; printString ( 51 ) ; printString ( 52 ) ; printString ( 80 ) ; printString ( 676 ) ; printString ( 702 ) ; printString ( 705 ) ;
Calculate the angle between hour hand and minute hand | Utility function to find minimum of two integers ; Function to calculate the angle ; validate the input ; Calculate the angles moved by hour and minute hands with reference to 12 : 00 ; Find the difference between two angles ; Return the smaller angle of two possible angles ; Driver Code
function min ( x , y ) { return ( x < y ) ? x : y ; } function calcAngle ( h , m ) { if ( h < 0 m < 0 h > 12 m > 60 ) document . write ( " " ) ; if ( h == 12 ) h = 0 ; if ( m == 60 ) { m = 0 ; h += 1 ; if ( h > 12 ) h = h - 12 ; } let hour_angle = 0.5 * ( h * 60 + m ) ; let minute_angle = 6 * m ; let angle = Math . abs ( hour_angle - minute_angle ) ; angle = min ( 360 - angle , angle ) ; return angle ; } document . write ( calcAngle ( 9 , 60 ) + " " ) ; document . write ( calcAngle ( 3 , 30 ) + " " ) ;
How to check if an instance of 8 puzzle is solvable ? | A utility function to count inversions in given array ' arr [ ] ' ; Value 0 is used for empty space ; This function returns true if given 8 puzzle is solvable . ; Count inversions in given 8 puzzle ; return true if inversion count is even . ; Driver code
function getInvCount ( arr ) { let inv_count = 0 ; for ( let i = 0 ; i < 2 ; i ++ ) { for ( let j = i + 1 ; j < 3 ; j ++ ) { if ( arr [ j ] [ i ] > 0 && arr [ j ] [ i ] > arr [ i ] [ j ] ) inv_count += 1 ; } } return inv_count ; } function isSolvable ( puzzle ) { let invCount = getInvCount ( puzzle ) ; return ( invCount % 2 == 0 ) ; } puzzle = [ [ 1 , 8 , 2 ] , [ 0 , 4 , 3 ] , [ 7 , 6 , 5 ] ] ; if ( isSolvable ( puzzle ) ) document . write ( " " ) ; else document . write ( " " ) ;
Birthday Paradox | Returns approximate number of people for a given probability ; Driver code
function find ( p ) { return Math . ceil ( Math . sqrt ( 2 * 365 * Math . log ( 1 / ( 1 - p ) ) ) ) ; } document . write ( find ( 0.70 ) ) ;
Count Distinct Non | This function counts number of pairs ( x , y ) that satisfy the inequality x * x + y * y < n . ; Driver program to test above function
function countSolutions ( n ) { let res = 0 ; for ( let x = 0 ; x * x < n ; x ++ ) { for ( let y = 0 ; x * x + y * y < n ; y ++ ) { res ++ ; } } return res ; } document . write ( " " + countSolutions ( 6 ) ) ;
Count Distinct Non | This function counts number of pairs ( x , y ) that satisfy the inequality x * x + y * y < n . ; Find the count of different y values for x = 0. ; One by one increase value of x , and find yCount forcurrent x . If yCount becomes 0 , then we have reached maximum possible value of x . ; Add yCount ( count of different possible values of y for current x ) to result ; Increment x ; Update yCount for current x . Keep reducing yCount while the inequality is not satisfied . ; Driver program
function countSolutions ( n ) { let x = 0 , yCount , res = 0 ; for ( yCount = 0 ; yCount * yCount < n ; yCount ++ ) ; while ( yCount != 0 ) { res += yCount ; x ++ ; while ( yCount != 0 && ( x * x + ( yCount - 1 ) * ( yCount - 1 ) >= n ) ) yCount -- ; } return res ; } document . write ( " " + " " + countSolutions ( 6 ) ) ;
Program for Method Of False Position | JavaScript program for implementation of Bisection Method for solving equations ; An example function whose solution is determined using Bisection Method . The function is x ^ 3 - x ^ 2 + 2 ; Prints root of func ( x ) in interval [ a , b ] ; Initialize result ; Find the point that touches x axis ; Check if the above found point is root ; Decide the side to repeat the steps ; Initial values assumed
let MAX_ITER = 1000000 function func ( x ) { return x * x * x - x * x + 2 ; } function regulaFalsi ( a , b ) { if ( func ( a ) * func ( b ) >= 0 ) { document . write ( " " ) ; return ; } let c = a ; for ( let i = 0 ; i < MAX_ITER ; i ++ ) { c = Math . floor ( ( a * func ( b ) - b * func ( a ) ) / ( func ( b ) - func ( a ) ) ) ; if ( func ( c ) == 0 ) { break ; } else if ( func ( c ) * func ( a ) < 0 ) { b = c ; } else { a = c ; } } document . write ( " " + c ) ; } let a = - 200 ; let b = 300 ; regulaFalsi ( a , b ) ;
Program for Newton Raphson Method | JavaScript program for implementation of Newton Raphson Method for solving equations ; An example function whose solution is determined using Bisection Method . The function is x ^ 3 - x ^ 2 + 2 ; Derivative of the above function which is 3 * x ^ x - 2 * x ; Function to find the root ; x ( i + 1 ) = x ( i ) - f ( x ) / f '(x) ; Initial values assumed
let EPSILON = 0.001 ; function func ( x ) { return x * x * x - x * x + 2 ; } function derivFunc ( x ) { return 3 * x * x - 2 * x ; } function newtonRaphson ( x ) { let h = func ( x ) / derivFunc ( x ) ; while ( Math . abs ( h ) >= EPSILON ) { h = func ( x ) / derivFunc ( x ) ; x = x - h ; } document . write ( " " + " " + Math . round ( x * 100.0 ) / 100.0 ) ; } let x0 = - 20 ; newtonRaphson ( x0 ) ;
Find the element that appears once | Method to find the element that occur only once ; " one ▁ & ▁ arr [ i ] " gives the bits that are there in both ' ones ' and new element from arr [ ] . We add these bits to ' twos ' using bitwise OR ; " one ▁ & ▁ arr [ i ] " gives the bits that are there in both ' ones ' and new element from arr [ ] . We add these bits to ' twos ' using bitwise OR ; The common bits are those bits which appear third time So these bits should not be there in both ' ones ' and ' twos ' . common_bit_mask contains all these bits as 0 , so that the bits can be removed from ' ones ' and ' twos ' ; Remove common bits ( the bits that appear third time ) from ' ones ' ; Remove common bits ( the bits that appear third time ) from ' twos ' ; Driver Code
function getSingle ( arr , n ) { let ones = 0 , twos = 0 ; let common_bit_mask ; for ( let i = 0 ; i < n ; i ++ ) { twos = twos | ( ones & arr [ i ] ) ; ones = ones ^ arr [ i ] ; common_bit_mask = ~ ( ones & twos ) ; ones &= common_bit_mask ; twos &= common_bit_mask ; } return ones ; } let arr = [ 3 , 3 , 2 , 3 ] ; let n = arr . length ; document . write ( " " + getSingle ( arr , n ) ) ;
Find the element that appears once | Javascript program to find the element that occur only once ; Initialize result ; Iterate through every bit ; Find sum of set bits at ith position in all array elements ; The bits with sum not multiple of 3 , are the bits of element with single occurrence . ; Driver code
let INT_SIZE = 32 ; function getSingle ( arr , n ) { let result = 0 ; let x , sum ; for ( let i = 0 ; i < INT_SIZE ; i ++ ) { sum = 0 ; x = ( 1 << i ) ; for ( let j = 0 ; j < n ; j ++ ) { if ( arr [ j ] & x ) sum ++ ; } if ( ( sum % 3 ) != 0 ) result |= x ; } return result ; } let arr = [ 12 , 1 , 12 , 3 , 12 , 1 , 1 , 2 , 3 , 2 , 2 , 3 , 7 ] ; let n = arr . length ; document . write ( " " + getSingle ( arr , n ) ) ;
Detect if two integers have opposite signs | Function to detect signs ; Driver Code
function oppositeSigns ( x , y ) { return ( ( x ^ y ) < 0 ) ; } let x = 100 , y = - 100 ; if ( oppositeSigns ( x , y ) == true ) document . write ( " " ) ; else document . write ( " " ) ;
Count total set bits in all numbers from 1 to n | Returns count of set bits present in all numbers from 1 to n ; initialize the result ; A utility function to count set bits in a number x ; Driver program
function countSetBits ( n ) { let bitCount = 0 ; for ( let i = 1 ; i <= n ; i ++ ) { bitCount += countSetBitsUtil ( i ) ; } return bitCount ; } function countSetBitsUtil ( x ) { if ( x <= 0 ) { return 0 ; } return ( x % 2 == 0 ? 0 : 1 ) + countSetBitsUtil ( Math . floor ( x / 2 ) ) ; } let n = 4 ; document . write ( " " ) ; document . write ( countSetBits ( n ) ) ;
Count total set bits in all numbers from 1 to n | Javascript program for the above approach Function which counts set bits from 0 to n ; ans store sum of set bits from 0 to n ; while n greater than equal to 2 ^ i ; This k will get flipped after 2 ^ i iterations ; change is iterator from 2 ^ i to 1 ; This will loop from 0 to n for every bit position ; When change = 1 flip the bit ; again set change to 2 ^ i ; increment the position ; Driver Code
function countSetBits ( n ) { let i = 0 ; let ans = 0 ; while ( ( 1 << i ) <= n ) { let k = 0 ; let change = 1 << i ; for ( let j = 0 ; j <= n ; j ++ ) { ans += k ; if ( change == 1 ) { k = ! k ; change = 1 << i ; } else { change -- ; } } i ++ ; } return ans ; } let n = 17 ; document . write ( countSetBits ( n ) ) ;
Count total set bits in all numbers from 1 to n |
function getSetBitsFromOneToN ( N ) { var two = 2 var ans = 0 var n = N while ( n != 0 ) { ans += Math . floor ( N / two ) * ( two >> 1 ) if ( ( N & ( two - 1 ) ) > ( two >> 1 ) - 1 ) ans += ( N & ( two - 1 ) ) - ( two >> 1 ) + 1 two <<= 1 ; n >>= 1 ; } return ans }
Swap bits in a given number | Javascript Program to swap bits in a given number ; Move all bits of first set to rightmost side ; Move all bits of second set to rightmost side ; XOR the two sets ; Put the xor bits back to their original positions ; XOR the ' xor ' with the original number so that the two sets are swapped ; Driver Code
function swapBits ( x , p1 , p2 , n ) { let set1 = ( x >> p1 ) & ( ( 1 << n ) - 1 ) ; let set2 = ( x >> p2 ) & ( ( 1 << n ) - 1 ) ; let xor = ( set1 ^ set2 ) ; xor = ( xor << p1 ) | ( xor << p2 ) ; let result = x ^ xor ; return result ; } let res = swapBits ( 28 , 0 , 3 , 2 ) ; document . write ( " " + res ) ;