Learn/TypeScript/3. Reading input and arithmetic
Lesson 3 of 15
Sign in

TypeScript, lesson 3

Reading input and arithmetic

Your programs get their data from standard input (stdin): the tests feed text into the program, and the program reads it. This lesson shows the one line you will use for that in every exercise from now on, and how to turn the text into numbers.

Reading stdin in Deno

There is a lot packed into that line, so take it apart:

  • Deno.stdin.readable is standard input as a stream of bytes that arrive over time.
  • Response is a standard web class for "a body of data". Wrapping the stream in a Response gives you its handy text() method, which collects every chunk until the input ends and decodes the bytes as UTF-8 text.
  • text() is : it returns a , a value that will be ready later. pauses until it is ready and hands you the .

2 exercises to try what you just read.

Exercise 1

Paint the wall

Press Ctrl Enter or Check to test your code.

Exercise 2

Change machine

Press Ctrl Enter or Check to test your code.

asynchronous
Promise<string>
await
string

Deno treats each file as a module, and modules allow await at the top level, so no extra setup is needed. The type of input is inferred as string. (Deno's prompt() function is meant for interactive terminals and returns null when input is piped in, which is what the runner does, so stick to the line above.)

Splitting the input

The input is one long string such as "12\n30\n". Break it up with string methods:

trim() removes whitespace at both ends, which also drops the final line break. split(/\s+/) splits on any run of spaces or tabs. The type string[] means "an array of strings"; you will learn arrays properly in the collections lesson.

Text to numbers

The pieces are still strings. The type checker will stop you from doing maths on them:

Convert with Number():

Number() requires the whole string to be numeric. parseInt(text, 10) and parseFloat(text) read a leading number and ignore the rest. NaN is still of type number, so the type checker cannot catch bad input for you; you will handle that in the errors lesson.

A handy idiom converts a whole array at once: words.map(Number) gives number[].

Operators

OperatorMeaningExampleResult
+ - *add, subtract, multiply7 * 214
/divide7 / 23.5
%remainder7 % 21
**power2 ** 101024

There is no separate integer division. Use Math.floor(7 / 2) (gives 3) or Math.trunc (rounds toward zero). Compound assignments update a variable in place: total += 5, n *= 2, count++.

Formatting results

toFixed(d) rounds to d decimals and returns a string, ready to print. Math.round, Math.floor and Math.ceil return numbers.

Further reading

  • Deno API: Deno.stdin
  • MDN: Response.text()
  • MDN: Number
  • MDN: Expressions and operators

You are painting a wall. The input has two numbers on one line: the wall's width and height in metres (decimals allowed). One litre of paint covers 10 square metres. Print the area with two decimals, and the number of whole litres to buy (always round up).

Sample input:

Sample output:

A vending machine gives change in coins of 50, 20, 10, 5 and 1 cents, always using as few coins as possible (largest coins first). The input is one whole number: the change in cents (0 or more). Print how many coins of each kind it gives, one kind per line, in the form VALUE: COUNT, from 50 down to 1.

Sample input:

Sample output:

Use Math.floor for the count and % for what is left over.

const input = await new Response(Deno.stdin.readable).text();
const lines: string[] = input.trim().split("\n");   // ["12", "30"]
const words = "4  7 9".trim().split(/\s+/);          // ["4", "7", "9"]
const a = "12";
const b = a * 2;   // error: the left-hand side must be of type 'number'
const n: number = Number("12");    // 12
Number(" 3.5 ");                   // 3.5
Number("12kg");                    // NaN (not a number)
const share = 100 / 3;
console.log(share.toFixed(2));   // 33.33
4.5 2.4
Area: 10.80 m2
Paint: 2 L
87
50: 1
20: 1
10: 1
5: 1
1: 2