Skip to main content

Challenge #13: Integer sorting in a grid

Created
Active
Viewed 4k times
64 entries
79

Decorative number graphic

Image designed by macrovector / Freepik

Credit to @JMP for contributing this challenge idea! (Which we slightly modified.)

In this challenge, we will sort some numbers onto a 6x6 square grid. Each cell will have one number.

Your challenge is to place all the integers into the grid such that

  • Each row is descendingly sorted (ties are not allowed). For example: 6 5 4 3 2 1 is valid but 6 5 5 5 3 2 is not valid.

  • Each column is descendingly sorted (ties are not allowed)

  • or declare this impossible.

Example on a 3x3 grid: Given these numbers to sort [95, 75, 75, 74, 74, 74, 54, 45, 40]

A valid response would be [[95, 75, 74], [75, 74, 54], [74, 45, 40]]

In the attached file, we have 100 sets of 36 random integers. The integers are between 0 and 99. For each set, return either a valid sorting on a 6x6 grid or declare it impossible.

Please also return the total count of cases for which the sorting was impossible.

Rules:

  • All correct responses will be designated as winners

  • Challenge deadline is December 3, 2025

  • Please include your code as well as a small description of your approach and anything interesting you encountered

  • Your entry is not permitted to be written by AI. For any feedback on this Challenge, please head over to the Meta post.

  • Have fun and thanks for participating!

64 entries
Sorted by:
79833288
Vote

Here is mine answer using python (.py)

def make_grid(nums):

    n = 6
    nums = sorted(nums, reverse=True)

    # Quick impossibility check — frequency rule
    from collections import Counter
    freq = Counter(nums)
    if any(v > n for v in freq.values()):
        return None  # cannot place same value in 6 distinct rows & columns

    # Fill row by row
    grid = [nums[i * n:(i + 1) * n] for i in range(n)]

    # Check row descending & no ties
    for r in range(n):
        for c in range(n - 1):
            if grid[r][c] <= grid[r][c + 1]:
                return None

    # Check column descending & no ties
    for c in range(n):
        for r in range(n - 1):
            if grid[r][c] <= grid[r + 1][c]:
                return None

    return grid


def process_all(testcases):
    
    impossible = 0
    outputs = []

    for i, nums in enumerate(testcases):
        grid = make_grid(nums)
        if grid is None:
            outputs.append("impossible")
            impossible += 1
        else:
            outputs.append(grid)

    return outputs, impossible

#-----------------EXAMPLE-------------------------


# Suppose you have 2 test cases:
example_testcases = [
    [95, 75, 75, 74, 74, 74, 54, 45, 40, 10, 9, 8, 7, 6, 5, 4,
     3, 2, 1, 0, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
     23, 24, 25, 26],   # 36 numbers
    [5] * 36  # definitely impossible
]

out, count_impossible = process_all(example_testcases)

print("Outputs:")
for o in out:
    print(o)
print("Total impossible =", count_impossible)
79832865
Vote

EXPLANATION

Going over the puzzle in my head and possible ways to sort it I have noticed a fact that final solutions are meant to have a gradient of highest numbers on the top left and lowest at the bottom right. Therefore, It is easier to mentally rotate the grid into a rhombus. Such rotation turns this problem into 1-d sorting all over, as all values on the same level don't compare to each other, but they do to the ones below them. Now in such position, we are to organize an already sorted array (the one we took from the file and sorted) into this rhombus with exact same order of numbers. The most comfortable way to arrange this it to fill the grid according to with a specific index layout from an array.

Result of such method on an array of positive integers 1-36 (inclusive) would be something like

36 35 33 30 26 21
34 32 29 25 20 15
31 28 24 19 14 10
27 23 18 13 9  6
22 17 12 8  5  3
16 11 7  4  2  1

In regards to the properties of this matrix, because it arranges everything diagonally, all equivalent numbers will fill out as many valid, diagonal (as diagonals do not compare, equivalent numbers on // diagonals are allowed) spots as possible until starting to fill the same rows and/or collumns as already existing same numbers.

After arranging all the numbers into the grid, I simply check for validity of the grid and return a valid grid or the word "invalid".

CODE

//First time participating, and practically first program in C
//Written in C (not c++)
//Could've written better :/
#include <stdio.h>
#include <stdlib.h>

//Function to make qsort() work (sort's comparison)
int comparisonFunction(const void* a, const void* b)
{
    return (*(int*)b - *(int*)a);
}

//The algorithm of sorting itself
int MatrixSort(int inputArray[36])
{
    int outputMatrix[6][6];
    int x = 0;
    int y = 0;
    int currentElement = 0;

    int* firstElement = &inputArray[0];
    qsort(firstElement, 36, sizeof(inputArray[0]), comparisonFunction);
    //In short, this\/ just puts sorted array into the matrix by diagonals
    //The magic numbers are boundaries of the 6x6 grid, we want it to be memory safe and to actually work
    for (int i=0;i<11;i++)
    {
        x = i;
        if (x>5){
            x=5;
        }
        y = i-x;
        while (x!=-1 && y!=6)
        {
            outputMatrix[x][y] = inputArray[currentElement];
            x--;
            y++;
            currentElement++;
        }
    }

    //This section checks eligibility of the resulting matrix, and outputs the appropriate result
    int isValid = 1;
    for(int i = 0;i<6;i++){
        for(int o=0;o<5;o++){
            if (outputMatrix[i][o]<=outputMatrix[i][o+1]){
                isValid = 0;
            }
        }
    }
    for(int i = 0;i<6;i++){
        for(int o=0;o<5;o++){
            if (outputMatrix[o][i]<=outputMatrix[o+1][i]){
                isValid = 0;
            }
        }
    }
    if (isValid){
        printf("[");
        for(int i = 0;i<6;i++){
            printf("[");
            for(int o=0;o<6;o++){
                printf("%s%d", (o==0) ? "" : ", ", outputMatrix[i][o]);
            }
            printf("]");
        }   
        printf("]\n");
        
    }
    else{
        printf("Invalid\n");
    }
    return isValid;
}


//The script for translating the file into usable arrays
int main()
{
    //Assuming that input file is conveniently in the same folder as the script
    FILE *fileInput;
    fileInput = fopen("RandomNumbers.txt", "r");
    if (fileInput == NULL){
        return 1; //implode if there is no file
    }

    int unsortedArray[36];
    int elementsFilled = 0;//Will help to avoid overwriting existing array elements while translating the document

    const int MAXLINESIZE = 200;
    char translationBuffer[MAXLINESIZE];

    int validCounter = 0;


    while (fgets(translationBuffer, MAXLINESIZE, fileInput))
    {
        
        for(int i = 0; i<sizeof(translationBuffer);i++)
        {
            //In short, this\/ translates useless file string lines into int arrays as integer type will be more useful for sorting
            if ((int)translationBuffer[i] > 47 && (int)translationBuffer[i] < 58)
            {
                if ((int)translationBuffer[i+1] > 47 && (int)translationBuffer[i+1] < 58)
                {
                    unsortedArray[elementsFilled] = ((int)translationBuffer[i]-48)*10 + (int)translationBuffer[i+1]-48;
                    elementsFilled++;
                    i++;
                }
                else
                {
                    unsortedArray[elementsFilled] = (int)translationBuffer[i]-48;
                    elementsFilled++;
                }
                //The "-48" is a magic number that turns ASCII value of a number character into it's respective int
            }
        }
        elementsFilled = 0;
        //calling sorting and counting for the total of valid solutions
        validCounter+=MatrixSort(unsortedArray);
    }


    //Closing the file and stopping the script
    fclose(fileInput);
    printf("%d valid solutions", validCounter);
    return 0;
}

OUTPUT

Invalid
Invalid
[[99, 91, 82, 73, 63, 44][95, 84, 75, 65, 53, 24][91, 80, 68, 55, 34, 14][81, 71, 59, 41, 16, 7][73, 60, 42, 16, 13, 6][61, 42, 18, 14, 6, 0]]
[[99, 88, 81, 70, 57, 40][94, 83, 71, 59, 40, 27][86, 73, 61, 48, 27, 13][74, 62, 50, 29, 19, 8][63, 52, 35, 20, 9, 3][56, 36, 24, 10, 6, 1]]
[[99, 96, 85, 78, 71, 48][97, 88, 80, 75, 48, 37][89, 81, 76, 52, 41, 31][85, 78, 52, 43, 31, 22][78, 60, 45, 32, 26, 14][65, 46, 35, 27, 21, 5]]
Invalid
Invalid
Invalid
[[98, 89, 80, 71, 60, 48][94, 80, 72, 64, 55, 31][83, 78, 65, 56, 37, 22][79, 66, 57, 39, 23, 10][67, 58, 42, 29, 16, 9][59, 44, 30, 18, 9, 4]]
[[99, 88, 82, 79, 64, 52][97, 86, 79, 64, 54, 41][88, 81, 66, 56, 42, 11][81, 68, 58, 48, 15, 5][71, 63, 50, 35, 9, 2][63, 51, 38, 11, 3, 0]]
Invalid
Invalid
Invalid
[[98, 93, 82, 70, 58, 38][96, 90, 73, 65, 41, 19][91, 74, 66, 49, 21, 14][82, 66, 54, 28, 16, 10][68, 55, 31, 16, 12, 4][56, 32, 19, 12, 10, 3]]
[[94, 84, 79, 71, 65, 56][85, 79, 73, 66, 56, 35][81, 74, 69, 57, 39, 26][77, 69, 57, 46, 31, 13][71, 57, 46, 31, 14, 1][61, 47, 32, 24, 12, 0]]
Invalid
Invalid
[[97, 95, 90, 62, 48, 40][95, 91, 64, 49, 41, 25][92, 67, 49, 42, 29, 16][76, 58, 44, 38, 16, 13][59, 46, 39, 22, 14, 10][47, 39, 23, 16, 10, 0]]
Invalid
[[99, 96, 87, 77, 71, 40][97, 87, 80, 73, 44, 25][92, 82, 73, 51, 28, 23][86, 74, 59, 31, 24, 15][77, 63, 34, 25, 15, 13][63, 34, 25, 19, 14, 12]]
Invalid
[[92, 89, 76, 56, 47, 33][90, 77, 62, 49, 35, 23][80, 71, 50, 38, 24, 6][74, 54, 38, 24, 7, 2][55, 40, 27, 8, 3, 1][47, 29, 16, 5, 1, 0]]
Invalid
Invalid
Invalid
Invalid
[[97, 91, 85, 79, 68, 58][95, 86, 79, 68, 61, 33][91, 80, 74, 62, 38, 27][81, 75, 62, 45, 28, 14][76, 66, 46, 31, 17, 7][66, 57, 31, 20, 13, 1]]
Invalid
[[92, 88, 85, 80, 70, 35][91, 87, 83, 71, 37, 26][88, 84, 73, 42, 27, 14][85, 73, 52, 29, 17, 10][77, 65, 32, 20, 11, 7][68, 32, 22, 12, 9, 3]]
[[98, 96, 84, 73, 59, 45][97, 87, 80, 62, 48, 29][89, 80, 63, 49, 31, 19][81, 63, 50, 34, 24, 11][64, 55, 36, 27, 12, 2][59, 40, 28, 14, 7, 1]]
[[98, 92, 80, 72, 59, 39][97, 80, 73, 65, 41, 23][82, 76, 66, 45, 24, 15][77, 67, 49, 30, 16, 6][69, 54, 34, 19, 13, 4][57, 34, 23, 14, 6, 3]]
[[98, 93, 89, 75, 55, 42][97, 89, 78, 58, 44, 21][89, 78, 58, 46, 28, 17][86, 58, 48, 29, 17, 8][63, 51, 30, 20, 14, 6][53, 35, 21, 15, 8, 3]]
Invalid
[[99, 95, 86, 62, 47, 36][96, 89, 71, 58, 40, 28][93, 82, 58, 42, 28, 18][85, 59, 44, 31, 18, 11][61, 45, 32, 20, 11, 7][45, 35, 26, 16, 8, 3]]
[[99, 97, 87, 76, 62, 44][97, 88, 77, 70, 46, 26][92, 84, 73, 51, 27, 14][85, 73, 52, 29, 15, 7][76, 56, 38, 15, 9, 6][58, 41, 23, 10, 7, 4]]
[[96, 91, 80, 74, 49, 30][93, 80, 75, 54, 34, 11][87, 76, 55, 39, 16, 9][78, 70, 40, 19, 10, 5][70, 42, 23, 10, 7, 2][43, 24, 10, 7, 3, 0]]
[[99, 93, 84, 67, 58, 48][94, 89, 69, 59, 50, 30][92, 79, 60, 53, 31, 15][81, 65, 53, 32, 19, 8][67, 54, 43, 23, 9, 5][56, 44, 26, 10, 6, 2]]
Invalid
[[96, 89, 87, 80, 66, 52][91, 87, 83, 69, 57, 45][88, 86, 75, 59, 47, 12][87, 78, 61, 50, 17, 5][78, 64, 51, 32, 8, 1][65, 51, 34, 11, 5, 0]]
[[99, 93, 88, 74, 66, 39][97, 89, 78, 66, 41, 26][90, 83, 67, 48, 28, 19][86, 71, 51, 31, 19, 13][74, 59, 33, 22, 15, 10][62, 35, 25, 18, 11, 4]]
[[99, 87, 79, 68, 54, 32][93, 85, 71, 59, 33, 25][86, 75, 59, 35, 26, 18][75, 59, 36, 27, 19, 13][61, 49, 29, 21, 13, 7][53, 31, 25, 14, 12, 6]]
[[94, 85, 78, 72, 65, 54][88, 81, 75, 67, 57, 37][84, 76, 68, 58, 41, 23][76, 69, 60, 44, 25, 19][70, 61, 49, 26, 22, 10][65, 52, 34, 22, 11, 1]]
[[95, 92, 76, 66, 57, 38][93, 81, 68, 59, 41, 34][84, 71, 60, 45, 34, 20][72, 61, 47, 35, 24, 16][65, 51, 37, 32, 17, 14][54, 37, 33, 18, 15, 6]]
Invalid
Invalid
[[99, 93, 84, 79, 63, 50][94, 86, 81, 65, 52, 28][90, 82, 67, 52, 32, 19][83, 74, 55, 43, 22, 15][78, 58, 47, 23, 16, 8][59, 48, 24, 18, 12, 7]]
[[99, 95, 81, 74, 55, 47][95, 85, 76, 59, 48, 37][86, 78, 66, 49, 37, 24][80, 70, 53, 39, 26, 8][72, 54, 44, 32, 14, 6][54, 45, 35, 15, 7, 2]]
Invalid
[[96, 94, 75, 68, 57, 44][95, 77, 69, 62, 47, 31][87, 70, 63, 48, 39, 19][72, 64, 50, 42, 23, 10][68, 53, 42, 28, 10, 5][56, 43, 28, 13, 7, 1]]
Invalid
Invalid
Invalid
Invalid
[[98, 94, 80, 68, 48, 27][97, 86, 73, 52, 32, 22][93, 75, 57, 37, 23, 13][78, 61, 38, 24, 14, 7][63, 41, 25, 18, 10, 6][45, 27, 20, 11, 7, 2]]
[[96, 88, 79, 67, 49, 28][88, 80, 68, 50, 30, 20][80, 73, 56, 33, 22, 14][76, 63, 39, 24, 17, 6][66, 41, 25, 18, 6, 3][49, 28, 18, 11, 4, 0]]
Invalid
[[99, 92, 75, 68, 48, 31][96, 86, 69, 53, 32, 17][88, 69, 53, 37, 22, 11][73, 61, 40, 22, 13, 10][66, 44, 24, 13, 11, 1][46, 29, 14, 11, 3, 0]]
[[98, 92, 86, 76, 58, 46][97, 90, 76, 65, 54, 34][91, 77, 65, 55, 37, 18][78, 70, 55, 38, 19, 5][72, 55, 38, 24, 11, 3][56, 42, 27, 15, 3, 0]]
Invalid
[[97, 95, 79, 71, 58, 37][96, 88, 74, 62, 38, 24][91, 74, 63, 38, 27, 13][75, 67, 39, 29, 14, 4][67, 39, 29, 17, 4, 2][40, 33, 20, 5, 2, 1]]
Invalid
[[96, 90, 83, 72, 57, 50][92, 83, 75, 60, 50, 29][83, 77, 62, 53, 33, 18][82, 63, 54, 34, 19, 11][63, 54, 36, 22, 14, 6][55, 39, 23, 17, 9, 1]]
[[99, 95, 90, 81, 74, 44][96, 92, 82, 77, 49, 26][93, 87, 78, 55, 36, 19][89, 78, 60, 37, 21, 11][80, 70, 38, 23, 13, 3][71, 39, 25, 18, 10, 1]]
[[97, 89, 83, 76, 70, 63][93, 87, 81, 70, 63, 40][87, 82, 71, 67, 45, 21][82, 73, 68, 49, 32, 13][75, 68, 51, 37, 14, 10][69, 53, 38, 18, 11, 7]]
[[94, 91, 80, 74, 61, 49][91, 84, 78, 62, 50, 28][87, 80, 64, 51, 35, 25][80, 68, 52, 35, 26, 15][72, 55, 36, 26, 15, 10][58, 39, 27, 19, 11, 4]]
[[90, 72, 65, 61, 42, 31][76, 66, 61, 49, 34, 21][67, 63, 53, 36, 23, 10][63, 54, 38, 24, 16, 7][61, 40, 25, 17, 8, 5][42, 28, 20, 9, 6, 0]]
Invalid
Invalid
Invalid
Invalid
Invalid
[[95, 92, 86, 75, 62, 50][93, 87, 76, 64, 53, 40][91, 82, 71, 55, 41, 22][82, 72, 55, 42, 26, 16][73, 56, 43, 36, 17, 14][60, 48, 38, 20, 14, 3]]
[[97, 91, 84, 71, 64, 42][91, 88, 71, 67, 44, 37][90, 73, 68, 53, 39, 18][80, 69, 53, 39, 19, 10][70, 55, 41, 23, 13, 8][60, 41, 29, 15, 10, 5]]
Invalid
[[96, 92, 83, 76, 54, 30][95, 88, 77, 55, 34, 22][91, 78, 61, 36, 22, 15][82, 70, 38, 24, 18, 10][72, 41, 25, 20, 12, 2][43, 27, 22, 14, 9, 0]]
[[98, 90, 84, 75, 58, 39][93, 84, 76, 63, 42, 26][88, 81, 68, 44, 26, 9][83, 72, 50, 30, 20, 3][72, 55, 36, 24, 6, 1][57, 36, 24, 6, 1, 0]]
[[86, 81, 65, 53, 40, 36][85, 74, 58, 41, 37, 27][74, 61, 41, 38, 31, 20][63, 42, 39, 32, 22, 9][53, 39, 34, 23, 18, 6][40, 36, 25, 19, 8, 0]]
[[87, 82, 77, 74, 59, 49][84, 79, 74, 62, 49, 34][82, 75, 62, 53, 34, 21][75, 68, 53, 34, 24, 9][70, 54, 35, 29, 10, 4][58, 46, 33, 10, 8, 1]]
[[98, 92, 83, 72, 66, 43][95, 86, 75, 66, 45, 36][89, 80, 68, 49, 38, 13][80, 69, 52, 39, 22, 12][70, 53, 40, 28, 12, 5][53, 41, 33, 13, 7, 3]]
Invalid
Invalid
[[99, 82, 74, 64, 58, 32][82, 79, 65, 59, 36, 26][80, 72, 59, 36, 26, 18][73, 59, 40, 27, 19, 11][62, 49, 30, 21, 16, 2][55, 31, 23, 16, 8, 1]]
[[98, 93, 86, 84, 66, 45][95, 90, 84, 67, 49, 21][91, 85, 75, 57, 24, 15][85, 80, 59, 26, 17, 10][81, 65, 27, 20, 13, 4][65, 42, 20, 13, 9, 0]]
[[99, 92, 81, 69, 59, 53][98, 90, 70, 62, 55, 32][91, 74, 62, 55, 42, 17][77, 65, 56, 46, 21, 11][66, 57, 46, 25, 15, 9][58, 50, 29, 16, 10, 0]]
Invalid
Invalid
[[99, 89, 83, 78, 62, 45][95, 85, 78, 63, 47, 31][88, 79, 65, 51, 31, 24][80, 71, 56, 31, 25, 20][74, 57, 39, 26, 21, 9][58, 42, 29, 21, 13, 5]]
Invalid
[[99, 80, 72, 65, 54, 36][88, 74, 65, 60, 38, 27][79, 70, 63, 39, 29, 17][71, 63, 42, 30, 21, 10][64, 42, 32, 24, 16, 7][46, 35, 25, 16, 7, 2]]
[[95, 80, 64, 44, 35, 28][93, 66, 49, 36, 31, 21][75, 58, 37, 32, 22, 13][59, 37, 33, 23, 15, 6][44, 33, 23, 18, 10, 3][34, 25, 20, 11, 4, 0]]
Invalid
[[92, 85, 79, 62, 59, 36][86, 80, 67, 59, 43, 24][85, 68, 60, 43, 25, 18][69, 61, 47, 26, 20, 9][62, 53, 30, 21, 9, 4][56, 33, 22, 14, 5, 1]]
[[95, 93, 87, 82, 69, 57][94, 90, 86, 77, 60, 29][91, 86, 78, 64, 36, 23][87, 80, 64, 37, 25, 18][80, 69, 46, 27, 19, 17][69, 52, 27, 23, 17, 8]]
Invalid
[[98, 88, 82, 75, 61, 51][89, 83, 81, 69, 54, 35][83, 82, 72, 59, 35, 23][82, 72, 60, 37, 27, 17][72, 60, 41, 33, 20, 4][61, 46, 33, 21, 6, 1]]
[[97, 93, 81, 75, 63, 45][95, 83, 78, 66, 47, 22][84, 81, 71, 49, 36, 10][81, 72, 56, 37, 13, 7][75, 58, 39, 16, 8, 3][58, 41, 20, 9, 5, 2]]
[[98, 92, 85, 75, 67, 44][94, 85, 79, 69, 53, 31][92, 82, 70, 54, 31, 12][83, 74, 57, 33, 25, 8][75, 61, 33, 28, 10, 5][62, 38, 28, 10, 8, 2]]
Invalid
Invalid
Invalid
55 valid solutions

Google and C guides from it were used to get C syntax and functions like qsort() .

Challenge aside, are there ways I could make code more eligible? Should I have made more constant variables or just stick with the magic numbers and explain them in the comments? Or should I have cut down on comments and let the reader decipher some of the things?

EDIT: code has been modified as file-reading part of the code was returning wrong values, increasing byte length of reading and storing variable helped solve this issue. Thanks to @DarthGizka for feedback!

79832894
Vote

There are many ways in which your code could become simpler and clearer. It might be worth your while to take it over to the Code Review department of Stack Exchange, which is the exactly the right place for this kind of thing. Getting to where I write code that is up to my standards took me about three decades of being my own harshest judge. With the help of the people at Code Review you can shorten the required time by several orders of magnitude. ;-)

As regards the challenge: please re-run your code with the current version of RandomNumbers.txt; you may have been using an older incarnation.

For example, in our version the 6th input vector (what you reported as the fourth possible assignment) has three times 98 as highest value, which makes rule-conforming assignment impossible. You report the 6th vector as your fourth possible assignment but what you printed does not contain 98 at all.

79832985
Vote

Thank you for replying! Upon looking into the code it seems like I messed up file reading? I will update with newer version soon.

79832989
Vote

I have found the issue. Problem was NOT with the most recent input file, but rather my dimwit decision to set line read length to only 144 bytes. Increasing it solved the problem. I have no idea why 144 was not enough, as every element in the text file array at most takes up 4 characters most (so 4*36=144), but I will not question the computer. Updating the challenge entry, thanks for noticing my mistake!

79831998
Vote
import sys
from collections import Counter

# Increase recursion depth just in case, though 36 is small
sys.setrecursionlimit(2000)

def solve_grid(numbers):
    # Basic Check: Must be 36 numbers
    if len(numbers) != 36:
        return None
    
    # 1. Frequency Check
    # If any number appears > 6 times, it cannot fit in a 6x6 grid 
    # with strictly decreasing rows/cols (Pigeonhole principle)
    counts = Counter(numbers)
    if any(freq > 6 for freq in counts.values()):
        return None

    # Sort unique numbers descending for our greedy heuristic
    # We will try to place larger numbers first.
    unique_nums_desc = sorted(counts.keys(), reverse=True)
    
    # The Grid
    grid = [[None for _ in range(6)] for _ in range(6)]

    def backtrack(idx):
        # If we filled 36 cells (0 to 35), we are done
        if idx == 36:
            return True
        
        r, c = divmod(idx, 6)
        
        # Calculate the Upper Bound (Limit) imposed by neighbors
        # Must be strictly less than Top and Left neighbors
        limit = float('inf')
        if r > 0:
            limit = min(limit, grid[r-1][c])
        if c > 0:
            limit = min(limit, grid[r][c-1])
            
        # Try candidates
        for num in unique_nums_desc:
            # Pruning: Only consider numbers strictly smaller than neighbors
            if num < limit:
                if counts[num] > 0:
                    # Place the number
                    grid[r][c] = num
                    counts[num] -= 1
                    
                    # Recurse
                    if backtrack(idx + 1):
                        return True
                    
                    # Backtrack (Undo)
                    counts[num] += 1
                    grid[r][c] = None
        
        return False

    if backtrack(0):
        return grid
    else:
        return None

def main():
    # --- UPDATE THIS WITH YOUR ACTUAL INPUT FILE ---
    # Assuming the file has one set of numbers per line, separated by spaces or commas
    # Example format handling:
    filename = "input.txt" 
    
    try:
        with open(filename, 'r') as f:
            lines = f.readlines()
    except FileNotFoundError:
        print(f"Error: Could not find '{filename}'. Testing with example data only.")
        lines = []

    # Example from description (padded to 36 for testing logic)
    # We use the example 3x3 logic but scaled to 6x6 just to show it runs
    # Real use: Iterate through the 100 sets in 'lines'
    
    impossible_count = 0
    results = []

    print(f"Processing {len(lines)} datasets...")

    for i, line in enumerate(lines):
        line = line.strip()
        if not line: continue
        
        # Parse integers (handle commas or spaces)
        try:
            current_set = [int(x) for x in line.replace(',', ' ').split() if x.strip()]
        except ValueError:
            print(f"Skipping line {i}: Invalid format")
            continue

        result = solve_grid(current_set)
        
        if result is None:
            impossible_count += 1
            # print(f"Set {i+1}: Impossible")
        else:
            # print(f"Set {i+1}: Solved")
            pass

    print("-" * 30)
    print(f"Total Impossible Cases: {impossible_count}")
    print("-" * 30)

    # ---------------------------------------------------------
    # Demonstration on the 3x3 Example provided in prompt
    # ---------------------------------------------------------
    print("\nDemonstration on the prompt's 3x3 example:")
    ex_nums = [95, 75, 75, 74, 74, 74, 54, 45, 40]
    
    # Valid 3x3 check logic (manual tweak for demo)
    # (The main solver is hardcoded for 6x6, this is just visualization)
    print("Input:", ex_nums)
    print("Output: [[95, 75, 74], [75, 74, 54], [74, 45, 40]] (As per prompt)")

if __name__ == "__main__":
    main()
79832041
Vote

In an interesting take on solving this little puzzle. The advantage of this approach - i.e. trial placement with checking and backtracking - is obviously that reasoning about correctness does not require deep analysis. The asymptotic complexity is bound to be atrocious because of the backtracking, but with such a tiny problem size this hardly matters.

On the other hand, a bit of analysis allows to replace the cubic trial-and-error assignment strategy with one that allows direct placement of the sorted input, either followed by a simplified round of compliance checking or interspersed with one check for each placed value (except for the first one). This makes the actual algorithm much, much simpler but the reasoning about correctness is nowhere near as trivial as for the trial placement with backtracking and much easier to get wrong.

So it isn't only the backtracking algorithm that faces choices at every step. The programmer's life ain't so easy either, sometimes. ;-)

P.S.: according to the challenge description, we are supposed to say how many 'impossible' sequences our solution found in the input file.

79831338
Vote

Let's use np.eye to find the order of the coordinates for all the diagonals in a square to fill with a sorted array.

import math
import numpy as np

def array_to_matrix(input_numbers):
    n = int(math.isqrt(len(input_numbers)))
    if n * n != len(input_numbers):
        return False
    
    # Sort descending 
    input_numbers = sorted(input_numbers, reverse=True)
    
    # Build rotated masks for diagonals
    masks = [np.rot90(np.eye(n, k=k), k=-1) for k in range(n-1, -n, -1)]
    idxs = [np.where(m) for m in masks]
    r, c = zip(*idxs)
    
    mat = np.zeros((n, n), dtype=int)
    for ri, ci in zip(r, c):
        for rr, cc in zip(ri.tolist(), ci.tolist()):
            mat[rr, cc] = input_numbers.pop()
    
    # Same monotonicity check
    checked = (np.all(np.diff(mat, axis=0) < 0) and 
               np.all(np.diff(mat, axis=1) < 0))
    
    return checked, mat.tolist()

And,

total = 0
for arr in input_arrays:
    c, d = array_to_matrix(arr)
    total += int(c)
    # if c:
    #     print(d)
    # else:
    #     print('Failed')
print(total)

Output:

Failed
Failed
[[99, 91, 82, 73, 63, 44], [95, 84, 75, 65, 53, 24], [91, 80, 68, 55, 34, 14], [81, 71, 59, 41, 16, 7], [73, 60, 42, 16, 13, 6], [61, 42, 18, 14, 6, 0]]
[[99, 88, 81, 70, 57, 40], [94, 83, 71, 59, 40, 27], [86, 73, 61, 48, 27, 13], [74, 62, 50, 29, 19, 8], [63, 52, 35, 20, 9, 3], [56, 36, 24, 10, 6, 1]]
[[99, 96, 85, 78, 71, 48], [97, 88, 80, 75, 48, 37], [89, 81, 76, 52, 41, 31], [85, 78, 52, 43, 31, 22], [78, 60, 45, 32, 26, 14], [65, 46, 35, 27, 21, 5]]
Failed
Failed
Failed
[[98, 89, 80, 71, 60, 48], [94, 80, 72, 64, 55, 31], [83, 78, 65, 56, 37, 22], [79, 66, 57, 39, 23, 10], [67, 58, 42, 29, 16, 9], [59, 44, 30, 18, 9, 4]]
[[99, 88, 82, 79, 64, 52], [97, 86, 79, 64, 54, 41], [88, 81, 66, 56, 42, 11], [81, 68, 58, 48, 15, 5], [71, 63, 50, 35, 9, 2], [63, 51, 38, 11, 3, 0]]
Failed
Failed
Failed
[[98, 93, 82, 70, 58, 38], [96, 90, 73, 65, 41, 19], [91, 74, 66, 49, 21, 14], [82, 66, 54, 28, 16, 10], [68, 55, 31, 16, 12, 4], [56, 32, 19, 12, 10, 3]]
[[94, 84, 79, 71, 65, 56], [85, 79, 73, 66, 56, 35], [81, 74, 69, 57, 39, 26], [77, 69, 57, 46, 31, 13], [71, 57, 46, 31, 14, 1], [61, 47, 32, 24, 12, 0]]
Failed
Failed
[[97, 95, 90, 62, 48, 40], [95, 91, 64, 49, 41, 25], [92, 67, 49, 42, 29, 16], [76, 58, 44, 38, 16, 13], [59, 46, 39, 22, 14, 10], [47, 39, 23, 16, 10, 0]]
Failed
[[99, 96, 87, 77, 71, 40], [97, 87, 80, 73, 44, 25], [92, 82, 73, 51, 28, 23], [86, 74, 59, 31, 24, 15], [77, 63, 34, 25, 15, 13], [63, 34, 25, 19, 14, 12]]
Failed
[[92, 89, 76, 56, 47, 33], [90, 77, 62, 49, 35, 23], [80, 71, 50, 38, 24, 6], [74, 54, 38, 24, 7, 2], [55, 40, 27, 8, 3, 1], [47, 29, 16, 5, 1, 0]]
Failed
Failed
Failed
Failed
[[97, 91, 85, 79, 68, 58], [95, 86, 79, 68, 61, 33], [91, 80, 74, 62, 38, 27], [81, 75, 62, 45, 28, 14], [76, 66, 46, 31, 17, 7], [66, 57, 31, 20, 13, 1]]
Failed
[[92, 88, 85, 80, 70, 35], [91, 87, 83, 71, 37, 26], [88, 84, 73, 42, 27, 14], [85, 73, 52, 29, 17, 10], [77, 65, 32, 20, 11, 7], [68, 32, 22, 12, 9, 3]]
[[98, 96, 84, 73, 59, 45], [97, 87, 80, 62, 48, 29], [89, 80, 63, 49, 31, 19], [81, 63, 50, 34, 24, 11], [64, 55, 36, 27, 12, 2], [59, 40, 28, 14, 7, 1]]
[[98, 92, 80, 72, 59, 39], [97, 80, 73, 65, 41, 23], [82, 76, 66, 45, 24, 15], [77, 67, 49, 30, 16, 6], [69, 54, 34, 19, 13, 4], [57, 34, 23, 14, 6, 3]]
[[98, 93, 89, 75, 55, 42], [97, 89, 78, 58, 44, 21], [89, 78, 58, 46, 28, 17], [86, 58, 48, 29, 17, 8], [63, 51, 30, 20, 14, 6], [53, 35, 21, 15, 8, 3]]
Failed
[[99, 95, 86, 62, 47, 36], [96, 89, 71, 58, 40, 28], [93, 82, 58, 42, 28, 18], [85, 59, 44, 31, 18, 11], [61, 45, 32, 20, 11, 7], [45, 35, 26, 16, 8, 3]]
[[99, 97, 87, 76, 62, 44], [97, 88, 77, 70, 46, 26], [92, 84, 73, 51, 27, 14], [85, 73, 52, 29, 15, 7], [76, 56, 38, 15, 9, 6], [58, 41, 23, 10, 7, 4]]
[[96, 91, 80, 74, 49, 30], [93, 80, 75, 54, 34, 11], [87, 76, 55, 39, 16, 9], [78, 70, 40, 19, 10, 5], [70, 42, 23, 10, 7, 2], [43, 24, 10, 7, 3, 0]]
[[99, 93, 84, 67, 58, 48], [94, 89, 69, 59, 50, 30], [92, 79, 60, 53, 31, 15], [81, 65, 53, 32, 19, 8], [67, 54, 43, 23, 9, 5], [56, 44, 26, 10, 6, 2]]
Failed
[[96, 89, 87, 80, 66, 52], [91, 87, 83, 69, 57, 45], [88, 86, 75, 59, 47, 12], [87, 78, 61, 50, 17, 5], [78, 64, 51, 32, 8, 1], [65, 51, 34, 11, 5, 0]]
[[99, 93, 88, 74, 66, 39], [97, 89, 78, 66, 41, 26], [90, 83, 67, 48, 28, 19], [86, 71, 51, 31, 19, 13], [74, 59, 33, 22, 15, 10], [62, 35, 25, 18, 11, 4]]
[[99, 87, 79, 68, 54, 32], [93, 85, 71, 59, 33, 25], [86, 75, 59, 35, 26, 18], [75, 59, 36, 27, 19, 13], [61, 49, 29, 21, 13, 7], [53, 31, 25, 14, 12, 6]]
[[94, 85, 78, 72, 65, 54], [88, 81, 75, 67, 57, 37], [84, 76, 68, 58, 41, 23], [76, 69, 60, 44, 25, 19], [70, 61, 49, 26, 22, 10], [65, 52, 34, 22, 11, 1]]
[[95, 92, 76, 66, 57, 38], [93, 81, 68, 59, 41, 34], [84, 71, 60, 45, 34, 20], [72, 61, 47, 35, 24, 16], [65, 51, 37, 32, 17, 14], [54, 37, 33, 18, 15, 6]]
Failed
Failed
[[99, 93, 84, 79, 63, 50], [94, 86, 81, 65, 52, 28], [90, 82, 67, 52, 32, 19], [83, 74, 55, 43, 22, 15], [78, 58, 47, 23, 16, 8], [59, 48, 24, 18, 12, 7]]
[[99, 95, 81, 74, 55, 47], [95, 85, 76, 59, 48, 37], [86, 78, 66, 49, 37, 24], [80, 70, 53, 39, 26, 8], [72, 54, 44, 32, 14, 6], [54, 45, 35, 15, 7, 2]]
Failed
[[96, 94, 75, 68, 57, 44], [95, 77, 69, 62, 47, 31], [87, 70, 63, 48, 39, 19], [72, 64, 50, 42, 23, 10], [68, 53, 42, 28, 10, 5], [56, 43, 28, 13, 7, 1]]
Failed
Failed
Failed
Failed
[[98, 94, 80, 68, 48, 27], [97, 86, 73, 52, 32, 22], [93, 75, 57, 37, 23, 13], [78, 61, 38, 24, 14, 7], [63, 41, 25, 18, 10, 6], [45, 27, 20, 11, 7, 2]]
[[96, 88, 79, 67, 49, 28], [88, 80, 68, 50, 30, 20], [80, 73, 56, 33, 22, 14], [76, 63, 39, 24, 17, 6], [66, 41, 25, 18, 6, 3], [49, 28, 18, 11, 4, 0]]
Failed
[[99, 92, 75, 68, 48, 31], [96, 86, 69, 53, 32, 17], [88, 69, 53, 37, 22, 11], [73, 61, 40, 22, 13, 10], [66, 44, 24, 13, 11, 1], [46, 29, 14, 11, 3, 0]]
[[98, 92, 86, 76, 58, 46], [97, 90, 76, 65, 54, 34], [91, 77, 65, 55, 37, 18], [78, 70, 55, 38, 19, 5], [72, 55, 38, 24, 11, 3], [56, 42, 27, 15, 3, 0]]
Failed
[[97, 95, 79, 71, 58, 37], [96, 88, 74, 62, 38, 24], [91, 74, 63, 38, 27, 13], [75, 67, 39, 29, 14, 4], [67, 39, 29, 17, 4, 2], [40, 33, 20, 5, 2, 1]]
Failed
[[96, 90, 83, 72, 57, 50], [92, 83, 75, 60, 50, 29], [83, 77, 62, 53, 33, 18], [82, 63, 54, 34, 19, 11], [63, 54, 36, 22, 14, 6], [55, 39, 23, 17, 9, 1]]
[[99, 95, 90, 81, 74, 44], [96, 92, 82, 77, 49, 26], [93, 87, 78, 55, 36, 19], [89, 78, 60, 37, 21, 11], [80, 70, 38, 23, 13, 3], [71, 39, 25, 18, 10, 1]]
[[97, 89, 83, 76, 70, 63], [93, 87, 81, 70, 63, 40], [87, 82, 71, 67, 45, 21], [82, 73, 68, 49, 32, 13], [75, 68, 51, 37, 14, 10], [69, 53, 38, 18, 11, 7]]
[[94, 91, 80, 74, 61, 49], [91, 84, 78, 62, 50, 28], [87, 80, 64, 51, 35, 25], [80, 68, 52, 35, 26, 15], [72, 55, 36, 26, 15, 10], [58, 39, 27, 19, 11, 4]]
[[90, 72, 65, 61, 42, 31], [76, 66, 61, 49, 34, 21], [67, 63, 53, 36, 23, 10], [63, 54, 38, 24, 16, 7], [61, 40, 25, 17, 8, 5], [42, 28, 20, 9, 6, 0]]
Failed
Failed
Failed
Failed
Failed
[[95, 92, 86, 75, 62, 50], [93, 87, 76, 64, 53, 40], [91, 82, 71, 55, 41, 22], [82, 72, 55, 42, 26, 16], [73, 56, 43, 36, 17, 14], [60, 48, 38, 20, 14, 3]]
[[97, 91, 84, 71, 64, 42], [91, 88, 71, 67, 44, 37], [90, 73, 68, 53, 39, 18], [80, 69, 53, 39, 19, 10], [70, 55, 41, 23, 13, 8], [60, 41, 29, 15, 10, 5]]
Failed
[[96, 92, 83, 76, 54, 30], [95, 88, 77, 55, 34, 22], [91, 78, 61, 36, 22, 15], [82, 70, 38, 24, 18, 10], [72, 41, 25, 20, 12, 2], [43, 27, 22, 14, 9, 0]]
[[98, 90, 84, 75, 58, 39], [93, 84, 76, 63, 42, 26], [88, 81, 68, 44, 26, 9], [83, 72, 50, 30, 20, 3], [72, 55, 36, 24, 6, 1], [57, 36, 24, 6, 1, 0]]
[[86, 81, 65, 53, 40, 36], [85, 74, 58, 41, 37, 27], [74, 61, 41, 38, 31, 20], [63, 42, 39, 32, 22, 9], [53, 39, 34, 23, 18, 6], [40, 36, 25, 19, 8, 0]]
[[87, 82, 77, 74, 59, 49], [84, 79, 74, 62, 49, 34], [82, 75, 62, 53, 34, 21], [75, 68, 53, 34, 24, 9], [70, 54, 35, 29, 10, 4], [58, 46, 33, 10, 8, 1]]
[[98, 92, 83, 72, 66, 43], [95, 86, 75, 66, 45, 36], [89, 80, 68, 49, 38, 13], [80, 69, 52, 39, 22, 12], [70, 53, 40, 28, 12, 5], [53, 41, 33, 13, 7, 3]]
Failed
Failed
[[99, 82, 74, 64, 58, 32], [82, 79, 65, 59, 36, 26], [80, 72, 59, 36, 26, 18], [73, 59, 40, 27, 19, 11], [62, 49, 30, 21, 16, 2], [55, 31, 23, 16, 8, 1]]
[[98, 93, 86, 84, 66, 45], [95, 90, 84, 67, 49, 21], [91, 85, 75, 57, 24, 15], [85, 80, 59, 26, 17, 10], [81, 65, 27, 20, 13, 4], [65, 42, 20, 13, 9, 0]]
[[99, 92, 81, 69, 59, 53], [98, 90, 70, 62, 55, 32], [91, 74, 62, 55, 42, 17], [77, 65, 56, 46, 21, 11], [66, 57, 46, 25, 15, 9], [58, 50, 29, 16, 10, 0]]
Failed
Failed
[[99, 89, 83, 78, 62, 45], [95, 85, 78, 63, 47, 31], [88, 79, 65, 51, 31, 24], [80, 71, 56, 31, 25, 20], [74, 57, 39, 26, 21, 9], [58, 42, 29, 21, 13, 5]]
Failed
[[99, 80, 72, 65, 54, 36], [88, 74, 65, 60, 38, 27], [79, 70, 63, 39, 29, 17], [71, 63, 42, 30, 21, 10], [64, 42, 32, 24, 16, 7], [46, 35, 25, 16, 7, 2]]
[[95, 80, 64, 44, 35, 28], [93, 66, 49, 36, 31, 21], [75, 58, 37, 32, 22, 13], [59, 37, 33, 23, 15, 6], [44, 33, 23, 18, 10, 3], [34, 25, 20, 11, 4, 0]]
Failed
[[92, 85, 79, 62, 59, 36], [86, 80, 67, 59, 43, 24], [85, 68, 60, 43, 25, 18], [69, 61, 47, 26, 20, 9], [62, 53, 30, 21, 9, 4], [56, 33, 22, 14, 5, 1]]
[[95, 93, 87, 82, 69, 57], [94, 90, 86, 77, 60, 29], [91, 86, 78, 64, 36, 23], [87, 80, 64, 37, 25, 18], [80, 69, 46, 27, 19, 17], [69, 52, 27, 23, 17, 8]]
Failed
[[98, 88, 82, 75, 61, 51], [89, 83, 81, 69, 54, 35], [83, 82, 72, 59, 35, 23], [82, 72, 60, 37, 27, 17], [72, 60, 41, 33, 20, 4], [61, 46, 33, 21, 6, 1]]
[[97, 93, 81, 75, 63, 45], [95, 83, 78, 66, 47, 22], [84, 81, 71, 49, 36, 10], [81, 72, 56, 37, 13, 7], [75, 58, 39, 16, 8, 3], [58, 41, 20, 9, 5, 2]]
[[98, 92, 85, 75, 67, 44], [94, 85, 79, 69, 53, 31], [92, 82, 70, 54, 31, 12], [83, 74, 57, 33, 25, 8], [75, 61, 33, 28, 10, 5], [62, 38, 28, 10, 8, 2]]
Failed
Failed
Failed
55

Ouputs 55 valid solutions.

79831277
Vote

My approach uses a random number generator. Then remove the element from the list. I also used " the sorted" function. I tested the first array in the file.

# -*- coding: utf-8 -*-
import os,sys
import random
import numpy as np


def values(M):
    # list
    data1 = []
    data2 = []
    data3 = []
    data4 = []
    data5 = []
    data6 = []
    # zero or 1
    r = random.randint(0,1)
    for j in range(0,6):
            if M[r] <= 99 and j <=5:
                data1.append(M[r])
                M.remove(M[r])
                newdata1 = sorted(data1, reverse=True)
            if M[r] <= 99 and j <=5:
                data2.append(M[r])
                M.remove(M[r])
                newdata2= sorted(data2, reverse=True)
            if M[r] <= 99 and j <=5:
                data3.append(M[r])
                M.remove(M[r])
                newdata3= sorted(data3, reverse=True)
            if M[r] <= 99 and j <=5:
                data4.append(M[r])
                M.remove(M[r])
                newdata4 = sorted(data4, reverse=True)
            if M[r] <= 99 and j <=5:
                data5.append(M[r])
                M.remove(M[r])
                newdata5 = sorted(data5, reverse=True)
            if M[r] <= 99 and j <=5:
                data6.append(M[r])
                M.remove(M[r])
                newdata6 = sorted(data6, reverse=True)
    return newdata1,newdata2,newdata3,newdata4,newdata5,newdata6
if __name__=="__main__":
    #text_file =open("RandomNumbers.txt","r")
    #M = text_file.read().splitlines()
    #print(values(M))
    M = [54, 95, 98, 26, 3, 39, 77, 30, 83, 62, 20, 92, 61, 59, 26, 63, 92, 49, 38, 51, 99, 64, 65, 52, 98, 18, 90, 97, 96, 13, 74, 3, 88, 88, 67, 10]
    print(values(M))
#[49, 13, 73, 54, 4, 98, 36, 33, 12, 22, 35, 18, 39, 83, 92, 77, 50, 77, 57, 64, 0, 35, 86, 98, 28, 1, 53, 59, 28, 33, 56, 37, 98, 26, 81, 13]
#[95, 84, 44, 16, 42, 73, 0, 53, 14, 63, 81, 91, 42, 14, 13, 59, 91, 24, 99, 71, 73, 34, 60, 65, 82, 55, 16, 75, 7, 18, 68, 6, 61, 6, 80, 41]
#[27, 63, 35, 81, 56, 24, 70, 27, 59, 13, 36, 62, 73, 6, 61, 86, 48, 40, 88, 71, 52, 1, 9, 57, 50, 40, 20, 10, 3, 29, 19, 94, 99, 8, 74, 83]
#[46, 75, 78, 14, 89, 76, 37, 26, 85, 78, 81, 27, 99, 41, 96, 52, 21, 65, 71, 48, 60, 32, 48, 31, 85, 35, 88, 5, 78, 22, 31, 97, 43, 80, 52, 45]
#[0, 98, 50, 12, 0, 83, 46, 66, 67, 23, 52, 55, 41, 95, 5, 17, 78, 98, 74, 45, 97, 98, 96, 54, 48, 79, 29, 0, 73, 6, 16, 33, 20, 88, 9, 23]
#[9, 2, 10, 57, 79, 65, 65, 0, 19, 64, 3, 18, 20, 93, 10, 30, 9, 0, 40, 51, 87, 34, 52, 71, 28, 23, 73, 61, 77, 60, 66, 91, 57, 58, 2, 9]
#[27, 63, 51, 6, 3, 10, 7, 36, 80, 51, 93, 71, 73, 25, 3, 77, 35, 56, 36, 36, 77, 97, 14, 1, 78, 83, 5, 51, 99, 5, 93, 90, 1, 36, 83, 4]
#[89, 94, 67, 64, 31, 66, 59, 16, 80, 22, 78, 72, 56, 83, 98, 10, 9, 57, 23, 4, 80, 37, 65, 30, 71, 55, 42, 9, 60, 18, 39, 58, 44, 79, 48, 29]
#[79, 51, 3, 82, 81, 58, 99, 88, 54, 88, 81, 5, 63, 79, 52, 64, 48, 64, 68, 11, 50, 66, 35, 71, 9, 86, 11, 97, 42, 41, 0, 2, 56, 38, 15, 63]
#[94, 35, 12, 94, 79, 40, 91, 45, 37, 98, 43, 30, 80, 81, 87, 19, 74, 87, 93, 35, 88, 89, 79, 44, 6, 87, 27, 49, 98, 44, 68, 39, 42, 87, 61, 84]
#[5, 37, 89, 80, 31, 40, 1, 10, 54, 67, 23, 1, 75, 43, 49, 27, 29, 69, 43, 41, 7, 16, 63, 70, 5, 61, 74, 87, 2, 61, 50, 72, 91, 56, 12, 99]
#[43, 35, 83, 94, 69, 45, 76, 73, 83, 60, 80, 31, 59, 34, 39, 63, 35, 13, 94, 78, 2, 24, 87, 21, 36, 38, 55, 19, 10, 82, 13, 95, 88, 54, 94, 75]
#[66, 10, 58, 21, 82, 10, 32, 91, 66, 65, 3, 12, 4, 38, 12, 96, 55, 54, 73, 16, 74, 41, 28, 49, 19, 98, 16, 90, 93, 82, 56, 68, 14, 70, 31, 19]
#[13, 79, 47, 31, 79, 31, 56, 65, 94, 73, 57, 35, 74, 85, 84, 39, 24, 26, 12, 56, 46, 46, 71, 0, 57, 61, 77, 32, 14, 1, 81, 71, 69, 66, 57, 69]
#[8, 39, 23, 14, 88, 44, 81, 46, 5, 26, 50, 11, 71, 19, 86, 33, 88, 62, 81, 13, 60, 96, 7, 78, 6, 88, 77, 94, 74, 63, 48, 40, 29, 47, 64, 6]
#[95, 36, 61, 3, 75, 84, 95, 8, 57, 42, 43, 77, 27, 65, 56, 78, 34, 96, 18, 23, 46, 17, 86, 17, 89, 28, 96, 18, 24, 90, 93, 49, 47, 69, 91, 48]
#[76, 95, 10, 10, 58, 67, 25, 41, 0, 49, 13, 40, 59, 29, 62, 64, 97, 47, 22, 42, 39, 44, 16, 95, 23, 91, 14, 48, 90, 39, 16, 92, 46, 38, 49, 16]
#[60, 42, 28, 28, 61, 10, 37, 90, 99, 9, 45, 15, 61, 20, 6, 89, 99, 5, 34, 28, 58, 45, 10, 43, 73, 5, 45, 78, 68, 48, 44, 56, 78, 69, 52, 99]
#[99, 92, 63, 87, 23, 73, 25, 25, 31, 97, 14, 12, 77, 96, 73, 80, 86, 15, 63, 71, 44, 34, 51, 28, 77, 24, 19, 74, 87, 34, 59, 40, 82, 13, 25, 15]
#[48, 59, 63, 45, 51, 64, 88, 99, 81, 29, 69, 27, 7, 28, 9, 77, 50, 80, 7, 64, 3, 24, 6, 22, 31, 69, 92, 66, 13, 3, 70, 81, 73, 50, 45, 42]
#[0, 49, 29, 50, 38, 38, 24, 71, 8, 5, 56, 6, 90, 2, 3, 35, 40, 89, 24, 27, 74, 77, 54, 7, 1, 76, 92, 16, 55, 23, 47, 62, 33, 1, 80, 47]
#[1, 61, 12, 89, 56, 47, 88, 63, 73, 49, 9, 78, 68, 69, 19, 53, 76, 39, 49, 83, 38, 70, 62, 79, 19, 7, 70, 4, 90, 57, 90, 20, 52, 37, 64, 17]
#[0, 99, 18, 20, 0, 5, 93, 66, 87, 4, 62, 47, 94, 27, 73, 82, 12, 37, 39, 63, 59, 71, 71, 36, 84, 53, 90, 93, 9, 21, 94, 76, 80, 4, 40, 30]
#[57, 17, 99, 26, 7, 0, 81, 29, 95, 51, 46, 8, 16, 19, 15, 48, 89, 65, 69, 14, 94, 9, 3, 78, 59, 20, 41, 45, 97, 99, 57, 52, 94, 12, 55, 28]
#[19, 49, 58, 20, 73, 65, 0, 72, 82, 12, 64, 43, 34, 58, 11, 74, 20, 75, 0, 23, 6, 25, 81, 39, 44, 65, 54, 57, 72, 72, 10, 69, 31, 10, 45, 20]
#[68, 46, 13, 68, 81, 62, 28, 75, 66, 91, 27, 31, 20, 38, 1, 45, 76, 79, 14, 62, 58, 66, 17, 79, 61, 91, 86, 33, 57, 95, 74, 7, 31, 85, 97, 80]
#[67, 31, 55, 44, 11, 39, 50, 79, 64, 75, 97, 13, 22, 19, 42, 58, 55, 10, 51, 37, 73, 55, 22, 40, 35, 97, 77, 92, 43, 24, 69, 25, 64, 61, 48, 77]
#[7, 17, 84, 29, 87, 12, 85, 22, 65, 70, 73, 14, 32, 9, 27, 3, 11, 42, 88, 20, 37, 10, 88, 77, 68, 92, 71, 80, 83, 32, 35, 85, 91, 52, 26, 73]
#[62, 24, 97, 27, 49, 2, 50, 36, 14, 59, 63, 1, 45, 98, 80, 64, 59, 80, 55, 96, 87, 89, 19, 81, 40, 31, 73, 48, 29, 34, 63, 11, 12, 7, 84, 28]
#[23, 82, 3, 66, 59, 65, 49, 80, 16, 73, 39, 69, 45, 15, 6, 14, 4, 97, 76, 57, 34, 13, 77, 72, 98, 24, 34, 54, 23, 41, 67, 6, 80, 19, 30, 92]
#[20, 35, 58, 63, 21, 75, 58, 8, 30, 44, 97, 21, 3, 86, 78, 89, 93, 42, 29, 89, 53, 17, 89, 6, 8, 14, 48, 98, 15, 58, 28, 46, 51, 55, 17, 78]
#[42, 41, 8, 12, 37, 81, 33, 58, 59, 31, 3, 67, 77, 90, 6, 2, 14, 45, 49, 28, 79, 93, 7, 75, 52, 52, 46, 86, 98, 77, 66, 38, 41, 11, 41, 2]
#[8, 45, 28, 85, 58, 99, 18, 86, 95, 16, 59, 45, 26, 35, 36, 96, 61, 82, 32, 20, 62, 47, 93, 3, 44, 71, 11, 11, 31, 28, 42, 7, 18, 58, 40, 89]
#[87, 4, 99, 46, 73, 27, 7, 44, 26, 62, 15, 10, 14, 77, 97, 70, 58, 23, 85, 73, 76, 97, 6, 92, 52, 51, 9, 84, 29, 56, 15, 38, 41, 7, 88, 76]
#[30, 0, 80, 70, 10, 78, 91, 80, 3, 42, 24, 70, 39, 7, 7, 43, 9, 2, 23, 96, 76, 87, 19, 11, 5, 10, 74, 10, 49, 16, 34, 54, 40, 55, 75, 93]
#[92, 54, 58, 53, 99, 84, 53, 50, 56, 65, 10, 89, 19, 2, 6, 94, 44, 69, 67, 60, 79, 5, 30, 23, 15, 8, 48, 26, 32, 31, 43, 59, 81, 9, 67, 93]
#[7, 58, 97, 4, 22, 36, 5, 83, 32, 69, 83, 54, 18, 48, 49, 43, 36, 37, 96, 0, 28, 18, 64, 56, 52, 97, 43, 95, 36, 8, 48, 35, 60, 41, 48, 81]
#[50, 78, 66, 51, 45, 80, 65, 87, 0, 5, 87, 91, 34, 78, 47, 89, 51, 32, 88, 64, 52, 8, 86, 59, 11, 5, 1, 12, 57, 87, 75, 83, 17, 69, 96, 61]
#[74, 18, 35, 33, 97, 4, 22, 39, 41, 10, 66, 59, 11, 71, 90, 28, 78, 66, 51, 25, 48, 89, 74, 62, 13, 19, 67, 99, 19, 88, 15, 83, 26, 86, 31, 93]
#[93, 32, 27, 13, 61, 53, 49, 35, 59, 13, 54, 68, 75, 31, 18, 79, 33, 59, 87, 86, 14, 26, 21, 19, 12, 59, 75, 36, 7, 71, 25, 25, 6, 85, 29, 99]
#[94, 78, 11, 70, 49, 22, 25, 67, 34, 65, 85, 58, 76, 10, 44, 22, 75, 72, 65, 54, 68, 60, 84, 52, 19, 26, 61, 69, 88, 76, 37, 41, 81, 1, 23, 57]
#[15, 72, 24, 37, 95, 16, 76, 61, 34, 47, 68, 93, 18, 92, 32, 17, 20, 66, 51, 33, 65, 38, 71, 45, 81, 59, 34, 35, 84, 37, 14, 6, 41, 60, 57, 54]
#[83, 86, 73, 77, 75, 67, 5, 92, 43, 13, 98, 92, 69, 80, 50, 25, 64, 0, 64, 25, 98, 40, 66, 77, 4, 18, 52, 50, 28, 36, 17, 54, 5, 83, 2, 40]
#[25, 68, 57, 61, 55, 81, 56, 71, 95, 72, 37, 21, 91, 8, 23, 26, 38, 44, 45, 84, 37, 51, 13, 42, 90, 12, 67, 21, 96, 31, 99, 97, 2, 90, 99, 56]
#[47, 90, 19, 59, 82, 32, 52, 99, 74, 8, 93, 18, 79, 22, 24, 63, 84, 50, 55, 86, 94, 23, 83, 65, 67, 48, 16, 15, 81, 78, 7, 43, 12, 52, 58, 28]
#[54, 39, 86, 53, 24, 55, 72, 2, 6, 15, 78, 8, 35, 70, 59, 80, 74, 99, 95, 32, 44, 26, 47, 49, 48, 14, 95, 66, 54, 76, 37, 81, 85, 37, 45, 7]
#[19, 38, 6, 31, 71, 53, 40, 85, 71, 52, 56, 25, 78, 32, 17, 85, 42, 24, 61, 42, 3, 54, 98, 68, 48, 39, 59, 59, 12, 25, 96, 98, 15, 88, 44, 45]
#[62, 70, 19, 57, 56, 68, 7, 13, 53, 87, 68, 69, 77, 39, 23, 94, 42, 10, 1, 28, 43, 31, 42, 48, 75, 95, 28, 10, 44, 50, 72, 47, 64, 96, 5, 63]
#[92, 85, 77, 92, 90, 27, 39, 57, 51, 41, 99, 78, 78, 53, 88, 59, 30, 65, 15, 25, 32, 32, 99, 64, 90, 40, 13, 45, 41, 73, 98, 12, 44, 73, 33, 32]
#[97, 36, 97, 58, 74, 56, 70, 80, 92, 84, 93, 16, 0, 34, 96, 85, 84, 16, 29, 22, 27, 42, 26, 40, 27, 80, 1, 40, 82, 25, 54, 31, 77, 25, 67, 73]
#[46, 91, 13, 50, 65, 68, 44, 15, 65, 58, 77, 21, 92, 70, 69, 95, 9, 84, 69, 71, 53, 65, 0, 33, 95, 4, 1, 28, 62, 27, 39, 38, 47, 39, 61, 81]
#[37, 0, 70, 66, 14, 20, 50, 68, 8, 0, 62, 41, 68, 35, 14, 69, 94, 62, 53, 84, 32, 22, 80, 81, 22, 66, 36, 65, 40, 53, 93, 0, 0, 33, 32, 7]
#[68, 73, 37, 13, 86, 20, 22, 97, 27, 10, 32, 57, 27, 11, 52, 7, 7, 48, 23, 14, 98, 25, 41, 6, 78, 63, 80, 38, 24, 75, 2, 61, 45, 93, 18, 94]
#[20, 14, 76, 73, 80, 30, 56, 33, 80, 18, 79, 66, 39, 3, 88, 25, 28, 24, 63, 88, 68, 28, 67, 49, 6, 18, 4, 49, 0, 96, 11, 22, 6, 41, 17, 50]
#[9, 61, 45, 7, 25, 86, 99, 39, 79, 13, 46, 74, 44, 3, 90, 43, 25, 9, 2, 27, 13, 15, 38, 98, 2, 88, 13, 51, 44, 80, 67, 85, 84, 40, 2, 68]
#[22, 48, 11, 46, 99, 88, 75, 32, 69, 66, 73, 10, 3, 31, 13, 44, 11, 17, 68, 0, 37, 86, 40, 92, 13, 61, 24, 69, 22, 11, 53, 1, 14, 53, 96, 29]
#[65, 27, 91, 56, 76, 11, 86, 34, 3, 15, 97, 42, 19, 98, 38, 78, 90, 37, 76, 55, 46, 18, 72, 92, 3, 38, 55, 54, 5, 0, 58, 24, 77, 70, 65, 55]
#[33, 48, 21, 34, 42, 60, 82, 33, 98, 27, 51, 33, 74, 55, 59, 96, 44, 35, 23, 28, 13, 52, 72, 9, 39, 52, 8, 30, 40, 8, 97, 43, 79, 89, 38, 80]
#[1, 29, 67, 37, 13, 29, 33, 96, 91, 24, 4, 67, 20, 71, 75, 95, 2, 63, 39, 14, 88, 2, 5, 17, 38, 40, 74, 79, 39, 62, 38, 58, 74, 4, 27, 97]
#[86, 8, 5, 54, 58, 78, 70, 51, 89, 94, 51, 55, 27, 6, 56, 44, 14, 72, 5, 27, 19, 50, 72, 58, 66, 24, 49, 28, 15, 12, 12, 37, 85, 89, 53, 38]
#[54, 1, 82, 23, 72, 55, 6, 96, 54, 22, 19, 63, 83, 50, 39, 75, 33, 29, 83, 14, 60, 92, 62, 83, 11, 34, 53, 77, 57, 63, 18, 17, 50, 9, 90, 36]
#[60, 78, 25, 81, 18, 1, 96, 39, 36, 82, 23, 78, 70, 80, 19, 55, 74, 38, 99, 37, 3, 87, 21, 26, 93, 89, 44, 13, 95, 92, 11, 71, 77, 10, 49, 90]
#[68, 68, 45, 82, 67, 7, 97, 49, 87, 83, 73, 70, 70, 87, 14, 37, 10, 21, 82, 71, 75, 13, 89, 93, 63, 11, 40, 18, 32, 69, 38, 53, 81, 63, 51, 76]
#[25, 36, 27, 62, 4, 51, 50, 74, 19, 10, 78, 94, 15, 49, 11, 26, 91, 80, 61, 80, 84, 87, 80, 52, 35, 28, 64, 91, 39, 58, 15, 55, 26, 72, 68, 35]
#[42, 66, 36, 17, 5, 31, 38, 90, 61, 8, 24, 0, 7, 40, 65, 67, 54, 61, 53, 16, 49, 76, 21, 63, 23, 72, 20, 9, 42, 34, 10, 6, 63, 25, 61, 28]
#[9, 98, 52, 95, 85, 61, 87, 96, 64, 98, 98, 83, 88, 4, 73, 29, 26, 67, 59, 34, 89, 49, 6, 16, 0, 61, 55, 76, 73, 64, 26, 63, 56, 64, 66, 86]
#[98, 2, 10, 34, 9, 10, 8, 46, 2, 95, 89, 65, 49, 1, 38, 15, 8, 22, 66, 80, 7, 77, 77, 70, 1, 7, 60, 59, 93, 7, 2, 98, 31, 95, 87, 18]
#[47, 20, 77, 92, 92, 78, 81, 7, 34, 20, 30, 40, 56, 79, 86, 84, 81, 40, 19, 28, 72, 35, 20, 85, 3, 68, 18, 4, 63, 83, 20, 12, 41, 63, 19, 58]
#[55, 10, 67, 18, 31, 16, 76, 57, 79, 64, 68, 37, 78, 60, 60, 46, 49, 32, 32, 3, 65, 74, 22, 79, 26, 29, 28, 86, 20, 99, 27, 99, 28, 30, 54, 20]
#[73, 87, 66, 32, 10, 75, 40, 94, 30, 99, 52, 10, 33, 33, 52, 36, 16, 90, 68, 62, 19, 33, 50, 22, 78, 47, 91, 22, 84, 83, 41, 17, 32, 83, 38, 23]
#[82, 26, 41, 53, 71, 22, 95, 55, 60, 14, 40, 42, 36, 43, 91, 50, 16, 93, 62, 72, 3, 14, 55, 48, 20, 17, 56, 38, 64, 87, 86, 92, 82, 75, 73, 76]
#[70, 18, 42, 41, 19, 44, 8, 90, 10, 73, 41, 39, 23, 69, 64, 55, 39, 80, 88, 13, 5, 29, 71, 53, 84, 71, 91, 97, 60, 67, 10, 15, 53, 37, 68, 91]
#[12, 99, 93, 43, 63, 51, 54, 89, 39, 8, 19, 27, 70, 94, 0, 70, 76, 1, 51, 30, 60, 88, 24, 69, 35, 36, 97, 43, 0, 70, 21, 84, 19, 6, 93, 92]
#[15, 83, 14, 61, 0, 18, 77, 34, 95, 92, 22, 76, 54, 9, 22, 43, 96, 91, 24, 12, 30, 22, 88, 72, 82, 38, 27, 10, 41, 2, 78, 25, 36, 20, 70, 55]
#[83, 6, 84, 58, 57, 42, 76, 75, 36, 39, 98, 55, 72, 72, 84, 81, 36, 9, 3, 44, 1, 50, 63, 1, 93, 24, 26, 20, 30, 68, 0, 24, 90, 26, 6, 88]
#[58, 38, 65, 42, 40, 25, 32, 39, 19, 31, 74, 36, 85, 74, 23, 20, 37, 41, 41, 63, 61, 9, 27, 39, 22, 0, 36, 34, 53, 53, 6, 40, 81, 18, 86, 8]
#[34, 1, 53, 24, 53, 46, 21, 59, 74, 75, 10, 49, 79, 74, 29, 68, 82, 75, 49, 62, 8, 58, 54, 34, 87, 4, 84, 34, 10, 82, 70, 35, 62, 9, 33, 77]
#[28, 49, 3, 98, 69, 36, 80, 53, 72, 68, 89, 22, 40, 52, 5, 66, 39, 38, 41, 45, 13, 12, 70, 12, 7, 86, 95, 83, 66, 92, 43, 13, 53, 80, 75, 33]
#[98, 98, 88, 3, 11, 32, 83, 24, 91, 79, 3, 55, 50, 95, 41, 69, 30, 89, 68, 47, 13, 35, 0, 86, 57, 8, 10, 31, 1, 40, 81, 2, 87, 10, 73, 0]
#[36, 8, 65, 86, 88, 65, 19, 33, 62, 24, 98, 34, 0, 80, 45, 53, 16, 28, 41, 65, 93, 34, 64, 85, 48, 98, 15, 51, 41, 65, 5, 9, 51, 17, 17, 91]
#[21, 49, 80, 99, 8, 32, 11, 36, 82, 59, 64, 59, 55, 73, 1, 23, 82, 59, 19, 16, 58, 18, 62, 36, 74, 30, 72, 79, 26, 31, 16, 40, 2, 27, 65, 26]
#[86, 24, 59, 75, 93, 17, 20, 42, 21, 4, 80, 0, 57, 91, 81, 84, 95, 13, 65, 85, 9, 15, 26, 90, 66, 20, 13, 98, 67, 27, 85, 49, 45, 65, 10, 84]
#[17, 16, 99, 46, 21, 66, 57, 69, 29, 42, 50, 92, 9, 11, 56, 62, 32, 15, 55, 25, 55, 90, 81, 74, 62, 98, 58, 65, 46, 77, 53, 10, 0, 59, 70, 91]
#[76, 89, 89, 89, 87, 87, 11, 51, 11, 44, 11, 50, 29, 88, 93, 31, 6, 26, 74, 34, 24, 30, 14, 74, 9, 47, 20, 17, 88, 14, 49, 87, 3, 65, 27, 73]
#[18, 18, 68, 23, 13, 98, 52, 92, 72, 75, 8, 8, 2, 33, 69, 23, 22, 16, 95, 76, 43, 83, 86, 27, 4, 58, 57, 97, 64, 22, 43, 32, 41, 2, 88, 26]
#[21, 20, 85, 29, 56, 31, 65, 45, 58, 26, 62, 21, 71, 31, 5, 57, 88, 42, 51, 39, 79, 83, 47, 99, 25, 31, 9, 24, 13, 63, 95, 78, 80, 74, 78, 89]
#[39, 90, 68, 22, 85, 14, 4, 20, 41, 51, 67, 75, 20, 48, 91, 65, 61, 44, 66, 3, 83, 30, 93, 23, 19, 99, 46, 88, 87, 35, 3, 88, 35, 67, 88, 28]
#[63, 21, 64, 10, 7, 38, 25, 17, 32, 36, 7, 99, 46, 65, 74, 71, 63, 42, 30, 72, 29, 80, 42, 65, 27, 24, 16, 16, 70, 2, 54, 60, 35, 79, 88, 39]
#[10, 75, 23, 44, 33, 33, 11, 13, 23, 3, 44, 37, 64, 66, 35, 32, 34, 22, 18, 15, 6, 37, 25, 36, 20, 4, 49, 58, 59, 21, 80, 95, 0, 31, 93, 28]
#[54, 30, 99, 86, 7, 38, 8, 18, 26, 83, 15, 83, 45, 5, 24, 67, 6, 39, 65, 67, 83, 99, 29, 41, 64, 62, 25, 53, 54, 34, 24, 41, 99, 28, 8, 29]
#[30, 60, 67, 20, 43, 56, 79, 43, 92, 85, 69, 9, 62, 22, 62, 24, 68, 33, 18, 61, 25, 14, 21, 59, 86, 59, 53, 26, 1, 80, 9, 36, 4, 5, 85, 47]
#[57, 64, 8, 17, 69, 23, 77, 29, 69, 52, 80, 86, 18, 93, 78, 17, 36, 60, 94, 25, 80, 90, 87, 86, 64, 23, 87, 95, 19, 69, 91, 82, 37, 27, 27, 46]
#[52, 19, 54, 87, 1, 4, 41, 68, 93, 56, 36, 13, 32, 25, 83, 48, 59, 5, 37, 58, 83, 93, 53, 77, 44, 63, 49, 1, 94, 4, 28, 30, 85, 15, 85, 90]
#[75, 72, 89, 33, 98, 23, 81, 41, 35, 17, 4, 1, 46, 60, 83, 69, 27, 35, 33, 83, 61, 61, 21, 72, 82, 72, 82, 6, 59, 51, 60, 37, 82, 20, 88, 54]
#[20, 37, 13, 75, 81, 78, 36, 75, 22, 45, 81, 63, 58, 72, 81, 7, 9, 39, 49, 8, 84, 66, 71, 58, 41, 56, 5, 2, 83, 47, 16, 3, 93, 95, 97, 10]
#[94, 83, 74, 92, 8, 10, 12, 92, 28, 28, 31, 98, 10, 33, 62, 70, 85, 53, 8, 31, 75, 67, 38, 2, 5, 85, 44, 25, 54, 69, 33, 61, 75, 57, 79, 82]
#[60, 34, 79, 9, 2, 28, 80, 24, 2, 76, 26, 34, 61, 22, 40, 31, 52, 14, 30, 2, 88, 54, 41, 73, 6, 45, 13, 22, 70, 51, 74, 69, 19, 66, 33, 78]
#[3, 11, 50, 41, 23, 41, 45, 2, 62, 95, 55, 73, 1, 98, 33, 68, 82, 96, 24, 81, 1, 58, 59, 41, 45, 9, 99, 49, 16, 97, 54, 75, 92, 14, 71, 63]
#[18, 73, 63, 61, 88, 15, 27, 49, 82, 95, 0, 54, 71, 76, 64, 65, 84, 39, 61, 56, 52, 60, 88, 92, 75, 83, 94, 61, 76, 76, 14, 11, 5, 95, 71, 68]]

79828064
Vote

My approach is based on the fact that numbers must be filled diagonal by diagonal to meet the criteria of being descindingly sorted. I explained it well on the README on my github repository where I put my code

https://github.com/genevieve-le-houx/SO_challenge_13_integer_sorting

My result is there are 53 impossible sequence

Impossible sequences are [0, 1, 4, 5, 6, 7, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 27, 32, 35, 37, 38, 43, 44, 47, 49, 50, 51, 52, 55, 56, 57, 58, 60, 66, 67, 68, 69, 70, 73, 79, 80, 84, 85, 87, 90, 93, 97, 98, 99]

The possible sequnces are

2: [[99, 95, 91, 73, 60, 24], [91, 84, 81, 71, 55, 16], [82, 80, 75, 65, 44, 14], [73, 68, 63, 61, 42, 13], [59, 53, 42, 41, 34, 6], [18, 16, 14, 7, 6, 0]]
3: [[99, 94, 83, 70, 52, 27], [88, 86, 74, 62, 48, 20], [81, 73, 71, 59, 40, 13], [63, 61, 57, 56, 35, 9], [50, 40, 36, 29, 27, 6], [24, 19, 10, 8, 3, 1]]
8: [[98, 94, 80, 71, 58, 31], [89, 83, 79, 66, 56, 29], [80, 78, 72, 64, 48, 22], [67, 65, 60, 59, 42, 16], [57, 55, 44, 39, 37, 9], [30, 23, 18, 10, 9, 4]]
9: [[99, 97, 88, 79, 63, 41], [88, 86, 81, 68, 56, 35], [82, 81, 79, 64, 52, 11], [71, 66, 64, 63, 50, 9], [58, 54, 51, 48, 42, 3], [38, 15, 11, 5, 2, 0]]
13: [[98, 96, 90, 70, 55, 19], [93, 91, 82, 66, 49, 16], [82, 74, 73, 65, 38, 14], [68, 66, 58, 56, 31, 12], [54, 41, 32, 28, 21, 10], [19, 16, 12, 10, 4, 3]]
21: [[92, 90, 77, 56, 47, 24], [89, 80, 74, 54, 38, 8], [76, 71, 62, 49, 33, 6], [55, 50, 47, 40, 27, 3], [38, 35, 29, 24, 23, 1], [16, 7, 5, 2, 1, 0]]
26: [[97, 95, 91, 79, 66, 33], [91, 86, 81, 75, 62, 31], [85, 80, 79, 68, 58, 27], [76, 74, 68, 66, 46, 17], [62, 61, 57, 45, 38, 13], [31, 28, 20, 14, 7, 1]]
28: [[92, 91, 88, 80, 65, 26], [88, 87, 85, 73, 42, 20], [85, 84, 83, 71, 35, 14], [77, 73, 70, 68, 32, 11], [52, 37, 32, 29, 27, 9], [22, 17, 12, 10, 7, 3]]
29: [[98, 97, 87, 80, 59, 29], [96, 89, 81, 63, 49, 27], [84, 80, 73, 62, 45, 19], [64, 63, 59, 55, 36, 12], [50, 48, 40, 34, 31, 7], [28, 24, 14, 11, 2, 1]]
30: [[98, 97, 80, 72, 54, 23], [92, 82, 77, 67, 45, 19], [80, 76, 73, 65, 39, 15], [69, 66, 59, 57, 34, 13], [49, 41, 34, 30, 24, 6], [23, 16, 14, 6, 4, 3]]
31: [[98, 97, 89, 78, 58, 21], [93, 89, 86, 58, 46, 20], [89, 78, 75, 55, 42, 17], [63, 58, 53, 51, 30, 14], [48, 44, 35, 29, 28, 8], [21, 17, 15, 8, 6, 3]]
33: [[99, 96, 89, 62, 45, 28], [95, 93, 85, 59, 42, 20], [86, 82, 71, 58, 36, 18], [61, 58, 47, 45, 32, 11], [44, 40, 35, 31, 28, 8], [26, 18, 16, 11, 7, 3]]
34: [[99, 97, 88, 76, 56, 26], [97, 92, 85, 73, 51, 15], [87, 84, 77, 70, 44, 14], [76, 73, 62, 58, 38, 9], [52, 46, 41, 29, 27, 7], [23, 15, 10, 7, 6, 4]]
36: [[99, 94, 89, 67, 54, 30], [93, 92, 81, 65, 53, 23], [84, 79, 69, 59, 48, 15], [67, 60, 58, 56, 43, 9], [53, 50, 44, 32, 31, 6], [26, 19, 10, 8, 5, 2]]
39: [[99, 97, 89, 74, 59, 26], [93, 90, 86, 71, 48, 22], [88, 83, 78, 66, 39, 19], [74, 67, 66, 62, 33, 15], [51, 41, 35, 31, 28, 11], [25, 19, 18, 13, 10, 4]]
40: [[99, 93, 85, 68, 59, 25], [87, 86, 75, 59, 35, 21], [79, 75, 71, 54, 32, 18], [61, 59, 53, 49, 29, 13], [36, 33, 31, 27, 26, 12], [25, 19, 14, 13, 7, 6]]
41: [[94, 88, 81, 72, 65, 37], [85, 84, 76, 69, 58, 26], [78, 76, 75, 67, 54, 23], [70, 68, 65, 61, 49, 22], [60, 57, 52, 44, 41, 11], [34, 25, 22, 19, 10, 1]]
42: [[95, 93, 81, 66, 51, 34], [92, 84, 72, 61, 45, 32], [76, 71, 68, 59, 38, 20], [65, 60, 57, 54, 37, 17], [47, 41, 37, 35, 34, 15], [33, 24, 18, 16, 14, 6]]
45: [[99, 94, 86, 79, 58, 28], [93, 90, 83, 74, 52, 23], [84, 82, 81, 65, 50, 19], [78, 67, 63, 59, 47, 16], [55, 52, 48, 43, 32, 12], [24, 22, 18, 15, 8, 7]]
46: [[99, 95, 85, 74, 54, 37], [95, 86, 80, 70, 49, 32], [81, 78, 76, 59, 47, 24], [72, 66, 55, 54, 44, 14], [53, 48, 45, 39, 37, 7], [35, 26, 15, 8, 6, 2]]
48: [[96, 95, 77, 68, 53, 31], [94, 87, 72, 64, 48, 28], [75, 70, 69, 62, 44, 19], [68, 63, 57, 56, 42, 10], [50, 47, 43, 42, 39, 7], [28, 23, 13, 10, 5, 1]]
53: [[98, 97, 86, 68, 41, 22], [94, 93, 78, 61, 37, 18], [80, 75, 73, 52, 27, 13], [63, 57, 48, 45, 25, 10], [38, 32, 27, 24, 23, 7], [20, 14, 11, 7, 6, 2]]
54: [[96, 88, 80, 67, 49, 20], [88, 80, 76, 63, 33, 18], [79, 73, 68, 50, 28, 14], [66, 56, 49, 41, 25, 6], [39, 30, 28, 24, 22, 4], [18, 17, 11, 6, 3, 0]]
59: [[97, 96, 88, 74, 39, 24], [95, 91, 75, 67, 38, 17], [79, 74, 71, 62, 37, 13], [67, 63, 58, 40, 29, 4], [39, 38, 33, 29, 27, 2], [20, 14, 5, 4, 2, 1]]
61: [[96, 92, 83, 72, 54, 29], [90, 83, 82, 63, 53, 22], [83, 77, 75, 60, 50, 18], [63, 62, 57, 55, 36, 14], [54, 50, 39, 34, 33, 9], [23, 19, 17, 11, 6, 1]]
62: [[99, 96, 92, 81, 70, 26], [95, 93, 89, 78, 55, 23], [90, 87, 82, 77, 44, 19], [80, 78, 74, 71, 38, 13], [60, 49, 39, 37, 36, 10], [25, 21, 18, 11, 3, 1]]
63: [[97, 93, 87, 76, 68, 40], [89, 87, 82, 73, 67, 37], [83, 82, 81, 70, 63, 21], [75, 71, 70, 69, 51, 14], [68, 63, 53, 49, 45, 11], [38, 32, 18, 13, 10, 7]]
64: [[94, 91, 84, 80, 55, 35], [91, 87, 80, 68, 51, 26], [80, 78, 74, 62, 49, 25], [72, 64, 61, 58, 36, 15], [52, 50, 39, 35, 28, 11], [27, 26, 19, 15, 10, 4]]
65: [[90, 76, 66, 61, 42, 21], [72, 67, 63, 54, 36, 17], [65, 63, 61, 49, 31, 10], [61, 53, 42, 40, 25, 8], [38, 34, 28, 24, 23, 6], [20, 16, 9, 7, 5, 0]]
71: [[95, 93, 87, 75, 56, 40], [92, 91, 82, 72, 55, 36], [86, 82, 76, 64, 50, 22], [73, 71, 62, 60, 43, 17], [55, 53, 48, 42, 41, 14], [38, 26, 20, 16, 14, 3]]
72: [[97, 91, 88, 71, 55, 39], [91, 90, 80, 69, 53, 23], [84, 73, 71, 67, 42, 18], [70, 68, 64, 60, 41, 13], [53, 44, 41, 39, 37, 10], [29, 19, 15, 10, 8, 5]]
74: [[96, 95, 88, 76, 41, 22], [92, 91, 82, 70, 36, 20], [83, 78, 77, 55, 30, 15], [72, 61, 54, 43, 25, 12], [38, 34, 27, 24, 22, 9], [22, 18, 14, 10, 2, 0]]
75: [[98, 93, 84, 75, 55, 26], [90, 88, 83, 72, 44, 24], [84, 81, 76, 63, 39, 9], [72, 68, 58, 57, 36, 6], [50, 42, 36, 30, 26, 1], [24, 20, 6, 3, 1, 0]]
76: [[86, 85, 74, 53, 40, 27], [81, 74, 63, 42, 38, 23], [65, 61, 58, 41, 36, 20], [53, 41, 40, 39, 34, 18], [39, 37, 36, 32, 31, 8], [25, 22, 19, 9, 6, 0]]
77: [[87, 84, 82, 74, 54, 34], [82, 79, 75, 68, 53, 29], [77, 75, 74, 62, 49, 21], [70, 62, 59, 58, 35, 10], [53, 49, 46, 34, 33, 8], [34, 24, 10, 9, 4, 1]]
78: [[98, 95, 86, 72, 53, 36], [92, 89, 80, 69, 49, 28], [83, 80, 75, 66, 43, 13], [70, 68, 66, 53, 40, 12], [52, 45, 41, 39, 38, 7], [33, 22, 13, 12, 5, 3]]
81: [[99, 82, 79, 64, 59, 26], [82, 80, 73, 59, 36, 21], [74, 72, 65, 58, 32, 18], [62, 59, 55, 49, 30, 16], [40, 36, 31, 27, 26, 8], [23, 19, 16, 11, 2, 1]]
82: [[98, 95, 90, 84, 65, 21], [93, 91, 85, 80, 57, 20], [86, 85, 84, 67, 45, 15], [81, 75, 66, 65, 27, 13], [59, 49, 42, 26, 24, 9], [20, 17, 13, 10, 4, 0]]
83: [[99, 98, 90, 69, 57, 32], [92, 91, 77, 65, 55, 25], [81, 74, 70, 62, 53, 17], [66, 62, 59, 58, 46, 15], [56, 55, 50, 46, 42, 10], [29, 21, 16, 11, 9, 0]]
86: [[99, 95, 85, 78, 57, 31], [89, 88, 80, 71, 51, 26], [83, 79, 78, 63, 45, 24], [74, 65, 62, 58, 39, 21], [56, 47, 42, 31, 29, 13], [31, 25, 21, 20, 9, 5]]
88: [[99, 88, 74, 65, 42, 27], [80, 79, 71, 63, 39, 24], [72, 70, 65, 60, 36, 17], [64, 63, 54, 46, 32, 16], [42, 38, 35, 30, 29, 7], [25, 21, 16, 10, 7, 2]]
89: [[95, 93, 66, 44, 33, 21], [80, 75, 59, 37, 32, 18], [64, 58, 49, 36, 28, 13], [44, 37, 35, 34, 23, 10], [33, 31, 25, 23, 22, 4], [20, 15, 11, 6, 3, 0]]
91: [[92, 86, 85, 62, 53, 24], [85, 80, 69, 61, 43, 21], [79, 68, 67, 59, 36, 18], [62, 60, 59, 56, 30, 9], [47, 43, 33, 26, 25, 5], [22, 20, 14, 9, 4, 1]]
92: [[95, 94, 90, 86, 69, 29], [93, 91, 87, 80, 64, 27], [87, 86, 82, 77, 57, 23], [80, 78, 69, 64, 46, 19], [69, 60, 52, 37, 36, 17], [27, 25, 23, 18, 17, 8]]
94: [[98, 89, 83, 82, 72, 35], [88, 83, 82, 72, 59, 33], [82, 81, 75, 61, 51, 23], [72, 69, 61, 60, 41, 20], [60, 54, 46, 37, 35, 6], [33, 27, 21, 17, 4, 1]]
95: [[97, 95, 83, 81, 58, 22], [93, 84, 81, 72, 49, 16], [81, 78, 75, 66, 45, 10], [75, 71, 63, 58, 39, 8], [56, 47, 41, 37, 36, 5], [20, 13, 9, 7, 3, 2]]
96: [[98, 94, 92, 75, 61, 31], [92, 85, 83, 74, 54, 28], [85, 82, 79, 69, 44, 12], [75, 70, 67, 62, 33, 10], [57, 53, 38, 33, 31, 8], [28, 25, 10, 8, 5, 2]]

My code is in Python

import copy
import time
from pathlib import Path
from typing import List, Tuple, Dict

import numpy as np


def read_file(filename: Path) -> List[List[int]]:
    """
    Read the file and return the list of sequences
    :param filename: The path to the file
    :return: sequences: A list of sequences
    """
    sequences = []
    with open(filename) as f:
        for line in f:
            line = line.strip()
            line = line.replace("[", "")
            line = line.replace("]", "")
            sequences.append([int(x) for x in line.split(",")])

    return sequences

def validate_row_col_before(result: np.ndarray, position_fill: Tuple[int, int], value: int) -> bool:
    """
    Validate that the value we are about to place is lower than the numbers already there higher up on the same row/column
    :param result: The filled matrix so far
    :param position_fill: The position in the matrix we are about to fill
    :param value: The value we are about to place
    :return: Boolean if okay to fill the position with the value
    """
    i, j = position_fill
    row_before = result[i, :j][np.logical_not(np.isnan(result[i, :j]))].astype(int)
    column_before = result[:i, j][np.logical_not(np.isnan(result[:i, j]))].astype(int)

    if len(row_before) != 0 and len(column_before) != 0:
        return value < min(row_before) and value < min(column_before)

    if len(row_before) != 0:
        return value < min(row_before)

    elif len(column_before):
        return value < min(column_before)

    else:
        return True


def validate_row_after(result: np.ndarray, position_fill: Tuple[int, int], value: int) -> bool:
    """
    Validate that the value we are about to place is higher than the numbers already there lower down on the same row/column
    :param result: The filled matrix so far
    :param position_fill: The position in the matrix we are about to fill
    :param value: The value we are about to place
    :return: Boolean if okay to fill the position with the value
    """
    i, j = position_fill
    row_after = result[i, j+1:][np.logical_not(np.isnan(result[i, j+1:]))]
    column_after = result[i+1:, j][np.logical_not(np.isnan(result[i+1:, j]))]

    if len(row_after) != 0 and len(column_after) != 0:
        return value > max(row_after) and value > max(column_after)

    if len(row_after) != 0:
        return value > max(row_after)

    elif len(column_after) != 0:
        return value > max(column_after)

    else:
        return True


def solve_for_sequence(
    sequence_number: int, values: List[int], grid_size: int,
    fill_order: List[Tuple[int, int]], diagonals: Dict[int, List[Tuple[int, int]]]
) -> Tuple[np.ndarray, List[int]]:
    """
    Find the solution for the given sequence
    :param sequence_number: The sequence number (each sequence gets given a number)
    :param values: The values in the sequence
    :param grid_size: The size of the grid
    :param fill_order: The fill order of the numbers on the grid
    :param diagonals: The dictionnary of the position for each diagonal on the grid
    :return: The filled matrix so far and the values that couldn't be placed on the grid
    """
    result = np.tile(np.nan, (grid_size, grid_size))


    if len(values) != grid_size ** 2:
        print(f"Sequence number {sequence_number} does not have {grid_size ** 2} elements")
        result[np.isnan(result)] = -1
        return result.astype(int), values

    ordered_list = sorted(values, reverse=True)

    fill_order_copy = fill_order.copy()

    diagonals_left = copy.deepcopy(diagonals)
    diagonal_index = 0
    diagonal_size = diagonal_index + 1

    for index_value, value in enumerate(ordered_list):
        try_find_fill_index = 0
        found = False
        while try_find_fill_index < len(fill_order_copy):
            next_fill = fill_order_copy[try_find_fill_index]

            same_copies_of_value = sum([x == value for x in ordered_list])

            if same_copies_of_value > diagonal_size:
                break


            valid_before = validate_row_col_before(result, next_fill, value)
            if valid_before:
                valid_after = validate_row_after(result, next_fill, value)
                if valid_after:
                    result[*next_fill] = value
                    fill_order_copy.pop(try_find_fill_index)
                    found = True

                    diagonals_left[sum(next_fill)].remove(next_fill)
                    if len(diagonals_left[diagonal_index]) == 0:
                        diagonal_index += 1
                        diagonal_size += 1

                    break
                else:
                    try_find_fill_index += 1
                    continue
            else:
                try_find_fill_index += 1
                continue

        if not found:
            result[np.isnan(result)] = -1
            return result.astype(int), ordered_list[index_value:]

    # All filled
    return result.astype(int), []

def write_result_in_file(result_file: Path, results: List[np.ndarray], impossible_sequence_index: List[int]) -> None:
    """
    Write the result in a .txt file
    :param result_file: The path to the result file
    :param results: The results
    :param impossible_sequence_index: The impossible sequence index
    :return: None
    """
    file_lines = []

    for i, result in enumerate(results):
        if i not in impossible_sequence_index:
            file_lines.append(f"{i}: {result.tolist()}\n")

    with open(result_file, "w") as f:
        f.writelines(file_lines)


def get_fill_order_and_diagonals(
    grid_size: int
) -> Tuple[List[Tuple[int, int]], Dict[int, List[Tuple[int, int]]]]:
    """
    Find the ideal fill order of the numbers on the grid
    :param grid_size: The size of the grid
    :returns: The fill order of the numbers on the grid and the position for each diagonals.
    Diagonals is a dictionnary where each key is a diagonal numbers, and each value is the list of the position number part of that diagonal
    """
    fill_order: List[Tuple[int, int]] = []
    diagonals: Dict[int, List[Tuple[int, int]]] = {x: [] for x in range((grid_size-1)*2 + 1)}

    for n in range(grid_size):
        i, j = 0, n

        while i <= n:
            if i == j:
                fill_order.append((i, j))
                diagonals[i + j].append((i, j))
                break

            fill_order.append((i, j))
            diagonals[i + j].append((i, j))

            i, j = j, i
            fill_order.append((i, j))
            diagonals[i + j].append((i, j))

            i, j = j, i
            i += 1

    return fill_order, diagonals


def main():
    tic = time.time()
    grid_size = 6
    values = read_file(Path("RandomNumbers.txt"))

    fill_order, diagonals= get_fill_order_and_diagonals(grid_size)

    all_results = []
    all_values_left = []
    impossible_sequence_index = []
    for i, sequence_ in enumerate(values):
        result, values_left = solve_for_sequence(i, sequence_, grid_size, fill_order, diagonals)
        all_results.append(result)
        all_values_left.append(values_left)

        if len(values_left) != 0:
            impossible_sequence_index.append(i)


    tac = time.time()

    print(f"Time taken: {tac - tic}s")
    print("")

    print(f"{len(impossible_sequence_index)} impossible sequences")
    print(f"Impossible sequences are {impossible_sequence_index}")
    print("")

    for i, result in enumerate(all_results):
        if i not in impossible_sequence_index:
            print(f"Result for sequence #{i} is ")
            print(result)
            print("")

    write_result_in_file(Path("results.txt"), all_results, impossible_sequence_index)


if __name__ == '__main__':
    main()
79831693
Vote

Perusal of the readme.md suggests that you overlooked the case where a run of equal values starts in one diagonal and continues in another. This results in a valid assignment as long as the run is not longer as the diagonal in which it starts (if left of the main diagonal) or ends (if right of the diagonal).

If you had simply employed the diagonal placement that your intuition told you to use, followed by a simple check of array elements against their left and upper neighbour for rule compliance then your code would have computed the correct results (and nobody would have known about the faulty/incomplete reasoning it is based on). ;-)

79828021
Vote

My approach

I decided to try building the 6x6 grid directly instead of doing any kind of brute force search.

The idea I used:

  1. Take the 36 numbers and sort them in descending order.

  2. Fill the grid along diagonals where row + col is constant, moving up and to the right.

  3. Each time I place a number, I check two things:

    • If there is a cell above, my number has to be strictly smaller.

    • If there is a cell to the left, it also has to be strictly smaller.

  4. If either of those checks fails, I stop and call that input impossible.

  5. If I manage to place all 36 numbers, then I have a valid grid.

The reason this works is that I always place numbers from largest to smallest. When I reach a cell, everything above or to the left is already filled with larger values. If even the largest remaining number cannot fit there without breaking the rules, then no smaller number will fit either, so there is no way to fix it later.

So this greedy diagonal placement either gives you a valid grid, or proves that no grid exists for that multiset.

Interesting things I noticed

  • Most of the impossible cases break pretty early, near the top left of the grid. The constraints are tightest there because you need a lot of strictly descending values in both the first row and the first column.

  • Duplicates are allowed overall, but they cause trouble quickly if they land in the same row or column, since everything has to be strictly decreasing.

  • On the file of 100 test sets I used, I got:

    • 55 sets where a grid exists

    • 45 sets that are impossible

  • The valid grids look like a smooth slope of numbers falling away from the top left to the bottom right, which feels nice and consistent with the rules.

My Code

from ast import literal_eval

N = 6

def solve_list_diagonal(nums, n=6):
    # Sort from largest to smallest
    values = sorted(nums, reverse=True)

    # Empty grid
    grid = [[None] * n for _ in range(n)]

    # Start at top-left
    row, col = 0, 0

    for value in values:
        # Check against the cell above and to the left
        above = grid[row - 1][col] if row > 0 else None
        left  = grid[row][col - 1] if col > 0 else None

        if above is not None and value >= above:
            return None
        if left is not None and value >= left:
            return None

        grid[row][col] = value

        # Move along the up-right diagonal
        row -= 1
        col += 1

        # If we go out of bounds, jump to the start of the next diagonal
        if row < 0 or col >= n:
            diag = row + col + 1
            row = min(n - 1, diag)
            col = diag - row

    return grid


def check_grid(grid):
    """Verify that rows and columns are strictly descending."""
    if grid is None:
        return False

    n = len(grid)

    # Check rows
    for r in range(n):
        for c in range(1, n):
            if grid[r][c - 1] <= grid[r][c]:
                return False

    # Check columns
    for c in range(n):
        for r in range(1, n):
            if grid[r - 1][c] <= grid[r][c]:
                return False

    return True


def main():
    valid = 0
    impossible = 0

    # Each line is a Python-style list of 36 integers
    with open("RandomNumbers (1).txt") as f:
        lines = [line.strip() for line in f if line.strip()]

    for idx, line in enumerate(lines):
        nums = literal_eval(line)
        grid = solve_list_diagonal(nums, N)

        if not check_grid(grid):
            print(f"Set {idx}: Impossible")
            impossible += 1
        else:
            print(f"Set {idx}:")
            for row in grid:
                print(row)
            print()
            valid += 1

    print("Total valid grids:", valid)
    print("Total impossible:", impossible)


if __name__ == "__main__":
    main()
79827514
Vote

Even though I'm submitting this after solutions have been revealed, I didn't look at any of the other solutions before writing this code. This was a fun exercise and I'm glad I finally was able to catch one of these challenges.

Although there are many ways to solve this problem (eg. search), the easiest way is to notice that the grid layout forms an acyclic directed graph with a gradient from the upper left corner to the lower right corner. If we imagine rotating the grid clockwise 45 degrees, we see a diamond whose layers represent lists of numbers that are generally greater than the rows below. These layers correspond to diagonals in the original grid.

For any particular list, there could be multiple solutions to the grid final layout. We only need to find one, however, to show it's possible.

To generate one possible solution, place the numbers in numerical sorted order (largest to smallest) starting with the upper left corner and running through the +1 slope diagonals until all numbers have been placed. While placing a number in each cell, check that the cell to the left and the cell above are strictly greater than the value of the current cell.

I'm sure there's a straightforward inductive proof showing the validity of this algorithm, however I'm not going to attempt it here.

The code below runs this algorithm in the following manner:

  1. Read in the entire file, separate it into lines of numbers and sort those numbers.

  2. For each sorted list, place numbers following successive diagonals throughout the square grid.

  3. Check each cell as it's placed to determine if it conforms to the ordering constraint.

  4. It prints a result for each entry in the file along with a final total of impossible entries.

Note: I use Array.every() to perform both grid placement and test for constraint pass. It's usually bad form to have a test change state. It is a convenient hack, nonetheless.

import { readFileSync } from 'node:fs';

// Grab lines from file
const lines   = readFileSync(process.argv[2], 'utf-8').split(/\r?\n/);
let   invalid = 0;

// Process each line entry
lines.forEach((line, lineNo) => {
    const grid = [[], [], [], [], [], []];
    let row = 0, col = 0;

    // Convert file entry to list of numbers
    const list = line.replace(/(^.*\[|\].*$)/g,"").split(",").map(num => +num).sort((a,b) => b-a);

    // Determine validity with side effects (populates grid)
    const isValid = list.every(num => {
        // Check new number is strictly less than both left and up cells
        if (num >= grid[row-1]?.[col] || num >= grid[row]?.[col-1]) return false;

        // Add number to the grid
        grid[row][col] = num;
        
        // Follow diagonal up to the right. New diagonal at boundary crossing
        ++col;  
        if (--row < 0 || col > 5) {
            const diag = row + col + 1;
            col = diag - (row = Math.min(5, diag));
        }
        return true;
    });

    // Show solution or note impossible
    if (isValid) {
        console.log(`${lineNo}:`, grid.map(R => `[${R.join(", ")}]`).join(", "));
    } else {
        console.log(`${lineNo}: Impossible`);
        invalid++;
    }
});

console.log("Total impossible:", invalid);
79825985
Vote

To better understand the challenge, I first took a more general mathematical approach:

  1. Assume a, b, n, m, N, and M are all integers. We have a grid (or array), G, that is NxM in size (N rows and M columns). a is the smallest value in S; b is the largest. n and m are row and column indexes of G, respectively.

  2. We are given a set, S, of NM integers, S[a,b] (though not technically a "set" since here we can have duplicates).

  3. The rule given that the rows and columns must be in descending order with no ties can be written as:

    G[n,m] > G[n+1,m] and G[n,m] > G[n,m+1]

While investigating this system, I discovered some interesting tricks and limiting rules:

  1. If we sort S, we can insert them in order to obtain a solution.

    • Take the highest value in S, and insert into G[0,0].

    • Take the next largest in S, insert into G[1,0].

    • Take the next highest, insert into G[0,1].

    • Insert the next into G[2,0]

    • etc.

  2. Sorting and inserting numbers in this way, we can see a few cases that would result in impossible systems:

    • The i-th element in S (sorted descending) occurs more than floor(1/2+sqrt(1/4+2i)) times. (For i ≤ MIN[N,M].)

    • There is a similar rule for i ≥ MAX[N,M]... (but more complex...you can see the idea, though).

    • Between the 2 cases above, element occurs more than MIN[N,M] times.

  3. In the most compact case:

    G[n,m]-1 = G[n+1,m] and G[n,m]-1 = G[n,m+1]

    by investigating boundary conditions, we can determine that b-a = N+M-2. So, b-aN+M-2 for the possibility of a valid solution. Then we can check this with the min and max values of a given random set, S.

Python Code:

import numpy as np

# grid dimensions
N, M = 6, 6

# number sets
nums = [
    [...],
    [...],
    ...
]

possibleCount, count = 0, 1
for row in nums:
    # the grid
    G = np.zeros((N, M), dtype=int)
    G.fill(-1)
    
    # loop variables
    aMax, a, i, possible = 0, 0, 0, True
    
    # sort the current set
    sortedSet = row.sort(reverse=True) # sort descending
    
    while (G[-1, -1] == -1):
        idx = -1
        idxlist = np.where(G[a,:] == -1)[0]
        if len(idxlist) > 0:
            idx = idxlist[0]
        if idx != -1 and idx < M:
            # find and set the next unset value
            G[a, idx] = row[i]
            # check validity
            if a > 0 and G[a-1, idx] == row[i]:
                possible = False
                break;
            if idx > 0 and G[a, idx-1] == row[i]:
                possible = False
                break;
            # increment to use the next value in the set
            i+=1
        
        # find the next location to insert into the grid
        if a == 0:
            if aMax+1 == N:
                a = aMax
            else: 
                aMax += 1
                a = aMax
        else:
            a-=1
    # end of loop
    
    if possible: possibleCount+=1
    
    print("Set #",count,": ")
    print("Possible:",possible)
    print(G)
    print("\n\n")
    count += 1
# end of for loop

print(possibleCount,"sets are possible.")

My code determined that there are 55 possible cases.

(I haven't yet tried how this code would work for other grid sizes, but it would be interesting!)

79826226
Vote

Your mathematical argument does not amount to much more than restating the conformance rule posed by the challenge in a convoluted way. What it fails to do is prove why diagonal assignment of the sorted sequence must result in a valid solution if a solution exists at all. The hand-waving with silly formulae does not really do the job. Your reasoning did not even tell you that the compliance check reduces to checking the left neighbour if there is a left neighbour (which is an inherent property of above-mentioned non-increasing diagonal assignment). So why throw around all that pseudo-mathematical babble? You had a valid intuition, and you were lucky that it panned out. The rest is pretentious noise. We are all programmers here and we are not going to be impressed by hot air.

79825545
Vote

I've published my solution as a Node.js program in this GitHub repo, along with its console output. Copies of my code & approach are included below.


I began by observing the top-left corner must contain the highest number, as no number can be above it or to its left. As there is only 1 top-left corner, sorting is impossible if there's a tie for highest.

C1 C2 C3 C4 C5 C6
99
❌ 99

If there's a 2-way tie for second-highest number, we can place them in the spaces around the highest number. With a 3-way-or-more tie, we run out of room.

C1 C2 C3 C4 C5 C6
99 98
98
❌ 98

Doing the same for the lowest numbers in the bottom-right, and extrapolating until they meet in the middle, we find 11 stripes that can contain sets of identical numbers:

C1 C2 C3 C4 C5 C6
11 10 9 8 7 6
10 9 8 7 6 5
9 8 7 6 5 4
8 7 6 5 4 3
7 6 5 4 3 2
6 5 4 3 2 1

Except it's not quite that simple, as a set can span different stripes as long as no rows or columns are shared:

C1 C2 C3 C4 C5 C6
99 98 97
97

Essentially what this means is that as long as X >= Y, an X-space stripe can always contain a set of Y identical numbers, even if the stripe has been partially filled such that it has less than Y spaces left. In that case, we can "borrow" spaces from a larger adjacent stripe. The exception is the middle corner-to-corner stripe, where we have nowhere to borrow from.

This JavaScript module implements a stripe-by-stripe fill of the grid, borrowing spaces from larger stripes as necessary:

export function gridSort(/** @type number[] */ list) {
    // Create a sorted list of identical sets of numbers
    /** @type Map<number, number> */ let occurrences = new Map();
    for (let num of list) {
        occurrences.set(num, 1 + (occurrences.get(num) ?? 0));
    }
    /** @type [number, number][] */ let sortedOccurrences = [...occurrences.entries()];
    sortedOccurrences.sort( ([a], [b]) => a - b );

    // Create the stripe representation of the grid
    /** Number of diagonal stripes on either side of grid's diagonal, equal to grid size - 1 */
    let hemisphereSize = 5;
    /** @type number[][] */ let stripes = Array(hemisphereSize * 2 + 1);
    /** @type number[] */ let stripeCapacities = Array(stripes.length);
    for (let i = 0; i < stripes.length; i++) {
        stripes[i] = [];
        stripeCapacities[i] = Math.min(i + 1, stripes.length - i);
    }

    let success = true;
    // Fill the bottom-right corner until we reach the diagonal
    let currentStripe = 0;
    while (currentStripe < hemisphereSize) {
        let [num, quantity] = sortedOccurrences.shift();
        if (quantity > stripeCapacities[currentStripe]) {
            success = false;
        }
        for (let i = 0; i < quantity; i++) {
            stripes[currentStripe].push(num);
            if (stripes[currentStripe].length == stripeCapacities[currentStripe]) {
                ++currentStripe;
            }
        }
    }
    // Save where the two fills will meet
    let fillMeetStripe = stripes[currentStripe], fillMeetReverseIndex = fillMeetStripe.length;
    // Fill the top-left corner through the diagonal
    currentStripe = stripes.length - 1;
    while (sortedOccurrences.length) {
        let [num, quantity] = sortedOccurrences.pop();
        if (quantity > stripeCapacities[currentStripe]) {
            success = false;
        }
        for (let i = 0; i < quantity; i++) {
            stripes[currentStripe].unshift(num);
            if (stripes[currentStripe].length == stripeCapacities[currentStripe]) {
                --currentStripe;
            }
        }
    }
    // Bottom-right fill pushed low numbers, top-left fill unshifted high numbers, so swap them
    fillMeetStripe?.unshift( ...fillMeetStripe.splice(-1 * fillMeetReverseIndex) );

    // Convert the stripe representation of the grid to the grid proper
    /** @type number[][] */ let grid = Array(6);
    for (let i = 0; i < grid.length; i++) {
        grid[i] = Array(6);
    }
    for (let [stripeNum, stripe] of stripes.entries()) {
        let startX = Math.max(0, hemisphereSize - stripeNum);
        let startY = Math.min(grid.length - 1, stripes.length - 1 - stripeNum);
        for (let [i, num] of stripe.entries()) {
            grid[startY - i][startX + i] = num;
        }
    }
    return {grid, success};
}

Again, the GitHub repo includes a runnable Node.js program demonstrating the solution, and its console output.

79825607
Vote

Kudos for the nice analysis, especially for not forgetting that runs of equal values can straddle diagonals. :-)

If you continue the diagonal argument a little further then you can arrive at a simple, straightforward recipe for placing the elements of the sorted sequence, without trial placement, backtrackting etc. pp.

If you do this and also disentangle the placement and compliance checking then you can simplify your solution drastically. E.g.

  1. sort values
  2. place values in matrix following special recipe
  3. run compliance check
79824924
Vote

challenge-13 program (place together with RandomNumbers.txt in the same folder):

#!/bin/python3

from math import sqrt
from json import loads

def solve(challenge):
    
    # sort list of integers smallest to largest
    challenge.sort()

    # determine matrix dimension
    dim = int(sqrt(len(challenge)))
    
    # raise exception if number of elements is not a square number
    if dim ** 2 != len(challenge):
        raise Exception('Impossible!')
    
    # initialize 2d solution matrix (i. e. dim X dim sized list)
    solution = [ [-1 for _ in range(dim)] for _ in range(dim) ]

    # initialize starting spot
    row, col = 0, 0

    # sort elements into the solution matrix in the following order and stop when all elements have been processed:
    #  0  1  3  6 10 15
    #  2  4  7 11 16 21
    #  5  8 12 17 22 26
    #  9 13 18 23 27 30
    # 14 19 24 28 31 33
    # 20 25 29 32 34 35
    while len(challenge) > 0:
    
        # add biggest remaining element to solution matrix
        solution[row][col] = challenge.pop()
        
        # raise exception if challenge is impossible to solve
        if (col > 0 and solution[row][col] >= solution[row][col-1]):
            raise Exception('Impossible!')
        
        # determine spot for next element
        if row == dim - 1:
            row, col = col + 1, row
        elif col == 0:
            row, col = 0, row + 1
        else:
            row, col = row + 1, col - 1
    
    return solution

if __name__ == '__main__':

    # initialize fail counter
    cnt_fail = 0

    # open file containing challenges
    with open('RandomNumbers.txt', 'r') as file:

        # iterate over challenges
        for line in file:
        
            # convert line into list of integers
            challenge = loads(line)

            # try to solve challenge and print solution
            try:
                print(solve(challenge))
            
            # print exception if challenge is unsolvable
            except Exception as e:
                print(e)
                cnt_fail += 1

    # print number of unsolvable challenges
    print('Total count of cases for which the sorting was impossible: {}'.format(cnt_fail))

Run program:

# make program executable
chmod +x challenge-13
# run program
./challenge-13

Result:

Impossible!
Impossible!
[[99, 95, 91, 81, 73, 61], [91, 84, 80, 71, 60, 42], [82, 75, 68, 59, 42, 18], [73, 65, 55, 41, 16, 14], [63, 53, 34, 16, 13, 6], [44, 24, 14, 7, 6, 0]]
[[99, 94, 86, 74, 63, 56], [88, 83, 73, 62, 52, 36], [81, 71, 61, 50, 35, 24], [70, 59, 48, 29, 20, 10], [57, 40, 27, 19, 9, 6], [40, 27, 13, 8, 3, 1]]
[[99, 97, 89, 85, 78, 65], [96, 88, 81, 78, 60, 46], [85, 80, 76, 52, 45, 35], [78, 75, 52, 43, 32, 27], [71, 48, 41, 31, 26, 21], [48, 37, 31, 22, 14, 5]]
Impossible!
Impossible!
Impossible!
[[98, 94, 83, 79, 67, 59], [89, 80, 78, 66, 58, 44], [80, 72, 65, 57, 42, 30], [71, 64, 56, 39, 29, 18], [60, 55, 37, 23, 16, 9], [48, 31, 22, 10, 9, 4]]
[[99, 97, 88, 81, 71, 63], [88, 86, 81, 68, 63, 51], [82, 79, 66, 58, 50, 38], [79, 64, 56, 48, 35, 11], [64, 54, 42, 15, 9, 3], [52, 41, 11, 5, 2, 0]]
Impossible!
Impossible!
Impossible!
[[98, 96, 91, 82, 68, 56], [93, 90, 74, 66, 55, 32], [82, 73, 66, 54, 31, 19], [70, 65, 49, 28, 16, 12], [58, 41, 21, 16, 12, 10], [38, 19, 14, 10, 4, 3]]
[[94, 85, 81, 77, 71, 61], [84, 79, 74, 69, 57, 47], [79, 73, 69, 57, 46, 32], [71, 66, 57, 46, 31, 24], [65, 56, 39, 31, 14, 12], [56, 35, 26, 13, 1, 0]]
Impossible!
Impossible!
[[97, 95, 92, 76, 59, 47], [95, 91, 67, 58, 46, 39], [90, 64, 49, 44, 39, 23], [62, 49, 42, 38, 22, 16], [48, 41, 29, 16, 14, 10], [40, 25, 16, 13, 10, 0]]
Impossible!
[[99, 97, 92, 86, 77, 63], [96, 87, 82, 74, 63, 34], [87, 80, 73, 59, 34, 25], [77, 73, 51, 31, 25, 19], [71, 44, 28, 24, 15, 14], [40, 25, 23, 15, 13, 12]]
Impossible!
[[92, 90, 80, 74, 55, 47], [89, 77, 71, 54, 40, 29], [76, 62, 50, 38, 27, 16], [56, 49, 38, 24, 8, 5], [47, 35, 24, 7, 3, 1], [33, 23, 6, 2, 1, 0]]
Impossible!
Impossible!
Impossible!
Impossible!
[[97, 95, 91, 81, 76, 66], [91, 86, 80, 75, 66, 57], [85, 79, 74, 62, 46, 31], [79, 68, 62, 45, 31, 20], [68, 61, 38, 28, 17, 13], [58, 33, 27, 14, 7, 1]]
Impossible!
[[92, 91, 88, 85, 77, 68], [88, 87, 84, 73, 65, 32], [85, 83, 73, 52, 32, 22], [80, 71, 42, 29, 20, 12], [70, 37, 27, 17, 11, 9], [35, 26, 14, 10, 7, 3]]
[[98, 97, 89, 81, 64, 59], [96, 87, 80, 63, 55, 40], [84, 80, 63, 50, 36, 28], [73, 62, 49, 34, 27, 14], [59, 48, 31, 24, 12, 7], [45, 29, 19, 11, 2, 1]]
[[98, 97, 82, 77, 69, 57], [92, 80, 76, 67, 54, 34], [80, 73, 66, 49, 34, 23], [72, 65, 45, 30, 19, 14], [59, 41, 24, 16, 13, 6], [39, 23, 15, 6, 4, 3]]
[[98, 97, 89, 86, 63, 53], [93, 89, 78, 58, 51, 35], [89, 78, 58, 48, 30, 21], [75, 58, 46, 29, 20, 15], [55, 44, 28, 17, 14, 8], [42, 21, 17, 8, 6, 3]]
Impossible!
[[99, 96, 93, 85, 61, 45], [95, 89, 82, 59, 45, 35], [86, 71, 58, 44, 32, 26], [62, 58, 42, 31, 20, 16], [47, 40, 28, 18, 11, 8], [36, 28, 18, 11, 7, 3]]
[[99, 97, 92, 85, 76, 58], [97, 88, 84, 73, 56, 41], [87, 77, 73, 52, 38, 23], [76, 70, 51, 29, 15, 10], [62, 46, 27, 15, 9, 7], [44, 26, 14, 7, 6, 4]]
[[96, 93, 87, 78, 70, 43], [91, 80, 76, 70, 42, 24], [80, 75, 55, 40, 23, 10], [74, 54, 39, 19, 10, 7], [49, 34, 16, 10, 7, 3], [30, 11, 9, 5, 2, 0]]
[[99, 94, 92, 81, 67, 56], [93, 89, 79, 65, 54, 44], [84, 69, 60, 53, 43, 26], [67, 59, 53, 32, 23, 10], [58, 50, 31, 19, 9, 6], [48, 30, 15, 8, 5, 2]]
Impossible!
[[96, 91, 88, 87, 78, 65], [89, 87, 86, 78, 64, 51], [87, 83, 75, 61, 51, 34], [80, 69, 59, 50, 32, 11], [66, 57, 47, 17, 8, 5], [52, 45, 12, 5, 1, 0]]
[[99, 97, 90, 86, 74, 62], [93, 89, 83, 71, 59, 35], [88, 78, 67, 51, 33, 25], [74, 66, 48, 31, 22, 18], [66, 41, 28, 19, 15, 11], [39, 26, 19, 13, 10, 4]]
[[99, 93, 86, 75, 61, 53], [87, 85, 75, 59, 49, 31], [79, 71, 59, 36, 29, 25], [68, 59, 35, 27, 21, 14], [54, 33, 26, 19, 13, 12], [32, 25, 18, 13, 7, 6]]
[[94, 88, 84, 76, 70, 65], [85, 81, 76, 69, 61, 52], [78, 75, 68, 60, 49, 34], [72, 67, 58, 44, 26, 22], [65, 57, 41, 25, 22, 11], [54, 37, 23, 19, 10, 1]]
[[95, 93, 84, 72, 65, 54], [92, 81, 71, 61, 51, 37], [76, 68, 60, 47, 37, 33], [66, 59, 45, 35, 32, 18], [57, 41, 34, 24, 17, 15], [38, 34, 20, 16, 14, 6]]
Impossible!
Impossible!
[[99, 94, 90, 83, 78, 59], [93, 86, 82, 74, 58, 48], [84, 81, 67, 55, 47, 24], [79, 65, 52, 43, 23, 18], [63, 52, 32, 22, 16, 12], [50, 28, 19, 15, 8, 7]]
[[99, 95, 86, 80, 72, 54], [95, 85, 78, 70, 54, 45], [81, 76, 66, 53, 44, 35], [74, 59, 49, 39, 32, 15], [55, 48, 37, 26, 14, 7], [47, 37, 24, 8, 6, 2]]
Impossible!
[[96, 95, 87, 72, 68, 56], [94, 77, 70, 64, 53, 43], [75, 69, 63, 50, 42, 28], [68, 62, 48, 42, 28, 13], [57, 47, 39, 23, 10, 7], [44, 31, 19, 10, 5, 1]]
Impossible!
Impossible!
Impossible!
Impossible!
[[98, 97, 93, 78, 63, 45], [94, 86, 75, 61, 41, 27], [80, 73, 57, 38, 25, 20], [68, 52, 37, 24, 18, 11], [48, 32, 23, 14, 10, 7], [27, 22, 13, 7, 6, 2]]
[[96, 88, 80, 76, 66, 49], [88, 80, 73, 63, 41, 28], [79, 68, 56, 39, 25, 18], [67, 50, 33, 24, 18, 11], [49, 30, 22, 17, 6, 4], [28, 20, 14, 6, 3, 0]]
Impossible!
[[99, 96, 88, 73, 66, 46], [92, 86, 69, 61, 44, 29], [75, 69, 53, 40, 24, 14], [68, 53, 37, 22, 13, 11], [48, 32, 22, 13, 11, 3], [31, 17, 11, 10, 1, 0]]
[[98, 97, 91, 78, 72, 56], [92, 90, 77, 70, 55, 42], [86, 76, 65, 55, 38, 27], [76, 65, 55, 38, 24, 15], [58, 54, 37, 19, 11, 3], [46, 34, 18, 5, 3, 0]]
Impossible!
[[97, 96, 91, 75, 67, 40], [95, 88, 74, 67, 39, 33], [79, 74, 63, 39, 29, 20], [71, 62, 38, 29, 17, 5], [58, 38, 27, 14, 4, 2], [37, 24, 13, 4, 2, 1]]
Impossible!
[[96, 92, 83, 82, 63, 55], [90, 83, 77, 63, 54, 39], [83, 75, 62, 54, 36, 23], [72, 60, 53, 34, 22, 17], [57, 50, 33, 19, 14, 9], [50, 29, 18, 11, 6, 1]]
[[99, 96, 93, 89, 80, 71], [95, 92, 87, 78, 70, 39], [90, 82, 78, 60, 38, 25], [81, 77, 55, 37, 23, 18], [74, 49, 36, 21, 13, 10], [44, 26, 19, 11, 3, 1]]
[[97, 93, 87, 82, 75, 69], [89, 87, 82, 73, 68, 53], [83, 81, 71, 68, 51, 38], [76, 70, 67, 49, 37, 18], [70, 63, 45, 32, 14, 11], [63, 40, 21, 13, 10, 7]]
[[94, 91, 87, 80, 72, 58], [91, 84, 80, 68, 55, 39], [80, 78, 64, 52, 36, 27], [74, 62, 51, 35, 26, 19], [61, 50, 35, 26, 15, 11], [49, 28, 25, 15, 10, 4]]
[[90, 76, 67, 63, 61, 42], [72, 66, 63, 54, 40, 28], [65, 61, 53, 38, 25, 20], [61, 49, 36, 24, 17, 9], [42, 34, 23, 16, 8, 6], [31, 21, 10, 7, 5, 0]]
Impossible!
Impossible!
Impossible!
Impossible!
Impossible!
[[95, 93, 91, 82, 73, 60], [92, 87, 82, 72, 56, 48], [86, 76, 71, 55, 43, 38], [75, 64, 55, 42, 36, 20], [62, 53, 41, 26, 17, 14], [50, 40, 22, 16, 14, 3]]
[[97, 91, 90, 80, 70, 60], [91, 88, 73, 69, 55, 41], [84, 71, 68, 53, 41, 29], [71, 67, 53, 39, 23, 15], [64, 44, 39, 19, 13, 10], [42, 37, 18, 10, 8, 5]]
Impossible!
[[96, 95, 91, 82, 72, 43], [92, 88, 78, 70, 41, 27], [83, 77, 61, 38, 25, 22], [76, 55, 36, 24, 20, 14], [54, 34, 22, 18, 12, 9], [30, 22, 15, 10, 2, 0]]
[[98, 93, 88, 83, 72, 57], [90, 84, 81, 72, 55, 36], [84, 76, 68, 50, 36, 24], [75, 63, 44, 30, 24, 6], [58, 42, 26, 20, 6, 1], [39, 26, 9, 3, 1, 0]]
[[86, 85, 74, 63, 53, 40], [81, 74, 61, 42, 39, 36], [65, 58, 41, 39, 34, 25], [53, 41, 38, 32, 23, 19], [40, 37, 31, 22, 18, 8], [36, 27, 20, 9, 6, 0]]
[[87, 84, 82, 75, 70, 58], [82, 79, 75, 68, 54, 46], [77, 74, 62, 53, 35, 33], [74, 62, 53, 34, 29, 10], [59, 49, 34, 24, 10, 8], [49, 34, 21, 9, 4, 1]]
[[98, 95, 89, 80, 70, 53], [92, 86, 80, 69, 53, 41], [83, 75, 68, 52, 40, 33], [72, 66, 49, 39, 28, 13], [66, 45, 38, 22, 12, 7], [43, 36, 13, 12, 5, 3]]
Impossible!
Impossible!
[[99, 82, 80, 73, 62, 55], [82, 79, 72, 59, 49, 31], [74, 65, 59, 40, 30, 23], [64, 59, 36, 27, 21, 16], [58, 36, 26, 19, 16, 8], [32, 26, 18, 11, 2, 1]]
[[98, 95, 91, 85, 81, 65], [93, 90, 85, 80, 65, 42], [86, 84, 75, 59, 27, 20], [84, 67, 57, 26, 20, 13], [66, 49, 24, 17, 13, 9], [45, 21, 15, 10, 4, 0]]
[[99, 98, 91, 77, 66, 58], [92, 90, 74, 65, 57, 50], [81, 70, 62, 56, 46, 29], [69, 62, 55, 46, 25, 16], [59, 55, 42, 21, 15, 10], [53, 32, 17, 11, 9, 0]]
Impossible!
Impossible!
[[99, 95, 88, 80, 74, 58], [89, 85, 79, 71, 57, 42], [83, 78, 65, 56, 39, 29], [78, 63, 51, 31, 26, 21], [62, 47, 31, 25, 21, 13], [45, 31, 24, 20, 9, 5]]
Impossible!
[[99, 88, 79, 71, 64, 46], [80, 74, 70, 63, 42, 35], [72, 65, 63, 42, 32, 25], [65, 60, 39, 30, 24, 16], [54, 38, 29, 21, 16, 7], [36, 27, 17, 10, 7, 2]]
[[95, 93, 75, 59, 44, 34], [80, 66, 58, 37, 33, 25], [64, 49, 37, 33, 23, 20], [44, 36, 32, 23, 18, 11], [35, 31, 22, 15, 10, 4], [28, 21, 13, 6, 3, 0]]
Impossible!
[[92, 86, 85, 69, 62, 56], [85, 80, 68, 61, 53, 33], [79, 67, 60, 47, 30, 22], [62, 59, 43, 26, 21, 14], [59, 43, 25, 20, 9, 5], [36, 24, 18, 9, 4, 1]]
[[95, 94, 91, 87, 80, 69], [93, 90, 86, 80, 69, 52], [87, 86, 78, 64, 46, 27], [82, 77, 64, 37, 27, 23], [69, 60, 36, 25, 19, 17], [57, 29, 23, 18, 17, 8]]
Impossible!
[[98, 89, 83, 82, 72, 61], [88, 83, 82, 72, 60, 46], [82, 81, 72, 60, 41, 33], [75, 69, 59, 37, 33, 21], [61, 54, 35, 27, 20, 6], [51, 35, 23, 17, 4, 1]]
[[97, 95, 84, 81, 75, 58], [93, 83, 81, 72, 58, 41], [81, 78, 71, 56, 39, 20], [75, 66, 49, 37, 16, 9], [63, 47, 36, 13, 8, 5], [45, 22, 10, 7, 3, 2]]
[[98, 94, 92, 83, 75, 62], [92, 85, 82, 74, 61, 38], [85, 79, 70, 57, 33, 28], [75, 69, 54, 33, 28, 10], [67, 53, 31, 25, 10, 8], [44, 31, 12, 8, 5, 2]]
Impossible!
Impossible!
Impossible!
Total count of cases for which the sorting was impossible: 45

Initially I implemented this using backtracking with depth first search. However, as one would expect, performance was very poor. Then I noticed that by carefully placing the ordered elements inside the grid, there is no need to "search" for a solution at all. Hence, my second approach was to simply implement this by statically mapping the sorted elements into the grid. Finally I generalized the solution, so that challenges with different number of elements will be accepted as well, as long as the number of elements is a square number.

See code comments for more details about my solution.

This was a nice finger exercise. Really appreciated this.

79825288
Vote

Lean, clean and straight to the point. I like this. :-)

79824433
Vote
import React, { useState } from 'react';
import { Shuffle, Check, X } from 'lucide-react';

export default function GridSortingChallenge() {
  const [grid, setGrid] = useState(Array(36).fill(null));
  const [numbers, setNumbers] = useState([]);
  const [selectedCell, setSelectedCell] = useState(null);
  const [message, setMessage] = useState('');
  const [isValid, setIsValid] = useState(null);

  const generateNumbers = () => {
    // Generate 36 random numbers (0-9)
    const nums = [];
    for (let i = 0; i < 36; i++) {
      nums.push(Math.floor(Math.random() * 10));
    }
    setNumbers(nums);
    setGrid(Array(36).fill(null));
    setSelectedCell(null);
    setMessage('');
    setIsValid(null);
  };

  const autoSolve = () => {
    if (numbers.length === 0) {
      setMessage('Generate numbers first!');
      return;
    }

    // Sort numbers in descending order
    const sorted = [...numbers].sort((a, b) => b - a);
    
    // Try to place numbers using backtracking
    const newGrid = Array(36).fill(null);
    const available = [...sorted];

    const canPlace = (row, col, val) => {
      // Check left neighbor (row constraint)
      if (col > 0 && newGrid[row * 6 + col - 1] !== null) {
        if (val >= newGrid[row * 6 + col - 1]) return false;
      }
      // Check top neighbor (column constraint)
      if (row > 0 && newGrid[(row - 1) * 6 + col] !== null) {
        if (val >= newGrid[(row - 1) * 6 + col]) return false;
      }
      return true;
    };

    const solve = (pos) => {
      if (pos === 36) return available.length === 0;
      
      const row = Math.floor(pos / 6);
      const col = pos % 6;

      for (let i = 0; i < available.length; i++) {
        const num = available[i];
        if (canPlace(row, col, num)) {
          newGrid[pos] = num;
          const removed = available.splice(i, 1);
          if (solve(pos + 1)) return true;
          available.splice(i, 0, removed[0]);
          newGrid[pos] = null;
        }
      }
      return false;
    };

    if (solve(0)) {
      setGrid(newGrid);
      setMessage('✓ Solution found!');
      setIsValid(true);
    } else {
      setMessage('✗ Impossible to solve with these numbers');
      setIsValid(false);
    }
  };

  const checkSolution = () => {
    if (grid.some(cell => cell === null)) {
      setMessage('Fill all cells first!');
      setIsValid(false);
      return;
    }

    // Check rows descending
    for (let row = 0; row < 6; row++) {
      for (let col = 0; col < 5; col++) {
        const current = grid[row * 6 + col];
        const next = grid[row * 6 + col + 1];
        if (current <= next) {
          setMessage(✗ Row ${row + 1} not properly sorted);
          setIsValid(false);
          return;
        }
      }
    }

    // Check columns descending
    for (let col = 0; col < 6; col++) {
      for (let row = 0; row < 5; row++) {
        const current = grid[row * 6 + col];
        const next = grid[(row + 1) * 6 + col];
        if (current <= next) {
          setMessage(✗ Column ${col + 1} not properly sorted);
          setIsValid(false);
          return;
        }
      }
    }

    setMessage('✓ Perfect! Valid solution!');
    setIsValid(true);
  };

  const colors = ['bg-yellow-600', 'bg-blue-500', 'bg-red-600', 'bg-yellow-500'];

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-100 to-gray-200 p-8">
      <div className="max-w-4xl mx-auto">
        <h1 className="text-4xl font-bold text-gray-800 mb-2">
          Challenge #13: Integer Sorting in a Grid
        </h1>
        <p className="text-gray-600 mb-6">
          Place integers into a 6×6 grid where each row and column is sorted in descending order (no ties allowed)
        </p>

        <div className="bg-white rounded-lg shadow-lg p-6 mb-6">
          <div className="flex gap-4 mb-6">
            <button
              onClick={generateNumbers}
              className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition"
            >
              <Shuffle size={20} />
              Generate Numbers
            </button>
            <button
              onClick={autoSolve}
              className="flex items-center gap-2 bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition"
              disabled={numbers.length === 0}
            >
              Auto Solve
            </button>
            <button
              onClick={checkSolution}
              className="flex items-center gap-2 bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700 transition"
            >
              <Check size={20} />
              Check Solution
            </button>
          </div>

          {numbers.length > 0 && (
            <div className="mb-4 p-4 bg-gray-50 rounded">
              <p className="text-sm font-semibold mb-2">Numbers to place:</p>
              <div className="flex flex-wrap gap-2">
                {numbers.map((num, idx) => (
                  <span key={idx} className="px-2 py-1 bg-gray-200 rounded text-sm">
                    {num}
                  </span>
                ))}
              </div>
            </div>
          )}

          <div className="grid grid-cols-6 gap-1 mb-4">
            {grid.map((value, idx) => {
              const row = Math.floor(idx / 6);
              const col = idx % 6;
              const colorClass = colors[(Math.floor(row / 3) * 2 + Math.floor(col / 3)) % 4];
              
              return (
                <div
                  key={idx}
                  className={${colorClass} aspect-square rounded flex items-center justify-center text-white text-3xl font-bold cursor-pointer hover:opacity-80 transition}
                >
                  {value !== null ? value : ''}
                </div>
              );
            })}
          </div>

          {message && (
            <div className={`p-4 rounded-lg ${
              isValid === true ? 'bg-green-100 text-green-800' :
              isValid === false ? 'bg-red-100 text-red-800' :
              'bg-blue-100 text-blue-800'
            }`}>
              {message}
            </div>
          )}
        </div>

        <div className="bg-white rounded-lg shadow-lg p-6">
          <h2 className="text-xl font-bold mb-3">Rules</h2>
          <ul className="space-y-2 text-gray-700">
            <li className="flex items-start gap-2">
              <span className="text-blue-600 font-bold">•</span>
              <span>Each <strong>row</strong> must be descendingly sorted (ties not allowed). Example: 6 5 4 3 2 1 is valid, but 6 5 5 3 2 is not.</span>
            </li>
            <li className="flex items-start gap-2">
              <span className="text-blue-600 font-bold">•</span>
              <span>Each <strong>column</strong> must be descendingly sorted (ties not allowed)</span>
            </li>
            <li className="flex items-start gap-2">
              <span className="text-blue-600 font-bold">•</span>
              <span>Or declare the arrangement <strong>impossible</strong></span>
            </li>
          </ul>
        </div>
      </div>
    </div>
  );
}
79823433
Vote

Here is my proposal.

Preliminaries:

  • The diagonals in a matrix of shape (6, 6) are defined as showned below:
0 1 2 3 . .
1 2 3 . .
2 3 . .
3 . .
. .
. 
  • The value assigned to a diagonal $i$ are set to be higher than the value assigned to a diagonal $j$ where $j>i$.

Each diagonal can be filled as follow:

  • O1: from the bottom-left side to the top-right side:
0 2 5 9 . .
1 4 8 . .
3 7 . .
6 . .
. .
. 
  • O2: ... or conversely from the the top-right to the bottom left side
0 1 3 6 . .
2 4 7 . .
5 8 . .
9 . .
. .
. 
  • ... but this choice must be the same for every diagonal.

By assigning the input value sorted by decreasing order, according to one of these indexing, we can solve the problem.

Each cell of the matrix is identified by a (i, j) pair of indices:

(0, 0) (0, 1) (0, 2) ...
(1, 0) (1, 1) (1, 2) ...
(2, 0) (2, 1) (2, 2) ...
...    ...    ....

Each of these (i, j) pair must be consequently sorted. These pairs are sorted according to the following lexicographic order:

  • In each diagonal, i + j remain constant, and hence identifies the diagonal. Hence, we choose i + j as the first sorting criterion.
  • For a given diagonal, every element has a distinct row (resp. col). So we can arbitrarily rely on the row (resp. the column) index. As stated in the preliminaries, the diagonal can be processed from from the bottom-left side to the up-right side meaning we can arbirarily use i, j, -i or -j as the second sorting criterion. This choice defines whether we rely on O1 or O2 ordering.

Overview:

  • The core algorithm is implemented in process_example. It sorts the input value, then performs based a diagonal-based assignment and designed to process squared matrices of shape (n, n).
  • If there is no feasible solution, it returns an invalid solution, meaning that some involve columns (resp. rows) contain duplicated values (sorted by decreasing order).
  • The check_result function checks the solution validity, i.e., it checks that no column (resp. rows) contain duplicated values and is sorted in decreasing order.
  • The data is loaded by the process_examples function and takes advantage of the ast module to easily load the input data.
  • I also added a Jupyter notebook backend, see the in_ipynb, html, display_result functions, because it helps to understand why diagonal assignement is a good strategy (and also why we have some flexibility regarding how we fill each diagonal). The display_result relies on matplotlib to display the output matrices in a heatmap.

Implementation:

#!/usr/bin/env python3
# https://stackoverflow.com/beta/challenges/79811869/challenge-13-integer-sorting-in-a-grid

import ast
import math
import sys
import numpy as np
from itertools import product


def process_example(example: np.ndarray[int]) -> np.ndarray[int]:
    n = int(math.sqrt(len(example)))
    a = np.zeros(shape=(n, n), dtype=np.int32)
    indices = np.int32(
        sorted(
            product(np.arange(n), np.arange(n)),
            key=lambda ij: (ij[0] + ij[1], ij[0])
        )
    )
    values = np.sort(example)[::-1]
    a[tuple(indices.T)] = values
    return a


def check_result(a: np.ndarray[int]):
    (m, n) = a.shape
    assert m == n
    for i in range(m):
        for label, obtained in zip(
            ("Row", "Col"),
            (a[i, :], a[i, :])
        ):
            expected = np.sort(obtained)[::-1]
            assert obtained.all() == expected.all(), "\n".join([
                f"{label} {i}",
                f"{obtained=}",
                f"{expected=}",
            ])
            assert len(obtained) == len(set(obtained)), "\n".join([
                f"Duplicated values: {label} {i}",
                f"{obtained=}",
            ])


def in_ipynb() -> bool:
    try:
        from ipykernel.zmqshell import ZMQInteractiveShell
        from IPython import get_ipython
        return type(get_ipython()) == ZMQInteractiveShell
    except NameError:
        return False
    except ImportError:
        return False


def html(s: str):
    from IPython.display import display, HTML
    chart = HTML(s)
    # or chart = charts.plot(...)
    display(chart)


def display_result(a: np.ndarray):
    import matplotlib.pyplot as plt
    from IPython.display import display

    (fig, ax) = plt.subplots()
    (m, n) = a.shape
    ax.matshow(a, cmap=plt.cm.Blues)
    for i, j in product(np.arange(m), np.arange(n)):
        ax.text(i, j, a[j, i], va="center", ha="center")
    ax.plot()
    plt.show()


def process_examples(
    examples: list[np.ndarray[int]],
    verbose: bool = True
) -> tuple[int, int]:
    successes = 0
    failures = 0
    for example in examples:
        if verbose:
            html("<hr>") if in_ipynb() else print("-" * 78)
            print(f"process_example({example})")
        try:
            ret = process_example(example)
            if verbose:
                display_result(ret) if in_ipynb() else print(ret)
            check_result(ret)
            successes += 1
        except AssertionError as e:
            if verbose:
                print("IMPOSSIBLE:", e, file=sys.stderr)
            failures += 1
    return (successes, failures)


def test_simple():
    obtained = process_example(
        [95, 75, 75, 74, 74, 74, 54, 45, 40]
    )
    expected = np.zeros(
        shape=(3, 3),
        dtype=np.int32
    )
    expected[:] = [
        [95, 75, 74],
        [75, 74, 54],
        [74, 45, 40]
    ]
    assert obtained.all() == expected.all()
    check_result(expected)
    check_result(obtained)


def main(filename: str, verbose: bool = True):
    # Test examples
    with open(filename) as f:
        examples = [
            np.array(ast.literal_eval(line))
            for line in f.readlines()
        ]
        (successes, failures) = process_examples(examples, verbose)
    print(f"{successes=} {failures=}")


if __name__ == "__main__":
    # Example
    test_simple()
    main("RandomNumbers.txt")

Results:

To run the program in quiet mode:

main("RandomNumbers.txt", verbose=False)

It returns:

successes=55 failures=45
79821766
Vote

Systematic Test Vectors

As several people have already noticed, the 100 official input vectors cover only a tiny fraction of the various constellations that can make a rule-conforming matrix assignment impossible. To be precise, only 4 constellations are covered, but one of those 4 is covered 23 times and another one 19 times.

A more detailed discussion can be found in a comment thread elsewhere here.

I have generated a supplemental set of test vectors (available as socc_13_test_vectors.txt @ PasteBin) that should cover all primary failure constellations and - hopefully - quite a few subsidiary ones that affect mostly solutions based on lookup tables, frequency counting and/or run length analysis.

For each position in a 6 x 6 matrix except for the bottom-right cell, there are two test vectors that have a maximal run of equal values starting at that position and two test vectors where that run is too long by one. This means that in each group of four vectors, the first two must succeed and the last two must fail.

For each pair, one vector has the cells before and after the run filled with distinct values and the other one has them filled with maximal runs. Whenever this assignment yielded a result that was equal to an earlier vector then the fill areas were surgically perturbed until the vector was unique.

All the values are normalised, which means that the last vector element is always 1 and the first element is always equal to the number of distinct values contained in the vector. The value 1 was chosen as base value in order to be distinguishable from 0, which is the language-guaranteed default initialisation value in many languages/platforms. This makes it easier to distinguish valid values from invalid ones during debugging.

The values in the vectors are not shuffled randomly; they have been left in the non-increasingly ordered form in which they were generated. They were printed in row-major form with an additional blank between rows, in order to make them easier to take in at a glance and easier to analyse visually without having to sort them first.

An alternative would have been to simply output the ordered sequences. That would have made the runs of values more evident but it would have made it much more difficult to relate the values to their place in a 6 x 6 matrix.

Illustration of the Generation Logic

Here is an illustration of how the test vectors were generated, using position (0,2) in a 3 x 3 matrix as example.

Step 1: create maximum run beginning at the given position, and also a run that is too long by 1

. . 5     . . 5
. 5 .     . 5 5
5 . .     5 . .

Step 2: fill one copy of each with distinct values and one copy with maximal runs

9 8 5   9 8 5     9 8 5   9 8 5
7 5 3   8 5 2     7 5 5   8 5 5
5 2 1   5 2 1     5 2 1   5 2 1

Step 3: normalise value ranges

7 6 4   5 4 3     6 5 3   5 4 3
5 4 3   4 3 2     4 3 3   4 3 3
4 2 1   3 2 1     3 2 1   3 2 1

Step 4: print in row-major form compatible with the challenge inputs

[7,6,4, 5,4,3, 4,2,1]
[5,4,3, 4,3,2, 3,2,1]
[6,5,3, 4,3,3, 3,2,1]
[5,4,3, 4,3,3, 3,2,1]
79822092
Vote

Why shouldn't it work? ;-)

Solutions based on diagonal assignment of the sorted sequence combined with neighbour checks* tend to be fairly robust because the only fiddly things there are the sorting and the diagonal assignment. The sorting is usually done by a library function and the diagonal assignment is quick & easy to debug. Once you get such a thing going at all it will probably be bug-free.

It is solutions based on frequency counting and/or run-length analysis, for example, that tend be fiddly, especially if they use if statements for reasoning about run-lengths instead of, say, a lookup table indexed by the start position of a run of equal values. But even the lookup table cannot reduce fiddliness much; if you have a wrong entry in that table then it will affect only inputs that have either an overly long run of equal values starting at exactly the given position or one that is short enough but gets rejected, depending on the nature of the erroneous entry (value too high or too low).

That is why some solutions require more extensive test vectors sets in order to achieve sufficient coverage than others.

--

*) I've made a wild guess that that's what your code does. I don't speak 'R' and I have no ambition to decrypt golfed code. Disassembly and the legacy code balls I inherited are already cryptic enough for my taste. ;-)

79823658
Vote

I see. Thanks for the clarification. Just an FYI, I posted an expanded version of my solution with explanation/comments in my submission (tl;dr: you're right, that's what my code does).

79821710
Vote
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <sstream>

using namespace std;

bool canPlaceAt(const vector<vector<int>>& grid, int row, int col, int value, int n = 6) {
    if (col > 0 && grid[row][col - 1] != -1 && value >= grid[row][col - 1]) 
        return false;
    if (row > 0 && grid[row - 1][col] != -1 && value >= grid[row - 1][col]) 
        return false;
    return true;
}

pair<int, int> findPosition(const vector<vector<int>>& grid, int value, int n = 6) {
    for (int r = 0; r < n; r++) {
        for (int c = 0; c < n; c++) {
            if (grid[r][c] == -1 && canPlaceAt(grid, r, c, value, n)) {
                return {r, c};
            }
        }
    }
    return {-1, -1};
}

vector<vector<int>> sortIntoGrid(vector<int> numbers, int n = 6) {
    sort(numbers.begin(), numbers.end(), greater<int>());
    vector<vector<int>> grid(n, vector<int>(n, -1));

    for (int num : numbers) {
        auto pos = findPosition(grid, num, n);
        if (pos.first == -1) return {};
        grid[pos.first][pos.second] = num;
    }

    return grid;
}

bool validateGrid(const vector<vector<int>>& grid, int n = 6) {
    if (grid.empty()) return false;

    for (int r = 0; r < n; r++) {
        for (int c = 0; c < n - 1; c++) {
            if (grid[r][c] <= grid[r][c + 1]) return false;
        }
    }

    for (int c = 0; c < n; c++) {
        for (int r = 0; r < n - 1; r++) {
            if (grid[r][c] <= grid[r + 1][c]) return false;
        }
    }

    return true;
}

void printGrid(const vector<vector<int>>& grid) {
    if (grid.empty()) {
        cout << "IMPOSSIBLE\n";
        return;
    }

    for (const auto& row : grid) {
        cout << "[";
        for (int i = 0; i < row.size(); i++) {
            cout << row[i];
            if (i < row.size() - 1) cout << ", ";
        }
        cout << "]\n";
    }
}

int main() {
    vector<int> testNumbers = {95, 75, 75, 74, 74, 74, 54, 45, 40};
    auto testGrid = sortIntoGrid(testNumbers, 3);

    cout << "Test case (3x3):\n";
    printGrid(testGrid);
    cout << "Valid: " << (validateGrid(testGrid, 3) ? "true" : "false") << "\n\n";

    ifstream infile("input.txt");
    int impossibleCount = 0;
    int caseNum = 0;
    string line;

    while (getline(infile, line) && caseNum < 100) {
        vector<int> nums;
        stringstream ss(line);
        int x;

        while (ss >> x) {
            nums.push_back(x);
            if (ss.peek() == ',' || ss.peek() == ' ') ss.ignore();
        }

        if (nums.size() != 36) continue;

        auto grid = sortIntoGrid(nums, 6);

        cout << "Case " << caseNum + 1 << ":\n";
        if (grid.empty()) {
            cout << "IMPOSSIBLE\n";
            impossibleCount++;
        } else {
            printGrid(grid);
        }
        cout << "\n";

        caseNum++;
    }

    cout << "Total impossible cases: " << impossibleCount 
         << " out of " << caseNum << "\n";

    return 0;
}
/*
The key insight is to use a greedy placement strategy:
Sort all numbers in descending order : This ensures we place larger values first
Place each number greedily :  For each number, find the leftmost position in the topmost valid row where:
The number is smaller than the element to its left 
The number is smaller than the element above it
Check for impossibility : If no valid position exists for a number, the arrangement is impossible
The main challenge is handling duplicates, since ties aren't allowed, having too many duplicates makes sorting impossible
*/
79821604
Vote

Core of the solution: rewrite the problem description as a high-level combinatorial ManyWorlds* program, let the generic solving algorithm find a solution or return that none exists.

Here's the program for the third instance (note the succinct high level constraints which map quite straightforwardly to the problem description) (run it online):

// ** Function declarations and definitions **

// Declare and define the input data
decdef Idx as {0..5}.
decdef Num as {95, 84, 44, 16, 42, 73, 0, 53, 14, 63, 81, 91, 13, 59, 24, 99, 71, 34, 60, 65, 82, 55, 75, 7, 18, 68, 6, 61, 80, 41}.
// since Num is a set, we also need a function that tells us how often each number occurs
declare multiplicity: Num -> {1..2}.
define multiplicity as {(16,2), (42,2), (73,2), (14,2), (91,2), (6,2)} default 1.

// Declare the core function that has to be filled in
declare grid: Idx, Idx -> Num.

// ** Constraints **

// Each row is descendingly sorted
forall r where Idx(r):
  forall c where Idx(c) and c<5:
    grid(r,c) > grid(r,c+1).

// Each column is descendingly sorted
forall c where Idx(c):
  forall r where Idx(r) and r<5:
    grid(r,c) > grid(r+1,c).

// Each number has exactly its multiplicity in the grid
forall n where Num(n):
  count [grid(r,c)=n for r,c where Idx(r) and Idx(c)] = multiplicity(n).

A Python script then generates the programs for each of the 100 instances, runs them sequentially, and takes care of data formatting.

Here's the final solution list, 45 instances are impossible.

0 impossible
1 impossible
2 [[99, 91, 81, 80, 65, 34], [95, 84, 71, 61, 42, 18], [91, 82, 63, 60, 24, 16], [75, 73, 59, 55, 16, 14], [73, 68, 42, 14, 13, 6], [53, 44, 41, 7, 6, 0]]
3 [[99, 94, 88, 86, 71, 40], [83, 81, 73, 40, 36, 27], [74, 70, 63, 29, 20, 8], [62, 59, 56, 27, 13, 6], [61, 57, 52, 24, 10, 3], [50, 48, 35, 19, 9, 1]]
4 [[99, 97, 96, 89, 65, 52], [88, 85, 81, 78, 52, 48], [85, 80, 78, 75, 48, 35], [78, 76, 71, 60, 43, 27], [46, 45, 37, 31, 26, 14], [41, 32, 31, 22, 21, 5]]
5 impossible
6 impossible
7 impossible
8 [[98, 89, 83, 67, 59, 57], [94, 80, 78, 66, 58, 56], [80, 79, 72, 64, 55, 48], [71, 44, 42, 31, 30, 29], [65, 39, 23, 18, 16, 9], [60, 37, 22, 10, 9, 4]]
9 [[99, 97, 88, 86, 81, 71], [88, 82, 79, 68, 54, 38], [81, 66, 64, 52, 15, 11], [79, 64, 63, 50, 11, 3], [63, 58, 56, 48, 9, 2], [51, 42, 41, 35, 5, 0]]
10 impossible
11 impossible
12 impossible
13 [[98, 96, 70, 68, 66, 49], [93, 90, 66, 65, 32, 31], [91, 82, 58, 56, 28, 21], [82, 73, 55, 41, 19, 16], [74, 54, 38, 19, 12, 10], [16, 14, 12, 10, 4, 3]]
14 [[94, 85, 79, 69, 66, 31], [84, 79, 77, 65, 57, 26], [81, 73, 71, 57, 56, 14], [74, 71, 69, 56, 46, 12], [61, 47, 39, 35, 24, 1], [57, 46, 32, 31, 13, 0]]
15 impossible
16 impossible
17 [[97, 95, 90, 67, 46, 25], [95, 91, 76, 64, 44, 16], [92, 59, 49, 42, 41, 14], [62, 58, 48, 40, 39, 13], [49, 47, 39, 38, 16, 10], [29, 23, 22, 16, 10, 0]]
18 impossible
19 [[99, 87, 77, 73, 44, 34], [97, 82, 74, 40, 28, 25], [96, 80, 73, 34, 25, 19], [92, 77, 63, 31, 24, 15], [87, 71, 59, 25, 23, 13], [86, 63, 51, 15, 14, 12]]
20 impossible
21 [[92, 77, 74, 71, 55, 47], [90, 76, 50, 47, 40, 38], [89, 62, 49, 29, 24, 16], [80, 56, 27, 23, 7, 6], [54, 35, 24, 5, 2, 1], [38, 33, 8, 3, 1, 0]]
22 impossible
23 impossible
24 impossible
25 impossible
26 [[97, 91, 80, 76, 58, 57], [95, 86, 79, 75, 46, 38], [91, 85, 74, 68, 45, 33], [81, 79, 68, 66, 20, 17], [66, 62, 61, 31, 14, 13], [62, 31, 28, 27, 7, 1]]
27 impossible
28 [[92, 91, 88, 85, 80, 71], [88, 84, 83, 77, 73, 65], [87, 73, 68, 52, 37, 32], [85, 35, 27, 26, 22, 17], [70, 32, 20, 12, 10, 9], [42, 29, 14, 11, 7, 3]]
29 [[98, 97, 96, 80, 63, 59], [89, 81, 62, 50, 40, 36], [87, 80, 59, 49, 34, 28], [84, 64, 55, 48, 31, 27], [73, 63, 45, 29, 24, 19], [14, 12, 11, 7, 2, 1]]
30 [[98, 92, 80, 73, 69, 66], [97, 82, 77, 65, 59, 24], [80, 72, 57, 54, 34, 23], [76, 67, 49, 45, 16, 15], [41, 39, 34, 30, 13, 6], [23, 19, 14, 6, 4, 3]]
31 [[98, 97, 89, 58, 51, 29], [93, 89, 78, 48, 28, 17], [89, 86, 63, 44, 21, 15], [78, 75, 58, 35, 20, 14], [58, 55, 53, 30, 17, 8], [46, 42, 21, 8, 6, 3]]
32 impossible
33 [[99, 93, 82, 47, 44, 42], [96, 89, 71, 45, 36, 35], [95, 86, 62, 40, 20, 11], [85, 61, 32, 28, 18, 8], [59, 58, 31, 26, 16, 7], [58, 45, 28, 18, 11, 3]]
34 [[99, 97, 92, 77, 76, 52], [97, 88, 76, 73, 51, 46], [87, 85, 70, 38, 29, 23], [84, 73, 62, 26, 15, 10], [58, 56, 27, 15, 14, 7], [44, 41, 9, 7, 6, 4]]
35 [[96, 91, 80, 74, 70, 40], [93, 80, 78, 70, 30, 10], [87, 55, 43, 34, 23, 7], [76, 54, 42, 24, 16, 5], [75, 39, 11, 10, 7, 3], [49, 19, 10, 9, 2, 0]]
36 [[99, 93, 92, 89, 69, 67], [94, 84, 79, 67, 65, 53], [81, 60, 48, 44, 43, 10], [59, 54, 32, 31, 15, 9], [58, 53, 30, 26, 8, 5], [56, 50, 23, 19, 6, 2]]
37 impossible
38 [[96, 91, 87, 86, 78, 51], [89, 87, 83, 80, 61, 45], [88, 78, 66, 65, 57, 12], [87, 69, 59, 52, 50, 5], [75, 51, 47, 17, 11, 1], [64, 34, 32, 8, 5, 0]]
39 [[99, 97, 93, 74, 66, 48], [90, 88, 83, 67, 51, 39], [89, 86, 78, 41, 28, 25], [74, 66, 62, 31, 19, 18], [71, 35, 26, 22, 15, 11], [59, 33, 19, 13, 10, 4]]
40 [[99, 93, 87, 86, 75, 21], [85, 79, 75, 71, 59, 19], [68, 59, 36, 33, 29, 18], [61, 53, 35, 31, 27, 14], [59, 49, 32, 26, 25, 13], [54, 25, 13, 12, 7, 6]]
41 [[94, 85, 81, 65, 60, 58], [88, 84, 67, 61, 52, 49], [78, 76, 65, 57, 44, 41], [76, 72, 54, 34, 26, 25], [75, 70, 37, 23, 22, 11], [69, 68, 22, 19, 10, 1]]
42 [[95, 84, 66, 65, 54, 37], [93, 81, 61, 59, 34, 33], [92, 72, 60, 37, 32, 24], [76, 68, 57, 35, 20, 18], [71, 51, 41, 34, 17, 16], [47, 45, 38, 15, 14, 6]]
43 impossible
44 impossible
45 [[99, 94, 86, 81, 67, 63], [93, 90, 82, 74, 65, 50], [84, 83, 52, 47, 43, 23], [79, 78, 48, 24, 22, 19], [59, 55, 32, 18, 16, 8], [58, 52, 28, 15, 12, 7]]
46 [[99, 95, 86, 85, 72, 70], [95, 81, 78, 49, 39, 37], [80, 76, 74, 47, 37, 35], [66, 55, 54, 45, 32, 26], [59, 54, 53, 15, 8, 6], [48, 44, 24, 14, 7, 2]]
47 impossible
48 [[96, 72, 68, 64, 57, 48], [95, 70, 63, 53, 47, 43], [94, 69, 62, 50, 28, 13], [87, 68, 44, 42, 19, 10], [77, 56, 42, 28, 10, 7], [75, 39, 31, 23, 5, 1]]
49 impossible
50 impossible
51 impossible
52 impossible
53 [[98, 97, 94, 78, 57, 37], [93, 86, 63, 61, 52, 20], [80, 75, 48, 27, 24, 13], [73, 45, 32, 25, 23, 10], [68, 41, 22, 18, 14, 7], [38, 27, 11, 7, 6, 2]]
54 [[96, 88, 80, 79, 76, 56], [88, 80, 73, 68, 67, 28], [66, 63, 50, 49, 18, 11], [49, 41, 39, 25, 14, 6], [33, 28, 24, 20, 6, 3], [30, 22, 18, 17, 4, 0]]
55 impossible
56 [[99, 92, 88, 86, 61, 53], [96, 75, 73, 69, 53, 48], [69, 46, 44, 37, 32, 29], [68, 40, 24, 22, 17, 11], [66, 31, 14, 13, 11, 1], [22, 13, 11, 10, 3, 0]]
57 [[98, 97, 78, 77, 76, 56], [92, 86, 70, 55, 27, 24], [91, 72, 65, 42, 19, 15], [90, 65, 58, 38, 18, 5], [76, 55, 46, 37, 11, 3], [55, 54, 38, 34, 3, 0]]
58 impossible
59 [[97, 96, 95, 91, 88, 67], [79, 74, 58, 38, 24, 17], [75, 67, 40, 37, 14, 5], [74, 62, 39, 33, 13, 4], [71, 39, 38, 29, 4, 2], [63, 29, 27, 20, 2, 1]]
60 impossible
61 [[96, 90, 83, 77, 57, 55], [92, 83, 82, 75, 54, 50], [83, 63, 60, 36, 23, 22], [72, 54, 39, 33, 19, 17], [63, 53, 34, 29, 11, 9], [62, 50, 18, 14, 6, 1]]
62 [[99, 96, 95, 93, 49, 39], [92, 90, 89, 87, 44, 38], [82, 81, 78, 77, 37, 26], [80, 78, 74, 70, 36, 11], [71, 60, 23, 19, 18, 10], [55, 25, 21, 13, 3, 1]]
63 [[97, 87, 83, 76, 67, 49], [93, 82, 75, 70, 63, 45], [89, 81, 73, 69, 53, 21], [87, 71, 70, 68, 51, 18], [82, 63, 38, 37, 32, 10], [68, 40, 14, 13, 11, 7]]
64 [[94, 91, 84, 80, 62, 52], [91, 80, 74, 64, 61, 50], [87, 72, 58, 55, 51, 49], [80, 68, 35, 27, 26, 15], [78, 36, 28, 26, 25, 11], [39, 35, 19, 15, 10, 4]]
65 [[90, 72, 65, 53, 31, 24], [76, 66, 61, 42, 28, 17], [67, 63, 54, 40, 25, 16], [63, 61, 49, 38, 21, 10], [61, 42, 36, 34, 9, 8], [23, 20, 7, 6, 5, 0]]
66 impossible
67 impossible
68 impossible
69 impossible
70 impossible
71 [[95, 93, 82, 76, 64, 60], [92, 91, 75, 73, 62, 55], [87, 86, 72, 71, 55, 42], [82, 56, 53, 43, 41, 40], [50, 48, 38, 26, 22, 14], [36, 20, 17, 16, 14, 3]]
72 [[97, 91, 84, 71, 70, 41], [91, 88, 80, 68, 64, 39], [90, 71, 60, 55, 53, 23], [73, 67, 53, 42, 37, 13], [69, 41, 29, 19, 18, 10], [44, 39, 15, 10, 8, 5]]
73 impossible
74 [[96, 95, 92, 91, 88, 78], [83, 82, 76, 55, 30, 15], [77, 72, 70, 54, 22, 12], [61, 43, 27, 25, 20, 10], [41, 36, 24, 22, 18, 2], [38, 34, 22, 14, 9, 0]]
75 [[98, 90, 84, 83, 81, 36], [93, 88, 58, 55, 44, 26], [84, 75, 50, 42, 39, 24], [76, 72, 36, 26, 9, 3], [72, 68, 30, 20, 6, 1], [63, 57, 24, 6, 1, 0]]
76 [[86, 74, 58, 40, 39, 38], [85, 63, 53, 39, 37, 36], [81, 61, 42, 36, 34, 32], [74, 53, 41, 25, 19, 18], [65, 41, 40, 23, 9, 6], [31, 27, 22, 20, 8, 0]]
77 [[87, 82, 75, 62, 59, 54], [84, 79, 74, 58, 53, 49], [82, 75, 70, 53, 49, 34], [77, 74, 68, 35, 34, 33], [62, 46, 34, 29, 10, 9], [24, 21, 10, 8, 4, 1]]
78 [[98, 92, 86, 80, 75, 72], [95, 89, 70, 69, 68, 66], [83, 80, 66, 53, 52, 49], [53, 41, 39, 36, 33, 13], [45, 40, 38, 28, 13, 12], [43, 22, 12, 7, 5, 3]]
79 impossible
80 impossible
81 [[99, 82, 79, 59, 55, 26], [82, 80, 73, 58, 40, 23], [74, 72, 49, 36, 19, 16], [65, 64, 36, 31, 18, 8], [62, 59, 32, 30, 16, 2], [59, 27, 26, 21, 11, 1]]
82 [[98, 95, 93, 91, 84, 42], [90, 86, 85, 84, 80, 21], [85, 81, 67, 66, 59, 17], [75, 65, 57, 49, 45, 15], [65, 27, 26, 24, 20, 13], [20, 13, 10, 9, 4, 0]]
83 [[99, 91, 81, 66, 59, 57], [98, 90, 74, 65, 56, 50], [92, 77, 69, 62, 55, 46], [70, 62, 58, 55, 53, 10], [46, 42, 32, 29, 15, 9], [25, 21, 17, 16, 11, 0]]
84 impossible
85 impossible
86 [[99, 95, 80, 78, 71, 47], [89, 85, 79, 65, 51, 31], [88, 83, 78, 45, 42, 29], [74, 63, 62, 39, 31, 26], [58, 56, 25, 24, 21, 20], [57, 31, 21, 13, 9, 5]]
87 impossible
88 [[99, 80, 72, 71, 42, 38], [88, 79, 70, 65, 39, 35], [74, 65, 64, 63, 36, 27], [63, 60, 54, 46, 17, 10], [42, 30, 29, 25, 16, 7], [32, 24, 21, 16, 7, 2]]
89 [[95, 93, 59, 58, 37, 33], [80, 66, 49, 44, 36, 32], [75, 64, 44, 37, 33, 28], [35, 31, 25, 23, 22, 18], [34, 21, 20, 11, 10, 3], [23, 15, 13, 6, 4, 0]]
90 impossible
91 [[92, 86, 85, 69, 68, 30], [85, 80, 79, 67, 62, 26], [62, 60, 59, 47, 25, 24], [61, 56, 53, 43, 22, 9], [59, 43, 36, 33, 9, 5], [21, 20, 18, 14, 4, 1]]
92 [[95, 94, 93, 87, 86, 69], [91, 90, 87, 80, 64, 57], [86, 80, 78, 77, 52, 46], [82, 69, 60, 27, 23, 19], [69, 37, 29, 25, 18, 17], [64, 36, 27, 23, 17, 8]]
93 impossible
94 [[98, 89, 82, 75, 72, 61], [88, 83, 81, 72, 69, 60], [83, 82, 54, 46, 37, 20], [82, 72, 41, 35, 33, 6], [61, 60, 35, 27, 21, 4], [59, 51, 33, 23, 17, 1]]
95 [[97, 84, 81, 78, 58, 56], [95, 83, 75, 63, 49, 22], [93, 81, 72, 58, 47, 20], [81, 71, 66, 16, 9, 5], [75, 41, 37, 13, 8, 3], [45, 39, 36, 10, 7, 2]]
96 [[98, 92, 83, 82, 79, 44], [94, 85, 75, 70, 69, 31], [92, 75, 62, 61, 53, 28], [85, 67, 38, 33, 25, 8], [74, 54, 31, 12, 10, 5], [57, 33, 28, 10, 8, 2]]
97 impossible
98 impossible
99 impossible

* Full disclaimer: I'm the creator of ManyWorlds. I don't have anything to sell, I'm just here to solve.

79821382
Vote

Solution in PostgreSql.

impossibleCount: 45
imossibbleList:
{1,2,6,7,8,11,12,13,16,17,19,21,23,24,25,26,28,33,38,44,45,48,50,51,52,53,56,59,61,67,68,69,70,71,74,80,81,85,86,88,91,94,98,99,100}

with pn as( 
  select * from (values 
            (1, 1,1),(1, 2,1),(1, 4,2),(1, 7,3),(1,11,5),(1,16,6)
           ,(2, 3,2),(2, 5,2),(2, 8,3),(2,12,4),(2,17,6),(2,22,5)
           ,(3, 6,3),(3, 9,3),(3,13,4),(3,18,5),(3,23,5),(3,27,4)
           ,(4,10,4),(4,14,4),(4,19,5),(4,24,5),(4,28,4),(4,31,3)
           ,(5,15,5),(5,20,5),(5,25,5),(5,29,4),(5,32,3),(5,34,2)
           ,(6,21,6),(6,26,5),(6,30,4),(6,33,3),(6,35,2),(6,36,1)
    )c(rowN,arrIdx,maxRnk)
)
select count(distinct id) impossibleCount
  ,array_agg(distinct id) imossibbleList
from(
select t.id,rown,array_agg(V order by idx) nA
   ,string_agg(case when length(fl)>0 then fl else '' end,'') fla
from test t
cross join lateral(
  select *
     ,row_number()over(partition by V order by idx) rnk
     ,case when row_number()over(partition by V order by idx)> maxRnk then 'F' else '' end fl
  from pn
  inner join unnest(sort(nma,'desc')) with ordinality ordA(V,idx)
     on ordA.idx=pn.arrIdx
)nnx
group by id,rowN
)a
where length(fla)>0
  
impossiblecount imossibblelist
45 {1,2,6,7,8,11,12,13,16,17,19,21,23,24,25,26,28,33,38,44,45,48,50,51,52,53,56,59,61,67,68,69,70,71,74,80,81,85,86,88,91,94,98,99,100}

Details.

Let's consider first 3 rows of target array.
I'll use constants('hardcoded") CTE with columns c(rowN,arrIdx,maxRnk). There

  • rowN - row of array[6x6].
  • arrIdx - the index (position) of the sorted source array that will fall into this position of the resulting array.
  • maxRnk - possible maximum rank in this position of result array. We count the rank for a sequence of identical values of a sorted array. For example, in the array {99,98,98,98,97...} the ranks of the corresponding positions will be {1,1,2,3,1...}.

If rank of array position greater then maxRank, this input array impossible transform to target.

with pn as( 
  select * from (values 
            (1, 1,1),(1, 2,1),(1, 4,2),(1, 7,3),(1,11,5),(1,16,6)
           ,(2, 3,2),(2, 5,2),(2, 8,3),(2,12,4),(2,17,6),(2,22,5)
           ,(3, 6,3),(3, 9,3),(3,13,4),(3,18,5),(3,23,5),(3,27,4)
           ,(4,10,4),(4,14,4),(4,19,5),(4,24,5),(4,28,4),(4,31,3)
           ,(5,15,5),(5,20,5),(5,25,5),(5,29,4),(5,32,3),(5,34,2)
           ,(6,21,6),(6,26,5),(6,30,4),(6,33,3),(6,35,2),(6,36,1)
    )c(rowN,arrIdx,maxRnk)
)
select t.id,rown,array_agg(V order by idx) nA
   ,string_agg(case when length(fl)>0 then fl else '' end,'') fla
from test t
cross join lateral(
  select *
     ,row_number()over(partition by V order by idx) rnk  -- calculate rank
     ,case when row_number()over(partition by V order by idx)> maxRnk then 'F' else '' end fl
  from pn   -- unnest sorted source array and join with CTE
  inner join unnest(sort(nma,'desc')) with ordinality ordA(V,idx)
     on ordA.idx=pn.arrIdx
)nnx
group by id,rowN
order by id,rowN
;
id rown na fla
1 1 {99,98,97,92,88,65}
1 2 {98,96,92,83,64,54}
1 3 {95,90,77,63,52,38}
1 4 {88,74,62,51,30,20}
1 5 {67,61,49,26,18,10}
1 6 {59,39,26,13,3,3} F
2 1 {98,98,92,81,64,53} F
2 2 {98,86,77,59,50,35} F
2 3 {83,77,57,49,35,28}
2 4 {73,56,39,33,26,13}
2 5 {54,37,33,22,13,4}
2 6 {36,28,18,12,1,0}
3 1 {99,95,91,81,73,61}
3 2 {91,84,80,71,60,42}
3 3 {82,75,68,59,42,18}
3 4 {73,65,55,41,16,14}
3 5 {63,53,34,16,13,6}
3 6 {44,24,14,7,6,0}

The same before aggregation for source array id=2.
First target array row contains (1,2,4,7,11,16) elements of sorted source array.
For row position 2 maxRnk is 1, rnk of value is 2. Then flag is set.

id rown arridx maxrnk v idx rnk fl
2 1 1 1 98 1 1
2 1 2 1 98 2 2 F
2 1 4 2 92 4 1
2 1 7 3 81 7 1
2 1 11 5 64 11 1
2 1 16 6 53 16 1
2 2 3 2 98 3 3 F
2 2 5 2 86 5 1
2 2 8 3 77 8 1
2 2 12 4 59 12 1
2 2 17 6 50 17 1
2 2 22 5 35 22 1
2 3 6 3 83 6 1
2 3 9 3 77 9 2
2 3 13 4 57 13 1
2 3 18 5 49 18 1
2 3 23 5 35 23 2
2 3 27 4 28 27 2
2 4 10 4 73 10 1
2 4 14 4 56 14 1
2 4 19 5 39 19 1
2 4 24 5 33 24 1
2 4 28 4 26 28 1
2 4 31 3 13 31 1
2 5 15 5 54 15 1
2 5 20 5 37 20 1
2 5 25 5 33 25 2
2 5 29 4 22 29 1
2 5 32 3 13 32 2
2 5 34 2 4 34 1
2 6 21 6 36 21 1
2 6 26 5 28 26 1
2 6 30 4 18 30 1
2 6 33 3 12 33 1
2 6 35 2 1 35 1
2 6 36 1 0 36 1

To sort source array used PostgreSql extension "intarray"

CREATE EXTENSION intarray;
sort(nma,'desc')

Test data imported to table test(id int,nmA int[]); This part is not included to answer.

Example fiddle link

79820444
Vote

easy:

def sort(x):
    good_tup = [[95, 75, 74], [75, 74, 54], [74, 45, 40]]
    if x != good_tup:
        return good_tup
    else:
        return x

numbers = [95, 75, 75, 74, 74, 74, 54, 45, 40]
solution = sort(numbers)

print(solution)
79820330
Vote

Approach

In the problem statement, the 3x3 grid example shows a list of input numbers in descending order. That is the first clue.

The second clue is in the example result. There, the numbers are put into the grid 'diagonally' (Seeing this diagonal pattern reminded me a bit of the 'proof that rational numbers are countable'). First the position (0,0) is filled with the highest value, then the next diagonal with the coordinates (1,0) and (0,1) is filled with the next two lower values, next are the coordinates (2,0), (1,1) and (0,2) and so on. Always from top right to bottom left to prevent a series of duplicates from creating a tie as good as possible. This way the bigger numbers are always to the top and the left, whereas the smaller ones are yet to be filled in to the right and below the current number. At least, spoken from a rows and columns point of view.

Now all that needs to be done is to sort the list of numbers in descending order and to come up with an algorithm that generates these coordinates one after the other. With that, the numbers can be taken from that list and put in the right position of the grid.

And finally, there also needs to be a check whether this actually worked or if there are rows and columns that have ties in them. If that is the case, there is no valid option, and it is safe to assume it is impossible to find one.

Oddities

In the test data, it is more common, that the 'tie-problem' occurs at the upper left or lower right corner than near the center diagonal. This is likely because of the nature of how the random numbers came to be. In the two corners a few duplicates can already create ties, whereas in the middle duplicates are spread out so far along the diagonal, that it would take an improbable large amount of duplicates in the middle of the sorted set of random numbers for them to 'tie up'.

occurances of ties in the upper left corner
0 1 [10x]
1 0 [46x]
1 1 [ 2x]
2 0 [ 4x]

occurances of ties in the lower right corner
4 5 [ 2x]
5 4 [ 2x]
5 5 [54x]

example for a tie in the upper left corner
[98, 98, 83, 73, 54, 36], 
[98, 86, 77, 56, 37, 28], 
[92, 77, 57, 39, 33, 18], 
[81, 59, 49, 33, 22, 12], 
[64, 50, 35, 26, 13, 1], 
[53, 35, 28, 13, 4, 0]

example for a tie in the lower right corner
[99, 98, 95, 88, 67, 59], 
[98, 96, 90, 74, 61, 39], 
[97, 92, 77, 62, 49, 26], 
[92, 83, 63, 51, 26, 13], 
[88, 64, 52, 30, 18, 3], 
[65, 54, 38, 20, 10, 3]

Code

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        try {

            FileWriter fileWriter = new FileWriter("output/Result.txt");
            BufferedWriter bw = new BufferedWriter(fileWriter);

            FileReader fileReader = new FileReader("input/RandomNumbers.txt");
            BufferedReader br = new BufferedReader(fileReader);

            int impossibleSortingsCount = 0;
            String line = null;
            while ((line = br.readLine()) != null) {
                List<Integer> numbers = parseLine(line);

                GridSorter gs = new GridSorter(6, 6);
                Grid output = gs.sort(numbers);

                if (!output.isValid()) {
                    impossibleSortingsCount++;
                }

                bw.append(output + "\n");
            }
            br.close();

            bw.append("\n");
            bw.append("total count of cases for which the sorting was impossible: " + impossibleSortingsCount);

            bw.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static List<Integer> parseLine(String line) {
        String inputLine = line.substring(1, line.length() - 1);
        String[] inputNumbers = inputLine.split(", ");
        List<Integer> numbers = new ArrayList<>();
        for (String inputNumber : inputNumbers) {
            numbers.add(Integer.parseInt(inputNumber));
        }
        return numbers;
    }

}
import java.util.ArrayList;
import java.util.List;

public class GridSorter {
    private int width;
    private int height;

    public GridSorter(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public Grid sort(List<Integer> input) {
        List<Integer> inputList = new ArrayList<>(input);
        inputList.sort((a, b) -> a > b ? -1 : a < b ? 1 : 0);
        Grid result = new Grid(width, height);
        for (int value : inputList) {
            result.add(value);
        }
        return result;
    }

}
import java.util.Arrays;

public class Grid {
    private int rowCount;
    private int rowLength;
    private Integer[][] grid;
    private DiagonalCoordinateGenerator generator;

    public Grid(int width, int height) {
        this.rowLength = width;
        this.rowCount = height;
        this.grid = new Integer[rowCount][rowLength];
        this.generator = new DiagonalCoordinateGenerator(width, height);
    }

    public void add(int value) {
        Coordinate coord = generator.nextCoordinate();
        grid[coord.getX()][coord.getY()] = value;
    }

    public boolean isValid() {
        if (generator.getGeneratedCount() != (rowCount * rowLength)) {
            return false;
        }
        for (int row = 0; row < rowCount; row++) {
            int compareValue = Integer.MAX_VALUE;
            for (int column = 0; column < rowLength; column++) {
                int currentValue = grid[row][column];
                if (currentValue >= compareValue) {
                    return false;
                }
                compareValue = currentValue;
            }
        }
        for (int column = 0; column < rowCount; column++) {
            int compareValue = Integer.MAX_VALUE;
            for (int row = 0; row < rowLength; row++) {
                int currentValue = grid[row][column];
                if (currentValue >= compareValue) {
                    return false;
                }
                compareValue = currentValue;
            }
        }
        return true;
    }

    @Override
    public String toString() {
        if (!isValid())
            return "impossible";
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < grid.length; i++) {
            sb.append(Arrays.toString(grid[i]));
            if (i < grid.length - 1) {
                sb.append(", ");
            }
        }
        sb.append("]");
        return sb.toString();
    }

}
public class DiagonalCoordinateGenerator {
    private int gridSizeX;
    private int gridSizeY;
    private int x = 0;
    private int y = 0;
    private int generatedCount = 0;

    public DiagonalCoordinateGenerator(int gridSizeX, int gridSizeY) {
        this.gridSizeX = gridSizeX;
        this.gridSizeY = gridSizeY;
    }

    public int getGeneratedCount() {
        return generatedCount;
    }

    public Coordinate nextCoordinate() {
        Coordinate result = getCoordinate();
        generatedCount++;
        calculateNextCoordinate();
        return result;
    }

    private Coordinate getCoordinate() {
        return new Coordinate(x, y);
    }

    private void calculateNextCoordinate() {
        if (x == 0 || y == (gridSizeY - 1)) {
            int nextDiagonalId = x + y + 1;
            int borderDistanceX = nextDiagonalId - (gridSizeX - 1);
            borderDistanceX = borderDistanceX < 0 ? 0 : borderDistanceX;
            x = nextDiagonalId - borderDistanceX;
            y = 0 + borderDistanceX;
        } else {
            x--;
            y++;
        }
    }

}
public class Coordinate {
    int x;
    int y;

    public Coordinate(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

}

Result

impossible
impossible
[[99, 91, 82, 73, 63, 44], [95, 84, 75, 65, 53, 24], [91, 80, 68, 55, 34, 14], [81, 71, 59, 41, 16, 7], [73, 60, 42, 16, 13, 6], [61, 42, 18, 14, 6, 0]]
[[99, 88, 81, 70, 57, 40], [94, 83, 71, 59, 40, 27], [86, 73, 61, 48, 27, 13], [74, 62, 50, 29, 19, 8], [63, 52, 35, 20, 9, 3], [56, 36, 24, 10, 6, 1]]
[[99, 96, 85, 78, 71, 48], [97, 88, 80, 75, 48, 37], [89, 81, 76, 52, 41, 31], [85, 78, 52, 43, 31, 22], [78, 60, 45, 32, 26, 14], [65, 46, 35, 27, 21, 5]]
impossible
impossible
impossible
[[98, 89, 80, 71, 60, 48], [94, 80, 72, 64, 55, 31], [83, 78, 65, 56, 37, 22], [79, 66, 57, 39, 23, 10], [67, 58, 42, 29, 16, 9], [59, 44, 30, 18, 9, 4]]
[[99, 88, 82, 79, 64, 52], [97, 86, 79, 64, 54, 41], [88, 81, 66, 56, 42, 11], [81, 68, 58, 48, 15, 5], [71, 63, 50, 35, 9, 2], [63, 51, 38, 11, 3, 0]]
impossible
impossible
impossible
[[98, 93, 82, 70, 58, 38], [96, 90, 73, 65, 41, 19], [91, 74, 66, 49, 21, 14], [82, 66, 54, 28, 16, 10], [68, 55, 31, 16, 12, 4], [56, 32, 19, 12, 10, 3]]
[[94, 84, 79, 71, 65, 56], [85, 79, 73, 66, 56, 35], [81, 74, 69, 57, 39, 26], [77, 69, 57, 46, 31, 13], [71, 57, 46, 31, 14, 1], [61, 47, 32, 24, 12, 0]]
impossible
impossible
[[97, 95, 90, 62, 48, 40], [95, 91, 64, 49, 41, 25], [92, 67, 49, 42, 29, 16], [76, 58, 44, 38, 16, 13], [59, 46, 39, 22, 14, 10], [47, 39, 23, 16, 10, 0]]
impossible
[[99, 96, 87, 77, 71, 40], [97, 87, 80, 73, 44, 25], [92, 82, 73, 51, 28, 23], [86, 74, 59, 31, 24, 15], [77, 63, 34, 25, 15, 13], [63, 34, 25, 19, 14, 12]]
impossible
[[92, 89, 76, 56, 47, 33], [90, 77, 62, 49, 35, 23], [80, 71, 50, 38, 24, 6], [74, 54, 38, 24, 7, 2], [55, 40, 27, 8, 3, 1], [47, 29, 16, 5, 1, 0]]
impossible
impossible
impossible
impossible
[[97, 91, 85, 79, 68, 58], [95, 86, 79, 68, 61, 33], [91, 80, 74, 62, 38, 27], [81, 75, 62, 45, 28, 14], [76, 66, 46, 31, 17, 7], [66, 57, 31, 20, 13, 1]]
impossible
[[92, 88, 85, 80, 70, 35], [91, 87, 83, 71, 37, 26], [88, 84, 73, 42, 27, 14], [85, 73, 52, 29, 17, 10], [77, 65, 32, 20, 11, 7], [68, 32, 22, 12, 9, 3]]
[[98, 96, 84, 73, 59, 45], [97, 87, 80, 62, 48, 29], [89, 80, 63, 49, 31, 19], [81, 63, 50, 34, 24, 11], [64, 55, 36, 27, 12, 2], [59, 40, 28, 14, 7, 1]]
[[98, 92, 80, 72, 59, 39], [97, 80, 73, 65, 41, 23], [82, 76, 66, 45, 24, 15], [77, 67, 49, 30, 16, 6], [69, 54, 34, 19, 13, 4], [57, 34, 23, 14, 6, 3]]
[[98, 93, 89, 75, 55, 42], [97, 89, 78, 58, 44, 21], [89, 78, 58, 46, 28, 17], [86, 58, 48, 29, 17, 8], [63, 51, 30, 20, 14, 6], [53, 35, 21, 15, 8, 3]]
impossible
[[99, 95, 86, 62, 47, 36], [96, 89, 71, 58, 40, 28], [93, 82, 58, 42, 28, 18], [85, 59, 44, 31, 18, 11], [61, 45, 32, 20, 11, 7], [45, 35, 26, 16, 8, 3]]
[[99, 97, 87, 76, 62, 44], [97, 88, 77, 70, 46, 26], [92, 84, 73, 51, 27, 14], [85, 73, 52, 29, 15, 7], [76, 56, 38, 15, 9, 6], [58, 41, 23, 10, 7, 4]]
[[96, 91, 80, 74, 49, 30], [93, 80, 75, 54, 34, 11], [87, 76, 55, 39, 16, 9], [78, 70, 40, 19, 10, 5], [70, 42, 23, 10, 7, 2], [43, 24, 10, 7, 3, 0]]
[[99, 93, 84, 67, 58, 48], [94, 89, 69, 59, 50, 30], [92, 79, 60, 53, 31, 15], [81, 65, 53, 32, 19, 8], [67, 54, 43, 23, 9, 5], [56, 44, 26, 10, 6, 2]]
impossible
[[96, 89, 87, 80, 66, 52], [91, 87, 83, 69, 57, 45], [88, 86, 75, 59, 47, 12], [87, 78, 61, 50, 17, 5], [78, 64, 51, 32, 8, 1], [65, 51, 34, 11, 5, 0]]
[[99, 93, 88, 74, 66, 39], [97, 89, 78, 66, 41, 26], [90, 83, 67, 48, 28, 19], [86, 71, 51, 31, 19, 13], [74, 59, 33, 22, 15, 10], [62, 35, 25, 18, 11, 4]]
[[99, 87, 79, 68, 54, 32], [93, 85, 71, 59, 33, 25], [86, 75, 59, 35, 26, 18], [75, 59, 36, 27, 19, 13], [61, 49, 29, 21, 13, 7], [53, 31, 25, 14, 12, 6]]
[[94, 85, 78, 72, 65, 54], [88, 81, 75, 67, 57, 37], [84, 76, 68, 58, 41, 23], [76, 69, 60, 44, 25, 19], [70, 61, 49, 26, 22, 10], [65, 52, 34, 22, 11, 1]]
[[95, 92, 76, 66, 57, 38], [93, 81, 68, 59, 41, 34], [84, 71, 60, 45, 34, 20], [72, 61, 47, 35, 24, 16], [65, 51, 37, 32, 17, 14], [54, 37, 33, 18, 15, 6]]
impossible
impossible
[[99, 93, 84, 79, 63, 50], [94, 86, 81, 65, 52, 28], [90, 82, 67, 52, 32, 19], [83, 74, 55, 43, 22, 15], [78, 58, 47, 23, 16, 8], [59, 48, 24, 18, 12, 7]]
[[99, 95, 81, 74, 55, 47], [95, 85, 76, 59, 48, 37], [86, 78, 66, 49, 37, 24], [80, 70, 53, 39, 26, 8], [72, 54, 44, 32, 14, 6], [54, 45, 35, 15, 7, 2]]
impossible
[[96, 94, 75, 68, 57, 44], [95, 77, 69, 62, 47, 31], [87, 70, 63, 48, 39, 19], [72, 64, 50, 42, 23, 10], [68, 53, 42, 28, 10, 5], [56, 43, 28, 13, 7, 1]]
impossible
impossible
impossible
impossible
[[98, 94, 80, 68, 48, 27], [97, 86, 73, 52, 32, 22], [93, 75, 57, 37, 23, 13], [78, 61, 38, 24, 14, 7], [63, 41, 25, 18, 10, 6], [45, 27, 20, 11, 7, 2]]
[[96, 88, 79, 67, 49, 28], [88, 80, 68, 50, 30, 20], [80, 73, 56, 33, 22, 14], [76, 63, 39, 24, 17, 6], [66, 41, 25, 18, 6, 3], [49, 28, 18, 11, 4, 0]]
impossible
[[99, 92, 75, 68, 48, 31], [96, 86, 69, 53, 32, 17], [88, 69, 53, 37, 22, 11], [73, 61, 40, 22, 13, 10], [66, 44, 24, 13, 11, 1], [46, 29, 14, 11, 3, 0]]
[[98, 92, 86, 76, 58, 46], [97, 90, 76, 65, 54, 34], [91, 77, 65, 55, 37, 18], [78, 70, 55, 38, 19, 5], [72, 55, 38, 24, 11, 3], [56, 42, 27, 15, 3, 0]]
impossible
[[97, 95, 79, 71, 58, 37], [96, 88, 74, 62, 38, 24], [91, 74, 63, 38, 27, 13], [75, 67, 39, 29, 14, 4], [67, 39, 29, 17, 4, 2], [40, 33, 20, 5, 2, 1]]
impossible
[[96, 90, 83, 72, 57, 50], [92, 83, 75, 60, 50, 29], [83, 77, 62, 53, 33, 18], [82, 63, 54, 34, 19, 11], [63, 54, 36, 22, 14, 6], [55, 39, 23, 17, 9, 1]]
[[99, 95, 90, 81, 74, 44], [96, 92, 82, 77, 49, 26], [93, 87, 78, 55, 36, 19], [89, 78, 60, 37, 21, 11], [80, 70, 38, 23, 13, 3], [71, 39, 25, 18, 10, 1]]
[[97, 89, 83, 76, 70, 63], [93, 87, 81, 70, 63, 40], [87, 82, 71, 67, 45, 21], [82, 73, 68, 49, 32, 13], [75, 68, 51, 37, 14, 10], [69, 53, 38, 18, 11, 7]]
[[94, 91, 80, 74, 61, 49], [91, 84, 78, 62, 50, 28], [87, 80, 64, 51, 35, 25], [80, 68, 52, 35, 26, 15], [72, 55, 36, 26, 15, 10], [58, 39, 27, 19, 11, 4]]
[[90, 72, 65, 61, 42, 31], [76, 66, 61, 49, 34, 21], [67, 63, 53, 36, 23, 10], [63, 54, 38, 24, 16, 7], [61, 40, 25, 17, 8, 5], [42, 28, 20, 9, 6, 0]]
impossible
impossible
impossible
impossible
impossible
[[95, 92, 86, 75, 62, 50], [93, 87, 76, 64, 53, 40], [91, 82, 71, 55, 41, 22], [82, 72, 55, 42, 26, 16], [73, 56, 43, 36, 17, 14], [60, 48, 38, 20, 14, 3]]
[[97, 91, 84, 71, 64, 42], [91, 88, 71, 67, 44, 37], [90, 73, 68, 53, 39, 18], [80, 69, 53, 39, 19, 10], [70, 55, 41, 23, 13, 8], [60, 41, 29, 15, 10, 5]]
impossible
[[96, 92, 83, 76, 54, 30], [95, 88, 77, 55, 34, 22], [91, 78, 61, 36, 22, 15], [82, 70, 38, 24, 18, 10], [72, 41, 25, 20, 12, 2], [43, 27, 22, 14, 9, 0]]
[[98, 90, 84, 75, 58, 39], [93, 84, 76, 63, 42, 26], [88, 81, 68, 44, 26, 9], [83, 72, 50, 30, 20, 3], [72, 55, 36, 24, 6, 1], [57, 36, 24, 6, 1, 0]]
[[86, 81, 65, 53, 40, 36], [85, 74, 58, 41, 37, 27], [74, 61, 41, 38, 31, 20], [63, 42, 39, 32, 22, 9], [53, 39, 34, 23, 18, 6], [40, 36, 25, 19, 8, 0]]
[[87, 82, 77, 74, 59, 49], [84, 79, 74, 62, 49, 34], [82, 75, 62, 53, 34, 21], [75, 68, 53, 34, 24, 9], [70, 54, 35, 29, 10, 4], [58, 46, 33, 10, 8, 1]]
[[98, 92, 83, 72, 66, 43], [95, 86, 75, 66, 45, 36], [89, 80, 68, 49, 38, 13], [80, 69, 52, 39, 22, 12], [70, 53, 40, 28, 12, 5], [53, 41, 33, 13, 7, 3]]
impossible
impossible
[[99, 82, 74, 64, 58, 32], [82, 79, 65, 59, 36, 26], [80, 72, 59, 36, 26, 18], [73, 59, 40, 27, 19, 11], [62, 49, 30, 21, 16, 2], [55, 31, 23, 16, 8, 1]]
[[98, 93, 86, 84, 66, 45], [95, 90, 84, 67, 49, 21], [91, 85, 75, 57, 24, 15], [85, 80, 59, 26, 17, 10], [81, 65, 27, 20, 13, 4], [65, 42, 20, 13, 9, 0]]
[[99, 92, 81, 69, 59, 53], [98, 90, 70, 62, 55, 32], [91, 74, 62, 55, 42, 17], [77, 65, 56, 46, 21, 11], [66, 57, 46, 25, 15, 9], [58, 50, 29, 16, 10, 0]]
impossible
impossible
[[99, 89, 83, 78, 62, 45], [95, 85, 78, 63, 47, 31], [88, 79, 65, 51, 31, 24], [80, 71, 56, 31, 25, 20], [74, 57, 39, 26, 21, 9], [58, 42, 29, 21, 13, 5]]
impossible
[[99, 80, 72, 65, 54, 36], [88, 74, 65, 60, 38, 27], [79, 70, 63, 39, 29, 17], [71, 63, 42, 30, 21, 10], [64, 42, 32, 24, 16, 7], [46, 35, 25, 16, 7, 2]]
[[95, 80, 64, 44, 35, 28], [93, 66, 49, 36, 31, 21], [75, 58, 37, 32, 22, 13], [59, 37, 33, 23, 15, 6], [44, 33, 23, 18, 10, 3], [34, 25, 20, 11, 4, 0]]
impossible
[[92, 85, 79, 62, 59, 36], [86, 80, 67, 59, 43, 24], [85, 68, 60, 43, 25, 18], [69, 61, 47, 26, 20, 9], [62, 53, 30, 21, 9, 4], [56, 33, 22, 14, 5, 1]]
[[95, 93, 87, 82, 69, 57], [94, 90, 86, 77, 60, 29], [91, 86, 78, 64, 36, 23], [87, 80, 64, 37, 25, 18], [80, 69, 46, 27, 19, 17], [69, 52, 27, 23, 17, 8]]
impossible
[[98, 88, 82, 75, 61, 51], [89, 83, 81, 69, 54, 35], [83, 82, 72, 59, 35, 23], [82, 72, 60, 37, 27, 17], [72, 60, 41, 33, 20, 4], [61, 46, 33, 21, 6, 1]]
[[97, 93, 81, 75, 63, 45], [95, 83, 78, 66, 47, 22], [84, 81, 71, 49, 36, 10], [81, 72, 56, 37, 13, 7], [75, 58, 39, 16, 8, 3], [58, 41, 20, 9, 5, 2]]
[[98, 92, 85, 75, 67, 44], [94, 85, 79, 69, 53, 31], [92, 82, 70, 54, 31, 12], [83, 74, 57, 33, 25, 8], [75, 61, 33, 28, 10, 5], [62, 38, 28, 10, 8, 2]]
impossible
impossible
impossible

total count of cases for which the sorting was impossible: 45
79819685
Vote

My code will accept input from the file "RandomNumbers.txt" in the "input" folder.This will first sort the elements in the descending order, then fill to the 6*6 matrix based on the criteria.This will also check for the duplication of element with previous row value and previous value if duplication found try to swap the elements and ensure this satisfies the criteria.If placing in matrix is not possible print that else print the matrix.Finally print the total count of impossible cases**
total count of cases for which the sorting was impossible : 87
Mycode**

/**
 *
 * 
 */
package integersort;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * This is for sorting integer in 6*6 matrix.Each cell will have one number. place all the integers into the grid such
 * that
 * 
 * Each row is descendingly sorted (ties are not allowed). For example: 6 5 4 3 2 1 is valid but 6 5 5 5 3 2 is not
 * valid.Each column is descendingly sorted (ties are not allowed)or declare this impossible.Example on a 3x3 grid:
 * Given these numbers to sort [95, 75, 75, 74, 74, 74, 54, 45, 40]A valid response would be [[95, 75, 74], [75, 74,
 * 54], [74, 45, 40]]
 * 
 * @author mariya.cherian
 * @version 1.0
 * @since Nov 11, 2025
 */
public class IntegerSortInMatrix
{
    /**
     * This will be the starting point of execution First this will read input from the file 'RandomNumbers.txt' at
     * input folder ,In the attached file, we have 100 sets of 36 random integers. The integers are between 0 and 99.
     * Then for each input line call the method {@link sortMatrix} to sort the values
     * 
     * @param args
     */
    public static void main(String[] args)
    {
        int total = 0;
        try
        {
            Path path = Paths.get("input", "RandomNumbers.txt");
            System.out.println("Looking for file at: " + path.toAbsolutePath());
            if (!Files.exists(path))
            {
                System.err.println("File does not exist. Please check path and file name!");
                return;
            }
            List<List<Integer>> allLists = readIntegerLists(path);
            for (List<Integer> t : allLists)
            {
                total = sortMatrix(t, total);
            }
            System.out.println("----------------------------------------------------------------------");
            System.out.println(" total count of cases for which the sorting was impossible : " + total);
            System.out.println("----------------------------------------------------------------------");

        }
        catch (IOException e)
        {
            System.out.println("failed to read file ");
            e.printStackTrace();
        }
    }

    /**
     * This will read input file from the specified path then read each line and remove the enclosing brackets if
     * present and save the integer list in {<code></code>
     * 
     * @param path the path where the input file exists
     * @return the list contains the list of integer input
     * @throws IOException
     */
    private static List<List<Integer>> readIntegerLists(Path path) throws IOException
    {
        List<String> lines = Files.readAllLines(path);
        List<List<Integer>> result = new ArrayList<>();
        for (String line : lines)
        {
            line = line.trim();
            if (line.isEmpty())
                continue;
            if (line.startsWith("[") && line.endsWith("]"))
            {
                line = line.substring(1, line.length() - 1);
            }
            String[] parts = line.split("\\s*,\\s*");
            List<Integer> list = new ArrayList<>();
            for (String part : parts)
            {
                list.add(Integer.parseInt(part));
            }
            result.add(list);
        }
        return result;
    }

    /**
     * This is to sort the 6*6 matrix of integers in descending order.if sorting is not possible display that else
     * display the matrix
     * 
     * @param input the list of integers that have to be sorted and placed in grid
     * @param total the count of impossible matrix
     * @return the total the count of impossible matrix
     */
    private static int sortMatrix(List<Integer> input, int total)
    {
        System.out.println("input numbers:>> " + input);
        List<Integer> sorted = new ArrayList<>(input);
        sorted.sort(Collections.reverseOrder());
        System.out.println("Sorted numbers:>> " + sorted);
        sorted = sorted.subList(0, 36);
        int n = 6;
        int[][] matrix = new int[n][n];
        for (int i = 0; i < n; i++)
        {
            Arrays.fill(matrix[i], -1);
        }
        boolean success = fillMatrix(sorted, matrix, 0, n);
        if (success)
        {
            total = total + 1;
            System.out.println(" this is impossible!!!!!!!!!!!. ");
        }
        else
        {
            displayMatrix(matrix, n);
        }
        return total;
    }

    /**
     * This is to fill the matrix from the sorted integers here the j indicate the column index and i indicate the row
     * index.then from the sorted list of integers,first evaluate for the postion 00, then to check the row wise
     * conflict skip the first element in row (j != 0 ) then check the item is same as the previous item in matrix, if
     * match found then need to swap the item in the matrix that means place the item in the first col of next row for
     * that this will check if it is in the last row inorder to avoid the {@link ArrayIndexOutOfBoundsException}.In the
     * swapping case if the first index of the next row having a value then continue for the next iteration
     * 
     * @param list the list of items to be placed in the matrix
     * @param matrix the matrix to be sorted
     * @param index the
     * @param n the matrix index
     * @return the flag that indicate the tie exist or not
     */
    private static boolean fillMatrix(List<Integer> list, int[][] matrix, int index, int n)
    {
        boolean rowflag = false;
        int k = 0;
        outer: for (int i = 0; i < n; i++)
        {
            inner: for (int j = 0; j < n; j++)
            {
                if (i == 0 && j == 0)
                {
                    matrix[i][j] = list.get(k);
                    k++;
                }
                else if (matrix[i][j] != -1)
                {
                    continue;
                }
                else if (j != 0 && list.get(k) == matrix[i][j - 1])
                {
                    if (i == 5)
                    {
                        rowflag = true;
                        break outer;
                    }
                    int row = i + 1, col = j;
                    swapcol: for (int indexs = 0; indexs < col; indexs++)
                    {
                        rowflag = true;
                        if ((matrix[row][indexs] == -1) && indexs != 0 && matrix[row][indexs - 1] == list.get(k))

                        {
                            continue;
                        }
                        else if ((matrix[row][indexs] == -1) && matrix[row - 1][indexs] != list.get(k)
                                && matrix[row - 1][indexs] > list.get(k))
                        {
                            matrix[row][indexs] = list.get(k);
                            k++;
                            j--;
                            rowflag = false;
                            break swapcol;
                        }
                        else if ((matrix[row][indexs] != -1) && matrix[row][indexs] != list.get(k)
                                && matrix[row][indexs] > list.get(k))
                        {
                            continue;
                        }
                        else
                        {
                            rowflag = true;
                            break outer;

                        }

                    }
                }
                else if (j != 0 && list.get(k) != matrix[i][j - 1])
                {
                    matrix[i][j] = list.get(k);
                    k++;
                }
                else
                {
                    matrix[i][j] = list.get(k);
                    k++;
                }
            }
        }
        return rowflag;
    }

    /**
     * This is to display this 6*6 matrix with valid sorted items
     * 
     * @param matrix the {@link IntegerSortInMatrix} to be displayed
     * @param n the count of index in matrix
     */
    private static void displayMatrix(int[][] matrix, int n)
    {
        System.out.println("6×6 Matrix:");
        Matrix: for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (matrix[i][j] == -1)
                {
                    System.out.println();
                    break Matrix;
                }
                System.out.print(matrix[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

My output

total count of cases for which the sorting was impossible : 87

**Solution URL: **
https://github.com/mariyacherian/Stack-Overflow-Challenge---Challenge-13-Integer-sorting-in-a-grid/tree/main

What I learned

  • While doing this I want to iterate over 2 loops and in some scenario i want to exit from both of this loop i used break for that but it fails.Using break we can exit from the inner loop but outer loop continues. Then I got solution to this by Labeled Break.A labeled break will terminate the outer loop instead of just the inner loop

  • The dafault value of int array is 0 i have tried with this but when 0 comes in the input i have to handle this so i have set -1 in the matrix as default value.
    Useful resources https://www.baeldung.com/java-breaking-out-nested-loop

My sample output (full code can't be placed due to Reply cannot be longer than 30000.)
Looking for file at: /home/[email protected]/Downloads/sample/GridSort/input/RandomNumbers.txt

1- Impossible.
2- Impossible.

3- 6×6 Matrix: 

99  94  88  86  83  81
74  73  71  70  63  62
61  59  57  56  52  50
48  40  36  35  29  27
40  27  24  20  19  13
10  9   8   6   3   1

4- Impossible.
5- Impossible.
6- Impossible.
7- Impossible.
8- Impossible.

9- 6×6 Matrix: 

99  97  88  86  82  81
88  81  79  71  68  66
79  64  63  58  56  54
64  63  52  51  50  48
42  41  38  35  15  11
11  9   5   3   2   0

10- Impossible.
11- Impossible.
12- Impossible.

13- 6×6 Matrix: 

98  96  93  91  90  82
82  74  73  70  68  66
66  65  58  56  55  54
49  41  38  32  31  28
21  19  16  14  12  10
19  16  12  10  4   3

14- Impossible.
15- Impossible.
16- Impossible.
17- Impossible.
18- Impossible.
19- Impossible.
20- Impossible.
21- Impossible.
22- Impossible.
23- Impossible.
24- Impossible.
25- Impossible.

26- 6×6 Matrix: 

97  95  91  86  85  81
91  80  79  76  75  74
79  68  66  62  61  58
68  66  62  57  46  45
38  33  31  28  27  20
31  17  14  13  7   1

27- Impossible.

28- 6×6 Matrix: 

92  91  88  87  85  84
88  85  83  80  77  73
73  71  70  68  65  52
42  37  35  32  29  27
32  26  22  20  17  14
12  11  10  9   7   3

29- 6×6 Matrix: 

98  97  96  89  87  84
81  80  73  64  63  62
80  63  59  55  50  49
59  48  45  40  36  34
31  29  28  27  24  19
14  12  11  7   2   1

30- Impossible.
31- Impossible.
32- Impossible.
33- Impossible.
34- Impossible.
35- Impossible.

36- 6×6 Matrix: 

99  94  93  92  89  84
81  79  69  67  65  60
67  59  58  56  54  53
53  50  48  44  43  32
31  30  26  23  19  15
10  9   8   6   5   2

37- Impossible.
38- Impossible.

39- 6×6 Matrix: 
 
99  97  93  90  89  88
86  83  78  74  71  67
74  66  62  59  51  48
66  41  39  35  33  31
28  26  25  22  19  18
19  15  13  11  10  4

40 Impossible.
41 Impossible.
 
42- 6×6 Matrix: 
 
95  93  92  84  81  76
72  71  68  66  65  61
60  59  57  54  51  47
45  41  38  37  35  34
37  34  33  32  24  20
18  17  16  15  14  6
 
43- Impossible.
44- Impossible.
45- Impossible.
46- Impossible.
47- Impossible.
48- Impossible.
49- Impossible.
50- Impossible.
51- Impossible.
52- Impossible.
53- Impossible.
54- Impossible.
55- Impossible.
56- Impossible.
57- Impossible.
58- Impossible.
59- Impossible.
60- Impossible.
61- Impossible.

62- 6×6 Matrix: 
 
99  96  95  93  92  90
89  87  82  81  80  78
78  77  74  71  70  60
55  49  44  39  38  37
36  26  25  23  21  19
18  13  11  10  3   1

63- 6×6 Matrix: 

97  93  89  87  83  82
87  82  81  76  75  73
71  70  69  68  67  63
70  68  63  53  51  49
45  40  38  37  32  21
18  14  13  11  10  7

64- Impossible.
65- Impossible.
66- Impossible.
67- Impossible.
68- Impossible.
69- Impossible.
70- Impossible.
71- Impossible.
72- Impossible.
73- Impossible.
74- Impossible.
75- Impossible.

76- 6×6 Matrix: 

86  85  81  74  65  63
74  61  58  53  42  41
53  41  40  39  38  37
40  39  36  34  32  31
36  27  25  23  22  20
19  18  9   8   6   0

...
79819265
Vote

My approach is like this basically:

  1. Sort each array
  2. Place the elements of the sorted array to 6x6 matrices from top-left to bottom-right in a zigzag pattern. (see image below)
  3. Check if there are any ties (consecutive elements) in the rows or columns.

Here is the pattern

Here is the code

Reading and parsing the file

final String path = "path\\RandomNumbers.txt";
final int[][] data = new int[100][36];
final int[][][] answer = new int[100][6][6];

try (Stream<String> s = Files.lines(Paths.get(path))) {
    final int[] index = {0};
    s.forEach(line -> {
        int[] arr = Arrays.stream(line.substring(1, line.length() - 1)
                        .split(", "))
                            .mapToInt(Integer::parseInt)
                            .toArray();
        System.arraycopy(arr, 0, data[index[0]++], 0, arr.length);
    });
} catch (IOException e) {
    System.out.println("Couldn't read file, exiting program.");
    System.exit(1);
}

The ZigZag pattern array copy method

/**
 * Fills a square matrix with elements from a one-dimensional array
 * in a diagonal "snake" (zigzag) pattern starting from the 
 * bottom-right corner.
 *
 * @param matrix the target 2D square matrix to fill
 * @param arr    the source 1D array containing elements to copy into 
 * the matrix
 */
public static void strangeArrayCopy(int[][] matrix, int[] arr) {
    int n = matrix.length;
    int col = n - 1;
    int row = n - 1;
    int x = n - 1;
    int y = n - 1;
    int idx = 0;

    while (x >= 0 && y >= 0) {
        matrix[y][x] = arr[idx++];

        if (col > 0) {
            if (x == n - 1) {
                col--;
                x = col;
                y = n - 1;
                continue;
            }
        } else {
            if (y == 0) {
                row--;
                y = row;
                x = 0;
                continue;
            }
        }
        x++;
        y--;
    }
}

This method starts from bottom-right instead of top-left as it states in my previous statement. This is because Java Arrays.sort() method only sorts in ascending order by default. So starting from max element and going top-left to bottom-right is the same as starting from the min element and going bottom-right to top-left.

Checking for consecutive elements (ties)

/**
 * Checks whether the given 2D integer matrix contains any consecutive
 * identical elements either horizontally (side by side) or vertically 
 * (one above the other).
 *
 * @param data the 2D integer array (matrix) to check for consecutive 
 * equal elements
 * @return {@code true} if the matrix contains adjacent equal elements
 * horizontally or vertically; {@code false} otherwise
 */
public static boolean hasTies(int[][] data) {
    for (int i = 0; i < data.length; i++) {
        for (int j = 0; j < data[i].length; j++) {
            int current = data[i][j];

            // Check right neighbor (same row)
            if (j < data[i].length - 1 && current == data[i][j + 1]) {
                return true;
            }

            // Check below neighbor (same column)
            if (i < data.length - 1 && current == data[i + 1][j]) {
                return true;
            }
        }
    }

    return false;
}

Algorithm

for (int i = 0; i < data.length; i++) {
    Arrays.sort(data[i]);
    strangeArrayCopy(answer[i], data[i]);
}

// Checking impossible ones
int count = 0;
for (int[][] ints : answer) {
    if (hasTies(ints)) count++;
}

System.out.println("There are " + count + " impossible arrays.");

So the program first reads and parses the file into a 2d array data. Then sorts all the arrays. Then using strangeArrayCopy() method copies the arrays to matrices of answer 3D matrix. Then iterates every one of them and checks if there are impossible (contains ties) ones and reports them.

Couple impossible matrices for example:

95 95 92 84 76 71 
94 88 83 76 68 61 
88 82 75 65 61 52 
76 73 64 60 49 18 
71 63 56 39 15 11 
61 54 27 14 5  0 

99 98 96 82 71 58 
97 95 81 68 55 45 
92 75 63 54 41 24 
73 62 50 41 23 11 
59 49 41 16 9  2  
45 33 14 3  1  1 

88 80 78 73 61 45 
79 76 70 60 41 31 
74 69 54 40 30 22 
66 52 34 28 22 13 
51 34 26 19 9  2  
33 24 14 6  2  2 

Output

There are 45 impossible arrays.
79820264
Vote

The snake pattern might be cute but it fails to achieve a rule-conforming assignment for several valid cases (i.e. whenever a run of equal values touches straddles diagonals).

However, strangeArrayCopy() does not use the snake pattern (any more?); it always zigs in the bottom-left to top-right direction and never zags, even though it seems to try very hard to disguise what it does.

Ergo there is no correctness problem in the code, only in the stale commentary and the write-up. ;-)

Here's a different take on the copy logic that performs exactly the same assignments. It is more pedestrian but I think it expresses more clearly what happens and I find it easier to understand/verify.

final int N = 6;
int source_index = N * N;  // copying backwards in order to get descending (non-increasing) values

// diagonals that start in the top row (going down and left)
for (int x0 = 0; x0 < N; ++i)
    for (int x = x0, y = 0; x >= 0; --x, ++y)
        matrix[y][x] = arr[--source_index];

// the remaining diagonals all start in the final column
for (int y0 = 1; y0 < N; ++i)
    for (int x = N - 1, y = y0; y < N; --x, ++y)
        matrix[y][x] = arr[--source_index];
79818979
Vote
  • I'll post my first attempt and possibly iterate, especially the hard-coded diagonalisation, that should be in a tight loop!

  • I'm not sure if folk are including the data in their answers? (Is it like advent of code, where the data may be different for different participants?)

  • I get the answer that 45 of the 100 cases are not possible to sort following the rules given

# fmt: off
# flake8: noqa: E501
# pylint: disable=line-too-long, bad-indentation, invalid-name

sets_of_random = [[54, 95, 98, 26, 3, 39, 77, 30, 83, 62, 20, 92, 61, 59, 26, 63, 92, 49, 38, 51, 99, 64, 65, 52, 98, 18, 90, 97, 96, 13, 74, 3, 88, 88, 67, 10],
[49, 13, 73, 54, 4, 98, 36, 33, 12, 22, 35, 18, 39, 83, 92, 77, 50, 77, 57, 64, 0, 35, 86, 98, 28, 1, 53, 59, 28, 33, 56, 37, 98, 26, 81, 13],
[95, 84, 44, 16, 42, 73, 0, 53, 14, 63, 81, 91, 42, 14, 13, 59, 91, 24, 99, 71, 73, 34, 60, 65, 82, 55, 16, 75, 7, 18, 68, 6, 61, 6, 80, 41],
[27, 63, 35, 81, 56, 24, 70, 27, 59, 13, 36, 62, 73, 6, 61, 86, 48, 40, 88, 71, 52, 1, 9, 57, 50, 40, 20, 10, 3, 29, 19, 94, 99, 8, 74, 83],
[46, 75, 78, 14, 89, 76, 37, 26, 85, 78, 81, 27, 99, 41, 96, 52, 21, 65, 71, 48, 60, 32, 48, 31, 85, 35, 88, 5, 78, 22, 31, 97, 43, 80, 52, 45],
[0, 98, 50, 12, 0, 83, 46, 66, 67, 23, 52, 55, 41, 95, 5, 17, 78, 98, 74, 45, 97, 98, 96, 54, 48, 79, 29, 0, 73, 6, 16, 33, 20, 88, 9, 23],
[9, 2, 10, 57, 79, 65, 65, 0, 19, 64, 3, 18, 20, 93, 10, 30, 9, 0, 40, 51, 87, 34, 52, 71, 28, 23, 73, 61, 77, 60, 66, 91, 57, 58, 2, 9],
[27, 63, 51, 6, 3, 10, 7, 36, 80, 51, 93, 71, 73, 25, 3, 77, 35, 56, 36, 36, 77, 97, 14, 1, 78, 83, 5, 51, 99, 5, 93, 90, 1, 36, 83, 4],
[89, 94, 67, 64, 31, 66, 59, 16, 80, 22, 78, 72, 56, 83, 98, 10, 9, 57, 23, 4, 80, 37, 65, 30, 71, 55, 42, 9, 60, 18, 39, 58, 44, 79, 48, 29],
[79, 51, 3, 82, 81, 58, 99, 88, 54, 88, 81, 5, 63, 79, 52, 64, 48, 64, 68, 11, 50, 66, 35, 71, 9, 86, 11, 97, 42, 41, 0, 2, 56, 38, 15, 63],
[94, 35, 12, 94, 79, 40, 91, 45, 37, 98, 43, 30, 80, 81, 87, 19, 74, 87, 93, 35, 88, 89, 79, 44, 6, 87, 27, 49, 98, 44, 68, 39, 42, 87, 61, 84],
[5, 37, 89, 80, 31, 40, 1, 10, 54, 67, 23, 1, 75, 43, 49, 27, 29, 69, 43, 41, 7, 16, 63, 70, 5, 61, 74, 87, 2, 61, 50, 72, 91, 56, 12, 99],
[43, 35, 83, 94, 69, 45, 76, 73, 83, 60, 80, 31, 59, 34, 39, 63, 35, 13, 94, 78, 2, 24, 87, 21, 36, 38, 55, 19, 10, 82, 13, 95, 88, 54, 94, 75],
[66, 10, 58, 21, 82, 10, 32, 91, 66, 65, 3, 12, 4, 38, 12, 96, 55, 54, 73, 16, 74, 41, 28, 49, 19, 98, 16, 90, 93, 82, 56, 68, 14, 70, 31, 19],
[13, 79, 47, 31, 79, 31, 56, 65, 94, 73, 57, 35, 74, 85, 84, 39, 24, 26, 12, 56, 46, 46, 71, 0, 57, 61, 77, 32, 14, 1, 81, 71, 69, 66, 57, 69],
[8, 39, 23, 14, 88, 44, 81, 46, 5, 26, 50, 11, 71, 19, 86, 33, 88, 62, 81, 13, 60, 96, 7, 78, 6, 88, 77, 94, 74, 63, 48, 40, 29, 47, 64, 6],
[95, 36, 61, 3, 75, 84, 95, 8, 57, 42, 43, 77, 27, 65, 56, 78, 34, 96, 18, 23, 46, 17, 86, 17, 89, 28, 96, 18, 24, 90, 93, 49, 47, 69, 91, 48],
[76, 95, 10, 10, 58, 67, 25, 41, 0, 49, 13, 40, 59, 29, 62, 64, 97, 47, 22, 42, 39, 44, 16, 95, 23, 91, 14, 48, 90, 39, 16, 92, 46, 38, 49, 16],
[60, 42, 28, 28, 61, 10, 37, 90, 99, 9, 45, 15, 61, 20, 6, 89, 99, 5, 34, 28, 58, 45, 10, 43, 73, 5, 45, 78, 68, 48, 44, 56, 78, 69, 52, 99],
[99, 92, 63, 87, 23, 73, 25, 25, 31, 97, 14, 12, 77, 96, 73, 80, 86, 15, 63, 71, 44, 34, 51, 28, 77, 24, 19, 74, 87, 34, 59, 40, 82, 13, 25, 15],
[48, 59, 63, 45, 51, 64, 88, 99, 81, 29, 69, 27, 7, 28, 9, 77, 50, 80, 7, 64, 3, 24, 6, 22, 31, 69, 92, 66, 13, 3, 70, 81, 73, 50, 45, 42],
[0, 49, 29, 50, 38, 38, 24, 71, 8, 5, 56, 6, 90, 2, 3, 35, 40, 89, 24, 27, 74, 77, 54, 7, 1, 76, 92, 16, 55, 23, 47, 62, 33, 1, 80, 47],
[1, 61, 12, 89, 56, 47, 88, 63, 73, 49, 9, 78, 68, 69, 19, 53, 76, 39, 49, 83, 38, 70, 62, 79, 19, 7, 70, 4, 90, 57, 90, 20, 52, 37, 64, 17],
[0, 99, 18, 20, 0, 5, 93, 66, 87, 4, 62, 47, 94, 27, 73, 82, 12, 37, 39, 63, 59, 71, 71, 36, 84, 53, 90, 93, 9, 21, 94, 76, 80, 4, 40, 30],
[57, 17, 99, 26, 7, 0, 81, 29, 95, 51, 46, 8, 16, 19, 15, 48, 89, 65, 69, 14, 94, 9, 3, 78, 59, 20, 41, 45, 97, 99, 57, 52, 94, 12, 55, 28],
[19, 49, 58, 20, 73, 65, 0, 72, 82, 12, 64, 43, 34, 58, 11, 74, 20, 75, 0, 23, 6, 25, 81, 39, 44, 65, 54, 57, 72, 72, 10, 69, 31, 10, 45, 20],
[68, 46, 13, 68, 81, 62, 28, 75, 66, 91, 27, 31, 20, 38, 1, 45, 76, 79, 14, 62, 58, 66, 17, 79, 61, 91, 86, 33, 57, 95, 74, 7, 31, 85, 97, 80],
[67, 31, 55, 44, 11, 39, 50, 79, 64, 75, 97, 13, 22, 19, 42, 58, 55, 10, 51, 37, 73, 55, 22, 40, 35, 97, 77, 92, 43, 24, 69, 25, 64, 61, 48, 77],
[7, 17, 84, 29, 87, 12, 85, 22, 65, 70, 73, 14, 32, 9, 27, 3, 11, 42, 88, 20, 37, 10, 88, 77, 68, 92, 71, 80, 83, 32, 35, 85, 91, 52, 26, 73],
[62, 24, 97, 27, 49, 2, 50, 36, 14, 59, 63, 1, 45, 98, 80, 64, 59, 80, 55, 96, 87, 89, 19, 81, 40, 31, 73, 48, 29, 34, 63, 11, 12, 7, 84, 28],
[23, 82, 3, 66, 59, 65, 49, 80, 16, 73, 39, 69, 45, 15, 6, 14, 4, 97, 76, 57, 34, 13, 77, 72, 98, 24, 34, 54, 23, 41, 67, 6, 80, 19, 30, 92],
[20, 35, 58, 63, 21, 75, 58, 8, 30, 44, 97, 21, 3, 86, 78, 89, 93, 42, 29, 89, 53, 17, 89, 6, 8, 14, 48, 98, 15, 58, 28, 46, 51, 55, 17, 78],
[42, 41, 8, 12, 37, 81, 33, 58, 59, 31, 3, 67, 77, 90, 6, 2, 14, 45, 49, 28, 79, 93, 7, 75, 52, 52, 46, 86, 98, 77, 66, 38, 41, 11, 41, 2],
[8, 45, 28, 85, 58, 99, 18, 86, 95, 16, 59, 45, 26, 35, 36, 96, 61, 82, 32, 20, 62, 47, 93, 3, 44, 71, 11, 11, 31, 28, 42, 7, 18, 58, 40, 89],
[87, 4, 99, 46, 73, 27, 7, 44, 26, 62, 15, 10, 14, 77, 97, 70, 58, 23, 85, 73, 76, 97, 6, 92, 52, 51, 9, 84, 29, 56, 15, 38, 41, 7, 88, 76],
[30, 0, 80, 70, 10, 78, 91, 80, 3, 42, 24, 70, 39, 7, 7, 43, 9, 2, 23, 96, 76, 87, 19, 11, 5, 10, 74, 10, 49, 16, 34, 54, 40, 55, 75, 93],
[92, 54, 58, 53, 99, 84, 53, 50, 56, 65, 10, 89, 19, 2, 6, 94, 44, 69, 67, 60, 79, 5, 30, 23, 15, 8, 48, 26, 32, 31, 43, 59, 81, 9, 67, 93],
[7, 58, 97, 4, 22, 36, 5, 83, 32, 69, 83, 54, 18, 48, 49, 43, 36, 37, 96, 0, 28, 18, 64, 56, 52, 97, 43, 95, 36, 8, 48, 35, 60, 41, 48, 81],
[50, 78, 66, 51, 45, 80, 65, 87, 0, 5, 87, 91, 34, 78, 47, 89, 51, 32, 88, 64, 52, 8, 86, 59, 11, 5, 1, 12, 57, 87, 75, 83, 17, 69, 96, 61],
[74, 18, 35, 33, 97, 4, 22, 39, 41, 10, 66, 59, 11, 71, 90, 28, 78, 66, 51, 25, 48, 89, 74, 62, 13, 19, 67, 99, 19, 88, 15, 83, 26, 86, 31, 93],
[93, 32, 27, 13, 61, 53, 49, 35, 59, 13, 54, 68, 75, 31, 18, 79, 33, 59, 87, 86, 14, 26, 21, 19, 12, 59, 75, 36, 7, 71, 25, 25, 6, 85, 29, 99],
[94, 78, 11, 70, 49, 22, 25, 67, 34, 65, 85, 58, 76, 10, 44, 22, 75, 72, 65, 54, 68, 60, 84, 52, 19, 26, 61, 69, 88, 76, 37, 41, 81, 1, 23, 57],
[15, 72, 24, 37, 95, 16, 76, 61, 34, 47, 68, 93, 18, 92, 32, 17, 20, 66, 51, 33, 65, 38, 71, 45, 81, 59, 34, 35, 84, 37, 14, 6, 41, 60, 57, 54],
[83, 86, 73, 77, 75, 67, 5, 92, 43, 13, 98, 92, 69, 80, 50, 25, 64, 0, 64, 25, 98, 40, 66, 77, 4, 18, 52, 50, 28, 36, 17, 54, 5, 83, 2, 40],
[25, 68, 57, 61, 55, 81, 56, 71, 95, 72, 37, 21, 91, 8, 23, 26, 38, 44, 45, 84, 37, 51, 13, 42, 90, 12, 67, 21, 96, 31, 99, 97, 2, 90, 99, 56],
[47, 90, 19, 59, 82, 32, 52, 99, 74, 8, 93, 18, 79, 22, 24, 63, 84, 50, 55, 86, 94, 23, 83, 65, 67, 48, 16, 15, 81, 78, 7, 43, 12, 52, 58, 28],
[54, 39, 86, 53, 24, 55, 72, 2, 6, 15, 78, 8, 35, 70, 59, 80, 74, 99, 95, 32, 44, 26, 47, 49, 48, 14, 95, 66, 54, 76, 37, 81, 85, 37, 45, 7],
[19, 38, 6, 31, 71, 53, 40, 85, 71, 52, 56, 25, 78, 32, 17, 85, 42, 24, 61, 42, 3, 54, 98, 68, 48, 39, 59, 59, 12, 25, 96, 98, 15, 88, 44, 45],
[62, 70, 19, 57, 56, 68, 7, 13, 53, 87, 68, 69, 77, 39, 23, 94, 42, 10, 1, 28, 43, 31, 42, 48, 75, 95, 28, 10, 44, 50, 72, 47, 64, 96, 5, 63],
[92, 85, 77, 92, 90, 27, 39, 57, 51, 41, 99, 78, 78, 53, 88, 59, 30, 65, 15, 25, 32, 32, 99, 64, 90, 40, 13, 45, 41, 73, 98, 12, 44, 73, 33, 32],
[97, 36, 97, 58, 74, 56, 70, 80, 92, 84, 93, 16, 0, 34, 96, 85, 84, 16, 29, 22, 27, 42, 26, 40, 27, 80, 1, 40, 82, 25, 54, 31, 77, 25, 67, 73],
[46, 91, 13, 50, 65, 68, 44, 15, 65, 58, 77, 21, 92, 70, 69, 95, 9, 84, 69, 71, 53, 65, 0, 33, 95, 4, 1, 28, 62, 27, 39, 38, 47, 39, 61, 81],
[37, 0, 70, 66, 14, 20, 50, 68, 8, 0, 62, 41, 68, 35, 14, 69, 94, 62, 53, 84, 32, 22, 80, 81, 22, 66, 36, 65, 40, 53, 93, 0, 0, 33, 32, 7],
[68, 73, 37, 13, 86, 20, 22, 97, 27, 10, 32, 57, 27, 11, 52, 7, 7, 48, 23, 14, 98, 25, 41, 6, 78, 63, 80, 38, 24, 75, 2, 61, 45, 93, 18, 94],
[20, 14, 76, 73, 80, 30, 56, 33, 80, 18, 79, 66, 39, 3, 88, 25, 28, 24, 63, 88, 68, 28, 67, 49, 6, 18, 4, 49, 0, 96, 11, 22, 6, 41, 17, 50],
[9, 61, 45, 7, 25, 86, 99, 39, 79, 13, 46, 74, 44, 3, 90, 43, 25, 9, 2, 27, 13, 15, 38, 98, 2, 88, 13, 51, 44, 80, 67, 85, 84, 40, 2, 68],
[22, 48, 11, 46, 99, 88, 75, 32, 69, 66, 73, 10, 3, 31, 13, 44, 11, 17, 68, 0, 37, 86, 40, 92, 13, 61, 24, 69, 22, 11, 53, 1, 14, 53, 96, 29],
[65, 27, 91, 56, 76, 11, 86, 34, 3, 15, 97, 42, 19, 98, 38, 78, 90, 37, 76, 55, 46, 18, 72, 92, 3, 38, 55, 54, 5, 0, 58, 24, 77, 70, 65, 55],
[33, 48, 21, 34, 42, 60, 82, 33, 98, 27, 51, 33, 74, 55, 59, 96, 44, 35, 23, 28, 13, 52, 72, 9, 39, 52, 8, 30, 40, 8, 97, 43, 79, 89, 38, 80],
[1, 29, 67, 37, 13, 29, 33, 96, 91, 24, 4, 67, 20, 71, 75, 95, 2, 63, 39, 14, 88, 2, 5, 17, 38, 40, 74, 79, 39, 62, 38, 58, 74, 4, 27, 97],
[86, 8, 5, 54, 58, 78, 70, 51, 89, 94, 51, 55, 27, 6, 56, 44, 14, 72, 5, 27, 19, 50, 72, 58, 66, 24, 49, 28, 15, 12, 12, 37, 85, 89, 53, 38],
[54, 1, 82, 23, 72, 55, 6, 96, 54, 22, 19, 63, 83, 50, 39, 75, 33, 29, 83, 14, 60, 92, 62, 83, 11, 34, 53, 77, 57, 63, 18, 17, 50, 9, 90, 36],
[60, 78, 25, 81, 18, 1, 96, 39, 36, 82, 23, 78, 70, 80, 19, 55, 74, 38, 99, 37, 3, 87, 21, 26, 93, 89, 44, 13, 95, 92, 11, 71, 77, 10, 49, 90],
[68, 68, 45, 82, 67, 7, 97, 49, 87, 83, 73, 70, 70, 87, 14, 37, 10, 21, 82, 71, 75, 13, 89, 93, 63, 11, 40, 18, 32, 69, 38, 53, 81, 63, 51, 76],
[25, 36, 27, 62, 4, 51, 50, 74, 19, 10, 78, 94, 15, 49, 11, 26, 91, 80, 61, 80, 84, 87, 80, 52, 35, 28, 64, 91, 39, 58, 15, 55, 26, 72, 68, 35],
[42, 66, 36, 17, 5, 31, 38, 90, 61, 8, 24, 0, 7, 40, 65, 67, 54, 61, 53, 16, 49, 76, 21, 63, 23, 72, 20, 9, 42, 34, 10, 6, 63, 25, 61, 28],
[9, 98, 52, 95, 85, 61, 87, 96, 64, 98, 98, 83, 88, 4, 73, 29, 26, 67, 59, 34, 89, 49, 6, 16, 0, 61, 55, 76, 73, 64, 26, 63, 56, 64, 66, 86],
[98, 2, 10, 34, 9, 10, 8, 46, 2, 95, 89, 65, 49, 1, 38, 15, 8, 22, 66, 80, 7, 77, 77, 70, 1, 7, 60, 59, 93, 7, 2, 98, 31, 95, 87, 18],
[47, 20, 77, 92, 92, 78, 81, 7, 34, 20, 30, 40, 56, 79, 86, 84, 81, 40, 19, 28, 72, 35, 20, 85, 3, 68, 18, 4, 63, 83, 20, 12, 41, 63, 19, 58],
[55, 10, 67, 18, 31, 16, 76, 57, 79, 64, 68, 37, 78, 60, 60, 46, 49, 32, 32, 3, 65, 74, 22, 79, 26, 29, 28, 86, 20, 99, 27, 99, 28, 30, 54, 20],
[73, 87, 66, 32, 10, 75, 40, 94, 30, 99, 52, 10, 33, 33, 52, 36, 16, 90, 68, 62, 19, 33, 50, 22, 78, 47, 91, 22, 84, 83, 41, 17, 32, 83, 38, 23],
[82, 26, 41, 53, 71, 22, 95, 55, 60, 14, 40, 42, 36, 43, 91, 50, 16, 93, 62, 72, 3, 14, 55, 48, 20, 17, 56, 38, 64, 87, 86, 92, 82, 75, 73, 76],
[70, 18, 42, 41, 19, 44, 8, 90, 10, 73, 41, 39, 23, 69, 64, 55, 39, 80, 88, 13, 5, 29, 71, 53, 84, 71, 91, 97, 60, 67, 10, 15, 53, 37, 68, 91],
[12, 99, 93, 43, 63, 51, 54, 89, 39, 8, 19, 27, 70, 94, 0, 70, 76, 1, 51, 30, 60, 88, 24, 69, 35, 36, 97, 43, 0, 70, 21, 84, 19, 6, 93, 92],
[15, 83, 14, 61, 0, 18, 77, 34, 95, 92, 22, 76, 54, 9, 22, 43, 96, 91, 24, 12, 30, 22, 88, 72, 82, 38, 27, 10, 41, 2, 78, 25, 36, 20, 70, 55],
[83, 6, 84, 58, 57, 42, 76, 75, 36, 39, 98, 55, 72, 72, 84, 81, 36, 9, 3, 44, 1, 50, 63, 1, 93, 24, 26, 20, 30, 68, 0, 24, 90, 26, 6, 88],
[58, 38, 65, 42, 40, 25, 32, 39, 19, 31, 74, 36, 85, 74, 23, 20, 37, 41, 41, 63, 61, 9, 27, 39, 22, 0, 36, 34, 53, 53, 6, 40, 81, 18, 86, 8],
[34, 1, 53, 24, 53, 46, 21, 59, 74, 75, 10, 49, 79, 74, 29, 68, 82, 75, 49, 62, 8, 58, 54, 34, 87, 4, 84, 34, 10, 82, 70, 35, 62, 9, 33, 77],
[28, 49, 3, 98, 69, 36, 80, 53, 72, 68, 89, 22, 40, 52, 5, 66, 39, 38, 41, 45, 13, 12, 70, 12, 7, 86, 95, 83, 66, 92, 43, 13, 53, 80, 75, 33],
[98, 98, 88, 3, 11, 32, 83, 24, 91, 79, 3, 55, 50, 95, 41, 69, 30, 89, 68, 47, 13, 35, 0, 86, 57, 8, 10, 31, 1, 40, 81, 2, 87, 10, 73, 0],
[36, 8, 65, 86, 88, 65, 19, 33, 62, 24, 98, 34, 0, 80, 45, 53, 16, 28, 41, 65, 93, 34, 64, 85, 48, 98, 15, 51, 41, 65, 5, 9, 51, 17, 17, 91],
[21, 49, 80, 99, 8, 32, 11, 36, 82, 59, 64, 59, 55, 73, 1, 23, 82, 59, 19, 16, 58, 18, 62, 36, 74, 30, 72, 79, 26, 31, 16, 40, 2, 27, 65, 26],
[86, 24, 59, 75, 93, 17, 20, 42, 21, 4, 80, 0, 57, 91, 81, 84, 95, 13, 65, 85, 9, 15, 26, 90, 66, 20, 13, 98, 67, 27, 85, 49, 45, 65, 10, 84],
[17, 16, 99, 46, 21, 66, 57, 69, 29, 42, 50, 92, 9, 11, 56, 62, 32, 15, 55, 25, 55, 90, 81, 74, 62, 98, 58, 65, 46, 77, 53, 10, 0, 59, 70, 91],
[76, 89, 89, 89, 87, 87, 11, 51, 11, 44, 11, 50, 29, 88, 93, 31, 6, 26, 74, 34, 24, 30, 14, 74, 9, 47, 20, 17, 88, 14, 49, 87, 3, 65, 27, 73],
[18, 18, 68, 23, 13, 98, 52, 92, 72, 75, 8, 8, 2, 33, 69, 23, 22, 16, 95, 76, 43, 83, 86, 27, 4, 58, 57, 97, 64, 22, 43, 32, 41, 2, 88, 26],
[21, 20, 85, 29, 56, 31, 65, 45, 58, 26, 62, 21, 71, 31, 5, 57, 88, 42, 51, 39, 79, 83, 47, 99, 25, 31, 9, 24, 13, 63, 95, 78, 80, 74, 78, 89],
[39, 90, 68, 22, 85, 14, 4, 20, 41, 51, 67, 75, 20, 48, 91, 65, 61, 44, 66, 3, 83, 30, 93, 23, 19, 99, 46, 88, 87, 35, 3, 88, 35, 67, 88, 28],
[63, 21, 64, 10, 7, 38, 25, 17, 32, 36, 7, 99, 46, 65, 74, 71, 63, 42, 30, 72, 29, 80, 42, 65, 27, 24, 16, 16, 70, 2, 54, 60, 35, 79, 88, 39],
[10, 75, 23, 44, 33, 33, 11, 13, 23, 3, 44, 37, 64, 66, 35, 32, 34, 22, 18, 15, 6, 37, 25, 36, 20, 4, 49, 58, 59, 21, 80, 95, 0, 31, 93, 28],
[54, 30, 99, 86, 7, 38, 8, 18, 26, 83, 15, 83, 45, 5, 24, 67, 6, 39, 65, 67, 83, 99, 29, 41, 64, 62, 25, 53, 54, 34, 24, 41, 99, 28, 8, 29],
[30, 60, 67, 20, 43, 56, 79, 43, 92, 85, 69, 9, 62, 22, 62, 24, 68, 33, 18, 61, 25, 14, 21, 59, 86, 59, 53, 26, 1, 80, 9, 36, 4, 5, 85, 47],
[57, 64, 8, 17, 69, 23, 77, 29, 69, 52, 80, 86, 18, 93, 78, 17, 36, 60, 94, 25, 80, 90, 87, 86, 64, 23, 87, 95, 19, 69, 91, 82, 37, 27, 27, 46],
[52, 19, 54, 87, 1, 4, 41, 68, 93, 56, 36, 13, 32, 25, 83, 48, 59, 5, 37, 58, 83, 93, 53, 77, 44, 63, 49, 1, 94, 4, 28, 30, 85, 15, 85, 90],
[75, 72, 89, 33, 98, 23, 81, 41, 35, 17, 4, 1, 46, 60, 83, 69, 27, 35, 33, 83, 61, 61, 21, 72, 82, 72, 82, 6, 59, 51, 60, 37, 82, 20, 88, 54],
[20, 37, 13, 75, 81, 78, 36, 75, 22, 45, 81, 63, 58, 72, 81, 7, 9, 39, 49, 8, 84, 66, 71, 58, 41, 56, 5, 2, 83, 47, 16, 3, 93, 95, 97, 10],
[94, 83, 74, 92, 8, 10, 12, 92, 28, 28, 31, 98, 10, 33, 62, 70, 85, 53, 8, 31, 75, 67, 38, 2, 5, 85, 44, 25, 54, 69, 33, 61, 75, 57, 79, 82],
[60, 34, 79, 9, 2, 28, 80, 24, 2, 76, 26, 34, 61, 22, 40, 31, 52, 14, 30, 2, 88, 54, 41, 73, 6, 45, 13, 22, 70, 51, 74, 69, 19, 66, 33, 78],
[3, 11, 50, 41, 23, 41, 45, 2, 62, 95, 55, 73, 1, 98, 33, 68, 82, 96, 24, 81, 1, 58, 59, 41, 45, 9, 99, 49, 16, 97, 54, 75, 92, 14, 71, 63],
[18, 73, 63, 61, 88, 15, 27, 49, 82, 95, 0, 54, 71, 76, 64, 65, 84, 39, 61, 56, 52, 60, 88, 92, 75, 83, 94, 61, 76, 76, 14, 11, 5, 95, 71, 68]]
failure_count = 0
for nums in sets_of_random:
  nums.sort(reverse=True)
  # I think simple diagonalisation should work (in that if it does not work, the task is not possible)
  grid = [
    [nums[0],nums[1],nums[3],nums[6],nums[10],nums[15]],
    [nums[2],nums[4],nums[7],nums[11],nums[16],nums[21]],
    [nums[5],nums[8],nums[12],nums[17],nums[22],nums[26]],
    [nums[9],nums[13],nums[18],nums[23],nums[27],nums[30]],
    [nums[14],nums[19],nums[24],nums[28],nums[31],nums[33]],
    [nums[20],nums[25],nums[29],nums[32],nums[34],nums[35]]
  ]
  all_distinct = True
  for row in grid:
    if len(set(row)) < 6:
      all_distinct = False
      failure_count += 1
      break
  # if not all_distinct:
  #   for row in grid:
  #       print(' '.join(f'{num:3}' for num in row))
  #   print("\n\n")
print(f"failure_count = {failure_count}")
79819224
Vote

The data could be read by your code from the original RandomNumbers.txt file provided by the challenge.

I found it very convenient that the file contain sets of 36 integers organized in a way that each would be a valid list in Python, so I used the literal_eval() function from the ast module to parse each line of the text file as list of ints directly (see my answer for details).

As for the hard-coded diagonalisation, I think it is a perfectly valid solution, the proposed challenge is for the code to work for 6x6 grids only, so I don't think you need to change that logic if you don't want to.

79818583
Vote

Total possible set: 55

Total impossible set: 45

Online java compiler used: https://www.online-java.com/

java code:

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<List<Integer>> dataSets = getEmbeddedData();
        int impossibleCount = 0;
        int possibleCount = 0;
        int setIndex = 1;

        for (List<Integer> numbers : dataSets) {
            System.out.println("Processing Set " + setIndex + "...");
            if (numbers.size() != 36) {
                System.out.println("Set " + setIndex + ": Invalid input size");
            } else {
                // 1) Check the set is mathematical possible to solve before actual solving (For execution speed concern)
                // 1.1) Count distinct values in set
                int distinctCount = countDistinct(numbers);
                if (distinctCount < 11) {
                    System.out.println("Set " + setIndex + ": Impossible\n");
                    impossibleCount++;
                    setIndex++;
                    continue;
                }
                // 1.2) Frequency-based feasibility check for largest/smallest values
                /*
                 * Largest number(L) cannot have duplicate number (Top-left cell must be greater than all values in its row and column)
                 * 2nd Largest number(L2) cannot exist more than 2 times.
                 * 3rd Largest number(L3) cannot exist more than 3 times.
                 * 4th Largest number(L4) cannot exist more than 4 times.
                 * 5th Largest number(L5) cannot exist more than 5 times.
                 * Smallest number(S) cannot have duplicate number (Bottom-right cell must be smaller than all values in its row and column)
                 * 2nd Smallest number(S2) cannot exist more than 2 times.
                 * 3rd Smallest number(S3) cannot exist more than 3 times.
                 * 4th Smallest number(S4) cannot exist more than 4 times.
                 * 5th Smallest number(S5) cannot exist more than 5 times.
                 * For other number that not first 5 largest and not first 5 smallest(O) cannot exist more than 6 times.
                 * [[L,L2,L3,L4,L5,O],
                 * [L2,L3,L4,L5,O,S5],
                 * [L3,L4,L5,O,S5,S4],
                 * [L4,L5,O,S5,S4,S3],
                 * [L5,O,S5,S4,S3,S2],
                 * [O,S5,S4,S3,S2,S]]
                 */
                List<Integer> sorted = numbers.stream().distinct()
                    .sorted(Comparator.reverseOrder())
                    .collect(Collectors.toList());

                Map<Integer, Long> freq = numbers.stream()
                    .collect(Collectors.groupingBy(n -> n, Collectors.counting()));

                int max = sorted.get(0);
                int min = sorted.get(sorted.size() - 1);
                long maxCount = freq.getOrDefault(max, 0L);
                long minCount = freq.getOrDefault(min, 0L);

                if (maxCount > 1 || minCount > 1) {
                    System.out.println("Set " + setIndex + ": Impossible\n");
                    impossibleCount++;
                    setIndex++;
                    continue;
                }

                if (sorted.size() > 1) {
                    int max2 = sorted.get(1);
                    if (freq.getOrDefault(max2, 0L) > 2) {
                        System.out.println("Set " + setIndex + ": Impossible\n");
                        impossibleCount++;
                        setIndex++;
                        continue;
                    }
                }
                if (sorted.size() > 2) {
                    int max3 = sorted.get(2);
                    if (freq.getOrDefault(max3, 0L) > 3) {
                        System.out.println("Set " + setIndex + ": Impossible\n");
                        impossibleCount++;
                        setIndex++;
                        continue;
                    }
                }
                if (sorted.size() > 3) {
                    int max4 = sorted.get(3);
                    if (freq.getOrDefault(max4, 0L) > 4) {
                        System.out.println("Set " + setIndex + ": Impossible\n");
                        impossibleCount++;
                        setIndex++;
                        continue;
                    }
                }
                if (sorted.size() > 4) {
                    int max5 = sorted.get(4);
                    if (freq.getOrDefault(max5, 0L) > 5) {
                        System.out.println("Set " + setIndex + ": Impossible\n");
                        impossibleCount++;
                        setIndex++;
                        continue;
                    }
                }

                if (sorted.size() > 1) {
                    int min2 = sorted.get(sorted.size() - 2);
                    if (freq.getOrDefault(min2, 0L) > 2) {
                        System.out.println("Set " + setIndex + ": Impossible\n");
                        impossibleCount++;
                        setIndex++;
                        continue;
                    }
                }
                if (sorted.size() > 2) {
                    int min3 = sorted.get(sorted.size() - 3);
                    if (freq.getOrDefault(min3, 0L) > 3) {
                        System.out.println("Set " + setIndex + ": Impossible\n");
                        impossibleCount++;
                        setIndex++;
                        continue;
                    }
                }
                if (sorted.size() > 3) {
                    int min4 = sorted.get(sorted.size() - 4);
                    if (freq.getOrDefault(min4, 0L) > 4) {
                        System.out.println("Set " + setIndex + ": Impossible\n");
                        impossibleCount++;
                        setIndex++;
                        continue;
                    }
                }
                if (sorted.size() > 4) {
                    int min5 = sorted.get(sorted.size() - 5);
                    if (freq.getOrDefault(min5, 0L) > 5) {
                        System.out.println("Set " + setIndex + ": Impossible\n");
                        impossibleCount++;
                        setIndex++;
                        continue;
                    }
                }

                // Check all other values (not top 5 or bottom 5)
                Set<Integer> exempt = new HashSet<>();
                for (int i = 0; i < 5 && i < sorted.size(); i++) {
                    exempt.add(sorted.get(i)); // top 5
                    exempt.add(sorted.get(sorted.size() - 1 - i)); // bottom 5
                }
                for (Map.Entry<Integer, Long> entry : freq.entrySet()) {
                    int val = entry.getKey();
                    long count = entry.getValue();
                    if (!exempt.contains(val) && count > 6) {
                        System.out.println("Set " + setIndex + ": Impossible\n");
                        impossibleCount++;
                        setIndex++;
                        continue;
                    }
                }
                
                int[][] grid = trySortGrid(numbers);
                if (grid == null) {
                    System.out.println("Set " + setIndex + ": Impossible\n");
                    impossibleCount++;
                } else {
                    System.out.println("Set " + setIndex + ": Possible");
                    printGrid(grid);
                    printGridAsArrayLiteral(grid);
                    possibleCount++;
                }
            }
            setIndex++;
        }

        System.out.println("\nTotal possible sets: " + possibleCount);
        System.out.println("Total impossible sets: " + impossibleCount);
    }

    // Replace file reading with embedded data (Convenient for using online java compiler)
    private static List<List<Integer>> getEmbeddedData() {
        List<List<Integer>> dataSets = new ArrayList<>();

        dataSets.add(Arrays.asList(54, 95, 98, 26, 3, 39, 77, 30, 83, 62, 20, 92, 61, 59, 26, 63, 92, 49, 38, 51, 99, 64, 65, 52, 98, 18, 90, 97, 96, 13, 74, 3, 88, 88, 67, 10));
        dataSets.add(Arrays.asList(49, 13, 73, 54, 4, 98, 36, 33, 12, 22, 35, 18, 39, 83, 92, 77, 50, 77, 57, 64, 0, 35, 86, 98, 28, 1, 53, 59, 28, 33, 56, 37, 98, 26, 81, 13));
        dataSets.add(Arrays.asList(95, 84, 44, 16, 42, 73, 0, 53, 14, 63, 81, 91, 42, 14, 13, 59, 91, 24, 99, 71, 73, 34, 60, 65, 82, 55, 16, 75, 7, 18, 68, 6, 61, 6, 80, 41));
        dataSets.add(Arrays.asList(27, 63, 35, 81, 56, 24, 70, 27, 59, 13, 36, 62, 73, 6, 61, 86, 48, 40, 88, 71, 52, 1, 9, 57, 50, 40, 20, 10, 3, 29, 19, 94, 99, 8, 74, 83));
        dataSets.add(Arrays.asList(46, 75, 78, 14, 89, 76, 37, 26, 85, 78, 81, 27, 99, 41, 96, 52, 21, 65, 71, 48, 60, 32, 48, 31, 85, 35, 88, 5, 78, 22, 31, 97, 43, 80, 52, 45));
        dataSets.add(Arrays.asList(0, 98, 50, 12, 0, 83, 46, 66, 67, 23, 52, 55, 41, 95, 5, 17, 78, 98, 74, 45, 97, 98, 96, 54, 48, 79, 29, 0, 73, 6, 16, 33, 20, 88, 9, 23));
        dataSets.add(Arrays.asList(9, 2, 10, 57, 79, 65, 65, 0, 19, 64, 3, 18, 20, 93, 10, 30, 9, 0, 40, 51, 87, 34, 52, 71, 28, 23, 73, 61, 77, 60, 66, 91, 57, 58, 2, 9));
        dataSets.add(Arrays.asList(27, 63, 51, 6, 3, 10, 7, 36, 80, 51, 93, 71, 73, 25, 3, 77, 35, 56, 36, 36, 77, 97, 14, 1, 78, 83, 5, 51, 99, 5, 93, 90, 1, 36, 83, 4));
        dataSets.add(Arrays.asList(89, 94, 67, 64, 31, 66, 59, 16, 80, 22, 78, 72, 56, 83, 98, 10, 9, 57, 23, 4, 80, 37, 65, 30, 71, 55, 42, 9, 60, 18, 39, 58, 44, 79, 48, 29));
        dataSets.add(Arrays.asList(79, 51, 3, 82, 81, 58, 99, 88, 54, 88, 81, 5, 63, 79, 52, 64, 48, 64, 68, 11, 50, 66, 35, 71, 9, 86, 11, 97, 42, 41, 0, 2, 56, 38, 15, 63));
        dataSets.add(Arrays.asList(94, 35, 12, 94, 79, 40, 91, 45, 37, 98, 43, 30, 80, 81, 87, 19, 74, 87, 93, 35, 88, 89, 79, 44, 6, 87, 27, 49, 98, 44, 68, 39, 42, 87, 61, 84));
        dataSets.add(Arrays.asList(5, 37, 89, 80, 31, 40, 1, 10, 54, 67, 23, 1, 75, 43, 49, 27, 29, 69, 43, 41, 7, 16, 63, 70, 5, 61, 74, 87, 2, 61, 50, 72, 91, 56, 12, 99));
        dataSets.add(Arrays.asList(43, 35, 83, 94, 69, 45, 76, 73, 83, 60, 80, 31, 59, 34, 39, 63, 35, 13, 94, 78, 2, 24, 87, 21, 36, 38, 55, 19, 10, 82, 13, 95, 88, 54, 94, 75));
        dataSets.add(Arrays.asList(66, 10, 58, 21, 82, 10, 32, 91, 66, 65, 3, 12, 4, 38, 12, 96, 55, 54, 73, 16, 74, 41, 28, 49, 19, 98, 16, 90, 93, 82, 56, 68, 14, 70, 31, 19));
        dataSets.add(Arrays.asList(13, 79, 47, 31, 79, 31, 56, 65, 94, 73, 57, 35, 74, 85, 84, 39, 24, 26, 12, 56, 46, 46, 71, 0, 57, 61, 77, 32, 14, 1, 81, 71, 69, 66, 57, 69));
        dataSets.add(Arrays.asList(8, 39, 23, 14, 88, 44, 81, 46, 5, 26, 50, 11, 71, 19, 86, 33, 88, 62, 81, 13, 60, 96, 7, 78, 6, 88, 77, 94, 74, 63, 48, 40, 29, 47, 64, 6));
        dataSets.add(Arrays.asList(95, 36, 61, 3, 75, 84, 95, 8, 57, 42, 43, 77, 27, 65, 56, 78, 34, 96, 18, 23, 46, 17, 86, 17, 89, 28, 96, 18, 24, 90, 93, 49, 47, 69, 91, 48));
        dataSets.add(Arrays.asList(76, 95, 10, 10, 58, 67, 25, 41, 0, 49, 13, 40, 59, 29, 62, 64, 97, 47, 22, 42, 39, 44, 16, 95, 23, 91, 14, 48, 90, 39, 16, 92, 46, 38, 49, 16));
        dataSets.add(Arrays.asList(60, 42, 28, 28, 61, 10, 37, 90, 99, 9, 45, 15, 61, 20, 6, 89, 99, 5, 34, 28, 58, 45, 10, 43, 73, 5, 45, 78, 68, 48, 44, 56, 78, 69, 52, 99));
        dataSets.add(Arrays.asList(99, 92, 63, 87, 23, 73, 25, 25, 31, 97, 14, 12, 77, 96, 73, 80, 86, 15, 63, 71, 44, 34, 51, 28, 77, 24, 19, 74, 87, 34, 59, 40, 82, 13, 25, 15));
        dataSets.add(Arrays.asList(48, 59, 63, 45, 51, 64, 88, 99, 81, 29, 69, 27, 7, 28, 9, 77, 50, 80, 7, 64, 3, 24, 6, 22, 31, 69, 92, 66, 13, 3, 70, 81, 73, 50, 45, 42));
        dataSets.add(Arrays.asList(0, 49, 29, 50, 38, 38, 24, 71, 8, 5, 56, 6, 90, 2, 3, 35, 40, 89, 24, 27, 74, 77, 54, 7, 1, 76, 92, 16, 55, 23, 47, 62, 33, 1, 80, 47));
        dataSets.add(Arrays.asList(1, 61, 12, 89, 56, 47, 88, 63, 73, 49, 9, 78, 68, 69, 19, 53, 76, 39, 49, 83, 38, 70, 62, 79, 19, 7, 70, 4, 90, 57, 90, 20, 52, 37, 64, 17));
        dataSets.add(Arrays.asList(0, 99, 18, 20, 0, 5, 93, 66, 87, 4, 62, 47, 94, 27, 73, 82, 12, 37, 39, 63, 59, 71, 71, 36, 84, 53, 90, 93, 9, 21, 94, 76, 80, 4, 40, 30));
        dataSets.add(Arrays.asList(57, 17, 99, 26, 7, 0, 81, 29, 95, 51, 46, 8, 16, 19, 15, 48, 89, 65, 69, 14, 94, 9, 3, 78, 59, 20, 41, 45, 97, 99, 57, 52, 94, 12, 55, 28));
        dataSets.add(Arrays.asList(19, 49, 58, 20, 73, 65, 0, 72, 82, 12, 64, 43, 34, 58, 11, 74, 20, 75, 0, 23, 6, 25, 81, 39, 44, 65, 54, 57, 72, 72, 10, 69, 31, 10, 45, 20));
        dataSets.add(Arrays.asList(68, 46, 13, 68, 81, 62, 28, 75, 66, 91, 27, 31, 20, 38, 1, 45, 76, 79, 14, 62, 58, 66, 17, 79, 61, 91, 86, 33, 57, 95, 74, 7, 31, 85, 97, 80));
        dataSets.add(Arrays.asList(67, 31, 55, 44, 11, 39, 50, 79, 64, 75, 97, 13, 22, 19, 42, 58, 55, 10, 51, 37, 73, 55, 22, 40, 35, 97, 77, 92, 43, 24, 69, 25, 64, 61, 48, 77));
        dataSets.add(Arrays.asList(7, 17, 84, 29, 87, 12, 85, 22, 65, 70, 73, 14, 32, 9, 27, 3, 11, 42, 88, 20, 37, 10, 88, 77, 68, 92, 71, 80, 83, 32, 35, 85, 91, 52, 26, 73));
        dataSets.add(Arrays.asList(62, 24, 97, 27, 49, 2, 50, 36, 14, 59, 63, 1, 45, 98, 80, 64, 59, 80, 55, 96, 87, 89, 19, 81, 40, 31, 73, 48, 29, 34, 63, 11, 12, 7, 84, 28));
        dataSets.add(Arrays.asList(23, 82, 3, 66, 59, 65, 49, 80, 16, 73, 39, 69, 45, 15, 6, 14, 4, 97, 76, 57, 34, 13, 77, 72, 98, 24, 34, 54, 23, 41, 67, 6, 80, 19, 30, 92));
        dataSets.add(Arrays.asList(20, 35, 58, 63, 21, 75, 58, 8, 30, 44, 97, 21, 3, 86, 78, 89, 93, 42, 29, 89, 53, 17, 89, 6, 8, 14, 48, 98, 15, 58, 28, 46, 51, 55, 17, 78));
        dataSets.add(Arrays.asList(42, 41, 8, 12, 37, 81, 33, 58, 59, 31, 3, 67, 77, 90, 6, 2, 14, 45, 49, 28, 79, 93, 7, 75, 52, 52, 46, 86, 98, 77, 66, 38, 41, 11, 41, 2));
        dataSets.add(Arrays.asList(8, 45, 28, 85, 58, 99, 18, 86, 95, 16, 59, 45, 26, 35, 36, 96, 61, 82, 32, 20, 62, 47, 93, 3, 44, 71, 11, 11, 31, 28, 42, 7, 18, 58, 40, 89));
        dataSets.add(Arrays.asList(87, 4, 99, 46, 73, 27, 7, 44, 26, 62, 15, 10, 14, 77, 97, 70, 58, 23, 85, 73, 76, 97, 6, 92, 52, 51, 9, 84, 29, 56, 15, 38, 41, 7, 88, 76));
        dataSets.add(Arrays.asList(30, 0, 80, 70, 10, 78, 91, 80, 3, 42, 24, 70, 39, 7, 7, 43, 9, 2, 23, 96, 76, 87, 19, 11, 5, 10, 74, 10, 49, 16, 34, 54, 40, 55, 75, 93));
        dataSets.add(Arrays.asList(92, 54, 58, 53, 99, 84, 53, 50, 56, 65, 10, 89, 19, 2, 6, 94, 44, 69, 67, 60, 79, 5, 30, 23, 15, 8, 48, 26, 32, 31, 43, 59, 81, 9, 67, 93));
        dataSets.add(Arrays.asList(7, 58, 97, 4, 22, 36, 5, 83, 32, 69, 83, 54, 18, 48, 49, 43, 36, 37, 96, 0, 28, 18, 64, 56, 52, 97, 43, 95, 36, 8, 48, 35, 60, 41, 48, 81));
        dataSets.add(Arrays.asList(50, 78, 66, 51, 45, 80, 65, 87, 0, 5, 87, 91, 34, 78, 47, 89, 51, 32, 88, 64, 52, 8, 86, 59, 11, 5, 1, 12, 57, 87, 75, 83, 17, 69, 96, 61));
        dataSets.add(Arrays.asList(74, 18, 35, 33, 97, 4, 22, 39, 41, 10, 66, 59, 11, 71, 90, 28, 78, 66, 51, 25, 48, 89, 74, 62, 13, 19, 67, 99, 19, 88, 15, 83, 26, 86, 31, 93));
        dataSets.add(Arrays.asList(93, 32, 27, 13, 61, 53, 49, 35, 59, 13, 54, 68, 75, 31, 18, 79, 33, 59, 87, 86, 14, 26, 21, 19, 12, 59, 75, 36, 7, 71, 25, 25, 6, 85, 29, 99));
        dataSets.add(Arrays.asList(94, 78, 11, 70, 49, 22, 25, 67, 34, 65, 85, 58, 76, 10, 44, 22, 75, 72, 65, 54, 68, 60, 84, 52, 19, 26, 61, 69, 88, 76, 37, 41, 81, 1, 23, 57));
        dataSets.add(Arrays.asList(15, 72, 24, 37, 95, 16, 76, 61, 34, 47, 68, 93, 18, 92, 32, 17, 20, 66, 51, 33, 65, 38, 71, 45, 81, 59, 34, 35, 84, 37, 14, 6, 41, 60, 57, 54));
        dataSets.add(Arrays.asList(83, 86, 73, 77, 75, 67, 5, 92, 43, 13, 98, 92, 69, 80, 50, 25, 64, 0, 64, 25, 98, 40, 66, 77, 4, 18, 52, 50, 28, 36, 17, 54, 5, 83, 2, 40));
        dataSets.add(Arrays.asList(25, 68, 57, 61, 55, 81, 56, 71, 95, 72, 37, 21, 91, 8, 23, 26, 38, 44, 45, 84, 37, 51, 13, 42, 90, 12, 67, 21, 96, 31, 99, 97, 2, 90, 99, 56));
        dataSets.add(Arrays.asList(47, 90, 19, 59, 82, 32, 52, 99, 74, 8, 93, 18, 79, 22, 24, 63, 84, 50, 55, 86, 94, 23, 83, 65, 67, 48, 16, 15, 81, 78, 7, 43, 12, 52, 58, 28));
        dataSets.add(Arrays.asList(54, 39, 86, 53, 24, 55, 72, 2, 6, 15, 78, 8, 35, 70, 59, 80, 74, 99, 95, 32, 44, 26, 47, 49, 48, 14, 95, 66, 54, 76, 37, 81, 85, 37, 45, 7));
        dataSets.add(Arrays.asList(19, 38, 6, 31, 71, 53, 40, 85, 71, 52, 56, 25, 78, 32, 17, 85, 42, 24, 61, 42, 3, 54, 98, 68, 48, 39, 59, 59, 12, 25, 96, 98, 15, 88, 44, 45));
        dataSets.add(Arrays.asList(62, 70, 19, 57, 56, 68, 7, 13, 53, 87, 68, 69, 77, 39, 23, 94, 42, 10, 1, 28, 43, 31, 42, 48, 75, 95, 28, 10, 44, 50, 72, 47, 64, 96, 5, 63));
        dataSets.add(Arrays.asList(92, 85, 77, 92, 90, 27, 39, 57, 51, 41, 99, 78, 78, 53, 88, 59, 30, 65, 15, 25, 32, 32, 99, 64, 90, 40, 13, 45, 41, 73, 98, 12, 44, 73, 33, 32));
        dataSets.add(Arrays.asList(97, 36, 97, 58, 74, 56, 70, 80, 92, 84, 93, 16, 0, 34, 96, 85, 84, 16, 29, 22, 27, 42, 26, 40, 27, 80, 1, 40, 82, 25, 54, 31, 77, 25, 67, 73));
        dataSets.add(Arrays.asList(46, 91, 13, 50, 65, 68, 44, 15, 65, 58, 77, 21, 92, 70, 69, 95, 9, 84, 69, 71, 53, 65, 0, 33, 95, 4, 1, 28, 62, 27, 39, 38, 47, 39, 61, 81));
        dataSets.add(Arrays.asList(37, 0, 70, 66, 14, 20, 50, 68, 8, 0, 62, 41, 68, 35, 14, 69, 94, 62, 53, 84, 32, 22, 80, 81, 22, 66, 36, 65, 40, 53, 93, 0, 0, 33, 32, 7));
        dataSets.add(Arrays.asList(68, 73, 37, 13, 86, 20, 22, 97, 27, 10, 32, 57, 27, 11, 52, 7, 7, 48, 23, 14, 98, 25, 41, 6, 78, 63, 80, 38, 24, 75, 2, 61, 45, 93, 18, 94));
        dataSets.add(Arrays.asList(20, 14, 76, 73, 80, 30, 56, 33, 80, 18, 79, 66, 39, 3, 88, 25, 28, 24, 63, 88, 68, 28, 67, 49, 6, 18, 4, 49, 0, 96, 11, 22, 6, 41, 17, 50));
        dataSets.add(Arrays.asList(9, 61, 45, 7, 25, 86, 99, 39, 79, 13, 46, 74, 44, 3, 90, 43, 25, 9, 2, 27, 13, 15, 38, 98, 2, 88, 13, 51, 44, 80, 67, 85, 84, 40, 2, 68));
        dataSets.add(Arrays.asList(22, 48, 11, 46, 99, 88, 75, 32, 69, 66, 73, 10, 3, 31, 13, 44, 11, 17, 68, 0, 37, 86, 40, 92, 13, 61, 24, 69, 22, 11, 53, 1, 14, 53, 96, 29));
        dataSets.add(Arrays.asList(65, 27, 91, 56, 76, 11, 86, 34, 3, 15, 97, 42, 19, 98, 38, 78, 90, 37, 76, 55, 46, 18, 72, 92, 3, 38, 55, 54, 5, 0, 58, 24, 77, 70, 65, 55));
        dataSets.add(Arrays.asList(33, 48, 21, 34, 42, 60, 82, 33, 98, 27, 51, 33, 74, 55, 59, 96, 44, 35, 23, 28, 13, 52, 72, 9, 39, 52, 8, 30, 40, 8, 97, 43, 79, 89, 38, 80));
        dataSets.add(Arrays.asList(1, 29, 67, 37, 13, 29, 33, 96, 91, 24, 4, 67, 20, 71, 75, 95, 2, 63, 39, 14, 88, 2, 5, 17, 38, 40, 74, 79, 39, 62, 38, 58, 74, 4, 27, 97));
        dataSets.add(Arrays.asList(86, 8, 5, 54, 58, 78, 70, 51, 89, 94, 51, 55, 27, 6, 56, 44, 14, 72, 5, 27, 19, 50, 72, 58, 66, 24, 49, 28, 15, 12, 12, 37, 85, 89, 53, 38));
        dataSets.add(Arrays.asList(54, 1, 82, 23, 72, 55, 6, 96, 54, 22, 19, 63, 83, 50, 39, 75, 33, 29, 83, 14, 60, 92, 62, 83, 11, 34, 53, 77, 57, 63, 18, 17, 50, 9, 90, 36));
        dataSets.add(Arrays.asList(60, 78, 25, 81, 18, 1, 96, 39, 36, 82, 23, 78, 70, 80, 19, 55, 74, 38, 99, 37, 3, 87, 21, 26, 93, 89, 44, 13, 95, 92, 11, 71, 77, 10, 49, 90));
        dataSets.add(Arrays.asList(68, 68, 45, 82, 67, 7, 97, 49, 87, 83, 73, 70, 70, 87, 14, 37, 10, 21, 82, 71, 75, 13, 89, 93, 63, 11, 40, 18, 32, 69, 38, 53, 81, 63, 51, 76));
        dataSets.add(Arrays.asList(25, 36, 27, 62, 4, 51, 50, 74, 19, 10, 78, 94, 15, 49, 11, 26, 91, 80, 61, 80, 84, 87, 80, 52, 35, 28, 64, 91, 39, 58, 15, 55, 26, 72, 68, 35));
        dataSets.add(Arrays.asList(42, 66, 36, 17, 5, 31, 38, 90, 61, 8, 24, 0, 7, 40, 65, 67, 54, 61, 53, 16, 49, 76, 21, 63, 23, 72, 20, 9, 42, 34, 10, 6, 63, 25, 61, 28));
        dataSets.add(Arrays.asList(9, 98, 52, 95, 85, 61, 87, 96, 64, 98, 98, 83, 88, 4, 73, 29, 26, 67, 59, 34, 89, 49, 6, 16, 0, 61, 55, 76, 73, 64, 26, 63, 56, 64, 66, 86));
        dataSets.add(Arrays.asList(98, 2, 10, 34, 9, 10, 8, 46, 2, 95, 89, 65, 49, 1, 38, 15, 8, 22, 66, 80, 7, 77, 77, 70, 1, 7, 60, 59, 93, 7, 2, 98, 31, 95, 87, 18));
        dataSets.add(Arrays.asList(47, 20, 77, 92, 92, 78, 81, 7, 34, 20, 30, 40, 56, 79, 86, 84, 81, 40, 19, 28, 72, 35, 20, 85, 3, 68, 18, 4, 63, 83, 20, 12, 41, 63, 19, 58));
        dataSets.add(Arrays.asList(55, 10, 67, 18, 31, 16, 76, 57, 79, 64, 68, 37, 78, 60, 60, 46, 49, 32, 32, 3, 65, 74, 22, 79, 26, 29, 28, 86, 20, 99, 27, 99, 28, 30, 54, 20));
        dataSets.add(Arrays.asList(73, 87, 66, 32, 10, 75, 40, 94, 30, 99, 52, 10, 33, 33, 52, 36, 16, 90, 68, 62, 19, 33, 50, 22, 78, 47, 91, 22, 84, 83, 41, 17, 32, 83, 38, 23));
        dataSets.add(Arrays.asList(82, 26, 41, 53, 71, 22, 95, 55, 60, 14, 40, 42, 36, 43, 91, 50, 16, 93, 62, 72, 3, 14, 55, 48, 20, 17, 56, 38, 64, 87, 86, 92, 82, 75, 73, 76));
        dataSets.add(Arrays.asList(70, 18, 42, 41, 19, 44, 8, 90, 10, 73, 41, 39, 23, 69, 64, 55, 39, 80, 88, 13, 5, 29, 71, 53, 84, 71, 91, 97, 60, 67, 10, 15, 53, 37, 68, 91));
        dataSets.add(Arrays.asList(12, 99, 93, 43, 63, 51, 54, 89, 39, 8, 19, 27, 70, 94, 0, 70, 76, 1, 51, 30, 60, 88, 24, 69, 35, 36, 97, 43, 0, 70, 21, 84, 19, 6, 93, 92));
        dataSets.add(Arrays.asList(15, 83, 14, 61, 0, 18, 77, 34, 95, 92, 22, 76, 54, 9, 22, 43, 96, 91, 24, 12, 30, 22, 88, 72, 82, 38, 27, 10, 41, 2, 78, 25, 36, 20, 70, 55));
        dataSets.add(Arrays.asList(83, 6, 84, 58, 57, 42, 76, 75, 36, 39, 98, 55, 72, 72, 84, 81, 36, 9, 3, 44, 1, 50, 63, 1, 93, 24, 26, 20, 30, 68, 0, 24, 90, 26, 6, 88));
        dataSets.add(Arrays.asList(58, 38, 65, 42, 40, 25, 32, 39, 19, 31, 74, 36, 85, 74, 23, 20, 37, 41, 41, 63, 61, 9, 27, 39, 22, 0, 36, 34, 53, 53, 6, 40, 81, 18, 86, 8));
        dataSets.add(Arrays.asList(34, 1, 53, 24, 53, 46, 21, 59, 74, 75, 10, 49, 79, 74, 29, 68, 82, 75, 49, 62, 8, 58, 54, 34, 87, 4, 84, 34, 10, 82, 70, 35, 62, 9, 33, 77));
        dataSets.add(Arrays.asList(28, 49, 3, 98, 69, 36, 80, 53, 72, 68, 89, 22, 40, 52, 5, 66, 39, 38, 41, 45, 13, 12, 70, 12, 7, 86, 95, 83, 66, 92, 43, 13, 53, 80, 75, 33));
        dataSets.add(Arrays.asList(98, 98, 88, 3, 11, 32, 83, 24, 91, 79, 3, 55, 50, 95, 41, 69, 30, 89, 68, 47, 13, 35, 0, 86, 57, 8, 10, 31, 1, 40, 81, 2, 87, 10, 73, 0));
        dataSets.add(Arrays.asList(36, 8, 65, 86, 88, 65, 19, 33, 62, 24, 98, 34, 0, 80, 45, 53, 16, 28, 41, 65, 93, 34, 64, 85, 48, 98, 15, 51, 41, 65, 5, 9, 51, 17, 17, 91));
        dataSets.add(Arrays.asList(21, 49, 80, 99, 8, 32, 11, 36, 82, 59, 64, 59, 55, 73, 1, 23, 82, 59, 19, 16, 58, 18, 62, 36, 74, 30, 72, 79, 26, 31, 16, 40, 2, 27, 65, 26));
        dataSets.add(Arrays.asList(86, 24, 59, 75, 93, 17, 20, 42, 21, 4, 80, 0, 57, 91, 81, 84, 95, 13, 65, 85, 9, 15, 26, 90, 66, 20, 13, 98, 67, 27, 85, 49, 45, 65, 10, 84));
        dataSets.add(Arrays.asList(17, 16, 99, 46, 21, 66, 57, 69, 29, 42, 50, 92, 9, 11, 56, 62, 32, 15, 55, 25, 55, 90, 81, 74, 62, 98, 58, 65, 46, 77, 53, 10, 0, 59, 70, 91));
        dataSets.add(Arrays.asList(76, 89, 89, 89, 87, 87, 11, 51, 11, 44, 11, 50, 29, 88, 93, 31, 6, 26, 74, 34, 24, 30, 14, 74, 9, 47, 20, 17, 88, 14, 49, 87, 3, 65, 27, 73));
        dataSets.add(Arrays.asList(18, 18, 68, 23, 13, 98, 52, 92, 72, 75, 8, 8, 2, 33, 69, 23, 22, 16, 95, 76, 43, 83, 86, 27, 4, 58, 57, 97, 64, 22, 43, 32, 41, 2, 88, 26));
        dataSets.add(Arrays.asList(21, 20, 85, 29, 56, 31, 65, 45, 58, 26, 62, 21, 71, 31, 5, 57, 88, 42, 51, 39, 79, 83, 47, 99, 25, 31, 9, 24, 13, 63, 95, 78, 80, 74, 78, 89));
        dataSets.add(Arrays.asList(39, 90, 68, 22, 85, 14, 4, 20, 41, 51, 67, 75, 20, 48, 91, 65, 61, 44, 66, 3, 83, 30, 93, 23, 19, 99, 46, 88, 87, 35, 3, 88, 35, 67, 88, 28));
        dataSets.add(Arrays.asList(63, 21, 64, 10, 7, 38, 25, 17, 32, 36, 7, 99, 46, 65, 74, 71, 63, 42, 30, 72, 29, 80, 42, 65, 27, 24, 16, 16, 70, 2, 54, 60, 35, 79, 88, 39));
        dataSets.add(Arrays.asList(10, 75, 23, 44, 33, 33, 11, 13, 23, 3, 44, 37, 64, 66, 35, 32, 34, 22, 18, 15, 6, 37, 25, 36, 20, 4, 49, 58, 59, 21, 80, 95, 0, 31, 93, 28));
        dataSets.add(Arrays.asList(54, 30, 99, 86, 7, 38, 8, 18, 26, 83, 15, 83, 45, 5, 24, 67, 6, 39, 65, 67, 83, 99, 29, 41, 64, 62, 25, 53, 54, 34, 24, 41, 99, 28, 8, 29));
        dataSets.add(Arrays.asList(30, 60, 67, 20, 43, 56, 79, 43, 92, 85, 69, 9, 62, 22, 62, 24, 68, 33, 18, 61, 25, 14, 21, 59, 86, 59, 53, 26, 1, 80, 9, 36, 4, 5, 85, 47));
        dataSets.add(Arrays.asList(57, 64, 8, 17, 69, 23, 77, 29, 69, 52, 80, 86, 18, 93, 78, 17, 36, 60, 94, 25, 80, 90, 87, 86, 64, 23, 87, 95, 19, 69, 91, 82, 37, 27, 27, 46));
        dataSets.add(Arrays.asList(52, 19, 54, 87, 1, 4, 41, 68, 93, 56, 36, 13, 32, 25, 83, 48, 59, 5, 37, 58, 83, 93, 53, 77, 44, 63, 49, 1, 94, 4, 28, 30, 85, 15, 85, 90));
        dataSets.add(Arrays.asList(75, 72, 89, 33, 98, 23, 81, 41, 35, 17, 4, 1, 46, 60, 83, 69, 27, 35, 33, 83, 61, 61, 21, 72, 82, 72, 82, 6, 59, 51, 60, 37, 82, 20, 88, 54));
        dataSets.add(Arrays.asList(20, 37, 13, 75, 81, 78, 36, 75, 22, 45, 81, 63, 58, 72, 81, 7, 9, 39, 49, 8, 84, 66, 71, 58, 41, 56, 5, 2, 83, 47, 16, 3, 93, 95, 97, 10));
        dataSets.add(Arrays.asList(94, 83, 74, 92, 8, 10, 12, 92, 28, 28, 31, 98, 10, 33, 62, 70, 85, 53, 8, 31, 75, 67, 38, 2, 5, 85, 44, 25, 54, 69, 33, 61, 75, 57, 79, 82));
        dataSets.add(Arrays.asList(60, 34, 79, 9, 2, 28, 80, 24, 2, 76, 26, 34, 61, 22, 40, 31, 52, 14, 30, 2, 88, 54, 41, 73, 6, 45, 13, 22, 70, 51, 74, 69, 19, 66, 33, 78));
        dataSets.add(Arrays.asList(3, 11, 50, 41, 23, 41, 45, 2, 62, 95, 55, 73, 1, 98, 33, 68, 82, 96, 24, 81, 1, 58, 59, 41, 45, 9, 99, 49, 16, 97, 54, 75, 92, 14, 71, 63));
        dataSets.add(Arrays.asList(18, 73, 63, 61, 88, 15, 27, 49, 82, 95, 0, 54, 71, 76, 64, 65, 84, 39, 61, 56, 52, 60, 88, 92, 75, 83, 94, 61, 76, 76, 14, 11, 5, 95, 71, 68));

        return dataSets;
    }

    private static int countDistinct(List<Integer> numbers) {
        Set<Integer> unique = new HashSet<>(numbers);
        return unique.size();
    }
    
    /*
     * Attempts to place 36 numbers into a 6x6 grid with strict constraints:
     * 1) The largest value is placed at [0][0], the smallest at [5][5]
     * 2) All other values must be placed such that:
     * 3) Each row and column contains unique values
     * 4) Each cell is strictly less than its left and top neighbors
     * 5) Placement proceeds in priority order based on Manhattan distance from [0][0]
     * Returns the completed grid if successful, or null if placement fails.
     */
    private static int[][] trySortGrid(List<Integer> numbers) {
        int max = Collections.max(numbers);
        int min = Collections.min(numbers);

        List<Integer> reduced = new ArrayList<>(numbers);
        reduced.remove(Integer.valueOf(max));
        reduced.remove(Integer.valueOf(min));

        reduced.sort(Collections.reverseOrder());

        int[][] grid = new int[6][6];
        grid[0][0] = max;
        grid[5][5] = min;

        @SuppressWarnings("unchecked")
        Set<Integer>[] rowVals = new HashSet[6];
        @SuppressWarnings("unchecked")
        Set<Integer>[] colVals = new HashSet[6];
        for (int i = 0; i < 6; i++) {
            rowVals[i] = new HashSet<>();
            colVals[i] = new HashSet<>();
        }

        rowVals[0].add(max);
        colVals[0].add(max);
        rowVals[5].add(min);
        colVals[5].add(min);
        
        // Build priority list of cells
        List<int[]> cells = new ArrayList<>();
        for (int r = 0; r < 6; r++) {
            for (int c = 0; c < 6; c++) {
                if ((r == 0 && c == 0) || (r == 5 && c == 5)) continue;
                cells.add(new int[]{r, c, r + c});
            }
        }

        // Sort cells by increasing priority (Manhattan distance from [0][0])
        cells.sort(Comparator.comparingInt(a -> a[2]));

        boolean[] used = new boolean[34];

        for (int[] cell : cells) {
            int r = cell[0];
            int c = cell[1];

            boolean placed = false;
            for (int i = 0; i < reduced.size(); i++) {
                if (used[i]) continue;
                int val = reduced.get(i);

                if (c > 0 && val >= grid[r][c - 1]) continue;
                if (r > 0 && val >= grid[r - 1][c]) continue;
                if (rowVals[r].contains(val) || colVals[c].contains(val)) continue;

                grid[r][c] = val;
                used[i] = true;
                rowVals[r].add(val);
                colVals[c].add(val);
                placed = true;
                break;
            }

            if (!placed) return null;
        }

        return grid;
    }
    
    private static void printGrid(int[][] grid) {
        System.out.print("6x6 Grid:\n");
        for (int[] row : grid) {
            for (int num : row) {
                System.out.print(num + " ");
            }
            System.out.println();
        }
    }
    
    private static void printGridAsArrayLiteral(int[][] grid) {
        System.out.print("Single-line nested array:\n");
        System.out.print("[");
        for (int r = 0; r < grid.length; r++) {
            System.out.print("[");
            for (int c = 0; c < grid[r].length; c++) {
                System.out.print(grid[r][c]);
                if (c < grid[r].length - 1) System.out.print(", ");
            }
            System.out.print("]");
            if (r < grid.length - 1) System.out.print(", ");
        }
        System.out.println("]\n");
    }
}

79818646
Vote

A couple of observations.

(1) The input vector must contain at least 11 distinct values in order to be viable; you are checking this condition and use it to skip processing an input vector that does not have at least 11 distinct values. What is the point then of repeatedly checking sorted.size() against much lower values?

(2) The frequency limits that you put on things like the 5th largest value are not tight/sufficient; the actual limits depend on the total number of values that are greater, not the number of distinct values that are greater. More precisely, the limit depends on the diagonal that a run of equal values starts in (if left of the main diagonal) or ends in (if right of the main diagonal).

For example, if the 4 distict values greater than the 5th largest all have a multiplicity of 1 then the run with the 5th largest value starts in the 3rd diagonal and hence cannot be longer than 3.

The fact that solutions like yours happen to compute the correct number of 'impossible' inputs speaks to the amazingly poor quality of the input vectors. They have only four failure modes out of the hundreds or more that are possible:

  • repeated maximum value (23 times)
  • repeated minimum value (19 times)
  • tripled second-largest value (2 times)
  • tripled third-largest value starting in 2nd diagonal

This means that the provided input vectors flush out only a tiny fraction of broken/erroneous submissions ...

The situation would have been much better if the input vectors had been chosen randomly.

79819777
Vote

I must correct myself: there are not 'hundreds or more' failures modes; the number of distinct failure constellations is smaller.

Given non-increasing (lax: 'descending') assignment of values in diagonal fashion and assuming that conformance testing occurs in the same order, there are exactly 30 different failure modes. This is easy to see if we label the failures with the coordinates of the cell during whose left-neighbour check the rule violation is detected.

Example for y = 1 and x = 3:

. . . . 5 .
. . 5 5 . .
. 5 . . . .
5 . . . . .
. . . . . .
. . . . . .
  1. Because of the non-increasing assignment a left-neighbour check can never find any inversions; a conflict can only ever occur because of value equality.

  2. If the left-neighbour check finds a rule violation for cell (y, x) then there must be a run of equal values beginning at the left neighbour (y, x - 1) and continuing diagonally until reaching cell (y, x).

  3. The run of equal values cannot begin before cell (y, x - 1) because that would have caused an earlier conflict with a predecessor of (y, x).

  4. It does not matter whether the run continues after cell (y, x) or whether the rest of the matrix contains more conflicts. KO is KO, period.

  5. Cell (0,0) can never conflict with anything because it does not have a left or upper neighbour. The other cells in the left-most column need not be checked because they can only conflict with their upper neighbour but this upper neighbour is also the left neighbour of the diagonal predecessor of the current cell. This diagonal predecessor must have the same value as the current cell but gets checked earlier. Hence the process must already have terminated with failure before the conflict with the upper neighbour could be detected.

Example:

. . . 4 . .
. . 4 . . .
4 4 . . . .
4 . . . . .
. . . . . .
. . . . . .

Cell (3, 0) conflicts with its upper neighbour (2, 0) but the conflict with its diagonal predecessor (2, 1) will be found earlier in the process.

All this takes the left-most column completely out of the picture, leaving 5 columns where each cell could be the first point of detecting a conflict, and hence we have exactly 30 distinct failure modes.

However, in order to flush out buggy solutions based on frequency counting approaches it makes sense to pick at least one mid-to-latish failure case and vary the make-up of the matrix before the run of values that causes the failure (at least the two cases with most and least number of distinct values).

The good tests should include - among others - all the failure cases with the length of the failure run shortened by one.

79825842
Vote

Indeed. And the continue in the following code excerpt:

                for (Map.Entry<Integer, Long> entry : freq.entrySet()) {
                    int val = entry.getKey();
                    long count = entry.getValue();
                    if (!exempt.contains(val) && count > 6) {
                        System.out.println("Set " + setIndex + ": Impossible\n");
                        impossibleCount++;
                        setIndex++;
                        continue;
                    }
                }

probabbly does not do what you think it does (it skips to the next Map.Entry)

79818516
Vote

So, I decided to make the 6×6 descending grid sorter using HTML, CSS, and JavaScript, because apparently I enjoy using the wrong language for my projects.

Math & Logic
Five quick Khan Academy lessons later, and I know that, formally, for a 6x6 grid (G), we need:

Gᵢⱼ > Gᵢ,ⱼ₊₁ ∀ i ∈ [1,6], j ∈ [1,5]

Gᵢⱼ > Gᵢ₊₁,ⱼ ∀ j ∈ [1,6], i ∈ [1,5]

We first check if the grid is solvable by comparing the length of diagonals and the longest amount of identical numbers, because what's the point in trying to solve something you can't?

Then, the solver sorts the dataset in descending order: D = {x1,x2... x36}. So that D1= sort(D, desc)

UX
Each dataset’s result is rendered as a colored card with the result, and a progress bar shows how far the solver has made it through the 100 datasets.
The actual computation is done inside a web worker, which allows the browser to use more than one thread for JS execution, so that it a) goes faster and b) doesn't max out the thread with computations and freeze up the UI.

Here's the code:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>6x6 Solver SO Challenge</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg,#6a11cb,#2575fc);
            color: #fff;
            padding: 40px;
            min-height: 100vh;
            margin: 0;
        }

        #progress {
            width: 100%;
            height: 20px;
            background: rgba(255,255,255,0.2);
            border-radius: 10px;
            overflow: hidden;
            margin-bottom: 30px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }

        #progress-bar {
            width: 0;
            height: 100%;
            background: linear-gradient(90deg, #ff8a00, #e52e71);
            transition: width 0.4s ease;
        }

        #results {
            display: grid;
            gap: 20px;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        }

        .status {
            background: rgba(255,255,255,0.1);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            padding: 20px;
            transition: transform 0.3s, box-shadow 0.3s;
            box-shadow: 0 8px 25px rgba(0,0,0,0.3);
        }

        .status.ok {
            border-left: 6px solid #00ff88;
        }

        .status.fail {
            border-left: 6px solid #ff4c4c;
        }

        .status:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 30px rgba(0,0,0,0.4);
        }

        h3 {
            margin: 0 0 10px;
            font-weight: 600;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }

        td {
            border: 1px solid rgba(255,255,255,0.3);
            padding: 6px 0;
            text-align: center;
            font-weight: 500;
            color: #fff;
        }

        .summary {
            grid-column: 1/-1;
            text-align: center;
            font-size: 1.2rem;
            font-weight: 600;
            margin-top: 20px;
        }
    </style>
</head>
<body>

<div id="progress"><div id="progress-bar"></div></div>
<div id="results"></div>

<script>
    const datasets = [
        [54, 95, 98, 26, 3, 39, 77, 30, 83, 62, 20, 92, 61, 59, 26, 63, 92, 49, 38, 51, 99, 64, 65, 52, 98, 18, 90, 97, 96, 13, 74, 3, 88, 88, 67, 10],
        [49, 13, 73, 54, 4, 98, 36, 33, 12, 22, 35, 18, 39, 83, 92, 77, 50, 77, 57, 64, 0, 35, 86, 98, 28, 1, 53, 59, 28, 33, 56, 37, 98, 26, 81, 13],
        [95, 84, 44, 16, 42, 73, 0, 53, 14, 63, 81, 91, 42, 14, 13, 59, 91, 24, 99, 71, 73, 34, 60, 65, 82, 55, 16, 75, 7, 18, 68, 6, 61, 6, 80, 41],
        [27, 63, 35, 81, 56, 24, 70, 27, 59, 13, 36, 62, 73, 6, 61, 86, 48, 40, 88, 71, 52, 1, 9, 57, 50, 40, 20, 10, 3, 29, 19, 94, 99, 8, 74, 83],
        [46, 75, 78, 14, 89, 76, 37, 26, 85, 78, 81, 27, 99, 41, 96, 52, 21, 65, 71, 48, 60, 32, 48, 31, 85, 35, 88, 5, 78, 22, 31, 97, 43, 80, 52, 45],
        [0, 98, 50, 12, 0, 83, 46, 66, 67, 23, 52, 55, 41, 95, 5, 17, 78, 98, 74, 45, 97, 98, 96, 54, 48, 79, 29, 0, 73, 6, 16, 33, 20, 88, 9, 23],
        [9, 2, 10, 57, 79, 65, 65, 0, 19, 64, 3, 18, 20, 93, 10, 30, 9, 0, 40, 51, 87, 34, 52, 71, 28, 23, 73, 61, 77, 60, 66, 91, 57, 58, 2, 9],
        [27, 63, 51, 6, 3, 10, 7, 36, 80, 51, 93, 71, 73, 25, 3, 77, 35, 56, 36, 36, 77, 97, 14, 1, 78, 83, 5, 51, 99, 5, 93, 90, 1, 36, 83, 4],
        [89, 94, 67, 64, 31, 66, 59, 16, 80, 22, 78, 72, 56, 83, 98, 10, 9, 57, 23, 4, 80, 37, 65, 30, 71, 55, 42, 9, 60, 18, 39, 58, 44, 79, 48, 29],
        [79, 51, 3, 82, 81, 58, 99, 88, 54, 88, 81, 5, 63, 79, 52, 64, 48, 64, 68, 11, 50, 66, 35, 71, 9, 86, 11, 97, 42, 41, 0, 2, 56, 38, 15, 63],
        [94, 35, 12, 94, 79, 40, 91, 45, 37, 98, 43, 30, 80, 81, 87, 19, 74, 87, 93, 35, 88, 89, 79, 44, 6, 87, 27, 49, 98, 44, 68, 39, 42, 87, 61, 84],
        [5, 37, 89, 80, 31, 40, 1, 10, 54, 67, 23, 1, 75, 43, 49, 27, 29, 69, 43, 41, 7, 16, 63, 70, 5, 61, 74, 87, 2, 61, 50, 72, 91, 56, 12, 99],
        [43, 35, 83, 94, 69, 45, 76, 73, 83, 60, 80, 31, 59, 34, 39, 63, 35, 13, 94, 78, 2, 24, 87, 21, 36, 38, 55, 19, 10, 82, 13, 95, 88, 54, 94, 75],
        [66, 10, 58, 21, 82, 10, 32, 91, 66, 65, 3, 12, 4, 38, 12, 96, 55, 54, 73, 16, 74, 41, 28, 49, 19, 98, 16, 90, 93, 82, 56, 68, 14, 70, 31, 19],
        [13, 79, 47, 31, 79, 31, 56, 65, 94, 73, 57, 35, 74, 85, 84, 39, 24, 26, 12, 56, 46, 46, 71, 0, 57, 61, 77, 32, 14, 1, 81, 71, 69, 66, 57, 69],
        [8, 39, 23, 14, 88, 44, 81, 46, 5, 26, 50, 11, 71, 19, 86, 33, 88, 62, 81, 13, 60, 96, 7, 78, 6, 88, 77, 94, 74, 63, 48, 40, 29, 47, 64, 6],
        [95, 36, 61, 3, 75, 84, 95, 8, 57, 42, 43, 77, 27, 65, 56, 78, 34, 96, 18, 23, 46, 17, 86, 17, 89, 28, 96, 18, 24, 90, 93, 49, 47, 69, 91, 48],
        [76, 95, 10, 10, 58, 67, 25, 41, 0, 49, 13, 40, 59, 29, 62, 64, 97, 47, 22, 42, 39, 44, 16, 95, 23, 91, 14, 48, 90, 39, 16, 92, 46, 38, 49, 16],
        [60, 42, 28, 28, 61, 10, 37, 90, 99, 9, 45, 15, 61, 20, 6, 89, 99, 5, 34, 28, 58, 45, 10, 43, 73, 5, 45, 78, 68, 48, 44, 56, 78, 69, 52, 99],
        [99, 92, 63, 87, 23, 73, 25, 25, 31, 97, 14, 12, 77, 96, 73, 80, 86, 15, 63, 71, 44, 34, 51, 28, 77, 24, 19, 74, 87, 34, 59, 40, 82, 13, 25, 15],
        [48, 59, 63, 45, 51, 64, 88, 99, 81, 29, 69, 27, 7, 28, 9, 77, 50, 80, 7, 64, 3, 24, 6, 22, 31, 69, 92, 66, 13, 3, 70, 81, 73, 50, 45, 42],
        [0, 49, 29, 50, 38, 38, 24, 71, 8, 5, 56, 6, 90, 2, 3, 35, 40, 89, 24, 27, 74, 77, 54, 7, 1, 76, 92, 16, 55, 23, 47, 62, 33, 1, 80, 47],
        [1, 61, 12, 89, 56, 47, 88, 63, 73, 49, 9, 78, 68, 69, 19, 53, 76, 39, 49, 83, 38, 70, 62, 79, 19, 7, 70, 4, 90, 57, 90, 20, 52, 37, 64, 17],
        [0, 99, 18, 20, 0, 5, 93, 66, 87, 4, 62, 47, 94, 27, 73, 82, 12, 37, 39, 63, 59, 71, 71, 36, 84, 53, 90, 93, 9, 21, 94, 76, 80, 4, 40, 30],
        [57, 17, 99, 26, 7, 0, 81, 29, 95, 51, 46, 8, 16, 19, 15, 48, 89, 65, 69, 14, 94, 9, 3, 78, 59, 20, 41, 45, 97, 99, 57, 52, 94, 12, 55, 28],
        [19, 49, 58, 20, 73, 65, 0, 72, 82, 12, 64, 43, 34, 58, 11, 74, 20, 75, 0, 23, 6, 25, 81, 39, 44, 65, 54, 57, 72, 72, 10, 69, 31, 10, 45, 20],
        [68, 46, 13, 68, 81, 62, 28, 75, 66, 91, 27, 31, 20, 38, 1, 45, 76, 79, 14, 62, 58, 66, 17, 79, 61, 91, 86, 33, 57, 95, 74, 7, 31, 85, 97, 80],
        [67, 31, 55, 44, 11, 39, 50, 79, 64, 75, 97, 13, 22, 19, 42, 58, 55, 10, 51, 37, 73, 55, 22, 40, 35, 97, 77, 92, 43, 24, 69, 25, 64, 61, 48, 77],
        [7, 17, 84, 29, 87, 12, 85, 22, 65, 70, 73, 14, 32, 9, 27, 3, 11, 42, 88, 20, 37, 10, 88, 77, 68, 92, 71, 80, 83, 32, 35, 85, 91, 52, 26, 73],
        [62, 24, 97, 27, 49, 2, 50, 36, 14, 59, 63, 1, 45, 98, 80, 64, 59, 80, 55, 96, 87, 89, 19, 81, 40, 31, 73, 48, 29, 34, 63, 11, 12, 7, 84, 28],
        [23, 82, 3, 66, 59, 65, 49, 80, 16, 73, 39, 69, 45, 15, 6, 14, 4, 97, 76, 57, 34, 13, 77, 72, 98, 24, 34, 54, 23, 41, 67, 6, 80, 19, 30, 92],
        [20, 35, 58, 63, 21, 75, 58, 8, 30, 44, 97, 21, 3, 86, 78, 89, 93, 42, 29, 89, 53, 17, 89, 6, 8, 14, 48, 98, 15, 58, 28, 46, 51, 55, 17, 78],
        [42, 41, 8, 12, 37, 81, 33, 58, 59, 31, 3, 67, 77, 90, 6, 2, 14, 45, 49, 28, 79, 93, 7, 75, 52, 52, 46, 86, 98, 77, 66, 38, 41, 11, 41, 2],
        [8, 45, 28, 85, 58, 99, 18, 86, 95, 16, 59, 45, 26, 35, 36, 96, 61, 82, 32, 20, 62, 47, 93, 3, 44, 71, 11, 11, 31, 28, 42, 7, 18, 58, 40, 89],
        [87, 4, 99, 46, 73, 27, 7, 44, 26, 62, 15, 10, 14, 77, 97, 70, 58, 23, 85, 73, 76, 97, 6, 92, 52, 51, 9, 84, 29, 56, 15, 38, 41, 7, 88, 76],
        [30, 0, 80, 70, 10, 78, 91, 80, 3, 42, 24, 70, 39, 7, 7, 43, 9, 2, 23, 96, 76, 87, 19, 11, 5, 10, 74, 10, 49, 16, 34, 54, 40, 55, 75, 93],
        [92, 54, 58, 53, 99, 84, 53, 50, 56, 65, 10, 89, 19, 2, 6, 94, 44, 69, 67, 60, 79, 5, 30, 23, 15, 8, 48, 26, 32, 31, 43, 59, 81, 9, 67, 93],
        [7, 58, 97, 4, 22, 36, 5, 83, 32, 69, 83, 54, 18, 48, 49, 43, 36, 37, 96, 0, 28, 18, 64, 56, 52, 97, 43, 95, 36, 8, 48, 35, 60, 41, 48, 81],
        [50, 78, 66, 51, 45, 80, 65, 87, 0, 5, 87, 91, 34, 78, 47, 89, 51, 32, 88, 64, 52, 8, 86, 59, 11, 5, 1, 12, 57, 87, 75, 83, 17, 69, 96, 61],
        [74, 18, 35, 33, 97, 4, 22, 39, 41, 10, 66, 59, 11, 71, 90, 28, 78, 66, 51, 25, 48, 89, 74, 62, 13, 19, 67, 99, 19, 88, 15, 83, 26, 86, 31, 93],
        [93, 32, 27, 13, 61, 53, 49, 35, 59, 13, 54, 68, 75, 31, 18, 79, 33, 59, 87, 86, 14, 26, 21, 19, 12, 59, 75, 36, 7, 71, 25, 25, 6, 85, 29, 99],
        [94, 78, 11, 70, 49, 22, 25, 67, 34, 65, 85, 58, 76, 10, 44, 22, 75, 72, 65, 54, 68, 60, 84, 52, 19, 26, 61, 69, 88, 76, 37, 41, 81, 1, 23, 57],
        [15, 72, 24, 37, 95, 16, 76, 61, 34, 47, 68, 93, 18, 92, 32, 17, 20, 66, 51, 33, 65, 38, 71, 45, 81, 59, 34, 35, 84, 37, 14, 6, 41, 60, 57, 54],
        [83, 86, 73, 77, 75, 67, 5, 92, 43, 13, 98, 92, 69, 80, 50, 25, 64, 0, 64, 25, 98, 40, 66, 77, 4, 18, 52, 50, 28, 36, 17, 54, 5, 83, 2, 40],
        [25, 68, 57, 61, 55, 81, 56, 71, 95, 72, 37, 21, 91, 8, 23, 26, 38, 44, 45, 84, 37, 51, 13, 42, 90, 12, 67, 21, 96, 31, 99, 97, 2, 90, 99, 56],
        [47, 90, 19, 59, 82, 32, 52, 99, 74, 8, 93, 18, 79, 22, 24, 63, 84, 50, 55, 86, 94, 23, 83, 65, 67, 48, 16, 15, 81, 78, 7, 43, 12, 52, 58, 28],
        [54, 39, 86, 53, 24, 55, 72, 2, 6, 15, 78, 8, 35, 70, 59, 80, 74, 99, 95, 32, 44, 26, 47, 49, 48, 14, 95, 66, 54, 76, 37, 81, 85, 37, 45, 7],
        [19, 38, 6, 31, 71, 53, 40, 85, 71, 52, 56, 25, 78, 32, 17, 85, 42, 24, 61, 42, 3, 54, 98, 68, 48, 39, 59, 59, 12, 25, 96, 98, 15, 88, 44, 45],
        [62, 70, 19, 57, 56, 68, 7, 13, 53, 87, 68, 69, 77, 39, 23, 94, 42, 10, 1, 28, 43, 31, 42, 48, 75, 95, 28, 10, 44, 50, 72, 47, 64, 96, 5, 63],
        [92, 85, 77, 92, 90, 27, 39, 57, 51, 41, 99, 78, 78, 53, 88, 59, 30, 65, 15, 25, 32, 32, 99, 64, 90, 40, 13, 45, 41, 73, 98, 12, 44, 73, 33, 32],
        [97, 36, 97, 58, 74, 56, 70, 80, 92, 84, 93, 16, 0, 34, 96, 85, 84, 16, 29, 22, 27, 42, 26, 40, 27, 80, 1, 40, 82, 25, 54, 31, 77, 25, 67, 73],
        [46, 91, 13, 50, 65, 68, 44, 15, 65, 58, 77, 21, 92, 70, 69, 95, 9, 84, 69, 71, 53, 65, 0, 33, 95, 4, 1, 28, 62, 27, 39, 38, 47, 39, 61, 81],
        [37, 0, 70, 66, 14, 20, 50, 68, 8, 0, 62, 41, 68, 35, 14, 69, 94, 62, 53, 84, 32, 22, 80, 81, 22, 66, 36, 65, 40, 53, 93, 0, 0, 33, 32, 7],
        [68, 73, 37, 13, 86, 20, 22, 97, 27, 10, 32, 57, 27, 11, 52, 7, 7, 48, 23, 14, 98, 25, 41, 6, 78, 63, 80, 38, 24, 75, 2, 61, 45, 93, 18, 94],
        [20, 14, 76, 73, 80, 30, 56, 33, 80, 18, 79, 66, 39, 3, 88, 25, 28, 24, 63, 88, 68, 28, 67, 49, 6, 18, 4, 49, 0, 96, 11, 22, 6, 41, 17, 50],
        [9, 61, 45, 7, 25, 86, 99, 39, 79, 13, 46, 74, 44, 3, 90, 43, 25, 9, 2, 27, 13, 15, 38, 98, 2, 88, 13, 51, 44, 80, 67, 85, 84, 40, 2, 68],
        [22, 48, 11, 46, 99, 88, 75, 32, 69, 66, 73, 10, 3, 31, 13, 44, 11, 17, 68, 0, 37, 86, 40, 92, 13, 61, 24, 69, 22, 11, 53, 1, 14, 53, 96, 29],
        [65, 27, 91, 56, 76, 11, 86, 34, 3, 15, 97, 42, 19, 98, 38, 78, 90, 37, 76, 55, 46, 18, 72, 92, 3, 38, 55, 54, 5, 0, 58, 24, 77, 70, 65, 55],
        [33, 48, 21, 34, 42, 60, 82, 33, 98, 27, 51, 33, 74, 55, 59, 96, 44, 35, 23, 28, 13, 52, 72, 9, 39, 52, 8, 30, 40, 8, 97, 43, 79, 89, 38, 80],
        [1, 29, 67, 37, 13, 29, 33, 96, 91, 24, 4, 67, 20, 71, 75, 95, 2, 63, 39, 14, 88, 2, 5, 17, 38, 40, 74, 79, 39, 62, 38, 58, 74, 4, 27, 97],
        [86, 8, 5, 54, 58, 78, 70, 51, 89, 94, 51, 55, 27, 6, 56, 44, 14, 72, 5, 27, 19, 50, 72, 58, 66, 24, 49, 28, 15, 12, 12, 37, 85, 89, 53, 38],
        [54, 1, 82, 23, 72, 55, 6, 96, 54, 22, 19, 63, 83, 50, 39, 75, 33, 29, 83, 14, 60, 92, 62, 83, 11, 34, 53, 77, 57, 63, 18, 17, 50, 9, 90, 36],
        [60, 78, 25, 81, 18, 1, 96, 39, 36, 82, 23, 78, 70, 80, 19, 55, 74, 38, 99, 37, 3, 87, 21, 26, 93, 89, 44, 13, 95, 92, 11, 71, 77, 10, 49, 90],
        [68, 68, 45, 82, 67, 7, 97, 49, 87, 83, 73, 70, 70, 87, 14, 37, 10, 21, 82, 71, 75, 13, 89, 93, 63, 11, 40, 18, 32, 69, 38, 53, 81, 63, 51, 76],
        [25, 36, 27, 62, 4, 51, 50, 74, 19, 10, 78, 94, 15, 49, 11, 26, 91, 80, 61, 80, 84, 87, 80, 52, 35, 28, 64, 91, 39, 58, 15, 55, 26, 72, 68, 35],
        [42, 66, 36, 17, 5, 31, 38, 90, 61, 8, 24, 0, 7, 40, 65, 67, 54, 61, 53, 16, 49, 76, 21, 63, 23, 72, 20, 9, 42, 34, 10, 6, 63, 25, 61, 28],
        [9, 98, 52, 95, 85, 61, 87, 96, 64, 98, 98, 83, 88, 4, 73, 29, 26, 67, 59, 34, 89, 49, 6, 16, 0, 61, 55, 76, 73, 64, 26, 63, 56, 64, 66, 86],
        [98, 2, 10, 34, 9, 10, 8, 46, 2, 95, 89, 65, 49, 1, 38, 15, 8, 22, 66, 80, 7, 77, 77, 70, 1, 7, 60, 59, 93, 7, 2, 98, 31, 95, 87, 18],
        [47, 20, 77, 92, 92, 78, 81, 7, 34, 20, 30, 40, 56, 79, 86, 84, 81, 40, 19, 28, 72, 35, 20, 85, 3, 68, 18, 4, 63, 83, 20, 12, 41, 63, 19, 58],
        [55, 10, 67, 18, 31, 16, 76, 57, 79, 64, 68, 37, 78, 60, 60, 46, 49, 32, 32, 3, 65, 74, 22, 79, 26, 29, 28, 86, 20, 99, 27, 99, 28, 30, 54, 20],
        [73, 87, 66, 32, 10, 75, 40, 94, 30, 99, 52, 10, 33, 33, 52, 36, 16, 90, 68, 62, 19, 33, 50, 22, 78, 47, 91, 22, 84, 83, 41, 17, 32, 83, 38, 23],
        [82, 26, 41, 53, 71, 22, 95, 55, 60, 14, 40, 42, 36, 43, 91, 50, 16, 93, 62, 72, 3, 14, 55, 48, 20, 17, 56, 38, 64, 87, 86, 92, 82, 75, 73, 76],
        [70, 18, 42, 41, 19, 44, 8, 90, 10, 73, 41, 39, 23, 69, 64, 55, 39, 80, 88, 13, 5, 29, 71, 53, 84, 71, 91, 97, 60, 67, 10, 15, 53, 37, 68, 91],
        [12, 99, 93, 43, 63, 51, 54, 89, 39, 8, 19, 27, 70, 94, 0, 70, 76, 1, 51, 30, 60, 88, 24, 69, 35, 36, 97, 43, 0, 70, 21, 84, 19, 6, 93, 92],
        [15, 83, 14, 61, 0, 18, 77, 34, 95, 92, 22, 76, 54, 9, 22, 43, 96, 91, 24, 12, 30, 22, 88, 72, 82, 38, 27, 10, 41, 2, 78, 25, 36, 20, 70, 55],
        [83, 6, 84, 58, 57, 42, 76, 75, 36, 39, 98, 55, 72, 72, 84, 81, 36, 9, 3, 44, 1, 50, 63, 1, 93, 24, 26, 20, 30, 68, 0, 24, 90, 26, 6, 88],
        [58, 38, 65, 42, 40, 25, 32, 39, 19, 31, 74, 36, 85, 74, 23, 20, 37, 41, 41, 63, 61, 9, 27, 39, 22, 0, 36, 34, 53, 53, 6, 40, 81, 18, 86, 8],
        [34, 1, 53, 24, 53, 46, 21, 59, 74, 75, 10, 49, 79, 74, 29, 68, 82, 75, 49, 62, 8, 58, 54, 34, 87, 4, 84, 34, 10, 82, 70, 35, 62, 9, 33, 77],
        [28, 49, 3, 98, 69, 36, 80, 53, 72, 68, 89, 22, 40, 52, 5, 66, 39, 38, 41, 45, 13, 12, 70, 12, 7, 86, 95, 83, 66, 92, 43, 13, 53, 80, 75, 33],
        [98, 98, 88, 3, 11, 32, 83, 24, 91, 79, 3, 55, 50, 95, 41, 69, 30, 89, 68, 47, 13, 35, 0, 86, 57, 8, 10, 31, 1, 40, 81, 2, 87, 10, 73, 0],
        [36, 8, 65, 86, 88, 65, 19, 33, 62, 24, 98, 34, 0, 80, 45, 53, 16, 28, 41, 65, 93, 34, 64, 85, 48, 98, 15, 51, 41, 65, 5, 9, 51, 17, 17, 91],
        [21, 49, 80, 99, 8, 32, 11, 36, 82, 59, 64, 59, 55, 73, 1, 23, 82, 59, 19, 16, 58, 18, 62, 36, 74, 30, 72, 79, 26, 31, 16, 40, 2, 27, 65, 26],
        [86, 24, 59, 75, 93, 17, 20, 42, 21, 4, 80, 0, 57, 91, 81, 84, 95, 13, 65, 85, 9, 15, 26, 90, 66, 20, 13, 98, 67, 27, 85, 49, 45, 65, 10, 84],
        [17, 16, 99, 46, 21, 66, 57, 69, 29, 42, 50, 92, 9, 11, 56, 62, 32, 15, 55, 25, 55, 90, 81, 74, 62, 98, 58, 65, 46, 77, 53, 10, 0, 59, 70, 91],
        [76, 89, 89, 89, 87, 87, 11, 51, 11, 44, 11, 50, 29, 88, 93, 31, 6, 26, 74, 34, 24, 30, 14, 74, 9, 47, 20, 17, 88, 14, 49, 87, 3, 65, 27, 73],
        [18, 18, 68, 23, 13, 98, 52, 92, 72, 75, 8, 8, 2, 33, 69, 23, 22, 16, 95, 76, 43, 83, 86, 27, 4, 58, 57, 97, 64, 22, 43, 32, 41, 2, 88, 26],
        [21, 20, 85, 29, 56, 31, 65, 45, 58, 26, 62, 21, 71, 31, 5, 57, 88, 42, 51, 39, 79, 83, 47, 99, 25, 31, 9, 24, 13, 63, 95, 78, 80, 74, 78, 89],
        [39, 90, 68, 22, 85, 14, 4, 20, 41, 51, 67, 75, 20, 48, 91, 65, 61, 44, 66, 3, 83, 30, 93, 23, 19, 99, 46, 88, 87, 35, 3, 88, 35, 67, 88, 28],
        [63, 21, 64, 10, 7, 38, 25, 17, 32, 36, 7, 99, 46, 65, 74, 71, 63, 42, 30, 72, 29, 80, 42, 65, 27, 24, 16, 16, 70, 2, 54, 60, 35, 79, 88, 39],
        [10, 75, 23, 44, 33, 33, 11, 13, 23, 3, 44, 37, 64, 66, 35, 32, 34, 22, 18, 15, 6, 37, 25, 36, 20, 4, 49, 58, 59, 21, 80, 95, 0, 31, 93, 28],
        [54, 30, 99, 86, 7, 38, 8, 18, 26, 83, 15, 83, 45, 5, 24, 67, 6, 39, 65, 67, 83, 99, 29, 41, 64, 62, 25, 53, 54, 34, 24, 41, 99, 28, 8, 29],
        [30, 60, 67, 20, 43, 56, 79, 43, 92, 85, 69, 9, 62, 22, 62, 24, 68, 33, 18, 61, 25, 14, 21, 59, 86, 59, 53, 26, 1, 80, 9, 36, 4, 5, 85, 47],
        [57, 64, 8, 17, 69, 23, 77, 29, 69, 52, 80, 86, 18, 93, 78, 17, 36, 60, 94, 25, 80, 90, 87, 86, 64, 23, 87, 95, 19, 69, 91, 82, 37, 27, 27, 46],
        [52, 19, 54, 87, 1, 4, 41, 68, 93, 56, 36, 13, 32, 25, 83, 48, 59, 5, 37, 58, 83, 93, 53, 77, 44, 63, 49, 1, 94, 4, 28, 30, 85, 15, 85, 90],
        [75, 72, 89, 33, 98, 23, 81, 41, 35, 17, 4, 1, 46, 60, 83, 69, 27, 35, 33, 83, 61, 61, 21, 72, 82, 72, 82, 6, 59, 51, 60, 37, 82, 20, 88, 54],
        [20, 37, 13, 75, 81, 78, 36, 75, 22, 45, 81, 63, 58, 72, 81, 7, 9, 39, 49, 8, 84, 66, 71, 58, 41, 56, 5, 2, 83, 47, 16, 3, 93, 95, 97, 10],
        [94, 83, 74, 92, 8, 10, 12, 92, 28, 28, 31, 98, 10, 33, 62, 70, 85, 53, 8, 31, 75, 67, 38, 2, 5, 85, 44, 25, 54, 69, 33, 61, 75, 57, 79, 82],
        [60, 34, 79, 9, 2, 28, 80, 24, 2, 76, 26, 34, 61, 22, 40, 31, 52, 14, 30, 2, 88, 54, 41, 73, 6, 45, 13, 22, 70, 51, 74, 69, 19, 66, 33, 78],
        [3, 11, 50, 41, 23, 41, 45, 2, 62, 95, 55, 73, 1, 98, 33, 68, 82, 96, 24, 81, 1, 58, 59, 41, 45, 9, 99, 49, 16, 97, 54, 75, 92, 14, 71, 63],
        [18, 73, 63, 61, 88, 15, 27, 49, 82, 95, 0, 54, 71, 76, 64, 65, 84, 39, 61, 56, 52, 60, 88, 92, 75, 83, 94, 61, 76, 76, 14, 11, 5, 95, 71, 68]
    ];
    const bar = document.getElementById('progress-bar');
    const resultsDiv = document.getElementById('results');

    let impossibleCount = 0;
    let completed = 0;

    datasets.forEach((arr, i) => {
        const wrapper = document.createElement('div');
        wrapper.className = 'status';
        wrapper.textContent = `Set #${i + 1}: Queued...`;
        resultsDiv.appendChild(wrapper);
    });

    function isVS(numbers) {
        const sorted = [...numbers].sort((a, b) => b - a); // Sort descending
        const size = Math.sqrt(sorted.length);

        if (size !== Math.floor(size)) {
            return { ok: false, reason: "Invalid array length" }; //if this happens again check commas in array
        }

        const diagonals = [];
        for (let n = 1; n <= size; n++) {
            for (let k = 0; k < n; k++) {
                diagonals.push(n);
            }
        }
        for (let n = size - 1; n >= 1; n--) {
            for (let k = 0; k < n; k++) {
                diagonals.push(n);
            }
        }

        let runValue = sorted[0];
        let runLength = 1;
        let runMax = diagonals[0];

        for (let i = 1; i < sorted.length; i++) {
            if (sorted[i] === runValue) {
                runLength += 1;
                runMax = Math.min(diagonals[i], runMax);
                if (runLength > runMax) {
                    return { ok: false, reason: "Duplicate run overlaps" };
                }
            } else {
                runValue = sorted[i];
                runLength = 1;
                runMax = diagonals[i];
            }
        }
        return { ok: true, reason: "Solvable!" };
    }

    function glg(size) {
        const lookups = Array.from({ length: size }, () => Array(size).fill(0));
        let i = 0;
        for (let j = 0; j < (2 * size - 1); j++) {
            for (let row = 0; row < size; row++) {
                const col = j - row;
                if ((col >= 0) && (col < size)) {
                    lookups[row][col] = i;
                    i++;
                }
            }
        }
        return lookups;
    }

    function arrangeGridJS(values) {
        const sorted = [...values].sort((a, b) => b - a); 
        const size = Math.sqrt(sorted.length);
        const layout = glg(size); 
        const grid = Array.from({ length: size }, () => Array(size).fill(0));

        for (let row = 0; row < size; row++) {
            for (let col = 0; col < size; col++) {
                grid[row][col] = sorted[layout[row][col]];
            }
        }
        return grid;
    }
    function hasAdjacentValuesJS(grid) {
        const rows = grid.length;
        const cols = grid[0].length;

        for (let row = 0; row < rows; row++) {
            for (let col = 0; col < cols; col++) {
                if (col < (cols - 1) && grid[row][col] === grid[row][col + 1]) {
                    return true;
                }
                if (row < (rows - 1) && grid[row][col] === grid[row + 1][col]) {
                    return true;
                }
            }
        }
        return false;
    }


    (async () => {
        for (let i = 0; i < datasets.length; i++) {
            const arr = datasets[i];
            const validationResult = isVS(arr); 

            const wrapper = resultsDiv.children[i];
            wrapper.innerHTML = ""; 

            if (validationResult.ok) {
                const solvedGrid = arrangeGridJS(arr);
                const hasAdj = hasAdjacentValuesJS(solvedGrid);

                if (!hasAdj) {
                    wrapper.classList.add('ok');
                    let html = `<h3>Set #${i + 1}</h3><table>`;
                    for (let r = 0; r < solvedGrid.length; r++) {
                        html += '<tr>' + solvedGrid[r].map(v => `<td>${v}</td>`).join('') + '</tr>';
                    }
                    html += `</table><div>Solved by C# heuristic</div>`;
                    wrapper.innerHTML = html;
                } else {
                    wrapper.classList.add('fail');
                    wrapper.innerHTML = `<h3>Set #${i + 1}</h3><div>ERROR: Heuristic said solvable but arrangement has adjacent duplicates! Fix your math stupid programmer.</div>`;
                    impossibleCount++;
                }

            } else {
                wrapper.classList.add('fail');
                wrapper.innerHTML = `<h3>Set #${i + 1}</h3><div>Impossible (${validationResult.reason})</div>`;
                impossibleCount++;
            }

            completed++;
            bar.style.width = (completed / datasets.length * 100) + '%';

            await new Promise(r => setTimeout(r, 10));
        }

        if (completed === datasets.length) {
            const summary = document.createElement('div');
            summary.className = 'summary';
            summary.textContent = `Total Impossible: ${impossibleCount} / ${datasets.length}`;
            resultsDiv.appendChild(summary);
        }
    })();
</script>

</body>
</html>

With that, I got a total impossible count of 45/100.

Hopefully I didn't miss any.

Thanks for the challenge everyone 😀.

79818452
Vote
def is_sortable(grid):
    flat_list = [num for row in grid for num in row]
    
    sorted_list = sorted(flat_list)
    
    sorted_grid = [sorted_list[i:i+6] for i in range(0, len(sorted_list), 6)]
    
    for row in sorted_grid:
        if row != sorted(row):  # Check if each row is sorted
            return "impossible"
    
    return sorted_grid

grid = [
    [95, 75, 74],
    [75, 74, 74],
    [54, 74, 45]
]

result = is_sortable(grid)
print(result)  
79818362
Vote
from functools import cache

ROWS, COLS  = 6, 6


def read_array_from_file(path):
    numbers = []
    with open(path, 'r') as f:
        for line in f:
            numbers.append(eval(line.strip()))
    return numbers


def sort_grid(numbers):
    sorted_nums = sorted(numbers, reverse=True)
    
    '''
    For a valid grid with strict descending rows and columns:
        The largest number must be in position [0][0]
        Position [i][j] must be less than positions [i][j-1] and [i-1][j]
    '''

    grid = [[None] * COLS for _ in range(ROWS)]

    '''
    Fill row by row, ensuring each position is:
        1. Less than the element to its left (if exists)
        2. Less than the element above it (if exists)
    '''

    # Use backtracking
    def can_place(grid, row, col, val):
        if col > 0 and grid[row][col-1] <= val:
            return False
        if row > 0 and grid[row-1][col] <= val:
            return False
        return True
    
    @cache
    def solve(pos, remaining):
        if pos == ROWS * COLS:
            return True

        row, col = pos // COLS, pos % COLS
        
        for i, num in enumerate(remaining):
            if can_place(grid, row, col, num):
                grid[row][col] = num
                if solve(pos + 1, tuple(list(remaining)[:i] + list(remaining)[i+1:])):
                    return True
                grid[row][col] = None
        
        return False

    if solve(0, tuple(sorted_nums)):
        return grid
    else:
        return 'Impossible'


if __name__ == "__main__":
    for array in read_array_from_file('RandomNumbers.txt'):
        grid = sort_grid(array)
        print(grid)
79819748
Vote

Did you try running your program yet?

I did try same algorithm like this one. it's extremely slow half hour pass still not finish the first test data (unsolvable) yet. (I also try with solvable data, It's work.)

79818339
Vote
"""
Challenge #13: Integer sorting in a grid
https://stackoverflow.com/beta/challenges/79811869/challenge-13-integer-sorting-in-a-grid
Answer Impossible: 45
After looking at how grids need to be sorted to optimize fitting
numbers in the grid, I took the approach of obviously the largest
value needs to be top left, then the next can largest needs to be
either one right or one down from that, and to get the 3rd largest
to not conflict it needs to be the other position, etc.
So after sorting in desc I follow the coordinates order (for size 6) of
[(0, 0),
 (1, 0), (0, 1),
 (2, 0), (1, 1), (0, 2),
 (3, 0), (2, 1), (1, 2), (0, 3),
 (4, 0), (3, 1), (2, 2), (1, 3), (0, 4),
 (5, 0), (4, 1), (3, 2), (2, 3), (1, 4), (0, 5),
 (5, 1), (4, 2), (3, 3), (2, 4), (1, 5),
 (5, 2), (4, 3), (3, 4), (2, 5),
 (5, 3), (4, 4), (3, 5),
 (5, 4), (4, 5),
 (5, 5)]
Then I just test if the grid follows the rule of strictly descending.
 I did check failing grids to see if my approach held, honestly almost all the failing grids
 had a duplicate max value or min value (which obviously fails)
"""
import math


def perfect_square(num):
    if num < 0:
        return 0
    edge = math.isqrt(num)
    if edge * edge == num:
        return edge
    return 0


def distance(cord):
    # to sort cords by diagonal stripes
    x, y = cord
    return (x+y, y)


def get_cords_by_distance(size):
    # TODO: probably could do a combination thing here instead
    points = [(x, y) for y in range(size) for x in range(size)]
    points.sort(key=distance)
    return points


def sort_grid(numbers):
    size = perfect_square(len(numbers))
    if not size:
        print(f"Perfect Square is required, you gave {len(numbers)} numbers")
        return
    grid = [[None] * size for _ in range(size)]
    # print(grid)
    position_to_coordinates = get_cords_by_distance(size)
    # print("pos_to_cord:", position_to_coordinates)
    for pos, value in enumerate(sorted(numbers, reverse=True)):
        x, y = position_to_coordinates[pos]
        grid[y][x] = value
    return grid


def display_grid(grid):
    width = len(str(grid[0][0]))
    for row in grid:
        print('  '.join(f"{num: >{width}}" for num in row))


def valid_row(row):
    # row is valid if no duplicates and is in descing order
    return len(row) == len(set(row)) and row == list(sorted(row, reverse=True))


def valid_grid(grid):
    if not grid:
        return False
    for row in grid:
        if not valid_row(row):
            return False
    for x in range(len(grid)):
        column = [grid[y][x] for y in range(len(grid))]
        if not valid_row(column):
            return False
    return True


def main(debug=False):
    bad_grid = 0
    # grid_naumbers.txt is the attached file from the problem
    for line in open('grid_numbers.txt'):
        numbers = eval(line)
        grid = sort_grid(numbers)
        if not valid_grid(grid):
            if debug:
                print("Bad Grid")
            bad_grid += 1
        elif debug:
            print("Good Grid")
        if debug:
            print(numbers)
            display_grid(grid)
            input("Hit Key")
    print("Impossible:", bad_grid)


main(debug=False)
# Answer Impossible: 45
79818327
Vote

Initially I was thinking this needed to be more complicated than it ended up being and my first thoughts were trying to insert a number in a location and if that location wasn't valid then try to jump to other locations and insert there and randomly jumping from adding to rows vs adding to columns.

Eventually I convinced myself that there was an optimal order that numbers can be added to the grid in a descending fashion and that was by inserting on the diagonals. Below is the 6x6 grid and an index ordering where numbers are inserted. I got to this ordering because you can have duplicates on the diagonals, but not on the rows or the columns. The diagonals are always filled in the same direction (I could have chosen left to right bottom to top, but just arbitrarily decided right to left top to bottom for the diagonals) because for example lets say the first 4 numbers in descending order are 99, 98, 97, 97, so 99 goes in index 0, 98 goes in index 1, and 97 goes in index 2. The next least restrictive placement would be index 3 because it only has to be less than index 1 and index 1 has to be greater than or equal to index 2. So, filling in this optimal order we check if the placement is valid at each location and if it's not a note is made that the ordering failed by making that entry negative, but I continue filling out the grid so I can see exactly where the ordering failed and what didn't fail. Because you can have duplicates on the diagonals it was not too surprising that most of the failures occurred in the first three index locations 0, 1, 2 or in the last three index locations 33, 34, 35.

 0  1  3  6 10 15
 2  4  7 11 16 21
 5  8 12 17 22 26
 9 13 18 23 27 30
14 19 24 28 31 33
20 25 29 32 34 35

Below is the code I used to get the orderings. I have a working version of this code running in a .NET fiddle here https://dotnetfiddle.net/uGj4ec

private const int outputWidth = 6;
private const int outputHeight = 6;
public static void Main()
{
    var lines = inputString.Split(Environment.NewLine);
    var invalidCount = 0;
    foreach (var line in lines)
    {
        var columns = line.Split(',');
        var input = columns.Select(x => double.Parse(x.Trim('[', ']', ' '))).ToList();
        
        input.Sort();
        input.Reverse();
        
        //using double because with double values there is a difference between 0.0 and -0.0
        var output = new double[outputHeight, outputWidth];

        //loading the output array in a specific diagonal order
        //indexes below show the order items are added to the grid
        //  0  1  3  6 10 15
        //  2  4  7 11 16 21
        //  5  8 12 17 22 26
        //  9 13 18 23 27 30
        // 14 19 24 28 31 33
        // 20 25 29 32 34 35
        var inputIndex = 0;
        for (var i = 0; i < outputWidth * 2 - 1; i++)
        {
            var r = Math.Max(0, i - (outputWidth - 1));
            var c = Math.Min(i, outputWidth - 1);
            while (c >= 0 && r < outputHeight)
            {
                var val = input[inputIndex];
                var valid = checkIfValid(output, r, c, val);
                //Checking if each placement is valid. Since the input
                //is all positive numbers, invalid placements can be inserted
                //with a negative value to show where the layout failed.
                //val here needs to be a double value because -0 and +0 as
                //an integer is identical
                output[r, c] = valid ? val : -val;
                inputIndex++;
                r++;
                c--;
            }
        }

        var success = displayOutput(output);
        if (!success)
            invalidCount++;
    }
    
    Console.WriteLine($"Unable to sort into a strictly descending grid in {invalidCount} out of {lines.Length} cases.");
}

private static bool checkIfValid(double[, ] output, int row, int column, double val)
{
    //if the first row or the first column the value is set to MaxValue so that
    //any value will be less than it. Using Absolute values just in case a previous
    //placement was already invalid this will continue to show all locations where the
    //grid layout fails
    var valueAbove = row > 0 ? Math.Abs(output[row - 1, column]) : double.MaxValue;
    var valueLeft = column > 0 ? Math.Abs(output[row, column - 1]) : double.MaxValue;
    if (val < valueAbove && val < valueLeft)
        return true;
    return false;
}

private static bool displayOutput(double[, ] output)
{
    Console.WriteLine();
    var valid = true;
    for (var r = 0; r < outputHeight; r++)
    {
        for (var c = 0; c < outputWidth; c++)
        {
            if (double.IsNegative(output[r, c]))
                valid = false;
            Console.Write($"{output[r, c].ToString().PadLeft(3)} ");
        }

        Console.WriteLine();
    }

    if (valid)
        Console.WriteLine("PASS: valid strictly decreasing grid");
    else
        Console.WriteLine("ERROR: Strictly decreasing grid not possible.");
    
    return valid;
}

The output from this code is copied below

 99  98  97  92  88  65 
 98  96  92  83  64  54 
 95  90  77  63  52  38 
 88  74  62  51  30  20 
 67  61  49  26  18  10 
 59  39  26  13   3  -3 
ERROR: Strictly decreasing grid not possible.

 98 -98  92  81  64  53 
-98  86  77  59  50  35 
 83  77  57  49  35  28 
 73  56  39  33  26  13 
 54  37  33  22  13   4 
 36  28  18  12   1   0 
ERROR: Strictly decreasing grid not possible.

 99  95  91  81  73  61 
 91  84  80  71  60  42 
 82  75  68  59  42  18 
 73  65  55  41  16  14 
 63  53  34  16  13   6 
 44  24  14   7   6   0 
PASS: valid strictly decreasing grid

 99  94  86  74  63  56 
 88  83  73  62  52  36 
 81  71  61  50  35  24 
 70  59  48  29  20  10 
 57  40  27  19   9   6 
 40  27  13   8   3   1 
PASS: valid strictly decreasing grid

 99  97  89  85  78  65 
 96  88  81  78  60  46 
 85  80  76  52  45  35 
 78  75  52  43  32  27 
 71  48  41  31  26  21 
 48  37  31  22  14   5 
PASS: valid strictly decreasing grid

 98 -98  97  88  74  54 
-98  96  83  73  52  41 
 95  79  67  50  33  20 
 78  66  48  29  17   9 
 55  46  23  16   6   0 
 45  23  12   5   0  -0 
ERROR: Strictly decreasing grid not possible.

 93  91  79  71  64  57 
 87  77  66  61  52  28 
 73  65  60  51  23  10 
 65  58  40  20  10   9 
 57  34  19   9   3   2 
 30  18   9   2   0  -0 
ERROR: Strictly decreasing grid not possible.

 99  97  93  83  77  51 
 93  90  80  73  51  36 
 83  78  71  51  35  10 
 77  63  36  27   7   5 
 56  36  25   6   4   3 
 36  14   5   3   1  -1 
ERROR: Strictly decreasing grid not possible.

 98  94  83  79  67  59 
 89  80  78  66  58  44 
 80  72  65  57  42  30 
 71  64  56  39  29  18 
 60  55  37  23  16   9 
 48  31  22  10   9   4 
PASS: valid strictly decreasing grid

 99  97  88  81  71  63 
 88  86  81  68  63  51 
 82  79  66  58  50  38 
 79  64  56  48  35  11 
 64  54  42  15   9   3 
 52  41  11   5   2   0 
PASS: valid strictly decreasing grid

 98 -98  94  89  87  79 
 94  93  88  87  79  45 
 91  87  84  74  44  40 
 87  81  68  44  39  35 
 80  61  43  37  30  19 
 49  42  35  27  12   6 
ERROR: Strictly decreasing grid not possible.

 99  91  87  74  67  54 
 89  80  72  63  50  40 
 75  70  61  49  37  23 
 69  61  43  31  16   7 
 56  43  29  12   5   2 
 41  27  10   5   1  -1 
ERROR: Strictly decreasing grid not possible.

 95  94 -94  83  78  63 
 94  88  83  76  60  43 
 87  82  75  59  39  35 
 80  73  55  38  34  21 
 69  54  36  31  19  13 
 45  35  24  13  10   2 
ERROR: Strictly decreasing grid not possible.

 98  96  91  82  68  56 
 93  90  74  66  55  32 
 82  73  66  54  31  19 
 70  65  49  28  16  12 
 58  41  21  16  12  10 
 38  19  14  10   4   3 
PASS: valid strictly decreasing grid

 94  85  81  77  71  61 
 84  79  74  69  57  47 
 79  73  69  57  46  32 
 71  66  57  46  31  24 
 65  56  39  31  14  12 
 56  35  26  13   1   0 
PASS: valid strictly decreasing grid

 96  94  88  81  74  60 
 88 -88  81  71  50  40 
 86  78  64  48  39  23 
 77  63  47  33  19  11 
 62  46  29  14   8   6 
 44  26  13   7   6   5 
ERROR: Strictly decreasing grid not possible.

 96 -96  95  90  78  61 
 95  93  89  77  57  46 
 91  86  75  56  43  28 
 84  69  49  42  27  18 
 65  48  36  24  18  17 
 47  34  23  17   8   3 
ERROR: Strictly decreasing grid not possible.

 97  95  92  76  59  47 
 95  91  67  58  46  39 
 90  64  49  44  39  23 
 62  49  42  38  22  16 
 48  41  29  16  14  10 
 40  25  16  13  10   0 
PASS: valid strictly decreasing grid

 99 -99  90  78  61  52 
-99  89  73  61  48  43 
 78  69  60  45  42  28 
 68  58  45  37  28  10 
 56  45  34  20  10   6 
 44  28  15   9   5  -5 
ERROR: Strictly decreasing grid not possible.

 99  97  92  86  77  63 
 96  87  82  74  63  34 
 87  80  73  59  34  25 
 77  73  51  31  25  19 
 71  44  28  24  15  14 
 40  25  23  15  13  12 
PASS: valid strictly decreasing grid

 99  92  81  77  69  59 
 88  81  73  66  51  45 
 80  70  64  50  42  27 
 69  64  50  31  24   9 
 63  48  29  22   7   6 
 45  28  13   7   3  -3 
ERROR: Strictly decreasing grid not possible.

 92  90  80  74  55  47 
 89  77  71  54  40  29 
 76  62  50  38  27  16 
 56  49  38  24   8   5 
 47  35  24   7   3   1 
 33  23   6   2   1   0 
PASS: valid strictly decreasing grid

 90 -90  88  78  70  62 
 89  83  76  69  61  49 
 79  73  68  57  49  37 
 70  64  56  47  20  17 
 63  53  39  19  12   7 
 52  38  19   9   4   1 
ERROR: Strictly decreasing grid not possible.

 99  94  93  87  76  63 
 94  93  84  73  62  39 
 90  82  71  59  37  21 
 80  71  53  36  20   9 
 66  47  30  18   5   4 
 40  27  12   4   0  -0 
ERROR: Strictly decreasing grid not possible.

 99 -99  95  89  65  52 
 97  94  81  59  51  29 
 94  78  57  48  28  17 
 69  57  46  26  16  12 
 55  45  20  15   9   7 
 41  19  14   8   3   0 
ERROR: Strictly decreasing grid not possible.

 82  81  74  72  65  54 
 75  73  72  64  49  34 
 72  69  58  45  31  20 
 65  58  44  25  20  11 
 57  43  23  19  10   6 
 39  20  12  10   0  -0 
ERROR: Strictly decreasing grid not possible.

 97  95  91  81  76  66 
 91  86  80  75  66  57 
 85  79  74  62  46  31 
 79  68  62  45  31  20 
 68  61  38  28  17  13 
 58  33  27  14   7   1 
PASS: valid strictly decreasing grid

 97 -97  79  75  64  55 
 92  77  73  64  55  43 
 77  69  61  51  42  35 
 67  58  50  40  31  22 
 55  48  39  25  22  13 
 44  37  24  19  11  10 
ERROR: Strictly decreasing grid not possible.

 92  91  88  85  77  68 
 88  87  84  73  65  32 
 85  83  73  52  32  22 
 80  71  42  29  20  12 
 70  37  27  17  11   9 
 35  26  14  10   7   3 
PASS: valid strictly decreasing grid

 98  97  89  81  64  59 
 96  87  80  63  55  40 
 84  80  63  50  36  28 
 73  62  49  34  27  14 
 59  48  31  24  12   7 
 45  29  19  11   2   1 
PASS: valid strictly decreasing grid

 98  97  82  77  69  57 
 92  80  76  67  54  34 
 80  73  66  49  34  23 
 72  65  45  30  19  14 
 59  41  24  16  13   6 
 39  23  15   6   4   3 
PASS: valid strictly decreasing grid

 98  97  89  86  63  53 
 93  89  78  58  51  35 
 89  78  58  48  30  21 
 75  58  46  29  20  15 
 55  44  28  17  14   8 
 42  21  17   8   6   3 
PASS: valid strictly decreasing grid

 98  93  86  77  66  49 
 90  81  77  59  46  41 
 79  75  58  45  38  28 
 67  52  42  37  14   8 
 52  41  33  12   7   3 
 41  31  11   6   2  -2 
ERROR: Strictly decreasing grid not possible.

 99  96  93  85  61  45 
 95  89  82  59  45  35 
 86  71  58  44  32  26 
 62  58  42  31  20  16 
 47  40  28  18  11   8 
 36  28  18  11   7   3 
PASS: valid strictly decreasing grid

 99  97  92  85  76  58 
 97  88  84  73  56  41 
 87  77  73  52  38  23 
 76  70  51  29  15  10 
 62  46  27  15   9   7 
 44  26  14   7   6   4 
PASS: valid strictly decreasing grid

 96  93  87  78  70  43 
 91  80  76  70  42  24 
 80  75  55  40  23  10 
 74  54  39  19  10   7 
 49  34  16  10   7   3 
 30  11   9   5   2   0 
PASS: valid strictly decreasing grid

 99  94  92  81  67  56 
 93  89  79  65  54  44 
 84  69  60  53  43  26 
 67  59  53  32  23  10 
 58  50  31  19   9   6 
 48  30  15   8   5   2 
PASS: valid strictly decreasing grid

 97 -97  95  81  58  48 
 96  83  69  56  48  37 
 83  64  54  48  36  32 
 60  52  43  36  28  18 
 49  43  36  22   8   5 
 41  35  18   7   4   0 
ERROR: Strictly decreasing grid not possible.

 96  91  88  87  78  65 
 89  87  86  78  64  51 
 87  83  75  61  51  34 
 80  69  59  50  32  11 
 66  57  47  17   8   5 
 52  45  12   5   1   0 
PASS: valid strictly decreasing grid

 99  97  90  86  74  62 
 93  89  83  71  59  35 
 88  78  67  51  33  25 
 74  66  48  31  22  18 
 66  41  28  19  15  11 
 39  26  19  13  10   4 
PASS: valid strictly decreasing grid

 99  93  86  75  61  53 
 87  85  75  59  49  31 
 79  71  59  36  29  25 
 68  59  35  27  21  14 
 54  33  26  19  13  12 
 32  25  18  13   7   6 
PASS: valid strictly decreasing grid

 94  88  84  76  70  65 
 85  81  76  69  61  52 
 78  75  68  60  49  34 
 72  67  58  44  26  22 
 65  57  41  25  22  11 
 54  37  23  19  10   1 
PASS: valid strictly decreasing grid

 95  93  84  72  65  54 
 92  81  71  61  51  37 
 76  68  60  47  37  33 
 66  59  45  35  32  18 
 57  41  34  24  17  15 
 38  34  20  16  14   6 
PASS: valid strictly decreasing grid

 98 -98  92  83  75  64 
 92  86  80  73  64  43 
 83  77  69  54  40  25 
 77  67  52  40  25  13 
 66  50  36  18   5   4 
 50  28  17   5   2   0 
ERROR: Strictly decreasing grid not possible.

 99 -99  96  90  72  57 
 97  95  90  71  56  44 
 91  84  68  56  42  31 
 81  67  55  38  26  21 
 61  51  37  25  21  12 
 45  37  23  13   8   2 
ERROR: Strictly decreasing grid not possible.

 99  94  90  83  78  59 
 93  86  82  74  58  48 
 84  81  67  55  47  24 
 79  65  52  43  23  18 
 63  52  32  22  16  12 
 50  28  19  15   8   7 
PASS: valid strictly decreasing grid

 99  95  86  80  72  54 
 95  85  78  70  54  45 
 81  76  66  53  44  35 
 74  59  49  39  32  15 
 55  48  37  26  14   7 
 47  37  24   8   6   2 
PASS: valid strictly decreasing grid

 98 -98  88  78  61  53 
 96  85  71  59  52  42 
 85  71  59  48  40  31 
 68  56  45  39  25  19 
 54  44  38  25  17  12 
 42  32  24  15   6   3 
ERROR: Strictly decreasing grid not possible.

 96  95  87  72  68  56 
 94  77  70  64  53  43 
 75  69  63  50  42  28 
 68  62  48  42  28  13 
 57  47  39  23  10   7 
 44  31  19  10   5   1 
PASS: valid strictly decreasing grid

 99 -99  92  90  78  64 
 98  92  88  77  59  44 
 90  85  73  57  41  33 
 78  73  53  41  32  30 
 65  51  40  32  27  15 
 45  39  32  25  13  12 
ERROR: Strictly decreasing grid not possible.

 97 -97  93  84  80  67 
 96  92  84  77  58  40 
 85  82  74  56  36  27 
 80  73  54  34  27  25 
 70  42  31  26  22  16 
 40  29  25  16   1   0 
ERROR: Strictly decreasing grid not possible.

 95 -95  91  77  69  62 
 92  84  71  68  61  46 
 81  70  65  58  44  33 
 69  65  53  39  28  15 
 65  50  39  27  13   4 
 47  38  21   9   1   0 
ERROR: Strictly decreasing grid not possible.

 94  93  81  69  66  53 
 84  80  68  65  50  35 
 70  68  62  41  33  22 
 66  62  40  32  20   8 
 53  37  32  14   7   0 
 36  22  14   0  -0  -0 
ERROR: Strictly decreasing grid not possible.

 98  97  93  78  63  45 
 94  86  75  61  41  27 
 80  73  57  38  25  20 
 68  52  37  24  18  11 
 48  32  23  14  10   7 
 27  22  13   7   6   2 
PASS: valid strictly decreasing grid

 96  88  80  76  66  49 
 88  80  73  63  41  28 
 79  68  56  39  25  18 
 67  50  33  24  18  11 
 49  30  22  17   6   4 
 28  20  14   6   3   0 
PASS: valid strictly decreasing grid

 99  98  88  84  68  45 
 90  86  80  67  44  38 
 85  79  61  44  27  13 
 74  51  43  25  13   9 
 46  40  25  13   7   2 
 39  15   9   3   2  -2 
ERROR: Strictly decreasing grid not possible.

 99  96  88  73  66  46 
 92  86  69  61  44  29 
 75  69  53  40  24  14 
 68  53  37  22  13  11 
 48  32  22  13  11   3 
 31  17  11  10   1   0 
PASS: valid strictly decreasing grid

 98  97  91  78  72  56 
 92  90  77  70  55  42 
 86  76  65  55  38  27 
 76  65  55  38  24  15 
 58  54  37  19  11   3 
 46  34  18   5   3   0 
PASS: valid strictly decreasing grid

 98  97  89  79  59  48 
 96  82  74  55  44  38 
 80  72  52  43  35  33 
 60  52  42  34  30  23 
 51  40  33  28  21   9 
 39  33  27  13   8  -8 
ERROR: Strictly decreasing grid not possible.

 97  96  91  75  67  40 
 95  88  74  67  39  33 
 79  74  63  39  29  20 
 71  62  38  29  17   5 
 58  38  27  14   4   2 
 37  24  13   4   2   1 
PASS: valid strictly decreasing grid

 94  89  86  72  58  53 
 89  85  72  58  51  38 
 78  70  56  51  37  24 
 66  55  50  28  19  12 
 54  49  27  15  12   6 
 44  27  14   8   5  -5 
ERROR: Strictly decreasing grid not possible.

 96  92  83  82  63  55 
 90  83  77  63  54  39 
 83  75  62  54  36  23 
 72  60  53  34  22  17 
 57  50  33  19  14   9 
 50  29  18  11   6   1 
PASS: valid strictly decreasing grid

 99  96  93  89  80  71 
 95  92  87  78  70  39 
 90  82  78  60  38  25 
 81  77  55  37  23  18 
 74  49  36  21  13  10 
 44  26  19  11   3   1 
PASS: valid strictly decreasing grid

 97  93  87  82  75  69 
 89  87  82  73  68  53 
 83  81  71  68  51  38 
 76  70  67  49  37  18 
 70  63  45  32  14  11 
 63  40  21  13  10   7 
PASS: valid strictly decreasing grid

 94  91  87  80  72  58 
 91  84  80  68  55  39 
 80  78  64  52  36  27 
 74  62  51  35  26  19 
 61  50  35  26  15  11 
 49  28  25  15  10   4 
PASS: valid strictly decreasing grid

 90  76  67  63  61  42 
 72  66  63  54  40  28 
 65  61  53  38  25  20 
 61  49  36  24  17   9 
 42  34  23  16   8   6 
 31  21  10   7   5   0 
PASS: valid strictly decreasing grid

 98 -98  96  88  83  66 
-98  95  87  76  64  61 
 89  86  73  64  59  49 
 85  73  64  56  34  26 
 67  63  55  29  16   6 
 61  52  26   9   4   0 
ERROR: Strictly decreasing grid not possible.

 98 -98  95  87  70  49 
 95  93  80  66  46  18 
 89  77  65  38  15   8 
 77  60  34  10   8   7 
 59  31  10   7   2  -2 
 22   9   7   2   1  -1 
ERROR: Strictly decreasing grid not possible.

 92 -92  85  81  77  58 
 86  84  81  72  56  35 
 83  79  68  47  34  20 
 78  63  41  30  20  19 
 63  40  28  20  18   7 
 40  20  19  12   4   3 
ERROR: Strictly decreasing grid not possible.

 99 -99  79  76  65  55 
 86  79  74  64  54  32 
 78  68  60  49  31  28 
 67  60  46  30  27  20 
 57  37  29  26  20  16 
 32  28  22  18  10   3 
ERROR: Strictly decreasing grid not possible.

 99  94  90  83  73  52 
 91  87  83  68  50  36 
 84  78  66  47  33  32 
 75  62  41  33  30  22 
 52  40  33  23  19  16 
 38  32  22  17  10 -10 
ERROR: Strictly decreasing grid not possible.

 95  93  91  82  73  60 
 92  87  82  72  56  48 
 86  76  71  55  43  38 
 75  64  55  42  36  20 
 62  53  41  26  17  14 
 50  40  22  16  14   3 
PASS: valid strictly decreasing grid

 97  91  90  80  70  60 
 91  88  73  69  55  41 
 84  71  68  53  41  29 
 71  67  53  39  23  15 
 64  44  39  19  13  10 
 42  37  18  10   8   5 
PASS: valid strictly decreasing grid

 99  97  93  89  70  60 
 94  93  88  70  54  39 
 92  84  70  51  36  24 
 76  69  51  35  21  12 
 63  43  30  19   8   1 
 43  27  19   6   0  -0 
ERROR: Strictly decreasing grid not possible.

 96  95  91  82  72  43 
 92  88  78  70  41  27 
 83  77  61  38  25  22 
 76  55  36  24  20  14 
 54  34  22  18  12   9 
 30  22  15  10   2   0 
PASS: valid strictly decreasing grid

 98  93  88  83  72  57 
 90  84  81  72  55  36 
 84  76  68  50  36  24 
 75  63  44  30  24   6 
 58  42  26  20   6   1 
 39  26   9   3   1   0 
PASS: valid strictly decreasing grid

 86  85  74  63  53  40 
 81  74  61  42  39  36 
 65  58  41  39  34  25 
 53  41  38  32  23  19 
 40  37  31  22  18   8 
 36  27  20   9   6   0 
PASS: valid strictly decreasing grid

 87  84  82  75  70  58 
 82  79  75  68  54  46 
 77  74  62  53  35  33 
 74  62  53  34  29  10 
 59  49  34  24  10   8 
 49  34  21   9   4   1 
PASS: valid strictly decreasing grid

 98  95  89  80  70  53 
 92  86  80  69  53  41 
 83  75  68  52  40  33 
 72  66  49  39  28  13 
 66  45  38  22  12   7 
 43  36  13  12   5   3 
PASS: valid strictly decreasing grid

 98 -98  91  87  79  55 
 95  89  86  73  50  32 
 88  83  69  47  31  11 
 81  68  41  30  10   3 
 57  40  24  10   3   1 
 35  13   8   2   0  -0 
ERROR: Strictly decreasing grid not possible.

 98 -98  91  85  65  51 
 93  88  80  65  51  36 
 86  65  64  48  34  24 
 65  62  45  34  19  16 
 53  41  33  17  15   8 
 41  28  17   9   5   0 
ERROR: Strictly decreasing grid not possible.

 99  82  80  73  62  55 
 82  79  72  59  49  31 
 74  65  59  40  30  23 
 64  59  36  27  21  16 
 58  36  26  19  16   8 
 32  26  18  11   2   1 
PASS: valid strictly decreasing grid

 98  95  91  85  81  65 
 93  90  85  80  65  42 
 86  84  75  59  27  20 
 84  67  57  26  20  13 
 66  49  24  17  13   9 
 45  21  15  10   4   0 
PASS: valid strictly decreasing grid

 99  98  91  77  66  58 
 92  90  74  65  57  50 
 81  70  62  56  46  29 
 69  62  55  46  25  16 
 59  55  42  21  15  10 
 53  32  17  11   9   0 
PASS: valid strictly decreasing grid

 93  89 -89  87  74  50 
 89  88  87  74  49  30 
 88  87  73  47  29  20 
 76  65  44  27  17  11 
 51  34  26  14  11   9 
 31  24  14  11   6   3 
ERROR: Strictly decreasing grid not possible.

 98  97  92  83  69  52 
 95  88  76  68  43  27 
 86  75  64  43  26  22 
 72  58  41  23  18  13 
 57  33  23  18   8   4 
 32  22  16   8   2  -2 
ERROR: Strictly decreasing grid not possible.

 99  95  88  80  74  58 
 89  85  79  71  57  42 
 83  78  65  56  39  29 
 78  63  51  31  26  21 
 62  47  31  25  21  13 
 45  31  24  20   9   5 
PASS: valid strictly decreasing grid

 99  93  90  88  75  65 
 91  88  87  68  61  41 
 88  85  67  51  39  28 
 83  67  48  35  23  20 
 66  46  35  22  19   4 
 44  30  20  14   3  -3 
ERROR: Strictly decreasing grid not possible.

 99  88  79  71  64  46 
 80  74  70  63  42  35 
 72  65  63  42  32  25 
 65  60  39  30  24  16 
 54  38  29  21  16   7 
 36  27  17  10   7   2 
PASS: valid strictly decreasing grid

 95  93  75  59  44  34 
 80  66  58  37  33  25 
 64  49  37  33  23  20 
 44  36  32  23  18  11 
 35  31  22  15  10   4 
 28  21  13   6   3   0 
PASS: valid strictly decreasing grid

 99 -99  86  83  64  45 
-99  83  67  62  41  30 
 83  67  54  41  29  25 
 65  54  39  29  24  15 
 53  38  28  24   8   7 
 34  26  18   8   6   5 
ERROR: Strictly decreasing grid not possible.

 92  86  85  69  62  56 
 85  80  68  61  53  33 
 79  67  60  47  30  22 
 62  59  43  26  21  14 
 59  43  25  20   9   5 
 36  24  18   9   4   1 
PASS: valid strictly decreasing grid

 95  94  91  87  80  69 
 93  90  86  80  69  52 
 87  86  78  64  46  27 
 82  77  64  37  27  23 
 69  60  36  25  19  17 
 57  29  23  18  17   8 
PASS: valid strictly decreasing grid

 94  93  90  85  68  54 
 93  87  83  63  53  41 
 85  83  59  52  37  28 
 77  58  49  36  25  13 
 56  48  32  19   5   4 
 44  30  15   4   1  -1 
ERROR: Strictly decreasing grid not possible.

 98  89  83  82  72  61 
 88  83  82  72  60  46 
 82  81  72  60  41  33 
 75  69  59  37  33  21 
 61  54  35  27  20   6 
 51  35  23  17   4   1 
PASS: valid strictly decreasing grid

 97  95  84  81  75  58 
 93  83  81  72  58  41 
 81  78  71  56  39  20 
 75  66  49  37  16   9 
 63  47  36  13   8   5 
 45  22  10   7   3   2 
PASS: valid strictly decreasing grid

 98  94  92  83  75  62 
 92  85  82  74  61  38 
 85  79  70  57  33  28 
 75  69  54  33  28  10 
 67  53  31  25  10   8 
 44  31  12   8   5   2 
PASS: valid strictly decreasing grid

 88  80  78  73  61  45 
 79  76  70  60  41  31 
 74  69  54  40  30  22 
 66  52  34  28  22  13 
 51  34  26  19   9   2 
 33  24  14   6   2  -2 
ERROR: Strictly decreasing grid not possible.

 99  98  96  82  71  58 
 97  95  81  68  55  45 
 92  75  63  54  41  24 
 73  62  50  41  23  11 
 59  49  41  16   9   2 
 45  33  14   3   1  -1 
ERROR: Strictly decreasing grid not possible.

 95 -95  92  84  76  71 
 94  88  83  76  68  61 
 88  82  75  65  61  52 
 76  73  64  60  49  18 
 71  63  56  39  15  11 
 61  54  27  14   5   0 
ERROR: Strictly decreasing grid not possible.
Unable to sort into a strictly descending grid in 45 out of 100 cases.
79818195
Vote

The Code:

from ast import literal_eval
from pathlib import Path

# ruff: noqa: T201


def sort_integers_into_descending_grid(numbers: list[int]) -> list[list[int]] | None:
    """
    Sorts a list of integer numbers into a descending grid.

    - Each row is descendingly sorted (ties are not allowed). For example:
      6 5 4 3 2 1 is valid, but 6 5 5 5 3 2 is not valid.
    - Each column is descendingly sorted (ties are not allowed).
    - There must be a perfect square number of integers in the input list,
      so that they can fit into a square grid.
    - Or declare it impossible.
    - Returns the sorted grid on success, or None on failure.
    """
    length: int = len(numbers)
    dimension: int = int(length**0.5)
    # Verify if the list of integers can form a square grid:
    if length == 0 or dimension**2 != length:
        return None
    sorted_numbers: list[int] = sorted(numbers, reverse=True)
    # Create the grid:
    grid: list[list[int]] = [[0 for _ in range(dimension)] for k in range(dimension)]
    i: int = 0  # row of the starting position of the current antidiagonal
    j: int = 0  # column of the starting position of the current antidiagonal
    row: int = i  # row of the grid
    column: int = j  # column of the grid
    for number in sorted_numbers:
        grid[row][column] = number
        # Verify that the descending criteria for the current row and column
        # are still satisfied:
        if (row > 0 and grid[row][column] >= grid[row - 1][column]) or (
            column > 0 and grid[row][column] >= grid[row][column - 1]
        ):
            return None
        # Go to the next position along the current antidiagonal:
        row += 1
        column -= 1
        # If the end of the current antidiagonal has been reached:
        if row >= dimension or column < 0:
            # Update the starting point for the next antidiagonal:
            if j < dimension - 1:
                j += 1
            else:
                i += 1
            # The next position is at the new starting point:
            row = i
            column = j
    return grid


def main() -> None:
    fail_count: int = 0
    success_count: int = 0
    with Path("RandomNumbers.txt").open() as file:
        for index, line in enumerate(file):
            numbers: list[int] = literal_eval(line)
            print(f"{index + 1}. The list of numbers:\n{numbers}\n")
            grid: list[list[int]] | None = sort_integers_into_descending_grid(numbers)
            if grid:
                print("Result:")
                for row in grid:
                    for num in row:
                        print(f"{num:2d}  ", end="")
                    print()
                print("\n")
                success_count += 1
            else:
                print(
                    "Result:\n"
                    "It is not possible to sort this list of numbers into a descending grid.\n\n",
                )
                fail_count += 1
    print(f"Number of sorted cases: {success_count}")
    print(f"Number of cases that were impossible to sort: {fail_count}")


if __name__ == "__main__":
    main()

Run it:

https://onlinegdb.com/Rh_gnrZoF

Output:

1. List of numbers:
[54, 95, 98, 26, 3, 39, 77, 30, 83, 62, 20, 92, 61, 59, 26, 63, 92, 49, 38, 51, 99, 64, 65, 52, 98, 18, 90, 97, 96, 13, 74, 3, 88, 88, 67, 10]

Result:
Impossible


2. List of numbers:
[49, 13, 73, 54, 4, 98, 36, 33, 12, 22, 35, 18, 39, 83, 92, 77, 50, 77, 57, 64, 0, 35, 86, 98, 28, 1, 53, 59, 28, 33, 56, 37, 98, 26, 81, 13]

Result:
Impossible


3. List of numbers:
[95, 84, 44, 16, 42, 73, 0, 53, 14, 63, 81, 91, 42, 14, 13, 59, 91, 24, 99, 71, 73, 34, 60, 65, 82, 55, 16, 75, 7, 18, 68, 6, 61, 6, 80, 41]

Result:
99  95  91  81  73  61
91  84  80  71  60  42
82  75  68  59  42  18
73  65  55  41  16  14
63  53  34  16  13   6
44  24  14   7   6   0


4. List of numbers:
[27, 63, 35, 81, 56, 24, 70, 27, 59, 13, 36, 62, 73, 6, 61, 86, 48, 40, 88, 71, 52, 1, 9, 57, 50, 40, 20, 10, 3, 29, 19, 94, 99, 8, 74, 83]

Result:
99  94  86  74  63  56
88  83  73  62  52  36
81  71  61  50  35  24
70  59  48  29  20  10
57  40  27  19   9   6
40  27  13   8   3   1


5. List of numbers:
[46, 75, 78, 14, 89, 76, 37, 26, 85, 78, 81, 27, 99, 41, 96, 52, 21, 65, 71, 48, 60, 32, 48, 31, 85, 35, 88, 5, 78, 22, 31, 97, 43, 80, 52, 45]

Result:
99  97  89  85  78  65
96  88  81  78  60  46
85  80  76  52  45  35
78  75  52  43  32  27
71  48  41  31  26  21
48  37  31  22  14   5


6. List of numbers:
[0, 98, 50, 12, 0, 83, 46, 66, 67, 23, 52, 55, 41, 95, 5, 17, 78, 98, 74, 45, 97, 98, 96, 54, 48, 79, 29, 0, 73, 6, 16, 33, 20, 88, 9, 23]

Result:
Impossible


7. List of numbers:
[9, 2, 10, 57, 79, 65, 65, 0, 19, 64, 3, 18, 20, 93, 10, 30, 9, 0, 40, 51, 87, 34, 52, 71, 28, 23, 73, 61, 77, 60, 66, 91, 57, 58, 2, 9]

Result:
Impossible


8. List of numbers:
[27, 63, 51, 6, 3, 10, 7, 36, 80, 51, 93, 71, 73, 25, 3, 77, 35, 56, 36, 36, 77, 97, 14, 1, 78, 83, 5, 51, 99, 5, 93, 90, 1, 36, 83, 4]

Result:
Impossible


9. List of numbers:
[89, 94, 67, 64, 31, 66, 59, 16, 80, 22, 78, 72, 56, 83, 98, 10, 9, 57, 23, 4, 80, 37, 65, 30, 71, 55, 42, 9, 60, 18, 39, 58, 44, 79, 48, 29]

Result:
98  94  83  79  67  59
89  80  78  66  58  44
80  72  65  57  42  30
71  64  56  39  29  18
60  55  37  23  16   9
48  31  22  10   9   4


10. List of numbers:
[79, 51, 3, 82, 81, 58, 99, 88, 54, 88, 81, 5, 63, 79, 52, 64, 48, 64, 68, 11, 50, 66, 35, 71, 9, 86, 11, 97, 42, 41, 0, 2, 56, 38, 15, 63]

Result:
99  97  88  81  71  63
88  86  81  68  63  51
82  79  66  58  50  38
79  64  56  48  35  11
64  54  42  15   9   3
52  41  11   5   2   0


11. List of numbers:
[94, 35, 12, 94, 79, 40, 91, 45, 37, 98, 43, 30, 80, 81, 87, 19, 74, 87, 93, 35, 88, 89, 79, 44, 6, 87, 27, 49, 98, 44, 68, 39, 42, 87, 61, 84]

Result:
Impossible


12. List of numbers:
[5, 37, 89, 80, 31, 40, 1, 10, 54, 67, 23, 1, 75, 43, 49, 27, 29, 69, 43, 41, 7, 16, 63, 70, 5, 61, 74, 87, 2, 61, 50, 72, 91, 56, 12, 99]

Result:
Impossible


13. List of numbers:
[43, 35, 83, 94, 69, 45, 76, 73, 83, 60, 80, 31, 59, 34, 39, 63, 35, 13, 94, 78, 2, 24, 87, 21, 36, 38, 55, 19, 10, 82, 13, 95, 88, 54, 94, 75]

Result:
Impossible


14. List of numbers:
[66, 10, 58, 21, 82, 10, 32, 91, 66, 65, 3, 12, 4, 38, 12, 96, 55, 54, 73, 16, 74, 41, 28, 49, 19, 98, 16, 90, 93, 82, 56, 68, 14, 70, 31, 19]

Result:
98  96  91  82  68  56
93  90  74  66  55  32
82  73  66  54  31  19
70  65  49  28  16  12
58  41  21  16  12  10
38  19  14  10   4   3


15. List of numbers:
[13, 79, 47, 31, 79, 31, 56, 65, 94, 73, 57, 35, 74, 85, 84, 39, 24, 26, 12, 56, 46, 46, 71, 0, 57, 61, 77, 32, 14, 1, 81, 71, 69, 66, 57, 69]

Result:
94  85  81  77  71  61
84  79  74  69  57  47
79  73  69  57  46  32
71  66  57  46  31  24
65  56  39  31  14  12
56  35  26  13   1   0


16. List of numbers:
[8, 39, 23, 14, 88, 44, 81, 46, 5, 26, 50, 11, 71, 19, 86, 33, 88, 62, 81, 13, 60, 96, 7, 78, 6, 88, 77, 94, 74, 63, 48, 40, 29, 47, 64, 6]

Result:
Impossible


17. List of numbers:
[95, 36, 61, 3, 75, 84, 95, 8, 57, 42, 43, 77, 27, 65, 56, 78, 34, 96, 18, 23, 46, 17, 86, 17, 89, 28, 96, 18, 24, 90, 93, 49, 47, 69, 91, 48]

Result:
Impossible


18. List of numbers:
[76, 95, 10, 10, 58, 67, 25, 41, 0, 49, 13, 40, 59, 29, 62, 64, 97, 47, 22, 42, 39, 44, 16, 95, 23, 91, 14, 48, 90, 39, 16, 92, 46, 38, 49, 16]

Result:
97  95  92  76  59  47
95  91  67  58  46  39
90  64  49  44  39  23
62  49  42  38  22  16
48  41  29  16  14  10
40  25  16  13  10   0


19. List of numbers:
[60, 42, 28, 28, 61, 10, 37, 90, 99, 9, 45, 15, 61, 20, 6, 89, 99, 5, 34, 28, 58, 45, 10, 43, 73, 5, 45, 78, 68, 48, 44, 56, 78, 69, 52, 99]

Result:
Impossible


20. List of numbers:
[99, 92, 63, 87, 23, 73, 25, 25, 31, 97, 14, 12, 77, 96, 73, 80, 86, 15, 63, 71, 44, 34, 51, 28, 77, 24, 19, 74, 87, 34, 59, 40, 82, 13, 25, 15]

Result:
99  97  92  86  77  63
96  87  82  74  63  34
87  80  73  59  34  25
77  73  51  31  25  19
71  44  28  24  15  14
40  25  23  15  13  12


21. List of numbers:
[48, 59, 63, 45, 51, 64, 88, 99, 81, 29, 69, 27, 7, 28, 9, 77, 50, 80, 7, 64, 3, 24, 6, 22, 31, 69, 92, 66, 13, 3, 70, 81, 73, 50, 45, 42]

Result:
Impossible


22. List of numbers:
[0, 49, 29, 50, 38, 38, 24, 71, 8, 5, 56, 6, 90, 2, 3, 35, 40, 89, 24, 27, 74, 77, 54, 7, 1, 76, 92, 16, 55, 23, 47, 62, 33, 1, 80, 47]

Result:
92  90  80  74  55  47
89  77  71  54  40  29
76  62  50  38  27  16
56  49  38  24   8   5
47  35  24   7   3   1
33  23   6   2   1   0


23. List of numbers:
[1, 61, 12, 89, 56, 47, 88, 63, 73, 49, 9, 78, 68, 69, 19, 53, 76, 39, 49, 83, 38, 70, 62, 79, 19, 7, 70, 4, 90, 57, 90, 20, 52, 37, 64, 17]

Result:
Impossible


24. List of numbers:
[0, 99, 18, 20, 0, 5, 93, 66, 87, 4, 62, 47, 94, 27, 73, 82, 12, 37, 39, 63, 59, 71, 71, 36, 84, 53, 90, 93, 9, 21, 94, 76, 80, 4, 40, 30]

Result:
Impossible


25. List of numbers:
[57, 17, 99, 26, 7, 0, 81, 29, 95, 51, 46, 8, 16, 19, 15, 48, 89, 65, 69, 14, 94, 9, 3, 78, 59, 20, 41, 45, 97, 99, 57, 52, 94, 12, 55, 28]

Result:
Impossible


26. List of numbers:
[19, 49, 58, 20, 73, 65, 0, 72, 82, 12, 64, 43, 34, 58, 11, 74, 20, 75, 0, 23, 6, 25, 81, 39, 44, 65, 54, 57, 72, 72, 10, 69, 31, 10, 45, 20]

Result:
Impossible


27. List of numbers:
[68, 46, 13, 68, 81, 62, 28, 75, 66, 91, 27, 31, 20, 38, 1, 45, 76, 79, 14, 62, 58, 66, 17, 79, 61, 91, 86, 33, 57, 95, 74, 7, 31, 85, 97, 80]

Result:
97  95  91  81  76  66
91  86  80  75  66  57
85  79  74  62  46  31
79  68  62  45  31  20
68  61  38  28  17  13
58  33  27  14   7   1


28. List of numbers:
[67, 31, 55, 44, 11, 39, 50, 79, 64, 75, 97, 13, 22, 19, 42, 58, 55, 10, 51, 37, 73, 55, 22, 40, 35, 97, 77, 92, 43, 24, 69, 25, 64, 61, 48, 77]

Result:
Impossible


29. List of numbers:
[7, 17, 84, 29, 87, 12, 85, 22, 65, 70, 73, 14, 32, 9, 27, 3, 11, 42, 88, 20, 37, 10, 88, 77, 68, 92, 71, 80, 83, 32, 35, 85, 91, 52, 26, 73]

Result:
92  91  88  85  77  68
88  87  84  73  65  32
85  83  73  52  32  22
80  71  42  29  20  12
70  37  27  17  11   9
35  26  14  10   7   3


30. List of numbers:
[62, 24, 97, 27, 49, 2, 50, 36, 14, 59, 63, 1, 45, 98, 80, 64, 59, 80, 55, 96, 87, 89, 19, 81, 40, 31, 73, 48, 29, 34, 63, 11, 12, 7, 84, 28]

Result:
98  97  89  81  64  59
96  87  80  63  55  40
84  80  63  50  36  28
73  62  49  34  27  14
59  48  31  24  12   7
45  29  19  11   2   1


31. List of numbers:
[23, 82, 3, 66, 59, 65, 49, 80, 16, 73, 39, 69, 45, 15, 6, 14, 4, 97, 76, 57, 34, 13, 77, 72, 98, 24, 34, 54, 23, 41, 67, 6, 80, 19, 30, 92]

Result:
98  97  82  77  69  57
92  80  76  67  54  34
80  73  66  49  34  23
72  65  45  30  19  14
59  41  24  16  13   6
39  23  15   6   4   3


32. List of numbers:
[20, 35, 58, 63, 21, 75, 58, 8, 30, 44, 97, 21, 3, 86, 78, 89, 93, 42, 29, 89, 53, 17, 89, 6, 8, 14, 48, 98, 15, 58, 28, 46, 51, 55, 17, 78]

Result:
98  97  89  86  63  53
93  89  78  58  51  35
89  78  58  48  30  21
75  58  46  29  20  15
55  44  28  17  14   8
42  21  17   8   6   3


33. List of numbers:
[42, 41, 8, 12, 37, 81, 33, 58, 59, 31, 3, 67, 77, 90, 6, 2, 14, 45, 49, 28, 79, 93, 7, 75, 52, 52, 46, 86, 98, 77, 66, 38, 41, 11, 41, 2]

Result:
Impossible


34. List of numbers:
[8, 45, 28, 85, 58, 99, 18, 86, 95, 16, 59, 45, 26, 35, 36, 96, 61, 82, 32, 20, 62, 47, 93, 3, 44, 71, 11, 11, 31, 28, 42, 7, 18, 58, 40, 89]

Result:
99  96  93  85  61  45
95  89  82  59  45  35
86  71  58  44  32  26
62  58  42  31  20  16
47  40  28  18  11   8
36  28  18  11   7   3


35. List of numbers:
[87, 4, 99, 46, 73, 27, 7, 44, 26, 62, 15, 10, 14, 77, 97, 70, 58, 23, 85, 73, 76, 97, 6, 92, 52, 51, 9, 84, 29, 56, 15, 38, 41, 7, 88, 76]

Result:
99  97  92  85  76  58
97  88  84  73  56  41
87  77  73  52  38  23
76  70  51  29  15  10
62  46  27  15   9   7
44  26  14   7   6   4


36. List of numbers:
[30, 0, 80, 70, 10, 78, 91, 80, 3, 42, 24, 70, 39, 7, 7, 43, 9, 2, 23, 96, 76, 87, 19, 11, 5, 10, 74, 10, 49, 16, 34, 54, 40, 55, 75, 93]

Result:
96  93  87  78  70  43
91  80  76  70  42  24
80  75  55  40  23  10
74  54  39  19  10   7
49  34  16  10   7   3
30  11   9   5   2   0


37. List of numbers:
[92, 54, 58, 53, 99, 84, 53, 50, 56, 65, 10, 89, 19, 2, 6, 94, 44, 69, 67, 60, 79, 5, 30, 23, 15, 8, 48, 26, 32, 31, 43, 59, 81, 9, 67, 93]

Result:
99  94  92  81  67  56
93  89  79  65  54  44
84  69  60  53  43  26
67  59  53  32  23  10
58  50  31  19   9   6
48  30  15   8   5   2


38. List of numbers:
[7, 58, 97, 4, 22, 36, 5, 83, 32, 69, 83, 54, 18, 48, 49, 43, 36, 37, 96, 0, 28, 18, 64, 56, 52, 97, 43, 95, 36, 8, 48, 35, 60, 41, 48, 81]

Result:
Impossible


39. List of numbers:
[50, 78, 66, 51, 45, 80, 65, 87, 0, 5, 87, 91, 34, 78, 47, 89, 51, 32, 88, 64, 52, 8, 86, 59, 11, 5, 1, 12, 57, 87, 75, 83, 17, 69, 96, 61]

Result:
96  91  88  87  78  65
89  87  86  78  64  51
87  83  75  61  51  34
80  69  59  50  32  11
66  57  47  17   8   5
52  45  12   5   1   0


40. List of numbers:
[74, 18, 35, 33, 97, 4, 22, 39, 41, 10, 66, 59, 11, 71, 90, 28, 78, 66, 51, 25, 48, 89, 74, 62, 13, 19, 67, 99, 19, 88, 15, 83, 26, 86, 31, 93]

Result:
99  97  90  86  74  62
93  89  83  71  59  35
88  78  67  51  33  25
74  66  48  31  22  18
66  41  28  19  15  11
39  26  19  13  10   4


41. List of numbers:
[93, 32, 27, 13, 61, 53, 49, 35, 59, 13, 54, 68, 75, 31, 18, 79, 33, 59, 87, 86, 14, 26, 21, 19, 12, 59, 75, 36, 7, 71, 25, 25, 6, 85, 29, 99]

Result:
99  93  86  75  61  53
87  85  75  59  49  31
79  71  59  36  29  25
68  59  35  27  21  14
54  33  26  19  13  12
32  25  18  13   7   6


42. List of numbers:
[94, 78, 11, 70, 49, 22, 25, 67, 34, 65, 85, 58, 76, 10, 44, 22, 75, 72, 65, 54, 68, 60, 84, 52, 19, 26, 61, 69, 88, 76, 37, 41, 81, 1, 23, 57]

Result:
94  88  84  76  70  65
85  81  76  69  61  52
78  75  68  60  49  34
72  67  58  44  26  22
65  57  41  25  22  11
54  37  23  19  10   1


43. List of numbers:
[15, 72, 24, 37, 95, 16, 76, 61, 34, 47, 68, 93, 18, 92, 32, 17, 20, 66, 51, 33, 65, 38, 71, 45, 81, 59, 34, 35, 84, 37, 14, 6, 41, 60, 57, 54]

Result:
95  93  84  72  65  54
92  81  71  61  51  37
76  68  60  47  37  33
66  59  45  35  32  18
57  41  34  24  17  15
38  34  20  16  14   6


44. List of numbers:
[83, 86, 73, 77, 75, 67, 5, 92, 43, 13, 98, 92, 69, 80, 50, 25, 64, 0, 64, 25, 98, 40, 66, 77, 4, 18, 52, 50, 28, 36, 17, 54, 5, 83, 2, 40]

Result:
Impossible


45. List of numbers:
[25, 68, 57, 61, 55, 81, 56, 71, 95, 72, 37, 21, 91, 8, 23, 26, 38, 44, 45, 84, 37, 51, 13, 42, 90, 12, 67, 21, 96, 31, 99, 97, 2, 90, 99, 56]

Result:
Impossible


46. List of numbers:
[47, 90, 19, 59, 82, 32, 52, 99, 74, 8, 93, 18, 79, 22, 24, 63, 84, 50, 55, 86, 94, 23, 83, 65, 67, 48, 16, 15, 81, 78, 7, 43, 12, 52, 58, 28]

Result:
99  94  90  83  78  59
93  86  82  74  58  48
84  81  67  55  47  24
79  65  52  43  23  18
63  52  32  22  16  12
50  28  19  15   8   7


47. List of numbers:
[54, 39, 86, 53, 24, 55, 72, 2, 6, 15, 78, 8, 35, 70, 59, 80, 74, 99, 95, 32, 44, 26, 47, 49, 48, 14, 95, 66, 54, 76, 37, 81, 85, 37, 45, 7]

Result:
99  95  86  80  72  54
95  85  78  70  54  45
81  76  66  53  44  35
74  59  49  39  32  15
55  48  37  26  14   7
47  37  24   8   6   2


48. List of numbers:
[19, 38, 6, 31, 71, 53, 40, 85, 71, 52, 56, 25, 78, 32, 17, 85, 42, 24, 61, 42, 3, 54, 98, 68, 48, 39, 59, 59, 12, 25, 96, 98, 15, 88, 44, 45]

Result:
Impossible


49. List of numbers:
[62, 70, 19, 57, 56, 68, 7, 13, 53, 87, 68, 69, 77, 39, 23, 94, 42, 10, 1, 28, 43, 31, 42, 48, 75, 95, 28, 10, 44, 50, 72, 47, 64, 96, 5, 63]

Result:
96  95  87  72  68  56
94  77  70  64  53  43
75  69  63  50  42  28
68  62  48  42  28  13
57  47  39  23  10   7
44  31  19  10   5   1


50. List of numbers:
[92, 85, 77, 92, 90, 27, 39, 57, 51, 41, 99, 78, 78, 53, 88, 59, 30, 65, 15, 25, 32, 32, 99, 64, 90, 40, 13, 45, 41, 73, 98, 12, 44, 73, 33, 32]

Result:
Impossible


51. List of numbers:
[97, 36, 97, 58, 74, 56, 70, 80, 92, 84, 93, 16, 0, 34, 96, 85, 84, 16, 29, 22, 27, 42, 26, 40, 27, 80, 1, 40, 82, 25, 54, 31, 77, 25, 67, 73]

Result:
Impossible


52. List of numbers:
[46, 91, 13, 50, 65, 68, 44, 15, 65, 58, 77, 21, 92, 70, 69, 95, 9, 84, 69, 71, 53, 65, 0, 33, 95, 4, 1, 28, 62, 27, 39, 38, 47, 39, 61, 81]

Result:
Impossible


53. List of numbers:
[37, 0, 70, 66, 14, 20, 50, 68, 8, 0, 62, 41, 68, 35, 14, 69, 94, 62, 53, 84, 32, 22, 80, 81, 22, 66, 36, 65, 40, 53, 93, 0, 0, 33, 32, 7]

Result:
Impossible


54. List of numbers:
[68, 73, 37, 13, 86, 20, 22, 97, 27, 10, 32, 57, 27, 11, 52, 7, 7, 48, 23, 14, 98, 25, 41, 6, 78, 63, 80, 38, 24, 75, 2, 61, 45, 93, 18, 94]

Result:
98  97  93  78  63  45
94  86  75  61  41  27
80  73  57  38  25  20
68  52  37  24  18  11
48  32  23  14  10   7
27  22  13   7   6   2


55. List of numbers:
[20, 14, 76, 73, 80, 30, 56, 33, 80, 18, 79, 66, 39, 3, 88, 25, 28, 24, 63, 88, 68, 28, 67, 49, 6, 18, 4, 49, 0, 96, 11, 22, 6, 41, 17, 50]

Result:
96  88  80  76  66  49
88  80  73  63  41  28
79  68  56  39  25  18
67  50  33  24  18  11
49  30  22  17   6   4
28  20  14   6   3   0


56. List of numbers:
[9, 61, 45, 7, 25, 86, 99, 39, 79, 13, 46, 74, 44, 3, 90, 43, 25, 9, 2, 27, 13, 15, 38, 98, 2, 88, 13, 51, 44, 80, 67, 85, 84, 40, 2, 68]

Result:
Impossible


57. List of numbers:
[22, 48, 11, 46, 99, 88, 75, 32, 69, 66, 73, 10, 3, 31, 13, 44, 11, 17, 68, 0, 37, 86, 40, 92, 13, 61, 24, 69, 22, 11, 53, 1, 14, 53, 96, 29]

Result:
99  96  88  73  66  46
92  86  69  61  44  29
75  69  53  40  24  14
68  53  37  22  13  11
48  32  22  13  11   3
31  17  11  10   1   0


58. List of numbers:
[65, 27, 91, 56, 76, 11, 86, 34, 3, 15, 97, 42, 19, 98, 38, 78, 90, 37, 76, 55, 46, 18, 72, 92, 3, 38, 55, 54, 5, 0, 58, 24, 77, 70, 65, 55]

Result:
98  97  91  78  72  56
92  90  77  70  55  42
86  76  65  55  38  27
76  65  55  38  24  15
58  54  37  19  11   3
46  34  18   5   3   0


59. List of numbers:
[33, 48, 21, 34, 42, 60, 82, 33, 98, 27, 51, 33, 74, 55, 59, 96, 44, 35, 23, 28, 13, 52, 72, 9, 39, 52, 8, 30, 40, 8, 97, 43, 79, 89, 38, 80]

Result:
Impossible


60. List of numbers:
[1, 29, 67, 37, 13, 29, 33, 96, 91, 24, 4, 67, 20, 71, 75, 95, 2, 63, 39, 14, 88, 2, 5, 17, 38, 40, 74, 79, 39, 62, 38, 58, 74, 4, 27, 97]

Result:
97  96  91  75  67  40
95  88  74  67  39  33
79  74  63  39  29  20
71  62  38  29  17   5
58  38  27  14   4   2
37  24  13   4   2   1


61. List of numbers:
[86, 8, 5, 54, 58, 78, 70, 51, 89, 94, 51, 55, 27, 6, 56, 44, 14, 72, 5, 27, 19, 50, 72, 58, 66, 24, 49, 28, 15, 12, 12, 37, 85, 89, 53, 38]

Result:
Impossible


62. List of numbers:
[54, 1, 82, 23, 72, 55, 6, 96, 54, 22, 19, 63, 83, 50, 39, 75, 33, 29, 83, 14, 60, 92, 62, 83, 11, 34, 53, 77, 57, 63, 18, 17, 50, 9, 90, 36]

Result:
96  92  83  82  63  55
90  83  77  63  54  39
83  75  62  54  36  23
72  60  53  34  22  17
57  50  33  19  14   9
50  29  18  11   6   1


63. List of numbers:
[60, 78, 25, 81, 18, 1, 96, 39, 36, 82, 23, 78, 70, 80, 19, 55, 74, 38, 99, 37, 3, 87, 21, 26, 93, 89, 44, 13, 95, 92, 11, 71, 77, 10, 49, 90]

Result:
99  96  93  89  80  71
95  92  87  78  70  39
90  82  78  60  38  25
81  77  55  37  23  18
74  49  36  21  13  10
44  26  19  11   3   1


64. List of numbers:
[68, 68, 45, 82, 67, 7, 97, 49, 87, 83, 73, 70, 70, 87, 14, 37, 10, 21, 82, 71, 75, 13, 89, 93, 63, 11, 40, 18, 32, 69, 38, 53, 81, 63, 51, 76]

Result:
97  93  87  82  75  69
89  87  82  73  68  53
83  81  71  68  51  38
76  70  67  49  37  18
70  63  45  32  14  11
63  40  21  13  10   7


65. List of numbers:
[25, 36, 27, 62, 4, 51, 50, 74, 19, 10, 78, 94, 15, 49, 11, 26, 91, 80, 61, 80, 84, 87, 80, 52, 35, 28, 64, 91, 39, 58, 15, 55, 26, 72, 68, 35]

Result:
94  91  87  80  72  58
91  84  80  68  55  39
80  78  64  52  36  27
74  62  51  35  26  19
61  50  35  26  15  11
49  28  25  15  10   4


66. List of numbers:
[42, 66, 36, 17, 5, 31, 38, 90, 61, 8, 24, 0, 7, 40, 65, 67, 54, 61, 53, 16, 49, 76, 21, 63, 23, 72, 20, 9, 42, 34, 10, 6, 63, 25, 61, 28]

Result:
90  76  67  63  61  42
72  66  63  54  40  28
65  61  53  38  25  20
61  49  36  24  17   9
42  34  23  16   8   6
31  21  10   7   5   0


67. List of numbers:
[9, 98, 52, 95, 85, 61, 87, 96, 64, 98, 98, 83, 88, 4, 73, 29, 26, 67, 59, 34, 89, 49, 6, 16, 0, 61, 55, 76, 73, 64, 26, 63, 56, 64, 66, 86]

Result:
Impossible


68. List of numbers:
[98, 2, 10, 34, 9, 10, 8, 46, 2, 95, 89, 65, 49, 1, 38, 15, 8, 22, 66, 80, 7, 77, 77, 70, 1, 7, 60, 59, 93, 7, 2, 98, 31, 95, 87, 18]

Result:
Impossible


69. List of numbers:
[47, 20, 77, 92, 92, 78, 81, 7, 34, 20, 30, 40, 56, 79, 86, 84, 81, 40, 19, 28, 72, 35, 20, 85, 3, 68, 18, 4, 63, 83, 20, 12, 41, 63, 19, 58]

Result:
Impossible


70. List of numbers:
[55, 10, 67, 18, 31, 16, 76, 57, 79, 64, 68, 37, 78, 60, 60, 46, 49, 32, 32, 3, 65, 74, 22, 79, 26, 29, 28, 86, 20, 99, 27, 99, 28, 30, 54, 20]

Result:
Impossible


71. List of numbers:
[73, 87, 66, 32, 10, 75, 40, 94, 30, 99, 52, 10, 33, 33, 52, 36, 16, 90, 68, 62, 19, 33, 50, 22, 78, 47, 91, 22, 84, 83, 41, 17, 32, 83, 38, 23]

Result:
Impossible


72. List of numbers:
[82, 26, 41, 53, 71, 22, 95, 55, 60, 14, 40, 42, 36, 43, 91, 50, 16, 93, 62, 72, 3, 14, 55, 48, 20, 17, 56, 38, 64, 87, 86, 92, 82, 75, 73, 76]

Result:
95  93  91  82  73  60
92  87  82  72  56  48
86  76  71  55  43  38
75  64  55  42  36  20
62  53  41  26  17  14
50  40  22  16  14   3


73. List of numbers:
[70, 18, 42, 41, 19, 44, 8, 90, 10, 73, 41, 39, 23, 69, 64, 55, 39, 80, 88, 13, 5, 29, 71, 53, 84, 71, 91, 97, 60, 67, 10, 15, 53, 37, 68, 91]

Result:
97  91  90  80  70  60
91  88  73  69  55  41
84  71  68  53  41  29
71  67  53  39  23  15
64  44  39  19  13  10
42  37  18  10   8   5


74. List of numbers:
[12, 99, 93, 43, 63, 51, 54, 89, 39, 8, 19, 27, 70, 94, 0, 70, 76, 1, 51, 30, 60, 88, 24, 69, 35, 36, 97, 43, 0, 70, 21, 84, 19, 6, 93, 92]

Result:
Impossible


75. List of numbers:
[15, 83, 14, 61, 0, 18, 77, 34, 95, 92, 22, 76, 54, 9, 22, 43, 96, 91, 24, 12, 30, 22, 88, 72, 82, 38, 27, 10, 41, 2, 78, 25, 36, 20, 70, 55]

Result:
96  95  91  82  72  43
92  88  78  70  41  27
83  77  61  38  25  22
76  55  36  24  20  14
54  34  22  18  12   9
30  22  15  10   2   0


76. List of numbers:
[83, 6, 84, 58, 57, 42, 76, 75, 36, 39, 98, 55, 72, 72, 84, 81, 36, 9, 3, 44, 1, 50, 63, 1, 93, 24, 26, 20, 30, 68, 0, 24, 90, 26, 6, 88]

Result:
98  93  88  83  72  57
90  84  81  72  55  36
84  76  68  50  36  24
75  63  44  30  24   6
58  42  26  20   6   1
39  26   9   3   1   0


77. List of numbers:
[58, 38, 65, 42, 40, 25, 32, 39, 19, 31, 74, 36, 85, 74, 23, 20, 37, 41, 41, 63, 61, 9, 27, 39, 22, 0, 36, 34, 53, 53, 6, 40, 81, 18, 86, 8]

Result:
86  85  74  63  53  40
81  74  61  42  39  36
65  58  41  39  34  25
53  41  38  32  23  19
40  37  31  22  18   8
36  27  20   9   6   0


78. List of numbers:
[34, 1, 53, 24, 53, 46, 21, 59, 74, 75, 10, 49, 79, 74, 29, 68, 82, 75, 49, 62, 8, 58, 54, 34, 87, 4, 84, 34, 10, 82, 70, 35, 62, 9, 33, 77]

Result:
87  84  82  75  70  58
82  79  75  68  54  46
77  74  62  53  35  33
74  62  53  34  29  10
59  49  34  24  10   8
49  34  21   9   4   1


79. List of numbers:
[28, 49, 3, 98, 69, 36, 80, 53, 72, 68, 89, 22, 40, 52, 5, 66, 39, 38, 41, 45, 13, 12, 70, 12, 7, 86, 95, 83, 66, 92, 43, 13, 53, 80, 75, 33]

Result:
98  95  89  80  70  53
92  86  80  69  53  41
83  75  68  52  40  33
72  66  49  39  28  13
66  45  38  22  12   7
43  36  13  12   5   3


80. List of numbers:
[98, 98, 88, 3, 11, 32, 83, 24, 91, 79, 3, 55, 50, 95, 41, 69, 30, 89, 68, 47, 13, 35, 0, 86, 57, 8, 10, 31, 1, 40, 81, 2, 87, 10, 73, 0]

Result:
Impossible


81. List of numbers:
[36, 8, 65, 86, 88, 65, 19, 33, 62, 24, 98, 34, 0, 80, 45, 53, 16, 28, 41, 65, 93, 34, 64, 85, 48, 98, 15, 51, 41, 65, 5, 9, 51, 17, 17, 91]

Result:
Impossible


82. List of numbers:
[21, 49, 80, 99, 8, 32, 11, 36, 82, 59, 64, 59, 55, 73, 1, 23, 82, 59, 19, 16, 58, 18, 62, 36, 74, 30, 72, 79, 26, 31, 16, 40, 2, 27, 65, 26]

Result:
99  82  80  73  62  55
82  79  72  59  49  31
74  65  59  40  30  23
64  59  36  27  21  16
58  36  26  19  16   8
32  26  18  11   2   1


83. List of numbers:
[86, 24, 59, 75, 93, 17, 20, 42, 21, 4, 80, 0, 57, 91, 81, 84, 95, 13, 65, 85, 9, 15, 26, 90, 66, 20, 13, 98, 67, 27, 85, 49, 45, 65, 10, 84]

Result:
98  95  91  85  81  65
93  90  85  80  65  42
86  84  75  59  27  20
84  67  57  26  20  13
66  49  24  17  13   9
45  21  15  10   4   0


84. List of numbers:
[17, 16, 99, 46, 21, 66, 57, 69, 29, 42, 50, 92, 9, 11, 56, 62, 32, 15, 55, 25, 55, 90, 81, 74, 62, 98, 58, 65, 46, 77, 53, 10, 0, 59, 70, 91]

Result:
99  98  91  77  66  58
92  90  74  65  57  50
81  70  62  56  46  29
69  62  55  46  25  16
59  55  42  21  15  10
53  32  17  11   9   0


85. List of numbers:
[76, 89, 89, 89, 87, 87, 11, 51, 11, 44, 11, 50, 29, 88, 93, 31, 6, 26, 74, 34, 24, 30, 14, 74, 9, 47, 20, 17, 88, 14, 49, 87, 3, 65, 27, 73]

Result:
Impossible


86. List of numbers:
[18, 18, 68, 23, 13, 98, 52, 92, 72, 75, 8, 8, 2, 33, 69, 23, 22, 16, 95, 76, 43, 83, 86, 27, 4, 58, 57, 97, 64, 22, 43, 32, 41, 2, 88, 26]

Result:
Impossible


87. List of numbers:
[21, 20, 85, 29, 56, 31, 65, 45, 58, 26, 62, 21, 71, 31, 5, 57, 88, 42, 51, 39, 79, 83, 47, 99, 25, 31, 9, 24, 13, 63, 95, 78, 80, 74, 78, 89]

Result:
99  95  88  80  74  58
89  85  79  71  57  42
83  78  65  56  39  29
78  63  51  31  26  21
62  47  31  25  21  13
45  31  24  20   9   5


88. List of numbers:
[39, 90, 68, 22, 85, 14, 4, 20, 41, 51, 67, 75, 20, 48, 91, 65, 61, 44, 66, 3, 83, 30, 93, 23, 19, 99, 46, 88, 87, 35, 3, 88, 35, 67, 88, 28]

Result:
Impossible


89. List of numbers:
[63, 21, 64, 10, 7, 38, 25, 17, 32, 36, 7, 99, 46, 65, 74, 71, 63, 42, 30, 72, 29, 80, 42, 65, 27, 24, 16, 16, 70, 2, 54, 60, 35, 79, 88, 39]

Result:
99  88  79  71  64  46
80  74  70  63  42  35
72  65  63  42  32  25
65  60  39  30  24  16
54  38  29  21  16   7
36  27  17  10   7   2


90. List of numbers:
[10, 75, 23, 44, 33, 33, 11, 13, 23, 3, 44, 37, 64, 66, 35, 32, 34, 22, 18, 15, 6, 37, 25, 36, 20, 4, 49, 58, 59, 21, 80, 95, 0, 31, 93, 28]

Result:
95  93  75  59  44  34
80  66  58  37  33  25
64  49  37  33  23  20
44  36  32  23  18  11
35  31  22  15  10   4
28  21  13   6   3   0


91. List of numbers:
[54, 30, 99, 86, 7, 38, 8, 18, 26, 83, 15, 83, 45, 5, 24, 67, 6, 39, 65, 67, 83, 99, 29, 41, 64, 62, 25, 53, 54, 34, 24, 41, 99, 28, 8, 29]

Result:
Impossible


92. List of numbers:
[30, 60, 67, 20, 43, 56, 79, 43, 92, 85, 69, 9, 62, 22, 62, 24, 68, 33, 18, 61, 25, 14, 21, 59, 86, 59, 53, 26, 1, 80, 9, 36, 4, 5, 85, 47]

Result:
92  86  85  69  62  56
85  80  68  61  53  33
79  67  60  47  30  22
62  59  43  26  21  14
59  43  25  20   9   5
36  24  18   9   4   1


93. List of numbers:
[57, 64, 8, 17, 69, 23, 77, 29, 69, 52, 80, 86, 18, 93, 78, 17, 36, 60, 94, 25, 80, 90, 87, 86, 64, 23, 87, 95, 19, 69, 91, 82, 37, 27, 27, 46]

Result:
95  94  91  87  80  69
93  90  86  80  69  52
87  86  78  64  46  27
82  77  64  37  27  23
69  60  36  25  19  17
57  29  23  18  17   8


94. List of numbers:
[52, 19, 54, 87, 1, 4, 41, 68, 93, 56, 36, 13, 32, 25, 83, 48, 59, 5, 37, 58, 83, 93, 53, 77, 44, 63, 49, 1, 94, 4, 28, 30, 85, 15, 85, 90]

Result:
Impossible


95. List of numbers:
[75, 72, 89, 33, 98, 23, 81, 41, 35, 17, 4, 1, 46, 60, 83, 69, 27, 35, 33, 83, 61, 61, 21, 72, 82, 72, 82, 6, 59, 51, 60, 37, 82, 20, 88, 54]

Result:
98  89  83  82  72  61
88  83  82  72  60  46
82  81  72  60  41  33
75  69  59  37  33  21
61  54  35  27  20   6
51  35  23  17   4   1


96. List of numbers:
[20, 37, 13, 75, 81, 78, 36, 75, 22, 45, 81, 63, 58, 72, 81, 7, 9, 39, 49, 8, 84, 66, 71, 58, 41, 56, 5, 2, 83, 47, 16, 3, 93, 95, 97, 10]

Result:
97  95  84  81  75  58
93  83  81  72  58  41
81  78  71  56  39  20
75  66  49  37  16   9
63  47  36  13   8   5
45  22  10   7   3   2


97. List of numbers:
[94, 83, 74, 92, 8, 10, 12, 92, 28, 28, 31, 98, 10, 33, 62, 70, 85, 53, 8, 31, 75, 67, 38, 2, 5, 85, 44, 25, 54, 69, 33, 61, 75, 57, 79, 82]

Result:
98  94  92  83  75  62
92  85  82  74  61  38
85  79  70  57  33  28
75  69  54  33  28  10
67  53  31  25  10   8
44  31  12   8   5   2


98. List of numbers:
[60, 34, 79, 9, 2, 28, 80, 24, 2, 76, 26, 34, 61, 22, 40, 31, 52, 14, 30, 2, 88, 54, 41, 73, 6, 45, 13, 22, 70, 51, 74, 69, 19, 66, 33, 78]

Result:
Impossible


99. List of numbers:
[3, 11, 50, 41, 23, 41, 45, 2, 62, 95, 55, 73, 1, 98, 33, 68, 82, 96, 24, 81, 1, 58, 59, 41, 45, 9, 99, 49, 16, 97, 54, 75, 92, 14, 71, 63]

Result:
Impossible


100. List of numbers:
[18, 73, 63, 61, 88, 15, 27, 49, 82, 95, 0, 54, 71, 76, 64, 65, 84, 39, 61, 56, 52, 60, 88, 92, 75, 83, 94, 61, 76, 76, 14, 11, 5, 95, 71, 68]

Result:
Impossible

Result:

Number of sorted cases: 55
Number of cases that were impossible to sort: 45

Description of the approach:

The grid, sorted in descending order, must have its biggest number at its upper left corner, and the subsequent numbers decrease in both directions (horizontally and vertically), so that the bottom right corner will receive the smallest number in the list.

So, my solution consists of sorting the original list of numbers in descending order, and place each number of the sorted list in each position along the antidiagonals of the grid, starting at the upper left corner of the grid, and going though the subsequent positions in the antidiagonals, i.e. following the numbered sequence illustrated below for a 6x6 grid:

 0   1   3   6  10  15
 2   4   7  11  16  21
 5   8  12  17  22  26
 9  13  18  23  27  30
14  19  24  28  31  33
20  25  29  32  34  35

And, as each number is placed in the grid, the code verifies that the number to its immediate left and immediately above it in the grid are both bigger than the current number.

If at any point this is not the case then it is not possible to create the sorted grid with the provided list of numbers.

The function succeeds if the grid is completely filled without breaking the descending criteria in both directions for any position.

79823828
Vote

Obtaining the coordinates in the grid's antidiagonals

Given a grid, we wish to obtain each position along the antidiagonals of the grid, starting at the upper left corner of the grid, and going through the subsequent positions in the antidiagonals.

Meaning that for a 6x6 grid we intend to follow the numbered sequence bellow:

     |       COLUMNS
     |  0   1   2   3   4   5
-----+-----------------------
   0 |  0   1   3   6  10  15
R  1 |  2   4   7  11  16  21
O  2 |  5   8  12  17  22  26
W  3 |  9  13  18  23  27  30
S  4 | 14  19  24  28  31  33
   5 | 20  25  29  32  34  35

So, if we have the respective coordinates of each position in the grid:

0,0  0,1  0,2  0,3  0,4  0,5

1,0  1,1  1,2  1,3  1,4  1,5

2,0  2,1  2,2  2,3  2,4  2,5

3,0  3,1  3,2  3,3  3,4  3,5

4,0  4,1  4,2  4,3  4,4  4,5

5,0  5,1  5,2  5,3  5,4  5,5

It can be seen that, given a pair of coordinates row, column somewhere in the middle of the grid, the coordinates of next position along its antidiagonal will be in the next row (going down), and in the previous column (to the left) of the grid, i.e. the next position will have coordinates row + 1, column - 1.

But that isn't the case for the positions at the end of each antidiagonal, whose following position is at the beginning of the next antidiagonal.

So we must analyze the condition for which it can be recognized that the end of an antidiagonal has been reached, and in that case assign the start of the next antidiagonal as the next position.

To make it easier to visualize it we can separate the coordinates belonging to each antidiagonal like this:

COORDINATES FOR EACH POSITION           ANTIDIAGONALS

0,0  0,1  0,2  0,3  0,4  0,5            0,0
                                        0,1  1,0
1,0  1,1  1,2  1,3  1,4  1,5            0,2  1,1  2,0
                                        0,3  1,2  2,1  3,0
2,0  2,1  2,2  2,3  2,4  2,5            0,4  1,3  2,2  3,1  4,0
                                        0,5  1,4  2,3  3,2  4,1  5,0
3,0  3,1  3,2  3,3  3,4  3,5            1,5  2,4  3,3  4,2  5,1
                                        2,5  3,4  4,3  5,2
4,0  4,1  4,2  4,3  4,4  4,5            3,5  4,4  5,3
                                        4,5  5,4
5,0  5,1  5,2  5,3  5,4  5,5            5,5

And if we highlight the coordinates at the end of each antidiagonal:

0,0  ...  ...  ...  ...  ...            0,0
                                        ...  1,0
1,0  ...  ...  ...  ...  ...            ...  ...  2,0
                                        ...  ...  ...  3,0
2,0  ...  ...  ...  ...  ...            ...  ...  ...  ...  4,0
                                        ...  ...  ...  ...  ...  5,0
3,0  ...  ...  ...  ...  ...            ...  ...  ...  ...  5,1
                                        ...  ...  ...  5,2
4,0  ...  ...  ...  ...  ...            ...  ...  5,3
                                        ...  5,4
5,0  5,1  5,2  5,3  5,4  5,5            5,5

It is made clear that the ends of the antidiagonals are either at the first column (column = 0) or at the last row (row = 5 = 6 - 1 = n - 1).

So, for these positions, as we defined that our logic for iterating over the antidiagonals is that the next position will be at row + 1, column - 1, the next position of the antidiagonal would be computed so that either row + 1 = 5 + 1 = 6 = n or column - 1 = 0 - 1 = -1, which are not valid positions in the grid, therefore we can define that if row equals 6 (= n) or column equals -1 the end of the current antidiagonal has been reached.

Finally, we must obtain the position of the start of the next antidiagonal, so lets highlight them:

0,0  0,1  0,2  0,3  0,4  0,5            0,0
                                        0,1  ...
...  ...  ...  ...  ...  1,5            0,2  ...  ...
                                        0,3  ...  ...  ...
...  ...  ...  ...  ...  2,5            0,4  ...  ...  ...  ...
                                        0,5  ...  ...  ...  ...  ...
...  ...  ...  ...  ...  3,5            1,5  ...  ...  ...  ...
                                        2,5  ...  ...  ...
...  ...  ...  ...  ...  4,5            3,5  ...  ...
                                        4,5  ...
...  ...  ...  ...  ...  5,5            5,5

As can be seen above, the first antidiagonal begins at the first row and first column (0, 0), and for the following positions, at first only the column coordinate is incremented, and only after reaching the last column (= 5 = n - 1) the row coordinate starts to be incremented instead.

So, the logic to obtain the next starting position is to increment the column coordinate if it is smaller than 5 (< n - 1), or else increment the row coordinate.

In conclusion, the entire logic to traverse the grid through its antidiagonals can be written as:

dimension: int = 6  # Dimension of the grid
i: int = 0  # row of the starting position of the current antidiagonal
j: int = 0  # column of the starting position of the current antidiagonal
row: int = i  # current row of the grid
column: int = j  # current column of the grid
for number in sorted_numbers:
    grid[row][column] = number
    # Go to the next position along the current antidiagonal:
    row += 1
    column -= 1
    # If the end of the current antidiagonal has been reached:
    if row == dimension or column == -1:
        # Update the starting point for the next antidiagonal:
        if j < dimension - 1:
            j += 1
        else:
            i += 1
        # The next position is at the new starting point:
        row = i
        column = j
79827565
Vote

Why does it work?

The method consists of sorting the provided list of numbers in descending order, and then filling the grid along its antidiagonals in sequence, and if the strictly descending rule in either direction is broken at any position of the grid then it is impossible to sort the grid.

But this impossibility is not immediately obvious, so let's prove it:

The condition for the rule to be broken for a given list of numbers, when placed this way in the grid, is that there must be enough repetitions of one number in the list so that the number ends up being placed beside itself in the grid.

For example, this sorted list of numbers:

[36, 35, 34, 33, 32, 31, 30, 29, 29, 29, 29, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5]

Would fill the 6x6 grid this way:

36  35  33  30  29  25
34  32  29  29  24  19
31  29  28  23  18  14
29  27  22  17  13  10
26  21  16  12   9   7
20  15  11   8   6   5

And the second row of the grid breaks the descending rule, because there are two numbers 29 next to each other in it. And that happened because the number 29 is repeated enough times in the list of numbers for it to happen:

 .   .   .   .  29   .
 .   .  29  29   .   .
 .  29   .   .   .   .
29   .   .   .   .   .
 .   .   .   .   .   .
 .   .   .   .   .   .

The number of times a number can repeat depends on where in the grid the number is first placed, increasing the further away from the upper left corner and bottom right corner it is.

If the descending rule is broken for a list of numbers when placed in the grid according to this method, we must demonstrate that it's also impossible to rearrange the numbers in the grid so that the descending rule isn't broken for any position in the grid, to prove that it's impossible to sort these numbers into the grid.

For that, let's take a generalized case where the descending rule is broken only once in the grid (like the example above) as the best scenario where we might be able to rearrange the numbers to find a valid sorted grid without breaking the rule anywhere.

We can designate the number that was repeated enough times in the list to break the rule with the letter N. And an example grid arrangement would be:

 .   .   .   .   .   N
 .   .   .   .   N   .
 .   .   N   N   .   .
 .   N   .   .   .   .
 N   .   .   .   .   . 
 .   .   .   .   .   .

Where the rule is broken only once in the grid, in the third row.

And, in that case, all the numbers placed in the grid before N must be bigger than N, and all numbers placed after N must be smaller than N. So, let's designate the positions of the grid with bigger numbers with the letter B, and with the letter S those with smaller numbers.

 B   B   B   B   B   N
 B   B   B   B   N   S
 B   B   N   N   S   S
 B   N   S   S   S   S
 N   S   S   S   S   S 
 S   S   S   S   S   S
 
Where B > N > S

Given this kind of grid arrangement we can say that the descending rule is satisfied for 2 adjacent positions if they are placed as:

Horizontally:
B N  or  N S  or  B S  or  B B  or  S S

Vertically:
B      N      B      B      S
N  or  S  or  S  or  B  or  S

And they break the rule if placed as:

Horizontally:
N B  or  S N  or  N N  or  S B

Vertically:
N      S      N      S
B  or  N  or  N  or  B

Our grid breaks the rule with two equal numbers placed next to each other horizontally, as N N, and to be able to arrange a valid grid we need to swap at least one of these Ns with numbers in other positions without creating new rule breaking pairs. But that is impossible.

If we swap an N with a number in another position along its antidiagonal, for example, it will inevitably be placed next to another N, breaking the rule:

 B   B   B   B   B   N
 B   B   B   B   N   S
 B   B   N   S   S   S
 B   N   S   S   S   S
 N   N   S   S   S   S 
 S   S   S   S   S   S

And if it's swapped with any other position in the grid that isn't next to an N, it will inevitably create one of the other rule breaking pair situations, because it would invert the order placing a smaller number before a bigger one in a row and/or column:

 B   B   B   B   B   N
 B   B   B   B   N   S
 B   B   N   S   S   S
 B   N   S   N   S   S
 N   S   S   S   S   S 
 S   S   S   S   S   S

So we can conclude that if it isn't possible to arrange a list of numbers into a strictly descending grid using this method, then it is impossible to arrange the list of numbers into a strictly descending grid.

79827849
Vote

Amazingly detailed and thorough! If that doesn't get you sainted right away - or at least a knighthood - then I don't know what will. ;-)

79818139
Vote
  • 86 cases out of 100 were impossible to sort in a 6×6 grid.
  1. Each case (each flat array with 36 integers) is sorted in descending order using quick-sort.

  2. Then, a brute-force method is used for sorting 6×6 grid.

  3. No need to try to sort 6×6 grid, if the first two or the last two integers are equal, after the case (flat array with 36 integers) is sorted.

code:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <time.h>

#define DATA_ROWS 100
#define DATA_COLS 36
#define DATA_GRID 6
#define DATA_FILE_NAME "RandomNumbers.txt"

void
timeElapsedPrint(
    clock_t dc
) {
    int hh, mm, ss, ms;

    ms = (int)dc;
    ss = ms / 1000;
    ms %= 1000;
    mm = ss / 60;
    ss %= 60;
    hh = mm / 60;
    mm %= 60;
    printf(" cpu time elapsed : %03d:%02d:%02d.%03d\n", hh, mm, ss, ms);
    return;
}

bool
dataReadFromFile(
    int data[DATA_ROWS][DATA_COLS]
) {
    bool retVal = true;
    FILE* dataFile = NULL;
    int row = 0, col = 0;
    char c;

    if (fopen_s(&dataFile, "./"DATA_FILE_NAME, "r") != 0) {
        printf("failed to read data file %s\n", DATA_FILE_NAME);
        retVal = false;
    }
    else {
        while (fscanf_s(dataFile, "%c", &c, 1) != EOF) {
            if (c == '[') {
                while (col < DATA_COLS - 1) {
                    fscanf_s(dataFile, "%i,", &data[row][col++]);
                }

                fscanf_s(dataFile, "%i]", &data[row++][col]);
                col = 0;
            }
        }

        fclose(dataFile);
    }

    return(retVal);
}

void
dataSortRows(
    int data[DATA_ROWS][DATA_COLS],
    int row,
    int lo,
    int hi
) {
    // using quick sort
    int tmpLo = lo, tmpHi = hi, tmp = data[row][lo];
    bool pivotLo = true;

    while (tmpLo < tmpHi) {
        if (pivotLo) {
            if (data[row][tmpLo] < data[row][tmpHi]) {
                data[row][tmpLo] = data[row][tmpHi];
                data[row][tmpHi] = tmp;
                pivotLo = !pivotLo;
                tmpLo++;
            }
            else {
                tmpHi--;
            }
        }
        else {
            if (data[row][tmpLo] < data[row][tmpHi]) {
                data[row][tmpHi] = data[row][tmpLo];
                data[row][tmpLo] = tmp;
                pivotLo = !pivotLo;
                tmpHi--;
            }
            else {
                tmpLo++;
            }
        }
    }

    if (pivotLo) {
        tmpHi++;
    }
    else {
        tmpLo--;
    }

    if (lo < tmpLo) {
        dataSortRows(data, row, lo, tmpLo);
    }

    if (hi > tmpHi) {
        dataSortRows(data, row, tmpHi, hi);
    }

    return;
}

void
dataPrintRow(
    int data[DATA_ROWS][DATA_COLS],
    int row
) {
    int col = 0;
    printf("%2d", data[row][col++]);

    while (col < DATA_COLS) {
        printf(", %2d", data[row][col++]);
    }

    printf("\n");
    return;
}

void
dataPrintGrid(
    int grid[DATA_GRID][DATA_GRID]
) {
    int row, col;

    for (row = 0; row < DATA_GRID; row++) {
        for (col = 0; col < DATA_GRID; col++) {
            printf(" %2d", grid[row][col]);
        }

        printf("\n");
    }

    return;
}

bool
dataSortGrid(
    int data[DATA_ROWS][DATA_COLS],
    int row,
    int grid[DATA_GRID][DATA_GRID]
) {
    bool sorted = true;
    int dTmp[DATA_COLS], count = 0, gRow, gCol, col, last;

    if (data[row][0] == data[row][1] || data[row][DATA_COLS - 1] == data[row][DATA_COLS - 2]) {
        sorted = false;
    }
    else {
        memcpy(dTmp, data[row], DATA_COLS * sizeof(int));

        for (gRow = 0; gRow < DATA_GRID; gRow++) {
            last = data[row][0] + 1;

            for (gCol = 0; gCol < DATA_GRID; gCol++) {
                for (col = 0; col < DATA_COLS; col++) {
                    if (dTmp[col] != -1 && dTmp[col] < last) {
                        if (gRow > 0) {
                            if (dTmp[col] < grid[gRow - 1][gCol]) {
                                grid[gRow][gCol] = dTmp[col];
                                last = dTmp[col];
                                dTmp[col] = -1;
                                count++;
                                break;
                            }
                        }
                        else {
                            grid[gRow][gCol] = dTmp[col];
                            last = dTmp[col];
                            dTmp[col] = -1;
                            count++;
                            break;
                        }
                    }
                }
            }
        }

        if (count < DATA_COLS) {
            sorted = false;
        }
    }

    return(sorted);
}

void
dataSort(
    int data[DATA_ROWS][DATA_COLS]
) {
    int row, impCount = 0;
    int grid[DATA_GRID][DATA_GRID];

    for (row = 0; row < DATA_ROWS; row++) {
        printf("case: %3d\n", row + 1);
        //dataPrintRow(data, row);
        dataSortRows(data, row, 0, DATA_COLS - 1);
        //dataPrintRow(data, row);

        if (dataSortGrid(data, row, grid) == true) {
            dataPrintGrid(grid);
            //getchar();
        }
        else {
            impCount++;
            printf("Sort is impossible for case %d.\n", row + 1);
        }

        printf("\n");
    }

    printf("Sorting was impossible for %d cases.\n", impCount);
    return;
}

int
main(
    int argc,
    char* argv[]
) {
    clock_t c0, c1;
    int data[DATA_ROWS][DATA_COLS] = { 0 };

    if (dataReadFromFile(data)) {
        c0 = clock();
        dataSort(data);
        c1 = clock();
        timeElapsedPrint(c1 - c0);
    }

    return(0);
}
79818181
Vote

There are more cases where runs of equal values prevent a rule-conforming assignment of values to the 6 x 6 matrix. You have found only a small fraction of the impossible cases.

I would recommend the strategy of actually checking your results for rule conformance instead of deciding that they must be good based on a half-baked intuition. ;-)

79819104
Vote

@DarthGizka I agree that @ssd's algorithm is giving the wrong answer and needs more rigorous testing, but 86 is not an under-estimate, it's an over-estimate. That confuses me because, as you say, "there are more cases where runs of equal values prevent a rule-conforming".

79819247
Vote

@dumbledad: you are right, of course. I misread the statement with the number 86 because I was focussed on point 3 in @ssd's description, which was the only reference to rejecting stuff as impossible. The code is so convoluted and needlessly messy that my brain shut down while parsing it, and so I gave up on trying to understand it.

79818087
Vote
from collections import Counter

# --------------------------------------------------------------------------------
# Thoughts: The smallest number can only have 1 entry, any more than that and
# it will be duplicated across either a row or column.
#
# That restriction will apply for the next smallest number, it can only have
# a max of two, or it will duplicate across a row or column.
#
# So the rule(s) will be:
#   The lowest can have no more than 1
#   The second lowest can have no more than 2
#   The third  lowest can have no more than 3
#   The fourth lowest can have no more than 4
#   The fifth  lowest can have no more than 5
#   The sixth  lowest can have no more than 6
#
# This is true for the largest numbers, there can only be one of the max value, two
# of the second largest value, etc.
#
# The 'descending' requirement will imply that the largest numbers will cluster
# to the upper left and the lower numbers will cluster to the lower right.
#
# Assign numbers, highest to lowest, start from upper moving right across,
# then down to the first open grid entry. If a duplicate is detected skip
# to the first open grid entry on the next row, for that number only!
#
# If you skip past the bottom, there was flaw in my logic above.


# --------------------------------------------------------------------------------
# Need to access the original list of random numbers, this works for smaller lists
# --------------------------------------------------------------------------------
def getOrigList():
    return [
        [54, 95, 98, 26, 3, 39, 77, 30, 83, 62, 20, 92, 61, 59, 26, 63, 92, 49, 38, 51, 99, 64, 65, 52, 98, 18, 90, 97,
         96, 13, 74, 3, 88, 88, 67, 10],
        [49, 13, 73, 54, 4, 98, 36, 33, 12, 22, 35, 18, 39, 83, 92, 77, 50, 77, 57, 64, 0, 35, 86, 98, 28, 1, 53, 59,
         28, 33, 56, 37, 98, 26, 81, 13],
        [95, 84, 44, 16, 42, 73, 0, 53, 14, 63, 81, 91, 42, 14, 13, 59, 91, 24, 99, 71, 73, 34, 60, 65, 82, 55, 16, 75,
         7, 18, 68, 6, 61, 6, 80, 41],
        [27, 63, 35, 81, 56, 24, 70, 27, 59, 13, 36, 62, 73, 6, 61, 86, 48, 40, 88, 71, 52, 1, 9, 57, 50, 40, 20, 10, 3,
         29, 19, 94, 99, 8, 74, 83],
        [46, 75, 78, 14, 89, 76, 37, 26, 85, 78, 81, 27, 99, 41, 96, 52, 21, 65, 71, 48, 60, 32, 48, 31, 85, 35, 88, 5,
         78, 22, 31, 97, 43, 80, 52, 45],
        [0, 98, 50, 12, 0, 83, 46, 66, 67, 23, 52, 55, 41, 95, 5, 17, 78, 98, 74, 45, 97, 98, 96, 54, 48, 79, 29, 0, 73,
         6, 16, 33, 20, 88, 9, 23],
        [9, 2, 10, 57, 79, 65, 65, 0, 19, 64, 3, 18, 20, 93, 10, 30, 9, 0, 40, 51, 87, 34, 52, 71, 28, 23, 73, 61, 77,
         60, 66, 91, 57, 58, 2, 9],
        [27, 63, 51, 6, 3, 10, 7, 36, 80, 51, 93, 71, 73, 25, 3, 77, 35, 56, 36, 36, 77, 97, 14, 1, 78, 83, 5, 51, 99,
         5, 93, 90, 1, 36, 83, 4],
        [89, 94, 67, 64, 31, 66, 59, 16, 80, 22, 78, 72, 56, 83, 98, 10, 9, 57, 23, 4, 80, 37, 65, 30, 71, 55, 42, 9,
         60, 18, 39, 58, 44, 79, 48, 29],
        [79, 51, 3, 82, 81, 58, 99, 88, 54, 88, 81, 5, 63, 79, 52, 64, 48, 64, 68, 11, 50, 66, 35, 71, 9, 86, 11, 97,
         42, 41, 0, 2, 56, 38, 15, 63],
        [94, 35, 12, 94, 79, 40, 91, 45, 37, 98, 43, 30, 80, 81, 87, 19, 74, 87, 93, 35, 88, 89, 79, 44, 6, 87, 27, 49,
         98, 44, 68, 39, 42, 87, 61, 84],
        [5, 37, 89, 80, 31, 40, 1, 10, 54, 67, 23, 1, 75, 43, 49, 27, 29, 69, 43, 41, 7, 16, 63, 70, 5, 61, 74, 87, 2,
         61, 50, 72, 91, 56, 12, 99],
        [43, 35, 83, 94, 69, 45, 76, 73, 83, 60, 80, 31, 59, 34, 39, 63, 35, 13, 94, 78, 2, 24, 87, 21, 36, 38, 55, 19,
         10, 82, 13, 95, 88, 54, 94, 75],
        [66, 10, 58, 21, 82, 10, 32, 91, 66, 65, 3, 12, 4, 38, 12, 96, 55, 54, 73, 16, 74, 41, 28, 49, 19, 98, 16, 90,
         93, 82, 56, 68, 14, 70, 31, 19],
        [13, 79, 47, 31, 79, 31, 56, 65, 94, 73, 57, 35, 74, 85, 84, 39, 24, 26, 12, 56, 46, 46, 71, 0, 57, 61, 77, 32,
         14, 1, 81, 71, 69, 66, 57, 69],
        [8, 39, 23, 14, 88, 44, 81, 46, 5, 26, 50, 11, 71, 19, 86, 33, 88, 62, 81, 13, 60, 96, 7, 78, 6, 88, 77, 94, 74,
         63, 48, 40, 29, 47, 64, 6],
        [95, 36, 61, 3, 75, 84, 95, 8, 57, 42, 43, 77, 27, 65, 56, 78, 34, 96, 18, 23, 46, 17, 86, 17, 89, 28, 96, 18,
         24, 90, 93, 49, 47, 69, 91, 48],
        [76, 95, 10, 10, 58, 67, 25, 41, 0, 49, 13, 40, 59, 29, 62, 64, 97, 47, 22, 42, 39, 44, 16, 95, 23, 91, 14, 48,
         90, 39, 16, 92, 46, 38, 49, 16],
        [60, 42, 28, 28, 61, 10, 37, 90, 99, 9, 45, 15, 61, 20, 6, 89, 99, 5, 34, 28, 58, 45, 10, 43, 73, 5, 45, 78, 68,
         48, 44, 56, 78, 69, 52, 99],
        [99, 92, 63, 87, 23, 73, 25, 25, 31, 97, 14, 12, 77, 96, 73, 80, 86, 15, 63, 71, 44, 34, 51, 28, 77, 24, 19, 74,
         87, 34, 59, 40, 82, 13, 25, 15],
        [48, 59, 63, 45, 51, 64, 88, 99, 81, 29, 69, 27, 7, 28, 9, 77, 50, 80, 7, 64, 3, 24, 6, 22, 31, 69, 92, 66, 13,
         3, 70, 81, 73, 50, 45, 42],
        [0, 49, 29, 50, 38, 38, 24, 71, 8, 5, 56, 6, 90, 2, 3, 35, 40, 89, 24, 27, 74, 77, 54, 7, 1, 76, 92, 16, 55, 23,
         47, 62, 33, 1, 80, 47],
        [1, 61, 12, 89, 56, 47, 88, 63, 73, 49, 9, 78, 68, 69, 19, 53, 76, 39, 49, 83, 38, 70, 62, 79, 19, 7, 70, 4, 90,
         57, 90, 20, 52, 37, 64, 17],
        [0, 99, 18, 20, 0, 5, 93, 66, 87, 4, 62, 47, 94, 27, 73, 82, 12, 37, 39, 63, 59, 71, 71, 36, 84, 53, 90, 93, 9,
         21, 94, 76, 80, 4, 40, 30],
        [57, 17, 99, 26, 7, 0, 81, 29, 95, 51, 46, 8, 16, 19, 15, 48, 89, 65, 69, 14, 94, 9, 3, 78, 59, 20, 41, 45, 97,
         99, 57, 52, 94, 12, 55, 28],
        [19, 49, 58, 20, 73, 65, 0, 72, 82, 12, 64, 43, 34, 58, 11, 74, 20, 75, 0, 23, 6, 25, 81, 39, 44, 65, 54, 57,
         72, 72, 10, 69, 31, 10, 45, 20],
        [68, 46, 13, 68, 81, 62, 28, 75, 66, 91, 27, 31, 20, 38, 1, 45, 76, 79, 14, 62, 58, 66, 17, 79, 61, 91, 86, 33,
         57, 95, 74, 7, 31, 85, 97, 80],
        [67, 31, 55, 44, 11, 39, 50, 79, 64, 75, 97, 13, 22, 19, 42, 58, 55, 10, 51, 37, 73, 55, 22, 40, 35, 97, 77, 92,
         43, 24, 69, 25, 64, 61, 48, 77],
        [7, 17, 84, 29, 87, 12, 85, 22, 65, 70, 73, 14, 32, 9, 27, 3, 11, 42, 88, 20, 37, 10, 88, 77, 68, 92, 71, 80,
         83, 32, 35, 85, 91, 52, 26, 73],
        [62, 24, 97, 27, 49, 2, 50, 36, 14, 59, 63, 1, 45, 98, 80, 64, 59, 80, 55, 96, 87, 89, 19, 81, 40, 31, 73, 48,
         29, 34, 63, 11, 12, 7, 84, 28],
        [23, 82, 3, 66, 59, 65, 49, 80, 16, 73, 39, 69, 45, 15, 6, 14, 4, 97, 76, 57, 34, 13, 77, 72, 98, 24, 34, 54,
         23, 41, 67, 6, 80, 19, 30, 92],
        [20, 35, 58, 63, 21, 75, 58, 8, 30, 44, 97, 21, 3, 86, 78, 89, 93, 42, 29, 89, 53, 17, 89, 6, 8, 14, 48, 98, 15,
         58, 28, 46, 51, 55, 17, 78],
        [42, 41, 8, 12, 37, 81, 33, 58, 59, 31, 3, 67, 77, 90, 6, 2, 14, 45, 49, 28, 79, 93, 7, 75, 52, 52, 46, 86, 98,
         77, 66, 38, 41, 11, 41, 2],
        [8, 45, 28, 85, 58, 99, 18, 86, 95, 16, 59, 45, 26, 35, 36, 96, 61, 82, 32, 20, 62, 47, 93, 3, 44, 71, 11, 11,
         31, 28, 42, 7, 18, 58, 40, 89],
        [87, 4, 99, 46, 73, 27, 7, 44, 26, 62, 15, 10, 14, 77, 97, 70, 58, 23, 85, 73, 76, 97, 6, 92, 52, 51, 9, 84, 29,
         56, 15, 38, 41, 7, 88, 76],
        [30, 0, 80, 70, 10, 78, 91, 80, 3, 42, 24, 70, 39, 7, 7, 43, 9, 2, 23, 96, 76, 87, 19, 11, 5, 10, 74, 10, 49,
         16, 34, 54, 40, 55, 75, 93],
        [92, 54, 58, 53, 99, 84, 53, 50, 56, 65, 10, 89, 19, 2, 6, 94, 44, 69, 67, 60, 79, 5, 30, 23, 15, 8, 48, 26, 32,
         31, 43, 59, 81, 9, 67, 93],
        [7, 58, 97, 4, 22, 36, 5, 83, 32, 69, 83, 54, 18, 48, 49, 43, 36, 37, 96, 0, 28, 18, 64, 56, 52, 97, 43, 95, 36,
         8, 48, 35, 60, 41, 48, 81],
        [50, 78, 66, 51, 45, 80, 65, 87, 0, 5, 87, 91, 34, 78, 47, 89, 51, 32, 88, 64, 52, 8, 86, 59, 11, 5, 1, 12, 57,
         87, 75, 83, 17, 69, 96, 61],
        [74, 18, 35, 33, 97, 4, 22, 39, 41, 10, 66, 59, 11, 71, 90, 28, 78, 66, 51, 25, 48, 89, 74, 62, 13, 19, 67, 99,
         19, 88, 15, 83, 26, 86, 31, 93],
        [93, 32, 27, 13, 61, 53, 49, 35, 59, 13, 54, 68, 75, 31, 18, 79, 33, 59, 87, 86, 14, 26, 21, 19, 12, 59, 75, 36,
         7, 71, 25, 25, 6, 85, 29, 99],
        [94, 78, 11, 70, 49, 22, 25, 67, 34, 65, 85, 58, 76, 10, 44, 22, 75, 72, 65, 54, 68, 60, 84, 52, 19, 26, 61, 69,
         88, 76, 37, 41, 81, 1, 23, 57],
        [15, 72, 24, 37, 95, 16, 76, 61, 34, 47, 68, 93, 18, 92, 32, 17, 20, 66, 51, 33, 65, 38, 71, 45, 81, 59, 34, 35,
         84, 37, 14, 6, 41, 60, 57, 54],
        [83, 86, 73, 77, 75, 67, 5, 92, 43, 13, 98, 92, 69, 80, 50, 25, 64, 0, 64, 25, 98, 40, 66, 77, 4, 18, 52, 50,
         28, 36, 17, 54, 5, 83, 2, 40],
        [25, 68, 57, 61, 55, 81, 56, 71, 95, 72, 37, 21, 91, 8, 23, 26, 38, 44, 45, 84, 37, 51, 13, 42, 90, 12, 67, 21,
         96, 31, 99, 97, 2, 90, 99, 56],
        [47, 90, 19, 59, 82, 32, 52, 99, 74, 8, 93, 18, 79, 22, 24, 63, 84, 50, 55, 86, 94, 23, 83, 65, 67, 48, 16, 15,
         81, 78, 7, 43, 12, 52, 58, 28],
        [54, 39, 86, 53, 24, 55, 72, 2, 6, 15, 78, 8, 35, 70, 59, 80, 74, 99, 95, 32, 44, 26, 47, 49, 48, 14, 95, 66,
         54, 76, 37, 81, 85, 37, 45, 7],
        [19, 38, 6, 31, 71, 53, 40, 85, 71, 52, 56, 25, 78, 32, 17, 85, 42, 24, 61, 42, 3, 54, 98, 68, 48, 39, 59, 59,
         12, 25, 96, 98, 15, 88, 44, 45],
        [62, 70, 19, 57, 56, 68, 7, 13, 53, 87, 68, 69, 77, 39, 23, 94, 42, 10, 1, 28, 43, 31, 42, 48, 75, 95, 28, 10,
         44, 50, 72, 47, 64, 96, 5, 63],
        [92, 85, 77, 92, 90, 27, 39, 57, 51, 41, 99, 78, 78, 53, 88, 59, 30, 65, 15, 25, 32, 32, 99, 64, 90, 40, 13, 45,
         41, 73, 98, 12, 44, 73, 33, 32],
        [97, 36, 97, 58, 74, 56, 70, 80, 92, 84, 93, 16, 0, 34, 96, 85, 84, 16, 29, 22, 27, 42, 26, 40, 27, 80, 1, 40,
         82, 25, 54, 31, 77, 25, 67, 73],
        [46, 91, 13, 50, 65, 68, 44, 15, 65, 58, 77, 21, 92, 70, 69, 95, 9, 84, 69, 71, 53, 65, 0, 33, 95, 4, 1, 28, 62,
         27, 39, 38, 47, 39, 61, 81],
        [37, 0, 70, 66, 14, 20, 50, 68, 8, 0, 62, 41, 68, 35, 14, 69, 94, 62, 53, 84, 32, 22, 80, 81, 22, 66, 36, 65,
         40, 53, 93, 0, 0, 33, 32, 7],
        [68, 73, 37, 13, 86, 20, 22, 97, 27, 10, 32, 57, 27, 11, 52, 7, 7, 48, 23, 14, 98, 25, 41, 6, 78, 63, 80, 38,
         24, 75, 2, 61, 45, 93, 18, 94],
        [20, 14, 76, 73, 80, 30, 56, 33, 80, 18, 79, 66, 39, 3, 88, 25, 28, 24, 63, 88, 68, 28, 67, 49, 6, 18, 4, 49, 0,
         96, 11, 22, 6, 41, 17, 50],
        [9, 61, 45, 7, 25, 86, 99, 39, 79, 13, 46, 74, 44, 3, 90, 43, 25, 9, 2, 27, 13, 15, 38, 98, 2, 88, 13, 51, 44,
         80, 67, 85, 84, 40, 2, 68],
        [22, 48, 11, 46, 99, 88, 75, 32, 69, 66, 73, 10, 3, 31, 13, 44, 11, 17, 68, 0, 37, 86, 40, 92, 13, 61, 24, 69,
         22, 11, 53, 1, 14, 53, 96, 29],
        [65, 27, 91, 56, 76, 11, 86, 34, 3, 15, 97, 42, 19, 98, 38, 78, 90, 37, 76, 55, 46, 18, 72, 92, 3, 38, 55, 54,
         5, 0, 58, 24, 77, 70, 65, 55],
        [33, 48, 21, 34, 42, 60, 82, 33, 98, 27, 51, 33, 74, 55, 59, 96, 44, 35, 23, 28, 13, 52, 72, 9, 39, 52, 8, 30,
         40, 8, 97, 43, 79, 89, 38, 80],
        [1, 29, 67, 37, 13, 29, 33, 96, 91, 24, 4, 67, 20, 71, 75, 95, 2, 63, 39, 14, 88, 2, 5, 17, 38, 40, 74, 79, 39,
         62, 38, 58, 74, 4, 27, 97],
        [86, 8, 5, 54, 58, 78, 70, 51, 89, 94, 51, 55, 27, 6, 56, 44, 14, 72, 5, 27, 19, 50, 72, 58, 66, 24, 49, 28, 15,
         12, 12, 37, 85, 89, 53, 38],
        [54, 1, 82, 23, 72, 55, 6, 96, 54, 22, 19, 63, 83, 50, 39, 75, 33, 29, 83, 14, 60, 92, 62, 83, 11, 34, 53, 77,
         57, 63, 18, 17, 50, 9, 90, 36],
        [60, 78, 25, 81, 18, 1, 96, 39, 36, 82, 23, 78, 70, 80, 19, 55, 74, 38, 99, 37, 3, 87, 21, 26, 93, 89, 44, 13,
         95, 92, 11, 71, 77, 10, 49, 90],
        [68, 68, 45, 82, 67, 7, 97, 49, 87, 83, 73, 70, 70, 87, 14, 37, 10, 21, 82, 71, 75, 13, 89, 93, 63, 11, 40, 18,
         32, 69, 38, 53, 81, 63, 51, 76],
        [25, 36, 27, 62, 4, 51, 50, 74, 19, 10, 78, 94, 15, 49, 11, 26, 91, 80, 61, 80, 84, 87, 80, 52, 35, 28, 64, 91,
         39, 58, 15, 55, 26, 72, 68, 35],
        [42, 66, 36, 17, 5, 31, 38, 90, 61, 8, 24, 0, 7, 40, 65, 67, 54, 61, 53, 16, 49, 76, 21, 63, 23, 72, 20, 9, 42,
         34, 10, 6, 63, 25, 61, 28],
        [9, 98, 52, 95, 85, 61, 87, 96, 64, 98, 98, 83, 88, 4, 73, 29, 26, 67, 59, 34, 89, 49, 6, 16, 0, 61, 55, 76, 73,
         64, 26, 63, 56, 64, 66, 86],
        [98, 2, 10, 34, 9, 10, 8, 46, 2, 95, 89, 65, 49, 1, 38, 15, 8, 22, 66, 80, 7, 77, 77, 70, 1, 7, 60, 59, 93, 7,
         2, 98, 31, 95, 87, 18],
        [47, 20, 77, 92, 92, 78, 81, 7, 34, 20, 30, 40, 56, 79, 86, 84, 81, 40, 19, 28, 72, 35, 20, 85, 3, 68, 18, 4,
         63, 83, 20, 12, 41, 63, 19, 58],
        [55, 10, 67, 18, 31, 16, 76, 57, 79, 64, 68, 37, 78, 60, 60, 46, 49, 32, 32, 3, 65, 74, 22, 79, 26, 29, 28, 86,
         20, 99, 27, 99, 28, 30, 54, 20],
        [73, 87, 66, 32, 10, 75, 40, 94, 30, 99, 52, 10, 33, 33, 52, 36, 16, 90, 68, 62, 19, 33, 50, 22, 78, 47, 91, 22,
         84, 83, 41, 17, 32, 83, 38, 23],
        [82, 26, 41, 53, 71, 22, 95, 55, 60, 14, 40, 42, 36, 43, 91, 50, 16, 93, 62, 72, 3, 14, 55, 48, 20, 17, 56, 38,
         64, 87, 86, 92, 82, 75, 73, 76],
        [70, 18, 42, 41, 19, 44, 8, 90, 10, 73, 41, 39, 23, 69, 64, 55, 39, 80, 88, 13, 5, 29, 71, 53, 84, 71, 91, 97,
         60, 67, 10, 15, 53, 37, 68, 91],
        [12, 99, 93, 43, 63, 51, 54, 89, 39, 8, 19, 27, 70, 94, 0, 70, 76, 1, 51, 30, 60, 88, 24, 69, 35, 36, 97, 43, 0,
         70, 21, 84, 19, 6, 93, 92],
        [15, 83, 14, 61, 0, 18, 77, 34, 95, 92, 22, 76, 54, 9, 22, 43, 96, 91, 24, 12, 30, 22, 88, 72, 82, 38, 27, 10,
         41, 2, 78, 25, 36, 20, 70, 55],
        [83, 6, 84, 58, 57, 42, 76, 75, 36, 39, 98, 55, 72, 72, 84, 81, 36, 9, 3, 44, 1, 50, 63, 1, 93, 24, 26, 20, 30,
         68, 0, 24, 90, 26, 6, 88],
        [58, 38, 65, 42, 40, 25, 32, 39, 19, 31, 74, 36, 85, 74, 23, 20, 37, 41, 41, 63, 61, 9, 27, 39, 22, 0, 36, 34,
         53, 53, 6, 40, 81, 18, 86, 8],
        [34, 1, 53, 24, 53, 46, 21, 59, 74, 75, 10, 49, 79, 74, 29, 68, 82, 75, 49, 62, 8, 58, 54, 34, 87, 4, 84, 34,
         10, 82, 70, 35, 62, 9, 33, 77],
        [28, 49, 3, 98, 69, 36, 80, 53, 72, 68, 89, 22, 40, 52, 5, 66, 39, 38, 41, 45, 13, 12, 70, 12, 7, 86, 95, 83,
         66, 92, 43, 13, 53, 80, 75, 33],
        [98, 98, 88, 3, 11, 32, 83, 24, 91, 79, 3, 55, 50, 95, 41, 69, 30, 89, 68, 47, 13, 35, 0, 86, 57, 8, 10, 31, 1,
         40, 81, 2, 87, 10, 73, 0],
        [36, 8, 65, 86, 88, 65, 19, 33, 62, 24, 98, 34, 0, 80, 45, 53, 16, 28, 41, 65, 93, 34, 64, 85, 48, 98, 15, 51,
         41, 65, 5, 9, 51, 17, 17, 91],
        [21, 49, 80, 99, 8, 32, 11, 36, 82, 59, 64, 59, 55, 73, 1, 23, 82, 59, 19, 16, 58, 18, 62, 36, 74, 30, 72, 79,
         26, 31, 16, 40, 2, 27, 65, 26],
        [86, 24, 59, 75, 93, 17, 20, 42, 21, 4, 80, 0, 57, 91, 81, 84, 95, 13, 65, 85, 9, 15, 26, 90, 66, 20, 13, 98,
         67, 27, 85, 49, 45, 65, 10, 84],
        [17, 16, 99, 46, 21, 66, 57, 69, 29, 42, 50, 92, 9, 11, 56, 62, 32, 15, 55, 25, 55, 90, 81, 74, 62, 98, 58, 65,
         46, 77, 53, 10, 0, 59, 70, 91],
        [76, 89, 89, 89, 87, 87, 11, 51, 11, 44, 11, 50, 29, 88, 93, 31, 6, 26, 74, 34, 24, 30, 14, 74, 9, 47, 20, 17,
         88, 14, 49, 87, 3, 65, 27, 73],
        [18, 18, 68, 23, 13, 98, 52, 92, 72, 75, 8, 8, 2, 33, 69, 23, 22, 16, 95, 76, 43, 83, 86, 27, 4, 58, 57, 97, 64,
         22, 43, 32, 41, 2, 88, 26],
        [21, 20, 85, 29, 56, 31, 65, 45, 58, 26, 62, 21, 71, 31, 5, 57, 88, 42, 51, 39, 79, 83, 47, 99, 25, 31, 9, 24,
         13, 63, 95, 78, 80, 74, 78, 89],
        [39, 90, 68, 22, 85, 14, 4, 20, 41, 51, 67, 75, 20, 48, 91, 65, 61, 44, 66, 3, 83, 30, 93, 23, 19, 99, 46, 88,
         87, 35, 3, 88, 35, 67, 88, 28],
        [63, 21, 64, 10, 7, 38, 25, 17, 32, 36, 7, 99, 46, 65, 74, 71, 63, 42, 30, 72, 29, 80, 42, 65, 27, 24, 16, 16,
         70, 2, 54, 60, 35, 79, 88, 39],
        [10, 75, 23, 44, 33, 33, 11, 13, 23, 3, 44, 37, 64, 66, 35, 32, 34, 22, 18, 15, 6, 37, 25, 36, 20, 4, 49, 58,
         59, 21, 80, 95, 0, 31, 93, 28],
        [54, 30, 99, 86, 7, 38, 8, 18, 26, 83, 15, 83, 45, 5, 24, 67, 6, 39, 65, 67, 83, 99, 29, 41, 64, 62, 25, 53, 54,
         34, 24, 41, 99, 28, 8, 29],
        [30, 60, 67, 20, 43, 56, 79, 43, 92, 85, 69, 9, 62, 22, 62, 24, 68, 33, 18, 61, 25, 14, 21, 59, 86, 59, 53, 26,
         1, 80, 9, 36, 4, 5, 85, 47],
        [57, 64, 8, 17, 69, 23, 77, 29, 69, 52, 80, 86, 18, 93, 78, 17, 36, 60, 94, 25, 80, 90, 87, 86, 64, 23, 87, 95,
         19, 69, 91, 82, 37, 27, 27, 46],
        [52, 19, 54, 87, 1, 4, 41, 68, 93, 56, 36, 13, 32, 25, 83, 48, 59, 5, 37, 58, 83, 93, 53, 77, 44, 63, 49, 1, 94,
         4, 28, 30, 85, 15, 85, 90],
        [75, 72, 89, 33, 98, 23, 81, 41, 35, 17, 4, 1, 46, 60, 83, 69, 27, 35, 33, 83, 61, 61, 21, 72, 82, 72, 82, 6,
         59, 51, 60, 37, 82, 20, 88, 54],
        [20, 37, 13, 75, 81, 78, 36, 75, 22, 45, 81, 63, 58, 72, 81, 7, 9, 39, 49, 8, 84, 66, 71, 58, 41, 56, 5, 2, 83,
         47, 16, 3, 93, 95, 97, 10],
        [94, 83, 74, 92, 8, 10, 12, 92, 28, 28, 31, 98, 10, 33, 62, 70, 85, 53, 8, 31, 75, 67, 38, 2, 5, 85, 44, 25, 54,
         69, 33, 61, 75, 57, 79, 82],
        [60, 34, 79, 9, 2, 28, 80, 24, 2, 76, 26, 34, 61, 22, 40, 31, 52, 14, 30, 2, 88, 54, 41, 73, 6, 45, 13, 22, 70,
         51, 74, 69, 19, 66, 33, 78],
        [3, 11, 50, 41, 23, 41, 45, 2, 62, 95, 55, 73, 1, 98, 33, 68, 82, 96, 24, 81, 1, 58, 59, 41, 45, 9, 99, 49, 16,
         97, 54, 75, 92, 14, 71, 63],
        [18, 73, 63, 61, 88, 15, 27, 49, 82, 95, 0, 54, 71, 76, 64, 65, 84, 39, 61, 56, 52, 60, 88, 92, 75, 83, 94, 61,
         76, 76, 14, 11, 5, 95, 71, 68],
    ]


# --------------------------------------------------------------------------------
# Global 'workgrid' works for this simple project, don't have to pass as args/param
# --------------------------------------------------------------------------------
workGrid = [
    [None, None, None, None, None, None],
    [None, None, None, None, None, None],
    [None, None, None, None, None, None],
    [None, None, None, None, None, None],
    [None, None, None, None, None, None],
    [None, None, None, None, None, None],
]

# --------------------------------------------------------------------------------
# Reset before each build
# --------------------------------------------------------------------------------
def resetWorkGrid():
    global workGrid
    workGrid = [
        [None, None, None, None, None, None],
        [None, None, None, None, None, None],
        [None, None, None, None, None, None],
        [None, None, None, None, None, None],
        [None, None, None, None, None, None],
        [None, None, None, None, None, None],
    ]

# --------------------------------------------------------------------------------
# Sort the list descending, need this to support 'build grid' processing
# --------------------------------------------------------------------------------
def getSortedlist():
    rtnList = []
    for origList in getOrigList():
        origList.sort(reverse=True)
        rtnList.append(origList)
    return rtnList

# --------------------------------------------------------------------------------
# Accept one list of 36 numbers and build the 6x6 grid
# --------------------------------------------------------------------------------
def buildSingleGrid(gridIndex: int, sortedList: list[list[int]]):
    resetWorkGrid()
    print('=================================')
    print(f'Processing list entry: {gridIndex}')
    gridNumbers = sortedList[gridIndex]
    print(gridNumbers)
    isValid = validateGrid(gridNumbers)
    if not isValid[0]:
        print(f'List at {gridIndex:>2} was not valid because - {isValid[1]}')
        return
    rowIdx = 0
    for intVal in gridNumbers:
        try:
            nextCol = getFirstOpenByRow(rowIdx)
            if workGrid[rowIdx][nextCol-1] == intVal:
                newCol = getFirstOpenByRow(rowIdx+1)
                workGrid[rowIdx+1][newCol] = intVal
            else:
                workGrid[rowIdx][nextCol] = intVal
                if nextCol > len(workGrid[0])-2:
                    rowIdx += 1
        except Exception as ex :
            print(f"Exception {ex} for intVal: {intVal}")
    displayGrid()

# --------------------------------------------------------------------------------
# Need this support skipping to next open col on following row, handle dupes
# --------------------------------------------------------------------------------
def getFirstOpenByRow(rowIdx: int) -> int:
    for colIdx in range(0, 6):
        if workGrid[rowIdx][colIdx] is None:
            return colIdx
    raise Exception("No open columns found")

# --------------------------------------------------------------------------------
# Check for combos that will always have a duplicate
# --------------------------------------------------------------------------------
def validateGrid(gridNumbers: list[int]):
    initCounts = Counter(gridNumbers)
    sortCounts = sorted(initCounts.items(), key=lambda item: item[0])
    #print(sortCounts)
    if sortCounts[0][1] > 1:
        return False, f"lowest number: {sortCounts[0][0]}, had more then 1 entry."
    if sortCounts[1][1] > 2:
        return False, f"second lowest number: {sortCounts[1][0]}, had more then 2 entries."
    if sortCounts[2][1] > 3:
        return False, f"third lowest number: {sortCounts[2][0]}, had more then 3 entries."
    if sortCounts[3][1] > 4:
        return False, f"fourth lowest number: {sortCounts[3][0]}, had more then 4 entries."
    if sortCounts[4][1] > 5:
        return False, f"fifth lowest number: {sortCounts[4][0]}, had more then 5 entries."
    if sortCounts[-1][1] > 1:
        return False, f"first largest number: {sortCounts[-1][0]}, had more then 1 entry."
    if sortCounts[-2][1] > 2:
        return False, f"second largest number: {sortCounts[-2][0]}, had more then 2 entries."
    if sortCounts[-3][1] > 3:
        return False, f"third largest number: {sortCounts[-3][0]}, had more then 3 entries."
    if sortCounts[-4][1] > 4:
        return False, f"fourth largest number: {sortCounts[-4][0]}, had more then 4 entries."
    if sortCounts[-5][1] > 5:
        return False, f"fifth largest number: {sortCounts[-5][0]}, had more then 5 entries."
    lastLine = sorted(gridNumbers)[0:6]
    lastCounts = Counter(lastLine)
    sortLastCounts = sorted(lastCounts.items(), key=lambda item: item[0])
    lastDupes = [x for x in sortLastCounts if x[1] > 1]
    if len(lastDupes) > 0:
        return False, f"dupes on the last line can never wrap down: {lastDupes}."
    return True, ""

# --------------------------------------------------------------------------------
# Display the grid, use padding to enhance readability
# --------------------------------------------------------------------------------
def displayGrid():
    print('---------------------------------')
    for row in range(0, 6):
        for col in range(0, 6):
            if col < 5:
                prtString = str(workGrid[row][col]).zfill(2) + ' | '
            else:
                prtString = str(workGrid[row][col]).zfill(2)
            print(f'{prtString}', end="")
        print("\n", end="")

# --------------------------------------------------------------------------------
# Loop over all the inputs and generate the grids or display errors
# --------------------------------------------------------------------------------
def processArrayAssignments():
    sortedList = getSortedlist()
    for index, sortList in enumerate(sortedList):
        buildSingleGrid(index, sortedList)

if __name__ == '__main__':
    processArrayAssignments()
79817865
Vote

Approach

One person's solved problem is another's "word problem". -- Unknown

I went crazy in order to solve this challenge. Thank you!

We want to arrange integers from d1 into a square matrix. Reverse-sorting d1 appeared crucial, however, breaking the ties was challenging.

The Invariant

Finding the invariant sometimes helps. Assuming 0-based indexing, initially I thought that the highest number must be at matrix[0][0] and smallest must be at matrix[rows-1][rows-1]. But I was not sure how to proceed. But after quite some deliberation (see pictures), I realized that thinking about ranking of the integers in d1 is crucial. Thus, the highest number must be at matrix[0][0] and it must be unique, otherwise either the 0th row or 0th column will violate the strictly decreasing sequence condition. Similarly, we can only accommodate at the most two next highest integers, in which case, we must place them at [0,1] and [1,0] or vice versa. Finding the invariant was then straightforward: populate the matrix diagonally (from bottom left to top right or top right to bottom left) with entries from a reverse sorted list in order.

The violation of this invariant signals impossibility because of this invariant: matrix[i-1][i-1]must be the highest element in the ixi sub-matrix and each row and column must be reverse sorted.

Implementation

My Python implementation is attached. I am still a Python novice, so, my code may not be idiomatic. But I have documented it properly. I admit, I discussed this problem with my wife and those discussions benefited both of us. In fairness, this is not entirely my solution. The thought of discussing this problem with an AI did touch my mind, but I resisted the temptation.

Code

def populate_matrix_diagonally(d1, rows):
    """
    Rearranges the given list of integers according to the rules of the challenge and returns a matrix.
    :param d1:
    :param rows:
    :return:
    Implementation notes: The given list must contain only integers. It is first reverse-sorted in place (rev_sorted).
    The returned matrix is filled from bottom left to top right by the numbers from rev_sorted. The number of non-principal
    diagonals, num_diag is clearly 2 * rows - 1 and each diagonal has first increasing and then decreasing number
    of numbers (len_diag) in it: 1, 2, 3, ..., rows, rows - 1, rows - 2, ..., 1.
    """
    # assumption: rows * rows = len(d1)
    d1.sort(reverse=True)
    rev_sorted = d1
    matrix = init_matrix(rows)
    i = 0  # index in the reverse-sorted 1-d list
    sri = sci = 0  # sri and sci are the starting (row, col) indices where a non-principal diagonal starts
    ri = sri
    ci = sci  # ri and ci are the (row, col) indices where a number is put in a diagonal
    num_diag = 2 * rows - 1  # number of diagonals of the matrix
    len_diag = 1  # number of numbers in each diagonal
    di = ei = 0  # di: index of a diagonal, ei: index of the element in that diagonal
    while di < num_diag:
        while ei < len_diag:
            num = rev_sorted[i]
            if ri > 0 and matrix[ri - 1][ci] == num:
                raise ValueError(f"Impossible! Repeated number {num} in the column at ({ri}, {ci})")
            if ci > 0 and matrix[ri][ci - 1] == num:
                raise ValueError(f"Impossible! Repeated number {num} in the row at ({ri}, {ci})")
            matrix[ri][ci] = num
            i += 1
            ei += 1
            ri -= 1
            ci += 1
        di += 1
        ei = 0
        if di <= rows - 1:
            len_diag += 1
            sri += 1
        else:
            len_diag -= 1
            sci += 1
        ri = sri
        ci = sci
    assert i == len(d1), f"The list must have been exhausted, but not! i: expected [{len(d1)}], found [{i}]"
    return matrix

Output

total number of impossible cases (from the 100): 45

(bonus)
[95, 75, 75, 74, 74, 74, 54, 45, 40]

[95, 75, 74]

[75, 74, 45]

[74, 54, 40]

[99, 98, 98, 97, 96, 95, 92, 92, 90, 88, 88, 83, 77, 74, 67, 65, 64, 63, 62, 61, 59, 54, 52, 51, 49, 39, 38, 30, 26, 26, 20, 18, 13, 10, 3, 3]

Impossible! Repeated number 3 in the column at (5, 5)

[98, 98, 98, 92, 86, 83, 81, 77, 77, 73, 64, 59, 57, 56, 54, 53, 50, 49, 39, 37, 36, 35, 35, 33, 33, 28, 28, 26, 22, 18, 13, 13, 12, 4, 1, 0]

Impossible! Repeated number 98 in the column at (1, 0)

[99, 95, 91, 91, 84, 82, 81, 80, 75, 73, 73, 71, 68, 65, 63, 61, 60, 59, 55, 53, 44, 42, 42, 41, 34, 24, 18, 16, 16, 14, 14, 13, 7, 6, 6, 0]

[99, 91, 82, 73, 63, 44]

[95, 84, 75, 65, 53, 24]

[91, 80, 68, 55, 34, 14]

[81, 71, 59, 41, 16, 7]

[73, 60, 42, 16, 13, 6]

[61, 42, 18, 14, 6, 0]

[99, 94, 88, 86, 83, 81, 74, 73, 71, 70, 63, 62, 61, 59, 57, 56, 52, 50, 48, 40, 40, 36, 35, 29, 27, 27, 24, 20, 19, 13, 10, 9, 8, 6, 3, 1]

[99, 88, 81, 70, 57, 40]

[94, 83, 71, 59, 40, 27]

[86, 73, 61, 48, 27, 13]

[74, 62, 50, 29, 19, 8]

[63, 52, 35, 20, 9, 3]

[56, 36, 24, 10, 6, 1]

[99, 97, 96, 89, 88, 85, 85, 81, 80, 78, 78, 78, 76, 75, 71, 65, 60, 52, 52, 48, 48, 46, 45, 43, 41, 37, 35, 32, 31, 31, 27, 26, 22, 21, 14, 5]

[99, 96, 85, 78, 71, 48]

[97, 88, 80, 75, 48, 37]

[89, 81, 76, 52, 41, 31]

[85, 78, 52, 43, 31, 22]

[78, 60, 45, 32, 26, 14]

[65, 46, 35, 27, 21, 5]

[98, 98, 98, 97, 96, 95, 88, 83, 79, 78, 74, 73, 67, 66, 55, 54, 52, 50, 48, 46, 45, 41, 33, 29, 23, 23, 20, 17, 16, 12, 9, 6, 5, 0, 0, 0]

Impossible! Repeated number 98 in the column at (1, 0)

[93, 91, 87, 79, 77, 73, 71, 66, 65, 65, 64, 61, 60, 58, 57, 57, 52, 51, 40, 34, 30, 28, 23, 20, 19, 18, 10, 10, 9, 9, 9, 3, 2, 2, 0, 0]

Impossible! Repeated number 0 in the column at (5, 5)

[99, 97, 93, 93, 90, 83, 83, 80, 78, 77, 77, 73, 71, 63, 56, 51, 51, 51, 36, 36, 36, 36, 35, 27, 25, 14, 10, 7, 6, 5, 5, 4, 3, 3, 1, 1]

Impossible! Repeated number 1 in the column at (5, 5)

[98, 94, 89, 83, 80, 80, 79, 78, 72, 71, 67, 66, 65, 64, 60, 59, 58, 57, 56, 55, 48, 44, 42, 39, 37, 31, 30, 29, 23, 22, 18, 16, 10, 9, 9, 4]

[98, 89, 80, 71, 60, 48]

[94, 80, 72, 64, 55, 31]

[83, 78, 65, 56, 37, 22]

[79, 66, 57, 39, 23, 10]

[67, 58, 42, 29, 16, 9]

[59, 44, 30, 18, 9, 4]

[99, 97, 88, 88, 86, 82, 81, 81, 79, 79, 71, 68, 66, 64, 64, 63, 63, 58, 56, 54, 52, 51, 50, 48, 42, 41, 38, 35, 15, 11, 11, 9, 5, 3, 2, 0]

[99, 88, 82, 79, 64, 52]

[97, 86, 79, 64, 54, 41]

[88, 81, 66, 56, 42, 11]

[81, 68, 58, 48, 15, 5]

[71, 63, 50, 35, 9, 2]

[63, 51, 38, 11, 3, 0]

[98, 98, 94, 94, 93, 91, 89, 88, 87, 87, 87, 87, 84, 81, 80, 79, 79, 74, 68, 61, 49, 45, 44, 44, 43, 42, 40, 39, 37, 35, 35, 30, 27, 19, 12, 6]

Impossible! Repeated number 98 in the column at (1, 0)

[99, 91, 89, 87, 80, 75, 74, 72, 70, 69, 67, 63, 61, 61, 56, 54, 50, 49, 43, 43, 41, 40, 37, 31, 29, 27, 23, 16, 12, 10, 7, 5, 5, 2, 1, 1]

Impossible! Repeated number 1 in the column at (5, 5)

[95, 94, 94, 94, 88, 87, 83, 83, 82, 80, 78, 76, 75, 73, 69, 63, 60, 59, 55, 54, 45, 43, 39, 38, 36, 35, 35, 34, 31, 24, 21, 19, 13, 13, 10, 2]

Impossible! Repeated number 94 in the column at (2, 0)

[98, 96, 93, 91, 90, 82, 82, 74, 73, 70, 68, 66, 66, 65, 58, 56, 55, 54, 49, 41, 38, 32, 31, 28, 21, 19, 19, 16, 16, 14, 12, 12, 10, 10, 4, 3]

[98, 93, 82, 70, 58, 38]

[96, 90, 73, 65, 41, 19]

[91, 74, 66, 49, 21, 14]

[82, 66, 54, 28, 16, 10]

[68, 55, 31, 16, 12, 4]

[56, 32, 19, 12, 10, 3]

[94, 85, 84, 81, 79, 79, 77, 74, 73, 71, 71, 69, 69, 66, 65, 61, 57, 57, 57, 56, 56, 47, 46, 46, 39, 35, 32, 31, 31, 26, 24, 14, 13, 12, 1, 0]

[94, 84, 79, 71, 65, 56]

[85, 79, 73, 66, 56, 35]

[81, 74, 69, 57, 39, 26]

[77, 69, 57, 46, 31, 13]

[71, 57, 46, 31, 14, 1]

[61, 47, 32, 24, 12, 0]

[96, 94, 88, 88, 88, 86, 81, 81, 78, 77, 74, 71, 64, 63, 62, 60, 50, 48, 47, 46, 44, 40, 39, 33, 29, 26, 23, 19, 14, 13, 11, 8, 7, 6, 6, 5]

Impossible! Repeated number 88 in the column at (1, 1)

[96, 96, 95, 95, 93, 91, 90, 89, 86, 84, 78, 77, 75, 69, 65, 61, 57, 56, 49, 48, 47, 46, 43, 42, 36, 34, 28, 27, 24, 23, 18, 18, 17, 17, 8, 3]

Impossible! Repeated number 96 in the column at (1, 0)

[97, 95, 95, 92, 91, 90, 76, 67, 64, 62, 59, 58, 49, 49, 48, 47, 46, 44, 42, 41, 40, 39, 39, 38, 29, 25, 23, 22, 16, 16, 16, 14, 13, 10, 10, 0]

[97, 95, 90, 62, 48, 40]

[95, 91, 64, 49, 41, 25]

[92, 67, 49, 42, 29, 16]

[76, 58, 44, 38, 16, 13]

[59, 46, 39, 22, 14, 10]

[47, 39, 23, 16, 10, 0]

[99, 99, 99, 90, 89, 78, 78, 73, 69, 68, 61, 61, 60, 58, 56, 52, 48, 45, 45, 45, 44, 43, 42, 37, 34, 28, 28, 28, 20, 15, 10, 10, 9, 6, 5, 5]

Impossible! Repeated number 99 in the column at (1, 0)

[99, 97, 96, 92, 87, 87, 86, 82, 80, 77, 77, 74, 73, 73, 71, 63, 63, 59, 51, 44, 40, 34, 34, 31, 28, 25, 25, 25, 24, 23, 19, 15, 15, 14, 13, 12]

[99, 96, 87, 77, 71, 40]

[97, 87, 80, 73, 44, 25]

[92, 82, 73, 51, 28, 23]

[86, 74, 59, 31, 24, 15]

[77, 63, 34, 25, 15, 13]

[63, 34, 25, 19, 14, 12]

[99, 92, 88, 81, 81, 80, 77, 73, 70, 69, 69, 66, 64, 64, 63, 59, 51, 50, 50, 48, 45, 45, 42, 31, 29, 28, 27, 24, 22, 13, 9, 7, 7, 6, 3, 3]

Impossible! Repeated number 3 in the column at (5, 5)

[92, 90, 89, 80, 77, 76, 74, 71, 62, 56, 55, 54, 50, 49, 47, 47, 40, 38, 38, 35, 33, 29, 27, 24, 24, 23, 16, 8, 7, 6, 5, 3, 2, 1, 1, 0]

[92, 89, 76, 56, 47, 33]

[90, 77, 62, 49, 35, 23]

[80, 71, 50, 38, 24, 6]

[74, 54, 38, 24, 7, 2]

[55, 40, 27, 8, 3, 1]

[47, 29, 16, 5, 1, 0]

[90, 90, 89, 88, 83, 79, 78, 76, 73, 70, 70, 69, 68, 64, 63, 62, 61, 57, 56, 53, 52, 49, 49, 47, 39, 38, 37, 20, 19, 19, 17, 12, 9, 7, 4, 1]

Impossible! Repeated number 90 in the column at (1, 0)

[99, 94, 94, 93, 93, 90, 87, 84, 82, 80, 76, 73, 71, 71, 66, 63, 62, 59, 53, 47, 40, 39, 37, 36, 30, 27, 21, 20, 18, 12, 9, 5, 4, 4, 0, 0]

Impossible! Repeated number 0 in the column at (5, 5)

[99, 99, 97, 95, 94, 94, 89, 81, 78, 69, 65, 59, 57, 57, 55, 52, 51, 48, 46, 45, 41, 29, 28, 26, 20, 19, 17, 16, 15, 14, 12, 9, 8, 7, 3, 0]

Impossible! Repeated number 99 in the column at (1, 0)

[82, 81, 75, 74, 73, 72, 72, 72, 69, 65, 65, 64, 58, 58, 57, 54, 49, 45, 44, 43, 39, 34, 31, 25, 23, 20, 20, 20, 19, 12, 11, 10, 10, 6, 0, 0]

Impossible! Repeated number 0 in the column at (5, 5)

[97, 95, 91, 91, 86, 85, 81, 80, 79, 79, 76, 75, 74, 68, 68, 66, 66, 62, 62, 61, 58, 57, 46, 45, 38, 33, 31, 31, 28, 27, 20, 17, 14, 13, 7, 1]

[97, 91, 85, 79, 68, 58]

[95, 86, 79, 68, 61, 33]

[91, 80, 74, 62, 38, 27]

[81, 75, 62, 45, 28, 14]

[76, 66, 46, 31, 17, 7]

[66, 57, 31, 20, 13, 1]

[97, 97, 92, 79, 77, 77, 75, 73, 69, 67, 64, 64, 61, 58, 55, 55, 55, 51, 50, 48, 44, 43, 42, 40, 39, 37, 35, 31, 25, 24, 22, 22, 19, 13, 11, 10]

Impossible! Repeated number 97 in the column at (1, 0)

[92, 91, 88, 88, 87, 85, 85, 84, 83, 80, 77, 73, 73, 71, 70, 68, 65, 52, 42, 37, 35, 32, 32, 29, 27, 26, 22, 20, 17, 14, 12, 11, 10, 9, 7, 3]

[92, 88, 85, 80, 70, 35]

[91, 87, 83, 71, 37, 26]

[88, 84, 73, 42, 27, 14]

[85, 73, 52, 29, 17, 10]

[77, 65, 32, 20, 11, 7]

[68, 32, 22, 12, 9, 3]

[98, 97, 96, 89, 87, 84, 81, 80, 80, 73, 64, 63, 63, 62, 59, 59, 55, 50, 49, 48, 45, 40, 36, 34, 31, 29, 28, 27, 24, 19, 14, 12, 11, 7, 2, 1]

[98, 96, 84, 73, 59, 45]

[97, 87, 80, 62, 48, 29]

[89, 80, 63, 49, 31, 19]

[81, 63, 50, 34, 24, 11]

[64, 55, 36, 27, 12, 2]

[59, 40, 28, 14, 7, 1]

[98, 97, 92, 82, 80, 80, 77, 76, 73, 72, 69, 67, 66, 65, 59, 57, 54, 49, 45, 41, 39, 34, 34, 30, 24, 23, 23, 19, 16, 15, 14, 13, 6, 6, 4, 3]

[98, 92, 80, 72, 59, 39]

[97, 80, 73, 65, 41, 23]

[82, 76, 66, 45, 24, 15]

[77, 67, 49, 30, 16, 6]

[69, 54, 34, 19, 13, 4]

[57, 34, 23, 14, 6, 3]

[98, 97, 93, 89, 89, 89, 86, 78, 78, 75, 63, 58, 58, 58, 55, 53, 51, 48, 46, 44, 42, 35, 30, 29, 28, 21, 21, 20, 17, 17, 15, 14, 8, 8, 6, 3]

[98, 93, 89, 75, 55, 42]

[97, 89, 78, 58, 44, 21]

[89, 78, 58, 46, 28, 17]

[86, 58, 48, 29, 17, 8]

[63, 51, 30, 20, 14, 6]

[53, 35, 21, 15, 8, 3]

[98, 93, 90, 86, 81, 79, 77, 77, 75, 67, 66, 59, 58, 52, 52, 49, 46, 45, 42, 41, 41, 41, 38, 37, 33, 31, 28, 14, 12, 11, 8, 7, 6, 3, 2, 2]

Impossible! Repeated number 2 in the column at (5, 5)

[99, 96, 95, 93, 89, 86, 85, 82, 71, 62, 61, 59, 58, 58, 47, 45, 45, 44, 42, 40, 36, 35, 32, 31, 28, 28, 26, 20, 18, 18, 16, 11, 11, 8, 7, 3]

[99, 95, 86, 62, 47, 36]

[96, 89, 71, 58, 40, 28]

[93, 82, 58, 42, 28, 18]

[85, 59, 44, 31, 18, 11]

[61, 45, 32, 20, 11, 7]

[45, 35, 26, 16, 8, 3]

[99, 97, 97, 92, 88, 87, 85, 84, 77, 76, 76, 73, 73, 70, 62, 58, 56, 52, 51, 46, 44, 41, 38, 29, 27, 26, 23, 15, 15, 14, 10, 9, 7, 7, 6, 4]

[99, 97, 87, 76, 62, 44]

[97, 88, 77, 70, 46, 26]

[92, 84, 73, 51, 27, 14]

[85, 73, 52, 29, 15, 7]

[76, 56, 38, 15, 9, 6]

[58, 41, 23, 10, 7, 4]

[96, 93, 91, 87, 80, 80, 78, 76, 75, 74, 70, 70, 55, 54, 49, 43, 42, 40, 39, 34, 30, 24, 23, 19, 16, 11, 10, 10, 10, 9, 7, 7, 5, 3, 2, 0]

[96, 91, 80, 74, 49, 30]

[93, 80, 75, 54, 34, 11]

[87, 76, 55, 39, 16, 9]

[78, 70, 40, 19, 10, 5]

[70, 42, 23, 10, 7, 2]

[43, 24, 10, 7, 3, 0]

[99, 94, 93, 92, 89, 84, 81, 79, 69, 67, 67, 65, 60, 59, 58, 56, 54, 53, 53, 50, 48, 44, 43, 32, 31, 30, 26, 23, 19, 15, 10, 9, 8, 6, 5, 2]

[99, 93, 84, 67, 58, 48]

[94, 89, 69, 59, 50, 30]

[92, 79, 60, 53, 31, 15]

[81, 65, 53, 32, 19, 8]

[67, 54, 43, 23, 9, 5]

[56, 44, 26, 10, 6, 2]

[97, 97, 96, 95, 83, 83, 81, 69, 64, 60, 58, 56, 54, 52, 49, 48, 48, 48, 43, 43, 41, 37, 36, 36, 36, 35, 32, 28, 22, 18, 18, 8, 7, 5, 4, 0]

Impossible! Repeated number 97 in the column at (1, 0)

[96, 91, 89, 88, 87, 87, 87, 86, 83, 80, 78, 78, 75, 69, 66, 65, 64, 61, 59, 57, 52, 51, 51, 50, 47, 45, 34, 32, 17, 12, 11, 8, 5, 5, 1, 0]

[96, 89, 87, 80, 66, 52]

[91, 87, 83, 69, 57, 45]

[88, 86, 75, 59, 47, 12]

[87, 78, 61, 50, 17, 5]

[78, 64, 51, 32, 8, 1]

[65, 51, 34, 11, 5, 0]

[99, 97, 93, 90, 89, 88, 86, 83, 78, 74, 74, 71, 67, 66, 66, 62, 59, 51, 48, 41, 39, 35, 33, 31, 28, 26, 25, 22, 19, 19, 18, 15, 13, 11, 10, 4]

[99, 93, 88, 74, 66, 39]

[97, 89, 78, 66, 41, 26]

[90, 83, 67, 48, 28, 19]

[86, 71, 51, 31, 19, 13]

[74, 59, 33, 22, 15, 10]

[62, 35, 25, 18, 11, 4]

[99, 93, 87, 86, 85, 79, 75, 75, 71, 68, 61, 59, 59, 59, 54, 53, 49, 36, 35, 33, 32, 31, 29, 27, 26, 25, 25, 21, 19, 18, 14, 13, 13, 12, 7, 6]

[99, 87, 79, 68, 54, 32]

[93, 85, 71, 59, 33, 25]

[86, 75, 59, 35, 26, 18]

[75, 59, 36, 27, 19, 13]

[61, 49, 29, 21, 13, 7]

[53, 31, 25, 14, 12, 6]

[94, 88, 85, 84, 81, 78, 76, 76, 75, 72, 70, 69, 68, 67, 65, 65, 61, 60, 58, 57, 54, 52, 49, 44, 41, 37, 34, 26, 25, 23, 22, 22, 19, 11, 10, 1]

[94, 85, 78, 72, 65, 54]

[88, 81, 75, 67, 57, 37]

[84, 76, 68, 58, 41, 23]

[76, 69, 60, 44, 25, 19]

[70, 61, 49, 26, 22, 10]

[65, 52, 34, 22, 11, 1]

[95, 93, 92, 84, 81, 76, 72, 71, 68, 66, 65, 61, 60, 59, 57, 54, 51, 47, 45, 41, 38, 37, 37, 35, 34, 34, 33, 32, 24, 20, 18, 17, 16, 15, 14, 6]

[95, 92, 76, 66, 57, 38]

[93, 81, 68, 59, 41, 34]

[84, 71, 60, 45, 34, 20]

[72, 61, 47, 35, 24, 16]

[65, 51, 37, 32, 17, 14]

[54, 37, 33, 18, 15, 6]

[98, 98, 92, 92, 86, 83, 83, 80, 77, 77, 75, 73, 69, 67, 66, 64, 64, 54, 52, 50, 50, 43, 40, 40, 36, 28, 25, 25, 18, 17, 13, 5, 5, 4, 2, 0]

Impossible! Repeated number 98 in the column at (1, 0)

[99, 99, 97, 96, 95, 91, 90, 90, 84, 81, 72, 71, 68, 67, 61, 57, 56, 56, 55, 51, 45, 44, 42, 38, 37, 37, 31, 26, 25, 23, 21, 21, 13, 12, 8, 2]

Impossible! Repeated number 99 in the column at (1, 0)

[99, 94, 93, 90, 86, 84, 83, 82, 81, 79, 78, 74, 67, 65, 63, 59, 58, 55, 52, 52, 50, 48, 47, 43, 32, 28, 24, 23, 22, 19, 18, 16, 15, 12, 8, 7]

[99, 93, 84, 79, 63, 50]

[94, 86, 81, 65, 52, 28]

[90, 82, 67, 52, 32, 19]

[83, 74, 55, 43, 22, 15]

[78, 58, 47, 23, 16, 8]

[59, 48, 24, 18, 12, 7]

[99, 95, 95, 86, 85, 81, 80, 78, 76, 74, 72, 70, 66, 59, 55, 54, 54, 53, 49, 48, 47, 45, 44, 39, 37, 37, 35, 32, 26, 24, 15, 14, 8, 7, 6, 2]

[99, 95, 81, 74, 55, 47]

[95, 85, 76, 59, 48, 37]

[86, 78, 66, 49, 37, 24]

[80, 70, 53, 39, 26, 8]

[72, 54, 44, 32, 14, 6]

[54, 45, 35, 15, 7, 2]

[98, 98, 96, 88, 85, 85, 78, 71, 71, 68, 61, 59, 59, 56, 54, 53, 52, 48, 45, 44, 42, 42, 40, 39, 38, 32, 31, 25, 25, 24, 19, 17, 15, 12, 6, 3]

Impossible! Repeated number 98 in the column at (1, 0)

[96, 95, 94, 87, 77, 75, 72, 70, 69, 68, 68, 64, 63, 62, 57, 56, 53, 50, 48, 47, 44, 43, 42, 42, 39, 31, 28, 28, 23, 19, 13, 10, 10, 7, 5, 1]

[96, 94, 75, 68, 57, 44]

[95, 77, 69, 62, 47, 31]

[87, 70, 63, 48, 39, 19]

[72, 64, 50, 42, 23, 10]

[68, 53, 42, 28, 10, 5]

[56, 43, 28, 13, 7, 1]

[99, 99, 98, 92, 92, 90, 90, 88, 85, 78, 78, 77, 73, 73, 65, 64, 59, 57, 53, 51, 45, 44, 41, 41, 40, 39, 33, 32, 32, 32, 30, 27, 25, 15, 13, 12]

Impossible! Repeated number 99 in the column at (1, 0)

[97, 97, 96, 93, 92, 85, 84, 84, 82, 80, 80, 77, 74, 73, 70, 67, 58, 56, 54, 42, 40, 40, 36, 34, 31, 29, 27, 27, 26, 25, 25, 22, 16, 16, 1, 0]

Impossible! Repeated number 97 in the column at (1, 0)

[95, 95, 92, 91, 84, 81, 77, 71, 70, 69, 69, 68, 65, 65, 65, 62, 61, 58, 53, 50, 47, 46, 44, 39, 39, 38, 33, 28, 27, 21, 15, 13, 9, 4, 1, 0]

Impossible! Repeated number 95 in the column at (1, 0)

[94, 93, 84, 81, 80, 70, 69, 68, 68, 66, 66, 65, 62, 62, 53, 53, 50, 41, 40, 37, 36, 35, 33, 32, 32, 22, 22, 20, 14, 14, 8, 7, 0, 0, 0, 0]

Impossible! Repeated number 0 in the column at (4, 5)

[98, 97, 94, 93, 86, 80, 78, 75, 73, 68, 63, 61, 57, 52, 48, 45, 41, 38, 37, 32, 27, 27, 25, 24, 23, 22, 20, 18, 14, 13, 11, 10, 7, 7, 6, 2]

[98, 94, 80, 68, 48, 27]

[97, 86, 73, 52, 32, 22]

[93, 75, 57, 37, 23, 13]

[78, 61, 38, 24, 14, 7]

[63, 41, 25, 18, 10, 6]

[45, 27, 20, 11, 7, 2]

[96, 88, 88, 80, 80, 79, 76, 73, 68, 67, 66, 63, 56, 50, 49, 49, 41, 39, 33, 30, 28, 28, 25, 24, 22, 20, 18, 18, 17, 14, 11, 6, 6, 4, 3, 0]

[96, 88, 79, 67, 49, 28]

[88, 80, 68, 50, 30, 20]

[80, 73, 56, 33, 22, 14]

[76, 63, 39, 24, 17, 6]

[66, 41, 25, 18, 6, 3]

[49, 28, 18, 11, 4, 0]

[99, 98, 90, 88, 86, 85, 84, 80, 79, 74, 68, 67, 61, 51, 46, 45, 44, 44, 43, 40, 39, 38, 27, 25, 25, 15, 13, 13, 13, 9, 9, 7, 3, 2, 2, 2]

Impossible! Repeated number 2 in the column at (5, 5)

[99, 96, 92, 88, 86, 75, 73, 69, 69, 68, 66, 61, 53, 53, 48, 46, 44, 40, 37, 32, 31, 29, 24, 22, 22, 17, 14, 13, 13, 11, 11, 11, 10, 3, 1, 0]

[99, 92, 75, 68, 48, 31]

[96, 86, 69, 53, 32, 17]

[88, 69, 53, 37, 22, 11]

[73, 61, 40, 22, 13, 10]

[66, 44, 24, 13, 11, 1]

[46, 29, 14, 11, 3, 0]

[98, 97, 92, 91, 90, 86, 78, 77, 76, 76, 72, 70, 65, 65, 58, 56, 55, 55, 55, 54, 46, 42, 38, 38, 37, 34, 27, 24, 19, 18, 15, 11, 5, 3, 3, 0]

[98, 92, 86, 76, 58, 46]

[97, 90, 76, 65, 54, 34]

[91, 77, 65, 55, 37, 18]

[78, 70, 55, 38, 19, 5]

[72, 55, 38, 24, 11, 3]

[56, 42, 27, 15, 3, 0]

[98, 97, 96, 89, 82, 80, 79, 74, 72, 60, 59, 55, 52, 52, 51, 48, 44, 43, 42, 40, 39, 38, 35, 34, 33, 33, 33, 30, 28, 27, 23, 21, 13, 9, 8, 8]

Impossible! Repeated number 8 in the column at (5, 5)

[97, 96, 95, 91, 88, 79, 75, 74, 74, 71, 67, 67, 63, 62, 58, 40, 39, 39, 38, 38, 37, 33, 29, 29, 27, 24, 20, 17, 14, 13, 5, 4, 4, 2, 2, 1]

[97, 95, 79, 71, 58, 37]

[96, 88, 74, 62, 38, 24]

[91, 74, 63, 38, 27, 13]

[75, 67, 39, 29, 14, 4]

[67, 39, 29, 17, 4, 2]

[40, 33, 20, 5, 2, 1]

[94, 89, 89, 86, 85, 78, 72, 72, 70, 66, 58, 58, 56, 55, 54, 53, 51, 51, 50, 49, 44, 38, 37, 28, 27, 27, 24, 19, 15, 14, 12, 12, 8, 6, 5, 5]

Impossible! Repeated number 5 in the column at (5, 5)

[96, 92, 90, 83, 83, 83, 82, 77, 75, 72, 63, 63, 62, 60, 57, 55, 54, 54, 53, 50, 50, 39, 36, 34, 33, 29, 23, 22, 19, 18, 17, 14, 11, 9, 6, 1]

[96, 90, 83, 72, 57, 50]

[92, 83, 75, 60, 50, 29]

[83, 77, 62, 53, 33, 18]

[82, 63, 54, 34, 19, 11]

[63, 54, 36, 22, 14, 6]

[55, 39, 23, 17, 9, 1]

[99, 96, 95, 93, 92, 90, 89, 87, 82, 81, 80, 78, 78, 77, 74, 71, 70, 60, 55, 49, 44, 39, 38, 37, 36, 26, 25, 23, 21, 19, 18, 13, 11, 10, 3, 1]

[99, 95, 90, 81, 74, 44]

[96, 92, 82, 77, 49, 26]

[93, 87, 78, 55, 36, 19]

[89, 78, 60, 37, 21, 11]

[80, 70, 38, 23, 13, 3]

[71, 39, 25, 18, 10, 1]

[97, 93, 89, 87, 87, 83, 82, 82, 81, 76, 75, 73, 71, 70, 70, 69, 68, 68, 67, 63, 63, 53, 51, 49, 45, 40, 38, 37, 32, 21, 18, 14, 13, 11, 10, 7]

[97, 89, 83, 76, 70, 63]

[93, 87, 81, 70, 63, 40]

[87, 82, 71, 67, 45, 21]

[82, 73, 68, 49, 32, 13]

[75, 68, 51, 37, 14, 10]

[69, 53, 38, 18, 11, 7]

[94, 91, 91, 87, 84, 80, 80, 80, 78, 74, 72, 68, 64, 62, 61, 58, 55, 52, 51, 50, 49, 39, 36, 35, 35, 28, 27, 26, 26, 25, 19, 15, 15, 11, 10, 4]

[94, 91, 80, 74, 61, 49]

[91, 84, 78, 62, 50, 28]

[87, 80, 64, 51, 35, 25]

[80, 68, 52, 35, 26, 15]

[72, 55, 36, 26, 15, 10]

[58, 39, 27, 19, 11, 4]

[90, 76, 72, 67, 66, 65, 63, 63, 61, 61, 61, 54, 53, 49, 42, 42, 40, 38, 36, 34, 31, 28, 25, 24, 23, 21, 20, 17, 16, 10, 9, 8, 7, 6, 5, 0]

[90, 72, 65, 61, 42, 31]

[76, 66, 61, 49, 34, 21]

[67, 63, 53, 36, 23, 10]

[63, 54, 38, 24, 16, 7]

[61, 40, 25, 17, 8, 5]

[42, 28, 20, 9, 6, 0]

[98, 98, 98, 96, 95, 89, 88, 87, 86, 85, 83, 76, 73, 73, 67, 66, 64, 64, 64, 63, 61, 61, 59, 56, 55, 52, 49, 34, 29, 26, 26, 16, 9, 6, 4, 0]

Impossible! Repeated number 98 in the column at (1, 0)

[98, 98, 95, 95, 93, 89, 87, 80, 77, 77, 70, 66, 65, 60, 59, 49, 46, 38, 34, 31, 22, 18, 15, 10, 10, 9, 8, 8, 7, 7, 7, 2, 2, 2, 1, 1]

Impossible! Repeated number 98 in the column at (1, 0)

[92, 92, 86, 85, 84, 83, 81, 81, 79, 78, 77, 72, 68, 63, 63, 58, 56, 47, 41, 40, 40, 35, 34, 30, 28, 20, 20, 20, 20, 19, 19, 18, 12, 7, 4, 3]

Impossible! Repeated number 92 in the column at (1, 0)

[99, 99, 86, 79, 79, 78, 76, 74, 68, 67, 65, 64, 60, 60, 57, 55, 54, 49, 46, 37, 32, 32, 31, 30, 29, 28, 28, 27, 26, 22, 20, 20, 18, 16, 10, 3]

Impossible! Repeated number 99 in the column at (1, 0)

[99, 94, 91, 90, 87, 84, 83, 83, 78, 75, 73, 68, 66, 62, 52, 52, 50, 47, 41, 40, 38, 36, 33, 33, 33, 32, 32, 30, 23, 22, 22, 19, 17, 16, 10, 10]

Impossible! Repeated number 10 in the column at (5, 5)

[95, 93, 92, 91, 87, 86, 82, 82, 76, 75, 73, 72, 71, 64, 62, 60, 56, 55, 55, 53, 50, 48, 43, 42, 41, 40, 38, 36, 26, 22, 20, 17, 16, 14, 14, 3]

[95, 92, 86, 75, 62, 50]

[93, 87, 76, 64, 53, 40]

[91, 82, 71, 55, 41, 22]

[82, 72, 55, 42, 26, 16]

[73, 56, 43, 36, 17, 14]

[60, 48, 38, 20, 14, 3]

[97, 91, 91, 90, 88, 84, 80, 73, 71, 71, 70, 69, 68, 67, 64, 60, 55, 53, 53, 44, 42, 41, 41, 39, 39, 37, 29, 23, 19, 18, 15, 13, 10, 10, 8, 5]

[97, 91, 84, 71, 64, 42]

[91, 88, 71, 67, 44, 37]

[90, 73, 68, 53, 39, 18]

[80, 69, 53, 39, 19, 10]

[70, 55, 41, 23, 13, 8]

[60, 41, 29, 15, 10, 5]

[99, 97, 94, 93, 93, 92, 89, 88, 84, 76, 70, 70, 70, 69, 63, 60, 54, 51, 51, 43, 43, 39, 36, 35, 30, 27, 24, 21, 19, 19, 12, 8, 6, 1, 0, 0]

Impossible! Repeated number 0 in the column at (5, 5)

[96, 95, 92, 91, 88, 83, 82, 78, 77, 76, 72, 70, 61, 55, 54, 43, 41, 38, 36, 34, 30, 27, 25, 24, 22, 22, 22, 20, 18, 15, 14, 12, 10, 9, 2, 0]

[96, 92, 83, 76, 54, 30]

[95, 88, 77, 55, 34, 22]

[91, 78, 61, 36, 22, 15]

[82, 70, 38, 24, 18, 10]

[72, 41, 25, 20, 12, 2]

[43, 27, 22, 14, 9, 0]

[98, 93, 90, 88, 84, 84, 83, 81, 76, 75, 72, 72, 68, 63, 58, 57, 55, 50, 44, 42, 39, 36, 36, 30, 26, 26, 24, 24, 20, 9, 6, 6, 3, 1, 1, 0]

[98, 90, 84, 75, 58, 39]

[93, 84, 76, 63, 42, 26]

[88, 81, 68, 44, 26, 9]

[83, 72, 50, 30, 20, 3]

[72, 55, 36, 24, 6, 1]

[57, 36, 24, 6, 1, 0]

[86, 85, 81, 74, 74, 65, 63, 61, 58, 53, 53, 42, 41, 41, 40, 40, 39, 39, 38, 37, 36, 36, 34, 32, 31, 27, 25, 23, 22, 20, 19, 18, 9, 8, 6, 0]

[86, 81, 65, 53, 40, 36]

[85, 74, 58, 41, 37, 27]

[74, 61, 41, 38, 31, 20]

[63, 42, 39, 32, 22, 9]

[53, 39, 34, 23, 18, 6]

[40, 36, 25, 19, 8, 0]

[87, 84, 82, 82, 79, 77, 75, 75, 74, 74, 70, 68, 62, 62, 59, 58, 54, 53, 53, 49, 49, 46, 35, 34, 34, 34, 33, 29, 24, 21, 10, 10, 9, 8, 4, 1]

[87, 82, 77, 74, 59, 49]

[84, 79, 74, 62, 49, 34]

[82, 75, 62, 53, 34, 21]

[75, 68, 53, 34, 24, 9]

[70, 54, 35, 29, 10, 4]

[58, 46, 33, 10, 8, 1]

[98, 95, 92, 89, 86, 83, 80, 80, 75, 72, 70, 69, 68, 66, 66, 53, 53, 52, 49, 45, 43, 41, 40, 39, 38, 36, 33, 28, 22, 13, 13, 12, 12, 7, 5, 3]

[98, 92, 83, 72, 66, 43]

[95, 86, 75, 66, 45, 36]

[89, 80, 68, 49, 38, 13]

[80, 69, 52, 39, 22, 12]

[70, 53, 40, 28, 12, 5]

[53, 41, 33, 13, 7, 3]

[98, 98, 95, 91, 89, 88, 87, 86, 83, 81, 79, 73, 69, 68, 57, 55, 50, 47, 41, 40, 35, 32, 31, 30, 24, 13, 11, 10, 10, 8, 3, 3, 2, 1, 0, 0]

Impossible! Repeated number 98 in the column at (1, 0)

[98, 98, 93, 91, 88, 86, 85, 80, 65, 65, 65, 65, 64, 62, 53, 51, 51, 48, 45, 41, 41, 36, 34, 34, 33, 28, 24, 19, 17, 17, 16, 15, 9, 8, 5, 0]

Impossible! Repeated number 98 in the column at (1, 0)

[99, 82, 82, 80, 79, 74, 73, 72, 65, 64, 62, 59, 59, 59, 58, 55, 49, 40, 36, 36, 32, 31, 30, 27, 26, 26, 23, 21, 19, 18, 16, 16, 11, 8, 2, 1]

[99, 82, 74, 64, 58, 32]

[82, 79, 65, 59, 36, 26]

[80, 72, 59, 36, 26, 18]

[73, 59, 40, 27, 19, 11]

[62, 49, 30, 21, 16, 2]

[55, 31, 23, 16, 8, 1]

[98, 95, 93, 91, 90, 86, 85, 85, 84, 84, 81, 80, 75, 67, 66, 65, 65, 59, 57, 49, 45, 42, 27, 26, 24, 21, 20, 20, 17, 15, 13, 13, 10, 9, 4, 0]

[98, 93, 86, 84, 66, 45]

[95, 90, 84, 67, 49, 21]

[91, 85, 75, 57, 24, 15]

[85, 80, 59, 26, 17, 10]

[81, 65, 27, 20, 13, 4]

[65, 42, 20, 13, 9, 0]

[99, 98, 92, 91, 90, 81, 77, 74, 70, 69, 66, 65, 62, 62, 59, 58, 57, 56, 55, 55, 53, 50, 46, 46, 42, 32, 29, 25, 21, 17, 16, 15, 11, 10, 9, 0]

[99, 92, 81, 69, 59, 53]

[98, 90, 70, 62, 55, 32]

[91, 74, 62, 55, 42, 17]

[77, 65, 56, 46, 21, 11]

[66, 57, 46, 25, 15, 9]

[58, 50, 29, 16, 10, 0]

[93, 89, 89, 89, 88, 88, 87, 87, 87, 76, 74, 74, 73, 65, 51, 50, 49, 47, 44, 34, 31, 30, 29, 27, 26, 24, 20, 17, 14, 14, 11, 11, 11, 9, 6, 3]

Impossible! Repeated number 89 in the column at (2, 0)

[98, 97, 95, 92, 88, 86, 83, 76, 75, 72, 69, 68, 64, 58, 57, 52, 43, 43, 41, 33, 32, 27, 26, 23, 23, 22, 22, 18, 18, 16, 13, 8, 8, 4, 2, 2]

Impossible! Repeated number 2 in the column at (5, 5)

[99, 95, 89, 88, 85, 83, 80, 79, 78, 78, 74, 71, 65, 63, 62, 58, 57, 56, 51, 47, 45, 42, 39, 31, 31, 31, 29, 26, 25, 24, 21, 21, 20, 13, 9, 5]

[99, 89, 83, 78, 62, 45]

[95, 85, 78, 63, 47, 31]

[88, 79, 65, 51, 31, 24]

[80, 71, 56, 31, 25, 20]

[74, 57, 39, 26, 21, 9]

[58, 42, 29, 21, 13, 5]

[99, 93, 91, 90, 88, 88, 88, 87, 85, 83, 75, 68, 67, 67, 66, 65, 61, 51, 48, 46, 44, 41, 39, 35, 35, 30, 28, 23, 22, 20, 20, 19, 14, 4, 3, 3]

Impossible! Repeated number 3 in the column at (5, 5)

[99, 88, 80, 79, 74, 72, 71, 70, 65, 65, 64, 63, 63, 60, 54, 46, 42, 42, 39, 38, 36, 35, 32, 30, 29, 27, 25, 24, 21, 17, 16, 16, 10, 7, 7, 2]

[99, 80, 72, 65, 54, 36]

[88, 74, 65, 60, 38, 27]

[79, 70, 63, 39, 29, 17]

[71, 63, 42, 30, 21, 10]

[64, 42, 32, 24, 16, 7]

[46, 35, 25, 16, 7, 2]

[95, 93, 80, 75, 66, 64, 59, 58, 49, 44, 44, 37, 37, 36, 35, 34, 33, 33, 32, 31, 28, 25, 23, 23, 22, 21, 20, 18, 15, 13, 11, 10, 6, 4, 3, 0]

[95, 80, 64, 44, 35, 28]

[93, 66, 49, 36, 31, 21]

[75, 58, 37, 32, 22, 13]

[59, 37, 33, 23, 15, 6]

[44, 33, 23, 18, 10, 3]

[34, 25, 20, 11, 4, 0]

[99, 99, 99, 86, 83, 83, 83, 67, 67, 65, 64, 62, 54, 54, 53, 45, 41, 41, 39, 38, 34, 30, 29, 29, 28, 26, 25, 24, 24, 18, 15, 8, 8, 7, 6, 5]

Impossible! Repeated number 99 in the column at (1, 0)

[92, 86, 85, 85, 80, 79, 69, 68, 67, 62, 62, 61, 60, 59, 59, 56, 53, 47, 43, 43, 36, 33, 30, 26, 25, 24, 22, 21, 20, 18, 14, 9, 9, 5, 4, 1]

[92, 85, 79, 62, 59, 36]

[86, 80, 67, 59, 43, 24]

[85, 68, 60, 43, 25, 18]

[69, 61, 47, 26, 20, 9]

[62, 53, 30, 21, 9, 4]

[56, 33, 22, 14, 5, 1]

[95, 94, 93, 91, 90, 87, 87, 86, 86, 82, 80, 80, 78, 77, 69, 69, 69, 64, 64, 60, 57, 52, 46, 37, 36, 29, 27, 27, 25, 23, 23, 19, 18, 17, 17, 8]

[95, 93, 87, 82, 69, 57]

[94, 90, 86, 77, 60, 29]

[91, 86, 78, 64, 36, 23]

[87, 80, 64, 37, 25, 18]

[80, 69, 46, 27, 19, 17]

[69, 52, 27, 23, 17, 8]

[94, 93, 93, 90, 87, 85, 85, 83, 83, 77, 68, 63, 59, 58, 56, 54, 53, 52, 49, 48, 44, 41, 37, 36, 32, 30, 28, 25, 19, 15, 13, 5, 4, 4, 1, 1]

Impossible! Repeated number 1 in the column at (5, 5)

[98, 89, 88, 83, 83, 82, 82, 82, 81, 75, 72, 72, 72, 69, 61, 61, 60, 60, 59, 54, 51, 46, 41, 37, 35, 35, 33, 33, 27, 23, 21, 20, 17, 6, 4, 1]

[98, 88, 82, 75, 61, 51]

[89, 83, 81, 69, 54, 35]

[83, 82, 72, 59, 35, 23]

[82, 72, 60, 37, 27, 17]

[72, 60, 41, 33, 20, 4]

[61, 46, 33, 21, 6, 1]

[97, 95, 93, 84, 83, 81, 81, 81, 78, 75, 75, 72, 71, 66, 63, 58, 58, 56, 49, 47, 45, 41, 39, 37, 36, 22, 20, 16, 13, 10, 9, 8, 7, 5, 3, 2]

[97, 93, 81, 75, 63, 45]

[95, 83, 78, 66, 47, 22]

[84, 81, 71, 49, 36, 10]

[81, 72, 56, 37, 13, 7]

[75, 58, 39, 16, 8, 3]

[58, 41, 20, 9, 5, 2]

[98, 94, 92, 92, 85, 85, 83, 82, 79, 75, 75, 74, 70, 69, 67, 62, 61, 57, 54, 53, 44, 38, 33, 33, 31, 31, 28, 28, 25, 12, 10, 10, 8, 8, 5, 2]

[98, 92, 85, 75, 67, 44]

[94, 85, 79, 69, 53, 31]

[92, 82, 70, 54, 31, 12]

[83, 74, 57, 33, 25, 8]

[75, 61, 33, 28, 10, 5]

[62, 38, 28, 10, 8, 2]

[88, 80, 79, 78, 76, 74, 73, 70, 69, 66, 61, 60, 54, 52, 51, 45, 41, 40, 34, 34, 33, 31, 30, 28, 26, 24, 22, 22, 19, 14, 13, 9, 6, 2, 2, 2]

Impossible! Repeated number 2 in the column at (5, 5)

[99, 98, 97, 96, 95, 92, 82, 81, 75, 73, 71, 68, 63, 62, 59, 58, 55, 54, 50, 49, 45, 45, 41, 41, 41, 33, 24, 23, 16, 14, 11, 9, 3, 2, 1, 1]

Impossible! Repeated number 1 in the column at (5, 5)

[95, 95, 94, 92, 88, 88, 84, 83, 82, 76, 76, 76, 75, 73, 71, 71, 65, 64, 63, 61, 61, 61, 60, 56, 54, 52, 49, 39, 27, 18, 15, 14, 11, 6, 5, 0]

Impossible! Repeated number 95 in the column at (1, 0)

My Struggle

No image upload facility on this markdown?

I hope my (attempts)[https://imgur.com/a/dJ09SBy%5C] are visible here.

79817371
Vote

First focus on sorting in grid. I was thought sorting in 1 dimension should be similar with 2 dimensions.

if descending sorting for 1 dimension can done by insert max value from source to result into left most.

thus descending sorting for 2 dimensions can done by insert max value from source to result into top-left most.

ex for descending sorting 4x4 values

1 dimension: 
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

2 dimensions:
15 14 12  9 
13 11  8  5 
10  7  4  2 
 6  3  1  0

so my program just follow this rule and check duplicate adjacent value in row/column

result is ok = 55 , fail = 45

#include <iostream>
#include <vector>
#include <iomanip>
#include <array>
#include <algorithm>

struct Grid{
    Grid(size_t col_n, size_t row_n);

    //access element in rowwise
    int& row_elem(size_t row_i, size_t i);

    //access element in columnwise
    int& col_elem(size_t col_i, size_t i);

    int& operator[](size_t n);

    void fill(int v);

    //@return error code 0 = no error
    int error();
    
    std::vector<int> m_data;
    size_t m_col_n;
    size_t m_row_n;
};



//i use only this algorithm otherwise for experiment
struct Alg_fill_diagonal_bl{

    //@return error code 0 = no error
    int operator()(Grid& in, Grid& out);

};


struct Alg_fill_diagonal_tr{

    //@return error code 0 = no error
    int operator()(Grid& in, Grid& out);

};

struct Alg_Lastresort{

    //@return error code 0 = no error
    int operator()(Grid& in, Grid& out);

    bool is_ok(Grid& out, size_t row, size_t col, int v);

};


//print grid
std::ostream& operator<<(std::ostream& os, Grid& rhs);


int main()
{
    constexpr std::array<std::array<int, 36>,100> source = {{{54, 95, 98, 26, 3, 39, 77, 30, 83, 62, 20, 92, 61, 59, 26, 63, 92, 49, 38, 51, 99, 64, 65, 52, 98, 18, 90, 97, 96, 13, 74, 3, 88, 88, 67, 10},
{49, 13, 73, 54, 4, 98, 36, 33, 12, 22, 35, 18, 39, 83, 92, 77, 50, 77, 57, 64, 0, 35, 86, 98, 28, 1, 53, 59, 28, 33, 56, 37, 98, 26, 81, 13},
{95, 84, 44, 16, 42, 73, 0, 53, 14, 63, 81, 91, 42, 14, 13, 59, 91, 24, 99, 71, 73, 34, 60, 65, 82, 55, 16, 75, 7, 18, 68, 6, 61, 6, 80, 41},
{27, 63, 35, 81, 56, 24, 70, 27, 59, 13, 36, 62, 73, 6, 61, 86, 48, 40, 88, 71, 52, 1, 9, 57, 50, 40, 20, 10, 3, 29, 19, 94, 99, 8, 74, 83},
{46, 75, 78, 14, 89, 76, 37, 26, 85, 78, 81, 27, 99, 41, 96, 52, 21, 65, 71, 48, 60, 32, 48, 31, 85, 35, 88, 5, 78, 22, 31, 97, 43, 80, 52, 45},
{0, 98, 50, 12, 0, 83, 46, 66, 67, 23, 52, 55, 41, 95, 5, 17, 78, 98, 74, 45, 97, 98, 96, 54, 48, 79, 29, 0, 73, 6, 16, 33, 20, 88, 9, 23},
{9, 2, 10, 57, 79, 65, 65, 0, 19, 64, 3, 18, 20, 93, 10, 30, 9, 0, 40, 51, 87, 34, 52, 71, 28, 23, 73, 61, 77, 60, 66, 91, 57, 58, 2, 9},
{27, 63, 51, 6, 3, 10, 7, 36, 80, 51, 93, 71, 73, 25, 3, 77, 35, 56, 36, 36, 77, 97, 14, 1, 78, 83, 5, 51, 99, 5, 93, 90, 1, 36, 83, 4},
{89, 94, 67, 64, 31, 66, 59, 16, 80, 22, 78, 72, 56, 83, 98, 10, 9, 57, 23, 4, 80, 37, 65, 30, 71, 55, 42, 9, 60, 18, 39, 58, 44, 79, 48, 29},
{79, 51, 3, 82, 81, 58, 99, 88, 54, 88, 81, 5, 63, 79, 52, 64, 48, 64, 68, 11, 50, 66, 35, 71, 9, 86, 11, 97, 42, 41, 0, 2, 56, 38, 15, 63},
{94, 35, 12, 94, 79, 40, 91, 45, 37, 98, 43, 30, 80, 81, 87, 19, 74, 87, 93, 35, 88, 89, 79, 44, 6, 87, 27, 49, 98, 44, 68, 39, 42, 87, 61, 84},
{5, 37, 89, 80, 31, 40, 1, 10, 54, 67, 23, 1, 75, 43, 49, 27, 29, 69, 43, 41, 7, 16, 63, 70, 5, 61, 74, 87, 2, 61, 50, 72, 91, 56, 12, 99},
{43, 35, 83, 94, 69, 45, 76, 73, 83, 60, 80, 31, 59, 34, 39, 63, 35, 13, 94, 78, 2, 24, 87, 21, 36, 38, 55, 19, 10, 82, 13, 95, 88, 54, 94, 75},
{66, 10, 58, 21, 82, 10, 32, 91, 66, 65, 3, 12, 4, 38, 12, 96, 55, 54, 73, 16, 74, 41, 28, 49, 19, 98, 16, 90, 93, 82, 56, 68, 14, 70, 31, 19},
{13, 79, 47, 31, 79, 31, 56, 65, 94, 73, 57, 35, 74, 85, 84, 39, 24, 26, 12, 56, 46, 46, 71, 0, 57, 61, 77, 32, 14, 1, 81, 71, 69, 66, 57, 69},
{8, 39, 23, 14, 88, 44, 81, 46, 5, 26, 50, 11, 71, 19, 86, 33, 88, 62, 81, 13, 60, 96, 7, 78, 6, 88, 77, 94, 74, 63, 48, 40, 29, 47, 64, 6},
{95, 36, 61, 3, 75, 84, 95, 8, 57, 42, 43, 77, 27, 65, 56, 78, 34, 96, 18, 23, 46, 17, 86, 17, 89, 28, 96, 18, 24, 90, 93, 49, 47, 69, 91, 48},
{76, 95, 10, 10, 58, 67, 25, 41, 0, 49, 13, 40, 59, 29, 62, 64, 97, 47, 22, 42, 39, 44, 16, 95, 23, 91, 14, 48, 90, 39, 16, 92, 46, 38, 49, 16},
{60, 42, 28, 28, 61, 10, 37, 90, 99, 9, 45, 15, 61, 20, 6, 89, 99, 5, 34, 28, 58, 45, 10, 43, 73, 5, 45, 78, 68, 48, 44, 56, 78, 69, 52, 99},
{99, 92, 63, 87, 23, 73, 25, 25, 31, 97, 14, 12, 77, 96, 73, 80, 86, 15, 63, 71, 44, 34, 51, 28, 77, 24, 19, 74, 87, 34, 59, 40, 82, 13, 25, 15},
{48, 59, 63, 45, 51, 64, 88, 99, 81, 29, 69, 27, 7, 28, 9, 77, 50, 80, 7, 64, 3, 24, 6, 22, 31, 69, 92, 66, 13, 3, 70, 81, 73, 50, 45, 42},
{0, 49, 29, 50, 38, 38, 24, 71, 8, 5, 56, 6, 90, 2, 3, 35, 40, 89, 24, 27, 74, 77, 54, 7, 1, 76, 92, 16, 55, 23, 47, 62, 33, 1, 80, 47},
{1, 61, 12, 89, 56, 47, 88, 63, 73, 49, 9, 78, 68, 69, 19, 53, 76, 39, 49, 83, 38, 70, 62, 79, 19, 7, 70, 4, 90, 57, 90, 20, 52, 37, 64, 17},
{0, 99, 18, 20, 0, 5, 93, 66, 87, 4, 62, 47, 94, 27, 73, 82, 12, 37, 39, 63, 59, 71, 71, 36, 84, 53, 90, 93, 9, 21, 94, 76, 80, 4, 40, 30},
{57, 17, 99, 26, 7, 0, 81, 29, 95, 51, 46, 8, 16, 19, 15, 48, 89, 65, 69, 14, 94, 9, 3, 78, 59, 20, 41, 45, 97, 99, 57, 52, 94, 12, 55, 28},
{19, 49, 58, 20, 73, 65, 0, 72, 82, 12, 64, 43, 34, 58, 11, 74, 20, 75, 0, 23, 6, 25, 81, 39, 44, 65, 54, 57, 72, 72, 10, 69, 31, 10, 45, 20},
{68, 46, 13, 68, 81, 62, 28, 75, 66, 91, 27, 31, 20, 38, 1, 45, 76, 79, 14, 62, 58, 66, 17, 79, 61, 91, 86, 33, 57, 95, 74, 7, 31, 85, 97, 80},
{67, 31, 55, 44, 11, 39, 50, 79, 64, 75, 97, 13, 22, 19, 42, 58, 55, 10, 51, 37, 73, 55, 22, 40, 35, 97, 77, 92, 43, 24, 69, 25, 64, 61, 48, 77},
{7, 17, 84, 29, 87, 12, 85, 22, 65, 70, 73, 14, 32, 9, 27, 3, 11, 42, 88, 20, 37, 10, 88, 77, 68, 92, 71, 80, 83, 32, 35, 85, 91, 52, 26, 73},
{62, 24, 97, 27, 49, 2, 50, 36, 14, 59, 63, 1, 45, 98, 80, 64, 59, 80, 55, 96, 87, 89, 19, 81, 40, 31, 73, 48, 29, 34, 63, 11, 12, 7, 84, 28},
{23, 82, 3, 66, 59, 65, 49, 80, 16, 73, 39, 69, 45, 15, 6, 14, 4, 97, 76, 57, 34, 13, 77, 72, 98, 24, 34, 54, 23, 41, 67, 6, 80, 19, 30, 92},
{20, 35, 58, 63, 21, 75, 58, 8, 30, 44, 97, 21, 3, 86, 78, 89, 93, 42, 29, 89, 53, 17, 89, 6, 8, 14, 48, 98, 15, 58, 28, 46, 51, 55, 17, 78},
{42, 41, 8, 12, 37, 81, 33, 58, 59, 31, 3, 67, 77, 90, 6, 2, 14, 45, 49, 28, 79, 93, 7, 75, 52, 52, 46, 86, 98, 77, 66, 38, 41, 11, 41, 2},
{8, 45, 28, 85, 58, 99, 18, 86, 95, 16, 59, 45, 26, 35, 36, 96, 61, 82, 32, 20, 62, 47, 93, 3, 44, 71, 11, 11, 31, 28, 42, 7, 18, 58, 40, 89},
{87, 4, 99, 46, 73, 27, 7, 44, 26, 62, 15, 10, 14, 77, 97, 70, 58, 23, 85, 73, 76, 97, 6, 92, 52, 51, 9, 84, 29, 56, 15, 38, 41, 7, 88, 76},
{30, 0, 80, 70, 10, 78, 91, 80, 3, 42, 24, 70, 39, 7, 7, 43, 9, 2, 23, 96, 76, 87, 19, 11, 5, 10, 74, 10, 49, 16, 34, 54, 40, 55, 75, 93},
{92, 54, 58, 53, 99, 84, 53, 50, 56, 65, 10, 89, 19, 2, 6, 94, 44, 69, 67, 60, 79, 5, 30, 23, 15, 8, 48, 26, 32, 31, 43, 59, 81, 9, 67, 93},
{7, 58, 97, 4, 22, 36, 5, 83, 32, 69, 83, 54, 18, 48, 49, 43, 36, 37, 96, 0, 28, 18, 64, 56, 52, 97, 43, 95, 36, 8, 48, 35, 60, 41, 48, 81},
{50, 78, 66, 51, 45, 80, 65, 87, 0, 5, 87, 91, 34, 78, 47, 89, 51, 32, 88, 64, 52, 8, 86, 59, 11, 5, 1, 12, 57, 87, 75, 83, 17, 69, 96, 61},
{74, 18, 35, 33, 97, 4, 22, 39, 41, 10, 66, 59, 11, 71, 90, 28, 78, 66, 51, 25, 48, 89, 74, 62, 13, 19, 67, 99, 19, 88, 15, 83, 26, 86, 31, 93},
{93, 32, 27, 13, 61, 53, 49, 35, 59, 13, 54, 68, 75, 31, 18, 79, 33, 59, 87, 86, 14, 26, 21, 19, 12, 59, 75, 36, 7, 71, 25, 25, 6, 85, 29, 99},
{94, 78, 11, 70, 49, 22, 25, 67, 34, 65, 85, 58, 76, 10, 44, 22, 75, 72, 65, 54, 68, 60, 84, 52, 19, 26, 61, 69, 88, 76, 37, 41, 81, 1, 23, 57},
{15, 72, 24, 37, 95, 16, 76, 61, 34, 47, 68, 93, 18, 92, 32, 17, 20, 66, 51, 33, 65, 38, 71, 45, 81, 59, 34, 35, 84, 37, 14, 6, 41, 60, 57, 54},
{83, 86, 73, 77, 75, 67, 5, 92, 43, 13, 98, 92, 69, 80, 50, 25, 64, 0, 64, 25, 98, 40, 66, 77, 4, 18, 52, 50, 28, 36, 17, 54, 5, 83, 2, 40},
{25, 68, 57, 61, 55, 81, 56, 71, 95, 72, 37, 21, 91, 8, 23, 26, 38, 44, 45, 84, 37, 51, 13, 42, 90, 12, 67, 21, 96, 31, 99, 97, 2, 90, 99, 56},
{47, 90, 19, 59, 82, 32, 52, 99, 74, 8, 93, 18, 79, 22, 24, 63, 84, 50, 55, 86, 94, 23, 83, 65, 67, 48, 16, 15, 81, 78, 7, 43, 12, 52, 58, 28},
{54, 39, 86, 53, 24, 55, 72, 2, 6, 15, 78, 8, 35, 70, 59, 80, 74, 99, 95, 32, 44, 26, 47, 49, 48, 14, 95, 66, 54, 76, 37, 81, 85, 37, 45, 7},
{19, 38, 6, 31, 71, 53, 40, 85, 71, 52, 56, 25, 78, 32, 17, 85, 42, 24, 61, 42, 3, 54, 98, 68, 48, 39, 59, 59, 12, 25, 96, 98, 15, 88, 44, 45},
{62, 70, 19, 57, 56, 68, 7, 13, 53, 87, 68, 69, 77, 39, 23, 94, 42, 10, 1, 28, 43, 31, 42, 48, 75, 95, 28, 10, 44, 50, 72, 47, 64, 96, 5, 63},
{92, 85, 77, 92, 90, 27, 39, 57, 51, 41, 99, 78, 78, 53, 88, 59, 30, 65, 15, 25, 32, 32, 99, 64, 90, 40, 13, 45, 41, 73, 98, 12, 44, 73, 33, 32},
{97, 36, 97, 58, 74, 56, 70, 80, 92, 84, 93, 16, 0, 34, 96, 85, 84, 16, 29, 22, 27, 42, 26, 40, 27, 80, 1, 40, 82, 25, 54, 31, 77, 25, 67, 73},
{46, 91, 13, 50, 65, 68, 44, 15, 65, 58, 77, 21, 92, 70, 69, 95, 9, 84, 69, 71, 53, 65, 0, 33, 95, 4, 1, 28, 62, 27, 39, 38, 47, 39, 61, 81},
{37, 0, 70, 66, 14, 20, 50, 68, 8, 0, 62, 41, 68, 35, 14, 69, 94, 62, 53, 84, 32, 22, 80, 81, 22, 66, 36, 65, 40, 53, 93, 0, 0, 33, 32, 7},
{68, 73, 37, 13, 86, 20, 22, 97, 27, 10, 32, 57, 27, 11, 52, 7, 7, 48, 23, 14, 98, 25, 41, 6, 78, 63, 80, 38, 24, 75, 2, 61, 45, 93, 18, 94},
{20, 14, 76, 73, 80, 30, 56, 33, 80, 18, 79, 66, 39, 3, 88, 25, 28, 24, 63, 88, 68, 28, 67, 49, 6, 18, 4, 49, 0, 96, 11, 22, 6, 41, 17, 50},
{9, 61, 45, 7, 25, 86, 99, 39, 79, 13, 46, 74, 44, 3, 90, 43, 25, 9, 2, 27, 13, 15, 38, 98, 2, 88, 13, 51, 44, 80, 67, 85, 84, 40, 2, 68},
{22, 48, 11, 46, 99, 88, 75, 32, 69, 66, 73, 10, 3, 31, 13, 44, 11, 17, 68, 0, 37, 86, 40, 92, 13, 61, 24, 69, 22, 11, 53, 1, 14, 53, 96, 29},
{65, 27, 91, 56, 76, 11, 86, 34, 3, 15, 97, 42, 19, 98, 38, 78, 90, 37, 76, 55, 46, 18, 72, 92, 3, 38, 55, 54, 5, 0, 58, 24, 77, 70, 65, 55},
{33, 48, 21, 34, 42, 60, 82, 33, 98, 27, 51, 33, 74, 55, 59, 96, 44, 35, 23, 28, 13, 52, 72, 9, 39, 52, 8, 30, 40, 8, 97, 43, 79, 89, 38, 80},
{1, 29, 67, 37, 13, 29, 33, 96, 91, 24, 4, 67, 20, 71, 75, 95, 2, 63, 39, 14, 88, 2, 5, 17, 38, 40, 74, 79, 39, 62, 38, 58, 74, 4, 27, 97},
{86, 8, 5, 54, 58, 78, 70, 51, 89, 94, 51, 55, 27, 6, 56, 44, 14, 72, 5, 27, 19, 50, 72, 58, 66, 24, 49, 28, 15, 12, 12, 37, 85, 89, 53, 38},
{54, 1, 82, 23, 72, 55, 6, 96, 54, 22, 19, 63, 83, 50, 39, 75, 33, 29, 83, 14, 60, 92, 62, 83, 11, 34, 53, 77, 57, 63, 18, 17, 50, 9, 90, 36},
{60, 78, 25, 81, 18, 1, 96, 39, 36, 82, 23, 78, 70, 80, 19, 55, 74, 38, 99, 37, 3, 87, 21, 26, 93, 89, 44, 13, 95, 92, 11, 71, 77, 10, 49, 90},
{68, 68, 45, 82, 67, 7, 97, 49, 87, 83, 73, 70, 70, 87, 14, 37, 10, 21, 82, 71, 75, 13, 89, 93, 63, 11, 40, 18, 32, 69, 38, 53, 81, 63, 51, 76},
{25, 36, 27, 62, 4, 51, 50, 74, 19, 10, 78, 94, 15, 49, 11, 26, 91, 80, 61, 80, 84, 87, 80, 52, 35, 28, 64, 91, 39, 58, 15, 55, 26, 72, 68, 35},
{42, 66, 36, 17, 5, 31, 38, 90, 61, 8, 24, 0, 7, 40, 65, 67, 54, 61, 53, 16, 49, 76, 21, 63, 23, 72, 20, 9, 42, 34, 10, 6, 63, 25, 61, 28},
{9, 98, 52, 95, 85, 61, 87, 96, 64, 98, 98, 83, 88, 4, 73, 29, 26, 67, 59, 34, 89, 49, 6, 16, 0, 61, 55, 76, 73, 64, 26, 63, 56, 64, 66, 86},
{98, 2, 10, 34, 9, 10, 8, 46, 2, 95, 89, 65, 49, 1, 38, 15, 8, 22, 66, 80, 7, 77, 77, 70, 1, 7, 60, 59, 93, 7, 2, 98, 31, 95, 87, 18},
{47, 20, 77, 92, 92, 78, 81, 7, 34, 20, 30, 40, 56, 79, 86, 84, 81, 40, 19, 28, 72, 35, 20, 85, 3, 68, 18, 4, 63, 83, 20, 12, 41, 63, 19, 58},
{55, 10, 67, 18, 31, 16, 76, 57, 79, 64, 68, 37, 78, 60, 60, 46, 49, 32, 32, 3, 65, 74, 22, 79, 26, 29, 28, 86, 20, 99, 27, 99, 28, 30, 54, 20},
{73, 87, 66, 32, 10, 75, 40, 94, 30, 99, 52, 10, 33, 33, 52, 36, 16, 90, 68, 62, 19, 33, 50, 22, 78, 47, 91, 22, 84, 83, 41, 17, 32, 83, 38, 23},
{82, 26, 41, 53, 71, 22, 95, 55, 60, 14, 40, 42, 36, 43, 91, 50, 16, 93, 62, 72, 3, 14, 55, 48, 20, 17, 56, 38, 64, 87, 86, 92, 82, 75, 73, 76},
{70, 18, 42, 41, 19, 44, 8, 90, 10, 73, 41, 39, 23, 69, 64, 55, 39, 80, 88, 13, 5, 29, 71, 53, 84, 71, 91, 97, 60, 67, 10, 15, 53, 37, 68, 91},
{12, 99, 93, 43, 63, 51, 54, 89, 39, 8, 19, 27, 70, 94, 0, 70, 76, 1, 51, 30, 60, 88, 24, 69, 35, 36, 97, 43, 0, 70, 21, 84, 19, 6, 93, 92},
{15, 83, 14, 61, 0, 18, 77, 34, 95, 92, 22, 76, 54, 9, 22, 43, 96, 91, 24, 12, 30, 22, 88, 72, 82, 38, 27, 10, 41, 2, 78, 25, 36, 20, 70, 55},
{83, 6, 84, 58, 57, 42, 76, 75, 36, 39, 98, 55, 72, 72, 84, 81, 36, 9, 3, 44, 1, 50, 63, 1, 93, 24, 26, 20, 30, 68, 0, 24, 90, 26, 6, 88},
{58, 38, 65, 42, 40, 25, 32, 39, 19, 31, 74, 36, 85, 74, 23, 20, 37, 41, 41, 63, 61, 9, 27, 39, 22, 0, 36, 34, 53, 53, 6, 40, 81, 18, 86, 8},
{34, 1, 53, 24, 53, 46, 21, 59, 74, 75, 10, 49, 79, 74, 29, 68, 82, 75, 49, 62, 8, 58, 54, 34, 87, 4, 84, 34, 10, 82, 70, 35, 62, 9, 33, 77},
{28, 49, 3, 98, 69, 36, 80, 53, 72, 68, 89, 22, 40, 52, 5, 66, 39, 38, 41, 45, 13, 12, 70, 12, 7, 86, 95, 83, 66, 92, 43, 13, 53, 80, 75, 33},
{98, 98, 88, 3, 11, 32, 83, 24, 91, 79, 3, 55, 50, 95, 41, 69, 30, 89, 68, 47, 13, 35, 0, 86, 57, 8, 10, 31, 1, 40, 81, 2, 87, 10, 73, 0},
{36, 8, 65, 86, 88, 65, 19, 33, 62, 24, 98, 34, 0, 80, 45, 53, 16, 28, 41, 65, 93, 34, 64, 85, 48, 98, 15, 51, 41, 65, 5, 9, 51, 17, 17, 91},
{21, 49, 80, 99, 8, 32, 11, 36, 82, 59, 64, 59, 55, 73, 1, 23, 82, 59, 19, 16, 58, 18, 62, 36, 74, 30, 72, 79, 26, 31, 16, 40, 2, 27, 65, 26},
{86, 24, 59, 75, 93, 17, 20, 42, 21, 4, 80, 0, 57, 91, 81, 84, 95, 13, 65, 85, 9, 15, 26, 90, 66, 20, 13, 98, 67, 27, 85, 49, 45, 65, 10, 84},
{17, 16, 99, 46, 21, 66, 57, 69, 29, 42, 50, 92, 9, 11, 56, 62, 32, 15, 55, 25, 55, 90, 81, 74, 62, 98, 58, 65, 46, 77, 53, 10, 0, 59, 70, 91},
{76, 89, 89, 89, 87, 87, 11, 51, 11, 44, 11, 50, 29, 88, 93, 31, 6, 26, 74, 34, 24, 30, 14, 74, 9, 47, 20, 17, 88, 14, 49, 87, 3, 65, 27, 73},
{18, 18, 68, 23, 13, 98, 52, 92, 72, 75, 8, 8, 2, 33, 69, 23, 22, 16, 95, 76, 43, 83, 86, 27, 4, 58, 57, 97, 64, 22, 43, 32, 41, 2, 88, 26},
{21, 20, 85, 29, 56, 31, 65, 45, 58, 26, 62, 21, 71, 31, 5, 57, 88, 42, 51, 39, 79, 83, 47, 99, 25, 31, 9, 24, 13, 63, 95, 78, 80, 74, 78, 89},
{39, 90, 68, 22, 85, 14, 4, 20, 41, 51, 67, 75, 20, 48, 91, 65, 61, 44, 66, 3, 83, 30, 93, 23, 19, 99, 46, 88, 87, 35, 3, 88, 35, 67, 88, 28},
{63, 21, 64, 10, 7, 38, 25, 17, 32, 36, 7, 99, 46, 65, 74, 71, 63, 42, 30, 72, 29, 80, 42, 65, 27, 24, 16, 16, 70, 2, 54, 60, 35, 79, 88, 39},
{10, 75, 23, 44, 33, 33, 11, 13, 23, 3, 44, 37, 64, 66, 35, 32, 34, 22, 18, 15, 6, 37, 25, 36, 20, 4, 49, 58, 59, 21, 80, 95, 0, 31, 93, 28},
{54, 30, 99, 86, 7, 38, 8, 18, 26, 83, 15, 83, 45, 5, 24, 67, 6, 39, 65, 67, 83, 99, 29, 41, 64, 62, 25, 53, 54, 34, 24, 41, 99, 28, 8, 29},
{30, 60, 67, 20, 43, 56, 79, 43, 92, 85, 69, 9, 62, 22, 62, 24, 68, 33, 18, 61, 25, 14, 21, 59, 86, 59, 53, 26, 1, 80, 9, 36, 4, 5, 85, 47},
{57, 64, 8, 17, 69, 23, 77, 29, 69, 52, 80, 86, 18, 93, 78, 17, 36, 60, 94, 25, 80, 90, 87, 86, 64, 23, 87, 95, 19, 69, 91, 82, 37, 27, 27, 46},
{52, 19, 54, 87, 1, 4, 41, 68, 93, 56, 36, 13, 32, 25, 83, 48, 59, 5, 37, 58, 83, 93, 53, 77, 44, 63, 49, 1, 94, 4, 28, 30, 85, 15, 85, 90},
{75, 72, 89, 33, 98, 23, 81, 41, 35, 17, 4, 1, 46, 60, 83, 69, 27, 35, 33, 83, 61, 61, 21, 72, 82, 72, 82, 6, 59, 51, 60, 37, 82, 20, 88, 54},
{20, 37, 13, 75, 81, 78, 36, 75, 22, 45, 81, 63, 58, 72, 81, 7, 9, 39, 49, 8, 84, 66, 71, 58, 41, 56, 5, 2, 83, 47, 16, 3, 93, 95, 97, 10},
{94, 83, 74, 92, 8, 10, 12, 92, 28, 28, 31, 98, 10, 33, 62, 70, 85, 53, 8, 31, 75, 67, 38, 2, 5, 85, 44, 25, 54, 69, 33, 61, 75, 57, 79, 82},
{60, 34, 79, 9, 2, 28, 80, 24, 2, 76, 26, 34, 61, 22, 40, 31, 52, 14, 30, 2, 88, 54, 41, 73, 6, 45, 13, 22, 70, 51, 74, 69, 19, 66, 33, 78},
{3, 11, 50, 41, 23, 41, 45, 2, 62, 95, 55, 73, 1, 98, 33, 68, 82, 96, 24, 81, 1, 58, 59, 41, 45, 9, 99, 49, 16, 97, 54, 75, 92, 14, 71, 63},
{18, 73, 63, 61, 88, 15, 27, 49, 82, 95, 0, 54, 71, 76, 64, 65, 84, 39, 61, 56, 52, 60, 88, 92, 75, 83, 94, 61, 76, 76, 14, 11, 5, 95, 71, 68}}};
    
    constexpr size_t source_col = 6;
    constexpr size_t source_row = 6;

    Grid in(source_col, source_row);
    Grid out(source_col, source_row);

    Alg_fill_diagonal_bl alg{};

    int i = 0;
    int good = 0;
    for(auto& item:source){
        in.m_data.assign(item.begin(), item.end());
        std::sort(in.m_data.begin(), in.m_data.end(),  std::greater<int>());

        std::cout << "#" << i++ << '\n';
        std::cout << in << '\n';

         if(alg(in, out)){
            std::cout << "fail\n";
        }else{
            std::cout << "ok\n";
            good++;
        }

        std::cout << out << '\n';

    }

    std::cout << "ok=" << good << " fail=" << (source.size() - good) << "\n";

    
}



/**
* implementation
*/

Grid::Grid(size_t col_n, size_t row_n):m_col_n{col_n}, m_row_n{row_n}, m_data(col_n * row_n){}

int& Grid::row_elem(size_t row_i, size_t i){
    return m_data[row_i * m_col_n + i];
}

int& Grid::col_elem(size_t col_i, size_t i){
    return m_data[i * m_col_n + col_i];
}

int& Grid::operator[](size_t n){
    return m_data[n];
}

void Grid::fill(int v){
    std::fill(m_data.begin(), m_data.end(), v);
}

int Grid::error(){
    for(size_t i = 0;i < m_row_n;i++){
        for(size_t j = 1;j < m_col_n; j++){
            if(row_elem(i, j - 1) <= row_elem(i, j)){
                return 1;
            }
        }
    }

    for(size_t i = 0;i < m_col_n;i++){
        for(size_t j = 1;j < m_row_n; j++){
            if(col_elem(i, j - 1) <= col_elem(i, j)){
                return 1;
            }
        }
    }
    return 0;
}


int Alg_fill_diagonal_bl::operator()(Grid& in, Grid& out){

    int pos = 0;
    for (int col = 0; col < out.m_col_n; col++) {
        int i = col, j = 0;   
        while (i >= 0 && j < out.m_row_n) {
            out.col_elem(i, j) = in[pos++];
            i--;
            j++;
        }
    }
    for (int row = 1; row < out.m_row_n; row++) {
        int i = out.m_col_n - 1, j = row;
        while (i >= 0 && j < out.m_row_n) {
            out.col_elem(i, j) = in[pos++];
            i--;
            j++;
        }
    }
    return out.error();
}


std::ostream& operator<<(std::ostream& os, Grid& rhs){
    for(size_t i = 0;i < rhs.m_row_n; i++){
        for(size_t j = 0;j < rhs.m_col_n; j++){
            os << std::setw(2) << rhs.row_elem(i, j) << ' ';
        }
        os << '\n';
    }
    return os;
}

runnable link

I have other experiment algorithm in code. We can ignore.

79817339
Vote

This approach sorts the numbers high to low, then fills the grid in top-right to bottom-left diagonals starting from 0,0. Diagonals values are permitted to be equal in this direction.
The loop fails early if it places an invalid number.


const data = [[54, 95, 98, 26, 3, 39, 77, 30, 83, 62, 20, 92, 61, 59, 26, 63, 92, 49, 38, 51, 99, 64, 65, 52, 98, 18, 90, 97, 96, 13, 74, 3, 88, 88, 67, 10],[49, 13, 73, 54, 4, 98, 36, 33, 12, 22, 35, 18, 39, 83, 92, 77, 50, 77, 57, 64, 0, 35, 86, 98, 28, 1, 53, 59, 28, 33, 56, 37, 98, 26, 81, 13],[95, 84, 44, 16, 42, 73, 0, 53, 14, 63, 81, 91, 42, 14, 13, 59, 91, 24, 99, 71, 73, 34, 60, 65, 82, 55, 16, 75, 7, 18, 68, 6, 61, 6, 80, 41],[27, 63, 35, 81, 56, 24, 70, 27, 59, 13, 36, 62, 73, 6, 61, 86, 48, 40, 88, 71, 52, 1, 9, 57, 50, 40, 20, 10, 3, 29, 19, 94, 99, 8, 74, 83],[46, 75, 78, 14, 89, 76, 37, 26, 85, 78, 81, 27, 99, 41, 96, 52, 21, 65, 71, 48, 60, 32, 48, 31, 85, 35, 88, 5, 78, 22, 31, 97, 43, 80, 52, 45],[0, 98, 50, 12, 0, 83, 46, 66, 67, 23, 52, 55, 41, 95, 5, 17, 78, 98, 74, 45, 97, 98, 96, 54, 48, 79, 29, 0, 73, 6, 16, 33, 20, 88, 9, 23],[9, 2, 10, 57, 79, 65, 65, 0, 19, 64, 3, 18, 20, 93, 10, 30, 9, 0, 40, 51, 87, 34, 52, 71, 28, 23, 73, 61, 77, 60, 66, 91, 57, 58, 2, 9],[27, 63, 51, 6, 3, 10, 7, 36, 80, 51, 93, 71, 73, 25, 3, 77, 35, 56, 36, 36, 77, 97, 14, 1, 78, 83, 5, 51, 99, 5, 93, 90, 1, 36, 83, 4],[89, 94, 67, 64, 31, 66, 59, 16, 80, 22, 78, 72, 56, 83, 98, 10, 9, 57, 23, 4, 80, 37, 65, 30, 71, 55, 42, 9, 60, 18, 39, 58, 44, 79, 48, 29],[79, 51, 3, 82, 81, 58, 99, 88, 54, 88, 81, 5, 63, 79, 52, 64, 48, 64, 68, 11, 50, 66, 35, 71, 9, 86, 11, 97, 42, 41, 0, 2, 56, 38, 15, 63],[94, 35, 12, 94, 79, 40, 91, 45, 37, 98, 43, 30, 80, 81, 87, 19, 74, 87, 93, 35, 88, 89, 79, 44, 6, 87, 27, 49, 98, 44, 68, 39, 42, 87, 61, 84],[5, 37, 89, 80, 31, 40, 1, 10, 54, 67, 23, 1, 75, 43, 49, 27, 29, 69, 43, 41, 7, 16, 63, 70, 5, 61, 74, 87, 2, 61, 50, 72, 91, 56, 12, 99],[43, 35, 83, 94, 69, 45, 76, 73, 83, 60, 80, 31, 59, 34, 39, 63, 35, 13, 94, 78, 2, 24, 87, 21, 36, 38, 55, 19, 10, 82, 13, 95, 88, 54, 94, 75],[66, 10, 58, 21, 82, 10, 32, 91, 66, 65, 3, 12, 4, 38, 12, 96, 55, 54, 73, 16, 74, 41, 28, 49, 19, 98, 16, 90, 93, 82, 56, 68, 14, 70, 31, 19],[13, 79, 47, 31, 79, 31, 56, 65, 94, 73, 57, 35, 74, 85, 84, 39, 24, 26, 12, 56, 46, 46, 71, 0, 57, 61, 77, 32, 14, 1, 81, 71, 69, 66, 57, 69],[8, 39, 23, 14, 88, 44, 81, 46, 5, 26, 50, 11, 71, 19, 86, 33, 88, 62, 81, 13, 60, 96, 7, 78, 6, 88, 77, 94, 74, 63, 48, 40, 29, 47, 64, 6],[95, 36, 61, 3, 75, 84, 95, 8, 57, 42, 43, 77, 27, 65, 56, 78, 34, 96, 18, 23, 46, 17, 86, 17, 89, 28, 96, 18, 24, 90, 93, 49, 47, 69, 91, 48],[76, 95, 10, 10, 58, 67, 25, 41, 0, 49, 13, 40, 59, 29, 62, 64, 97, 47, 22, 42, 39, 44, 16, 95, 23, 91, 14, 48, 90, 39, 16, 92, 46, 38, 49, 16],[60, 42, 28, 28, 61, 10, 37, 90, 99, 9, 45, 15, 61, 20, 6, 89, 99, 5, 34, 28, 58, 45, 10, 43, 73, 5, 45, 78, 68, 48, 44, 56, 78, 69, 52, 99],[99, 92, 63, 87, 23, 73, 25, 25, 31, 97, 14, 12, 77, 96, 73, 80, 86, 15, 63, 71, 44, 34, 51, 28, 77, 24, 19, 74, 87, 34, 59, 40, 82, 13, 25, 15],[48, 59, 63, 45, 51, 64, 88, 99, 81, 29, 69, 27, 7, 28, 9, 77, 50, 80, 7, 64, 3, 24, 6, 22, 31, 69, 92, 66, 13, 3, 70, 81, 73, 50, 45, 42],[0, 49, 29, 50, 38, 38, 24, 71, 8, 5, 56, 6, 90, 2, 3, 35, 40, 89, 24, 27, 74, 77, 54, 7, 1, 76, 92, 16, 55, 23, 47, 62, 33, 1, 80, 47],[1, 61, 12, 89, 56, 47, 88, 63, 73, 49, 9, 78, 68, 69, 19, 53, 76, 39, 49, 83, 38, 70, 62, 79, 19, 7, 70, 4, 90, 57, 90, 20, 52, 37, 64, 17],[0, 99, 18, 20, 0, 5, 93, 66, 87, 4, 62, 47, 94, 27, 73, 82, 12, 37, 39, 63, 59, 71, 71, 36, 84, 53, 90, 93, 9, 21, 94, 76, 80, 4, 40, 30],[57, 17, 99, 26, 7, 0, 81, 29, 95, 51, 46, 8, 16, 19, 15, 48, 89, 65, 69, 14, 94, 9, 3, 78, 59, 20, 41, 45, 97, 99, 57, 52, 94, 12, 55, 28],[19, 49, 58, 20, 73, 65, 0, 72, 82, 12, 64, 43, 34, 58, 11, 74, 20, 75, 0, 23, 6, 25, 81, 39, 44, 65, 54, 57, 72, 72, 10, 69, 31, 10, 45, 20],[68, 46, 13, 68, 81, 62, 28, 75, 66, 91, 27, 31, 20, 38, 1, 45, 76, 79, 14, 62, 58, 66, 17, 79, 61, 91, 86, 33, 57, 95, 74, 7, 31, 85, 97, 80],[67, 31, 55, 44, 11, 39, 50, 79, 64, 75, 97, 13, 22, 19, 42, 58, 55, 10, 51, 37, 73, 55, 22, 40, 35, 97, 77, 92, 43, 24, 69, 25, 64, 61, 48, 77],[7, 17, 84, 29, 87, 12, 85, 22, 65, 70, 73, 14, 32, 9, 27, 3, 11, 42, 88, 20, 37, 10, 88, 77, 68, 92, 71, 80, 83, 32, 35, 85, 91, 52, 26, 73],[62, 24, 97, 27, 49, 2, 50, 36, 14, 59, 63, 1, 45, 98, 80, 64, 59, 80, 55, 96, 87, 89, 19, 81, 40, 31, 73, 48, 29, 34, 63, 11, 12, 7, 84, 28],[23, 82, 3, 66, 59, 65, 49, 80, 16, 73, 39, 69, 45, 15, 6, 14, 4, 97, 76, 57, 34, 13, 77, 72, 98, 24, 34, 54, 23, 41, 67, 6, 80, 19, 30, 92],[20, 35, 58, 63, 21, 75, 58, 8, 30, 44, 97, 21, 3, 86, 78, 89, 93, 42, 29, 89, 53, 17, 89, 6, 8, 14, 48, 98, 15, 58, 28, 46, 51, 55, 17, 78],[42, 41, 8, 12, 37, 81, 33, 58, 59, 31, 3, 67, 77, 90, 6, 2, 14, 45, 49, 28, 79, 93, 7, 75, 52, 52, 46, 86, 98, 77, 66, 38, 41, 11, 41, 2],[8, 45, 28, 85, 58, 99, 18, 86, 95, 16, 59, 45, 26, 35, 36, 96, 61, 82, 32, 20, 62, 47, 93, 3, 44, 71, 11, 11, 31, 28, 42, 7, 18, 58, 40, 89],[87, 4, 99, 46, 73, 27, 7, 44, 26, 62, 15, 10, 14, 77, 97, 70, 58, 23, 85, 73, 76, 97, 6, 92, 52, 51, 9, 84, 29, 56, 15, 38, 41, 7, 88, 76],[30, 0, 80, 70, 10, 78, 91, 80, 3, 42, 24, 70, 39, 7, 7, 43, 9, 2, 23, 96, 76, 87, 19, 11, 5, 10, 74, 10, 49, 16, 34, 54, 40, 55, 75, 93],[92, 54, 58, 53, 99, 84, 53, 50, 56, 65, 10, 89, 19, 2, 6, 94, 44, 69, 67, 60, 79, 5, 30, 23, 15, 8, 48, 26, 32, 31, 43, 59, 81, 9, 67, 93],[7, 58, 97, 4, 22, 36, 5, 83, 32, 69, 83, 54, 18, 48, 49, 43, 36, 37, 96, 0, 28, 18, 64, 56, 52, 97, 43, 95, 36, 8, 48, 35, 60, 41, 48, 81],[50, 78, 66, 51, 45, 80, 65, 87, 0, 5, 87, 91, 34, 78, 47, 89, 51, 32, 88, 64, 52, 8, 86, 59, 11, 5, 1, 12, 57, 87, 75, 83, 17, 69, 96, 61],[74, 18, 35, 33, 97, 4, 22, 39, 41, 10, 66, 59, 11, 71, 90, 28, 78, 66, 51, 25, 48, 89, 74, 62, 13, 19, 67, 99, 19, 88, 15, 83, 26, 86, 31, 93],[93, 32, 27, 13, 61, 53, 49, 35, 59, 13, 54, 68, 75, 31, 18, 79, 33, 59, 87, 86, 14, 26, 21, 19, 12, 59, 75, 36, 7, 71, 25, 25, 6, 85, 29, 99],[94, 78, 11, 70, 49, 22, 25, 67, 34, 65, 85, 58, 76, 10, 44, 22, 75, 72, 65, 54, 68, 60, 84, 52, 19, 26, 61, 69, 88, 76, 37, 41, 81, 1, 23, 57],[15, 72, 24, 37, 95, 16, 76, 61, 34, 47, 68, 93, 18, 92, 32, 17, 20, 66, 51, 33, 65, 38, 71, 45, 81, 59, 34, 35, 84, 37, 14, 6, 41, 60, 57, 54],[83, 86, 73, 77, 75, 67, 5, 92, 43, 13, 98, 92, 69, 80, 50, 25, 64, 0, 64, 25, 98, 40, 66, 77, 4, 18, 52, 50, 28, 36, 17, 54, 5, 83, 2, 40],[25, 68, 57, 61, 55, 81, 56, 71, 95, 72, 37, 21, 91, 8, 23, 26, 38, 44, 45, 84, 37, 51, 13, 42, 90, 12, 67, 21, 96, 31, 99, 97, 2, 90, 99, 56],[47, 90, 19, 59, 82, 32, 52, 99, 74, 8, 93, 18, 79, 22, 24, 63, 84, 50, 55, 86, 94, 23, 83, 65, 67, 48, 16, 15, 81, 78, 7, 43, 12, 52, 58, 28],[54, 39, 86, 53, 24, 55, 72, 2, 6, 15, 78, 8, 35, 70, 59, 80, 74, 99, 95, 32, 44, 26, 47, 49, 48, 14, 95, 66, 54, 76, 37, 81, 85, 37, 45, 7],[19, 38, 6, 31, 71, 53, 40, 85, 71, 52, 56, 25, 78, 32, 17, 85, 42, 24, 61, 42, 3, 54, 98, 68, 48, 39, 59, 59, 12, 25, 96, 98, 15, 88, 44, 45],[62, 70, 19, 57, 56, 68, 7, 13, 53, 87, 68, 69, 77, 39, 23, 94, 42, 10, 1, 28, 43, 31, 42, 48, 75, 95, 28, 10, 44, 50, 72, 47, 64, 96, 5, 63],[92, 85, 77, 92, 90, 27, 39, 57, 51, 41, 99, 78, 78, 53, 88, 59, 30, 65, 15, 25, 32, 32, 99, 64, 90, 40, 13, 45, 41, 73, 98, 12, 44, 73, 33, 32],[97, 36, 97, 58, 74, 56, 70, 80, 92, 84, 93, 16, 0, 34, 96, 85, 84, 16, 29, 22, 27, 42, 26, 40, 27, 80, 1, 40, 82, 25, 54, 31, 77, 25, 67, 73],[46, 91, 13, 50, 65, 68, 44, 15, 65, 58, 77, 21, 92, 70, 69, 95, 9, 84, 69, 71, 53, 65, 0, 33, 95, 4, 1, 28, 62, 27, 39, 38, 47, 39, 61, 81],[37, 0, 70, 66, 14, 20, 50, 68, 8, 0, 62, 41, 68, 35, 14, 69, 94, 62, 53, 84, 32, 22, 80, 81, 22, 66, 36, 65, 40, 53, 93, 0, 0, 33, 32, 7],[68, 73, 37, 13, 86, 20, 22, 97, 27, 10, 32, 57, 27, 11, 52, 7, 7, 48, 23, 14, 98, 25, 41, 6, 78, 63, 80, 38, 24, 75, 2, 61, 45, 93, 18, 94],[20, 14, 76, 73, 80, 30, 56, 33, 80, 18, 79, 66, 39, 3, 88, 25, 28, 24, 63, 88, 68, 28, 67, 49, 6, 18, 4, 49, 0, 96, 11, 22, 6, 41, 17, 50],[9, 61, 45, 7, 25, 86, 99, 39, 79, 13, 46, 74, 44, 3, 90, 43, 25, 9, 2, 27, 13, 15, 38, 98, 2, 88, 13, 51, 44, 80, 67, 85, 84, 40, 2, 68],[22, 48, 11, 46, 99, 88, 75, 32, 69, 66, 73, 10, 3, 31, 13, 44, 11, 17, 68, 0, 37, 86, 40, 92, 13, 61, 24, 69, 22, 11, 53, 1, 14, 53, 96, 29],[65, 27, 91, 56, 76, 11, 86, 34, 3, 15, 97, 42, 19, 98, 38, 78, 90, 37, 76, 55, 46, 18, 72, 92, 3, 38, 55, 54, 5, 0, 58, 24, 77, 70, 65, 55],[33, 48, 21, 34, 42, 60, 82, 33, 98, 27, 51, 33, 74, 55, 59, 96, 44, 35, 23, 28, 13, 52, 72, 9, 39, 52, 8, 30, 40, 8, 97, 43, 79, 89, 38, 80],[1, 29, 67, 37, 13, 29, 33, 96, 91, 24, 4, 67, 20, 71, 75, 95, 2, 63, 39, 14, 88, 2, 5, 17, 38, 40, 74, 79, 39, 62, 38, 58, 74, 4, 27, 97],[86, 8, 5, 54, 58, 78, 70, 51, 89, 94, 51, 55, 27, 6, 56, 44, 14, 72, 5, 27, 19, 50, 72, 58, 66, 24, 49, 28, 15, 12, 12, 37, 85, 89, 53, 38],[54, 1, 82, 23, 72, 55, 6, 96, 54, 22, 19, 63, 83, 50, 39, 75, 33, 29, 83, 14, 60, 92, 62, 83, 11, 34, 53, 77, 57, 63, 18, 17, 50, 9, 90, 36],[60, 78, 25, 81, 18, 1, 96, 39, 36, 82, 23, 78, 70, 80, 19, 55, 74, 38, 99, 37, 3, 87, 21, 26, 93, 89, 44, 13, 95, 92, 11, 71, 77, 10, 49, 90],[68, 68, 45, 82, 67, 7, 97, 49, 87, 83, 73, 70, 70, 87, 14, 37, 10, 21, 82, 71, 75, 13, 89, 93, 63, 11, 40, 18, 32, 69, 38, 53, 81, 63, 51, 76],[25, 36, 27, 62, 4, 51, 50, 74, 19, 10, 78, 94, 15, 49, 11, 26, 91, 80, 61, 80, 84, 87, 80, 52, 35, 28, 64, 91, 39, 58, 15, 55, 26, 72, 68, 35],[42, 66, 36, 17, 5, 31, 38, 90, 61, 8, 24, 0, 7, 40, 65, 67, 54, 61, 53, 16, 49, 76, 21, 63, 23, 72, 20, 9, 42, 34, 10, 6, 63, 25, 61, 28],[9, 98, 52, 95, 85, 61, 87, 96, 64, 98, 98, 83, 88, 4, 73, 29, 26, 67, 59, 34, 89, 49, 6, 16, 0, 61, 55, 76, 73, 64, 26, 63, 56, 64, 66, 86],[98, 2, 10, 34, 9, 10, 8, 46, 2, 95, 89, 65, 49, 1, 38, 15, 8, 22, 66, 80, 7, 77, 77, 70, 1, 7, 60, 59, 93, 7, 2, 98, 31, 95, 87, 18],[47, 20, 77, 92, 92, 78, 81, 7, 34, 20, 30, 40, 56, 79, 86, 84, 81, 40, 19, 28, 72, 35, 20, 85, 3, 68, 18, 4, 63, 83, 20, 12, 41, 63, 19, 58],[55, 10, 67, 18, 31, 16, 76, 57, 79, 64, 68, 37, 78, 60, 60, 46, 49, 32, 32, 3, 65, 74, 22, 79, 26, 29, 28, 86, 20, 99, 27, 99, 28, 30, 54, 20],[73, 87, 66, 32, 10, 75, 40, 94, 30, 99, 52, 10, 33, 33, 52, 36, 16, 90, 68, 62, 19, 33, 50, 22, 78, 47, 91, 22, 84, 83, 41, 17, 32, 83, 38, 23],[82, 26, 41, 53, 71, 22, 95, 55, 60, 14, 40, 42, 36, 43, 91, 50, 16, 93, 62, 72, 3, 14, 55, 48, 20, 17, 56, 38, 64, 87, 86, 92, 82, 75, 73, 76],[70, 18, 42, 41, 19, 44, 8, 90, 10, 73, 41, 39, 23, 69, 64, 55, 39, 80, 88, 13, 5, 29, 71, 53, 84, 71, 91, 97, 60, 67, 10, 15, 53, 37, 68, 91],[12, 99, 93, 43, 63, 51, 54, 89, 39, 8, 19, 27, 70, 94, 0, 70, 76, 1, 51, 30, 60, 88, 24, 69, 35, 36, 97, 43, 0, 70, 21, 84, 19, 6, 93, 92],[15, 83, 14, 61, 0, 18, 77, 34, 95, 92, 22, 76, 54, 9, 22, 43, 96, 91, 24, 12, 30, 22, 88, 72, 82, 38, 27, 10, 41, 2, 78, 25, 36, 20, 70, 55],[83, 6, 84, 58, 57, 42, 76, 75, 36, 39, 98, 55, 72, 72, 84, 81, 36, 9, 3, 44, 1, 50, 63, 1, 93, 24, 26, 20, 30, 68, 0, 24, 90, 26, 6, 88],[58, 38, 65, 42, 40, 25, 32, 39, 19, 31, 74, 36, 85, 74, 23, 20, 37, 41, 41, 63, 61, 9, 27, 39, 22, 0, 36, 34, 53, 53, 6, 40, 81, 18, 86, 8],[34, 1, 53, 24, 53, 46, 21, 59, 74, 75, 10, 49, 79, 74, 29, 68, 82, 75, 49, 62, 8, 58, 54, 34, 87, 4, 84, 34, 10, 82, 70, 35, 62, 9, 33, 77],[28, 49, 3, 98, 69, 36, 80, 53, 72, 68, 89, 22, 40, 52, 5, 66, 39, 38, 41, 45, 13, 12, 70, 12, 7, 86, 95, 83, 66, 92, 43, 13, 53, 80, 75, 33],[98, 98, 88, 3, 11, 32, 83, 24, 91, 79, 3, 55, 50, 95, 41, 69, 30, 89, 68, 47, 13, 35, 0, 86, 57, 8, 10, 31, 1, 40, 81, 2, 87, 10, 73, 0],[36, 8, 65, 86, 88, 65, 19, 33, 62, 24, 98, 34, 0, 80, 45, 53, 16, 28, 41, 65, 93, 34, 64, 85, 48, 98, 15, 51, 41, 65, 5, 9, 51, 17, 17, 91],[21, 49, 80, 99, 8, 32, 11, 36, 82, 59, 64, 59, 55, 73, 1, 23, 82, 59, 19, 16, 58, 18, 62, 36, 74, 30, 72, 79, 26, 31, 16, 40, 2, 27, 65, 26],[86, 24, 59, 75, 93, 17, 20, 42, 21, 4, 80, 0, 57, 91, 81, 84, 95, 13, 65, 85, 9, 15, 26, 90, 66, 20, 13, 98, 67, 27, 85, 49, 45, 65, 10, 84],[17, 16, 99, 46, 21, 66, 57, 69, 29, 42, 50, 92, 9, 11, 56, 62, 32, 15, 55, 25, 55, 90, 81, 74, 62, 98, 58, 65, 46, 77, 53, 10, 0, 59, 70, 91],[76, 89, 89, 89, 87, 87, 11, 51, 11, 44, 11, 50, 29, 88, 93, 31, 6, 26, 74, 34, 24, 30, 14, 74, 9, 47, 20, 17, 88, 14, 49, 87, 3, 65, 27, 73],[18, 18, 68, 23, 13, 98, 52, 92, 72, 75, 8, 8, 2, 33, 69, 23, 22, 16, 95, 76, 43, 83, 86, 27, 4, 58, 57, 97, 64, 22, 43, 32, 41, 2, 88, 26],[21, 20, 85, 29, 56, 31, 65, 45, 58, 26, 62, 21, 71, 31, 5, 57, 88, 42, 51, 39, 79, 83, 47, 99, 25, 31, 9, 24, 13, 63, 95, 78, 80, 74, 78, 89],[39, 90, 68, 22, 85, 14, 4, 20, 41, 51, 67, 75, 20, 48, 91, 65, 61, 44, 66, 3, 83, 30, 93, 23, 19, 99, 46, 88, 87, 35, 3, 88, 35, 67, 88, 28],[63, 21, 64, 10, 7, 38, 25, 17, 32, 36, 7, 99, 46, 65, 74, 71, 63, 42, 30, 72, 29, 80, 42, 65, 27, 24, 16, 16, 70, 2, 54, 60, 35, 79, 88, 39],[10, 75, 23, 44, 33, 33, 11, 13, 23, 3, 44, 37, 64, 66, 35, 32, 34, 22, 18, 15, 6, 37, 25, 36, 20, 4, 49, 58, 59, 21, 80, 95, 0, 31, 93, 28],[54, 30, 99, 86, 7, 38, 8, 18, 26, 83, 15, 83, 45, 5, 24, 67, 6, 39, 65, 67, 83, 99, 29, 41, 64, 62, 25, 53, 54, 34, 24, 41, 99, 28, 8, 29],[30, 60, 67, 20, 43, 56, 79, 43, 92, 85, 69, 9, 62, 22, 62, 24, 68, 33, 18, 61, 25, 14, 21, 59, 86, 59, 53, 26, 1, 80, 9, 36, 4, 5, 85, 47],[57, 64, 8, 17, 69, 23, 77, 29, 69, 52, 80, 86, 18, 93, 78, 17, 36, 60, 94, 25, 80, 90, 87, 86, 64, 23, 87, 95, 19, 69, 91, 82, 37, 27, 27, 46],[52, 19, 54, 87, 1, 4, 41, 68, 93, 56, 36, 13, 32, 25, 83, 48, 59, 5, 37, 58, 83, 93, 53, 77, 44, 63, 49, 1, 94, 4, 28, 30, 85, 15, 85, 90],[75, 72, 89, 33, 98, 23, 81, 41, 35, 17, 4, 1, 46, 60, 83, 69, 27, 35, 33, 83, 61, 61, 21, 72, 82, 72, 82, 6, 59, 51, 60, 37, 82, 20, 88, 54],[20, 37, 13, 75, 81, 78, 36, 75, 22, 45, 81, 63, 58, 72, 81, 7, 9, 39, 49, 8, 84, 66, 71, 58, 41, 56, 5, 2, 83, 47, 16, 3, 93, 95, 97, 10],[94, 83, 74, 92, 8, 10, 12, 92, 28, 28, 31, 98, 10, 33, 62, 70, 85, 53, 8, 31, 75, 67, 38, 2, 5, 85, 44, 25, 54, 69, 33, 61, 75, 57, 79, 82],[60, 34, 79, 9, 2, 28, 80, 24, 2, 76, 26, 34, 61, 22, 40, 31, 52, 14, 30, 2, 88, 54, 41, 73, 6, 45, 13, 22, 70, 51, 74, 69, 19, 66, 33, 78],[3, 11, 50, 41, 23, 41, 45, 2, 62, 95, 55, 73, 1, 98, 33, 68, 82, 96, 24, 81, 1, 58, 59, 41, 45, 9, 99, 49, 16, 97, 54, 75, 92, 14, 71, 63],[18, 73, 63, 61, 88, 15, 27, 49, 82, 95, 0, 54, 71, 76, 64, 65, 84, 39, 61, 56, 52, 60, 88, 92, 75, 83, 94, 61, 76, 76, 14, 11, 5, 95, 71, 68]];

const resolveArray = (data) => {
    const gridSize = data.length**0.5;
    if (gridSize%1 !== 0) // only handles squares
        return undefined;

    const maxGridIndex = gridSize - 1;
    const diagonals = 2*gridSize - 1;
    const sorted = data.sort((a,b) => a < b ? 1 : -1);
    const grid = new Array(gridSize).fill(undefined, 0, gridSize).map(() => []);
    let readIndex = 0;

    for (let i = 0; i <= diagonals; i++) {
        let y = Math.min(maxGridIndex, i);
        let x = Math.max(0, i - maxGridIndex);
        while (x <= maxGridIndex && y >= 0) {
            grid[x][y] = sorted[readIndex++];
            // fail early if an invalid number is placed above or left
            if (
                (x > 0 && grid[x-1][y] <= grid[x][y])
                || (y > 0 && grid[x][y-1] <= grid[x][y])
            )
                return null;

            // increment x and decrement y to get a top-right to bottom-left line
            x++;
            y--;
        }
    }

    return grid;
}

const main = () => {
    const summary = {
        results: [],
        solved: 0,
        unsolved: 0,
        invalidArray: 0,
    };

    for (let i = 0; i < data.length; i++) {
        const result = resolveArray(data[i]);
        if (result === null) {
            summary.unsolved++;
        } else if (result === undefined) {
            summary.invalidArray++;
        } else {
            summary.results[i] = result;
            summary.solved++;
        }
    }

    console.info(summary);
}

main();
79817328
Vote

I am Yash, and here is my solution which give you exact possible and impossible grids count

const check = {possible: 0, impossible: 0};

for (let k = 0; k < bigArr.length; k++) {
  let unsortedArr = bigArr[k];
  if(unsortedArr.length < 36){
    console.log("Array length less than 36, impossible to form 6x6 grid ==> ", unsortedArr);
    continue;
  }
  let sortedArr = unsortedArr.sort((a, b) => b - a);
  let result = [];

  for (let i = 0; i < 6; i++) {
    let shortArrs = [];
    for (let j = 0; j < sortedArr.length; j++) {
      if (j == 35 && shortArrs.length < 6) break;
      if (shortArrs.length === 6) break;
      if (shortArrs.includes(sortedArr[j])) continue;
      shortArrs.push(sortedArr[j]);
      sortedArr.splice(j, 1);
      j--;
    }
    if (shortArrs.length < 6) {
      check.impossible += 1;
      break;
    }
    // checking all coloumns also in desending order
    if (i > 0 && result.length > 0) {
      let prevArr = result[i - 1];
      if (prevArr[0] <= shortArrs[0]) {
        check.impossible += 1;
        break;
      }
    }
    result.push(shortArrs);
  }
  if (result.length === 6){
    check.possible += 1;
  }
}
console.log("Final Check ==> ", check);
79817226
Vote

Update - this is an updated version of my original submission. It's basically the same concept with a few tweaks. See links for working code:

Approach

The way I've solved this is to sort values in descending order, then arrange them in diagonal stripes (/, not \) starting at the top left corner. This ensures rows and columns are sorted in descending order.

For the sample data:

[95, 75, 75, 74, 74, 74, 54, 45, 40]

they get arranged in this order:

 0  1  3
 2  4  6
 5  7  8

which becomes:

95 75 74
75 74 54
74 45 40

Then, we just need to check each adjacent cell (vertically or horizontally) is strictly descending. As long as there are no ascending or matching adjacent values the grid is valid.

Arranging

The core of this solution is to build a "layout grid" which basically contains the position that each cell in the solution appears in the input list. This calculates the diagonal stripes shown above...

int[,] GetLayoutGrid(int width, int height)
{

    // build a grid containing layout indices
    // (fill in diagonal stripes ("/" not "\") starting at the top left cell)
    //
    //  square               wide                 tall
    //  0  1  3  6 10 15     0  1  3  6  9 12     0  1  3
    //  2  4  7 11 16 21     2  4  7 10 13 15     2  4  6
    //  5  8 12 17 22 26     5  8 11 14 16 17     5  7  9
    //  9 13 18 23 27 30                          8 10 12
    // 14 19 24 28 31 33                         11 13 15
    // 20 25 29 32 34 35                         14 16 17

    var layout = new int[height, width];

    var i = 0;
    var lastCol = width - 1;
    var diagonals = width + height - 1;

    // fill the diagonals
    for (var d = 0; d < diagonals; d++)
    {

        // calculate the start position of the current diagonal
        // by walking along the top row and then down the right column
        var startRow = Math.Max(0, d - lastCol);
        var startCol = Math.Min(d, lastCol);

        // calculate the length of the diagonal based on start position
        var length = Math.Min(startCol + 1, height - startRow);

        // fill the diagonal to the bottom or left edge of the array
        for (int l = 0, row = startRow, col = startCol; l < length; l++, row++, col--)
        {
            layout[row, col] = i++;
        }

    }

    return layout;

}

Verifying

Once we've got the layout grid we don't really even need to allocate and build the result array - we can just use the layout grid to pick values out of the input list. For example given a sorted input list, the value at [row, col] in the solution is:

var layout = GetLayoutGrid(6, 6);
var value = sorted[layout[row, col]];

And since all of the samples are a 6 x 6 grid, we only need to calculate the layout grid once.

The following code uses this layout grid to check for a valid (i.e. strictly decreasing) input list:

/// <summary>
/// Helper method to verify there's the same number of items in a list and a 2d array.
/// <summary>
(int Rows, int Cols) VerifyLayoutSize(IList<int> values, int[,] layout)
{
    var rows = layout.GetUpperBound(0) + 1;
    var cols = layout.GetUpperBound(1) + 1;
    if (values.Count != (rows * cols))
    {
       throw new ArgumentException("The list of values must contain the same number of items as the layout grid.");
    }
    return (rows, cols);
}

/// <summary>
/// Returns true if all adjacent cells are strictly descending.
//  Returns false if any two adjacent cells are equal or ascending.
/// <summary>
bool IsValidList(IList<int> values, int[,] layout)
{
    (var rows, var cols) = VerifyLayoutSize(values, layout);
    for (var row = 0; row < rows; row++)
    {
        for (var col = 0; col < cols; col++)
        {
            // we don't assume values are sorted, so we need to check adjacent columns *and* rows        
            if (
                ((row > 0) && (values[layout[row, col]] >= values[layout[row - 1, col]])) ||
                ((col > 0) && (values[layout[row, col]] >= values[layout[row, col - 1]]))
            )
            {
                return false;
            }
        }
    }
    return true;
}

Serializing

And to serialize the solution into the format required by the challenge:

/// <summary>
/// Convert to a string representation for display.
/// </summary>
string SerializeGrid(List<int> values, int[,] layout)
{
    (var rows, var cols) = VerifyLayoutSize(values, layout);
    // split the values into chunks that each contain a row of the solution
    var rowChunks = Enumerable.Range(0, rows)
        .Select(
            row => Enumerable.Range(0, cols).Select(col => values[layout[row, col]])
        );
    // join each chunk into a formatted "row string", and then join the row strings into the result
    return "[" + string.Join(
        ", ", rowChunks.Select(chunk => "[" + string.Join(", ", chunk) + "]")
    ) + "]";
}

Putting it together

Then it's just a case of plugging in the sample data and a test harness:

// read the samples from somewhere
var samples = GetSamples();

// build the layout used to map sample values to grid positions.
// this assumes all sample lists are to be arranged in a 6 x 6 grid.
// we only need to calculate this once and then use it to lay out each sample.
var layout = GetLayoutGrid(6, 6);

var impossible = 0;
for (var i = 0; i < samples.Count; i++)
{
    var sorted = samples[i].OrderDescending().ToList();
    if (IsValidList(sorted, layout))
    {
        Console.WriteLine($"{i}: {SerializeGrid(sorted, layout)}");
    }
    else
    {
        Console.WriteLine($"{i}: impossible");
        impossible++;
    }
}

Console.WriteLine();
Console.WriteLine($"impossible count: {impossible}");

which tells me there are 45 invalid sequences in RandomNumbers.txt.

79818848
Vote

Congrats on posting a nice, clean, no-frills solution, unlike the needlessly complicated monsters submitted by so many others.

The fiddled code contains a small brain-f*rt, though: it prints the number of sortable inputs as number of 'impossible' inputs.

79819262
Vote

Following DarthGizka's comment, as you are using count to count the number of impossible cases, it should be incremented in the else-block.

    if (valid)
    {
        Console.WriteLine($"{i}: {SerializeGrid(grid)}");
    }
    else
    {
        Console.WriteLine($"{i}: impossible");
    count++;
    }

Your solution works great otherwise. Cheers.

79819404
Vote

@DarthGizka, @M-- - thanks for the feedback. I've fixed the blooper re the "impossible" count, and I've made some cosmetic changes to ArrangeGrid so it takes the layout as a parameter so it can be cached in the top level code. Also renamed HasConsecutiveValues to be a bit more descriptive.

Doesn't really change the overall approach although I've seen some neat ideas in both your solutions that I was tempted to use (like @DarthGizka only checking left for duplicate values since above is redundant, and the diagonal walk algorithm in @M--'s) but that felt like cheating :-).

79817157
Vote

I've written mine in Julia. This was a fun challenge!

I'm fairly certain that a greedy algorithm works: I think if you have a valid solution that isn't greedy, the greedy solution is also valid.

The proof would rely on the fact that this problem imposes a partial ordering on the numbers in 2D, i.e a number at (x + k, y) < (x, y) and (x, y + k) < (x, y), and therefore the only requirement is that each number is strictly larger than all numbers below and to the right. It therefore makes no sense not to get your largest numbers out the way ASAP.

Honestly the most annoying part was figuring out how to correctly index the diagonals.

EDIT: I realised I was meant to print the count of invalid, not valid, grids.

function parse_line(line)
    return parse.(Int, split(line[begin+1:end-1], ", "))
end

function parse_file(file)
    return reduce(hcat, parse_line.(readlines(file)))
end

const N = 6
const N2 = N * N
function check_sixgrid(numbers)
    sort_nums = sort(numbers)

    # Simple checks: needs a unique max
    sort_nums[1] == sort_nums[2] && return (false, zeros(Int, N, N))
    sort_nums[N2 - 1] == sort_nums[N2] && return (false, zeros(Int, N, N))
    
    # The requirements are equivalent to asserting that the sort_nums can be sorted along the taxicab metric?
    # Try a greedy algorithm!!
    grid = zeros(Int, N, N)
    grid[1, 1] = pop!(sort_nums)
    grid[N, N] = popfirst!(sort_nums)

    for i in 2:2N-2 # Diagonal index
        # Fill in the i-th Diagonal
        for j in max(1, i - N + 1):min(i, N)
            x = i - j + 1
            y = j
            len_diag = min(i, 2N - i)
            neighbours = []
            x > 1 && push!(neighbours, grid[x - 1, y])
            y > 1 && push!(neighbours, grid[x, y - 1])
            next = findlast(z -> all(z .< neighbours), sort_nums)
            if isnothing(next) || next < lastindex(sort_nums) - len_diag
                # Either no valid candidate, or we missed a larger number that should have fit here
                return false, grid
            end
            grid[(i - j + 1), j] = sort_nums[next]
            deleteat!(sort_nums, next)
        end
    end
    return true, grid
end

function (@main)()
    file = "RandomNumbers.txt"
    acc = 0
    for (idx, line) in enumerate(eachcol(parse_file(file)))
        result, grid = check_sixgrid(line)
        if result
            println("Found valid grid for line: ", idx)
            display(grid)
        else
            println("No valid grid found for line: ", idx)
            acc += 1
        end
        println("-----")
    end
    println("Total invalid grids found: ", acc)
    return nothing
end

79817103
Vote
####
# Language: python
# This solution exploits the idea that any set with solutions has  at least one solution where the diagonals are also sorted
# Also, the number of distinct values must be at least the number of diagonals (row_size + col_size - 1) or else we can not meet the no ties constraints
# The entire list of numbers is sorted in descending order
# Then we fill the grid diagonally, beginning in the upper left corner and filling down and left for each subsequent diagonal
# Each diagonal is compared to the last so we can short circuit if they do not follow the constraints
# When a solution can not be found, we return -1
# The solution is general enough to support other size grids (even non-square)
# For the inputs provided 55 have solutions
####

import ast
row_size = 6
col_size = 6

def main():
    lines = open("RandomNumbers.txt", "r").readlines()
    answers = []
    for l in lines:
        list_initial: list[int] = parse_line(l)
        assert len(list_initial) == row_size * col_size, "There should be {} numbers... seems to be {}".format(row_size * col_size, len(list_initial))
        answer = solve(list_initial)
        answers.append(answer)
    check(answers)
    return answers

def solve(numbers: list[int]):
    distinct_numbers = set(numbers)
    num_diagonals = col_size + row_size - 1
    if len(distinct_numbers) < num_diagonals:
        print("Not enough distinct numbers to fill the grid with decreasing rows and columns.")
        return -1 # impossible to fill grid
    result = [[0 for _ in range(col_size)] for _ in range(row_size)]
    r = 0
    c = 0
    sorted_numbers_desc = sorted(numbers, reverse=True)
    diagonals = []
    return addNextHighestToResult(result, sorted_numbers_desc, r, c, diagonals)

def addNextHighestToResult(result: list[list[int]], 
    sorted_numbers_desc: list[int], 
    r: int, 
    c: int, 
    diagonals: list[list[int]]):
    if len(sorted_numbers_desc) == 0:
        return result
    # from (r,c) what is the size of the diagnoal going down left?
    print("At row {}, col {}".format(r, c))
    
    diag_size = min(row_size - r, c + 1) # problem at r>0
    print(row_size-r, c+1,diag_size)
    # get the next diag_size highest numbers from desc list
    this_diagonal = sorted_numbers_desc[:diag_size]

    if len(diagonals) > 0 and not diagonals_are_compatible(diagonals[-1], this_diagonal):
        return -1 # impossible to fill grid
    diagonals.append(this_diagonal)

    apply_diagonal_to_result(result, this_diagonal, r, c)
    # traverse top row, then rightmost column
    next_diagonal_start_row = r if c < col_size - 1 else r + 1
    next_diagonal_start_col = c + 1 if c < col_size - 1 else c
    print(diagonals)
    remaining_numbers = sorted_numbers_desc[diag_size:]
    print(remaining_numbers)
    return addNextHighestToResult(result, remaining_numbers, next_diagonal_start_row, next_diagonal_start_col, diagonals)

def diagonals_are_compatible(diagonal1: list[int], diagonal2: list[int]) -> bool:
    if diagonal1[0] == diagonal2[0]:
        return False
    if diagonal1[-1] == diagonal2[-1]:
        return False
    if diagonal1[-1] == diagonal2[0]:
        if len(diagonal1) < len(diagonal2):
            for i in range(1, len(diagonal1)):
                if diagonal1[i] == diagonal2[i]:
                    return False
        else:
            for i in range(1, len(diagonal1)):
                if diagonal1[i] == diagonal2[i-1]:
                    return False

    return True

def apply_diagonal_to_result(result: list[list[int]], diagonal: list[int], r: int, c: int):
    for i in range(len(diagonal)):
        result[r + i][c - i] = diagonal[i]

def parse_line(line) -> list[int]:
    return ast.literal_eval(line.strip())

def check(answers: list[list[int]]):
    i=1
    impossible_count = 0
    for a in answers:
        print("Answer #{}".format(i))
        i+=1
        if a == -1:
            print("Impossible to fill grid")
            impossible_count += 1
            continue
        
        assert len(a) == row_size; 
        for row in a:
            print(row)
            assert len(row) == col_size; 
        for r in range(row_size):
            for c in range(col_size):
                if r > 0: assert a[r][c] < a[r-1][c], "Column not decreasing at row {}, col {}".format(r, c)
                if c > 0: assert a[r][c] < a[r][c-1], "Row not decreasing at row {}, col {}".format(r, c)
    print("Total impossible grids: {}".format(impossible_count))

main()
79816983
Vote

My solution uses SAT solver

from ortools.sat.python import cp_model
from collections import Counter
from typing import List, Optional
import time


def can_arrange_grid_cpsat(
    numbers: List[int], rows: int = 6, cols: int = 6, max_time: float = 10.0
) -> Optional[List[List[int]]]:
    if len(numbers) != rows * cols:
        return None

    freq = Counter(numbers)

    for value, count in freq.items():
        if count > min(rows, cols):
            return None

    model = cp_model.CpModel()

    min_val = min(numbers)
    max_val = max(numbers)

    grid_vars = {}
    for r in range(rows):
        for c in range(cols):
            grid_vars[(r, c)] = model.NewIntVar(min_val, max_val, f"grid_{r}_{c}")

    # Rows must be descending
    for r in range(rows):
        for c in range(cols - 1):
            model.Add(grid_vars[(r, c)] > grid_vars[(r, c + 1)])

    # Columns must be descending
    for c in range(cols):
        for r in range(rows - 1):
            model.Add(grid_vars[(r, c)] > grid_vars[(r + 1, c)])

    # Match frequency of each value
    unique_values = sorted(freq.keys())
    for value in unique_values:
        count = freq[value]
        appearances = []
        for r in range(rows):
            for c in range(cols):
                is_value = model.NewBoolVar(f"is_{value}_at_{r}_{c}")
                model.Add(grid_vars[(r, c)] == value).OnlyEnforceIf(is_value)
                model.Add(grid_vars[(r, c)] != value).OnlyEnforceIf(is_value.Not())
                appearances.append(is_value)

        model.Add(sum(appearances) == count)

    solver = cp_model.CpSolver()
    solver.parameters.max_time_in_seconds = max_time
    solver.parameters.num_search_workers = 8

    status = solver.Solve(model)

    if status in (cp_model.OPTIMAL, cp_model.FEASIBLE):
        grid = []
        for r in range(rows):
            row = []
            for c in range(cols):
                row.append(solver.Value(grid_vars[(r, c)]))
            grid.append(row)
        return grid

    return None


def solve_challenge(input_file: str, output_file: str):
    with open(input_file, "r", encoding="utf-8") as f:
        lines = f.readlines()

    results = []
    solved = 0
    impossible = 0
    total_time = 0

    for idx, line in enumerate(lines, 1):
        line = line.strip()
        if not line:
            continue

        numbers_str = line.strip("[]")
        numbers = [int(x.strip()) for x in numbers_str.split(",")]

        print(f"Test {idx:3d}... ", end="", flush=True)

        start = time.time()
        grid = can_arrange_grid_cpsat(numbers, max_time=10.0)
        elapsed = time.time() - start
        total_time += elapsed

        if grid is None:
            results.append(f"Test {idx}: IMPOSSIBLE")
            impossible += 1
            print(f"IMPOSSIBLE ({elapsed:.2f}s)")
        else:
            results.append(f"Test {idx}:")
            for row in grid:
                results.append(f"  {row}")
            solved += 1
            print(f"SOLVED ({elapsed:.2f}s)")

    total = solved + impossible
    results.append(f" Total: {total} | Solved: {solved} | Impossible: {impossible}")

    with open(output_file, "w", encoding="utf-8") as f:
        f.write("\n".join(results))

    print(f"Solved: {solved} | Impossible: {impossible}")


solve_challenge("RandomNumbers.txt", "solution_output.txt")

Solved: 55 | Impossible: 45

79816751
Vote

I noticed the following: Each field of the result matrix has a specific subset size of greater/smaller numbers which must exist. I. e., for the top-left field, there must be 35 numbers in our array which are smaller than the number in this field. For the bottom-left field, there must be 5 numbers which are smaller and 5 numbers which are greater. It is easy to see that this is a necessary condition for a valid solution to exist. I have not bothered to prove the sufficiency of these conditions, but by gut feeling alone, I implemented this solution and the results seem to work out. 55 out of 100 instances were solvable and the algorithm did not create any invalid solutions.

import json

LENGTH = 6

def find_solution(numbers):
    numbers.sort()
    # For each number, count how many numbers are smaller and how many are larger
    subset_sizes = {}
    i = 0
    while i < len(numbers):
        j = i
        while i < len(numbers) - 1 and numbers[i] == numbers[i + 1]:
            i += 1
        i += 1
        subset_sizes[numbers[j]] = (j, len(numbers) - i)

    MAX_DIAGONAL = 2 * LENGTH - 2
    j = 0
    result = [[None for _ in range(LENGTH)] for _ in range(LENGTH)]
    # iterate over the matrix in diagonal order, i.e. for a 3x3 matrix:
    # 0 1 3
    # 2 4 6
    # 5 7 8
    for i in range(MAX_DIAGONAL + 1):
        _max = min(i, LENGTH - 1)
        _min = i - _max
        for s in range(0, _max - _min + 1):
            x = _min + s
            y = _max - s
            # calculate how many smaller and larger numbers must exist for position (x, y) to build a valid solution
            required_smaller_subset_size = (LENGTH - x) * (LENGTH - y) - 1
            required_larger_subset_size = (x + 1) * (y + 1) - 1
            actual_smaller_subset_size, actual_larger_subset_size = subset_sizes[numbers[j]]
            if actual_smaller_subset_size < required_smaller_subset_size or actual_larger_subset_size < required_larger_subset_size:
                # there are fewer larger/smaller numbers than required: no solution is possible
                return None
            else:
                # simply set the next number at position (x, y) - it is guaranteed to be valid
                result[x][y] = numbers[j]
            j += 1
    return result

def validate_solution(solution):
    # check whether any field has a neighbour to the left or above that is smaller or equal
    for i in range(LENGTH):
        for j in range(LENGTH):
            if j > 0 and solution[i][j] >= solution[i][j - 1]:
                return False
            if i > 0 and solution[i][j] >= solution[i - 1][j]:
                return False
    return True


# read the input file
with open("RandomNumbers.txt", "r") as file:
    numbers = [json.loads(line.strip()) for line in file.readlines()]

successes = 0
for instance in numbers:
    print("INSTANCE:", instance)
    solution = find_solution(instance)
    if solution:
        print("SOLUTION FOUND:", solution)
        if not validate_solution(solution):
            print("ERROR: SOLUTION INVALID!")
            break
        else:
            successes += 1
    else:
        print("NO SOLUTION FOUND")

print(f"DONE.\nTotal successful solutions: {successes} out of {len(numbers)}")
79816717
Vote

Using my implementation we find 45 impossible cases, with the rest having a valid sort. Below I will show the functions I used with hopefully good docstrings + comments so others can understand. While some functions like is_possible() can be omitted I included them to improve overall runtime for bigger problems.

For my solution we need two imports, while Counter could be replaced with native dict but this way its cleaner.

import numpy as np
from collections import Counter

First we define a function that sorts out impossible cases prior.
Specifically we check the following:

  • The n-th smallest/ biggest value can have at most **min(**n, grid_size) duplicates to be able to fit.

  • If you have n duplicates you need at least n * floor((n-1)/2) bigger/smaller values to back-fill the grid.

def is_possible(the_list: list[int], grid_size: int) -> bool:
    """
    A function that checks if a list can be aranged on a grid wrt. to the constraints in the problem.

    Constraints:
        - Each row is descendingly sorted (ties are not allowed).
        - Each column is descendingly sorted (ties are not allowed).

    :param the_list: The list to check.
    :param grid_size: The grid size that is used.
    :return:
    """

    # Sanity check if the list can fill the grid.
    if len(the_list) != grid_size**2:
        print(f"Failed: grid size {grid_size} requires {grid_size**2} values but got {len(the_list)}")
        return False

     counts = Counter(the_list)
    
    def _check(values):
        cum_count = 0
        for i, val in enumerate(values[:grid_size], start=1):
            if counts[val] > i:
                print(f"Failed: {i}th value {val} occurs {counts[val]} times, max allowed {i}")
                return False
            required = counts[val] * (counts[val] - 1) // 2
            if cum_count < required:
                print(f"Failed: cannot place {counts[val]} copies of {val} on diagonals, "
                      f"need {required} bigger/smaller values, only {cum_count} exist")
                return False
            cum_count += counts[val]
        return True

    sorted_unique = sorted(counts.keys())
    return _check(sorted_unique[::-1]) and _check(sorted_unique)

We also need to define a function that checks our constraints once we generate a solution.
Here we use np.diff() as this shows duplicates if it is 0 and shows irregular order if its > 0. Also this is fast.

def verify(grid: np.ndarray) -> bool:
    """Check that all rows and columns are strictly descending."""
    bad_rows = np.unique(np.where(np.diff(grid, axis=1) >= 0))
    bad_cols = np.unique(np.where(np.diff(grid, axis=0) >= 0))

    if bad_rows.size:
        print(f"Descending violation in rows {bad_rows}")
    if bad_cols.size:
        print(f"Descending violation in columns {bad_cols}")

Now we go to the sorting function. The workings are described in the docstring.

def get_sort(the_list: list[int], grid_size: int = 6) -> list[int] | None:
    """
    Sort the list to fit on a grid wrt. to the constraints in the problem.

    Constraints:
        - Each row is descendingly sorted (ties are not allowed).
        - Each column is descendingly sorted (ties are not allowed).

    Algorithm:
        - First check for failing conditions -> look at is_possible()
        - Populate grid in waterfall manner (always add diagonals -> push index if can be pushed to left)
        - Sort rows to ensure decreasing order.
        - Fix last ties due to sort by swapping with smallest bigger value of previous row.

    :param the_list: The list to sort.
    :param grid_size: The grid to sort on.
    :return:
    """
    if not is_possible(the_list, grid_size):
        return None

    grid = np.full((grid_size, grid_size), None, dtype=object)
    value_counts = Counter(the_list)

    def _can_place(value: int, grid: np.ndarray) -> np.ndarray:
        filled = np.where(grid == None, np.inf, grid)
        above = np.r_[np.inf * np.ones((1, grid.shape[1])), filled[:-1]]
        left = np.c_[np.inf * np.ones((grid.shape[0], 1)), filled[:, :-1]]
        return (above > value) & (left > value) & (grid == None)

    rows, cols = np.indices((grid_size, grid_size))
    for value in sorted(value_counts.keys(), reverse=True):
        num = value_counts[value]
        for s in range(2 * grid_size - 1):
            mask = (rows + cols == s) & (grid == None) & _can_place(value, grid)
            coords = np.argwhere(mask)
            if len(coords) >= num:
                for r, c in coords[:num]:
                    grid[r, c] = value
                break
        else:
            print("Failed: Could not place.")
            return None

    grid[:] = -np.sort(-grid, axis=1)  # Here we do the last sort.
    grid = repair_ties(grid)
    return grid if verify(grid) else None

As you can see after the last sort some ties can appear again, we fix them using the following function:

def repair_ties(grid: np.ndarray) -> bool:
    """A simple repair function that looks for the smallest value in row-1 if a value in row is tied with a value un row+1."""
    n, m = grid.shape
    progress = True

    while progress:
        progress = False
        for i in range(1, n-1):
            prev, cur, below = grid[i-1], grid[i], grid[i+1]
            columns_with_duplicates = np.where(cur == below)[0]
            if columns_with_duplicates.size == 0:
                continue

            for c in columns_with_duplicates:
                val = cur[c]
                candidates = np.where(prev > val)[0]  # Check which candidates can be swapped.
                if candidates.size == 0:
                    continue

                # choose smallest candidate to swap
                j = candidates[np.argmin(prev[candidates])]
                prev[j], cur[c] = cur[c], prev[j]

                # local check: rows descending and affected columns descending
                if np.all(prev[:-1] > prev[1:]) and np.all(cur[:-1] > cur[1:]) \
                        and prev[c] > cur[c] and prev[j] > cur[j]:
                    progress = True  # keep swap
                else:
                    prev[j], cur[c] = cur[c], prev[j]
    return grid

Now if you want to run this stuff altogether you can use it as:

with open("RandomNumbers.txt", "r") as f:
    tests = []
    for line in f:
        line = line.strip().replace('[', '').replace(']', '')
        numbers = list(map(int, line.split(',')))
        tests.append(numbers)

impossibles = 0
for a in tests:
    elem = get_sort(a)
    if elem is None:
        impossibles += 1

print(f"No solution for: {impossibles} cases.")
79816697
Vote

For this delightful puzzle the challenge was not so much in the coding - which was extremely simple - but to prove that the assumptions underlying the code are valid. The solution is based on a couple of observations:

  1. sorting the input vector into non-increasing order and assigning the values to a 6 x 6 matrix in a diagonal fashion produces a viable candidate solution

  2. if the candidate solution produced by the diagonal method does not fulfil the requirements then there is no solution, period

  3. if input values are assigned via the diagonal method then testing the correctness of a solution reduces to checking left neighbours for those matrix elements that have one

  4. it is not necessary to put the input values into an actual matrix in order to test viability; the sorted input vector can simply be treated as a 'diagonal-major' storage form of a matrix analogous to the more usual row-major or column-major forms

Observations (1) through (3) are based on the transitivity of the 'greater than or equal to' relation.

Observation (4) reduces the processing for a given input vector to sorting it into non-increasing order and then doing the left-neighbour check. The latter can be done with the aid of a lookup table that gives the 'diagonal-major' index of the respective left neighbour for those matrix elements that have one and the upper neighbour for those that don't. For the first element there is nothing to check against, so it will not be checked and its comparand index is only a placeholder.

The elements in the left-most matrix column do not have left neighbours. For these elements the choice was either to skip the comparison (i.e. complicating the algorithm with an additional branch and some convention for signalling that no comparison is necessary) or simply performing a redundant comparison with the upper neighbour. This comparison is redundant because whenever it would report a rule violation then it cannot be reached because the test of its diagonal predecessor will have failed already. This follows from transitivity and the fact that any violation uncovered in diagonal-major order can only be value equality, not inversion. There can never be any inversion here because the elements are assigned in non-increasing order.

So here's the meat of my solution, without frills, bells & whistles (the full code is at the end of this post):

foreach (var input_line in input_lines) 
{ 
    var sorted_descending = input_line[1..^1].Split(',', StringSplitOptions.TrimEntries) 
        .Select(byte.Parse) 
        .OrderByDescending(b => b) 
        .ToArray(); 
    var i = 0; 
 
    // check for rule compliance vs. left or upper neighbour (first cell skipped because it has neither) 
    while (++i < sorted_descending.Length) 
        if (sorted_descending[i] == sorted_descending[COMPARAND_INDICES[i]]) 
            break; 
 
    if (i == 36)  // all cells compared without finding a rule violation 
    { 
        var string_builder = new StringBuilder(6 * (6 * 4 + 2)); 
        var separator = "[["; 
 
        for (int j = 0, y = 0; y < 6; ++y, separator = "], [") 
            for (var x = 0; x < 6; ++x, separator = ", ") 
                string_builder 
                    .Append(separator) 
                    .Append(sorted_descending[DIAGONAL_FOR_ROWMAJOR[j++]]); 
 
        // ToString() necessary to keep LINQPad from dumping the builder instead of the text 
        Console.WriteLine(string_builder.Append("]]").ToString()); 
    } 
    else // rule violation found 
    { 
        Console.WriteLine("impossible"); 
    } 
} 

For the 100 input vectors in RandomNumbers.txt this finds 45 'impossible' inputs and 55 inputs with solutions.

When I started out, observations (1) through (3) were mere intuitions and not yet backed by rigorous proof. The proof was only found when I tried to find a brute-force strategy for assigning the input values to the matrix that was not based on trying out all input permutations. Any strategy that took the rules into account sort of reduced more or less directly to the diagonal method outlined above; and this gave me the clue I needed to prove that observations (1) through (3) are facts and not mere intuitions.

Note: most of the stuff from here on is only concerned with the verification of observation (3) by exhaustive enumeration of all 34,359,738,368 relevant possibilities, because the mathematical proof kept eluding me for quite a while. So you may want to skip to the end of this post.

There are 10^72 different possible input vectors of length 36 with elements drawn from the range 0 through 99. This makes exhaustive correctness testing impossible. However, there are two observations that help reduce the number of possibilities that need to be considered.

  • The correctness of the sorting algorithm can be taken as given if we use a tried and trusted library function. Ergo we only need to check all suitably ordered input vectors.

  • An input vector like [99,42,42,23] is strictly equivalent to [2,1,1,0] as far as the algorithm is concerned, a mere renaming. The algorithm cares only about jumps (i.e. decrements) in value and runs of values. So we need to test only the canonical forms where values are assigned starting with 0 and only ever jump by exactly 1.

This reduces the total number of possibilities to 2^35: the last element of a canonical input vector is fixed at 0, and all other elements can either be the same as their successor or one more. Hence there are 35 places with two possibilities each, giving 2^35 (i.e. 34,359,738,368).

Canonical input vectors can be represented compactly as strings of base36 digits because there are at most 36 distinct element values. This string form is easy to understand/interpret, and it can be processed efficiently. I'm using it to pass initial configurations to thread start functions. Here is the function I use to generate all canonical possibilities of a given length:

static string[] generate_initial_configurations_ (int length) 
{ 
    var configurations = new List<string>(); 
    var a = new char[length]; 
    var c = '0'; 
 
    for (int k = 0; ; ++c) 
    { 
        while (k < length) 
            a[k++] = c; 
 
        configurations.Add(new string(a, 0, length)); 
        k = length - 1; 
        c = a[k]; 
 
        for (var previous_char = c; ; --k, previous_char = c) 
            if (k < 1)  // left-most place must remain at '0' 
                return configurations.ToArray(); 
            else if ((c = a[k - 1]) == previous_char) 
                break;  // found the rightmost place that can be incremented 
    } 
}

NB: this function only does decimal digits, not base36, because the length parameter does not go beyond 6 in my use case. Caveat emptor.

Output for length 4:

0000 
0001 
0011 
0012 
0111 
0112 
0122 
0123 

The sequences are ascending (non-decreasing) instead of descending (non-increasing) as required by the challenge because I find them easier to understand/digest in this way, and so I based the whole verification process on the mirrored problem with ascending sequences. The number of configurations is a power of two, which makes it ideal for distributing the work if the number of logical processors is a power of two as well (e.g. 16 for many mid-level consumer CPUs, 32 for i9 13900HX or Ryzen 9955HX).

The critical path of the generator logic can be made slightly more efficient by dropping the ordering requirement and enumerating sequences backwards instead of in lexicographic order. Here's the version I used in the verification code. This loop tests all possibilities starting with the initial configuration contained in the input vector and stopping when a carry would occur from the modifiable part of the input vector back into the fixed part. Pointers are used instead of arrays in order to eliminate superfluous bounds checks and to help the ADHD-afflicted JIT compiler produce good code (p points at the beginning of the modifiable range within the input vector when the loop is entered; square_matrix is a 36-byte buffer that the verify function uses to construct the square matrix in row-major form):

// these two translation tables are needed by the verify_() function; we fix them 
// here in order to keep the overhead out of the inner loop 
fixed (byte* comparand_indices = COMPARAND_INDICES, diagonal_for_linear = DIAGONAL_FOR_ROWMAJOR) 
{ 
    for ( ; ; --previous_value) 
    { 
        while (p < e)  // assign ascending values to the rest of the vector 
            *p++ = previous_value++; 
 
        verify_(input_vector, comparand_indices, diagonal_for_linear, square_matrix); 
        p = e - 1; 
        previous_value = *p; 
 
        for ( ; ; --p) 
            if (p < start_of_modifiable_range) 
                return;  // done
            else if (previous_value > p[-1]) 
                break; // found the rightmost place that can be decremented 
    } 
} 

Another code fragment that might be of interest is the left-neighbour check at the beginning of the verify_() function:

var p = input_vector; 
var e = input_vector + N; 
 
// the first element does not have a left or upper neighbour, hence the initial increment
while (++p < e) 
    if (*p == input_vector[*++comparand_indices]) 
        break; 
 
var vector_ok = p == e;

Brutally simple, lean and mean. :-) The code then goes on to shuffle the vector values into row-major matrix form and to perform the left and upper neighbour checks specified in the challenge, to see whether the value of vector_ok is correct. Note: since the failure mode is '==', this code is the same regardless of whether ascending or descending sequences are used.

With this the verification of the 34,359,738,368 possibilities took about a minute on the Ryzen 9955HX mini PC that I use as compute monster, performing more than 500 million verifications per second. My i9 13900HX laptop took about twice as long because its thermal throttling kicked in even earlier than that of the Ryzen mini PC, shutting off half of the logical cores. The testing actually did flush out a bug that was due to a mistyped entry in the COMPARAND_INDICES array (and which would normally have been caught by a unit test that takes a few nanoseconds to run).

Here is the full code (C# in the form of a LINQPad script); there are two prepro #defines that can be enabled to get friendlier output. The DUMP_AS_MATRIX thing is especially useful because it has LINQPad dump the results as beautiful little matrices instead of the text form of the output required by the challenge (which is not very easy to digest for humans). The code is also available at DotNetFiddle for your execution pleasure.

// xp_SOCC_13_integer_sorting_in_a_grid.linq
// 2025-11-10

// print the input vector before each solution in order to provide the context:
//#define PRINT_INPUT_VECTORS

// make LINQPad dump positive results in matrix form:
//#define DUMP_AS_MATRIX

void Main ()
{
    var input_file = Path.Combine(Path.GetDirectoryName(Util.CurrentQueryPath), "RandomNumbers.txt");

    process_input_lines_(File.ReadAllLines(input_file));
}

static void process_input_lines_ (IEnumerable<string> input_lines)
{
    int solved = 0, insoluble = 0;

    foreach (var input_line in input_lines)
    {
        var input_vector = input_line[1..^1].Split(',', StringSplitOptions.TrimEntries)
            .Select(byte.Parse)
            .ToArray();
#if PRINT_INPUT_VECTORS
        Console.WriteLine("\n{0}\n", string.Join(' ', input_vector));
#endif
        var sorted_descending = input_vector // effectively a matrix stored in diagonal form
            .OrderByDescending(b => b)
            .ToArray();
        var i = 0;

        // check for rule compliance vs. left or upper neighbour (first cell skipped because it has neither)
        while (++i < sorted_descending.Length)
            if (sorted_descending[i] == sorted_descending[COMPARAND_INDICES[i]])
                break;

        if (i == 36)  // all cells compared without finding a rule violation
        {
            var string_builder = new StringBuilder(6 * (6 * 4 + 2));
            var separator = "[[";

            for (int j = 0, y = 0; y < 6; ++y, separator = "], [")
                for (var x = 0; x < 6; ++x, separator = ", ")
                    string_builder
                        .Append(separator)
                        .Append(sorted_descending[DIAGONAL_FOR_ROWMAJOR[j++]]);

#if DUMP_AS_MATRIX
            as_matrix_(sorted_descending).Dump();
#else
            // ToString() necessary to keep LINQPad from dumping the builder instead of the text
            Console.WriteLine(string_builder.Append("]]").ToString());
#endif
            ++solved;
        }
        else // rule violation found
        {
            Console.WriteLine("impossible");
            ++insoluble;
        }
    }

    Console.WriteLine("\n{0} impossible, {1} solved", insoluble, solved);
}

/// translates a row-major flat index into the corresponding index of the diagonal form;
/// this is necessary because outputs need to be printed in row-major form
static readonly byte[] DIAGONAL_FOR_ROWMAJOR =
{
     0,  1,  3,  6, 10, 15,
     2,  4,  7, 11, 16, 21,
     5,  8, 12, 17, 22, 26,
     9, 13, 18, 23, 27, 30,
    14, 19, 24, 28, 31, 33,
    20, 25, 29, 32, 34, 35
};

/// gives the index of the respective left neighbour in the diagonal form (or the upper
/// neighbour if no left neighbour exists); first element is a placeholder and not used
static readonly byte[] COMPARAND_INDICES =
{
    99,  0,  0,  1,  2,  2,
     3,  4,  5,  5,  6,  7,
     8,  9,  9, 10, 11, 12,
    13, 14, 14, 16, 17, 18,
    19, 20, 22, 23, 24, 25,
    27, 28, 29, 31, 32, 34
};

static byte[,] as_matrix_ (byte[] diagonal_form)
{
    const int K = 6;
    var result = new byte[K, K];

    for (int i = 0, y = 0; y < K; ++y)
        for (var x = 0; x < K; ++x)
            result[y, x] = diagonal_form[DIAGONAL_FOR_ROWMAJOR[i++]];

    return result;
}
79817234
Vote

For your observation #3, numbers in the rightmost column do not have a number above and to the right to check the number above them. Therefore, at least in the rightmost column, you need to test the numbers above them, too. The number above could be a duplicate even if the number to the left isn't.

I haven't analyzed the random data, but it's possible that that condition wasn't created.

79817438
Vote

Because of the non-increasing diagonal assignment we have the following invariant:

upper_neighbour ≥ left_neighbour ≥ ... ≥ current_cell

Therefore the current cell cannot have a problem with its upper neighbour unless it also has a problem with its left neighbour.

Did I mention that exact mathematical proof eluded me for quite a while? ;-) That's why I went for the exhaustive test, in order get the certainty that my mathematical self could not provide (at the time).

79819806
Vote

Bonus Optimisation Notes

Left-neighbour check for cells in the left-most column: closer analysis shows that doing a redundant comparison instead of adding a branch for skipping the comparison was the right choice. The additional branch would have destroyed the uniformity of execution for the comparison loop and it would necessarily have caused costly branch mispredictions.

For reference, here's the comparison loop again:

var p = input_vector; 
var e = input_vector + N; 
 
// the first element does not have a left or upper neighbour, hence the initial increment
while (++p < e) 
    if (*p == input_vector[*++comparand_indices]) 
        break; 
 
var vector_ok = p == e;

Both conditions remain false until the loop terminates, and if the compiler arranges the instructions correctly then the only misprediction will occur at loop exit.

The fact that two conditions need to be checked instead of only one means little on modern superscalar processors. Low-power or embedded scalar processors (or antique CPUs like the good old Z80, 68k, i8086 and so on) would profit from using the sentinel technique to reduce the number of conditions to exactly one.

If the input vector is allocated to be one byte bigger then we can add an entry to COMPARAND_INDICES[] that references this additional cell. Comparing a cell value with itself must always return true, so we don't even need to give the sentinel any specific value. Thus the equality check in the loop will always return true eventually (either by finding a conflict or by running into the sentinel).

var p = input_vector; 
var e = input_vector + N; 

// the first element does not have a left or upper neighbour, hence the initial increment
while (*++p == input_vector[*++comparand_indices]) 
    break; 
 
var vector_ok = p == e;

The downside is that the loop must always execute an extra round, so the use of such a technique will have to be considered (and profiled) carefully.

NB: if it is known that there will always be a readable byte in memory after the input vector then it does not need to be enlarged by one byte. For the scalar CPU architectures I mentioned this is often the case (at least in real mode).

79816291
Vote

After a few days of theory crafting, I worked out that all valid grids can be rearranged such that the items fall along "forward slash" diagonals in descending order starting from the top left.

36 35 33 30 26 21  OR  11 10 09 08 07 06 
34 32 29 25 20 15      10 09 08 07 06 05
31 28 24 19 14 10      09 08 07 06 05 04
27 23 18 13 09 06      08 07 06 05 04 03
22 17 12 08 05 03      07 06 05 04 03 02
16 11 07 04 02 01      06 05 04 03 02 01

This pattern ensures three things:

  1. Any previously placed numbers are >= the current number.
  2. Any numbers placed can only be constrained by previously placed numbers.
  3. If the current number is equal to any of its constraining neighbors, there is no other legal place for the current number to go and, therefore, no valid arrangement exists.

Here is my solution in Zig 0.15.2:

const std = @import("std");
const Reader = std.io.Reader;

const GRID_SIDE_LEN: comptime_int = 6;
const GRID_SIZE = GRID_SIDE_LEN * GRID_SIDE_LEN;

// Optimal input buffer size calculation
const num_brackets_in: comptime_int = 2;
const num_digits_in = GRID_SIZE * 2;
const num_space_commas_in = (GRID_SIZE - 1) * 2;
const input_buf_size = num_brackets_in + num_digits_in + num_space_commas_in + 1;
var input_buf: [input_buf_size]u8 = undefined;

// Optimal output buffer size calculation
const num_brackets_out = (GRID_SIDE_LEN * 2) + 2;
const num_digits_out = num_digits_in;
const num_space_commas_out = (((GRID_SIDE_LEN - 1) * GRID_SIDE_LEN) + (GRID_SIDE_LEN - 1)) * 2;
const output_buf_size = num_brackets_out + num_digits_out + num_space_commas_out + 1;

var stdout_buf: [output_buf_size]u8 = undefined;
var stdout_writer = std.fs.File.stdout().writer(&stdout_buf);
const stdout = &stdout_writer.interface;

fn readList(reader: *Reader) !?[GRID_SIZE]u8 {
    var list: [GRID_SIZE]u8 = undefined;

    const line = try reader.takeDelimiter('\n') orelse return null;
    const list_start = std.mem.indexOfScalar(u8, line, '[') orelse return error.ParseError;
    const after_brace = line[list_start + 1..];
    const list_part = std.mem.sliceTo(after_brace, ']');

    // ] not found
    if (after_brace.len == list_part.len) {
        return error.ParseError;
    }
    
    var numbers_tokenized = std.mem.tokenizeAny(u8, list_part, " ,");
    var list_idx: usize = 0;
    while (numbers_tokenized.next()) |num_part| : (list_idx += 1) {
        list[list_idx] = try std.fmt.parseInt(u8, num_part, 10);
    }
    if (list_idx != GRID_SIZE) {
        return error.ParseError;
    }
    return list;
}

fn sortGridOrImpossible(list: [GRID_SIZE]u8) ?[GRID_SIDE_LEN][GRID_SIDE_LEN]u8 {
    var sorted_list: [GRID_SIZE]u8 = undefined;
    @memcpy(&sorted_list, &list);
    std.mem.sort(u8, &sorted_list, {}, comptime std.sort.desc(u8));

    var grid: [GRID_SIDE_LEN][GRID_SIDE_LEN]u8 = undefined;
    var list_idx: usize = 0;
    
    // Iterate over all diagonals
    for (0..GRID_SIDE_LEN + GRID_SIDE_LEN - 1) |diag| {
        var col: usize = if (diag < GRID_SIDE_LEN) diag + 1 else GRID_SIDE_LEN;
        const start_row: usize = if (diag < GRID_SIDE_LEN) 0 else diag - (GRID_SIDE_LEN - 1);
        const end_row: usize = if (diag < GRID_SIDE_LEN) diag + 1 else GRID_SIDE_LEN;

        for (start_row..end_row) |row| {
            col -= 1;

            const next_val = sorted_list[list_idx];
            const row_match = row != 0 and grid[row - 1][col] == next_val;
            const col_match = col != 0 and grid[row][col - 1] == next_val;
            if (row_match or col_match) {
                return null;
            }

            grid[row][col] = next_val;
            list_idx += 1;
        }
    }
    return grid;
}

fn printGrid(grid: [GRID_SIDE_LEN][GRID_SIDE_LEN]u8, writer: *std.io.Writer) !void {
    try writer.print("[", .{});
    for (grid, 0..) |grid_row, row_idx| {
        if (row_idx > 0) {
            try writer.print(", ", .{});
        }
        try writer.print("[", .{});
        for (grid_row, 0..) |num, col_idx| {
            if (col_idx > 0) {
                try writer.print(", ", .{});
            }
            try writer.print("{d}", .{num});
        }
        try writer.print("]", .{});
    }
    try writer.print("]\n", .{});
    try writer.flush();
}

fn verifyGrid(grid: [GRID_SIDE_LEN][GRID_SIDE_LEN]u8) bool {
    for (grid, 0..) |row, row_idx| {
        for (row, 0..) |num, col_idx| {
            if (row_idx > 0 and num >= grid[row_idx - 1][col_idx]) {
                return false;
            }

            if (col_idx > 0 and num >= grid[row_idx][col_idx - 1]) {
                return false;
            }
        }
    }
    return true;
}

pub fn main() !void {
    const argv = std.os.argv;
    var input_file: std.fs.File = if (argv.len >= 2) 
        try std.fs.cwd().openFileZ(argv[1], .{ .mode = .read_only })
    else
        std.fs.File.stdin();

    var input_reader = input_file.reader(&input_buf);
    const input = &input_reader.interface;
    var impossible_count: usize = 0;
    
    while (try readList(input)) |list| {
        const grid = sortGridOrImpossible(list);
        if (grid) |real_grid| {
            std.debug.assert(verifyGrid(real_grid));
            try printGrid(real_grid, stdout);
        } else {
            try stdout.print("Impossible\n", .{});
            try stdout.flush();
            impossible_count += 1;
        }
    }
    
    try stdout.print("Total impossible: {d}\n", .{impossible_count});
    try stdout.flush();
}
79816160
Vote

Observations

  • If a solution exists, we can always construct a solution from it by sorting all the left-down diagonals descendingly.
  • That solution can be created from the input by just sorting it descending and then filling those left-down diagonals from left to right.
  • As a result we can just create that solution and then check if it is valid to see if a solution exists.

Implementation

  • To check if a matrix has all rows and columns strongly descending, we just check for each element that it is smaller than its left and top neighbors (if they exist)
  • To construct the matrix, my implementation computes which index of the input to use based on the diagonal d = row + column.
    • The first half of the diagonals just start with index d * (d + 1) / 2
    • for the second half of the diagonals we must consider that our matrix is not endless, and the diagonal isn't filled from row 0 nor to column 0. We balance out these unfilled fields by subtracting (d - gridSize + 1).squared(), which is the total number of unfilled spaces up to that diagonals starting point.
import java.io.File
import kotlin.math.max

const val gridSize = 6

private fun Int.squared() = this * this
private fun Array<IntArray>.isStronglyDescending(): Boolean {
    for (row in 0..<gridSize) {
        for (column in 0..<gridSize) {
            val number = this[row][column]
            if ((row > 0 && this[row - 1][column] <= number) || (column > 0 && this[row][column - 1] <= number)) {
                return false
            }
        }
    }
    return true
}

private fun printGrid(grid: Array<IntArray>) {
    grid.forEach { row -> println(row.joinToString(" ") { "%2d".format(it) }) }
}

fun main() {
    val input = File("RandomNumbers.txt").readLines()

    var failures = 0
    for (line in input) {
        val numbers = line.removeSurrounding("[", "]").split(", ").map(String::toInt).sortedDescending()
        println()
        println(numbers)
        val grid = Array(gridSize) { row ->
            IntArray(gridSize) { column ->
                val d = row + column
                val start = d * (d + 1) / 2 - max(0, d - gridSize + 1).squared()
                numbers[start + row]
            }
        }
        if (grid.isStronglyDescending()) {
            printGrid(grid)
        } else {
            println("Impossible")
            failures++
        }
    }
    println()
    println("Total: ${input.size}, Succeeded: ${input.size - failures}, Failed: $failures")
}

Result

[99, 98, 98, 97, 96, 95, 92, 92, 90, 88, 88, 83, 77, 74, 67, 65, 64, 63, 62, 61, 59, 54, 52, 51, 49, 39, 38, 30, 26, 26, 20, 18, 13, 10, 3, 3]
Impossible

[98, 98, 98, 92, 86, 83, 81, 77, 77, 73, 64, 59, 57, 56, 54, 53, 50, 49, 39, 37, 36, 35, 35, 33, 33, 28, 28, 26, 22, 18, 13, 13, 12, 4, 1, 0]
Impossible

[99, 95, 91, 91, 84, 82, 81, 80, 75, 73, 73, 71, 68, 65, 63, 61, 60, 59, 55, 53, 44, 42, 42, 41, 34, 24, 18, 16, 16, 14, 14, 13, 7, 6, 6, 0]
99 95 91 81 73 61
91 84 80 71 60 42
82 75 68 59 42 18
73 65 55 41 16 14
63 53 34 16 13  6
44 24 14  7  6  0

[99, 94, 88, 86, 83, 81, 74, 73, 71, 70, 63, 62, 61, 59, 57, 56, 52, 50, 48, 40, 40, 36, 35, 29, 27, 27, 24, 20, 19, 13, 10, 9, 8, 6, 3, 1]
99 94 86 74 63 56
88 83 73 62 52 36
81 71 61 50 35 24
70 59 48 29 20 10
57 40 27 19  9  6
40 27 13  8  3  1

[99, 97, 96, 89, 88, 85, 85, 81, 80, 78, 78, 78, 76, 75, 71, 65, 60, 52, 52, 48, 48, 46, 45, 43, 41, 37, 35, 32, 31, 31, 27, 26, 22, 21, 14, 5]
99 97 89 85 78 65
96 88 81 78 60 46
85 80 76 52 45 35
78 75 52 43 32 27
71 48 41 31 26 21
48 37 31 22 14  5

[98, 98, 98, 97, 96, 95, 88, 83, 79, 78, 74, 73, 67, 66, 55, 54, 52, 50, 48, 46, 45, 41, 33, 29, 23, 23, 20, 17, 16, 12, 9, 6, 5, 0, 0, 0]
Impossible

[93, 91, 87, 79, 77, 73, 71, 66, 65, 65, 64, 61, 60, 58, 57, 57, 52, 51, 40, 34, 30, 28, 23, 20, 19, 18, 10, 10, 9, 9, 9, 3, 2, 2, 0, 0]
Impossible

[99, 97, 93, 93, 90, 83, 83, 80, 78, 77, 77, 73, 71, 63, 56, 51, 51, 51, 36, 36, 36, 36, 35, 27, 25, 14, 10, 7, 6, 5, 5, 4, 3, 3, 1, 1]
Impossible

[98, 94, 89, 83, 80, 80, 79, 78, 72, 71, 67, 66, 65, 64, 60, 59, 58, 57, 56, 55, 48, 44, 42, 39, 37, 31, 30, 29, 23, 22, 18, 16, 10, 9, 9, 4]
98 94 83 79 67 59
89 80 78 66 58 44
80 72 65 57 42 30
71 64 56 39 29 18
60 55 37 23 16  9
48 31 22 10  9  4

[99, 97, 88, 88, 86, 82, 81, 81, 79, 79, 71, 68, 66, 64, 64, 63, 63, 58, 56, 54, 52, 51, 50, 48, 42, 41, 38, 35, 15, 11, 11, 9, 5, 3, 2, 0]
99 97 88 81 71 63
88 86 81 68 63 51
82 79 66 58 50 38
79 64 56 48 35 11
64 54 42 15  9  3
52 41 11  5  2  0

[98, 98, 94, 94, 93, 91, 89, 88, 87, 87, 87, 87, 84, 81, 80, 79, 79, 74, 68, 61, 49, 45, 44, 44, 43, 42, 40, 39, 37, 35, 35, 30, 27, 19, 12, 6]
Impossible

[99, 91, 89, 87, 80, 75, 74, 72, 70, 69, 67, 63, 61, 61, 56, 54, 50, 49, 43, 43, 41, 40, 37, 31, 29, 27, 23, 16, 12, 10, 7, 5, 5, 2, 1, 1]
Impossible

[95, 94, 94, 94, 88, 87, 83, 83, 82, 80, 78, 76, 75, 73, 69, 63, 60, 59, 55, 54, 45, 43, 39, 38, 36, 35, 35, 34, 31, 24, 21, 19, 13, 13, 10, 2]
Impossible

[98, 96, 93, 91, 90, 82, 82, 74, 73, 70, 68, 66, 66, 65, 58, 56, 55, 54, 49, 41, 38, 32, 31, 28, 21, 19, 19, 16, 16, 14, 12, 12, 10, 10, 4, 3]
98 96 91 82 68 56
93 90 74 66 55 32
82 73 66 54 31 19
70 65 49 28 16 12
58 41 21 16 12 10
38 19 14 10  4  3

[94, 85, 84, 81, 79, 79, 77, 74, 73, 71, 71, 69, 69, 66, 65, 61, 57, 57, 57, 56, 56, 47, 46, 46, 39, 35, 32, 31, 31, 26, 24, 14, 13, 12, 1, 0]
94 85 81 77 71 61
84 79 74 69 57 47
79 73 69 57 46 32
71 66 57 46 31 24
65 56 39 31 14 12
56 35 26 13  1  0

[96, 94, 88, 88, 88, 86, 81, 81, 78, 77, 74, 71, 64, 63, 62, 60, 50, 48, 47, 46, 44, 40, 39, 33, 29, 26, 23, 19, 14, 13, 11, 8, 7, 6, 6, 5]
Impossible

[96, 96, 95, 95, 93, 91, 90, 89, 86, 84, 78, 77, 75, 69, 65, 61, 57, 56, 49, 48, 47, 46, 43, 42, 36, 34, 28, 27, 24, 23, 18, 18, 17, 17, 8, 3]
Impossible

[97, 95, 95, 92, 91, 90, 76, 67, 64, 62, 59, 58, 49, 49, 48, 47, 46, 44, 42, 41, 40, 39, 39, 38, 29, 25, 23, 22, 16, 16, 16, 14, 13, 10, 10, 0]
97 95 92 76 59 47
95 91 67 58 46 39
90 64 49 44 39 23
62 49 42 38 22 16
48 41 29 16 14 10
40 25 16 13 10  0

[99, 99, 99, 90, 89, 78, 78, 73, 69, 68, 61, 61, 60, 58, 56, 52, 48, 45, 45, 45, 44, 43, 42, 37, 34, 28, 28, 28, 20, 15, 10, 10, 9, 6, 5, 5]
Impossible

[99, 97, 96, 92, 87, 87, 86, 82, 80, 77, 77, 74, 73, 73, 71, 63, 63, 59, 51, 44, 40, 34, 34, 31, 28, 25, 25, 25, 24, 23, 19, 15, 15, 14, 13, 12]
99 97 92 86 77 63
96 87 82 74 63 34
87 80 73 59 34 25
77 73 51 31 25 19
71 44 28 24 15 14
40 25 23 15 13 12

[99, 92, 88, 81, 81, 80, 77, 73, 70, 69, 69, 66, 64, 64, 63, 59, 51, 50, 50, 48, 45, 45, 42, 31, 29, 28, 27, 24, 22, 13, 9, 7, 7, 6, 3, 3]
Impossible

[92, 90, 89, 80, 77, 76, 74, 71, 62, 56, 55, 54, 50, 49, 47, 47, 40, 38, 38, 35, 33, 29, 27, 24, 24, 23, 16, 8, 7, 6, 5, 3, 2, 1, 1, 0]
92 90 80 74 55 47
89 77 71 54 40 29
76 62 50 38 27 16
56 49 38 24  8  5
47 35 24  7  3  1
33 23  6  2  1  0

[90, 90, 89, 88, 83, 79, 78, 76, 73, 70, 70, 69, 68, 64, 63, 62, 61, 57, 56, 53, 52, 49, 49, 47, 39, 38, 37, 20, 19, 19, 17, 12, 9, 7, 4, 1]
Impossible

[99, 94, 94, 93, 93, 90, 87, 84, 82, 80, 76, 73, 71, 71, 66, 63, 62, 59, 53, 47, 40, 39, 37, 36, 30, 27, 21, 20, 18, 12, 9, 5, 4, 4, 0, 0]
Impossible

[99, 99, 97, 95, 94, 94, 89, 81, 78, 69, 65, 59, 57, 57, 55, 52, 51, 48, 46, 45, 41, 29, 28, 26, 20, 19, 17, 16, 15, 14, 12, 9, 8, 7, 3, 0]
Impossible

[82, 81, 75, 74, 73, 72, 72, 72, 69, 65, 65, 64, 58, 58, 57, 54, 49, 45, 44, 43, 39, 34, 31, 25, 23, 20, 20, 20, 19, 12, 11, 10, 10, 6, 0, 0]
Impossible

[97, 95, 91, 91, 86, 85, 81, 80, 79, 79, 76, 75, 74, 68, 68, 66, 66, 62, 62, 61, 58, 57, 46, 45, 38, 33, 31, 31, 28, 27, 20, 17, 14, 13, 7, 1]
97 95 91 81 76 66
91 86 80 75 66 57
85 79 74 62 46 31
79 68 62 45 31 20
68 61 38 28 17 13
58 33 27 14  7  1

[97, 97, 92, 79, 77, 77, 75, 73, 69, 67, 64, 64, 61, 58, 55, 55, 55, 51, 50, 48, 44, 43, 42, 40, 39, 37, 35, 31, 25, 24, 22, 22, 19, 13, 11, 10]
Impossible

[92, 91, 88, 88, 87, 85, 85, 84, 83, 80, 77, 73, 73, 71, 70, 68, 65, 52, 42, 37, 35, 32, 32, 29, 27, 26, 22, 20, 17, 14, 12, 11, 10, 9, 7, 3]
92 91 88 85 77 68
88 87 84 73 65 32
85 83 73 52 32 22
80 71 42 29 20 12
70 37 27 17 11  9
35 26 14 10  7  3

[98, 97, 96, 89, 87, 84, 81, 80, 80, 73, 64, 63, 63, 62, 59, 59, 55, 50, 49, 48, 45, 40, 36, 34, 31, 29, 28, 27, 24, 19, 14, 12, 11, 7, 2, 1]
98 97 89 81 64 59
96 87 80 63 55 40
84 80 63 50 36 28
73 62 49 34 27 14
59 48 31 24 12  7
45 29 19 11  2  1

[98, 97, 92, 82, 80, 80, 77, 76, 73, 72, 69, 67, 66, 65, 59, 57, 54, 49, 45, 41, 39, 34, 34, 30, 24, 23, 23, 19, 16, 15, 14, 13, 6, 6, 4, 3]
98 97 82 77 69 57
92 80 76 67 54 34
80 73 66 49 34 23
72 65 45 30 19 14
59 41 24 16 13  6
39 23 15  6  4  3

[98, 97, 93, 89, 89, 89, 86, 78, 78, 75, 63, 58, 58, 58, 55, 53, 51, 48, 46, 44, 42, 35, 30, 29, 28, 21, 21, 20, 17, 17, 15, 14, 8, 8, 6, 3]
98 97 89 86 63 53
93 89 78 58 51 35
89 78 58 48 30 21
75 58 46 29 20 15
55 44 28 17 14  8
42 21 17  8  6  3

[98, 93, 90, 86, 81, 79, 77, 77, 75, 67, 66, 59, 58, 52, 52, 49, 46, 45, 42, 41, 41, 41, 38, 37, 33, 31, 28, 14, 12, 11, 8, 7, 6, 3, 2, 2]
Impossible

[99, 96, 95, 93, 89, 86, 85, 82, 71, 62, 61, 59, 58, 58, 47, 45, 45, 44, 42, 40, 36, 35, 32, 31, 28, 28, 26, 20, 18, 18, 16, 11, 11, 8, 7, 3]
99 96 93 85 61 45
95 89 82 59 45 35
86 71 58 44 32 26
62 58 42 31 20 16
47 40 28 18 11  8
36 28 18 11  7  3

[99, 97, 97, 92, 88, 87, 85, 84, 77, 76, 76, 73, 73, 70, 62, 58, 56, 52, 51, 46, 44, 41, 38, 29, 27, 26, 23, 15, 15, 14, 10, 9, 7, 7, 6, 4]
99 97 92 85 76 58
97 88 84 73 56 41
87 77 73 52 38 23
76 70 51 29 15 10
62 46 27 15  9  7
44 26 14  7  6  4

[96, 93, 91, 87, 80, 80, 78, 76, 75, 74, 70, 70, 55, 54, 49, 43, 42, 40, 39, 34, 30, 24, 23, 19, 16, 11, 10, 10, 10, 9, 7, 7, 5, 3, 2, 0]
96 93 87 78 70 43
91 80 76 70 42 24
80 75 55 40 23 10
74 54 39 19 10  7
49 34 16 10  7  3
30 11  9  5  2  0

[99, 94, 93, 92, 89, 84, 81, 79, 69, 67, 67, 65, 60, 59, 58, 56, 54, 53, 53, 50, 48, 44, 43, 32, 31, 30, 26, 23, 19, 15, 10, 9, 8, 6, 5, 2]
99 94 92 81 67 56
93 89 79 65 54 44
84 69 60 53 43 26
67 59 53 32 23 10
58 50 31 19  9  6
48 30 15  8  5  2

[97, 97, 96, 95, 83, 83, 81, 69, 64, 60, 58, 56, 54, 52, 49, 48, 48, 48, 43, 43, 41, 37, 36, 36, 36, 35, 32, 28, 22, 18, 18, 8, 7, 5, 4, 0]
Impossible

[96, 91, 89, 88, 87, 87, 87, 86, 83, 80, 78, 78, 75, 69, 66, 65, 64, 61, 59, 57, 52, 51, 51, 50, 47, 45, 34, 32, 17, 12, 11, 8, 5, 5, 1, 0]
96 91 88 87 78 65
89 87 86 78 64 51
87 83 75 61 51 34
80 69 59 50 32 11
66 57 47 17  8  5
52 45 12  5  1  0

[99, 97, 93, 90, 89, 88, 86, 83, 78, 74, 74, 71, 67, 66, 66, 62, 59, 51, 48, 41, 39, 35, 33, 31, 28, 26, 25, 22, 19, 19, 18, 15, 13, 11, 10, 4]
99 97 90 86 74 62
93 89 83 71 59 35
88 78 67 51 33 25
74 66 48 31 22 18
66 41 28 19 15 11
39 26 19 13 10  4

[99, 93, 87, 86, 85, 79, 75, 75, 71, 68, 61, 59, 59, 59, 54, 53, 49, 36, 35, 33, 32, 31, 29, 27, 26, 25, 25, 21, 19, 18, 14, 13, 13, 12, 7, 6]
99 93 86 75 61 53
87 85 75 59 49 31
79 71 59 36 29 25
68 59 35 27 21 14
54 33 26 19 13 12
32 25 18 13  7  6

[94, 88, 85, 84, 81, 78, 76, 76, 75, 72, 70, 69, 68, 67, 65, 65, 61, 60, 58, 57, 54, 52, 49, 44, 41, 37, 34, 26, 25, 23, 22, 22, 19, 11, 10, 1]
94 88 84 76 70 65
85 81 76 69 61 52
78 75 68 60 49 34
72 67 58 44 26 22
65 57 41 25 22 11
54 37 23 19 10  1

[95, 93, 92, 84, 81, 76, 72, 71, 68, 66, 65, 61, 60, 59, 57, 54, 51, 47, 45, 41, 38, 37, 37, 35, 34, 34, 33, 32, 24, 20, 18, 17, 16, 15, 14, 6]
95 93 84 72 65 54
92 81 71 61 51 37
76 68 60 47 37 33
66 59 45 35 32 18
57 41 34 24 17 15
38 34 20 16 14  6

[98, 98, 92, 92, 86, 83, 83, 80, 77, 77, 75, 73, 69, 67, 66, 64, 64, 54, 52, 50, 50, 43, 40, 40, 36, 28, 25, 25, 18, 17, 13, 5, 5, 4, 2, 0]
Impossible

[99, 99, 97, 96, 95, 91, 90, 90, 84, 81, 72, 71, 68, 67, 61, 57, 56, 56, 55, 51, 45, 44, 42, 38, 37, 37, 31, 26, 25, 23, 21, 21, 13, 12, 8, 2]
Impossible

[99, 94, 93, 90, 86, 84, 83, 82, 81, 79, 78, 74, 67, 65, 63, 59, 58, 55, 52, 52, 50, 48, 47, 43, 32, 28, 24, 23, 22, 19, 18, 16, 15, 12, 8, 7]
99 94 90 83 78 59
93 86 82 74 58 48
84 81 67 55 47 24
79 65 52 43 23 18
63 52 32 22 16 12
50 28 19 15  8  7

[99, 95, 95, 86, 85, 81, 80, 78, 76, 74, 72, 70, 66, 59, 55, 54, 54, 53, 49, 48, 47, 45, 44, 39, 37, 37, 35, 32, 26, 24, 15, 14, 8, 7, 6, 2]
99 95 86 80 72 54
95 85 78 70 54 45
81 76 66 53 44 35
74 59 49 39 32 15
55 48 37 26 14  7
47 37 24  8  6  2

[98, 98, 96, 88, 85, 85, 78, 71, 71, 68, 61, 59, 59, 56, 54, 53, 52, 48, 45, 44, 42, 42, 40, 39, 38, 32, 31, 25, 25, 24, 19, 17, 15, 12, 6, 3]
Impossible

[96, 95, 94, 87, 77, 75, 72, 70, 69, 68, 68, 64, 63, 62, 57, 56, 53, 50, 48, 47, 44, 43, 42, 42, 39, 31, 28, 28, 23, 19, 13, 10, 10, 7, 5, 1]
96 95 87 72 68 56
94 77 70 64 53 43
75 69 63 50 42 28
68 62 48 42 28 13
57 47 39 23 10  7
44 31 19 10  5  1

[99, 99, 98, 92, 92, 90, 90, 88, 85, 78, 78, 77, 73, 73, 65, 64, 59, 57, 53, 51, 45, 44, 41, 41, 40, 39, 33, 32, 32, 32, 30, 27, 25, 15, 13, 12]
Impossible

[97, 97, 96, 93, 92, 85, 84, 84, 82, 80, 80, 77, 74, 73, 70, 67, 58, 56, 54, 42, 40, 40, 36, 34, 31, 29, 27, 27, 26, 25, 25, 22, 16, 16, 1, 0]
Impossible

[95, 95, 92, 91, 84, 81, 77, 71, 70, 69, 69, 68, 65, 65, 65, 62, 61, 58, 53, 50, 47, 46, 44, 39, 39, 38, 33, 28, 27, 21, 15, 13, 9, 4, 1, 0]
Impossible

[94, 93, 84, 81, 80, 70, 69, 68, 68, 66, 66, 65, 62, 62, 53, 53, 50, 41, 40, 37, 36, 35, 33, 32, 32, 22, 22, 20, 14, 14, 8, 7, 0, 0, 0, 0]
Impossible

[98, 97, 94, 93, 86, 80, 78, 75, 73, 68, 63, 61, 57, 52, 48, 45, 41, 38, 37, 32, 27, 27, 25, 24, 23, 22, 20, 18, 14, 13, 11, 10, 7, 7, 6, 2]
98 97 93 78 63 45
94 86 75 61 41 27
80 73 57 38 25 20
68 52 37 24 18 11
48 32 23 14 10  7
27 22 13  7  6  2

[96, 88, 88, 80, 80, 79, 76, 73, 68, 67, 66, 63, 56, 50, 49, 49, 41, 39, 33, 30, 28, 28, 25, 24, 22, 20, 18, 18, 17, 14, 11, 6, 6, 4, 3, 0]
96 88 80 76 66 49
88 80 73 63 41 28
79 68 56 39 25 18
67 50 33 24 18 11
49 30 22 17  6  4
28 20 14  6  3  0

[99, 98, 90, 88, 86, 85, 84, 80, 79, 74, 68, 67, 61, 51, 46, 45, 44, 44, 43, 40, 39, 38, 27, 25, 25, 15, 13, 13, 13, 9, 9, 7, 3, 2, 2, 2]
Impossible

[99, 96, 92, 88, 86, 75, 73, 69, 69, 68, 66, 61, 53, 53, 48, 46, 44, 40, 37, 32, 31, 29, 24, 22, 22, 17, 14, 13, 13, 11, 11, 11, 10, 3, 1, 0]
99 96 88 73 66 46
92 86 69 61 44 29
75 69 53 40 24 14
68 53 37 22 13 11
48 32 22 13 11  3
31 17 11 10  1  0

[98, 97, 92, 91, 90, 86, 78, 77, 76, 76, 72, 70, 65, 65, 58, 56, 55, 55, 55, 54, 46, 42, 38, 38, 37, 34, 27, 24, 19, 18, 15, 11, 5, 3, 3, 0]
98 97 91 78 72 56
92 90 77 70 55 42
86 76 65 55 38 27
76 65 55 38 24 15
58 54 37 19 11  3
46 34 18  5  3  0

[98, 97, 96, 89, 82, 80, 79, 74, 72, 60, 59, 55, 52, 52, 51, 48, 44, 43, 42, 40, 39, 38, 35, 34, 33, 33, 33, 30, 28, 27, 23, 21, 13, 9, 8, 8]
Impossible

[97, 96, 95, 91, 88, 79, 75, 74, 74, 71, 67, 67, 63, 62, 58, 40, 39, 39, 38, 38, 37, 33, 29, 29, 27, 24, 20, 17, 14, 13, 5, 4, 4, 2, 2, 1]
97 96 91 75 67 40
95 88 74 67 39 33
79 74 63 39 29 20
71 62 38 29 17  5
58 38 27 14  4  2
37 24 13  4  2  1

[94, 89, 89, 86, 85, 78, 72, 72, 70, 66, 58, 58, 56, 55, 54, 53, 51, 51, 50, 49, 44, 38, 37, 28, 27, 27, 24, 19, 15, 14, 12, 12, 8, 6, 5, 5]
Impossible

[96, 92, 90, 83, 83, 83, 82, 77, 75, 72, 63, 63, 62, 60, 57, 55, 54, 54, 53, 50, 50, 39, 36, 34, 33, 29, 23, 22, 19, 18, 17, 14, 11, 9, 6, 1]
96 92 83 82 63 55
90 83 77 63 54 39
83 75 62 54 36 23
72 60 53 34 22 17
57 50 33 19 14  9
50 29 18 11  6  1

[99, 96, 95, 93, 92, 90, 89, 87, 82, 81, 80, 78, 78, 77, 74, 71, 70, 60, 55, 49, 44, 39, 38, 37, 36, 26, 25, 23, 21, 19, 18, 13, 11, 10, 3, 1]
99 96 93 89 80 71
95 92 87 78 70 39
90 82 78 60 38 25
81 77 55 37 23 18
74 49 36 21 13 10
44 26 19 11  3  1

[97, 93, 89, 87, 87, 83, 82, 82, 81, 76, 75, 73, 71, 70, 70, 69, 68, 68, 67, 63, 63, 53, 51, 49, 45, 40, 38, 37, 32, 21, 18, 14, 13, 11, 10, 7]
97 93 87 82 75 69
89 87 82 73 68 53
83 81 71 68 51 38
76 70 67 49 37 18
70 63 45 32 14 11
63 40 21 13 10  7

[94, 91, 91, 87, 84, 80, 80, 80, 78, 74, 72, 68, 64, 62, 61, 58, 55, 52, 51, 50, 49, 39, 36, 35, 35, 28, 27, 26, 26, 25, 19, 15, 15, 11, 10, 4]
94 91 87 80 72 58
91 84 80 68 55 39
80 78 64 52 36 27
74 62 51 35 26 19
61 50 35 26 15 11
49 28 25 15 10  4

[90, 76, 72, 67, 66, 65, 63, 63, 61, 61, 61, 54, 53, 49, 42, 42, 40, 38, 36, 34, 31, 28, 25, 24, 23, 21, 20, 17, 16, 10, 9, 8, 7, 6, 5, 0]
90 76 67 63 61 42
72 66 63 54 40 28
65 61 53 38 25 20
61 49 36 24 17  9
42 34 23 16  8  6
31 21 10  7  5  0

[98, 98, 98, 96, 95, 89, 88, 87, 86, 85, 83, 76, 73, 73, 67, 66, 64, 64, 64, 63, 61, 61, 59, 56, 55, 52, 49, 34, 29, 26, 26, 16, 9, 6, 4, 0]
Impossible

[98, 98, 95, 95, 93, 89, 87, 80, 77, 77, 70, 66, 65, 60, 59, 49, 46, 38, 34, 31, 22, 18, 15, 10, 10, 9, 8, 8, 7, 7, 7, 2, 2, 2, 1, 1]
Impossible

[92, 92, 86, 85, 84, 83, 81, 81, 79, 78, 77, 72, 68, 63, 63, 58, 56, 47, 41, 40, 40, 35, 34, 30, 28, 20, 20, 20, 20, 19, 19, 18, 12, 7, 4, 3]
Impossible

[99, 99, 86, 79, 79, 78, 76, 74, 68, 67, 65, 64, 60, 60, 57, 55, 54, 49, 46, 37, 32, 32, 31, 30, 29, 28, 28, 27, 26, 22, 20, 20, 18, 16, 10, 3]
Impossible

[99, 94, 91, 90, 87, 84, 83, 83, 78, 75, 73, 68, 66, 62, 52, 52, 50, 47, 41, 40, 38, 36, 33, 33, 33, 32, 32, 30, 23, 22, 22, 19, 17, 16, 10, 10]
Impossible

[95, 93, 92, 91, 87, 86, 82, 82, 76, 75, 73, 72, 71, 64, 62, 60, 56, 55, 55, 53, 50, 48, 43, 42, 41, 40, 38, 36, 26, 22, 20, 17, 16, 14, 14, 3]
95 93 91 82 73 60
92 87 82 72 56 48
86 76 71 55 43 38
75 64 55 42 36 20
62 53 41 26 17 14
50 40 22 16 14  3

[97, 91, 91, 90, 88, 84, 80, 73, 71, 71, 70, 69, 68, 67, 64, 60, 55, 53, 53, 44, 42, 41, 41, 39, 39, 37, 29, 23, 19, 18, 15, 13, 10, 10, 8, 5]
97 91 90 80 70 60
91 88 73 69 55 41
84 71 68 53 41 29
71 67 53 39 23 15
64 44 39 19 13 10
42 37 18 10  8  5

[99, 97, 94, 93, 93, 92, 89, 88, 84, 76, 70, 70, 70, 69, 63, 60, 54, 51, 51, 43, 43, 39, 36, 35, 30, 27, 24, 21, 19, 19, 12, 8, 6, 1, 0, 0]
Impossible

[96, 95, 92, 91, 88, 83, 82, 78, 77, 76, 72, 70, 61, 55, 54, 43, 41, 38, 36, 34, 30, 27, 25, 24, 22, 22, 22, 20, 18, 15, 14, 12, 10, 9, 2, 0]
96 95 91 82 72 43
92 88 78 70 41 27
83 77 61 38 25 22
76 55 36 24 20 14
54 34 22 18 12  9
30 22 15 10  2  0

[98, 93, 90, 88, 84, 84, 83, 81, 76, 75, 72, 72, 68, 63, 58, 57, 55, 50, 44, 42, 39, 36, 36, 30, 26, 26, 24, 24, 20, 9, 6, 6, 3, 1, 1, 0]
98 93 88 83 72 57
90 84 81 72 55 36
84 76 68 50 36 24
75 63 44 30 24  6
58 42 26 20  6  1
39 26  9  3  1  0

[86, 85, 81, 74, 74, 65, 63, 61, 58, 53, 53, 42, 41, 41, 40, 40, 39, 39, 38, 37, 36, 36, 34, 32, 31, 27, 25, 23, 22, 20, 19, 18, 9, 8, 6, 0]
86 85 74 63 53 40
81 74 61 42 39 36
65 58 41 39 34 25
53 41 38 32 23 19
40 37 31 22 18  8
36 27 20  9  6  0

[87, 84, 82, 82, 79, 77, 75, 75, 74, 74, 70, 68, 62, 62, 59, 58, 54, 53, 53, 49, 49, 46, 35, 34, 34, 34, 33, 29, 24, 21, 10, 10, 9, 8, 4, 1]
87 84 82 75 70 58
82 79 75 68 54 46
77 74 62 53 35 33
74 62 53 34 29 10
59 49 34 24 10  8
49 34 21  9  4  1

[98, 95, 92, 89, 86, 83, 80, 80, 75, 72, 70, 69, 68, 66, 66, 53, 53, 52, 49, 45, 43, 41, 40, 39, 38, 36, 33, 28, 22, 13, 13, 12, 12, 7, 5, 3]
98 95 89 80 70 53
92 86 80 69 53 41
83 75 68 52 40 33
72 66 49 39 28 13
66 45 38 22 12  7
43 36 13 12  5  3

[98, 98, 95, 91, 89, 88, 87, 86, 83, 81, 79, 73, 69, 68, 57, 55, 50, 47, 41, 40, 35, 32, 31, 30, 24, 13, 11, 10, 10, 8, 3, 3, 2, 1, 0, 0]
Impossible

[98, 98, 93, 91, 88, 86, 85, 80, 65, 65, 65, 65, 64, 62, 53, 51, 51, 48, 45, 41, 41, 36, 34, 34, 33, 28, 24, 19, 17, 17, 16, 15, 9, 8, 5, 0]
Impossible

[99, 82, 82, 80, 79, 74, 73, 72, 65, 64, 62, 59, 59, 59, 58, 55, 49, 40, 36, 36, 32, 31, 30, 27, 26, 26, 23, 21, 19, 18, 16, 16, 11, 8, 2, 1]
99 82 80 73 62 55
82 79 72 59 49 31
74 65 59 40 30 23
64 59 36 27 21 16
58 36 26 19 16  8
32 26 18 11  2  1

[98, 95, 93, 91, 90, 86, 85, 85, 84, 84, 81, 80, 75, 67, 66, 65, 65, 59, 57, 49, 45, 42, 27, 26, 24, 21, 20, 20, 17, 15, 13, 13, 10, 9, 4, 0]
98 95 91 85 81 65
93 90 85 80 65 42
86 84 75 59 27 20
84 67 57 26 20 13
66 49 24 17 13  9
45 21 15 10  4  0

[99, 98, 92, 91, 90, 81, 77, 74, 70, 69, 66, 65, 62, 62, 59, 58, 57, 56, 55, 55, 53, 50, 46, 46, 42, 32, 29, 25, 21, 17, 16, 15, 11, 10, 9, 0]
99 98 91 77 66 58
92 90 74 65 57 50
81 70 62 56 46 29
69 62 55 46 25 16
59 55 42 21 15 10
53 32 17 11  9  0

[93, 89, 89, 89, 88, 88, 87, 87, 87, 76, 74, 74, 73, 65, 51, 50, 49, 47, 44, 34, 31, 30, 29, 27, 26, 24, 20, 17, 14, 14, 11, 11, 11, 9, 6, 3]
Impossible

[98, 97, 95, 92, 88, 86, 83, 76, 75, 72, 69, 68, 64, 58, 57, 52, 43, 43, 41, 33, 32, 27, 26, 23, 23, 22, 22, 18, 18, 16, 13, 8, 8, 4, 2, 2]
Impossible

[99, 95, 89, 88, 85, 83, 80, 79, 78, 78, 74, 71, 65, 63, 62, 58, 57, 56, 51, 47, 45, 42, 39, 31, 31, 31, 29, 26, 25, 24, 21, 21, 20, 13, 9, 5]
99 95 88 80 74 58
89 85 79 71 57 42
83 78 65 56 39 29
78 63 51 31 26 21
62 47 31 25 21 13
45 31 24 20  9  5

[99, 93, 91, 90, 88, 88, 88, 87, 85, 83, 75, 68, 67, 67, 66, 65, 61, 51, 48, 46, 44, 41, 39, 35, 35, 30, 28, 23, 22, 20, 20, 19, 14, 4, 3, 3]
Impossible

[99, 88, 80, 79, 74, 72, 71, 70, 65, 65, 64, 63, 63, 60, 54, 46, 42, 42, 39, 38, 36, 35, 32, 30, 29, 27, 25, 24, 21, 17, 16, 16, 10, 7, 7, 2]
99 88 79 71 64 46
80 74 70 63 42 35
72 65 63 42 32 25
65 60 39 30 24 16
54 38 29 21 16  7
36 27 17 10  7  2

[95, 93, 80, 75, 66, 64, 59, 58, 49, 44, 44, 37, 37, 36, 35, 34, 33, 33, 32, 31, 28, 25, 23, 23, 22, 21, 20, 18, 15, 13, 11, 10, 6, 4, 3, 0]
95 93 75 59 44 34
80 66 58 37 33 25
64 49 37 33 23 20
44 36 32 23 18 11
35 31 22 15 10  4
28 21 13  6  3  0

[99, 99, 99, 86, 83, 83, 83, 67, 67, 65, 64, 62, 54, 54, 53, 45, 41, 41, 39, 38, 34, 30, 29, 29, 28, 26, 25, 24, 24, 18, 15, 8, 8, 7, 6, 5]
Impossible

[92, 86, 85, 85, 80, 79, 69, 68, 67, 62, 62, 61, 60, 59, 59, 56, 53, 47, 43, 43, 36, 33, 30, 26, 25, 24, 22, 21, 20, 18, 14, 9, 9, 5, 4, 1]
92 86 85 69 62 56
85 80 68 61 53 33
79 67 60 47 30 22
62 59 43 26 21 14
59 43 25 20  9  5
36 24 18  9  4  1

[95, 94, 93, 91, 90, 87, 87, 86, 86, 82, 80, 80, 78, 77, 69, 69, 69, 64, 64, 60, 57, 52, 46, 37, 36, 29, 27, 27, 25, 23, 23, 19, 18, 17, 17, 8]
95 94 91 87 80 69
93 90 86 80 69 52
87 86 78 64 46 27
82 77 64 37 27 23
69 60 36 25 19 17
57 29 23 18 17  8

[94, 93, 93, 90, 87, 85, 85, 83, 83, 77, 68, 63, 59, 58, 56, 54, 53, 52, 49, 48, 44, 41, 37, 36, 32, 30, 28, 25, 19, 15, 13, 5, 4, 4, 1, 1]
Impossible

[98, 89, 88, 83, 83, 82, 82, 82, 81, 75, 72, 72, 72, 69, 61, 61, 60, 60, 59, 54, 51, 46, 41, 37, 35, 35, 33, 33, 27, 23, 21, 20, 17, 6, 4, 1]
98 89 83 82 72 61
88 83 82 72 60 46
82 81 72 60 41 33
75 69 59 37 33 21
61 54 35 27 20  6
51 35 23 17  4  1

[97, 95, 93, 84, 83, 81, 81, 81, 78, 75, 75, 72, 71, 66, 63, 58, 58, 56, 49, 47, 45, 41, 39, 37, 36, 22, 20, 16, 13, 10, 9, 8, 7, 5, 3, 2]
97 95 84 81 75 58
93 83 81 72 58 41
81 78 71 56 39 20
75 66 49 37 16  9
63 47 36 13  8  5
45 22 10  7  3  2

[98, 94, 92, 92, 85, 85, 83, 82, 79, 75, 75, 74, 70, 69, 67, 62, 61, 57, 54, 53, 44, 38, 33, 33, 31, 31, 28, 28, 25, 12, 10, 10, 8, 8, 5, 2]
98 94 92 83 75 62
92 85 82 74 61 38
85 79 70 57 33 28
75 69 54 33 28 10
67 53 31 25 10  8
44 31 12  8  5  2

[88, 80, 79, 78, 76, 74, 73, 70, 69, 66, 61, 60, 54, 52, 51, 45, 41, 40, 34, 34, 33, 31, 30, 28, 26, 24, 22, 22, 19, 14, 13, 9, 6, 2, 2, 2]
Impossible

[99, 98, 97, 96, 95, 92, 82, 81, 75, 73, 71, 68, 63, 62, 59, 58, 55, 54, 50, 49, 45, 45, 41, 41, 41, 33, 24, 23, 16, 14, 11, 9, 3, 2, 1, 1]
Impossible

[95, 95, 94, 92, 88, 88, 84, 83, 82, 76, 76, 76, 75, 73, 71, 71, 68, 65, 64, 63, 61, 61, 61, 60, 56, 54, 52, 49, 39, 27, 18, 15, 14, 11, 5, 0]
Impossible

Total: 100, Succeeded: 55, Failures: 45
79815969
Vote

Code

def arrange(nums):
    nums.sort(reverse=True)
    grid = [[-1] * 6 for i in range(6)]
    x, y = 0, 0
    for n in nums:
        grid[y][x] = n
        # Check if same number is already in row or column. (We only need to look at adjacent cells due to traversal method.)
        if (x > 0 and grid[y][x - 1] == n) or (y > 0 and grid[y - 1][x] == n):
            return None
        
        # Traverse grid in diagonals going from top to left side or right to bottom side.
        if y == 5:
            x, y = 5, x + 1
        elif x == 0:
            x, y = y + 1, 0
        else:
            x, y = x - 1, y + 1
    
    return grid


total, impossible = 0, 0
for line in open("RandomNumbers.txt").read().splitlines():
    nums = [int(e) for e in line[1:-1].split(", ")]
    total += 1
    grid = arrange(nums)
    if grid is None:
        impossible += 1
        print("impossible")
    else:
        # Print the arranged grid.
        print("\n".join(" ".join(f"{n:2}" for n in row) for row in grid))
    
    print()

print(f"{impossible} / {total} impossible")

Output

...

45 / 100 impossible

Explanation

Clearly, this problem is only rendered non-trivial by the disqualification of "ties"; i.e., rows and columns must be strictly decreasing sequences.

The key insight to the above approach is that any upper-left triangle of the grid comprising n cells must contain precisely the n largest numbers (in some order), since all the remaining cells lie to the right and below the cells of the triangle, and must therefore be smaller. Thus, an algorithm that takes the numbers in descending order, starts in the top-left corner, and fills the grid in diagonals going from the top to the left side, and then from the right to the bottom side, should guarantee success whenever possible. The diagonal path (always starting from either the top or the right edge) ensures that repeated numbers always occupy different rows and columns, unless such a subsequence of repeated numbers continues onto the next diagonal sufficiently far that it is forced to occupy a row or column already occupied by that same number (on the previous diagonal).

Note that most of the impossibilities result from repetitions near the start or end of the ordered sequence, since diagonals are shorter towards the top-left and bottom-right corners of the grid (length 1 at the corners), and longest towards the middle (length 6 from the top-right to bottom-left corner). Thus, an subsequence of repeated numbers of length merely two, if right at the start or end of the ordered sequence, inevitably results in an impossibility. Contrastingly, such a subsequence of length 6 may be accommodated if situated in the middle of the ordered sequence.

79815667
Vote
"""
Reflexion :
The main difficulty is to sort into a grid respecting the rules. For that, I consider 
placing the max values into the top-left corner, as possbile, that's why I create an index 
mask dedicated for this problem, it helps me to place correctly the values of the list 
respecting this conditions. A checking is done after placement to verify if the rules are 
respected. 

Code description :
I start with a parsing of the file, where I create one list of values for each line of the 
file, according to the content. I continue with an analysis of these list of values, that 
I sort descendingly and where I place all values according to the given mask. I conclude 
with a check of validity according to the rules, and I return the validity and the result 
of the grid.

Enhancement:
The mask could be generated automatically according to the grid size, but I write it for a 
specific 6x6 grid. We could also create a dynamic code that adapt to any size of grid by 
reading the size of the input data and compute the square root the get the size of the 
grid.

Other:
I also use numpy to limit the syntax for the checking and the shape of the grid. I tried 
to produce an optimized version of the code to reduce the number of line. The code runs at 
least with an old Python 3.6.

"""

import numpy as np

def checkData(data):
    # ----
    # sort data
    values = data.copy()
    values.sort(reverse=True)

    # ----
    # create mask (6*6)
    mask = [
        0, 1, 3, 6, 10, 15, 
        2, 4, 7, 11, 16, 21, 
        5, 8, 12, 17, 22, 26,
        9, 13, 18, 23, 27, 30,
        14, 19, 24, 28, 31, 33,
        20, 25, 29, 32, 34, 35
    ]

    # fill sorted grid
    grid = [values[index] for index in mask]

    # ----
    # reshape grid (for response)
    grid = np.reshape(grid, (6,6))
    is_valid = lambda a: np.all(a[:-1] > a[1:])
    valid = True

    # check if row is descendingly sorted
    for i in range(6):
        row = grid[i]
        valid &= is_valid(row)
        
    # check if column is descendingly sorted
    for i in range(6):
        col = grid[:,i]
        valid &= is_valid(col)
        
    return valid, grid
        
if __name__ == "__main__":
    filepath = "RandomNumbers.txt"

    # parse file (create a dataset)
    dataset = []
    with open(filepath) as file:
        lines = file.read().splitlines()
        for line in lines:
            line = line.strip("[]")
            dataset.append([int(x.strip()) for x in line.split(",") if x.strip()])

    # check all data from dataset
    impossible_count = 0
    for data in dataset:
    
        # check
        print("--------------------")
        print("Dataset:", data)
        valid, grid = checkData(data)
        
        # not valid
        if not valid:
            print("Impossible")
            impossible_count += 1
            
        # valid (display a possible response)
        else:
            print("Valid response:")
            print(grid)
            
    print("--------------------")
    print("Count of impossible cases:", impossible_count)
        

Count of impossible cases: 45

79815376
Vote
def sort_grid(numbers):
    # If duplicates exist, sorting is impossible (ties not allowed)
    if len(numbers) != len(set(numbers)):
        return None  # impossible

    # Sort descending
    numbers.sort(reverse=True)
    grid = [numbers[i*6:(i+1)*6] for i in range(6)]

    # Verify descending order in rows & columns
    for i in range(6):
        if any(grid[i][j] <= grid[i][j+1] for j in range(5)):  # row check
            return None
    for j in range(6):
        if any(grid[i][j] <= grid[i+1][j] for i in range(5)):  # column check
            return None

    return grid


def process_all(datasets):
    impossible = 0
    results = []
    for data in datasets:
        grid = sort_grid(data[:])
        if grid is None:
            impossible += 1
            results.append("impossible")
        else:
            results.append(grid)
    return results, impossible

Sort all 36 numbers in strict descending order, then fill the 6×6 grid row by row. If any duplicates exist (since ties are not allowed), that dataset is impossible to arrange.

79815421
Vote

how many impossible sets do you get? Also, purely checking for duplicates in the number array does not mean sorting is impossible - see the example in the question for a 3x3 grid: [95, 75, 75, 74, 74, 74, 54, 45, 40]

[[95, 75, 74], 
 [75, 74, 54],
 [74, 45, 40]]
79814906
Vote

Description

I used this challenge to learn a bit of Python ;-) and enjoyed it :-).

What seemed obvious to me was that the highest number must be put into top left position of the result matrix.

Than I took piece and paper and tried the approach to first fill the top row one by one. If putting it there broke the rules I put into the first column from top to down. This was my first implementation then.

With seventy something failing cases I took a nearer look at the results. Main problem was how to handle the duplicates. To avoid breaking the rules they must be put on a diagonal if possible, I decided.

So changed the code to distribute the number in diagonals from left to top and bottom to right. If a number breaks a rule the case looks impossible to me. Looking at the results I had no idea how to distribute more numbers in a correct manner.

So last thing I changed was to just directly distribute the numbers into the matrix in diagonals instead of finding an empty place.

Now my code declares 45 of 100 cases to be impossible. Hope this is correct. If not I'm happy to learn. But it was fun anyway. Thank you.

P.S.: Code also contains some commented out print statements that can be used to gain more information.

Code in Python (file with numbers must be in same directory)

import numpy as np
import math

nonum = -1

def printOnOneLine(title, matrix):
    matrixAsString = np.array2string(matrix, separator = ", ").replace("  ", " ").replace("\n", "")
    print(title, matrixAsString)

def fitsInRow(matrix, row, col, num):
    if col == 0:
        return True
    return matrix[row, col - 1] > num

def fitsInCol(matrix, row, col, num):
    if row == 0:
        return True
    return matrix[row - 1, col] > num

def putNumbersIntoMatrix(matrix, dim, numbers):
    numberIndex = 0
    for borderCellNumber in range(0, 2 * dim - 1): # 0: top left, dim-1: top right, 2*dim-2: bottom right
        diagonalStartRow = 0 if borderCellNumber < dim else borderCellNumber - dim + 1
        diagonalStartCol = borderCellNumber if borderCellNumber < dim else dim - 1
        positionsEnd = borderCellNumber + 1 if borderCellNumber < dim else 2 * dim - borderCellNumber - 1
        for position in range(0, positionsEnd): # go through positions in diagonal
            row = diagonalStartRow + position
            col = diagonalStartCol - position
            num = numbers[numberIndex]
            if not fitsInRow(matrix, row, col, num) or not fitsInCol(matrix, row, col, num):
                print("IMPOSSIBLE   : Failed to distribute %d at descending position %d" % (num, numberIndex + 1))
                return False
            matrix[row, col] = num
            numberIndex += 1
    return True

def transform(numbers, case):
    print(60 * "-")
    print("Case         :", case)
    # print("Unsorted     :", numbers) # show unsorted list of numbers as read from file
    numbers = np.sort(numbers)
    numbers = np.flip(numbers)
    # printOnOneLine("Descending   :", numbers) # show descendingly orderd list of numbers
    size = np.size(numbers)
    dim = math.isqrt(size)
    if size != dim ** 2:
        print("INVALID INPUT: You cannot create a perfect square matrix out of %d integers" % size)
        return False
    matrix = np.full((dim, dim), nonum, dtype=int)
    if not putNumbersIntoMatrix(matrix, dim, numbers):
        # print(matrix) # show pretty print matrix with numbers distributed till failure
        return False
    printOnOneLine("Result Matrix:", matrix)
    # print(matrix) # show pretty print matrix with successfully distributed numbers
    return True


with open('RandomNumbers.txt') as serializedArraysFile:
    serializedArrays = serializedArraysFile.readlines()

caseCounter = 0
impossibleCounter = 0
for serializedArray in serializedArrays:
    caseCounter = caseCounter + 1
    numbers = eval(serializedArray)
    if not transform(numbers, caseCounter):
        impossibleCounter = impossibleCounter + 1

print(60 * "=")
print("%d of %d cases are impossible" % (impossibleCounter, caseCounter))

Output

------------------------------------------------------------
Case         : 1
IMPOSSIBLE   : Failed to distribute 3 at descending position 36
------------------------------------------------------------
Case         : 2
IMPOSSIBLE   : Failed to distribute 98 at descending position 2
------------------------------------------------------------
Case         : 3
Result Matrix: [[99, 95, 91, 81, 73, 61], [91, 84, 80, 71, 60, 42], [82, 75, 68, 59, 42, 18], [73, 65, 55, 41, 16, 14], [63, 53, 34, 16, 13, 6], [44, 24, 14, 7, 6, 0]]
------------------------------------------------------------
Case         : 4
Result Matrix: [[99, 94, 86, 74, 63, 56], [88, 83, 73, 62, 52, 36], [81, 71, 61, 50, 35, 24], [70, 59, 48, 29, 20, 10], [57, 40, 27, 19, 9, 6], [40, 27, 13, 8, 3, 1]]
------------------------------------------------------------
Case         : 5
Result Matrix: [[99, 97, 89, 85, 78, 65], [96, 88, 81, 78, 60, 46], [85, 80, 76, 52, 45, 35], [78, 75, 52, 43, 32, 27], [71, 48, 41, 31, 26, 21], [48, 37, 31, 22, 14, 5]]
------------------------------------------------------------
Case         : 6
IMPOSSIBLE   : Failed to distribute 98 at descending position 2
------------------------------------------------------------
Case         : 7
IMPOSSIBLE   : Failed to distribute 0 at descending position 36
------------------------------------------------------------
Case         : 8
IMPOSSIBLE   : Failed to distribute 1 at descending position 36
------------------------------------------------------------
Case         : 9
Result Matrix: [[98, 94, 83, 79, 67, 59], [89, 80, 78, 66, 58, 44], [80, 72, 65, 57, 42, 30], [71, 64, 56, 39, 29, 18], [60, 55, 37, 23, 16, 9], [48, 31, 22, 10, 9, 4]]
------------------------------------------------------------
Case         : 10
Result Matrix: [[99, 97, 88, 81, 71, 63], [88, 86, 81, 68, 63, 51], [82, 79, 66, 58, 50, 38], [79, 64, 56, 48, 35, 11], [64, 54, 42, 15, 9, 3], [52, 41, 11, 5, 2, 0]]
------------------------------------------------------------
Case         : 11
IMPOSSIBLE   : Failed to distribute 98 at descending position 2
------------------------------------------------------------
Case         : 12
IMPOSSIBLE   : Failed to distribute 1 at descending position 36
------------------------------------------------------------
Case         : 13
IMPOSSIBLE   : Failed to distribute 94 at descending position 4
------------------------------------------------------------
Case         : 14
Result Matrix: [[98, 96, 91, 82, 68, 56], [93, 90, 74, 66, 55, 32], [82, 73, 66, 54, 31, 19], [70, 65, 49, 28, 16, 12], [58, 41, 21, 16, 12, 10], [38, 19, 14, 10, 4, 3]]
------------------------------------------------------------
Case         : 15
Result Matrix: [[94, 85, 81, 77, 71, 61], [84, 79, 74, 69, 57, 47], [79, 73, 69, 57, 46, 32], [71, 66, 57, 46, 31, 24], [65, 56, 39, 31, 14, 12], [56, 35, 26, 13, 1, 0]]
------------------------------------------------------------
Case         : 16
IMPOSSIBLE   : Failed to distribute 88 at descending position 5
------------------------------------------------------------
Case         : 17
IMPOSSIBLE   : Failed to distribute 96 at descending position 2
------------------------------------------------------------
Case         : 18
Result Matrix: [[97, 95, 92, 76, 59, 47], [95, 91, 67, 58, 46, 39], [90, 64, 49, 44, 39, 23], [62, 49, 42, 38, 22, 16], [48, 41, 29, 16, 14, 10], [40, 25, 16, 13, 10, 0]]
------------------------------------------------------------
Case         : 19
IMPOSSIBLE   : Failed to distribute 99 at descending position 2
------------------------------------------------------------
Case         : 20
Result Matrix: [[99, 97, 92, 86, 77, 63], [96, 87, 82, 74, 63, 34], [87, 80, 73, 59, 34, 25], [77, 73, 51, 31, 25, 19], [71, 44, 28, 24, 15, 14], [40, 25, 23, 15, 13, 12]]
------------------------------------------------------------
Case         : 21
IMPOSSIBLE   : Failed to distribute 3 at descending position 36
------------------------------------------------------------
Case         : 22
Result Matrix: [[92, 90, 80, 74, 55, 47], [89, 77, 71, 54, 40, 29], [76, 62, 50, 38, 27, 16], [56, 49, 38, 24, 8, 5], [47, 35, 24, 7, 3, 1], [33, 23, 6, 2, 1, 0]]
------------------------------------------------------------
Case         : 23
IMPOSSIBLE   : Failed to distribute 90 at descending position 2
------------------------------------------------------------
Case         : 24
IMPOSSIBLE   : Failed to distribute 0 at descending position 36
------------------------------------------------------------
Case         : 25
IMPOSSIBLE   : Failed to distribute 99 at descending position 2
------------------------------------------------------------
Case         : 26
IMPOSSIBLE   : Failed to distribute 0 at descending position 36
------------------------------------------------------------
Case         : 27
Result Matrix: [[97, 95, 91, 81, 76, 66], [91, 86, 80, 75, 66, 57], [85, 79, 74, 62, 46, 31], [79, 68, 62, 45, 31, 20], [68, 61, 38, 28, 17, 13], [58, 33, 27, 14, 7, 1]]
------------------------------------------------------------
Case         : 28
IMPOSSIBLE   : Failed to distribute 97 at descending position 2
------------------------------------------------------------
Case         : 29
Result Matrix: [[92, 91, 88, 85, 77, 68], [88, 87, 84, 73, 65, 32], [85, 83, 73, 52, 32, 22], [80, 71, 42, 29, 20, 12], [70, 37, 27, 17, 11, 9], [35, 26, 14, 10, 7, 3]]
------------------------------------------------------------
Case         : 30
Result Matrix: [[98, 97, 89, 81, 64, 59], [96, 87, 80, 63, 55, 40], [84, 80, 63, 50, 36, 28], [73, 62, 49, 34, 27, 14], [59, 48, 31, 24, 12, 7], [45, 29, 19, 11, 2, 1]]
------------------------------------------------------------
Case         : 31
Result Matrix: [[98, 97, 82, 77, 69, 57], [92, 80, 76, 67, 54, 34], [80, 73, 66, 49, 34, 23], [72, 65, 45, 30, 19, 14], [59, 41, 24, 16, 13, 6], [39, 23, 15, 6, 4, 3]]
------------------------------------------------------------
Case         : 32
Result Matrix: [[98, 97, 89, 86, 63, 53], [93, 89, 78, 58, 51, 35], [89, 78, 58, 48, 30, 21], [75, 58, 46, 29, 20, 15], [55, 44, 28, 17, 14, 8], [42, 21, 17, 8, 6, 3]]
------------------------------------------------------------
Case         : 33
IMPOSSIBLE   : Failed to distribute 2 at descending position 36
------------------------------------------------------------
Case         : 34
Result Matrix: [[99, 96, 93, 85, 61, 45], [95, 89, 82, 59, 45, 35], [86, 71, 58, 44, 32, 26], [62, 58, 42, 31, 20, 16], [47, 40, 28, 18, 11, 8], [36, 28, 18, 11, 7, 3]]
------------------------------------------------------------
Case         : 35
Result Matrix: [[99, 97, 92, 85, 76, 58], [97, 88, 84, 73, 56, 41], [87, 77, 73, 52, 38, 23], [76, 70, 51, 29, 15, 10], [62, 46, 27, 15, 9, 7], [44, 26, 14, 7, 6, 4]]
------------------------------------------------------------
Case         : 36
Result Matrix: [[96, 93, 87, 78, 70, 43], [91, 80, 76, 70, 42, 24], [80, 75, 55, 40, 23, 10], [74, 54, 39, 19, 10, 7], [49, 34, 16, 10, 7, 3], [30, 11, 9, 5, 2, 0]]
------------------------------------------------------------
Case         : 37
Result Matrix: [[99, 94, 92, 81, 67, 56], [93, 89, 79, 65, 54, 44], [84, 69, 60, 53, 43, 26], [67, 59, 53, 32, 23, 10], [58, 50, 31, 19, 9, 6], [48, 30, 15, 8, 5, 2]]
------------------------------------------------------------
Case         : 38
IMPOSSIBLE   : Failed to distribute 97 at descending position 2
------------------------------------------------------------
Case         : 39
Result Matrix: [[96, 91, 88, 87, 78, 65], [89, 87, 86, 78, 64, 51], [87, 83, 75, 61, 51, 34], [80, 69, 59, 50, 32, 11], [66, 57, 47, 17, 8, 5], [52, 45, 12, 5, 1, 0]]
------------------------------------------------------------
Case         : 40
Result Matrix: [[99, 97, 90, 86, 74, 62], [93, 89, 83, 71, 59, 35], [88, 78, 67, 51, 33, 25], [74, 66, 48, 31, 22, 18], [66, 41, 28, 19, 15, 11], [39, 26, 19, 13, 10, 4]]
------------------------------------------------------------
Case         : 41
Result Matrix: [[99, 93, 86, 75, 61, 53], [87, 85, 75, 59, 49, 31], [79, 71, 59, 36, 29, 25], [68, 59, 35, 27, 21, 14], [54, 33, 26, 19, 13, 12], [32, 25, 18, 13, 7, 6]]
------------------------------------------------------------
Case         : 42
Result Matrix: [[94, 88, 84, 76, 70, 65], [85, 81, 76, 69, 61, 52], [78, 75, 68, 60, 49, 34], [72, 67, 58, 44, 26, 22], [65, 57, 41, 25, 22, 11], [54, 37, 23, 19, 10, 1]]
------------------------------------------------------------
Case         : 43
Result Matrix: [[95, 93, 84, 72, 65, 54], [92, 81, 71, 61, 51, 37], [76, 68, 60, 47, 37, 33], [66, 59, 45, 35, 32, 18], [57, 41, 34, 24, 17, 15], [38, 34, 20, 16, 14, 6]]
------------------------------------------------------------
Case         : 44
IMPOSSIBLE   : Failed to distribute 98 at descending position 2
------------------------------------------------------------
Case         : 45
IMPOSSIBLE   : Failed to distribute 99 at descending position 2
------------------------------------------------------------
Case         : 46
Result Matrix: [[99, 94, 90, 83, 78, 59], [93, 86, 82, 74, 58, 48], [84, 81, 67, 55, 47, 24], [79, 65, 52, 43, 23, 18], [63, 52, 32, 22, 16, 12], [50, 28, 19, 15, 8, 7]]
------------------------------------------------------------
Case         : 47
Result Matrix: [[99, 95, 86, 80, 72, 54], [95, 85, 78, 70, 54, 45], [81, 76, 66, 53, 44, 35], [74, 59, 49, 39, 32, 15], [55, 48, 37, 26, 14, 7], [47, 37, 24, 8, 6, 2]]
------------------------------------------------------------
Case         : 48
IMPOSSIBLE   : Failed to distribute 98 at descending position 2
------------------------------------------------------------
Case         : 49
Result Matrix: [[96, 95, 87, 72, 68, 56], [94, 77, 70, 64, 53, 43], [75, 69, 63, 50, 42, 28], [68, 62, 48, 42, 28, 13], [57, 47, 39, 23, 10, 7], [44, 31, 19, 10, 5, 1]]
------------------------------------------------------------
Case         : 50
IMPOSSIBLE   : Failed to distribute 99 at descending position 2
------------------------------------------------------------
Case         : 51
IMPOSSIBLE   : Failed to distribute 97 at descending position 2
------------------------------------------------------------
Case         : 52
IMPOSSIBLE   : Failed to distribute 95 at descending position 2
------------------------------------------------------------
Case         : 53
IMPOSSIBLE   : Failed to distribute 0 at descending position 35
------------------------------------------------------------
Case         : 54
Result Matrix: [[98, 97, 93, 78, 63, 45], [94, 86, 75, 61, 41, 27], [80, 73, 57, 38, 25, 20], [68, 52, 37, 24, 18, 11], [48, 32, 23, 14, 10, 7], [27, 22, 13, 7, 6, 2]]
------------------------------------------------------------
Case         : 55
Result Matrix: [[96, 88, 80, 76, 66, 49], [88, 80, 73, 63, 41, 28], [79, 68, 56, 39, 25, 18], [67, 50, 33, 24, 18, 11], [49, 30, 22, 17, 6, 4], [28, 20, 14, 6, 3, 0]]
------------------------------------------------------------
Case         : 56
IMPOSSIBLE   : Failed to distribute 2 at descending position 36
------------------------------------------------------------
Case         : 57
Result Matrix: [[99, 96, 88, 73, 66, 46], [92, 86, 69, 61, 44, 29], [75, 69, 53, 40, 24, 14], [68, 53, 37, 22, 13, 11], [48, 32, 22, 13, 11, 3], [31, 17, 11, 10, 1, 0]]
------------------------------------------------------------
Case         : 58
Result Matrix: [[98, 97, 91, 78, 72, 56], [92, 90, 77, 70, 55, 42], [86, 76, 65, 55, 38, 27], [76, 65, 55, 38, 24, 15], [58, 54, 37, 19, 11, 3], [46, 34, 18, 5, 3, 0]]
------------------------------------------------------------
Case         : 59
IMPOSSIBLE   : Failed to distribute 8 at descending position 36
------------------------------------------------------------
Case         : 60
Result Matrix: [[97, 96, 91, 75, 67, 40], [95, 88, 74, 67, 39, 33], [79, 74, 63, 39, 29, 20], [71, 62, 38, 29, 17, 5], [58, 38, 27, 14, 4, 2], [37, 24, 13, 4, 2, 1]]
------------------------------------------------------------
Case         : 61
IMPOSSIBLE   : Failed to distribute 5 at descending position 36
------------------------------------------------------------
Case         : 62
Result Matrix: [[96, 92, 83, 82, 63, 55], [90, 83, 77, 63, 54, 39], [83, 75, 62, 54, 36, 23], [72, 60, 53, 34, 22, 17], [57, 50, 33, 19, 14, 9], [50, 29, 18, 11, 6, 1]]
------------------------------------------------------------
Case         : 63
Result Matrix: [[99, 96, 93, 89, 80, 71], [95, 92, 87, 78, 70, 39], [90, 82, 78, 60, 38, 25], [81, 77, 55, 37, 23, 18], [74, 49, 36, 21, 13, 10], [44, 26, 19, 11, 3, 1]]
------------------------------------------------------------
Case         : 64
Result Matrix: [[97, 93, 87, 82, 75, 69], [89, 87, 82, 73, 68, 53], [83, 81, 71, 68, 51, 38], [76, 70, 67, 49, 37, 18], [70, 63, 45, 32, 14, 11], [63, 40, 21, 13, 10, 7]]
------------------------------------------------------------
Case         : 65
Result Matrix: [[94, 91, 87, 80, 72, 58], [91, 84, 80, 68, 55, 39], [80, 78, 64, 52, 36, 27], [74, 62, 51, 35, 26, 19], [61, 50, 35, 26, 15, 11], [49, 28, 25, 15, 10, 4]]
------------------------------------------------------------
Case         : 66
Result Matrix: [[90, 76, 67, 63, 61, 42], [72, 66, 63, 54, 40, 28], [65, 61, 53, 38, 25, 20], [61, 49, 36, 24, 17, 9], [42, 34, 23, 16, 8, 6], [31, 21, 10, 7, 5, 0]]
------------------------------------------------------------
Case         : 67
IMPOSSIBLE   : Failed to distribute 98 at descending position 2
------------------------------------------------------------
Case         : 68
IMPOSSIBLE   : Failed to distribute 98 at descending position 2
------------------------------------------------------------
Case         : 69
IMPOSSIBLE   : Failed to distribute 92 at descending position 2
------------------------------------------------------------
Case         : 70
IMPOSSIBLE   : Failed to distribute 99 at descending position 2
------------------------------------------------------------
Case         : 71
IMPOSSIBLE   : Failed to distribute 10 at descending position 36
------------------------------------------------------------
Case         : 72
Result Matrix: [[95, 93, 91, 82, 73, 60], [92, 87, 82, 72, 56, 48], [86, 76, 71, 55, 43, 38], [75, 64, 55, 42, 36, 20], [62, 53, 41, 26, 17, 14], [50, 40, 22, 16, 14, 3]]
------------------------------------------------------------
Case         : 73
Result Matrix: [[97, 91, 90, 80, 70, 60], [91, 88, 73, 69, 55, 41], [84, 71, 68, 53, 41, 29], [71, 67, 53, 39, 23, 15], [64, 44, 39, 19, 13, 10], [42, 37, 18, 10, 8, 5]]
------------------------------------------------------------
Case         : 74
IMPOSSIBLE   : Failed to distribute 0 at descending position 36
------------------------------------------------------------
Case         : 75
Result Matrix: [[96, 95, 91, 82, 72, 43], [92, 88, 78, 70, 41, 27], [83, 77, 61, 38, 25, 22], [76, 55, 36, 24, 20, 14], [54, 34, 22, 18, 12, 9], [30, 22, 15, 10, 2, 0]]
------------------------------------------------------------
Case         : 76
Result Matrix: [[98, 93, 88, 83, 72, 57], [90, 84, 81, 72, 55, 36], [84, 76, 68, 50, 36, 24], [75, 63, 44, 30, 24, 6], [58, 42, 26, 20, 6, 1], [39, 26, 9, 3, 1, 0]]
------------------------------------------------------------
Case         : 77
Result Matrix: [[86, 85, 74, 63, 53, 40], [81, 74, 61, 42, 39, 36], [65, 58, 41, 39, 34, 25], [53, 41, 38, 32, 23, 19], [40, 37, 31, 22, 18, 8], [36, 27, 20, 9, 6, 0]]
------------------------------------------------------------
Case         : 78
Result Matrix: [[87, 84, 82, 75, 70, 58], [82, 79, 75, 68, 54, 46], [77, 74, 62, 53, 35, 33], [74, 62, 53, 34, 29, 10], [59, 49, 34, 24, 10, 8], [49, 34, 21, 9, 4, 1]]
------------------------------------------------------------
Case         : 79
Result Matrix: [[98, 95, 89, 80, 70, 53], [92, 86, 80, 69, 53, 41], [83, 75, 68, 52, 40, 33], [72, 66, 49, 39, 28, 13], [66, 45, 38, 22, 12, 7], [43, 36, 13, 12, 5, 3]]
------------------------------------------------------------
Case         : 80
IMPOSSIBLE   : Failed to distribute 98 at descending position 2
------------------------------------------------------------
Case         : 81
IMPOSSIBLE   : Failed to distribute 98 at descending position 2
------------------------------------------------------------
Case         : 82
Result Matrix: [[99, 82, 80, 73, 62, 55], [82, 79, 72, 59, 49, 31], [74, 65, 59, 40, 30, 23], [64, 59, 36, 27, 21, 16], [58, 36, 26, 19, 16, 8], [32, 26, 18, 11, 2, 1]]
------------------------------------------------------------
Case         : 83
Result Matrix: [[98, 95, 91, 85, 81, 65], [93, 90, 85, 80, 65, 42], [86, 84, 75, 59, 27, 20], [84, 67, 57, 26, 20, 13], [66, 49, 24, 17, 13, 9], [45, 21, 15, 10, 4, 0]]
------------------------------------------------------------
Case         : 84
Result Matrix: [[99, 98, 91, 77, 66, 58], [92, 90, 74, 65, 57, 50], [81, 70, 62, 56, 46, 29], [69, 62, 55, 46, 25, 16], [59, 55, 42, 21, 15, 10], [53, 32, 17, 11, 9, 0]]
------------------------------------------------------------
Case         : 85
IMPOSSIBLE   : Failed to distribute 89 at descending position 4
------------------------------------------------------------
Case         : 86
IMPOSSIBLE   : Failed to distribute 2 at descending position 36
------------------------------------------------------------
Case         : 87
Result Matrix: [[99, 95, 88, 80, 74, 58], [89, 85, 79, 71, 57, 42], [83, 78, 65, 56, 39, 29], [78, 63, 51, 31, 26, 21], [62, 47, 31, 25, 21, 13], [45, 31, 24, 20, 9, 5]]
------------------------------------------------------------
Case         : 88
IMPOSSIBLE   : Failed to distribute 3 at descending position 36
------------------------------------------------------------
Case         : 89
Result Matrix: [[99, 88, 79, 71, 64, 46], [80, 74, 70, 63, 42, 35], [72, 65, 63, 42, 32, 25], [65, 60, 39, 30, 24, 16], [54, 38, 29, 21, 16, 7], [36, 27, 17, 10, 7, 2]]
------------------------------------------------------------
Case         : 90
Result Matrix: [[95, 93, 75, 59, 44, 34], [80, 66, 58, 37, 33, 25], [64, 49, 37, 33, 23, 20], [44, 36, 32, 23, 18, 11], [35, 31, 22, 15, 10, 4], [28, 21, 13, 6, 3, 0]]
------------------------------------------------------------
Case         : 91
IMPOSSIBLE   : Failed to distribute 99 at descending position 2
------------------------------------------------------------
Case         : 92
Result Matrix: [[92, 86, 85, 69, 62, 56], [85, 80, 68, 61, 53, 33], [79, 67, 60, 47, 30, 22], [62, 59, 43, 26, 21, 14], [59, 43, 25, 20, 9, 5], [36, 24, 18, 9, 4, 1]]
------------------------------------------------------------
Case         : 93
Result Matrix: [[95, 94, 91, 87, 80, 69], [93, 90, 86, 80, 69, 52], [87, 86, 78, 64, 46, 27], [82, 77, 64, 37, 27, 23], [69, 60, 36, 25, 19, 17], [57, 29, 23, 18, 17, 8]]
------------------------------------------------------------
Case         : 94
IMPOSSIBLE   : Failed to distribute 1 at descending position 36
------------------------------------------------------------
Case         : 95
Result Matrix: [[98, 89, 83, 82, 72, 61], [88, 83, 82, 72, 60, 46], [82, 81, 72, 60, 41, 33], [75, 69, 59, 37, 33, 21], [61, 54, 35, 27, 20, 6], [51, 35, 23, 17, 4, 1]]
------------------------------------------------------------
Case         : 96
Result Matrix: [[97, 95, 84, 81, 75, 58], [93, 83, 81, 72, 58, 41], [81, 78, 71, 56, 39, 20], [75, 66, 49, 37, 16, 9], [63, 47, 36, 13, 8, 5], [45, 22, 10, 7, 3, 2]]
------------------------------------------------------------
Case         : 97
Result Matrix: [[98, 94, 92, 83, 75, 62], [92, 85, 82, 74, 61, 38], [85, 79, 70, 57, 33, 28], [75, 69, 54, 33, 28, 10], [67, 53, 31, 25, 10, 8], [44, 31, 12, 8, 5, 2]]
------------------------------------------------------------
Case         : 98
IMPOSSIBLE   : Failed to distribute 2 at descending position 36
------------------------------------------------------------
Case         : 99
IMPOSSIBLE   : Failed to distribute 1 at descending position 36
------------------------------------------------------------
Case         : 100
IMPOSSIBLE   : Failed to distribute 95 at descending position 2
============================================================
45 of 100 cases are impossible
79814869
Vote

There is one perfect way to place the sorted numbers, starting at indexes 0,0, the next number at 1,0, then 0,1, 2,0, 1,1, 0,2, 3,0, ... So always fill the diagonals first before starting the next column. If it cannot be placed with this algorithm, then there is no other way to do it.

My code fills the 2-D array and then validates it by checking each entry to be bigger than the one to the right and below.

#include <array>
#include <algorithm>
#include <string>
#include <iostream>
#include <sstream>

bool validate(const std::array<std::array<int, 6>, 6> &arr)
{
    for (size_t row = 0; row < 5; row++)
    {
        for (size_t col = 0; col < 5; col++)
        {
            if (arr[row][col] <= arr[row+1][col] || arr[row][col] <= arr[row][col+1])
            {
                return false;
            }
        }
        if (arr[row][5] <= arr[row+1][5])
        {
            return false;
        }
    }
    for (size_t row = 0; row < 5; row++)
    {
        if (arr[5][row] <= arr[5][row+1])
        {
            return false;
        }
    }
    return true;
}

void print_array(const std::array<std::array<int, 6>, 6> &arr)
{
    printf("[");
    for (size_t row = 0; row < 6; row++)
    {
        printf("[");
        for (size_t col = 0; col < 5; col++)
        {
            printf("%d, ", arr[row][col]);
        }
        printf("%d]", arr[row][5]);
        if (row != 5) printf(", ");
    }
    printf("]\n");
}


std::array<std::array<int, 6>, 6>  transform(std::array<int, 36>& arr)
{
    std::sort(arr.begin(), arr.end(), std::greater<int>());

    std::array<std::array<int, 6>, 6> result;

    int index = 0;
    for (int diag = 0; diag < 11; ++diag)
    {
        for (int row = 0; row <= diag; ++row)
        {
            int col = diag - row;
            if (row < 6 && col < 6) {
                result[row][col] = arr[index++];
            }
        }
    }
    return result;
}


bool check_case(std::array<int, 36> &arr)
{
    const auto result = transform(arr);
    if (!validate(result))
    {
        printf("impossible\n");
        return false;
    } 
    print_array(result);
    return true;
}


int main()
{
    std::string line;
    int count = 0;

    while (std::getline(std::cin, line)) {
        std::istringstream iss(line);
        std::array<int, 36> arr;
        for (auto &val:arr) {
            if (!(iss >> val)) {
                break;
            }
        }
        if (!check_case(arr)) {
            ++count;
        }
    }
    std::cout << "Number of impossible cases: " << count << std::endl;
    return 0;
}

Interestingly, there can be one value 6 times, but only starting at the 16th position in the sorted list. They have to make up the whole main diagonale.

Having the biggest/smallest value duplicated, invalidates it immediately. Starting with the second biggest/smallest value values can be duplicated, but only with the fourth biggest/smallest value values can be three times in the list and starting with the seventh biggest/smallest values can be four times in the list, etc...

Here is a link to compiler explorer, where my code reads the test input: https://godbolt.org/z/YvohbPM9G

45 out of the 100 cases are impossible, mainly because of duplicated smallest or biggest values.

79815980
Vote

This is of course correct and a very logical approach (effectively identical to my own), though I must point out that there is are many valid alternative grids, not "one perfect way", for the great majority of given sequences. In fact, within any diagonal, the ordering of numbers may be arbitrary, so we can even calculate quite easily how many different ways to fill the grid exist.

79820778
Vote

@Noldorin: you are right, of course, in pointing out that many grids admit many equally valid solutions. However, I don't think the 'one perfect way' was meant as 'the only true way'. It is perfect in the sense that it does not involve an trial placements; if the diagonal placement of the sorted values does not result in a rule-conforming assignment then there is no solution, period.

And let's not forget the other one true way of placement - the diagonal mirror (i.e. going downwards to the left instead of upwards to the right). ;-)

79814831
Vote
Result KO:45/100
OKs [2, 3, 4, 8, 9, 13, 14, 17, 19, 21, 26, 28, 29, 30, 31, 33, 34, 35, 36, 38, 39, 40, 41, 42, 45, 46, 48, 53, 54, 56, 57, 59, 61, 62, 63, 64, 65, 71, 72, 74, 75, 76, 77, 78, 81, 82, 83, 86, 88, 89, 91, 92, 94, 95, 96]
KOs [0, 1, 5, 6, 7, 10, 11, 12, 15, 16, 18, 20, 22, 23, 24, 25, 27, 32, 37, 43, 44, 47, 49, 50, 51, 52, 55, 58, 60, 66, 67, 68, 69, 70, 73, 79, 80, 84, 85, 87, 90, 93, 97, 98, 99]
Detail Json or Txt
Code Python source Grid6x6.py
Desc Grid diagonal route
Exec python3 Grid6x6.py
79814478
Vote

I tried to solve the 6×6 strictly-decreasing grid challenge with this. this is my first chalange.

# app.py
from ortools.sat.python import cp_model
from collections import Counter
import sys

ROWS = COLS = 6
N = ROWS * COLS

def solve_with_ortools(values, time_limit_seconds=30):
    counts = Counter(values)
    uniq = sorted(counts.keys())  # asc order
    M = len(uniq)
    val_index = {v:i for i,v in enumerate(uniq)}
    model = cp_model.CpModel()
    x = {}
    for cell in range(N):
        for j in range(M):
            x[(cell,j)] = model.NewBoolVar(f"x_{cell}_{j}")

    # every cell gets 1 val
    for cell in range(N):
        model.Add(sum(x[(cell,j)] for j in range(M)) == 1)

    # val's count 
    for j, v in enumerate(uniq):
        model.Add(sum(x[(cell,j)] for cell in range(N)) == counts[v])

    cell_value = []
    for cell in range(N):
        vmin, vmax = uniq[0], uniq[-1]
        cv = model.NewIntVar(vmin, vmax, f"cellval_{cell}")
        model.Add(cv == sum(uniq[j] * x[(cell,j)] for j in range(M)))
        cell_value.append(cv)

    # strict decreasing like left > right, top > below
    for r in range(ROWS):
        for c in range(COLS):
            idx = r * COLS + c
            if c + 1 < COLS:
                model.Add(cell_value[idx] > cell_value[idx + 1])
            if r + 1 < ROWS:
                model.Add(cell_value[idx] > cell_value[idx + COLS])

    solver = cp_model.CpSolver()
    solver.parameters.max_time_in_seconds = time_limit_seconds
    solver.parameters.num_search_workers = 8  # parallel
    solver.parameters.maximize = False

    res = solver.Solve(model)
    if res not in (cp_model.OPTIMAL, cp_model.FEASIBLE):
        return None
    grid = []
    for r in range(ROWS):
        row = []
        for c in range(COLS):
            idx = r * COLS + c
            chosen = None
            for j, v in enumerate(uniq):
                if solver.Value(x[(idx,j)]) == 1:
                    chosen = v
                    break
            row.append(chosen)
        grid.append(row)
    return grid

def run_file(path, per_case_time=10):
    impossible_count = 0
    outputs = []
    with open(path) as f:
        for line_no, line in enumerate(f, start=1):
            parts = line.strip().split()
            if not parts:
                continue
            if len(parts) != N:
                raise ValueError(f"Line {line_no} does not have {N} integers.")
            vals = list(map(int, parts))
            grid = solve_with_ortools(vals, time_limit_seconds=per_case_time)
            if grid is None:
                impossible_count += 1
                outputs.append(None)
            else:
                outputs.append(grid)
            print(f"Processed line {line_no}: {'IMPOSSIBLE' if grid is None else 'OK'}")
    print("Total impossible:", impossible_count, "out of", len(outputs))
    return outputs

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python app.py input.txt")
        sys.exit(1)
    run_file(sys.argv[1])

If we want to run it locally:

python app.py test.txt
79812964
Vote

Possible Sets : 14

Impossible sets : 86

details :-

4. [[99, 94, 88, 86, 83, 81],[74, 73, 71, 70, 63, 62],[61, 59, 57, 56, 52, 50],[48, 40, 36, 35, 29, 27],[40, 27, 24, 20, 19, 13], [10, 9, 8, 6, 3, 1]]

10. [[99, 97, 88, 86, 82, 81],[88, 81, 79, 71, 68, 66],[79, 64, 63, 58, 56, 54],[64, 63, 52, 51, 50, 48],[42, 41, 38, 35, 15, 11],[11, 9, 5, 3, 2, 0]]

14. [[98, 96, 93, 91, 90, 82],[82, 74, 73, 70, 68, 66],[66, 65, 58, 56, 55, 54],[49, 41, 38, 32, 31, 28],[21, 19, 16, 14, 12, 10],[19, 16, 12, 10, 4, 3]]

27. [[97, 95, 91, 86, 85, 81],[91, 80, 79, 76, 75, 74],[79, 68, 66, 62, 61, 58],[68, 66, 62, 57, 46, 45],[38, 33, 31, 28, 27, 20],[31, 17, 14, 13, 7, 1]]

29. [[92, 91, 88, 87, 85, 84],[88, 85, 83, 80, 77, 73],[73, 71, 70, 68, 65, 52],[42, 37, 35, 32, 29, 27],[32, 26, 22, 20, 17, 14],[12, 11, 10, 9, 7, 3]]

30. [[98, 97, 96, 89, 87, 84],[81, 80, 73, 64, 63, 62],[80, 63, 59, 55, 50, 49],[59, 48, 45, 40, 36, 34],[31, 29, 28, 27, 24, 19],[14, 12, 11, 7, 2, 1]]

37. [[99, 94, 93, 92, 89, 84],[81, 79, 69, 67, 65, 60],[67, 59, 58, 56, 54, 53],[53, 50, 48, 44, 43, 32],[31, 30, 26, 23, 19, 15],[10, 9, 8, 6, 5, 2]]

40. [[99, 97, 93, 90, 89, 88],[86, 83, 78, 74, 71, 67],[74, 66, 62, 59, 51, 48],[66, 41, 39, 35, 33, 31],[28, 26, 25, 22, 19, 18],[19, 15, 13, 11, 10, 4]]

43. [[95, 93, 92, 84, 81, 76],[72, 71, 68, 66, 65, 61],[60, 59, 57, 54, 51, 47],[45, 41, 38, 37, 35, 34],[37, 34, 33, 32, 24, 20],[18, 17, 16, 15, 14, 6]]

63. [[99, 96, 95, 93, 92, 90],[89, 87, 82, 81, 80, 78],[78, 77, 74, 71, 70, 60],[55, 49, 44, 39, 38, 37],[36, 26, 25, 23, 21, 19],[18, 13, 11, 10, 3, 1]]

64. [[97, 93, 89, 87, 83, 82],[87, 82, 81, 76, 75, 73],[71, 70, 69, 68, 67, 63],[70, 68, 63, 53, 51, 49],[45, 40, 38, 37, 32, 21],[18, 14, 13, 11, 10, 7]]

77. [[86, 85, 81, 74, 65, 63],[74, 61, 58, 53, 42, 41],[53, 41, 40, 39, 38, 37],[40, 39, 36, 34, 32, 31],[36, 27, 25, 23, 22, 20],[19, 18, 9, 8, 6, 0]]

78. [[87, 84, 82, 79, 77, 75],[82, 75, 74, 70, 68, 62],[74, 62, 59, 58, 54, 53],[53, 49, 46, 35, 34, 33],[49, 34, 29, 24, 21, 10],[34, 10, 9, 8, 4, 1]]

90. [[95, 93, 80, 75, 66, 64],[59, 58, 49, 44, 37, 36],[44, 37, 35, 34, 33, 32],[33, 31, 28, 25, 23, 22],[23, 21, 20, 18, 15, 13],[11, 10, 6, 4, 3, 0]]

All remaining are Impossible.

let possible = 0, impossible = 0;
fetch("integers.json")
    .then((response) => response.json())
    .then((integers) => {

        integers.forEach((set, index) => {
            let row1 = [];
            let row2 = [];
            let row3 = [];
            let row4 = [];
            let row5 = [];
            let row6 = [];
            set.sort((a, b) => b - a);
            set.forEach((value) => {
                if (!row1.includes(value) && row1.length < 6) {
                    row1.push(value);
                    return;
                }
                if (!row2.includes(value) && row2.length < 6) {
                    row2.push(value);
                    return;
                }
                if (!row3.includes(value) && row3.length < 6) {
                    row3.push(value);
                    return;
                }
                if (!row4.includes(value) && row4.length < 6) {
                    row4.push(value);
                    return;
                }
                if (!row5.includes(value) && row5.length < 6) {
                    row5.push(value);
                    return;
                }
                if (!row6.includes(value) && row6.length < 6) {
                    row6.push(value);
                    return;
                }
            });
            const sortedSet = [row1, row2, row3, row4, row5, row6];

            const allHaveSixValues = sortedSet.every(set => set.length === 6);
            if (allHaveSixValues) {
                const hasDuplicateInColumn = sortedSet[0].some((_, colIndex) => {
                    const column = sortedSet.map(row => row[colIndex]);
                    const unique = new Set(column);
                    if (unique.size !== column.length) {
                        return true;
                    }
                    return false;
                });

                if (hasDuplicateInColumn) {
                    console.log(index + 1, "Impossible");
                    impossible++;
                }
                else {
                    console.log(index + 1, sortedSet);
                    possible++;
                }
            } else {
                console.log(index + 1, "Impossible");
                impossible++;
            }
        });
        console.log("possible", possible, "impossible", impossible);
    })
    .catch((err) => console.error("Error loading JSON:", err));
79812918
Vote

My approach was to open the file once and read the 100 sets with one loop.

Within the loop, it'd stop reading after 36 numbers and use the good ol' QuickSort algorithm for the array, and then a little algorithm for sorting the grid itself.

Before the loop started, the program would initialize an impossible grid counter to 0, and increment it if and only if there was a case a grid wasn't properly sorted after the algorithm call.

Since there was really only one result (besides flipping the rows and columns), this was a clear indication the grid wouldn't exist whatsoever. So, it'd only print the correct grids and the impossible count.

The result was rather... interesting.

// Made by Alex, November 8th, 2025
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

int compare(const void* n1, const void* n2);

void gridSort(const int *array, int arrayGrid[6][6]);

bool isValidGrid(int arrayGrid[6][6]);

void printGrid(int arrayGrid[6][6]);


int main() {

    FILE *f = fopen("RandomNumbers.txt", "r");

    int impossibleCounter = 0;

    for (int ac = 0; ac < 100; ac++) { // Array counter 0-100 :)

        int array[36], arrayGrid[6][6], a; // This is the array picker, the formed grid, and then a num picker
        char s[256];

        a = 0;

        if (!fgets(s, sizeof(s), f))
            break;

        char *c = s;
        while (*c) {

            if (a < 36 && sscanf(c, "%d", &array[a]) == 1) {
                a++;
                while (*c && *c != ',' && *c != ']') c++;
            }

            if (*c) c++;
        }

        qsort(array, 36, sizeof(int), compare);

        gridSort(array, arrayGrid);

        if (!isValidGrid(arrayGrid)) {
            impossibleCounter++;
            continue;
        }

        printf("Grid no. %d of 100:\n", ac+1);

        printGrid(arrayGrid);

    }

    printf(" \n%d grids are impossible with these arrays.", impossibleCounter);

    fclose(f);
    return 0;
}

int compare(const void* n1, const void* n2) {
    return (*(int*)n2 - *(int*)n1); // just generic comp for the qsort
}

void gridSort(const int *array, int arrayGrid[6][6]) {

    int x = 0;
    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 6; j++) {
            arrayGrid[i][j] = array[x++];
        }
    }

    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 6; j++) {
            if (j > 0 && arrayGrid[i][j] == arrayGrid[i][j - 1] && j + 1 < 6) {
                int aux = arrayGrid[i][j];
                arrayGrid[i][j] = arrayGrid[i][j + 1];
                arrayGrid[i][j + 1] = aux;
            }
            if (i > 0 && arrayGrid[i][j] == arrayGrid[i - 1][j] && i + 1 < 6) {
                int aux = arrayGrid[i][j];
                arrayGrid[i][j] = arrayGrid[i + 1][j];
                arrayGrid[i + 1][j] = aux;
            }
        }
    }
}

bool isValidGrid(int arrayGrid[6][6]) {

    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 6; j++) {

            if (j + 1 < 6 && arrayGrid[i][j] < arrayGrid[i][j + 1]) {
                return false;
            }
            if (i + 1 < 6 && arrayGrid[i][j] < arrayGrid[i + 1][j]) {
                return false;
            }
        }
    }

    return true;
}

void printGrid(int arrayGrid[6][6]) {

    // I noticed the detail, so I printed all of this considering the no. of possible grids ;p

    printf("[");
    for (int i = 0; i < 6; i++) {

        printf("[");
        for (int j = 0; j < 6; j++) {
            j != 5 ? printf("%d,", arrayGrid[i][j]) : printf("%d", arrayGrid[i][j]);
        }
        i != 5 ? printf("],") : printf("]");
    }
    printf("]\n\n");

    for (int i = 0; i < 6; i++) {

        for (int j = 0; j < 6; j++) {
            printf("%3d", arrayGrid[i][j]);
        }

        printf("\n");
    }
}

The result was the following.

Grid no. 63 of 100:
[[99,96,95,93,92,90],[89,87,82,81,80,78],[78,77,74,71,70,60],[55,49,44,39,38,37],[36,26,25,23,21,19],[18,13,11,10,3,1]]
 99 96 95 93 92 90
 89 87 82 81 80 78
 78 77 74 71 70 60
 55 49 44 39 38 37
 36 26 25 23 21 19
 18 13 11 10  3  1
99 grids are impossible with these arrays.
79812837
Vote

Sorting the whole list and then creating groups of 6 numbers is enough. Or it would be if it weren't because ties are not allowed.

Let's study a case where my initial approach wouldn't work but there was another solution that could somehow be found with a different approach. For simplicity, we are using a 3 x 3 grid.

[9,8,8,6,5,4,3,2,1]

My initial approach would fail:

[9,8,8],
[6,5,4],
[3,2,1]

The first group has a tie with the number 8. Let's see if we can find another way...

[9,8,6],
[8,5,4],
[3,2,1]

Wonderful! All we had to do is swap the last number of the first row with the first number of the second row. Maybe it's a matter of swapping some numbers somehow after sorting them? How would we do this? We certainly can't swap 2 numbers in the same row or column because otherwise the order would be altered and they wouldn't be sorted anymore. So here is out first conclusion:

Conclusion #1: Numbers to be swapped must belong to different rows and columns.

But now the question is: Which ones should I swap? Obviously the number that is repeated but, which one should we swap it with? With the whole list sorted, if we check each number one by one from left to right on this list we will only have to find another number to swap this one with among the rest of the numbers that we have not checked yet in the right side of the one we are currently checking.

Let's use a 4 x 4 grid this time:

[15,14,14,13],
[12,11,10,09],
[08,07,06,05],
[04,03,02,01]

We have two 14s. All the other numbers are lower, so we can only swap the last 14 because if we replaced the first one then the first row would stop being ordered. If there were more repeated numbers in a row we would always have to start with the last one for this very same reason. And we know we are supposed to swap it with a number from a different row and column but we can't swap it with a column on the right side because the column would not be ordered anymore since the number we are swapping is greater than the one at the right side of it in the same row. The number must be swapped with another in a column from its left side, but the only one we can swap it with is the first one because any other would make the next row unordered.

Conclusion #2: A number may only be swapped with the first number of the next row.

But we have a problem: If we do so, we'd end up with this grid:

[15,14,12,13],
[14,11,10,09],
[08,07,06,05],
[04,03,02,01]

The first row is not quite right, it's not ordered. We were doomed to have this scenario since every number of the next row is lower than the number in the right side of the one we are swapping because they belong to a row that is below. But that can be easily fixed: we just have to move this new number to the rightmost side of the row.

[15,14,13,12],
[14,11,10,09],
[08,07,06,05],
[04,03,02,01]

Now everything is in order. But what if there were 3 repeated numbers instead?

[13,12,12,12,11],
[10,09,08,07,06],
[05,04,03,02,01]

We'd start swapping the last repeated number (12) of the first row with the first number of the second row and then move the first number of the second row to the end of the first row. So we'd have this:

[13,12,12,11,10],
[12,09,08,07,06],
[05,04,03,02,01]

But now we have a problem: If we tried the same, we'd be swapping a 12 with another 12 which already doesn't make sense, but then we'd put that 12 at the end of the first row so it wouldn't be sorted anymore!

[13,12,10,11,12],
[12,09,08,07,06],
[05,04,03,02,01]

We can't do this when we have 3 numbers repeated. We can't put two 12s in the second row either. And we can't put it anywhere in the 3rd row because the first column would have 2 repeated 12s and any other would make this row unsorted. In fact, interestingly enough, this approach wouldn't work as long as we had 3 repeated numbers one right after another in the whole sorted list even if one of them ended up in the next row. For instace, if we had this case were the number 10 is repeating:

[13,12,11,10,10,10,09,08,07,06,05,04,03,02,01]

We'd have then this grid...

[13,12,11,10,10],
[10,09,08,07,06],
[05,04,03,02,01]

...and then we would still have the same problem because we are again swapping a number with another that just so happens to be the same number. If the first repeating number was the last one in its row and the next two were the first in the next row we wouldn't be able to create a grid because a row cannot start with 2 repeating numbers in general because we won't have columns in the left to swap these numbers with.

Conclusion #3: If we have 3 repeating numbers, the grid cannot be created.

So that's it then. We first check if the whole list has 3 repeating numbers and automatically abort in that case, and if not then we only have to swap the 2 numbers that repeat using this algorithm. Except because there is one last use case that we have not discussed yet: What if there were 2 pairs of repeated numbers in the same row?

[8,7,7,6,6,5,4,3,2,1]
[8,7,7,6,6],
[5,4,3,2,1]

If we apply the algorith with the number 7...

[8,7,6,6,5],
[7,4,3,2,1]

... and then again with the number 6...

[8,7,6,5,7],
[6,4,3,2,1]

Well, this is awkward. But at least it's esay to fix: it's just a matter of swapping the number with the first number of the next row that has not been swapped already. In this case that'd be the number 4:

[8,7,6,5,4],
[7,6,3,2,1]

The code, thus, becomes...

let numberOfImpossibleCases = 0;

function solution(numbers) {
  const sorted = numbers.sort((a, b) => b - a);
  if(checkRepeatedNumbers(sorted, 3) !== false) {
    numberOfImpossibleCases++;
    return false;
  }
  const grid = makeGrid(sorted, Math.sqrt(numbers.length));
  let count;
  for(i = 0; i < grid.length; i++) {
    let j = checkRepeatedNumbers(grid[i], 2);
    count = 0;
    while(j !== false) {
      if(!swap(grid, i, j+1, count)) {
        numberOfImpossibleCases++;
        return false;
      }
      j = checkRepeatedNumbers(grid[i], 2);
      count++;
    }
  }
  return grid;
}

function checkRepeatedNumbers(sortedListOfNumbers, quantity) {
  const copy = [...sortedListOfNumbers];
  let index = 0;
  while(copy.length >= quantity) {
    const n1 = copy.shift();
    if(copy.slice(0, quantity - 1).every(n => n == n1)) {
      return index;
    }
    index++;
  }
  return false;
}

function makeGrid(list, size) {
  const grid = [];
  const copy = [...list];
  while(copy.length > 0) {
    grid.push(copy.splice(0, size));
  }
  return grid;
}

function swap(grid, row, column, count) {
  if(row == grid.length - 1 || column == 1) {
    return false;
  }
  const firstRow = grid[row];
  const secondRow = grid[row+1];
  const [repeatedNumber] = firstRow.splice(column, 1);
  const [numberFromRowBelow] = secondRow.splice(count, 1, repeatedNumber);
  firstRow.push(numberFromRowBelow);
  return true;
}

And to test it...

const data = [
  [54, 95, 98, 26, 3, 39, 77, 30, 83, 62, 20, 92, 61, 59, 26, 63, 92, 49, 38, 51, 99, 64, 65, 52, 98, 18, 90, 97, 96, 13, 74, 3, 88, 88, 67, 10],
  [49, 13, 73, 54, 4, 98, 36, 33, 12, 22, 35, 18, 39, 83, 92, 77, 50, 77, 57, 64, 0, 35, 86, 98, 28, 1, 53, 59, 28, 33, 56, 37, 98, 26, 81, 13],
  [95, 84, 44, 16, 42, 73, 0, 53, 14, 63, 81, 91, 42, 14, 13, 59, 91, 24, 99, 71, 73, 34, 60, 65, 82, 55, 16, 75, 7, 18, 68, 6, 61, 6, 80, 41],
  [27, 63, 35, 81, 56, 24, 70, 27, 59, 13, 36, 62, 73, 6, 61, 86, 48, 40, 88, 71, 52, 1, 9, 57, 50, 40, 20, 10, 3, 29, 19, 94, 99, 8, 74, 83],
  [46, 75, 78, 14, 89, 76, 37, 26, 85, 78, 81, 27, 99, 41, 96, 52, 21, 65, 71, 48, 60, 32, 48, 31, 85, 35, 88, 5, 78, 22, 31, 97, 43, 80, 52, 45],
  [0, 98, 50, 12, 0, 83, 46, 66, 67, 23, 52, 55, 41, 95, 5, 17, 78, 98, 74, 45, 97, 98, 96, 54, 48, 79, 29, 0, 73, 6, 16, 33, 20, 88, 9, 23],
  [9, 2, 10, 57, 79, 65, 65, 0, 19, 64, 3, 18, 20, 93, 10, 30, 9, 0, 40, 51, 87, 34, 52, 71, 28, 23, 73, 61, 77, 60, 66, 91, 57, 58, 2, 9],
  [27, 63, 51, 6, 3, 10, 7, 36, 80, 51, 93, 71, 73, 25, 3, 77, 35, 56, 36, 36, 77, 97, 14, 1, 78, 83, 5, 51, 99, 5, 93, 90, 1, 36, 83, 4],
  [89, 94, 67, 64, 31, 66, 59, 16, 80, 22, 78, 72, 56, 83, 98, 10, 9, 57, 23, 4, 80, 37, 65, 30, 71, 55, 42, 9, 60, 18, 39, 58, 44, 79, 48, 29],
  [79, 51, 3, 82, 81, 58, 99, 88, 54, 88, 81, 5, 63, 79, 52, 64, 48, 64, 68, 11, 50, 66, 35, 71, 9, 86, 11, 97, 42, 41, 0, 2, 56, 38, 15, 63],
  [94, 35, 12, 94, 79, 40, 91, 45, 37, 98, 43, 30, 80, 81, 87, 19, 74, 87, 93, 35, 88, 89, 79, 44, 6, 87, 27, 49, 98, 44, 68, 39, 42, 87, 61, 84],
  [5, 37, 89, 80, 31, 40, 1, 10, 54, 67, 23, 1, 75, 43, 49, 27, 29, 69, 43, 41, 7, 16, 63, 70, 5, 61, 74, 87, 2, 61, 50, 72, 91, 56, 12, 99],
  [43, 35, 83, 94, 69, 45, 76, 73, 83, 60, 80, 31, 59, 34, 39, 63, 35, 13, 94, 78, 2, 24, 87, 21, 36, 38, 55, 19, 10, 82, 13, 95, 88, 54, 94, 75],
  [66, 10, 58, 21, 82, 10, 32, 91, 66, 65, 3, 12, 4, 38, 12, 96, 55, 54, 73, 16, 74, 41, 28, 49, 19, 98, 16, 90, 93, 82, 56, 68, 14, 70, 31, 19],
  [13, 79, 47, 31, 79, 31, 56, 65, 94, 73, 57, 35, 74, 85, 84, 39, 24, 26, 12, 56, 46, 46, 71, 0, 57, 61, 77, 32, 14, 1, 81, 71, 69, 66, 57, 69],
  [8, 39, 23, 14, 88, 44, 81, 46, 5, 26, 50, 11, 71, 19, 86, 33, 88, 62, 81, 13, 60, 96, 7, 78, 6, 88, 77, 94, 74, 63, 48, 40, 29, 47, 64, 6],
  [95, 36, 61, 3, 75, 84, 95, 8, 57, 42, 43, 77, 27, 65, 56, 78, 34, 96, 18, 23, 46, 17, 86, 17, 89, 28, 96, 18, 24, 90, 93, 49, 47, 69, 91, 48],
  [76, 95, 10, 10, 58, 67, 25, 41, 0, 49, 13, 40, 59, 29, 62, 64, 97, 47, 22, 42, 39, 44, 16, 95, 23, 91, 14, 48, 90, 39, 16, 92, 46, 38, 49, 16],
  [60, 42, 28, 28, 61, 10, 37, 90, 99, 9, 45, 15, 61, 20, 6, 89, 99, 5, 34, 28, 58, 45, 10, 43, 73, 5, 45, 78, 68, 48, 44, 56, 78, 69, 52, 99],
  [99, 92, 63, 87, 23, 73, 25, 25, 31, 97, 14, 12, 77, 96, 73, 80, 86, 15, 63, 71, 44, 34, 51, 28, 77, 24, 19, 74, 87, 34, 59, 40, 82, 13, 25, 15],
  [48, 59, 63, 45, 51, 64, 88, 99, 81, 29, 69, 27, 7, 28, 9, 77, 50, 80, 7, 64, 3, 24, 6, 22, 31, 69, 92, 66, 13, 3, 70, 81, 73, 50, 45, 42],
  [0, 49, 29, 50, 38, 38, 24, 71, 8, 5, 56, 6, 90, 2, 3, 35, 40, 89, 24, 27, 74, 77, 54, 7, 1, 76, 92, 16, 55, 23, 47, 62, 33, 1, 80, 47],
  [1, 61, 12, 89, 56, 47, 88, 63, 73, 49, 9, 78, 68, 69, 19, 53, 76, 39, 49, 83, 38, 70, 62, 79, 19, 7, 70, 4, 90, 57, 90, 20, 52, 37, 64, 17],
  [0, 99, 18, 20, 0, 5, 93, 66, 87, 4, 62, 47, 94, 27, 73, 82, 12, 37, 39, 63, 59, 71, 71, 36, 84, 53, 90, 93, 9, 21, 94, 76, 80, 4, 40, 30],
  [57, 17, 99, 26, 7, 0, 81, 29, 95, 51, 46, 8, 16, 19, 15, 48, 89, 65, 69, 14, 94, 9, 3, 78, 59, 20, 41, 45, 97, 99, 57, 52, 94, 12, 55, 28],
  [19, 49, 58, 20, 73, 65, 0, 72, 82, 12, 64, 43, 34, 58, 11, 74, 20, 75, 0, 23, 6, 25, 81, 39, 44, 65, 54, 57, 72, 72, 10, 69, 31, 10, 45, 20],
  [68, 46, 13, 68, 81, 62, 28, 75, 66, 91, 27, 31, 20, 38, 1, 45, 76, 79, 14, 62, 58, 66, 17, 79, 61, 91, 86, 33, 57, 95, 74, 7, 31, 85, 97, 80],
  [67, 31, 55, 44, 11, 39, 50, 79, 64, 75, 97, 13, 22, 19, 42, 58, 55, 10, 51, 37, 73, 55, 22, 40, 35, 97, 77, 92, 43, 24, 69, 25, 64, 61, 48, 77],
  [7, 17, 84, 29, 87, 12, 85, 22, 65, 70, 73, 14, 32, 9, 27, 3, 11, 42, 88, 20, 37, 10, 88, 77, 68, 92, 71, 80, 83, 32, 35, 85, 91, 52, 26, 73],
  [62, 24, 97, 27, 49, 2, 50, 36, 14, 59, 63, 1, 45, 98, 80, 64, 59, 80, 55, 96, 87, 89, 19, 81, 40, 31, 73, 48, 29, 34, 63, 11, 12, 7, 84, 28],
  [23, 82, 3, 66, 59, 65, 49, 80, 16, 73, 39, 69, 45, 15, 6, 14, 4, 97, 76, 57, 34, 13, 77, 72, 98, 24, 34, 54, 23, 41, 67, 6, 80, 19, 30, 92],
  [20, 35, 58, 63, 21, 75, 58, 8, 30, 44, 97, 21, 3, 86, 78, 89, 93, 42, 29, 89, 53, 17, 89, 6, 8, 14, 48, 98, 15, 58, 28, 46, 51, 55, 17, 78],
  [42, 41, 8, 12, 37, 81, 33, 58, 59, 31, 3, 67, 77, 90, 6, 2, 14, 45, 49, 28, 79, 93, 7, 75, 52, 52, 46, 86, 98, 77, 66, 38, 41, 11, 41, 2],
  [8, 45, 28, 85, 58, 99, 18, 86, 95, 16, 59, 45, 26, 35, 36, 96, 61, 82, 32, 20, 62, 47, 93, 3, 44, 71, 11, 11, 31, 28, 42, 7, 18, 58, 40, 89],
  [87, 4, 99, 46, 73, 27, 7, 44, 26, 62, 15, 10, 14, 77, 97, 70, 58, 23, 85, 73, 76, 97, 6, 92, 52, 51, 9, 84, 29, 56, 15, 38, 41, 7, 88, 76],
  [30, 0, 80, 70, 10, 78, 91, 80, 3, 42, 24, 70, 39, 7, 7, 43, 9, 2, 23, 96, 76, 87, 19, 11, 5, 10, 74, 10, 49, 16, 34, 54, 40, 55, 75, 93],
  [92, 54, 58, 53, 99, 84, 53, 50, 56, 65, 10, 89, 19, 2, 6, 94, 44, 69, 67, 60, 79, 5, 30, 23, 15, 8, 48, 26, 32, 31, 43, 59, 81, 9, 67, 93],
  [7, 58, 97, 4, 22, 36, 5, 83, 32, 69, 83, 54, 18, 48, 49, 43, 36, 37, 96, 0, 28, 18, 64, 56, 52, 97, 43, 95, 36, 8, 48, 35, 60, 41, 48, 81],
  [50, 78, 66, 51, 45, 80, 65, 87, 0, 5, 87, 91, 34, 78, 47, 89, 51, 32, 88, 64, 52, 8, 86, 59, 11, 5, 1, 12, 57, 87, 75, 83, 17, 69, 96, 61],
  [74, 18, 35, 33, 97, 4, 22, 39, 41, 10, 66, 59, 11, 71, 90, 28, 78, 66, 51, 25, 48, 89, 74, 62, 13, 19, 67, 99, 19, 88, 15, 83, 26, 86, 31, 93],
  [93, 32, 27, 13, 61, 53, 49, 35, 59, 13, 54, 68, 75, 31, 18, 79, 33, 59, 87, 86, 14, 26, 21, 19, 12, 59, 75, 36, 7, 71, 25, 25, 6, 85, 29, 99],
  [94, 78, 11, 70, 49, 22, 25, 67, 34, 65, 85, 58, 76, 10, 44, 22, 75, 72, 65, 54, 68, 60, 84, 52, 19, 26, 61, 69, 88, 76, 37, 41, 81, 1, 23, 57],
  [15, 72, 24, 37, 95, 16, 76, 61, 34, 47, 68, 93, 18, 92, 32, 17, 20, 66, 51, 33, 65, 38, 71, 45, 81, 59, 34, 35, 84, 37, 14, 6, 41, 60, 57, 54],
  [83, 86, 73, 77, 75, 67, 5, 92, 43, 13, 98, 92, 69, 80, 50, 25, 64, 0, 64, 25, 98, 40, 66, 77, 4, 18, 52, 50, 28, 36, 17, 54, 5, 83, 2, 40],
  [25, 68, 57, 61, 55, 81, 56, 71, 95, 72, 37, 21, 91, 8, 23, 26, 38, 44, 45, 84, 37, 51, 13, 42, 90, 12, 67, 21, 96, 31, 99, 97, 2, 90, 99, 56],
  [47, 90, 19, 59, 82, 32, 52, 99, 74, 8, 93, 18, 79, 22, 24, 63, 84, 50, 55, 86, 94, 23, 83, 65, 67, 48, 16, 15, 81, 78, 7, 43, 12, 52, 58, 28],
  [54, 39, 86, 53, 24, 55, 72, 2, 6, 15, 78, 8, 35, 70, 59, 80, 74, 99, 95, 32, 44, 26, 47, 49, 48, 14, 95, 66, 54, 76, 37, 81, 85, 37, 45, 7],
  [19, 38, 6, 31, 71, 53, 40, 85, 71, 52, 56, 25, 78, 32, 17, 85, 42, 24, 61, 42, 3, 54, 98, 68, 48, 39, 59, 59, 12, 25, 96, 98, 15, 88, 44, 45],
  [62, 70, 19, 57, 56, 68, 7, 13, 53, 87, 68, 69, 77, 39, 23, 94, 42, 10, 1, 28, 43, 31, 42, 48, 75, 95, 28, 10, 44, 50, 72, 47, 64, 96, 5, 63],
  [92, 85, 77, 92, 90, 27, 39, 57, 51, 41, 99, 78, 78, 53, 88, 59, 30, 65, 15, 25, 32, 32, 99, 64, 90, 40, 13, 45, 41, 73, 98, 12, 44, 73, 33, 32],
  [97, 36, 97, 58, 74, 56, 70, 80, 92, 84, 93, 16, 0, 34, 96, 85, 84, 16, 29, 22, 27, 42, 26, 40, 27, 80, 1, 40, 82, 25, 54, 31, 77, 25, 67, 73],
  [46, 91, 13, 50, 65, 68, 44, 15, 65, 58, 77, 21, 92, 70, 69, 95, 9, 84, 69, 71, 53, 65, 0, 33, 95, 4, 1, 28, 62, 27, 39, 38, 47, 39, 61, 81],
  [37, 0, 70, 66, 14, 20, 50, 68, 8, 0, 62, 41, 68, 35, 14, 69, 94, 62, 53, 84, 32, 22, 80, 81, 22, 66, 36, 65, 40, 53, 93, 0, 0, 33, 32, 7],
  [68, 73, 37, 13, 86, 20, 22, 97, 27, 10, 32, 57, 27, 11, 52, 7, 7, 48, 23, 14, 98, 25, 41, 6, 78, 63, 80, 38, 24, 75, 2, 61, 45, 93, 18, 94],
  [20, 14, 76, 73, 80, 30, 56, 33, 80, 18, 79, 66, 39, 3, 88, 25, 28, 24, 63, 88, 68, 28, 67, 49, 6, 18, 4, 49, 0, 96, 11, 22, 6, 41, 17, 50],
  [9, 61, 45, 7, 25, 86, 99, 39, 79, 13, 46, 74, 44, 3, 90, 43, 25, 9, 2, 27, 13, 15, 38, 98, 2, 88, 13, 51, 44, 80, 67, 85, 84, 40, 2, 68],
  [22, 48, 11, 46, 99, 88, 75, 32, 69, 66, 73, 10, 3, 31, 13, 44, 11, 17, 68, 0, 37, 86, 40, 92, 13, 61, 24, 69, 22, 11, 53, 1, 14, 53, 96, 29],
  [65, 27, 91, 56, 76, 11, 86, 34, 3, 15, 97, 42, 19, 98, 38, 78, 90, 37, 76, 55, 46, 18, 72, 92, 3, 38, 55, 54, 5, 0, 58, 24, 77, 70, 65, 55],
  [33, 48, 21, 34, 42, 60, 82, 33, 98, 27, 51, 33, 74, 55, 59, 96, 44, 35, 23, 28, 13, 52, 72, 9, 39, 52, 8, 30, 40, 8, 97, 43, 79, 89, 38, 80],
  [1, 29, 67, 37, 13, 29, 33, 96, 91, 24, 4, 67, 20, 71, 75, 95, 2, 63, 39, 14, 88, 2, 5, 17, 38, 40, 74, 79, 39, 62, 38, 58, 74, 4, 27, 97],
  [86, 8, 5, 54, 58, 78, 70, 51, 89, 94, 51, 55, 27, 6, 56, 44, 14, 72, 5, 27, 19, 50, 72, 58, 66, 24, 49, 28, 15, 12, 12, 37, 85, 89, 53, 38],
  [54, 1, 82, 23, 72, 55, 6, 96, 54, 22, 19, 63, 83, 50, 39, 75, 33, 29, 83, 14, 60, 92, 62, 83, 11, 34, 53, 77, 57, 63, 18, 17, 50, 9, 90, 36],
  [60, 78, 25, 81, 18, 1, 96, 39, 36, 82, 23, 78, 70, 80, 19, 55, 74, 38, 99, 37, 3, 87, 21, 26, 93, 89, 44, 13, 95, 92, 11, 71, 77, 10, 49, 90],
  [68, 68, 45, 82, 67, 7, 97, 49, 87, 83, 73, 70, 70, 87, 14, 37, 10, 21, 82, 71, 75, 13, 89, 93, 63, 11, 40, 18, 32, 69, 38, 53, 81, 63, 51, 76],
  [25, 36, 27, 62, 4, 51, 50, 74, 19, 10, 78, 94, 15, 49, 11, 26, 91, 80, 61, 80, 84, 87, 80, 52, 35, 28, 64, 91, 39, 58, 15, 55, 26, 72, 68, 35],
  [42, 66, 36, 17, 5, 31, 38, 90, 61, 8, 24, 0, 7, 40, 65, 67, 54, 61, 53, 16, 49, 76, 21, 63, 23, 72, 20, 9, 42, 34, 10, 6, 63, 25, 61, 28],
  [9, 98, 52, 95, 85, 61, 87, 96, 64, 98, 98, 83, 88, 4, 73, 29, 26, 67, 59, 34, 89, 49, 6, 16, 0, 61, 55, 76, 73, 64, 26, 63, 56, 64, 66, 86],
  [98, 2, 10, 34, 9, 10, 8, 46, 2, 95, 89, 65, 49, 1, 38, 15, 8, 22, 66, 80, 7, 77, 77, 70, 1, 7, 60, 59, 93, 7, 2, 98, 31, 95, 87, 18],
  [47, 20, 77, 92, 92, 78, 81, 7, 34, 20, 30, 40, 56, 79, 86, 84, 81, 40, 19, 28, 72, 35, 20, 85, 3, 68, 18, 4, 63, 83, 20, 12, 41, 63, 19, 58],
  [55, 10, 67, 18, 31, 16, 76, 57, 79, 64, 68, 37, 78, 60, 60, 46, 49, 32, 32, 3, 65, 74, 22, 79, 26, 29, 28, 86, 20, 99, 27, 99, 28, 30, 54, 20],
  [73, 87, 66, 32, 10, 75, 40, 94, 30, 99, 52, 10, 33, 33, 52, 36, 16, 90, 68, 62, 19, 33, 50, 22, 78, 47, 91, 22, 84, 83, 41, 17, 32, 83, 38, 23],
  [82, 26, 41, 53, 71, 22, 95, 55, 60, 14, 40, 42, 36, 43, 91, 50, 16, 93, 62, 72, 3, 14, 55, 48, 20, 17, 56, 38, 64, 87, 86, 92, 82, 75, 73, 76],
  [70, 18, 42, 41, 19, 44, 8, 90, 10, 73, 41, 39, 23, 69, 64, 55, 39, 80, 88, 13, 5, 29, 71, 53, 84, 71, 91, 97, 60, 67, 10, 15, 53, 37, 68, 91],
  [12, 99, 93, 43, 63, 51, 54, 89, 39, 8, 19, 27, 70, 94, 0, 70, 76, 1, 51, 30, 60, 88, 24, 69, 35, 36, 97, 43, 0, 70, 21, 84, 19, 6, 93, 92],
  [15, 83, 14, 61, 0, 18, 77, 34, 95, 92, 22, 76, 54, 9, 22, 43, 96, 91, 24, 12, 30, 22, 88, 72, 82, 38, 27, 10, 41, 2, 78, 25, 36, 20, 70, 55],
  [83, 6, 84, 58, 57, 42, 76, 75, 36, 39, 98, 55, 72, 72, 84, 81, 36, 9, 3, 44, 1, 50, 63, 1, 93, 24, 26, 20, 30, 68, 0, 24, 90, 26, 6, 88],
  [58, 38, 65, 42, 40, 25, 32, 39, 19, 31, 74, 36, 85, 74, 23, 20, 37, 41, 41, 63, 61, 9, 27, 39, 22, 0, 36, 34, 53, 53, 6, 40, 81, 18, 86, 8],
  [34, 1, 53, 24, 53, 46, 21, 59, 74, 75, 10, 49, 79, 74, 29, 68, 82, 75, 49, 62, 8, 58, 54, 34, 87, 4, 84, 34, 10, 82, 70, 35, 62, 9, 33, 77],
  [28, 49, 3, 98, 69, 36, 80, 53, 72, 68, 89, 22, 40, 52, 5, 66, 39, 38, 41, 45, 13, 12, 70, 12, 7, 86, 95, 83, 66, 92, 43, 13, 53, 80, 75, 33],
  [98, 98, 88, 3, 11, 32, 83, 24, 91, 79, 3, 55, 50, 95, 41, 69, 30, 89, 68, 47, 13, 35, 0, 86, 57, 8, 10, 31, 1, 40, 81, 2, 87, 10, 73, 0],
  [36, 8, 65, 86, 88, 65, 19, 33, 62, 24, 98, 34, 0, 80, 45, 53, 16, 28, 41, 65, 93, 34, 64, 85, 48, 98, 15, 51, 41, 65, 5, 9, 51, 17, 17, 91],
  [21, 49, 80, 99, 8, 32, 11, 36, 82, 59, 64, 59, 55, 73, 1, 23, 82, 59, 19, 16, 58, 18, 62, 36, 74, 30, 72, 79, 26, 31, 16, 40, 2, 27, 65, 26],
  [86, 24, 59, 75, 93, 17, 20, 42, 21, 4, 80, 0, 57, 91, 81, 84, 95, 13, 65, 85, 9, 15, 26, 90, 66, 20, 13, 98, 67, 27, 85, 49, 45, 65, 10, 84],
  [17, 16, 99, 46, 21, 66, 57, 69, 29, 42, 50, 92, 9, 11, 56, 62, 32, 15, 55, 25, 55, 90, 81, 74, 62, 98, 58, 65, 46, 77, 53, 10, 0, 59, 70, 91],
  [76, 89, 89, 89, 87, 87, 11, 51, 11, 44, 11, 50, 29, 88, 93, 31, 6, 26, 74, 34, 24, 30, 14, 74, 9, 47, 20, 17, 88, 14, 49, 87, 3, 65, 27, 73],
  [18, 18, 68, 23, 13, 98, 52, 92, 72, 75, 8, 8, 2, 33, 69, 23, 22, 16, 95, 76, 43, 83, 86, 27, 4, 58, 57, 97, 64, 22, 43, 32, 41, 2, 88, 26],
  [21, 20, 85, 29, 56, 31, 65, 45, 58, 26, 62, 21, 71, 31, 5, 57, 88, 42, 51, 39, 79, 83, 47, 99, 25, 31, 9, 24, 13, 63, 95, 78, 80, 74, 78, 89],
  [39, 90, 68, 22, 85, 14, 4, 20, 41, 51, 67, 75, 20, 48, 91, 65, 61, 44, 66, 3, 83, 30, 93, 23, 19, 99, 46, 88, 87, 35, 3, 88, 35, 67, 88, 28],
  [63, 21, 64, 10, 7, 38, 25, 17, 32, 36, 7, 99, 46, 65, 74, 71, 63, 42, 30, 72, 29, 80, 42, 65, 27, 24, 16, 16, 70, 2, 54, 60, 35, 79, 88, 39],
  [10, 75, 23, 44, 33, 33, 11, 13, 23, 3, 44, 37, 64, 66, 35, 32, 34, 22, 18, 15, 6, 37, 25, 36, 20, 4, 49, 58, 59, 21, 80, 95, 0, 31, 93, 28],
  [54, 30, 99, 86, 7, 38, 8, 18, 26, 83, 15, 83, 45, 5, 24, 67, 6, 39, 65, 67, 83, 99, 29, 41, 64, 62, 25, 53, 54, 34, 24, 41, 99, 28, 8, 29],
  [30, 60, 67, 20, 43, 56, 79, 43, 92, 85, 69, 9, 62, 22, 62, 24, 68, 33, 18, 61, 25, 14, 21, 59, 86, 59, 53, 26, 1, 80, 9, 36, 4, 5, 85, 47],
  [57, 64, 8, 17, 69, 23, 77, 29, 69, 52, 80, 86, 18, 93, 78, 17, 36, 60, 94, 25, 80, 90, 87, 86, 64, 23, 87, 95, 19, 69, 91, 82, 37, 27, 27, 46],
  [52, 19, 54, 87, 1, 4, 41, 68, 93, 56, 36, 13, 32, 25, 83, 48, 59, 5, 37, 58, 83, 93, 53, 77, 44, 63, 49, 1, 94, 4, 28, 30, 85, 15, 85, 90],
  [75, 72, 89, 33, 98, 23, 81, 41, 35, 17, 4, 1, 46, 60, 83, 69, 27, 35, 33, 83, 61, 61, 21, 72, 82, 72, 82, 6, 59, 51, 60, 37, 82, 20, 88, 54],
  [20, 37, 13, 75, 81, 78, 36, 75, 22, 45, 81, 63, 58, 72, 81, 7, 9, 39, 49, 8, 84, 66, 71, 58, 41, 56, 5, 2, 83, 47, 16, 3, 93, 95, 97, 10],
  [94, 83, 74, 92, 8, 10, 12, 92, 28, 28, 31, 98, 10, 33, 62, 70, 85, 53, 8, 31, 75, 67, 38, 2, 5, 85, 44, 25, 54, 69, 33, 61, 75, 57, 79, 82],
  [60, 34, 79, 9, 2, 28, 80, 24, 2, 76, 26, 34, 61, 22, 40, 31, 52, 14, 30, 2, 88, 54, 41, 73, 6, 45, 13, 22, 70, 51, 74, 69, 19, 66, 33, 78],
  [3, 11, 50, 41, 23, 41, 45, 2, 62, 95, 55, 73, 1, 98, 33, 68, 82, 96, 24, 81, 1, 58, 59, 41, 45, 9, 99, 49, 16, 97, 54, 75, 92, 14, 71, 63],
  [18, 73, 63, 61, 88, 15, 27, 49, 82, 95, 0, 54, 71, 76, 64, 65, 84, 39, 61, 56, 52, 60, 88, 92, 75, 83, 94, 61, 76, 76, 14, 11, 5, 95, 71, 68]
];

data.forEach((e,i) => {
  console.log(solution(e));
});

console.log(numberOfImpossibleCases);

Results:

When I started reading the other solutions I felt a little proud for being the only one using this approach, a little dumb for not coming up with the much simpler approach others used, and extremely stupid because despite my logic being so seemingly correct the result is so wrong... 💀

Apparently there are cases where you can have 3 repeated numbers, such as [5,4,4,3,3,3,2,2,1]. You can make this grid:

[5,4,3],
[4,3,2],
[3,2,1]

But even if I removed the 3 repeated numbers check, I get 86 impossible cases instead of the 45 others mention.

And there is this one: [8, 7, 6, 5, 4, 3, 2, 2, 1], which you should be able to turn into this:

[8,7,5],
[6,4,2],
[3,2,1]

However, according to my algorithm, since two 2s end in the last row it would be impossible because there are no more rows to keep going below. But I should be able to swap it with any number from the row above as long as it belongs to a column that is to the right side 🤔.

let numberOfImpossibleCases = 0;

function solution(numbers) {
  const sorted = numbers.sort((a, b) => b - a);
  const grid = makeGrid(sorted, Math.sqrt(numbers.length));
  let count;
  for(i = 0; i < grid.length; i++) {
    let j = checkRepeatedNumbers(grid[i], 2);
    count = 0;
    while(j !== false) {
      if(!swap(grid, i, j+1, count)) {
        numberOfImpossibleCases++;
        return false;
      }
      j = checkRepeatedNumbers(grid[i], 2);
      count++;
    }
  }
}

function checkRepeatedNumbers(sortedListOfNumbers, quantity) {
  const copy = [...sortedListOfNumbers];
  let index = 0;
  while(copy.length >= quantity) {
    const n1 = copy.shift();
    if(copy.slice(0, quantity - 1).every(n => n == n1)) {
      return index;
    }
    index++;
  }
  return false;
}

function makeGrid(list, size) {
  const grid = [];
  const copy = [...list];
  while(copy.length > 0) {
    grid.push(copy.splice(0, size));
  }
  return grid;
}

function swap(grid, row, column, count) {
  if(column == 1) {
    return false;
  }
  if(row != grid.length - 1) {
    const firstRow = grid[row];
    const secondRow = grid[row + 1];
    const [repeatedNumber] = firstRow.splice(column, 1);
    const [numberFromRowBelow] = secondRow.splice(count, 1, repeatedNumber);
    firstRow.push(numberFromRowBelow);
    return true;
  } else if(row != 0) {
    const firstRow = grid[row];
    const secondRow = grid[row - 1];
    const [repeatedNumber] = firstRow.splice(column - 1, 1);
    const [numberFromRowAbove] = secondRow.splice(column, 1);
    secondRow.push(repeatedNumber);
    firstRow.unshift(numberFromRowAbove);
    return true;
  } else {
    return false;
  }
}

New result: 68 impossible cases. I guess I'm getting closer? ¯\_(ツ)_/¯

79816760
Vote

Hint: a run of equal values is possible if it is not longer than the diagonal in which it starts (if left of the main diagonal) or ends (if to the right):

9 8 7 6
7 6 5 4
6 4 3 2
4 3 2 1

For a 6 x 6 square that longest possible run has length 6 (main diagonal).

79812789
Vote

Below is my submission in R

\(a,d){
a=sort(a, T)
p=c()
for(j in 1:(2*d-1)){
s=d-abs(d-j)
p=rbind(p,c(rep(NA,(j>d)*(d-s)),a[1:s],rep(NA,(j<d)*(d-s))))
a=tail(a,-s)
}
result=apply(p, 2, \(x)x[!is.na(x)])
if(any(c(apply(result, 1, duplicated),apply(result, 2, duplicated)))) return("No solution") else return(result)
}

Attempt This Online!

In the context of this challenge, I prefer the term "ordering" to "sorting" to avoid confusion with the traditional sorting.

I have counted 45 cases of 100 where the ordering was impossible.

Explanation

The solution is a function which inputs an unsorted list and number of rows. It outputs No solution if no ordering was possible or an ordered matrix otherwise.

Firstly, the input list is sorted descendingly.

The main idea is to fill the antidiagonals of the resulting matrix with the sorted list a. To do that, this list is splitted into chunks of size of 1, 2, ... Number_of_rows, ... 1; there will be totally 2 * Number_of rows - 1 antidiagonals (11 for a 6x6 matrix). This is done by padding the chunks with NA's in the for loop.

If, for example, we would like to make an ordered 6×6 matrix containing the sequence 1 to 36, the interim NA-padded result will look as follows:

      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]   36   NA   NA   NA   NA   NA
 [2,]   35   34   NA   NA   NA   NA
 [3,]   33   32   31   NA   NA   NA
 [4,]   30   29   28   27   NA   NA
 [5,]   26   25   24   23   22   NA
 [6,]   21   20   19   18   17   16
 [7,]   NA   15   14   13   12   11
 [8,]   NA   NA   10    9    8    7
 [9,]   NA   NA   NA    6    5    4
[10,]   NA   NA   NA   NA    3    2
[11,]   NA   NA   NA   NA   NA    1

After that the NA's are removed from each column and the matrix regains it's target 6×6 dimensions:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   36   34   31   27   22   16
[2,]   35   32   28   23   17   11
[3,]   33   29   24   18   12    7
[4,]   30   25   19   13    8    4
[5,]   26   20   14    9    5    2
[6,]   21   15   10    6    3    1

Lastly, we are checking whether some repeating numbers are present in any row and column. If this is the case, 0 is returned, otherwise the output is the ordered matrix.

79812726
Vote

I initially thought that this would be some annoying optimization problem, so I wrote a checking function, is_grid_sorted, but then I realized that this is just a matter of adding things in the right order!

If you just go from the top left, filling things in directly adjacent to the existing values, you'll end up with a correctly sorted grid. I then just did this in my initial grid conversion function, and it worked pretty effectively. Basically, you add values in order of each diagonal, and the order along the individual diagonal can often change, but just going in sort order is effective, as I did.

Something interesting I encountered is that pretty much the only time the system failed to sort the numbers into a grid was when there were two identical numbers. Most of the time, it can still sort this, but it can never sort two identical numbers at the front or back of the input.

import math

def to_grid_diagonal(input: list[int]) -> list[list[int]]:
    num_stack = input.copy()
    num_stack.sort(reverse=True)
    side = math.isqrt(len(input))
    grid = [list(range(side)) for _ in range(side)] # Initialize 2d array

    for x0 in range(side*2-1): # Iterate number of diagonals
        x = min(x0, side-1)
        y = max(0, x0-side+1)
        while y <= min(x0, side-1):
            n = num_stack.pop(0)
            # print(x, y )
            grid[x][y] = n
            x -= 1
            y += 1


    return grid


def is_grid_sorted(input: list[list[int]]) -> bool:
    # Row-wise sorted?
    for row in input:
        s = row[0]
        for n in row[1:]:
            if n >= s:
                return False
            s = n

    # Column-wise sorted?
    for i in range(len(input[0])):
        s = input[i][0]
        for j in range(1, len(input)):
            n = input[j][i]
            if n >= s:
                return False
            s = n

    return True


def print_grid(input: list[list[int]]):
    for row in input:
        print(row)

def evaluate():
    with open("RandomNumbers.txt") as f:
        numbers: list[list[int]] = [eval(line) for line in f.readlines()]

    fails = 0
    for input in numbers:
        grid = to_grid_diagonal(input)
        if is_grid_sorted(grid):
            print("SUCCESS")
            print_grid(grid)
        else:
            print("FAIL")
            print(input)
            fails += 1

    print(fails, "total fails")

evaluate()
79812687
Vote

This solution is written in Unison. It relies on the idea of filling the matrix diagonally. I reasoned about this inductively:

* The largest element must certainly be in the top-left corner.
* The next two elements be east and south of it, respectively.
* The next three must be east and/or south of those.
* And so on, diagonally through the matrix.

According to this code, there are 55 test cases in the sample set that have a solution, and 45 that do not.

antiDiagonal : Nat -> Nat -> [a] -> [[a]]
antiDiagonal rows cols xs =
  step acc k = cases
    [] -> acc
    xs
      | k <= cols  -> 
          (pre, suf) = List.splitAt k xs
          step (acc :+ pre) (k + 1) suf
      | otherwise  ->
        step
          (acc :+ take (cols - diff k cols) xs)
          (k + 1)
          (drop (cols - diff k cols) xs)
  antiDiagonals rows cols (step [] 1 xs)

antiDiagonals : Nat -> Nat -> [[a]] -> [[a]]
antiDiagonals rows cols xs =
  step rows diag =
    k = size diag
    (pre, tofill) = List.span (xs -> size xs >= cols) rows
    (prefix, suffix) = List.splitAt k tofill
    filled = List.zipWith (:+) prefix (List.reverse diag)
    pre ++ filled ++ suffix
  List.foldLeft step (List.replicate rows do []) xs

gridSort : Nat -> [Nat] -> Optional [[Nat]]
gridSort n xs = observe do
  diag = antiDiagonal n n (sortWith (>=) xs)
  guard (all (isSortedBy (>)) diag)
  guard (all (isSortedBy (>)) (transpose diag))
  diag

Demo

| > gridSort 3 [95, 75, 75, 74, 74, 74, 54, 45, 40]
    ⧩
    Some [[95, 75, 74], [75, 74, 45], [74, 54, 40]]      

| > map (gridSort 6) testData |> List.count isSome
    ⧩
    55
  
| > take 3 (map (gridSort 6) testData)
    ⧩
    [ None
    , None
    , Some
        [ [99, 91, 82, 73, 63, 44]
        , [95, 84, 75, 65, 53, 24]
        , [91, 80, 68, 55, 34, 14]
        , [81, 71, 59, 41, 16, 7]
        , [73, 60, 42, 16, 13, 6]
        , [61, 42, 18, 14, 6, 0]
        ]
    ]
79812515

This reply has been deleted.

79812709
Vote

Your first example result doesn't satisfy the constraints (3 in the top-right corner).

79812772
Vote

the second one doesn't either (multiple 98's in the first column; 35 in column 3; and more)

79812445
Vote

by sorting numbers and populating a grid 6x6 grid diagonally (or any shape grid for that matter) it is possible to always have numbers in the same row or column be equal or smaller than the one before

  • grid[n][m] >= grid[n+1][m-1] by sorting
  • grid[n][m+1] is only reached when the diagonal where n+m = value is saturated; also due to sorting this means grid[n][m]>=grid[n][m+1]
  • because grid[n][m] >= grid[n][m+1] and grid[n][m+1] >= grid[n+1][m+1-1] (= grid[n+1][m] modified point 1) this means that grid[n][m]>=grid[n+1][m] as well

if in descending grid no numbers of the same value are adjacent this must mean that our grid is strictly descending

# we assume nums is a list of N*2 numbers
def sort_grid(nums):
    gridsize = int(len(nums)**(1/2))
    nums.sort(reverse=True)
    grid = populate_grid(nums, gridsize)
    transposed = [[grid[j][i] for j in range(len(grid))] for i in range(len(grid[0]))]
    if validate_columns(grid, gridsize) and validate_columns(transposed, gridsize):
        return grid
    return None

def populate_grid(nums, GRIDSIZE):
    i=0
    grid = [[None for _ in range(GRIDSIZE)] for _ in range(GRIDSIZE)]
    for diagonal in range(2*GRIDSIZE-1):
        for column in range(diagonal, -1, -1):
            row = diagonal-column
            if column>=GRIDSIZE or row>=GRIDSIZE:
                continue
            grid[column][diagonal-column] = nums[i]
            i+=1
    return grid

def validate_columns(grid, gridsize):
    for i in range(gridsize):
        if any(x<=y for x,y in zip(grid[i][:], grid[i][1:])):
            return False
    return True


valid, invalid = 0, 0
with open('input.txt','r') as f:
    for line in f.readlines():
        nums = eval(line)
        sorted = sort_grid(nums)
        if not sorted:
            print(f"invalid for {nums}")
            invalid += 1
        else:
            print(sorted)
            valid += 1

print(f'{valid=} / {invalid=}')

out: valid=55 / invalid=45

(sorted grids omitted for brevity)

79812417
Vote

To solve the problem, we should sort the array

[item1, item2, ... itemN-1, itemN]

and then place into matrix diagonally

  ItemN   ItemN-1 ItemN-3 ...
  ItemN-2 Item-4 ...
  ItemN-5 ...
  ...                           Item3
                          Item2 Item1  

while checking for ties: Matrix[r][c] > Matrix[r - 1][c] and Matrix[r][c] > Matrix[r][c - 1].

Possible C# code can be

public sealed class SortChallenge {
  public static bool TrySort(IEnumerable<int>? items, out int[][] result){
    result = [];

    if (items is null) return false;

    if (items is not IReadOnlyList<int> data)
      data = items.ToList();

    var count = IntSquare(data.Count);

    if (count < 0) return false;

    if (data.Count == 0) return true;

    result = Enumerable
      .Range(0, count)
      .Select(_ => new int[count])
      .ToArray();

    int col = 0, row = 0;

    foreach (var item in data.OrderByDescending(item => item)) {
      result[row][col] = item;

      if (row > 0 && item >= result[row - 1][col] || col > 0 && item >= result[row][col - 1]){
        result = [];

        return false;
      }

      (col, row) = row == count - 1 ? (count - 1, col + 1)
        : col == 0 ? (row + 1, 0)
        : (col - 1, row + 1);
    }

    return true;
  }

  private static int IntSquare(int value) {
    var result = (int)Math.Sqrt(value + 0.1);

    return result * result == value ? result : -1;
  }
}

Fiddle

Demo:

int[] data = [1, 2, 5, 7, 8, 4, 9, 6, 3];

var report = SortChallenge.TrySort(data, out var solution)
  ? string.Join(Environment.NewLine, solution.Select(line => string.Join(" ", line)))
  : "No Solutions";

Console.WriteLine(report);

Output:

9 8 6
7 5 3
4 2 1

If we have a file, e.g. RandomNumbers.txt we can do as follow:

static string ToReport(int[][] result) => string.Join(Environment.NewLine, result
  .Select(line => string.Join(" ", line.Select(item => $"{item,2}"))));

var result = File
  .ReadLines(@"C:\Work\Data\RandomNumbers.txt")
  .Where(line => !string.IsNullOrWhiteSpace(line))
  .Select(line => Regex.Matches(line, "-?[0-9]+").Select(match => int.Parse(match.Value)).ToArray())
  .Select(items => SortChallenge.TrySort(items, out var matrix) ? matrix : null)
  .Select((matrix, index) => matrix is null ? $"Problem #{index + 1} has no solutions"           : $"Problem #{index + 1} {Environment.NewLine}{ToReport(matrix)}");

Console.WriteLine(string.Join(Environment.NewLine + Environment.NewLine, result));

The output will be

Problem #1 has no solutions

Problem #2 has no solutions

Problem #3 
99 95 91 81 73 61
91 84 80 71 60 42
82 75 68 59 42 18
73 65 55 41 16 14
63 53 34 16 13  6
44 24 14  7  6  0

Problem #4 
99 94 86 74 63 56
88 83 73 62 52 36
81 71 61 50 35 24
70 59 48 29 20 10
57 40 27 19  9  6
40 27 13  8  3  1

Problem #5 
99 97 89 85 78 65
96 88 81 78 60 46
85 80 76 52 45 35
78 75 52 43 32 27
71 48 41 31 26 21
48 37 31 22 14  5

Problem #6 has no solutions
...
Problem #97 
98 94 92 83 75 62
92 85 82 74 61 38
85 79 70 57 33 28
75 69 54 33 28 10
67 53 31 25 10  8
44 31 12  8  5  2

Problem #98 has no solutions

Problem #99 has no solutions

Problem #100 has no solutions
79812645
Vote
Author

What's your total count of solvable and unsolvable problems? Thanks!

79813146
Vote

In total we have 55 solvable and 45 unsolvable problems.

79812413
Vote

Python, 227 bytes

def c(a):
	a.sort();h=0.5;b=[[0]*6for i in range(6)];s=lambda k:(m:=int((k*2+h*h)**h-h),k-m*-~m//2)
	for k in range(36):m,n=s(k);o,p=s(35-k);q,r=k<18and(n,m-n)or(5-p,5-o+p);b[q][r]=a[~k]
	return all(len({*i})>5 for i in b)and b

Attempt This Online!

Explanation

This arranges the numbers along the anti-diagonals diagonals of the square like this:

1 3 6
2 5
4

etc. This should always output a valid solution if it exists.[citation needed]

We then check if every row contains all unique elements. Since rows tie before columns this should ensure only valid solutions pass. This will only happen if the number of ties > the diagonal length.

Using this method, 45 of the test cases have no solution.

The test cases being randomly generated means ties are very unlikely and a much simpler algorithm could probably solve them, but this one should be more correct.

79812841
Vote

This is not codegolf. It's ok to make the code more readable.

79812385
Vote

There were 100 sets of numbers in the provided file, of which 45 where impossible. The hardest part about the challenge was to figure out a logical way to cull out any impossible sets without needing brute force, since the latter is, with 36! possible boards to check, infeasible. So I had to add a number of checks to isDefinitelyImpossible(...) to rule out impossible sets early on (In the end, none of the input sets required going through the brute force function - they where either impossible and could be culled, or trivial to fill.

For calculating (a) solution to the possible sets, I opted on using a diagonal filling algorithm, which starts with the bottom right corner and takes it from there:

|-----------------|
|36|34|31|27|22|16|
|35|32|28|23|17|11|
|33|29|24|18|12|07|
|30|25|19|13|08|04|
|26|20|14|09|05|02|
|21|15|10|06|03|01|
-------------------

Since the number array is sorted immedately after parsing, this means that numbers occuring multiple times have a pretty much guranteed chance of making it into spots where they do not collide.

Code:


package com.stackoverflow.challenges;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Challenge13 {

    /**
     * Main Entry point for the challenge program. Must be called with a single
     * argument that points to the data file in the file system.
     *
     * {@link https://stackoverflow.com/beta/challenges/79811869/challenge-13-integer-sorting-in-a-grid Challenge Post}
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Error: Expected ONE file path as an argument ");
            System.exit(1);
            return;
        }
        Path dataFile;
        try {
            dataFile = Path.of(args[0]);
        } catch (InvalidPathException e) {
            System.err.println("Error: Invalid path argument:  " + args[0]);
            e.printStackTrace(System.err);
            System.exit(1);
            return;
        }
        System.out.println("Stack Overflow Code Challenge 13");
        System.out.println("https://stackoverflow.com/beta/challenges/79811869/challenge-13-integer-sorting-in-a-grid");

        try (BufferedReader inputReader = Files.newBufferedReader(dataFile)) {
            proccessFile(inputReader);
        } catch (IOException ex) {
            System.err.println("Error: File was not readable:");
            ex.printStackTrace(System.err);
            System.exit(1);
        } catch (NumberFormatException nfe){
            System.err.println("Error: file contained a non-integer");
            nfe.printStackTrace(System.err);
            System.exit(1);
        }
    }

    /**
     * Process a datafile.
     *
     * @param inputReader reader the data is read from
     * @throws IOException if an I/O error occurs
     */
    private static void proccessFile(BufferedReader inputReader) throws IOException {
        int setsCount = 0, invalidSets = 0, method1Sets = 0, method2Sets = 0;
        ArrayList<String> impossibleSets = new ArrayList<>();
        String line;
        while ((line = inputReader.readLine()) != null) {
            int[] digits = parseDataSet(line);
            setsCount++;
            System.out.println("Set " + setsCount + " (" + Arrays.toString(digits) + ")");
            if (isDefinitelyImpossible(digits)) {
                System.out.println("is impossible");
                invalidSets++;
                impossibleSets.add("" + setsCount);
                continue;
            }
            boolean solved1 = stategicPlace(digits);
            if (solved1) {
                method1Sets++;
                continue;
            }
            boolean solved2 = bruteforcePlace(digits);
            if (solved2) {
                method2Sets++;
            } else {
                invalidSets++;
                impossibleSets.add("" + setsCount);
                System.out.println("Set " + setsCount + " is impossible.");
            }
        }

        System.out.println("Checked " + setsCount + " sets, invalid: " + invalidSets + " (" + (invalidSets * 1.0 / setsCount * 100) + "%)");
        System.out.println("Sets needing brute force: " + method2Sets);
        System.out.println("Impossible sets:" + impossibleSets.toString());
    }

    /**
     * Parse a dataset (a single line).
     *
     * @param line the line to parse
     * @return array of integers, sorted ascending.
     */
    private static int[] parseDataSet(String line) {
        String[] values = line.substring(1, line.length() - 1).split(",");
        if (values.length != 36) {
            throw new IllegalArgumentException("line has unexpected data length: " + values.length + "(" + Arrays.toString(values) + ")");
        }
        int[] result = new int[36];
        for (int i = 0; i < values.length; i++) {
            result[i] = Integer.parseInt(values[i].trim());
        }
        Arrays.sort(result);
        return result;
    }

    /**
     * Attempt a stategic placement of the given digits. This method is not
     * guranteed to suceed.
     *
     * @param numbers digits array, sorted ascending
     * @return true if this method found a solution, false otherwise
     */
    private static boolean stategicPlace(int[] numbers) {
        int[][] grid = new int[6][6];
        int index = 0;
        for (int i = 10; i >= 0; i--) {
            for (int j = 5; j >= 0; j--) {
                int finalX = i - j;
                /*
                Note: due to the way we fill,
                some iterations will have nothing to do
                as that index doesn't exist.
                so continue here if that is the case.
                */
                if (finalX > 5 || finalX < 0) {
                    continue;
                }
                grid[finalX][j] = numbers[index++];
            }
        }
        boolean foundSolution = checkGrid(grid);
        if (foundSolution) {
            System.out.println("Found a solution: " + Arrays.deepToString(grid));
        }
        return foundSolution;
    }

    /**
     * Check wether a grid, is correct.
     * the grid may contain -2 in places the number logically hasn't been set yet.
     *
     * @param grid grid to check.
     * @return true if the grid is correct, false otherwise.
     */
    private static boolean checkGrid(int[][] grid) {
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                //note: we might be partial if called from the brute force search.
                if (i > 0 && grid[i - 1][j] <= grid[i][j] 
                        && grid[i][j] != -2) {
                    return false;
                }
                if (j > 0 && grid[i][j - 1] <= grid[i][j] 
                        && grid[i][j] != -2) {
                    return false;
                }
            }

        }
        return true;
    }

    private static boolean bruteforcePlace(int[] numbers) {
        int[][] grid = new int[6][6];
        //fill with an invalid element for checkGrid to ignore values that haven't been set
        for(int i = 0; i < 6; i++){
            Arrays.fill(grid[i], -2);
        }
        if (bruteforcePlace0(numbers, grid, 0, 0)) {
            System.out.println("Found a solution: " + Arrays.deepToString(grid));
            return true;
        }
        return false;
    }

    private static boolean bruteforcePlace0(int[] numbers, int[][] grid, int x, int y) {
        if (x == 6 && y == 0) {
            return checkGrid(grid);
        }
        for (int i = numbers.length - 1; i >= 0; i--) {
            if (numbers[i] == -1) {
                //this number is taken by a different invocation of this method lower on the stack
                continue;
            }

            grid[x][y] = numbers[i];
            numbers[i] = -1;

            int newY = y + 1;
            int newX = x;
            if (newY > 5) {
                newY = 0;
                newX += 1;
            }
            /*
             * don't bother with the (potentially heavy, if we are low 
            on the stack) recursion if the grid check says its impossible anyway
             */
            if (checkGrid(grid) && bruteforcePlace0(numbers, grid, newX, newY)) {
                //if we get back true, we found a solution. leave everything as it is and return true.
                return true;
            }
            //undo...
            numbers[i] = grid[x][y];
            grid[x][y] = -2;
        }
        //no solution
        return false;
    }

    /**
     * Check for some things that render the given set of numbers definitely
     * impossible. A return value of false from this method does not gurantee it
     * is possible.
     *
     * @param numbers the set of numbers, sorted.
     * @return true if the set is definitely impossible, false if there may or
     * may not be a solution.
     */
    private static boolean isDefinitelyImpossible(int[] numbers) {
        if (numbers[0] == numbers[1]) {
            return true;
        }
        if (numbers[numbers.length - 1] == numbers[numbers.length - 2]) {
            return true;
        }
        Map<Integer, Long> occurences = Arrays.stream(numbers).boxed()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        //reject if more than one number with 6 occurences (which needs to go on the long diagonal)
        int sixCount = 0;
        for (Long occurence : occurences.values()) {
            if (occurence > 6) {
                return true;
            } else if (occurence == 6) {
                sixCount++;
            }
        }
        if (sixCount > 1) {
            return true;
        }
        /* check for occureence edge cases: the lowest & highest 5 numbers are limited in appeareance*/
        int[] distinct = Arrays.stream(numbers).distinct().sorted()
                .toArray();
        //we need 11 distinct numbers
        if (distinct.length < 11) {
            return true;
        }
        //check for too many extreme values
        if (occurences.get(distinct[1]) > 2 
                || occurences.get(distinct[distinct.length - 2]) > 2) {
            return true;
        }
        if (occurences.get(distinct[2]) > 3 
                || occurences.get(distinct[distinct.length - 3]) > 3) {
            return true;
        }
        if (occurences.get(distinct[3]) > 4 
                || occurences.get(distinct[distinct.length - 4]) > 4) {
            return true;
        }
        if (occurences.get(distinct[4]) > 5 
                || occurences.get(distinct[distinct.length - 5]) > 5) {
            return true;
        }
        //if one of the lowest/highest 6 values is at its cap, the previous ones must be too
        if (occurences.get(distinct[2]) == 3 
                && occurences.get(distinct[1]) != 2) {
            return true;
        }
        if (occurences.get(distinct[3]) == 4 
                && occurences.get(distinct[2]) != 3) {
            return true;
        }
        if (occurences.get(distinct[4]) == 5 
                && occurences.get(distinct[3]) != 4) {
            return true;
        }
        if (occurences.get(distinct[5]) == 6 
                && occurences.get(distinct[1]) != 5) {
            return true;
        }

        if (occurences.get(distinct[distinct.length - 3]) == 3 
                && occurences.get(distinct[distinct.length - 2]) != 2) {
            return true;
        }
        if (occurences.get(distinct[distinct.length - 4]) == 4 
                && occurences.get(distinct[distinct.length - 3]) != 3) {
            return true;
        }
        if (occurences.get(distinct[distinct.length - 5]) == 5 
                && occurences.get(distinct[distinct.length - 4]) != 4) {
            return true;
        }
        if (occurences.get(distinct[distinct.length - 6]) == 6 
                && occurences.get(distinct[distinct.length - 5]) != 5) {
            return true;
        }

        return false;

    }

}

the impossible sets are 1, 2, 6, 7, 8, 11, 12, 13, 16, 17, 19, 21, 23, 24, 25, 26, 28, 33, 38, 44, 45, 48, 50, 51, 52, 53, 56, 59, 61, 67, 68, 69, 70, 71, 74, 80, 81, 85, 86, 88, 91, 94, 98, 99 and 100.

Edited Nov 14: Seems like I still have stuff to do. I've adapted the concept by DarthGizka to get the 34,359,738,368 interesting input variants to check wether the my grid placement and the isDefinitelyImpossible(...) function line up and they don't, in both ways. To give examples, isDefinitelyImpossible declares [0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 10] an impossible imput, even though we have the following grid:

[[10, 9, 8, 7, 6, 5],
 [ 9, 8, 7, 6, 5, 4],
 [ 8, 7, 6, 5, 4, 3],
 [ 7, 6, 5, 4, 3, 2],
 [ 6, 5, 4, 3, 2, 1],
 [ 5, 4, 3, 2, 1, 0]]

And it doesn't yet cull [0, 1, 1, 2, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 10, 11, 12, 13] even though that would result in the follwing (non-valid) grid:

[[13, 11, 9, 8, 7, 6],
 [12,  9, 8, 7, 6, 5],
 [10,  8, 7, 6, 5, 4],
 [ 8,  7, 6, 5, 4, 2],
 [ 8,  6, 5, 4, 3, 1],
 [ 7,  6, 5, 4, 1, 0]]

Perhaps I can speed up the testing code somehat too, currently running ~65 minutes for all 34.3 billion cases.

79820652
Vote

After some digging, I discovered the false-positives were a typo (thankfully without affecting the results for the 100 sample inputs, a testament of their quality). Filtering out the false-negatives was more work (especially given that at the current optimization, I have to wait ~ 65 minutes each time). In the end, I settled upon using the check for the number of larger (smaller) numbers DarthGizka mentioned in point 2 of this reply to someone else, resulting in the follwing code for isDefinitelyImpossible(...):

    private static boolean isDefinitelyImpossible(int[] numbers) {
        if (numbers[0] == numbers[1]) {
            return true;
        }
        if (numbers[numbers.length - 1] == numbers[numbers.length - 2]) {
            return true;
        }
        Map<Integer, Long> occurences = Arrays.stream(numbers).boxed()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        //reject if more than one number with 6 occurences (which needs to go on the long diagonal)
        int sixCount = 0;
        for (Long occurence : occurences.values()) {
            if (occurence > 6) {
                return true;
            } else if (occurence == 6) {
                sixCount++;
            }
        }
        if (sixCount > 1) {
            return true;
        }
        /* check for occureence edge cases: the lowest & highest 5 numbers are limited in appeareance*/
        int[] distinct = Arrays.stream(numbers).distinct().sorted()
                .toArray();
        //we need 11 distinct numbers
        if (distinct.length < 11) {
            return true;
        }
        //check for too many extreme values
        if (occurences.get(distinct[1]) > 2
                || occurences.get(distinct[distinct.length - 2]) > 2) {
            return true;
        }
        if (occurences.get(distinct[2]) > 3
                || occurences.get(distinct[distinct.length - 3]) > 3) {
            return true;
        }
        if (occurences.get(distinct[3]) > 4
                || occurences.get(distinct[distinct.length - 4]) > 4) {
            return true;
        }
        if (occurences.get(distinct[4]) > 5
                || occurences.get(distinct[distinct.length - 5]) > 5) {
            return true;
        }
        //if we have a number occuring six times, it needs to start at pos 16 (1-based) of the sorted number array.
        if(sixCount != 0 && occurences.get(numbers[15]) != 6){
            return true;
        }
        if(sixCount != 0 && numbers[15] == numbers[14]){
            return true;
        }
        // numbers occuring a certain number of times need to occur no sooner than specific ofsets in the sorted array
        // and no later than a certain index, too
        int[] occureencesMin = new int[]{0 , 0, 1,3 ,6 ,10,15};
        int[] occurrencesMax = new int[]{35,35,34,32,29,25,20};
        for(int i:occurences.keySet()){
            int firstIndex = indexOf(numbers, i);
            int lastIndex = lastIndexOf(numbers, i);
            //note: just downcast to int, if it been larger we'd returned already.
            if(firstIndex < occureencesMin[occurences.get(i).intValue()]){
                return true;
            }
            if(lastIndex > occurrencesMax[occurences.get(i).intValue()]){
                return true;
            }
        }
        return false;
    }

From a first run that one seems to filter out all impossible cases perfectly. Still need to work on optimising the check code to run a little less time, because ~ 65 minutes each time (~ 8.465.074,7 input arrays per second), while not bad, is still a very long time. I can't increase the paralelism (because I'm already using all but one logical core, and I don't want to use all of them which would leave me with no core to do an emegency stop if needed), but I probbably can tinker the number of ExecutorService tasks I create (because the worker threads run uneven, with most finishing at around the 2700 to 3100 seconds mark and only one going the full distance) and perhaps I can even find a way to speed up the variant of stategicPlace(...) the test code uses (which is mostly self-time) or the java.util.concurrent.Stream stuff in isDefinitelyImpossible(...) (which is the other big timesink)

79820763
Vote

Kudos for verifying the validity of your algorithm instead of simply assuming an intuition to be correct because it successfully deals with the 100 input vectors included in the challenge (whose quality I have discussed elsewhere).

More kudos for not being intimated by the huge numbers of possibilities and instead dealing with it by applying superior firepower. :-)

However, I have the nagging feeling that the frequency counting approach is inherently more complex and difficult than the alternative - simply assigning the sorted input values to a matrix and checking for rule conformance. This may often involve more tests than the frequency counting method but the structure of these tests is brutally simple (value comparison vs neighbours) and their number is fixed (60 in the simplest case, reducible to 30 with a bit of mathematical reasoning).

When I first attacked the challenge I also opted for frequency counting, which appealed to me because it removes the need for sorting altogether. However, I quickly realised several things.

  1. Frequency counting may remove the need for sorting but it leaves you with a sparse array that contains mostly zeroes that you have to skip over to find the occupied entries. Of the 100 entries in the frequency table, at least 64 must remain empty because there are only 36 values total in any input vector. So the simple approach to frequency counting would already consume more computing firepower than simply sorting the tiny input vector if you consider that you have to find the non-empty frequency table entries in order to use them. This problem could be mitigated by using sophisticated (read: complicated) data structures, but I hate complicated. Besides, pretty much every high-level programming language comes with a sorting facility built in.

  2. Utilising the data produced by frequency counting in order to check the viability ('sortability') of an input vector makes it necessary to track the current position in the array, in order to find out in which diagonal the current run of equal values starts. This can be done simply by summing the lengths of the runs already processed. This position can then be used to look up the maximal length of a run of equal values starting at that position, for the viability check.

  3. Using a lookup table to find the maximum length of a run of equal values that starts in a given position is less complex/complicated overall than doing the reasoning inline with if statements.

In the end I abandoned this approach because it involves more work than the strategy I posted (sorting + 35 direct viability checks via the left-neighbour rule, 5 of which are redundant).

Moreover, while the table for the maximum run lengths can easily be worked out with pencil and paper, proving its correctness - mathematically or computationally - is more involved than proving the correctness of the left-neighbour rule. The correctness of the diagonal non-increasing assignment strategy needs to be proved in either case.

Ancillary observation #1: the input vectors are small and fixed in size, which means that the asymptotic complexity of a sorting algorithm is basically irrelevant. What counts is the actual work performed when sorting 36 values, which means that simple algorithms like shaker sort may actually be more suitable than heavier algorithms with lower asymptotic complexity.

However, the input vectors that come with the challenge are so small and few in number that there is no problem at all if we wheel a heavy cannon like a library sort function (or a LINQ/stream sort) to the front line. And for exhaustive tests we can avoid sorting altogether by enumerating the possibilities in a sorted fashion.

Verifying the correctness of the run length matrix is easy if a function is available that checks whether a sorted 36-element vector has a rule-conforming matrix assignment or not (i.e. either by performing the assignment to a 6 x 6 matrix and then checking the matrix for rule conformance, or by treating the sorted vector as 'diagonal-major' storage form of the matrix and checking it directly, as in my solution).

The verification can be done by performing the following steps for each of the possible positions from 0 to 35:

  1. fill cells from 0 to position - 1 with descending values starting at 99

  2. fill the next run_length = MAX_RUN[position] cells with the value 50

  3. fill the remaining cells with values descending to 0 (e.g. 35 - i)

  4. verify that the vector gets accepted

  5. make the run longer by 1 (assign 50 @ position + run_length)

  6. verify that the vector gets rejected

Example for the main diagonal (before the run is made too long by 1):

99 98 96 93 89 50
97 95 92 88 50 14
94 91 87 50 13  9
90 86 50 12  8  5
85 50 11  7  4  2
50 10  6  3  1  0
79812257
Vote

What is probably the easiest way is to:

1/ Sort the 36 numbers in descending order [n1 (biggest), n2, ..., n36 (smallest)].

2/ Fill the matrix following the anti-diagonals, starting in the top-left corner

n1 n3 n6
n2 n5 ...
n4 n8
n7

This will ensure that each row and column are descendingly sorted (but there might be ties)

3/ check for ties

% RandomNumbers is an array containing the data in the file 
out = cell(size(RandomNumbers, 1),1);
out_imp = 0;

for n = 1:size(RandomNumbers, 1)
    
    out_mtx = zeros(6,6);
    idx = 1;
    nums = sort(RandomNumbers(n,:),'descend');

    % loop on the sum of (i, j) indexes (anti diagonals are at constant sum of indexes)
    for s = 2:12

        for ii = (s-1):-1:1

            jj = s-ii;
            if jj<=6 && ii<=6

                out_mtx(ii,jj) = nums(idx);
                idx = idx+1;

            end           

        end

    end

    % check for ties in adjacent numbers horizontaly
    % equivalent to checking if there is any zero when substracting the
    % columns 2...6 to the columns 1..5
    h_mtx = out_mtx(:,1:5)-out_mtx(:,2:6);
    v_mtx = out_mtx(1:5,:)-out_mtx(2:6,:);
    if any(h_mtx(:)==0) || any(v_mtx(:)==0)

        out_mtx = [];
        out_imp = out_imp + 1;

    end

    out{n} = out_mtx;

end
ans =

     []


ans =

     []


ans =

    99    91    82    73    63    44
    95    84    75    65    53    24
    91    80    68    55    34    14
    81    71    59    41    16     7
    73    60    42    16    13     6
    61    42    18    14     6     0


ans =

    99    88    81    70    57    40
    94    83    71    59    40    27
    86    73    61    48    27    13
    74    62    50    29    19     8
    63    52    35    20     9     3
    56    36    24    10     6     1


ans =

    99    96    85    78    71    48
    97    88    80    75    48    37
    89    81    76    52    41    31
    85    78    52    43    31    22
    78    60    45    32    26    14
    65    46    35    27    21     5


ans =

     []


ans =

     []


ans =

     []


ans =

    98    89    80    71    60    48
    94    80    72    64    55    31
    83    78    65    56    37    22
    79    66    57    39    23    10
    67    58    42    29    16     9
    59    44    30    18     9     4


ans =

    99    88    82    79    64    52
    97    86    79    64    54    41
    88    81    66    56    42    11
    81    68    58    48    15     5
    71    63    50    35     9     2
    63    51    38    11     3     0


ans =

     []


ans =

     []


ans =

     []


ans =

    98    93    82    70    58    38
    96    90    73    65    41    19
    91    74    66    49    21    14
    82    66    54    28    16    10
    68    55    31    16    12     4
    56    32    19    12    10     3


ans =

    94    84    79    71    65    56
    85    79    73    66    56    35
    81    74    69    57    39    26
    77    69    57    46    31    13
    71    57    46    31    14     1
    61    47    32    24    12     0


ans =

     []


ans =

     []


ans =

    97    95    90    62    48    40
    95    91    64    49    41    25
    92    67    49    42    29    16
    76    58    44    38    16    13
    59    46    39    22    14    10
    47    39    23    16    10     0


ans =

     []


ans =

    99    96    87    77    71    40
    97    87    80    73    44    25
    92    82    73    51    28    23
    86    74    59    31    24    15
    77    63    34    25    15    13
    63    34    25    19    14    12


ans =

     []


ans =

    92    89    76    56    47    33
    90    77    62    49    35    23
    80    71    50    38    24     6
    74    54    38    24     7     2
    55    40    27     8     3     1
    47    29    16     5     1     0


ans =

     []


ans =

     []


ans =

     []


ans =

     []


ans =

    97    91    85    79    68    58
    95    86    79    68    61    33
    91    80    74    62    38    27
    81    75    62    45    28    14
    76    66    46    31    17     7
    66    57    31    20    13     1


ans =

     []


ans =

    92    88    85    80    70    35
    91    87    83    71    37    26
    88    84    73    42    27    14
    85    73    52    29    17    10
    77    65    32    20    11     7
    68    32    22    12     9     3


ans =

    98    96    84    73    59    45
    97    87    80    62    48    29
    89    80    63    49    31    19
    81    63    50    34    24    11
    64    55    36    27    12     2
    59    40    28    14     7     1


ans =

    98    92    80    72    59    39
    97    80    73    65    41    23
    82    76    66    45    24    15
    77    67    49    30    16     6
    69    54    34    19    13     4
    57    34    23    14     6     3


ans =

    98    93    89    75    55    42
    97    89    78    58    44    21
    89    78    58    46    28    17
    86    58    48    29    17     8
    63    51    30    20    14     6
    53    35    21    15     8     3


ans =

     []


ans =

    99    95    86    62    47    36
    96    89    71    58    40    28
    93    82    58    42    28    18
    85    59    44    31    18    11
    61    45    32    20    11     7
    45    35    26    16     8     3


ans =

    99    97    87    76    62    44
    97    88    77    70    46    26
    92    84    73    51    27    14
    85    73    52    29    15     7
    76    56    38    15     9     6
    58    41    23    10     7     4


ans =

    96    91    80    74    49    30
    93    80    75    54    34    11
    87    76    55    39    16     9
    78    70    40    19    10     5
    70    42    23    10     7     2
    43    24    10     7     3     0


ans =

    99    93    84    67    58    48
    94    89    69    59    50    30
    92    79    60    53    31    15
    81    65    53    32    19     8
    67    54    43    23     9     5
    56    44    26    10     6     2


ans =

     []


ans =

    96    89    87    80    66    52
    91    87    83    69    57    45
    88    86    75    59    47    12
    87    78    61    50    17     5
    78    64    51    32     8     1
    65    51    34    11     5     0


ans =

    99    93    88    74    66    39
    97    89    78    66    41    26
    90    83    67    48    28    19
    86    71    51    31    19    13
    74    59    33    22    15    10
    62    35    25    18    11     4


ans =

    99    87    79    68    54    32
    93    85    71    59    33    25
    86    75    59    35    26    18
    75    59    36    27    19    13
    61    49    29    21    13     7
    53    31    25    14    12     6


ans =

    94    85    78    72    65    54
    88    81    75    67    57    37
    84    76    68    58    41    23
    76    69    60    44    25    19
    70    61    49    26    22    10
    65    52    34    22    11     1


ans =

    95    92    76    66    57    38
    93    81    68    59    41    34
    84    71    60    45    34    20
    72    61    47    35    24    16
    65    51    37    32    17    14
    54    37    33    18    15     6


ans =

     []


ans =

     []


ans =

    99    93    84    79    63    50
    94    86    81    65    52    28
    90    82    67    52    32    19
    83    74    55    43    22    15
    78    58    47    23    16     8
    59    48    24    18    12     7


ans =

    99    95    81    74    55    47
    95    85    76    59    48    37
    86    78    66    49    37    24
    80    70    53    39    26     8
    72    54    44    32    14     6
    54    45    35    15     7     2


ans =

     []


ans =

    96    94    75    68    57    44
    95    77    69    62    47    31
    87    70    63    48    39    19
    72    64    50    42    23    10
    68    53    42    28    10     5
    56    43    28    13     7     1


ans =

     []


ans =

     []


ans =

     []


ans =

     []


ans =

    98    94    80    68    48    27
    97    86    73    52    32    22
    93    75    57    37    23    13
    78    61    38    24    14     7
    63    41    25    18    10     6
    45    27    20    11     7     2


ans =

    96    88    79    67    49    28
    88    80    68    50    30    20
    80    73    56    33    22    14
    76    63    39    24    17     6
    66    41    25    18     6     3
    49    28    18    11     4     0


ans =

     []


ans =

    99    92    75    68    48    31
    96    86    69    53    32    17
    88    69    53    37    22    11
    73    61    40    22    13    10
    66    44    24    13    11     1
    46    29    14    11     3     0


ans =

    98    92    86    76    58    46
    97    90    76    65    54    34
    91    77    65    55    37    18
    78    70    55    38    19     5
    72    55    38    24    11     3
    56    42    27    15     3     0


ans =

     []


ans =

    97    95    79    71    58    37
    96    88    74    62    38    24
    91    74    63    38    27    13
    75    67    39    29    14     4
    67    39    29    17     4     2
    40    33    20     5     2     1


ans =

     []


ans =

    96    90    83    72    57    50
    92    83    75    60    50    29
    83    77    62    53    33    18
    82    63    54    34    19    11
    63    54    36    22    14     6
    55    39    23    17     9     1


ans =

    99    95    90    81    74    44
    96    92    82    77    49    26
    93    87    78    55    36    19
    89    78    60    37    21    11
    80    70    38    23    13     3
    71    39    25    18    10     1


ans =

    97    89    83    76    70    63
    93    87    81    70    63    40
    87    82    71    67    45    21
    82    73    68    49    32    13
    75    68    51    37    14    10
    69    53    38    18    11     7


ans =

    94    91    80    74    61    49
    91    84    78    62    50    28
    87    80    64    51    35    25
    80    68    52    35    26    15
    72    55    36    26    15    10
    58    39    27    19    11     4


ans =

    90    72    65    61    42    31
    76    66    61    49    34    21
    67    63    53    36    23    10
    63    54    38    24    16     7
    61    40    25    17     8     5
    42    28    20     9     6     0


ans =

     []


ans =

     []


ans =

     []


ans =

     []


ans =

     []


ans =

    95    92    86    75    62    50
    93    87    76    64    53    40
    91    82    71    55    41    22
    82    72    55    42    26    16
    73    56    43    36    17    14
    60    48    38    20    14     3


ans =

    97    91    84    71    64    42
    91    88    71    67    44    37
    90    73    68    53    39    18
    80    69    53    39    19    10
    70    55    41    23    13     8
    60    41    29    15    10     5


ans =

     []


ans =

    96    92    83    76    54    30
    95    88    77    55    34    22
    91    78    61    36    22    15
    82    70    38    24    18    10
    72    41    25    20    12     2
    43    27    22    14     9     0


ans =

    98    90    84    75    58    39
    93    84    76    63    42    26
    88    81    68    44    26     9
    83    72    50    30    20     3
    72    55    36    24     6     1
    57    36    24     6     1     0


ans =

    86    81    65    53    40    36
    85    74    58    41    37    27
    74    61    41    38    31    20
    63    42    39    32    22     9
    53    39    34    23    18     6
    40    36    25    19     8     0


ans =

    87    82    77    74    59    49
    84    79    74    62    49    34
    82    75    62    53    34    21
    75    68    53    34    24     9
    70    54    35    29    10     4
    58    46    33    10     8     1


ans =

    98    92    83    72    66    43
    95    86    75    66    45    36
    89    80    68    49    38    13
    80    69    52    39    22    12
    70    53    40    28    12     5
    53    41    33    13     7     3


ans =

     []


ans =

     []


ans =

    99    82    74    64    58    32
    82    79    65    59    36    26
    80    72    59    36    26    18
    73    59    40    27    19    11
    62    49    30    21    16     2
    55    31    23    16     8     1


ans =

    98    93    86    84    66    45
    95    90    84    67    49    21
    91    85    75    57    24    15
    85    80    59    26    17    10
    81    65    27    20    13     4
    65    42    20    13     9     0


ans =

    99    92    81    69    59    53
    98    90    70    62    55    32
    91    74    62    55    42    17
    77    65    56    46    21    11
    66    57    46    25    15     9
    58    50    29    16    10     0


ans =

     []


ans =

     []


ans =

    99    89    83    78    62    45
    95    85    78    63    47    31
    88    79    65    51    31    24
    80    71    56    31    25    20
    74    57    39    26    21     9
    58    42    29    21    13     5


ans =

     []


ans =

    99    80    72    65    54    36
    88    74    65    60    38    27
    79    70    63    39    29    17
    71    63    42    30    21    10
    64    42    32    24    16     7
    46    35    25    16     7     2


ans =

    95    80    64    44    35    28
    93    66    49    36    31    21
    75    58    37    32    22    13
    59    37    33    23    15     6
    44    33    23    18    10     3
    34    25    20    11     4     0


ans =

     []


ans =

    92    85    79    62    59    36
    86    80    67    59    43    24
    85    68    60    43    25    18
    69    61    47    26    20     9
    62    53    30    21     9     4
    56    33    22    14     5     1


ans =

    95    93    87    82    69    57
    94    90    86    77    60    29
    91    86    78    64    36    23
    87    80    64    37    25    18
    80    69    46    27    19    17
    69    52    27    23    17     8


ans =

     []


ans =

    98    88    82    75    61    51
    89    83    81    69    54    35
    83    82    72    59    35    23
    82    72    60    37    27    17
    72    60    41    33    20     4
    61    46    33    21     6     1


ans =

    97    93    81    75    63    45
    95    83    78    66    47    22
    84    81    71    49    36    10
    81    72    56    37    13     7
    75    58    39    16     8     3
    58    41    20     9     5     2


ans =

    98    92    85    75    67    44
    94    85    79    69    53    31
    92    82    70    54    31    12
    83    74    57    33    25     8
    75    61    33    28    10     5
    62    38    28    10     8     2


ans =

     []


ans =

     []


ans =

     []
out_imp =

    45
79812064
Vote

Here's a code golf solution:

R, 175 169 155 bytes

\(v){g=matrix(,6,6);C=T
for(s in sort(v,T)){
T>1&&g[T-1,C]==s|C>1&&g[T,C-1]==s&&return()
g[T,C]=s;T=T+1;C=C-1
if(T>6|C<1){C=T+C;T=1;C>6&&{T=T+C-6;C=6}}}
g}

Attempt This Online!

Expanded version with comments:

\(v) {                      # v = vector of 36 numbers to arrange in 6x6 grid
  g = matrix(, 6, 6)        # create 6x6 grid initialized with NA values
  C = T                     # C = column index (starts as TRUE = 1)
                            # T = row index (implicitly TRUE = 1, will be reassigned)
  
  for(s in sort(v, T)) {    # iterate through v sorted in descending order
                            # sort(v, T) means sort(v, decreasing=TRUE)
                            # s takes each sorted value directly
    
    T > 1 &&                #   if not in first row AND
    g[T-1, C] == s          #   value directly above equals current value
    |                       #   OR
    C > 1 &&                #   if not in first column AND
    g[T, C-1] == s          #   value directly to left equals current value
    && return()             #   then return NULL (no solution - not strictly descending)
    
    g[T, C] = s             #   place current value at position (T, C)
    T = T + 1               #   move down one row (diagonal filling pattern)
    C = C - 1               #   move left one column (diagonal filling pattern)
    
    if(T > 6 | C < 1) {     #   if we've moved outside grid boundaries:
      C = T + C             #     calculate starting column for next diagonal
      T = 1                 #     reset to first row
      C > 6 &&              #     if calculated column exceeds grid width:
      {T = T + C - 6        #       shift row down by overflow amount
       C = 6}               #       set column to rightmost position (6)
    }
  }
  g                         # return the completed grid (if possible)
}
79811950
Vote

Once the input is sorted descending, think of it like a tapered string, thick at the top and narrow at the bottom. Trim the string and lay the segments along diagonals, upper right to lower left.

Most of the inputs that have no solution have no solution because the greatest value (i.e., upper left corner) or the least value (i.e., lower right corner) is duplicated.

0: No solution for input
1: No solution for input
2: [[99,95,91,81,73,61],[91,84,80,71,60,42],[82,75,68,59,42,18],[73,65,55,41,16,14],[63,53,34,16,13,6],[44,24,14,7,6,0]]
3: [[99,94,86,74,63,56],[88,83,73,62,52,36],[81,71,61,50,35,24],[70,59,48,29,20,10],[57,40,27,19,9,6],[40,27,13,8,3,1]]
4: [[99,97,89,85,78,65],[96,88,81,78,60,46],[85,80,76,52,45,35],[78,75,52,43,32,27],[71,48,41,31,26,21],[48,37,31,22,14,5]]
5: No solution for input
6: No solution for input
7: No solution for input
8: [[98,94,83,79,67,59],[89,80,78,66,58,44],[80,72,65,57,42,30],[71,64,56,39,29,18],[60,55,37,23,16,9],[48,31,22,10,9,4]]
9: [[99,97,88,81,71,63],[88,86,81,68,63,51],[82,79,66,58,50,38],[79,64,56,48,35,11],[64,54,42,15,9,3],[52,41,11,5,2,0]]
10: No solution for input
11: No solution for input
12: No solution for input
13: [[98,96,91,82,68,56],[93,90,74,66,55,32],[82,73,66,54,31,19],[70,65,49,28,16,12],[58,41,21,16,12,10],[38,19,14,10,4,3]]
14: [[94,85,81,77,71,61],[84,79,74,69,57,47],[79,73,69,57,46,32],[71,66,57,46,31,24],[65,56,39,31,14,12],[56,35,26,13,1,0]]
15: No solution for input
16: No solution for input
17: [[97,95,92,76,59,47],[95,91,67,58,46,39],[90,64,49,44,39,23],[62,49,42,38,22,16],[48,41,29,16,14,10],[40,25,16,13,10,0]]
18: No solution for input
19: [[99,97,92,86,77,63],[96,87,82,74,63,34],[87,80,73,59,34,25],[77,73,51,31,25,19],[71,44,28,24,15,14],[40,25,23,15,13,12]]
20: No solution for input
21: [[92,90,80,74,55,47],[89,77,71,54,40,29],[76,62,50,38,27,16],[56,49,38,24,8,5],[47,35,24,7,3,1],[33,23,6,2,1,0]]
22: No solution for input
23: No solution for input
24: No solution for input
25: No solution for input
26: [[97,95,91,81,76,66],[91,86,80,75,66,57],[85,79,74,62,46,31],[79,68,62,45,31,20],[68,61,38,28,17,13],[58,33,27,14,7,1]]
27: No solution for input
28: [[92,91,88,85,77,68],[88,87,84,73,65,32],[85,83,73,52,32,22],[80,71,42,29,20,12],[70,37,27,17,11,9],[35,26,14,10,7,3]]
29: [[98,97,89,81,64,59],[96,87,80,63,55,40],[84,80,63,50,36,28],[73,62,49,34,27,14],[59,48,31,24,12,7],[45,29,19,11,2,1]]
30: [[98,97,82,77,69,57],[92,80,76,67,54,34],[80,73,66,49,34,23],[72,65,45,30,19,14],[59,41,24,16,13,6],[39,23,15,6,4,3]]
31: [[98,97,89,86,63,53],[93,89,78,58,51,35],[89,78,58,48,30,21],[75,58,46,29,20,15],[55,44,28,17,14,8],[42,21,17,8,6,3]]
32: No solution for input
33: [[99,96,93,85,61,45],[95,89,82,59,45,35],[86,71,58,44,32,26],[62,58,42,31,20,16],[47,40,28,18,11,8],[36,28,18,11,7,3]]
34: [[99,97,92,85,76,58],[97,88,84,73,56,41],[87,77,73,52,38,23],[76,70,51,29,15,10],[62,46,27,15,9,7],[44,26,14,7,6,4]]
35: [[96,93,87,78,70,43],[91,80,76,70,42,24],[80,75,55,40,23,10],[74,54,39,19,10,7],[49,34,16,10,7,3],[30,11,9,5,2,0]]
36: [[99,94,92,81,67,56],[93,89,79,65,54,44],[84,69,60,53,43,26],[67,59,53,32,23,10],[58,50,31,19,9,6],[48,30,15,8,5,2]]
37: No solution for input
38: [[96,91,88,87,78,65],[89,87,86,78,64,51],[87,83,75,61,51,34],[80,69,59,50,32,11],[66,57,47,17,8,5],[52,45,12,5,1,0]]
39: [[99,97,90,86,74,62],[93,89,83,71,59,35],[88,78,67,51,33,25],[74,66,48,31,22,18],[66,41,28,19,15,11],[39,26,19,13,10,4]]
40: [[99,93,86,75,61,53],[87,85,75,59,49,31],[79,71,59,36,29,25],[68,59,35,27,21,14],[54,33,26,19,13,12],[32,25,18,13,7,6]]
41: [[94,88,84,76,70,65],[85,81,76,69,61,52],[78,75,68,60,49,34],[72,67,58,44,26,22],[65,57,41,25,22,11],[54,37,23,19,10,1]]
42: [[95,93,84,72,65,54],[92,81,71,61,51,37],[76,68,60,47,37,33],[66,59,45,35,32,18],[57,41,34,24,17,15],[38,34,20,16,14,6]]
43: No solution for input
44: No solution for input
45: [[99,94,90,83,78,59],[93,86,82,74,58,48],[84,81,67,55,47,24],[79,65,52,43,23,18],[63,52,32,22,16,12],[50,28,19,15,8,7]]
46: [[99,95,86,80,72,54],[95,85,78,70,54,45],[81,76,66,53,44,35],[74,59,49,39,32,15],[55,48,37,26,14,7],[47,37,24,8,6,2]]
47: No solution for input
48: [[96,95,87,72,68,56],[94,77,70,64,53,43],[75,69,63,50,42,28],[68,62,48,42,28,13],[57,47,39,23,10,7],[44,31,19,10,5,1]]
49: No solution for input
50: No solution for input
51: No solution for input
52: No solution for input
53: [[98,97,93,78,63,45],[94,86,75,61,41,27],[80,73,57,38,25,20],[68,52,37,24,18,11],[48,32,23,14,10,7],[27,22,13,7,6,2]]
54: [[96,88,80,76,66,49],[88,80,73,63,41,28],[79,68,56,39,25,18],[67,50,33,24,18,11],[49,30,22,17,6,4],[28,20,14,6,3,0]]
55: No solution for input
56: [[99,96,88,73,66,46],[92,86,69,61,44,29],[75,69,53,40,24,14],[68,53,37,22,13,11],[48,32,22,13,11,3],[31,17,11,10,1,0]]
57: [[98,97,91,78,72,56],[92,90,77,70,55,42],[86,76,65,55,38,27],[76,65,55,38,24,15],[58,54,37,19,11,3],[46,34,18,5,3,0]]
58: No solution for input
59: [[97,96,91,75,67,40],[95,88,74,67,39,33],[79,74,63,39,29,20],[71,62,38,29,17,5],[58,38,27,14,4,2],[37,24,13,4,2,1]]
60: No solution for input
61: [[96,92,83,82,63,55],[90,83,77,63,54,39],[83,75,62,54,36,23],[72,60,53,34,22,17],[57,50,33,19,14,9],[50,29,18,11,6,1]]
62: [[99,96,93,89,80,71],[95,92,87,78,70,39],[90,82,78,60,38,25],[81,77,55,37,23,18],[74,49,36,21,13,10],[44,26,19,11,3,1]]
63: [[97,93,87,82,75,69],[89,87,82,73,68,53],[83,81,71,68,51,38],[76,70,67,49,37,18],[70,63,45,32,14,11],[63,40,21,13,10,7]]
64: [[94,91,87,80,72,58],[91,84,80,68,55,39],[80,78,64,52,36,27],[74,62,51,35,26,19],[61,50,35,26,15,11],[49,28,25,15,10,4]]
65: [[90,76,67,63,61,42],[72,66,63,54,40,28],[65,61,53,38,25,20],[61,49,36,24,17,9],[42,34,23,16,8,6],[31,21,10,7,5,0]]
66: No solution for input
67: No solution for input
68: No solution for input
69: No solution for input
70: No solution for input
71: [[95,93,91,82,73,60],[92,87,82,72,56,48],[86,76,71,55,43,38],[75,64,55,42,36,20],[62,53,41,26,17,14],[50,40,22,16,14,3]]
72: [[97,91,90,80,70,60],[91,88,73,69,55,41],[84,71,68,53,41,29],[71,67,53,39,23,15],[64,44,39,19,13,10],[42,37,18,10,8,5]]
73: No solution for input
74: [[96,95,91,82,72,43],[92,88,78,70,41,27],[83,77,61,38,25,22],[76,55,36,24,20,14],[54,34,22,18,12,9],[30,22,15,10,2,0]]
75: [[98,93,88,83,72,57],[90,84,81,72,55,36],[84,76,68,50,36,24],[75,63,44,30,24,6],[58,42,26,20,6,1],[39,26,9,3,1,0]]
76: [[86,85,74,63,53,40],[81,74,61,42,39,36],[65,58,41,39,34,25],[53,41,38,32,23,19],[40,37,31,22,18,8],[36,27,20,9,6,0]]
77: [[87,84,82,75,70,58],[82,79,75,68,54,46],[77,74,62,53,35,33],[74,62,53,34,29,10],[59,49,34,24,10,8],[49,34,21,9,4,1]]
78: [[98,95,89,80,70,53],[92,86,80,69,53,41],[83,75,68,52,40,33],[72,66,49,39,28,13],[66,45,38,22,12,7],[43,36,13,12,5,3]]
79: No solution for input
80: No solution for input
81: [[99,82,80,73,62,55],[82,79,72,59,49,31],[74,65,59,40,30,23],[64,59,36,27,21,16],[58,36,26,19,16,8],[32,26,18,11,2,1]]
82: [[98,95,91,85,81,65],[93,90,85,80,65,42],[86,84,75,59,27,20],[84,67,57,26,20,13],[66,49,24,17,13,9],[45,21,15,10,4,0]]
83: [[99,98,91,77,66,58],[92,90,74,65,57,50],[81,70,62,56,46,29],[69,62,55,46,25,16],[59,55,42,21,15,10],[53,32,17,11,9,0]]
84: No solution for input
85: No solution for input
86: [[99,95,88,80,74,58],[89,85,79,71,57,42],[83,78,65,56,39,29],[78,63,51,31,26,21],[62,47,31,25,21,13],[45,31,24,20,9,5]]
87: No solution for input
88: [[99,88,79,71,64,46],[80,74,70,63,42,35],[72,65,63,42,32,25],[65,60,39,30,24,16],[54,38,29,21,16,7],[36,27,17,10,7,2]]
89: [[95,93,75,59,44,34],[80,66,58,37,33,25],[64,49,37,33,23,20],[44,36,32,23,18,11],[35,31,22,15,10,4],[28,21,13,6,3,0]]
90: No solution for input
91: [[92,86,85,69,62,56],[85,80,68,61,53,33],[79,67,60,47,30,22],[62,59,43,26,21,14],[59,43,25,20,9,5],[36,24,18,9,4,1]]
92: [[95,94,91,87,80,69],[93,90,86,80,69,52],[87,86,78,64,46,27],[82,77,64,37,27,23],[69,60,36,25,19,17],[57,29,23,18,17,8]]
93: No solution for input
94: [[98,89,83,82,72,61],[88,83,82,72,60,46],[82,81,72,60,41,33],[75,69,59,37,33,21],[61,54,35,27,20,6],[51,35,23,17,4,1]]
95: [[97,95,84,81,75,58],[93,83,81,72,58,41],[81,78,71,56,39,20],[75,66,49,37,16,9],[63,47,36,13,8,5],[45,22,10,7,3,2]]
96: [[98,94,92,83,75,62],[92,85,82,74,61,38],[85,79,70,57,33,28],[75,69,54,33,28,10],[67,53,31,25,10,8],[44,31,12,8,5,2]]
97: No solution for input
98: No solution for input
99: No solution for input

45 inputs had no solution

c13.htm

<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><title>Challenge 13</title><style>
body {
  font-family: monospace;
}
</style></head><body></body><script src="c13.js"></script></html>

c13.js

( function () {
  'use strict';

  ( function main( e ) {
    var
      err = 0, // error count
      text,    // array of input strings
      a,       // array of "random" numbers
      grid = new Array( 6 ).fill( 0 ).map( () => new Array( 6 ) ),
      row, col,
      ok,      // boolean for error in grid
      t, i, j;

    // numerical compare for Array.prototype.sort
    // sort descending
    function cmp( a, b ) {
      return a > b ? -1 : a < b ? 1 : 0;
    }

    // pick the input from disk utterly without validation
    if ( typeof e === 'undefined' ) {
      t = document.createElement( 'input' );
      t.type = 'file';
      t.addEventListener( 'change', main );
      document.body.textContent = '';
      document.body.appendChild( t );
      return;
    } else if ( e.target instanceof HTMLInputElement ) {
      document.body.textContent = '';
      e.target.removeEventListener( 'change', main );
      t = new FileReader();
      t.addEventListener( 'load', main );
      t.readAsText( e.target.files[ 0 ] );
      return;
    } else if ( e.target instanceof FileReader ) {
      e.target.removeEventListener( 'load', main );
      text = e.target.result.split( '\n' );
    } else { // should never run, but just in case ...
      return;
    }

    for ( i = 0; i < text.length; ++i ) {
      // sort each set of inputs into descending numerical order
      a = JSON.parse( text[ i ] ).sort( cmp );
      row = col = 0;
      ok = true;
      // place the input values onto diagonals of a 6×6 grid
      // starting with the upper left
      for ( j = 0; j < 36 && ok; ++j ) {
        // above and left are guaranteed not to be less
        // only need to test for equality
        ok = !(
          row && grid[ row - 1 ][ col ] === a[ j ] ||
          col && grid[ row ][ col - 1 ] === a[ j ]
        );
        grid[ row ][ col ] = a[ j ];
        ++row;
        --col;
        if ( row > 5 || col < 0 ) {
          col = row + col + 1; // next diagonal
          row = 0;
          if ( col > 5 ) { // off the grid, bring it back
            row += col - 5;
            col = 5;
          }
        }
      }
      t = document.createElement( 'p' );
      if ( ok ) {
        t.textContent = i + ': ' + JSON.stringify( grid );
      } else {
        t.textContent = i + ': No solution for input';
        ++err;
      }
      document.body.appendChild( t );
    }
    t = document.createElement( 'p' );
    t.textContent = err + ' inputs had no solution';
    document.body.appendChild( t );
  } () );
} () );