Reverse String Palindrome - string

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.

Related

Unlikely argument type int for get(Object) on a Map<Character,Integer>Java(1200)

longest= Math.max(longest,map.get(i)); [Error is being shown]
I understand Math.max and Longest is int AND map.get is Integer. I tried intValue() but its not working;
import java.util.HashMap;
public class longestSubstring {
public static void main(String[] args){
String str = "abcabcbb";
HashMap<Character,Integer> map = new HashMap<>();
for(int i=0;i<str.length();i++){
char c = str.charAt(i);
if(map.containsKey(c)){
map.put(c,map.get(c)+1);
}else{
map.put(c,1);
}
}
int longest = 0;
for(int i: map.keySet()){
longest= Math.max(longest,map.get(i)); // error here
}
System.out.println(longest);
}
}
Please help
import java.util.HashMap;
public class longestSubstring {
public static void main(String[] args){
String str = "abcabcbb";
HashMap<Character,Integer> map = new HashMap<>();
for(int i=0;i<str.length();i++){
char c = str.charAt(i);
if(map.containsKey(c)){
map.put(c,map.get(c)+1);
}else{
map.put(c,1);
}
}
int longest = 0;
for(Character c: map.keySet()){
longest= Math.max(longest,map.get(c));
}
System.out.println(longest);
}
}

How to scramble a 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);
}

how to generate sequence number using c# in window application

private string GenerateID()
{
}
private void auto()
{
AdmissionNo.Text = "A-" + GenerateID();
}
with prefix of A like below
A-0001
A-0002 and so on .
You can use below code.
private string GenerateId()
{
int lastAddedId = 8; // get this value from database
string demo = Convert.ToString(lastAddedId + 1).PadLeft(4, '0');
return demo;
// it will return 0009
}
private void Auto()
{
AdmissionNo.Text = "A-" + GenerateId();
// here it will set the text as "A-0009"
}
Look at this
public class Program
{
private static int _globalSequence;
static void Main(string[] args)
{
_globalSequence = 0;
for (int i = 0; i < 10; i++)
{
Randomize(i);
Console.WriteLine("----------------------------------------->");
}
Console.ReadLine();
}
static void Randomize(int seed)
{
Random r = new Random();
if (_globalSequence == 0) _globalSequence = r.Next();
Console.WriteLine("Random: {0}", _globalSequence);
int localSequence = Interlocked.Increment(ref _globalSequence);
Console.WriteLine("Increment: {0}, Output: {1}", _globalSequence, localSequence);
}
}
Whether it is an windows application or not is IMHO not relevant. I'd rather care about thread safety. Hence, I would use something like this:
public sealed class Sequence
{
private int value = 0;
public Sequence(string prefix)
{
this.Prefix = prefix;
}
public string Prefix { get; }
public int GetNextValue()
{
return System.Threading.Interlocked.Increment(ref this.value);
}
public string GetNextNumber()
{
return $"{this.Prefix}{this.GetNextValue():0000}";
}
}
This could easily be enhanced to use the a digit count. So the "0000" part could be dynamically specified as well.

I'm getting Resource Leaks

Whenever I run this code, it works pretty smoothly, until the while loop runs through once. It will go back and ask for the name again, and then skip String b = sc.nextLine();, and print the next line, instead.
static Scanner sc = new Scanner(System.in);
static public void main(String [] argv) {
Name();
}
static public void Name() {
boolean again = false;
do
{
System.out.println("What is your name?");
String b = sc.nextLine();
System.out.println("Ah, so your name is " + b +"?\n" +
"(y//n)");
int a = getYN();
System.out.println(a + "! Good.");
again = askQuestion();
} while(again);
}
static public boolean askQuestion() {
System.out.println("Do you want to try again?");
int answer = sc.nextInt();
if (answer == 1) {
return true;
}
else {
return false;
}
}
static int getYN() {
switch (sc.nextLine().substring(0, 1).toLowerCase()) {
case "y":
return 1;
case "n":
return 0;
default:
return 2;
}
}
}
Also, I'm trying to create this program in a way that I can ask three questions (like someone's Name, Gender, and Age, maybe more like race and whatnot), and then bring all of those answers back. Like, at the very end, say, "So, your name is + name +, you are + gender +, and you are + age + years old? Yes/No." Something along those lines. I know there's a way to do it, but I don't know how to save those responses anywhere, and I can't grab them since they only occur in the instance of the method.
Don't try to scan text with nextLine() AFTER using nextInt() with the same scanner! It may cause problems. Open a scanner method for ints only...it's recommended.
You could always parse the String answer of the scanner.
Also, using scanner this way is not a good practice, you could organize questions in array an choose a loop reading for a unique scanner instantiation like this:
public class a {
private static String InputName;
private static String Sex;
private static String Age;
private static String input;
static Scanner sc ;
static public void main(String [] argv) {
Name();
}
static public void Name() {
sc = new Scanner(System.in);
String[] questions = {"Name?","Age","Sex?"};//
int a = 0;
System.out.println(questions[a]);
while (sc.hasNext()) {
input = sc.next();
setVariable(a, input);
if(input.equalsIgnoreCase("no")){
sc.close();
break;
}
else if(a>questions.length -1)
{
a = 0;
}
else{
a++;
}
if(a>questions.length -1){
System.out.println("Fine " + InputName
+ " so you are " + Age + " years old and " + Sex + "." );
Age = null;
Sex = null;
InputName = null;
System.out.println("Loop again?");
}
if(!input.equalsIgnoreCase("no") && a<questions.length){
System.out.println(questions[a]);
}
}
}
static void setVariable(int a, String Field) {
switch (a) {
case 0:
InputName = Field;
return;
case 1:
Age = Field;
return;
case 2:
Sex = Field;
return;
}
}
}
Pay attention on the global variables, wich stores your info until you set them null or empty...you could use them to the final affirmation.
Hope this helps!
Hope this helps!

Algorithm for Hyper String

I want to know about the algorithm to solve HyperString Problem.
You can find the description at https://www.hackerrank.com/challenges/hyper-strings.
Can it be solved by dynamic programming?
Any help would be highly apreciated.
public class HyperString {
//Abubaker Tagelsir
private static int n,m,sum=1;
private static void temp(String u,String []d)
{
for(int i=0 ; i<d.length;i++)
{
if((u.length()+d[i].length())<=m)
{
sum++;
temp(u+d[i],d);
}
}
}
private static int Input3(String [] d)
{
sum +=d.length;
for(int i=0;i<d.length;i++){
for(int j=0;j<d.length;j++)
{
if((d[i].length()+d[j].length())<=m)
{
sum++;
temp(d[i]+d[j],d);
}
}
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String h = sc.nextLine();
StringTokenizer tz = new StringTokenizer(h);
String h1 = tz.nextToken();
n = Integer.parseInt(h1);
String h2 = tz.nextToken();
m = Integer.parseInt(h2);
//Input2();
String [] d = new String[n];
for(int i=0;i<n;i++)
{
d[i] = sc.nextLine();
}
System.out.println(Input3(d));
}
}

Resources