Genetic processes help in java - java

Merged with Genetic Programming help.
I need some guidance on a java project. I'm to develop a human genetic(family) tree.
This is the subject:
Each human cell contains 23 pairs of chromosomes numbered from 1 to 22,and a pair of sex chromosomes: XX in females and XY in man. During fertilization, the 22 chromosomes + (X or Y) of the man merges with the 22 + X chromosome of the woman. This results in 22 pairs of chromosomes + (X or Y) in the cell that will form the future baby. The 23rd chromosome transmitted by the father (an X or Y) will determine the sex of the child (XX for a girl, XY for a boy).
Each chromosome carries many genes (encoding almost everything, a characteristic morphological, physiological, behavioral). Due to pairs of chromosomes, the genetic information is duplicated (except for parts of the sex chromosomes). Each copy of a gene is called an allele. So that means for example, if the a gene is responsible for the color of an eye, then the allele is blue.
The genetic information expressed as a consequence of the combined expression of alleles being present. A dominant allele is always expressed in the genome of its bearer. However, if information from one allele is not expressed when a dominant allele of the same gene is present, it is a recessive allele. The peculiarity of the recessive allele of a gene is that it can be present in the genome and transmitted over several generations without it is expressed in the phenotype its bearers. If there is no dominant allele, two copies of the gene have the same recessive allele (homozygous recessive) then the recessive character is expressed. Through the use of family tree, it is possible to determine the expression of a gene within a family.
The program should be able to do the following:
generate a simplified version relied on 23 chromosomes and allow the user to place genes on chromosomes then simulate replication, mitosis, meiosis and fusion of the chromosomes and display the locations of genes on the resulting cells.
allow to draw genealogical trees and deduced probabilities (or certainty) on the expression of genes on a person's family tree.
So far so good i've created a class Gene and a class Chromosome. Next, i thought about creating a class "Parent" for example and creating 23 chromosomes in it. But before doing that i want to make the 23rd chromosome different for a man/woman. Then simulates replication, crossovers, mitosis etc.. I don't know if i'm on the right track. I also don't know how to specify that a particular allele/gene is recessive or dominant. For the moment my classes only act in a random manner.
Gene.java
import java.util.Random;
/**
* #author mkab
*
*/
public class Gene implements Cloneable {
private Object allele;
public Gene(){
super();
}
public Gene(Object allele){
super();
this.allele = allele;
}
/**
* Randomly selects a trait from trait1 or trait2 and returns a new Gene with that trait
* #param trait1
* #param trait2
*
* #return a new Gene
*/
public Gene randomAllele(Object trait1, Object trait2){
Object allele = null;
Random rand = new Random();
int i = rand.nextInt(2);// generate between 0 and 2: only 2 possibilities: 0 or 1
switch(i){
case 0:
allele = trait1;
break;
case 1:
allele = trait2;
break;
}
return new Gene(allele);
}
public Gene clone() throws CloneNotSupportedException{
Gene g;
g = (Gene) super.clone();
return g;
}
/**
* #param allele the allele to set
*/
public void setAllele(Object allele) {
this.allele = allele;
}
/**
* #return the allele
*/
public Object getAllele() {
return allele;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "Gene [allele=" + allele +"]";
}
}
Chromosome.java
import java.util.ArrayList;
import java.util.Iterator;
/**
* Class that creates a pair of chromosome by adding random genes
* #author mkab
*
*/
public class Chromosome implements Cloneable {
/**
* the user can put as many genes as possible on the chromosome
*/
private ArrayList<Gene> genes = new ArrayList<Gene>();
public Chromosome(){
super();
}
public Chromosome(ArrayList<Gene> genes){
this.genes = genes;
}
/**
* Add a gene object to this chromosomes list.
*/
public void addGene(Gene gene) {
genes.add(gene);
}
/**
*creates a copy of a chromosome
*/
#SuppressWarnings("unchecked")
#Override
public Chromosome clone()throws CloneNotSupportedException{
Chromosome c;
c = (Chromosome) super.clone();
c.genes = (ArrayList<Gene>)this.genes.clone();
//Iterator<Gene> it = c.genes.iterator();
/*Gene tmp;
while(it.hasNext()){
}*/
return c;
}
/**
* #return the genes
*/
public ArrayList<Gene> getGenes() {
return genes;
}
/**
* #param genes the genes to set
*/
public void setGenes(ArrayList<Gene> genes) {
this.genes = genes;
}
/**
*
* #return
*/
public int getSize(){
return genes.size();
}
/**
* #return a gene at an index i of the ArrayList
* #param index - the index at which to return a gene
*/
public Gene getGenes(int index) {
return genes.get(index);
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "Chromosome [genes=" + genes + "]";
}
}
Thanks

Related

Write a public method firstFifteen() that returns a String consisting of the first fifteen characters in the longNumber

I am starting to learn Java and the content in which we learn from I just CANNOT get on with, it doesn't explain much but just gives you a mild example and tells you to do it yourself with something completely different. as above I need to take the 'longNumber' string and take the last character off it.
* Write a description of class CreditCardChecker here.
*
* #author Craig Beverley
* #version 03/12/2020
*/
public class CreditCardChecker
{
// Variable for long numbers to be checked
public String longNumber;
public StringBuilder firstFifteen;
/**
* Constructor for objects of class CreditCardChecker
* including long number and first fifteen
*/
public CreditCardChecker(String longNumber)
{
// initialise long number variable
this.longNumber=longNumber;
}
/**
* Sets the value of long number
*/
public void setLongNumber(String aLongNumber)
{
this.longNumber=aLongNumber;
}
/**
* method to get the long number
*/
public String getLongNumber()
{
return this.longNumber;
}
/**
* method to check that long number has exactly 16 digits
*/
public boolean isCorrectLength()
{
if (longNumber.length() == 16)
{
return (true);
}
else
{
return (false);
}
}
/**
* Method to get the first 15 characters of long number
*/
public String firstFifteen(String longNumber)
{
firstFifteen=longNumber.deleteCharAt(16);
}
}```
I'm not entirely sure you need firstFifteen as a field. You can simply grab the first 15 characters
return longNumber.substring(0, 15);
You also don't need a parameter for that method, since longNumber is a field

Java problem - method undefined even though I already defined it in the package

I'm a total beginner in Java and I'm working on an assignment that's largely prefabricated/preformatted code, but I can't get it to work. In Eclipse, I get an error saying "Method cardToString(MyCard) is undefined for the type MyCardTester" before I even run it. I've looked at similar questions on Stackoverflow,
(Eclipse is telling me a method is undefined when it clearly is in fact defined, "The method is not defined for the type" error in simple program in java)
and they have different problems from me. I think that my problem may be with my classpath or run configuration, but those settings seem fine. Here is the code:
Here's the first class:
package EllevensGame;
import EllevensGame.MyCard;
import java.lang.String;
/**
* This is a class that tests the Card class.
*/
public class MyCardTester {
/**
* The main method in this class checks the Card operations for consistency.
* #param args is not used.
*/
public static void main(String[] args) {
MyCard testCard = new MyCard("King", "Hearts", 13);
String printStuff = cardToString(testCard);
System.out.println(printStuff);
}
}
Second class:
package EllevensGame;
/**
* MyCard.java
*
* <code>MyCard</code> represents a playing card.
*/
import java.lang.String;
public class MyCard {
/**
* String value that holds the suit of the card
*/
protected String suit;
/**
* String value that holds the rank of the card
*/
protected String rank;
/**
* int value that holds the point value.
*/
protected int pointValue;
/**
* Creates a new <code>Card</code> instance.
*
* #param cardRank a <code>String</code> value
* containing the rank of the card
* #param cardSuit a <code>String</code> value
* containing the suit of the card
* #param cardPointValue an <code>int</code> value
* containing the point value of the card
*/
public MyCard(String cardRank, String cardSuit, int cardPointValue) {
//MyCard newCard = new MyCard(cardRank, cardSuit, cardPointValue); Not sure if this is right or not
}
/**
* Accesses this <code>Card's</code> suit.
* #return this <code>Card's</code> suit.
*/
public String suit() {
return suit;
}
/**
* Accesses this <code>Card's</code> rank.
* #return this <code>Card's</code> rank.
*/
public String rank() {
return rank;
}
/**
* Accesses this <code>Card's</code> point value.
* #return this <code>Card's</code> point value.
*/
public int pointValue() {
return pointValue;
}
/** Compare this card with the argument.
* #param otherCard the other card to compare to this
* #return true if the rank, suit, and point value of this card
* are equal to those of the argument;
* false otherwise.
*/
public boolean matches(MyCard otherCard) {
if (otherCard.pointValue == (pointValue()) && (otherCard.rank.equals(rank)) && (otherCard.suit.equals(suit))) {
return true;
}
else {return false;}
}
/**
* Converts the rank, suit, and point value into a string in the format
* "[Rank] of [Suit] (point value = [PointValue])".
* This provides a useful way of printing the contents
* of a <code>Deck</code> in an easily readable format or performing
* other similar functions.
*
* #return a <code>String</code> containing the rank, suit,
* and point value of the card.
*/
//#Override
public String cardToString(MyCard newCard) {
String pointstring = String.valueOf(pointValue);
String print = rank + " of " + suit + pointstring;
return print;
}
}
Final note: the code is supposed to create a "card" object for a card game (Ellevens).
Thanks!!
cardToString is a method in MyCard, you must invoke it through the reference. Change
String printStuff = cardToString(testCard);
to
String printStuff = testCard.cardToString(testCard);
Although it might be better to make that method return a String based on the this instance (which would make more sense).
public String cardToString() {
return rank + " of " + suit + pointValue;
}
And then
String printStuff = testCard.cardToString();
I then fixed your constructor
public MyCard(String cardRank, String cardSuit, int cardPointValue) {
this.rank = cardRank;
this.suit = cardSuit;
this.pointValue = cardPointValue;
}
And ran it getting
King of Hearts13

How to implement code before super without creating another method?

So I want to implement a code that would scramble the words!!
It is a homework assignment question.
Although we are not given the liberty of creating another Method in the class, nor are we allowed to create another field in the class. Everything that we want has to be enclosed within the Constructor parameters.
and then send the word as an argument for super(arg);
Although would it not be illegal and an error if I put any code before super???
Note: I also cannot create any variables outside the constructor.
Note2: ScrambledWordPuzzle is a contructor for class ScrambledWordPuzzle that extends another abstract class
Edit 2: Extra Info
Class to make changes:
public class ScrambledWordPuzzle extends AbstractWordPuzzle {
/**
* The solution to the puzzle
*/
private String solution;
/**
* Creates a scrambled word puzzle given the solution word.
*
* #param solutionWord
* the puzzle word
*/
public ScrambledWordPuzzle(String solutionWord) {
// COMPLETE THIS
// Hint: You need to scramble the letters of the solution word
// to generate the puzzle word and then set the puzzle word.
// The easiest way to scramble the letters is to put them
// into a list, use Collections.shuffle, and then convert the
// the shuffled list of letters back into a string.
super();
this.solution = solutionWord;
}
/**
* Get the solution for this reverse word puzzle.
*
* #return the solution for this reverse word puzzle
*/
#Override
public String getSolution() {
// COMPLETE THIS
return this.solution;
}
}
Abstract Class:
public abstract class AbstractWordPuzzle {
/**
* The puzzle word.
*/
private String puzzle;
/**
* Initializes this puzzle to the empty string.
*/
public AbstractWordPuzzle() {
// COMPLETE THIS
this.puzzle="";
}
/**
* Initializes this puzzle to the specified puzzle word.
*
* #param puzzleWord
* the puzzle word
*/
public AbstractWordPuzzle(String puzzleWord) {
// COMPLETE THIS
this.puzzle=puzzleWord;
}
/**
* Get the solution word. For word puzzles with more than one solution this
* method returns the solution that comes first in dictionary order.
*
* #return the solution word that comes first in dictionary order
*/
public abstract String getSolution();
/**
* Get the puzzle word
*
* #return the puzzle word
*/
public final String getPuzzleWord() {
// ALREADY IMPLEMENTED; DO NOT MODIFY
return this.puzzle;
}
/**
* Set the puzzle word for this puzzle.
*
* #param puzzleWord
* the puzzle word
*/
public final void setPuzzleWord(String puzzleWord) {
// COMPLETE THIS
this.puzzle=puzzleWord;
}
}
I need the code before super() because, if it is after the super code, I will not be able to call the variable or whatever it would be in the super(arg).
Ok, so no methods allowed. Then everything should be inline.
public ScrambledWordPuzzle(String solutionWord) {
super(new MyCollection(solutionWord.split("")).shuffle().toString());
}

How to use addAll and retainAll methods in HashSet

When I try to compile I get an error message for my makeUnion method and I'm guessing I will get one for makeIntersection too. I'm not sure why this is, or how to implement makeUnion if I want to add a set interface to the new set. Can someone explain to me what I am doing wrong?
public class Set<T> implements SetInterface<T>
{
private HashSet<T> set;
/**
* Constructs a new empty set.
*/
public Set () {
set = new HashSet <>();
}
/**
* Constructs a new set containing the elements in the specified collection.
* Default load factor of 0.75 and initial capacity of 50.
*
* #param c- the collection whose elements are to be place into this set
*/
public Set(Collection <? extends T> c) {
set = new HashSet<>(Math.max((int) (c.size()/.75f) + 1, 50));
set.addAll(c);
}
/**
* Constructs a new empty set. Default load factor of 0.75.
*
* #param initialCapacity- the initial capacity of the hash table
*/
public Set(int initialCapacity) {
set = new HashSet <>(initialCapacity);
}
/**
* Constructs a new empty set.
* Hashmap has specified initial capacity and specified load factor.
*
* #param initialCapacity- the initial capacity of the hash table
* loadFactor- the load factor of the hash map
*/
public Set(int initialCapacity, float loadFactor) {
set = new HashSet <>(initialCapacity, loadFactor);
}
/**
* Add an item of type T to the interface Duplicate items will not be
* added to the set.
*
* #param itemToAdd - what to add.
*/
public void add(T itemToAdd) {
set.add(itemToAdd);
}
/**
* Removes an item from the set ( if the item is in the set) If the item is not
* in the set this operation does nothing
*
* #param item to remove.
*/
public void remove( T itemToDelete) {
set.remove(itemToDelete);
}
/**
* Return if the SetInterface contains an item
*
* #param itemToCheck. The item you are looking for
* #return true if found. False if not found.
*/
public boolean contains( T itemToCheck) {
return set.contains(itemToCheck);
}
/**
* Make a union of two sets. We add all items in either set to a new set and
* return the new set.
*
* #param the 'other' set to add to our set.
* #return A new set which is the union of the two sets.
*/
public Set<T> makeUnion( SetInterface<T> otherSet) {
return set.addAll(otherSet);
}
/**
* Make an intersection of two sets. We add create a new set which only has
* items in it that are contained in both sets.
*
* #param the 'other' set to intersect with
* #return A new set which is the intersection of the two sets.
*/
public Set<T> makeIntersection( SetInterface<T> otherSet) {
return set.retainAll(otherSet);
}
/**
* Return an iterator for the set. This is used to walk thought all elements
* in the set
*
* #return The iterator
*/
public Iterator<T> getIterator() {
return set.iterator();
}
/**
* Tell the caller how many elements are in the set
*
* #return int with the number of elements
*/
public int size() {
return set.size();
}
}
interface SetInterface<T> {
void add(T itemToAdd);
public void remove( T itemToDelete);
public boolean contains( T itemToCheck);
public Set<T> makeUnion( SetInterface<T> otherSet);
public Iterator<T> getIterator();
public int size();
HashSet<T> getSet();
}
public class Set<T> implements SetInterface<T>
{
private HashSet<T> set;
public HashSet<T> getSet() {
return set;
}
/**
* Constructs a new empty set.
*/
public Set () {
set = new HashSet <>();
}
/**
* Constructs a new set containing the elements in the specified collection.
* Default load factor of 0.75 and initial capacity of 50.
*
* #param c- the collection whose elements are to be place into this set
*/
public Set(Collection <? extends T> c) {
set = new HashSet<>(Math.max((int) (c.size()/.75f) + 1, 50));
set.addAll(c);
}
/**
* Constructs a new empty set. Default load factor of 0.75.
*
* #param initialCapacity- the initial capacity of the hash table
*/
public Set(int initialCapacity) {
set = new HashSet <>(initialCapacity);
}
/**
* Constructs a new empty set.
* Hashmap has specified initial capacity and specified load factor.
*
* #param initialCapacity- the initial capacity of the hash table
* loadFactor- the load factor of the hash map
*/
public Set(int initialCapacity, float loadFactor) {
set = new HashSet <>(initialCapacity, loadFactor);
}
/**
* Add an item of type T to the interface Duplicate items will not be
* added to the set.
*
* #param itemToAdd - what to add.
*/
public void add(T itemToAdd) {
set.add(itemToAdd);
}
/**
* Removes an item from the set ( if the item is in the set) If the item is not
* in the set this operation does nothing
*
* #param item to remove.
*/
public void remove( T itemToDelete) {
set.remove(itemToDelete);
}
/**
* Return if the SetInterface contains an item
*
* #param itemToCheck. The item you are looking for
* #return true if found. False if not found.
*/
public boolean contains( T itemToCheck) {
return set.contains(itemToCheck);
}
/**
* Make a union of two sets. We add all items in either set to a new set and
* return the new set.
*
* #param the 'other' set to add to our set.
* #return A new set which is the union of the two sets.
*/
public Set<T> makeUnion( SetInterface<T> otherSet) {
set.addAll(new java.util.ArrayList<T>(otherSet.getSet()));
return this;
}
/**
* Return an iterator for the set. This is used to walk thought all elements
* in the set
*
* #return The iterator
*/
public Iterator<T> getIterator() {
return set.iterator();
}
/**
* Tell the caller how many elements are in the set
*
* #return int with the number of elements
*/
public int size() {
return set.size();
}
}

How to add a runner to an array of results

I have been trying to figure out how to add runner information into an array of runner information. It should contain at most 100 runners.
This is part of a larger project that must fulfill these requirements:
Operations (methods):
• A constructor that takes in a race name and distance.
• Getters and setters for both the name and distance instance variables.
• Method to return the count of the number of RunnerResult objects added to the array.
• Method to add a RunnerResult to the array (given an instance of Runner and the runner’s finishing time).
• Methods to get a RunnerResult object; one that takes in the position in which the RunnerResult was added (to directly access the object from the array) and one that takes in a runner name (to use to search for the matching runner). The first runner’s index is 0, the second is 1, etc.
• A method with conditional logic to give a count of all runners for a certain category (youth, adult, senior, male, female, all) triggered by a flag passed in as a whole number (1, 2, 3, 4, 5, 6, respectively, implemented as public constants). A similar method provides the average race result (time to finish race) for each potential category.
• A method with conditional logic finds runners with a race time less than the specified minutes per mile. For example, find all runners who finished the race with a time of less than 8 minutes per mile.
• A toString method that simply gives the race name, race distance, a count of total runners in the race, and the average time of all runners in the race.
So far, this is what I have:
public class Race
{
// instance variables
private String name;
private double distance;
private int nextPos;
private RunnerResult [] results;
// public constants
/**
* Flag to signify YOUTH.
*/
public static final int YOUTH = 1;
/**
* Flag to signify ADULT.
*/
public static final int ADULT = 2;
/**
* Flag to signify SENIOR.
*/
public static final int SENIOR = 3;
/**
* Flag to signify MALE.
*/
public static final int MALE = 4;
/**
* Flag to signify FEMALE.
*/
public static final int FEMALE = 5;
/**
* Flag to signify ALL.
*/
public static final int ALL = 6;
/**
* Array limit.
*/
public static final int MAX_COUNT = 100;
/**
* Constructor for objects of class Race.
*
* #param inName the race name.
* #param inDist the distance of the race.
*
*/
public Race(String inName, double inDist)
{
// initialize the instance variables and
// empty array of results, initalize nextPos
this.name = inName;
this.distance = inDist;
RunnerResult[] results = new RunnerResult[100];
}
/**
* Set the race Name.
*
* #param inName the race name.
*
*/
public void setName(String inName)
{
this.name = inName;
}
/**
* Get the race Name.
*
* #return String The race name.
*
*/
public String getName()
{
return this.name;
}
/**
* Set the race distance.
*
* #param inDist the distance of the Race.
*
*/
public void setDist(double inDist)
{
this.distance = inDist;
}
/**
* Get the race distance.
*
* #return double the distance of the race.
*
*/
public double getDist()
{
return this.distance;
}
/**
* Add a runner to the results
* (runners are NOT entered in order of finish).
*
* #param inChip the runner's chip id.
* #param inRunner a Runner object.
* #param inStart the start time for the runner.
* #param inEnd the end time for the runner.
*
*/
public void addRunner(String inChip, Runner inRunner, Time inStart, Time inEnd)
{
if (this.nextPos < MAX_COUNT)
{
// set the instance field element to a "copy" of passed-in object
// add to array, increment counter
for(int i = 0; i < results.length; i++);
{
RunnerResult[] results = { copyinChip, copyinRunner, copyinStart,
copyinEnd };
i++;
}
}
}
}
I just cannot figure out how to get these values into the array. (I get an incompatible type error. Any input would be greatly appreciated.
two things here.
1.) when you re-declare results, you are not referencing the same object that you declare as a field, but an entirely new object that then has no purpose, because it only lives within addRunner.
2.) When you assign results = { ---, ---, ---, ---}; You aren't adding a new runner to the array. Rather, you are reassigning the entire array every single time you do that loop. You would want to create a new RunnerResult object, add the necessary data to it, and then put that at results[];
An example here:
public void addRunner(String inChip, Runner inRunner, Time inStart, Time inEnd)
{
if (this.nextPos < MAX_COUNT)
{
// set the instance field element to a "copy" of passed-in object
// add to array, increment counter
for(int i = 0; i < results.length; i++);
{
results[i] = new RunnerResult(<your params>);
}
}
}

Categories