Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.6 kB
5
Indexable
Never
/**
 *
 *  @author Grudzień Jonasz S23416
 *
 */

package zad3;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class Anagrams {
    String allWords;
    Scanner sc;
    ArrayList<String> words;
    ArrayList<String>[] list;
    public Anagrams(String allWords) {
        this.allWords = allWords;
        readFile(allWords);
        list = new ArrayList[5];
    }

    public List<String>[] getSortedByAnQty() {
        char[][] c1 = new char[words.size()][];
        char[] c2;
        list[0] = new ArrayList<String>(Collections.singletonList(words.get(0)));
        boolean nWord;
        int counter = 1;
        for (int i = 1; i<words.size(); i++) {
            c1[i] = words.get(i).toCharArray();
            Arrays.sort(c1[i]);
            nWord = true;
            for(int j = 0; j<list.length; j++){
                if(list[j]== null)
                    break;
                c2 = list[j].get(0).toCharArray();
                Arrays.sort(c2);
                if(Arrays.equals(c2, c1[i])){
                    nWord = false;
                    list[j].add(words.get(i));
                    break;
                }
            }
                if(nWord){
                    list[counter] = new ArrayList<String>(Collections.singletonList(words.get(i)));
                    counter++;
                }
            }

        Arrays.asList(list).sort((o1,o2) ->{
            return Integer.compare(o2.size(), o1.size());
        });
        return list;
    }

    public String getAnagramsFor(String next) {
        for(int j = 0; j<list.length; j++){
            if(list[j]== null)
                break;
            for(int i = 0; i<list[j].size();i++){
                if(next.equals(list[j].get(i))) {
                    list[j].remove(next);
                    return next + ": " +list[j].toString();
                }
            }
        }

        return next + ": []";
    }

    public void readFile(String sciezka) {
        words = new ArrayList();
        String word;
        try {
            sc = new Scanner(new File(sciezka));
            Scanner sc2;
            while (sc.hasNextLine()){

                sc2 = new Scanner(sc.nextLine());
                while(sc2.hasNext()) {
                    word = sc2.next();
                    words.add(word);
                }

                sc2.close();


            }
            sc.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


    }
}