I have created the following but need the output line to maintain a consistent width to give the appearance of a race. I also need to ensure that the racers do not slip back past the start.
Currently, the output plots correctly, but the line only extends to the racers position.
Also, when there is a "slip" it appears that the racer sometimes moves back to start. I'm not sure if that is solved with a consistent length of "race track" as well.
import java.util.*;
public class Race {
public static void main(String []args) {
int finish=70,tort=1,hare=1,rtime=0;
System.out.println("ON YOUR MARK, GET SET\nBANG !!!!!\nAND THEY'RE OFF !!!!!\n");
do{
hare=movehare(hare);
tort=movetort(tort);
print(tort,hare);
rtime++;
}
while(tort<finish&&hare<finish);
if(tort>hare ){
System.out.println("\nTORTOISE WINS!\n");
}
else if(tort<hare ){
System.out.println("\nHARE WINS!\n");
}
else{
System.out.println("IT\'S A TIE!\n");
}
}
public static void print(int t,int h){
int i;
if(h==t){
for(i=0;i<h;i++)
System.out.print("_");
System.out.println("OUCH!!!");
}
else if(h<t){
for(i=0;i<h;i++)
System.out.print("_");
System.out.print("H");
for(i=0;i<(t-h);i++)
System.out.print("_");
System.out.print("T");
}
else{
for(i=0;i<t;i++)
System.out.print("_");
System.out.print("T");
for(i=0;i<(h-t);i++)
System.out.print("_");
System.out.print("H");
}
System.out.println();
}
public static int movehare(int r ){
int num;
num=(int)(Math.random()*10);
if(num<2){
r-=2;
}
else if(num<5){
r++;
}
else if(num<6){
r-=12;
}
else if(num<8){
r+=9;
}
if(r< 1 ){
r=1;
}
return r;
}
public static int movetort(int t){
int num;
num=(int)(Math.random()*10);
if(num<5){
t+=3;
}
else if(num<7){
t-= 6;
}
else{
t++;
}
if(t<1){
t=1;
}
return t;
}
}
You can print extra "_" after each of the IF branches in your print method
if(h != t){
for(i = Math.max(h,t); i < 70; i++){
System.out.print("_");
}
}
Note: The line breaks will be off when the H == T because you print "Ouch!!!", so you'll have to check for that and accommodate.
Related
So, I've created a simple app for moving a bug along a wire. The code works well (for the most part) though, I am having a few issues.
When reaching the end of the wire, the program terminates all well and good but I'm getting a double output that it's fallen off the wire when it reaches the end.
I am supposed to be writing a toString for this, but am having a bit of a hard time grasping why and how I should go about doing this.
If someone could assist with this, I'd greatly appreciate it.
import java.util.Scanner;
public class ClassPracticeMain {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
int userInput;
Bug bug1 = new Bug();
bug1.setInitialPosition();
bug1.setInitialDirection();
System.out.println("Your starting position is " + bug1.initialPosition
+ " and you are facing " + bug1.getCurrentDirection()
);
while (bug1.getExit(1) != 0) {
System.out.println("Which way would you like to move? 1 for left/ 2 for right or 0 for exit");
userInput = input.nextInt();
bug1.move(userInput);
bug1.getCurrentDirection();
bug1.getCurrentPosition();
System.out.println("You are now at " + bug1.currentPosition + " and you are facing " + bug1.getCurrentDirection());
bug1.getExit(userInput);
}
}
}
public class Bug {
final int WIRELEFTEND=-15;
final int WIRERIGHTEND=15;
int initialPosition=0, currentPosition=0, direction,exit=1;
String currentDirection;
String left = "left";
String right = "right";
public int setInitialPosition(){
return initialPosition;
}
public int setInitialDirection(){
direction=1;
return direction;
}
public int getCurrentPosition(){
return currentPosition;
}
public String getCurrentDirection(){
if (direction== 1){
currentDirection=left;
} else if (direction == 2){
currentDirection=right;
}
return currentDirection;
}
public int move(int move){
if(move==1 && direction==1){
currentPosition=currentPosition-1;
return currentPosition;
} else if (move==1 && direction==2){
direction=1;
return currentPosition;
} else if (move==2 && direction==1){
direction=2;
return currentPosition;
} else if (move==2 && direction ==2){
currentPosition=currentPosition+1;
return currentPosition;
}
return 0;
}
public int getExit(int exit){
if(currentPosition<(WIRELEFTEND)||currentPosition>WIRERIGHTEND){
System.out.println("You've fallen off the wire... Oh no!");
exit=0;
} else{
exit=exit;
}
return 1;
}
}
You probably want to write
public int getExitStatus(){
if(currentPosition<(WIRELEFTEND)||currentPosition>WIRERIGHTEND){
System.out.println("You've fallen off the wire... Oh no!");
return 0;
}
return 1;
}
instead of your current getExist(int) function. It always returns 1, and setting the exit argument doesn't do anything.
I was asked in an interview to write code to check if a given string is a palindrome or can be a palindrome by altering some character without using a library function. Here is my Approach
import java.util.Scanner;
public class Palindrom {
static int temp=0;
static char[] cArr;
static boolean chackPotentialPalindrom(char[] cAr){
cArr=cAr;
if(cArr!=null){
char current=cArr[0];
for(int i=1;i<cArr.length;i++){
if(current==cArr[i]){
cArr=removeElement(i);
chackPotentialPalindrom(cArr);
break;
}
}
if(cAr.length==2){
if(cAr[0]==cAr[1]){
cArr=null;
}}
if(temp==0 && cArr!=null){
temp=1;
cArr=removeFirstElement(cArr);
chackPotentialPalindrom(cArr);
}
}
if(cArr==null){
return true;
}else{
return false;
}
}
static char[] removeFirstElement(char[] cAr){
cArr=cAr;
if(cArr!=null){
if(cArr.length >1){
char[] cArrnew=new char[cArr.length-1];
for(int j=1,k=0;j<cArr.length;j++,k++){
cArrnew[k]=cArr[j];
}
return cArrnew;
} else {
return null;
}
} else {
return null;
}
}
static char[] removeElement(int i){
if(cArr.length>2){
char[] cArrnew=new char[cArr.length-2];
for(int j=1,k=0;j<cArr.length;j++,k++){
if(i!=j){
cArrnew[k]=cArr[j];
}else{
k-=1;
}
}
return cArrnew;}
else{
return null;
}
}
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
while(true){
temp=0;
String s=scn.next();
char[] arr=s.toCharArray();
System.out.println(chackPotentialPalindrom(arr));
}
}
}
Any tips to optimize this code?I could not write this in an interview as they have given a pen and paper to code.It took 3 hrs for me to write this. Can I be a developer?
Title says "without loop" but you need to check all symbol pairs, so using recursion, as you have tried, looks reasonable. But you don't check and use results of recursive calls.
Pseudocode might look like (note we don't need to change source data or extract substring):
Edit to provide possibility to alter one char
boolean checkPotentialPalindrom(char[] cAr, start, end, altcnt){
if (end <= start)
return true
if (cAr[start] != cAr[end])
altcnt = altcnt + 1
if (altcnt > 1)
return false
return checkPotentialPalindrom(cAr, start + 1, end - 1, altcnt)
}
and make the first call with arguments 0, len(cAr-1), 0
Answering to your first question..You have to use recursion to solve this problem. Here is my approach.
public boolean isPalindrom(char[] str, int start, int end) {
if (end <= start)
return true;
if (str[start] != str[end] || arraySize(str) <= 1)
return false;
return isPalindrom(str, start + 1, end - 1);
}
public int arraySize(char[] str) {
int count = 0;
for (char i : str) {
count++;
}
return count;
}
You have tried to implement this algorithm using loops and you can simplify it like this
public boolean isPalindroms(char[] str) {
int diffCount = 0;
int left = 0;
int right = arraySize(str) - 1;
while (right > left) {
if (str[right--] != str[left++]) {
diffCount++;
}
}
return (diffCount < 2);
}
public int arraySize(char[] str) {
int count = 0;
for (char i : str) {
count++;
}
return count;
}
The answer for the second question that you have ask is definitely you can be a good developer. Computer programming is a Craft. Not Some Kind of Rocket Science. You have to master it by crafting it.
using recursive function
calling with left=0 and right = arr.length-1
public static boolean isPalindrom(char[] arr, int left, int right){
if(arr[left++] != arr[right--])
return false;
if(left < right)
isPalindromss(arr, left++, right--);
return true;
}
if you have to use while loop, you can simplify it like following
public boolean isPalindrom(char[] arr){
int left=0;
int right = arr.length-1;
while(left < right){
if(arr[left++] == arr[right--])
continue;
return false;
}
return true;
}
Using StringBuilder, We can do it
public static boolean isPalindrom(String str, int len){
StringBuilder sb= new StringBuilder(str);
if((len > 1) & !(sb.substring(0,len/2 + 1).equals(sb.reverse().substring(0,len/2 + 1))))
return false;
return true;
}
function palin(input, leftIdx = 0, rightIdx = input.length - 1) {
if (leftIdx >= rightIdx) return true;
if (input[leftIdx] != input[rightIdx]) return false;
return palin(input, leftIdx + 1, rightIdx - 1);
}
const testCases = {
air: false,
airia: true,
caria: false,
a: true,
bb: true,
bcdb: false,
zzaaaaz: false,
};
Object.keys(testCases).forEach(test =>
console.log("Test: ", test, " is palindrome: ", palin(test), testCases[test])
);
I am writing a java code to Change a number from decimal base to another base.
But I don't know why the program runs wrong. I think the error comes from function Prin_as. Can anyone tell me why ?
Below is my code,
import java.util.Scanner;
public class bai2chuyendoi {
public static void main(String[] args) {
int a, b;
System.out.println("Number in decimal base:");
a = Enter();
System.out.println("Other base :");
b = Enter();
Change_base (a, b);
}
public static int Enter() {
int n = 0;
boolean check = false;
while (!check) {
Scanner sc = new Scanner(System.in);
try {
n = sc.nextInt();
check = true;
} catch (Exception e) {
System.out.println("Enter again:");
sc.nextLine();
}
}
return n;
}
public static void Change_base(int a, int b) {
int i = 0;
int[] c = new int[8];
while (a != 0) {
c[i] = a % b;
a = a / b;
i++;
}
while (i >= 0) {
--i;
if (c[i] < 10) {
System.out.print(c[i]);
} else {
System.out.print((char) (c[i] + 55));
}
}
}
}
The error was in Change_base method in second while loop.
You need decrement 'i' and check that i >= 0, but you didn't.
while (--i >= 0) {
if (c[i] < 10) {
System.out.print(c[i]);
} else {
System.out.print((char) (c[i] + 55));
}
}
I am trying to figure out exactly what is wrong with my winorTie method in this little tictacttoe game I am trying to create. Would anyone be able to help? Thanks
package tictactoegame;
/**
*
* #author Douglas Boulden
*/
public class tictactoegame {
static int [][] gameboard;
static final int EMPTY = 0;
static final int NOUGHT = -1;
static final int CROSS = 1;
static void set (int val, int row) throws IllegalArgumentException {
int col = 0;
if (gameboard[row][col] == EMPTY)
gameboard[row][col] = val;
else throw new
IllegalArgumentException("Player already there!");
}
static void displayBoard () {
for (int[] gameboard1 : gameboard) {
System.out.print("|");
for (int c = 0; c < gameboard1.length; c++) {
switch (gameboard1[c]) {
case NOUGHT:
System.out.print("0");
break;
case CROSS:
System.out.print("X");
break;
default: //Empty
System.out.print(" ");
}
System.out.print("|");
}
System.out.println("\n------\n");
}
}
static void createBoard(int rows, int cols) {
gameboard = new int [rows] [cols];
}
static int winOrTie() {
if (gameboard [0][0] == NOUGHT && gameboard [0][-1])
return NOUGHT;
} else if (gameboard [0][0] == && CROSS) [0][1] {
return CROSS;
} else if (gameboard [0][0]== && " "()) [0][0] {
return 0;
} else {
return false;
}
/**
* #param args the command line arguments
*/ /**
* #param args the command line arguments
*/
public static void main(String[] args) {
createBoard(3,3);
int turn = 0;
int playerVal;
int outcome;
java.util.Scanner scan = new
java.util.Scanner(System.in);
do {
displayBoard();
playerVal = (turn % 2 == 0)? NOUGHT : CROSS;
if (playerVal == NOUGHT) {
System.out.println ("\n-0's turn-");
} else {
System.out.println("\n-X's turn-");
}
System.out.print("Enter row and Column:");
try {
set(playerVal, scan.nextInt());
} catch (IllegalArgumentException ex)
{System.err.println(ex);}
turn ++;
outcome = winOrTie();
} while ( outcome == -2 );
displayBoard();
switch (outcome) {
case NOUGHT:
System.out.println("0 wins!");
break;
case CROSS:
System.out.println("X wins!");
break;
case 0:
System.out.println("Tie.");
break;
}
}
}
Some of this was mentioned in the comments, but these conditions fundamentally don't make sense:
if (gameboard [0][0] == NOUGHT && gameboard [0][-1])
return NOUGHT;
} else if (gameboard [0][0] == && CROSS) [0][1] {
return CROSS;
} else if (gameboard [0][0]== && " "()) [0][0] {
return 0;
For example, what do you think that if (gameboard [0][0] == && CROSS) [0][1] is supposed to do? What exactly is " "() supposed to be? And what do you think that == && does? It's difficult to know exactly what you were actually trying to achieve here.
Also, consider gameboard [0][-1]. There are two problems here. First, you do realize that -1 isn't actually a valid array index in Java, right? (That's allowable in Python, but not Java). Also, gameboard [0][-1] is an integer, not a bool, so && gameboard [0][-1] doesn't make sense. If you have something like A && B, both A and B must evaluate to some kind of boolean value (i.e. true or false).
Also, I'd encourage you not to do indentation like you have here. I'd recommend putting each "else if" on its own line.
I am unable to optimise the following dynamic programming problem:
This is my JAVA solution for the problem with the following test cases.The limit gets exceeded on higher recursion levels. I am unable to understand how memoization can be implemented in this case. Any help would be appreciated.
import java.util.*;
public class ProblemD {
static class Fireworks{
boolean occupied;
int dir;
public Fireworks(boolean occupied,int dir){
this.occupied=occupied;
this.dir=dir;
}
}
public static void fireworks(Fireworks f[][],int i,int j,int levels[],int n){
if(n<levels.length){
for(int k=1;k<levels[n];k++){
if(f[i][j].dir==0){
f[i+1][j]=new Fireworks(true,0);
i=i+1;
}
else if(f[i][j].dir==45){
f[i+1][j-1]=new Fireworks(true,45);
i=i+1;
j=j-1;
}
else if(f[i][j].dir==90){
f[i][j-1]=new Fireworks(true,90);
j=j-1;
}
else if(f[i][j].dir==135){
f[i-1][j-1]=new Fireworks(true,135);
i=i-1;
j=j-1;
}
else if(f[i][j].dir==180){
f[i-1][j]=new Fireworks(true,180);
i=i-1;
}
else if(f[i][j].dir==225){
f[i-1][j+1]=new Fireworks(true,225);
i=i-1;
j=j+1;
}
else if(f[i][j].dir==270){
f[i][j+1]=new Fireworks(true,270);
j=j+1;
}
else{
f[i+1][j+1]=new Fireworks(true,315);
i=i+1;
j=j+1;
}
}
//n++;
if(f[i][j].occupied && n<levels.length-1){
if(f[i][j].dir==0){
f[i+1][j-1]=new Fireworks(true,45);
f[i+1][j+1]=new Fireworks(true,315);
fireworks(f,i+1,j-1,levels,n+1);
fireworks(f,i+1,j+1,levels,n+1);
return;
}
else if (f[i][j].dir==45){
f[i][j-1]=new Fireworks(true,90);
f[i+1][j]=new Fireworks(true,0);
fireworks(f,i,j-1,levels,n+1);
fireworks(f,i+1,j,levels,n+1);
return;
}
else if(f[i][j].dir==90){
f[i+1][j-1]=new Fireworks(true,45);
f[i-1][j-1]=new Fireworks(true,135);
fireworks(f,i+1,j-1,levels,n+1);
fireworks(f,i-1,j-1,levels,n+1);
return;
}
else if(f[i][j].dir==135){
f[i][j-1]=new Fireworks(true,90);
f[i-1][j]=new Fireworks(true,180);
fireworks(f,i,j-1,levels,n+1);
fireworks(f,i-1,j,levels,n+1);
return;
}
else if(f[i][j].dir==180){
f[i-1][j-1]=new Fireworks(true,135);
f[i-1][j+1]=new Fireworks(true,225);
fireworks(f,i-1,j-1,levels,n+1);
fireworks(f,i-1,j+1,levels,n+1);
return;
}
else if(f[i][j].dir==225){
f[i-1][j]=new Fireworks(true,180);
f[i][j+1]=new Fireworks(true,270);
fireworks(f,i-1,j,levels,n+1);
fireworks(f,i,j+1,levels,n+1);
return;
}
else if(f[i][j].dir==270){
f[i-1][j+1]=new Fireworks(true,225);
f[i+1][j+1]=new Fireworks(true,315);
fireworks(f,i-1,j+1,levels,n+1);
fireworks(f,i+1,j+1,levels,n+1);
return;
}
else {
f[i+1][j]=new Fireworks(true,0);
f[i][j+1]=new Fireworks(true,270);
fireworks(f,i+1,j,levels,n+1);
fireworks(f,i,j+1,levels,n+1);
return;
}
}
}
else{
return;
}
}
public static void main(String[] args){
Fireworks f[][];
f=new Fireworks[500][500];
for(int i=0;i<500;i++){
for(int j=0;j<500;j++){
f[i][j]=new Fireworks(false,0);
}
}
Scanner sc=new Scanner(System.in);
int start=250;
int n=sc.nextInt();
int levels[]=new int[n];
f[start][start].occupied=true;
f[start][start].dir=0;
for(int i=0;i<n;i++){
levels[i]=sc.nextInt();
}
fireworks(f,start,start,levels,0);
int count=0;
for(int i=0;i<500;i++){
for(int j=0;j<500;j++){
if(f[i][j].occupied){
System.out.println(i+" "+j);
count++;
}
}
}
System.out.println(count);
}
}