Find Common Elements between two Arrays - java

I want to find the common elements between two arrays with different sizes and put them in another array.
Can you tell what's wrong with my code?
public static int[] numratEQelluar(int[] vargu, int[]varguPer)
{
int count = 0;
int [] nrQelluar = new int[count];
for(int i = 0; i<vargu.length; i++)
{
for(int idx = 1;idx<varguPer.length ; idx++)
{
if(vargu[i] == (varguPer[idx]))
{
count++;
for(int index = 0; index<nrQelluar.length; index++)
{
nrQelluar[index] = vargu[i];
}
}
}
}
return nrQelluar;

The reason it doesn't work is indeed due to incorrect memory allocation to nrEqualler as been said in the comments.
However, there are a few thing i'd change in your code:
using a LinkedList instead of primitive int [] for dynamic sized
array is much more efficient (add in O(1)).
less indentations and confusing indexes by extracting methods.
So this should do:
public static int[] numratEQelluar(int[] vargu, int[]varguPer){
List<Integer> nrQelluar = new LinkedList<Integer> ();
for(int i = 0; i < vargu.length; i++) {
if (contains(varguPer, vargu[i])) nrQelluar.add(vargu[i]);
}
return toPrimitive(nrQelluar);
}
private static boolean contains(int [] array, int num){
for(int i = 0; i < array.length; i++){
if(array[i] == num) return true;
}
return false;
}
private static int[] toPrimitive(List<Integer> list) {
int[] primitiveArray = new int[list.size()];
for(int i = 0; i < list.size(); i++){
primitiveArray[i] = list.get(i);
}
return primitiveArray;
}

The problem is between these lines of code
int count = 0;
int [] nrQelluar = new int[count];
The size of your new array will be zero. try changing this to the sum of the length of both the arrays.
Updated with a working code.
Try this code :
public static Integer[] findCommonElements(int[] arr1, int[] arr2){
HashSet set = new HashSet<>();
for(int i=0;i<arr1.length;i++){
for(int j=0;j<arr2.length;j++){
if(arr1[i] == arr2[j]){
set.add(arr1[i]);
}
}
}
Integer[] resultArray = (Integer[]) set.toArray(new Integer[set.size()]);
return resultArray;
}
Using a set will ensure that you won't get any duplicates in the resulting array. If duplicates are fine, then you can use ArrayList to store the common elements and then convert them into Array.

Related

Having a casting issue with traveling salesperson using a greedy algorithm

I figure I have the general idea down for how to solve the algorithm but the implementation seems to elude me. What I have thus far is this:
public class GreedySalesman {
public static int[] greedySalesmanSolution(int[][] distances) {
List cityList = new ArrayList();
for(int[] array: distances) {
cityList.add(Arrays.asList(array));
}
List<Integer> initialResult = new ArrayList();
initialResult.add(0);
List<Integer> finalResult = findMinDistance(cityList, cityList, initialResult, 0);
/*int finalResultArray = new int[finalResult.size()+1];
int i = 0;
while (!(finalResult.isEmpty)) {
finalResultArray[i] = finalResult.poll();
i++;
}
return finalResultArray;
*/
return null;
}
public static List<Integer> findMinDistance(List<List<Integer>> initialCityInput, List<List<Integer>> cityInput, List<Integer> distanceResult, int index) {
if(cityInput.isEmpty()) {
distanceResult.add(0);
return distanceResult;
}
int min = Collections.min(initialCityInput.get(index));
List<Integer> city = initialCityInput.get(index);
index = city.indexOf(min);
distanceResult.add(index);
cityInput.remove(city);
return findMinDistance(initialCityInput,cityInput,distanceResult,index);
}
}
That is, the algorithm will take an two dimensional array of ints as an input, then make a List cityList referring to distances, then pass it into findMinDistance. The commented out part is where the result from findMinDistance will be converted into an array of ints and returned as finalResultArray but that part is not important yet.
findMinDistance will take in a two dimensional list of Integers twice, a List of Integers that will become the result and an int representing an index.
The function will return the distanceResult when cityInput has been emptied. Otherwise it will start with the first city based on the index, get the minimum distance from that List and its index and add the index to the distanceResult.
Once that has been done, the city will be removed from the cityInput and the program will go into recursion until cityInput has been emptied.
The issue I am getting currently is
I cannot be cast to java.lang.Integer
at
int min = Collections.min(initialCityInput.get(index));
And in main upon trying to run the program with some test data.
Any help will be appreciated.
======
Edit:
I made some changes to my code
public class GreedyTSP {
public int[] greedySalesmanSolution(int[][] distances) {
List<List<Integer>> cityList = new ArrayList();
List<List<Integer>> initialCityList = new ArrayList();
int iLength = distances.length;
for (int i = 0; i < iLength; ++i) {
int jLength = distances[0].length;
cityList.add(new ArrayList(jLength));
initialCityList.add(new ArrayList(jLength));
for (int j = 0; j < jLength; ++j) {
cityList.get(i).add(distances[i][j]);
initialCityList.get(i).add(distances[i][j]);
}
}
List<Integer> initialResult = new ArrayList();
initialResult.add(0);
List<Integer> finalResult = findMinDistance(initialCityList, cityList, initialResult, 0);
int[] finalResultArray = new int[finalResult.size()];
Iterator<Integer> iterator = finalResult.iterator();
for (int i = 0; i < finalResultArray.length; i++){
finalResultArray[i] = iterator.next().intValue();
}
return finalResultArray;
}
public List<Integer> findMinDistance(List<List<Integer>> initialCityInput, List<List<Integer>> cityInput, List<Integer> distanceResult, int initialIndex) {
if(cityInput.isEmpty()) {
distanceResult.add(0);
return distanceResult;
}
List<Integer> city = initialCityInput.get(initialIndex);
Integer min = findMin(city, distanceResult, initialIndex);
int resultIndex = city.indexOf(min);
distanceResult.add(resultIndex);
cityInput.remove(city);
return findMinDistance(initialCityInput,cityInput,distanceResult,resultIndex);
}
public Integer findMin(List<Integer> city, List<Integer> distanceResult, int inputIndex) {
Integer min = Integer.MAX_VALUE;
for(int i = 0; i < city.size();i++) {
if (city.get(i) > inputIndex && city.get(i) < min) min = city.get(i);
}
int resultIndex = city.indexOf(min);
if(distanceResult.contains(resultIndex)) {
return findMin(city, distanceResult, inputIndex);
}
return min;
}
}
Im not having any cast errors at the moment but it seems that the parts of my program dealing with recursion are causing StackOverflowError-s. I've been messing with this thing for literally 16 hours now and I'm all out of ideas as to why. Any ideas?
The problem with your casting is the following
List<List<Integer>> initialCityInput is a List containing Lists with integers.
Therefore initalCityInput.get(index) returns a List not an Int, which cannot be cast to int.
Well, I looked around a bit and I was basically overcomplicating the task through using multidimensional arraylists. I changed the code quite a bit:
public class GreedyTSP {
public static int[] greedySolution(int[][] adjacencyMatrix) {
List<Integer> visitedCities = new ArrayList<>();
int min = Integer.MAX_VALUE;
int startLocation = 0;
int tempStartLocation = 0;
int[] resultArray = new int[adjacencyMatrix.length+1];
visitedCities.add(0);
while(visitedCities.size() < adjacencyMatrix.length ){
for(int i = 0; i < adjacencyMatrix.length; i++){
if(!visitedCities.contains(i) && adjacencyMatrix[startLocation][i] < min){
min = adjacencyMatrix[startLocation][i];
tempStartLocation = i;
}
}
startLocation = tempStartLocation;
visitedCities.add(tempStartLocation);
min = Integer.MAX_VALUE;
}
visitedCities.add(0);
for(int i = 0; i < resultArray.length; i++){
int temp = visitedCities.get(i);
resultArray[i] = temp;
}
return resultArray;
}
}
This will solve the task using a greedy algorithm

How to return specific int values from an array; How to make a testclass?

I started to code an assignment for uni, but after a short while, i got stuck.
public class MostCommonElemnt
{
//private int[] liste;
public MostCommonElemnt()
{
//int[] liste = {1,2,3,4,5,6,7,8,9};
}
Is it bad to initialize an array in the constructor, or is it just not necassary?
public int findMostCommonElemnt(int[] list)
{
int help = 0;
for(int i = 0; i < liste.length; i++)
{
help = list[i];
}
return help;
}
Here i tried to get a specific int value (or number) returned from my int array, but "help" only returns the last number from the int array. How do i get the 2nd or 4th? To see all of them i can use System.out.println();
public static void main (int[] args)
{
//int[] liste = {1,2,3,4,5,6,7,8,9};
System.out.println(new MostCommonElemnt().findMostCommonElemnt(int[] list));
}
}
In this section i tried to make a testMethod but, i can not get it to work,
BlueJ (we have to use it for uni) always complaints about something.
I especially to not know, what to do after the
new MostCommonElemnt().
I just want, the programm to take specific numbers, with which i want to test. e.g: {1,2,3,4,5,6,7...}
otherwise i always have to type them in, which gets boring fast.
This could probably be shorter, but it works.
public static int findMostCommonElement(int[] list) {
int max = 0;
for (int i : list)
if (i > max)
max = i;
int[] newArr = new int[max];
for (int i = 0; i < max; i++)
newArr[i] = 0;
for (int i = 0; i < max; i++)
newArr[list[i]] += 1;
int mostCommon = 0;
int mostCommonMax = 0;
for (int i = 0; i < max; i++)
if (newArr[i] > mostCommonMax) {
mostCommonMax = newArr[i];
mostCommon = i;
}
return mostCommon;
}
To pass fixed values to your method, you can use:
int[] liste = {1,2,3,4,5,6,7,8,9};
System.out.println(new MostCommonElemnt().findMostCommonElemnt(liste));
You can return the second value of the array using return list[1]; inside the findMostCommonElemnt method, but this probably isn't what the method should do.

Creating an Array with the same numbers from an old one but without repetitions

So I created an array with random numbers, i printed and counted the repeated numbers, now I just have to create a new array with the same numbers from the first array but without any repetitions. Can't use ArrayList by the way.
What I have is.
public static void main(String[] args) {
Random generator = new Random();
int aR[]= new int[20];
for(int i=0;i<aR.length;i++){
int number=generator.nextInt(51);
aR[i]=number;
System.out.print(aR[i]+" ");
}
System.out.println();
System.out.println();
int countRep=0;
for(int i=0;i<aR.length;i++){
for(int j=i+1;j<aR.length-1;j++){
if(aR[i]==aR[j]){
countRep++;
System.out.println(aR[i]+" "+aR[j]);
break;
}
}
}
System.out.println();
System.out.println("Repeated numbers: "+countRep);
int newaR[]= new int[aR.length - countRep];
}
Can someone help?
EDIT: Can't really use HashSet either. Also the new array needs to have the correct size.
Using Java 8 and streams you can do the following:
int[] array = new int[1024];
//fill array
int[] arrayWithoutDuplicates = Arrays.stream(array)
.distinct()
.toArray();
This will:
Turn your int[] into an IntStream.
Filter out all duplicates, so retaining distinct elements.
Save it in a new array of type int[].
Try:
Set<Integer> insertedNumbers = new HashSet<>(newaR.length);
int index = 0;
for(int i = 0 ; i < aR.length ; ++i) {
if(!insertedNumbers.contains(aR[i])) {
newaR[index++] = aR[i];
}
insertedNumbers.add(aR[i]);
}
One possible approach is to walk through the array, and for each value, compute the index at which it again occurs in the array (which is -1 if the number does not occur again). The number of values which do not occur again is the number of unique values. Then collect all values from the array for which the corresponding index is -1.
import java.util.Arrays;
import java.util.Random;
public class UniqueIntTest
{
public static void main(String[] args)
{
int array[] = createRandomArray(20, 0, 51);
System.out.println("Array " + Arrays.toString(array));
int result[] = computeUnique(array);
System.out.println("Result " + Arrays.toString(result));
}
private static int[] createRandomArray(int size, int min, int max)
{
Random random = new Random(1);
int array[] = new int[size];
for (int i = 0; i < size; i++)
{
array[i] = min + random.nextInt(max - min);
}
return array;
}
private static int[] computeUnique(int array[])
{
int indices[] = new int[array.length];
int unique = computeIndices(array, indices);
int result[] = new int[unique];
int index = 0;
for (int i = 0; i < array.length; i++)
{
if (indices[i] == -1)
{
result[index] = array[i];
index++;
}
}
return result;
}
private static int computeIndices(int array[], int indices[])
{
int unique = 0;
for (int i = 0; i < array.length; i++)
{
int value = array[i];
int index = indexOf(array, value, i + 1);
if (index == -1)
{
unique++;
}
indices[i] = index;
}
return unique;
}
private static int indexOf(int array[], int value, int offset)
{
for (int i = offset; i < array.length; i++)
{
if (array[i] == value)
{
return i;
}
}
return -1;
}
}
This sounds like a homework question, and if it is, the technique that you should pick up on is to sort the array first.
Once the array is sorted, duplicate entries will be adjacent to each other, so they are trivial to find:
int[] numbers = //obtain this however you normally would
java.util.Arrays.sort(numbers);
//find out how big the array is
int sizeWithoutDuplicates = 1; //there will be at least one entry
int lastValue = numbers[0];
//a number in the array is unique (or a first duplicate)
//if it's not equal to the number before it
for(int i = 1; i < numbers.length; i++) {
if (numbers[i] != lastValue) {
lastValue = i;
sizeWithoutDuplicates++;
}
}
//now we know how many results we have, and we can allocate the result array
int[] result = new int[sizeWithoutDuplicates];
//fill the result array
int positionInResult = 1; //there will be at least one entry
result[0] = numbers[0];
lastValue = numbers[0];
for(int i = 1; i < numbers.length; i++) {
if (numbers[i] != lastValue) {
lastValue = i;
result[positionInResult] = i;
positionInResult++;
}
}
//result contains the unique numbers
Not being able to use a list means that we have to figure out how big the array is going to be in a separate pass — if we could use an ArrayList to collect the results we would have only needed a single loop through the array of numbers.
This approach is faster (O(n log n) vs O (n^2)) than a doubly-nested loop through the array to find duplicates. Using a HashSet would be faster still, at O(n).

Find values in array and return index

I want to return an array with the index's where the getElem() is equal or higher a certain value.
This is my function:
public static int []findIndex(BufferedImage image,int value)
{
DataBuffer b = image.getRaster().getDataBuffer();
int array[] = new int[600];
for(int i=0;i<76400;i++)
{
if(b.getElem(i)>=value)
array[i]=i;
}
return array;
}
but i have an error
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 27001
at arraytest.imageMan.findIndex(imageMan.java:139)
at arraytest.imageMan.main(imageMan.java:183)"
int array[] = new int[600];
The array you declare is of size 600.
for(int i=0;i<76400;i++)
Yet you attempt to reference the array at the 76400'th index.
Why doesn't this work?
Well, when you say new int[600], you are essentially saying, my array can store 600 things, and this means that it has 600 different "slots" to store values.
You access these values by their index, starting from 0.
array[0] // First item
array[599] // Last item.
Your error has occurred because you have exceeded 599.
How to fix this
Well, you can either make your array 76400 long, (which to me is suspicious), or you can change 76400 to array.length (or 600) in your for loop.
This is the solution i find..
I think that is the best..
public static int[] findIndex(BufferedImage image, int value) {
DataBuffer b = image.getRaster().getDataBuffer();
int array[] = new int[600];
int j = 0;
for (int i = 0; i < b.getSize(); i++) {
if (b.getElem(i) >= value) {
if (j < 600) {
array[j] = i;
j++;
}
}
}
return array;
}
That's because your loop from 0 to 76400, which much much greater than the size of your array.
public static int []findIndex(BufferedImage image,int value)
{
DataBuffer b = image.getRaster().getDataBuffer();
int array[] = new int[600];
for(int i=0;i<array.length;i++)
{
if(b.getElem(i)>=value)
array[i]=i;
}
return array;
}
This is my final function.
How should we choose a generic programming,i made some changes that made ​​a focused precisely on that.
Use now have a list instead of a static array.
public static int[] findIndex(BufferedImage image, int value) {
DataBuffer b = image.getRaster().getDataBuffer();
ArrayList<Integer> a = new ArrayList<>(20);
int j = 0;
for (int i = 0; i < b.getSize(); i++) {
if (b.getElem(i) >= value) {
a.add(i);
j++;
}
}
int array[] = new int[a.size()];
for (int k = 0; k < a.size(); k++) {
array[k] = a.get(k);
}
return array;
}

Repeating array

So I'm trying to repeat an int[] array by the values that are in it.
So basically if you have an array
{1,2,3,4}
your output will be
{1,2,2,3,3,3,4,4,4,4}
or if you get
{0,1,2,3}
your output is
{1,2,2,3,3,3}.
I know for sure there has to be two for loops in here but I can't seem to figure out the code to make it copy the value in the array.
I can't get 2 to out 2,2,
Any help will be much appreciated, thank you.
edit here the code I thought would work
public static int[] repeat(int []in){
int[] newarray = new int[100];
for(int i = 0; i<=in.length-1;i++){
for(int k= in[i]-1;k<=in[i];k++){
newarray[i] = in[i];
}
}
return newarray;
}
I thought that this would work but it just returns the same list, or sometime if I change it around ill just get 4 in the new array.
This will dynamically build a new array of the correct size and then populate it.
int[] base = { 1, 2, 3, 4 };
int size = 0;
for( int count : base ){
size += count;
}
int[] product = new int[size];
int index = 0;
for( int value : base ){
for(int i = 0; i < value; i++){
product[index] = value;
index++;
}
}
for( int value : product ){
System.out.println(mine);
}
Try:
LinkedList<Integer> resList = new LinkedList<Integer>();
for(int i = 0 ; i < myArray.length ; ++i) {
int myInt = myArray[i];
for(int j = 0 ; j < myInt ; ++j) { // insert it myInt-times
resList.add(myInt);
}
}
// TODO: build the result as an array : convert the List into an array
Try this:
int[] anArray = {
0, 1, 2
};
int[] newArray = new int[100];
int cnt=0;
for(int i=0; i<anArray.length; i++)
{
for(j=1;j>0;j--)
{
newArray[cnt]=anArray[i];
cnt++;
}
}

Categories