I am taking a Java class at school. Java looks simple but complicated for me.
I am having a trouble with sorting a two-dimensional array. Please Please Please help me.
Here is what I coded. I don't know why it doesn't work.
public static void selectionSort(int[][] list) {
for (int k = 0; k < list.length;k++){
for (int i = 0; i < list[k].length;i++) {
int currentMin = list[k][i];
int currentMinIndexRow = k;
int currentMinIndexColumn = i;
if (k == 3 && i == 3) continue;
for (int m = k; m < list.length; m++) {
for (int j = i; j < list[k].length; j++) {
if (m == k && i == j) continue;
if (currentMin > list[m][j]) {
currentMin = list[m][j];
currentMinIndexRow = m;
currentMinIndexColumn = j;
}
}
}
if (currentMinIndexRow != k && currentMinIndexColumn != i) {
list[currentMinIndexRow][currentMinIndexColumn] = list[k][i];
list[k][i] = currentMin;
}
}
}
}
Thank you so much guys!!!!!
I am trying to write a program that prompts the user to enter two lists of integers and displays whether the two are identical.
Such as,
"Enter list1: 51 25 22 6 1 4 24 54 6
Enter list2: 51 22 25 6 1 4 24 54 6
The two arrays are identical
Enter list1: 51 5 22 6 1 4 24 54 6
Enter list2: 51 22 25 6 1 4 24 54 6
The two arrays are not identical
Here is what I wrote.
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
int[][] list1 = new int[3][3];
int[][] list2 = new int[3][3];
System.out.print("Enter list1: ");
for (int row=0 ;row < list1.length ;row++){
for (int column=0;column<list1[row].length; column++){
list1[row][column] = input.nextInt();
}
}
System.out.print("Enter list2: ");
for (int row=0 ;row < list2.length ;row++){
for (int column=0;column<list2[row].length; column++){
list2[row][column] = input.nextInt();
}
}
selectionSort(list1);
selectionSort(list2);
if (equals(list1, list2) == true)
System.out.println("The two arrays are identical");
else
System.out.println("The two arrays are not identical");
}// void main
public static boolean equals(int[][] m1, int[][] m2){
boolean result = true;
for (int row=0 ;row < m1.length ;row++){
for (int column=0 ;column<m1[row].length ; column++){
if (m1[row][column] != m2[row][column]) {result = false; break;}
}
}
return result;
}// boolean equals
public static void selectionSort(int[][] list) {
for(int k = 0; k < list.length;k++){
for(int i = 0; i < list[k].length;i++) {
int currentMin = list[k][i];
int currentMinIndexRow = k;
int currentMinIndexColumn = i;
if(k == 3 && i == 3) continue;
for(int m = k; m < list.length; m++){
for (int j = i; j < list[k].length; j++) {
if (m == k && i == j) continue;
if (currentMin > list[m][j]) {
currentMin = list[m][j];
currentMinIndexRow = m;
currentMinIndexColumn = j;
}
}
}
if (currentMinIndexRow != k && currentMinIndexColumn != i) {
list[currentMinIndexRow][currentMinIndexColumn] = list[k][i];
list[k][i] = currentMin;
}
}
}
}
Thank you for your comments.
Thank you so much guys!!!!
I figured out why I was wrong.
There was a really really really simple error.
if (currentMinIndexRow != k || currentMinIndexColumn != i) {
list[currentMinIndexRow][currentMinIndexColumn] = list[k][i];
list[k][i] = currentMin;
}
The above code is what I corrected. Thank you.
Related
first input: size of array: 5
second input: 0 -2 4 0 6
output: 2
Here is what I have tried. It is also adding the numbers before zero:
My code's output:
array size: 10
elements: 6 19 0 -3 4 8 0 -6 9 59
my output: 25 9
import java.util.Scanner;
import java.util.Vector;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
Vector<Integer> A = new Vector<Integer>();
int sum = 0;
for(int i=0; i<arr.length; i++){
arr[i] = in.nextInt();
}
for(int i = 0; i < arr.length; i++)
{
if (arr[i] == 0)
{
i++;
break;
}
}
for(int i=0; i < arr.length; i++)
{
if (arr[i] == 0)
{
A.add(sum);
sum = 0;
}
else
{
sum += arr[i];
}
}
for(int j = 0; j < A.size(); j++)
{
System.out.print(A.get(j) + " ");
}
}
}
You don't need 2 loops, one to look for the first zero and then sum up.
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
List<Integer> sums = new ArrayList<>();
int sum = 0;
// read input
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
boolean isCounting = false;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0 && isCounting) {
sum += arr[i];
} else if(arr[i] == 0){
// if already counting then finish the sum
if (isCounting) {
sums.add(sum);
sum = 0;
} else { // else start counting
isCounting = true;
}
}
}
System.out.println(sums);
}
}
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int arr[] = new int[size];
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
int sum = 0;
int idx = 0;
while (arr[idx] != 0)
idx++; // After this, idx will be the index of the first 0
do {
idx++; // Keep looping from idx + 1 until the next 0
if (arr[idx] != 0 && idx < arr.length)
sum += arr[idx];
} while (idx < arr.length && arr[idx] != 0);
System.out.println("Sum = " + sum);
}
}
int sum = -1;
int j = -1;
for(int i=0; i<arr.length;i++ ){
if (arr[i] == 0) {
j = i;
if (sum == -1)
sum = 0;
else
break;
}
if ( j == -1)
continue;
sum += arr[i];
}
The above should work
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
int sum = 0;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
if (arr[i] == 0) {
list.add(i);
}
}
for (int i = list.get(0); i <= list.get(list.size()-1); i++) {
sum += arr[i];
}
System.out.println(sum);
}
I wrote a program that reads an array of integers and two numbers n and m. The program check that n and m never occur next to each other (in any order) in the array.
import java.util.*;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner (System.in);
int len = scanner.nextInt();
int [] array = new int [len];
boolean broken = false;
for (int i = 0; i < len; i++){
array [i] = scanner.nextInt();
}
int n = scanner.nextInt();
int m = scanner.nextInt();
for (int j = 1; j < len; j++){
if((array[j]==n)&&(array[j+1]==m) || (array[j]==n)&&(array[j-1]==m) || (array[j]==m)&&(array[j+1]==n) || (array[j]==m)&&(array[j-1]==n)){
broken = true;
break;
}
}
System.out.println(broken);
}
}
Test input:
3
1 2 3
3 4
Correct output: true
My output is blank. What am I doing wrong?
Your code will throw ArrayIndexOutOfBoundsException as you are using array[j+1] whereas you have loop condition as j < len. The condition should be j < len -1.
The following works as expected:
for (int j = 1; j < len - 1; j++) {
if ((array[j] == n && array[j + 1] == m) || (array[j] == n && array[j - 1] == m)
|| (array[j] == m && array[j + 1] == n) || (array[j] == m && array[j - 1] == n)) {
broken = true;
break;
}
}
A sample run:
3
1 2 3
3 4
true
Your code will throw ArrayIndexOutOfBoundsException because of array[j+1] where j can be len-1. Actually you don't need to check both sides(previous and next element), checking combination with previous is enough since in the next iteration combination with next element will be checked.
for (int j = 1; j < len; j++){
if((array[j]==n && array[j-1]==m) || (array[j]==m && array[j-1]==n)){
broken = true;
break;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int len = scan.nextInt();
Map<Integer, Set<Integer>> map = new HashMap<>();
for (int i = 0, prv = 0; i < len; i++) {
int num = scan.nextInt();
if (!map.containsKey(num))
map.put(num, new HashSet<>());
if (i > 0)
map.get(prv).add(num);
prv = num;
}
int n = scan.nextInt();
int m = scan.nextInt();
boolean res = !map.containsKey(n) || !map.containsKey(m) || !map.get(n).contains(m) && !map.get(m).contains(n);
System.out.println(res);
}
So I want to skip the first and last elements of the array to initialize. What am I doing wrong?
public static void main(String args[]) throws Exception {
//Write code here
Scanner sc = new Scanner(System.in);
System.out.println("Input Rows: ");
int m = sc.nextInt();
System.out.println("Input Columns: ");
int n = sc.nextInt();
System.out.println("Enter values: ");
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == arr[0][0] || arr[i][j] == arr[m][n]) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
Here is my output:
Input Rows:
3
Input Columns:
3
Entered Values:
0 0 0
0 0 0
0 0 0
You need to change the if condition inside the loop like following:
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if ((i == 0 && j==0) || (i == m -1 && j == n -1)) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
In this line:
if (arr[i][j] == arr[0][0] || arr[i][j] == arr[m][n]) {
You are testing for the equality of values within your array. You should be comparing whether the indices you are looking at are the beginning or end of the array.
That is to say, you want to compare whether (in pseudo code):
i==0 and j==0, OR i==max index in its dimension and j==max index in its dimension
I have deliberately omitted the literal answer, because this looks a tiny bit like homework.
You compare the value of arr[i][j] with the value of arr[0][0]. You should instead compare i==0 && j==0 || i==m -1 && j==n -1
As your array was empty, and as you start the loop, arr[i][j] was equal to arr[0][0], skipping the first element. but for the next loop, arr[i][j] was still empty, and as you compare it to a non-initialised value, it's always true, skipping in each step
public static void main(String args[]) throws Exception {
//Write code here
Scanner sc = new Scanner(System.in);
System.out.println("Input Rows: ");
int m = sc.nextInt();
System.out.println("Input Coloumns: ");
int n = sc.nextInt();
System.out.println("Enter values: ");
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i==0 && j==0 || i==m-1 && j==n-1) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
You don't need to check whether the array items are equal, you just want to check whether the row and column are equal to the last and first.
I need help with this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 54
at Main.oddSort(Main.java:44)
at Main.main(Main.java:19)
I understand that this error occurs because I am trying either trying to assign too many values in the array correct? I just don't know how to fix it or why what I did was wrong.
The assignment is to generate 100 random numbers, and to call two different functions, one after the other to assign the odd and even numbers into two different arrays and to display them.
Here is the section that is giving me trouble:
public static int[] oddSort ( int input[] )
{
int amountOfOdd = 0;
int j = 0;
for(int i = 0; i < input.length; i++)
{
if (input[i] % 2 != 0)
amountOfOdd++;
}
int[] odd = new int[amountOfOdd];
for(int i = 0; i <= 99; i++)
{
if (input[i] % 2 != 0)
/*it's this line specifically that doesn't work, according to the debugger*/
odd[j] = input[i];
j++;
}
return odd;
}
Here is the full thing:
public class Main
{
public static void main(String[] args)
{
int[] numbers = new int[100];
for(int i = 0; i < numbers.length-1; i++)
numbers[i] = (int)(Math.random() * 26);
int[] odd = oddSort(numbers);
int[] even= evenSort(numbers);
System.out.println("The odd numbers are:");
display( odd );
System.out.println("The even number are:");
display( even );
}
public static int[] oddSort ( int input[] )
{
int amountOfOdd = 0;
int j = 0;
for(int i = 0; i < input.length; i++)
{
if (input[i] % 2 != 0)
amountOfOdd++;
}
int[] odd = new int[amountOfOdd];
for(int i = 0; i <= 99; i++)
{
if (input[i] % 2 != 0)
odd[j] = input[i];
j++;
}
return odd;
}
public static int[] evenSort ( int input[] )
{
int amountOfEven = 0;
int j = 0;
for(int i = 0; i < input.length; i++)
{
if (input[i] % 2 != 0)
amountOfEven++;
}
int[] even = new int[amountOfEven];
for(int i = 0; i < input.length; i++)
{
if (input[i] % 2 != 0)
even[j] = input[i];
j++;
}
return even;
}
public static void display (int input[] )
{
for (int i = 0; i < input.length; i++)
System.out.print(input[i] + " ");
}
}
The cause of the exception is the fact that you did not put the brackets around the body of your if condition. Should be like this :
for(int i = 0; i <= 99; i++)
{
if (input[i] % 2 != 0){
odd[j] = input[i];
j++;
}
}
Right now, what you are actually doing is increasing j every time through the loop, not every time there is an odd number. So of course you will get this exception when at least one value in the input is not odd since the odd array will have a size that is less than the size of input.
I'm an AP Computer Science student and my current assignment is that I have to make a program that takes an ArrayList of numbers and, only using the standard Java API, sort it using a Merge Sort. There aren't any compiling errors, but on run-time it doesn't even return the ArrayList! After a little debugging I found that it isn't populating the original list. Please help! Code:
import java.io.*;
import java.util.*;
public class MergeSort {
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
Random r = new Random();
int size, largestInt, holder;
System.out.println("How many integers would you like me to create?");
size = in.nextInt();
ArrayList<Integer>list = new ArrayList<Integer>(size);
System.out.println("What would the largest integer be?");
largestInt = in.nextInt();
for(int i = 0; i < list.size(); i++){
holder = r.nextInt(largestInt + 1);
list.add(holder);
}
mergeSort(list);
for (int j = 0; j < list.size(); j++) {
if(j == 19 || j == 39 || j == 59 || j == 79 || j == 99 || j == 119 || j == 139 || j == 159 || j == 179 || j == 199){
System.out.print(list.get(j));
System.out.println();
}
else{
System.out.println(list.get(j) + "\t");
}
}
}
static void mergeSort(ArrayList<Integer> list) {
if (list.size() > 1) {
int q = list.size()/2;
ArrayList<Integer> leftList = new ArrayList<Integer>();
for(int i = 0; i > 0 && i <= q; i++){
leftList.add(list.get(i));
}
ArrayList<Integer> rightList = new ArrayList<Integer>();
for(int j = 0; j > q && j < list.size(); j++){
rightList.add(list.get(j));
}
mergeSort(leftList);
mergeSort(rightList);
merge(list,leftList,rightList);
}
}
static void merge(ArrayList<Integer> a, ArrayList<Integer> l, ArrayList<Integer> r) {
int totElem = l.size() + r.size();
int i,li,ri;
i = li = ri = 0;
while ( i < totElem) {
if ((li < l.size()) && (ri<r.size())) {
if (l.get(li) < r.get(ri)) {
a.set(i, l.get(li));
i++;
li++;
}
else {
a.set(i, r.get(ri));
i++;
ri++;
}
}
else {
if (li >= l.size()) {
while (ri < r.size()) {
a.set(i, r.get(ri));
i++;
ri++;
}
}
if (ri >= r.size()) {
while (li < l.size()) {
a.set(i, l.get(li));
li++;
i++;
}
}
}
}
}
This is because list.size() returns 0 for an empty list. In your loop where you populate the list, replace list.size() with size.
I haven't checked the actual mergeSort part of your program, but the change that I suggested will at least make the initial population of the list work.