What is alpha sampling parameter in Cybozu for language detection? - java

****I checked below code in Cybozu for alpha parameter and how they have used it. It Looks like will reduce the weight if you are reducing alpha **
private boolean updateLangProb(double[] prob, String word, double alpha) {
if (word != null && this.wordLangProbMap.containsKey(word)) {
double[] langProbMap = (double[])this.wordLangProbMap.get(word);
if (this.verbose) {
System.out.println(word + "(" + unicodeEncode(word) + "):" + this.wordProbToString(langProbMap));
}
double weight = alpha / 10000.0D;
for(int i = 0; i < prob.length; ++i) {
prob[i] *= weight + langProbMap[i];
}
return true;
} else {
return false;
}
}

Related

I don't understand how to properly work with NaN in Java [duplicate]

This question already has answers here:
How do you test to see if a double is equal to NaN?
(7 answers)
Closed 1 year ago.
I was wondering if anyone was able to understand the reason why this program doesn't return NaN the way it should.
I'm currently writing a program that calculates the solutions of a quadratic equation, but if the solutions are not real, I want it to print out "The solutions are not real" instead of NaN. Instead, it keeps on printing NaN nonetheless.
This is the code I've written:
import java.util.Scanner;
import java.lang.*;
public class QuadraticEquationTester {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Insert the value a of the following equation: a*x^(2)+b*x+c=0");
double a = Double.parseDouble(scan.nextLine());
System.out.println("Insert the value b of the following equation: a*x^(2)+b*x+c=0");
double b = Double.parseDouble(scan.nextLine());
System.out.println("Insert the value c of the following equation: a*x^(2)+b*x+c=0");
double c = Double.parseDouble(scan.nextLine());
scan.close();
QuadraticEquation equation1 = new QuadraticEquation(a, b, c);
equation1.getEquation();
System.out.println("Does this equation has solutions? " + equation1.hasSolutions());
System.out.println("How many solutions does this equation have? " + equation1.howManySolutions());
if (equation1.getSolution1() == Double.NaN && equation1.getSolution2() == Double.NaN) {
System.out.println("There are no real solutions");
}
if (equation1.getSolution1() != Double.NaN) {
System.out.println("The first solution is: " + equation1.getSolution1());
} else if (equation1.getSolution1() == Double.NaN) {
System.out.println("The first solution is not real");
}
if (equation1.getSolution2() != Double.NaN) {
System.out.println("The second solution is: " + equation1.getSolution2());
} else if (equation1.getSolution2() == Double.NaN) {
System.out.println("The second solution is not real");
}
if (equation1.getSolution1() != Double.NaN && equation1.getSolution2() != Double.NaN) {
System.out.println(equation1.getAllSolutions());
}
}
}
class QuadraticEquation {
// I'm initialing the variables
private double a;
private double b;
private double c;
private double delta;
// This is the basic constructor: it initializes the variables to zero
public QuadraticEquation() {
this.a = 0;
this.b = 0;
this.c = 0;
}
public QuadraticEquation(double aCoefficient, double bCoefficient, double cCoefficient) {
this.a = aCoefficient;
this.b = bCoefficient;
this.c = cCoefficient;
this.delta = (Math.pow(this.b, 2)) - 4 * this.a * this.c;
}
public void getEquation() {
System.out
.println("The equation we're going to solve is " + this.a + "*x^(2)+" + this.b + "*x+" + this.c + "=0");
}
public double getSolution1() {
double solution1 = (-this.b + (Math.sqrt(this.delta))) / (2 * this.a);
return solution1;
}
public double getSolution2() {
double solution2 = (-this.b - (Math.sqrt(this.delta))) / (2 * this.a);
return solution2;
}
public String getAllSolutions() {
double solution1 = (-this.b + (Math.sqrt(this.delta))) / (2 * this.a);
double solution2 = (-this.b - (Math.sqrt(this.delta))) / (2 * this.a);
return "The first solution is: " + solution1 + " while the second solution is: " + solution2;
}
public boolean hasSolutions() {
if (this.delta >= 0) {
return true;
} else if (this.delta < 0) {
return false;
}
return false;
}
public String howManySolutions() {
if (this.a == 0 && this.b == 0 && this.c != 0) {
return "0 Solutions";
} else if (this.a == 0 && this.b != 0) {
return "1 Solution";
} else if (this.a == 0 && this.b == 0 && this.c == 0) {
return "Infinite Solutions";
} else {
return "2 Solutions";
}
}
public static boolean isNaN(double v) {
if (v == Double.NaN) {
return true;
}
else return false;
}
}
You should use Double.isNaN(x) instead of comparing x == Double.NaN.
It's an interesting property of NaN that NaN != NaN. You can check this question for the reasons behind that.

Getting out of bounds error

so I'm testing out this piece of code, and when I read a file, the output when being printed halts and I get java.lang.ArrayIndexOutOfBoundsException: -1
at WordLengths.countWordLengthsWithIsLettermethod(WordLengths.java:126)
at WordLengths.testWordLengths(WordLengths.java:152).
I'm wondering if somewhere I inadvertently added a limit to how many results I get, otherwise I can't think of what could be wrong.
This is the bit that's causing trouble (max = freqs[i];):
public int maxIndex(int[] freqs) {
int max = freqs[0];
for (int i = 1; i < freqs.length; i++) {
if (freqs[i] > max) {
max = freqs[i];
}
}
System.out.println("max number of words of certain lengths: "+max);
return freqs[max];
//return max;
}
Here's the whole code with the problem area included:
import edu.duke.FileResource;
public class WordLengths {
public void countWordLengths(FileResource resource, int[] counts) {
String abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (String word : resource.words()) {
String trim = word.trim();
int wordSize = trim.length();
//System.out.println("word" + "\t" + trim);
int lastInd = trim.length()-1;
//System.out.println("lastIndexOf word" + "\t" + lastInd);
//abc.contains(trim.charAt(lastInd));
char firstChar = trim.charAt(0);
char endChar = trim.charAt(trim.length()-1);
//System.out.println("firstChar" + "\t" + firstChar + "\t" + "endChar" + "\t" + endChar);
int idx = abc.indexOf(firstChar);
int idx_e = abc.indexOf(endChar);
int edx_sum = idx + idx_e;
//System.out.println("indexes abc" + "\t" + edx_sum);
//int idx_s = small.indexOf(firstChar);
//int idx_s_e = small.indexOf(endChar);
//int edx_s_sum = idx_s + idx_s_e;
//System.out.println("indexes small" + "\t" + edx_s_sum);
//System.out.println("indexes" + "\t" + idx + "\t" + idx_e + "\t" + idx_s + "\t" + idx_s_e);
//System.out.println("indexes" + "\t" + idx + "\t" + idx_e + "\t");
if (idx == -1 && idx_e == -1) {
wordSize -= 2;
} else
if (idx == -1 || idx_e == -1) {
wordSize -= 1;
}
if(wordSize>=counts.length) {
counts[counts.length-1] += 1;
} else
//right algorithm
if( counts[wordSize] != 0) {
counts[wordSize] += 1;
} else {
counts[wordSize] = 1;
}
}
//test
/*for(int i : counts) {
System.out.println(i);
}*/
}
/**
* the method countWordLengths(FileResource resource, int[] counts) with isLetter method
*
* #param resource
* #param counts
*/
public void countWordLengthsWithIsLettermethod(FileResource resource, int[] counts) {
for (String word : resource.words()) {
String trim = word.trim();
int wordSize = trim.length();
char firstChar = trim.charAt(0);
char endChar = trim.charAt(trim.length()-1);
if (!Character.isLetter(firstChar) && !Character.isLetter(endChar)) {
wordSize -= 2;
} else
if (!Character.isLetter(firstChar) || !Character.isLetter(endChar)) {
wordSize -= 1;
}
if(wordSize>=counts.length) {
counts[counts.length-1] += 1;
} else
//right algorithm
if( wordSize> 0 && counts[wordSize] != 0 ) {
counts[wordSize] += 1;
} else if ( wordSize> 0) {
counts[wordSize] = 1;
}
System.out.println(counts[wordSize] + " words with length " + wordSize + ": " + word);
}
//test
/*for(int i : counts) {
System.out.println(i);
}*/
}
public int maxIndex(int[] freqs) {
int max = freqs[0];
for (int i = 1; i < freqs.length; i++) {
if (freqs[i] > max) {
max = freqs[i];
}
}
System.out.println("max number of words of certain lengths: "+max);
return freqs[max];
//return max;
}
public void testWordLengths() {
WordLengths wl = new WordLengths();
FileResource fr = new FileResource();
int counts[] = new int[100];
//wl.countWordLengths(fr, counts);
wl.countWordLengthsWithIsLettermethod(fr, counts);
wl.maxIndex(counts);
}
}
What do think would happen if the word was empty (or just filled with blanks)
String trim = word.trim();
int wordSize = trim.length();
char firstChar = trim.charAt(0);
char endChar = trim.charAt(trim.length()-1);

Printing a polynomial

I am trying to print a polynomial from a given number.
I did the example below, but for something like 100 it will print 1x^2+, when I want just x^2. What I'm looking for is how can I make it to not print + and at the same time get rid of coefficients that are 1.
Edit: I did it, it prints perfectly. Feel free to use it.
private static String S_frumos(int poli) {
String s = "";
for (int i = 0; i < String.valueOf(poli).length(); i++) {
int nr = Character.getNumericValue(S_GetCoefs(poli, i));
if (nr != 0) {
if (i == String.valueOf(poli).length() - 1) {
s = s + nr;
} else if (i == String.valueOf(poli).length() - 2) {
if ((S_zero(poli, i + 1) == 1)) {
if (nr != 1) {
s = s + nr + "x";
} else {
s = s + "x";
}
} else {
if (nr != 1) {
s = s + nr + "x" + "+";
} else {
s = s + "x" + "+";
}
}
} else if ((S_zero(poli, i + 1) == 1)) {
if (nr != 1) { s = s + nr + "x^" + (String.valueOf(poli).length() - i - 1);}
else { s = s + "x^" + (String.valueOf(poli).length() - i - 1);}
} else {
if (nr != 1){ s = s + nr + "x^" + (String.valueOf(poli).length() - i - 1) + "+";}
else { s = s + "x^" + (String.valueOf(poli).length() - i - 1) + "+";}
}
}
}
return s;
}
private static int S_GetCoefs(int poli, int x) {
return String.valueOf(java.lang.Math.abs(poli)).charAt(x);
}
To store something of an unknown length... then you can still use an int/double array, just gets slightly more complicated.
public static void main(String[] args)
{
// Say the size is given in a command line argument.
int coefficientNumber = Integer.parseInt(args[0]);
int[] poly = new int[coefficientNumber];
for (int i = 0; i < poly.length; i++)
{
poly[i] = 0;
}
// Set the highest coeffient to 1 (if there is 3 coefficients, this is coefficient
// of x^2, if 4 coefficients, this is coefficient of x^3
poly[0] = 1;
printPoly(poly);
}
// To print a polynomial of unknown length.
// If the coefficient is 0, don't print it.
private static void printPoly(int[] poly)
{
String output = "";
for (int index = 0; index < poly.length; index++)
{
if (poly[index] != 0)
{
// If this is the first coefficient with a value
if (output.length() == 0)
output = poly[index] + "x^" + (poly.length - (index + 1));
// Else if there is already some coefficient with values printed.
else
output += " + " + "x^" + (poly.length - (index + 1));
} // if
} // for
System.out.println(output);
} // printPoly
First of all, storing a polynomial in one variable isn't a great idea as if you have coefficients of more than 9 you'll get confused.
A better method imo (without making a polynomial class) is to store the polynomial in an int/double array.
public static void main(String[] args)
{
// To store the polynomial x^2, you could do the following:
int[] poly = new int[3];
poly[0] = 1;
poly[1] = 0;
poly[2] = 0;
printPoly(poly);
}
// To print it:
private static void printPoly(int[] poly)
{
String output = "";
if (poly[0] != 0)
output += poly[0] + "x^2"
if (poly[1] != 0)
{
if (output.size() > 0)
output += " + " + poly[1] + "^x";
else
output += poly[1] + "x";
}
if (poly[2] != 0)
{
if (output.size() > 0)
output += " + " + poly[2];
else
output += poly[2];
}
}

puzzling recursion with java

Given a string and a non-empty substring sub, compute recursively the largest substring which starts and ends with sub and return its length.
strDist("catcowcat", "cat") → 9
strDist("catcowcat", "cow") → 3
strDist("cccatcowcatxx", "cat") → 9
my solution
public int strDist(String str, String sub) {
int i = sub.length();
int j = str.length();
int count = 0;
if (str.length() == 1 && str.equals(sub)) {
return 1;
} else if (str.length() < sub.length() || str.length() <= 1) {
return 0;
}
if (str.substring(0, i).equals(sub)) {
if (str.substring(str.length() - i, str.length()).equals(sub)) {
return str.length();
} else {
strDist(str.substring(0, str.length() - i), sub);
}
} else {
strDist(str.substring(1, str.length()), sub);
}
return 0;
}
tell me how to correct my code?
Why does this need to be done with recursion?
Edit: fixed code to handle case where sub is not present in str, or only present once.
public int strDist(String str, String sub) {
int last=str.lastIndexOf(sub);
if (last != -1) {
int first=str.indexOf(sub);
if (first != last)
return last - first + sub.length();
}
}
return 0;
}
Recursion is great, if it is suited to the problem. In this case, recursion doesn't add value, and writing it with recursion for the sake of recursion makes the code inefficient.
This will , "compute recursively the largest substring which starts and ends with sub and return its length" as you described.
public class PuzzlingRecursion {
static String substringFound = "";
public static void main(String[] args) {
String sentence = "catcowcat";
String substring = "cat";
int sizeString = findNumberOfStrings(sentence, substring, 0);
System.out.println("you are searching for: " + substring);
System.out.println("in: " + sentence);
System.out.println("substring which starts and ends with sub and return its length is:"+substringFound + ", " + sizeString);
}
private static int findNumberOfStrings(String subStringPassed,
String setenecePassed, int count) {
if (subStringPassed.length() == 0) {
return count + 0;
}
if (subStringPassed.length() < setenecePassed.length()) {
return count + 0;
}
count++;
String lastStringMiddle = subStringPassed.replaceAll("(.*?)" + "("
+ setenecePassed + ")" + "(.*?)" + "(" + setenecePassed + ")"
+ "(.*?.*)", "$3");
if (subStringPassed.contains(setenecePassed)
&& lastStringMiddle.length() != setenecePassed.length()) {
if (subStringPassed.contains(setenecePassed)
&& lastStringMiddle.contains(setenecePassed)) {
// only found one item no pattern but according to the example
// you posted it should return the length of one word/substring
count = setenecePassed.length();
substringFound = subStringPassed;
return count;
}
}
// makesure the lastSrtringMiddle has the key we are search
if (!lastStringMiddle.equals(subStringPassed)) {
subStringPassed = subStringPassed.replaceFirst(setenecePassed, "");
String lastString = subStringPassed.substring(0,
subStringPassed.lastIndexOf(setenecePassed));
if (null != lastString && !"".equals(lastString)) {
count = lastStringMiddle.length() + setenecePassed.length()
+ setenecePassed.length();
substringFound = setenecePassed + lastStringMiddle
+ setenecePassed;
subStringPassed = "";
}
return findNumberOfStrings(subStringPassed, setenecePassed, count);
}
return count;
}
}
I think this is much nicer recursive solution:
public int strDist(String str, String sub) {
if (str.length()==0) return 0;
if (!str.startsWith(sub))
return strDist(str.substring(1),sub);
if (!str.endsWith(sub))
return strDist(str.substring(0,str.length()-1),sub);
return str.length();
}

Adding duplicates in an ArrayList

I am stuck on how to find duplicate entries in an ArrayList and then manipulate them. I am implementing a polynomial class and I want to add monomials of the same order to create a new polynomial. Monomials have a degree and a coefficient. I want to cycle through a collection of monomials and find the monomials that have the same power and add the coefficients. The sum of all these like powered monomials will be the polynomial.
ArrayList (or any List) accepts duplicates.
However, since you want to group Monomials by their power, you might consider using a Map<Integer,Foo> where the key is the power. Foo has a lot of options. Foo could be an ArrayList<Monomial>, an ArrayList<Double>, holding only the coefficiants, that you add later. This requires some code writing on your part or else using a 3rd partly library for a MultiMap.
Or, Foo could be a Double which represents the summed coefficient, in which case you need to write an add(Monomial) method which updates the Double everytime.
If the possible range of powers is small and known, you could use a simple array too.
Here's my solution, you can add two polynomials of the same degree. Watch for bugs.
public class Polynome {
private double[] coefficients;
private int degre;
public Polynome(int degre) {
if (degre < 0) {
System.out.println("Invalid Degree");
}
this.degre = degre;
coefficients = new double[degre + 1];
for (int i = 0; i < degre; i++)
coefficients[i] = 0;
coefficients[degre] = 1;
}
public void setCoefficient(int degre, double coefficient) {
if (degre < 0 || degre > this.degre) {
System.out.println("Invalid Degree");
}
if (coefficient == 0 && degre == this.degre && this.degre != 0) {
System.out.println("Null Degree");
}
coefficients[degre] = coefficient;
}
/*
* Returns the coeff giving the degree of the element
*/
public double getCoefficient(int degre) {
if (degre < 0 || degre > this.degre) {
return 0;
}
if (degre == this.degre && this.degre != 0) {
return coefficients[this.getDegre()];
}
return this.coefficients[degre];
}
public String ToString() {
if (degre == 0)
return "" + this.coefficients[0];
String result = "" + this.coefficients[degre]+" x^" + degre;
for (int i = degre-1 ; i > 0 ; i--){
if (this.coefficients[i] < 0) {
result += "-" + Math.abs(this.coefficients[i]) + " x^" + i;
}
else {
if (this.coefficients[i] > 0){
result += " + " + this.coefficients[i] + " x^" + i;
}
}
}
if (this.coefficients[0]!= 0) result += " + " + this.coefficients[0] ;
return result;
}
/*
* Returns the degree of the current poly
*/
public int getDegre() {
return degre;
}
/*
* Adds two Polys with the same degrees
*/
public Polynome add(Polynome p) {
Polynome result = new Polynome(p.getDegre());
int deg = result.getDegre();
for(int i = deg ; i >0 ; i--) {
result.coefficients[i] = this.getCoefficient(i) + p.getCoefficient(i);
}
return result;
}
public static void main(String...args) {
Polynome p = new Polynome(2);
p.setCoefficient(2, 7);
Polynome p1 = new Polynome(2);
p1.setCoefficient(2, 2);
System.out.println(p.ToString() + "\n" + p1.ToString() + "\n\n" + (p.add(p1)).ToString());
}
}

Categories

Resources