001package algs13; 002import java.text.DecimalFormat; 003import stdlib.*; 004public class PlaygroundA { 005 private double a[]; 006 private Node first; 007 static class Node { 008 public double item; 009 public Node next; 010 public Node (double item, Node next) { 011 this.item = item; 012 this.next = next; 013 } 014 } 015 016 public int numFives () { 017 return StdRandom.uniform (100); //TODO: fix this 018 } 019 020 /* ToString method to print */ 021 public String toString () { 022 // Use DecimalFormat #.### rather than String.format 0.3f to leave off trailing zeroes 023 DecimalFormat format = new DecimalFormat ("#.###"); 024 StringBuilder result = new StringBuilder ("[ "); 025 for (Node x = first; x != null; x = x.next) { 026 result.append (format.format (x.item)); 027 result.append (" "); 028 } 029 result.append ("]"); 030 return result.toString (); 031 } 032 033 /* Method to create lists */ 034 public static PlaygroundA from(String s) { 035 PlaygroundA result = new PlaygroundA (); 036 if ("".equals (s)) { 037 // special case for the empty array 038 result.first = null; 039 result.a = new double [0]; 040 } else { 041 String[] nums = s.split (" "); 042 Node first = null; 043 double[] a = new double[nums.length]; 044 for (int i = nums.length-1; i >= 0; i--) { 045 double num = Double.NaN; 046 try { 047 num = Double.parseDouble (nums[i]); 048 } catch (NumberFormatException e) { 049 throw new IllegalArgumentException (String.format ("Bad argument \"%s\": could not parse \"nums[i]\" as a double", s, nums[i])); 050 } 051 a[i] = num; 052 first = new Node (num, first); 053 } 054 result.a = a; 055 result.first = first; 056 } 057 return result; 058 } 059 060 public static void testNumFives (int expected, String sList) { 061 PlaygroundA list = PlaygroundA.from (sList); 062 int actual = list.numFives (); 063 if (expected != actual) { 064 StdOut.format ("Failed: Expecting [%d] Actual [%d] with argument %s\n", expected, actual, list); 065 } 066 } 067 public static void main (String[] args) { 068 testNumFives (2, "11 5 5 21"); 069 testNumFives (0, "11 21 31 41"); 070 testNumFives (1, "11 21 5 31 41"); 071 testNumFives (1, "5 11 21 31 41"); 072 testNumFives (1, "11 21 31 41 5"); 073 testNumFives (5, "5 11 21 5 5 31 5 41 5"); 074 testNumFives (3, "5 5 5"); 075 testNumFives (1, "5"); 076 testNumFives (0, "11"); 077 testNumFives (0, ""); 078 StdOut.println ("Finished tests"); 079 } 080 public static void main1 (String[] args) { 081 Trace.drawStepsOfMethod ("numFives"); 082 Trace.drawStepsOfMethod ("numFivesH"); 083 Trace.run (); 084 PlaygroundA list0 = PlaygroundA.from ("5"); 085 PlaygroundA list1 = PlaygroundA.from ("5 11 5 5"); 086 int result = list1.numFives (); 087 StdOut.println ("result: " + result); 088 } 089}