Trying to increment counter using character comparison - java

I'm writing a method that is supposed to iterate through a string and increment a counter each time the letter c is found. The method uses the count to calculate the proportion of the string that was c. I added print statements to investigate why it was wrongly returning 0.0 for a string that had some c's in it.
I have tried declaring the counter as an int and then casting it to double later but that didn't help.
public double cRatio() {
String dna = "ATCCCCCCGTACCTAGCAA";
double cCount = 0.0;
for (int i = 0; i < dna.length(); i++) {
char ch = dna.charAt(i);
if (ch == 'c') {cCount++;}
}
System.out.println("C Count is : " + cCount);
System.out.println("dna.length() is : " + dna.length());
double cgRatio = (cCount / dna.length());
System.out.println("C Ratio is : " + cgRatio);
return cgRatio;
}
I expect the counter to have value 9.0 at the time it prints but instead, it is 0.0.

Your code does not count the letter c because you are checking for the letter C. The small c does not equal the upper C (different ASCII code).
if (ch == 'C') {cCount++;}
This will fix your problem.

Related

I dont understand why my Java code isnt reading IX as 9 but is reading LIX as 59

I am trying to create some code to read roman numerals and turn them into an integer. the issue im having is the 9s and 4s. I am able to get it to read if the 9 or 4 is inside a number (I.E LIV is 54 and LXI is 59) but by its self (IV and IX) it only reads 6 and 11.
here is my code:
public static void RomantoInt(String s) {
HashMap<Character, Integer> RomanNums = new HashMap<>();
int count = 0;
RomanNums.put('I', 1);
RomanNums.put('V', 5);
RomanNums.put('X', 10);
RomanNums.put('L', 50);
RomanNums.put('C', 100);
RomanNums.put('D', 500);
RomanNums.put('M', 1000);
LinkedList<Character> UserInput = new LinkedList<>();
//Adds Each numeral to the Array
for (int i = 0; i < s.length(); i++) {
char userint = s.charAt(i);
UserInput.add(userint);
}
//loop through the array backwards and adds up the count.
for(int j =UserInput.toArray().length -1; j> -1 ; j--) {
int grab = RomanNums.get(UserInput.get(j));
count += grab;
// Checks for 4s and 9s.
if(grab == RomanNums.get('X') && (j - 1) == RomanNums.get('I')) {
count -= 2;
}
}
System.out.println(count);
Comparing j - 1 -- which is a position in a string -- to the value of a roman numeral does not seem to make any sense.
Specifically, it only works when the roman 'I' is the second character, exactly.
What you really want to be testing is whether the character at the (j-1)'th position is 'I'.
The correct formulation should be something like
if (grab == RomanNums.get('X') &&
j > 0 &&
UserInput.get(j-1) == 'I') ...
This was my solution for leetcode: https://leetcode.com/problems/roman-to-integer/
You have the right idea about reading the input backwards and one loop should be enough to get the job done.
All you need to do is account for the cases when you have to subtract the roman numeral, and you can do that by keeping track of the previous roman numeral for comparison.
For example when input string is: "IX"
We start at 'X' in the first iteration and since previous is equal to '?' we just add 10 and set previous to 'X'. Now when we attempt to sum up 'I' in the next iteration, we look at previous and notice that it is an 'X' and instead of adding 1 to the running sum , we should subtract 1. The total should be 9.
public int romanToInt(String s) {
int sum = 0;
char prev = '?';
for(int i = s.length()-1;i >= 0;i--) {
switch(s.charAt(i)) {
case 'I' : sum += prev == 'V' || prev == 'X' ? -1 : 1;
break;
case 'V' : sum += 5;
break;
case 'X' : sum += prev == 'L' || prev == 'C' ? -10 : 10;
break;
case 'L' : sum += 50;
break;
case 'C' : sum += prev == 'D' || prev == 'M' ? -100 : 100;
break;
case 'D' : sum += 500;
break;
case 'M' : sum += 1000;
break;
default :
break;
}
prev = s.charAt(i);
}
return sum;
}
Time complexity is O(n) - Iterated the length of the input string
Space complexity is O(1) - No additional data structure was needed

How would I add two int that are in the same array to each other and convert them into an int. In the Luhn Algorithm

I am trying to add two parts of an array together to go into an int value. I am using Luhn algorithm to figure out of a credit card is a valid credit card. We are only using 6 digit credit card's just to make sure no one enter's a real credit card number. The part I am confused on is when I go to split a number that is above 10 and add it together. Example if the algorithm was to give me 12 I would need to separate it into 1 and 2 and then add them together to equal 3. I believe I am splitting it currently in the code but when I go to add them together I get some number that makes no since. here is a section of the code with some notes about it.
I have printed out numbers in certain places to show myself what is going on in certain places. I have also added in some comments that say that either the number that is printed out is what is expected, and some comments for when there isn't something I expected
int[] cardNumber = new int[]{ 1,2,3,4,5,5};
int doubleVariablesum = 0;
int singleVariablesum = 0;
int totalSum = 0;
int cutOffVar = 0;
String temp2;
for (int i = cardNumber.length - 1; i >= 0;) {
int tempSum = 0;
int temp = cardNumber[i];
temp = temp * 2;
System.out.println("This is the temp at temp * 2: " + temp);
temp2 = Integer.toString(temp);
if (temp2.length() == 1) {
System.out.println("Temp2 char 0: "+ temp2.charAt(0));
// this prints out the correct number
// Example: if there number should be 4 it will print 4
tempSum = temp2.charAt(0);
System.out.println("This is tempSum == 1: " + tempSum);
// when this goes to add temp2.charAt(0) which should be 4 it prints out //something like 56
} else {
System.out.println("TEMP2 char 0 and char 1: " + temp2.charAt(0) + " " + temp2.charAt(1));
// this prints out the correct number successfully spited
tempSum = temp2.charAt(0) + temp2.charAt(1);
System.out.println("This is tempSum != 1: " + tempSum);
// but here it when I try to add them together it is giving me something
// like 97 which doesn't make since for the numbers I am giving it
}
doubleVariablesum = tempSum + doubleVariablesum;
System.out.println("This is the Double variable: " + doubleVariablesum);
System.out.println();
i = i - 2;
}
Since you are converting the number to a string to split the integer, and then trying to add them back together. You're essentially adding the two characters numerical values together which is giving you that odd number. You would need to convert it back to an integer, which you can do by using
Integer.parseInt(String.valueOf(temp2.charAt(0)))
When adding char symbols '0' and '1' their ASCII values are added - not numbers 0 and 1.
It is possible to use method Character::getNumericValue or just subtract '0' when converting digit symbol to int.
However, it is also possible to calculate sum of digits in a 2-digit number without any conversion to String and char manipulation like this:
int sum2digits = sum / 10 + sum % 10; // sum / 10 always returns 1 if sum is a total of 2 digits
Seems like charAt() type casts into integer value, but the ascii one. Hence for the characters '0' and '1', the numbers 48 and 49 are returned resulting in a sum of 97. To fix this, you could just assign temp2 to (temp / 10) + (temp % 10). Which actually splits a two digit integer and adds their sum.
You need to be aware of the following when dealing with char and String
Assigning the result of charAt(index) to an int will assign the ASCII value and not the actual integer value. To get the actual value you need to String.valueOf(temp2.charAt(0)).
The result of concatenating chars is the sum of the ASCII values.
eg if char c = '1'; System.out.println(c + c); will print "98" not "11".
However System.out.println("" + c + c); will print "11". Note the "" will force String concatenation.

Adding/Subtracting big number to and from a character

For case #1, adding 2 to 'a' gives us 'c'.
How can I write a program so that adding 2 to 'z' gives 'b' as an output and subtracting 3 from 'a' gives 'x' as an output?
In other words, I want only alphabet character as an output. No matter how big number you are adding or subtracting to and from the character, I always expect the output between a and z inclusive.
case #1
public void addNumberToCharacter{
char character = 'a' + 2;
System.out.println(character); // 'c'
}
case #2
public void addNumberToCharacter{
char character = 'z' + 2;
System.out.println(character); // 'b'
}
case #3
public void addNumberToCharacter{
char character = 'a' - 3;
System.out.println(character); // 'x'
}
To handle two cases you might also require:
uppercase and lowercase;
adding/subtracting number whose absolute value is bigger than 26;
And here is the method you can refer to:
private static void addNumToChar(int a, char c0) {
char c = 'a';
if(Character.isUpperCase(c0)) {
c = 'A';
}
while (a < 0) a += 26;
char c1 = (char) (c + (c0 - c + a) % 26);
System.out.println(c1);
}
Run the test as follows:
addNumToChar(2, 'B'); // D
addNumToChar(2, 'b'); // d
addNumToChar(261, 'B'); // C
addNumToChar(261, 'b'); // c
addNumToChar(-2, 'B'); // Z
addNumToChar(-2, 'b'); // z
addNumToChar(-261, 'B'); // A
addNumToChar(-261, 'b'); // a
After you add or subtract, correct with:
character = (character + 26 - 'a')%26 + 'a';
Java's x%y operator gives the remainder from integer division of x by y. Subtracting 'a' gives the offset from the start of the lowercase alphabet, and then adding 26 guarantees a positive sum, provided you didn't add an offset less than -26 or subtract more than +26.
public char number(int num, char c){ // -- num =29, char= 'd'
int n = c - 96 ; // n = 4
n = n+(num%26); // n = 4 + 3 = 7
if(n > 26){ return (char)(n-26); } // doesnot follow
else if(n < 0){ return (char)(n+26); } // doesnot follow
else { return (char)(n); } // return g
}
You can try this method. It can handle positive as well as negative number.
use that one :-
public static void main(String[] args) {
char c= 'a' - 1;
if(!(c>=97 && c<=122)) {
if(c>=123)
c= (char) (c-26);
else
c= (char) (c+26);
}
System.out.println(c);
}

Incremented by a value x but it gets incremented by value x-1

I am implementing an Algorithm where when user gives input string, every character in string (if it is alphabet) should be incremented by value given(here rotator). I am playing with this code for 2 hr but can't figure out why when i increment by value rotator, it gets incremented by rotator-1.
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner in = new Scanner(System.in);
int length = in.nextInt();
String input = in.next();
int nextvalue = 0;
int temp = 0;
char array[] = input.toCharArray();
int rotator = in.nextInt();
for(int i = 0; i < length; i++){
if((array[i] >= 'a' && array[i] <= 'z') || (array[i] >= 'A' && array[i] <= 'Z')){
nextvalue = (int)array[i] + rotator;
array[i] = (char)nextvalue;
if((int)array[i] > (int)'z'){
temp = (int)array[i] - (int)'z';
nextvalue = (int)'a' + temp -1;
array[i] = (char)nextvalue;
}
else if((int)array[i] > (int)'Z'){
temp = (int)array[i] - (int)'Z';
nextvalue = (int)'Z' + temp -1;
array[i] = (char)nextvalue;
}
}
}
System.out.println(array);
}
}
Inside first if there are two if statements to handle(Overflow condition) if letter is > z or >Z. Now if I Remove those two statements everything except overflow condition is correctly printed
(without overflow condition)
Sample I/P :
11 <- String length
middle-Outz
2 <- rotator
Sample O/P :
okffng-Qwv| <- Overflow condition not handled
(with overflow condition)
Sample I/P :
11
middle-Outz
2
Sample O/P :
njeemf-Qvub <- Overflow handled but everything else incremented by rotator - 1 except 'Q'
Why is this happening? I also checked using print statement in inner if condition , it executes only one time for this input since there is only one overflow condition.
Help/Suggestion appreciated.Thanks.
I think the easiest way to handle the overflow cases is to use the modulus operator to let the character wrap-around any number of times to land in the current logical position. Something like this should work:
for (int i=0; i < length; i++) {
if (array[i] >= 'a' && array[i] <= 'z') {
int currDiff = (int)array[i] - (int)'a';
int newPos = (int)'a' + ((rotator + currDiff) % 26);
array[i] = (char)newPos;
}
else if (array[i] >= 'A' && array[i] <= 'Z') {
int currDiff = (int)array[i] - (int)'A';
int newPos = (int)'A' + ((rotator + currDiff) % 26);
array[i] = (char)newPos;
}
}
I tested this code using an input string of abcdefg and a rotator value of 51, which returned zabcdef. This is expected, because we rotated one step short of two complete rounds. Hence, the a landed on z, after one complete rotation, and the following characters followed suit.
Note that there is a much nicer way of handling the calculus of character positions here, but this answer stays true to the way you were doing it in your original question.
Final note:
The modulus operator % returns the remainder of the division of the number which preceeds it and proceeds it. In the solution I gave above, I take the effective rotator % 26. Here, the effective rotator is the current distance of the letter from either a or A plus however many steps we want to rotate. By taking this number mod 26, we always will end up with a number between 0 and 25. Hence, we will always take between 0 and 25 steps from a or A, which is the behavior you want in your program.
Because you are modifying it twice in your loop.
for(int i = 0; i < length; i++){
if((array[i] >= 'a' && array[i] <= 'z') || (array[i] >= 'A' && array[i] <= 'Z')){
nextvalue = (int)array[i] + rotator;
array[i] = (char)nextvalue; //<-- modifies from m to o
if((int)array[i] > (int)'z'){
temp = (int)array[i] - (int)'z';
nextvalue = (int)'a' + temp -1;
array[i] = (char)nextvalue;
}
else if((int)array[i] > (int)'Z'){
temp = (int)array[i] - (int)'Z';
nextvalue = (int)'Z' + temp -1;
array[i] = (char)nextvalue; //<--modifies again from o to n
}
}
}
The mistake is in this line:
if ((int) array[i] > (int) 'Z') {
You have to keep in mind that lowercase letters come "after" uppercase letters: 'Z' is represented by 90, and (for example) 'j ' is represented by 106 (for more info see this). The reason why 'Q' isn't affected by this mistake is because it is also a capital letter, and thus has a smaller decimal representation than 'Z'.
To fix this, you have to replace the line of code above with something along the lines of this:
if ((int) array[i] > (int) 'Z' && (int) array[i] <= (int) 'Z' + rotator) {
Instead of
nextvalue = (int)'Z' + temp -1;
Shouldn't it be
nextvalue = (int)'A' + temp -1;

How to properly use substring

public static String updatePartialword(String partial, String secretWord, char guess){
char achar = secretWord.charAt(0);
char bchar = secretWord.charAt(1);
char cchar = secretWord.charAt(2);
char dchar = secretWord.charAt(3);
char echar = secretWord.charAt(4);
if (achar == guess);{
partial = guess + partial.substring(1,4);
}if (bchar == guess);{
partial = partial.substring(0)+ guess + partial.substring(2,4);
}if (cchar == guess);{
partial = partial.substring(0,1)+ guess + partial.substring(3,4);
}if (dchar == guess);{
partial = partial.substring(0,2)+ guess + partial.substring(3);
}if (echar == guess);{
partial = partial.substring(0,3)+ guess;
}
This is returning values like "aaaa", a being the value that was input. The initial value for partial is "-----". This is kind of like wheel of fortune. So when a user enters "a", the result should be something like "-a---" Thanks.
Enter your guess:
a
Character a appears 1 time(s)
You now have 150 dollars
a----
You have two options:
a) guess a character
b) buy a character
Type a or b
a
You chose to guess a character
Rolling Dice
Outcome is 0
Enter your guess:
n
Character n appears 1 time(s)
You now have 150 dollars
a----n---
You have two options:
a) guess a character
b) buy a character
Type a or b
Others have answered the question, but have in mind also that you should do
partial = guess + partial.substring(1,5);
because the ending position you specify is not included in the substring, so with your code it'd get the positions 1-3.

Categories

Resources