I am required to write a program that takes in an input file (which represents a graph) and outputs the chromatic number along with the vertices colors. I wrote a program that does this successfully, however I am given a large input file and the program runs indefinitely. I need to make the program narrow down the chromatic number to a range of ten values. Can anyone give me some advice as to how I can accomplish this. I will post my code below for reference.
Any help would be appreciated. Thanks!
import java.util.*;
import java.io.*;
public class chromatic_num {
public static int n;
public static int q[];
public static int matrix[][];
public static List<Integer> list;
public static void main(String[] args) throws IOException {
//reads input from file
BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream("file1.txt")));
} catch (FileNotFoundException e) {
throw new RuntimeException();
}
String line;
boolean readFirstLine = false;
// new array list to store input
list = new ArrayList<Integer>();
// read file line by line
while ((line = br.readLine()) != null) {
// prints content
String[] toks = line.split(" ");
if (readFirstLine) {
list.add(Integer.parseInt(toks[0]));
list.add(Integer.parseInt(toks[1]));
}
else {
readFirstLine = true;
n = Integer.parseInt(toks[0]);
}
}
// finds max edges
n = Collections.max(list);
// for adjacency matrix
matrix = new int[n][n];
// constructs adj. matrix
int count = 0;
Integer v1 = 0, v2 = 0;
for (Integer v : list) {
if (count % 2 == 0) {
v1 = v - 1;
}
else {
v2 = v - 1;
matrix[v1][v2] = 1;
matrix[v2][v1] = 1;
}
count++;
}
// new array to store colors
q = new int[n];
chromatic_num chromatic = new chromatic_num();
//print solution to screen
System.out.println(chromatic.color());
for (int i = 0; i < n; i++) {
System.out.println("" + (i + 1) + " " + q[i]);
}
//print solution to file
try {
System.setOut(new PrintStream(new FileOutputStream("chromatic_num.txt")));
} catch (FileNotFoundException e) {
throw new RuntimeException();
}
System.out.println(chromatic.color());
for (int i = 0; i < n; i++) {
System.out.println("" + (i + 1) + " " + q[i]);
}
br.close();
}
//color G using minimum number of colors, returns chromatic number
public int color()
{
//for (int t = 0
for (int i = 1; i <= n; i++)
{
//if G can be colored using i colors starting at vertex 0
//System.out.println("colored using " + i + " colors starting at vertex 1");
if (color(0,i)) {
//chromatic number is i, return it
return i;
}
else {
for (int j = 0; j < n; j++) {
q[j] = 0;
}
}
}
return 0;
}
//colors G using m colors starting at vertex v
public boolean color(int v, int m)
{
if (v > n - 1) {
//all vertices have been colored, success
return true;
}
else
{
for (int i = 1; i <= m; i++)
{
//assign color i to vertex v
q[v] = i;
//System.out.println("color " + i + " to vertex " + (v + 1));
//check whether colors of v and its neighbors conflict
boolean hasConflicted = hasConflicted(v);
//System.out.println("hasConflicted = " + hasConflicted);
if (hasConflicted == false)
{
//color the rest of G using m colors starting at vertex v+1, done by recursive call color(v+1, m)
boolean success = color(v + 1, m);
//if (the rest of G can be colored)
// all vertices have been colored, success
if (success) {
return true;
}
}
}
//assign color 0 to vertex v and fail, this happens when none of the m colors can be assigned to vertex v
q[v] = 0;
return false;
}
}
public boolean hasConflicted(int v) {
for (int i = 0; i < n; i++)
{
if (i != v && matrix[i][v] == 1 && q[i] == q[v]) {
return true;
}
}
return false;
}
}
I am making SOS game with "stack".No other data structures such as normal array, string etc.
Gameboard size 3*6 and I am using random for determining letters.
But I don't know is the game over or not.
How can I control is there any horizontal or vertical sos at the console
Here is my code(I am beginner)
public static void main(String[] args) {
Random rnd = new Random();
Stack S1 = new Stack(6);
Stack S2 = new Stack(6);
Stack S3 = new Stack(6);
Stack ts1 = new Stack(6);
Stack ts2 = new Stack(6);
Stack ts3 = new Stack(6);
int Round = 0;
int satir;
boolean winner = false;
// for S1
int i = 0;
while (i != 6) { // 6time
i++;
// System.out.println(i);
if (rnd.nextBoolean()) {
S1.push("S");
} else {
S1.push("O");
}
}
// for S2
i = 0;
while (i != 6) {
i++;
if (rnd.nextBoolean()) {
S2.push("S");
} else {
S2.push("O");
}
}
// for S3
i = 0;
while (i != 6) {
i++;
if (rnd.nextBoolean()) {
S3.push("S");
} else {
S3.push("O");
}
}
int a = 0, b = 0, c = 0;
int tempa = a;
int tempb = b;
int tempc = c;
while (!winner) {
System.out.println("User" + ((Round % 2) + 1) + ":"); // User1:
// User2:
satir = rnd.nextInt(3) + 1;
if (satir == 1 && a != 6) {
a++;
}
if (satir == 2 && b != 6) {
b++;
}
if (satir == 3 && c != 6) {
c++;
}
tempa = a;
tempb = b;
tempc = c;
System.out.print("S1 ");
while (a > 0) { // S1 in icini yazdir bosalt ts1e kaydet
System.out.print(S1.peek() + " ");
ts1.push(S1.pop());
a--;
}
a = tempa;
while (!ts1.isEmpty()) { // S1i tekrar doldur
S1.push(ts1.pop());
}
System.out.println();
System.out.print("S2 ");
while (b > 0) { // S2 in icini yazdir bosalt ts1e kaydet
System.out.print(S2.peek() + " ");
ts2.push(S2.pop());
b--;
}
b = tempb;
while (!ts2.isEmpty()) { // S2i tekrar doldur
S2.push(ts2.pop());
}
System.out.println();
System.out.print("S3 ");
while (c > 0) { // S3 in icini yazdir bosalt ts1e kaydet
System.out.print(S3.peek() + " ");
ts3.push(S3.pop());
c--;
}
c = tempc;
while (!ts3.isEmpty()) { // S3i tekrar doldur
S3.push(ts3.pop());
}
System.out.println();
// check if there is sos winner=true;
if (a > 2) { //check S1 Horizontal
for (int yatay1 = 0; yatay1 < a; yatay1++) {
if (S1.peek().equals("S")) {
ts1.push(S1.pop());
if (S1.peek().equals("O")) {
ts1.push(S1.pop());
if (S1.peek().equals("S")) {
System.out.println("SOS-wow");
winner = true;
} else {
while (!ts1.isEmpty()) {
S1.push(ts1.pop());
}
}
} else {
S1.push(ts1.pop());
}
}
}
}
Round++;
} // end of loop
}
I need help with this program because it is not compiling correctly.
The program is supposed to do this:
java PostfixToInfix
1 2 3 + *
1*(2+3)
I am getting these errors when compiling:
PostfixToInfix.java:64: error: bad operand types for binary operator '-'
s.push(o2 - o1);
^
first type: String
second type: String
PostfixToInfix.java:68: error: bad operand types for binary operator '*'
s.push(o1 * o2);
^
first type: String
second type: String
2 errors
How many I supposed to code this so that it works properly? I am unsure what is wrong with my code that it is not allowing it do the functions properly.
This is my code:
import java.util.Scanner;
import java.util.Stack;
public class PostfixToInfix
{
public static void main(String[] args)
{
String[] input = readExpr();
if(checkSyntax(input) == true)
{
int k = 0;
Stack<String> s = new Stack<>();
for(int i = 0; i < input.length; ++i)
{
if(isOperator(input[i]))
{
String o1;
String o2;
if(!(s.empty()))
{
o1 = s.pop();
}
else
{
for(int j = 0; j < i; ++j)
{
k += input[j].length() + 1;
}
System.out.println("Too few operands for " + input[i]);
writeExpr(input);
for(int l = 0; l < k; ++l)
{
System.out.print(" ");
}
System.out.println("^");
return;
}
if(!(s.empty()))
{
o2 = s.pop();
}
else
{
for(int j = 0; j < i; ++j)
{
k += input[j].length() + 1;
}
System.out.println("Too few operands for " + input[i]);
writeExpr(input);
for(int l = 0; l < k; ++l)
{
System.out.print(" ");
}
System.out.println("^");
return;
}
if(input[i].equals("+"))
{
s.push(o1 + o2);
}
else if(input[i].equals("-"))
{
s.push(o2 - o1);
}
else
{
s.push(o1 * o2);
}
}
else
{
s.push(input[i]);
}
}
String Result = s.pop();
if(!(s.empty()))
{
System.out.println("Too few operators to produce a single result");
}
else
{
System.out.println(Result);
}
}
} // end main
static String[] readExpr()
{
Scanner stdin = new Scanner(System.in);
String s = stdin.nextLine();
String[] sA = s.split(" ");
return sA;
}
static void writeExpr(String[] expr)
{
for(int i = 0; i < expr.length; ++i)
{
System.out.print(expr[i] + " ");
}
System.out.println();
}
static boolean isOperator(String s)
{
if(s.equals("+") || s.equals("-") || s.equals("*"))
{
return true;
}
return false;
}
static boolean checkSyntax(String[] expr)
{
int k = 0;
for(int i = 0; i < expr.length; ++i)
{
if(!(isOperator(expr[i])))
{
try
{
Double.parseDouble(expr[i]);
}
catch (Exception e)
{
for(int j = 0; j < i; ++j)
{
k += expr[j].length() + 1;
}
writeExpr(expr);
for(int l = 0; l < k; ++l)
{
System.out.print(" ");
}
System.out.println("^");
System.out.println("Not a number or valid operator");
return false;
}
}
}
return true;
}
} // end Postfix2
class StringStack
{
int top;
String[] pancake;
StringStack() //constructor for a new empty stack
{
top = 0;
pancake = new String[1000];
} // end DoubleStack
boolean empty() //whether the stack is empty
{
return top == 0;
} // end empty
String pop() //remove and return the top element; throw an error if empty
{
if(empty())
{
throw new Error("Error");
}
top -= 1;
return pancake[top];
} // end pop
void push(String x) //add x to the top of the stack
{
if(top < 1000)
{
pancake[top] = x;
top += 1;
}
else{
throw new Error("Error");
}
} // end push
} // end StringStack
Change you code like this.
if(input[i].equals("+"))
{
s.push(o1 + "+" + o2);
}
else if(input[i].equals("-"))
{
s.push(o2 + "-" + o1);
}
else
{
s.push(o1 + "*" + o2);
}
But the result for "1 2 3 + *" is "3+2*1".
It is another problem.
I'm creating a TCP game of Battleship in Java, and as I've made some functions work, methods that used to work no longer work.
Here's what's happening when it's a users turn. A bomb being dropped on 2 diffrent char[][], where clientGrid is the actual grid where the client has his ships. It's on this grid where the dropBomb method is being printed, and tells us whether a bomb has hit or not. clientDamage is just an overview for the server to see where he has previously dropped bombs.
if (inFromServer.ready()) {
System.out.println("\nInput coordinate");
int x = scan.nextInt();
int y = scan.nextInt();
System.out.println(dropBomb(x, y, clientGrid));
dropBomb(x, y, clientDamage);
outToClient.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
System.out.println(printBoard(clientDamage));
}
Here's the drop bomb method. It's proved to work before, however I have made some small changes to it. However I can't see why it wouldn't work. + indicates that there is a ship, x indicates that the target already has been bombed, and the else is ~, which is water. The method always returns "Nothing was hit on this coordinate...", and I can't seem to figure out why?
public static String dropBomb(int row, int col, char[][] board) {
if (row < gridSize && col < gridSize) {
if (board[row][col] == '+') {
board[row][col] = 'x';
return "Ship has been hit!";
} else if (board[row][col] == 'x') {
return "Already bombed.";
} else {
board[row][col] = 'x';
return "Nothing was hit on this coordinate...";
}
} else {
return "No such coordinate.";
}
}
Here is the full code... can someone please point out what I'm missing?
//server = player 1
//client = player 2
public class BattleshipGame {
public static ArrayList<Ship> fleet;
public static InetAddress clientAddress;
public static BattleshipGame battleship;
private final static int gridSize = 11;
public final static int numberOfShips = 3;
public static char[][] serverGrid;
public static char[][] clientGrid;
public static char[][] serverDamage;
public static char[][] clientDamage;
private int whosTurn;
private int whoStarts;
public static int count;
public static int bombCount;
public BattleshipGame() {
whoStarts = 0;
start();
showShipList();
}
public static String printBoard(char[][] board) {
String out = "";
for (int i = 1; i < board.length; i++) {
for (int j = 1; j < board.length; j++) {
out += board[j][i];
}
out += '\n';
}
return out;
}
public void start() {
Random rand = new Random();
if (rand.nextBoolean()) {
whoStarts = 1;
whosTurn = 1;
} else {
whoStarts = 2;
whosTurn = 2;
}
whoStarts = 1;
whosTurn = 1;
System.out.println("Player " + whoStarts + " starts\n");
}
public void initializeGrid(int playerNo) {
serverGrid = new char[gridSize][gridSize];
for (int i = 0; i < serverGrid.length; i++) {
for (int j = 0; j < serverGrid.length; j++) {
serverGrid[i][j] = '~';
}
}
serverDamage = new char[gridSize][gridSize];
for (int i = 0; i < serverDamage.length; i++) {
for (int j = 0; j < serverDamage.length; j++) {
serverDamage[i][j] = '~';
}
}
clientGrid = new char[gridSize][gridSize];
for (int i = 0; i < clientGrid.length; i++) {
for (int j = 0; j < clientGrid.length; j++) {
clientGrid[i][j] = '~';
}
}
clientDamage = new char[gridSize][gridSize];
for (int i = 0; i < clientDamage.length; i++) {
for (int j = 0; j < clientDamage.length; j++) {
clientDamage[i][j] = '~';
}
}
if (playerNo == 1) {
System.out.println("\nYour grid (player 1):\n"
+ printBoard(serverGrid));
} else if (playerNo == 2) {
System.out.println("\nYour grid (player 2):\n"
+ printBoard(clientGrid));
} else {
System.out.println("No such player.");
}
}
public static void deployShip(char[][] board, Ship ship, char direction,
int x, int y) {
if (direction == 'H') {
if (x < gridSize && y < gridSize) {
for (int i = 0; i < ship.getSize(); i++) {
board[x + i][y] = '+';
}
System.out
.println("Ship has been placed horizontally on coordinates "
+ x + ", " + y + ".");
} else {
System.out.println("Unable to place ship in this coordinate.");
}
} else if (direction == 'V') {
if (x < gridSize && y < gridSize) {
for (int i = 0; i < ship.getSize(); i++) {
board[x][y + i] = '+';
}
System.out
.println("Ship has been placed vertically on coordinates "
+ x + ", " + y + ".");
} else {
System.out.println("Unable to place ship in this coordinate.");
}
}
}
public static String dropBomb(int row, int col, char[][] board) {
if (row < gridSize && col < gridSize) {
if (board[row][col] == '+') {
System.out.println(board[row][col]);
board[row][col] = 'x';
bombCount++;
return "Ship has been hit!";
}
if (board[row][col] == 'x') {
System.out.println(board[row][col]);
bombCount++;
return "Already bombed.";
}
if (board[row][col] == '~') {
System.out.println(board[row][col]);
board[row][col] = 'x';
bombCount++;
return "Nothing was hit on this coordinate...";
}
} else {
return "No such coordinate.";
}
return "";
}
public void showShipList() {
System.out
.println("Choose ships to add to your fleet from the following list ("
+ numberOfShips + " ships allowed):");
ArrayList<Ship> overview = new ArrayList<Ship>();
Ship ac = new Ship("Aircraft carrier", 5, false);
Ship bs = new Ship("Battleship", 4, false);
Ship sm = new Ship("Submarine", 3, false);
Ship ds = new Ship("Destroyer", 3, false);
Ship sp = new Ship("Patrol Boat", 2, false);
overview.add(ac);
overview.add(bs);
overview.add(sm);
overview.add(ds);
overview.add(sp);
for (int i = 0; i < overview.size(); i++) {
System.out.println(i + 1 + ". " + overview.get(i));
}
}
public static ArrayList<Ship> createFleet(ArrayList<Ship> fleet, int choice) {
if (count < numberOfShips && choice > 0 && choice < 6) {
if (choice == 1) {
Ship ac = new Ship("Aircraft carrier", 5, false);
fleet.add(ac);
count++;
System.out.println("Aircraft carrier has been added to fleet.");
} else if (choice == 2) {
Ship bs = new Ship("Battleship", 4, false);
fleet.add(bs);
count++;
System.out.println("Battleship has been added to fleet.");
} else if (choice == 3) {
Ship sm = new Ship("Submarine", 3, false);
fleet.add(sm);
count++;
System.out.println("Submarine has been added to fleet.");
} else if (choice == 4) {
Ship ds = new Ship("Destroyer", 3, false);
fleet.add(ds);
count++;
System.out.println("Destroyer has been added to fleet.");
} else if (choice == 5) {
Ship sp = new Ship("Patrol Boat", 2, false);
fleet.add(sp);
count++;
System.out.println("Patrol boat has been added to fleet.");
}
} else {
System.out.println("Not an option.");
}
System.out.println("\nYour fleet now contains:");
for (Ship s : fleet) {
System.out.println(s);
}
return fleet;
}
}
public class TCPServer extends BattleshipGame {
private static final int playerNo = 1;
public static void main(String[] args) {
System.out.println("You are player: " + playerNo);
battleship = new BattleshipGame();
try {
InetAddress.getLocalHost().getHostAddress();
ServerSocket serverSocket = new ServerSocket(6780);
Socket socket = serverSocket.accept();
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(System.in));
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream());
Scanner scan = new Scanner(System.in);
while (true) {
if (inFromServer.ready()) {
setup(scan, playerNo);
System.out.println("\nInput coordinate");
int x = scan.nextInt();
int y = scan.nextInt();
System.out.println(dropBomb(x, y, clientGrid));
System.out.println(printBoard(clientGrid));
dropBomb(x, y, clientDamage);
outToClient.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
printBoard(clientDamage);
}
if (inFromClient.ready()) {
System.out.println(inFromClient.readLine());
System.out.println(printBoard(serverGrid));
}
}
// socket.close();
// serverSocet.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void setup(Scanner inFromUser, int playerNo) {
fleet = new ArrayList<Ship>();
while (count < numberOfShips) {
createFleet(fleet, inFromUser.nextInt());
}
battleship.initializeGrid(playerNo);
for (int i = 0; i < fleet.size(); i++) {
System.out.println(fleet.get(i));
System.out.println("Define direction (V/H) plus coordinates");
deployShip(serverGrid, fleet.get(i), inFromUser.next().charAt(0), inFromUser.nextInt(), inFromUser.nextInt());
}
System.out.println("Placements:\n" + printBoard(serverGrid));
System.out.println("Fleet has been deployed. Press enter to continue.\n");
}
}
public class TCPClient extends BattleshipGame {
private static final int playerNo = 2;
public static void main(String[] args) {
System.out.println("You are player: " + playerNo);
battleship = new BattleshipGame();
try {
InetAddress.getLocalHost().getHostAddress();
Socket socket = new Socket(InetAddress.getLocalHost()
.getHostAddress(), 6780);
DataOutputStream dataOutputStream = new DataOutputStream(
socket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(System.in));
Scanner scan = new Scanner(System.in);
setup(scan, playerNo);
while (true) {
if (inFromClient.ready()) {
System.out.println("\nInput coordinate");
int x = scan.nextInt();
int y = scan.nextInt();
System.out.println(dropBomb(x, y, serverGrid));
dropBomb(x, y, serverDamage);
dataOutputStream.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
System.out.println(printBoard(serverDamage));
}
if (inFromServer.ready()) { // modtag data fra server
System.out.println(inFromServer.readLine());
System.out.println(printBoard(clientGrid));
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void setup(Scanner inFromUser, int playerNo) {
fleet = new ArrayList<Ship>();
while (count < numberOfShips) {
createFleet(fleet, inFromUser.nextInt());
}
battleship.initializeGrid(playerNo);
for (int i = 0; i < fleet.size(); i++) {
System.out.println(fleet.get(i));
System.out.println("Define direction (V/H) plus coordinates");
deployShip(clientGrid, fleet.get(i), inFromUser.next().charAt(0), inFromUser.nextInt(), inFromUser.nextInt());
}
System.out.println("Placements:\n" + printBoard(clientGrid));
System.out.println("Fleet has been deployed. Press enter to continue.\n");
}
}
package Battleships;
public class Ship {
private String name;
private int size;
private boolean isDestroyed;
public Ship(String n, int s, boolean d) {
this.name = n;
this.size = s;
this.isDestroyed = d;
}
public String getName() {
String output = "";
output = "[" + name + "]";
return output;
}
public int getSize() {
return size;
}
public String toString() {
String output = "";
output = "[" + name + ", " + size + ", " + isDestroyed + "]";
return output;
}
}
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]