상세 컨텐츠

본문 제목

Array and String - Introduction to Array from java to Go

Go/Leet Code

by Gopythor 2022. 3. 22. 16:47

본문

728x90
반응형

Operations in Array

https://leetcode.com/explore/learn/card/array-and-string/201/introduction-to-array/1143/

Java

// "static void main" must be defined in a public class.
public class Main {
    public static void main(String[] args) {
        // 1. Initialize
        int[] a0 = new int[5];
        int[] a1 = {1, 2, 3};
        // 2. Get Length
        System.out.println("The size of a1 is: " + a1.length);
        // 3. Access Element
        System.out.println("The first element is: " + a1[0]);
        // 4. Iterate all Elements
        System.out.print("[Version 1] The contents of a1 are:");
        for (int i = 0; i < a1.length; ++i) {
            System.out.print(" " + a1[i]);
        }
        System.out.println();
        System.out.print("[Version 2] The contents of a1 are:");
        for (int item: a1) {
            System.out.print(" " + item);
        }
        System.out.println();
        // 5. Modify Element
        a1[0] = 4;
        // 6. Sort
        Arrays.sort(a1);
    }
}

Go

// Java uses the main method, but Golang uses func main.
func main() {
    // 1. Initialize
    var a0 [5]int
    var a1 = []int{1, 2, 3}
    // 2. Get Length
    fmt.Println("The size of a1 is:", len(a1))
    // 3. Access Element
    fmt.Println("The first element is: ", a1[0])
    // 4. Iterate all Elements
    fmt.Print("[Version 1] The contents of a1 are:")
    for i := 0; i < len(a1); i++ {
        fmt.Print(" ", a1[i])
    }
    fmt.Println(" ")
    fmt.Print("[Version 2] The contents of a1 are:")
    for _, v := range a1 {
        fmt.Print(" ", v)
    }
    fmt.Println(" ")
    // 5. Modify Element
    a1[0] = 4
    // A sort function does not support array, So I changed a1 from array to slice.
    sort.Ints(a1)

    // Check values if arranged or not.
    for _, v := range a1 {
        fmt.Print(" ", v)
    }
    fmt.Println(" ")

    // Go does not allow to use not used variable.
    for _, v := range a0 {
        fmt.Print(" ", v)
    }
}

Result

The size of a1 is: 3
The first element is:  1
[Version 1] The contents of a1 are: 1 2 3
[Version 2] The contents of a1 are: 1 2 3

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

728x90
반응형

관련글 더보기

댓글 영역