So, I have a method that is looping through and returning these numbers automatically :
6527.6 6755.6 7009.9 7384.7 7775.9 8170.7 8382.6 8598.8 8867.6 9208.2 9531.8 9821.7 10041.6 10007.2 9847.0 10036.3 10263.5 10449.7 10699.7
I would like to average the first number to the second number, the second to the third number, and so on. What ways should I go about doing this? Adding all these doubles to an array? Or is there a way to get a running total in order to do this?
The problem I'm having is that I can only seem to get all or none of these doubles, not specific ones.
So the output would be the results of something like (6527.6+6755.6)/2, (6755.6+7009.9)/2, and so on. Just printing them, nothing else.
Edit : Code from the parser here : http://pastebin.com/V6yvntcP
What you are describing is known as moving average.
Some formal explanation is here:
http://en.wikipedia.org/wiki/Moving_average
[...] simple moving average (SMA) is the unweighted mean of the previous n data [...]
You want to compute moving average for n = 2.
Below is simple code that do this:
public static void main(String[] args) {
List<Double> list = Arrays.asList(6527.6, 6755.6, 7009.9, 7384.7, 7775.9, 8170.7);
for (int i = 1; i < list.size(); i++) {
double avg = (list.get(i) + list.get(i - 1)) / 2;
System.out.println("avg(" + (i - 1) + "," + i + ") = " + avg);
}
}
And second approach without List or array:
Double prev = null;
// inside loop:
double curr = getMethodResult(...);
if (prev != null) {
double avg = (curr + prev) / 2;
}
prev = curr;
// end of loop
Create and array of double and just do some traversing and swapping and its done. Check it out:
double[] array = { 6527.6, 6755.6, 7009.9, 7384.7, 7775.9, 8170.7 };
double avg = 0;
double sum = 0.0;
double temp = 6527.6;
for (int i = 0; i < array.length - 1; i++) {
sum = temp + array[i + 1];
avg = sum / 2;
System.out.println("(" + temp + "+" + array[i + 1] + ")/2" + "= "
+ avg);
temp = avg;
}
So I've looked at "questions that may already have my answer" but, despite getting the same error message as those questions, I think I may have a different issue:
//find greatest product generated by 5 consecutive integers below
class project_euler8 {
public static String numbers =
"73167176531330624919225119674426574742355349194934" +
"96983520312774506326239578318016984801869478851843" +
"85861560789112949495459501737958331952853208805511" +
"12540698747158523863050715693290963295227443043557" +
"66896648950445244523161731856403098711121722383113" +
"62229893423380308135336276614282806444486645238749" +
"30358907296290491560440772390713810515859307960866" +
"70172427121883998797908792274921901699720888093776" +
"65727333001053367881220235421809751254540594752243" +
"52584907711670556013604839586446706324415722155397" +
"53697817977846174064955149290862569321978468622482" +
"83972241375657056057490261407972968652414535100474" +
"82166370484403199890008895243450658541227588666881" +
"16427171479924442928230863465674813919123162824586" +
"17866458359124566529476545682848912883142607690042" +
"24219022671055626321111109370544217506941658960408" +
"07198403850962455444362981230987879927244284909188" +
"84580156166097919133875499200524063689912560717606" +
"05886116467109405077541002256983155200055935729725" +
"71636269561882670428252483600823257530420752963450";
public static int calculateProduct(int[] myArray) {
int product = 1;
for (int i = 0; i < myArray.length; i++) {
product *= myArray[i];
}
return product;
}
public static void main(String[] args) {
//declare biggest_product, temporary array
int biggest_product = 0;
int[] temp = new int[5];
//loop through each sequence of 5 integers
for (int i = 0; i < numbers.length() - 5; i++) {
int remainder = i % 5;
**temp[remainder] = Integer.parseInt(numbers[i]);**
int candidate_product = calculateProduct(temp);
if (candidate_product > biggest_product) {
biggest_product = candidate_product;
}
}
System.out.println("Biggest product is " + biggest_product);
}
The line the compiler doesn't like is bolded above. If I declare my array (temp) within the for loop, will this fix the issue? I'm a bit confused why I can't assign integer values element-wise based on array index...
I know arrays in Java are immutable but, if this were the case, how could I assign values at any point after array declaration?
numbers isn't declared as an array; it is instead a String.
If you wanted to iterate over each character in the String, then that can be accomplished by numbers.charAt(i).
However, since what you're getting back is a char and not a String, you have to convert it appropriately (that is, subtract '0' from your numerical character to normalize it).
Since a char really is an int (with a shorter range), there's no convenience method in Integer to convert from a char to an int, so one has to subtract the char '0' to get a number back.
That solution would look something like this:
temp[remainder] = numbers.charAt(i) - '0';
This means that you have more work to do in changing the signature of your method that accepts an int[], but I leave that as an exercise for the reader.
It looks like you want to extract five digits from i to i+5. You can achieve this with substring method.
Instead of:
temp[remainder] = Integer.parseInt(numbers[i]);
do:
temp[remainder] = Integer.parseInt(numbers.substring(i,i+5));
I want to move cursor up to the beginning after it wrote something at lower part. I mean is there something like SetCursorPosition(0,0)?
edit: it is about writing 6x3 matrix with numbers in it. it should be seem like this
...
7 8 9
4 5 6
1 2 3
it'll start write from bottom. when the cursor at (0,0) it'll put 6x space then write 1 2 3, then go to (0,0), put 5x space, write 4 5 6 ...
code:
boolean sa;
int yoyo;
int lo = 18;
int y = 0;
for (int k = 1; k < 100; k++)
{
if (y < 18)
{
sa = true;
for (int h = 2; h < k; h++)
{
if (k % h == 0)
sa = false;
}
if (sa)
{
lo--;
if (y % 3 == 0)
{
yoyo = lo / 3 + 1;
// here where I need Console.SetCursorPosition(0,0)
for (int yos = 0; yos < yoyo; yos++)
{
System.out.print("\n");
}
if (k < 10)
System.out.print(" " + k + " ");
else
System.out.print(k + " ");
}
else
{
if (k< 10)
System.out.print(" " + k + " ");
else
System.out.print(k + " ");
}
y++;
}
}
}
Unfortunately, Java doesn't have full console support.
You might try JLine.
I asked the developers of JLine and you can set the cursor position using this.
terminal.puts(InfoCmp.Capability.cursor_address, 0, 0);
Here's a small example of it's usage and as an added bonus I'll show how to make the cursor invisible and visible.
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.jline.utils.InfoCmp;
import java.io.IOException;
public class CursorStuff
{
public static void main(String[] args) throws IOException, InterruptedException
{
int row = 10;
int col = 40;
Terminal terminal = TerminalBuilder.terminal();
terminal.puts(InfoCmp.Capability.cursor_address, row, col);
System.out.println("Here we start at row " + row + " col " + col);
System.out.println("Now you see the cursor");
Thread.sleep(2000);
terminal.puts(InfoCmp.Capability.cursor_invisible);
System.out.println("Now you don't!");
Thread.sleep(2000);
terminal.puts(InfoCmp.Capability.cursor_visible);
System.out.println("And the cursor is back again.");
}
}
Make sure to have either Jansi or JNA in your libraries otherwise you will get a dumb terminal and not be able to use these functions at least on Windows as it requires these to do native function calls.
As far as I can tell this is the easiest method to accomplish this as before I knew this was an option I was writing C++ and calling those native function calls I made using JNI.
im trying to write an algorithm that will find all the possible values of A^5 + B^5 + C^5 when the user inputs a number 'N'.
For example if N=100 I want to make an array that contains all the possible values where each slot in the array contains a number that was found by plugging in numbers between 1-100 for A^5 + B^5 + C^5. So one of the positions in the array contains 1 from (1^5 + 1^5 + 1^5). Another position in the array contains
the number 355447518 (from 19^5 + 43^5 + 46^5). So there will be 100^3 elements in my array.
public long[] possibleValues(int n)
{
long[] solutionSet = new long[(int) Math.pow(n, 3)];
for(int i=1;i<=n;i++)
{
solutionSet[i] = ((long) Math.pow(i, 5) + (long) Math.pow(i, 5) + (long) Math.pow(i, 5));
//testing purposes
System.out.println(i +"^5 " + "+" + i+"^5 " + "+" + i+"^5" + "=" + solutionSet[i]);
}
return solutionSet;
}
thats what I have so far, but my problem is that it doesn't do all the permutations of N. What is the best way to get all possible permutations of N? Am i making this more complicated than necessary? How would I arrange all possible (A, B, C)'s ?
Use nested forloops:
index=0;
for (int i=1;i<=n;i++){
for (int j=1;i<=n;j++){
for (int k=1;i<=n;k++){
solutionSet[index++] = ((long) Math.pow(i, 5) + (long) Math.pow(j, 5) + (long) Math.pow(k, 5));
}
}
}
You can calculate all powers quicker by using an array containing all fifth powers up to N.
You're using i for all 3 terms, thus you're essentially calculating permutations of
A^5 + A^5 + A^5 = 3A^5.
You need a 3-dimensional array and 3 for loops.
public long[][][] possibleValues(int n)
{
long[][][] solutionSet = new long[n+1][n+1][n+1];
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
for(int k=1;k<=n;k++)
{
solutionSet[i][j][k] = ((long) Math.pow(i, 5) + (long) Math.pow(j, 5) + (long) Math.pow(k, 5));
//testing purposes
System.out.println(i +"^5 " + "+" + j+"^5 " + "+" + k+"^5" + "=" + solutionSet[i][j][k]);
}
return solutionSet;
}
If you indeed only want a 1-dimensional array, you'll do something similar to the above, just have a separate variable for the index:
Since you probably don't want excessive repetition of values, you can probably start j from i and k from j.
public long[] possibleValues(int n)
{
long[] solutionSet = new long[n*n*n];
int c = 0;
for(int i = 1; i <= n; i++)
for(int j = i; j <= n; j++)
for(int k = j; k <= n; k++)
{
solutionSet[c] = ((long) Math.pow(i, 5) + (long) Math.pow(j, 5) + (long) Math.pow(k, 5));
//testing purposes
System.out.println(i +"^5 " + "+" + j+"^5 " + "+" + k+"^5" + "=" + solutionSet[c]);
c++;
}
return solutionSet;
}
Some significant optimizations can still be done:
Math.pow isn't particularly efficient, as Peter mentioned.
For the first version, you can derive values from previous values in certain circumstances.
The really brute-force way to do it would require three nested loops:
for(int a = 1; a <= n; ++a)
{
for(int b = 1; b <= n; ++b)
{
for(int c = 1; c <= n; ++c)
{
// Add this combination to your array, and print it out.
// It may be more convenient to use ArrayList instead of long[].
}
}
}
Note that for this takes O(n^3) time, so n doesn't have to be very large before it will take forever to compute (and also use up all of your memory).
Use three loops. One each for A, B, C. This is a pseudo code and does not adhere to java syntax
for(int A:100){
for(int B:100){
for(int C:100) {
calculate A^5 * B^5 * C^5
}
}
}
I agree with the other answers about nested forloops. For better performance it may be profitable to store the answers in a hash table so that you don't recalculate the same value. For instance, you calculate 15^5 then you store that answer in an array like ans['155'] = 759375. So when you go to calculate 15^5 again you can do an if statement if(ans[num.tostring+'5']) then use that value instead of calculating 15^5 again.
Starting from #Dukeling previous answer:
I use a powers array to compute the powers just n times (not n*n*n)
public static void test(int n){
long[] powers = new long[n+1];
for (int i=0; i<powers.length; i++)
powers[i] = (long) Math.pow(i, 5);
long[][][] solutionSet = new long[n+1][n+1][n+1];
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
for(int k=1;k<=n;k++)
{
solutionSet[i][j][k] = ((long) powers[i] + (long) powers[i] + (long) powers[i]);
//testing purposes
System.out.println(i +"^5 " + "+" + j+"^5 " + "+" + k+"^5" + "=" + solutionSet[i][j][k]);
}
}
I believe you are looking for a combination and not a permutation. It also seems that you want A, B, and C to be all possible values from 1 to N. In that case, you'll want to make your nested for loop as such to only calculate the combinations:
for (int a = 0; a < n; a++) {
for (int b = 0; b <= a; b++) {
for (int c = 0; c <= b; c++) {
pow5(a) + pow5(b) + pow5(c);
}
}
}
You'll also want to use a lookup table which could be loaded from a file. The more values in your lookup table, the faster your algorithm will perform. In my opinion, the best method will reduce the number of operations required. That means not calculating every value at runtime. Alternatively, you could also optimize for memory usage and just use a simple algorithm. Additionally, you'll want to measure the performance of the algorithm. Here is an example.
// for all number > 0 and <= 25
public static final double[] powersOf5 = {1.0, 32.0, 243.0, 1024.0, 3125.0,
7776.0, 16807.0, 32768.0, 59049.0, 100000.0, 161051.0, 248832.0, 371293.0,
537824.0, 759375.0, 1048576.0, 1419857.0, 1889568.0, 2476099.0, 3200000.0,
4084101.0, 5153632.0, 6436343.0, 7962624.0, 9765625.0};
// calc pow(i, 5) and use a lookup table for small values i
public static double pow5(int i) {
if (i > 0 && i <= 25) {
return powersOf5[i-1];
} else {
return Math.pow(i, 5);
}
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
System.out.println(pow5(i));
}
long end = System.currentTimeMillis();
System.out.println("Execution time: " + (end - start) + " ms");
}
have a think at first
1. 1^5 + 2^5 + 3^5 = 3^5 + 2^5 +1^5 , So i<j<k
for(i=0;i<N;i++)
for(j=i;j<N;j++)
for(k=j;k<N;k++)
2. A^5+B^5+C^5=D^5+E^5+F^5
If we use array , there may be lots of same value in it.
we can use Set to save memory, if time is not the most important.
3. A^5 cannot be saved by Long type, when A is too big.
So, do we make sure N is little? otherwise, there may be a bug.
4. Multiplication cost lots of time.
Give a example, if N=100, to get all result, how many times does it spend
calc 5^5.
5^5+1^5+1^5
5^5+1^5+2^5
5^5+1^5+3^5
...
How about if there is an array save the answer
define array[i] = i^5
Then it save our time;
Just think more, Algorithm is something that like this
Now let's talk more about Math.pow();
Yes it's a good method that help you, but this is an algorithm which is impl, we just want to know A^5, not A^N, the second parameter is static;
Why not impl a method by yourself.
First, we try to impl a method like this
public Long powOf5(Long A){
return A*A*A*A*A;
}
Then, we find we can optimize it.
public Long powOf5(Long A){
Long A2 = A*A;
return A2*A2*A;
}
This multiply 3 times, that multiply 4 times;
I am sure this method is faster than Math.pow()
I'm sure I'm making a rookie mistake with java(this is actually my first program). I am trying to port some working python code I made into java(as a learning/testing exercise to learn a bit of the differences) but I'm getting different results between the two.
My program takes a list of data and generates another list based on it(basically sees if a value can be broken down by a sum). Python correctly gives 2,578 results while Java only gives 12. I tried to find the same commands in java and thought I did but can't seem to figure out why the results differ(the difference between the two I have experienced problems with multi threading and syncing of variables, wasn't sure if Java was doing anything behind the scenes so I had a while loop to keep running until the results stabilize, but it didn't help). Any suggestions would be helpful.
Here's the offending code(java at the top, python and pseudo code commented out in the bottom as reference):
for (int c = 0; c <= max_value; c++){
String temp_result = (s - c * data.get(i) + "," + i);
if( results.contains( temp_result ) ){
String result_to_add = (s + "," + i+1);
if( results.contains( result_to_add ) ){
System.out.println("contains result already");
} else {
results.add(result_to_add);
} print len(T)
#Here's the basic pseudo code(I added a few control variables but here's a high level view):
for i = 1 to k
for z = 0 to sum:
for c = 1 to z / x_i:
if T[z - c * x_i][i - 1] is true:
set T[z][i] to true
*/
In java s + "," + i+1 is a String concatenation : "10" + "," + 4 + 1 will return 10,41.
Use String result_to_add = s + "," + (i+1); instead.
I see you've solved it just now, but since I've written it already, here's my version:
This uses the trick of using a Point as a substitute for a 2-element Python list/tuple of int, which (coincidentally) bypasses your String concatenation issue.
public class Sums
{
public static void main(String[] args)
{
List T = new ArrayList();
T.add(new Point(0, 0));
int target_sum = 100;
int[] data = new int[] { 10, -2, 5, 50, 20, 25, 40 };
float max_percent = 1;
int R = (int) (target_sum * max_percent * data.length);
for (int i = 0; i < data.length; i++)
{
for (int s = -R; s < R + 1; s++)
{
int max_value = (int) Math.abs((target_sum * max_percent)
/ data[i]);
for (int c = 0; c < max_value + 1; c++)
{
if (T.contains(new Point(s - c * data[i], i)))
{
Point p = new Point(s, i + 1);
if (!T.contains(p))
{
T.add(p);
}
}
}
}
}
System.out.println(T.size());
}
}