Java won't stop reading from input - java

Java won't stop reading from input.
I understand that maybe this while loop might have something to do with it:
while(input.hasMoreTokens());
{
array1[counter] = input.nextToken();
counter++;
}
But I don't see why the loop should be a problem because I am already calling .nextToken() which should advance the token.
Here's the full source code:
import java.io.*;
import java.util.*;
class HelloWorld
{
static String ReadLn (int maxLg) // utility function to read from stdin
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main (String args[]) // entry point from OS
{
HelloWorld myWork = new HelloWorld(); // create a dinamic instance
myWork.Begin(); // the true entry point
}
void Begin()
{
String idata;
StringTokenizer input;
while ((idata = HelloWorld.ReadLn (255)) != null)
{
input = new StringTokenizer (idata);
String[] array1 = {};
int counter = 0;
while(input.hasMoreTokens());
{
array1[counter] = input.nextToken();
counter++;
}
int[] array2 = {};
for(int a = 0; a < array1.length; a++)
{
array2[a] = Integer.parseInt(array1[a]);
}
int[] array3 = {};
for(int b = 0; b < array2.length; b++)
{
if ( array2[b] != 42)
{
array3[b] = array2[b];
}
else
{
break;
}
}
String string = "";
for( int c = 0; c < array3.length; c++)
{
if( c < array3.length - 1)
{
string += array3[c] + "\n";
}
else
{
string += array3[c];
}
}
System.out.println(string);
}
}
}

You have a stray semicolon at the end of the while:
while(input.hasMoreTokens());
^ REMOVE THIS

Related

PALIN- The next Palindrome - a SPOJ problem

I have opened an account for Ridit, one of 7-years-old students learning Java at SPOJ. The first task i gave to him was PALIN -The Next Palindrome. Here is the link to this problem- PALIN- The next Palindrome- SPOJAfter i explained it to him, he was able to solve it mostly except removing the leading zeros, which i did. Following is his solution of the problem -
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Scanner in = new Scanner(System.in);
int t = Integer.parseInt(in.nextLine());
String[] numbersInString = new String[t];
for (int i = 0; i <t; i++) {
String str = in.nextLine();
numbersInString[i] = removeLeadingZeros(str);
}
for (int i = 0 ; i<t; i++) {
int K = Integer.parseInt(numbersInString[i]);
int answer = findTheNextPalindrome(K);
System.out.println(answer);
}
}catch(Exception e) {
return;
}
}
static boolean isPalindrome(int x) {
String str = Integer.toString(x);
int length = str.length();
StringBuffer strBuff = new StringBuffer();
for(int i = length - 1;i>=0;i--) {
char ch = str.charAt(i);
strBuff.append(ch);
}
String str1 = strBuff.toString();
if(str.equals(str1)) {
return true;
}
return false;
}
static int findTheNextPalindrome(int K) {
for(int i = K+1;i<9999999; i++) {
if(isPalindrome(i) == true) {
return i;
}
}
return -1;
}
static String removeLeadingZeros(String str) {
String retString = str;
if(str.charAt(0) != '0') {
return retString;
}
return removeLeadingZeros(str.substring(1));
}
}
It is giving correct answer in Eclipse on his computer, but it is failing in SPOJ. If someone helps this little boy in his first submission, it will definitely make him very happy. I couldn't find any problem with this solution... Thank you in advance...
This might be helpful
import java.io.IOException;
import java.util.Scanner;
public class ThenNextPallindrom2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int t = 0;
Scanner sc = new Scanner(System.in);
if(sc.hasNextInt()) {
t = sc.nextInt();
}
sc.nextLine();
int[] arr, arr2;
while(t > 0) {
t--;
String s = sc.nextLine();
arr = getStringToNumArray(s);
if(all9(arr)) {
arr2 = new int[arr.length + 1];
arr2[0] = 1;
for(int i=0;i<arr.length;i++) {
arr2[i+1] = 0;
}
arr2[arr2.length -1] = 1;
arr = arr2;
} else{
int mid = arr.length/ 2;
int left = mid-1;
int right = arr.length % 2 == 1 ? mid + 1 : mid;
boolean left_small = false;
while(left >= 0 && arr[left] == arr[right]) {
left--;
right++;
}
if(left < 0 || arr[left] < arr[right]) left_small = true;
if(!left_small) {
while(left >= 0) {
arr[right++] = arr[left--];
}
} else {
mid = arr.length/ 2;
left = mid-1;
int carry = 1;
if(arr.length % 2 == 0) {
right = mid;
} else {
arr[mid] += carry;
carry = arr[mid]/10;
arr[mid] %= 10;
right = mid + 1;
}
while(left >= 0) {
arr[left] += carry;
carry = arr[left] / 10;
arr[left] %= 10;
arr[right++] = arr[left--];
}
}
}
printArray(arr);
}
}
public static boolean all9(int[] arr) {
for(int i=0;i<arr.length;i++) {
if(arr[i] != 9)return false;
}
return true;
}
public static void printArray(int[] arr) {
for(int i=0;i<arr.length;i++) {
System.out.print(arr[i]);
}
System.out.println();
}
public static int[] getStringToNumArray(String s) {
int[] arr = new int[s.length()];
for(int i=0; i<s.length();i++) {
arr[i] = Integer.parseInt(String.valueOf(s.charAt(i)));
}
return arr;
}
}

Error in String/character uppercase/lowercase conversion with loop

I have been doing an assignment, and I'm stuck. If I enter the letters: ahb, it prints only the last letter b not the whole thing:
public void run()
{
String value;
while (true) {
try {
value = (String) conB.remove();
if(value != null) { {
for(int i=0; i < value.length(); i++) {
if(Character.isDigit(value.charAt(i))) {
int x = Integer.parseInt(value);
bConWin.setData(" "+(x*2));
}
if(Character.isLowerCase(value.charAt(i))) {
char x = value.toUpperCase().charAt(i);
//changed.append(Character.toUpperCase(x));
bConWin.setData(" " +x);
}
if(Character.isUpperCase(value.charAt(i))) {
char x = value.toLowerCase().charAt(i);
bConWin.setData(" "+x);
}
}
}
}
}
}
You are only ever assigning one character as bConWin's data. Here's a fix as well as some tidying:
public static void main(String args[]) {
String value = "HaaaOppSaN";
if(value != null) {
StringBuilder newValue = new StringBuilder();
for(int i = 0; i < value.length(); i++) {
char x = value.charAt(i);
if(Character.isLowerCase(x)) {
x = Character.toUpperCase(x);
} else {
x = Character.toLowerCase(x);
}
newValue.append("" + x);
}
bConWin.setData(newValue.toString());
}
}
The outer endless loop is not needed. The try without a catch block as well.
Take a look at this:
public static void main(String[] args) {
String switched = switchCharacterCase("Hello World!");
bConWin.setData(switched);
System.out.println(switched);
}
public static String switchCharacterCase(final String input) {
StringBuilder switched = new StringBuilder();
if(input != null) { // nothing to do here, return switched
for(int i = 0; i < input.length(); i++) {
Character c = input.charAt(i);
if(Character.isLowerCase(c)) {
c = Character.toUpperCase(c);
} else {
c = Character.toLowerCase(c);
}
switched.append(c);
}
}
return switched.toString();
}

Knuth-Morris-Pratt algorithm confusion

I'm trying to implement KMP algorithm. My algorithm works correctly with the following example
Text: 121121
Pattern: 121
Result: 1,4
But when Text is 12121 and pattern is the same as above, result just: 1. I don't know if this is the problem of the algorithm or of my implementation?
Other example:
Text: 1111111111
Pattern: 111
Result: 1,4,7
My code is:
public class KMP {
public static void main(String[] args) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String text = reader.readLine();
String pattern = reader.readLine();
search(text,pattern);
}
private static void search(String text,String pattern)
{
int[] Pi = Pi(pattern);
for (int i = 0,q=0; i <text.length()&&q<pattern.length() ; i++,q++) {
while (q>=0 && pattern.charAt(q)!=text.charAt(i))
{
q=Pi[q];
}
if(q==pattern.length()-1) {
System.out.println(i-pattern.length()+2);
q=Pi[q];
}
}
}
private static int[] Pi(String p) {
int[] Pi = new int[p.length()];
Pi[0]=-1;
int i=0;
int j=-1;
while (i<p.length()-1) {
while (j>=0 && p.charAt(j)!=p.charAt(i))
{
j=Pi[j];
}
i++;
j++;
if(p.charAt(j)==p.charAt(i)) Pi[i]=Pi[j];
else Pi[i]=j;
}
return Pi;
}
}
Hope help you.
public int strStr(String source, String target) {
if (source == null || target == null){
return -1;
}
if (source.isEmpty() && !target.isEmpty()){
return -1;
}
if (source.isEmpty() && target.isEmpty()){
return 0;
}
if (target.isEmpty()){
return 0;
}
int index = 0;
int compare_index = 0;
int compare_start_index = 0;
int compare_same_length = 0;
List<Integer> answers = new ArrayList<Integer>();
while (true){
if (compare_same_length ==0){
compare_start_index = compare_index;
}
if (source.charAt(compare_index) == target.charAt(index)){
compare_same_length++;
index++;
} else {
if (compare_same_length >0){
compare_index--;
}
compare_same_length = 0;
index = 0;
}
compare_index++;
if (compare_same_length == target.length()){
answers.add(compare_start_index+1);
compare_same_length=0;
index=0;
}
if (compare_index == source.length()){
//here are answers
for (int i = 0; i < answers.size(); i++) {
int value = answers.get(i);
}
return 1;
}
}
}

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