Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

/////// Problem 1

////// 1 A

public static boolean isValidDNA(String str)


{
String s = "";
for(int i = 0; i < str.length(); i++)
{
s = str.substring(i, i + 1);
if(!s.equals("A") && !s.equals("C") && !s.equals("T") &&
!s.equals("G") )
{
return false;
}
}
return true;
}

//////// 1 B

public static int matchTwoGenes(String dna, String gene1, String gene2)


{
int index1 = dna.indexOf(gene1) + gene1.length();
int index2 = dna.indexOf(gene2);

if(index1 == -1 || index2 == -1 || index1 > index2)


{
return -1;
}
return index2 - index1;
}

///// Problem 2

public class Car


{
private final double TANKSIZE;
private double fuel;
private int milesDriven;
private double gasUsed;

public Car(double ts)


{
TANKSIZE = ts;
fuel = ts;
milesDriven = 0;
gasUsed = 0.0;
}

public double getGasLeft()


{
return fuel;
}

public void fillUp()


{
fuel = TANKSIZE;
}

public void logTrip(int driven, int gas)


{
milesDriven+=driven;
double g = TANKSIZE * gas;
gasUsed+=g;
fuel-=g;
}

public int mpg()


{
return (int)(milesDriven / gasUsed);
}
Hv to round to the nearest
double, so add 0.5 to the
double solution b4 converting
to an int
}

////// Problem 3

////// 3 A

public void add(Message msg)


{
int priority = msg.getPriority();
queue[priority].add(msg);
numMessages++;
}

///// 3 B

public Message remove()


{
for(int i = queue.length - 1; i >= 0; i--)
{
if(!queue[i].isEmpty())
{
return queue[i].remove();
}
}
return null;
}

Decrease numMessages as well


//// Problem 4

/// 4A

public boolean canSwitchLane(int lane, int x, int dir)


{

if(dir == 1)
{
if(lane == hwy.length - 1)
{
return false;
}
for(int i = lane + dir; i < hwy.length; i+=dir)
{
if(hwy[lane][x] == 1)
{
return false;
}
} Use only one while loop instead of
return true;
} splitting into 2 different loops,
else makes code much more efficient.
{
if(lane == 0)
{
return false;
}
for(int i = lane + dir; i > 0; i+=dir)
{
if(hwy[lane][x] == 1)
{
return false;
}
}
return true;
}

////// 4 B

public void moveAllForward()


{
int temp = 0;
for(int row = 0; row < hwy.length; row++)
{
temp = hwy[row][0];
for(int col = 0; col < hwy[0].length; col++)
{
if(temp == 1)
{
if(col + 1 < hwy[0].length)
{
temp = hwy[row][col + 1];
hwy[row][col + 1] = 1; Works, but too confusing, can just
hwy[row][col] = 0;
}
make save the last object and go
else back from the end of the list and
{ make it equal to the number b4 it,
hwy[row][0] = 1;
} then set the first object to the last
index
}
else
{
temp = hwy[row][col + 1];
}
}
}
}

You might also like