我如何最终得到这个FizzBu​​zz?


21

FizzBu​​zz非常简单,您可以向后退。在此挑战中,将为您提供FizzBu​​zz字符串的长度,并且必须提供产生该字符串的正整数。

描述

为了解决这个问题,n以下算法生成了一个FizzBu​​zz字符串。

以一个空字符串开头,对于每个i=1..n(包括):

  1. 如果i3和整除5,则追加FizzBuzz到字符串。
  2. 如果i只是被3追加整除Fizz
  3. 如果i只是被5追加整除Buzz
  4. 如果不能i被整除,请附加的十进制表示形式i

因此,例如FizzBuzz(15)以下内容:

12Fizz4BuzzFizz78FizzBuzz11Fizz1314FizzBuzz

您将被给予Length(FizzBuzz(n))并且必须确定n。您可以假设输入为正,并且始终为某些FizzBu​​zz字符串的长度。

规则

您的解决方案可以是任何标准可接受语言的完整程序或功能定义。您的程序/函数可以接受参数并以任何标准接受的方式返回答案。禁止出现标准漏洞。

您可能会假设输入是肯定有效的(描述了某些FizzBu​​zz字符串的长度),并且小于您语言中本机可表示的最大整数。

这是代码高尔夫,因此最短的字节数获胜。

例子

这是一些例子

Length(FizzBuzz(n)) -> n
1                   -> 1
6                   -> 3
15                  -> 6
313                 -> 100
3677                -> 1001

编辑

修复了最后一个测试用例。谢谢@SteadyBox。


啊!我尝试进行递归,但是我的数字太大...
0WJYxW9FMN17年


3
@Toto这是怎么重复的?
AdmBorkBork '17

1
@Toto根本不是重复的。也许您应该阅读重复的含义。
mbomb007 '17

Answers:


8

果冻 16  14 字节

2个字节使用较新的语言功能保存)µ€Ä+\

3,5ḍS×4oDL$)Äi

在线尝试!或查看测试用例

怎么样?

建立从1输入到输入的每个项目的长度的列表,通过加法来减少长度,然后在列表中找到输入的基于一的索引。(这也意味着输入无效,结果为0“不在列表中”)。

3,5ḍS×4oDL$)Äi - Main link: theLength
           )    - perform the chain to the left for each (€) in
                     implicit range from 1 to the input and
                     pass the result into the monadic chain (µ) to the right
3,5            - 3 paired with 5: [3,5]
   ḍ           - divides?  for a multiple of 15 [1,1]; sum = 2; times 4 = 8
    S          - sum       for a multiple of  5 [0,1]; sum = 1; times 4 = 4
     ×4        - times 4   for a multiple of  3 [1,0]; sum = 1; times 4 = 4
                           for none of those    [0,0]; sum = 0; times 4 = 0
          $    - last two links as a monad
        D      -     to decimal digit list
         L     -     length - e.g. 313 -> [3,1,3] -> 3
       o       - logical or: replace a 0 with the decimal length, keep the 4s and 8s
            Ä  - reduce with addition: e.g. [1,1,4,1, 4, 4, 1, 1, 4, 4, 2, 4, 2 ,2, 8]
                                         -> [1,2,6,7,11,15,16,17,21,25,27,31,33,35,43]
             i - index of theLength in that list (e.g. 15 is at index 6)

11

C,81 78字节

l,i;f(n){for(l=i=0;l<n;l+=++i%3?i%5?snprintf(0,0,"%d",i):4:i%5?4:8);return i;}

68个字节(如果您不介意double来回转换):

l,i;f(n){for(l=i=0;l<n;l+=++i%3?i%5?log10(i)+1:4:i%5?4:8);return i;}

当“ i”是全局变量时,是否还需要“返回i”?-)如果可以编译并允许,则可以将长的snprintf调用替换为log10(i)+1,它对我有用gcc -lm
Rennex '17

@Rennex return i;是必需的,因为这是在代码高尔夫中输出的一种标准接受方式,而无需修改全局变量。我考虑过使用log10(i)+1,但是我认为这可能会引起一些问题,因为转换为double并返回(例如,pow(i)使用整数不可靠)。现在看来,尽管它对于an int可以代表的所有正值都可以正常工作,所以我可能会使用它。(值大于简单值int可以容纳的值,有时确实会失败,但这并不重要。)
Steadybox

嗯。。好。我是本代码的新手,但是我看了问题中的规则链接,并说“功能可以通过修改参数或写出参数来输出”。这是否意味着至少可以使用结果指针参数?
Rennex

@Rennex是的,我想我可以将nin作为指针,然后只修改最后指向的值,但这会在调用站点上需要更多代码才能打印该值,因此感觉有点像骗我。
Steadybox

6

MATL31 28 27字节

`@:tI5h!\XJA)VXznJ~z4*+G-}@

在线尝试!

说明

`        % Do...while
  @:     %   Push array [1 2 ...k], where k is iteration index
  t      %   Duplicate  
  I5h!   %   Push column vector [3; 5]
  \      %   Modulo, with broadcast. Gives 2 × k matrix
  XJ     %   Copy into clipboard J
  A      %   Row vector that contains true for columns that contain two nonzeros
  )      %   Index with that vector. This keeps numbers that are non-fizz/buzz
  V      %   Convert to string. This inserts spaces between numbers
  Xzn    %   Number of nonspace characters
  J      %   Push 2 × k matrix resulting from modulo operation again
  ~z     %   Number of zeros
  4*     %   Multiply by 4. Gives number of characters corresponding to fizz/buzz
  +      %   Add
  G-     %   Subtract input. This is the loop condition: exit if 0
}        % Finally (execute right before exiting loop)
  @      %   Push current iteration index
         % End (implicit)
         % Display (implicit)

4

Mathematica,67个字节

(For[n=s=0,s<#,s+=Tr[4Boole[{3,5}∣++n]]/. 0:>IntegerLength@n];n)&

这比我最初的解决方案更快,更短:

1//.x_/;Sum[Tr[4Boole[{3,5}∣n]]/. 0:>IntegerLength@n,{n,x}]!=#:>x+1&

或我不顾一切地试图缩短它:

(s=0;1)//.x_/;(s+=Tr[4Boole[{3,5}∣x]]/. 0:>IntegerLength@x)!=#:>x+1&

说明

标准For循环递增n直到s := Length(FizzBuzz(n))至少与输入相等#。唯一有趣的一点是我如何计算(n+1)FizzBu​​zz序列的-th项的长度

                ++n                           Preincrement n
          {3,5}∣                              Test for divisibility by 3 and 5 (returns a list)
    Boole[         ]                          Convert True to 1 and False to 0
   4                                          Multiply by 4
Tr[                 ]                         Sum
                     /.                       Replace
                        0                     0 (leading space is necessary or it thinks we are dividing by 0.0)
                         :>                   with
                           IntegerLength@n    the number of digits in n

3

MATL,31 30 28字节

:tI5h!\~s4*t~b10&YlkQ*+YsG=f

使用与Jonathan Allen的Jelly解决方案相同的想法。

matl.suever.net上尝试一下!


现在降至28!:-PI认为我们的方法现在更加相似
Luis Mendo

啊,干得好!是的,看起来像:)
B. Mehta

3

爪哇8,100个 97字节

打高尔夫球:

l->{int i=0;for(String s="";s.length()<l;)s+=++i%15<1?"12345678":i%5<1||i%3<1?"1234":i;return i;}

取消高尔夫:

import java.util.function.*;

public class HowDidIEndUpWithThisFizzBuzz {

  public static void main(String[] args) {
    for (final int[] data : new int[][] { { 1, 1 }, { 6, 3 }, { 15, 6 },
        { 313, 100 }, { 3677, 1001 } }) {
      final int fizzBuzzLength = data[0];
      final int expected = data[1];
      final int actual = f(l -> {
        int i = 0;
        for (String s = ""; s.length() < l;) {
          s += (++i % 15 < 1 ? "12345678" : (i % 5 < 1 || i % 3 < 1 ? "1234" : i));
        }
        return i;
      } , fizzBuzzLength);
      System.out.println("Length(FizzBuzz(n)) -> " + fizzBuzzLength);
      System.out.println("Expected            -> " + expected);
      System.out.println("Actual              -> " + actual);
      System.out.println();
    }

  }

  private static int f(IntFunction<Integer> function, int fizzBuzzLength) {
    return function.apply(fizzBuzzLength);
  }
}

输出:

Length(FizzBuzz(n)) -> 1
Expected            -> 1
Actual              -> 1

Length(FizzBuzz(n)) -> 6
Expected            -> 3
Actual              -> 3

Length(FizzBuzz(n)) -> 15
Expected            -> 6
Actual              -> 6

Length(FizzBuzz(n)) -> 313
Expected            -> 100
Actual              -> 100

Length(FizzBuzz(n)) -> 3677
Expected            -> 1001
Actual              -> 1001

2

JavaScript(ES6),62 57字节

f=(n,k=0)=>n?f(n-(++k%3?k%5?`${k}`.length:4:k%5?4:8),k):k

测试用例


长度相同的替代表达式:(!(++k%3)+!(k%5)<<2||`${k}`.length)
尼尔

2

Javascript(ES6),56个字节

f=(x,s=i=0)=>s[x]?i:f(x,s+[++i%3?i%5?i:1e3:i%5?1e3:1e7])
<!-- snippet demo: -->
<input list=l oninput=console.log(f(this.value))>
<datalist id=l><option value=1><option value=6><option value=15><option value=313><option value=3677></datalist>


2

Python 3,78个字节

f=lambda i,n=1,s=0:~-n*(s==i)or f(i,n+1,s+(4*((n%3<1)+(n%5<1))or len(str(n))))

递归函数。任何高于1000的结果都将需要增加递归限制。

说明:

# i = length of final string
# n = current number in sequence, starting with 1
# s = length of current string, starting with 0
f=lambda i,n=1,s=0: \

# if s==1, this will evaluate to n+1, which is NOT 0, and will return
# else, it will evaluate to (n+1)*0, and trigger the second half of the OR clause
~-n*(s==i)or \

# recursively call the next iteration, with the next number in the sequence
f(i,n+1, \ 

# increase s by 4 if Fizz or Buzz, 8 if FizzBuzz, or len(n) if number
s+(4*((n%3<1)+(n%5<1))or len(str(n))))

1

Python,93个字节

def g(n,c=0,a=[4,0]):
 while n:c+=1;s=a[c%3>0]+a[c%5>0];s+=(s<1)*len(str(c));n-=s
 return c

1

k,33个字节

{1+&x=+\{(#$x;4;8)+/~3 5!'x}'1+!x}

简短的(python-ish)说明:

{                                } / function(x):
                             1+!x  /   array from 1 to x, inclusive
                            '      /   for y in array:
        {                  }       /     function(y):
         (#$x;4;8)                 /       yield [ len(str(y), 4, 8 ][
                  +/~3 5!'x        /         sum([not(y mod 3), not(y mod 5)])
                                   /       ]
      +\                           /   cumulative sum of result of for loop
 1+&x=                             /   get index of x in cumulative sum, add one

使用kmac 2016.06.28的示例:

 f:{1+&x=+\{(#$x;4;8)+/~3 5!'x}'1+!x}
 ,/f'1 6 15 313 3677
1 3 6 100 1001

欢迎来到编程难题和代码高尔夫球!众所周知,编辑答案时,社区用户自动投下了反对票。我认为这是一个错误
丹尼斯,


1

Ruby,69 66字节

->n{i=0;(i+=1;n-=i%3>0?i%5>0?i.to_s.size: 4:i%5>0?4:8)while n>0;i}

最初,我是避免嵌套三元运算符的怪异性,并减少到69个字节:

->n{i=0;(i+=1;n-=(x=[i%3,i%5].count 0)>0?4*x:i.to_s.size)while n>0;i}

1

Java 8,95 93字节

l->{int j=0,i=0;for(;j<l;)j+=++i%15<1?8:i%3<1||i%5<1?4:Math.floor(Math.log10(i)+1);return i;}

这是@Snowman答案的优化版本


在最后两个测试用例上,这为我返回了不正确的结果:75(而不是100)和686(而不是1001

1

Groovy,76个字节

def f(n){i=0;for(s='';s.size()<n;)s+=++i%15<1?"1"*8:i%5<1||i%3<1?"1"*4:i;i;}

基本上与@Snowman的答案相同,但是使用一些Groovy魔术/差异来减少字节数。


0

Perl 6的55 52个字节

{1+first $_,:k,[\+] map {4*($_%%3+$_%%5)||.chars},1..*}

{(0,{my \i=++$;$_+(4*(i%%3+i%%5)||i.chars)}...$_)-1}

在线尝试!

怎么运行的

{                                                  }  # A lambda.
  0                                                   # Start with 0.
   ,{                                     }           # Use the iteration formula...
     my \i=++$;                                       #   Fetch current index.
               $_+(                      )            #   Last element plus:
                   4*(i%%3+i%%5)                      #     Fizz/Buzz/FizzBuzz length,
                                ||i.chars             #     or number length.
                                           ...$_      # ...until the input is reached.
 (                                              )-1   # Sequence length minus 1.

0

Japt,20 字节

@µ35ìx_XvZÃ*4ªXìÊ}f1

试试吧

@µ35ìx_XvZÃ*4ªXìÊ}f1     :Implicit input of integer U
@                        :Function taking an integer X as argument
 µ                       :  Decrement U by
  35ì                    :    Digit array of 35
     x                   :    Reduce by addition
      _                  :    After passing each Z through the following function
       XvZ               :      Is X divisible by Z?
          Ã              :    End reduce
           *4            :    Multiply by 4
             ª           :    Logical OR with
              Xì         :      Digit array of X
                Ê        :      Length
                 }       :End function
                  f1     :First integer >=1 that returns a falsey value (i.e, 0) when passed through that function



0

05AB1E,17 个字节

Lε35SÖ4*OygM}.¥sk

在线尝试验证所有测试用例

说明:

L          # Create a list in the range [1, (implicit) input]
           #  i.e. 15 → [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
 ε         # Map each value to:
  35S      #  Push 35 as digit list: [3,5]
     Ö     #  Check if the current value is divisible by these (1 if truthy; 0 if falsey)
      4*   #  Multiply both by 4
        O  #  And take the sum of that
           #   i.e. 2 → [0,0] → [0,0] → 0
           #   i.e. 9 → [1,0] → [4,0] → 4
           #   i.e. 10 → [0,1] → [0,4] → 4
           #   i.e. 15 → [1,1] → [4,4] → 8
  yg       #  Push the current value again, and pop and push it's length
           #   i.e. 2 → 1
           #   i.e. 15 → 2
  M        #  And then push the largest value on the stack
           #   i.e. 0 and 1 → 1
           #   i.e. 8 and 2 → 8
 }.¥       # After the map: undelta the list (starting from 0)
           #  i.e. [1,1,4,1,4,4,1,1,4,4,2,4,2,2,8]
           #   → [0,1,2,6,7,11,15,16,17,21,25,27,31,33,35,43] 
    sk     # Swap to get the (implicit) input, and get its 0-based index in the list
           #  i.e. 15 → 6
           # (after which the result is output implicitly)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.