Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recipe: Reversing an Array has incorrect algorithm #18

Open
pjbgtnj opened this issue Dec 18, 2019 · 5 comments
Open

Recipe: Reversing an Array has incorrect algorithm #18

pjbgtnj opened this issue Dec 18, 2019 · 5 comments

Comments

@pjbgtnj
Copy link
Contributor

pjbgtnj commented Dec 18, 2019

The last example - reversing an array by making a new copy doesn't work if the length of the array is an old number of elements: I'd suggest adding:

if len(numbers) & 1 == 1 {  // if odd
    halfWay := len(numbers) >> 1 // divide by 2 
    newNumbers[halfWay] = numbers[halfWay]
}

or better yet:

func reverse(numbers []int) []int {
    newNumbers := make([]int, 0, len(numbers))
    for i := len(numbers)-1; i >= 0; i-- {
        newNumbers = append(newNumbers, numbers[i])
    }
    return newNumbers
}
@tammersaleh
Copy link
Member

Thanks @pjbgtnj! Working on a test for this now.

@tammersaleh
Copy link
Member

Hey @pjbgtnj - I think you might be incorrect. The existing tests run this code against an odd number of elements and they pass:

func reverse(numbers []int) []int {
newNumbers := make([]int, len(numbers))
for i, j := 0, len(numbers)-1; i < j; i, j = i+1, j-1 {
newNumbers[i], newNumbers[j] = numbers[j], numbers[i]
}
return newNumbers
}
func main() {
array := []int{1, 2, 3, 4, 5}
fmt.Printf("%v\n", reverse(array))
fmt.Printf("%v\n", array)
}

Could you possibly attempt a PR where you show this code failing?

@pjbgtnj
Copy link
Contributor Author

pjbgtnj commented Dec 18, 2019 via email

@pjbgtnj
Copy link
Contributor Author

pjbgtnj commented Dec 19, 2019

I just ran the test you provided above and the output is incorrect:

[5 4 0 2 1] <<< - The 0 should be a 3
[1 2 3 4 5]

When copying in place the middle most element doesn't need to be swapped but when you copy to a new slice, it does.

@tammersaleh
Copy link
Member

That was right in front of me, and I still didn't see it. Thank you for being persistent :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants