❌

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Collections Tasks

By: Sugirtha
19 November 2024 at 01:55

TASKS:

  • // 1. Reverse an ArrayList without using inbuilt method
  • // 2. Find Duplicate Elements in a List
  • // 3. Alphabetical Order and Ascending Order (Done in ArrayList)
  • // 4. Merge Two Lists and Remove Duplicates
  • // 5. Removing Even Nos from the List
  • // 6. Array to List, List to Array
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;


public class CollectionsInJava {
	public static void main(String[] args) {
		// 1. Reverse an ArrayList without using inbuilt method
		// 2. Find Duplicate Elements in a List 
		// 3. Alphabetical Order and Ascending Order (Done in ArrayList)
		// 4. Merge Two Lists and Remove Duplicates
		// 5. Removing Even Nos from the List
		// 6. Array to List, List to Array
		ArrayList<String> names = new ArrayList<>(Arrays.asList("Abinaya", "Ramya", "Gowri", "Swetha",  "Sugi", "Anusuya", "Moogambigai","Jasima","Aysha"));
		ArrayList<Integer> al2 = new ArrayList<>(Arrays.asList(100,90,30,20,60,40));
		
		ArrayList<Integer> al =  insertValuesIntoAL();
		System.out.println("Before Reversing ArrayList="+ al);
		System.out.println("Reversed ArrayList="+ reverseArrayList(al));
		
		System.out.println("Duplicates in ArrayList="+findDuplicates(al));
		
		System.out.println("Before Order = "+names);
		Collections.sort(names);
		System.out.println("After Alphabetical Order = " + names);
		Collections.sort(al);
		System.out.println("Ascending Order = "+ al);
		
		System.out.println("List -1 = "+al);
		System.out.println("List -2 = "+al2);
		System.out.println("After Merging and Removing Duplicates="+mergeTwoLists(al,al2));
		System.out.println("After Removing Even Nos fromt the List-1 = "+removeEvenNos(al));
		
		arrayToListViceVersa(al,new int[] {11,12,13,14,15}); //Sending ArrayList and anonymous array
	}
	
	// 1. Reverse an ArrayList without using inbuilt method
	private static ArrayList<Integer> reverseArrayList(ArrayList<Integer> al) {
		int n=al.size();
		int j=n-1, mid=n/2;
		for (int i=0; i<mid; i++) {
			int temp = al.get(i);
			al.set(i, al.get(j));
			al.set(j--, temp);
		}
		return al;
	}
	
	// 2. Find Duplicate Elements in a List 
	private static ArrayList<Integer> findDuplicates(ArrayList<Integer> al) {
		HashSet<Integer> hs = new HashSet<>();
		ArrayList<Integer> arl = new ArrayList<>();
		for (int ele:al) {
			if (!hs.add(ele)) arl.add(ele);
		}
		return arl;
	}
	
	//4. Merge Two Lists into one and Remove Duplicates
	private static HashSet<Integer> mergeTwoLists(ArrayList<Integer> arl1,ArrayList<Integer> arl2) {
		ArrayList<Integer> resAl = new ArrayList<>();
		HashSet<Integer> hs = new HashSet<>();
		hs.addAll(arl1);
		hs.addAll(arl2);
		return hs;
	}
	
	// 5. Removing Even Nos from the List
	private static ArrayList<Integer> removeEvenNos(ArrayList<Integer> al) {
		ArrayList<Integer> res = new ArrayList<>();
		Iterator itr = al.iterator();
		while (itr.hasNext()) {
			int ele = (int)itr.next();
			if (ele%2==1) res.add(ele);
		}
		return res;
	}
	
	// 6. Array to List, List to Array
	private static void arrayToListViceVersa(ArrayList<Integer> arl, int[] ar) {
		Integer arr[] = arl.toArray(new Integer[0]);
		System.out.println("Convert List to Array = " + Arrays.toString(arr));
		List<Integer> lst = Arrays.asList(arr);
		System.out.println("Convert Array to List = " +  lst);
	}
	
	private static ArrayList<Integer> insertValuesIntoAL() {
		Integer[] ar = {30,40,60,10,94,23,05,46, 40, 94};
		ArrayList<Integer> arl = new ArrayList<>();
		Collections.addAll(arl, ar);
		//Collections.reverse(al);   //IN BUILT METHOD
		return arl;
			//Arrays.sort(ar);  
		//List lst = Arrays.asList(ar);    //TBD
		//return new ArrayList<Integer>(lst);
		
	}

}

OUTPUT:

Finding SubArray

By: Sugirtha
30 October 2024 at 11:23
package taskPkg;

import java.util.Scanner;

public class SubArray {

	public static void main(String[] args) {
		// FINDING SUBARRAY AND ITS POSITION
		System.out.println("Enter a sentence to search in.");
		Scanner scn = new Scanner(System.in);
		String sentn = scn.nextLine();
		System.out.println("Enter a word to be searched.");
		String word = scn.next();
		scn.close();
		char[] sentence = sentn.toCharArray();
		char[] key = word.toCharArray();
		int n = sentence.length, m = key.length;
		int i = 0, j = 0, st = 0; // i- maintain index in the sentence, j-maintain index in key
		boolean match = false;
		while (i < n && j < m) {// 
			//System.out.println("i=" + i + "     sentence[i]=" + sentence[i] + "    j=" + j + "   key[j]=" + key[j]);
			if (sentence[i] == key[j]) { //if it matches incrementing both pos
				i++;
				j++;
				if (j == m) { //if the key reaches end, made the match and exit
					match = true;
					break;
				}
			} 
			else {    // if no match move on to the next letter, but key should start from 0
				j = 0;
				i=st+1;
				st = i;  // this is to save the starting of the subarray
			}
		}
		if (match)
			System.out.println("SubArray is found at " + st);
		else
			System.out.println("SubArray is not found");
	}
}

OUTPUT:

Playing with Char Array

By: Sugirtha
24 October 2024 at 09:23
    // 1. REMOVING UNWANTED SPACE
    // 2. CAPITALIZE EACH WORD
package taskPkg;

import java.util.Scanner;

public class PlayingWithCharAr {

	public static void main(String[] args) {
		// 1. REMOVING UNWANTED SPACE
		// 2. CAPITALIZE EACH WORD
		Scanner scn = new Scanner(System.in);
		System.out.println("Enter a sentence...");
		String sentence = scn.nextLine();
		scn.close();
		char[] sen = sentence.toCharArray();
		PlayingWithCharAr obj = new PlayingWithCharAr();
		obj.removeSpace(sen);
		obj.wordStartWithCaps(sen);
	}

	private void removeSpace(char[] words) {
		int k = 0, n = words.length;
		System.out.print("Removed unwanted spaces :");
		while (k < n && words[k] == ' ')
			k++;
		for (; k < n - 1; k++) {
			if (!(words[k] == ' ' && words[k + 1] == ' '))
				System.out.print(words[k]);
		}
		if (words[n - 1] != ' ')
			System.out.print(words[n - 1]);
		System.out.println();
	}

	private void wordStartWithCaps(char[] words) {
		int i = 0, n = words.length;
		System.out.print("Capitalize Each Word :");
		if (words[i] != ' ')
			System.out.print((char) (words[i] - 32));
		for (i = 1; i < n; i++) {
			if (words[i - 1] == ' ' && words[i] != ' ' && (words[i] >= 'a' && words[i] <= 'z'))
				System.out.print((char) (words[i] - 32));
			else
				System.out.print(words[i]);
		}
	}

}

OUTPUT:

Arrays Task

By: Sugirtha
22 October 2024 at 18:29
  1. First Letter Occurrence, Last Letter Occurrence in the given Word
  2. Print Reversed Array
  3. Cricketers array and their best score array – Give name as input and get the high score.
package taskPkg;
import java.util.Scanner;
public class ArraysBasics {
//1. PRINTING 1ST LETTER OF THE CHAR ARRAY
//2. PRINT REVERSED A CHAR ARRAY	
//3. 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArraysBasics obj = new ArraysBasics();
		Scanner scn = new Scanner(System.in);
		System.out.println("Enter a name to find its first and Last Letter.");
		String nam =  scn.next();
		char[] name = nam.toCharArray();
		System.out.println("First Letter of "+nam+" is repeated at "+obj.findFirstLtr(name));
		System.out.println("Last Letter of "+nam+" is repeated at "+obj.findLastLtr(name));
		obj.printReversedArray(name);
		System.out.println();  
		
		String[] cricketers = {"Rohit","Suryakumar","Ashwin", "Jadeja","Yashasvi"}; 
		int[] scores = {100,120,86,102,98};
		System.out.println("Enter one cricketer name to get his high score");
		String givenName = scn.next();
		System.out.println("Score for " + givenName+  " is "+obj.getScore(cricketers,scores,givenName));
		
		
	}
	private int findFirstLtr(char name[]) {
		char ch = name[0];
		for (int i=1; i<name.length; i++) {
			if (ch==name[i]) return i;
		}
		return -1;
	}
	private int findLastLtr(char name[]) {
		char ch = name[name.length-1];
		for (int i=0; i<name.length-1; i++) {
			if (ch==name[i]) return i;
		}
		return -1;
	}
	private void printReversedArray(char[] name) {
		System.out.println("Reversed Array = ");
		for (int i=name.length-1; i>=0; i--) {
			System.out.println(" "+name[i]);
		}
	}
	private int getScore(String[] name, int[] score, String givenName) {
		int n = name.length;
		for(int i=0; i<n; i++) {
			if(name[i].equals(givenName)) return score[i];
		}
		return 0;
	}
	
}

OUTPUT:

❌
❌