Knit row stitch check
EasyOnline Assessment
Check a knitting pattern row by row to make sure every row can actually be worked with the stitches on the needle.
A knitter casts on cast_on stitches. Each row of the pattern is a string of instructions separated by single spaces, worked left to right across all the stitches currently on the needle. Every instruction uses up some stitches from the needle and produces some new ones:
| instruction | uses | makes |
|---|---|---|
k, p, sl | 1 | 1 |
k<n>, p<n>, sl<n> (plain stitches, e.g. k5) | n | n |
k<n>tog, p<n>tog (e.g. k2tog), ssk (equal to k2tog) | n (ssk: 2) | 1 |
kfb, pfb | 1 | 2 |
yo, m1 | 0 | 1 |
co<n> (cast on n more stitches) | 0 | n |
A group (instr instr ...)xN means the instructions inside the brackets are worked N times in a row; groups are never nested. For example (k2tog yo)x2 is the same as k2tog yo k2tog yo.
A row is valid when the total number of stitches its instructions use equals the number of stitches on the needle at the start of that row. The stitches it makes are then on the needle for the next row. Stop at the first invalid row: it and every later row are not worked.
Input: cast_on, the starting stitch count, and rows, the list of row strings.
Output: a list with the stitch count on the needle after each valid row, in order, ending just before the first invalid row (or after the last row if all are valid). Return [] if rows is empty or the first row is invalid.
Example 1
- Input:
- [12,["k2 (k2tog yo)x2 k6","kfb k11","k12"]]
- Output:
- [12,13]
- Explanation
- Row 1 on 12 stitches:
k2uses 2,(k2tog yo)x2isk2tog yo k2tog yoand uses 4 and makes 4,k6uses 6; that is 12 used, matching the needle, and makes 2 + 4 + 6 = 12. Row 2:kfbuses 1 and makes 2,k11uses 11, so 12 used and 13 made. Row 3k12uses only 12 of the 13 stitches, so it is invalid and the answer stops:[12, 13].
Example 2
- Input:
- [8,["ssk k4 k2tog","(kfb)x6","p3tog k9","co2 k10","k"]]
- Output:
- [6,12,10,12]
- Explanation
- Row 1 uses
ssk2 +k44 +k2tog2 = 8 of 8 and makes 6. Row 2(kfb)x6uses 6 and makes 12. Row 3:p3toguses 3 and makes 1,k9uses 9, so 12 used and 10 made. Row 4:co2uses nothing but makes 2,k10uses all 10, leaving 12. Row 5 is a barek, which uses just 1 of 12 stitches, so it fails.
Example 3
- Input:
- [4,["k2 p3tog","k4"]]
- Output:
- []
- Explanation
k2 p3toguses 2 + 3 = 5 stitches but only 4 are on the needle, so the very first row is invalid and the result is empty.
Constraints
1 <= cast_on <= 5000 <= rows.length <= 200- every row is a non-empty valid instruction string of at most 80 characters, built only from the instructions in the table and non-nested groups
- every
nand every repeat countNis an integer from1to99