1

I need a String array with the following attributes:

  • 4 digits numbers
  • No repeating digits ("1214" is invalid)
  • No 0's

Is there an easier way to do this than manually type it? Like:

String[] s = {"1234","1235",1236",1237",1238",1239","1243","1245"};

Sorry for my English!

Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57
Atinator98
  • 51
  • 1
  • 7

3 Answers3

1

****edit**** Just saw that it is in Java. So use this function: String.valueOf(number) to convert integer to string if none of the digits are repeats in the loop.


Not sure what language you are doing but I am assuming no repeats not replies. So what you can do is have a loop from 0 to 9999 and then run through all the numbers while checking if each digit has repeats if so discard number (do not store it into array). You can convert integers to strings in many languages in their function so you can do that then store it into array. Good luck. Hope this helped (fastest solution from my head...there could be more efficient ones)

Albert Tai
  • 121
  • 6
  • Start at 1234 so you don't have to check if it has 4 digits – Evan M Dec 30 '14 at 23:00
  • Thank you very much for the help! But how should I do this exactly? I supposewith some for cycle am I right? – Atinator98 Dec 30 '14 at 23:13
  • EvanM you are correct! Sorry I rushed that and made it inefficient by starting at 0. @Atinator98 use a for loop to run from 1234 (smallest number possible without repeats) through this until you hit 9876 (largest number without repeats)! – Albert Tai Dec 31 '14 at 01:08
1

The following code will generate an array with your specifications.

public class Test {

public static void main(String[] args) {

    List<String> result = new ArrayList<>();

    Set<Character> set = new HashSet<>();
    for (int i = 1234; i <= 9876; i++) {
        set.clear();

        String iAsString = Integer.toString(i);
        char[] chars = iAsString.toCharArray();

        boolean valid = true;
        for (char c : chars) {
            if (c == '0' || !set.add(c)) {
                valid = false;
                break;
            }
        }

        if (valid) {
            result.add(iAsString);
        }
    }


    String[] yourStringArray = result.toArray(new String[result.size()]);

    System.out.println(Arrays.toString(yourStringArray));

}


}
Markus Patt
  • 467
  • 3
  • 11
0

Try this method for creating Random number with your structure :

ArrayList<Integer> rawNumbers = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9));
public String createRandomNumberSring()
{
    String result = "";
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.addAll(rawNumbers);
    for(int i = 0; i < 4; i++)
    {
        int index = (int)(Math.random() * (numbers.size() + 1));
        result += numbers.get(index).toString();
        numbers.remove(index);
    }
    return result;
}
Morteza Soleimani
  • 2,652
  • 3
  • 25
  • 44