The goal of the program is to find the prime-numbers below a certain maximum.
the cancelNonPrimes() method acts like it's working (in the step-by-step debugger) but just does not write the false-values to the list...
public class Era2
{
int m;
int i;
boolean[] list;
/**
* Constructor for objects of class Era2
*/
public Era2(int max) {
m = max;
list = new boolean[m];
initialize();
}
/**
* Constructor for objects of class Era2 with standard-maximum-value = 25
*/
public Era2() {
m = 25;
list = new boolean[m];
initialize();
}
/**
* Method for initializing an object: all values to true except 0 and 1
*/
void initialize() {
while (i < m) {
setList(i, true);
i = i + 1;
}
setList(0, false);
setList(1, false);
}
/**
* Method for setting a bool to a number on the list
*/
void setList(int p, boolean b) {
list[p] = b;
}
/**
* Method for reading the entire list, printed in terminal
*/
void getList() {
for (int p = 0; p < m; p++){
if (readList(p) == true){
System.out.println(p + "true");
}
else {
System.out.println(p + "false");
}
}
}
/**
* Method for reading a specific shizl on the list
*/
boolean readList(int p) {
return list[p];
}
/**
* Method for setting all non-primes to false
*/
void cancelNonPrimes() {
i = 2;
while (i < m) {
if (readList(i) == true) {
int c = i;
int n = 2;
while (c < m) {
c = (i * n);
setList(c, false);
n = n + 1;
}
}
i = i + 1;
}
}
}
Related
first excuse me for my English it is not strong.
Yesterday a friend tell me about The Sagrada Familia Magic Square that is conformed by 16 numbers in a 4x4 matrix.
According to the creator "Antoni Gaudi" there are 310 possible combinations of 4 number without getting repeated that sums 33 'age at which Jesus died'.
So, i have created a java program using Depth First Search algorithm "just for practice" but i just get 88 combinations, i would like to know if there is anything wrong with my code or if making 310 combinations is not possible.
PDT:"I have searched on internet if it is not possible to make 310 combinations but without lucky".
The program has three classes Nodo, IA, Pila.
"IA is the main part of the project which centralize everything, Nodo is just a Node and Pila is for Stacking purposes"
First, I have divided the matrix 4x4 Sagrada familia in position and values. Position starts at 0 and ends in 15 and each position has a specific values "wath the hastable on IA"
The program creates every possible combination of positions in a DFS way "combinations of four numbers" and then checks if they sum 33.
the value -1 is a special number that means that this position can take any number.
How does it works - tree ('posx','posy','posw','posz')
-1,-1,-1,-1
0,-1,-1,-1 1,-1,-1,-1 . . .
0,1,-1,-1 0,2,-1,-1 . . . 1,0,-1,-1 1,2,-1,-1 . .
0,1,2,-1 . . . . . . . .
0,1,2,3 . . .
Nodo Class
import java.util.Arrays;
/**
*
* #author Vicar
*/
public class Nodo {
private int posx;
private int posy;
private int posw;
private int posz;
private int valx;
private int valy;
private int valw;
private int valz;
public Nodo (){
posx=-1;
posy=-1;
posw=-1;
posz=-1;
valx=-1;
valy=-1;
valw=-1;
valz=-1;
}
public Nodo (int posx, int posy, int posw, int posz, int valx, int valy, int valw, int valz){
this.posx=posx;
this.posy=posy;
this.posw=posw;
this.posz=posz;
this.valx=valx;
this.valy=valy;
this.valw=valw;
this.valz=valz;
}
//returns the sum
public int sumar (){
return valx+valy+valw+valz;
}
//Returns the position of each value
public String retornarPos(){
return posx+","+posy+","+posw+","+posz;
}
//returns the value
public String retornarVal(){
return valx+","+valy+","+valw+","+valz;
}
//Returns the sorted position of the 4 combinations
public String retornarPosOrdenado(){
int [] arreglo ={posx,posy,posw,posz};
Arrays.sort(arreglo);
return arreglo[0]+","+arreglo[1]+","+arreglo[2]+","+arreglo[3];
}
/**
* #return the posx
*/
public int getPosx() {
return posx;
}
/**
* #param posx the posx to set
*/
public void setPosx(int posx) {
this.posx = posx;
}
/**
* #return the posy
*/
public int getPosy() {
return posy;
}
/**
* #param posy the posy to set
*/
public void setPosy(int posy) {
this.posy = posy;
}
/**
* #return the posw
*/
public int getPosw() {
return posw;
}
/**
* #param posw the posw to set
*/
public void setPosw(int posw) {
this.posw = posw;
}
/**
* #return the posz
*/
public int getPosz() {
return posz;
}
/**
* #param posz the posz to set
*/
public void setPosz(int posz) {
this.posz = posz;
}
/**
* #return the valx
*/
public int getValx() {
return valx;
}
/**
* #param valx the valx to set
*/
public void setValx(int valx) {
this.valx = valx;
}
/**
* #return the valy
*/
public int getValy() {
return valy;
}
/**
* #param valy the valy to set
*/
public void setValy(int valy) {
this.valy = valy;
}
/**
* #return the valw
*/
public int getValw() {
return valw;
}
/**
* #param valw the valw to set
*/
public void setValw(int valw) {
this.valw = valw;
}
/**
* #return the valz
*/
public int getValz() {
return valz;
}
/**
* #param valz the valz to set
*/
public void setValz(int valz) {
this.valz = valz;
}
}
Pila class
import java.util.ArrayList;
import java.util.Stack;
/**
*
* #author Vicar
*/
public class Pila {
private Stack <Nodo> pila;
private ArrayList<String> valor;
public Pila (){
pila = new Stack();
valor = new ArrayList<String>();
}
//add a Node to the stack
public void agregar(Nodo nodo){
pila.push(nodo);
valor.add(nodo.retornarPos());
}
//Pops a node from the stack
public Nodo sacar(){
valor.remove(valor.indexOf(pila.peek().retornarPos()));
return pila.pop();
}
// checks if the stack is empty
public boolean estaVacia(){
return pila.isEmpty();
}
// checks if the stack contains an specific node
public boolean contiene(String busqueda){
return valor.contains(busqueda);
}
}
IA Class
import java.util.*;
/**
*
* #author vicar
*/
public class IA {
Hashtable<Integer,Integer> tabla=new Hashtable<Integer,Integer>();
//add the matrix 4,4 to a hastable (pos,val)
public IA(){
tabla.put(0, 1);
tabla.put(1, 14);
tabla.put(2, 14);
tabla.put(3, 4);
tabla.put(4, 11);
tabla.put(5, 7);
tabla.put(6, 6);
tabla.put(7, 9);
tabla.put(8, 8);
tabla.put(9, 10);
tabla.put(10,10);
tabla.put(11, 5);
tabla.put(12, 13);
tabla.put(13, 2);
tabla.put(14, 3);
tabla.put(15, 15);
}
//DFS
public ArrayList<String> busquedaAProfundidad(){
Pila pila = new Pila();
ArrayList <String> visitados = new ArrayList<String>();
ArrayList <Nodo> hijos = new ArrayList<Nodo>();
ArrayList <String> resultado = new ArrayList<String>();
Nodo nodoRaiz = new Nodo();
pila.agregar(nodoRaiz);
//Chsck if the stack is empty
while(!pila.estaVacia()){
Nodo nodo = pila.sacar();
visitados.add(nodo.retornarPos());
//i get every possible children from the node
hijos=crearHijos(nodo);
for (int i = 0; i < hijos.size(); i++) {
//checks that the node is not visited and the sum results in 33
if(!visitados.contains(hijos.get(i).retornarPos()) && !pila.contiene(hijos.get(i).retornarPos())){
if(hijos.get(i).getPosx()!=-1 && hijos.get(i).getPosy()!=-1 && hijos.get(i).getPosw()!=-1 && hijos.get(i).getPosz()!=-1 && hijos.get(i).sumar()==33 ){
//this is the final result without repeted numbers
if(!resultado.contains(hijos.get(i).retornarPosOrdenado())){
resultado.add(hijos.get(i).retornarPosOrdenado());
}
}
else{
//System.err.println("pos: "+hijos.get(i).retornarPosOrdenado());
pila.agregar(hijos.get(i));
}
}
}
}
return resultado;
}
// method to create children from a father node
public ArrayList<Nodo> crearHijos(Nodo padre){
ArrayList <Nodo> hijos = new ArrayList<Nodo>();
//positions of the father
int x = padre.getPosx();
int y = padre.getPosy();
int w = padre.getPosw();
int z = padre.getPosz();
if (x==-1 && y==-1 && w==-1 && z==-1){
for (int i = 0; i < 16; i++) {
hijos.add(new Nodo(i,-1,-1,-1,tabla.get(i),-1,-1,-1));
}
return hijos;
}
else if(x>=0 && y==-1 && w==-1 && z==-1){
for (int i = 0; i < 16; i++) {
if (x != i){
hijos.add(new Nodo(x,i,-1,-1,tabla.get(x),tabla.get(i),-1,-1));
}
}
}
else if(x>=0 && y>=0 && w==-1 && z==-1){
for (int i = 0; i < 16; i++) {
if (x != i && y != i){
hijos.add(new Nodo(x,y,i,-1,tabla.get(x),tabla.get(y),tabla.get(i),-1));
}
}
}
else if(x>=0 && y>=0 && w>=0 && z==-1){
for (int i = 0; i < 16; i++) {
if (x != i && y != i && w !=i){
hijos.add(new Nodo(x,y,w,i,tabla.get(x),tabla.get(y),tabla.get(w),tabla.get(i)));
}
}
}
return hijos;
}
}
a final class to check the result and send the output to a txt file
import java.util.ArrayList;
import java.io.File;
import java.io.FileWriter;
/**
*
* #author vicar
*/
public class Probador {
public static void main(String[] args) {
IA run = new IA();
ArrayList<String> resultado = run.busquedaAProfundidad();
try {
File archivo = new File("/tmp/gaudi.in");
FileWriter escribir = new FileWriter(archivo, true);
for (String resul : resultado) {
escribir.write(resul+"\n");
}
escribir.close();
}
catch (Exception e) {
System.out.println("Error al escribir");
}
}
}
Thanks!!!
The number 310 refers to the number of combinations of any size taking elements from the matrix (without picking the same cell twice). See https://blog.sagradafamilia.org/en/divulgation/the-magic-square-the-passion-facade-keys-to-understanding-it/
Here are the seventeen possible combinations of three numbers: [...]
With four numbers, there are 88 possible combinations that add up to
33; with five, there are 131; and with six, 66. With seven numbers,
there are eight different combinations:...
17 + 88 + 131 + 66 + 8 = 310
I coded multiple methods which use arrays to determine a certain value but they all result in 0 and I don't know why. The goal is to create a list of textbooks in a library and then return the heaviest book, weight, index, average page count and total page count.
public class Project3Driver {
// Data Fields
public static final int SUBJECTS = 5;
public static final int TEXTBOOKS = 10000;
String[] SUBJECT_LIST = {"Biology", "Calculus", "Linear Algebra", "Geology", "C++"};
Textbook[] library = new Textbook[TEXTBOOKS];
Random rand = new Random();
// Constructor that uses min-max system to randomize page count from 500-1500 and randomizes the subject
public Project3Driver() {
for (int i = 0; i < library.length; i++) {
library[i] = new Textbook(SUBJECT_LIST[rand.nextInt(SUBJECTS)], 500 + (int) (Math.random() * ((1500 - 500) + 1)));
}
}
// Methods
// Finds the heaviest book and returns the weight
public double findHeaviest() {
double heaviestBook = library[0].getWeight();
for (int i = 1; i < library.length; i++) {
if (library[i].getWeight() > heaviestBook) {
heaviestBook = library[i].getWeight();
}
}
return heaviestBook;
}
// Finds the heaviest book and returns the index
public int getHeaviest() {
double heaviestBook = library[0].getWeight();
int index = 0;
for (int i = 1; i < library.length; i++) {
if (library[i].getWeight() > heaviestBook)
{
heaviestBook = library[i].getWeight();
index = i;
}
}
return index;
}
// Returns the average page count of the library
public int computeAverageSize() {
int pageCount = 0;
for (int i = 0; i < library.length; i++)
{
pageCount = pageCount + library[i].getPageCount();
}
pageCount = pageCount / library.length;
return pageCount;
}
// Returns the total page count of the library
public int computeTotalPages()
{
int pageCount = 0;
for (int i = 0; i < library.length; i++)
{
pageCount = pageCount + library[i].getPageCount();
}
return pageCount;
}
// Tests each method and prints it (called in the main function)
public void getLibraryStats()
{
System.out.println("Heaviest book is " + library[getHeaviest()].getSubject());
System.out.println("The heaviest book is " + findHeaviest() + " kg");
System.out.println("The heaviest book is at the index " + getHeaviest());
System.out.println("The average book size is " + computeAverageSize());
System.out.println("There are " + computeTotalPages() + " pages total");
}
}
The getPageCount method simply returns the page count and getWeight returns the weight (by multiplying pageCount * 0.0025)
Any help would be greatly appreciated! I feel like it could be a problem with my arrays but I checked multiple times for errors
EDIT:
public class Textbook {
public static final double PAGE_WEIGHT = 0.0025;
public static final int PAGE_KNOWLEDGE = 5;
private String subject;
private int pageCount;
private int unreadPages;
// Start of Constructors
// Default constructor
public Textbook() {
subject = "Object-Oriented Programming";
pageCount = 800;
unreadPages = pageCount;
}
// Constructor with subject only
public Textbook(String textSubject) {
subject = textSubject;
}
// End subject constructor
// Constructor with subject and page count
public Textbook(String bookSubject, int bookPages) {
subject = bookSubject;
unreadPages = pageCount;
} // End subject and page count constructor
// End of Constructors
// Start of Accessor Methods
// Method to return text subject
public String getSubject() {
return subject;
}
// Method to return page count
public int getPageCount() {
return pageCount;
}
// Method to return unread pages
public int getUnreadPageCount() {
return unreadPages;
}
// Method to get weight
public double getWeight() {
return pageCount * PAGE_WEIGHT;
}
// Method to read the pages
public int readPages(int numPages) {
if (numPages > pageCount) {
numPages = pageCount;
}
int knowledgeGained = 0;
if (unreadPages == 0) {
knowledgeGained = numPages * 5 / 2;
} else if (unreadPages <= numPages) {
knowledgeGained = unreadPages * 5 + (numPages - unreadPages) * 5 / 2;
unreadPages = 0;
} else {
knowledgeGained = numPages * 5;
unreadPages -= numPages;
}
return knowledgeGained;
}
}
public class CSC211Project3
{
public static void main(String[] args)
{
Project3Driver librarytester = new Project3Driver();
librarytester.getLibraryStats();
}
}
Your Textbook constructor doesn't initialize pageCount, so it will default to 0.
To fix it, initialize the field:
public Textbook(String bookSubject, int bookPages) {
subject = bookSubject;
pageCount = bookPages;
unreadPages = bookPages;
}
Try using a system out statement in the for loop to debug or debug with breakpoints.
Debugging with system out,
System.out.println("getting formed book weight "+library[i].getWeight())
There might be something wrong in the logic of the Textbook class constructor
Thank you for everyone who got me on my feet. However, My cutSplice method is inefficient. I need to be able to modify it easy so that i can do the reverse method.
developing a single Java class (LinkedDnaStrand) that uses a linked list of nodes to represent a strand of DNA that supports splicing. Each node in the list will contain a string of one or more nucleotides (A, C, G, or T). The class will be responsible for operations such as append() and cutSplice(), which model real-world restriction enzyme processing.
EX. tt will be replaced with cat. (Better LinkedDnaStrandTester)
package dnasplicing;
public class DnaSequenceNode {
public String dnaSequence;
public DnaSequenceNode previous;
public DnaSequenceNode next;
public DnaSequenceNode(String initialDnaSequence) {
dnaSequence = initialDnaSequence;
}
}
package dnasplicing;
public class LinkedDnaStrand implements DnaStrand {
int nodeCount = 0;
int appendCount = 0;
long nucleotideCount = 0;
String sequenceString;
DnaSequenceNode cursor, head, tail;
public LinkedDnaStrand(String dnaSequence) {
DnaSequenceNode newNode = new DnaSequenceNode(dnaSequence);
head = newNode;
cursor = head;
tail = head;
head.previous = null;
tail.previous = null;
sequenceString = dnaSequence;
nodeCount++;
}
public String toString() {
String result = "";
DnaSequenceNode n = head;
while (n != null) {
result += n.dnaSequence;
n = n.next;
}
return result;
}
#Override
public long getNucleotideCount() {
nucleotideCount = sequenceString.length();
return nucleotideCount;
}
#Override
public void append(String dnaSequence) {
if (dnaSequence != null && dnaSequence.length() > 0) {
tail.next = new DnaSequenceNode(dnaSequence);
tail.next.previous = tail;
tail = tail.next;
sequenceString += dnaSequence;
appendCount++;
nodeCount++;
}
}
#Override
public DnaStrand cutSplice(String enzyme, String splicee) {
boolean frontSplice = false;
boolean backSplice = false;
if (sequenceString.startsWith(enzyme)) {
frontSplice = true;
}
if (sequenceString.endsWith(enzyme)) {
backSplice = true;
}
String[] dnaParts = sequenceString.split(enzyme);
LinkedDnaStrand newLinkedStrand = null;
if (frontSplice == true) {
newLinkedStrand = new LinkedDnaStrand(splicee);
// newLinkedStrand.append(dnaParts[0]);
for (int i = 1; i < dnaParts.length; i++) {
newLinkedStrand.append(dnaParts[i]);
if (i < dnaParts.length - 1) {
newLinkedStrand.append(splicee);
}
}
} else {
newLinkedStrand = new LinkedDnaStrand(dnaParts[0]);
for (int index = 1; index < dnaParts.length; index++) {
newLinkedStrand.append(splicee);
newLinkedStrand.append(dnaParts[index]);
}
}
if (backSplice == true) {
newLinkedStrand.append(splicee);
}
// sequenceString = newLinkedStrand.toString();
return newLinkedStrand;
}
#Override
public DnaStrand createReversedDnaStrand() {
// TODO Auto-generated method stub
return null;
}
#Override
public int getAppendCount() {
// TODO Auto-generated method stub
return appendCount;
}
#Override
public DnaSequenceNode getFirstNode() {
return head;
}
#Override
public int getNodeCount() {
return nodeCount;
}
}
package dnasplicing;
public interface DnaStrand {
/**
* NOTE: Your LinkedDnaStrand class must have a constructor that takes one parameter: String dnaSequence. When the
* constructor completes, your linked list should have just one node, and it should contain the passed-in
* dnaSequence. For example, if the following line of code was executed:
*
* LinkedDnaStrand strand = new LinkedDnaStrand("GATTACA");
*
* Then strand's linked list should look something like (previous pointers not shown):
*
* first -> "GATTACA" -> null
*
* The first line of this constructor should look like:
*
* public LinkedDnaStrand(String dnaSequence) {
*/
/**
* #return The entire DNA sequence represented by this DnaStrand.
*/
public String toString();
/**
* Returns the number of nucleotides in this strand.
*
* #return the number of base-pairs in this strand
*/
public long getNucleotideCount();
/**
* Appends the given dnaSequence on to the end of this DnaStrand. appendCount is incremented. Note: If this
* DnaStrand is empty, append() should just do the same thing as the constructor. In this special case, appendCount
* is not incremented.
*
* #param dnaSequence
* is the DNA string to append
*/
public void append(String dnaSequence);
/**
* This method creates a <bold>new</bold> DnaStrand that is a clone of the current DnaStrand, but with every
* instance of enzyme replaced by splicee. For example, if the LinkedDnaStrand is instantiated with "TTGATCC", and
* cutSplice("GAT", "TTAAGG") is called, then the linked list should become something like (previous pointers not
* shown):
*
* first -> "TT" -> "TTAAGG" -> "CC" -> null
*
* <b>NOTE</b>: This method will only be called when the linke list has just one node, and it will only be called
* once for a DnaStrand. This means that you do not need to worry about searching for enzyme matches across node
* boundaries.
*
* #param enzyme
* is the DNA sequence to search for in this DnaStrand.
*
* #param splicee
* is the DNA sequence to append in place of the enzyme in the returned DnaStrand
*
* #return A <bold>new</bold> strand leaving the original strand unchanged.
*/
public DnaStrand cutSplice(String enzyme, String splicee);
/**
* Returns a <bold>new</bold> DnaStrand that is the reverse of this strand, e.g., if this DnaStrand contains "CGAT",
* then the returned DnaStrand should contain "TAGC".
*
* #return A <bold>new</bold> strand containing a reversed DNA sequence.
*/
public DnaStrand createReversedDnaStrand();
/**
*
* #return The number of times that the DnaStrand has been appended via a call to append() or during the cutSplice()
* operation. Note that the very first time that a DnaStrand is given a DNA sequence is not to be counted as
* an append.
*/
public int getAppendCount();
/**
* This is a utility method that allows the outside world direct access to the nodes in the linked list.
*
* #return The first DnaSequenceNode in the linked list of nodes.
*/
public DnaSequenceNode getFirstNode();
/**
* This is a utility method that allows the outside world to determine the number of nodes in the linked list.
*
* #return
*/
public int getNodeCount();
}
package sbccunittest;
import static java.lang.Math.*;
import static java.lang.System.*;
import static org.apache.commons.lang3.StringUtils.*;
import static org.junit.Assert.*;
import java.io.*;
import org.apache.commons.lang3.*;
import org.junit.*;
import dnasplicing.*;
// Updated 25-Feb-2016 at 6:10pm
public class LinkedDnaStrandTester {
static String ecoliSmall = "AGCTTTTCATTAGCCCGCAGGCAGCCCCACACCCGCCGCCTCCTGCACCGAGAGAGATGGAATAAAGCCCTTGAACCAGC";
static String ecor1 = "GAATTC"; // restriction enzyme
public static int totalScore = 0;
public static int extraCredit = 0;
public static InputStream defaultSystemIn;
public static PrintStream defaultSystemOut;
public static PrintStream defaultSystemErr;
public static String newLine = System.getProperty("line.separator");
public void testCutSplice() {
String enzyme = "GAT";
String splicee = "TTAAGG";
String[] strands = { "TTGATCC", "TCGATCTGATTTCCGATCC", "GATCTGATCTGAT" };
String[][] recombinants = { { "TT", "TTAAGG", "CC" },
{ "TC", "TTAAGG", "CT", "TTAAGG", "TTCC", "TTAAGG", "CC" },
{ "TTAAGG", "CT", "TTAAGG", "CT", "TTAAGG" } };
for (int ndx = 0; ndx < strands.length; ndx++) {
LinkedDnaStrand linkedStrand = new LinkedDnaStrand(strands[ndx]);
DnaStrand newlinkedStrand = linkedStrand.cutSplice(enzyme, splicee);
assertEquals("cutSplice(" + enzyme + ", " + splicee + ") failed at ndx = " + ndx, join(recombinants[ndx]),
newlinkedStrand.toString());
assertEquals("Append counts didn't match for ndx = " + ndx, recombinants[ndx].length - 1,
newlinkedStrand.getAppendCount());
// Verify that each node contains the correct DNA sequence
DnaSequenceNode node = newlinkedStrand.getFirstNode();
for (int nodeNdx = 0; nodeNdx < recombinants.length; nodeNdx++) {
assertNotNull("For strand " + ndx + ", there is no node at position " + nodeNdx, node);
assertEquals("For strand " + ndx + ", the sequences don't match at position " + nodeNdx,
recombinants[ndx][nodeNdx], node.dnaSequence);
node = node.next;
}
}
totalScore += 5;
}
/**
* Verifies that LinkedDnaStrand can model a cut and splice of (part of) the E Coli sequence using the ECoR1
* restriction enzyme and insulin as a splicee.
*/
#Test
public void testSpliceInsulinIntoEcoli() {
for (int testNumber = 1; testNumber <= 5; testNumber++) {
int startNdx = (int) (random() * 0.33 * ecoliSmall.length()); // Somewhere in the
// first third
int endNdx = ecoliSmall.length() - 1 - (int) (random() * 0.33 * ecoliSmall.length());
String ecoliPart = ecoliSmall.substring(startNdx, endNdx);
LinkedDnaStrand linkedStrand = new LinkedDnaStrand(ecoliPart);
SimpleDnaStrand simpleStrand = new SimpleDnaStrand(ecoliPart);
DnaStrand newL = linkedStrand.cutSplice(ecor1, insulin);
DnaStrand newS = simpleStrand.cutSplice(ecor1, insulin);
assertEquals(newS.toString(), newL.toString());
assertEquals(newS.getAppendCount(), newL.getAppendCount());
assertEquals(newS.getAppendCount(), newL.getNodeCount() - 1);
// Verify that the nodes exist
DnaSequenceNode node = newL.getFirstNode();
for (int ndx = 0; ndx < newL.getNodeCount(); ndx++) {
assertNotNull("There is no node at position " + ndx, node);
node = node.next;
}
}
totalScore += 10;
}
/**
* Verifies that LinkedDnaStrand can model a cut and splice efficiently.
*/
#Test
public void testSplicingTime() {
// First verify that the LinkedDnaStrand cutSplice works
int startNdx = (int) (random() * 0.33 * ecoliSmall.length()); // Somewhere in the first
// third
int endNdx = ecoliSmall.length() - 1 - (int) (random() * 0.33 * ecoliSmall.length());
String ecoliPart = ecoliSmall.substring(startNdx, endNdx);
LinkedDnaStrand linkedStrand = new LinkedDnaStrand(ecoliPart);
SimpleDnaStrand simpleStrand = new SimpleDnaStrand(ecoliPart);
String splicee = createRandomDnaSequence(1024 * 1024, 1024 * 1024);
DnaStrand newL = linkedStrand.cutSplice(ecor1, splicee);
DnaStrand newS = simpleStrand.cutSplice(ecor1, splicee);
assertEquals(newS.toString(), newL.toString());
assertEquals(newS.getAppendCount(), newL.getAppendCount());
// Now verify that it can cut and splice N times in less than T seconds
int numSplicings = 200;
double maxTime = 2.0;
double start = nanoTime();
for (int i = 0; i < numSplicings; i++)
newL = linkedStrand.cutSplice(ecor1, splicee);
double end = nanoTime();
double time = ((end - start) / 1e9);
// out.println("Time = " + time);
assertTrue("Time limit of " + maxTime + " seconds exceeded. Time to splice " + numSplicings + " times was "
+ time + " seconds.", time <= maxTime);
totalScore += 5;
}
/**
* Verifies that LinkedDnaStrand can create a new, reversed LinkedDnaStrand.
*/
#Test
public void testReverse() {
String dnaSequence = createRandomDnaSequence(50, 100);
String dnaToAppend = createRandomDnaSequence(5, 10);
int numTimesToAppend = (int) (random() * 10);
LinkedDnaStrand linkedStrand = new LinkedDnaStrand(dnaSequence);
SimpleDnaStrand simpleStrand = new SimpleDnaStrand(dnaSequence);
for (int ndx = 0; ndx < numTimesToAppend; ndx++) {
linkedStrand.append(dnaToAppend);
simpleStrand.append(dnaToAppend);
}
assertEquals(simpleStrand.toString(), linkedStrand.toString());
assertEquals(numTimesToAppend + 1, linkedStrand.getNodeCount());
LinkedDnaStrand rl = (LinkedDnaStrand) linkedStrand.createReversedDnaStrand();
// Verify that the original linked strand wasn't changed
DnaSequenceNode node = linkedStrand.getFirstNode();
int nodeNdx = 0;
while (node != null) {
assertEquals("Sequences don't match at node index " + nodeNdx, nodeNdx == 0 ? dnaSequence : dnaToAppend,
node.dnaSequence);
node = node.next;
nodeNdx++;
}
// Verify that the new strand string is reversed
assertEquals(simpleStrand.createReversedDnaStrand().toString(), rl.toString());
totalScore += 10;
// If the new strand has a reverse order of nodes and sequences within each node, give extra
// credit
int numNodes = linkedStrand.getNodeCount();
if (numNodes == rl.getNodeCount()) {
// Build array of reversed dna strings from original LinkedDnaStrand. Start at end of
// array and move toward
// start
node = linkedStrand.getFirstNode();
String[] reversedDnaSequences = new String[linkedStrand.getNodeCount()];
nodeNdx = numNodes - 1;
while (node != null) {
reversedDnaSequences[nodeNdx] = reverse(node.dnaSequence);
node = node.next;
nodeNdx--;
}
// Verify that the reversed list's nodes contain the same data as in the array
node = rl.getFirstNode();
nodeNdx = 0;
while (node != null) {
if (!node.dnaSequence.equals(reversedDnaSequences[nodeNdx]))
break;
node = node.next;
nodeNdx++;
}
if (nodeNdx == linkedStrand.getNodeCount())
extraCredit += 5;
}
}
private String[] createRandomDnaSequences(int numDnaSequences, int minLength, int maxLength) {
String[] dnaSequences = new String[numDnaSequences];
for (int ndx = 0; ndx < numDnaSequences; ndx++)
dnaSequences[ndx] = createRandomDnaSequence(minLength, maxLength);
return dnaSequences;
}
private String createRandomDnaSequence(int minLength, int maxLength) {
return RandomStringUtils.random((int) (random() * (maxLength - minLength) + minLength), "ACGT");
}
#BeforeClass
public static void beforeTesting() throws Exception {
totalScore = 0;
extraCredit = 0;
}
#AfterClass
public static void afterTesting() {
out.println("Estimated score (w/o late penalties, etc.) = " + totalScore);
out.println("Estimated extra credit (assuming on time submission) = " + extraCredit);
}
#Before
public void setUp() throws Exception {
defaultSystemIn = System.in;
defaultSystemOut = System.out;
defaultSystemErr = System.err;
}
#After
public void tearDown() throws Exception {
System.setIn(defaultSystemIn);
System.setOut(defaultSystemOut);
System.setErr(defaultSystemErr);
}
public void sendToStdinOfTestee(String message) {
System.setIn(new ByteArrayInputStream(message.getBytes()));
}
}
So I don't have some of the classes like the node class you are using so I cannot write the actual code but i will give you some pseudo code.
public String toString(){
String result = "";
Node n = start;
while(n != null){
string += n.data;
}
return result;
}
public long getNucleotideCount() {
long result = 0;
Node n = start;
while(n != null){
result += n.data.length();
}
return result;
}
public void append(String dnaSequence) {
end.next = new Node(dnaSequence);
end = end.next;
appendCount++;
}
public DnaStrand cutSplice(String enzyme, String splice) {
// For this I think it would be best to assemble into string then use replace
Node n = start;
String result = "";
while(n != null){
result += n.data;
}
result = result.replace(enzyme, splice)
return new DnaStrand(result);
}
The reverse method would be similar to cutSplice. Assemble to string, manipulate, then return new strand. If you need more help LMK.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication7.ai;
import javaapplication7.model.Move;
import javaapplication7.model.TicTacToeGame;
/**
*
* #author Harshal
*/
public class NegaScout extends Strategy{
#Override
public Move makeMove(TicTacToeGame game) {
System.out.println("Negascout");
Move move = game.getAvaiableMoves().get(0);
int best = Integer.MIN_VALUE;
for(int i=0; i<game.getAvaiableMoves().size(); i++){
System.out.print(game.getAvaiableMoves().get(i) + ",");
}
System.out.println();
for (int i = 0; i < game.getAvaiableMoves().size(); i++) {
//int result = negaMax(game);
//TicTacToeGame tmp = game.clone();
//tmp.playMove(game.getAvaiableMoves().get(i));
int result = negaScout(game, Integer.MIN_VALUE, Integer.MAX_VALUE);
//System.out.println("for i = " + i + " : " + game.getAvaiableMoves().get(i) + " result : " + result);
System.out.printf("%d %d\n",best,result);
if (result > best) {
move = game.getAvaiableMoves().get(i);
best = result;
}
}
System.out.println();
return move;
}
private int negaScout(TicTacToeGame game, int a, int b){
if (Move.isWon(game.getCurrentPlayer().getMoves())) {
return 1;
}
if (Move.isWon(game.getNonCurrentPlayer().getMoves())) {
return -1;
}
//int score;
int score = Integer.MIN_VALUE;
for (int i = 0; i < game.getAvaiableMoves().size(); i++) {
//Move move = game.getAvaiableMoves().get(i);
//TicTacToeGame tmp = game.clone();
Move move = game.getAvaiableMoves().get(i);
TicTacToeGame tmp = game.clone();
tmp.switchPlayers();
tmp.playMove(move);
if(i==0){
score = -negaScout(tmp,-b,-a);
}else{
score = -negaScout(tmp, ((-a)-1), -a);
if(a<score && score<b)
score = -negaScout(tmp, -b, -score);
}
a = Math.max(a,score);
if(a >= b){
break;
}
}
return a;
}
}
I am trying to implement negascout for tic-tac-toe, but the alglorithm doesn't do anything.
It only chooses the first move in the set of available moves.
It returns values but i couldn't trace them.
Some help will be appreciated.
I'm trying to make a 2d array of an object in java. This object in java has several private variables and methods in it, but won't work. Can someone tell me why and is there a way I can fix this?
This is the exeception I keep getting for each line of code where I try to initialize and iterate through my 2d object.
"Exception in thread "main" java.lang.NullPointerException
at wumpusworld.WumpusWorldGame.main(WumpusWorldGame.java:50)
Java Result: 1"
Here is my main class:
public class WumpusWorldGame {
class Agent {
private boolean safe;
private boolean stench;
private boolean breeze;
public Agent() {
safe = false;
stench = false;
breeze = false;
}
}
/**
* #param args
* the command line arguments
* #throws java.lang.Exception
*/
public static void main(String [] args) {
// WumpusFrame blah =new WumpusFrame();
// blah.setVisible(true);
Scanner input = new Scanner(System.in);
int agentpts = 0;
System.out.println("Welcome to Wumpus World!\n ******************************************** \n");
//ArrayList<ArrayList<WumpusWorld>> woah = new ArrayList<ArrayList<WumpusWorld>>();
for (int i = 0 ; i < 5 ; i++) {
WumpusWorldObject [] [] woah = new WumpusWorldObject [5] [5];
System.out.println( "*********************************\n Please enter the exact coordinates of the wumpus (r and c).");
int wumpusR = input.nextInt();
int wumpusC = input.nextInt();
woah[wumpusR][wumpusC].setPoints(-3000);
woah[wumpusR][wumpusC].setWumpus();
if ((wumpusR <= 5 || wumpusC <= 5) && (wumpusR >= 0 || wumpusC >= 0)) {
woah[wumpusR][wumpusC].setStench();
}
if (wumpusC != 0) {
woah[wumpusR][wumpusC - 1].getStench();
}
if (wumpusR != 0) {
woah[wumpusR - 1][wumpusC].setStench();
}
if (wumpusC != 4) {
woah[wumpusR][wumpusC + 1].setStench();
}
if (wumpusR != 4) {
woah[wumpusR + 1][wumpusC].setStench();
}
System.out.println( "**************************************\n Please enter the exact coordinates of the Gold(r and c).");
int goldR = input.nextInt();
int goldC = input.nextInt();
woah[goldR][goldC].setGold();
System.out.println("***************************************\n How many pits would you like in your wumpus world?");
int numPits = input.nextInt();
for (int k = 0 ; k < numPits ; k++) {
System.out.println("Enter the row location of the pit");
int r = input.nextInt();
System.out.println("Enter the column location of the pit");
int c = input.nextInt();
woah[r][c].setPit();
if ((r <= 4 || c <= 4) && (r >= 0 || c >= 0)) {
woah[r][c].setBreeze();
}
if (c != 0) {
woah[r][c - 1].setBreeze();
}
if (r != 0) {
woah[r - 1][c].setBreeze();
}
if (c != 4) {
woah[r][c + 1].setBreeze();
}
if (r != 4) {
woah[r + 1][c].setBreeze();
}
}
for (int x = 0 ; x < 4 ; x++) {
int j = 0;
while (j < 4) {
agentpts = agentpts + woah[x][j].getPoints();
Agent [] [] k = new Agent [4] [4];
if (woah[x][j].getWumpus() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("You just got ate by the wumpus!!! THE HORROR!! Your score is " + agentpts);
}
if (woah[x][j].getStench() == true) {
k[x][j].stench = true;
System.out.println("You smell something funny... smells like old person.");
}
if (woah[x][j].getBreeze() == true) {
k[x][j].breeze = true;
System.out.println("You hear a breeze. yeah");
}
if (woah[x][j].getPit() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH! you dumb bith, your dead now.");
}
// if breeze or stench, if breeze and stench, if nothing, etc then move.
k[x][j].safe = true;
// if(k[i][j].isSafe()!=true){
// } else { }
}
}
}
}
}
Here is my class object that I'm trying to implement:
package wumpusworld;
/**
*
* #author Jacob
*/
public class WumpusWorldObject {
private boolean stench;
private boolean breeze;
private boolean pit;
private boolean wumpus;
private boolean gold;
private int points;
private boolean safe;
public WumpusWorldObject(){
}
public boolean getPit() {
return pit;
}
public void setPit() {
this.pit = true;
}
public boolean getWumpus() {
return wumpus;
}
public void setWumpus() {
this.wumpus = true;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public boolean getStench() {
return stench;
}
public void setStench() {
this.stench = true;
}
public boolean getBreeze() {
return breeze;
}
public void setBreeze() {
this.breeze = true;
}
public boolean getSafe() {
return safe;
}
public void setSafe() {
this.safe = true;
}
public void setGold(){
this.gold=true;
}
}
Creating array doesn't mean it will be automatically filled with new instances of your class. There are many reasons for that, like
which constructor should be used
what data should be passed to this constructor.
This kind of decisions shouldn't be made by compiler, but by programmer, so you need to invoke constructor explicitly.
After creating array iterate over it and fill it with new instances of your class.
for (int i=0; i<yourArray.length; i++)
for (int j=0; j<yourArray[i].length; j++)
yourArray[i][j] = new ...//here you should use constructor
AClass[][] obj = new AClass[50][50];
is not enough, you have to create instances of them like
obj[i][j] = new AClass(...);
In your code the line
woah[wumpusR][wumpusC].setPoints(-3000);
must be after
woah[wumpusR][wumpusC] = new WumpusWorldObject();
.