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--)
Related
public class Main
{
public static void main(String[] args)
{
String[] find2 = {"cool","NOT","NOT,"Cool"};
String[] nofind = {"Fly","poke","ok";
System.out.println(Test.out(find);
System.out.println(Test.out(nofind));
}
}
+
public class Test
{
public static boolean Out(String[] input) {
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input.length; j++) {
if (input[i].equals(input[j]) && i != j) {
return true;
}
}
}
return false;
}
I've managed to function a code that tells me if it is true or false if there is repeated series of word in the string array, however, how can I achieve this without a loop construct that also finds upper and lower case dupes?
In short, you cannot do this without any loops. However, if you are looking for hidden loops, you can use this:
public static boolean out(String[] input) {
return input.length != new HashSet<String>(Arrays.asList(input)).size();
}
If you need to ignore case, then:
public static boolean out(String[] input) {
return input.length != Arrays.stream(input).map(String::toLowerCase).collect(Collectors.toSet()).size();
}
Using a Map<String, Integer> which would have words from list/array of strings as keys (lowercase words) should solve your problem. If the new word is already present (check new words by using toLowercase()) in the map then you can return true.
You would have to traverse the list or array of strings at least once (if not for-loop then for-each loop) either explicitly or implicitly(Java8 hidden loops or other collection’s constructors) to find if any words are repeated.
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.
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);
}
So here I am stuck with my program where its a simple thing to do. so basically in the search metod is where I have 3 variables as you can see, Char P char T and List pos. Below the method you can see there is a Main where its says what value the char P, char T has and my idea was to make a matching program where I enter a value P and looks if there is a same value in char T. Ones it founds out, it should continue until the value is done. so in the main method after it found out the result, it should give you the index of what position the value is set to.
Now to the problem is, if I give a correct value example P =abc T = abcqweqweabc it would give me a correct, but if I do abcqweqweqwe it will loop all the time and never end which is killing my processor and ram (hehe) and I have been trying to figure out but I can't find the problem. It seems like it should work and I don't understand why it does like it.
public class StringSearch {
public static void search(char[] P, char[] T, List<Integer> pos) {
int i = 0;
int j;
while(i!=P.length){
for (j= 0; j<T.length; j++){
if(P[i] == T[j]) {
i++;
if(i == P.length) {
pos.add((j-(P.length-1)));
i = 0;
if(j==T.length-1) {
i = P.length;
}
}
}
else {
i = 0;
}
}
}
public static void main(String[] args) {
ArrayList<Integer> where = new ArrayList<Integer>();
search("abcx".toCharArray(), "abcdabcxxabctx".toCharArray(), where);
for (int i : where) {
System.out.println(i);
}
}
}
Also please! If you need to know something. Just comment and I will probably answer you in a minute! Feel free to ask question aswell!
EDIT: To give a exactly meaning of what I'm trying to do is that, Our Char T is where the "text" is and char P is where letters are that I want to match P and T. So whenever we find a correct matching between char P and T it should be add in the list which we called pos. which will give us later a result where in the index the matching is the same. like T = qweabcqwe and P = abc. It should give us a result of 4. so what I'm trying to do is to see if there is a matching between those two and where in the position are they the same and if there is, put in the list and then the loop at the main method will tell us where.
EDIT PART 2.3:
public static void search(char[] P, char[] T, List<Integer> pos) {
for (int i=0;i<=T.length-P.length;) {
if (T[i] == P[0]) {
boolean match=true;
for (int j=0;j<P.length;j++) {
if (T[i+j] != P[j]) {
match = false;
break;
}
}
if (match) {
pos.add(i);
i = P.length -1;
}
}
}
}
public static void main(String[] args) {
ArrayList<Integer> where = new ArrayList<Integer>();
search("abcx".toCharArray(), "abcdabcxxabctx".toCharArray(), where);
for (int i : where) {
System.out.println(i);
}
}
}
if there is even one case where
if(P[i] != T[j])
then you set i to 0
else {
i = 0;
and you get stuck in the while loop
BUT basicaly what you are trying to do is something that gives you the same result as indexOf()
Try this :
String Str = new String("qweabcqwe");
String SubStr1 = new String("abc");
System.out.println( Str.indexOf( SubStr1 )); // will print 3
You might want to check out the KMP algorithm explaind in detail using Java here to give you some hints if you want to implement it yourself: http://tekmarathon.com/2013/05/14/algorithm-to-find-substring-in-a-string-kmp-algorithm/
To find the index of every character that is the same at the same position in each array just do:
for (int i=0;i<P.length && i<T.length;i++) {
if (P[i] == T[i]) {
pos.add(i);
}
}
You only need one loop as you are only comparing one value.
If you want to find the location of the substring then you do need a nested loop but it can still be a simple for loop.
for (int i=0;i<=P.length-T.length;i++) { // Can stop when we get to within T length of the end of P
if (P[i] == T[0]) {
boolean match=true;
for (j=0;j<T.length;j++) {
if (P[i+j] != T[j]) {
match = false;
break;
}
}
if (match) {
pos.add(i);
// You might want to add T.length-1 to i here to cause it to skip, it depends if you want to find overlapping results or not. (i.e. searching for bobob in bobobob.
}
}
}
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;
}