text:
Gerrymander North Carolina
The challenge
How well can you gerrymander North Carolina into 13 voting districts?
In this challenge, you use the following files to draw different maps for Republicans and Democrats.
File 1: NC_2016_presidential_election.csv
File 2: NC_county_adjacency.csv
File 1 gives county-level voting data from the 2016 presidential election (based on this and that), while File 2 gives adjacency information between counties (based on this). For File 2, the first entry of each row is adjacent to the other entries in that row. For example, Alexander is adjacent to Alexander, Caldwell, Catawba, Iredell and Wilkes. (Note that every county is adjacent to itself.)
Admissibility
Your code should be written in a way that can gerrymander arbitrary maps. In particular, your code must take each of the following as inputs:

A set \$C\$ of counties and a set \$P\$ of parties.
Weights \$(v_{cp})\$ that count voters in county \$c\in C\$ who vote for party \$p\in P\$. (E.g., File 1.)
A connected graph \$G\$ with vertex set \$C\$. (E.g., File 2.)
A number of districts \$k\$.
A party \$p^\star\in P\$ to gerrymander in favor of.

The output must be an assignment of counties to districts such that the counties in each district induce a connected subgraph of \$G\$. For example, for the counties in Files 1 and 2 (listed in alphabetical order), the following is one of 13! sequences that specify the partition of counties into districts pictured below:
3,5,5,10,5,5,13,11,10,8,9,12,1,12,13,13,3,9,3,12,13,12,9,8,13,10,13,13,4,4,8,11,11,5,7,9,11,12,11,13,4,11,7,12,12,11,1,13,4,12,7,13,3,13,9,12,12,11,12,2,12,1,1,7,8,11,13,3,13,13,8,13,3,11,9,3,10,10,3,1,9,8,10,1,5,5,12,12,13,10,11,6,11,11,5,8,5,7,5,12

(This map is loosely based on the current map of U.S. congressional districts in North Carolina.)
Scoring
Your score is determined by how your code performs for various problem instances.
Given a district assignment, let \$d\$ denote the number of districts for which party \$p^\star\$ receives the plurality of votes cast, and let \$a\$ and \$b\$ denote the minimum and maximum number of voters in a district, respectively. Then the score for the district assignment is given by
$$ \text{assignment score} = d - \frac{b}{a}. $$
For example, if \$p^\star\$ is the Republican party, then the district assignment described above has \$d=10\$, \$a=247739\$, and \$b=527337\$, leading to a score of about \$7.87\$.
To compute your score, gerrymander North Carolina (as specified in Files 1 and 2) into \$k=13\$ districts in favor of the Republican party, and then in favor of the Democratic party. Let \$S_1\$ denote the sum of these two assignment scores. Next, gerrymander 10 different modifications of North Carolina, each obtained by removing one of the following counties from Files 1 and 2:
Cleveland,Davidson,Hyde,Johnston,Madison,Montgomery,Pender,Scotland,Warren,Wilkes

(Since North Carolina is biconnected, each of these are acceptable problem instances.) For each modification, gerrymander into \$k=13\$ districts in favor of the Republican party, and then in favor of the Democratic party. Let \$S_2\$ denote the sum of these 20 assignment scores. Then the score of your submission is given by
$$ \text{submission score} = S_1+\frac{S_2}{10}. $$
In addition to your code, you are encouraged to provide an illustration of your two maps that gerrymander all of North Carolina for Republicans and for Democrats. (DRA2020 might be a helpful resource.)

Does my solution have to halt before the heat death of the universe? If not, I know a proven perfect algorithm! While we won't know its score, it's known it's perfect anyway.

@someone - Feel free to submit your solution when it terminates. ;)

I posit that any given algorithm should complete in no more than 4 years. ;)

I feel this question needs a bounty.

@Anush I'm working on an answer...

C++, score = 33.526203, all test cases in 2min34s
(of course, the score can be improved by running the program for more time; please do not do that to claim a victory or something)
That score is usually 11 won districts for the Republicans and from 9 to 11 for the Democrats.
In this revision, the score decreased significantly, because I found some really large bugs in the input parsing. My program also verifies its solution now.
//#define _GLIBCXX_DEBUG
#include <iostream>
#include <streambuf>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <bitset>
#include <cassert>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cmath>
#include <climits>
#include <random>
#include <set>
#include <map>
#include <deque>
#include <string>

constexpr uint64_t rotl(uint64_t x, char k)
{
    return (x<<k) | (x>>(64-k)); //typo of the day: replace the >> with <<
}
uint64_t xs128()
{
    static uint64_t s_0 = 0, s_1 = 1;
    const uint64_t s0 = s_0;
    uint64_t s1 = s_1;
    uint64_t res = s0 + s1;
    s1 ^= s0;
    s_0 = rotl(s0, 24) ^ s1 ^ (s1 << 16);
    s_1 = rotl(s1, 37);
    return res >> 4;
}
std::vector<std::string> getCsvLine(std::istream& str)
{
    https://stackoverflow.com/a/1120224 - saved some time writing a parser...
    std::vector<std::string> result;
    std::string line; std::getline(str,line);
    std::stringstream lineStream(line);
    std::string cell;
    while(std::getline(lineStream,cell, ','))
        result.push_back(cell);
    return result;
}
struct county
{
    int good = 0;
    int sum = 0;
    std::vector<int> others;
    std::string name;
};
struct district
{
    int good = 0;
    int sum = 0;
    std::vector<int> others;
    void operator += (county& rhs)
    {
        good += rhs.good; sum += rhs.sum;
        for(int i = 0; i < others.size(); i++)
            others[i] += rhs.others[i];
    }
    void operator -= (county& rhs)
    {
        good -= rhs.good; sum -= rhs.sum;
        for(int i = 0; i < others.size(); i++)
            others[i] -= rhs.others[i];
    }
};
//seems like exactly 100 districts exist, below CHAR_MAX
std::vector<std::vector<char>> graph;
std::vector<char> curdistrict;
std::vector<county> counties;
std::vector<district> districts;
std::vector<char> marks;
bool pluralityCheck(const district& d)
{
    return d.good > *std::max_element(d.others.begin(), d.others.end());
}
int n, k, excluded;
double getFitness(std::vector<char>& dmap)
{
    std::vector<district> districts(k);
    for(district& d : districts)
        d.others.resize(counties[excluded==0?1:0].others.size());
    for(int i = 0; i < n; i++)
        if(i != excluded) districts[dmap[i]] += counties[i];
    double score = 0;
    int min = INT_MAX, max = INT_MIN;
    for(int i = 0; i < k; i++)
        score += pluralityCheck(districts[i]),
        min = std::min(min, districts[i].sum), max = std::max(max, districts[i].sum);
    score -= double(max) / min;
    return score;
}
void dfs(char v, char color)
{
    marks[v] = color;
    for(int to : graph[v])
        if(marks[to] != color && curdistrict[to] == curdistrict[v])
            dfs(to, color);
}
bool dfsFor(char at, char target, char color)
{
    marks[at] = color;
    if(at == target) return true;
    if(at == excluded) return false;
    bool ans = false;
    for(int to : graph[at])
        if(marks[to] != color && curdistrict[to] == curdistrict[at])
            ans |= dfsFor(to, target, color);
    return ans;
}
bool isCutpoint(int v)
{
    static int call = 0;
    char color = call + 1;
    call = (call + 1) % 255;
    if(color == 1) for(char& el : marks) el = 0; //reset every 256 calls
    marks[v] = color;
    int calls = 0;
    for(char to : graph[v])
    {
        if(curdistrict[to] != curdistrict[v]) continue;
        if(marks[to] == color) continue;
        calls++;
        if(calls == 2) break;
        dfs(to, color);
    }
    return calls != 1; //0 -> kills a district, >=2 -> a cutpoint -> splits a district
}
std::map<std::string, int> dnamemap;
double solve(int n, int k, int target, int excluded)
{
    ::n = n; ::k = k; ::excluded = excluded;
    marks = std::vector<char>(n);
    curdistrict = std::vector<char>(n, -1); graph = std::vector<std::vector<char>>(n);
    districts = std::vector<district>(k); counties = std::vector<county>(n);
    dnamemap = std::map<std::string, int>();
    std::ifstream data("NC_2016_presidential_election.csv");
    getCsvLine(data); //skip header
    for(int i = 0; i < n; i++)
    {
        std::vector<std::string> row = getCsvLine(data);
        dnamemap[row[0]] = i;
        counties[i].name = row[0];
        if(i == excluded) continue;
        for(int j = 1; j < row.size(); j++)
        {
            int v = std::stoi(row[j]);
            if(j - 1 == target)
                counties[i].good = v;
            else counties[i].others.push_back(v);
            counties[i].sum += v;
        }

    }
    data = std::ifstream("NC_county2.csv"); //no header
    //NC_county2.csv is obtained by cat NC_county_adjacency.csv | sort | tr -d '\r'
    //the default counties file caused not one but TWO horrible parsing bugs
    //they silently increased the score.
    //There were \r\n line endings instead of \n, and my program mishandled them.
    //and *the worst*. It seems to be in alphabetic order, but it actually simply isn't.
    for(int i = 0; i < n; i++)
    {
        std::vector<std::string> row = getCsvLine(data);
        if(i == excluded) continue;
        for(int j = 1; j < row.size(); j++)
        {
            if(row[j] == row[0]) continue;
            int to = dnamemap[row[j]];
            if(to == excluded) continue;
            graph[i].push_back(to);
        }
    }
    for(district& d : districts)
        d.others.resize(counties[excluded==0?1:0].others.size());
    int di = 0;
    for(int i = 0; di < k; i++) if(i != excluded) curdistrict[i] = di++;
    for(int it = n; it --> 0;)
        for(int i = 0; i < n; i++)
        {
            if(i == excluded || curdistrict[i] != -1) continue;
            for(int to : graph[i])
            {
                if(to == excluded || curdistrict[to] == -1) continue;
                curdistrict[i] = curdistrict[to];
                break;
            }
        }
    if(excluded >= 0) curdistrict[excluded] = -1;
    for(int i = 0; i < n; i++) printf("%d ", curdistrict[i]);
    printf("%d\n", excluded);
    for(int i = 0; i < n; i++) if(excluded != i) districts[curdistrict[i]] += counties[i];
    double temp = 3;
    int its = 2e7;
    std::vector<char> bestplacement = curdistrict;
    std::vector<district> bestdistricts = districts;
    int lastimprovement = 0;
    double bestscore = getFitness(curdistrict);
    int perblock = 2e4; //max number of iterations without improvement
    double delta = 1.01 * temp / its;
    double curscore = bestscore;
    double withoutimprovement = 0;
    for(int it = 0; it < its; it++)
    {
        temp -= delta;
        if(it % 1048576 == 0)
            printf("it=%d, cs=%lf       \r", it, curscore);
        int i = xs128() % n;
        while(i == excluded) i = xs128() % n;
        if(isCutpoint(i)) continue; //<- around 50% of program time
        std::vector<int> nearby;
        bool ok = false;
        for(int to : graph[i])
            if(curdistrict[to] != curdistrict[i] && curdistrict[to] != -1) ok = true;
        if(!ok) continue;
        int nd = -1;
        while(nd == curdistrict[i] || nd == -1)
            nd = curdistrict[graph[i][xs128() % graph[i].size()]];
        //calculate new min size, new max size etc.
        //can be done via std::set and other tree-based stuff, but it's much simpler to use a normal arrays (for k=13)
        //*might* use a segment tree to optimize later, but it's not spending a lot of time here
        char oldmaj1 = pluralityCheck(districts[curdistrict[i]]);
        char newmaj1 = pluralityCheck(districts[nd]);
        int maxs = INT_MIN, mins = INT_MAX;
        for(int i = 0; i < k; i++)
            maxs = std::max(maxs, districts[i].sum), mins = std::min(mins, districts[i].sum);
        double pen1 = double(maxs) / mins;
        districts[curdistrict[i]] -= counties[i];
        districts[nd] += counties[i];
        char oldmaj2 = pluralityCheck(districts[curdistrict[i]]);
        char newmaj2 = pluralityCheck(districts[nd]);
        maxs = INT_MIN, mins = INT_MAX;
        for(int i = 0; i < k; i++)
            maxs = std::max(maxs, districts[i].sum), mins = std::min(mins, districts[i].sum);
        double pen2 = double(maxs) / mins;
        double delta = pen1 - pen2 + (oldmaj2 + newmaj2 - oldmaj1 - newmaj1);
        if(delta <= 0 && (temp <= 0 || ldexpf(std::exp(delta / temp), 60) < xs128()))
        {
            districts[nd] -= counties[i], districts[curdistrict[i]] += counties[i];
        }
        else
        {
            curdistrict[i] = nd;
            curscore += delta;
            if(curscore > bestscore)
            {
                bestscore = curscore; lastimprovement = it;
                bestplacement = curdistrict; withoutimprovement = 0;
                bestdistricts = districts;
            }
        }
        if(curscore < bestscore) withoutimprovement += bestscore - curscore;
        if(it - lastimprovement > perblock || withoutimprovement > 3e4)
        {
            //restart at best score so far
            withoutimprovement = 0;
            lastimprovement = it;
            curdistrict = bestplacement;
            districts = bestdistricts;
            curscore = bestscore;
        }
    }
    for(int i = 0; i < n; i++)
        printf("%d ", curdistrict[i]);
    printf("\n");
    for(district& d : districts)
    {
        printf("%d total, maj=%d, %d good; rest:", d.sum, (int)pluralityCheck(d), d.good);
        for(int el : d.others) printf(" %d", el);
        printf("\n");
    }
    for(int i = 0; i < n; i++) //verify validness
    for(int j = i+1; j < n; j++)
    {
        if(i == excluded || j == excluded) continue;
        if(curdistrict[i] != curdistrict[j]) continue;
        for(char& el : marks) el = 0;
        bool good = dfsFor(i, j, 1);
        if(!good) printf("invalid: i=%d, j=%d, d=%d!\n", i, j, curdistrict[i]);
    }
    double score = getFitness(curdistrict);
    printf("%lf\n", score);
    return score;
}
int main()//int64_t argc, char*argv[])
{
    //randomly choose and recolor vertices
    //do not recolor a vertex if it is a cutpoint (more known as an articulation point or cut vertex) or alone
    //to check, DFS over same-colored vertices from it. If != 1 calls were done, it's alone or a cutpoint
    //initial state: all counties belong to district 0, but first 13 belong to district i (dumb but why bother)
    //for each district maintain the voters for both parties and total number
    //oh, and don't merely randomly recolor: use Simulated Annealing (TM) (it actually improves a lot!)
    setbuf(stdout, 0);
    int k = 13, n = 100;
    std::vector<int> toExclude { -1, 22, 28, 47, 50, 57, 61, 70, 82, 92, 97 }; //the final score computing
    //std::vector<int> toExclude { -1 };
    double score = 0;
    for(int el : toExclude)
    {
        double s = 0;
        s += solve(n, k, 0, el);
        s += solve(n, k, 1, el);
        if(el == -1) score += s;
        else score += s / 10;
    }
    printf("%lf\n", score);
}

Uses (attempts to use) simulated annealing to improve from a dumb assignment by making random changes if they do not ruin things (that is, destroy or split districts). Restarts from the best known assignment when either 20000 iterations passed without an improvement or the accumulated difference between the best score and the current score since the last improvement exceeds 30000.
Can be compiled with clang++ hax.cpp -Ofast -march=native -flto -no-pie -o a.out. Assumes files NC_2016_presidential_election.csv and NC_county2.csv are in the current directory, where NC_county2.csv is the NC_county_adjacency.csv, but with its lines actually sorted in alphabetical order, and with Unix (\n) line endings.
Quoting from the question, "you are encouraged to provide an illustration". I am definitely encouraged (I would really like to know whether or not the code has no bugs), but I have no idea how to create an illustration. I also have no idea how to export the output into a format readable by the linked website.
Assignment information on the normal map for the Democrats, then for the Republicans:

begin assignment for target=0, excluded=-1
Alamance,4
Alexander,8
Alleghany,8
Anson,12
Ashe,8
Avery,5
Beaufort,6
Bertie,6
Bladen,9
Brunswick,9
Buncombe,5
Burke,10
Cabarrus,8
Caldwell,8
Camden,7
Carteret,9
Caswell,0
Catawba,10
Chatham,12
Cherokee,10
Chowan,7
Clay,10
Cleveland,10
Columbus,2
Craven,9
Cumberland,2
Currituck,7
Dare,7
Davidson,12
Davie,8
Duplin,6
Durham,12
Edgecombe,6
Forsyth,3
Franklin,7
Gaston,10
Gates,7
Graham,10
Granville,0
Greene,6
Guilford,4
Halifax,7
Harnett,12
Haywood,10
Henderson,10
Hertford,7
Hoke,2
Hyde,7
Iredell,8
Jackson,10
Johnston,12
Jones,6
Lee,12
Lenoir,6
Lincoln,11
Macon,10
Madison,10
Martin,6
McDowell,5
Mecklenburg,11
Mitchell,5
Montgomery,12
Moore,12
Nash,7
New Hanover,9
Northampton,7
Onslow,9
Orange,0
Pamlico,9
Pasquotank,7
Pender,9
Perquimans,7
Person,0
Pitt,6
Polk,10
Randolph,4
Richmond,12
Robeson,2
Rockingham,0
Rowan,8
Rutherford,10
Sampson,9
Scotland,2
Stanly,8
Stokes,0
Surry,3
Swain,10
Transylvania,10
Tyrrell,7
Union,8
Vance,7
Wake,1
Warren,7
Washington,6
Watauga,5
Wayne,9
Wilkes,8
Wilson,6
Yadkin,8
Yancey,10
end assignment for target=0, excluded=-1
begin assignment for target=1, excluded=-1
Alamance,0
Alexander,1
Alleghany,11
Anson,7
Ashe,11
Avery,10
Beaufort,6
Bertie,6
Bladen,8
Brunswick,12
Buncombe,10
Burke,10
Cabarrus,7
Caldwell,11
Camden,9
Carteret,6
Caswell,0
Catawba,1
Chatham,2
Cherokee,4
Chowan,9
Clay,4
Cleveland,4
Columbus,12
Craven,9
Cumberland,8
Currituck,6
Dare,6
Davidson,0
Davie,7
Duplin,9
Durham,0
Edgecombe,9
Forsyth,1
Franklin,6
Gaston,4
Gates,9
Graham,10
Granville,6
Greene,6
Guilford,11
Halifax,6
Harnett,8
Haywood,10
Henderson,4
Hertford,9
Hoke,2
Hyde,6
Iredell,7
Jackson,4
Johnston,8
Jones,9
Lee,2
Lenoir,9
Lincoln,10
Macon,4
Madison,10
Martin,9
McDowell,10
Mecklenburg,5
Mitchell,10
Montgomery,2
Moore,2
Nash,9
New Hanover,12
Northampton,9
Onslow,12
Orange,2
Pamlico,9
Pasquotank,6
Pender,12
Perquimans,6
Person,0
Pitt,6
Polk,4
Randolph,0
Richmond,7
Robeson,8
Rockingham,0
Rowan,2
Rutherford,4
Sampson,12
Scotland,2
Stanly,2
Stokes,11
Surry,11
Swain,10
Transylvania,4
Tyrrell,6
Union,7
Vance,6
Wake,3
Warren,9
Washington,6
Watauga,11
Wayne,9
Wilkes,1
Wilson,9
Yadkin,1
Yancey,10
end assignment for target=1, excluded=-1

You just answered it!

What's the max number in favour of the two parties from your code?

Uh, I think I mentioned that in the post (where it says "usually 11 for the Republicans and from 9 to 11 for the Democrats") (although I think I forgot to update that - more like from 9 to 10 for the Democrats after the bugfixes)

If you provide the district assignments of your Republican- and Democrat-gerrymandered maps, then someone (like me, say) might be able to obtain illustrations of your maps using the DRA2020 website.

That'd be very nice. Is a CSV with rows like Name,district_number good?

@mypronounismonicareinstate - Yes.


text:
Visualize a large int
Convert a large int (e. g. 1234567890) into a string containing the usual decimal prefixes k, M, G, T, etc. for kilo, mega, giga, tera, etc.  The result shall be groups of three digits, interspersed by the prefixes (e. g. 1G234M567k890), so that it is easy to glance the order of magnitude of the number without counting the digits.
It shall work for numbers of all digit counts up to 15.  Only non-negative numbers are allowed as input.
More test cases:
0 → 0
123 → 123
1234 → 1k234
1000 → 1k000
1000000000 → 1G000M000k000

@Arnauld Look at my example result.  It contains several prefixes, but if the number is small, it could also contain one or even none (for numbers below 100000 and below 1000).

Can I take the input as a string, since my language supports integers only up to 2^32?

you don't even need peta, because 15 digits is only up to tera. 123T 456G 789M 012k 345

@GalenIvanov If the language cannot handle integers up to 15 digits, the input can be a string representation of the number in decimal format.

So a block of 0s should still display? E.g., 1000234 -> 1M000k234

can we get more than 1 test case?

The number shall be displayed completely, just interspersed with the correct prefixes to ease orientation.  I will add more test cases.

"easy to glance the order of magnitude". I personally find 1G000M000k000 much harder to parse than 1 000 000 000

@EricDuminil I agree.  That's why in practice I would use ᵏᴹᴳᵀ as markers instead.   I find a 1ᵀ002ᴳ289ᴹ732ᵏ929 way better to read than the same with ASCII letters.  And if the colour for the letters also is set to something unobtrusive (grey, for instance), this effect is even improved.  This fancy Unicode thing brought me some criticism in my own answer, though (Python3 below).

JavaScript (ES6), 64 bytes
Takes input as a string.
f=(n,i=0,[d,t]=n.split(/(...)$/))=>t?f(d,i+1)+['kMGT'[d&&i]]+t:d

Try it online!
How?
The regular expression /(...)/$ matches the last three digits of the integer, or nothing at all if there are less than 3 digits remaining.
Because there's a capturing group, these digits -- if present -- are included in the output of the .split() method.
Examples:
'123456789'.split(/(...)$/) // --> [ '123456', '789' '' ]
'123'.split(/(...)$/))      // --> [ '', '123' ]
'12'.split(/(...)$/))       // --> [ '12' ]
''.split(/(...)$/))         // --> [ '' ]

Commented
f = (                 // f is a recursive function taking:
  n,                  //   n = input
  i = 0,              //   i = index of next prefix
  [d, t] =            //   d = either the leading digits without the last 3 ones,
                      //       or all remaining digits if there are less than 3
    n.split(/(...)$/) //   t = last three digits (or undefined)
) =>                  //
  t ?                 // if t is defined:
    f(d, i + 1) +     //   append the result of a recursive call with d and i + 1
    ['kMGT'[d && i]]  //   append the prefix if d is defined, or an empty string otherwise
    + t               //   append the last 3 digits
  :                   // else:
    d                 //   stop recursion and return the remaining digits

56 bytes: f=(n,i=0)=>n.replace(/.+(?=...)/g,d=>f(d,i+1)+'kMGT'[i])

@tsh I think this is different enough to be posted as a new answer.

05AB1E, 15 14 bytes
R3ô"kMGTP"øSR¦

Try it online!
Thanks to Kevin Cruijssen for -1 byte
R       reverse input
3ô      split it into groups of 3 digits
"kMGTP" push the prefixes
ø       zip the groups of numbers with them
S       split to a list of characters
R       reverse again
¦       drop the first element
        implicitly print

You can change the JJ to S (which implicitly flattens) to output as a list of characters instead of a string, which is allowed when a string output is asked by default. (You could add a J in the footer if you want to pretty-print it.)

As you noticed above, P is not required.

I know, but I can't remove it, because the code would cut off the number after 12 digits. It builds a list that looks like this: ["P1", "T234", "G567", "M890", "k123"]. Then it deletes the first letter. When I remove the "P", it can't fill the "P1" string.

Python 2, 57 bytes
f=lambda s,p="":s and f(s[:-3],p[1:]+"kMGT")+s[-3:]+p[:1]

Try it online!
Takes input as a string. If the output may have a trailing space, we can avoid some workarounds and save 3 bytes.
54 bytes
f=lambda s,p=" kMGT":s and f(s[:-3],p[1:])+s[-3:]+p[0]

Try it online!
One potentially-useful observation is that the string format '{:,}'.format puts commas in the places we want to insert letters:
'{:,}'.format(1234567) == "1,234,567"

However, I haven't found a short enough way to use this.

Yep, shortest format version I got so far: 76 bytes

The shortest I found using the formatting trick would be: https://tio.run/##XYjLDoIwEEX3fEV3bZOGWB6KTVi7cufelAjaSNtJKQnG@O0IigpOcu89Z@DmL9bEGbi@Vxqs88iVQZXXUhcniTrhyrBpC4IZZtNPM8hr1XiCD7v9FVMBIVgglOG7YA8cVtZp6UlHaT8gOiJlkJPmXBKeUhEgBE4ZTyoytjLQekKH63kU8Cgek7wqffd6ms1nsy9sf7SaIZ9ztJB4acmfpk8 That's already 81 chars, but maybe someone can improve it.

Brachylog, 17 bytes
↔ġ₃;"
kMGT"↔z₀cc↔

Input as a string, returns through output the result, with a trailing newline :)
Explanation:
            More or less a translation of Jelly answer:
↔           Reverse input string
 ġ₃         Group into triples, excluding last group with length in range (0,3]
   ;        Pair those groups with:
    "
kMGT"       A string containing a newline followed by the symbols in reverse order
     ↔      Reverse the pair so the string comes before the list of digit triplets
      z₀    Zip the pair until the smallest list is depleted
        cc  Concatenate the zipped lists together, then concatenate the strings together
          ↔ Reverse the result

Try it online

Looks like we have a new Brachylog user :)

@Fatalize What gave you that idea? :) You created a nice language, but I wouldn't have found it without that bounty on another question. It'd be harder if I didn't already know a bit of Prolog, of course.

The idea to create Brachylog? Well I started participating to this site with Prolog, because I though it would be fun and different. Then people started creating new golf languages in the second half of 2015, which gave me the insipiration to make a shorthand version of Prolog

Perl 5 (-p), 40 bytes
y/ kMG/kMGT/while s/\d\K((\d{3})+$)/ $1/

Try it online!

Jelly, 14 bytes
13 if input formatted as a string is acceptable for languages which can handle large integers (remove Ṿ and quote the argument)
ṾṚs3żFtṚʋ“kMGT

A full program accepting the non-negative number as a command line argument which prints the result
Try it online!
How?
ṾṚs3żFtṚʋ“kMGT - Main Link: integer         e.g. 12345
Ṿ              - un-evaluate the integer         ['1', '2', '3', '4', '5']
 Ṛ             - reverse                         ['5', '4', '3', '2', '1']
  s3           - split into chunks of three      [['5', '4', '3'], ['2', '1']]
         “kMGT - literal list of characters      ['k', 'M', 'G', 'T']
        ʋ      - last four links as a dyad  i.e. f([['5', '4', '3'], ['2', '1']], ['k', 'M', 'G', 'T'])
    ż          -   zip                           [[['5', '4', '3'], 'k'], [['2', '1'],'M'], ['G'], ['T']]
     F         -   flatten                       ['5', '4', '3', 'k', '2', '1','M', 'G', 'T']
      t        -   trim (from either side)       ['5', '4', '3', 'k', '2', '1']
       Ṛ       -   reverse                       ['1', '2', 'k', '3', '4', '5']
               - implicit (smashing) print       12k345

PHP, 67 65 bytes
for(;''<$d=$argn[-++$i];)$r=$d.' kMGT'[$i%3==1?$i/3:5].$r;echo$r;

Try it online!
Loops on input digits from right to left and concatenates each digit to $r variable in reversed order. When we are on 4th, 7th, etc... digit, the respective prefix is concatenated to $r as well. Output has a trailing space.
for(;''<$d=$argn[-++$i];) // loop on input digits from right to left, $d is current digit and $i is incremental (1, 2, ...)
  $r=$d                   // concatenate current digit to beginning of $r
  .' kMGT'                // string of prefixes, first item is space for first digit and causes a trailing space in output
    [$i%3==1?$i/3:5]      // if $i is 1, 4, 7, etc... concatenate letter at index of $i/3 (1/3=0.33, 4/3=1.33, 7/3=2.33, etc...)
                          // PHP uses integer part of decimal indexes, so 1.33 will return the letter at index 1
                          // for any other $i, use index 5 which doesn't exist and is equal to an empty string
  .$r;                    // concatenate $r itself to the end, so everything will be in reversed order of reading (which itself is in reversed order of input)
echo$r;                   // output $r when the loop is finished

A schematic example for how an output is created for input of 1234:
| Current Digit | Concatenation | $r    |
|---------------|---------------|-------|
| 4             | 4             | 4     |
| 3             | 3             | 34    |
| 2             | 2             | 234   |
| 1             | 1k            | 1k234 |

Icon, 76 71 bytes
procedure f(s)
k:=0
s[i:=*s-2to 2by-3:i]:="kMGT"[k+:=1]&\z
return s
end

Try it online!
Takes input as a string.

JavaScript (Node.js), 55 bytes
f=(n,i=0)=>n.replace(/.+(?=...)/,d=>f(d,i+1)+'kMGT'[i])

Try it online!

Poetic, 485 bytes
honestly
i lived my life
i faced a boatload of brutal challenges
i desire a day of bliss-i want badly to forget a day where things backfire
i desire a day-i covet a week-and of course i want solitude around everyone
i desire a day-i crave a year-finding no faults i seem to create everyday
i desire a day-i plead,i pray-for an answer i need,i should deserve
fea-r-s,smea-r-s
really,i have a stupid aim
oh world,why was i on earth
o,i suggest venus
o,i deserve a way i go to space
by-by

Try it online!
Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols.
The point of the language is to allow for programs to be written in free-verse poetry. It was fun to write this one (though usually two consecutive ones would be written as 11-letter words; it was hard to golf this poem and make it sound interesting!).
This poem is equivalent to the following brainfuck program, which others are more than welcome to golf:
,[>>->,]<<<<<<<<<<[<++>-----]<+++++<<<<<<<<[<+>---]<--------<<<<<<<<[<+>-------]<--<<<<<<<<[<+>---]<-<<<<<<<-[+[<+<<<]>>>-]>[.>[.[+]]>>]

Red, 85 bytes
func[n][p: copy"kMGT"parse reverse n[any[3 skip ahead skip insert(take p)]]reverse n]

Try it online!
Takes the input as a string.

APL+WIN, 46 bytes
Prompts for integer as a string
∊(n/m),¨(n←3>+/¨' '=¨m←((3/⍳5)⊂¯15↑⎕))/'TGMk '

Try it online! Courtesy of Dyalog Classic

PowerShell, 81 73 71 69 64 bytes
($a=$args)|%{$r=$a[--$i]+' kMGT'[$j+5*!$k]+$r;$j+=$k=!($i%3)}
$r

Try it online!
Takes argument as a splatted string.

Gema, 88 characters
\A=@subst{?=\@push\{p\;?\};TGMk }
*=@reverse{@subst{<d3>=\$p\$1\@pop\{p\};@reverse{$0}}}

Boring double reverse approach, but looping in Gema would be painfully long.
Sample run:
bash-5.0$ echo -n '1234567890' | gema '\A=@subst{?=\@push\{p\;?\};TGMk };*=@reverse{@subst{<d3>=\$p\$1\@pop\{p\};@reverse{$0}}}'
1G234M567k890

Try it online!

C (clang), 65  62 bytes
f(char*n,z){for(;z--;z%3||printf(L" kMGT"+z/3))putchar(*n++);}

Try it online!
Taking a char array as input.
Saved 3 thanks to @ceilingcat
C (clang), 68 bytes
f(n,s){!s|n&&f(n/10,s+1)+printf(s%3?"%d":"%d%c",n%10," kMGT"[s/3]);}

Try it online!
Taking an int as input
Recursive function which first call itself and outputs after.
f(n,s) // Idk if it's acceptable or if I have to wrap with a g(n){f(n,0);}
{
!s| // to allow 0 value calls
n&& // when n=0 exit recursion
f(n/10,s+1)+printf(
s%3?"%d":"%d%c" // select format string
,n%10, // digit to print
" kMGT"[s/3]);} // if second format selected add character

Bash, 83 bytes
a=('' k M G T)
s=
(($1>99))&&s=${1: -3}
echo `$0 ${1:0:-3} $[$2+1]`${s:-$1}${a[$2]}

Try it online! (link shows 82 bytes, but uses function recursion instead of $0-recursion)
Nice little recursive solution.
Bash doesn't like invalid string indexing, which both helps (gives us our exit condition for free) and hurts (we have to have separate logic for when our number has n != 0 mod 3 digits).

Perl 6, 39 bytes
{flip [~] <<''k M G T>>Z~.flip.comb(3)}

Try it online!

Python3, 89 83 bytes 65 chars
(or 65 bytes, if you use just ASCII, but I fancy the Unicode superscript small letters)
f=lambda n,p='ᵏᴹᴳᵀ':len(n)<4 and n or f(n[:-3],p[1:])+p[0]+n[-3:]

Try it online!
Python3, 89 bytes:
import re;print(''.join(sum(zip(re.findall('..?.?',str(x)[::-1]),'kMGT.'),()))[::-1][1:])

Try it online!
I didn't try to shorten this dramatically.  See it as an incentive to beat me :)  This is my first challenge in this forum; by now I understand the asker isn't supposed to post an answer right away.  Next time I will wait a little longer before doing it.  But since I couldn't really undo the post (deleting the post leaves it visible to too many people anyway), I saw no use in even trying to.

It is fine to answer your own challenge, but normally, authors wait for a while (I'd say a week) to give others a chance.

Taking input in a variable is not allowed. Typically, answers are either functions with the relevant number of arguments, or full programs using STDIN / STDOUT. For more detailed rules, see Default for Code Golf: Input/Output methods.

@Alfe, as the maximum length to handle is known, you could just pad the input up to a multiple of 3 ≥ 15, then split to groups from left, without reversing twice: Try it online! Just hint, it still violate the IO rule.

Or the same pad & trim idea without reversing, but with a for loop over hardcoded list: Try it online!

@Arnauld Thanks for the clarification, but that leaves me with the option to replace the str(x) by input(), effectively even skipping the conversion to string (and adding a byte).  How should we pass in a number in code-golf?  Always via reading from stdin and converting it to int afterwards?

@Alfe See the golfing rules summary for Python.. Your first function is fine as a standalone. If you use Python 2, its input can take in a number or string. For functions, you can also generally assume whichever kind you prefer.

Your answer doesn't follow your own spec; just leave it at kGMT instead of your fancy Unicode. Especially because the default scoring is bytes not characters.

You can remove the space after the 4, like: len(n)<4and

Python 2, 84 74 bytes
i=input();o=""
for x in"kMGT ":o=(i,x+i[-3:])[len(i)>3]+o;i=i[:-3]
print o

Try it online!
Previous version for 84 bytes
i=input()[::-1];o=""
for x in"kMGT ":o+=(i,i[0:3]+x)[len(i)>3];i=i[3:]
print o[::-1]

Try it online!

Reverse the input
Step through backwards in threes appending prepending the next letter
Reverse and print

Not sure that this is the most efficient approach but it's the best I can come up with at the moment.

JavaScript (V8), 71 bytes
Takes input as number
b=(a,l=10e11,x=0,c=a/l|0)=>(l-1)?(c?c+'TGMk'[x]:'')+b(a%l,l/1000,x+1):c

Try it online!

Retina 0.8.2, 31 bytes
r`\B...
,$.'$&
T`9630,`TGMk_`,.

Try it online! Explanation:
r`\B...

Match groups of three digits starting from the end but ensure that there is at least one more digit before the match.
,$.'$&

Prefix each match with a marker comma and the number of digits after the match (0 for the last match, then 3, 6 and 9 respectively).
T`9630,`TGMk_`,.

Replace the marker and following number with the appropriate suffix.

Python 2, 72 bytes
f=lambda n,p=' kMGT':(n>M and f(n/M,p[1:])or'')+`n%M+M`[-3:]+p[0]
M=1000

Try it online!

001G234M567k890 is not the correct output.  But I also thought about a recursive solution!

@Alfe: "The result shall be groups of three digits...". 001 is a group of three digits; 1 is not a group of three digits.

… as available.  The digits 00 in your example are invented and not part of the input.

Zsh, 53 bytes
a=kMGT
for z y x (${(Oas::)1})s=$x$y$z$a[i++]$s
<<<$s

Try it online!
(s::) splits the stirng, Oa reverses the characters. Zsh arrays and strings are 1-indexed, so $a[0] on the first iteration substitutes nothing.

Haskell, 99 bytes
f n=concatMap(\(a,b)->a++b)$reverse$zip(reverse<$>chunksOf 3(reverse$show n))(["","k","M","G","T"])

Try it online!
The function f takes a number, converts it into a string and splits it backwards into chunks of 3 characters, e.g.
reverse<$>chunksOf 3(reverse$show 1234) == ["234","1"]

it then zips the list of chunks with the list of magnitue identifieres ["","k","M","G","T"].
Then the list is reversed and with concatMap converted to one string.
It uses the function chunksOf from the package Data.List.Split

Forth (gforth), 84 bytes
: f s" kMGT" bounds <# do
1000 /mod tuck if
0 # # # d. i c@ hold then loop
0 #s #> ;

Try it online!
A function that takes a number from the stack, and returns a string as (address, length) pair, which is the standard representation for a string in Forth. Produces lots of garbage under the returned string, and a few zeros on stdout.
Forth has a dedicated set of facilities for customized number-to-string formatting, and this challenge seemed to be the right place to showcase it.
On the golfing perspective, I found that do .. if .. then loop (test and ignore the rest of the body) is shorter than begin .. while .. repeat (test and break simple loop) or do .. if leave then .. loop (test and break counted loop).
How it works
: f ( n -- addr len )
  s" kMGT"            \ Create a local string "kMGT"; gives its address and length
  bounds              \ Convert (addr, len) to (addr+8*len, addr)
  <#                  \ Initialize the buffer for number-to-string conversion
  do                  \ Loop; i = addr .. addr+8*len; stack=(n)
    1000 /mod         \   Calculate n%1000 and n/1000
    tuck if           \   Stack=(n/1000 n%1000); if n/1000 is nonzero...
      0 # # # d.      \     emit three digits from n%1000 and discard it
      i c@ hold       \     emit the next char of "kMGT"
    then              \   End if
  loop                \ End loop
  0 #s                \ Emit all the remaining digits
  #>                  \ Finish conversion; push addr/len of the result string
;                     \ End function

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Explore a Klarner-Rado sequence
One of the Klarner-Rado sequences is defined as follows:

the first term is \$1\$
for all subsequent terms, the following rule applies: if \$x\$ is present, so are \$2x+1\$ and \$3x+1\$
the sequence is strictly increasing

This is A002977.
The first few terms are:
1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...

(\$3\$ is present because it's \$2\times1+1\$, \$4\$ is present because it's \$3\times1+1\$, \$7\$ is present because it's \$2\times3+1\$, etc.)
Your task
Given \$n\$, you must return the \$n\$th element of the sequence. You may use either 0-based or 1-based indexing. (Please specify your choice in your answer.)
0-indexed example:
input = 10
output = 22

Let's see who can get less bytes...
Also featured on codewars

Why is this tagged [javascript]? Is this restricted to it? How is this related to array manipulation and linear algebra? Does "ordered with <" mean "ascending"?

Apart from the arbitrary language restriction there isn't any problem.

https://codegolf.meta.stackexchange.com/a/8058/69850 -- you can "look at the challenge as a separate competition in each language".

@Arnauld and what's with that? I solved the problem but I want to see community's inventions

@user89702 It's not yours, so you can't post it, especially without any attribution.

Why so strict? Is just a challenge, if you don't want to participate just ignore this post, let people have fun

However, I do believe this is a rather interesting challenge that would be worth rephrasing properly for Code Golf. There's nothing wrong on posting a challenge about this sequence (which is A002977, btw), but you can't copy from an external site without any authorization or credits.

I want to agree with @user89702. Two of my top posts are not my challenge, but they get upvotes.

I've rephrased your post so that it better fits our standard and is not a copy of codewars anymore. Feel free to edit further if needed.

closely related

Currently this needs to mention that this sequence is in ascending order.  Without it the only term that we can know the location of is the first one.

I upvoted & closed as a duplicate (even though slightly different). This could get reopened if people think the offset difference is enough to make answers not trivially portable.

How do we define duplicate? This question: If x occurs in the sequence, then 2x+1 and 3x+1 also exists. Claimed duplicate:If x occurs in the sequence, then 2x+1 and 3x-1 also exists. Are the two definitions sufficiently close to count as a duplicate. Rules Committee????

I made the comment above as it is exceedingly frustrating to spend the time to answer a question only to find some considerable time later it is claimed to be a duplicate. Personally I do not have the time or inclination to validate every question before answering it.

@Graham, if you've taken the time to work up a solution then absolutely post it to the dupe target. If your solution cannot be trivially modified to fit the dupe target then you have a case to reopen this one and you should cast your vote accordingly.

05AB1E, 15 14 bytes
$FDx>DŠ+)˜ê}sè

Try it online!

Times out for me on TIO for inputs of 14 and above

@Graham Well this is code golf, not fastest code, so that’s not an issue.

@Graham, for the purposes of code golf, we may assume infinite memory & time.

@Grimy Thanks to you and Shaggy for this information which I had not appreciated. All solutions I have offered in the past have worked efficiently within the capabilities of my machine. This opens up some wacky impractical solutions ;)

JavaScript (ES6),  53  50 bytes
1-indexed.
n=>(g=k=>n?g(g[k]|!k++?g[n--,k*2]=g[k*3]=k:k):k)``

Try it online!
Commented
Note: On the first iteration, we have k = [''], which is zero-ish but truthy. By doing !k++, we force k to be coerced to \$0\$ right away (and  not just before it's incremented), which makes the test work as expected.
n => (                    // n = requested index
  g = k =>                // h is a recursive function taking k, starting at 0
    n ?                   // if n is not equal to 0:
      g(                  //   do a recursive call:
        g[k] |            //     if g[k] is defined
        !k++ ?            //     or k = 0 (increment k after the test):
          g[n--, k * 2] = //       decrement n; set g[k * 2]
          g[k * 3] = k    //       and g[k * 3] and pass k
        :                 //     else:
          k               //       just pass k
      )                   //   end of recursive call
    :                     // else:
      k                   //   stop recursion and return k
)``                       // initial call to g with k = [''] (zero-ish)

JavaScript (ES6), 65 bytes
I thought the '11'[k/x-2] trick was neat, but overall this initial approach is far too long.
0-indexed.
n=>(g=k=>a[n]||g(-~k,a.some(x=>'11'[k/x-2])&&a.push(k+1)))(a=[1])

Try it online!
Commented
n => (                  // n = requested index
  g = k =>              // g is a recursive function taking k (starting at 1)
    a[n] ||             // if a[n] is defined, return it and stop
    g(                  // otherwise, do a recursive call:
      -~k,              //   with k + 1
      a.some(x =>       //   if there exists some x in a[]
        '11'[k / x - 2] //   such that k / x is either 2 or 3 ...
      )                 //
      && a.push(k + 1)  //   ... then push k + 1 in a[]
    )                   // end of recursive call
)(a = [1])              // initial call to g with k = a = [1]

R, 57 bytes
n=scan();for(i in 1:n)T=sort(unique(c(T,T%o%2:3+1)));T[n]

Try it online!
1-based index.

APL+WIN, 54 bytes
Index origin 1
Prompts for the index of required value. Given the response that I received from Grimy and Shaggy that I can assume infinite memory and time then it is trivial to modify this function to work with a series up to the limit of your machine by increasing the value 20 in the function below. This version is limited to index position 1901981
m←1⋄(⍎∊20⍴⊂'m←(0≠1,-2-/m)/m←m[⍋m←m,∊1+m×¨⊂2 3]⋄')⋄m[⎕]

For some reason this function will not run on Dyalog Classic in TIO which is what I usually use.
On my machine 1 => 1, 11 => 22 and 61 => 237 (checked on http://oeis.org)

JavaScript (ES6), 99 bytes
x=>eval("a=[i=1],a.b=a.includes;while(i++,c=i-1,x)a.b(i)||!a.b(c/2)&&!a.b(c/3)||(a.push(i),x--);c")

I think this works for 96 bytes: Try it online!

Ah, type casting is fun.

Python 3, 73 bytes
f=lambda n,i=0,k=[1]:(i==n)*k[i]or f(n,i+1,sorted(k+[2*k[i]+1,3*k[i]+1]))

Try it online!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
List where pinballs would exit a grid of bumpers from different entrance points
Inspired by this lumosity mini game, Pinball Recall
We start with a rectangular grid (viewed from above) with several bumpers as follows. Entrances/exits are numbered counter-clockwise starting from the leftmost of the bottom of the grid, as number 0.
   24 23 22 21 20 19 18 17 16 15
25  .  .  .  .  .  /  .  .  .  . 14
26  .  .  .  .  .  .  .  .  .  . 13
27  .  /  \  .  .  \  .  .  \  . 12
28  .  .  .  .  .  .  .  .  .  . 11
29  .  .  .  .  .  .  /  .  .  . 10
    0  1  2  3  4  5  6  7  8  9

Pinballs can be fired from each entrance into the grid at a direction perpendicular to the grid wall, e.g. in the above example:

0 to 9: fired upwards
10 to 14: fired to the left
15 to 24: fired downwards
24 to 29: fired to the right

The pinballs will move in a straight line until they reach an exit, or a bumper, in which case the ball will bounce off the bumper and change direction. So in above diagram,

from 0, ball goes straight to 24
from 1, ball goes up to / and bounces off to reach \, then bounces off again and ends up at 2
from 10, ball goes left to / and bounces off to 6

Inputs
Program shall receive the grid width and height.
Then program receives the bumper orientation (represented as / or \) followed by coordinates, which also start from 0 from bottom left, e.g.
 4  .  .  .  .  .  .  .  .  .  .
 3  .  .  .  .  .  .  .  .  .  .
 2  .  .  .  .  .  .  .  .  .  .
 1  .  .  .  .  .  .  .  .  .  .
 0  .  .  .  .  .  .  .  .  .  .
    0  1  2  3  4  5  6  7  8  9

"done" keyword used to indicate end of input
edit: as suggested by ngn, program may receive list of bumper coordinates instead so the "done" keyword is not needed
Output
Program should print out the exit locations of a pinball if they are fired from 0 to the last entrance of grid, in above case, 0 to 29
Sample input and output
Input
10 5
/ 1 2 / 5 4 / 6 0 \ 2 2 \ 5 2 \ 8 2
done

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

Leaderboard (as of 20Oct2019)

Neil, Charcoal, 133 bytes
Arnauld, JavaScript (ES6), 212 bytes
Embodiment of Ignorance, C# (Visual C# Interactive Compiler), 277 bytes
Chas Brown, Python 2, 290 bytes

edit: FryAmTheEggman points out a similar question to try

nice first challenge! welcome to codegolf.stackexchange.com. how much flexibility would you allow in the input? for instance would it be ok to write a function that accepts a list like [["/",x0,y0],["\\",x1,y1],...] instead of input terminated with done?

@ngn thanks! I think that's ok, as long as numbering follows the description

I'm definitely going to try and answer this in Scratch as soon as I can. Should be fun! (nice question btw)

@Jono2906 have fun!

There are several similar questions, the closest of which seems to be this one.

@FryAmTheEggman thanks for pointing out! The idea is similar, though that question adds obstacles and portals, with laser guns and targets at arbitrary locations. My question is basically inspired/ripped off from the lumosity game that happens to be similar. Going to add a link to that question

Just to be clear, I wasn't pointing that out to in any way say your challenge was bad. Other challenges are often linked on this site so that people can look at other approaches for golfing/etc inspiration. Also, while this went very well for a first challenge, please consider using our sandbox in the future! :)

@FryAmTheEggman no worries, it's fine. Really appreciate your feedback thumbs up

Can we take the upper-left point of the grid as (0,0) or swap the positions of x,y?  Fwiw changes like these would all be allowed by the default input rules but it's up to you if you want to follow these.

@Jonah I can allow anyway you want to define the order in the (orientation,x,y) tuple, so you can have (y,x,orientation) if you wish, but please state this clearly in your answer. But the origin (0,0) should always start from bottom-left.

Can I take a visual representation of the grid as input?

@Neil I don't get what you mean. Do you mean input is an image?

I'm pretty sure @Neil meant taking it as an ASCII grid with the / and \\s baked right in.

@Veskah um I'm not sure, considering there are already 3 answers receiving coords as input. Perhaps receiving ascii art should be considered as a separate category?

JavaScript (ES6),  218 215 213  212 bytes
Takes input as (w,h,o) where \$o\$ is an object whose keys are the coordinates of the bumpers in 'x,y' format and whose values are either '/' or '\'.
(w,h,o)=>(A=[...Array(w+h<<1)].map((_,n)=>(p=n-w)<0?[n,-1,3]:p<h?[w,p]:(p-=w)<h?[h+~p,h,1]:[-1,2*h+~p,2])).map(g=([x,y,d])=>A.every(([X,Y])=>X-x|Y-y&&++i,(c=o[[x+=~-d%2,y+=~-~-d%2]])?d^=c<{}||3:i=0)?g([x,y,d]):i)

Try it online!
Commented
We first create an array \$A[\:]\$ of tuples \$[x, y, d]\$ where \$(x, y)\$ is the starting position along the borders of the playfield and \$d\$ is the initial direction.
( A = [...Array(w + h << 1)]  // create an array A[] of (w + h) * 2 items
  .map((_, n) =>              // for each item at position n in A[]:
    (p = n - w) < 0 ?         //   set p = n - w; if this is the bottom side:
      [n, -1, 3]              //     start at (n, -1) in direction 3
    :                         //   else:
      p < h ?                 //     if this is the right side:
        [w, p]                //       start at (w, p) in direction 0 (implicit)
      :                       //     else:
        (p -= w) < h ?        //       subtract w from p; if this is the top side:
          [h + ~p, h, 1]      //         start at (h + ~p, h) in direction 1
        :                     //       else (left side):
          [-1, 2 * h + ~p, 2] //         start at (-1, 2 * h + ~p) in direction 2
  )                           // end of map()
)                             //

We then simulate the trajectory of the ball, starting at each position defined above, until it reaches another starting position.
.map(g = ([x, y, d]) =>       // for each tuple [x, y, d] in A[]:
  A.every(([X, Y]) =>         //   for each tuple [X, Y] in A[]:
    X - x | Y - y             //     break if (x, y) = (X, Y)
    && ++i,                   //     otherwise, increment i
    ( c =                     //     define c as
        o[[                   //       the bumper character at
          x += ~-d % 2,       //         (x, y), once updated according to d
          y += ~-~-d % 2      //         (0 = West, 1 = South, 2 = East, 3 = North)
        ]]                    //
    ) ?                       //     if c is set:
      d ^= c < {} || 3        //       XOR d with 1 (for '/') or 3 (for '\')
    :                         //     else:
      i = 0                   //       initialize i to 0
  ) ?                         //   end of every(); if truthy:
    g([x, y, d])              //     do a recursive call to move the ball further
  :                           //   else:
    i                         //     we've reached a starting position: yield i
)                             // end of map()

Amazing! I got one question, I cannot understand why A=[...Array((w+h)*2)] works, but A=Array((w+h)*2) doesn't. Isn't [...Array((w+h)*2)] actually creating same array as Array((w+h)*2) itself?

@Night2 Array(n) basically just sets the length of the array to $n$ but doesn't create any item -- even undefined ones. [...Array(n)] forces the array to be filled with $n$ undefined values that can be iterated with .map().

Thanks, for some reason FireFox's console was showing they are the same and I was confused: https://i.imgur.com/JOeSkxn.png It probably is a bug in how FireFox visualizes arrays in the console.

@Night2 Yes, the output of the console in FF is misleading. BTW, I should have said forces the creation of another array filled with $n$ undefined values (this is definitely not the same array). Here is some code illustrating that.

Python 2, 317 300 298 290 bytes
def f(w,h,B):
 A=[w*[-1]for c in' '*h];p=w+h
 for x,y,c in B:A[y][x]=c<'0'
 for i in range(2*p):
	x,y,d=[[[(0,2*p+~i,0),(w+p+~i,h-1,1)][i<w+p],(w-1,i-w,3)][i<p],(i,0,2)][i<w]
	while w>x>=0<=y<h:d^=1+A[y][x];x+=[1,0,0,-1][d];y+=[0,-1,1,0][d]
	print[[y+w,2*p+~y][x<0],[w+p+~x,x][y<h]][0<d<3],

Try it online!
Takes the bumpers as a list of tuples (x,y,c)where x and y are the coordinates of the bumper and c is either \ or /.

C# (Visual C# Interactive Compiler), 277 bytes
(w,h,d)=>{var z=new int[w+h<<1].Select((_,i)=>i<w?(i,-1,3):i<w+h?(w,i-w,0):(i-=w+w)<h?(h+~i,h,1):(-1,h+h+~i,2)).ToList();z.ForEach(x=>{var(a,b,c)=x;do{try{c^=d[(a,b)]<48?1:3;}catch{}a+=~-c%2;b+=(c-2)%2;}while(a>=0&a<w&b>=0&b<h);Print(z.FindIndex(l=>l.Item1==a&l.Item2==b));});}

Try it online!

Charcoal, 133 bytes
ＮθＮηＵＯθη.ＷＳ«ＪＮＮι»≔⟦⟧ζＦθ⊞ζ⟦²ι±¹⟧Ｆη⊞ζ⟦⁰θι⟧Ｆθ⊞ζ⟦⁶⁻θ⊕ιη⟧Ｆη⊞ζ⟦⁴±¹⁻η⊕ι⟧Ｆζ«Ｊ§ι¹§ι²≔﹪⁺⁴§ι⁰¦⁸δＭ✳δＷ¬№ζ⟦δⅈⅉ⟧«≡ＫＫ/≦⁻⁶δ\≔﹪⁻χδ⁸δＰωＭ✳δ»⊞υ⌕ζ⟦δⅈⅉ⟧»⎚Ｉυ

Try it online! Link is to verbose version of code. Takes input on separate lines with a blank trailing line but for convenience the test case uses spaces instead of newlines. Explanation:
ＮθＮηＵＯθη.

Input the width and height and draw a box of .s of that size. I'm drawing with the origin at the top left but I'm flipping the vertical co-ordinate in all of my calculations so the results will be correct.
ＷＳ«ＪＮＮι»

Loop over the input list and print the \ or / characters at the relevant positions.
≔⟦⟧ζＦθ⊞ζ⟦²ι±¹⟧Ｆη⊞ζ⟦⁰θι⟧Ｆθ⊞ζ⟦⁶⁻θ⊕ιη⟧Ｆη⊞ζ⟦⁴±¹⁻η⊕ι⟧Ｆζ«

Build up a list for all of the entry/exit points giving the direction of exit and the coordinates and loop over the list.
Ｊ§ι¹§ι²≔﹪⁺⁴§ι⁰¦⁸δＭ✳δ

Jump to the exit point, calculate the direction of entry and take a step in that direction.
Ｗ¬№ζ⟦δⅈⅉ⟧«

Until an exit point is found...
≡ＫＫ/≦⁻⁶δ\≔﹪⁻χδ⁸δＰω

... adjust the direction if the cursor is over a / or \...
Ｍ✳δ»

... and take a step in the current direction.
⊞υ⌕ζ⟦δⅈⅉ⟧

Remember the found exit point.
»⎚Ｉυ

Clear the grid and output the list of exit points.

It appears the output doesn't display on tio.run?

@kuantumleap123 My bad, I typo'd a character, sorry about that. Fixed now.


text:
Implement the 2D Hadamard Transform
The Hadamard transform works similarly to the Fourier transform: it takes a vector and maps it to its frequency components, which are the Walsh functions. Instead of sine waves in the Fourier transform, the Walsh functions are discrete "square waves" so to speak. This makes it easier to compute.
The size of a Hadamard matrix is a power of two, 2^n x 2^n. We can build a Hadamard matrix for a given n recursively. $$H_1 = \begin{pmatrix}1&1\\1 & -1\end{pmatrix}$$ And then build block matrices in the same pattern to get $$H_n = \begin{pmatrix}H_{n-1}&H_{n-1}\\H_{n-1} & -H_{n-1}\end{pmatrix}$$
For instance,
$$H_3 = \begin{pmatrix}1&1&1&1&1&1&1&1\\1&-1&1&-1&1&-1&1&-1\\1&1&-1&-1&1&1&-1&-1\\1&-1&-1&1&1&-1&-1&1\\1&1&1&1&-1&-1&-1&-1\\1&-1&1&-1&-1&1&-1&1\\1&1&-1&-1&-1&-1&1&1\\1&-1&-1&1&-1&1&1&-1\end{pmatrix} = \begin{pmatrix}H_2&H_2\\H_2&-H_2\end{pmatrix}$$
Note how the entries are always 1 or -1 and symmetric! Easy! Then the Hadamard transform is simply multiplying H_n by a column vector and dividing by 2^n.
In order to apply the Hadamard transform to 2D images, we have to apply the 1D HT across every column and then every row. In short, for an input matrix X, the output will be a new matrix Y given by two matrix multiplications:
$$Y = \frac{1}{2^{2n}}H_nXH_n$$
Another way to implement this is by first applying the HT to every column in the image separately. Then apply it to every row, pretending they were column vectors. For example, to compute the 2D HT of $$\begin{pmatrix}2 & 3\\ 2 & 5\end{pmatrix}$$
we first do
$$\frac{1}{2}\begin{pmatrix}1&1\\1 & -1\end{pmatrix}\begin{pmatrix}2 \\ 2\end{pmatrix} = \begin{pmatrix}2 \\ 0\end{pmatrix} \quad\quad\quad \frac{1}{2}\begin{pmatrix}1&1\\1 & -1\end{pmatrix}\begin{pmatrix}3 \\ 5\end{pmatrix} = \begin{pmatrix}4 \\ -1\end{pmatrix} \quad\rightarrow\quad \begin{pmatrix}2&4\\0 & -1\end{pmatrix} $$
which takes care of the columns, and then we do the rows,
$$\frac{1}{2}\begin{pmatrix}1&1\\1 & -1\end{pmatrix}\begin{pmatrix}2 \\ 4\end{pmatrix} = \begin{pmatrix}3 \\ -1\end{pmatrix} \quad\quad\quad \frac{1}{2}\begin{pmatrix}1&1\\1 & -1\end{pmatrix}\begin{pmatrix}0 \\ -1\end{pmatrix} = \begin{pmatrix}-0.5 \\ 0.5\end{pmatrix} \quad\rightarrow\quad \begin{pmatrix}3&-1\\-0.5 & 0.5\end{pmatrix} $$
Finally, one can also compute this recursively using the fast Hadamard transform. It's up to you to find out if this is shorter or not.
Challenge
Your challenge is to perform the 2D Hadamard transform on a 2D array of arbitrary size 2^n x 2^n, where n > 0. Your code must accept the array as input (2D array or a flattened 1D array). Then perform the 2D HT and output the result.
In the spirit of flexibility, you have a choice for the output. Before multiplying by the prefactor 1/(2^(2n)), the output array is all integers. You may either multiply by the prefactor and output the answer as floats (no formatting necessary), or you may output a string "1/X*" followed by the array of integers, where X is whatever the factor should be. The last test case shows this as an example.
You may not import the Hadamard matrices from some convenient file that already contains them; you must build them inside the program.
Test Cases
Input:
2,3
2,5

Output:
3,-1
-0.5,0.5

Input:
1,1,1,1
1,1,1,1
1,1,1,1
1,1,1,1

Output:
1,0,0,0
0,0,0,0
0,0,0,0
0,0,0,0

Input:
1,0,0,0
1,1,0,0
1,1,1,0
1,1,1,1

Output:
0.6250,0.1250,0.2500,0
-0.1250,0.1250,0,0
-0.2500,0,0.1250,0.1250
0,0,-0.1250,0.1250

Input:
0,0,0,0,0,0,0,1
0,0,0,0,0,0,2,0
0,0,0,0,0,3,0,0
0,0,0,0,4,0,0,0
0,0,0,5,0,0,0,0
0,0,6,0,0,0,0,0
0,7,0,0,0,0,0,0
8,0,0,0,0,0,0,0

Output:
1/64*
36,4,8,0,16,0,0,0
-4,-36,0,-8,0,-16,0,0
-8,0,-36,-4,0,0,-16,0
0,8,4,36,0,0,0,16
-16,0,0,0,-36,-4,-8,0
0,16,0,0,4,36,0,8
0,0,16,0,8,0,36,4
0,0,0,-16,0,-8,-4,-36

Scoring
This is code golf, so the smallest program in bytes wins.

Nice first challenge!

Related. Loosely related

@Arnauld Thanks! I don't think I'm good enough to golf yet, but it's still fun seeing the other answers.

"You may not import the Hadamard matrices from some convenient file that already contains them; you must build them inside the program." Does this include using build-in functions that return the matrix?

an upvote and applause for not requiring floating point

@Kroppeb No, that's fine. Like MATLAB has hadamard. I just didn't know if someone would try to use a loophole :) But I think file IO is longer than generating the matrices anyway

Haskell, 111 102 97 92 bytes
import Data.Matrix
t x|n<-nrows x=h n*x*h n
h 1=1
h i|m<-h$div i 2=(/2)<$>m<->m<|>(m<->(-m))

This uses the Data.Matrix module. The input matrix has to be of type Matrix Float or Matrix Double.
TIO doesn't provide Data.Matrix, so no link.
Edit: -9 bytes thanks to @ceased to turn counterclockwis, -5 bytes thanks to @H.PWiz, -5 bytes thanks to @xnor

I am amazed that identity 1 is the shortest way to represent $\left[1\right]$, but it does seem to be.

@SriotchilismO'Zaic actually no, pure 1 is shorter. Heck, even 1 does the trick.

t x|Right m<-inverse$h$nrows x=m*x*m

Can you divide the matrix by 2 in the recursive step to avoid needing to scale or invert at the end?

JavaScript (ES6), 114 bytes
This version is golfed a bit further by embedding the function \$h\$ within the callback of the deepest loop.
M=>(g=z=>M=M.map((r,y)=>r.map((_,x)=>r.map(v=>s+=(h=m=>m?-h(m&~-m):z?v:M[i-1][x])(i++&(z?x:y)),i=s=0)&&s/i)))(g())

Try it online!

JavaScript (ES6),  161 ... 117  116 bytes
M=>(h=m=>m?-h(m&~-m):1,g=z=>M=M.map((r,y)=>r.map((_,x)=>r.map(v=>s+=(z?v:M[i][x])*h(i++&(z?x:y)),s=i=0)&&s/i)))(g())

Try it online!
How?
Each 0-indexed cell \$(x,y)\$ of a Hadamard matrix \$H_n\$ is equal to:
$$H_n(x,y)=\cases{
1,&\text{if $(x\And y)$ is evil}\\
-1,&\text{otherwise}
}$$
or:
$$H_n(x,y)=(-1)^{\operatorname{popcount}(x \And y)}$$
where \$\And\$ is a bitwise AND and \$\operatorname{popcount(m)}\$ is the number of bits set in \$m\$.
The function \$h\$ computes \$(-1)^{\operatorname{popcount}(m)}\$ recursively:
h = m => m ? -h(m & ~-m) : 1

(This is similar to my answer to Is this number evil?)
The function \$g\$ computes either \$\frac{1}{2^n}H_nM\$ or \$\frac{1}{2^n}MH_n\$, depending on the flag \$z\$:
g = z =>                      // z = flag cleared on the 1st pass, set on the 2nd
  M =                         // update M[]:
    M.map((r, y) =>           //   for each row r[] at position y in M[]:
      r.map((_, x) =>         //     for each cell at position x in r[]:
        r.map(v =>            //       for each value v in r[]:
          s +=                //         add to s:
            (z ? v            //           v = M(i, y) if z is set,
               : M[i][x]) *   //             or M(x, i) otherwise
            h(i++ & (z ? x    //           multiplied by H(x, i) if z is set,
                       : y)), //             or H(i, y) otherwise
                              //           and increment i afterwards
          s = i = 0           //         start with s = i = 0
        )                     //       end of inner map() over the columns
        && s / i              //       yield s divided by the width of the matrix
      )                       //     end of outer map() over the columns
    )                         //   end of map() over the rows

We invoke it twice to compute \$\frac{1}{2^{2n}}H_nMH_n\$.

"If (x&y) is evil" :D

MATL, 12 bytes
&nKYLw/Gy,Y*

Try it online! Or verify all test cases.
Explanation
Consider input [2,3; 2,5] as an example.
&n     % Input (implicit). Push number of rows and number of columns
       % STACK: 2, 2
KYL    % Hadamard matrix of specified size
       % STACK: 2, [1 1; 1 -1]
w/     % Swap, divide element-wise
       % STACK: [0.5 0.5; 0.5 -0.5]
G      % Push input again
       % STACK: [0.5 0.5; 0.5 -0.5], [2,3; 2,5]
y      % Duplicate from below
       % STACK: [0.5 0.5; 0.5 -0.5], [2,3; 2,5], [0.5 0.5; 0.5 -0.5]
,      % Do twice
  Y*   %   Matrix multiply
       % End (implicit)
       % STACK: [3 -1; -0.5 0.5]
       % Display (implicit)

I don't know MATL. But it might be shorter to get an inverse, instead of dividing by the number of rows. (both get the same result)

@H.PWiz Thanks for the idea! I didn't know that. Unfortunately, computing the inverse matrix (and getting rid of the extra number of rows) would require more characters

Octave, 93 79 bytes
@(x)(r=f(f=@(f)@(x){@()[x=f(f)(x-1) x;x -x],1}{1+~x}())(log2(r=rows(x)))/r)*x*r

This computes \$\frac{1}{2^n}H_nX\frac{1}{2^n}H_n\$
Try it online!
Octave, 47 33 bytes (uses builtin)
@(x)(r=hadamard(r=rows(x))/r)*x*r

Try it online!

APL (Dyalog), 28 bytes
{(⍵∘⌹+.×⌹)(,⍨⍪⊢,-)⍣(2⍟≢⍵)⍪1}

Try it online!

Brachylog, 23 bytes
{ḍ\⟨+ᵐ↰₁ᵐ-ᵐ⟩c/₂ᵐ|}ᵐ\↰₁ᵐ

Input: A list of columns
Output: A list of rows

How:
It uses the Fast Hadamard Transformation. AFAIK Brachylog doesn't have matrix multiplication, nor binary operations so I doubt using the "evil numbers technique" will help shorten the code.
    {ḍ\⟨+ᵐ↰₁ᵐ-ᵐ⟩c/₂ᵐ|}ᵐ\↰₁ᵐ   #
    {ḍ\⟨+ᵐ↰₁ᵐ-ᵐ⟩c/₂ᵐ|}ᵐ       # Fast transform:
    {               }ᵐ       #   for each column:
     ḍ                       #     Split in 2
                   |         #       (if this fails, return the collum.
                             #         This is the case in the final recursion step)
      \                      #      Zip,
        +ᵐ                   #         and add each pair  (adds the 2 subvectors)
             -ᵐ              #         and sub each pair  (subs the 2 subvectors)
       ⟨  ↰₁ᵐ  ⟩              #      and apply the transformation on both results
               c             #      concat both transformed results.
                 /₂^m        #        and half each element
                      \      #  Transpose
                       ↰₁ᵐ   #    and apply the transformation again

Try it online!

Jelly, 18 bytes
J’&þ`B§-*ðæ×⁺@÷L$⁺

A monadic Link accepting a list of lists of integers (any numbers really), the square input matrix of side \$2^n\$, which yields  a list of lists of floats.
Try it online!
How?
It feels like one should be able to outer-product the dot-product of the binary representations of the 0-indexed coordinates, however to do so one would need to left-pad the binary representations with zeros which, I believe, costs too many bytes.
J’&þ`B§-*ðæ×⁺@÷L$⁺ - Link: list of lists of integers, M
J                  - range of length = [1,2,...,rows(M)]
 ’                 - decrement (vectorises) = [0,1,...,rows(M)-1]
    `              - use left argument as both arguments of:
   þ               -   outer-product with:
  &                -     bit-wise AND         [[0&0, 0&1, ...],[1&0, 1&1, ...], ...]
     B             - convert to binary (vectorises)
      §            - sums (vectorises at depth 1) - i.e. bit-sums
       -           - literal minus one
        *          - exponentiate (vectorises) - i.e. the appropriately sized Hadamard matrix, H
         ð        - start a new dyadic chain - i.e. f(H, M)
          æ×       - matrix multiply - i.e. H×M
             @     - with swapped arguments i.e. f(H×M, H):
            ⁺      -   repeat previous link i.e. H×M×H
                $  - last two links as a monad:
               L   -   length (number of rows)
              ÷    -   divide (vectorises)
                 ⁺ - repeat the previous link (divide by the length again)

R, 80 78 74 bytes
function(M){for(i in 1:log2(nrow(M)))T=T%x%matrix(1-2*!3:0,2)/2
T%*%M%*%T}

Try it online!
Calculates \$\frac{1}{2^n}H_nX\frac{1}{2^n}H_n\$; constructs \$\frac{1}{2^n}H_n\$ by Kronecker product %x%.
Looks like I can still golf, recalling that 1-2*!3:0 is shorter than c(1,1,1,-1) as I realized in the comments to this answer.

Pari/GP, 51 bytes
a->h=1;while(#h<#a,h=matconcat([h,h;h,-h])/2);h*a*h

Try it online!


text:
Length-terminated sequences
We all know the age-old debate - should strings be length-prefixed or should they be null-terminated? Well, you've run into a blob of binary data and apparently whoever made it decided that the best solution would be a compromise and length-terminated their strings.
For the purposes of this challenge, a length-terminated sequence is a series of one or multiple integers such that the last item in the sequence is equal to the number of items in the sequence, and no prefix of the sequence is also a valid length-terminated sequence. For example, [1], [15, 2], and [82, 19, 42, 111, 11, 6] are all valid length-terminated sequences. [15] is not a valid length-terminated sequence (it hasn't been terminated), and neither is [15, 2, 3] (it should have ended at the 2).
Your task is to write a program or function that takes a list of integers, and outputs all the valid length-terminated sequences within that list. For example, for the input list [7, 6, 5, 4, 3, 2, 1], valid length-terminated sequences would be [1], [3, 2], [5, 4, 3] and [7, 6, 5, 4].

You must output all valid length-terminated sequences found in the input, in any order. The order may vary between runs of your program. You must output no length-terminated sequences not found within the input, and no sequences found within the input that aren't valid length-terminated sequences.
If some length-terminated sequence occurs multiple times within the input, it should also be output multiple times. The sequence [9, 8, 3] occurs twice in the input [9, 8, 3, 9, 8, 3] (once starting with the first number, and again starting at the fourth number) and should thus be output twice.
A number may be part of more than one length-terminated sequence. For example, the input [9, 9, 2, 4] contains both the length-terminated sequences [9, 9, 2, 4] and [9, 2] and they should both be output.
You may assume all numbers are between 0 and 127 (both inclusive).
You may assume the input contains no more than 126 numbers.
You may not make any further assumptions about the input, including the assumption that the input contains at least one valid length-terminated sequence.
You may take input or produce output by any of the default methods. Input and output formats are flexible (within reason) and the input format need not be the same as the output format. However, the your input and output formats must not depend on the input, and must not vary between runs of your program.
This is code-golf - make your code as small as possible.

Examples
[input] -> [output], [output], ...
[7, 6, 5, 4, 3, 2, 1] -> [7, 6, 5, 4], [5, 4, 3], [3, 2], [1]
[90, 80, 70] -> (no output)
[1, 2, 3, 4, 5] -> [1]
[100, 0, 2, 2, 2, 0, 0, 2, 4] -> [0, 2], [2, 2], [2, 2], [0, 0, 2, 4], [0, 2]
[] -> (no output)
[54, 68, 3, 54, 68, 3] -> [54, 68, 3], [54, 68, 3]
[4, 64, 115, 26, 20, 85, 118, 9, 109, 84, 64, 48, 75, 123, 99, 32, 35, 98, 14, 56, 30, 13, 33, 55, 119, 54, 19, 23, 112, 58, 79, 79, 45, 118, 45, 51, 91, 116, 7, 63, 98, 52, 37, 113, 64, 81, 99, 30, 83, 70] -> [85, 118, 9, 109, 84, 64, 48, 75, 123, 99, 32, 35, 98, 14], [118, 9, 109, 84, 64, 48, 75, 123, 99, 32, 35, 98, 14, 56, 30, 13, 33, 55, 119, 54, 19, 23, 112, 58, 79, 79, 45, 118, 45, 51, 91, 116, 7, 63, 98, 52, 37], [109, 84, 64, 48, 75, 123, 99, 32, 35, 98, 14, 56, 30, 13, 33, 55, 119, 54, 19], [84, 64, 48, 75, 123, 99, 32, 35, 98, 14, 56, 30, 13], [14, 56, 30, 13, 33, 55, 119, 54, 19, 23, 112, 58, 79, 79, 45, 118, 45, 51, 91, 116, 7, 63, 98, 52, 37, 113, 64, 81, 99, 30], [45, 118, 45, 51, 91, 116, 7]

Interesting problem, but surely the definition of a string is that it can store arbitrary quantities of data retrievably?  Your third clause breaks that explicitly by misreporting of a substring as a separate string.  If constructing a string from the values "9, 9, 2" gives you the output "9,9,2,9", then by definition this is not storing data retrievably.

Let's give the OP the benefit of the doubt that they're proposing a fun code-golf challenge and not arguing that the given data structure should be used in real life.

@Graham If you know where in a blob of arbitrary data your string begins (or, indeed, where it ends), you can absolutely retrieve it. If you don't, it doesn't matter how you represent your strings, you're almost certainly going to find segments of memory that look like strings but aren't the string you're looking for.

(that is not to say this is a practical way to store data)

@Graham In a system with length-prefixed strings, the bytes 2 3 4 5 6 contain two strings (3 4 and 4 5 6), both of which can be referenced with separate pointers to the first or second byte of the list.

@SaraJ But if you have a pointer to the start of a string, and you have stored some data in that string, and that string has not since been corrupted, then there must be one and only one result from reading that string which is identical to the string you stored.  I'm sure you didn't mean for this to be a practical way to store data - it's a fun code golf thing. :) My point is that it basically isn't a way to store data, because if you don't get out what you put in then you fundamentally haven't stored that data.

@Sparr That's not the same thing at all though.  Given a pointer to the start of a length-prefixed string, there is one and only one interpretation of the string stored at that address, which is exactly what you stored.  You don't have to be able to pick up at a random location in the middle, but you do have to be able to read back the whole string from the start.  My point is that a pointer to the start of SaraJ's not-strings fundamentally cannot do that.  (It's still a nice idea for a challenge, of course. :)

@Graham Say you want to store the numbers 2,3,5. You find a place where you can store numbers, and put the numbers 2,3,5 there, and finish with a 4 as a string terminator. You later want the numbers back, so you go back to where you started writing. You read 2,3,5,4 and notice that the 4 is also the length, so you stop - the data ended and it was 2,3,5. You unambiguously got exactly the data you stored. Yes there are limits on the data you can store (the n-th value can't be n) which makes it impractical, but for any data that can be stored in this format it seems to work fine?

@SaraJ I don't think it's quite that. - my reading of your rules is that all values must be >= their index in the array.  For any value <= its own index, that value will be incorrectly recognised as a terminator.  You also have a problem with your [9, 9, 2, 4] example - the point of a terminator is that parsing terminates there, so it can't also return 9,9,2 unless it's going to scan the entire system memory looking for matches (or at least the next 126 bytes, which may break array bounds).

@Graham The definition of a length terminated string clearly states that the terminator is exactly the length. You might also notice that in the 9,9,2,4 example, the possible strings (9,9,2,4 and 9,2 if we include the terminators) start in different locations, so if you know where the string starts you do get an unambiguous value - the 2 won't terminate 9,9,2 but will terminate 9,2. The input contains zero or more strings in unknown locations because scanning the entire memory for possible matches is exactly what the challenge is about.

@SaraJ OK - still not totally convinced, but then code golf isn't exactly supposed to be practical, so fair enough. :) A good challenge anyway!

@Graham You have the problem with this format exactly backwards. If you attempt to store 9 9 2 at some memory location it will result in the memory pattern 9 9 2 4, and reading the memory location later will unambiguously give you back 9 9 2. The problem is that if you try to store 9 9 2 4 9 at some location, that will result in the memory pattern 9 9 2 4 9 6, but reading it back will give you 9 9 2 (and the last 3 numbers will be leaked memory) because the 4 in the data is mistaken for a terminator.

@Graham This isn't fundamentally different from the problem with trying to store strings containing null bytes with null-terminated conventions. There are some strings you just can't store without using an encoding scheme that avoids using the invalid characters, and storing the encoded strings instead of the logical ones.

@Graham Scanning through the input string to find all possible valid length-terminated subsequences is part of the code golf problem statement, not a description that the rules for reading this storage format should be to always look for sub-sequences that don't start at the memory location you're trying to read!

Python 2, 67 bytes
f=lambda l:l and[l[:x]for i,x in enumerate(l)if-~i==x][:1]+f(l[1:])

Try it online!

Jelly, 9 bytes
Ẇ=J$Ḅ⁼ɗƇ1

A monadic Link accepting a list of integers which yields a list of lists of integers.
Try it online!
Or ẆĖE€Ḅ⁼ʋƇ1 - Try it.
How?
Ẇ=J$Ḅ⁼ɗƇ1 - Link: list of integers
Ẇ         - all sublists
        1 - set right argument to 1
       Ƈ  - filter keep those (sublists) for which:
      ɗ   -   last three links as a dyad - i.e. f(sublist, 1):
   $      -     last two links as a monad i.e. g(sublist)
  J       -       range of length = [1,2,3,...,length]
 =        -       (sublist) equals (that)? (vectorises)
    Ḅ     -     from binary
     ⁼    -     (that) equals (1)?

7 bytes?

@cairdcoinheringaahing Nope, they are not valid when they include a valid prefix. (Otherwise 6)

JavaScript (V8), 65 bytes
Prints the results.
a=>a.map((_,i)=>a.every((v,j)=>j<i|v-++j+i||print(a.slice(i,j))))

Try it online!
Commented
a => a.map((_, i) => // for each value at position i in a[]:
  a.every((v, j) =>  //   for each value v at position j in a[]:
    j < i |          //     yield true and go on with the next iteration if j < i
    v - ++j + i      //     or v is not equal to j - i + 1 (increment j)
    || print(        //     otherwise, print ...
      a.slice(i, j)  //       ... the sublist of a[] from i to j - 1
    )                //     and break (print() returns undefined)
  )                  //   end of every()
)                    // end of map()

Is it any better to use reduce, and look at current-memo.length?

@Pureferret Do you mean reduce() instead of map() or instead of every()? I fail to see a shorter approach either way, but I've probably not fully understood what you are suggesting.

the former. I tried to get something wherein I would check the length at every stage, building up the array at the time. I was just playing, and couldn't figure out if it was better.

Python, 62 bytes
f=lambda l:l and[l[:x]for x in l if[x]==l[x-1:x]][:1]+f(l[1:])

Try it online!
This is a subtle improvement on @xnor's solution.
The solution we wish we could use is
f=lambda l:l and[l[:x]for x in l if x==l[x-1]][:1]+f(l[1:])

However, this will crash on an out-of-bounds index. xnor avoided this problem by using the index at which the value x appeared rather than actually indexing into l, but this required using the expensive enumerate function.
Instead, I used [x-1:x] to slice out the length-1 slice including the index we're interested in. Slicing in Python is much more permissive with respect to out of bounds errors. Now, we only need to check that the part of the list sliced out is [x].
Works in Python 2 or 3.

Nice improvement! I've posted a bounty, which I'll keep up for the 7 days to give this visibility.

Brachylog, 12 bytes
a₁ᶠ{a₀.l~t}ˢ

Try it online!
a₁ᶠ{      }ˢ    For every suffix of the input, if possible,
    a₀.         find the shortest prefix
       l        the length of which is
      . ~t      its last element.

An alternate generator solution using s, taking inspiration from Jonathan Allan's Jelly solution:
Brachylog, 13 12 bytes
s.i₁ᶠ=ˢ~gh~l

Try it online!
 .              The output is
s               any substring of the input
  i₁ᶠ           such that a list of all elements paired with their 1-indices
     =ˢ         filtered by equality
       ~g       has only one element, of which
         h      the first element
          ~l    is the length of the output.

What's wrong with using s?
-4 bytes: Try it online!

"and no prefix of the sequence is also a valid length-terminated sequence". Seems better to find the shortest prefix (if any) of every suffix than to filter the substrings for not having length-terminated prefixes.

(Your -4 bytes is in fact what I had before I noticed that it fails the third test case.)

Oof, missed that.

Haskell, 69 64 bytes
((1#)=<<).scanr(:)[]
l#(a:b)|l==a=[[a]]|m<-l+1=(a:)<$>m#b
_#_=[]

Edit: -5 bytes thanks to @Sriotchilism O'Zaic
Try it online!

64 byte version

Prolog (SWI), 67 bytes
X-Y:-X+Y+1.
[_|X]-Y:-X-Y.
[H|T]+[H|X]+N:-X=[],N=H,!;M is N+1,T+X+M.

Try it online!
Uses the -/2 predicate.
There are two parts to the code.
[H|T]+[H|X]+N:-X=[],N=H,!;M is N+1,T+X+M.

Essentially computes the shortest prefix that end in its length.  However it only does this when called with X+Y+1.
Then we have the main predicate -/2
X-Y:-X+Y+1.
[_|X]-Y:-X-Y.

This matches all the prefixes of X than end in their length:
X-Y:-X+Y+1.

and anything that matches the tail of X.
[_|X]-Y:-X-Y.

That turns our predicate over prefixes to a predicate over sublists.

This seems to fail on the third test case - it outputs [1], [1,2], [1,2,3], [1,2,3,4] and [1,2,3,4,5] when it should only output [1]

@SaraJ Ah then I must be misunderstanding the challenge.

@SaraJ Now that I undestand the issue I have resolved it. The indended problem is much easier to express in Prolog than the one I had interpreted.

Haskell, 59 bytes
(>>= \l->take 1[take x l|(i,x)<-zip[1..]l,i==x]).scanr(:)[]

Try it online!
60 bytes
f l@(h:t)=take 1[take x l|(i,x)<-zip[1..]l,i==x]++f t
f _=[]

Try it online!

Perl 5, 59 bytes
/(?<!\d).*?\b(\d++)(??{$1^1+$&=~y, ,,||"(*PRUNE)".say$&})^/

Try it online!

Charcoal, 38 bytes
ＩＥΦＬθ∧‹§θι⁺²ι⬤✂θ⁻⊕ι§θιι¹⁻λ⊕μ✂θ⁻⊕ι§θι⊕ι

Try it online! Link is to verbose version of code. Explanation:
    θ                                   Input array
   Ｌ                                    Length
  Φ                                     Filter over implicit range
       §θι                              Value at current index
      ‹                                 Is less than
          ⁺²ι                           Current index plus 2
     ∧                                  And
             ⬤                          For all elements of
              ✂θ                        Slice of input array
                ⁻⊕ι§θι                  From potential sequence start
                      ι¹                To current index
                         λ              Value
                        ⁻               Does not equal
                          ⊕μ            1-indexed index
 Ｅ                                      Map over matching indices
                            ✂θ⁻⊕ι§θι⊕ι  Extract sequence including length
Ｉ                                       Cast to string for implicit print

J, 28 22 bytes
a:-.~((#={:)\{.@#<\)\.

Try it online!
Take the empty boxes a: away from -.~ the following result:
For each postfix of the input \. do the following:
Filter # the boxed prefixes of the current input <\ using the boolean mask which asks, also for each prefix of the current input, "Is the length equal to the last item?" (#={:)\.
From those boxed prefixes that do pass the filter, take the first one {.@.  If no prefixes pass the filter, this will return the empty box a: (ie, the zero value of a list of boxes).
Note for J-ers: The function always returns a list of boxes, each of which contains a list of numbers.  This (desirable) consistency is what creates some of the seeming inconsistencies required to correctly specify the expected values of the test cases:

(,:1) -- a list containing 1
,:<,:1 -- a boxed list containing the list containing 1 (remember: a single box is an atom)

C (clang),  101 98 97  95 bytes
j;f(*l,z){for(l+=z;z;)if((j=-*--l)&&j>~z--&&j-~l[-1]|!z)for(puts("");printf("%d ",l[++j])*j;);}

Try it online!
-1 thanks to @ceilingcat
j;
f(*l,z){ // function taking a pointer and size
for(l+=z;z;) // move pointer to the end for backward iteration
if( // cascaded conditions :
  (j=-*--l) // skip if value is 0 while assigning to j its negation
  &&j>~z-- // skip if j>z ( before array begins)
  &&j-~l[-1] // skip if previous value is 1 less than value
  |!z // if z =0 previous value doesn't care
)
for(puts("") // newline to separate lists obtained
   ;printf("%d ",l[++j]) // print each value from j before l position
    *j;);} // to l (j=0)

Japt -mR, 12 bytes
WsV
¯ÒUbÈÉ¶Y

Try it
-mR         //Map each element in the input to the following program, and join with newlines
            //U is the element being mapped over
            //V is the index
            //And W is the original array
WsV         //Set U to the original array, removing the first V(index) elements
¯           //Take the first n elements, where n is the following:
   Ub       //  The first index in U which satisfies the following condition
     ÈÉ¶Y   //    Where the element at that index minus one equals the index
  Ò         //   Add 1 to that result

Ruby, 72 70 bytes
-2 bytes by somehow typing a.length instead of a.size when constructing the range, but still using the correct function later down the line when checking the sequences.
->a{(r=0..a.size).map{|i|r.map{|j|a[i,j]}.find{|s|s[-1]==s.size}}-[p]}

Try it online!

Perl 6, 40 bytes
{~<<m:ov/(<<\d+>>)+?%\s<!{$0-$0.tail}>/}

Try it online!
Regex-based approach working with strings of space-separated numbers.
35 bytes when working directly with ASCII strings:
{~<<m:ov/(.)+?<!{$0-$0.tail.ord}>/}

Try it online!
Explanation
{                                      }  # Anonymous block
    m:ov/                             /   # Find all overlapping matches
          <<       # Left word boundary
            \d+    # One or more digits
               >>  # Right word boundary
         (       )+?     # One or more numbers, lazy
                    %\s  # Separated by space
                       <!{          }>  # Negative boolean condition check
                          $0-$0.tail    # Count of numbers minus last number
 ~<<  # Stringify matches

Curry, 33 bytes
Tested in both KiCS2 and PAKCS.
f(_++u++x:_)|x==1+length u=u++[x]

Curry's powerful patterns let it beat the Haskell answer once again!
To test it you can use Smap.  Just select KiCS2 2.2.0 or PAKCS 2.2.0 with the /all-values option and paste the following complete code:
f(_++u++x:_)|x==1+length u=u++[x]
main=f [7, 6, 5, 4, 3, 2, 1]

Python 3, 98 bytes
lambda s,e=enumerate:[s[i-n:i]for i,n in e([9]+s)if all(m+~j for j,m in e(s[i-n:i-1]))>0<n<=i]

Try it online!
Takes the input as a list and maps it to a list of lists where each item is a sublist of length n ending with item n for each item. Then it is filtered so that no list contains other valid length terminators.
-4 bytes thanks to Jonathan Frech

m!=j+1for can be golfed to m+~j for, saving one byte.

all(...)and 0<... could possibly be all(...)>0<....

PHP, 90 bytes
for(;++$i<$c=count($argv);)for($j=$i;$c>$j;$j-$i-$n?:$c=print_r($$i))$$i[]=$n=$argv[$j++];

Try it online!
Input sequence is sent using command arguments (each number is one argument) and output is string representation of arrays using PHP's print_r.
for(;                  // outer loop on $argv input items
  ++$i<                // $i is current index, starts from second item as PHP fills first item with script's name
  $c=count($argv);     // $c is total number of input items
)
  for(                 // inner loop on input items
    $j=$i;             // $j is inner loop's index, always starts from outer loop's index
    $c>$j;             // continue while inner index is less than $c
    $j-$i-$n?:         // THIS IS RUN LAST: if current number ($n) is equal to $j-$i ($j is incremented by one already, so $j-$i gives a position starting from 1 in the $$i)
       $c=print_r($$i) // THIS IS RUN LAST: print the $$i array and set $c to 1 to break the inner loop
  )
    $$i[]=             // THIS IS RUN FIRST: push into an array named by value of $i (if $i=2, variable name is 2)
    $n=$argv[$j++];    // THIS IS RUN FIRST: current number in index of inner loop and increment the index ($j) by one, $n also keeps current number

Red, 149 121 bytes
func[b][j: i: 0 until[if(i: i + 1)> n: length? b[j: j + 1 i: 1]if
b/(j + i) = i[print[copy/part at b j + 1 i]i: n]j = n]]

Try it online!

Zsh,  35 37 bytes
+2 bytes to suppress zero-length lists
for x;((s=++i-x+1,x*s>0))&&<<<$@[s,i]

Try it online!
For each element in the input, calculate the index of where the sequence would have to start. If the start index and the element are both >0, then print the elements from there to the current index, inclusive.

RE your edit, I'd say no in this case. Since each of your lists otherwise occupy exactly one line, a blank line would mean explicitly outputting the empty list, which should never be part of the output.

Thanks Sara, edited.

Icon, 121 bytes
procedure f(b)
r:=[];i:=j:=0
while j<*b do{if*b<(i+:=1)then j+:=1&i:=0 else b[j+i]=i&put(r,b[j+1+:i])&i:=*b}
return r
end

Try it online!

Ruby 2.7-preview1, 50 bytes
Uses Ruby 2.7's new Enumerable#filter_map method. (Sorry for no TiO link; TiO is still on Ruby 2.5.5.)
->a{i=0
a.filter_map{|c|i+=1
c>0&&c<=i&&a[i-c,c]}

Miss a closing brace somewhere?

Also fails on [1,2,3,4,5]

T-SQL, 175 bytes
with s(r,i)as(select row_number()over(order by(rand())),*from string_split(<Comma delimited integer string>,','))select string_agg(l.i,',')from s,s l where l.r>s.r-s.i and l.r<=s.r and s.r-s.i>=0group by s.i

Try it online!

Verbose version
with s(r,i) as
(
    select row_number() over (order by (rand())) -- Add a row number for sorting
          ,*
    from string_split('7,6,5,4,3,2,1',',')       -- to the split out integer list
)
select string_agg(l.i,',')                       -- then aggregate back together
from s,s l                                       -- joining to itself
where l.r > s.r - s.i                            --   where the previous numbers sit in rows between [current int value] rows before
    and l.r <= s.r                               --     and the current row
    and s.r - s.i >= 0                           --     and there are enough list items for the current integer value
group by s.i                                     -- grouped to each output string

Ruby, 64 bytes
->a,*s{(r=0;a.find{|x|(x==r+=1)&&s<<a[0,x]};w,*a=a)while a[0];s}

Try it online!

Prolog (SWI), 135 bytes
A*B:-reverse(A,B).
[]-_. [A|Q]-[A|R]:-Q-R.
+[Q|R]:-length([Q|R],Q),\+((R*Z,X-Z,S*X,+S)).
Q/R:-N-Q,N*Z,X-Z,R*X,+X.
X//Y:-bagof(R,X/R,Y).

Try it online!
A*B is reverse(A,B)
A-B is true if A is a prefix of B
+A is true if A is a valid encoding, i.e. length-terminated list
A/B is true if, given list A, B is contained within A and B is a valid encoding
A//B is true if, given list A, Y is the list of all valid encodings in A (if there are no valid encodings in A, A//B fails)
Calling predicate ///2 with the left argument a list and the right argument a variable unifies the variable with the required result. For example, [7,6,5,4,3,2,1]S. will unify S with the [[7, 6, 5, 4], [5, 4, 3], [3, 2], [1]]. The TIO link contains a helper predicate that runs all inputs with against this predicate.
Verbose
prefix([],_).
prefix(_,[]):-1<0.
prefix([A|Q], [A|R]):-
	prefix(Q,R).
suffix(A, B):-
	reverse(B, Q),
	prefix(P, Q),
	reverse(A, P).
encoded([H|T]):-
	length([H|T], H),
	\+((suffix(P,T), encoded(P))).
f(Q, R):-
	prefix(N, Q),
	suffix(R, N),
	reverse(R, T),
	encoded(T).
g(List, All):-
	bagof(Encoding, f(List, Encoding), All).

Try it online!
The tricks used from this verbose solution is to first create another predicate for reverse because it is repeated many times. Then operators are used in place of predicate names. The predicate for suffix turns out to only be used once, so it can be removed, replacing its call in f with its conditions. Doing this removes the need to use reverse(R, T) as the suffix predicate already has the same condition.

05AB1E, 12 bytes
ŒʒDη.Δ¤sgQ}Q

Try it online or verify all test cases.
Explanation:
Œ           # Get all sublists of the (implicit) input-list
 ʒ          # Filter it by:
  D         #  Duplicate the current sublist
   η        #  Pop the copy and push its prefixes
    .Δ      #  Find the first prefix that's truthy for:
            #  (or -1 if none are)
      ¤     #   Push the last value (without popping the list itself)
       s    #   Swap so the list is at the top
        g   #   Pop and push its length
         Q  #   Check if the two values are the same
     }Q     #  After the find_first: Check if both are the same
            # (after which the filtered list is output implicitly)

The ¤sgQ could alternatively be DgÅ¿ or Ðθ∍Q for the same byte-count.
      D     #   Duplicate the list
       g    #   Pop the copy and push its length
        Å¿  #   Check if the list ends with this length as trailing value

      Ð     #   Triplicate the list
       θ    #   Pop one copy and push its last value
        ∍   #   Extend/shorten another copy to this length
         Q  #   Check if the two lists are still the same

APL(NARS), chars 148, bytes 296
r←f w;i;j;v;q
k←≢w⋄r←⍬⋄i←0⋄w←(⍳k),¨w
→4×⍳k<i+←1⋄→2×⍳(j>q←≢v←i↑w)∨0=j←2⊃i⊃w⋄v←v↓⍨q-j⋄→3×⍳r≡⍬⋄→2×⍳∨/{(⍵[1]≡v[1])∧⍵⊆v}¨r
r←r,⊂v⋄→2
→0×⍳r≡⍬⋄r←{⍵[2]}¨¨r

because of the problem one has to know index of the element, the input set is elaborate as one set with indices  (w←(⍳k),¨w) that in the end were removed (in r←{⍵[2]}¨¨r) test:
  ⎕fmt f 90 80 70
┌0─┐
│ 0│
└~─┘
  ⎕fmt f 100 0  2  2  2 0 0 2 4
┌5─────────────────────────────────────┐
│┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐ ┌4───────┐│
││ 0 2│ │ 2 2│ │ 2 2│ │ 0 2│ │ 0 0 2 4││
│└~───┘ └~───┘ └~───┘ └~───┘ └~───────┘2
└∊─────────────────────────────────────┘
  ⎕fmt f 7 6 5 4 3 2 1
┌4──────────────────────────────┐
│┌4───────┐ ┌3─────┐ ┌2───┐ ┌1─┐│
││ 7 6 5 4│ │ 5 4 3│ │ 3 2│ │ 1││
│└~───────┘ └~─────┘ └~───┘ └~─┘2
└∊──────────────────────────────┘
  ⎕fmt f 1 2 3 4 5
┌1───┐
│┌1─┐│
││ 1││
│└~─┘2
└∊───┘
  ⎕fmt f ⍬
┌0─┐
│ 0│
└~─┘