22
\$\begingroup\$

I define the n-th ternary as a ternary that returns n and has the form:

1 ? 2 ? 3 ? n - 1 ? n : 0 : 0 : 0  # n - 1 zeroes

Write a function or complete program that given an input n will output or return the n-th ternary. Code-Golf.

Testcases

0 #=> undefined behaviour
1 #=> 1
2 #=> 1 ? 2 : 0
3 #=> 1 ? 2 ? 3 : 0 : 0
10 #=> 1 ? 2 ? 3 ? 4 ? 5 ? 6 ? 7 ? 8 ? 9 ? 10 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0

The 1000-th ternary I think there is some kind of zen harmony to it.

\$\endgroup\$
7
  • 1
    \$\begingroup\$ Is trailing whitespace allowed? \$\endgroup\$ Commented Jul 9, 2015 at 19:15
  • \$\begingroup\$ @rink no, no training space \$\endgroup\$
    – Caridorc
    Commented Jul 9, 2015 at 19:39
  • 1
    \$\begingroup\$ Since "ternary" means 3, shouldn't you name it the "n-ary", which is what it's referred to in mathematics? \$\endgroup\$
    – mbomb007
    Commented Jul 9, 2015 at 21:10
  • 4
    \$\begingroup\$ The way to "edit" a comment is: delete it, and add a new one. \$\endgroup\$ Commented Jul 9, 2015 at 21:15
  • 2
    \$\begingroup\$ @RetoKoradi You can edit a comment if it's within five minutes of posting it. \$\endgroup\$
    – mbomb007
    Commented Jul 9, 2015 at 21:48

33 Answers 33

10
\$\begingroup\$

CJam, 18 18 bytes

ri,:)":?0"*2/ze_S*

Try it online.

Explanation

ri,:)          e# Generate the list 1..n.
":?0"*         e# Insert ":?0" between every two numbers.
2/             e# Split into pairs, e.g. 1:, ?0, 2:, ?0, ..., ?0, n.
z              e# First items in every pair before second items in every pair.
e_             e# Concatenate the two parts.
S*             e# Insert spaces.
\$\endgroup\$
1
  • 14
    \$\begingroup\$ I love the :). \$\endgroup\$
    – Alex A.
    Commented Jul 9, 2015 at 20:36
9
\$\begingroup\$

Pyth - 19 18 17 bytes

The spaces are killing me, thinking of a better way to handle them.

+j" ? "SQ*tQ" : 0

It just joins the numbers by a " ? " and then concatenates the second part on.

+              String concatenation
 j" ? "        Join by the string
  SQ           1-indexed inclusive range to input
 *             String repetition
  tQ           Input - 1
  " : 0        String implicitly closed by end of program

Try it online here.

\$\endgroup\$
9
\$\begingroup\$

Ruby, 31 bytes

f=->n{[*1..n]*' ? '+' : 0'*~-n}

Test:

> f[1]
=> "1"
> f[7]
=> "1 ? 2 ? 3 ? 4 ? 5 ? 6 ? 7 : 0 : 0 : 0 : 0 : 0 : 0"
\$\endgroup\$
6
  • 2
    \$\begingroup\$ So array * string == array.join string ... interesting \$\endgroup\$
    – Caridorc
    Commented Jul 9, 2015 at 20:08
  • \$\begingroup\$ This is really cool. Out of curiosity, what happens when you do f[0]? \$\endgroup\$
    – Alex A.
    Commented Jul 9, 2015 at 20:08
  • 1
    \$\begingroup\$ @AlexA. irb(main):007:0> f[0] ArgumentError: negative argument from (irb):6:in * from (irb):6:in block in irb_binding from (irb):7:in [] from (irb):7 from /usr/bin/irb:11:in <main> \$\endgroup\$
    – Caridorc
    Commented Jul 9, 2015 at 20:09
  • 4
    \$\begingroup\$ @Caridorc Both loud and unintelligible. Nice. \$\endgroup\$
    – Alex A.
    Commented Jul 9, 2015 at 20:11
  • 2
    \$\begingroup\$ @daniero Warning: anti-string may be generated \$\endgroup\$
    – Caridorc
    Commented Jul 9, 2015 at 20:14
8
\$\begingroup\$

CJam, 19 bytes

Just a start...

ri_,:)'?*\(":0"*+S*

How it works

ri_                       e# Read the number as integer and make a copy of it on stack
   ,:)                    e# Convert the copy to array [1 .. n]
      '?*                 e# Join the numbers with a '?'. So we have [1 '? 2 '? ... '? n]
         \(               e# Swap the stack to get original integer on top. Decrement it by 1
           ":0"*          e# Get n-1 repeated ":0" string
                +S*       e# Join the two strings and fill it with spaces. 

Try it online here

\$\endgroup\$
5
  • \$\begingroup\$ Heck, 1 minute too late. \$\endgroup\$
    – Dennis
    Commented Jul 9, 2015 at 19:04
  • 3
    \$\begingroup\$ wow you are pretty fast at coding in Cjam :O \$\endgroup\$
    – Caridorc
    Commented Jul 9, 2015 at 19:05
  • \$\begingroup\$ @Dennis I think your initial solution, which was identical to Optimizers's first solution, was actually first. At least I'm pretty sure that I saw it pop up first. But the post time of yours was updated when you edited it within the grace period. \$\endgroup\$ Commented Jul 9, 2015 at 19:40
  • 1
    \$\begingroup\$ @RetoKoradi his post id is 52870. Mine is 52869 :) \$\endgroup\$
    – Optimizer
    Commented Jul 9, 2015 at 19:42
  • \$\begingroup\$ Ah, ok, I don't have permission to see deleted posts on this site. Both must have popped up at the same time for me then, and I only noticed the top one. I do seem to remember that SE might do some funky stuff to post times when editing within the grace period. Otherwise you could post an empty place holder, and fill in the content within the grace period, to make it look like you had the first answer, and it actually contained useful content from the start because edits within the grace period are not tracked. \$\endgroup\$ Commented Jul 9, 2015 at 20:46
6
\$\begingroup\$

Brainfuck, 305

(Without input number from STDIN, see edit at the bottom)

-[->+>+<<]>>>++++[>++++++++<-]>[<+>-]+++++++[>+++++++++<-]>[<+>-]++++++[>++++++++
<-]>[<+>-]++<<<<>>>+.-<<<[>.>.<.>>>>>++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<
]>>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<
+>+>[-]]<[<[->-<]++++++[->++++++++<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]<+<<<
<-]>>-----<<<[->>.>.<.>>.<<<<]

I used this lovely algorithm to print a number, which takes up 155 bytes of the whole program.

It works for inputs up to 32768 (16-bit limitation of the algorithm). It doesn't produce trailing spaces and works for input 1 as well:

input    output
0        [infinite loop (til underflow)]
1        "1"
2        "1 ? 2 : 0"
4        "1 ? 2 ? 3 ? 4 : 0 : 0 : 0"
etc.

Quick walk-through:

Setup (97 bytes)

-                                 Decrease input (position 0)
[->+>+<<]  >>>                    Copy input twice to the right and 
                                      shift 3 positions to the right
++++[>++++++++<-]>   [<+>-]       Precalculate number 32 (=" ") at position 3
+++++++[>+++++++++<-]>  [<+>-]    Precalculate number 63 (="?") at position 4
++++++[>++++++++<-]>    [<+>-]    Precalculate number 48 (="0") at position 5
++<<<<                            Precalculate number 2 for later use. This number
                                      will be printed in each iteration. (position 6)

First part (181 bytes)

>>>+.-<<<                Go to the char "0" we saved, increase it, print it,
                             decrease it and go back (this prints "1" everytime)
[                        While our second copy of the number isn't zero
    >.>.<.>>>                Move to " ", print, move to "?", print,
                                 move to " " again, print, move to our
                                 number at the end which is initially 2

    [>>+>+<<<-]>>>[<<<+>>>-]<<+>[<->[>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]
        ++++++++[<++++++>-]>[<<+>>-]>[<<+>>-]<<]>]<[->>++++++++[<++++++>-]]<
        [.[-]<]<             Algorithm to print the number at current position

    +<<<<                    Increase our number at the end and return to the beginning
-]                       Decrease the loop variable

Second part (27 bytes)

>>-----<<<        Move to our "?" char and decrease it by 5 to get ":"
[-                While our first copy of the number isn't zero decrease it
   >>.>.<.>>.<<<<     Print " ", print ":", print " ", print "0"
]

If it would be allowed to map the 8 Brainfuck commands to 3 bits, then this program would take up 114 bytes and another 3 bits

Unary, ~4.08*10^275 bytes

It would be too long for here, but it's just 408452257862560239329948606295286361112603208650130608525040044700379331457759667646985586658469601803889628246410788572492437928714867190270708935427798983714797786123292750743771225096145575210320040188155473030775033228313350778616384531426430459309802833775612506568528463 zeros and works the same as the Brainfuck program.

EDIT: I messed up, this program doesn't take user input really, it just uses the current pointer value as input. For being able to parse a number a whole lot more would be required and I can't be bothered to do that.

So it works with a value directly entered into the program (by appending n times "+" before the program) but not with STDIN

\$\endgroup\$
5
\$\begingroup\$

JavaScript (ES6), 42 39 bytes

f=m=>(g=k=>k-m?k+` ? ${g(k+1)} : 0`:m)(1)

The outer function f takes the input value and then calls the inner function g recursively to build the string from the middle out, using the input value as a maximum to test for the base case.

Ungolfed:

function f(max) {
    function g(count) {
        if(count==max) {
            // base case: return max for the center
            return max;
        } else {
            // recursive case: build outer shell around center
            return count + " ? " + g(count+1) + " : 0";
        }
    }

    return g(1);
}
\$\endgroup\$
0
4
\$\begingroup\$

Python 56 55

t=lambda n:' ? '.join(map(str,range(1,n+1)))+' : 0'*~-n
\$\endgroup\$
0
4
\$\begingroup\$

C# - 76

Func<int,string>F=k=>{var r="";for(;k>1;)r=" ? "+k--+r+" : 0";return"1"+r;};
\$\endgroup\$
3
\$\begingroup\$

Haskell, 53 bytes

g n='1':foldr(\x s->" ? "++show x++s++" : 0")""[2..n]

How it works: build the string from inside out by starting with an empty string and looping from n down to 2 with prepending the current number and a ? and appending a : 0. Finally put a 1 in front of all.

A different approach (thanks to @Mauris now 9 bytes shorter):

Haskell, 60 51 bytes

 f n='1':((=<<[2..n])=<<[(" ? "++).show,\x->" : 0"])

How it works: a literal 1 followed by ? <x> for each <x> in [2..n] followed by a constant : 0 for each <x> in [2..n].

\$\endgroup\$
2
  • \$\begingroup\$ An approach based on your 60 bytes that gets down to 51: g n='1':((=<<[2..n])=<<[(" ? "++).show,\x->" : 0"]) \$\endgroup\$
    – lynn
    Commented Jul 9, 2015 at 20:41
  • \$\begingroup\$ Actually, you can get it down to 51 more directly by just replacing (\_->" : 0")=<<[2..n] with [2..n]>>" : 0" \$\endgroup\$
    – lynn
    Commented Jul 9, 2015 at 20:45
3
\$\begingroup\$

Pyth, 17 bytes

jd.iSQs*RtQ,\?":0

Demonstration.

\$\endgroup\$
3
\$\begingroup\$

Julia, 44 31 bytes

n->join(1:n," ? ")*" : 0"^(n-1)

This creates an unnamed function that accepts an integer as input and returns a string. To call it, give it a name, e.g. f=n->....

First we join together the integers 1 to n, separating each with ? and spaces into a single string. Then we append to this the string " : 0" repeated n-1 times.

Examples:

julia> f(1)
"1"

julia> f(3)
"1 ? 2 ? 3 : 0 : 0"

julia> f(0)
can't repeat a string -1 times
\$\endgroup\$
3
\$\begingroup\$

Perl, 36 bytes

say join(" ? ",1..$_)." : 0"x($_-1)

35 characters +1 for -n.

Run with:

echo 10 | perl -nE'say join(" ? ",1..$_)." : 0"x($_-1)'
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Can shave one byte using -p instead of -n and say: Try it online! \$\endgroup\$
    – Xcali
    Commented Feb 1, 2021 at 3:21
2
\$\begingroup\$

JavaScript ES7, 62 bytes

n=>[for(i of Array(n).keys())i+1].join` ? `+' : 0'.repeat(n-1)

I don't know if I can golf this more. But it's a pretty straightforward solution

Firefox only:

var f=n=>[for(i of Array(n).keys())i+1].join` ? `+' : 0'.repeat(n-1)

alert(f(+prompt('Input: ')));

ES5 equivalent:

// Most browsers now support .repeat
String.prototype.repeat = String.prototype.repeat || function(n){var _n = '', i = 0; for (;i < n; i += 1){_n+=this};return _n}
                                                             //Function                         
function f(n){a=[];for(i of Array(n).keys()){a.push(i+1)};return a.join(' ? ')+' : 0'.repeat(n-1)}

alert(f(+prompt('Input: ')))

\$\endgroup\$
2
\$\begingroup\$

CoffeeScript, 52 bytes

f=(n)->s='';s=' ? '+n--+s+' : 0'while n;s.slice 3,-4

Explanation

f=(n)->
 s = ''                                # initialize string
 s = ' ? ' + n-- + s + ' : 0' while n  # prepend and append in decrementing loop
 s.slice 3,-4                          # chop off leading ?, trailing 0 and whitespace
\$\endgroup\$
2
\$\begingroup\$

SWI-Prolog, 90 bytes

a(X):-Y is X-1,\+ (between(1,Y,L),\+writef('%w ? ',[L])),write(X),writef('%r',[' : 0',Y]).

Definitely not going to win, but the \+ (between(1,TopBound,N),\+do_something(N)) construction is pretty interesting to repeat something on a sequence of integers.

\$\endgroup\$
2
\$\begingroup\$

Swift 145 (135 w/o whitespace)

func t(n:Int) -> String {
    let a = (1..<n).reverse().reduce("") {" ? \($1)\($0) : 0"}
    return a.substringFromIndex(advance(a.startIndex, 3))
}

Can you believe the part to substring is actually longer than the part to produce the expression.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Gotta love Swift <3 I really wish though that they make it so you can access Strings with Integer indices like str[1] or str[0...5]. Of course you can make a small extension, but I wish the standard library enabled this \$\endgroup\$
    – Kametrixom
    Commented Jul 9, 2015 at 22:21
  • \$\begingroup\$ @Kametrixom apple once allowed this in the first beta, but the various unicode encodings prevent you from doing so. That's mainly because some symbols are two bytes or more long and some are not. So it is not guaranteed to fetch the same character in different encodings with the same index. My description may not be accurate, but that's basically why apple introduced the ugly mouthful string index syntax. \$\endgroup\$
    – Ben Lu
    Commented Jul 9, 2015 at 22:53
  • \$\begingroup\$ Recently I've really gotten used to use Swift for Code Golfing, have a look at my Swift answer \$\endgroup\$
    – Kametrixom
    Commented Jul 10, 2015 at 3:34
2
\$\begingroup\$

Java, 71

I couldn't help myself after commenting on RCB's answer. So here's another Java (71 like wow when is Java not the longest!)

String t(int n){String s=""+n;for(;--n>0;)s=n+" ? "+s+" : 0";return s;}
\$\endgroup\$
2
\$\begingroup\$

Java, 125 88 bytes

Original

String f(int n){if(n==1)return"1";String s="",e="";for(int i=1;i<n;i++){s+=i+" ? ";e+=i==n-1?": 0":": 0 ";}return s+n+" "+e;}

With nicer formatting and variable names:

String nAry(int n) {
    if (n == 1) {
        return "1";
    }
    String start = "", end = "";
    for (int i = 1; i < n; i++) {
        start += i + " ? ";
        end += (i == n - 1) ? ": 0" : ": 0 ";
    }
    return start + n + " " + end;
}

Improved - Thanks to Jack Ammo's comments below:

String f(int n){String s="",e=s;for(int i=1;i<n;){s+=i+++" ? ";e+=" : 0";}return s+n+e;}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ you don't need that triadic operator for appending to e just to account for the space, just assume you always need the space on front of the colon e+=" : 0";. You can then save 1 byte by post-incrementing i when it's used instead of on the forloop line for(int i=1;i<n;){s+=i+++" ? ";Your return statement will no longer need the space added after n return s+n+e;. You can also save 1 byte by using e=s. Also, the if statement at the beginning is unnecessary since the for loop logic will guarantee that result anyway. \$\endgroup\$
    – Jack Ammo
    Commented Jul 14, 2015 at 1:18
  • \$\begingroup\$ @JackAmmo Excellent tips, thanks! The if statement was necessary to avoid trailing whitespace, but no longer after your improvements to the for loop logic. I've incorporated the changes and upvoted your answer. \$\endgroup\$
    – RCB
    Commented Jul 14, 2015 at 10:45
1
\$\begingroup\$

JavaScript (ES6), 59 bytes

Same approach as my CoffeeScript answer, using template strings help. String.prototype.repeat costs too many characters.

f=n=>{for(s=``;n;)s=` ? ${n--+s} : 0`;return s.slice(3,-4)}

Demo

Firefox only for now, as it is ES6.

f=n=>{for(s=``;n;)s=` ? ${n--+s} : 0`;return s.slice(3,-4)}

// DEMO
console.log = x => document.body.innerHTML += '<p>' + x

console.log(f(1));
console.log(f(3));
console.log(f(10));

\$\endgroup\$
1
\$\begingroup\$

K, 36 bytes

{(3_,/(" ? ",)'$!x),(4*-1+x)#" : 0"}
\$\endgroup\$
1
\$\begingroup\$

Python 2, 63 60 58 56

Try it here

Easy solution: (63)

n=input()
for i in range(n-1):print-~i,'?',
print`n`+' : 0'*~-n

Edit: I really wanted to try a recursive function. Here it is: (56)

f=lambda n,c=1:`c`+(' ? '+f(n,c+1)if c<n else~-n*' : 0')

Edit: Anyone know why this isn't working? I tried a list with an index of c<n, but that didn't work because of a stack overflow error. Same with this:

f=lambda n,c=1:`c`+((c<n)*(' ? '+f(n,c+1))or~-n*' : 0')
\$\endgroup\$
2
  • \$\begingroup\$ The index doesn't work because it has to create a list containing the evaluated function (which obviously would run forever). The same thing happens with your multiplication, it still needs to evaluate the function even though it is doing 0* it. \$\endgroup\$ Commented Jul 9, 2015 at 22:08
  • \$\begingroup\$ @FryAmTheEggman Alright, thanks. I've never had a situation like this occur before. \$\endgroup\$
    – mbomb007
    Commented Jul 10, 2015 at 1:22
1
\$\begingroup\$

rs, 77 bytes

(\d+)/(_)^^(\1)
+^_(_+)/\1 _\1
_(_+)$/_\1( : 0)^^((^^\1))
(__+)/? (^^\1)
^./1

Live demo and test cases.

Explanation:

(\d+)/(_)^^(\1)

Expand the number into a series of N underscores.

+^_(_+)/\1 _\1

Repeatedly create a range of underscores, separated by spaces. e.g. This would turn ___ into _ __ ___.

_(_+)$/_\1( : 0)^^((^^\1))

Append to the last set of underscores (of length N) N-1 instances of : 0.

(__+)/? (^^\1)

Replace each group of underscores by it's length, preceded by ?, EXCEPT for the first one.

^./1

Replace the first one with the number 1.

Because of the format, this also handles 0 well: it just prints the empty string.

\$\endgroup\$
1
\$\begingroup\$

Swift, 79 75 bytes

let f={{$0+$1}((1..<$0).reduce(("1","")){($0.0+" ? \($1+1)",$0.1+" : 0")})}

f is implicitly declared as a function with one Int parameter which returns a String

Works with n >= 1 and crashes at runtime when n == 0. There are no trailing whitespaces

Edit: Managed to remove 2*2 characters, because string interpolation isn't always the shortest

Note to edit: This code takes forever (it doesn't stop) to compile, but it definitely would if the compiler would be able to handle it. Take a look at the version before this edit to get one that compiles

\$\endgroup\$
1
\$\begingroup\$

><>, 32 + 3 = 35 bytes

:l(?vln" ? "ooo0$
"ooo>nl?!;" : 

Note that there is a trailing space on the second line. The +3 is for the -v flag, e.g. run like

$ py -3 fish.py ternary.py -v 2
1 ? 2 : 0

Taking input as a code point like

i:l(?vln" ? "ooo0$!
 "ooo>nl?!;" :

is 34 bytes, but I prefer the above version since it's easier to test and it won't win anyway.

Explanation

There's quite a bit of pseudo-recursion and abuse going on, so let's take a look.

The first line prints the "1 ? 2 ? ... n-1 ? " part. The stack starts off with just the input n, thanks to the -v flag, and we do the following:

:l(?v           If (length of stack + 1 > n), go to the second line
ln              Print the length of the stack
" ? "ooo        Print the reverse of " ? " (but hey, palindromes)
0$              Push 0 and swap, keeping n on top and increasing the 
                length of the stack by 1

><> is toroidal, so the above executes in a loop until the stack consists of n at the top with n-1 zeroes below, at which point it moves to the second line.

The first time the second line is executed, the n instruction is run, printing the n at the top of the stack. This leaves just the n-1 zeroes, and we do the following, also in a loop:

l?!;            If the stack is empty, terminate
" : "ooo        Print the reverse of " : " (but hey, palin...)
n               Print one of the 0s, decreasing the stack's length by 1
                This reuses the same n instruction from before
\$\endgroup\$
3
  • \$\begingroup\$ " ? "ooo Print the reverse of " ? " (but hey, palindromes) is printing the reverse shorter than printing the actual string? \$\endgroup\$
    – Caridorc
    Commented Jul 10, 2015 at 19:52
  • \$\begingroup\$ @Caridorc Yes, because ><> can only print char-by-char by popping off a stack :) \$\endgroup\$
    – Sp3000
    Commented Jul 10, 2015 at 19:53
  • \$\begingroup\$ sp3000 nice to know. \$\endgroup\$
    – Caridorc
    Commented Jul 10, 2015 at 19:54
1
\$\begingroup\$

Scala, 78 71 52 50 bytes

def f(n:Int)=(1 to n).mkString(" ? ")+" : 0"*(n-1)
\$\endgroup\$
1
\$\begingroup\$

Objective-C, 346 bytes

-(void)printTernaryOfInt:(int)ternary{NSMutableString *outString=@"".mutableCopy; for (int i=1;i<=ternary;i++) {[outString appendString:[NSString stringWithFormat:@" ? %i",i]];}[outString deleteCharactersInRange:NSMakeRange(0, 2)];for (int i=1;i<ternary;i++) {[outString appendString:[NSString stringWithFormat:@" : 0"]];}NSLog(@"%@",outString);}

Putting in 0 for the int or anything negative raises an NSRangeException due to outString containing nil. This should run on iOS 2.0 and later and many of the latest versions of Mac OS X.

A breakdown of the code:

-(void)printTernaryOfInt:(int)ternary{ ... }

Standard function declaration in Objective-C.

NSMutableString *outString=@"".mutableCopy;

Makes a string for output to go to, outString, and makes it mutable. (In other words, it can be read and written to.

for (int i=1;i<=ternary;i++) {[outString appendString:[NSString stringWithFormat:@" ? %i",i]];}

Adds the first part of the string to output.

[outString deleteCharactersInRange:NSMakeRange(0, 2)];

Cleans up the beginning of the string to make sure ? 1 is replaced with 1. Note: if 0 was given, this is where the NSRangeException would occur, due to there not being an index 1.

for (int i=1;i<ternary;i++) {[outString appendString:[NSString stringWithFormat:@" : 0"]];}

Adds the second part of the string to the string.

NSLog(@"%@",outString);}

Spits the string back out using NSLog and closes off the function.

Output:

Inputting 0 gives this crash log:

    2015-07-11 05:15:28.036 Example App[41665:2134488] *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString deleteCharactersInRange:]: Range or index out of bounds'
*** First throw call stack:
(
    0   CoreFoundation                      0x009b5746 __exceptionPreprocess + 182
    1   libobjc.A.dylib                     0x0063ea97 objc_exception_throw + 44
    2   CoreFoundation                      0x009b566d +[NSException raise:format:] + 141
    3   CoreFoundation                      0x00981813 mutateError + 259
    4   CoreFoundation                      0x009818c1 -[__NSCFString deleteCharactersInRange:] + 65
    5   Example App                         0x000e3785 -[ViewController printTernaryOfInt:] + 277
    6   Example App                         0x000e3645 -[ViewController placeOrder:] + 133
    7   libobjc.A.dylib                     0x006547cd -[NSObject performSelector:withObject:withObject:] + 84
    8   UIKit                               0x00d75a40 -[UIApplication sendAction:to:from:forEvent:] + 99
    9   UIKit                               0x00d759d2 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 64
    10  UIKit                               0x00eb613a -[UIControl sendAction:to:forEvent:] + 69
    11  UIKit                               0x00eb6557 -[UIControl _sendActionsForEvents:withEvent:] + 598
    12  UIKit                               0x00eb57c1 -[UIControl touchesEnded:withEvent:] + 660
    13  UIKit                               0x00dcdcaa -[UIWindow _sendTouchesForEvent:] + 874
    14  UIKit                               0x00dce786 -[UIWindow sendEvent:] + 792
    15  UIKit                               0x00d8c681 -[UIApplication sendEvent:] + 242
    16  UIKit                               0x00d9cab8 _UIApplicationHandleEventFromQueueEvent + 21484
    17  UIKit                               0x00d702e7 _UIApplicationHandleEventQueue + 2300
    18  CoreFoundation                      0x008d706f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
    19  CoreFoundation                      0x008ccb7d __CFRunLoopDoSources0 + 253
    20  CoreFoundation                      0x008cc0d8 __CFRunLoopRun + 952
    21  CoreFoundation                      0x008cba5b CFRunLoopRunSpecific + 443
    22  CoreFoundation                      0x008cb88b CFRunLoopRunInMode + 123
    23  GraphicsServices                    0x029e42c9 GSEventRunModal + 192
    24  GraphicsServices                    0x029e4106 GSEventRun + 104
    25  UIKit                               0x00d740b6 UIApplicationMain + 1526
    26  Example App                         0x000e3cfa main + 138
    27  libdyld.dylib                       0x02d76ac9 start + 1
    28  ???                                 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

1 gives this:

2015-07-11 05:06:02.360 Example App[41665:2134488]  1

2 gives this:

2015-07-11 05:06:07.613 Example App[41665:2134488]  1 ? 2 : 0

7 gives this:

2015-07-11 05:06:12.147 Example App[41665:2134488]  1 ? 2 ? 3 ? 4 ? 5 ? 6 ? 7 : 0 : 0 : 0 : 0 : 0 : 0

200 gives this:

2015-07-11 05:06:35.552 Example App[41665:2134488]  1 ? 2 ? 3 ? 4 ? 5 ? 6 ? 7 ? 8 ? 9 ? 10 ? 11 ? 12 ? 13 ? 14 ? 15 ? 16 ? 17 ? 18 ? 19 ? 20 ? 21 ? 22 ? 23 ? 24 ? 25 ? 26 ? 27 ? 28 ? 29 ? 30 ? 31 ? 32 ? 33 ? 34 ? 35 ? 36 ? 37 ? 38 ? 39 ? 40 ? 41 ? 42 ? 43 ? 44 ? 45 ? 46 ? 47 ? 48 ? 49 ? 50 ? 51 ? 52 ? 53 ? 54 ? 55 ? 56 ? 57 ? 58 ? 59 ? 60 ? 61 ? 62 ? 63 ? 64 ? 65 ? 66 ? 67 ? 68 ? 69 ? 70 ? 71 ? 72 ? 73 ? 74 ? 75 ? 76 ? 77 ? 78 ? 79 ? 80 ? 81 ? 82 ? 83 ? 84 ? 85 ? 86 ? 87 ? 88 ? 89 ? 90 ? 91 ? 92 ? 93 ? 94 ? 95 ? 96 ? 97 ? 98 ? 99 ? 100 ? 101 ? 102 ? 103 ? 104 ? 105 ? 106 ? 107 ? 108 ? 109 ? 110 ? 111 ? 112 ? 113 ? 114 ? 115 ? 116 ? 117 ? 118 ? 119 ? 120 ? 121 ? 122 ? 123 ? 124 ? 125 ? 126 ? 127 ? 128 ? 129 ? 130 ? 131 ? 132 ? 133 ? 134 ? 135 ? 136 ? 137 ? 138 ? 139 ? 140 ? 141 ? 142 ? 143 ? 144 ? 145 ? 146 ? 147 ? 148 ? 149 ? 150 ? 151 ? 152 ? 153 ? 154 ? 155 ? 156 ? 157 ? 158 ? 159 ? 160 ? 161 ? 162 ? 163 ? 164 ? 165 ? 166 ? 167 ? 168 ? 169 ? 170 ? 171 ? 172 ? 173 ? 174 ? 175 ? 176 ? 177 ? 178 ? 179 ? 180 ? 181 ? 182 ? 183 ? 184 ? 185 ? 186 ? 187 ? 188 ? 189 ? 190 ? 191 ? 192 ? 193 ? 194 ? 195 ? 196 ? 197 ? 198 ? 199 ? 200 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0
\$\endgroup\$
1
\$\begingroup\$

C, 84 78 bytes

C, even though it is not the shortest, as a function:

i;f(n){while(++i<n)printf("%i ? ",i);printf("%i",n);while(--i)printf(" : 0");}

In the name of golfing, the int type specifier is left off of i, f, and n because it is the default. i can be uninitialized because it is a global variable and defaults to zero. f does not return a value, but that only causes a warning. printf is not #include'd. To run, here is a full program version:

#include <stdio.h>

i;f(n){while(++i<n)printf("%i ? ",i);printf("%i",n);while(--i)printf(" : 0");}

int main(int argc, char *argv[]){
    if(argc != 2){
        return 1;
    }
    f(atoi(argv[1]));
    puts("");
}
\$\endgroup\$
1
  • \$\begingroup\$ You may be able to shorten this by using for(printf(...);--i;). \$\endgroup\$
    – lirtosiast
    Commented Jul 12, 2015 at 4:56
1
\$\begingroup\$

C, 63 bytes

Reusable function, takes n as an argument.

i;f(n){for(i=1;i<2*n;i++)printf(i-1?n/i?" ? %d":" : 0":"1",i);}

Ungolfed and commented (pretty straightforward):

int f(int n) {
    int i;

    // 1 ... n, n+1 ... 2n-1
    for(i = 1; i < 2*n; i++) {
        // If i == 1, prints "1"
        // If i <= n, prints " ? %d", i (i = 2 ... n)
        // Else, prints " : 0" (i = n+1 ... 2n-1)
        printf(
            i-1 ?
                n/i ?
                    " ? %d" :
                    " : 0" :
                "1",
        i);
    }
}
\$\endgroup\$
1
\$\begingroup\$

Common Lisp, 84

(format t "~{~A ? ~}~@*~{~[~;~:;0~^ ? ~]~}" (loop for i from 1 to (read) collect i))

First, (loop for i from 1 to (read) collect i) generates a list of integers from 1 to whatever is put in, which is used as the only argument to the function. But the real magic of it is in the control string that looks like line noise. "~{~A ? ~}" iterates over the entire list stored within the first argument, outputting each number with the ? for the first half. ~@* resets the argument list to the first argument. ~{~[~;~:;0~^ ? ~]~} reiterates over the list, outputting 0 ? for each argument consumed, but outputting nothing if the argument is 0 or 1.

\$\endgroup\$
1
\$\begingroup\$

PowerShell Core, 52 38 bytes

param($a)(1..$a-join' ? ')+' : 0'*--$a

Try it online!

Save 14 bytes thanks to mazzy!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Try it online! ? \$\endgroup\$
    – mazzy
    Commented Jan 29, 2021 at 10:25
  • 1
    \$\begingroup\$ or Captain Hook! :) \$\endgroup\$
    – mazzy
    Commented Jan 29, 2021 at 10:36
  • \$\begingroup\$ it was a hard choice :) Thanks ! ⏰ \$\endgroup\$
    – Julian
    Commented Feb 1, 2021 at 3:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.