x∈92的正无穷穷t=x^5-5x 5[5 55/9 95/9^

这是个机器人猖狂的时代,请输一下验证码,证明咱是正常人~贺连星, 李毅, 李广成, 等. 无铅压电陶瓷材料研究进展[J]. 电子元件与材料, ): 52-55. HE Lianxing, LI Yi, LI Guancheng, et al. Electron Compon Mater (in Chinese), ): 52-55. [2] TAKENKA T, HUZUMI A, HATA T, et al. Mechanical properties of (BiNa)1/2TiO3-based piezoelectric ceramics [J]. Silic Ind, ): 136-142. [3] LI Y M, CHEN W, ZHOU J, et al. Dielectric and piezoelectric properties of lead-free (Na0.5Bi0.5)TiO3-NaNbO3 ceramics [J]. Mater Sci Eng B, : 5-9. [4] SAITO Y, TAKAO H, TANI T, et al. Lead-free pizoceramics [J]. Nature, : 84-87. [5] GUO Y, KAKIMOTO K, OHSATO H, et al. Dielectric and piezoelectric properties of lead-free Na0.5K0.5NbO3-SrTiO3 ceramics [J]. Solid State Commun, : 279-284. [6] LI Y M, WANG J, LIAO R, et al. Synthesis and piezoelectric properties of KxNa1-xNbO3 ceramic by molten salt method [J]. J Alloys Compd, /2): 282-286. [7] DAI Y J, ZHANG X W, CHEN K P. Morphotropic phase boundary and electrical properties of K1-xNaxNbO3 lead-free ceramics [J] Appl Phys Lett, 2905. [8] LI Y M, SHEN Z Y, JIANG L, et al. Microstructure, phase transition, and electrical properties of KxNa1-xNbO3 lead-free piezoceramics [J]. Mater Chem Phys, 2010, [9] ABRAHAMS S C, LEVINSTEIN H J, REDDY J M. Ferroelectric lithium niobate: polycrystal X-ray diffraction study between 24 ℃ and 1 200 ℃ [J]. J Phys Chem Solids, 19-1026 . [10] GUO Y, KAKIMOTO K, OHSATO H, et al. Phase transitional behavior and piezoelectric properties of (Na0.5K0.5)NbO3- LiNbO3 ceramics [J]. Appl Phys Lett, ): . [11] JAFFE B, COOK W R, JAFFE H. Piezoelectric Ceramics [M]. New York: Academic, . [12] EGERTON L, DILLON D M. piezoelectric and dielectric properties of ceramics in the system potassium-sodium niobate [J]. J Am Ceram Soc, 8-442. [13] HOLLENSTEIN E, DAVIS M, DAMJANOVIC D, et al. Piezoelectric properties of Li and Ta modified (K0.5Na0.5)NbO3 ceramics [J]. Appl Phys Lett, ): 182905. [14] WANG X X, TANG X G, KWOK K W, et al. Effect of excess Bi2O3 on the electrical properties and microstructure of(Bi1/2Na1/2)TiO3ceramics [J]. Appl Phys A, ): . [15] AKDO?AN E K, KERMAN K, ABAZARI M, et al. Origin of high piezoelectric activity in ferroelectric (K0.44Na0.52Li0.04)-(Nb0.84Ta0.1? Sb0.06)O3 ceramics [J]. Appl Phys Lett, 2908. [16] DAMJANOVIC D. A morphotropic phase boundary system based on polarization rotation and polarization extension [J]. Appl Phys Lett, ): 062906. [17] SHEN Z Y, LI J F. Enhancement of piezoelectric constant d33 in BaTiO3 ceramics due to nano-domain structure [J]. J Ceram Soc Jpn, : 940-943. [18] CROSS L E. Relaxor ferroelectrics [J]. Ferroelectrics, 1- 267. [19] FU J, ZUO R, WANG X, et al. Polymorphic phase transition and enhanced piezoelectric properties of LiTaO3-modified (Na0.52K0.48)? (Nb0.93Sb0.07)O3 lead-free ceramics [J]. J Phys D: Appl Phys, 2006. [20] SHEN Z Y, LI J F, WANG K, et al. Electrical and mechanical properties of fine-grained Li/Ta-modified (Na,K)NbO3-based piezoceramics prepared by spark plasma sintering [J]. J Am Ceram Soc, 78-1383.
被如下文章引用:
AUTHORS: ,,,,,
JOURNAL NAME:
Jan 20, 2016
ABSTRACT: 用传统固相烧结法制备(1-x)K0.49Na0.51NbO3-xLiNbO3(KNNLN,x=0.00~0.08,摩尔分数)体系无铅压电陶瓷。用X射线衍射仪及精密阻抗分析仪等研究不同掺量LiNbO3掺杂后对KNNLN体系陶瓷的晶体结构和电性能的影响。结果表明在研究组成范围内,LiNbO3加入后能够形成单一钙钛矿结构的固溶体。随着LiNbO3的掺量的增加,晶体结构从正交转变为四方结构,并且经过由正交至四方多型相转变的过渡组成区域0.05≤x≤0.06。在过渡组成区域的四方相边界x=0.06处能够获得优异的电学性能压电常数d33=246pC/N,相对介电常数εr=679,机械品质因子Qm=52,平面机电耦合系数kp=41.6%。由于该组成陶瓷具有很高的Curie温度TC=467℃,因此适合应用于高温场合。math - 9 Hole Challenge - Programming Puzzles & Code Golf Stack Exchange
to customize your list.
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.
Here's how it works:
Anybody can ask a question
Anybody can answer
The best answers are voted up and rise to the top
The 9 Hole Challenge
9 code golfing challenges of varying difficulty.
Penalties for using the same language more than once.
The question will be updated with pars, hole champions and trophy winners.
This comes from a competition I have with some friends, it's not the usual format, but I hope some of you will appreciate the different spin on it. Challenges, rules and trophies below.
Greenway (24)
f(c:string, n:integer)
Prints a line containing n instances of c.
Somewhere in the Rough (73)
f(t:string, s:string, n:integer) -& i
Where i is the index of the nth instance of s in t.
Curry for Dinner (6235)
f(x:function, y: function) -& g
Where g is a function that will call y, n
where n is the return value of x
f(p:string)
Writes to file at p and fills it with a randomly sized rectangle of random characters (ascii).
Treasure Hunt (75)
f(p:string, c:char) -& (x, y)
Reads file at p which contains a grid of symbols
and returns the x and y coordinates of the first instance of that symbol
within the grid, assume it exists.
Bridge on the River Kwai (179)
f(l:list[int])
Prints difference bridges diagram for l.
E.g for [1,7,3,17,1]
/+6\ /-4\ /+14\
Make sure that the spaces are created according to the size of the
number above. For a 3 digit long number, you are going to need 4 spaces
between the digits on the line below.
Catch: Somewhere, your code must spell trousers
(Must have at least 1 non-alphanumeric delimiters.
E.g. tr(ou,se)(rs)
Time Flies When You're Playing Golf (1157)
f(p:string) -& [h, m]
Reads file at p which contains an ASCII representation
of an analogue clock, where the hour hand is represented
with one lines, and the minutes by two. Output a list
containing two elements: the hours and minutes shown on
the clock. If only one hand is visible, assume both point
to that position.
Here are all the possible combinations for a hand.
These positions, respectively are (12, 1, 3, 5, 6, 7, 9, 11).
Assume that the other characters within the clock face are spaces.
Timber! ()
f(p:string) -& b:boolean
Where p is the path to a file with an ascii building in.
Blocks with white space underneath them will fall.
(Except from slashes, which stay in place if there is a stable block in the
opposite direction to the way they face). If the building is structurally integral
return true, otherwise return false. All non whitespace blocks
are counted as being solid and other than slashes, they all fall.
Structurally safe
Safe version
Slacker News (218)
f(s:string, r:string, p:string)
Gets the titles of the top 20 stories on Hacker News and changes all instances of s to r, then writes the new titles to a html file at p, where each title is contained within a h1 element.
The outputted file should something like this
&h1&Some title&/h1&&/h1&Some other title&/h1&...etc
You may not use the HN api.
You may not use Regex.
You may not use angle braces anywhere in your code.
Character count is the length of the function that will compile & run correctly. However you still need to submit the full code, including imports.
+10% for every repeated language in your submission. (E.g. If you use Ruby for 3 solutions, then your final score will be multiplied by 1.2). Different versions of the same language count still count as the same language.
Par will be average score for each hole.
Submit your solutions in one answer.
Your overall score is your character count + your language penalty, then round it up.
Gold Jacket - ( - 1290) Lowest overall score
Shooter - ( - 9) Most languages used
Bunker - Most above par score on any hole
Snakes on a Plane - ( - 1727) Highest python character submission in a single solution
Good Parts - ( - 255) Highest JS character count in a single solution
Shakey Steve - Shortest solution that uses interfaces
You're Not From Round Here - Shortest unique language solution that's language has the shortest wikipedia page.
Happy Gilmoore - ( - 31) Shortest solution that has the word 'alligator' in the code.
Unicycling Dwarf Magic - The default extensions of your 9 submission source files are a perfect anagram of a word in the Oxford Dictionary.
You are only eligible for a trophy once you have completed all 9 holes
Submissions
locked by ♦
This question exists because it has historical significance, but it is not considered a good, on-topic question for this site,
so please do not use it as evidence that you can ask similar questions here.
This question and its answers are frozen and cannot be changed.
More info: .
closed as off-topic by ♦
This question does not appear to be about programming puzzles or code golf within the scope defined in the .If this question can be reworded to fit the rules in the , please .
Score: 4651
2907 + 60% penalty
1. GolfScript - 14 characters
{*}:a;lligator
Usage: c n a e.g. "test" 3 a -> testtesttest
Happy Gilmoore
2. Python - 72 characters
def f(t,s,n,p=-1):
while n:p=t.find(s,p+1);n-=1 if p+1 else n
3. Javascript - 255 characters
Curry for Dinner
f(x:function, y: function) -& g Where g is a function that will call y, where n is the return value of x
function f(x, y) {
var g = function() {
var n = x();
for (var i = 0; i & ++i) {
Good Parts
4. Python - 132 characters
from random import randrange as r
def f(p):l=range(r(9));open(p,'w').writelines([''.join([chr(r(94)+33)for _ in l])+'\n'for _ in l])
5. Python - 89 characters
def f(p,c):
for y,d in enumerate(open(p).readlines()):
x=d.find(c)
if x+1:return x,y
6. Python - 189 characters
for i in 0,1:
for n,u in enumerate(l):
o=l[n+1] if len(l)&n+1 else id
if i:print u,' '*4,
elif o!=id:print' /'+('+' if o-u&0 else '')+str(o-u)+'sers'*0+'\\ ',
7. Python - 1727 characters
lines = open(p).read().split('\n')
# preprocess lines to ensure correct format
if len(lines) & 5:
for i, line in enumerate(list(lines)):
if 'o' in line:
if i == 0:
lines.insert(0, ' ' * 5)
lines.insert(0, ' ' * 5)
elif i == 1:
lines.insert(0, ' ' * 5)
while len(lines) & 5:
lines.append(' ' * 5)
# find characters that can only be the hour hand
for i, line in enumerate(lines):
if i == 0:
if '\\' in line:
elif '|' in line:
elif '/' in line:
elif i == 2:
if '--o' in line:
elif 'o--' in line:
elif i == 4:
if '/' in line:
elif '|' in line:
elif '\\' in line:
# find characters that might represent the minute hand
possible_minutes = []
for i, line in enumerate(lines):
if i == 1:
if '\\' in line:
possible_minutes.append(55)
if '|' in line:
possible_minutes.append(0)
if '/' in line:
possible_minutes.append(5)
elif i == 2:
if '-o' in line:
possible_minutes.append(45)
if 'o-' in line:
possible_minutes.append(15)
elif i == 3:
if '/' in line:
possible_minutes.append(35)
if '|' in line:
possible_minutes.append(30)
if '\\' in line:
possible_minutes.append(25)
HOUR_MINUTES = {
# remove minute hand that is actually hour hand
if len(possible_minutes) & 1:
not_minute = HOUR_MINUTES[hour]
if not_minute in possible_minutes:
possible_minutes.remove(not_minute)
assert(len(possible_minutes) == 1)
minute = possible_minutes[0]
h, m = hour, minute
return [h, m]
Snakes on a Plane
8. Python - 226 characters
e=q,t=e(),True
for l in open(p).readlines():
r,b,q=e(q),e(),e()
for i,c in enumerate(l):
if c.strip():b.add(i);q.add(i-1 if c == '/' else i+1 if c == '\\' else i)
if not r.issubset(b):t=False
9. Python - 203 characters
import urllib
def f(s,r,p):f,l,g=open(p,'w'),'\74','\76';[f.write(l+'h1'+g+t.replace(s,r)+'h1'+g)for i,t in enumerate(urllib.urlopen('http://x.co/3WYln').read().split('title'+g))if(i in range(2,42))&i%2]
Score: 1320
I've plenty to do to improve this score... Oh well, at least I avoided repeated-language penalties. :-)
1. Python (21 chars)
def f(c,n):print(c*n)
The "obvious" solution.
2. ECMAScript 6 (47 chars)
f=(t,s,n)=&t.split(s).slice(0,n).join(s).length
Finds the index in a bit of an unconventional way, by counting the length of the substring before it.
3. J (12 chars)
f=:2 :'v^:u'
The built-in conjunction ^: raises a function to a power (i.e. repeats a function a given number of times).
That is, f^:3 y = f (f (f y))).
However, it's overloaded to alos accept functions rather than integers, in which case it runs the function on the input to get the number of repetitions.
Unfortunately we need to flip the operands for the task, otherwise we'd have the consise
answer f=:^:.
4. C (95 chars)
#include &stdio.h&
#include &stdlib.h&
f(char*p){FILE*f=fopen(p,"a");for(int n=rand(),y=n*n;y--;y%n||putc(10,f))putc(rand()%94+32,f);}
This task leaves quite a bit of room for interpretation and abuse: is it okay to just output a random printable ASCII character and say it's a randomly-dimensioned rectangle with dimensions from the set {1}?
Probably not.
Anyway, I went with plain rand() but in reality you probably want to add %9 or something if you want to test it.
On my linux box I didn't have to flush the file in order for it to be written (I guess it flushes automatically on program exit), but I'm pretty sure you have to flush it to be standards-compliant, so feel free to add fflush(f); to the count here.
5. Haskell (100 chars)
import Control.Arrow
import Data.List
import Data.Tuple
import Control.Applicative
h p c=head.filter(p c.snd).zip[1..]
g c=swap.(id***fst.h(==)c).h elem c.lines
f p c=g c&$&readFile p
I like the repeated pattern between finding the row and the column (abstracted via h).
6. Lua (261 chars)
function f(s,m,y,...)if s and m then for i,v in pairs(m)do
io.write(v,(" "):rep(#tostring(s[i])))end print()elseif s then
r=unpack f(s,{"",f(trouse,r(s))})f({f(nil,r(s))},s)elseif y then
return ("/%s%d\\"):format(m&y and"+"or"-",math.abs(m-y)),f(s,y,...)end end
Makes use of multiple return values and recursion to deal with computing the differences.
It cost me a few
characters to match the sample output exactly (adding the right amount of spaces everywhere).
7. Go (307 chars)
func f(p string)[]int{var l[]string
g,_:=os.Open(p)
H,M,s,m:=0,0,bufio.NewScanner(g),[][]int{{-1,-1,11},{-1,0,12},{-1,1,1},{0,-1,9},{0,1,3},{1,-1,7},{1,0,6},{1,1,5}}
for s.Scan(){l=append(l,s.Text())}
for _,a:=range m{if l[2+a[0]*2][2+a[1]*2]!=' '{M=a[2]}
if l[2+a[0]][2+a[1]]!=' '&&(H==0||M!=a[2]){H=a[2]}}
return[]int{H,M}}
Could probably
I barely know Go.
8. CoffeeScript (+ node.js) (223 chars)
a=require('fs').readFileSync(p).toString().split "\n"
U=(i,j)-&a[i]?[j]and a[i][j]==' '
for l,i in a
for c,j in l
"/":[i+1,j-1]
"\\":[i+1,j+1]
return if U.apply(0,m[c]or m.a)
A bit of a cheap-shot since I already have JS.
Returns a falsy value (namely, undefined) or a truthy value (namely, 1) to indicate the answer.
9. Bash (254 chars)
curl /rss|
awk -Ftitle '{OFS="h1\76\n\74h1";ORS="";print substr(OFS,4);print$2,$4,$6,$8,$10,$12,$14,$16,$18,$20,$22,$24,$26,$28,$30,$32,$34,$36,$38,$40;print substr(OFS,0,3)}'|
do echo ${l//$1/$2};done|
(Newlines after pipes added for readability.)
Working around the restrictions with the shell was fun.
I realise there's probably a better way to do $2,$4,$6,..., but this was what I came up with anyway.
Score: 1,394.4
996 characters + 40% penalty
1. Greenway - Haskell, 19 chars
f c n=replicate n c
& f "hello" 5
["hello","hello","hello","hello","hello"]
2. Rough - PHP, 72 chars
function f($t,$s,$n){for($i=-1;$n--;$i=strpos($t,$s,++$i));return$i;}
3. Curry - JavaScript 1.8, 45 chars
f=function(x,y)function(){for(i=x();i--;)y()}
4. Spew - J, 43 chars
f=:3 :'((33+?(1+?2#100)$1#93){a.)fwrites y'
f 'file.txt'
5. Treasure - J, 64 chars
a=.freads x
b=.1+a i.u:10
e=.d,c-b*d
'file.txt' f 'c'
6. Bridge - Python, 166 chars
def f(l):J=''.t=r=lambda n:' '*len(n);s=t(str,l);o=['/%+d\\'%(y-x)for x,y in zip(l,l[1:])];print J(t(J,zip(t(r,s),o)))+'\n'+J(t(J,zip(s,t(r,o)+['users'*0])))
7. Time - Python, 205 chars
s=open(p).read();a=[s[:12],s[18:],s[11:15],s[15:18]];z=[0]*3
for l in(0,1):
for c in'/|\\':z[a[l].count(c)]=('|/'.find(c)+6*l)%12or 12
z[a[2+l].count('-')]=3+6*l
print[z[1]or z[2],z[2]*5%60]
Assumes lines are space padded to be five characters wide. Uses tabs for second indentation level.
8. Timber - Python, 190 chars
def f(p):g=open(p).readlines();C='\\/ ';return all(1-[x+2&len(g[y])or g[y][x+1]in C,x&1or g[y][x-1]in C,0,' '==g[y+1][x]][C.find(g[y][x])]for y in range(len(g)-1)for x in range(len(g[y])-1))
9. Slacker - Python, 192 chars
import urllib
def f(s,r,p):F=open(p,'w');d=urllib.urlopen('http://x.co/3WYmQ').read()[37:];o,c='\x3c\x3e';exec"d=d[d.find(o+'t')+7:];F.write(o+'h1'+c+d[:d.find(o)].replace(s,r)+o+'/h1'+c);"*20
Thanks to Tyzoid for the url shortener idea.
16.1k52470
Edit: Think I'll just submit this as is: 1290 total, no language repeats.
Greenway, C#
void g(string s,int n){while(n--&0)Console.Write(s);}
I decided to swap languages with #1 and #9. Totally worth 30 here for hundreds later.
Somewhere In The Rough, Python
I really shouldn't have used up such a good language on an easy problem. Also, how is this not part of any language's indexOf family of functions? I seem to always need this...
def f(t,s,n):return sum(map(len,t.split(s))[:n+1])+n*len(s)
Curry For Dinner, Lisp
I haven't touched lisp since that one week in college....
(defun f (c g)(loop for i from 1 to(funcall c)do(funcall g)))
Spew, Bash/shell utils
My bash-foo was never that good to begin with. I'll fiddle with this one later. BTW if you want it to finish faster, switch it over to /dev/urandom.
c=$(($RANDOM%9+9))
for i in $(seq $c);do
echo `tr -cd [:print:]&/dev/random|head -c$c`&&$1
Treasure Hunt, C
Probably one of the more C friendly problems. I interpreted "return two integers" as take a return array pointer as an argument. Warnings? What warnings? An int* is just as good as a FILE* =p.
void f(int*p,int c,int*r){int*f,t;*r=r[1]=0;f=fopen(p,"r");while(c-(t=fgetc(f))){*r=t-'\n'?*r+1:0;r[1]+=*r?0:1;}
Bridge on the River Kwai, Perl
I started learning perl while writing this one. (Better late than never!) I came into this wanting to do regex heroics, so I form the string as both layers of the bridge together, then use regexes with space replacements to form the two different lines.
sub f{@trouse=0..$#_-1;foreach $i(@trouse){$r.=sprintf("%d/%+d\\",$_[$i],$_[$i+1]-$_[$i])}$r.=$_[$#_]."\n";print$r=~s/(^|\\)(\d+)(\/|$)/$1.' 'x length($2).$3/print$r=~s/(\/[+-]\d+\\)/' 'x length($1)/egr}
Time Flies When You're Playing Golf, Java
You can only do so much to make java terse... It assumes the clock is space padded so each line is 5 spaces long.
public boolean p(int r,int m,String s){int c[]={1,1,0,-1,-1,-1,0,1};return s.charAt(6*c[(r+6)%8]*m+14+c[(r)%8]*m)!=' ';}
public int[]time(String c){int h=9,m=0,t[]={3,5,6,7,9,11,12,1};for(int i=0;i&8;i++)if(p(i,1,c))if(p(i,2,c))m=i;else h=i;if(h==9)h=m;m=(t[m]*5)%60;h=t[h];return new int[]{h,m};}
Timber! Javascript
It runs in chrome's console. I make no guarantees elsewhere =p. It requires that the lines be space padded out to the length of the longest line. I feel like this is a reasonable request of ASCII art.
function f(s) {s=s.split("\n")
d={};m={'/':-1,'\\':1};r=1
s.forEach(function(x){t={}
for(i=0;i&x.i++){if(x[i]!=' '){j=m[x[i]]?i+m[x[i]]:i
t[j]=1}}for(n in d){if(x[n]==' '){r=0}}d = t})
Slacker News, Ruby
def s(f,s,t)
IO.write(f,l+"h1"+r+URI.parse("").read().split('mhead')[0,20].map{|x|x[0,x.length-19].split(r).last.sub(s,t)}.join(l+"/h1#{r+l}h1"+r))
Had fun touching a few languages for a little bit...
Character counts obtained after removing unnecessary spaces/newlines but submission mostly kept readable.
Since the question is a mix of functions and programs I included only the body of the function where required...
Also some liberty taken with what the meaning of "return" is...
Total ~1719
1- Python (~20)
def f(c, n):
2- C (~109)
int f(char*t,char*s,int n){char*q=t;int l=strlen(s);for(i=0;i&n;++i){t=strstr(t, s)+l;}return(t-q-l);}
Readable version:
#include &string.h&
int f(const char *t, const char *s, int n)
char *start =
int l = strlen(s);
for(i = 0; i & ++i)
t = strstr(t, s) +
return(t - start - l);
3- Javascript (~56)
function(x, y) {return function() {for(i=0; i&x(); i++) y();}}
4- Rexx (~136)
f: Procedure
Parse arg p
w = random(1, 9)
h = random(1, 9)
Do y = 1 to h
Do x = 1 to w
Call CHAROUT p, d2c(random(32, 99))
Call LINEOUT p, ""
5- Scala (~290)
def f(p: String, c: Char) {
def sc(w: String, c: Char, x: Int, y:Int ): Boolean =
if(w.isEmpty) false else
if(w.head==c) {println(x, y); true} else sc(w.tail, c, x+1, y)
def sr(w: Array[String], c: Char, x: Int, y: Int)
if(!sc(w.head, c, 0, y)) sr(w.tail, c, 0, y+1)
sr(io.Source.fromFile(p).mkString.split('\n'), c, 0, 0)
6- C++ (~355)
void b(list&int& l) // trouser+s
auto i = l.begin();
while(j!=s.end()) d.push_back(*j++ - *i++);
j = d.begin();
ostringstream o[2];
for(auto i : l)
while(o[0].tellp()!=o[1].tellp()) o[1] && " ";
if(j != d.end())
while(o[0].tellp()!=o[1].tellp()) o[0] && " ";
o[0] && "/" && (*j&=0 ? "+" : "") && *j++ && "\\";
cout && o[0].str() && endl && o[1].str() &&
7- Go (~301)
Note this requires the clock to be padded (i.e. all lines are same length).
func f(p string)(h int,m int) {
var a=[8]int {0, 2, 4, 12, 16, 24, 26, 28}
var b=[8]int {7, 8, 9, 13, 15, 19, 20, 21}
var d=[8]int {11, 12, 1, 9, 3, 7, 6, 5}
c, e := ioutil.ReadFile(p)
if e==nil {
for i:=range a {
if c[a[i]]&32 {
for i:= range b {
if c[b[i]]&32 {
m=d[m]*5%60
8- Ruby (~259)
a,b = File.read(p).split(/\n/).reverse,Hash.new(1)
a.each_with_index {
l.split("").each_with_index {|k,j|
b[j] = b[j]|b[j-1]
b[j] = b[j]|b[j+1]
unless k==' '
if b[j]==0
9- bash/Unix hack (~193)
wget -qO - /rss | tr "\074\076" "\n" | grep -B1 /title | awk 'NR % 3 == 1' | head -21 | tail -20 | sed 's/$1/$2/' | awk '{ print "\074h1\076" $0 "\074/h1\076"}' & $3
Not really here to golf, but here's some Tcl, since the language needs more love:
set holes {
proc greenway {c n} {
puts [string repeat $c $n]
proc rough {t s n} {
set i [string first $s $t] ;# a bit wet
while {[incr n -1]} {
incr i [string first $s $t $i]
proc curry {x y} {
set n [uplevel 1 $x]
set body [string repeat "$y;" $n]
return [list apply [list args $body]]
proc spew {p} {
set w [expr {int(rand()*80)}]
set h [expr {int(rand()*80)}]
set f [open $p w]
for {set y 0} {$y&$h} {incr y} {
for {set x 0} {$x&$h} {incr x} {
append ln [format %c [expr {int(rand()*96+32)}]]
puts $f $ln
proc hunt {p c} {
set f [open $p r]
while {[gets $f line]&=0} {
set x [string first $f $c]
if {$x != -1} {
return [list $x $y]
proc bridge {l} {
set l [lassign $l m]
set top ""
set btm $m
foreach n $l {
set t "/[expr {$n&$m?"+":""}][expr {$n-$m}]\\"
append top "[string repeat \
[string length $m]]$t"
append btm "[string repeat \
[string length $t]]$n"
# trousers
return $top\n$btm
proc time {p} {
set f [open $p r]
while {[gets $f line] &= 0} {
set line [format %-.5s $line]
lappend c [split $line {}]
foreach {x y h} {
set 2 incr 2x $x
set 2 incr 2y $y
if {[lindex $c $2y $2x] != " "} {
} elseif {[lindex $c $y $x] != " "} {
if {![info exists $mm]} {
set mm $hh
set mm [expr {$mm*5}]
if {$hh == 0} {set hh 12}
list $hh $mm
proc timber {p} {
set f [open $p r]
set must {}
while {[gets $f line] &= 0} {
set line [format %-.5s $line]
foreach i $must {
if {[string index $line $must] eq " "} {
return false
set must {}
foreach c [split $line] {
switch $c {
"\\" {lappend must [expr {$i+1}]}
{lappend must [expr {$i-1}]}
{lappend $must $i}
return true
proc slacker {s r p} {
package require tdom
set f [open $p w]
set h [::http::geturl /]
set html [string trim [::http::data $h]]
::http::cleanup $h
set dom [dom parse $html]
lappend map , [string index $html 0]
lappend map . [string index $html end]
set root [$dom documentElement]
foreach n [$root selectNodes {//td[@class=title]/a}] {
set x [$n text]
set x [string map [list $s $r] $x]
puts $f [string map $map ",h1.$x,/h1."]
Mostly untested because writing these procs in half an hour is much more interesting than trying to properly engineer golf code.
Only had time to work on 1/2 of these.
You seem to want them in the form of a function and not a one liner.
So all of these are functions.
Testing code below the function.
sub f{print$_[0]x$_[1]}
&f("abc",5);
sub f{$i=-1;$n=$_[2];do{$i=index$_[0],$_[1],$i+1;$n--}while($n&0 && $i&-1);print$i+1}
&f("abcefgacefgabcefgabcefgabcefg","cef",4);
use Sub::C
curry f($x,$y){$q=0;foreach(1..&$x){$q=&$y};return $q;}
sub fy { return 1;}
sub fx { return 10;}
print&f(\&fx,\&fy);
use Crypt::PRNG qw(random_string_from irand);
sub f{open($o,"&$_[0]");$m=(irand)%10+1;map{printf $o "%s\n",random_string_from(['A'..'z'],$m)}(1..$m)}
&f('/tmp/t');
sub f{open($i,"&$_[0]");$x=$y=0;@l=&$i&;while($y&=$#l){$x=1+index$l[$#l-$y],$_[1];@a=($x,$y+1)if($x);$y++;}return\@a}
@b=@{&f('/tmp/t','f')};
print join(",",@b);
I'll work on 6-9 tomorrow.
WIP. Note, character counts may be off due to '\n' and wc
[1 Greenway] Mindf*ck, 54 characters
&&+[+&,-]&[&]&,&&++++++++[&&------&&-]&&[&[.&]&[&]&-]
Once the code is written, input your string, and terminate your string with a ^a (ctr+a), then immediately after, enter your number.
One caveat: the number given must only be from 0-9 (if you wish a larger one, the ascii value-48 of whatever character you input will be used as n)
Screenshot:
[3 Curry for Dinner] Javascript, 59 characters
function f(x,y){return function(){n=x();while(--n!=0)y();}}
[4 Spew] BASH, 56 characters
f(){ dd if=/dev/urandom of="$1" count=$((RANDOM%30+2));}
[7 Time Flies When You're Playing Golf] C, 334 Characters (412 with macro definition)
#define E(A) else if(s[A]==
#define G(A) else if(A)m=
#define M(A) &&m!=A)h=A
int (*f(char* s)){short h=0,m=0;if(s[0]=='\\')m=11;G(s[2]=='|')12;G(s[4]='/')1;G(s[11]=='-')9;G(s[15]=='-')3;G(s[22]=='/')7;G(s[24]=='|')6;G(s[26]=='\\')5;if(s[7]=='\\'M(11);E(8)'|'M(12);E(9)'/'M(1);E(12)'-'
M(9);E(14)'-'M(3);E(18)'/'M(7);E(19)'|'M(6);E(20)'\\'M(5);int* i=malloc(sizeof(int)*2);i[0]=(h==0)?m:h;i[1]=m*5;}
Note: this function returns a pointer to a two dimensional integer array, formatted like so:
{3, 55} (for a clock position of hour on 3, minute on 11)
[9 Slacker News] PHP, 246 characters
function f($a,$b,$c){$t=file_get_contents("http://x.co/3WQoY");$g=explode('d class="t',$t);$f=fopen($c,"w");for($i=1;++$i!=count($g)-10;){$e=explode("\x3e",$g[$i]);fwrite($f,"\x3ch1\x3e".str_replace($a,$b,s
ubstr($e[2],0,-3))."\x3c/h1\x3e\n");}}
Seperate/Original implementation in BASH+AWK, 218 characters
f(){ wget -qO- x.co/3WQoY|grep "e_"|awk '{n=split($0,a,"d class=\"t");for(q=1;++q!=n-10;){split(a[q],b,"\x3e");m=substr(b[3],0,index(b[3],"\x3c/")-1);gsub("'"$1\",\"$2"'",m);print "\x3ch1\x3e"m"\x3c/h1\x3e"
}}'&"$3";};
1. Greenway (Haskell - 37)
f x y=do print(concat(replicate x y))
2. Somewhere in the Rough (Mathematica - 43)
f[t_,s_,n_]:=StringPosition[t, s][[n+1, 1]]
3. Curry for Dinner (Lisp - 58)
(defun f(x y)(lambda()(dotimes(c(funcall x))(funcall y))))
4. Spew (Matlab/Octave - 83)
function x(f)
save f arrayfun(@char,randi(255,randi(255),randi(255)))
endfunction
5. Treasure Hunt (C - 176)
char* f(char* s,char c){FILE*char*int i=0,j=0,k=0;n=fopen(s,"r");while(!feof(n)){k=fgetc(n);if(k==(int)c)j++;if(k=='\n'){i++;j=0;}}sprintf(r,"%d %d",i,j);}
6. Bridge on the River Kwai (Ruby - 192)
trouse="\n%s"
rs = l[0].to_s
for i in 1..l.length-1
s = "/%+d\\"%(l[i]-l[i-1])
print " "*l[i-1].to_s().length+s
rs += " "*s.length+"%d"%l[i]
puts trouse%rs
7. Time Flies When You're Playing Golf (Node.js - 406)
function f(n){var g,h,m,q;fs.readFile(n,'ascii',function(e,d){l=d.split('\n');g=function(x,y){try{return l[x][y].trim()&&1;}catch(e){return 0;}};h=g(0,0)*11||g(0,2)*12||g(0,4)*1||g(2,0)*9||g(2,4)*3||g(4,0)*7||g(4,2)*6||g(4,4)*5;m=(g(1,1)&&h!=11)*55||(g(1,2)&&h!=12)*0||(g(1,3)&&h!=1)*5||(g(2,1)&&h!=9)*45||(g(2,3)&&h!=3)*15||(g(3,1)&&h!=7)*35||(g(3,2)&&h!=6)*30||(g(3,3)&&h!=5)*25||h*5%60;return [h,m];});}
8. Timber! (Go - 329)
func f(p string)bool{
x,_:=ioutil.ReadFile(p)
b:=strings.Split(string(x),"\n")
for j:=0;j&len(b)-2;j++{
for i:=0;i&len(b[j]);i++{
switch string(b[j][i]){
case " ": continue
case "/": r,o=0,-1
case "\\": r,o=0,1
if i+o&len(b[j]) && b[j+r][i+o]==' ' {
return false
return true
9. Slacker News (Python - 330)
def f(s,r,p):
w=urllib2.urlopen('')
a=[l.get_text() for l in BS(w).body("a") if l.find_parent("td", class_="title")]
t=lambda x:u"\x3c{}\x3e{}\x3c/{}\x3e".format(x,'{}',x)
m=''.join(t("h1").format(l.replace(s,r)) for l in a[:20])
with open(p,'w') as h:
h.write(t("html").format(m).encode('utf8'))
I’m a cheater & I ain’t played all 9 holes … yet. Nonetheless, here’s my hole 8, “Timber” solution in Perl (149 char).
One of my coworkers put this up as as a challenge at work. We’ve been having fun with it, especially me, since I have the lowest par solution so far!
Our rules were that it had to be a stand alone script that outputted true or false followed by a newline to STDOUT, and that no “shebang” was OK.
Below is the “minified” solution. I also put up a “” of the same that includes non-“minified” code & (often tortuously long) explanations of the reasoning behind my approach.
$r=open F,while(&F&){y/0/6/;s/^|\s|$/0/g;s#\\(?=0)|(?&=0)/|[^\\/0]#6#g;@n=split//;for(0..@n){!$n[$_]&&$l[$_]==6?$r=fals:1}@l=@n;}print$r,'e
I am too lazy to modify it according to the competition rules
Meh, but it works fine...
from numpy import *
import sys
def greenway(c,n):
def somewhereintherough(t,s,n):
while(count&n):
i = t.find(s,i+1)
def curryfordinner(x,y):
for i in range(x()):
def spew(p):
f = open(p,'w')
n = random.randint(1,28)
for i in range(n):
f.write('\n')
str1 = ''.join([chr(random.randint(32,126)) for _ in range(n)])
f.writelines(str1)
print "Grid size: ",n,'x',n
def treasurehunt(p,c):
f = open(p,'r')
arr = f.readlines()
n = len(arr)
f = open(p,'r')
found=False
for i in range(n):
line = f.readline()
#print line
loc = line.find(c)
if(loc!=-1):
print c,"found in",p,"at",i,loc
found=True
if(not found):
print c,"not in",p
def bridgeontheriverkwai(l):
str_list = []
for i in range(len(l)-1):
sign = '+' if l[i+1]-l[i]&0 else '-'
str_1 = '/'+sign+str(abs(l[i+1]-l[i]))+'\\'
sys.stdout.write(' '*(len(str(l[i])))+str_1)
str_list.append(str_1)
for i in range(len(l)):
if i&len(l)-1:
print str(l[i])+' '*(len(str_list[i])-1),
print l[i]
def timeflieswhenyoureplayinggolf(p):
f = open(p,'r')
#clock = [[0]*5,[0]*5,[0]*5,[0]*5,[0]*5]
line1 = f.readline()
line2 = f.readline()
line3 = f.readline()
line4 = f.readline()
line5 = f.readline()
if line1.find('\\')!=-1:
elif line1.find('|')!=-1:
elif line1.find('/')!=-1:
elif line5.find('/')!=-1:
elif line5.find('|')!=-1:
elif line5.find('\\')!=-1:
elif line3[4]=='-':
elif line3[0]=='-':
if line2[1]=='\\' and h!=11:
elif line2[3]=='/' and h!=1:
elif line3[1]=='-' and h!=9:
elif line3[3]=='-' and h!=3:
elif line4[1]=='/' and h!=7:
elif line4[3]=='\\' and h!=5:
elif line2[2]=='|' and h!=12:
elif line4[2]=='|' and h!=6:
def timber(p):
f = open(p,'r')
linecount=0
line_size = 0
line = f.readline()
while(line):
linecount+=1
line_size = max(line_size,len(line)-1)
line = f.readline()
block = array([[0]*line_size]*linecount)
for i in range(linecount):
line = f.readline()
for j in range(len(line)-1):
if(line[j]==' '):
block[i][j]=0
elif(line[j]=='/'):
block[i][j]=1
elif(line[j]=='\\'):
block[i][j]=2
block[i][j]=3
for i in range(linecount):
for j in range(line_size):
if(block[i][j]==1 and j!=0 and block[i][j-1]==3):
block[i][j]=4
for j in range(line_size-1,0,-1):
if(block[i][j]==2 and j!=line_size-1 and block[i][j+1]==3):
block[i][j]=4
for i in range(linecount):
for j in range(line_size):
if(block[i][j]==3 and i&linecount-1 and block[i+1][j]==0):
print "Unsafe Structure"
print "Safe Structure"
def slackernews(s,r,p):
import urllib2
response = urllib2.urlopen('')
html = response.read()
titles_list = []
index_list =
while(count&21):
ix = html.find("&td class=\"title\"",ix+1)
index_list.append(ix)
for i in range(len(index_list)-1):
line = html[index_list[i]:index_list[i+1]]
line = line[line.find("a href"):]
start = line.find('&')
end = line.find('&')
titles_list.append(line[start+1:end])
f = open(p,'w')
for title in titles_list:
title = title.replace(s,r)
f.write('&h1&'+title+'&/h1&')
print "Done writing, Check : ",p
greenway('test!',2)
s='this is a cat. this is a dog. dog is an animal, animal is a beast in disguise.'
ix=somewhereintherough(s,t,8)
print ix,s[ix:]
print ' !y_called! '
g = curryfordinner(x,y)
spew('test.dat')
treasurehunt('test.dat','a')
bridgeontheriverkwai([-7,-22,6,9])
timeflieswhenyoureplayinggolf('clock.dat')
timber('block.dat')
slackernews('a','b','slacker.html')
First code golf!
(Still a work in progress...)
1. Greenway
Language: Python 3.2.3
File size: 23 bytes
def f(c,n): print(c*n)
3. Curry for Dinner
Language: Python 3.2.3
File size: 64 bytes
def f(x,y):
for i in [1]*x(): y()
Another work in progress here, and I'm at work so I'll head back later.
Greenway in Ruby (14 characters, 24 with #alligator), call with f.(c, n)
f=-&c,n{p c*n}#alligator
Screenshot
Somewhere in the Rough in CoffeeScript (38 characters)
f=(t,s,n)-&t.split(s,n).join(s).length
Screenshot
Curry for Dinner in JavaScript (54 characters)
f=function(x,y){return function(){for(i=x();i--;)y()}}
Screenshot
Spew in PHP (111 characters)
This requires short_open_tag in the PHP configuration file to be enabled. Otherwise the opening delimiter should be &?php, the @ symbols are used to silence PHP_NOTICE errors that are thrown for avoiding enclosing rand in quotes, and for not explicitly declaring the $s variable. This will generate a square grid of ascii characters between 4 and 30 characters on both axis.
&? @$r=$x=$r(4,30);for($i=$x*$x;--$i;){@$s.=$i%$x!=0?chr($r(33,126)):"\n";}file_put_contents($argv[1],$s);
Screenshot
1. Greenway (Python 2: 20)
def a(x,n):print x*n
Example input: a("asdf",3) -> string(asdfasdfasdf)
2. Somewhere in the Rough (Python 2: 47)
def b(t,s,n):return len(s.join(t.split(s)[:n]))
Example input: b("1,2,333,4,5,6",",",3) -> int(7)
3. Curry for Dinner (Javascript: 61)
function c(a,b){d=a();return function(){while(d){d--;b()}};};
Example input: function z(){ return 3; }; function y(){ console.log( '1' ) }; myfunc = c(z,y); myfunc(); -> logs string(1) to the console... 3 times.
As per the specs, c returns a function, and doesn't actually execute that function itself.
4. Spew (C++11: 171)
#include&fstream&
void d(string f){int i=rand()%10;int j=rand()%10;o.open(f);for(int x=0;x&i;x++){for(int y=0;y&j;y++){o.put(rand()%256);}}}
Not actually tested this, but should work.
Some indentation is left intact for readability but it was taken out when counting characters. The total is around 1227. Or not, I forgot a problem. 1486 1465 characters.
1. MIPS ASM (55 chars)
#a0 : the address of the null terminated string.
#a1 : the repetition count.
addi $a1,$a1,-1
bne $a1,$0,f
2. Scheme (52 chars)
(define (f t s n)(list-ref(string-search-all s t)n))
3. F# (39 chars)
let f x y=fun()-&for i in 1..x() do y()
4. Powershell (133 chars)
Function f($p){
$r=(Get-Random)%100
$z="";for($b=$r*$r;$b -gt 0;$b--){$z+=[char](33+(Get-Random)%94);if($b%$r -eq 1){"$z"&&$p;$z=""}}
5. C++ (184 152 chars)
#include &istream&
#include &string&
int*f(std::string p,char c){int*x=new int[2]();std::ifstream i(p);for(;i&&p;x[1]++)if((x[0]=p.find(c))&0)}
6. C# (291 282 chars)
static void f(List&int& l)
var z = "";
var o = l[0].ToString();
for (int j = 1; j & l.Cj++)
int p = l[j-1];
int i = l[j];
var q = "/"+(i-p&0?"":"+")+(i-p).ToString()+"\\";
o += new String(' ',q.Length)+i.ToString();
z+=new String(' ',p.ToString().Length)+q;
Console.Out.Write(z+"\n"+o);
7. Haskell (318 306 chars)
I was looking for an excuse to try out Haskell. I thought I was clever by generating the list of positions via combinations of numbers, but with the number of characters it took I could have hard coded the damn thing. Oh well. The code is atrocious but it was fun to write anyway.
edit: Fixed so it correctly returns minutes.
w i s=[s!!(j!!1)!!(j!!0)/=' '|j&-mapM(const i)[1,2],j/=[2,2]]
k[e,r](i,o,n)|i&&o=[e, n]|i&&not o=[n, r]|not$o||i=[e, r]
g s=let[h,m]=foldl k[0,0](zipWith3(\x y z-&(x,y,z))(w[1,2,3]s)(w[0,2,4]s)[11,9,7,12,6,1,3,5])in let u=mod(m*5)60 in if h==0 then[m,u]else[h,u]
s&-readFile p
return$g$lines s
8. Lua (259 chars)
I was surprised to find that strings didn't support array style indexing, so I had to rely on sub.
function f (p)
s=' ' g=''
for l in io.open(p):lines() do l=l..s:rep(#g-#l) for v=1,#g do
d=({['/']=v-1,['\\']=v+1,[s]=0})[g:sub(v,v)] or -1
if l:sub(v,v)==s and (d&0 or d&0 and g:sub(d,d)==s and l:sub(d,d)==s) then
return false
end g=l end
return true
9. Python (187 chars)
Thanks to grc/Tyroid for the url shortener.
import urllib2
def f(s,r,p):[open(p,'a').write('\074h1\076'+i.split("\074")[0].replace(s,r)+'\074/h1\076') for i in urllib2.urlopen("http://x.co/3WYmQ").read().split("\074title\076")[2:]]
Not the answer you're looking for?
Browse other questions tagged
The week's top questions and answers
Important community announcements
Questions that need answers
By subscribing, you agree to the
Programming Puzzles & Code Golf Stack Exchange works best with JavaScript enabled

我要回帖

更多关于 2的正无穷 的文章

 

随机推荐