#Question on implementation of code

10 messages · Page 1 of 1 (latest)

waxen grail
#

I'm currently working on a coding exercise and came across two code snippets. However, I'm having trouble understanding the differences between them. I was wondering if someone could kindly help me out and provide some insights.

Here are the two code snippets:

Code Snippet 1:

public void reverse() {
    if (numberOfChars > 1) {
        char[] a = new char[numberOfChars];
        int i = 0;
        Node n = first;
        while (n != null) {
            a[i++] = n.ch;
            n = n.next;
        }
        n = first;
        i = a.length - 1;
        while (n != null) {
            n.ch = a[i--];
            n = n.next;
        }
    }
}

Code Snippet 2:

public void reverse(char[] chars) {
    int i = 0;
    int j = chars.length - 1;
    while (i < chars.length && j >= 0) {
        chars[i++] = chars[j--];
    }
}

In the second snippet, I wrote it like it's a method to reverse the order of characters in an array. It uses a two-pointer approach to swap elements from both ends of the array. The first snippet seems to have the intention of reversing something as well, given its method name. I would really appreciate it if someone could help me understand the differences between these two snippets. Are they meant to achieve the same result?

real havenBOT
#

This post has been reserved for your question.

Hey @waxen grail! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

willow rune
#

the first one is copying the contents over to an array reversed then copying them back out in the right order
seems to be a method for a linked structure, considering the use of Node

#

the second snippet seems wrong to me though, it's assigning in-place so it overwrites data before it can swap it

#

you'd want to actually swap the data rather than move 1 at a time (unless you have external storage like in the first case)

waxen grail
#

like this?

public static void reverseArray(int[] arr) {
        int start = 0;
        int end = arr.length - 1;

        while (start < end) {
            // Swap elements at start and end indices
            int temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;

            // Move indices towards each other
            start++;
            end--;
        }
    }```
willow rune
#

sure, but you don't really need to store both indices

#

i'd write it more like this

void reverseArray(int[] arr) {
  for (int i = 0; i < arr.length / 2; i++) {
    int j = arr.length - i - 1;
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  }
}