Module 1: Given two numbers a and b as input, return the sum of the numbers. Runs in a series
The scores of a batsman in the five matches of a one day international series have been provided. Calculate the total number of runs the batsman scored in the series Compute polynomial
Compute the value of the polynomial x^2y^2 +10xy – 6x + 150y -100, where the inputs x and y have been provided. Seconds to hours
Given the time in number of seconds, find out how many hours have been completed toHours(22125) = 6 toHours(3598) = 0 Hundreds digit
Given a 4 digit number as input, find the value of its hundreds digit. significantDigit(3454) = 4 significantDigit(1999) = 9 Most Significant Digit
Given a 4 digit number as input, find the value of its most significant digit. significantDigit(3454) = 3 significantDigit(1999) = 1 Required run rate
A team is chasing the target set in a one day international m atch. The objective is to compute the required run rate. The following have provided as input: target, maxOvers, currentScore, oversBowled. runrateRequired(326,49,210,33)=7.25 Difference in average
The scores of a batsman in first and second innings of two test matches have been provided. Note that inn1 and inn2 refer to the first and second innings of the first test match. inn3 and inn4 refer to the first and second innings of the second test match. Compute the difference in average of the batsman while performing in the first innings of a test match vs the second innings. diffInAverage(134,29,56,48)=56.5 (The first innings average is (134+56)/2 = 95. The second innings average is (29+48)/2 = 38.5. The difference in averages is 95-38.5 = 56.5) Make a 3 digit number
Given a digit as input, create a 3 digit number in which all the digits are the same as the input digit. make3DigitNum(4) = 444 make3DigitNum(1) = 111 Sum of 2 Digits
Given a 2 digit number as input, compute the sum of its digits. Assume that the number has 2 digits. sum2Digits(12) = 3 (1+2 = 3)
sum2Digits(10) = 1 (1+0 = 0) sum2Digits(96) = 15 (9+6 = 15) Sum of 4 Digits
Given a number as input, compute the sum of its last 4 digits. Assume that the number has atleast 4 digits. sumOfDigits(12345) = 14 (last 4 digits 2+3+4+5 = 14) sumOfDigits(1000) = 1 Area of a square
You have been given 4 inputs x1,y1,x2 and y2. The points (x1,y1) and (x2,y2) represent the end points of the diagonal of a square. Return the area of the square. computeArea(0,0,5,5) = 25 computeArea(2,3,8,15) = 90 computeArea(1,1,4,3) = 6.5 Make the right decimal
Given 3 digits a,b and c as input, return a double of the form a.bc makeDecimal(4,8,1) = 4.81 makeDecimal(0,0,6) = 0.06 makeDecimal(9,0,7) = 9.07 Make and add numbers
Given three digits as input, create a 4 digit number out of each input in which all the digits are the same. Then add all the 3 numbers and return the value add4DigitNums(1,2,3) = 6666 (as 1 will form 1111, 2 will form 2222, 3 will form 3333 and 1111+2222+3333 = 6666) add4DigitNums(4,5,6) = 16665 (as 4 will form 4444, 5 will form 5555, 6 will form 6666 and 4444+5555+6666 = 16665) Seconds to time
Given the time of a day in number of seconds, convert it into time in hhmmss format. Note that the time is past noon, and hence the hours will never be less than 12. toHours(86399) = 235959 toHours(46800) = 130000
Module 1b And of booleans
Given three booleans as input, return the and of the all three booleans Larger than at least one
Given three numbers as input, num, num1 and num2, return true if num is greater than atleast one of
sum2Digits(10) = 1 (1+0 = 0) sum2Digits(96) = 15 (9+6 = 15) Sum of 4 Digits
Given a number as input, compute the sum of its last 4 digits. Assume that the number has atleast 4 digits. sumOfDigits(12345) = 14 (last 4 digits 2+3+4+5 = 14) sumOfDigits(1000) = 1 Area of a square
You have been given 4 inputs x1,y1,x2 and y2. The points (x1,y1) and (x2,y2) represent the end points of the diagonal of a square. Return the area of the square. computeArea(0,0,5,5) = 25 computeArea(2,3,8,15) = 90 computeArea(1,1,4,3) = 6.5 Make the right decimal
Given 3 digits a,b and c as input, return a double of the form a.bc makeDecimal(4,8,1) = 4.81 makeDecimal(0,0,6) = 0.06 makeDecimal(9,0,7) = 9.07 Make and add numbers
Given three digits as input, create a 4 digit number out of each input in which all the digits are the same. Then add all the 3 numbers and return the value add4DigitNums(1,2,3) = 6666 (as 1 will form 1111, 2 will form 2222, 3 will form 3333 and 1111+2222+3333 = 6666) add4DigitNums(4,5,6) = 16665 (as 4 will form 4444, 5 will form 5555, 6 will form 6666 and 4444+5555+6666 = 16665) Seconds to time
Given the time of a day in number of seconds, convert it into time in hhmmss format. Note that the time is past noon, and hence the hours will never be less than 12. toHours(86399) = 235959 toHours(46800) = 130000
Module 1b And of booleans
Given three booleans as input, return the and of the all three booleans Larger than at least one
Given three numbers as input, num, num1 and num2, return true if num is greater than atleast one of
num1 and num2. Do not use if statement to solve this problem. largerThanOne(24,10,36) = true largerThanOne(50,60,76) = false largerThanOne(20,10,0) = true Larger than exactly one
Given three numbers as input, num, num1 and num2, return true if num is greater than exactly one of num1 or num2. Do not use if statement to solve this problem. largerThanExactlyOne(24,10,36) = true largerThanExactlyOne(50,60,76) = false largerThanExactlyOne(20,10,0) = false Numbers in ascending order
Given 3 numbers : num1, num2 and num3 as input, return true if they are in ascending order. Important:Do not use if statement in solution. inAscendingOrder(2,4,6) = true inAscendingOrder(2,6,4) = false Numbers in order
Given 4 numbers : num1, num2, num3 and num4 as input, return true if they are in ascending order or in descending order. Important: Do not use if statement in solution inOrder(2,4,6,6) = true inOrder(8,7,7,0) = true inOrder(2,4,7,6) = false Dry run – run – If If
Dry runs for If Divides (a,b)
Given two numbers, return true if any one of them divides the other, else return false Is Multiple of 3 and 7
Given a number n, return true if it is divisible by either 3 or 7. For e.g., if n= 27, output is true. If n=58, output is false. If n=63, output is true. Largest number (of 3)
Given three numbers as input, return the largest number. largest(10,20,15) = 20 Has scored a century
The scores of a batsman in his last three innings have been provided. You have to determine whether he has scored a century in the last three innings or not. If yes, return true else return false. For e.g. if the scores in the last three innings are 48,102,89 return true. If the scores are 99, 12, 0 return false Number of days in month
Given the number of the month in 2013 (1 for January, 12 for December), return the number of days in it.
numOfDays(3) = 31 numOfDays(6) = 30
Same last digit
Given 2 non negative numbers a and b, return true if both of them have the same last digit. For e.g. if the two numbers are 1268 and 80128 the output is true. If the two numbers are 901 and 9010 the output is false Leap year
Given a year, return true if it is a leap year otherwise return false. Please note that years that are multiples of 100 are not leap years, unless they are also multiples of 400. Boolean computation
The inputs are three booleans a,b and c and a number n. If n=1, the return value is (a or b or c). If n=2 the return value is ((a and b) or c). If n=3, the return value is (a and b and c). Dry runs – runs – Else Else
Dry runs for Else Largest Number
Given 5 numbers as input, find out the largest number Addition of two fractions
Given two fractions, check whether their sum sum is greater than or equal to 1. You have been provided 4 inputs, num1, den1, num2 and den2. The first fraction is num1/den1 and the second fraction is num2/den2. Add the fractions and return true if their sum is greater than or equal to 1 else return false. For e.g. if num1= 6, den1=11, num2 = 10, den2 = 21, their sum is 236/231 which is greater than 1 and hence the output is true. Add to form third
Given three numbers a,b and c, return true if the sum of any two equals the third number. For e.g. if a=12,b=28,c=16 output is true (a+c=b). Scored century in two innings
Given the scores of a batsman in four innings, return whether he scored at least two centuries or not. twoCentury(125,86,48,231) = true twoCentury(25,50,98,123) = false twoCentury(128,145,23,177) = true Absolute Value of Diff
Given an input n, the return value is the absolute value of the difference between n and 144. However, if n is greater than 288, the return value is thrice the absolute value of the difference of n and 144. Check Combination – Combination – 3 3
Given a, b and c, return true if any one of them can be formed by a mathematical operation using the other two numbers. the mathematical operations permitted are addition, subtraction, multiplication and division. For e.g if a=12, b = 15, c = 3 output is true (15-12 = 3). Closest Number
Given three numbers, num1, num2 and target as input, the objective is to figure out which one of num1 or num2 is closest to target and return it. If both are equally close, return the larger number. closest(10,100,6) = 10 closest(124,190,177)= 190
Dry runs on char
Dry runs for Char Dry runs on fns
DryRunFns0 Change the case
Given a char as input, if it is an alphabet change its case otherwise return it as it is. For e.g. if the input is
„a‟ return „A‟, if the input is „K‟ return „k‟, if the input is ‟8′ return ‟8′. Is digit
Given a char as input, return true if it is a digit (i.e. between 0 to 9).
isDigit(„a‟) = false isDigit(‟2′) = true Middle Char
Given three chars as input, return the char that would come in the middle if the chars were arranged in order. Note that > operator can used for chars.
middle(„a‟,'x‟,'X‟) = „a‟ middle(‟5′,‟6′,‟2′) = ‟5′ Arithmetic Operation
Two numbers a and b and a char c have been provided as inputs. The char c represents a mathematical operation namely +,-,*,/,% (remainder). The task is to perform the correct operation on a and b as specified by the char c.
compute(10,3,‟+') = 13 compute(10,3,‟/') = 3 compute(10,3,‟%') = 1 Compute grade
Given the marks of a student in five subjects, compute the overall grade. The grades will be on the basis of the aggregate percentage. if overall percentage >= 85%, grade is A, if it is >=75% it is B, >=60% is C, >=45% is D, if it is >=33% it is E else F.
getGrade(87,79,98,82,75) = „B‟ Lottery prize
Jack bought a lottery ticket. He will get a reward based on the number of the lottery ticket. The rules are as follows - If the ticket number is divisible by 4, he gets 6 - If the ticket number is divisible by 7, he gets 10 - If the ticket number is divisible by both 4 and 7, he gets 20 - Otherwise, he gets 0. Given the number of the lottery ticket as input, compute the reward he will receive lotteryReward(22) = 0 lotteryReward(16) = 6 lotteryReward(21) = 10 lotteryReward(56) = 20
Lottery prize – 3 tickets
Jack bought 3 lottery tickets. He will get a reward based on the number of the lottery ticket. The rules are as follows - If the ticket number is divisible by 4, he gets 6 - If the ticket number is divisible by 7, he gets 10 - If the ticket number is divisible by both 4 and 7, he gets 20 - Otherwise, he gets 0. Given the numbers of the 3 lottery tickets as input, compute the total reward he will receive. In this problem define a function to compute the reward given the ticket number and use that function to calculate the total reward. lotteryRewardFor3(22,16,21) = 16 lotteryRewardFor3(56,8,49) = 36 Same last digits
You have been given 4 numbers as input. Return true if any one the numbers has the same last 2 digits. For e.g. 123455 has the same last 2 digits (5 and 5) whereas 123545 does not (4 and 5). In this problem, define a function that check whether a number has the same two digits or not and returns true or false. Use that function to calculate for the 4 numbers. sameLastDigits(12445, 234454, 12781, 2300) = true sameLastDigits(12, 20, 5, 6) = false Dry run fns-1
DryRunFns1 Sum divisible by 11
You have been given 4 numbers as input. Return true if you can find 3 numbers among them whose sum is divisible by 11. In this problem, define a function that takes 3 numbers as input and returns true if there sum is divisible by 11. Use this function to check for the 4 numbers. sumDivBy11(20,30,10,16) = true (as 20+30+16 = 66 which is divisible by 11) sumDivBy11(20,21,23,28) = false (as 20+21+23=64, 20+21+28=69, 21+23+28=71, 21+23+28=72 none of which are divisible by 11) Multiple Check
Given a number n as input, return true if n is divisible by at least three and not divisible by at least one of 2,3,5,7 and 11. check(24) = false (divisible by 2 nos, not divisible by 3 nos) check(60) = true (divisible by 3 nos, not divisible by 2 nos) Double century and century
A batsman played 4 innings in a test series. His scores have been provided as input. You have t o determine whether he scored a double century and a century in the series. This means that the batsman should have had one score of at least 200 and a different score of at least 100. Please note that if the batsman scored two double centuries, then also the output will be true. For e.g. if the scores are 56, 208, 45, 110 the output is true. If the scores are 22, 0, 210, 45 the output is false. Add the last digits
Given two numbers num1 and num2 as input, return the sum of the last 3 digits of num1 and the last 3
digits of num2. For solving this problem, define a function that returns the sum of the last 3 digits of a number provided as a parameter and use that function. sumLast3(123,8456) = 21 (123 -> 1+2+3 = 6, 8456 -> 4+5+6 = 15) Closest 100
Given a positive number as input find the multiple of 100 which is closest to it. Note that the multiple of 100 can be greater or smaller than the number. Also if the number is equidistant from the greater and smaller multiple, return the greater multiple. closest100(214) = 200 closest100(277) = 300 closest100(250) = 300 closes100(300) = 300 Close to century
Given the score of a batsman and an integer n, return true if the score is within n of a multiple of 100. For e.g. if the score is 186 and n = 15, the output is true. If score is 392 and n=5, the output is false. If score is 409 and n = 12 the output is true Scored consecutive century
Given the scores of a batsman in four innings, return true if he scored centuries in consecutive innings. consecutiveCentury(123,45,178,88) = false consecutiveCentury(123,23,145,221) = true consecutiveCentury(23,111,152,89) = true Special 20
A number is special20 if it is a multiple of 20 or if it is one more than a m ultiple of 20. Write a function that return true if the given non-negative number is special20. special20(21) = true special20(100) = true special20(99) = false Diff 25
Given three ints as input , return true if one of them is 25 or more less than one of the other numbers. diff25(1, 13, 40) = true diff25(13, 1, 25) = false diff25(40, 60, 2) = true Lottery ticket
You have purchased a lottery ticket showing 3 digits a, b, and c. The digits can be 0, 1, or 2. If they all have the value 2, the result is 10. Otherwise if they are all the same, the result is 5. Otherwise if both b and c are different from a, the result is 1. Otherwise the result is 0. lotteryTicket(2, 2, 2) = 10 lotteryTicket(4, 2, 1) = 1 lotteryTicket(2, 2, 1) = 0 lotteryTicket(0, 0, 0) = 5 More same, more prize
You have a green lottery ticket, with ints a, b, and c on it. If the numbers are all different from each other,
the result is 0. If all of the numbers are the same, the result is 20. If two of the numbers are the same, the result is 10. greenTicket(1, 2, 3) = 0 greenTicket(2, 2, 2) = 20 greenTicket(1, 1, 2) = 10 Blackjack
Given 2 int values greater than 0, return whichever value is nearest to 21 without being greater than 21. Return -1 if the values are greater than 21. Also return -2 if both the values are same and less or equal to 21. blackjack(18,21) = 21 blackjack(21,16) = 21 blackjack(22,23) = -1 blackjack(12,22) = 12 blackjack(20,20) = -2
Module1c Sum of numbers
Given a number n as input, output the sum of numbers from 1 to n. sum(3) = 6 sum(355) = 63190 Sum of Squares
Given two numbers n1 and n2 such that n2>n1, find sum of squares of all numbers from n1 to n2 (including n1 and n2). computeSumofSquares(1,5) = 55 Sum of certain numbers
Given a number n as input, find the sum of all numbers from 1 to n which are not divisible by either 2 or 3. sum(10) = 13 (1+5+7) sum(20) = 73 Count factors
Given a number n as input, find the count of its factors other than 1 and n. countOfFactors(144) = 13 (2,3,4,6,8,9,12,16,18,24,36,48,72) countOfFactors(13) = 0 Count common factors
Given two numbers n1 and n2 as input, find the count of common factors of n1 and n2. Note 1 and the number itself have not been considered as factors in this problem.
countFactors(144,12) = 4 (2,3,4,6) countFactors(144,13) = 0 Is Prime
Given a number n as input, return whether the number is a prime number or not. Please note that 1 is not a prime number Nth Power
Given a number a, compute the nth power of a Sum of Digits (with no. of digits)
Given 2 inputs, a number n and the number of digits it has d , find the sum of its digits. For e.g. if n=123, d =3, the output is 1+2+3=6. If n=45891 and d=5 the output is 4+5+8+9+1=27. Reading links – While
While loop Dry run – While
DryRunWhile Dry run – For (2)
DryRunFor_2 No. of 9′s in number (No. of digits specified)
Given 2 inputs, a number and the number of digits it has , find out the no. of 9′s in the number. For e.g. if number=80123 and digits=5, the output is 0. If number=909090 and digits=6, the output is 3. Perfect Number
A perfect number is a positi ve integer that is equal to t he sum of its factors. For example, 6 is a perfect number because 6=1+2+3; but 24 is not perfect because 24<1+2+3+4+6+8+12. Given a number n, the objective is find out whether it is a perfect number or not. FizzBuzz
A number is considered fizz if it is divisible by 3. It is considered buzz if it is divisible by 5. I t is considered fizzbuzz if it is divisible by both 3 and 5. A fizzbuzz is neither fizz nor buzz. Given two numbers n1 and n2 such that n2>n1, find the sum of total number of fizz, buzz and fizzbuzz. countFizzBuzz(1,20) = 9 (fizzbuzz : 15; fizz : 3, 6, 9, 12, 18; buzz : 5, 10, 20) Is Fizz
A number is defined as a Fizz if it is a multiple of 3 or h as the digit 3 in it. Given a number as input, determine whether it is a Fizz or not. isFizz(12) = true isFizz(13) = true isFizz(14) = false Dry run – While
These are exercises that provide dry run practise. No code needs to be written and hence there is no need to upload the code in this problem. Sum of Digits
Given a number n, find the sum of its digits. sumDigits(12345) = 15 sumDigits(1000010) = 2
Count digits
Given a number as input, count the number of digits it has. You can assume that the number is not negative. countDigits(0) = 1 countDigits(1234) = 4 Count the digit
Given a number n and a digit d as input, find the number of time d occurs in n. You can assume that the number is non-negative. findDigitCount(2001,0) = 2 findDigitCount(0,0) = 1 findDigitCount(9,2) = 0 Binary to decimal
Given a number as binary (digits 0 and 1), convert it to its corresponding decimal number. convertBinaryToDecimal(1001) = 9 convertBinaryToDecimal(11111) = 31 Reading links – Break, return
Break, return Dry run – functions
DryRunFns Anyone prime
Given three numbers as input, return true if at least one of them is a prime number. For solving this problem, define a function that checks whether a number is a prime or not and use that function. anyonePrime(12,23,45) = true anyonePrime(97,83,71) = true anyonePrime(169,361,121) = false Same first digit
Given three numbers as input, return true if the first digit of any two of them is the same. The first digit of 2345 is 2, of 981201 is 9. Assume all the numbers are positive integers greater than 0. For solving this problem, define a function that computes the first digit if a number and use that function. sameFirstDigit(981231,7810009,9) = true (981231 and 9 have the same first digit, which is 9). sameFirstDigit(122341,2231,341) = false Next multiple of 3 and 7
Given a number num as input, find the smallest number greater than num that is a multiple of both 3 and 7. findNextMultiple(12) = 21 findNextMultiple(30) = 42 Middle Digit
Given a number as input, find its middle digit. If number of digits in the number is even, return average of the two middle digits.If n has only one digit, return that digit. You can assume the number to be nonnegative. findMiddleDigit(12345) = 3
findMiddleDigit(125839) = 6 (average of 5 and 8) findMiddleDigit(0) = 0 Check Combination – 3
Given a, b and c, return true if any one of them can be formed by a mathematical operation using the other two numbers. the mathematical operations permitted are addition, subtraction, multiplication and division. For e.g if a=12, b = 15, c = 3 output is true (15-12 = 3). Prime, Perfect, Has Digits
Given two integers, n and checkType as input, return - If checkType =1, return whether n is a prime or not - If checkType =2, return whether n is a perfect number or not - If checkType =3, return whether n has a 3,6 or 9 in its digits or not - Otherwise, return false check(23,1) = true; check(23,2) = false; check(23,3) = true; Check combination – 4
Given 4 numbers a, b, c and d as input, return true if we can find a set of 3 numbers among them with the property that : One of numbers can be formed by a mathematical operation using the other two numbers. The mathematical operations permitted are addition, subtraction, multiplication and division. check4(8,16,48,2) = true (because we can form a set of three numbers (8,16,2) where 16=8*2) check4(8,16,48,12) = false Check combination – 5
Given 5 numbers a, b, c, d and e as input, return true if we can find a set of 3 numbers among them with the property that : One of numbers can be formed by a mathematical operation using the other two numbers. The mathematical operations permitted are addition, subtraction, multiplication and division. check5(3,7,9,48,2) = true (because we can form a set of three numbers (7,9,2) where 2=9-7) check5(3,7,9,48,5) = false Dry run – Nested loops
DryRunFor_Nested Sum rounded numbers
Round a number to the next multiple of 10 if its ones digit is 5 or more, othwerise round it the previous multiple of 10.So, 25 and 26 round to 30 where as 23 and 24 round to 20. 20 also rounds to 20. You have been given 4 ints as input. Round each of the input values and return their sum. roundedSum(11,15,23,30) = 80 (11 rounds to 10, 15 to 20, 23 to 20 and 30 to 30) roundedSum(1,3,7,9) = 20 Compute the HCF
Given 2 numbers a and b, compute the HCF (Highest Common Factor) of a and b. HCF is the largest number that divides both a and b. For e.g. the HCF of 144 and 162 is 18. The HCF of 32 and 81 is 1. HCF can be computed as follows. If a=b, the HCF(a,b)=a. If a>b and b divides a, HCF (a,b) = b, else HCF(a,b)=HCF(b,a%b) hcf(100,125)=25
hcf(24,144)=24 hcf(97,41)=1 Count Fizz
A number is defined as a Fizz if it is a multiple of 3 or has t he digit 3 in it. Given a number num as input, count the number of Fizz between 1 and num. countFizz(15) = 6 (3,6,9,12,13,15) countFizz(100) = 45 (3,6,9,12,13,15, 18,21,23,24,27,30,31, 32,33,34,35,36,37,38,39,42, 43,45,48,51,53, 54,57,60,63,66,69, 72,73,75,78,81,83, 84,87,90,93,96,99) Count the primes in between
Given two numbers n1 and n2 as input, count the number of primes between n1 and n2. Note that n2>=n1. Also both n1 and n2 will be included in the count, if they are primes. countPrimes(31,41) = 3 (31,37,41) countPrimes(1,50) = 15 (2,3,5,7,11,13,17,19,23,29,31,37,41,43,47) Compute nth prime
Given an input n, find out the nth prime Sum of Digits (Repeated)
Given a number n, find the sum of its digits. If the sum is greater than 9, repeat the same process till it becomes a single digit. For e.g. if the number is 123 the output is 1+2+3=6, if the input is 45891, the output is 4+5+8+9+1=27 -> 2+7=9 Sum of Primes
Given a number n, return true if there exist a and b such that a+b=n and both a and b are prime numbers. isSumOfPrimes(15) = true (2+13=15) isSumOfPrimes(17) = false Super divide
A positive int is called super -divide if every digit in t he number divides the number. So for example 128 divides itself since 128 is divisble by 1, 2, and 8. Note that no number is divisible by 0. Given a number as input, determine if it is a super-divide. superDivide(184) = true superDivide(39) = false superDivide(120) = false Sum numbers, check digits
Given 2 non-negative ints, a and b, return their sum, so long as the sum has the same number of digits as a. If the sum has more digits than a, just return a. sumLimit(2, 3) = 5 sumLimit(8, 3) = 8 (as 8+3 = 11 which has 2 digits which a = 8 has 1 digit) sumLimit(8, 1) = 9 Are all factors prime
Given a number n, return true is all the factors of n are prime numbers. Note that 1 and the number itself are not considered as factors in this problem. areAllFactorsPrime(22) = true (2,11 are prime)
areAllFactorsPrime(25) = true (5 is a prime) areAllFactorsPrime(32) = false (4,8,16 are not prime) Check sequence in number
Given two numbers, n and target, as input, check whether the number target can be found in n or not. For e.g. if n=1234, the return value will true if target is 12, 23 or 34. For all other values of target, the return value will be false. Note that target is always a two digit number. hasSequence(234567,45) = true (as 45 is there is 234567) hasSequence(234567,54) = false (as 54 is not there is 234567) Rotating digits
Given a number n as input, the objective is to figure out whether any rotation of the digits of n is a prime number or not. A rotation is formed by the removing the last digit and putting it in front. For e.g. the rotations of n=1639 are 1639, 9163, 3916 and 6391. Note that the count of possible rotations is equals to the count of digits in the number. It can be assumed that none of the digits in the input number is a zero. isPrimePossible(91) = true (as 19 is a prime) isPrimePossible(824) = false isPrimePossible(1462) = true (4621 is a prime) Maximum number of factors
Given a number n as input, find the number x, such that n<=x<=n*n and x has the maximum number of factors. If two numbers in the range (n,n*n) have the same maximum number of factors, return the smaller number. maxFactors(4) = 12 (12 has the maximum no of factors between 4 and 16) maxFactors(6) = 36 Count largest sequence of composites
Given a number n as input, find the length of largest sequence of composite numbers between n and n*n (both n and n*n are inclusive). maxSequence(6) = 5 (24,25,26,27,28 are all composite numbers while 23 and 29 are prime) maxSequence(10) = 7 (90,91,92,93,94,95,96 are composite numbers while 89 and 97 are prime)
Module 2
Is char in string
Given a string s1 and a char ch as input, return true if ch is present in s1. For e.g. is s1=”Trisect”, ch = „T‟, output is true. If s1=”Trisect”, ch = „m‟, output is false. Determine the longer string
Given two strings s1 and s2 of different length as input, return the longer string. For e.g. if s1=”Trisect”, s2
= “Institute”, the output is “Institute”. Join alternate chars
Given two strings s1 and s2 of equal length as input, the expected output is a string which the 1st char from s1, then 1st char from s2, then 2nd char from s1, then 2nd char from s2 and so on. For e.g. if
s1=”Outer”, s2 = “Space”, the output is “OSuptaecre”. Count of char in string
Given a string and a char as input, output the number of times, the char appears in the string.
count(“Hello World”,‟l')=3 count(“Animal”,‟N')=0 Change the case of the String
Given a string as input, the expected output is a string where the case of all alphabets has been changed.
changeCase(“Hello 123″) = “hELLO 123″. Get the first word
Given a sentence as an input, return the first word of the sentence. Note that words in a sentence have
the char space or „ „ between them. firstWord(“Hello how are you”)=”Hello” firstWord(“May I come in?”) =”May” Make String Pattern
Given 2 strings str1 and str2 as input, return a string of the form (str1)str2(/str1)
makePattern(“site”,”google”)=(site)google(/site) Reading Links : Strings
The following are the reading links on String. They also include the link for the Javadoc on String Manipulating Characters in a String Comparing Strings and Portions of Strings Javadoc : String Dry Run : Strings(2)
File for DryRun_Strings_2 Second half of string
Given a string as input, output the second half of the string. You can assume that the length of the string
is a even number. For e.g. if input is “HelloWorld” output is “World”. Are same strings
Given 3 strings as input, return true if any two of the strings are the same.
areSame(“hello”,”world”,”hello”) = true areSame(“123″,”4567″,”89102″) = false
Ends with ing
Given a string as input, return true if the string ends with “ing”. endsIng(“string”) = true endsIng(“strain”) = false Combine to form expression
Given an outer string of length 6, and a word, the expected output is a string where the word is in the
middle of the outer string. For e.g. if the outer string is “((()))” and the word is “hello”, the expected output is “(((hello)))”. Is Java File
A file name in java ends in . java. Given the name of t he file, return true if its a java file, else return f alse
isJavaFile(“hello.java”)=true isJavaFile(“java.pdf”)=false Pattern in string
Given two strings str1 and str2 as input, determine whether str2 occurs with str1 or not.
occurs(“JavaLadders”,”Java”)=true occurs(“Problem Panel”,”Panes”) = false Reverse a string
Given a string as input, reverse it. Reverse means return the string if it is read from right to left
reverse(“Hello”)=”olleH” reverse(“TAP”)=”PAT” Count chars in same position
Given 2 strings, str1 and str2, as input, return the count of the chars which are in the same position in str1 and str2.
count(“Hello”,”World”)=1 (Because l is at 3rd position in both Hello and World) count(“New York”,”New Delhi”)=4 (because “New ” are in the position count(“rhinoceroses”,”hippopotamus”)=2 (because o is 4 position in both, s is in 11th position in both) Remove chars from string
Given two strings, str1 and str2 as input, remove all chars from str1 that appear in str2.
remove(“Hello”,”World”)=”He” (l and o have been removed from Hello as they appear in World) Swap last 2 chars
Given a string as input, return the string with its last 2 chars swapped.
swap(“Hello”)=”Helol” swap(“123456″)=”123465″ Double the string
Given a string, return a string where for every char in the original, there are two chars.
double(“The”) = “TThhee” double(“AAbb”) = “AAAAbbbb” double(“HiHello”) = “HHiiHHeelllloo” Count hello
Return the number of times that the string “hello” appears anywhere in the given string. countHello(“abc hello def”) = 1
countHello(“Hi. Hello. Hello. Ok”) = 2 countHello(“hi”) = 0 Is bat = ball
Given a string, return true if the string “bat” and “ball” appear the same number of times. batBall(“1bat2ball”) = true batBall(“1bat2bat3ball4catch”) = false batBall(“hello”) = true Is Trisect there
Given a string, return true if the string contains an appearance of “Trisect” where “Trisect” is not immediately followed by #. So “Trisect?” is fine but “Trisect#” is not. trisectThere(“TrisectInstitute”) = true trisectThere(“TheTrisect#Institute”) = false Do they end the other
Given two strings as input, return true if either of the strings appears at the end of the other string.
endOther(“HiHello”, “Hi”) = true endOther(“Hello”, “Hello. How are you”) = true endOther(“Hi. Hello”, “Hello. Hi”) = false Combine s1 and s2
Given two strings s1 and s2 as input, create a string made of the first char of s1, the first char of s2, the second char of s1, the second char of s2, and so on. Any leftover chars go at the end of the result string.
combine(“abc”,”123″) = “a1b2c3″ combine(“Hi”,”Hello”) = “HHiello” combine(“Namaste”, “Hi”) = “NHaimaste” Repeat n chars
Given a string and an integer n as input, return a string made of n repetitions of the last n characters of the string. Note that n is non-negative and less than the length of the string.
repeatN(“Trisect”,3) = “ectectect” repeatN(“Trisect”,1) = “ttt” repeatN(“Trisect”,0) = “” Repeat count times
Given two strings s1 and s2 and an integer count as input, return a string made of count occurrences of s1 with each occurrence separated by s2.
repeatCount(“Trisect”, “##”, 3) = “Trisect##Trisect##Trisect” repeatCount(“Hi”, “x”, 2) = “HixHi” repeatCount(“Trisect”, “##”, 1) = “Trisect” Reducing n chars
Given a string and an integer n as input, return a string made of the first n characters of the string, followed by the first n-1 characters of the string, and so on. Note that n is non-negative and less than the length of the string.
reducingN(“Trisect”,3) = “TriTrT”
reducingN(“Choco”, 4) = “ChocChoChC” reducingN(“Cream”, 2) = “CrC” And in middle
Given a string s1 as input, return true if “and” appears in the middle of s1. Note that middle means that the number of chars to the left and right of the “and” must differ by at most one. andInMiddle(“ABCandDEF”) = true andInMiddle(“ABCandDEFandABCandDEF”) = true andInMiddle(“ABCandDEFandABCandDEF123″) = false andInMiddle(“ABC”) = false In between this
Given a string as input, return the substring that is between the first and last appearance of “this” in the
string. If “this” is present 0 ot 1 times return the empty string. getInBetween(“thisXandthisY”) = “Xand” getInBetween(“thisXandthisYandthisZ”) = “XandthisYand” getInBetween(“thisXand”) = “” Star covered by same char
Given a string as input, return true if for every „*‟ in the string, the chars both immediately before and after
„*‟ are the same. Note that it is given that „*‟ cannot be followed by „*‟ in the input. Also if „*‟ is at the beginning or end of the string, then the output should be false.
coveredStar(“123*3″) = true coveredStar(“123*34*455*56″) = true coveredStar(“*123*34″) = false coveredStar(“123*34*455*667*789″) = false Remove neighbours
Given a string as input, return a string where for every „@‟ in the input the chars immediately to its left and right have been removed. Note that it is given that „@‟ cannot be followed by „@‟ in the input. Also if „@‟ is at the beginning or end of the string, then only one char will be removed.
removeNeighbours(“123@456″) = “12@56″ removeNeighbours(“123@456@789@0@1@234″) = “12@5@8@@@34″ removeNeighbours(“@”) = “@” removeNeighbours(“123@”) = “12@” Replace not present chars
Given two strings s1 and s2 as input, return a string where the characters of s1 which are not in s2 have been replaced by #.
replaceChars(“12345612″, “274″) = “#2#4###2″ replaceChars(“9990001″, “9″) = “999#####” replaceChars(“876768678″, “667788″) = “876768678″ Three letter pattern
A string str has been provided as input. T he objective is to find three character patterns in str start ing with
„t‟ and ending with the char „p‟. For all such patterns, the middle character is removed. tpPattern(“tiptop”) = “tptp”
tpPattern(“tip.tip..tip”) = “tp.tp..tp”
tpPattern(“tpttipptptaptptopp”) = “tpttpptptptptpp” Is present – t?m
Given a string as input, return true if the string contains a “tim” string, but where the middle char „i‟ can be any char.
findTim(“tom”) = true findTim(“simtiptrimterm”) = false
findTim(“sim tip twm stern”) = true Count pattern code
Given a string as input, count the number of times, the string “code” appears in the input string. Note that while counting the occurrence of “code”, we‟ll accept any letter in place of „d‟. So “core”, “cope”, “come” etc will also be added to the count.
countCode(“count code now”) = 1 countCode(“count code now. come here.”)= 2 countCode(“code core coore coome cope cone coone”) = 4 Middle one-third of string
Given a string as input, return the middle one-third of the string. That is, if the string is of length 12, break
it into 3 pieces of length 4 and return the middle piece. For e.g. if the input is “abcdefghijkl”, the 3 pieces will be “abcd”, “efgh”, “ijkl” and the middle one-third will be “efgh”. If the length of the string is of the form 3n+1 add a space at the beginning and end of the string before computing the middle one-third. If the length of the string is of the form 3n+2, remove the first and last character and then compute the middle one-third.
oneThird(“animal”)=”im” oneThird(“America”)=”eri” oneThird(“HelloMother”)=”oMo” Is palindrome
Given a string as input, check whether it is a palindrome or not. A palindrome is a string which is same if it is read from left to right or from right to left
isPalindrome(“1234321″)=true isPalindrome(“malayalam”)=true isPalindrome(“INDIA”)=false Middle word as per dictionary
Given 3 words w1,w2 and w3 as input, output the word that will come in between in a dictionary.
middleWord(“sat”,”soot”,”sit”)=”sit” middleWord(“gone”,”went”,”go”)=”gone” Move uppercase chars to end
Given a string as input, move all the alphabets in uppercase to the end of the string
move(“Hello World”)=”ello orldHW” move(“India”)=”ndiaI” Larger number
Given 2 strings representing numbers as input, return the larger number. Note that both the numbers are
non negative.
larger(“123″,”3243″)=”3243″ larger(“”2354725234782357″,”2354725234782347″)=”2354725234782357″ Convert string to number
Given a string as input, convert it into the number it represents. You can assume that the string consists of only numeric digits. It will not consist of negative numbers
toNumber(“12001″)=12001 toNumber(“9945″)=9945 Remove multiple spaces
Given a string as input, remove all the extra spaces that appear in it. Spaces wherever they appear should be a single space. Multiple spaces should be replaced by a single space.
remove(“How are you”)=”How are you”) remove(“123 456 789″)=”123 456 789″ Add the numbers in string
Given a string as inp ut, add all the numbers that are part of the string. Note that one or more spaces „ „ demarcate two numbers. Also there is no negative number in the string.
addNumbers(“12 24 36″)=72 addNumbers(“12 12 100″)=124 Convert string to number (with negative nos)
Given a string as input, convert it into the number it represents. You can assume that the string consists of only numeric digits. The numbers can also be negative in which the string will begin with -.
toNumber(“12001″)=12001 toNumber(“-45″)=-45 Convert a binary to decimal system
Given a binary number as input convert it into base 10 (decimal system).
convert(“10011010010″)=1234 convert(“100″)=4 Note that to convert a number 100111 from binary to decimal, the value is 1*2^5 + 0*2^4 + 0*2^3 + 1*2^2 + 1*2^1+ 1*2^0. Also note that 5 here is the length of the binary number – 1. Find the middle word of the list
Given 5 strings as input, find the word which will appear in the middle if the strings are arranged in lexicographical order
middleWord(“hello”,”how”,”are”,”you”,”today”)=”how” middleWord(“12″,”34″,”56″,”78″,”90″)=”56″ Solve simple arithmetic expression
Given a string representing a simple arithmetic expression, solve it and return its integer value. The expression consists of two numbers with a + or – operator between the numbers. Note that the numbers will be non negative.
solve(“34+45″)=79 solve(“100-2110″)=2010
Convert to binary
Given a number in base 10 as input convert it into binary.
convert(1234) = “10011010010″ convert(4) = “100″ Note that the way to convert a number from decimal is as follows. Suppose the input decimal number is num and the binary string is bin. Append the remainder of num with 2 to the front of the string bin and then divide num by 2. Go on doing it till num becomes 0. So if num = 14, and bin is initially “” (empty string)
Step 1: append num%2 to the front of bin. So bin = “0″. Divide num by 2. Hence and num = 14/2 = 7 Step 2: bin = “10″ and num = 7/2 = 3 Step 3: bin = “110″ and num = 3/2 = 1 Step 4: bin = “1110″ and num = 1/2 = 0 Largest number in list
Given a string consisting of space demarcated numbers as input, return the largest number. Note that all the numbers are non negative.
largest(“1 4 8 21 144 6 13″) = “144″ largest(“1231242342343 23423234234232342342″) =”23423234234232342342″ Permutation of each other
Given two strings str1 and str2 as input, check whether the strings are a permutation of each other. str1 is a permutation of str2 if all the characters of str2 can be arranged in some way to form str1.
isPermutation(“how”,”who”)=true isPermutation(“1234″,”43210″)=false Add large numbers
Two strings representing two numbers have been provided as input. The numbers in the string can be so large that they may not be represented by the Java datatype int. The objective is to add the two numbers and output it as a string. You can assume that the numbers are non negative
add(“123456776587789″,”23455876876896987″)=”23579333653484776″ add(“10101″,”20202″)=”30303″ Remove chars that appear again
Given a string as input, remove all chars from the string that appear again. That is, while reading a string if a char has appeared previously it will be removed.
remove(“Hello”)=”Helo” remove(“World”)=”World” remove(“DPMD Jayawardene”) = “DPM Jaywrden”
Module 3 Any century in the match
The scores of all the batsman in a match have been provided as input. Return true if any batsman scored a century (>=100) in the match. century({12,24,98,0,22,11})=false century({65,121,44,23,10,0,9,122})=true Count the number of Evens
Given an array of ints as input, return the number of even ints in it. countEvens({2,51,16,7,20,100}) = 4 countEvens({77,45,107,31}) = 0 countEvens({0,12,24,48,16,16}) = 6 Compute max difference
Given an array of ints as input, compute the difference between the largest and smallest numbers in the array. maxDifference({100,18,12,44,20})=56 maxDifference({100,100,100,100,100,100})=0 maxDifference({0,10,20,30,4})=30 maxDifference({121})=0 String array of numbers
Given a number n as input, return a new string array of length n, containing the strings “0″, “1″, “2″ so on till n-1. If n=0, return an array of length 0.
stringArray(4) = {“0″,”1″,”2″,”3″} stringArray(8) = {“0″,”1″,”2″,”3″,”4″,”5″,”6″,”7″} stringArray2) = {“0″,”1″} Matching marks
You have been given the scores of two students in different subjects. Count the number of times the difference in their marks for the same subject is less than 10. matchMarks({87,75,88,91},{89,78,68,95}) = 3 matchMarks({100,80,79,88,92},{89,78,68,95,78})=2 Sum of digits of numbers
Given an array of ints as input, return the sum of the digits of all the numbers in the array. sumDigits({11,22,33,44})=20 sumDigits({10001})=2 sumDigits({8,6,500})=19 More 6′s than 4′s
Given an array of int s as input, return true if the number of 6′s (sixes) is greater than the number of 4′s (fours). more6Than4({6,6,6,4,4,4,6}) = true
more6Than4({2,3,5,7,9,11}) = false more6Than4({4,4,4,6,6}) = false Paired number
Define a number x as “paired” in an array, if for every two adjacent elements in the array, at least one of them is x. For e.g. in the array {1,2, 1,4}, the adjacents are (1,2), (2,1) and (1,4) and 1 is present in each
of them. Hence x is a “paired” number for the input array. Given an array of int s and x as input, return true if x is a “paired” number for the input array. isPaired({1,2,1,4},1) = true isPaired({1,2,1,4,5,1},1) = false isPaired({1,1,1,1,10,1,20,1},1) = true Multiple Choice Questions
You have been given two string arrays as input, ke y and answers. The “key” array contains the correct
answers of an examination, like {“a”,”b”,”d”,”c”,”b”,”d”,”c”}. The “answers” array contains the answers that a student has given. You can assume that the student has answered all the questions. While scoring the examination, a correct answer gets +3 marks while an incorrect answer gets -1 marks. Calculate the score of the student.
studentScore({“a”,”b”,”d”,”c”,”b”,”d”,”c”},{“a”,”b”,”b”,”c”,”a”,”d”,”b”}) = 9 (4 are correct and 3 are wrong) studentScore({“c”,”b”,”d”,”c”},{“a”,”d”,”b”,”a”}) = -4 Shift array elements
Given a array of chars as input, return an array where the elements have been “left shifted” by one, i.e. {„b‟,'c‟,'d‟,'e‟} becomes {„c‟,'d‟,'e‟,'b‟}. Note that you should not create a new array and only modify the given input array.
shiftChars({„a‟,'b‟,'c‟,'d‟,”e‟})=({„b‟,'c‟,'d‟,”e‟,'a‟}) shiftChars({„$‟}) = {„$‟}; shiftChars({‟9′,‟1′}) = {‟1′,‟9′} Count strings of size
You have been given an array of strings and an int size as input. Return the number of strings in the input array which have the length as size.
stringsOfSize({“A”,”BC”,”DEF”,”GHI”},1) = 1 stringsOfSize({“A”,”BC”,”DEF”,”GHI”},3) = 2 stringsOfSize({“A”,”BC”,”DEF”,”GHI”},4) = 0 Generate FizzBuzz
You have been two ints, n1 and n2 as input. Return a new String[] containing the numbers from n1 to n2
as strings, except for multiples of 3, use “Fizz” instead of the number, for multiples of 5 use “Buzz”, and for multiples of both 3 and 5 use “FizzBuzz”. generateFizzBuzz(2,8) = {“2″,”Fizz”,”4″,”Buzz”,”Fizz”,”7″,”8″} generateFizzBuzz(10,16) = {“Buzz”,”11″,”Fizz”,”13″,”14″,”FizzBuzz”,16} Similar strings
You have been given 2 arrays of strings as input arr1 and arr2. Both arr1 and arr2 have the same length. Compare the string at index i in arr1 with the string at index i in arr2. If the first 3 chars of the two strings
are the same, they are called “similar”. If the length of any one of the strings is less than 3, then the
strings cannot be similar. Count the number of similar strings in the input. Note that the ith string in arr1 is compared only with the ith string in arr2.
countSimilar({“aaa”,”bbb”,”ccc”},{“aaa”,”bb”,”ccd”}) = 2 countSimilar({“aaadefghi”,”bbbcdr”},{“aaaqwerty”,”bbcdr”}) = 1 Split into two
Given an array of ints as input, return true if it is possible to split the array into two so that the sum of the numbers on the lefy is equal to the sum of the numbers on the right. canSplit({10,11,12,5,4}) = true (can split after index 1 as 10+11 = 12+5+4) canSplit({1,3,5,-3,-5,2,-1,0,1,-1}) = true (can split after index 4 as 1+3+5+(-3)+(-5)=2+(-1)+0+1+(-1)) canSplit({10,11,12,5,4,20}) = false Create Domino
Given and int n as input where n>=0, create an array with the pattern {1,1,2,1,2,3,… 1,2,3..n}. domino(1) = {1} domino(2) = {1,1,2} domino(3) = {1,1,2,1,2,3} domino(4) = {1,1,2,1,2,3,1,2,3,4} Reverse an array
Given an array of integers as input, output an array which has the elements in reverse order. reverse({1,2,3,4})={4,3,2,1} reverse({8,10,12,-8,-10})={-10,-8,12,10,8} Dry run – Array Passing(1)
DryRun_ArrayPassing Similar 3
Given an array of ints as input, find out if the array contains either 3 even or 3 odd numbers which are all next to each other. similar3({2,1,3,5,4,8,11}) = true // 1,3,5 – 3 odd numbers are next to each other similar3({10,15,20,25,30,36,40,45}) = true // 30,36,40 – 3 even numbers are next to each other similar3({11,31,51}) = true similar3({1,3,2,4,5,7,6,8}) = false Consecutive 4
Given an array of ints as input, find out if the array contains, 4 consective numbers together like 2,3,4,5 or 33,34,35,36. consecutive4({1,2,4,8,11,12,13,14,15,20,21}) = true // 11,12,13,14 are 4 consective numbers that appear together consecutive4({3,5,7,9,11,12,13,16,20}) = false consecutive4({10,9,8,7,6,5}) = false Move even numbers to the front
Given an array of ints as input, return an array that contains the same numbers as that in the input array, but rearranged so that all the even numbers are in front and the odds numbers are at the back. Note that the order of the even numbers and odd numbers should be maintained i.e. if an even number n1 that appears before an even number n2 in the input, then in the output array n1 should appear before n2. The
same is true for odd numbers. Also note that in this problem you should not create any new array. evenInFront({1,2,3,4,5,6,7,8,10,12}) = {2,4,6,8,10,12,1,3,5,7} evenInFront({2,1,2,1,2,1}) = {2,2,2,1,1,1} evenInFront({10,8,20,4,24}) = {10,8,20,4,24} evenInFront({5,3,7,1}) = {5,3,7,1} Count same numbers
You have been two arrays of ints as input. Both the arrays are sorted in ascending order. Return the number of distinct ints that appear in both the arrays. You need to solve it in a single pass over both the arrays. sameNumbers({1,2,4,8,16,32,64},{2,2,2,4,4,4,6,8,10,12,14,28,32})=4 sameNumbers({1,3,5,7,9,11},{2,3,4,5,5,6,6,7,7,13,15})=3 Array2 in Array1
Given two arrays of ints sorted in ascending order, arr1 and arr2, return true if all of the numbers in arr2 are there in arr1. Note that you can assume that arr1 has only distinct values. You should solve it in a single pass of both arrays, by taking advantage of the fact that the arrays are already sorted in ascending order. Single pass means that you have only one loop (which is not nested) where you looking at the elements of the array. hasInside({1,2,3,4,5,6,7}, {2,4,6}) = true hasInside({1,2,3,4,5,6,7}, {2,4,6,8}) = false Count clusters
You have been given an array of Strings as input. Define a “clusters” in an array as a series of two or more adjacent elements with the same value. The objective is count the number of “clusters” in the given array.
clusters({“India”,”USA”,”USA”,”India”,”India”,”UK”}) = 2 (first cluster is “USA”,”USA”, second cluster is “India”,”India”) clusters({“India”,”USA”,”USA”,”USA”,”India”,”USA”,”USA”,”India”,”UK”}) = 2 (first cluster is “USA”,”USA”,”USA” second cluster is “USA”,”USA”) clusters({“111″,”111″,”111″,”111″,”111″,”111″}) = 1 Join n alphabets
You have been two arrays of strings as input. In both the arrays, each element is a lower case alphabet. Also the elements of both the arr ays are in alphabetical order. You have also been provided an int n as input. Return a new string array containing n elements which have been picked from the initial elements of arr1 and arr2. Also the output array should be sorted in alphabetical order.
joinAlphabets({“a”,”c”,”x”}, {“b”,”f”,”w”}, 3) = {“a”,”b”,”c”} joinAlphabets({“a”,”c”,”y”}, {“c”,”f”,”t”}, 3) = {“a”,”c”,”c”}
joinAlphabets({“f”,”g”,”z”}, {“c”,”f”,”g”}, 5) = {“c ”,”f”,”f”,”g”,”g”} Join n alphabets (no duplicates)
You have been two arrays of strings as input. In both the arrays, each element is a lower case alphabet. Also the elements of both the arr ays are in alphabetical order. You have also been provided an int n as input. Return a new string array containing n elements which have been picked from the initial elements of arr1 and arr2. Also the output array should be sorted in alphabetical order and should not have
duplicates.
joinAlphabets({“a”,”c”,”x”}, {“b”,”f”,”w”}, 3) = {“a”,”b”,”c”} joinAlphabets({“a”,”c”,”y”}, {“c”,”f”,”t”}, 3) = {“a”, ”c”,”f”} joinAlphabets({“f”,”g”,”t”,”u”}, {“c”,”f”,”g”,”u”}, 4) = {“c”,”f”,”g”,”t”} Dry run – Array Passing (2)
DryRun_ArrayPassing_2 Any duplicates in array
Given an array of integers, check whether any number has been repeated in the array. That is, whether the array has any duplicates. anyDuplicates({1,2,3,4})=false anyDuplicates({11,22,33,44,22)=true Append two array’s
Given two arrays, arr1 and arr2 as input, return an array which has the values of arr1 followed by those of arr2. join({1,14,15,2,3},{20,30,40,30,20}) = {1,14,15, 2,3,20,30,40,30,20} Form largest number
An array of size 10 has been provided as input. Assuming that the value of array at index i, denotes the number of times digit i can be used, the objective is to form the largest possible number using all the digits.
form({1,2,3,4,5,6,1,2,3,4})=”9999888776555555444443333222110″ form({1,1,1,1,1,1,1,1,1,1})=”9876543210″ Is the array of numbers sorted
Given an array of integers as input, return true if the array is sorted. Note that the array can be sorted in either ascending or descending order. isSorted([1,3,5,7})=true isSorted({11,9,2,-5})=true isSorted({1,2,3,4,-1,-2})=false Remove Zeros
Given an array of integers return an array in the same order with all 0's removed. remove({1,2,3,4,5,0,1,2,0,0,2})= {1,2,3,4,5,1,2,2} remove({0,0,1,2})={1,2}remove{0,0,0,0}={} Third largest number in array
Given an array of integers, find out the third largest value in the array thirdLargest{0,21,19,0,17,15,0,11,908,4,299,110}=110 Remove all 3s
Given an array on numbers as input, remove all elements from the array which are either multiple of 3 or have the digit 3 in them. For e.g. 13 and 15 will be both removed from the array if they are present. remove({21,19,17,23,15,11,8,4,31})={19,17,11,8,4} Array of digits in string
Given a string which contains a number as input, the objective is to create an array arr, such that arr[i] represents the number of times the digit i appeared in the string. Note that the maximum value of i in arr[i] will be 9 as the digits are 0,1,2,3,4,5,6,7,8,9.
getDigitArray(“9988776655″)={0,0,0,0,0,2,2,2,2,2} getDigitArray(“123456789013579″)={1,2,1,2,1,2,1,2,1,2} Dry run – 2D array
DryRun2DArray Largest number in 2D array
Given a 2D array consisting of ints as input, return the largest int in it. largestIn2D({{1,2,3},{4,6,8},{3,5,7},{1,4,0}}) = 8 Matrix Addition
Given two matrices M1 and M2, the objective to add them. Each matrix is provided as an int[][], a 2 dimensional integer array. The expected output is also 2 dimensional integer array. Words to 2D chars
Given a para of words (separated by space), create a 2D array where each array in it represents the word. Note that the words are of the same size.
to2DChars(“bat sat put mat”) = {{„b‟,'a‟,'t‟},{„s‟,'a‟,'t‟},{„p‟,'u‟,'t‟},{„m‟,'a‟,'t‟}} to2DChars(“hi is to”) = {{„h‟,'i‟},{„i‟,'s‟},{„t‟,'o‟}} Compute mid value of array
Given an integer array with odd number of values, find out the value of the middle number if the array was sorted. For e.g. if the length of array is 11, the value of the 6th element when sorted needs to be found. Note that whether the array is sorted in ascending or descending order, the middle element will remain the same. midNumber({2,4,6,8,10,1,3,5,7,9,0})=5 Remove duplicates from array
Given an array of numbers as input, return an array with all the duplicate values removed. remove({1,2,3,4,0,1,4,3,2)}={1,2,3,4,0} Most frequent digit
Given a number, the objective is to find out the most frequently occuring digit in the number. If more than 2 digits have the same frequency, return the smallest digit.
getFreqDigit(“9988776655″)=5 getFreqDigit(“127341743217″)=1 Split array into two
Given an array of numbers as input, return true if it can be split at a point such that the sum of the two parts is equal. canSplit({1, 1, 1, 2, 1,3,4,5,3,4,1})=true canSplit({1,2})=false Dry run – Array Passing (3)
DryRun_ArrayPassing_3 Join 2 sorted arrays
Given two arrays, arr1 and arr2, that have been sorted in descending order, output an array which appends the values from both arr1 and arr2 while being sorted in descending order. join({21,19,17},{111,21,10})={111,21,21,19,17,10}
Array of factors
Given a number n as input, return an array consisting of all the factors of n. The factors should be in ascending order. Note that 1 and n are also factors of n. getFactors(967)={1,967} getFactors(1440)={1,2,3,4,5,6,8,9,10,12,15,16,18,20,24,30,32,36,40,45,48,60,72,80,90,96,120,144,160,1 80,240,288,360,480,720,1440} All primes between
Given two numbers n1 and n2 as input, return an array containing all the primes between n1 and n2 (Note that both n1 and n2 can be included in the array if they are prime). Also, the primes in the array need to be in ascending order. getPrimes(967,1041)={967,971,977,983,991,997,1009,1013,1019,1021,1031,1033,1039} getPrimes(6,11)={7,11} Array contains the other
Given two arrays outer and inner as input, determine whether the outer array contains all the values of inner array. Both the arrays, outer and inner, are sorted in the same order. That is, if outer is sorted in ascending order, inner will also be sorted in ascending order. Note that this problem has to be solved without visiting the value of anu element of either array more than once. contains({2,4,6,7,10},{6,7}) = true contains({40,30,20,10,-10},{40,20,10,4}) = false Word Puzzle – Up, Down, Left, Right
A rectangular grid of words has been laid out before you. Also provided is a list of words to find in t he grid. Your job is to find which of these words appear in the grid. The words can appear in a straight line (left, right, up or down). For e.g. if the grid of words is E L P P AR A E V VX Y A X WM U C L OG I H S A
and the list of words is “APPLE,BANANA,GUAVA,PEACH,PEAR,PLUM”, the words APPLE and PEACH can be found in the grid.The grid is provided as a 2 dimensional array of char like
{{„E‟,'L‟,'P‟,'P‟,'A‟},{„R‟,'A‟,'E‟,'V‟,'V‟},{„X‟,'Y‟,'A‟,'X‟,'W‟},{„M‟,'U‟,'C‟,'L‟,'O‟},{„G‟,'I‟,'H‟,'S‟,'A‟}} and the list is provided like a string of comma demarcated words like “APPLE,BANANA,GUAVA,PEACH,PEAR,PLUM”. The output is a string which contains the words found in the grid in the same order as they appear in the
list. In this example the output will be “APPLE,PEACH”. Multiply large numbers
The objective of this exercise is two multiply any 2 numbers. The numbers can be extremely large (i.e. run into hundreds of digits) and are provided as strings. The expected output is a string which represents the product of the two numbers.
multiply(“268435456″,”524288″)=”140737488355328″ multiply(“12321412423524534534543″,”0″)=”0″
Module 4a Create a class TwoDPoint
Create a class TwoDPoint that contains two fields x, y which are of type int. Define another class TestTwoDPoint, where a main method is defined. The main method should create two TwoDPoint objects, assign them values 2,2 and 3,3 and print them. TwoDPoint-2
Adding to the previous problem, m odify the class TestTwoDPoint and add a function to it. This function takes two ints as input and returns a TwoDPoint. TwoDPoint-3
Adding to the previous problem, m odify the class TestTwoDPoint and add another function to it. This function takes two TwoDPoints as input and returns the TwoDPoint that is farthest from the point (0,0). TwoDPoint-4
Adding to the previous problem, m odify the class TestTwoDPoint and add another function to it. This function takes two TwoDPoints as input and returns a new TwoDPoint whose x value is the sum of x
values of the input TwoDPoint‟s and whose y value is the sum of the y valaues of the input TwoDPoint‟s. Create a class Student
Create a class Student that contains the following fieldds – name (of type string), marks(of type int[]). Define another class TestStudent, where a main method is defined. The main method should creates a
Student object with name as “Bill” and marks as {88,92,76,81,83} and print it. Student-2
Adding to the previous problem, m odify the class TestStudent and add a function t otalMarks(Student st). This function takes a Student as input and returns the total marks of the student. Student-3
Adding to the previous problem, m odify the class TestStudent and add a function betterS tudent(Student
st1, Student st2). This function takes two Student‟s as input and returns the Student with the higher total marks. Student-4
Adding to the previous problem, m odify the class TestStudent and add a f unction createStudent(String nameStr, String marksStr). This function creates and return a new Student. The name of the new Student is nameStr and the marks are determined from comma separated string marksStr. For e.g. marksStr can
be “68,72,76,81,73″. Student-5
Adding to the previous problem, m odify the class TestStudent and add a function displa y(Student st). This function takes a Student as input and prints it. Dry run – Objects(2)
DryRunObjects_1_2 Create a class Rectangle
Create a class Rectangle that contains the following fields – length(of type int), breadth(of type int).
Define another class TestRectangle, where a main method is defined. The main method should creates a Rectangle object with length = 10 and breadth = 20 and print it. Rectangle-2
Adding to the previous problem, m odify the class TestRectangle and add a function createSt udent(int ln, in br). This function creates and return a new Rectangle. Rectangle-3
Adding to the previous problem, m odify the class TestRectangle and add a function computeArea(Rectangle rect). This function returns the area of the Rectangle rect. Also add another function computePerimeter(Rectangle rect) which returns the perimeter of the Rectangle rect Rectangle-4
Adding to the previous problem, m odify the class TestRectangle and add a function createRectangles(int[] lengths, int[] breadths). This function returns an array of Rectangle (Rectangle[]) which corresponds to the lengths and breadths being input. Note that the length of both the input arrays is the same and you will create the same of the new Rectangle. Rectangle-5
Adding to the previous problem, m odify the class TestRectangle and add a f unction largestPerimeter(Rectangle[] rects). This function returns the Rectangle with the largest perimeter in the input rectangles. Rectangle-6
Adding to the previous problem, m odify the class TestRectangle and add a function largestArea(Rectangle[] rects). This function returns the Rectangle with the largest area in the input rectangles. Dry run – Objects(3)
DryRunObjects_1_3 DryRunObjects_1_4 Create a class Circle
Create a class Circle that contains the following field – radius(of type int). In the class Circle, also define the following methods - area : which returns the area of the circle. Assume pi = 3.14 - perimeter : which returns the perimeter of the circle. Define another class TestCircle, where a main method is defined. The main method should create a Circle object with radius = 5 and display the area and perimeter of the circle. Note that in calculating the area and perimeter use the corresponding methods defined in Circle class. Circle – 2
Adding to the previous problem, Modify the class TestCircle. Add to it a function largerCircle(Circle circle1, Circle circle2), which returns the Circle with the larger area. Note that while calculating the area, you have to use the method defined in Circle class. Create a class Result
Create a class Result that contains the following fields – marks(of type int[]). The int[] marks contains the marks obtained by a student in the various examinations that were conducted. In the class Result also define the following functions
- maxMarks : which returns the maximum marks scored (it is the maximum value in the int[] marks). - avgMarks : whichs returns the average marks scored in the exams. - totalMarks : whichs returns the total marks scored in the exams. Also define the class TestResult in which there is function which created a new Re sult and displays the values of max marks and average marks. Note that for calculating max marks and average marks, you should use the methods defined in the class Result. Result – 2
Adding to the previous problem, Modify the class TestResult. Add to it a function betterResult(Result res1, Result res2), which returns the better Result. Better result is defined as the result the higher total marks. If total marks are the same, then it is the one with the higher maximum marks. Note that while calculating total marks, you have to use the method defined in the Result class. Result – 3
Adding to the previous problem, Modify the class TestResult. Add to it a function bestResult(Result[] results), which returns the best Result. The best result is defined as the result with the highest average marks. Note that while calculating average marks, you have to use the method defined in the Result class. Also, you can assume that no two results have the same average marks. Create the classes Item and ShoppingCart
Create a class Item which refers to an item in the shopping cart of an online shopping site like Amazon. The class Item has the fields name (of type String), productId (of type String), price (of type double), quantity (of type int), amount (of type double). The field amount is calculated as price * quantity. Also define a class ShoppingCart which r efers to the shopping cart of a custom er at Amazon. The class ShoppingCart has the fields items (of type Item[]), totalAmount (of type double). Also define a class TestCart which has a f unction makeCart(String[] it emData) which takes the information about the shopping cart of a customer as input and returns an object of type ShoppingCart.The input String[] items, consists of an array of String where each String provides
information on an item in the manner “name,id,price, quantity”. For e.g. it can be “Colgate,CP10023,54.50,3″ where Colgate is the name, CP10023 is the product id, 54.50 is the price and 3 is the quantity. Note that the ShoppingCart object returned should have the correct totalAmount and each Item in it should the correct amount. ShoppingCart-2
Modify the class ShoppingCart. Add to it the method addItem(Item item) which takes an Item as input and adds it to the field items. The way we add it is that if the customer has already added that product id to the cart earlier, only the quantity is modified and increased to reflect the new purchase. If the item was not present, then the it id added to the field items. Remember that if the field items can also be null. Also the field totalAmount should reflect the correct value. Also add the method removeItem (String productId) which takes a productI d as input removes the item with that product id from the cart. Also the field totalAmount should reflect the correct value. Create the classes Section and Student
Create a class Student which has the following fields name (of type String), marks (of type int[]), overallGrade (of type char). All the marks are out of 100, and grades are assigned on the following basis : >=85% (A grade), 70%-85% (B grade), 55%-70% (C grade), 40%-55% (D grade), <40% (F grade).
Also define a class Section which has the f ollowing fields students (of t ype Student[]), numOfA (of type int), numOfF (of type int), highestTotal (of type int). numOfA refers to the number of students in the section who got A grade. numOfF refers to the number of students who got F grade. highestTotal refers to the highest total marks achieved by a student in the section. Also define a class TestSection which has a funct ion makeSection(String[] studentsData) which takes the information on students as input and returns an object of type Section. Each element of the input String[] studentsData consists of a String of the form "Jack:88:92:76:90:66" where Jack is the name of the student and 88,92,76,90 and 66 are the marks. Note that in the Section object that is returned by the function makeSection, all the fields of Section should be correctly updated. Also, all the fields in each Student in the Section object should be properly updated. Bowler and BowlerList
Define the following classes Class Bowler which has the fields name(String), overs (int), maidens (int), runs (int), wickets (int). Class BowlerList which has the field bowlers(of type Bowler[]). The class also has the following functions
– totalOvers() – returns the total number of overs bowled by all the bowlers. – totalRuns() – returns the total number of runs conceded by all the bowlers. – totalWickets() – returns the total number of wickets taken by all the bowlers. – economyRate() – returns a double calculated as total runs conceded divided by total overs bowled – wickets(String bowlerName) – returns the number of wickets taken by the bowler whose name is specified as parameter. If the name does not exist it is 0. Class TestBowler which has a function makeBowlers(String[ ] bowlerData). The String[] is like {“Zaheer 10-1-55-0″,”Ishant-8-0-72- 0″,”Jadeja-10-2-34-2″}, where each String like “Zaheer -10-1-55-0″ means Name-Overs-Maidens-Runs-Wickets. Reading Links – Defining constructors for Objects and Classes
Providing Constructors for Your Classes Passing Information to a Method or a Constructor Reading links :Using objects
Objects Creating Objects Using Objects Using the this Keyword Dry Run – Object (Constructors)
DryRunObjects_2 Add a constructor to TwoDPoint
Modify the class TwoDPoint defined earlier and add a constructor that takes two parameters. Add a constructor to Student
Modify the class Student defined earlier and add a constructor that takes two parameters of type String and int[]. Also define a constructor that takes no parameters. Add a constructor to Rectangle
Modify the class Rectangle defined earlier and add a constructor that takes two parameters – length and breadth. Define a constructor that takes no parameters and initializes the rectangle values to 0.
Add a constructor to Item and ShoppingCart
Modify the solution of problem Item and ShoppingCart to add constructors. In the class Item add a constructor that takes the requisite parameters as input and also computes and sets the field amount. In the class ShoppingCart add a constructor which takes a String[] itemData as input. This input is similar to the parameter itemData provided to the function makeCart in the class TestCart.
Module 4b Reading Links : Class Diagrams
A class diagram is a type of static structure diagram that describes t he structure of a system by showing
the system‟s classes, their attributes, operations (or methods), and the relationships among the classes. The following reading links provide insights into class diagrams. Class Diagram UML basics: The class diagram Create class Shape with member color
Create a class Shape that has member color indicating color of shape. Extend Shape to create Square, Circle, Rectangle. Also, draw the class diagram. Create class FourDimensionalShape
Create a class FourDimensionalShape that extends Shape and has four corners. Extend it to create Square and Rectangle class. Put a print in every constructor of each class – what is the result? Also, draw the class diagram. Create class Vehicle
Create a class Vehicle with the fields type (String), color (String), tyres (int). Extend Vehicle to create the
class Car which always has 4 tyres and the type = “car”. Car has the additional fields brand (String), fuel (String). Also, extend Vehicle to create the class Cycle which has always has 2 tyres and the type =
“cycle”. Cycle has the additional fields, hasGears (boolean). Dry runs for Objects – Inheritance (2)
DryRunInheritance2 Shape with calculateArea
Create a class Shape that has a method calculateArea which returns 0. Extend Shape to create Square, Circle, Rectangle which have the corresponding calculateArea method. Also, draw the class diagram. Define Point, 2DPoint, 3DPoint
Define a class Point which has a method distance() which returns the distance of the point from origin. This method in the class Point always returns 0. Define a class 2DPoint which extends Point and represents a point (x,y). The method distance() returns the distance from (0,0).
Define a class 3DPoint which extends Point and represents a point (x,y,z). The method distance() returns the distance from (0,0,0). Note that the classes should have the correct implementation of distance and all the required constructors
Module 4c Implement toString and equals
Implement toString, equals, and hashCode for all classes in the class 2Dpoint which represents a point (x,y). The function toString should represent a String representation of the 2DPoint. The function equals
should return true if two 2Dpoint‟s represent the same point. In the main class, create two 2DPoints. Pass them to a function that takes Objects as input and see if you can invoke the toString and equals correctly. Reading links : Abstract Classes
Abstract Methods and Classes Dry run – Abstract Class
DryRunAbstract Abstract class – Shape
Define the class Shape (as specified in the problem above) as an abstract class. Define the sub-classes Square, Circle and Rectangle. See what changes are required to make the code work. Dry run – Interface
DryRunInterface Reading docs – Interfaces
The following are the reading links for Interfaces Interfaces Defining an Interface Implementing an Interface Using an Interface as a Type Rewriting Interfaces Summary of Interfaces Reading doc : Abstract class vs Interface
Abstract Classes vs Interfaces Create an interface Measurable
Create an interface Measurable that has 2 methods – calculateArea and calculatePerimeter. Define classes Square, Rectangle and Circle that implement Measurable. Note that the classes Square, Rectangle and Circle do not extend Shape. See how you can define Square, Rectangle and Circle as of type Measurable and use it to calculate the area and perimeter.
Reading links : Controlling Access to Members of a Class
Access level modifiers determine whether other classes can use a particular field or invoke a particular method. Reading links : Packages
Creating and Using Packages Creating a Package Naming a Package Using Package Members Managing Source and Class Files Different packages – Shape
Define the class Shape (as specified in the problem above) in a package in.trisect.shapes. Define the sub-classes Square, Circle and Rectangle in a different package in.trisect.shapes.define. See what changes are required to make the code work. Different packages – Person
Define the class Person (as specified in the problem above) in a package in.trisect.person. Define the sub-classes Student and Faculty in a different package in.trisect.college. See what changes are required to make the code work. Different packages – Person
Define the class Person (as specified in the problem above) as an abstract class. Define the sub-classes Student and Faculty. See what changes are required to make the code work. Private data members – Shape
Define a class Shape with the member color and methods getPerimeter, getArea and display. The method display prints the color, perimeter and area. For Shape, the methods getPerimeter and getArea return 0. Extend Shape to Circle, Rectangle and Square. Make the data members of Shape private. Modify your code to get it code working with private data members. Also, draw the class diagram. Private data members – Person
Create a class Person with name, dateOfBirth and a method display which displays all the fields in a single line. Make all the data members private. Extend Person to create Student and Faculty. Student has an additional field collegeName and Faculty has an additional field subject. They also override display method to display all the values in a single line. Modify you code to get it code working with private data members. Also, draw the class diagram.
Module 4d Find best bowler
In a one day international, the bowling figures of all the bowlers have been provided. The organizers have
asked you to help them figure out who bowled the best. The approach is to award points to each bowler and then choose the bowler with the highest points. The points are given for maiden overs, economy and wickets. Each wicket carries 10 points. Each maiden over bowled carries 2 points. A bowler who has conceded lesser runs than what the overall run rate indicates, gets points equivalent to the runs he saved. For e.g. if a bowler bowled 4 overs and conceded 21 runs while the overall runrate was 6.4 runs per over, the bowler will get 4*6.4 – 21 = 4.6 economy points. However, if the bowler bowled 6 over for 45 runs while the overage average was 6.3 gets 6*6.3 – 45 = -7.2 economy points. Note that the overall run rate can be computed by adding the runs and then dividing them by the total number of overs bowled. The input is provided as 2 arrays of the object Bowler. The Bowler object has fields corresponding to name, overs, maidens, runs conceded and wickets. You can download the base classes here. Also draw the class diagram for this problem. Download files for BestBowler Dry run – Vector
DryRunVector Reading links : Vector
Vector – Javadoc Reading links : Integer, Character, Boolean
Integer Character Boolean Words in para
Given a paragraph, return a vector consisting of all the words in the para. The words in the paragraph are
separated by space. If para is “How are you today”, the output vector consists of the words – How, are, you, today Distinct numbers in string
Given a string, return a vector of Integer consisting of all the distinct numbers in the para. The numbers in
the string are separated by space. If para is “88 99 22 33 44 55 88 22 55 100″, the output vector consists of the numbers – 88,99,22,33,44,55,100 Flight Tickets
Given the details of flights as input, create a vector of the object Ticket. Note that the tickets should appear in the vector in the same order as the input. The details have been provided as a String[]. Each item in the array corresponds to a ticket and has the following space separated details: Origin, destination, departure, arrival, amount. For e.g. a string in the
String[] can be “Delhi Mumbai 0700 0920 5850″. Dry run – Pass by reference(2)
DryRunObjects_4_2 Zoo Animals
Given a zoo, the objective is to compute the food requirements of the zoo as well create a count of various animals. All these values are to be stored in the object ZooAnimals. There is a function foodCalc(String[] animalDetails, String[] animalList) in the class ZooFoodSystem which needs to be defined. Note that while returning the object ZooAnimals, all the fields in the object should
have the correct values. The inputs to the function foodCalc are String[] animalDetails : Name, Food type (carnivore / herbivore) and amount of daily food consumption. String[] animalList : List of all animals found in the zoo. An animal will occur as many times in the list as they are in the zoo. The following Java files has been provided as download – Animal, AnimalCount and ZooAnimals. Also draw the class diagrams. Download files for Zoo Animals Billing Counter
The problem here simulates the action of the billing counter of a department store.Two inputs have been provided as String[], master and billscan. The String[] master, contains the following details for each product : code, description, price and applicable discount. The String[] billscan consists of the codes being scanned at the billing counter. Note that billscan can have the same code appear multiple times. The objective is to generate the itemized bill for the billscan provided. The itemized bill is an object of the class ItemizedBill and consists of a Vector of BillItems and the total value of the bill. Each BillItem corresponds to the different products being purchased at the counter. The quantity purchased is reflected in the quantity field of the BillItem. You have been provided the following Java files in the download, Product, ProductMaster, BillItem, ItemizedBill and BillingCounter. Also draw the class diagram for this problem. Download files for Billing Counter NewVector
The objective of this exercise is to implement a class NewVector which has an Object[] as its data member. It behaves like a vector and implements the functions add, size, elementAt, remove and set. Note that in this problem we are not supposed to use vectors. Attendance System
The objective is to compute the weekly salary of all the employees for the week from 01/07 to 05/07. The following has been provided as input: String[] empDetails : consists of Name, Employee Id and Grade for each employee String[] attendanceRecords : Date wise record of all those who reported for work String[] gradeSalary : The grade and the daily salary associated with it String[] medicalLeave : Date wise record of who availed medical leave on that date String[] tourRecords : Date wise record of who was on official tour on that date The objective is to create the correct EmployeeMaster for the 5 days from 01/07 to 05/07. Ensure that all the fields in EmployeeMaster have suitably filled. Note that the salary of a person is computed as follows : for each day on work it as per daily salary defined as per grade. For each day of medical leave it is 80% of grade salary and on tour it is 115% of applicable salary. No salary is paid for days a person is absent without medical leave. Also in the char[] for attendance, the following values are to be used P : Present, A : Absent, M: Medical leave, T: On tour The following Java filed has been provided as download – Employee, Grade and EmployeeMaster. Also draw the class diagrams. Download files for Attendance System
Module 5a Linear Search
Given an array of integers, nums, sorted in ascending order and an integer, number, as input, find out the index of number in the array. You can assume that all the values in the array are unique. If number cannot be found in the array return -1. getIndex({1,3,5,7,9},3)=1 Binary Search
In this problem, we will use binary search. Given an array of integers, nums, sorted in ascending order and an integer, number, as input, find out the index of number in the array. You can assume that all the values in the array are unique. If number cannot be found in the array return -1. getIndex({1,3,5,7,9},3)=1 Insert number correctly
Given an array of numbers of size (n+1) as input, the array consists of n numbers which have been sorted in ascending position. The last position in the array is intended to be empty which is denoted by it having a value -99999. You have also been provided a number n1 which is to be inserted in the array in the correct position. Note that when you insert the number the elements will need to be shifted for which there is a single space in the array. Also, in this problem ensure that a new array is not created. insert({0,3, 6, 9, 12, 15, 18, 21,24,30,-99999},17) = {0,3,6,9,12,15,17,18,21,24,30} Binary Search – Large Numbers
Use binary search to solve the problem. Two inputs have been provided : - An array of String, nums, where each String represents a non negative integer. The integers can be very large and hence have been stored as strings. The array has been sorted in ascending order of the integer value of the strings. - an integer, number Find out the index of number in the array. You can assume that all the values in the array are unique. If number cannot be found in the array return -1.
getIndex({“99″,”99″,”999″,”112343″,”723534″,”18456543876″,”54253445340001″},”723534″)=4 Reading links – Bubble sort
Bubble sort Algorithm Detailed explanation of Bubble sort Bubble sort of numbers
Given an array of integers and a string which has the values “ascending” or “descending” as input, sort them in ascending / descending order as specified by the input string using bubble sort.
bubbleSort({1,4,2,3},”ascending”) = {1,2,3,4} bubbleSort({11,4,8,12} ,”descending”) = {12,11,8,4}
Bubble sort of fn of digits
Given an array of integers and a string which has the values “ascending” or “descending” as input, sort them in ascending / descending order as specified by the input string using bubble sort. Define for num1, a function prod(num1) which is the product of digits of num1 and a function sum(num1) which is the sum of digits of num1. num1 is greater than num2 if - prod(num1) > prod(num2) - prod(num1>=prod(num2) and sum(num1)>sum(num2) - prod(num1)=prod(num2), sum(num1)=sum(num2), and num1>num2.
bubbleSort({18,24,44,8},”ascending”) = {24,8,18,44} bubbleSort({33,19,91,9,133},”descending”) = {91,19,9,133,33} Bubble sort of strings
Given an array of strings as input, sort them in ascending order using bubble sort.
bubbleSort({“hello”,”how”,”are”,”you”,”little”,”angel”} = {“angel”,”are”,”hello”,”how”,”little”,”you”} Bubble Sort – Large Numbers
An array of String, nums , has been provided as input. Each Strin g represents a non negative integer. T he integers can be very large and hence have been stored as strings. The array has to be sorted in ascending order of the integer value of the strings.
bubbleSort({“999″,”723534″,”99″,”18456543876″,”54253445340001″,”99″,”112343″,})={“99″,”99″,”999″,”11 2343″,”723534″,”18456543876″,”54253445340001″} Ranking students in a section
Given the students of a section in a school, the objective is to order the students as per their total marks in descending order. The marks for each student are provided in the object Student, while the object Section represents all the students in the class. If two students have the same total marks, they will be ordered based on their marks in the subjects. The inputs provided are two String[]. The first String[] consists of name of student followed by his/her marks in all the subjects. The second String[] is the list of all subjects. The order of subjects in figuring out the rank in case total marks for two students are identical is the same as the order of the subjects provided in this input. The output is the object Section in which the students in Vector have been ordered on rank. You can download the base classes here. Also draw the class diagram for this problem . Download files for Ranking Students in a section
Module 5b
Sample – Hashtable
The download file provided is a sample of Hashtable. It adds the number names and their numbers to a hashtable and retrieves the values. It also obtains all the keys to create a hashtable where the number is the key and number name is the value. The new hashtable is then used to retrieve the number name of a specified number . Download file De-Duplicate
Given a String array of words as input, remove all duplicates and return a Vector of all the unique strings. Use Hashtable to solve this problem. After solving it, solve the same problem using HashSet instead of Hashtable. Max count of words
Given a String[] of words as input, return a Vector of most frequently occurring words. If only one word has the maximum frequency, the Vector will have a single entry. Use Hashtable to solve the problem. Same Strings (No duplicates)
Given two arrays of Strings, determine if they both contain the same strings. Note that no string will appear more than once in each array. Do not use sorting to solve this problem. Also use HashSet to solve this problem. Max cities
You have been given a Vector as input. Each element in the vector is of type “Country:City”. Find out the country which has the maximum number of cities. You can assume that there is only 1 country with maximum number of cities in the input. Same Numbers , Same Count
Given two arrays of int, determine if they both contain the same numbers. Note that a number can appear more than once in each array. Also note that if a number that is present n times in the first input array, it should be present n in the second input array. And vice-versa, if a number is present m times in the second input array should be present m times in the first input array. Do not use sorting to solve this problem. Use HashMap to solve this problem. Reading Doc – Understanding Java Collections Framework
Introduction Core Collection Interfaces Algorithms in Collections class Javadoc : Collections Reading Doc – Exceptions
The following are the documents to read about Exceptions. Javadoc – Throwable Javadoc – Exception What is an Exception The Catch or Specify Requirement Catching and Handling Exceptions The try Block The catch Blocks The finally Block
Putting It All Together Specifying the Exceptions Thrown by a Method How to Throw Exceptions Creating Exception Classes Advantages of Exceptions Sample – Exceptions
Attached is a sample code, that wi ll provide insight into exceptions. Stud y and understand every concept covered in it. Sample_Exception Shopping System
This problem simulates the functioning of a department store. Product represents all the different products in the department store ProductMaster is the master of all the Product(s) in the department store Scheme represents all the schemes and offers running in the store. They have two fields, quantity and discount. Quantity represents the minimum quantity a shopper needs to purchase to qualify for the discount. ItemizedBill represents the bill of a shopper BillItem represents each line item in the ItemizedBill of the shopper BillingCounter represents all the bills that a billing counter has issued in a day Given the list of products, schemes and the scan details at the billing counter, process the details and return the object BillingCounter. In the scan details that have been provided as input, a bill for a shopper starts with the string START:num where num represents the id of the bill. A bill for a shopper ends with
“STOP”. The following Java filed has been provided as download – Product, ProductMaster, Scheme, BillItem, ItemizedBill and BillingCounter. Also draw the class diagram for this problem. Download files for Shopping System Round robin tournament
A round robin soccer tournament is being played. The objective it to create the points tables based on matches played so far. Note that the points tables in sorted with the team on top coming first in the table. The input is provided as a String[] with each element consisting of 3 space demarcated values – Name of team1, Name of team2 and final scoreline. The scoreline if provided as 2-1 where 2 represents the no. of goals scored by team1 and 1 represents it for team2. The object Match stores all the values for a match. The object PointsTableRow stores the performance of a particular team. It has the following fields – matches played, wins, draw, loss, goalsFor (i.e. goals scored), goalsAgainst (i.e. goals the opposing team scored), points. For each win a the winning team gets 3 pts. In case of draw, both the teams get 1 point each. The Object PointsTable stores all the PointsTableRow in a vector. Note that the expected output is a PointsTable object in which the field table is sorted. The performance of two teams is compared as follows: Team A is better than Team B if A has more points than B. If points are the same, A has a better goal difference (goalsFor – goalsAgainst) than B. If they are same, then A should have scored more goals
than A. The following Java filed has been provided as download – Match, PointsTableRow and PointsTable. Also draw the class diagrams. Download files for Round Robin Reading Doc – Linked List
The following are the documents to read about Linked List. Understanding Linked List Dry Run – Linked List
SampleLinkedList Basic Linked List functions
The objective of this exercise is to implement the class BasicList1 which implements the interface ListInterface. The functions defined in ListInterface are insert, hasElement, elements and length. Note that the function getBasicList has been defined and should not be modified. Download files Basic Linked List functions – 2
The objective of this exercise is to implement the class BasicList2 which implements the interface ListInterfaceAdvanced. The functions defined in ListInterface are insert, hasElement, elements, length, delete and reverse. Note that the function getBasicList has been defined and should not be modified. Download files Count prime nodes
You have been given the head of a linked list as input. Each node of the linked list stores 2 ints, n1 and n2. Define a function that will count all those nodes from the linked list for which at least one of n1 or n2 is a prime number. Sum of neighbours
You have been given the head of a linked list as input. Each node of the linked list has 2 values of type int, myNum and sum3. The field myNum stores the value pertaining to that node. The field sum3 stores the sum of myNum for that node as well as the previous and next node. If the previous or next node is not present, it will only sum the relevant values. In the input linked list, the value of sum3 has not been computed. Define a function that will compute and assign the correct value of sum3 for each node in the linked list. Remove nodes with duplicate chars
You have been given the head of a linked list as input. Each node of the linked list stores a string data. If
the field “data” has any char that is repeated in it, it has to removed from the list. Define a function that will remove all those nodes from the linked list for which the field data has a char that is present more than once in it. Find kth node
You have been given the head of a linked list and an integer k as input. Define a function which returns the kth element from the end of the input linked list in one loop only. You cannot use any collection / array. Also the input linked list should not be modified in any manner. If k is greater than the length of the linked list return null. Loop in list – store node approach
You have been given the head of a linked list input. Find out whether the linked list has a loop in it or not.
The approach to be used is to save all the nodes and check if you find any node that you have already saved. Solve it using vector and then solve it using HashSet. Loop in list – tortoise hare approach
You have been given the head of a linked list input. Find out whether the linked list has a loop in it or not. The approach to be used is to traverse the list using two different speeds simultaneously. In traverse1 (hare) move 2 nodes at an instance, while traverse2 (tortoise) is the normal traversal. If you land on the same node in both the traversals, what does it tell you. Merge linked lists
You have been given the 2 linked lists as input. Both the linked list consist of a data of type int and are sorted in ascending order. The objective is to return a merged Linked List which is also sorted in ascending order. Note that should not create any extra node of the linked list nor use collections or arrays.
More programing exercises Number in words (5 digits)
Given a number as input, write it as it would be written in words. Note that the number can have atmost five digits and is non-negative. Also all the characters in the output should be in lower case and a single space should be there between words.
inWords(12345)= “twelve thousand three hundred forty five” inWords(0) = “zero” inWords(100) = “one hundred” In numerals (max 5 digits)
Given a number written in words, return its equivalent numeric value. Assume that the maximum value of the number is 99999 and that it is not negative.
inNumerals(“sixty five thousand two hundred forty one”)=65241 inNumerals(“four”)=4 Evaluate polynomial (2 variables)
Given a polynomial, compute its value. The polynomial consists of 2 variables x and y and can also have a constant term in it .
evalXY(“-12y^2x^2-4xy- 6x^4y^5+600″,”x=2,y=3″)= -23184 evalXY(“x^2+y^2-4xy+2x+y+10″,”x=2,y=3″)=6 Subtract large numbers
Two strings representing two numbers have been provided as input. The numbers in the string can be so large that they may not be represented by the Java datatype int. The objective is to subtract the two
numbers and output it as a string. You can assume that the first number is larger than the second.< Note that "0012" is not a valid output, "12" is. Do not use BigInteger for solving this problem. Divide large numbers
Two strings representing two numbers have been provided as input. The numbers in the string can be so large that they may not be represented by the Java datatype int. The objective is to divide the two
numbers and output the quotient as a string. Note that “0012″ is not a valid output, “12″ is. Do not use BigInteger for solving this problem. Solve Expression (with multiplication)
Given an arithmetic expression involving numbers and the operators +,- and * solve it. There can also be spaces in the expression which have to be ignored.
solve(“- 4- 12-2*12- 3- 4* 5 “)=-63 Evaluate polynomial (n variables)
Given a polynomial, compute its value. The polynomial can consist of a maximum of 20 variables and can also have constant terms in it .
evalXYZ(“15xyz-2x^2y^3z^4+ab+bc+abc+123″,”x= -2,y=-1,z=1,a=2,b=3,c=4″)=203 evalXYZ(“a^3+d^3+f^3+m^3 -100-200″,”a=2,d=3,f=4,m= -3″)=-228 Is the sum in array
Given an array of positive integers and a number n as input, return true if a possible subset of elements of the array add upto n. If it is not possible return false. This problem can be solved by recursion. The key is to observe that there are only two states associated with a number. Either it will form a part of the group adding to n or it will not. Recursively evaluate if the number can lead to the sum n and also recursively evaluate if not choosing number can lead to the sum n. hasSum({2,4,8,10},14)= true (4+10 = 14) hasSum({2,3,4,8,9,10},16)= true (3+4+9 = 16) hasSum({2,4,8,10,12},15)= false Is the sum in array (with values)
Given an array of positive integers and a number n as input, return a possible subset of elements of the array that add upto n. If it is not possible return null. This problem can be solved by recursion. The key is to observe that there are only two states associated with a number. Either it will form a part of the group adding to n or it will not. Recursively evaluate if the number can lead to the sum n and also recursively evaluate if not choosing number can lead to the sum n. sumNumbers({2,4,8,10},14)={2,4,8} sumNumbers({2,4,8,10,12},15)=null Is the sum in array (values of all solutions)
Given an array of positive integers and a number n as input, return all the possible ways in which the elements of the array can add upto n. Each such possibility is returned as a String of comma(,) separated values and all the values are returned as a String[]. If it is not possible return null. This problem can be solved by recursion. The key is to observe that there are only two states associated with a number. Either it will form a part of the group adding to n or it will not. Recursively evaluate if the