Skip to content

Commit

Permalink
MinAvgTwoSlice
Browse files Browse the repository at this point in the history
  • Loading branch information
adrianiacobghiula committed Jun 5, 2020
1 parent 0b2fa6c commit a4383b3
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/main/java/codility/p05_prefix_sums/MinAvgTwoSlice.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package codility.p05_prefix_sums;

/*
https://app.codility.com/programmers/lessons/5-prefix_sums/min_avg_two_slice/
*/
public class MinAvgTwoSlice {

//https://app.codility.com/demo/results/training2QFURF-GHG/
public int solution(int[] a) {
int minAvgPos = 0;
double avg = (a[0] + a[1]) / 2d;
for (int i = 0; i < a.length - 1; i++) {
double avg2 = (a[i] + a[i + 1]) / 2d;
if (avg > avg2) {
avg = avg2;
minAvgPos = i;
}
if (i + 2 < a.length) {
double avg3 = (a[i] + a[i + 1] + a[i + 2]) / 3d;
if (avg > avg3) {
avg = avg3;
minAvgPos = i;
}
}
}
return minAvgPos;
}

}
22 changes: 22 additions & 0 deletions src/test/java/codility/p05_prefix_sums/MinAvgTwoSliceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package codility.p05_prefix_sums;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class MinAvgTwoSliceTest {
MinAvgTwoSlice minAvgTwoSlice;

@BeforeEach
public void init() {
minAvgTwoSlice = new MinAvgTwoSlice();
}

@Test
public void sample1() {
int solution = minAvgTwoSlice.solution(new int[]{4, 2, 2, 5, 1, 5, 8});
assertThat(solution).isEqualTo(1);
}

}

0 comments on commit a4383b3

Please sign in to comment.