I have a String Unitedin.
Here the char "n" is occurred at index 1 and index 6 ; The Difference between index number is 5
Similarly for "i" which occurs at index 2 and index 5. The Difference is 3.
I need to Print the chars according to ascending order of there Difference at the OutPut.
Challenge is I cannot use any type of array list or List or hashMap or set or linked hash etc
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuilder temp = new StringBuilder();
StringBuilder output = new StringBuilder();
System.out.println("Enter a string : ");
String instring = in.next();
for (int i = 0; i < instring.length(); i++) {
for (int j = i + 1; j < instring.length(); j++) {
if (instring.charAt(i) == instring.charAt(j)) {
temp.append(instring.charAt(i));
}
}
}
for (int m = 0; m < temp.length(); m++) {
for (int p = m + 1; p < temp.length(); p++) {
if (m == temp.length() - 1) {
output.append(temp.charAt(m));
} else if (instring.lastIndexOf(temp.charAt(m), 0) >= instring.lastIndexOf(temp.charAt(p), 0)) {
output.append(temp.charAt(p));
} else {
output.append(temp.charAt(m));
}
}
}
System.out.println(output);
}
I am Getting output as i. Can anyone help me? Expected output = in
Smth. like that. This is not the best performance, but it does not use Collections:
public static String foo(String str) {
str = str.toLowerCase();
int[] letters = new int[26];
Arrays.fill(letters, Integer.MIN_VALUE);
for (int i = 0; i < str.length(); i++)
if (letters[str.charAt(i) - 'a'] == Integer.MIN_VALUE)
letters[str.charAt(i) - 'a'] = -i;
for (int i = str.length() - 1; i >= 0; i--)
if (letters[str.charAt(i) - 'a'] != Integer.MIN_VALUE)
letters[str.charAt(i) - 'a'] += i;
return IntStream.range(0, letters.length)
.filter(i -> letters[i] > 0)
.boxed()
.sorted(Comparator.comparingInt(i -> letters[i]))
.map(i -> String.valueOf((char)('a' + i)))
.collect(Collectors.joining());
}
In case you do not want to use Streams, then the second part it:
int cur = 1;
boolean checkNext;
StringBuilder buf = new StringBuilder();
do {
checkNext = false;
for (int i = 0; i < letters.length; i++) {
if (letters[i] < cur)
continue;
checkNext = true;
if (letters[i] == cur)
buf.append((char)('a' + i));
}
cur++;
} while (checkNext);
return buf.toString();
import java.util.TreeMap;
import java.util.Scanner;
public class SameCharOccurenceDiff {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int firstIndex = 0;
int lastIndex = 0;
TreeMap<Integer,Character> outputMap = new TreeMap<Integer,Character>();
String stringInput = sc.next();
StringBuilder strBuilder = new StringBuilder();
sc.close();
for (int i = 0; i < stringInput.length(); i++) {
char chr = stringInput.charAt(i);
firstIndex = stringInput.indexOf(chr);
lastIndex = stringInput.lastIndexOf(chr);
int diff = lastIndex-firstIndex;
if( diff > 0) {
outputMap.put(diff,chr);
}
}
for (char c : outputMap.values()) {
strBuilder.append(c);
}
System.out.println(strBuilder);
}
}
Edit : ( Without using TreeMap )
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class SameCharOccurenceDiff {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int firstIndex = 0;
int lastIndex = 0;
int count = 0;
String stringInput = sc.next().toLowerCase();
String[] stringInputArr = new String[stringInput.length()];
StringBuilder strBuilder = new StringBuilder();
sc.close();
for (int i = 0; i < stringInput.length(); i++) {
char chr = stringInput.charAt(i);
firstIndex = stringInput.indexOf(chr);
lastIndex = stringInput.lastIndexOf(chr);
int diff = lastIndex - firstIndex;
if( diff > 0 && !inArray(stringInputArr,diff+""+chr)) {
stringInputArr[count] = diff+""+chr;
count++;
}
}
//System.out.println(Arrays.toString(stringInputArr));
Arrays.sort(stringInputArr,0,count,new Comparator<String>() {
public int compare(String s1, String s2) {
int num1 = Integer.parseInt(s1.replaceAll("[^\\d]", ""));
int num2 = Integer.parseInt(s2.replaceAll("[^\\d]", ""));
return num1 - num2;
}
});
//System.out.println(Arrays.toString(stringInputArr));
for (String str : stringInputArr) {
if(str == null)break;
strBuilder.append(str.replaceAll("\\d", ""));
}
System.out.println(strBuilder);
}
public static boolean inArray(String[] arr,String chr) {
boolean isPresent = false;
for (int i = 0; i < arr.length; i++) {
if(arr[i] == null)break;
if(arr[i].equalsIgnoreCase(chr)) {
isPresent = true;
break;
}
}
return isPresent;
}
}
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;
}
}
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;
}
}
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);
}
}
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]