What this program is trying to do is go through numbers starting at "000000" going all the way up to "999999" and trying to find numbers which are palindromes. (eg: 0000000000).
I am having trouble with reversing the string and creating a valid result. The system adds the next 4 numbers creating a length 10 string.
import java.util.Arrays;
public class TestPalindrome{
public static void main(String []args){
int[] intArray = new int[6];
String[] strArray = new String[99];
String nextString;
int count = 0;
int nextnum;
int thisnum;
String thisString = "";
String s = "000000";
nextString = s;
do {
for(int i=0;i<6;i++) {
intArray[i] = Integer.parseInt(String.valueOf(nextString.charAt(i)));
}
int pos1 = intArray[5];
int pos2 = intArray[4]*10;
int pos3 = intArray[3]*100;
int pos4 = intArray[2]*1000;
int pos5 = intArray[1]*10000;
int pos6 = intArray[0]*100000;
nextnum = (pos1 + 1) + pos2 + pos3 + pos4 + pos5 + pos6;
thisnum = pos1 + pos2 + pos3 + pos4 + pos5 + pos6;
// If any of below values = 10, then number is not used
int d7 = ((4*intArray[0])+(10*intArray[1])+(9*intArray[2])+(2*intArray[3])+intArray[4]+(7*intArray[5])) % 11;
int d8 = ((7*intArray[0])+(8*intArray[1])+(7*intArray[2])+(intArray[3])+9*intArray[4]+(6*intArray[5])) % 11;
int d9 = ((9*intArray[0])+(intArray[1])+(7*intArray[2])+(8*intArray[3])+7*intArray[4]+(7*intArray[5])) % 11;
int d10 = ((intArray[0])+(2*intArray[1])+(9*intArray[2])+(10*intArray[3])+4*intArray[4]+(intArray[5])) % 11;
if (d7==10) { }
else if (d8==10) { }
else if (d9==10) { }
else if (d10==10) { }
else {
String s7 = Integer.toString(d7);
String s8 = Integer.toString(d8);
String s9 = Integer.toString(d9);
String s10 = Integer.toString(d10);
thisString = String.format("%06d", thisnum);
String concat = thisString + s7 + s8 + s9 + s10;
StringBuilder input = new StringBuilder(concat);
StringBuilder value = input.reverse();
if( value == input){
System.out.println("" + concat);
strArray[count] = concat;
count = count+1;
}
else {}
}
nextString = String.format("%06d", nextnum);
}
while (nextnum < 1000000 && nextnum > 000000);{
}
}
}
The problem is that it displays all numbers and not just palindromes. Any help is very welcomed.
I would simply put the numbers into strings. Then reverse the string and see if it equals the original.
String originalString = "110011";
String newString = new StringBuilder(originalString ).reverse().toString();
if (originalString.equals(newString )) {
//Is a palindrome
}
Note: Consider how you want to handle leading zeros. "11" is a palindrome, but if you need 4 values then "0011" is not.
One funny way is to use just one for-loop :
public static void main(String [] args){
for(String s = "000000"; !s.equals("1000000"); s = String.format("%06d",Integer.parseInt(s)+1)){
if(new StringBuilder(s).reverse().toString().equals(s))
System.out.println(s);
}
}
Related
I need to write encryptor.
The first letter needs to be converted to its ASCII code.
The second letter needs to be switched with the last letter
It should make from this "65 119esi 111dl 111lw 108dvei 105n 97n 111ka"
This "A wise old owl lived in an oak"
But when I check is char a digit i have an error.
public static void encryptThis(String text) {
String [] text_arr = text.split("\\s");
for(int i = 0; i < text_arr.length;i++){
String word = text_arr[i];
int length = word.length();
char [] char_word = new char [length];
char_word = word.toCharArray();
int k = 0;
length = char_word.length;
char [] numb = new char [length];
for (int j = 0;j < length; j++){
//In this place
if (Character.isDigit(char_word[i])){
numb[k] = char_word[i];
char_word[i] = ' ';
k++;
System.out.println(numb[k]);
}
}
int number = Integer.parseInt(numb.toString(),8);
String edit_char_word = char_word.toString();
String final_str = new StringBuffer(edit_char_word).reverse().toString().trim();
final_str = number + final_str;
text_arr[i] = final_str;
}
String fin_text = text_arr.toString();
return fin_text;
}
I wrote the encryptThis method from the beginning and tried to stay as simple to get readable code, here is
a full working example. As you did not mention what to do if a number is the first "letter" there is no
special handling for this - an "1" will be encrypted to (ascii) 49...
public class Main_So {
public static void main(String[] args) {
System.out.println("https://stackoverflow.com/questions/62460366/in-function-isdigit-java-lang-arrayindexoutofboundsexception-5");
String input = "A wise old owl lived in an oak";
String outputExpected = "65 119esi 111dl 111lw 108dvei 105n 97n 111ka";
System.out.println("input: " + input);
String output = encryptThis(input);
System.out.println("output encryptThis: " + output);
System.out.println("output expected: " + outputExpected);
}
public static String encryptThis(String text) {
String[] text_arr = text.split("\\s");
String outputString = "";
for (int i = 0; i < text_arr.length; i++) {
String word = text_arr[i];
int length = word.length();
int ascii0 = (int) word.charAt(0);
String word0 = String.valueOf(ascii0); // first char as ascii code
String subString = word.substring(1);
if (length > 2) { // switch chars if string length > 2
char char1 = word.charAt(1);
char charEnd = word.charAt(length - 1);
StringBuilder wordBuilder = new StringBuilder(subString);
wordBuilder.setCharAt(0, charEnd);
wordBuilder.setCharAt((length - 2), char1);
subString = String.valueOf(wordBuilder);
}
outputString = outputString + word0 + subString + " ";
}
return outputString;
}
}
This is the result:
input: A wise old owl lived in an oak
output encryptThis: 65 119esi 111dl 111lw 108dvei 105n 97n 111ka
output expected: 65 119esi 111dl 111lw 108dvei 105n 97n 111ka
I am reworking a class problem on For Loops and cannot gain a total out of a running score. I attempted to use the string comparisons, but that may be where the problem is. The assignment is:
"Simon Says" is a memory game where "Simon" outputs a sequence of 10 characters (R, G, B, Y) and the user must repeat the sequence. Create a for loop that compares the two strings starting from index 0. For each match, add one point to userScore. Upon a mismatch, exit the loop using a break statement. Ex: The following patterns yield a userScore of 4:
simonPattern: RRGBRYYBGY
userPattern: RRGBBRYBGY
import java.util.Scanner;
public class SimonSays {
public static void main (String [] args) {
String simonPattern = "";
String userPattern = "";
int userScore = 0;
int i = 0;
userScore = 0;
simonPattern = "RRGBRYYBGY";
userPattern = "RRGBBRYBGY";
/* Your solution begins here */
String ss1 = simonPattern.substring(0, 2);
String us1 = userPattern.substring(0, 2);
String ss2 = simonPattern.substring(2, 3);
String us2 = userPattern.substring(2, 3);
String ss3 = simonPattern.substring(4, 5);
String us3 = userPattern.substring(4, 5);
String ss4 = simonPattern.substring(6, 7);
String us4 = userPattern.substring(6, 7);
String ss5 = simonPattern.substring(8, 9);
String us5 = userPattern.substring(8, 9);
for (i = 0; i < simonPattern.length(); i++) {
if (ss1.equals(us1)) {
userScore = userScore + 1;
}
if (ss2.equals(us2)){
userScore = userScore + 1;
}
if (ss3.equals(us3)){
userScore = userScore + 1;
}
if (ss4.equals(us4)){
userScore = userScore + 1;
}
if (ss5.equals(us5)){
userScore = userScore + 1;
}
else{
break;
}
}
/* ^ Your solution goes here ^ */
System.out.println("userScore: " + userScore);
return;
}
}
your problem is in your for loop change if (ss1 == us1) to if (ss1.equals(us1)) same with the else if stucture because String is a reference type and not a primitive data type
primitive data types are int,double,long,float,byte,short,boolean,char and all objects are reference type
public static void main (String [] args)
{
String simonPattern = "";
String userPattern = "";
int userScore = 0;
userScore = 0;
simonPattern = "RRGBRYYBGY";
userPattern = "RRGBBRYBGY";
String[] simons = new String[5];
String[] users = new String[5];
int adder=2;
int location=0;
for(int i=0;i<simonPattern.length();i+=2)
{
simons[location]=simonPattern.substring(i,adder);
location++;
adder+=2;
}
adder=2;
location=0;
for(int i=0;i<userPattern.length();i+=2)
{
users[location]=userPattern.substring(i,adder);
location++;
adder+=2;
}
for (int i = 0; i < simonPattern.length(); i++)
{
if(users[i].equals(simons[i]))
userScore++;
}
System.out.println(userScore);
}
You might want to consider doing it by iterating through the userPattern instead like this:
int userScore = 0;
String simonPattern = "RRGBRYYBGY";
String userPattern = "RRGBBYYBGY";
for (int i = 0; i < userPattern.length(); i++) {
String p = userPattern.substring(0, 1 + i);
if (simonPattern.startsWith(p)) {
userScore = userScore + 1;
}
}
if (userScore < simonPattern.length()) {
System.out.println("You got " + userScore + " letters deep out of " +
simonPattern.length() + " before you made a mistake.");
}
else {
System.out.println("YOU WIN!");
}
You correctly changed the loop to iterate length of simonPattern. Now you just need to throw away the code inside the loop and actually use the iterator variable i.
To extract a single character from a string, you could continue to use substring(i, i+1) to get a String value, but for single characters it's better to use charAt(i).
Also, to increment a variable by 1, it's better to use userScore++, instead of userScore = userScore + 1, although that does work too.
This means that your code should be:
String simonPattern = "RRGBRYYBGY";
String userPattern = "RRGBBRYBGY";
int userScore = 0;
for (int i = 0; i < simonPattern.length(); i++) {
char c1 = simonPattern.charAt(i);
char c2 = userPattern.charAt(i);
if (c1 != c2)
break;
userScore++;
}
System.out.println("userScore: " + userScore); // prints 4
I am trying to solve this question: https://www.hackerrank.com/challenges/anagram
Here's my code:
import java.util.*;
public class Anagram {
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
int t = reader.nextInt();
while((t--) > 0)
{
String input = reader.nextLine();
if((input.length()) % 2 == 1)
System.out.println(-1);
else
{
int x = input.length();
int q = (int)(Math.floor((x / 2)));
String input1 = input.substring(0, q);
String input2 = input.substring(q, x);
int [] count2 = new int[26];
for(int i = 0; i < input2.length(); i++)
{
char ch2 = input2.charAt(i);
count2[ch2 - 'a']++;
}
// int [] count1 = new int[26];
for(int i = 0; i < input1.length(); i++)
{
char ch1 = input1.charAt(i);
if(count2[i] > 0)
count2[ch1 - 'a']--;
}
int count = 0;
for(int j = 0; j < 26; j++)
{
count = count + Math.abs(count2[j]);
}
System.out.println(count);
}
}
}
}
Sample Input
6
aaabbb
ab
abc
mnop
xyyx
xaxbbbxx
Expected Output
3
1
-1
2
0
1
My output
0
4
1
-1
2
2
Can anyone please tell me where it went wrong? I couldn't find the error...
Your first output always comes 0, because of this line:
int t = reader.nextInt();
followed by reader.nextLine();. Check this post for more details on that. For quick fix, change that line to:
int t = Integer.parseInt(reader.nextLine());
Now, let's start with the below two statements:
int x = input.length();
int q = (int)(Math.floor((x/2)));
No need to do a Math.floor there. x/2 is an integer division, and will give you integer result only.
Moving to the 2nd for loop. You used the following condition:
if(count2[i]>0)
count2[ch1-'a']--;
Notice the mistake there in condition? It should be count2[ch1 - 'a'] > 0. And also, you will miss the case where that count is not greater than 0, in which case you would have to do a ++. BTW, since you're anyways doing a Math.abs(), you don't need the condition. Just do a --:
for( int i = 0; i < input1.length(); i++ ) {
char ch1 = input1.charAt(i);
count2[ch1-'a']--;
}
BTW, the final result would be count / 2, and not count, because count contains the total mismatch from input1 to input2 and vice-versa. But we just have to fix one of them to match the other. So, just consider half the total mismatch.
You can use this to check if two strings are palindromes:
String original = "something";
String reverse = new StringBuilder(original).reverse().toString();
boolean anagram = original.equals(reverse);
As per your question, main logic could be changed to something like below.
Note - I have added only the main logic and excluded the user inputs here.
public static void main(String[] args) {
String str = "acbacccbaac";
int len = str.length();
String str1 = null, str2 = null;
if(len %2 != 0) {//check for odd length
str1 = str.substring(0, len/2);
str2 = str.substring(len/2+1, len);
}else {//check for even length
str1 = str.substring(0, len/2);
str2 = str.substring(len/2, len);
}
char[] arr1 = str1.toLowerCase().toCharArray();
Arrays.sort(arr1);
char[] arr2 = str2.toLowerCase().toCharArray();
Arrays.sort(arr2);
if(Arrays.equals(arr1, arr2))
System.out.println("Yes");
else
System.out.println("No");
}
I implemented this way for the same problem in my HackerRank profile, and works great.
This is my solution to the prob and it works!
static int anagram(String s) {
String a = "";
String b = "";
if (s.length() % 2 == 0) {
a = s.substring(0, s.length() / 2);
b = s.substring((s.length() / 2), s.length());
}
if (s.length() % 2 != 0) {
a = s.substring(0, s.length() / 2);
b = s.substring((s.length() / 2), s.length());
}
if (a.length() == b.length()) {
char[] aArray = a.toCharArray();
char[] bArray = b.toCharArray();
HashMap<Character, Integer> aMap = new HashMap<Character, Integer>();
HashMap<Character, Integer> bMap = new HashMap<Character, Integer>();
for (char c : aArray) { // prepare a Hashmap of <char>,<count> for first string
if (aMap.containsKey(c)) {
aMap.put(c, aMap.get(c) + 1);
} else {
aMap.put(c, 1);
}
}
for (char c : bArray) {// prepare a Hashmap of <char>,<count> for second string
if (bMap.containsKey(c)) {
bMap.put(c, bMap.get(c) + 1);
} else {
bMap.put(c, 1);
}
}
int change = 0;
for (Map.Entry<Character, Integer> entry : bMap.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
if (!aMap.containsKey(entry.getKey())) {
change += entry.getValue();
} else {
if (entry.getValue() > aMap.get(entry.getKey())) {
change += entry.getValue() - aMap.get(entry.getKey());
} else {
//change += entry.getValue();
}
}
}
return change;
} else {
return -1;
}
}
I have written this code to generate the bit stream corresponding to string a and then invert
specific bits in a bit stream.the variable cc gets an integer value in the processing before the code snippet.
However it gives Array Index Out Of Bounds Exception on the following line.
if(sb2.charAt(cc)=='1')
can anyone tell me what is the probable cause?
package abc1;
import java.util.Scanner;
public class abc2 {
public static void main(String s[]) {
String seckey = " ";
String cbs = " ";
String a = "Manikaparasher";
System.out.println("String originally:" + a);
char[] car = a.toCharArray();
StringBuilder sb = new StringBuilder();
for (char c : car) {
cbs = Integer.toBinaryString((int) c);
sb.append(cbs);
}
Scanner sc = new Scanner(System.in);
System.out.println(" Enter your passkey ");
int n = sc.nextInt();
int ul, ll;
double nv1, nv2, ns;
ll = n * 3;
ul = n * 7;
nv1 = ll + (Math.random() * (ul - ll));
nv2 = ll + (Math.random() * (ul - ll));
int nv11 = (int) nv1 % 7; //inversion bit
int nv22 = (int) nv2 % 3; //embedding bit
ns = ll + (Math.random() * (ul - ll));
int ns1 = (int) ns % 5;//start bit
if (nv11 == nv22) {
nv11++;
}
if (nv22 == ns) {
ns++;
}
if (nv11 == ns) {
nv11++;
}
seckey = "I" + nv11 + "E" + nv22 + "S" + ns1;
System.out.println(seckey);
System.out.println("old" + sb.toString());
System.out.println("nv11" + nv11);
StringBuilder sb2 = new StringBuilder(sb);
int cc = 0;
while (!cbs.isEmpty()) {
cc = cc + nv11;
if (sb2.charAt(cc) == '1') {
sb2.setCharAt(cc, '0');
sb2.append(sb);
} else {
sb2.setCharAt(cc, '1');
sb2.append(sb);
}
}
System.out.println("new" + sb2.toString());
}
}
You haven't put anything inside sb2 variable before calling
if(sb2.charAt(cc)=='1')
and what ever the cc value, it exceeds the sb2.length() size.
I have a problem wherein I have two strings, the length of one of which I will know only upon execution of my function. I want to write my function such that it would take these two stings and based upon which one is longer, compute a final string as under -
finalString = longerStringChars1AND2
+ shorterStringChar1
+ longerStringChars3and4
+ shorterStringChar2
+ longerStringChars5AND6
...and so on till the time the SHORTER STRING ENDS.
Once the shorter string ends, I want to append the remaining characters of the longer string to the final string, and exit. I have written some code, but there is too much looping for my liking. Any suggestions?
Here is the code I wrote - very basic -
public static byte [] generateStringToConvert(String a, String b){
(String b's length is always known to be 14.)
StringBuffer stringToConvert = new StringBuffer();
int longer = (a.length()>14) ? a.length() : 14;
int shorter = (longer > 14) ? 14 : a.length();
int iteratorForLonger = 0;
int iteratorForShorter = 0;
while(iteratorForLonger < longer) {
int count = 2;
while(count>0){
stringToConvert.append(b.charAt(iteratorForLonger));
iteratorForLonger++;
count--;
}
if(iteratorForShorter < shorter && iteratorForLonger >= longer){
iteratorForLonger = 0;
}
if(iteratorForShorter<shorter){
stringToConvert.append(a.charAt(iteratorForShorter));
iteratorForShorter++;
}
else{
break;
}
}
if(stringToConvert.length()<32 | iteratorForLonger<b.length()){
String remainingString = b.substring(iteratorForLonger);
stringToConvert.append(remainingString);
}
System.out.println(stringToConvert);
return stringToConvert.toString().getBytes();
}
You can use StringBuilder to achieve this. Please find below source code.
public static void main(String[] args) throws InterruptedException {
int MAX_ALLOWED_LENGTH = 14;
String str1 = "yyyyyyyyyyyyyyyy";
String str2 = "xxxxxx";
StringBuilder builder = new StringBuilder(MAX_ALLOWED_LENGTH);
builder.append(str1);
char[] shortChar = str2.toCharArray();
int index = 2;
for (int charCount = 0; charCount < shortChar.length;) {
if (index < builder.length()) {
// insert 1 character from short string to long string
builder.insert(index, shortChar, charCount, 1);
}
// 2+1 as insertion index is increased after after insertion
index = index + 3;
charCount = charCount + 1;
}
String trimmedString = builder.substring(0, MAX_ALLOWED_LENGTH);
System.out.println(trimmedString);
}
Output
yyxyyxyyxyyxyy
String one = "longwordorsomething";
String two = "short";
String shortString = "";
String longString = "";
if(one.length() > two.length()) {
shortString = two;
longString = one;
} else {
shortString = one;
longString = two;
}
StringBuilder newString = new StringBuilder();
int j = 0;
for(int i = 0; i < shortString.length(); i++) {
if((j + 2) < longString.length()) {
newString.append(longString.substring(j, j + 2));
j += 2;
}
newString.append(shortString.substring(i, i + 1));
}
// Append last part
newString.append(longString.substring(j));
System.out.println(newString);