Output of Adding StringArrayOfNumbers does not come as expected - java

Given an array of integers, check whether any number has been repeated in the array. That is, whether the array has any duplicates.
Sample Input 1
anyDuplicates({1,2,3,4})
Sample Output 1
false
Sample Input 2
anyDuplicates({11,22,33,44,22)
Sample Output 2
true
MyApproach
For checking whether the elements contains duplicates or not.I took too loops and checked whether the elements contains more than or equal to 2 times repeatition.If it does,i return false.else I return true.
public boolean anyDuplicates(int[] arr) {
boolean b1=false;
int count=0;
int z[]=new int[arr.length];
for(int i=0; i<arr.length; i++)
{ count=0; //#Edit
for(int j=0; j<arr.length; j++) {
if(arr[i]==arr[j]) {
count++;
}
}
z[i]=count;
if(z[i]>=2) {
b1=true;
break;
}
}
if(b1==true)
return true;
else
return false;
}
#Edit
DRY RUN
When I dry run the code I got my Ans as I need to put count=0 after my for i loop.Thank you all for giving me your views.
Parameters Actual Output Expected Output
{24,27,30} false false
My question:Why I am not getting expected output?

Update you code likewise,
for(int i=0;i<arr.length-1;i++)
{
for(int j=i+1;j<arr.length;j++)
{
.........
if(z[i]>=1){...}
}
}
Your mistake is, you are first taking one value that is reside into
a[i], and again into j-loop start with 0, so obviously a[i=0] and a[j=0] comes into comparison, which return true , and you will get
wrong comparion as per your requirement,
My code will work like, once value pick that is store into a[i=0...n-1],
now not repeat a[j=1...n] again unless and untill it is revise into array

Two problems with your code:
You're comparing each element with itself.
You're also comparing each pair of number twice which could be reduced to once.
Here's a sample code that could achieve solutions to both these problems:
public boolean anyDuplicates(int[] arr) {
for(int i=0; i<arr.length-1; i++) {
for(int j=i+1; j<arr.length; j++)
if (arr[i]==arr[j])
return true;
}
return false;
}

in your code, change:
if ((i!=j) && (arr[i]==arr[j]))
more clean:
public boolean anyDuplicates(int[] arr)
{
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr.length;j++)
if ((i!=j) && (arr[i]==arr[j]))
return true;
}
return false;
}
faster:
use a Set to put your values, and check the length against array length
public boolean anyDuplicates(int[] arr)
{
// => Integer[]
Integer[] array_Integer = ArrayUtils.toObject(arr);
// => Set<Integer>
Set<Integer> Set_Integer= new HashSet<Integer>(Arrays.asList(array_Integer));
// => size
int sz=Set_Integer.size();
return (sz!=arr.length);
}

Related

Dead code on a nested for loop that returns a boolean

I am trying to complete an exercise that we received in class. The solution was not nor will ever be posted since it is not evaluated. I can't seem to figure it out. When I run this code I get a warning for dead code. Which makes sense because my code seems to not permit to iterate through the second sub-array. So, when all elements are the same for the first sub-array even when they aren't for the second the method returns true. Any idea of how to fix this? I'm pretty lost at this point.
public class Warmup2 {
public static void main(String[] args) {
int[][] arr = {{1,1},{6,6,7}};
System.out.println(subArraySame(arr));
}
//method that takes a 2D-array and checks if the elements of the subarrays are all the same
public static boolean subArraySame(int[][] arr) {
for(int i = 0; i<arr.length; i++) {
for(int j = 0; j<arr[i].length-1; j++) {
if(arr[i][j]==arr[i][j+1]) {
return true;
} else {
return false;
}
}
}return false;
}
}
The dead code refers to the increment (j++) of the second loop. This will be never reached since the statement:
if(arr[i][j]==arr[i][j+1]) {
return true;
} else {
return false;
}
returns immediately at the first point it is met, i.e. when j=0, hence j++ will never get reached.
I guess you want this:
public static boolean subArraySame(int[][] arr) {
for(int i = 0; i<arr.length; i++) {
for(int j = 0; j < arr[i].length-1; j++) {
if(arr[i][j] != arr[i][j+1]) {
return false;
}
}
}
return true;
}
which returns true only if every subarray consists of equal items.
Your code terminated the loop at the 1st iteration because the if/else statements both contained a return.

Matching value with ArrayList?

I'm fairly new to java and have started on ArrayLists and I'm stuck on a particular issue.
What I'm trying to do in the code below is have a value passed to the method locateCatalogue, which will go through the array list collection to match the value entered.
Once it finds the matched value, stop executing and show how many items there are for the said item. Otherwise if the number doesn't exist just return null, Here's my code:
Arraylist<Catalogue> items;
Public locateCatalogue (int number)
// if int number matches value entered, find number.
for(int i=0; i < locateCatalogue.length; i++)
if (Catalogue.get(i) = number)
return Catalogue;
}
else {
//return no value if entered value has no matching number.
return null;
}
the operator =means to define variables. For comparison use ==. Furthermore you messed up the if statement:
Arraylist<Catalogue> items;
Public int locateCatalogue (Catalogue catalogue ){
for(int i=0; i < items.size(); i++)
if(items.get(i) == catalogue )
return i;
else
return -1;
}
But you can not count the items you want if you return after you found the first. Also it's not clear what you want to return
The syntax for the for-loop is as follow:
for(int i=0; i < items.size(); i++) {
//some code
}
The syntax for the if-statement is:
if(items.get(i) == number) {
//some code
}
public Catalogue locateCatalogue( int number ) {
for( Catalogue item : items ) {
if( item.id == number ) {
return item;
}
return null;
}

In Java, how can I test if an Array contains the same value?

I'm looking for a method to detect if all objects within an array(list) are the same.
e. g:
arraylist1 = {"1", "1", "1", "1"} // elements are the same
arraylist2 = {"1", "1", "0", "1"} // elements are not the same
Thanks for help
Java 8 solution :
boolean match = Arrays.stream(arr).allMatch(s -> s.equals(arr[0]));
Same logic for lists :
boolean match = list.stream().allMatch(s -> s.equals(list.get(0)));
It comes quite complicated if there are only or any null values in the array (resulting in a NullPointerException). So possible workarounds are:
Using Predicate.isEqual, it uses the static method equals from the Objects class and it will do the null check for you before calling equals on the first argument.
boolean match = Arrays.stream(arr).allMatch(Predicate.isEqual(arr[0]));
boolean match = Arrays.stream(arr).allMatch(s -> Objects.equals(arr[0], s));
Using distinct() and count() :
boolean match = Arrays.stream(arr).distinct().count() == 1;
that can be improved into Arrays.stream(arr).distinct().limit(2).count() == 1; as there is no need to check the all pipeline's content if you already find 2 distinct elements.
public static boolean AreAllSame(String[] array)
{
boolean isFirstElementNull = array[0] == null;
for(int i = 1; i < array.length; i++)
{
if(isFirstElementNull)
if(array[i] != null) return false;
else
if(!array[0].equals(array[i])) return false;
}
return true;
}
Please feel free to correct any syntax mistakes. I fear my Java-fu may be lacking today.
if( new HashSet<String>(Arrays.asList(yourArray)).size() == 1 ){
// All the elements are the same
}
If your list is empty return true.
If not, loop through it and check if all elements are equal to the element at index 0.
If so, return true, otherwise return false.
public boolean containsSameValues(int[] array) {
if(array.length == 0) {
throw new IllegalArgumentException("Array is empty");
}
int first = array[0];
for(int i=0;i<array.length;i++) {
if(array[i] != first) {
return false;
}
}
return true;
}
boolean containsAllValues=false;
boolean t=false;
int isto=0;
for(int k=0;k<arraylist1.size();k++){
for(int n=0;n<arraylist2.size();n++){
if(arraylist1.get(k).equals(arraylist2.get(n))){
t=true;
}
}
if(t){
isto++;
}else{
isto=0;
break;
}
}
if(isto!=0){
containsAllValues=true;
}
With this you can check if arraylist2 contains values from arraylist1.
You can sort the array and then use the Array equals method:
public boolean equalArrays(int []f ,int [] g){
Arrays.sort(f);
Arrays.sort(g);
if (Arrays.equals(f, g))
return true;
return false;
}
To test it out:
int [] h={1,1,0,1};
int [] t={1,1,1,0};
System.out.println(cc.equalArrays(h,t));
For Java 8, Alexis C's solution is probably the best. However, if you're stuck with <= Java 7 and don't think David Wallace's approach is expressive enough, you could also try this:
boolean result = Collections.frequency(yourList, "1") == yourList.size();
Basically what this does is that it checks whether the number of elements in your list equal to "1" matches the total number of elements in the list. Pretty straightforward.
By the way -- this is pure Java Collections API, and I believe Collection.frequency(..) has been there since at least JDK 1.5. See the javadocs for more information.
EDIT: Here's a quick fiddle if you want to take this for a test drive.
The easiest one:
public static boolean checkTheSame(int[] numbers) {
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] != numbers[i + 1]) {
return false;
}
}
return true;
}

Both '==' operator and Equals/compareTo method not working

I am trying to accept an array of numbers and output if the the numbers entered are distinct or not. I checked the earlier questions regarding this:
1)using '==' operator doesn't give me the correct output i.e. if the enter "2,3,4" as the command line arguments (inputs), it still returns that the "numbers are not distinct". The program could be compiled and runs in this case, but doesn't give the correct output.
2) using the 'equals' and 'compareTo' methods returns an error while compiling that, "int cannot be dereferenced!" The complilation itself is not successful here.
My code is as follows:
class DistinctNoCheck
{
public static void main(String[] args)
{ int temp = 0;
int [] a = new int [10];
for(int i=0;i<args.length;i++)
{
a[i] = Integer.parseInt(args[i]);
}
for(int i=0;i<a.length;i++)
{
temp = a[i];
for(int j=0;j<a.length;j++)
{
if((a[j] == temp) && (!(i == j)))
{
System.out.println("Numbers are not distinct!");
System.exit(0);
}
}
}
System.out.println("Numbers are distinct!");
}
}
You are using a.length which is 10. You should use args.length while iterating over the array.
Replace
for(int j=0;j<a.length;j++)
with
for(int j=0;j<args.length;j++)
Same goes for loop with i variable.

Checking if one array is the reverse of another array in java

Im trying to create a method that take 2 int array as the input parameter and returns true if the array are reverse and false otherwise. This is what I have so far but it is wrong.
public static void main(String[] args)
{
int b,a;
int[] data1 = {14,-70,-18,88,85,97,-65,13,-71,-12};
int[] data2 = {-12,-71,13,-65,97,85,88,-18,-70,14};
boolean check = true;
for (a=0;a<data1.length;a++)
{
for (b=data2.length-1;b>=0;b=b-1)
{
if (data1[a] != data2[b])
check=false
}
}
System.out.println(check);
}
My example is suppose to print true but it doesn't.I am assuming the 2 arrays are of the same length. Can anyone help?
You don't need two loops - you only need to loop once, using the index "normally" in one array, and from the other end for the other array:
public static boolean checkReversed(int[] x, int[] y)
{
// For production code, possibly add nullity checks here (see comments)
if (x.length != y.length)
{
return false;
}
// Loop through x forwards and y backwards
for (int i = 0; i < x.length; i++)
{
if (x[i] != y[y.length - 1 - i])
{
// As soon as we've found a "mistake" we can exit:
// This is simpler (IMO) than keeping a "check" variable
return false;
}
}
return true;
}
You can try doing:
// compare the length.
check = (data1.length != data2.length)?false:true;
// if lengths are equal..go ahead and compare elements in reverse.
if(check) {
for(int i=0,j=data2.length;(i<data1.length) && (j>=0);i++,j--) {
// if you find a mismatch..set check to false..and break
// no need to compare other ele.
if(data1[i] != data2[j]) {
check = false;
break;
}
}
}
in this, both array length should be equal. then
for(int i=0,j=array.length;i<array.length,j=0;i++,j--){
write your comparison logic here
}
Your code actually compares every element in data1 with every element with data2 and prints false if there is any one mismatch. That is not what you intend it to do.
here is an answer to your question in a complete .java file
//yeah.java
public class yeah {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] data1 = {14,-70,-18,88,85,97,-65,13,-71,-12};
int[] data2 = {-12,-71,13,-65,97,85,88,-18,-70,12};
System.out.println(isReverse(data1, data2));
}
public static boolean isReverse(int[] a, int[] b)
{
if (a.length != b.length) //If a and b are not of the same length how can they be reverse?
return false;
for (int i=0;i<a.length;i++)
if (a[i] != b[a.length-i-1])
return false;
return true;
}
}
Just a quick note about method and functions.. As soon as you discover that they are not reversed, you should exit using a return statement.. no need to keep on computing..
You can do it in one loop, you don't need two.
for (int i=0,j=end;i<end;i++,j--)
This can be done in a single loop there is no need for two loops.
For example:
for (int i = 0, j = last; i < last; i++, j--)

Categories

Resources