JAVA (I've tried reversing two String using for loop - windows

(1) Can anyone tell me how do I declare array org[] and rev[] where I'm storing my two strings the original and reverse string?
(2) When I'm trying to store the characters of original String in org[] using charAt() they are throwing me an error.
Can anyone help me out on reversing two strings without making use of reverse() instead making use of for loop ?

String a = "12345";
char [] original= a.toCharArray();
char[] reverse = new char[a.length()];
int j =0;
for(int i=reverse.length-1; i>=0; i--) {
reverse[j] = original[i];
j++;
}
System.out.println(new String(reverse));

Here's a quick method you can use (must go inside your class):
public static void getCharacters(String input, char[] forward, char[] reverse)
{
for(int i = 0; i < input.length(); i++)
{
forward[i] = input.charAt(i);
reverse[i] = input.charAt(input.length() - 1 - i);
}
}
This assumes that forward and reverse were already allocated, and were initialized to the length of the string input. Example usage from inside another method:
String input = "Hello, world!";
char[] forward = new char[input.length()];
char[] reverse = new char[input.length()];
getCharacters(input, forward, reverse);
// forward and reverse now contain the characters from input

Related

Java (move point in string)

I have a string = "abc";
And also I have a point ".".
How I can move this point "." in that string("abc").
Example :
Input date = "abc".
Output date = "abc", "a.bc", "ab.c", "a.b.c".
Thanks'.
public class MovePoint {
public static void main(String[] args) {
String str = "abcd";
String str1 = ".";
String[] ara = new String[str.length()];
for (int i = 0; i < str.length(); i++) {
ara[i] = str.substring(i, 1) + str1 + str.substring(1, 2);
System.out.print(Arrays.toString(ara));
}
}
}
Here is one way to do it. This uses StringBuilder as well as a plain char array to avoid having another loop over the array to build the last String, but it therefore consumes more memory.
First I print the first desired output, which is just the unmodified input String. Then I create a StringBuilder which can hold all chars from the input + one more for the chosen separator to avoid unnecessary array resizing. Then I initialize the StringBuilder so that it is in the form of the second desired ouput [char, sep, char, ...]. I am using StringBuilder here because it is just more convenient as it has the append() function that I need here.
Last but not least I also initialize a char array which will hold the values for the last String to avoid having to iterate over the array twice to generate that.
Now I loop over over the StringBuilder starting from one (as its already initialize to the first result with separator) to the last character. In this loop I do three things.
Print out the current value of StringBuilder
Swap the separator with the next character in the StringBuilder
Put the character and separator to the correct position in the char array as required for the last string
After the loop the last desired output is computed and I just have to print it to the console.
Runtime for this in BigO-notation would be O(n).
public static void main(String[] args) {
String str = "abcd";
char sep = '.';
movePoint(str, sep);
}
public static void movePoint(String str, char sep){
// print first desired output
System.out.println(str);
// String builder that can hold str.length + 1 characters, so no unnecessary resizing happens
var sb = new StringBuilder(str.length() + 1);
// fill with first char
sb.append(str.charAt(0));
// add separator
sb.append(sep);
// add rest of the string
sb.append(str.substring(1));
// Array that holds the last string
var lastStr = new char[str.length() + str.length() - 1];
for (int i = 1; i < sb.capacity() - 1; i++) {
System.out.println(sb);
// build current string
// swap separator with next character
var temp = sb.charAt(i);
sb.setCharAt(i, sb.charAt(i+1));
sb.setCharAt(i+1, temp);
// manipulate char array so last string is built correctly
int doubled = i << 1;
// set character at correct position
lastStr[doubled - 2] = sb.charAt(i-1);
// set separator at correct position
lastStr[doubled - 1] = sep;
}
// add last character of string to this char array
lastStr[lastStr.length - 1] = sb.charAt(sb.length() - 2);
// print last desired output
System.out.println(lastStr);
}
Expected output:
abcd
a.bcd
ab.cd
abc.d
a.b.c.d

Java Palindrome always returns true

I tried to create a palindrome java program with JOptionPane by using for loop, but it ends up returning true all the time no matter the input is really a palindrome or not. Can guys please help if you guys know what's wrong with the code below, thanks.
public class program {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
JOptionPane.showMessageDialog(null, "Welcome to The Palindrome!", "Hello", JOptionPane.INFORMATION_MESSAGE);
String str = JOptionPane.showInputDialog("Please input a string");
int len = str.length();
int j = len - 1;
int i = 0;
boolean result;
for(i = 0; i <= (len - 1)/2; i++);
{
if(str.charAt(i) != str.charAt(j))
result = false;
j--;
}
if(result = true)
JOptionPane.showMessageDialog(null, str + " is a palindrome.", "ByeBye", JOptionPane.INFORMATION_MESSAGE);
if(result = false)
JOptionPane.showMessageDialog(null, str + " is not a palindrome.", "ByeBye", JOptionPane.INFORMATION_MESSAGE);
}
Instead of using traditional way to check palindrome, just use the smart way. Here you go
boolean result = str.equalsIgnoreCase(new StringBuffer(str).reverse().toString());
When you check for the value of result, you are using =, which assigns that value to the result variable, and always evaluates to true.
To correct your code, you can either remove the equal sign, or use result == true (usually you use the former, as it is more concise).
However, this may result in an error, as you are not initialising the value of result. I recommend setting it's value to true as the default value.

splitting up the contents of a single line

I just went through a problem, where input is a string which is a single word.
This line is not readable,
Like, I want to leave is written as Iwanttoleave.
The problem is of separating out each of the tokens(words, numbers, abbreviations, etc)
I have no idea where to start
The first thought that came to my mind is making a dictionary and then mapping accordingly but I think making a dictionary is not at all a good idea.
Can anyone suggest some algorithm to do it ?
First of all, create a dictionary which helps you to identify if some string is a valid word or not.
bool isValidString(String s){
if(dictionary.contains(s))
return true;
return false;
}
Now, you can write a recursive code to split the string and create an array of actually useful words.
ArrayList usefulWords = new ArrayList<String>; //global declaration
void split(String s){
int l = s.length();
int i,j;
for(i = l-1; i >= 0; i--){
if(isValidString(s.substr(i,l)){ //s.substr(i,l) will return substring starting from index `i` and ending at `l-1`
usefulWords.add(s.substr(i,l));
split(s.substr(0,i));
}
}
}
Now, use these usefulWords to generate all possible strings. Maybe something like this:
ArrayList<String> splits = new ArrayList<String>[10]; //assuming max 10 possible outputs
ArrayList<String>[] allPossibleStrings(String s, int level){
for(int i = 0; i < s.length(); i++){
if(usefulWords.contains(s.substr(0,i)){
splits[level].add(s.substr(0,i));
allPossibleStrings(s.substr(i,s.length()),level);
level++;
}
}
}
Now, this code gives you all possible splits in a somewhat arbitrary manner. eg.
dictionary = {cat, dog, i, am, pro, gram, program, programmer, grammer}
input:
string = program
output:
splits[0] = {pro, gram}
splits[1] = {program}
input:
string = iamprogram
output:
splits[0] = {i, am, pro, gram} //since `mer` is not in dictionary
splits[1] = {program}
I did not give much thought to the last part, but I think you should be able to formulate a code from there as per your requirement.
Also, since no language is tagged, I've taken the liberty of writing the code in JAVA-like syntax as it is really easy to understand.
Instead of using a Dictionary, I'd suggest you use a Trie with all your valid words (the whole English dictionary?). Then you can start moving one letter at a time in your input line and the trie at the same time. If the letter leads to more results in the trie, you can continue expanding the current word, and if not, you can start looking for a new word in the trie.
This won't be a forward only search for sure, so you'll need some sort of backtracking.
// This method Generates a list with all the matching phrases for the given input
List<string> CandidatePhrases(string input) {
Trie validWords = BuildTheTrieWithAllValidWords();
List<string> currentWords = new List<string>();
List<string> possiblePhrases = new List<string>();
// The root of the trie has an empty key that points to all the first letters of all words
Trie currentWord = validWords;
int currentLetter = -1;
// Calls a backtracking method that creates all possible phrases
FindPossiblePhrases(input, validWords, currentWords, currentWord, currentLetter, possiblePhrases);
return possiblePhrases;
}
// The Trie structure could be something like
class Trie {
char key;
bool valid;
List<Trie> children;
Trie parent;
Trie Next(char nextLetter) {
return children.FirstOrDefault(c => c.key == nextLetter);
}
string WholeWord() {
Debug.Assert(valid);
string word = "";
Trie current = this;
while (current.Key != '\0')
{
word = current.Key + word;
current = current.parent;
}
}
}
void FindPossiblePhrases(string input, Trie validWords, List<string> currentWords, Trie currentWord, int currentLetter, List<string> possiblePhrases) {
if (currentLetter == input.Length - 1) {
if (currentWord.valid) {
string phrase = ""
foreach (string word in currentWords) {
phrase += word;
phrase += " ";
}
phrase += currentWord.WholeWord();
possiblePhrases.Add(phrase);
}
}
else {
// The currentWord may be a valid word. If that's the case, the next letter could be the first of a new word, or could be the next letter of a bigger word that begins with currentWord
if (currentWord.valid) {
// Try to match phrases when the currentWord is a valid word
currentWords.Add(currentWord.WholeWord());
FindPossiblePhrases(input, validWords, currentWords, validWords, currentLetter, possiblePhrases);
currentWords.RemoveAt(currentWords.Length - 1);
}
// If either the currentWord is a valid word, or not, try to match a longer word that begins with current word
int nextLetter = currentLetter + 1;
Trie nextWord = currentWord.Next(input[nextLetter]);
// If the nextWord is null, there was no matching word that begins with currentWord and has input[nextLetter] as the following letter.
if (nextWord != null) {
FindPossiblePhrases(input, validWords, currentWords, nextWord, nextLetter, possiblePhrases);
}
}
}

Processing: create an array of the characters within the string

I am new to processing and trying to figure out a way to create an array of all the characters within a string. Currently I Have:
String[] words = {"hello", "devak", "road", "duck", "face"};
String theWord = words[int(random(0,words.length))];
I've been googling and haven't found a good solution yet. Thanks in advance.
In addition to the comment you posted (which perhaps should have been an answer), there are a ton of ways to split a String.
The most obvious solution might be the String.split() function. If you give that function an empty String "" as an argument, it will split every character:
void setup() {
String myString = "testing testing 123";
String[] chars = myString.split("");
for (String c : chars) {
println(c);
}
}
You could also just use the String.charAt() function:
void setup() {
String myString = "testing testing 123";
for (int i = 0; i < myString.length(); i++) {
char c = myString.charAt(i);
println(c);
}
}

Simple encryption algorithm for homework. not getting decryption working properly

This is a homework question that I can't get my head around at all
Its a very simple encryption algorithm. You start with a string of characters as your alphabet:
ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!, .
Then ask the user to enter there own string that will act as a map such as:
0987654321! .,POIUYTREWQASDFGHJKLMNBVCXZ
Then the program uses this to make a map and allows you to enter text that gets encrypted.
For example MY NAME IS JOSEPH would be encrypted as .AX,0.6X2YX1PY6O3
This is all very easy, however he said that its a one to one mapping and thus implied that if I enter .AX,0.6X2YX1PY6O3 back into the program I will get out MY NAME IS JOSEPH
This doesn't happen, because .AX,0.6X2YX1PY6O3 becomes Z0QCDZQGAQFOALDH
The mapping only works to decrypt when you go backwards but the question implies that the program just loops and runs the one algorithm every time.
Even if some could say that it is possible I would be happy, I have pages and pages of paper filled up with possible workings, but I came up with nothing, the only solution to run the algorithm backwards back I don't think we are allowed to do that.
Any ideas?
Edit:
Unfortunately I can't get this to work (Using the orbit computation idea) What am I doing wrong?
//import scanner class
import java.util.Scanner;
public class Encryption {
static Scanner inputString = new Scanner(System.in);
//define alphabet
private static String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!, .";
private static String map;
private static int[] encryptionMap = new int[40];//mapping int array
private static boolean exit = false;
private static boolean valid = true;
public static void main(String[] args) {
String encrypt, userInput;
userInput = new String();
System.out.println("This program takes a large reordered string");
System.out.println("and uses it to encrypt your data");
System.out.println("Please enter a mapping string of 40 length and the same characters as below but in different order:");
System.out.println(alpha);
//getMap();//don't get user input for map, for testing!
map=".ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!, ";//forced input for testing only!
do{
if (valid == true){
System.out.println("Enter Q to quit, otherwise enter a string:");
userInput = getInput();
if (userInput.charAt(0) != 'Q' ){//&& userInput.length()<2){
encrypt = encrypt(userInput);
for (int x=0; x<39; x++){//here I am trying to get the orbit computation going
encrypt = encrypt(encrypt);
}
System.out.println("You entered: "+userInput);
System.out.println("Encrypted Version: "+encrypt);
}else if (userInput.charAt(0) == 'Q'){//&& userInput.length()<2){
exit = true;
}
}
else if (valid == false){
System.out.println("Error, your string for mapping is incorrect");
valid = true;//reset condition to repeat
}
}while(exit == false);
System.out.println("Good bye");
}
static String encrypt(String userInput){
//use mapping array to encypt data
String encrypt;
StringBuffer tmp = new StringBuffer();
char current;
int alphaPosition;
int temp;
//run through the user string
for (int x=0; x<userInput.length(); x++){
//get character
current = userInput.charAt(x);
//get location of current character in alphabet
alphaPosition = alpha.indexOf(current);
//encryptionMap.charAt(alphaPosition)
tmp.append(map.charAt(alphaPosition));
}
encrypt = tmp.toString();
return(encrypt);
}
static void getMap(){
//get a mapping string and validate from the user
map = getInput();
//validate code
if (map.length() != 40){
valid = false;
}
else{
for (int x=0; x<40; x++){
if (map.indexOf(alpha.charAt(x)) == -1){
valid = false;
}
}
}
if (valid == true){
for (int x=0; x<40; x++){
int a = (int)(alpha.charAt(x));
int y = (int)( map.charAt(x));
//create encryption map
encryptionMap[x]=(a-y);
}
}
}
static String getInput(){
//get input(this repeats)
String input = inputString.nextLine();
input = input.toUpperCase();
if ("QUIT".equals(input) || "END".equals(input) || "NO".equals(input) || "N".equals(input)){
StringBuffer tmp = new StringBuffer();
tmp.append('Q');
input = tmp.toString();
}
return(input);
}
}
You will (probably) not get your original string back if you apply that substitution again. I say probably because you can construct such inputs (they all do things like if A->B then B->A). But most inputs won't do that. You would have to construct the reverse map to decrypt.
However, there is a trick you can do if you're only allowed to go forward. Keep applying the mapping and you'll eventually return to your original input. The number of times you'll have to do that depends on your input. To figure out how many times, compute the orbit of each character, and take the least common multiple of all the orbit sizes. For your input the orbits are size 1 (T->T, W->W), 2 (B->9->B H->3->H U->R->U P->O->P), 4 (C->8->N->,->C), 9 (A->...->Y->A), and 17 (E->...->V->E). The LCM of all those is 612, so 611 forward mappings applied to the ciphertext will return you to the plaintext.
Well, you can get your string back this way only if you do reverse mapping. One to one mapping means that a single letter of your default alphabet maps to only one letter of your new alphabet and vice versa. I.e. you can't map ABCD to ABBA. It doesn't imply that you can get your initial string by doing a second round of encryption.
The thing you have described can be achieved if you use a finite alphabet and a displacement to encode your string. You can choose the displacement in such a way that after a number of rounds of encryption totalDisplacement mod alphabetSize == 0 Than you will get your string back going only forward.

Resources