This question already has answers here:
Finding minimum and maximum in Java 2D array
(4 answers)
Closed 2 years ago.
This is my sample code, I am having trouble with finding the smallest variable. It always returns zero while finding the largest variable works fine.
I have used the same technique but don't know where I am going wrong.
Please help me.
for (int i = 0; i < n; i++) {
smallest = array[i][0];
largest = array[i][0];//set largest to 0 at each round
mean = 0;
System.out.print("Round " + (i + 1) + " Cards: ");
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
if (in.hasNextInt()) {
for (int j = 0; j < m; j++) {
array[i][j] = in.nextInt();
if (array[i][j] > 9) {
System.out.println("Must be between 1-9");
// Arrays.fill(array, null);
j = 0;
System.out.print("Round " + (i + 1) + " Cards: ");
}
// Largest value
if (array[i][j] >= largest) {
largest = array[i][j];
}
// Smallest value
//smallest = array[i][0];
if (array[i][j] < smallest) {
smallest = array[i][j];
}
// total
mean += array[i][j];
}
break;
} else {
in.next();
}
}
//mean calculation
array[i][m] = largest;
array[i][m + 1] = smallest;
array[i][m + 2] = (int) mean / m;
}
This would be a clean way to find the minimum and maximum value in a 2D array.
You can replace i < array.length with m and i < array[i].length with n, if I understood correctly what you were trying to say in the comments.
public static void main(String[] args) {
int[][] array = new int[][]{{7, 8, 32439, 0}, {1, -32, 3, 5}};
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (array[i][j] < smallest) {
smallest = array[i][j];
}
if (array[i][j] > largest) {
largest = array[i][j];
}
}
}
System.out.println(smallest);
System.out.println(largest);
}
Output:
-32
32439
Related
I created this program that allows the user to input 5 numbers for array 1 and 5 numbers for array 2, the idea of the program is to iterate through those arrays and find the matching values for example: user types on input 1 = 1, 2, 3, 4 and 5 and the same for input 2, the lowest matching value is 1 and my program does that, if there is no matching value displays a message that there is no matching values and my program does that. However, if the user inputs something like this on 1 = 3, 4, 5, 7, 2 and input 2 = 9, 12, 8, 7, 15, what my program does in this case, variable min1 on array1 find lowest value which is 2 and variable min2 on array2 find lowest value which is 7 so in theory does not match, but they are asking me to find the lowest MATCHING values so both of them have 7 so it should display 7, I have some code there that select the 7 on each array and display them, now I have to figure out how to add that temporal variable into the displays so it only displays one or the other, as of now it displays 7 and then no matching value, tried adding it to the if statement but couldn't make it
import java.util.Scanner;
public class SmallestArrayItem {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int array1[] = new int[5];
int array2[] = new int[5];
System.out.println("Please enter 5 values for array 1");
for(int i = 0; i < array1.length; i++) {
int userInput = keyboard.nextInt();
array1[i] = userInput;
}
System.out.println("Please enter 5 values for array 2");
for(int i = 0; i < array2.length; i++) {
int userInput = keyboard.nextInt();
array2[i] = userInput;
}
int min1 = array1[0];
for(int index1 = 1; index1 < array1.length; index1++) {
if(array1[index1] < min1) {
min1 = array1[index1];
}
}
int min2 = array2[0];
for(int index2 = 1; index2 < array2.length; index2++) {
if(array2[index2] < min2) {
min2 = array1[index2];
}
}
int tmpval = Integer.MAX_VALUE;
for(int i = 0; i < array1.length; i++){
for(int j = 0; j < array2.length; j++){
if(array1[i] == array2[j]){
// same value
if(tmpval > array1[i]){
tmpval = array1[i];
}
}
}
}
System.out.println(tmpval);
if(min1 == min2) {
System.out.println("The Smalest match in the array is : " + min1);
} else if(min1 != min2) {
System.out.println("There is no smallest matching integer!");
}
}
}
Your code look great, its just a problem with your logic. In your question, you talked about nesting for loops, so you were on the right track.
int[] arr1 = {3,4,5,7,2};
int[] arr2 = {9,12,8,7,15};
int tmpval = Integer.MAX_VALUE;
for(int i = 0; i < arr1.length; i++){
for(int j = 0; j < arr2.length; j++){
if(arr1[i] == arr2[j]){
// same value
if(tmpval > arr1[i]){
tmpval = arr1[i];
}
}
}
}
System.out.println(tmpval);
It's not clear from your description if the matching values have to be at the same position in the two arrays. If we assume that they do then something like this would work:
int[] arr1 = {3,4,5,7,2};
int[] arr2 = {9,12,8,7,15};
int minIdx = -1;
for(int i = 0; i < arr1.length; i++)
{
if(arr1[i] == arr2[i] && (minIdx < 0 || arr1[i] < arr1[minIdx]))
{
minIdx = i;
}
}
if(minIdx < 0)
System.out.println("No match");
else
System.out.println("Min match: " + arr1[minIdx]);
Note how we use a negative index as an indicator that we haven't found a match. The standard trick of using Integer.MAX_VALUE as our starting value isn't really safe as it could be a matching value in the array.
If the matching values can appear at any position in the arrays then you'll need to compare each value in array1 with every value in array2:
for(int i = 0; i < arr1.length; i++)
{
for(int j = 0; j < arr2.length; j++)
{
if(arr1[i] == arr2[j] && (minIdx < 0 || arr1[i] < arr1[minIdx]))
{
minIdx = i;
}
}
}
Thanks for all your help guys, this is the final code:
public class SmallestArrayItem {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int array1[] = new int[5];
int array2[] = new int[5];
System.out.println("Please enter 5 values for array 1");
for(int i = 0; i < array1.length; i++) {
int userInput = keyboard.nextInt();
array1[i] = userInput;
}
System.out.println("Please enter 5 values for array 2");
for(int i = 0; i < array2.length; i++) {
int userInput = keyboard.nextInt();
array2[i] = userInput;
}
int minIdx = -1;
for(int i = 0; i < array1.length; i++)
{
for(int j = 0; j < array2.length; j++)
{
if(array1[i] == array2[j] && (minIdx < 0 || array1[i] < array1[minIdx]))
{
minIdx = i;
}
}
}
if(minIdx < 0)
System.out.println("There is no smallest matching integer!");
else
System.out.println("The Smallest match in the array is : " + array1[minIdx]);
}
}
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);
I need to print all prime numbers from 1 to 1,000,000 and print all even numbers from 4 to 10,000 and two prime numbers that sum to it.
I have a sieve method that changes all non-prime numbers in an array to a 0 (the problem specifically asks for this to be done), and I need to use a goldbach method that passes this array and displays all even numbers from 4 to 10,000 and two primes that sum up to that number.
The point of the goldbach portion of the problem is to print the numbers efficiently, and I am pretty sure my solution uses a polynomial time search when the correct solution is to be done with a linear time search. Any clue on how I might optimize this?
import java.lang.Math;
public class sieveAndGoldbach {
public static void sieve(int[] a) {
int n = a.length;
a[0] = 0;
for (int i = 1; i <= Math.sqrt(n); i++) {
if (a[i] != 0) {
for (int j = a[i]*a[i]; j <= n; j+=a[i]) {
a[j-1] = 0;
}
}
}
}
public static void goldbach(int[] a) {
int max = 10000;
for (int i = 4; i <= max; i += 2) {
int count = 0;
for (int j = 0; j < i/2; j++) {
if (a[j] != 0) {
int difference = i-a[j];
for (int k = 0; k < max; k++) {
if (a[k] == difference && count == 0) {
System.out.println(i + " = " + a[j] + " + " + (difference));
count++;
}
}
}
}
}
}
public static void main(String[] args) {
//initialize and fill array from 1 to n
int n = 1000000; //initially one million GOLDBACH METHOD WILL NOT WORK FOR n < 10,000
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = i + 1;
}
//Call sieve method on array a, then print all primes, not the zeros
sieve(a);
for (int i = 0; i < n; i++) {
if (a[i] != 0) {
System.out.print(a[i]);
System.out.print(" ");
}
}
System.out.print("\n");
//Call goldbach method on array a
goldbach(a);
}
}
You currently seem to be iterating through the array of primes for each prime looking for one that sums to your target. That's not necessary; you just need to check whether the difference is a prime:
int[] primes;
int target;
for (int i = 2; i < target / 2; i++) {
if (primes[i] != 0 && primes[target - i] != 0)
...
}
Beyond that I can't see a lot of obvious optimisation but there may well be some numerical analysis that allows you to target likely primes first.
Given a list of unsorted integers, find the pair of elements that have the smallest absolute difference between them. If there are multiple pairs, find them all.
My reasoning was to compare each: arr[j] - arr[i] with lowest and if it is smaller or equal to that, add that value to the array lowest, but it's not working.
Code:
static int[] closestNumbers(int[] arr) {
int lowest = arr[1] - arr[0];
int lowestArray[] = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (Math.abs(arr[j] - arr[i]) < lowest) {
lowest = Math.abs(arr[j] - arr[i]);
}
}
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] == lowest) {
lowestArray[i] = arr[i];
}
}
return lowestArray;
}
Below is the required code:-
import java.util.*;
class GFG
{
// Returns minimum difference between
// any two pair in arr[0..n-1]
static void printMinDiffPairs(int arr[], int n)
{
if (n <= 1)
return;
// Sort array elements
Arrays.sort(arr);
// Compare differences of adjacent
// pairs to find the minimum difference.
int minDiff = arr[1] - arr[0];
for (int i = 2; i < n; i++)
minDiff = Math.min(minDiff, arr[i] - arr[i-1]);
// Traverse array again and print all pairs
// with difference as minDiff.
for ( int i = 1; i < n; i++)
{
if ((arr[i] - arr[i-1]) == minDiff)
{
System.out.print("(" + arr[i-1] + ", "
+ arr[i] + ")," );
}
}
}
// Driver code
public static void main (String[] args)
{
int arr[] = {5, 3, 2, 4, 1};
int n = arr.length;
printMinDiffPairs(arr, n);
}
}
Does above program handle duplicates?
The cases like {x, x, x} are not handled by above program. For this case, the expected output (x, x), (x, x), (x, x), but above program prints (x, x), (x, x)
The problem is that when you initialize your lowest array like this,
int[] lowest = new int[arr.length];
you are actually initializing it with zeros. Also, whenever you are taking arr[j]-arr[i], it will always be greater than or equal to zero (since your array is sorted in an ascending fashion), leading to incorrect results because the following if statement,
if(Math.abs(arr[j] - arr[i]) <= lowest[l]) {
lowest[l] = Math.abs(arr[j] - arr[i]);
}
will never execute for differences greater than 0.
Initialize the lowest array like so,
for(int i=0;i<lowest.length;i++){
lowest[i] = Integer.MAX_VALUE;
}
Also, your outer loop for the i variable starts with i=1, but it should start with i=0
static int[] closestNumbers(int[] arr) {
int minAbs = Integer.MAX_VALUE;
Arrays.sort(arr);
int[] out = new int[(arr.length) + 3];
int j = 0;
for (int i = 1; i < arr.length; i++) {
minAbs = Math.min(minAbs, Math.abs(arr[i] - arr[i - 1]));
}
for (int i = 1; i < arr.length; i++) {
if(minAbs ==Math.abs(arr[i] - arr[i - 1])) {
out[j++]=arr[i - 1];
out[j++]=arr[i];
}
}
int[] tem= new int[j];
for(int i=0; i<j;i++) {
tem[i]=out[i];
}
return tem;
}
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.