Провідний нульовий виклик


31

Змагання

З урахуванням двох цілих чисел як введення ( xі y), виведіть xу вигляді рядка з стільки необхідних нульових нулів, як це потрібноy довгими символами без знака.

Правила

  • Якщо xмає більше yцифр, виведіть xяк рядок без змін.

  • Виведення як ціле число не приймається, навіть якщо немає провідних нулів.

  • Коли xце негативно, зберігайте- як є, і дійте на абсолютне значення.

  • До негативних yслід ставитися як до 0, тобто ви отримуєте висновокx як є (але як рядок)

Приклади:

IN: (1,1)   OUT: "1"
IN: (1,2)   OUT: "01"
IN: (10,1)  OUT: "10"
IN: (-7,3)  OUT: "-007"
IN: (-1,1)  OUT: "-1"
IN: (10,-1) OUT: "10"
IN: (0,0)   OUT: "0"
IN: (0,1)   OUT: "0"
IN: (0,4)   OUT: "0000"

Найкоротший код у байтах виграє, застосовуються стандартні лазівки.



1
Чи можу я взяти x як рядок?
LiefdeWen

що (-1,1)дає?
Adám

@ Adám додав це до прикладів.
Брайан Х.

1
Чи +прийнятний провідний знак для додатних чисел?
Том Карпентер

Відповіді:


4

Japt, 13 8 bytes

Takes first input (x) as a string.

®©ùTV}'-

Try it

Saved a massive 5 bytes thanks to ETHproductions.


Explanation

Implicit input of string U=x and integer V=y.

® }'- splits U to an array on the minus symbol, maps over it and rejoins it to a string with a minus symbol.

© is logical AND (&&) so if the current element is truthy (a non-empty string) then pad left (ù) with 0 (T) to length V.


Nice one! You can save quite a bit by simply mapping around -: ethproductions.github.io/japt/…
ETHproductions

@ETHproductions: Great call. Thanks. Been so long since I've done so, I'd completely forgotten you can split, map and rejoin a string all in one method!
Shaggy

Yes, I suppose that functionality should be moved to q, which would then be q-_©ùTV to save 1 byte :-)
ETHproductions

@ETHproductions, if I'm understanding that right, you're suggesting that if a function is passed as a second argument of S.q() (giving us S.q(s,f)) then S would be split on s, run through f and rejoined with s? I like it! :)
Shaggy

Yeah, did I talk to Oliver and not you about doing that (if passed a function, do the normal functionality, run through the function, and undo the first change; N.s, S/A.y, N.ì do this already) with a bunch of methods? I had a conversation with someone, I just can't remember who now :s
ETHproductions



6

05AB1E, 11 10 bytes

Input given as amount_of_digits, number

ÎIÄg-×ì'-†

Try it online!

Explanation

Î            # push 0 and first input
 IÄ          # push the absolute value of the second input
   g         # length
    -        # subtract, (input1-len(abs(input2))
     ×       # repeat the zero that many times
      ì      # prepend to the second input
       '-†   # move any "-" to the front

Seems like this is the winning answer so far, if not bettered tomorrow i'll accept it.
Brian H.

you've been outgolfed :(
Brian H.

@BrianH. Indeed I have :)
Emigna




5

JavaScript (ES6), 42

Recursive, parameters in reverse order, first y then x. And Currying

y=>r=x=>x<0?'-'+r(-x):`${x}`.padStart(y,0)

Test

var F=
y=>r=x=>x<0?'-'+r(-x):`${x}`.padStart(y,0)

;`IN: (1,1)   OUT: "1"
IN: (1,2)   OUT: "01"
IN: (10,1)  OUT: "10"
IN: (-7,3)  OUT: "-007"
IN: (-1,1)  OUT: "-1"
IN: (10,-1) OUT: "10"
IN: (0,0)   OUT: "0"
IN: (0,1)   OUT: "0"
IN: (0,4)   OUT: "0000"`
.split(`\n`).map(r => r.match(/[-\d]+/g))
.forEach(([x,y,k])=>{
  o = F(y)(x)
  ok = o == k
  console.log(ok?'OK':'KO',x,y,'->', o)
})


While impressive, I feel this answer skirts the rules slightly by defining the function f(y)(x) instead of f(x,y).
styletron

Reading up on the "currying" rules, I wanted to add that my objection was more with the reversed params and not with the currying itself.
styletron

1
@styletron the order of the parameters is not specified in the challenge. So I can take advantage of this
edc65

Dang, y=>r=x=>x<0?'-'+r(-x):(x+='')[y-1]?x:r(0+x) comes so close...
ETHproductions

i have no issues with people reversing the input order.
Brian H.



5

Husk, 12 bytes

Ö±Ωo≥⁰#±:'0s

Try it online!

Explanation

Ö±Ωo≥⁰#±:'0s  Inputs are y=4 and x=-20
           s  Convert x to string: "-20"
        :'0   Prepend '0'
  Ω           until
      #±      the number of digits
   o≥⁰        is at least y: "00-20"
Ö±            Sort by is-digit: "-0020"
              Print implicitly.

5

R, 56 48 bytes

function(x,y)sprintf(paste0("%0",y+(x<0),"d"),x)

Try it online!

-8 bytes thanks to djhurio

Explanation

  • sprintf("%0zd",x) returns x as a string padded with zeros to be of length z
  • paste0("%0",y+(x<0),"d") constructs the string "%0zd", where z is y, plus 1 if x is less than zero
  • If z is less than the number of digits in x, x is printed as a string as is

48 bytes function(x,y)sprintf(paste0("%0",y+(x<0),"d"),x)
djhurio

@djhurio brilliant! I think that would warrant another answer rather than an edit of mine, what do you say?
duckmayr

You can make it as an edit. This solution is not so much different, just using different function.
djhurio

4

Alice, 23 bytes

/oRe./'+Ao
\I*tI&0-R$@/

Try it online!

Input should be linefeed-separated with the number on the first line and the width on the second.

Explanation

/...
\...@/

This is the usual framework for linear programs in Ordinal mode. The only catch in this case is this bit:

.../...
...&...

This causes the IP to enter Cardinal mode vertically and execute just the & in Cardinal mode before resuming in Ordinal mode.

Unfolding the zigzag control flow then gives:

IRt.&'-A$o*eI/&/0+Ro@

I    Read the first line of input (the value) as a string.
R    Reverse the string.
t.   Split off the last character and duplicate it.
&    Fold the next command over this string. This doesn't really do anything,
     because the string contains only one character (so folding the next
     command is identical to executing it normally).
'-   Push "-".
A    Set intersection. Gives "-" for negative inputs and "" otherwise.
$o   If it's "-", print it, otherwise it must have been a digit which we
     leave on the stack.
*    Join the digit back onto the number. If the number was negative, this
     joins the (absolute value of the) number to an implicit empty string,
     doing nothing.
e    Push an empty string.
I    Read the width W.
/&/  Iterate the next command W times.
0    Append a zero. So we get a string of W zeros on top of the absolute
     value of the input number.
+    Superimpose. This takes the character-wise maximum of both strings
     and appends extraneous characters from the longer string. Since the
     string of zeros can never be larger than the digits in the input,
     the input itself will be uneffected, but extraneous zeros are appended,
     padding the string to the required length.
R    Reverse the result.
o    Print it.
@    Terminate the program.

Here are two alternatives, also at 23 bytes, which use Cardinal H (abs) to get rid of the -:

/R.I&0-RoH
\Ie#\'+Ao\@/

/R.H#/.+Xo
\Ie\I&0QRo@/

In principle, these are a command shorter, but the & doesn't fit into a position where there's a 1-character string on the stack, so we need to skip it with a #.



4

Charcoal, 16 13 bytes

‹N⁰﹪⁺⁺%0ηd↔Iθ

Try it online!

This is the shortest I could get using Charcoal without printing leading or trailing whitespaces. At least I am now starting to understand how to use the Modulo function to format strings.

The deverbosed code is as follows:

Print(Less(InputNumber(),0));    # Prints a - if the first input is less than 0
Print(Modulo(Add(Add("%0",h),"d"),Abs(Cast(q))));   # q: first input;  h: second input
  • 3 bytes saved thanks to Neil!

1
To print - or nothing is really easy in Charcoal: Printing 1 prints - while printing 0 prints nothing. So, the ternary is superfluous, saving 3 bytes.
Neil

If you swap the InputNumber() with the Cast(q), I think you can then switch to a string comparison to save another byte.
Neil

@Neil I knew that I could simplify the Ternary!
Charlie


4

PHP, 45 bytes

printf("%0".($argv[2]+(0>$n=$argv[1])).d,$n);

or

[,$n,$e]=$argv;printf("%0".($e+(0>$n)).d,$n);       # requires PHP 7.1 or later

Run with -nr or try them online.


Getting an error when executing the code in that link.
Shaggy

@Shaggy The second version requires PHP 7.1
Titus

I went on and on about this, and I arrived to exactly this answer. I believe this is the optimal version
Ismael Miguel


3

Mathematica, 63 62 bytes

If[#<0,"-",""]<>IntegerString[#,10,Max[#2,IntegerLength@#,1]]&

Try it online!


2
Welcome to PPCG! I think this isn't quite doing what you want. You probably meant IntegerLength instead of IntegerDigits. You can save a byte by using IntegerLength@# instead of IntegerLength[#] though.
Martin Ender

Thank you! I was copying the code from another computer by hand where I was testing it and I indeed mistyped IntegerDigits for IntegerLength. It should work now. I have also added a TIO link with all the test cases in the challenge description (+1) showing that it works as expected. Thank you also for the suggestion for saving an extra byte! I don't know how I missed it before. :)
MatjazGo

2

Excel, 29 bytes

Using Excel's TEXT functionality ("Converts a value to text in a specific number format").

x in A1, y in B1

=TEXT(A1,REPT("0",MAX(1,B1)))

You can drop the ))) for -3 Bytes by converting to Google Sheets
Taylor Scott




2

Japt, 14 12 bytes

Saved 2 bytes thanks to @ETHproductions

s r"%d+"_ù0V

Try it online


It's a bit cheaper to keep the minus sign in and just mess with the digits: Test it online
ETHproductions

@ETHproductions: Or take x as a string for 10 bytes.
Shaggy

@ETHproductions thanks fellas. I'll update it when I get back to my desk.
Oliver

@Shaggy Looks like you posted your own answer, so I'll use ETHproduction's trick. Thanks though.
Oliver

Oliver, that 10-byter is just @ETHproduction's 12-byte solution upgraded to Japt 2.0a0 with U as a string allowing us to golf off the first 2 characters.
Shaggy

2

PowerShell, 25 40 bytes

param($a,$b)$a|% *g $("D$b"*($b|% *o 0))

Try it online!

Explanation

This calls .ToString() on the number with a generated format string, but multiplies it by -1, 0, or 1 based on whether $b (y) is negative, 0, or positive respectively; this is to handle negative y values which format strings don't by themselves.

This seems to require wrapping negative numbers in a substatement () for it to work which is just a quirk of the invocation when using literals; if passed variables of type integer, it would not need that.


It looks like both of these fail when y is negative.
Shaggy

@Shaggy ugh good catch. Removed second solution altogether and fixed up the first, thanks!
briantist

Ouch, 15 bytes! Sorry!
Shaggy

@Shaggy heh, one of these days I'll actually write the PowerShell-based golfing language I've been thinking about. This actually pushed me to research a bit more and get closer to starting it, so thanks for that ;)
briantist

2

C# 6.0, 35 bytes

(x,y)=>(x.ToString($"D{y<0?0:y}"));

Alternative solution (51 bytes)

(x,y)=>(x.ToString(string.Format("D{0}",y<0?0:y)));


1

C (gcc), 45 bytes

f(x,y){printf("%s%0*i","-"+(x>=0),y,abs(x));}

Try it online!

Explanation

printf formats three arguments:

%s      ->    "-"+(x>=0)
%0*i    ->    y
        ->    abs(x)

%s formats the string "-"+(x>=0). "-" is really just an address, something like 41961441. In memory, this looks something like this:

MEMORY ADDRESS | 41961441  41961442 ...
VALUE          | 45 ('-')  0 (0x00) ...

When formatted into a string, C takes the address (say 41961441) and keeps on acquiring characters until a null byte (0x00) is met. When x is less than zero, the value "-"+(x>=0) has that of the original address (41961441). Otherwise, x>=0 is 1, so the expression becomes "-"+1, which points the null byte after "-", which prints nothing.

%0*i prints an integer padded with a specified number of 0s. y denotes this number. We pad abs(x) to avoid the negative in some arguments.



Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.