Count bits used in int - java

If you have the binary number 10110 how can I get it to return 5? e.g a number that tells how many bits are used? There are some likewise examples listed below:
101 should return 3
000000011 should return 2
11100 should return 5
101010101 should return 9
How can this be obtained the easiest way in Java? I have come up with the following method but can i be done faster:
public static int getBitLength(int value)
{
if (value == 0)
{
return 0;
}
int l = 1;
if (value >>> 16 > 0) { value >>= 16; l += 16; }
if (value >>> 8 > 0) { value >>= 8; l += 8; }
if (value >>> 4 > 0) { value >>= 4; l += 4; }
if (value >>> 2 > 0) { value >>= 2; l += 2; }
if (value >>> 1 > 0) { value >>= 1; l += 1; }
return l;
}

Easiest?
32 - Integer.numberOfLeadingZeros(value)
If you are looking for algorithms, the implementors of the Java API agree with your divide-and-conquer bitshifting approach:
public static int numberOfLeadingZeros(int i) {
if (i == 0)
return 32;
int n = 1;
if (i >>> 16 == 0) { n += 16; i <<= 16; }
if (i >>> 24 == 0) { n += 8; i <<= 8; }
if (i >>> 28 == 0) { n += 4; i <<= 4; }
if (i >>> 30 == 0) { n += 2; i <<= 2; }
n -= i >>> 31;
return n;
}
Edit: As a reminder to those who trust in the accuracy of floating point calculations, run the following test harness:
public static void main(String[] args) {
for (int i = 0; i < 64; i++) {
long x = 1L << i;
check(x);
check(x-1);
}
}
static void check(long x) {
int correct = 64 - Long.numberOfLeadingZeros(x);
int floated = (int) (1 + Math.floor(Math.log(x) / Math.log(2)));
if (floated != correct) {
System.out.println(Long.toString(x, 16) + " " + correct + " " + floated);
}
}
The first detected deviation is:
ffffffffffff 48 49

Unfortunately there is no Integer.bitLength() method that would give you the answer directly.
An analogous method exists for BigInteger, so you could use that one:
BigInteger.valueOf(value).bitLength()
Constructing the BigInteger object will make it somewhat less efficient, but that will only matter if you do it many millions of times.

You want to compute the base 2 logarithm of the number - specifically: 1 + floor(log2(value))
Java has a Math.log method which uses base e, so you can do:
1 + Math.floor(Math.log(value) / Math.log(2))

Be careful what you ask for. One very fast technique is to do a table lookup:
int bittable [] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, ... };
int numbits (int v)
{
return bittable [v];
}
where bittable contains an entry for every int. Of course that has complications for negative values. A more practical way would be to count the bits in bitfields of the number
int bittable [16] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};
int numbits (int v)
{
int s = 0;
while (v != 0)
{
s += bittable [v & 15];
v >>= 4;
}
return s;
}

You really just want to find the position of the highest bit that is a 1. See this page, under the heading "Finding integer log base 2 of an integer (aka the position of the highest bit set)".

From here, a way to do it with just bitwise-and and addition:
int GetHighestBitPosition(int value) {
if (value == 0) return 0;
int position = 1;
if ((value & 0xFFFF0000) == 0) position += 16;
if ((value & 0xFF00FF00) == 0) position += 8;
if ((value & 0xF0F0F0F0) == 0) position += 4;
if ((value & 0xCCCCCCCC) == 0) position += 2;
if ((value & 0xAAAAAAAA) == 0) position += 1;
return position;
}

Integer.toBinaryString(value).length()

I think the rounded-up log_2 of that number will give you what you need.
Something like:
return (int)(Math.log(value) / Math.log(2)) + 1;

int CountBits(uint value)
{
for (byte i = 32; i > 0; i--)
{
var b = (uint)1 << (i - 1);
if ((value & b) == b)
return i;
}
return 0;
}

If you are looking for the fastest (and without a table, which is certainly faster), this is probably the one:
public static int bitLength(int i) {
int len = 0;
while (i != 0) {
len += (i & 1);
i >>>= 1;
}
return len;
}

Another solution is to use the length() of a BitSet which according to the API
Returns the "logical size" ... the index of
the highest set bit ... plus one.
To use the BitSet you need to create an array. So it is not as simple as starting with a pure int. But you get it out of the JDK box - tested and supported. It would look like this:
public static int bitsCount(int i) {
return BitSet.valueOf(new long[] { i }).length();
}
Applied to the examples in the question:
bitsCount(0b101); // 3
bitsCount(0b000000011); // 2
bitsCount(0b11100); // 5
bitsCount(0b101010101); // 9
When asking for bits the BitSetseems to me to be the appropriate data structure.

Related

Extracting even digits from int

Here is the problem that I am solving.
Write a method evenDigits that accepts an integer parameter n and that
returns the integer formed by removing the odd digits from n. The
following table shows several calls and their expected return values:
Call Valued Returned
evenDigits(8342116); 8426
evenDigits(4109); 40
evenDigits(8); 8
evenDigits(-34512); -42
evenDigits(-163505); -60
evenDigits(3052); 2
evenDigits(7010496); 46
evenDigits(35179); 0
evenDigits(5307); 0
evenDigits(7); 0
If a negative number with even digits other than 0 is passed to the method, the result should also be negative, as shown above when -34512 is passed.
Leading zeros in the result should be ignored and if there are no even digits other than 0 in the number, the method should return 0, as shown in the last three outputs.
I have this so far -
public static int evenDigits(int n) {
    if (n != 0) { 
        int new_x = 0;
int temp = 0;
String subS = "";
    String x_str = Integer.toString(n);
if (x_str.substring(0, 1).equals("-")) {
 temp = Integer.parseInt(x_str.substring(0, 2));
 subS = x_str.substring(2);
} else {
 temp = Integer.parseInt(x_str.substring(0, 1));
 subS = x_str.substring(1);
}
        if (subS.length() != 0) {
             new_x = Integer.parseInt(x_str.substring(1));
        }
        
        if (temp % 2 == 0) {
             return Integer.parseInt((Integer.toString(temp) + evenDigits(new_x)));
        } else {
            return evenDigits(new_x);
        }
    }
return 0;
}
Why do people seem always to want to convert to String to deal with digits? Java has perfectly good arithmetic primitives for handling the job. For example:
public static int evenDigits(int n) {
int rev = 0;
int digitCount = 0;
// handle negative arguments
if (n < 0) return -evenDigits(-n);
// Extract the even digits to variable rev
while (n != 0) {
if (n % 2 == 0) {
rev = rev * 10 + n % 10;
digitCount += 1;
}
n /= 10;
}
// The digits were extracted in reverse order; reverse them again
while (digitCount > 0) {
n = n * 10 + rev % 10;
rev /= 10;
digitCount -= 1;
}
// The result is in n
return n;
}
Although it makes no difference for a simple academic exercise such as this one, handling the job via arithmetic alone can be expected to perform better than anything involving converting to String.
It's often easier to start with a recursive solution and then work you way back to iterative (if you must):
public static int evenDigits(int n) {
if (n < 0) {
return -evenDigits(-n);
} else if (n == 0) {
return 0;
} else if (n % 2 == 1) {
return evenDigits(n / 10);
} else {
return 10 * evenDigits(n / 10) + (n % 10);
}
}
int n = 8342116;
StringBuilder sb = new StringBuilder();
Integer.toString(n).chars()
.filter(x -> x % 2 == 0)
.mapToObj(i -> (char) i)
.forEachOrdered(sb::append);
int result = Integer.valueOf(sb.toString());
System.out.println(result); // 8426
public int evenDigits(int n) {
int r = 0;
boolean neg = false;
String evenDigits = "";
if (n < 0) { neg = true; n = abs(n); }
// keep dividing n until n = 0
while (n > 0) {
r = n % 10;
n = n / 10; // int division
if (r % 2 == 0) { evenDigits = Integer.toString(r) + evenDigits; }
}
int result = Integer.parseInt(evenDigits);
if (neg) { result -= 2 * result; }
return result;
}
This is more or less a pseudo code, but I think you get my idea. I have used this method for the same problem before.
A layman's solution that's based on Strings:
public static int evenDigits(int n) {
StringBuilder evenDigitsBuffer = new StringBuilder();
for (char digitChar : String.valueOf(n).toCharArray()) {
int digit = Character.getNumericValue(digitChar);
if (digit % 2 == 0) {
evenDigitsBuffer.append(digit);
}
}
return evenDigitsBuffer.length() > 0
? Integer.signum(n) * Integer.parseInt(evenDigitsBuffer.toString())
: 0;
}

how to find maximum number M less than N in which some specific digit is not allowed to exist in Java

Recently I got a interview programming question about how to find maximum number M less than N, and some specific digit is not allowed to exist in M.
For example, N = 123, digit = 2,then it will output: 119
My ideas is to convert N to string first, and then find the first position of digit from left to right to make this digit decreased by 1. Then I set all the remaining digits in N to 9 to make this number maximized. Does some could point out some corner case which I ignored? and is there some good implementation in Java of this problem for reference?
... convert N to string first, and then find the first position of digit from left to right to make this digit decreased by 1.
That seems difficult. How would you "find the position to make a digit decreased"?
Why not go with a more brute-force approach: keep the number as a number, decrease it one by one, convert to string to find if the digit exists, for example:
public int getMaxN(int N, char digit) {
for (int i = N; i > 0; --i) {
if (Integer.toString(i).indexOf(digit) == -1) {
return i;
}
}
throw new NoSuchElementException();
}
#Test
public void testGetMaxN() {
assertEquals(119, getMaxN(123, '2'));
assertEquals(122, getMaxN(123, '3'));
assertEquals(99, getMaxN(123, '1'));
}
#Test(expected = NoSuchElementException.class)
public void testNoSuchElement() {
getMaxN(0, '0');
}
Probably a more intelligent and efficient method exists.
Attempt 3. Still O(n) but due to the special 0 case needing to cascade back up:
static int banDigit(int number, int digit) {
int length = (Integer.toString(number)).length();
int result = 0;
boolean foundDigit = false;
for (int i = length - 1; i >= 0; i--) {
if (!foundDigit) {
int currentDigit = (int) number / ((int) Math.pow(10, i));
number = number % (int) Math.pow(10, i);
if (currentDigit == digit) {
//if nonzero digit banned, we can just decrement and purge 9 or 8 to right
if (digit > 0) {
currentDigit--;
} else {
// we have to subtract one from the previous
result = result - (int) Math.pow(10, i);
//then we have to check if doing that caused a bunch of ones prior
for (int j = i + 1; j < length; j++) {
if ((int) (result % (int) Math.pow(10, j + 1)) / (int) Math.pow(10, j) == 0) {
result = result - (int) Math.pow(10, j);
}
}
}
foundDigit = true;
}
result += currentDigit * Math.pow(10, i);
} else if (digit == 9) {
result += 8 * Math.pow(10, i);
} else {
result += 9 * Math.pow(10, i);
}
}
return result;
}
The trick I used is to find the correct number to subtract from the original number and max out the rest of the number. This is usually just a number with a 1 in the first bad digit place, but it is a bit more tricky if the banned digit it 0 since it can produce more 0's when the subtraction carries over. This happens when there is a string of digits like 1110 with 1's preceding the 0's. My program keeps track of these in this O(n) time solution where n is the number of digits.
import java.math.BigInteger;
import java.util.Arrays;
public class RemoveDigits {
public static BigInteger removeDigits(BigInteger number, int banned) {
char[] digits = number.toString().toCharArray(); // digits of the number
char[] subtractChars = null; // array used to initialize BigInteger to subtract from the bad digit
char maxDigit = banned == 9 ? '8' : '9'; // digit to fill rest of the number with
int badCarryIndex = -1; // if banned == 0 keep track of the carry possibility
int badDigitIndex = -1;
for (int i = 0; i < digits.length; i++) {
if (banned == 0 && digits[i] == '1') { // keep track of first character affected by carry
if (badCarryIndex < 0) {
badCarryIndex = i;
}
} else if (Character.digit(digits[i], 10) == banned) {
badDigitIndex = i;
if (badCarryIndex != 0) { // calculate the real first character affected by carry
badCarryIndex--;
}
subtractChars = badCarryIndex < 0 ? new char[digits.length - badDigitIndex] : new char[digits.length - badCarryIndex - 1];
subtractChars[0] = '1';
break;
} else { // reset if found a good character
badCarryIndex = -1;
}
}
if (badDigitIndex >= 0) {
// fill the rest of the digits with maxDigit
Arrays.fill(digits, badDigitIndex + 1, digits.length, maxDigit);
// build subtractChars
if (badCarryIndex >= 0) {
// banned == 0, have to worry about carry producing 0's
Arrays.fill(subtractChars, 1, badDigitIndex - badCarryIndex, '1');
Arrays.fill(subtractChars, badDigitIndex - badCarryIndex, subtractChars.length, '0');
} else {
Arrays.fill(subtractChars, 1, subtractChars.length, '0');
}
BigInteger maxedNumber = new BigInteger(new String(digits));
BigInteger subtractNumber = new BigInteger(new String(subtractChars));
return maxedNumber.subtract(subtractNumber);
}
return number; // no bad digits in original number
}
public static void main(String[] args) {
System.out.println(removeDigits(new BigInteger("20"), 0));
System.out.println(removeDigits(new BigInteger("210"), 0));
System.out.println(removeDigits(new BigInteger("123"), 0));
System.out.println(removeDigits(new BigInteger("123"), 2));
System.out.println(removeDigits(new BigInteger("1000"), 0));
System.out.println(removeDigits(new BigInteger("1000"), 1));
System.out.println(removeDigits(new BigInteger("1111020"), 0));
System.out.println(removeDigits(new BigInteger("2011020"), 0));
System.out.println(removeDigits(new BigInteger("80000009"), 9));
System.out.println(removeDigits(new BigInteger("80937921"), 9));
}
}
It prints:
19
199
123
119
999
999
999999
999999
80000008
80888888
Edit: fixed corner case pointed out by JoJo.
I think it works, please tell me if you see any case not well handled.
public static void main(String[] args) {
int N = 100211020;
int digit = 0;
int m;
for (m = 9 ; m > 0 && m == digit; m--);
String sres;
String s = N + "";
int length = s.length();
int i = s.indexOf(digit + "");
if (i < 0)
sres = s;
else {
StringBuilder sb = new StringBuilder();
if (digit != 0) {
for (int j=0 ; j<i ; j++) sb.append(s.charAt(j));
sb.append(digit - 1);
for (int j=i + 1 ; j<length ; j++) sb.append(m);
} else {
if (s.charAt(0) != '1')
sb.append(mod10(s.charAt(0) - '0' - 1));
for (int j=1 ; j<length ; j++) sb.append(9);
}
sres = sb.toString();
}
System.out.println(sres);
}
public static int mod10(int n) {
int res = n % 10;
return res < 0 ? res + 10 : res;
}
EDIT :
I finally decided to use strings to handle the case of digit = 0, which was quite complicated with my first approach.

Recursive function to promote binary ARRAY

How can I promote binary array using recursion func.
The function receives binary array V and increases the value of the number represented by V the following number with the same number of unity. Function returns true if the operation can be performed (java)
Example:
v = {0,0,0,1,1,0,0,1,1} => return true, v = {0,0,0,1,1,0,1,0,1}
i write this:
public static boolean incrementSameOnes(int[] vec) {
boolean succ=false;
int[] v=new int[vec.length-1];
if(vec.length==1){
return false;
}
if (vec[vec.length-1]==1 && vec[vec.length-2]==0)
{
vec[vec.length-2] = 1;
vec[vec.length-1] = 0;
System.out.print(Arrays.toString(vec));
return true;
}else {
for(int j=0;j<vec.length-1;j++)
v[j]=vec[j];
succ=incrementSameOnes(v);
}
return succ;
}
If I understand you correctly, you want to find the next higher integer with the same amount of set bits in the binary representation, correct? If so, I propose:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] x = { 1, 1, 1, 0, 1, 1, 0 };
System.out.println("original: " + Arrays.toString(x));
if (promote(x)) System.out.println("promoted: " + Arrays.toString(x));
else System.out.println("not promotable");
}
private static boolean promote(int[] x) {
// convert to integer value
int value = 0;
for (int i = 0; i < x.length; i++) {
value += x[x.length - 1 - i] * (1 << i);
}
int newValue = value + 1, maxValue = 1 << x.length;
int nBits = getNumberOfSetBits(value);
// increase value until same amount of set bits found
while (newValue < maxValue && getNumberOfSetBits(newValue) != nBits)
newValue++;
// convert back to array
if (newValue < maxValue) {
for (int i = 0; i < x.length; i++) {
x[x.length - 1 - i] = (newValue & (1 << i)) >> i;
}
return true;
} else {
return false;
}
}
// kung fu magic to get number of set bits in an int
// see http://stackoverflow.com/a/109025/1137043
private static int getNumberOfSetBits(int i) {
i = i - ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}
}
output:
original: [1, 1, 1, 0, 1, 1, 0]
promoted: [1, 1, 1, 1, 0, 0, 1]
EDIT: For a 2D array like in your example, the conversion to int and back to your array format would look a bit different but I would recommend the same approach.

Java decimal to binary int array

For this exercise I'm making I want a decimal < 4096 to be written in binary form in an int array.
So for example, 4 would be {0,0,0,0,0,0,0,0,0,1,0,0}. I need this for (nearly) all integers up to 4096, so I've written this piece of code:
for(int k=0; k<4096; k++){
int[] myNumber = { (k / 2048) % 2, (k / 1024) % 2, (k / 512) % 2, (k / 256) % 2, (k / 128) % 2, (k / 64) % 2, (k / 32) % 2, (k / 16) % 2, (k / 8) % 2, (k / 4) % 2, (k / 2) % 2, (k / 1) % 2 }
/* Some processing */
}
This looks kind of ugly, so that's why I'm curious to find out if there is a more elegant way of achieving this?
For the interested reader:
I chose for the array approach of storing the binary numbers, because I need to perform some shifting and addition modulo 2. I'm using an LFSR, and this is my implementation for that:
public class LFSR {
private int[] polynomial;
public LFSR(int[] polynomial) {
this.polynomial = polynomial;
}
public int[] shiftLeft(int[] input) {
int[] result = new int[input.length];
int out = input[0];
result[input.length - 1] = out;
for (int i = input.length - 1; i > 0; i--) {
result[i - 1] = (input[i] + polynomial[i - 1] * out) % 2;
}
return result;
}
}
Any suggestions?
Some pseudo code:
While (int i = 0; i < 12; i++) {
bitarray[i] = numericalValue & 0x1;
numericalValue = numericalValue >> 1;
}
So, shifting right by one bit is division by 2, and ANDing with 1 always leaves you only with the lowest bit which is what you want.
One quick suggestion would be to switch to a byte array instead of an int array, simply to save space, as they will only be 'bits'.
With regards to improving the elegance of your solution, it is perhaps easier to use subcomputations:
int[] intToBinaryArray(int dec){
int[] res = int[12]
for(int i =0; i < 12; i++)
bitarray[i] = numericalValue & 0x1; //grab first bit only
dec /= 2;
}
return res;
}
String s = Integer.toBinaryString(int value);
Now convert the String to int[]
int[] intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10);
}
This is somewhat shorter ;)
int[] bits = new int[13];
String bin = Integer.toBinaryString(8192 + value);
for(int i = 1; i < bin.length(); i++) {
bits[i-1] = bin.charAt(i)-'0';
}
"Elegance" is in the eye of the beholder, but I'd start by creating a method to avoid repetition and improve clarity:
int[] myNumber = { getBit(k, 12), getBit(k, 11), ... };
I personally feel this is the "most elegant" way to get a particular bit:
int getBit(int v, int i)
{
return v >> i & 1;
}
Then you have to decide whether you want to keep repeating yourself with the calls to getBit or whether you'd rather just use a single while or for loop to populate the whole array. You'd think it'd be quicker the way you've got it written, but there's good chance the JIT compiler automatically unrolls your loop for you if you use a loop like Jochen suggests.
Since this particular operation is entirely self contained, you might even want to create a special method for it:
int[] getBits(int v, int num)
{
int[] arr = new int[num];
for(int i=0; i<num; i++) {
arr[i] = getBit(v, num - i - 1);
}
return arr;
}
That makes it easier to unit test, and you can reuse it in a variety of situations.
public int[] toBin (int num)
{
int[] ret = new int[8];
for (int i = 7, p = 0; i>=0; i--, p++)
{
ret[i] = (num/2**p) % 2;
}
return ret;
}
You could use the bit shift operator together withbthe bitwise AND operator as follows. Note bitCount - i - 1 is needed to get the high bit first.
final int bitCount =12; // Increase to support greater than 4095
int[] number = new int[bitCount];
for( int i = 0; i < bitCount; i++ )
{
number[i] = ( k >>> ( bitCount - i - 1 ) ) & 1;
}

Fastest algorithm to check if a number is pandigital?

Pandigital number is a number that contains the digits 1..number length.
For example 123, 4312 and 967412385.
I have solved many Project Euler problems, but the Pandigital problems always exceed the one minute rule.
This is my pandigital function:
private boolean isPandigital(int n){
Set<Character> set= new TreeSet<Character>();
String string = n+"";
for (char c:string.toCharArray()){
if (c=='0') return false;
set.add(c);
}
return set.size()==string.length();
}
Create your own function and test it with this method
int pans=0;
for (int i=123456789;i<=123987654;i++){
if (isPandigital(i)){
pans++;
}
}
Using this loop, you should get 720 pandigital numbers. My average time was 500 millisecond.
I'm using Java, but the question is open to any language.
UPDATE
#andras answer has the best time so far, but #Sani Huttunen answer inspired me to add a new algorithm, which gets almost the same time as #andras.
C#, 17ms, if you really want a check.
class Program
{
static bool IsPandigital(int n)
{
int digits = 0; int count = 0; int tmp;
for (; n > 0; n /= 10, ++count)
{
if ((tmp = digits) == (digits |= 1 << (n - ((n / 10) * 10) - 1)))
return false;
}
return digits == (1 << count) - 1;
}
static void Main()
{
int pans = 0;
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 123456789; i <= 123987654; i++)
{
if (IsPandigital(i))
{
pans++;
}
}
sw.Stop();
Console.WriteLine("{0}pcs, {1}ms", pans, sw.ElapsedMilliseconds);
Console.ReadKey();
}
}
For a check that is consistent with the Wikipedia definition in base 10:
const int min = 1023456789;
const int expected = 1023;
static bool IsPandigital(int n)
{
if (n >= min)
{
int digits = 0;
for (; n > 0; n /= 10)
{
digits |= 1 << (n - ((n / 10) * 10));
}
return digits == expected;
}
return false;
}
To enumerate numbers in the range you have given, generating permutations would suffice.
The following is not an answer to your question in the strict sense, since it does not implement a check. It uses a generic permutation implementation not optimized for this special case - it still generates the required 720 permutations in 13ms (line breaks might be messed up):
static partial class Permutation
{
/// <summary>
/// Generates permutations.
/// </summary>
/// <typeparam name="T">Type of items to permute.</typeparam>
/// <param name="items">Array of items. Will not be modified.</param>
/// <param name="comparer">Optional comparer to use.
/// If a <paramref name="comparer"/> is supplied,
/// permutations will be ordered according to the
/// <paramref name="comparer"/>
/// </param>
/// <returns>Permutations of input items.</returns>
public static IEnumerable<IEnumerable<T>> Permute<T>(T[] items, IComparer<T> comparer)
{
int length = items.Length;
IntPair[] transform = new IntPair[length];
if (comparer == null)
{
//No comparer. Start with an identity transform.
for (int i = 0; i < length; i++)
{
transform[i] = new IntPair(i, i);
};
}
else
{
//Figure out where we are in the sequence of all permutations
int[] initialorder = new int[length];
for (int i = 0; i < length; i++)
{
initialorder[i] = i;
}
Array.Sort(initialorder, delegate(int x, int y)
{
return comparer.Compare(items[x], items[y]);
});
for (int i = 0; i < length; i++)
{
transform[i] = new IntPair(initialorder[i], i);
}
//Handle duplicates
for (int i = 1; i < length; i++)
{
if (comparer.Compare(
items[transform[i - 1].Second],
items[transform[i].Second]) == 0)
{
transform[i].First = transform[i - 1].First;
}
}
}
yield return ApplyTransform(items, transform);
while (true)
{
//Ref: E. W. Dijkstra, A Discipline of Programming, Prentice-Hall, 1997
//Find the largest partition from the back that is in decreasing (non-icreasing) order
int decreasingpart = length - 2;
for (;decreasingpart >= 0 &&
transform[decreasingpart].First >= transform[decreasingpart + 1].First;
--decreasingpart) ;
//The whole sequence is in decreasing order, finished
if (decreasingpart < 0) yield break;
//Find the smallest element in the decreasing partition that is
//greater than (or equal to) the item in front of the decreasing partition
int greater = length - 1;
for (;greater > decreasingpart &&
transform[decreasingpart].First >= transform[greater].First;
greater--) ;
//Swap the two
Swap(ref transform[decreasingpart], ref transform[greater]);
//Reverse the decreasing partition
Array.Reverse(transform, decreasingpart + 1, length - decreasingpart - 1);
yield return ApplyTransform(items, transform);
}
}
#region Overloads
public static IEnumerable<IEnumerable<T>> Permute<T>(T[] items)
{
return Permute(items, null);
}
public static IEnumerable<IEnumerable<T>> Permute<T>(IEnumerable<T> items, IComparer<T> comparer)
{
List<T> list = new List<T>(items);
return Permute(list.ToArray(), comparer);
}
public static IEnumerable<IEnumerable<T>> Permute<T>(IEnumerable<T> items)
{
return Permute(items, null);
}
#endregion Overloads
#region Utility
public static IEnumerable<T> ApplyTransform<T>(
T[] items,
IntPair[] transform)
{
for (int i = 0; i < transform.Length; i++)
{
yield return items[transform[i].Second];
}
}
public static void Swap<T>(ref T x, ref T y)
{
T tmp = x;
x = y;
y = tmp;
}
public struct IntPair
{
public IntPair(int first, int second)
{
this.First = first;
this.Second = second;
}
public int First;
public int Second;
}
#endregion
}
class Program
{
static void Main()
{
int pans = 0;
int[] digits = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Stopwatch sw = new Stopwatch();
sw.Start();
foreach (var p in Permutation.Permute(digits))
{
pans++;
if (pans == 720) break;
}
sw.Stop();
Console.WriteLine("{0}pcs, {1}ms", pans, sw.ElapsedMilliseconds);
Console.ReadKey();
}
}
This is my solution:
static char[][] pandigits = new char[][]{
"1".toCharArray(),
"12".toCharArray(),
"123".toCharArray(),
"1234".toCharArray(),
"12345".toCharArray(),
"123456".toCharArray(),
"1234567".toCharArray(),
"12345678".toCharArray(),
"123456789".toCharArray(),
};
private static boolean isPandigital(int i)
{
char[] c = String.valueOf(i).toCharArray();
Arrays.sort(c);
return Arrays.equals(c, pandigits[c.length-1]);
}
Runs the loop in 0.3 seconds on my (rather slow) system.
Two things you can improve:
You don't need to use a set: you can use a boolean array with 10 elements
Instead of converting to a string, use division and the modulo operation (%) to extract the digits.
Using a bit vector to keep track of which digits have been found appears to be the fastest raw method. There are two ways to improve it:
Check if the number is divisible by 9. This is a necessary condition for being pandigital, so we can exclude 88% of numbers up front.
Use multiplication and shifts instead of divisions, in case your compiler doesn't do that for you.
This gives the following, which runs the test benchmark in about 3ms on my machine. It correctly identifies the 362880 9-digit pan-digital numbers between 100000000 and 999999999.
bool IsPandigital(int n)
{
if (n != 9 * (int)((0x1c71c71dL * n) >> 32))
return false;
int flags = 0;
while (n > 0) {
int q = (int)((0x1999999aL * n) >> 32);
flags |= 1 << (n - q * 10);
n = q;
}
return flags == 0x3fe;
}
My solution involves Sums and Products.
This is in C# and runs in about 180ms on my laptop:
static int[] sums = new int[] {1, 3, 6, 10, 15, 21, 28, 36, 45};
static int[] products = new int[] {1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
static void Main(string[] args)
{
var pans = 0;
for (var i = 123456789; i <= 123987654; i++)
{
var num = i.ToString();
if (Sum(num) == sums[num.Length - 1] && Product(num) == products[num.Length - 1])
pans++;
}
Console.WriteLine(pans);
}
protected static int Sum(string num)
{
int sum = 0;
foreach (char c in num)
sum += (int) (c - '0');
return sum;
}
protected static int Product(string num)
{
int prod = 1;
foreach (char c in num)
prod *= (int)(c - '0');
return prod;
}
Why find when you can make them?
from itertools import *
def generate_pandigital(length):
return (''.join for each in list(permutations('123456789',length)))
def test():
for i in range(10):
print i
generate_pandigital(i)
if __name__=='__main__':
test()
J does this nicely:
isPandigital =: 3 : 0
*./ (' ' -.~ ": 1 + i. # s) e. s =. ": y
)
isPandigital"0 (123456789 + i. 1 + 123987654 - 123456789)
But slowly. I will revise. For now, clocking at 4.8 seconds.
EDIT:
If it's just between the two set numbers, 123456789 and 123987654, then this expression:
*./"1 (1+i.9) e."1 (9#10) #: (123456789 + i. 1 + 123987654 - 123456789)
Runs in 0.23 seconds. It's about as fast, brute-force style, as it gets in J.
TheMachineCharmer is right. At least for some the problems, it's better to iterate over all the pandigitals, checking each one to see if it fits the criteria of the problem. However, I think their code is not quite right.
I'm not sure which is better SO etiquette in this case: Posting a new answer or editing theirs. In any case, here is the modified Python code which I believe to be correct, although it doesn't generate 0-to-n pandigitals.
from itertools import *
def generate_pandigital(length):
'Generate all 1-to-length pandigitals'
return (''.join(each) for each in list(permutations('123456789'[:length])))
def test():
for i in range(10):
print 'Generating all %d-digit pandigitals' % i
for (n,p) in enumerate(generate_pandigital(i)):
print n,p
if __name__=='__main__':
test()
You could add:
if (set.add(c)==false) return false;
This would short circuit a lot of your computations, since it'll return false as soon as a duplicate was found, since add() returns false in this case.
bool IsPandigital (unsigned long n) {
if (n <= 987654321) {
hash_map<int, int> m;
unsigned long count = (unsigned long)(log((double)n)/log(10.0))+1;
while (n) {
++m[n%10];
n /= 10;
}
while (m[count]==1 && --count);
return !count;
}
return false;
}
bool IsPandigital2 (unsigned long d) {
// Avoid integer overflow below if this function is passed a very long number
if (d <= 987654321) {
unsigned long sum = 0;
unsigned long prod = 1;
unsigned long n = d;
unsigned long max = (log((double)n)/log(10.0))+1;
unsigned long max_sum = max*(max+1)/2;
unsigned long max_prod = 1;
while (n) {
sum += n % 10;
prod *= (n%10);
max_prod *= max;
--max;
n /= 10;
}
return (sum == max_sum) && (prod == max_prod);
}
I have a solution for generating Pandigital numbers using StringBuffers in Java. On my laptop, my code takes a total of 5ms to run. Of this only 1ms is required for generating the permutations using StringBuffers; the remaining 4ms are required for converting this StringBuffer to an int[].
#medopal: Can you check the time this code takes on your system?
public class GenPandigits
{
/**
* The prefix that must be appended to every number, like 123.
*/
int prefix;
/**
* Length in characters of the prefix.
*/
int plen;
/**
* The digit from which to start the permutations
*/
String beg;
/**
* The length of the required Pandigital numbers.
*/
int len;
/**
* #param prefix If there is no prefix then this must be null
* #param beg If there is no prefix then this must be "1"
* #param len Length of the required numbers (excluding the prefix)
*/
public GenPandigits(String prefix, String beg, int len)
{
if (prefix == null)
{
this.prefix = 0;
this.plen = 0;
}
else
{
this.prefix = Integer.parseInt(prefix);
this.plen = prefix.length();
}
this.beg = beg;
this.len = len;
}
public StringBuffer genPermsBet()
{
StringBuffer b = new StringBuffer(beg);
for(int k=2;k<=len;k++)
{
StringBuffer rs = new StringBuffer();
int l = b.length();
int s = l/(k-1);
String is = String.valueOf(k+plen);
for(int j=0;j<k;j++)
{
rs.append(b);
for(int i=0;i<s;i++)
{
rs.insert((l+s)*j+i*k+j, is);
}
}
b = rs;
}
return b;
}
public int[] getPandigits(String buffer)
{
int[] pd = new int[buffer.length()/len];
int c= prefix;
for(int i=0;i<len;i++)
c =c *10;
for(int i=0;i<pd.length;i++)
pd[i] = Integer.parseInt(buffer.substring(i*len, (i+1)*len))+c;
return pd;
}
public static void main(String[] args)
{
GenPandigits gp = new GenPandigits("123", "4", 6);
//GenPandigits gp = new GenPandigits(null, "1", 6);
long beg = System.currentTimeMillis();
StringBuffer pansstr = gp.genPermsBet();
long end = System.currentTimeMillis();
System.out.println("Time = " + (end - beg));
int pd[] = gp.getPandigits(pansstr.toString());
long end1 = System.currentTimeMillis();
System.out.println("Time = " + (end1 - end));
}
}
This code can also be used for generating all Pandigital numbers(excluding zero). Just change the object creation call to
GenPandigits gp = new GenPandigits(null, "1", 9);
This means that there is no prefix, and the permutations must start from "1" and continue till the length of the numbers is 9.
Following are the time measurements for different lengths.
#andras: Can you try and run your code to generate the nine digit Pandigital numbers? What time does it take?
This c# implementation is about 8% faster than #andras over the range 123456789 to 123987654 but it is really difficult to see on my test box as his runs in 14ms and this one runs in 13ms.
static bool IsPandigital(int n)
{
int count = 0;
int digits = 0;
int digit;
int bit;
do
{
digit = n % 10;
if (digit == 0)
{
return false;
}
bit = 1 << digit;
if (digits == (digits |= bit))
{
return false;
}
count++;
n /= 10;
} while (n > 0);
return (1<<count)-1 == digits>>1;
}
If we average the results of 100 runs we can get a decimal point.
public void Test()
{
int pans = 0;
var sw = new Stopwatch();
sw.Start();
for (int count = 0; count < 100; count++)
{
pans = 0;
for (int i = 123456789; i <= 123987654; i++)
{
if (IsPandigital(i))
{
pans++;
}
}
}
sw.Stop();
Console.WriteLine("{0}pcs, {1}ms", pans, sw.ElapsedMilliseconds / 100m);
}
#andras implementation averages 14.4ms and this implementation averages 13.2ms
EDIT:
It seems that mod (%) is expensive in c#. If we replace the use of the mod operator with a hand coded version then this implementation averages 11ms over 100 runs.
private static bool IsPandigital(int n)
{
int count = 0;
int digits = 0;
int digit;
int bit;
do
{
digit = n - ((n / 10) * 10);
if (digit == 0)
{
return false;
}
bit = 1 << digit;
if (digits == (digits |= bit))
{
return false;
}
count++;
n /= 10;
} while (n > 0);
return (1 << count) - 1 == digits >> 1;
}
EDIT: Integrated n/=10 into the digit calculation for a small speed improvement.
private static bool IsPandigital(int n)
{
int count = 0;
int digits = 0;
int digit;
int bit;
do
{
digit = n - ((n /= 10) * 10);
if (digit == 0)
{
return false;
}
bit = 1 << digit;
if (digits == (digits |= bit))
{
return false;
}
count++;
} while (n > 0);
return (1 << count) - 1 == digits >> 1;
}
#include <cstdio>
#include <ctime>
bool isPandigital(long num)
{
int arr [] = {1,2,3,4,5,6,7,8,9}, G, count = 9;
do
{
G = num%10;
if (arr[G-1])
--count;
arr[G-1] = 0;
} while (num/=10);
return (!count);
}
int main()
{
clock_t start(clock());
int pans=0;
for (int i = 123456789;i <= 123987654; ++i)
{
if (isPandigital(i))
++pans;
}
double end((double)(clock() - start));
printf("\n\tFound %d Pandigital numbers in %lf seconds\n\n", pans, end/CLOCKS_PER_SEC);
return 0;
}
Simple implementation. Brute-forced and computes in about 140 ms
In Java
You can always just generate them, and convert the Strings to Integers, which is faster for larger numbers
public static List<String> permutation(String str) {
List<String> permutations = new LinkedList<String>();
permutation("", str, permutations);
return permutations;
}
private static void permutation(String prefix, String str, List<String> permutations) {
int n = str.length();
if (n == 0) {
permutations.add(prefix);
} else {
for (int i = 0; i < n; i++) {
permutation(prefix + str.charAt(i),
str.substring(0, i) + str.substring(i + 1, n), permutations);
}
}
}
The below code works for testing a numbers pandigitality.
For your test mine ran in around ~50ms
1-9 PanDigital
public static boolean is1To9PanDigit(int i) {
if (i < 1e8) {
return false;
}
BitSet set = new BitSet();
while (i > 0) {
int mod = i % 10;
if (mod == 0 || set.get(mod)) {
return false;
}
set.set(mod);
i /= 10;
}
return true;
}
or more general, 1 to N,
public static boolean is1ToNPanDigit(int i, int n) {
BitSet set = new BitSet();
while (i > 0) {
int mod = i % 10;
if (mod == 0 || mod > n || set.get(mod)) {
return false;
}
set.set(mod);
i /= 10;
}
return set.cardinality() == n;
}
And just for fun, 0 to 9, zero requires extra logic due to a leading zero
public static boolean is0To9PanDigit(long i) {
if (i < 1e6) {
return false;
}
BitSet set = new BitSet();
if (i <= 123456789) { // count for leading zero
set.set(0);
}
while (i > 0) {
int mod = (int) (i % 10);
if (set.get(mod)) {
return false;
}
set.set(mod);
i /= 10;
}
return true;
}
Also for setting iteration bounds:
public static int maxPanDigit(int n) {
StringBuffer sb = new StringBuffer();
for(int i = n; i > 0; i--) {
sb.append(i);
}
return Integer.parseInt(sb.toString());
}
public static int minPanDigit(int n) {
StringBuffer sb = new StringBuffer();
for(int i = 1; i <= n; i++) {
sb.append(i);
}
return Integer.parseInt(sb.toString());
}
You could easily use this code to generate a generic MtoNPanDigital number checker
I decided to use something like this:
def is_pandigital(n, zero_full=True, base=10):
"""Returns True or False if the number n is pandigital.
This function returns True for formal pandigital numbers as well as
n-pandigital
"""
r, l = 0, 0
while n:
l, r, n = l + 1, r + n % base, n / base
t = xrange(zero_full ^ 1, l + (zero_full ^ 1))
return r == sum(t) and l == len(t)
Straight forward way
boolean isPandigital(int num,int length){
for(int i=1;i<=length;i++){
if(!(num+"").contains(i+""))
return false;
}
return true;
}
OR if you are sure that the number is of the right length already
static boolean isPandigital(int num){
for(int i=1;i<=(num+"").length();i++){
if(!(num+"").contains(i+""))
return false;
}
return true;
}
I refactored Andras' answer for Swift:
extension Int {
func isPandigital() -> Bool {
let requiredBitmask = 0b1111111111;
let minimumPandigitalNumber = 1023456789;
if self >= minimumPandigitalNumber {
var resultBitmask = 0b0;
var digits = self;
while digits != 0 {
let lastDigit = digits % 10;
let binaryCodedDigit = 1 << lastDigit;
resultBitmask |= binaryCodedDigit;
// remove last digit
digits /= 10;
}
return resultBitmask == requiredBitmask;
}
return false;
}
}
1023456789.isPandigital(); // true
great answers, my 2 cents
bool IsPandigital(long long number, int n){
int arr[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, amax = 0, amin;
while (number > 0){
int rem = number % 10;
arr[rem]--;
if (arr[rem] < 0)
return false;
number = number / 10;
}
for (int i = 0; i < n; i++){
if (i == 0)
amin = arr[i];
if (arr[i] > amax)
amax = arr[i];
if (arr[i] < amin)
amin = arr[i];
}
if (amax == 0 && amin == 0)
return true;
else
return false;
}

Categories

Resources