Week 7

List to Set

import java.util.List;
import java.util.Set;
import java.util.HashSet;
public class Challenge {
    public static Set<Integer> listToSet(List<Integer> list) {
        Set<Integer> result = new HashSet<Integer>();
        for (Integer i : list) {
            result.add(i);
        }
        return result;
    }
}
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
public class Main {
    public static void main(String[] args) {
        List<Integer> input = new ArrayList<Integer>();
        input.add(1);
        input.add(1);
        input.add(2);
        input.add(2);
        input.add(3);
        input.add(4);
        input.add(4);
        Set<Integer> output = Challenge.listToSet(input);
        System.out.println(output.size());
        for (Integer i : output) {
            System.out.println(i);
        }
    }
}

Loopless pair detection

import java.util.HashSet;
import java.util.Set;
public class Challenge {
    public static boolean hasPair(String[] list) {
        Set<String> seen = new HashSet<String>();
        try {
            java.util.Arrays.stream(list).forEach(s -> {
                if (!seen.add(s)) {
                    throw new RuntimeException("pair");
                }
            });
        } catch (RuntimeException ex) {
            return true;
        }
        return false;
    }
}
public class Main {
    public static void main(String[] args) {
        String[] nopair = {"Apple","Orange","Banana","Python","Zebra"};
        String[] nopair2 = {"Green","Blue","Yellow","Red"};
        String[] pair = {"Fred","Harry","Bill","Fred","Jane","Kate"};
        System.out.println(Challenge.hasPair(nopair));
        System.out.println(Challenge.hasPair(nopair2));
        System.out.println(Challenge.hasPair(pair));
    }
}

Doc/line/word

public class Word {
    private String text;
    private boolean underlined;
    private boolean bold;
    public Word(String text) {
        this.text = text;
        this.underlined = false;
        this.bold = false;
    }
    public void setUnderlined(boolean underlined) {
        this.underlined = underlined;
    }
    public boolean isUnderlined() {
        return underlined;
    }
    public void setBold(boolean bold) {
        this.bold = bold;
    }
    public boolean isBold() {
        return bold;
    }
    public String getText() {
        return text;
    }
    public void setText(String text) {
        this.text = text;
    }
}
import java.util.ArrayList;
public class Line {
    private ArrayList words;
    public Line(String text) {
        words = new ArrayList();
        if (text != null && !text.isEmpty()) {
            String[] parts = text.split(" ");
            for (String p : parts) {
                words.add(new Word(p));
            }
        }
    }
    public Line(Word[] wordsArray) {
        words = new ArrayList();
        if (wordsArray != null) {
            for (Word w : wordsArray) {
                words.add(w);
            }
        }
    }
    public int getNumberOfWords() {
        return words.size();
    }
    // 1-based index as required by the tests
    public Word getWord(int index) {
        return words.get(index - 1);
    }
    public void addWord(Word w) {
        words.add(w);
    }
}
import java.util.ArrayList;
public class Document {
    private String name;
    private String author;
    private int priority;
    private ArrayList lines;
    public Document() {
        lines = new ArrayList();
    }
    // getters and setters for name, author, priority (for the test helper)
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public int getPriority() {
        return priority;
    }
    public void setPriority(int priority) {
        this.priority = priority;
    }
    public int getNumberOfWords() {
        int total = 0;
        for (Line l : lines) {
            total += l.getNumberOfWords();
        }
        return total;
    }
    public int getNumberOfLines() {
        return lines.size();
    }
    public void addLine(Line line) {
        lines.add(line);
    }
    public void addWord(Word word) {
        if (lines.isEmpty()) {
            Line newLine = new Line(new Word[] { word });
            lines.add(newLine);
        } else {
            Line last = lines.get(lines.size() - 1);
            last.addWord(word);
        }
    }
    public void generatePreview() {
        for (Line l : lines) {
            StringBuilder sb = new StringBuilder();
            int count = l.getNumberOfWords();
            for (int i = 1; i <= count; i++) {
                Word w = l.getWord(i);
                if (i > 1) {
                    sb.append(" ");
                }
                sb.append(formatWord(w));
            }
            System.out.println(sb.toString());
        }
    }
    private String formatWord(Word w) {
        String text = w.getText();
        boolean bold = w.isBold();
        boolean underlined = w.isUnderlined();
        if (bold && underlined) {
            return "_*" + text + "*_";
        } else if (bold) {
            return "*" + text + "*";
        } else if (underlined) {
            return "_" + text + "_";
        } else {
            return text;
        }
    }
}
public class Main {
    public static void main(String[] args) {
        Document d = new Document();
        Line l = new Line("This is a test line");
        d.addLine(l);
        Word[] words = {
            new Word("My"),
            new Word("second"),
            new Word("line"),
            new Word("now")
        };
        words[0].setUnderlined(true);
        words[1].setBold(true);
        words[1].setUnderlined(true);
        words[2].setBold(true);
        Line l2 = new Line(words);
        d.addLine(l2);
        d.addWord(new Word("hooray"));
        d.generatePreview();
        // expected:
        // This is a test line
        // _My_ _*second*_ *line* now hooray
    }
}

List to Array

import java.util.List;
public class Challenge {
    public static Integer[] listToArray(List<Integer> list) {
        Integer[] arr = new Integer[list.size()];
        for (int i = 0; i < list.size(); i++) {
            arr[i] = list.get(i);
        }
        return arr;
    }
}
import java.util.List;
import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        List<Integer> myList = new ArrayList<Integer>();
        myList.add(1);
        myList.add(2);
        myList.add(3);
        Integer[] arr = Challenge.listToArray(myList);
        for (Integer i : arr) {
            System.out.println(i);
        }
    }
}

Week 8

Unique elements

public class Challenge {
    public static String[] uniques(String[] arr) {
        java.util.LinkedHashSet<String> set = new java.util.LinkedHashSet<String>();
        for (int i = 0; i < arr.length; i++) {
            set.add(arr[i]);
        }
        return set.toArray(new String[set.size()]);
    }
}
public class Main {
    public static void main(String[] args) {
        String[] test1 = {"one","two","two","three","three","one","bumpers"};
        String[] results = Challenge.uniques(test1);
        for (String result : results) {
            System.out.println(result);
        }
    }
}

Map Keys to Array

import java.util.Map;
public class Challenge {
    public static String[] mapKeysToArray(Map<String,Integer> map) {
        String[] arr = new String[map.size()];
        int i = 0;
        for (String key : map.keySet()) {
            arr[i] = key;
            i++;
        }
        return arr;
    }
}
import java.util.Map;
import java.util.HashMap;
public class Main {
    public static void main(String[] args) {
        Map<String,Integer> input = new HashMap<String,Integer>();
        input.put("one",1);
        input.put("two",2);
        input.put("three",3);
        String[] output = Challenge.mapKeysToArray(input);
        System.out.println(output.length);
        for (String s : output) {
            System.out.println(s);
        }
    }
}

Map

public class Map {
    private String[] keys = new String[10];
    private String[] values = new String[10];
    public void put(String key, String value) {
        for (int i = 0; i < keys.length; i++) {
            if (keys[i] != null && keys[i].equals(key)) {
                values[i] = value;
                return;
            }
        }
        for (int i = 0; i < keys.length; i++) {
            if (keys[i] == null) {
                keys[i] = key;
                values[i] = value;
                return;
            }
        }
    }
    public String get(String key) {
        for (int i = 0; i < keys.length; i++) {
            if (keys[i] != null && keys[i].equals(key)) {
                return values[i];
            }
        }
        return null;
    }
}
public class Main {
    public static void main(String[] args) {
        Map test = new Map();
        test.put("paul","neve");
        test.put("fred","bloggs");
        test.put("bill","smith");
        test.put("paul","jones");
        System.out.println(test.get("fred"));
        System.out.println(test.get("bill"));
        System.out.println(test.get("fred"));
        System.out.println(test.get("paul"));
        System.out.println(test.get("nobody"));
    }
}

Map Values to Array

import java.util.Map;
public class Challenge {
    public static Integer[] mapValuesToArray(Map<String,Integer> map) {
        Integer[] arr = new Integer[map.size()];
        int i = 0;
        for (Integer val : map.values()) {
            arr[i] = val;
            i++;
        }
        return arr;
    }
}
import java.util.Map;
import java.util.HashMap;
public class Main {
    public static void main(String[] args) {
        Map<String,Integer> input = new HashMap<String,Integer>();
        input.put("one",1);
        input.put("two",2);
        input.put("three",3);
        Integer[] output = Challenge.mapValuesToArray(input);
        System.out.println(output.length);
        for (Integer i : output) {
            System.out.println(i);
        }
    }
}

Week 9

MediaItem Equality

public class MediaItem {
    private String title;
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public MediaItem(String t) {
        setTitle(t);
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof MediaItem)) {
            return false;
        }
        MediaItem other = (MediaItem) obj;
        String thisTitle = (this.title == null) ? "" : this.title.trim();
        String otherTitle = (other.title == null) ? "" : other.title.trim();
        return thisTitle.equalsIgnoreCase(otherTitle);
    }
}
import java.util.*;
public class Main {
    public static void main(String[] args) {
        MediaItem p1 = new MediaItem("Prince");
        MediaItem q1 = new MediaItem("Queen");
        MediaItem p2 = new MediaItem("prince ");
        if (p1.equals(p2)) {
            System.out.println("correct -- we are asked to ignore differences " +
                    "between upper and lower case characters");
        } else {
            System.out.println("incorrect -- we are asked to ignore differences " +
                    "between upper and lower case characters");
        }
        if (p1.equals(q1) == false) {
            System.out.println("correct -- these are different");
        } else {
            System.out.println("incorrect -- these are different");
        }
    }
}

Unique elements using Java8 Streams

public class Challenge {
    public static String[] uniquesJava8(String[] arr) {
        return java.util.Arrays.stream(arr)
                               .distinct()
                               .toArray(String[]::new);
    }
}
public class Main {
    public static void main(String[] args) {
        String[] test1 = {"one","two","two","three","three","one","bumpers"};
        String[] results = Challenge.uniquesJava8(test1);
        System.out.println(results.length);
        System.out.println(results[0]);
        System.out.println(results[1]);
        System.out.println(results[2]);
        System.out.println(results[3]);
        // should get:
        // 4 - size of set
        // one
        // two
        // three
        // bumpers
    }
}

MediaItem Hashcode

public class MediaItem {
    private String title;
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public MediaItem(String t) {
        setTitle(t);
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null) return false;
        if (!(o instanceof MediaItem)) return false;
        MediaItem other = (MediaItem) o;
        return this.title != null && this.title.equals(other.getTitle());
    }
    @Override
    public int hashCode() {
        return (title == null ? 0 : title.hashCode());
    }
}
import java.util.*;
public class Main {
    public static void main(String[] args) {
        MediaItem princeKey = new MediaItem("Prince");
        MediaItem queenKey = new MediaItem("Queen");
        MediaItem anotherPrinceKey = new MediaItem("Prince");
        Set<MediaItem> myItems = new HashSet<MediaItem>();
        myItems.add(princeKey);
        myItems.add(queenKey);
        myItems.add(anotherPrinceKey);
        System.out.println("there are " + myItems.size() + " items in the set");
        Map<MediaItem, Integer> myMap = new HashMap<MediaItem, Integer>();
        myMap.put(princeKey, 10);
        myMap.put(queenKey, 20);
        Integer intValueStoredWithPrince = myMap.get(anotherPrinceKey);
        System.out.println("value stored with Prince Key is " + intValueStoredWithPrince);
    }
}

Week 10

Tic Tac OO

public class Square {
    private int xpos;
    private int ypos;
    private String player;
    public Square(int xpos, int ypos, String player) {
        this.xpos = xpos;
        this.ypos = ypos;
        this.player = player;
    }
    public int getXpos() {
        return xpos;
    }
    public int getYpos() {
        return ypos;
    }
    public String getPlayer() {
        return player;
    }
}
public class Board {
    private Square[][] grid = new Square[3][3];
    private int moves = 0;
    public String placeMove(Square move) {
        int x = move.getXpos();
        int y = move.getYpos();
        if (x < 1 || x > 3 || y < 1 || y > 3) {
            return "illegal";
        }
        int i = x - 1;
        int j = y - 1;
        if (grid[i][j] != null) {
            return "illegal";
        }
        grid[i][j] = move;
        moves++;
        String player = move.getPlayer();
        if (hasWon(player)) {
            return player;
        }
        if (moves == 9) {
            return "stalemate";
        }
        return "continue";
    }
    private boolean hasWon(String player) {
        for (int r = 0; r < 3; r++) {
            if (cellPlayer(r, 0, player) &&
                cellPlayer(r, 1, player) &&
                cellPlayer(r, 2, player)) {
                return true;
            }
        }
        for (int c = 0; c < 3; c++) {
            if (cellPlayer(0, c, player) &&
                cellPlayer(1, c, player) &&
                cellPlayer(2, c, player)) {
                return true;
            }
        }
        if (cellPlayer(0, 0, player) &&
            cellPlayer(1, 1, player) &&
            cellPlayer(2, 2, player)) {
            return true;
        }
        if (cellPlayer(0, 2, player) &&
            cellPlayer(1, 1, player) &&
            cellPlayer(2, 0, player)) {
            return true;
        }
        return false;
    }
    private boolean cellPlayer(int r, int c, String player) {
        return grid[r][c] != null && player.equals(grid[r][c].getPlayer());
    }
}

Catching the Exceptional

public class Month
{
  private static String[] monthnames = {
    "January","February","March","April","May","June","July","August",
    "September","October","November","December"
  };
  public static String getMonth(int monthno)
  {
    try {
      return monthnames[monthno - 1];
    } catch (ArrayIndexOutOfBoundsException e) {
      return "illegal";
    }
  }
}
public class Main
{
  public static void main(String[] args)
  {
    // NOOBLAB READONLY
    // You are not to change the main method! Your job is to
    // change the other class so any exception is handled.
    System.out.println(Month.getMonth(1)); // will be January
    System.out.println(Month.getMonth(9)); // will be September
    System.out.println(Month.getMonth(13)); // EH-RAW :-)
  }
}

Exceptions to the Rule

public class Customer
{
  private String name;
  private double balance;
  private double discount = 1;
  public double getDiscountedBalance()
  {
    return this.getBalance() / this.getDiscount();
  }
  public void setName(String name)
  {
     this.name = name;
  }
  public String getName()
  {
     return this.name;
  }
  public void setBalance(double balance)
  {
     this.balance = balance;
  }
  public double getBalance()
  {
     return this.balance;
  }
  public void setDiscount(double discount)
  {
     if (discount <= 0) {
       throw new IllegalArgumentException("Discount must be greater than zero");
     }
     this.discount = discount;
  }
  public double getDiscount()
  {
     return this.discount;
  }
}
import java.util.ArrayList;
public class AccountManager
{
  private String name;
  private ArrayList customers = new ArrayList();
  public double getCollectiveBalance()
  {
    double total = 0;
    for (Customer singleCustomer : customers)
    {
      total += singleCustomer.getDiscountedBalance();
    }
    return total;
  }
  public void addCustomer(Customer customer)
  {
    this.getCustomers().add(customer);
  }
  public void setName(String name)
  {
     this.name = name;
  }
  public String getName()
  {
     return this.name;
  }
  public void setCustomers(ArrayList customers)
  {
     this.customers = customers;
  }
  public ArrayList getCustomers()
  {
     return this.customers;
  }
}
public class Main
{
  public static void main(String[] args)
  {
    Customer fred = new Customer();
    fred.setName("Fred Flintstone");
    fred.setBalance(257.00);
    fred.setDiscount(1);
    Customer jane = new Customer();
    jane.setName("Jane Doe");
    jane.setBalance(12.99);
    // these will now throw exceptions:
    try {
      jane.setDiscount(-1.5); // this shouldn't be allowed
    } catch (Exception e) {
      System.out.println("Invalid discount for Jane: " + e.getMessage());
    }
    Customer bill = new Customer();
    bill.setName("Bill Bloggs");
    bill.setBalance(1200.50);
    try {
      bill.setDiscount(0); // this shouldn't be allowed either
    } catch (Exception e) {
      System.out.println("Invalid discount for Bill: " + e.getMessage());
    }
    AccountManager paul = new AccountManager();
    paul.setName("Paul Neve");
    paul.addCustomer(fred);
    paul.addCustomer(jane);
    paul.addCustomer(bill);
    System.out.println(paul.getCollectiveBalance());
  }
}

Week 11

Read a CSV File

import java.util.List;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Challenge
{
  private static List tasks = new ArrayList();
  public static void readCSVFile(String filename)
  {
    tasks = new ArrayList();
    BufferedReader br = null;
    try {
      br = new BufferedReader(new FileReader(filename));
      String line;
      while ((line = br.readLine()) != null) {
        line = line.trim();
        if (line.length() == 0) {
          continue;
        }
        String[] parts = line.split(",", 3);
        if (parts.length != 3) {
          continue;
        }
        Task t = new Task();
        t.setTitle(parts[0]);
        t.setPriority(Integer.parseInt(parts[1]));
        t.setTargetDate(parts[2]);
        tasks.add(t);
      }
    } catch (IOException e) {
      // if there is an IO problem, just leave tasks as whatever has been read so far
    } finally {
      if (br != null) {
        try {
          br.close();
        } catch (IOException e) {
          // ignore
        }
      }
    }
  }
  public static List getTasks(){
     return tasks;
  }
  public static void setTasks(List tasks){
     Challenge.tasks = tasks;
  }
}
public class Main
{
  public static void main(String[] args){
    // Use the relative path that the tests use
    Challenge.readCSVFile("myfiles/japi-io/tasks.csv");
    for (Task t : Challenge.getTasks()) {
      System.out.println(t);
    }
  }
}

Read a File

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Challenge
{
  public static void readFile()
  {
    BufferedReader reader = null;
    try {
      reader = new BufferedReader(new FileReader("myfiles/japi-io/readfile.txt"));
      String line;
      while ((line = reader.readLine()) != null) {
        System.out.println(line);
      }
    } catch (IOException e) {
      // silently ignore for this exercise
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          // ignore
        }
      }
    }
  }
}
public class Main
{
  public static void main(String[] args){
    Challenge.readFile();
    // expected:
    // This is a sample file.
    // Can you read it?
  }
}

Write a File

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Challenge
{
  public static void writeFile()
  {
    BufferedWriter writer = null;
    try {
      writer = new BufferedWriter(new FileWriter("/myfiles/japi-io/writefile.txt"));
      writer.write("Hello there.");
      writer.newLine();
      writer.write("This is a file I made.");
    } catch (IOException e) {
      // ignore for this exercise
    } finally {
      if (writer != null) {
        try {
          writer.close();
        } catch (IOException e) {
          // ignore
        }
      }
    }
  }
}
public class Main
{
  public static void main(String[] args){
    Challenge.writeFile();
  }
}