How to determine if a given String is part of a group? - grouping

Very new to programming here. I am attempting to make a method that determines if the users input is part of a group of variables. For example:
User input is "C"
If "C" is found from a group containing the letters "C Db E Fb G Ab B", then print "true".
But, I want it to print "false" if user input is "D", because the D needs to be paired with "b".
How to achieve this? Here is what I have tried but obviously it doesn't work since it doesn't understand that some letters need to be paired with another letter:
// Check the Scale Project
import java.util.Scanner;
public class Hiekkalaatikko {
public static void main(String[] args) {
Scanner skanneri = new Scanner(System.in);
String I = String.valueOf(skanneri.nextLine()); //asking for the values
String II = String.valueOf(skanneri.nextLine());
String III = String.valueOf(skanneri.nextLine());
checker(I, II, III); // sending the values to method
}
public static void checker(String I, String II, String III) {
String DbScale = "Db_Eb_F_Gb_Ab_Bb_C"; // If input is found from this group, then print C major
if (DbScale.contains(I) && DbScale.contains(II) && DbScale.contains(III)) {
System.out.println("Db major");
}
}
}

Related

How to connect my collectable items with the random generator and use a list of words for generating in UNITY 2D

I have a script for random word generating:
...
public TextMeshPro largeText;
public void BtnAction()
{
CreateRandomString();
}
private void CreateRandomString(int stringLength = 10)
{
int _stringLength = stringLength - 1;
string randomString = "";
string[] characters = new string[] { "A", "B", "C", "D" };
for (int i = 0; i<= _stringLength; i++)
{
randomString = randomString + characters[Random.Range(0, characters.Length)];
}
largeText.text = randomString;
}
...
In my game, the player has to collect letters, which I have made with a tag of collectables, to use in the inventory system for gathering.
...
private void OnTriggerEnter2D(Collider2D other)
{
if(other.CompareTag("Collectable"))
{
string inventoryType = other.gameObject.GetComponent<Collectable>().inventoryType;
print("We have collected a:"+ inventoryType);
inventory.Add(inventoryType);
print("Inventory length:" + inventory.Count);
Destroy(other.gameObject);
string wordType = other.gameObject.GetComponent<Collectable>().inventoryType;
}
}
...
I want instead of:
string[] characters = new string[] { "A", "B", "C", "D" };
the string to be from the gathered letters.
After that, to be generated a word from an existing list with words.
How do I do that?
In your OnTriggerEnter script you can store the letters in an List like this,
//Instantiate your List
public List<string> mylist = new List<string>();
//Add the letters to your List
mylist.Add(other.gameObject.GetComponent<Collectable>().inventoryType);
Then you have to refernce List to your other function that generates the random string(I'm assuming you know how to do this,I can't give you a specific method because I don't know the arrangement on your side).Its easy if both these functions are in one script.
If the functions are in two different scripts you have to reference the GameObject with the first script to your second script in the inspector and then
public GameObject GameObject_with_your_first_Script;
......
firstScriptClassName myScript = GameObject_with_your_first_Script.GetComponent<fistScriptClassName>();
List referencedList = myScript.mylist;
Hope this is helpful.I've mentioned the bare essentials you need to get what you want done..Let me know If anything is not clear.

Change a tuple using pig

I need to substitute characters of a tuple using Pig UDF. For eg, if i have a line in the file as "hello world, Hello WORLD, hello\WORLD" required to be transformed as "hello_world,hello_world,hello_world". To accomplish this, i tried below UDF:
package myUDF;
import java.io.IOException;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
public class ReplaceValues extends EvalFunc<Tuple>
{
public Tuple exec(Tuple input) throws IOException {
if (input == null || input.size() == 0)
return null;
try{
String str = (String)input.get(0);
str=str.replace(" ", "_");
str=str.replace("/","");
str=str.replace("\\","");
TupleFactory tf = TupleFactory.getInstance();
Tuple t = tf.newTuple();
t.append(str);
return t;
}catch(Exception e){
throw new IOException("Caught exception processing input row ", e);
}
}
}
but when calling this UDF via pig script i am facing issues, please help me in resolving this:
A = load '/user/cloudera/Stage/ActualDataSet.csv' using PigStorage(',') AS (Rank:chararray,NCTNumber:chararray,Title:chararray,Recruitment:chararray);
B = FILTER A by Rank == 'Rank';
C = FOREACH B GENERATE PigUDF.ReplaceValues(B);
Error: Pig script failed to parse:
Invalid scalar projection: B : A column needs to be projected from a relation for it to be used as a scalar
You have to pass the field that you are trying to modify and not the relation B.Assuming the field that you are trying to match is Title, then you would call the UDF like below
C = FOREACH B GENERATE B.Rank,B.NCTNumber,PigUDF.ReplaceValues(B.Title),B.Recruitment;
Note that if you are trying to replace it in the entire record then your load statement is incorrect.You will have to load the entire record as one line:chararray and then pass the line to your UDF.
Also, instead of an UDF you can use REGEX to match and replace the string of your choice.
In your Pig script, you are passing entire Bag "B" in the UDF, while it accepts tuple as an argument.
Instead pass the field like B.Title as given below.
C = FOREACH B GENERATE PigUDF.ReplaceValues(B.Title);
you can call this UDF on other fields also in the same line as:
C = FOREACH B GENERATE PigUDF.ReplaceValues(B.Title), PigUDF.ReplaceValues(B.Rank);

Write a method that takes a string from the user and sends back only the even characters

I'm a complete noob and have been working at this part of my homework for hours now im pretty sure I'm doing it completely wrong.
Ask the user for an encrypted sentence and then decrypt the sentence and output
it. Here is the encryption algorithm: only even numbers characters are part of the
message. For example if the user enters “Hiejlzl3ow” after you decrypt it will be the
word “Hello”. Must write a method for this part. This method should receive a
String as its parameter and return the decrypted String as its parameter.
heres my code so far:
import java.util.Scanner;
public class secret{
public static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Can you encrypt a sentance for me? \n");
String input = console.nextLine();
String foundMessage = findMessage(input);
System.out.print(foundMessage);
}
public static String findMessage(String encodedMessage){
for (int i=0; i<encodedMessage.length(); i++){
if(i%2==0){
String decode =encodedMessage.charAt(i);
}
}
return decode;
}
}
You define String decode in if statement so it can not be seen outside of that, in return statement. In addition you should add the characters in your previous decode string. Also, define method findMethod outside the main method and your problem solved.
import java.util.Scanner;
public class Secret{
public static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Can you encrypt a sentance for me? \n");
String input = console.nextLine();
String foundMessage = findMessage(input);
System.out.print(foundMessage);
}
public static String findMessage(String encodedMessage){
String decode = "";
for (int i=0; i<encodedMessage.length(); i++){
if(i%2==0){
decode += encodedMessage.charAt(i);
}
}
return decode;
}
}
I think you can get what you want by incrementing your loop by 2...
Also, at the moment you're declaring your "decode" inside the loop; it will be recreated in every iteration, so that won't do what you want. This method should work:
public static String findMessage(String encodedMessage){
String decode;
for (int i=0; i<encodedMessage.length(); i+=2){
decode += encodedMessage.charAt(i);
}
return decode;
}

REGEX: find pattern, extract data, and replace the searched pattern with a string in relations to the content of searched

As the title says, I would like to:
1) find a pattern. Ex: getting $(getThisString+100) from this string: "this is some random string $(getThisString+100)"
2) extract data. Ex: grabbing the value 100 from $(getThisString+100)
3) replace the searched pattern with a string in relations to the content of searched. Ex: replace $(getThisString+100) with 150 (100 + 50) (this 50 is any number that I just made up)
so in the end, i will need "this is some random string 150"
I'm quite new to regex, please let me know if this is possible.
Thanks a lot
How about this?
package myparser;
import static org.junit.Assert.assertEquals;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
public class ParseTest {
private final Pattern re = Pattern.compile(".*?(\\$\\(getThisString\\+(\\d+)\\)).*");
public String parseMyString(final String str) {
Matcher m = re.matcher(str);
if (m.matches()) {
int val = Integer.parseInt(m.group(2));
int newVal = val + 50;
String strStart = str.substring(0, m.start(1));
String strEnd = str.substring(m.end(1));
return parseMyString(strStart + String.valueOf(newVal) + strEnd);
} else {
return str;
}
}
#Test
public void testParseNone() {
String in = "this is some random string)";
String out = parseMyString(in);
assertEquals(in, out);
}
#Test
public void testParseOne() {
String in = "this is some random string $(getThisString+100)";
String out = parseMyString(in);
assertEquals("this is some random string 150", out);
}
#Test
public void testParseMultiple() {
String in = "this is some random string $(getThisString+100) and some more random $(getThisString+60)";
String out = parseMyString(in);
assertEquals("this is some random string 150 and some more random 110", out);
}
}
Notes:
Just in case you don't know: this is a JUnit test.
I have used recursion to parse multiple strings. In my opinion this is a lot easier to read. When you are dealing with thousands of replacements this might lead to a stack overflow though. In that case you will have to rewrite the recursion to a loop.

Problems with drools list not firing for all matched item

I'm starting with drools engine. I tweaked their sample program. it doesn't seem to be working. No matter how many MessageItem I put inside Message, I always get one "Test" printed on the console.
Here is my list file :
package com.sample
import com.sample.Message;
import com.sample.MessageItem;
rule "Hello World"
when
m : Message( status == Message.HELLO, $mItems : messageItems)
mi : MessageItem(message == m, item == "test") from $mItems
then
System.out.println( "Test "); # This is printed only once.
# code to update m and mi
update( m );
update (mi);
end
end
Here are my classes, I have ommitted the getters/setters
public static class Message {
public static final int HELLO = 0;
public static final int GOODBYE = 1;
private String message;
private List<MessageItem> messageItems = new ArrayList<MessageItem>();
private int status;
}
public static class MessageItem {
private String item;
private Message message;
}