The program won't print smallest area and perimeter in the figure - java

I'm trying to print the smallest area and perimeter but all that comes out of the output the the perimeter and area for the circle class. Here is my main method (the for loops are all the way at the bottom):
public static void main (String [] args)//print Figure(Figure[])
{
System.out.println("TESTING FIGURES");
System.out.println("===============\n\n\n");
// form an array of figures
System.out.println("We form an array of 4 figures");
Figure[] set1 = new Figure[4];
set1[0] = new Circle(10);
set1[1] = new Triangle(10, 6, 8);
try
{
set1[2] = new Triangle(5, 12, 7);
}
catch (IllegalArgumentException e)
{
System.out.println("We try to form an illegal triangle");
}
set1[2] = new Parallelogram(10, 20, Math.PI / 3);
set1[3] = new Square(6);
System.out.println("The array is ");
printArray(set1);
// find the figures with the largest area, largest perimeter,
// smallest area, smallest perimeter
Figure smallArea = getSmallestArea(set1);
Figure bigArea = getLargestArea(set1);
Figure smallPerimeter = getSmallestPerimeter(set1);
Figure bigPerimeter = getLargestPerimeter(set1);
// print these figures
System.out.print("\nThe figure with a largest perimeter is ");
printFig(bigPerimeter);
System.out.print("\nThe figure with a smallest perimeter is ");
printFig(smallPerimeter);
System.out.print("\nThe figure with a largest area is ");
printFig(bigArea);
System.out.print("\nThe figure with a smallest area is ");
printFig(smallArea);
}
// print an array of figures
// if the array is null or empty print the message "The array is empty"
// otherwise print 2 lines
// that displays the shape, the fields, the perimeter and the area
// of each item in the array
public static void printArray(Figure[] figs)
{
if(figs == null || figs.length == 0)
{
System.out.println("The array is empty");
}
else
for(int i = 0; i < figs.length; i++)
{
printFig(figs[i]);
}
}
// print the shape, the fields, the perimeter and the area
// of fig
// if fig = null, write null
public static void printFig(Figure fig)
{
if(fig == null)
System.out.println("null");
else
{
if( fig instanceof Circle)
{
System.out.print("a circle of ");
System.out.println( "radius = " + ((Circle)fig).getRadius() );
}
else if (fig instanceof Triangle)
{
System.out.print("a triangle with ");
System.out.println("sides " + ((Triangle)fig).getSide1() + ", " + ((Triangle)fig).getSide2() + ", " + ((Triangle)fig).getSide3());
}
else if (fig instanceof Parallelogram)
{
System.out.print("a parallelogram with ");
System.out.println("sides " + ((Parallelogram)fig).getSide1() + " and " + ((Parallelogram)fig).getSide2() + " and angle of " +
((Parallelogram)fig).getAngle());
}
else if (fig instanceof Square)
{
System.out.print("a square with ");
System.out.println("side= " + ((Square)fig).getSide());
}
System.out.println( "The perimeter is " + fig.getPerimeter( ) + " and the area is " + fig.getArea());
}
}
// return a reference to a figure with the largest perimeter
// among all figures of arr
// if arr is null or empty return null
public static Figure getLargestPerimeter(Figure[] arr)
{
if(arr == null || arr.length == 0)
return null;
Figure bigPerimeter = arr[0];
for(int i = 0; i < arr.length; i++)
{
if(arr[i] != null && arr[i].getPerimeter() > bigPerimeter.getPerimeter())
bigPerimeter = arr[i];
}
return bigPerimeter;
}
// return a reference to a figure with the smallest perimeter
// among all figures of arr
// if arr is null or empty return null
public static Figure getSmallestPerimeter(Figure[] arr)
{
if(arr == null || arr.length == 0)
return null;
Figure smallPerimeter = arr[0];
for(int i = 0; i > arr.length; i++)
{
if(arr[i] != null && arr[i].getPerimeter() < smallPerimeter.getPerimeter())
smallPerimeter = arr[i];
}
return smallPerimeter;
}
// return a reference to a figure with the largest area
// among all figures of arr
// if arr is null or empty return null
public static Figure getLargestArea(Figure[] arr)
{
if(arr == null || arr.length == 0)
return null;
Figure bigArea = arr[0];
for(int i = 0; i < arr.length; i++)
{
if(arr[i] != null && arr[i].getArea() > bigArea.getArea())
bigArea = arr[i];
}
return bigArea;
}
// return a reference to a figure with the smallest area
// among all figures of arr
// if arr is null or empty return null
public static Figure getSmallestArea(Figure[] arr)
{
if(arr == null || arr.length == 0)
return null;
Figure smallArea = arr[0];
for(int i = 0; i > arr.length; i++)
{
if(arr[i] != null && arr[i].getArea() < smallArea.getArea())
smallArea = arr[i];
}
return smallArea;
}
Also my triangle class won't print the sides and i tried to input an IllegalArgumentException but the side still wont print. Here is the code:
public class Triangle implements Figure
{
// the fields
private double a, b, c; // the 3 fields
// the constructor
// form a triangle with sides s1,s2,s3
// if s1,s2,s3 do not form a triangle, throw an
// IllegalArgumentException
public Triangle(double s1, double s2, double s3) //throws IllegalArgumentException
{
s1= a;//hypotenuse
s2= b;//base
s3= c;//height
if(a + b < c || a + c < b || c + b < a)
{
throw new IllegalArgumentException
("We try to form an illegal triangle");
}
}
// methods that return the 3 sides
public double getSide1()
{
return a;
}
public double getSide2()
{
return b;
}
public double getSide3()
{
return c;
}
// # return the perimeter
#Override
public double getPerimeter()
{
return a + b + c;
}
// #return the area
#Override
public double getArea()
{
return (0.5) * b * c;
}
}

The second expression in a for loop means "keep executing the loop AS LONG AS the condition is true" -- not "keep executing UNTIL it's true". This means that if your loop looks like this:
for(int i = 0; i > arr.length; i++)
you will never execute anything in the loop, because i starts out as 0 and 0 > arr.length is false and so the loop stops right away. Change > to <.

Related

Narrow down chromatic number to range

I am required to write a program that takes in an input file (which represents a graph) and outputs the chromatic number along with the vertices colors. I wrote a program that does this successfully, however I am given a large input file and the program runs indefinitely. I need to make the program narrow down the chromatic number to a range of ten values. Can anyone give me some advice as to how I can accomplish this. I will post my code below for reference.
Any help would be appreciated. Thanks!
import java.util.*;
import java.io.*;
public class chromatic_num {
public static int n;
public static int q[];
public static int matrix[][];
public static List<Integer> list;
public static void main(String[] args) throws IOException {
//reads input from file
BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream("file1.txt")));
} catch (FileNotFoundException e) {
throw new RuntimeException();
}
String line;
boolean readFirstLine = false;
// new array list to store input
list = new ArrayList<Integer>();
// read file line by line
while ((line = br.readLine()) != null) {
// prints content
String[] toks = line.split(" ");
if (readFirstLine) {
list.add(Integer.parseInt(toks[0]));
list.add(Integer.parseInt(toks[1]));
}
else {
readFirstLine = true;
n = Integer.parseInt(toks[0]);
}
}
// finds max edges
n = Collections.max(list);
// for adjacency matrix
matrix = new int[n][n];
// constructs adj. matrix
int count = 0;
Integer v1 = 0, v2 = 0;
for (Integer v : list) {
if (count % 2 == 0) {
v1 = v - 1;
}
else {
v2 = v - 1;
matrix[v1][v2] = 1;
matrix[v2][v1] = 1;
}
count++;
}
// new array to store colors
q = new int[n];
chromatic_num chromatic = new chromatic_num();
//print solution to screen
System.out.println(chromatic.color());
for (int i = 0; i < n; i++) {
System.out.println("" + (i + 1) + " " + q[i]);
}
//print solution to file
try {
System.setOut(new PrintStream(new FileOutputStream("chromatic_num.txt")));
} catch (FileNotFoundException e) {
throw new RuntimeException();
}
System.out.println(chromatic.color());
for (int i = 0; i < n; i++) {
System.out.println("" + (i + 1) + " " + q[i]);
}
br.close();
}
//color G using minimum number of colors, returns chromatic number
public int color()
{
//for (int t = 0
for (int i = 1; i <= n; i++)
{
//if G can be colored using i colors starting at vertex 0
//System.out.println("colored using " + i + " colors starting at vertex 1");
if (color(0,i)) {
//chromatic number is i, return it
return i;
}
else {
for (int j = 0; j < n; j++) {
q[j] = 0;
}
}
}
return 0;
}
//colors G using m colors starting at vertex v
public boolean color(int v, int m)
{
if (v > n - 1) {
//all vertices have been colored, success
return true;
}
else
{
for (int i = 1; i <= m; i++)
{
//assign color i to vertex v
q[v] = i;
//System.out.println("color " + i + " to vertex " + (v + 1));
//check whether colors of v and its neighbors conflict
boolean hasConflicted = hasConflicted(v);
//System.out.println("hasConflicted = " + hasConflicted);
if (hasConflicted == false)
{
//color the rest of G using m colors starting at vertex v+1, done by recursive call color(v+1, m)
boolean success = color(v + 1, m);
//if (the rest of G can be colored)
// all vertices have been colored, success
if (success) {
return true;
}
}
}
//assign color 0 to vertex v and fail, this happens when none of the m colors can be assigned to vertex v
q[v] = 0;
return false;
}
}
public boolean hasConflicted(int v) {
for (int i = 0; i < n; i++)
{
if (i != v && matrix[i][v] == 1 && q[i] == q[v]) {
return true;
}
}
return false;
}
}

Tic Tac Toe: All states get returned as best moves

I am working on building the game of Tic Tac Toe. Please find below the description of the classes used.
Game:: The main class. This class will initiate the multiplayer mode.
Board: This class sets the board configurations.
Computer: This class comprises of the minimax algorithm.
BoardState: This class comprises of the Board Object, along with the last x and y coordinates which were used to generate the board
configuration.
State: This class comprises of the score and the x and y coordinates that that will lead to that score in the game.
Context
Working on DFS here.
Exploring the whole tree works fine.
The game is set in such a way that the user is prompted to play first.
The user will put x and y co ordinates in the game.Coordinates are between 0 to 2. The Play of the player is marked as 1
The response from the computer is 2, which the algorithm decides. Th algorithm will determine the best possible coordinates to play and then play 2 on the position.
One of the winning configurations for Player is :
Player wins through diagonal
121
112
221
One of the winning configuration for AI is:
222
121
211
AI wins Horizontal
Problem
All the states give the max score.
Essentially, when you start the game in your system, you will find that since all states are given the max score, the computer looks to play sequentially.
As in if you put at (00), the computer plays at (01) and if you play at (02), the computer will play at (10)
I have been trying to debug it for a long time now. I believe, I may be messing up something with the scoring function. Or there could be a bug in the base recursion steps. Moreover, I don't think immutability among classes could cause problems as I have been recreating/creating new objects everywhere.
I understand, this might not be the best context I could give, but it would be a great help if you guys could help me figure out where exactly is it going wrong and what could I do to fix it. Answers through code/logic used would be highly appreciated. Thanks!
Game Class
import java.io.Console;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Game {
static int player1 = 1;
static int player2 = 2;
public static void main(String[] args) {
// TODO Auto-generated method stub
//
//PLays Game
playGame();
/* Test Use Case
ArrayList<Board> ar = new ArrayList<Board>();
Board b = new Board();
b.setVal(0,0,1);
b.setVal(0,1,1);
b.setVal(0,2,2);
b.setVal(1,0,2);
b.setVal(1,1,2);
b.setVal(2,0,1);
b.setVal(2,1,1);
b.display();
Computer comp = new Computer();
State x = comp.getMoves(b, 2);
*/
}
private static void playGame() {
// TODO Auto-generated method stub
Board b = new Board();
Computer comp = new Computer();
while(true)
{
if(b.isBoardFull())
{
System.out.println("Game Drawn");
break;
}
b.display();
int[] pmove = getPlayerMove(b);
b.setVal(pmove[0],pmove[1], player1);
if(b.isVictoriousConfig(player1))
{
System.out.println("Player 1 Wins");
break;
}
if(b.isBoardFull())
{
System.out.println("Game Drawn");
break;
}
b.display();
System.out.println("Computer Moves");
/*For Random Play
* int[] cmove = comp.computeMove(b);
*/
Computer compu = new Computer();
State s = compu.getMoves(b, 2);
int[] cmove = new int[2];
cmove[0] = s.x;
cmove[1] = s.y;
b.setVal(cmove[0],cmove[1], player2);
if(b.isVictoriousConfig(player2))
{
System.out.println("Computer Wins");
break;
}
}
System.out.println("Game Over");
}
//Gets Player Move. Basic Checks on whether the move is a valud move or not.
private static int[] getPlayerMove(Board b) {
// TODO Auto-generated method stub
int[] playerMove = new int[2];
System.out.println("You Play");
while(true)
{
#SuppressWarnings("resource")
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter X Position: ");
while(true)
{
playerMove[0] = reader.nextInt(); // Scans the next token of the input as an int.
if(playerMove[0] >2)
{
System.out.println("Incorrect Position");
}
else
{
break;
}
}
System.out.println("Enter Y Position: ");
while(true)
{
playerMove[1] = reader.nextInt(); // Scans the next token of the input as an int.
if(playerMove[1] >2)
{
System.out.println("Incorrect Position");
}
else
{
break;
}
}
System.out.println("You entered positions: X is " + playerMove[0] + " and Y is " + playerMove[1] );
if(!b.isPosOccupied(playerMove[0], playerMove[1]))
{
break;
}
System.out.println("Incorrect Move. PLease try again");
}
return playerMove;
}
}
Board Class
import java.util.Arrays;
public class Board {
// Defines Board Configuration
private final int[][] data ;
public Board()
{
data = new int[3][3];
for(int i=0;i<data.length;i++ )
{
for(int j=0;j<data.length;j++ )
{
data[i][j] = 0;
}
}
}
//Displays Current State of the board
public void display()
{
System.out.println("Board");
for(int i = 0; i< data.length;i++)
{
for(int j = 0; j< data.length;j++)
{
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
// Gets the Value on a specific board configuration
public int getVal(int i, int j)
{
return data[i][j];
}
//Sets the value to a particular board location
public void setVal(int i, int j,int val)
{
data[i][j] = val;
}
public boolean isBoardFull()
{
for(int i=0;i< data.length ; i++)
{
for(int j=0;j< data.length ;j++)
{
if(data[i][j] == 0)
return false;
}
}
return true;
}
public boolean isVictoriousConfig(int player)
{
//Noting down victory rules
//Horizontal Victory
if ( (data[0][0] != 0) && ((data[0][0] == data [0][1]) && (data[0][1] == data [0][2]) && (data[0][2] == player)))
return true;
if ((data[1][0] != 0) && ((data[1][0] == data [1][1]) && (data[1][1] == data [1][2]) && (data[1][2] == player)))
return true;
if ((data[2][0] != 0) && ((data[2][0] == data [2][1]) && (data[2][1] == data [2][2]) && (data[2][2] == player)))
return true;
//Vertical Victory
if ( (data[0][0] != 0) && ((data[0][0] == data [1][0]) && (data[1][0] == data [2][0]) && (data[2][0] == player)))
return true;
if ((data[0][1] != 0) && ((data[0][1] == data [1][1]) && (data[1][1] == data [2][1]) && (data[2][1] == player)))
return true;
if ((data[0][2] != 0) && ((data[0][2] == data [1][2]) && (data[1][2] == data [2][2]) && (data[2][2] == player)))
return true;
//Diagonal Victory
if ( (data[0][0] != 0) && ((data[0][0] == data [1][1]) && (data[1][1] == data [2][2]) && (data[2][2] == player)))
return true;
if ( (data[0][2] != 0) && ((data[0][2] == data [1][1]) && (data[1][1] == data [2][0]) && (data[2][0] == player)))
return true;
//If none of the victory rules are met. No one has won just yet ;)
return false;
}
public boolean isPosOccupied(int i, int j)
{
if(data[i][j] != 0)
{
return true;
}
return false;
}
public Board(int[][] x)
{
this.data = Arrays.copyOf(x, x.length);
}
}
Board State
public class BoardState {
final Board br;
final int x ;
final int y;
public BoardState(Board b, int posX, int posY)
{
br = b;
x = posX;
y = posY;
}
}
State
public class State {
final int s;
final int x;
final int y;
public State(int score, int posX, int posY)
{
s = score;
x = posX;
y = posY;
}
}
Computer
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
public class Computer {
int[] pos = new int[2];
static int player2 = 2;
static int player1 = 1;
ArrayList<Board> win =new ArrayList<Board>();
ArrayList<Board> loose =new ArrayList<Board>();
ArrayList<Board> draw =new ArrayList<Board>();
public Computer()
{
}
public int[] computeMove(Board b)
{
while(true)
{
Random randX = new Random();
Random randY = new Random();
pos[0] = randX.nextInt(3);
pos[1] = randY.nextInt(3);
if(!b.isPosOccupied(pos[0], pos[1]))
{
return pos;
}
}
}
public State getMoves(Board b,int p)
{
//System.out.println("test2");
int x = 0;
int y = 0;
BoardState bs = new BoardState(b,0,0);
//System.out.println("test");
State s = computeMoveAI(bs,p);
//System.out.println("Sore : X : Y" + s.s + s.x + s.y);
return s;
}
private State computeMoveAI(BoardState b, int p) {
// TODO Auto-generated method stub
//System.out.println("Hello");
int[][]sArray = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
sArray[i1][j1] = b.br.getVal(i1, j1);
}
}
Board d = new Board(sArray);
//System.out.println("d is ");
//d.display();
//System.out.println("p is "+ p);
int xvalue= b.x;
int yvalue = b.y;
BoardState bs = new BoardState(d,xvalue,yvalue);
if(getConfigScore(d,p) == 1)
{
//System.out.println("Winning Config");
//System.out.println("X is " + b.x + " Y is " + b.y);
// b.br.display();
State s = new State(-1,bs.x,bs.y);
return s;
}
else if (getConfigScore(d,p) == -1)
{
//System.out.println("LooseConfig");
State s = new State(1,bs.x,bs.y);
//System.out.println("Coordinates are "+bs.x + bs.y+ " for " + p);
return s;
}
else if(bs.br.isBoardFull())
{
//System.out.println("Board is full");
State s = new State(0,bs.x,bs.y);
//System.out.println("score " + s.s + "x "+ s.x + "y "+ s.y);
return s;
}
else
{
//Get Turn
//System.out.println("In else condiyion");
int turn;
if(p == 2)
{
turn = 1;
}else
{
turn = 2;
}
ArrayList<BoardState> brr = new ArrayList<BoardState>();
ArrayList<State> st = new ArrayList<State>();
brr = getAllStates(d,p);
for(int k=0;k<brr.size();k++)
{
//System.out.println("Goes in " + "turn " + turn);
//brr.get(k).br.display();
int xxxxx = computeMoveAI(brr.get(k),turn).s;
State temp = new State(xxxxx,brr.get(k).x,brr.get(k).y);
st.add(temp);
}
//Find all Nodes.
//Go to First Node and proceed with recursion.
//System.out.println("Displaying boards");
for(int i=0;i<brr.size();i++)
{
//brr.get(i).br.display();
//System.out.println(brr.get(i).x + " " + brr.get(i).y);
}
//System.out.println("Board configs are");
for(int i=0;i<st.size();i++)
{
//System.out.println(st.get(i).x + " " + st.get(i).y + " and score " + st.get(i).s);
}
//System.out.println("xvalue" + xvalue);
//System.out.println("yvalue" + yvalue);
//System.out.println("Board was");
//d.display();
//System.out.println("Coming to scores");
//System.out.println(" p is "+ p);
if(p == 2)
{
//System.out.println("Size of first response" + st.size());
//System.out.println("Returns Max");
return max(st);
}
else
{
//System.out.println("The last");
return min(st);
}
}
}
private State min(ArrayList<State> st) {
// TODO Auto-generated method stub
ArrayList<State> st1= new ArrayList<State>();
st1= st;
int min = st.get(0).s;
//System.out.println("Min score is " + min);
for(int i=1;i<st1.size();i++)
{
if(min > st1.get(i).s)
{
min = st1.get(i).s;
//System.out.println("Min is");
//System.out.println(min);
//System.out.println("Min" + min);
State s = new State(min,st1.get(i).x,st1.get(i).y);
return s;
}
}
State s = new State(st1.get(0).s,st1.get(0).x,st1.get(0).y);
//System.out.println("Max" + st1.get(0).s);
//System.out.println("Exits Min");
//System.out.println("Min Score" + st1.get(0).s + " x" + st1.get(0).x + "y " + st1.get(0).y);
return s;
}
private State max(ArrayList<State> st) {
// TODO Auto-generated method stub
//System.out.println("Size of first response in funciton is " + st.size());
ArrayList<State> st1= new ArrayList<State>();
st1 = st;
int max = st1.get(0).s;
for(int i=0;i<st1.size();i++)
{
// System.out.println(i+1 + " config is: " + "X:" + st1.get(i).x + "Y:" + st1.get(i).y + " with score " + st1.get(i).s);
}
for(int i=1;i<st1.size();i++)
{
//.out.println("Next Item " + i + st.get(i).s + "Coordinates X"+ st.get(i).x +"Coordinates Y"+ st.get(i).y );
if(max < st1.get(i).s)
{
max = st1.get(i).s;
//System.out.println("Max" + max);
//System.out.println("Max is");
//System.out.println(max);
State s = new State(max,st1.get(i).x,st1.get(i).y);
//System.out.println("Max Score returned" + s.s);
//System.out.println("Returned");
return s;
}
}
State s = new State(st1.get(0).s,st1.get(0).x,st1.get(0).y);
//System.out.println("Max" + st1.get(0).s);
//System.out.println("Max is outer");
//System.out.println(st.get(0).s);
return s;
}
//Basic brain Behind Min Max algorithm
public int getConfigScore(Board b,int p)
{
int score;
int turn ;
int opponent;
if(p == player1)
{
turn = p;
opponent = player2;
}
else
{
turn = player2;
opponent = player1;
}
int[][]sArray = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
sArray[i1][j1] = b.getVal(i1, j1);
}
}
Board d = new Board(sArray);
//System.out.println("s arrasy is ");
//d.display();
//System.out.println("turn is " + turn);
if(d.isVictoriousConfig(turn))
{
score = 1;
}
else if(d.isVictoriousConfig(opponent))
{
score = -1;
}
else
{
score = 0;
}
return score;
}
public static ArrayList<BoardState> getAllStates(Board b, int player)
{
ArrayList<BoardState> arr = new ArrayList<BoardState>();
int[][]s1 = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
s1[i1][j1] = b.getVal(i1, j1);
}
}
Board d = new Board(s1);
for(int i = 0;i <3; i ++)
{
for (int j=0;j<3;j++)
{
if(!d.isPosOccupied(i, j))
{
int previousState = d.getVal(i, j);
int[][]s = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
s[i1][j1] = d.getVal(i1, j1);
}
}
s[i][j] = player;
Board d1 = new Board(s);
BoardState bs = new BoardState(d1,i,j);
arr.add(bs);
}
}
}
return arr;
}
}
This is the output of the test case in the Game class:
Board
1 1 2
2 2 0
1 1 0
Score : X : Y -> 1: 1: 2
The solution here is score:1 for x:1, y:2. It looks correct.
But again, you could say since it is moving sequentially, and since position (1,2) will come before (2,2), it gets the right coordinate.
I understand that this may be huge lines of code to figure out the problem. But
computemoveAI(), getConfigScore() could be the functions to look out for. Also I do not want to bias your thoughts with where I think the problem could as sometimes, we look somewhere , but the problem lies elsewhere.!!

Why is method A flawed compared to B for UVa online judge 100 (3n+1)?

Simply changing from Swap Method A to Swap Method B, the UVa judge goes from 'Wrong Answer' to 'Accepted'. Why is that? I thank you all in advance for your responses.
import java.io.IOException;
import java.util.StringTokenizer;
/**
* #author Coder47
* Another solution to 3n+1 (UVa ID: 100)
*/
class Main {
public static int[] cache = new int[1000000];
static String ReadLn (int maxLg) // utility function to read from stdin
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main(String[] args) {
Main myWork = new Main(); // create a dynamic instance
myWork.Begin(); // the true entry point
}
void Begin() {
String input;
StringTokenizer idata;
// corresponds to swap method A
int a, b, temp, cycle, cycleMax;
// corresponds to swap method B
// int a, b, min, max, cycle, cycleMax;
while ((input = Main.ReadLn(255)) != null)
{
idata = new StringTokenizer(input);
a = Integer.parseInt(idata.nextToken());
b = Integer.parseInt(idata.nextToken());
// swap method A
if (b < a) {
temp = a;
a = b;
b = temp;
}
// swap method B
// min = Math.min(a, b);
// max = Math.max(a, b);
cycleMax = 0;
// corresponds to swap method A
for (int i = a; i <= b; i++)
// corresponds to swap method B
// for ( int i = min; i <= max; i++)
{
cycle = calculateCycle(i);
if (cycle > cycleMax) {
cycleMax = cycle;
}
}
System.out.println (a + " " + b + " " + cycleMax);
}
}
public int calculateCycle(int n) {
return calculateCycleHelper(n, 1);
}
public int calculateCycleHelper(int n, int cycleNum) {
if (n == 1) {
return cycleNum;
} else {
return calculateCycleHelper(next(n), cycleNum + 1);
}
}
public int next(int n) {
if (n % 2 == 0) {
n = n/2;
}
else {
n = 3*n+1;
}
return n;
}
}
Please overlook the efficiency and other related issues of the code, since that is not the issue here.
It's because if (a < b) says the opposite of what you want. You need to swap the elements if b < a, because in the for loop
for (int i = a; i <= b; i++)
you want a to be less than b.
EDIT
For your updated question, the answer is that it's because the judge is checking the output. If you swap a and b the output from the line
System.out.println (a + " " + b + " " + cycleMax);
changes, so the judge does not accept it.

Java Binary Tree entered in a specific order

I am trying to complete an assignment where I need to write a Java program to take a string from the command line, and implement it as a Binary Tree in a specific order, then get the depth of the binary tree.
For example: "((3(4))7((5)9))"
would be entered as a tree with 7 as the root, 3 and 9 as the children, and 4 as a right child of 3, and 5 as a left child of 9.
My code is below.. The problem I am having is that, because I am basing my checks off of finding a right bracket, I am unsure how to get the elements correctly when they are not directly preceding the brackets, such as the 3 in the above string. Any direction would be greatly appreciated..
class Node {
int value;
Node left, right;
}
class BST {
public Node root;
// Add Node to Tree
public void add(int n) {
if (root == null) {
root = new Node( );
root.value = n;
}
else {
Node marker = root;
while (true) {
if (n < marker.value) {
if (marker.left == null) {
marker.left = new Node( );
marker.left.value = n;
break;
} else {
marker = marker.left;
}
} else {
if (marker.right == null) {
marker.right = new Node( );
marker.right.value = n;
break;
} else {
marker = marker.right;
}
}
}
}
} // End ADD
//Find Height of Tree
public int height(Node t) {
if (t.left == null && t.right == null) return 0;
if (t.left == null) return 1 + height(t.right);
if (t.right == null) return 1 + height(t.left);
return 1 + Math.max(height(t.left), height(t.right));
} // End HEIGHT
// Check if string contains an integer
public static boolean isInt(String s) {
try {
Integer.parseInt(s);
}
catch(NumberFormatException e) {
return false;
}
return true;
} // End ISINT
public int elementCount(String[] a) {
int count = 0;
for (int i = 0; i < a.length; i++) {
if (isInt(a[i])) count++;
}
return count;
}
} // End BST Class
public class Depth {
public static void main(String[] args) {
String[] a = args[0].split(" ");
BST tree = new BST();
int[] bcount = new int[10];
int[] elements = new int[10];
int x = 0, bracketcount = 0;
// Display entered string
System.out.print("Entered Format: ");
for (int j=0; j < a.length; j++) {
System.out.print(a[j]);
}
for (int i=0; i < a.length; i++) {
char c = a[i].charAt(0);
switch (c)
{
case '(':
bracketcount++;
break;
case ')':
if (isInt(a[i-1])) {
bcount[x] = bracketcount--;
elements[x++] = Integer.parseInt(a[i-1]);
}
break;
case '1':
case '7':
default : // Illegal character
if ( (a[i-1].charAt(0) == ')') && (a[i+1].charAt(0) == '(') ) {
bcount[x] = bracketcount;
elements[x++] = Integer.parseInt(a[i]);
}
break;
}
}
System.out.println("\nTotal elements: " + tree.elementCount(a));
// Display BracketCounts
for (int w = 0; w < x; w++) {
System.out.print(bcount[w] + " ");
}
System.out.println(" ");
// Display Elements Array
for (int w = 0; w < x; w++) {
System.out.print(elements[w] + " ");
}
System.out.println("\nDepth: " + tree.height(tree.root));
// Build the tree
for (int y = 0; y < x-1; y++) {
for (int z = 1; z < tree.height(tree.root); z++) {
if (bcount[y] == z) {
tree.add(elements[y]);
}
}
}
} // End Main Function
public static boolean isInt(String s) {
try {
Integer.parseInt(s);
}
catch(NumberFormatException e) {
return false;
}
return true;
}
} // End Depth Class
I would do a couple of statements to get access to a tree with that kind of shape:
For input string : input= "((3(4))7((5)9))"
You could do :
public class Trial {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String input = "((3(4))7((5)9))";
String easier = input.replaceAll("\\(\\(", "");
String evenEasier = easier.replaceAll("\\)\\)", "");
System.out.println(evenEasier);
int firstVal = Integer.parseInt(evenEasier.substring(0, 1));
int firstBracketVal = Integer.parseInt(evenEasier.substring(2, 3));
int middleVal = Integer.parseInt(evenEasier.substring(3, 4));
int secondBracketVal = Integer.parseInt(evenEasier.substring(4,5));
int lastVal = Integer.parseInt(evenEasier.substring(6));
System.out.println("First Val:"+firstVal);
System.out.println("First bracket Val:"+firstBracketVal);
System.out.println("Middle Val:"+middleVal);
System.out.println("Second Bracket Val:"+secondBracketVal);
System.out.println("Last Val:"+lastVal);
}
}
This however would only ever work for entries in that specific format, if that were to change, or the length of the input goes up - this would work a bit or break.....If you need to be able to handle more complicated trees as input in this format a bit more thought would be needed on how to best handle and convert into your internal format for processing.
pseudocode:
function getNode(Node)
get one char;
if (the char is "(")
getNode(Node.left);
get one char;
end if;
Node.value = Integer(the char);
get one char;
if (the char is "(")
getNode(Node.right);
get one char;
end if;
//Now the char is ")" and useless.
end function
Before calling this function, you should get a "(" first.
In this method, the framwork of a Node in string is "[leftchild or NULL] value [rightchild or NULL])".
"("is not belong to the Node, but ")" is.

Adding duplicates in an ArrayList

I am stuck on how to find duplicate entries in an ArrayList and then manipulate them. I am implementing a polynomial class and I want to add monomials of the same order to create a new polynomial. Monomials have a degree and a coefficient. I want to cycle through a collection of monomials and find the monomials that have the same power and add the coefficients. The sum of all these like powered monomials will be the polynomial.
ArrayList (or any List) accepts duplicates.
However, since you want to group Monomials by their power, you might consider using a Map<Integer,Foo> where the key is the power. Foo has a lot of options. Foo could be an ArrayList<Monomial>, an ArrayList<Double>, holding only the coefficiants, that you add later. This requires some code writing on your part or else using a 3rd partly library for a MultiMap.
Or, Foo could be a Double which represents the summed coefficient, in which case you need to write an add(Monomial) method which updates the Double everytime.
If the possible range of powers is small and known, you could use a simple array too.
Here's my solution, you can add two polynomials of the same degree. Watch for bugs.
public class Polynome {
private double[] coefficients;
private int degre;
public Polynome(int degre) {
if (degre < 0) {
System.out.println("Invalid Degree");
}
this.degre = degre;
coefficients = new double[degre + 1];
for (int i = 0; i < degre; i++)
coefficients[i] = 0;
coefficients[degre] = 1;
}
public void setCoefficient(int degre, double coefficient) {
if (degre < 0 || degre > this.degre) {
System.out.println("Invalid Degree");
}
if (coefficient == 0 && degre == this.degre && this.degre != 0) {
System.out.println("Null Degree");
}
coefficients[degre] = coefficient;
}
/*
* Returns the coeff giving the degree of the element
*/
public double getCoefficient(int degre) {
if (degre < 0 || degre > this.degre) {
return 0;
}
if (degre == this.degre && this.degre != 0) {
return coefficients[this.getDegre()];
}
return this.coefficients[degre];
}
public String ToString() {
if (degre == 0)
return "" + this.coefficients[0];
String result = "" + this.coefficients[degre]+" x^" + degre;
for (int i = degre-1 ; i > 0 ; i--){
if (this.coefficients[i] < 0) {
result += "-" + Math.abs(this.coefficients[i]) + " x^" + i;
}
else {
if (this.coefficients[i] > 0){
result += " + " + this.coefficients[i] + " x^" + i;
}
}
}
if (this.coefficients[0]!= 0) result += " + " + this.coefficients[0] ;
return result;
}
/*
* Returns the degree of the current poly
*/
public int getDegre() {
return degre;
}
/*
* Adds two Polys with the same degrees
*/
public Polynome add(Polynome p) {
Polynome result = new Polynome(p.getDegre());
int deg = result.getDegre();
for(int i = deg ; i >0 ; i--) {
result.coefficients[i] = this.getCoefficient(i) + p.getCoefficient(i);
}
return result;
}
public static void main(String...args) {
Polynome p = new Polynome(2);
p.setCoefficient(2, 7);
Polynome p1 = new Polynome(2);
p1.setCoefficient(2, 2);
System.out.println(p.ToString() + "\n" + p1.ToString() + "\n\n" + (p.add(p1)).ToString());
}
}

Categories

Resources