In the code below I have a double for loop resulting in a time complexity of O^2 in method getResponse(). This code prompts the user for a 10 integer sequence string and an uppercase sensitive pin. It then converts the pin to numbers on a phone pad ie. [ABC] --> 2, [DEF] --> 3. Lastly a response array is generated with each digit of the new phone pin corresponding to indexes of sequence. So input "0123456789","HAM", response = "426"
import java.util.Scanner;
public class Test {
public static final int SEQ_DIGITS = 10;
public static final String ERR_SEQ = "Invalid sequence";
public static final String ERR_PIN = "Invalid PIN";
public static int letterToPhone(char c) {
int phoneNumber = 0;
if (Character.toString(c).matches("[ABC]")) {
phoneNumber = 2;
} else if (Character.toString(c).matches("[DEF]")) {
phoneNumber = 3;
} else if (Character.toString(c).matches("[GHI]")) {
phoneNumber = 4;
} else if (Character.toString(c).matches("[JKL]")) {
phoneNumber = 5;
} else if (Character.toString(c).matches("[MNO]")) {
phoneNumber = 6;
} else if (Character.toString(c).matches("[PQRS]")) {
phoneNumber = 7;
} else if (Character.toString(c).matches("[TUV]")) {
phoneNumber = 8;
} else if (Character.toString(c).matches("[WXYZ]")) {
phoneNumber = 9;
}
return phoneNumber;
}
public static int[] getResponse(String pin, int[] values) {
int[] response = new int[pin.length()];
for(int i = 0; i < pin.length(); i++) {
for (int j = 0; j < values.length; j++) {
int x = letterToPhone(pin.charAt(i));
if(x == j) {
response[i] = values[j];
}
}
}
return response;
}
public static boolean stringIsLengthK(String s, int k) {
boolean isLength = false;
if (s.length() == k) {
isLength = true;
}
return isLength;
}
public static boolean allDigits(String s) {
boolean isDigit = true;
for (int i = 0; i < s.length(); i++) {
if (!(Character.isDigit(s.charAt(i)))) {
isDigit = false;
break;
}
}
return isDigit;
}
public static boolean allUppercaseLetters(String s) {
boolean isUpper = true;
for (int i = 0; i < s.length(); i++) {
if (!(Character.isUpperCase(s.charAt(i)))) {
isUpper = false;
break;
}
}
return isUpper;
}
public static int[] digitStringToIntArray(String s) {
int[] arrayS = new int[s.length()];
for(int i = 0; i < arrayS.length; i++) {
for(int j = 0; j < SEQ_DIGITS; j++) {
if (((int) s.charAt(i) - 48) == j) {
arrayS[i] = j;
}
}
}
return arrayS;
}
public static int countValues(int value, int[] values) {
int count = 0;
for(int i = 0; i < values.length; i++) {
if(value == values[i]) {
count++;
}
}
return count;
}
public static int numPossible(int[] response, int[] values) {
int product = 1;
int[] count = new int[response.length];
for (int i = 0; i < count.length; i++) {
count[i] = countValues(response[i], values);
}
for(int i=0; i<response.length; i++){
product = product * count[i];
}
return product;
}
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.printf("Enter value sequence: ");
final String seq = in.nextLine();
System.out.printf("Enter PIN: ");
final String pin = in.nextLine();
if (!(allUppercaseLetters(pin))) {
throw new AssertionError(ERR_PIN);
} else if (!(allDigits(seq)) || !(stringIsLengthK(seq, SEQ_DIGITS))) {
throw new AssertionError(ERR_SEQ);
}
int[] seqArray = new int[SEQ_DIGITS];
seqArray = digitStringToIntArray(seq);
int[] response = new int[SEQ_DIGITS];
response = getResponse(pin, seqArray);
System.out.printf("Response: ");
for (int i = 0; i < response.length; i++) {
System.out.printf("%d", response[i]);
}
System.out.printf("%n");
numPossible(response, seqArray);
} catch (Error e) {
System.out.println(e.getMessage());
}
}
}
I want to be to able to accommodate larger sequence numbers without a scaling of n^2. Is there a way to change the for loop to instead compare the int x = letterToPhone(pin.charAt(i)); value in getResponse() to a range of integers such as "[0-9]"
One easy optimization of constant factors is to move the call to letterToPhone() out of the inner loop.
And yes, you can compare the x value to a range, eliminating the need for the inner loop.
for(int i = 0; i < pin.length(); i++) {
int x = letterToPhone(pin.charAt(i));
if ( (0 <= x) && (x < values.length)) {
response[i] = values[x];
}
}
Another optimization of constant factors would be to replace all the function calls in letterToPhone() with a switch statement. The compiler may choose to optimize that into a table lookup.
I want to write a code that count repeat of every word in a string,words separate each other with some character that input as a string...why my code don't work?
please answer soon!
public class repeat {
public static void main(String[] args) {
Scanner ss = new Scanner(System.in);
System.out.println("Please write a string:");
String s = ss.nextLine();
System.out.println("Please write a character:");
String w = ss.nextLine();
int i = 0;
int j = 0;
int k = 0;
int y=0;
for (i=0 ;i < s.length() ;i++) {
for (j = 0; j < w.length(); j++) {
if (w.charAt(j) == s.charAt(i) && i!=y && i!=0 && i!=s.length() -1 ) {
k += 1;
y=i+1;
}
}
}
i = 0;
j = 0;
y = 0;
int r = 0;
k++;
System.out.println(k);
String[] a = new String[k];
for (r=0 ;r < k-1 ;r++) {
for (j=1 ;j < s.length() ;j++) {
for (i = 1; i < w.length(); i++) {
if (w.charAt(i) == s.charAt(j)) {
a[r] = s.substring(y, j);
y = j+1;
}
}
}
System.out.println(a[r]);
}
a[k-1] = s.substring(y+1,s.length());
i = 0;
int[] b = new int[k];
while (i <k) {
b[i] = 0;
i++;
}
i = j = 0;
while (i < k) {
while (j != i && j < k) {
if (a[i] == a[j]) {
a[j] = null;
b[i]++;
}
j++;
}
i++;
}
i = j = 0;
while (i < k) {
if (a[i] != null) {
System.out.println(a[i] + " " + b[i]);
}
i++;
}
}
}
Looking through your code your taking a very long approach to this problem. The easiest thing to do is use regex https://docs.oracle.com/javase/tutorial/essential/regex/. Please see the methods below.
public Sentence(String sentanceString) {
this.fullSentence = sentanceString;
breakStringIntoWords(sentanceString);
}
private void breakStringIntoWords(String sentanceString) {
String[] wordsInString = sentanceString.split("\\W+");
for (String word : wordsInString) {
words.add(new Word(word));
}
}
In the second method I broke a sentence (delimited by [spaces]) into words. From here you would write code to compare each word (a class that has a to string method so treat it as a string) to every other word in the Words array list, be careful to avoid over counting.
ok this is now Java with Split instead of searching the string manually:
I don't exactly know if the copyarray is the best practice to make it larger but if your string is not megabytes large it won't be a problem:
public class repeat
{
public static void main(String[] args)
{
String s = "Hello world this is a very good test to a world just that contains just more words than just hello";
String w = " ";
String[] foundwords = new String[0];
int[] wordcount = new int[0];
String[] splittext = s.split(w);
for (int i = 0; i< splittext.length; i++)
{
int IndexOfWord = getIndexOfWord(splittext[i], foundwords);
if (IndexOfWord < 0)
{
String[] foundwordsTemp = new String[foundwords.length + 1];
int[] wordcountTemp = new int[foundwords.length + 1];
System.arraycopy(foundwords, 0, foundwordsTemp, 0, foundwords.length);
System.arraycopy(wordcount, 0, wordcountTemp, 0, foundwords.length);
foundwords = new String[foundwords.length + 1];
wordcount = new int[wordcount.length + 1];
System.arraycopy(foundwordsTemp, 0, foundwords, 0, foundwordsTemp.length);
System.arraycopy(wordcountTemp, 0, wordcount, 0, foundwordsTemp.length);
foundwords[foundwords.length-1] = splittext[i];
wordcount[foundwords.length-1] = 1;
}
else
{
wordcount[IndexOfWord]++;
}
}
for (int i = 0; i < foundwords.length; i++)
{
System.out.println(String.format("Found word '%s' %d times.", foundwords[i], wordcount[i]));
}
}
private static int getIndexOfWord(String word, String[] foundwords)
{
for (int i = 0; i < foundwords.length; i++)
{
if (word.equals(foundwords[i]))
{
return i;
}
}
return -1;
}
}
(Wrong language i did it wrongly in c# - see next answer for java)
I suggest to use array and Split for this because it is very complicated work with substring to seach for the char. While w still is a String, c need to be a type char.
String[] foundwords = { };
Int32[] wordcount = { };
foreach (String word in s.Split(w))
{
int IndexOfWord = Array.IndexOf(foundwords, word);
if (IndexOfWord < 0)
{
Array.Resize(ref foundwords, foundwords.Length + 1);
Array.Resize(ref wordcount, wordcount.Length + 1);
foundwords[foundwords.GetUpperBound(0)] = word;
wordcount[foundwords.GetUpperBound(0)] = 1;
}
else
{
wordcount[IndexOfWord]++;
}
}
for (int i = 0; i <= foundwords.GetUpperBound(0); i++)
{
Console.WriteLine(String.Format("Found word '{0}' {1} times.", foundwords[i], wordcount[i]));
}
be aware that it is case sensitive.
so if it is still on your list i made a code.
First - you where lost to just let it run in the main procedure only. You should start and seperate your work into single tasks instead of writing a strait start stop program. Using functions with a "good" name will make it easier to you in future.
First you need something to find the String in another.
Usually you may use
int dividerPosition = restString.indexOf(searchString);
this is a java build in function. If you want to write it yourself, you could create a function like this (that will do the same but you can "see" it working:)
private static int indexOf(String restString, String searchString)
{
int dividerPosition = -1;
for (int i = 0; i < restString.length()-searchString.length(); i++)
{
// Debuging test:
System.out.println(String.format("search Pos %d in '%s' for length %d.", i, restString, searchString.length()));
if (restString.substring(i, i + searchString.length()).equals(searchString))
{
dividerPosition = i;
i = restString.length();
}
}
return dividerPosition;
}
and use this function in your code later on like:
int dividerPosition = indexOf(restString, searchString);
I will again use the function to find either a word is allready known
private static int getIndexOfWord(String word, String[] foundwords)
{
for (int i = 0; i < foundwords.length; i++)
{
if (word.equals(foundwords[i]))
{
return i;
}
}
return -1;
}
Third Task would be to Split and count the Words at the found position.
The easier way (only my opinion) would be just to cut of the found Words from the String - so write a function that will "save" the found word in a array or count the "counter"-Array if it is allready found.
This most important task to understand is important - ok we will just look for the position of the string we are searching. We need to check if it is not found (so the last word)
We will store the found word (that is the part before the found String) in a variable and do the "count or create new word" thing. And then we will return the String cut of the word and the Seach-String.
The Cut-Off is important because we replace the origin String by the one without the first word and just repeat this until the origin String is "".
For the last word we ensure the function will return "" by changing the dividerPosition to the length of the RestString - that is the last word now only - minus "searchString.length()" so it will fit to the return "restString.substring(dividerPosition+searchString.length());" to return ""
Look in the next part into the function named "getNextW("
you can run int with the self-written IndexOf function or the Java function by changing the commentlines in
/// Index Of Search (better)
//int dividerPosition = restString.indexOf(searchString);
/// Manual Search (why make it more difficuilt - you should learn to make your work as easy as possible)
int dividerPosition = indexOf(restString, searchString);
Everything together
to get startet you will have very little code in the main procedure using the "cut" function until the String is empty - all together now:
public class repeat
{
public static void main(String[] args)
{
String s = "Hello a world a this is a very good test to a a a a world just that contains just more words than just hello";
String w = " ";
while (!(s = getNextW(s, w)).equals(""))
{
System.out.println(s);
}
System.out.println("");
for (int i = 0; i < foundwords.length; i++)
{
// Debuging test:
System.out.println(String.format("Found word '%s' %d times.", foundwords[i], wordcount[i]));
}
}
private static String[] foundwords = new String[0];
private static int[] wordcount = new int[0];
private static String getNextW(String restString, String searchString)
{
/// Index Of Search (better)
//int dividerPosition = restString.indexOf(searchString);
/// Manual Search (why make it more difficuilt - you should learn to make your work as easy as possible)
int dividerPosition = indexOf(restString, searchString);
String foundWord;
if (dividerPosition > 0)
{
foundWord = restString.substring(0, dividerPosition);
}
else
{
foundWord = restString;
dividerPosition = restString.length()-searchString.length();
}
int IndexOfWord = getIndexOfWord(foundWord, foundwords);
if (IndexOfWord < 0)
{
String[] foundwordsTemp = new String[foundwords.length + 1];
int[] wordcountTemp = new int[foundwords.length + 1];
System.arraycopy(foundwords, 0, foundwordsTemp, 0, foundwords.length);
System.arraycopy(wordcount, 0, wordcountTemp, 0, foundwords.length);
foundwords = new String[foundwords.length + 1];
wordcount = new int[wordcount.length + 1];
System.arraycopy(foundwordsTemp, 0, foundwords, 0, foundwordsTemp.length);
System.arraycopy(wordcountTemp, 0, wordcount, 0, foundwordsTemp.length);
foundwords[foundwords.length-1] = foundWord;
wordcount[foundwords.length-1] = 1;
}
else
{
wordcount[IndexOfWord]++;
}
// Debuging test:
System.out.println(String.format("Rest of String is '%s' positionnext is %d.", restString, dividerPosition));
return restString.substring(dividerPosition+searchString.length());
}
private static int getIndexOfWord(String word, String[] foundwords)
{
for (int i = 0; i < foundwords.length; i++)
{
if (word.equals(foundwords[i]))
{
return i;
}
}
return -1;
}
private static int indexOf(String restString, String searchString)
{
int dividerPosition = -1;
for (int i = 0; i < restString.length()-searchString.length(); i++)
{
// Debuging test:
System.out.println(String.format("search Pos %d in '%s' for length %d.", i, restString, searchString.length()));
if (restString.substring(i, i + searchString.length()).equals(searchString))
{
dividerPosition = i;
i = restString.length();
}
}
return dividerPosition;
}
}
Other variant with charAt and im am using your kind of "count words to size the array" what will result in a to big array (potentially far to big):
public class repeat
{
private static String[] foundwords;
private static int[] wordcount;
private static int counter;
public static void main(String[] args) {
String s = "Hello a world a this is a very good test to a a a a world just that contains just more words than just hello";
String w = " ";
int tempPos = 0;
counter = 1; // counting total w-strings+1 for dim
while ((tempPos = findnext(s, w, tempPos)) >= 0)
{
tempPos = tempPos + w.length();
counter++;
}
foundwords = new String[counter];
wordcount = new int[counter];
counter = 0;
while ((tempPos = findnext(s, w, 0)) >= 0)
{
String foundWord = s.substring(0, tempPos);
s = s.substring(tempPos + w.length());
foundWordToArray(foundWord);
}
foundWordToArray(s);
for (int i = 0; i < counter; i++)
{
System.out.println(String.format("Found word '%s' %d times.", foundwords[i], wordcount[i]));
}
}
public static int findnext(String haystack, String needle, int startPos)
{
int hpos, npos;
for (hpos = startPos; hpos < haystack.length()-needle.length(); hpos++)
{
for (npos = 0; npos < needle.length(); npos++)
{
if (haystack.charAt(hpos+npos)!=needle.charAt(npos))
{
npos = needle.length()+1;
}
}
if (npos == needle.length())
{
return hpos;
}
}
return -1;
}
private static int getIndexOfWord(String word, String[] foundwords)
{
for (int i = 0; i < foundwords.length; i++)
{
if (word.equals(foundwords[i]))
{
return i;
}
}
return -1;
}
private static void foundWordToArray(String foundWord)
{
int IndexOfWord = getIndexOfWord(foundWord, foundwords);
if (IndexOfWord < 0)
{
foundwords[counter] = foundWord;
wordcount[counter] = 1;
counter++;
}
else
{
wordcount[IndexOfWord]++;
}
}
}
i like this one:
public class repeat
{
private static String[] foundwords = new String[0];
private static int[] wordcount = new int[0];
public static void main(String[] args) {
String s = "Hello a world a this is a very good test to a a a a world just that contains just more words than just hello";
String w = " ";
int tempPos;
while ((tempPos = findnext(s, w, 0)) >= 0)
{
String foundWord = s.substring(0, tempPos);
s = s.substring(tempPos + w.length());
foundWordToArray(foundWord);
}
foundWordToArray(s);
for (int i = 0; i < foundwords.length; i++)
{
System.out.println(String.format("Found word '%s' %d times.", foundwords[i], wordcount[i]));
}
}
private static void foundWordToArray(String foundWord)
{
int IndexOfWord = getIndexOfWord(foundWord, foundwords);
if (IndexOfWord < 0)
{
String[] foundwordsTemp = new String[foundwords.length + 1];
int[] wordcountTemp = new int[foundwords.length + 1];
System.arraycopy(foundwords, 0, foundwordsTemp, 0, foundwords.length);
System.arraycopy(wordcount, 0, wordcountTemp, 0, foundwords.length);
foundwords = new String[foundwords.length + 1];
wordcount = new int[wordcount.length + 1];
System.arraycopy(foundwordsTemp, 0, foundwords, 0, foundwordsTemp.length);
System.arraycopy(wordcountTemp, 0, wordcount, 0, foundwordsTemp.length);
foundwords[foundwords.length-1] = foundWord;
wordcount[foundwords.length-1] = 1;
}
else
{
wordcount[IndexOfWord]++;
}
}
public static int findnext(String haystack, String needle, int startPos)
{
int hpos, npos;
for (hpos = startPos; hpos < haystack.length()-needle.length(); hpos++)
{
for (npos = 0; npos < needle.length(); npos++)
{
if (haystack.charAt(hpos+npos)!=needle.charAt(npos))
{
npos = needle.length()+1;
}
}
if (npos == needle.length())
{
return hpos;
}
}
return -1;
}
private static int getIndexOfWord(String word, String[] foundwords)
{
for (int i = 0; i < foundwords.length; i++)
{
if (word.equals(foundwords[i]))
{
return i;
}
}
return -1;
}
}
Here is my input file
So I am reading in a .txt file and I keep getting a string index out of bounds exception. I have been trying to find duplicate words and keep the array sorted as I add words to it. I thought my problem was trying to sort and search the array when It has no words or only one word in it.
The line with the ** in front of it is the problem line. Its line 129
import java.io.*;
import java.util.Scanner;
import java.util.regex.*;
public class BuildDict
{
static String dict[] = new String[20];
static int index = 0;
public static void main(String args [])
{
readIn();
print();
}
public static void readIn()
{
File inFile = new File("carol.txt");
try
{
Scanner scan = new Scanner(inFile);
while(scan.hasNext())
{
String word = scan.next();
if(!Character.isUpperCase(word.charAt(0)))
{
checkRegex(word);
}
}
scan.close();
}
catch(IOException e)
{
System.out.println("Error");
}
}
public static void addToDict(String word)
{
if(index == dict.length)
{
String newAr[] = new String[dict.length*2];
for(int i = 0; i < index; i++)
{
newAr[i] = dict[i];
}
if(dict.length < 2)
{
newAr[index] = word;
index++;
}
else
{
bubbleSort(word);
if(!wordHasDuplicate(word))
{
newAr[index] = word;
index++;
}
}
dict = newAr;
}
else
{
dict[index] = word;
index++;
}
}
public static void checkRegex(String word)
{
String regex = ("[^A-Za-z]");
Pattern check = Pattern.compile(regex);
Matcher regexMatcher = check.matcher(word);
if(!regexMatcher.find())
{
addToDict(word);
}
}
public static void print()
{
try
{
FileWriter outFile = new FileWriter("dict.txt");
for(int i = 0; i < index; i++)
{
outFile.write(dict[i]);
outFile.write(" \n ");
}
outFile.close();
}
catch (IOException e)
{
System.out.println("Error ");
}
}
public static void bubbleSort(String word)
{
boolean swap = true;
String temp;
int wordBeforeIndex = 0;
String wordBefore;
while(swap)
{
swap = false;
wordBefore = dict[wordBeforeIndex];
for(int i = 0; (i < word.length()) && (i < wordBefore.length()) i++)
{
**if(word.charAt(i) < wordBefore.charAt(i))**
{
temp = wordBefore;
dict[wordBeforeIndex] = word;
dict[wordBeforeIndex++] = temp;
wordBeforeIndex++;
swap = true;
}
}
}
}
public static boolean wordHasDuplicate(String word)
{
int low = 0;
int high = dict.length - 1;
int mid = low + (high - low) /2;
while (low <= high && dict[mid] != word)
{
if (word.compareTo(dict[mid]) < 0)
{
low = mid + 1;
}
else
{
high = mid + 1;
}
}
return true;
}
}
Error is shown below:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.charAt(String.java:658)
at BuildDict.bubbleSort(BuildDict.java:129)
at BuildDict.addToDict(BuildDict.java:60)
at BuildDict.checkRegex(BuildDict.java:90)
at BuildDict.readIn(BuildDict.java:30)
at BuildDict.main(BuildDict.java:14)
Check the length of wordBefore as a second condition of your for loop:
for(int i = 0; (i < word.length()) && (i < wordbefore.length()); i++)
This question already has answers here:
Printing reverse of any String without using any predefined function?
(34 answers)
Closed 8 years ago.
I was asked this in a technical interview. I have no idea whatsoever please please help me.
it goes in infinite loop. I just cant find the correct logic.
not once, but twice i came across this kind of a question, so please help
public static int numberOfCharsInString(String sentence)
{
int numberOfChars = 0,i=0;
while (!sentence.equals(""))
{
sentence = sentence.substring(1);
++numberOfChars;
}
return numberOfChars;
}
public static void reverseSequenceOfWords(String inp)
{
int len=numberOfCharsInString(inp);
char[] in=inp.toCharArray();
int i=0;
for(i=len-1;i>=0;i--)
{
if(in[i]==' ')
{
while(!in.equals("")||in.equals(" "))
{
System.out.print(in[i]+" ");
}
}
else if(in[i]=='\0')
{
break;
}
}
}
public static void main(String[] args)
{
int length=0;
String inpstring = "";
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
try
{
System.out.print("Enter a string to reverse:");
inpstring = reader.readLine();
length=numberOfCharsInString(inpstring);
System.out.println("Number of Characters: "+length);
reverseSequenceOfWords(inpstring);
}
catch (Exception e)
{
e.printStackTrace();
}
}
String[] array = "Are you crazy".split(" ");
for (int i = array.length - 1; i >= 0; --i) {
System.out.print(array[i] + " ");
}
Brute forced this so hard lol
public static void main (String args[]){
String input = new Scanner(System.in).nextLine();
input+=" ";
ArrayList<String> words = new ArrayList<String>();
int start = 0;
for(int i=0; i<input.length(); i++){
if(input.charAt(i)==' '){
String toAdd="";
for(int r=start; r<i; r++){
toAdd+=input.charAt(r);
}
words.add(toAdd);
start = i+1;
}
}
for(int i=words.size()-1; i>=0; i--){
System.out.print(words.get(i)+" ");
}
}
I've used String.length() and String.substring()and String.charAt() - I hope that is allowed.
private static class Word {
private final String message;
private final int start;
private final int end;
public Word(String message, int start, int end) {
this.message = message;
this.start = start;
this.end = end;
}
#Override
public String toString() {
return message.substring(start, end);
}
}
private Word[] split(String message) {
// Split it into words - there cannot be more words than characters in the message.
int[] spaces = new int[message.length()];
// How many words.
int nWords = 0;
// Pretend there's a space at the start.
spaces[0] = -1;
// Walk the message.
for (int i = 0; i < message.length(); i++) {
if (message.charAt(i) == ' ') {
spaces[++nWords] = i;
}
}
// Record the final position.
spaces[++nWords] = message.length();
// Build the word array.
Word[] words = new Word[nWords];
for (int i = 0; i < nWords; i++) {
words[i] = new Word(message, spaces[i] + 1, spaces[i + 1]);
}
return words;
}
private String reverse(String message) {
Word[] split = split(message);
String reversed = "";
for ( int i = split.length - 1; i >= 0; i--) {
reversed += split[i].toString();
if ( i > 0 ) {
reversed += " ";
}
}
return reversed;
}
public void test() {
String message = "Hello how are you today?";
System.out.println(reverse(message));
}
prints
today? you are how Hello
Much more minimal but less useful. Only uses length, charAt and substring again:
public void printWordsReversed(String message) {
int end = message.length();
for ( int i = end - 1; i >= 0; i--) {
if ( message.charAt(i) == ' ') {
System.out.print(message.substring(i+1, end)+" ");
end = i;
}
}
System.out.print(message.substring(0, end));
}
The only function i'm still using is the IndexOf function, but that is not that hard to create for yourself.
static void Main(string[] args)
{
string sentence = "are you cracy";
int length = Program.StringLength(sentence);
int currentpos = 0;
List<string> wordList = new List<string>();
int wordCount = 0;
while (currentpos < length)
{
// find the next space
int spacepos = sentence.IndexOf(' ', currentpos);
string word;
if (spacepos < 0)
{
// end of string reached.
word = sentence.Substring(currentpos, length - currentpos);
wordList.Add(word);
wordCount++;
// no need to continue.
break;
}
word = sentence.Substring(currentpos, spacepos - currentpos);
wordList.Add(word);
wordCount++;
currentpos = spacepos + 1;
}
// display
for (int i = wordList.Count - 1; i >= 0; i--)
{
// after first word is display, add spaces to the output
if (i < wordList.Count - 1)
{
Console.WriteLine(" ");
}
// display word
Console.WriteLine(wordList[i]);
}
}
public static int StringLength(String sentence)
{
int numberOfChars = 0;
while (!sentence.Equals(""))
{
sentence = sentence.Substring(1);
++numberOfChars;
}
return numberOfChars;
}
Given a string how can i figure out the number of times each char in a string repeats itself
ex: aaaabbaaDD
output: 4a2b2a2D
public static void Calc() {
Input();
int count = 1;
String compressed = "";
for (int i = 0; i < input.length(); i++) {
if (lastChar == input.charAt(i)) {
count++;
compressed += Integer.toString(count) + input.charAt(i);
}
else {
lastChar = input.charAt(i);
count = 1;
}
}
System.out.println(compressed);
}
What you'r looking for is "Run-length encoding". Here is the working code to do that;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RunLengthEncoding {
public static String encode(String source) {
StringBuffer dest = new StringBuffer();
// iterate through input string
// Iterate the string N no.of.times where N is size of the string to find run length for each character
for (int i = 0; i < source.length(); i++) {
// By default run Length for all character is one
int runLength = 1;
// Loop condition will break when it finds next character is different from previous character.
while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {
runLength++;
i++;
}
dest.append(runLength);
dest.append(source.charAt(i));
}
return dest.toString();
}
public static String decode(String source) {
StringBuffer dest = new StringBuffer();
Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z]");
Matcher matcher = pattern.matcher(source);
while (matcher.find()) {
int number = Integer.parseInt(matcher.group());
matcher.find();
while (number-- != 0) {
dest.append(matcher.group());
}
}
return dest.toString();
}
public static void main(String[] args) {
String example = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
System.out.println(encode(example));
System.out.println(decode("1W1B1W1B1W1B1W1B1W1B1W1B1W1B"));
}
}
This program first finds the unique characters or numbers in a string. It will then check the frequency of occurance.
This program considers capital and small case as different characters. You can modify it if required by using ignorecase method.
import java.io.*;
public class RunLength {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
System.out.println("Please enter the string");
String str = br.readLine();//the input string is in str
calculateFrequency(str);
}
private static void calculateFrequency(String str) {
int length = str.length();
String characters[] = new String[length];//to store all unique characters in string
int frequency[] = new int[length];//to store the frequency of the characters
for (int i = 0; i < length; i++) {
characters[i] = null;
frequency[i] = 0;
}
//To get unique characters
char temp;
String temporary;
int uniqueCount = 0;
for (int i = 0; i < length; i++) {
int flag = 0;
temp = str.charAt(i);
temporary = "" + temp;
for (int j = 0; j < length; j++) {
if (characters[j] != null && characters[j].equals(temporary)) {
flag = 1;
break;
}
}
if (flag == 0) {
characters[uniqueCount] = temporary;
uniqueCount++;
}
}
// To get the frequency of the characters
for(int i=0;i<length;i++){
temp=str.charAt(i);
temporary = ""+temp;
for(int j=0;i<characters.length;j++){
if(characters[j].equals(temporary)){
frequency[j]++;
break;
}
}
}
// To display the output
for (int i = 0; i < length; i++) {
if (characters[i] != null) {
System.out.println(characters[i]+" "+frequency[i]);
}
}
}}
Some hints: In your code sample you also need to reset count to 0 when the run ends (when you update lastChar). And you need to output the final run (after the loop is done). And you need some kind of else or continue between the two cases.
#Balarmurugan k's solution is better - but just by improving upon your code I came up with this -
String input = "aaaabbaaDD";
int count = 0;
char lastChar = 0;
int inputSize = input.length();
String output = "";
for (int i = 0; i < inputSize; i++) {
if (i == 0) {
lastChar = input.charAt(i);
count++;
} else {
if (lastChar == input.charAt(i)) {
count++;
} else {
output = output + count + "" + lastChar;
count = 1;
lastChar = input.charAt(i);
}
}
}
output = output + count + "" + lastChar;
System.out.println(output);