ToDo List (with.Java)
In this article, we learned about to-do lists (with.Java).
We’ll be solving coding test problems, reflecting on the problems we’ve solved, and learning about other ways to solve them.
Let’s start with the problem.
Problem
Given a string array todo_list containing a list of things to do today and a boolean array finished indicating whether you have finished each task now, write a solution function that returns an array of strings containing the unfinished tasks in order from todo_list.
Example input and output
todo_list | finished | result |
---|---|---|
[“problemsolving”, “practiceguitar”, “swim”, “studygraph”] | [true, false, true, false] | [“practiceguitar”, “studygraph”] |
My solution to the problem
import java.util.*;
class Solution {
public String[] solution(String[] todo_list, boolean[] finished) {
ArrayList<String> answer = new ArrayList<String>();
for(int i = 0; i < finished.length; i++){
if(finished[i] == false){
answer.add(todo_list[i]);
}
}
String[] result = new String[answer.size()];
for(int j = 0; j < answer.size(); j++){
result[j] = answer.get(j);
}
} return result;
}
}
Solution
ArrayList
for(int i = 0; i < finished.length; i++) : Iterate over the finished array, checking each to-do for completion.
if(finished[i] == false) : If the current to-do is not finished (i.e., if finished[i] is false), add that to-do to the answer ArrayList.
String[] result = new String[answer.size()];: Create an array of strings result that fits the size of answer ArrayList.
for(int j = 0; j < answer.size(); j++) : Iterate over the answer ArrayList, copying each to-do to the result array.
return result; : Finally, return the result array with the list of to-dos that have not yet been completed.