Skip to content

I would like a simpler way to create a SliceArg that matches an arbitrary Dimension #892

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

Closed
insideoutclub opened this issue Jan 12, 2021 · 3 comments

Comments

@insideoutclub
Copy link
Contributor

The code below is my solution for Advent Of Code 2020 Day 17. The problem involves running Conway's Game of Life in both 3 and 4 dimensions. I want to use slice_mut to create a mutable slice for Dimension D. The only way I could figure out how to do it was to convert the array to IxDyn using into_dimensionality, slice the array using a Vec I created, and then convert the array back to dimension D.

To solve a similar problem, I was able to call raw_dim on my existing array, and then iterate over it and modify it. My initial proposal would be to have a similar method (raw_slice?) that would return a SliceArg that I could then iterate over and modify in place.

https://play.rust-lang.org/?version=stable&mode=release&edition=2018&gist=4a028d474bec27d8f32f938ece81b0e4

@jturner314
Copy link
Member

I think the simplest way to implement the slicing in the example would be like this:

let mut v = x.view_mut();
field
    .axes()
    .for_each(|ax| v.slice_axis_inplace(ax.axis(), Slice::from(2..2 + ax.len())));
v.assign(field);

This doesn't require x to be dynamic-dimensional.

Usually, the simplest way to perform slicing in a function which is generic over dimensionality is to use the methods which slice individual axes, like .slice_axis_inplace() and .collapse_axis(). I've created #912 to improve the documentation in this area.

@insideoutclub
Copy link
Contributor Author

That's a lovely solution. Thank-you.

@jturner314
Copy link
Member

When the next version of ndarray is released, the slicing in the example will be able to be implemented like this:

x.slice_each_axis_mut(|ax| Slice::from(2..2 + field.len_of(ax.axis()))).assign(field);

(See PR #913.)

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

Successfully merging a pull request may close this issue.

3 participants