Introduction to Programming in Java - An Interdisciplinary Approach 计算机科学导论-跨学科方法 部分练习答案1.4

1.4.4 Write a code fragment that reverses the order of the values in a one-dimensional string array. Do not create another array to hold the result. Hint : Use the code in the text for exchanging the values of two elements.

public class Work {  
    public static void main(String[] args) { 
        int[] a = {1,2,3,4,5};//在这里改要逆序的数组
        int n = a.length;
        for (int i = 0; i < n/2; i++){
            int temp = a[i];
            a[i] = a[n-1-i];
            a[n-1-i] = temp;
        }
        for (int i = 0; i <= n-1; i++){
            System.out.print(a[i]+" ");//不能用单引号' '
        }
        //System.out.println();
    }
}


1.4.15 Write a code fragment to transpose a square two-dimensional array in place without creating a second array.

public class Transpose {

    public static void main(String[] args) {

        // create n-by-n matrix
        int n = Integer.parseInt(args[0]);
        int[][] a = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                a[i][j] = n*i + j;
            }
        }

        // print out initial matrix
        System.out.println("Before");
        System.out.println("------");
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.printf("%4d", a[i][j]);
            }
            System.out.println();
        }

        // transpose in-place
        for (int i = 0; i < n; i++) {
            for (int j = i+1; j < n; j++) {
                int temp = a[i][j];
                a[i][j] = a[j][i];
                a[j][i] = temp;
            }
        }

        // print out transposed matrix
        System.out.println();
        System.out.println("After");
        System.out.println("------");
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.printf("%4d", a[i][j]);
            }
            System.out.println();
        }

    }
}

输入:3

输出:

Before
------
   0   1   2
   3   4   5
   6   7   8

After
------
   0   3   6
   1   4   7
   2   5   8

Transpose.java (princeton.edu)


1.4.33 Find a duplicate. Given an integer array of length n, with each value between 1 and n, write a code fragment to determine whether there are any duplicate values. You may not use an extra array (but you do not need to preserve the contents of the given array.)

public class Repeated {
    public static void main(String[] args) 
    {
        int[] my_array = {1, 2, 5, 5, 6, 6, 7, 2, 9, 2};
        findDupicateInArray(my_array);
 
    }
 
    public static void findDupicateInArray(int[] a) {
        int count=0;
        for(int j=0;j<a.length;j++) {
            for(int k =j+1;k<a.length;k++) {
                if(a[j]==a[k]) {
                    count++;
                }
            }
            if(count==1)
               System.out.println("repeated:"+a[j]);
            count = 0;
        }
    }
}

Java 实例 – 查找数组中的重复元素 | 菜鸟教程 (runoob.com)


1.4.41 Binomial distribution. Write a program that takes an integer command-line argument n and creates a two-dimensional ragged array a[][] such that a[n] [k] contains the probability that you get exactly k heads when you toss a fair coin n times. These numbers are known as the binomial distribution: if you multiply each element in row i by 2 n, you get the binomial coefficients—the coefficients of x k in (x+1)n—arranged in Pascal’s triangle. To compute them, start with a[n][0] = 0.0 for all n and a[1][1] = 1.0, then compute values in successive rows, left to right, with a[n][k] = (a[n-1][k] + a[n-1][k-1]) / 2.0.

Pascal’s triangle                                      binomial distribution
1                                                              1
11                                                             1/2 1/2
1 2 1                                                         1/4 1/2 1/4
1 3 3 1                                                      1/8 3/8 3/8 1/8
1 4 6 4 1                                                   1/16 1/4 3/8 1/4 1/16

public class BinomialCoefficients {
    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);

        int[][] pascal = new int[n+1][];

        // initialize first row
        pascal[1] = new int[1 + 2];
        pascal[1][1] = 1;

        // fill in Pascal's triangle
        for (int i = 2; i <= n; i++) {
            pascal[i] = new int[i+2];
            for (int k = 1; k < pascal[i].length - 1; k++)
                pascal[i][k] = pascal[i-1][k-1] + pascal[i-1][k];
        }

        // print binomial coefficients
        int denominator = 1;
        for (int i = 1; i <= n; i++) {
            for (int k = 1; k < pascal[i].length - 1; k++) {
                System.out.print(pascal[i][k] + "/" + denominator + " ");
            }
            System.out.println();
            denominator += denominator;
        }
    }

}

 BinomialCoefficients.java (princeton.edu)


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Programming skills are indispensable in today’s world, not just for computer science students, but also for anyone in any scientific or technical discipline. Introduction to Programming in Java, Second Edition, by Robert Sedgewick and Kevin Wayne is an accessible, interdisciplinary treatment that emphasizes important and engaging applications, not toy problems. The authors supply the tools needed for students and professionals to learn that programming is a natural, satisfying, and creative experience, and to become conversant with one of the world’s most widely used languages. This example-driven guide focuses on Java’s most useful features and brings programming to life for every student in the sciences, engineering, and computer science. Coverage includes Basic elements of programming: variables, assignment statements, built-in data types, conditionals, loops, arrays, and I/O, including graphics and sound Functions, modules, and libraries: organizing programs into components that can be independently debugged, maintained, and reused Algorithms and data structures: sort/search algorithms, stacks, queues, and symbol tables Applications from applied math, physics, chemistry, biology, and computer science Drawing on their extensive classroom experience, throughout the text the authors provide Q&As;, exercises, and opportunities for creative engagement with the material. Together with the companion materials described below, this book empowers people to pursue a modern approach to teaching and learning programming. Companion web site (introcs.cs.princeton.edu/java) contains Chapter summaries Supplementary exercises, some with solutions Detailed instructions for installing a Java programming environment Program code and test data suitable for easy download Detailed creative exercises, projects, and other supplementary materials Companion studio-produced online videos (informit.com/sedgewick) are available for purchase and provide students and professionals with th
Programming skills are indispensable in today’s world, not just for computer science students, but also for anyone in any scientific or technical discipline. Introduction to Programming in Java, Second Edition, by Robert Sedgewick and Kevin Wayne is an accessible, interdisciplinary treatment that emphasizes important and engaging applications, not toy problems. The authors supply the tools needed for students and professionals to learn that programming is a natural, satisfying, and creative experience, and to become conversant with one of the world’s most widely used languages. This example-driven guide focuses on Java’s most useful features and brings programming to life for every student in the sciences, engineering, and computer science. Coverage includes Basic elements of programming: variables, assignment statements, built-in data types, conditionals, loops, arrays, and I/O, including graphics and sound Functions, modules, and libraries: organizing programs into components that can be independently debugged, maintained, and reused Algorithms and data structures: sort/search algorithms, stacks, queues, and symbol tables Applications from applied math, physics, chemistry, biology, and computer science Drawing on their extensive classroom experience, throughout the text the authors provide Q&As;, exercises, and opportunities for creative engagement with the material. Together with the companion materials described below, this book empowers people to pursue a modern approach to teaching and learning programming. Companion web site (introcs.cs.princeton.edu/java) contains Chapter summaries Supplementary exercises, some with solutions Detailed instructions for installing a Java programming environment Program code and test data suitable for easy download Detailed creative exercises, projects, and other supplementary materials Companion studio-produced online videos (informit.com/sedgewick) are available for purchase and provide students and professionals with the opportunity to engage with the material at their own pace and give instructors the opportunity to spend their time with students helping them to succeed on assignments and exams.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值