Advertisement
joxaren

recursive SumAndCount

Nov 17th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. public class SumAndCount {
  5.  
  6.     public static void main(String[] args) {
  7.         ArrayList<Integer> list = new ArrayList<>();
  8.         list.add(1);
  9.         list.add(2);
  10.         list.add(3);
  11.         list.add(1);
  12.         list.add(1);
  13.         System.out.println(sum(list));
  14.         System.out.println(sum(list));
  15.     }
  16.  
  17.     static int sum(List<Integer> integers) { // dima
  18.         if (integers.isEmpty()) return 0;
  19.         else {
  20.             int lastIndex = integers.size() - 1;
  21.             return integers.get(lastIndex) + sum(integers.subList(0, lastIndex));
  22.         }
  23.     }
  24.  
  25.     static int sum(ArrayList<Integer> list) { // recursion
  26.         int sum;
  27.         ArrayList<Integer> tempList = new ArrayList<>(list);
  28.         if (tempList.isEmpty()) {
  29.             return 0;
  30.         } else {
  31.             sum = tempList.get(0);
  32.             tempList.remove(0);
  33.             sum += sum(tempList);
  34.         }
  35.         return sum;
  36.     }
  37.  
  38.     public static int sum1(ArrayList<Integer> list) { // loop
  39.         int sum = 0;
  40.         for (int i : list) {
  41.             sum += i;
  42.         }
  43.         return sum;
  44.     }
  45.  
  46.     static int countNumberOfItems(ArrayList<Integer> list) {
  47.         int count = 0;
  48.         if (list.isEmpty()) {
  49.             return 0;
  50.         } else {
  51.             for (Integer items : list) {
  52.                 count++;
  53.                 System.out.println("derp");
  54.             }
  55.         }
  56.         return count;
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement