word length in Java - java

I am having trouble with understanding some of the codes in my assignment of finding the word lengths in a file. NB: the Environment I am using is Blue J with a library from dukelearntoprogram.com, this is the link for downloading Blue J, http://www.dukelearntoprogram.com/course3/index.php. I have created a void method called countWordLength, with parameter FileResource called resource, and an integer array called counts. this method should return the number words at a specific length in a file. For instance: 2 words of length 2: My as.
They have given me the code for this assignment but I am not understanding the following code, in my countWordLength method.
for (String word : resource.words()) {
int finalLength = 0;
int totalLength = word.length();
if (Character.isLetter(word.charAt(0)) == false) {
finalLength = totalLength-1;
}
else {
finalLength = totalLength;
}
if (Character.isLetter(word.charAt(totalLength-1)) == false && totalLength > 1) {
finalLength = finalLength-1;
}
if (finalLength >= counts.length) {
counts[counts.length-1] += 1;
}
else {
counts[finalLength] += 1;
}
The specific part that I don't understand is the meaning or usefulness of
if (finalLength >= counts.length) {
counts[counts.length-1] += 1;
}
else {
counts[finalLength] += 1;
}
if my question is not clear, and you may want more parts of my code please let know. Any help
will be highly appreciated.

Explanation:
int finalLength = 0;
int totalLength = word.length();
if (Character.isLetter(word.charAt(0)) == false) {
finalLength = totalLength-1;
}
else {
finalLength = totalLength;
}
Above lines are initiating lengths. If 1st character is not alphabet, then reducing length.
if (Character.isLetter(word.charAt(totalLength-1)) == false && totalLength > 1) {
finalLength = finalLength-1;
}
If last character is not alphabet, removing one more character but a special condition added here that it is we reduce word length only if it's length > 1
if (finalLength >= counts.length) {
counts[counts.length-1] += 1;
}
This might be bit tricky for you. If calculated length is greater than array we assigned, we are adding count to last one. Ex: Let's say they assigned array with 20 and if got word length as 30, then we will assign this word count to last index (19).
else {
counts[finalLength] += 1;
}
If length is less than size allowed than we will add to that respective index.

Related

How to obtain the length of the last word in the string

I have reversed the string and have a for loop to iterate through the reversed string.
I am counting characters and I know I have a logic flaw, but I cannot pinpoint why I am having this issue.
The solution needs to return the length of the last word in the string.
My first thought was to iterate through the string backward (I don't know why I decided to create a new string, I should have just iterated through it by decrementing my for loop from the end of the string).
But the logic should be the same from that point for my second for loop.
My logic is basically to try to count characters that aren't whitespace in the last word, and then when the count variable has a value, as well as the next whitespace after the count has counted the characters of the last word.
class Solution {
public int lengthOfLastWord(String s) {
int count = 0;
int countWhite = 0;
char ch;
String reversed = "";
for(int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
reversed += ch;
}
for(int i = 0; i < reversed.length(); i++) {
if(!Character.isWhitespace(reversed.charAt(i))) {
count++;
if(count > 1 && Character.isWhitespace(reversed.charAt(i)) == true) {
break;
}
}
}
return count;
}
}
Maybe try this,
public int lengthOfLastWord(String s) {
String [] arr = s.trim().split(" ");
return arr[arr.length-1].length();
}
Another option would be to use index of last space and calculate length from it:
public int lengthOfLastWord(String string) {
int whiteSpaceIndex = string.lastIndexOf(" ");
if (whiteSpaceIndex == -1) {
return string.length();
}
int lastIndex = string.length() - 1;
return lastIndex - whiteSpaceIndex;
}
String.lastIndexOf() finds the start index of the last occurence of the specified string. -1 means the string was not found, in which case we have a single word and length of the entire string is what we need. Otherwise means we have index of the last space and we can calculate last word length using lastIndexInWord - lastSpaceIndex.
There are lots of ways to achieve that. The most efficient approach is to determine the index of the last white space followed by a letter.
It could be done by iterating over indexes of the given string (reminder: String maintains an array of bytes internally) or simply by invoking method lastIndexOf().
Keeping in mind that the length of a string that could be encountered at runtime is limited to Integer.MAX_VALUE, it'll not be a performance-wise solution to allocate in memory an array, produced as a result of splitting of this lengthy string, when only the length of a single element is required.
The code below demonstrates how to address this problem with Stream IPA and a usual for loop.
The logic of the stream:
Create an IntStream that iterates over the indexes of the given string, starting from the last.
Discard all non-alphabetic symbols at the end of the string with dropWhile().
Then retain all letters until the first non-alphabetic symbol encountered by using takeWhile().
Get the count of element in the stream.
Stream-based solution:
public static int getLastWordLength(String source) {
return (int) IntStream.iterate(source.length() - 1, i -> i >= 0, i -> --i)
.map(source::charAt)
.dropWhile(ch -> !Character.isLetter(ch))
.takeWhile(Character::isLetter)
.count();
}
If your choice is a loop there's no need to reverse the string. You can start iteration from the last index, determine the values of the end and start and return the difference.
Just in case, if you need to reverse a string that is the most simple and efficient way:
new StringBuilder(source).reverse().toString();
Iterative solution:
public static int getLastWordLength(String source) {
int end = -1; // initialized with illegal index
int start = 0;
for (int i = source.length() - 1; i >= 0; i--) {
if (Character.isLetter(source.charAt(i)) && end == -1) {
end = i;
}
if (Character.isWhitespace(source.charAt(i)) && end != -1) {
start = i;
break;
}
}
return end == -1 ? 0 : end - start;
}
main()
public static void main(String[] args) {
System.out.println(getLastWord("Humpty Dumpty sat on a wall % _ (&)"));
}
output
4 - last word is "wall"
Firstly, as you have mentioned, your reverse string formed is just a copy of your original string. To rectify that,
for (int i = s.length() - 1; i >= 0; i--) {
ch = s.charAt(i);
reversed += ch;
}
Secondly, the second if condition is inside your first if condition. That is why, it will never break ( because you are first checking if character is whitespace, if it is, then you are not going inside the if statement, thus your second condition of your inner if loop will never be satisfied).
public class HW5 {
public static void main(String[] args) {
String s = "My name is Mathew";
int count = lengthOfLastWord(s);
System.out.println(count);
}
public static int lengthOfLastWord(String s) {
int count = 0;
int countWhite = 0;
char ch;
String reversed = "";
System.out.println("original string is----" + s);
for (int i = s.length() - 1; i >= 0; i--) {
ch = s.charAt(i);
reversed += ch;
}
System.out.println("reversed string is----" + reversed);
for (int i = 0; i < reversed.length(); i++) {
if (!Character.isWhitespace(reversed.charAt(i)))
count++;
if (count > 1 && Character.isWhitespace(reversed.charAt(i)) == true) {
break;
}
}
return count;
}
}
=
and the output is :
original string is----My name is Mathew
reversed string is----wehtaM si eman yM
6
Another way to go about is : you use the inbuilt function split which returns an array of string and then return the count of last string in the array.

credit card numbers need to be added without the dash

So one of the conditions for the credit card number to be valid is that "the sum of first 4 digits must be 1 less than the sum of the last 4 digits" I believe the problem could be it's counting the dashes as a digit but not sure. the rule 4 is that the sum of all digits must be divisible by 4, which seems to work, but rule 5 doesn't.
int sum = ccNumber.chars().filter(Character::isDigit).map(Character::getNumericValue).sum();
if(sum%4!=0){
valid = false;
errorCode = 4;
return;
}
// set values and for loop for fifth rule.
String digits = ccNumber.replaceAll("[ˆ0-9]","");
int firstfourdigits = 0;
int lastfourdigits = 0;
for(int i=0; i<4; i++)
firstfourdigits = firstfourdigits + Character.getNumericValue(ccNumber.charAt(i));
for (int i=0, m = ccNumber.length()-1; i<4; i++, m--)
lastfourdigits = lastfourdigits + Character.getNumericValue(ccNumber.charAt(m));
// mutator for fifth rule
if(lastfourdigits!= firstfourdigits -1){
valid = false;
errorCode = 5;
return;
}
sorry I'm lost and new to coding.
Edit since you altered your question. Original anwser to the original question is at the bottom part
Checking if first part and last part have a difference of one
The code you currently have is close, but there are some mistakes here and there.
Filtering out only digits: The code you use to filter out all characters that are not numeric should work, but in your following code you are no longer using this filtered value in your loop.
firstfourdigits + Character.getNumericValue(ccNumber.charAt(i));
This should use the variable with only your numeric values => digits
firstfourdigits = firstfourdigits + Character.getNumericValue(digits.charAt(i));
Difference in first group vs last group: The -1 should be replaced by +1 here. When you are experiencing problems with this type of checks, it's always adviced to try and calculate it on a piece of paper. Lets assume the sum of the first 4 digits is 8 and the sum of the last 4 digits is 9. As per the requirement, this is a valid number, and should result to false in your check if(lastfourdigits!= firstfourdigits -1)
Let's fill it in: 9 != 8-1 => 9 != 7 so this returns false, and marks it as invalid. If we base it on the requirement, you could write the sum of the first 4 digits should be one less then the last 4 digits as: firstfourdigits = lastfourdigits - 1. This is mathmatically the same as lastfourdigits = firstfourdigits + 1. However, in our check we want to know if this check is not correct, so we should change the statement to: if(lastfourdigits != firstfourdigits + 1)
These 2 changes should give you the results you asked for. Combining these changes, we come to the following code example
String digits = ccNumber.replaceAll("[ˆ0-9]", "");
int firstfourdigits = 0;
int lastfourdigits = 0;
for (int i = 0; i < 4; i++)
firstfourdigits = firstfourdigits + Character.getNumericValue(digits.charAt(i));
for (int i = 0, m = ccNumber.length() - 1; i < 4; i++, m--)
lastfourdigits = lastfourdigits + Character.getNumericValue(digits.charAt(m));
if(lastfourdigits!= firstfourdigits + 1){
valid = false;
errorCode = 5;
return;
}
Other recommendations
The above example should work for what you asked, and is based on your code. However there are some optimalisations possible to the code to make everything more readable
Use brackets on your for loop: To make it clearer what is inside the for loop, and what isn't, I would advise you to make use of curly brackets. Though they are not required, they will make it very clear what is and isn't in the for loop and will prevent hard to spot issues when you add something extra in the for loop
Use the short notation for addition: Instead of writing firstfourdigits = firstfourdigits + Character.getNumericValue(digits.charAt(i));, You could use a shorter notation of +=. This will take the value on the left side of your equals, and will calculate the sum of that value on the right side. firstfourdigits += Character.getNumericValue(digits.charAt(i));
The code looks like this then:
String digits = ccNumber.replaceAll("[ˆ0-9]", "");
int firstfourdigits = 0;
int lastfourdigits = 0;
for (int i = 0; i < 4; i++){
firstfourdigits += Character.getNumericValue(digits.charAt(i));
}
for (int i = 0, m = ccNumber.length() - 1; i < 4; i++, m--) {
lastfourdigits += Character.getNumericValue(digits.charAt(m));
}
if(lastfourdigits!= firstfourdigits + 1){
valid = false;
errorCode = 5;
return;
}
Anwser to original question to calculate the sum of all digits
You could make use of Character.isDigit(char). To simplify the for loop, you can even make use of a stream to get the sum
int sum = ccNumber.chars().filter(Character::isDigit).map(Character::getNumericValue).sum();
if (sum % 4 != 0) {
valid = false;
errorCode = 4;
return;
}
.chars(): This will create a stream of all the characters in the provided string so that we can loop over them one by one
.filter(Character::isDigit): This will filter out every character that is not a digit
.map(Character::getNumericValue): This will map the stream from Characters to their numeric values so that we can use those further
sum() will calculate the sum of the numeric values that we currently have in the Stream
The difference is always a positive value e.g. the difference between 4 and 5 or between 5 and 4 is the same i.e. 1. In other words, you need to compare the absolute value of the subtraction with 1.
Therefore, replace
if(lastfourdigits!= firstfourdigits -1)
with
if(Math.abs(lastfourdigits - firstfourdigits) != 1)
Another mistake in your code is that you have used ccNumber, instead of digits in your loops.
Some recommendations to make your code easier to understand:
Replace for (int i=0, m = digits.length()-1; i<4; i++, m--) with for (int m = digits.length() - 1; m >= digits.length() - 4; m--). Note that I've already replaced ccNumber, with digits in these statements.
Replace ccNumber.replaceAll("[^0-9]","") with ccNumber.replaceAll("\\D", "").
Replace firstfourdigits = firstfourdigits + Character.getNumericValue(digits.charAt(i)) with firstfourdigits += Character.getNumericValue(digits.charAt(i)). Note that I've already replaced ccNumber, with digits in these statements.
Always enclose the body of if and loop statements within { } even if there is just one statement inside the body.
Demo:
public class Main {
public static void main(String[] args) {
System.out.println(isValidOnDiffCriteria("1234-5678-9101-1213"));
System.out.println(isValidOnDiffCriteria("1234-5678-9101-1235"));
System.out.println(isValidOnDiffCriteria("1235-5678-9101-1234"));
}
static boolean isValidOnDiffCriteria(String ccNumber) {
String digits = ccNumber.replaceAll("\\D", "");
int firstfourdigits = 0;
int lastfourdigits = 0;
for (int i = 0; i < 4; i++) {
firstfourdigits += Character.getNumericValue(digits.charAt(i));
}
for (int m = digits.length() - 1; m >= digits.length() - 4; m--) {
lastfourdigits += Character.getNumericValue(digits.charAt(m));
}
if (Math.abs(lastfourdigits - firstfourdigits) != 1) {
return false;
}
return true;
}
}
Output:
false
true
true
Try the code above. Should be what you asked. You don't need a try catch.
static boolean isCardValid(String creditCard) {
// group digits in a string array
String[] cards = creditCard.split("-");
int sumAll = 0;
// for every group of digits we convert it to char[]
for (String card : cards) {
sumAll += sum(card.toCharArray());
}
int firstGroupOfDigits = sum(cards[0].toCharArray()) ;
int lastGroupOfDigits = sum(cards[cards.length-1].toCharArray());
if( firstGroupOfDigits == lastGroupOfDigits -1){
if (sumAll % 4 == 0) {
return true;
}
}
return false;
}
// sum the group of digits separated by "-"
static int sum(char[] chr) {
int sum = 0;
for (char c : chr) {
sum += Character.getNumericValue(c);
}
return sum;
}
Well, your program is not that bad and as far as I can tell there is only one problem and that is the you simply reversed the required test on the first and last groups. I would advise you to ensure the valid is initialized to true as the default. Then if none of the error codes are set, it will return true.
Presently you have the following:
if (lastfourdigits != firstfourdigits - 1) {
valid = false;
errorCode = 5;
}
But what you need is this
if (lastfourdigits != firstfourdigits + 1) {
valid = false;
errorCode = 5;
}
Your also have the following, unnecessary code.
String digits = ccNumber.replaceAll("[ˆ0-9]","");
The reason being is that you are simply using ccNumber starting at the beginning for the first four characters and starting at the end for the last four. In this way you are not encountering dashes so you don't need to get just the digits.
Another recommendation is that as soon as you find an error you set the error code and return immediately. What's the use in continuing to process a card that has already been found to be flawed?
Other considerations and an alterative approach
It may not be a part of the assignment but I would also consider the following:
What if you have more or less than 16 digits?
What if you have more than three dashes giving more than four groups of numbers.
Checking the above would require additional logic and would complicate your effort. But it is something to consider. What follows demonstrates one way to check on those particular format issues and report them. This uses basic techniques and avoids streams so as not to repeat unnecessary operations.
This example throws selective errors based on problems found. Those may be changed or eliminated altogether as explained later. Credit card validation is a task where the most straightforward solution is best and should require low overhead.
First, declare a special exception to catch credit card errors.
class BadCreditCardException extends Exception {
public BadCreditCardException(String message) {
super(message);
}
}
Now declare some test data.
String[] testData = {
"1234-4566-9292-0210",
"1500-4009-2400-1600",
"1500-4009-2400-160000",
"1234-45669292-0210",
"1#34-45-66-9292-0210",
"1234-45B6-9292-0210",
"1234-4566-9292-2234",
"1234-4566-9292-021022",
"1234-4566-9292-0210",
"4567-4566-92!2-6835",
"1234-4566-9292-0210",
"1234-45+6-9292-0210",
"1234-4566-92x2-0210",
"1234-4566-9292-0210",
};
Test the credit cards and report errors. Note that only first encountered errors are reported. There may be multiple errors in the number.
String fmt = "%-23s - %s%n";
for(String card : testData) {
try {
validate(card);
System.out.printf(fmt,card, "Valid");
} catch (BadCreditCardException bce) {
System.out.printf(fmt,card, bce.getMessage());
}
}
The above prints.
1234-4566-9292-0210 - Invalid credit card checksum
1500-4009-2400-1600 - Valid
1500-4009-2400-160000 - Non group of 4 digits
1234-45669292-0210 - Insufficient or too may dashes
1#34-45-66-9292-0210 - Insufficient or too may dashes
1234-45B6-9292-0210 - Non digit found.
1234-4566-9292-2234 - Valid
1234-4566-9292-021022 - Non group of 4 digits
1234-4566-9292-0210 - Invalid credit card checksum
4567-4566-92!2-6835 - Non digit found.
1234-4566-9292-0210 - Invalid credit card checksum
1234-45+6-9292-0210 - Non digit found.
1234-4566-92x2-0210 - Non digit found.
1234-4566-9292-0210 - Invalid credit card checksum
The Explanation
The validate method. The method works as follows.
split the card into groups using the dash (-) as a delimiter.
If there are not four groups, throw an exception.
Otherwise, sum each of the groups as follows each of these is checked during the summation process.
first check that the group is of size four, if not throw an exception.
as the group characters are iterated, if a non-digit is encountered, throw an exception.
otherwise, continue computing the sum for the current group as follows:
If the character is a digit, subtract 0 to convert it to an int
and add to the current sums array element.
when completed, add that group sum to the totalSum of all digits.
if the totalSum is divisible by four and the first group is one less than the last group, it is a valid card. Otherwise, throw an exception.
Alternative error handling modification
If the exceptions are not wanted, but just a pass or fail indication, then make the following changes.
change the void return type to boolean
if an exception was throw, simply return false
if all tests pass, then the last statement should return true
public static void validate(String cardNumber) throws BadCreditCardException {
int [] groupSums = new int[4];
int totalSum = 0;
String [] groups = cardNumber.split("-");
if (groups.length != 4) {
throw new BadCreditCardException("Insufficient or too may dashes");
}
for (int i = 0; i < groupSums.length; i++) {
if (groups[i].length() != 4) {
throw new BadCreditCardException("Non group of 4 digits");
}
for(int digit : groups[i].toCharArray()) {
if (!Character.isDigit(digit)) {
throw new BadCreditCardException("Non digit found.");
}
groupSums[i]+= digit -'0';
}
totalSum += groupSums[i];
}
if (groupSums[0]+1 != groupSums[3] || totalSum % 4 != 0) {
throw new BadCreditCardException("Invalid credit card checksum");
}
}
A separate class for Credit card and its parts
Add a Part class that manages a portion of the credit card
Add a CreditCard class that manages these portions
Valid each portion
In addition to validating each potion individually, validate additional check
Depending on the number of times, the valid & sumDigits method will be called, validation/sum can be added in respective methods or in constructor.
import java.util.Arrays;
public class CreditCard {
private final String input;
private final Part[] parts;
private final boolean valid;
CreditCard(String card) {
this.input = card;
if (card == null || card.length() != 19) {
valid = false;
parts = null;
} else {
parts = Arrays.stream(card.split("-")).map(Part::new).toArray(Part[]::new);
final int totalSum = Arrays.stream(parts).mapToInt(Part::sumDigits).sum();
valid = totalSum % 4 == 0 && parts.length == 4
&& parts[0].sumOfDigits + 1 == parts[3].sumOfDigits
&& Arrays.stream(parts).allMatch(Part::isValid);
}
}
static class Part {
final int num;
final boolean valid;
final int sumOfDigits;
Part(String part) {
int localNum = 0;
try {
localNum = Integer.parseInt(part);
} catch (Throwable ignored) {
}
this.num = localNum;
valid = part.length() == 4 && part.equals(String.format("%04d", num));
if (valid) {
sumOfDigits = part.chars().map(Character::getNumericValue).sum();
} else {
sumOfDigits = -1;
}
}
boolean isValid() {
return valid;
}
int sumDigits() {
return sumOfDigits;
}
}
public static void main(String[] args) {
String[] creditCards = {
"1000-0000-0001-0002",
"0000-0000-0000-0000",
"10000-0000-0001-0002",
"10000000-0001-0002",
"1a00-0000-0001-0002",
"1234-4826-6535-1235",
};
Arrays.stream(creditCards).map(CreditCard::new)
.forEach(c -> System.out.println(c.input + " is " + c.valid));
}
}
Everything is fine except the second for loop and your if condition.
Replace your code with the following changes and it should work fine:
int firstfourdigits = 0, lastfourdigits = 0;
for(int i=0; i<4; i++)
firstfourdigits = firstfourdigits + Character.getNumericValue(ccNumber.charAt(i));
for (int m = ccNumber.length()-1; m>ccNumber.length()-5; m--)
lastfourdigits = lastfourdigits + Character.getNumericValue(ccNumber.charAt(m));
if(firstfourdigits != lastfourdigits - 1){
valid = false;
errorCode = 5;
return;
}
You do not need to extract digits at all.
public boolean ccnCheck(String ccn){
String iccn = ccn.replaceAll("-","");
int length = iccn.length();
int fsum = 0;
int lsum = 0;
int allsum = 0;
for( int i = 0; i < length; i++){
int val = Character.getNumericValue(iccn.charAt(m))
if( i < 4)
fsum += val;
if( i >= length-4)
lsum += val;
allsum += val;
}
if( (allsum % 4) != 0)
return false;
if( fsum != lsum-1 )
return false;
return true;
}
In your rule five check, you're using ccNumber instead of your digits string.
For example, shouldn't
Character.getNumericValue(ccNumber.charAt(i));
be this instead:
Character.getNumericValue(digits.charAt(i));

Codingbat coverting recursive loop to for loop?

I am doing codingbat as practice for an upcoming quiz that I have. I am doing the recursion problems using recursion, but my teacher said that I should be able to do them using other loops. I figured that I should use for loops as they achieve are easily able to achieve the same result.
But I am having trouble converting the recursion to a for loop.
This is the problem:
Given a string and a non-empty substring sub, compute recursively the number of times that sub appears in the string, without the sub strings overlapping.
strCount("catcowcat", "cat") → 2
strCount("catcowcat", "cow") → 1
strCount("catcowcat", "dog") → 0
This is the code I am trying to use:
public int strCount(String str, String sub) {
int number = 0;
for (int i = 0; i >= str.length() - 1; i++) {
if (str.substring(i, sub.length()).equals(sub)) {
number += 1;
}
}
return number;
}
When I return, everything returns as 0.
In your for loop when you say
i >= str.length() - 1
the loop is never entered, because you are testing that i is greater than the allowed length (and it isn't). You need something like
i <= str.length() - 1
or
i < str.length()
Also, number += 1; can be written as number++;
One of the details you missed is "without the sub strings overlapping". This problem calls for a while loop, rather than a for loop, since the index will be incremented by different amounts, depending on whether there is a match or not.
Here's executable code to test whether or not the strCount method works correctly.
package com.ggl.testing;
public class StringCount {
public static void main(String[] args) {
StringCount stringCount = new StringCount();
System.out.println(stringCount.strCount("catcowcat", "cat"));
System.out.println(stringCount.strCount("catcowcat", "cow"));
System.out.println(stringCount.strCount("catcowcat", "dog"));
}
public int strCount(String str, String sub) {
int count = 0;
int length = str.length() - sub.length();
int index = 0;
while (index <= length) {
int substringLength = index + sub.length();
if (str.substring(index, substringLength).equals(sub)) {
count++;
index += sub.length();
} else {
index++;
}
}
return count;
}
}

Java Counting letter,digit and symbol

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.

Using for loop to get the Hamming distance between 2 strings

In this task i need to get the Hamming distance (the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different - from Wikipedia) between the two strings sequence1 and sequence2.
First i made 2 new strings which is the 2 original strings but both with lowered case to make comparing easier. Then i resorted to using the for loop and if to compare the 2 strings. For any differences in characters in these 2 pair of string, the loop would add 1 to an int x = 0. The returns of the method will be the value of this x.
public static int getHammingDistance(String sequence1, String sequence2) {
int a = 0;
String sequenceX = sequence1.toLowerCase();
String sequenceY = sequence2.toLowerCase();
for (int x = 0; x < sequenceX.length(); x++) {
for (int y = 0; y < sequenceY.length(); y++) {
if (sequenceX.charAt(x) == sequenceY.charAt(y)) {
a += 0;
} else if (sequenceX.charAt(x) != sequenceY.charAt(y)) {
a += 1;
}
}
}
return a;
}
So does the code looks good and functional enough? Anything i could to fix or to optimize the code? Thanks in advance. I'm a huge noob so pardon me if i asked anything silly
From my point the following implementation would be ok:
public static int getHammingDistance(String sequence1, String sequence2) {
char[] s1 = sequence1.toCharArray();
char[] s2 = sequence2.toCharArray();
int shorter = Math.min(s1.length, s2.length);
int longest = Math.max(s1.length, s2.length);
int result = 0;
for (int i=0; i<shorter; i++) {
if (s1[i] != s2[i]) result++;
}
result += longest - shorter;
return result;
}
uses array, what avoids the invocation of two method (charAt) for each single char that needs to be compared;
avoid exception when one string is longer than the other.
your code is completely off.
as you said yourself, the distance is the number of places where the strings differ - so you should only have 1 loop, going over both strings at once. instead you have 2 nested loops that compare every index in string a to every index in string b.
also, writing an if condition that results in a+=0 is a waste of time.
try this instead:
for (int x = 0; x < sequenceX.length(); x++) { //both are of the same length
if (sequenceX.charAt(x) != sequenceY.charAt(x)) {
a += 1;
}
}
also, this is still a naive approach which will probbaly not work with complex unicode characters (where 2 characters can be logically equal yet not have the same character code)
public static int getHammingDistance(String sequenceX, String sequenceY) {
int a = 0;
// String sequenceX = sequence1.toLowerCase();
//String sequenceY = sequence2.toLowerCase();
if (sequenceX.length() != sequenceY.length()) {
return -1; //input strings should be of equal length
}
for (int i = 0; i < sequenceX.length(); i++) {
if (sequenceX.charAt(i) != sequenceY.charAt(i)) {
a++;
}
}
return a;
}
Your code is OK, however I'd suggest you the following improvements.
do not use charAt() of string. Get char array from string using toCharArray() before loop and then work with this array. This is more readable and more effective.
The structure
if (sequenceX.charAt(x) == sequenceY.charAt(y)) {
a += 0;
} else if (sequenceX.charAt(x) != sequenceY.charAt(y)) {
a += 1;
}
looks redundant. Fix it to:
if (sequenceX.charAt(x) == sequenceY.charAt(y)) {
a += 0;
} else {
a += 1;
}
Moreover taking into account that I recommended you to work with array change it to something like:
a += seqx[x] == seqY[x] ? 0 : 1
less code less bugs...
EDIT: as mentionded by #radai you do not need if/else structure at all: adding 0 to a is redundant.

Categories