Sort array using if condition in java - java

Below program is in java which is suppose to sort array elements in ascending order but it is not functioning as such. Please try out the program below and explain me why it is not storing some of the values in 'second' array. Some values in second array is stored as 0. Which I couldn't able to figure. Kindly solve this program and let me know. Thank you.
public static void main(String[] args) {
int first[]={9,8,2,6,3};
int second[]=new int[5];
for(int i=0;i<first.length;i++){
int count=0;
for(int j=0;j<second.length;j++){
if(first[i]<first[j]){
count++;
}
}
if(count == 0){
second[4]=first[i];
}
if(count == 1){
second[3]=first[i];
}
if(count == 2){
second[2]=first[i];
}
if(count == 3){
second[1]=first[i];
}
if(count == 4){
second[0]=first[i];
}
System.out.print(second[i]);
}
}

Here's the code that will do what you asked for:
public class SortIt{
public static void main(String[] args){
int[] arr = {9,8,2,6,3};
boolean a = true;
int index = 0;
int arrBuffer;
int check = 0;
while(a){
if(index + 1 != arr.length){
if(arr[index] > arr[index+1]){
arrBuffer = arr[index+1];
arr[index+1] = arr[index];
arr[index] = arrBuffer;
index += 1;
check = 0;
}
else if(arr[index] <= arr[index+1]){
index += 1;
check += 1;
}
if(check == arr.length){a = false;}
}
else
index = 0;
}
System.out.print("[");
for(int i = 0; i + 1 < arr.length; i++){
System.out.print("'" + arr[i] + "', " );
}
System.out.println("'" + arr[arr.length-1] + "']");
}
}
Input:
9,8,2,6,3
Output:
['2', '3', '6', '8', '9']

public static void main(String[] args) {
int first[]={9,8,2,6,3};
int second[]=new int[5];
for(int i=0;i<first.length;i++){
int count=0;
for(int j=0;j<second.length;j++){
if(first[i]<first[j]){
count++;
}
}
if(count == 0){
second[4]=first[i];
}
if(count == 1){
second[3]=first[i];
}
if(count == 2){
second[2]=first[i];
}
if(count == 3){
second[1]=first[i];
}
if(count == 4){
second[0]=first[i];
}
//System.out.print(second[i]);
}
for(int a:second){
System.out.println(a);
}
}

you are printing array inside the loop that's why some values are printed as zeros.Her is the modified code.
public static void main(String[] args) {
int first[]={9,8,2,6,3};
int second[]=new int[5];
for(int i=0;i<first.length;i++){
int count=0;
for(int j=0;j<second.length;j++){
if(first[i]<first[j]){
count++;
}
}
if(count == 0){
second[4]=first[i];
}
if(count == 1){
second[3]=first[i];
}
if(count == 2){
second[2]=first[i];
}
if(count == 3){
second[1]=first[i];
}
if(count == 4){
second[0]=first[i];
}
}
System.out.println(new Gson().toJson(second));
}

Related

My ConnectFour game works when it's a square grid but not in a rectangle grid

My connect four game program works when the GRID_HEIGHT and GRID_WIDTH is the same but my assignment requires the height to be 6 and the width to be 7. It doesn't work when I set it to 6 and 7 however for some reason it works when the width is 7 and the height is 6, though I need the opposite. For this version, the system instantly crashes when an input is entered, though it works perfectly on a square grid. Thanks for any help!
import java.util.Scanner;
public class WrittenStuff
{
public static final int GRID_HEIGHT=7;
public static final int GRID_WIDTH=7;
int totalMovesPlayed;
char[][] board;
public WrittenStuff()
{
board=new char[GRID_HEIGHT][GRID_WIDTH];
totalMovesPlayed=0;
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
WrittenStuff c4=new WrittenStuff();
System.out.println("WELCOME TO CONNECT FOUR!!!");
c4.printBoard();
outer:
while(true)
{
int column=0;
//PLAYER 1.
while(true)
{
System.out.print("\n\nPlayer 1 play:");
column = input.nextInt();
column = column-1;
if(c4.isPlayable(column))
{
if(c4.playMove(column, 'X'))
{
c4.printBoard();
System.out.println("\n\nPlayer 1 wins!!!");
break outer;
}
break;
}
else{
System.out.println("Column "+column+" is already full!!");
}
}
c4.printBoard();
//PLAYER 2.
while(true)
{
System.out.print("\n\nPlayer 2 play:");
column = input.nextInt();
column = column-1;
if(c4.isPlayable(column))
{
if(c4.playMove(column, 'O'))
{
c4.printBoard();
System.out.println("\n\nPlayer 2 wins!!!");
break outer;
}
break;
}
else{
System.out.println("Column "+column+" is already full!!");
}
}
c4.printBoard();
if(c4.isFull())
{
System.out.print("Game drawn. Both of you suck at this!!! ");
break;
}
}
}
public void printBoard()
{
for(int vert=0;vert<board.length;vert++)
{
for(int hori=0;hori<board[0].length;hori++)
{
if(board[vert][hori] == 0)
{
System.out.print("|" + "_" + "|");
}
else
{
System.out.print("|" + board[vert][hori] + "|");
}
}
System.out.println();
}
for(int vert=0;vert<GRID_WIDTH;vert++)
System.out.print(" "+(vert+1)+" ");
System.out.println();
}
public boolean playMove(int column, char playerNum)
{
int vert=0;
for(vert=0;vert<GRID_HEIGHT;vert++)
{
if(board[vert][column] == 'X' || board[vert][column] == 'O')
{
board[vert-1][column]=playerNum;
break;
}
}
if(vert == GRID_HEIGHT)
{
board[vert-1][column]=playerNum;
}
totalMovesPlayed++;
return isConnected(vert-1,column);
}
public boolean isPlayable(int column)
{
return board[0][column] == 0;
}
public boolean isFull()
{
return totalMovesPlayed == GRID_HEIGHT*GRID_WIDTH;
}
public boolean isConnected(int x, int y)
{
int num=board[x][y];
int count=0;
int vert=y;
//HORIZONTAL.
while(vert<GRID_WIDTH && board[x][vert] == num)
{
count++; vert++;
}
vert=y-1;
while(vert>=0 && board[x][vert] == num)
{
count++; vert--;
}
if(count == 4){
return true;}
//VERTICAL.
count=0; int hori=x;
while(hori<GRID_HEIGHT && board[hori][y] == num)
{
count++; hori++;
}
if(count == 4){
return true;}
//SECONDARY DIAGONAL.
count=0; vert=x; hori=y;
while(vert<GRID_WIDTH && hori<GRID_HEIGHT && board[vert][hori] == num)
{
count++; vert++; hori++;
}
vert=x-1; hori=y-1;
while(vert>=0 && hori>=0 && board[vert][hori] == num)
{
count++; vert--; hori--;
}
if(count == 4){
return true;}
//LEADING DIAGONAL.
count=0; vert=x; hori=y;
while(vert<GRID_WIDTH && hori>=0 && board[vert][hori] == num)
{
count++; vert++; hori--;
}
vert=x-1; hori=y+1;
while(vert>=0 && hori<GRID_HEIGHT && board[vert][hori] == num)
{
count++; vert--; hori++;
}
if(count == 4){
return true;}
return false;
}
}
Looking at all your uses of board, I find:
board[vert][hori]
board[vert][hori]
board[vert][column]
board[vert][column]
board[vert-1][column]
board[vert-1][column]
board[0][column]
board[x][y]
board[x][vert]
board[x][vert]
board[hori][y]
board[vert][hori]
board[vert][hori]
board[vert][hori]
board[vert][hori]
So, if first dimension is indexed by vert, and second dimension is indexed by hori, why is second dimension variable sometimes named column, not hori? Consistent naming is important for the human understanding of your code, including your own, to prevent coding errors.
But more importantly, what's up with the [x][y], [x][vert], and [hori][y]? Assuming y is equivalent to vert, and that x is equivalent to hori (again, consistent naming, please), aren't those reversed?

Why won't the program detect that I won (Towers Of Hanoi)?

I am doing an assignment for school. It is a towers of hanoi assignment. (I didn't add the larger-disk-over-smaller-disk code yet). When I set tower3 as 4, 3, 2, 1, it says I won, but when I do it while playing the game, nothing happens. Please help! This is due Monday 8:30pm EST.
import java.util.Scanner;
/**
* Simulates a tower that can hold disks.
* #author S. Camilleri
* #author <Hasan Zafar>
*/
public class Challenge {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// This array holds the disks. A 0 represents no disk.
int[] tower = {4,3,2,1};
int[] tower2 = {0,0,0,0};
int[] tower3 = {0,0,0,0};
// This index represents the first available empty spot for a disk.
int index = 0;
int towerCounter = 0;
int length = tower.length;
int length2 = tower2.length;
int length3 = tower3.length;
int diskChoice = 1;
int i;
int held = 0;
int placeChoice;
boolean playing = true;
while (playing)
{
//Check if Won
if (tower3[0] == 4 && tower3[1] == 3 && tower3[2] == 2 && tower[3] == 1) {
System.out.println("Congratulations! You win!");
playing = false;
break;
}
/********************
* Display the towers
********************/
System.out.println();
//Tower1
System.out.print("{ ");
for (int x=0; x<length; x++)
{
System.out.print(tower[x]);
}
System.out.println();
//Tower2
System.out.print("{ ");
towerCounter = 0;
for (int x=0; x<length2; x++)
{
System.out.print(tower2[x]);
}
System.out.println();
//Tower3
System.out.print("{ ");
towerCounter = 0;
for (int x=0; x<length3; x++)
{
System.out.print(tower3[x]);
}
/********************
* Select the highest disk from the tower
********************/
System.out.println();
System.out.println("Pick a tower (The disk highest on that tower will be chosen)");
diskChoice = input.nextInt();
// If user uses the first tower
if (diskChoice == 1) {
i = 3;
while (tower[i] == 0) {
i--;
}
held = tower[i];
tower[i] = 0;
} else if (diskChoice == 2) { // If user uses the second tower
i = 3;
while (tower2[i] == 0) {
i--;
}
held = tower2[i];
tower2[i] = 0;
} else if (diskChoice == 3) { // If user uses the third tower
i = 3;
while (tower3[i] == 0) {
i--;
}
held = tower3[i];
tower3[i] = 0;
}
/********************
* Place the disk
********************/
System.out.println("Where would you like to place" + " " + held + "?");
placeChoice = input.nextInt();
if (placeChoice == 1) {
i = 3;
if (tower[3] == 0){
while (tower[i] == 0) {
i--;
if (i == 0) {
break;
}
}
}
if (tower[i] == 0) {
tower[i] = held;
} else if (tower[i] != 0) {
tower[i+1] = held;
}
} else if (placeChoice == 2) {
i = 3;
if (tower2[3] == 0){
while (tower2[i] == 0) {
i--;
if (i == 0) {
break;
}
}
}
if (tower2[i] == 0) {
tower2[i] = held;
} else if (tower2[i] != 0) {
tower2[i+1] = held;
}
} else if (placeChoice == 3) {
i = 3;
if (tower3[3] == 0){
while (tower3[i] == 0) {
i--;
if (i == 0) {
break;
}
}
}
if (tower3[i] == 0) {
tower3[i] = held;
} else if (tower3[i] != 0) {
tower3[i+1] = held;
}
}
}
}
}
If I set tower3 as 4321 manually, it says I won.
If I set tower3 as 4321 in-game, it just keeps playing.
I figured it out. I forgot to write the 3 at the of win statement.

Java program- finding if all the values in an array are equal

This program will print a statement for when they are all equal, but not when they aren't. What is wrong?
int k = 0;
while (k < numbers.length - 1 )
{
if(numbers[k]==numbers[k+1])
{
k++;
}
}
if(k == numbers.length - 1)
{
System.out.println("All the numbers are the same");
}
else
{
System.out.println("All the numbers are not the same");
}
You have an infinite loop, see:
int[] numbers = {3,3,5,3,3};
int k = 0;
while (k < numbers.length - 1 ) // k never be k >= numbers.length - 1
{
if(numbers[k]==numbers[k+1]) // if not, k never increase
{
k++;
}
}
if(k == numbers.length - 1)
{
System.out.println("All the numbers are the same");
}
else
{
System.out.println("All the numbers are not the same");
}
You can use following code instead of you solution:
private static boolean isEqual(int[] numbers) {
Integer oldNumber = null;
for(int number: numbers) {
if(oldNumber != null && oldNumber != number) {
return false;
}
oldNumber = number;
}
return true;
}
public static void main(String[] args) {
int[] numbers = {3,3,5,3, 3};
if(isEqual(numbers))
{
System.out.println("All the numbers are the same");
}
else
{
System.out.println("All the numbers are not the same");
}
}
Change your code to use a for loop, and break out when you find a difference:
boolean allSame = true;
for(int i = 0; i < numbers.length - 1; i++)
{
if(numbers[i]!=numbers[i+1])
{
allSame = false;
break;
}
}
if(allSame)
{
System.out.println("All the numbers are the same");
}
else
{
System.out.println("All the numbers are not the same");
}
Try this:
boolean allSame = true;
while (allSame == true) {
for (int i = 0; i < numbers.length; i++) {
if (numbers[0] != numbers[i+1]) {
allSame = false;
}
}
}
//Lets user know if array contained same elements or not
if (allSame) {
System.out.println("All the numbers are the same. ");
}
else {
System.out.println("Not all numbers are the same. ");
}
Check out the "numbers[0]" in that for loop. We can always compare all the elements to the first element because if they're not the same even once, obviously they're not all the same.

trouble with yahtzee in java

I have to create the yahtzee game and its methods like full house, small straight, big straight, 3 of kind, 4 of kind , and chance. Now this is what i have done so far and i would like to know if my methods are right and also i'm having a hard time trying to figure out how to check if its yahtzee , 3 of kind, 4 of kind , etc and this is in my main method. The program consists of seven rolls, where every roll can have up to two sub-rolls
static final int NUM_RERROLS_ = 2;
static final int NUM_OF_DICE = 5;
static final int NUM_ROLLS_ = 7;
static final int[] dice = new int[NUM_OF_DICE];
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
rollDice();
for (int i = 0; i < NUM_RERROLS_; i++) {
if (gotYatzee()) {
break;
}
System.out.println(diceToString());
askUser();
System.out.println("Which dice do you want to reroll: ");
secondReroll(convert(keyboard.nextLine()));
}
System.out.println(diceToString());
if (gotYatzee()) {
System.out.println("You got Yatzee & 50 points!");
} else if (largeStraight() == true) {
System.out.println("You got large straight");
} else {
System.out.println("Sorry no large straight");
}
if (smallStraight() == true) {
System.out.println("You got smallStraight");
} else {
System.out.println("Sorry no small straight");
}
if (fullHouse() == true) {
System.out.println("You got full house");
} else {
System.out.println("Sorry no full house");
}
{
System.out.println("SORRY NO YAHTZEE");
}
if (askUser() == false) {
if (largeStraight() == true) {
System.out.println("You got large straight");
} else {
System.out.println("Sorry no large straight");
}
if (smallStraight() == true) {
System.out.println("You got smallStraight");
} else {
System.out.println("Sorry no small straight");
}
if (fullHouse() == true) {
System.out.println("You got full house");
} else {
System.out.println("Sorry no full house");
}
}
}
public static void rollDice() {
for (int i = 0; i < NUM_OF_DICE; i++) {
dice[i] = randomValue();
}
}
public static int randomValue() {
return (int) (Math.random() * 6 + 1);
}
public static String diceToString() {
String dado = "Here are your dice: ";
for (int element : dice) {
dado = dado + element + " ";
}
return dado;
}
public static boolean gotYatzee() {
for (int element : dice) {
if (element != dice[0]) {
return false;
}
}
return true;
}
public static void secondReroll(int[] newValue) {
for (int element : newValue) {
dice[element - 1] = randomValue();
}
}
public static int[] convert(String s) {
StringTokenizer st = new StringTokenizer(s);
int[] a = new int[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
a[i++] = Integer.parseInt(st.nextToken());
}
return a;
}
public static boolean Chance() {
for (int element : dice) {
int i = 0;
if (element != dice[i]) {
i++;
return false;
}
}
return true;
}
public static boolean smallStraight() {
for (int i = 1; i <= NUM_OF_DICE; i++) {
boolean b = false;
for (int j = 0; j < NUM_OF_DICE; j++) {
b = b || (dice[j] == i);
}
if (!b) {
return false;
}
}
return true;
}
public static boolean largeStraight() {
int[] i = new int[5];
i = dice;
sortArray(i);
if (((i[0] == 1) && (i[1] == 2) && (i[2] == 3) && (i[3] == 4) && (i[4] == 5))
|| ((i[0] == 2) && (i[1] == 3) && (i[2] == 4) && (i[3] == 5) && (i[4] == 6))
|| ((i[1] == 1) && (i[2] == 2) && (i[3] == 3) && (i[4] == 4) && (i[5] == 5))
|| ((i[1] == 2) && (i[2] == 3) && (i[3] == 4) && (i[4] == 5) && (i[5] == 6))) {
return true;
} else {
return false;
}
}
public static boolean askUser() {
Scanner keyboard = new Scanner(System.in);
int a = 0;
String yes = "Yes";
String no = "No";
System.out.println("Do you want to reroll the dice again: Yes or No? ");
String userInput;
userInput = keyboard.next();
if (userInput.equals(yes)) {
System.out.println("ALRIGHTY!!");
return true;
} else if (userInput.equals(no)) {
}
return false;
}
public static boolean threeKind() {
int[] a = new int[5];
a = dice;
sortArray(a);
if ((((a[0] == a[1]) && (a[1] == a[2])) // Three of a Kind
|| ((a[1] == a[2]) && ((a[2] == a[3])
|| (((a[2] == a[3]) && (a[3] == a[4]))))))) {
return true;
} else {
return false;
}
}
/*public static boolean fourKind(int[] dice) {
}
*/
public static int[] sortArray(int[] numbers) {
int stop;
for (stop = 0; stop < numbers.length; stop++) {
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
swap(numbers, i, i + 1);
}
}
}
return numbers;
}
public static void swap(int[] numbers, int pos1, int pos2) {
int temp = numbers[pos1];
numbers[pos1] = numbers[pos2];
numbers[pos2] = temp;
}
public static boolean fullHouse() {
int[] a = new int[5];
a = dice;
sortArray(a);
if ((((a[0] == a[1]) && (a[1] == a[2])) && // Three of a Kind
(a[3] == a[4]) && // Two of a Kind
(a[2] != a[3]))
|| ((a[0] == a[1]) && // Two of a Kind
((a[2] == a[3]) && (a[3] == a[4])) && // Three of a Kind
(a[1] != a[2]))) {
return true;
} else {
return false;
}
}
}
basically i want to figure out a way to check if its full house, 3 of kind, 4 of kind , etc
You have 6 dice after three rolls. Sort the array of user-retained dice after the 3 rolls.
Yahtzee: ((die[0] == die[4]) || (die[1] == die[5]))
4 of a kind: ((die[0] == die[3]) || (die[1] == die[4] || (die[2] == die[5]))
Small straight, 3 tests (x = 3,4,5): ((die[x] - die[x-3]) == 3)
Large straight, 2 tests (x = 4,5): ((die[x] - die[x-4]) == 4)
etc.
Chance: Up to the user, right?
Unless I'm missing something (I'm a little rusty on Yatzee), this should be fairly straightforward.

repetitive element in array algorithm

Can someone help me find the error in my logic for the following code?
I am supposed to print out the array elements only once (value vise)
public class dfdf
{
public static void main(String...args)
{
System.out.println(args.length);
String a= "1234512";
for(int i = 0; i < a.length(); i++)
{
for(int j = 0; j <= (i); j++)
{
if (i == 0)
{
System.out.print(a.charAt(i)); break;
}
else if (a.charAt(j) == a.charAt(i))
{
break;
}
else
{
System.out.print(a.charAt(i));}
}
}
}
}
}
desired output=12345 real output-123344455552
public static void main(String args[]){
String a="1234512";
for(int i=0;i<a.length();i++){
boolean already = false;
for(int j = i - 1; j >= 0; --j){
if(a.charAt(j)==a.charAt(i)){
already = true;
break;
}
}
if(already == false){
System.out.print(a.charAt(i));
}
}
}

Categories