The source code for this blog is available on GitHub.
Note
Top

Civil Service Exam Prep: Common Programming Languages to Know

Cover Image for Civil Service Exam Prep: Common Programming Languages to Know
Chen Han
Chen Han

Q1 - language c

What is x?

int a[10][20];
int x=&a[5]-&a[4];

a is a two-dimensional array of integers with 10 rows and 20 columns. The expression &a[5] is a pointer to the 5th row of the array, and &a[4] is a pointer to the 4th row.

Subtracting these two pointers produces the distance between the two rows in terms of the number of rows. In this case, the distance is 1 row, since a[5] is the 5th row and a[4] is the 4th row.

So, x is assigned the value of 1, which is the distance between the two rows in terms of the number of rows.

It is important to note that this is different from the previous examples, where the distance between the rows was calculated in terms of the number of elements (columns) in the array. Here, the distance is being calculated in terms of the number of rows, which is why the result is 1 rather than 20.

Q2 - language c

What is z?

int a[10][20];
int z=a[5]-a[4];

The value of z in this code is 20.

a is a two-dimensional array of integers with 10 rows and 20 columns. The expression a[5] is the first element in the 5th row of the array, and a[4] is the first element in the 4th row.

Subtracting these two elements produces the distance between the two rows in terms of the number of elements. In this case, the distance is 20 elements, which is the number of columns in the array.

So, z is assigned the value of 20, which is the number of columns in the array.

Note that this is the same result as in the previous example, but the difference is that in this case the elements being subtracted are array elements rather than pointers to the rows of the array. The result is the same because the rows of the array are contiguous in memory, so the distance between them in terms of the number of elements is equal to the number of columns in the array.

C#

pass function as argument

public class Class1
{
    public int Method1(string input)
    {
        //... do something
        return 0;
    }

    public int Method2(string input)
    {
        //... do something different
        return 1;
    }

    public bool RunTheMethod(Func<string, int> myMethodName)
    {
        //... do stuff
        int i = myMethodName("My String");
        //... do more stuff
        return true;
    }

    public bool Test()
    {
        return RunTheMethod(Method1);
    }
}

桌面應用程式

It will be nice to have Winforms and WebForms supports in Rider because millions of developers still use Winforms and WebForms today. Third parties components providers like Telerik,Infragistics,DevExpress ,ComponentOne,Syncfusion will boost Rider if Winforms/WebForms are added to Rider.

參考資料

C

資料型態

0x

C語言、C++、Shell、Python、Java語言及其他相近的語言使用字首0x,例如0x5A3。開頭的0令解析器更易辨認數,而x則代表十六進制(就如O代表八進制)。

(int *)

int* 是型別說明,而()是強制轉換運算子,*a 是取a指標變數地址中的資料。舉例來說:

return *(int *) a - *(int *) b; ➡️返回a b兩個地址中的整型資料的差!

int *a; 有時候有人會寫成(int *)(int *) 的用法

  • int *a ➡️定義一個int的指標變數a
  • a = (int *) <Address of b>
  • If b address is 0x3FFFF ➡️b = (int *) 0x3FFFF;

If statement

#include <stdio.h>

void *func(void *void_ptr)
{
	return void_ptr; 
}


int main(int argc, char* argv[])
{
	int a = 10, c = 5;
	int *b;
	if(a == 10) if (c == 5) printf("qwer\n"); else printf("asdf\n");
	if(a == 10) if (c == 8) printf("qwer\n"); else printf("asdf\n");
    if(a == 11) if (c == 8) printf("qwer\n"); else printf("asdf\n"); else printf("zxcv\n");
    
	b = ((int *)func(&a));

	printf("value: %d\n", *b);

    return 0;
}
qwer
asdf
zxcv
value: 10

宣告

我們也可以在宣告陣列時一併賦值:

int arr[5] = {3, 4, 5, 6, 7};

或者是用稍微取巧的方式來初始化:

int arr[] = {3, 4, 5, 6, 7};

陣列

下列為陣列長度

#include <assert.h>                        
#include <stddef.h>                        

int main(void)                             
{                                          
    int arr[] = {3, 4, 5, 6, 7};           
    size_t sz = sizeof(arr) / sizeof(int); 
    assert(sz == 5);                       

    return 0;                              
}                                          

指標&陣列

陣列裡面填入i++會發生的事情

int main()
{
    int arr[4] = {1, 2, 3, 4};
    int i = 0;
    printf("what is arr[i++]: %d\n", arr[i++]);
    printf("what is arr[i]: %d\n", arr[i]);

    return 0;
}
what is arr[i++]: 1
what is arr[i]: 2
Hello World

陣列裡面填入++i會發生的事情

int main()
{
    int arr[4] = {1, 2, 3, 4};
    int i = 0;
    printf("what is arr[++i]: %d\n", arr[++i]);
    printf("what is arr[i]: %d\n", arr[i]);

    return 0;
}
what is arr[++i]: 2
what is arr[i]: 2
Hello World

下列為陣列與指標的關係

  • 記憶體位址: &arr[i] == ptr+i
  • 變數值存取: arr[i] == *(ptr+i)

優先權

int *p[3]; //首先從p處開始,先與[]結合,因為優先權比較高

參考資料

下列為中鋼的考試內容,以及其輸出

#include <stdio.h>

int main()
{
    printf("Hello World\n");

     int z=0, i=20, j=-2;
     int a[10][20];
     int matrix[2][3] = {{1,2,3},{4,5,6}};
     
     printf("What is matrix[0]: %p\n", matrix[0]);
     printf("What is matrix[1] - matrix[0]: %ld\n", matrix[1] - matrix[0]);
     printf("What is matrix[0][0]: %i\n", matrix[0][0]);
     
     while(i-=2)
       ++z;
    
    printf("What is z: %i\n", z);   
    
    printf("What is a[5]: %p\n", a[5]);
    printf("What is a[4]: %p\n", a[4]);
    
    printf("What is &a[5]: %p\n", &a[5]);
    printf("What is &a[4]: %p\n", &a[4]);
    
    printf("What is a[5]-a[4]: %ld\n", a[5]-a[4]); 
    printf("What is a[8]-a[4]: %ld\n", a[8]-a[4]); 
    printf("What is &a[5]-&a[4]: %ld\n", &a[5]-&a[4]); 
    printf("What is &a[6]-&a[4]: %ld\n", &a[6]-&a[4]); 
    printf("What is &a[10]-&a[4]: %ld\n", &a[10]-&a[4]); 
    return 0;
}
Hello World
What is matrix[0]: 0x7fffc30780c0
What is matrix[1] - matrix[0]: 3
What is matrix[0][0]: 1
What is z: 9
What is a[5]: 0x7fffc3078270
What is a[4]: 0x7fffc3078220
What is &amp;a[5]: 0x7fffc3078270
What is &amp;a[4]: 0x7fffc3078220
What is a[5]-a[4]: 20
What is a[8]-a[4]: 80
What is &amp;a[5]-&amp;a[4]: 1
What is &amp;a[6]-&amp;a[4]: 2
What is &amp;a[10]-&amp;a[4]: 6

[&a2] - &a[1]

&a[2] is same as &(*(a + 2)) (i.e (a + 2)) and &a[1] is same as &(*(a + 1)) (i.e. (a + 1)). So answer will be 1.

&a[2] - &a[1]
(a + 2) - (a + 1)
a + 2 - a - 1
2 - 1
1

Tool

Java

寫這篇文章的時候,最熟悉的程式語言是Ruby,次熟悉的語言是Javascript。目前打算先看Mosh的影片當作起始點,再來依據自己的經驗來了解Java程式語言

使用Java

  • 首先先Google "JDK download",接著進入官網,依照自己電腦版本下載Tool ➡️下載連結
  • 接著下載適合自己的編輯器,我選擇的是intellj編輯器

使用

開Java專案(非空專案),開完以後再選擇Next,再選擇Command Line App即可開啟新專案

package com.codebyhan2;

public class Main {

    public static void main(String[] args) {
	  // write your code here
    }
}

上面為Command Line App預設產生的程式碼。接著簡單打個簡單的程式碼並執行,程式碼和結果如下

package com.codebyhan2;

public class Main {

    public static void main(String[] args) {
	// write your code here
        byte a=1;
        byte b=a++;
        System.out.println("HelloWorld");
        System.out.println("What is a: " + a);
        System.out.println("What is b: " + b);
    }
}
HelloWorld
What is a: 2
What is b: 1

What is under the hood

型別

String

空字串的長度為0

System.out.println("Null string: " + "".length());

Primitive & Reference

觀念蠻像Javascript

Method Overloading

如果因為不同型別就宣告不同的function name的話沒有必要

static int plusMethodInt(int x, int y) {
  return x + y;
}

static double plusMethodDouble(double x, double y) {
  return x + y;
}

public static void main(String[] args) {
  int myNum1 = plusMethodInt(8, 5);
  double myNum2 = plusMethodDouble(4.3, 6.26);
  System.out.println("int: " + myNum1);
  System.out.println("double: " + myNum2);
}

使用同個命名方式就好了

static int plusMethod(int x, int y) {
  return x + y;
}

static double plusMethod(double x, double y) {
  return x + y;
}

public static void main(String[] args) {
  int myNum1 = plusMethod(8, 5);
  double myNum2 = plusMethod(4.3, 6.26);
  System.out.println("int: " + myNum1);
  System.out.println("double: " + myNum2);
}

包含object overloading的完整程式碼如下

package com.codebyhan2;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
    // Overloaded sum().
    // This sum takes two int parameters
    public int sum(int x, int y) {
        return (x + y);
    }

    // Overloaded sum().
    // This sum takes three int parameters
    public int sum(int x, int y, int z) {
        return (x + y + z);
    }

    // Overloaded sum().
    // This sum takes two double parameters
    public double sum(double x, double y) {
        return (x + y);
    }

    public static void main(String[] args) {
        /* initialize the value */
        Main m = new Main();
        System.out.println(m.sum(10, 20));
    }
}

下列為Java內建overloading

Casting

Casting也為Type Conversion

Common Usage in Math

The common use case in Java is min, max, square, random...

Interactive command

下列輸入名字、並且輸出原本輸入的名字

package com.codebyhan2;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Name:");
        String name = scanner.nextLine().trim();
        System.out.println("You are " + name);
    }
}
Name:
HanTing
You are HanTing

快捷鍵

  • sout + tab 產生System.out.println()

進度

日期 進度
2/22 1:17:00

時間複雜度

下列為常見的時間複雜度,以及其常見的使用情境

  1. O(1):陣列讀取
  2. O(n):簡易搜尋
  3. O(log n):二分搜尋(終極密碼)
  4. O(nlogn):合併排序
  5. O(n²):選擇排序
  6. O(2^n):費波那契數列

Thread

相關的講解在這裡

for loop

以下為Java for Loop寫法連結

for (type variableName : arrayName) {
  // code block to be executed
}

Map

Map為鍵值成對的資料型態

Set

HashSet

TreeSet

SortedSet

import java.util.SortedSet; 
import java.util.TreeSet; 

public class HelloWorld{
     public static void main(String []args){
        int[] a = {1, 2, 6};
        a[0] = 1;
        // Create a TreeSet and inserting elements 
        SortedSet<Integer> s = new TreeSet<>(); 
  
        // Adding Element to SortedSet 
        s.add(1); 
        s.add(5); 
        s.add(2); 
        s.add(3); 
        s.add(9); 
  
        // Returning the lowest element from set 
        System.out.print("Lowest element in set is : " + s + "\n");
                         
        System.out.println("Hello World " + a[0]);
        System.out.println("Hello World");
     }
}
Lowest element in set is : [1, 2, 3, 5, 9]
Hello World 1
Hello World

TreeSet

這裡改成HashSet也可以,那HashSet、TreeSet最大的差別在哪裡?答案是會遞升排列

In order to add an element to the TreeSet, we can use the add() method. However, the insertion order is not retained in the TreeSet. Internally, for every element, the values are compared and sorted in ascending order. We need to keep a note that duplicate elements are not allowed and all the duplicate elements are ignored. And also, Null values are not accepted by the TreeSet.

import java.util.SortedSet; 
import java.util.TreeSet; 
import java.util.Set;

public class HelloWorld{
     public static void main(String []args){
        int[] a = {1, 2, 6};
        a[0] = 1;
        
        Set<String> ts1 = new TreeSet<>();
 
        // Elements are added using add() method
        ts1.add("A");
        ts1.add("B");
        ts1.add("C");
 
        // Duplicates will not get insert
        ts1.add("C");
 
        // Elements get stored in default natural
        // Sorting Order(Ascending)
        System.out.println(ts1);
     }
}

// [A, B, C]

郵局考試

郵局的題目很大的機會來自Java,以下列出幾個經典題目

  • 請以 JAVA 語言設計一程式,該程式在使用者輸入一整數後,可以計算判斷其是否為質數,n 若為質數則輸出"n 為質數!!";n 若不是質數除了輸出他不是質數的訊息外,也要列舉 一可以整除 n 的整數。程式判斷該整數是否為質數的方法,須依如下說明的方法進行,且程 式一定要使用迴圈指令。【20 分】 說明:假設使用者輸入值為 n,判斷 n 是否可以被介於 2 到 n/2 之間的所有整數整除, 如果都無法整除 n,則判斷 n 為質數(prime number)

    • 質數(prime number)
    • 最大公因數(英語:highest common factor,hcf)

    下列為判斷是否為質數的作法

    public class Main {
    
      public static void main(String[] args) {
    
        int num = 33, i = 2;
        boolean flag = false;
        while (i <= num / 2) {
          // condition for nonprime number
          if (num % i == 0) {
            flag = true;
            break;
          }
    
          ++i;
        }
    
        if (!flag)
          System.out.println(num + " is a prime number.");
        else
          System.out.println(num + " is not a prime number.");
      }
    }
    

    公因數的作法

    public class Main {
    
      public static void main(String[] args) {
    
        // positive number
        int number = 60;
    
        System.out.print("Factors of " + number + " are: ");
    
        // loop runs from 1 to 60
        for (int i = 1; i <= number; ++i) {
    
          // if number is divided by i
          // i is the factor
          if (number % i == 0) {
            System.out.print(i + " ");
          }
        }
      }
    }
    
  • 請以 Java 程式設計副程式 fac1 與 fac2 如後並符合下列需求(要寫完整程式,否則不予 計分):【25 分】 持續輸入一整數 N,直到 N 為 999 則停止,請分別使用遞迴技巧設計 fac1 及迴圈技巧 設計 fac2,它們均可計算 N!的值回傳

Algorithm

郵局會考演算法,因此需要事前去Leetcode或者Heckerrank查看會考的題目,以下內容下列為在Leetcode看到的演算法

Two Sum

使用下列的例子更熟悉Java的語法

package com.codebyhan2;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
    public int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < numbers.length; i++) {
            if (map.containsKey(target - numbers[i])) {
                result[1] = i;
                result[0] = map.get(target - numbers[i]);
                return result;
            }
            map.put(numbers[i], i);
        }
        return result;
    }

    public static void main(String[] args) {
        /* initialize the value */
        Main m = new Main();
        System.out.println(m.sum(10, 20));

        int[] result = new int[2];
        result = m.twoSum(new int[]{1, 2, 3, 6, 10}, 16);
        System.out.println("What is the result: " + Arrays.toString(result));
    }
}
30
What is the result: [3, 4]

Reverse String

下列為實現反轉數字的作法

public class Solution {
    public int reverse(int x) {
        long result =0;
        while(x != 0)
        {
            result = (result*10) + (x%10);
            if(result > Integer.MAX_VALUE) return 0;
            if(result < Integer.MIN_VALUE) return 0;
            x = x/10;
        }
        return (int)result;
        
        
    }
}

有人提供更佳的解法,將負數轉正以後用純數字去解析會更快

public int reverse(int x) {
  	if (x == Integer.MIN_VALUE)
  		return 0;
  	boolean minus = false;
  	if (x < 0){
  		x = Math.abs(x);
  		minus = true;
  	}
    long temp = 0;
    while(x != 0){
    	temp *= 10;
    	if (temp > Integer.MAX_VALUE || temp < Integer.MIN_VALUE)
    		return 0;
    	temp +=  x%10;
    	x /= 10;
    }
    if (minus)
    	return (int)(-temp);
    return (int)temp;
}

Excel Sheet Column Number

public class Solution {
    public int titleToNumber(String s) {
        if (s == null) return -1;
        int sum = 0;
        // for each loop so we don't need to mess with index values.
        for (char c : s.toUpperCase().toCharArray()) {
            sum *= 26;
            sum += c - 'A' + 1;
        }
        return sum;
    }
}

Fibonacci

Solution 1: Iterative

Time complexity: O(n) Space complexity: O(1)

class Solution 
{
    public int fib(int N)
    {
        if(N <= 1)
            return N;
        
		int a = 0, b = 1;
		
		while(N-- > 1) {
			int sum = a + b;
			a = b;
			b = sum;
		}
        return b;
    }
}

Solution 2: Recursive

Time complexity: O(2^n)- since T(n) = T(n-1) + T(n-2)is an exponential time Space complexity: O(n) - space for recursive function call stack

class Solution 
{
    public int fib(int N)
    {
        if(N <= 1)
            return N;
        else
            return fib(N - 1) + fib(N - 2);
    }
}

and there is an one-liner, which use the ternary operator

class Solution 
{
    public int fib(int N) {
      return (N <= 1) ? N : fib(N - 1) + fib(N - 2);
    }
}

Solution 3: Dynamic Programming - Top Down Approach

Time complexity: O(n) Space complexity: O(n)

class Solution 
{
    int[] fib_cache = new int[31];
	
	public int fib(int N)
    {
        if(N <= 1)
            return N;
        else if(fib_cache[N] != 0)
            return fib_cache[N];
		    else 
            return fib_cache[N] = fib(N - 1) + fib(N - 2);
    }
}

Solution 4: Dynamic Programming - Bottom Up Approach

Time complexity: O(n) Space complexity: O(n)

class Solution 
{
    public int fib(int N)
    {
        if(N <= 1)
            return N;

		    int[] fib_cache = new int[N + 1];
		    fib_cache[1] = 1;
    
		    for(int i = 2; i <= N; i++)
		    {
		    	fib_cache[i] = fib_cache[i - 1] + fib_cache[i - 2];
		    }
		    return fib_cache[N];
    }
}

網友回覆的類似題目

Longest Substring Without Repeating Characters

Given a string s, find the length of the longest substring without repeating characters.

Example 1:

Input: s = &quot;abcabcbb&quot;
Output: 3
Explanation: The answer is &quot;abc&quot;, with the length of 3.

Example 2:

Input: s = &quot;bbbbb&quot;
Output: 1
Explanation: The answer is &quot;b&quot;, with the length of 1.

Example 3:

Input: s = &quot;pwwkew&quot;
Output: 3
Explanation: The answer is &quot;wke&quot;, with the length of 3.
Notice that the answer must be a substring, &quot;pwke&quot; is a subsequence and not a substring.

And the answer is

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s.length()==0) return 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max=0;
        for (int i=0, j=0; i<s.length(); ++i){
            if (map.containsKey(s.charAt(i))){
                j = Math.max(j,map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i),i);
            max = Math.max(max,i-j+1);
        }
        return max;
    }
}

參考資料

© 2024 WOOTHINK. All Rights Reserved.
Site MapTerms and ConditionsPrivacy PolicyCookie Policy