I have looked at other questions about out of bounds error and understood them, couldn't understand the fault in this code.
Question: A JAVA program that will read a boolean matrix corresponding to a relation R and output whether R is Reflexive, Symmetric, Anti-Symmetric and/or Transitive. Input to the program will be the size n of an n x n boolean matrix followed by the matrix elements.
The program must output a reason in the case that an input relation fails to have a certain property.
Solution: I have provided the code, it throws the "java.lang.ArrayIndexOutOfBoundsException" error at main and line 65. I can't see how my arrays are out of bounds
ERROR: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at XYZ.BooleanMatrix.main(BooleanMatrix.java:65)
Code:
package XYZ;
import edu.princeton.cs.algs4.*;
public class BooleanMatrix {
// read matrix from standard input
public static boolean[][] read() {
int n = StdIn.readInt();
boolean[][] a = new boolean[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (StdIn.readInt() != 0)
a[i][j] = true;
}
}
return a;
}
// print matrix to standard output
public static void print(boolean[][] a) {
int n = a.length;
StdOut.println(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j])
StdOut.print("1 ");
else
StdOut.print("0 ");
}
StdOut.println();
}
}
// random n-by-n matrix, where each entry is true with probability p
public static boolean[][] random(int n, double p) {
boolean[][] a = new boolean[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = StdRandom.bernoulli(p);
}
}
return a;
}
// display the matrix using standard draw
// depending on variable which, plot true or false entries in foreground
// color
public static void show(boolean[][] a, boolean which) {
int n = a.length;
StdDraw.setXscale(0, n - 1);
StdDraw.setYscale(0, n - 1);
double r = 0.5;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j] == which) {
StdDraw.filledSquare(j, n - i - 1, r);
}
}
}
}
// test client
public static void main(String[] args) {
int n = Integer.parseInt(args[0]); //LINE 65
double p = Double.parseDouble(args[1]);
boolean[][] a = random(n, p);
print(a);
show(a, true);
}}
I don´t know the exact working of StdDraw.setXscale(0, n - 1); but i think it creates a table with n-1 rows. so if you try to fill it with n rows there will be an out of bounds error. try using this in line 47:
StdDraw.setXscale(0, n);
StdDraw.setYscale(0, n);
As stated in the comments below your post: if you don´t enter any arguments when calling the program you´ll get an out of bounds exception because the program expects arguments in the aray and there aren´t any.
To provide arguments open command line and call /java yourcompiledjavafile arg[0] arg[1]
Related
I have tried several ways changing my code in LeetCode but I can't find the fix, the challenge is the next one :
<<Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.>>
My proposal code is the next one:
import java.util.Scanner;
class Solution {
public int countPrimes(int n) {
Scanner sc = new Scanner(System.in);
int sum = 0;
int cont = 0;
int prime = 0;
prime = sc.nextInt();
int a[] = new int [prime];
for(int i = 0; i < a.length; i++) {
a[i] = i;
cont = 0;
for(int y = 1; y< a.length; y++) {
if(a[i] % y == 0) {
cont ++;
}
}
if (cont == 2) {
sum ++;
}
}
return sum;
}
}
Meanwhile the error marks as follows:
Submission Result: Compile Error More Details
Line 7: error: cannot find symbol [in __Driver__.java] int ret = new Solution().countPrimes(param_1); ^ symbol: method countPrimes(int) location: class Solution
Run Code Status: Runtime Error
×
Run Code Result:
Your input
10
Your answer
java.util.NoSuchElementException
at line 937, java.base/java.util.Scanner.throwFor
at line 1594, java.base/java.util.Scanner.next
at line 2258, java.base/java.util.Scanner.nextInt
at line 2212, java.base/java.util.Scanner.nextInt
at line 8, Solution.countPrimes
at line 54, __DriverSolution__.__helper__
at line 84, __Driver__.main
Show Diff
Runtime: N/A
Please help!
This'll also pass through:
public class Solution {
public static final int countPrimes(int n) {
// mapping for if the number is divisible by prime numbers, which would make that number a composite number
boolean[] notPrime = new boolean[n];
// counting prime numbers
int count = 0;
for (int i = 2; i < n; i++) {
// If the index of notPrime would be false, we have a prime number, we go through the if, otherwise we continue
if (notPrime[i] == false) {
// Increment the number of prime numbers
count++;
// Look into future numbers
for (int j = 2; i * j < n; j++) {
// find composite numbers and set their indices to true
notPrime[i * j] = true;
}
}
}
return count;
}
}
References
For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.
Sieve of Eratosthenes
YouTube 1
YouTube 2
You got confused with the input/output part: you don't need any scanner to do this, just:
class Solution
{
public static int countPrimes(int n)
{
int sum = 0;
int a[] = new int [n];
for(int i = 0; i < a.length; i++) {
a[i] = i;
int cont = 0;
for(int y = 1; y< a.length; y++) {
if(a[i] % y == 0) {
cont++;
}
}
if (cont == 2) {
sum++;
}
}
return sum; //this is the output
}
public static void main(String args[])
´{
countPrimes(10); //this is the input
}
}
Proof:
Et voilá. LeetCode accepts the input (10) and the output (4). That's all you need :)
Your answer gets a scanner object which is not needed therefore you could remove it.
You also create an array which will decrease performance, which I recommend not using as you do not need to display the prime numbers but only keep track of them.
public static int countPrimes(int n) {
int sum=0;
for(int i = n; i > 1; i-- ){
int count = 0; //Keep track of the number of primes.
for(int j = 2; j < i; j++){
if(i % j == 0){
count++;
}
}
if(count==0) {
sum++;
}
}
return sum;
}
I have been running this algorithm in order to solve this CCC (Canadian Computing Contest) question. It runs fine and gives the correct output on IntelliJ but shows an NoSuchElementException in DMOJ and the CCC online grader.
Here is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
solution(sc.nextInt());
}
public static void solution(int lines) {
Scanner sc = new Scanner(System.in);
int[][] sunflowers = new int[lines][lines];
int[][] temp = new int[lines][lines];
// Creating sunflowers array
for (int i = 0; i < lines; i++) {
for (int j = 0; j < lines; j++) {
sunflowers[i][j] = sc.nextInt();
}
}
boolean readyToSubmit = false;
int a = 0;
int b = 0;
while (readyToSubmit == false) {
b = 0;
a = 0;
readyToSubmit = true;
for (int g = 0; g < sunflowers.length - 1; g++) {
for (int h = 1; h < sunflowers[g].length; h++) {
if (sunflowers[g][h - 1] > sunflowers[g][h]) {
// Turn true if previous value smaller than current
readyToSubmit = false;
}
}
}
// If each column is in descending order
for (int d = 0; d < sunflowers.length; d++) {
for (int e = 1; e < sunflowers.length; e++) {
if (sunflowers[e - 1][d] > sunflowers[e][d]) {
readyToSubmit = false;
}
}
}
if (readyToSubmit == true) {
break;
}
// Rotating the Array w/ temp
for (int i = sunflowers.length - 1; i >= 0; i--) { // we want position to go right -> left
b = 0;
for (int j = 0; j < sunflowers[0].length; j++) { // We want columns to go up -> down
temp[a][b] = sunflowers[j][i];
b += 1;
}
a += 1;
}
for (int x = 0; x < lines; x++) {
for (int y = 0; y < lines; y++) {
sunflowers[x][y] = temp[x][y];
}
}
}
for (int s = 0; s < sunflowers.length; s++) {
for (int k = 0; k < sunflowers[s].length; k++) {
System.out.print(sunflowers[s][k] + " ");
}
System.out.println();
}
}
}
Input:
3
3 7 9
2 5 6
1 3 4
Output (in IntelliJ):
1 2 3
3 5 7
4 6 9
Output (on DMOJ):
IR (java.util.NoSuchElementException)
Output (on CCC Grader):
Exception in thread "main" java.util.NoSuchElementException
<251 more characters> // unfortunately, I am not able to see what the 251 characters are.
I am currently not sure on what causes this NoSuchElementException (since it doesn't tell me the line number on DMOJ nor the CCC grader). Any help would be greatly appreciated.
Note: This is found in the comment section, I just added it as answer to verify that this problem has been solved.
Remove this line Scanner sc = new Scanner(System.in); on the solution method. Then close sc after solution(sc.nextInt()); line on the main method. Refer to this [link]1
pass your scanner in the solution method. Change your solution method to accept a scanner, so the method signature will be public static void solution(int lines, Scanner sc) , then call it in your main method by solution(sc.nextInt(), sc);. Then after solution(sc.nextInt(), sc); close your scanner by using sc.close()
I'm trying to develop an algorithm in Java, which, given two matrices (let's say a and b), returns true if at least one row is identical in a and b.
Here's my attempt of method:
public static boolean check_row(int a[][], int b[][]){
boolean check = false;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < b[0].length; j++){
if(a[i][j] == b[i][j])
check = true;
}
}
return check;
}
And here's a simple main:
public static void main(String[] args){
int a[][] = {{1,2}, {3,4}};
int b[][] = {{1,2}, {7,8}};
System.out.println(check_row(a, b));
}
Here I get true because first row of both matrices is the same.
But if I change the matrices initialization to this:
int a[][] = {{1,2}, {3,4}};
int b[][] = {{5,6}, {1,2}};
I get false, even though the first row of a and the second row of b are identical.
How should I modify the method in order to get true in both cases?
Your condition is too simple... High level idea is, that for each row from a and b pick a row and then identify whether it is the same, so you need 3 loops...
code:
public class SameRowFinder {
public static void main(String[] args){
int a[][] = {{1,2},{3,4}};
int b[][] = {{1,2}, {7,8}};
System.out.println(hasSameRow(a, b));
int aa[][] = {{1,2},{3,4}};
int bb[][] = {{5,6}, {1,2}};
System.out.println(hasSameRow(aa, bb));
}
private static boolean hasSameRow(int[][] a, int[][] b) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
if (isSameRow(a[i], b[j])) {
System.out.printf("Same rows are %d and %d (0-based).%n", i, j);
return true;
}
}
}
return false;
}
private static boolean isSameRow(int[] row1, int[] row2) {
if (row1.length != row2.length) {
throw new IllegalArgumentException("rows with different length");
}
for (int i = 0; i < row2.length; i++) {
if (row1[i] != row2[i]) {
return false;
}
}
return true;
}
}
Also you do not need to write your own function for array compare, but use Arrays.equal(int[], int[]), but it will just hide 3rd loop. Method above throws runtime exception in case of different length of arrays. It's definitelly worth look at Arrays.equal(int[], int[]) implementation for some tips (check for equality + null checks).
You have an error in your 2nd loop.
Change:
for(int j = 0; j < b[0].length; j++)
to
for(int j = 0; j < b.length; j++){
Further, the issue is that you cannot compare the rows like you do it.
You have to check that the rows have the same length and finally compare the rows. You will need an additional for loop for comparing the rows.
This one will do the trick:
public static boolean check_row(int a[][], int b[][]){
boolean check = false;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < b.length; j++){
if (compareRows(a[i], b[j]))
check = true;
}
}
return check;
}
private static boolean compareRows(int[] row1, int[] row2) {
if (row1.length == row2.length) {
for (int i = 0; i < row2.length; i++) {
if (row1[i] != row2[i]) {
return false;
}
}
return true;
}
return false;
}
public static void main(String[] args){
int a[][] = {{1,2},{3,4}};
int b[][] = {{5,6}, {1,2}};
System.out.println(check_row(a, b));
}
In the example provided by OP, the loop over rows in b matrix was missing.
When learning, the algorithm can be written as follows:
public static boolean check_row(int a[][], int b[][]) {
int row_size = a[0].length;
for (int i = 0; i < a.length; i++) {
b: for (int j = 0; j < b.length; j++) {
for (int k = 0; k < row_size; k++) {
if (a[i][k] != b[j][k])
continue b; // move to next row in 'b' matrix
}
return true; // all elements in row were equal if we reached this point
}
}
return false;
}
In real life it would probably look like this:
public static boolean check_row(int[][] a, int[][] b) {
return Arrays.stream(b)
.anyMatch(rowB -> Arrays.stream(a).anyMatch(rowA -> Arrays.equals(rowA, rowB)));
}
i hope this code can help you
public static boolean check_row(int a[][], int b[][])
{
boolean check = false;
for(int i = 0; i < a.length; i++)
{
for(int k = 0 ; k< b.length ; k++)
{
for(int j = 0 ; j<b[0].length ; j++)
{
if(a[i][j]!=b[k][j])
{
break;
}//if even one cell were not similar in both a and b break
else
{
if(j==b[0].length-1)
{
check = true;
}//if you haven't broken the loop yet and if j went till the end
}//else if they are equal
}//j to go through columns
if(check == true)
{
break;
}//for bringing down the time complexity
}//k to go through b rows
if(check == true)
{
break;
}//for bringing down the time complexity
}//i
return check;
}
I start from the left-bottom and proceeding in clockwise direction till no chars are left. here is my code.
import java.io.*;
import java.util.*;
public class Solution {
static int count = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
char[][] matrix = new char[n][m];
char[] temp = new char[n*m];
for(int r=0;r<n;r++){
for(int col=0;col<m;col++){
matrix[r][col] = sc.next().charAt(col);
}
}
int k=0, l = 0;
while(k < n && l < m){
if(l<m){
for(int i = n-1;i>=k;i--){
temp[count] = matrix[i][l];
count++;
}
l++;
}
for(int i = l;i<m;i++){
temp[count] = matrix[k][i];
count++;
}
k++;
for(int i = k;i<n;i++){
temp[count] = matrix[i][m-1];
count++;
}
m--;
if(k < n){
for(int i = m-1;i>=l;i--){
temp[count] = matrix[n-1][i];
}
n--;
}
}
String code = String.valueOf(temp);
String[] dec = code.split("#");
//System.out.println(dec);
int count2 = dec.length;
System.out.println(count2);
}
}
So can anyone point out where I am going wrong? I start at left bottom, climb up, go right , then go down, go left and continue till no elements left.
There are two issues: incorrect input and missing counter increment.
Incorrect input:
for(int r=0;r<n;r++){
for(int col=0;col<m;col++){
// The following reads a new line each time a new character is needed
matrix[r][col] = sc.next().charAt(col);
}
}
This could be fixed either by lifting sc.next() from the inner loop:
for (int r = 0; r < n; r++) {
String line = sc.next();
for (int col = 0; col < m; col++) {
matrix[r][col] = line.charAt(col);
}
}
Or (preferable) removing inner loop completely:
for (int r = 0; r < n; r++) {
matrix[r] = sc.next().toCharArray();
}
Missing increment (lower part of the spiral):
for(int i = m-1;i>=l;i--){
temp[count] = matrix[n-1][i];
// Counter increment is missing. Add
// counter++;
}
In general, is is better to use StringBuilder for gradual construction of the string. In you case it will look as following:
StringBuilder temp = new StringBuilder();
<...>
temp.append(matrix[n-1][i]);
<...>
String code = temp.toString();
In this code you don't have to estimate possible string size nor manually track current insert position.
starting left bottom in the matrix is
matrix[0][m];
going up the hill will be made by decreasing m to a point where you already had a char inserted.
i would use 4 for loops inside a while loop like is presented:
while (usedRow < (int)0.5*n && usedCol < (int)0.5*m)
{
//usedRow and usedCol start with the value of 0 and will be raised
// by the end of the loop
int i, j;
for (i = m - usedCol; i<=(m-usedCol); i++)
{
matrix[usedRow][m-i] = sc.next().charAt(0);
}
for (j = usedRow; j <= (n-usedRow); j++)
{
matrix[n + j][usedCol] = sc.next.charAt(0);
}
for (i = usedCol; i <= (m-usedCol); i++)
{
matrix [n - usedRow][m+i] = sc.next().chatAt(0);
}
for ( j = n - usedRow; j <= (n - usedRow); j++)
{
matrix[n - j][m - usedCol] = sc.next().charAt(0);
}
usedRow++;
usedCol++;
}
this way you go clockwise and keep the loop within the rows and cols that are not in use.
hope that it helped you in a way.
I need to create a function that outputs all possible binary combinations (2^8 == 256 different sequences of 8 bits.). I'm really stumped on this. I have to do it with nested loops, and am not sure how to go about it. Below is what I tried so far. I was told that I could write this program using 8 nested loops, each one going from 0 to 1; Also, I could try to do this with bit manipulation operators.
Although what I have below is obviously wrong, I tried my best to show that I at least tried this. I also need to put new line's after each closing bracket, to separate the output.
The output should look like this:
00000000
00000001
00000010
00000011
00000100
...
11111110
11111111
public static void outputBinary(){
int[][][][][][][][] num = new int[2][2][2][2][2][2][2][2];
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
for (int k = 0; k < 2; k++){
for (int l = 0; l < 2; l++){
for (int m = 0; m < 2; m++){
for (int n = 0; n < 2; n++){
for (int o = 0; o < 2; o++){
for (int p = 0; p < 2; p++){
System.out.print(num[i][j][k][l][m][n][o][p]);
} }}}}}}}
}
Thanks for looking.
No need for the array. Here is a slight modification to your code that will output all the permutations.
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
for (int k = 0; k < 2; k++){
for (int l = 0; l < 2; l++){
for (int m = 0; m < 2; m++){
for (int n = 0; n < 2; n++){
for (int o = 0; o < 2; o++){
for (int p = 0; p < 2; p++){
System.out.println("" + i + j + k + l + m + n + o + p);
}
}
}
}
}
}
}
}
Do you have to use nested loops? Because this is trivially easy when you simply take advantage of the fact that the binary representation of all the numbers from 0 through 255 cover every permutation.
for (int i=0; i<256; i++) {
System.out.println(Integer.toBinaryString(i));
}
Just print the for variables (i...p) without accessing this obscure empty array.
Well, if it's OK to use some built-in classes, you can do this in the following way:
for (int i=0; i<256; i++){
System.out.println(Integer.toBinaryString(i));
}
And the second way (I believe you should use it, because looking by looking at it you can understand what's under the hood instead of "some magic", it uses bit mask):
for (int i=0;i<256;i++){
int mask = 256;
while (mask > 0){
if ((mask & i) == 0){
System.out.print("0");
} else {
System.out.print("1");
}
mask = mask >> 1;
}
System.out.println();
}
Here's my version. It uses recursion to convert base 2 to base 10 through repeated division:
public static void printBin()
{
for (int i = 0; i < 256; i++) {
int binary = decToBin(i, "");
// pad to give length of 8
System.out.println(String.format("%08d", binary));
}
}
public static int decToBin(int dec, String bin)
{
int quot = dec / 2;
int remainder = dec % 2;
if (quot == 0)
return Integer.parseInt("" + remainder + bin);
return decToBin(quot, "" + remainder + bin);
}
Heres another way of generating all the values using bit operations
public static void main(String[] args) {
int numBits = 8;
int val = 0;
int[] values = new int[]{0,1};
values[0] = 0;
values[1] = 1;
for (int i = 1; i < numBits; i++) {
int[] moreValues = new int[values.length * 2];
int start = (int)Math.pow(2, i);
for (int j = 0; j < values.length; j++) {
moreValues[j * 2] = values[j] << 1;
moreValues[j * 2 + 1] = values[j] << 1 | 1;
}
values = moreValues;
}
//print the values
for (int value: values) {
System.out.println(Integer.toBinaryString(value));
}
}
And another way, using bit operations and recursion
private static void generateNumbers(int number, int numBits, int currentBit) {
if (numBits == currentBit) {
Integer.toBinaryString(number);
return;
}
currentBit++;
generateNumbers(number << 1, numBits, currentBit);
generateNumbers(number << 1 | 1, numBits, currentBit);
}
public static void generateNumbers(int numBits) {
generateNumbers(0, 8, 1);
generateNumbers(1, 8, 1);
}
public static void main(String[] args) {
generateNumbers(8);
}
package org.cross.topology;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
//System.out.println("sushil");
int digits=3;//Provide number of digits for which you want combinations of 0 and 1
int noof0and1=(int) Math.pow(2,digits)/*(2^digits)*/,combinations=(int) Math.pow(2,digits),secondloopcounter=0,temp=0;
String current_char="0";
int startindex=0,lastindex;
ArrayList<String> al=new ArrayList<String>(combinations);
for(int k=0;k<combinations;k++)
{
al.add("");
}
for(int i=1;i<=digits;i++)
{
noof0and1=noof0and1/2;
while(temp!=combinations)
{
temp=temp+noof0and1;
secondloopcounter++;
}
lastindex=noof0and1;
startindex=0;
for(int s=0;s<secondloopcounter;s++)
{
for(int j=startindex;j<lastindex;j++)
{
String temps=al.get(j)+current_char;
al.remove(j);
al.add(j, temps);
}
if(current_char.equals("0"))
{
current_char="1";
}
else
{
current_char="0";
}
startindex=lastindex;
lastindex=lastindex+noof0and1;
}
temp=0;
secondloopcounter=0;
}
for(int l=0;l<al.size();l++)
{
System.out.println(al.get(l));
}
}
}
Below is the solution using Recursion as an approach in java
public class NumberOfBinaryPatterns {
static int[] bitArray = new int[]{0,1};
public static void main(String args[])
{
System.out.println("Below are the patterns\n");
int numberOfBits=4; // It can be any value based on the requirement, In this case we can put this as 8
drawBinaryPattern(numberOfBits,"");
}
private static void drawBinaryPattern(int n,String seed)
{
if(n==0){
System.out.println(seed);
return;
}
for(int j=0;j<bitArray.length;j++)
{
String temp = seed+bitArray[j];
drawBinaryPattern(n-1,temp);
}
}
}
Do in php , very easy
Just convert every count of combinations in binary and add as many 0 as required to complete it in a byte representation.
for($c=1;$c<=pow(2,8);$c++)
{
$bin_str=base_convert($c,10,2); //converting combination number into binary string
$len_str=strlen($bin_str); // Length of string obtained
for($i=1;$i<=8-$len_str;$i++)
$bin_str="0".$bin_str; // adding as many 0 as required to complete in byte format
echo "<br>".$bin_str; //Displaying binary values in byte structure
}