I have seen many resources from the internet but couldn't found the exact help. i am trying to figure out the edit distance between the two strings example:
String a = "put return between paragraph gioo";
String b = "put hello between line phone gio";
here I am always comparing with String a with the other string so here the edit distance should be 4.
I have done some code execution its comparing me with the each character in the string.
int len1 = row10.length();
int len2 = row01.length();
int[][] dp = new int[len1 + 1][len2 + 1];
for (int i = 0; i <= len1; i++) {
dp[i][0] = i;
}
for (int j = 0; j <= len2; j++) {
dp[0][j] = j;
}
for (int i = 0; i < len1; i++) {
char c1 = row10.charAt(i);
for (int j = 0; j < len2; j++) {
char c2 = row01.charAt(j);
if (c1 == c2) {
dp[i + 1][j + 1] = dp[i][j];
} else {
int replace = dp[i][j] + 1;
int insert = dp[i][j + 1] + 1;
int delete = dp[i + 1][j] + 1;
int min = replace > insert ? insert : replace;
min = delete > min ? min : delete;
dp[i + 1][j + 1] = min;
}
}
}
System.out.println(dp[len1][len2]);
Made a sample function. It doesn't really take into the consideration of corner cases but it works. Also, do think about the case sensitivity of the words.
package test;
public class CalcWordDiff {
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "My name is ABC.";
String b = "My name xyz.";
System.out.println("Edit distance will be : "+calcDistanceBetweenWords(a,b));
}
public static int calcDistanceBetweenWords(String first, String second)
{
int res = 0;
String[] words_string_first = first.trim().split(" "); // By trim, I removed the Whitespaces if they exist
String[] words_string_second = second.trim().split(" ");
//Check the length of both the arrays
System.out.println("Size of arrays first is : "+words_string_first.length);
System.out.println("Size of arrays second is : "+words_string_second.length);
int lowerWordSentSize = 0;
if(words_string_first.length<=words_string_second.length)
{
lowerWordSentSize = words_string_first.length;
}
else
{
lowerWordSentSize = words_string_second.length;
}
//Now iterate through the array of lower size
for(int i = 0; i< lowerWordSentSize; i++)
{
if(words_string_first[i].equals(words_string_second[i]))
{
//Do nothing, it means both the words are same
}
else
{
System.out.println("Words mismatched at "+(i+1)+" th Position.");
res = i;
}
}
return res;
}
}
Related
I want to calculate the frequency of the occurrence of all the operators from an input text file. The file contains the operators + and ++. How can I distinguish their respective frequency, as my program treats ++ as 2 distinct + operators rather than 1 ++?
Here is my code (input7.txt is a test file):
public static void main(String[] args) throws IOException {
String string = new String(Files.readAllBytes(Paths.get("input7.txt"))); //String to be counted
int frequencyArray[] = new int[string.length()];
int frequencyArray2[] = new int[string.length()];
char stringArray[] = string.toCharArray(); //Array of characters
int i, j;
//Count characters
for (i = 0; i < string.length(); i++) {
frequencyArray[i] = 1;
//frequencyArray2[i] = 1;
for(j = i + 1; j < string.length(); j++)
{
if(stringArray[i] == stringArray[j])
{
frequencyArray[i]++;
stringArray[j] = '0'; //To avoid revisiting a character
}
}
}
//Display results
System.out.println("Characters and their corresponding frequencies");
for (i = 0; i < frequencyArray.length; i++) {
if (stringArray[i] != ' ' && stringArray[i] != '0') {
System.out.println(stringArray[i] +"-" + frequencyArray[i]);
}
}
}
This works for me:
String s = "sdfasd++ sdfadsf+asdf sdf++sadfasdf++sadfsdf+asdfasdf++";
// create Set with all distinct characters
Set<Character> chars = new HashSet<Character>();
for (int i = 0; i < s.length(); i++) {
chars.add(s.charAt(i));
}
// count distinct characters and put Results in HashMap
Map<Character, Integer> counts = new HashMap<Character, Integer>();
for (Character c : chars) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c)
count++;
}
counts.put(c, count);
}
// Count double-Character-Operators like this
int countPlusPlus = 0;
for (int i = 0; i < s.length() - 1; i++) {
if (s.substring(i, i + 2).equals("++"))
countPlusPlus++;
}
// Calculate totals like this
int singleplusTotal = counts.get('+');
System.out.println("Single Plus total" + singleplusTotal);
System.out.println("Double Plus total" + countPlusPlus);
System.out.println("Only single Plus" + (singleplusTotal - countPlusPlus * 2));
I'm trying to build a function, that gets a string of letters, and prints the amount of each letter in the string.
for example:
input: String = "aaabbaccxyxyx"
output: 4a2b2c3x2y
This is what I've come up with:
public class Q1 {
public static String numLetters(String s){
String end = new String();
int counter = 0;
char c,d;
for(int i=0; i<s.length();i++){
c = s.charAt(i);
for(int j=0; j<s.length();j++){
d = s.charAt(j);
if(c == d){
counter++;
}
}
end = end + counter+c;
counter = 0;
}
return end;
}
but, this is the output: 4a4a4a2b2b4a2c2c3x2y3x2y3x
A lot of repeats..
Any help how to make it right?
Keep in mind, the function needs to return a string, not just prints it out.
Thanks! =)
I would make an int array to keep the count of each letter in in the string. Because there are 26 letters, the length of the array should be 26:
public static String numLetters(String s) {
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
count[(int)(c - 'a')]++;
}
String ans = "";
for (int i = 0; i < 26; i++) {
if (count[i] != 0) {
ans += String.valueOf(count[i]) + (char)(i + 'a');
}
}
return ans;
}
A straightforward variant could look like this:
public static String countChars(String arg) {
String res = "";
boolean[] counted = new boolean[arg.length()];
for (int i = 0; i < counted.length; i++) {
if (!counted[i]) {
char c = arg.charAt(i);
int counter = 1;
for (int j = i + 1; j < counted.length; j++) {
if (arg.charAt(j) == c) {
counter++;
counted[j] = true;
}
}
res += counter + "" + c;
}
}
return res;
}
If you want to keep your original structure, I suggest using a StringBuilder so that you can delete characters that you have already seen. In case you delete a character, you have to adjust your indexes i and j.
public static String numLetters(String str){
StringBuilder s = new StringBuilder(s);
String end = new String();
int counter = 0;
char c,d;
for(int i=0; i<s.length();i++){
c = s.charAt(i);
for(int j=0; j<s.length();j++){
d = s.charAt(j);
if(c == d){
s.deleteCharAt(j);
if (i >= j) i--;
j--;
counter++;
}
}
end = end + counter+c;
counter = 0;
}
return end;
}
Try this:
int count = StringUtils.countMatches("a.b.c.d", ".");
This question already has answers here:
Counting the number of a certain letter appears in series of strings in an ArrayList
(4 answers)
Closed 6 years ago.
I have an ArrayList that stores strings, or notes, in the form of "walk the dog". I have a notes class with a method that prints the number of times each letter appears in the entire ArrayList. I'm supposed to declare and use a primitive array of ints of size 26 and turn each letter in the notebook into a char using the charAt method in the String class. Then I have to use that char to index into the appropriate location in the low-level array. This is my method so far but it's not finished:
public void printLetterDistribution() {
ArrayList<Integer> aList = new ArrayList<Integer>();
for (int i = 0; i < notes.size(); i++) {
String note = notes.get(i);
for (int j = 0; j < note.length(); j++) {
char letter = note.charAt(j);
int code = (int)letter;
aList.add(code);
}
}
Collections.sort(aList);
}
I've hit a wall and I don't know how to continue. As you can see, I've tried to convert the letters to their character code but it's probably not the best way to do it and I'm still getting stuck. Can anybody help?
EDIT - Here is the entire notes class:
public class Notebook {
private ArrayList<String> notes;
public Notebook() { notes = new ArrayList<String>(); }
public void addNoteToEnd(String inputnote) {
notes.add(inputnote);
}
public void addNoteToFront(String inputnote) {
notes.add(0, inputnote);
}
public void printAllNotes() {
for (int i = 0; i < notes.size(); i++) {
System.out.print("#" + (i + 1) + " ");
System.out.println(notes.get(i));
}
System.out.println();
}
public void replaceNote(int inputindex, String inputstring) {
int index = inputindex - 1;
if (index > notes.size() || index < 0) {
System.out.println("ERROR: Note number not found!");
} else {
notes.set(index, inputstring);
}
}
public int countNotesLongerThan(int length) {
int count = 0;
for (int i = 0; i < notes.size(); i++) {
String temp = notes.get(i);
if (temp.length() > length) {
count++;
}
}
return count;
}
public double averageNoteLength() {
int sum = 0;
for (int i = 0; i < notes.size(); i++) {
String temp = notes.get(i);
int length = temp.length();
sum += length;
}
double average = (double)(sum / notes.size());
return average;
}
public String firstAlphabetically() {
String min = "";
for (int i = 0; i < notes.size(); i++) {
for (int j = i + 1; j < notes.size(); j++) {
if ((notes.get(i)).compareTo(notes.get(j)) < 0) {
min = notes.get(i);
} else {
min = notes.get(j);
}
}
}
return min;
}
public void removeNotesBetween(int startnote, int endnote) {
int start = startnote - 1;
int end = endnote - 1;
for (int i = end - 1; i > start; i--) {
notes.remove(i);
}
}
public void printNotesContaining(String findString) {
for (int i = 0; i < notes.size(); i++) {
if (notes.get(i).contains(findString)) {
System.out.println("#" + i + " " + notes.get(i));
}
}
}
public int countNumberOf(String letter) {
int count = 0;
for (int i = 0; i < notes.size(); i++) {
String note = (notes.get(i));
for (int j = 0; j < note.length(); j++) {
if (note.charAt(j) == letter.charAt(0)) {
count++;
}
}
}
return count;
}
public void findAndReplaceFirst(String old, String newWord) {
for (int i = 0; i < notes.size(); i++) {
String note = notes.get(i);
if (note.contains(old)) {
int loc = note.indexOf(old);
int len = old.length();
String temp = note.substring(0, loc ) + note.substring(loc + len, note.length());
String newString = temp.substring(0, loc) + newWord + temp.substring(loc, temp.length());
notes.set(i, newString);
} else {
String newString = note;
notes.set(i, newString);
}
}
}
public void printLetterDistribution() {
int[] p = new int[26];
for (int i = 0; i < 26; i++) {
p[i] = 0;
}
for (int i = 0; i < notes.size(); i++) {
String note = notes.get(i);
note = note.toLowerCase();
for (int j = 0; j < note.length(); j++) {
char letter = note.charAt(j);
p[letter - 'a']++;
}
}
System.out.println(p);
}
}
You can use an int array of 26 length and increment the count of the index letter-'a';
int[] p = new int[26];
for(int i = 0; i < 26; i++) p[i] = 0;
for (int i = 0; i < notes.size(); i++) {
String note = notes.get(i);
for (int j = 0; j < note.length(); j++) {
char letter = note.charAt(j);
if(letter>= 'a' && letter <= 'z')
p[letter-'a']++;
}
PS: I am assuming that the notes are in lowercase only. If it is not the case, use note.toLowerCase() to make them lower.
Since in your notes you can have spaces, I have updated the code.
What I need to do is take a String array with each element having an exact length of 2, and find all possible combinations of the the elements, using each character within each String. By that I mean the String array {"Ss", "Ff"} returns "SF", "Sf", "sF", "sf". I have already tried a loop method that counts the iteration and then chooses a letter based on that, but it only works for arrays with a single element:
public String [] generatePossibilities(String [] s)
{
if(s[0].length() != 2)
throw new IllegalArgumentException();
String [] r = new String [s.length * 2];
for(int i = 0; i < r.length; i++)
{
r[i] = getPossibility(i, s);
}
return r;
}
private String getPossibility(int iteration, String [] source)
{
int [] choose = new int [source.length];
for(int i = 0; i < choose.length; i++)
{
choose[i] = 0;
}
for(int i = choose.length - 1; i >= 0; i--)
{
if(iteration < 1)
break;
choose[i] = 1;
iteration--;
}
String result = "";
for(int i = 0; i < source.length; i++)
result += source[i].substring(choose[i], choose[i] + 1);
return result;
}
Solved Thanks Sven!
public String [] generatePossibilities(String [] s)
{
if(s[0].length() != 2)
throw new IllegalArgumentException();
ArrayList<String> ra = new ArrayList<String>();
for(int i = s.length - 1; i >= 0; i--)
{
for(int j = 0; j < s[i].length(); j++)
{
String c = s[i].substring(j, j + 1);
if(ra.size() < 2)
{
ra.add(c);
}
else
{
for(int k = 0; k < ra.size(); k++)
{
String s1 = ra.get(k);
if(s1.substring(0, 1).equalsIgnoreCase(c))
continue;
else
{
s1 = c + s1;
ra.add(s1);
}
}
}
}
for(int j = 0; j < ra.size(); j++)
{
if(ra.get(j).length() != s.length - i)
{
ra.remove(j);
j--;
}
}
}
String [] r = new String [ra.size()];
for(int i = 0; i < r.length; i++)
{
r[i] = ra.get(i);
}
return r;
}
I would iterate the array of character tuples from last element to first. In each step you append to each current character the possibilities of the last iteration. You therefore double the elements in each step.
So for your example in the first iteration you have {Ff} and this would result to the two strings "F" and "f". In the next step you take each character of {Ss} and append each string of the last step to it getting "SF", "Sf", "sF" and "sf". You could then continue with further character tuples.
I have this problem, I need to generate from a given permutation not all combinations, but just those obtained after permuting 2 positions and without repetition. It's called the region of the a given permutation, for example given 1234 I want to generate :
2134
3214
4231
1324
1432
1243
the size of the region of any given permutation is , n(n-1)/2 , in this case it's 6 combinations .
Now, I have this programme , he does a little too much then what I want, he generates all 24 possible combinations :
public class PossibleCombinations {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Entrer a mumber");
int n=s.nextInt();
int[] currentab = new int[n];
// fill in the table 1 TO N
for (int i = 1; i <= n; i++) {
currentab[i - 1] = i;
}
int total = 0;
for (;;) {
total++;
boolean[] used = new boolean[n + 1];
Arrays.fill(used, true);
for (int i = 0; i < n; i++) {
System.out.print(currentab[i] + " ");
}
System.out.println();
used[currentab[n - 1]] = false;
int pos = -1;
for (int i = n - 2; i >= 0; i--) {
used[currentab[i]] = false;
if (currentab[i] < currentab[i + 1]) {
pos = i;
break;
}
}
if (pos == -1) {
break;
}
for (int i = currentab[pos] + 1; i <= n; i++) {
if (!used[i]) {
currentab[pos] = i;
used[i] = true;
break;
}
}
for (int i = 1; i <= n; i++) {
if (!used[i]) {
currentab[++pos] = i;
}
}
}
System.out.println(total);
}
}
the Question is how can I fix this programme to turn it into a programme that generates only the combinations wanted .
How about something simple like
public static void printSwapTwo(int n) {
int count = 0;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < n - 1;i++)
for(int j = i + 1; j < n; j++) {
// gives all the pairs of i and j without repeats
sb.setLength(0);
for(int k = 1; k <= n; k++) sb.append(k);
char tmp = sb.charAt(i);
sb.setCharAt(i, sb.charAt(j));
sb.setCharAt(j, tmp);
System.out.println(sb);
count++;
}
System.out.println("total=" + count+" and should be " + n * (n - 1) / 2);
}