1
$\begingroup$

I've tried making a HashMap in Java that used arrays of integers as keys, however this didn't quite work out the way I wanted. Therefore I want to try a different approach. What would be a simple and fast (to compute) injection of the set $\{(x_1, x_2, ..., x_7)\in\mathbb{N}^7 | x_1+x_2+...+x_7=20\}$ into $\mathbb{N}$?

  • 0
    The obvious one is the value of the string $x_1x_2\cdots x_7$ viewed in base $21$. But since that requires a lot of storage (almost two billion values), would that actually help you?2017-02-03
  • 0
    $\sum_i {p_i}^{x_i}$ with different primes $p_1\dots p_7$ would do, but would probably be also too expensive to calculate and provide too sparse set of resulting values...2017-02-03

1 Answers 1

1

I'm interpreting this situation as you needing a way to store elements of your subset of $\Bbb N^7$ in a HashMap, and not necessarily needing an injection into $\Bbb N$ (unless you have a requirement that your keys need to be positive integers).

I recommend using a HashMap where the keys are strings of the form "$x_1\_x_2\_x_3\_x_4\_x_5\_x_6\_x_7$".

For example, $(1,1,1,1,1,1,14)$ is in your set. Its corresponding key is the string: $$``1\_1\_1\_1\_1\_1\_14"$$

Note that the underscores are required. This is because without them, some elements would have the same key. For example, $(1,11,1,1,1,1,4)$ and $(11,1,1,1,1,1,4)$ would have the same key if not using underscores.

As far as being easy to compute, it's a simple loop as long as you have access to the actual entries of the $7$-tuple. Of course it could take a while if you need to store the entire set. But if you're storing the entire set then I think most or all ways of doing this will be rather time consuming. And memory consuming.

// Untested code snippet.
// The parameter "element" represents one element of the set of 7-tuples.
public static String makeKey(ArrayList element) {
    StringBuilder key = new StringBuilder();

    for (int i = 0; i < 7; i++)
        key.append(arr.get(i).toString() + (i < 6 ? "_" : ""));

    return key.toString();
}
  • 0
    Such a simple solution and I did not even see it! Thank you, this is indeed a much easier way to solve my problem.2017-02-03
  • 0
    @Dasherman, no worries, glad to help!2017-02-03