loops and probabtily - java

i have to Have the computer compute all the possible ways three dice can be thrown: 1 + 1 + 1, 1 + 1 + 2, 1 + 1 + 3, etc. Add up each of these possibilities and see how many give nine as the result and how many give ten.
public class prog209b
{
public static void main(String []args){
int sum = 0;
int count = 0;
do{
for(int i = 1; i<=6; i++){
count +=1;
for(int y=1; y<=6; y++){
count += 1;
for(int x=1; x<=6; x++ ){
sum = i + y + x;
}
}
}
}while (sum == 10 && count == 27);{
System.out.println("There are " +count +" ways to get ten");
}
}
}
Thats what i came up with but i can get it to work correctly at all. instead of giving me that theres 27 ways it gives me like 42. Obviously im not doing this correctly. Please help me before i have an aneurysm

I'm not going to do your homework for you but:
You don't need the do/while loop - why would you need to keep going once you'd found all the possibilities?
You don't need to count all the possible dice rolls - you need to count how many give 9 as a total, and how many give 10. You could either do that with two variables, or you could make a method which took the "target" as a parameter
You don't need the sum other than right in the innermost loop - all you need to do is find out whether the sum of the values is equal to one of your target values, and increment the appropriate counter...

Your count += 1s are in the wrong place and your while (sum == 10 && count == 27) makes no sense.

int nine = 0
int ten = 0;
for(int i = 1; i<=6; i++){
for(int y=1; y<=6; y++){
for(int x=1; x<=6; x++ ){
sum = i + y + x;
if (sum == 9) nine++;
if (sum == 10) ten++;
}
}
}

You should do something like this:
for(int i = 1; i<=6; i++){
for(int y=1; y<=6; y++){
for(int x=1; x<=6; x++ ){
sum = i + y + x;
if (sum == 10)
count++;
}
}
}
System.out.println("There are " + count + " ways to make 10");

Related

What is the role of temp = 0 in finding primes?

I have the following code to print all prime numbers from 2 to 100:
int number1 = 2, number2 = 100, temp = 0;
System.out.println("prime numbers between" + number1 + "and" + number2 + "are :");
for (int i = number1; i <= number2; i++) {
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
temp = 1;
break;
} else {
temp = 0;
}
}
if (temp == 0) {
System.out.println(i);
}
}
What is the role of temp = 0 in the very beginning?
If I modify it to, lets say 1, I get a different output. The code then prints all primes starting from 5 instead of 2. Why are the other numbers skipped?
Explanation
Have a close look at your loop logic flow:
for (int i = number1; i <= number2; i++) {
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
temp = 1;
break;
} else {
temp=0;
}
}
if (temp == 0) {
System.out.println(i);
}
}
i starts as 2 and increments. The inner loop is:
for (int j = 2; j <= i / 2; j++) {
Inner loop is skipped
That means that for the first iterations of the outer loop, for example i = 2 the condition of the inner loop evaluates to:
j <= i / 2
// which is
2 <= 2 / 2
// which is
2 <= 1
Hence the inner loop does not even enter at all and is skipped. So we directly reach
if (temp == 0) {
System.out.println(i);
}
The same is true for the iterations, i = 3.
i = 4 is the first iteration that actually enters the inner loop and starts overwriting temp with either 0 or 1.
Meaning of temp == 0
So during the first iterations of the outer loop (i = 2, i = 3), the initial state of temp plays a role, since it determines whether i will be printed or not.
So you need it to start as 0 to have the first values, for which the inner loop is not even entered, included in the output.
Notes
That said, using temp in such a way is overly complicated. It would be better if it would be moved to the place where it is actually needed, inside the loop, given a better name and also changed to a boolean. All in all, you may simplify the code as follows:
int min = 2;
int max = 100;
System.out.println("prime numbers between" + min + "and" + max + "are :");
for (int i = min; i <= max; i++) {
boolean isPrime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(i);
}
}
And if you are willing to introduce a helper method like:
public static boolean isPrime(int candidate) {
for (int i = 2; i <= candidate / 2; i++) {
if (candidate % i == 0) {
return false;
}
}
return true;
}
Your code will heavily simplify and be very easy to read:
int min = 2;
int max = 100;
System.out.println("prime numbers between" + min + "and" + max + "are :");
for (int i = min; i <= max; i++) {
if (isPrime(i)) {
System.out.println(i);
}
}
you need to understand, what is the role of the variable temp in this code.
The variable temp is behaving like a flag, means whenever the number found to be divisible by another number, temp variable is setting as 1 and the code stops checking.
if we scan all the number upto i/2 and the variable temp is still 0, means we didn't find any number j which can divide current number i, then the current number is prime.
edit:
the role of temp=0 at the very beginning assumes all the number is prime. if found later number is divisible then we are assigning temp=1 and we get to know that the number is not prime.
The role in temp is to simply indicate if a prime was or was not found. Then use that value to control printing of the value under test. But it is not really needed (and as already stated in the comments, should have been a boolean).
Here is one way you could improve your effort without using that value.
Other than dividing by already found primes, you can make it somewhat more efficient by doing the following:
If the first prime is even, check to make certain it isn't 2.
if it is, print it.
if even, increment number1 by 1 to make it odd.
then starting iterating by both candidates and divisors by two to get just the odd numbers.
don't divide by any number > the square root of the candidate. Otherwise you are wasting time. Example, if 97 is not divisible by any of 3,5,7,11 then it must be a prime because any larger divisor would return a quotient < 11 which has already been checked.
you don't need a temp value. Just continue to the outer loop if the number is divided. Otherwise, print the number.
int number1 = 2, number2 = 100;
System.out.println("prime numbers between" + number1 + "and"
+ number2 + "are :");
if (number1 % 2 == 0) {
if (number1 == 2) {
System.out.println(2);
}
number1++;
}
outer:
for (int i = number1; i <= number2; i += 2) {
int max = (int)Math.sqrt(i);
for (int j = 3; j <= max; j += 2) {
if (i % j == 0) {
// try next candidate
continue outer;
}
}
// must be a prime so print it.
System.out.println(i);
}
A better approach is to use the Sieve of Erastosthenes. A BitSet is perfect for this. The idea is to:
mark every bit that is not a prime.
This eliminates composite numbers since it eliminates all their prime factors from the composite positions in the bitset.
The unset bit positions in the bitset are then primes.
as the list is being built, the first unset (clear) bit in the list is as prime.
BitSet bits = new BitSet();
bits.set(0,2); // set bits 0 and 1
initialize nextBit to the first prime
int nextBit = 2; // essentially bitSet.nextClearBit(0);
Continue the loop while the next bit is less than the square root of the terminal value.
while (nextBit <= Math.sqrt(number2)) {
// mark every prime position after this one.
for (int i = 2*nextBit; i < number2; i += nextBit) {
bits.set(i);
}
// the next clear bit after the previous prime must be a prime
// since it is next unset bit
nextBit = bits.nextClearBit(nextBit+1);
}
Now display them
// This is done by simply printing all the bit positions
// that are clear up to the terminal value.
int i = bits.nextClearBit(0);
while (i < number2) {
System.out.println(i);
i = bits.nextClearBit(i+1);
}

How to get indices as well as array numbers printed out horizontally?

I have an assignment of which a part is to generate n random numbers between 0-99 inclusive in a 1d array, where the user enters n. Now, I have to print out those numbers formatted like this:
What is your number? 22 //user entered
1 2 3 4 5 6 7 8 9 10
----random numbers here---------
11 12 13 14 15 16 17 18 19 20
-----random numbers here--------
21 22
---two random numbers here---
Using those numbers, I have find lots of other things, (like min, max, median, outliers, etc.) and I was able to do so. However, I wasn't able to actually print it out in the format shown above, with no more than 10 numbers in one row.
Edit: Hello, I managed to figure it out, here's how I did it:
int counter = 0;
int count2 = 0;
int count3 = 0;
int add = 0;
int idx = 1;
int idx2 = 0;
if (nums > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums;
count2 = nums;
}
if (nums%10 == 0) add = 0;
else add = 1;
for (int i = 0; i < nums/10 + add; i++)
{
for (int j = 0; j < count3; j++)
{
System.out.print(idx + "\t");
idx++;
}
System.out.println();
for (int k = 0; k < count2; k++)
{
System.out.print(numbers[idx2] + "\t");
idx2++;
counter++;
}
System.out.println("\n");
if (nums-counter > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums-counter;
count2 = nums-counter;
}
}
Thank you to everyone who helped! Also, please let me know if you find a way to shorten what I have done above.
*above, nums was the number of numbers the user entered
I'd use a for-loop to make an array of arrays: and then formatting the lines using those values:
var arr_random_n = [1,2,3,4,5,6,7,8,9,0,1,2,3,6,4,6,7,4,7,3,1,5,7,9,5,3,2,54,6,8,5,2];
var organized_arr = [];
var idx = 0
for(var i = 0; i < arr.length; i+=10){
organized_arr[idx] = arr.slice(i, i+10); //getting values in groups of 10
idx+=1 //this variable represents the idx of the larger array
}
Now organized_arr has an array of arrays, where each array in index i contains the values to be printed in line i.
There's probably more concise ways of doing this. but this is very intuitive.
Let me know of any improvements.
Something like this might be what you're looking for.
private static void printLine(String msg)
{
System.out.println("\r\n== " + msg + " ==\r\n");
}
private static void printLine(int numDisplayed)
{
printLine(numDisplayed + " above");
}
public static void test(int total)
{
int[] arr = new int[total];
// Fill our array with random values
for (int i = 0; i < total; i++)
arr[i] = (int)(Math.random() * 100);
for (int i = 0; i < total; i++)
{
System.out.print(arr[i] + " ");
// Check if 10th value on the line, if so, display line break
// ** UNLESS it's also the last value - in that case, don't bother, special handling for that
if (i % 10 == 9 && i != total - 1)
printLine("Random Numbers");
}
// Display number of displayed elements above the last line
if (total < 10 || total % 10 != 0)
printLine(total % 10);
else
printLine(10);
}
To print 10 indexes on a line then those elements of an array, use two String variables to build the lines, then print them in two nested loops:
for (int i = 0; i < array.length; i += 10) {
String indexes = "", elements = "";
for (int j = 0; j < 10 && i * 10 + j < array.length; j++) {
int index = i * 10 + j;
indexes += (index + 1) + " "; // one-based as per example in question
elements += array[index] + " ";
}
System.out.println(indexes);
System.out.println(elements);
}

For loop java making the output into 2 columns

Hi I'm a beginner and I'm still learning and if someone could help me in this one thx in advance my code is:
for(int i = 0; i < 10; i++) {
System.out.println(i);
}
and the output should be like this:
0 1
2 3
4 5
6 7
8 9
Just use next line only for odd numbers:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0)
System.out.format("%2d", i);
else
System.out.format(" %2d\n", i);
}
Output:
0 1
2 3
4 5
6 7
8 9
P.S. For more general usage, I would extract it into separate method
public static void printTwoColumns(int min, int max) {
int width = String.valueOf(max).length();
for (int i = min; i < max; i++) {
String str = String.format("%" + width + 'd', i);
if (i % 2 == 0)
System.out.print(str);
else {
System.out.print(' ');
System.out.println(str);
}
}
}
You can do something like this:
for (int i = 0; i < 10; i++) {
System.out.print(i);
System.out.println(++i);
}
The first print uses the current i value and using System.out.print.
The second
print is using println so it goes one line down and also takes ++i so it will advance i by 1 and will also print the new value.
Each loop iteration is printing two values and advances i by total of 2.
To do what you want you can either do something like this:
for(int i = 0; i < 10; i ++){
if(i % 2 == 0){
System.out.print(i); //Only for evens
}else{
System.out.println(i); //Only for odds
}
}
Or you could simplify it even more with something like this:
for(int i = 0; i < 5; i += 2){
System.out.println(i + " " + (i + 1));
}

triangular Numbers Java

the problem is there is two types of codes for same result(triangular number)
1.
for (int i = 1; i <= 10; i++) {
int triangular = 0;
for (int j = 1; j <= i; j++) {
triangular = triangular + j;
}
System.out.println(i + " = " + triangular);
2.
int x =1;
int triangular = 1;
while(x<=10){
System.out.println(x+ "=" +triangular);
x++;
triangular= triangular+x;
}
why for (1) "int triangualr" is 0 and for (2) its 1 ??? idont understand
In the method 1, int triangular is initialized everytime inside the for loop. Nested for loop is calculating the value for triangular and then you are printing the value
for (int i = 1; i <= 10; i++) {
int triangular = 0;
for (int j = 1; j <= i; j++) {
triangular = triangular + j;
}
System.out.println(i + " = " + triangular);
}
But in Method 2, Value for x=1 is printed in the first line of the while loop and then the value of x is incremented
int x =1;
int triangular = 1;
while(x<=10){
System.out.println(x+ "=" +triangular);
x++;
triangular= triangular+x;
}
So in first method, value for triangular is calculated starting from 1 and in second method value for triangular is calculated is not calculated for 1st Iteration
Because in the second code the "triangular" first is printed with value=1
while in the first code the "triangular" first is increased (goes from 0 to 1) and then is printed with value=1.
So in both cases what you see first is triangular=1.

Java loop divisibility sum and average

I have made a loop that produces the sum and average of numbers 1,2,3,...,to an upperbound 100. What I am having trouble with is modifying my current code so it only includes numbers that are multiples of 7. Here is what I have:
public class SumAndAverageForLoop {
public void SumAndAverageForLoop() {
double sum = 0;
for (double i = 1; i <=100; i++) sum+= i;
System.out.println ("the average is " + sum/100);
System.out.println ("the sum is " + sum);
}
}
I am trying to do it without a main method so I had to create a Launcher class.
Any help is appreciated. Thank you in advance.
In order to determine if a number is divisible by 7 you should use the modulo devision operator % and compare the remainder to 0;
int sum = 0;
int count = 0;
for (int i = 0; i <= 100; i++) {
if (i % 7 == 0) {
sum += i;
count++;
}
}
System.out.println("the average is " + sum/count);
System.out.println("the sum is " + sum);
Also I wouldn't recommend using a double when all you need is an int. You might get caught out by precision issues further down the road. You could cast your sum to a double before dividing to by count if you want a decimal average. Like this:
System.out.println("the average is " + ((double) sum)/count);
In Java 8 this is now easily accomplished without writing error prone looping structures as follows:
IntStream.range(0,100).filter(i -> i % 7 == 0).summaryStatistics();
Result:
IntSummaryStatistics{count=15, sum=735, min=0, average=49.000000, max=98}
Your for loop should increment in 7's for each iteration and also you should maintain a count of your iterations because you need it for finding average.
int sum = 0;
int count = 0;
int average = 0;
for(int i=7; i<=100; i=i+7)
{
sum = sum + i;
count= count+1;
average = sum/count;
}
I would use the Modulus operator for this use case.
public class SumAndAverageForLoop {
public void SumAndAverageForLoop() {
double sum = 0;
for (double i = 1; i <=100; i++){
if((i % 7) == 0){
sum+= i;
}
System.out.println ("the average is " + sum/100);
System.out.println ("the sum is " + sum);
}
}

Categories

Resources