Move Element by Offset
Write a function moveab(x, A, B, option) that moves the element at index A in array x by B positions.
- Positive B moves the element to the right
- Negative B moves the element to the left
- The relative order of all other elements must be preserved
- Use 1-based indexing
Philosophy:
When moving elements in an array, a special case occurs when end elements can either move to the next index in the array or move by its relative postion between other elements. When the end element is moved by one space, it can then wrap and move to the first index in the array, however, the order of the elements has not changed. With the option of ring behavior, end elements will wrap but also move as intended by moving to the second index instead of the first. This is also maintained for reverse move options.
Default behavior:
- Remove the element at index A and reinsert it B positions away in the array
- If the shift goes past either end, wrap around to the other side
- Large values of B must wrap correctly (e.g., use modulo with the array length)
- Default wrapping acts as follows: x = [1 2 3]; moveab(x, 3, 1) → [3 1 2]
Examples:
- x = [1 2 3 4 5 6 7 8]; moveab(x, 3, 3) → [1 2 4 5 6 3 7 8]
- x = [1 2 3]; moveab(x, 3, 1) → [3 1 2]
'ring' option for wrapping:
- The default simply wrapping simply shifts the last element to the first, but when the array to treated as a ring, the element was never moved by 1 space, the order was never changed. The 'ring' option moves the last element by 1 space in a ring, resulting in the following behavior: x = [1 2 3]; moveab(x, 3, 1,'ring') → [1 3 2]
- Moving backwards in 'ring' mode: x = [1 2 3]; moveab(x, 1, -1,'ring') → [3 1 2].
- Moving backwards in default mode: x = [1 2 3]; moveab(x, 1, -1) → [2 3 1].
Examples (comparison of ring and default mode):
- x = [1 2 3]; moveab(x, 3, 1) → [3 1 2]
- x = [1 2 3]; moveab(x, 3, 1, 'ring') → [1 3 2]
- x = [1 2 3]; moveab(x, 1, -1) → [2 1 3]
- x = [1 2 3]; moveab(x, 1, -1, 'ring') → [2 1 3]
- x = 1:10; moveab(x, 10, 1) → [10 1 2 3 4 5 6 7 8 9]
- x = 1:10; moveab(x, 10, 1, 'ring') → [1 10 2 3 4 5 6 7 8 9]
- x = 1:10; moveab(x, 1, -1) → [2 3 4 5 6 7 8 9 10 1]
- x = 1:10; moveab(x, 1, -1, 'ring') → [2 3 4 5 6 7 8 9 1 10]
Solution Stats
Solution Comments
Show comments
Loading...
Problem Recent Solvers3
Suggested Problems
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!