I am trying to solve this problem on SPOJ
http://www.spoj.com/problems/STPAR/
My code is written in the following link:
My Solution
This is my code
public static void main(String[] args)throws IOException
{
Scan sc = new Scan();
PrintWriter pr = new PrintWriter(System.out);
while(true)
{
int n = sc.scanInt();
if(n == 0)
break;
ArrayStack<Integer> stack = new ArrayStack<>();
int[] arr = new int[n+1];
arr[0] = -1;
// without using an extra array
// for(int i=0; i<n; i++)
// arr[i+1] = sc.scanInt();
boolean isOrdered = true;
int count = 1, number;
for(int i=0; i<n; i++)
{
// System.out.println("i: " + i + " n: " +n + " count: " + count);
// number = arr[i+1];
number = sc.scanInt();
while(stack.peep() != null && stack.peep() == count)
{
// pr.print(stack.pop() + " ");
// System.out.println("From 2");
stack.pop();
count++;
}
if(number == count)
{
// System.out.println("From 1");
count++;
}
else
{
if(stack.peep() == null || stack.peep() > number)
{
// System.out.println("From 3");
stack.push(number);
}
else if(stack.peep() <= number)
{
// System.out.println("From 4");
isOrdered = false;
// break;
}
}
// else
// pr.println("From 5");
// System.out.println("stack: " + stack.toString());
}
// pr.println();
if(isOrdered)
pr.println("yes");
else
pr.println("no");
}
sc.close();
pr.close();
}
I have seen all the comments on that problem. All the mentioned test case are passed for my code, but still it is giving NZEC after submitting. I have also searched for solutions on the internet most of them looks like my solution. After trying to solve it for more than 2 hrs I am posting this question.
Please help me in debugging the my code.
Sorry if it looks naive!!
This is my solution to the question:
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
while(n!=0)
{
int arr[]=new int[n], k=1;
for(int i=0; i<n; i++)
arr[i]=sc.nextInt();
int stack[]=new int[n], top=-1, i=0;
Arrays.fill(stack, 0);
while(i<n)
{
if(arr[i]!=k)
{
if(top<0)
{
top=top+1;
stack[top]=arr[i];
i++;
}
else if(stack[top]==k)
{
top--;
k++;
}
else
{
top=top+1;
stack[top]=arr[i];
i++;
}
}
else
{
k++;
i++;
}
}
for(i=top; i>=0; i--, k++)
if(stack[i]!=k)
break;
if(k==n+1)
System.out.println("yes");
else
System.out.println("no");
n=sc.nextInt();
}
}
}
Related
I am trying to write a program that creates an array and fill it with int numbers(first method). In the end, it is supposed to see if a specific number is given in the array(second method). The problem is that the program does not run my if loops. I do not know why.
The variable x is the number the program is looking for in the array and pos the position of the number in the array
public class Program {
static int [] numbers= new int[100];
public static void main(String [] args) {
PrintWriter out = new PrintWriter(System.out);
arrayConstruction();
test(out);
out.flush();
}
public static void arrayConstruction() {
int x = 0;
for (int i = 0; i < numbers.length; i++) {
numbers[i] = x;
x++;
}
}
public static void test(PrintWriter out) {
int x = 17;
int pos = 0;
if(pos != numbers.length) {
if(numbers[pos] == x) {
out.println("The number was found!");
out.flush();
}
pos++;
}
else if(pos == numbers.length) {
out.println("The number does not exist!");
out.flush();
}
}
}
You forgot to add a loop to the test method, so it checks the first array's item only. E.g. you can use while loop.
public static void test(PrintWriter out) {
int x = 17;
int pos = 0;
while (true) {
if (pos != numbers.length) {
if (numbers[pos] == x) {
out.println("The number was found!");
return;
}
pos++;
} else if (pos == numbers.length) {
out.println("The number does not exist!");
return;
}
}
}
I think you should redesign your code by splitting different activities with separate methods. It makes your code clear to understand.
public class Main {
public static void main(String[] args) {
int[] arr = createArray(100);
System.out.println(isNumberExist(arr, 17) ? "The number was found!"
: "The number does not exist!");
}
public static int[] createArray(int total) {
int[] arr = new int[total];
Random random = new Random();
for (int i = 0; i < arr.length; i++)
arr[i] = random.nextInt(arr.length);
return arr;
}
public static boolean isNumberExist(int[] arr, int x) {
for (int i = 0; i < arr.length; i++)
if (arr[i] == x)
return true;
return false;
}
}
You should add a while loop to your test method, like this:
public static void test(PrintWriter out) {
int x = 17;
int pos = 0;
while(pos < numbers.length) {
if(numbers[pos] == x) {
out.println("The number was found!");
out.flush();
break;
}
pos++;
}
if(pos == numbers.length) {
out.println("The number does not exist!");
out.flush();
}
}
In your method, the if statement will only be executed once.
I need help with creating a table in for my blackjack, that records all games and also shows the average score of all games.I Have my code but im stuck on what to do to fix the code. Here are all the codes that im working with. Here is an example of what the output should look like:Pic of how output should look like
import java.util.*;
class Blackjack{
public static void main (String[] arg) {
Deck d = new Deck(); d.shuffle();
Hand h = new Hand();
//Score s = new Score(); //added for bonus
System.out.println(d);
System.out.println(d.hit());
System.out.println( d.decode(d.hit()) );
h.add(5);
h.add(10);
System.out.println(h.display());
while(true) {
System.out.print("Enter (n)ew hand, (h)it, or (q)uit: ");
Scanner scan = new Scanner (System.in);
// these variables are for collecting the information for the Score
int [] line = new int [5]; //added for Bonus
int handScore = 0; //added for Bonus
char c = scan.next().charAt(0);
if (c == 'n' || c == 'N') {
System.out.println(c);
h.reset();
if (d.currentIndex < 51){
int card= d.hit(); h.add(card);
card= d.hit(); h.add(card);
h.display();
System.out.println();
} else if (d.currentIndex > 51) {
System.out.println("--- NO CARDS LEFT ON DECK ---");
System.out.println();
break;
} else {
System.out.println("-- NOT ENOUGH CARDS LEFT ON DECK--");
System.out.println();
break;
}
} else if (c == 'h' || c == 'H') {
System.out.println(c);
if (d.currentIndex < 52){ //must be 52
int handValue = h.scoreInHand() ;
if (handValue > 21) { //already busted
System.out.println("--- GET A NEW HAND --- ");
System.out.println();
} else if (handValue == 21) {//already blackjack
System.out.println("--- BlackJack --- ");
System.out.println();
} else if (h.firstIndex > 4 ) {
System.out.println( "-- ALREADY 5 CARDS IN HAND ---");
h.display();
System.out.println( "--- GET A NEW HAND ---");
System.out.println();
} else if (h.firstIndex == 0) {
System.out.println("--- GET A NEW HAND FIRST ---");
System.out.println();
} else {
int card= d.hit(); h.add(card);
h.display(); System.out.println();
}
} else { // > or = 52
System.out.println("----- NO CARDS LEFT ON DECK -----");
System.out.println();
break;
}//end if (d.firstIndex < 52
} else if (c == 'q' || c == 'Q') {
System.out.println(c);
//same as the if(c == n), so it can collect the last game.
break;
}
} //while
//prints the scores of the games the user played while the game was run.
//System.out.print(s.display());System.out.println(); //added for Bonus
System.out.println("BYE!");
}//end main
}
class Hand{
private int []Hand;
public int firstIndex;
Hand(){
Hand=new int[5];
for (int i=0; i<Hand.length; i++)
Hand[i]=-1;
firstIndex=0;
}
public String display(){
String s="";
String empty="Hand is empty";
for (int i=0; i<firstIndex;i++)
s=s+" "+decode(Hand[i]);
if (s.length()==0)
s= empty;
String sih="";
int sihand= scoreInHand();
if(sihand>0&&sihand<21)
sih=""+sihand;
else if(sihand==21&&firstIndex==2)
sih="blackjack";
else if (sihand==21&&firstIndex>2)
sih=""+sihand;
else
sih="BUST";
System.out.println(s+"\n"+sih);
return s.trim();
}
public void reset(){
for (int i=0; i<Hand.length;i++)
Hand[i]=-1;
firstIndex=0;
}
public void add(int card){
Hand[firstIndex]=card;
firstIndex++;
}
public String decode2(int value){
String code=""+"HCDS".charAt(value/13)
+"23456789TJQA".charAt(value%13);
return code;
}
public String decode(int value){
String[] pattern={"Heart","Clubs","Diamond","Spades"};
String[] num={"two","three","four","five","six","seven","eight","nine","ten","jack","queen","king","ace"};
return num[value%13]+ " of " + pattern[value/13];
}
public int scoreInHand(){
int[] s={2,3,4,5,6,7,8,9,10,10,10,10};
boolean firstAce=true;
int value=0;
int sum=0;
for (int i=0; i<firstIndex; i++)
{
value=Hand[i]%13;
if (value==12)
{
if (firstAce)
{
value=11;
firstAce=false;
}
else
value=1;
}
else
value=s[value];
sum=sum+value;
}
return sum;
}
public String toString{
String s="";
for (int i=0; i<5; i++)
{
if (i<firstIndex)
s=s+" | " + decode2(Hand[i])+" ";
else
s=s+" ";
}
s=s+firstIndex;
return s;
}
}//(2,3,4,5,6,7,8,9,10,10,10,10,11)
class Deck{
private int[] cards;
public int currentIndex;
Deck(){
currentIndex=0;
cards=new int[52];
for (int i=0; i<cards.length; i++)
cards[i]=i;
}
public String toString(){
String s="";
for (int i=currentIndex;i<cards.length; i++)
{
/* s=s+" "+cards[i];*/
String code=decode(cards[i]);
s=s+" "+code;
}
return s;
}
public String decode(int value)
{
String code=""+"HCDS".charAt (value/13)
+"23456789TJQKA".charAt(value%13);
return code;
}
public void shuffle(){
int j=0;
for (int i=0;i<cards.length; i++)
{
j=(int)(52*Math.random());
swap(i,j);
}
}
public void swap(int i, int j){
int temp=cards[i];
cards[i]=cards[j];
cards[j]=temp;
}
public int hit(){
int i=cards[currentIndex];
currentIndex++;
return i;
}
}
class Score extends Deck{
private String [] cuts=new String [26];
private int gfirstIndex;
Score(){
cuts=new String[26];
gfirstIndex=0;
}
public void markScore(Hand h, int score)
{
String s="";
char fi;
String hand=h.toString();
int firstIndex;
fi=hand.charAt(hand.length()-1);
firstIndex=fi-'0';
hand=hand.substring(0,hand.length()-1);
s=s+" | "+(gfirstIndex+1)+(((gfirstIndex+1)<10)?" ":" ")|;
s=s+hand+" ";
s=s+"(score="+score+")";
if (score>21)
s=s+"(BUSTS)";
else if (score==21&&firstIndex==2)
s=s+"(BLACKJACK)";
cuts[gfirstIndex]=s;
gfirstIndex++;
}
}
I need help with this program because it is not compiling correctly.
The program is supposed to do this:
java PostfixToInfix
1 2 3 + *
1*(2+3)
I am getting these errors when compiling:
PostfixToInfix.java:64: error: bad operand types for binary operator '-'
s.push(o2 - o1);
^
first type: String
second type: String
PostfixToInfix.java:68: error: bad operand types for binary operator '*'
s.push(o1 * o2);
^
first type: String
second type: String
2 errors
How many I supposed to code this so that it works properly? I am unsure what is wrong with my code that it is not allowing it do the functions properly.
This is my code:
import java.util.Scanner;
import java.util.Stack;
public class PostfixToInfix
{
public static void main(String[] args)
{
String[] input = readExpr();
if(checkSyntax(input) == true)
{
int k = 0;
Stack<String> s = new Stack<>();
for(int i = 0; i < input.length; ++i)
{
if(isOperator(input[i]))
{
String o1;
String o2;
if(!(s.empty()))
{
o1 = s.pop();
}
else
{
for(int j = 0; j < i; ++j)
{
k += input[j].length() + 1;
}
System.out.println("Too few operands for " + input[i]);
writeExpr(input);
for(int l = 0; l < k; ++l)
{
System.out.print(" ");
}
System.out.println("^");
return;
}
if(!(s.empty()))
{
o2 = s.pop();
}
else
{
for(int j = 0; j < i; ++j)
{
k += input[j].length() + 1;
}
System.out.println("Too few operands for " + input[i]);
writeExpr(input);
for(int l = 0; l < k; ++l)
{
System.out.print(" ");
}
System.out.println("^");
return;
}
if(input[i].equals("+"))
{
s.push(o1 + o2);
}
else if(input[i].equals("-"))
{
s.push(o2 - o1);
}
else
{
s.push(o1 * o2);
}
}
else
{
s.push(input[i]);
}
}
String Result = s.pop();
if(!(s.empty()))
{
System.out.println("Too few operators to produce a single result");
}
else
{
System.out.println(Result);
}
}
} // end main
static String[] readExpr()
{
Scanner stdin = new Scanner(System.in);
String s = stdin.nextLine();
String[] sA = s.split(" ");
return sA;
}
static void writeExpr(String[] expr)
{
for(int i = 0; i < expr.length; ++i)
{
System.out.print(expr[i] + " ");
}
System.out.println();
}
static boolean isOperator(String s)
{
if(s.equals("+") || s.equals("-") || s.equals("*"))
{
return true;
}
return false;
}
static boolean checkSyntax(String[] expr)
{
int k = 0;
for(int i = 0; i < expr.length; ++i)
{
if(!(isOperator(expr[i])))
{
try
{
Double.parseDouble(expr[i]);
}
catch (Exception e)
{
for(int j = 0; j < i; ++j)
{
k += expr[j].length() + 1;
}
writeExpr(expr);
for(int l = 0; l < k; ++l)
{
System.out.print(" ");
}
System.out.println("^");
System.out.println("Not a number or valid operator");
return false;
}
}
}
return true;
}
} // end Postfix2
class StringStack
{
int top;
String[] pancake;
StringStack() //constructor for a new empty stack
{
top = 0;
pancake = new String[1000];
} // end DoubleStack
boolean empty() //whether the stack is empty
{
return top == 0;
} // end empty
String pop() //remove and return the top element; throw an error if empty
{
if(empty())
{
throw new Error("Error");
}
top -= 1;
return pancake[top];
} // end pop
void push(String x) //add x to the top of the stack
{
if(top < 1000)
{
pancake[top] = x;
top += 1;
}
else{
throw new Error("Error");
}
} // end push
} // end StringStack
Change you code like this.
if(input[i].equals("+"))
{
s.push(o1 + "+" + o2);
}
else if(input[i].equals("-"))
{
s.push(o2 + "-" + o1);
}
else
{
s.push(o1 + "*" + o2);
}
But the result for "1 2 3 + *" is "3+2*1".
It is another problem.
I'm making an assignment for my study, but everytime i execute my program I get an error. The error is "Exception in thread "main" java.util.NoSuchElementException".
I have no clue how to fix this, can anyone help me?
This is my program:
import java.util.Scanner;
class Cellulitis {
Scanner sc = new Scanner(System.in);
static char automata;//type A or B automaton
static int length; //length of row
static int gen; //generation
static boolean[] cellrow;
static boolean[] newCellrow;
void readGeneral() {//define different variables
automata = sc.next().charAt(0);
length = sc.nextInt() + 2;
gen = sc.nextInt();
cellrow = new boolean[length];
newCellrow = new boolean[length];
}
void readInitialConfiguration() {//input initial configuration
sc.next();
while (sc.hasNextInt()) {
cellrow[sc.nextInt()] = true;
}
}
void draw() {//prints out each cellrow
for(int i = 0; i < length-1; i++) {
if(cellrow[i]){
System.out.print('*');
}
else{
System.out.print(' ');
}
}
System.out.println("");
}
boolean newCellValueByA(int k){//calculates the state of each cell by the last cellrow by rules of automaton A
if (cellrow[k]) {
if((!cellrow[k-1] && cellrow[k+1]) || (cellrow[k-1] && !cellrow[k+1])){
return true;
}
else{
return false;
}
}
else{
if(!cellrow[k-1] && !cellrow[k+1]){
return false;
}
else{
return true;
}
}
}
boolean newCellValueByB(int k){//claculates the state of each cell by the last cellrow by rules of automaton B
if(cellrow[k]) {
if(!cellrow[k+1]){
return true;
}
else{
return false;
}
}
else{
if((!cellrow[k-1] && cellrow[k+1]) || (cellrow[k-1] && !cellrow[k+1])){
return true;
}
else{
return false;
}
}
}
void changeToNewRow() {//selects what rule will be used and makes the new cellrow
for(int i = 1; i < length - 1; i++){
if(automata == 'A'){
newCellrow[i] = newCellValueByA(i);
}
else if(automata == 'B'){
newCellrow[i] = newCellValueByB(i);
}
}
cellrow = newCellrow.clone();
}
void nextCellrow() {//draws the cellrow and jumps to the next cellrow
for(int i = 1; i < gen; i++){
draw();
changeToNewRow();
}
}
public static void main(String[] args) {
(new Cellulitis()).readGeneral();
(new Cellulitis()).readInitialConfiguration();
(new Cellulitis()).draw();
(new Cellulitis()).changeToNewRow();
(new Cellulitis()).nextCellrow();
}
}
This is the error i get:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Cellulitis.readInitialConfiguration(Cellulitis.java:28)
at Cellulitis.main(Cellulitis.java:108)
How can i fix this?
Thanks in advance!
As seen together in the answers, problem was because
Scanner sc = new Scanner(System.in);
had to be changed to
private static Scanner sc = new Scanner(System.in);
Hy there. Below you can see sagment of my code. So lets go to the problem.
int i is not returning correct values and i cannot figure it out why.
LIST: [AGRFT, AGRFT, ARNES, ASCII, ASEAN, Aaron, Abdul, Abdul]
So for example. User inputs AS***, the program should return i is at 2. However i am getting i is at 0.
If i remember right it should go like this:
User_input= AS***
User_input.lenght() should be 5
first it should be user_input.charAt(0)=='*' NO
second it should be user_input.charAt(1)=='*' NO
third it should be user_input.charAt(2)=='*' YES
BREAK
i is at 2.
SO what am i missing?
I am getting 0.
Oh and also at
for(i=0; i < user_input.length();i++){
i am getting warning that i++ is Dead code?
if (dolzina == 5) {
for(i=0; i < user_input.length();i++){
if (user_input.charAt(i)=='*');
break;
}
System.out.println("i is at "+ i);
this is my full code for refrence. What it does it reads from txt file add wor
public class proba {
public static void main(String[] args) {
String izbira;
int dolzina=0;
int i=0;
Scanner in = new Scanner(System.in);
String user_input;
Scanner input = new Scanner(System.in);
String regex;
List<String> list5 = new ArrayList<String>();
int beseda;
String prefix = null;
try {
File file = new File("sort.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String vrstica;
while ((vrstica = bufferedReader.readLine()) != null) {
if (vrstica.length() == 5) {
list5.add(vrstica);
}
}
System.out.println(list5);
do{
do {
System.out.println("Enter lenght of word:");
if (in.hasNextInt()) {
dolzina = in.nextInt();
} else if (in.hasNextLine()) {
System.out.printf("Wrong entry!%n ",
in.nextLine());
}
} while (dolzina <= 0);
Collections.sort(list5);
System.out.println("Enter a word for unknown character enter * :");
user_input = input.nextLine();
System.out.println("Sorted list: [length: " + list5.size() + "]");
if (dolzina == 5) {
for(i=0; i < user_input.length();i++){
if (user_input.charAt(i)=='*');
break;
}
System.out.println("i je"+ i);
prefix=user_input.substring(0,i);
System.out.println(prefix);
int start=binarySearchfirst(list5,prefix);
int end=binarySearchlast(list5,prefix);
System.out.println(start);
System.out.println(end);
for (int b=start;b<=end;b++)
{
user_input = user_input.replace("*", ".");
String s = (String) list5.get(b);
if (s.matches(user_input))
System.out.println(s);
}
}
dolzina=-1;
System.out.println("Ponovni vnos (da/ne):");
Scanner inn= new Scanner (System.in);
izbira = inn.next();
}while (izbira.equalsIgnoreCase("da"));
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}}
public static int binarySearchfirst(List<String> integerList, String prefix) {
int low = 0;
int high = integerList.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (integerList.get(mid).startsWith(prefix)) {
if (mid == 0 || !integerList.get(mid - 1).startsWith(prefix)) {
return mid;
} else {
high = mid - 1;
}
} else if (prefix.compareTo(integerList.get(mid)) > 0) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}
public static int binarySearchlast(List<String> integerList, String prefix) {
int low = 0;
int high = integerList.size()-1;
while (low <= high) {
int mid = (low+high)/2;
if (integerList.get(mid).startsWith(prefix)) {
if (mid == integerList.size()-1 || !integerList.get(mid+1).startsWith(prefix)) {
return mid;
}
else {
low = mid+1;
}
}
else if (prefix.compareTo(integerList.get(mid)) > 0) {
low = mid+1;
}
else {
high = mid-1;
}
}
return high;
}
}
You have an extra semi-colon after your if statement:
for(i=0; i < user_input.length();i++)
{ if (user_input.charAt(i)=='*');
break;
}
So the break is executed the first time through the loop no matter what. This is also why i++ is being reported as dead code...it's never being executed.