Hey can someone please explain this coding line by line?
public boolean twoE(String str) {
int count = 0;
for (int i=0; i<str.length(); i++) {
if (str.charAt(i) == 'e')
count++;
}
if (count == 2){
return true;
}
return false;
// this last if/else can be written simply as "return (count == 2);"
}
public boolean twoE(String str) {
Declares method twoE that takes the argument str of type String.
int count = 0;
Creates a variable named count of type int and initializes it to 0.
for (int i=0; i<str.length(); i++) {
Uses a for loop to iterate from 0 - the length of the string (str.length()).
if (str.charAt(i) == 'e') count++;
Checks if the the ith letter (str.charAt(i)) of str is a 'e'. If so, increment the count.
if (count == 2) return true;
return false;
If there were 2 'e's, then return true, otherwise, return false.
Note You might not have written this code, but if you did I have one suggestion. Change the last line to return (count == 2); to save space and make the meaning more clear.
The summary of what this function does is that it returns a boolean (true or false) whether or not the String argument passed in contains exactly two lowercase e characters.
How it achieves this is as follows:
Initialize an empty count of 0
Loop through every character of the string
For each character, if the character is a lowercase e, add 1 to the counter
After you are done looping, check what the count was.
If the count was exactly 2, return true, otherwise, return false.
Related
can you please explain me this code? i am not able to understand the use of buffer array. how does value at every index become zero?
public static boolean isAnagram(String input1, String input2) {
if(input1 == null || input2 == null || (input1.length() != input2.length())){
return false;
} else {
int[] buffer = new int[26];
for(int i=0; i < input1.length(); i++){
buffer[input1.charAt(i) - 'a']++;
buffer[input2.charAt(i) - 'a']--;
}
for(int j=0; j < buffer.length; j++){
if(buffer[j] != 0) return false;
}
return true;
}
}
buffer holds a use counter for each lower-case character value used in the strings, all zero initially.
Each counter is then incremented for each use of a character in input1, decremented for each use of a character in input2, so if all characters are used the same number of times, all counters will become zero in the end.
This function will likely crash if called with strings that have anything but lower case letters in them.
What I am supposed to do is create an algorithm that counts the number of substrings in a piece of text where the substrings can be the letter B followed by C or C followed by B. I'm not sure what to do, but I tried it and came up with the result below. I'd like to know if I did it correctly.
int substrCount(String S[0...n-1]){
int count = 0;
for (int i = 0; i<=n-2; i++) {
for (int j=i+1; j<i+2; j++) {
if ((S[i] == 'B' && S[j] == 'C' ) || (S[i] == 'C' && S[j] == 'B')) {
count = count + 1;
}
}
}
}
I am gonna ignore whether it includes lowercase or uppercase for now. I also need to find the complexity of the algorithm from which I believe it is O(n^(2)). Did I do this correctly? If so, can I make it any more efficient?
This works well for me
static int substrCount( String str) {
int count=0;
for (int i=0; i<str.length()-1; i++)
{
boolean bc = (str.charAt(i) == 'B' && str.charAt(i+1) == 'C');
boolean cb = (str.charAt(i) == 'C' && str.charAt(i+1) == 'B');
if (bc || cb) {
count++;
}
}
return count;
}
You need to loop the sequence of chars in string just once to get the desired result. Check the couple of chars if they are equal "BC" or "CB" and move one index forward to the end of the string.
Output example:
"ACBAA" gives result 1
"ABCBA" gives result 2
"BCBCB" gives result 4
"BBBBB" gives result 0
This method is supposed to return true if there is more than one 1 in a column of a 2D array, yet it doesn't work. I can't figure out what's wrong with it so I thought I'd get some expert opinions.
Example:
10010
01001
10100
will return true because there are 2 ones in the first column.
Here is the code
public static boolean isVert(int[][] x) { //checks for more than one 1 in columns
int count = 0;
boolean break2 = false;
boolean check = false; //false means no 2 (or more) queens in same column
for (int i = 0; i < x.length; i++) {
count = 0;
for (int j = 0; j < x[i].length; j++) {
if (x[i][j] == 1) {
count++;
}
if (count > 1) {
break2 = true;
check = true;
break;
}
}
if (break2) {
break;
}
}
return check;
}
You break at the first occurance of 1 in whole array, which is probably not the expected result.
Explanation of how your code works:
loop until counter i is less than length of array (number of rows in array)
loop until counter j is less than length of i-th row (number of columns or elements in array)
check if element on i-th row and j-th column is 1, if true, increase variable count by one
if count is greater than 1 (this means it has to be 2 or greater) set break2 and check to true, break
if break2 is true (which is as count is > 2 and first loop breaks), break this loop too:
this happens in 1st row of your example table
end of loops, return check (which is true because 1st row contains 2 ones)
The problem in your code is that you break when you find your first row that satisfies your condition, but you do not (necessarily) check all the rows in given array.
I have corrected the code for you, hopefully it works (untested)
public static boolean isVert(int[][] x) { //checks for more than one 1 in columns
int count = 0;
for (int i = 0; i < x.length; i++) {
int rowCount = 0;
for (int j = 0; j < x[i].length; j++) {
if (x[i][j] == 1) {
rowCount++;
}
if(rowCount > 1) {
count++;
break;
}
}
}
// returns true if count of lines containing 1 equals length of array,
// if not, returns false
return count == x.length;
}
Start of by improving your naming convention. Your code has many variables named by their contents, instead of named by how they are used. For example:
boolean check = false; // false means no two queens in the same column.
instead of
boolean twoQueensInColumn = false;
and the other example
boolean break2 = false;
instead of the more reasonable
boolean continueLooking = true;
Plus, it is a very good idea to avoid using variables as place holders for loop escaping logic. For example, the two stanzas
...
if (count > 1) {
break2 = true;
check = true;
break;
}
}
if (break2) {
break;
}
are a breeding ground for bugs, requiring a lot of debugging to ensure they work "right now" which will break just as soon as you modify the code. Much better would be
boolean keepLooking = false;
for (int row = 0; keepLooking && (row < board.length); row++) {
int queensInColumn = 0;
for (int column = 0; keepLooking && (column < board[row].length, column++) {
if (board[row][column] != 0) {
queensInColumn++;
}
if (queensInColumn > 1) {
keepLooking = false;
}
}
}
The main difference being the control logic is in the loop "conditional" block, where it belongs.
I would recommend turning your integers to string and using the .contains() method and looping through that. This would make the code easier to understand.
I m working with an array of characters in java. The array can have some missing entries in the middle and I need to know the leftmost index that is empty
My code for that is
private int checkMissingEntry(){
int p = 0;
for(int i = characterArray.length - 1; i >= 0; i--){
if (characterArray[i] == ' '){
p = i;
}
else{
}
}
return p;
}
However, characterArray[i] == ' ' does not detect empty character, the code always returns whatever p was originally assigned to, in this case 0. the if statement never gets executed.
I tried '\0' and '\u0000' but none seems to work.
What is the solution?
private int checkMissingEntry(){
String tmp = new String(characterArray);
if (tmp != null)
return tmp.lastIndexOf(" ");
return -1;
}
Why not search from left to right and return the index immediately when you've reached the first missing character?
EDIT: included example array with missing value
private int checkMissingEntry(){
char[]characterArray = new char[4]; // 4 characters in 1 array
characterArray[0] = 'a'; //but we'll only set values for 3 of them
characterArray[2] = 'b'; //so: index 1 is your empty character
characterArray[3] = 'd';
for(int i = 0; i < characterArray.length ; i++){
char c = characterArray[i]; //get the character at index i
if(c =='\0' || c =='\u0000'){ //check for empty character
return i; //return index
}
} return -1; //only returns -1 if characterArray does not contain the empty character
}
I want to count the number of letter, digit and symbol using JAVA
However the result output is not ideal. it should be 5,2,4
but I got 5,2,13
int charCount = 0;
int digitCount = 0;
int symbol = 0;
char temp;
String y = "apple66<<<<++++++>>>";
for (int i = 0; i < y.length(); i++) {
temp = y.charAt(i);
if (Character.isLetter(temp)) {
charCount++;
} else if (Character.isDigit(temp)) {
digitCount++;
} else if (y.contains("<")) {
symbol++;
}
}
System.out.println(charCount);
System.out.println( digitCount);
System.out.println( symbol);
It should be
} else if (temp == '<')) {
symbol++;
}
In your solution, for every non-letter-or-digit character you check if the entire string contains <. This is always true (at least in your example), so the result you get is the number of special characters in the string.
You should use y.charAt(i) == '<' rather than y.contains("<")
if you use y.contains("<"), it uses the whole string to check whether it contains '<' or not. Since String y contains '<'. When in for loop, there are 4 '<', 6 '+' and 3 '>'.
For checking such charraters, y.contains("<") always be true. That is why you get 13 (=4+6+3) for symbol rather than 4.
This bit is wrong:
y.contains("<")
You are checking the whole string each time when you only want to check a single character (temp)
int charCount = 0;
int digitCount = 0;
int symbol = 0;
char temp;
String y = "apple66<<<<++++++>>>";
for (int i = 0; i < y.length(); i++) {
temp = y.charAt(i);
if (Character.isLetter(temp)) {
charCount++;
} else if (Character.isDigit(temp)) {
digitCount++;
****} else if (temp =="<") {
symbol++;
}
}****
else if (y.contains("<")) {
should be
else if (temp == '<') {
because else every time youu have no letter or digit it is raised.
y.contains("<")
seaches for the substring "<" in the string "apple66<<<<++++++>>>" and it always finds it. This happens 13 times which is the number of chars in the substring <<<<++++++>>>" which does contains neither a letter nor a digt.