using doubly linked list to process a text - java

I have to read a paragraph containing words from an input file. then create a doubly linked list containing the distinct words read, where the words of the same length are placed in the same list, in ascending order.
So i tried to create an array of doubly linked list, I know how to add the words but I can't sort them in ascending order.(we have to sort the words while adding them, not sorting the text then adding.)
int x = max(s);
DoublyLinkedList[] list = new DoublyLinkedList[x];
for (int i = 0; i < list.length; i++) {
list[i] = new DoublyLinkedList();
}
public static void m(DoublyLinkedList[] list, String s) {
String[] s1 = s.split(" ");
for (int i = 0; i < s1.length; i++) {
list[s1[i].length()].addLast(s1[i]);
}
}
public static int max(String s) {
String[] s1 = s.split(" ");
int max = s1[1].length();
for (int i = 0; i < s1.length; i++) {
if (s1[i].length() > max) {
max = s1[i].length();
}
}
return max + 1;
}

public static void insertAtRightSpot(DoublyLinekdList list, String s){
int i = 0;
boolean inserted = false;
while(i<list.length()){
if(list.get(i).compareTo(s) < 0){
i++;
} else {
list.insertAt(s, i);
inserted = true;
break;
}
}
if (!inserted) list.addLast(s);
}
Try insertAtRightSpot(list[s1[i].length()], s1[i]) instead of list[s1[i].length()].addLast(s1[i])
The Method searches for the first Element that is not smaller that the one you want to insert and inserts it right before

Related

how to remove duplicates in a string, for example: "my name is this and that this and that"- the output would be "my name is this and that" [duplicate]

This question already has answers here:
Removing duplicates from a string
(7 answers)
Closed 2 years ago.
i have tried this
public static void duplicateRemover(){
//removes all the duplicate words in a string from the user
//ask the user to enter his/her input
System.out.println("Enter your sentence: ");
//get user input
Scanner string = new Scanner(System.in);
String UserInput = string.nextLine();
//add comas into string and create an array
String[] arrayString = UserInput.split(",");
System.out.print(Arrays.toString(arrayString));
//create a new array that stores the non duplictes
String[] newArray = new String[arrayString.length];
Arrays.asList(newArray);
//loop through array to find duplicates
for (int i = 0 ; i < arrayString.length; i ++){
for (int j = 0; i < arrayString.length; i ++){
//try to remove duplicates
if (i != j){
//this is tha part i am struggling with, how would i removes a duplicate after looping through he array
String a = Integer.toString(i);
String b = Integer.toString(j);
newArray.add(a);
}
This seems to be the easier way:
List<String> arr = Arrays.asList(source.split("\\s"));
Set<String> distincts = new LinkedHashSet<>(arr);
String result String.join(" ", distincts);
Rewriting above using Java 8 streams
public void duplicateRemover() {
String source = "my name is this and that this and that";
List<String> distincts = Arrays.stream(source.split("\\s")).distinct().collect(Collectors.toList());
String result = String.join(" ", distincts);
System.out.println(result);
}
In Array It will work
public class RemoveDuplicateInArrayExample{
public static int removeDuplicateElements(int arr[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (arr[i] != arr[i+1]){
temp[j++] = arr[i];
}
}
temp[j++] = arr[n-1];
// Changing original array
for (int i=0; i<j; i++){
arr[i] = temp[i];
}
return j;
}
public static void main (String[] args) {
int arr[] = {10,20,20,30,30,40,50,50};
int length = arr.length;
length = removeDuplicateElements(arr, length);
//printing array elements
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");
}
}

Selection Sort using a comparable class [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I made java Selection Sort using Comparable class, File scanner.
In this code, we get txt file's name and store all words in String[] list and show index and stored word.
Finally, we sort this String[] list using Selection Sorting and check how much time was spent. but there's some error code.
This is an AbstractSort class
abstract class AbstractSort
{
public static void sort(Comparable[] a) { };
protected static boolean less(Comparable v, Comparable w )
{
return v.compareTo(w) < 0; // This Line is Error
}
protected static void exch(Comparable[] a, int i, int j)
{
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
protected static void show(Comparable[] a)
{
for(int i = 0; i < a.length; i++)
System.out.println(a[i] + " ");
System.out.println();
}
protected static boolean isSorted(Comparable[] a)
{
for(int i = 1; i < a.length; i++)
{
if(less(a[i], a[i - 1])) // This Line is also Error
return false;
}
return true;
}
}
and this is a Selection Sort class which is extends AbstractSort class
class Selection extends AbstractSort {
public static void sort(Comparable[] a) {
int n = a.length;
for(int i = 0; i < n - 1; i++) {
int min = i;
for(int j = i + 1; j < n; j++) {
if(less(a[j], a[min]))
min = j;
}
exch(a, i, min);
}
assert isSorted(a);
};
}
and this is main function
public class HW1{
static String[] resize(int idx, String[] arr) {
String[] temp = new String[idx * 2];
for(int i = 0; i < idx; i++)
temp[i] = arr[i];
return temp;
}
public static void main(String args[]) {
int INIT_LEN = 10000;
long start, end, time;
String[] list = new String[INIT_LEN];
Scanner sc = new Scanner(System.in);
int idx = 0;
try {
System.out.println("File Name?");
String src = sc.nextLine();
sc = new Scanner(new FileInputStream(src));
while(sc.hasNext()) {
String word = sc.next().toString();
if(idx == list.length)
list = resize(idx, list);
list[idx++] = word;
}
System.out.println("1. Total Word = " + idx);
for(int i = 0; i < idx; i++)
System.out.println(i + "idx:" + list[i]);
start = System.currentTimeMillis();
Selection.sort(list); // This Line is also Error
end = System.currentTimeMillis();
time = end - start;
System.out.println("2. Selection Sorted? = true, Time = " + time + "ms");
}catch (FileNotFoundException fnfe) {
System.out.println("No File");
}catch (IOException ioe) {
System.out.println("Can't Read File");
}
}
}
when I run this code, I can see all words are stored int String[] list but there's also error code together.
Exception in thread "main" java.lang.NullPointerException
at AbstractSort.less(HW1.java:8)
at Selection.sort(HW1.java:40)
at HW1.main(HW1.java:84)
I don't know why this error code is occured...
When you call Selection.sort(list) in main, it appears that the list has a length of 10000.
Every element defaults to null.
So if you read in three words your list will look like this:
word1,word2,word3,null,null,null......null
Quick hack so you don't need to resize the array - try making your inner loop in Selection::sort:
for (int j = i + 1; j < n; j++) {
if (a[j] == null) {
break;
}
if (less(a[j], a[min]))
min = j;
}
Or - resize the array appropriately before processing.
Or - use an ArrayList to push words to and then convert to an array if you absolutely must use an array.

sub arraylist's size isn't correct

After hard searchig I still haven't found the proper answer for my question and there is it:
I have to write a java program that enters an array of strings and finds in it the largest sequence of equal elements. If several sequences have the same longest length, the program should print the leftmost of them. The input strings are given as a single line, separated by a space.
For example:
if the input is: "hi yes yes yes bye",
the output should be: "yes yes yes".
And there is my source code:
public static void main(String[] args) {
System.out.println("Please enter a sequence of strings separated by spaces:");
Scanner inputStringScanner = new Scanner(System.in);
String[] strings = inputStringScanner.nextLine().split(" ");
System.out.println(String.join(" ", strings));
ArrayList<ArrayList<String>> stringsSequencesCollection = new ArrayList<ArrayList<String>>();
ArrayList<String> stringsSequences = new ArrayList<String>();
stringsSequences.add(strings[0]);
for (int i = 1; i < strings.length; i++) {
if(strings[i].equals(strings[i - 1])) {
stringsSequences.add(strings[i]);
} else {
System.out.println(stringsSequences + " " + stringsSequences.size());
stringsSequencesCollection.add(stringsSequences);
stringsSequences.clear();
stringsSequences.add(strings[i]);
//ystem.out.println("\n" + stringsSequences);
}
if(i == strings.length - 1) {
stringsSequencesCollection.add(stringsSequences);
stringsSequences.clear();
System.out.println(stringsSequences + " " + stringsSequences.size());
}
}
System.out.println(stringsSequencesCollection.size());
System.out.println(stringsSequencesCollection.get(2).size());
System.out.println();
int maximalStringSequence = Integer.MIN_VALUE;
int index = 0;
ArrayList<String> currentStringSequence = new ArrayList<String>();
for (int i = 0; i < stringsSequencesCollection.size(); i++) {
currentStringSequence = stringsSequencesCollection.get(i);
System.out.println(stringsSequencesCollection.get(i).size());
if (stringsSequencesCollection.get(i).size() > maximalStringSequence) {
maximalStringSequence = stringsSequencesCollection.get(i).size();
index = i;
//System.out.println("\n" + index);
}
}
System.out.println(String.join(" ", stringsSequencesCollection.get(index)));
I think it should be work correct but there is a problem - the sub array list's count isn't correct: All the sub arrayList's size is 1 and for this reason the output is not correct. I don't understand what is the reason for this. If anybody can help me to fix the code I will be gratefull!
I think it is fairly straight forward just keep track of a max sequence length as you go through the array building sequences.
String input = "hi yes yes yes bye";
String sa[] = input.split(" ");
int maxseqlen = 1;
String last_sample = sa[0];
String longest_seq = last_sample;
int seqlen = 1;
String seq = last_sample;
for (int i = 1; i < sa.length; i++) {
String sample = sa[i];
if (sample.equals(last_sample)) {
seqlen++;
seq += " " + sample;
if (seqlen > maxseqlen) {
longest_seq = seq;
maxseqlen = seqlen;
}
} else {
seqlen = 1;
seq = sample;
}
last_sample = sample;
}
System.out.println("longest_seq = " + longest_seq);
Lots of issues.
First of all, when dealing with the last string of the list you are not actually printing it before clearing it. Should be:
if(i == strings.length - 1)
//...
System.out.println(stringsSequences + " " + stringsSequences.size());
stringsSequences.clear();
This is the error in the output.
Secondly, and most importantly, when you do stringsSequencesCollection.add you are adding an OBJECT, i.e. a reference to the collection. When after you do stringsSequences.clear(), you empty the collection you just added too (this is because it's not making a copy, but keeping a reference!). You can verify this by printing stringsSequencesCollection after the first loop finishes: it will contain 3 empty lists.
So how do we do this? First of all, we need a more appropriate data structure. We are going to use a Map that, for each string, contains the length of its longest sequence. Since we want to manage ties too, we'll also have another map that for each string stores the leftmost ending position of the longest sequence:
Map<String, Integer> lengths= new HashMap<>();
Map<String, Integer> indexes= new HashMap<>();
String[] split = input.split(" ");
lengths.put(split[0], 1);
indexes.put(split[0], 0);
int currentLength = 1;
int maxLength = 1;
for (int i = 1; i<split.length; i++) {
String s = split[i];
if (s.equals(split[i-1])) {
currentLength++;
}
else {
currentLength = 1;
}
int oldLength = lengths.getOrDefault(s, 0);
if (currentLength > oldLength) {
lengths.put(s, currentLength);
indexes.put(s, i);
}
maxLength = Math.max(maxLength, currentLength);
}
//At this point, youll have in lengths a map from string -> maxSeqLengt, and in indexes a map from string -> indexes for the leftmost ending index of the longest sequence. Now we need to reason on those!
Now we can just scan for the strings with the longest sequences:
//Find all strings with equal maximal length sequences
Set<String> longestStrings = new HashSet<>();
for (Map.Entry<String, Integer> e: lengths.entrySet()) {
if (e.value == maxLength) {
longestStrings.add(e.key);
}
}
//Of those, search the one with minimal index
int minIndex = input.length();
String bestString = null;
for (String s: longestStrings) {
int index = indexes.get(s);
if (index < minIndex) {
bestString = s;
}
}
System.out.println(bestString);
Below code results in output as you expected:
public static void main(String[] args) {
System.out.println("Please enter a sequence of strings separated by spaces:");
Scanner inputStringScanner = new Scanner(System.in);
String[] strings = inputStringScanner.nextLine().split(" ");
System.out.println(String.join(" ", strings));
List <ArrayList<String>> stringsSequencesCollection = new ArrayList<ArrayList<String>>();
List <String> stringsSequences = new ArrayList<String>();
//stringsSequences.add(strings[0]);
boolean flag = false;
for (int i = 1; i < strings.length; i++) {
if(strings[i].equals(strings[i - 1])) {
if(flag == false){
stringsSequences.add(strings[i]);
flag= true;
}
stringsSequences.add(strings[i]);
}
}
int maximalStringSequence = Integer.MIN_VALUE;
int index = 0;
List <String> currentStringSequence = new ArrayList<String>();
for (int i = 0; i < stringsSequencesCollection.size(); i++) {
currentStringSequence = stringsSequencesCollection.get(i);
System.out.println(stringsSequencesCollection.get(i).size());
if (stringsSequencesCollection.get(i).size() > maximalStringSequence) {
maximalStringSequence = stringsSequencesCollection.get(i).size();
index = i;
//System.out.println("\n" + index);
}
}
System.out.println(stringsSequences.toString());

How to iterate through two dimensional ArrayList using iterator?

I would like to iterate through two dimensional ArrayList which includes String objects using iterator. I also would like to iterate in a way that let me choose whether I want to iterate horizontally(row) first or vertically(column) by using a boolean value. How can I implement this in java?
What I've tried so far.
public class IterateThis implements Iterator<String>{
ArrayList<ArrayList<String>> array;
public IterateThis(){
array = new ArrayList<ArrayList<String>>();
array.add(new ArrayList<String>());
array.add(new ArrayList<String>());
array.add(new ArrayList<String>());
array.get(0).add("1");
array.get(0).add("2");
array.get(0).add("2");
array.get(1).add("4");
array.get(1).add("5");
array.get(1).add("6");
}
Iterator<String> it = array.iterator(); //This gives me an error...why?
I don't know how I can implement the boolean value though.
Maybe you need to implement two versions, with a boolean that decides which loop to use:
public void iterate(boolean horizantalFirst){
if(horizontalFirst){
for(int i=0; i<array.size(); i++){ // first iterate through the "outer list"
for(int j=0; j<array.get(i).size(); j++){ // then iterate through all the "inner lists"
array.get(i).get(j)="1";
}
}
}else{
int j=0; // index to iterate through the "inner lists"
for(; j<array.get(j).size(); j++){ //dangerous, you need to be sure that there is a j-th element in array
for(int i=0; i<array.size(); i++){ // iterate here through the outer list, by always working on the j-th element
array.get(i).get(j)="1";
}
}
}
}
Why not try this:
import java.util.ArrayList;
public class Iteration
{
private ArrayList<ArrayList<String>> array;
public Iteration()
{
array = new ArrayList<>();
array.add(new ArrayList<String>());
array.get(0).add("000");
array.get(0).add("001");
array.get(0).add("010");
array.add(new ArrayList<String>());
array.get(1).add("100");
array.get(1).add("101");
array.get(1).add("110");
array.get(1).add("111");
iterateRowWise();
System.out.println("\n\n");
iterateColumnWise();
}
public void iterateRowWise()
{
// This uses iterator behind the scene.
for (ArrayList<String> row : array)
{
for (String element : row)
{
System.out.print(element + " ");
}
System.out.println();
}
}
public void iterateColumnWise()
{
int arraySize = array.size();
int maxColumns = getMaximumListSize();
for (int c = 0; c < maxColumns; c++)
{
for (int r = 0; r < arraySize; r++)
{
ArrayList<String> rowList = array.get(r);
if (c < rowList.size())
{
System.out.print(rowList.get(c) + " ");
}
}
System.out.println();
}
}
private int getMaximumListSize()
{
int maxListSize = 0;
for (ArrayList<String> rowList : array)
{
if (maxListSize < rowList.size())
maxListSize = rowList.size();
}
return maxListSize;
}
public static void main(String[] args)
{
new Iteration();
}
}
The iterateRowWise() method iterates using the iterator, but it does so behind the scene.
The iterateColumnWise() method doesn't use iterator, but its safe to use.
Row-wise iteration is simple as shown in the #Awfully Awesome answer.
Tried a columnwise iteration with assumption that List will always have m cross n elements where m=n
public static void IterateThis() {
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
array.add(new ArrayList<String>());
array.add(new ArrayList<String>());
array.get(0).add("1");
array.get(0).add("2");
array.get(0).add("2");
array.get(1).add("4");
array.get(1).add("5");
array.get(1).add("6");
Iterator<ArrayList<String>> it = array.iterator();
int topLevelIteratorResetCounter = 0;
int noOfIteratorNextRequired = 1;
int size = array.size();
while (it.hasNext()) {
ArrayList<String> strList = it.next();
if (noOfIteratorNextRequired > strList.size())
break;
Iterator<String> itString = strList.iterator();
int numtimes = 0;
String str = null;
while (numtimes != noOfIteratorNextRequired) {
str = itString.next();
numtimes++;
}
System.out.println(str);
numtimes = 0;
topLevelIteratorResetCounter++;
if (topLevelIteratorResetCounter == size) { //as column count is equal to column size
it = array.iterator(); //reset the iterator
noOfIteratorNextRequired++;
topLevelIteratorResetCounter = 0;
}
}
}
The answer uses Iterator.

Sorting String[][] unexpected output

I want to sort my String[][] with respect to second column. I tried this
public static String[][] sorting_minn(String[][] list){
double[] temp = new double[list.length];
String[][] tempf = list;
if(list[1][1]!=null){
for(int i = 0; i<list.length; i++){
if(list[i][2]==null){
break;
} else {
temp[i]=Double.parseDouble(list[i][2]);
}
}
Arrays.sort(temp);
for(int f = 0; f<list.length-1;f++){
for(int m = 0; m<list.length;m++){
if(list[m][2]!=null && Double.parseDouble(list[m][2])==temp[f]){
for(int n = 0; n<4; n++){
tempf[list.length-f-1][n]=list[m][n];
}
m = list.length;
}
}
}
}
return tempf;
}
As an output I get this: . I need suggestion on how to improve this code.
try something like:
Arrays.sort(list, new Comparator<String[]>() {
#Override
public int compare(String[] o1, String[] o2) {
String left = o1[1]!=null ? o1[1] : "";
String right = o2[1]!=null ? o2[1] : "";
return left.compareTo(right);
}
});
this treats nulls as empty strings, and exploits the fact that strings are comparable, although lexicographic. if you want the reverse order just do this instead:
right.compareTo(left)
if you want integer ordering you could parse an Integer out of both sides (Integer.MIN for null) and compare 2 Integers

Categories