How do I terminate this loop? - java

"Only one while loop should be used to determine all even and odd numbers between 50 and 100."
public class EvenOdd {
public static void main(String args[]) {
int x = 50;
int y = 50;
int i = 0;
int j = 0;
int n = 0;
System.out.print("Even numbers between 50 and 100: ");
while((i != x) || (j != y)) {
n++;
System.out.print(i + x + ", ");
i += 2;
if(i != x)
continue;
System.out.println("100");
System.out.print("\nOdd numbers between 50 and 100: ");
System.out.print((j+1) + y + ", ");
j += 2;
if(j != y)
continue;
}
}
}
The evens print fine but the odds continue on forever. This may be a dumb question, but I'm having the biggest brainfart right now, and I would really appreciate help on this.

Simply try this and let me know. It's based on your code, with just a few minor adjustments:
public class Teste4 {
public static void main(String args[]) {
int x = 50;
int y = 50;
int i = 0;
int j = 1;
int n = 0;
System.out.print("Even numbers between 50 and 100: ");
while((i < x) || (j < y)) {
if(i < x){
System.out.print(i + x + ", ");
i += 2;
continue;
}else if(i == x){
System.out.println("100");
i++;
}
if(j == 1){
System.out.print("\nOdd numbers between 50 and 100: ");
}
System.out.print(j + y + ", ");
j += 2;
}
}
}

Perhaps you should try this
int even_counter = 50;
int odd_counter=51;
System.out.println("Even numbers between 50 and 100: ");
while((even_counter < 100 ) || (odd_counter < 100)){
if(even_counter < 100){
System.out.print(even_counter+ " ");
even_counter+=2;
continue;
}
if(odd_counter < 100){
if(odd_counter == 51){
System.out.println("\nOdd numbers between 50 and 100: ");
}
System.out.print(odd_counter+ " ");
odd_counter+=2;
}
}

I'm sure this is an assignment but i'll add my 2 cents since it's solved. This one will give you an array.
final int EVEN = 0, ODD = 1;
int low = 50, high = 100, current = low;
int[][] numbers = new int[2][];
numbers[EVEN] = new int[((high - low) / 2) + ((high - low) % 2)];
numbers[ODD] = new int[((high - low) / 2)];
while(current < high){
numbers[current % 2][(current - low) / 2] = current++;
}
System.out.println("EVEN" + Arrays.toString(numbers[EVEN]));
System.out.println("ODD " + Arrays.toString(numbers[ODD]));

Alternative approach ,
int current = 50 , end = 100 ;
String odd , even ;
while(current <= 100){
if (current % 2 == 0)
even = even.concat ("," + current);
else
odd = odd.concat("," + current);
current++;
}
System.out.println("Even no are : " + even);
System.out.println("Odd no are : " + odd);
I dont have a compiler now . I think this should be right :) .

Related

How to resolve hashing collisions in Java

Write the following program using Java:
Suppose Player1 has 7 dice and Player2 has 5 dice (all 12 dice are standard 1 through 6 dice and fair). Both players roll their dice and compare their individual sum totals (i.e. Player1 rolls 1,3,5,2,6,1,1 = 19 and Player2 rolls 2,1,4,6,3 = 16). If Player1 rolls a total sum higher than Player2, Player1 wins the match, otherwise, Player2 wins. If all 2,176,782,336 combinations are rolled, how many matches will Player1 win? How many matches will Player2 win? How many matches will result in a tie? (note: only totals answering the three questions need to be printed)
The part where I'm stuck is how can I guarantee that I have no duplicate rolls?
Thanks.
import java.util.Random;
public class KDice {
public static void main(String[] args) {
Random random = new Random();
long playerOneWins = 0, playerTwoWins = 0, ties = 0;
int playerOneSum, playerTwoSum;
//for long number use L as suffix
for (long i = 0; i < 2176782336L; i++) {
//roll dice for player 1
playerOneSum = rollDice(random, 7);
//roll dice for player 2
playerTwoSum = rollDice(random, 5);
//find who won
if (playerOneSum == playerTwoSum) {
ties++;
} else if (playerOneSum > playerTwoSum) {
playerOneWins++;
} else {
playerTwoWins++;
}
}
//after all the round done, display stats
System.out.println("Player 1 win: " + playerOneWins);
System.out.println("Player 2 win: " + playerTwoWins);
System.out.println("Ties: " + ties);
}
public static int rollDice(Random random, int count) {
int sum = 0;
for (int i = 0; i < count; i++) {
sum += generateRandomNumber(random);
}
return sum;
}
public static int generateRandomNumber(Random random) {
return random.nextInt(6) + 1; //return number between 1 to 6
}
}
To simulate each possible roll of 12 dice, I use 12 nested for-loops so that I can produce each possible roll.
I replaced your random rolls of the dice with this loop:
int[] dice = new int[12];
for (dice[0] = 1; dice[0] <= 6; dice[0]++) {
System.out.println("dice[0] = " + dice[0]);
for (dice[1] = 1; dice[1] <= 6; dice[1]++) {
System.out.println("dice[1] = " + dice[1]);
for (dice[2] = 1; dice[2] <= 6; dice[2]++) {
System.out.println("dice[2] = " + dice[2]);
for (dice[3] = 1; dice[3] <= 6; dice[3]++) {
for (dice[4] = 1; dice[4] <= 6; dice[4]++) {
for (dice[5] = 1; dice[5] <= 6; dice[5]++) {
for (dice[6] = 1; dice[6] <= 6; dice[6]++) {
for (dice[7] = 1; dice[7] <= 6; dice[7]++) {
for (dice[8] = 1; dice[8] <= 6; dice[8]++) {
for (dice[9] = 1; dice[9] <= 6; dice[9]++) {
for (dice[10] = 1; dice[10] <= 6; dice[10]++) {
for (dice[11] = 1; dice[11] <= 6; dice[11]++) {
playerOneSum = dice[0] + dice[1] + dice[2] + dice[3] + dice[4] + dice[5] + dice[6];
playerTwoSum = dice[7] + dice[8] + dice[9] + dice[10] + dice[11];
//find who won
if (playerOneSum == playerTwoSum) {
ties++;
} else if (playerOneSum > playerTwoSum) {
playerOneWins++;
} else {
playerTwoWins++;
}
}
}
}
}
}
}
}
}
}
}
}
}
It took about three-four minutes to run through. I put in the println's to keep me from being too impatient. The results are:
Player 1 win: 1877280394
Player 2 win: 225654001
Ties: 73847941
If you are trying to go through every combination, you should not be rolling randomly. Just systematically go through every combination (e.g., with loops), and do your counting as you go along.
It seems to me that you misunderstood the question.
The question asks you to go through all possible outcomes and classify each outcome to either "A wins", "B wins" or "a tie".
For that, you don't use random. The answer should not change if you run the program many times. To enumerate all possible combinations of rolled dice, you can use 12 nested for loops that each count from 1 to 6. This way, the body of innermost loop will be executed 6^12 times - exactly once per any possible outcome. What you need to do is to sum 7 of the loop variables and compare it to sum of 5 other loop variables. Based on that, you either increase the counter for "A wins", "B wins" or "ties".
Alternatively, you don't need to count ties, since you always know the total number of results.
Here is a more compact and slightly more efficient way of achieving this. It works by:
starting with an array of 12 dice, initialized to all 1's (except the last for the first "toss")
then those dice are essentially incremented in a quasi base 7 to get the next toss. quasi because there are no 0's.
the sums are modified by either adding 1 or subtracting 5 depending on the the transition between between adjacent dice which would alter the sum by either +1 or -5.
int[] dice = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 };
int sum5 = 4; // inital sum for sum of five dice before first toss
int sum7 = 7; // initial sum for sum of seven dice before first toss
int sum7wins = 0;
int sum5wins = 0;
int ties = 0;
outer:
for(;;) {
for (int i = dice.length - 1; i >= 0;) {
int val = dice[i];
if (val < 6) {
dice[i] = val + 1;
if (i < 7) {
sum7++;
} else {
sum5++;
}
break;
}
if (i == 0) {
// first die is a 6 so we're done.
break outer;
}
dice[i] = 1;
if(i < 7) {
sum7-=5;
} else {
sum5-=5;
}
i--;
}
if (sum5 > sum7) {
sum5wins++;
} else if (sum7 > sum5) {
sum7wins++;
} else {
ties++;
}
}
System.out.println("sum7wins: " + sum7wins);
System.out.println("sum5wins: " + sum5wins);
System.out.println("ties: " + ties);
Prints
sum7wins: 1877205968
sum5wins: 225571216
ties: 74005152
2,176,782,336 is the number of possibilities of combination that can happens (= 6^12).
As i see you are trying roll 2,176,782,336 times randomly - which i think cannot resolve your question.
Edit, using 12 nested for loop might resolve your question:
public static void main(String args[]) {
int numP1Win = 0;
int numP2Win = 0;
int numdraw = 0;
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= 6; j++) {
for (int k = 1; k <= 6; k++) {
for (int l = 1; l <= 6; l++) {
for (int m = 1; m <= 6; m++) {
for (int n = 1; n <= 6; n++) {
for (int o = 1; o <= 6; o++) {
for (int p = 1; p <= 6; p++) {
for (int q = 1; q <= 6; q++) {
for (int r = 1; r <= 6; r++) {
for (int s = 1; s <= 6; s++) {
for (int t = 1; t <= 6; t++) {
if (i + j + k + l + m + n + o > p + q + r + s + t) {
numP1Win++;
}
else if (i + j + k + l + m + n + o < p + q + r + s + t) {
numP2Win++;
}
else {
numdraw++;
}
}
}
}
}
}
}
}
}
}
}
}
}
System.out.println("Num P1 Win: " + numP1Win);
System.out.println("Num P2 Win: " + numP2Win);
System.out.println("Num Draw: " + numdraw);
}
Output:
Num P1 Win: 1877205968
Num P2 Win: 225571216
Num Draw: 74005152

Excluding an integer from an array to find the 2nd smallest

I have an assignment where my prof. will input an unspecified number of integers into my program, and my program will process the data accordingly to assign a grade to each value and find the highest and lowest value, however he always places a -1 at the end of the data so that when input<0 it will stop prompting for input.
The problem is my program isn't supposed to process the -1. It doesn't get added as a grade, but it is a part of the list of grades, so the lowest value is always -1.
I've tried writing code that would remove the -1 from my array when detected as a part of the logic to evaluate a grade, but everything I've tried only returns errors.
How can I ignore the -1 and find the next lowest value, or remove the -1 from the list before evaluating?
import java.util.*;
public class Hw5{
public static void main(String[] args){
Scanner console = new Scanner(System.in);
int input = console.nextInt();
ArrayList<Integer> GradeList = new ArrayList<>();
while(input >= 0){
input = console.nextInt();
GradeList.add(input);
}
evaluateGrade(GradeList);
System.out.print(GradeList);
}
public static void evaluateGrade(List<Integer> Scores){
int count = Scores.size();
int high = Collections.max(Scores);
int low = Collections.min(Scores);
int Aplus = 0;
int A = 0;
int Amin = 0;
int Bplus = 0;
int B = 0;
int Bmin = 0;
int Cplus = 0;
int C = 0;
int Cmin = 0;
int Dplus = 0;
int D = 0;
int Dmin = 0;
int F = 0;
for(int i : Scores){
if(i > 97){
Aplus += 1;
}
else if(i >= 93 && i <= 96){
A += 1;
}
else if(i >= 89 && i <= 92){
Amin += 1;
}
else if(i >= 85 && i <= 88){
Bplus += 1;
}
else if(i >= 81 && i <= 84){
B += 1;
}
else if(i >= 77 && i <= 80){
Bmin += 1;
}
else if(i >= 81 && i <= 84){
B += 1;
}
else if(i >= 77 && i <= 80){
Bmin += 1;
}
else if(i >= 76 && i <= 73){
Cplus += 1;
}
else if(i >= 69 && i <= 72){
C += 1;
}
else if(i >= 65 && i <= 68){
Cmin += 1;
}
else if(i >= 61 && i <= 64){
Dplus += 1;
}
else if(i >= 57 && i <= 60){
D += 1;
}
else if(i >= 53 && i <= 56){
Dmin += 1;
}
else if(i >= 52 && i <= 0){
F += 1;
}
}
System.out.printf("Total number of grades = %d", count);
System.out.println();
System.out.printf("Number of A+'s = %d", Aplus);
System.out.println();
System.out.printf("Number of A's = %d", A);
System.out.println();
System.out.printf("Number of A-'s = %d", Amin);
System.out.println();
System.out.printf("Number of B+'s = %d", Bplus);
System.out.println();
System.out.printf("Number of B's = %d", B);
System.out.println();
System.out.printf("Number of B-'s = %d", Bmin);
System.out.println();
System.out.printf("Number of C+'s = %d", Cplus);
System.out.println();
System.out.printf("Number of C's = %d", C);
System.out.println();
System.out.printf("Number of C-'s = %d", Cmin);
System.out.println();
System.out.printf("Number of D+'s = %d", Dplus);
System.out.println();
System.out.printf("Number of D's = %d", D);
System.out.println();
System.out.printf("Number of D+'s = %d", Dmin);
System.out.println();
System.out.printf("Number of F's = %d", F);
System.out.println();
System.out.printf("The highest grade = %d", high);
System.out.println();
System.out.printf("The lowest grade = %d", low);
System.out.println();
}
Change this
int input = console.nextInt();
ArrayList<Integer> GradeList = new ArrayList<>();
while(input >= 0){
input = console.nextInt();
GradeList.add(input);
}
To something like
List<Integer> gradeList = new ArrayList<>();
int input;
while ((input = console.nextInt()) >= 0) {
gradeList.add(input);
}
Which programs to the List interface, follows the Java idiomatic convention of assignment and evaluation and observes standard variable naming conventions.

How do i make java output number decreasing order

So far this is my code and I need it to output from 66 down to 11. Right now it does 11 upto 66.
public class ListNumbers {
public static void main(String[] args) {
//define limit
int limit = 66;
System.out.println("Printing Even numbers between 1 and " + limit);
for(int x=11; x <= limit; x++){
if(x != 44 && x != 22){
System.out.print(x + " ");
}
}
}
}
You just need to start from limit and ends when it reaches 11
for(int x = limit; x > 10; x--){
if(x! = 44 && x != 22){
System.out.print(x + " ");
}
}
You start the loop at the upper limit (66) and decrements down to the lower limit (1). Then you check if they are even or odd but only output the even numbers.
int lowerLimit = 1;
int upperLimit = 66;
System.out.println("Printing Even numbers between " + lowerLimit + " and " + upperLimit);
for (int x = upperLimit; x >= lowerLimit; x--)
{
if ((x & 1) == 0)
{
// even
System.out.print(x + " ");
}
else
{
// odd
}
}

How to make the for inner loop more efficient?

I am new to Java and there's this one question that makes me wonder. How to make the for inner loop more efficient in this code?
for (int i = 2; i <= 100; i++) {
System.out.print("Factors of " + i + " is: ");
for (int j = 2; j < i; j++) {
if (i % j == 0) System.out.print(j + " ");
}
System.out.println();
}
I was just trying to get the factors of numbers from 2 to 100 but how can i make the inner loop more efficient?
It's a little bit number theory involved here but if you do this it would be efficient specially when the 100 is replaced with something much bigger:
for (int i = 2; i <= 100; i++) {
System.out.print("Factors of " + i + " is: ");
for (int j = 2; j <= (int) Math.sqrt(i); j++) {
if (i % j == 0) System.out.print(j + " " + i / j + " ");
}
System.out.println();
}
You could use the fact that for every divisor a of i there is a number b such that a * b = i.
Find all divisors a <= sqrt(i) and save b = i/a and print these values later.
final int num = 100;
int[] divisors = new int[(int) Math.sqrt(num)];
for (int i = 2; i <= num; i++) {
System.out.print("Factors of " + i + " is: ");
int j = 2;
int index = 0;
for (; j * j < i; j++) {
if (i % j == 0) {
System.out.print(j + " ");
divisors[index++] = i / j;
}
}
if (j * j == i) {
// print sqrt(i) only once, if it's integral
System.out.print(j + " ");
}
while (--index >= 0) {
System.out.print(divisors[index] + " ");
}
System.out.println();
}
This way your inner loop needs only O(sqrt(i)) instead of O(i) operations.
This code time complexity is O(N2).
public static void main(String[] args) {
for (int i = 2; i <= 100; i++) {
System.out.print("Factors of " + i + " is: ");
for (int j = i/2; j > 1; j--) {
if (i % j == 0) System.out.print(j + " ");
}
System.out.println();
}
}
Try this,as your code output will be displayed as follows (ascending order)
Factors of 24 is: 2 3 4 6 8 12
please be noticed, but this given code will be displayed output as follows (descending order )
Factors of 24 is: 12 8 6 4 3 2

Argument values error [duplicate]

This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 7 years ago.
For one of my classes, we had to find a way to make a certain amount of change given an arbitrary amount of coins, with the least amount of coins. Here is my code below:
public class Changemaker {
public static void main ( String[] args ) {
int amount = Integer.parseInt(args[args.length-1]);
int coins = args.length - 1;
if (amount < 0){
throw new IllegalArgumentException("IMPROPER AMOUNT");
} else {
for (int i = 1; i <= coins; i++) {
int coin = Integer.parseInt(args[i]);
if (coin <= 0){
throw new IllegalArgumentException("IMPROPER DENOMINATION");
} else {
for (int j = 1; j <= coins; j++) {
int validCoin = Integer.parseInt(args[j]);
if (validCoin == coin && j != i ) {
throw new IllegalArgumentException("DUPLICATE DENOMINATION");
}
}
}
try {
String firstCoin = args[1];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("INSUFFICIENT DATA");
throw new ArrayIndexOutOfBoundsException(" ");
}
}
}
Tuple [][] table = new Tuple [coins][amount + 1];
for(int x = 0; x < coins; x++) {
for (int i = 0; i <= amount; i++) {
Tuple tuple = new Tuple (coins);
table[x][i] = tuple;
}
}
for (int i = 1; i <= amount; i++) {
Tuple tuple = table[0][i];
int coin = Integer.parseInt(args[1]);
int total = i;
int remainder = total % coin;
int coinAmt= (int)Math.floor(total / coin);
if (remainder == 0) {
tuple.setElement(0, coinAmt);
}
}
for(int x = 1; x < coins; x++) {
int coin = Integer.parseInt(args[x + 1]);
for (int i = 1; i <= amount; i++) {
Tuple tuple = table[x][i];
int total = i;
int remainder = total % coin;
int coinAmt= (int)Math.floor(total / coin);
if (remainder == 0) {
tuple.setElement(x, coinAmt);
int optimalRow = optimalCheck(table, tuple, x, i);
Tuple optimalTuple = table[optimalRow][i];
tuple.copy(optimalTuple);
} else if (remainder != 0 && amount < coin) {
tuple.copy(table[x - 1][i]);
} else if (remainder != 0 && amount > coin) {
tuple.setElement(x, coinAmt);
Tuple remainderTuple = table[x][remainder];
tuple.add(remainderTuple);
int optimalRow = optimalCheck(table, tuple, x, i);
Tuple optimalTuple = table[optimalRow][i];
tuple.copy(optimalTuple);
}
}
}
Tuple finalAnswer = table[coins - 1][amount];
String result = "";
result = result + finalAnswer.total() + " COIN(S) IN TOTAL: ";
for (int i = 0; i < coins; i++) {
result = result + finalAnswer.getElement(i) + " x " + args[i + 1] + " cent , ";
}
if (finalAnswer.total() == 0) {
System.out.println("AMOUNT CANNOT BE MADE");
} else {
System.out.println(result);
}
}
public static int optimalCheck(Tuple[][] table, Tuple tuple, int row, int column) {
int total = tuple.total();
int optimalRow = 0;
for (int i = 0; i <= row; i++ ){
int checkedTotal = table[i][column].total();
if (checkedTotal < total && checkedTotal > 0) {
optimalRow = optimalRow + i;
break;
} else if (checkedTotal == total && i == row) {
optimalRow = optimalRow + row;
break;
}
}
return optimalRow;
} }
For the most part, my code is correct. The only thing wrong with it is that it counts the amount of change to make as a denomination, and it cuts out my first denomination amount.
So, for example, if I put 1 5 10 25 133 in the command line (1,5,10, and 25 cent coins to make 133 cents), it returns:
1 COIN(S) IN TOTAL: 0 x 5 cent , 0 x 10 cent , 0 x 25 cent , 1 x 133 cent ,
I looked at the code, and I don't see where I went wrong. Can anyone tell me where I made the error? Thanks a ton.
In your for loop, you want
for (int i = 1; i < coins; i++) {
not
for (int i = 1; i <= coins; i++) {
<= will include coins, which is length - 1 - the last argument.

Categories

Resources