remove start codon from final println - java

I need to print out everything between a start codon atg and one of three end codons tga, taa, and tag. I have been trying to solve this problem for a couple days now but I can't seem to find a way to remove the start codon from what gets printed out at the end EX: If you use my code it will print out ATGAAA but I need it to print out only AAA.
public class GeneFinderYang {
public static int findStopIndex(String dna, int index){
int stop1 = dna.indexOf("tga", index);
if (stop1 == -1 || (stop1 - index) % 3 != 0) {
stop1 = dna.length();
}
int stop2 = dna.indexOf("taa", index);
if (stop2 == -1 || (stop2 - index) % 3 != 0) {
stop2 = dna.length();
}
int stop3 = dna.indexOf("tag", index);
if (stop3 == -1 || (stop3 - index) % 3 != 0) {
stop3 = dna.length();
}
return Math.min(stop1, Math.min(stop2,stop3));
}
public static void printAll(String dna){
String dnaLow = dna.toLowerCase();
int start = 0;
while (true) {
int loc = dnaLow.indexOf( "atg", start );
int stop = findStopIndex( dnaLow, loc+3 );
if ( stop != dna.length() ) {
System.out.println( dna.substring(loc, stop) );
start = stop + 3;
} else {
start = start + 3;
}
}
}
// demo
public static void testFinder() {
String dna1 = "ATGAAATGAAAA";
System.out.println("DNA string is: \n" +dna1);
System.out.println("Genes found are:");
printAll(dna1);
System.out.print("\n");
}
public static void main(String[] args) {
testFinder();
}
}

The error is in your printAll() function.
public static void printAll(String dna){
String dnaLow = dna.toLowerCase();
int start = 0;
while (true) {
int loc = dnaLow.indexOf( "atg", start );
int stop = findStopIndex( dnaLow, loc+3 );
if ( stop != dna.length() ) {
System.out.println( dna.substring(loc, stop) );
start = stop + 3;
} else {
start = start + 3;
}
}
}
The main issue here is you are using too many variables. You should only need the start variable, not the loc variable. If we switch all occurrences of loc and get rid of the ugly arithmetic the function will look like this:
public static void printAll(String dna){
String dnaLow = dna.toLowerCase();
int start = 0;
while (true) {
start = dnaLow.indexOf( "atg", start ) + 3;
int stop = findStopIndex( dnaLow, start );
if ( stop != dna.length() ) {
System.out.println( dna.substring(start, stop) );
start = stop + 3;
} else {
start = start + 3;
}
}
}
But we are not done. If we run the code this way, things will work much the same as your code currently does. Now what the indexOf() function does is return the index of the start of the string. So when you are finding the index of ATG, it returns zero. Well, the string you want starts at index 3 because atg is three characters long. This is easily solved by adding three to the result. You need to do this everytime, not just when your if statement fails. If this is supposed to output multiple genes, you might try restructuring your code a bit, preferably away from an infinite loop. The main issue being that in your if statement, you are checking if we are at the end of the string and then setting start equal to stop+3. But then the loop runs again and it gets set to the index of atg again. This is a symptom of ditching the loc variable admittedly.
public static void printAll(String dna) {
String dnaLow = dna.toLowerCase();
int start = 0;
int stop = 0;
start = dnaLow.indexOf( "atg", start ) + 3;
while (start < dna.length())
{
stop = findStopIndex( dnaLow, start );
System.out.println( dna.substring(start, stop) );
start = stop + 3;
}
}
I also initialized the stop variable outside of the loop, but that is personal preference and it doesn't matter.
Edit:
For loops are your friend when dealing with multiple items. This is obvious in the findStopIndex() function. This function is actually easier to write with a for loop. What we will do is create arrays to hold our codons and indexes so there is one index per codon. Then we iterate through them trying find a stop index for each. If we don't find one, then we set the corresponding index to the end of the string.
public static int findStopIndex(String dna, int index){
String endCodons[] = { "tga", "taa", "tag"};
int stopIndexes[] = new int[3];
for(int i = 0; i<3 ;i++)
{
stopIndexes[i] = dna.indexOf(endCodons[i], index);
if(stopIndexes[i]==-1||(stopIndexes[i] - index) % 3 != 0)
stopIndexes[i] = dna.length();
}
return Math.min(stopIndexes[0], Math.min(stopIndexes[1],stopIndexes[2]));
}

Related

Why does my method return the wrong value?

Even though my method operationsNeeded prints the correct value for my return-int "count1", the very next line it returns something else to my main method. I did not include the rest of my code, if needed I'd gladly provide it.
For example if operationsNeeded is executed 4 times, count1 is on 4 which is printed out as well. But for reasons unknown to me the System.out.println("check: " +count1); Statement is executed 4 times like this:
check: 4
check: 4
check: 3
check: 2
I would expect my program to execute this only once and then continue to the return statement.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcases = sc.nextInt();
int count =0;
while (count<testcases){
int numberOfColleagues = sc.nextInt();
sc.nextLine();
String startPieces = sc.nextLine();
int[] listOfcolleagues = listOfColleagues(numberOfColleagues, startPieces);
int count2 = operationsNeeded(listOfcolleagues, 1);
count++;
System.out.println(count2);
}
}
public static int operationsNeeded (int[] listOfColleagues, int count1){
//remove duplicates first
ArrayList<Integer> relevantList=removeDuplicatesAndSort(listOfColleagues);
System.out.println("relevantlist" + relevantList);
//check for smallestdelta & index
int [] deltaAndIndex = smallestDeltaHigherIndex(relevantList);
int delta = deltaAndIndex[0];
int index = deltaAndIndex[1];
if (delta==1){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+1);
}
}
}
if (delta>1 && delta<5){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+2);
}
}
}
if (delta>4){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+5);
}
}
}
System.out.println(count1);
int[] updatedList = new int[relevantList.size()];
for (int i=0; i<relevantList.size();i++){
updatedList[i]=relevantList.get(i);
}
if (!isAllTheSame(relevantList)) {
count1 +=1;
operationsNeeded(updatedList,count1);
}
System.out.println("check: " + count1);
return count1;
}
Your method is recursive. The "check: " line is printed on each level of that recursion, with the value that it currently has on that level. It first prints the "inner-most" value (4), than that of the level above (also 4), and finally hte value in the top-level, which is 2 after being incremented in the if above. And the value it returns is always the value from to top-level.
If you want to print it only once, you could print it on the inner-most level only, using else. However, that will still return the value from the top-level iteration; instead, keep track of the value returned from the recirsive call and update count1 accordingly.
if (! isAllTheSame(relevantList)) {
// we have to go deeper!
count1 = operationsNeeded(updatedList, count1 + 1);
} else {
// phew, finally done
System.out.println("check: " + count1);
}

Need to find prime and perfect integers from min max values in an input file

This is a homework question.
The code compiles, but in the test case, 2 is outputting as perfect, which it is not.
I cannot use an array. I cannot use Math.min() or Math.max(). Purely conditionals and loops.
My professor says I need to only test for divisors up to and including n/2 but when I do that, I still get the 2 as a perfect number.
Any help would be appreciated.
// Project2.java
import java.io.*; // BufferedReader
import java.util.*; // Scanner
public class Project2
{
public static void main (String args[]) throws Exception
{
// ALWAYS TEST FIRST TO VERIFY USER PUT REQUIRED CMD ARGS
if (args.length < 3)
{
System.out.println("\nusage: C:\\> java Project2 <input file name> <lo> <hi>\n\n");
// i.e. C:\> java Project2 P2input.txt 1 30
System.exit(0);
}
String infileName = args[0]; // i.e. L2input.txt
int lo = Integer.parseInt( args[1] ); // i.e. 1
int hi = Integer.parseInt( args[2] ); // i.e. 30
// STEP #1: OPEN THE INPUT FILE AND COMPUTE THE MIN AND MAX. NO OUTPUT STATMENTS ALLOWED
Scanner infile = new Scanner( new File(infileName) );
int min,max;
min=max=infile.nextInt(); // WE ASSUME INPUT FILE HAS AT LEAST ONE VALUE
while ( infile.hasNextInt() )
{
// YOUR CODE HERE FIND THE MIN AND MAX VALUES OF THE FILE
// USING THE LEAST POSSIBLE NUMBER OF COMPARISONS
// ASSIGN CORRECT VALUES INTO min & max INTHIS LOOP.
// MY CODE BELOW WILL FORMAT THEM TO THE SCREEN
// DO NOT WRITE ANY OUTPUT TO THE SCREEN
int number = infile.nextInt();
if ( number < min )
{
min = number;
}
else if ( number > max )
{
max = number;
}
}
System.out.format("min: %d max: %d\n",min,max); // DO NOT REMOVE OR MODIFY IN ANY WAY
// STEP #2: DO NOT MODIFY THIS BLOCK
// TEST EVERY NUMBER BETWEEN LO AND HI INCLUSIVE FOR
// BEING PRIME AND/OR BEING PERFECT
for ( int i=lo ; i<=hi ; ++i)
{
System.out.print( i );
if ( isPrime(i) ) System.out.print( " prime ");
if ( isPerfect(i) ) System.out.print( " perfect ");
System.out.println();
}
} // END MAIN
// *************** YOU FILL IN THE METHODS BELOW **********************
// RETURNs true if and only if the number passed in is perfect
static boolean isPerfect( int n )
{
int sum = 0;
for(int i = 1; i <= n/2; i ++)
{
if(n%i == 0)
{
sum += i;
}
}
if (sum == n)
{
return true;
}
else
{
return false;
}
// (just to make it compile) YOU CHANGE AS NEEDED
}
// RETURNs true if and only if the number passed in is prime
static boolean isPrime( int n )
{
if (n < 3)
{
return false;
}
for(int i = 2; i <= n/2; i++)
{
if(n%i == 0)
{
return false;
}
}
return true;
}// (just to make it compile) YOU CHANGE AS NEEDED
}
OK, I found a bug, although it's not quite the bug you described.
static boolean isPrime( int n )
{
if (n < 3)
{
return false;
}
This will incorrectly list 2 as not prime, because it's less than 3.

How to pass a String parameter to a void method? [duplicate]

This question already has an answer here:
What does "Incompatible types: void cannot be converted to ..." mean?
(1 answer)
Closed 3 years ago.
I need to write a Java program for a course I'm taking which looks for genes in a strand of DNA.The Issue I am having is that from the test method, I need to pass printAllgenes(a) to the void printAllgenes method. In the test method I've tried setting 'int a' to 'String a', but in either case an error when compiling explaining that void cannot be converted to int or String. I'm sure its obvious, but I'm very new to programming, so please pardon my ignorance! Thank you.
import java.io.*;
import edu.duke.*;
public class FindProtein {
public void test() {
String a = "atg aaa tab tag atg aaa tga aat ag";
int b = printAllgenes(a);
System.out.println("DNA string is " + a);
System.out.println("Gene found is " + b);
}
public void printAllgenes(String dna) {
int sp = 0; //start point
while (true) {
int start = dna.indexOf("atg,sp");
if (start == -1) {
break;
}
int stop = findStopIndex(dna, start + 3);
if (stop != dna.length()) {
System.out.println(dna.substring(start, stop + 3));
sp = stop + 3;
} else {
sp = sp + 3;
}
}
}
public int findStopIndex(String dna, int index) {
int tga = dna.indexOf("tga", index);
if (tga == -1 || (tga - index) % 3 != 0) {
tga = dna.length();
}
int taa = dna.indexOf("taa", index);
if (taa == -1 || (taa - index) % 3 != 0) {
taa = dna.length();
}
int tag = dna.indexOf("tag", index);
if (tag == -1 || (tga - index) % 3 != 0) {
tag = dna.length();
}
return Math.min(tga, Math.min(taa, tag));
}
}
Try to use just:
printAllgenes(a);
Because printAllgenes method doesn't have any type of return statement.
change return type void to int It will return your count whatever u want to return from printAllgenes(String dns) Method. You will get a int return which will initialize you variable b that is being displayed on Console.
public int printAllgenes(String dna){
int sp = 0; //start point
while (true){
int start = dna.indexOf("atg,sp");
if (start==-1){
break;
}
int stop = findStopIndex(dna,start+3);
if (stop!=dna.length()){
System.out.println(dna.substring(start,stop+3));
sp=stop+3;
}
else{
sp=sp+3;
}
}
return sp;
}
Now Your Test Method Implementation will work fine...
public void test(){
String a= "atg aaa tab tag atg aaa tga aat ag";
int b = printAllgenes(a);
System.out.println("DNA string is " +a);
System.out.println("Gene found is "+b);
}
Thank you..

Recursive print Factorial

So I did search and read abut every factorial listing on this site but I cannot seem to figure out what is wrong with my code. Iv tried multiple different return methods but they all keep failing. Any ideas?
public class RecursivelyPrintFactorial {
public static void printFactorial(int factCounter, int factValue) {
int nextCounter = 0;
int nextValue = 0;
if (factCounter == 0) // Base case: 0! = 1
System.out.println("1");
}
else if (factCounter == 1) // Base case: print 1 and result
System.out.println(factCounter + " = " + factValue);
}
else { // Recursive case
System.out.print(factCounter + " * ");
nextCounter = factCounter - 1;
nextValue = nextCounter * factValue;
}
return factValue * printFactorial(factValue - factCounter);
}
}
public static void main (String [] args) {
int userVal = 0;
userVal = 5;
System.out.print(userVal + "! = ");
printFactorial(userVal, userVal);
}
}
I have a feeling I have the equation incorrect in my return but iv tried every combination I can think of. Its driving me insane. Every one reports an error. Any ideas?
return factValue * printFactorial(factValue - factCounter);
I assume that you should be using the "next" values instead of these.
Edit: Also note that the function takes two parameters and is void. Returning factValue times void doesn't make sense.

While Parallelizing QuickSort in Java, Threads never returns back at join(). Why?

I am having simple code of paralellizing QuickSort algorithm in Java, in run method I everytime create two seperate new threads for parallelizing processing of Array elements. But as it encounters join() statements for both created threads, threads never backs and halts on joins(), seems join() never releases them.
Below is the code.
class StartJoinQuickSort implements Runnable
{
private int m_Low, m_High;
private int[] m_Array = null;
private final static int NR_OF_VALUES = 10; // TOTAL_NO_VALUES
private int PivotElement;
private static Random m_random = new Random( );
public StartJoinQuickSort(int[] a_Array,int a_Low,int a_High)
{
this.m_Array = a_Array;
this.m_Low = a_Low;
this.m_High = a_High;
}
private void SwapArrayElements(int a_i,int a_j)
{
int temp = this.m_Array[a_i];
this.m_Array[a_i] = this.m_Array[a_j];
this.m_Array[a_j] = temp;
}// end of SwapArrayElements
private static int nextRandomFunctionValue(int aStart, int aEnd)
{
if ( aStart > aEnd )
{
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems
long range = (long)aEnd - (long)aStart + 1;
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * m_random.nextDouble());
int randomNumber = (int)(fraction + aStart);
return randomNumber;
}// end of nextRandomFunctionValue
private static int[] GetArrayWithRandomValues()
{
int[] ArrayToBePopulatedWithRandomValues = new int[NR_OF_VALUES];
for(int index =0; index<NR_OF_VALUES;index++)
{
int RandomValue = StartJoinQuickSort.nextRandomFunctionValue(0,NR_OF_VALUES);
ArrayToBePopulatedWithRandomValues[index] = RandomValue;
}//end of for
return ArrayToBePopulatedWithRandomValues;
}//end of GetArrayWithRandomValues
private int middleIndex(int left, int right)
{
return left + (right - left) / 2;
}
public int Partition(int a_Start,int a_end)
{
// System.out.println("Partition ..thId : " + Thread.currentThread().getId());
int pivotIndex = 0;
int i = a_Start;
int j = a_end;
try
{
pivotIndex = middleIndex(a_Start , a_end);
this.PivotElement = this.m_Array[pivotIndex];
do
{
while(this.m_Array[i] < PivotElement )
i++;
if(j>0)
{
try
{
while( this.m_Array[j] > PivotElement )
j--;
}
catch(Exception ex){System.out.println(" j : " + j);}
}//end of if
if(i<=j)
{
SwapArrayElements(i,j);
// System.out.println("Swap .." + + Thread.currentThread().getId());
i++;
j--;
}//end of if
}while(i<=j);
}
catch(Exception except)
{
System.out.println("exception in Partition " + except);
}
return j;
}
public void run()
{
//System.out.println("in run..");
//System.out.println("after PARTITION");
StartJoinQuickSort oStartQuickSort_1 = null;
StartJoinQuickSort oStartQuickSort_2 = null;
if(this.m_Low < this.m_High )
{
int Index = Partition(this.m_Low,this.m_High);
Thread thPart_1 = new Thread ( new StartJoinQuickSort( this.m_Array,this.m_Low,Index ) );
Thread thPart_2 = new Thread ( new StartJoinQuickSort( this.m_Array,Index + 1,this.m_High ) );
thPart_1.start(); thPart_2.start();
//}//end of if
//if( Index + 1 < this.m_High)
//{
try
{
thPart_1.join(); thPart_2.join();
}catch (InterruptedException e) { e.printStackTrace();}
}
}//end of run
Regards
Usman
Hmmm, it is never a good idea to implement a recursive algorithm in parallel like this. You will end up creating a huge number of threads (exponential at every level) and will eventually oversubscribe the system.
The best idea is to have a cutoff point, which let's say is equal to the number of available cores. Then when the current level of recursion has a number of branches equal to the cutoff point switch to a sequential quicksort. Some very rough pseudocode of the flow:
parallel_quicksort(level, interval) {
// compute subintervals interval1, interval2
if(level < cutoff) {
spawn1: parallel_quicksort(level + 1, interval1);
spawn2: parallel_quicksort(level + 1, interval2);
join1();
join2();
} else {
quicksort(interval1);
quicksort(interval2);
}
}
Also have a look over this implementation to see if you've missed something: http://www.inf.fh-flensburg.de/lang/algorithmen/sortieren/quick/quicken.htm
What happens if you have e.g. low=0, high=1? If your Partition returns 1, you'll have an infinite loop of threads, right?
join() blocks if your thread doesn't finish. You need to determine why your threads are not finishing. Can you try debugging your program with a debugger?
Thanks all for your kind suggestions and advices.
I myself detected the problem. it was with Partition function which was not working fine, it was having some problems, I choose another one and it worked fine for me..
New Partition procedure is :
public int Partition(int[] a_Array, int a_Left, int a_Right)
{
// chose middle value of range for our pivot
int pivotValue = a_Array[middleIndex(a_Left, a_Right)];
--a_Left;
++a_Right;
while (true)
{
do
++a_Left;
while (a_Array[a_Left] < pivotValue);
do
--a_Right;
while (a_Array[a_Right] > pivotValue);
if (a_Left < a_Right)
SwapArrayElements(a_Left,a_Right);
else
{
return a_Right;
}
}
}

Categories