Skip to content

Instantly share code, notes, and snippets.

@sadikovi
Last active August 29, 2015 14:06
Show Gist options
  • Save sadikovi/e08e17d6b63ebd9192ac to your computer and use it in GitHub Desktop.
Save sadikovi/e08e17d6b63ebd9192ac to your computer and use it in GitHub Desktop.
Codility Lesson 3
class Solution {
public int solution(int A, int B, int K) {
return B/K - A/K + ((A % K == 0)?1:0);
}
}
class Solution {
public int[] solution(String S, int[] P, int[] Q) {
int[] seq = new int[P.length];
int[][] fs = new int[3][S.length()];
for (int i=0; i<S.length(); i++) {
short a = 0; short c = 0; short g = 0;
if (S.charAt(i) == 'A') a = 1;
if (S.charAt(i) == 'C') c = 1;
if (S.charAt(i) == 'G') g = 1;
fs[0][i] = ((i==0)?0:fs[0][i-1]) + a;
fs[1][i] = ((i==0)?0:fs[1][i-1]) + c;
fs[2][i] = ((i==0)?0:fs[2][i-1]) + g;
}
for (int k=0; k<P.length; k++) {
if (P[k] == Q[k]) {
if (S.charAt(P[k]) == 'A') seq[k] = 1;
if (S.charAt(P[k]) == 'C') seq[k] = 2;
if (S.charAt(P[k]) == 'G') seq[k] = 3;
if (S.charAt(P[k]) == 'T') seq[k] = 4;
} else {
if (P[k] > 0) {
if ((fs[0][Q[k]] - fs[0][P[k]-1]) > 0) {
seq[k] = 1;
} else if ((fs[1][Q[k]] - fs[1][P[k]-1]) > 0) {
seq[k] = 2;
} else if ((fs[2][Q[k]] - fs[2][P[k]-1]) > 0) {
seq[k] = 3;
} else {
seq[k] = 4;
}
} else {
if (fs[0][Q[k]] > 0) seq[k] = 1;
else if (fs[1][Q[k]] > 0) seq[k] = 2;
else if (fs[2][Q[k]] > 0) seq[k] = 3;
else seq[k] = 4;
}
}
}
return seq;
}
}
class Solution {
public int solution(int[] A) {
int[] fs = new int[A.length];
for (int i=0; i<A.length; i++) {
if (i==0) fs[i] = A[i];
if (i>0) fs[i] = fs[i-1] + A[i];
}
double avg = fs[1]/2.0;\
int startingPos = 0;\
for (int j=2; j< fs.length; j++) {
// 2 elements in slice
double tempAvg2 = (fs[j]-fs[j-2])/2.0;
if (tempAvg2 < avg) {
avg = tempAvg2;
startingPos = j-1;
}
// 3 elements in slice
double tempAvg3 = (fs[j]-((j>2)?fs[j-3]:0))/3.0;
if (tempAvg3 < avg) {
avg = tempAvg3;
startingPos = j-2;
}
}
return startingPos;
}
}
// solution 2
// might be a bit faster than the previous one
class Solution {
public int solution(int[] A) {
double minAvg = (A[0] + A[1]) / 2.0;
int pos = 0;
for (int i=0; i<A.length-1; i++) {
if (minAvg > (A[i] + A[i+1]) / 2.0) {
minAvg = (A[i] + A[i+1]) / 2.0;
pos = i;
}
if (i < A.length-2) {
if (minAvg > (A[i] + A[i+1] + A[i+2]) / 3.0) {
minAvg = (A[i] + A[i+1] + A[i+2]) / 3.0;
pos = i;
}
}
}
return pos;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment