多次运行的数字


30

任务

找到一组数字,使二进制表示形式包含两个或多个1由至少一个隔开的游程0

例如,对于4位长的数字:

 0 0000        (no ones)
 1 0001        (only one run)
 2 0010        (only one run)
 3 0011        (only one run)
 4 0100        (only one run)
 5 0101 Valid
 6 0110        (only one run)
 7 0111        (only one run)
 8 1000        (only one run)
 9 1001 Valid
10 1010 Valid
11 1011 Valid
12 1100        (only one run)
13 1101 Valid
14 1110        (only one run)
15 1111        (only one run)

输入值

通过范围内的某些输入提供给应用程序的整数3 .. 32。这表示要计数的最大位数。

输入n表示需要检查数字。0 .. 2n-1

输出量

符合条件的所有数字的定界(您选择)列表。数字应按数字顺序显示。可以使用额外的尾部定界符。数据结构外壳(例如[]和类似外壳)也是可以接受的。

Input: 3
Output: 5

Input: 4
Output: 5, 9, 10, 11, 13

Input: 5
Output: 5, 9, 10, 11, 13, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 29

这是 -字节数最少的答案获胜。


我想您因为n = 5而错过了23。
xnor 2015年

@ xnor你是正确的。谢谢,是的,这也使其不等同于A094695。嗯 oeis.org/A101082oeis.org/A166934

@VTCAKAVSMoACE是的。如果要\n定界并\n在最后一行,加上a ,则,也可以使用尾随定界。更新。

1
输入可以采用列表格式[1, 2, 3]吗?
kirbyfan64sos

@ kirbyfan64sos是的。更新。

Answers:


7

Pyth,12个字节

f<2r.BT8U^2Q

在线尝试。

理念

任何正数的二进制表示始终始于1 s的行程,然后可能跟随其他交替的0 s和1 s的行程。如果至少有三个独立运行,则保证其中两个运行时间为1 s。

              (implicit) Store the evaluated input in Q.
         ^2Q  Calculate 2**Q.
f       U     Filter; for each T in [0, ..., 2**Q-1]:
    .BT         Compute T's binary representation.
   r   8        Perform run-length encoding.
                This returns a list of character/run-length pairs.
 <2             Discard the trailing two pairs.
                This returns a non-empty array if there are more than 2 runs.
              Keep T if the array was truthy (non-empty).

22

Python,48岁

lambda n:[i for i in range(2**n)if'01'in bin(i)]

我一直在想太多。我们只需要检查二进制扩展名是否包含'01'

要有两次运行,必须在右侧运行一个0。如果只进行一次,则不会有任何前导0,因此不会发生。


旧答案:

lambda n:[i for i in range(2**n)if len(set(bin(i).split('0')))>2]

Python二进制表示形式在这里非常好用。二进制数写成bin(9)=='0b10110'。分割'0'结果为以下列表

  • 在首字母的左侧,0两个连续的字母之间以及任何结尾0的右侧的空字符串0
  • 字母b后跟一个或多个前导字母
  • 的运行1的未龙头

前两个类别始终存在,但最后一个类别仅在有一个1不包含前导的运行' 时才存在'1',因此只有在有多个运行的1' 时才存在。因此,只需检查列表中是否包含多个2不同的元素即可。

Python 3.5通过解压缩{*_}代替节省了2个字符set(_)


感谢您使用/01/代替的想法/10+1/。我在Perl中利用了这一点。
msh210

13

Ruby,44 40 38个字符

划掉44仍然是常规44;(

->n{(0..2**n).select{|x|/01/=~'%b'%x}}

一个匿名函数(实际上是proc),它接受一个整数并返回一个数组。

使用正则表达式/10+1/:a 1,至少一个0,然后另一个1@histocrat指出,如果01字符串中的任何位置存在必须在其1之前的某个位置。


1
在这里使用格式字符串要短一些:/10+1/=~'%b'%x。另外,您可以使用包含性的range(0..2**n)保存字符,因为它2**n绝不会多次运行。
histocrat

@histocrat Huh,我不知道您可以使用来翻转字符串和正则表达式的顺序=~。谢谢!
门把手

1
等等,正则表达式实际上/01/也一样。如果有01,则左侧某处必须有1。
histocrat

@histocrat哦,这很聪明!这样可以节省两个字符。
门把手

7

朱莉娅 43 41字节

n->filter(i->ismatch(r"01",bin(i)),1:2^n)

这将创建一个未命名的函数,该函数接受一个整数并返回一个数组。它使用了hitocrats的regex技巧(用于Doorknob的答案),01只有在前面有1的情况下才会匹配。

取消高尔夫:

function f(n::Int)
    # Take the integers from 1 to 2^n and filter them down to
    # only those such that the binary representation of the integer
    # matches the regex /01/.
    filter(i -> ismatch(r"01", bin(i)), 1:2^n)
end

历史学家的s俩,不是我的。:)
门把手

@Doorknob哦,嘿,现在你们俩都获得了荣誉。:)
Alex A.

6

Matlab, 79 68 64 59

这个想法是将二进制数解释为零和一的数组,然后计算每对邻居之间的绝对差。如果我们有两个或更多乘以1的差,那么显然我们有两个或更多的乘积。请注意,这仅在我们表示不带前导零的二进制数时有效。

@(n)find(arrayfun(@(k)sum(~~diff(dec2bin(k)+0))>1,1:2^n-1))

旧版本:

k=1:2^input('')-1;k(arrayfun(@(k)sum(~~diff(dec2bin(k)+0))>1,k))

for k=1:2^input('')-1;if sum(~~diff(dec2bin(k)+0))>1;disp(k);end;end

for k=1:2^input('')-1;if sum(~~conv(dec2bin(k)+0,[-1,1],'v'))>1;disp(k);end;end

6

JavaScript(ES7),89 85 72 69 62字节

在JS中创建范围并不容易。实际for循环可能会更短。不,我撒谎;实际上更长一些。那好吧。我想我只需要解决已保存的27个字节。(7感谢Mwr247!)

x=>[for(a of Array(1<<x).keys())if(/01/.test(a.toString(2)))a]

在最新版本的Firefox中可以正常运行,但在其他任何浏览器中均不能正常运行。试试看:

<!--                               Try the test suite below!                              --><strong id="bytecount" style="display:inline; font-size:32px; font-family:Helvetica"></strong><strong id="bytediff" style="display:inline; margin-left:10px; font-size:32px; font-family:Helvetica; color:lightgray"></strong><br><br><pre style="margin:0">Code:</pre><textarea id="textbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><pre style="margin:0">Input:</pre><textarea id="inputbox" style="margin-top:5px; margin-bottom:5px">5</textarea><br><button id="testbtn">Test!</button><button id="resetbtn">Reset</button><br><p><strong id="origheader" style="font-family:Helvetica; display:none">Original Code Output:</strong><p><div id="origoutput" style="margin-left:15px"></div><p><strong id="newheader" style="font-family:Helvetica; display:none">New Code Output:</strong><p><div id="newoutput" style="margin-left:15px"></div><script type="text/javascript" id="golfsnippet">var bytecount=document.getElementById("bytecount");var bytediff=document.getElementById("bytediff");var textbox=document.getElementById("textbox");var inputbox=document.getElementById("inputbox");var testbtn=document.getElementById("testbtn");var resetbtn=document.getElementById("resetbtn");var origheader=document.getElementById("origheader");var newheader=document.getElementById("newheader");var origoutput=document.getElementById("origoutput");var newoutput=document.getElementById("newoutput");textbox.style.width=inputbox.style.width=window.innerWidth-50+"px";var _originalCode="x=>[for(a of Array(1<<x).keys())if(/01/.test(a.toString(2)))a]";function getOriginalCode(){if(_originalCode!=null)return _originalCode;var allScripts=document.getElementsByTagName("script");for(var i=0;i<allScripts.length;i++){var script=allScripts[i];if(script.id!="golfsnippet"){originalCode=script.textContent.trim();return originalCode}}}function getNewCode(){return textbox.value.trim()}function getInput(){try{var inputText=inputbox.value.trim();var input=eval("["+inputText+"]");return input}catch(e){return null}}function setTextbox(s){textbox.value=s;onTextboxChange()}function setOutput(output,s){output.innerHTML=s}function addOutput(output,data){output.innerHTML+='<pre style="background-color:'+(data.type=="err"?"lightcoral":"lightgray")+'">'+escape(data.content)+"</pre>"}function getByteCount(s){return(new Blob([s],{encoding:"UTF-8",type:"text/plain;charset=UTF-8"})).size}function onTextboxChange(){var newLength=getByteCount(getNewCode());var oldLength=getByteCount(getOriginalCode());bytecount.innerHTML=newLength+" bytes";var diff=newLength-oldLength;if(diff>0){bytediff.innerHTML="(+"+diff+")";bytediff.style.color="lightcoral"}else if(diff<0){bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgreen"}else{bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgray"}}function onTestBtn(evt){origheader.style.display="inline";newheader.style.display="inline";setOutput(newoutput,"");setOutput(origoutput,"");var input=getInput();if(input===null){addOutput(origoutput,{type:"err",content:"Input is malformed. Using no input."});addOutput(newoutput,{type:"err",content:"Input is malformed. Using no input."});input=[]}doInterpret(getNewCode(),input,function(data){addOutput(newoutput,data)});doInterpret(getOriginalCode(),input,function(data){addOutput(origoutput,data)});evt.stopPropagation();return false}function onResetBtn(evt){setTextbox(getOriginalCode());origheader.style.display="none";newheader.style.display="none";setOutput(origoutput,"");setOutput(newoutput,"")}function escape(s){return s.toString().replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}window.alert=function(){};window.prompt=function(){};function doInterpret(code,input,cb){var workerCode=interpret.toString()+";function stdout(s){ self.postMessage( {'type': 'out', 'content': s} ); }"+" function stderr(s){ self.postMessage( {'type': 'err', 'content': s} ); }"+" function kill(){ self.close(); }"+" self.addEventListener('message', function(msg){ interpret(msg.data.code, msg.data.input); });";var interpreter=new Worker(URL.createObjectURL(new Blob([workerCode])));interpreter.addEventListener("message",function(msg){cb(msg.data)});interpreter.postMessage({"code":code,"input":input});setTimeout(function(){interpreter.terminate()},1E4)}setTimeout(function(){getOriginalCode();textbox.addEventListener("input",onTextboxChange);testbtn.addEventListener("click",onTestBtn);resetbtn.addEventListener("click",onResetBtn);setTextbox(getOriginalCode())},100);function interpret(code,input){window={};alert=function(s){stdout(s)};window.alert=alert;console.log=alert;prompt=function(s){if(input.length<1)stderr("not enough input");else{var nextInput=input[0];input=input.slice(1);return nextInput.toString()}};window.prompt=prompt;(function(){try{var evalResult=eval(code);if(typeof evalResult=="function"){var callResult=evalResult.apply(this,input);if(typeof callResult!="undefined")stdout(callResult)}}catch(e){stderr(e.message)}})()};</script>

(摘录自此

建议欢迎!


您可以使用.keys()替代.fill()a取代i扎矿为62:x=>[for(a of Array(1<<x).keys())if(/01/.test(a.toString(2)))a]
Mwr247

@ Mwr247谢谢!我想知道是否有可能在62岁以下... :)
ETHproductions

6

Haskell,68 61 53字节

达米安的改进

g x|x`mod`4==1=x>4|2>1=g$x`div`2
a x=filter g[1..2^x]

历史:

这样可以修复错误(Switched ==和=,以及正方形而不是2的幂)。并将true替换为2> 1,并将false替换为1> 2。还要感谢指出2 ^ x总是失败。感谢Thomas Kwa和nimi

g x|x<5=1>2|x`mod`4==1=2>1|2>1=g$x`div`2
a x=filter g[1..2^x]

本来

g x|x<5=False|x`mod`4=1==True|2>1=g$x`div`2
a x=filter g[1..(x^2-1)]

如果必须是完整程序,

g x|x<5=False|x`mod`4==1=True|2>1=g$x`div`2
main=interact$show.a
a x=filter g[1..2^(read x)]

1
Lambda很好,因为OP没有指定编写命名函数或程序。顺便说一句,欢迎来到PPCG!
lirtosiast

1
我认为您的意思1..(2^x-1)1.. (2^x)2 ^ x总是失败。
lirtosiast

您可以替换常量FalseTrue1>21<2。不需要括号2^x-1。(顺便说一句:您有错字:必须是4==1=True)。
nimi 2015年

感谢您输入错误。我的时间已经很晚了。
Akangka

我认为您可以将g减少为:gx | x mod4 == 1 = x> 4 | 2> 1 = g $ x div2
Damien 2015年

5

APL,34 27字节

{0~⍨{⍵×2<+/2≢/⍵⊤⍨⍵/2}¨⍳2*⍵}

这将创建一个未命名的monadic函数,该函数在右侧接受一个整数并返回一个数组。

说明:

                     }¨⍳2*⍵}  ⍝ For each integer from 1 to 2^input...
              ⍵⊤⍨⍵/2         ⍝ Get the binary representation as a vector
           2≢/                ⍝ Pairwise non-match, yielding a boolean vector
       2<+/                   ⍝ Check whether the number of trues is >2
     ⍵×                       ⍝ Yield the integer if so, otherwise 0
{0~⍨{                         ⍝ Remove the zeros from the resulting array

感谢Dennis,节省了7个字节!


4

R,55 47字节

(在@ Alex.A的帮助下)

cat(grep("10+1",R.utils::intToBin(1:2^scan())))

R没有内置函数以方便的方式显示转换后的数字,因此我正在使用R.utils::intToBin此功能,而其余的几乎都只是报告匹配的regex表达式的位置,并打印到STDOUT时,用逗号分隔空间。


我认为默认分隔符cat是一个空格,因此您可以,sep=","完全省略,节省7个字节。
Alex A.

@AlexA。是的,我可以在这里用空格作为分隔符吗?我不确定
David Arenburg 2015年

1
OP表示您选择的分隔符,因此我认为空格似乎足够合理。:)
Alex A.

这真的需要cat功能吗?没有它,它将以制表符分隔输出。左侧计数器是UI的一部分,如果将​​其写入文件中,则不会包含在内,因此它不属于输出。
freekvd15年

没有它的@freekvd将不会打印到STDOUT,有关此网站的愚蠢规则。
David Arenburg


4

JavaScript(ES6),69 68 67 62字节

a=>[...Array(1<<a).keys()].filter(i=>/01/.test(i.toString(2)))

今天,我发现了一种无需使用fill或map即可动态填充数组的更短的新方法。这样做x=>[...Array(x).keys()]将返回范围为0到x的数组。如果您想定义自己的范围/值,请使用x=>[...Array(x)].map((a,i)=>i),因为它仅长几个字节。


4

Java中,214 165 155 154 148 141 110字节

该提交利用了以下事实:Java中数字的二进制字符串表示形式永远不会有前导零。如果字符串“ 01”出现在数字的二进制表示中,则表示必须标记第二次出现的数字“ 1”。

打高尔夫球:

String f(int l){String r="";for(long i=5;i<1L<<l;++i)if(Long.toString(i,2).contains("01"))r+=i+", ";return r;}

取消高尔夫:

public class NumbersWithMultipleRunsOfOnes {

  public static void main(String[] a) {
    // @formatter:off
    String[][] testData = new String[][] {
      { "3", "5" },
      { "4", "5, 9, 10, 11, 13" },
      { "5", "5, 9, 10, 11, 13, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 29" }
    };
    // @formatter:on

    for (String[] data : testData) {
      System.out.println("Input: " + data[0]);
      System.out.println("Expected: " + data[1]);
      System.out.print("Actual:   ");
      System.out.println(new NumbersWithMultipleRunsOfOnes().f(Integer.parseInt(data[0])));
      System.out.println();
    }
  }

  // Begin golf
  String f(int l) {
    String r = "";
    for (long i = 5; i < 1L << l; ++i)
      if (Long.toString(i, 2).contains("01")) r += i + ", ";
    return r;
  }
  // End golf
}

程序输出(请记住,可以使用尾部定界符):

Input: 3
Expected: 5
Actual:   5, 

Input: 4
Expected: 5, 9, 10, 11, 13
Actual:   5, 9, 10, 11, 13, 

Input: 5
Expected: 5, 9, 10, 11, 13, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 29
Actual:   5, 9, 10, 11, 13, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 29, 

您不使用int计数器变量吗?
瑕疵的

Java中的所有整数类型都是无符号的。为了使用32位正整数,需要64位long。此外,使用int会由于引用包装程序类进行数字解析而实际上增加了代码的大小Integer。我认为可能会节省空间的地方是正则表达式,但是我的测试表明我必须要领先和落后.*

哦,对了,但我认为您可以将Long包装器用于int?(不是在这种情况下,而是在一般情况下?)
虚假的2015年

是的,当与用作参数时,int将升级longLong。在这种情况下,int由于符号位,实际上没有任何使用方法,并且Integer比更长Long。不过,我发现了一些方法可以从像Java这样冗长的语言中挤出一些额外的空间。

可以new Long()代替使用Long.parseLong()吗?
Ypnypn

4

C(gcc)111 99字节

long i,x;main(a,b)char**b;{for(;++i<1L<<atol(b[1]);x>>ffsl(~x)-1&&printf("%ld,",i))x=i>>ffsl(i)-1;}

在线尝试!

感谢@ceilingcat,减少了12个字节!

取消高尔夫:

int main(int a, char **b) {
  for(long i = 0, x = 0; ++i < (1LL << atol(b[1])); ) {
    x = i >> (ffsl(i) - 1);
    if (x >> (ffsl(~x) - 1))
      printf("%ld,", i);
  }
}

ffsl()函数为您提供以长整数设置的第一位的索引。因此,我们从循环i = 1到2 ^ number_of_bits。我们设置xi右移,直到删除了最低有效端上所有连续的零位。然后,我们x向右移动,直到在最低有效端删除了所有连续的1位。如果结果仍非零,则找到匹配项。


2
我必须说,我真的很喜欢有人做了一些操作性的回答,而不是“转换为字符串和正则表达式”的方法。

@MichaelT我想知道是否仅使用原始的按位运算就可以解决问题。
lirtosiast 2015年

@ThomasKwa这可能是代码挑战的事情。

有趣。您还可以像这样编写测试:if (popcount(i ^ (i*2))>3),并将popcount()扩展为一系列按位AND和shift操作。但这将导致相当长的代码。
G. Sliepen

1
@ThomasKwa y = x |(x-1)打开所有最右边的0位。然后z = y&(y + 1)关闭所有尾随的1位。如果z不为零,则原始数字运行了多个。
Alchymist 2015年

3

JavaScript(ES6)76

f=n=>Array(1<<n).fill().map((_,x)=>/01/.test(x.toString(2))?x+',':'').join``

//TEST
for(i=1;i<16;i++)O.innerHTML+=i+' -> '+f(i)+'\n'
<pre id=O></pre>


@DLosc不,结果将类似于,,,,,5,,,,9,10,11,,13,,,,17,18,19,20,21,22,23,,25,26,27,,29,,
edc65

3

K5,19个字节

这遵循与Dennis解决方案相似的原理,但是利用的内置函数更少。

{&2<+/'~0=':'+!x#2}

首先,生成一系列二进制x元组(+!x#2),然后如果我们为此目的将列表的-1st元素视为0,则为每个元组查找数字与前一个不匹配的每个点~0=':'。我们的解决方案是两个小于每个运行计数的总和。(&2<+/')。

显示每个中间步骤更加清晰:

  4#2
2 2 2 2

  !4#2
(0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1)

  +!4#2
(0 0 0 0
 0 0 0 1
 0 0 1 0
 0 0 1 1
 0 1 0 0
 0 1 0 1
 0 1 1 0
 0 1 1 1
 1 0 0 0
 1 0 0 1
 1 0 1 0
 1 0 1 1
 1 1 0 0
 1 1 0 1
 1 1 1 0
 1 1 1 1)

  ~0=':'+!4#2
(0 0 0 0
 0 0 0 1
 0 0 1 1
 0 0 1 0
 0 1 1 0
 0 1 1 1
 0 1 0 1
 0 1 0 0
 1 1 0 0
 1 1 0 1
 1 1 1 1
 1 1 1 0
 1 0 1 0
 1 0 1 1
 1 0 0 1
 1 0 0 0)

  +/'~0=':'+!4#2
0 1 2 1 2 3 2 1 2 3 4 3 2 3 2 1

  2<+/'~0=':'+!4#2
0 0 0 0 0 1 0 0 0 1 1 1 0 1 0 0

  &2<+/'~0=':'+!4#2
5 9 10 11 13

以及所有:

  {&2<+/'~0=':'+!x#2}'3 4 5 
(,5
 5 9 10 11 13
 5 9 10 11 13 17 18 19 20 21 22 23 25 26 27 29)

2

点,13 +1 = 14字节

从命令行获取输入,并将-s标志用于输出数字之间的空格。

01NTB_FI,2**a

非常简单:range(2**a)在上构建和过滤lambda _: "01" in toBinary(_)。我很高兴01独立思考这个想法。不需要引号,01因为它以数字文字形式扫描(数字和字符串在Pip中是同一类型)。


2

朱莉娅,40个字节

n->filter(i->count_ones(i$i>>1)>2,1:2^n)

这与Julia的其他解决方案使用的方法有所不同-而不是在位字符串中进行字符串搜索“ 01”,而是使用一些数学方法确定数字是否满足条件。

i$i>>1仅在数字从零变为一或从一变为零的位置中才会有一个。因此,必须至少有三个用于i在零和一之间进行足够的来回切换。count_ones找到一个,然后filter删除那些没有足够数量的。


2

C ++,197 188 141字节

注:这是写和使用MSVC ++ 2013年测试了它看来,#includeING<iostream>包含了所有必需的C头文件才能完成此工作。似乎代码也不再是真正的C ++,但是使用C ++进行编译允许使用标头技巧,与包含更多的C标头相比,它可以减少代码大小。

使用printf代替cout还可以节省几个字节。

打高尔夫球:

#include<iostream>
int main(int a,char**b){char c[34];for(long i=5;i<1L<<atol(b[1]);++i){_ltoa(i,c,2);if(strstr(c,"01"))printf("%ld\n",i);}}

取消高尔夫:

#include <iostream>
int main(int a, char **b) {
  char c[34];
  for (long i = 5; i < 1L << atol(b[1]); ++i) {
    _ltoa(i, c, 2);
    if (strstr(c, "01"))
      printf("%ld\n", i);
  }
}

Yoiu可以使用'\n'代替std :: endl(通常),或者','因为任何分隔符都有效并且尾随分隔符就可以了。
G. Sliepen

您可以使用来代替regex strstr(c,"01")
G. Sliepen

@ G.Sliepen谢谢!老实说,我只是复制了Java解决方案并转换为C ++,但是简单的解决方案通常是最好的。我现在应该使用Java做类似的事情。

两个小错误:1<<atol(b[1])应该是1L<<atol(b[1]),否则该表达式的结果将是一个带符号的32位整数,这意味着代码最多只能运行2 ^ 30。printf应该用于%ld正确打印2 ^ 31到2 ^ 32之间的数字。
G. Sliepen

2

Perl 5,55 53 49 47 41字节

sprintf("%b",$_)=~/01/&&say for 0..2**<>

54 52 48 46 40字节,加上1 -E代替-e


感谢xnor提供有关using 代替的提示,它节省了两个字节。/01//10+1/

感谢Dennis<>代替使用的建议$ARGV[0],它节省了六个字节。


2

C,84 81字节

long i,j,k;main(){for(scanf("%ld",&j);++i<1L<<j;k&k+1&&printf("%ld ",i))k=i|i-1;}

这是基于我对这个问题的另一个C答案的评论,即有关使用简单按位运算符的可能性。它通过将语句i |(i-1)中的所有尾随0位切换为1来工作。然后,使用k&(k + 1)将所有尾随的1位切换为0。如果只运行一次,则结果为零,否则为非零。我确实假设long是64位,但是可以通过使用int64_t来以3个字节为代价更正此错误。

不打高尔夫球

long i,j,k;
main()
{
    for(scanf("%ld",&j);++i<1L<<j;)
    {
        k=i|(i-1);
        if((k&(k+1)) == 0)
            printf("%d ",i);
    }
}

int64_t仅当您定义时#include<stdint.h>。确保64位操作需要long long输入5个字节的字。
chqrlie 2015年

请注意,您调用未定义行为传递long i%d格式。还要注意,()对于&|运算符来说是多余的。解决此问题可节省3个字节! long i,j,k;main(){for(scanf("%ld",&j);++i<1L<<j;k&k+1&&printf("%ld ",i))k=i|i-1;}
chqrlie 2015年

@chqrlie所有非常好的观点。谢谢。
Alchymist


1

Python 2.7, 89 bytes

print[i for i in range(1,2**input())if[n[:1]for n in bin(i)[2:].split("0")].count("1")-1]

I think this could be golfed a bit.


@mbomb007 I tried that, it didn't work.
Loovjo

@mbomb007 Are you using Python 2.7?
Loovjo

Does it matter which version of 2.7? I run it on repl.it (2.7.2) and it doesn't work, but Ideone (2.7.10) does. It might just be a bug in repl.it though, not necessarily a version difference.
mbomb007

Your program incorrectly prints 0 in the output.
mbomb007

Also print[i for i in range(2**input())if[n[:1]for n in bin(i)[2:].split("0")].count("1")-1] is two bytes shorter. But with the fix for 0 would be the same length (89), if you use range(1,2**input()).
mbomb007

1

TI-BASIC, 34 32 30 bytes

For a TI-83+/84+ series calculator.

For(X,5,e^(Ans
If log(sum(2=int(4fPart(X/2^randIntNoRep(1,Ans
Disp X
End

For a number to contain two runs of 1s, it must contain two 10s when we tack a trailing zero onto the binary representation.

Rather than generate the binary representation and check for a 10, we test pairs of bits mathematically by using remainder by 4 (int(4fPart(), which will give 2 where there is a 10. Because we don't care about order, randIntNoRep( is the shortest way to generate the list of exponents.

We use log( to check for the number of runs:

  • If there are at least 2 runs, then the log( is positive, and the number is displayed.

  • If there is one run, then the log( is 0, and the number is not displayed.

  • If there are no runs (which first happens at X=2^Ans), then log( throws an ERR:DOMAIN, stopping the output at exactly the right point.

We use e^(Ans as the ending argument of the For( loop—it's always greater than 2^Ans, but e^( is a single token, so it's one byte shorter.

Input/output for N=4:

4:prgmRUNSONES
               5
               9
              10
              11
              13

Then the calculator throws an error; the error screen looks like this:

ERR:DOMAIN
1:Quit
2:Goto

When 1 is pressed, the home screen is displayed again:

4:prgmRUNSONES
               5
               9
              10
              11
              13
           Error

TI calculators store all numbers in a BCD float with 14 digits of precision, not an int or binary float. Therefore, divisions by powers of two greater than 2^14 may not be exact. While I have verified that the trickiest numbers, 3*2^30-1 and 2^32-1, are handled correctly, I have not ruled out the possibility of rounding errors. I would however be surprised if there were errors for any input.


How do you count 32 bytes? It looks like 70 to me (including the newlines).
msh210

TI-BASIC is tokenized; it uses a proprietary character encoding in which all of these commands are one byte each and the others are two. It is the community consensus to score by this encoding-- see meta.codegolf.stackexchange.com/a/4764/39328 for details.
lirtosiast

Oh, cool. Thanks FYI.
msh210

1
  • this doesnt beat flawr's answer but i couldnt resist the charm of the question

matlab(90)(70)

j=input('');for l=2:j-1,a=1;for k=l:-1:2,a=a+2^k;a:a+2^(k-1)-2,end,end

execution

4

ans =

5

ans =

9    10    11

ans =

13

principle

  • The series of numbers are a result of consequent strip of 1's, which does mean f(n,l)=2^l+2^(l+1)+....2^n

Any number taken from the interval ]f(n,l),f(n,l)+2^(l-1)[ where l>1 verifies this condition, so the outcome is a result of the negation of this series in terms of n.

x=1

x=x+1=01,

x=x+2^0=11,

x=x+1=001,

x=x+2^1=011,

x=x+2^0=111,

x=x+1=0001,

x=x+2^2=0011,

x=x+2^1=0111,

x=x+2^0=0111,

x=x+1=1111 ...

x+1, x=x+2^n, x=x+2^(n-1)...x=x+2^0

My program prints the range between each two lines (if exists)


Edit: unfortunately that doesnt make it golfed more but i wanted to add another approach of proceding this idea

after a period of struggle i succeded to find a mathematical representation for this series which is:

2^l(0+1+2^1+...2^k) with l+k < n

=2^l(2^k-1)

score=90

@(n)setdiff(0:2^n-1,arrayfun(@(x)2^mod(x,(n+1)-fix(x/(n+1)))*(2^fix(x/(n+1))-1),0:(n+1)^2))

1

C, 103 102 bytes

long i,x;main(int a,char**b){for(;++i<1L<<atoi(b[1]);)for(x=i;x>4&&(x%4!=1||!printf("%ld,",i));x/=2);}

Expanding (actually contracting) on G.Sliepen entry, taking advantage of xnor remark on the 01 pattern in the binary representation, but using only standard functions and some bit twiddling.

Ungolfed version:

long i, x;
main(int a, char**b) {
    for (; ++i < 1L << atoi(b[1]);) {
        for (x = i; x > 4 && (x % 4 != 1 || !printf("%ld,", i)); x /= 2)
            ;
    }
}

The inner loop scans i for the binary pattern 01 by iteratively shifting x to the right as long as it has 3 bits left. printf returns the number of characters printed, hence never 0, so the inner loop test fails after the printf, avoiding the need for a break statement.

C++, 129 128 bytes

Adapting the same idea, the C++ variant is here:

#include<iostream>
long i,x;int main(int a,char**b){for(;++i<1L<<atoi(b[1]);)for(x=i;x>4&&(x%4!=1||!(std::cout<<i<<','));x/=2);}

Technically, I should make i a long long to ensure 64 bit operation and compute upto 2^32 for an extra 5 bytes, but modern platforms have 64 bit ints.


1

JavaScript ES6, 60 bytes

Code

n=>[...Array(1<<n).keys()].filter(g=x=>x>4?x%4==1|g(x>>1):0)

Try it online!

Explanation

[...Array(1<<n).keys()]                                          Create an array of numbers from 0 to 2^n-1
                       .filter(                                  Find the numbers which meet criteria
                               g=x=>x>4?                  :0     If x is less than or equal to four return zero (false/invalid)
                                        x>4?x%4==1|              If the binary pattern ends with 01 return one (true/valid)
                                                   g(x>>1)       Otherwise bitshift right by one and try again

0

C (sort of - compiles with warnings in GCC) - 103

This uses no library functions of any kind except printf. You can see by looking at this that no effort has been spared to make it standards compliant or avoid UB.

x,c;main(n,v){n--;for(;c<1<<n;c++)for(v=0;v<32;v++)if(c&1<<v){if(x&&x<v&&printf("%d ",c))break;x=v+1;}}

To make it compliant you would need to do lots of things like including stdio.h which would be against the spirit of making it as small as possible.

If anyone has suggestions for making it shorter please let me know.


0

PowerShell, 80 bytes

while([Math]::Pow(2,$args[0])-gt$n++){$n|?{[Convert]::ToString($n,2)-match"01"}}

0

Python, 44 Bytes

Okay, this could probably be shorter but it's my first codegolf:

x=1
while True:
    if '01' in bin(x):
        print(x)
    x+=1

Think this answers the question, please don't down vote if it doesn't, just post whats wrong with it below.


1
You need to take input (input() is ideal) to get n, and then only count up to 2^n-1, rather than looping indefinitely. Also, you can use 1 and 2 spaces for the nesting, rather than 4 and 8, and using map or a list comprehension would probably shorten your code tremendously.
Mego

0

another different matlab answer of good score.

matlab 60(57)

@(n)find(mod(log2(bitcmp(1:2^n,fix(log2(1:2^n)+1))+1),1))

execution

>> @(n)find(mod(log2(bitcmp(1:2^n,fix(log2(1:2^n)+1))+1),1))

ans =

@(n)find(mod(log2(bitcmp(1:2^n,fix(log2(1:2^n)+1))+1),1))

>> ans(5)

ans =

 5     9    10    11    13    17    18    19    20    21    22    23    25    26    27    29

  • The idea is picking up numbers x where the binary representation of -(x)+1 doesnt contain only one occurence of 1

example:

0000111 is rejected because ~x=1111,~x+1=00001 contains one digit=1

0100111 is accepted because ~x=1011,~x+1=0111 contains many 1's

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.