在无限制的字符串中找到缺失的数字


19

面临的挑战是在无界整数字符串中标识丢失的数字。

系统会为您提供一串数字(有效输入将匹配正则表达式^[1-9][0-9]+$)。该字符串表示整数序列。例如,1234567891011。序列中的所有数字都在范围12147483647包容性。

该序列是一系列数字,其中每个数字都比其前身大一个。但是,此序列可能包含一个且序列中只有一个缺失的数字。给定的字符串也可能不包含序列中的缺失数字。该字符串将始终包含序列中的至少两个数字。

该代码必须输出或返回缺失值,或者00如果没有缺失值,则该值是-而不是伪造的值)。

以下是有效的输入及其输出/返回:

input                         output    actual sequence (for refrence)
123467                        5         1 2 3 4 _ 6 7
911                           10        9 __ 11
123125126                     124       123 ___ 125 126
8632456863245786324598632460  8632458   8632456 8632457 _______ 8632459 8632460  
123                           0         1 2 3
8632456863245786324588632459  0         8632456 8632457 8632458 8632459  

尽管所有这些都被描述为输入的“字符串”,但如果该语言能够处理任意大的数字(dc并且mathematica,我正在看你们两个),则输入可能是任意大的数字,而不是字符串,如果这样代码更容易。

作为参考,这是受Programmers.SE问题的启发:按字符串顺序查找缺失的数字


4
您确定这是明确的吗?
Martin Ender

@MartinBüttner我已经考虑了一下,还没有想到当序列加1(可能是问题)时,模棱两可的情况。

在OEIS中是否有一个整数列表的条目,该整数列表是仅缺少一个元素的串联序列?
mbomb007 '16

@ mbomb007我不认为如此,因为有无数不同的列表。而且这只是一个很大的问题。不确定如何定义。为此,一个有趣的CS问题将是“接受所有这些字符串的语言是什么”。它当然不规则。我怀疑它的CF。

1
我将序列作为挑战的主题:codegolf.stackexchange.com/q/73513/34718
mbomb007 '16

Answers:


5

Haskell,115112字节

g b|a<-[b!!0..last b]=last$0:[c|c<-a,b==filter(/=c)a]
maximum.map(g.map read.words.concat).mapM(\c->[[c],c:" "])

第一行是辅助函数定义,第二行是主要的匿名函数。 验证测试用例(由于时间限制,我不得不运行较短的测试)。

说明

这是一个蛮力的解决方案:以所有可能的方式将字符串拆分为单词,将单词解析为整数,查看是否是缺少一个元素的范围(返回该元素,0否则),并在所有拆分中取最大值。该区间与缺失元素检查的辅助函数完成的g,这需要一个列表b,并在返回范围的唯一元素[head of b..last of b],这不是在b,或者0如果一个不存在。

g b|                         -- Define g b
    a<-[b!!0..last b]=       -- (with a as the range [head of b..last of b]) as:
    last$0:[...]             --  the last element of this list, or 0 if it's empty:
            c|c<-a,          --   those elements c of a for which
            b==filter(/=c)a  --   removing c from a results in b.
mapM(\c->[[c],c:" "])        -- Main function: Replace each char c in input with "c" or "c "
map(...)                     -- For each resulting list of strings:
  g.map read.words.concat    --  concatenate, split at spaces, parse to list of ints, apply g
maximum                      -- Maximum of results (the missing element, if exists)

2

JavaScript(ES6),117个字节

s=>eval(`for(i=l=0;s[i];)for(n=s.slice(x=i=m=0,++l);s[i]&&!x|!m;x=s.slice(x?i:i+=(n+"").length).search(++n))m=x?n:m`)

说明

相当有效的方法。立即完成所有测试用例。

从输入字符串的开头获取每个子字符串为数字n,并将缺少的数字初始化m0。然后,它n从字符串的开头反复删除,递增n并在字符串中搜索它。如果是index of n != 0,它会检查m。如果为m == 0,则设置m = n并继续,如果没有,则存在多个丢失的数字,因此请停止从此子字符串中进行检查。此过程将一直持续到删除了整个字符串为止。

var solution =

s=>
  eval(`                     // use eval to use for loops without writing {} or return
    for(
      i=                     // i = index of next substring the check
      l=0;                   // l = length of initial substring n
      s[i];                  // if it completed successfully i would equal s.length
    )
      for(
        n=s.slice(           // n = current number to search for, initialise to subtring l
          x=                 // x = index of n relative to the end of the previous n
          i=                 // set i to the beginning of the string
          m=0,               // m = missing number, initialise to 0
          ++l                // increment initial substring length
        );
        s[i]&&               // stop if we have successfully reached the end of the string
        !x|!m;               // stop if there are multiple missing numbers
        x=                   // get index of ++n
          s.slice(           // search a substring that starts from the end of the previous
                             //     number so that we avoid matching numbers before here
            x?i:             // if the previous n was missing, don't increment i
            i+=(n+"").length // move i to the end of the previous number
          )
          .search(++n)       // increment n and search the substring for it's index
      )
        m=x?n:m              // if the previous number was missing, set m to it
  `)                         // implicit: return m
<input type="text" id="input" value="8632456863245786324598632460" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>


2

JavaScript(ES6)114

s=>eval("for(d=0,n=-9,z=s;z=z.slice((n+'').length);z.search(++n)?z.search(++n)?n=(z=s).slice(x=0,++d):x=n-1:0);x")  

少打高尔夫球和解释

f=s=>{
  d = 0  // initial digit number, will be increased to 1 at first loop 
  n = -9 // initial value, can not be found
  z = s  // initializa z to the whole input string
  // at each iteration, remove the first chars of z that are 'n' 
  // 'd' instead of 'length' would be shorter, but the length can change passing from 9 to 10 
  for(; z=z.slice((n+'').length); ) 
  {
    ++n; // n is the next number expected in sequence
    if (z.search(n) != 0)
    {
      // number not found at position 0
      // this could be the hole
      // try to find the next number
      ++n;
      if (z.search(n) != 0)
      {
        // nope, this is not the correct sequence, start again
        z = s; // start to look at the whole string again
        x = 0; // maybe I had a candidate result in xm but now must forget it
        ++d;   // try a sequence starting with a number with 1 more digit
        n = z.slice(0,d) // first number of sequence
      }
      else
      {
        // I found a hole, store a result in x but check the rest of the string
        x = n-1
      }
    }
  }      
  return x // if no hole found x is 0
}

测试

F=s=>eval("for(d=0,n=-9,z=s;z=z.slice((n+'').length);z.search(++n)?z.search(++n)?n=(z=s).slice(x=0,++d):x=n-1:0);x")

console.log=x=>O.textContent+=x+'\n'

elab=x=>console.log(x+' -> '+F(x))

function test(){ elab(I.value) }

;['123467','911','123125126','8632456863245786324598632460',
  '123','124125127','8632456863245786324588632459']
.forEach(t=>elab(t))
<input id=I><button  onclick='test()'>Try your sequence</button>
<pre id=O></pre>


2

C,183个 168 166 163字节

n,l,c,d,b[9];main(s,v,p)char**v,*p;{for(;s>1;)for(d=s=0,n=atoi(strncpy(b,p=v[1],++l)),p+=l;*p&&s<2;)p+=memcmp(p,b,c=sprintf(b,"%d",++n))?d=n,s++:c;printf("%d",d);}

不打高尔夫球

n,l,c,d,b[9];

main(s,v,p)char**v,*p;
{
    /* Start at length 1, counting upwards, while we haven't
       found a proper number of missing numbers (0 or 1) */
    for(;s>1;)
        /* Start at the beginning of the string, convert the
           first l chars to an integer... */
        for(d=s=0,n=atoi(strncpy(b,p=v[1],++l)),p+=l;*p&&s<2;)
            /* If the next number is missing, then skip, otherwise
               move forward in the string.... */
            p+=memcmp(p,b,c=sprintf(b,"%d",++n))?d=n,s++:c;

    printf("%d",d); /* print the missing number */
}

2
对于891112数字长度不同的输入,这如何工作?
Zgarb '16

@Zgarb它很好用。该sprintf调用返回的失踪人数的长度,不管它比以前更长与否。
科尔·卡梅隆

好,谢谢!+1。
Zgarb
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.