如何移动一个数组元素环绕?
我正在尝试编写一个迭代数组的函数,当它找到某种类型的值时,它会将其向右移动指定数量的位置。
我知道如何通过临时存储值、将右侧元素移至左侧然后将临时值写入正确的位置来移动元素。
我遇到的问题是,如果某个字符出现在数组末尾附近,我需要它环绕并从数组的开头继续,所以是循环的。
因此,数组移位,例如,大写字母向右 3 个位置,特殊字符向左 1 个位置:
{ M, y, N, a, m, e, P} becomes...
{ y, M, P, a, N, m, e}
要将 8 的元素向右移动 3 个位置,我在下面有,但这仅在 8 出现早于 3 个元素时才有效从数组末尾开始,不会环绕。
输入数组:
{0, 1, 2, 3, 4, 5, 6, 7, **8**, 9}
期望输出:
{0, **8**, 1, 2, 3, 4, 5, 6, 7, 9}
int[] array = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int i = array.Length - 1; i >= 0; i--)
{
if (array[i] == 8)
{
int temp = array[i];
int j = 0;
for (j = i; j < i + 3; j++)
{
array[j] = array[j + 1];
}
array[j] = temp;
}
}
I am trying to write a function which iterates through an array and when it finds a certain type of value it will shift it to the right a defined number of places.
I know how to shift elements by temporarily storing a value, shifting the right side elements to the left and then writing the temporary value in the correct place.
The bit I am struggling with is if the certain character appears near the end of the array I need it to wrap around and continue from the start of the array, so is circular.
So an array shifting, for example, capital letters to the right 3 places and special characters to the left 1 place:
{ M, y, N, a, m, e, P} becomes...
{ y, M, P, a, N, m, e}
To shift an element of 8 to the right 3 places I have below, but this only works if 8 appears earlier than 3 elements from the end of the array and will not wrap around.
input array:
{0, 1, 2, 3, 4, 5, 6, 7, **8**, 9}
desired output:
{0, **8**, 1, 2, 3, 4, 5, 6, 7, 9}
int[] array = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int i = array.Length - 1; i >= 0; i--)
{
if (array[i] == 8)
{
int temp = array[i];
int j = 0;
for (j = i; j < i + 3; j++)
{
array[j] = array[j + 1];
}
array[j] = temp;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需使用模算术,这样在移位时就不会写入索引
j
处的元素,而是写入索引j % array.Length
处的元素。因此:我排除了错误检查。
Just use modulo arithmetic so that instead of writing to the element at index
j
as you shift, instead write to the element at indexj % array.Length
. Thusly:I have excluded error checking.
您可以使用 if 语句来完成此操作,检查数组末尾之前是否有足够的空间,如果没有,您还必须计算在数组开头移动多少步。
我还认为,您可以通过在进行移位时计算以数组长度为模的位置来完成此操作,我目前无法尝试,但我头脑中的逻辑表明它应该有效。
You can do it with an if statement, check if there is room enough before the end of the array and if it isn't you have to calculate how many steps to shift in the beginning of the array aswell.
I also think that you can do it by calculating the positions modulo the length of the array when you do the shifting, I can't try it at the moment but the logic in my head says that it should work.