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 8 years ago.
Improve this question
I've been trying to generate this output :
aaa aaa aab aOa baa aaa aab c
given this sequence:
aaaab aOa baaab c
I'm really new to JAVA and I can't form the other sequences, just
aaa aaa aab
I've been trying for a month so that's why I'm asking here, can someone help me please?
Here is my code:
public void generateSequence(String text, int n)
{
text ="aaaab aOa baaab c";
n=3; //i.e
String[] words = text.split(" ");
StringBuilder newGram = new StringBuilder();
int p1 = 0;
int p2 = n;
String seq = "";
int seqLength = seq.length();
while (p1 < p2 && p2 <= seqLength) {
newGram = newGram.append(seq.substring(p1, p2) + " ");
p1++;
p2++;
if (p2 == seqLength) {
System.out.println("End of 1st element");
//Skip to the next elements in array and form sequences....
}
}
System.out.println(newGram);
}
This works for me.
public static void main(final String[] args) {
final String input = "aaaab aOa baaab c";
final String[] sections = input.split(" ");
final int length = 3;
final List<String> list = new ArrayList<>();
for (final String section : sections) {
for (int i = 0; i < section.length(); i++) {
if (section.length() < length) {
list.add(section);
continue;
}
final int end = i + length;
if (end > section.length()) {
break;
}
final String result = section.substring(i, end);
list.add(result);
}
}
list.stream().forEach(s -> System.out.println(s));
}
Ok user put some text now n is the number of subsequences generated from the text, as you may know text are words and i save them into words array.
now if u say pilot for n = 3
resulting array would be pil ilo lot
for n = 2
resulting array would be pi il lo ot
and so on
for example text = Java Rocks!
for n = 3
Jav ava Roc ock cks!
i want to generate n-gram according to some text as input and n for generating subsequences, could you put some code? thanks a lot.
Related
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 20 days ago.
Improve this question
My task is to find number of occurrences of a string character and replace the character with the number of occurrence up to that particular index inside the string
public static void main(String[] args) {
char[] arr = "hello".toCharArray();
arr[2] = '1';
arr[3] = '2';
System.out.println(arr);
}
Output should be: he12o
I know we cant reuse this approach.
what is the output of "helololol"?
output for helololol, ch='l' , then the output should be he1o2o3o4; if ch='o' then output should be hel1l2l3l
If according to this rule, Can be achieved with a loop:
public static void main(String[] args) {
char flag = 'l';
String str = "hellollololollol";
int num = 1;
for(int i = 0, len = str.length(); i < len; i++) {
if (str.charAt(i) == flag) {
str = str.substring(0, i) + num++ + str.substring(i + 1);
}
}
System.out.println(str);
}
Note that if the number of specified characters exceeds 9, it will look weird, If the number of characters exceeds 9, special processing is required:
public static void main(String[] args) {
char flag = 'l';
String str = "hellollololollollol";
int num = 1;
for(int i = 0, len = str.length(); i < len; i++) {
if (str.charAt(i) == flag) {
str = str.substring(0, i) + num++ + str.substring(i + 1);
if (num > 10) {
len++;
}
}
System.out.println(str);
}
}
The same problem, if the number of characters exceeds 100, 1000, 10000, special processing is required, because the length of the number added to the string is one bit longer than the original character, how to deal with it flexibly, you need to think about it yourself!
Instead of using primitive methods to manipulate string , we can use the following to have clean code .
public static void main(String args[]) {
String str="helolololololololololololololololololololololololololololololololololololo";
String checkString="l";
int count=1;
StringBuilder sb=new StringBuilder();
List<String> strLst= new ArrayList<String>();
for(int i=0;i<str.length();i++) {
strLst.add(String.valueOf(str.charAt(i)));
}
for(String x : strLst) {
if(x.equals(checkString)) {
sb.append(count);
count++;
}else {
sb.append(x);
}
}
System.out.println(sb);
}
The output for the above string will be
he1o2o3o4o5o6o7o8o9o10o11o12o13o14o15o16o17o18o19o20o21o22o23o24o25o26o27o28o29o30o31o32o33o34o35o36o
With this implementation , we don't have to worry about splitting the string using substring and checking their index .Will work for 'n' number of repetitive letters.
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
Input a string which contains some palindrome substrings. Find out the position of palindrome substrings if exist and replace it by *. (For example if input string is “bob has a radar plane” then it should convert in “** has a ***** plane”.
My code is given below.
import java.util.Scanner;
public class Pallindrome_String {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
String sen;
System.out.println("Enter the String: ");
sen = in.nextLine();
pallindrome(sen);
in.close();
}
public static void pallindrome(String s) {
int len = s.length();
for (int i = 0; i < len; i++) {
String res = "";
if (s.charAt(i) == ' ') {
res = s.substring(0, i);
String rev = "";
for (int j = res.length() - 1; j >= 0; j--) {
rev = rev + res.charAt(i);
}
if (rev.equals(res)) {
rev = "*";
System.out.print(rev + " ");
} else {
System.out.print(res + " ");
}
}
}
}
}
There is a simpler, more efficient way of finding palindromes in Java. I'll explain the steps to implementing it.
first, after getting your input 'sen', you can use the split method of the String class to seperate each word.
sen = in.nextLine();
String[] splitted = s.split(" "); // seperates the string when there is a whitespace and stores the resulting words in an array
After you've got the words in an array, you can check each word and see if its a palindrome. To do so, you can read the word front to back and back to front and compare the result.
If u find a palindrome, store its index (position in the 'splitted' array). After you've gone through all the words in the 'splitted' array, you can then print out the appropriate number of *'s based on the length of the word.
The split() will loose double spaces and punctuation in source string and make a lot of useless objects in memory. This is more correct solution. IMHO
public static void main(String[] args) {
String s = "Bob! Do you have a radar plane?";
StringBuilder sb = new StringBuilder(s);
Matcher m = Pattern.compile("[a-zA-Z]+").matcher(s);
while (m.find()) {
String word = m.group();
if (word.length() == 0)
continue;
String reversed = new StringBuffer(word).reverse().toString();
if (word.equalsIgnoreCase(reversed)) {
StringBuilder replacement = new StringBuilder();
for (int i = 0; i < word.length(); i++)
replacement.append('*');
sb.replace(m.start(), m.end(), replacement.toString());
}
}
System.out.println(sb);
}
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 3 years ago.
Improve this question
How can i seperate this String:
"thisisanexampleforthisproblemicantsolvetestes"
To this array:
{"thisi","sanex","ampl","efor","this","prob","lemi","cant","solv","etes","tes"}
I want to seperate the first 10 letters in the String into 2 elemnts in an array and the rest should be every 4 letters, to one elemnt in an array.
I hope you can help me. I tried this all day but still didnt solve it
Assuming your input string length >= 10 you can do something like below using streams:
String str = "thisisanexampleforthisproblemicantsolvetestes";
String[] splited = Stream.of(str.substring(0, 10).split("(?<=\\G.{5})"),
str.substring(10).split("(?<=\\G.{4})"))
.flatMap(e -> Arrays.stream(e))
.toArray(String[]::new);
System.out.println(Arrays.toString(splited));
where the regex "(?<=\\G.{n})" is used to split a string at each nth char
More simple to understand:
Results in: thisi, sanex, ampl, efor, this, prob, lemi, cant, solv, etes, tes
public static List<String> strangeThingsDo(String str)
{
List<String> li = new ArrayList<>();
int len = str.length();
if (len <= 5)
{
li.add(str);
return li;
}
if (len <= 10)
{
li.add(str.substring(0,5));
li.add(str.substring(5));
return li;
}
li.add(str.substring(0,5));
li.add(str.substring(5,10));
String s,rest = str.substring(10);
int restlen = rest.length();
int end = 0;
for (int i = 0; i < restlen;i += 4)
{
end = i + 4;
if (end > restlen)
{ s = rest.substring(i);
li.add(s);
break;
}
s = rest.substring(i,end);
li.add(s);
}
System.out.println("---: " + li );
return li;
}
The following code will show you how to split a string by numbers of characters. We create a method called splitToNChars() that takes two arguments. The first arguments is the string to be split and the second arguments is the split size.
This splitToNChars() method will split the string in a for loop. First we’ll create a List object that will store parts of the split string. Next we do a loop and get the substring for the defined size from the text and store it into the List. After the entire string is read we convert the List object into an array of String by using the List‘s toArray() method.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SplitStringForEveryNChar {
public static void main(String[] args) {
String text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(Arrays.toString(splitToNChar(text, 3)));
System.out.println(Arrays.toString(splitToNChar(text, 4)));
System.out.println(Arrays.toString(splitToNChar(text, 5)));
}
private static String[] splitToNChar(String text, int size) {
List<String> parts = new ArrayList<>();
int length = text.length();
for (int i = 0; i < length; i += size) {
parts.add(text.substring(i, Math.min(length, i + size)));
}
return parts.toArray(new String[0]);
}
}
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
can you give me some pointers as of how can I find the most frequent word in an String? I cannot use Maps, lists or so on. I should only achieve this by for's and if's and some in-build methods.
Split String and save to array, sort the array, iterate over the sorted array and count frequency of same strings updating the maximal count. Example:
public static void main(String[] args) {
String myStr = "how can I find the most frequent word in an string how can I find how how how string";
String[] splited = myStr.split(" ");
Arrays.sort(splited);
System.out.println(Arrays.toString(splited));
int max = 0;
int count= 1;
String word = splited[0];
String curr = splited[0];
for(int i = 1; i<splited.length; i++){
if(splited[i].equals(curr)){
count++;
}
else{
count =1;
curr = splited[i];
}
if(max<count){
max = count;
word = splited[i];
}
}
System.out.println(max + " x " + word);
}
Sample idea (there are thousand ways to solve this):
1: A B B C B (< String with words, seperated by blanks)
'A' is your start position
2: count the A (1) and save the pos of A (0). You always iterate from pos until the end of the String.
3: continue counting until you iterated over the entire String. When you reached the end of the String save the count by assigning it to another variable (e.g. oldCount).
4: move on to the next word and start counting B's (new position = 1). You are about to count 3 B's. If newer count > older count replace the older count.
5: count the next word and update the position to your current position, which is 3. (which is the last position of the String).
6: you are not gonna update the counter, B is the most used word in the String.
For the purists - just loops and String.
private String mostFrequentWord(String words) {
// Where my current word starts.
int wordStart = 0;
// How many I counted.
int wordCount = 0;
// The currently most frequent.
String word = "";
for (int wordEnd = wordStart; wordEnd < words.length(); wordEnd++) {
// Is this the end of a word?
if (wordEnd > words.length() || words.charAt(wordEnd) == ' ') {
// We have a word! How many times does it occur?
String thisWord = words.substring(wordStart, wordEnd);
// How many times this word occurs.
int thisWordCount = 0;
// Current start of search.
int search = -1;
// Count them.
while ((search = words.indexOf(thisWord, search + 1)) >= 0) {
thisWordCount += 1;
}
// Is it longer?
if (thisWordCount > wordCount) {
// Keep track.
word = thisWord;
wordCount = thisWordCount;
}
// Move start to the next word.
wordStart = wordEnd + 1;
}
}
return word;
}
private void test() {
String words = "Now is the time for all good men to come to the aid of the party";
System.out.println("Most frequent word in \"" + words + "\" is " + mostFrequentWord(words));
}
public static void main(String...strings) {
String para = "Paris in the the spring.Not that that is related.Why are you laughing? Are my my regular expressions THAT bad??";
String[] words = para.split("\\s+");
int finalCount = 0;
int tempCount = 0;
String mostlyUsedWord = null;
for (String word: words) {
tempCount = 0;
for (String w: words) {
if (word.equalsIgnoreCase(w)) {
tempCount++;
}
}
if (tempCount >= finalCount) {
finalCount = tempCount;
mostlyUsedWord = word;
}
}
System.out.println("mostlyUsedWord:: = " + mostlyUsedWord + " ,count:: = " + finalCount);
}
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 1 year ago.
Improve this question
I am trying to compute all possible permutations of a given string using recursion in Java. However, I don't know what's wrong with my code.
Here's my algorithm:
public static ArrayList<String> computeAllPossiblePermutations(String str) {
ArrayList<String> perms = new ArrayList<>();
//base case
if (str.length() == 1)
perms.add(str);
else {
//loop over the string
for (int i = 0; i < str.length() - 1; i++) {
//make a subset of the string excluding the first char
String sub = str.substring(i + 1, str.length());
//compute permutations of the subset
ArrayList<String> subPerms = computeAllPossiblePermutations(sub);
//add the first char that we excluded at the start of each permutations
for (String s : subPerms) {
s = str.charAt(i) + s;
perms.add(s);
}
}
}
return perms;
}
There are a few issues:
The following line: String sub = str.substring(i+1, str.length()); ignores the first character
The same line also treats anything after index i as a "block" of substring that is left unchanged, while in order to generate permutation we should insert the current (first) character in between any two characters of the rest of the string - and do that for each permutation
The line s = str.charAt(i) + s; repeats the same mistake in #2
Here's a suggested fix:
public static ArrayList<String> computeAllPossiblePermutations(String str) {
ArrayList<String> perms = new ArrayList<>();
if (str.length() == 1) {
perms.add(str);
} else {
String chr = str.substring(0,1);
String rest = str.substring(1);
ArrayList<String> subPerms = computeAllPossiblePermutations(rest);
for (String s : subPerms) {
for (int j = 0; j <= s.length(); j++) {
String newPerm = s.substring(0,j) + chr + s.substring(j);
perms.add(newPerm);
}
}
}
return perms;
}