Wednesday, September 11, 2019

Reverse Linked list in java

To reverse a linked list we need to change the pointers so in the reverseList method i have taken 3 pointers next, prev, current,
current pointer is head at starting and next and prev are null.
in while loop we will check current pointer if it is null or now if its null it means it reached to last of the list and that time while loop will break.
inside while loop first we are assigning next = current.next here next will hold the next pointer of current and current.next = prev it will change the pointer and make the previous node as next node for the current, then prev = current assign current node to prev node and current = next, this will be keep running till current =null and then loop will break, at last our head = prev , prev node will be assigned to head because at this time last node is prev and current node is null.


public class ReverseLinkedList {


Node head;
class Node{
int data;
Node next;
Node(int data){
this.data = data;
next = null;
}
}

void addData(int d) {
Node newNode = new Node(d);
if(head == null)head = newNode;
else {
Node temp = head;
while(temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
}

void printList() {
Node temp = head;
while(temp !=null) {
System.out.print(temp.data+" ");
temp = temp.next;
}
}


 void reverseL() {
reverseList(head);
}
void reverseList(Node node) {
Node prev = null;
        Node current = node;
        Node next = null;
        while (current != null) {
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        head = prev;
}
public static void main(String[] args) {
ReverseLinkedList l = new ReverseLinkedList();
for(int i=1;i<=5;i++) {
l.addData(i);
}

l.printList();
System.out.println();
l.reverseL();
l.printList();

}
}

Saturday, August 24, 2019

Store User type Object to HashSet in java

HashSet dnt store duplicates. here employee object storing in hashset mean based on id duplicate object can't be store in HashSet. so override equals and hashCode methods for id.


import java.util.HashSet;
import java.util.Set;

class Emp{
int id;
String name;

Emp(int id, String name){
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Emp [id=" + id + ", name=" + name + "]";
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Emp other = (Emp) obj;
if (id != other.id)
return false;
return true;
}
 }

  public class EmployeHashSet {
public static void main(String[] args) {
Set<Emp> set = new HashSet<>();
Emp e1 = new Emp(1,"AAA");
Emp e2 = new Emp(1,"VVV");
Emp e3 = new Emp(2,"V3VV");

set.add(e1);
set.add(e2);
set.add(e3);

System.out.println(set);

}
}

Output : [Emp [id=1, name=AAA], Emp [id=2, name=V3VV]]






Sunday, August 18, 2019

Creating binary tree

Creating binary tree.




class Tree{
BTree root;
List<String> result = new ArrayList<String>();
class BTree{
BTree left;
BTree right;
int data;
BTree(int data){
this.data = data;
left = null;
right = null;
}
}
void insert(int data) {
root = insrt(root,data);
}

public BTree insrt(BTree root,int data) {
if(root == null) {
root = new BTree(data);
return root;
}
if(data<root.data ) {
root.left = insrt(root.left, data);
}else {
root.right = insrt(root.right, data);
}
return root;
}


public void inOrder(BTree root) {
if(root == null)return;
inOrder(root.left);
System.out.print(root.data+" ");
inOrder(root.right);
}
public void preOrder(BTree root) {
if(root == null)return;
System.out.print(root.data+" ");
preOrder(root.left);
preOrder(root.right);
}
public void postOrder(BTree root) {
if(root == null)return;
postOrder(root.left);
postOrder(root.right);
System.out.print(root.data+" ");
}

void findNumber(BTree root, int data) {
if (root == null)
return;
if (root.data == data) {
result.add("Yes");
} else {
findNumber(root.left, data);
findNumber(root.right, data);
}
}
}
public class BinaryTree {

public static void main(String[] args) {
Tree t = new Tree();
int[] arr = {50,30,20,40,70,60,80};
for(int i=0;i<arr.length;i++) {
t.insert(arr[i]);
}

t.inOrder(t.root);
System.out.println();
t.preOrder(t.root);
System.out.println();
t.postOrder(t.root);
t.findNumber(t.root, 50);
if(t.result.contains("Yes")) {
System.out.println("yes");
}else {
System.out.println("No");
}
}

}

Picking Numbers

Given an array of integers, find and print the maximum number of integers you can select from the array such that the absolute difference between any two of the chosen integers is less than or equal to . For example, if your array is , you can create two subarrays meeting the criterion:  and . The maximum length subarray has  elements.
Function Description
Complete the pickingNumbers function in the editor below. It should return an integer that represents the length of the longest array that can be created.
pickingNumbers has the following parameter(s):
  • a: an array of integers

public static int pickingNumbers(List<Integer> a) {
Collections.sort(a);
List<List<Integer>> resultList = new ArrayList<List<Integer>>();
List<Integer> tempList = null;
for (int i = 0; i < a.size(); i++) {
tempList = new ArrayList<Integer>();
for (int j = i; j < a.size(); j++) {
if (a.get(j) - a.get(i) <= 1) {
tempList.add(a.get(j));
} else {
resultList.add(tempList);
tempList = new ArrayList<Integer>();
break;
}
}
resultList.add(tempList);
}
int max =0;
for(int i=0;i<resultList.size();i++) {
if(resultList.get(i).size()>max)max = resultList.get(i).size();
}
//System.out.println(resultList);
return max;
}

Non Unique Numbers

Find Non Unique Numbers from an given array.
Exp : [1,3,1,4,5,6,3,2 ] in this array [1,3] are non unique number.

public class NonUniqueNumbers  {

public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,3,1,4,5,6,3,2);
System.out.println(getCount(list));
}

private static int getCount(List<Integer> numbers) {
int result = 0;
    Map<Integer, Integer> numberMap = new HashMap<>();
    for(int i=0;i<numbers.size();i++){
        if(numberMap.containsKey(numbers.get(i))){
            numberMap.put(numbers.get(i), numberMap.get(numbers.get(i))+1);
        }else{
        numberMap.put(numbers.get(i), 1);
        }
    }
    for(Map.Entry<Integer, Integer> mp:numberMap.entrySet()){
        if((int)mp.getValue() > 1){
            result++;
        }
    }
    return result;
}

}



Library Fine

Your local library needs your help! Given the expected and actual return dates for a library book, create a program that calculates the fine (if any). The fee structure is as follows:
  1. If the book is returned on or before the expected return date, no fine will be charged (i.e.: .
  2. If the book is returned after the expected return day but still within the same calendar month and year as the expected return date, .
  3. If the book is returned after the expected return month but still within the same calendar year as the expected return date, the .
  4. If the book is returned after the calendar year in which it was expected, there is a fixed fine of .
Charges are based only on the least precise measure of lateness. For example, whether a book is due January 1, 2017 or December 31, 2017, if it is returned January 1, 2018, that is a year late and the fine would be .

static int libraryFine(int d1, int m1, int y1, int d2, int m2, int y2) {
if(d1 == d2 && m1 == m2 && y1 == y2) {
return 0;
}else if(d1 - d2>0 && m1 == m2 && y1 == y2) {
return (d1-d2)*15;
}else if(m1-m2>0 && y1 == y2) {
return (m1-m2)*500;
}else if(y1-y2>0) {
return 10000;
}else {
return 0;
}
    }