Based on web, giving right Armstrong numbers. Following advice on this page, zero is excluded. Don't know what's wrong!!
Addendum: With some modifications to the code below I have tried:
1. excluding 0, numbers < N
2. excluding 0, numbers <= N
3. including 0, numbers < N
4. including 0, numbers <= N
None pass.
package com.codegym.task.task20.task2025;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import static oracle.jrockit.jfr.events.Bits.intValue;
/*
Number algorithms
This solution borrows its basic strategy (and some code) from https://github.com/shamily/ArmstrongNumbers
*/
public class Solution {
private static ArrayList<Long> numbersArray = new ArrayList<>();
private static int[] digitsMultiset = new int[10];
private static long maxNum;
private static long minNum;
private static int digits;
private static long[] powers = {1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l};
public static long[] getNumbers(long N) {
numbersArray.add(0l);
while (maxNum < N) {
digits += 1;
minNum = (long) Math.pow(10, digits - 1);
maxNum = (long) Math.pow(10, digits);
if (N < maxNum) { maxNum = N; }
for (int i = 0; i < 10; i++) { powers[i] *= i; }
searchMultiset(0, digits, 0);
}
Collections.sort(numbersArray);
return arrayListToArray(numbersArray);
}
private static void searchMultiset(int digit, int remDigits, long sumPower) {
if (digit == 10) {
if (sumPowerInMultiset(sumPower)) { numbersArray.add(sumPower); }
return;
}
if (digit == 9) {
digitsMultiset[digit] = remDigits;
searchMultiset(digit + 1, 0, sumPower + remDigits * powers[digit]);
}
else {
for (int i = 0; i <= remDigits; i++) {
digitsMultiset[digit] = i;
searchMultiset(digit + 1, remDigits - i, sumPower + i * powers[digit]);
}
}
}
private static boolean sumPowerInMultiset(long sumPower) {
if (sumPower >= maxNum) return false;
if (sumPower < minNum) return false;
int[] testMultiset = new int[10];
while (sumPower > 0) {
int i = (int) (sumPower % 10);
testMultiset[i] ++;
sumPower = sumPower / 10;
}
for (int i = 0; i < 10; i++) {
if (testMultiset[i] != digitsMultiset[i]) return false;
}
return true;
}
public static long[] arrayListToArray (ArrayList<Long> numbersArray) {
long[] array = new long[numbersArray.size()];
int index = 0;
for (Long value : numbersArray) {
array[index] = value;
index++;
}
return array;
}
public static void main(String[] args) {
long N = Long.MAX_VALUE;
// long N = 3L;
long[] result = getNumbers(N);
for (int i = 0; i < result.length; i++) { System.out.println(result[i]); }
}
}