Monday, 6 January 2020

Menu Driven Java Program to Sort Student details based on Id, total, Modify name based on id, search based on id, search based on name, add new student, print details of student

import java.util.Scanner;
import java.util.Arrays;

class Student
{
private long id;
private String name;
private int marks[],total;
Student(long tid, String tname,int tmarks[],int ttotal )
{
id=tid;name=tname; marks=tmarks;total=ttotal;
}
public void setName(String tname)
{
name=tname;
}
public String toString()
{
return "regd id = "+ id+" name = "+name + "\n marks in 6 subjects = "+Arrays.toString(marks) +" Total ="+total;
}
public long getId()
{
return id;
}
public String getName()
{
return name;
}
public int[] getMarks()
{
return marks;
}
public int getTotal()
{
return total;
}
}
class SearchSort
{
public static void sortById(Student st[], int n)
{
   
for(int i=0;i<n-1;i++)
      {
for(int j=0;j<n-i-1;j++)
{
if(st[j].getId() > st[j+1].getId())
{
Student temp = st[j];
st[j]=st[j+1];
st[j+1]=temp;
}
}
      }
System.out.println("After sorting based on id, Student details are");
for(int i=0;i<n;i++)
System.out.println(st[i]);
}
public static void sortByTotal(Student st[],int n)
{
for(int i=0;i<n-1;i++)
      {
for(int j=0;j<n-i-1;j++)
{
if(st[j].getTotal() > st[j+1].getTotal())
{
Student temp = st[j];
st[j]=st[j+1];
st[j+1]=temp;
}
}
      }
System.out.println("After sorting based on total, Student details are");
for(int i=0;i<n;i++)
System.out.println(st[i]);
}
public static int linearSearch(Student st[], int n, int key)
{
int flag=0;
for(int i=0;i<n;i++)
{
if(st[i].getId() == key)
return i;
                                    }
return -1;
}
public static int linearSearch(Student st[], int n, String key)
{
int flag=0;
for(int i=0;i<n;i++)
{
if(st[i].getName().equalsIgnoreCase(key))
return i;
                                    }
return -1;
}
}
public class StudentDemo
{
public static void main(String args[])
{
System.out.println(" 1. Add New Student \n 2. Print details of all students  \n 3. Search a student based on id \n 4. Search based on name \n 5. Modify name based on id \n 6. Sort based on id \n 7. Sort based on total \n 8. Exit");
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
Student st[] = new Student[100];
int nos=0;
while(true){
switch(choice)
{
case 1:
System.out.println("enter id, name");
int tid=sc.nextInt();
String tname=sc.next();
int tmarks[]=new int[6];
int ttotal=0;
for(int i=0;i<tmarks.length;i++)
{
System.out.println("enter marks of  subject "+i);
tmarks[i]=sc.nextInt();
ttotal=ttotal+tmarks[i];
}
st[nos]  = new Student(tid,tname,tmarks,ttotal);
nos++;
break;
case 2:
for(int i=0;i<nos;i++)
System.out.println(st[i]);
break;
case 3:     System.out.println("enter id to search");
                int key=sc.nextInt();
                int index = SearchSort.linearSearch(st,nos,key);
                if(index == -1)
    System.out.println("search id not found");
               else
    System.out.println("search element found at index " + index +" student details are " +st[index]);
               break;

case 4:
               System.out.println("enter Student name to search");
               String key1=sc.next();
               index = SearchSort.linearSearch(st,nos,key1);
                if(index == -1)
    System.out.println("search id not found");
               else
    System.out.println("search element found at index " + index +" student details are " +st[index]);
               break;
case 5: System.out.println("enter id whose name to be modified");
                int key2=sc.nextInt();
                index = SearchSort.linearSearch(st,nos,key2);
                if(index == -1)
    System.out.println("search id not found");
                else
{
System.out.println("enter Student name ");
st[index].setName(sc.next());
System.out.println(" student details after modifying name = " +st[index]);
}
break;
case 6:
SearchSort.sortById(st,nos);
break;
case 7:
SearchSort.sortByTotal(st,nos);
break;
case 8:
System.exit(0);
}
System.out.println(" 1. Add New Student \n 2. Print details of all students  \n 3. Search a student based on id \n 4. Search based on name \n 5. Modify name based on id \n 6. Sort based on id \n 7. Sort based on total \n 8. Exit");
choice = sc.nextInt();
}
}
}



Anonymous arrays example in java

import java.util.Scanner;


public class MyClass {
    public static void display(int a[])
    {
        for(int ele:a)
            System.out.println(ele);
    }
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("enter 3 numbers");
        display(new int[]{sc.nextInt(),sc.nextInt(),sc.nextInt()});
    }
}

Sunday, 5 January 2020

Program to declare instantiate read and display the elements of 2D array in java

public class MyClass {
    public static void main(String args[])
    {
        int arr[][];
        arr=new int[3][3];
        for(int i=0;i<arr.length;i++)
        {
            for(int j=0;j<arr[i].length;j++)
                arr[i][j]=i;
        }
        for(int[] u: arr)
        {
            for(int ele: u)
                System.out.print(ele+" ");
            System.out.println("");
        }
    }
}

Wednesday, 1 January 2020

Menu DrivenJava Program to Add new Student, Sort Sudents by id, Search Student by id

import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;

import java.util.Collections; 
class Student implements Comparable<Student>
{
private long id;
private String name;
private int m1,m2,m3,total;
Student(long tid, String tname, int tm1, int tm2, int tm3)
{
id=tid;name=tname;m1=tm1;m2=tm2;m3=tm3; total =tm1+tm2+tm3;
}
public String toString()
{
return "regd id = "+ id+" name = "+name +" m1 marks = "+m1 +" m2 marks = "+m2 +" m3 marks = "+m3 ;
}
public long getId()
{
return id;
}
public int compareTo(Student tob)
{       
return (this.getId() < tob.getId() ? -1 : 1);
}

}

public class StudentDemo
{
public static void main(String args[])
{
System.out.println("1. add new student 2. Print all  3. sort id 4. search id 5. exit");
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
Student st;
ArrayList<Student> students = new ArrayList<Student>();
int nos=0;
do{
switch(choice)
{
case 1:
System.out.println("enter id, name, m1 ,m2 and m3 marks");
st  = new Student(sc.nextInt(),sc.next(),sc.nextInt(),sc.nextInt(),sc.nextInt());
students.add(st);
break;
case 2:
for(Student ele: students)
System.out.println(ele);
break;
case 3:
Collections.sort(students);
for(Student ele: students)
System.out.println(ele);
break;
case 4:
System.out.println("enter id to search");
int key=sc.nextInt(),flag=0;
for(Student ele: students)
if(ele.getId() == key)
{
System.out.println("search element found");
System.out.println("ele");
flag=1;
break;
}
if(flag == 0)
System.out.println("search element not found");
break;
case 5:
System.exit(0);
}
System.out.println("1. add new student 2. Print all 3. sort id 4. search id 5. exit");
choice = sc.nextInt();
}while(choice>0 && choice <6);
}
}


=================================================================
Sorting using comparator

import java.util.*;
import java.lang.*;
import java.io.*;

// A class to represent a student.
class Student
{
int rollno;
String name, address;

// Constructor
public Student(int rollno, String name,
String address)
{
this.rollno = rollno;
this.name = name;
this.address = address;
}

// Used to print student details in main()
public String toString()
{
return this.rollno + " " + this.name +
" " + this.address;
}
}

class Sortbyroll implements Comparator<Student>
{
// Used for sorting in ascending order of
// roll number
public int compare(Student a, Student b)
{
return a.rollno - b.rollno;
}
}

// Driver class
class Main
{
public static void main (String[] args)
{
Student [] arr = {new Student(111, "bbbb", "london"),
new Student(131, "aaaa", "nyc"),
new Student(121, "cccc", "jaipur")};

System.out.println("Unsorted");
for (int i=0; i<arr.length; i++)
System.out.println(arr[i]);

Arrays.sort(arr, new Sortbyroll());

System.out.println("\nSorted by rollno");
for (int i=0; i<arr.length; i++)
System.out.println(arr[i]);
}

}


Thursday, 26 December 2019

Use of Functions in programming languages

For example:

an Account has account_no, balance;
if person has withdrawn some amount then balance = balance - amount;
after withdraw if we want to print the account_no and balance

you have to write print account_no, balance

again if we deposit amount

balance = balance + amount;

you have to write print account_no, balance

again and again we have to print account_no and balance after every withdrawal and deposit

so we can put display() and write account_no and balance in that method display()
and call display() inside withdraw() and deposit()
int acno,bal;
void withdraw(int amt)
{
        bal=bal-amt;
}
void deposit(int amt)
{
        bal=bal-amt;
}
void display()
{
      printf("acc number = %d and Balance = %d", acno, bal);
}
int main()
{
       printf("Press 1. for withdraw 2. for deposit 3. display 4. exit");
       int choice;
       scanf("%d",&choice);
       switch(choice)
      {
             case 1:
                          printf("enter amount to withdraw");
                          int amt;
                          scanf("%d",&amt);
                          withdraw(amt);
                          display();
                          break;
           case 2:
                          printf("enter amount to deposit");
                          int amt;
                          scanf("%d",&amt);
                          deposit(amt);
                          display();
                          break;
           case 3:
                       display();
                       break;
           case 4: exit(0);
     }
}


Saturday, 21 December 2019

String of concatenation, rotating the matrix, turning binary matrix

string concatenation
A string is called a pString if it can be represented as p concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1String, a 2String and a 4String, but it is not a 3String, a 5String, or a 6String and so on. Obviously any string is a 1String.
You are given a string s, consisting of lowercase English letters and a positive integer p. Your task is to find if it is possible to reorder the letters in the string s in such a way that the resulting string is a pString.
Input Format
The first input line contains integer p.
The second line contains s, all characters in s are lowercase English letters.
Constraints
1 ≤ p ≤ 1000
1 ≤ |s| ≤ 1000
Output Format
Print "YES" if it is possible to rearrange the letters in string s in such a way that the result is a pString. Print the result on a single output line. If it is not possible print "NO". (without quotes).
Sample Input 0
2
aazz
Sample Output 0
YES
Explanation 0
aazz can be rearranged to azaz which is a 2String

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
    int n;
    scanf("%d",&n);
    char s[1010];
    scanf("%s",s);
    int h[26]={0},i;
    for(i=0;s[i]!='\0';i++)
        h[s[i]-'a']++;
    for(i=0;i<26;i++)
    {
        if(h[i]!=0 )
        {
            if(h[i]%n != 0)
            {
                printf("NO\n");
            return 0;
            }
        }
           
        }
    printf("YES");
    return 0;
}

=============
rotating the matrix
Thomas, a computer programmer, is led to fight an underground war against powerful computers who now rule the world with a system called 'The Matrix'.
To win against the system, he must rotate the Matrix clockwise by an angle of 90 degrees.
Unfortunately the system has wiped Thomas' memory and it is now in your hands to save the world.
The matrix can be considered as a 2Dimensional Array of size NxN.
SEE THE SAMPLE INPUT OUTPUT FOR CLARITY
Input Format
The first line contains the size of the matrix N.
The next N lines contain N integers each, together denoting the square matrix of size NxN.
Constraints
1 <= N <= 10
Output Format
Output the final matrix after rotation.
Sample Input 0
2
1 2
3 4
Sample Output 0
3 1
4 2

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int n;
    scanf("%d",&n);
    int a[n][n],b[n][n],i,j;
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            scanf("%d",&a[i][j]);
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            b[i][j]=a[n-j-1][i];
    for(i=0;i<n;i++){
        for(j=0;j<n;j++)
            printf("%d ",b[i][j]);
        printf("\n");
    }
    return 0;
}
Turning binary matrix


Consider a binary matrix A of size N X N. Now, consider the following matrices : A90 - obtained by rotating A clockwise by 90 degrees. A180 - obtained by rotating A clockwise by 180 degrees. A270 - obtained by rotating A clockwise by 270 degrees.
Note : Binary matrix implies that every element will be either 0 or 1.
Your task is to construct another binary matrix B of size N X N such that : B(i,j) = 1 iff either A(i,j) = 1 OR A90(i,j) = 1 OR A180(i,j) = 1 OR A270(i,j) = 1 B(i,j) = 0 otherwise
INPUT
First line contains the size of the matrix N (1 ≤ N ≤ 100) Next N lines contain N integers each (Only 0 or 1) denoting the matrix A
OUTPUT
Print N X N integers, denoting the matrix B.
Sample Input 0
4
0 0 0 0
0 0 0 0
0 0 1 0
1 0 0 0
Sample Output 0
1 0 0 1
0 1 1 0
0 1 1 0
1 0 0 1
int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int n;
    scanf("%d",&n);
    int a[n][n],b[n][n],i,j;
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            scanf("%d",&a[i][j]);
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            b[i][j]=a[i][j]|a[n-j-1][i]|a[n-i-1][n-j-1]|a[j][n-i-1];//for 360,90,180,270 rotations
    for(i=0;i<n;i++){
        for(j=0;j<n;j++)
            printf("%d ",b[i][j]);
        printf("\n");
    }
    return 0;
}