Currently I have a program that asks for a string, for example "Hello stackoverflow!" and I'm trying to make it increment every individual character by a large, random number. The problem is, once the program gets to '~' it has to start going backwards, then once it gets '!' it has to switch again. (! is the first Ascii symbol, and ~ is the last, with numbers and letters in the middle.) So far this is what I have for the incrementing part, it isn't quite working though:
for(int i = 0; i < inputStringB.length(); i++){
currentChar = inputString.charAt(i);
for(int e = 0; e < 1000; e++){
if(currentChar == '!'){
switchIncrement = 1;
} else if(currentChar == '~') {
switchIncrement = 0;
}
switch(switchInc){
case 0: currentChar--;
inputStringB.setCharAt(i, currentChar);
break;
case 1: currentChar++;
inputStringB.setCharAt(i, currentChar);
break;
default: currentChar++;
inputStringB.setCharAt(i, currentChar);
break;
}
}
System.out.println(inputStringB);
}
When I input 'Hello' I receive: 'n#J&)' Which doesn't make sense considering 'Hello' contains two l's, so I would expect 'n#JJ)'
Any help would be awesome, thanks!
Full code:
import java.util.Scanner;
public class EncryptionMain {
public static void main(String args[]){
char currentChar;
String EorD;
int switchInc = 1; // 0 = BACK 1 = FORWARD
Scanner scanner = new Scanner(System.in);
System.out.println("Encrypt or decrypt: ");
EorD = scanner.next();
if(EorD.equalsIgnoreCase("e")){
System.out.println("Please enter text to encrypt: ");
String inputString = scanner.next();
System.out.println("Encrypting: '" + inputString + "' ");
System.out.println("...");
System.out.println("...");
System.out.println("...");
StringBuilder inputStringB = new StringBuilder(inputString);
for(int i = 0; i < inputStringB.length(); i++){
currentChar = inputStringB.charAt(i);
System.out.println(currentChar);
for(int e = 0; e < 1000; e++){
if(currentChar == '!'){
switchInc = 1;
}else if(currentChar == '~'){
switchInc = 0;
}
switch(switchInc){
case 0: currentChar--;
inputStringB.setCharAt(i, currentChar);
break;
default: currentChar++;
inputStringB.setCharAt(i, currentChar);
break;
}
}
System.out.println(inputStringB);
}
}else if(EorD.equalsIgnoreCase("d")){
System.out.println("Please enter text to decrypt: ");
String inputString = scanner.next();
System.out.println("Decrypting: '" + inputString + "' ");
System.out.println("...");
System.out.println("...");
System.out.println("...");
StringBuilder inputStringB = new StringBuilder(inputString);
for(int i = 0; i < inputStringB.length(); i++){
currentChar = inputStringB.charAt(i);
for(int e = 0; e < 1000; e++){
if(currentChar == '!'){
switchInc = 0;
}else if(currentChar == '~'){
switchInc = 1;
}
switch(switchInc){
case 0: currentChar++;
inputStringB.setCharAt(i, currentChar);
break;
case 1: currentChar--;
inputStringB.setCharAt(i, currentChar);
break;
default: currentChar--;
inputStringB.setCharAt(i, currentChar);
break;
}
}
inputStringB.setCharAt(i, currentChar);
System.out.println(inputStringB);
}
}
}
}
First I'm going to remove all of the I/O (except for outputting the result), get rid of the decryption piece for brevity, and write encrypt(String) and encrypt(char) as pure functions.
public class EncryptionMain {
public static void main(String args[]){
System.out.println(encrypt("Hello"));
}
static String encrypt(String plaintext) {
StringBuilder ciphertext = new StringBuilder(plaintext);
for (int i = 0; i < ciphertext.length(); i++) {
ciphertext.setCharAt(i, encrypt(ciphertext.charAt(i)));
}
return ciphertext.toString();
}
static char encrypt(char c) {
int switchInc = 1; // 0 = BACK 1 = FORWARD
for(int e = 0; e < 1000; e++){
if (c == '!') {
switchInc = 1;
} else if (c == '~') {
switchInc = 0;
}
switch (switchInc) {
case 0: c--; break;
default: c++; break;
}
}
return c;
}
}
And, whoops! - just by doing that, I accidentally fixed the bug. Here, I'll add it back:
public class EncryptionMain {
public static void main(String args[]){
System.out.println(encrypt("Hello"));
}
static String encrypt(String plaintext) {
StringBuilder ciphertext = new StringBuilder(plaintext);
for (int i = 0; i < ciphertext.length(); i++) {
ciphertext.setCharAt(i, encrypt(ciphertext.charAt(i)));
}
return ciphertext.toString();
}
static int switchInc = 1; // 0 = BACK 1 = FORWARD
static char encrypt(char c) {
for(int e = 0; e < 1000; e++){
if (c == '!') {
switchInc = 1;
} else if (c == '~') {
switchInc = 0;
}
switch (switchInc) {
case 0: c--; break;
default: c++; break;
}
}
return c;
}
}
Edit - Here's a working Caesar cipher I referred to in the comments below.
main/cipher/Cipher.java
package cipher;
public final class Cipher {
public Cipher(Range range, int key) {
this.range = range;
this.key = key;
}
public final Range range;
public final int key;
public String encrypt(String plaintext) {
return cipher(plaintext, key);
}
public String decrypt(String ciphertext) {
return cipher(ciphertext, -key);
}
String cipher(String in, int n) {
StringBuilder out = new StringBuilder(in.length());
for (int i = 0; i < in.length(); i++) {
out.append(range.shift(in.charAt(i), n));
}
return out.toString();
}
}
main/cipher/Range.java
package cipher;
public final class Range {
public final char min;
public final char max;
public final int size;
public static Range inclusive(char min, char max) {
return new Range(min, max);
}
Range(char min, char max) {
this.min = min;
this.max = max;
size = max - min + 1;
}
/** Shift c up by i places, wrapping around to the
* beginning of the range when it reaches the end. */
public char shift(char c, int i) {
return (char) (min + mod(c - min + i, size));
}
/** x mod a */
static int mod(int x, int a) {
return ((x % a) + a) % a;
}
}
test/cipher/CipherTest.java
package cipher;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
public class CipherTest {
#Test
public void testZeroKey() throws Exception {
Cipher cipher = new Cipher(Range.inclusive('a', 'z'), 0);
assertEquals(cipher.encrypt("abcxyz"), "abcxyz");
assertEquals(cipher.decrypt("abcxyz"), "abcxyz");
}
#Test
public void testOneKey() throws Exception {
Cipher cipher = new Cipher(Range.inclusive('a', 'z'), 1);
assertEquals(cipher.encrypt("abcxyz"), "bcdyza");
assertEquals(cipher.decrypt("bcdyza"), "abcxyz");
}
#Test
public void testSizePlusOneKey() throws Exception {
Cipher cipher = new Cipher(Range.inclusive('a', 'z'), 27);
assertEquals(cipher.encrypt("abcxyz"), "bcdyza");
assertEquals(cipher.decrypt("bcdyza"), "abcxyz");
}
}
test/cipher/RangeTest.java
package cipher;
import org.testng.Assert;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static cipher.Range.mod;
public class RangeTest {
#Test
public void testSize() {
Assert.assertEquals(Range.inclusive('a', 'c').size, 3);
}
#Test
public void testMod() throws Exception {
assertEquals(mod(-2, 5), 3);
assertEquals(mod(-1, 5), 4);
assertEquals(mod(0, 5), 0);
assertEquals(mod(1, 5), 1);
assertEquals(mod(2, 5), 2);
assertEquals(mod(3, 5), 3);
assertEquals(mod(4, 5), 4);
assertEquals(mod(5, 5), 0);
assertEquals(mod(6, 5), 1);
}
#Test
public void testShift() throws Exception {
Range r = Range.inclusive('a', 'd');
Assert.assertEquals(r.shift('a', -2), 'c');
Assert.assertEquals(r.shift('a', -1), 'd');
Assert.assertEquals(r.shift('a', 0), 'a');
Assert.assertEquals(r.shift('a', 1), 'b');
Assert.assertEquals(r.shift('a', 2), 'c');
Assert.assertEquals(r.shift('a', 3), 'd');
Assert.assertEquals(r.shift('a', 4), 'a');
Assert.assertEquals(r.shift('a', 5), 'b');
}
}
Related
Getting back into programming after many years, and build a simple "blackjack" program in Java.
I'm wondering if the way I structured the methods/objects is bad, using global static variables. The program seems to work fine, but there's no way to implement a "split" method without re-writing everything, since you can't pass the new "split" hands into the "hit" or "stand" functions.
I'm curious how others would structure this and what the flaws in my methodology were. Thanks!
import java.io.*;
import java.util.*;
public class BlackJack {
static int bankroll = 0;
static int bet = 1;
static int index = 0;
static CardDeck d = new CardDeck();
static ArrayList<Card> playerCards = new ArrayList<Card>();
static ArrayList<Card> playerCards2 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards3 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards4 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards5 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards6 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> dealerCards = new ArrayList<Card>(); //unused - was thinking of using for splitting
static int playerScore = 0;
static int dealerScore = 0;
static String action = "";
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
initializeBankroll();
while (bet != 0) {
startRound();
display();
if(checkBlackJacks()) continue;
while (playerScore <= 21) {
System.out.println("H - hit, S - stand, X - surrender, D - double down");
action = s.nextLine();
if (action.equals("H")) hit();
else if (action.equals("S")) {
stand();
break;
}
else if (action.equals("X")) surrender();
else if (action.equals("D")) {
doubleDown();
break;
}
}
eval();
}
}
public static int score (ArrayList<Card> list) {
int ret = 0;
int acecounter = 0;
for (int i=0; i<list.size(); i++) {
if (list.get(i).getVal()>1) {
ret += Math.min(10, list.get(i).getVal());
}
else { //An ace
ret += 11;
acecounter++;
}
}
while(ret >21 && acecounter >0) {
ret -= 10;
acecounter -= 1;
}
return ret;
}
public static void dealToPlayer() {
playerCards.add(d.getCard(index));
index++;
}
public static void dealToDealer() {
dealerCards.add(d.getCard(index));
index++;
}
public static void display() {
System.out.println("PLAYER CARDS:");
String playerCardString = "";
for (int i=0; i<playerCards.size(); i++) {
playerCardString += playerCards.get(i).toString();
playerCardString += " ";
}
System.out.println(playerCardString);
System.out.println("DEALER CARD:");
System.out.println(dealerCards.get(0).toString());
}
public static void hit() {
dealToPlayer();
reScore();
display();
}
public static void surrender() {
if(playerCards.size()>2) {
System.out.println("You can't do that");
return;
}
bankroll -= (bet / 2);
playerScore = 100; //surrender
}
public static void reScore() {
playerScore = score(playerCards);
dealerScore = score(dealerCards);
}
public static void stand() {
try {
System.out.println("DEALER DOWNCARD: " + dealerCards.get(1).toString());
Thread.sleep(1000);
while (dealerScore <17) {
dealToDealer();
System.out.println(dealerCards.get(dealerCards.size()-1).toString());
reScore();
System.out.println("DEALER SCORE " + Integer.toString(dealerScore));
Thread.sleep(1000);
}
}catch(Exception E) {
System.out.println("Exception");
}
}
public static void doubleDown() {
if(playerCards.size()>2) {
System.out.println("You can't do that, hitting instead");
hit();
if(playerScore<=21) stand();
return;
}
if( bet * 2 > bankroll) {
System.out.println("Doubling for less...");
bet = bankroll;
hit();
if(playerScore<=21) stand();
return;
}
bet *= 2;
hit();
if(playerScore<=21) stand();
}
public static void split(ArrayList<Card> splitarray, int splitcount) { //INCOMPLETE. How to get this to work?
if(splitarray.size()>2 || bet * (splitcount+1) > bankroll || splitarray.get(1).getVal() != splitarray.get(0).getVal()) {
System.out.println("Can't split. Hitting instead");
hit();
}
ArrayList<Card> s1 = new ArrayList<Card>();
ArrayList<Card> s2 = new ArrayList<Card>();
s1.add(splitarray.get(0));
s2.add(splitarray.get(1));
}
public static void eval() {
if (playerScore==100) { //indicates a surrender, and bankroll has already been adjusted
return;
}
if (playerScore>21) {
System.out.println("BUST");
bankroll -= bet;
return;
}
if (dealerScore>21) {
System.out.println("DEALER BUST");
bankroll += bet;
return;
}
if (playerScore > dealerScore) {
System.out.println("WIN");
bankroll += bet;
return;
}
if (playerScore < dealerScore) {
System.out.println("LOSE");
bankroll -= bet;
return;
}
System.out.println("PUSH");
return;
}
public static void newhand() {
d.shuffle();
playerCards.clear();
dealerCards.clear();
index = 0;
reScore();
}
public static boolean checkBlackJacks() {
if(playerScore == 21) {
if(dealerCards.get(0).getVal()==1) {
System.out.println("Even money? Y / N");
String even = s.nextLine();
if (even=="Y"){
bankroll += bet;
newhand();
return true;
}
}
if(dealerScore != 21) {
System.out.println("BlackJack");
bankroll += (1.5 * bet);
newhand();
return true;
}
else {
System.out.println("Push - Mutual Blackjack");
newhand();
return true;
}
}
if(dealerCards.get(0).getVal()==1) { //insurance
System.out.println("Insurance? Type wager or 0, up to half your bet");
int insuranceBet = s.nextInt();
if (insuranceBet > bankroll) insuranceBet = bankroll;
if (insuranceBet > (bet / 2)) insuranceBet = bet / 2;
if (dealerScore == 21) bankroll += (insuranceBet * 2);
else bankroll -= insuranceBet;
}
if(dealerScore==21) {
System.out.println("Dealer Blackjack");
bankroll -= bet;
newhand();
return true;
}
return false;
}
public static void initializeBankroll() {
System.out.println("Enter your buy-in");
bankroll = s.nextInt();
}
public static void startRound() {
newhand();
System.out.println("Money remaining:" + Integer.toString(bankroll));
System.out.println("Enter your bet");
bet = s.nextInt();
if (bet>bankroll) bet=0;
dealToPlayer();
dealToDealer();
dealToPlayer();
dealToDealer();
reScore();
}
}
___________________
public class Card {
int val; //1 = Ace, 11 = Jack, 12 = Queen, 13 = King
int suit; //1 = Club, 2 = Diamond, 3 = Heart, 4 = Spade
public Card() {
this(1,1);
}
public Card(int val, int suit) {
this.val = val;
this.suit = suit;
}
public int getSuit(){
return suit;
}
public int getVal() {
return val;
}
public void setVal(int a) {
if(a>=1 && a<= 13) val = a;
}
public void setSuit(int a) {
if (a>=1 && a<=4) suit = a;
}
public String toString() {
String valString = "";
String suitString = "";
String ret = "";
switch(val) {
case 1: valString = "A"; break;
case 10: valString = "T"; break;
case 11: valString = "J"; break;
case 12: valString = "Q"; break;
case 13: valString = "K"; break;
default: valString = Integer.toString(val);
}
switch(suit) {
case 1: suitString = "c"; break;
case 2: suitString = "d"; break;
case 3: suitString = "h"; break;
case 4: suitString = "s"; break;
default: suitString = "ERROR"; break;
}
ret = valString + suitString;
return ret;
}
}
______________________
public class CardDeck{
Card[] deck;
public CardDeck(){
int k=0;
deck = new Card[52];
for (int i=0; i<13; i++){
for (int j=0; j<4; j++){
Card c = new Card(i+1,j+1);
deck[k]=c;
k++;
}
}
shuffle();
}
public void shuffle(){
Card[] deckCopy = new Card[52];
boolean[] flags = new boolean[52];
for (int i=0; i<flags.length; i++) flags[i]=false;
int numConverted=0;
while(numConverted<52){
int num = (int)(Math.random() * 52);
if (flags[num]==false){
deckCopy[numConverted]=deck[num];
numConverted++;
flags[num]=true;
}
}
deck = deckCopy;
} //end shuffle
public String toString() {
String ret = "";
for (int i = 0; i<deck.length; i++) {
ret += deck[i].toString();
ret += " ";
}
return ret;
}
public Card getCard(int a) {
if (a<0 || a > 51) return null;
else return deck[a];
}
public int getSuit(int a) {
if (a<0 || a > 51) return 0;
else return deck[a].getSuit();
}
public int getVal(int a) {
if (a<0 || a > 51) return 0;
else return deck[a].getVal();
}
}
I have opened an account for Ridit, one of 7-years-old students learning Java at SPOJ. The first task i gave to him was PALIN -The Next Palindrome. Here is the link to this problem- PALIN- The next Palindrome- SPOJAfter i explained it to him, he was able to solve it mostly except removing the leading zeros, which i did. Following is his solution of the problem -
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Scanner in = new Scanner(System.in);
int t = Integer.parseInt(in.nextLine());
String[] numbersInString = new String[t];
for (int i = 0; i <t; i++) {
String str = in.nextLine();
numbersInString[i] = removeLeadingZeros(str);
}
for (int i = 0 ; i<t; i++) {
int K = Integer.parseInt(numbersInString[i]);
int answer = findTheNextPalindrome(K);
System.out.println(answer);
}
}catch(Exception e) {
return;
}
}
static boolean isPalindrome(int x) {
String str = Integer.toString(x);
int length = str.length();
StringBuffer strBuff = new StringBuffer();
for(int i = length - 1;i>=0;i--) {
char ch = str.charAt(i);
strBuff.append(ch);
}
String str1 = strBuff.toString();
if(str.equals(str1)) {
return true;
}
return false;
}
static int findTheNextPalindrome(int K) {
for(int i = K+1;i<9999999; i++) {
if(isPalindrome(i) == true) {
return i;
}
}
return -1;
}
static String removeLeadingZeros(String str) {
String retString = str;
if(str.charAt(0) != '0') {
return retString;
}
return removeLeadingZeros(str.substring(1));
}
}
It is giving correct answer in Eclipse on his computer, but it is failing in SPOJ. If someone helps this little boy in his first submission, it will definitely make him very happy. I couldn't find any problem with this solution... Thank you in advance...
This might be helpful
import java.io.IOException;
import java.util.Scanner;
public class ThenNextPallindrom2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int t = 0;
Scanner sc = new Scanner(System.in);
if(sc.hasNextInt()) {
t = sc.nextInt();
}
sc.nextLine();
int[] arr, arr2;
while(t > 0) {
t--;
String s = sc.nextLine();
arr = getStringToNumArray(s);
if(all9(arr)) {
arr2 = new int[arr.length + 1];
arr2[0] = 1;
for(int i=0;i<arr.length;i++) {
arr2[i+1] = 0;
}
arr2[arr2.length -1] = 1;
arr = arr2;
} else{
int mid = arr.length/ 2;
int left = mid-1;
int right = arr.length % 2 == 1 ? mid + 1 : mid;
boolean left_small = false;
while(left >= 0 && arr[left] == arr[right]) {
left--;
right++;
}
if(left < 0 || arr[left] < arr[right]) left_small = true;
if(!left_small) {
while(left >= 0) {
arr[right++] = arr[left--];
}
} else {
mid = arr.length/ 2;
left = mid-1;
int carry = 1;
if(arr.length % 2 == 0) {
right = mid;
} else {
arr[mid] += carry;
carry = arr[mid]/10;
arr[mid] %= 10;
right = mid + 1;
}
while(left >= 0) {
arr[left] += carry;
carry = arr[left] / 10;
arr[left] %= 10;
arr[right++] = arr[left--];
}
}
}
printArray(arr);
}
}
public static boolean all9(int[] arr) {
for(int i=0;i<arr.length;i++) {
if(arr[i] != 9)return false;
}
return true;
}
public static void printArray(int[] arr) {
for(int i=0;i<arr.length;i++) {
System.out.print(arr[i]);
}
System.out.println();
}
public static int[] getStringToNumArray(String s) {
int[] arr = new int[s.length()];
for(int i=0; i<s.length();i++) {
arr[i] = Integer.parseInt(String.valueOf(s.charAt(i)));
}
return arr;
}
}
To shrink a string "abbcccbfgh" by removing consecutive k characters till no removal can be done.
e.g. for k=3 output for the above string will be "afgh".
Please note that K and string both are dynamic i.e provided by the user.
I wrote the below program but I couldn't complete it. Please help.
public class Test {
public static void main(String[] args) {
String str = "abbcccbfgh";
int k = 3;
String result = removeConsecutive(str, k);
System.out.print("result is " + result);
}
private static String removeConsecutive(String str, int k) {
String str1 = str + "";
String res = "";
int len = str.length();
char c1 = 0, c2 = 0;
int count = 0;
for (int i = 0; i < len - 1; i++) {
c1 = str.charAt(i);
c2 = str.charAt(i + 1);
if (c1 == c2) {
count++;
} else {
res = res + String.valueOf(c1);
count = 0;
}
if (count == k-1) {
//remove String
}
}
return res;
}
I suggest to do it with regex:
int l = 0;
do {
l = str.length();
str = str.replaceAll("(.)\\1{" + n + "}", "");
} while (l != str.length());
n = k - 1
(.)\1{2} means any character followed by n same characters. \1 means the same character as in group #1
Is it okey to have recursion ?
public class Test {
public static void main(String[] args) {
String str = "abbcccbfgh";
int k = 3;
String result = removeConsecutive(str, k);
System.out.print("result is " + result);
}
private static String removeConsecutive(String str, int k) {
String ret = str;
int len = str.length();
int count = 0;
char c1 = 0 ;
char c2 = 0;
char last = 0 ;
for (int i = 0; i < ret.length()-1; i++) {
last = c1 ;
c1 = str.charAt(i);
c2 = str.charAt(i + 1);
if (c1 == c2 ) {
if( count > 0 ) {
if( last == c1 ) {
count ++ ;
}
else {
count = 0;
}
}
else {
count++;
}
} else {
count = 0;
}
if (count == k-1) {
int start = ((i+1) - k) + 1 ;
String one = str.substring(0, start) ;
String two = str.substring(start+k);
String new1 = one + two ;
//recursion
ret = removeConsecutive(new1, k) ;
count = 0;
}
}
return ret;
}
}
You can do it with a stack. For each character ch in the string, push it to the stack, if there's 3 consecutive same characters, pop them all. In the end, convert the stack to a string. You can improve the program a little by using a special stack that remembers the number of occurrences of each element.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class Reduce implements Function<String, String> {
private final int k;
public Reduce(final int k) {
if (k <= 0) {
throw new IllegalArgumentException();
}
this.k = k;
}
#Override
public String apply(final String s) {
Stack<Character> stack = new Stack<>();
for (Character ch : s.toCharArray()) {
stack.push(ch);
if (stack.topCount() == k) {
stack.pop();
}
}
return stack.toString();
}
public static void main(String[] args) {
Reduce reduce = new Reduce(3);
System.out.println(reduce.apply("abbcccbfgh"));
}
private static class Stack<T> {
private class Node {
private T value;
private int count;
Node(T value) {
this.value = value;
this.count = 1;
}
}
private List<Node> nodes = new ArrayList<>();
public void push(T value) {
if (nodes.isEmpty() || !top().value.equals(value)) {
nodes.add(new Node(value));
} else {
top().count++;
}
}
public int topCount() {
return top().count;
}
public void pop() {
nodes.remove(nodes.size()-1);
}
private Node top() {
return nodes.get(nodes.size()-1);
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
nodes.forEach(n->{
for (int i = 0; i < n.count; i++) {
sb.append(n.value);
}
});
return sb.toString();
}
}
}
This is the problem :
Input
The first line of input will contain the number of test cases, T (1 ≤ T ≤ 50). Each of the following T
lines contains a positive integer N that is no more than 80 digits in length.
Output
The output of each test case will be a single line containing the smallest palindrome that is greater
than or equal to the input number.
Sample Input
2
42
321
Sample Output
44
323
I keep having time limit exceeded when i submit to the code to online judge ( 3 seconds limit)
class Main {
static String ReadLn (int maxLg)
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
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));
}
static boolean isPalandriome(String s){
String newString = "";
for(int i =s.length()-1;i >= 0; i--){
newString += s.charAt(i);
}
if(newString.equals(s))
return true;
else
return false;
}
public static void main(String[] args) {
BigInteger entredNumber;
String input;
input = Main.ReadLn(10);
int tests = Integer.parseInt(input);
List<BigInteger> numbers = new ArrayList<BigInteger>();
for (int i =0;i<tests;i++)
{
input = Main.ReadLn(100);
entredNumber = new BigInteger(input);
numbers.add(entredNumber);
}
for(int i=0;i<tests;i++){
BigInteger number = numbers.get(i);
while(!isPalandriome(String.valueOf(number))){
number = number.add(BigInteger.ONE);
}
System.out.println(number);
}
}
}
I can't find what takes too much time in my code.
At last coded Hope you find this helpful took 0.10 seconds
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
CustomReader cr = new CustomReader(1000000);
int T = cr.nextInt(), fIndex, bIndex, fStartIndex, bStartIndex;
StringBuilder output = new StringBuilder();
byte[] input;
boolean isAppend1 = false;
for (int i = 0; i < T; i++) {
input = cr.nextInput();
fStartIndex = bStartIndex = cr.getCurrInputLength() / 2;
isAppend1 = false;
if (cr.getCurrInputLength() % 2 == 0) {
bStartIndex--;
}
fIndex = fStartIndex;
bIndex = bStartIndex;
while (input[bIndex] == input[fIndex]) {
if (bIndex - 1 < 0) {
break;
} else {
bIndex--;
fIndex++;
}
}
if (input[bIndex] > input[fIndex]) {
while (bIndex >= 0) {
input[fIndex++] = input[bIndex--];
}
} else {
if (input[bStartIndex] < 57) {
input[bStartIndex] = (byte) (input[bStartIndex] + 1);
} else {
bIndex = bStartIndex;
while (bIndex >= 0 && input[bIndex] == 57) {
input[bIndex] = 48;
bIndex--;
}
if (bIndex >= 0) {
input[bIndex] = (byte) (input[bIndex] + 1);
} else {
input[0] = 49;
if (fStartIndex != bStartIndex) {
input[fStartIndex] = 48;
bStartIndex = fStartIndex;
} else {
input[fStartIndex + 1] = 48;
bStartIndex = fStartIndex = fStartIndex + 1;
}
isAppend1 = true;
}
}
while (bStartIndex > -1) {
input[fStartIndex++] = input[bStartIndex--];
}
}
for (int j = 0; j < cr.getCurrInputLength(); j++) {
output.append((char) input[j]);
}
if (isAppend1) {
output.append("1");
}
output.append("\n");
}
System.out.print(output.toString());
// genInput();
}
private static class CustomReader {
private byte[] buffer;
private byte[] currInput = new byte[1000000];
private int currInputLength;
private int currIndex;
private int validBytesInBuffer;
CustomReader(int buffSize) {
buffer = new byte[buffSize];
}
public int nextInt() throws IOException {
int value;
byte b;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
break;
}
}
value = b - 48;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
value = (value * 10) + (b - 48);
} else {
break;
}
}
return value;
}
public byte[] nextInput() throws IOException {
byte b;
this.currInputLength = 0;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
break;
}
}
currInput[currInputLength++] = b;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
currInput[currInputLength++] = b;
} else {
break;
}
}
return this.currInput;
}
public int getCurrInputLength() {
return this.currInputLength;
}
private byte getNextByte() throws IOException {
if (currIndex == buffer.length || currIndex == validBytesInBuffer) {
validBytesInBuffer = System.in.read(buffer);
currIndex = 0;
}
return buffer[currIndex++];
}
}
public static void genInput() {
for (int i = 0; i < 100; i++) {
System.out.println((int) (Math.random() * 1000000000));
}
}
}
I'm a bit new to java, I'm having one error with my Java program that I can't seem to fix, very easy solution I just can't see it haha. How can I fix this? I tried a few things but it adds more errors on top of each other. Thank you all!
import java.io.*;
import java.util.*;
class Node {
public char ch;
public Node leftChild;
public Node rightChild;
Node(char c) {
ch = c;
}
public void displayNode() {
System.out.print(ch);
}
}
class Tree {
public Node root;
public Tree(Node nd) {
root = nd;
}
public void traverse(int traverseType) {
switch (traverseType) {
case 1:
System.out.print(" \n Preorder traversal : ");
preOrder(root);
break;
case 2:
System.out.print(" \n Inorder traversal : ");
inOrder(root);
break;
case 3:
System.out.print(" \n Postorder traversal : ");
postOrder(root);
break;
}
System.out.println();
}
private void preOrder(Node localRoot) {
if (localRoot != null) {
localRoot.displayNode();
preOrder(localRoot.leftChild);
preOrder(localRoot.rightChild);
}
}
private void inOrder(Node localRoot) {
if (localRoot != null) {
inOrder(localRoot.leftChild);
localRoot.displayNode();
inOrder(localRoot.rightChild);
}
}
private void postOrder(Node localRoot) {
if (localRoot != null) {
postOrder(localRoot.leftChild);
postOrder(localRoot.rightChild);
localRoot.displayNode();
}
}
public void displayTree() {
Stack globalStack = new Stack();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out.println(" ...................................................... ");
while (isRowEmpty == false) {
Stack localStack = new Stack();
isRowEmpty = true;
for (int j = 0; j < nBlanks; j++)
System.out.print(' ');
while (globalStack.isEmpty() == false) {
Node temp = (Node) globalStack.pop();
if (temp != null) {
temp.displayNode();
localStack.push(temp.leftChild);
localStack.push(temp.rightChild);
if (temp.leftChild != null || temp.rightChild != null)
isRowEmpty = false;
} else {
System.out.print("-");
localStack.push(null);
localStack.push(null);
}
for (int j = 0; j < nBlanks * 2 - 1; j++)
System.out.print(' ');
}
System.out.println();
nBlanks / = 2;
while (localStack.isEmpty() == false)
globalStack.push(localStack.pop());
}
System.out.println(" ...................................................... ");
}
}
class BottomUp {
private String inString;
private int strlen;
private Tree[] treeArray;
private Tree aTree;
private int numNodes;
BottomUp(String s) {
inString = s;
strlen = inString.length();
treeArray = new Tree[100];
for (int j = 0; j < strlen; j++) {
char ch = inString.charAt(j);
Node aNode = new Node(ch);
treeArray[j] = new Tree(aNode);
}
}
public Tree getTree() {
return aTree;
}
public void balanced() {
numNodes = strlen;
while (numNodes > 1) {
int i = 0;
int j = 0;
Tree[] tempArray = new Tree[100];
for (j = 0; j < strlen - 1; j++) {
Tree tree1 = treeArray[j];
Tree tree2 = treeArray[j + 1];
Node aNode = new Node('+');
aTree = new Tree(aNode);
aTree.root.leftChild = tree1.root;
aTree.root.rightChild = tree2.root;
tempArray[i++] = aTree;
numNodes--;
j++;
}
if (strlen % 2 == 1) {
Tree tree1 = treeArray[j];
Node aNode = new Node('+');
aTree = new Tree(aNode);
aTree.root.leftChild = tree1.root;
tempArray[i++] = aTree;
}
treeArray = tempArray;
strlen = numNodes;
}
aTree = treeArray[0];
}
}
class BottomUpApp {
public static void main(String[] args) throws IOException {
BottomUp bup;
Tree theTree = null;
int value;
String str;
while (true) {
System.out.print(" Enter first letter of ");
System.out.print(" balanced , show , or traverse : ");
int choice = getChar();
switch (choice) {
case 'b':
System.out.print(" Enter string : ");
str = getString();
bup = new BottomUp(str);
bup.balanced();
theTree = bup.getTree();
break;
case 's':
theTree.displayTree();
break;
case 't':
System.out.print(" Enter type 1, 2 or 3 : ");
value = getInt();
theTree.traverse(value);
break;
default:
System.out.print(" Invalid entry \n ");
}
}
}
public static String getString() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
public static char getChar() throws IOException {
String s = getString();
return s.charAt(0);
}
public static int getInt() throws IOException {
String s = getString();
return Integer.parseInt(s);
}
}
ERROR CODE
Node.java:112: error: illegal start of expression
nBlanks / = 2 ;
^
1 error
The Java operator /= must be typed without spaces in between, or else it will be parsed as 2 separate operators, / and =, which is a syntax error. Try
nBlanks /= 2 ;