Avatar of artemkorsakov

artemkorsakov's solution

to Allergies in the Java Track

Published at Feb 08 2019 · 0 comments
Instructions
Test suite
Solution

Given a person's allergy score, determine whether or not they're allergic to a given item, and their full list of allergies.

An allergy test produces a single numeric score which contains the information about all the allergies the person has (that they were tested for).

The list of items (and their value) that were tested are:

  • eggs (1)
  • peanuts (2)
  • shellfish (4)
  • strawberries (8)
  • tomatoes (16)
  • chocolate (32)
  • pollen (64)
  • cats (128)

So if Tom is allergic to peanuts and chocolate, he gets a score of 34.

Now, given just that score of 34, your program should be able to say:

  • Whether Tom is allergic to any one of those allergens listed above.
  • All the allergens Tom is allergic to.

Note: a given score may include allergens not listed above (i.e. allergens that score 256, 512, 1024, etc.). Your program should ignore those components of the score. For example, if the allergy score is 257, your program should only report the eggs (1) allergy.

Java Tips

Since this exercise has difficulty 5 it doesn't come with any starter implementation. This is so that you get to practice creating classes and methods which is an important part of programming in Java. It does mean that when you first try to run the tests, they won't compile. They will give you an error similar to:

 path-to-exercism-dir\exercism\java\name-of-exercise\src\test\java\ExerciseClassNameTest.java:14: error: cannot find symbol
        ExerciseClassName exerciseClassName = new ExerciseClassName();
        ^
 symbol:   class ExerciseClassName
 location: class ExerciseClassNameTest

This error occurs because the test refers to a class that hasn't been created yet (ExerciseClassName). To resolve the error you need to add a file matching the class name in the error to the src/main/java directory. For example, for the error above you would add a file called ExerciseClassName.java.

When you try to run the tests again you will get slightly different errors. You might get an error similar to:

  constructor ExerciseClassName in class ExerciseClassName cannot be applied to given types;
        ExerciseClassName exerciseClassName = new ExerciseClassName("some argument");
                                              ^
  required: no arguments
  found: String
  reason: actual and formal argument lists differ in length

This error means that you need to add a constructor to your new class. If you don't add a constructor, Java will add a default one for you. This default constructor takes no arguments. So if the tests expect your class to have a constructor which takes arguments, then you need to create this constructor yourself. In the example above you could add:

ExerciseClassName(String input) {

}

That should make the error go away, though you might need to add some more code to your constructor to make the test pass!

You might also get an error similar to:

  error: cannot find symbol
        assertEquals(expectedOutput, exerciseClassName.someMethod());
                                                       ^
  symbol:   method someMethod()
  location: variable exerciseClassName of type ExerciseClassName

This error means that you need to add a method called someMethod to your new class. In the example above you would add:

String someMethod() {
  return "";
}

Make sure the return type matches what the test is expecting. You can find out which return type it should have by looking at the type of object it's being compared to in the tests. Or you could set your method to return some random type (e.g. void), and run the tests again. The new error should tell you which type it's expecting.

After having resolved these errors you should be ready to start making the tests pass!

Running the tests

You can run all the tests for an exercise by entering

$ gradle test

in your terminal.

Source

Jumpstart Lab Warm-up http://jumpstartlab.com

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

AllergiesTest.java

import org.junit.Test;
import org.junit.Ignore;

import java.util.Arrays;
import java.util.List;
import java.util.Collections;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;

public class AllergiesTest {


    @Test
    public void noAllergiesMeansNotAllergicToAnything() {
        Allergies allergies = new Allergies(0);

        assertFalse(allergies.isAllergicTo(Allergen.PEANUTS));
        assertFalse(allergies.isAllergicTo(Allergen.CATS));
        assertFalse(allergies.isAllergicTo(Allergen.STRAWBERRIES));
    }

    @Ignore("Remove to run test")
    @Test
    public void allergicToEggs() {
        Allergies allergies = new Allergies(1);

        assertTrue(allergies.isAllergicTo(Allergen.EGGS));
    }

    @Ignore("Remove to run test")
    @Test
    public void allergicToEggsInAdditionToOtherStuff() {
        Allergies allergies = new Allergies(5);

        assertTrue(allergies.isAllergicTo(Allergen.EGGS));
        assertTrue(allergies.isAllergicTo(Allergen.SHELLFISH));
        assertFalse(allergies.isAllergicTo(Allergen.STRAWBERRIES));
    }

    @Ignore("Remove to run test")
    @Test
    public void allergicToStrawberriesButNotPeanuts() {
        Allergies allergies = new Allergies(9);

        assertTrue(allergies.isAllergicTo(Allergen.EGGS));
        assertFalse(allergies.isAllergicTo(Allergen.PEANUTS));
        assertFalse(allergies.isAllergicTo(Allergen.SHELLFISH));
        assertTrue(allergies.isAllergicTo(Allergen.STRAWBERRIES));
    }

    @Ignore("Remove to run test")
    @Test
    public void noAllergies() {
        Allergies allergies = new Allergies(0);

        assertEquals(0, allergies.getList().size());
    }

    @Ignore("Remove to run test")
    @Test
    public void isAllergicToJustEggs() {
        Allergies allergies = new Allergies(1);
        List<Allergen> expectedAllergens = Collections.singletonList(Allergen.EGGS);

        assertEquals(expectedAllergens, allergies.getList());
    }

    @Ignore("Remove to run test")
    @Test
    public void isAllergicToJustPeanuts() {
        Allergies allergies = new Allergies(2);
        List<Allergen> expectedAllergens = Collections.singletonList(Allergen.PEANUTS);

        assertEquals(expectedAllergens, allergies.getList());
    }

    @Ignore("Remove to run test")
    @Test
    public void isAllergicToJustStrawberries() {
        Allergies allergies = new Allergies(8);
        List<Allergen> expectedAllergens = Collections.singletonList(Allergen.STRAWBERRIES);

        assertEquals(expectedAllergens, allergies.getList());
    }

    @Ignore("Remove to run test")
    @Test
    public void isAllergicToEggsAndPeanuts() {
        Allergies allergies = new Allergies(3);
        List<Allergen> expectedAllergens = Arrays.asList(
                Allergen.EGGS,
                Allergen.PEANUTS
        );

        assertEquals(expectedAllergens, allergies.getList());
    }

    @Ignore("Remove to run test")
    @Test
    public void isAllergicToEggsAndShellfish() {
        Allergies allergies = new Allergies(5);
        List<Allergen> expectedAllergens = Arrays.asList(
                Allergen.EGGS,
                Allergen.SHELLFISH
        );

        assertEquals(expectedAllergens, allergies.getList());
    }

    @Ignore("Remove to run test")
    @Test
    public void isAllergicToLotsOfStuff() {
        Allergies allergies = new Allergies(248);
        List<Allergen> expectedAllergens = Arrays.asList(
                Allergen.STRAWBERRIES,
                Allergen.TOMATOES,
                Allergen.CHOCOLATE,
                Allergen.POLLEN,
                Allergen.CATS
        );

        assertEquals(expectedAllergens, allergies.getList());
    }

    @Ignore("Remove to run test")
    @Test
    public void isAllergicToEverything() {
        Allergies allergies = new Allergies(255);
        List<Allergen> expectedAllergens = Arrays.asList(
                Allergen.EGGS,
                Allergen.PEANUTS,
                Allergen.SHELLFISH,
                Allergen.STRAWBERRIES,
                Allergen.TOMATOES,
                Allergen.CHOCOLATE,
                Allergen.POLLEN,
                Allergen.CATS
        );

        assertEquals(expectedAllergens, allergies.getList());
    }

    @Ignore("Remove to run test")
    @Test
    public void ignoreNonAllergenScoreParts() {
        Allergies allergies = new Allergies(509);
        List<Allergen> expectedAllergens = Arrays.asList(
                Allergen.EGGS,
                Allergen.SHELLFISH,
                Allergen.STRAWBERRIES,
                Allergen.TOMATOES,
                Allergen.CHOCOLATE,
                Allergen.POLLEN,
                Allergen.CATS
        );

        assertEquals(expectedAllergens, allergies.getList());
    }
}
import java.util.ArrayList;
import java.util.List;

class Allergies {
    private List<Allergen> allergens = new ArrayList<>();

    Allergies(int score) {
        checkScore(score);
        calculateAllergens(score);
    }

    boolean isAllergicTo(Allergen allergen) {
        return allergens.contains(allergen);
    }

    List<Allergen> getList() {
        return allergens;
    }

    /**
     * There is an allergen if the final score is a multiple of the allergen score, but not a multiple of the next power of two.
     * In this case we subtract the allergen score so that it does not affect the subsequent calculation
     */
    private void calculateAllergens(int score) {
        for (Allergen allergen : Allergen.values()) {
            int currentScore = allergen.getScore();
            if ((score % currentScore == 0) && (score % (2 * currentScore) != 0)) {
                allergens.add(allergen);
                score = score - currentScore;
            }
        }
    }

    private void checkScore(int score) {
        if (score < 1) {
            throw new IllegalArgumentException("score must be more than 0");
        }
    }
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?