Vai a generare un po 'di Java


14

Il tuo capo vuole che tu scriva codice in questo modo:

public static boolean isPowerOfTen(long input) {
  return
    input == 1L
  || input == 10L
  || input == 100L
  || input == 1000L
  || input == 10000L
  || input == 100000L
  || input == 1000000L
  || input == 10000000L
  || input == 100000000L
  || input == 1000000000L
  || input == 10000000000L
  || input == 100000000000L
  || input == 1000000000000L
  || input == 10000000000000L
  || input == 100000000000000L
  || input == 1000000000000000L
  || input == 10000000000000000L
  || input == 100000000000000000L
  || input == 1000000000000000000L;
}

(Martin Smith, su /codereview//a/117294/61929 )

che è efficiente e così, ma non è così divertente da scrivere. Poiché si desidera ridurre al minimo il numero di pressioni di tasti da eseguire, si scrive un programma o una funzione (o metodo) più breve che genera questa funzione per l'utente (o restituisce una stringa all'output). E poiché hai la tua tastiera unicode full range personalizzata con tutti i 120.737 tasti richiesti per tutti gli Unicode 8.0, contiamo i caratteri Unicode, anziché i tasti premuti. O byte, se la tua lingua non utilizza il codice sorgente Unicode.

Qualsiasi input che il tuo programma o funzione tiene conto del tuo punteggio, dal momento che ovviamente devi anche digitarlo.

Chiarimenti e modifiche:

  • Rimossi 3 spazi finali dopo l'ultimo }
  • Rimosso un singolo spazio finale dopo return
  • Restituire una stringa di output da una funzione / metodo è ok

12
0==Math.log10(input)%1
SuperJedi224,

7
Dici " contiamo i caratteri unicode ", ma poi dici subito " O byte ". Qual é?
Maniglia della porta

2
Qualunque cosa tu preferisca, cioè quella che ti dà il punteggio più basso. Aggiunti byte per consentire lingue che non usano la sorgente di testo.
Filip Haglund,

1
while(input%10==0) input/=10; return input == 1;
PSkocik,

4
05AB1E utilizza Windows CP1252, che è byte, non unicode. Sto mirando a regole standard, ma mi viene detto che mi sbaglio sempre.
Filip Haglund,

Risposte:


15

PostgreSQL, 158 caratteri

select'public static boolean isPowerOfTen(long input) {
  return
   '||string_agg(' input == 1'||repeat('0',x)||'L','
  ||')||';
}'from generate_series(0,18)x

Non ho mai visto un RDBMS usato come risposta da golf di codice ... dolce! +1
Chris Cirefice,

@ChrisCirefice SQL è in realtà un po 'comune su questo sito. (O almeno più comune di quanto ci si potrebbe aspettare.)
Alex A.

@AlexA. Beh, PCG è uno dei miei siti SE meno frequentati, quindi non ho mai visto una risposta SQL :)
Chris Cirefice,

7

Tasti di Vim 97

ipublic static boolean isPowerOfTen(long input) {
  return
  || input == 1L<esc>qyYpfLi0<esc>q16@yo}<esc>3Gxx

Bene, oggi sono in giro con Vim che produce Java, quindi perché non continuare la tendenza!


la sostituzione fLcon $potrebbe salvarti una sequenza di tasti
Leaky Nun,

Inoltre, la terza riga input == 1Lè disallineata di un byte ...
Leaky Nun,

Quindi l'ultimo xdovrebbe essere cambiato in r<sp>e quindi il numero di sequenze di tasti sarebbe invariato
Leaky Nun

7

05AB1E , 99 97 96 94 93 87 byte

Codice:

“‚Æ£‹ÒŒ€ˆPowerOfTen(“?“¢„î®) {
 «‡
   “?19FN0›i"  ||"?}’ î® == ’?N°?'L?N18Qi';,"}"?}"",

Provalo online!

Utilizza la codifica CP-1252 .


7

CJam, 52 caratteri

YA#_("𐀑򀺸󆚜񸎟񜏓񞍁򛟯󩥰󾐚򉴍􍼯𹾚򶗜򳙯󭧐񹷜񊽅𸏘򴂃򦗩󧥮𤠐𰑈򶂤𘏧󔆧򇃫󡀽򊠑񊩭򯐙񛌲񊚩𤱶𻺢"f&bY7#b:c~

Provalo online!

Fase 1

Utilizzando i caratteri Unicode da U + 10000 a U + 10FFFF, possiamo codificare 20 bit in un singolo carattere. CJam utilizza internamente caratteri a 16 bit, quindi ognuno verrà codificato come una coppia di surrogati , uno nell'intervallo da U + D800 a U + DBFF, seguito da uno nell'intervallo da U + DC00 a U + DFFF.

Prendendo il AND bit a bit di ogni surrogato con 1023, otteniamo i 10 bit di informazioni che codifica. Possiamo convertire l'array risultante dalla base 1024 alla base 128 per decodificare una stringa arbitraria di caratteri Unicode all'esterno del BMP in una stringa ASCII.

Il codice procede come segue:

YA#    e# Push 1024 as 2 ** 10.
_(     e# Copy and decrement to push 1023.

"𑅰󻢶񹱨񉽌񍍎񄆋򎿙򧃮񑩹󠷽􂼩􉪦񭲣񶿝򭁩󭰺􄔨񍢤𘎖񮧗򦹀𹀠񐢑񜅈𠟏򘍎󾇗򲁺􅀢򅌛񎠲򦙤򃅒𹣬񧵀򑀢"

f&     e# Apply bitwise AND with 1023 to each surrogate character.
b      e# Convert the string from base 1024 to integer.
Y7#    e# Push 128 as 2 ** 7.
b      e# Convert the integer to base 128.
:c     e# Cast each base-128 to an ASCII character.
~      e# Evaluate the resulting string.

Fase 2

Il processo di decodifica dall'alto produce il seguente codice sorgente ( 98 byte ).

"public static boolean isPowerOfTen(long input) {
  return
   ""L
  || input == ":S6>AJ,f#S*"L;
}"

Provalo online!

Il codice procede come segue:

e# Push the following string.

"public static boolean isPowerOfTen(long input) {
  return
   "

e# Push the following string and save it in S.

"L
  || input == ":S

e# Discard the first 6 characters of S. The new string begins with " input".

6>

e# Elevate 10 (A) to each exponent below 19 (J).

AJ,f#

e# Join the resulting array, using the string L as separator.

S*

e# Push the following string.

"L;
}"

Potresti aspettarti che un sito SE come l'ebraismo sia quello che mette alla prova lo stress del supporto unicode del sito, ma questo è pazzo: D
Filip Haglund

Vedo esattamente due dei caratteri tra le virgolette. Puoi pubblicare un hexdump?
Pavel,

Puoi davvero vederne due? Non ho tale fortuna ... Codificando i personaggi come UTF-8, il hexdump sarebbe simile a questo. tio.run/nexus/bash#AagAV///eHhkIC1nIDH//…
Dennis

6

Java, 217 215 220 219 192 byte

golfed:

public static String b(){String s="public static boolean isPowerOfTen(long input) {\n  return\n    input == 1L",z="";for(int i=0;i++<18;){z+="0";s+="\n  || input == 1"+z+"L";}return s+";\n}";}

Ungolfed:

  public static String a(){
    String s = "public static boolean isPowerOfTen(long input) {\n  return\n    input == 1L", z="";
    for (int i=0; i++ < 18;) {
        z += "0";
        s += "\n  || input == 1"+z+"L";
    }
    return s + ";\n}";
  }

(prima risposta, wuhu)

Grazie!
-2 byte: user902383
-1 byte: Denham Coote

I cambiamenti:

  • schede utilizzate anziché spazi
  • ha perso l'ultima riga di output: 18 -> 19
  • anello interno rimosso
  • modificato dalla stampa alla stringa di ritorno

4
il tuo ciclo interno non ha bisogno di parentesi quadre
user902383

Usa la sintassi Java 8, abbreviata anche qualche altra cosa: ()->{String s="public static boolean isPowerOfTen(long input) {\n\treturn input == 1L";for(int i=0,k;i++<18;){s+="\n\t|| input == 1";for(k=0;k++<i;)s+="0";s+="L";}return s+";\n}";}(180 byte) Ora restituisce la stringa invece di stampare, ma è più breve.
Addison Crump,

1
+1 per la scrittura di un programma Java dettagliato per generare un programma Java ancora più dettagliato.
Cyoce,

invece di for(int i=1;i<19;i++)te puoi scrivere for(int i=1;i++<19;)che salva un byte
Denham Coote il

Inoltre, dichiarare int i=1,k;e quindi è possibile scrivere for(;i++<19;)efor(k=0;k++<i;)
Denham Coote il

4

Pyth, 118 106 103 byte

s[."
{Z-L¡JxÙÿ
LæÝ<­í?¢µb'¥ÜA«Ç}h¹äÚÏß"\nb*4dj"\n  || "ms[." uøs|ÀiÝ"*d\0\L)U19\;b\}

Provalo online!

Tutta questa stringa hardcoding consuma davvero molti byte , ma non posso farci nulla .

Aggiornamento: 3 byte salvati utilizzando una stringa compressa. Grazie @ user81655 per il suggerimento!


Potresti usare stringhe piene ...
user81655,

Non conosco Pyth e non sono sicuro che esista un modo per impacchettare l'intera stringa (il programma di impacchettamento la altererebbe sempre) ma comprimendo re concatenando i nrisultati in questo (98 byte).
user81655,

@ user81655 Grazie, non sapevo che Pyth avesse questo. :) Ha senso solo impacchettare la prima grande stringa, quindi il sovraccarico che produci dalla decompressione non vale per stringhe più piccole.
Denker,

@ user81655 Ne sono consapevole, ma conto 103 caratteri. Come sei arrivato a 97?
Denker,

Oops, errore mio, li stavo contando male.
user81655

4

C # (CSI) 181 180 179 byte

string i=" input == 1",e="public static bool";Console.Write(e+@"ean isPowerOfTen(long input) {
  return
   "+i+string.Join(@"L
  ||"+i,e.Select((_,x)=>new string('0',x)))+@"L;
}")

C'è solo un piccolo trucco coinvolto. Il modo semplice per scrivere questo sarebbe:

string.Join("L\n  || input == 1",Enumerable.Range(0,18).Select(x=>new string('0',x)))

usando la stringa con i primi 18 caratteri del testo di cui ho bisogno comunque, posso liberarmi del lungo Enumerable.Range. Ciò funziona perché la stringa implementa IEnumerable e esiste una versione di Select che passa l'elemento (non necessario) e l'indice che vogliamo alla funzione lambda.


1
@WashingtonGuedes Grazie
raggy

1
aggiungi qualche spiegazione per favore
Eumel

1
CSI supporta i corpi di espressione? In tal caso, { return ... }può essere sostituito da =>....
mınxomaτ,

Al momento non sono sul computer, quindi non posso provarlo. L'ultima stringa testuale sfugge alla parentesi al suo interno? O è un grande trucco che non conoscevo? :)
Yytsi,

4

PowerShell, 120 byte

'public static boolean isPowerOfTen(long input) {'
'  return'
"   $((0..18|%{" input == 1"+"0"*$_})-join"L`n  ||")L;`n}"

Le prime due righe sono semplicemente letterali stringa, che vengono emesse così come sono.

La terza riga inizia con tre spazi e termina con L;`n}"per finire gli ultimi due byte. Il bit centrale all'interno del blocco di script $(...)è costruito mediante il for-loop %da 0a 18e ogni iterazione costruisce una stringa che inizia con input == 1concatenata con il numero corrispondente di zeri. Questo sputerà una serie di stringhe. Abbiamo quindi -joinogni elemento dell'array con L`n ||per realizzare i newline-pipe. Quella stringa grande è l'output del blocco di script, che viene inserito automaticamente nel mezzo e output.

PS C:\Tools\Scripts\golfing> .\go-generate-some-java.ps1
public static boolean isPowerOfTen(long input) {
  return
    input == 1L
  || input == 10L
  || input == 100L
  || input == 1000L
  || input == 10000L
  || input == 100000L
  || input == 1000000L
  || input == 10000000L
  || input == 100000000L
  || input == 1000000000L
  || input == 10000000000L
  || input == 100000000000L
  || input == 1000000000000L
  || input == 10000000000000L
  || input == 100000000000000L
  || input == 1000000000000000L
  || input == 10000000000000000L
  || input == 100000000000000000L
  || input == 1000000000000000000L;
}

3

Javascript, 172 157 152 150 148 byte

p=>`public static boolean isPowerOfTen(long input) {
  return${[...Array(19)].map((x,i)=>`
  ${i?'||':' '} input == 1${'0'.repeat(i)}L`).join``};
}`


2
In ES7 è possibile salvare 9 byte utilizzando ${10**i}invece di 1${'0'.repeat(i)}.
Neil,

3

C, 158 155 byte

i;main(){for(puts("public static boolean isPowerOfTen(long input) {\n  return");i<19;)printf("  %s input == 1%0.*dL%s\n",i++?"||":" ",i,0,i<18?"":";\n}");}

Provalo online qui .


È possibile radere via un byte se si utilizza il valore restituito di printf:i;main(){for(puts("public static boolean isPowerOfTen(long input) {\n return");printf(" %s input == 1%0.*dL%s\n",i++?"||":" ",i,0,i<18?"":";\n}")-37);}
algmyr

3

Gelatina, 75 byte

(Questi sono byte nella tabella codici personalizzata di Jelly .)

0r18⁵*;@€⁶j“¢œḤḅg^NrÞḢ⁷ẉ»“⁵®UẆƓḃÐL⁴ṖịṛFþẈ¹9}¶ ƁḋȮ¦sẒẆd€Ḟɼ¿ỌṀP^µ\f@»;;“L;¶}”

Provalo qui.

Spiegazione

0r18      Range [0..18]
⁵*        Take the 10^ of each number
;@€⁶      Prepend a space to each number
j“...»    Join by compressed string "L\n  || input =="
“...»;    Prepend compressed string "public static ... =="
;“L;¶}”   Append "L;\n}"

3

Vimscript, 120 byte

Potrebbe anche usare lo strumento giusto per il lavoro.

Ciò presuppone che non siano stati impostati autoindent, ecc. ^[e ^Msono caratteri di escape rispettivamente per i caratteri ESCe CR.

La amacro duplica la riga corrente e aggiunge uno 0 alla copia. La :normlinea genera tutta la piastra della caldaia e la indent == 1Llinea, quindi utilizza aper creare le altre.

:let @a='yyp$i0^['
:norm ipublic static boolean isPowerOfTen(long input) {^M  return^M  || input == 1L^[18@a$a;^M}
:3s/||/ /

Nel caso in cui gli spazi finali dell'output di esempio su due righe non fossero errori di battitura, ecco una versione da 126 byte che li include.

:let @a='yyp/L^Mi0^['
:norm ipublic static boolean isPowerOfTen(long input) {^M  return ^M  || input == 1L^[18@a$a;^M}   
:3s/||/ /

2

Oracle SQL 9.2, 311 byte

SELECT REPLACE(REPLACE('public static boolean isPowerOfTen(long input) {'||CHR(10)||'  return'||c||';'||'}', 'n  ||', 'n'||CHR(10)||'   '),CHR(10)||';', ';'||CHR(10)) FROM(SELECT LEVEL l,SYS_CONNECT_BY_PATH('input == '||TO_CHAR(POWER(10,LEVEL-1))||'L'||CHR(10),'  || ')c FROM DUAL CONNECT BY LEVEL<20)WHERE l=19

2

Perl 5 - 130 141

@s=map{'input == 1'.0 x$_."L\n  ||"}0..18;$s[$#s]=~s/\n  \|\|/;\n}/g;print"public static boolean isPowerOfTen(long input){\n  return\n    @s"

EDIT: risolto per avere il rientro esatto


Non è necessario utilizzare la parentesi nell'intervallo. In cambio sarebbe bello riprodurre l'esatto rientro.
arte

Grazie per la parentesi che ho dimenticato. L'ho corretto per avere il rientro esatto.
ChatterOne

Non è necessaria la gbandiera per la sostituzione. Anche quando si dispone di un singolo \nin quella stringa, si può semplicemente abbinare e tutto quello che segue: $s[$#s]=~s/\n.+/;\n}/. Ma uno joinbasato sarebbe ancora più breve: pastebin.com/hQ61Adt8
manatwork

Grazie, ma non penso che sarebbe bello se avessi appena copiato e incollato la tua soluzione, quindi la lascerò come è il mio miglior sforzo. Col tempo, starò meglio giocando a golf :-)
ChatterOne

2

ES6, 139 byte

_=>"0".repeat(19).replace(/./g,`
 || input == 1$\`L`).replace(`
 ||`,`public static boolean isPowerOfTen(long input) {
  return\n  `)+`;
}`

Adoro queste domande sulla generazione del triangolo.


2

Kotlin, 194 193 characters

fun main(u:Array<String>){var o="public static boolean isPowerOfTen(long input) {\n\treturn"
var p:Long=1
for(k in 0..18){
o+="\n\t"
if(k>0)o+="||"
o+=" input == ${p}L"
p*=10
}
print("$o;\n}")}

Test it at http://try.kotlinlang.org/


Welcome to Programming Puzzles & Code Golf. Nice first answer, but please add a link to an online interpreter or add an example on how to run this program, so others can verify it. However, have a great time here! :)
Denker

2

Ruby, 125 119 bytes

$><<'public static boolean isPowerOfTen(long input) {
  return
   '+(0..19).map{|i|" input == #{10**i}L"}*'
  ||'+';
}'

Thanks to manatwork for -6 bytes!


Not much original as most of the solutions are doing this way, but still shorter: pastebin.com/1ZGF0QTs
manatwork

2

jq, 123 characters

(121 characters code + 2 characters command line option.)

"public static boolean isPowerOfTen(long input) {
  return
   \([range(19)|" input == 1\("0"*.//"")L"]|join("
  ||"));
}"

Sample run:

bash-4.3$ jq -nr '"public static boolean isPowerOfTen(long input) {
>   return
>    \([range(19)|" input == 1\("0"*.//"")L"]|join("
>   ||"));
> }"'
public static boolean isPowerOfTen(long input) {
  return
    input == 1L
  || input == 10L
  || input == 100L
  || input == 1000L
  || input == 10000L
  || input == 100000L
  || input == 1000000L
  || input == 10000000L
  || input == 100000000L
  || input == 1000000000L
  || input == 10000000000L
  || input == 100000000000L
  || input == 1000000000000L
  || input == 10000000000000L
  || input == 100000000000000L
  || input == 1000000000000000L
  || input == 10000000000000000L
  || input == 100000000000000000L
  || input == 1000000000000000000L;
}

On-line test (Passing -r through URL is not supported – check Raw Output yourself.)


1

Javascript 175 bytes

Let's do this regularly

var s = "public static boolean isPowerOfTen(long input) {\n\treturn\n\t\tinput == 1";
for (var i = 1; i < 20; i++) {
    s += "\n\t|| input == 1";
    for (var j = 0; j < i; j++) {
        s += "0";
    }
    s += "L" ;
}
s += ";\n}";
alert(s);

Pretty small. Now, some javascript magic, like no semicolons needed, or no var's, etc.:

k="input == 1"
s="public static boolean isPowerOfTen(long input) {\n\treturn\n\t\t"+k+"L"
for(i=1;i<20;i++){s+="\n\t|| "+k
for(j=0;j<i;j++)s+="0";s+="L"}s+=";\n}"
alert(s)

Can you explain how that magic works? :)
Marv

3
Javascript doesn't care about semicolons, at least until the keywords (for, while, var, etc.) aren't "touching" anything else. Also, if you don't use the var keyword, you get global variables, wich is the worst feature I have ever seen in a programming language thus far.
Bálint

@Bálint. Why this would be the worst feature?
removed

@WashingtonGuedes You know, most languages remind you if you misstyped something inside a function. Because javascript takes that as if you made a whole new variable, it does not going to say anything about that.
Bálint

Also, same one applies to = returning a true.
Bálint

1

Python (3.5) 137 136 bytes

print("public static boolean isPowerOfTen(long input) {\n  return\n   ",'\n  || '.join("input == %rL"%10**i for i in range(19))+";\n}")

Previous version

print("public static boolean isPowerOfTen(long input) {\n  return\n   ",'\n  || '.join("input == 1"+"0"*i+"L"for i in range(19))+";\n}")

135 with Python 2.7: print "public static boolean isPowerOfTen(long input) {\n return\n %s;\n}"%"\n || ".join("input == %r"%10L**i for i in range(19))
moooeeeep

@moooeeeep you're right, the use of %r win 1 bytes and the python 2 print (without parenthesis ) win another one
Erwan

0

ANSI-SQL, 252 characters

WITH t as(SELECT '   'x,1 c,1 l UNION SELECT'  ||',c*10,l+1 FROM t WHERE l<19)SELECT 'public static boolean isPowerOfTen(long input) {'UNION ALL SELECT'  return 'UNION ALL SELECT x||' input == '||c||'L'||SUBSTR(';',1,l/19)FROM t UNION ALL SELECT'}   ';

Ungolfed:

WITH t as (SELECT '   ' x,1 c,1 l UNION
           SELECT '  ||',c*10,l+1 FROM t WHERE l<19)
SELECT 'public static boolean isPowerOfTen(long input) {' UNION ALL
SELECT '  return ' UNION ALL
SELECT x||' input == '||c||'L'||SUBSTR(';',1,l/19) FROM t UNION ALL
SELECT '}   ';

Not a serious attempt, just poking at the Oracle SQL/T-SQL entries.


For 40 additional chars I can add "from dual " and make it an "Oracle SQL" entry.
user1361991

0

JavaScript (Node.js), 156 bytes

s="public static boolean isPowerOfTen(long input) {\n  return "
for(i=1;i<1e19;i*=10)s+="\n  "+(i-1?"||":" ")+" input == "+i+"L"
console.log(s+";\n}   \n")

The i-1 will only be 0 (and thus falsey) on the very first round (it's just slightly shorter than i!=1.

Suggestions welcome!


0

Perl 5, 137 bytes

Not based on the previous Perl answer, but it is somehow shorter. I believe it can be shortened down again by taking care of the first "input" inside the loop, but I didn't try anything yet (at work atm)

$i="input";for(1..18){$b.="  || $i == 1"."0"x$_."L;\n"}print"public static boolean isPowerOfTen(long $i) {\n  return\n    $i == 1L;\n$b}"

0

CJam, 112 chars

"public static boolean isPowerOfTen(long input) {
  return
    input == 1"19,"0"a19*.*"L
  || input == 1"*"L;
}"

0

AWK+shell, 157 bytes

echo 18|awk '{s="input == 1";printf"public static boolean isPowerOfTen(long input) {\n return\n    "s"L";for(;I<$1;I++)printf"\n  ||%sL",s=s"0";print";\n}"}'

The question did say to count everything you would have to type. This does have the added bonus of being able to select how many lines would be placed in the isPowersOfTen method when the boss inevitably changes his mind.


Passing a here-string is shorter than piping from echo: awk '…'<<<18
manatwork

I knew about here-file but not here-string. Thanks for the info.
Robert Benson

0

T-SQL 289, 277, 250, 249 bytes

SELECT'public static boolean isPowerOfTen(long input){return '+STUFF((SELECT'||input=='+N+'L 'FROM(SELECT TOP 19 FORMAT(POWER(10.0,ROW_NUMBER()OVER(ORDER BY id)),'F0')N FROM syscolumns)A FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'),1,2,'')+';}'

Update: Thanks @Bridge, I found a few more spaces too :)

Update2: Changed CTE to subquery -27 chars :) Update3: Another space bites the dust @bridge :)


1
I was able to trim off 7 more spaces (282 bytes) without changing the rest of the code: WITH A AS(SELECT CAST('1'AS VARCHAR(20))N UNION ALL SELECT CAST(CONCAT(N,'0')AS VARCHAR(20))FROM A WHERE LEN(N)<20)SELECT'public static boolean isPowerOfTen(long input){return '+STUFF((SELECT'|| input=='+N+'L 'FROM A FOR XML PATH(''),TYPE).value('.', 'VARCHAR(MAX)'), 1, 3, '')+';}'
Bridge

1
Now I look back I can see all the extra spaces in my original comment! I've found one more space you can get rid of - the one immediately after ROW_NUMBER()
Bridge

0

R, 185 bytes

Golfed

options(scipen=999);p=paste;cat(p("public static boolean isPowerOfTen(long input) {"," return",p(sapply(0:19,function(x)p(" input == ",10^x,"L",sep="")),collapse="\n ||"),"}",sep="\n"))

Ungolfed

options(scipen=999)
p=paste
cat(
  p("public static boolean isPowerOfTen(long input) {",
        " return",
        p(sapply(0:19,function(x)p(" input == ",10^x,"L",sep="")),collapse="\n ||"),
        "}",
        sep="\n")
)

0

Perl 6 (115 bytes)

say "public static boolean isPowerOfTen(long input) \{
  return
   {join "L
  ||",(" input == "X~(10 X**^19))}L;
}"

X operator does list cartesian product operation, for example 10 X** ^19 gives powers of ten (from 10 to the power of 0 to 19, as ^ is a range operator that counts from 0). Strings can have code blocks with { (which is why I escape the first instance of it).


0

Java, 210 / 166

Score is depending on whether returning the input from a function meets the definition of 'output'.

Console output (210):

class A{public static void main(String[]z){String a=" input == 1",t="L\n  ||"+a,s="public static boolean isPowerOfTen(long input) {\n  return\n   "+a;for(int i=0;++i<19;)s+=t+="0";System.out.print(s+"L;\n}");}}

String return (166):

String a(){String a=" input == 1",t="L\n  ||"+a,s="public static boolean isPowerOfTen(long input) {\n  return\n   "+a;for(int i=0;++i<19;)s+=t+="0";return s+"L;\n}";}

Legible version:

String a() {
    String a=" input == 1", t = "L\n  ||"+a,
        s = "public static boolean isPowerOfTen(long input) {\n  return\n   "+a;
    for (int i = 0; ++i < 19;)
        s += t += "0";
    return s + "L;\n}";
}

0

Batch, 230 208 206 205 bytes

@echo off
echo public static boolean isPowerOfTen(long input) {
echo   return
set m=input == 1
echo    %m%L
for /l %%a in (1,1,17)do call:a
call:a ;
echo }
exit/b
:a
set m=%m%0
echo  ^|^| %m%L%1

Edit: Saved 22 bytes by avoiding repeating input == and reusing the subroutine for the line with the extra semicolon. Saved 2 3 bytes by removing unnecessary spaces.


Do you need spaces around ==?
Pavel

@Pavel That's not code; it's part of the output.
Dennis
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.