I've been trying to use nested for loops to repeat the word, "hedgehog" with three letters up to 6 times only, however, it keeps going until it fully spells hedgehog.
public static String print3LetterSubstrings(String word) {
for (int len = 3; len <= word.length(); len++) {
for (int i = 0; i+len <= word.length(); i++) {
System.out.println(word.substring(i, i+len));
}
}
return word;
}
What I want is to have just 3 letters that just repeat 6 times.
hed
edg
dge
geh
eho
hog
If you always want three character substring(s) then len shouldn't change. You want to loop printing the substring from i to i + len. Like,
public static String print3LetterSubstrings(String word) {
int len = 3;
for (int i = 0; i + len <= word.length(); i++) {
System.out.println(word.substring(i, i + len));
}
return word;
}
Outputs when called as print3LetterSubstrings("hedgehog"); (as requested)
hed
edg
dge
geh
eho
hog
Related
I got this problem in my programming competency test. I need to find the exponent of a string.
For Eg :
Input Str = "pctpctpct", output : pct 3.
Input str : "pressure", output 0. Because pressure is not repeating as a string.
That is the string pct is repeated 3 times.
I need to create a method for this. I tried everything but failed.
My method was :
public static int findExponent(String str) {
int count = 0;
String subs = "";
ArrayList<String> al = new ArrayList<String>();
for (int i = 0; i < str.length() / 2; i++) {
for (int j = i + 1; j <= str.length() / 2; j++) {
subs = str.substring(i, j);
al.add(subs);
System.out.println(al);
for (String x : al)
for (int k = 0; k < str.length(); k++) {
if (str.contains(x)) {
count++;
}
}
}
}
return count;
}
Here I was checking if any substring matches the pattern of the String. But it is not giving me the correct output. What changes should I need to do in this?
How to check the pattern for such a type of question where we have to create a pattern and check if it's repeated?
How about this. I would go ahead with the algorithm based on java:-
Lets assume the input is the string
convert it to character sequence (array of char)
Sort the array into a temp array
loop from 0 to array length
count the ith letter repetition
if its 0
return 0;
else
if count for all word matches
return count;
complexity is 0(n) and this code would work
Not sure how to set up this method which gets as parameter a String array and has to return in a new array all values that meet the following condition:
25% of characters in every element of array are numbers;
public static String[] returnSentence(String[] str){
int nrOfWords = str.length;
int count = 0;
for(int i = 0; i < nrOfWords; i++){
for(int j = 0; j < str[i].length; j++){
}
}
}
I had an idea that it should be something like this but cant format the code to test the condition...
Your question basically boils down to figuring out how many characters in the String fullfil a given condition, and how many do not.
There is two ways to do this:
1) Simply count the characters:
int numPositiveChars = 0;
int numNegativeChars = 0;
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if (/*check c here*/)
numPositiveChars++;
else
numNegativeChars++;
}
In fact you don't even need to count the negative chars, because that value is simply s.length() - numPositiveChars.
2) Another approach would be to use regular expressions, e.g. by removing all non-numerical characters and then get the character count:
int numPositiveChars = s.replaceAll("[^0-9]+", "").length();
This line will remove all characters from the String that are not numerical (not 0-9) and then return the length of the result (the number of characters that are numerical).
Once you have the number of chars that match your condition, calculating the percentage is trivial.
You need to just replace all non digits in each element and then compare the length like so :
public static List<String> returnSentence(String[] str) {
int nrOfWords = str.length;
List<String> result = new ArrayList<>();
for (int i = 0; i < nrOfWords; i++) {
if(str[i].replaceAll("\\D", "").length() == str[i].length() * 0.25){
result.add(str[i]);
}
}
return result; // If you want an array use : return result.toArray(String[]::new);
}
I would also use as result a List instead of array because you don't have any idea how many element is respect the condition.
If you want to solve with streaming it can be more easier :
public static String[] returnSentence(String[] str) {
return Arrays.stream(str)
.filter(s-> s.replaceAll("\\D", "").length() == s.length() * 0.25)
.toArray(String[]::new);
}
some thing like this
public static String[] returnSentence(String[] str){
int nrOfWords= str.length;
String[] temp_Str = new String[20];
int count = 0;
int k=0;
for(int i = 0;i<nrOfWords;i++){
for(int j = 0;j<str[i].length;j++){
if(Character.isAlphabetic(str[i].getcharat(j)))
{
count++;
}
if((count/100.0)*100>=25)
{ temp_Str[k]=str[i];
k++;
}
}
}
}
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
Here's the basics of the assignment:
Your task is to write a program that decodes a sequence of characters which was encoded using a simple form of run-length encoding, as described by the rules below.
Any sequence of between 2 to 9 identical characters is encoded by two characters. The first character is the length of the sequence, represented by one of the characters 2 through 9. The second character is the value of the repeated character. A sequence of more than 9 identical characters is dealt with by first encoding 9 characters, then the remaining ones.
Any sequence of characters that does not contain consecutive repetitions of any characters is represented by a 1 character followed by the sequence of characters, terminated with another 1. If a 1 appears as part of the sequence, it is escaped with a 1, thus two 1 characters are output.
Example Input and Output:
Input:
9A1ABC131
1112 3124
111111
Output:
AAAAAAAAAABC111
12 344
11
My code that I have so far but doesn't quite work:
import java.util.Scanner;
public class RunLength {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String test = kb.nextLine();
System.out.println(decode(test));
}
public static String encode(String s) {
if (s == "" || s == null) return "";
StringBuffer sb = new StringBuffer();
int count = 0;
char ch = 0;
for (int i = 0; i < s.length(); i++) {
if (i == 0) {
ch = s.charAt(i);
count++;
} else {
if (ch == s.charAt(i)) {
count++;
} else {
sb.append(ch).append(count);
count = 1; // count is set to 1 as 1 occurrence of ch has been appended to the output
ch = s.charAt(i);
}
}
}
sb.append(ch).append(count);
return sb.toString();
}
public static String decode(String st) {
if (st == "" || st == null) return "";
char[] stArr = st.toCharArray();
char lastseen = 0;
StringBuffer sb = new StringBuffer();
for (char s : stArr) {
if (!Character.isDigit(s)) {
lastseen = s;
sb.append(s);
} else {
int n = Integer.parseInt(String.valueOf(s));
for (int i = 0; i < n - 1; i++) {
sb.append(lastseen);
}
}
}
return sb.toString();
}
public static int[] decode2(String source) {
int arrLength = 0;
for (int i = 0; i < source.length(); i += 2) {
int count = Character.getNumericValue(source.charAt(i));
arrLength += count;
}
int array[] = new int[arrLength];
int k = 0;
for (int i = 0; i < source.length(); i += 2) {
int count = Character.getNumericValue(source.charAt(i));
for (int j = 0; j < count; j++) {
array[i + k] = Character.getNumericValue(source.charAt(i + 1));
}
}
return array;
}
}
I suggest you try to split your decode methods into two main logical parts:
One for the case that you are actually performing a RLE and the other for the case where you have a sequence of non-repeated characters, in which 1s have to be escaped.
The latter is easy to implement and your solution for that part seems to be correct.
The former needs you to loop over the next characters until the end of the sequence has been found.
If you read anything but a 1, just add it to the output.
In case there is a 1, you need to look ahead at the next character to see whether there is another 1, meaning there is an unrepeated 1 that had to be escaped, which is to be added to the output (consuming the lookahead, too). If the look ahead is not a 1 (including the special case where there is no next character) the unrepeated characters sequence ends here and nothing is to be added to the output.
Since this page is not supposed to solve your homework, I won't post a complete solution, though.
I am trying to print
a
bb
ccc
dddd
The code I have is not doing the pattern I would like and not sure where the issue is at. Any help would be great.
public static String generatRowOfSymbols(char letterOne, char letterTwo){
char i;
char j;
String letters = "";
String row = "";
for(i=letterOne; i<= letterTwo; i++ ){
for(j=letterOne; j<=i; j++){
row += i ;
}
letters += row + "\n";
}
return letters;
First, use a StringBuilder -- it's faster and more efficient. I didn't calculate the length, but if you want to, you can. Second, take a look at the changes I made to your method and let me know if it doesn't make sense. Please note that I'm using the System's line separator -- if you really want to append '\n', please do so.
As you should see, our first for-loop walks through the letters. The second, which is nested, prints out count letters, which increments by one each time that we change the letter.
public static String generatRowOfSymbols(char letterOne, char letterTwo) {
StringBuilder letters = new StringBuilder();
int count = 1;
for (char i = letterOne; i <= letterTwo; i++, count++) {
StringBuilder row = new StringBuilder(count);
for (int j = 0; j < count; j++) {
row.append(i);
}
letters.append(row).append(System.lineSeparator());
}
return letters.toString();
}
Edit
Here's yours fixed using Strings instead of StringBuilder, since there is a hesitation to use StringBuilder.
public static String generatRowOfSymbols(char letterOne, char letterTwo) {
String letters = "";
int count = 1;
for (char i = letterOne; i <= letterTwo; i++, count++) {
String row = "";
for (int j = 0; j < count; j++) {
row +=i ;
}
letters += row + System.lineSeparator();
}
return letters;
}
public static String generatRowOfSymbols(char letterOne, char letterTwo){
char i;
char j;
String letters = "";
for(i=letterOne; i<= letterTwo; i++ ){
for(j=letterOne; j<=i; j++){
letters +=i;
}
letters+= "\n";
}
return letters;
The simplest solution that I can come up with is as follows. I used IntStream but you can easily change it to a for-loop; the logic is the same.
public static void printPattern(int rows) {
IntStream.range(0, rows).forEach(x -> {
IntStream.range(0, x + 1).forEach(y -> {
System.out.print((char) ('a' + x));
});
System.out.println();
});
}
Suppose, we use it as follows.
printPattern(10);
Output:
a
bb
ccc
dddd
eeeee
ffffff
ggggggg
hhhhhhhh
iiiiiiiii
jjjjjjjjjj