David :
I would like to print the occurrence of each character in a text using a dictionary system:
Ex: Text is "I like apples"
Console output looks like:
'i' has an occurrence of 2 times on positions: 1, 4
'l' has an occurrence of 2 times on positions: 3, 11
..
So far I've got this
String text = "text";
HashMap<Integer, String> dictionary = new HashMap<Integer, String>();
for (int i = 0; i < text.length(); i++) {
dictionary.put(i, String.valueOf(text.charAt(i)));
}
Basically just adding each letter to a key value in the dictionary, but I can't figure out how to do the print...
Artanis :
This code uses a dictionary and prints the correct answer in the exact format requested:
import java.util.ArrayList;
import java.util.HashMap;
public class TestDriver {
public static void main(String[] args) {
String text = "i like apples";
char[] textArray = text.toCharArray();
//a dictionary that will hold the letter as the key and a list of it's positions as the value.
HashMap<Character, ArrayList<Integer>> dictionary = new HashMap<Character, ArrayList<Integer>>();
//loop through the text to check each letter
for (int i = 0; i < textArray.length; i++) {
//if you've already checked this letter, skip to the next one
if(dictionary.containsKey(textArray[i])) {
continue;
}
//add the letter's position to its position list
ArrayList<Integer> positionList = new ArrayList<>();
positionList.add(i);
//compare the remaining letters in the text to the current letter
for (int j = i+1; j < textArray.length; j++) {
//if a letter matches, add it's position to the list
if(textArray[i] == textArray[j]) {
positionList.add(j);
}
}
//add the letter and its list of positions to the dictionary
dictionary.put(textArray[i], positionList);
}
//format the response
for(char key : dictionary.keySet()) {
ArrayList<Integer> positions = new ArrayList<>();
positions = dictionary.get(key);
System.out.println(key + " has an occurance of " + positions.size() + " on positions: " + positions);
}
}
}
Prints to console:
has an occurance of 2 on positions: [1, 6]
p has an occurance of 2 on positions: [8, 9]
a has an occurance of 1 on positions: [7]
s has an occurance of 1 on positions: [12]
e has an occurance of 2 on positions: [5, 11]
i has an occurance of 2 on positions: [0, 3]
k has an occurance of 1 on positions: [4]
l has an occurance of 2 on positions: [2, 10]