how to increase the count of frequently occuring words using java - java

Hi below is my program which displays top 10 frequently occuring words but my requirement is to get top 30 frequently occuring words,
class FrequencyCount {
int[][] table = new int[4][1000000];
TreeMap<Integer, List<String>> map = new TreeMap<Integer, List<String>>(
Collections.reverseOrder());
public static void main(String[] args) throws Exception {
FrequencyCount freq = new FrequencyCount();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File(
"C:/portable.pdf")));
String fileline = br.readLine();
System.out.println("fileline:" + fileline);
while (fileline != null) {
if (fileline.length() > 0) {
String[] sArr = fileline.split(" ");
for (String s : sArr) {
int flag = 1;
for (int j = 0; j < stopwords.length; j++) {
String s1 = s.toLowerCase();
}
if (flag != 0) {
if (s.trim().length() > 0) {
try {
freq.add(freq.trimStr(s));
} catch (ArrayIndexOutOfBoundsException e) {
}
}
}
}
}
fileline = br.readLine();
}
Set<Integer> set = freq.map.keySet();
for (Integer x : set) {
System.out.println(freq.map.get(x) + " found " + x + " times");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
}
}
public String trimStr(String s) {
if (s.toUpperCase().equals(s.toLowerCase())) {
return s;
}
s = s.toLowerCase().trim();
if (s.endsWith("'s")) {
s = s.substring(0, s.length() - 2);
}
int i = 0;
int j = s.length() - 1;
char[] cArr = s.toCharArray();
while (!(cArr[i] >= 65 && cArr[i] <= 90)
&& !(cArr[i] >= 97 && cArr[i] <= 122)) {
i++;
}
while (!(cArr[j] >= 65 && cArr[j] <= 90)
&& !(cArr[j] >= 97 && cArr[j] <= 122)) {
j--;
}
return s.substring(i, j + 1);
}
public int[] hash(String s) {
int h1 = hash1(s);
int h2 = hash2(s);
int h3 = hash3(s);
int h4 = hash4(s);
int[] res = new int[] { h1, h2, h3, h4 };
return res;
}
public int hash1(String x) {
char ch[] = x.toCharArray();
int i, sum;
for (sum = 0, i = 0; i < x.length(); i++)
sum += ch[i];
return sum % 1000000;
}
public int hash2(String s) {
int h = 0;
for (int i = 0; i < s.length(); i++) {
h = 31 * h + s.charAt(i);
}
h = h % 1000000;
if (h < 0) {
h = -h;
}
return h;
}
public int hash3(String s) {
int h = 0;
for (int i = 0; i < s.length(); i++) {
h = 17 * h + s.charAt(i);
}
h = h % 1000000;
if (h < 0) {
h = -h;
}
return h;
}
public int hash4(String s) {
int h = 0;
for (int i = 0; i < s.length(); i++) {
h = 11 * h + s.charAt(i);
}
h = h % 1000000;
if (h < 0) {
h = -h;
}
return h;
}
public void add(String s) {
int[] h = hash(s);
table[0][h[0]] = table[0][h[0]] + 1;
table[1][h[1]] = table[1][h[1]] + 1;
table[2][h[2]] = table[2][h[2]] + 1;
table[3][h[3]] = table[3][h[3]] + 1;
int r = Math.min(Math.min(Math.min(table[0][h[0]], table[1][h[1]]),
table[2][h[2]]), table[3][h[3]]);
boolean add = true;
List<String> list = map.get(r);
if (list == null) {
if (map.size() == 10) {
Integer lastKey = map.lastKey();
if (lastKey.intValue() > r) {
add = false;
} else {
map.remove(lastKey);
}
}
list = new ArrayList<String>();
}
if (add) {
list.add(s);
map.put(r, list);
if (r > 1) {
list = map.get(r - 1);
if (list != null) {
if (list.size() == 1) {
map.remove(r - 1);
} else {
list.remove(s);
}
}
}
}
}
public int count(String s) {
int[] h = hash(s);
int a = table[0][h[0]];
int b = table[1][h[1]];
int c = table[2][h[2]];
int d = table[3][h[3]];
int r = Math.min(Math.min(Math.min(a, b), c), d);
return r;
}
}
I have changed the map size to 30, but its not working, please suggest me how to get top 30 frequently occurring words.
Thanks

I would use a different approach. I would add store the word in a HashMap instead and use the string in lowercase as key and then number of time it occured as the value. When the entire map is created you can sort it as described here and display any number from the top as you like.
The general idea:
HashMap<String, Integer> wordcounter = new HashMap<String, Integer>();
if (wordcounter.containsKey(s))
wordcounter.put(s, wordcounter.get(s) + 1);
else
wordcounter.put(s, 1);

There is only one word change from 10 to 30 as mentioned below.
public void add(String s) {
int[] h = hash(s);
table[0][h[0]] = table[0][h[0]] + 1;
table[1][h[1]] = table[1][h[1]] + 1;
table[2][h[2]] = table[2][h[2]] + 1;
table[3][h[3]] = table[3][h[3]] + 1;
int r = Math.min(Math.min(Math.min(table[0][h[0]], table[1][h[1]]),
table[2][h[2]]), table[3][h[3]]);
boolean add = true;
List<String> list = map.get(r);
if (list == null) {
if (map.size() == 30) {//Changed from 10 to 30
Integer lastKey = map.lastKey();
if (lastKey.intValue() > r) {
add = false;
} else {
map.remove(lastKey);
}
}
list = new ArrayList<String>();
}
if (add) {
list.add(s);
map.put(r, list);
if (r > 1) {
list = map.get(r - 1);
if (list != null) {
if (list.size() == 1) {
map.remove(r - 1);
} else {
list.remove(s);
}
}
}
}
}

Related

Ant colony optimization for TSP not getting the shortest path

I have implemented the algorithm according to this paper it's working well, but for certain tests, it doesn't get the shortest path,
here's the pseudo-code
Initialize
For t=1 to iteration number do
For k=1 to l do
Repeat until ant k has completed a tour
Select the city j to be visited next
With probability pij given by Eq. (1)
Calculate Lk
Update the trail levels according to Eqs. (2-4).
End
here's the code
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class test2 {
private InputReader cin;
private PrintWriter cout;
double pheromones[][];
double distances[][];
double visibility[][];
static int n;
City[] city;
Ant[] ant;
int m;
int T;
double alpha = 1; // pheromone importance
double beta = 2; // visibility importance
double evaporation = 0.1;
double Q = 100.0;
static class City {
double x, y;
int id;
public City(double x, double y, int id) {
this.x = x;
this.y = y;
this.id = id;
}
}
static class Ant {
int whereAmI;
boolean[] visited;
double tourDistance;
LinkedList<Integer> citiesVisitedInOrder;
int cityEdges[][];
Ant(int whereAmI) {
this.whereAmI = whereAmI;
visited = new boolean[n + 1];
cityEdges = new int[n + 1][n + 1];
reset();
}
void reset() {
Arrays.fill(visited, false);
visited[whereAmI] = true;
for (int i = 1; i <= n; i++)
Arrays.fill(cityEdges[i], 0);
tourDistance = 0;
citiesVisitedInOrder = new LinkedList<>();
citiesVisitedInOrder.addLast(whereAmI);
}
}
//the actual algorithm iteration
/*
Initialize
For t=1 to iteration number do
For k=1 to l do
Repeat until ant k has completed a tour
Select the city j to be visited next
With probability pij given by Eq. (1)
Calculate Lk
Update the trail levels according to Eqs. (2-4).
End
*/
private void solve() {
n = cin.readInt();
initializeParameter();
//the main loop
for (int t = 0; t < T; t++) {
for (int i = 0; i < m; i++) {//for each ant
Ant current = ant[i];
for (int j = 0; j < n; j++) {//for each city
int currentAntsCity = current.whereAmI;
double highestProbability = 0;
int cityId = 1;
double sumNotiation = calculateSum(current.visited, currentAntsCity);
//traverse all non-visited cities and choose the best
boolean good = false;
for (int c = 1; c <= n; c++) {//remove the equal
if (!current.visited[c]) {
double prop = (pow(pheromones[currentAntsCity][c], alpha) * pow(visibility[currentAntsCity][c], beta))
/ sumNotiation;
if (prop >= highestProbability) {
highestProbability = prop;
cityId = c;
good = true;
}
}
}
if (good) {
current.tourDistance += distances[currentAntsCity][cityId];
current.cityEdges[currentAntsCity][cityId] = current.cityEdges[cityId][currentAntsCity] = 1;
current.citiesVisitedInOrder.addLast(cityId);
current.whereAmI = cityId;
current.visited[cityId] = true;
}
}//after n iteration i ant completes a tour
current.tourDistance += distances[current.citiesVisitedInOrder.getFirst()][current.citiesVisitedInOrder.getLast()];
}//update
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
double deltaPhermons = 0;
for (int a = 0; a < m; a++) {
if (ant[a].cityEdges[i][j] != 0) {
deltaPhermons += Q / ant[a].tourDistance;
}
}
pheromones[i][j] = pheromones[j][i] = pheromones[i][j] * evaporation + deltaPhermons;
pheromones[i][i] = 0;
}
}
if (t == T - 1)
break;
//reset everything
for (int i = 0; i < m; i++) {
ant[i].reset();
}
}
//get the best ant route
double minDistance = Double.MAX_VALUE;
LinkedList<Integer> minRout = new LinkedList<>();
for (Ant ant : ant) {
if (ant.tourDistance < minDistance) {
minDistance = ant.tourDistance;
minRout = ant.citiesVisitedInOrder;
}
}
cout.println(minDistance);
for (int element : minRout)
cout.print(element + " ");
}
private double calculateSum(boolean[] visited, int currentAntsCity) {
//traverse all non-visited cities
double ans = 0.0;
for (int c = 1; c <= n; c++) {
if (!visited[c]) {
ans +=
pow(pheromones[currentAntsCity][c], alpha) *
pow(visibility[currentAntsCity][c], beta);
}
}
return ans;
}
private void initializeParameter() {
m = 2 * n;
T = 4 * m;
city = new City[n + 1];
pheromones = new double[n + 1][n + 1];
distances = new double[n + 1][n + 1];
visibility = new double[n + 1][n + 1];
//read cities coordinates
for (int i = 1; i <= n; i++) {
city[i] = new City(cin.readDouble(), cin.readDouble(), i);
}
//initialize distances
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
distances[i][j] = distances[j][i] = sqrt(pow(city[i].x -
city[j].x, 2.0) + pow(city[i].y -
city[j].y, 2.0));
}
}
//initialize the pheromones
double pheromones0 = 1.0 / (double) n;
for (int i = 1; i <= n; i++) {
Arrays.fill(pheromones[i], pheromones0);
pheromones[i][i] = 0;
}
//initialize the visibility
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
visibility[i][j] = visibility[j][i] = 1.0 / distances[i][j];
}
}
//initialize the ants
ant = new Ant[m];
Random rand = new Random(); //instance of random class for
for (int i = 0; i < m; i++) {
int random_int = rand.nextInt(n) + 1;
ant[i] = new Ant(random_int);
}
}
public static void main(String args[]) {
new test2().run();
}
private void run() {
// cin = new InputReader(System.in);
// cout = new PrintWriter(System.out);
try {
cin = new InputReader(new FileInputStream("input.txt"));
cout = new PrintWriter(new FileOutputStream("output.txt"));
} catch (FileNotFoundException e) {
//System.out.println(e.toString());
}
solve();
cout.close();
}
//just for faster reading from a file
public static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
the test case
10
-15 89
-5 -49
-35 -18
7 49
-95 -68
85 -39
53 -1
69 -99
-74 8
-52 -35
the right answer:
615.11811789868988853
1 9 5 10 3 2 8 6 7 4
my coes's output:
685.2134200307595
5 9 10 3 2 8 6 7 4 1
as you can notice I am not getting the shortest path, I believe that the mistake is somewhere in the constant, and the probability comparing!
the formula I have implemented
and the update formulas
how can I improve the algorithm accuracy? or maybe there's something wrong in my implementation!
I found the solution, Changing the Update functions after each complete tour for all ants, fixed the problem:
#part 1
//the elaboration presses after a complete tour for all ants
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
pheromones[i][j] *= evaporation;
if (pheromones[i][j] < 1.0 / (double) n)//notice it the phermones can't be less than the starting value`
pheromones[i][j] = 1.0 / (double) n;
pheromones[i][i] = 0;
}
}
#part 2
//update the phermonses
for (int i = 0; i < m; i++) {
for (int j = i + 1; j <= n; j++) {
int from = ant[i].rout[0];
int to = ant[i].rout[n - 1];
pheromones[from][to] += Q / ant[i].tourDistance;
pheromones[to][from] = pheromones[from][to];
}
}
source HERE
strangely enough the algorithm can work without the elaboration presses i.e. #part1.
Anyway here's the complete code with little changes
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class test2 {
private InputReader cin;
private PrintWriter cout;
double[][] arr;
double[][] pheromones;
double[][] distances;
double[][] visibility;
static int n;
Ant[] ant;
int m;
int T;
double alpha = 1; // pheromone importance
double beta = 3; // visibility importance
double evaporation = 0.9;
double Q = 40.0;
double pheromones0;
static class Ant {
int whereAmI;
boolean[] visited;
double tourDistance;
private int ctr; //counter for the cites thought which the ant pass
private int[] route;
Ant(int whereAmI) {
this.whereAmI = whereAmI;
reset();
}
void reset() {
ctr = 0;
route = new int[n];
visited = new boolean[n + 1];
visited[whereAmI] = true;
tourDistance = 0;
addCityToTheRoute(whereAmI);
}
void addCityToTheRoute(int cityId) {
route[ctr++] = cityId;
}
}
private void solve() {
n = cin.readInt();
initializeParameter();
double mi = Double.MAX_VALUE;
int[] cityRoute = new int[n];
//the main loop
for (int t = 0; t < T; t++) {
for (int i = 0; i < m; i++) {//for each ant
for (int j = 0; j < n; j++) {//for each city
double highestProbability = 0;
int cityId = 1;
double sumNotiation = calculateSum(ant[i].visited, ant[i].whereAmI);
//traverse all non-visited cities and choose the best
boolean good = false;
for (int c = 1; c <= n; c++) {//remove the equal
if (!ant[i].visited[c]) {
double prop = (pow(pheromones[ant[i].whereAmI][c], alpha) * pow(visibility[ant[i].whereAmI][c], beta))
/ sumNotiation;
if (prop >= highestProbability) {
highestProbability = prop;
cityId = c;
good = true;
}
}
}
if (good) {
ant[i].tourDistance += distances[ant[i].whereAmI][cityId];
ant[i].addCityToTheRoute(cityId);
ant[i].whereAmI = cityId;
ant[i].visited[cityId] = true;
}
}//after n iteration i ant completes a tour
ant[i].tourDistance += distances[ant[i].route[0]][ant[i].route[n - 1]];//add the distance from the last city to the first city
//while k ant finishes its tour take the best ant's route so far
if (ant[i].tourDistance < mi) {
mi = ant[i].tourDistance;
cityRoute = ant[i].route;
}
}
//update
//evaporatePheromones
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
pheromones[i][j] *= evaporation;
if (pheromones[i][j] < pheromones0)
pheromones[i][j] = pheromones0;
pheromones[i][i] = 0;
}
}
//updatePheromones
for (int i = 0; i < m; i++) {
for (int j = i + 1; j <= n; j++) {
int from = ant[i].route[0];
int to = ant[i].route[n - 1];
pheromones[from][to] += Q / ant[i].tourDistance;
pheromones[to][from] = pheromones[from][to];
}
}
if (t == T - 1)
break;
//reset everything
for (int i = 0; i < m; i++) {
ant[i].reset();
}
}
//print the route with the distance
cout.println(mi);
for (int element : cityRoute)
cout.print(element + " ");
}
private double calculateSum(boolean[] visited, int currentAntsCity) {
//traverse all non-visited cities
double ans = 0.0;
for (int c = 1; c <= n; c++) {
if (!visited[c]) {
ans +=
pow(pheromones[currentAntsCity][c], alpha) *
pow(visibility[currentAntsCity][c], beta);
}
}
return ans;
}
private void initializeParameter() {
m = 20 * n;
T = 20;
pheromones = new double[n + 1][n + 1];
distances = new double[n + 1][n + 1];
visibility = new double[n + 1][n + 1];
//read cities coordinates
arr = new double[n + 1][2];
for (int i = 1; i <= n; i++) {
double x = cin.readDouble();
double y = cin.readDouble();
arr[i][0] = x;
arr[i][1] = y;
}
//initialize distances
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
distances[i][j] = distances[j][i] = sqrt(pow(arr[i][0] -
arr[j][0], 2.0) + pow(arr[i][1] -
arr[j][1], 2.0));
}
}
//initialize the pheromones
pheromones0 = 1.0 / (double) n;
for (int i = 1; i <= n; i++) {
Arrays.fill(pheromones[i], pheromones0);
pheromones[i][i] = 0;
}
//initialize the visibility
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
visibility[i][j] = visibility[j][i] = 1.0 / distances[i][j];
}
}
//initialize the ants
ant = new Ant[m];
Random rand = new Random(); //instance of random class for
for (int i = 0; i < m; i++) {
int random_int = rand.nextInt(n) + 1;
ant[i] = new Ant(random_int);
}
}
public static void main(String args[]) {
new test2().run();
}
private void run() {
// cin = new InputReader(System.in);
// cout = new PrintWriter(System.out);
try {
cin = new InputReader(new FileInputStream("input.txt"));
cout = new PrintWriter(new FileOutputStream("output.txt"));
} catch (FileNotFoundException e) {
//System.out.println(e.toString());
}
solve();
cout.close();
}
//just for faster reading from a file
public static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}

Processing sketch crashing website

Made a new sketch on openprocessing.org to test for some different grade combinations quickly... but whenever I run it, the page freezes hangs until chrome says that it is unresponsive. My other sketches are working just fine, it is only this one.
Here is the sketch:
double a, o, u, k;
int[][] combos;
int[][] a_combos, b_combos;
int failcounter;
void setup() {
size(100,100);
background(100);
noLoop();
a = 2 + 4;
o = 4 + 4;
u = 3 + 4;
k = 3 + 5;
combos = new int[10000][4];
a_combos = new int[10000][4];
b_combos = new int[10000][4];
failcounter = 0;
}
void draw() {
fillCombos();
for (int i = 0; i < combos.length; i++) {
double atemp = a + combos[0];
double otemp = o + combos[1];
double utemp = u + combos[2];
double ktemp = k + combos[3];
double avg = (atemp + otemp + utemp + ktemp) / 4;
if (avg >= 17) {
a_combos[i] = combos[i];
} else if (avg >= 13.48) {
b_combos[i] = combos[i];
} else {
failcounter++;
}
}
println("Getting an A:");
for (int i = 0; i < a_combos.length; i++) {
if (a_combos[i] != null) println(a_combos[i]);
}
println("Getting a B:");
for (int i = 0; i < b_combos.length; i++) {
if (b_combos[i] != null) println(b_combos[i]);
}
println("A or B versus C, D, or F:");
println(10000 - failcount + ", " + failcount);
}
void fillCombos() {
int q = 0;
int w = 0;
int e = 0;
int r = 0;
for (int i = 0; i < combos.length; i++) {
combos[i][0] = q;
combos[i][1] = w;
combos[i][2] = e;
combos[i][3] = r;
r++;
if (r == 10) {
r = 0;
e++;
}
if (e == 10) {
e = 0;
w++;
}
if (w == 10) {
w = 0;
q++;
}
}
}
If I put print lines into several different locations in the code, none of them run for whatever reason. Any insight?

reducing using instance variable to decrease the use of memory

I'm trying to do the Algorithm programming assignment of Princeton , and I met a problem about the memory test. The assignment requires us run the percolation program N times and find the medium of the result, and I write a percolationtest.java and for each time, I create an instance variable, it worked, but use too much memory, and the instructor suggests me to use local variable, but I don't know how. Can some one help me and give me some advice, I really appreciate it.
public class PercolationStats {
private int N, T, totalSum;
private double []fraction;
private int []count;
public PercolationStats(int N, int T) {
if (N <= 0 || T <= 0)
throw new IllegalArgumentException();
else {
this.N = N;
this.T = T;
count = new int [T];
totalSum = N*N;
fraction = new double[T];
int randomX, randomY;
for (int i = 0; i < T; i++) {
Percolation perc = new Percolation(N);
while (true) {
if (perc.percolates()) {
fraction[i] = (double) count[i]/totalSum;
break;
}
randomX = StdRandom.uniform(1, N+1);
randomY = StdRandom.uniform(1, N+1);
if (perc.isOpen(randomX, randomY)) continue;
else {
perc.open(randomX, randomY);
count[i]++;
}
}
}
}
} // perform T independent experiments on an N-by-N grid
public double mean() {
double totalFraction = 0;
for (int i = 0; i < T; i++) {
totalFraction += fraction[i];
}
return totalFraction/T;
} // sample mean of percolation threshold
public double stddev() {
double u = this.mean();
double sum = 0;
for (int i = 0; i < T; i++) {
sum += (fraction[i] - u) * (fraction[i] - u);
}
return Math.sqrt(sum/(T-1));
} // sample standard deviation of percolation threshold
public double confidenceLo() {
double u = this.mean();
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u-1.96*theta/sqrtT;
} // low endpoint of 95% confidence interval
public double confidenceHi() {
double u = this.mean();
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u+1.96*theta/sqrtT;
} // high endpoint of 95% confidence interval
public static void main(String[] args) {
int N = 200;
int T = 100;
if (args.length == 1) N = Integer.parseInt(args[0]);
else if (args.length == 2) {
N = Integer.parseInt(args[0]);
T = Integer.parseInt(args[1]); }
PercolationStats a = new PercolationStats(N, T);
System.out.print("mean = ");
System.out.println(a.mean());
System.out.print("stddev = ");
System.out.println(a.stddev());
System.out.print("95% confidence interval = ");
System.out.print(a.confidenceLo());
System.out.print(", ");
System.out.println(a.confidenceHi());
}
}
public class Percolation {
private boolean[][] site;
private WeightedQuickUnionUF uf;
private int N;
public Percolation(int N) {
if (N < 1)
throw new IllegalArgumentException();
else {
site = new boolean[N + 2][N + 2];
for (int j = 1; j <= N; j++) {
site[0][j] = true;
site[N + 1][j] = true;
}
uf = new WeightedQuickUnionUF((N + 2) * (N + 2));
for (int i = 1; i <= N; i++) {
uf.union(0, i);
}
this.N = N;
}
}
public void open(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else {
if (!site[i][j]) {
site[i][j] = true;
if (site[i - 1][j]) {
uf.union((N + 2) * (i - 1) + j, (N + 2) * i + j);
}
if (site[i + 1][j]) {
uf.union((N + 2) * i + j, (N + 2) * (i + 1) + j);
}
if (site[i][j + 1]) {
uf.union((N + 2) * i + (j + 1), (N + 2) * i + j);
}
if (site[i][j - 1]) {
uf.union((N + 2) * i + (j - 1), (N + 2) * i + j);
}
}
}
}
public boolean isOpen(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else
return site[i][j];
}
public boolean isFull(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else
return site[i][j] && (i == 1 || uf.connected((N + 2) * i + j, 0));
}
public boolean percolates() {
for (int i = 1; i <= N; i++) {
if (this.isFull(N, i)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
}
}
Added meanValue instance variable to keep mean value and replaced it in multiple places where you used to call mean() method which was over head to calculate again and again. Also modified "int[] count" as local variable which you were not using outside the constructor. post your "Percolation" and "StdRandom" classes for more optimization of code. you can run this code and test, it should reduce the runtime than yours.
public class PercolationStats {
private int N, T, totalSum;
private double []fraction;
private double meanValue;
public PercolationStats(int N, int T) {
if (N <= 0 || T <= 0)
throw new IllegalArgumentException();
else {
this.N = N;
this.T = T;
int [] count = new int [T];
totalSum = N*N;
fraction = new double[T];
int randomX, randomY;
for (int i = 0; i < T; i++) {
Percolation perc = new Percolation(N);
while (true) {
if (perc.percolates()) {
fraction[i] = (double) count[i]/totalSum;
break;
}
randomX = StdRandom.uniform(1, N+1);
randomY = StdRandom.uniform(1, N+1);
if (perc.isOpen(randomX, randomY)) continue;
else {
perc.open(randomX, randomY);
count[i]++;
}
}
}
}
}
// perform T independent experiments on an N-by-N grid
public double mean() {
double totalFraction = 0;
for (int i = 0; i < T; i++) {
totalFraction += fraction[i];
}
meanValue = totalFraction/T;
return meanValue;
} // sample mean of percolation threshold
public double stddev() {
double u = meanValue;
double sum = 0;
for (int i = 0; i < T; i++) {
sum += (fraction[i] - u) * (fraction[i] - u);
}
return Math.sqrt(sum/(T-1));
} // sample standard deviation of percolation threshold
public double confidenceLo() {
double u = meanValue;
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u-1.96*theta/sqrtT;
} // low endpoint of 95% confidence interval
public double confidenceHi() {
double u = meanValue;
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u+1.96*theta/sqrtT;
} // high endpoint of 95% confidence interval
public static void main(String[] args) {
int N = 200;
int T = 100;
if (args.length == 1) N = Integer.parseInt(args[0]);
else if (args.length == 2) {
N = Integer.parseInt(args[0]);
T = Integer.parseInt(args[1]); }
PercolationStats a = new PercolationStats(N, T);
System.out.print("mean = ");
System.out.println(a.mean());
System.out.print("stddev = ");
System.out.println(a.stddev());
System.out.print("95% confidence interval = ");
System.out.print(a.confidenceLo());
System.out.print(", ");
System.out.println(a.confidenceHi());
}
}

compare two string in java result in percentage [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have to compare two strings which 4000-5000 characters.
I need result in percentage(i.e. 70% - 80% matched), in java.
Kindly suggest me any solution for it.
Regards
Here is the code to compare two strings and getting result in integer form from 0 to 100.
/**
*
* #author WARLOCK
*/
public class LockMatch {
public static void main(String arg[]) {
//---Provide source and target strings to lock_match function to compare--//
System.out.println("Your Strings are Matched="+lock_match("The warlock","The warlock powered by WTPL")+"%");
}
public static int lock_match(String s, String t) {
int totalw = word_count(s);
int total = 100;
int perw = total / totalw;
int gotperw = 0;
if (!s.equals(t)) {
for (int i = 1; i <= totalw; i++) {
if (simple_match(split_string(s, i), t) == 1) {
gotperw = ((perw * (total - 10)) / total) + gotperw;
} else if (front_full_match(split_string(s, i), t) == 1) {
gotperw = ((perw * (total - 20)) / total) + gotperw;
} else if (anywhere_match(split_string(s, i), t) == 1) {
gotperw = ((perw * (total - 30)) / total) + gotperw;
} else {
gotperw = ((perw * smart_match(split_string(s, i), t)) / total) + gotperw;
}
}
} else {
gotperw = 100;
}
return gotperw;
}
public static int anywhere_match(String s, String t) {
int x = 0;
if (t.contains(s)) {
x = 1;
}
return x;
}
public static int front_full_match(String s, String t) {
int x = 0;
String tempt;
int len = s.length();
//----------Work Body----------//
for (int i = 1; i <= word_count(t); i++) {
tempt = split_string(t, i);
if (tempt.length() >= s.length()) {
tempt = tempt.substring(0, len);
if (s.contains(tempt)) {
x = 1;
break;
}
}
}
//---------END---------------//
if (len == 0) {
x = 0;
}
return x;
}
public static int simple_match(String s, String t) {
int x = 0;
String tempt;
int len = s.length();
//----------Work Body----------//
for (int i = 1; i <= word_count(t); i++) {
tempt = split_string(t, i);
if (tempt.length() == s.length()) {
if (s.contains(tempt)) {
x = 1;
break;
}
}
}
//---------END---------------//
if (len == 0) {
x = 0;
}
return x;
}
public static int smart_match(String ts, String tt) {
char[] s = new char[ts.length()];
s = ts.toCharArray();
char[] t = new char[tt.length()];
t = tt.toCharArray();
int slen = s.length;
//number of 3 combinations per word//
int combs = (slen - 3) + 1;
//percentage per combination of 3 characters//
int ppc = 0;
if (slen >= 3) {
ppc = 100 / combs;
}
//initialising an integer to store the total % this class genrate//
int x = 0;
//declaring a temporary new source char array
char[] ns = new char[3];
//check if source char array has more then 3 characters//
if (slen < 3) {
} else {
for (int i = 0; i < combs; i++) {
for (int j = 0; j < 3; j++) {
ns[j] = s[j + i];
}
if (cross_full_match(ns, t) == 1) {
x = x + 1;
}
}
}
x = ppc * x;
return x;
}
/**
*
* #param s
* #param t
* #return
*/
public static int cross_full_match(char[] s, char[] t) {
int z = t.length - s.length;
int x = 0;
if (s.length > t.length) {
return x;
} else {
for (int i = 0; i <= z; i++) {
for (int j = 0; j <= (s.length - 1); j++) {
if (s[j] == t[j + i]) {
// x=1 if any charecer matches
x = 1;
} else {
// if x=0 mean an character do not matches and loop break out
x = 0;
break;
}
}
if (x == 1) {
break;
}
}
}
return x;
}
public static String split_string(String s, int n) {
int index;
String temp;
temp = s;
String temp2 = null;
int temp3 = 0;
for (int i = 0; i < n; i++) {
int strlen = temp.length();
index = temp.indexOf(" ");
if (index < 0) {
index = strlen;
}
temp2 = temp.substring(temp3, index);
temp = temp.substring(index, strlen);
temp = temp.trim();
}
return temp2;
}
public static int word_count(String s) {
int x = 1;
int c;
s = s.trim();
if (s.isEmpty()) {
x = 0;
} else {
if (s.contains(" ")) {
for (;;) {
x++;
c = s.indexOf(" ");
s = s.substring(c);
s = s.trim();
if (s.contains(" ")) {
} else {
break;
}
}
}
}
return x;
}
}
Just supply the two strings as argument to lock_match(string1, string2) and it will return the integer value of matching. If the size of string is bigger then increase the total name variable size
in the code.
Like int total=1000
Then the result will be given out of 0 to 1000.
This code is case sensitive.
Uppercase or lowercase both strings to get rid from this problem.
Source code available at: lock match
You can use Apache Commons Lang 3.
Maven dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.lang.version}</version>
</dependency>
#Test
public void test_stringDistance() throws Exception {
String teamName = "Partizn Belgrade";
String propositionName = "Partizan Belgrade";
// This one seems better
double distance = StringUtils.getJaroWinklerDistance(teamName, propositionName);
System.out.println(distance);
}
This is print out percentage, the larger the better (100% is exact )
org.apache.commons.lang3.StringUtils.getJaroWinklerDistance(first, second) is deprecated as of commons-lang3:3.6
Use new org.apache.commons.text.similarity.JaroWinklerDistance().apply(left, right) instead where left and right stand for first and second respectively. See maven dependency below
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.9</version>
</dependency>

Consecutive factor test

A positive number n is consecutive-factored if and only if it has factors, i and j where i > 1, j > 1 and j = i +1. I need a function that returns 1 if its argument is consecutive-factored, otherwise it returns 0.For example, 24=2*3*4 and 3 = 2+1 so it has the function has to return 1 in this case.
I have tried this:
public class ConsecutiveFactor {
public static void main(String[] args) {
// TODO code application logic here
Scanner myscan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int num = myscan.nextInt();
int res = isConsecutiveFactored(num);
System.out.println("Result: " + res);
}
static int isConsecutiveFactored(int number) {
ArrayList al = new ArrayList();
for (int i = 2; i <= number; i++) {
int j = 0;
int temp;
temp = number %i;
if (temp != 0) {
continue;
}
else {
al.add(i);
number = number / i;
j++;
}
}
System.out.println("Factors are: " + al);
int LengthOfList = al.size();
if (LengthOfList >= 2) {
int a =al(0);
int b = al(1);
if ((a + 1) == b) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
}
Can anyone help me with this problem?
First check if its even, then try trial division
if(n%2!=0) return 0;
for(i=2;i<sqrt(n);++i) {
int div=i*(i+1);
if( n % div ==0) { return 1; }
}
return 0;
very inefficient, but fine for small numbers. Beyond that try a factorisation algorithm from http://en.wikipedia.org/wiki/Prime_factorization.
I have solved my problem with the above code. Following is the code.
public class ConsecutiveFactor {
public static void main(String[] args) {
// TODO code application logic here
Scanner myscan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int num = myscan.nextInt();
int res = isConsecutiveFactored(num);
System.out.println("Result: " + res);
}
static int isConsecutiveFactored(int number) {
ArrayList al = new ArrayList();
for (int i = 2; i <= number; i++) {
int j = 0;
int temp;
temp = number % i;
if (temp != 0) {
continue;
}
else {
al.add(i);
number = number / i;
j++;
}
}
Object ia[] = al.toArray();
System.out.println("Factors are: " + al);
int LengthOfList = al.size();
if (LengthOfList >= 2) {
int a = ((Integer) ia[0]).intValue();
int b = ((Integer) ia[1]).intValue();
if ((a + 1) == b) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
}

Categories