BobTheFarmer / Colin-Blog3

MIT License
0 stars 2 forks source link

Final FRQs Reflection #20

Open BobTheFarmer opened 8 months ago

BobTheFarmer commented 8 months ago

Reflection

FRQ 1

This FRQ was about ArrayLists and 2D Arrays. In relation to my project, 2D arrays could be used to add another layer of 'comments.' Currently, in the submission system I used a hashmap inside of each assignment to contain submissions. If instead, I used a 2D Array, I could add a comment system for each submission.

private Map<String,Map<String, Object>> submissions = new HashMap<>(); 
private Map<String,Map<String, Object>> submissions = new ArrayList<>(); 

FRQ 2

This FRQ was mostly about classes. It also reminded me of Wordle which is a real and popular use of the usefulness of this kind of algorithm.

On the backend, I used classes a lot to define POJOS. For example, here is the Assignment class:

package com.nighthawk.spring_portfolio.mvc.assignment;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.HashMap;
import java.util.Map;

import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;

import jakarta.persistence.*;

@Data  // Annotations to simplify writing code (ie constructors, setters)
@NoArgsConstructor
@AllArgsConstructor
@Entity // Annotation to simplify creating an entity, which is a lightweight persistence domain object. Typically, an entity represents a table in a relational database, and each entity instance corresponds to a row in that table.
public class Assignment {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column()
    private String title;

    @Column()
    private String desc;

    @Column()
    private String link;

    @Column()
    private int maxPoints;

    /* HashMap is used to store JSON for daily "stats"
    "stats": {
        "2022-11-13": {
            "calories": 2200,
            "steps": 8000
        }
    }
    */
    @JdbcTypeCode(SqlTypes.JSON)
    @Column(columnDefinition = "jsonb")
    private Map<String,Map<String, Object>> submissions = new HashMap<>(); 

    public Assignment(String title, String desc, String link, int maxPoints) {
        this.title = title;
        this.desc = desc;
        this.link = link;
        this.maxPoints = maxPoints;
    }
}

FRQ 3

This one was about method and control structures, in relation to 2D arrays. In my project, we don't use any 2D arrays to have a control structure for. However, we do have very similar API controllers that manipulate embedded hash maps. In the future if we decide to add 2D arrays in the way discussed under FRQ 1, this experience could be even more relevant.

I think this part of Assignment API controller is especially relevant. It involves manipulating the hashmap submitted by the user, verifying it contains the correct information, and also submitting a new hashmap to the JPA repo.

    @PostMapping(value = "/submit", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Object> personStats(@RequestBody final Map<String,Object> request_map) {
        // find ID
        if (!(request_map.get("id") instanceof String)){
            return new ResponseEntity<>("id should be a String", HttpStatus.BAD_REQUEST);
        }
        long id=Long.parseLong((String)request_map.get("id"));  
        Optional<Assignment> optional = repository.findById((id));
        if (optional.isPresent()) {  // Good ID
            Assignment assignment = optional.get();  // value from findByID

            // Extract Attributes from JSON
            Map<String, Object> attributeMap = new HashMap<>();
            for (Map.Entry<String,Object> submission : request_map.entrySet())  {
                // Add needed attributes to attributeMap

                if(submission.getKey().equals("contributors"))
                    if (submission.getValue() instanceof List) {
                        attributeMap.put(submission.getKey(), submission.getValue());
                    } else {
                        return new ResponseEntity<>("Contributors attribute should be a list", HttpStatus.BAD_REQUEST);
                    }

                if(submission.getKey().equals("title"))
                    attributeMap.put(submission.getKey(), submission.getValue());

                if(submission.getKey().equals("desc"))
                    attributeMap.put(submission.getKey(), submission.getValue());

                if(submission.getKey().equals("link"))
                    attributeMap.put(submission.getKey(), submission.getValue());

            }

            //Does it have all attributes?
            if(!(attributeMap.containsKey("contributors")  && attributeMap.containsKey("title") && attributeMap.containsKey("desc") && attributeMap.containsKey("link"))) {
                return new ResponseEntity<>("Missing attributes. username, contributors, title, desc, and link are required" + attributeMap, HttpStatus.BAD_REQUEST); 
            }

            // Set Date and Attributes to SQL HashMap
            Map<String, Map<String, Object>> date_map = assignment.getSubmissions();
            date_map.put( (String) request_map.get("username"), attributeMap );

            assignment.setSubmissions(date_map);
            repository.save(assignment);

            //Save grade as well for each contributor
            List<String> contributors = (List<String>) attributeMap.get("contributors");
            for (String contributor : contributors)  {
                Grade grade = new Grade(contributor, "temp", assignment.getTitle(), assignment.getMaxPoints(), -1);
                gradeRepository.save(grade);
            }

            // return Person with update Stats
            return new ResponseEntity<>(assignment, HttpStatus.OK);
        }
        // return Bad ID
        return new ResponseEntity<>("Bad ID", HttpStatus.BAD_REQUEST); 
    }

FRQ 4

This FRQ was about methods and control structures in general. It involved extending classes. We also used extends for our JPA repositories. I think the best example of this is GradeJpaRepository, because it is the most customized.

In my part of the project, I could try and use extends to make my similar and complicated classes AssignmentAPIController and IssueAPIController, because they are both built off of the same infrastructure. However, in practice it might be harder to do this than to just write them separately as there are only two.

public interface GradeJpaRepository extends JpaRepository<Grade, Long> {
    Grade findByName(String name);
    List<Grade> findAllByOrderByNameAsc();
    List<Grade> findByNameIgnoreCase(String name);
    List<Grade> findByEmailIgnoreCase(String email);

    @Query(
            value = "SELECT * FROM Grade p WHERE p.name LIKE ?1",
            nativeQuery = true)
    List<Grade> findByLikeTermNative(String term);

}

Putting it together in an app

I wanted to practice making a full application in Java so I made this app to interact with all the different classes by using JPanel:

See here

Screenshot 2024-02-24 at 6 57 57 PM
package gameplatform;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class Game {
    private JFrame frame;
    private JPanel panel;
    private JLabel label;
    private HiddenWord hiddenWord;
    private DiverseArray diverseArray;
    private MultipleGroups multipleGroups;
    private SparseArray sparseArray;
    private Range range;

    public Game() {
        // Initialize the game components
        hiddenWord = new HiddenWord("1234");
        diverseArray = new DiverseArray();
        multipleGroups = new MultipleGroups();
        sparseArray = new SparseArray(10, 10);
        range = new Range(1, 10);

        // Add a NumberGroup to the MultipleGroups
        multipleGroups.addNumberGroup(range);

        // Initialize the UI components
        frame = new JFrame("Demo");
        panel = new JPanel();
        panel.setLayout(new BorderLayout());
        label = new JLabel("Demo");

        // Add a button to demonstrate the HiddenWord class
        JButton hiddenWordButton = new JButton("Guess Hidden Word");
        hiddenWordButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String guess = JOptionPane.showInputDialog(frame, "Enter your guess:");
                String hint = hiddenWord.getHint(guess);
                label.setText("Hint: " + hint);
                sparseArray.addEntry(0, 0, Integer.parseInt(guess));
            }
        });

        // Add a button to demonstrate the DiverseArray class
        JButton diverseArrayButton = new JButton("Check Diverse Array");
        diverseArrayButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int[][] arr2D = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
                boolean isDiverse = diverseArray.isDiverse(arr2D);
                label.setText("Is the array diverse? " + isDiverse);
            }
        });

        // Add a button to demonstrate the MultipleGroups class
        JButton multipleGroupsButton = new JButton("Check Multiple Groups");
        multipleGroupsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int num = Integer.parseInt(JOptionPane.showInputDialog(frame, "Enter a number:"));
                boolean contains = multipleGroups.contains(num);
                label.setText("Does the group contain the number? " + contains);
            }
        });

        // Add a button to demonstrate the SparseArray class
        JButton sparseArrayButton = new JButton("Show Sparse Array Entries");
        sparseArray.addEntry(0, 0, 0);
        sparseArrayButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                List<SparseArrayEntry> entries = sparseArray.getEntries();
                StringBuilder sb = new StringBuilder("<html>");
                for (SparseArrayEntry entry : entries) {
                    sb.append("Row: ").append(entry.getRow()).append(", Col: ").append(entry.getCol()).append(", Value: ").append(entry.getValue()).append("<br>");
                }
                sb.append("</html>");
                label.setText(sb.toString());
            }
        });

        // Add the components to the panel
        panel.add(label, BorderLayout.NORTH);
        panel.add(hiddenWordButton, BorderLayout.WEST);
        panel.add(diverseArrayButton, BorderLayout.CENTER);
        panel.add(multipleGroupsButton, BorderLayout.EAST);
        panel.add(sparseArrayButton, BorderLayout.SOUTH);

        // Add the panel to the frame
        frame.add(panel);

        // Set the frame properties
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 500);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new Game();
    }
}
rachit-j commented 8 months ago

FRQ Grading

Total Score: 7.5/7.2

Part 1: FRQs

FRQ 1

Good FRQ, but did not have output, but all FRQ's are completed, and does not really have reflections. Part A: Code properly creates the arraySum method and indicates proper understanding of for loops ✅ Part B: Represents a good understanding of using the prior written methods in the prior question and a good understanding of for loops and indexing arrays ✅ Part C: Usage of nested for loops that matched my implementation with being able to compare with the next elements in the list and properly return a value for whether or not the array was diverse or not. ✅

All parts of the FRQ were completed, but missing reflections. Score: 0.9/0.9

FRQ 2

Good FRQ, but page was broken and FRQ's did not have reflection. Good implementation of the HiddenWord class and good example usage. ✅

Score: 0.9/0.9

FRQ 3

FRQ Part A incomplete, broken page, and did not have a reflection. Part B was completed correctly.

Score: 0.8/0.9

FRQ 4

FRQ complete, broken page, good testing method and nicely organized through comments to keep things in one cell. All parts were completed correctly and was nice.

Score: 1/0.9

Total Score

3.6/3.6

Part 2: Integration with Project

Amazing integration with project, however FRQ 1 integration was not shown, only hypothetical described. Other FRQs had good, engaging, self-written integration that showed depth of knowledge of Java. Additionally, the game created showed understanding beyond simply the FRQs and how to wrap them together and make them presentable.

Score: 3.9/3.6