Skip to content

Instantly share code, notes, and snippets.

@mrmemmo
Created December 14, 2020 14:55
Show Gist options
  • Save mrmemmo/6c7c17176bd7194adc3270d475aeaad8 to your computer and use it in GitHub Desktop.
Save mrmemmo/6c7c17176bd7194adc3270d475aeaad8 to your computer and use it in GitHub Desktop.
import java.util.*;
/*
* the MonthlyBudget class will be provided a limit (example, $200),
* a string array of items (netflix, gym membership, spotify premium, etc)
* a parallel int array of prices for each item (15, 50, 8, etc)
*
* The monthlyBudget class should also keep track of a current budget
* and
* a myItems arraylist that tracks items that fit in your budget
*
* You will create the entire MonthlyBudget class
* which will include three methods
* 1) the constructor method
* 2) the ArrayList<String> assignRandomItems() method - this method continues to assign
* random items from the items array to your myItems list until the limit is exceeded
* The items that exceeds the item should not be added to the list
* If all items are added the method should end and return the myItems arraylist
*
* 3) a method that returns the budget value
*
*/
public class MonthlyBudget
{
private int budget;
private int limit;
private ArrayList<String> items;
private ArrayList<Integer> price;
private ArrayList<String> myItems;
public MonthlyBudget(int limit, String[] it, int[] p)
{
this.limit = limit;
items = new ArrayList<String>();
price = new ArrayList<Integer>();
for(int i = 0; i<it.length; i++){
items.add(it[i]);
price.add(p[i]);
}
budget = 0;
myItems = new ArrayList<String>();
}
public ArrayList<String> assignRandomItems(){
boolean go = true;
while(go && items.size()>0){
int r = (int) (Math.random() * items.size());
if(budget + price.get(r) < limit){
myItems.add(items.remove(r));
budget += price.remove(r);
}else{
go = false;
}
}
return myItems;
}
public int getBudget(){
return budget;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment