-
Notifications
You must be signed in to change notification settings - Fork 2
/
exercises1.txt
648 lines (471 loc) · 16.7 KB
/
exercises1.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
Algorithms 4th Ed
Exercises 1
1.1.1 Give the value of the following expressions:
a) (0 + 15) / 2 ?
= 7
because is integer division. 15/2 = 7.5 gets truncated to 7
b) 2.0e-6 * 100000000.1
== 0.000002 * 100000000.1
= 2 x 10^-6 * 1000000001 * 10^-1 == 2000000002 * 10^-7 == 200.0000002
Program prints this value as expected
c) true && false || true && true
evaluation is left associative so first term is true then next term is false BUT there is then an or so
checks that term - is true so then checks last term - is true so returns true.
1.1.2 Give the type and value of each of the following expressions:
a) (1 + 2.236) / 2
In brackets there is a floating point number so integer 1 is promoted to floating point and hence brackets
evaluates to 3.236. floating point divided by integer is promoted to floating point division and result is: 1.618
b) 1 + 2 + 3 + 4.0 = 10.0
addition is left associative so 1 + 2 + 3 results in integer addition resulting in 6
Then you get 6 + 4.0 which is promoted to 6.0 + 4.0 = 10
c) 4.1 >= 4 = true
d) 1 + 2 + "3" = "123"
*** Got that wrong. I am getting 33. Why???
Ah got it, addition is left associative so you get 1+2 = 3 by integer addition. Then java seens + used
with an integer and a string so the tostring conversion is used to concatenate resulting in "33"
1.1.3 Write a program that takes three integer command line arguments and prints equal if all three are equal,
and not equal otherwise.
// set PATH="C:\Program Files\Java\jdk1.7.0_07\bin";%PATH%
// javac -cp stdlib.jar;algs4.jar;. ex1a.java
// java -cp stdlib.jar;algs4.jar;. ex1a 6 7 8
public class ex1a {
public static void main(String[] args) {
if(args.length < 3)
StdOut.println("Must pass 3 integer arguments");
else {
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
int n3 = Integer.parseInt(args[2]);
StdOut.println( n1 == n2 && n2 == n3 ? "equal" : "not equal");
}
}
}
1.1.4 What (if anything) is wrong with each of the following statements?
a) if (a > b) then c = 0; // then is a syntax error
b) if a > b { c = 0; } //brackets around a>b expression required
c) if (a > b) c = 0; // fine.
d) if (a > b) c = 0 else b = 0; //; required after c = 0
1.1.5 Write a code fragment that prints true if the double variables x and y are both strictly between
0 and 1 and false otherwise.
public static void main(String[] args) {
if(args.length < 2)
StdOut.println("Must pass 2 double arguments");
else {
double d1 = Double.parseDouble(args[0]);
double d2 = Double.parseDouble(args[1]);
StdOut.println(d1 > 0 && d1 < 1 && d2 > 0 && d2 < 1 );
}
}
1.1.6 - prints fibonacci sequence.
1.1.7 Give the value printed by each of the following code fragments:
a.
double t = 9.0;
while(Math.abs(t - 9.0/t) > .001)
t = (9.0/t + t) / 2.0;
StdOut.printf("%.5f\n", t);
while loop produces:
5.0
3.4
3.02
converging towards 3.0000000
When run mine produced: 3.00009
b.
int sum = 0;
for (int i = 1; i < 1000; i++)
for(int j = 0; j < 1000; j++)
sum++;
StdOut.println(sum);
should produce 1000 * 1000 (1000 being incremented by 1, 1000 times.
Ah, that was wrong. Produces 999000.
Ah, because i is from 1 to 999 (excludes 1000) you miss out 1000. and 999000 + 1000 = 1000000.
Edit for loop to be (int i = 1; i <= 1000; i++) and get expected 1m. Or better:
(int i = 0; i < 1000; i++)
c.
int sum = 0;
for (int i = 1; i < 1000; i++)
for(int j = 0; j < 1000; j++)
sum++;
StdOut.println(sum);
The outer loop doubles each time, bounded by 1000. log2(1000)/log2(2) = 9.97 so will go from 0 - 9
so sum will be 9 * 1000 = 9000
No, because I forgot log2(1) = 0. So add 1.
sum will be 10 * 1000 = 10000
ie i increments like this:
1 1 2^0
2 2 2^1
3 4 2^2
4 8 2^3
5 16 2^4
6 32 2^5
7 64 2^6
8 128 2^7
9 256 2^8
10 512 2^9
1.1.8 What do each of the following print?
a. System.out.println('b');
prints b
Correct.
b. System.out.println('b' + 'c');
prints bc
Wrong! Prints 197.
Why?
The + operator does not work like concatenation on char values, instead it works like addition.
ascii value 'b' is integral value 98 (or 0x62). The UTF value is the same. Ascii 'c' is 99. 98 + 99 = 197
c. System.out.println('a' + 4);
From above we can probably guess correctly.
ascii 'a' = 97 + 4 = 101
Correct!
1.1.9 Write a code fragment that puts the binary representation of a positive integer N into a String s.
Without looking at solution I did this:
public static String int2binary(int n) {
String s = new String();
while(n > 0) {
s += (n % 2);
n /= 2;
}
StringBuilder rev = new StringBuilder(s);
return rev.reverse().toString();
}
The reversing bit on end is not very elegant. so I liked the solution. all it does differently is add the
character to the BEGINNING of the string each time.
my version converted:
public static String int2binary(int n) {
String s = new String();
while(n > 0) {
s = (n % 2) + s;
n /= 2;
}
return s;
}
1.1.10 - answer provided - just read it.
1.1.11 Write a code fragment that prints the contents of a two dimensional boolean array, using * to to
represent true and a space to represent false. Include row and column numbers.
public static void printarray(boolean[][] arr) {
for(int row = 0; row < arr.length; ++row) {
for(int col = 0; col < arr[row].length; ++col) {
System.out.print(arr[row][col] ? "*" : " "); }
System.out.print('\n');
}
System.out.printf("Array contains %d rows and %d columns\n", arr.length, arr[0].length);
}
1.1.12 What does the following print?
int[] a = new int[10];
for (int i = 0; i < 10; i++)
a[i] = 9 - i;
for (int i = 0; i < 10; i++)
a[i] = a[a[i]];
for (int i = 0; i < 10; i++)
System.out.println(i);
Surely it just prints 0 to 9.
And it does.
1.1.13 Write a code fragment to print the transposition (rows and columns changed) of a two dimensional
array with M rows and N columns.
import java.util.Arrays;
//http://en.wikipedia.org/wiki/Transpose
public static int[][] transposition(int[][] array,int m,int n){
int[][] transposed=new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
transposed[i][j]=array[j][i];
}
}
return transposed;
}
1.1.14 Write a static method lg() that takes an int value N as argument and returns the largest int not
larger than the base-2 logarithm of N. Do not use Math.
// log base 2
public static int lg(int n) {
//take number and keep dividing by 2 until zero
int count = 0;
while(n > 0) {
n /= 2;
++count;
}
return count - 1;
}
1.1.15 Write a static method histogram() that takes an array a[] of int values and an integer M as
arguments and returns an array of length M whose ith entry is the number of times the integer i
appeared in the argument array. If the values in a[] are all between 0 and M-1, the sum of the values
in the returned array should be equal to a.length.
int[] histogram(int[] array, int m) {
Arrays.sort(array);
int[] ret=new int[m];
int i=0;
while (i<array.length&&array[i]<m){
ret[array[i]]= ++ret[array[i]];
i++;
}
return ret;
}
Call it like this:
int[] arr = {5,5,5,4};
int ret[] = histogram(arr, 6));
1.1.16 Give the value of exR1(6):
public static String exR1(int n)
{
if (n <= 0) return "";
return exR1(n-3) + n + exR1(n-2) + n;
}
exR1(6) -> n >= 0 so returns blank string
1.1.17 Criticise the following recursive function:
public static String exR2(int n)
{
String s = exR2(n-3) + n + exR2(n-2) + n;
if(n <= 0) return "";
return s;
}
Example exR2(6)
exR2(6) -> exR2(3) + 6 + exR2(4) + 6;
exR2(3) -> exR2(0) + 3 + exR2(1) + 3;
exR2(4) -> exR2(1) + 4 + exR2(2) + 4;
exR2(0) -> exR2(-3) + 0 + exR2(-2) + 0;
Problem is that the base case (ie when a condition met, return) is AFTER recursive calls. So recursion
step never ends. Get stackoverflow as per book.
1.1.18 Consider the following recursive function:
public static int mystery(int a, int b)
{
if (b == 0) return 0;
if(b % 2 == 0) return mystery(a+a, b/2);
return mystery(a+a, b/2) + a;
}
What are the values of mystery(2, 25) and mystery(3, 11)? Given positive integers a and b, describe what
value mystery(a, b) computes. answer the same question, but replace + with * and replace return 0 with return 1.
mystery(2, 25)
1) -> mystery(4, 12) + 2
2) -> ( mystery(8, 6) ) + 2
3) -> ( mystery(16, 3) + 16) + 2
4) -> (( mystery(32, 1) + 32 ) + 16) + 2
5) -> ( mystery(64, 0) + 32 ) + 16) + 2
6) -> ( 0 ) + 32 + 16 + 2
= 50
1) -> mystery(3, 11)
2) -> ( mystery(6, 5) + 3
3) -> ( mystery(12, 2) + 6) + 3
4) -> ( mystery(24, 1) + 6) + 3
5) -> ( mystery(48, 0) + 24 ) + 6) + 3
5) -> ( 0 + 24 + 6 + 3)
= 33
mystery(a, b) = ?
Well, I thought best thing to do is try some small numbers and run them and see what it looks like:
example input:
0, 5 = 0
1, 5 = 5
2, 5 = 10
2, 25 = 50
it looks like the answer is a * b.
Lets put in some values just to check that works. Try even and odd combinations. You could use code like
this to test:
if(args.length < 2)
System.out.println("Must pass 2 integer arguments");
else {
System.out.println(mystery(Integer.parseInt(args[0]), Integer.parseInt(args[1])));
}
It seems to work. Hence mystery(a, b) = a * b
If we change any + to * and 0 to 1, then the function will eventually return a^b.
1.1.19 Run the following program on your computer:
public class fibonacci {
public static long f(int n)
{
if (n == 0) return 0;
if (n == 1) return 1;
return f(n-1) + f(n-2);
}
public static void main(String[] args) {
for(int n = 0; n<100; n++)
StdOut.println(n + " " + f(n));
}
}
This program takes a long..... long.... time.
Largest value of n? About 55?
The question asks for a better implementation which saves computed values in an array.
OK looked this up. Idea is memoization. See here:
http://en.wikipedia.org/wiki/Memoization
And here for Java code examples:
http://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Fibonacci_Number_Program#Java
Essentially, the idea is to 'chache' values in an array.
Doing this very simply with fixed size array:
public class fib_memo {
static long[] fib = new long[100];
public static long f(int n)
{
if (n == 0) return 0;
if (n == 1) return 1;
if(fib[n] == 0) {
fib[n] = f(n-1) + f(n-2);
}
return fib[n];
}
public static void main(String[] args) {
for(int n = 0; n<100; n++)
StdOut.printf("fib[%4d] = %14d\n", n, f(n));
}
}
To do more professionally, you would need to use a re-sizeable array and keep expanding the array as large n's
were required. But this simple implementation makes operation very quick. You now do not even notice any
delay in printing results.
One other issue is that even the 64 bit long overflows with large fib numbers. Looks like from fib(93).
So better to use Java's bigInteger type for big n.
If you read up on fibonacci and the golden ratio you will see that there is an algebraic method of
calculating fibonacci. It is an estmimation but it is accurate for integer values.
Formula can be found here:
http://www.mathsisfun.com/numbers/nature-golden-ratio-fibonacci.html
In java code:
public class fibonacci {
public static long f(int n)
{
if (n == 0) return 0;
if (n == 1) return 1;
return f(n-1) + f(n-2);
}
// phi = (1 + sqrt(5) / 2)
public static double phi()
{
return (1 + Math.sqrt(5)) / 2.0;
}
public static long fib_alg(int n) {
return (long)Math.round(Math.pow(phi(), n) / Math.sqrt(5.0) );
}
public static void main(String[] args) {
for(int n = 0; n<100; n++)
StdOut.println(n + " " + fib_alg(n));
}
}
1.1.20 Write a recursive static method that computes the value of ln(N!)
public class ex_1_1_20 {
public static long fact(int n)
{
if (n < 2) return 1;
return n * fact(n-1);
}
public static void main(String[] args) {
for(int n = 0; n<20; n++)
StdOut.printf("ln(%d!) = %f\n", n, Math.log(fact(n)));
}
}
1.1.21 Write a program that reads in lines from std input with each line
containing a name and two integers and then use printf() to print a table
with a column of the names, the integers, and the result of dividing the
first by the second, accurate to three decimal places. You could use a
program like this to tabulate batting averages for baseball players or grades for students.
public class ex_1_1_21 {
public static class Data
{
public Data() {}
public Data(double v1, double v2, String s1) { n1 = v1; n2 = v2; s = s1; }
public double n1;
public double n2;
public String s;
};
public static void main(String[] args) {
int i = 0;
int idx = 0; // array index
double v1, v2;
v1 = v2 = 0;
String s;
Data items[] = new Data[100]; //asumes no more than 100 items
while(!StdIn.isEmpty()) {
switch(i % 3) {
case 0: v1 = StdIn.readFloat(); break;
case 1: v2 = StdIn.readInt(); break;
case 2:
s = StdIn.readString();
items[idx++] = new Data(v1, v2, s);
break;
}
++i;
}
StdOut.println("Item\tNum1\tNum2\tdiv");
for(int j = 0; j < idx; ++j) {
StdOut.printf( "%s\t%3.3f\t%3.3f\t%3.3f\n",
items[j].s, items[j].n1, items[j].n2, items[j].n1 / items[j].n2);
}
StdOut.printf("%d items\n", idx);
}
}
Improved tidy version:
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
public class test {
public class Data
{
public Data() {}
public Data(double v1, double v2, String s1) { n1 = v1; n2 = v2; s = s1; }
public double n1;
public double n2;
public String s;
};
LinkedList<Data> getData() {
int i = 0;
double v1, v2;
v1 = v2 = 0;
String s;
LinkedList<Data> list = new LinkedList<Data>();
Scanner input = new Scanner(System.in);
while(input.hasNext()) {
switch(i % 3) {
case 0: v1 = input.nextFloat(); break;
case 1: v2 = input.nextFloat(); break;
case 2:
s = input.next();
list.add(new Data(v1, v2, s));
break;
}
++i;
}
input.close();
return list;
}
void display_table(LinkedList<Data> list) {
System.out.printf("%d items\n", list.size());
System.out.println("Item\tNum1\tNum2\tdiv");
Iterator<Data> iter = list.iterator();
while(iter.hasNext()) {
Data item = (Data) iter.next();
System.out.printf( "%s\t%3.3f\t%3.3f\t%3.3f\n", item.s, item.n1, item.n2, item.n1 / item.n2);
}
}
void run() {
display_table(getData());
}
public static void main(String[] args) {
new test().run();
}
}
1.1.22 Write a version of BinarySearch that uses the recursive rank() given on page 25 and traces the method
calls. Each time the recursive method is called, print the argument values lo and hi, indented by the depth
of the recursion. hint: Add an argument to the recursive method that keeps track of the depth.
import java.util.Arrays;
public class BinarySearchRec
{
public static int rank(int key, int[] a)
{
return rank(key, a, 0, a.length - 1, 0);
}
public static int rank(int key, int[] a, int lo, int hi, int depth)
{ // Index of key in a[], if present, is not smaller than lo
// and not larger than hi
int tmp = depth;
while(tmp-- > 0)
StdOut.print(' '); //padding by recursion call depth
StdOut.printf("key = %d, lo = %d, hi = %d\n", key, lo, hi);
if(lo > hi) {
StdOut.printf("key = %d not found\n", key);
return -1;
}
int mid = lo + (hi - lo) / 2;
if (key < a[mid]) return rank(key, a, lo, mid - 1, ++depth);
else if (key > a[mid]) return rank(key, a, mid + 1, hi, ++depth);
else return mid;
}
public static void main(String[] args) {
int[] whitelist = In.readInts(args[0]);
Arrays.sort(whitelist);
while(!StdIn.isEmpty())
{ //read key, print if not in whitelist
int key = StdIn.readInt();
if(rank(key, whitelist) < 0)
StdOut.println(key);
}
}
}