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

bug, array swaping values #61

Closed
kostya opened this issue Dec 21, 2013 · 3 comments
Closed

bug, array swaping values #61

kostya opened this issue Dec 21, 2013 · 3 comments

Comments

@kostya
Copy link
Contributor

kostya commented Dec 21, 2013

./bin/crystal -e 'a = [1,2]; a[0], a[1] = a[1], a[0]; p a'
Syntax error in -:1: Impossible

./bin/crystal -e 'a = [1,2]; t = a[1]; a[1] = a[0]; a[0] = t; p a'
[2, 1]

@asterite
Copy link
Member

I also added Array#swap(index0, index1) that should be faster if you care about performance (if that's your bottleneck). This only does two bounds check. The other way:

a[0], a[1] = a[1], a[0]

gets translated to:

temp1 = a[1]
temp2 = a[0]
a[0] = temp1
a[1] = temp2

so that's four bounds check.

@kostya
Copy link
Contributor Author

kostya commented Dec 22, 2013

thanks, maybe better to call it swap! because it changes array state.

@asterite
Copy link
Member

I don't think it makes sense to clone the array and swap the elements. There's also no "pop!" in Ruby and "pop" modifies self, so...

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