Arrary list while creating a buildin - java

package uk.ac.reading.Nischal.buidlingconsole;
import java.util.ArrayList;
public class Building {
private int xSize = 10; // size of building in x
private int ySize = 10; // and y
private static String test;
StringSplitter bigBox;
private static ArrayList<Room> allRooms; // array of rooms
public Building(String build) {
setBuilding(build);
}
public void setBuilding(String bS) {
// allRooms.clear();
allRooms= new ArrayList<Room>();
bigBox = new StringSplitter(bS, ";");
String first = (bigBox.getNth(0, ""));
StringSplitter sizeXY = new StringSplitter(first, " ");
xSize = Integer.parseInt(sizeXY.getNth(0, ""));
ySize = Integer.parseInt(sizeXY.getNth(1, ""));
//test = bigBox.getNth(3, "");
for(int i = 0; i < bigBox.numElement(); i++){
String r = (bigBox.getNth(i, ""));
allRooms.add(new Room(r));
}
}
public String toString(){
String res = "Building size " + xSize + "," + ySize + "\n" ;
String s = "";
for (Room r : allRooms)
s = s + r.toString() + "\n";
return res + s;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Building b = new Building("11 11;0 0 5 5 3 5;6 0 10 10 6 6;0 5 5 10 2 5"); // create
System.out.println(b.toString());
System.out.println(test);
}
}
i'm trying to create a building by passing a string of the form,
11 11;0 0 5 5 3 5;6 0 10 10 6 6;0 5 5 10 2 5 but i'm getting unknown errors
i'm told I have to use array list and here I've tried to do so yet I get weird errors.

I hope i'm getting this right, that this StringSplitter does nearly the same like the split-method from String.
Due the condition, that the 0th-Element of the bigBox, contains the xSize and ySize, i think your loop should start with 1 and not with 0.
for(int i = 1; i < bigBox.numElement(); i++){
String r = (bigBox.getNth(i, ""));
allRooms.add(new Room(r));
}
It would be helpful if you can show as the error-logs.

Related

Running my world generation code ends up in 2 or more ArrayIndexOutOfBoundsExceptions

So I'm coding my text-based game with world generation and my friend coded the world generation. He's away right now so I have to ask this.
The code should generate an array with the X and Y positions of chests that spawn in random positions. The packages used are: java.util.Scanner,
java.util.Arrays,
java.util.Random,
Class is declared but I'm not including it in this snippet.
The Code for the method worldgen():
static double[] worldgen() {
//coded by *my friend, name censored*
int random_int_1 = 0;
int random_int_2 = 0;
int x;
int y;
int chest_x;
int chest_y;
double[] chest_x_values;
double[] chest_y_values;
int mineral_x;
int mineral_y;
// chest_x_and_y_values[something (or else)] = chest_x_values[something];
// chest_x_and_y_values[something else] = chest_y_values[something];
Random rand1 = new Random();
int num_of_chests = rand1.nextInt(100);
chest_x_values = new double[num_of_chests];
chest_y_values = new double[num_of_chests];
while (random_int_1 <= num_of_chests)
{
Random rand2 = new Random();
chest_x = rand2.nextInt(301);
System.out.println(chest_x);
chest_x_values[random_int_1] = chest_x;
System.out.println(Arrays.toString(chest_x_values));
if(random_int_1 <= num_of_chests) {
random_int_1++;
System.out.println(random_int_1);
}
}
while (random_int_2 <= num_of_chests)
{
Random rand3 = new Random();
chest_y = rand3.nextInt(301);
chest_y_values[random_int_2] = chest_y;
random_int_2 = random_int_2 + 1;
}
int random_int_3 = num_of_chests;
random_int_1 = 0;
random_int_2 = 0;
double[] chest_x_and_y_values = new double[random_int_3 = random_int_3*2+1];
while (random_int_1 <= random_int_3) {
chest_x_and_y_values[random_int_1] = chest_x_values[random_int_1];
random_int_1 = random_int_1 + 1;
}
chest_x_and_y_values[random_int_1+1] = -1;
while (random_int_2 <= random_int_3) {
chest_x_and_y_values[random_int_1 + 1 + random_int_2] = chest_y_values[random_int_2];
random_int_2 = random_int_2 + 1;
}
return chest_x_and_y_values;
}
public static void main(String[] args) {
//coded by EnZon3
Scanner uIn = new Scanner(System.in);
System.out.println("-------------------------------");
System.out.println(" *game name censored* ");
System.out.println(" 1: Generate new world.. ");
System.out.println(" 2: Generate w/ custom seed.. ");
System.out.println(" 3: See world data ");
System.out.println(" 4: Exit ");
System.out.println("-------------------------------");
int option = uIn.nextInt();
if (option > 4) {
System.err.println("Error 0x1: Not an option");
}
while (option != 4) {
if (option == 1) {
double[] world = worldgen();
System.out.println(Arrays.toString(world));
}
}
}
The error I get is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 77 out of bounds for length 77 at
.worldgen(.java:35) at .main(.java:86)
I've tried tweaking the values but that didn't work
while (random_int_1 <= num_of_chests)
This should be < (strictly less than), remember arrays are 0 indexed.
while (random_int_2 <= num_of_chests)
Same thing here
while (random_int_1 <= random_int_3) {
chest_x_and_y_values[random_int_1] = chest_x_values[random_int_1];
random_int_1 = random_int_1 + 1;
}
random_int_3 is 2 * num_of_chests +1, and chest_x_values is a list of length num_of_chests. In this part, random_int_1 can go all the way up to 2 * num_of_chests +1 which is higher than chest_x_values.

I want to know why the program worked in eclipse but was not able to submit in Codejam

I tried to attend in google code jam and in qualification round when I submit it I got WA(Wrong Answer). When it worked fine in my eclipse can I know the problem with my code so I can fix my code. I also got the correct output when I tried to test my program with sample input and output.
Input
4
3
360 480
420 540
600 660
3
0 1440
1 3
2 4
5
99 150
1 100
100 301
2 5
150 250
2
0 720
720 1440
Output
Case #1: CJC
Case #2: IMPOSSIBLE
Case #3: JCCJJ
Case #4: CC
import java.util.Scanner;
public class Solution {
public static void main(String args[]) {
int T=0;
Scanner a = new Scanner(System.in);
T = a.nextInt();
int cases=0;
String work[][] = new String[T][1000];
String data[] = new String[T];
while(T>cases) {
//System.out.println("cases: "+cases);//debug
int N=a.nextInt();
int J[][] = new int[N][2];
int C[][] = new int[N][2];
for(int i=0;i<N;i++) {
//System.out.println("For : i"+ i);//debug
int Si = a.nextInt();
int Ei = a.nextInt();
boolean check = true;
boolean check1 =true;
for(int k=0;k<i;k++) {
if(Si>=J[k][0]&&Si<J[k][1]) {
check=false;
}
if(Ei>J[k][0]&&Ei<=J[k][1]) {
check=false;
}
if(Si>=C[k][0]&&Si<C[k][1]) {
check1=false;
}
if(Ei>C[k][0]&&Ei<=C[k][1]) {
check1=false;
}
}
if(check) {
//System.out.println("Upgrade1");
J[i][0] = Si;
J[i][1] = Ei;
work[cases][i] = "J";
}else if(check1) {
//System.out.println("Upgrade2");
C[i][0] = Si;
C[i][1] = Ei;
work[cases][i] = "C";
}else
work[cases][i]= "I";
}
for(int k=0;k<N;k++) {
//System.out.println("N: "+ N);
if(k==0)
data[cases] = work[cases][k];
else
data[cases]+=work[cases][k];
}
cases++;
}
for(int k=0;k<T;k++) {
if(data[k].contains("I")) {
data[k]="Impossible";
}
}
for(int i=0;i<T;i++) {
//System.out.println("Printing");
System.out.println("Case #" + (i+1) + ": "+ data[i]);
}
}
}

Java NameLengthNotValidException always gets thrown in domainclass

IMPORTANT: Probably a rookie question, but I'm clueless on how to solve it.
I have a UI class which I use to input a name and gender (geslacht) using a scanner (see code below)
private static void geefNaamEnGeslacht(int aantal) {
String naam, geslacht;
for (int i = 0; i < aantal; i++) {
System.out.print("Wat is de naam van speler " + (i + 1) + " (min 6 tekens, max 12 tekens)? ");
naam = sc.next();
naam += sc.nextLine();
System.out.print("Wat is het geslacht van speler " + (i + 1) + "(man=m vrouw=v)? ");
geslacht = sc.next();
System.out.println(naam.length());
try {
dc.maakSpelerAan(naam, geslacht.charAt(0));
} catch (NameLengthNotValidException e) {
System.out.println(e.getMessage());
i--;
}
}
}
In my domain class I check the length of that name in the setter, but it always throws the exception, no matter what I tried. When debugging, the length of any name I picked checks out to be between 6 and 12 characters strangely enough. (see code below)
public final void setNaam(String naam) {
int lengte = naam.length();
if (naam.length() < 6 || naam.length() > 12) {
throw new NameLengthNotValidException("Je naam moet tussen 6 en 12 tekens liggen!");
}
this.naam = naam;
}
Any ideas or tips are apreciated.
EDIT1 code of dc.maakSpelerAan
public void maakSpelerAan(String naam, char geslacht){
s.maakSpeler(naam, geslacht);
}
EDIT2 code of s.maakspeler
public void maakSpeler(String naam, char geslacht){
if (spelCompleet()) {
throw new ListFilledException("De lijst met spelers is vol !");
}
if (!controleerUniekeNaam(naam)) {
throw new NotUniqueNameException();
}
Kaart[] schatkaarten = new Kaart[STARTAANTAL];
Kaart[] kerkerkaarten = new Kaart[STARTAANTAL];
for (int i = 0; i > STARTAANTAL; i++) {
schatkaarten[i] = stapels.get(SCHATKAART).geefBovensteKaart();
kerkerkaarten[i] = stapels.get(KERKERKAART).geefBovensteKaart();
}
try{
Speler s = new Speler(naam, geslacht);
s.getKaarten(kerkerkaarten, schatkaarten);
spelers.add(s);
}catch (IllegalArgumentException | NameLengthNotValidException e){
throw e;
}
if (spelCompleet()) {
//UC2
spelers.get(EERSTESPELERINDEX).setBeurt(true);
}
}
EDIT3 REPOST WITH CORRECT IMAGE Image of variable "naam" right before it goes in the IF loop while debugging. MINLENGTHNAAM and MAXLENGTHNAAM are set to 6 and 12 respectively in an interface class.
EDIT4 Code in my interface class for MINLENGTH AND MAXLENGTH
public interface SpelInfo {
final int STARTAANTAL = 2;
final int MAXAANTALPUNTEN = 10;
final int INDEXNAAMDETAILS = 0;
final int INDEXGESLACHTDETAILS = 1;
final int INDEXPUNTENDETAILS = 2;
final int MINAANTALSPELERS = 3;
final int MAXAANTALSPELERS= 6;
final int EERSTESPELERINDEX = 0;
final int MAXLENGTHNAAM = 6;
final int MINLENGTHNAAM = 12;
final int AANTALSTAPELS = 2;
final char MAN = 'm';
final char VROUW = 'v';
final int SCHATKAART = 0;
final int KERKERKAART = 1;
}
In "Edit4" you need to change the green line into:
if(naam.length() > MAXLENGTHNAAM || naam.length() < MINLENGTHNAAM) {
Just a little logical issue :)

How to declare the size of x and y - java

so for an assignment I've had to create a building class i was given the bare bones of the code and I've got this far the part I'm struggling on is setting the size of the x and y coordinate which needs to be in setBuilding().
This is the desired output of the class:
Building size 11×11
Room from (0,0) to (5, 5) door at (3, 5)
Room from (6,0) to (10, 10) door at (6, 6)
Room from (0,5) to (5, 10) door at (2, 5)
The program displays everything apart from the "Building size 11×11", I'm not looking for someone to do the work for me just want to be pointed in the right direction.
Thanks for any help
import java.util.*;
public class Building {
private int xSize = 10; // size of building in x
private int ySize = 10; // and y
private ArrayList<Room> allRooms; // array of rooms
Building (String first) {
allRooms = new ArrayList<Room>();
setBuilding(first);
}
public void setBuilding(String bS) {
String[] Space;
allRooms.clear();
Space = bS.split(";");
allRooms.add(new Room(Space[1]));
allRooms.add(new Room(Space[2]));
allRooms.add(new Room(Space[3]));
}
public String toString() {
String s;
s = " ";
for (Room r : allRooms) {
s = s + r.toString();
}
return s;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Buidling test\n");
Building b = new Building("11 11;0 0 5 5 3 5;6 0 10 10 6 6;0 5 5 10 2 5"); // Create
System.out.println("built building\n");
System.out.println(b.toString()); // And print
}
}
you didn't add any declaration to your toString for showing the building dimensions. I assume you want to use the xSize and ySize of the building. Also note that you're not extracting the building dimensions from the buidlString you pass to setBuilding.
Change your toString to the code below.
public String toString() {
String s = "Building size" + xSize + ", " + ySize;
for (Room r : allRooms) {
s += r.toString();
}
return s;
}
for defining your building size:
public void setBuilding(String bS) {
String[] Space;
allRooms.clear();
Space = bS.split(";");
//Here we'll update the requested building size
String[] buildingSize = Space[0].split(" "); //split the two integers
xSize = Integer.ParseInt(buildingSize[0]); //transform the string to int
ySize = Integer.ParseInt(buildingSize[1]); //transform the string to int
allRooms.add(new Room(Space[1]));
allRooms.add(new Room(Space[2]));
allRooms.add(new Room(Space[3]));
}

Extracting Polynomial Coefficients From input String in JAVA

I made this code for extracting Polynomial coefficients and also evaluating equation in a point,and it is work.
but i want to modify that so the user can enter any shape of polynomial equation.
in my code you have to enter equation like this:
2*x^2+3*x^1+4
but i want :
2*x^5+1*x+6
also if there any term with same power , their coeffs must be added together.
Here is my code in java:
package Priest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class Equation {
private String Eq;
private final String[] C;
private int Deg;
private final String EqHolder;
public Equation(String Equation) {
this.Eq = Equation;
EqHolder = Equation;
Eq = Eq.replaceAll("[^0-9\\-\\.]+", " ");
Eq = Eq.replaceAll("-", " -");
this.C = Eq.split(" ");
}
public String SourceEquation() {
return EqHolder.toUpperCase().replaceAll("\\*", "").replaceAll("[a-zA-Z]", "\\*(X)").replaceAll("\\+", "\\ + ").replaceAll("\\-", "\\ - ");
}
public List<BigDecimal> CaptureCoeff() {
getDegree();
List<BigDecimal> Temp = new ArrayList<>();
for (String S : C) {
Temp.add(new BigDecimal(S));
}
int Location = Temp.indexOf(BigDecimal.valueOf(Deg));
List<BigDecimal> Coeffs = new ArrayList<>();
for (int Counter = Location - 1; Counter < Temp.size(); Counter += 2) {
Coeffs.add(Temp.get(Counter));
}
return Coeffs;
}
public int getDegree() {
int Degree = 0;
for (int Counter = 0; Counter < C.length; Counter += 2) {
if ((new Double(C[Counter])) != 0) {
Degree = new Integer(C[Counter + 1]);
this.Deg = Degree;
break;
}
}
return Degree;
}
public BigDecimal Evaluate(List<BigDecimal> Coefficients, double EvalPoint) {
BigDecimal Output = BigDecimal.ZERO;
for (int Index = 0; Index < Coefficients.size(); Index++) {
Output = Output.add(Coefficients.get(Index).multiply(BigDecimal.valueOf(EvalPoint).pow(Deg--)));
}
return Output;
}
}
and main class:
package Priest;
import java.math.RoundingMode;
public class MainClass {
public static void main(String[] args) {
long Start = System.nanoTime();
String Str = "3.1415x^5-12.6x^4+6x^3+12*x^2-6*x^1-0";
Equation E = new Equation(Str);
System.out.println("Equation is: " + E.SourceEquation());
System.out.println("Coefficients :" + E.CaptureCoeff());
System.out.println("Polynomial Degree: " + E.getDegree());
double Target = 47.784;
System.out.println("Equation # (X:" + Target + ")= " + E.Evaluate(E.CaptureCoeff(), Target).setScale(15, RoundingMode.HALF_UP));
System.out.println("Elapsed Time: " + String.format("%.20G", (System.nanoTime() - Start) / 1.0e6) + " ms.");
}
}
the output:
run:
Equation is: 3.1415*(X)^5 - 12.6*(X)^4 + 6*(X)^3 + 12*(X)^2 - 6*(X)^1 - 0
Coefficients :[3.1415, -12.6, 6, 12, -6, 0]
Polynomial Degree: 5
Equation # (X:47.784)= 717609084.382589022327914
Elapsed Time: 32.306242000000000000 ms.
BUILD SUCCESSFUL (total time: 0 seconds)
Let's go with the following equation String Str2 = "3.1415x^5+6x^2+12*x-5";
Here is the code that I have added upon your code in order to preprocess this equation and made it compatible to your actual logic so that It will treat it without any major change to your code.
To be totally accurate I had to change the following in your equation class:
public List<BigDecimal> CaptureCoeff() {
getDegree();
List<BigDecimal> Temp = new ArrayList<BigDecimal>();
for (String S : C) {
if (! "".equals(S.trim())) {
Temp.add(new BigDecimal(S));
}
}
So I have added the control to check that none of these S strings is trim - empty.
Here is my preprocessing code.
I have added a method called powerSplitt that allows to splitt the equation on the basis of the '^' char.
Then I created another method called generateNullCoeffPolynomeWithDegree that generate a monome in the form 0*X^k. And a similar one that generate all the similar intermediate monomes between the greater power and the lesser power
Example:
String str3 = generateAllNullCoeffPolynomesWithDegreeExclusiveBetween(5, 2);
System.out.println("all poly = " + str3);
will generate: all poly = 0*x^4+0*x^3
Then I created a buildPreProcessedPolynome that takes the initial equation and pre process it to produce one with the null monomes inside of it. And then I just gave it to your equation program and it could process it fine!!!
Here is the code and a call example all done in the MainClass
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
public class MainClass {
private static List<String> workList = new ArrayList<String>();
public static void powerSplitt(String equationText) {
char[] charsList = equationText.toCharArray();
boolean foundTargetChar = false;
int index = 0;
for (int i = 0; i < charsList.length; i++) {
index = i;
if (charsList[i] == '^') {
foundTargetChar = true;
break;
}
}
if (foundTargetChar) {
workList.add(equationText.substring(0, index));
if (index +1 < equationText.length()) {
powerSplitt(equationText.substring(index+1));
} else {
workList.add(equationText);
return;
}
} else {
workList.add(equationText);
}
}
public static String generateNullCoeffPolynomeWithDegree(int degree) {
return "0*x^" + degree;
}
public static String generateAllNullCoeffPolynomesWithDegreeExclusiveBetween(int startDegree, int endDegree) {
if (startDegree-endDegree <= 1) {
return "";
}
int index = 0;
StringBuilder builder = new StringBuilder();
for (int i = startDegree -1; i > endDegree; i--) {
if (index > 0) {
builder.append("+");
}
builder.append(generateNullCoeffPolynomeWithDegree(i));
index++;
}
return builder.toString();
}
public static String buildPreProcessedPolynome(String initialEquationText) {
workList.clear();
powerSplitt(initialEquationText);
StringBuilder resultBuilder = new StringBuilder();
assert workList.size() >= 3;
resultBuilder.append(workList.get(0));
for (int i = 1; i <= workList.size()-2; i++) {
int actualPower = Integer.parseInt( workList.get(i).substring(0,1));
int nextFoundPower = Integer.parseInt( workList.get(i+1).substring(0,1));
System.out.print("actual power = " + actualPower + " and next power = " + nextFoundPower);
System.out.println();
String additionalPolyParts = generateAllNullCoeffPolynomesWithDegreeExclusiveBetween(actualPower, nextFoundPower);
resultBuilder.append("^" + actualPower);
resultBuilder.append("+");
resultBuilder.append(additionalPolyParts);
resultBuilder.append(workList.get(i).substring(1));
}
resultBuilder.append("^" + workList.get(workList.size()-1));
return resultBuilder.toString();
}
public static void main(String[] args) {
workList.clear();
String Str2 = "3.1415x^5+6x^2+12*x-5";
powerSplitt(Str2);
for (String part: workList) {
System.out.println("PART:" + part);
}
System.out.println("-----------------");
long Start = System.nanoTime();
String str3 = generateAllNullCoeffPolynomesWithDegreeExclusiveBetween(5, 2);
System.out.println("all poly = " + str3);
String preprocessed = buildPreProcessedPolynome(Str2);
System.out.println("preprocessed = " + preprocessed);
System.out.println();
Equation E = new Equation(preprocessed);
System.out.println("Equation is: " + E.SourceEquation());
System.out.println("Coefficients :" + E.CaptureCoeff());
System.out.println("Polynomial Degree: " + E.getDegree());
double Target = 47.784;
System.out.println("Equation # (X:" + Target + ")= " + E.Evaluate(E.CaptureCoeff(), Target).setScale(15, RoundingMode.HALF_UP));
System.out.println("Elapsed Time: " + String.format("%.20G", (System.nanoTime() - Start) / 1.0e6) + " ms.");
}
}
And here is the produced results (I haved added some System.out.println to check the results of my methods calls. I just noticed I have to take into account the last constant as a monome of type K*X^0, but I will leave that to you):
PART:3.1415x
PART:5+6x
PART:2+12*x-5
all poly = 0*x^4+0*x^3
actual power = 5 and next power = 2
preprocessed = 3.1415x^5+0*x^4+0*x^3+6x^2+12*x-5
Equation is: 3.1415*(X)^5 + 0*(X)^4 + 0*(X)^3 + 6*(X)^2 + 12*(X) - 5
Coefficients :[3.1415, 0, 0, 6, 12]
Polynomial Degree: 5
Equation # (X:47.784)= 782631805.485054892561514
Elapsed Time: 18,441978000000000000 ms.

Categories

Resources