JavaScript (ES6), 92 bytes
f=(n,i=3)=>eval([...s=i.toString(3)].map(d=>"-+"[d]||"").join`1`+".0")-n?f(n,i+1):s.length-1
n = <input type="number" oninput="R.textContent=f(this.value)" /><pre id="R"></pre>
Explanation
Recursive function. This generates all possible permutations of 1
s separated by either +
, -
or nothing. It does this by incrementing a base-3 number, turning it into an array of digits, converting each digit 0
to -
, 1
to +
and 2
to an empty string, then joining them together with 1
s. The resulting string is eval
d as a JavaScript statement which returns the result of the equation.
Because the operators are joined with 1
s in between (like +1+1+1+
), there are length - 1
1
s. The first operator is ignored (because +1
= 1
, <nothing>1
= 1
and it's a number so there will never be a leading 0
for -
) and the final operator is also ignored (by appending .0
to the equation).
Higher Output Version, 96 bytes
The other version can't return outputs higher than ~10 because of the recursion call stack limit. This version uses a for loop instead of recursion, so it can return outputs up to ~33. The amount of time required increases exponentially though so I don't recommend testing it.
n=>eval('for(a=3;eval([...s=a.toString(3)].map(d=>"-+"[d]||"").join`1`+".0")-n;)a++;s.length-1')
Nice first challenge. I'd suggest including more test cases. Is "VALID OUTPUTS" a mistake, given that there's a single output? Also, is 0 a valid input, and if so, what should be output? – xnor – 2016-05-03T02:29:17.790
This is an interesting challenge. You may want to add an explanation for the outputs, change
VALID OUTPUTS
. It's your choice, but generally people like bold or italics instead of CAPITAL LETTERS (they make it look like shouting instead of emphasis). Bold is**bold text**
, and italics is*italics text*
. You could also use### Text
for bold-er text. Anyway, welcome to PPCG! – NoOneIsHere – 2016-05-03T02:34:35.870You should make a computer-readable table or list of test cases that people can run their code on. See this tip.
– xnor – 2016-05-03T02:59:08.0876
I'm voting to close this question because this question is of a duplicate of the current (active!!) golfing challenge over at https://codefights.com/challenges. Even if the OP is also the author of the original challenge on codefights (which I doubt), the question should be closed until the challenge on codefights isn't active any more.
– Jakube – 2016-05-03T10:18:58.9701
@Jakube the direct link could've been helpful, but I agree. I will vote to close.
– NoOneIsHere – 2016-05-03T14:27:03.213Is it gone yet? – CalculatorFeline – 2016-05-06T21:47:22.360