I am trying to write a program that prints out numbers with unique absolute value. Here is my attempt:
import java.util.*;
public class MyClass {
static ArrayList<Integer> aCopy;
public static void main(String[] args)
{
int myArray[]= {-5, 4,-6,8,-4,6,13};
System.out.println(Arrays.toString(myArray));
aCopy = new ArrayList<>();
for(int i=0; i<myArray.length; i++)
{ aCopy.add(myArray[i]); }
System.out.println("Numbers with unique abs. value are:");
findDifferentAbsoluteValues(myArray);
System.out.println(aCopy);
}
public static boolean findDifferentAbsoluteValues (int[] anArray)
{
for (int i=0; i<anArray.length;i++)
{
for(int j=i+1;j<anArray.length; j++)
{
if ( Math.abs(anArray[i]) == Math.abs(anArray[j]) )
{
aCopy.remove(anArray[i]);
return false;
}
}
}
return true;
}
}
but it gives incorrect output. I am not (yet) very fluent in java so it is not main concern for me than the solution is elegant, just need it working)) Anyone could shed some light what's wrong, please?
I understand the question you want to take a series of absolute values that are different. First wrong
aCopy.remove(anArray[i]);
It can not delete these, which has the same value. You find same value but anArray[i] not worth to be deleted. ex: i=1 anArray[1]= 4. You will delete this
aCopy.remove(4);/* because anArray[1] = 4*/
Second wrong dont return false. Because loop not done.
I understand the question and answer in the following way;
public static void main(String[] args)
{
int myArray[]= {-5, 4,-6,8,-4,6,13};
System.out.println(Arrays.toString(myArray));
aCopy = new ArrayList<>();
System.out.println("Numbers with unique abs. value are:");
findDifferentAbsoluteValues(myArray);
System.out.println(aCopy);
}
public static void findDifferentAbsoluteValues (int[] anArray)
{
for (int i=0; i<anArray.length;i++)
{
Boolean dif =true;
for(int j=i+1;j<anArray.length; j++)
{
if ( Math.abs(anArray[i]) == Math.abs(anArray[j]) )
{
dif = false;
}
}
if(dif == true)
aCopy.add(anArray[i]); //if you want absolute value aCopy.add(Math.abs(anArray[i]))
}
}
In Java 8+, you might use an IntStream.map(IntUnaryOperator) to get the absolute values, then a IntStream.distinct() to get the unique values, and finally a IntStream.forEach(IntConsumer) to print it. Something like,
int[] myArray = { -5, 4, -6, 8, -4, 6, 13 };
IntStream.of(myArray).map(Math::abs).distinct().forEach(System.out::println);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With