why am I getting this error : data structures (arrays)? - java

I basically need to find the number of sub arrays that have a negative sum.
import java.io.*;
import java.util.stream.IntStream;
import java.util.Arrays;
import java.util.Scanner;
public class Solution {
static int add(int a[]) {
int sum = 0;
for (int i = 0; i < a.length; ++i) {
sum = sum + a[i];
}
return sum;
}
public static void main(String[] args) {
/*
* Enter your code here.
* Read input from STDIN.
* Print output to STDOUT.
* Your class should be named Solution.
*/
int count = 0;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int k = 0; k < n; ++k) {
arr[k] = sc.nextInt();
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n - i; ++j) {
int slice[] = IntStream.range(j, j + i + 1).map(j -> arr[j]).toArray();
if (add(slice) < 0) {
++count;
}
}
}
System.out.println(count);
}
}
Compile Message
Solution.java:32: error: variable j is already defined in method main(String[])
int slice[] = IntStream.range(j, j + i + 1).map(j -> arr[j]).toArray();
^
1 error
Exit Status
255

Its because of the scope of the variable j here. When you refer a variable in map, JVM tries to initiliaze this. In your case, JVM is trying to initialize j with the contents of the map but it is already available at that point from your second for loop. Just use any other variable such as 'k' to get it done.
import java.io.*;
import java.util.stream.IntStream;
import java.util.Arrays;
import java.util.Scanner;
public class Solution {
static int add(int a[])
{
int sum= 0;
for(int i = 0; i < a.length; ++i)
{
sum = sum + a[i];
}
return sum;
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int count = 0;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for(int k = 0; k < n; ++k)
{
arr[k] = sc.nextInt();
}
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < n - i; ++j)
{
int slice[] = IntStream.range(j, j + i + 1).map(k -> arr[k]).toArray();
if(add(slice) < 0)
{
++count;
}
}
}
System.out.println(count);
}
}

This line declares a variable j which is already declared as the loop counter in that scope:
int slice[] = IntStream.range(j, j + i + 1).map(j -> arr[j]).toArray();
You will have to give it a differen name to get rid of this compilation error:
for (int i = 0; i < n; ++i) {
// this is where j is defined for the loop scope
for (int j = 0; j < n - i; ++j) {
// replace the j inside the .map(...)
int slice[] = IntStream.range(j, j + i + 1).map(s -> arr[s]).toArray();
if (add(slice) < 0) {
++count;
}
}
}

Related

I need to find the first maximum element in a 2D matrix using java but the code doesn't seem to work like i wanted it to. Can anyone help me?

I need the maximum elements position if there is more than one maximum element then the first one is to be printed.
My code prints the position of the maximum element but not the first one.
I don't understand why the last iteration is not working as I intend it to.
Please solve it using only Java.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
// define lengths
int n = sc.nextInt();
int m = sc.nextInt();
// add length to matrix
int[][] matrix = new int[n][m];
// insert elements
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
// define max
int max = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
// System.out.print(i + " " + j);
}
// System.out.print(max + " ");
// print index of highest element
// int pos1 = 0;
// int pos2 = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (matrix[i][j] == max) {
System.out.print(i + " " + j);
break;
}
// pos2 += 1;
break;
}
// pos1 += 1;
// break;
}
}
}
There is no need to go through the matrix twice. When you are searching for the max, store also the coordinates of the matrix where that max was found. A code example:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
// define lengths
int n = sc.nextInt();
int m = sc.nextInt();
// add length to matrix
int[][] matrix = new int[n][m];
// insert elements
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
// define max
int max = Integer.MIN_VALUE, row=0, col=0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
row=i;
col=j;
}
}
}
System.out.print("max: "+max + " is at: ");
System.out.print(col + " " + row); //indexes starting from zero
}
}
Create a new variable to hold the position of the max value and set it in the current loop
int max = matrix[0][0];
int[] maxPos = new int[2];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
maxPos[0] = i;
maxPos[1] = j;
}
}
}
and then remove the rest of the code and print the result
System.out.printf("Max is %d and is found at [%d, %d]\n", max, maxPos[0], maxPos[1]);

How to write a function to read elements from 2D array?

When I run the code in the stdin line the program gives me an exception. How to solve it so the program works?
static double read_matrix(double matrix[][]) {
int i, j;
for (i = 0; i < matrix.length; i++) {
for (j = 0; j < matrix[i].length; j++) {
System.out.println("Enter elements:");
matrix[i][j]=stdin.nextInt();
}
}
return 0;
}
You are not declaring stdin inside your method.
To read from the user-input you can use for example: Scanner(System.in) that is provided by java.util.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Main.read_matrix(new double[2][2]);
}
static double read_matrix(double matrix[][]) {
int i, j;
final Scanner scanner = new Scanner(System.in);
for (i = 0; i < matrix.length; i++) {
for (j = 0; j < matrix[i].length; j++) {
System.out.println("Enter element:");
matrix[i][j] = scanner.nextInt();
System.out.println("[" + i + "][" + j + "] = " + matrix[i][j]);
}
}
scanner.close(); // make sure to close it to prevent memory leaks
return 0;
}
}

How can I sort using two different packages?

I had an assignment for a class where I had to develop a simple number sort program.
My main is supposed to receive the user input and my sort class is supposed to interrupt and spit out the resulting numbers in ascending and descending order. The problem is that my main is taking the input but it's not putting it in order at all and I'm unsure why.
package main;
import sort.Sort;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int arr[] = new int[5];
Scanner myScanner = new Scanner(System.in);
for(int i=0; i<5; i++) {
System.out.print("Enter a number: ");
myScanner.nextLine();
}
Sort sortObj = new Sort();
sortObj.ascendingsort(arr);
}
}
package sort;
public class Sort {
public void ascendingsort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
void descendingsort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
}
I know I'm missing something in my Main, because I'm fairly certain I don't need to put anything else into the sort class.
You're code is perfect. You just missed one assignment in your main method.
Instead of myScanner.nextLine(); you should have written arr[i] = myScanner.nextLine();
myScanner.nextLine(); is getting the next line you enter in the console but it isn't saving it anywhere. arr[i] = myScanner.nextLine(); will save the value of the console in the arr array.
Everything else should work after that.
First you are getting user input using myScanner.nextLine() but not storing it. myScanner.nextLine() won't save anything which user enters .
Thus you need to store it in an array and then use it later. So your main method after the changes should be like this.
public static void main(String[] args) {
int arr[] = new int[3];
Scanner myScanner = new Scanner(System.in);
for(int i=0; i<3; i++) {
System.out.print("Enter a number: ");
arr[i] = myScanner.nextInt();
}
Sort sortObj = new Sort();
sortObj.ascendingsort(arr);
}
And your sorting functions are also wrong. There you do some mis-calculations and return / log nothing. Thus you will not see anything in the console if you are not logging or returning anything.
public void descendingsort(int array[]) {
int n = array.length;
int i, j, temp;
for (i = 0; i < ( n- 1 ); i++) {
for (j = 0; j < n - i - 1; j++) {
if (array[j] < array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for (i = 0; i < n; i++){
System.out.println(array[i]);
}
}
public void ascendingsort(int array[]) {
int n = array.length;
int i, j, temp;
for (i = 0; i < ( n- 1 ); i++) {
for (j = 0; j < n - i - 1; j++) {
if (array[j] > array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for (i = 0; i < n; i++){
System.out.println(array[i]);
}
}
I hope this functions will work for your use case of ascending and descending sort.

BubbleSort and Selection Sort

So I'm trying to create Bubble and Selection sort and this is the code I have so far.
package club.westcs.javabasics;
import java.util.ArrayList;
import java.util.Collections;
public class SortsRunner {
public static void BubbleSort(ArrayList<Integer> nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
boolean swapped = false;
for (int j = 0; j < n-1; j++) {
if (nums.get(j) > nums.get(j + 1)) {
int temp = nums.get(j);
nums.set(j, nums.get(j + 1));
nums.set(j + 1, temp);
swapped = true;
}
}
if (!swapped) {
break;
}
}
}
public static void SelectionSort(ArrayList<Integer> nums) {
int n = nums.size();
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (nums.get(j) < nums.get(min_idx))
min_idx = j;
int temp = nums.get(min_idx);
nums.set(j, nums.get(j+1)) = nums.set(i);
nums.set(i, min_idx) = temp;
}
}
public static void printArrayList(ArrayList<Integer> nums) {
for(int i = 0; i < nums.size(); i++) {
System.out.println(nums.get(i) + " ");
}
System.out.println();
}
public static ArrayList<Integer> makeRandomArrayList() {
ArrayList<Integer> nums = new ArrayList<>();
for(int i = 0; i < (int)(Math.random() * 11) + 5; i++) {
nums.add((int)(Math.random() * 100));
}
return nums;
}
public static void main(String[] args) {
printArrayList(makeRandomArrayList());
}
}
My selection sort is erroring for nums.set(j, nums.get(j+1)) = nums.set(i); and nums.set(i, min_idx) = temp; I want this portion of the code to swap the minimum element with the first element. I'm not sure how to do it correctly with the ArrayList stuff. Could someone give me some tips?
You are getting a compilation error because it is impossible to use '=' operator for void functions (such as nums.set(j, nums.get(j+1))). Setters are always void and you cannot assign smth to nothing!
The signature of ArrayList setter looks like:
public E set(int index, E element)
where first parameter is index of the array (0, 2, 3 ... N), second is a value you want to set under this index.
By the way your selection sort looks strange.
Try this code:
public static void doSelectionSort(ArrayList<Integer> arr) {
for (int i = 0; i < arr.size(); i++) {
// find position of smallest num between (i + 1)th element and last element
int pos = i;
for (int j = i; j < arr.size(); j++) {
if (arr.get(j) < arr.get(pos))
pos = j;
}
// Swap min (smallest num) to current position on array
int min = arr.get(pos);
arr.set(pos, arr.get(i));
arr.set(i, min);
printOut(i + 1, arr);
}
}

Difference between these two codes

What is the difference between these two codes?
1st code
import java.io.*;
import java.util.*;
import java.math.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
int MAXsum = Integer.MIN_VALUE;
for(int i=0; i < 6; i++){
for(int j=0; j < 6; j++){
arr[i][j] = in.nextInt();
}
}
for(int i = 1;i<=4;i++)
{
int sum = 0;
for(int j = 1; j<=4;j++)
{
sum = arr[i][j] + arr[i-1][j-1] + arr[i-1][j] + arr[i-1][j+1] + arr[i+1][j-1] + arr[i+1][j] + arr[i+1][j+1];
if(sum > MAXsum)
MAXsum = sum;
}
}
System.out.println(MAXsum);
}
}
2nd code
import java.io.*;
import java.util.*;
import java.math.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
int MAXsum = 0;
for(int i=0; i < 6; i++){
for(int j=0; j < 6; j++){
arr[i][j] = in.nextInt();
}
}
for(int i = 1;i<=4;i++)
{
int sum = 0;
for(int j = 1; j<=4;j++)
{
sum = arr[i][j] + arr[i-1][j-1] + arr[i-1][j] + arr[i-1][j+1] + arr[i+1][j-1] + arr[i+1][j] + arr[i+1][j+1];
if(sum > MAXsum)
MAXsum = sum;
}
}
System.out.println(MAXsum);
}
}
---> The only diff is in the MAXsum declaration then how both differ from each other?
Note:
The 1st code runs all test cases successfully and the second code does not run all test cases.
Integer.MIN_VALUE is the least possible number, which is Negative. In the test cases, the sum might be negative and 0 is greater than that. So 0 gets returned instead of the negative sum.

Categories