how to ask user input for list of strings - string

I wanna know how to ask user input for a string. For example:
when user input is asked "lruud" is entered
Enter letters: lruud
and I want it the return should be:
Left
right
up
up
down
left = l, right = r, etc.
So basically it should return the result in the order the letters are entered.
The code below is what I have tried where al() is move left, ar() is move right etc
def move(s: String) {
if(s == "l"){
al()
}else if(s == "r"){
ar()
}else if(s == "u"){
au()
}else if(s == "d"){
ad()
}
}

You can read in a string from standard input using
val s = scala.io.StdIn.readLine()
Scala implicitly considers String to be a Scala collection, in particular an IndexedSeq which means you can call standard collections methods on it such as map to transform it. For example
def move(s: Char): String = {
if (s == 'l') "left"
else if (s == 'r') "right"
else if (s == 'u') "up"
else if (s == 'd') "down"
else throw new RuntimeException("Bad input")
}
"lruud".map(move)
// res4: IndexedSeq[String] = ArraySeq(left, right, up, up, down)
Mapping over a String reads each Char in the string and passes it to the move method for transformation.

Here's one way to go about this.
val action :Map[Char,String] =
Map('d'->"down",'l'->"left",'r'->"right",'u'->"up")
.withDefault(c => s"$c?")
val moves :Seq[String] =
io.StdIn.readLine("Enter letters: ").map(c =>action(c.toLower))
println("\ndirections:\n" + moves.mkString(" ","\n ",""))
testing:
Enter letters: lLdRbu
directions:
left
left
down
right
b?
up

Related

getting multiple user inputs

def move(s: String){
if(s.equals("l")){
al()
}else if(s.equals("r")){
ar()
}else if(s.equals("u")){
au()
}else if(s.equals("d")){
ad()
} }
the code above is something I have tried but doesn't work. It should be able to get multiple strings like (lrudd) in one line and each letter equals to a function.
so if lrudd is entered the al(), ar(), au(), ad(), ad() function should be done, its a 2d game so the player should move al()- which is left, ar()- which is right, ar()- which up and ad(),twice as down is entered twice (dd)
You'll want to map() over the String in order to evaluate each Char individually.
def move(s: String) = s.map {
case 'l' => al()
case 'r' => ar()
case 'u' => au()
case 'd' => ad()
case _ => //report error
}

Inverse the input Expression using stacks

I had a coding challenge as one of the process for recruitment into a company. In that coding challenge, one of the question was to inverse an expression.
For Example,
Input : 14-3*2/5
Output : 5/2*3-14
I used stack to put each number say 14 or 3 and expressions and then popped it out again to form the output.
Input format is : num op num op num op num
So we need not worry about input being -2.
num can be between -10^16 to 10^16. I was dealing with strings completely, so even if the number exceeds the 10^16 limit, my algorithm wouldn't have any problem.
My algorithm passed 7 test cases and failed in 2 of them.
I couldn't figure it out what the corner case would be. I couldn't see the test cases as well. Any idea what that might be. I know there isn't enough information, but unfortunately I too don't have them.
// Complete the reverse function below.
static String reverse(String expression) {
expression = expression.trim();
if(expression == ""){
return "";
}
Stack<String> stack = new Stack<String>();
String num = "";
for(int i=0; i<expression.length(); i++){
char c = expression.charAt(i);
if(c==' '){
continue;
}
if(c == '+' || c == '-' || c == '*' || c == '/'){
if(num != "") {
stack.push(num);
}
num = "";
stack.push(Character.toString(c));
} else{
num += c;
}
}
if(num != "") {
stack.push(num);
}
String revExp = "";
while(! stack.empty()){
revExp = revExp + stack.pop();
}
return revExp;
}

Java Eclipse console terminates program before comparing values of user input and string value

So I'm making this program for my younger brother and I ran into a problem. The program is suppose to ask for the user's input and then compare it to multiple string values through a series of "if" statements. What happens instead is the user provides their input and then the program instantly terminates. I've been at this for hours and am starting to get pretty ticked about it. Here's the code that I've typed so far:
package package1;
import java.util.Scanner;
public class Psychic_Calculator {
#SuppressWarnings("resource")
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Hello user, please type your name below:");
String a = scan.nextLine();
System.out.println("Welcome " + a + ", think of a number. Once you have your number, type 'okay' below!");
String b = scan.nextLine();
if (b == "okay"){
System.out.println("Now, add '11' to your number and type 'okay' below.");
}
else if (b == "Okay"){
System.out.println("Please don't capitalize 'okay', try typing it again!");
String c = scan.nextLine();
if (c == "okay"){
System.out.println("Now, add '11' to your number and type 'okay' below.");
String d = scan.nextLine();
if (d == "okay"){
System.out.println("Now, add '2' to your new number, then type 'okay' below.");
String e = scan.nextLine();
if (e == "okay"){
System.out.println("Now, subtract your original number from your new number, then type 'okay' below.");
String f = scan.nextLine();
if (f == "okay"){
System.out.println("Your new number is '13'. Don't even try denying it.");
}
}
}
}
if (c == "Okay"){
System.out.println("I already told you not to capitalize 'okay', try typing it again, you idiot!");
String g = scan.nextLine();
if (g == "okay"){
System.out.println("Now, add '11' to your number and type 'okay' below.");
String h = scan.nextLine();
if (h == "okay"){
System.out.println("Now, add '2' to your new number, then type 'okay' below.");
String i = scan.nextLine();
if (i == "okay"){
System.out.println("Now, subtract your original number from your new number, then type 'okay' below.");
String j = scan.nextLine();
if (j == "okay"){
System.out.println("Your new number is '13'. Don't even try denying it.");
}
}
}
}
}
if (c != "okay") {
while (c != "okay") {
System.out.println("Do you even know how to spell 'okay'?" + "'" + c + "' does not spell 'okay', you moron! Try typing 'okay' again.");
String n = scan.nextLine();
if (n == "okay"){
System.out.println("Finally, you learned how to spell 'okay'. Your vocabulary is now one word larger, you're welcome. Now, please add '11' to your number and then type 'okay'(correctly this time).");
String k = scan.nextLine();
if (k == "okay"){
System.out.println("Now, add '2' to your new number, then type 'okay' below.");
String l = scan.nextLine();
if (l == "okay"){
System.out.println("Now, subtract your original number from your new number, then type 'okay' below.");
String m = scan.nextLine();
if (m == "okay"){
System.out.println("Your new number is '13'. Don't even try denying it.");
}
}
}
}
else {
System.out.println(a + ", " + "you have failed to type 'okay' too many times! You have no idea how to spell 'okay' you electricutin' motherboarder! Go shove your face in a pile of computer chips and grow a pair!");
System.out.println("(of RAM cartriges...I meant to say RAM cartriges).");
}
}
}
}
}
}
The problem is how you're comparing the strings. Change b == "okay" to b.equals("okay")
Change all the == comparisons to .equals() or .equalsIgnoreCase().
For negations, use (!(c.equals("okay"))
In Java, == will compare primitive types by value but will compare objects by memory address. In other words, when you say b == "okay" its not doing a value comparison, its checking to see whether or not those two objects point to the same memory address, which of course is false.
Update: Just a few things about the way you're going about writing this program.
1) You're creating a lot of string objects needlessly. You're better off re-using one string object until you absolutely need another one. This applies to any object you're using. Try not allocate objects needlessly.
2) Instead of all the if-statements, you can define an array of instructions, like such and condense your code:
String [] instr = {"Add 2", "Add 11", "Subtract Original"};//array of directions
String [] invalidResp = {"Wrong", "You can't spell", "Try Again", "No"};//array of responses to print if user doesnt type 'okay' properly
int instrCounter = 0;//you don't really need this but it helps with readability
String userInput = "";//only string object you'll need =)
while (instrCounter < instr.length){//I couldve just as easily used a for loop instead.
userInput = scan.nextLine();
while (!userInput.equals("okay")){
userInput = scan.nextLine();
System.out.println(invalidResp[(int) (Math.random()*invalidResp.length)]);
//will print a random invalid response from the invalidResp array
System.out.println(userInput + " is not how you spell okay");
}//end while
System.out.println("Great, now, " + instr[instrCounter]);
instrCounter++;
}//end outer while
Remember, when you write code, you want it to be fairly generic and flexible. The way I wrote my code, I can add to the instr array or add more invalid responses and im not needlessly creating objects.
Like I said in the inline comment, I could've just as easily used a for loop for the outer loop but for the sake of readability and making sure you understood what I was doing, I used a while loop as I believe they're more intuitive to read.
GAME:
while(running) {
System.out.println("---------------------------");
continue GAME;
//Name the while loop and then you can break; out.

Finding minimum moves required for making 2 strings equal

This is a question from one of the online coding challenge (which has completed).
I just need some logic for this as to how to approach.
Problem Statement:
We have two strings A and B with the same super set of characters. We need to change these strings to obtain two equal strings. In each move we can perform one of the following operations:
1. swap two consecutive characters of a string
2. swap the first and the last characters of a string
A move can be performed on either string.
What is the minimum number of moves that we need in order to obtain two equal strings?
Input Format and Constraints:
The first and the second line of the input contains two strings A and B. It is guaranteed that the superset their characters are equal.
1 <= length(A) = length(B) <= 2000
All the input characters are between 'a' and 'z'
Output Format:
Print the minimum number of moves to the only line of the output
Sample input:
aab
baa
Sample output:
1
Explanation:
Swap the first and last character of the string aab to convert it to baa. The two strings are now equal.
EDIT : Here is my first try, but I'm getting wrong output. Can someone guide me what is wrong in my approach.
int minStringMoves(char* a, char* b) {
int length, pos, i, j, moves=0;
char *ptr;
length = strlen(a);
for(i=0;i<length;i++) {
// Find the first occurrence of b[i] in a
ptr = strchr(a,b[i]);
pos = ptr - a;
// If its the last element, swap with the first
if(i==0 && pos == length-1) {
swap(&a[0], &a[length-1]);
moves++;
}
// Else swap from current index till pos
else {
for(j=pos;j>i;j--) {
swap(&a[j],&a[j-1]);
moves++;
}
}
// If equal, break
if(strcmp(a,b) == 0)
break;
}
return moves;
}
Take a look at this example:
aaaaaaaaab
abaaaaaaaa
Your solution: 8
aaaaaaaaab -> aaaaaaaaba -> aaaaaaabaa -> aaaaaabaaa -> aaaaabaaaa ->
aaaabaaaaa -> aaabaaaaaa -> aabaaaaaaa -> abaaaaaaaa
Proper solution: 2
aaaaaaaaab -> baaaaaaaaa -> abaaaaaaaa
You should check if swapping in the other direction would give you better result.
But sometimes you will also ruin the previous part of the string. eg:
caaaaaaaab
cbaaaaaaaa
caaaaaaaab -> baaaaaaaac -> abaaaaaaac
You need another swap here to put back the 'c' to the first place.
The proper algorithm is probably even more complex, but you can see now what's wrong in your solution.
The A* algorithm might work for this problem.
The initial node will be the original string.
The goal node will be the target string.
Each child of a node will be all possible transformations of that string.
The current cost g(x) is simply the number of transformations thus far.
The heuristic h(x) is half the number of characters in the wrong position.
Since h(x) is admissible (because a single transformation can't put more than 2 characters in their correct positions), the path to the target string will give the least number of transformations possible.
However, an elementary implementation will likely be too slow. Calculating all possible transformations of a string would be rather expensive.
Note that there's a lot of similarity between a node's siblings (its parent's children) and its children. So you may be able to just calculate all transformations of the original string and, from there, simply copy and recalculate data involving changed characters.
You can use dynamic programming. Go over all swap possibilities while storing all the intermediate results along with the minimal number of steps that took you to get there. Actually, you are going to calculate the minimum number of steps for every possible target string that can be obtained by applying given rules for a number times. Once you calculate it all, you can print the minimum number of steps, which is needed to take you to the target string. Here's the sample code in JavaScript, and its usage for "aab" and "baa" examples:
function swap(str, i, j) {
var s = str.split("");
s[i] = str[j];
s[j] = str[i];
return s.join("");
}
function calcMinimumSteps(current, stepsCount)
{
if (typeof(memory[current]) !== "undefined") {
if (memory[current] > stepsCount) {
memory[current] = stepsCount;
} else if (memory[current] < stepsCount) {
stepsCount = memory[current];
}
} else {
memory[current] = stepsCount;
calcMinimumSteps(swap(current, 0, current.length-1), stepsCount+1);
for (var i = 0; i < current.length - 1; ++i) {
calcMinimumSteps(swap(current, i, i + 1), stepsCount+1);
}
}
}
var memory = {};
calcMinimumSteps("aab", 0);
alert("Minimum steps count: " + memory["baa"]);
Here is the ruby logic for this problem, copy this code in to rb file and execute.
str1 = "education" #Sample first string
str2 = "cnatdeiou" #Sample second string
moves_count = 0
no_swap = 0
count = str1.length - 1
def ends_swap(str1,str2)
str2 = swap_strings(str2,str2.length-1,0)
return str2
end
def swap_strings(str2,cp,np)
current_string = str2[cp]
new_string = str2[np]
str2[cp] = new_string
str2[np] = current_string
return str2
end
def consecutive_swap(str,current_position, target_position)
counter=0
diff = current_position > target_position ? -1 : 1
while current_position!=target_position
new_position = current_position + diff
str = swap_strings(str,current_position,new_position)
# p "-------"
# p "CP: #{current_position} NP: #{new_position} TP: #{target_position} String: #{str}"
current_position+=diff
counter+=1
end
return counter,str
end
while(str1 != str2 && count!=0)
counter = 1
if str1[-1]==str2[0]
# p "cross match"
str2 = ends_swap(str1,str2)
else
# p "No match for #{str2}-- Count: #{count}, TC: #{str1[count]}, CP: #{str2.index(str1[count])}"
str = str2[0..count]
cp = str.rindex(str1[count])
tp = count
counter, str2 = consecutive_swap(str2,cp,tp)
count-=1
end
moves_count+=counter
# p "Step: #{moves_count}"
# p str2
end
p "Total moves: #{moves_count}"
Please feel free to suggest any improvements in this code.
Try this code. Hope this will help you.
public class TwoStringIdentical {
static int lcs(String str1, String str2, int m, int n) {
int L[][] = new int[m + 1][n + 1];
int i, j;
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
if (i == 0 || j == 0)
L[i][j] = 0;
else if (str1.charAt(i - 1) == str2.charAt(j - 1))
L[i][j] = L[i - 1][j - 1] + 1;
else
L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]);
}
}
return L[m][n];
}
static void printMinTransformation(String str1, String str2) {
int m = str1.length();
int n = str2.length();
int len = lcs(str1, str2, m, n);
System.out.println((m - len)+(n - len));
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str1 = scan.nextLine();
String str2 = scan.nextLine();
printMinTransformation("asdfg", "sdfg");
}
}

String Matching: Matching words with or without spaces

I want to find a way by which I can map "b m w" to "bmw" and "ali baba" to "alibaba" in both the following examples.
"b m w shops" and "bmw"
I need to determine whether I can write "b m w" as "bmw"
I thought of this approach:
remove spaces from the original string. This gives "bmwshops". And now find the Largest common substring in "bmwshop" and "bmw".
Second example:
"ali baba and 40 thieves" and "alibaba and 40 thieves"
The above approach does not work in this case.
Is there any standard algorithm that could be used?
It sounds like you're asking this question: "How do I determine if string A can be made equal to string B by removing (some) spaces?".
What you can do is iterate over both strings, advancing within both whenever they have the same character, otherwise advancing along the first when it has a space, and returning false otherwise. Like this:
static bool IsEqualToAfterRemovingSpacesFromOne(this string a, string b) {
return a.IsEqualToAfterRemovingSpacesFromFirst(b)
|| b.IsEqualToAfterRemovingSpacesFromFirst(a);
}
static bool IsEqualToAfterRemovingSpacesFromFirst(this string a, string b) {
var i = 0;
var j = 0;
while (i < a.Length && j < b.Length) {
if (a[i] == b[j]) {
i += 1
j += 1
} else if (a[i] == ' ') {
i += 1;
} else {
return false;
}
}
return i == a.Length && j == b.Length;
}
The above is just an ever-so-slightly modified string comparison. If you want to extend this to 'largest common substring', then take a largest common substring algorithm and do the same sort of thing: whenever you would have failed due to a space in the first string, just skip past it.
Did you look at Suffix Array - http://en.wikipedia.org/wiki/Suffix_array
or Here from Jon Bentley - Programming Pearl
Note : you have to write code to handle spaces.

Resources