text:
Generate Random Boggle Board
Generate a 4x12 grid of letters / spaces:
Each die should appear precisely once, location randomly chosen.  Locations should be approximate a uniform random permutation of the dice.  Display a random (again, approximately uniform) face of each die.  Left-justify the face in the 3-character window.  For example,
A  E  A  A
E  C  D  E
D  A  Qu E
E  A  H  D

Is a non-randomized board in the format I want.  Trailing space is allowed.
The dice:
A  A  E  E  G  N
E  L  R  T  T  Y
A  O  O  T  T  W
A  B  B  J  O  O
E  H  R  T  V  W
C  I  M  O  T  U
D  I  S  T  T  Y
E  I  O  S  S  T
D  E  L  R  V  Y
A  C  H  O  P  S
H  I  M  N  Qu U
E  E  I  N  S  U
E  E  G  H  N  W
A  F  F  K  P  S
H  L  N  N  R  Z
D  E  I  L  R  X

Amusing fact: there is only 1 K in the set.  What other letter exclusively shares that die?
This is code-golf so the program with the shortest bytecount wins!

there can't be F's if there are K's. this means you can't spell f...iretruck! :P

@Blazer: Yeah, and you can't spell f...olk either. :P

@Ry- or f......lock

GolfScript, 116 bytes
Since the scoring is in bytes, I figure that means we can use all bytes in the solution.  Going outside the printable ASCII set allows a somewhat shorter solution than Peter Taylor's, at the cost of making the code harder to display here.  Without the unprintable data, my code looks like this:
'57 BYTES OF BINARY DATA HERE'256base 26base 6/{;9.?rand}${6rand=65+.81='  u '2/=}%8/n*

It's pretty similar to Peter Taylor's solution, and I admit to shamelessly borrowing bits of it (such as the .81='  u '2/= trick), although I think I managed to shorten his shuffle slightly, even after spending an extra char byte for better randomness.
The binary string in the beginning of the script contains unprintable characters, and so cannot be directly pasted here.  Instead, I'll provide the script as a hex dump:
0000000: 2701 8302 7c56 97d5 ec9c 52e3 462e 44d7  '...|V....R.F.D.
0000010: a8d2 81c9 6115 fc80 4da4 6cd3 b06f a6d8  ....a...M.l..o..
0000020: 4e7e 2029 12a9 f331 0b83 3481 de36 81e2  N~ )...1..4..6..
0000030: 41b4 534d dee8 13f7 ccfd 2732 3536 6261  A.SM......'256ba
0000040: 7365 2032 3662 6173 6520 362f 7b3b 392e  se 26base 6/{;9.
0000050: 3f72 616e 647d 247b 3672 616e 643d 3635  ?rand}${6rand=65
0000060: 2b2e 3831 3d27 2020 7520 2732 2f3d 7d25  +.81='  u '2/=}%
0000070: 382f 6e2a                                8/n*

On Linux, or any system with the xxd utility installed, this hex dump can be turned back into a working 116-byte GolfScript program by passing it through xxd -r.
Edit: Replaced 999rand with 9.?rand for much better randomness.  The shuffle should now be about as close to perfect as the underlying RNG allows.

Ah - I'd forgotten that you can sort by a mapping.

Python 2.7, 253 229 215 chars
from random import*
j=0
for x in map(choice,sample("AAEEGN ELRTTY AOOTTW ABBJOO EHRTVW CIMOTU DISTTY EIOSST DELRVY ACHOPS HIMNQU EEINSU EEGHNW AFFKPS HLNNRZ DEILRX".split(),16)):j+=1;print x+' u'[x=='Q']+'\n'[j%4:],

Most of the characters are just the dice themselves. I didnt want to spend too much time trying to reduce it too much
minor edit: removed 2 unnecessary bytes (extra spaces)
edit2: down to 229
edit3: down to 215

you can make your code tighter with indexing, print a+' u'[a=='Q'] and print'\n'[j%4:]

@keith thanks! I made it even tighter by combining those two tricks :)

I managed to get it down to 218 without killing it (I think?): 1) Change the import statement to from random import* and remove all r.. 2) Change separators in string to   (space) and take advantage of str.split's default argument. 3) Get rid of anything to do with j and use '\n'[len(d)%4:]. 4) Use list.pop's default argument. 5) ... 6) Profit!

@D C ahh thanks! I'm surprised I overlooked them. but I guess that's what I get for writing it in a few minutes :P

And I reduced it even more by 3 chars using a little map trick, but I had to keep the j=0...+'\n'[j%4:] for it to work

GolfScript (141 139 137 charsbytes)
Of which 94 expand to the string containing the dice. Figure doesn't include the unnecessary newline inserted to make it wrap so that the code can be seen without scrolling:
'Y
ISY
XIAOOW
VYAAEEGNABBJOOEHRTVWCIMOTUEIOSSTACHOPSHIMNQUEEINSUEEGHNWAFFKPSHLNNRZ'n/'TTELRD'*
6/{[6rand=99rand\]}%${1=.81='  u '2/=}%8/n*

If my (by hand) analysis is correct there aren't any other strings which are both long enough and frequent enough to compress the data by simple replacement, regardless of ordering of dice and within dice.

I was able to get the table down from 96 to 84 characters by interleaving the dice and using run-length encoding.  Decoding that might make up the difference... it sure does for python.

You can encode 6 letters in 30 bits, then in 5 printable characters , saving 16 bytes. But you'll need some shift/mask to extract them.

@ugoren, Ilmari already did that.

@PeterTaylor, if you say he did, I believe you (I never bothered to learn Golfscript). But he seems to be using 57 unprintable characters, while I suggested 80 printable.

@boothby, I can get it down to 77 chars, but the decoding leaves it 4 chars behind my current approach.

Using upper / lowercase, you can do a '1 or 2' runlength encoding.  There's probably some room for improvement... but I packed the dice down to 73 chars.

Ruby, 201 197 chars
%W(AAEEGN ELRTTY AOOTTW ABBJOO EHRTVW CIMOTU DISTTY EIOSST DELRVY ACHOPS HIMNQU EEINSU EEGHNW AFFKPS HLNNRZ DEILRX).sample(16).map{|c|c[rand 6]}.each_slice(4){|x|puts x.join("  ").gsub(/Q ?/,"Qu")}

(and it's a one-liner)
Edit 1: Used %W() to avoid the .split and a pair of quotes.
Edit 2: Made it to spec (two spaces between each output column)

I just approved an edit by "an anonymous user" to this answer; I assume that was you, Mark, and you just forgot to log in.  (Ps. You output doesn't seem to be exactly to spec; using x.join("  ").gsub(/Q ?/,"Qu") would fix that at the cost of three extra chars.)

(That's one extra space in the join string and an extra space and question mark in the regex, in case the SE software mangles the spaces...)

@IlmariKaronen Thanks, I didn't notice the two spaces between columns. It should be to spec now.

Powershell, 234 characters
$d=(0..15|%{@{'AAEEGNELRTTYAOOTTWABBJOOEHRTVWCIMOTUDISTTYEIOSSTDELRVYACHOPSHIMNQUEEINSUEEGHNWAFFKPSHLNNRZDEILRX'[6*$_+(random)%6]=random}.GetEnumerator()}|sort Value|%{$_.Key})
0..3|%{($d[($_*4)..($_*4+3)])-join"   "-replace'Q ','Qu'}

Here's the same code with extra whitespace, in an attempt at improving readability :-)
#########################################
# roll the 16 dice and shuffle them     #
#########################################

$d=(
        0..15 | % {
                    @{
                       'AAEEGNELRTTYAOOTTWABBJOOEHRTVWCIMOTUDISTTYEIOSSTDELRVYACHOPSHIMNQUEEINSUEEGHNWAFFKPSHLNNRZDEILRX'[6*$_+(random)%6]=random
                     }.GetEnumerator()
                  } | sort Value | % {
                                        $_.Key
                                     }
    )

############################################
# add the 16 results to the 4 by 4 grid    #
############################################

0..3 | % {
            ($d[($_*4)..($_*4+3)]) -join "   " -replace 'Q ','Qu'
         }

I'm not aware of a built in shuffle feature in powershell, so I turned each result into a key-value pair - the key equalling a dice result and the value equalling a random number. Then it was just a case of sorting these pairs by the value then outputting the keys.

maybe you could use the last digits in the current time in ms as a sorting value?

@Blazer - possibly, but "random" only takes six characters :-)

Perl, 179 chars
@d=(Qu,map"$_ ",HIMNUAAEEGNELRTTYAOOTTWABBJOOEHRTVWCIMOTUDISTTYEIOSSTDELRVYACHOPSEEINSUEEGHNWAFFKPSHLNNRZDEILRX
=~/./g);print+(splice@d,6*int rand@d/6,6)[rand 6],@d%24?$":$/while@d

Here's a verbose version of the program:
my $fullset = "HIMNUAAEEGNELRTTYAOOTTWABBJOOEHRTVWCIMOTUDISTTY"
           . "EIOSSTDELRVYACHOPSEEINSUEEGHNWAFFKPSHLNNRZDEILRX";
my @dice = ("Qu");
push @dice, "$_ " for split //, $fullset;
while (@dice) {
    my @die = splice @dice, 6 * (int rand @dice / 6), 6;
    print $die[rand 6];
    print @dice % 24 ? " " : "\n";
}

Vyxal, 85 bytes
«3꘍Ẋʀɖ>¯ɖ\4ȧḊ#⅛F>ẇ#₂⟑†ql~-ṡ²<vŻ%)∆₆U÷↵ʁʀeµṘbD{⇧½⁰ṙ⟩ĊI3≥⁰?λ«16/v℅Ṗ℅4ẇƛ÷W‛  j;⁋⇧‛Q ‛QuV

Don't try it Online! Because it breaks the interpreter trying to handle 16! permutations of the dice at once. Would work given enough memory + time though.  Try this one that doesn't shuffle online!
«...«                           # Compressed string
     16/                        # Into 16 pieces
        v℅                      # Random choice from each
          Ṗ℅                    # Shuffle
            4ẇ                  # Split into four pieces
              ƛ      ;          # Foreach...
               ÷W               # To list of characters
                 ‛  j           # Joined by double spaces
                      ⁋⇧        # Joined by newlines and uppercased
                        ‛Q ‛QuV # Replace `Q ` with `Qu`

Batch 252 bytes
Note: script = 243 bytes + 9 bytes required to invoke script with Delayed expansion enabled from cmd.exe:
Cmd/Von/Cboggle.bat

boggle.bat
@Set c=0&For %%G in (AAEEGN ELRTTY AOOTTW ABBJOO EHRTVW CIMOTU DISTTY EIOSST DELRVY ACHOPS HIMNQU EEINSU EEGHNW AFFKPS HLNNRZ DEILRX)Do @Set D=%%G&Set/ac+=1&For /f %%i in ('Set/A!random!%%6')Do @<nul Set/p=!D:~%%i,1! &If !c!==4 (Echo(&Set c=0)

Perl 5, 157 bytes
@d{JobaotwHTVErHnZlRIXDeLtYrDELVyDItsHOPCafKPsIeUneagWeHnQUHImCIOUtEOsI=~s/[a-z]/\U$&$&/gr=~/.{6}/g}++;print$_=(/./g)[rand 6],/Q/?u:$",++$-%4?$":$/for keys%d

Try it online!
Explanation
This solution builds up the dice from the long string, replacing occurrences of lowercase letters with two of their uppercase companions (s/[a-z]/\U$&$&/gr) resulting in an ordering of 16 sets of 6 characters (/.{6}/g) which are then used as hash keys and set to 1 (@d{...}++). Since keys aren't stored in a particular order in Perl, this gives the ordering of the dice the required randomness.
Then for each of the keys in %d, print a randomly selected char from the list, either u or $" (which defaults to space) depending on whether or not the randomly selected letter was Q, and either $" or $/ (which defaults to newline) depending on whether or not we're working on a multiple of 4.
I quite enjoyed playing with the ordering to maximise saved characters, making sure that each dice ends with a letter that the next starts with and keeping other doubles in the middles of each set of 6. 68 bytes of data, but the decoding is a little expensive. Maybe it'll help someone else though!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Implement Oplop
Oplop is an algorithm to generate website specific passwords based on a master password and a keyword.
It is described here: http://code.google.com/p/oplop/wiki/HowItWorks
There's an online implementation here: https://oplop.appspot.com/
My attempt in Q is 204 200 167 165 139 characters ignoring whitespace:
{d:.Q.A,.Q.a,(n:"0123456789"),"-_";
b:d 2 sv'6 cut(,/)0b vs'(md5 x,y),2#0x00;
i:b in n;j:i?1b;k:(j _i)?0b;
8#$[0=0+/i;"1";8>j;();b j+(!)k],b}

EDIT: I achieved significant character savings by removing some redundant code from my Hex->Base64 conversion.
2012.03.07 - Cut out 2 more characters
2012.03.11 - Removed duplication and got accurate char count
2012.03.20 - Down to 141
Criteria
Candidate functions/implementations should take two strings as arguments and return an 8 character password as defined in the algorithm.
Judging
Code golf so shortest code takes the prize.

When will the judging be done?

I'll give it until the end of the month. 2012-04-01 00:00:00.000

Imho, the problem description should be complete in that way, that an average programmer knows what to do. So you should name the steps to generate the code, while it is to the user to find out how to md5sum or to base64encode something. A website for further details is welcome, of course. Preparing a challenge on meta or in chat is - btw. - recommended.

Ruby (113 110 chars)

require 'digest'
b=Digest::MD5.base64digest(ARGV.join)
puts "#{b} 1".sub(/(^\D{8,}(\d*))/,'\2\1')[0..7].tr'+/','-_'

require'digest'
b=Digest::MD5.base64digest(ARGV.join)
puts"#{b} 1".sub(/(^\D{8,}(\d*))/,'\2\1')[0,8].tr'+/','-_'

I notice that all the non-Python languages have to do a translation of the + and / to be - and _, respectively. It seems that Python's base64 is different/wrong?

There are several variants for different applications where different characters need escaping. Note that the Python method used is called urlsafe_b64encode

Python - 198 166 152 150

import base64,md5,sys,re
b=base64.urlsafe_b64encode(md5.md5(sys.argv[1]+sys.argv[2]).digest())
r=re.findall('\d+',b)if all(not c.isdigit()for c in b[:8])else['']
print((r[0]if len(r)else'1')+b)[:8]

import base64,md5,sys,re
b=base64.urlsafe_b64encode(md5.md5("".join(sys.argv[1:])).digest())
print((''if re.search('\d',b[:8])else re.findall('\d+',b+'1')[0])+b)[:8]

import base64,md5,sys,re
b=base64.urlsafe_b64encode(md5.md5("".join(sys.argv[1:])).digest())
print(re.findall('(?:[^\d]{8,}(\d*)|)',b+' 1')[0]+b)[:8]

This was a fun one. Could be a lot shorter if not for the verbosity of the md5 and base64 modules. The third and fourth lines are the interesting ones. My favourite trick was using a list containing only an empty string to avoid having to use any real if statements.
EDIT: Had to change from checking c.isalpha() to not c.isdigit() (added 4 characters)
EDIT: Shaved off 32 characters. Many thanks to Ugoren!
EDIT: Shaved off 14 more chars again many thanks to Ugoren. Used some regex trickiness
print(re.findall('(?:[^\d]{8,}(\d*)|)',b+' 1')[0]+b)[:8]

instead of
print((re.findall('^[^\d]{8,}(\d*)',b+' 1')+[''])[0]+b)[:8]

To save three chars.

This seems to give incorrect values for some input eg. (a,aaaa)

Oh shoot, I know why. I'll update in a second, thanks for catching that.

Small improvements: "".join(sys.argv[1:3]) (or even [1:]), if r can replace if len(r) (I think), re.match('^[^\d]{8}',b).

Also - r=re.findall('\d+',b+' 1') allows you to remove the if-else later (and then you don't need r). And reversing if-else on line 3 allows using re.match('\d',b[:8]) instead of my above suggestion.

Nice tips, shaved off 32 characters, thanks!

Save a few more characters: print((re.findall('[^\d]{8,}(\d*)',b+' 1')+[''])[0]+b)[:8]. It's maybe possible to replace +[''] with some RE stuff. Also, b+'1' is a bug (if b ends with a digit).

Thanks a second time, you're a regex master. I did manage to shave off a single character from your expression though.

Very nice. I'm not sure how it works exactly - when there are no digits in b, findall returns ['', '', '1', ''], which ends up OK. But you can drop () around findall to round the score down.

Oh weird, I didn't notice that (I was always testing with the [0] I guess). Although for me it just returns ['1','']. Wouldn't it break if it returned what you said there?

Shell - 116
echo -n $1$2|md5sum|xxd -r -p|base64|sed -re'y!+/!-_!;/^.{0,7}[0-9]/!{s/^([^0-9]*)([0-9]+)/\2\1/;t;s/^/1/}'|cut -c-8

Depends on cut, md5sum and base64 from coreutils, xxd and GNU sed.

PHP (126)
function f($m,$n){return substr(preg_replace('/^\D{8,}(\d+)/','$1$0',strtr(base64_encode(md5($m.$n,1)),'+/','-_').' 1'),0,8);}

Beautified:
function oplop( $master, $nick ) {
    return substr( preg_replace(
        '/^\D{8,}(\d+)/', '$1$0',
        strtr( base64_encode( md5( $master . $nick, true ) ), '+/', '-_' ) . ' 1'
    ), 0, 8 );
}

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Find one-handed words
'exaggerated' is an example of a word which can be typed on the left hand, on a normal qwerty keyboard map.  'monopoly' is an example for the right hand.
Searching the unix words file for words that can be typed on one hand.  Output should be two lines:  space separated list of such words for the left hand, followed by the list for the right hand.  e.g.
a abaft abase abased abases abate abated abates abbess abbesses ...
h hi hill hilly him hip hippo hippy ho hokum ...

The left-hand letters are:
qwertasdfgzxcvb

The right-hand letters are:
yuiophjklnm'

Uppercase letters count as one-handed; letters with diacritics count as two-handed and hence words containing them can be ignored.

Do capital letters require two hands or one?  I suppose that characters such as "é" cannot be typed with either hand, right?  Finally, I assume apostrophe is a valid right hand key, correct?

This question isn't self-contained without a definition of left-hand and right-hand letters.

One thing that might help people using regular expressions: using [a-gq-tv-xz] for the left-hand letters and ['h-puy] for the right-hand letters is slightly shorter than writing them all out.

sed, 78 bytes
1{x;s/^/! /;x};/^['h-puy]*$/IH;/^[a-gq-tv-xz]*$/I{G;x};${x;y/\n/ /;s/! */\n/p}

requires GNU sed, run with sed -n -f words.sed < /usr/share/dict/words

Bash (100 89 chars)
for x in a-gq-tvwxz h-puy\'
do grep -iE ^[$x]*$ /usr/share/dict/words|tr '
' \
echo
done

Note that 21 chars go to the full path to the words file: if we're allowed to assume that pwd is /usr/share/dict then 16 of those can be saved.
Credit to chron for the shorter regexes.

"^([$x])*$" should be the regex

Bash, 86
for x in a-gq-tvwxz h-pyu\'
do egrep ^[$x]*$ /usr/share/dict/words|tr '
' \
echo
done

Taylors for, my egrep, chrons grouping of chars.
By definition, if you type by two hands blind, if you like to produce an uppercase letter, you always use the left hand to produce an uppercase character of the right hand and vice versa.
Of course you may produce an uppercase W with only the left hand, but you can produce junk with the left hand, too, if you like.

Beat me to the grouping on the letters, good job!

It's been a race condition between Peter Taylor and me. His 100 (101?) char solution was public, when I started my post and optimization, but he finished his improvement before me, which I observed after finishing my own. I wouldn't have made the post in the same language, just with egrep and without -i, but would have made an comment instead, if he had been some minutes faster.

I thought about it right after I had made the comment correcting the regex, and left work before I had a chance to do it. Completely forgot about it by the time I got home.

Your final paragraph is the reason Steven Rumbalski and I pushed for clarification, and the clarification that uppercase counts as one-handed was received more than 24 hours before you published this, so it's not really to spec.

Python 3.8 - 126 135 139 144 152 137 chars
r,a={*"YUIOPHJKLNM'"},'\n'
try:
 while w:=input():
  s={*w.upper()}
  if r|s==r:a=w+' '+a
  if s-r==s:a+=w+' '
except:print(a)

edit: handle upper case and apostrophe.
edit 2: move to python 3. get rid of ' '.join(). use walrus operator. change +=w to +=[w] to fix bug.
edit 3: change printing to save 5 characters.
edit 4: change set creation from set(iterable) to {*iterable} to save 2 characters twice.
edit 5: change two lists to one string to hold result allowing one less assignment on the first line and one less print statement on the last line to save 9 characters.

Get rid of the for loop and just print(*a);print(*b) to save two bytes :)

@movatica: Nice improvement. Updated answer.

s<=r saves another two over r|s==r

[w] -> w, save 2 byte. set(w.upper()) -> {*w.upper()}

set("YUIOPHJKLNM'") -> {*"YUIOPHJKLNM'"}

@a25bedc5-3d09-41b8-82fb-ea6c353d75ae: brackets are required on +=[w] otherwise string characters get added individually.

Python 2.7 (139 characters)
import os
a=set("yuiophjklnm'")
c=os.read(0,9**9).lower().split()
print'\n'.join([' '.join(filter(x,c))for x in a.isdisjoint,a.issuperset])

Bourne shell, 55 chars
(Or any Bourne-like shell but bash, zsh or yash)
w=$1;f()echo `grep -ixe[$1]*<$w`;f a-gq-tvwxz;f h-puy\'

Called as sh -f words.sh /usr/share/dict/words. (of course, on systems where sh is actually bash like on some Linux distributions, use another Bourne-like shell like ash, ksh, mksh, pdksh, posh...)

Javascript (node), 201 byte
f=require('fs');c=d='';r=(a=f.readFileSync('/dev/stdin')+c).split('\n');a.
replace(/[aqzxswcdevfrbgt]/ig,'').split('\n').map(function(k,i){k==r[i]&&(
d+=k+' ');!k.length&&(c+=r[i]+' ')});console.log(c,d)

This can probably be rewritten to a much shorter version in another language, but I just wanted to give node a try.
Run with node words.js < /usr/share/dict/words

Q (121 140 Bytes)
Output isn't the exact same (backticks instead of spaces) but this is symptomatic of how Q displays string types.
i:read0`:/usr/share/dict/words;
0N!/:i:`$/:i where each (min each) each flip i in/:\:(x,upper x:"qwertasdfgzxcvb";y,upper y:"yuiophjklnm");

EDIT: Had to handle mixed case, +20 chars

You can golf this considerably for 111. \$'i(&:')(min'')(+)(i:read0`:/usr/share/dict/words)in/::(x,upper x:"qwertasdfgzxcvb";y,upper y:"yuiophjklnm'")`

Ruby, 112 92 characters
EDIT: This is shorter, though not nearly as fun:
puts %w(a-gq-tv-xz 'h-puy).map{|r|File.read('/usr/share/dict/words').scan(/^[#{r}]+$/i)*' '}

Original:
puts File.read('/usr/share/dict/words').scan(/(^[a-gq-tv-xz]+$)|(^['h-puy]+$)/i).transpose.map{|w|w.compact*' '}

Pretty simple regex-based solution.  As with the others, you could save some characters if you're allowed to pass the filename in ARGV or if it's assumed to be in your current directory.

Python, 130 Bytes
a="\n"
b=""
try:
 while 1:v=raw_input();m=[x.lower()in"yuiophjklnm'"for x in v];v+=" ";a+=v*all(m);b+=0**any(m)*v
except:print b+a

Run with python one_handed_words.py < /usr/share/dict/words

Am I allowed to take one of the solutions posted here, shorten it, and put it in my post?

If it's just small improvements, it's more friendly to post comments. If you are making a significant change, it's better to post a new answer, but nice to give credit to the answer(s) you are basing it on.

127 bytes in Python 3

125 bytes using sets

Haskell (191)
import Char
g x=all(`elem`x)
f m[]=m
f[x,y](w:ws)|g"quertasdfgzxcvb"w=f[w:x,y]ws|g"yuiophjklnm'"w=f[x,w:y]ws|1<2=f[x,y]ws
main=getContents>>=mapM(putStrLn.unwords).f[[],[]].lines.map toLower

Perl, 72 bytes
$a{/^['h-puy]+$/i-/^[a-gq-tv-xz]+$/i}.=y/\n/ /rfor<>;print@a{1,-1,$,=$/}

run with perl words.pl /usr/share/dict/words

I get syntax error: Bareword found where operator expected at words.pl line 1, near "tr/\n/ /rfor"

This works for me on perl 5.14.2, and requires perl 5.14 and up (which is where the non-destructive substitution flag r was added)

Jelly, 26 24 25 bytes
Øqs€5⁾q'ṭZF€
ỴŒlfƑ¥ƇⱮ¢K€Y

Try it online!
Explanation (older version)
Øqs€5⁾q'ṭZF€   Auxiliary niladic link
Øq             Lowercase QWERTY keyboard
  s€5          Split each row into chunks of at most 5 letters
     ⁾q'ṭ      Append the string "q'"
         Z     Zip (transpose)
          F€   Flatten each => ["qwertasdfgzxcvbq", "yuiophjklnm'"]

ỴŒlfƑƇⱮ¢K€Y   Main monadic link
Ỵ             Split on newlines
 Œl           Lowercase
      Ɱ¢      Map over the result of the auxiliary link:
     Ƈ          Filter by
    Ƒ             Invariant under
   f                Filtering by the right argument
        K€    Join each with spaces
          Y   Join with a newline

Python, 243 chars
edit: here's a more compliant program according to the question:
import sys
def o(w):
 r="yuiophjklnm'";f=2;w=w.lower()
 for l in w:
  if(f==1)&(l in r)|(f==0)&(l not in r):return 2
  f=l not in r
 return f
y=[[],[],[]]
for w in sys.stdin.read().split('\n'):y[o(w)].append(w)
for i in y[0:2]:print' '.join(i)

invoke: python onehanded.py > /usr/share/dict/words or any other words file with newline-separated words
old: 141 chars, just a single-word function
returns right or left if w is onehanded, and both if both hands are used.
def o(w):
 r="yuiophjklnm'";f=2
 for l in w:
  if(f==1)&(l in r)|(f==0)&(l not in r):f=2;break
  f=[1,0][l in r]
 return'rlbieogfththt'[f::3]

Would you kindly turn that into a working program or remove the character count?  Otherwise, the title is misleading.

Q, 95 (111 with hardcoded dict path)
{`$'e[(w(&)l(w)in .Q.a except a)],(e:enlist)w(&)(l:all')(w:(_)read0 -1!`$x)in a:"yuiophjklnm'"}

usage
q){`$'e[(w(&)l(w)in .Q.a except a)],(e:enlist)w(&)(l:all')(w:(_)read0 -1!`$x)in a:"yuiophjklnm'"} "/usr/share/dict/words"
`a`a`aa`aa`aaa`aaa`aaaa`aaaaaa`aaas`aaberg`aae`aaee`aaf`aag`aar`aara`aarc`aas..
`h`h`hh`hi`hi`hi`hih`hiko`hikuli`hili`hill`hill`hillo`hilly`hilly`hilo`hilum`..

14 more chars if you hardcode it
`$'e[(w(&)l(w)in .Q.a except a)],(e:enlist)w(&)(l:all')(w:(_)read0`:/usr/share/dict/words)in a:"yuiophjklnm'"

J, 109
1!:2&2;:^:_1('qwertasdfgzxcvb';'yuiophjkl''nm')((#@[>[:>./i.)&>/#]);:1!:1<'/usr/share/dict/words'[9!:37]0,3$_

I'm sure this can be done better, I don't know how to do string manipulation :-(

Pyth, 44 bytes
Ljdf.A}RbrT0cQdy."az:ïÑý>Íï“"y"yuiophjklnm'
Try it online!

Ljdf.A}RbrT0cQdy."az:ïÑý>Íï“"y"yuiophjklnm' | # Python 3 Translation
---------------------------------------------+------------------------------
                                             | from operator import contains
                                             | from itertools import repeat
                                             | Q = eval(input())
L                                            | y = lambda b:
 jd                                          |   " ".join(
   f                                         |     filter(lambda T:
    .A                                       |       all(
      }R                                     |         map(contains,
        b                                    |           repeat(b),
         rT0                                 |           T.lower()
                                             |         )
                                             |       ),
            cQd                              |       Q.split(" ")
                                             |     )
                                             |   )
               y."az:ïÑý>Íï“"               | print(y("qwertasdfgzxcvb"))
                              y"yuiophjklnm' | print(y("yuiophjklnm'"))

Python: 122
import os
S=set("yuiophjklnm'")
c=os.read(0,9**9).lower().split()
print"\n".join(w for w in c if set(w)<=S or set(w)^S>=S)

Launched with:
python name_of_program.py < /usr/share/dict/words

The idea is mostly the same of Dillon Cower's, but I use set(w)<=S to indicate a subset while set(w)^S>=S for a disjoint set.

The output format is wrong. The words should be sorted by hand.


text:
Swaps needed to sort an array in bubble sort method
Write shortest code that detect how many swaps (minimum) are needed to sort (in increasing order) any array of unique positive integers. It should be fast enough to detect number of swaps in array of 1'000'000 integers in decreasing order in 1-2 minutes.
Refs

Bubble Sort on Wiki
Example implementations of bubble sort

Score
[time elapsed]s/60s * [length of code]

Can you post a link to a reference implementation/description of bubble sort in your post?

I thought that everyone on CodeGolf.SE.com know that algorithm.

May there be repeating elements in the array?

in C++, the above example scenario takes ~190ms on my core i5 laptop and reports: 499999500000 swaps [179 chars], but this method fails if the ordering is random or if there are duplicates - can you clarify @leftaroundabout's point?

I'm confused by "minimum" here.  Bubble sort, as specified by the first pseudocode implementation on the Wikipedia page, is a well-specified algorithm which takes an unknown but fixed number of swaps given an input.  What are we taking the minimum over?  Or do you mean what is the minimum number of swaps needed, not doing the swaps in the order that standard bubble sort does them?

@Hauleth: I don't doubt that, it's just good practice to include all details in a spec.  It's also a little confusing that bubble sort is only mentioned in your title.  Can you work it into your introductory paragraph as well?

Apart from small optimizations, the number of swaps for bubblesorting a given input should be constant, independent from the language. Sort 1M of values with bubblesort shouldn't be possible in 2 minutes on a nowadays customer PC/laptop/xPhone. Can you provide a reference code which solves the sorting in 2 Minutes? I vote to close.

Python - 262 chars * 45 / 60 = 196.5
Edit: much faster sorting algorithm.
First it will sort all the items in the list by what hundred they are in (0, 100, 200, etc), in a list in m (note: I count these as 1 step each, so a list of 1,000,000 items will automatically have 1,000,000 steps initially)
Then it will sort the lists within m using the bubble sorting function c
This is greatly sped up from using c on the original list to be sorted, because the amount of time it takes to sort 1000 items is small (~0.04 seconds), but exponentially increases the larger the list gets (~45 seconds at 10,000 items). But if you sort 100 lists of 100 items, it only takes .4 seconds, to sort, more than 100 times faster than sorting 1 list of 10,000 items. It should therefor take 4 seconds to sort 100,000 items, and 40 seconds to finally sort 1,000,000
In actuality, it took 45 seconds to sort the reversed 1,000,000 item list this way, and results in 50,500,000 steps:
python bubblesortcount.py
50500000
44.6600000858

This functon works with the given case (reverse ordered list), as well as any random case. No negative integers, though.
r=range
def b(l):
 m=[[]for i in r(len(l)//100+1)];t=[];o=0
 for e in l:m[e//100].append(e);o+=1
 for e in m:x=c(e);t+=x[0];o+=x[1]
 return t,o
def c(l):
 s=0
 for p in r(len(l)-1,0,-1):
  for i in r(p):
   if l[i]>l[i+1]:l[i],l[i+1]=l[i+1],l[i];s+=1
 return l,s

test:
import random,time
a=time.time()
d=b(range(1000000)[::-1]) #reversed list
#d=b(random.sample(range(1000000),1000000)) #scrambled list
z=(time.time()-a)
#print d[0] # comment to not print a gigantic list
print d[1] # number of steps
print z # time it took

Edit: by changing the amount the helper function sorts by to 100, I reduced the average time it takes to sort the list to 45 seconds. also reduces character count by 2
edit again: you know what? maybe what I'm doing isn't valid. I can change the amount the helper function sorts by to just 1 and it will sort a million items in 5 seconds.. is this valid?

Well, of course it's too slow if you actually implement Bubblesort (this being an O (n ²) algorithm)! That's the interesting thing about this challenge.

I suppose that the speed in which the code runs all depends on the machine it's being run on as well. my wimpy dualcore 1.83ghz laptop processor isn't quite up to speed to recent quad-core, 3.3 ghz technology (though I am building a spankin' new desktop soon, just not soon enough)

The challenge doesn't seem to necessarily be to implement bubble sort, but to report the number of swaps needed.

@StevenRumbalski: misleading title is misleading, then

@Blazer: hardware is hardly significant compared to algorithm complexity when you're dealing with data blocks in the order of magnitude of millions, as well as language performance (otherwise you clearly shouldn't be using Python: you're program re-written in C and compiled with a decent compiler with -O2, run on your Laptop, would almost certainly outperform your code as simply run through the python interpreter on a state-of-the-art PC with an eight-core i7 processor).

I think what I'm doing now isn't valid.. what do you guys think?

I think it is incorrect.  If I run b([7,7,8,3,1,9]) I get a swap count of 13.  But if I bubble sort on paper I get a result of 7.

@StevenRumbalski: of unique positive integers


text:
Calculate the total number of paths
Description
There will be a grid of 9x9, where there will be placed 12 rocks.
You will start at a starting-rock and walking with a starting-direction (north, south, west or east), whenever you see a rock, you have two options:

Climb over the rock and continue in the same direction
Change direction to your *left

*NOT to the west, you change to your left as if you were walking and you take your own left.
So the flow of the paths will always be counter-clockwise. Here is an example that illustrates the flow:

Note: In this case, the starting-rock is the yellow (X) and the starting-direction is to the south

Rules

The code must be able to solve it for any rock (if it doesn't have complete paths, then is 0)
You can NOT memorize anything different than the rocks used
The rocks must be included on the code (so you can't pass them by input)
We will use the above's rock placement in the competition
You chose how you will pick the starting-rock (Example: passing an
array index or giving a xy location, etc) and how you chose the starting-direction (Example: 1=north, 2=south or etc)
It must return, print or otherwise make us know the total number of
paths somehow for that given rock
Counted by characters used

Just to immortalize the grid and rock placements in case the image dies for unknown reasons, I will put it in plain text:
100100000
100100010
000000000
000000000
000000000
010010000
000000000
010100000
100010010

//rocks = 1, empty = 0

Clarifications

You can't walk on the same part twice on the same path (crossing ways are allowed)
We need to be able to set on the input: a) the starting-rock and b)
the starting-direction
The complete paths must end on the starting-rock
Note that it shouldn't be a problem whether we can climb over a starting rock or not, because it is impossible to this to happen with the current map and rules (we do have a four-path rock where this could happen, but after analysing it, this can't happen)
You are allowed to compress the 9x9 grid. (the most it can be compressed is to a 5x5 I think)

How do paths end?  Do they have to end at a rock?  The starting point?

@KeithRandall yes, to the starting point.

One more nitpick: can the path cross the starting rock before ending up at it?

@KeithRandall I didn't see any case that this will affect us. We only have one rock where theoretically this could happen because it have (+) formation, but I revised it and it is impossible to bother us except if a) we allow to walk twice on the same part on the same path or b) modify the map. But as it is now, it shouldn't be a problem

I have a map where it can happen.  If you're going to restrict the program to just the given map, then print 3 is a pretty good program...

@KeithRandall but we will not always start at the starting-rock of the example (so it won't always be 3). Also, memorizing stuff is against the rules

You say you can't walk on the same part twice, but also demonstrate paths crossing, which is walking on the same tile twice. :/

green path and blue path both cross themselves.

@Rob, you are right, it is ambiguous. I will add a clarification that says crossing is allowed

Python, 274 chars
S=7
D=-1j

R=[0,4,7,1+1j,3+1j,1+3j,4+3j,7j,3+7j,7+7j,8j,3+8j]
Z={}
for i in range(4096):
 d=D;p=R[S];L=[]
 while len(L)<12:
  p+=d;P=[(abs(r-p),r)for r in R if r-p==abs(r-p)*d]
  if not P:break
  p=min(P)[1];d*=1j**(i>>R.index(p)&1);L+=[p]
  if p==R[S]:Z[tuple(L)]=1;break
print len(Z)

The code I'm counting starts at the R=[..., the initial two lines are "input" which I didn't count.
R is the set of rock coordinates, listed using complex number coordinates.  S is the starting rock.  D is the starting direction, again using complex numbers (1=right,-1=left,1j=up,-1j=down).
The code tries all of the 2^12=4096 possibilities for go straight/turn left for each rock, then walks from the starting rock until it gets back to the starting rock, or there is no more rock on the path, or the path gets too long (it loops).  It saves the path in Z if it is successful.

very interesting way. Just remember that the rock placements can't be passed by input

@ajax333221: fixed

ASM - WinXP Command shell .COM 128 bytes, source = 607 characters
To run, provide the rock id and the direction, e.g.
program c1

where the letter is the rock (top left = a, bottom right = l) and the number is the direction: up = 3, left = 2, down = 1, right = 0
   mov bp,1000h
   mov di,bp
   mov cx,bp
   xor ax,ax
   rep stosw
   mov bl,b[82h]
   sub bl,'a'-1
   mov bh,ch
   add bx,bx
   mov cl,b[83h]
   sub cl,48
   shl cl,2
   mov di,bx
   call l2
   mov dx,bp
   add b[bp],48
   mov b[bp+1],'$'
   mov ah,9
   int 21h
   ret
l1:inc b[bp]
   cmp di,bx
   je ret
   dec b[bp]
   cmp b[di+bp],0
   jne ret
   call l2
   sub cl,4
l2:mov dx,[di+l3-2]
   ror dx,cl
   and dx,15
   jz ret
   mov b[di+bp],1
   pusha
   mov di,dx
   add di,di
   call l1
   popa
   mov b[di+bp],0
   ret
l3:xor al,b[bx+si]
   inc ax
   add w[si+09510],sp
   and ax,ax
   add al,087
   add b[bx+si+0906],dh
   pusha
   add b[bx+si+0b],cl
   xor b[si],cl
   jpe l4
l4:pop bx

JavaScript, 466 chars

Starting-direction is equal to: North=1, West=2, South=3, East=4
The starting-rock is in row/column notation, where the upper-left is
11. (the grid was compressed to a 5x5)

The first two lines are input and aren't included in the count of characters, also I added some break lines to wrap the code.
D=3;//starting direction
C=21;//starting rock

function a(a){return a+="",(a[0]-1)*5+(a[1]-1)}
function b(a){var b=!1,c=C+"";a==4?(h=c[0]+(c[1]-1))[1]>0&&(b=!0):a==3?(h=-(-c[0]-1)+c[1]+"")[0]<6&&(b=!0):a==2?(h=c[0]+ -(-c[1]-1))[1]<6&&(b=!0):(h=c[0]-1+c[1])[0]>0&&(b=!0);if(b)return C=h*1,!0}
function c(){var c=C;while(b(D)&&F[a(C)]==0);if(C!=c&&F[a(C)]==1)return!0}
function d(){if(c()){F[C]++;var a=D,b=C;C!=B?(d(),C=b,D=a,D==1?D=4:D--,d()):(A++,F=E)}}
A=0,B=C,E=F="1010010101010100110010011".split(""),d(),alert(A)

Uncompressed and explained code:
dir=3;
start=21;

//transforms row-column notation to array index
function toAV(a){
    return a+="",(a[0]-1)*5+(a[1]-1);
}

//advance one square on the current direction
//returns true when it succeed
function walk(num){
    var walkbol=false,str=xy+"";
    if(num==4){
        if((wal_rec=str[0]+(str[1]-1))[1]>0){
            walkbol=true;
        }
    }else if(num==3){
        if((wal_rec=-(-str[0]-1)+str[1]+"")[0]<6){
            walkbol=true;
        }
    }else if(num==2){
        if((wal_rec=str[0]+-(-str[1]-1))[1]<6){
            walkbol=true;
        }
    }else{
        if((wal_rec=(str[0]-1)+str[1])[0]>0){
            walkbol=true;
        }
    }
    if(walkbol){
        xy=wal_rec*1;
        return true;
    }
}

//start walking on the current dir until a)didn't succeed walking or b)step on a rock
//returns true when it moved at least once and it ended above a rock
function nextRock(){
    var str1=xy;
    while(walk(dir)&&map[toAV(xy)]==0){}

    if(xy!=str1&&map[toAV(xy)]==1){
        return true;
    }
}

//if it finds a rock, it calls itself twice
//one with the current direction and one with the direction to its left
function splitways(){
    if(nextRock()){
        map[xy]++;
        var cc=dir,dd=xy;
        if(xy!=start){
            splitways();
            //--
            xy=dd;
            dir=cc;
            dir==1?dir=4:dir--;
            splitways();
        }else{
            count++;
            map=xmap;
        }
    }
}

//globals
count=0,xy=start,xmap=map="1010010101010100110010011".split("");

//start
splitways();
alert(count);

I really don't know many languages so I used the only one that I think I understand. BTW, it is my first code-golf :)


text:
Code-Golf: Permutations
Write a function that takes as input a set of integers (can be a list, array or any other container with distinct numbers), and outputs the list of all its permutations.
Python (95 chars):
p=lambda s:s and sum(map(lambda e:map(lambda p:[e]+p,p(filter(lambda x:x!=e,s))),s),[]) or [[]]
It'd be nice to be beaten in the same language, but implementations in other languages are more than welcome!

Python - 76 chars
Longer than gnibbler's, but implements things from scratch.
p=lambda x:x and[[a]+b for a in x for b in p([c for c in x if c!=a])]or[[]]

I like the usage of comprehensions here. It really simplifies the code I posted a lot!

Python, 52
Input is a set. Output is a list of lists.
f=lambda a:[p+[x]for x in a for p in f(a-{x})]or[[]]

This is shorter than the answer that does all the work with a builtin.

I've submitted a golfing suggestion to this answer which makes it shorter than your answer.

J, 11 characters
(i.@!@#A.[)

Usage:
   (i.@!@#A.[) 1 3 5
1 3 5
1 5 3
3 1 5
3 5 1
5 1 3
5 3 1

Explanation:
i.@!@# uses three verbs to return a list from 0 to (!n)-1 where n is the number of items in the given list.
[ returns the list itself. In the example shown that gives 0 1 2 3 4 5 A. 1 3 5.
A. returns one possible permutation of the second list for each item in the first list (kind of - the proper explanation is given here).

Provide a link to information about J?

@Sparr The J website has a couple of good guides - Learning J and J for C programmers - and a page covering the vocabulary.

Python - 55 chars
from itertools import*
p=lambda x:list(permutations(x))

Not exactly what I was hoping folks would write... but it's useful to know Python has such utilities in the standard library.

@zxul767: Why reinvent the wheel? Using the standard library will prove incredibly efficient... (and in this case makes for concise code when golfing ;-)

Haskell, 44 43
p[]=[[]]
p l=[e:r|e<-l,r<-p$filter(/=e)l]

Essentially the same as ugoren's solution, but Haskell is better at list comprehensions!

Of course, it can also do
30
import Data.List
p=permutations

More efficient approach, that doesn't require an equality comparison:
92
import Data.List
p[]=[[]]
p l=(\(l,(e:r))->map(e:)$p(l++r))=<<(init$zip(inits l)(tails l))

As a consequece, this one also works when there are duplicate elements in the list.

The best part of this is that the 44 line haskell solution with the list comprehension is shorter than the python solution that just uses the standard library.

p=Data.List.permutations. It feels like cheating, though. Also, Data.List.permutations doesn't output the permutations in lexicographic order.

You can write p[]=[[]] as a base case instead, saving two bytes.

@Mauris: right! I somehow assumed that the empty list would have zero permutations by definition, but since 0! = 1 that clearly doesn't make any sense. Having an empty base case is much nicer.

C, 270 243 239 characters
#define S t=*a;*a=a[i];a[i]=t;
#define R o=p(n,r-1,a+1,o,r-2,0)
int*p(n,r,a,o,i,t)int*a,*o;{if(!r)for(;n;--n)*o++=*--a;else{R;for(;i;--i){S R;S}}return o;}
P(n,a)int*a;{int N=1,i=n;for(;i;N*=i--);return p(n,n,a,malloc(N*n*8),n-1,0)-N*n;}

The function P(n,a) returns a pointer to the n! permutations of a, packed one after another in one giant array.

Some tips: <malloc.h> isn't needed (ignore the warnings). sizeof nis 4 (portability is nice, but shorter is nicer). Use extra parameters as variables (e.g.p(n,a,N,i)). intp(..)inta,o;`. Using global variables instead of parameters and return values often helps.

@ugoren, thanks for the tips. So far, I haven't seen how to shave any further characters using globals. (And hey, the function is thread-safe as it is!)

215 bytes

181 bytes

Prolog (SWI), 33 bytes
X-Y:-bagof(A,permutation(X,A),Y).

Try it online!
-2 from steffan

you can use bagof instead of findall

in Q (48)
g:{$[x=1;y;raze .z.s[x-1;y]{x,/:y except x}\:y]}

Sample usage:
q)g[3;1 2 3]
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

Ruby - 23 chars
f=->x{p *x.permutation}

for example f[[1,2,3]] outputs this.
but using [].permutation feels like cheating, so:
Ruby - 59 chars
f=->a{a.size<2?[a]:a.flat_map{|x|f[(a-x=[x])].map{|y|x+y}}}

tested with
100.times.all?{arr=(1..99).to_a.sample(rand(5)); arr.permutation.to_a==f[arr]}
=> true

If you want, you can demo your code using a site like IdeOne: http://ideone.com/crvtD

Why would using built-in language features be cheating?

@Mark maybe not cheating, but not much fun either, to write a function that just calls a built-in function. Like for example: "write a function to sort an array" -> f(array) { return array.sort(); }

Scala 30:
def p(s:Seq[_])=s.permutations

Scala 195, quick'n'dirty, without permutations from library:
def c(x:Int,t:List[_]):List[_]={val l=t.size
val o=x%l
if(l>1){val r=c(x/l,t.tail)
r.take(o):::(t.head::r.drop(o))}else
t}
def p(y:List[_])=(0 to(1 to y.size).product).foreach(z=>println(c(z,y)))

val y=List(0,1,2,3)
p(y)

Scala 293, full grown, type safe iterator:
class P[A](val l:Seq[A])extends Iterator[Seq[A]]{
var c=0
val s=(1 to l.size).product
def g(c:Int,t:List[A]):List[A]={
val n=t.size
val o=c%n
if(n>1){val r=g(c/n,t.tail)
r.take(o):::(t.head::r.drop(o))
}else
t}
def hasNext=c!=s
def next={c+=1
g(c-1,l.toList)}
}
for(e<-new P("golf"))println(e)

Python - 58 chars
Slightly shorter than ugoren's, by taking a set as input:
p=lambda x:x and[[y]+l for y in x for l in p(x-{y})]or[[]]

K, 30 bytes
{x@v@&((#x;1)~^=:)'v:!(#x)##x}

No builtins!

JS - 154 146 chars
function f(x){var a=[],m;(m=x.length)>1?f(x.slice(1)).map(function(y){for(l=m;l--;a.push(y.slice(0,l).concat(x[0],y.slice(l))));}):a=[x];return a}
Test : f([1,2,3,4,5]).map(function(a){return a.join('')}).join('\n') returns this.

R
Since we are talking about permutations let me show at least one solution in R:
library(gtools);v=c(3,4,5);permutations(length(v),length(v),v)

Perl 188
No library routines, no recursion
sub p{$l=(@_=sort split'',shift)-1;while(print@_){$k=$j=$l;--$k while($_[$k-1]cmp$_[$k])>=0;$k||last;--$j while($_[$k-1]cmp$_[$j])>=0;@_[$j,$k-1]=@_[$k-1,$j];@_[$k..$l]=reverse@_[$k..$l]}}

Python - 50 chars
import itertools
list(itertools.permutations("123"))

Pyth, 4 bytes
L.pb

Yeah, Pyth was created after this challenge was posted and all. This is still really cool. :D
Live demo.
Reading from stdin is a byte shorter:
.pQ

JavaScript 143 136 134 123

function p(s,a="",c="",i,z=[]){a+=c,i=s.length
!i?z.push(a):0
for(;i--;s.splice(i,0,c))p(s,a,c=s.splice(i,1),0,z);return z}

var perms = p([1,2,3]);

document.getElementById('output').innerHTML = perms.join("\n");

I think you could gain 8 bytes by doing : js  function p(s,a="",c="",i,z=[]){
instead of
function p(s,a,c,i,z){if(!z)a=c="",z=[]```

Thanks ColdK. It worked and now is 8 bytes shorter.

Just saying, you can use ES6 arrow functions to knock off a few bytes

05AB1E - 2 1 bytes
œ
The input must be an array/list.
Explanation:
œ //Takes all the permutations of the elements in the top of the stack (the input is a list, so it would work)

Saved a byte thanks to Erik the Outgolfer

You can take input as a single list, no need to take it separated by newlines.

Thank you! I can now shorten this to one byte!

This doesn't output unique permutations

Brachylog, 2 bytes
pᵘ

Try it online!
 ᵘ    Find every unique
p     permutation of the input.

Vyxal, 2 bytes
ṖU

Try it Online!
Ṗ  # All permutations of input
 U # Filtered by unique

JavaScript (ES6), 91 78 bytes
-5 thanks to @Neil
f=a=>a.length<2?[a]:a.flatMap((x,i)=>f(a.filter((_,j)=>i-j)).map(t=>[x,...t]))

Pretty normal recursive approach, and my first time using copyWithin :p
Okay, copyWithin modifies the array, so that doesn't work. Used a different approach, which now saves more bytes.

Curry, 41 26 bytes
15 bytes saved by alephalpha
Tested in PAKCS
p[]=[]
p(x++a:y)=a:p(x++y)

Try it online!
Uses non-determinism to output all the permutations.  This same code is used in my answer here for which I originally wrote it.

Shorter.

Knight, 180 bytes
;=i=jF;W=pP E++"=x"=i+1i" p";=s"";W>i-=j+1jT=s+++++++s";=y"j"F W>i-=y"j"+1y"j"T"E+s';=z=bF;W>i-=z+1zT;=aF W>i-=a+1aT|?z a=b|b?E+"y"zE+"y"a|b;=rF;=s"";W>z=r+1r=s++sE+"x"E+"y"r" "Os'

Try it online!
This was a pain. Nested evals and stuff. Since recursion doesn't really work, I had to literally compose a string of nested while loops, and then eval it. Extremely inefficient, \$O(n^{n+1})\$ where \$n\$ is the length of the input. My browser started to freeze up with \$n=6\$.
-2 bytes thanks to Aiden Chow.

You could combine =iF and =jF into =i=jF for -2 bytes.

K (ngn/k), 15 bytes
{x@?<'+!a#a:#x}

Try it online!

Perl 5, 66 bytes
sub{$"=",";grep{my%t;@t{@$_}++;@_==%t}map{[/\d+/g]}glob"{@_}-"x@_}

Try it online!
Relies on the problem definition of distinct integers.  Also horribly wasteful--it creates n**n candidates only to discard the ones that duplicate members within them.

Python, 53 bytes
from itertools import*;lambda x:list(permutations(x))

This is basically a duplicate of another submitted answer. I assume you came up with it independently (and you golfed it better), but I thought it was worth pointing out the duplicate.

50 bytes

Axiom, 160 bytes
p(a)==(#a=0=>[[]];r:=[[a.1]];r:=delete(r,1);n:=#a;m:=factorial n;m>1.E7=>r;b:=permutations n;for j in 1..m repeat(x:=b.j;r:=concat([a.(x.i)for i in 1..n],r));r)

ungolfed
--Permutation of a
pmt(a)==
     #a=0=>[[]]
     r:=[[a.1]]; r:=delete(r,1) -- r has the type List List typeof(a)
     n:=#a
     m:=factorial n
     m>1.E7=>r
     b:=permutations(n)         --one built in for permutation indices
     for j in 1..m repeat
        x:=b.j
        r:=concat([a.(x.i) for i in 1..n],r)
     r

All this call one library function that give permutation on index (only integers as permutation as permutations on [1], permutations on [1,2], permutations on[1,2,3] etc).So it is enough get these set of indices and build the lists; One has to note that this seems to be compiled good for every List of type X
(4) -> p([1,2,3])
   Compiling function p with type List PositiveInteger -> List List
      PositiveInteger
   (4)  [[1,2,3],[1,3,2],[3,1,2],[2,1,3],[2,3,1],[3,2,1]]
                                          Type: List List PositiveInteger
(5) -> p([x^2,y*x,y^2])
   Compiling function p with type List Polynomial Integer -> List List
      Polynomial Integer
   (5)
      2      2    2  2        2  2            2  2        2  2    2      2
   [[x ,x y,y ],[x ,y ,x y],[y ,x ,x y],[x y,x ,y ],[x y,y ,x ],[y ,x y,x ]]
                                       Type: List List Polynomial Integer
(6) -> p([sin(x),log(y)])
   Compiling function p with type List Expression Integer -> List List
      Expression Integer
   (6)  [[sin(x),log(y)],[log(y),sin(x)]]
                                       Type: List List Expression Integer
(7) -> m:=p("abc")::List List Character
   Compiling function p with type String -> Any
   (7)  [[a,b,c],[a,c,b],[c,a,b],[b,a,c],[b,c,a],[c,b,a]]
                                                Type: List List Character
(8) -> [concat(map(x+->x::String, m.j))  for j in 1..#m]
   (8)  ["abc","acb","cab","bac","bca","cba"]
                                                        Type: List String

Do you have a link to the Axiom interpreter? I'd love to get it added to Try It Online!, it looks like an interesting language.

Jelly, 2 bytes
Œ!

Try it online!
Yay for builtins!

K (oK), 3 bytes
Solution
prm

Try it online!
Explanation:
It's a 3 byte built-in shortcut to the following built-in 47 byte function:
{[x]{[x]$[x;,/x ,''o'x ^/:x;,x]}@$[-8>@x;!x;x]}

... which can be shortened to 23 bytes if we know we're getting a list of ints as input:
{$[x;,/x,''o'x^/:x;,x]} / golfed built in
{                     } / lambda function with implicit input x
 $[ ;             ;  ]  / if[condition;true;false]
   x                    / if x is not null...
             x^/:x      / x except (^) each-right (/:) x; create length-x combinations
           o'           / call self (o) with each of these
       x,''             / x concatenated with each-each of these results (this is kinda magic to me)
     ,/                 / flatten list
                    ,x  / otherwise enlist x (enlisted empty list)

APL(NARS), 39 chars, 78 bytes
{1≥k←≢w←,⍵:⊂w⋄↑,/{w[⍵],¨q w[a∼⍵]}¨a←⍳k}

test:
  q←{1≥k←≢w←,⍵:⊂w⋄↑,/{w[⍵],¨q w[a∼⍵]}¨a←⍳k}
  q 1 2 3
1 2 3  1 3 2  2 1 3  2 3 1  3 1 2  3 2 1
  q 'abcd'
abcd abdc acbd acdb adbc adcb bacd badc bcad bcda bdac bdca cabd cadb cbad cbda cdab cdba dabc dacb dbac dbca dcab dcba

Japt, 1 byte
á

Japt interpreter
This got bumped and didn't have a Japt answer, so I figured I'd go ahead and add one. á when applied to an array and without any arguments is the builtin for "get all permutations". The -R flag used in the interpreter link only modifies how the result is printed.


text:
Create a rotating quine
A rotation of a string is made by splitting a string into two pieces and reversing their order, for example "world!Hello, " is a rotation of "Hello, world!". It is possible to create programs that can be rotated to form a different, but still valid program. Consider this example in python:
print ")import sys; sys.stdout.write("

It can be rotated to form
import sys; sys.stdout.write("print ")

Which is itself a valid python program.
Your challenge is to write a program that outputs a rotation of itself, which when run will output the original program. Bonus points to any entry with a cycle length greater than two!
This is code golf, the exact scoring will be: (length of code)/(cycle length - 1).
EDIT: We have a winner (unless someone else is able to beat a score of 4)! I'd still be very interested to see any other solutions, whether they're contenders or not.

Nice!  You've excluded cheap concatenation with your (cycle length-1) weighting.

Try doing this in Befunge, with a literal rotation.

Using chicken and egg is also a good touch on this one.

Technically world! Hello, isn't a rotation of Hello, world!; world!Hello,  is.

Right you are! Fixed, thanks

APL (158 characters, score = 4)
'''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0

I'm using Dyalog APL here. The number of cycles can be increased by one by adding 0  (0 followed by a space) to the end of the expression and to the end of the string (before '''). The cycle length is (# 0's) + 1, and the length of the expression is 150 + 4*(cycle length)). Assuming we continue adding zeros forever, the score is Limit[(150 + 4*n)/(n - 1), n -> Infinity] = 4, where n is the cycle length.
Here's an example with cycle length=6:
      '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0
 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0

      0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0
 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0

      0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0
 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0

      0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0
 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0

      0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0
 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1

      0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1
'''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0

192 characters, score = 2
'''{2≠⍴⍺:¯3⌽(2×1+⍴⍺)⍴(1+⍴⍺)⍴⍺ ⋄ a←⊃2⌷⍺ ⋄ ⍵=0:¯2⌽(2×1+⍴a)⍴(1+⍴a)⍴a⋄(-4+⌊10⍟⊃⍺)⌽(2×1+⍴a)⍴(1+⍴a)⍴a}01'''{2≠⍴⍺:¯3⌽(2×1+⍴⍺)⍴(1+⍴⍺)⍴⍺⋄a←⊃2⌷⍺⋄⍵=0:¯2⌽(2×1+⍴a)⍴(1+⍴a)⍴a⋄(-4+⌊10⍟⊃⍺)⌽(2×1+⍴a)⍴(1+⍴a)⍴a}01

Depending on the implementation, one point of failure could be when the integer prefixed to the string is too large. Theoretically, though, we can add a cycle by adding two characters - a 1 at the end of the string (before ''') and a 1 at the end of the entire line.
200 characters, score = 1
'''{a←{2=⍴⍵:⊃2⌷⍵⋄⍵}⍺⋄(⍺{⍵=9:⍬⋄⍕1+{2=⍴⍵:10×⊃⍵⋄0}⍺}⍵),(¯2⌽(2×1+⍴a)⍴(1+⍴a)⍴a),⍺{⍵=9:(⍕9),⍕⊃⍺⋄⍕⌊⍵÷10}⍵}'''{a←{2=⍴⍵:⊃2⌷⍵⋄⍵}⍺⋄(⍺{⍵=9:⍬⋄⍕1+{2=⍴⍵:10×⊃⍵⋄0}⍺}⍵),(¯2⌽(2×1+⍴a)⍴(1+⍴a)⍴a),⍺{⍵=9:(⍕9),⍕⊃⍺⋄⍕⌊⍵÷10}⍵}91

My APL implementation doesn't have unlimited precision integers by default, so the integer is converted to a float when it becomes too large, causing the output to be wrong. So this one is the most finicky, but theoretically (either by hand or with a different APL interpreter), it should have a score of 1. Just add a 1 to the end of the expression, and you get another cycle.
Overview (with a shorter quine)
I'm going to give an overview of the first version, because I think it's probably the easiest to comprehend. Before tackling that version, however, we're going to consider a simple quine in APL:
1⌽22⍴11⍴'''1⌽22⍴11⍴'''

I've found that one of the best ways to understand some APL expressions is to look at the output throughout the cascade of operators/functions. All operators and functions in APL are right-associative and have the same precedence, so here is is, from right to left:

'''1⌽22⍴11⍴''': This is just a string literal (a list of characters). '' is the APL way of escaping single quote marks. Output: '1⌽22⍴11⍴'.
11⍴'''1⌽22⍴11⍴''': Here, we reshape (⍴) the string to be of length 11. Because the string's length is under 11, it is repeated (i.e., 5⍴'abc' would yield 'abcab'). Output: '1⌽22⍴11⍴''. So we now have two quotation marks at the end - we're getting somewhere!
22⍴11⍴'''1⌽22⍴11⍴''': Similarly, we now reshape our previous output to be of length 22. Output: '1⌽22⍴11⍴'''1⌽22⍴11⍴''. We're almost there - we just need to move the first single quote to the end.
1⌽22⍴11⍴'''1⌽22⍴11⍴''': Here, we rotate (⌽) the list of characters by 1. This moves the first character of the string to the end. As another example, 2⌽'abcdef' returns 'cdefab'. Output: 1⌽22⍴11⍴'''1⌽22⍴11⍴'''.

The rotating quine
That short quine is the main basis for our rotating quine. Now, with that in mind, let's take a look at our quine:
'''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0

{ ... } defines an unnamed function, which is where we'll be doing the work. Note that functions in APL take a right argument, denoted by ⍵, and an optional left argument, denoted by ⍺ (think infix). We want to feed this function both our quine string and something to aid us in creating an arbitrary number of cycles. To make things easier on ourselves (and anyone wanting to add cycles), we make the quine string the left argument. The right argument, then, is where we put our list of cycles. 2 or more items separated by a space creates a list, so in this example, we have 2-element list consisting of a 1 and a 0.
We can see that the function looks similar to the quine from before. We have the same ...⌽...⍴...⍴... form from before. So that's good - we at least understand that much! Let's delve deeper into the ellipses, starting with everything after the last ⍴: ⊃,/(~^/¨⍺=0)/⍺.

As you can see by looking at the example above, we prefix the string with the 0's from the right-hand side, adding one with each iteration; but we don't care about those right now. We just want the string!
First, consider what's in the parentheses. (They group like in most other languages, by the way.)

⍺=0 returns a list, in this case, with the same shape as ⍺, where each element in ⍺ is replaced by a 1 if it is equal to 0, and a 0 otherwise. This is performed recursively; so if we have a list of a list of a list of characters, the individual characters will be tested against 0, and you will get back a list of a list of a list of binary values.
So if ⍺ consists of just our string, we get back a list of 0's. Otherwise, our left argument has some 0's prefixed to it (e.g., 0 0 0 'quinestring'), so it is a list consisting of 0's and another list, our string. Then our output looks like 1 1 1 <sub-list of zeros>.
^/¨⍺=0: We apply the derived function ^/, which reduces (/) using the logical AND (^) function, to each (¨) element of ⍺=0. This is to flatten the sub-list of zeros so that we can consider the quine string to be one binary value. Considering the previous example, the output would be 1 1 1 0.
~: We binary NOT each of the values from before (e.g., returning 0 0 0 1).

(~^/¨⍺=0)/⍺: For each element in ⍺, we replicate (/) it the number of times given by the corresponding element in the left argument. This eliminates all of the 0's, leaving us only with our quine string.
⊃,/ is some necessary paperwork to ensure that we get back a flattened list of characters, by reducing the result with the concatenation function (,). If the input is already a flattened list (i.e., the left argument to our main function is only the string), we get a 1-element list containing that list. In the other case, when we have a list consisting of a sub-list for the string, we get the same thing back (a list with a sub-list). We then unpack this (⊃), giving us only the first element of the list (i.e., the sub-list of characters). This might seem unnecessary, but otherwise we would then be trying to reshape a 1-element list!

Next, we look at the length given for the first reshape, within the parentheses:

⍺,⍵: We concatenate the right argument to the first argument
⊃,/⍺,⍵: Same as before - flatten the list.
+/0=⊃,/⍺,⍵: Add up the number of zeros in the list by reducing (/) using the addition (+) function.
2×+/0=⊃,/⍺,⍵: Multiply that number by two.
z←2×+/0=⊃,/⍺,⍵: Assign (←) the result to a variable, z. To recap, z is now twice the number of zeros found in both the left and right arguments.
77+z←2×+/0=⊃,/⍺,⍵: We then add 77, for the characters in the quine string, ignoring everything after the space following 1. Like in the initial quine example, we add 1 to the length of the string to get another single quote.
The output of this reshape, in this example, is: '{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 ''

The argument to the reshape that follows is simple and mirrors the short quine (2 times the length for the first reshape). Our output now is:
'{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 ''

Now for the final step, where we calculate how much to rotate the output string:

As you can see by looking at the previous output, we want to rotate it back (a negative amount) to bring the 2 final quotes to the beginning. Because we want a 0 (and another space) to move to the beginning as well, we want to rotate it an additional 3 characters back.
+/+/¨⍺=0: Add up the number of zeros in the left argument. The first (from the right) +/¨ sums each element's count (i.e., a sublist or just an integer), and the second +/ gives us the sum of that resulting list.
5+2×+/+/¨⍺=0: Multiply by two (to rotate the spaces as well), and add 5 (the result we came up with before).
Now, we subtract the previous value from the left argument to - to handle the case when we hit the end of our cycle:

(3+z)×^/⍵: AND all of the elements in the right argument together to see if we've reached our end (1), and multiply that by 3+z.

And we're done!

Wow, very cool, I didn't expect anything like this when I wrote the original question! I don't speak APL at all, is there any chance you could give an overview of how this works?

Sure! I've got a couple more versions to post (with theoretically lower scores), so I'll add an overview with those sometime tomorrow.

Thanks very much for your extremely thorough documentation, you're using some neat tricks here. I especially like the use of the ⍴ operator(?). I think I'll have to read through the whole thing a couple more times before I fully digest it!

GolfScript, 10046 / 9999 ≈ 1.0047 (asymptotic score 1)
OK, I'm going to try and beat D C's APL entry with this:
{\''+.,{(;\'.~1'}{'1'9999*@'.~']puts:puts}if}.~

The code above is not the actual quine — I felt that posting a 10kB one-liner would not be a very good idea.  Rather, running the code above once produces the actual 10046-char GolfScript program, which, when iterated as specified in the question, generates 9999 rotations of itself and, finally, itself again.
The length of the cycle (and the program) can be adjusted by changing the constant 9999.  For brevity and convenience, I'll show what the iterated output looks like if the constant is reduced to 9:
111111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~
11111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~1
1111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~11
111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~111
11111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~1111
1111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~11111
111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~111111
11{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~1111111
1{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~11111111
{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~111111111
111111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~
11111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~1
1111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~11
111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~111
etc.

As the constant 9999 is increased, the ratio of the program length and cycle length (minus one) tends to one.
I'm pretty sure that this solution can't be beaten, at least not asymptotically. ;-)
How does it work?
GolfScript is a pretty easy language to write quines in, since basically any number literal acts as a quine: for example, the GolfScript program 12345 outputs — you guessed it — 12345.  Also, concatenating multiple quines typically produces a quine.  Thus, I could use a simple number like 11111...111 as the repetitive part of my cyclic quine.
However, to get the quine to actually cycle, we need to carry and execute a non-trivial "payload".  The simplest GolfScript quine I could think of that can do that is the following:
{PAYLOAD'.~'}.~

So my plan was to prefix a quine like that with a repetitive numeric constant, and use a payload that chops one digit off the number and moves it to the end of the program.  If the program detects that there is no numeric constant in front of it (in which case the value below it on the stack will be an empty string, assuming there no input), it will instead prepend a fixed-length numeric constant in front of itself.
There's one additional wrinkle, though — when "wrapping around", the payload must also suppress the output of the number after itself.  Normally, when a GolfScript program ends, all values on the stack are automatically printed, which would be a problem here.
However, there turns out to be an (AFAIK) undocumented way to avoid that: the interpreter actually calls the predefined function puts to do the printing, so redefining that function as a no-op suppresses the automatic output.  Of course, this also means that we must first call puts ourselves to print the part of the stack we want printed.
The final code looks pretty messy (even for GolfScript), but at least it works.  I suspect there may be some clever ways I haven't yet thought of to shave a few chars off the payload, but for this version I was mainly just focusing on the asymptotic score.

Seems to work for me without the puts{}:puts, although I could see an argument for {print}:puts on the grounds that a newline in the output would mean that it isn't strictly cycling.

@Peter: The ]puts{}:puts is needed for the wrap-around from {STUFF}.~111111111 to 111111111{STUFF}.~, otherwise the number of 1s at the end of the program just keeps growing and growing.  (The {} seems to be unnecessary, though; apparently, the GolfScript interpreter allows assignment from an empty stack.)

Very nice, although it looks like D C has also posted a solution with an asymptotic score of 1, so we might have a tie.

Alice, 94 bytes, score --> 1
<pp&a0Ra*880R9Z640R8Z5e0R7*a70R6Z060R5Z9e0R4Z4R20R3*79Y3Zea0eZ1R51!Z73

Unfortunately, I had to fix a bug in the interpreter to make this work, so this doesn't work on TIO.
Explanation
This is a straightforward extension of my solution to Rotation-safe quine. Since that solution is a proper, payload-capable quine for every rotation of the source code, we can simply shift the source by one character before printing to cycle through all possible rotations. So this solution has byte count = cycle length.
The code we're writing into the grid to do so is
@o&~,.^'h%?t"

The only difference to the other quine is that we pull up the 94th character to the top of the stack, before printing everything.
We can arbitrarily increase the byte count and cycle length by adding no-ops anywhere in the program, which lets the score tend arbitrarily close to 1.

Python 3.8 (pre-release), 127 bytes, asymptotic score = 1
000000000
for i in 1,0:exec(s:="i or print(end=-~-len(str(n))%10*'0'+f'\\nfor i in 1,0:exec(s:=%r);n={n//10 or 10**9}'%s)");n=1

Try it online!
How it works :
We run the for loop twice.

The first time we initialize the variable n to a power of 10 and
The second time we print our quine dividing n by 10 and prepending a 0 in front of the code.

When n is equals to 1, we set n to the initial power of 10 an we remove the prepending 0
By adjusting the number of 0 in the original program, modifying len(str(n))%10 by len(str(n))%< x > and n//10 or 10**9 by n//10 or 10**< x-1 >, with x -> infinity, the asymptotic score is 1

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Build an Authenticating SMTP Client
The basic parts of SMTP can be implemented in surprising little code. I was able to build an example SMTP client that works with Gmail and Amazon SES in about 320 characters using PHP.
Your task is to implement an SMTP client that can send UTF-8 email from at least 2 major providers listed here:

Gmail
Yahoo!
Live/Hotmail
Postmark
Amazon SES

Keep in mind that most require SSL support. Some SMTP services (like Amazon) require different SMTP Auth and From addresses. Your function can take input for the actual data transmitted. After all, it woudn't make sense to hard-code anything into the transport layer.

SMTP User
SMTP Password
SMTP Host
SMTP Port
DATA (message)
From email
To email

Sample DATA (message)
Subject: =?UTF-8?B?VGVzdCBFbWFpbA==?=\r\n
To: <him@gmail.com>\r\n
From: <you@gmail.com>\r\n
MIME-Version: 1.0\r\n
Content-Type: text/html; charset=utf-8\r\n
Content-Transfer-Encoding: base64\r\n\r\n
PGgxPlRlc3QgRW1haWw8L2gxPjxwPkhlbGxvIFRoZXJlITwvcD4=\r\n.

In Summary

Build an SMTP client that can send email through at least two of the services above.
Accepts the seven inputs needed to form a valid SMTP Auth request (above). (Might only need six inputs if you combine the "From" and "SMTP User" inputs).
Use as few characters as posible.

Welcome to CodeGolf.SE! Our FAQ requires that every challenge have a "An objective primary winning criterion", and you need to indicate what it is; [code-golf] (i.e. fewest source characters) is the most common but there are others. Please have a look at some well received contests to see what kind of specification is usual.

@dmckee, thanks! I assumed that "fewest source characters" was a given so I listed the other requirements above. However, I have amended the question with the [code-golf] tag. It would be great if someone with more rep could add other tags like "smtp".

-1 I (as a user, not as a mod---ignore the diamond for this message) dislike this question, because your "reference" solution doesn't display any originality---it just calls library functions to do the heavy-lifting. That's no fun! If your code actually handled the SMTP (using system-provided sockets is okay), the encryption (using system crypto primitives is okay), the base64, etc., then it'd be far more interesting to try to golf. But what you have now is basically a "which language provides the right libraries?" contest.

@ChrisJester-Young, I'm not sure what to say. Using built-in language functions like fsocketopen is to be expected. What exactly are you looking for in an example?

Oh, I see. I see you did actually implement your own SMTP. My bad for not seeing the second file in your Gist. :-P (I retracted my downvote, BTW.)

@ChrisJester-Young, I suppose. However, if they include a pre-built mail client - then they automatically fail because they don't meet the first requirement of "build an SMTP client". However, I can't imagine anyone having the time to build a TLS SSL implementation - so they are welcome to use system libraries to solve this problem.

That's a fair enough explanation. As I mentioned, I removed my downvote---you seemed to have adequately clarified your question. Thanks!

@ChrisJester-Young, ah, now your comment makes sense.

Python 3 864 bytes
Extremely quick and dirty. Works with AWS SES and Yahoo!. Could not get it to work with Postmark (requires STARTTLS) or Gmail (requires further authentication outside of the SMTP connection).
import socket,ssl
from base64 import*
N=b'\x00'
U='utf-8'
E=lambda s:s.encode(U)
D=lambda b:b.decode(U)
B=lambda s:D(b64encode(E(s)))
A=lambda f,t,j,b:E('\r\n'.join(['DATA','Subject: =?UTF-8?B?{}?=','To: <{}>','From: <{}>','MIME-Version: 1.0','Content-Type: text/html; charset=utf-8','Content-Transfer-Encoding: base64',B(b),'','.','']).format(B(j),t,f,b))
X=lambda s,e:s.startswith(e)
def S(h,u,p,t,f,j,b):
    c,F,W=ssl.wrap_socket(socket.create_connection((h,465))),lambda m:E(m if'amazonaws'in h else'<'+m+'>'),lambda m:c.write(m+b'\r\n')
    def R(d,o=[]):
        x,y=c.read(),str(d)
        if not(X(x,E(y))or filter(lambda i:X(i,X(x,E(y))),o)):raise RuntimeError(y+' '+repr(x))
    R(220);W(b'EHLO x');R(250);W(b'AUTH PLAIN '+b64encode(N+E(u)+N+E(p)));R(235);W(b'MAIL FROM: '+F(f));R(250);W(b'RCPT TO: '+F(t));R(250);W(A(f,t,j,b));R(250,(354,));W(b'QUIT')

Invoke like S(hostname, username, password, to, from_, subject, body)
Expect bugs and changes (kind of got bored so it feels slightly half-baked).

I have a feeling you're going to be one of the new regulars ;)

C# .NET, assuming all the proper namespaces have been imported and not counting newlines/whitespace as characters. Also, displays no output as it's used as a library function.
bool sm(string h, string u, string p, string r, string m) {
    try {
        SmtpClient smtp = new SmtpClient();
        smtp.Port = 587;
        smtp.Host = h;
        smtp.Credentials = new NetworkCredential(u, p);
        smtp.UseSsl = true;
        smtp.Send(u, r, "", m);
        return true;
    } catch {
        return false;
    }
}

In its compressed form, the way I would code it, it'd look like this:
bool sm(string h, string u, string p, string r, string m) { try { SmtpClient smtp = new SmtpClient(); smtp.Port = 587; smtp.Host = h; smtp.Credentials = new NetworkCredential(u, p); smtp.UseSsl = true; smtp.Send(u, r, "", m); return true; } catch { return false; } }

Call it cheating, because of using .NET, but 266 characters. Works with major providers that allow SMTP with STARTTLS authentication on port 587. I use this for my Gmail all the time, works with Windows Live Hotmail too. Can be used either client-side OR server-side, and requires .NET 2.0 or newer (so it's compatible with pretty much every Windows machine).

Almost forgot the SSL, that's all fine and good though. I fixed it, with +20 characters.

You did not 1. Build an SMTP client.

We will leave that for the op to decide :P As it was not said that library calls could not be used, I decline to change my code at this time.

You can use built-in functions and libraries, but you still have to build an SMTP client - not wrap one. ;)


text:
Return the first N primes
With a twist; your algorithm has to be less complex than O(X2) where X is the Nth prime. Your solution post should include the character count and the theoretical complexity in terms of X (or N, which ~= X/ln(X) and so will usually be more efficient)
Here's a hint solution in C# (O(Xln(sqrt(X))), 137 chars):

 public List<int> P(int n){var r = new List<int>{2}; int i=3; while(r.Count<n) if(!r.TakeWhile(x=>x<Math.Sqrt(i)).Any(x=>i%x==0)) r.Add(i++); else i++; }

I fail to see how the sample is O(n*ln(sqrt(n))).  O(n*sqrt(n)) maybe, but there's nothing hints to why it would have an ln in there.  Please correct me if I'm wrong.

For each value tested, it's checked against all prime numbers less than the square root of the number. If you haven't found a prime factor by then you won't find one. There are on the order of ln(i) primes between 0 and any i. So, in finding prime X which is the Nth prime, you will have run checks equal to ln(sqrt(X)) against each number up to and including X. Or, simply, O(X*ln(sqrt(X))).

By the way, O(ln(sqrt(x)) == O(ln(x))

@KeithS actully, π(i) ~ i/ln(i). So, sqrt(X)/ln(sqrt(X)) ~ sqrt(X)/ln(X) and overall complexity of producing N ~= X/ln(X) primes is O(X^1.5 / (ln(X))^2 ), not counting the testing of composites, most of which are multiples of 2 or 3, so will be weeded out with very few tests.

@KeithS or in terms of N: X ~= N*log(N), it is O(N^1.5/sqrt(ln(N))). Or in practical terms N^1.4 .. 1.45. So you might want to amend your spec to "below N^1.5" (or at least "below X^1.5") or all kinds of solutions will have to be admitted.

J, 4 characters
p:i.

Usage:
   p:i.10
2 3 5 7 11 13 17 19 23 29

The problem with using J here is that I don't really know how efficient it is. I'd assume that as a language specialising in "mathematical, statistical, and logical analysis of data", that the algorithm used to generate the primes is pretty good.
I did look at the C source for clues, but it turns out that the C source for J is almost as unreadable as J itself. :-)
(The file is called v2.c for anyone who wants to have a look)

Haha, that C code is crazy, looks like someone tried to codegolf it.

My lord! The source looks as if it has been compiled already.

You could do some timing, like I did, couldn't you?

My goodness, is it how thinking in J affects one's coding style?:-)

I mean the J source code...

Haha, nice, and it reads "pi".

C, 98 characters
The good old sieve method.
We assume the first N primes are among the first N*24 integers. this works up to 2^32, because ln(2^32)<24. A general solution would need to estimate prime density, but since I use 32bit integers, I saw no need to generalize.
Complexity analysis (which I may do later) should use a formula instead of the constant 24.
i,j,m,*p;
f(n){
    p=calloc(m=n*24,4);
    for(i=2;n;i++)
        if(!p[i])for(n--,printf("%d\n",j=i);p[j+=i]=j<m;);
}

Nice work, very nice. Note: The expression p[j+=i]=j<m walks off the end of the array and corrupts memory. On my system, it corrupts printf and produces '\0' characters in the output (visible with | less or with | hexdump -C). To fix, instead say p[j]=j<m,j+=i, or maybe there is a way to write it with while(j<m)p[j]=1,j+=i; ?

@ToddLehman, you're right, I'm writing out of bounds. The easy fix is changing calloc's 2nd parameter to 8. I can't seem to do it, because of my employer's upload policy.

Haskell, 47 46
Since the problem definition demands less than O(X^2) complexity, where X ~= N*log(N), the following solution is acceptable. Its theoretical complexity is below O(X^2), testing each number below X by all its preceding numbers until a divisor is found. For primes only, having ~ X/log(X) primes overall, the complexity is thus O(X^2/log(X)). Most of the composites are multiples of small primes so are only divided few times, so they don't count.
p n=take n[n|n<-[2..],all((>0).rem n)[2..n-1]]

Prelude> last $ p 500
3571    (1.60 secs)
Prelude> last $ p 700
5279    (3.31 secs)
Prelude> logBase (5279/3571) (3.31/1.60)  -- in X
1.8597116027280054
Prelude> logBase (7/5) (3.31/1.60)        -- in N
2.1604889825177507

Prelude> last $ p 900
6997    (5.69 secs)
Prelude> logBase (6997/5279) (5.69/3.31)
1.9228821930296973                        -- in X
Prelude> logBase (9/7) (5.69/3.31)
2.155714108637307                         -- in N

If the complexity constraint in the problem definition will be amended to below O(N^1.5) (as I believe it should) then this solution will not be acceptable. That is why I post it in addition to another Haskell solution which is indeed better than O(N^1.5).

scala 191
Not the shortest one...
object P extends App{
def c(M:Int)={
val p=(false::false::true::List.range(3,M+1).map(_%2!=0)).toArray
for(i<-List.range(3,M)
if(p(i))){
var j=2*i;
while(j<M){
if(p(j))p(j)=false
j+=i}
}
(1 to M).filter(x=>p(x))
}
println(c(args(0).toInt))
}

Just measuring the method c, like the others do.
But how to prove, that it fulfills the Big-O requierement?
Well, I feed it with numbers, each twice as big as the number before. If it was of O(x²) complexity, it should need about 4 times as long, shouldn't it?
So I just measure it:
for p in {10..22}
do
  /usr/bin/time scala P $((2**p))> /dev/null
  echo "N="$((2**p))
done 2>&1 | tee primes.log

and then it's just a grep:
egrep -o "(^.*user|N=.*|#)" primes.log | tr "\n" "\t" | tr "#" "\n"
0.57user    N=1024
0.54user    N=2048
0.56user    N=4096
0.59user    N=8192
0.62user    N=16384
0.66user    N=32768
0.70user    N=65536
0.77user    N=131072
0.99user    N=262144
1.48user    N=524288
2.59user    N=1048576
5.68user    N=2097152
10.79user   N=4194304

So in the beginning there is only a startup overhead of about .55s - later it is a linear growth. For N'=2*N, t(N') ≈ 2*t(N).

you can assume growth of the order n^a, and estimate a as log( t2/t1 ) / log( n2/n1 ). Optimal trial division should run at about ~ n^1.30 .. 1.45. Sieve of Eratosthenes can be  n^1.0 .. 1.1. A priority-queue based s. of E. runs at about n^1.2 (it has an additional log factor compared with SoE).

Perl: 249 chars
The sieve certainly would have been shorter, but here is an implementation of the Miller-Rabin test:
sub p{
  $n=shift;
  $m=$n-1;
  return$n==2||$n==3if$n<=3or!($n&1);
  $s=unpack"%32b*",pack"L",($m&-$m)-1;
  for(1..5){
    next if($x=(int(rand($n-3))+2)**($n>>$s)%$n)==1||$x==$m;
    map{($x=$x**2%$n)==1&&last;$x==$m&&next}(1..$s-1);
  0}
1}
p($_)&&print"$_\n"for(1..$ARGV[0]);

Wikipedia says the runtime is O((log(X))^3)

Ruby (91)
Almost same as the example, so should have similar complexity. Unless I'm still missing something obvious (almost used select instead of take_while to save a few chars)
q=->n{k=[2];p=3;while k.size<n;k<<p if !k.take_while{|x|x*x<=p}.any?{|x|p%x<1};p+=2;end;k}

and with some whitespace:
q=->n{
  k=[2];
  p=3;
  while k.size<n;
    k<<p if !k.take_while{|x| x*x <= p }.any?{|x| p%x < 1};
    p+=2;
  end;
  k
}

Ruby 37
require 'prime'
p Prime.take gets.to_i

Can you elaborate on the Big-O of your approach?


text:
all occurences of each line from a file in another file for each line in the first file
This is a code golf problem: Say you have two files, one file s and one  file h. The problem is that for each line l of s you should produce a list that contains all lines of h that contain l. By "contain" I mean a substring, so, for example the line "foobar12baz" contains either foo, bar, foobar, 12, 1 or baz, etc...
You may use any programming language or any program to accomplish this in the least number of characters possible. Instead of a list you may print an array, or other sequence type structure.
Here is some Haskell I wrote that does it in 103 characters, and assumes you have the following modules imported
Data.List
Control.Monad
Control.Applicative
let f = (<$>) lines . readFile in (\(a,b)-> [[d|d<-b, isInfixOf c d]|c<-a]) <$> liftM2 (,) (f "s") (f "h")

Example files:
"h"
asdf1
asd2asdf
s3adsf

"s"
1
2
3

Output:
[["asdf1"],["asd2asdf"],["s3adsf"]]

Thanks for the edits, Wes. And again, welcome to CodeGolf.SE.

just grep is enough...
grep -Ff s h

Better:
puts IO.readlines('h').grep /#{IO.readlines's'}/

In ruby, 53 characters, outputs an array and not a file:
p IO.readlines('h').each{|m|m=~/#{IO.readlines's'}/}

This reads file 'h' for every line of 's' to save a variable. Not ideal.
Happy golfing!

while read -r;do grep "$REPLY" --h>"$REPLY";done<s

YEAAAAAAAH!!1