The following code is from Java mooc that is supposed to find all genes in a given file. The problem is that my getAllGenes method is not returning any genes for a given string of dna. I simply don't know what is wrong with the code.
The file I'm testing against (brca1line.fa) is located here https://github.com/polde-live/duke-java-1/tree/master/AllGenesFinder/dna
Thank you.
This is my java code.
public class AllGenesStored {
public int findStopCodon(String dnaStr,
int startIndex,
String stopCodon){
int currIndex = dnaStr.indexOf(stopCodon,startIndex+3);
while (currIndex != -1 ) {
int diff = currIndex - startIndex;
if (diff % 3 == 0) {
return currIndex;
}
else {
currIndex = dnaStr.indexOf(stopCodon, currIndex + 1);
}
}
return -1;
}
public String findGene(String dna, int where) {
int startIndex = dna.indexOf("ATG", where);
if (startIndex == -1) {
return "";
}
int taaIndex = findStopCodon(dna,startIndex,"TAA");
int tagIndex = findStopCodon(dna,startIndex,"TAG");
int tgaIndex = findStopCodon(dna,startIndex,"TGA");
int minIndex = 0;
if (taaIndex == -1 ||
(tgaIndex != -1 && tgaIndex < taaIndex)) {
minIndex = tgaIndex;
}
else {
minIndex = taaIndex;
}
if (minIndex == -1 ||
(tagIndex != -1 && tagIndex < minIndex)) {
minIndex = tagIndex;
}
if (minIndex == -1){
return "";
}
return dna.substring(startIndex,minIndex + 3);
}
public StorageResource getAllGenes(String dna) {
//create an empty StorageResource, call it geneList
StorageResource geneList = new StorageResource();
//Set startIndex to 0
int startIndex = 0;
//Repeat the following steps
while ( true ) {
//Find the next gene after startIndex
String currentGene = findGene(dna, startIndex);
//If no gene was found, leave this loop
if (currentGene.isEmpty()) {
break;
}
//Add that gene to geneList
geneList.add(currentGene);
//Set startIndex to just past the end of the gene
startIndex = dna.indexOf(currentGene, startIndex) +
currentGene.length();
}
//Your answer is geneList
return geneList;
}
public void testOn(String dna) {
System.out.println("Testing getAllGenes on " + dna);
StorageResource genes = getAllGenes(dna);
for (String g: genes.data()) {
System.out.println(g);
}
}
public void test() {
FileResource fr = new FileResource();
String dna = fr.asString();
// ATGv TAAv ATG v v TGA
//testOn("ATGATCTAATTTATGCTGCAACGGTGAAGA");
testOn(dna);
// ATGv v v v TAAv v v ATGTAA
//testOn("ATGATCATAAGAAGATAATAGAGGGCCATGTAA");
}
}
The data in the file is like "acaagtttgtacaaaaaagcagaagggccgtcaaggcccaccatgcctattggatccaaagagaggccaacatttttt". You are searching for uppercase characters in a string containing only lower case characters. String.indexOf will therefore never find TAA, TAG or TGA. Change the strings to a lower case.
int startIndex = dna.indexOf("atg", where);
...
int taaIndex = findStopCodon(dna,startIndex,"taa");
int tagIndex = findStopCodon(dna,startIndex,"tag");
int tgaIndex = findStopCodon(dna,startIndex,"tga");
Responding to the comment below: if you want to be able to handle mixed case, like you do in your text, you need to lowercase() the string first.
Related
I'm very new to binary search and I attempted a code that would read values from a document and then the user can input a number to search for from the document, and through binary search, the number would be found. I'm having trouble now because the "low" variable that I initialize in the binary search section of my code is not being returned to my main code and there's an error that says "low can not be resolved to a variable".
Here is the code for my binary search:
static public int search (int[]numbers,int target, int count)
{
int high = numbers.length;
int low = -1;
int middle = (high+low)/2;
while(high-low>1)
{
count++;
middle = (high+low)/2;
if(numbers[middle]>target)
{
high = middle;
}
else if(numbers[middle]<target)
{
low = middle;
}
else
{
break;
}
System.out.println(numbers[middle]);
System.out.println(middle);
}
if(low == -1 || numbers[low]!=target)
{
low=-1;
return low;
}
else
{
return low;
}
}
And here is the code from my main code. The part with the if statements is where the error is showing up:
public static void main(String[] args) throws IOException {
DataInputStream input = new DataInputStream(System.in);
int [] numbers = new int [50000];
int target;
int count=0;
try
{
BufferedReader br = new BufferedReader(new FileReader("randNums.txt"));
for(int i=0;i<50000;i++)
{
numbers[i]=Integer.parseInt(br.readLine());
}
br.close();
Arrays.sort(numbers);
System.out.print("Choose a number between 1-100000000 to search for: ");
target = Integer.parseInt(input.readLine());
search(numbers, target,count);
if(low==-1)
{
System.out.println("The number was not on the list.");
}
else
{
System.out.println("The number is at position " + low);
System.out.println("It took " + count + " comparisons to find the number.");
}
}
You have to initialize low in main:
int low=search(numbers, target,count);
I have Already resolved this algorithm.
Try my code :
public static int guessNumber(int number) {
int first = 0;
int last = 1_000_000;
if (verify(first) == 0) {
count++;
return first;
}
if (verify(last) == 0) {
count++;
return last;
}
while (last > first && count <= 50) {
count += 1;
// get the middle of the range
int middle = (first + last) / 2;
if (verify(middle) == 0) {
return middle;
}
if (verify(middle) == 1) {
first = middle + 1;
if (verify(first) == 0) {
return first;
}
}else {
last = middle - 1;
if (verify(last) == 0)
return last;
}
}
return 0;
}
//Function verify(integer) => integer
public static int verify(int guess){
if (numberTobeGuessed > guess ) {
return 1;
}else if (numberTobeGuessed < guess) {
return -1;
}
return 0;
}
I recently found a solution for lazy peoples like me use below code
int position = Arrays.binarySearch(numbers , target);
here no need to sort, and array variable number integer variable target.
public class CreditCardNumber {
private String issuerId;
private String accountNum;
private int checkDigit = 9;
private StringBuilder builder;
public CreditCardNumber(String id, String accNum) {
this();
if (id != null && accNum != null && id.length() == 6 && accNum.length() == 9 && isDigit(id) == true
&& isDigit(accNum) == true) {
accountNum = accNum;
issuerId = id;
}
setCheckDigit();
}
public CreditCardNumber() {
issuerId = "000000";
accountNum = "999999999";
}
public String getId() {
return issuerId;
}
public String getAccNum() {
return accountNum;
}
public int getCheckDigit() {
return checkDigit;
}
// A
private void setCheckDigit() {
int sum = checkSum();
int temp = sum + checkDigit;
if(temp%10 != 0) {
int num = temp%10;
checkDigit = checkDigit - num;
}
}
// Method to check if each character in string is a digit
public boolean isDigit(String s) {
boolean condition = true;
for (int i = 0; i < s.length(); i++) {
if (Character.isDigit(s.charAt(i))) {
condition = true;
}
}
return true;
}
// B
public void changeId(String id) {
int max = 9;
int min = 0;
if (id != null && id.length() == 6 && isDigit(id) == true) {
issuerId = id;
}
builder = new StringBuilder();
for (int i = 0; i <= 9; i++) {
int randomNum = (int) (Math.random() * (max - min + 1)) + min;
builder.append(randomNum);
accountNum = builder.toString();
}
setCheckDigit();
}
// C
private int checkSum() {
int sum = 0;
builder = new StringBuilder();
builder.append(issuerId);
builder.append(accountNum);
for (int i = 0; i < builder.length(); i++) {
// In each of the chars with an EVEN index
if (i % 2 == 0) {
int x = Integer.parseInt(Character.toString(builder.charAt(i))); //// get the int value from the char
int y = x * 2; // multiply it by 2
if (y >= 10) {
int z = y % 10;
z += 1; //// if doubling it has 2 digits, add those digits
builder.setCharAt(i, Character.forDigit(z, 10)); // put above result back into the StringBuilder at
// the same index
}
}
}
// Add the values of each digit in the StringBuilder
for (int i = 0; i < builder.length(); i++) {
sum += Integer.parseInt(Character.toString(builder.charAt(i)));
}
return sum;
}
//D
}
/* public String toString() {
a public method called toString (NO PARAMETERS) that returns (in a
return
statement) the issuerID, accountNum and checkDigit , BUT WITH A ' '
(space)
BETWEEN EVERY 4 CHARACTERS! (don't change any of the instance variables
here!)
}
}
*/
So my main issue here is, the directions say that I have to return these variables (all more than 4 digits) but with a delimiter ' ' between every 4 characters. I need some guidance into figuring out how to implement the "every 4 digits" part. Maybe using a StringBuilder? Please help.
To return a String with ' ' delimiters in between every four characters, use these methods:
// Takes a String as input and outputs a formatted String:
public String toFormattedString(String inputString){
StringBuilder returnStringBuilder = new StringBuilder();
for(int i = 0; i < inputString.length(); i++) {
returnStringBuilder.append(inputString.charAt(i));
if(i%4==3) {
returnStringBuilder.append(' ');
}
}
return new String(returnStringBuilder);
}
// Takes a int as input and outputs a formatted String:
public String toFormattedString(int inputInt){
return toFormattedString(Integer.toString(inputInt));
}
You can use these methods in your public String toString() method. I'm just not sure how you want the three Strings to be returned in one String return value. Do you want them appended to each other or returned in a different way?
I have been working on this problem for several hours now and I just cannot figure out what I am doing wrong here. Could anyone help point me in the right direction?
I was asked to write an Autocomplete program and I've completed everything except for this one method I cannot get working. Each term has: 1. String query and 2. long weight.
Here is the method:
public static Comparator<Term> byReverseWeightOrder() {
return new Comparator<Term>() { // LINE CAUSING PROBLEM
public int compare(Term t1, Term t2) {
if (t1.weight > t2.weight) { // LINE CAUSING PROBLEM
return -1;
} else if (t1.weight == t2.weight) {
return 0;
} else {
return 1;
}
}
};
}
My problem is that no matter how I mess with the method I always result in a NullPointerException(). Which, it points to this method (byReverseWeightOrder) as well as these two statements.
Arrays.sort(matches, Term.byReverseWeightOrder());
Term[] results = autocomplete.allMatches(prefix);
Here is the rest of the code if it can be found helpful:
Term
import java.util.Comparator;
public class Term implements Comparable<Term> {
public String query;
public long weight;
public Term(String query, long weight) {
if (query == null) {
throw new java.lang.NullPointerException("Query cannot be null");
}
if (weight < 0) {
throw new java.lang.IllegalArgumentException("Weight cannot be negative");
}
this.query = query;
this.weight = weight;
}
public static Comparator<Term> byReverseWeightOrder() {
return new Comparator<Term>() {
public int compare(Term t1, Term t2) {
if (t1.weight > t2.weight) {
return -1;
} else if (t1.weight == t2.weight) {
return 0;
} else {
return 1;
}
}
};
}
public static Comparator<Term> byPrefixOrder(int r) {
if (r < 0) {
throw new java.lang.IllegalArgumentException("Cannot order with negative number of characters");
}
final int ref = r;
return
new Comparator<Term>() {
public int compare(Term t1, Term t2) {
String q1 = t1.query;
String q2 = t2.query;
int min;
if (q1.length() < q2.length()) {
min = q1.length();
}
else {
min = q2.length();
}
if (min >= ref) {
return q1.substring(0, ref).compareTo(q2.substring(0, ref));
}
else if (q1.substring(0, min).compareTo(q2.substring(0, min)) == 0) {
if (q1.length() == min) {
return -1;
}
else {
return 1;
}
}
else {
return q1.substring(0, min).compareTo(q2.substring(0, min));
}
}
};
}
public int compareTo(Term that) {
String q1 = this.query;
String q2 = that.query;
return q1.compareTo(q2);
}
public long getWeight() {
return this.weight;
}
public String toString() {
return this.weight + "\t" + this.query;
}
}
BinarySearchDeluxe
import java.lang.*;
import java.util.*;
import java.util.Comparator;
public class BinarySearchDeluxe {
public static <Key> int firstIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
if (a == null || key == null || comparator == null) {
throw new java.lang.NullPointerException();
}
if (a.length == 0) {
return -1;
}
int left = 0;
int right = a.length - 1;
while (left + 1 < right) {
int middle = left + (right - left)/2;
if (comparator.compare(key, a[middle]) <= 0) {
right = middle;
} else {
left = middle;
}
}
if (comparator.compare(key, a[left]) == 0) {
return left;
}
if (comparator.compare(key, a[right]) == 0) {
return right;
}
return -1;
}
public static <Key> int lastIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
if (a == null || key == null || comparator == null) {
throw new java.lang.NullPointerException();
}
if (a == null || a.length == 0) {
return -1;
}
int left = 0;
int right = a.length - 1;
while (left + 1 < right) {
int middle = left + (right - left)/2;
if (comparator.compare(key, a[middle]) < 0) {
right = middle;
} else {
left = middle;
}
}
if (comparator.compare(key, a[right]) == 0) {
return right;
}
if (comparator.compare(key, a[left]) == 0) {
return left;
}
return -1;
}
}
AutoComplete
import java.util.Arrays;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.util.Comparator;
public class Autocomplete {
public Term[] terms;
public Autocomplete(Term[] terms) {
if (terms == null) {
throw new java.lang.NullPointerException();
}
this.terms = terms.clone();
Arrays.sort(this.terms);
}
public Term[] allMatches(String prefix) {
if (prefix == null) {
throw new java.lang.NullPointerException();
}
Term theTerm = new Term(prefix, 0);
int start = BinarySearchDeluxe.firstIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
int end = BinarySearchDeluxe.lastIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
int count = start;
System.out.println("Start: " + start + " End: " + end);
if (start == -1 || end == -1) {
// System.out.println("PREFIX: " + prefix);
throw new java.lang.NullPointerException();
} // Needed?
Term[] matches = new Term[end - start + 1];
//matches = Arrays.copyOfRange(terms, start, end);
for (int i = 0; i < end - start; i++) {
matches[i] = this.terms[count];
count++;
}
Arrays.sort(matches, Term.byReverseWeightOrder());
System.out.println("Finished allmatches");
return matches;
}
public int numberOfMatches(String prefix) {
if (prefix == null) {
throw new java.lang.NullPointerException();
}
Term theTerm = new Term(prefix, 0);
int start = BinarySearchDeluxe.firstIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
int end = BinarySearchDeluxe.lastIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
System.out.println("Finished numberMatches");
return end - start + 1; // +1 needed?
}
public static void main(String[] args) throws IOException {
// Read the terms from the file
Scanner in = new Scanner(new File("wiktionary.txt"));
int N = in.nextInt(); // Number of terms in file
Term[] terms = new Term[N];
for (int i = 0; i < N; i++) {
long weight = in.nextLong(); // read the next weight
String query = in.nextLine(); // read the next query
terms[i] = new Term(query.replaceFirst("\t",""), weight); // construct the term
}
Scanner ip = new Scanner(System.in);
// TO DO: Data Validation Here
int k;
do {
System.out.println("Enter how many matching terms do you want to see:");
k = ip.nextInt();
} while (k < 1 || k > N);
Autocomplete autocomplete = new Autocomplete(terms);
// TO DO: Keep asking the user to enter the prefix and show results till user quits
boolean cont = true;
do {
// Read in queries from standard input and print out the top k matching terms
System.out.println("Enter the term you are searching for. Enter * to exit");
String prefix = ip.next();
if (prefix.equals("*")) {
cont = false;
break;
}
Term[] results = autocomplete.allMatches(prefix);
System.out.println(results.length);
for(int i = 0; i < Math.min(k,results.length); i++)
System.out.println(results[i].toString());
} while(cont);
System.out.println("Done!");
}
}
I apologize for the sloppy code, I have been pulling my hair out for awhile now and keep forgetting to clean it up.
Two examples:
Example 1:
int k = 2;
String prefix = "auto";
Enter how many matching terms do you want to see:
2
Enter the term you are searching for. Enter * to exit
auto
619695 automobile
424997 automatic
Example 2:
int k = 5;
String prefix = "the";
Enter how many matching terms do you want to see:
5
Enter the term you are searching for. Enter * to exit
the
5627187200 the
334039800 they
282026500 their
250991700 them
196120000 there
Problem:
Develop a recursive algorithm to determine if there is a palindrome hidden within a longer word or phrase. A palindrome is a word or phrase that has the same sequence of letters when read from left to right and when read from right to left, ignoring the spaces (e.g., Some like cake, but I prefer pie contains the palindrome I prefer pi).
Below is my code:
public class e125 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int i = 0;
String sLine = "Some like cake, but I prefer pie";
sLine.replaceAll("\\s+", "");
System.out.println(PlainRet(sLine, i));
}
public static String PlainRet(String sLine, int i) {
int nNum;
char c = 0;
String sPlain = "";
if (i >= sLine.length()) {
return "No Plaindrome";
}
c = sLine.charAt(i);
nNum = Isgood(sLine, c, i);
if (nNum != 0) {
for (; i < nNum; i++) {
sPlain += sLine.charAt(i);
}
return sPlain;
}
return PlainRet(sLine, i + 1);
}
public static int Isgood(String sLine, char c, int i) {
for (int j = i + 1; j < sLine.length(); j++) {
if (Character.toUpperCase(sLine.charAt(j)) == Character.toUpperCase(c)) {
if (Isplain(sLine, i, j)) {
return j;
}
}
}
return 0;
}
public static boolean Isplain(String sLine, int i, int j) {
if (Character.toUpperCase(sLine.charAt(j)) != Character.toUpperCase(sLine.charAt(i))) {
return false;
}
else if (i == j || j == i + 1) {
return true;
}
return (Isplain(sLine, i + 1, j - 1));
}
}
I keep getting an output of "I"
I have no idea what is wrong.
Like FatalError commented sLine.replaceAll() returns a new String. You need to reassign sLine or pass the results of the replaceAll() into the method.
You'll find a new error to fix after you do that, but it's just an off-by-one!
Here's my application
"Textform", take value from the searchbox.
"listKamus", take value from the array. Then "player name", change it value to string.
"KMP.knutMorris(textform, playerName)", send textform, playerName value to knutMorris class
MAIN CLASS
public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3)
{
String textform = s.toString();
searchResults.clear();
for(int i=0;i<listKamus.size();i++)
{
String playerName=listKamus.get(i).toString();
KMP.knutMorris(textform, playerName);
if(KMP.value==1){
searchResults.add(listKamus.get(i));
}
}
adapter.notifyDataSetChanged();
}
KMP CLASS
public class KMP {
/** Failure array **/
private int[] failure;
public static int value;
/** Constructor **/
public KMP(String text, String pat)
{
/** pre construct failure array for a pattern **/
failure = new int[pat.length()];
fail(pat);
/** find match **/
int pos = posMatch(text, pat);
if (pos >= 0)
{
KMP.value = 1;
}
}
/** Failure function for a pattern **/
private void fail(String pat)
{
int n = pat.length();
failure[0] = -1;
for (int j = 1; j < n; j++)
{
int i = failure[j - 1];
while ((pat.charAt(j) != pat.charAt(i + 1)) && i >= 0)
i = failure[i];
if (pat.charAt(j) == pat.charAt(i + 1))
failure[j] = i + 1;
else
failure[j] = -1;
}
}
/** Function to find match for a pattern **/
private int posMatch(String text, String pat)
{
int i = 0, j = 0;
int lens = text.length();
int lenp = pat.length();
while (i < lens && j < lenp)
{
if (text.charAt(i) == pat.charAt(j))
{
i++;
j++;
}
else if (j == 0)
i++;
else
j = failure[j - 1] + 1;
}
return ((j == lenp) ? (i - lenp) : -1);
}
/** Main Function **/
public static void knutMorris(String textform, String isidatabase)
{
String text = textform;
String pattern = isidatabase;
KMP kmp = new KMP(text, pattern);
}
I want when people type on the searchbox it shows the right list of array.
I think the error one is here
MAIN CLASS
if(KMP.value==1){
searchResults.add(listKamus.get(i));
}
Or here
KMP CLASS
if (pos >= 0)
{
KMP.value = 1;
}
Can anyone tell me how to fix this ?