有关人物


28

背景

有关人物是CBS上的犯罪剧,也是我最近最喜欢的电视节目。

该节目讲述的是一个名叫亿万富翁程序员的哈罗德·芬奇(Harold Finch)和他的搭档约翰·里斯(John Reese)的故事,他是特种部队的资深人士和前中央情报局特工。该程序员创建了一个有感觉的AI,称为“机器”,可以在暴力犯罪发生之前对其进行预测。它通过监视和分析全球所有的监视摄像机和电子通讯,随时跟踪地球上的每个人。

哈罗德(Harold)为美国政府制造了“机器”(The Machine),以事前侦查恐怖活动。它根据预测的犯罪是否与国家安全相关将其划分为列表。相关案件由政府处理,而“无关”列表被编程为每天删除。

哈罗德本人为自己准备了一个后门,希望自己能处理“无关紧要”的清单。此后门会导致机器致电距Harold最近的公用电话(大约每天一次)并向他读取一个社会安全号码。该SSN属于因预谋犯罪而处于生命危险中的人,或正在计划此类犯罪的人。


挑战

编写一个无需输入即可输出30个随机电话号码和SSN的程序(请参见下文)。


输出量

每两天将打印两行文本。

  1. Crime predicted: 555-55-5555
  2. Calling: 1-555-555-5555 跟换行符

此过程应重复一个“月”(30个“天”)。


电话号码

每个电话号码必须包含以下元素:

  • 必须具有美国国家/地区代码(第一位数字)。

  • 必须具有随机区号(第一个三位数字)。

  • 电话号码本身的前三位数字应为555,其后为4位随机数。

这是一个带注释的示例:

1-814-555-3857
|  |   |   |
|  |   |   |
|  |   |   +---------->   random four digits
|  |   |
|  |   +-------------->   the set 555
|  |
|  +------------------>   area code
|
+--------------------->   country code

社会安全号码

每个SSN必须为9个随机数字,格式如下。

342-98-1613

Crime predicted: 234-72-8311
Calling: 1-633-555-0188

Crime predicted: 135-77-0910
Calling: 1-202-555-4719

Crime predicted: 722-90-6653
Calling: 1-466-555-1069

...

继续运行27个周期。


计分板

为了使您的分数出现在黑板上,应该采用以下格式:

# Language, Bytes

删除线不会引起问题。


3
此外,美国国家/地区代码/地区代码的有效值是多少?
mınxomaτ

2
我取消了时间限制。关于您的第二个问题,美国国家/地区代码明确是1。至于区号,就此挑战而言,任何三位数字都可以。@minxomat
扎克·盖茨

1
@ LuisMendo 关于元数据如果没有完全定义,意味着什么是共识
FryAmTheEggman 2015年

5
当然,以节目中The Machine实际传输的格式生成数字会更加复杂...;)
Mason Wheeler

Answers:


10

CJam,68 66 64字节

感谢Dennis节省了2个字节!

"Crime predicted: --
Calling: 1--555-

"30*{_5<{iAa*:mr}&}/

复制粘贴将不起作用,因为有一些不可打印的内容(每个随机组一个)。因此, xxd转储:

00000000: 2243 7269 6d65 2070 7265 6469 6374 6564  "Crime predicted
00000010: 3a20 032d 022d 040a 4361 6c6c 696e 673a  : .-.-..Calling:
00000020: 2031 2d03 2d35 3535 2d04 0a0a 2233 302a   1-.-555-..."30*
00000030: 7b5f 353c 7b69 4161 2a3a 6d72 7d26 7d2f  {_5<{iAa*:mr}&}/

要反转它,请将其粘贴到文件中并启动xxd -r in_file > out_file。你也可以可以在线尝试

说明

"..."30*     Push the string 30 times
{ ... }/     For each character in the string:
_5<{ ... }&    If the ASCII code is < 5:
iAa*             Push an array of as many 10s as the ASCII code
:mr              For each 10, choose a random 0-9 number

我本人从未想过,但在Pyth中似乎两个字节
FryAmTheEggman 2015年

@FryAmTheEggman我可能应该学习Pyth,它通常比CJam短。您可以根据需要发布该答案:)
Andrea Biondo

8

蟒蛇2,129

from random import*
print''.join([c,`randint(0,9)`][c>'w']for c in'Crime predicted: xxx-xx-xxxx\nCalling: 1-xxx-555-xxxx\n\n'*30)

天真的方法。接受消息

Crime predicted: xxx-xx-xxxx
Calling: 1-xxx-555-xxxx

并复制30次。然后,x用一个随机数字替换每个数字randint(0,9),并保持所有其他字符相同。


6

Python 2,151字节

感谢领主(和@Dennis)的%0nd:D

from random import randrange as r
for i in[1]*30:print"Crime predicted: %03d-%02d-%04d\nCalling: 1-%03d-555-%04d\n"%(r(1e3),r(100),r(1e4),r(1e3),r(1e4))

6

Perl,85字节,感谢Dennis和grc!

$_="Crime Predicted: NNN-NN-NNNN 
Calling: 1-NNN-555-NNNN 

"x30;s/N/0|rand 10/eg;print

原始Perl,91 92字节

print"Crime Predicted: NNN-NN-NNNN
Calling: 1-NNN-555-NNNN

"=~s/N/int rand 10/egr for 1..30

1
@Dennis aw,我将要发布它,直到我看到这个答案。我有$_="..."x30;s/_/0|rand 10/eg;print保存/r标志。
grc

谢谢@丹尼斯和@grc!将注释中建议的更改合并(当然带有归因)是惯例吗?如果没有,我将恢复编辑。但是,无论如何,谢谢!我已经完全忘记了0|rand ...我现在要反复使用的技巧和重复运算符,因为我错过了!
type_outcast

2
是的,这是习惯。如果还没有,您应该看看Perl打高尔夫球的技巧吗?。这是一个很棒的资源。
丹尼斯2015年

5

CJam,73 71 70字节

30{"Crime predicted: x-x-x
Calling: 1-x-555-x
"'x/[ZY4Z4]Aaf*::mr.+N}*

CJam解释器中在线尝试。

怎么运行的

30{     e# Repeat 30 times:

e# Push the following string:

"Crime predicted: x-x-x
Calling: 1-x-555-x
"

'x/     e# Split at x's.
[ZY4Z4] e# Push the array [3 2 4 3 4].
Aaf*    e# For each integer in that array, repeat [10] that many times.
        e# This pushes [[10 10 10][10 10][10 10 10 10][10 10 10][10 10 10 10]].
::mr    e# For each 10, select a random integer between 0 and 9 (inclusive).
.+      e# Vectorized concatenation.
        e# This places the digits at the spots of the x's.
N       e# Push a linefeed.
}*      e#

5

SS,121个 118 112字节

°/N=1°(30°/M°=ß$-ß$$'Crime predicted: 000-00-0000\nCalling: 1-000-555-0000\n\n'),'',3)µ€(M='0')?ß!G0,9,1):M)°)°)

基本上将0分别替换为一个随机数,并自称为30次。

使用在线终端对其进行测试:

sharps:~$ "<ctrl+v the code here>"                       
Crime predicted: 214-59-4707                              
Calling: 1-850-555-8529                                   

Crime predicted: 722-97-6832                              
Calling: 1-864-555-6965                                   

<and so on...>

Edit (112B): Using $$ (something like sprintf) & ternary operator.


Could you provide a link to this language's spec?
LegionMammal978

@LegionMammal978 Takes some time to write. In simple terms: Has every feature AutoIt has.
mınxomaτ

4

Pyth, 66

V30sX"Crime Predicted: v-w-x
Calling: 1-y-555-z
">5GmjkmOTdj32434T

Uses X to translate the last 5 letters of the alphabet (>5G == 'vwxyz') onto the 5 random numbers. Uses the same RNG as Sok found.

Try it online here


4

Pyth, 62

An implementation of Andrea's fantastic CJam answer.

sm?<Cd5jkmOTCdd*30"Crime Predicted: --
Calling: 1--555-

"

Note that there are several unprintable characters in the source, and there should not be a trailing ". That was added for SE so that it seems a bit more readable. I have not been able to get a hexdump yet, but the link below works and you should be able to copy-paste out of it.

Try it online here


3

CJam, 74 bytes

30{[ZY4Z4]{Aa*:mrs}%"Crime predicted: %s-%s-%s
Calling: 1-%s-555-%s

"e%}*

Not a winner, but it's at least somewhat close to what Dennis has so far, and it's using a different approach. So I thought it was worth posting anyway.

This uses the CJam e% operator, which generates output with a printf style format string.

30      Repeat count for whole output.
{       Start loop.
  [ZY4Z4] Build list of random number lengths: [3 2 4 3 4].
  {       Start loop over all random number lengths.
    Aa*     Build list of [10 ... ] with the random number length.
            E.g. for length 3, this will be [10 10 10].
    :mr     Apply the random number operator to the list. This will generate
            a list of random numbers between 0 and 9, with the given length.
    s       Convert it to a string.
  }%      End of loop over random number lengths.
  "..."   Format string, with a %s for each random number.
  e%      Apply printf style formatting.
}*      End of main repeat loop.

Woah, I thought you were @DavidCarraher with that avatar!
Beta Decay

@BetaDecay This? codegolf.stackexchange.com/users/3967/david-carraher. Not even the same animal! :) The colors are almost the same, though.
Reto Koradi

If we combine our approaches, we can get to 70 bytes: permalink
Dennis

@Dennis Feel free to go for it. You have helped me plenty of times.
Reto Koradi

@RetoKoradi Close enough ;)
Beta Decay

3

Matlab / Octave, 108 172 bytes

disp(sprintf('Crime predicted: %i%i%i-%i%i-%i%i%i%i\nCalling: 1-%i%i%i-555-%i%i%i%i\n\n',randi(10,1,480)-1))

Try it online


3

JavaScript (ES6), 142

Side note mixmat answer in ß shows a so better way to accomplish this task, and could easily implemented in JS giving a better score. I wish I had thought about it.

Edit Added the missing text (I misread the challenge)

Test running the snippet below in an EcmaScript 6 compliant browser

/* TEST redirect console.log */ console.log=x=>O.innerHTML+=x+'\n'

for(i=30;i--;)console.log(`Crime predicted: ${(R=d=>(1e-9+Math.random()+'').substr(2,d))(3)}-${R(2)}-${R(4)}
Calling: 1-${R(3)}-555-${R(4)}
`)
<pre id=O></pre>


Very nice solution! However, the last part of the phone number occasionally has less than 4 digits; same with the second and third parts of the SSN.
ETHproductions

@ETHproductions rats! Reverting to previous version!
edc65

3

Fourier, 166 142 bytes

45~d030(~i67a114a-9a+4a-8a32a112a^^a101ava+5a-6a116a101ava58a32a999roda99roda9999ro10a67a97a108aa-3a+5a-7a58a32a1oda999roda5oooda9999ro10aai^)

This has one of the highest byte counts, but I am a huge fan of Fourier and wanted to try my hand at a solution. Not very optimized.

Breaking it down:

45~d

Sets the variable d to 45, the ASCII code for a hyphen. This character is printed so much that it saves some bytes to declare it here.

030(...)

Sets the accumulator to zero and loops inside the parentheses until it reaches 30.

67a114a-9a+4a-8a32a112a^^a101ava+5a-6a116a101ava58a32a

Print "Crime predicted: ".

999roda99roda9999ro10a

Print a completely random SSN + newline.

67a97a108aa-3a+5a-7a58a32a

Print "Calling: ".

1oda999roda5oooda9999ro

Print a phone number that follows the guidelines: 1-xxx-555-xxxx

10aa

Print two newlines to start over.


1
Hey, you might be interested that there's now an online interpreter at fourier.tryitonline.net (and also labs.turbo.run/beta/fourier)
Beta Decay

2

Pyth, 67 bytes

V30s.ic"Crime predicted: |-|-|
Calling: 1-|-555-|
"\|mjkmOTdj32434T

The newlines are important, and are included in byte count. Try it out here.

                                Implicit: T=10, k=''
       "..."                    The output string
      c     \|                  Split on '|' placeholders
                     j32434T    32434 to base ten -> [3,2,4,3,4]
              m                 Map for d in the above:
                 mOTd             Generate d random numbers from 0-9
               jk                 Concatenate into string (join on empty string)
    .i                          Interleave segments of output string with random strings
   s                            Concatenate and output
V30                             Perform the above 30 times

2

Haskell, 150 bytes

import System.Random
p '#'=putChar=<<randomRIO('0','9')
p x=putChar x
main=mapM p$[1..30]>>"Crime predicted: ###-##-####\nCalling: 1-###-555-####\n\n"

2

JavaScript (ES6), 130 123 bytes

Taking minxomat's ß solution a step further, I've replaced the 0s with the number of 0s that would have been there. The code uses those numbers to pull the correct number of digits off of Math.random(), saving a good bit of bytes in the process.

for(i=30;i--;)console.log(`Crime predicted: 3-2-4
Calling: 1-3-555-4
`.replace(/[2-4]/g,x=>`${Math.random()}`.substr(2,x)))

Try it out:

// redirecting console.log() for this demonstration
console.log=x=>O.innerHTML+=x+'\n';
O.innerHTML='';

for(i=30;i--;)console.log(`Crime predicted: 3-2-4
Calling: 1-3-555-4
`.replace(/[2-4]/g,x=>`${Math.random()}`.substr(2,x)))
<pre id=O>

As always, suggestions welcome!


2

Java, 246 bytes

import java.util.*;class C{static{Random r=new Random();for(int i=0;i++<30;)System.out.printf("Crime predicted: %s-%s-%s\nCalling: 1-%s-555-%s\n\n",r.nextInt(900)+100,r.nextInt(90)+10,r.nextInt(900)+100,r.nextInt(900)+100,r.nextInt(9000)+1000);}}

With line breaks:

import java.util.*;
class C{
    static{
       Random r = new Random();
       for(int i = 0; i++<30;)
           System.out.printf("Crime predicted: %s-%s-%s\nCalling: 1-%s-555-%s\n\n",r.nextInt(900)+100,r.nextInt(90)+10,r.nextInt(900)+100,r.nextInt(900)+100,r.nextInt(9000)+1000);
    }
}

It's a start. Instead of producing random digits I used random 3-digit or 4-digit numbers.


2

R, 151 146 or 144 Bytes

Code

for(l in 1:30)cat(sep="","Crime predicted: ",(i=floor(runif(16,,10)))[1:3],"-",i[4:5],"-",i[6:9],"\nCalling: 1-",i[10:12],"-555-",i[13:16],"\n\n")

Test it online.

Ungolfed

for(l in 1:30) {
  i=floor(runif(16,,10))
  cat(sep="","Crime predicted: ",
      i[1:3],"-",i[4:5],"-",i[6:9],
      "\nCalling: 1-",i[10:12],"-555-",
      i[13:16],"\n\n")
  }

I think there is a lot of room to improve but I am no good messing with strings in R.

Edit 1: changed the runif(16,max=10) to runif(16,,10).

I've done another code (147 144 bytes) with sprintf but I don't think it is much a R-like code.

for(l in 1:30)cat(do.call(sprintf,as.list(c('Crime predicted: %s%s%s-%s%s-%s%s%s%s\nCalling: 1-%s%s%s-555-%s%s%s%s\n\n',floor(runif(16,,10))))))

Another approach (149 bytes):

for(p in 1:30)cat(sep="",replace(s<-strsplit("Crime predicted: '''-''-''''\nCalling: 1-'''-555-''''\n\n","")[[1]],which(s<"-"),floor(runif(16,,10))))

2

PHP, 144 143 Bytes

<?=preg_replace_callback('/x/',function($x){return chr(rand(48,57));},str_repeat("Crime predicted: xxx-xx-xxxx
Calling: 1-xxx-555-xxxx

",30));


2

C#, 280 263 246 bytes

Golfed:

using System;class C{static string G(){var r=new Random();var s="";n h=x=>r.Next(x).ToString("D"+x);for(int i=0;i++<30;){s+="Crime predicted: "+h(3)+"-"+h(2)+"-"+h(4)+"\nCalling: 1-"+h(3)+"-555-"+h(4)+"\n\n";}return s;}delegate string n(int x);}

Indented:

using System;
class C
{
    static string G()
    {
        Random r = new Random();
        string s = "";
        Func<int, string> f = x => r.Next((int)Math.Pow(10, x)).ToString("D" + x);            

        for (int i = 0; i++ < 30;)
        {
            s += "Crime predicted: " + f(3) + "-" + f(2) + "-" + f(4) + "\nCalling: 1-" + f(3) + "-555-" + f(4) + "\n\n";
        }
        return s;
    }
}

New on Codegolf, tips are welcome!


Welcome to Programming Puzzles & Code Golf! I'm not intimately familiar with C#, but since it's predicated on .NET like PowerShell is, I think the h(999) will generate a number from 000 to 998 inclusive, so that means this doesn't quite hit the spirit of the specifications. I ran into the same issue.
AdmBorkBork

You're right, I'll fix it now!
anthonytimmers

Went up to 280 bytes after the fix, then thought of doing the formatting in the delegate handler, reducing it back to 263 bytes.
anthonytimmers

1

Hassium, 230 Bytes

func main(){foreach(x in range(1,31){println("Crime predicted: "+r(3)+"-"+r(2)+"-"+r(4));println("Calling: 1-"+r(3)+"-555-"+r(4)+"\n");}}
func r(l){z=new Random();a="";foreach(y in range(1,l))a+=z.next(0,10).toString();return a;}

Expanded:

func main () {
        foreach (x in range(1, 31) {
                println("Crime predicted: " + r(3) + "-" + r(2) + "-" + r(4));
                println("Calling: 1-" + r(3) + "-555-" + r(4) + "\n");
        }
}
func r (l) {
        z = new Random();
        a = "";
        foreach (y in range(1, l))
                a += z.next(0, 10).toString();
        return a;
}

1

Ruby, 98 characters

30.times{puts"Crime Predicted: DEF-GH-IJKL
Calling: 1-MNO-555-QRST

".tr"D-OQ-T",rand.to_s[2..-1]}

Sample run:

bash-4.3$ ruby -e '30.times{puts"Crime Predicted: DEF-GH-IJKL\nCalling: 1-MNO-555-QRST\n\n".tr"D-OQ-T",rand.to_s[2..-1]}' | head
Crime Predicted: 867-29-2637
Calling: 1-278-555-5424

Crime Predicted: 913-31-6306
Calling: 1-744-555-8188

Crime Predicted: 868-36-4612
Calling: 1-926-555-3576

Crime Predicted: 988-06-1643

1

JavaScript, 146 141

console.log(Array(30).join("Crime predicted: 3-2-3\nCalling: 1-3-555-4\n\n").replace(/[2-4]/g,function(m){return(m+Math.random()).substr(3,m)}))

there is already answer in same language with less characters than yours.
Jakuje

@Jakuje the other answer uses ES6 which isn't widely available yet
Peleg

Then it is probably ok. Mentioning this in your answer would be good.
Jakuje

1
@Jakuje People can submit whatever they want! It's as much about the challenge as it is about beating others.
ErikE

1

pre-ES6 Javascript, 128

for(i=30;i--;)console.log('Crime predicted: x-x-x\nCalling: x-555-x\n'.replace(/x/g, function(){return 1e3*Math.random()|0}))

I feel like the dashes could be removed somehow, but not sure.


1
Several errors:1) random parts are not of correct length (and not even trying to) 2) missing "1-".
edc65

1

Pyth, 73 bytes

V30FGPc"Crime predicted: xxx-xx-xxxx\nCalling: 1-xxx-555-xxxx"\xpGpOT)pb"

Demo


1

Julia, 120 bytes

R(n)=lpad(rand(0:10^n-1),n,0)
for i=1:30 println("Crime Predicted: "R(3)"-"R(2)"-"R(4)"\nCalling: 1-"R(3)"-555-"R(4))end

Ungolfed:

# Define a function for returning a random number with a
# specified number of digits
function R(n::Int)
    lpad(rand(0:10^n-1), n, 0)
end

# Print 30 times
for i = 1:30
    println("Crime Predicted: " R(3) "-" R(2) "-" R(4)
            "\nCalling: 1-" R(3) "-555-" R(4))
end

1

Ruby, 90 88 bytes

30.times{puts"Crime predicted: NNN-NN-NNNN
Calling: 1-NNN-555-NNNN

".gsub(?N){rand 10}}

Try it online.


1
No need for string notation, just character ?N is enough. No need for parenthesis, around rand's parameter.
manatwork

1

PowerShell, 120 108 103 102 Bytes

0..29|%{("Crime predicted: XXX-XX-XXXX`nCalling: 1-XXX-555-XXX"-split"X"|%{$_+(Random 10)})-join'';""}

Shortened a few more bytes by setting the split-loop to instead be a code block that outputs to an array @(..) and is re-joined.

Eliminated the @ by remembering that (...) designates a code block executed before the -join'' anyway.

This eliminates needing to assign the $a variable. Also noticed that due to how the -split functionality works, the previous code was spitting out too many digits for the phone number, so got a free byte saving there by shrinking to 1-XXX-555-XXX. That made up for the erroneous Random 9 that actually picks random from 0-8, so we instead need to specify Random 10.

Sooo dang close to double-digits, but I'm not sure where it's possible to golf off another four 3 bytes ...


Previous, 108

0..29|%{$a="";"Crime predicted: XXX-XX-XXXX`nCalling: 1-XXX-555-XXXX"-split"x"|%{$a+="$_$(Random 9)"};$a;""}

Shortened the code a couple bytes by instead splitting a string on X's, then re-looping through the resultant array of strings and concatenating each entry with a Random digit to build our final output string $a. Note that we couldn't do something like "string".replace("x",$(Random 9)) because then the Random would only get called once, so you'd have 1-222-555-2222 for a phone number, for example.


Previous-er, 120

0..29|%{"Crime predicted: "+(Random 1e9).ToString("000-00-0000");"Calling: "+(Random 1e7).ToString("1-000-555-0000");""}

Pretty dang competitive for a verbose language, thanks to generous output specifications (i.e., 000-00-0001 is treated as a valid SSN) and the really robust .ToString() formatting algorithm that PowerShell uses. PowerShell also outputs \r\n after every string output, so the requirement for a newline in between iterations is just a simple "".

Note that this uses an implied Get- in front of Random, so this may be really slow on some platforms/implementations.


0

Befunge-98, 170

I think this can still be golfed down a bit. But at least I beat C#. Tested at befungius.aurlien.net.

a3*>  82*v>":detciderp emirC">:#,_$...'-,..'-,....av
>1 -:!#;_v^;v,,,"-555-"...,,,,,,,,,,,"Calling: 1-",<
\  ^v< <2?1v,
+    ^;^3<;<,
^ <0?3vv....<
^;^6<;<>a,v
   v_@#:-1<

0

Python 2, 151 150 bytes

from random import*
p="Crime predicted: xxx-xx-xxxx\nCalling: 1-xxx-555-xxxx\n\n"*30
while'x'in p:p=p.replace('x',str(randint(0,9)),1)
print p.strip()

As golfed as I could get this method.

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.