//Cody McMahon
//Laptop Problem: Perm.c
//10/7/11
//COP 3223-201

#include<stdio.h>

int main()
{
    //declare variables and creat file pointer to perm file
    int count=0, j=1, numCase=0, cases, n, k,temp;
    int i, permSet=1, permDivisor;

    FILE *fin=fopen("perm.in", "r");

    //read in the number of cases
    fscanf(fin,"%d", &cases);


    //run this for each case
    while(numCase<cases)
    {

        //read in the number to permutate and the line of permutation you want
        fscanf(fin,"%d%d", &n, &k);


        //dynamically allocate memory for the array set to the size of the number to permutate
        int* array = (int*)malloc(sizeof(int)*(n));

        //set the number to divide out the from the total factorial
        //so first will be n
        permDivisor=n;

        //initialize the array with the first line of the permutation and
        //find the total number of lines using factorial
        for(i=0;i<n;i++)
        {
            array[i]=i+1;
            permSet=permSet*(i+1);
        }

        //find the number of lines within each number in the first spot
        permSet=permSet/permDivisor;

        //while count is less than the total amount of switches needed
        while((count + 1)!=n)
        {
            //check to see if the line is within the first set of permutations
            //if it is move to find the number for the next slot and decrease
            //the permutation. if its not less than switch the number in the first
            //with the second slot if then subract the permutation number
            //from k to see if its in the next set if not switch the next number to
            //slot you are looking for. Repeat
            if(k<=permSet)
            {
                count++;
                j=count+1;
                permDivisor--;
                permSet= permSet/permDivisor;
            }
            else
            {
                temp=array[count];
                array[count]=array[j];
                array[j]=temp;
                j++;
                k-=permSet;

            }

        }

        //print the line in order
        for(i=0;i<n;i++)
        {
            if(i==n-1)
            {
                printf("%d", array[i]);
            }
            else
            {
                printf("%d,",array[i]);
            }
        }

        printf("\n");

        numCase++;

        //reset variables
        count=0;
        j=1;
        permSet=1;

        //empty array to ready for next case
        free(array);
    }
    fclose(fin);
    return 0;
}

