so I am in the middle of working on a problem requiring me to:
Use 3 nested loops to generate every combination of (F^5-E^5-D^5) store all these combinations. Then use 3 different nested loops to generate every combination of (A^5+B^5+C^5) and store all these values. Where 0 < A ≤ B ≤ C ≤ D ≤ E ≤ F ≤ N
I have been following this thread which is exactly what I am trying to accomplish.
The problem I am having is the way my code is set up, the array that I am storing the values in will be overwritten every time the loop goes around again.
How long does the array need to be to store the values (N^3 maybe)? And how can I do it without overwriting?
Here is my code so far:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the value for N:");
int n = scan.nextInt();
int countF = n;
double[] fifth_orderN = new double[n+1];
double[] F_answer = new double[n+1];
double[] A_answer = new double[n+1];
for(int i = 1; i != n+1; i++)
{
fifth_orderN[i] = Math.pow(i, 5);
}
for(int i = 1; i != n+1 ; i++)
{
double F = Math.pow(countF, 5);
countF--;
for(int j = 1; j != n+1 ; j++)
{
double E = fifth_orderN[j];
for(int k = 1; k != n+1; k++)
{
double D = fifth_orderN[k];
double ans = (F-(D+E));
if(ans < 0)
{
break;
}
else
{
F_answer[k] = ans;
}
}
}
}
for(int i = 1; i != n+1; i++)
{
double A = fifth_orderN[i];
for(int j = 1; j != n+1; j++)
{
double B = fifth_orderN[j];
for(int k = 1; k != n+1; k++)
{
double C = fifth_orderN[k];
double ans = (A + B + C);
A_answer[k] = ans;
}
}
}
}
Related
Here is what I am suppose to be getting.
This is what I am actually getting.
Write a program DiscreteDistribution.java that takes an integer command-line argument m, followed by a sequence of positive integer command-line arguments a1,a2,…,an, and prints m random indices (separated by whitespace), choosing each index i with probability proportional to ai.
So far I have
public static void main(String[] args) {
// number of random indices
int m = Integer.parseInt(args[0]);
// read in frequency of occurrence of n values
int n = args.length;
int[] freq = new int[n];
for (int i = 0; i < n; i++) {
freq[i] = Integer.parseInt(args[i]);
}
// compute total count of all frequencies
int total = 0;
for (int i = 0; i < n; i++) {
total += freq[i];
}
for (int j = 0; j < m; j++) {
// generate random integer with probability proportional to frequency
int r = (int) ((total) * Math.random() - 1); // integer in [0, total)
int sum = 0;
int event = -1;
for (int i = 0; i < n && sum <= r; i++) {
sum += freq[i];
event = i;
System.out.println(freq[i]);
}
}
}
Under the assumption that I understand your problem correctly, then you can use the following algorithm to produce m random numbers in the range 1 to n according to the given frequencies:
public static void main(String[] args) {
// number of random indices
int m = Integer.parseInt(args[0]);
// read in frequency of occurrence of n values
int n = args.length;
int[] freq = new int[n];
for (int i = 1; i < n; i++) {
freq[i] = Integer.parseInt(args[i]);
}
// compute total count of all frequencies
int total = 0;
for (int i = 1; i < n; i++) {
total += freq[i];
}
double[] summedProbabilities = new double[n];
for (int i = 1; i < summedProbabilities.length; i++) {
final double probability = freq[i] / (double) total;
summedProbabilities[i] = summedProbabilities[i -1] + probability;
}
for (int j = 0; j < m; j++) {
// generate random integer with probability proportional to frequency
double randomProbability = Math.random();
int i = 1;
while (randomProbability > summedProbabilities[i]) {
i++;
}
System.out.print(i + " ");
if (j % 10 == 0) {
System.out.println();
}
}
}
I strongly suggest you to refactor the code in a way that you use methods to calculate small pieces and compose it then.
public class DiscreteDistribution{
public static void main(String[] args) {
// takes in number of times we must loop to print indices
int m = Integer.parseInt(args[0]);
// set the array size to the number of input from command line
//minus the first input
//because we are not considering the input at args[0]
int [] n = new int[args.length-1];
// cSum to store the cummulatives
int [] cSum = new int[args.length];
// to store an array of random generated
//number of size m
int [] rand = new int[m];
int count = 1;
int cCount = 1;
int sum = 0; // to add the inputs n;
// to store user input in an array in n ignoring the first input
for(int i =0; i < n.length; i++)
{
n[i] = Integer.parseInt(args[count]);
count++;
}
//stores the cummulatives of n in cSum
for(int j = 0; j < n.length; j++)
{
sum = sum + n[j];
cSum[j+1] = sum;
}
//generate a random number and stores in rand representing the //probabilites
for(int p = 0; p < m; p++) {
int r = (int)(1+Math.random()*cSum[cSum.length-1]);
rand[p] = r;
}
// loop from 0 to m to print the indices of n;
for(int s = 0; s < m; s++) {
//prints the indices corresponding to the condition
for(int q = 1; q < n.length; q++) {
if(rand[s] <= cSum[q-1]) {
System.out.print(q+" ");
}
}
}
}
I am working to calculate values of various Paycodes in a PayStructure based on linear equations using java. My different equations are as below:
CTC = Fixed Value
Basic = CTC * 0.4
HRA = Basic/2
ConveyanceAllowance = Fixed Value
ProvidentFund = Basic * 0.12
Gratuity = Basic * .0481
OtherAllowance = (CTC - (Basic + HRA + ConveyanceAllowance + ProvidentFund + Gratuity))
I have tried using the solution given here. But this solution will only work in case all the calculated values are integers and in my case, the values could contain decimal figures as well. My modified code as per the above conditions is as below:
public class PayStructure {
public static void main(String[] args) {
findAndprintSolutions(1, 1000000);
}
private static void findAndprintSolutions(int from, int to) {
for (int a = from; a < to; a++) {
for (int b = from; b < to; b++) {
for (int c = from; c < to; c++) {
for (int d = from; d < to; d++) {
for (int e = from; e < to; e++) {
for (int f = from; f < to; f++) {
for (int g = from; g < to; g++) {
if (isSolution(a, b, c, d, e, f, g))
printSolution(new int[] { a, b, c, d, e, f, g });
}
}
}
}
}
}
}
}
private static boolean isSolution(int a, int b, int c, int d, int e, int f, int g) {
if (a != 100000)
return false;
if (b != a * (.4))
return false;
if (c != b / 2)
return false;
if (d != 10000)
return false;
if (e != b * (.12))
return false;
if (f != b * (.0481))
return false;
if (g != (a - (b + c + d + e + f)))
return false;
return true;
}
private static void printSolution(int[] variables) {
StringBuilder output = new StringBuilder();
for (int variable : variables) {
output.append(variable + ", ");
}
output.deleteCharAt(output.length() - 1);
output.deleteCharAt(output.length() - 1);
System.out.println(output.toString());
}
}
Moreover the above mentioned code will be terminated as the maximum value of CTC could be millions and depending on the number of variables, time complexity will end up to be millions^NumberOfVariables. Is there any other possibility to calculate the values based on the given equations? The number of equations and variables could vary but there will be a solution to calculate value of each variable, so any inputs for a generic solution would be better.
E.g.: If CTC = 100000 and ConveyanceAllowance = 10000, the code should return the output as:
Basic = 40000
HRA = 20000
ProvidentFund = 4800
Gratuity = 1924
OtherAllowance = 23276
Maybe your best bet would be to figure out how to get this into the form of a system of linear equations of the form c[1]x[1] + c[2]x[2] … + c[n]x[n] = 0. From there, you can solve the system using widely established techniques for linear systems. See the Wikipedia page for lots of information. You could either have the users provide input to your method in this form, or you could do a small amount of processing on each equation to transform it (e.g., if all the equations have one variable on the LHS as in your example, flip the sign and put it on the end of the RHS).
Explaining the theory of solving a system of linear equations is beyond the scope of this answer but, basically, your system will either be uniquely determined if there is one valid assignment, overdetermined if no valid assignment exists, or underdetermined if infinitely many assignments are possible. If there is a unique assignment you will get numbers; if the system is underdetermined you'll at least get a set of constraints that must hold of any of the infinitely many solutions; if underdetermined, you'll get nothing and know why.
Use the some linear algebra library for Java. Solve the system of linear equations using matrix operations as documented here, for instance. Your deeply nested loop is too slow, there are much better algorithms available.
This is how I solved this. Firstly I created equations by taking all the variables to the left side and values & 0 to the right side:
CTC = 1000000
(0.4)CTC - Basic = 0
(0.5)Basic-HRA = 0
ConvAll = 10000
(0.12)Basic-PF = 0
(0.0481)Basic - Gratuity = 0
CTC - (Basic + HRA + ConvAll + PF+ Gratuity + OtherAll) = 0
Then I created a matrix like this:
|1 0 0 0 0 0 0| |CTC | = |1000000|
|0.4 -1 0 0 0 0 0| |Basic | = |0 |
|0 0.5 -1 0 0 0 0| |HRA | = |0
|0 0 0 1 0 0 0| |ConvAll | = |10000 |
|0 0.12 0 0 -1 0 0| |PF | = |0 |
|0 0.0481 0 0 0 -1 0| |Gratuity| = |10000 |
|1 -1 -1 -1 -1 -1 -1| |OtherAll| = |0 |
After this, I calculated the product of (inverse of above 1st matrix) and (right most matrix) and got the corresponding values of each component using the below code:
public class Matrix
{
static int n = 0;
public static void main(String argv[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the dimension of square matrix: ");
n = input.nextInt();
double a[][] = new double[n][n];
System.out.println("Enter the elements of matrix: ");
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
a[i][j] = input.nextDouble();
double d[][] = invert(a);
System.out.println();
System.out.println("Enter the equation values: ");
System.out.println();
double b[][] = new double[n][1];
for (int i = 0; i < n; i++) {
b[i][0] = input.nextDouble();
}
double e[][] = multiplyMatrix(d, b);
System.out.println();
System.out.println("The final solution is: ");
System.out.println();
for (int i = 0; i < n; i++) {
for (int j = 0; j < 1; j++) {
System.out.printf(e[i][j] + " ");
}
System.out.println();
}
input.close();
}
public static double[][] invert(double a[][]) {
int n = a.length;
double x[][] = new double[n][n];
double b[][] = new double[n][n];
int index[] = new int[n];
for (int i = 0; i < n; ++i)
b[i][i] = 1;
// Transform the matrix into an upper triangle
gaussian(a, index);
// Update the matrix b[i][j] with the ratios stored
for (int i = 0; i < n - 1; ++i)
for (int j = i + 1; j < n; ++j)
for (int k = 0; k < n; ++k)
b[index[j]][k] -= a[index[j]][i] * b[index[i]][k];
// Perform backward substitutions
for (int i = 0; i < n; ++i) {
x[n - 1][i] = b[index[n - 1]][i] / a[index[n - 1]][n - 1];
for (int j = n - 2; j >= 0; --j) {
x[j][i] = b[index[j]][i];
for (int k = j + 1; k < n; ++k) {
x[j][i] -= a[index[j]][k] * x[k][i];
}
x[j][i] /= a[index[j]][j];
}
}
return x;
}
// Method to carry out the partial-pivoting Gaussian
// elimination. Here index[] stores pivoting order.
public static void gaussian(double a[][], int index[]) {
int n = index.length;
double c[] = new double[n];
// Initialize the index
for (int i = 0; i < n; ++i)
index[i] = i;
// Find the rescaling factors, one from each row
for (int i = 0; i < n; ++i) {
double c1 = 0;
for (int j = 0; j < n; ++j) {
double c0 = Math.abs(a[i][j]);
if (c0 > c1)
c1 = c0;
}
c[i] = c1;
}
// Search the pivoting element from each column
int k = 0;
for (int j = 0; j < n - 1; ++j) {
double pi1 = 0;
for (int i = j; i < n; ++i) {
double pi0 = Math.abs(a[index[i]][j]);
pi0 /= c[index[i]];
if (pi0 > pi1) {
pi1 = pi0;
k = i;
}
}
// Interchange rows according to the pivoting order
int itmp = index[j];
index[j] = index[k];
index[k] = itmp;
for (int i = j + 1; i < n; ++i) {
double pj = a[index[i]][j] / a[index[j]][j];
// Record pivoting ratios below the diagonal
a[index[i]][j] = pj;
// Modify other elements accordingly
for (int l = j + 1; l < n; ++l)
a[index[i]][l] -= pj * a[index[j]][l];
}
}
}
public static double[][] multiplyMatrix(double a[][], double b[][]) {
double c[][] = new double[n][1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < 1; j++) {
for (int k = 0; k < n; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
return c;
}
}
Thank you all for the leads.
I'm trying to implement the matrix multiplication algorithm, but I have an issue dealing with BigInteger.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Size of Matrix A");
int tamA1 = scan.nextInt();
int tamA2 = scan.nextInt();
System.out.println("Size of Matrix B");
int tamB1 = scan.nextInt();
int tamB2 = scan.nextInt();
BigInteger[][] A = new BigInteger[tamA1][tamA2];
BigInteger[][] B = new BigInteger[tamB1] [tamB2];
BigInteger[][] C = new BigInteger[A.length][B[0].length];
System.out.println("Values of Matrix A");
for (int i = 0; i < tamA1; i++) {
for (int j = 0; j < tamA2; j++) {
A[i][j] = scan.nextBigInteger();
}
}
System.out.println("Values of Matrix B");
for (int i = 0; i < tamB1; i++) {
for (int j = 0; j < tamB2; j++) {
B[i][j] = scan.nextBigInteger();
}
}
if (A[0].length == B.length) {
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B[0].length; j++) {
for (int k = 0; k < A[0].length; k++) {
C[i][j] =C[i][j].add(A[i][k].multiply(B[k][j])); // Result
}
}
}
}
System.out.println(" C is equal to: ");
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
System.out.print(C[i][j]+" ");
}
System.out.println("");
}
}
Take a look at this output:
Matrix A
2 2
Matrix B
2 2
Values of A
2 2
1 0
Values of B
3 4
5 6
Exception in thread "main" java.lang.NullPointerException
at matrixmultiplication.MatrixMultiplication.main(MatrixMultiplication.java:56)
C:\Users\Luis Miguel\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
I don't know why I can do this operation with int and not with BigInteger.
Thanks in advance.
The "difference" (or really a similarity, depending on how you think about it) between an array of int and an array of BigInteger is that when you make a new array of integers, all the integers exist (and are zero) while a new array of BigInteger is filled with null. Of course add cannot be called on null.
There are different fixes, for example you could fill the matrix C with zeros, or you could modify the multiplication so that it does not read from C at all but instead sums into a local variable which you initialize to zero.
What am i doing wrong here?
Java code for computing prefix function. Two input are right but the last one is wrong.
Here's the pseudocode:
Java code:
class Main {
// compute prefix function
public static void main(String[] args) {
String p = "422213422153342";
String x = "ababbabbabbababbabb";
String y = "ababaca";
printOutput(p);
printOutput(y);
System.out.println();System.out.println();
System.out.println("the prefix func below is wrong. I am not sure why.");
System.out.print("answer should be: 0 0 1 2 0 1 2 0 1 2 0 1 2 3 4 5 6 7 8");
printOutput(x);
}
static void printOutput(String P){
System.out.println();System.out.println();
System.out.print("p[i]: ");
for(int i = 0; i < P.length(); i++)System.out.print(P.charAt(i) + " ");
System.out.println();
System.out.print("Pi[i]: ");
compute_prefix_func(P);
}
public static void compute_prefix_func(String P){
int m = P.length();
int pi[] = new int[m];
for(int i = 0; i < pi.length; i++){
pi[i] = 0;
}
pi[0] = 0;
int k = 0;
for(int q = 2; q < m; q++){
while(k > 0 && ( ((P.charAt(k) + "").equals(P.charAt(q) + "")) == false)){
k = pi[k];
}
if ((P.charAt(k) + "").equals(P.charAt(q) + "")){
k = k + 1;
}
pi[q] = k;
}
for(int i = 0; i < pi.length; i++){
System.out.print(pi[i] + " ");
}
}
}
Okay, let's start off by making the code much easier to read. This:
if ((P.charAt(k) + "").equals(P.charAt(q) + ""))
can be simplified to:
if (P.charAt(k) == P.charAt(q))
... and you've done that in multiple places.
Likewise here:
int pi[] = new int[m];
for(int i = 0; i < pi.length; i++){
pi[i] = 0;
}
pi[0] = 0;
... you don't need the explicit initialization. Variables are 0-initialized by default. (It's unclear why you're then setting pi[0] again, although I note that if P.length() is 0, this will throw an exception.)
Next is to remove the explicit comparison with false, instead just using ! so we have:
while(k > 0 && P.charAt(k) != P.charAt(q))
Finally, let's restructure the code a bit to make it easier to follow, use more conventional names, and change int pi[] to the more idiomatic int[] pi:
class Main {
public static void main(String[] args) {
String x = "ababbabbabbababbabb";
int[] prefix = computePrefix(x);
System.out.println("Prefix series for " + x);
for (int p : prefix) {
System.out.print(p + " ");
}
System.out.println();
}
public static int[] computePrefix(String input) {
int[] pi = new int[input.length()];
int k = 0;
for(int q = 2; q < input.length(); q++) {
while (k > 0 && input.charAt(k) != input.charAt(q)) {
k = pi[k];
}
if (input.charAt(k) == input.charAt(q)) {
k = k + 1;
}
pi[q] = k;
}
return pi;
}
}
That's now much easier to follow, IMO.
We can now look back to the pseudocode and see that it appears to be using 1-based indexing for both arrays and strings. That makes life slightly tricky. We could mimic that throughout the code, changing every array access and charAt call to just subtract 1.
(I've extracted the common subexpression of P[q] to a variable target within the loop.)
public static int[] computePrefix(String input) {
int[] pi = new int[input.length()];
int k = 0;
for (int q = 2; q <= input.length(); q++) {
char target = input.charAt(q - 1);
while (k > 0 && input.charAt(k + 1 - 1) != target) {
k = pi[k - 1];
}
if (input.charAt(k + 1 - 1) == target) {
k++;
}
pi[q - 1] = k;
}
return pi;
}
That now gives your desired results, but it's really ugly. We can shift q very easily, and remove the + 1 - 1 parts:
public static int[] computePrefix(String input) {
int[] pi = new int[input.length()];
int k = 0;
for (int q = 1; q < input.length(); q++) {
char target = input.charAt(q);
while (k > 0 && input.charAt(k) != target) {
k = pi[k - 1];
}
if (input.charAt(k) == target) {
k++;
}
pi[q] = k;
}
return pi;
}
It's still not entirely pleasant, but I think it's what you want. Make sure you understand why I had to make the changes I did.
public static int[] computePrefix(String input) {
int[] pi = new int[input.length()];
pi[0] = -1;
int k = -1;
for (int q = 1; q < input.length(); q++) {
char target = input.charAt(q);
while (k > 0 && input.charAt(k + 1) != target) {
k = pi[k];
}
if (input.charAt(k + 1) == target) {
k++;
}
pi[q] = k;
}
return pi;
}
I asked a question on helping me with this question about a week ago
Java permutations
, with a problem in the print permutation method. I have tidied up my code and have a working example that now works although if 5 is in the 5th position in the array it doesn't print it. Any help would be really appreciated.
package permutation;
public class Permutation {
static int DEFAULT = 100;
public static void main(String[] args) {
int n = DEFAULT;
if (args.length > 0)
n = Integer.parseInt(args[0]);
int[] OA = new int[n];
for (int i = 0; i < n; i++)
OA[i] = i + 1;
System.out.println("The original array is:");
for (int i = 0; i < OA.length; i++)
System.out.print(OA[i] + " ");
System.out.println();
System.out.println("A permutation of the original array is:");
OA = generateRandomPermutation(n);
printArray(OA);
printPermutation(OA);
}
static int[] generateRandomPermutation(int n)// (a)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;
for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
int swap = A[r];
A[r] = A[i];
A[i] = swap;
}
return A;
}
static void printArray(int A[]) {
for (int i = 0; i < A.length; i++)
System.out.print(A[i] + " ");
System.out.println();
}
static void printPermutation(int[] p)
{
int n = p.length-1;
int j = 0;
int m;
int f = 0;
System.out.print("(");
while (f < n) {
m = p[j];
if (m == 0) {
do
f++;
while (p[f] == 0 && f < n);
j = f;
if (f != n)
System.out.print(")(");
}
else {
System.out.print(" " + m);
p[j] = 0;
j = m - 1;
}
}
System.out.print(" )");
}
}
I'm not too crazy about
int n = p.length-1;
followed by
while (f < n) {
So if p is 5 units long, and f starts at 0, then the loop will be from 0 to 3. That would seem to exclude the last element in the array.
You can use the shuffle method of the Collections class
Integer[] arr = new Integer[] { 1, 2, 3, 4, 5 };
List<Integer> arrList = Arrays.asList(arr);
Collections.shuffle(arrList);
System.out.println(arrList);
I don't think swapping each element with a random other element will give a uniform distribution of permutations. Better to select uniformly from the remaining values:
Random rand = new Random();
ArrayList<Integer> remainingValues = new ArrayList<Integer>(n);
for(int i = 0; i < n; i++)
remainingValues.add(i);
for(int i = 0; i < n; i++) {
int next = rand.nextInt(remainingValues.size());
result[i] = remainingValues.remove(next);
}
Note that if order of running-time is a concern, using an ArrayList in this capacity is n-squared time. There are data-structures which could handle this task in n log n time but they are very non-trivial.
This does not answer the problem you have identified.
Rather i think it identifies a mistake with your generateRandomPermutation(int n) proc.
If you add a print out of the random numbers generated (as i did below) and run the proc a few times it allows us to check if all the elements in the ARRAY TO BE permed are being randomly selected.
static int[] generateRandomPermutation(int n)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;
System.out.println("random nums generated are: ");
for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
System.out.print(r + " ");
Run the proc several times.
Do you see what i see?
Jerry.