TrisectSolvedAll Java Prorgams
TrisectSolvedAll Java Prorgams
Module 1 - A Trisect All Modules Programs with Output JAVA for Interview
/*
RunsInSeries
*
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.
*/
package module1a;
/*AddTwoNums
*/
package module1a;
}
}
/*
SecondToHours
Given the time in number of seconds, find out how many hours have been completed
*/
package module1a;
/*
HundredsDigit
Given a 4 digit number as input, find the value of its hundreds digit.
*/
package module1a;
public class HundredsDigit
{
public static void main(String[] args)
{
HundredsDigit obj=new HundredsDigit();
int result=obj.hundredsDigit(456896327);
System.out.println(" 100 place digit number is : = " + result);
}
public int hundredsDigit(int num)
{
int a=num/100 ;
return a%10;
}
/*
RequiredRunRate
A team is chasing the target set in a one day international match. The objective is to
compute the required run rate.
* The following have provided as input: target, maxOvers, currentScore, oversBowled
*/
package module1a;
}
public double runrateRequired(int target,int maxOvers, int currentScore, int
oversBowled)
{
double remainOvers=maxOvers - oversBowled;
double remainScore=target - currentScore;
double totalrunrate=(remainScore/remainOvers);
return totalrunrate;
/*
Make3Digit
Given a digit as input, create a 3 digit number in which all the digits are the same as
the input digit.
*/
package module1a;
import java.util.Scanner;
int digit=num1*100+num1*10+num1*1;
System.out.println("Three digit number is = "+digit);
/*
MakeDecimal
Given 3 digits a,b and c as input, return a double of the form a.bc
*/
package module1a;
public class MakeDecimal
{
public static void main(String[] args)
{
MakeDecimal obj=new MakeDecimal();
double result=obj.makeDecimal(4,8,1);
System.out.println("Make 3 digit number is = " +result);
}
public double makeDecimal(int a, int b, int c)
{
double mkDecimal=((a*100)+(b*10)+(c*1))/100.0;
return mkDecimal;
}
/*
Sum2Digit
Given a 2 digit number as input, compute the sum of its digits. Assume that the
number has 2 digits.
*/
package module1a;
int result1=obj.sumTwoDigit(10);
System.out.println("sum of two digit no is = " +result1);
int result2=obj.sumTwoDigit(13);
System.out.println("sum of two digit no is = " +result2);
int result3=obj.sumTwoDigit(19);
System.out.println("sum of two digit no is = " +result3);
int result4=obj.sumTwoDigit(67);
System.out.println("sum of two digit no is = " +result4);
}
public int sumTwoDigit(int n)
{
int digit=0;
digit=n/10+n%10;
return digit;
/*
AndBooleans
Given three booleans as input, return the and of the all three booleans
*/
package module1a;
}
public boolean andBooleans(boolean bool1, boolean bool2, boolean bool3)
{
if(bool1 && bool2 && bool3)
return true;
else
return false;
}
}
/*
LargerThanOne
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.
*/
package module1a;
import java.util.Scanner;
/*
NumberInAscendingOrder
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.
*/
package module1a;
import java.util.Scanner;
/*
SumOf4Digits
Given a number as input, compute the sum of its last 4 digits. Assume that the number
has at least 4 digits.
*/
package module1a;
import java.util.Scanner;
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.
*/
package module1a;
import java.util.Scanner;
}
public double areaOfSquare(int x1, int y1, int x2, int y2)
{
return (Math.pow((x1-x2),2)+Math.pow((y1-y2),2))/2;
}
}
/*
AddDigitNumbers
Problem Statement
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.
*/
package module1a;
import java.util.Scanner;
}
public int add3To4(int digit1,int digit2,int digit3)
{
int sum1,sum2,sum3;
int totalSum=0;
sum1=digit1*1000+digit1*100+digit1*10+digit1;
sum2=digit2*1000+digit2*100+digit2*10+digit2;
sum3=digit3*1000+digit3*100+digit3*10+digit3;
totalSum=sum1+sum2+sum3;
return totalSum;
}
/*
SecondsToTime
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.
*/
package module1a;
}
Module 1 - B
/*
AddForThird
Given three numbers a, b and c, return true if the sum of any two equals the third
number.
*/
package Module1b;
import java.util.Scanner;
}
}
/*
ArithmeticOps
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.
*/
package Module1b;
import java.util.Scanner;
}
public int compute(int a, int b, char operator)
{
switch(operator)
{
case '+': return a+b;
case '-': return a-b;
case '*': return a*b;
case '/': return a/b;
case '%': return a%b;
default :
return 0;
}
}
/*
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.
*/
package Module1b;
import java.util.Scanner;
}
public int calculateBlackjack(int num1, int num2)
{
if(num1<=21 && num2<=21)
{
if(num1>num2 && num1!=num2)
return num1;
if(num2>num1 && num1!=num2)
return num2;
if((num1==num2) || (num1<21 && num2<21) || (num1==21 && num2==21))
return -2;
}
else if(num1>21 && num2>21)
{
return -1;
}
else if((num1<21 && num2>21) || (num2<21 && num1>21))
{
if(num1<num2)
return num1;
else
return num2;
}
return 0;
/*
ChangeCharCase
Given a char as input, if it is an alphabet change its case otherwise return it as it is.
*/
package Module1b;
import java.util.Scanner;
}
public char changeCase(char ch)
{
if(ch>='A' && ch<='Z')
ch+=32;
else if(ch>='a' && ch<='z')
ch-=32;
return ch;
/*
ComputeGrade
Problem Statement
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.
*/
package Module1b;
import java.util.Scanner;
}
public char isComputeGrade(int marks1,int marks2, int marks3, int marks4, int
marks5)
{
int percentage=(marks1+marks2+marks3+marks4+marks5)*100/500;
if(percentage>=85)
return 'A';
else if(percentage>=75)
return 'B';
else if(percentage>=60)
return 'C';
else if(percentage>=45)
return 'D';
else if (percentage>=33)
return 'E';
else
return 'F';
}
/*
ConsecutiveCentury
Given the scores of a batsman in four innings, return whether he scored at least two
centuries or not.
*/
package Module1b;
import java.util.Scanner;
}
public boolean isConsecutiveCentury(int score1, int score2, int score3, int score4 )
{
if((score1>=100 && score2>=100) || (score3>=100 && score4>=100)
||(score3>=100 && score1>=100) || (score2>=100 && score4>=100))
return true;
else
return false;
/*
DaysInMonth
Given the number of the month in 2013 (1 for January, 12 for December), return the
number of days in it.
*/
package Module1b;
import java.util.Scanner;
}
public int numOfDays(int month)
{
switch(month)
{
case 1: return 31;
case 2: return 28;
case 3: return 31;
case 4: return 30;
case 5: return 31;
case 6: return 30;
case 7: return 31;
case 8: return 31;
case 9: return 30;
case 10: return 31;
case 11: return 30;
case 12: return 31;
default:
return 0;
}
}
}
/*
Diff25
Given three ints as input , return true if one of them is 25 or more less than one of the
other numbers.
*/
package Module1b;
import java.util.Scanner;
}
public boolean checkDiff25(int a, int b, int c)
{
int x=a-b;
int y=b-c;
int z=c-a;
if(x>=25 || y>=25 || z>=25 || x<=(-25) || y<=(-25) || z<=(-25))
return true;
else
return false;
}
/*
IsDigit
Given a char as input, return true if it is a digit (i.e. between 0 to 9).
*/
package Module1b;
import java.util.Scanner;
}
public boolean isDigit(char ch)
{
if(ch>='0' && ch<='9')
return true;
else
return false;
}
/*
LargestOfThree
import java.util.Scanner;
/*
LeapYear
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.
*/
package Module1b;
import java.util.Scanner;
}
public boolean isLeapYear(int year)
{
if((year%400==0 || year%100!=0) && (year%4==0))
return true;
else
return false;
/*
otteryPrize
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
*/
package Module1b;
import java.util.Scanner;
}
public int lotteryReward(int ticketNumber)
{
if(ticketNumber%4==0 && ticketNumber%7!=0 )
return 6;
else if(ticketNumber%7==0 && ticketNumber%4!=0)
return 10;
else if (ticketNumber%4==0 && ticketNumber%7==0)
return 20;
else
return 0;
/*
LotteryPrize3
Problem Statement
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.
*/
package Module1b;
import java.util.Scanner;
System.out.println("Result is = "+result);
}
}
/*
LotteryTicket
Problem Statement
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.
*/
package Module1b;
import java.util.Scanner;
}
public int lotteryTicket(int a, int b, int c)
{
if(a==2 && b==2 && c==2)
return 10;
else if(a==b && b==c && c==a && a!=2)
return 5;
else if(a!=b && a!=c)
return 1;
else
return 0;
/*
MiddleChar
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 be used for chars.
*/
package Module1b;
import java.util.Scanner;
char a=input.next().charAt(0);
System.out.print("Enter 2nd Element is = ");
char b=input.next().charAt(0);
System.out.print("Enter 3rd Element is = ");
char c=input.next().charAt(0);
char result=obj.middle(a, b, c);
System.out.println("Result of Middle element is = "+result);
}
public char middle(char ch1, char ch2, char ch3)
{
if((ch1>=ch2 && ch1<=ch3) ||(ch1>=ch3 && ch1<=ch2))
return ch1;
else if((ch2>=ch3 && ch2<=ch1) || (ch2>=ch1 && ch2<=ch3))
return ch2;
else
return ch3;
}
/*
Multiple37
import java.util.Scanner;
}
public boolean multiple37(int n)
{
if(n%3==0 || n%7==0)
return true;
else
return false;
}
/*
MultipleCheck
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.
*/
package Module1b;
import java.util.Scanner;
}
public boolean isMultipleCheck(int num)
{
if(num%2==0 && num%3==0 && num%5==0 && num%7==0 &&
num%11==0)
return false;
else if((num%2==0 && num%3==0 && num%5==0) || (num%2==0 &&
num%3==0 && num%7==0) || (num%3==0 && num%7==0 && num%11==0))
return true;
else if((num%2==0 && num%3==0 && num%11==0) || (num%5==0 &&
num%7==0 && num%11==0) || (num%2==0 && num%5==0 && num%11==0))
return true;
else if((num%2==0 && num%5==0 && num%7==0)||(num%3==0 &&
num%5==0 && num%7==0) ||(num%2==0 && num%7==0 && num%11==0))
return true;
/*
Reverse3
import java.util.Scanner;
}
public int reverseDigit(int num)
{
int revNum=0;
int rem;
while(num>0)
{
rem=num%10;
revNum=(revNum*10)+rem;
num=num/10;
}
return revNum;
}
/*
SameLast2Digits
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
*/
package Module1b;
import java.util.Scanner;
}
public boolean isSameLastDigit(int num1,int num2,int num3,int num4)
{
boolean a=checkLast2Digit(num1);
boolean b=checkLast2Digit(num2);
boolean c=checkLast2Digit(num3);
boolean d=checkLast2Digit(num4);
if(a|b|c|d==true)
return true;
else
return false;
}
public boolean checkLast2Digit(int num)
{
int n1,n2;
n1=num%10;
n2=(num/10)%10;
if(n1==n2)
return true;
else
return false;
/*
SameLastDigit
Given 2 non negative numbers a and b, return true if both of them have the same last
digit.
*/
package Module1b;
import java.util.Scanner;
public class SameLastDigit
{
public static void main(String[] args)
{
SameLastDigit obj=new SameLastDigit();
Scanner input=new Scanner(System.in);
System.out.print("Enter 1st number is = " );
int x=input.nextInt();
System.out.print("Enter 2nd number is = ");
int y=input.nextInt();
boolean result=obj.isSameLarstDigit(x, y);
System.out.println("Result is a%b = " +result);
}
public boolean isSameLarstDigit(int a, int b)
{
int num1=a%10;
int num2=b%10;
if(num1==num2)
return true;
else
return false;
}
/*
ScoredCentury
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.
*/
package Module1b;
import java.util.Scanner;
}
public boolean hasScored(int score1, int score2, int score3)
{
if(score1>=100 || score2>=100 || score3>=100)
return true;
else
return false;
/*
Special20Number
import java.util.Scanner;
}
public boolean special20(int num)
{
if(num%20==0 || num%20==1)
return true;
else
return false;
}
/*
SumDivide11
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.
*/
package Module1b;
import java.util.Scanner;
}
public boolean sumDivBy11(int num1, int num2, int num3, int num4)
{
boolean a=checkSumDivBy11(num1, num2, num3);
boolean b=checkSumDivBy11(num2, num3, num4);
boolean c=checkSumDivBy11(num3, num4, num1);
boolean d=checkSumDivBy11(num4, num1, num2);
if(a|b|c|d==true)
return true;
else
return false;
}
public boolean checkSumDivBy11(int x, int y, int z)
{
int sum=x+y+z;
if(sum%11==0)
return true;
else
return false;
}
/*
SumLast3
import java.util.Scanner;
/*
TicketNumbers
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.
*/
package Module1b;
import java.util.Scanner;
}
public int calcuPrize(int a, int b, int c)
{
if(a!=b && b!=c && c!=a)
return 0;
else if(a==b && b==c && c==a)
return 20;
else
return 10;
}
Module 1 - C
/*
AllFactorsArePrime
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.
*/
package Module1c;
import java.util.Scanner;
}
}
/*
AnyonePrime
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.
*/
package Module1c;
import java.util.Scanner;
}
public boolean anyOnePrimeNo(int num1, int num2, int num3)
{
boolean a=isPrimeNo(num1);
boolean b=isPrimeNo(num2);
boolean c=isPrimeNo(num3);
if(a|b|c==true)
return true;
else
return false;
}
public boolean isPrimeNo(int num)
{
if(num>1)
{
for(int i=2; i<=num/2; i++)
{
if(num%i==0)
return false;
}
return true;
}
return false;
}
/*
ComputeNthPrime
import java.util.Scanner;
}
public int computePrime(int n)
{
int currentNum=1;
int count=0;
while(count!=n)
{
currentNum++;
if(isPrime(currentNum))
count++;
}
return currentNum;
}
}
return true;
}
return false;
}
/*
Count3Den
import java.util.Scanner;
int count=0;
for(int i=1; i<=num; i++)
{
if(i%3==0 || check3Den(i))
count++;
}
return count;
}
public boolean check3Den(int x)
{
while(x>0)
{
int a=x%10;
if(a==3)
return true;
x=x/10;
}
return false;
}
/*
CountFactors
Given a number n as input, find the count of its factors other than 1 and n.
*/
package Module1c;
import java.util.Scanner;
}
public int countOfFactors(int n)
{
int count=0;
for(int i=2; i<n; i++)
{
if(n%i==0)
count++;
}
return count;
}
/*
CountTheDigit
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.
*/
package Module1c;
import java.util.Scanner;
}
public int findDigitCount(int num, int digit)
{
int temp=0,count=0;
while(num>0)
{
temp=num%10;
if(temp==digit)
count++;
num=num/10;
}
return count;
/*
FirstDigit
Given a number as input, find the most significant digit in it. You can assume that the
number is not negative.
*/
package Module1c;
import java.util.Scanner;
/*
FizzBuzz
import java.util.Scanner;
}
public int isFizzBuzz(int num1, int num2)
{
int fb=0,f=0,b=0;
for(int i=num1; i<=num2; i++)
{
if(i%3==0 && i%5==0)
fb=fb+1;
else if(i%3==0)
f=f+1;
else if(i%5==0)
b=b+1;
}
return 3*f+5*b-15*fb;
}
/*
s3Den
import java.util.Scanner;
}
public boolean is3Den(int num)
{
int i=0;
if(num%3==0)
return true;
while(num>0)
{
i=num%10;
if(i==3)
num=num/10;
return true;
return false;
}
/*
IsPrimeNumber
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.
*/
package Module1c;
import java.util.Scanner;
/*
LargestDigit
Given a number as input, find the largest digit in it. You can assume that the number
is not negative.
*/
package Module1c;
import java.util.Scanner;
/*
NextMultiple37
Given a number num as input, find the smallest number greater than num that is a
multiple of both 3 and 7.
*/
package Module1c;
import java.util.Scanner;
}
public int findNextMultiple37(int num)
{
int mul=0;
//for(int i=num; i<=10000; i++)
for(int i=num; i>=num; i++)
{
if(i%3==0 && i%7==0)
break;
mul=i+1;
}
return mul;
}
}
/*
NthPower
import java.util.Scanner;
}
public int nthPower(int a, int b)
{
int temp=1;
if(b==0)
return 1;
for(int i=1; i<=b; i++)
{
temp=temp*a;
}
return temp;
}
/*
PerfectNumber
A perfect number is a positive integer that is equal to the 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.
*/
package Module1c;
import java.util.Scanner;
}
public boolean isPerfect(int num)
{
int sum=0;
for(int i=1; i<num; i++)
{
if(num%i==0)
sum=i+sum;
if(sum==num)
return true;
else
return false;
}
/*
ReverseNumber
Given a number as input, reverse it. You can assume that the number is not negative.
*/
package Module1c;
import java.util.Scanner;
int revNum = 0;
while (num > 0) {
int rem = num % 10;
revNum = (revNum * 10) + rem;
num = num / 10;
}
return revNum;
/*
SameFirst
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.
*/
package Module1c;
import java.util.Scanner;
}
public boolean sameFirstDigit(int num1, int num2, int num3)
{
int x=findDigit(num1);
int y=findDigit(num2);
int z=findDigit(num3);
if(x==y || y==z || z==x)
return true;
else
return false;
}
public int findDigit(int num)
{
int temp=0,rem=0;
while(num>0)
{
rem=num%10;
temp=rem;
num=num/10;
}
return temp;
}
/*
SumNumbers
import java.util.Scanner;
/*
SumNumbers1
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.
*/
package Module1c;
import java.util.Scanner;
}
public int isSum(int n)
{
int sum=0;
for(int i=0; i<=n; i++)
{
if(i%2!=0 && i%3!=0)
sum=sum+i;
}
return sum;
}
/*
SumOfDigits
import java.util.Scanner;
}
public int sumDigits(int num)
{
int sumDig=0;
while(num>0)
{
int rem=num%10;
sumDig=sumDig+rem;
num=num/10;
}
return sumDig;
}
/*
SumOfDigitsWithCount
Given 2 inputs, a number n and the number of digits it has d , find the sum of its
digits.
*/
package Module1c;
import java.util.Scanner;
}
public int sumDigits(int num, int count)
{
int sum=0;
for(int i=1; i<=count; i++)
{
int b=num%10;
sum=sum+b;
num=num/10;
}
return sum;
}
/*
SumOfSquares
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).
*/
package Module1c;
import java.util.Scanner;
/*
SumRounded
Round a number to the next multiple of 10 if its ones digit is 5 or more, otherwise
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.
*/
package Module1c;
import java.util.Scanner;
}
public int sumRounded(int num1, int num2, int num3, int num4)
{
int n1=roundedNum(num1);
int n2=roundedNum(num2);
int n3=roundedNum(num3);
int n4=roundedNum(num4);
return n1+n2+n3+n4;
}
public int roundedNum(int num)
{
int rem=num%10;
num=num/10;
if(rem>=0 && rem<5)
return num*10;
else
return num*10+10;
}
/*
SuperDivide
A positive int is called super-divide if every digit in the number divides the number.
So for example 128 divides itself since 128 is divisible 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.
*/
package Module1c;
import java.util.Scanner;
}
public boolean checkSuper(int num)
{
if(num%10==0)
return false;
else if(num%10!=0)
{
int temp=num;
while(temp>0)
{
int rem=temp%10;
if(num%rem!=0)
return false;
temp=temp/10;
}
}
return true;
Module 2 – Strings
/*
BatBall
Given a string, return true if the string "bat" and "ball" appear the same number of
times.
*/
package module2_strings;
import java.util.Scanner;
/*
BinToInt
Given a binary number as input convert it into base 10 (decimal system). 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.
*/
package module2_strings;
import java.util.Scanner;
public class BinaryToInt
{
public static void main(String[] args)
{
BinaryToInt obj=new BinaryToInt();
Scanner input=new Scanner(System.in);
System.out.print("Enter binary number is : ");
String str=input.nextLine();
int result=obj.convert(str);
System.out.println("Convert binary no. to Decimal system : "+result);
}
public int convert(String binary)
{
long num=Long.parseLong(binary);
int len=binary.length();
int sum=0;
for(int i=0; i<len; i++)
{
long rem=num%10;
double digit=rem*(Math.pow(2, i));
sum=sum+(int)digit;
num=num/10;
}
return sum;
}
/*
ChangeStringCase
Given a string as input, the expected output is a string where the case of all alphabets
has been changed.
*/
package module2_strings;
import java.util.Scanner;
public class ChangeStringCase
{
public static void main(String[] args)
{
ChangeStringCase obj=new ChangeStringCase();
Scanner input=new Scanner(System.in);
System.out.print("Enter String ");
String str1=input.nextLine();
String result=obj.changeCase(str1);
System.out.println("Change String is : "+result);
}
public String changeCase(String sentence)
{
/* 1st Method program
char chars[]=sentence.toCharArray();
for(int i=0; i<chars.length; i++)
{
char ch=chars[i];
if(Character.isUpperCase(ch))
{
chars[i] =Character.toLowerCase(ch);
}
else if(Character.isLowerCase(ch))
{
chars[i]=Character.toUpperCase(ch);
}
}
return new String(chars); */
int len=sentence.length();
String res="";
for(int i=0; i<len; i++)
{
char ch=sentence.charAt(i);
if(ch>='A'&& ch<='Z')
{
res+=(char)(ch+32);
}
else if(ch>='a' && ch<='z')
{
res+=(char)(ch-32);
}
else
{
res+=ch;
}
}
return res;
}
/*
CombineStr
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.
*/
package module2_strings;
import java.util.Scanner;
}
public String combine(String str1, String str2)
{
int len1=str1.length();
int len2=str2.length();
String result="";
int i;
for(i=0; i<len1 && i<len2; i++)
{
result=result+str1.charAt(i)+str2.charAt(i);
}
if(i==len1)
{
result+=str2.substring(i);
}
else
{
result+=str1.substring(i);
}
return result;
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package module2_strings;
import java.util.*;
/**
*
* @author Home
*/
public class ComparatorDemo1 {
public static void main(String[] args) {
Given 2 strings str1 and str2 as input, return a string of the form (str1)str2(/str1)
*/
package module2_strings;
import java.util.Scanner;
}
public String makePattern(String str1, String str2)
{
String res="("+str1+")"+str2+"(/"+str2+")";
return res;
}
/*
CountCharInString
Given a string and a char as input, output the number of times, the char appears in the
string.
*/
package module2_strings;
//import java.io.BufferedReader;
//import java.io.InputStreamReader;
import java.util.Scanner;
}
public int countCharacter(String word, char ch)
{
int len=word.length();
int count=0;
for(int i=0; i<len; i++)
{
if(ch==word.charAt(i))
count++;
}
return count;
}
/*
CountCode
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.
*/
package module2_strings;
import java.util.Scanner;
}
/*
CountCommonChars
Given 2 strings, str1 and str2, as input, return the count of the chars which are in the
same position in str1 and str2.
*/
package module2_strings;
import java.util.Scanner;
}
public int count(String str1, String str2)
{
int len=str1.length();
int len2=str2.length();
int i=0;
int count=0;
if(len<=len2)
{
i=len;
}
else
i=len2;
for(int j=0;j<i; j++)
{
if(str1.charAt(j)==str2.charAt(j))
count++;
}
return count;
}
/*
CountHello
Return the number of times that the string "Hello" appears anywhere in the given
string.
*/
package module2_strings;
import java.util.Scanner;
}
public int count(String str)
{
// String str2=str.toUpperCase();
String str1=str.toLowerCase();
int index=str1.indexOf("hello");
int count=0;
while(index!=-1)
{
index=str1.indexOf("hello", index+1);
count++;
}
return count;
}
/*
DoubleString
Given a string, return a string where for every char in the original, there are two chars.
*/
package module2_strings;
import java.util.Scanner;
}
public String doubleStr(String str)
{
String str1="";
for(int i=0; i<str.length(); i++)
{
char ch=str.charAt(i);
char ch1=str.charAt(i);
str1+=ch+""+ch1;
}
return str1;
}
/*
GetFirstWord
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.
*/
package module2_strings;
import java.util.Scanner;
}
public String firstWord(String sentence)
{
String str1=" ";
for(int i=0; i<sentence.length(); i++)
{
char ch=sentence.charAt(i);
if(ch==' ')
return str1;
//else
str1=str1+ch;
}
return str1;
}
}
/*
GetMiddleWord
Given 3 words w1,w2 and w3 as input, output the word that will come in between in a
dictionary.
*/
package module2_strings;
import java.util.Scanner;
}
public String middleWord(String word1, String word2, String word3)
{
if((word1.compareToIgnoreCase(word2)>=0 &&
word2.compareToIgnoreCase(word3)>=0) ||
(word1.compareToIgnoreCase(word2)<=0 &&
word2.compareToIgnoreCase(word3)<=0))
return word2;
else if ((word2.compareToIgnoreCase(word3)>=0 &&
word3.compareToIgnoreCase(word1)>=0) ||
(word2.compareToIgnoreCase(word3)<=0 &&
word3.compareToIgnoreCase(word1)<=0))
return word3;
else
return word1;
/*
IntToBin
Given a number in base 10 (decimal system) as input convert it into binary (base 2).
Note that to convert a number from base 10 to base 2, keep on dividing it by 2 and
appending
the remainder to start of the binary number. For e.g. to convert 12 into binary,
Step 1 : divide 12 by 2, quotient = 6, remainder = 0, output = "0" Step 2 : divide 6 by
2, quotient = 3,
remainder = 0, output = "00" Step 3 : divide 3 by 2, quotient = 1, remainder = 1,
output = "100"
Step 4 : divide 1 by 2, quotient = 0, remainder = 1, output = "1100" As quotient = 0 at
step 4,
we stop and the binary representation of 12 is 1100.
*/
package module2_strings;
import java.util.Scanner;
}
public String convert(int num)
{
String str="";
if(num==0)
return "0";
while(num>0)
{
int rem=num%2;
str=rem+str;
num=num/2;
}
return str;
}
/*
JavaFile
A file name in java ends in .java. Given the name of the file, return true if its a java
file, else return false
*/
package module2_strings;
import java.util.Scanner;
/*
JoinChars
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.
*/
package module2_strings;
import java.util.Scanner;
}
public String join(String str1, String str2)
{
String a="";
for(int i=0; i<str1.length(); i++)
{
String b=str1.charAt(i)+""+str2.charAt(i);
a+=b;
}
return a;
}
}
/*
LargerNumber
Given 2 strings representing numbers as input, return the larger number. Note that
both the numbers are non negative.
*/
package module2_strings;
import java.util.Scanner;
/*
LetterPattern
A string str has been provided as input. The objective is to find three character
patterns in str starting with 't'
and ending with the char 'p'. For all such patterns, the middle character is removed.
*/
package module2_strings;
import java.util.Scanner;
/*
MostFrequentChar
Given a string as input, return the char which occurs the maximum number of times in
the string.
You can assume that only 1 char will appear the maximum number of times.
*/
package module2_strings;
import java.util.Scanner;
}
public char mostCharacter(String str)
{
char[] array = str.toCharArray();
int maxCount = 1;
char maxChar = array[0];
for(int i = 0, j = 0; i < str.length() - 1; i = j){
int count = 1;
while (++j < str.length() && array[i] == array[j]) {
count++;
}
if (count > maxCount) {
maxCount = count;
maxChar = array[i];
}
}
return maxChar;
}
}
/*
MoveUppercaseChars
Given a string as input, move all the alphabets in uppercase to the end of the string.
*/
package module2_strings;
import java.util.Scanner;
}
public String move(String str)
{
String cap="";
String low="";
for(int i=0; i<str.length(); i++)
{
char ch=str.charAt(i);
if(ch>='A' && ch<='Z')
{
cap=cap+ch;
}
else
{
low=low+ch;
}
}
return low+cap;
}
/*
NotPresentChars
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 #.
*/
package module2_strings;
import java.util.Scanner;
}
public String replace(String str1, String str2)
{
int len= str1.length();
String res="";
//char c='';
for(int i=0; i<len; i++)
{
int index=str2.indexOf(str1.charAt(i));
if(index==-1)
{
res=res+'#';
}
else
{
res=res+str1.charAt(i);
}
}
return res;
/*
PalindromeString
import java.util.Scanner;
}
if(str.equals(revString))
return true;
return false;
}
/*
PatternInString
Given two strings str1 and str2 as input, determine whether str2 occurs with str1 or
not.
*/
package module2_strings;
import java.util.Scanner;
}
public boolean containString(String str1, String str2)
{
if(str1.contains(str2))
return true;
else
return false;
}
/*
PermutationString
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.
*/
package module2_strings;
import java.util.Scanner;
}
public boolean isPermutation(String str1, String str2)
{
int lenStr1=str1.length();
int lenStr2=str2.length();
if(lenStr1!=lenStr2)
{
return false;
}
for(int i=0; i<lenStr1; i++)
{
char ch2=str1.charAt(i);
int count1=countingChar(ch2, str1);
int count2=countingChar(ch2, str2);
if(count1!=count2)
{
return false;
}
}
return true;
}
//counting number of a particular character in string
private int countingChar(char ch, String str)
{
int count=0;
for(int i=0; i<str.length(); i++)
{
char ch1=str.charAt(i);
if(ch==ch1)
{
count++;
}
}
return count;
}
}
/*
RemoveCharsFromString
Given two strings, str1 and str2 as input, remove all chars from str1 that appear in
str2.
*/
package module2_strings;
import java.util.Scanner;
}
public String remove(String str1, String str2)
{
String str3="";
for(int i=0; i<str1.length(); i++)
{
int index=str2.indexOf(str1.charAt(i));
if(index==-1)
str3=str3+str1.charAt(i);
}
return str3;
}
}
/*
RemoveDuplicateChars
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.
*/
package module2_strings;
import java.util.Scanner;
/*
RemoveMultipleSpaces
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.
*/
package module2_strings;
import java.util.Scanner;
/*
ReverseString
Given a string as input, reverse it. Reverse means return the string if it is read from
right to left.
*/
package module2_strings;
import java.util.Scanner;
}
public String reverse(String str1)
{
String revString="";
int len=str1.length();
for(int i=0; i<len; i++)
{
char eachChar=str1.charAt(i);
revString= eachChar + revString;
}
return revString;
}
/*
SameString
Given 3 strings as input, return true if any two of the strings are the same.
*/
package module2_strings;
import java.util.Scanner;
}
public boolean isSame(String str1, String str2, String str3)
{
String a=new String(str1);
String b=new String(str2);
String c=new String(str3);
if(a.equals(b) || b.equals(c) || c.equals(a))
return true;
else
return false;
}
/*
SecondHalf
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.
*/
package module2_strings;
import java.util.Scanner;
}
public String halfString(String word)
{
String secHalf="";
int k=word.length()/2;
for(int i=k; i<word.length(); i++)
{
secHalf=secHalf+word.charAt(i);
}
return secHalf;
}
/*
SolveExpression
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, i.e., it will of the form x+y or x-y where x and y are not negative.
*/
package module2_strings;
import java.util.Scanner;
}
public int solve(String str)
{
int len=str.length();
int result=0;
for(int i=0; i<len; i++)
{
if(str.charAt(i)=='+')
{
int first=Integer.parseInt(str.substring(0, i));
int last=Integer.parseInt(str.substring(i+1, len));
result=first+last;
}
else if(str.charAt(i)=='-')
{
int first=Integer.parseInt(str.substring(0, i));
int last=Integer.parseInt(str.substring(i+1, len));
result=first-last;
}
}
return result;
}
/*
StringToNumber
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. Do not use
Integer.parseInt to solve this problem.
*/
package module2_strings;
import java.util.Scanner;
public class StringToNumber
{
public static void main(String[] args)
{
StringToNumber obj=new StringToNumber();
Scanner input=new Scanner(System.in);
System.out.print("Enter String as a numeric type : ");
String str1=input.nextLine();
int result=obj.toNumber(str1);
System.out.println("Result is : "+result);
}
public int toNumber(String str)
{
int num=Integer.parseInt(str);
return num;
}
/*
SwapLastChars
Given a string as input, return the string with its last 2 chars swapped. If the string
has less than 2 chars, do nothing and return the input string.
*/
package module2_strings;
import java.util.Scanner;
}
Module 3 – ARRAYS
/*
AllPrimesBetween
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.
*/
package module3_arrays;
import java.util.Scanner;
count++;
}
}
int[] result=new int[count];
int j=0;
for(int i=start; i<=stop; i++)
{
if(isPrime(i))
{
result[j]=i ;
j++;
}
}
return result;
}
public boolean isPrime(int num){
if(num>1)
{
for(int i=2; i<=num/2; i++)
{
if(num%i==0)
return false;
}
return true;
}
return false;
}
/*
AnyDuplicatesInArray
Given an array of integers, check whether any number has been repeated in the array. That is,
whether the array has any duplicates.
*/
package module3_arrays;
import java.util.Scanner;
{
for(int j=i+1; j<len; j++)
{
if(arr[i]==arr[j])
return true;
}
}
return false;
}
/*
CountEvens
Given an array of ints as input, return the number of even ints in it.
*/
package module3_arrays;
import java.util.Scanner;
/*
CountStrings
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.
*/
package module3_arrays;
import java.util.Scanner;
int len1=input.nextInt();
String[] arr=new String[len1];
}
System.out.println("Enter String length to count:");
int len2=input.nextInt();
int result=obj.stringOfSize(arr, len2);
System.out.println("result count:"+result);
}
public int stringOfSize(String[] strs, int len)
{
int count=0;
for(int i=0; i<strs.length; i++)
{
if(len==strs[i].length())
{
count++;
}
}
return count;
}
}
/*
CreateDomino
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}.
*/
package module3_arrays;
import java.util.Scanner;
/*
GenerateFizzBuzz
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".
*/
package module3_arrays;
import java.util.Scanner;
/*
IsSortedArray
*
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.
*/
package module3_arrays;
import java.util.Scanner;
int num=input.nextInt();
int[] arr1=new int[num];
System.out.println("Enter the array of size is = {"+num+"}");
System.out.println("{");
for(int i=0; i<num; i++)
{
arr1[i]=input.nextInt();
}
System.out.println("}");
System.out.println("Result is = "+obj.isSorted(arr1));
}
public boolean isSorted(int[] arr)
{
int len=arr.length;
boolean ascending=true;
if(arr[0]>arr[len-1])
{
ascending=false;
}
for(int i=0; i<len-1; i++)
{
if(ascending)
{
if(arr[i]>arr[i+1])
return false;
}
else
{
if(arr[i]<arr[i+1])
return false;
}
}
return true;
}
/*
JoinArray
Given two arrays, arr1 and arr2 as input, return an array which has the values of arr1 followed
by those of arr2.
*/
package module3_arrays;
import java.util.Scanner;
int num1=input.nextInt();
int[] array1=new int[num1];
System.out.println("First array of size is = {"+num1+"}");
/*
JoinDescArray
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.
*/
package module3_arrays;
import java.util.Scanner;
/*
LargestIn2D
Given a 2D array consisting of ints as input, return the largest int in it.
*/
package module3_arrays;
import java.util.Scanner;
}
System.out.println("}");
/*
MatchingMarks
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.
*/
package module3_arrays;
import java.util.Scanner;
/*
MatrixAdd
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.
*/
package module3_arrays;
import java.util.Scanner;
}
public int[][] add(int[][] m1, int[][] m2)
{
int rows=m1.length;
int columns=m1[0].length;
int[][] sum=new int[rows][columns];
{
for(int i=0; i<rows; i++)
{
for(int j=0; j<columns; j++)
sum[i][j]=m1[i][j]+m2[i][j];
}
}
return sum;
}
/*
MaxDifference
Given an array of ints as input, compute the difference between the largest and smallest
numbers in the array.
*/
package module3_arrays;
import java.util.Scanner;
}
public int maxDiffNum(int numbers[])
{
int min=numbers[0];
int max=0;
for(int i=0; i<numbers.length; i++)
{
if(numbers[i]>max)
{
max=numbers[i];
}
if(numbers[i]<min)
{
min=numbers[i];
}
}
return max-min;
}
}
/*
MCQScore
You have been given two char arrays as input, key and answersheet. The first input parameter
is the key array
and contains the correct answers of an examination, like {'a','b','d','c','b','d','c'}. The second
input parameter
is answersheet array and 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.
*/
package module3_arrays;
import java.util.Scanner;
/*
More6Than4
Given an array of ints as input, return true if the number of 6's (sixes) is greater than the
number of 4's (fours).
*/
package module3_arrays;
import java.util.Scanner;
}
public boolean count6And4(int [] numbers)
{
int count6=0;
int count4=0;
for(int i=0; i<numbers.length; i++)
{
if(numbers[i]==6)
count6++;
if(numbers[i]==4)
count4++;
}
if(count6>count4)
return true;
else
return false;
}
/*
MostFreqDigit
Given an array of numbers as input, return the digit which occurs the maximum number of
times in the input.
*/
package module3_arrays;
import java.util.Scanner;
}
public int frequentDigit(int[] numbers)
{
int[] count= new int[10];
for(int num: numbers)
{
calcCount(count, num);
}
int dig=0;
int max=0;
for(int i=0; i<count.length; i++)
{
if(count[i]>max)
{
max=count[i];
dig=i;
}
}
return dig;
}
/*
MostFreqNum
Given an array of numbers as input, return the number which occurs the maximum number of
times in the input.
*/
package module3_arrays;
import java.util.Scanner;
}
public int frequentNumuber(int[] numbers)
{
int store = numbers[0];
int count=0,max=0;
for(int i=0;i<numbers.length-1;i++)
{
for(int j=i+1;j<numbers.length;j++)
{
if(numbers[i]==numbers[j])
{
count++;
}
}
if(count>max)
{
max=count;
store = numbers[i];
}
count=0;
}
return store;
}
}
/*
Remove3s
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.
*/
package module3_arrays;
import java.util.Scanner;
}
public int[] remove(int[] arr)
{
int len=arr.length;
int j=0;
for(int i=0; i<len; i++)
{
int a=arr[i]%10;
int b=arr[i]/10;
int c=b%10;
if(arr[i]%3==0 || a==3 || c==3)
{
j++;
}
}
int z=len-j;
int[] result=new int[z];
int d=0;
for(int k=0; k<len; k++)
{
int p=arr[k]%10;
int q=arr[k]/10;
int r=q%10;
if(arr[k]%3==0 || p==3 || r==3)
{
}
else
{
result[d]=arr[k];
d++;
}
}
return result;
}
/*
RemoveDuplicates
Given an array of numbers as input, return an array with all the duplicate values removed.
*/
package module3_arrays;
import java.util.Scanner;
}
public int[] remove(int[] arr)
{
int len=arr.length;
int j=0;
int[] a= new int[len];
for(int i=0; i<len; i++)
{
if(!isPresent(arr[i], a))
{
a[j++]=arr[i];
}
}
int x=0;
int[] result=new int[j];
for(int i=0; i<len; i++)
{
if(!isPresent(arr[i], result))
{
result[x++]=arr[i];
}
}
//result=a;
return result;
}
public boolean isPresent(int c, int[]a)
{
for(int i=0; i<a.length;i++)
{if(a[i]==c)
return true;
}
return false;
}
/*
RemoveZeros
Given an array of integers return an array in the same order with all 0's removed.
*/
package module3_arrays;
import java.util.Scanner;
/*
ReverseArray
Given an array of integers as input, output an array which has the elements in reverse order.
*/
package module3_arrays;
import java.util.Scanner;
}
public int[] reverse(int[] arr)
{
int len=arr.length;
int a=len-1;
int[] res=new int[len];
for(int i=0; i<len; i++)
{
res[i]=arr[a--];
}
return res;
}
/*
ShiftElements
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.
*/
package module3_arrays;
import java.util.Scanner;
System.out.print(result[j]);
}
*/
System.out.println("\n }");
}
elements[len-1]=ch;
return elements;
}
/*
SplitSumArray
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 left is equal to the sum of the numbers on the right.
*/
package module3_arrays;
import java.util.Scanner;
}
public boolean canSplit(int[] arr)
{
int len=arr.length;
int sum=0;
for(int i=0; i<len; i++)
{
sum+=arr[i];
}
int sum1=0;
if(sum%2==0)
{
sum=sum/2;
for(int j=0; j<len-1; j++)
{
sum1+=arr[j];
if(sum1==sum)
return true;
}
}
return false;
}
/*
StringArrayOfNumbers
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.
*/
package module3_arrays;
import java.util.Scanner;
}
public String[] make(int num)
{
String[] arr=new String[num];
for(int i=0; i<num; i++)
{
arr[i]=""+i+"";
}
return arr;
}
/*
ThirdLargestNumberInArray
Given an array of integers, find out the third largest value in the array.
*/
package module3_arrays;
import java.util.Scanner;
}
public int thirdLargest(int[] arr)
{
int len=arr.length;
/*
WordTo2DChar
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.
*/
package module3_arrays;
import java.util.Scanner;
System.out.print("'"+result[row][col]);
if(col!=result[0].length-1)
{System.out.print("',");}
else
{System.out.print("'");}
}
if(row!=result.length-1)
{ System.out.print("};");}
else
{System.out.print("}");}
}
// System.out.println(result[0][4]);
System.out.print("}");
}
public char[][] to2DChars(String words)
{
int row=0;
int index=words.indexOf(' ');
int col=index;
if(index==-1)
{
col=words.length();
}
while(index!=-1)
{
row++;
index=words.indexOf(' ', index+1);
}
row++;
char[][] ch=new char[row][col];
int k=0;
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
{
ch[i][j]=words.charAt(i+k);
k++;
}
}
return ch;
}
/*
Write a Program a Dimond * shape
*
***
*****
*******
*****
***
*
*/
package practicesharendra;
/*
Write a Program is
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package practicesharendra;
import java.util.Scanner;
}
}
/*
*The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
The next number is found by adding up the two numbers before it. Similarly, the 3 is
found by adding the two numbers before it (1+2),
*/
package practicesharendra;
import java.util.Scanner;
System.out.println(next);
}
/*
int current=1,last=0;
Scanner input=new Scanner(System.in);
int num=input.nextInt();
System.out.println(last);
System.out.println(current);
int lastlast=2;
for(int i=2; i<num; i++)
{
lastlast=last;
last=current;
current=lastlast+last;
System.out.println(current);
}
*/
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package practicesharendra;
import java.util.Scanner;
/*
Enter a Number is : 5
print like this :
*
*
*
*
*
*
*
*
*
*
*/
package practicesharendra;
import java.util.Scanner;
/*
Enter a number is : 5
Print like this :
*****
****
***
**
*
*/
package practicesharendra;
import java.util.Scanner;
/*
Enter a number is : 5
To Print like this :
*
**
***
****
*****
*/
package practicesharendra;
import java.util.Scanner;
/*
Enter a number is : 8
********
*******
******
*****
****
***
**
*
*
**
***
****
*****
******
*******
********
*/
package practicesharendra;
import java.util.Scanner;
/*
Enter a number is : 8
To Print like this :
*
**
***
****
*****
******
*******
********
********
*******
******
*****
****
***
**
*
*/
package practicesharendra;
import java.util.Scanner;
/*
Enter a Number is : 8
print like this :
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package practicesharendra;
import java.util.Scanner;
public class StarPrint5 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a Number is : ");
int n=sc.nextInt();
System.out.println("print like this : ");
/*
Enter a number is : 5
To print * star like this
* *
**
*
**
* *
*/
package practicesharendra;
import java.util.Scanner;
System.out.println();
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package practicesharendra;
import java.util.Scanner;
}
System.out.println();
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package practicesharendra;
import java.util.Scanner;
System.out.println();
/*
Enter the less than 10 number is :
6
Triagle shape is * :
*
***
*****
*******
*********
***********
*/
package practicesharendra;
import java.util.Scanner;
/*
Enter a Number to Print Star
10
Triagle Sape is :
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*/
package practicesharendra;
import java.util.Scanner;
/*
To print * is like this
*
**
***
****
*****
******
*******
********
*********
**********
*/
package practicesharendra;
/*
Write a Program like this
**********
*********
********
*******
******
*****
****
***
**
*
*/
package practicesharendra;
/*
Enter a number is
10
Triangle like this
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*/
package practicesharendra;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package practicesharendra;
import java.util.Scanner;
Module 5 - Collection
/*
ArrayList Basic
*/
package com.collection;
import java.util.ArrayList;
package com.collection;
import java.util.*;
public class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList l=new ArrayList();
l.add("A");
l.add(10);
l.add("A");
l.add(null);
System.out.println(l);
l.remove(2);
System.out.println(l);
l.add(2,"M");
l.add("N");
System.out.println(l);
}
package com.collection;
package com.collection;
import java.util.*;
public class CursorDemo
{
public static void main(String[] args)
{
Vector v=new Vector();
Enumeration e=v.elements();
Iterator itr=v.iterator();
ListIterator litr=v.listIterator();
System.out.println(e.getClass().getName());
System.out.println(itr.getClass().getName());
System.out.println(litr.getClass().getName());
package com.collection;
import java.util.*;
public class EnumerationDemo
{
public static void main(String[] args)
{
Vector v=new Vector();
for(int i=0; i<=10; i++)
{
v.addElement(i);
}
System.out.println(v); // [0,1,2,3....,10]
Enumeration e=v.elements();
while(e.hasMoreElements())
{
Integer I=(Integer)e.nextElement();
if(I%2==0)
System.out.println(I); //0 2 4 6 8 10
}
System.out.println(v); //[0,1,2,3....,10]
}
}
package com.collection;
import java.util.*;
public class HashSetDemo
{
public static void main(String[] args)
{
HashSet h=new HashSet();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.println(h.add("Z")); // false
System.out.println(h);
package com.collection;
import java.util.*;
public class IteratorDemo
{
public static void main(String[] args)
{
ArrayList l=new ArrayList();
for(int i=0; i<=10; i++)
{
l.add(i);
}
System.out.println(l); //[0,1,2,...10]
Iterator itr=l.iterator();
while(itr.hasNext())
{
Integer I=(Integer)itr.next();
if(I%2==0)
System.out.println(I); //0 2 4 6 8 10
else
itr.remove();
}
System.out.println(l); //[0,2,4,6,8,10]
}
package com.collection;
import java.util.*;
public class LinkedHashSetDemo
{
public static void main(String[] args) {
LinkedHashSet h=new LinkedHashSet();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.println(h.add("Z")); //false
System.out.println(h); //[B,C,D,Z,null,10]
}
package com.collection;
import java.util.*;
public class LinkedListDemo
{
public static void main(String[] args)
{
LinkedList l=new LinkedList();
l.add("durga");
l.add(30);
l.add(null);
l.add("durga");
l.set(0, "Software");
l.add(0,"Venky");
l.removeLast();
l.addFirst("ccc");
System.out.println(l);
}
package com.collection;
import java.util.*;
public class ListIteratorDemo
{
public static void main(String[] args)
{
LinkedList l=new LinkedList();
l.add("balakrishna");
l.add("venki");
l.add("chiru");
l.add("nag");
System.out.println(l);
ListIterator Itr=l.listIterator();
while(Itr.hasNext())
{
String s=(String)Itr.next();
if(s.equals("venki"))
{
Itr.remove();
}
else if(s.equals("nag"))
{
Itr.add("chaitu");
}
else if(s.equals("chiru"))
{
Itr.set("charan");
}
}
System.out.println(l);
package com.collection;
import java.util.*;
public class StackDemo
{
public static void main(String[] args)
{
Stack s=new Stack();
s.push("A");
s.push("B");
s.push("C");
System.out.println(s);
System.out.println(s.search("A"));
System.out.println(s.search("Z"));
package com.collection;
import java.util.*;
public class TreeSetCompareToDemo
{
public static void main(String[] args)
{
TreeSet t=new TreeSet();
t.add("B");
t.add("Z"); //"Z".compareTo("B"); +ive
t.add("A"); //"A".compareTo("B"); -ive
System.out.println(t); //[A,B,Z]
package com.collection;
import java.util.*;
public class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet t=new TreeSet();
t.add("A");
t.add("a");
t.add("B");
t.add("Z");
t.add("L");
//t.add(new Integer(10)); //ClassCastException
//t.add(null); // NullPointerException
System.out.println(t); //[A, B, L, Z, a]
package com.collection;
import java.util.*;
package com.collection;
import java.util.*;
public class TreeSetDemo2
{
public static void main(String[] args)
{
//TreeSet t=new TreeSet(); //[0, 10, 15, 20]
TreeSet t=new TreeSet(new MyComparator()); //[20,15,10,0]
t.add(10);
t.add(0);
t.add(15);
t.add(20);
t.add(20);
System.out.println(t);
}
class MyComparator implements Comparator
{
public int compare(Object obj1, Object obj2)
{
Integer I1=(Integer)obj1;
Integer I2=(Integer)obj2;
if(I1<I2)
return +1;
else if (I1>I2)
return -1;
else
return 0;
// return I1.compareTo(I2); //Assecending order [0,10,15,20]
//return -I1.compareTo(I2); //Descending order [20,15,10,0]
}
}
package com.collection;
import java.util.*;
public class TreeSetDemo3
{
public static void main(String[] args)
{
TreeSet t=new TreeSet(new MyComparator1());
t.add("Roja");
t.add("ShobhaRani");
t.add("RajaKumari");
t.add("GangaBhavani");
t.add("Ramulamma");
System.out.println(t);
}
}
class MyComparator1 implements Comparator
{
public int compare(Object obj1, Object obj2)
{
String s1=obj1.toString();
String s2=(String)obj2;
//return s2.compareTo(s1); //[ShobhaRani, Roja, Ramulamma, RajaKumari,
GangaBhavani]
return -s1.compareTo(s2); //[ShobhaRani, Roja, Ramulamma, RajaKumari,
GangaBhavani]
}
}
package com.collection;
import java.util.*;
public class TreeSetDemo4
{
public static void main(String[] args)
{
TreeSet t=new TreeSet(new MyComparator2());
t.add(new StringBuffer("A"));
t.add(new StringBuffer("Z"));
t.add(new StringBuffer("K"));
t.add(new StringBuffer("L"));
System.out.println(t);
}
}
class MyComparator2 implements Comparator
{
public int compare(Object obj1, Object obj2)
{
String s1=obj1.toString();
String s2=obj2.toString();
return s1.compareTo(s2); //[A, K, L, Z]
}
}
package com.collection;
import java.util.*;
public class TreeSetDemo5
{
public static void main(String[] args)
{
TreeSet t=new TreeSet(new MyComparator3());
t.add("A");
t.add(new StringBuffer("ABCD"));
t.add(new StringBuffer("AA"));
t.add("XX");
t.add("A");
System.out.println(t);
}
}
class MyComparator3 implements Comparator
{
public int compare(Object obj1, Object obj2)
{
String s1=obj1.toString();
String s2=obj2.toString();
int len1=s1.length();
int len2=s2.length();
if(len1<len2)
return -1;
else if (len1>len2)
return 1;
else
return s1.compareTo(s2); //[A, AA, XX, ABC]
}
}
/*
Write a Demo Program for Customized sorting for Employee class :
*/
package com.collection;
import java.util.*;
class Employee implements Comparable
{
String name;
int eid;
Employee(String name, int eid)
{
this.name=name;
this.eid=eid;
}
public String toString()
{
return name+"-"+eid;
}
package com.collection;
import java.util.*;
public class VectorDemo1
{
public static void main(String[] args)
{
Vector v=new Vector();
System.out.println(v.capacity()); //10
for(int i=1; i<=10; i++)
{
v.addElement(i);
}
System.out.println(v.capacity()); //10
v.addElement("A");
System.out.println(v.capacity()); //20
System.out.println(v);
}
package com.collection;
import java.util.*;
public class VectorDemo2
{
public static void main(String[] args)
{
package com.collection;
import java.util.*;
public class VectorDemo3
{
public static void main(String[] args)
{
Vector v=new Vector(10,5);
System.out.println(v.capacity()); //10
for(int i=1; i<=10; i++)
{
v.addElement(i);
}
System.out.println(v.capacity());//10
v.addElement("A");
System.out.println(v.capacity());//15
System.out.println(v);
package com.collection.jPont;
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class ArrayListAddBook {
public static void main(String[] args) {
//Creating list of Books
List<Book> list=new ArrayList<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc
Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to list
list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list
for(Book b:list){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+"
"+b.quantity);
}
}
}
package com.collection.jPont;
import java.util.ArrayList;
import java.util.Iterator;
package com.collection.jPont;
import java.util.ArrayList;
import java.util.Iterator;
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
public class UserDefObjList {
public static void main(String args[]){
//Creating user-defined class objects
Student s1=new Student(101,"Sonoo",23);
Student s2=new Student(102,"Ravi",21);
Student s3=new Student(103,"Hanumat",25);
//creating arraylist
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);//adding Student class object
al.add(s2);
al.add(s3);
//Getting Iterator
Iterator itr=al.iterator();
//traversing elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
package com.soft.collection;
import java.util.*;
public class HashMapDemo {
public static void main(String args[]){
HashMap m=new HashMap();
m.put("Chiran Jeevi", 700);
m.put("Balaiah", 800);
m.put("Venkatesh", 200);
m.put("Nagaarjuna", 500);
System.out.println("m ::: "+m);
System.out.println(m.put("Chiran Jeevi", 1000));
Set s=m.keySet();
System.out.println(s);
Collection c=m.values();
System.out.println("c ::: " +c);
Set s1=m.entrySet();
System.out.println("s1 ::: "+s1);
Iterator itr=s1.iterator();
while(itr.hasNext()){
Map.Entry m1=(Map.Entry)itr.next();
System.out.println(m1.getKey()+ " -------- " +m1.getValue());
if(m1.getKey().equals("Nagaarjuna")){
m1.setValue(10000);
}
}
System.out.println(m);
}
package com.soft.collection;
import java.util.HashMap;
import java.util.IdentityHashMap;
package com.soft.collection;
import java.util.HashMap;
import java.util.WeakHashMap;
import javax.xml.transform.Templates;