Thursday, 3 September 2020

My Activity Tracker in Angular 2

My Activity Tracker solution is available here

 Hold on
Are you doing a hackerrank ?

oh wait, Are you from doing this on Fresco Play?

and Are you from TCS?

okay so I get it you may be stuck here because the question is incomplete 

You need to create an activity tracker and here I show u my code-

app.component.ts-

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  //Define your variables done,todos,newToDo,newToDoObj,error
  todos:any
  done:boolean
  newToDo : String
  newToDoObj:any
  error: boolean
   TODOS :any[]

  //Define your constructor here with todos as [] ,newToDo as '' and error as false
  constructor() {
      this.newToDo = '';
      this.todos = [];
      this.error = false;
    }
  //Define your addMore function here
  addMore(newToDo) {
      if(this.newToDo != '')
      {
        this.newToDoObj = {
          newTodo: this.newToDo,
          done: false
        }
        this.todos.push(this.newToDoObj);
        this.newToDo = '';
      }
      else
      {
        this.error = true
      }
      console.log(this.todos);
    }

  //Define your clearAll function here
  clearAll(){
    this.todos.length = 0;
  }
}

app.component.html-

<h1>Fresco PLAY Activity Tracker</h1>

<div>
    <div *ngFor="let todo of todos; let i=index" class="todoItem">
        <input type="checkbox" [(ngModel)]="todo.done" />
        <span [ngClass]="{'checked': todo.done}">{{i+1}}. {{ todo.desc }}</span>
    </div>
    <span *ngIf="todos.length == 0">No Activities to track! Start by adding one</span><br/>
    <input id="newTodo" type="text" [(ngModel)]="newToDo">
    <span *ngIf="error" style="color:red;">Please enter an activity!</span>
    <br/>
    <button id="addActivity" (click)="addMore()">Add an Activity!</button>
    <button id="clearAll" (click)="clearAll()">Clear All</button>
</div>



Tuesday, 19 May 2020

Why Netflix loads faster? (1min read)

Netflix has an entire team dedicated to development obviously, 

What I was curious about is how Netflix allows 167 million people to stream the media on their devices, apparently, the answer to this is pretty sharp and smart 
What Netflix did was contacted the ISPs(Internet Service Provider) and installed a Box called Netflix Open Connect Appliances (OCAs) right at each ISP's office, these little red-colored boxes stores entire data of Netflix i.e. your movies and series. This allows faster delivery of content from the ISP to the user eliminating the usual process of how the internet works,
for those of you who don't know how the internet works here's an explanation - (Your regular website from your laptop goes to - modem - ISP - satellite - data center - data, Data centers are the harddisks of the internet, located at 6-8 places in the entire world, basically every data on the internet is stored right in a data center)

You can read about this particular feature here
I hope this image clears everything out for you -




Well, some pretty interesting stuff coming out about Netflix - stay tuned

Sunday, 16 June 2019

Sudo Placements geeks for geeks Solution in Java

FOR THE SOLUTION YOU MAY GET TLE- error(Exceeding timelimit error) it's just because Java is slower than cpp/c

Ques-

If a=1, b=2, c=3,....z=26. Given a string, find all possible codes that string can generate. Give a count as well as print the strings. 

For example: 
Input: "1123". You need to general all valid alphabet codes from this string.

Output List 
aabc //a = 1, a = 1, b = 2, c = 3 
kbc // since k is 11, b = 2, c= 3 
alc // a = 1, l = 12, c = 3 
aaw // a= 1, a =1, w= 23 
kw // k = 11, w = 23
Solution -
public class JavaApplication3 {

    /**
     * @param args the command line arguments
     */
    
    public static Set<String> decode(String prefix, String code) {
Set<String> set = new HashSet<String>();
if (code.length() == 0) 
                {
set.add(prefix);
return set;
}

if (code.charAt(0) == '0')
return set;

set.addAll(decode(prefix + (char) (code.charAt(0) - '1' + 'a'),
code.substring(1)));
if (code.length() >= 2 && code.charAt(0) == '1') {
set.addAll(decode(
prefix + (char) (10 + code.charAt(1) - '1' + 'a'),
code.substring(2)));
}
if (code.length() >= 2 && code.charAt(0) == '2'
&& code.charAt(1) <= '6') {
set.addAll(decode(
prefix + (char) (20 + code.charAt(1) - '1' + 'a'),
code.substring(2)));
}
return set;
}
    
    public static void main(String[] args) {
        Set s = decode("", "9999");
        System.out.println(s);
    }    
}

Immediate Smaller Element

Given an integer array of size N. For each element in the array, check whether there exist a smaller element on the next immediate position of the array. If such an element exists, print that element. If there is no smaller element on the immediate next to the element then print -1.

Input:
The first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains 2 lines of input:

The first line contains an integer N, where N is the size of array.
The second line contains N integers(elements of the array) sperated with spaces.

Output:

For each test case, print the next immediate smaller elements for each element in the array.

Constraints:

1 ≤ T ≤ 200
1 ≤ N ≤ 107
1 ≤ arr[i] ≤ 1000

Example:

Input
2
5
4 2 1 5 3
6
5 6 2 3 1 7

Output
2 1 -1 3 -1
-1 2 -1 1 -1 -1



Explanation:
Testcase 1: Array elements are 4, 2, 1, 5, 3. Immediate smaller of 2 is immediate smaller of 4, 1 is immediate smaller of 2,no immediate smaller of 1, 3 is immediate smaller of 5, and no immediate smaller for last element exists. So ouput is : 2 1 -1 3 -1.



CODE- SOLUTION

import java.util.*;

import java.lang.*;

import java.io.*;



class GFG {
 public static void main (String[] args) {
  //code
  Scanner kb=new Scanner(System.in);
  int times=kb.nextInt();
  for(int i=0;i<times;i++)//testcases
  {

      int size_arr=kb.nextInt();

      int arr[]=new int[size_arr];

      for(int j=0;j<size_arr;j++)

      {
          arr[j]=kb.nextInt();
      }

   

      try{

      for(int j=0;j<size_arr;j++)
      {
          if(arr[j]>arr[j+1])
          {
              System.out.println(arr[j+1]);
          }
          else
          {
              System.out.println("-1");
          }

       
      }
      }

      catch(Exception e)

      {
          System.out.println("-1");
      }


  }//testcases

 }


}


Rotating an Array
Given an array of N size. The task is to rotate array by d elements where d is less than or equal to N.

Input:
The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consist of three lines. The first line of each test case consists of an integer N, where N is the size of array.
The second line of each test case contains N space separated integers denoting array elements. The third line of each test case contains "d" .

Output:
Corresponding to each test case, in a new line, print the modified array.

Constraints:
1 ≤ T ≤ 200
1 ≤ N ≤ 200
1 ≤ A[i] ≤ 1000

Example:
Input
1
5
1 2 3 4 5
2

Output
3 4 5 1 2

Solution-

/*package whatever //do not write package name here */

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

class GFG {
public static void main (String[] args) {
//code
Scanner kb=new Scanner(System.in);
int times=kb.nextInt();
for(int i=0;i<times;i++)
{
    int sizearr=kb.nextInt();
    int arr[]=new int[sizearr];
    for(int j=0;j<sizearr;j++)
    {
        arr[j]=kb.nextInt();
      
    }
    int by_ro = kb.nextInt();
    for(int j=by_ro;j<sizearr;j++)
    {
        System.out.print(arr[j]);
    }
    for(int j=0;j<by_ro;j++)
    {
        System.out.print(arr[j]);
    }
    
}//times

}

}

Leaders in an array


Given an array of positive integers. Your task is to find the leaders in the array.
Note: An element of array is leader if it is greater than or equal to all the elements to its right side. Also, the rightmost element is always a leader. 

Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N denoting the size of array.
The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.

Output:
Print all the leaders.

Constraints:
1 <= T <= 100
1 <= N <= 107
0 <= Ai <= 107

Example:
Input:
3
6
16 17 4 3 5 2
5
1 2 3 4 0
5
7 4 5 7 3
Output:
17 5 2
4 0
7 7 3

Explanation:
Testcase 3: All elements on the right of 7 (at index 0) are smaller than or equal to 7. Also, all the elements of right side of 7 (at index 3) are smaller than 7. And, the last element 3 is itself a leader since no elements are on its right.

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

class GFG {
    
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases
while(t-->0){
    int n = Integer.parseInt(br.readLine().trim());
    int arr[] = new int[n];
    String inputLine[] = br.readLine().trim().split(" ");
    for(int i=0; i<n; i++){
        arr[i] = Integer.parseInt(inputLine[i]);
    }
    int maxEle = arr[n-1];
    StringBuffer str = new StringBuffer();
    ArrayList<Integer> res = new ArrayList<Integer>();
    for(int i=n-1; i>=0; i--) {
        if(arr[i] >= maxEle){
            maxEle = arr[i];
            res.add(maxEle);
        }
    }
    for(int i=res.size()-1; i>=0; i--){
        str.append(res.get(i)+" ");
    }
    System.out.println(str);
}
}

}



Print an array in Pendulum Arrangement

Write a program to input a list of n integers in an array and arrange them in a way similar to the to-and-fro movement of a Pendulum.

The minimum element out of the list of integers, must come in center position of array. If there are even elements, then minimum element should be moved to (n-1)/2 index (considering that indexes start from 0)
The next number (next to minimum) in the ascending order, goes to the right, the next to next number goes to the left of minimum number and it continues like a Pendulum.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer n denoting the size of the array. Then next line contains N space separated integers forming the array.

Output:
Output the array in Pendulum Arrangement.

Constraints:
1<=T<=500
1<=N<=100
1<=a[i]<=1000

Example:
Input:
2
5
1 3 2 5 4
5
11 12 31 14 5

Output:
5 3 1 2 4
31 12 5 11 14

Solution-

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;

public class test {
    public static void main(String[] args) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int times=Integer.parseInt(br.readLine());
        while(times-->0)
        {
           int size=Integer.parseInt(br.readLine());
           int arr[]=new int[size];
           String line=br.readLine();
           String [] strs=line.trim().split("\\s+");

           for(int i=0;i<size;i++)
               arr[i]=Integer.parseInt(strs[i]);

            Arrays.sort(arr);
            StringBuffer sb=new StringBuffer();
            int mid_point=(size-1)/2;
            sb.append(arr[0]+" ");
            int j=1;
            for(int i=0;i<size/2;i++)
            {
                sb.append(arr[j++]+" ");
                sb.insert(0,arr[j++]+" ");

            }
            if(size%2==0)
                sb.append(arr[arr.length-1]+" ");

            System.out.println(sb);


        }//times

    }
}




SP BIT MAGIC JAVA SOLUTIONS

Binary representation

Write a program to print Binary representation of a given number N.


Input:
The first line of input contains an integer T, denoting the number of test cases. Each test case contains an integer N.

Output:
For each test case, print the binary representation of the number N in 14 bits.

Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 5000

Example:
Input:
2
2
5

Output:
00000000000010
00000000000101

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

class binary {
    public static void main (String[] args) {
        //code
        Scanner kb=new Scanner(System.in);
        int times=kb.nextInt();
        int t=0;
        int arr[]=new int[14];
        for(int i=0;i<times;i++)
        {
            int num=kb.nextInt();

            for(int j=0;j<14;j++)
            {
                //System.out.println("j value "+ j);
                arr[j]=num%2;
                //System.out.println(arr[j]);
                num=num/2;
                //System.out.println(num);
            }



            //System.out.println("result");
            int j=13;
            while(j>=0)
            {
                System.out.print(arr[j]);
                j=j-1;
            }
            System.out.println();



        }//times
    }

}

Friday, 29 March 2019

Practice Coding Questions for Companies

Count ways to N'th Stair(Order does not matter)

There are N stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does not matter).
Note: Order does not matter means for n=4 {1 2 1},{2 1 1},{1 1 2} are considered same.
Input:
The first line contains an integer 'T' denoting the total number of test cases. In each test cases, an integer N will be given.
Output:
For each testcase, in a new line, print number of possible ways to reach Nth stair.
Constraints:
1 <= T <= 1000
1 <= N <= 106
Example:
Input:
2
4
5
Output:
3
3
Explanation:
Testcase 1:
 There are 3 ways to reach 4th stair.


Solution-
class DynamicProgramming{
    
    // function to find number of ways 
    Long countWays(int m){
        
        // your code here
        m=(m/2)+1;
        Long l=Long.valueOf(m);
        
        return l;
    }   
    
}

Question - Find the smallest positive number missing from an unsorted array

  Input: {2, 3, 7, 6, 8, -1, -10, 15}
 Output: 1

 Input: { 2, 3, -7, 6, 8, 1, -10, 15 }
 Output: 4

 Input: {1, 1, 0, -1, -2}
 Output: 2

Solution-


import java.util.*; 
  
class test
{    
       
    /* Utility function that puts all non-positive  
       (0 and negative) numbers on left side of  
       arr[] and return count of such numbers */
    static int segregate (int arr[], int size) 
    { 
        int j = 0, i; 
        for(i = 0; i < size; i++) 
        { 
           if (arr[i] <= 0)   
           { 
               int temp; 
               temp = arr[i]; 
               arr[i] = arr[j]; 
               arr[j] = temp; 
               // increment count of non-positive  
               // integers 
               j++;   
           } 
        } 
       
        return j; 
    } 
       
    /* Find the smallest positive missing  
       number in an array that contains 
       all positive integers */
    static int findMissingPositive(int arr[], int size) 
    { 
      int i; 
       
      // Mark arr[i] as visited by making  
      // arr[arr[i] - 1] negative. Note that  
      // 1 is subtracted because index start  
      // from 0 and positive numbers start from 1 
      for(i = 0; i < size; i++) 
      { 
        int x = Math.abs(arr[i]); 
        if(x - 1 < size && arr[x - 1] > 0) 
          arr[x - 1] = -arr[x - 1]; 
      } 
       
      // Return the first index value at which  
      // is positive 
      for(i = 0; i < size; i++) 
        if (arr[i] > 0) 
          return i+1;  // 1 is added becuase indexes  
                       // start from 0 
       
      return size+1; 
    } 
       
    /* Find the smallest positive missing  
       number in an array that contains 
       both positive and negative integers */
    static int findMissing(int arr[], int size) 
    { 
       // First separate positive and  
       // negative numbers 
       int shift = segregate (arr, size); 
       int arr2[] = new int[size-shift]; 
       int j=0; 
       for(int i=shift;i<size;i++) 
           { 
               arr2[j] = arr[i]; 
               j++; 
           }     
       // Shift the array and call  
       // findMissingPositive for 
       // positive part 
       return findMissingPositive(arr2, j); 
    } 
    // main function 
    public static void main (String[] args)  
    { 
        int arr[] = {0, 10,1,2, 2, -10, -20}; 
        int arr_size = arr.length; 
        int missing = findMissing(arr, arr_size); 
        System.out.println("The smallest positive missing number is "+  
                            missing); 
    } 
} 


Source-Geeksforgeeks

Question - Longest Common Substring in an Array of Strings

Input: grace graceful disgraceful gracefully
Output: grace

Input: sadness sad sadly
Output: sad

Solution - 

// Java program to find the stem of given list of 
// words 
import java.io.*; 
import java.util.*; 

class stem { 

// function to find the stem (longest common substring) from the string array 
public static String findstem(String arr[]) 
{ 
// Determine size of the array 
int n = arr.length; 

// Take first word from array as reference 
String s = arr[0]; 
int len = s.length(); 

String res = ""; 

for (int i = 0; i < len; i++) { 
for (int j = i + 1; j <= len; j++) { 

// generating all possible substrings 
// of our reference string arr[0] i.e s 
String stem = s.substring(i, j); 
int k = 1; 
for (k = 1; k < n; k++) 

// Check if the generated stem is 
// common to to all words 
if (!arr[k].contains(stem)) 
break; 
// If current substring is present in 
// all strings and its length is greater 
// than current result 
if (k == n && res.length() < stem.length()) 
res = stem; 
} 
} 
return res; 
} 

// Driver Code 
public static void main(String args[]) 
{ 
String arr[] = { "grace", "graceful", "disgraceful", "gracefully" }; 
String stems = findstem(arr); 
System.out.println(stems); 
} 
} 

Question - Given an amount convert the amount into different currencies - example- amount to us,indian,france,china and display.

Solution-

import java.util.Scanner;
import java.text.NumberFormat;
import java.util.Locale;

public class Solution {
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double payment = scanner.nextDouble();
        scanner.close();

        /* Create custom Locale for India. 
          I used the "IANA Language Subtag Registry" to find India's country code */
        Locale indiaLocale = new Locale("en", "IN");

        NumberFormat us     = NumberFormat.getCurrencyInstance(Locale.US);
        NumberFormat india  = NumberFormat.getCurrencyInstance(indiaLocale);
        NumberFormat china  = NumberFormat.getCurrencyInstance(Locale.CHINA);
        NumberFormat france = NumberFormat.getCurrencyInstance(Locale.FRANCE);

    
        System.out.println("US: "     + us.format(payment));
        System.out.println("India: "  + india.format(payment));
        System.out.println("China: "  + china.format(payment));
        System.out.println("France: " + france.format(payment));
    }
}

Question - Java Program to Print Diamond Pattern

Solution -

import java.util.*;
class dia
{
public static void main(String []args)
{
Scanner kb=new Scanner(System.in);
int n=kb.nextInt();
int i=0,j=0;
int space=n-1;
for (j = 1; j <= n; j++) 
        {
            for (i = 1; i <= space; i++) 
            {
                System.out.print(" ");
            }
            space--;
            for (i = 1; i <= 2 * j - 1; i++) 
            {
                System.out.print("*");                
            }
            System.out.println("");
        }

        space = 1;
        
        for (j = 1; j <= n - 1; j++) 
        {
            for (i = 1; i <= space; i++) 
            {
                System.out.print(" ");
            }
            space++;
            for (i = 1; i <= 2 * (n - j) - 1; i++) 
            {
                System.out.print("*");
            }
            System.out.println("");
        }
}
}

Question  - Write a program to evaluate the postfix expression

input = a mathematical expression 
example = 231*+9-
output = -4

Solution

import java.util.Stack; 
  
class main 
{ 
    static int evaluatePostfix(String exp) 
    {  
        Stack<Integer> stack=new Stack<>(); 
           
        for(int i=0;i<exp.length();i++) 
        { 
            char c=exp.charAt(i); 
              
            if(Character.isDigit(c)) 
                stack.push(c - '0'); 
              
            else
            { 
                int val1 = stack.pop(); 
                int val2 = stack.pop(); 
                  
                switch(c) 
                { 
                    case '+': 
                    stack.push(val2+val1); 
                    break; 
                      
                    case '-': 
                    stack.push(val2- val1); 
                    break; 
                      
                    case '/': 
                    stack.push(val2/val1); 
                    break; 
                      
                    case '*': 
                    stack.push(val2*val1); 
                    break; 
              } 
            } 
        } 
        return stack.pop();     
     }
           
    public static void main(String[] args)  
    { 
        String exp="231*+9-"; 
        System.out.println("postfix evaluation: "+ evaluatePostfix(exp)); 
    } 
}

Question - Given a collection of intervals, merge all the overlapping intervals, for example-

given - [1,3] [2,6] [8,10] [15,18]
output- [1,6] [8,10] [15,18]

Solution-

import java.util.*;
class main
{
public static void main(String []args)
{
Scanner kb=new Scanner(System.in);
int n=kb.nextInt();
int arr1[]=new int[n];
int arr2[]=new int[n];
int arr3[]=new int[n];
int arr4[]=new int[n];
int i,j,k=0;
int temp1=0,temp2=0;

for(i=0;i<n;i++)
{
arr1[i]=kb.nextInt();
arr2[i]=kb.nextInt();
}

for(j=0;j<n-1;j++)
{
if(arr2[j]>arr1[j+1])
{
System.out.println("Found at "+ arr1[j+1] +" and "+ arr2[j]);
temp1=j;
temp2=j+1;

}

}
       }
}

Question - Given an array of N elements, determine whether a given set can be partitioned into two subsets such that the sum of elements in both subsets is same.

input format- Input to contain a number of elements N, next line contain the N elements
5
3 1 5 9 12
Output format- Can be divided into two subsets of an equal sum

Solution-

import java.io.*; 
  
class main
{ 
    static boolean isSubsetSum (int arr[], int n, int sum) 
    { 

        if (sum == 0) 
            return true; 
        if (n == 0 && sum != 0) 
            return false; 
  

        if (arr[n-1] > sum) 
            return isSubsetSum (arr, n-1, sum); 
  

        return isSubsetSum (arr, n-1, sum) || 
               isSubsetSum (arr, n-1, sum-arr[n-1]); 
    } 
  

    static boolean findPartition (int arr[], int n) 
    { 

        int sum = 0; 
        for (int i = 0; i < n; i++) 
            sum += arr[i]; 
  

        if (sum%2 != 0) 
            return false; 
  

        return isSubsetSum (arr, n, sum/2); 
    } 
  
    public static void main (String[] args) 
    { 
  
        int arr[] = {3, 1, 5, 9, 12}; 
        int n = arr.length; 
        if (findPartition(arr, n) == true) 
            System.out.println("Can be divided into two "+ 
                                "subsets of equal sum"); 
        else
            System.out.println("Can not be divided into " + 
                                "two subsets of equal sum"); 
    } 
} 

__________________________________________________

source- geeksforgeeks.com

Question - You Are given an alphanumeric String. Write a program to find the sum of numbers in the given string.

input format-51b6de19
output format -21

Solution

import java.util.Scanner;
class main
{
public static void main(String [] args)
{
Scanner kb=new Scanner(System.in);
String word=kb.nextLine();
int length=word.length();
int sum=0;
for(int i=0;i<length;i++)
{
if(Character.isDigit(word.charAt(i)))
{
int temp=Character.getNumericValue(word.charAt(i));
sum=sum+temp;
}
}
System.out.println("The sum is" +sum);
}
}

Wednesday, 26 December 2018

CSE1007 - Wintersem 2018-19

Question- Slow learner problem
Write a program to demonstrate the knowledge of students in multidimensional arrays and looping
constructs.
Eg., If there are 4 batches in BTech - “CSE1007” course, read the count of the slow learners (who have scored <25) in each batch. Tutors should be assigned in the ratio of 1:4 (For every 4 slow learners, there should be one tutor). Determine the number of tutors for each batch. Create a 2-D jagged array with 4 rows to store the count of slow learners in the 4 batches. The number of columns in each row should be equal to the number of groups formed for that particular batch ( Eg., If there are 23 slow learners in a batch, then there should be 6 tutors and in the jagged array, the corresponding row should store 4, 4, 4, 4, 4,3). Use for-each loop to traverse the array and print the details. Also print the number of batches in which all tutors have exactly 4 students.

/*
 * 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 practice.apps;

/**
 *
 * @author Naman Khurpia
 */
import java.util.Scanner;
public class faltu
{
    public static void main(String arr[])
    {
        Scanner b= new Scanner(System.in);
        int content,z;
        int ans=0;

        int a[][]=new int[4][];
        for(int i=0;i<4;i++)
        {
            System.out.println("Enter the number of slow learners in the batch "+i);
            content=b.nextInt();
            if(content%4==0)
                z=content/4;
            else
                z=content/4+1;
         
            a[i]=new int[z];

            for(int j=0;j<z;j++)
            {
                if(content>4)
                {
                    a[i][j]=4;
                    content=content-4;
                }
                else
                {
                    a[i][j]=content;
                    content=0;
                }
            }
        }
        System.out.println("\n\nThe Contents of Jagged array are");
        for(int i=0;i<4;i++)
        {
            for(int n:a[i])
            {
                System.out.print(n);
                if(n==4)
                    ans++;
            }
            System.out.println();
        }
        System.out.println("\n\nThe number of Tutors with 4 students are (ans) = "+ans);

    }

}




Question
Write a program to demonstrate the knowledge of students in String handling. Eg., Write a program to read a chemical equation and find out the count of the reactants and the products. Also display the count of the number of molecules of each reactant and product. Eg., For the equation, 2NaOH + H2SO4 -> Na2SO4+ 2H2O, the O/P should be as follows. Reactants are 2 moles of NaOH, 1 mole of H2SO4. Products are 1 mole of Na2SO4 and 2 moles of H2O.


Solution-
/*
 * 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 practice.apps;

import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.*;
/**
 *
 * @author Naman Khurpia
 */
class chemicals{
ArrayList<String> arrl1 = new ArrayList<String>(50); ArrayList<String> arrl2 = new
ArrayList<String>(50);
void add(String substring) {
throw new UnsupportedOperationException("Not supported yet."); //To change body ofgenerated methods, choose Tools | Templates.
}
}
public class moles {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String equation = scan.nextLine();
String reactants = " ";
String prod = " ";
for(int i=0;i<equation.length();i++){
if((equation.charAt(i)=='-') && (equation.charAt(i+1)=='>')){
reactants = equation.substring(0, i);
reactants = reactants.replaceAll("\\s","");
enter(reactants,"Reactants");
prod = equation.substring(i+2,equation.length());
prod = prod.replaceAll("\\s","");
enter(prod,"Product");
}
}
}
public static void enter(String s,String tpe){
chemicals total = new chemicals();
for(int i=0;i<s.length()-1;i++){
for(int j=i+1;j<s.length();j++){
if((s.charAt(j)=='+')){
String check=s.substring(i,j);
if(check.charAt(check.length()-1)=='+')
total.arrl1.add(check.substring(0,check.length()));
else
total.arrl1.add(check.substring(0,check.length()));
i=j+1;
}
else if((s.length()-1==j)){
String check2=s.substring(i,j+1);
if(check2.charAt(check2.length()-1)=='+')
total.arrl1.add(check2.substring(0,check2.length()));
else
total.arrl1.add(check2.substring(0,check2.length()));
i=j+1;
}
}
}
System.out.print( tpe+" are ");
for(int i=0;i<total.arrl1.size();i++){
Pattern p = Pattern.compile("^\\d*");
Matcher m = p.matcher(total.arrl1.get(i));
if (m.find()) {
if(!m.group().equals(""))
System.out.print(m.group(0)+" moles of"+total.arrl1.get(i).substring(m.group(0).length(),total.arrl1.get(i).length())+" ");
else
System.out.print("1 moles of "+total.arrl1.get(i)+" ");
}
}
System.out.println();
}
}



Screenshot-

GPT4ALL - A new LLaMa (Large Language Model)

posted 29th March, 2023 - 11:50, GPT4ALL launched 1 hr ago  What if we use AI generated prompt and response to train another AI - Exactly th...