Android find repeat values in ArrayList [duplicate] - java

This question already has answers here:
How to count the number of occurrences of an element in a List
(25 answers)
Closed 6 years ago.
Got an ArrayList like that. Wanna find how many values are repeated:
Example: person:4 times , girl:4 times
public ArrayList<String> new_contains_all= new ArrayList<>();
...
[[laying, beautiful, brushing, group, young, head, bed, close, couple, female, teeth, white, indoor, pair, holding, sunglasses, stuffed, wearing, posing, dress, person, hair, standing, looking, girl, red, playing, made, top, woman, lady, hat, clothing, goggles, people],
[person, hair, young, shirt, looking, phone, girl, white, glasses, food, sunglasses, wearing, woman, hat], [blue, beautiful, person, cake, standing, young, shirt, black, female, board, girl, white, photo, holding, ready, wearing, top, posing, woman, lady, smiling, clothing, dress, suitcase], [street, clock, light, stop, sign, red, text, sitting,
man, photo, traffic], [blue, person, young, looking, phone, sitting, female, girl, photo, computer, using, red, laptop, holding, glasses, food, sunglasses, wearing, top, woman, lady, hat]]
Notify that the Array have 5 elements inside.
Already tried this, that should be working for simple ArrayList but with more than 1 string per element its creepy, i know the solution must implement another bucle inside key, but so tired for today :/ maybe someone blinks my mind :P
List<String> l = new_contains_all;
Set<String> s = new HashSet<String>(l);
for (String key : s) {
int count = Collections.frequency(l, key);
if (count > 1)
System.out.println("Found '" + key + "' " + count + " times."+"key: "+key.toString()+"l: "+l.toString());
}

You almost solved your problem, but there is one subtle bug in your code:
Set<String> s = new HashSet<String>(l);
The core property of a Set is: it doesn't allow for duplicates. Thus this one call simply removes all duplicates from that input list l.
Thus: all frequencies will be one.
So, instead, you can do:
for (String singleWord: new_contains_all) {
count = Collections.frequency(new_contains_all, singleWord);
...

Related

Sort an array of instances of a custom class based on a field

I'm having a problem right now in a project that I'm making just to learn more about java, so I have a txt file which has wonders, I'll have to read it and then store it different information in a object (name country, heightdepth, accessibility, hostility, kmfromlondon, temperature, wondervalue and a fact about the wonder), then I have to sort by the hostility rate and output the all of the wonders
here's the txt file of the wonders:
Amazonia,Brazil,60,10,10,8100,30,4,The Amazon rainforest occupies some 5.5 million square kilometres of South America.
Iguassu Falls,Brazil|Argentina,82,11,50,10064,25,4,Two hundred and seventy waterfalls flow along nearly 3 kilometres of rivers.
Niagra Falls,USA|Canada,50,18,69,5804,20,4,Adventurous tourists can take a cruise on the river below into the falls' mist.
Giant's Causeway,Northern Ireland,12,19,17,592,15,2,Legend has it that is is a former 'walkway' to Scotland.
Great Barrier Reef,Australia,60,10,10,15292,28,4,Over 30 species of whale and 15000 species of fish live here.
Mount Everest,Tibet|Nepal,8840,7,95,7424,-10,4,The highest mountain on Earth is located in the Himalayas.
Mount Vesuvius,Italy,1281,18,95,1630,30,1,The only volcano in mainland Europe to have erupted in the last 100 years.
Old Faithful,USA,55,14,65,7432,118,2,Over half of the world's geysers are located in Yellowstone national park.
Sahara Desert,African Union,3445,14,84,3800,35,3,Covers part of North Africa and is almost the same size as the USA.
Great Rift Valley,African Union,1470,14,12,5887,25,4,The valley was formed by activity between tectonic plates 35 million years ago.
Gobi Desert,Mongolia|China,2700,9,84,7279,30,3,The desert has been the location of many fossil finds.
Ngorongoro Crater,Tanzania,610,14,19,5804,30,2,Home to almost 25000 animals including masses of flamingoes around Lake Magadi.
Perito Morena Glacier,Argentina,60,9,82,13230,-5,3,The 5 kilometre wide glacier is well known for its process of rupturing.
Mount Fuji,Japan,3776,13,69,8671,25,2,Although classed as active its last eruption was in 1707.
Mont Blanc,Italy|France,4808,18,85,808,0,2,The highest mountain in Europe and a popular skiing destination.
The Dead Sea,Israel|Jordan,418,13,91,3666,25,1,The lowest point on the surface of the Earth and is really two large lakes.
The Matterhorn,France|Italy|Switzerland,4478,17,85,840,-5,2,Not the highest mountain in the Alps but perhaps the most breathtaking.
Uluru,Australia,346,10,70,14993,35,4,A massive monolith made from sandstone infused with minerals that reflect in the sunlight.
Lake Baikal,Russia,1637,8,55,6613,-30,2,An immense depth of 1637 metres and contains 20% of the worlds fresh water.
Kilauea,The Hawaiian Islands,1247,9,65,11783,30,3,Hawaiian legend considers the island to be the home of a volcano goddess.
Guilin Caves,China,220,9,16,9101,30,2,The people of Guilin have had to take refuge in them during times of conflict.
Giant Sequoia,USA,84,15,2,8570,30,2,The largest species of tree found only in California.
Mount Erebus,Antarctica,3794,4,95,17059,-49,3,Has continually erupted since 1972 and has a permanent lava lake within its summit.
Grand Canyon,USA,1600,15,80,8296,30,4,A vast and breathtaking spectacle stretching across the Arizona desert.
so I created an object like this
public class Wonders {
String name;
List countries = new ArrayList();
int heightDepth;
int accessibility;
int hostility;
int kmFromLondon;
int temperature;
int wonderValue;
String fact;
List compare = new ArrayList();
and then I stored it like this
String unftxt[];
unftxt = new String[24];
Wonders w[] = new Wonders[unftxt.length];
try (Scanner sfile = new Scanner(new File(fName))) {
while(sfile.hasNextLine()){
unftxt[ctrl] = sfile.nextLine();
ctrl++;
}//end while .hasnextLine()
}//try
for(int i=0;i<unftxt.length;i++){
String[] parts = unftxt[i].split(",");
w[i] = new Wonders();
w[i].name = parts[0];
w[i].countries.add(Arrays.toString(parts[1].split("\\|")));
w[i].heightDepth = Integer.parseInt(parts[2]);
w[i].accessibility = Integer.parseInt(parts[3]);
w[i].hostility = Integer.parseInt(parts[4]);
w[i].kmFromLondon = Integer.parseInt(parts[5]);
w[i].temperature = Integer.parseInt(parts[6]);
w[i].wonderValue = Integer.parseInt(parts[7]);
w[i].fact = parts[8];
}
I'm new in programming and I've been stuck for a while now so my question is how can I sort this array by hostility
The regular way to define a custom ordering in Java is via a Comparator instance. This object can be plugged into the sorting routines of eg Arrays or Collections.
In Java 8 for example you can sort your array like so:
Arrays.sort(wonderArray, Comparator.comparingInt(wonder -> wonder.hospitality));
In Java 7 or before, you can do it with an anonymous class:
Arrays.sort(wonderArray, new Comparator<Wonder>() {
#Override public int compareTo(Wonder w1, Wonder w2) {
return Integer.compare(w1.hospitality, w2.hospitality);
}
});

Eclipse android IndexOutOfBounds

currently i dont know what im doing wrong here is my sample code please help me
Problem:
02-28 03:41:51.750: E/AndroidRuntime(8431): java.lang.IndexOutOfBoundsException: Invalid index 95, size is 90
02-28 03:41:51.750: E/AndroidRuntime(8431): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
02-28 03:41:51.750: E/AndroidRuntime(8431): at com.example.finalpro.ThirdQuiz$1.onClick(ThirdQuiz.java:248
02-28 03:41:51.750: E/AndroidRuntime(8431): at com.example.finalpro.ThirdQuiz.showNextQuiz(ThirdQuiz.java:194)
02-28 03:41:51.750: E/AndroidRuntime(8431): at java.util.ArrayList.get(ArrayList.java:308)
Now my Java :
public class ThirdQuiz extends ActionBarActivity {
private TextView countLabel;
private TextView questionLabel;
private Button answerBtn1;
private Button answerBtn2;
private Button answerBtn3;
private Button answerBtn4;
private String rightAnswer;
private int rightAnswerCount = 0;
private int quizCount = 1;
static final private int QUIZ_COUNT = 25;
int quizCategory = 0;
ArrayList<ArrayList<String>> quizArray = new ArrayList<>();
String quizData[][] = {
// {"Country", "Right Answer", "Choice1", "Choice2", "Choice3"}
{"Feed me and I live, yet give me a drink and I die", "Fire"," Ice ","Hot","Cold"} ,
{"I fly without wings, I cry without eyes. What am I", " Clouds"," Rain ","Rainbow ","Sun"},
{"You can see me in water, but I never get wet. What am I?", " A reflection"," Mirror","Wall","BlackBoard"},
{"What belongs to you but others use it more than you do?", " Your name"," Your NickName","Your LastName"," Your UserName"},
{"What 4-letter word can be written forward, backward or upside down, and can still be read from left to right?", " NOON"," Moon","Four","Dead"},
{"What runs around the whole yard without moving?", " A fence"," Wall","Board"," Table"},
{"What kind of table can you eat?", " Vegetable"," Meat","Fruits"," Chicken"},
{"What's orange and sounds like a parrot?", " A carrot","Banana","Meat"," Potato"},
{"Which is the most curious letter?", " Y?","A?","B?"," X?"},
{"What does the big tomato say to the small tomato?", " Ketchup","Mang Thomas","Datu Puti","Silver Swan"},
{"What begins with T, ends with T and has T in it?", " Teapot","Team Potatot","Tilt","Talt"},
{"People buy me to eat, but never eat me. What am I?", "Plates and cuttlery","My Friends","Food","Junk Food"},
{"The more you take, the more you leave behind. What am I?", "Footsteps","Slow Motion","At the back","Hiding"},
{"A blue house has blue bricks; a yellow house has a yellow bricks. What is a green house made of?", "Glass","Grass","Wall","Door"},
{"Railroad crossing without any cars. Can you spell that without any R’s?", "Thats","Why","Where","How"},
{"What kind of dog keeps the best time?", "Watchdog","Watch Anime","Watch Cartoons","Watch Actions"},
{"You can do this with your friends. You can do this with your nose. But don't do it with your friend's nose!", "Pick","Touch","Watch","Move"},
{"What is it something that you always have but you always leave behind?", "Fingerprints","Footprints","Faceprints","Bodyprints"},
{"How can you physically stand behind your father while he is standing behind you?", "Stand back to back","Following me","Stay","Istalker"},
{"There was a plane crash every single person died. Who survived?", "Married couples","Single Parents","Single","RelationShip"},
{"What does no man want, yet no man want to lose?", "His job","His Family","Important to me"," His RelationShip"},
{"This company makes billions of dollars selling Windows.", "Microsoft","Google","PowerPoint"," Microsoft Office"},
{"What language does a billboard speak?", " Sign language"," Rain ","Rainbow ","Sun"} ,
{"What does this mean? Wondealicerland", "Alice in wonderland"," Batman ","Superman ","SpiderMan"} ,
{"Which ring is square?", "A boxing ring","Basketball Court ","Volleyball Court ","Class Room"} ,
{"What US state is surrounded by the most water?", "Hawaii"," Canada ","America ","Hongkong"} ,
{"Three times what number is no larger than two times that same number?", "0"," 2 ","4","6"} ,
{"Which of Santa's reindeer can you see in outer space?", "Comet"," Asteroid ","Meteors","Planet"} ,
{"What gets tighter when stretched?", "A budget"," Exercise ","Hungry","Waster"} ,
{"When set loose I fly away, Never so cursed As when I go astray.", "A fart"," hungry ","Hurry","Sleepy"} ,
{"Everyone has me but nobody can lose me. What am I?", "A shadow"," A friend ","Family","Enemy"} ,
{"Fashions change but what can a person wear that is never out of style?", "A smile"," Sad ","Angry","Ugly"},
{"A kind of tree can you carry in your hand?", "A palm"," Foot ","Ears","Touch"} ,
{"What can you catch but not throw?", "A cold"," Sad ","Angry","Ugly"} ,
{"What sits in a corner while travelling all around the world?", "Stamp"," Hi ","Signature","Messages"} ,
{"I'm flat when I'm new. I'm fat when you use me. I release my gas when something sharp touches me. What am I?", "A balloon"," Mirror","Picture","Selfie"},
{"I am a king who’s good at measuring stuff. What am I?", "Ruler"," Ball Pen ","Eraser","Pencil"},
{"Which word contains 26 letters but only three syllables?", "Alphabet"," Letters ","Spelling","Direction"} ,
{"What can you hear but not touch or see and yet control?", "Your voice"," Moving ","Stay","Go away"} ,
{"What did the thief get for stealing the calendar?", "12 Months"," 10 Months ","11 Months","8 Months"} ,
{"Before Mt. Everest was discovered as the highest mountain in the world, which mountain was the highest?", "Mt Everest"," Mt k2 ","Mt Makalu","Mr Panaslu"} ,
{"howers bring may flowers, what do may flowers bring?", "Pilgrims"," Ball Pen ","Eraser","Pencil"} ,
{"What did Adam say the day before Christmas?", "It's Christmas, Eve!"," New Year ","Birthday","Reunion"} ,
{"What kind of fish chases a mouse?", "Catfish"," Dog ","Horse","Bird"} ,
{"What has four legs, but can't walk?", "A table"," Board ","Chair","Pencil"} ,
{"What is always slow to come, but never actually happens?", "Tomorrow"," Yesterday ","Later","After Noon"} ,
{"If you blow past your destination, you'll have to throw your car into this."," Reverse ","Force","Move","Walk"},
{"What has a mouth but can't chew?", "River"," Road ","Air","Inside"} ,
{"David's father has three sons: Snap, Crackle, and ?","David"," Angel ","Mico","Klein"} ,
{"What has a ring, but no finger?", "Phone"," Laptop ","Computer","Tablet"},
{"You play with me at night before going to sleep. You can’t get caught fiddling with me at work. You only let a select few people touch me. What am I?","Phone","pillow","blanket","toys"},
{" What’s a four-letter word that ends in “k” and means the same as intercourse?","Talk","seek","peek","weak"},
{" I start with a “v” and every woman has one. She can even use me to get what she wants. What am I?","voice.","vase","vein","verse"},
{" I come in a lot of different sizes. Sometimes, I drip a little. If you blow me, it feels really good. What am I?","nose.","mout","ears","eyes"},
{".What’s in a man’s pants that you won’t find in a girl’s dress?","Pockets","stripes","buttons","zipper"},
{"You stick your poles inside me. You tie me down to get me up. I get wet before you do. What am I?","tent.","house","barbique","rope"},
{"What’s long and hard and has cum in it?","cucumber","egg plant","bittergourd","bottlegourd"},
{" If I miss, I might hit your bush. It’s my job to stuff your box. When I come, it’s news. What am I?","newspaperboy","reporter","tv","radio"},
{" What four-letter word begins with “f” and ends with “k,” and if you can’t get it you can always just use your hands?"," fork","fowk","feek","flak"},
{" All day long it’s in and out. I discharge loads from my shaft. Both men and women go down on me. What am I?","elevator","escalator","stairs","ladders"},
{"I’m spread out before being eaten. Your tongue gets me off. People sometimes lick my nuts. What am I?","Peanut butter.","jelly","ketchup","mayonnaise"},
{"Arnold Schwarzenegger’s is really long. Michael J. Fox’s is short. Daffy Duck’s isn’t human. Madonna doesn’t have one. What am I?","last name","first name","middle name","nickname"},
{"What is hard and hairy on the outside, soft and wet on the inside? The word begins with “c,” ends in “t,”.","coconut.","coat","cat","carrot"},
{"I start with a “p” and ends with “n” and I’m a major player in the film industry. What am I?","popcorn","person","penguin","putin"},
{"My business is briefs. I’m a cunning linguist. I plead and plead for it regularly. What am I?","lawyer","judge","police","governor"},
{"You get a lot of it if you’re powerful and successful, but significantly less when you’re just starting out. You sometimes do it with yourself, but it’s a lot better when you do it with another person. What am I talking about?","email","chat","text","mail"},
{"I have a stiff shaft. My tip penetrates. I come with a quiver. What am I?","arrow","javellin","bullet","rocket"},
{"I go in hard but come out soft, and I never mind if you want to blow me. What am I?","bubblegum","clay","paper","cement"},
{"What does a dog do that a man steps into?","pants","shorts","shirt","underwear"},
{"I’m great for protection. You use your fingers to get me off. What am I?","gloves","cloth","shield","ring"},
{"What gets longer if pulled, fits snugly between breasts, slides neatly into a hole, chokes people when used incorrectly, and works well when jerked?","seatbelt","belt","tie","sash"},
{"What’s beautiful and natural, but gets prickly if it isn’t trimmed regularly?","lawn","park","tree","hair"},
{"All men have one, but it’s longer on some than others. The Pope never uses his, and a man gives it to his wife once they’re married.","last name","first name","middle name","nickname"},
{"I assist with erections. Sometimes, giant balls hang from me. I’m known as a big swinger. What am I?","crane","wrecking ball","giant arm","hook"},
{"You find me in a guy’s pants. I’m about six inches long, I have a head, and some women love to blow me. What am I?","twenty dollar bill","credit card","check","ID"},
{"When I go in, I can cause some pain. I’ll fill your holes when you ask me to. I also ask that you spit, and not swallow. What am I?","dentist","Dermatologists ","Endocrinologists ","Colon and Rectal Surgeons "},
{"I grow in a bed, first white then red, and the plumper I get, the better women like me. What am I?","strawberry.","raspberries"," blueberries"," blackcurrants"},
{"I’m the highlight of many dates. I’m especially responsive when you put your fingers deep inside me. What am I?","bowling ball","basketball","baseball","soccer"},
{"What’s made of rubber, handed out at some schools, and exists to prevent mistakes?","Erasers","pencils","chalk","paper"},
{"I’m at least six inches long. I love it wet and foamy when I get to do my job. What am I?","toothbrush.","comb","brush","sponge"},
{"Over 1,000 people went down on me. I wasn’t a maiden for long. Something really big and hard ripped me open. What am I?","titanic","train to busan","snake on a plane","fast and furious"},
{"It’s a fun thing to do and you devote a significant amount of energy to thinking about it, but you hate knowing that your parents are doing it. What is it?","facebook","twitter","instagram","youtube"},
{"What’s most useful when it’s long and hard?","education","patience","relationship","trust"},
{"What’s white, sticky, and better to spit than to swallow?","toothpaste","glue","mayonnaise","milk"},
{"A lot of people like these to be as long as possible, but short ones can be effective, and it’s definitely possible for them to be too long. What are they?","tweets","cooments","reply","post"},
{"Name a word that’s four letters long, ends in “u-n-t” and is used to refer to some women?","aunt","uncle","grandmother","grandfather"},
{"What does a woman have two of the a cow has four of?","legs","arms","foot","toe"},
{"What goes up, lets out a load, and then goes back down?","elevator","bus","plane","rocket"},
{"If you put three fingers into these holes, it's gonna be a shocker. What am I talking about?","power outlet","window","bowlingball holes","ears"},
{"Some people prefer being on top, others prefer being on the bottom, and it always involves a bed.","bunk bed","floor","bedroom","bedrock"},
{"What goes naked to keep you warm?","sheep","cow","chicken","fish"},
{"What does a gay horse eat?","haaaay","grass","leaves","fish"},
{"If there is H2O on the inside of a fire hydrant, what is on the outside? ","K9P","CuTe","SiLi","h2"},
{"What word starts with ''c'' and ends with ''t'' and is synonymous with pussy?","cat","chicken","crow","cow"},
{"what is tall when it's young and short when old?","candle","pole","building","statue"},
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third_quiz);
countLabel = (TextView)findViewById(R.id.countLabel);
questionLabel = (TextView)findViewById(R.id.questionLabel);
answerBtn1 = (Button)findViewById(R.id.answerBtn1);
answerBtn2 = (Button)findViewById(R.id.answerBtn2);
answerBtn3 = (Button)findViewById(R.id.answerBtn3);
answerBtn4 = (Button)findViewById(R.id.answerBtn4);
Typeface font3 = Typeface.createFromAsset(getAssets(), "GrinchedRegular.otf");
countLabel.setTypeface(font3);
questionLabel.setTypeface(font3);
answerBtn1.setTypeface(font3);
answerBtn2.setTypeface(font3);
answerBtn3.setTypeface(font3);
answerBtn4.setTypeface(font3);
//Receive from StartuActivitu
quizCategory = getIntent().getIntExtra("QUIZ_CATEGORY",0);
Log.v("CATEGORY_TAG", quizCategory + "");
// Create quizArray from quizData.
for (int i = 0; i < quizData.length; i++) {
// Prepare array.
ArrayList<String> tmpArray = new ArrayList<>();
tmpArray.add(quizData[i][0]); // Country
tmpArray.add(quizData[i][1]); // Right Answer
tmpArray.add(quizData[i][2]); // Choice1
tmpArray.add(quizData[i][3]); // Choice2
tmpArray.add(quizData[i][4]); // Choice3
// Add tmpArray to quizArray.
quizArray.add(tmpArray);
}
showNextQuiz();
}
public void showNextQuiz() {
// Update quizCountLabel.
countLabel.setText("Q" + quizCount);
// Generate random number between 0 and 14 (quizArray's size - 1).
Random random = new Random();
int randomNum= 0;
if(quizCategory==0){
randomNum = random.nextInt(quizArray.size());
}
else if (quizCategory==1){
randomNum = random.nextInt(50 - 0) + 0 ;
}
else if (quizCategory==2){
randomNum= random.nextInt(100 - 50) + 50;
}
else {
randomNum= random.nextInt(150 - 100)+100;
}
// Pick one quiz set.
ArrayList<String> quiz = quizArray.get(randomNum);
// Set question and right answer.
// Array format: {"Country", "Right Answer", "Choice1", "Choice2", "Choice3"}
questionLabel.setText(quiz.get(0));
rightAnswer = quiz.get(1);
// Remove "Country" from quiz and Shuffle choices.
quiz.remove(0);
Collections.shuffle(quiz);
// Set Choices.
answerBtn1.setText(quiz.get(0));
answerBtn2.setText(quiz.get(1));
answerBtn3.setText(quiz.get(2));
answerBtn4.setText(quiz.get(3));
// Remove this quiz from quizArray.
quizArray.remove(randomNum);
}
public void checkAnswer(View view) {
// Get pushed button.
Button answerBtn = (Button) findViewById(view.getId());
String btnText = answerBtn.getText().toString();
String alertTitle;
if (btnText.equals(rightAnswer)) {
// Correct!
alertTitle = "Correct!";
rightAnswerCount++;
} else {
// Wrong...
alertTitle = "Wrong...";
}
// Create Dialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(alertTitle);
builder.setMessage("Answer : " + rightAnswer);
builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (quizCount == QUIZ_COUNT) {
// Show Result.
Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
intent.putExtra("RIGHT_ANSWER_COUNT", rightAnswerCount);
startActivity(intent);
} else {
quizCount++;
showNextQuiz();
}
}
});
builder.setCancelable(false);
builder.show();
}
}
Lastly let me add that i havent put the last details on index 100-150 our if fits realy index sorry if im stupid or sound stupid im fairly new ot this im really sorry.

Test instances always classified in to the the same class

I have written a java program that build a J48 classifier using training set. Then I pass a test instance to the classifier to predict the unknown class. But each and every test instance classified in to first element of the class attribute.
example : - if I declare element of class attributes,
cls.add("positive");
cls.add("negative");
In this order, each instance classified in to first class element which is positive.
If I declare class element in this order,
cls.add("negative");
cls.add("positive");
each instance classified in to first class element which is negative.
My training set shows more than 90% accuracy in weka explore.
public static void main(String[] args) throws Exception {
StringToWordVector filter = new StringToWordVector();
//training set
BufferedReader reader;
reader = new BufferedReader(new FileReader("D:/suicideTest.arff"));
Instances train = new Instances(reader);
train.setClassIndex(train.numAttributes() -1);
filter.setInputFormat(train);
train = Filter.useFilter(train, filter);
reader.close();
J48 nb = new J48();
nb.buildClassifier(train);
ArrayList cls = new ArrayList(2);
cls.add("positive");
cls.add("negative");
Attribute clsAtt = new Attribute("class", cls);
//ArrayList<String> tweet = new ArrayList(1);
//String tweet = "";
//Attribute tweetAtt = new Attribute("tweet", tweet);
ArrayList allAtt = new ArrayList(2);
//allAtt.add(tweetAtt);
allAtt.add(new Attribute("tweet", (FastVector) null));
allAtt.add(clsAtt);
// Create an empty test set
Instances testSet = new Instances("", allAtt, 1);
// Set class index
testSet.setClassIndex(testSet.numAttributes() - 1);
String names= "Fox News Devotes a Whole Evening[']s Worth of Programming to Whining About CNNAgain (column by #justinbaragona)";
Instance inst = new DenseInstance(2);
inst.setValue((Attribute)allAtt.get(0), names.toString());
testSet.add(inst);
System.out.println(testSet.instance(0).toString());
double pred = nb.classifyInstance(testSet.instance(0));
filter.setInputFormat(testSet);
testSet = Filter.useFilter(testSet, filter);
String predictString = testSet.classAttribute().value((int) pred);
System.out.println(predictString);
}
my training set look like
#RELATION suicidalideation
#ATTRIBUTE tweet string
#ATTRIBUTE class {positive,negative}
#DATA
"is it weird to be tired of living. i just. don't want to exist for a while", positive
"I don't want to exist", positive
"i don't want to exist in this world without you", positive
"I simply just don't want to exist anymore.", positive
"I don't want to exist im fed up of all this shit", positive
"I am deeply sad that i don't want to exist now", positive
"It's feel like I don't want to exist to anybody life", positive
"fuck me up i don't want to exist for myself", positive
"I don't want to be alone, I don't want to be in my room, I don't want to exist", positive
"I just kind of don't want to exist right now cause stress is just too much", positive
"if i'm going to be a problem i don't want to exist", positive
"If he leaves me I don't want to go on anymore..will jump to running train ..", positive
"Im dead inside and I don't want to go on.", positive
"I don't want to go on living in this world without you", positive
"I hate my life and Don't want to go on further", positive
"I dont want to go on living in this world without you", positive
"Wance&Forall | Coming SoonnHow soon depends on you!nLIKE/FOLLOW Wance & Forall on " , negative
"RT #ChampionsLeague: Zidane: Toughest opponent? Scholes. The complete midfielder; undoubtedly the greatest midfielder of his generation.[...]" , negative
"You are excited to participate in activities with people who m... " , negative
"RT #pussypun: rub ur ass against his dick by accident on purpose" , negative
"RT #NiallOfficial: Have a great 4th of July , America" , negative
"RT #thedrewpowell: Happy Birthday America! #FourthOfJuly" , negative
"RT #virtuaIg: she a child sir " , negative
"Happy 4th of July Fillies! Good day to play some golf. Coach played 9. How bout you? " , negative
"#TheEFCForum Fair enough. We will see. But I'm doubting I'm going to be wrong on this to be honest, if I am fair enough." , negative
"RT #_EVANGELO: We are aware we weren't free on this date. Please shut the entire fuck up and EAT. Gaddamn! Every damn holiday y'all got som[...]" , negative
"Langley's Abbey Fortin going to bat for Canada #Langley #bhivecan" , negative
"Daily Organic Multivitamins for Kids GLUTEN FREE - SUGAR FREE - VEGAN - KOSHER - HALAL VITAMIN SUPPLEMENTS Nutra Pharmnmultivitamin has 45" , negative
"RT #skinupgg: ST SSG 08 DRAGONFIRE GIVEAWAY OH MY GOD nnIT'S SO LIT nTO ENTERnn[?] RETWEET & FOLLOWn[?] " , negative
"RT #DerekCressman: Happy July 4th. Let's Declare American Independence from Russian interference in our sovereignty" , negative
"RT #wordstionary: Never let your past dictate your future. It's never too late to become better." , negative
"RT #Jon_Wienke: Stopped to clean his sign. Nothing but respect for my president. " , negative
"#Ayindeemu Please help my friend win the #isokenmovie #IsokenMegaGiveaway contest by liking the tweet above Please!n #_idarahh" , negative
"RT #politicques: What to The Slave is 4th of July? -- 1841 Speech by Frederick Douglass -- Courtesy of The Freeman Institute... " , negative
"idk why that bothers me" , negative
"RT #JPY_Kurdish: Stoke-on-Trent, England: [?] pedophile hunter group catches a Muslim man who wants to meet a 13-year-old girl for sex at Cen[...]" , negative
"#Danny_Draws Hah, that's very Portland. I wonder if it affects water pressure. :)" , negative
"RT #CSGORoll: AK-47 | Case Hardened FTnn- RTn- Follown- Enable notifications on CSGORolln- Play " , negative
"Nobody can go back... Maria Robinson #quote #quotes #inspiration #findyourhappily " , negative
"RT #ManuBlinkVIP: Rosé talking about IU again! You're doing great sweetie, keep mentioning that, this collab must happen!" , negative
"need to be as lit as the fireworks tonight" , negative
"#RyderDanielz #davey_sap ...I think he would be a great opponent for me at 'Chantz Of A Lifetime' for my titles." , negative
"RT #RealNiggy_: well if you move i could see all my options " , negative
"#Komangsrie21 polback donv" , negative
"RT #PeadaPipper: Easy Breezy Beautiful. " , negative

HashMap: sorting key into alphabetical order with it's mapped values

I asked a question here a while ago, fixed it, but now I have run into another problem.
This is jumblesOrdered ArrayList: [act, opst, dgo, art, aprt, fgor]
This is jumbles ArrayList: [atc, otsp, gdo, atr, arpt, grof]
This is dictionaryOrdered ArrayList: [act, act, act, dgo, dgo, opst, opst, opst, opst, opst, opst, art, art, art, aprt, aprt, aprt, fglo, fglo, fgor, gopr, glos]
This is dictionary ArrayList: [act, cat, tac, dog, god, post, pots, stop, spot, tops, opts, rat, tar, art, trap, tarp, part, flog, golf, frog, gorp, slog]
This is jumbleWordHM: {opst=otsp, art=atr, fgor=grof, aprt=arpt, dgo=gdo, act=atc}
This is dictWordHM: {opst=post pots stop spot tops opts, art=rat tar art, glos=slog, gopr=gorp, fgor=frog, aprt=trap tarp part, dgo=dog god, act=act cat tac, fglo=flog golf}Current Output:
Current Output:
atc act cat tac
otsp post pots stop spot tops opts
gdo dog god
atr rat tar art
arpt trap tarp part
grof frog
Desired Output:
arpt part tarp trap
atc act cat tac
atr art rat tar
gdo dog god
grof frog
otsp opts post pots spot stop tops
My code for printing out current output:
for (int i = 0; i < jumblesOrdered.size(); i++) {
String wordAnswer = jumblesOrdered.get(i);
System.out.println(jumbles.get(i) + " " + dictWordHM.get(wordAnswer));
}
The first word of each line is the scrambled word, and the subsequent words are the dictionary words that can be made from the scrambled letters.
My only problem is that I want to organize the scrambled words into alphabetical order like:
arpt - dictionary words
atc - dictionary words
atr - dictionary words
etc.....
HashMap cannot be sorted, you should use some kind of a sorted map, like TreeMap, but maps can only sort by keys. (TreeSet could also be beneficial, it only takes a key and sorts them automatically.)
Consider using a TreeSet or TreeMap, which automatically use natural ordering on their elements.
Probably a TreeMap where the key is element 1, and the value is the ArrayList the element comes from. (A TreeSet is basically a TreeMap with only a key--no value.)

Java midi note to string mapping via octave of a note

In my project I want to be able to at least inform the user what string the note they need to play is on. I can get the note and its octave but as I've discovered, that note and its octave can appear in multiple places on a guitar fret board.
So my question is: Is there anyway to map a midi note to a guitar string?
Here's code that takes the MIDI note value and returns the position on the guitar fretboard closest to the end of the instrument. Fret zero is an open string.
static class Fingering {
int string;
int fret;
public String toString() {
return "String : " + stringNames[string] + ", fret : " + fret;
}
}
static String[] stringNames = new String[] {"Low E", "A", "D", "G", "B", "High E"};
/** Array showing guitar string's relative pitches, in semi-tones, with "0" being low E */
static int[] strings = new int[]{64, 69, 74, 79, 83, 88};
public static Fingering getIdealFingering(int note) {
if (note < strings[0])
throw new RuntimeException("Note " + note + " is not playable on a guitar in standard tuning.");
Fingering result = new Fingering();
int idealString = 0;
for (int x = 1; x < strings.length; x++) {
if (note < strings[x])
break;
idealString = x;
}
result.string = idealString;
result.fret = note - strings[idealString];
return result;
}
public static void main(String[] args) {
System.out.println(getIdealFingering(64)); // Low E
System.out.println(getIdealFingering(66)); // F#
System.out.println(getIdealFingering(72)); // C on A string
System.out.println(getIdealFingering(76)); // E on D string
System.out.println(getIdealFingering(88)); // guitar's high e string, open
System.out.println(getIdealFingering(100)); // high E, 12th fret
System.out.println(getIdealFingering(103)); // high G
}
Result:
String : Low E, fret : 0
String : Low E, fret : 2
String : A, fret : 3
String : D, fret : 2
String : High E, fret : 0
String : High E, fret : 12
String : High E, fret : 15
Yes, with simple logic you can do this. I would consider using a HashMap of <Note, MidiNote> where Note is your class that holds both relative note and octave and has decent equals and hashcode methods, and MidiNote is your class to represent a Midi note.
Think of MIDI as like defining piano keys. Codes and keys are one-to-one. This is unlike a guitar or violin, where the same tone can be played in multiple places.
If you want to represent the greater freedom you have on a guitar in some data format, you'll have to find or invent a different format. MIDI won't encode what you want.
However, there's an indirect way you might go about this, and it has to do with developing heuristics as to where to play a note given a sliding window of notes that came before. A given note may be easier on one string or another depending on what you've just played, and you can calculate that given a model of the hand and where fingers will have been. Based on this, you can convert MIDI to guitar in a way that makes the MIDI easiest to play. If you have a piece of guitar music that follows these rules already, then you can encode it in MIDI and then decode it later.
But perhaps your question is more basic. Yes, you can map a MIDI note to a guitar. The naive method is to make a mapping of each note playable on the guitar, and you decide between equivalent alternatives by picking the one closest to the nut. This would be an easy one-to-one mapping but wouldn't necessarily be the easiest to play.
If you REALLY want to do it right, you'll do a careful analysis of the music to decide the optimal hand position and where the hand position should change, and then you'd associate MIDI notes with frets and strings based on what's easiest to reach based on the hand position. The optimal solution is probably NP-complete or worse, do you'd probably want to develop an approximate solution based on some rules about how often and how far you can change hand position.

Categories