Terminated due timeout - java

when i submit my code i get some successful test cases , but for some other test cases i get terminated due timeout , any help please ? i know it must be more optimized but i did my best to optimise and i still have the same problem , this is my code :
public class Solution{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();//
long tab[] = new long[T];
String s;
int n;
int j=0;
while(T-->0){
s=scan.next();
n=scan.nextInt();
if(s.equals("add"))
{
tab[j]=n;
j++;
}
if(s.equals("del"))
{
int i=0;
boolean e=false;
while(!e)
{
if(tab[i]==n)
{
e=true;
tab[i]=-1;
}
else
{
i++;
}
}
}
if(s.equals("cnt"))
{
int count=0;
int k=0;
while(k<j)
{
if((tab[k]!=-1)&&(n&tab[k])==tab[k])
{
count++;
}
k++;
}
System.out.println(count);
}}
}
}

If the number of testcases are high then Scanner might be slower compared to BufferedReader. I use a custom class as Scanner might be helpful to you.
private static final class FastScanner {
private final InputStream mIs;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner() {
this(System.in);
}
public FastScanner(final InputStream is) {
this.mIs = is;
}
public int read() {
if (this.numChars == -1) {
throw new InputMismatchException();
}
if (this.curChar >= this.numChars) {
this.curChar = 0;
try {
this.numChars = this.mIs.read(this.buf);
} catch (final IOException e) {
throw new InputMismatchException();
}
if (this.numChars <= 0) {
return -1;
}
}
return this.buf[this.curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
final StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c;
while (isSpaceChar(c = read())) {
}
final StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextArray(final int n) {
final int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(final int n) {
final long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
public char[] nextCharArray(final int n) {
final char[] buf = new char[n];
int b, p = 0;
while (isSpaceChar(b = read())) {
}
while (p < n && !isSpaceChar(b)) {
buf[p++] = (char) b;
b = read();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
public char[][] nextMatrix(final int n, final int m) {
final char[][] map = new char[n][];
for (int i = 0; i < n; i++) {
map[i] = nextCharArray(m);
}
return map;
}
public int[][] nextIntMatrix(final int n, final int m) {
final int[][] map = new int[n][];
for (int i = 0; i < n; i++) {
map[i] = nextArray(m);
}
return map;
}
public long[][] nextLongMatrix(final int n, final int m) {
final long[][] map = new long[n][];
for (int i = 0; i < n; i++) {
map[i] = nextLongArray(m);
}
return map;
}
public boolean isSpaceChar(final int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(final int c) {
return c == '\n' || c == '\r' || c == -1;
}
}

Related

more efficiently read int values from console

How can I read int values from console more efficiently (from memory) than this:
BufferedReader in ...
number = Integer.parseInt(in.readLine());
When I use readLine() and parse it to int, java create many String objects and сonsumes memory. I try to use Scanner and method nextInt() but this approach is also not that efficiently.
P.S I need read > 1000_000 values and I have memory limit.
EDIT Full code of task
import java.io.*;
public class Duplicate {
public static void main(String[] args) throws IOException {
int last = 0;
boolean b = false;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
for (int i = 0; i < n; i++) {
int number =Integer.parseInt(reader.readLine());
if (number == 0 && !b) {
System.out.println(0);
b = true;
}
if (number == last) continue;
last = number;
System.out.print(last);
}
}
}
And Rewrite variant:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
public class Duplicate {
public static void main(String[] args) throws IOException {
int last = 0;
boolean b = false;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int nextInt = getNextInt(reader);
for (int i = 0; i < nextInt; i++) {
int number = getNextInt(reader);
if (number == 0 && !b) {
System.out.println(0);
b = true;
}
if (number == last) continue;
b = true;
last = number;
System.out.println(last);
}
}
static int getNextInt(Reader in) throws IOException {
int c;
boolean negative = false;
do {
c = in.read();
if (!Character.isDigit(c)) {
negative = c == '-';
}
} while (c != -1 && !Character.isDigit(c));
if (c == -1) return Integer.MIN_VALUE;
int num = Character.getNumericValue(c);
while ((c = in.read()) != -1 && Character.isDigit(c)) {
num = 10 * num + Character.getNumericValue(c);
}
return negative ? -num : num;
}
}
Both options do not pass from memory (((
EDIT2 I try profiling
int number = getRandom(); and start with 1000000
once again launched the same
and splash GC
You can read from in one char at a time, checking if it's a digit, and then accumulating it into a number. Something like:
int getNextInt(Reader in) throws IOException {
int c;
boolean negative = false;
do {
c = in.read();
if (!Character.isDigit(c)) { negative = c == '-' };
} while (c != -1 && !Character.isDigit(c));
if (c == -1) return Integer.MIN_VALUE; // Some sentinel to indicate nothing found.
int num = Character.getNumericValue(c);
while ((c = in.read()) != -1 && Character.isDigit(c)) {
num = 10 * num + Character.getNumericValue(c);
}
return negative ? -num : num;
}
Ideone demo
Of course, this is incredibly primitive parsing. But you could perhaps take this code as a basis and adapt it as required.
You can use this FastScanner class
static class FastScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public FastScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
public String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n");
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
It is very commonly used on codeforces to read large input where Scanner class leads to TLE
This is originally authored by https://codeforces.com/profile/Petr
I use this InputReader on codeforces. Works pretty well for me on large input cases. You can extend this up to your use case. I came across this after getting TLE using Scanner and add functionalities if needed.
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() {
try {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0)
return -1;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return buf[curChar++];
}
public int readInt() {
return (int) readLong();
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
if (c == -1) throw new RuntimeException();
}
boolean negative = false;
if (c == '-') {
negative = true;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
res *= 10;
res += (c - '0');
c = read();
} while (!isSpaceChar(c));
return negative ? (-res) : (res);
}
public int[] readIntArray(int size) {
int[] arr = new int[size];
for (int i = 0; i < size; i++) arr[i] = readInt();
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}

Why do we apply BFS/DFS in SPOJ(ALLIZWELL) ? Why would not simple brute force work?

Problem Link
By brute force I mean if I take 6 variables a,l,i,w,e,z for alphabet A,L,I,W,E,Z and count their number of occurrence apply condition as:
if(a<1||l<4||i<1||w<1||e<1||z<2)
{
System.out.println("NO");
}
else
System.out.println("YES");
What's wrong in that?
Here's my complete code and also I'm getting wrong answer.
import java.io.*;
public class Main {
public static void main(String asd[]) throws Exception {
Parser in = new Parser(System.in);
int t=in.nextInt();
while(t-->0)
{
int r=in.nextInt();
int c=in.nextInt();int a,l,i,z,w,e;
a=l=i=z=w=e=0;
for(int j=0;j<r;j++)
{
String s=in.next();
for(int k=0;k<s.length();k++)
{
char ch=s.charAt(k);
switch(ch)
{
case 'A':a++;break;
case 'L':l++;break;
case 'I':i++;break;
case 'Z':z++;break;
case 'W':w++;break;
case 'E':e++;break;
}
}
}
if(a<1||l<4||i<1||w<1||e<1||z<2)
{
System.out.println("NO");
}
else
System.out.println("YES");
}
}
}
// for inputting
class Parser {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Parser(InputStream in) {
din = new DataInputStream(in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public long nextLong() throws Exception {
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
//reads in the next string
public String next() throws Exception {
StringBuilder ret = new StringBuilder();
byte c = read();
while (c <= ' ') c = read();
do {
ret = ret.append((char) c);
c = read();
} while (c > ' ');
return ret.toString();
}
public int nextInt() throws Exception {
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws Exception {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws Exception {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
}
Just because the matrix contains enough letters doesn't mean there's a path that puts them all in the right order.
For a simple example, consider
AILLZZWELL
You need an L adjacent to the A, but there is none.
Have you ever played the game "Boggle?" It's basically the same concept.

Memory Used 0Kb in Java

I was skimming through a few codes written in Java during a competitive programming contest and I simply Failed to understand the Memory used by their code turned out to be 0kb.
import java.io.*;
import java.util.*;
public class C {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
public void run() {
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
int[] a = in.nextIntArray(n);
long[] sum = new long[n+1];
for (int i = 1; i <= n; i++) {
sum[i] = sum[i-1] + a[i-1];
}
long[] cur = new long[n+1];
long[] old = new long[n+1];
for (int i = 1; i <= k; i++) {
Arrays.fill(cur, Long.MIN_VALUE / 2);
for (int j = i * m; j <= n; j++) {
cur[j] = Math.max(cur[j-1], old[j-m] + sum[j] - sum[j-m]);
}
long[] temp = cur;
cur = old;
old = temp;
}
System.out.println(old[n]);
out.close();
}
public static void main(String[] args) {
new C().run();
}
public void mapDebug(int[][] a) {
System.out.println("--------map display---------");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%3d ", a[i][j]);
}
System.out.println();
}
System.out.println("----------------------------");
System.out.println();
}
public void debug(Object... obj) {
System.out.println(Arrays.deepToString(obj));
}
class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
//stream = new FileInputStream(new File("dec.in"));
}
int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = nextInt();
return array;
}
long nextLong() {
return Long.parseLong(next());
}
long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nextLong();
return array;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDoubleArray(int n) {
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nextDouble();
return array;
}
String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
String[] nextStringArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++)
array[i] = next();
return array;
}
String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
}
How is memory used basically calculated during the contest? and what are the basic optimizations one can use in Java when it comes to execution time and memory.
And what is exactly the public void debug(Object ... obj) I've never seen anything like this before in java.

UVa-784 Wrong Answer [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am going crazy with this problem!
My solution is in Java - I have tried different inputs and haven't been able to reproduce the alleged wrong answer. Maybe someone here could possibly point to my solutions bottlenecks?
The verdict I am getting from UVa judge is "Wrong Answer".
// FOUND THE SOLUTION - I WAS PRINTING null chars at the end of some lines ('\u0000').
The problem is solved by adding if(maze[j][i] != '\u0000') before calling bufferedWriter.write(maze[j][i]
Thanks to everyone!
The intial code:
import java.io.*;
class Main {
public static final int MAX_NUMBER_OF_LINES = 31;
public static final int MAX_NUMBER_OF_CHARACTERS_PER_LINE = 81;
public static char[][] maze;
public static boolean[][] visitedLocations;
public static int numberOfMazes;
public static int numberOfLines;
public static int numberOfChars;
public static BufferedReader bufferedReader;
public static BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String args[]) throws IOException {
readFromStandardInput();
bufferedWriter.flush();
}
public static void readFromStandardInput() throws IOException {
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String line;
numberOfMazes = Integer.parseInt(bufferedReader.readLine());
int lineCounter = 0;
while (numberOfMazes > 0) {
maze = new char[MAX_NUMBER_OF_CHARACTERS_PER_LINE][MAX_NUMBER_OF_LINES];
visitedLocations = new boolean[MAX_NUMBER_OF_CHARACTERS_PER_LINE][MAX_NUMBER_OF_LINES];
lineCounter = 0;
while ((line = bufferedReader.readLine()) != null) {
if (line.charAt(0) == '_') {
break;
} else {
constructArrayLineByLine(line, lineCounter);
}
lineCounter++;
}
numberOfLines = lineCounter;
solvePreviousMaze();
bufferedWriter.write(line);
numberOfMazes--;
if (numberOfMazes > 0) {
bufferedWriter.write("\n");
}
}
}
public static void solvePreviousMaze() throws IOException {
for (int i = 1; i < numberOfLines; i++) {
for (int j = 1; j < numberOfChars; j++) {
if (maze[j][i] == '*') {
floodTheMaze(i, j);
solutionToStandardOutput();
return;
}
}
}
}
public static void solutionToStandardOutput() throws IOException {
for (int i = 0; i < numberOfLines; i++) {
for (int j = 0; j < numberOfChars; j++) {
bufferedWriter.write(maze[j][i]);
}
bufferedWriter.write("\n");
}
}
public static void floodTheMaze(int i, int j) {
if (visitedLocations[j][i]) {
return;
} else {
visitedLocations[j][i] = true;
}
if (maze[j][i] == ' ' || maze[j][i] == '*') {
maze[j][i] = '#';
floodTheMaze(i, j - 1);
floodTheMaze(i - 1, j);
floodTheMaze(i + 1, j);
floodTheMaze(i, j + 1);
}
}
public static void constructArrayLineByLine(String line, int numberOfLine) {
numberOfChars = Math.max(numberOfChars, line.length());
for (int i = 0; i < line.length(); i++) {
maze[i][numberOfLine] = line.charAt(i);
}
}
}
One very clear bug in your solution is that you are printing extra 'space characters' in your solution which is probably not what the question asked. For example, in the first sample output, you are printing extra spaces in the lower 5 lines. You can solve this problem by using an arraylist of array to store the input and then output that arraylist.
Also, you should probably output a new line after every line of output. (You are not doing so for the last line of output.)
Here is a link to my accepted solution for this problem.
import java.io.*;
import java.math.*;
import java.util.*;
import java.lang.*;
public class Main{
public static InputStream inputStream = System.in;
public static OutputStream outputStream = System.out;
public static FastReader in = new FastReader(inputStream);
public static PrintWriter out = new PrintWriter(outputStream);
public static void main(String[] args)throws java.lang.Exception{
new Main().run();
out.close();
}
int N;
int M;
boolean[][] dfsNode;
StringTokenizer tk;
char[][] grid;
char[][] filled;
String[] sep;
void run()throws java.lang.Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine().trim());
sep = new String[N];
for(int i=0; i<N; i++){
ArrayList<char[]> al = new ArrayList<char[]>();
while(true){
String s = br.readLine();
if(s.contains("_")){
sep[i] = s;
break;
}
char[] arr = s.toCharArray();
al.add(arr);
}
grid = new char[al.size()][];
for(int j=0; j<al.size(); j++){
grid[j] = al.get(j);
}
// ArrayUtils.printGrid(grid);
int stari = -1;
int starj = -1;
for(int j=0; j<grid.length; j++){
for(int k=0; k<grid[j].length; k++){
if(grid[j][k] == '*'){
stari = j;
starj = k;
break;
}
}
}
dfsNode = new boolean[grid.length][];
filled = new char[grid.length][];
for(int j=0; j<grid.length; j++){
char[] arr = new char[grid[j].length];
for(int k=0; k<grid[j].length; k++){
arr[k] = grid[j][k];
}
filled[j] = arr;
dfsNode[j] = new boolean[grid[j].length];
}
fillColour(stari, starj);
for(int j=0; j<filled.length; j++){
for(int k=0; k<filled[j].length; k++){
if(filled[j][k] == '*'){
out.print(' ');
}else{
out.print(filled[j][k]);
}
}
out.println();
}
out.println(sep[i]);
}
}
void fillColour(int row, int col){
if(row<0 || row>=grid.length || col<0 || col>=grid[row].length){
return;
}
if(dfsNode[row][col]){
return;
}
// fill on border?
if(grid[row][col]!=' ' && grid[row][col]!='*'){
return;
}
filled[row][col] = '#';
dfsNode[row][col] = true;
fillColour(row-1, col);
fillColour(row+1, col);
fillColour(row, col-1);
fillColour(row, col+1);
}
}
class FastReader{
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastReader(InputStream stream){
this.stream = stream;
}
public int read(){
if (numChars == -1){
throw new InputMismatchException ();
}
if (curChar >= numChars){
curChar = 0;
try{
numChars = stream.read (buf);
} catch (IOException e){
throw new InputMismatchException ();
}
if (numChars <= 0){
return -1;
}
}
return buf[curChar++];
}
public int peek(){
if (numChars == -1){
return -1;
}
if (curChar >= numChars){
curChar = 0;
try{
numChars = stream.read (buf);
} catch (IOException e){
return -1;
}
if (numChars <= 0){
return -1;
}
}
return buf[curChar];
}
public int nextInt(){
int c = read ();
while (isSpaceChar (c))
c = read ();
int sgn = 1;
if (c == '-'){
sgn = -1;
c = read ();
}
int res = 0;
do{
if(c==','){
c = read();
}
if (c < '0' || c > '9'){
throw new InputMismatchException ();
}
res *= 10;
res += c - '0';
c = read ();
} while (!isSpaceChar (c));
return res * sgn;
}
public long nextLong(){
int c = read ();
while (isSpaceChar (c))
c = read ();
int sgn = 1;
if (c == '-'){
sgn = -1;
c = read ();
}
long res = 0;
do{
if (c < '0' || c > '9'){
throw new InputMismatchException ();
}
res *= 10;
res += c - '0';
c = read ();
} while (!isSpaceChar (c));
return res * sgn;
}
public String nextString(){
int c = read ();
while (isSpaceChar (c))
c = read ();
StringBuilder res = new StringBuilder ();
do{
res.appendCodePoint (c);
c = read ();
} while (!isSpaceChar (c));
return res.toString ();
}
public boolean isSpaceChar(int c){
if (filter != null){
return filter.isSpaceChar (c);
}
return isWhitespace (c);
}
public static boolean isWhitespace(int c){
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0(){
StringBuilder buf = new StringBuilder ();
int c = read ();
while (c != '\n' && c != -1){
if (c != '\r'){
buf.appendCodePoint (c);
}
c = read ();
}
return buf.toString ();
}
public String nextLine(){
String s = readLine0 ();
while (s.trim ().length () == 0)
s = readLine0 ();
return s;
}
public String nextLine(boolean ignoreEmptyLines){
if (ignoreEmptyLines){
return nextLine ();
}else{
return readLine0 ();
}
}
public BigInteger nextBigInteger(){
try{
return new BigInteger (nextString ());
} catch (NumberFormatException e){
throw new InputMismatchException ();
}
}
public char nextCharacter(){
int c = read ();
while (isSpaceChar (c))
c = read ();
return (char) c;
}
public double nextDouble(){
int c = read ();
while (isSpaceChar (c))
c = read ();
int sgn = 1;
if (c == '-'){
sgn = -1;
c = read ();
}
double res = 0;
while (!isSpaceChar (c) && c != '.'){
if (c == 'e' || c == 'E'){
return res * Math.pow (10, nextInt ());
}
if (c < '0' || c > '9'){
throw new InputMismatchException ();
}
res *= 10;
res += c - '0';
c = read ();
}
if (c == '.'){
c = read ();
double m = 1;
while (!isSpaceChar (c)){
if (c == 'e' || c == 'E'){
return res * Math.pow (10, nextInt ());
}
if (c < '0' || c > '9'){
throw new InputMismatchException ();
}
m /= 10;
res += (c - '0') * m;
c = read ();
}
}
return res * sgn;
}
public boolean isExhausted(){
int value;
while (isSpaceChar (value = peek ()) && value != -1)
read ();
return value == -1;
}
public String next(){
return nextString ();
}
public SpaceCharFilter getFilter(){
return filter;
}
public void setFilter(SpaceCharFilter filter){
this.filter = filter;
}
public interface SpaceCharFilter{
public boolean isSpaceChar(int ch);
}
}

finding a supersequence of DNA Java

I am struggling with a "find supersequence" algorithm.
The input is for set of strings
String A = "caagccacctacatca";
String B = "cgagccatccgtaaagttg";
String C = "agaacctgctaaatgctaga";
the result would be properly aligned set of strings (and next step should be merge)
String E = "ca ag cca cc ta cat c a";
String F = "c gag ccat ccgtaaa g tt g";
String G = " aga acc tgc taaatgc t a ga";
Thank you for any advice (I am sitting on this task for more than a day)
after merge the superstring would be
cagagaccatgccgtaaatgcattacga
The definition of supersequence in "this case" would be something like
The string R is contained in supersequence S if and only if all characters in a string R are present in supersequence S in the order in which they occur in the input sequence R.
The "solution" i tried (and again its the wrong way of doing it) is:
public class Solution4
{
static boolean[][] map = null;
static int size = 0;
public static void main(String[] args)
{
String A = "caagccacctacatca";
String B = "cgagccatccgtaaagttg";
String C = "agaacctgctaaatgctaga";
Stack data = new Stack();
data.push(A);
data.push(B);
data.push(C);
Stack clone1 = data.clone();
Stack clone2 = data.clone();
int length = 26;
size = max_size(data);
System.out.println(size+" "+length);
map = new boolean[26][size];
char[] result = new char[size];
HashSet<String> chunks = new HashSet<String>();
while(!clone1.isEmpty())
{
String a = clone1.pop();
char[] residue = make_residue(a);
System.out.println("---");
System.out.println("OLD : "+a);
System.out.println("RESIDUE : "+String.valueOf(residue));
String[] r = String.valueOf(residue).split(" ");
for(int i=0; i<r.length; i++)
{
if(r[i].equals(" ")) continue;
//chunks.add(spaces.substring(0,i)+r[i]);
chunks.add(r[i]);
}
}
for(String chunk : chunks)
{
System.out.println("CHUNK : "+chunk);
}
}
static char[] make_residue(String candidate)
{
char[] result = new char[size];
for(int i=0; i<candidate.length(); i++)
{
int pos = find_position_for(candidate.charAt(i),i);
for(int j=i; j<pos; j++) result[j]=' ';
if(pos==-1) result[candidate.length()-1] = candidate.charAt(i);
else result[pos] = candidate.charAt(i);
}
return result;
}
static int find_position_for(char character, int offset)
{
character-=((int)'a');
for(int i=offset; i<size; i++)
{
// System.out.println("checking "+String.valueOf((char)(character+((int)'a')))+" at "+i);
if(!map[character][i])
{
map[character][i]=true;
return i;
}
}
return -1;
}
static String move_right(String a, int from)
{
return a.substring(0, from)+" "+a.substring(from);
}
static boolean taken(int character, int position)
{ return map[character][position]; }
static void take(char character, int position)
{
//System.out.println("taking "+String.valueOf(character)+" at "+position+" (char_index-"+(character-((int)'a'))+")");
map[character-((int)'a')][position]=true;
}
static int max_size(Stack stack)
{
int max=0;
while(!stack.isEmpty())
{
String s = stack.pop();
if(s.length()>max) max=s.length();
}
return max;
}
}
Finding any common supersequence is not a difficult task:
In your example possible solution would be something like:
public class SuperSequenceTest {
public static void main(String[] args) {
String A = "caagccacctacatca";
String B = "cgagccatccgtaaagttg";
String C = "agaacctgctaaatgctaga";
int iA = 0;
int iB = 0;
int iC = 0;
char[] a = A.toCharArray();
char[] b = B.toCharArray();
char[] c = C.toCharArray();
StringBuilder sb = new StringBuilder();
while (iA < a.length || iB < b.length || iC < c.length) {
if (iA < a.length && iB < b.length && iC < c.length && (a[iA] == b[iB]) && (a[iA] == c[iC])) {
sb.append(a[iA]);
iA++;
iB++;
iC++;
}
else if (iA < a.length && iB < b.length && a[iA] == b[iB]) {
sb.append(a[iA]);
iA++;
iB++;
}
else if (iA < a.length && iC < c.length && a[iA] == c[iC]) {
sb.append(a[iA]);
iA++;
iC++;
}
else if (iB < b.length && iC < c.length && b[iB] == c[iC]) {
sb.append(b[iB]);
iB++;
iC++;
} else {
if (iC < c.length) {
sb.append(c[iC]);
iC++;
}
else if (iB < b.length) {
sb.append(b[iB]);
iB++;
} else if (iA < a.length) {
sb.append(a[iA]);
iA++;
}
}
}
System.out.println("SUPERSEQUENCE " + sb.toString());
}
}
However the real problem to solve is to find the solution for the known problem of Shortest Common Supersequence http://en.wikipedia.org/wiki/Shortest_common_supersequence,
which is not that easy.
There is a lot of researches which concern the topic.
See for instance:
http://www.csd.uwo.ca/~lila/pdfs/Towards%20a%20DNA%20solution%20to%20the%20Shortest%20Common%20Superstring%20Problem.pdf
http://www.ncbi.nlm.nih.gov/pubmed/14534185
You can try finding the shortest combination like this
static final char[] CHARS = "acgt".toCharArray();
public static void main(String[] ignored) {
String A = "caagccacctacatca";
String B = "cgagccatccgtaaagttg";
String C = "agaacctgctaaatgctaga";
String expected = "cagagaccatgccgtaaatgcattacga";
List<String> ABC = new Combination(A, B, C).findShortest();
System.out.println("expected: " + expected.length());
System.out.println("Merged: " + ABC.get(0).length() + " " + ABC);
}
static class Combination {
int shortest = Integer.MAX_VALUE;
List<String> shortestStr = new ArrayList<>();
char[][] chars;
int[] pos;
int count = 0;
Combination(String... strs) {
chars = new char[strs.length][];
pos = new int[strs.length];
for (int i = 0; i < strs.length; i++) {
chars[i] = strs[i].toCharArray();
}
}
public List<String> findShortest() {
findShortest0(new StringBuilder(), pos);
return shortestStr;
}
private void findShortest0(StringBuilder sb, int[] pos) {
if (allDone(pos)) {
if (sb.length() < shortest) {
shortestStr.clear();
shortest = sb.length();
}
if (sb.length() <= shortest)
shortestStr.add(sb.toString());
count++;
if (++count % 100 == 1)
System.out.println("Searched " + count + " shortest " + shortest);
return;
}
if (sb.length() + maxLeft(pos) > shortest)
return;
int[] pos2 = new int[pos.length];
int i = sb.length();
sb.append(' ');
for (char c : CHARS) {
if (!tryChar(pos, pos2, c)) continue;
sb.setCharAt(i, c);
findShortest0(sb, pos2);
}
sb.setLength(i);
}
private int maxLeft(int[] pos) {
int maxLeft = 0;
for (int i = 0; i < pos.length; i++) {
int left = chars[i].length - pos[i];
if (left > maxLeft)
maxLeft = left;
}
return maxLeft;
}
private boolean allDone(int[] pos) {
for (int i = 0; i < chars.length; i++)
if (pos[i] < chars[i].length)
return false;
return true;
}
private boolean tryChar(int[] pos, int[] pos2, char c) {
boolean matched = false;
for (int i = 0; i < chars.length; i++) {
pos2[i] = pos[i];
if (pos[i] >= chars[i].length) continue;
if (chars[i][pos[i]] == c) {
pos2[i]++;
matched = true;
}
}
return matched;
}
}
prints many solutions which are shorter than the one suggested.
expected: 28
Merged: 27 [acgaagccatccgctaaatgctatcga, acgaagccatccgctaaatgctatgca, acgaagccatccgctaacagtgctaga, acgaagccatccgctaacatgctatga, acgaagccatccgctaacatgcttaga, acgaagccatccgctaacatgtctaga, acgaagccatccgctacaagtgctaga, acgaagccatccgctacaatgctatga, acgaagccatccgctacaatgcttaga, acgaagccatccgctacaatgtctaga, acgaagccatcgcgtaaatgctatcga, acgaagccatcgcgtaaatgctatgca, acgaagccatcgcgtaacagtgctaga, acgaagccatcgcgtaacatgctatga, acgaagccatcgcgtaacatgcttaga, acgaagccatcgcgtaacatgtctaga, acgaagccatcgcgtacaagtgctaga, acgaagccatcgcgtacaatgctatga, acgaagccatcgcgtacaatgcttaga, acgaagccatcgcgtacaatgtctaga, acgaagccatgccgtaaatgctatcga, acgaagccatgccgtaaatgctatgca, acgaagccatgccgtaacagtgctaga, acgaagccatgccgtaacatgctatga, acgaagccatgccgtaacatgcttaga, acgaagccatgccgtaacatgtctaga, acgaagccatgccgtacaagtgctaga, acgaagccatgccgtacaatgctatga, acgaagccatgccgtacaatgcttaga, acgaagccatgccgtacaatgtctaga, cagaagccatccgctaaatgctatcga, cagaagccatccgctaaatgctatgca, cagaagccatccgctaacagtgctaga, cagaagccatccgctaacatgctatga, cagaagccatccgctaacatgcttaga, cagaagccatccgctaacatgtctaga, cagaagccatccgctacaagtgctaga, cagaagccatccgctacaatgctatga, cagaagccatccgctacaatgcttaga, cagaagccatccgctacaatgtctaga, cagaagccatcgcgtaaatgctatcga, cagaagccatcgcgtaaatgctatgca, cagaagccatcgcgtaacagtgctaga, cagaagccatcgcgtaacatgctatga, cagaagccatcgcgtaacatgcttaga, cagaagccatcgcgtaacatgtctaga, cagaagccatcgcgtacaagtgctaga, cagaagccatcgcgtacaatgctatga, cagaagccatcgcgtacaatgcttaga, cagaagccatcgcgtacaatgtctaga, cagaagccatgccgtaaatgctatcga, cagaagccatgccgtaaatgctatgca, cagaagccatgccgtaacagtgctaga, cagaagccatgccgtaacatgctatga, cagaagccatgccgtaacatgcttaga, cagaagccatgccgtaacatgtctaga, cagaagccatgccgtacaagtgctaga, cagaagccatgccgtacaatgctatga, cagaagccatgccgtacaatgcttaga, cagaagccatgccgtacaatgtctaga, cagagaccatccgctaaatgctatcga, cagagaccatccgctaaatgctatgca, cagagaccatccgctaacagtgctaga, cagagaccatccgctaacatgctatga, cagagaccatccgctaacatgcttaga, cagagaccatccgctaacatgtctaga, cagagaccatccgctacaagtgctaga, cagagaccatccgctacaatgctatga, cagagaccatccgctacaatgcttaga, cagagaccatccgctacaatgtctaga, cagagaccatcgcgtaaatgctatcga, cagagaccatcgcgtaaatgctatgca, cagagaccatcgcgtaacagtgctaga, cagagaccatcgcgtaacatgctatga, cagagaccatcgcgtaacatgcttaga, cagagaccatcgcgtaacatgtctaga, cagagaccatcgcgtacaagtgctaga, cagagaccatcgcgtacaatgctatga, cagagaccatcgcgtacaatgcttaga, cagagaccatcgcgtacaatgtctaga, cagagaccatgccgtaaatgctatcga, cagagaccatgccgtaaatgctatgca, cagagaccatgccgtaacagtgctaga, cagagaccatgccgtaacatgctatga, cagagaccatgccgtaacatgcttaga, cagagaccatgccgtaacatgtctaga, cagagaccatgccgtacaagtgctaga, cagagaccatgccgtacaatgctatga, cagagaccatgccgtacaatgcttaga, cagagaccatgccgtacaatgtctaga, cagagccatcctagctaaagtgctaga, cagagccatcctagctaaatgctatga, cagagccatcctagctaaatgcttaga, cagagccatcctagctaaatgtctaga, cagagccatcctgactaaagtgctaga, cagagccatcctgactaaatgctatga, cagagccatcctgactaaatgcttaga, cagagccatcctgactaaatgtctaga, cagagccatcctgctaaatgctatcga, cagagccatcctgctaaatgctatgca, cagagccatcctgctaacagtgctaga, cagagccatcctgctaacatgctatga, cagagccatcctgctaacatgcttaga, cagagccatcctgctaacatgtctaga, cagagccatcctgctacaagtgctaga, cagagccatcctgctacaatgctatga, cagagccatcctgctacaatgcttaga, cagagccatcctgctacaatgtctaga]

Categories

Resources