Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
We will be given a string s. Suppose for example "creepfe". What we want to do is to remove duplicate and instead add a new letter in that place and new letter must be distinct letter available next to the duplicate letter in alphabetical order. So it goes like this :
creepfe to crefpfe -- first e is distinct and second e is changed to f which is distinct upto that.
crefpfe to crefpge -- second f is changed to g since we already have f before.
crefpge to crefpgf -- since e is already present.
Now again we got f duplicate , so change it to crefpgg , which again got g duplicate so finally we reach "crefpgh" which has all distinct letters.
Started learning java recently and a working code is appreciated ,BUT a good algorithm is what really needed.
Edit : yes capitals do count as duplicates as well. And string length is limited to 10-15 so no worry about running out of distinct letter.
Here's a solution. I m using recursion to left shift the letters if there are duplicates. I also went back and redid my code to include sets as mentioned by MBo. Its not the most efficient, but its a start while you wait for advice from more experienced members of SO
public class tester {
public static void main(String[] args){
//Application.launch(testclass.class, args);
String str = "creepFeZZ";
System.out.println(processStr(str));
}
public static String processStr(String str){
StringBuilder sb = new StringBuilder();
HashSet<String> seen = new HashSet<>();
insertStr(sb, seen, String.valueOf(str.charAt(0)));
for (int i=1; i<str.length(); i++){
char currentchar = str.charAt(i);
char processedchar = goNext(seen, currentchar);
insertStr(sb, seen, String.valueOf(processedchar));
}
//System.out.println(seen.toString());
return sb.toString();
}
private static void insertStr(StringBuilder sb, HashSet seen, String str){
seen.add(str.toLowerCase());
sb.append(str);
}
private static char goNext(HashSet seen, char c){
if (c>= 65 && c<=90){
//if uppercase letter, check if contains lowercase version
if (seen.contains(String.valueOf((char)(c+32)))){
c = goNext(seen, (char)(c+1));
}
//any left shifting will overflow back to A
return (char) ((c -(int) 'A') % 26 +(int) 'A');
}else{
//if lowercase letter, just check if contains
if (seen.contains(String.valueOf((char)(c)))){
c = goNext(seen, (char)(c+1));
}
//any left shifting will overflow back to a
return (char)((c-(int) 'a') % 26 +(int) 'a');
}
}
}
This gives output of:
crefpGhZA
Find the position where the string contains a duplicate. There are various methods to this. You can Google to find the most efficient one that fits your approach.
Generate the next character in alphabetical order. The following code shows how this can be done
String value = "C";
int charValue = value.charAt(0);
String next = String.valueOf( (char) (charValue + 1));
System.out.println(next);
Repeat the process until there are no more duplicates (have a while loop which breaks when there are no more duplicates)
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I should write a encoding and decoding program in a class and then use it in main. The program needs the position for each letter to increase by 2.
When I run the program, the problem is that when I enter a string (like cookie), only the last letter is encoding. Here is a Screenshot of program running.
What is the problem for my program.
Thanks.
The lesson is very basic tho and the assignment are forbid students import any other java method like base64.Only use the starter code.
The code I will put here as well
public class SimpleCipher {
/*
* comments here to overview the method
*/
public String encode(String text) {
String result = "";
char[] chars = text.toCharArray();
int length = chars.length;
for (char x: chars) {
x+=2;
result = Character.toString(x);
}
// ToDo
// convert text into char array
// reverse the array using provided method (see below)
// loop over array adding 2 to each element
// convert the char array back to a String named result
// return the resulting String.
return result;
}
The main problem is that you are overwriting your result in each iteration.
Instead you want to append the character to the result string.
You can simply do that with
result = result + Character.toString(x);
result += Character.toString(x); // shorter version
result += x; // java can append characters to strings without explicit conversion
According to the comment that is - even tho it is working - not the desired solution anyways. The task is to create a new character array and fill it.
Do that by creating a new array of the same length as the original, iterating over the indexes of your arrays ( for (int i=0; i<chars.length; i++) ) and for each index write the updated character into the new array. The string class has a constructor that accepts a char array.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Very new java student here (My first post, sorry for wrong formatting). I need help with rephrasing a paragraph.
I need to change the letters of the paragraph to the 13th next letter ie changing a to n and so on meanwhile conserving the structure of the paragraph ie line breaks, full stops, etc...I have only been able to change a word so far and need to expand this code to be able to do it with a paragraph...Thanks in advance...Much appreciated...
public class Assignment1b {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Please type any word: ");
String word = s.nextLine();
String ROT13 = "";
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
int value = c - 'a' + 1;
value = value + 13;
char ency = (char)((value % 26) + 'a' - 1);
ROT13 = ROT13 + ency;
}
System.out.println("The encrypted word is: " + ROT13);
}
}
General good programming practice: one method does one thing, and one thing only. This makes code easier to read, test, maintain and reuse. I suggest you start by taking the stuff in your for () loop and sticking it in a new method. Call it private char encryptCharacter(char oldCharacter), or some such. Add the return value to your ROT13 string to build the answer, as you are currently doing.
Your problem is now in this secondary module - how to preserve line breaks, spaces and similar characters. Refer to Charlie Armstrong's comment, that will help you identify them. You will probably end up with something like:
private char encryptCharacter(char oldCharacter) {
if (isWhiteSpaceOrPunctuation(oldCharacter)) {
return oldCharacter;
} else {
// add your code to encrypt the character here
return encryptedCharacter;
}
}
private boolean isWhiteSpaceOrPunctuation(char character) {
// return true or false, as appropriate
}
First you need to split paragraph by words, using method split of String class and passing the char, that splits words, in this case, the space " ". This method return array of String (String[]), which means, array of words, but I convert it to List<String> using Arrays.asList() method, to facilitate the process. Next, I iterate this list, and apply the rephrase method, that encript or change each word.
// this split your paragraph, and invoke your code, which means, rephrase method by word
public static String encript(String paragraph){
// split words by spaces, but punctuation still
List<String> words = Arrays.asList(paragraph.split(" ").clone());
StringBuilder sb = new StringBuilder();
for(String word : words) {
// rephrase and append
sb.append(rephrase(word));
}
return sb.toString();
}
// this is your code in a method, I recommend you rebuild this method using StringBuilder, it is more efficient
public static String rephrase(String word){
String ROT13 = "";
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
int value = c - 'a' + 1;
value = value + 13;
char ency = (char)((value % 26) + 'a' - 1);
ROT13 = ROT13 + ency;
}
return ROT13;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Basically, I am getting ready for an interview and following a regime that gives me a bunch of challenges that are often thrown in interviews.
This particular challenge's goal is to count the number of words that appear more than once in a sentence excluding punctuations. I did it but it took me at least 5 minutes to come up with it and code it.
I'm not sure if taking 5 minutes is acceptable to code something like this in java interviews so I would like to see something simpler with maybe less code. Below is how I solved it.
System.out.println("Part 6 challenge-------------------------------------------------------------------------");
String sentence3 = "She's the queen and likes, apples APPLES, bananas BANANAS Bananas, and oranges ORANGE."; //original string
StringBuilder sb3 = new StringBuilder(); //declared string builder to build new string without punctuations
char [] punctuations = {'.',',',':','?','!',';'};//Char array containing punctuations to lookout for
for (int i=0; i<sentence3.length(); i++){
boolean p = false; //declared boolean within loop to turn on if punctuation was found in the original string
for (Character c: punctuations){
if (sentence3.charAt(i) == c){
p = true;// turn on
}
} if(!p){
sb3.append(sentence3.charAt(i));//if no punctuations found, add it to the string builder to build new string
}
}
String word[] = sb3.toString().split(" ");
Set<String> uniqueWords = new HashSet<>();
int count = 0;
for (String s: word) {
uniqueWords.add(s.toLowerCase());
}
for (String s: uniqueWords){
for (String w: word){
if (s.equals(w.toLowerCase())){
count++;
}
}
System.out.println(String.format("Found %s %d times", s, count));
count =0;
}
A shorter way, outlined:
Split by regexp;
Filter for words (may be not needed depending on your regexp);
Replace Set<String> with a Map<String, Integer> and count word quantities in linear time;
Filter out and output words with count > 1.
BTW this can all be one stream expression if you're into minimal statement count.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a string that contains a lot of text. There's some weird characters in it like the following: █ ✖ ✔ ♫ ♬ ▬ ★
This is just a small portion of what I have found so far. I tried using the replaceAll method but it doesn't seem to work. Is there a collection of all these types of characters somewhere, or even better yet, a library that is able to remove them?
Iterate over characters and check each whether it belongs to some category you define as "standard" (here such categories are: alphabetic, digit, whitespace, or modifier applied to previously accepted character):
static String standartize(String s) {
if (s == null) return null;
StringBuilder sb = new StringBuilder();
boolean based = false; // is previous character accepted base for modifier?
int c;
for (int i = 0; i < s.length(); i += Character.charCount(c)) {
c = Character.codePointAt(s, i);
if (based && Character.getType(c) == Character.MODIFIER_SYMBOL) {
sb.appendCodePoint(c);
} else if (Character.isAlphabetic(c) || Character.isDigit(c)) {
sb.appendCodePoint(c);
based = true;
} else if (Character.isWhitespace(c)) {
sb.appendCodePoint(c);
based = false;
} else {
based = false;
}
}
return sb.toString();
}
You can add/remove checks in else if to widen/narrow range of characters you consider "standard": Character has many static isXxxx() methods to test if a character belongs to some category.
Please notice that iterated are not char items, but int codepoints. This is made to process not only UTF-16 chars, but surrogate pairs as well.
If you want only ASCII Characters in your string, you can loop through the length of the string and check wether ASCII value is between 65 - 90(A-Z) or 97 - 122(a-z) or 48-57(0 - 9)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Hey so for practice I found this coding challenge which I have now been working on for a few days. I have the first part, but I just can't seem to figure out how to continue from where I am. Here is the challenge:
Consider a "word" as any sequence of capital letters A-Z (not limited to
just "dictionary words"). For any word with at least two different letters,
there are other words composed of the same letters but in a different order (for
instance, STATIONARILY/ANTIROYALIST, which happen to both be dictionary words;
for our purposes "AAIILNORSTTY" is also a "word" composed of the same letters as
these two).
We can then assign a number to every word, based on where it falls in an
alphabetically sorted list of all words made up of the same set of letters. One
way to do this would be to generate the entire list of words and find the
desired one, but this would be slow if the word is long.
Write a program which takes a word as a command line argument and prints to
standard output its number. Do not use the method above of generating the entire
list. Your program should be able to accept any word 20 letters or less in
length (possibly with some letters repeated), and should use no more than 1 GB
of memory and take no more than 500 milliseconds to run. Any answer we check
will fit in a 64-bit integer.
Sample words, with their rank:
ABAB = 2
AAAB = 1
BAAA = 4
QUESTION = 24572
BOOKKEEPER = 10743
NONINTUITIVENESS = 8222334634
Your program will be judged on how fast it runs and how clearly the code is
written. We will be running your program as well as reading the source code, so
anything you can do to make this process easier would be appreciated.
So far, the code I have can return the correct answer if all of the letters are different. Here is my code:
import java.util.Arrays;
import java.util.Scanner;
public class AthenaDility {
public static void main (String[] args) {
//Finds word that is entered
Scanner scan = new Scanner (System.in);
String word = scan.next();
scan.close();
//added value
int value = 1;
//alphabetical representation
char[] charm = word.toCharArray();
char[] alphaCharm = word.toCharArray();
Arrays.sort(alphaCharm);
//Comparer
for (int m = 0; m < word.length(); m++) {
for (int c = 0; c < word.length()-1; c++) {
System.out.println(charm[m] + " " + alphaCharm[c]);
//Skips if alphaCharm is a space
if (alphaCharm[c] == '-') {
}
//If the same letter it breaks look and begins next
else if (charm[m] == alphaCharm[c]) {
System.out.println("Deleting: " + alphaCharm[c]);
alphaCharm[c] = '-'; //Delete letter for it is used and cannot be used to compare at later points
break;
}
//if the letter in alphaCharm comes before charm
else if (charm[m] > alphaCharm[c]){
System.out.println("Found!");
//factorial calculation
int factorial = 1;
//takes the length of the word minus the current location and one after for factorial
for (int f = word.length() - m - 1; f > 0; f--) {
System.out.print(f + " ");
factorial *= f;
}
//end loop
//Adding to others
System.out.println("\n" + "Factorial: " + factorial);
value += factorial;
}
else {
}
}
}
//Result
System.out.println("end: " + value);
}
}
To try and explain it as simply as I can, it creates two strings: one is the letters in alphabetical order and one is the original word. The program then compares each letter at a time and any letter that comes before the one in the original word alphabetically causes a factorial calculation for the number of combinations that would exist before the first word.
The part I need help factoring in is if the strings entered have more than one of the same letter. I have literally spent DAYS trying to figure this out. Thank you in advance!
p.s. the code has a lot of System.out.println for testing sake