算法 Robert Sedgewick 习题答案 1.1 基础编程模型

来源:互联网 发布:flyme升级清除数据吗 编辑:程序博客网 时间:2024/06/05 04:03

似乎Algorithms 4th没有答案,那就自己做一份吧,难免有错误

stdlib,algis4两个jar包去此书官网下载导入工程

main中为我自己写的测试程序


1.1.1

7

200.0000002

true


1.1.2 

double 1.618

double  10.0

boolaen true

String 33


1.1.3

package chapter1_1;public class Exercise3 {public static void main(String[] args) {if (new Exercise3().isEqual(args[0], args[1], args[2]))System.out.println("equal");elseSystem.out.println("not equal");}private boolean isEqual(String s1, String S2, String S3) {return Integer.parseInt(s1) == Integer.parseInt(S2)&& Integer.parseInt(S2) == Integer.parseInt(S3);}}

1.1.4

不需要then

少括号

正确

少分号


1.1.5

package chapter1_1;public class Exercise3 {public static void main(String[] args) {if (new Exercise3().isEqual(args[0], args[1], args[2]))System.out.println("equal");elseSystem.out.println("not equal");}private boolean isEqual(String s1, String S2, String S3) {return Integer.parseInt(s1) == Integer.parseInt(S2)&& Integer.parseInt(S2) == Integer.parseInt(S3);}}

1.1.6

0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610

斐波那契数列


1.1.7

3.00009

499500

10000


1.1.8

b

197

101


1.1.9

package chapter1_1;public class Exercise9 {public static void main(String[] args){System.out.println(new Exercise9().toBinaryString(525));}//N用二进制表示并private String toBinaryString(int N){String s = "";for(int n=N;n>0;n=n>>1)s = (n&1) + s;return s;}}

1.1.10

数组没有初始化


1.1.11

package chapter1_1;public class Exercise11 {public static void main(String[] args){boolean[][] a={{true,true},{false,true}};System.out.print(" 0 1");System.out.println();for(int i=0;i<2;i++){System.out.print(i);for(int j=0;j<2;j++)if(a[i][j])System.out.print("*"+" ");else System.out.print(" "+" ");System.out.println();}}}

1.1.12

0
1
2
3
4
5
6
7
8
9


1.1.13

package chapter1_1;public class Exercise13 {private int[][] transposition(int[][] a, int M, int N) {int[][] b = new int[N][M];for (int i = 0; i < N; i++)for (int j = 0; j < M; j++)b[i][j] = a[j][i];return b;}public static void main(String[] args) {int[][] a = { { 1, 2, 3, 4 }, { 3, 2, 3, 5 }, { 6, 3, 6, 8 } };a = new Exercise13().transposition(a, 3, 4);for (int i = 0; i < 4; i++) {for (int j = 0; j < 3; j++)System.out.print(a[i][j] + " ");System.out.println();}}}

1.14

package chapter1_1;public class Exercise14 {public static int lg(int N) {int count = 0;while (N != 1) {N = N >> 1;++count;}return count;}public static void main(String[] args) {System.out.println(Exercise14.lg(33));}}

1.1.15

package chapter1_1;public class Exercise15 {public static void main(String[] args) {int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 6, 5, 3 };int[] b = Exercise15.histogram(a, 11);int sum = 0;for (int i = 0; i < b.length; i++) {System.out.print(b[i] + " ");sum += b[i];}// a[]中所有元素都在0到M-1之间,b中元素的和应该和a的长度相等System.out.println(sum == a.length);}private static int[] histogram(int[] a, int M) {int[] b = new int[M];for (int i = 0; i < a.length; i++)if (a[i] >= 0 && a[i] <= M - 1)b[a[i]]++;return b;}}

1.1.16

311361142246

字符串+整形的应用


1.1.17

基础情况永远不会被访问


1.1.18

50

33

a,b的积


33554432
177147

a的b次方


1.1.19

计算到40以上效率明显变慢(没有测试1个小时)

package chapter1_1;public class Exercise19 {// 递归实现斐波那契数列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++)System.out.println(N + " " + F1(N));}// 循环实现斐波那契数列public static long F1(int N) {if (N == 0)return 0;int[] a = new int[N + 1];a[0] = 0;a[1] = 1;for (int i = 2; i < a.length; i++)a[i] = a[i - 1] + a[i - 2];return a[N];}// TODO 矩阵快速幂实现斐波那契数列,此题效率已经满足要求,以后写}

1.1.20

package chapter1_1;public class Exercise20 {public static double ln(int N) {if (N == 1)return Math.log(1);return Math.log(N) + ln(N - 1);}public static void main(String[] args) {System.out.println(ln(9));}}


1.1.21

使用的测试数据为2012-2013赛季西甲射手榜,输入为姓名,进球数,射门数

Messi|46|235
Ronaldo|34|163
Falcao|28|123
Negredo|25|150
Soldado|24|100
Castro|18|79
Piti|18|111
Higuaín|16|56
Aduriz|14|87
Alberto|14|102


package chapter1_1;import java.io.BufferedReader;import java.io.FileNotFoundException;import java.io.FileReader;import java.util.ArrayList;public class Exercise21 {public static void main(String[] args) {try {BufferedReader br = new BufferedReader(new FileReader("goals.txt"));String s = null;ArrayList<forward> forwards = new ArrayList<>();while ((s = br.readLine()) != null) {forward f = readData(s);forwards.add(f);}System.out.println("name      " + "goals      " + "shots     "+ "accuracy");for (forward f : forwards)System.out.print(f);} catch (Exception e) {e.printStackTrace();}}public static forward readData(String s) {String[] datas = s.split("\\|");return new forward(datas[0], Integer.parseInt(datas[1]),Integer.parseInt(datas[2]));}}class forward {String name;int goals;int shots;double accuracy;public forward(String name, int goals, int shots) {this.name = name;this.goals = goals;this.shots = shots;this.accuracy = (double) goals / shots;}@Overridepublic String toString() {return name + "        " + goals + "       " + shots + "     "+ accuracy + "\n";}}


1.1.22

package chapter1_1;public class Exercise22 {private int count;public int rank(int key, int lo, int hi, int[] a) {++count;for (int i = 0; i < count; i++)System.out.print(" ");System.out.println("lo=" + lo + "  hi=" + hi);if (lo > hi)return -1;int mid = (hi - lo) / 2 + lo;if (key < a[mid])return rank(key, lo, mid - 1, a);else if (key > a[mid])return rank(key, mid + 1, hi, a);elsereturn mid;}public static void main(String[] args) {int[] a = { 1, 3, 5, 6, 7, 8, 9, 11, 13, 15, 16, 17, 35, 67, 78, 79 };System.out.println(new Exercise22().rank(16, 0, a.length - 1, a));System.out.println(new Exercise22().rank(18, 0, a.length - 1, a));}}

1.1.23

使用的查找名单为(whiteList.txt)

3
2
1
237
343452
123
12
12333
756
43
23
433
233
55
554
332
221
7666
553344
45425
2524
32442
233444
5
5525
48789
87
3269
998
646
997
777777
46554544
456488994
6464646
64465
54656
4664
468
64684
898
894
99999
4653
44
48

package chapter1_1;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileReader;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;public class Exercise23 {public int rank(int key, int lo, int hi, ArrayList<Integer> arry) {int mid = (hi - lo) / 2 + lo;if (lo > hi)return -1;if (key > arry.get(mid))return rank(key, mid + 1, hi, arry);else if (key < arry.get(mid))return rank(key, lo, mid - 1, arry);elsereturn mid;}public void search(ArrayList<Integer> arry, int[] search, char c) {int[] a = new int[search.length];for (int i = 0; i < search.length; i++)a[i] = rank(search[i], 0, arry.size() - 1, arry);if (c == '+') {for (int j = 0; j < a.length; j++) {if (a[j] == -1)System.out.print(search[j] + " ");}} else {for (int j = 0; j < a.length; j++) {if (a[j] != -1)System.out.print(search[j] + " ");}}}public static void main(String args[]) {ArrayList<Integer> arry = new ArrayList<>();try {BufferedReader br = new BufferedReader(new FileReader("mydata/whiteList.txt"));String s = null;while ((s = br.readLine()) != null) {arry.add(Integer.parseInt(s));}} catch (Exception e) {e.printStackTrace();}Collections.sort(arry);int[] search = { 2, 3, 45, 23, 77, 3269, 9787, 693, 468, 8941, 6666666,99999, 777777 };Exercise23 binarySearch = new Exercise23();binarySearch.search(arry, search, '+');System.out.println();binarySearch.search(arry, search, '-');}}

1.1.24

package chapter1_1;public class Exercise24 {public static int Euclid(int p,int q){System.out.println("p="+p+" "+"q="+q);if(q==0)return p;elsereturn Euclid(q,p%q);}public static void main(String[] args){System.out.println(Euclid(105,24));System.out.println(Euclid(Integer.parseInt(args[0]), Integer.parseInt(args[1])));}}

p=105 q=24
p=24 q=9
p=9 q=6
p=6 q=3
p=3 q=0
3
p=1111111 q=1234567
p=1234567 q=1111111
p=1111111 q=123456
p=123456 q=7
p=7 q=4
p=4 q=3
p=3 q=1
p=1 q=0
1


1.1.25

首先,算法的最终结果rN−1同时整除ab。因为它是一个公约数,所以必然小于或者等于最大公约数g。然后,任何ab的公约数都能整除rN−1。所以g一定小于或等于rN−1。两个不等式只在rN−1 = g是同时成立。具体证明如下:

  1. 证明rN−1同时整除ab
    因为余数rN是0,rN−1能够整除rN−2
    rN−2 = qN rN−1
    因为rN−1能够整除rN−2,所以也能够整除rN−3
    rN−3 = qN−1 rN−2 + rN−1
    同理可证rN−1可以整除所有之前步骤的余数,包括ab,即rN−1ab的公约数,rN−1 ≤ g
  2. 证明任何整除ab的自然数g(也就是ab的公约数)都能整除rN-1
    根据定义,ab可以写成g的倍数:a = mgb = ng,其中mn是自然数。因为r0 = a − q0b = mg − q0ng = (m − q0n)g,所以g整除r0。同理可证g整除每个余数r1r2……rN-1。所以,最大公约数g一定整除rN−1,因而g ≤ rN−1

因为第一步的证明告诉我们rN−1 ≤ g,所以g = rN−1。即:

g = GCD(a, b) = GCD(b, r0) = GCD(r0,r1) = … = GCD(rN−2, rN−1) =rN−1