reducing using instance variable to decrease the use of memory - java

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());
}
}

Related

How can I output the points that are colinear?

THE PROBLEM: Write a program that reads N points in a plane and outputs any group of four or more colinear points
What I did: I calculated the slope of every 2 points and then put them in a hashmap to see which one is the max.
What I need to do: I need to output the points that are colinear from the initial 2D array. I found the number of points that are colinear with the hashmap.
import java.util.*;
public class app {
public static int maxPoints(int[][] points) {
int ans = 1;
int n = points.length;
for (int i = 0; i < n; i++) {
HashMap<String, Integer> map = new HashMap<>();
int OLP = 0;
int max = 0;
for (int j = i + 1; j < n; j++) {
if (points[i][0] == points[j][0] && points[i][1] == points[j][1]) {
OLP++;
continue;
}
int dy = points[j][1] - points[i][1];
int dx = points[j][0] - points[i][0];
int g = gcd(Math.abs(dy), Math.abs(dx));
int num = dy / g;
int deno = dx / g;
if (num == 0)
deno = 1;
if (deno == 0)
num = 1;
if ((num < 0 && deno < 0) || deno < 0) {
num *= -1;
deno *= -1;
}
map.put(createString(deno, num), map.getOrDefault(createString(deno, num), 0) + 1);
max = Math.max(max, map.get(createString(deno, num)));
}
ans = Math.max(ans, 1 + OLP + max);
}
return ans;
}
public static int gcd(int a, int b) {
if (a == 0)
return b;
if (b == 0)
return a;
int max = Math.max(a, b);
int min = Math.min(a, b);
return gcd(max % min, min);
}
public static String createString(int a, int b) {
return Integer.toString(a) + " " + Integer.toString(b);
}
public static void main(String[] args) {
int[][] points = { { 1, 1 }, { 2, 2 }, { 3, 3 }, { 4, 4 }, { 5, 4 } };
System.out.println("max Points are: " + maxPoints(points));
}}

Finding the largest Odd Fibonacci number in the given ranges of values

Ex: n1=100, n2=250, out=233.
Here I have to find the largest odd fibonacci number in the given set of ranges. If an odd fibonacci number doesn't exist then it should return 0. I am getting output as 50 times 0's and then 10 times 233. Where is my mistake and how can I get the desired output?
public class Fibo {
public static void main(String[] args) {
try {
int n1 = 100;
int n2 = 250;
int res = 0;
if (n1 % 2 == 0) {
n1 += 1;
for (int i = n1; i < n2; i += 2) {
if (isPerfectSquare(5 * i * i + 4) || isPerfectSquare(5 * i * i - 4))
res = i;
System.out.println(res);
}
}
} catch(Exception ignored) {
System.out.println("0");
}
}
public static boolean isPerfectSquare(int num) {
double sqrt = Math.sqrt(num);
int x = (int)sqrt;
return Math.pow(sqrt, 2) == Math.pow(x, 2);
}
}
public class Fibonacci {
public static void main(String[] args) {
System.out.println("Enter the starting range");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println("Enter the ending range");
int r = sc.nextInt();
int res = 0;
for (int i = n; i <= r; i++) {
if (isPerfectSquare(5 * i * i + 4) || isPerfectSquare(5 * i * i - 4))
res = i;
}
System.out.println("The biggest odd number in the range is"+" "+res);
}
public static boolean isPerfectSquare(int num) {
double sqrt = Math.sqrt(num);
int x = (int)sqrt;
return Math.pow(sqrt, 2) == Math.pow(x, 2);
}
}
public static int getLargestOddFibonacciBetween(int lo, int hi) {
assert lo <= hi;
int f0 = 0;
int f1 = 1;
int res = -1;
while (f1 <= hi) {
int val = f0 + f1;
f0 = f1;
f1 = val;
if (val >= lo && val <= hi && isOdd(val))
res = val;
}
return res;
}
private static boolean isOdd(int val) {
return (val & 1) == 1;
}

Calculating Tarloy series in Java

I want to calculate the sum of this function ((-1)^n)*(x^2n)/(2.n!) but my program isn't working.I need your help.Here's what i tried:
public double getCos()
{
double Cos = 0;
for(int i=0;i<=n;i++)
{
Cos+=(power(x,i)/facto(n));
}
return Cos;
}
private double facto(int n)
{
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result*2;
}
private double power(int x,int n)
{
double power=Math.pow(-1,n)*Math.pow(x,2*n);
return power;
}
}
This is How You Make It I Just Fix Some Errors On Your Program :
public class Cos {
public static double getCos(double x) {
double Cos = 0;
for (int i = 0; i <= 5; i++) {
Cos += (power(-1, i) * power(x, 2*i)) / factorial(2*i) ;
}
return Cos;
}
public class Cos {
public static double getCos(double x) {
double Cos = 0;
for (int i = 0; i <= 5; i++) {
Cos += (power(-1, i) * power(x, 2*i)) / factorial(2*i) ;
}
return Cos;
}
private static double factorial(int n) {
int result = 1;
if( n == 0 || n == 1 )
return 1;
else {
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
}
private static double power(double x, int n) {
return Math.pow(x, n);
}
public static void main(String[] args) {
System.out.println("Test For The 3 Methods!");
System.out.println("5^2 : " + power(5, 2));
System.out.println("4! : " + factorial(4));
System.out.println("Cos(0.2) : " + getCos(0.2));
}
}
private static double power(double x, int n) {
return Math.pow(x, n);
}
public static void main(String[] args) {
System.out.println("Test For The 3 Methods!");
System.out.println("5^2 : " + power(5, 2));
System.out.println("4! : " + factorial(4));
System.out.println("Cos(0.2) : " + getCos(0.2));
}
}
From what I can tell, your difficulties are arising in your facto method. First of all, result was never properly declared (at least in the code provided). Furthermore, when 0 is passed for the first term, i=1 and therefore i<=0 evaluates false and the loop never executes. So what value would result have?
private double facto(int n) {
if(n==0) return 1.0;
double result = 0.0;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result*2;
}
This is How I Will Make This Exercise :
public class TaylorSeries {
static double power(double x,int n)
{
double p = 1;
for (int i = 1; i <= n ; i++) {
p = p*x;
}
return p;
}
// this is the best way to make factorial function by recursion
static int factorial(int n)
{
if(n == 1 || n == 0)
{
return 1;
}
else
{
return n*factorial(n - 1);
}
}
// i = 0 to i = 5 the 5 is for the summation
static double cos(double x)
{
double cos = 0;
for (int i = 0; i <= 5 ; i++) {
cos += ( power(-1, i) * power(x, 2*i) ) / ( factorial(2*i) );
}
return cos;
}
public static void main(String[] args) {
System.out.println("2^3 : " + power(2, 3));
System.out.println("5! : " + factorial(5));
// 20 means summation from 0 to 20
System.out.println("Cos(0.15) : " + cos(0.15));
}
}

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>

Notepad++ to Unix timeshare Transfer issues

So I have a code that appears like it would have perfect formatting in Notepad++, but when I login to my Unix timeshare, open vim, and paste the code into the newly created file, it later has problems compiling. I keep getting "class, interface, or enum expected" errors, however my code appears to have the right amount of brackets and such. I've even tried using Filezilla to transfer my java file in to my unix folder, but I get the same errors. Does anybody else experience problems while transferring code from Notepad++ to Unix? If so, is there a way I can fix this? I've provided my code below; it is meant to find the roots of an entered polynomial using the bisection method:
import java.util.*;
class Roots {
public static int degree;
public static double[] coArrayC;
public static double[] coArrayD;
public static int coeffiNumb;
public static void main( String[] args ){
double resolution = 0.01;
double threshold = 0.001;
double tolerance = 0.0000001;
double rightEndPt;
double leftEndPt;
int polyRootPointer = 0;
int diffRootPointer = 0;
boolean rootAns = false;
Scanner sc = new Scanner(System.in);
System.out.println();
System.out.print("Enter the degree: ");
degree = sc.nextInt();
coeffiNumb = degree + 1;
System.out.print("Enter " + coeffiNumb + " coefficients: ");
double[] coefficients = new double[coeffiNumb];
coArrayC = new double[coeffiNumb];
double[] rootArray = new double[degree];
coArrayD = new double[coeffiNumb];
double[] rootArrayDeriv = new double[degree];
for(int i = 0; i < coeffiNumb; i++) {
coefficients[i] = sc.nextDouble();
}
System.out.print("Enter the lower and upper endpoints, in that order: ");
leftEndPt = sc.nextDouble();
rightEndPt = sc.nextDouble();
diff(coefficients);
for (double i = leftEndPt; i < rightEndPt-resolution; i = i + resolution){
if (isPositive(coArrayD, i) != isPositive(coArrayD, i+resolution) || isPositive(coArrayD, i) == 0) {
rootArrayDeriv[diffRootPointer] = findRoot(coArrayD, i, i+resolution, tolerance);
diffRootPointer++;
}
}
for (int i = 0; i < rootArrayDeriv.length; i++) {
double tempVal;
tempVal = poly(coefficients, rootArrayDeriv[i]);
tempVal = Math.abs(tempVal);
if (tempVal < threshold) {
rootArray[polyRootPointer] = rootArrayDeriv[i];
polyRootPointer++;
rootAns = true;
}
}
for (double i = leftEndPt; i < rightEndPt-resolution; i = i + resolution){
if (isPositive(coefficients, i) != isPositive(coefficients, i+resolution) || isPositive(coefficients, i) == 0) {
rootArray[polyRootPointer] = findRoot(coefficients, i, i+resolution, tolerance);
polyRootPointer++;
rootAns = true;
}
}
Arrays.sort(rootArray);
if (rootAns == false) {
System.out.println("Sorry - no roots were found at that particular interval.");
}
}
} else {
for (int i = 0; i < rootArray.length; i++) {
if (rootArray[i] != 0.0) {
System.out.printf("Root found at %.5f%n", Arrays.sort(rootArray));
}
}
static double poly(double[] C, double x){
double polySum = 0;
coArrayC[0] = C[0];
for (int i = 1; i < coArrayC.length; i++){
coArrayC[i] = C[i]*(Math.pow(x, i));
}
for (int i = 0; i < coArrayC.length; i++){
polySum = polySum + coArrayC[i];
}
return(polySum);
}
static double[] diff(double[] C){
for (int i = 0; i < degree; i++){
coArrayD[i] = (i+1)*C[i+1];
}
return(coArrayD);
}
static double findRoot(double[] C, double a, double b, double tolerance){
double root = 0.0 , residual;
while ( Math.abs(b - a) > tolerance ) {
root = (a + b) / 2.0;
residual = poly(C, root);
if (poly(C, a) > 0 && poly(C, b) < 0) {
if (residual > 0)
a = root;
else
b = root;
} else if (poly(C, a) < 0 && poly(C, b) > 0) {
if (residual > 0)
b = root;
else
a = root;
}
}
return(root);
}
static int isPositive(double[] C, double a){
double endpointTempA;
endpointTempA = poly(C, a);
if (endpointTempA < 0) {
return(1);
} else if (endpointTempA > 0) {
return(2);
} else {
return(0);
}
}
}

Categories