帮助试图了解在圆阵模操作 [英] Help trying to understand modulo operation in circular array

查看:95
本文介绍了帮助试图了解在圆阵模操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题,想弄清楚是如何被计算模运算。
我建立了一个队列,所以我有一个圆阵。
我想不通这个模运算如何工作的。

i have a small issue trying to figure out how a modulo operation is being calculated. I am building up a queue, so i have a circular array. i cannot figure out how this modulo operation works.

由于问:5个元素长度的字符数组,
马克斯不断给数组的最大长度5
难得的是一个int它重新presents在阵问:第一个可用的点

Given q: an array of Character of 5 elements length, The MAX constant gives the max length of the array "5" rare is an int which represents the first available spot in the array q

    public void enqueue(Character c)throws FullQueueException{

    if(size()== MAX -1){ //if only 1 place left, is full, throw exc 

        throw new FullQueueException("Queue is full");
    }
    q[rare]=c;  
    rare=(rare+1)%MAX;
}

现在,假定罕见的第一空点为三,什么是难得的价值将是该方法完成后?
这就是我不明白,稀有=(罕见+ 1)%MAX指罕见= 4%,5这给稀有= 0,8。

Now, supposing that the rare "first empty spot" is three, what is the rare value going to be after the method has finished? this is what i dont get, rare=(rare+1)%MAX means rare=4%5 which gives rare=0,8.

同样的方法大小:

public int size() {

    return (MAX - front + rear) % MAX;
}

由于,前面,从而重新$ P $ int变量psents的第一个元素数组中
假设前面是1和稀有4,所以有数组中3个元素,所以尺寸为(5-1 4)%5是8%5赋予1.6,而实际大小是3
任何建议?这可能是更多的数学那么Java,但可能一些你之前在同样的疑问来了。
谢谢!

Given, front, an int variable which represents the first element in the array Suppose front is 1 and rare 4, so there are 3 elements in the array, so size is (5-1+4)%5 which is 8%5 which gives 1.6, while the actual size is 3 Any suggestion? this might be more math then java but probably some of you came across the same doubt before. Thank you!

推荐答案

我觉得你有点conofused为模操作做了什么。它提供了分割后的整数余数。所以从你的例子。

I think you're a bit conofused as to what the modulo operation does. It gives the integer remainder after a division. So from your example.

4%5 = 4(因为4/5为0,与4的余数)

4 % 5 = 4 (because 4/5 is 0, with a remainder of 4)

8%5 = 3(因为8/​​5是1与3余数)

8 % 5 = 3 (because 8/5 is 1 with a remainder of 3)

在没有看到您的实现的其余部分,它有点难以进一步解释为什么使用模的,但它看起来像它基本上是用来确保您的圆阵环绕。也就是说,当你打的数组的结尾(比如指数7,用最大尺寸为8的数组,你会想下一个值将是第一要素,这将是8%,8或0)。

Without seeing the rest of your implementation, its a bit difficult to explain further why modulo is being used, but it looks like its basically being used to ensure that your circular array wraps around. i.e. when you hit the end of the array (say index 7, of an array with MAX size 8, the next value you would want would be the first element, which would be 8%8 or 0).

这篇关于帮助试图了解在圆阵模操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆