상세 컨텐츠

본문 제목

Array and string - Introduction to 2D Array from Java to Go

Go/Leet Code

by Gopythor 2022. 3. 27. 04:37

본문

728x90
반응형

Code

Java

// "static void main" must be defined in a public class.
public class Main {
    private static void printArray(int[][] a) {
        for (int i = 0; i < a.length; ++i) {
            System.out.println(a[i]);
        }
        for (int i = 0; i < a.length; ++i) {
            for (int j = 0; a[i] != null && j < a[i].length; ++j) {
                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
        System.out.println("Example I:");
        int[][] a = new int[2][5];
        printArray(a);
        System.out.println("Example II:");
        int[][] b = new int[2][];
        printArray(b);
        System.out.println("Example III:");
        b[0] = new int[3];
        b[1] = new int[5];
        printArray(b);
    }
}

Go

func printArrayA(a [2][5]int) { // When array is implemented, function also needs to get size of array.
    for i := 0; i < len(a); i++ {
        fmt.Println(a[i])
    }
    for i := 0; i < len(a); i++ {
        for j := 0; j < len(a[i]); j++ { // array cannot have nil value
            fmt.Print(a[i][j], " ")
        }
        fmt.Println()
    }
}

func printArrayB(a [][]int) { // When array is implemented, function also needs to get size of array.
    for i := 0; i < len(a); i++ {
        fmt.Println(a[i])
    }
    for i := 0; i < len(a); i++ {
        for j := 0; a[i] != nil && j < len(a[i]); j++ { // array cannot have nil value
            fmt.Print(a[i][j], " ")
        }
        fmt.Println()
    }
}
func main() {
    fmt.Println("Example I:")
    a := [2][5]int{}
    printArrayA(a)
    fmt.Println("Example II:")
    b := make([][]int, 2)
    printArrayB(b)
    fmt.Println("Example III:")
    b[0] = make([]int, 3)
    b[1] = make([]int, 5)
    printArrayB(b)
}

Result

Example I:
[0 0 0 0 0]
[0 0 0 0 0]
0 0 0 0 0 
0 0 0 0 0 
Example II:
[]
[]


Example III:
[0 0 0]
[0 0 0 0 0]
0 0 0 
0 0 0 0 0 

https://go.dev/play/p/N0kXA7tJxW0

  • In Leetcode sample was not working well.
  • I am not sure the result is same above like that.
  • slice can have dynamic demension sized slice.

728x90
반응형

관련글 더보기

댓글 영역