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()
Related
I am doing an exercise where I have to print 'x' (is an input) rows of numbers incrementing from 0 to 10.
If I input 3, the output should look like this
012
345
678
012
345
678
012
345
678
but instead, I get 3 rows of a 0 to 10 count.
I know it might be easy to code, but I am stuck in that!
I think I am not undestanding well the nested loops :(
public class quadrats {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for (int j = 0; j < q; j++) {
for (int i = 0; i <= 10; i++) {
System.out.print(i);
}
System.out.println();
}
}
}
You don't need two loops for this. All you need is to print a newline after every 3rd letter and an extra newline after every 3rd line. Your code can be like:
public class quadrats {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
int lines = 0;
int letters = 0;
while (lines < q) {
System.out.print(i);
if (letters && letters % q == 0) {
System.out.println();
lines++;
}
if (lines && lines % q == 0) {
System.out.println();
letters = 0;
continue;
}
letters++;
}
}
PS: I haven't tried this code myself. But concept would be the same.
The answer above should solve your problem so I will try to explain what your code does.
Let's start with code inside first for loop:
for (int i = 0; i <= 10; i++) {
System.out.print(i);
}
System.out.println();
First we have a loop iterating through numbers from 0 to 10 and the output is:
012345678910
and a new line after that.
That means that output of your program will print above mentioned output q times.
012345678910
012345678910
012345678910
You can try with below code
public class quadrats {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for (int j = 0; j < q; j++) {
for (int i = 0; i < 9; i++) {
if(i%3 == 0)
System.out.println();
System.out.print(i);
}
System.out.println();
}
}
}
Print X quandrants of X rows and X columns each
Scanner in = new Scanner(System.in);
int q = in.nextInt();
// q quadrants
for (int iQuadrat = 0; iQuadrat < q; iQuadrat++) {
// count will keep track of the last number you print
int count = 0;
// q rows
for (int iRow = 0; iRow < q; iRow++) {
// q cols
for (int iCol = 0; iCol < q; iCol++) {
System.out.print(count);
// increment the count and take its modulo 10 so it stays between 0 and 9
count = (count+1)%10;
}
// line return at the end of the row
System.out.println();
}
// line return between quadrants
System.out.println();
}
For an input of 12, it will print 12 times this quadrant
012345678901
234567890123
456789012345
678901234567
890123456789
012345678901
234567890123
456789012345
678901234567
890123456789
012345678901
234567890123
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]
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.
My question is
( - Write the following method that merges two sorted lists
into a new sorted list. Write a test program that prompts the user to enter two sorted lists and displays the merged list. Here is a sample run. Note that the first number in the input indicates the number of the elements in the list. - )
When I run this code, Eclipse give error.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at single_dimension_all_arrays.Merge_two_sorted_lists.getNumber(Merge_two_sorted_lists.java:60)
at single_dimension_all_arrays.Merge_two_sorted_lists.main(Merge_two_sorted_lists.java:77)
I can't understand why give the error. I can't exceed index.
private static void sort(int [] list3)
{
int temp=0;
for (int i = 0; i < list3.length; i++)
{
for (int j = 0; j < list3.length; j++)
{
if(list3[i]<list3[j])
{
temp=list3[i];
list3[i]=list3[j];
list3[j]=temp;
}
}
}
for (int i = 0; i < list3.length; i++)
{
System.out.println(list3[i]);
}
}
private static void getNumber(int [] list1,int [] list2)
{
Scanner scan = new Scanner(System.in);
int [] list3 = new int[list1.length+list2.length];
for (int i = 1; i < list1.length; i++)
{
System.out.println("Please, enter the number");
list1[i] = scan.nextInt();
}
for (int i = 1; i < list2.length; i++)
{
System.out.println("Please,enter the number");
list2[i]= scan.nextInt();
}
for (int i = 0; i <= list3.length; i++)
{
if(i<list1.length)
{
list3[i]=list1[i];
}
else if(i>list1.length)
{
list3[i] = list2[i];
}
}
sort(list3);
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please,enter the length of list1");
int l1 = scan.nextInt();
System.out.println("Please, enter the length of list2");
int l2 = scan.nextInt();
int [] list1 = new int[l1];
int [] list2 = new int[l2];
list1[0]=l1;
list2[0]=l2;
getNumber(list1,list2);
}
}
Thanks..:)
Although not exceed index...
Yes you do:
for (int i = 0; i <= list3.length; i++)
// ----------------^
The valid range of indexes is 0 to length - 1, so that should be < as it is in several other parts of your code.
Side note: You're also skipping the first element in arrays in a few places:
for (int i = 1; i < list1.length; i++)
// ----------^
I've been trying to solve the warmup challenges on Hackerrank. For this particular challenge - https://www.hackerrank.com/challenges/cut-the-sticks - I've written some code, and although it seems logically correct to me, I'm not getting the right answer.
My Code -
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int lengths[] = new int[n];
List<Integer> output = new LinkedList<Integer>();
for (int i = 0; i < n; i++)
lengths[i] = sc.nextInt();
sc.close();
Arrays.sort(lengths);
for (int i = 0; i < n; i++) {
if (lengths[i] == 0)
continue;
else {
output.add(n - i);
for (int j = i; j < n; j++) { // This loop isn't working like it should
lengths[j] -= lengths[i];
// System.out.print(lengths[j] + " "); // For debugging purposes
}
// System.out.println("");
}
}
for (int i = 0; i < output.size(); i++)
System.out.println(output.get(i));
}
}
For the following input -
6
5 4 4 2 8 2
The output I get is -
6
5
4
3
2
1
The correct output should be -
6
4
2
1
I tried to display the values of the lengths array throughout the runs of the for loop marked in the code (with a comment), and this is what i get for the same inputs as above -
0 2 4 4 5 8
0 4 4 5 8
0 4 5 8
0 5 8
0 8
0
6
5
4
3
2
1
I'm totally stumped as to why this would happen.
The problem is here:
lengths[j] -= lengths[i];
When i == j is true, this changes the value of lengths[i]. You need to save that value first.
final int v = lengths[i];
for (int j = i; j < n; j++) {
lengths[j] -= v;
}
Had solved it sometime back.
Here's a version of answer, using a do while loop
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int size = scan.nextInt();
int sticks [] = new int[size];
for (int i = 0; i < size; i++){
sticks[i] = scan.nextInt();
}
Arrays.sort(sticks);
do {
int count =0;
int leastLength = sticks[0];
for (int j=0; j < sticks.length; j++){
sticks[j] = sticks[j] - leastLength;
count++;
}
System.out.println(count);
List<Integer> resizeArray = new LinkedList<Integer>();
for ( int i=0; i< sticks.length; i++){
if (sticks[i] != 0){
resizeArray.add(sticks[i]);
}
}
int temp[] = new int[resizeArray.size()];
for (int i = 0; i < resizeArray.size(); i ++){
temp[i] = resizeArray.get(i);
}
sticks = temp;
} while (sticks.length > 0);
}
package com.omt.learn.algo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class CutTheSticks2 {
public static void main(String s[]) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
short N = Short.parseShort(br.readLine());
short[] A = new short[N];
N = 0;
for (String str : br.readLine().split(" ")) {
A[N++] = Short.parseShort(str);
}
Arrays.sort(A);
StringBuffer sb = new StringBuffer();
System.out.println(N);
for (int i = 1; i < N; i++) {
if (A[i - 1] != A[i]) {
sb.append((N - i) + "\n");
}
}
// OUTPUT
System.out.print(sb);
}
}
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int arr_i=0; arr_i < n; arr_i++){
arr[arr_i] = in.nextInt();
}
int count = 2;
int min=1000;
for(int arr_i=0;count !=1 ; arr_i++){ // read
count = 0;
for(int arr_j=0; arr_j < n; arr_j++)// find min
{ if(min >arr[arr_j] && arr[arr_j]!=0)
min=arr[arr_j];
}
for(int arr_k=0; arr_k < n; arr_k++)// sub
{
if(arr[arr_k]>=min)
{ count++;
arr[arr_k]= arr[arr_k] - min;
}
}
System.out.println(count);
}
}
}
This is a working solution in JavaScript. Took me a while to realize that the sort() in JavaScript performs a string comparison in alphabetical order.
function sortNumbers(a, b) {
return a - b;
}
function cutSticks(arr){
var smallestStick = 0;
arr = arr.sort(sortNumbers);
while(arr.length > 0) {
console.log(arr.length);
smallestStick = arr[0];
var newArray = [];
arr.forEach(function (val) {
var newValue = val - smallestStick;
if (newValue > 0) {
newArray.push(newValue);
}
});
arr = newArray;
}
}
function main() {
var n = parseInt(readLine());
arr = readLine().split(' ');
arr = arr.map(Number);
cutSticks(arr);
}
Hope it helps!
Java Version. Passed all tests, but not sure if is best performance.
static int[] cutTheSticks(int[] arr) {
List<Integer> sticks = Arrays.stream(arr).boxed().collect(toList());
List<Integer> cuts = new ArrayList<>();
while (true) {
int min = sticks.stream().mapToInt(Integer::valueOf).min().getAsInt();
Iterator it2 = sticks.iterator();
int cuted = 0;
List<Integer> temp = new ArrayList<>();
while (it2.hasNext()) {
int v = (int) it2.next();
if (v == min) {
it2.remove();
cuted++;
} else {
int nv = v - min;
it2.remove();
temp.add(nv);
cuted++;
}
}
cuts.add(cuted);
sticks.addAll(temp);
if (sticks.isEmpty()) {
break;
}
}
return cuts.stream().mapToInt(Integer::valueOf).toArray();
}