Last active
August 29, 2015 14:13
-
-
Save xynophon/dc9bfc91d28c55694af9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Created by xynophon on 15.1.12. | |
| */ | |
| import java.util.Random; | |
| import java.util.Scanner; | |
| public class moving_Average { | |
| // O(n^2) | |
| public void solution(double[] weights, int num_ma){ | |
| for(int cnt = 0; cnt <= weights.length-num_ma; cnt++){ | |
| double weight_sum = 0.0; | |
| for(int i = cnt; i < cnt+num_ma; i++){ | |
| weight_sum += weights[i]; | |
| } | |
| System.out.println("avg : "+weight_sum/num_ma); | |
| } | |
| } | |
| // O(n) | |
| public void solution_en(double[] weights, int num_ma){ | |
| double sum = 0.0; | |
| for(int i = 0; i < num_ma-1; i++){ | |
| sum += weights[i]; | |
| } | |
| for(int i = num_ma-1; i < weights.length; i++){ | |
| sum += weights[i]; | |
| System.out.println("ma : "+ sum/num_ma); | |
| sum -= weights[i-num_ma+1]; | |
| } | |
| } | |
| public static void main(String args[]){ | |
| moving_Average ma = new moving_Average(); | |
| System.out.print("how many items : "); | |
| Scanner sc = new Scanner(System.in); | |
| int how_many = sc.nextInt(); | |
| double[] weights = new double[how_many]; | |
| Random rnd = new Random(); | |
| for(int count = 0; count <how_many; count++){ | |
| weights[count] = rnd.nextDouble()*100; | |
| } | |
| System.out.print("moving avg : "); | |
| int num_ma = sc.nextInt(); | |
| for(double weight:weights){ | |
| System.out.println(weight + " "); | |
| } | |
| ma.solution_en(weights, num_ma); | |
| ma.solution(weights, num_ma); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment