Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created March 7, 2016 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/76dffc51880a80279f25 to your computer and use it in GitHub Desktop.
Save jianminchen/76dffc51880a80279f25 to your computer and use it in GitHub Desktop.
Bear And Steady Gene - binary search algorithm
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BearAndSteadyGene_BinarySearch
{
/*
* March 6, 2016
* code source:
* java code: https://gist.github.com/jianminchen/d01faa03ca9b06696db3
* convert it to C# code
*/
class BearAndSteadyGene_BinarySearch
{
static String GENES = "ACGT";
static void Main(string[] args)
{
int N = Int32.Parse(Console.ReadLine());
string line = Console.ReadLine();
Console.WriteLine(solve( N, line));
}
public static int solve(int n, string s) {
int[] a = new int[n];
int need = n / 4;
int[] cnt = new int[4];
for (int i = 0; i < n; i++) {
a[i] = indexOfGENES(s[i]);
cnt[a[i]]++;
}
if (cnt[0] == need && cnt[1] == need && cnt[2] == need && cnt[3] == need) {
return 0;
}
int low = 0;
int high = n;
while (high - low > 1) { // >1, confused here as well.
int mid = (low + high) >> 1;
int[] tmp = cloneF(cnt);
for (int i = 0; i < mid; i++) {
tmp[a[i]]--;
}
if (tmp[0] <= need && tmp[1] <= need && tmp[2] <= need && tmp[3] <= need) {
high = mid;
continue ;
}
bool isBreak = false;
for (int i = mid; i < n; i++) {
tmp[a[i - mid]]++; // test case: GAAATAAA, cannot figure out why we need to add tmp[a[0]]
tmp[a[i]]--;
if (tmp[0] <= need && tmp[1] <= need && tmp[2] <= need && tmp[3] <= need) {
high = mid;
isBreak = true;
break; // two loops, only break nearest loop for
}
}
if(!isBreak)
low = mid;
}
return high;
}
private static int indexOfGENES(char c)
{
for (int i = 0; i < GENES.Length; i++)
if (c == GENES[i])
return i;
return -1;
}
private static int[] cloneF(int[] cnt)
{
int[] ret = new int[4];
for(int i=0; i<4; i++)
ret[i] = cnt[i];
return ret;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment