How to scramble a String - string

I'm trying to make an Anagram puzzle where I input a word (for example, fire) and it scrambles it randomly around for me (and it ends up like "rfie", "frei", etc...) Below is the basics of what I'm trying to do. All I need to know is how to scramble the string.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input word");
String Word = sc.nextLine();
//Program jumbles word here
System.out.println(Word);
//Jumbled word is printed one previous line
}

You could use the following algorithm:
public static void main(String[] args){
String myWord = "Hello";
StringBuilder jumbledWord = new StringBuilder();
jumbledWord.append(myWord);
Random rand = new Random();
for (int i = myWord.length(); i > 0; i--)
{
int index1 = (rand.nextInt(i+1) % myWord.length());
int index2 = (rand.nextInt(i) % myWord.length());
char temp = jumbledWord.charAt(index1);
jumbledWord.setCharAt(index1, jumbledWord.charAt(index2));
jumbledWord.setCharAt(index2, temp);
}
System.out.println(jumbledWord);
}

Related

Program to Sort the String

I want to sort the String s = "eBaDcAfg153E" Such that the sorted string contains All lowercase first and then uppercase letters and then numbers.
The output should be like s = "acefgABDE135"
Can anyone help me with that?
Thanks
Welcome to stackoverflow!
Read how to ask good question, First try to solve, and if fail then first search over Google. and if you don't find answer, then you may ask.
This solution may work for you (just for test).. Still you can improve it a lot..
Use StringBuilder for string modification.
public static void main (String[] args) throws java.lang.Exception
{
String inputString = "eBaDcAfg153E";
String lowerCase = "";
String upperCase = "";
String numberCase = "";
for (int i = 0; i < inputString.length(); i++) {
char c = inputString.charAt(i);
if(Character.isUpperCase(c)) {
upperCase += c;
}else if (Character.isLowerCase(c)) {
lowerCase += c;
}else if(Character.isDigit(c)) {
numberCase += c;
}
}
char upperArray[] = upperCase.toCharArray();
char lowerArray[] = lowerCase.toCharArray();
char numArray[] = numberCase.toCharArray();
Arrays.sort(upperArray);
Arrays.sort(lowerArray);
Arrays.sort(numArray);
System.out.println(new String(lowerArray)+""+new String(upperArray)+""+new String(numArray));
}

XSSFCell in Apache POI encodes certain character sequences as unicode character

XSSFCell seems to encode certain character sequences as unicode characters. How can I prevent this? Do I need to apply some kind of character escaping?
e.g.
cell.setCellValue("LUS_BO_WP_x24B8_AI"); // The cell value now is „LUS_BO_WPⒸAI"
In Unicode Ⓒ is U+24B8
I've already tried setting an ANSI font and setting the cell type to string.
This character conversion is done in XSSFRichTextString.utfDecode()
I have now written a function that basicaly does the same thing in reverse.
private static final Pattern utfPtrn = Pattern.compile("_(x[0-9A-F]{4}_)");
private static final String UNICODE_CHARACTER_LOW_LINE = "_x005F_";
public static String escape(final String value) {
if(value == null) return null;
StringBuffer buf = new StringBuffer();
Matcher m = utfPtrn.matcher(value);
int idx = 0;
while(m.find()) {
int pos = m.start();
if( pos > idx) {
buf.append(value.substring(idx, pos));
}
buf.append(UNICODE_CHARACTER_LOW_LINE + m.group(1));
idx = m.end();
}
buf.append(value.substring(idx));
return buf.toString();
}
Based on what #matthias-gerth suggested with little adaptations:
Create your own XSSFRichTextString class
Adapt XSSFRichTextString.setString like this: st.setT(s); >> st.setT(escape(s));
Adapt the constructor of XSSFRichTextString like this: st.setT(str); >> st.setT(escape(str));
Add this stuff in XSSFRichTextString (which is very near to Matthias suggestion):
private static final Pattern PATTERN = Pattern.compile("_x[a-fA-F0-9]{4}");
private static final String UNICODE_CHARACTER_LOW_LINE = "_x005F";
private String escape(String str) {
if (str!=null) {
Matcher m = PATTERN.matcher(str);
if (m.find()) {
StringBuffer buf = new StringBuffer();
int idx = 0;
do {
int pos = m.start();
if( pos > idx) {
buf.append(str.substring(idx, pos));
}
buf.append(UNICODE_CHARACTER_LOW_LINE + m.group(0));
idx = m.end();
} while (m.find());
buf.append(str.substring(idx));
return buf.toString();
}
}
return str;
}

Trying to put random strings into a file

I am trying to insert random strings into a .txt file. My code is as follows:
import java.util.*;
import java.io.*;
class fileProcessing{
public static void main (String[] args) throws Exception{
letter();
}
public static void letter() throws Exception{
int count = 0;
PrintStream out = new PrintStream(new File("nums.txt"));
while (count < 7 ){
Random rand = new Random();
int randomNum = 97 + rand.nextInt((122 - 97) + 1);
char a = (char)randomNum;
out.print(a);
count++;
}
}
}
I'm trying to put a row of 7 random letters in a .txt file about 400 or so times. My code allows me to put in only a row of 7 letters. I'm not sure how to get the other 399 lines in. Any help would be appreciated. Thanks!
Use a nested loop that contains the loop you have already written. What this does is, after you generate one word, do a new iteration, writing another word in your file.
import java.util.*
import java.io.*;
class FileProcessing
{
public static void main(String[] args) throws IOException
{
letters();
}
public static void letters() throws IOException
{
int count;
PrintStream out = new PrintStream(new File("nums.txt"));
/*Outer loop. When the loop on the inside finishes generating
*a word, this loop will iterate again.
*/
for(int i=0; i<400; ++i)
{
count=0;
/*your current while loop*/
while (count < 7)
{
Random rand = new Random();
int randomNum = 97 + rand.nextInt((122-97)+1);
char a = (char) randomNum;
out.print(a);
count++;
}
//print new line so all words are in a separate line
out.println();
}
//close PrintStream
out.close();
}
}
Learn more on nested loops here: http://www.javawithus.com/tutorial/nested-loops

Reverse String Palindrome

Hi I am trying to reverse a String to make a palindrome. Can someone please give me a tutorial on how to reverse a string? I have read some tutorials online and I have tried applying them to the palindrome program that i am writing but have not been successful.
import java.util.Random;
public class IterativePalindromGenerator {
public static void main(String[] args) {
Random random = new Random();
int floorValue = 1;
int cielingValue = 20;
int randomNumber = random.nextInt(cielingValue - floorValue)
+ floorValue;
String alphabetLetters = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < randomNumber; i++) {
char generatedLetters = alphabetLetters.charAt(random
.nextInt(alphabetLetters.length()));
String generatedLetterSTRINGType = Character
.toString(generatedLetters);// converts char to string
System.out.print(generatedLetterSTRINGType);
}
}
}
To reverse a string you can use StringBuffers reverse() method:
public String reverse(String stringToReverse) {
return new StringBuffer(stringToReverse).reverse().toString();
}
Hey here is my code from a college course. Our task was to implement a recursive procedure. Hope this can help the community.
package DiskreteMathe;
import java.util.*;
public class AufgabePalindromTestRekursiv {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter text here:");
String text= sc.next();
System.out.println(testPalindrom(text));
}
public static boolean testPalindrom (String text){
if (text.length()==2 && text.charAt(0)==text.charAt(1) || text.length()==1)
return true;
if(text.charAt(0)!=text.charAt(text.length()-1)){
return false;
} else {
text = text.substring(1, text.length()-1);
return testPalindrom(text);
}
}
}
When creating a palindrome for existing string, you need to think of the cases of even and odd outcome strings. For example, if you input String "abc", you should expect there are two outcome palindrome strings: abccba (even) and abcba (odd).
Here is my code:
public class PalindromeGenerator {
public static void main(String[] args) {
String str = "abc";
String reverse_str = "";
for (int n = str.length(); n>0; n--){
reverse_str += str.substring(n-1, n);
}
String even_str = str + reverse_str;
String odd_str = str.substring(0, str.length()-1) + reverse_str;
System.out.println(even_str); // print "abccba"
System.out.println(odd_str); //print "abcba"
}
}
I Hope this can help you.

ReadLine - Array index out of bounds

I have been debugging this program to find the error but couldn't succeed in that. For some reason, it is displaying an error - array index out of bounds in this line
moves[nCount].sDirection = sStep[0]; I know, this forum is not meant for debugging, im sorry for that.
class Program
{
struct move
{
public char sDirection;
public int steps;
}
static void Main(string[] args)
{
int nNumOfInstructions = 0;
int nStartX = 0, nStartY = 0;
move[] moves = new move[nNumOfInstructions];
nNumOfInstructions=Convert.ToInt32(Console.ReadLine());
string sPosCoOrd = Console.ReadLine();
nStartX = Convert.ToInt32(sPosCoOrd[0]);
nStartY = Convert.ToInt32(sPosCoOrd[2]);
string sStep = "";
for (int nCount = 0; nCount < nNumOfInstructions; nCount++)
{
sStep = Console.ReadLine();
int length = sStep.Length;
moves[nCount].sDirection = sStep[0];
moves[nCount].steps = Convert.ToInt32(sStep[1]);
}
Console.ReadLine();
}
}
In your code, the moves array is created as an array of zero length. For any index, accessing this array will inevitably throw an Array index out of bounds
You probably want to do it this way:
class Program
{
struct move
{
public char sDirection;
public int steps;
}
static void Main(string[] args)
{
int nNumOfInstructions = Convert.ToInt32(Console.ReadLine());
move[] moves = new move[nNumOfInstructions];
string sPosCoOrd = Console.ReadLine();
int nStartX = Convert.ToInt32(sPosCoOrd[0]);
int nStartY = Convert.ToInt32(sPosCoOrd[2]);
string sStep = String.Empty;
for (int nCount = 0; nCount < nNumOfInstructions; nCount++)
{
sStep = Console.ReadLine();
int length = sStep.Length;
moves[nCount].sDirection = sStep[0];
moves[nCount].steps = Convert.ToInt32(sStep[1]);
}
}
}

Resources