Inspired by Reddit r/dailyprogrammer
A vampire number v is a number v=xy with an even number n of digits formed by multiplying a pair of n/2-digit numbers (where the digits are taken from the original number in any order) x and y together. Pairs of trailing zeros are not allowed. If v is a vampire number, then x and y are called its "fangs." EDIT FOR CLARITY Vampire numbers were original 2 two-digit number (fangs) that multiplied to form a four digit number. We can extend this concept to an arbitrary number of two digit numbers. For this challenge we'll work with three two-digit numbers (the fangs) to create six digit numbers with the same property - we conserve the digits we have on both sides of the equation.
As always, looking for general feedback over code readability, structure and efficiency. But also I was looking to make the code a bit more flexible.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created on 6/29/2016.
*
* Inspired by r/dailyprogrammer
* https://www.reddit.com/r/dailyprogrammer/comments/3moxid/20150928_challenge_234_easy_vampire_numbers/
*
*/
public class VampireNumbers {
/**
* Calls generate function then displays return value.
* @param args Not used in this application.
*/
public static void main(String args[]){
generate().forEach(System.out::println); // Generates vampires, displays them on screen.
}
/**
* Generates list of vampire numbers. Currently only supports 3 fangs of length 2.
* @return List of vampires generated along with their fangs.
*/
private static List<String> generate(){
ArrayList<String> vampires = new ArrayList<>();
for (int i = 10; i < 100; i++) {
String fangOne = String.valueOf(i);
for (int j = i; j < 100; j++) {
String fangTwo = String.valueOf(j);
for (int k = j; k < 100; k++) {
String fangThree = String.valueOf(k);
String vampire = String.valueOf(i * j * k);
if (sortVampire(fangOne + fangTwo + fangThree).equals(sortVampire(vampire))){
vampires.add(String.format("%s * %s * %s = %s", fangOne, fangTwo, fangThree, vampire));
}
}
}
}
return vampires;
}
/**
* Used to sort a string of numbers. Helpful when determining if all fangs
* are within the generated vampire number.
* @param vampire String of numbers
* @return The sorted character list of the given string.
*/
private static List<Character> sortVampire(String vampire){
List<Character> list = new ArrayList<>();
for (int i = 0; i < vampire.length(); i++){
list.add(vampire.charAt(i));
}
Collections.sort(list);
return list;
}
}
It works as of now but can only generate 3 fangs(of length 2) creating vampire numbers of length 6. Was looking to expand the parameters of the generate function to something like:
private static List<String> generate(int fangLength, int vampireLength)
Also I had a question over this line specifically:
if (sortVampire(fangOne + fangTwo + fangThree).equals(sortVampire(vampire)))
Instead of concatenating all three fangs, would it be worth it to use a StringBuilder in this scenario?