Today we cover a few more exercises:
Detect the Y-intersection of two lists that may be of different lengths:
Solution : find the length of the first list
find the length of the second list
traverse the longer list by the number of nodes equal to the different in the two lengths above.
Then traverse both the lists one node at a time to detect when the next node is the same for both lists.
Shuffle a deck of cards:
Knuth Shuffling :
split the cards into 1 to I and I+1 to n-1.
pick a card from 1 to I randomly and uniformly (I times)
replace with random number card between I+1 to n-1
Continuous subsequence divisible by a number:
The number of prefixes divisible by the given divisor say 5 for a sequence say 1,1,3,2,4,1,4,5
We apply the principle that if there is a continuous subsequence divisible by the divisor, then it is composed of pre-fixes (leading fragments) that give the same remainder and vice versa. Let us group the pre-fixes of a given sequence by the remainders from modulo 5 of the sum of their elements If there are k sub-sequences for some remainder, then the number of continuous subsequences with the sum of elements divisible by divisor is K choose 2 = k(k-1)/2
Check if two strings s1 and s2 are rotated
Return (s1+s1).indexOf(s2)
#codingexercise
Double GetNthRootProductEachTermRaisedPTimesQoverPDividedQ (Double [] A,Double p, Double q)
{
If ( A== null) return 0;
Return A.NthRootProductEachTermRaisedPTimesQoverPDividedQ(p, q);
}
Detect the Y-intersection of two lists that may be of different lengths:
Solution : find the length of the first list
find the length of the second list
traverse the longer list by the number of nodes equal to the different in the two lengths above.
Then traverse both the lists one node at a time to detect when the next node is the same for both lists.
Shuffle a deck of cards:
Knuth Shuffling :
split the cards into 1 to I and I+1 to n-1.
pick a card from 1 to I randomly and uniformly (I times)
replace with random number card between I+1 to n-1
Continuous subsequence divisible by a number:
The number of prefixes divisible by the given divisor say 5 for a sequence say 1,1,3,2,4,1,4,5
We apply the principle that if there is a continuous subsequence divisible by the divisor, then it is composed of pre-fixes (leading fragments) that give the same remainder and vice versa. Let us group the pre-fixes of a given sequence by the remainders from modulo 5 of the sum of their elements If there are k sub-sequences for some remainder, then the number of continuous subsequences with the sum of elements divisible by divisor is K choose 2 = k(k-1)/2
Check if two strings s1 and s2 are rotated
Return (s1+s1).indexOf(s2)
#codingexercise
Double GetNthRootProductEachTermRaisedPTimesQoverPDividedQ (Double [] A,Double p, Double q)
{
If ( A== null) return 0;
Return A.NthRootProductEachTermRaisedPTimesQoverPDividedQ(p, q);
}
No comments:
Post a Comment