var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let t = rn();
	while (t--) {
		let [n, k] = rna();

		if (n % 2)
			k += Math.floor((k - 1)/Math.floor(n / 2));

		const ans = (k - 1) % n + 1;

		console.log(ans);
	}
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    var x = Number(readline())
    Array(Number(x)).fill(1).map((t, i) => {

        var [n, k] = readline().split(' ').map((x, i) => {
            return parseInt(x)
        })
        if (n % 2 === 0) {
            if(k % n ===0) return console.log(n)
            return console.log(k % n)
        }
        var mid = Math.floor(n/2)
        var res = Math.floor((k-1) / mid)

        // console.log((k+res)%(n))
        // console.log(res, k, mid)
        if(k<mid) return console.log(k)
        if ((k + res) % (n) === 0) return console.log(n)
        console.log((k + res) % (n))
    })

}

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
}

/*
 * File Created: Tuesday, 16th February 2021 2:01:47 pm
 * Author: Lukas Rimkus
 */

 'use-strict'

 process.stdin.resume();
 process.stdin.setEncoding('utf8');

 let data = '';
 let currentLine = 0;

 process.stdin.on('data', chunk => {
 data += chunk;
 });

 process.stdin.on('end', () =>{
     data = data.replace(/\s*$/, '')
     .split('\n')
     .map(str => str.replace(/\s*$/, ''));

     let testCases = parseInt(data.shift());

     while(testCases--) {

         const [n,k] = readLine().split(' ').map(Number);

         b(n,k);
     }
 });

 function get_ints() {
     return data.shift().split(' ').map(Number);
 }

 function readLine() {
         return data[currentLine++];
 }

 function a(n,a){
     a.sort((a,b) => a - b);
     let count = 0;
     for(let i = 0 ; i < n; i++){
         if(i === n - 1) break;
         if(a[i] !== a[i+1]){
             return n - i - 1;
         }
     }
     return 0;
 }

function b(n,k){
    const f = Math.floor(n / 2);
    k--;
    const ans = (k + (n % 2) * Math.floor(k/f))
    return console.log(ans % n + 1)

}

module.exports = b;

/*
 * File Created: Tuesday, 16th February 2021 2:01:47 pm
 * Author: Lukas Rimkus
 */

 'use-strict'

 process.stdin.resume();
 process.stdin.setEncoding('utf8');

 let data = '';
 let currentLine = 0;

 process.stdin.on('data', chunk => {
 data += chunk;
 });

 process.stdin.on('end', () =>{
     data = data.replace(/\s*$/, '')
     .split('\n')
     .map(str => str.replace(/\s*$/, ''));

     let testCases = parseInt(data.shift());

     while(testCases--) {

         const [n,k] = readLine().split(' ').map(Number);

         const res = b(n,k);

         console.log(res)
     }
 });

 function get_ints() {
     return data.shift().split(' ').map(Number);
 }

 function readLine() {
         return data[currentLine++];
 }

 function a(n,a){
     a.sort((a,b) => a - b);
     let count = 0;
     for(let i = 0 ; i < n; i++){
         if(i === n - 1) break;
         if(a[i] !== a[i+1]){
             return n - i - 1;
         }
     }
     return 0;
 }

function b(n,k){
    let a = n;
    let b = 1;
    if(n % 2 === 0){
        // they don't meet each other
        if(n === k) return k;
        else if(n > k){
            return k;
        } else {
            return k % n;
        }
    } else {
        // they meet each other every 2 times in every cycle: ->
        // how many cycles?
        if(n === k){
            return b + 1;
        } else if(n > k){
            const middle = Math.ceil(n / 2);
            if(middle > k){
                return k;
            } else {
                return k + 1;
            }
        } else {
            const cycle = Math.floor(k / n);
            let rem = k % n - 1;
            // how many diff seq?
            const seq = Math.floor(n / 2);
            b = 1 + Math.min(seq,cycle) * 2;
            if(b === n) b = 1;
            for(let a = n; rem > 0; a--, rem--,b++){

                if(a === b) b++;
                // console.log(`${a}, ${rem}, ${b}`)
            }
            return b;
        }
    }
}

module.exports = b;

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    var x = Number(readline())
    Array(Number(x)).fill(1).map((t, i) => {

        var [n, k] = readline().split(' ').map((x, i) => {
            return parseInt(x)
        })
        if (n % 2 === 0) return console.log((k) % (n + 1))
        var mid = Math.floor(n/2)
        var res = Math.floor((k-1) / mid)

        // console.log((k+res)%(n))
        // console.log(res, k, mid)
        if(k<mid) return console.log(k)
        if ((k + res) % (n) === 0) return console.log(n)
        console.log((k + res) % (n))
    })

}

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
}


var gcd = function(x, y){
    while(y){
        var t = y;
        y = x % y;
        x = t;
    }
return x;
};
var MC = function(a){
    return Math.ceil(a);
};
var MF = function(a){
    return Math.floor(a);
};
var Mi = function(a, b){
    return Math.min(a, b);
};
var Ma = function(a, b){
    return Math.max(a, b);
};
var check = function(a){
    for(c = 2; c <= Math.sqrt(a); c++){
        if(a % c === 0){
            return false;
        }
    }
    return true;
};
let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0, k = 0;
    for(i = 1; i <= t * 2; i++){
        var s = lines[i].split(' ').map(Number);
        if(i % 2 == 1){
            n = s[0], k = s[1];
        }else{
            var ok = true;
            var a = 2e9;
            for(j = k - 1; j > 0; j--){
                if(s[j] - s[j - 1] > a){
                    ok = false;
                }
                a = s[j] - s[j - 1];
            }
            if((n - k + 1) * a < s[0]){
                ok = false;
            }
            console.log(ok ? 'YES' : 'NO');
        }
    }
});

var readline = require('readline');
var inputString = [], currentLine = 0;
process.stdin.resume();
process.stdin.setEncoding('utf-8');
var rl = readline.createInterface(process.stdin);
rl.on('line', line => { inputString.push(line) });
process.stdin.on('end', () => {  main()  });

function readLine() {
    return inputString[currentLine++];
}

function main() {
    const t = +readLine();
    for(let i = 0; i < t; i++){
        // const n = +readLine();
        const n_k = readLine().split(' ').map(p => +p);
        const arr = readLine().split(' ').map(p => +p);
        let result = myFunc(n_k[0], n_k[1], arr);
        console.log(result);
    }
}

function myFunc(n, k, arr){
    if(k == 1) return 'YES';

    let min = Infinity;
    for(let i = k-1; i > 0; i--){
        if(arr[i] - arr[i-1] > min) return 'NO';
        min = arr[i] - arr[i-1];
    }

    // if(arr[0] > min) return 'NO';
    if( (n-k+1) * min < arr[0]) return 'NO';

    return 'YES';

}

var gcd = function(x, y){
    while(y){
        var t = y;
        y = x % y;
        x = t;
    }
return x;
};
var MC = function(a){
    return Math.ceil(a);
};
var MF = function(a){
    return Math.floor(a);
};
var Mi = function(a, b){
    return Math.min(a, b);
};
var Ma = function(a, b){
    return Math.max(a, b);
};
var check = function(a){
    for(c = 2; c <= Math.sqrt(a); c++){
        if(a % c === 0){
            return false;
        }
    }
    return true;
};
let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0, k = 0;
    for(i = 1; i <= t * 2; i++){
        var s = lines[i].split(' ').map(Number);
        if(i % 2 == 1){
            n = s[0], k = s[1];
        }else{
            var ok = true;
            var a = 1e9;
            for(j = k - 1; j > 0; j--){
                if(s[j] - s[j - 1] > a){
                    ok = false;
                }
                a = s[j] - s[j - 1];
            }
            if((n - k + 1) * a < s[0]){
                ok = false;
            }
            console.log(ok ? 'YES' : 'NO');
        }
    }
});

var gcd = function(x, y){
    while(y){
        var t = y;
        y = x % y;
        x = t;
    }
return x;
};
var MC = function(a){
    return Math.ceil(a);
};
var MF = function(a){
    return Math.floor(a);
};
var Mi = function(a, b){
    return Math.min(a, b);
};
var Ma = function(a, b){
    return Math.max(a, b);
};
var check = function(a){
    for(c = 2; c <= Math.sqrt(a); c++){
        if(a % c === 0){
            return false;
        }
    }
    return true;
};
let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0, k = 0;
    for(i = 1; i <= t * 2; i++){
        var s = lines[i].split(' ').map(Number);
        if(i % 2 == 1){
            n = s[0], k = s[1];
        }else{
            var ok = true;
            var a = 1e5;
            for(j = k - 1; j > 0; j--){
                if(s[j] - s[j - 1] > a){
                    ok = false;
                }
                a = s[j] - s[j - 1];
            }
            if((n - k + 1) * a < s[0]){
                ok = false;
            }
            console.log(ok ? 'YES' : 'NO');
        }
    }
});

var gcd = function(x, y){
    while(y){
        var t = y;
        y = x % y;
        x = t;
    }
return x;
};
var MC = function(a){
    return Math.ceil(a);
};
var MF = function(a){
    return Math.floor(a);
};
var Mi = function(a, b){
    return Math.min(a, b);
};
var Ma = function(a, b){
    return Math.max(a, b);
};
var check = function(a){
    for(c = 2; c <= Math.sqrt(a); c++){
        if(a % c === 0){
            return false;
        }
    }
    return true;
};
let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0, k = 0;
    for(i = 1; i <= t * 2; i++){
        var s = lines[i].split(' ').map(Number);
        if(i % 2 == 1){
            n = s[0], k = s[1];
        }else{
            var ok = true;
            var a = 1e3;
            for(j = k - 1; j > 0; j--){
                if(s[j] - s[j - 1] > a){
                    ok = false;
                }
                a = s[j] - s[j - 1];
            }
            if((n - k + 1) * a < s[0]){
                ok = false;
            }
            console.log(ok ? 'YES' : 'NO');
        }
    }
});

var gcd = function(x, y){
    while(y){
        var t = y;
        y = x % y;
        x = t;
    }
return x;
};
var MC = function(a){
    return Math.ceil(a);
};
var MF = function(a){
    return Math.floor(a);
};
var Mi = function(a, b){
    return Math.min(a, b);
};
var Ma = function(a, b){
    return Math.max(a, b);
};
var check = function(a){
    for(c = 2; c <= Math.sqrt(a); c++){
        if(a % c === 0){
            return false;
        }
    }
    return true;
};
let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0, k = 0;
    for(i = 1; i <= t * 2; i++){
        var s = lines[i].split(' ').map(Number);
        if(i % 2 == 1){
            n = s[0], k = s[1];
        }else{
            var ok = true;
            var a = 100;
            for(j = k - 1; j > 0; j--){
                if(s[j] - s[j - 1] > a){
                    ok = false;
                }
                a = s[j] - s[j - 1];
            }
            if((n - k + 1) * a < s[0]){
                ok = false;
            }
            console.log(ok ? 'YES' : 'NO');
        }
    }
});

var gcd = function(x, y){
    while(y){
        var t = y;
        y = x % y;
        x = t;
    }
return x;
};
var MC = function(a){
    return Math.ceil(a);
};
var MF = function(a){
    return Math.floor(a);
};
var Mi = function(a, b){
    return Math.min(a, b);
};
var Ma = function(a, b){
    return Math.max(a, b);
};
var check = function(a){
    for(c = 2; c <= Math.sqrt(a); c++){
        if(a % c === 0){
            return false;
        }
    }
    return true;
};
let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0, k = 0;
    for(i = 1; i <= t * 2; i++){
        var s = lines[i].split(' ').map(Number);
        if(i % 2 == 1){
            n = s[0], k = s[1];
        }else{
            var ok = true;
            var a = 10;
            for(j = k - 1; j > 0; j--){
                if(s[j] - s[j - 1] > a){
                    ok = false;
                }
                a = s[j] - s[j - 1];
            }
            if((n - k + 1) * a < s[0]){
                ok = false;
            }
            console.log(ok ? 'YES' : 'NO');
        }
    }
});

var readline = require('readline');
var inputString = [], currentLine = 0;
process.stdin.resume();
process.stdin.setEncoding('utf-8');
var rl = readline.createInterface(process.stdin);
rl.on('line', line => { inputString.push(line) });
process.stdin.on('end', () => {  main()  });

function readLine() {
    return inputString[currentLine++];
}

function main() {
    const t = +readLine();
    for(let i = 0; i < t; i++){
        // const n = +readLine();
        const n_k = readLine().split(' ').map(p => +p);
        const arr = readLine().split(' ').map(p => +p);
        let result = myFunc(n_k[0], n_k[1], arr);
        console.log(result);
    }
}

function myFunc(n, k, arr){

    let min = Infinity;
    for(let i = k-1; i > 0; i--){
        if(arr[i] - arr[i-1] > min) return 'NO';
        min = arr[i] - arr[i-1];
    }

    if(arr[0] > min) return 'NO';
    if( (n-k+1) * min < min) return 'NO';

    return 'YES';

}


let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const str = readLine();
    console.log(solve(0, len - 1, "a"));

    function solve(start, end, char) {
      if (start === end) return +(str[start] !== char);

      let count1 = 0;
      for (let i = start; i <= Math.floor((start + end) / 2); i++) if (str[i] !== char) count1++;
      let _count1 = solve(Math.floor((start + end) / 2) + 1, end, String.fromCharCode(char.charCodeAt(0) + 1));

      let count2 = 0;
      for (let i = Math.floor((start + end) / 2) + 1; i <= end; i++) if (str[i] !== char) count2++;
      let _count2 = solve(start, Math.floor((start + end) / 2), String.fromCharCode(char.charCodeAt(0) + 1));

      return Math.min(count1 + _count1, count2 + _count2);
    }
  }
}

var anum = 'a'.charCodeAt(0);
var mod = 'z'.charCodeAt(0) - anum + 1;

function next(x) {
   return (x + 1) % mod;
}

function solve() {
   var n = Number(read());
   var s = read();
   var arr = [];
   var cArr = [];
   for (var i = 0; i < mod; i++) {
      cArr.push([]);
   }
   for (var i = 0; i < n; i++) {
      arr.push(s.charCodeAt(i) - anum);
      for (var j = 0; j < mod; j++) {
         var x = arr[i] === j ? 1 : 0;
         if (i === 0) {
            cArr[j].push(x);
         } else {
            cArr[j].push(cArr[j][i - 1] + x);
         }
      }
   }
   write(f(0, n - 1, mod - 1)[1]);

   function count(l, r, c) {
      var res = cArr[c][r];
      if (l > 0) {
         res -= cArr[c][l - 1];
      }
      return res;
   }

   function f(l, r, c) {
      if (l === r) {
         if (arr[l] === c) {
            return [0, 1];
         }
         if (arr[l] === next(c)) {
            return [1, 0];
         }
         return [1, 1];
      }
      var m = (r + l) >> 1;
      var ansl = f(l, m, next(c));
      var ansr = f(m + 1, r, next(c));
      var countC = r - l + 1 - count(l, r, c);
      return [countC, Math.min(ansl[0] + ansr[1], ansl[1] + ansr[0])];
   }
}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', init);
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readLine() {
    return inputString[currentLine++];
}

String.prototype.count = function(c) {
  let result = 0;
  for(let i = 0; i < this.length; i++)
    if(this[i] == c)
      result++;
  return result;
}

function nextChar(c) {
  return String.fromCharCode(c.charCodeAt(0) + 1);
}

function calc(s, c) {
  // console.log(s, c)
  if(s.length === 1)
    return s[0] !== c ? 1 : 0;

  const m = s.length / 2;
  const nxt = nextChar(c)
  let cntl = calc(s.substr(m), nxt);
  cntl += s.length / 2 - s.substr(0, m).count(c);
  let cntr = calc(s.substr(0, m), nxt);
  cntr += s.length / 2 - s.substr(m).count(c);
  return Math.min(cntl, cntr);
}

function main() {
  let t = readLine();
  t = parseInt(t);

  while(t--) {
    let n = parseInt(readLine());
    let s = readLine();
    console.log(calc(s, 'a'));
  }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let lines = []
process.stdin.on('data', input => {
  lines = input.trim().split('\n')
})
process.stdin.on('end', main)

String.prototype.count=function(c) {
  var result = 0, i = 0;
  for(i;i<this.length;i++)if(this[i]==c)result++;
  return result;
}

function nextChar(c) {
  return String.fromCharCode(c.charCodeAt(0) + 1);
}

function calc(s, c) {
  // console.log(s, c)
  if(s.length === 1)
    return s[0] !== c ? 1 : 0;

  const m = s.length / 2;
  const nxt = nextChar(c)
  let cntl = calc(s.substr(m), nxt);
  cntl += m - s.substr(0, m).count(c);
  let cntr = calc(s.substr(0, m), nxt);
  cntr += m - s.substr(m).count(c);
  return Math.min(cntl, cntr);
}

function main() {
  let t = lines[0]
  console.log(lines)

  for(let i = 2; i < lines.length; i += 2) {
    console.log(calc(lines[i], 'a'));
  }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let lines = []
process.stdin.on('data', input => {
  lines = input.trim().split('\n')
})
process.stdin.on('end', main)

function nextChar(c) {
  return String.fromCharCode(c.charCodeAt(0) + 1);
}

function calc(s, c) {
  // console.log(s, c)
  if(s.length === 1)
    return s[0] !== c ? 1 : 0;

  const m = s.length / 2;
  const nxt = nextChar(c)
  let cntl = calc(s.substr(m), nxt);
  cntl += m - s.substr(0, m).split(c).length;
  let cntr = calc(s.substr(0, m), nxt);
  cntr += m - s.substr(m).split(c).length;
  return Math.min(cntl, cntr);
}

function main() {
  let t = lines[0]

  for(let i = 2; i < lines.length; i += 2) {
    console.log(calc(lines[i], 'a'));
  }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let lines = []
process.stdin.on('data', input => {
  lines = input.trim().split('\n')
})
process.stdin.on('end', main)

String.prototype.count=function(c) {
  var result = 0, i = 0;
  for(i;i<this.length;i++)if(this[i]==c)result++;
  return result;
}

function nextChar(c) {
  return String.fromCharCode(c.charCodeAt(0) + 1);
}

function calc(s, c) {
  // console.log(s, c)
  if(s.length === 1)
    return s[0] !== c ? 1 : 0;

  const m = s.length / 2;
  const nxt = nextChar(c)
  let cntl = calc(s.substr(m), nxt);
  cntl += m - s.substr(0, m).count(c);
  let cntr = calc(s.substr(0, m), nxt);
  cntr += m - s.substr(m).count(c);
  return Math.min(cntl, cntr);
}

function main() {
  for(let i = 2; i < lines.length; i += 2) {
    console.log(calc(lines[i].trim(), 'a'));
  }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let lines = []
process.stdin.on('data', input => {
  lines = input.trim().split('\n')
})
process.stdin.on('end', main)

String.prototype.count=function(c) {
  var result = 0, i = 0;
  for(i;i<this.length;i++)if(this[i]==c)result++;
  return result;
}

function nextChar(c) {
  return String.fromCharCode(c.charCodeAt(0) + 1);
}

function calc(s, c) {
  // console.log(s, c)
  if(s.length === 1)
    return s[0] !== c ? 1 : 0;

  const m = s.length / 2;
  const nxt = nextChar(c)
  let cntl = calc(s.substr(m), nxt);
  cntl += m - s.substr(0, m).count(c);
  let cntr = calc(s.substr(0, m), nxt);
  cntr += m - s.substr(m).count(c);
  return Math.min(cntl, cntr);
}

function main() {
  let t = lines[0]

  for(let i = 2; i < lines.length; i += 2) {
    console.log(calc(lines[i], 'a'));
  }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let lines = []
// process.stdin.on('data', input => {
//   lines = input.trim().split('\n').map(s => s.trim());
// })
// process.stdin.on('end', main)

String.prototype.count = function(c) {
  let result = 0;
  for(let i = 0; i < this.length; i++)
    if(this[i] == c)
      result++;
  return result;
}

function nextChar(c) {
  return String.fromCharCode(c.charCodeAt(0) + 1);
}

function calc(s, c) {
  // console.log(s, c)
  if(s.length === 1)
    return s[0] !== c ? 1 : 0;

  const m = s.length / 2;
  const nxt = nextChar(c)
  let cntl = calc(s.substr(m), nxt);
  cntl += s.length / 2 - s.substr(0, m).count(c);
  let cntr = calc(s.substr(0, m), nxt);
  cntr += s.length / 2 - s.substr(m).count(c);
  return Math.min(cntl, cntr);
}

function prepareLines() {
  let t = parseInt(readline())
  for(let i = 0; i < t; i++) {
    lines.push(readline());
  }
}

function main() {
  prepareLines();
  for(let i = 1; i < lines.length; i += 2) {
    console.log(calc(lines[i].trim(), 'a'));
  }
}

// 'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let lines = []
process.stdin.on('data', input => {
  lines = input.trim().split('\n').map(s => s.trim());
})
process.stdin.on('end', main)

String.prototype.count = function(c) {
  let result = 0;
  for(let i = 0; i < this.length; i++)
    if(this[i] == c)
      result++;
  return result;
}

function nextChar(c) {
  return String.fromCharCode(c.charCodeAt(0) + 1);
}

function calc(s, c) {
  // console.log(s, c)
  if(s.length === 1)
    return s[0] !== c ? 1 : 0;

  const m = s.length / 2;
  const nxt = nextChar(c)
  let cntl = calc(s.substr(m), nxt);
  cntl += s.length / 2 - s.substr(0, m).count(c);
  let cntr = calc(s.substr(0, m), nxt);
  cntr += s.length / 2 - s.substr(m).count(c);
  return Math.min(cntl, cntr);
}

function main() {
  for(let i = 2; i < lines.length; i += 2) {
    console.log(calc(lines[i].trim(), 'a'));
  }
}


'use strict'

let lll
let N = +readline()
const alc = ['ABSINTH', 'BEER', 'BRANDY', 'CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA', 'VODKA', 'WHISKEY', 'WINE']
let ch = 0

while (lll = readline()) {
  if (+lll == lll) {
    if (lll < 18) ch++
  } else {
    if (~alc.indexOf(lll)) ch++
  }
}

print(ch)

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function main() {
	var alcoholic = { "ABSINTH": true, "BEER": true, "BRANDY": true,
		"CHAMPAGNE": true, "GIN": true, "RUM": true, "SAKE": true,
		"TEQUILA": true, "VODKA": true, "WHISKEY": true, "WINE": true },
		numPatrons = parseInt(readline(), 10),
		numChecks = 0,
		agePattern = /\d+/;
	for (var patronIx = 0; patronIx < numPatrons; ++patronIx) {
		var token = readline().replace(/\s+/g, "");
		if (agePattern.test(token)) {
			if (parseInt(token, 10) < 18) {
				++numChecks;
			}
		}
		else if (alcoholic[token] != undefined) {
			++numChecks;
		}
	}
	print(numChecks);
}

main();

'use strict';

// let inpFileStrArr = `
// 5
// 18
// VODKA
// COKE
// 19
// 17
// `.trim().split('\n'), inpFileCounter = 0;
// function readline() {
//   return inpFileStrArr[inpFileCounter++];
// }
// function print(x) {
//   console.log(x);
// }

var alcohol = ['ABSINTH', 'BEER', 'BRANDY', 'CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA', 'VODKA', 'WHISKEY', 'WINE'];

var n = Number(readline()),
    count = 0;
for (var i = 0; i < n; i++) {
  var str = readline();
  if (isNaN(str) && alcohol.indexOf(str) === -1 || !isNaN(str) && Number(str) >= 18) {
    continue;
  }
  count++;
}

print(count);

'use strict';

/*let input = `2
2
GIN`.split('\n');
function print(out) {
    console.log(out);
}
function readline() {
    return input.shift();
}*/

//code

var n = Number(readline());
var drinks = ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"];
var count = 0;
for (var i = 0; i < n; i++) {
    var line = readline();
    if (!isNaN(Number(line))) {
        if (Number(line) < 18) {
            count++;
        }
    } else if (drinks.includes(line)) {
        count++;
    }
}
print(count);

var alco = ['ABSINTH', 'BEER', 'BRANDY', 'CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA', 'VODKA', 'WHISKEY', 'WINE'];
var n = parseInt(readline());
var res = 0;

while(n--) {
	var input = readline();
	var num = parseInt(input);
	if (num >= 0) {
		if (num < 18) {
			res++;
		}
	} else {
		if (alco.indexOf(input) !== -1) {
			res++;
		}
	}
}

print(res);

var arr = ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"];
var t = Number(readline());
var ans = 0;
while(t--) {
    var input = readline();
    if ((input[0] >= "0" && input[0] <= "9" && input < 18) || arr.includes(input))
        ++ans;
}
print(ans);

'use strict';

/*let input = `5
18
VODKA
COKE
19
17`.split('\n');
function print(out) {
    console.log(out);
}
function readline() {
    return input.shift();
}*/

//code

var n = Number(readline());
var drinks = ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"];
var count = 0;
for (var i = 0; i < n; i++) {
    var line = readline();
    if (!isNaN(Number(line))) {
        if (Number(line) < 18) {
            count++;
        }
    } else if (!drinks.includes(line)) {
        count++;
    }
}
print(count);

var alco = ['ABSINTH', 'BEER', 'BRANDY', 'CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA', 'VODKA', 'WHISKEY', 'WINE'];
var n = parseInt(readline());
var res = 0;

while(n--) {
	var input = readline();
	if (num = parseInt(input)) {
		if (num < 18) {
			res++;
		}
	} else {
		if (alco.indexOf(input) !== -1) {
			res++;
		}
	}
}

print(res);

var arr = ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"];
var t = Number(readline());
var ans = 0;
while(t--) {
    var input = readline();
    if ((typeof input == 'number' && input < 18))
        ++ans;
}
print(ans);

var arr = ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"];
var t = Number(readline());
var ans = 0;
while (t--) {
    var input = readline();
    if ((typeof input === 'number' && input < 18) || arr.includes(input))
        ++ans;
}
print(ans);

var arr = ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"];
var t = Number(readline());
var ans = 0;
while(t--) {
    var input = readline();
    if ((input[0] >= "0" && input[0] <= "9") || arr.includes(input))
        ++ans;
}
print(ans);

var arr = ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"];
var t = Number(readline());
var ans = 0;
while(t--) {
    var input = readline();
    if ((typeof input == 'number' && input < 18) || arr.includes(input))
        ++ans;
}
print(ans);


let problem = "";
process.stdin.on("data", (c) => (problem += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = problem.split(EOL);
  lines.slice(-1);
  solve(lines);
});

function solve(lines) {
  const numProblems = lines[0];
  let moves = [];

  for (let problem = 1; problem <= numProblems; problem++) {
    // if (problem > 5 && problem < 501) {
    //   problem = 500;
    //   continue;
    // }

    moves = [];
    const str = lines[problem * 2];
    let arr = str.split(" ").map((n) => parseInt(n));

    // if (problem === 501) {
    //   console.log("FOO", problem, arr);
    // }

    const sorted = [...arr];
    sorted.sort((a, b) => a - b);

    let a = 0;
    let cur = sorted[0];

    for (let i = 0; i < arr.length; i++) {
      if (arr[i] === cur) {
        if (i - a > 0) {
          const diff = i - a;
          moves.push(`${a + 1} ${i + 1} ${diff}`);
          let newArr = [...arr];

          const len = i - a + 1;

          for (let x = 0; x < len; x++) {
            let q = (x + diff) % len;
            // if (q >= len) {
            //   q = q % len;
            // }
            // console.log(x, q);
            // console.log(x + a, q + a);
            newArr[x + a] = arr[q + a];
          }
          // console.log(arr, newArr);
          arr = newArr;
        }

        a += 1;
        i = a - 1;
        cur = sorted[a];
      }
    }
    console.log(moves.length);
    moves.forEach((str) => console.log(str));
  }

  process.exit(0);
}

// const testCase = [
//   "4",
//   "2",
//   "2 1",
//   "3",
//   "1 2 1",
//   "4",
//   "2 4 1 3",
//   "5",
//   "2 5 1 4 3",
//   "",
// ];

// testCase.splice(-1, 1);
// solve(testCase);

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		for (let i = 0; i < n; i++) {
			a[i] = [a[i], i];
		}

		a.sort((x, y) => x[0] - y[0]);

		const ans = [];
		const shfts = [];
		for (let i = 0; i < n; i++) {
			let indx = a[i][1];
			for (let j = 0; j < shfts.length; j++) {
				const m = n - j;
				indx -= j;
				indx = (indx + m - shfts[j]) % m;
				indx += j;
			}
			shfts[i] = indx - i;
			if (shfts[i]) {
				ans.push([i+1, n, shfts[i]]);
			}
		}

		console.log(ans.length);
		for (const stp of ans)
			console.log(stp.join(' '));
	}
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function main() {
   const t = parseInt(readline());
   for (let m = 0; m < t; m++){
        const n = parseInt(readline());

        const arr = readline().split(' ').map((str) => parseInt(str));
        let count = 0;
        const moves = [];
        for(let index = 0; index < n; index++){

          let min = index;

          for(let i = index; i < n; i++){
             if (arr[i] < arr[min]) {
                min = i;
             }
          }
          if(min !== index){
            let temp = arr[min]
            for(let j = index; j <= min; j++){
               let p = arr[j]
               arr[j] = temp;
               temp = p;
            }

            count++;
            moves.push(`${index + 1} ${min + 1} ${min - index}`);
          }
        }

        console.log(count);
        console.log(moves.join('\n'));
   }

}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}

const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let newArr = [...arr],
      res = [];
    newArr.sort((a, b) => a - b);
    for (let i = 0; i < n; i++) {
      if (arr[i] !== newArr[i]) {
        let f = newArr[i];
        for (let j = i; j < n; j++) {
          if (f === arr[j]) {
            let t = [i + 1, j + 1, j - i];
            let g = arr[j];
            for (let k = j; k > i; k--) arr[k] = arr[k - 1];
            arr[i] = g;
            res.push(t);
          }
        }
      }
    }
    if (res.length) {
      console.log(res.length);
      for (let i = 0; i < res.length; i++) console.log(res[i].join(" "));
    } else console.log(0);
  }
};
solve();

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = BigInt(next());
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var output = [];
		var count = 0;
		while(true){
			var isOK = true;
			for(var i = 0; i < list.length - 1; i++){
				if(list[i] > list[i + 1]){
					isOK = false;
					break;
				}
			}
			if(isOK){
				break;
			}
			var max = -Math.pow(10, 9) - 1;
			var maxIndex = -1;
			for(var i = 0; i < list.length; i++){
				if(max < list[i]){
					max = list[i];
					maxIndex = i;
				}
			}
			var newlist = [];
			for(var i = 0; i < list.length; i++){
				if(maxIndex != i){
					newlist.push(list[i]);
				}
			}
			if(maxIndex != list.length - 1){
				output.push((maxIndex + 1) + " " + (list.length) + " 1");
			}
			list = newlist;
		}
		myout(output.length);
		myout(myconv(output, 9));
	}
}

	function readStringArray() {
		return readline().split(' ');
	}
	function readNumArray() {
		return readStringArray().map(Number);
	}

	function main() {
		var testCasesNum = +readline();
		for (var i = 0; i < testCasesNum; i++) {
			var l = +readline();
			var arr = readNumArray();
			var results = [];
			for (var j = 0; j < arr.length - 1; j++) {
				var minIdx = findMinIdx(arr.slice(j));
				if (minIdx > 0) {
					results.push(`${j + 1} ${arr.length} ${minIdx}`);
					arr = arr
						.slice(0, j)
						.concat(arr.slice(j + minIdx))
						.concat(arr.slice(j, j + minIdx));
				}
			}
			print(results.length);
			for (var k = 0; k < results.length; k++) {
				print(results[k]);
			}
		}
	}

	function findMinIdx(arr) {
		var min = 0;
		for (var i = 0; i < arr.length; i++) {
			if (arr[i] < arr[min]) {
				min = i;
			}
		}
		return min;
	}
	main();

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const t = Number(readline());
    for(let i = 0; i < t; i++) {
        const n = Number(readline());
        const myArr = readline().split(" ");
        const ans = [];
        for(let i = 0; i < n - 1; i++) {
            let minIndex = i;
            for(let j = i; j < n; j++) {
                if(Number(myArr[j]) < Number(myArr[minIndex])) minIndex = j;
            }
            if(0 < minIndex - i) {
                ans.push((i + 1) + " " + n + " " + (minIndex - i));
                myArr.splice(i,n - i,...shift(myArr.slice(i), minIndex - i));
            }
        }
        console.log(ans.length);
        ans.forEach(str => console.log(str));
    }
}

function shift(arr, shiftValue) {
    const newArr = [...arr];
    const n = arr.length;
    for(let i = 0; i < n; i++) {
        let newIndex = i - shiftValue;
        if(0 <= newIndex) newArr[newIndex] = arr[i];
        else newArr[n + newIndex] = arr[i];
    }
    return newArr;
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

function readline() {
  return inputString[currentLine++];
}

const main = () => {
  let ansArr = []
  const a = readline();
  for (let i = 0; i < a; i++) {
    let c = []
    let k = readline();
    let arr = readline().split(' ').map(el=>Number(el))
    let sorted = [...arr].sort((a,b)=>a-b);
    for (let j = 0; j <sorted.length ; j++) {
      let index = arr.findIndex((el)=>el===sorted[j]);
      if (index+1 === arr.length ) continue
      arr =[ ...arr.slice(0,index) , ...arr.slice(index + 1), sorted[j]]
      c.push('' + (index+1) + ' ' +  sorted.length + ' ' + 1);
    }
    ansArr.push(c.length + '\n' + c.join('\n'))
  }
  process.stdout.write(ansArr.join('\n'))

}

let problem = "";
process.stdin.on("data", (c) => (problem += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = problem.split(EOL);
  lines.slice(-1);
  solve(lines);
});

function solve(lines) {
  const numProblems = lines[0];
  let moves = [];

  for (let problem = 1; problem <= numProblems; problem++) {
    moves = [];
    const str = lines[problem * 2];
    let arr = str.split(" ");

    const sorted = [...arr];
    sorted.sort((a, b) => a - b);

    let a = 0;
    let cur = sorted[0];

    for (let i = 0; i < arr.length; i++) {
      if (arr[i] === cur) {
        if (i - a > 0) {
          const diff = i - a;
          moves.push(`${a + 1} ${i + 1} ${diff}`);
          let newArr = [...arr];

          const len = i - a + 1;

          for (let x = 0; x < len; x++) {
            let q = (x + diff) % len;
            newArr[x + a] = arr[q + a];
          }
          arr = newArr;
        }

        a += 1;
        i = a - 1;
        cur = sorted[a];
      }
    }
    console.log(moves.length);
    moves.forEach((str) => console.log(str));
  }

  process.exit(0);
}

// const testCase = [
//   "4",
//   "2",
//   "2 1",
//   "3",
//   "1 2 1",
//   "4",
//   "2 4 1 3",
//   "5",
//   "2 5 1 4 3",
//   "",
// ];

// testCase.splice(-1, 1);
// solve(testCase);

"use strict";

process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});

process.stdin.on("end", (_) => {
  inputString = inputString
    .trim()
    .split("\n")
    .map((string) => {
      return string.trim();
    });

  main();
});

function readline() {
  return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  var n = parseInt(readline());
  while (n--) {
    readline();
    var temp = readline().split(" ");
    var arr = [];
    for (let i = 0; i < temp.length; i += 1) {
      temp[i] = parseInt(temp[i]);
      arr.push(temp[i]);
    }
    var sortArr = temp.sort(function (a, b) {
      return a - b;
    });
    var len = arr.length;
    var ans = [];
    for (var i = 0; i < len; i += 1) {
      for (var j = i; j < len; j += 1) {
        if (arr[j] === sortArr[i]) {
          if (i !== j) {
            ans.push([i + 1, j + 1, j - i]);
            for (var k = j - 1; k >= i; k -= 1) {
              arr[k + 1] = arr[k];
            }
            arr[i] = sortArr[i];
          }
          break;
        }
      }
    }
    console.log(ans.length);
    for (var i = 0; i < ans.length; i += 1) {
      console.log(ans[i][0], ans[i][1], ans[i][2]);
    }
  }
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		function shift (ar, l, r, d) {
			const cpy = ar.slice(l, r + 1);
			let i = d;
			while (l <= r) {
				ar[l++] = cpy[i];
				i = (i + 1) % cpy.length;
			}
		}

		const ans = [];
		for (let i = 0; i < n; i++) {
			const mn = Math.min(...a.slice(i));
			const d = a.slice(i).findIndex(x => x == mn);

			shift(a, i, n-1, d);

			if (d) ans.push([i+1, n, d]);
		}

		console.log(ans.length);
		for (const stp of ans)
			console.log(stp.join(' '));
	}
}

let problem = "";
process.stdin.on("data", (c) => (problem += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = problem.split(EOL);
  lines.slice(-1);
  solve(lines);
});

function solve(lines) {
  const numProblems = lines[0];
  let moves = [];

  for (let problem = 1; problem <= numProblems; problem++) {
    if (problem > 5 && problem < 501) {
      problem = 500;
      continue;
    }

    moves = [];
    const str = lines[problem * 2];
    let arr = str.split(" ").map((n) => parseInt(n));

    if (problem === 501) {
      console.log("FOO", problem, arr);
    }

    const sorted = [...arr];
    sorted.sort();

    let a = 0;
    let cur = sorted[0];

    for (let i = 0; i < arr.length; i++) {
      if (arr[i] === cur) {
        if (i - a > 0) {
          const diff = i - a;
          moves.push(`${a + 1} ${i + 1} ${diff}`);
          let newArr = [...arr];

          const len = i - a + 1;

          for (let x = 0; x < len; x++) {
            let q = (x + diff) % len;
            // if (q >= len) {
            //   q = q % len;
            // }
            // console.log(x, q);
            // console.log(x + a, q + a);
            newArr[x + a] = arr[q + a];
          }
          // console.log(arr, newArr);
          arr = newArr;
        }

        a += 1;
        i = a - 1;
        cur = sorted[a];
      }
    }
    console.log(moves.length);
    moves.forEach((str) => console.log(str));
  }

  process.exit(0);
}

// const testCase = [
//   "4",
//   "2",
//   "2 1",
//   "3",
//   "1 2 1",
//   "4",
//   "2 4 1 3",
//   "5",
//   "2 5 1 4 3",
//   "",
// ];

// testCase.splice(-1, 1);
// solve(testCase);

let problem = "";
process.stdin.on("data", (c) => (problem += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = problem.split(EOL);
  lines.slice(-1);
  solve(lines);
});

function solve(lines) {
  const numProblems = lines[0];
  let moves = [];

  for (let problem = 1; problem <= numProblems; problem++) {
    if (problem > 5 && problem < 499) {
      problem = 499;
      continue;
    }

    moves = [];
    const str = lines[problem * 2];
    let arr = str.split(" ").map((n) => parseInt(n));

    const sorted = [...arr];
    sorted.sort();

    let a = 0;
    let cur = sorted[0];

    for (let i = 0; i < arr.length; i++) {
      if (arr[i] === cur) {
        if (i - a > 0) {
          const diff = i - a;
          moves.push(`${a + 1} ${i + 1} ${diff}`);
          let newArr = [...arr];

          const len = i - a + 1;

          for (let x = 0; x < len; x++) {
            let q = (x + diff) % len;
            // if (q >= len) {
            //   q = q % len;
            // }
            // console.log(x, q);
            // console.log(x + a, q + a);
            newArr[x + a] = arr[q + a];
          }
          // console.log(arr, newArr);
          arr = newArr;
        }

        a += 1;
        i = a - 1;
        cur = sorted[a];
      }
    }
    console.log(moves.length);
    moves.forEach((str) => console.log(str));
  }

  process.exit(0);
}

// const testCase = [
//   "4",
//   "2",
//   "2 1",
//   "3",
//   "1 2 1",
//   "4",
//   "2 4 1 3",
//   "5",
//   "2 5 1 4 3",
//   "",
// ];

// testCase.splice(-1, 1);
// solve(testCase);

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL);
  lines.slice(-1);
  solve(lines);
});

function solve(lines) {
  const numProblems = lines[0];
  let moves = [];

  for (let problem = 1; problem <= numProblems; problem++) {
    moves = [];
    const str = lines[problem * 2];
    let arr = str.split(" ").map((n) => parseInt(n));

    const sorted = [...arr];
    sorted.sort();

    let a = 0;
    let cur = sorted[0];

    for (let i = 0; i < arr.length; i++) {
      if (i > 5) {
        i = 499;
        continue;
      }
      if (arr[i] === cur) {
        if (i - a > 0) {
          const diff = i - a;
          moves.push(`${a + 1} ${i + 1} ${diff}`);
          let newArr = [...arr];

          const len = i - a + 1;

          for (let x = 0; x < len; x++) {
            let q = (x + diff) % len;
            // if (q >= len) {
            //   q = q % len;
            // }
            // console.log(x, q);
            // console.log(x + a, q + a);
            newArr[x + a] = arr[q + a];
          }
          // console.log(arr, newArr);
          arr = newArr;
        }

        a += 1;
        i = a - 1;
        cur = sorted[a];
      }
    }
    console.log(moves.length);
    moves.forEach((str) => console.log(str));
  }

  process.exit(0);
}

// const testCase = [
//   "4",
//   "2",
//   "2 1",
//   "3",
//   "1 2 1",
//   "4",
//   "2 4 1 3",
//   "5",
//   "2 5 1 4 3",
//   "",
// ];

// testCase.splice(-1, 1);
// solve(testCase);

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL);
  lines.slice(-1);
  solve(lines);
});

function solve(lines) {
  // console.log(lines);
  const numProblems = lines[0];
  let moves = [];

  for (let problem = 1; problem <= numProblems; problem++) {
    moves = [];
    const str = lines[problem * 2];
    let arr = str.split(" ").map((n) => parseInt(n));

    const sorted = [...arr];
    sorted.sort();

    let a = 0;
    let cur = sorted[0];

    for (let i = 0; i < arr.length; i++) {
      if (arr[i] === cur) {
        if (i - a > 0) {
          const diff = i - a;
          moves.push(`${a + 1} ${i + 1} ${diff}`);
          let newArr = [...arr];

          const len = i - a + 1;

          for (let x = 0; x < len; x++) {
            let q = x + diff;
            if (q >= len) {
              q = q % len;
            }
            // console.log(x, q);
            newArr[x + a] = arr[q + a];
          }
          // console.log(arr, newArr);
          arr = newArr;
        }

        a += 1;
        i = a - 1;
        cur = sorted[a];
      }
    }
    console.log(moves.length);
    moves.forEach((str) => console.log(str));
  }

  process.exit(0);
}

// const testCase = [
//   "4",
//   "2",
//   "2 1",
//   "3",
//   "1 2 1",
//   "4",
//   "2 4 1 3",
//   "5",
//   "2 5 1 4 3",
//   "",
// ];

// testCase.splice(-1, 1);
// solve(testCase);

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL);
  lines.slice(-1);
  solve(lines);
});

function solve(lines) {
  // console.log(lines);
  const numProblems = lines[0];
  let moves = [];

  for (let problem = 1; problem <= numProblems; problem++) {
    moves = [];
    const str = lines[problem * 2];
    let arr = str.split(" ").map((n) => parseInt(n));

    const sorted = [...arr];
    sorted.sort();

    let a = 0;
    let cur = sorted[0];

    for (let i = 0; i < arr.length; i++) {
      if (arr[i] === cur) {
        if (i - a > 0) {
          const diff = i - a;
          moves.push(`${a + 1} ${i + 1} ${diff}`);
          let newArr = [...arr];

          const len = i - a + 1;

          for (let x = 0; x < len; x++) {
            let q = x + diff;
            if (q >= len) {
              q = q % len;
            }
            // console.log(x, q);
            newArr[x + a] = arr[q + a];
          }
          console.log(arr, newArr);
          arr = newArr;
        }

        a += 1;
        i = a - 1;
        cur = sorted[a];
      }
    }
    console.log(moves.length);
    moves.forEach((str) => console.log(str));
  }

  process.exit(0);
}

// const testCase = [
//   "4",
//   "2",
//   "2 1",
//   "3",
//   "1 2 1",
//   "4",
//   "2 4 1 3",
//   "5",
//   "2 5 1 4 3",
//   "",
// ];

// testCase.splice(-1, 1);
// solve(testCase);

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL);
  lines.slice(-1);
  solve(lines);
});

function solve(lines) {
  // console.log(lines);
  const numProblems = lines[0];
  let moves = [];

  for (let problem = 1; problem <= numProblems; problem++) {
    moves = [];
    const str = lines[problem * 2];
    let arr = str.split(" ");

    const sorted = [...arr];
    sorted.sort();

    let a = 0;
    let cur = sorted[0];

    for (let i = 0; i < arr.length; i++) {
      if (arr[i] === cur) {
        if (i - a > 0) {
          const diff = i - a;
          moves.push(`${a + 1} ${i + 1} ${diff}`);
          let newArr = [...arr];

          const len = i - a + 1;

          for (let x = 0; x < len; x++) {
            let q = x + diff;
            if (q >= len) {
              q = q % len;
            }
            // console.log(x, q);
            newArr[x + a] = arr[q + a];
          }
          // console.log(arr, newArr);
          arr = newArr;
        }

        a += 1;
        i = a - 1;
        cur = sorted[a];
      }
    }
    console.log(moves.length);
    moves.forEach((str) => console.log(str));
  }

  process.exit(0);
}

// const testCase = [
//   "4",
//   "2",
//   "2 1",
//   "3",
//   "1 2 1",
//   "4",
//   "2 4 1 3",
//   "5",
//   "2 5 1 4 3",
//   "",
// ];

// testCase.splice(-1, 1);
// solve(testCase);

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL);
  lines.slice(-1);
  solve(lines.slice(-1));
});

function solve(lines) {
  // console.log(lines);
  const numProblems = lines[0];
  let moves = [];

  for (let problem = 1; problem <= numProblems; problem++) {
    moves = [];
    const str = lines[problem * 2];
    let arr = str.split(" ");

    const sorted = [...arr];
    sorted.sort();

    let a = 0;
    let cur = sorted[0];

    for (let i = 0; i < arr.length; i++) {
      if (arr[i] === cur) {
        if (i - a > 0) {
          const diff = i - a;
          moves.push(`${a + 1} ${i + 1} ${diff}`);
          let newArr = [...arr];

          const len = i - a + 1;

          for (let x = 0; x < len; x++) {
            let q = x + diff;
            if (q >= len) {
              q = q % len;
            }
            // console.log(x, q);
            newArr[x + a] = arr[q + a];
          }
          // console.log(arr, newArr);
          arr = newArr;
        }

        a += 1;
        i = a - 1;
        cur = sorted[a];
      }
    }
    console.log(moves.length);
    moves.forEach((str) => console.log(str));
  }

  process.exit(0);
}

// const testCase = [
//   "4",
//   "2",
//   "2 1",
//   "3",
//   "1 2 1",
//   "4",
//   "2 4 1 3",
//   "5",
//   "2 5 1 4 3",
//   "",
// ];

// testCase.splice(-1, 1);
// solve(testCase);

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL);
  ines.slice(-1);
  solve(lines.slice(-1));
});

function solve(lines) {
  // console.log(lines);
  const numProblems = lines[0];
  let moves = [];

  for (let problem = 1; problem <= numProblems; problem++) {
    moves = [];
    const str = lines[problem * 2];
    let arr = str.split(" ");

    const sorted = [...arr];
    sorted.sort();

    let a = 0;
    let cur = sorted[0];

    for (let i = 0; i < arr.length; i++) {
      if (arr[i] === cur) {
        if (i - a > 0) {
          const diff = i - a;
          moves.push(`${a + 1} ${i + 1} ${diff}`);
          let newArr = [...arr];

          const len = i - a + 1;

          for (let x = 0; x < len; x++) {
            let q = x + diff;
            if (q >= len) {
              q = q % len;
            }
            // console.log(x, q);
            newArr[x + a] = arr[q + a];
          }
          // console.log(arr, newArr);
          arr = newArr;
        }

        a += 1;
        i = a - 1;
        cur = sorted[a];
      }
    }
    console.log(moves.length);
    moves.forEach((str) => console.log(str));
  }

  process.exit(0);
}

const testCase = [
  "4",
  "2",
  "2 1",
  "3",
  "1 2 1",
  "4",
  "2 4 1 3",
  "5",
  "2 5 1 4 3",
  "",
];

testCase.splice(-1, 1);
solve(testCase);

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL);
  ines.slice(-1);
  solve(lines.slice(-1));
});

function solve(lines) {
  // console.log(lines);
  const numProblems = lines[0];
  let moves = [];

  for (let problem = 1; problem < numProblems; problem++) {
    moves = [];
    const str = lines[problem * 2];
    let arr = str.split(" ");

    const sorted = [...arr];
    sorted.sort();

    let a = 0;
    let cur = sorted[0];

    for (let i = 0; i < arr.length; i++) {
      // console.log("test", i, a, arr[i], cur);
      if (arr[i] === cur) {
        if (i - a > 0) {
          const diff = i - a;
          moves.push(`${a + 1} ${i + 1} ${diff}`);
          let newArr = [...arr];
          for (let x = a; x <= i; x++) {
            let q = x + diff;
            if (q > i) {
              q = (q % (i - a + 1)) + a;
            }
            newArr[x] = arr[q];
          }
          // console.log(arr, newArr);
          arr = newArr;
        }
        a += 1;
        i = a - 1;
        cur = sorted[a];
      }
    }
    console.log(moves.length);
    moves.forEach((str) => console.log(str));
  }
  console.log(moves.length);
  moves.forEach((str) => console.log(str));

  process.exit(0);
}

const testCase = [
  "4",
  "2",
  "2 1",
  "3",
  "1 2 1",
  "4",
  "2 4 1 3",
  "5",
  "2 5 1 4 3",
  "",
];

testCase.splice(-1, 1);
solve(testCase);

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL);
  solve(lines);
});

function solve(lines) {
  console.log(lines);
  const problems = lines[0];
  let moves = [];
  for (let problem = 1; problem < problems; problem++) {
    const str = lines[problem * 2];
    const arr = str.split(" ");

    const sorted = [...arr];
    sorted.sort();

    let a = 0;
    let cur = sorted[0];

    for (let i = a; i < arr.length; i++) {
      if (arr[i] === cur) {
        if (i - a > 0) {
          moves.push(`${a + 1} ${i + 1} ${i - a}`);
        }
        a++;
        cur = sorted[a];
        i = a;
        // console.log("Cur", cur);
      }
    }
    console.log(moves.length);
    moves.forEach((str) => console.log(str));
  }
  console.log(moves.length);
  moves.forEach((str) => console.log(str));
  process.exit(0);
}

// const test = [
//   "4",
//   "2",
//   "2 1",
//   "3",
//   "1 2 1",
//   "4",
//   "2 4 1 3",
//   "5",
//   "2 5 1 4 3",
//   "",
// ];

// solve(test);

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL);
  solve(lines);
});

function solve(lines) {
  // console.log(lines);
  const problems = lines[0];
  let moves = [];
  for (let problem = 1; problem < problems; problem++) {
    const str = lines[problem * 2];
    const arr = str.split(" ");

    const sorted = [...arr];
    sorted.sort();

    let a = 0;
    let cur = sorted[0];

    for (let i = a; i < arr.length; i++) {
      if (arr[i] === cur) {
        if (i - a > 0) {
          moves.push(`${a + 1} ${i + 1} ${i - a}`);
        }
        a++;
        cur = sorted[a];
        i = a;
        // console.log("Cur", cur);
      }
    }
    console.log(moves.length);
    moves.forEach((str) => console.log(str));
  }
  console.log(moves.length);
  moves.forEach((str) => console.log(str));
  process.exit(0);
}

// const test = [
//   "4",
//   "2",
//   "2 1",
//   "3",
//   "1 2 1",
//   "4",
//   "2 4 1 3",
//   "5",
//   "2 5 1 4 3",
//   "",
// ];

// solve(test);

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL);
  solve(lines);
});

function solve(lines) {
  // console.log(lines);
  const problems = lines[0];
  let moves = [];
  for (let problem = 1; problem < problems; problem++) {
    const str = lines[problem * 2];
    const arr = str.split(" ");

    const sorted = [...arr];
    sorted.sort();

    let a = 0;
    let cur = sorted[0];

    for (let i = a; i < arr.length; i++) {
      if (arr[i] === cur) {
        moves.push(`${a + 1} ${i + 1} ${i - a}`);
        a++;
        cur = sorted[a];
        i = a;
        // console.log("Cur", cur);
      }
    }
    console.log(moves.length);
    moves.forEach((str) => console.log(str));
  }
  console.log(moves.length);
  moves.forEach((str) => console.log(str));
  process.exit(0);
}

// const test = [
//   "4",
//   "2",
//   "2 1",
//   "3",
//   "1 2 1",
//   "4",
//   "2 4 1 3",
//   "5",
//   "2 5 1 4 3",
//   "",
// ];

// solve(test);

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL);
  solve(lines);
});

function solve(lines) {
  // console.log(lines);
  const problems = lines[0];
  let moves = [];
  for (let problem = 1; problem < problems; problem++) {
    const str = lines[problem * 2];
    const arr = str.split(" ");

    const sorted = [...arr];
    sorted.sort();

    let a = 0;
    let cur = sorted[0];

    for (let i = a; i < arr.length; i++) {
      if (arr[i] === cur) {
        moves.push(`${a + 1} ${i + 1} ${i + 1 - a + 1}`);
        a++;
        cur = sorted[a];
        i = a;
        // console.log("Cur", cur);
      }
    }
    console.log(moves.length);
    moves.forEach((str) => console.log(str));
  }
  console.log(moves.length);
  moves.forEach((str) => console.log(str));
  process.exit(0);
}

// const test = [
//   "4",
//   "2",
//   "2 1",
//   "3",
//   "1 2 1",
//   "4",
//   "2 4 1 3",
//   "5",
//   "2 5 1 4 3",
//   "",
// ];

// solve(test);

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL);
  solve(lines);
});

function solve(lines) {
  // console.log(lines);
  const problems = lines[0];
  let moves = [];
  for (let problem = 1; problem < problems; problem++) {
    const str = lines[problem * 2];
    const arr = str.split(" ");

    const sorted = [...arr];
    sorted.sort();

    let a = 0;
    let cur = sorted[0];

    for (let i = a; i < arr.length; i++) {
      if (arr[i] === cur) {
        moves.push(`${a} ${i} ${i - a}`);
        a++;
        cur = sorted[a];
        i = a;
        // console.log("Cur", cur);
      }
    }
    console.log(moves.length);
    moves.forEach((str) => console.log(str));
  }
  console.log(moves.length);
  moves.forEach((str) => console.log(str));
  process.exit(0);
}

// const test = [
//   "4",
//   "2",
//   "2 1",
//   "3",
//   "1 2 1",
//   "4",
//   "2 4 1 3",
//   "5",
//   "2 5 1 4 3",
//   "",
// ];

// solve(test);

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL);
  solve(lines);
});

function solve(lines) {
  // console.log(lines);
  const problems = lines[0];
  for (let problem = 1; problem < problems; problem++) {
    const str = lines[problem * 2];
    const arr = str.split(" ");

    const sorted = [...arr];
    sorted.sort();

    let a = 0;
    let cur = sorted[0];
    // console.log("Cur", cur);

    for (let i = a; i < arr.length; i++) {
      if (arr[i] === cur) {
        console.log(`${a} ${i} ${i - a}`);
        a++;
        cur = sorted[a];
        i = a;
      }
    }
  }
  process.exit(0);
}

// const test = [
//   "4",
//   "2",
//   "2 1",
//   "3",
//   "1 2 1",
//   "4",
//   "2 4 1 3",
//   "5",
//   "2 5 1 4 3",
//   "",
// ];

// solve(test);

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL);
  solve(lines);
});

function solve(lines) {
  // console.log(lines);
  const problems = parseInt(lines[0]);
  for (let problem = 1; problem < problems; problem++) {
    const str = lines[problem * 2];
    const arr = str.split(" ");

    const sorted = new Array(arr);
    sorted.sort();

    let a = 0;
    let cur = sorted[0];

    for (let i = a; i < arr.length; i++) {
      console.log(i);
      if (arr[i] === cur) {
        console.log(a + " " + i + " " + i - a);
        a++;
        cur = sorted[a];
        i = a;
      }
    }
  }
  console.log("done");
}

// const test = [
//   "4",
//   "2",
//   "2 1",
//   "3",
//   "1 2 1",
//   "4",
//   "2 4 1 3",
//   "5",
//   "2 5 1 4 3",
//   "",
// ];

// solve(test);

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL);
  console.log(lines);
});

console.log("Testing");

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

function readline() {
  return inputString[currentLine++];
}

const main = () => {
  let ansArr = []
  const a = readline();
  for (let i = 0; i < a; i++) {
    let c = []
    let k = readline();
    let arr = readline().split(' ').map(el=>Number(el))
    let sorted = [...arr].sort((a,b)=>a-b);
    for (let j = 0; j <sorted.length ; j++) {
      let index = arr.findIndex((el)=>el===sorted[j]);
      if (index === j ) continue
      arr =[ ...arr.slice(0,index) , ...arr.slice(index + 1), sorted[j]]
      c.push('' + (index+1) + ' ' +  sorted.length + ' ' + 1);
    }
    ansArr.push(c.length + '\n' + c.join('\n'))
  }
  process.stdout.write(ansArr.join('\n'))

}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

function readline() {
  return inputString[currentLine++];
}

const main = () => {
  let ansArr = []
  const a = readline();
  for (let i = 0; i < a; i++) {
    let c = []
    let k = readline();
    let arr = readline().split(' ').map(el=>Number(el))
    let sorted = [...arr].sort((a,b)=>a-b);
    for (let j = 0; j <sorted.length ; j++) {
      let index = arr.findIndex((el)=>el===sorted[j]);
      arr =[ ...arr.slice(0,index) , ...arr.slice(index + 1), sorted[j]]
      c.push('' + (index+1) + ' ' +  sorted.length + ' ' + 1);
    }
    ansArr.push(c.length + '\n' + c.join('\n'))
  }
  process.stdout.write(ansArr.join('\n'))

}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

function readline() {
  return inputString[currentLine++];
}

const main = () => {
  let ansArr = []
  const a = readline();
  for (let i = 0; i < a; i++) {
    let c = []
    let k = readline();
    let arr = readline().split(' ').map(el=>Number(el))
    let sorted = [...arr].sort((a,b)=>a-b);
    for (let j = 0; j < sorted.length; j++) {
      let index = arr.findIndex((el)=>el===sorted[j]);
      if (index === j) continue
      if (index < j){
        let swp = arr[j];
        arr[j] = sorted[j];
        arr[index] = swp
      } else {
        let mid = arr.slice(j,index+1);
        mid.unshift(mid.pop())
        arr = [...arr.slice(0, j), ...mid, ...arr.slice(index+1)]
      }
      c.push('' + Math.min((j+1), (index+1)) + ' ' +  Math.max((j+1), (index+1)) + ' ' + (index < j ? 1 : index-j));
    }
    ansArr.push(c.length + '\n' + c.join('\n'))
  }
  process.stdout.write(ansArr.join('\n'))

}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

function readline() {
  return inputString[currentLine++];
}

const main = () => {
  let ansArr = []
  const a = readline();
  for (let i = 0; i < a; i++) {
    let c = []
    let k = readline();
    let arr = readline().split(' ').map(el=>Number(el))
    let sorted = [...arr].sort((a,b)=>a-b);
    for (let j = 0; j < sorted.length; j++) {
      let index = arr.findIndex((el)=>el===sorted[j]);
      if (index === j) continue
      if (index < j){
        let swp = arr[j];
        arr[j] = sorted[j];
        arr[index] = swp
      } else {
        arr = [...arr.slice(0, j), ...arr.slice(j,index+1).reverse(), ...arr.slice(index+1)]
      }
      c.push('' + Math.min((j+1), (index+1)) + ' ' +  Math.max((j+1), (index+1)) + ' ' + (index < j ? 1 : index-j));
    }
    ansArr.push(c.length + '\n' + c.join('\n'))
  }
  process.stdout.write(ansArr.join('\n'))

}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

function readline() {
  return inputString[currentLine++];
}

const main = () => {
  let ansArr = []
  const a = readline();
  for (let i = 0; i < a; i++) {
    let c = []
    let k = readline();
    let arr = readline().split(' ').map(el=>Number(el))
    let sorted = [...arr].sort((a,b)=>a-b);
    for (let j = 0; j < sorted.length; j++) {
      let index = arr.findIndex((el)=>el===sorted[j]);
      if (index === j) continue
      if (index < j){
        let swp = arr[j];
        arr[j] = sorted[j];
        arr[index] = swp
      } else {
        arr = [...arr.slice(0, j), ...arr.slice(j,index+1).reverse(), ...arr.slice(index+1)]
      }
      c.push('' + (index+1) + ' ' +  (j+1) + ' ' + (index < j ? 1 : index-j));
    }
    ansArr.push(c.length + '\n' + c.join('\n'))
  }
  process.stdout.write(ansArr.join('\n'))

}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

function readline() {
  return inputString[currentLine++];
}

const main = () => {
  let ansArr = []
  const a = readline();
  for (let i = 0; i < a; i++) {
    let c = []
    let k = readline();
    let arr = readline().split(' ').map(el=>Number(el))
    let sorted = [...arr].sort((a,b)=>a-b);
    for (let j = 0; j < sorted.length; j++) {
      let index = arr.findIndex((el)=>el===sorted[j]);
      if (index === j) continue
      let swp = arr[j];
      arr[j] = sorted[j];
      arr[index] = swp
      c.push('' + Math.min(j+1, index+1) + ' ' +  Math.max(j+1, index+1) + ' ' + 1);
    }
    ansArr.push(c.length + '\n' + c.join('\n'))
  }
  process.stdout.write(ansArr.join('\n'))

}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

function readline() {
  return inputString[currentLine++];
}

const main = () => {
  let ansArr = []
  const a = readline();
  for (let i = 0; i < a; i++) {
    let c = []
    let k = readline();
    let arr = readline().split(' ').map(el=>Number(el))
    let sorted = [...arr].sort((a,b)=>a-b);
    for (let j = 0; j < sorted.length; j++) {
      let index = arr.findIndex((el)=>el===sorted[j]);
      if (index === j) continue
      let swp = arr[j];
      arr[j] = sorted[j];
      arr[index] = swp
      c.push('' + (j+1) + ' ' +  (index+1) + ' ' + 1);
    }
    ansArr.push(c.length + '\n' + c.join('\n'))
  }
  process.stdout.write(ansArr.join('\n'))

}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

function readline() {
  return inputString[currentLine++];
}

const main = () => {
  let ansArr = []
  const a = readline();
  for (let i = 0; i < a; i++) {
    let c = []
    let k = readline();
    let arr = readline().split(' ').map(el=>Number(el))
    let sorted = [...arr].sort((a,b)=>a-b);
    for (let j = 0; j < sorted.length; j++) {
      let index = arr.findIndex((el)=>el===sorted[j]);
      if (index === j) continue
      let swp = arr[j];
      arr[j] = sorted[j];
      arr[index] = swp
      c.push('' + (j+1) + ' ' +  (index+1) + ' ' + 1);
    }
    console.log(arr);
    ansArr.push(c.length + '\n' + c.join('\n'))
  }
  process.stdout.write(ansArr.join('\n'))

}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

function readline() {
  return inputString[currentLine++];
}

const main = () => {
  let ansArr = []
  const a = readline();
  for (let i = 0; i < a; i++) {
    let c = []
    let k = readline();
    let arr = readline().split(' ').map(el=>Number(el))
    let sorted = [...arr].sort((a,b)=>a-b);
    for (let j = 0; j < sorted.length; j++) {
      let index = arr.findIndex((el)=>el===sorted[j]);
      if (index === j) continue
      let swp = arr[j];
      arr[j] = sorted[j];
      arr[index] = swp
      c.push('' + (index+1) + ' ' +  (j+1) + ' ' + 1);
    }
    ansArr.push(c.length + '\n' + c.join('\n'))
  }
  process.stdout.write(ansArr.join('\n'))

}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const t = Number(readline());
    for(let i = 0; i < t; i++) {
        const n = Number(readline());
        const myArr = readline().split(" ");
        const ans = [];
        for(let i = 0; i < n - 1; i++) {
            let minIndex = i;
            for(let j = i; j < n; j++) {
                if(myArr[j] < myArr[minIndex]) minIndex = j;
            }
            if(0 < minIndex - i) {
                ans.push((i + 1) + " " + n + " " + (minIndex - i));
                myArr.splice(i,n - i,...shift(myArr.slice(i), minIndex - i));
            }
        }
        console.log(ans.length);
        ans.forEach(str => console.log(str));
    }
}

function shift(arr, shiftValue) {
    const newArr = [...arr];
    const n = arr.length;
    for(let i = 0; i < n; i++) {
        let newIndex = i - shiftValue;
        if(0 <= newIndex) newArr[newIndex] = arr[i];
        else newArr[n + newIndex] = arr[i];
    }
    return newArr;
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const t = Number(readline());
    for(let i = 0; i < t; i++) {
        const n = Number(readline());
        const myArr = readline().split(" ");
        const ans = [];
        for(let i = 0; i < n - 1; i++) {
            let minIndex = i;
            for(let j = i; j < n; j++) {
                if(myArr[j] < myArr[minIndex]) minIndex = j;
            }
            if(0 < minIndex - i) ans.push((i + 1) + " " + n + " " + (minIndex - i));
            myArr.splice(i,n - i,...shift(myArr.slice(i), minIndex - i));
        }
        console.log(ans.length);
        ans.forEach(str => console.log(str));
    }
}

function shift(arr, shiftValue) {
    const newArr = [...arr];
    const n = arr.length;
    for(let i = 0; i < n; i++) {
        let newIndex = i - shiftValue;
        if(0 <= newIndex) newArr[newIndex] = arr[i];
        else newArr[n + newIndex] = arr[i];
    }
    return newArr;
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const t = Number(readline());
    for(let i = 0; i < t; i++) {
        const n = Number(readline());
        const myArr = readline().split(" ");
        const ans = [];
        for(let i = 0; i < n - 1; i++) {
            let minIndex = i;
            for(let j = i; j < n; j++) {
                if(myArr[j] < myArr[minIndex]) minIndex = j;
            }
            ans.push((i + 1) + " " + n + " " + (minIndex - i));
            myArr.splice(i,n - i,...shift(myArr.slice(i), minIndex - i));
        }
        console.log(n - 1);
        ans.forEach(str => console.log(str));
    }
}

function shift(arr, shiftValue) {
    const newArr = [...arr];
    const n = arr.length;
    for(let i = 0; i < n; i++) {
        let newIndex = i - shiftValue;
        if(0 <= newIndex) newArr[newIndex] = arr[i];
        else newArr[n + newIndex] = arr[i];
    }
    return newArr;
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function main() {
   const t = parseInt(readline());
   for (let m = 0; m < t; m++){
        const n = parseInt(readline());

        const arr = readline().split(' ').map((str) => parseInt(str));
        let count = 0;
        const moves = [];
        for(let index = 0; index < n; index++){

          let min = index;

          for(let i = index; i < n; i++){
             if (arr[i] < arr[min]) {
                min = i;
             }
          }
          if(min !== index){
            let t = arr[min];
            for(let j = index; j < min; j++){
              let p = arr[index];
              arr[index] = t;
              t = p;
            }
            count++;
            moves.push(`${index + 1} ${min + 1} 1`);
          }
        }

        console.log(count);
        console.log(moves.join('\n'));
   }

}


function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function printValues() {
	var parts = [];
	for (var i = 0; i < arguments.length; i += 2) {
		parts.push(arguments[i]+' = '+arguments[i+1]);
	}
	print(parts.join(', '));
}

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], m = data[1],
    v2v = {};
  if (n != m) {
    print('NO');
    return;
  }
  function augment(u, v) {
    if (v2v[u] === undefined) {
      v2v[u] = [v];
    } else {
      v2v[u].push(v);
    }
  }
  for (var i = 0; i < m; ++i) {
    data = tokenizeIntegers(readline());
    var x = data[0], y = data[1];
    augment(x, y);
    augment(y, x);
  }
  var count = 0,
      seen = {};
  function visit(u) {
    if (seen[u]) {
      return;
    }
    seen[u] = true;
    count += 1;
    var vs = v2v[u];
    if (vs === undefined) {
      return;
    }
    for (var i = 0; i < vs.length; ++i) {
      visit(vs[i]);
    }
  }
  visit(1);
  print(count == n ? 'FHTAGN!' : 'NO');
}

main();

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function printValues() {
	var parts = [];
	for (var i = 0; i < arguments.length; i += 2) {
		parts.push(arguments[i]+' = '+arguments[i+1]);
	}
	print(parts.join(', '));
}

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], m = data[1],
    v2v = {};
  if (n != m) {
    print('NO');
    return;
  }
  function augment(u, v) {
    if (v2v[u] === undefined) {
      v2v[u] = [v];
    } else {
      v2v[u].push(v);
    }
  }
  for (var i = 0; i < m; ++i) {
    data = tokenizeIntegers(readline());
    var x = data[0], y = data[1];
    augment(x, y);
    augment(y, x);
  }
  var seen = {},
      cycle = [],
      found = false;
  function search(u, parent) {
    if (seen[u]) {
      cycle.push(u);
      return true;
    }
    seen[u] = true;
    count += 1;
    var vs = v2v[u];
    if (vs === undefined) {
      return;
    }
    for (var i = 0; i < vs.length; ++i) {
      var v = vs[i];
      if (v == parent) {
        continue;
      }
      if (search(v, u)) {
        if (cycle[0] == u) {
          found = true;
        }
        if (!found) {
          cycle.push(u);
        }
        return true;
      }
    }
    return false;
  }
  search(1, -1);
  if (cycle.length < 3) {
    print('NO');
    return;
  }
  var count = 0;
  seen = {};
  function visit(u) {
    if (seen[u]) {
      return;
    }
    seen[u] = true;
    count += 1;
    var vs = v2v[u];
    for (var i = 0; i < vs.length; ++i) {
      visit(vs[i]);
    }
  }
  visit(cycle[0]);
  print(count == n ? 'FHTAGN!' : 'NO');
}

main();

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function printValues() {
	var parts = [];
	for (var i = 0; i < arguments.length; i += 2) {
		parts.push(arguments[i]+' = '+arguments[i+1]);
	}
	print(parts.join(', '));
}

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], m = data[1],
    v2v = {};
  if (n != m) {
    print('NO');
    return;
  }
  function augment(u, v) {
    if (v2v[u] === undefined) {
      v2v[u] = [v];
    } else {
      v2v[u].push(v);
    }
  }
  for (var i = 0; i < m; ++i) {
    data = tokenizeIntegers(readline());
    var x = data[0], y = data[1];
    augment(x, y);
    augment(y, x);
  }
  var seen = {},
      cycle = [],
      done = false;
  function findCycle(u, parent) {
    if (seen[u]) {
      cycle.push(u);
      return true;
    }
    seen[u] = true;
    count += 1;
    var vs = v2v[u];
    if (vs === undefined) {
      return;
    }
    for (var i = 0; i < vs.length; ++i) {
      var v = vs[i];
      if (v == parent) {
        continue;
      }
      if (findCycle(v, u)) {
        if (cycle[0] == u) {
          done = true;
        }
        if (!done) {
          cycle.push(u);
        }
        return true;
      }
    }
    return false;
  }
  findCycle(1, -1);
  if (cycle.length < 3) {
    print('NO');
    return;
  }
  var count = 0;
  seen = {};
  function visit(u) {
    if (seen[u]) {
      return;
    }
    seen[u] = true;
    count += 1;
    var vs = v2v[u];
    for (var i = 0; i < vs.length; ++i) {
      visit(vs[i]);
    }
  }
  visit(cycle[0]);
  print(count == n ? 'FHTAGN!' : 'NO');
}

main();

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function printValues() {
	var parts = [];
	for (var i = 0; i < arguments.length; i += 2) {
		parts.push(arguments[i]+' = '+arguments[i+1]);
	}
	print(parts.join(', '));
}

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], m = data[1],
    v2v = {};
  function augment(u, v) {
    if (v2v[u] === undefined) {
      v2v[u] = [v];
    } else {
      v2v[u].push(v);
    }
  }
  for (var i = 0; i < m; ++i) {
    data = tokenizeIntegers(readline());
    var x = data[0], y = data[1];
    augment(x, y);
    augment(y, x);
  }
  var seen = {},
      cycle = [],
      found = false;
  function search(u, parent) {
    //print('u = '+u+', parent = '+parent);
    if (seen[u]) {
      cycle.push(u);
      return true;
    }
    seen[u] = true;
    count += 1;
    var vs = v2v[u];
    for (var i = 0; i < vs.length; ++i) {
      var v = vs[i];
      if (v == parent) {
        continue;
      }
      if (search(v, u)) {
        if (cycle[0] == u) {
          found = true;
        }
        if (!found) {
          cycle.push(u);
        }
        return true;
      }
    }
    return false;
  }
  for (var u = 1; u <= n; ++u) {
    if (v2v[u] !== undefined) {
      search(u, -1);
      break;
    }
  }
  //print(found);
  //print(cycle.join(' '));
  if (cycle.length < 3 || n != m) {
    print('NO');
    return;
  }
  var count = 0;
  seen = {};
  function visit(u) {
    if (seen[u]) {
      return;
    }
    seen[u] = true;
    count += 1;
    var vs = v2v[u];
    for (var i = 0; i < vs.length; ++i) {
      visit(vs[i]);
    }
  }
  visit(cycle[0]);
  print(count == n ? 'FHTAGN!' : 'NO');
}

main();

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function printValues() {
	var parts = [];
	for (var i = 0; i < arguments.length; i += 2) {
		parts.push(arguments[i]+' = '+arguments[i+1]);
	}
	print(parts.join(', '));
}

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], m = data[1],
    v2v = {};
  function augment(u, v) {
    if (v2v[u] === undefined) {
      v2v[u] = [v];
    } else {
      v2v[u].push(v);
    }
  }
  for (var i = 0; i < m; ++i) {
    data = tokenizeIntegers(readline());
    var x = data[0], y = data[1];
    augment(x, y);
    augment(y, x);
  }
  var seen = {},
      cycle = [],
      found = false,
      deleted = {};
  function search(u, parent) {
    //print(u, parent);
    if (seen[u]) {
      cycle.push(u);
      return true;
    }
    seen[u] = true;
    var vs = v2v[u];
    for (var i = 0; i < vs.length; ++i) {
      var v = vs[i];
      if (v == parent || deleted[[u, v]]) {
        continue;
      }
      if (search(v, u)) {
        if (cycle[0] == u) {
          found = true;
        }
        if (!found) {
          cycle.push(u);
        }
        return true;
      }
    }
    return false;
  }
  for (var u = 1; u <= n; ++u) {
    if (v2v[u] !== undefined) {
      search(u, -1);
      break;
    }
  }
  //print(found);
  //print(cycle.join(' '));
  if (cycle.length < 3 || n != m) {
    print('NO');
    return;
  }
  for (var i = 0; i < cycle.length; ++i) {
    var u = cycle[i], v = cycle[(i+1)%cycle.length];
    deleted[[u, v]] = deleted[[v, u]] = true;
  }
  for (var u = 1; u <= n; ++u) {
    if (v2v[u] !== undefined) {
      seen = {};
      cycle = [];
      found = false;
      search(u, -1);
      if (found) {
        //print('found a cycle starting from '+u);
        //print(cycle.join(' '));
        print('NO');
        return;
      }
    }
  }
  print('FHTAGN!');
}

main();