You type an English string on an old mobile phone keypad. The keypad has thirteen keys: 0–9, #, * and _. 1–9 are letter keys, and each has a fixed list of characters that it cycles through. 1 has .,?!, 2 has abc, 3 has def, 4 has ghi, 5 has jkl, 6 has mno, 7 has pqrs, 8 has tuv, and 9 has wxyz. While typing, you keep track of the 'written string', the 'case mode' and the 'pending character'. At the start of each line the written string is empty, the case mode is 'lower', and there is no pending character. There is at most one pending character; it consists of one letter key and the number c of times that key has been pressed in a row. If the key has m characters, the pending character is character number ((c − 1) mod m + 1) of that key's list. So pressing 2 once gives a, three times gives c, and four times gives a again. 'Writing' happens only when there is a pending character: append it to the end of the written string and clear the pending character. If the character to write is a lowercase English letter and the case mode is 'one capital', write it in uppercase and set the case mode to 'lower'. If the character to write is a lowercase English letter and the case mode is 'caps lock', write it in uppercase and leave the case mode as it is. The punctuation marks ., ,, ? and ! are always written as they are and never change the case mode. Each key does the following. - A letter key: if the pending character belongs to the same key, add 1 to c. Otherwise, first do a writing, then create a new pending character for this key pressed once. - _: do a writing. - 0: do a writing, then append one space to the end of the written string. - #: do a writing, then change the case mode to the next one in the order 'lower' → 'one capital' → 'caps lock' → 'lower'. - *: if there is a pending character, clear it without writing it. If there is none, delete the last character of the written string, or do nothing if the written string is empty. In either case the case mode does not change. Adding or deleting spaces and punctuation marks never affects the case mode. After all keys of a line have been pressed, do one last writing. For each line, find the written string obtained this way.
Input
The first line gives the number of lines n. Each of the next n lines gives the keys pressed, in order, with no spaces. 1 ≤ n ≤ 100; each key line has 1 to 1,000 characters and consists only of 0–9, #, * and _. Each key line is typed separately from the initial state. The written string, case mode and pending character of a line do not carry over to the next line.
Output
For each key line, in input order, print the written string between < and > on one line. If the written string is empty, print <>.
Example 1 · stdin
1
#4433555_5556660966677755531111
stdout
<Hello world!>
Example 2 · stdin
3
#11_27777*8
##7777_0882**
*2*
stdout
<,At>
<S >
<>
main.py
Error List00F8 ↓ · ⇧F8 ↑
Input (stdin)
When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).
$ Ready
Open this on a computer to write and run code. On mobile you can read the problem and the solutions.
In other languagesShow solutions by language · 8 languages
The five-way choice of what to do for each key (_, 0, #, *, a letter key) is the switch of this problem. C, C++, Java and C# switch on a character with case '0':, JS and TS on a one-character string with case "0":, Python uses match p: with case "0": and case _: (since 3.10), and Craykon writes switch (p) { case "0": … break; default: … }. The Java solution here uses the arrow form case '0' -> { … }; the C++ solution uses a second switch to change the case mode (an enum class), and the C# solution uses the switch expression mode switch { Mode.Lower => Mode.Once, … } there. 'Writing' is a nested function with nonlocal in Python, an inner function (a lambda in C++) that uses outer variables in JS, TS and C++, and a function on global or static variables in C, Java and C#. The Craykon solution keeps the state in one Dict and passes it to its write function, and a change to st["mode"] inside the function is visible outside it. Trap one: leaving out break. In C, C++, Java (colon form), JS and TS a switch falls through to the next case when there is no break. Drop the break at the end of case '0': in the C solution and every space also runs case '#', which changes the case mode, so example 1 prints <Hello World!> instead of <Hello world!>. In C# a non-empty case that falls through is a compile error (CS0163), and Java's arrow form, Python's match and Craykon's switch do not fall through. Trap two: JS switch compares with ===. A character taken from a string is the string "0", which is not equal to case 0: (a number). The 0 key then goes to default (the letter keys), and the next writing stops with a TypeError when it reads .length of KEYS["0"], which is undefined. TS rejects the same code with type error TS2678. In C, C++ and Java case 0: compiles but is not the character '0' (code 48), so the 0 key again goes to the letter-key branch, and with the structure of these solutions that divides by the length 0 of the empty KEYS[0] (an ArithmeticException in Java). In C# the int constant 0 cannot be converted to char, so case 0: is a compile error (CS0266). Trap three: assuming every key has three characters.7, 9 and the punctuation key 1 have four. If every key cycles with % 3, the second line of example 2, ##7777…, gets p instead of s and <S > becomes <P >. Every solution here divides by the length of that key's list. Trap four: spending 'one capital' on a punctuation mark. The mode must be reset only when an English letter is written. If it is reset whenever anything is written, the comma in the first line of example 2, #11_2…, uses it up and <,At> becomes <,at>. Trap five: * deleting a written character. When there is a pending character, * throws away only that character. If you miss this and always delete the end of the written string, the pending character survives and the one before it disappears, so the first two lines of example 2 print <,st> and <SA>.
Pythonmain.py · 60 lines
import sys# 글자 키마다 차례로 돌아가며 나오는 글자들KEYS = { "1": ".,?!", "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz",}LOWER, ONCE, CAPS = 0, 1, 2 # 소문자, 한 글자 대문자, 대문자 고정def type_line(presses): text = [] mode = LOWER key, count = None, 0 # 쓰는 중인 글자: 키와 누른 횟수 (key가 None이면 없음) def commit(): nonlocal key, mode if key is None: return letters = KEYS[key] ch = letters[(count - 1) % len(letters)] if ch.isalpha() and mode != LOWER: ch = ch.upper() if mode == ONCE: mode = LOWER text.append(ch) key = None for p in presses: match p: case "_": commit() case "0": commit() text.append(" ") case "#": commit() mode = (mode + 1) % 3 case "*": if key is not None: key = None # 쓰는 중인 글자만 버린다 elif text: text.pop() case _: # 글자 키 1~9 if p == key: count += 1 else: commit() key, count = p, 1 commit() return "".join(text)def main(): lines = sys.stdin.read().split() n = int(lines[0]) print("\n".join("<" + type_line(lines[i]) + ">" for i in range(1, n + 1)))main()
JavaScriptmain.js · 60 lines
// 글자 키마다 차례로 돌아가며 나오는 글자들const KEYS = { "1": ".,?!", "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz",};const LOWER = 0, ONCE = 1, CAPS = 2; // 소문자, 한 글자 대문자, 대문자 고정function typeLine(presses) { const text = []; let mode = LOWER; let key = null, count = 0; // 쓰는 중인 글자: 키와 누른 횟수 (key가 null이면 없음) function commit() { if (key === null) return; const letters = KEYS[key]; let ch = letters[(count - 1) % letters.length]; if (ch >= "a" && ch <= "z" && mode !== LOWER) { ch = ch.toUpperCase(); if (mode === ONCE) mode = LOWER; } text.push(ch); key = null; } for (const p of presses) { switch (p) { // p는 한 글자 문자열이라 case도 "0"처럼 문자열로 쓴다 case "_": commit(); break; case "0": commit(); text.push(" "); break; case "#": commit(); mode = (mode + 1) % 3; break; case "*": if (key !== null) key = null; // 쓰는 중인 글자만 버린다 else if (text.length > 0) text.pop(); break; default: // 글자 키 1~9 if (p === key) { count++; } else { commit(); key = p; count = 1; } } } commit(); return text.join("");}const words = require("fs").readFileSync(0, "utf8").split(/\s+/).filter((w) => w.length > 0);const n = Number(words[0]);const out = [];for (let i = 1; i <= n; i++) out.push("<" + typeLine(words[i]) + ">");console.log(out.join("\n"));
TypeScriptmain.ts · 63 lines
import { readFileSync } from "node:fs";// 글자 키마다 차례로 돌아가며 나오는 글자들const KEYS: Record<string, string> = { "1": ".,?!", "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz",};enum Mode { Lower, Once, Caps } // 소문자, 한 글자 대문자, 대문자 고정function typeLine(presses: string): string { const text: string[] = []; let mode: Mode = Mode.Lower; let key: string | null = null; // 쓰는 중인 글자의 키 (null이면 없음) let count = 0; // 그 키를 누른 횟수 function commit(): void { if (key === null) return; const letters: string = KEYS[key]; let ch: string = letters[(count - 1) % letters.length]; if (ch >= "a" && ch <= "z" && mode !== Mode.Lower) { ch = ch.toUpperCase(); if (mode === Mode.Once) mode = Mode.Lower; } text.push(ch); key = null; } for (const p of presses) { switch (p) { // p는 한 글자 문자열이라 case도 "0"처럼 문자열로 쓴다 case "_": commit(); break; case "0": commit(); text.push(" "); break; case "#": commit(); mode = (mode + 1) % 3; break; case "*": if (key !== null) key = null; // 쓰는 중인 글자만 버린다 else if (text.length > 0) text.pop(); break; default: // 글자 키 1~9 if (p === key) { count++; } else { commit(); key = p; count = 1; } } } commit(); return text.join("");}const words: string[] = readFileSync(0, "utf8").split(/\s+/).filter((w: string) => w.length > 0);const n: number = Number(words[0]);const out: string[] = [];for (let i = 1; i <= n; i++) out.push("<" + typeLine(words[i]) + ">");console.log(out.join("\n"));
JavaMain.java · 72 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class Main { // 글자 키 1~9마다 차례로 돌아가며 나오는 글자들 static final String[] KEYS = {"", ".,?!", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; static final int LOWER = 0, ONCE = 1, CAPS = 2; // 소문자, 한 글자 대문자, 대문자 고정 static StringBuilder text; static int mode; static char key; // 쓰는 중인 글자의 키 ('\0'이면 없음) static int count; static void commit() { if (key == '\0') return; String letters = KEYS[key - '0']; char ch = letters.charAt((count - 1) % letters.length()); if (ch >= 'a' && ch <= 'z' && mode != LOWER) { ch = Character.toUpperCase(ch); if (mode == ONCE) mode = LOWER; } text.append(ch); key = '\0'; } static String typeLine(String presses) { text = new StringBuilder(); mode = LOWER; key = '\0'; count = 0; for (char p : presses.toCharArray()) { // 화살표 꼴 switch는 다음 case로 이어 내려가지 않는다 switch (p) { case '_' -> commit(); case '0' -> { commit(); text.append(' '); } case '#' -> { commit(); mode = (mode + 1) % 3; } case '*' -> { if (key != '\0') key = '\0'; // 쓰는 중인 글자만 버린다 else if (text.length() > 0) text.setLength(text.length() - 1); } default -> { // 글자 키 1~9 if (p == key) { count++; } else { commit(); key = p; count = 1; } } } } commit(); return text.toString(); } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine().trim()); StringBuilder out = new StringBuilder(); for (int i = 0; i < n; i++) { out.append('<').append(typeLine(in.readLine().trim())).append(">\n"); } System.out.print(out); }}
C#Main.cs · 88 lines
using System;using System.Text;class Program{ // 글자 키 1~9마다 차례로 돌아가며 나오는 글자들 static readonly string[] Keys = { "", ".,?!", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; enum Mode { Lower, Once, Caps } // 소문자, 한 글자 대문자, 대문자 고정 static StringBuilder text = new StringBuilder(); static Mode mode; static char key; // 쓰는 중인 글자의 키 ('\0'이면 없음) static int count; static void Commit() { if (key == '\0') return; string letters = Keys[key - '0']; char ch = letters[(count - 1) % letters.Length]; if (ch >= 'a' && ch <= 'z' && mode != Mode.Lower) { ch = char.ToUpper(ch); if (mode == Mode.Once) mode = Mode.Lower; } text.Append(ch); key = '\0'; } static string TypeLine(string presses) { text.Clear(); mode = Mode.Lower; key = '\0'; count = 0; foreach (char p in presses) { // C#은 내용이 있는 case 끝에 break가 없으면 컴파일 오류다 switch (p) { case '_': Commit(); break; case '0': Commit(); text.Append(' '); break; case '#': Commit(); mode = mode switch { Mode.Lower => Mode.Once, Mode.Once => Mode.Caps, _ => Mode.Lower, }; break; case '*': if (key != '\0') key = '\0'; // 쓰는 중인 글자만 버린다 else if (text.Length > 0) text.Length--; break; default: // 글자 키 1~9 if (p == key) { count++; } else { Commit(); key = p; count = 1; } break; } } Commit(); return text.ToString(); } static void Main() { int n = int.Parse(Console.ReadLine().Trim()); var output = new StringBuilder(); for (int i = 0; i < n; i++) { output.Append('<').Append(TypeLine(Console.ReadLine().Trim())).Append(">\n"); } Console.Write(output); }}
C++main.cpp · 72 lines
#include <iostream>#include <string>// 글자 키 1~9마다 차례로 돌아가며 나오는 글자들const std::string KEYS[10] = {"", ".,?!", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};enum class Mode { Lower, Once, Caps }; // 소문자, 한 글자 대문자, 대문자 고정std::string typeLine(const std::string& presses) { std::string text; Mode mode = Mode::Lower; char key = '\0'; // 쓰는 중인 글자의 키 ('\0'이면 없음) int count = 0; auto commit = [&]() { if (key == '\0') return; const std::string& letters = KEYS[key - '0']; char ch = letters[(count - 1) % letters.size()]; if (ch >= 'a' && ch <= 'z' && mode != Mode::Lower) { ch = static_cast<char>(ch - 'a' + 'A'); if (mode == Mode::Once) mode = Mode::Lower; } text += ch; key = '\0'; }; for (char p : presses) { switch (p) { case '_': commit(); break; case '0': commit(); text += ' '; break; case '#': commit(); switch (mode) { // enum class도 switch로 다음 방식을 고른다 case Mode::Lower: mode = Mode::Once; break; case Mode::Once: mode = Mode::Caps; break; case Mode::Caps: mode = Mode::Lower; break; } break; case '*': if (key != '\0') key = '\0'; // 쓰는 중인 글자만 버린다 else if (!text.empty()) text.pop_back(); break; default: // 글자 키 1~9 if (p == key) { count++; } else { commit(); key = p; count = 1; } break; } } commit(); return text;}int main() { std::ios::sync_with_stdio(false); int n; std::cin >> n; std::string line; for (int i = 0; i < n; i++) { std::cin >> line; std::cout << '<' << typeLine(line) << ">\n"; } return 0;}
Cmain.c · 69 lines
#include <stdio.h>#include <string.h>/* 글자 키 1~9마다 차례로 돌아가며 나오는 글자들 */static const char *KEYS[10] = {"", ".,?!", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};enum { LOWER, ONCE, CAPS }; /* 소문자, 한 글자 대문자, 대문자 고정 */static char text[1001];static int len, mode;static char key; /* 쓰는 중인 글자의 키 ('\0'이면 없음) */static int count;static void commit(void) { if (key == '\0') return; const char *letters = KEYS[key - '0']; char ch = letters[(count - 1) % (int)strlen(letters)]; if (ch >= 'a' && ch <= 'z' && mode != LOWER) { ch = (char)(ch - 'a' + 'A'); if (mode == ONCE) mode = LOWER; } text[len++] = ch; key = '\0';}int main(void) { int n; static char line[1001]; if (scanf("%d", &n) != 1) return 0; for (int t = 0; t < n; t++) { scanf("%1000s", line); len = 0; mode = LOWER; key = '\0'; count = 0; for (int i = 0; line[i] != '\0'; i++) { char p = line[i]; switch (p) { case '_': commit(); break; case '0': commit(); text[len++] = ' '; break; case '#': commit(); mode = (mode + 1) % 3; break; case '*': if (key != '\0') key = '\0'; /* 쓰는 중인 글자만 버린다 */ else if (len > 0) len--; break; default: /* 글자 키 1~9 */ if (p == key) { count++; } else { commit(); key = p; count = 1; } break; } } commit(); text[len] = '\0'; printf("<%s>\n", text); } return 0;}
Craykonmain.cray · 84 lines
// 글자 키 1~9마다 차례로 돌아가며 나오는 글자들KEYS = ["", ".,?!", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];// 쓰는 중인 글자가 있으면 문자열 끝에 적는다// st: "text" 적은 글자 목록, "mode" 0 소문자·1 한 글자 대문자·2 대문자 고정,// "key" 쓰는 중인 글자의 키(""이면 없음), "count" 그 키를 누른 횟수적기(st){ if (st["key"] == "") { return 0; } letters = KEYS[st["key"].ToNumber()]; ch = letters[(st["count"] - 1) % letters.Length]; if (ch >= "a" && ch <= "z" && st["mode"] != 0) { ch = ch.ToUpper(); if (st["mode"] == 1) { st["mode"] = 0; } } st["text"].Add(ch); st["key"] = ""; return 0;}// 한 줄의 키를 차례로 누른 결과 문자열줄치기(presses){ st = Dict(); st["text"] = []; st["mode"] = 0; st["key"] = ""; st["count"] = 0; for (i = 0; i < presses.Length; i = i + 1) { p = presses[i]; switch (p) { case "_": 적기(st); break; case "0": 적기(st); st["text"].Add(" "); break; case "#": 적기(st); st["mode"] = (st["mode"] + 1) % 3; break; case "*": if (st["key"] != "") { st["key"] = ""; // 쓰는 중인 글자만 버린다 } else if (st["text"].Count > 0) { st["text"].RemoveAt(st["text"].Count - 1); } break; default: if (p == st["key"]) { st["count"] = st["count"] + 1; } else { 적기(st); st["key"] = p; st["count"] = 1; } break; } } 적기(st); return st["text"].Join("");}n = Console.ReadLine().Trim().ToNumber();for (t = 0; t < n; t = t + 1){ Console.WriteLine("<" + 줄치기(Console.ReadLine().Trim()) + ">");}