finding a supersequence of DNA Java - 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]
Related
Difference between first index and last index of the char in the given string
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; } }
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; } }
To shrink a string "abbcccbfgh" by removing conescutive k characters till no removal can be done
To shrink a string "abbcccbfgh" by removing consecutive k characters till no removal can be done. e.g. for k=3 output for the above string will be "afgh". Please note that K and string both are dynamic i.e provided by the user. I wrote the below program but I couldn't complete it. Please help. public class Test { public static void main(String[] args) { String str = "abbcccbfgh"; int k = 3; String result = removeConsecutive(str, k); System.out.print("result is " + result); } private static String removeConsecutive(String str, int k) { String str1 = str + ""; String res = ""; int len = str.length(); char c1 = 0, c2 = 0; int count = 0; for (int i = 0; i < len - 1; i++) { c1 = str.charAt(i); c2 = str.charAt(i + 1); if (c1 == c2) { count++; } else { res = res + String.valueOf(c1); count = 0; } if (count == k-1) { //remove String } } return res; }
I suggest to do it with regex: int l = 0; do { l = str.length(); str = str.replaceAll("(.)\\1{" + n + "}", ""); } while (l != str.length()); n = k - 1 (.)\1{2} means any character followed by n same characters. \1 means the same character as in group #1
Is it okey to have recursion ? public class Test { public static void main(String[] args) { String str = "abbcccbfgh"; int k = 3; String result = removeConsecutive(str, k); System.out.print("result is " + result); } private static String removeConsecutive(String str, int k) { String ret = str; int len = str.length(); int count = 0; char c1 = 0 ; char c2 = 0; char last = 0 ; for (int i = 0; i < ret.length()-1; i++) { last = c1 ; c1 = str.charAt(i); c2 = str.charAt(i + 1); if (c1 == c2 ) { if( count > 0 ) { if( last == c1 ) { count ++ ; } else { count = 0; } } else { count++; } } else { count = 0; } if (count == k-1) { int start = ((i+1) - k) + 1 ; String one = str.substring(0, start) ; String two = str.substring(start+k); String new1 = one + two ; //recursion ret = removeConsecutive(new1, k) ; count = 0; } } return ret; } }
You can do it with a stack. For each character ch in the string, push it to the stack, if there's 3 consecutive same characters, pop them all. In the end, convert the stack to a string. You can improve the program a little by using a special stack that remembers the number of occurrences of each element. import java.util.ArrayList; import java.util.List; import java.util.function.Function; public class Reduce implements Function<String, String> { private final int k; public Reduce(final int k) { if (k <= 0) { throw new IllegalArgumentException(); } this.k = k; } #Override public String apply(final String s) { Stack<Character> stack = new Stack<>(); for (Character ch : s.toCharArray()) { stack.push(ch); if (stack.topCount() == k) { stack.pop(); } } return stack.toString(); } public static void main(String[] args) { Reduce reduce = new Reduce(3); System.out.println(reduce.apply("abbcccbfgh")); } private static class Stack<T> { private class Node { private T value; private int count; Node(T value) { this.value = value; this.count = 1; } } private List<Node> nodes = new ArrayList<>(); public void push(T value) { if (nodes.isEmpty() || !top().value.equals(value)) { nodes.add(new Node(value)); } else { top().count++; } } public int topCount() { return top().count; } public void pop() { nodes.remove(nodes.size()-1); } private Node top() { return nodes.get(nodes.size()-1); } #Override public String toString() { StringBuilder sb = new StringBuilder(); nodes.forEach(n->{ for (int i = 0; i < n.count; i++) { sb.append(n.value); } }); return sb.toString(); } } }
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.
Java String-Collection: Longest common prefixes
I got a collection of String (directory paths). How can I get the longest common prefixes of ALL strings? Example: ["e:/users/test", "e:/users/test/abc/", "c:/programs", "e:/data", "/test"] the solution has to be than: ["e:/", "c:/programs", "/test"] I have no idea how to realize this ... thanks for your help, greetings
Neither pretty nor fast, but seems to work: public List<String> longestCommonPrefixes(Collection<String> c) { List<String> list = new ArrayList<>(c); List<String> result = new ArrayList<>(); while (!list.isEmpty()) { String lcp = longestCommonPrefix(list); result.add(lcp); for (Iterator<String> it = list.iterator(); it.hasNext();) { if (it.next().startsWith(lcp)) { it.remove(); } } } return result; } private String longestCommonPrefix(List<String> list) { Map<Character, Integer> map = new HashMap<>(); for (String s : list) { char c = s.charAt(0); if (map.containsKey(c)) { map.put(c, map.get(c) + 1); } else { map.put(c, 1); } } char c = 0; int max = 0; for (Map.Entry<Character, Integer> e : map.entrySet()) { int n = e.getValue(); if (n > max) { max = n; c = e.getKey(); } else if (n == max) { c = 0; } } if (c == 0) { int maxLen = 0; String sMaxLen = null; for (String s : list) { if (s.length() > maxLen) { maxLen = s.length(); sMaxLen = s; } else if (s.length() == maxLen) { sMaxLen = null; } } return sMaxLen; } else { String s = null; for (int i = 0; i < list.size(); i++) { if (list.get(i).charAt(0) == c) { s = list.get(i); for (int j = i + 1; j < list.size(); j++) { String s2 = list.get(j); if (s2.charAt(0) != c) { continue; } if (s.length() > s2.length()) { s = s.substring(0, s2.length()); } for (int k = 0; k < s.length(); k++) { if (s.charAt(k) != s2.charAt(k)) { s = s.substring(0, k); break; } } } break; } } return s; } }