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

ex4.4: Incorrect solution #27

Closed
sherif-fanous opened this issue Mar 30, 2020 · 0 comments
Closed

ex4.4: Incorrect solution #27

sherif-fanous opened this issue Mar 30, 2020 · 0 comments

Comments

@sherif-fanous
Copy link

sherif-fanous commented Mar 30, 2020

The exercise requested to write a version of rotate that operates in a single pass. The answer provided rotates a slice by one position to the left, so while your code runs correctly it's not the right answer to the exercise.

Generic solution that performs in place rotation

// Rotates in place the slice s to the left by n steps
func rotateLeft(s []int, n int) {
	if len(s) == 0 || n%len(s) == 0 {
		return
	}

	n = n % len(s)

	ss := make([]int, len(s))

	copy(ss, s)
	copy(s, ss[n:])
	copy(s[len(s)-n:], ss[0:n])
}

Generic solution that doesn't perform in place rotation.

// Rotates the slice s to the left by n steps
func rotateLeft(s []int, n int) []int {
	if len(s) == 0 || n%len(s) == 0 {
		return s
	}

	n = n % len(s)
	s = append(s[n:], s[0:n]...)

	return s
}
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

1 participant