Commit bdb3bf5f authored by Zane Safi Mroue's avatar Zane Safi Mroue
Browse files

Merge branch 'MySolution' into 'master'

Created MyCompressor

See merge request ZaneMroue/hw1p3!1
parents 7c91e76a 71bbfcad
Loading
Loading
Loading
Loading
+55 −0
Original line number Diff line number Diff line
package edu.bu.ec504.hw1p3.compressors;

import edu.bu.ec504.hw1p3.util.Atom;
import edu.bu.ec504.hw1p3.util.CompressedText;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

//HELPED DEBUG with ChatGPT
public class MyCompressor extends Compressor {
    @Override
    public CompressedText processPlainText(BufferedReader in) {
        StringBuilder inputText = new StringBuilder();
        try{
            int c;
            while ((c = in.read()) != -1) {
                inputText.append((char) c);}
        } catch (IOException e) {
            e.printStackTrace();
        }
        return compress(inputText.toString());
    }

    private CompressedText compress(String text){
        ArrayList<Atom> compressedList = new ArrayList<>();
        if (text.isEmpty()) return new CompressedText(compressedList);
        HashMap<String, Integer> dict = new HashMap<>();
        String current = "";
        char[] chars = text.toCharArray();
        for (char ch : chars){
            String newCurrent = current + ch;
            if (!dict.containsKey(newCurrent)) {
                if (current.equals("")) {
                    compressedList.add(new Atom(0, String.valueOf(ch)));
                } else{
                    dict.put(current, dict.size() + 1);
                    compressedList.add(new Atom(dict.get(current), String.valueOf(ch)));
                }
                current = "";
            }else{
                current = newCurrent;
            }
        }
        if (!current.equals("")){
            if (dict.containsKey(current)){
                compressedList.add(new Atom(dict.get(current), ""));
            }else{
                compressedList.add(new Atom(0, current));
            }
        }
        return new CompressedText(compressedList);
    }
}