Function taking on all values thrice I recently saw the following puzzle somewhere:

Find a continuous, surjective function $f:\mathbb R\mapsto\mathbb R$ that takes on each of its values exactly three times.

Or, more technically stated,

Find a continuous, surjective function $f:\mathbb R\mapsto\mathbb R$, such that for all $y\in\mathbb R$, there exist exactly three real solutions $x$ to the equation $f(x)=y$.

My solution to this puzzle was the function
$$f(x)=\sin^2 \frac{3\pi(x-\lfloor x\rfloor)}{2}+\lfloor x\rfloor$$
Since then, I've thought of a few variations on this puzzle, none of which I have been able to solve:

  
*
  
*Can a function $g:\mathbb R\mapsto \mathbb R^2$ satisfy these requirements? What about a function $h:\mathbb R^2\mapsto \mathbb R$?
  
*What function $f$ satisfies the original puzzle, and is also $C^\infty$?
  

 A: I like Jack's description, draw a fixed sine curve and find tangent lines through the origin. In this case, I am finding a tangent point with $2 \pi < x < \frac{5 \pi}{2}.$ Under the circumstances, the slope $K$ comes out positive, with $K \approx 0.128374554, $ solution of $$K \left( 2 \pi + \arccos K \right) = \sqrt {1 - K^2}$$
The $x$ value for the tangent is about $7.725251838,$ just below $\frac{5 \pi}{2} \approx 7.853981635$$

This time, we get each value assumed by the function five times, the function being $\sin x - K x.$

Alright, I widened out to include $\pm 14,$ and clicked so it shows the roots and critical points. It says there are critical points at $x \approx \pm 14.008$

A: Starting from the following idea:
$$g(x)=\sin x + \frac{2}{3\pi}x$$
g(x) plot
we can adjust the constant for x in such way that
$$f(x)=\sin x + Kx$$
fullfills the given condition. 
The value of K can be easily found imposing that:
$$\begin{cases}(\sin x)'=\cos x=-K\\
Kx=-\sin x\end{cases}$$
$$\implies tanx=x \implies x\approx4.49340945790906 \quad K=-\cos x \approx 0.21723362821123...$$
f(x) plot

