Zeichnen Sie den Bogen einer Kugel

35

Zeichnen Sie die parabolische Flugbahn eines geworfenen Balls.

Die Eingabe ist die anfängliche Aufwärtsgeschwindigkeit des Balls, eine positive ganze Zahl v. Jede Sekunde bewegt sich der Ball nach 1rechts und vvertikal und vnimmt 1dann aufgrund der Schwerkraft um bis ab. Die Aufwärtsgeschwindigkeit steigt schließlich von vauf 0und ab und -vfällt schließlich auf ihre ursprüngliche Höhe zurück.

Die Positionen des Balls zeichnen eine Parabel nach. In horizontaler Position xbefindet sich seine Höhe y=x*(2*v+1-x)/2, wobei sich (0,0)die Ausgangsposition des Balls unten links befindet.

Geben Sie eine ASCII-Grafik der Flugbahn des Balls mit Oden Koordinaten aus, die der Ball jemals einnimmt. Die Ausgabe sollte ein einziger mehrzeiliger Text sein, keine Animation des zeitlichen Verlaufs.

Die Ausgabe sollte keine führenden Zeilen und höchstens eine nachfolgende Zeile enthalten. Die unterste Zeile sollte bündig mit dem linken Bildschirmrand abschließen, dh keine zusätzlichen Leerzeichen enthalten. Nachgestellte Leerzeichen sind in Ordnung. Sie können davon ausgehen, dass die Breite der Ausgabeleitung in den Ausgangsanschluss passt.

v = 1

 OO 
O  O

v = 2

  OO  
 O  O 

O    O

v = 3

   OO   
  O  O  

 O    O 


O      O

v = 4

    OO    
   O  O   

  O    O  


 O      O 



O        O

v = 10

          OO          
         O  O         

        O    O        


       O      O       



      O        O      




     O          O     





    O            O    






   O              O   







  O                O  








 O                  O 









O                    O

Verwandte: Bouncing Ball Simulation


Bestenliste:

xnor
quelle
Können wir eine Liste von Zeilen ausgeben?
2.
@Riker Nope, String mit Zeilenumbrüchen.
xnor
locker verwandt: codegolf.stackexchange.com/q/110410
Titus
Muss ich nur V> 0 berücksichtigen?
nmjcman101
Ja, v wird positiv sein.
xnor

Antworten:

17

Kohle , 18 16 13 Bytes

-3 Bytes dank @Neil !

F⊕N«←OM⊕ι↓»‖C

Erläuterung

F⊕N«        »    For ι (implicitly from 0) to (1 + input as number)
       ←O          Print O, with print direction rotated 180 degrees
         M⊕ι↓     Move 1+ ι units down

                ‖C Reflect (in the default direction, right), leaving original intact

Probieren Sie es online! Link ist zum ausführlichen Code.

Nur ASCII
quelle
Ich mag dieses sehr, +1; Auch der OP-Ausgang verwendet den Großbuchstaben "O". (Nicht, dass es überhaupt darauf ankommt, lol)
Albert Renshaw
Wenn Sie verwenden ↘O, können Sie stattdessen eine Schleife von 0 bis einschließlich N ausführen, wodurch Sie sofort zwei Bytes sparen.
Neil
@ Neil Danke! Dies ist auch ein sehr alter Beitrag: P (und ich frage mich, ob ich neuere Funktionen verwenden sollte. Wahrscheinlich nicht?)
Nur ASCII
Genau genommen habe ich nur gespeichert haben Sie 1 Byte , so weit wie die anderen beiden Bytes wurden Sie ersetzt ⁺¹mit . Jetzt, da Sie das von ‖Cauf verschoben haben O, können Sie ein weiteres Byte speichern, indem Sie schreiben ↙OMι↓, sodass ich wieder auf ein Speichern von zwei Bytes zurückgreifen kann.
Neil
Sie haben auch vergessen, Ihren TIO-Link zu aktualisieren. Und technisch gesehen, glaube ich, dass wir jetzt neuere Funktionen zulassen, aber ich kann keine Gutschrift für diese Bytes anfordern.
Neil
6

C, 93 92

(Beachten Sie, dass jemand in den Kommentaren auf 87 steht.)

y,n;f(s){for(y=0;y<=s;){printf("%*c%*c",s-y+1,79,y*2+1,79);for(n=++y;s+1-n&&n--;)puts("");}}

Probieren Sie es online!


Lesbar:

y,n;f(s){
    for(y=0;y<=s;){
        printf("%*c%*c",s-y+1,79,y*2+1,79);
        for(n=++y;s+1-n&&n--;)puts("");
    }
}

Anmerkungen:

Ich kann beide for-Schleifen zu einer for-Schleife zusammenfassen, indem ich die Gesamtzahl der ausgegebenen Zeilen iteriere, die durch die folgende Formel gegeben ist: n*-~n/2+1

y,n,r;f(s){
    for(r=s,y=n=0;r<s*-~s/2+1;)
        y==n?printf("%*c%*c",s-y+1,79,y*2+1,79),y=0,++n:r++,y++,puts("");
}

Am Ende sind es jedoch noch mehr Bytes als nur zwei separate for-Schleifen

Albert Renshaw
quelle
Sie können ein Byte speichern, indem Sie sam Anfang inkrementieren , wie y,n;f(s){++s;for(y=0;y<s;){printf("%*c%*c",s-y,79,y*2+1,79);for(n=++y;s-n&&n--;)puts("");}}
folgt
@Steadybox wird nicht für mich kompiliert. Außerdem habe ich 90 Bytes bekommen, als ich das gezählt habe (nachdem ich Leerzeichen entfernt hatte)
Albert Renshaw
Alles, was ich getan habe, war, das ++s;am Anfang hinzuzufügen und dann y<=szu y<sund s-y+1zu s-yund s+1-nzu zu wechseln s-n, damit es kompiliert werden sollte (und 91 Byte groß sein sollte).
Steadybox
Anscheinend stimmt etwas nicht mit der Codierung des Codeblocks in meinem Kommentar. Das Kopieren und Einfügen des Codes aus dem Kommentar wird auch für mich nicht kompiliert.
Steadybox
1
87 Bytes
Ceilingcat
5

GNU sed, 41

  • Die Wertung beinhaltet +1 von -rFlaggen bis Sed.
s/$/OO/
:
s/(\s*) O( *)O$/&\n\1O \2 O/
t

Die Eingabe ist als Zeichenfolge von Leerzeichen unär - die Länge der Zeichenfolge ist die Eingabe.

Probieren Sie es online aus .

Digital Trauma
quelle
4

Python 2, 76 bytes

x=input()
for i in range(x):print' '*(x-i),'O'+' '*i*2+'O'+'\n'*(i-x+1and i)

Pretty simple. The i-x+1and i is to prevent a bunch of trailing newlines.

HyperNeutrino
quelle
Moving the newline to the beginning of the print, like '\n'*(i-1)saves 7 bytes while avoiding the trailing newlines.
Emigna
4

MATL, 19 17 bytes

Q:tqYsQ79Z?PtPv!c

Try it at MATL Online! Or verify all test cases.

Explanation

Q        % Implicitly input v. Add 1
:        % Push [1 2 ... v+1]
tq       % Duplicate and subtract 1: pushes [0 1 ... v]]
Ys       % Cumulative sum: gives [0 1 3 6 ...]
Q        % Add 1: gives [1 2 4 7 ...]
79       % Push 79 (ASCII for 'O')
Z?       % Create sparse matrix from column indices [1 2 3 4 ...],
         % row indices [1 2 4 7 ...], and data 79
P        % Flip vertically
tP       % Duplicate, flip vertically
v        % Concatenate the two matrices vertically
!        % Transpose
c        % Convert to char. Implicitly display. Char 0 is shown as space
Luis Mendo
quelle
4

05AB1E, 18 14 bytes

Saved 4 bytes thanks to Adnan

ƒ¶N×'ONúRÂJ}.c

Try it online!

Explanation

ƒ                   # for N in [0 ... input]
 ¶N×                # push N newlines
    'O              # push "O"
      Nú            # pad with N spaces in front
        RÂ          # reverese and create a reversed copy
          J         # join everything to a string
           }        # end loop
            .c      # pad lines until centered 
Emigna
quelle
For 14 bytes: ƒ¶N×'ONúRÂJ}.c :)
Adnan
@Adnan Thanks! I tried .c with a different version, but it didn't work well then. Forgot about trying it with this one and complete forgot that ú exists :)
Emigna
Definitely better than the zip method I chose, interesting approach vertically.
Magic Octopus Urn
4

JavaScript (ES6), 98 92 89 84 78 bytes

(-20 bytes thanks to Arnauld!)

f=(v,i=0)=>i>v?"":" "[r="repeat"](v-i)+0+" "[r](2*i)+0+`
`[r](i++<v&&i)+f(v,i)

A recursive solution. This is also my first ever answer in JavaScript, so please be gentle! I am still learning all this neat language has to offer, so golfing tips are very much appreciated. :)

Test Snippet

You may need to scroll to see the entire output.

f=(v,i=0)=>i>v?"":" "[r="repeat"](v-i)+0+" "[r](2*i)+0+`
`[r](i++<v&&i)+f(v,i)
<input id=i min=1 type=number><button onclick=alert(f(document.getElementById("i").value))>Submit</button>

R. Kap
quelle
Also, including variables inside backtick strings with ${} only saves bytes when the variable part is surrounded by static parts. As such, these strings should always start and end with static parts.
Luke
@Arnauld Thanks for all the tips! I really appreciate it! :)
R. Kap
@Luke Thanks for the advice. That will come in handy. :)
R. Kap
You can safely use 0 instead of "0". They'll be coerced to strings. And on second thought: i++<v&&i is actually one byte shorter than (i<v)*++i.
Arnauld
@Arnauld Thank you once again! :)
R. Kap
3

RProgN 2, 37 bytes

x=0xR{y@xy-` *`o` y2**`o...2y{[` };};

Getting in with my kind-of-golfy language before the proper golfy langauges jump in.

Explained

x=              # Set 'x' to the input
0xR{            # For everything between the input and 0
    y@          # Set the iteration value to y, for this function only.
    xy-` *      # Subtract y from x, repeat the string " " that many times.
    `o          # Push an "o" to the stack.
    ` y2**      # Push 2*y " "'s to the stack
    `o          # Push another "o" to the stack
    ...         # Concatenate the parts of this string together, giving us the two balls.
    2y{[` };    # For all numbers between 2 and y, add a newline.
};              #

Try it online!

ATaco
quelle
3

Retina, 29 19 bytes

 ?
$.`$*¶$&$'O$`$`O

Try it online!

Takes input in unary as a run of spaces. Port of my JavaScript answer. Edit: Saved 10 bytes thanks to @MartinEnder♦.

Neil
quelle
I´m only waiting for someone to come up with a Retina spin off called Retsina.
Titus
3

Bash, 76 bytes

for((n=$1+1;--n;));{
yes ''|head -$n
r=$r${n}AO
t=›${n}BO$t
}
echo O${r}O$t

Only works in a terminal since it uses ANSI escape sequences. represents the CSI byte (0x9b).

Test run

$ # The terminal's encoding must be set to ISO-8859-1.
$
$ xxd -g 1 arc.sh
0000000: 66 6f 72 28 28 6e 3d 24 31 2b 31 3b 2d 2d 6e 3b  for((n=$1+1;--n;
0000010: 29 29 3b 7b 0a 79 65 73 20 27 27 7c 68 65 61 64  ));{.yes ''|head
0000020: 20 2d 24 6e 0a 72 3d 24 72 9b 24 7b 6e 7d 41 4f   -$n.r=$r.${n}AO
0000030: 0a 74 3d 9b 24 7b 6e 7d 42 4f 24 74 0a 7d 0a 65  .t=.${n}BO$t.}.e
0000040: 63 68 6f 20 4f 24 7b 72 7d 4f 24 74              cho O${r}O$t
$
$ bash arc.sh 1
 OO
O  O
$ bash arc.sh 2
  OO
 O  O

O    O
$ bash arc.sh 3
   OO
  O  O

 O    O


O      O
$ bash arc.sh 4
    OO
   O  O

  O    O


 O      O



O        O
Dennis
quelle
You can use sed $nq to save a byte.
zeppelin
Sadly, no. I'd have to use sed ${n}q which is longer.
Dennis
Argh, I see, you can do sed $n\q instead, but that does not make much sense either, as it would be the same byte count as head !
zeppelin
3

Retina, 35

  • 2 bytes saved thanks to @MartinEnder

Port of my sed answer:

.+
$* OO
+`(\s*) (O *)O$
$&¶$1O $2 O

Try it online.

Digital Trauma
quelle
3

R, 89 bytes

a=2*v+3
x=matrix(" ",a,v^2+1)
for(k in 0:v)x[c(1-k,k+2)+v,k^2+1]="o"
x[a,]="\n"
cat(x,sep="")
  • Create a matrix of spaces (the variable a is the width of this matrix, saving a couple of bytes)
  • Fill in "o"s at the required locations, working from the top of the arc downwards and outwards
  • Add a newline at the end of each matrix row
  • Collapse the matrix down to a single string and print

This is my first attempt at golfing, comments welcome...

user2390246
quelle
3

Röda, 53 52 bytes

f n{seq 0,n|{|i|["
"*i," "*(n-i),"O"," "*i*2,"O"]}_}

Try it online!

Usage: main { f(5) }

Ungolfed version:

function f(n) {
    seq(0, n) | for i do
        push("\n"*i, " "*(n-i), "O", " "*i*2, "O")
    done
}
fergusq
quelle
Can you use a literal newline instead of \n and save 1 byte?
Kritixi Lithos
@KritixiLithos That works. Thanks!
fergusq
2

Befunge, 75 73 bytes

<vp00:&
1<-1_:v#\+55:g01\-g01g00" O"1\*2g01" O"1p0
#@_\:v>$$:!
1\,:\_^#:-

Try it online!

The first line reads in the velocity, v, and saves a copy in memory. The second line then counts down from v to zero, with the index i, and on each iteration pushes a sequence of character/length pairs onto the stack.

Length  Character
-----------------
1       'O'
i*2     ' '
1       'O'
v-i     ' '
i       LINEFEED

This sequence represents a kind of run-length encoding of the required output in reverse. The last two lines then simply pop these character/length pairs off the stack, outputting length occurrences of each character, until the stack is empty.

James Holderness
quelle
2

Java 8, 129 124 109 bytes

Golfed:

v->{String s="",t="";for(int j,y=0;y<=v;++y){for(j=0;j<v;++j)s+=j<y?"\n":" ";s+="o"+t+"o";t+="  ";}return s;}

Try it online!

Ungolfed:

public class DrawTheArcOfABall {

  public static void main(String[] args) {
    for (int i = 1; i < 6; ++i) {
      System.out.println(f(v -> {
        String s = "", t = "";
        for (int j, y = 0; y <= v; ++y) {
          for (j = 0; j < v; ++j) {
            s += (j < y ? "\n" : " ");
          }
          s += "o" + t + "o";
          t += "  ";
        }
        return s;
      } , i));
      System.out.println();
      System.out.println();
    }
  }

  private static String f(java.util.function.IntFunction<String> f, int v) {
    return f.apply(v);
  }
}

quelle
For the second nested for loop, I think for(;j<v;++) would work, because at this point in time j==y. Also, you could remove the third by adding a second string variable inside the main for loop String t=""; (12) and t+=" "; (8) inside the first nested loop. Then the third loop just becomes s+="o"+t+"o";
nmjcman101
Also, you can combine the first two nested loops to for(j=0;j<v;++j)s+=j<y?"\n":" "; although I'm not sure how this meshes with my previous comment about t
nmjcman101
You can initialize t="" alongside s in the beginning, and then add t+=" " each loop around after you do s+="o"+t+"o"
nmjcman101
2

Haskell, 69 bytes

r=replicate
f n=[0..n]>>= \a->r a '\n'++r(n-a)' '++'O':r(2*a)' '++"O"

Usage example: f 3 -> " OO\n O O\n\n O O\n\n\nO O". Try it online!.

nimi
quelle
2

VBA, 124 112 85 88 66 63 59 bytes

For i=0To[A1]:?Space([A1]-i)"O"Space(2*i)"O"String(i,vbCr):Next

Saved 29 bytes in total thanks to Taylor Scott

This must be run the in VBA Immediate window and print the result in the same.

Expanded / Formatted, it becomes:

For i=0 To [A1]
   Debug.Print Space([A1]-i) & "O" & Space(2*i) & "O" & String(i,vbCr)
Next

(It turns out that concatenation in a print command is automatic without an operator.)

Engineer Toast
quelle
b & s & Spaces alert!
CalculatorFeline
I tried and it erred the first time. Going back, I realized it'll expand b &s &String but not b&s&String. Also, at first I thought you meant to use the Space function which I totally should have and that ended up saving more bytes.
Engineer Toast
You can condense for i=0 To v and debug.? b to for i=0To v and Debug.?b, respectively for -2 bytes. And just so you know, the community consensus is that for languages with autoformatting, you may count before it is autoformatted, meaning after you make these changes you should have a byte count of 85 Bytes
Taylor Scott
On a second look, this is a snippet - not a function or subroutine; so it is not a valid solution. I believe that you could fix this by converting it an Excel VBA immediate window function and taking input from [A1] (v=[A1]) Also, I don't think you actually need the s variable.
Taylor Scott
1
@TaylorScott That seems like an obvious improvement in retrospect but I did not know that concatenation did not require an operator in the immediate window. That'll save me some bytes in the future. I did have to add a ; to the end of the print command, though, because it kept adding an extra line break by default. Thanks!
Engineer Toast
2

05AB1E, 18 13 bytes

ÝηRO«ð×'O«ζ»

Try it online!

Ý                # [0..n]
 €LRO            # [0.sum(), 0..1.sum(), ..., 0..n-1.sum(), 0..n.sum()]
     «          # Mirror image the array [0, 0..n.sum(), 0]
       ð×'O«     # Push that many spaces with an O appended to it.
            .B   # Pad small elements with spaces to equal largest element length.
              ø» # Transpose and print.
Magic Octopus Urn
quelle
1

Jelly, 17 16 bytes

‘Ḷ+\Ṛ⁶ẋ;€”Om0z⁶Y

Try it online!

How?

‘Ḷ+\Ṛ⁶ẋ;€”Om0z⁶Y - Main link: v         e.g. 3
‘                - increment: v+1            4
 Ḷ               - lowered range             [0,1,2,3]
  +\             - reduce with addition      [0,1,3,6]
    Ṛ            - reverse                   [6,3,1,0]
     ⁶           - a space                   ' '
      ẋ          - repeat (vectorises)       ['      ','   ',' ','']
       ;€        - concatenate each with
         ”O      -     an 'O'                ['      O','   O',' O','O']
           m0    - concatenate reflection    ['      O','   O',' O','O','O','O ','O   ','O      ']
             z⁶  - transpose with space fill ['   OO   ','  O  O  ','        ',' O    O ','        ','        ','O      O']
               Y - join with line feeds      ['   OO   \n  O  O  \n        \n O    O \n        \n        \nO      O']
                 - implicit print
Jonathan Allan
quelle
1

PHP, 76 bytes

for(;$argn>=0;$s.="  ")echo($r=str_repeat)("
",$i++),$r(" ",$argn--),o,$s,o;

Run with echo <v> | php -nR '<code>' or test it online.

loops $argn down from input to 0 and $i up from 0;
prints - in that order - in each iteration

  • $i newlines (none in the first iteration)
  • left padding: $argn spaces
  • left ball: o
  • inner padding: 2*$i spaces
  • right ball: o
Titus
quelle
1

V, 23 19 bytes

2éoÀñYço/^2á O
HPJ>

Try it online!

Explain

2éo            " Insert two 'o's
   Àñ          " <Arg> times repeat
     Y         " Yank the current (top) line.  This is always '\s*oo'
      ço/      " On every line that matches 'o'
         ^     " Go to the first non-whitespace character (the 'o')
          2á   " Append two spaces (between the two 'o's
             O " Add a blank line on top of the current one
H              " Go to the first line
 P             " Paste in front ('\s*oo')
  J            " Join this line with the blank line immediately after it
   >           " Indent once
nmjcman101
quelle
1

JavaScript (ES6), 87 bytes

f=
n=>' '.repeat(n+1).replace(/./g,"$`#$'O$`$`O").replace(/ *#/g,s=>[...s].fill``.join`
`)
<input type=number min=0 oninput=o.textContent=f(+this.value)><pre id=o>

Nonrecursive solution. Indexing requirement was annoying, both in the above and the following 62-byte (I don't know whether it would result in a shorter Retina port) recursive solution:

f=n=>~n?` `.repeat(n)+`OO`+f(n-1).replace(/^ *O/gm,`
$&  `):``
Neil
quelle
0

Stacked, 67 63 bytes

args 0#1+:@x:>{!n x\-1-' '*'O'+n 2*' '*+'O'+x 1-n!=n*LF*+out}"!

Initial attempt, 67 bytes

args 0# :@v 1+2*:>[:v:+1+\-2/*' '*'O'+''split]"!fixshape tr rev out

Full program. Generates something like:

('O'
 ' ' 'O'
 ' ' 'O'
 'O')

Which is the padded, transposed, reversed, and outputted.

Conor O'Brien
quelle
0

Batch, 163 bytes

@set l=@for /l %%i in (1,1,%1)do @call
@set s=
%l% set s= %%s%%
@set t=
%l%:c&for /l %%j in (2,1,%%i)do @echo(
:c
@echo %s%O%t%O
@set s=%s:~1%
@set t=  %t%
Neil
quelle
0

Ruby, 52 bytes

->x{(0..x).map{|a|$><<$/*a+' '*(x-a)+?O+' '*a*2+?O}}

No trailing newline (allowed by the rules: "at most one trailing newline")

G B
quelle
0

AHK, 93 bytes

m=0
n=1
f=%1%-1
Loop,%1%{
r=%r%{VK20 %f%}O{VK20 %m%}O{`n %n%}
m+=2
n++
f--
}
FileAppend,%r%,*

If I could figure out how to do math inside of repeating keystrokes, that'd be great.
- VK20 equates to a space
- FileAppend outputs to stdout if the filename is *

Engineer Toast
quelle
0

Haskell, 77 bytes

n!x=[1..n]>>x
-1#i=[]
x#i=(x-1)#(i+1)++x!"\n"++i!" "++'O':(2*x)!" "++"O"
(#0)

Try it online! Usage: (#0) 5

Laikoni
quelle