index | submit | rank | book

function – Mathematical Function (challenge)

Write a program that given a pair of assignments f(x₁) = y₁ and f(x₂) = y₂, calculates the function f, given by f(x) = ax + b

Example 1. If f(0) = 0 and f(1) = 1 then f(x) = x.

Example 2. If f(0) = 42 and f(5) = 42 then f(x) = 42.

Example 3. If f(1) = 6 and f(4) = 12 then f(x) = 2x + 4.

Input and output

You program should read and write from the standard input and output devices. For each line of input containing the assignments for x₁, y₁, x₂ and y₂, your program should print a line describing the function in the format f(x) = .... If no such function is possible, print impossible.

-1000.0 ≤ x₁, y₁, x₂, y₂ ≤ 1000.0

x₁, y₁, x₂, y₂ are up to two decimal places

The values of a and b should be rounded to one decimal place, exhibiting the decimal place only when needed. Halfway cases should be rounded towards the nearest even digit. Omit a and b from the output when possible. In general, your program should print less symbols as possible.

Example input

0 0 1 1
0 42 60 42
1 6 4 12
3 7 5 8
0 -1 -1 0

Example output

f(x) = x
f(x) = 42
f(x) = 2x + 4
f(x) = 0.5x + 5.5
f(x) = -x - 1



This exercise is a challenge! Though it is easy to get a 2/6 score, you will find it difficult to reach 3/6, 4/6, 5/6 and 6/6. The test cases in the automated scorer are tough! If you are up for the challenge, here are some hints that may help:

Easier exercise. Make sure you are able to solve function1 first. It is an easier version of this exercise with simplfied output and more forgiving test cases.

Reference output. Output has to be exactly as described. For example, it’s 2x + 4 and not 2*x + 4.

Edge cases. Try to think of edge cases to test your program. For example: What if the resulting function is a constant zero? What about the given example test cases with signals inverted? What about the given example test cases with pairs of points inverted? When exactly is impossible to produce a function?

Rounding. Be careful when rounding to the nearest integer, as always:

When rounding, sometimes there is a tie, i.e.: a half-way case. These should be rounded towards the nearest even digit:

Here is an interesting fact: there are at least 9 different ways in which one can round halfway cases. In this exercise, you should round “half to even”.

try first: function1 pi

index | submit | rank | book

Copyright © 2020-2021 Rudy Matela
All rights reserved