2 x 2 矩阵的高效索引方法
如果我在 2 x 2 矩阵中填充 1 到 4 的数字,则有 16 种可能的组合。我想要做的是将值存储在与每个矩阵对应的大小为 24 的数组中。所以给定一个 2 x 2 矩阵,我想要一个有效的索引方法来直接索引到数组中。(我不想比较 16 个位置中每个位置的所有 4 个元素)。类似于位向量的东西?但无法弄清楚如何? 我想要一个 4 x 4 矩阵,也填充 1 到 9
If I fill numbers from 1 to 4 in a 2 by 2 matrix, there are 16 possible combinations. What I want to do is store values in an array of size 24 corresponding to each matrix. So given a
2 by 2 matrix, I want a efficient indexing method to index into the array directly.( I dont want comparing all 4 elements for each of 16 positions). Something similar to bit vector ? but not able to figure out how?
I want it for a 4 by 4 matrix also filling from 1 to 9
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
澄清一下:您正在寻找 2x2 矩阵的有效哈希函数。您想使用哈希函数的结果来比较矩阵以查看它们是否相同。
首先,假设您实际上想要数字 0 到 3,而不是 1 到 4 - 这使得它更容易,并且更计算机科学。接下来,16 不对。数字 0-3 有 24 种可能的排列。使用四个字母的字母表有 4^4 = 256 个可能的长度为 4 的字符串(您可以重复已使用的数字)。
任何一个都可以轻松编码为单个字节。让前 2 位代表 (0,0) 位置,接下来的 2 位代表 (0,1),依此类推。然后,要散列 2x2 矩阵,只需执行以下操作:
随机示例:二进制中的数字 54 是 00110110,它表示一个矩阵,如下所示:
to clarify: you're looking for an efficient hash function for 2x2 matrices. you want to use the results of the hash function to compare matrices to see if they're the same.
first, lets assume you actually want the numbers 0 to 3 instead of 1 to 4 - this makes it easier, and is more computer-sciency. Next, 16 is not right. there are 24 possible permutations of the numbers 0-3. There are 4^4 = 256 possible strings of length 4 that use a four-letter alphabet (you can repeat already-used numbers).
either one is trivial to encode into a single byte. Let the first 2 bits represent the (0,0) position, the next 2 bits represent (0,1), and so forth. Than, to hash your 2x2 matrix, simply do:
random example: the number 54 in binary is 00110110 which represents a matrix like:
当您需要效率时,有时代码清晰度就被抛之脑后了:)
首先您需要确定您想要效率 - 您有分析信息以确保简单的比较代码对您来说效率太低?
您可以简单地将其视为相同大小的字节数组。
memcmp
进行任意内存的比较:诸如以下的数据结构:
存储方式相同:
可以动态分配为:
我不是建议您动态分配它们,我正在说明字节是如何分配的在你的原始类型中实际上是在内存中布局的。
因此,以下内容是有效的:
When you need efficiency, sometimes code clarity goes out the window :)
First you need to be sure you want efficiency - you have profiling info to be sure that the simple comparison code is too inefficient for you?
You can simply treat it as an array of bytes of the same size.
memcmp
does comparisons of arbitary memory:A data structure such as:
is stored the same as:
which could be dynamically allocated as:
I'm not suggesting you dynamically allocate them, I'm illustrating how the bytes in your original type is actually layed out in memory.
Therefore, the following is valid: