Нули в интервале

14

Ваша задача - написать функцию или программу, которая берет два неотрицательных целых числа iи k( ik), и выяснить, сколько нулей вы бы написали, если бы вы написали все целые числа от iдо k(включительно) в вашей базе выбора на кусочке бумаги. Выведите это целое число, число нулей, в стандартный вывод или тому подобное.

-30%если вы также принимаете третий аргумент b, целочисленная база для записи чисел. Для получения этого бонуса необходимо обработать как минимум две базы.

  • Вы можете принять ввод в любой базе, которая вам нравится, и вы можете изменить базу между тестовыми примерами.
  • Вы можете принять аргументы i, kи , возможно , bв любом порядке.
  • Ответы должны обрабатывать хотя бы одну не одинарную базу.

Тестовые случаи (в базе 10):

i k -> output
10 10 -> 1
0 27 -> 3
100 200 -> 22
0 500 -> 92

Это код-гольф; Наименьшее количество байтов побеждает.

Филип Хаглунд
источник
2
Если вы можете использовать любую базу, какую захотите, от случая к случаю, не могли бы вы сделать каждую в базе k и вывести 0 или 1, в зависимости от того, i = 0?
StephenTG
4
Возможно, вы захотите исключить унарное в качестве базы, иначе эта проблема тривиальна: получите входные данные, напечатайте 0.
Mego
Можете ли вы добавить несколько тестов для других баз?
Морган Трепп
3
Я думаю, что это было бы более интересно, если бы требовался базовый аргумент. «База на ваш выбор» странная для меня.
Алекс А.
1
Да, @AlexA. но слишком поздно, чтобы изменить это сейчас, 10 ответов.
Филип Хаглунд

Ответы:

17

Желе, 1 байт

¬

Это использует базу k+2, в этом случае есть один 0, еслиi равен 0. Он принимает два аргумента, но применяет логическое NOT только к первому.

Если мы не хотим обманывать:

7 байтов - 30% = 4,9

-1,1 очка @Dennis

rb⁵$¬SS

Это получает бонус.

             dyadic link:
r            inclusive range
 b⁵$           Convert all to base input.
    ¬          Vectorized logical NOT
     S         Sum up 0th digits, 1st digits, etc.
      S        Sum all values
lirtosiast
источник
7
Это вторая программа Jelly, которую я написал на своем телефоне.
lirtosiast
13
Блин, 1 байт? Дайте нам шанс.
Rɪᴋᴇʀ
2
Это можно легко сделать за несколько байт на любом другом языке. Я говорю придерживайтесь не читерской версии.
ETHproductions
13
@ETHproductions Правила вопроса явно позволяют это делать. Обман или нет, это ответ, который требуют правила.
Деннис
8

Python 2, 36 байт

lambda a,b:`range(a,b+1)`.count('0')

Кредит muddyfish для `` трюк.

Dantal
источник
1
Добро пожаловать в Программирование Пазлов и Code Golf! Это хороший первый ответ. :)
Алекс А.
Вот это да! Я не знал, что это работает!
Дантал
6

05AB1E , 3 1 байт

Использует базу k+2как ответ желе, код:

_

Объяснение:

_  # Logical NOT operator

3-байтовая версия без читов:

Код:

Ÿ0¢

Объяснение:

Ÿ    # Inclusive range
 0¢  # Count zeroes

Бонус дает мне 3,5 байта из-за ошибки:

ŸB)0¢

Объяснение:

Ÿ      # Inclusive range
 B     # Convert to base input
  )    # Wrap into an array (which should not be needed)
   0¢  # Count zeroes

Использует кодировку CP-1252.

Аднан
источник
Как это работает?
lirtosiast
@ThomasKwa Объяснение добавлено
Аднан
5

Japt, 3 байта

+!U

Использует базу k+2, как желе ответ. Есть ноль, еслиi==0 . Проверьте это онлайн!

Лучшая версия, 10 8 байт

UòV ¬è'0

Этот использует базу 10. Проверьте это онлайн!

Бонусная версия, 14 12 байт - 30% = 8,4

UòV msW ¬è'0

К сожалению, с игрой в гольф, бонус больше не стоит ... Проверьте это онлайн!

Как это устроено

UòV msW ¬è'0   // Implicit: U = start int, V = end int, W = base
UòV            // Create the inclusive range [U..V].
    msW        // Map each item by turning it into a base-W string.
        ¬      // Join into a string.
         è'0   // Count the number of occurances of the string "0".
ETHproductions
источник
5

ES6, 91 86 - 30% = 60,2 байта

(i,k,b=10)=>([...Array(k+1-i)].map((_,n)=>(i+n).toString(b))+'0').match(/0/g).length-1

Или сохраните 3 (2.1) байта, если b не нужно по умолчанию 10.

Лучшая не бонусная версия, которую я мог сделать, была 65 байтов:

(i,k)=>([...Array(k+1).keys()].slice(i)+'0').match(/0/g).length-1

Редактировать: 5 байтов сохранены с помощью трюка с нулевым счетом @ edc65.

Нил
источник
Поскольку мне не удается получить голоса за мой ответ, я буду голосовать за вас (по крайней мере, там мое имя)
edc65
4

Серьезно, 10 байт

'0,,u@xεjc

Объяснение:

'0,,u@xεjc
'0,,u       push "0", i, k+1
     @x     swap i and k+1, range(i, k+1)
       εjc  join on empty string and count 0s

Попробуйте онлайн!

С бонусом: 11,9 байта

'0,,u@x,╗`╜@¡`Mεjc

Попробуйте онлайн!

Объяснение:

'0,,u@x,╗`╜@¡`MΣc
'0,,u@x             push "0", range(i, k+1)
       ,╗           push b to register 0
         `   `M     map:
          ╜@¡         push b, push string of a written in base b
               Σc   sum (concat for strings), count 0s
Mego
источник
3

CJam, 12 10 3 байта

li!

Это использует ярлык @ThomasKwa делает.

Если это не разрешено, то вот 10-байтовый ответ.

q~),>s'0e=

Хороший и короткий! Работает как Серьезный ответ @ Mego.

Спасибо @Dennis!

Было весело писать мой первый ответ CJam!

Попробуй это здесь!

TanMath
источник
3

T-SQL, 394 байта (без бонуса)

Я понимаю , почему нет , верно?

DECLARE @i INT, @k INT SET @i = 100 SET @k = 200  WITH g AS (SELECT @i AS n UNION ALL SELECT n+1 FROM g WHERE n+1<=@k ) SELECT LEN(n) AS c FROM (SELECT STUFF((SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(n, 1, ''), 2, ''), 3, ''), 4, ''), 5, ''), 6, ''), 7, ''), 8, ''), 9, ''), ' ', '') FROM g FOR XML PATH ('')) ,1,0,'') n ) a OPTION (maxrecursion 0)

И дружелюбный

-- CG!

DECLARE @i INT, @k INT 
SET @i = 100
SET @k = 200

WITH g AS 
(
    SELECT @i AS n
    UNION ALL
    SELECT n+1 FROM g WHERE n+1<=@k
)

SELECT LEN(n) AS c FROM 
(
    SELECT 
        STUFF((SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(n, 1, ''), 2, ''), 3, ''), 4, ''), 5, ''), 6, ''), 7, ''), 8, ''), 9, ''), ' ', '')
FROM g FOR XML PATH ('')) ,1,0,'') n
) a

OPTION (maxrecursion 0)
Nelz
источник
это преданность
colsw
3

Рубин, 46 - 30% = 32,2 байта

Возможно, вы могли бы играть в гольф больше, но по крайней мере я получаю 30% бонус!

->i,k,b{((i..k).map{|a|a.to_s b}*"").count ?0}

... или без бонуса (27 байт.)

->i,k{([*i..k]*"").count ?0}

Советы приветствуются, все еще изучая всю эту вещь "Рубин".

snail_
источник
Хороший ответ, вам не нужен оператор splat при использовании map, это может сэкономить 1 байт. (i..k)так же хорошо, как [*i..k]в первом случае.
GB
2

Брахилог , 26 байт

,{,.e?}?:1frcS:0xlI,Sl-I=.

Принимает ввод в виде списка [i,k].

объяснение

,{    }?:1f                § Unify the output with a list of all inputs which verify the
                           § predicate between brackets {...} with output set as the input
                           § of the main predicate

  ,.e?                     § Unify the input with a number between i and k with the ouput
                           § being the list [i,k]

           rcS             § Reverse the list and concatenate everything into a single
                           § number (we reverse it to not lose the leading 0 if i = 0 when
                           § we concatenate into a single number). Call this number S.

              :0xlI        § Remove all occurences of 0 from S, call I the length of this new
                           § number with no zeros

                   ,Sl-I=. § Output the length of S minus I.
Fatalize
источник
2

Юля, 48 байтов - 30% = 33,6

f(i,k,b)=sum(j->sum(c->c<49,[base(b,j)...]),i:k)

Это функция, которая принимает три целых числа и возвращает целое число. Один из аргументов указывает базу, так что это дает право на бонус.

Ungolfed:

function f(i, k, b)
    # For each j in the inclusive range i to k, convert j to base
    # b as a string, splat the string into a character array, and
    # compare each character to the ASCII code 49 (i.e. '1'). The
    # condition will only be true if the character is '0'. We sum
    # these booleans to get the number of zeros in that number,
    # then we sum over the set of sums to get the result.
    sum(j -> sum(c -> c < 49, [base(b, j)...]), i:k)
end

Реализация бонуса дает балл чуть лучше, чем не реализация (34 байта):

f(i,k)=sum(c->c<49,[join(i:k)...])
Alex A.
источник
2

Seriously, 2 bytes

This might be taking the Jelly answer trick to the limit, but here is a simple 2 byte Seriously answer.

,Y

Try it online!

TanMath
источник
2

Pyth, 6.3 bytes, with bonus (9 bytes - 30%)

/sjRQ}EE0

Explanation:

  jRQ     - [conv_base(Q, d) for d in V]
     }EE  - inclusive_range(eval(input), eval(input))
 s        - sum(^, [])
/       0 - ^.count(0)

Try it here

Or 7 bytes without the bonus:

/`}EE\0

Explanation:

  }EE   - inclusive_range(eval(input), eval(input))
 `      - repr(^)
/    \0 - ^.count("0")

Try it here

Or use a test suite

Blue
источник
I think getting the bonus is worth it: /sjRQ}EE0
FryAmTheEggman
Ehh, it's the same code with a base conversion, I'm pretty sure you know what you're doing, just the problem of a bonus forcing you to try different stuff and count... :P
FryAmTheEggman
2

PHP, 50 Bytes

supports decimal only

<?=substr_count(join(range($argv[1],$argv[2])),0);

supports decimal and binary with Bonus 63

<?=substr_count(join(array_map([2=>decbin,10=>""][$argv[3]],range($argv[1],$argv[2]))),0);

supports decimal,hexadecimal, octal and binary with Bonus 77.7

<?=substr_count(join(array_map([2=>decbin,8=>decoct,10=>"",16=>dechex][$argv[3]],range($argv[1],$argv[2]))),0);

supports base 2 - 36 with Bonus 78.4

<?=substr_count(join(array_map(function($i){return base_convert($i,10,$_GET[2]);},range($_GET[0],$_GET[1]))),0);
Jörg Hülsermann
источник
Nice collection! Care to do a version 3a including base 64? :D
Titus
@Titus How is the order of base 64? Why not en.wikipedia.org/wiki/Ascii85 or make a little more with all printable ascii chars
Jörg Hülsermann
2

JavaScript (ES6), 50 (71 - 30%)

(n,k,b)=>eval("for(o=0;n<=k;++n)o+=n.toString(b)").match(/0/g).length-1

No bonus, base k+2 is 10 bytes (i,k)=>+!i

No bonus, unary is 8 bytes (i,k)=>0

TEST

f=(n,k,b)=>eval("for(o=0;n<=k;++n)o+=n.toString(b)").match(/0/g).length-1

function go() {
  var i=I.value.match(/\d+/g)
  R.textContent = f(i[0],i[1],i[2])
}

go()
i,k,b:<input id=I value='0,500,10' oninput="go()">
<span id=R></span>

edc65
источник
If you move the o='0' before the loop your code continues to work even when k<i.
Neil
@Neil nice, but the spec says (i ≤ k). Update I tried this but in fact it does not work for k<i
edc65
Well, it worked for me (and I know the spec guarantees that i <= k, but your code crashes when k < i; by comparison my code only crashes when k < i - 1 !)
Neil
@Neil uh ok now I get it. It does not give a sensible answer but at least does not crash
edc65
1
@ForcentVintier anyway after your input I revised the code saving some bytes
edc65
1

Jolf, 7 bytes

Replace with \x11. Try it here!

Zl♂sjJ0
   sjJ  inclusive range between two numeric inputs
  ♂      chopped into single-length elements
Zl    0  and count the number of zeroes
        implicitly printed
Conor O'Brien
источник
1

Lua 74 bytes

z,c=io.read,""for a=z(),z()do c=c..a end o,b=string.gsub(c,"0","")print(b)

There's gotta be a more effective way to do this...

I thought I was really onto something here:

c,m,z=0,math,io.read for a=z(),1+z()do c=c+((m.floor(a/10))%10==0 and 1 or a%100==0 and 1 or a%10==0 and 1 or 0) end print(c)

But alas... It keeps getting longer and longer as I realize there's more and more zeroes I forgot about...

Skyl3r
источник
1

APL, 22 bytes

{+/'0'⍷∊0⍕¨(⍺-1)↓⍳⍵}

This is a monadic function that accepts the range boundaries on the left and right and returns an integer.

Ungolfed:

           (⍺-1)↓⍳⍵}  ⍝ Construct the range ⍺..⍵ by dropping the first
                      ⍝ ⍺-1 values in the range 1..⍵
       ∊0⍕¨           ⍝ Convert each number to a string
{+/'0'⍷               ⍝ Count the occurrences of '0' in the string

Try it here

Alex A.
источник
1

Haskell, 29 bytes

i#k=sum[1|'0'<-show=<<[i..k]]

I'm using base 10.

Usage example: 100 # 200 -> 22

How it works: turn each element in the list from i to k into it's string representation, concatenate into a single string, take a 1 for every char '0' and sum those 1s.

nimi
источник
1

MATL, 7 (10 bytes − 30% bonus)

2$:i:qYA~z

Try it online!

This works in release 11.0.2, which is earlier than this challenge.

Explanation

2$:      % implicitly input two numbers and generate inclusive range
i:q      % input base b and generate vector [0,1,...,b-1]
YA       % convert range to base b using symbols 0,1,...,b-1. Gives 2D array
~        % logical negation. Zeros become 1, rest of symbols become 0
z        % number of nonzero elements in array
Luis Mendo
источник
1

Matlab: 27 bytes

@(q,w)nnz(num2str(q:w)==48)

creates a vector from lower number to larger one, then converts all numbers to string and counts all the '0' symbols.

brainkz
источник
1

Python 3, 52.

Tried to implement the bonus, but it doesn't seem to be worth it.

lambda a,b:''.join(map(str,range(a,b+1))).count('0')

With test cases:

assert f(10, 10) == 1
assert f(0, 27) == 3
assert f(100, 200) == 22
assert f(0, 500) == 92
Morgan Thrapp
источник
1
I literally never heard about the assert statement before this comment. Thanks mate!
sagiksp
1

Perl 6, 23 bytes

{+($^i..$^k).comb(/0/)}
  1. creates a Range ( $^i..$^k )
  2. joins the values with spaces implicitly ( .comb is a Str method )
  3. creates a list of just the zeros ( .comb(/0/) )
  4. returns the number of elems in that list ( + )

Usage:

my &zero-count = {…}

for (10,10), (0,27), (100,200), (0,500), (0,100000) {
  say zero-count |@_
}
1
3
22
92
38895
Brad Gilbert b2gills
источник
You know, that comment at the end of your code makes it seem longer...
ETHproductions
@ETHproductions I usually do that so that if I come up with more than one way to do things that I can see if it is shorter than others. I just keep adding more ways to do it until I come up with what I think is the shortest way.
Brad Gilbert b2gills
1

Mathematica, 39 bytes, 27.3 with bonus

Count[#~Range~#2~IntegerDigits~#3,0,2]&
A Simmons
источник
1

C# 112 Bytes

int z(int i,int k)=>String.Join("",Enumerable.Range(i,k-i+1)).Count(c=>c=='0')
  1. Create a string with numbers from the first number up to the last number
  2. Count the zero characters in the string
lee
источник
Welcome to PPCG! I'm not super familiar with C# but I think you could probably save a few bytes if you removed some of the spaces.
0 '
thank you 0, you are right but only a couple bytes. I believe my edited answer removes all the spaces I can. :)
lee
1

PHP, 84 bytes *.7=58.8 (bases 2 to 36)

for(;($v=$argv)[2]>$a=$v[1]++;)$n+=substr_count(base_convert($a,10,$v[3]),0);echo$n;

or

for(;($v=$argv)[2]>$v[1];)$n+=substr_count(base_convert($v[1]++,10,$v[3]),0);echo$n;

takes decimal input from command line arguments; run with -r.

Titus
источник
For fun: <?=0 supports unary and alphabetic. ;)
Titus
1

PowerShell, 56 54 51 48 42 bytes

param($i,$k)(-join($i..$k)-split0).count-1

Takes input, creates a range with $i..$k then -joins that together into a string, followed by a regex -split command that separates the string into an array by slicing at the 0s. We encapsulate that with ().count-1 to measure how many zeros. That's left on the pipeline, and output is implicit.

Saved 6 bytes thanks to @ConnorLSW

Try it online!


Base-handling in PowerShell is limited and doesn't support arbitrary bases, so I'm not going for the bonus.

AdmBorkBork
источник
param($i,$k)(-join($i..$k)-split'0').Length-1 works for me, -3, or use .Count-1 to save even more, haven't tested that yet though.
colsw
@ConnorLSW Thanks! Don't need the quotes around '0', so that trimmed off a few more.
AdmBorkBork
nice one, I always forget powershell handles numbers like that.
colsw
0

Java 8, 102 bytes - 30% = 71.4

Why not.

(i,k,b)->{int j=0;for(;i<=k;i++)for(char c:Integer.toString(i,b).toCharArray())if(c==48)j++;return j;}

Without the bonus, 96 bytes (so the bonus actually improves my score!):

(i,k)->{int j=0;for(;i<=k;i++)for(char c:String.valueOf(i).toCharArray())if(c==48)j++;return j;}

This implements the following:

interface Function {
    public int apply(int i, int k, int b);
}
HyperNeutrino
источник
@mbomb007 The problem is that formatting it this way renders the answer as 102 bytes on the Leaderboard in the question.
HyperNeutrino
That's a flaw with the leaderboard, not the post. Look at how most of the other answers are doing it the same way.
mbomb007
@mbomb007 I'm looking at the answers and I see a ton of different formats, some of which work with the leaderboard, some of which don't.
HyperNeutrino
0

Clojure, 50 49 bytes

#(count(re-seq #"0"(apply str(range %(inc %2)))))

Oh regex is shorter than filtering. Original:

#(count(filter #{\0}(apply str(range %(inc %2)))))

Very basic, uses the set of character \0 to remove others and counts how many were found.

NikoNyrh
источник