Piramidi egiziane


15

La Grande Piramide di Giza, la più grande piramide dell'Egitto, non è solo la più antica delle sette meraviglie del mondo antico, ma è anche l' unica a rimanere in gran parte intatta. Le piramidi egiziane possono richiedere fino a 20 anni per essere costruite e sono così grandi che Al-Aziz Uthman, figlio del grande Saladino che ha schiacciato i crociati, ha dovuto rinunciare a demolire le grandi piramidi di Giza perché era considerato un compito troppo grande . Le piramidi egiziane furono in gran parte costruite come tombe per i faraoni del paese e le loro consorti durante i periodi del Vecchio e Medio Regno (2686-1690 a.C. circa), e dal 2008 sono state scoperte 138 piramidi egiziane.

Il compito è creare un programma che inserisca una sequenza di distanze separate da uno spazio e produca piramidi di testo 10 × 10 separate da quelle distanze. Una distanza di 1 equivale a due caratteri.

Una piramide di testo sarà simile a questa:

         /\
        /--\
       /----\
      /------\
     /--------\
    /----------\
   /------------\
  /--------------\
 /----------------\
/------------------\

Se l'input è costituito solo da un'interruzione di riga, verrà prodotta una piramide, come sopra . Per ogni piramide, le piramidi a sinistra vengono visualizzate come se fossero di fronte.

Esempio I.

Ingresso:

4 3 1

Produzione:

         /\      /\    /\/\
        /--\    /--\  /--\-\
       /----\  /----\/----\-\
      /------\/------\-----\-\
     /--------\-------\-----\-\
    /----------\-------\-----\-\
   /------------\-------\-----\-\
  /--------------\-------\-----\-\
 /----------------\-------\-----\-\
/------------------\-------\-----\-\

Esempio II

Ingresso:

0 9

Produzione:

         /\                /\
        /--\              /--\
       /----\            /----\
      /------\          /------\
     /--------\        /--------\
    /----------\      /----------\
   /------------\    /------------\
  /--------------\  /--------------\
 /----------------\/----------------\
/------------------\-----------------\

Esempio III

Ingresso:

11

Produzione:

         /\                    /\
        /--\                  /--\
       /----\                /----\
      /------\              /------\
     /--------\            /--------\
    /----------\          /----------\
   /------------\        /------------\
  /--------------\      /--------------\
 /----------------\    /----------------\
/------------------\  /------------------\

La domanda per soddisfare questi requisiti nel minor numero di personaggi è il vincitore.

Riferimento: Wikipedia.org


Presumo che sia consentito uno spazio bianco aggiuntivo alla fine della riga?
Peter Taylor,

Dipende da chi chiedi. Nella lettura più rigorosa delle specifiche, non c'è spazio bianco dopo l'output. Ma dato che questo è per divertimento, non ho alcun problema.
nharren,

Quindi sono ammessi argomenti da riga di comando per accettare input?
Joey,

Purché soddisfi i requisiti. Ora vedo che la soluzione di Whitledge non è effettivamente in grado di gestire le interruzioni di riga come input (non riesco a annullare il mio voto), semplicemente funziona attorno producendo una piramide se non c'è input. Ma se riesci a trovare una soluzione in grado di gestire gli input di interruzione di riga (\ r o \ n va bene) come sostiene la riga di comando, allora per me va bene.
nharren,

Risposte:


4

Golfscript, 70 caratteri

~]0-:|;10,{:§9\-" "*"/""-"§2**+"\\"+:&|{.§>{§-(2*" "*1$}{-2*&>}if}%n}%

Porta diretta della mia soluzione Ruby , quindi sono sicuro che è possibile accorciarlo di alcuni caratteri.


5

Windows PowerShell, 122 132 133 139

$d=@(-split$input)-gt0
0..9|%{' '*(9-($x=$_))+($a="/$('--'*$_)\")+-join($d|%{'  '*(($_-$x-1)*($x-lt$_))
$a[(-2*$_)..-1]})}

Test script .

L'input casuale rende anche belle immagini:

Piramidi casuali


Funziona se aggiungo $input=Read-Hostin alto, altrimenti non richiede input. Come dovrebbe essere eseguito?
nharren,

@nharren: echo 0 3 4 1|powershell -noprofile -file pyramids.ps1o da PowerShell '0 1 4 3' | .\pyramids.ps1. Questo è un problema frequente con golf in PowerShell, purtroppo, come si può solo accettare o convogliato in ingresso o input interattivo. PowerShell non ha davvero l'idea di stdin in altre lingue e ambienti e questo a volte lo dimostra. Di solito vado per l'input convogliato, a meno che l'attività non richieda esplicitamente l'interattività, come Indovina il numero .
Joey,

Ah sì, ora funziona. Il mio schiacciare i pulsanti non ha prodotto alcun risultato e non sono riuscito a capire perché.
nharren,

4

Haskell, 148 caratteri

r=replicate
p d=map(\k->foldr(\n i->r(9-k)' '++'/':r(2*k)'-'++"\\"++drop(11+k)(r(2*n)' '++i))""$d++[0])[0..9]
main=interact$unlines.p.map read.words

Non sono abbastanza soddisfatto di questo! Sembra troppo lungo. Idee?


All'interno della lambda, è possibile modificare la grande pila di ++"s" in un unico elenco e utilizzare concat aka >>=id. Non so se sarà di aiuto. Un altro punto sarebbe usare foldr1invece di foldr.
FUZxxl

Grazie per le idee Né aiuta in questo caso: la conversione delle ++sequenze consente di risparmiare solo un personaggio per elemento e il sovraccarico della finale concatè troppo alto qui. Non è foldrpossibile utilizzare il foldr1modulo poiché il tempo del risultato è Stringmentre il tipo di elenco è [Int](Le 1varianti foldrichiedono che siano uguali.)
MtnViewMark

4

Python, 123 caratteri

N=[10]+map(int,raw_input().split())
for y in range(10):print''.join((2*n*' '+'/'+2*y*'-'+'\ ')[-2*n-1:-1]for n in N)[9-y:]

Per curiosità, questo python 2.5? Per farlo funzionare in Python 3.2, ho avvolto la funzione mappa in una funzione elenco, ho cambiato raw_input () in input () e ho cambiato print in print ().
nharren,

@nharren: funziona in 2.4.4 e 2.5.2 per me.
Keith Randall,

4

Ruby 1.9, 116 caratteri

d=gets.split-[?0]
10.times{|i|puts [?\s*(9-i),l=?/+?-*2*i+?\\,d.map{|r|i<(r=r.to_i)??\s*2*(r+~i)+l :l[-2*r,99]}]*""}

2

Perl, 130 126 132 caratteri

$_=<>;$s=" "x9;map{$k.="/\\"."  "x($_-1)if$_}split;$_="$s$k/\\$s\n";for$i(0..9){print;s%\\-%-\\%g;s%\\/%-\\%g;s%\\ %-\\%g;s% /%/-%g}

Versione leggermente più corta che accetta input come argomenti della riga di comando anziché da stdin:

$s=" "x9;map{$k.="/\\"."  "x($_-1)if$_}@ARGV;$_="$s$k/\\$s\n";for$i(0..9){print;s%\\-%-\\%g;s%\\/%-\\%g;s%\\ %-\\%g;s% /%/-%g}

Non riesco a credere che nessuno abbia ancora fatto una soluzione regex. Perl è ben lungi dall'essere la mia lingua migliore, quindi probabilmente questo può perdere molto di più. Sarei interessato a vedere un'implementazione di sed, se qualcuno è pronto per la sfida.

(Grazie, @mbx, per 4 caratteri).


foreach == per -> salva 4 caratteri
mbx

hai testato la tua versione con le prove fornite ?!
mbx,

@mbx, sì, funziona per me. Perl 5.10.1, Ubuntu. Che bug stai vedendo?
Peter Taylor,

@Peter Taylor - sul mio Ubuntu e Win32 funziona anche bene. L'ho provato per la prima volta su ideone che esegue perl 5.12.1.
mbx,

2
»Se l'ingresso è costituito solo da un'interruzione di linea«, in realtà, suggerisce un input standard.
Joey,

1

JavaScript, 396 byte

function p(a){for(u=0;u<10;u++){t[u+a][9-u]="/";for(k=9-u+1+a;k<10+u+a;k++)t[k][u]="-";
t[10+u+a][u]="\\"}}function _(a){t=[];for(i=0;i<50;i++){t[i]=[];for(j=0;j<10;j++)t[i][j]=" "
}var a=a.split(" "),b=a.reduce(function(a,b){return a-0+(b-0)})*2;for(i=a.length-1;i>=0;
i--)p(b),b-=a[i]*2-0;p(0);a="";for(j=0;j<10;j++){b="";for(i=0;i<50;i++)b+=t[i][j];
a+=b.replace(/\s+$/,"")+(j<9?"\n":"")}return a}

Non ho intenzione di vincere con JavaScript, ma ora c'è una voce JavaScript :)

Utilizzo: _("1 2 3")ecc.


1

Rubino (112)

Leggermente più breve della soluzione Ruby di Ventero, con un approccio diverso. Ho appena iniziato a studiare Ruby, quindi probabilmente questo può essere ridotto abbastanza.

s=' '*9+r='/\\';gets.split.map{|i|s+=' '*2*(i.to_i-1)+r}
10.times{puts s;s.gsub!' /','/-';s.gsub!(/\\.?/,'-\\')}

1

Powershell, 105 98 byte, la lettura più rigorosa delle specifiche

-7 byte dalla risposta di migimaru .

($a=' '+-join(,5+$args-gt0|%{'  '*--$_+'/\'}))
1..9|%{($a=$a-replace' /','/-'-replace'\\.?','-\')}

Script di prova:

$f = {

($a=' '+-join(,5+$args-gt0|%{'  '*--$_+'/\'}))
1..9|%{($a=$a-replace' /','/-'-replace'\\.?','-\')}

}

@(
,(@"
         /\
        /--\
       /----\
      /------\
     /--------\
    /----------\
   /------------\
  /--------------\
 /----------------\
/------------------\
"@)

,(@"
         /\      /\    /\/\
        /--\    /--\  /--\-\
       /----\  /----\/----\-\
      /------\/------\-----\-\
     /--------\-------\-----\-\
    /----------\-------\-----\-\
   /------------\-------\-----\-\
  /--------------\-------\-----\-\
 /----------------\-------\-----\-\
/------------------\-------\-----\-\
"@, 4,3,1)

,(@"
         /\                /\
        /--\              /--\
       /----\            /----\
      /------\          /------\
     /--------\        /--------\
    /----------\      /----------\
   /------------\    /------------\
  /--------------\  /--------------\
 /----------------\/----------------\
/------------------\-----------------\
"@, 0,9)

,(@"
         /\                    /\
        /--\                  /--\
       /----\                /----\
      /------\              /------\
     /--------\            /--------\
    /----------\          /----------\
   /------------\        /------------\
  /--------------\      /--------------\
 /----------------\    /----------------\
/------------------\  /------------------\
"@, 11)
) | % {
    $expected, $a = $_
    $result = &$f @a
    ($result-join"`n")-eq$expected
    $result 
}

Produzione:

True
         /\
        /--\
       /----\
      /------\
     /--------\
    /----------\
   /------------\
  /--------------\
 /----------------\
/------------------\
True
         /\      /\    /\/\
        /--\    /--\  /--\-\
       /----\  /----\/----\-\
      /------\/------\-----\-\
     /--------\-------\-----\-\
    /----------\-------\-----\-\
   /------------\-------\-----\-\
  /--------------\-------\-----\-\
 /----------------\-------\-----\-\
/------------------\-------\-----\-\
True
         /\                /\
        /--\              /--\
       /----\            /----\
      /------\          /------\
     /--------\        /--------\
    /----------\      /----------\
   /------------\    /------------\
  /--------------\  /--------------\
 /----------------\/----------------\
/------------------\-----------------\
True
         /\                    /\
        /--\                  /--\
       /----\                /----\
      /------\              /------\
     /--------\            /--------\
    /----------\          /----------\
   /------------\        /------------\
  /--------------\      /--------------\
 /----------------\    /----------------\
/------------------\  /------------------\

Powershell, 101 94, divertente con uno spazio bianco principale

($a=-join(,6+$args-gt0|%{'  '*--$_+'/\'}))
1..9|%{($a=$a-replace' /','/-'-replace'\\.?','-\')}

0

Non sono riuscito a ottenere la versione C # 3 più corta di questa. Non conosco esattamente il conteggio dei personaggi, ma sospetto di aver perso. :-(

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace PyramidRenderer
{
    /// <summary>
    /// Generates ASCII-art pyramids at user-specified horizontal locations to
    /// the standard output stream.
    /// </summary>
    public class Program
    {
        /// <summary>
        /// Generates one or more ASCII-art pyramids at the locations specified and 
        /// sends them to the standard output stream.
        /// </summary>
        /// <param name="args">The command-line arguments. These should be non-negative 
        /// integers that specify the horizontal distance of each additional pyramid from the 
        /// preceeding pyramid. Whether or not any distances are suppplied, a pyramid
        /// is rendered at the starting location.</param>
        public static void Main(string[] args)
        {
            try
            {
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                int[] pyramidDistances = ParsePyramidLocationsFromCommandLine(args).ToArray();
                PyramidCollection pyramids = new PyramidCollection(pyramidDistances);
                pyramids.RenderToText(Console.Out);
            }
            catch (ArgumentException ex)
            {
                Console.Error.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// Handler for the unhandled exception. This just displays the error message to 
        /// the standard error stream.
        /// </summary>
        /// <param name="sender">Required but unnecessary sender object for the event handler.</param>
        /// <param name="e">The object that represents the exception.</param>
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Debug.Assert(e.ExceptionObject != null);

            string exceptionText;
            Exception ex = e.ExceptionObject as Exception;
            if (ex == null)
                exceptionText = e.ExceptionObject.ToString();
            else
                exceptionText = ex.Message;
            Console.Error.WriteLine(exceptionText);
        }

        /// <summary>
        /// Takes the command-line arguments and converts them to a sequence of 
        /// non-negative integers.
        /// </summary>
        /// <param name="args">The command-line arguments as supplied to Main.</param>
        /// <returns>A sequence of integers that represent the user’s distance selections.</returns>
        /// <exception cref="ArgumentException">An invalid argument was supplied.</exception>
        private static IEnumerable<int> ParsePyramidLocationsFromCommandLine(string[] args)
        {
            Debug.Assert(args != null);

            foreach (string arg in args)
            {
                int result;
                if (int.TryParse(arg, out result))
                {
                    if (result < 0)
                        throw new ArgumentException(string.Format("Invalid distance specified: {0}", arg));

                    yield return result;
                }
                else
                {
                    throw new ArgumentException(string.Format("Invalid option: {0}", arg));
                }
            }
        }
    }

    /// <summary>
    /// Represents a single pyramid to be rendered.
    /// </summary>
    internal class Pyramid
    {
        /// <summary>
        /// The height of the pyramids in text rows. The width of each pyramid will be
        /// twice the height.
        /// </summary>
        internal const int Height = 10;

        /// <summary>
        /// The length in characters of the horizontal unit distance in which the user 
        /// specifies the pyramid distances.
        /// </summary>
        internal const int PyramidUnits = 2;

        /// <summary>
        /// The character to output as the background of the pyramids.
        /// </summary>
        private const char backgroundChar = ' ';

        /// <summary>
        /// The character to output as the left edge of the pyramids.
        /// </summary>
        private const char leftEdgeChar = '/';

        /// <summary>
        /// The character to output within each pyramid, between the edges.
        /// </summary>
        private const char brickChar = '-';

        /// <summary>
        /// The character to output as the right edge of the pyramids.
        /// </summary>
        private const char rightEdgeChar = '\\';

        /// <summary>
        /// The absolute horizonal location of the pyramid’s bottom left corner as 
        /// specified in PyramidUnits.
        /// </summary>
        private int position;

        /// <summary>
        /// Constructs a new pyramid object at the specified location.
        /// </summary>
        /// <param name="position">The absolute horizonal location of the pyramid’s bottom
        /// left corner in PyramidUnits.</param>
        internal Pyramid(int position)
        {
            Debug.Assert(position >= 0);

            this.position = position;
        }

        /// <summary>
        /// Renders a single row the pyramid to the supplied text stream starting at
        /// the indicated location.
        /// </summary>
        /// <param name="textWriter">The output stream to which the pyramid is to
        /// be rendered.</param>
        /// <param name="row">The row of the pyramid to render. Zero is the top row,
        /// and Height - 1 is the bottom row.</param>
        /// <param name="startingPosition">The text character position—indexed at zero—at 
        /// which the rendering is to begin. If non-zero, this identifies the column one 
        /// past the ending location of the previous pyramid.</param>
        /// <returns>The horizontal location (in characters) at which the next item 
        /// may be rendered.</returns>
        internal int RenderRow(TextWriter textWriter, int row, int startingPosition)
        {
            Debug.Assert(textWriter != null);
            Debug.Assert(row >= 0);
            Debug.Assert(startingPosition >= 0);

            int leftBoundary = Height - 1 - row + position * PyramidUnits;
            int rightBoundary = Height + row + position * PyramidUnits;

            startingPosition = RenderField(textWriter, backgroundChar, startingPosition, leftBoundary);
            startingPosition = RenderField(textWriter, leftEdgeChar, startingPosition, leftBoundary + 1);
            startingPosition = RenderField(textWriter, brickChar, startingPosition, rightBoundary);
            startingPosition = RenderField(textWriter, rightEdgeChar, startingPosition, rightBoundary + 1);
            return startingPosition;
        }

        /// <summary>
        /// Outputs a sequence of repeated characters from the indicated starting position to
        /// just before the ending position, unless the starting position is already equal to
        /// or greater than the ending position.
        /// </summary>
        /// <param name="textWriter">The output stream to which the field is to be rendered.</param>
        /// <param name="character">The character to be repeated in the output.</param>
        /// <param name="startingPosition">The location at which rendering may begin in 
        /// characters indexed at zero.</param>
        /// <param name="endingPosition">The location one past the location at which rendering
        /// is to end.</param>
        /// <returns>The position at which the next field may begin.</returns>
        private static int RenderField(TextWriter textWriter, char character, int startingPosition, int endingPosition)
        {
            Debug.Assert(textWriter != null);
            Debug.Assert(startingPosition >= 0);
            Debug.Assert(endingPosition >= 0);

            int charCount = endingPosition - startingPosition;
            if (charCount <= 0)
                return startingPosition;
            textWriter.Write(new string(character, charCount));
            return endingPosition;
        }
    }

    /// <summary>
    /// A collection of pyramids to be displayed.
    /// </summary>
    internal class PyramidCollection
    {
        /// <summary>
        /// A left-to-right ordered list of the pyramids that the user has 
        /// requested to be rendered.
        /// </summary>
        List<Pyramid> allPyramids = new List<Pyramid>();

        /// <summary>
        /// Constructs a new pyramid collection.
        /// </summary>
        /// <param name="distances">The distances of each non-leftmost pyramid (in PyramidUnits) after
        /// the previous pyramid. The total number of pyramids will be one greater than the length of
        /// the distances array.</param>
        internal PyramidCollection(int[] distances)
        {
            Debug.Assert(distances != null);

            int nextPosition = 0;
            allPyramids.Add(new Pyramid(nextPosition));
            foreach (int nextDistance in distances)
            {
                Debug.Assert(nextDistance >= 0);

                try
                {
                    checked
                    {
                        nextPosition += nextDistance;
                        int endLocation = nextPosition * Pyramid.PyramidUnits + Pyramid.Height * 2;
                    }
                }
                catch (OverflowException)
                {
                    // Ignore any pyramids specified beyond the integer maximum distance.
                    break;
                }
                allPyramids.Add(new Pyramid(nextPosition));
            }
        }

        /// <summary>
        /// Outputs ASCII-art images of the pyramids in this collection to the 
        /// provided output stream.
        /// </summary>
        /// <param name="textWriter">The output stream to which the pyramids
        /// are to be rendered.</param>
        internal void RenderToText(TextWriter textWriter)
        {
            Debug.Assert(textWriter != null);

            for (int row = 0; row < Pyramid.Height; row++)
            {
                int startingPosition = 0;
                foreach (Pyramid pyramid in allPyramids)
                {
                    startingPosition = pyramid.RenderRow(textWriter, row, startingPosition);
                }
                textWriter.WriteLine();
            }
        }
    }

}

3
Hai confuso Code Bowling e Code Golf per caso?
Joey,

1
Almeno fingi di provare. Le persone non avranno una lingua verbosa contro di te se la giochi a golf .
dmckee --- ex-moderatore gattino

Immagino che sia la tua versione dettagliata per spiegare i tuoi astuti trucchi. Sembra che ti sia dimenticato di pubblicare la versione golf.
mbx,

@Joey, @dmckee - Ho pensato di fare una versione da golf, ma non ci sono riuscito. Sono terribile in questo gioco comunque. Il codice oscuro va completamente contro la mia natura. Probabilmente dovrei stare lontano dai puzzle del golf! - @mbx - Purtroppo, non ci sono trucchi intelligenti.
Jeffrey L Whitledge,
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.