Ascending ArrayList is adding element in wrong order - java

I have a list that is comparing the column elements of an ArrayList (essentially, the string word of an ArrayList that contains string lines).
I was able to read the column part correctly, but there's an error for my insertion method (which I'm doing recursively).
For instance, when it finds a word that is smaller than the previous word, instead of inserting it before the bigger word, it inserts it at the beginning of the ArrayList. I'm not exactly sure why this is, as I seem to be following the steps for insertion exactly what my notes say. Can anyone see why this is happening?
//line is just a string separated by commas
private void insertSorted(String line){
//memFile is the ArrayList
if(memFile.isEmpty()){
memFile.add(0,line);
}
else{
for(int i = memFile.size() - 1; i >=0 ; i--){
int index = i;
String lineList = memFile.get(i);
String[] tokens = line.trim().split(",");
String lineList = memFile.get(i);
String[] tokens1 = lineList.trim().split(",");
//column is the part I want to compare of the tokenized string
while(index >= 0){
if((tokens[column]).compareTo(tokens1[column]) < 0)
index--;
}
break;
}
memFile.add(index+1,line);
System.out.println("memFile is " + memFile);
}//for
}//else
}//insertSorted
It's printing out:
3
1
2
2
4
1
as
1
2
2
3
1
4
Edit:
Say I had an ArrayList memfile, and it contained the strings:
" 1,DOG,Airplane"
" 3,HAT,Basket"
And I wanted to sort the third variables by alphabetically order. Then I would tokenize the string, and from the main method, I would call 2 (column is an instance variable I declared making this class). So, then it would search for tokens[col], or, equivalently, tokens[2].

You have a logic mistake in your method, what you are doing is comparing the line with the last value of the memFile instead of comparing the current index line of the memFile when reducing the index
Here i modified the method according to your required logic.
private void insertSorted(String line) {
// memFile is the ArrayList
if (memFile.isEmpty()) {
memFile.add(0, line);
} else {
int index = memFile.size() - 1;
String[] tokens = line.trim().split(",");
// column is the part I want to compare of the tokenized string
while (index >= 0) {
String lineList = memFile.get(index);
String[] tokens1 = lineList.trim().split(",");
if ((tokens1[column]).compareTo(tokens[column]) > 0) {
index--;
} else {
break;
}
}
memFile.add(index + 1, line);
System.out.println("memFile is " + memFile);
}
}
Hope it helps you

Related

I want check each element in the stack collection and print it in reverse. the print out should print each element as long as its in ascending order

The assignment is to print in reverse. each element is on size larger than the previous. so when the order is disrupted it should stop.
public class Program {
private void printWordRun(ArrayList<String> words) {
for(int i = words.size() - 1; i > 0; i--) {
String str = words.get(i);
if(str.length() < words.size()) {
System.out.println(str);
}
}
}
public static void main(String[] args) {
Program program = new Program();
program.testPrintWordRun();
}
private void testPrintWordRun() {
ArrayList<String> words = new ArrayList<>();
words.add("I");
words.add("am");
words.add("cat");
words.add("with");
words.add("happy");
words.add("dog");
words.add("sitting");
System.out.println("Testing printWordRun...");
printWordRun(words);
System.out.println();
}
}
the print should be :
happy
with
cat
am
I
I get :
dog
happy
with
cat
am
I
Starting at the last before element, check if the length of the current string is one less than the next one. If yes, print it.
for(int i = words.size() - 2; i >= 0; i--) {
String str = words.get(i);
if(str.length() == words.get(i + 1).length() - 1) {
System.out.println(str);
}
}
In order to check if the length of the current string is bigger than the length of the previous one, we need to get the previous string and its length:
if (str.length() > words.get(i-1).length())
When you're using:
if(str.length() < words.size())
you're actually checking if the length of the current string is bigger than the size of the ArrayList words.
Also, checking if the order is disrupted shouldn't be done in reverse. If it's in reverse the output should be:
sitting
dog
You might want to create a new list in printWordRun with all the elements in words until the order is disrupted, and then print it in reverse.
Pseudo code:
// The output always contains the first word
list reverseList (words[0]);
// start from the second word
for(word in words)
if word.size == previous_word.size - 1 -> add word to reverse
// start from the end of reverse
for(word in reverse)
print word

Couting Word Frequency

public static void CountWordFrequency(ArrayList<String> UserString) {
//creating an array list to store every word
//each element in the UserString is one line
ArrayList<String> words_storage = new ArrayList<String>();
String words[]= {};
for(int i=0;i<UserString.size();i++) {//this is outer loop to access every line of the ArrayList
//we need to split the line and put them inside the array String
words = UserString.get(i).split("\\s");
//we still need to work with the "\'" , the upper case, and the dot and comma
for(int j=0;j<words.length;j++) {
for(int k=0;k<words[j].length();k++) {//access every character of one word
if(Character.isUpperCase(words[j].charAt(k))) {//first I want to convert them to Lower Case first
words[j]=words[j].toLowerCase();
}
if(!Character.isLetterOrDigit(words[j].charAt(k)) && words[j].charAt(k)!=',' && words[j].charAt(k)!= '.') {
//I am separating the comma and dot situations with the ' \' '
//need more work on this
if(words[j].compareTo("can't")==0) {
words[j]=words[j].replace(words[j].charAt(k), '\0');
words[j]=words[j].replace(words[j].charAt(k+1), '\0');
words[j] = "can";
words_storage.add("not");
}
else {
words[j]=words[j].replace(words[j].charAt(k), '\0');
words_storage.add("is");
}
}
//now if the that character is comma or dot
if(words[j].charAt(k)==',' ||words[j].charAt(k)=='.') {
words[j]=words[j].replace(words[j].charAt(k), '\0');
}
}//done with one-word loop
}
//now we need to store every element of the String Array inside the array list
for(int j=0;j<words.length;j++) {
words_storage.add(words[j]);
}
}//this is the end of the outer loop
//since it's harder to change the content of element in array list compared to array
//we need to store elements in another array
String[] array = new String[words_storage.size()];
for(int a =0;a<words_storage.size();a++) {
array[a] = words_storage.get(a);
}
//now when we are done with storing elements, we need to sort alphabetically
for(int a=0;a<array.length;a++) {
for(int b = a+1;b<array.length;b++) {
if(array[a].compareTo(array[b])>0) {
String temp = array[a];
array[a] = array[b];
array[b] = temp;
}
}
}
//now we count the frequency of each element in the Array array
int marker = 0;//marker will help me skip the word that already counted in the frequency
for(int x =0;x<array.length;x=marker) {
int counter = 1;
for(int y =x+1; y< array.length;y++) {
if(array[x].compareTo(array[y])==0) {//if they have the same content then we increase the counter and mark the y
counter++;
marker = y+1;
}
}
if(counter==1) {//if we did not find any similar word, we need to increase the marker by one to check on the next word
marker++;
}
System.out.println(array[x]+":"+counter); //now just print it out
}
}
Hey guys
I am trying to count word frequency in the given input which has many lines. I stored it in an ArrayList and put it as a paramenter.
First of all, I try to sort them aphabetically first
Right now, I am trying to remove the character ' in the word can't. But it didn't seem to work. so I tried using replace method but it will leave a blank when I replace it with '\0'
Hopefully, I got some solutions. Thanks in advance.
Just use compareTo() or compareToIgnoreCase() method to find the word.

Divide string into several substrings

I have a strings that contain only digits. String itself would look like this "0011112222111000" or "1111111000". I'd like to know how can I get an array of substrings which will consist of strings with only one digit.
For example, if I have "00011111122233322211111111110000000" string, I 'd like it to be in string array(string[]) which contains ["000","111111","222","333","222","1111111111","0000000"].
This is what I've tried
for (int i = (innerHierarchy.length()-1); i >= 1; i--) {
Log.e("Point_1", "innerHierarchy " + innerHierarchy.charAt(i));
c = Character.toChars(48 + max);
Log.e("Point_1", "c " + c[0]);
if (innerHierarchy.charAt(i) < c[0] && innerHierarchy.charAt(i - 1) == c[0]) {
Log.e("Point_1", "Start " + string.charAt(i));
o = i;
} else if (innerHierarchy.charAt(i) == c[0] && innerHierarchy.charAt(i - 1) < c[0]) {
Log.e("Point_1", "End " + string.charAt(i));
o1 = i;
string[j] = string.substring(o1,o);
j=j+1;
}
}
But this code won't work if string looks like this "111111000"
Thank you.
I have "00011111122233322211111111110000000" string, I 'd like it to
be in string array(string[]) which contains
["000","111111","222","333","222","1111111111","0000000"]
One approach I can think of right now (O(n)) (might not be the most efficient but would solve your problem) would be traversing the string of numbers i.e. ("00011111122233322211111111110000000" in your case )
and if char at that position under consideration is not same as char at previous position then making string till that part as one string and continuing.
(approach)
considering str= "00011111122233322211111111110000000"
//starting from position 1 (ie from 2nd char which is '0')
//which is same as prev character ( i.e 1st char which is '0')
// continue in traversal
// now char at pos 2 which is again '0'
// keep traversing
// but then char at position 3 is 1
// so stop here and
//make substring till here-1 as one string
//so "000" came as one string
//continue in same manner.
code
import java.util.*;
public class A {
public static void main(String []args){
String str = "00011111122233322211111111110000000";
str+='-'; //appended '-' to get last 0000000 as well into answer
//otherwise it misses last string which i guess was your problem
String one_element ="";
int start=0;
for(int i=1;i<str.length();i++){
if(str.charAt(i)== str.charAt(i-1) )
{
}
else{
one_element = str.substring(start,i);
start = i;
System.out.println(one_element);//add one_element into ArrayList if required.
}
}
}
}
I have printed each element here as string , if you need an array of all those you can simply use an array_list and keep adding one_element in array_list instead of printing.

Splitting an array with commas to separate each elemnt

I have an output that comes out printing : 1 2 3 4 5
I want the output to be : 1,2,3,4,5
When I print my final array, It looks like : System.out.println(D);
What should I add to it to suit my needs.
All answers are welcome.
why not simply use Arrays.toString
public static String toString(int[] a) Returns a string representation
of the contents of the specified array. The string representation
consists of a list of the array's elements, enclosed in square
brackets ("[]"). Adjacent elements are separated by the characters ",
" (a comma followed by a space). Elements are converted to strings as
by String.valueOf(int). Returns "null" if a is null. Parameters: a -
the array whose string representation to return Returns: a string
representation of a Since:
1.5
try
System.out.println (Arrays.toString (D));
if the spaces are unwanted, then they can be replaced using
System.out.println (Arrays.toString (D).replace(" ", ""));
Replace (typeof x) with the element type of the array (or put this code in a generic function for bonus points, but it won't work for primitive types then):
StringBuilder out = (new StringBuilder());
boolean first = true;
for ((typeof x) x : D) {
if (!first) {
out.append(",")
}
out.append(x.toString());
first = false;
}
return out.toString();
You can create you own methods for printing the result, for example this one :
for (int i = 0; i < D.length; i++) {
System.out.print(D[i]);
if (i != D.length-1){
System.out.print(",");
}
}
I think you are trying to print out an array with commas instead of spaces.
for (int i = 0; i < arr.length() - 1; i++) {
System.out.print(arr[i]);
System.out.print(',');
}
System.out.println(arr[arr.length() - 1]);
You can just print out the elements of the Array singly, like this:
String output = "";
//go through all elements in D
for (int i =0;i<D.length;i++){
//add the Integer to the String
output = output+i;
//add , if not the last element
if (i<D.length-1){
output = output+",";
}
}
//Print it out
System.out.println(output);
Try this code:
If your data type is an array of integer:
int my_array={1,2,3,4,5};
for(int i=0; i < my_array.length; i++) {
System.out.print(my_array[i] + ",");//this line will print the value with a coma (,)
}
If your data type is a string;
String my_number="1 2 3 4 5";
for(int i=0; i < my_number.length; i++){
if(my_number.toCharArray()[i]!=' ')
System.out.print(my_number.toCharArray()[i]+",");
}
Or,
String my_number="1 2 3 4 5";
my_number = my_number.replace(' ', ',');//this method (replace) will replace all space(' ') by coma(',')
System.out.println(my_number);

Find longest strings

I have a large string like "wall hall to wall hall fall be", and I want to print longest strings. Then i want to know how many times all longest strings Is repeated?
For exampele,longest strings are:
wall Is repeated 2
hall Is repeated 2
fall Is repeated 1
This is my code:
public void bigesttstring(String str){
String[] wordsArray=str.split(" ");
int n= str.trim().split("\\s+").length;
int maxsize=0;
String maxWord="";
for(int i=0;i<wordsArray.length;i++){
if(wordsArray[i].length()>maxsize){
maxWord=wordsArray[i];
maxsize=wordsArray[i].length();
}
}
System.out.println("Max sized word is "+maxWord+" with size "+maxsize);
}
But this code only prints "wall".
for count repeated String(i mean "maxWord"),this code write:
int count=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
count++;
}
}
and for display other longest strings i have this code:
int k=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
continue;
}
if(maxsize==wordsArray[i].length()){
k++;
}
}
String[] other=new String[k];
int o=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
continue;
}
if(maxsize==wordsArray[i].length()){
other[o]=wordsArray[i];
o++;
}
}
I allowed to use this functions:
char char At(int i);
int ComoareTo(String another string);
boolean endsWith(String suffix);
int indexof();
int indexof(String str);
String substring();
char[] toCharArray();
String lowercase();
And want another code like this for shortest strings.
You have written
if(wordsArray[i].length()>maxsize)
For wall, hall and fall, it is only true for first wall. That's why you are getting wall and size 4.
Here you are not considering that the longest string length may be same for different string. You will have to store the longest string in an array and if condition should be
if(wordsArray[i].length()>=maxsize)
you will consider = and > case seperately. Since in the case of > you will have to delete all the string in array.
You need to change it to equal because currently if the words is the same length as the current largest word it will ignore it. Also if you want it to have the biggest words. You need to store them in an array. I implemented it here.
package OtherPeoplesCode;
public class string {
public static void main(String[] args) {
bigeststring("wall hall to wall hall fall be");
}
public static void bigeststring(String str){
String[] wordsArray=str.split(" ");
String[] biggestWordsArray = new String[wordsArray.length];
int x = 0;
int n= str.trim().split("\\s+").length;
int maxsize=0;
String maxWord="";
for(int i=0;i<wordsArray.length;i++){
if(wordsArray[i].length()>maxsize){
maxWord=wordsArray[i];
maxsize=wordsArray[i].length();
for(int y = 0; y <= biggestWordsArray.length -1; y++){
biggestWordsArray[y] = "";
}
}
else if(maxsize==wordsArray[i].length()){
biggestWordsArray[x] = wordsArray[i];
x++;
}
}
if(biggestWordsArray[0].equals("")){
System.out.println("Max sized word is "+maxWord+" with size "+maxsize);
}
else if(!(biggestWordsArray[0].equals(""))){
System.out.println("TIE!");
for(int y = 0; y <= biggestWordsArray.length -1; y++){
if(!(biggestWordsArray[y].equals(""))){
System.out.print("Word #" + y + " is ");
System.out.println(biggestWordsArray[y]);
}
}
}
}
}
EDIT: This is the working code, sorry about the delay.
Using Map is possibly the most straight-forward and easy way to do. However if you said your teacher don't allow you to use that, may you tell us what is allowed? So that we don't end up wasting time suggesting different methods and end up none of them is acceptable because your teacher doesn't allow.
One most brute force way that I can suggest you to try is (lots of place for optimization, but I think you may want the easiest way):
loop through the list of words, and find out the length of the longest word and number of words with such length
Create a new array with "number of word" you found in 1. Loop through the original word list again, for each word with length == maxWordLength, put that in the new array IF it is not already existed in it (a simple check by a loop.
Now you have a list that contains all DISTINCT words that are "longest", with some possible null at the end. In order to display them in a format like "word : numOfOccurence", you can do something like
loop through result array until you hit null. For each word in the result array, have a loop in the original word list to count its occurence. Then you can print out the message as you want
in psuedo code:
String[] wordList = ....;
int maxLen = 0;
int maxLenOccurence = 0;
foreach word in wordList {
if word is longer then maxLen {
maxLen = word's length
maxLenOccurence = 1;
}
else if word's length is equals to maxLen {
maxLenOccurence ++
}
}
// 2,3
String[] maxLenWordList = new String[maxLenOccurence];
foreach word in wordList {
else if word's length is equals to maxLen {
for i = 0 to maxLenWordList length {
if (maxLenWordList[i] == word)
break
if (maxLenWordList[i] == null
maxLenWordList[i] = word
}
}
//4
foreach maxLenWord in maxLenWordList {
count = 0
foreach word in wordList {
if maxLenWord == word
count ++
}
display "Max sized word is "+ maxLenWord + " with size " + count
}
Another way doesn't involve other data structure is:
Have the word list
Sort the word list first by length then by the literal value
First element of the result list is the longest one, and string with same value become adjacent. You can do a loop print out all matching and its count (do some thinking by yourself here. Shouldn't be that hard)
Also you can use this;
String[] allLongestStrings(String[] inputArray) {
List<String> list = new ArrayList<String>();
int max = 0;
for (int i = 0; i < inputArray.length; i++) {
StringBuilder s = new StringBuilder(inputArray[i]);
int n = s.length();
if (n > max) {
max = n;
}
}
for (int i = 0; i < inputArray.length; i++) {
StringBuilder s = new StringBuilder(inputArray[i]);
int n = s.length();
if (n == max) {
list.add(s.toString());
}
}
return list.toArray(new String[list.size()]);
}

Categories

Resources