rolling dice using arrays [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
simple beginner Java question. I just learned how to use arrays and it's still a little confusing to me. My goal is to simply roll a number of dice a number of times and then project it as a sum, frequency, and percentage. I'm sure I'm doing something dumb, but I'm overlooking it!
import javax.swing.JOptionPane;
import java.util.Random;
public class Lab1 {
private static int N = 0;
private static int M = 0;
private static int total = 0;
private static Random rnd = new Random();
public Lab1(){
}
public static void main(String[] args) {
N = Integer.parseInt(JOptionPane.showInputDialog("How many dice would you like to roll?"));
System.out.println("Dice: "+N);
M = Integer.parseInt(JOptionPane.showInputDialog("How many times would you like to roll?"));
System.out.println("Rolls: "+M);
int total[] = new int[(6*Lab1.N)+1];
for (int i=0; i<=total.length; i++)
total[i] = 0;
for (int roll=1; roll<=M; roll++){
N = 1+rnd.nextInt(6);
total[N]++;
}
System.out.printf("%3s%12s%12s\n", "Sum","Frequency", "Percentage " );
for(int k=2; k<total.length; k++);{
int percent = total[k]/(360);
System.out.printf("%3s%12s%12s\n", k, total[k], percent);
}
}
}

From what I can see the question is how can you store the previous roles of the dice. And I believe your problem is with this method:
for (int roll=1; roll<=M; roll++){
N = 1+rnd.nextInt(6);
total[N]++;
}
I would change this to
for (int roll=1; roll<=M; roll++){
total[roll] = rnd.nextInt(6);
}
This will build up an array storing each dice roll - if that is of course what you are looking for...

Two things.
First, this loop will inevitably throw ArrayIndexOutOfBoundsException ("element" total[total.length] is out of bounds)
for (int i=0; i<=total.length; i++)
total[i] = 0;
You should use < instead of <=.
for (int i=0; i<total.length; i++)
total[i] = 0;
Second, this line here:
for(int k=2; k<total.length; k++);{
You have an empty loop here. You should remove the semicolon before the {:
for(int k=2; k<total.length; k++){
Now your code compiles, doesn't throw exceptions on the start, and prints a pretty table.
That's a start.

for(int k=2; k<total.length; k++);{
You need to remove the ; symbol from your loop as 'k' will not be resolved in the loop as you have terminated it. The format is for(x, x, x) {
The next thing to look at now is:
Dice: 1
Rolls: 1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at Lab1.main(Lab1.java:26)
Hint:
total[i] = 0; // this line is the problem.
Look at your <= in the loop.
for (int i=0; i<total.length; i++)
Simply chaging it to < results in this:
Dice: 1
Rolls: 1
Sum Frequency Percentage
2 1 0
3 0 0
4 0 0
5 0 0
6 0 0

Related

"Find Missing & Repeating Number" unable to compile on hackerrank suppose to use array list only not simple array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
Encountered this program on hackerrank it was showing runtime error.
The relevant code block is shown below.
On simple array its working, but on lists its not working.
Lists are only accepted.
Question statement on hackerrank:
You are given a read-only array of N integers with values also in the range [1,N] both inclusive. Each integer appears exactly once except A which appears twice and B which is missing. The task is to find the repeating and missing numbers A and B where A repeats twice and B is missing.
Input Format
First line is the length of the array - n
Second line contains n integer that is elements of the array
Constraints
1 <= n <= 105
1 <= arr[i] <= n
Output Format
Print array of integers containing repeating and missing number respectively
Sample Input 0
3
3 1 3
Sample Output 0
3 2
Explanation 0
A = 3 , B = 2 Since 3 is appearing twice and 2 is missing
public static List<Integer> find_missing(List<Integer> arr) {
int i;
// Repeating number
for (i = 0; i < arr.size(); i++) {
int abs_val = Math.abs(arr.get(i));
if (arr.get(abs_val - 1) > 0)
arr.get(abs_val - 1) = -arr.get(abs_val - 1);
else
return abs_val;
}
//Missing number
for (i = 0; i < arr.size(); i++) {
if (arr.get(i) > 0)
return (i + 1);
}
}
first of all arr.get(abs_val - 1) = -arr.get(abs_val - 1); is wrong because it's the same as saying 5 = -3 , as lValue is indeed a value not a variable , use arr.set(index, value); instead .
also in your code , you are using Math.abs() which isn'y necessary because in the question , it's said :
1 <= n <= 105 1 <= arr[i] <= n
so the values of arr[i] will always be positive.
so I edited the whole code of yours as it has many logic problems,
so for finding repeated numbers , what I do is to loop over the list , get every element then see if there is any other similar elements in the same array.
for finding repeated number , I loop over the numbers from 1 to N where N is entered by the user as specified by the problem above and check if every number is there in the list or not.
edited version of the code :
package com.example;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
List<Integer> example = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int i = 0; i < n; i++)
{
example.add(scanner.nextInt());
}
List<Integer> result = find_missing(example, n);
for (Integer i : result)
System.out.print(i + " ");
}
public static List<Integer> find_missing(List<Integer> arr, int n) {
List<Integer> temp = new ArrayList<>();
int i;
// Repeating number
for (i = 0; i < arr.size(); i++) {
for (int j = i + 1; j < arr.size(); j++) {
if (arr.get(j).equals(arr.get(i))){
if (temp.contains(arr.get(j)))
break;
temp.add(arr.get(i));
break;
}
}
}
//Missing number
for (i = 1; i <= n; i++) {
if (!arr.contains(i))
temp.add(i);
}
return temp;
}
}
and here is some examples of the output test cases:

In Java, how would I print a 2d array that resembles a seating chart with an 'aisle' down the middle? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am working on an assignment where I have to print a 2d array that resembles a seating chart. Each element has a number, and increases in number when you go through the array, and also has an "aisle" down the middle where no one can sit. Below is what the array should look like.
1 2 3 x 4 5 6
7 8 9 x 10 11 12
13 14 15 x 16 17 18
19 20 21 x 22 23 24
This would continue until there are 48 total seats. This would make it have 8 rows and 7 columns.
Right now my code is bad. I tried to make the code that would substitute the fourth column of the code with xs, but that did not work. Here is what my code looks like so far. My code only prints 0s when it runs. How would I make my code actually print the xs, and could I have some pointers on how to make each element display its respective number?
public class airplane {
public static void main(String[] args) {
int[] rows = new int[8];
int[] columns = new int[7];
int[][] chart = new int[rows.length][columns.length];
for(int j = 0; j < rows.length; j++)
{
for(int k = 0; k < columns.length; k++)
{
if(columns.length == 4)
{
chart[j][k] = 'x';
}
System.out.print(chart[j][k] + " ");
}
System.out.println();
}
}
}
I apologize if my code is bad. I am inexperienced, and I do not have much help at all right now.
It can be done as below with 2 for loops where first loop iterate column wise and second iterate row wise
public class Print2DArray {
public static void main(String[] args) {
int seatNo = 1;
int row = 8; // set row count
int column = 7; // set column count
int[][] print2DArray = new int[row][column]; // init your 2d seat matrix
for (int i = 0; i < print2DArray.length; i++) {
for (int j = 0; j < print2DArray[i].length/2; j++) {
System.out.print(seatNo++ + " ");
// System.out.print(print2DArray[i][j]++ + " "); // You can use this line to print the value on the current position in the array position
}
System.out.print("x ");
for (int j = 0; j < print2DArray[i].length/2; j++) {
System.out.print(seatNo++ + " ");
// System.out.print(print2DArray[i][j]++ + " "); // You can use this line to print the value on the current position in the array position
}
System.out.println();
}
}
}

No code inside of my for loop is being run - Java 8 SE [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I've been working on a simple Java code where you are to give 5 numbers to the program through the console, which will then tell you what numbers you chose and give you an average. I noticed, however, after I started trying to test my code, that the for loop was basically 'skipping over' all of the code inside of the loop, and I have no idea why. Here's my code:
import java.util.Scanner;
public class numAv {
public static void main(String[] args) {
int num;
int[] numbers = new int[5];
boolean done = false;
Scanner scan = new Scanner(System.in);
System.out.println("Enter five integer numbers one at a time.");
for (int i = 0; i >= 5; i++) {
scan.nextLine();
num = scan.nextInt();
numbers[i] = num;
}
// The code inside the for loop is being skipped; I'm not getting any time to type in an integer.
System.out.println("Your numbers are:");
for (int i = 0; i >= 5; i++) {
System.out.print(numbers[i]);
}
// The same has also happened above; The code within the for loop is essentially being skipped.
num = 0;
for (int i = 0; i >= 5; i++) {
num += numbers[i];
}
num /= (float) 5;
System.out.println("The average of the chosen numbers is " + num);
}
}
Here's what the console outputs:
Enter five integer numbers one at a time.
Your numbers are:
The average of the chosen numbers is: 0
Here:
for (int i = 0; i >= 5; i++) {
i will have a really hard time being zero and bigger than 5 at the same time.
The real answer here: each and any character that you put into your source code matters. There is a big difference between <= and >=, and even between <= and < for that matter. So, when your code doesn't do what you expect it to do: take a piece of paper, and start "running" that code manually. Really write down the values within your variables, and carefully check what the code is doing with them.
Bad condition:
for (int i = 0; i >= 5; i++) {
This will never works, try this:
for (int i = 0; i < 5; i++) {

This program in java doesn't stop executing [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have written this java program for sorting some numbers. But it doesn't stop executing. Can you help me with it?
package inplacesort;
import java.util.*;
public class InplaceSort
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
Vector <Integer> intList = new Vector <Integer> ();
//getting the numbers from the user
char ans = 'y';
while (ans == 'Y' || ans == 'y')
{
System.out.print("Enter a Number: ");
intList.addElement(console.nextInt());
System.out.print("Do You Want to Continue?(Y/N)");
ans = console.next().charAt(0);
}
System.out.println("Before Sorting the Numbers: " + intList);
for (int i = 1; i < intList.size(); i++)
{
int j = i - 1;
while (j > 0 && intList.elementAt(i) < intList.elementAt(j))
{
j--;
}
for (int k = intList.size() - 1; k >= j; k--)
{
intList.insertElementAt(intList.elementAt(k),k + 1);
}
intList.insertElementAt(intList.elementAt(i+1),j);
intList.removeElementAt(i+1);
}
System.out.print(intList);
}
}
Your problem is with intList.size() in the k & i loops. This is not be as what you would expect it. When I debugged your code the value of k was 425996.
Edit :
When i debugged it more I saw that because of you mutating the vector within it self it keeps increasing in size. If you let your program run for a few minutes you will get out of memory error.
Please don't mutate the object you are looping though it. Either make a copy of it and the loop though one of them and mutate another or start with a fresh one & keep adding the values to it while looping over the older one.
System.out.println("Before Sorting the Numbers: " + intList);
List<Integer> sortList = new ArrayList<Integer>();
int minVal;
int index=0;
int size = intList.size();
for (int i = 0; i < size; i++)
{ minVal=Integer.MAX_VALUE;
for (int j = 0; j < intList.size(); j++)
{
if(intList.get(j) < minVal){
index=j;
minVal=intList.get(j);
}
}
intList.remove(index);
sortList.add(minVal);
}
System.out.print("After Sorting the Numbers: "+ sortList);
The reason is because your value for j is ALWAYS 1 less than the value for i. Therefore, infinite while loop.

How to find a saddle point of a matrix using Java? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
How can I find a saddle point of a matrix, which is the highest number in the row and at the same time the highest number in column using Java?
For example, using this matrix:
| 7 2 |
| 1 3 |
| 5 8 |
the saddle points are: 7 and 8.
Here is the portion of my code I wrote to find the highest number in the row and in the column.
int NumRow = 3;
int NumCol = 2;
int [] matrix = new int [NumRow][NumCol];
for ( int i = 0; i < NumRow; i++)
{
max = matrix[i][0];
for ( int j = 1; j < NumCol; j++)
{
if (matrix[i][j]> max)
{
max = matrix[i][j];
}
}
System.out.print(max+" ");
}
System.out.println("\n");
for ( int c = 0; c < NumCol; c++)
{
largest = matrix[c][0];
for (int r = 0; r < NumRow; r++){
if (matrix[r][c] > largest){
largest = matrix[r][c];
}
}
System.out.print(largest+" ");
}
The output is:
7 3 8
7 8
Now I want to find the saddle point using the definition above.
From wikipedia (emphasis mine):
A saddle point is an element of the matrix which is both the largest
element in its column and the smallest element in its row.
You can determine it by going through the matrix in row-order and:
creating an array to store the current-column maximum
storing a current-row-minimum on the fly and store it in an array too
when you are done with this you can compare if an index occurs in both at the same time so that you have an index which is both the column-max and row-min.
Note: your example-matrix does not have any saddle points according to wikipedia's definition.
Unfortunately I have to go. It looks like you were going to get there in the end.
Here is a solution which is based on your description, and the way you describe it should work.
It's not the most efficient, you should improve that. You also should not submit this as an assignment, doing so would only be cheating yourself, you will find future assignments difficult.
public class SaddlePointerFinder{
public static void main(String[] args){
int [] [] matrix = {
{ 7, 2 },
{ 1, 3 },
{ 5, 8 },
};
// i loops though columns
for(int x = 0; x<matrix[0].length; x++){
// this is to store the highest on the ROW
int highestOnTheRow = -1;
// this is to store the index of that highest value
int indexOfHighest = -1;
// x loops through rows
for(int y = 0; y<matrix.length; y++){
if(matrix[y][x] > highestOnTheRow) {
// update the highest
highestOnTheRow = matrix[y][x];
indexOfHighest = y;
}
}
// After checking the whole row and finding the highest, check if it's highest on the column
boolean highest = true;
// here, i checks goes through each row using that column.
for(int i = 0; i<matrix[0].length; i++){
if(matrix[indexOfHighest][i] > highestOnTheRow) {
// one which was higher was found :(
highest = false;
}
}
if(highest){
System.out.println("If the forumla is correct, this is a saddle point: " + highestOnTheRow);
}
}
}

Categories