I have two char arrays that takes two strings as the input. If the char on either side has the matching char, for example after translating the char Arrays into string char A and B both have at least one H or R, then it will return true. If not then return false.
>char[] A = foo(A).toCharArray();
>
>char[] B = foo(B).toCharArray();
>
>System.out.println("String "+A+": "+Arrays.toString(A));
>
>System.out.println("String "+B+": "+Arrays.toString(B));
>String A: [H, , R, ]
>
>String B: [R, , R, R]
>>This will return true
>String A: [ , H, , R]
>
>String B: [H, H, , H]
>>This will return true
>String A: [H, , H, ]
>
>String B: [R, , R, ]
>>This will return false
I'm confused how to make such rule?
You can use java.util.Set here which will give the result in one iteration. Using java.util.TreeSet further reduce the execution time as it eliminates duplicates
public static void main(String[] args) {
char[] A = "HR".toCharArray();
char[] B = "RRR".toCharArray();
Set<Character> set = new TreeSet<>();
boolean flag = false;
for(char c : A) {
set.add(c);
}
for(char c : B) {
if(set.contains(c)) {
System.out.println(true);
flag = true;
break;
}
}
if(!flag) {
System.out.println(false);
}
}
That you can do is use a For to iterate in the matriz and verify if the current item is 'R' or 'H'.
boolean returnedValue = false;
for(int i = 0; i< B.length; i++){
char currentItem = B[i];
if(currentItem == 'R' || currentItem == 'H'){
returnedValue = true;
}
}
return returnedValue;
Use the first loop to take each element from the first array.
Use the second loop to check the first element inside the second array.
Check if the current value in the first array is equal to H or R.
If it is, check if it's in the second array and return true.
public static boolean check() {
String s1 = "ABHEEF", s2 = "RDDFVW";
char[] arr1 = s1.toCharArray();
char[] arr2 = s2.toCharArray();
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if(arr1[i] == 'H' || arr1[i] == 'R') {
if(arr1[i] == arr2[j])
return true;
}
}
}
return false;
}
Well its simple all you have to do is to add a nested loop
for(int i = 0; i < A.length; i++){
for(int j = 0; j < B.length; j++){
if(if B[j] ==A [i]){
return true
}
}
}
return false;
Using Java 1.8 you could do something like following:
//#Momir Sarac
String text1 = "b9H ello";
String text2 ="avn1c fk";
// 32 is for empty space character here, you could do i != ' ' and it would be the same
//turn text1 into intstream each int corresponding to it's char value
//filter empty space ints
//get only distinct out of them
//take a look for any match if some int is contained within text2
boolean result = text1.chars().filter(i->i != 32).distinct().anyMatch(character->text2.contains(String.valueOf(character)) || text2.lastIndexOf(character) != -1);
//print it on screen
System.out.printf("Two texts %s same letter(s).", result ? "have" : "don't have");
Related
Beginner here, We were assigned an assignment to find common consonants in two different strings. This code works perfectly if there is no space in the input but in this assignment we are taking inputs from our user and they are first and last names. If there is no space I get correct value of common characters but when there is a space in between first and last names it will give me an index out of bounds error because the space makes it a negative number. Any help would be nice thank you.
public static int commonCharacters(String string1, String string2) {
final int alphabetLength = 26;
int count = 0;
int[] counting1 = new int[alphabetLength];
int[] counting2 = new int[alphabetLength];
Arrays.fill(counting1, 0);
Arrays.fill(counting2, 0);
for (char c : string1.toCharArray()) {
c = Character.toLowerCase(c);
counting1[c - 'a']++;
}
for (char c : string2.toCharArray()) {
c = Character.toLowerCase(c);
counting2[c - 'a']++;
}
for(int i = 0; i < alphabetLength; i++) {
System.out.printf(String.valueOf(counting1[i]),counting2[i]);
count += Math.min(counting1[i], counting2[i]);
}
return count == 0 ? 1 :count;
}
}
you can trim space at the end of string string1 = string1.trim();
Here is some changes to your code. You just need if statement to check if the character is an alphabet. You do not need Arrays.fill because in Java array values are initialized to zero.
You wrote the assignment is about calculating consonants but your code calculates all common alphabets.
public static int commonCharacters(String string1, String string2) {
final int alphabetLength = 26;
int count = 0;
string1 = string1.toLowerCase();
string2 = string2.toLowerCase();
int[] counting1 = new int[alphabetLength];
int[] counting2 = new int[alphabetLength];
for (char c : string1.toCharArray()) {
if (c < 'a' || c > 'z') {
continue;
}
counting1[c - 'a']++;
}
for (char c : string2.toCharArray()) {
if (c < 'a' || c > 'z') {
continue;
}
counting2[c - 'a']++;
}
for(int i = 0; i < alphabetLength; i++) {
System.out.printf("%c %d %d%n", 'a' + i, counting1[i], counting2[i]);
count += Math.min(counting1[i], counting2[i]);
}
return count;
}
private void clear() {
for (int i = 0; i<9; i++){
for (int j = 0; j<9; j++){
if(iseditable(i,j)){
bord[i][j].setText("");
}
}
}
}
private boolean iseditable(int i, int j) {
for (String s : generatedXY) {
char[] m = s.toCharArray();
char x = (char) (i + '0');
char y = (char) (j + '0');
return m[1] != x || m[3] != y;
}
return false;
}
I have used the following code in my app here generatedXY array contains all the points in the formate (i,j) as strings I want to extract i & j from the string and compare them with index of board but it is only checking the first element of generatedXY it is not all elements
First your for loops go from 0 to 8, I assume you wanted to write
i<=9 instead.
Second: For iterate over all elements of generatedXY, but you exit loop already in the first iteration by the return statement. You possibly wanted to write something like
if (m[1] != x || m[3] != y)
{
return true;
}
, then the return statement is only executed if the condition is true.
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
example 3
"aad"
"cab"
Output
true
Expected
false
my 3 test case is giving output true why?
class Solution {
public boolean isAnagram(String s, String t) {
if (s.isEmpty() && t.isEmpty()) {
return true;
}
if (s.length() != t.length()) {
return false;
}
char[] a = s.toCharArray();
char[] b = t.toCharArray();
Arrays.sort(a);
Arrays.sort(b);
for (int i = 0; i <= a.length; i++) {
for (int j = 0; j <= b.length; j++) {
if (a[i] == b[j]) {
return true;
}
}
}
return false;
}
}
By using a nested for loop, you will iterate over every possible pair (i, j) with i and j an in idex in a and b respectively. Furthermore you use i++ and j++ twice, and thus you will skip the even indices. You can not return true from the moment a[i++] == b[j++] matches. In order to know if something is an anagram, you need to iterate over all elements. You can return false from the moment a[i] != b[i] however. Finally the bound should be i < a.length, not i <= a.length.
You thus need one for loop where you make a single increment and compare a[i] with b[i]:
public boolean isAnagram(String s, String t) {
if(s.length() != t.length()){
return false;
}
char[] a = s.toCharArray();
char[] b = t.toCharArray();
Arrays.sort(a);
Arrays.sort(b);
for(int i = 0; i < a.length; i++) {
if(a[i] != b[i]) {
return false;
}
}
return true;
}
You are just comparing the first letter of cab and rat which is a, and returning True, actually you need to check all letters.
Hence make the condition negative and swap the returns.
if(a[i++] !=b[j++]){
return false;
}
return true;
The above code will return false, when characters aren’t equal, hence the last line is reached only when all chars are equal.
So I'm trying to compare a char to an array of chars, the problems is when the array isn't full yet. I'm making a java program for advanced tic-tac-toe.
I've thought about using an ArrayList, but I need the type to char not a primitive type.
char players = new char[numPlayers] // ex: numPlayers == 4
getPlayers(numPlayers, players)
private static void getPlayers(int numPlayers, char players[]){
char temp;
for(int i = 0; i < numPlayers; i++){
System.out.println("Enter the character to represent player " + (i + 1));
temp = in.next().charAt(0);
char upper = Character.toUpperCase(temp);
players[i] = upper;
if(!validatePlayer(upper, players)){
System.out.println("Each character must be unique");
getPlayers(numPlayers, players);
}
}
}
private static boolean validatePlayer(char upper, char players[]){
for(int i = 0; i < players.length; i ++){
if(upper != players[i]){
return true;
}
}
return false;
}
The caller knows the length that has been filled so far, and can pass it.
if (!validatePlayer(upper, players, i ))
The method can use this length, rather than the full length of the array.
private static boolean validatePlayer(char upper, char players[], int len ){
for (int i = 0; i < len; i++) {
...
}
return false;
}
The way to initialize a char array is
char[] players = new char[numPlayers];
The problem is here:
private static boolean validatePlayer(char upper, char players[]){
for(int i = 0; i < players.length; i ++){
if(upper != players[i]){
return true;
}
}
return false;
}
When players.length == 0, for loop will never be executed. And you get always false.
Also imagine if your players contains 'a' and 'b' and you call validatePlayer('b', players):
1. for loop will get first element. `players[0]` -> 'a'
2. Compare 'b' != 'a' -> true
3. Return true.
validatePlayer('b', players) returns true, even if he has 'b'.
I recommand you to change method like this:
private static boolean validatePlayer(char upper, char players[]){
for(int i = 0; i < players.length; i ++){
if(upper == players[i]){ //equal
return false; //false
}
}
return true; //true
}
Check if contains char, otherwise return true.
I am comparing two strings, in Java, to see how many characters from the first string show up in the second string. The following is some expectations:
matchingChars("AC", "BA") → 1
matchingChars("ABBA", "B") → 2
matchingChars("B", "ABBA") → 1
My approach is as follows:
public int matchingChars(String str1, String str2) {
int count = 0;
for (int a = 0; a < str1.length(); a++)
{
for (int b = 0; b < str2.length(); b++)
{ char str1Char = str1.charAt(a);
char str2Char = str2.charAt(b);
if (str1Char == str2Char)
{ count++;
str1 = str1.replace(str1Char, '0');
}
}
}
return count;
}
I know my approach is not the best, but I think it should do it. However, for
matchingChars("ABBA", "B") → 2
My code yields "1" instead of "2". Does anyone have any suggestion or advice? Thank you very much.
Assuming that comparing "AABBB" with "AAAABBBCCC" should return 15 (2*3 + 3*3 + 0*3) then:
For each string make a Map from the character of the string to the count of characters.
Compute the intersection of the keysets for the two maps.
For each element in the keyset accumulate the product of the values. Print the result.
This is linear in the size of the two strings.
Is it ok to supply working code on homework problems?
public long testStringCount() {
String a = "AABBBCCC";
String b = "AAABBBDDDDD";
Map<Character,Integer> aMap = mapIt(a);
Map<Character,Integer> bMap = mapIt(b);
Set<Character> chars = Sets.newHashSet(aMap.keySet());
chars.addAll(bMap.keySet());
long result = 0;
for (Character c : chars) {
Integer ac = aMap.get(c);
Integer bc = bMap.get(c);
if (null != ac && null != bc) {
result += ac*bc;
}
}
return result;
}
private Map<Character, Integer> mapIt(String a) {
Map<Character,Integer> result = Maps.newHashMap();
for (int i = 0; i < a.length(); i++) {
Character c = a.charAt(i);
Integer x = result.get(c);
if (null == x) {
x = 0;
}
x++;
result.put(c, x);
}
return result;
}
Clearly you have to make sure you only count unique characters from string 1. You're double-counting B because you're counting B's twice, once for each occurrence in string 1.
Well your code is only showing 1 because of this line:
str1 = str1.replace(str1Char, '0');
That's turning "ABBA" into "A00A" - so the second B doesn't get seen.
Perhaps you should turn the second string into a HashSet<Character> instead... then you could just use something like:
int count = 0;
for (int i = 0; i < str1.length; i++)
{
if (otherSet.contains(str1.charAt(i))
{
count++;
}
}
It's not clear what result you want to get from "ABBA" / "CBCB" - if it's 2 (because there are 2 Bs) then the above approach will work. If it's 4 (because each of the 2 Bs in the first string matches 2 Bs in the second string) then all you need to do is get rid of your replace call.
EDIT: With the clarifications, it sounds like you could just do this:
for (int a = 0; a < str1.length(); a++)
{
for (int b = 0; b < str2.length(); b++)
{
if (str1.charAt(a) == str2.charAt(b))
{
count++;
// Terminate the inner loop which is iterating over str2,
// and move on to the next character in str1
break;
}
}
}
Your solution works, but is quadratic. If all characters are below 256, then you can do something like this:
int matching(String s1, String s2) {
int[] count1 = frequencies(s1);
int[] count2 = frequencies(s2);
sum = 0;
for(int i = 0; i< 256; i++) {
sum += count1[i]*count2[i] != 0 ? Math.max(count1[i], count2[i]) : 0;
}
return sum;
}
int[] frequencies(String s) {
int[] ret = new int[256];
for(char c : s) {
int[c]+=1;
}
}
Otherwise, you'll need a multiset.