Finding Palindromes in an Array - java

For this assignemnt, I think that I got it right, but when I submit it online, it doesn't list it as correct even though I checked with Eclipse.
The prompt:
Write a method isPalindrome that accepts an array of Strings as its argument and returns true if that array is a palindrome (if it reads the same forwards as backwards) and /false if not. For example, the array {"alpha", "beta", "gamma", "delta", "gamma", "beta", "alpha"} is a palindrome, so passing that array to your method would return true. Arrays with zero or one element are considered to be palindromes.
My code:
public static void main(String[] args) {
String[] input = new String[6]; //{"aay", "bee", "cee", "cee", "bee", "aay"} Should return true
input[0] = "aay";
input[1] = "bee";
input[2] = "cee";
input[3] = "cee";
input[4] = "bee";
input[5] = "aay";
System.out.println(isPalindrome(input));
}
public static boolean isPalindrome(String[] input) {
for (int i=0; i<input.length; i++) { // Checks each element
if (input[i] != input[input.length-1-i]){
return false; // If a single instance of non-symmetry
}
}
return true; // If symmetrical, only one element, or zero elements
}
As an example, {"aay", "bee", "cee", "cee", "bee", "aay"} returns true in Eclipse, but Practice-It! says it returns false. What is going on?

You cant use operator == or != to compare string object. The operators will work on the object references and not values.
public static boolean isPalindrome(String[] input) {
for (int i=0; i<input.length; i++) { // Checks each element
if (!input[i].equals( input[input.length-1-i])){
return false; // If a single instance of non-symmetry
}
}
return true; // If symmetrical, only one element, or zero elements
}

This is not how you compare Strings in Java. Use the following:
if (!input[i].equals(input[input.length-1-i])){
return false; // If a single instance of non-symmetry
}
Read this.

Related

Comparing characters in 2 char Array using Java

I am a beginner in Java and I will like to know if there's a way to compare characters in a char Array with other characters in another char Array in order to see if they have characters that match. Not to see if they contain exactly the same characters in the same sequence as most examples explain.
For instance:
char [] word1= {'a','c','f','b','e'};
char[] word2= {'a','b','c','d','e','h','j','f','i','m'};
and using maybe if statements to say that word1 contains the characters in word2 so it is correct. Else it is incorrect if word2 is missing at least one character that word1 has.
Try this. It will report if either array contains all the characters of the other. I used strings and converted them to arrays to facilitate the coding.
String[][] testData =
{ {"axyzx","xxyzaa"},
{"aaxyz","aaax"},
{"axa","a"},
{"arrs","asrrrs"},
{"acfbe","abcdehjfim"}};
for (String[] words : testData) {
boolean result = contains(words[0].toCharArray(), words[1].toCharArray());
String output = String.format("%s contains all %s","'"+words[0]+"'","'"+words[1]+"'");
System.out.printf("%34s - %b%n", output, result);
output = String.format("%s contains all %s","'"+words[1]+"'","'"+words[0]+"'");
result = contains(words[1].toCharArray(), words[0].toCharArray());
System.out.printf("%34s - %b%n%n", output, result);
}
Prints
'axyzx' contains all 'xxyzaa' - false
'xxyzaa' contains all 'axyzx' - true
'aaxyz' contains all 'aaax' - false
'aaax' contains all 'aaxyz' - false
'axa' contains all 'a' - true
'a' contains all 'axa' - false
'arrs' contains all 'asrrrs' - false
'asrrrs' contains all 'arrs' - true
'acfbe' contains all 'abcdehjfim' - false
'abcdehjfim' contains all 'acfbe' - true
Using a map, do a frequency count of the characters in the second array.
Now iterate thru the map using the first array, decrementing the character count when the character is found. When the count reaches 0, assign null to the value.
if map is now "empty", the first array contains all characters of second array.
// see if first array contains all of second array,
// regardless of order of the characters
public static boolean contains(char[] ch1, char[] ch2) {
// a smaller array cannot possible contain the same
// characters as a larger array
if (ch1.length < ch2.length) {
return false;
}
Map<Character,Integer> map = new HashMap<>();
// Do a frequency count
for(char c : ch2) {
map.compute(c, (k,v)->v == null ? 1 : v+1);
}
// now decrement count for each occurrence
// of character in first array, setting value to
// null when count reaches 0.
for(char c : ch1) {
map.computeIfPresent(c, (k,v)-> v <= 1 ? null : v-1);
}
return map.isEmpty();
}
I created a little snippet and think it is what you are looking for:
public class Main {
public static void main(String[] args) {
char[] word1= {'a','c','f','b','e'};
char[] word2= {'a','b','c','d','e','h','j','f','i','m'};
System.out.println(Contains(word1, word2));
}
private static boolean Contains(char[] arr1, char[] arr2) {
for (int i = 0; i < arr1.length; i++) {
boolean containsChar = false;
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) containsChar = true;
}
if (!containsChar) return false; // arr2 does not contain arr1[i]
}
return true;
}
}

Check if string contains all strings from array

How to check if String contains all Strings from Array.
My current code:
String word = "abc";
String[] keywords = {"a", "d"};
for(int i = 0; i < keywords.length; i++){
if(word.contains(keywords[i])){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
The code would look much more nicer if you wrap it into a separate method:
public static boolean containsAllWords(String word, String ...keywords) {
for (String k : keywords)
if (!word.contains(k)) return false;
return true;
}
If you are using Java 8+, you could use a Stream and test if all of the elements match your criteria with one line. Like,
if (Stream.of(keywords).allMatch(word::contains)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
In earlier versions, or if you want to understand what the above is doing, it might look something like
boolean allMatch = true;
for (String kw : keywords) { // <-- for each kw in keywords
if (!word.contains(kw)) { // <-- if "word" doesn't contain kw
allMatch = false; // <-- set allMatch to false
break; // <-- stop checking
}
}
if (allMatch) {
System.out.println("Yes");
} else {
System.out.println("No");
}
Use a boolean variable that will tell you if every keyword is matched. Set it to true as default value. Then check every keword: if any one is not contained in your word, stop searching and set your variable to false.
boolean containsAll = true;
for (String keyword : keywords){
if (!word.contains(keyword)){
containsAll = false;
break;
}
}
Note this solution work only if your keywords contain one char, there are many answers already mentioned if your keywords contain more then one char.
With one line :
boolean contain = Arrays.asList(word.split("")).containsAll(Arrays.asList(keywords));
The idea is :
String word = "abc";
String[] split = word.split("");
Split your String to get an array of chars split = {a, b, c}
String[] keywords = {"a", "b"};
Check if your array1 contain all the element of the second array2 using containsAll
boolean contain = Arrays.asList(split).containsAll(Arrays.asList(keywords));
Either use StringUtils (org.apache.commons.lang.StringUtils). It will return the index of the first occurrence of keywords or -1 if it is not there.
StringUtils.indexOfAny(word, keywords);
Or you can use Arrays which will return the boolean value.
Arrays.asList(word).contains(keywords)
A better code would be:
for(String s: keywords){
if(word.contains(s)){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
Simply use a counter:
String word = "abc";
String[] keywords = {"a", "d"};
int counter = 0;
for(int i = 0; i < keywords.length; i++){
if(word.contains(keywords[i])){
counter++;
}
}
if(counter == keywords.length){
System.out.println("Yes");
}else{
System.out.println("No");
}
If the counter equals the keywords length, it means that all elements are contained. With this solution you will also be able to find out how many keywords are matched by the word.

Comparing Array values in JAVA (checking if words are anagrams)

How to check if the two arrays have same values, ignoring their position. The arrays can have multiple of same value.
Example 1
String[] a = {"m","o","m","d","a","d"};
String[] b = {"d","a","d","m","o","m"};
//This should result true.
Example 2
String[] a = {"m","o","m","d","a","d"};
String[] b = {"d","a","d","m","o"};
//This should result false because second array has only one m and first array has two
I hope my condition is understood by example.
I am trying to check if the words are anagrams. I have made array out of words. But could not check if the arrays have same values. My code is as follows:
public class AreAnagrams {
public static boolean areAnagrams(String a, String b) {
//throw new UnsupportedOperationException("Waiting to be implemented.");
if(a.length() != b.length()) return false;
String[] test = new String[a.length()];
String[] testb = new String[b.length()];
for(int i=0; i<a.length(); i++){
test[i] = a.substring(i,i+1);
testb[i] = b.substring(i,i+1);
}
return test.equals(testb);
}
public static void main(String[] args) {
System.out.println(areAnagrams("momdad", "dadmom"));
}
}
You can sort the two arrays with Arrays.sort() and then compare the sorted arrays with Arrays.equals() to find out if they have the same values.

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;
}

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