This question already has answers here:
How do i find and count duplicates in a 2 dimensional array?
(4 answers)
Closed 5 years ago.
I am a beginner coder just learning arrays. I recently learned 2d arrays and I am trying to find out if there is a duplicate in a 2d array. I know how to check if there is a duplicate in the same column or row, but I cannot figure out how to compare a number if it is not in the same column or row as the number I am trying to compare it to. Here is my code as of now:
public static boolean correctNumbers(int[][] values) {
for (int i = 0; i < values.length; i++) {
for (int j = 0; j < values[i].length; j++) {
int num = values[i][j];
for (int k = j + 1; k < values.length; k++) {
if (num == values[i][k] || num > values.length * values.length || num < 1) {
return false;
}
}
for (int l = i + 1; l < values.length; l++) {
if (num == values[l][j] || num > values.length * values.length || num < 1) {
return false;
}
}
}
}
return true;
}
I need to create a method and I cannot use any other methods in creating it.
Thanks for the help!
Edit: It returns false if there is duplicates in the array, a number in the array is less than 1, or greater than total number of elements in the array. In other words this method is checking to see if the array contains all the values of 1 to (i*j) in the array. I realized I did a bad job of explaining that part. Thanks again!
You can simplify the logic by saving the numbers into a hashset and when you're iterating them check each one if it's already there (meaning duplicate) otherwise add it:
public static boolean correctNumbers(int[][] values) {
Set<Integer> set = new HashSet<>();
for (int i = 0; i < values.length; i++) {
for (int j = 0; j < values[i].length; j++) {
int num = values[i][j];
if (set.contains(num)) {
return false;
}
set.add(num);
}
}
return true;
}
EDIT
We can use an array for the same functionality the hashset is doing in the code above:
public static boolean correctNumbers(int[][] values) {
int n = values.length;
int[] dict = new int[n * n + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < values[i].length; j++) {
int num = values[i][j];
if (num < 1 || num > n || dict[num] != 0) {
return false;
}
dict[num] = 1;
}
}
return true;
}
Related
I am fairly new to this so any help would be appreciated. I am trying to subtract elements of array 'b' from array 'a'( not removing but just subtracting) provided if the element of array 'a' is greater than the corresponding element of array 'b'.
I am not getting the required output its just printing the array I have entered
Scanner sc = new Scanner(System.in);
short n = sc.nextShort();
short a[] = new short[n];
short b[] = new short[n];
for (short i = 0; i < n; i++) {// taking elements input
a[i] = sc.nextShort();
}
for (short i = 0; i < n; i++) {// taking elements input
b[i] = sc.nextShort();
}
short m = 0;
for (short i = 0; i < n; i++) {// finding smallest element in array 'a'
for (short j = 0; j < n; j++) {
if (a[i] < a[j]) {
m = a[i];
}
}
}
boolean allequal = false;
while (!allequal) {
for (short i = 0; i < n; i++) {// subtracting elements
if (a[i] == m)
continue;
if (a[i] >= b[i]) {
a[i] -= b[i];
}
}
for (short i = 0; i < n; i++) {
for (short j = 0; j < n; j++) {
if (a[i] == a[j]) {
allequal = true;
} else {
allequal = false;
}
}
}
}
for (int i = 0; i < n; i++) {// printing array 'a'
System.out.print(a[i] + " ");
}
5
5 7 10 5 15
2 2 1 3 5
5 5 9 5 10
Your program does not enter while loop since you mistakenly used = operator in while (allequal = false) { which is assignment, not comparison. The correct form would be allequal == false which rewrites to !allequal. I didn't checked remaining code.
Note you should use good IDE which would prevent you doing such bug and provide debugger from which you could easily discover yourself.
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.
Recently, I took Linkedin placement test in which there was a question in which output for 4 test cases were wrong for me. I could not figure out what was my mistake becasue inputs/outputs were hidden.
Anyways here was the question:
Find the maximum element from an array where product of any other two elements would be equal to that number and return that number .If no, such element is there then return -1.
Here was my solution:
static int maxElement(int[] arr) {
Arrays.sort(arr);
int max = arr[arr.length-1];
int result = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
result = arr[i] * arr[j];
if (result == max) {
return max;
}
}
}
return -1;
}
I guess you need to find the possible maximum number in the array and the product of two elements in the array.
If I assume this, your code fails for this test case:
int[] arr = {2,4,5,3,7,6}; , where the answer should be 6
Check this below code it will work for above test-case.
Just add one more reverse for loop to check the possible value and product.
static int maxElement(int[] arr) {
Arrays.sort(arr);
for (int k = arr.length-1; k >= 0; k--) {
int max = arr[k];
int result = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
result = arr[i] * arr[j];
if (result == max) {
return max;
}
}
}
}
return -1;
}
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < a.length; i++) {
list.add(a[i]);
}
int maxSum = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if ((a[i] * a[j]) > maxSum) {
if(list.contains(a[i] * a[j]))
maxSum = a[i] * a[j];
}
}
}
if (maxSum != 0)
return maxSum;
return -1;
This question already has answers here:
How to count distinct values in a list in linear time?
(3 answers)
Closed 7 years ago.
For this Algorithm assignment in class I have to find all the unique values in a 1000x250 2D array.
The data is between 2000000 to 2200000. All the data is stored in a 2D int array called data.
The problem I am having is that it takes a bit of time to run this and my prof said we can't use other data sets and also we need to optimize our code so it runs at a good speed.
int[] uniqueValues = new int[200000];
boolean isUnique = true;
int uniqueCounter = 0;
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
for (int x = 0; x < uniqueCounter; x++) {
if (data[i][j] != uniqueValues[x]) {
isUnique = true;
} else {
isUnique = false;
break;
}
}
if (isUnique) {
uniqueValues[uniqueCounter] = data[i][j];
uniqueCounter++;
}
}
}
Well if you allocate 200000 ints for the result anyway, you can use them as counters for each value, then collect the ones that only occur once:
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
uniqueValues[data[i][j] - 2000000]++;
}
}
int uniqueCounter = 0;
for (int i = 0; i < uniqueValue.length; i++) {
if (uniqueValues[i] == 1) {
uniqueValues[uniqueCounter++] = i + 2000000;
}
}
Creating the array, I am letting the user choose the length:
StartNum = scan.nextInt();
int[] NumBox = new int[StartNum];
for (int i = 1; i < NumBox.length+1; i++)
{NumBox[i - 1] = i;}
NumBox[0]=0;
Assuming there are other methods that can change cells in NumBox to 0, how would I use a for loop to check each cells in the array for any divisor? If there are no divisors for the cell in the array, it will then become a 0. For example, if the array is [0,2,0,4,0,6,7,8,9] 9,2 and 7 would become a 0.
The code below is what I tired but didn't get far.
boolean NoDiv=false;
for (int a=1; a < NumBox.length+1; a++)
{
a++
for (int check=1; a < NumBox.length+1; check++)
{
if (NumBox[a-1]% check == 0 && NumBox[a-1] !=0)
{
NumBox[a-1] = 0;
}
}
}
for (int i = 0; i < NumBox.length; i++) {
if (NumBox[i] == 0) continue;
boolean hasDivisor = false;
for (int j = 0; j < i; j++) {
if (NumBox[j] == 0) continue;
if (NumBox[i] % NumBox[j] == 0) {
hasDivisor = true;
break;
}
}
if (!hasDivisor) NumBox[i] = 0;
}