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);
}
}
}
Related
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();
}
}
}
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I've been trying to dive into java development and have gone for a relatively easy problem of finding prime numbers, however, I keep getting errors and can't see what I've done wrong, any help?
I've been toiling over my computer for an infuriating while and have tried everything, even rewriting the code from beginning
public class HelloWorld{
public static void main(String []args){
int[] check = {2};
//cycle through numbers 1-100
for (int i = 1; i < 100; i++) {
//cycle through numbers to be checked against i
for (int x = 0; x < 101; x++) {
//check if the current itteration of i has no multiples
if (i%check[x] == 0) {
check[i] = i;
} else {
// print any prime numbers
System.out.print(i);
check[i] = i;
}
}
}
}
}
The immediate cause of your error is that you defined the check[] array to have a size of 1, but you are trying to access elements higher than that, which don't exist. However, I don't think that you really need that array here. Consider this version:
for (int i=2; i < 100; i++) {
boolean match = true;
for (int x=2; x <= Math.sqrt(i); x++) {
if (i % x == 0) {
match = false;
break;
}
}
if (match) {
System.out.println("Prime number: " + i);
}
}
Note that the inner loop in x only needs to go as high as the square root of the outer i value. This is because any value greater than sqrt(i) can't possible divide it.
It is because your array has length 1
and you are trying to access out of bound indexes. In case you are lopping 0 to 101 You can initialize your array like this int [] check =new int [101]
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 8 years ago.
Improve this question
I have these two methods that i am using to find prime numbers based on user input, i have a method called isPrime that logically should return true if a number is prime, however it always return true no matter what the number is?
I realise there are plenty of answers similar to my query but none have helped so far.
public static void userPrimes(){
int[] tempPrimes = new int[49];
int primesFound = 0;
//Input Amount of numbers to be analysed
int[] initial = new int[Integer.parseInt(JOptionPane.showInputDialog("Enter Amount of numbers to be checked")) -1];
//Input Values
for(int i = 0; i<initial.length; i++){
initial[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter number at position:" + (i+1)));
if (initial[i] > 49){
initial[i] = Integer.parseInt(JOptionPane.showInputDialog("Numbers cannot be greater than 49, Try again:"));
}
}
for(int i = 0; i<initial.length; i++){
if (isPrime(initial[i]) == true){
tempPrimes[i] = initial[i];
primesFound++;
}
}
int[] finalPrimes = new int[primesFound];
for (int i=0;i<finalPrimes.length;i++){
finalPrimes[i] = tempPrimes[i];
System.out.print(finalPrimes[i] + " ");
}
}
//checks whether an int is prime or not.
static boolean isPrime(int n) {
for(int j = 2; j < n; j++) {
if(n % j == 0) {
return false;
}
}
return true;
}
You have some problems in your code:
1.
int[] initial = new int[Integer.parseInt(JOptionPane.showInputDialog("Enter Amount of numbers to be checked")) -1];
The array should be in length of the amount that the user entered, not minus 1
2.
if (isPrime(initial[i]) == true){
tempPrimes[i] = initial[i];
primesFound++;}
You should put the primes in the temp primes array in tempPrimes[primesFound]
Also, your final loop is not useful.You can do the printing in the previous loop
Your isPrime function is fine but as performance wise is concerned you need to iterate till half of the number rather than iterating till number
boolean x = isPrime(13);
System.out.println(x);
static boolean isPrime(int n) {
for(int j = 2; j <= n/2; j++) {
if(n % j == 0) {
return false;
}
}
return true;
}
returns true and passing 14 returns false..it works perfect here..
might be the problem is with your loop code which is calling this method
modify this line by by removing -1
no need to do minus 1 as it reduces the no of input to user by one .
if user inputs amount as 3 then -1 makes him to enter only 2 numbers. so make it as below
int[] initial = new int[Integer.parseInt(JOptionPane.showInputDialog
("Enter Amount of numbers to be checked"))];
use only one loop as below to print all prime numbers
for(int i = 0; i<initial.length; i++){
if (isPrime(initial[i]) == true){
tempPrimes[i] = initial[i];
System.out.println(tempPrimes[i]);
}
}
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
I'm trying to create a method that will search through a 2d array of numbers. If the numbers add up to a certain sum, those numbers should remain and all of the other numbers should be changed to a 0. For example, if the desired sum is 7 and a row contains 2 5 1 2, the result should be 2 5 0 0 after the method is implemented. I have everything functioning but instead of keeping all of the numbers that add up to the sum, only the last number is retained. So, I am left with 0 5 0 0 . I think I need another array somewhere but not sure exactly how to go about implementing it. Any ideas?
public static int[][] horizontalSums(int[][] a, int sumToFind) {
int[][] b = new int[a.length][a[0].length];
int columnStart = 0;
while (columnStart < a[0].length) {
for (int row = 0; row < a.length; row++) {
int sum = 0;
for (int column = columnStart; column < a[row].length; column++) {
sum += a[row][column];
if (sum == sumToFind) {
b[row][column] = a[row][column];
}
}
}
columnStart++;
}
return b;
}
In your example you use 2 5 1 1, would 0 5 1 1 also be a valid response? Or do you just need to find any combination? A recursive function may be the best solution.
If you just need to scan through the array and add up the numbers until the sum is reached then just add a for loop to copy the previous values from the array to the new array when the sum is found. Something like:
if (sum == sumToFind)
{
for (int i= 0; i<= columnStart; i++)
{
b[row][i] = a[row][i];
}
}
if (sum == sumToFind)
{
for (int i= columnStart; i<= column; i++)
{
b[row][i] = a[row][i];
}
}
A minor tweak was all it needed. If you have columnStart and column like in the other answer, it only finds the first number of the series.