Scrambling strings multiple times in eclipse - java

I'm having some trouble with some code for a program I'm writing. The purpose of this program is to take a word from a separate text file, scramble it ten times, and display the scrambled letters of the word. The problem that I'm having is that I'm unsure as to how I would go about scrambling the letters ten times. I know that the actual scrambling takes place in my mixer method but the how eludes me. I thought about using a for loop but I'm not sure how to go about it.
import java.io.*;
import java.util.*;
public class Scrambler {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("words.txt"));
String text = input.next();
System.out.println("Original Word: " + text);
System.out.println();
System.out.println("Scrambled Word:");
System.out.println("********");
separate(text);
System.out.println("********");
}
public static void separate(String text) {
System.out
.println(" " + text.charAt(0) + " " + text.charAt(1) + " ");
System.out.println(text.charAt(2) + " " + text.charAt(3));
System.out
.println(" " + text.charAt(4) + " " + text.charAt(5) + " ");
}
public static String mixer(String text) {
Random r = new Random();
int r1 = r.nextInt(text.length());
int r2 = r.nextInt(text.length());
String a = text.substring(0, r1);
char b = text.charAt(r1);
String c = text.substring(r1 + 1, r2);
char d = text.charAt(r2);
String e = text.substring(r2 + 1, text.length());
text = a + b + c + d + e;
return text;
}
}

Your mixer() is not working properly. I would first make the string into an char[], and then retrieve 2 random indices and switch the characters in these indices.
char[] stringasarray = text.toCharArray();
int length = text.length;
for(int i=0; i<length; i++){
int letter1 = rnd.nextInt(length);
int letter2 = rnd.nextInt(length);
char temp = stringasarray[letter1];
stringasarray[letter1] = stringasarray[letter2];
stringasarray[letter2] = temp;
}
String newtext = new String(stringasarray);

A simple for loop would do it:
String word = "Hello World";
for(int i = 0; i < 10; i++){
word = mixer(word);
}

Here is one approach for scrambling the string(s) ten times;
// Passing in the Random.
public static String mixer(String in, Random rnd) {
StringBuilder sb = new StringBuilder();
if (in != null) { // <-- check for null.
List<Character> chars = new ArrayList<Character>();
for (char ch : in.toCharArray()) {
chars.add(ch); // <-- add each character to the List.
}
Collections.shuffle(chars, rnd); // <-- "scramble"
for (char ch : chars) {
sb.append(ch);
}
}
return sb.toString();
}
public static void main(String[] args) {
String t = "Hello";
Random rnd = new Random();
// I'm not sure why you want to do it 10 times, but here is one way.
for (int i =0; i < 10; i++) {
t = mixer(t, rnd); // <-- call mixer function.
}
System.out.println(t);
}

public static String mixer(String text) {
Random r = new Random();
int r1 = r.nextInt(text.length()); // generates a random number from 0 to text.length - 1
int r2 = r.nextInt(text.length()); //generates a random number from 0 to text.length - 1
String a = text.substring(0, r1); // creates a substring containing characters from 0 to r1
char b = text.charAt(r1); //grabs the character at r1
String c = text.substring(r1 + 1, r2); // creates a substring from r1+1 to r2
char d = text.charAt(r2); // grabs the character at r2
String e = text.substring(r2 + 1, text.length()); // grabs any remaining characters
text = a + b + c + d + e; // recombines them
return text;
}
without delving into how substring works, this would most likely return the exact same string. If you changed the order of a + b + c + d + e it would scramble it. It takes the word and divides it into five pieces, then reassembles it.
It could probably use a lot of error checking, however, and some validation.

Related

How to sort a array that contains special characters alphabetically?

I am looking for code that produces the following output in standard output from the following string prepared according to a certain format.
Assumptions and rules:
Each letter is used 2 times in the given string and the letters between the same 2 letters are to be considered child letters.
The given string is always given in proper format. The string format
does not need to be checked.
Example:
Input : abccbdeeda
Expected output:
a
--b
----c
--d
----e
Explanation: since the 2 letters "b" occur between the letters "a", the letter b takes 2 hyphens (--b)
Attempt
public static void main(String[] args) {
String input = "abccbdeeda";
System.out.println("input: " + input);
String[] strSplit = input.split("");
String g = "";
String h = "-";
ArrayList<String> list = new ArrayList<String>();
int counter = 1;
boolean secondNumber;
list.add(strSplit[0]);
int dual = 0;
for (int i = 1; i < strSplit.length; i++) {
secondNumber = list.contains(strSplit[i]);
if ((secondNumber)) {
counter--;
dual = counter * 2;
for (int f = 0; f < dual; f++) {
strSplit[i] = h.concat(strSplit[i]);
}
g = "";
dual = 0;
} else {
list.add(strSplit[i]);
counter++;
}
}
Arrays.sort(strSplit);
for (int p = 0; p < strSplit.length; p++) {
System.out.println(strSplit[p]);
}
}
input: abccbdeeda
My output:
----c
----e
--b
--d
a
I wasn't able to sort the output alphabetically. How can I sort alphabetically with those hyphen characters in them?
This task is nicely done with the help of a stack. If the current character is equal to the top of the stack, then the character is closed and can be removed, otherwise we met it for the first time and it must be added to the stack and the resulting string by adding before it stack.size() * 2 dashes.
When we have completely traversed the string we can sort the resulting string.
public static void main(String[] args) {
Stack<Character> stack = new Stack<>();
String string = "abccbdeeda";
StringBuilder result = new StringBuilder();
for(int i = 0; i < string.length(); i++) {
char curChar = string.charAt(i);
if(!stack.isEmpty() && curChar == stack.peek()) {
stack.pop();
} else {
result.append("-".repeat(stack.size() * 2)).append(curChar).append(" ");
stack.add(curChar);
}
}
System.out.println(result);
System.out.println(Arrays.toString(Arrays.stream(result.toString().split(" ")).sorted().toArray()));
}
Output
a --b ----c --d ----e
[----c, ----e, --b, --d, a]
You can go through the strSplit array and extract the charactors in each element to a separate list/array. To check whether the array element contains a letter you can write a regular expression.
Ex: private final Pattern x = Pattern.compile("[a-z]");
Write a separate method to match the patern to each element in the strSplit array. This method will return the charactor in your input string.
private String findCharactor(final StringBuilder element) {
final Matcher matcher = x.matcher(element);
if (matcher.find()) {
final int matchIndex = matcher.start(); //this gives the index of the char in the string
return element.substring(matchIndex);
}
}
Add these returned charactors to a separate array and sort it using sorting function.
Suppose your result list is:
List<String> resultList = Arrays.asList("----c", "----e", "--b", "--d", "a");
You can sort it alphabetically by a single line:
Collections.sort(resultList, (o1, o2) -> new StringBuilder(o1).reverse().toString().compareTo(new StringBuilder(o2).reverse().toString()));
You can use recursion for a depth-first traversal (preorder):
public static String dfs(String string, String prefix) {
if (string.length() == 0) return "";
int i = string.indexOf(string.charAt(0), 1);
return prefix + string.charAt(0) + "\n" // current
+ dfs(string.substring(1, i), prefix + "--") // all nested
+ dfs(string.substring(i + 1), prefix); // all siblings
}
Example call:
public static void main(String[] args) {
System.out.println(dfs("abccbdeeda", ""));
}

in function "isDigit" java.lang.ArrayIndexOutOfBoundsException: 5

I need to write encryptor.
The first letter needs to be converted to its ASCII code.
The second letter needs to be switched with the last letter
It should make from this "65 119esi 111dl 111lw 108dvei 105n 97n 111ka"
This "A wise old owl lived in an oak"
But when I check is char a digit i have an error.
public static void encryptThis(String text) {
String [] text_arr = text.split("\\s");
for(int i = 0; i < text_arr.length;i++){
String word = text_arr[i];
int length = word.length();
char [] char_word = new char [length];
char_word = word.toCharArray();
int k = 0;
length = char_word.length;
char [] numb = new char [length];
for (int j = 0;j < length; j++){
//In this place
if (Character.isDigit(char_word[i])){
numb[k] = char_word[i];
char_word[i] = ' ';
k++;
System.out.println(numb[k]);
}
}
int number = Integer.parseInt(numb.toString(),8);
String edit_char_word = char_word.toString();
String final_str = new StringBuffer(edit_char_word).reverse().toString().trim();
final_str = number + final_str;
text_arr[i] = final_str;
}
String fin_text = text_arr.toString();
return fin_text;
}
I wrote the encryptThis method from the beginning and tried to stay as simple to get readable code, here is
a full working example. As you did not mention what to do if a number is the first "letter" there is no
special handling for this - an "1" will be encrypted to (ascii) 49...
public class Main_So {
public static void main(String[] args) {
System.out.println("https://stackoverflow.com/questions/62460366/in-function-isdigit-java-lang-arrayindexoutofboundsexception-5");
String input = "A wise old owl lived in an oak";
String outputExpected = "65 119esi 111dl 111lw 108dvei 105n 97n 111ka";
System.out.println("input: " + input);
String output = encryptThis(input);
System.out.println("output encryptThis: " + output);
System.out.println("output expected: " + outputExpected);
}
public static String encryptThis(String text) {
String[] text_arr = text.split("\\s");
String outputString = "";
for (int i = 0; i < text_arr.length; i++) {
String word = text_arr[i];
int length = word.length();
int ascii0 = (int) word.charAt(0);
String word0 = String.valueOf(ascii0); // first char as ascii code
String subString = word.substring(1);
if (length > 2) { // switch chars if string length > 2
char char1 = word.charAt(1);
char charEnd = word.charAt(length - 1);
StringBuilder wordBuilder = new StringBuilder(subString);
wordBuilder.setCharAt(0, charEnd);
wordBuilder.setCharAt((length - 2), char1);
subString = String.valueOf(wordBuilder);
}
outputString = outputString + word0 + subString + " ";
}
return outputString;
}
}
This is the result:
input: A wise old owl lived in an oak
output encryptThis: 65 119esi 111dl 111lw 108dvei 105n 97n 111ka
output expected: 65 119esi 111dl 111lw 108dvei 105n 97n 111ka

Put a space every 5 characters without using regex or StringBuilder

I want a user to put in a sentence with the scanner class.
Make sure to filter out all the spaces (for example the sentence: this is a test becomes thisisatest)
And then print out that sentence with a for loop with a space every 5 characters
(for example thisi sates t).
This is what i have so far
import java.util.Scanner;
public class BlockText {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Give your sentence: ");
String sentence = s.nextLine();
String nospace = sentence.replace(" ", "");
String out = "";
for (int i = 5; i < nospace.length(); i+=5) {
out += nospace.replaceAll( nospace.substring(i) , " ");
}
System.out.println("Sentence without spaces: " + nospace);
System.out.println("This gives: " + out);
}
}
but I have the issue that he repeats certain characters and removes others.
Like you can see underneath after "this gives:"
run:
Give your sentence:
this is a test
Sentence without spaces: thisisatest
This gives: thisi hisisa es
BUILD SUCCESSFUL (total time: 8 seconds)
Can someone help me out? Like I said in the titel, I want to accomplish this with a for loop and without using regex or StringBuilder.
You should really use a StringBuilder here, because appending strings with += in a loop is very inefficient.
Without a string builder, you can do something like this:
private static String addSpacesEvery5(String s) {
String out = "";
for (int i = 0 ; i < s.length() ; i++) {
if (i % 5 == 0 && i != 0) {
out += " "; // this will run once every five iterations, except the first one
}
out += s.charAt(i);
}
return out;
}
Or more efficiently without +=:
private static String addSpacesEvery5(String s) {
// s.length() / 5 is how many spaces we will add
char[] charArray = new char[s.length() + s.length() / 5];
int currentPos = 0;
for (int i = 0 ; i < s.length() ; i++) {
if (i % 5 == 0 && i != 0) {
charArray[currentPos] = ' ';
currentPos++;
}
charArray[currentPos] = s.charAt(i);
currentPos++;
}
return new String(charArray);
}
And then you can use it in your main method like this:
Scanner s = new Scanner(System.in);
System.out.println("Give your sentence: ");
String sentence = s.nextLine();
String nospace = sentence.replace(" ", "");
String out = addSpacesEvery5(nospace);
System.out.println("Sentence without spaces: " + nospace);
System.out.println("This gives: " + out);
With a string builder, the addSpacesEvery5 could be rewritten as:
private static String addSpacesEvery5(String s) {
StringBuilder out = new StringBuilder();
for (int i = 0 ; i < s.length() ; i++) {
if (i % 5 == 0 && i != 0) {
out.append(" ");
}
out.append(s.charAt(i));
}
return out.toString();
}
Here is one relatively simple and faster:
String tmp = new String();
int len = str.length();
int remOdds = len % 5;
int i = 0;
while (i < len - remOdds)
{
tmp = tmp.concat(str.substring(i, i + 5));
i += 5;
if (i < len)
{
tmp += " ";
}
}
while (i < len)
{
tmp += str.charAt(i);
i++;
}
str = tmp;

Expanding a condensed string

I am trying take a string similar to this: 3A5o2n4t and expand it back to a string like this: AAAooooonntttt (the number in front of the letter is how many times the letter repeats)
I was trying to use Integer.parseInt() to get the number in front of the letter, but it grabs all of the numbers. Is there a way to grab one number at a time? Also, does my code look okay after that issue is resolved? Or am I missing a bit still?
public String runLengthDecoding(String str3) {
String convert = "";
int number = 0;
if (! str3.isEmpty()) {
convert = str3.charAt(0) + "";
}
for (int i = 0; i <= str3.length() - 1; i++) {
if (Character.isDigit(str3.charAt(i))) { //true or false, the current character is a digit
String temp = "" + str3.charAt(i); //if true, make that character a string
number = Integer.parseInt(temp); /*now store that character as a number (but I only want the current
number, not all the numbers in the string*/
System.out.println(number); /*Testing to see what number is, which is where I found it was
storing all the numbers */
String temp2 = str3.charAt(i + 1) + ""; //Its supposed to start making a string that prints the character in front of it
convert = temp2.repeat(number); //it will print the character however many times that number was stored as
}
}
return convert;
}
Also I have not yet learned how to use arrays, that is why I am not using an array.
Edited to:
- accommodate strings that has length more then 1. Example: 10AA
- accommodate input that starts with a string. Example: A5o
To solve this you have to get all the simultaneous digits, example if you have "55s", you have to get "55", That is why your code is incorrect since if you parseInt whenever you see a digit then it will immediately parse into 5, but the actual number is 55, thus you should accumulate the simultaneous digits first and only parseInt when you encounter the first non digit.
Refer to the code and comments for details:
public class Main {
public static void main(String[] args) {
System.out.println("Input: 3A5o2n4t => Output : " + runLengthDecoding("3A5o2n4t"));
System.out.println("Input: 3AA5o2n4t => Output : " + runLengthDecoding("3AA5o2n4t"));
System.out.println("Input: 10A5o2n4t => Output : " + runLengthDecoding("10A5o2n4t"));
System.out.println("Input: 10AA5o2n4t => Output : " + runLengthDecoding("10AA5o2n4t"));
System.out.println("Input: A5o => Output : " + runLengthDecoding("A5o"));
System.out.println("Input: AB5o => Output : " + runLengthDecoding("AB5o"));
}
public static String runLengthDecoding(String str3) {
String convert = "";
int number = 0;
String numberString = "";
String toBeRepeatedString = "";
boolean flag = false;
for (int i = 0; i <= str3.length() - 1; i++) {
char currentChar = str3.charAt(i);
if (Character.isDigit(currentChar)) { // true or false, the current character is a digit
numberString = numberString + currentChar; // store the possible integer
} else {
if (i + 1 < str3.length()) {
char nextChar = str3.charAt(i + 1); // check if the next char is a digit
if (!Character.isDigit(nextChar)) { // if not a digit then append toBeRepeatedString
if (i == 0 || i + 1 >= str3.length()) {
flag = true;
} else {
toBeRepeatedString += nextChar;
flag = false;
}
} else {
flag = true;
}
}
if (flag) {
toBeRepeatedString += currentChar;
// This will accomodate inputs "A3B";
if (!numberString.isEmpty()) {
number = Integer.parseInt(numberString); // parse the number of repeats
} else {
number = 1;
}
numberString = ""; // reset number
String temp2 = "";
// Repeat the currentChar
for (int j = 0; j < number; j++) {
temp2 += toBeRepeatedString;
}
convert = convert + temp2; // store it to the result
toBeRepeatedString = ""; // reset toBeRepeatedString
}
}
}
return convert;
}
}
Result:
Input: 3A5o2n4t => Output : AAAooooonntttt
Input: 3AA5o2n4t => Output : AAAAAAooooonntttt
Input: 10A5o2n4t => Output : AAAAAAAAAAooooonntttt
Input: 10AA5o2n4t => Output : AAAAAAAAAAAAAAAAAAAAooooonntttt
Input: A5o => Output : Aooooo
Input: AB5o => Output : ABooooo
Here is the best way of doing the above problem it will handle all your scenarios:
public static void main(String[] args) {
String input = "5a2s3T66e";
System.out.println("Input is: "+input+" and output is: "+expandingCondenseString(input));
}
private static String expandingCondenseString(String input){
StringBuilder result = new StringBuilder();
String size = "";
String value = "";
for (int i=0;i<input.length();i++){
if (Character.isDigit(input.charAt(i))) {
size = size + input.charAt(i);
} else {
value = value + input.charAt(i);
if(i+1<input.length() && !Character.isDigit(input.charAt(i+1))){
continue;
}
if(size.isEmpty()){
size = "1";
}
for (int j=0;j<Integer.parseInt(size);j++){
result.append(value);
}
size = "";
value = "";
}
}
return String.valueOf(result);
}

Find Shortest Part of Sentence containing given words

Ex:
if there is a sentence given:
My name is not eugene. my pet name is not eugene.
And we have to search the smallest part in the sentence that Contains the given words
my and eugene
then the answer will be
eugene. my.
No need to check the uppercase or lowercase or special charaters or numerics.
I have pasted my code but getting wrong answer for some test cases.
can any one have any idea what is the problem with the code . I don't have the test case for which it is wrong.
import java.io.*;
import java.util.*;
public class ShortestSegment
{
static String[] pas;
static String[] words;
static int k,st,en,fst,fen,match,d;
static boolean found=false;
static int[] loc;
static boolean[] matches ;
public static void main(String s[]) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
pas = in.readLine().replaceAll("[^A-Za-z ]", "").split(" ");
k = Integer.parseInt(in.readLine());
words = new String[k];
matches = new boolean[k];
loc = new int[k];
for(int i=0;i<k;i++)
{
words[i] = in.readLine();
}
en = fen = pas.length;
find(0);
if(found==false)
System.out.println("NO SUBSEGMENT FOUND");
else
{
for(int j=fst;j<=fen;j++)
System.out.print(pas[j]+" ");
}
}
private static void find(int min)
{
if(min==pas.length)
return;
for(int i=0;i<k;i++)
{
if(pas[min].equalsIgnoreCase(words[i]))
{
if(matches[i]==false)
{
loc[i]=min;
matches[i] =true;
match++;
}
else
{
loc[i]=min;
}
if(match==k)
{
en=min;
st = min();
found=true;
if((fen-fst)>(en-st))
{
fen=en;
fst=st;
}
match--;
matches[getIdx()]=false;
}
}
}
find(min+1);
}
private static int getIdx()
{
for(int i=0;i<k;i++)
{
if(words[i].equalsIgnoreCase(pas[st]))
return i;
}
return -1;
}
private static int min()
{
int min=loc[0];
for(int i=1;i<loc.length;i++)
if(min>loc[i])
min=loc[i];
return min;
}
}
The code you've given will produce incorrect output for the following input. I'm assuming, the word length also matters when you want to 'Find Shortest Part of Sentence containing given words'
String: 'My firstname is eugene. My fn is eugene.'
Number of search strings: 2
string1: 'my'
string2: 'is'
Your solution is: 'My firstname is'
The correct answer is: 'My fn is'
The problem in your code is, it considers both 'firstname' and 'fn' as same length. In the comparison (fen-fst)>(en-st) you're only considering whether the number of words has minimized and not whether the word lengths has shortened.
the following codes (junit):
#Test
public void testIt() {
final String s = "My name is not eugene. my pet name is not eugene.";
final String tmp = s.toLowerCase().replaceAll("[^a-zA-Z]", " ");//here we need the placeholder (blank)
final String w1 = "my "; // leave a blank at the end to avoid those words e.g. "myself", "myth"..
final String w2 = "eugene ";//same as above
final List<Integer> l1 = getList(tmp, w1); //indexes list
final List<Integer> l2 = getList(tmp, w2);
int min = Integer.MAX_VALUE;
final int[] idx = new int[] { 0, 0 };
//loop to find out the result
for (final int i : l1) {
for (final int j : l2) {
if (Math.abs(j - i) < min) {
final int x = j - i;
min = Math.abs(j - i);
idx[0] = j - i > 0 ? i : j;
idx[1] = j - i > 0 ? j + w2.length() + 2 : i + w1.length() + 2;
}
}
}
System.out.println("indexes: " + Arrays.toString(idx));
System.out.println("result: " + s.substring(idx[0], idx[1]));
}
private List<Integer> getList(final String input, final String search) {
String t = new String(input);
final List<Integer> list = new ArrayList<Integer>();
int tmp = 0;
while (t.length() > 0) {
final int x = t.indexOf(search);
if (x < 0 || x > t.length()) {
break;
}
tmp += x;
list.add(tmp);
t = t.substring(search.length() + x);
}
return list;
}
give output:
indexes: [15, 25]
result: eugene. my
I think the codes with inline comments are pretty easy to understand. basically, playing with index+wordlength.
Note
the "Not Found" case is not implemented.
codes are just showing the
idea, it can be optimized. e.g. at least one abs() could be saved.
etc...
hope it helps.
I think it can be handled in another way :
First , find a matching result , and minimize the bound to the current result and then find a matching result from the current result .It can be coded as follows:
/**This method intends to check the shortest interval between two words
* #param s : the string to be processed at
* #param first : one of the words
* #param second : one of the words
*/
public static void getShortestInterval(String s , String first , String second)
{
String situationOne = first + "(.*?)" + second;
String situationTwo = second + "(.*?)" + first;
Pattern patternOne = Pattern.compile(situationOne,Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
Pattern patternTwo = Pattern.compile(situationTwo,Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
List<Integer> result = new ArrayList<Integer>(Arrays.asList(Integer.MAX_VALUE,-1,-1));
/**first , test the first choice*/
Matcher matcherOne = patternOne.matcher(s);
findTheMax(first.length(),matcherOne, result);
/**then , test the second choice*/
Matcher matcherTwo = patternTwo.matcher(s);
findTheMax(second.length(),matcherTwo,result);
if(result.get(0)!=Integer.MAX_VALUE)
{
System.out.println("The shortest length is " + result.get(0));
System.out.println("Which start # " + result.get(1));
System.out.println("And end # " + result.get(2));
}else
System.out.println("No matching result is found!");
}
private static void findTheMax(int headLength , Matcher matcher , List<Integer> result)
{
int length = result.get(0);
int startIndex = result.get(1);
int endIndex = result.get(2);
while(matcher.find())
{
int temp = matcher.group(1).length();
int start = matcher.start();
List<Integer> minimize = new ArrayList<Integer>(Arrays.asList(Integer.MAX_VALUE,-1,-1));
System.out.println(matcher.group().substring(headLength));
findTheMax(headLength, matcher.pattern().matcher(matcher.group().substring(headLength)), minimize);
if(minimize.get(0) != Integer.MAX_VALUE)
{
start = start + minimize.get(1) + headLength;
temp = minimize.get(0);
}
if(temp<length)
{
length = temp;
startIndex = start;
endIndex = matcher.end();
}
}
result.set(0, length);
result.set(1, startIndex);
result.set(2, endIndex);
}
Note that this can handle two situations , regardless of the sequence of the two words!
you can use Knuth Morris Pratt algorithm to find indexes of all occurrences of every given word in your text. Imagine you have text of length N and M words (w1 ... wM). Using KMP algorithm you can get array:
occur = string[N];
occur[i] = 1, if w1 starts at position i
...
occur[i] = M, if wM starts at position i
occur[i] = 0, if no word from w1...wM starts at position i
you loop through this array and from every non-zero position search forward for other M-1 words.
This is approximate pseudocode. Just to understand the idea. It definitely won't work if you just recode it on java:
for i=0 to N-1 {
if occur[i] != 0 {
for j = i + w[occur[i] - 1].length - 1 { // searching forward
if occur[j] != 0 and !foundWords.contains(occur[j]) {
foundWords.add(occur[j]);
lastWordInd = j;
if foundWords.containAllWords() break;
}
foundTextPeaceLen = j + w[occur[lastWordInd]].length - i;
if foundTextPeaceLen < minTextPeaceLen {
minTextPeaceLen = foundTextPeaceLen;
// also remember start and end indexes of text peace
}
}
}
}

Categories

Resources