Java BigInteger Calculate getNextLexicographicalPermutation(BigInteger v)

Here you can find the source of getNextLexicographicalPermutation(BigInteger v)

Description

It computes lexicographically the next permutation of the bits in the given number.

License

Open Source License

Parameter

Parameter Description
v Source number

Return

Bit-twiddled number

Declaration

public static BigInteger getNextLexicographicalPermutation(BigInteger v) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.math.BigInteger;

public class Main {
    /**/*  ww w .j  av a 2  s.  c  o m*/
     * It computes lexicographically the next permutation of the bits in the given number.
     *
     * For example 3 = 0b000011<br>
     * - next: 0b000101 (5)<br>
     * - next: 0b000110 (6)<br>
     * - next: 0b001001 (9)<br>
     * - next: 0b001010 (10)<br>
     * - next: 0b001100 (12)<br>
     * - next: 0b010001 (17)<br>
     *
     * Copied from <a href="http://graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation">Bit Twiddling Hacks: Compute the lexicographically next bit permutation</a>
     * @param v    Source number
     * @return  Bit-twiddled number
     */
    public static long getNextLexicographicalPermutation(long v) {
        long t = (v | (v - 1)) + 1;
        return t | ((((t & -t) / (v & -v)) >> 1) - 1);
    }

    /**
     * It computes lexicographically the next permutation of the bits in the given number.
     *
     * For example 3 = 0b000011<br>
     * - next: 0b000101 (5)<br>
     * - next: 0b000110 (6)<br>
     * - next: 0b001001 (9)<br>
     * - next: 0b001010 (10)<br>
     * - next: 0b001100 (12)<br>
     * - next: 0b010001 (17)<br>
     *
     * Copied from <a href="http://graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation">Bit Twiddling Hacks: Compute the lexicographically next bit permutation</a>
     * @param v    Source number
     * @return  Bit-twiddled number
     */
    public static BigInteger getNextLexicographicalPermutation(BigInteger v) {
        BigInteger t = v.or(v.subtract(BigInteger.ONE)).add(BigInteger.ONE);
        return t.and(t.negate()).divide(v.and(v.negate())).shiftRight(1)
                .subtract(BigInteger.ONE).or(t);
    }
}

Related

  1. getMetaDataMaskForLPortDispatcher(BigInteger metadataMaskForServiceIndex, BigInteger metadataMaskForLPortTag, BigInteger metadataMaskForService)
  2. getN(BigInteger p, BigInteger q)
  3. getNafWeight(BigInteger k)
  4. getNatRouterIdFromMetadata(BigInteger metadata)
  5. getNetAddress(BigInteger ip, BigInteger netmask)
  6. getNRightmostBits(final BigInteger in, final int n)
  7. getNumbersBetweenRange(BigInteger minValue, BigInteger maxValue)
  8. getPrivateKey(BigInteger ran, BigInteger publicKey)
  9. getPrivateKeyBytes(BigInteger privateKey)