How to solve Permutations on String element in java? - java

Problem Description
Given an integer array containing digits from [0, 99], the task is to print all possible letter combinations that the numbers could represent. A mapping of digit to letters (just like on the telephone buttons) is being followed. Note that 0 and 1 do not map to any letters. All the mapping are like:enter link description here
Here is my design:
First,default the String array and input the elements to it;like:
Second,default the show method like:
Third,config the mapping about String array and number
Four,Use Scanner method;
the show result like
input:Array[]={99,2,3};
output:HAD HAE HAF HBD HBE HBF HCD HCE HCF EAD EAE EAF EBD EBE EBF ECD ECE
ECF LAD LAE LAF LBD LBE LBF LCD LCE LCF LAD LAE LAF LBD LBE LBF LCD
LCE LCF OAD OAE OAF OBD OBE OBF OCD OCE OCF
import java.io.*;
import java.util.*;
public class GFG
{
// Function to return a vector that contains
// all the generated letter combinations
static ArrayList<String> letterCombinationsUtil(int[] number, int n,
String[] table)
{
// To store the generated letter combinations
ArrayList<String> list = new ArrayList<>();
Queue<String> q = new LinkedList<>();
q.add("");
while(!q.isEmpty())
{
String s = q.remove();
// If complete word is generated
// push it in the list
if (s.length() == n)
list.add(s);
else
{
String val = table[number[s.length()]];
for (int i = 0; i < val.length(); i++)
{
q.add(s + val.charAt(i));
}
}
}
return list;
}
// Function that creates the mapping and
// calls letterCombinationsUtil
static void letterCombinations(int[] number, int n)
{
// table[i] stores all characters that
// corresponds to ith digit in phone
String[] table = { "", "", "abc", "def", "ghi", "jkl",
"mno", "pqrs", "tuv", "wxyz" };
ArrayList<String> list =
letterCombinationsUtil(number, n, table);
// Print the contents of the list
for (int i = 0; i < list.size(); i++)
{
System.out.print(list.get(i) + " ");
}
}
public static void main(String args[])
{
int[] number = { 2, 3, 7, 9};
int n = number.length;
letterCombinations(number, n);
}
}
input:

Related

java| how to create block same-length String

I want to built in ten arrays of size n and place in the first stings of length one, in the second strings of length two and so forth where the tenth array has strings of length ten.
Array String = { a, b, the , c , no, yes, and, or, ...}
Array length_string = [ 1 , 1, 3, 1 , 2, 3, 3 , 2 , ....}
I don't understand how to do this, place string with same length into block:
[a,b,c] //every string length =1
[no,or] // every string length =2
[the,yes,and] // every string length =3
and so on
Edit:
I found hash Map work with my code
`final Map<Integer, List> lengthToWords = new TreeMap<>(
Arrays.stream(words).collect(Collectors.groupingBy(String::length)));
But how can control block size
I meaning want each block = 256
1 [ a , b ,c ,...] number element =256 , not more that
2 [ aa, bb, cc ,..] number element =256
and so on until ten block
I have ten block by using loop , Now i need limit number element inside block
Hi if your solution doesn't need to be efficient or your array size is limit you can do it with nested loops.
for(int i =1;i<=n;i++){
for(int j = 0;j<stringArray.length;j++){
if(i == stringArray[j].length){
resultArray[i-1] = stringArray[j];
break;
}
else
continue;
}
}
Be careful to check arrayIndexOutOfBound exception
String[] arr= { "a", "b", "the" , "c" , "no", "yes", "and", "or"};
String length1="[";
String length2="[";
String length3 ="[";
for (int i = 0; i < arr.length; i++)
{
switch(arr[i].length())
{
case 1:
length1=length1+ arr[i]+",";
break;
case 2:
length2=length2+ arr[i]+",";
break;
case 3:
length3=length3+ arr[i]+",";
break;
}
}
if (length1.endsWith(",")) {
length1 = length1.substring(0, length1.length()-1);
}
if (length2.endsWith(",")) {
length2 = length2.substring(0, length2.length()-1);
}
if (length3.endsWith(",")) {
length3 = length3.substring(0, length3.length()-1);
}
length1=length1+"]";
length2=length2+"]";
length3=length3+"]";
System.out.println(length1);
System.out.println(length2);
System.out.println(length3);
output :
[a,b,c]
[no,or]
[the,yes,and]
Below is the complete Java code with example input. The createBlockList does the following: 1) Create a list of lists to store the result. 2)Iterate through the string array and place the string in the right lists.
import java.util.*;
public class MyClass {
public static void createBlockList(String[] strArr, int[] strLenArr) {
List<List<String>>resList = new ArrayList<>();
for(int i=0; i<3; i++) {
resList.add(new ArrayList());
}
for(int i=0; i<strArr.length; i++) {
int strLen = strLenArr[i];
resList.get(strLen-1).add(strArr[i]);
}
}
public static void main(String []args){
String str[] = {"a","b","in","on","the","and"};
int len[] = {1,1,2,2,3,3};
createBlockList(str, len);
}
}

Replacing String in Java to get all variations

I'm trying to get a printout of all variations of a certain String. For example, we have this input: AB0C0. The 0 in the 3rd and 5th spots should be treated as variables. The variable characters are 1, 2, and 3 to be placed in the spot of 0. This means there would be all possible variations of this input:
AB1C1
AB2C1
AB3C1
AB1C2
AB1C3
AB2C2
AB2C3
AB3C2
AB3C3
This is just an example. A 5-character long string is a place for 1 to 5 variables. The issue I'm facing is, that it should generate all variations no matter how many variables are in the input in no matter in which place they are.
Scanner scanner = new Scanner (System.in);
System.out.println("Enter the key consisting of 5 characters:");
String input = scanner.next();
String strOutput1 = input.replaceFirst("0","1");
String strOutput1A = input.replace("0","1");
String strOutput2 = input.replaceFirst("0","2");
String strOutput3 = input.replaceFirst("0","3");
String strOutput4 = input.replaceFirst("0","4");
String strOutput5 = input.replaceFirst("0","5");
System.out.println(strOutput1.toUpperCase());
System.out.println(strOutput1A.toUpperCase());
System.out.println(strOutput2.toUpperCase());
System.out.println(strOutput3.toUpperCase());
System.out.println(strOutput4.toUpperCase());
System.out.println(strOutput5.toUpperCase());
What about this:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the key consisting of 5 characters:");
String input = scanner.next();
//find positions of '0' in input
List<Integer> varPositions = findVarPositions(input);
//create permutations
List<String> permutations = new ArrayList<>();
permutations.add(input);//AB0C0
for (int position : varPositions) {
permutations = permutateAtPosition(permutations, position);
}
//print permutations
for (String permutation : permutations) {
System.out.println(permutation.toUpperCase());
}
}
private static List<Integer> findVarPositions(String input) {
List<Integer> varPositions = new ArrayList<>();
int lastVarPosition = -1;
while ((lastVarPosition = input.indexOf('0', lastVarPosition + 1)) != -1) {
varPositions.add(lastVarPosition);
}
return varPositions;
}
private static List<String> permutateAtPosition(List<String> partialyPermutated, int position) {
List<String> result = new ArrayList<>();
char[] replacements = {'1', '2', '3', '4', '5'};
for (String item : partialyPermutated) {
for (int i = 0; i < replacements.length; i++) {
String output = replaceCharAt(item, position, replacements[i]);
result.add(output);
}
}
return result;
}
private static String replaceCharAt(String input, int position, char replacement) {
//converting to char array, because there's no method like
//String.replaceAtPosition(position, char)
char[] charArray = input.toCharArray();
charArray[position] = replacement;
return new String(charArray);
}
}
It's not fixed to a number of variables.
The idea is to extract positions of '0' and subsequently call the method permutateAtPosition, which takes a partially permutated list and permutates it by one more level.
For "a0b0c0" and values 1-2 it would be ['a0b0c0'], then ['a1b0c0','a2b0c0'], then ['a1b1c0','a1b2c0','a2b1c0','a2b2c0'], and finally ['a1b1c1','a1b1c2','a1b2c1','a1b2c2','a2b1c1','a2b1c2','a2b2c1''a2b2c2'].
This solution keeps everything in memory, so in the general case (unlimited input string) it would be wiser to go with depth-first instead.
I've got another solution for you.
First step, getting the amount of variables:
int variableCount = 0;
for (int i = 0; i < 5; i++) {
if (input.charAt(i) == '0') {
variableCount++;
}
}
Then calculating the amount of results we are expecting:
int countMax = (int)Math.pow(4,variableCount);
Lastly, count up in base 4. Pad the number with 0's and replace the original input 0's:
for (int i = 0; i < countMax; i++) {
String paddedNumbers = format("%" + variableCount + "s",Integer.toString(i, 4)).replace(" ", "0");
int replacedCount = 0;
char[] outputChars = input.toCharArray();
for (int j = 0; j < 5; j++) {
if (input.charAt(j) == '0') {
outputChars[j] = paddedNumbers.charAt(replacedCount);
replacedCount++;
}
}
System.out.println(outputChars);
}

Java: Finding jumbled word

In my country there is Game Show called Slagalica where one of the tasks is to find longest word in array of 12 letters. Size of the longest word is always 10, 11 or 12.
I have file with words from my language I use as database. Words that have 10, 11 or 12 letters in them I've saved in List (listWordSize10_11_12).
When I enter jumbled word [12 letters] in I want from my program to find what word is that originally. I know how to make it work when jumbled word is 12 letters word but I can't work it out when it's less.
Example: 10 letter word is jumbled + 2 random letters.
Goal is for that 10 letter word to be recognized and printed in original state.
Where is what I've done:
// un-jumbling word
System.out.println("Unesite rijec koja treba da se desifruje: ");
String jumbledWord = tast.nextLine();
char[] letter = jumbledWord.toCharArray();
Arrays.sort(letter);
String sorted_Mistery_Word = new String(letter);
for (int i = 0; i < listWordSize10_11_12.size(); i++) {
int exception = 0;
char[] letter_2 = listWordSize10_11_12.get(i).toCharArray();
Arrays.sort(letter_2);
String longWords = new String(letter_2);
int j = i;
while(longWords.length()>i){
if(sorted_Mistery_Word.charAt(j)!=longWords.charAt(i)){
exception++;
j++;
}
}
if(exception < 3){
System.out.println("Your word is: "+listWordSize10_11_12.get(i));
break;
}
}
Thanks!!!
P.S. This is not a homework or some job, just project I've been doing for fun!
Thanks everyone for the help, I've learned a lot!
Your basic approach for 12 characters, which I would characterize as fingerprinting, will also work for 10 or 11 letter words with some modification.
That is, rather that just sorting the letters in each candidate word as you examine it to create the fingerprint, pre-process your array to create a small(ish) fingerprint of each word as a byte[]. Using the English alphabet and ignoring case, for example, you could create a 26-byte array for each word, where each byte position contained the count of each letter in the word.
That is fingerprint[0] contains the number of 'a' characters in the word, and fingerprint[25] the number of 'z' characters.
Then just replace your sorted_Mistery_Word.charAt(j)!=longWords.charAt(i) check with a loop that increments a temporary array for each letter in the mystery word. Finally, check that the temporary array has at least the same value for every position. Something like:
byte [] makeFingerprint(String s) {
byte[] fingerprint = new byte[26];
for (char c : letter_2) {
fingerprint[c - 'a']++;
}
return fingerprint;
}
/** determine if sub is a subset of super */
boolean isSubset(byte[] sub, byte[] super) {
for (int i=0; i < sub.length; i++) {
if (sub[i] > super[i])
return false;
}
return true;
}
void findMatch(String jumbledWord) {
byte[] fingerprint = makeFingerprint(jumbledWord);
for (byte[] candidate : fingerprintList) {
if (isSubset(fingerprint, candidate)) {
System.out.println("Your word is: " + ...);
break;
}
}
}
Here I omitted the creation of the fingerprintList - but it just involves fingerprint each word.
There are plenty of optimizations possible, but this should already be quite a bit faster than your version (and is "garbage free" in the main loop). It can handle candidates of any length (not just 10-12 chars). The biggest optimization, if you will check many words, is to try to use the "fingerpint" as a key for direct lookup. For the 12 character case this is trivial (direct lookup), but for the 10 and 11 or this you would likely have to use type of technique for higher-dimensional searching - locality sensitive hashing seems like a natural fit.
Here's one way to go about the problem. Let's say (since no example input was provided) that there's 3 String[]'s, arr3 (that represents the 10-letter-words you have), arr4 (that represents the 11-letter-words you have), and arr5 (you guessed it, represents the 12-letter words you have). This is what I made for those:
String[] arr3 = { "map", "cat", "dog" };
String[] arr4 = { "four", "five", "nine" };
String[] arr5 = { "funny", "comma", "brace" };
So based on what you said, if we got the input of pam, we'd want the output of map. If we got the input of enni we'd want the output of nine. And if we got the input of yfunn we'd want the output of funny. So how to go about doing this? I like what #cricket_007 mentioned about using maps. But first, let's get the permutations down.
Based off of the linked SO question, I came up with this modified/variation to get the jumbled text:
public static List<String> jumble(String str) {
List<String> result = new ArrayList<String>();
permutation(result, "", str);
return result;
}
private static void permutation(List<String> l, String prefix, String s) {
int n = s.length();
if (n == 0) {
l.add(prefix);
} else {
for (int i = 0; i < n; i++)
permutation(l, prefix + s.charAt(i), s.substring(0, i) + s.substring(i + 1, n));
}
}
This code will let us easily construct a single map for us to store jumbled text in as a key, and the answer to that jumbled text as a value.
All together, the final code looks like this:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Appy {
public static void main(String[] args) {
String[] arr3 = { "map", "cat", "dog" };
String[] arr4 = { "four", "five", "nine" };
String[] arr5 = { "funny", "comma", "brace" };
List<String> permutations = new ArrayList<String>();
Map<String, String> map = new HashMap<String, String>();
for (String s : arr3) {
permutations = jumble(s);
for (String str : permutations)
map.put(str, s);
}
for (String s : arr4) {
permutations = jumble(s);
for (String str : permutations)
map.put(str, s);
}
for (String s : arr5) {
permutations = jumble(s);
for (String str : permutations)
map.put(str, s);
}
System.out.println("test = 'pam' -> " + map.get("pam"));
System.out.println("test = 'enni' -> " + map.get("enni"));
System.out.println("test = 'yfunn' -> " + map.get("yfunn"));
}
public static List<String> jumble(String str) {
List<String> result = new ArrayList<String>();
permutation(result, "", str);
return result;
}
private static void permutation(List<String> l, String prefix, String s) {
int n = s.length();
if (n == 0) {
l.add(prefix);
} else {
for (int i = 0; i < n; i++)
permutation(l, prefix + s.charAt(i), s.substring(0, i) + s.substring(i + 1, n));
}
}
}
Which gives the resulting output of:
test = 'pam' -> map
test = 'enni' -> nine
test = 'yfunn' -> funny
Now applying this logic, adapting for your case of 10, 11, and 12 letter words should be relatively simple. Cheers!

Randomize the letters in the middle of the word, while keeping the first and last letters unchanged

import java.util.Scanner;
/**
*
* #author Cutuk
*/
public class JavaApplication3 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String a;
Scanner in = new Scanner (System.in);
a = in.nextLine();
char first = a.charAt(0);
System.out.print(first);
int v= a.length()-1;
char last = a.charAt(v);
int k= a.length();
int random=0;
char x='\u0000';
char middle= '\u0000' ;
for (int i=1; i<a.length()-1;i++){
random= (int )(Math.random() * (k-2) + 1);
middle=a.charAt(random);
x=middle;
System.out.print(x);
}
System.out.print(last);
}
}
I am supposed to take a word, shuffle the letters inside, but keep the first and the last letter unchanged. I managed to randomize, but I cannot keep it from repeating.
Your approach is incorrect: when you pick middle letters at random, it is impossible to guarantee that all letters from the middle of the word would be printed (and as a consequence, that other letters would not be repeated).
There are several ways of fixing this:
Each time you generate a random index, mark that index in an array of booleans. The length of the array is equal to the length of the word. Check the array before using each new index that you generate; if the index is marked, continue generating new random indexes until you hit an empty one.
Create an array of integer indexes of letters inside the word (i.e. 1 through length-1, inclusive). Do a random shuffle on the array, and use the shuffled indexes to pick middle letters.
Similar to 2, except you put all middle letters in an array, and shuffle it.
If I understand your question, I would suggest you start by building a List<Character> and then use Collections.shuffle(List) and finally build your return String with a StringBuilder like
private static String shuffleLetters(String in) {
if (in == null || in.length() < 3) {
return in;
}
char first = in.charAt(0);
char last = in.charAt(in.length() - 1);
List<Character> chars = new ArrayList<>();
for (char ch : in.substring(1, in.length() - 1).toCharArray()) {
chars.add(ch);
}
Collections.shuffle(chars);
StringBuilder sb = new StringBuilder();
sb.append(first);
for (char ch : chars) {
sb.append(ch);
}
sb.append(last);
return sb.toString();
}
Assuming "shuffling" can allow a middle character to sometimes be swapped with itself, you can do something like:
private static final String[] TEST_WORDS = {"apple", "banana", "pear", "raspberry", "cucumber", "watermelon", "a", "ab", "", null};
public static void main(String[] args)
{
for (String word: TEST_WORDS)
{
System.out.println(shuffleInside(word));
}
}
private static String shuffleInside(String word)
{
String ret = word;
if (word != null)
{
Random r = new Random();
int strLen = word.length();
if (strLen > 2)
{
char[] middleChars = word.substring(1, strLen - 1).toCharArray();
shuffle(middleChars, r);
ret = word.charAt(0) + new String(middleChars) + word.charAt(strLen - 1);
}
}
return ret;
}
private static void shuffle(char[] chars, Random r)
{
for (int i = chars.length - 1; i > 0; i--)
{
int index = r.nextInt(i + 1);
char c = chars[index];
chars[index] = chars[i];
chars[i] = c;
}
}
Which handles the case where the word is null, one character, two characters, or two or more characters and produces the following output on a single run:
apple
bnaana
paer
rerrsbpay
cbuemucr
waomteerln
a
ab
null
You could simply create a List<Integer> for storing the random numbers that you generated.
Here is your code from above, cleaned up, with meaningful naming and the List for looking up the history:
public class Main {
public static void main(String[] args) {
final Scanner in = new Scanner(System.in);
final Random rnd = new Random(System.currentTimeMillis());
final List<Integer> rndHistory = new LinkedList<>(); // <-- your history
System.out.print("Please type a word: ");
final String input = in.nextLine();
System.out.print(input.charAt(0));
for (int i = 1, random = 0; i < input.length() - 1; i++) {
do {
random = rnd.nextInt(input.length() - 2) + 1;
} while (rndHistory.contains(random)); // check the history
rndHistory.add(random); // add to the history
System.out.print(input.charAt(random));
}
System.out.println(input.charAt(input.length() - 1));
}
}
Main differences:
final Random rnd = new Random(System.currentTimeMillis()); Using
the the java.util.Random class is a better way for generating
random numbers.
final List<Integer> rndHistory = new LinkedList<>(); This is the actual difference, part of the mechanism to prevent double shuffles
System.out.print("Please type a word: "); a meaningful prompt for
the user (who is going to know what to do, when you program is
executed and there is nothing on the screen?)
and finally:
do {
random = rnd.nextInt(input.length() - 2) + 1;
} while (rndHistory.contains(random)); // check the history
rndHistory.add(random); // add to the history
The 'prevent a random number from being used twice' mechanics
For your random try this: Random generator = new Random(System.currentTimeMillis());

How to check for equal words in string array in JAVA

This should be quite simple (I think), but I just can't get it right...:|
The task is as follows:
Ask the user for some input. The input must be split in to single words and put into an array. All words should be counted. If equal words exists, they get a "+1" on the output.
Finally I want to print out and hopefully the right amount of counted words in a list. I got the first two columns right, but the word-counter of equal words gave me a headache. If a word is found to be equal, it mustnt appear twice in the generated list! :!
I am a complete JAVA newbie so please be kind on the code-judging. ;)
Here is my code so far:
package MyProjects;
import javax.swing.JOptionPane;
public class MyWordCount {
public static void main(String[] args) {
//User input dialog
String inPut = JOptionPane.showInputDialog("Write som text here");
//Puts it into an array, and split it with " ".
String[] wordList = inPut.split(" ");
//Print to screen
System.out.println("Place:\tWord:\tCount: ");
//Check & init wordCount
int wordCount = 0;
for (int i = 0; i < wordList.length; i++) {
for (int j = 0; j < wordList.length; j++){
//some code here to compare
//something.compareTo(wordList) ?
}
System.out.println(i + "\t" + wordList[i]+ "\t" + wordCount[?] );
}
}
}
You can use Hashmap to do that. A Hashmap stores key-value pairs and each key has to be unique.
So in your case, a key will be a word of the string you have split and value will be it's count.
Once you have split the input into words and put them into a string array, put the first word,as a key, into the Hashmap and 1 as it's value. For each subsequent word, you can use the function containsKey() to match that word with any of the existing keys in the Hashmap. If it returns true, increment the value (count) of that key by one, else put the word and 1 as a new key-value pair into the Hashmap.
So in order to compare two strings, you do:
String stringOne = "Hello";
String stringTwo = "World";
stringOne.compareTo(stringTwo);
//Or you can do
stringTwo.compareTo(stringOne);
You can't compare a String to a String array like in your comment. You would have to take an element in this string array, and compare that (So stringArray[elementNumber]).
For counting how many words there are, if you are determining the number of repeated words, you would want to have an array of integers (So make a new int[]). Each place in the new int[] should correspond to the word in your array of words. This would allow you to count the number of times a word is repeated.
import java.util.ArrayList;
import java.util.regex.PatternSyntaxException;
import javax.swing.JOptionPane;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
//Print to screen
System.out.println("Place:\tWord:\tCount: ");
//User input dialog
String inPut = JOptionPane.showInputDialog("Write som text here");
//Puts it into an array, and split it with " ".
String[] wordList;
try{
wordList = inPut.split(" ");
}catch(PatternSyntaxException e) {
// catch the buggy!
System.out.println("Ooops.. "+e.getMessage());
return;
}catch(NullPointerException n) {
System.out.println("cancelled! exitting..");
return;
}
ArrayList<String> allWords = new ArrayList<String>();
for(String word : wordList) {
allWords.add(word);
}
// reset unique words counter
int uniqueWordCount = 0;
// Remove all of the words
while(allWords.size() > 0) {
// reset the word counter
int count = 0;
// get the next word
String activeWord = allWords.get(0);
// Remove all instances of this word
while(doesContainThisWord(allWords, activeWord)) {
allWords.remove(activeWord);
count++;
}
// increase the unique word count;
uniqueWordCount++;
// print result.
System.out.println(uniqueWordCount + "\t" + activeWord + "\t" + count );
}
}
/**
* This function returns true if the parameters are not null and the array contains an equal string to newWord.
*/
public static boolean doesContainThisWord(ArrayList<String> wordList, String newWord) {
// Just checking...
if (wordList == null || newWord == null) {
return false;
}
// Loop through the list of words
for (String oldWord : wordList) {
if (oldWord.equals(newWord)) {
// gotcha!
return true;
}
}
return false;
}
}
Here's a solution using a map of WordInfo objects that records locations of the words within the text and uses that as a count. The LinkedHashMap preserves the order of keys from when they are first entered so simply iterating through the keys gives you the "cast in order of appearance"
You can make this case insensitive while preserving the case of the first appearance by storing all keys as lower case but storing the original case in the WordInfo object. Or just convert all words to lower case and leave it at that.
You may also want to think about removing all , / . / " etc from the first text before splitting, but you'll never get that perfect anyway.
import java.util.LinkedHashMap;
import java.util.Map;
import javax.swing.JOptionPane;
public class MyWordCount {
public static void main(String[] args) {
//User input dialog
String inPut = JOptionPane.showInputDialog("Write som text here");
Map<String,WordInfo> wordMap = new LinkedHashMap<String,WordInfo>();
//Puts it into an array, and split it with " ".
String[] wordList = inPut.split(" ");
for (int i = 0; i < wordList.length; i++) {
String word = wordList[i];
WordInfo wi = wordMap.get(word);
if (wi == null) {
wi = new WordInfo();
}
wi.addPlace(i+1);
wordMap.put(word,wi);
}
//Print to screen
System.out.println("Place:\tWord:\tCount: ");
for (String word : wordMap.keySet()) {
WordInfo wi = wordMap.get(word);
System.out.println(wi.places() + "\t" + word + "\t" + wi.count());
}
}
}
And the WordInfo class:
import java.util.ArrayList;
import java.util.List;
public class WordInfo {
private List<Integer> places;
public WordInfo() {
this.places = new ArrayList<>();
}
public void addPlace(int place) {
this.places.add(place);
}
public int count() {
return this.places.size();
}
public String places() {
if (places.size() == 0)
return "";
String result = "";
for (Integer place : this.places) {
result += ", " + place;
}
result = result.substring(2, result.length());
return result;
}
}
Thanks for trying to help me. -This is what I ended up doing:
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class MyWordCount {
public static void main(String[] args) {
// Text in
String inText = JOptionPane.showInputDialog("Write some text here");
// Puts it into an array, and splits
String[] wordlist = inText.split(" ");
// Text out (Header)
System.out.println("Place:\tWord:\tNo. of Words: ");
// declare Arraylist for words
ArrayList<String> wordEncounter = new ArrayList<String>();
ArrayList<Integer> numberEncounter = new ArrayList<Integer>();
// Checks number of encounters of words
for (int i = 0; i < wordlist.length; i++) {
String word = wordlist[i];
// Make everything lowercase just for ease...
word = word.toLowerCase();
if (wordEncounter.contains(word)) {
// Checks word encounter - return index of word
int position = wordEncounter.indexOf(word);
Integer number = numberEncounter.get(position);
int number_int = number.intValue();
number_int++;
number = new Integer(number_int);
numberEncounter.set(position, number);
// Number of encounters - add 1;
} else {
wordEncounter.add(word);
numberEncounter.add(new Integer(1));
}
}
// Text out (the list of words)
for (int i = 0; i < wordEncounter.size(); i++) {
System.out.println(i + "\t" + wordEncounter.get(i) + "\t"
+ numberEncounter.get(i));
}
}
}

Categories

Resources