Showing posts with label intermediate. Show all posts
Showing posts with label intermediate. Show all posts

Binary Search in Java using Iteration and Recursion

Problem:

Create a binary search app in java using iteration and recursion.

Note: Binary search only works with sorted list of numbers.

Output:

Enter a target int
4
Target found iteratively!
Target found recursively!



Solution:

package binarySearchApp;

import java.util.Scanner;

public class BinarySearchApp {

 public static void main(String[] args) {
  int[] pool = {4,8,9,13,17,22};
  int target;
  Scanner scan = new Scanner(System.in);
  
  System.out.println("Enter a target int");
  target = scan.nextInt();
  boolean found;
  
//********************iterative version *************************   
  found = binarySearch_iter(pool, target);
  if (found) 
   System.out.println("Target found iteratively!");
  else
   System.out.println("Target not found iteratively!");
  
//********************recursive version ************************* 
  found = binarySearch_rec(pool, target, 0, pool.length-1);
  if (found) 
   System.out.println("Target found recursively!");
  else
   System.out.println("Target not found recursively!");
  
 }
 
//********************iterative method ************************* 
 private static boolean binarySearch_iter (int[] pool, int target) {
  
  int min = 0, max = pool.length-1, mid;
  boolean found = false;
  
  while (!found && min <= max) {
   mid = (min+max)/2;
   if (pool [mid] == target)
    found = true;
   else if (pool [mid] < target) 
    min = mid +1;
   else 
    max = mid -1;
   
  }
  return found;
 }

//********************recursive method ************************* 
 private static boolean binarySearch_rec (int[] pool, int target, int min, int max) {
  if (min > max)
   return false;
  else {
   int mid = (min + max)/2;
   if (pool[mid] == target)
    return true;
   else if (pool[mid] < target)
    return binarySearch_rec (pool, target, mid+1, max);
   else
    return binarySearch_rec (pool, target, min, mid-1);
  }
 }

}
Read More

Computer Fibonnaci Numbers with BigInteger in java

Problem:

Create a Fibonnaci program in java that calculate the fibbonaci numbers using BigInteger class. Include also iterative and recursive methods for the sake of comparaison.

Output:

Enter a positive int value (q to quit):
40
Iterative Fibonacci: 102334155
Recursion Fibonacci: 102334155
Duration: 2088
Accurate Fibonacci: 102334155
Enter a positive int value (q to quit):
q




Solution:

import java.math.BigInteger;
import java.util.Scanner;

public class FibonacciApp {

 public static void main(String[] args) {
  
  Scanner scan = new Scanner(System.in);
  int n;
  String n_str; 
  long fib_iter, fib_rec, time_in, time_out;
  BigInteger fib_acc;
  
  System.out.println("Enter a positive int value (q to quit):");
  n_str = scan.nextLine();
  
  while(!n_str.equalsIgnoreCase("q")) {
   try {
    n = Integer.parseInt(n_str);
    fib_iter = fibonacci_iter(n);
    System.out.println("Iterative Fibonacci: " + fib_iter);
    
    time_in = System.currentTimeMillis();
    
    fib_rec = fibonacci_rec(n);
    System.out.println("Recursion Fibonacci: " + fib_rec);
    
    time_out = System.currentTimeMillis();
    System.out.println("Duration: " + (time_out-time_in));
    
    fib_acc = fibonacci_acc(n);
    System.out.println("Accurate Fibonacci: " + fib_acc);
    
   } catch (NumberFormatException e) {
    System.out.println("Input must be numeric. Try Again");
   } 
   System.out.println("Enter a positive int value (q to quit):");
   n_str = scan.nextLine();
  }
  
  
 }
 
 private static long fibonacci_iter(int n) {
  
  if (n==0 || n==1) return n;
  else { 
   long previousprev = 0;
   long prev =1; 
   long current = 1L;
   
   for (int i=2 ; i <=n ; i++) {
   current = previousprev + prev; 
   previousprev = prev;
   prev = current;
   
   
   }
  return current;
  }
  
 }
 
 private static long fibonacci_rec(int n) {
  if (n ==0 || n==1 ) 
   return n;
  else 
   return fibonacci_rec(n-1)  + fibonacci_rec(n-2)
; }
 
 private static BigInteger fibonacci_acc(int n) {
  if (n==0 || n==1) 
   return BigInteger.valueOf(n);
  else {
   BigInteger prevprev = BigInteger.ZERO;
   BigInteger prev = BigInteger.ONE;
   BigInteger current = BigInteger.ONE;
   
   for (int i = 2; i <= n ; i++) {
    current = prevprev.add(prev);
    prevprev = prev;
    prev = current;
   }
   return current;
  }
 }
}
Read More

Write a java application that removes duplicates from an array using HashSet and Treeset in Java

Problem:

Write a java application that removes duplicates from an array using HashSet and Treeset in Java

Output:

[Blue, Red, Green, Orange]
[Blue, Green, Orange, Red]
HeadSet: [Blue, Green]
TailSet: [Orange, Red]
First: Blue
Last: Red

Solution:

import java.util.Arrays;
import java.util.HashSet;
import java.util.TreeSet;

public class RemovingDuplicates {

 public static void main(String[] args) {
  String[] colors = {"Red", "Red", "Red", "Green", "Blue", 
    "Green", "Blue", "Orange"
  };
  
  HashSet<String> colorsAsHashSet = 
    new HashSet<>(Arrays.asList(colors));
    
  System.out.println(colorsAsHashSet);
  
  TreeSet<String> colorsAsTreeSet = 
    new TreeSet<>(Arrays.asList(colors));
  System.out.println(colorsAsTreeSet);
  
  System.out.println("HeadSet: " + 
    colorsAsTreeSet.headSet("Orange"));
  
  System.out.println("TailSet: " + 
    colorsAsTreeSet.tailSet("Orange"));
  
  System.out.println("First: " + colorsAsTreeSet.first());
  System.out.println("Last: " + colorsAsTreeSet.last());
 }

}
Read More

Reverse arrays using Stacks in java

Problem:

Create a java program that reverses an array in java using stacks.

Output:

90 78 40 9 6 3 1
10.5 6.9 3.2 2.5

Solution:

import java.util.Stack;

public class ReverseArrayApp {

 public static void main(String[] args){
  Integer[] arr1 = {1, 3, 6, 9, 40, 78, 90};
  Double[] arr2 = {2.5, 3.2, 6.9, 10.5};
  
 
  Number[] arr1_rev = reverse(arr1);
  Number[] arr2_rev = reverse(arr2);
  
  
  for(Number eltInt : arr1_rev) 
   System.out.print(eltInt + " ");
  System.out.println();
  for(Number eltDouble : arr2_rev)
   System.out.print(eltDouble + " ");
  }

 
 private static Number[] reverse(Number[] arr) {
  Stack<Number> temp = new Stack<>();
  Number [] output = new Number[arr.length];
  
  for(Number elt: arr) 
   temp.push(elt);
  
  int index = 0;
  
  while(!temp.empty()){
   output[index] = temp.pop();
   index++;
  }
  
  return output;
  
 }
 
 
 }
 
Read More

Computing the polynomial mathematical function in java

Problem:

A polynomial function is a very famous mathematical function.
The greatest exponent, n, is called the degree of the polynomial. For example, p(x) = 7x4 2 is a
polynomial of degree 4. The simplest polynomials are constant polynomials such as p(x) = 6
(degree 0) and linear polynomials such as p(x) = 9x + 6 (degree 1). The unique zero polynomial
p(x) = 0 is defined to have degree 1. In this section we present a Polynomial class whose
instances represent mathematical polynomials and which supports the usual algebraic operations
on polynomials.
A polynomial can be regarded as a sum of distinct terms. A term is a mathematical function of
the form t (x) = cxe, where c is any real number and e is any nonnegative integer. The number c is
called the coefficient, and the number e is called the exponent.
To define a class whose objects represent polynomials, we use a linked list of Term objects.
For example, the polynomial p(x) = 3x2 2x + 5 could be represented as a list of three elements,
where the first element represents the term 3x2, the second element represents the term 2x, and
the third element represents the (constant) term 5.

Write a java program that computes the polynomial function.

Output:

Not applicable

Solution:

public class Polynomial {
private List<Term> list = new LinkedList<Term>();
public static final Polynomial ZERO = new Polynomial();
private Polynomial() { // default constructor
}
public Polynomial(double coef, int exp) {
if (coef != 0.0) {
list.add(new Term(coef, exp));
}
}
public Polynomial(Polynomial p) { // copy constructor
for (Term term : p.list) {
this.list.add(new Term(term));
}
}
public Polynomial(double... a) {
for (int i=0; i<a.length; i++) {
if (a[i] != 0.0) {
list.add(new Term(a[i], i));
}
}
}
public int degree() {
if (list.isEmpty()) {
return -1;
} else {
return list.get(list.size()-1).exp;
}
public boolean isZero() {
return list.isEmpty();
}
public Polynomial plus(Polynomial p) {
if (this.isZero()) {
return new Polynomial(p);
}
if (p.isZero()) {
return new Polynomial(this);
}
Polynomial q = new Polynomial();
ListIterator<Term> it = list.listIterator();
ListIterator<Term> itp = p.list.listIterator();
while (it.hasNext() && itp.hasNext()) {
Term term = it.next();
Term pTerm = itp.next();
if (term.exp < pTerm.exp) {
q.list.add(new Term(term));
itp.previous();
} else if (term.exp == pTerm.exp) {
q.list.add(new Term(term.coef + pTerm.coef, term.exp));
} else { // (term.exp > pTerm.exp)
q.list.add(new Term(pTerm));
it.previous();
}
}
while (it.hasNext()) {
q.list.add(new Term(it.next()));
}
while (itp.hasNext()) {
q.list.add(new Term(itp.next()));
}
return q;
}
public String toString() {
if (this.isZero()) {
return "0";
}
Iterator<Term> it = list.iterator();
StringBuilder buf = new StringBuilder();
boolean isFirstTerm = true;
while (it.hasNext()) {
Term term = it.next();
double c = term.coef;
int e = term.exp;
if (isFirstTerm) {
buf.append(String.format("%.2f", c));
isFirstTerm = false;
} else {
if (term.coef < 0) {
buf.append(String.format(" - %.2f", -c));
} else {
buf.append(String.format(" + %.2f", c));
}
}
if (e == 1) {
buf.append("x");
} else if (e > 1) {
buf.append("x^" + e);
}
}
return buf.toString();
}
private static class Term {
private double coef;
private int exp;
public Term(double coef, int exp) {
if (coef == 0.0 || exp < 0) {
throw new IllegalArgumentException();
}
this.coef = coef;
this.exp = exp;
}
public Term(Term that) { // copy constructor
this(that.coef, that.exp);
}
}
}
Read More

Implementing the Josephus Problem in Java

Problem:

This problem is based upon a report by the historian Joseph ben Matthias (Josephus) on the
outcome of a suicide pact that he had made between himself and 40 soldiers as they were
besieged by superior Roman forces in 67 A.D. Josephus proposed that each man slay his neighbor.
This scheme necessarily leaves one to kill himself. Josephus cleverly contrived to be that
one, thus surviving to tell the tale.

Output:

[A, B, C, D, E, F, G, H, I, J, K]
A killed B
C killed D
E killed F
G killed H
I killed J
K killed A
C killed E
G killed I
K killed C
G killed K
The lone survivor is G

Solution:

public class Josephus {
public static final int SOLDIERS = 8;
public static final String ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static void main(String[] args) {
Ring<String> ring = new Ring<String>();
for (int i=0; i<SOLDIERS; i++) {
ring.add(ALPHA.substring(i, i+1));
}
System.out.println(ring);
Iterator<String> it = ring.iterator();
String killer = it.next();
while (ring.size() > 1) {
String victim = it.next();
System.out.println(killer + " killed " + victim);
it.remove();
killer = it.next();
}
System.out.println("The lone survivor is " + it.next());
}
}
Read More

Using the sublist() Method as a Range-View Operation

Problem:

Use the sublist() in a java program as Method as a Range-View Operation

Output:

[A, B, C, D, E, F, G, H, I, J]
list.subList(3,8): [D, E, F, G, H]
list.subList(3,8).get(2): F
list.subList(3,8).set(2,"B"):
[A, B, C, D, E, B, G, H, I, J]
list.indexOf("B"): 1
list.subList(3,8).indexOf("B"): 2
[A, B, C, D, E, B, G, H, I, J]
Collections.reverse(list.subList(3,8)):
[A, B, C, H, G, B, E, D, I, J]
Collections.rotate(list.subList(3,8), 2):
[A, B, C, E, D, H, G, B, I, J]
Collections.fill(list.subList(3,8), "X"):
[A, B, C, X, X, X, X, X, I, J]
[A, B, C, I, J]

Solution:

public class TestSubList {
public static void main(String[] args) {
List list = new ArrayList();
Collections.addAll(list, "A","B","C","D","E","F","G","H","I","J");
System.out.println(list);
System.out.println("list.subList(3,8): " + list.subList(3,8));
System.out.println("list.subList(3,8).get(2): "
+ list.subList(3,8).get(2));
System.out.println("list.subList(3,8).set(2,\"B\"):");
list.subList(3,8).set(2, "B");
System.out.println(list);
System.out.println("list.indexOf(\"B\"): " + list.indexOf("B"));
System.out.println("list.subList(3,8).indexOf(\"B\"): "
+ list.subList(3,8).indexOf("B"));
System.out.println(list);
System.out.println("Collections.reverse(list.subList(3,8)):");
Collections.reverse(list.subList(3,8));
System.out.println(list);
1System.out.println("Collections.rotate(list.subList(3,8), 2):");
Collections.rotate(list.subList(3,8), 2);
System.out.println(list);
System.out.println("Collections.fill(list.subList(3,8), \"X\"):");
Collections.fill(list.subList(3,8), "X");
System.out.println(list);
list.subList(3,8).clear();
System.out.println(list);
}
}
Read More

Testing a List Class in Java

Problem:

Write a program that implements an LinkedQueue in java.

Output:

[GB, DE, FR, ES]
[GB, DE, FR, DE, ES]
list.get(3): DE
list.indexOf("DE"): 1
list.indexOf("IE"): -1
list.subList(1, 5): [DE, FR, DE, ES]
[GB, FR, DE, ES]

Solution:

public class TestStringList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Collections.addAll(list, "GB", "DE", "FR", "ES");
System.out.println(list);
list.add(3, "DE");
System.out.println(list);
System.out.println("list.get(3): " + list.get(3));
System.out.println("list.indexOf(\"DE\"): " + list.indexOf("DE"));
System.out.println("list.indexOf(\"IE\"): " + list.indexOf("IE"));
System.out.println("list.subList(1, 5): " + list.subList(1, 5));
list.remove("DE");
System.out.println(list);
}
}
Read More

Implementing an LinkedQueue class in java

Problem:

Write a program that implements an LinkedQueue in java.

Output:

Not available.

Solution:

public class LinkedQueue<E> implements Queue<E> {
private Node<E> head = new Node<E>(); // dummy node
private int size;

public void add(E element) {
head.prev = head.prev.next = new Node<E>(element, head.prev, head);
++size;
}

public E element() {
if (size == 0) {
throw new java.util.EmptyStackException();
}
return head.next.element; // front of queue // next <--> prev
}
public boolean isEmpty() {
return (size == 0);
}

public E remove() {
if (size == 0) {
throw new java.util.EmptyStackException();
}
E element = head.next.element; // next <--> prev
head.next = head.next.next; // next <--> prev
head.next.prev = head; // next <--> prev
--size;
return element;
}
public int size() {
return size;
}
private static class Node<E> {
E element;
Node<E> prev;
Node<E> next;
Node() {
this.prev = this.next = this;
}
Node(E element, Node<E> prev, Node<E> next) {
this.element = element;
this.prev = prev;
this.next = next;
}
}
}
Read More

Implementing an ArrayQueue in java

Problem:

Write a program that implements an ArrayQueue in java.

Output:

Not available.

Solution:

public class ArrayQueue<E> implements Queue<E> {
private E[] elements;
private int front;
private int back;
private static final int INITIAL_CAPACITY = 4;

public ArrayQueue() {
elements = (E[]) new Object[INITIAL_CAPACITY];
}

public ArrayQueue(int capacity) {
elements = (E[]) new Object[capacity];
}

public void add(E element) {
if (size() == elements.length - 1) {
resize();
}
elements[back] = element;
if (back < elements.length - 1) {
++back;
} else {
back = 0; //wrap
}
}

public E element() {
if (size() == 0) {
throw new java.util.NoSuchElementException();
}
return elements[front];
}

public boolean isEmpty() {
return (size() == 0);
}

public E remove() {
if (size() == 0) {
throw new java.util.NoSuchElementException();
}
E element = elements[front];
elements[front] = null;
++front;
if (front == back) { // queue is empty
front = back = 0;
}
Read More

Testing a String Queue in Java

Problem:

Write a program that tests a String Queue in java.

Output:

[GB, DE, FR, ES]
queue.element(): GB
queue.remove(): GB
[DE, FR, ES]
queue.remove(): DE
[FR, ES]
queue.add("IE"):
[FR, ES, IE]
queue.remove(): FR
[ES, IE]

Solution:

public class TestStringStack {
public static void main(String[] args) {
Queue<String> queue = new ArrayDeque<String>();
queue.add("GB");
queue.add("DE");
queue.add("FR");
queue.add("ES");
System.out.println(queue);
System.out.println("queue.element(): " + queue.element());
System.out.println("queue.remove(): " + queue.remove());
System.out.println(queue);
System.out.println("queue.remove(): " + queue.remove());
System.out.println(queue);
System.out.println("queue.add(\"IE\"): ");
queue.add("IE");
System.out.println(queue);
System.out.println("queue.remove(): " + queue.remove());
System.out.println(queue);
}
}
Read More

How to implement your own array list in java

Problem:

Implement your own array list in java.

Output:

Not applicable.

Solution:

import java.util.Arrays;

public class KWArrayList<E>
{
  private static final int INITIAL_CAPACITY = 10;
  
  //Underlying data array
  private E[] theData;
  
  //Current size
  private int size = 0;
  
  //Current Capacity
  private int capacity = 0;
  
  
  @SuppressWarnings("unchecked")
  public KWArrayList()
  {
    capacity = INITIAL_CAPACITY;
    theData = (E[]) new Object[capacity];
  }
  
  public boolean add(E anEntry)
  {
    if (size == capacity)
      reallocate();
    theData[size] = anEntry;
    size++;
    return true;
  }
  
  public void add(int index, E anEntry)
  {
    if (index < 0 || index > size)
      throw new ArrayIndexOutOfBoundsException(index);
    if (size == capacity)
      reallocate();
    
    // Shift data in elements from index to size -1 
    for (int i = size; i > index; i--)
      theData[i] = theData[i - 1];
    
    //Insert the new Item
    theData[index] = anEntry;
    size++; 
  }
  
  public E get(int index)
  {
    if (index < 0 || index >= size)
      throw new ArrayIndexOutOfBoundsException(index);
    
    return theData[index];
  }
  
  public E set(int index, E newValue)
  {
    if (index < 0 || index >= size)
      throw new ArrayIndexOutOfBoundsException(index);
    E oldValue = theData[index];
    theData[index] = newValue;
    return oldValue;
  }
  
  public E remove(int index)
  {
    if (index < 0 || index >= size)
      throw new ArrayIndexOutOfBoundsException(index);
    E returnValue = theData[index];
    
    for(int i = index + 1; i< size;i++)
      theData[i-1] = theData[i];
    size--;
    return returnValue;
  }
  
  
  public int indexOf(Object item) {
    for (int i = 0; i < size; i++) {
    if (theData[i] == null && item == null) {
    return i;
    }
    if (theData[i].equals(item)) {
    return i;
    }
    }
    return -1;
    }
  
  private void reallocate()
  {
    capacity = 2*capacity;
    theData = Arrays.copyOf(theData, capacity);
  }
  
  public int size() {
      return size;
    }
  }
Phone L
Read More

Binary search an array method in java

Problem:

Write a the typical and most known method that performs a binary search on the array.

Output:

Not applicable.

Solution:

public static int binarySearch(int[] a, int target) {
int min = 0;
int max = a.length - 1;
while (min <= max) {
int mid = (min + max) / 2;
if (a[mid] < target) {
min = mid + 1;
} else if (a[mid] > target) {
max = mid - 1;
} else {
return mid; // target found
}
}
return -(min + 1); // target not found
}
Read More

Finding the factorial of a number using iteration in Java

Problem:

Write a java method returns the factorial of a number using iteration.

Output:

Not applicable.

Solution:

public class interation_factorial
{
  static int factorial(int n )
  {
    int f = 1 ;
    for (int i =n;i>=1;i--)
    {
      f*=i;
    }
    return f;
  }
  public static void main(String[] args)
  {
    System.out.println(factorial(5));
  }
}
Read More

Finding the length of string using iteration in Java

Problem:

Write a java method returns the length of a string using iteration.

Output:

Not applicable.

Solution:

public class string_length_interation
{
  public static int length (String str)
  {
    char c = str.charAt(0);
    int count=0;
    while (c != '\0')
    {
      count++;
      c = str.charAt(count);
    }
    
    return count;
    
  }
  
  
  public static void main(String[] args)
  {
    System.out.println(length("Few"));
  }
}
Read More

Check if a character is balanced using Stacks in Java

Problem:

Write a java method that checks if a character is balanced using stacks.

Output:

Not applicable.

Solution:

import java.util.EmptyStackException;
import java.util.Scanner;
import java.util.Stack;

public class ParanChecker
{
  public static void main(String[] args)
  {
    //We assume that the Character is balanced from the beginning
    boolean balanced = true;
    
    String OPEN = "([{";
    String CLOSE = ")]}";
    
    Scanner scan = new Scanner(System.in);
    Stack <Character> s = new Stack<Character>();
    
    System.out.println("Enter your expression:");
    String expression = scan.nextLine();
    
    try 
    {
      int index = 0;
      
      while (balanced && index < expression.length())
      {
        char nextCh = expression.charAt(index);
        if ( OPEN.indexOf(nextCh) != -1 )
          s.push(nextCh);
        else if ( CLOSE.indexOf(nextCh) != -1)
        {
          char topCh = s.pop();
          balanced = (OPEN.indexOf(topCh) == CLOSE.indexOf(nextCh));
        }
      index++;    
      }
    }
    
    catch(EmptyStackException emptyStackException)
    {
      balanced = false;
    }
    
    if ( balanced && s.empty())
      System.out.println("The Character is balanced");
    else
      System.out.println("The Character is not balanced");
  }
}
Read More

Testing the LinkedHashSet Class in Java

Problem:

Write a java problem that tests the LinkedHashSet class.

Output:

[IT, VA, SM, CH]
[IT, SM, CH]
[IT, SM, CH, VA]

Solution:

public class TestLinkedHashSet {
public static void main(String[] args) {
Set<String> ital = new LinkedHashSet<String>();
Collections.addAll(ital, "IT", "VA", "SM", "CH");
System.out.println(ital);
ital.remove("VA");
System.out.println(ital);
ital.add("VA");
System.out.println(ital);
}
}
Read More

Testing the TreeSet Class in Java

Problem:

Write a java problem that tests the treeset class.

Output:

[GB, IN, NG, PH, PK, US, ZA]
[GB, IN, KE, NG, PH, PK, US, ZA]
[GB, IN] [KE, NG, PH, PK] [US, ZA]
engl.first(): GB
engl.last(): ZA
engl.lower("KE"): IN
engl.higher("KE"): NG

Solution:

public class TestTreeSet {
public static void main(String[] args) {
NavigableSet<String> engl = new TreeSet<String>();
Collections.addAll(engl, "IN", "US", "PK", "NG", "PH", "GB", "ZA");
System.out.println(engl);
engl.add("KE");
System.out.println(engl);
SortedSet<String> head = engl.headSet("KE");
SortedSet<String> mid = engl.subSet("KE", "US");
SortedSet<String> tail = engl.tailSet("US");
System.out.printf("%s %s %s%n", head, mid, tail);
System.out.printf("engl.first(): %s%n", engl.first());
System.out.printf("engl.last(): %s%n", engl.last());
}
}
Read More

Testing the HashSet Class in Java

Problem:

Write a program that tests 10 of the 15 methods of HashSet class in java.

Output:

set.isEmpty(): true
[FR, US, RU, GB, CN]
set.size(): 5
set.contains("GB"): true
set.contains("JP"): false
set.isEmpty(): false
[FR, US, RU, BR, GB, CN]
[US, RU, BR, GB, CN]
US RU BR GB CN
[JP, FR, US, RU, GB, DE, IT, CA]
[US, RU, GB]
[BR, CN]
[US, RU, BR, GB, CN]
[]

Solution:

public class TestHashSet {
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
System.out.printf("set.isEmpty(): %b%n", set.isEmpty());
Collections.addAll(set, "CN", "FR", "GB", "RU", "US");
System.out.println(set);
System.out.printf("set.size(): %d%n", set.size());
System.out.printf("set.contains(\"GB\"): %b%n", set.contains("GB"));
System.out.printf("set.contains(\"JP\"): %b%n", set.contains("JP"));
System.out.printf("set.isEmpty(): %b%n", set.isEmpty());
set.add("BR");
System.out.println(set);
set.remove("FR");
System.out.println(set);
String[] array = set.toArray(new String[0]);
for (String string : array) {
System.out.printf("%s ", string);
}
System.out.println("");
Set<String> g8 = new HashSet<String>();
Collections.addAll(g8, "CA", "DE", "FR", "GB", "IT", "JP", "RU", "US");
System.out.println(g8);
g8.retainAll(set);
System.out.println(g8);
set.removeAll(g8);
System.out.println(set);
set.addAll(g8);
System.out.println(set);
set.clear();
System.out.println(set);
}
}
Read More

implement delete() method of linkedList

Problem:

Implement the delete() method of a Linked List

Output:

Not applicable.

Solution:

Node delete(Node start, int x) {
// precondition: the list is in ascending order;
// postconditions: the list is in ascending order, and if it did
// contains x, then the first occurrence of x has been deleted;
if (start == null || start.data > x) { // x is not in the list
return start;
} else if (start.data == x) { // x is the first element in the list
return start.next;
}
for (Node p = start; p.next != null; p = p.next) {
if (p.next.data > x) {
break; // x is not in the list
} else if (p.next.data == x) { // x is in the p.next node
p.next = p.next.next; // delete it
break;
}
}
return start;
}
Read More

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact