Java - add N distance to string - java

I am quite new in Java world and I am struggeling with the following problem:
I am currently trying to edit a coding in which, given a string, following changes are made:
if is uppercase, change it to lowercase and vice versa
to the corresponding string corresponds another string which is in a distance of N positions
I wrote the following:
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public String code(String text, int distance) {
// cambio mayus <-> minus
StringBuilder sb = new StringBuilder(text);
for (int index = 0; index < sb.length(); index++) {
char c = sb.charAt(index);
if (Character.isLowerCase(c)) {
sb.setCharAt(index, Character.toUpperCase(c));
} else {
sb.setCharAt(index, Character.toLowerCase(c));
}
}
// comparison string to ALPHABET
for (int i = 0; i < sb.length(); i++) {
for (int j = 0, j < ALPHABET.length(); j++) {
//tiene en cuenta mayusculas y minusculas
if (sb[i] == ALPHABET[j] && sb[i] == ALPHABET[j].toUpperCase()) {
// adds the distance
sb[i] = ALPHABET[j+distance];
}
}
}
return sb;
}
Until now I doubt if is well done and I don't know how to deal with the problem that ALPHABET has a circular behaviour, I mean, if the distance N is greater than 26, from 'z', will go again to 'a' This is what I don't know how to express.
How would you do it?
Thank you in advance!

Related

Nested for loop, not picking up first instance in Array

I am trying to encode a word, and I am not sure why my for loops aren't picking up the first instance, 0. The input for this method is "This" and 3. The output from this method is klv. So my loop must not be working properly as the letter T is getting skipped. What is wrong with my loops?
String encodeWord(String word, int Shift) {
//word = "This"
//Shift = 3, is how far the letter is shifted to the right of the original
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
char[] temp = word.toCharArray();
char[] FA = new char[temp.length];
String tempWord = "";
StringBuilder sb = new StringBuilder(64);
for (int x = 0; x < word.length(); x++) {
for (int y = 0; y < alphabet.length; y++) {
if (word.charAt(0) == alphabet[y]) {
FA[0] = alphabet[y + shift];
System.out.println(FA[0]);
}
}
}
for (int i = 0; i < word.length(); i++) {
for (int j = 0; j < alphabet.length; j++) {
if (word.charAt(i) == alphabet[j]) {
FA[i] = alphabet[j + shift];
sb.append(FA[i]);
System.out.println(FA[i]);
}
}
}
System.out.println(sb);
return sb.toString();
}
The letter 'T' is different from the letter 't', so since only the letter 't' is found in your array, the program won't find a match for the letter 'T'.
Another problem with your code is that you will get an Index out of bounds exception if the input contains the letters 'x', 'y' or 'z' because there aren't 3 letters after them in the array.
public static String encoder(String word, int shift)
{
static const int max_char = 122; //letter 'z'
static const int min_char = 97; //letter 'a'
char[] c_array = word.toCharArray();
char[] encoded_string = new char[c_arary.length()];
for(for i = 0; i < c_array.length(); i++)
{
if( ((int)c + shift) > max_char) //makes sure that the ascii isnt a non number
{
encoded_string[i] = (min_char + (int)c + shift - max_char ); // this will correct the overflow
}
c = c + shfit;
}
return encoded_string;
}
This is an easier way to do this... also your loops have a few logical errors.. the first one i caught was in the first loop... if there is a z in your word your going to overflow your alphabet array.
This is using the Ascii table way

Java program to find the letter that appears in the most words?

I have a sentence, and I want to find the char that appears in the most words, and how many words it appears in.
For example: "I like visiting my friend Will, who lives in Orlando, Florida."
Which should output I 8.
This is my code:
char maxChar2 = '\0';
int maxCount2 = 1;
for (int j=0; j<strs2.length; j++) {
int charCount = 1;
char localChar = '\0';
for (int k=0; k<strs2[j].length(); k++) {
if (strs2[j].charAt(k) != ' ' && strs2[j].charAt(k) != maxChar2) {
for (int l=k+1; l<strs2[j].length(); l++) {
if (strs2[j].charAt(k)==strs2[j].charAt(l)) {
localChar = strs2[j].charAt(k);
charCount++;
}
}
}
}
if (charCount > maxCount2) {
maxCount2 = charCount;
maxChar2 = localChar;
}
}
, where strs2 is a String array.
My program is giving me O 79. Also, uppercase and lowercase do not matter and avoid all punctuation.
As a tip, try using more meaningful variable names and proper indentation. This will help a lot especially when your program is not doing what you thought it should do. Also starting smaller and writing some tests for it will help a bunch. Instead of a full sentence, get it working for 2 words, then 3 words, then a more elaborate sentence.
Rewriting your code to be a bit more readable:
// Where sentence is: "I like".split(" ");
private static void getMostFrequentLetter(String[] sentence) {
char mostFrequentLetter = '\0';
int mostFrequentLetterCount = 1;
for (String word : sentence) {
int charCount = 1;
char localChar = '\0';
for (int wordIndex = 0; wordIndex < word.length(); wordIndex++) {
char currentLetter = word.charAt(wordIndex);
if (currentLetter != ' ' && currentLetter != mostFrequentLetter) {
for (int l = wordIndex + 1; l < word.length(); l++) {
char nextLetter = word.charAt(l);
if (currentLetter == nextLetter) {
localChar = currentLetter;
charCount++;
}
}
}
}
if (charCount > mostFrequentLetterCount) {
mostFrequentLetterCount = charCount;
mostFrequentLetter = localChar;
}
}
}
Now all I did was rename your variables and change your for loop to a for-each loop. By doing this you can see more clearly your algorithm and what you're trying to do. Basically you're going through each word and comparing the current letter with the next letter to check for duplicates. If I run this with "I like" i should get i 2 but instead I get null char 1. You aren't properly comparing and saving common letters. This isn't giving you the answer, but I hope this makes it more clear what your code is doing so you can fix it.
Here is a somewhat more elegant solution
public static void FindMostPopularCharacter(String input)
{
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
input = input.toUpperCase();
HashMap<Character, Integer> charData = new HashMap<>();
char occursTheMost = 'A'; //start with default most popular char
int maxCount = 0;
//create the map to store counts of all the chars seen
for(int i = 0; i < alphabet.length(); i++)
charData.put(alphabet.charAt(i), 0);
//first find the character to look for
for(int i = 0; i < input.length(); i++)
{
char c = input.charAt(i);
//if contained in our map increment its count
if(charData.containsKey(c))
charData.put(c, charData.get(c) + 1);
//check for a max count and set the values accordingly
if(charData.containsKey(c) && charData.get(c) > maxCount)
{
occursTheMost = c;
maxCount = charData.get(c);
}
}
//final step
//now split it up into words and search which contain our most popular character
String[] words = input.split(" ");
int wordCount = 0;
CharSequence charSequence;
for(Character character : charData.keySet())
{
int tempCount = 0;
charSequence = "" + character;
for(int i = 0; i < words.length; i++)
{
if(words[i].contains(charSequence))
tempCount++;
}
if(tempCount > wordCount)
{
occursTheMost = character;
wordCount = tempCount;
}
}
System.out.println(occursTheMost + " " + wordCount);
}
Output of
String input = "I like visiting my friend Will, who lives in Orlando, Florida.";
FindMostPopularCharacter(input);
is
I 8
Note: If there are ties this will only output the character that first reaches the maximum number of occurrences.
FindMostPopularCharacter("aabb aabb aabb bbaa");
Outputs
B 4
because B reaches the max first before A due to the last word in the input.
FindMostPopularCharacter("aab aab b")
B 3

how can I use the for loop in java to print out the word chicken in a triangle shape?

Implement the printTriangle method so that it prints a triangle out of the letters in parameter str. For example, if str is Chicken then your method should print the following
C
Ch
Chi
Chic
Chick
Chicke
Chicken
Also What if I wanted it to go from the full word chicken to c and also a different one that starts with the last letter and builds up to the whole word?
public class Triangle {
public void printTriangle(String str) {
for (int x = 1; x < str.length(); x++){
}
for ( int y = 0 ; y < ; y ++ ){
System.out.print(str.substring(y))
System.out.println( );
}
this is what I have :(
//should look like a triangle
Try this one:
public class Triangle {
public void printTriangle(String input) {
for(int i = 0; i < input.length(); ++i) {
System.out.println(input.substring(0, i + 1));
}
}
public static void main(String[] args) {
new Triangle().printTriangle("Chicken");
}
}
Something like this should work.
String str = "Chicken";
for(int y = 1; y <= str.length(); y++) {
System.out.println(str.substring(0, y));
}
C
Ch
Chi
Chic
Chick
Chicke
Chicken
And other combination:
String str = "Chicken";
for(int y = 0; y < str.length(); y++) {
System.out.println(str.substring(y));
}
Chicken
hicken
icken
cken
ken
en
n
String str = "Chicken";
for(int y = str.length() - 1; y >= 0 ; y--) {
System.out.println(str.substring(y));
}
n
en
ken
cken
icken
hicken
Chicken
I tried some things for this but my best method was this:
public static void printOutWordAsTriangle(String word) { //Supply a String as the word to print
int currentLetter = 0; //The amount of letters which are printed per line. 0,1,2... (So it looks like a triangle)
char[] letters = word.toCharArray(); //Split the string into a char Array
while (currentLetter < letters.length) { //Print every line
String toPrint = "";
int i = 0;
for (char c : letters) { //Print all characters needed for the word-part of the line
if (i <= currentLetter) { // check if the character belongs to it
toPrint = toPrint + String.valueOf(c);
}
i++;
}
System.out.println(toPrint); // Print the line
currentLetter++;
}
}
Now, you can use this method. You just need to supply a String.
Example:
printOutWordAsTriangle("WeLoveChicken");
Note: This will only print out the word in one direction. To the second, I am confident that you can do it.
This Is what you are looking for. Ignoring syntax error in your code, the problem is you are doing substring of a string, so when you start with Chicken, and you are getting a substring of say... 0(the start) you are getting Chicken, at substring 1, you are getting hicken. You can do what you are trying to do using my following example.
public static void printTriangle(String str) {
String temp = "";
for (int x = 0; x < str.length(); x++){
temp += str.charAt(x);
System.out.println(temp);
}
}

Reverse a string then swap every nth letter

I've been stuck on this problem for two hours now. Basically I need to reverse a string (which I've done no problem), then swap every nth letter (which is where im stuck).
Here is what I have so far:
public class StringMethods {
public static void main(String[] args) {
String s = "Hey there";
int n = 2;
System.out.println(reverseString(s));
System.out.println(reverseStringChallenge(s, n));
}
private static String reverseString(String s) {
String reversed = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed = reversed + s.charAt(i);
}
return reversed;
}
private static String reverseStringChallenge(String s, int n) {
String reversed = "";
String swapped = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed = reversed + s.charAt(i); // normal reverse
}
char [] charArray = reversed.toCharArray(); //Strings are immutable, convert string to char array
for(int i = 0; i < charArray.length; i++) {
if(i%n == 0) {
//this is where im stuck
}
}
return swapped;
}
}
I know that strings are immutable in java so I need to convert the reversed string into a char array, and then loop through the array but not sure what to do here.
Any advice would be really appreciated. its doing my head in.
Edit: sorry what I mean by swap every nth letter is that say n = 2. then every second letter gets swapped with its previous one.
You didn't clarify the swap logic, but how about something like this:
for(int i = n; i < charArray.length; i += n) {
char a = charArray[i-n];
char b = charArray[n];
charArray[i-n] = b;
charArray[n] = a;
}
Here's a basic swap
int n = 1;
int n1 = 2;
int temp = n; // variable to hold n value
n = n2; // make n = n2
n2 = temp; // make n2 = n
// now n = 2
// and n2 = 1
Not really sure from your question what it is you're trying to do, so I can't really give a definite answer
If you are swapping the current char with the next char you could do something like:
private static String reverseStringChallenge(String s, int n)
{
String reversed = StringUitls.reverse(s);
StringBuilder sb = new StringBuilder();
char [] charArray = reversed.toCharArray();
for(int i = 0; i < charArray.length; i++) {
if(i%n == 0)
{
sb.append(charArray[i+1]).append(charArray[i]);
i++;
}else{
sb.append(charArray[i]);
}
}
return sb.toString();
}
I'm excuse null and out of bound checks =) good luck

Swapping elements in ArrayList

I want to write a method, which takes a String and swaps each pair of characters in it and then concatenates them into a new String. Please let me know how to fix this code (or write a new better one):
static String s;
public static void proc(String w) {
ArrayList k = new ArrayList();
ArrayList m = new ArrayList();
System.out.println(w.length());
int j = 0;
//test arraylist to check if string is written into arraylist
for (int i = 0; i < w.length(); i++){
k.add(w.charAt(i));
}
String p = k.get(2).toString();
System.out.println(p);
//here starts the logic of my app
for (int n = 0; n < w.length(); n++){
String v = k.get(n).toString();
if (n == 0){
m.add(1, v);
}
else if (n == 1){
m.add(0, v);
}
else if ((n % 2) == 0){
m.add(n+1, v);
}
else {
m.add(n, v);
}
}
}
public static void main(String[] args){
s = "tests";
proc(s);
}
Hi this is not a homework, but am doing exercises from a book. Anyway using code provided by Jon managed to work on my own - it may be not as much elegant but is doing the job using dynamic sizing as well:
public static void proc(String w) {
ArrayList k = new ArrayList();
ArrayList g = new ArrayList();
String h = "";
for (int i = 0; i < w.length(); i++){
char temp = w.charAt(i);
k.add(i, temp);
}
for (int i = 0; i < w.length(); i++){
if (i == 0){
h = k.get(1).toString();
g.add(h);
}
else if (i == 1){
h = k.get(0).toString();
g.add(h);
}
else if ((i % 2) == 0){
h = k.get(i+1).toString();
g.add(h);
}
else if ((i % 2) == 1){
h = k.get(i-1).toString();
g.add(h);
}
}
System.out.println(g.toString());
}
public static void main(String[] args){
s = "test";
proc(s);
}
I haven't tried to go through exactly how your code is trying to work, but it looks unnecessarily complicated to me. Given that you don't need dynamic sizing, you can do this more easily with an array:
public static String swapPairs(String input) {
char[] chars = input.toCharArray();
for (int i = 0; i < chars.length - 1; i += 2) {
char tmp = chars[i];
chars[i] = chars[i + 1];
chars[i + 1] = tmp;
}
return new String(chars);
}
Note that while this will work for "simple" characters (where each element of the array is independent of the rest), it doesn't try to take any form of "composite" characters into consideration, such as characters formed from two UTF-16 code units (surrogate pairs) or combined characters such as "e + acute accent". Doing this sort of contextually-aware swapping would take a lot more effort.
This looks like homework, so I'll limit my answer to a couple of hints.
I would accumulate the result in a StringBuilder (called sb in what follows).
I would have a loop (for i = 0; i < w.length(); i += 2). In this loop I would do two things:
if i + 1 is within the bounds of the string, I'd append the i + 1-th character to sb;
append the i-th character to sb.
At the end, call sb.toString().

Categories