I am confused on how to access the array temp in order to compare the current array element temp[i] to max sales which is 0 in order to determine which is bigger,each time i try i cannot access temp IN STEP 8 and STEP 7, i do not want to change the visibility of the classes
public class Sales {
public static void main(String[] args) {
int[] sales;
sales = getSales();
printSales(sales);
printSummary(sales);
}
private static int[] getSales() {
Scanner input = new Scanner(System.in);
int[] temp;
System.out.print("Enter the number of salespeople: ");
temp = new int[input.nextInt()]; // Step 1
for (int i = 0; i < temp.length; i++) // Step 2
{
System.out.print("Enter sales for salesperson " + (i + 1) + ": ");
temp[i] = input.nextInt(); // Step 3
}
return temp; // Step 4
}
private static void printSales(int[] s) {
System.out.println();
System.out.println("Salesperson Sales");
System.out.println("----------- -----");
for (int i = 0; i < 5; i++) // Step 5
{
System.out.printf("%6d%12d\n", i + 1, s[i]); // Step 6
}
}
private static void printSummary(int[] s) {
int sum = 0;
int max_sale = 0; // Salesperson with the most sales
int min_sale = 0; // Salesperson with the least sales
for (int i = 0; i < ________; i++) // Step 7
{
____________ // Step 8
}
System.out.println();
System.out.println("Total sales: " + sum);
System.out.println("Average sales: " + (double) sum / s.length);
System.out.println("Salesperson " + (max_sale + 1) + " had the maximum sale with " + s[max_sale]);
System.out.println("Salesperson " + (min_sale + 1) + " had the minimum sale with " + s[min_sale]);
}
}
temp is a local variable that had been created in the main and passed to your printSummary(int[] s) method, so there you can access it by using s.
for (int i = 0; i < s.length; i++) { // STEP 7
if (s[i] > max_sale) max_sale = s[i]; // STEP 8
if (s[i] < min_sale) min_sale = s[i];
sum += s[i];
}
Took Andrew Tobilko code and changed it to save the index to the person that has highest sale value. Implementing this replacing your loop will work.
for (int i = 0; i < s.length; i++) { // STEP 7
if (s[i] > s[max_sale]) max_sale = i; // STEP 8
if (s[i] < s[min_sale]) min_sale = i;
sum += s[i];
}
This works at step 7/8 thanks to #andrew
int max = 0;
int min = Integer.MAX_VALUE;
for (int i= 0; i < s.length; i++) {
sum += s[i];
if (s[i] > max) {
max_sale = i;
max = s[i];
}
if (s[i] < min) {
min_sale = i;
min = s[i];
}
}
Related
the efficiency of the code and time complexity? I am running while loops with if and else statements to find the largest and smallest integer instead of for loops I just want to know if my code is efficient enough or I need to use for loops, I also want to know if there is any shortcut to find time complexity like for loop - it is n^2, while loop -n, and examples for O(log(n)) and O(log(n)) and how to find them would be helpful too.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of values in an array : ");
int n = scan.nextInt();
int[] arr = new int[n];
System.out.println("Enter values in an Araay :");
for (int i = 0; i < arr.length; i++) {
arr[i] = scan.nextInt();
}
int i = 0;
int j = 0;
int k = 0;
while (i < n && j < n) {
if (arr[i] > arr[i + 1]) {
j = arr[i];
k = arr[i + 1];
} else if (arr[i] < arr[i + 1]) {
j = arr[i + 1];
k = arr[i];
}
i++;
}
System.out.println("the largest element is : " + j);
System.out.println("the smallest element is : " + k);
}
Your code is more complicated than it should be. More than that it doesn't seem to be working properly.
One approach to find the smallest / largest number is presented below
import java.util.Scanner;
public class MyClass{
public static int findMax(int[] array){
int max = int[0];
for(int i = 1; i < array.length; i++){
if(array[i] > max){
max = array[i];
}
}
return max;
}
public static int findMin(int[] array){
int min = int[0];
for(int i = 1; i < array.length; i++){
if(array[i] < min){
min = array[i];
}
}
return min;
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of values in an array : ");
int n = scan.nextInt();
int[] arr = new int[n];
System.out.println("Enter values in an Araay :");
for (int i = 0; i < arr.length; i++) {
arr[i] = scan.nextInt();
}
System.out.println("Max: " + findMax(arr));
System.out.println("Min: " + findMin(arr));
}
}
Your code does not work properly, it doesn't give the correct values.
Unless you want to code all from scratch, there are other methods.
Take a look at the following, in fact it is O(n^2) for the sort:
for (int i = 0; i < arr.length; i++) {
arr[i] = scan.nextInt();
}
Arrays.sort(arr);
System.out.println("min: " + arr[0] + " max: " + " " + arr[arr.length - 1];
OR if it is important that you implement it by your self, you could achieve that with O(n), looping only once.
int min = arr[0], max = arr[0];
for(int i= 0; i < arr.length; i++) {
if(arr[i] < min) min = arr[i];
if(arr[i] > max) max = arr[i];
}
System.out.println("min: " + min + " max: " + max);
As the title says, I want to know a way (in Java) to find which row (in a matrix/2D Array) and column has the highest sum of its numbers.
There might be an easy solution but I'm struggling to find it.
I currently have the first part of the program but I can't seem to find a solution to the second part, which is finding the row and column with the highest sum.
Desired output
I'm a beginner at this so any kind of advice would be appreciated.
This is the first part of my code:
import javax.swing.JOptionPane;
public class summat{
public static void main(String[] args){
int mat[][] = new int [3][3];
int num, sumop, sumw, i, j, mayop = 0, mayw = 0;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
String input = JOptionPane.showInputDialog(null, "Products sold by the operator " + (i+1) + " in week " + (j+1) + ".");
mat[i][j] = Integer.parseInt(input);
}
}
/*Sum of individual rows*/
for(i=0;i<3;i++){
sumop = 0;
for(j=0;j<3;j++){
sumop = sumop + mat[i][j];
}
JOptionPane.showMessageDialog(null, "The operator " + (i+1) + " sold " + sumop + " units.");
}
/*Sum of individual columns*/
for(j=0;j<3;j++){
sumw = 0;
for(i=0;i<3;i++){
sumw = sumw + mat[i][j];
}
JOptionPane.showMessageDialog(null, "In week " + (j+1) + " the company sold " + sumw + " units.");
}
}
}
public static void method(int[] arr, int row, int col) {
// converting array to matrix
int index = 0;
int mat[][] = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
mat[i][j] = arr[index];
index++;
}
}
// calculating sum of each row and adding to arraylist
ArrayList<Integer> rsum = new ArrayList<Integer>();
for (int i = 0; i < row; i++) {
int r = 0;
for (int j = 0; j < col; j++) {
r = r + mat[i][j];
}
rsum.add(r);
}
// calculating sum of each col and adding to arraylist
ArrayList<Integer> csum = new ArrayList<Integer>();
for (int i = 0; i < row; i++) {
int sum = 0;
for (int j = 0; j < col; j++) {
sum = sum + mat[j][i];
}
csum.add(sum);
}
System.out.println(
"Maximum row sum is " + Collections.max(rsum) + " at row " + rsum.indexOf(Collections.max(rsum)));
System.out.println(
"Maximum col sum is " + Collections.max(csum) + " at col " + csum.indexOf(Collections.max(csum)));
}
public static void method(int[][] mat, int row, int col) {
// calculating sum of each row and adding to arraylist
ArrayList<Integer> rsum = new ArrayList<Integer>();
for (int i = 0; i < row; i++) {
int r = 0;
for (int j = 0; j < col; j++) {
r = r + mat[i][j];
}
rsum.add(r);
}
// calculating sum of each col and adding to arraylist
ArrayList<Integer> csum = new ArrayList<Integer>();
for (int i = 0; i < row; i++) {
int sum = 0;
for (int j = 0; j < col; j++) {
sum = sum + mat[j][i];
}
csum.add(sum);
}
System.out.println(
"Maximum row sum is " + Collections.max(rsum) + " at row " + rsum.indexOf(Collections.max(rsum)));
System.out.println(
"Maximum col sum is " + Collections.max(csum) + " at col " + csum.indexOf(Collections.max(csum)));
}
You can use the following logic and implement it as desired.
// Row calculation
int rowSum = 0, maxRowSum = Integer.MIN_VALUE, maxRowIndex = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
rowSum = rowSum + mat[i][j];
}
if (maxRowSum < rowSum) {
maxRowSum = rowSum;
maxRowIndex = i;
}
rowSum = 0; // resetting before next iteration
}
// Column calculation
int colSum = 0, maxColSum = Integer.MIN_VALUE, maxColIndex = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
colSum = colSum + mat[j][i];
}
if (maxColSum < colSum) {
maxColSum = colSum;
maxColIndex = i;
}
colSum = 0; // resetting before next iteration
}
System.out.println("Row " + maxRowIndex + " has highest sum = " +maxRowSum);
System.out.println("Col " + maxColIndex + " has highest sum = " +maxColSum);
Here we use two additional variables maxRowSum to store the highest sum of the row and maxRowIndex to store the index of the highest row. The same applies for column as well.
You can have to integers one for row(maxRow) and one for col(maxCol) to maintain max values:
int maxRow = Integer.MIN_VALUE;
/*Sum of individual rows*/
for(i=0;i<3;i++){
sumop = 0;
for(j=0;j<3;j++){
sumop = sumop + mat[i][j];
}
if(maxRow > sumop)
maxRow = sumop;
JOptionPane.showMessageDialog(null, "The operator " + (i+1) + " sold " + sumop + " units.");
}
int maxCol = Integer.MIN_VALUE;
/*Sum of individual columns*/
for(j=0;j<3;j++){
sumw = 0;
for(i=0;i<3;i++){
sumw = sumw + mat[i][j];
}
if(maxCol > sumw)
maxCol = sumw;
JOptionPane.showMessageDialog(null, "In week " + (j+1) + " the company sold " + sumw + " units.");
}
Here's a method that first computes both row-wise and column-wise sums in one loop (the same one it uses to find max row sum), and a second one to find the max column sum:
//This returns an array with {maxRowIndex, maxColumnIndex}
public static int[] findMax(int[][] mat) {
int[] rowSums = new int[mat.length];
int[] colSums = new int[mat[0].length];
int maxRowValue = Integer.MIN_VALUE;
int maxRowIndex = -1;
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
rowSums[i] += mat[i][j];
colSums[j] += mat[i][j];
}
if (rowSums[i] > maxRowValue) {
maxRowIndex = i;
maxRowValue = rowSums[i];
}
// display current row message
JOptionPane.showMessageDialog(null, "The operator " +
(i + 1) + " sold " + rowSums[i] + " units.");
}
int maxColumnValue = Integer.MIN_VALUE;
int maxColumnIndex = -1;
// look for max column:
for (int j = 0; j < mat[0].length; j++) {
if (colSums[j] > maxColumnValue) {
maxColumnValue = colSums[j];
maxColumnIndex = j;
}
// display column message
JOptionPane.showMessageDialog(null, "In week " +
(j + 1) + " the company sold " + colSums[j] + " units.");
}
return new int[] { maxRowIndex, maxColumnIndex };
}
The following test (I had to hard-code matrix values) produces [2, 2]:
public static void main(String[] args) {
int mat[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[] maxValues = findMax(mat);
System.out.println("Max row index: " +
maxValues[0] + ". Max Column index: " + maxValues[1]);
}
I checked out the questions that were already posted, but I still couldn't find a solution.
My output for the code is:
Enter the number of integers: 5
Enter 5 integers: 1
2
3
4
5
Enter the number to be deleted: 2
-1
package array;
import java.util.*;
//import java.util.ArrayLists;
public class DeleteFromArray {
public static void main(String[] args) {
int n = 0; // number of integers
int d = 0; // the number to be deleted
int count = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number of integers: ");
n = scan.nextInt();
if (n <= 0) {
System.out.println("Invalid input");
System.exit(-1);
}
int[] buffer = new int[n];
System.out.print("Enter " + n + " integers: ");
for (int k = 0; k < buffer.length; k++) {
buffer[k] = scan.nextInt();
}
System.out.print("Enter the number to be deleted: ");
d = scan.nextInt();
for (int i = 0; i < buffer.length; i++) {
if (buffer[i] == d) {
for (int j = 0; j < (buffer.length) - 1; j++) {
buffer[j] = buffer[j + 1];
}
count++;
break;
}
}
if(count ==0) {
System.out.println("Element not found!");
}
else {
System.out.print("Element Deleted Successfully..!!");
System.out.print("\nNow the New Array is :\n");
for (int i = 0; i < (buffer.length)-1; i++) {
System.out.println(buffer[i]+ " ");
}
}
scan.close();
}
}
Your for loop
for (int j = 0; j < (buffer.length) - 1; j++) {
buffer[j] = buffer[j + 1];
}
will not work properly because it will replace the value at 0 index with the value at index 1 and so on. What you want to do is just intialize the j=i where i is the index of d. and it will replace this value with the next.
for (int j = i; j < (buffer.length) - 1; j++) {
buffer[j] = buffer[j + 1];
}
Try this loop it will work.
Alright, so I tried implementing the bubble sort algorithm into my code, but now my output for the second array (in my code) is giving me a ton of zeros. Can anybody tell me what is wrong with my code and how I can fix it so the zeros are removed and the only thing that remains in the output for my second array are the fixed numerically?
public static void main(String[] args) {
System.out.println("Input up to '10' numbers for current array: ");
int[] array1 = new int[10];
int i;
Scanner scan = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
} else {
array1[i] = input;
}
}
System.out.println("\n" + "Original Array: ");
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + ": " + array1[j]);
}
int[] array2 = new int[i];
System.out.println("\n" + "Organized Array: ");
for (int j = 0; j < i; j++) {
int temp;
boolean organized = false;
while (organized == false) {
organized = true;
for (i = 0; i < array1.length - 1; i++) {
if (array1[i] > array1[i + 1]) {
temp = array1[i + 1];
array1[i + 1] = array1[i];
array1[i] = temp;
organized = false;
}
}
}
for (i = 0; i < array1.length; i++) {
System.out.println(array1[i]);
}
scan.close();
}
}
}
Copy your array1 to an array2 of the correct length before sorting, something like
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
}
array1[i] = input;
}
int[] array2 = Arrays.copyOfRange(array1, 0, i);
System.out.println("Before sorting: " + Arrays.toString(array2));
Arrays.sort(array2); // <-- How I would sort.
System.out.println("After sorting: " + Arrays.toString(array2));
The reason this is necessary is because i might not be 10 in which case your array contains 0(s) to fill the other positions.
Is it possible to move all my numbers from Array 1 to Array 2 using a for-loop?
Yes. You could implement a copyOfRange function with a for loop,
private static int[] copyOfRange(int[] arr, int start, int end) {
int pos = 0;
int[] out = new int[end - start];
for (int i = start; i < end; i++) {
out[pos] = arr[i];
pos++;
}
return out;
}
the built-in version is almost certainly better.
1) You are printing the array multiple times, I think you might be giving 0 as input and thats the reason you are seeing 0's everywhere.
2) You have created array2 which is not necessary.
Move the printing logic out of for loop as in the below snippet. Otherwise your logic looks fine except fot the wrong looping of print statement.
public static void main(String args[]) {
System.out.println("Input up to '10' numbers for current array: ");
int[] array1 = new int[10];
int i;
Scanner scan = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
} else {
array1[i] = input;
}
}
System.out.println("\n" + "Original Array: ");
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + ": " + array1[j]);
}
int[] array2 = new int[i];
System.out.println("\n" + "Organized Array: ");
for (int j = 0; j < i; j++) {
int temp;
boolean organized = false;
while (organized == false) {
organized = true;
for (i = 0; i < array1.length - 1; i++) {
if (array1[i] > array1[i + 1]) {
temp = array1[i + 1];
array1[i + 1] = array1[i];
array1[i] = temp;
organized = false;
}
}
}
scan.close();
}
for (i = 0; i < array1.length; i++) {
System.out.println(array1[i]);
}
}
I'm trying to write code that checks for repeat numbers in an array. If numbers repeat within the same row, it should generate another random number to replace the number. This is my class/method that is meant to accomplish this goal:
import java.util.*;
public class NoRepeats
{
public static void clean(int ticks[][])
{
for(int i = 0; i < ticks.length; i++)
{
for(int j = 0; j < ticks[0].length; j++)
{
nums[j] = ticks[i][j];
}
for(int k = 0; k < nums.length; k++)
{
for(int count = k + 1; count < nums.length; count++)
{
int othNums = nums[count];
while(true)
{
if(nums[k] == othNums)
{
System.out.print("\n\n Repeat:" + nums[k] + k + " " + othNums + "\tTicket Number: " + (i+1) +"\n\n\n");
nums[k] = 1 + rndm.nextInt(48);
for(int counter = count; counter < nums.length; counter++)
{
int othNums2 = nums[count];
if(nums[k] == othNums2)
{
System.out.print("\n\n Repeat NUM2:" + nums[k] + " " + othNums2 + "\tTicket Number: " + (i+1) +"\n\n\n");
nums[k] = 1 + rndm.nextInt(48);
}
}
for(int l = 0; l < k; l++)
{
int othNums3 = nums[l];
if(nums[k] == othNums3)
{
System.out.print("\n\n RepeatNUM2: " + nums[k] + " " + othNums3 + "\tTicket Number: " + (i+1) +"\n\n\n");
nums[k] = 1 + rndm.nextInt(48);
}
}
}
else
{
break;
}
}
count++;
}
}
for(int q = 0; q < nums.length; q++)
{
ticks[i][q] = nums[q];
}
count = 0;
}
}
public static int nums[] = new int[6];
public static int count = 1;
public static Random rndm = new Random();
public static int numsMatched[] = new int[100];
}
For some reason, there are still matches and I don't know why. Can anyone find what I've done wrong?
You're incrementing count twice and thus skip entries:
for(int count = k + 1; count < nums.length; count++) //<- increment 1
{
int othNums = nums[count];
while(true)
{
//snip
}
count++; //<- increment 2
}
The problem probably originates from the fact that you have a static variable which is also called count and which will be shadowed by the count defined in the loop:
public static int count = 1;
So either remove the second increment or rename one of the variables.