Search code examples
emeditor

Calculate and list how many different 4 digit numbers can be done with the numbers 0 to 9?


There is something I want to learn.

Let's say we have some single digit numbers.

Example: 1-2-3-4-5-6-7-8-9-0 Example II: 1-2-4-6-0

And with these numbers, we want to get 4-digit numbers that are different from each other. And we want to print them as lists.

Result:

  • 4676
  • 4236
  • 1247
  • 1236
  • ....

Is it possible to do this?


Solution

  • You can write and run a macro like this:

    // retrieve the selected text
    str = document.selection.Text;
    
    // check the input string format. The input must be something like: "1-2-4-6-0"
    if( str.length == 0 ) {
        alert( "Select the input string" );
        Quit();
    }
    for( i = 0; i < str.length; ++i ) {
        c = str.substr( i, 1 );
        if( i % 2 == 0 ) {
            if( c < '0' || c > '9' ) {
                alert( "not digit" );
                Quit();
            }
        }
        else {
            if( c != '-' ) {
                alert( "not separated by '-'" );
                Quit();
            }
        }
    }
    
    var arr = new Array();
    j = 0;
    for( i = 0; i < str.length; ++i ) {
        if( i % 2 == 0 ) {
            c = str.substr( i, 1 );
            arr[j++] = c;
        }
    }
    
    if( arr.length < 4 ) {
        alert( "Input string should contain at least 4 digits" );
        Quit();
    }
    
    // list all 4-digit combinations
    len = arr.length;
    str = "";
    for( i = 0; i < len; ++i ) {
        for( j = 0; j < len; ++j ) {
            for( k = 0; k < len; ++k ) {
                for( l = 0; l < len; ++l ) {
                    str += arr[i] + arr[j] + arr[k] + arr[l] + "\r\n";
                }
            }
        }
    }
    
    // write the list in a new document
    editor.EnableTab = true;
    editor.NewFile();
    document.write( str );
    

    To run this, save this code as, for instance, GenCombinations.jsee, and then select this file from Select... in the Macros menu. Finally, select Run GenCombinations.jsee in the Macros menu after selecting an input string.