Using a Comparator with sorts - sorting

I'm trying to create a small program to take an input 1-3 and sorts through a list of contacts using a different sorting algorithm depending on what the user selects. I've got all my code written, but I'm having an issue when I try to use my sorts. The program runs fine if I use Collections sort, but I need to use those three algorithms.
public class {
public static void main(String[] args) {
Contact[] contacts = {
};
int input;
do{
Scanner in = new Scanner(System.in);
System.out.println("Sort by last name: [0]");
System.out.println("Sort by first name: [1]");
System.out.println("Sort by age: [2]");
System.out.println("Enter an option or 0 to end input: ");
input = in.nextInt();
if(input == 0)
{
System.out.println("Exiting...");
System.exit(input);
}
else if(input == 1)
{
Merge.sort(contacts, new LastNameComparator());
for(Contact contact : contacts)
{
System.out.println(contact);
}
}
else if(input == 2)
{
Quick.sort(contacts, new FirstNameComparator());
for(Contact contact : contacts)
{
System.out.println(contact);
}
}
else if(input == 3)
{
Heap.sort(contacts, new AgeComparator());
for(Contact contact : contacts)
{
System.out.println(contact);
}
}
else if(input > 3 || input < 0)
{
System.out.println("Invalid entry");
}
} while (input != 0);
}
}
public class Contact implements Comparable{
import java.util.Comparator;
String lastName;
String firstName;
String homeState;
Integer age;
Contact(String lastName, String firstName, String homeState, Integer age)
{
this.lastName = lastName;
this.firstName = firstName;
this.homeState = homeState;
this.age = age;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getHomeState() {
return homeState;
}
public void setHomeState(String homeState) {
this.homeState = homeState;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
#Override
public String toString() {
return String.format("%8s %8s %7s, %7d", this.lastName, this.firstName, this.homeState, this.age);
}
class FirstNameComparator implements Comparator<Contact> {
public int compare(Contact a, Contact b) {
return a.firstName.compareToIgnoreCase(b.firstName);
}
class LastNameComparator implements Comparator<Contact>{
public int compare(Contact a, Contact b) {
return a.lastName.compareToIgnoreCase(b.lastName);
}
class AgeComparator implements Comparator<Contact> {
public int compare(Contact a, Contact b) {
return a.age < b.age ? -1 : a.age == b.age ? 0 : 1;
}
}
}
}
}
Any tips are greatly appreciated. Thank you!

#Mark, here are the changes that I have made.
Its some ambiguous to use Comparator and Comparable, you can read this post and see the differences: What is the difference between compare() and compareTo()?
Your indexes were wrong, like 0 to 'Sort by last name' and 'exit'
The import is always before the class statement
There were some brackets missing
4.5 There were one main method in Heap and the other options in Assignment1 that I removed just to compile
I would advice you to use Generics to make this class, you can read more here: https://docs.oracle.com/javase/tutorial/java/generics/. In your Head.sort method, you definied it to receive a Comparable and you were passing a Comparable and a Comparator, like I said, its ambiguous. Its better to you pass a generic array (Like anything-> String[], int[], yourOwnClass[]) and provide a second argument: the Comparator! So, lets go back, changed to use generics and provide your Comparator! Now you are calling the method sort and saying to it what is the parameter to compare (Comparator). You can see the final result here:
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
Contact[] contacts = {
new Contact("Collins", "Kelly", "Illinois", 26),
new Contact("Smith", "Brandon", "Michigan", 32),
new Contact("Jones", "Mark", "California", 29),
new Contact("McDowell", "Ryan", "Texas", 30),
new Contact("Thompson", "April", "New York", 35)
};
int input;
do {
Scanner in = new Scanner(System.in);
System.out.println("Sort by last name: [1]");
System.out.println("Sort by first name: [2]");
System.out.println("Sort by age: [3]");
System.out.println("Enter an option or 0 to end input: ");
input = in.nextInt();
if (input == 0) {
System.out.println("Exiting...");
System.exit(input);
} else if (input == 3) {
Heap.sort(contacts, new Contact.AgeComparator());
for (Contact contact : contacts) {
System.out.println(contact);
}
} else if (input > 3 || input < 0) {
System.out.println("Invalid entry");
}
} while (input != 0);
}
}
Contact class:
import java.util.Comparator;
public class Contact {
String lastName;
String firstName;
String homeState;
Integer age;
Contact(String lastName, String firstName, String homeState, Integer age) {
this.lastName = lastName;
this.firstName = firstName;
this.homeState = homeState;
this.age = age;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getHomeState() {
return homeState;
}
public void setHomeState(String homeState) {
this.homeState = homeState;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
#Override
public String toString() {
return String.format("%8s %8s %7s, %7d", this.lastName, this.firstName, this.homeState, this.age);
}
static class FirstNameComparator implements Comparator<Contact> {
public int compare(Contact a, Contact b) {
return a.firstName.compareToIgnoreCase(b.firstName);
}
}
static class LastNameComparator implements Comparator<Contact> {
public int compare(Contact a, Contact b) {
return a.lastName.compareToIgnoreCase(b.lastName);
}
}
static class AgeComparator implements Comparator<Contact> {
public int compare(Contact a, Contact b) {
return a.age < b.age ? -1 : a.age == b.age ? 0 : 1;
}
}
}
Heap class
import java.util.Comparator;
public class Heap {
// This class should not be instantiated.
private Heap() { }
/**
* Rearranges the array in ascending order, using the natural order.
* #param pq the array to be sorted
*/
public static <T> void sort(T[] pq, Comparator<T> comparator) {
int n = pq.length;
for (int k = n/2; k >= 1; k--)
sink(pq, k, n, comparator);
while (n > 1) {
exch(pq, 1, n--);
sink(pq, 1, n, comparator);
}
}
private static <T> void sink(T[] pq, int k, int n, Comparator<T> comparator) {
while (2*k <= n) {
int j = 2*k;
if (j < n && less(pq, j, j+1, comparator)) j++;
if (!less(pq, k, j, comparator)) break;
exch(pq, k, j);
k = j;
}
}
private static <T> boolean less(T[] pq, int i, int j, Comparator<T> comparator) {
return comparator.compare(pq[i-1],pq[j-1]) < 0;
}
private static void exch(Object[] pq, int i, int j) {
Object swap = pq[i-1];
pq[i-1] = pq[j-1];
pq[j-1] = swap;
}
}
Merge
import java.util.Comparator;
public class Merge {
// This class should not be instantiated.
private Merge() {
}
// stably merge a[lo .. mid] with a[mid+1 ..hi] using aux[lo .. hi]
private static <T> void merge(T[] a, T[] aux, int lo, int mid, int hi, Comparator<T> comparator) {
// precondition: a[lo .. mid] and a[mid+1 .. hi] are sorted subarrays
assert isSorted(a, lo, mid, comparator);
assert isSorted(a, mid + 1, hi, comparator);
// copy to aux[]
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
}
// merge back to a[]
int i = lo, j = mid + 1;
for (int k = lo; k <= hi; k++) {
if (i > mid) a[k] = aux[j++];
else if (j > hi) a[k] = aux[i++];
else if (less(aux[j], aux[i], comparator)) a[k] = aux[j++];
else a[k] = aux[i++];
}
// postcondition: a[lo .. hi] is sorted
assert isSorted(a, lo, hi, comparator);
}
// mergesort a[lo..hi] using auxiliary array aux[lo..hi]
private static <T> void sort(T[] a, T[] aux, int lo, int hi, Comparator<T> comparator) {
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
sort(a, aux, lo, mid, comparator);
sort(a, aux, mid + 1, hi, comparator);
merge(a, aux, lo, mid, hi, comparator);
}
/**
* Rearranges the array in ascending order, using the natural order.
*
* #param a the array to be sorted
*/
public static <T> void sort(T[] a, Comparator<T> comparator) {
T[] aux = (T[])new Object[a.length];
sort(a, aux, 0, a.length - 1, comparator);
assert isSorted(a, comparator);
}
// is v < w ?
private static <T> boolean less(T v, T w, Comparator<T> comparator) {
return comparator.compare(v,w) < 0;
}
private static <T> boolean isSorted(T[] a, Comparator<T> comparator) {
return isSorted(a, 0, a.length - 1, comparator);
}
private static <T> boolean isSorted(T[] a, int lo, int hi, Comparator<T> comparator) {
for (int i = lo + 1; i <= hi; i++)
if (less(a[i], a[i - 1], comparator)) return false;
return true;
}
}
Quick
import java.util.Comparator;
public class Quick {
// This class should not be instantiated.
private Quick() {
}
/**
* Rearranges the array in ascending order, using the natural order.
*
* #param a the array to be sorted
*/
public static <T> void sort(T[] a, Comparator<T> comparator) {
sort(a, 0, a.length - 1, comparator);
assert isSorted(a, comparator);
}
// quicksort the subarray from a[lo] to a[hi]
private static <T> void sort(T[] a, int lo, int hi, Comparator<T> comparator) {
if (hi <= lo) return;
int j = partition(a, lo, hi, comparator);
sort(a, lo, j - 1, comparator);
sort(a, j + 1, hi, comparator);
assert isSorted(a, lo, hi, comparator);
}
// partition the subarray a[lo..hi] so that a[lo..j-1] <= a[j] <= a[j+1..hi]
// and return the index j.
private static <T> int partition(T[] a, int lo, int hi, Comparator<T> comparator) {
int i = lo;
int j = hi + 1;
T v = a[lo];
while (true) {
// find item on lo to swap
while (less(a[++i], v, comparator))
if (i == hi) break;
// find item on hi to swap
while (less(v, a[--j], comparator))
if (j == lo) break; // redundant since a[lo] acts as sentinel
// check if pointers cross
if (i >= j) break;
exch(a, i, j);
}
// put partitioning item v at a[j]
exch(a, lo, j);
// now, a[lo .. j-1] <= a[j] <= a[j+1 .. hi]
return j;
}
/**
* Rearranges the array so that {#code a[k]} contains the kth smallest key;
* {#code a[0]} through {#code a[k-1]} are less than (or equal to) {#code a[k]}; and
* {#code a[k+1]} through {#code a[n-1]} are greater than (or equal to) {#code a[k]}.
*
* #param a the array
* #param k the rank of the key
* #return the key of rank {#code k}
*/
public static <T> T select(T[] a, int k, Comparator<T> comparator) {
if (k < 0 || k >= a.length) {
throw new IndexOutOfBoundsException("Selected element out of bounds");
}
int lo = 0, hi = a.length - 1;
while (hi > lo) {
int i = partition(a, lo, hi, comparator);
if (i > k) hi = i - 1;
else if (i < k) lo = i + 1;
else return a[i];
}
return a[lo];
}
// is v < w ?
private static <T> boolean less(T v, T w, Comparator<T> comparator) {
return comparator.compare(v, w) < 0;
}
// exchange a[i] and a[j]
private static void exch(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
private static <T> boolean isSorted(T[] a, Comparator<T> comparator) {
return isSorted(a, 0, a.length - 1, comparator);
}
private static <T> boolean isSorted(T[] a, int lo, int hi, Comparator<T> comparator) {
for (int i = lo + 1; i <= hi; i++)
if (less(a[i], a[i - 1], comparator)) return false;
return true;
}
}

See you are passing two argument in
Heap.sort(contacts, new AgeComparator());
Now if you see sort method of Heap class
public static void sort(Comparable[] pq) {
int n = pq.length;
for (int k = n/2; k >= 1; k--)
sink(pq, k, n);
while (n > 1) {
exch(pq, 1, n--);
sink(pq, 1, n);
}
It accepts only one argument, so you need to modify it for two arguments.
Refer this in case you need: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Collections.java#Collections.sort%28java.util.List%2Cjava.util.Comparator%29

Related

how to use Java 8 for long function definitions?

I have a an object Product,
and code as below , hashSetProducts is LinkedHashSet of Products. How can I write all below using Java 8 stream function ? I understand that value of remianing will be replaced each time. I want the final value after the for loop exits.
int getRemaining(int remaining){
for(Product P : hashSetProducts){
remaining = calculate(p.qty(), p.price(), remaining, location); //
use Java 8 stream here
}
return remaining
}
private int calculate(int qty, double price, int rem, Location location){
if(rem== 0){
return 0;
}
int avail = location.get(qty, rem);
if(avail > 0){
rem = avail - rem;
}
return rem;
}
mapToLong will execute arbitrary code that returns a long. Here is an MCVE that uses your calculation verbatim:
import java.util.LinkedHashSet;
public class HelloWorld{
public static class Product {
private int qty;
private double price;
private int used;
public Product(int qty, double price, int used) {
this.qty = qty;
this.price =price;
this.used = used;
}
public int qty() {return qty;}
public double price() {return price;}
public int used() {return used;}
};
public static class Location {
public long get(int qty, int used) { return 0; };
};
public static void main(String []args) {
LinkedHashSet<Product> hashSetProducts = new LinkedHashSet();
hashSetProducts.add(new Product(1,1.0,1));
hashSetProducts.add(new Product(2,2.0,2));
hashSetProducts.add(new Product(3,3.0,3));
Location location = new Location();
long remaining = hashSetProducts.stream().mapToLong(p -> {
int qty = p.qty();
int used = p.used();
if( used == 0 )
return 0;
long rem = location.get(qty, used);
if( qty > 0)
rem = used - rem;
return rem;
}).sum();
System.out.println(remaining);
}
}

java 8 groupingBy list of list

Let say we have an object Draw:
class Draw {
private int num1, num2, num3;
public Draw (int num1, int num2, int num3) {
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
public int getNum1() {
return num1;
}
public void setNum1(int num1) {
this.num1 = num1;
}
public int getNum2() {
return num2;
}
public void setNum2(int num2) {
this.num2 = num2;
}
public int getNum3() {
return num3;
}
public void setNum3(int num3) {
this.num3 = num3;
}
public List<Integer> getResultAsList() {
return Arrays.asList(num1, num2, num3);
}
}
Now, having List of Draws, I need to get a Map where key is a number in draw and value is a count (how many times that number was drawn)
For example, having
List<Draw> drawList = Arrays.asList(new Draw(1,2,5), new Draw(1,5,6));
I want to get a map like the following: {1=2, 2=1, 5=2, 6=1}
Can I implement this using new groupingBy operations of java 8 or another new feature?
Thanks.
If I got everything right:
Map<Integer, Long> map = drawList
.stream()
.flatMap(x -> Stream.of(x.getNum1(), x.getNum2(), x.getNum3()))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(map); // {1=2, 2=1, 5=2, 6=1}
Or obviously like this:
Map<Integer, Long> map2 = drawList
.stream()
.flatMap(x -> x.getResultAsList().stream())
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Queue data structure requiring K accesses before removal

I need a specialized queue-like data structure. It can be used by multiple consumers, but each item in queue must be removed from queue after k consumers read it.
Is there any production ready implementation? Or Should I implement a queue with read-counter in each item, and handle item removal myself?
Thanks in advance.
I think this is what you are looking for. Derived from the source code for BlockingQueue. Caveat emptor, not tested.
I tried to find a way to wrap Queue, but Queue doesn't expose its concurrency members, so you can't get the right semantics.
public class CountingQueue<E> {
private class Entry {
Entry(int count, E element) {
this.count = count;
this.element = element;
}
int count;
E element;
}
public CountingQueue(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException();
}
this.items = new Object[capacity];
this.lock = new ReentrantLock(false);
this.condition = this.lock.newCondition();
}
private final ReentrantLock lock;
private final Condition condition;
private final Object[] items;
private int takeIndex;
private int putIndex;
private int count;
final int inc(int i) {
return (++i == items.length) ? 0 : i;
}
final int dec(int i) {
return ((i == 0) ? items.length : i) - 1;
}
private static void checkNotNull(Object v) {
if (v == null)
throw new NullPointerException();
}
/**
* Inserts element at current put position, advances, and signals.
* Call only when holding lock.
*/
private void insert(int count, E x) {
items[putIndex] = new Entry(count, x);
putIndex = inc(putIndex);
if (count++ == 0) {
// empty to non-empty
condition.signal();
}
}
private E extract() {
Entry entry = (Entry)items[takeIndex];
if (--entry.count <= 0) {
items[takeIndex] = null;
takeIndex = inc(takeIndex);
if (count-- == items.length) {
// full to not-full
condition.signal();
}
}
return entry.element;
}
private boolean waitNotEmpty(long timeout, TimeUnit unit) throws InterruptedException {
long nanos = unit.toNanos(timeout);
while (count == 0) {
if (nanos <= 0) {
return false;
}
nanos = this.condition.awaitNanos(nanos);
}
return true;
}
private boolean waitNotFull(long timeout, TimeUnit unit) throws InterruptedException {
long nanos = unit.toNanos(timeout);
while (count == items.length) {
if (nanos <= 0)
return false;
nanos = condition.awaitNanos(nanos);
}
return true;
}
public boolean put(int count, E e) {
checkNotNull(e);
final ReentrantLock localLock = this.lock;
localLock.lock();
try {
if (count == items.length)
return false;
else {
insert(count, e);
return true;
}
} finally {
localLock.unlock();
}
}
public boolean put(int count, E e, long timeout, TimeUnit unit)
throws InterruptedException {
checkNotNull(e);
final ReentrantLock localLock = this.lock;
localLock.lockInterruptibly();
try {
if (!waitNotFull(timeout, unit)) {
return false;
}
insert(count, e);
return true;
} finally {
localLock.unlock();
}
}
public E get() {
final ReentrantLock localLock = this.lock;
localLock.lock();
try {
return (count == 0) ? null : extract();
} finally {
localLock.unlock();
}
}
public E get(long timeout, TimeUnit unit) throws InterruptedException {
final ReentrantLock localLock = this.lock;
localLock.lockInterruptibly();
try {
if (waitNotEmpty(timeout, unit)) {
return extract();
} else {
return null;
}
} finally {
localLock.unlock();
}
}
public int size() {
final ReentrantLock localLock = this.lock;
localLock.lock();
try {
return count;
} finally {
localLock.unlock();
}
}
public boolean isEmpty() {
final ReentrantLock localLock = this.lock;
localLock.lock();
try {
return count == 0;
} finally {
localLock.unlock();
}
}
public int remainingCapacity() {
final ReentrantLock lock= this.lock;
lock.lock();
try {
return items.length - count;
} finally {
lock.unlock();
}
}
public boolean isFull() {
final ReentrantLock localLock = this.lock;
localLock.lock();
try {
return items.length - count == 0;
} finally {
localLock.unlock();
}
}
public void clear() {
final ReentrantLock localLock = this.lock;
localLock.lock();
try {
for (int i = takeIndex, k = count; k > 0; i = inc(i), k--)
items[i] = null;
count = 0;
putIndex = 0;
takeIndex = 0;
condition.signalAll();
} finally {
localLock.unlock();
}
}
}
A memory efficient way that retains the info you need:
Each queue entry becomes a
Set<ConsumerID>
so that you ensure the k times are for k distinct consumers: your app logic checks if the
set.size()==k
and removes it from queue in that case.
In terms of storage: you will have tradeoffs of which Set implementation based on
size and type of the ConsumerID
speed of retrieval requirement
E.g if k is very small and your queue retrieval logic has access to a
Map<ID,ConsumerId>
then you could have simply an Int or even a Short or Byte depending on # distinct ConsumerID's and possibly store in an Array . This is slower than accessing a set since it would be traversed linearly - but for small K that may be reasonable.

get average value from a tree of nodes

I have to implement this method:
public int GetAverage(Node root){
//TODO implement
}
this method should get average value of all nodes of root tree. where :
public interface Node {
int getValue();
List<Node> getNodes();
}
do you have any ideas how to implement this method?
thank you
my attempt:
public static double value;
public static int count;
public static double getAverage(Node root) {
count++;
value += root.getValue();
for (Node node : root.getNodes()) {
getAverage(node);
}
return value / count;
}
but how to do it without the static fields outside of the method?
Simply traverse through all nodes and remember the count and the overall sum of all values. Then calculate the average. This is an example written in Java.
public interface INode {
int getValue();
List<INode> getNodes();
}
public class Node implements INode {
private List<INode> children = new ArrayList<INode>();
private int value;
#Override
public int getValue() {
return value;
}
#Override
public List<INode> getNodes() {
return children;
}
public static int getAverage(INode root) {
if (root == null)
return 0;
Counter c = new Counter();
calculateAverage(root, c);
return c.sum / c.count;
}
class Counter {
public int sum;
public int count;
}
private static void calculateAverage(INode root, Counter counter) {
if (root == null)
return;
counter.sum += root.getValue();
counter.count++;
// recursively through all children
for (INode child : root.getNodes())
calculateAverage(child, counter);
}
}
public static double getAverage(Node root) {
Pair p = new Pair(0,0);
algo(root, p);
return ((double) p.element1) / ((double) p.element2);
}
private static void algo(Node root, Pair acc) {
for(Node child : root.getNodes()) {
algo(child, acc);
}
acc.sum += root.getValue();
acc.nbNodes++;
}
With Pair defined as follows:
public class Pair {
public int sum;
public int nbNodes;
public Pair(int elt1, int elt2) {
this.sum = elt1;
this.nbNodes = elt2;
}
}

Playing Logic about Card Game Bridge

i have have design a class whos constructor produce 52 Cards object each orject has its own color, value, isTrump(boolean) and imageIcon which store image of each card. now there is another class called Que who stores all the objects of cards into a que and shuffle them. there is a method which deals the cards object among 4 players into array of object(Cards). now i used LayeredPane and Jlabels to show them and a mouse-listener also attached with each.
Now i only want a tip how can i start each trick. means i place one card then three other robots placed there cards automatically after analysing my card on the bases of some predefined rules.
please any suggestions
public class Cards {
public Cards(int a, int b){
this.cardvalue = a;
this.color = b;
this.isTrump = false;
switch(a){
case 11: this.facevalue = 1;
break;
case 12: this.facevalue = 2;
break;
case 13: this.facevalue = 3;
break;
case 14: this.facevalue = 4;
break;
default : this.facevalue = 0;
}
switch(b){
case 1: this.colorName = "Spade";
this.CardImage= new ImageIcon(getClass().getResource("/testing/Cards/Spade/Spade ("+a+").jpg"));
break;
case 2: this.colorName = "Heart";
this.CardImage= new ImageIcon(getClass().getResource("/testing/Cards/Heart/Heart ("+a+").jpg"));
break;
case 3: this.colorName = "Diamond";
this.CardImage= new ImageIcon(getClass().getResource("/testing/Cards/Diamond/Diamond ("+a+").jpg"));
break;
default : this.colorName = "Club";
this.CardImage= new ImageIcon(getClass().getResource("/testing/Cards/Club/Club ("+a+").jpg"));
}
}
public void isTrump(){
this.isTrump = true;
}
public int getCardValue(){
return this.cardvalue;
}
public int getColor(){
return this.color;
}
public int getFaceValue(){
return this.facevalue;
}
public boolean getisTrump(){
return this.isTrump;
}
public String getColorName(){
return this.colorName;
}
public ImageIcon getCardImage(){
return this.CardImage;
}
public ImageIcon getBackSide(){
return backSide;
}
private String colorName;
private int cardvalue;
private int color; // 1 For Spade 2 For Heart 3 For Diamond 4 For Club
private int facevalue;
private boolean isTrump;
private ImageIcon CardImage;
private ImageIcon backSide = new
ImageIcon(getClass().getResource("/testing/Cards/Backside.jpg"));
}
Class which deal the card is
public class CardsInHand {
public CardsInHand(){
totalCards = new Que(52);
int a =1; int b=2;
for (int j = 0;j<52;j++){
if(j==13||j==26||j==39) a++;
if(b==15) b=2;
totalCards.put(new Cards(b,a));
b++;
}
totalCards.QueShuffle();
}
public static void Deal(){
card = new CardsInHand();
setPlayers();
}
private static void setPlayers(){
for(int i =0;i<13;i++){
Hands[0][i] = totalCards.get();
Hands[1][i] = totalCards.get();
Hands[2][i] = totalCards.get();
Hands[3][i] = totalCards.get();
}
sortingarr();
}
private static void Sorting(Cards arr[]){
//here some Sorting algorithm i used
}
private static void sortingarr(){
Sorting(Hands[0]);
Sorting(Hands[1]);
Sorting(Hands[2]);
Sorting(Hands[3]);
NumberSorting(Hands[0]);
NumberSorting(Hands[1]);
NumberSorting(Hands[2]);
NumberSorting(Hands[3]);
}
private static void NumberSorting(Cards arr[]){
//some algorith i used for number sorting
}
public static Cards[] getPlayer1(){
return Hands[0];
}
public static Cards[] getPlayer2(){
return Hands[1];
}
public static Cards[] getPlayer3(){
return Hands[2];
}
public static Cards[] getPlayer4(){
return Hands[3];
}
public static Cards[][] getAllHands(){
return Hands;
}
private final static Cards[] Player1 = new Cards[13];
private final static Cards[] Player2 = new Cards[13];
private final static Cards[] Player3 = new Cards[13];
private final static Cards[] Player4 = new Cards[13];
private final static Cards[][] Hands = {Player1,Player2,Player3,Player4};
private static Que totalCards;
private static CardsInHand card;
}
the class which is showing the cards after dealing is
public class ShowCards {
private JFrame frame = new JFrame();
private static JLayeredPane lpane = new JLayeredPane();
private static JLabel[] Player1 = new JLabel[13];
private static JLabel[] Player2 = new JLabel[13];
private static JLabel[] Player3 = new JLabel[13];
private static JLabel[] Player4 = new JLabel[13];
private static JButton button = new JButton("Deal Again");
public ShowCards()
{
CardsInHand.Deal();
frame.setPreferredSize(new Dimension(800, 640));
frame.setLayout(new BorderLayout());
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.LINE_AXIS));
frame.add(lpane, BorderLayout.CENTER);
frame.add(button);
lpane.add(button, new Integer(14), 0);
button.setBounds(200, 250, 100, 70);
button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonActionPerformed(evt);
}
});
lpane.setBounds(30, 30, 270, 270);
cardDeal();
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
static void cardDeal(){
loadJLabels1();
loadJLabels2();
loadJLabels3();
loadJLabels4();
}
static void loadJLabels1(){
int k = 30;
for(int i=0;i<13;i++){
Player1[i] = new JLabel();
Player1[i].setIcon(CardsInHand.getPlayer1()[i].getCardImage());
Player1[i].setBounds(k, 20, 170, 100);
Player1[i].setOpaque(true);
Player1[i].addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
int count = evt.getClickCount();
if (count == 1){
int Index = getIndex(Player1, (JLabel)evt.getSource());
Player1[Index].setIcon(CardsInHand.getPlayer1()[Index].getBackSide());
}
}
});
lpane.add(Player1[i], new Integer(i), 0);
k = k+30;
}
}
static void loadJLabels2(){
int k = 140;
for(int i=0;i<13;i++){
Player2[i] = new JLabel();
Player2[i].setIcon(CardsInHand.getPlayer2()[i].getCardImage());
Player2[i].setBounds(30, k, 170, 100);
Player2[i].setOpaque(true);
Player2[i].addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
int count = evt.getClickCount();
if (count == 1){
int Index = getIndex(Player2, (JLabel)evt.getSource());
Player2[Index].setIcon(CardsInHand.getPlayer2()[Index].getBackSide());
}
}
});
lpane.add(Player2[i], new Integer(i), 0);
k = k+20;
}
}
static void loadJLabels3(){
int k = 140;
for(int i=0;i<13;i++){
Player3[i] = new JLabel();
Player3[i].setIcon(CardsInHand.getPlayer3()[i].getCardImage());
Player3[i].setBounds(400, k, 170, 100);
Player3[i].setOpaque(true);
Player3[i].addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
int count = evt.getClickCount();
if (count == 1){
int Index = getIndex(Player3, (JLabel)evt.getSource());
Player3[Index].setIcon(CardsInHand.getPlayer2()[Index].getBackSide());
}
}
});
lpane.add(Player3[i], new Integer(i), 0);
k = k+20;
}
}
static void loadJLabels4(){
int k = 30;
for(int i=0;i<13;i++){
Player4[i] = new JLabel();
Player4[i].setIcon(CardsInHand.getPlayer4()[i].getCardImage());
Player4[i].setBounds(k, 500, 170, 100);
Player4[i].setOpaque(true);
Player4[i].addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
int count = evt.getClickCount();
if (count == 1){
int Index = getIndex(Player4, (JLabel)evt.getSource());
Player4[Index].setIcon(CardsInHand.getPlayer2()[Index].getBackSide());
}
}
});
lpane.add(Player4[i], new Integer(i), 0);
k = k+30;
}
}
private void buttonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
CardsInHand.Deal();
cardDeal();
}
static int getIndex(JLabel[] arr, JLabel obj){
int index=0;
for(JLabel cmp: arr){
if(cmp == obj) break;
index++;
}
return index;
}
}
Now i also creat a player class which creat three Bots to play and one will be the human. the class is as
public class Players {
public Players(Cards[] arr){
this.scoreInHand = getScoreInHand(arr);
getCardOfEachSuit(arr, this.cardsOfEachSuit);
this.isBalanceHand = getIsBalanceHand(arr);
this.longestSuit = getLongestSuit(arr);
this.numberOfTrump = getNumberOfTrump(arr);
this.smallestSuit = getSmallestSuit(arr);
this.strongestSuit = getStrongestSuit(arr);
this.weakestSuit = getWeakestSuit(arr);
for(int i=0;i<13;i++){
this.remainingSpade[i] = true;
this.remainingHeart[i] = true;
this.remainingClub[i] = true;
this.remainingDiamond[i] = true;
}
for(int i=0;i<4;i++){
this.rightOpCutSuit[i]= false;
this.leftOpCutSuit[i] = false;
this.frontOpCutSuit[i] = false;
}
this.coatCaution = false;
this.gcCaution = false;
this.numberOfTrumpExist = 13;
this.openingBet =0;
this.respondingBet =0;
this.trickStarter = false;
}
public static void createRobot(){
CardsInHand.Deal();
for(int i=0; i<3;i++){
Robots[i] = new Players(CardsInHand.getAllHands()[i+1]);
}
}
private int getScoreInHand(Cards[] arr){
int temp = 0;
for(Cards x: arr){
temp = temp + x.getFaceValue();
}
return temp;
}
private int getStrongestSuit(Cards[] arr){
int strong=0;
int S=0;int C=0;int D=0;int H=0;
for(Cards x: arr){
if(x.getColorName()=="Spade") S = S + x.getFaceValue();
else if(x.getColorName()=="Heart") H = H + x.getFaceValue();
else if(x.getColorName()=="Club") C = C + x.getFaceValue();
else D = D + x.getFaceValue();
}
int[] temp = {S,H,D,C};
int max = temp[0];
for(int i=0;i<4;i++){
if(max<temp[i]){
max=temp[i];
strong = i;
}
}
return strong+1;
}
private int getWeakestSuit(Cards[] arr){
int weak=0;
int S=0;int C=0;int D=0;int H=0;
for(Cards x: arr){
if(x.getColorName()=="Spade") S = S + x.getFaceValue();
else if(x.getColorName()=="Heart") H = H + x.getFaceValue();
else if(x.getColorName()=="Club") C = C + x.getFaceValue();
else D = D + x.getFaceValue();
}
int[] temp = {S,H,D,C};
int min = temp[0];
for(int i=0;i<4;i++){
if(min>temp[i]){
min=temp[i];
weak = i;
}
}
return weak+1;
}
private int getLongestSuit(Cards[] arr){
int Longest = 0;
int[] temp = new int[4];
getCardOfEachSuit(arr, temp);
int max = temp[0];
for(int i=0;i<4;i++){
if(max<temp[i]){
max=temp[i];
Longest = i;
}
}
return Longest+1;
}
private int getSmallestSuit(Cards[] arr){
int Smallest = 0;
int[] temp = new int[4];
getCardOfEachSuit(arr, temp);
int max = temp[0];
for(int i=0;i<4;i++){
if(max>temp[i]){
max=temp[i];
Smallest = i;
}
}
return Smallest+1;
}
private boolean getIsBalanceHand(Cards[] arr){
int S=0;int C=0;int D=0;int H=0;
for(Cards x: arr){
if(x.getColorName()=="Spade") S++;
else if(x.getColorName()=="Heart") H++;
else if(x.getColorName()=="Club") C++;
else D++;
}
if((S<=4&&S>=3)&&(H<=4&&H>=3)&&(D<=4&&D>=3)&&(C<=4&&C>=3)) return true;
else return false;
}
private void getCardOfEachSuit(Cards[] arr, int[] array){
int S=0;int C=0;int D=0;int H=0;
for(Cards x: arr){
if(x.getColorName()=="Spade") S++;
else if(x.getColorName()=="Heart") H++;
else if(x.getColorName()=="Club") C++;
else D++;
}
array[0] = S;
array[1] = H;
array[2] = D;
array[3] = C;
}
private int getNumberOfTrump(Cards[] arr){
int temp = 0;
for(Cards x: arr){
if(x.getisTrump() == true) temp = temp+1;
}
return temp;
}
public void setTrickStarter(boolean a){
this.trickStarter = a;
}
public boolean getTrickStarter(){
return this.trickStarter;
}
private static Players[] Robots = new Players[3]; //
private int[] cardsOfEachSuit = new int[4]; // ok
private boolean[] remainingSpade = new boolean[13]; //
private boolean[] remainingHeart = new boolean[13]; //
private boolean[] remainingDiamond = new boolean[13]; //
private boolean[] remainingClub = new boolean[13]; //
private int scoreInHand; // ok
private int longestSuit; // ok
private int smallestSuit; // ok
private int strongestSuit; // ok
private int weakestSuit; // ok
private boolean isBalanceHand; // ok
private int numberOfTrump; // ok
private int numberOfTrumpExist; //
private boolean[] rightOpCutSuit = new boolean[4]; //
private boolean[] frontOpCutSuit = new boolean[4]; //
private boolean[] leftOpCutSuit = new boolean[4]; //
private int openingBet; //
private int respondingBet; //
private boolean gcCaution; //
private boolean coatCaution; //
private boolean trickStarter;
}
Now please guide me little forward what is can do to start playing.

Resources