BubbleSort troubleshooting - java

It is my first attempt to do sorting in arrays. I am looking in BubbleSort. I looked up many examples on the net. However, I could not get my bubble sort working. Below is a snippet of my code:
//Sort by StudentID (long variable)
public static void BubbleSort(Student[] st) {
long tempID; //holding variable
for (int j = 0; j < st.length - 1; j++) {
if (st[j] != null) {
long studentID1 = st[j].getStudentID();
if (st[j + 1] != null) {
long studentID2 = st[j + 1].getStudentID();
if ((st[j] != null) && (st[j + 1] != null)) {
if (studentID1 < studentID2) // change to > for ascending sort
{
tempID = studentID1; //swap elements
studentID1 = studentID2;
studentID2 = tempID; //shows a swap occurred
}
}
}
}
}
}
//My main method
if (studentIndex >= 0) {
BubbleSort(studentList);
for (int i = 0; i <= studentIndex; i++) {
studentList[i].writeOutput();
}
} else {
System.out.println("No sorting done");
}

You have to swap elements. Your code doesn't.
In addition you have to check if you had modifications in your for loop. If yes you have to repeat the procedure.
So change it as follow
public static BubbleSort(Student[] st) {
Student temp; //holding variable
boolean changed = false;
for (int j = 0; j < st.length - 1; j++) {
if (st[j] != null) {
long studentID1 = st[j].getStudentID();
if (st[j + 1] != null) {
long studentID2 = st[j + 1].getStudentID();
if ((st[j] != null) && (st[j + 1] != null)) {
if (studentID1 < studentID2) // change to > for ascending sort
{
temp = st[j]; //swap elements
st[j] = st[j + 1];
st[j + 1] = temp; //shows a swap occurred
changed = true;
}
}
}
}
}
if (changed) {
BubbleSort(st);
}
}

Related

Binary heap output not as expected

I have a homework that the teacher test if it's corrects by checking it's output using this website moodle.caseine.org, so to test my code the program execute these lines and compare the output with the expected one, this is the test :
Tas t = new Tas();
Random r = new Random(123);
for(int i =0; i<10000;i++)t.inser(r.nextInt());
for(int i =0;i<10000;i++)System.out.println(t.supprMax());
System.out.println(t);
And my Heap (Tas) class:
package td1;
import java.util.ArrayList;
import java.util.List;
public class Tas {
private List<Integer> t;
public Tas() {
t = new ArrayList<>();
}
public Tas(ArrayList<Integer> tab) {
t = new ArrayList<Integer>(tab);
}
public static int getFilsGauche(int i) {
return 2 * i + 1;
}
public static int getFilsDroit(int i) {
return 2 * i + 2;
}
public static int getParent(int i) {
return (i - 1) / 2;
}
public boolean estVide() {
return t.isEmpty();
}
#Override
public String toString() {
String str = "";
int size = t.size();
if (size > 0) {
str += "[" + t.get(0);
str += toString(0);
str += "]";
}
return str;
}
public boolean testTas() {
int size = t.size();
int check = 0;
if (size > 0) {
for (int i = 0; i < t.size(); i++) {
if (getFilsGauche(i) < size) {
if (t.get(i) < t.get(getFilsGauche(i))) {
check++;
}
}
if (getFilsDroit(i) < size) {
if (t.get(i) < t.get(getFilsDroit(i))) {
check++;
}
}
}
}
return check == 0;
}
public String toString(int i) {
String str = "";
int size = t.size();
if (getFilsGauche(i) < size) {
str += "[";
str += t.get(getFilsGauche(i));
str += toString(getFilsGauche(i));
str += "]";
}
if (getFilsDroit(i) < size) {
str += "[";
str += t.get(getFilsDroit(i));
str += toString(getFilsDroit(i));
str += "]";
}
return str;
}
//insert value and sort
public void inser(int value) {
t.add(value);
int index = t.size() - 1;
if (index > 0) {
inserCheck(index); // O(log n)
}
}
public void inserCheck(int i) {
int temp = 0;
int parent = getParent(i);
if (parent >= 0 && t.get(i) > t.get(parent)) {
temp = t.get(parent);
t.set(parent, t.get(i));
t.set(i, temp);
inserCheck(parent);
}
}
//switch position of last element is list with first (deletes first and return it)
public int supprMax() {
int size = t.size();
int max = 0;
if (size > 0) {
max = t.get(0);
t.set(0, t.get(size - 1));
t.remove(size - 1);
supprMax(0);
}
else {
throw new IllegalStateException();
}
return max;
}
public void supprMax(int i) {
int size = t.size();
int temp = 0;
int index = i;
if (getFilsGauche(i) < size && t.get(getFilsGauche(i)) > t.get(index)) {
index = getFilsGauche(i);
}
if (getFilsDroit(i) < size && t.get(getFilsDroit(i)) > t.get(index)) {
index = getFilsDroit(i);
}
if (index != i) {
temp = t.get(index);
t.set(index, t.get(i));
t.set(i, temp);
supprMax(index);
}
}
public static void tri(int[] tab) {
Tas tas = new Tas();
for (int i = 0; i < tab.length; i++) {
tas.inser(tab[i]);
}
for (int i = 0; i < tab.length; i++) {
tab[i] = tas.supprMax();
}
}
}
The last 3 lines of the test are :
-2145024521
-2147061786
-2145666206
But the last 3 of my code are :
-2145024521
-2145666206
-2147061786
The problem are probably with the inser and supprMax methods.
I hate to get a bad grade just because of 3 lines placement, because it is a program that verify the code, it dosn't care the the solution was close, it's still says it's wrong.

5 Card Poker Hand JAVA-Analyze and Categorize

Prompt: Write a program that reads five cards from the user, then analyzes the cards and prints out the category of hand that they represent.
Poker hands are categorized according to the following labels: Straight flush, four of a kind, full house, flush, straight, three of a kind, two pairs, pair, high card.
I currently have my program set as follows, first prompting the user for 5 cards, 2-9, then sorting the cards in ascending order. I set up my program to prompt the user and then go through several if else statements calling methods. I am having issues though where its not identifying three or four of a kind.
Example, if I enter 1, 3, 2, 1, 1, it identifies it as TWO PAIRS instead of Three of a Kind.
Same for entering 1, 1,1, 1, 4, it identifies as three of kind instead of 4.
Any suggestions to my code?
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
final int HAND_SIZE = 5;
int[] hand = new int[HAND_SIZE];
getHand(hand); //Prompt user for hand
sortHand(hand);//Sort hand in ascending order
if(containsFullHouse(hand))
{
System.out.print("FULL HOUSE!");
}
else if(containsStraight(hand))
{
System.out.print("STRAIGHT!");
}
else if(containsFourOfAKind(hand))
{
System.out.print("FOUR OF A KIND!");
}
else if(containsThreeOfAKind(hand))
{
System.out.println("THREE OF A KIND!");
}
else if(containsTwoPair(hand))
{
System.out.println("TWO PAIRS!");
}
else if(containsPair(hand))
{
System.out.println("PAIR!");
}
else
System.out.println("High Card!");
}
public static void getHand(int[] hand)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter five numeric cards, 2-9, no face cards please");
for(int index = 0; index < hand.length; index++)
{
System.out.print("Card " + (index + 1) + ": ");
hand[index] = input.nextInt();
}
}
public static void sortHand(int[] hand)
{
int startScan, index, minIndex, minValue;
for(startScan = 0; startScan < (hand.length-1); startScan++)
{
minIndex = startScan;
minValue = hand[startScan];
for(index = startScan + 1; index <hand.length; index++)
{
if(hand[index] < minValue)
{
minValue = hand[index];
minIndex = index;
}
}
hand[minIndex] = hand[startScan];
hand[startScan] = minValue;
}
}
public static boolean containsPair(int hand[])
{
boolean pairFound = false;
int pairCount = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
pairCount++;
}
startCheck = hand[index];
}
if (pairCount == 1)
{
pairFound = true;
}
else if(pairCount !=1)
{
pairFound = false;
}
return pairFound;
}
public static boolean containsTwoPair(int hand[])
{
boolean twoPairFound = false;
int twoPairCount = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
twoPairCount++;
}
startCheck = hand[index];
}
if (twoPairCount == 2)
{
twoPairFound = true;
}
else if(twoPairCount != 2)
{
twoPairFound = false;
}
return twoPairFound;
}
public static boolean containsThreeOfAKind(int hand[])
{
boolean threeFound = false;
int threeKind = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
threeKind++;
}
startCheck = hand[index];
}
if(threeKind == 3)
{
threeFound = true;
}
else if(threeKind !=3)
{
threeFound = false;
}
return threeFound;
}
public static boolean containsStraight(int hand[])
{
boolean straightFound = false;
int straight = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 1)
{
straight++;
}
startCheck = hand[index];
}
if(straight == 4)
{
straightFound = true;
}
return straightFound;
}
public static boolean containsFullHouse(int hand[])
{
boolean fullHouseFound = false;
int pairCheck = 0;
int startPairCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startPairCheck) == 0)
{
pairCheck++;
}
startPairCheck = hand[index];
}
int threeOfKindCheck = 0;
int startThreeKindCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startThreeKindCheck) == 0)
{
threeOfKindCheck++;
}
startThreeKindCheck = hand[index];
}
if(pairCheck == 1 && startThreeKindCheck == 3)
{
fullHouseFound = true;
}
return fullHouseFound;
}
public static boolean containsFourOfAKind(int hand[])
{
boolean fourFound = false;
int fourKind = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
fourKind++;
}
startCheck = hand[index];
}
if(fourKind == 1)
{
fourFound = true;
}
else if(fourKind !=4)
{
fourFound = false;
}
return fourFound;
}
}
Some hints.
Start with the highest hand. This eliminates lots of logic.
I.e if you check for pairs first, than you also have to check to make sure that your pair is the only pair, and not three of a kind.
But if you already ruled all of those out your code would be check card 1and2 23 34 and 45.

HugeInteger Class adding and subtracting taking into account negative values

I'm currently writing a HugeInteger class that can take in 40 digits, and I have a few comparison tests that are already written. The thing I'm having most trouble with is adding and subtraction methods. I was able to get two values to add, but don't know how to implement a negate function if one of the values are negative. My subtraction method doesn't seem to work either.
public void add(HugeInteger hi) {
if (digits[NUM_DIGITS] < 0) {
negate();
this.subtract(hi);
}
int carry = 0;
for(int i = digits.length-1; i >=0 ;i--) {
int cur = this.digits[i] + hi.digits[i] + carry;
if (cur >= 10){
cur= cur-10;
resultAdd[i] = cur;
carry = 1;
} else{
resultAdd[i] = cur;
carry = 0;
}
}
StringBuilder builder = new StringBuilder();
int j=0;
for (int i : resultAdd) {
builder.append(i);
this.digits[j] = i;
j++;
}
this.hi = builder.toString().replace("0", "");
}
public void subtract(HugeInteger hi) {
for(int i = digits.length-1; i >=0 ;i--) {
if (this.digits[i] - hi.digits[i] < 0){
this.digits[i-1]--;
this.digits[i]+=10;
}
int cur = this.digits[i] - hi.digits[i];
this.digits[i] = cur;
}
StringBuilder builder = new StringBuilder();
int j=0;
for (int i : resultAdd) {
builder.append(i);
this.digits[j] = i;
j++;
}
this.hi = builder.toString().replace("0", "");
}
public void negate() {
if(this.positive){
this.positive = false;
} else{
this.positive = true;
this.hi = this.hi.replace("-", "");
}
}

java object comparison [duplicate]

This question already has answers here:
Compare objects in LinkedList.contains()
(6 answers)
Closed 9 years ago.
I'm trying to check if an object exists within a linked list, and perform an action depending on if it exists or not, however, java is treating all the objects as different no matter what I do. The main code is provided below, and I'm pretty sure the error in the logic is in this code. The article and customer classes are very standard. The flag variable, which is supposed to be true if the list contains the article with the title, is always false. Any help would be much appreciated.
import java.util.*;
import java.io.*;
public class Proj1 {
public static void main(String[] args) throws FileNotFoundException {
LinkedList<Article> Articles = new LinkedList<Article>();
LinkedList<Customer> Customers = new LinkedList<Customer>();
ListIterator<Customer> it = Customers.listIterator();
int id = 0;
String command = "";
if (args.length == 0 || args[0] == null) {
System.out.println("Please give a valid command file");
} else {
try {
Scanner reader = new Scanner(new FileInputStream(args[0]));
while (reader.hasNext()) {
String arg = reader.nextLine();
arg.split(" ");
String[] commands = arg.split("\\s+");
if (isInt(commands[0])) {
id = Integer.parseInt(commands[0]);
command = commands[1];
Customer temp = new Customer(id);
if (Customers.size() == 0) {
Customers.add(temp);
} else {
boolean flag = false;
for (int i = 0; i < Customers.size(); i++) {
if (id == Customers.get(i).getId()) {
flag = true;
}
}
if (flag == false) {
Customers.add(temp);
}
}
} else {
command = commands[0];
}
// System.out.println(id+" "+command);
if (command.equalsIgnoreCase("borrow")) {
String title = "";
int x = commands.length;
boolean flag = false;
for (int j = 2; j < x; j++) {
title += commands[j] + " ";
}
Article Article = new Article(title);
System.out.println(Articles.size());
if (Articles.size() == 0) {
Articles.add(Article);
} else {
for (int i = 0; i < Articles.size(); i++) {
if (Article.getTitle() == Articles.get(i).getTitle()) {
flag = true;
}
}
if (flag == false) {
Articles.add(Article);
}
}
System.out.println(flag);
for (int i = 0; i < Customers.size(); i++) {
if (Customers.get(i).CustomerList().contains(title) && flag == true) {
Article.addToQ(Customers.get(i));
} else {
Customers.get(i).CustomerBorrow(Article);
}
}
// System.out.println(title);
} else if (command.equalsIgnoreCase("return")) {
String title = "";
int x = commands.length;
for (int j = 2; j < x; j++) {
title += commands[j] + " ";
}
Article Article = new Article(title);
if (Articles.size() == 0) {
Articles.add(Article);
} else {
boolean flag = false;
for (int i = 0; i < Articles.size(); i++) {
if (title == Articles.get(i).getTitle()) {
flag = true;
}
}
if (flag == false) {
Articles.add(Article);
}
}
for (int i = 0; i < Customers.size(); i++) {
if (id == Customers.get(i).getId()) {
Customers.get(i).CustomerReturn(Article);
}
}
// System.out.println(title);
} else if (command.equalsIgnoreCase("list")) {
for (int i = 0; i < Customers.size(); i++) {
if (id == Customers.get(i).getId()) {
System.out.println("Customer " + id
+ " currently has: "
+ Customers.get(i).CustomerList());
}
}
} else if (command.equalsIgnoreCase("whohas")) {
String title = "";
int x = commands.length;
for (int i = 1; i < x; i++) {
title += commands[i] + " ";
}
boolean flag = false;
int tempId = 0;
for (int i = 0; i < Customers.size(); i++) {
tempId = Customers.get(i).getId();
if (Customers.get(i).CustomerList().contains(title)) {
flag = true;
tempId = Customers.get(i).getId();
}
}
if (flag = true) {
System.out.println(tempId + " currently has "
+ title);
} else {
System.out
.println("Currently no one has checked out "
+ title);
}
// System.out.println(title);
} else if (command.equalsIgnoreCase("waitlist")) {
String title = "";
int x = commands.length;
for (int i = 1; i < x; i++) {
title += commands[i] + " ";
}
for (int i = 0; i < Customers.size(); i++) {
if (Customers.get(i).CustomerList().contains(title)) {
Articles.get(i).printQ();
}
}
// System.out.println(title);
} else if (command.equalsIgnoreCase("listCustomers")) {
System.out.println("Customers include: ");
for (int i = 0; i < Customers.size(); i++) {
System.out.println(Customers.get(i).getId());
}
} else {
System.out.println("Command not recognized");
}
}
reader.close();
}
catch (Exception e) {
System.out.println("command not formatted correctly");
}
}
}
public static boolean isInt(String string) {
try {
Integer.parseInt(string);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
}
commands such as
29 borrow "new york times"
29 borrow "new york times"
allow duplicates, and I'm trying to avoid this. Thanks.
Could it be that
if (Article.getTitle() == Articles.get(i).getTitle()) {
intends to compare strings? That would explain why your flag always comes back false. To compare strings in Java you should use equals (or equalsIgnoreCase for case-insensitive comparison)
if (Article.getTitle().equals(Articles.get(i).getTitle()) {
More background information here
I'm only guessing, but I'd bet that you either didn't override equals and hashCode in your Customer and Article classes or you didn't do it properly.
Joshua Bloch shows you how in Chapter 3 of "Effective Java".
I'd also wonder why you didn't choose the Set data structure if duplicates weren't allowed.

Count continuous repeated occurrence of characters from String

This is my code.
public static void countContinuosOccurence() {
String first = "ABBCDDDEFGGH";
StringBuffer result = new StringBuffer();
int count = 1;
for (int i = 1; i < first.length(); i++) {
if (first.charAt(i) == (first.charAt(i - 1))) {
count++;
} else {
if (count > 1) {
result.append(String.valueOf(count) + first.charAt(i - 1));
} else {
result.append(first.charAt(i - 1));
}
count = 1;
}
}
System.out.println("First String is:"+ first);
System.out.println("Result is:" + result);
}
The result is:
First String is:ABBCDDDEFGGH
Result is:A2BC3DEF2G
It is missing the last character? May someone help me to solve this?
Not top-performing, but simplest code:
final String in = "ABBCDDDEFGGH" + '\u0000';
final StringBuilder b = new StringBuilder();
char prev = in.charAt(0);
int rpt = 0;
for (int i = 1; i < in.length(); i++) {
final char curr = in.charAt(i);
if (curr == prev) rpt++;
else {
b.append(rpt == 0? prev : "" + (rpt + 1) + prev);
rpt = 0; prev = curr;
}
}
System.out.println(b);
After the for loop ends, you'll need to append the count and the character of the last run of character(s) to the result:
public static void countContinuosOccurence() {
String first = "ABBCDDDEFGGH";
StringBuffer result = new StringBuffer();
int count = 1;
int i;
for (i = 1; i < first.length(); i++) {
if (first.charAt(i) == (first.charAt(i - 1))) {
count++;
} else {
if (count > 1) {
result.append(String.valueOf(count) + first.charAt(i - 1));
} else {
result.append(first.charAt(i - 1));
}
count = 1;
}
}
// ADD THIS - to take care of the last run.
if (count > 1) {
result.append(String.valueOf(count) + first.charAt(i - 1));
} else {
result.append(first.charAt(i - 1));
}
System.out.println("First String is:"+ first);
System.out.println("Result is:" + result);
}
public static void countContinuosOccurence() {
String[] input = "ABBCDDDEFGGH".split("");
String out = "";
for (int i = 0; i < input.length; i++) {
int repeatedCharCount = 1;
String currentChr = input[i];
if (!(i == input.length - 1)) {
while (input[i].equals(input[i + 1])) {
repeatedCharCount++;
i++;
}
}
out = out + repeatedCharCount + currentChr;
}
System.out.println(out);
}
There is also a hidden problem, that is that if you are terminating with a sequence with more than one occurrence, you will not write anything.
The simplest way to solve this problem and the problem you detected is to add a final check after the for block
[...]
}
int l = first.length();
if (count > 1) {
result.append(String.valueOf(count) + first.charAt(l - 1));
} else {
result.append(first.charAt(l - 1));
}
}
System.out.println("First String is:"+ first);
System.out.println("Result is:" + result);
}
import java.util.*;
public class HelloWorld{
public static void main(String []args){
System.out.println("Hello World");
String first = "ABBCDDDEFGGHhhhhh456456456{{{67}}}";
StringBuffer result = new StringBuffer();
result.append(first);
System.out.println(result);
Map<Character,Integer> map = new HashMap<Character,Integer>();
for(int i = 0; i < first.length(); i++) {
char c = first.charAt(i);
if (map.containsKey(c)) {
int cnt = map.get(c);
map.put(c, ++cnt);
} else {
map.put(c, 1);
}
}
Set set = map.entrySet();
// Get an iterator
Iterator itr = set.iterator();
// Display elements
while(itr.hasNext()) {
Map.Entry me = (Map.Entry)itr.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println("Hello World1");
}
}

Categories

Resources