text:
Random ticket code generator
A lottery company wants to generate a random lottery ticket number of length 10 characters.
Write a code in any language to create such a number in which every digit comes only once for example 9354716208 in this number all integers from 0 to 9 comes only once. This number should be a random number.

The generated number should be shown on screen.
It must be able to generate all permutations of all allowable characters.
The code is required to be as small as possible (in bytes).

Why should it be in Java or PhP?

@Fabinout Sorry, you can write it in any language.

Generally, it's good idea to allow any language, according to [tag:code-golf] description.

I take it that all passwords beginning with zero should be possible.

Can the password be output as an array of characters?

@DavidCarraher I see nowhere in this question that the output is expected to be a "password". The challenge is asking to generate a "number". Thus, I think it's appropriate to assume that an array of characters is not acceptable. A string, in a language where strings are also treated as arrays of characters, may be - but something which is an array only probably is not. The following may be acceptable: 1234567890 or "1234567890". However, this probably would not: "1","2","3","4","5","6","7","8","9","0" nor the same with newlines instead of commas - with or without quotes in the output.

Yes. I meant to say "number". Btw, I agree that instructions appear to request a number (an integer or string integer). I was hoping that Ankush would explain his position.

How is it that one of the longest and least golfed answers (the SQL answer), without even a char count, stand as the accepted answer in [tag:code-golf] when folks like @Howard have 5 or 8 character answers?

Yes, @marinus has a 4 byte solution (mine is 6 bytes)

-1 The selection of the winner is improper, given that this was a code-golf challenge.

I am equally confused, the accept answer (which is massive by code-golf standards) was submitted after a GolfScript answer.

 J (4 bytes)
Couldn't resist.
?~10

In J, if F is dyadic , F~ x is the same as x F x.

+1 I think I may have to try something slightly more terse than Python to beat this.

Does this allow for a password that begins with zero?  According to the rules, the program "must be able to generate all permutations of all allowable characters"

@DavidCarraher: yes. It selects 10 non-repeating random numbers from the interval [0..10), so that basically means a random permutation of '0123456789'.

I see. I raised this because in most languages, the "number", 0123456789, will automatically be edited to the form 123456789. The string, "0123456789", remains untouched. So my question is really this: is your output a number or a string?

@DavidCarraher It's an array.

+1, if I wouldn't run out of votes. Seriously, I knew that J programs can be short, but like this?

marinus I have doubts about whether an array of characters can be considered a number. It would need to have its elements concatenated in some way. I'll ask the OP to get his view

J, 5 characters and APL, 8 characters
J
10?10

J has the built-in deal operator (?). Thus, we can take 10 out of 10 (10?10).
APL
1-⍨10?10

APL has the same operator which unfortunately starts with one instead of zero. We are therefore subtracting one from each number (1-⍨X means X-1 due to the commute operator).

Oh, wow, that's nice.

If OP would have asked specifically for the number not an array, you should convert it to base10 number also, with 10#.

You may assume that ⎕IO←0 so you don't have to subtract one. Also, for both J and APL, you can use commute to save a byte with ?~10 and ?⍨10 since monadic application of the derived function uses its right argument also as left argument. NOte however that this makes the J code identical to that of Marinus.

Python 2.7 (64 63 57)
Not a chance here compared to the operator heavy languages and due to the lack of default loaded random :) This is the shortest I could come up with;
from random import*
print''.join(sample("0123456789",10))

It creates a range and samples 10 numbers from it without replacement.
(Thanks to @xfix for the shorter import format fix and @blkknght for pointing out my somewhat über complicated sampling range)
Python 2.7 (40)
If you run it from the interactive prompt and can read comma separated, you can shave it to 40, but it feels a bit like breaking the spirit of the rules;
from random import*
sample(range(10),10)

You can use from random import* to save one character. This looks like my Perl 6 solution, but more verbose, but it's great to see that something like this can work in Python, even if more verbose.

@xfix Yes, sadly the modules in Python are a bit verbose to get to in comparison :) Updated with your import fix, quite new to the golfing thing so not up to "par" on my idioms.

You can save a few more characters by sampling from the string "0123456789" rather than using range and them mapping str.

@Blckknght Thanks, updated with your suggestion :)

Perl 6 (18 16 characters)
print pick *,^10

This generates array containing all random elements (pick *) from 0 to 9 and outputs the result (print).
Sample output:
$ perl6 -e 'print pick *,^10'
4801537269
$ perl6 -e 'print pick *,^10'
1970384265
$ perl6 -e 'print pick *,^10'
3571684902

+1 I think you don't need the whitespace before pick.

@Howard: I actually need it. [~] (which is parsed as a listop, according to Perl 6 grammar) requires a whitespace (or paren) after it if it contains any arguments. Otherwise, Perl 6 compiler complains about "two terms in row". It wasn't needed in older versions of Perl 6, but this is the past. The Perl 6 is still being worked on.

@xfix: use print instead of say [~] and save 2 characters :)

@Ayiko: Thanks for an improvement :).

Ruby, 18
Run this in irb:
[*0..9].shuffle*''

If you want this to be a stand-alone program, with output to stdout (the rules don't seem to require this), then add these 4 chars at the start:
$><<

You may shorten (0..9).to_a to [*0..9].

You're welcome. But why do you not use [*0..9].shuffle in the first place?

@Howard, because it's late and I'm dumb.  :)  Thanks!

this return array with number not number

@Monk_Code, could you prove it? On my machine it returns and IO object, but return value was not a requirement anyway. Otherwise it outputs a String. (Which in most languages is the only way to represent numbers beginning with 0.)

@Monk_Code, no, the program outputs a 10-digit string. This is what the question asks for.

Why the $><<? [*0..9].shuffle*'' on its own works just fine.

@AlexQueue, I wanted output. I used that because 1) it's 1 char shorter than puts , 2) it's 2 chars shorter than print , and I felt using p  was cheating because it includes double-quotes in the output.

PHP - 37 Characters
<?=join('',array_rand(range(0,9),10))

I had an 18-character solution that should theoretically work but PHP is weird.
Or, if you want an xkcd answer:
<?="5398421706" // Chosen by program above; guaranteed to be random ?>

EDIT: Thanks xfix, it's now 5 characters shorter and complete.
EDIT AGAIN: Live example.

Write a complete program, instead of just complete parts. Also, echo doesn't need parens, and if echo is the first statement in the program, you can replace <?php echo with <?=. Also, join is an alias for implode.

You don't even need the <?= and ?>. It's valid PHP code without those.

@Jeremy The golf requires that the number be displayed; besides, echo  is the same length as <?= and ?> combined, and without those, it doesn't work in Codepad. Thanks though. :P

I guess you're right. I was, however, thinking PHP in the terminal, where I guess you'd need an echo anyways.

@Jeremy Ah, PHP, where non-embedded implementations besides a terminal are scarce. :P

I get 0123456789 every time. Think it only works pre-5.2.10 since after that it has the result in order..

@Sylwester That's a very strange output. Array_rand must  be malfunctioning in the newer versions. :/

Am I doing something wrong, your live example gives the same number over and over again?

@TobyAllen Codepad only executes code once. Click "Create a new paste based on this one" and then click Submit.

PHP, 29 chars

<?=str_shuffle('0123456789');

With PHP, the closing tag isn't required. But if that's against the rules, then you can replace ; with ?> for 1 net increase.

You beat me to this solution.

GolfScript, 12 characters
10,{;9rand}$

Simply generates the list of digits (10,) and sorts it {...}$ according to some random keys - which yields a random order of the digits.
Examples (try online):
4860972315

0137462985

I was about to post this :P

That's kind of a crap shuffle, though: for example, the first digit is about three times as likely to be 0 than 1. Replacing 9rand with 99rand would (mostly) fix that; 9.?rand would be practically perfect.

@IlmariKaronen I know, but the question didn't say anything about uniform distribution.

R (23 characters)
cat(sample(0:9),sep="")

Sample output:
> cat(sample(0:9),sep="")
3570984216
> cat(sample(0:9),sep="")
3820791654
> cat(sample(0:9),sep="")
0548697132

TI-BASIC, 5 bytes
randIntNoRep(1,10

Displays a list rather than a number. You're looking for randIntNoRep(0,9:.1sum(Ans10^(cumSum(1 or Ans.

I don't think this challenge requires an integer type, only that "The generated number should be shown on screen" which it is.

Hmm, I thought the question was asking for a number (as did others but it seems the intent of the challenge author was never clarified. Some other solutions output as a list (J and APL) in any case.

Well, I wouldn't assume that unless I was sure, because this method is shorter.

Octave (14)
randperm(10)-1

randperm unfortunately creates a selection from 1..n, so have to subtract 1 at the end to get 0-9.

In sql server
DECLARE @RandomNo varchar(10)
SET @RandomNo = ''

;WITH num as (
SELECT 0 AS [number]
Union
select 1
Union
select 2
Union
select 3
Union
select 4
Union
select 5
Union
select 6
Union
select 7
Union
select 8
Union
select 9
)
SELECT Top 9 @RandomNo = COALESCE(@RandomNo + '', '') + cast(n.number AS varchar(1))
FROM numbers n
ORDER BY NEWID()

SELECT cast(@RandomNo AS numeric(10,0))

See Demo
OR something similar (courtesy of @manatwork) using recursion and xml.
with c as(select 0i union all select i+1from c where i<9)select i+0from c order by newid()for xml path('')

Man, you love CTEs… But as this is a [tag:code-golf] challenge, better shorten it as much as possible. My best is 186 characters: select i+0from(select 0i union select 1union select 2union select 3union select 4union select 5union select 6union select 7union select 8union select 9)f order by newid()for xml path(''). (BTW, great trick that newid().)

Ok, you'r right. Is shorter with CTE. 106 characters: with c as(select 0i union all select i+1from c where i<9)select i+0from c order by newid()for xml path('').

You can simplify the cte with (VALUES (1),(2),...)

Javascript (79 78 68 characters)
Rather than creating an array with the numbers 0-9 and sorting it, I decided to generate random numbers. When it came up with a number that was not already in the array then added it. This repeats ten times and then alerts the output.
for(a="";!a[9];){~a.indexOf(b=~~(Math.random()*10))||(a+=b)}alert(a)

You can save 1 byte using || short-circuit evaluation instead of if like:
for(a="";!a[9];){b=Math.floor(Math.random()*10);~a.indexOf(b)||(a+=b)}alert(a)

@StevenPalinkas Thanks, great idea! I have updated the post accordingly.

We could also save 2 bytes with a bit of rearrangement in the code: for(a="";!a[9];){~a.indexOf(b=Math.floor(Math.random()*10))||(a+=b)}alert(a)

We can save an additional 8 bytes using the "shorthand" for Math.floor like: for(a="";!a[9];){~a.indexOf(b=~~(Math.random()*10))||(a+=b)}alert(a)

Mathematica 40
The number is created as a string so as to allow zero to be displayed as the first character, when needed.
""<>RandomSample["0"~CharacterRange~"9"]

Output examples

"0568497231"
"6813029574"

Explanation
"0"~CharacterRange~"9" is infix notation for CharacterRange["0","9"].
Either of these returns the list, {"0","1","2","3","4","5","6","7","8","9"}.
RandomSample[list] by default returns a permutation of the list. (It can also be used for other kinds of sampling, when parameters are included.  E.g. RandomSample[list, 4] will return a Random sample of 4 characters, with no repeats.

But why to display 0 as the first character?

According to the OP, the program "must be able to generate all permutations of all allowable characters".

@Ankush That's infix notation, so "0" is not always the first char.

Ajasja is correct. The program  can generate any permutation. I added some remarks above to clarify this.

C#, 145 bytes
Ungolfed
using System;
using System.Linq;
class P
{
    static void Main()
    {
        Enumerable.Range(0,10).OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);
    }
}

Golfed
using System;using System.Linq;class P{static void Main(){Enumerable.Range(0,10).OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);}}

You can use Enumerable.Range(0,10), and you don't need the curly brackets in the foreach loop.

JavaScript, 82 characters
EDIT: Thanks to Rob W, code length is reduced to 90 characters.
EDIT: Thanks to George Reith, code length is reduced to 82 characters (using for loop).
Pretty straightforward way: pick random element of [0,1,2,3,4,5,6,7,8,9] array and append it to the output, then reduce array and replay.
Old version (106 characters):
a=[0,1,2,3,4,5,6,7,8,9],l=11,t="";while(--l){r=Math.floor(Math.random()*l);t+=a[r];a.splice(r,1);}alert(t)

Readable version:
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], l = 10,t = "";
while(l--) {
  r = Math.floor(Math.random() * l);
  t += a[r];
  a.splice(r, 1);
}
alert(t);

Better version (90 characters):
a="0123456789".split(t=""),l=11;while(--l)t+=a[r=0|Math.random()*l],a.splice(r,1);alert(t)

Last version (82 characters):
a="0123456789".split(t='');for(l=11;--l;t+=a.splice(0|Math.random()*l,1));alert(t)

JSFiddle: http://jsfiddle.net/gthacoder/qH3t9/.

I golfed down your method to 90 characters: a='0123456789'.split(t=''),l=10;while(l--)t+=a[r=0|Math.random()*l],a.splice(r,1);alert(t). Big savers: Math.random(x) === 0|x. Replace curly braces and semicolons with commas. Directly use the result of an assignment as a value, instead of using an intermediate variable. Finally, initialize the initial array using .split(r=''). This is shorter than creating an array using array literals and assigning the string value in a separate expression.

@RobW Thanks for the tips. I updated my answer. P.S. I guess you meant Math.floor(x) === 0|x.

This always has 9 at the end. To fix, initialize l=11 and switch your while loop condition to while(--l)

@Greg Good point. Thank you. I updated the answer.

I like how you took an in-place (fisher-yates) shuffle algorithm and made it shorter by creating a new string to hold the shuffled data.

88 Characters: a="0123456789".split(t="");for(l=11;--l;a.splice(r,1))t+=a[r=0|Math.random()*l];alert(t)

82 Characters: a="0123456789".split(t='');for(l=11;--l;t+=a.splice(0|Math.random()*l,1));alert(t) - Your code fits perfectly into a for loops initialisation, condition and expression arguments. The r variable is redundant.

@GeorgeReith Nice idea about for loop. Thank you. I updated my answer.

Mathematica, 27
Row@RandomSample@Range[0,9]

Nice way to avoid strings!

Shell/Coreutils, 23
shuf -i0-9|paste -sd ''

If we don't need a trailing newline, you can shave this to 20 with shuf -i0-9|tr -d \\n

what about shuf -zi0-9

@marcosm: That gives you lines terminated with zeroes, which is slightly strange.

K/Kona (6)
-10?10

As with J, ? is the deal operator; the - forces the values to not repeat.

Scala, 37
util.Random.shuffle(0 to 9).mkString

JavaScript (80 characters)
alert("0123456789".split("").sort(function(){return .5-Math.random()}).join(""))

JS-Fiddle: http://jsfiddle.net/IQAndreas/3rmza/

Note this can be golfed further by using an arrow function (which currently only works in FF, but is coming soon to interpreters everywhere): alert("0123456789".split("").sort(n=>.5-Math.random()).join(""))

"0123456789".split("") vs [0,1,2,3,4,5,6,7,8,9] saves one characters.

This doesn't really guarantee a random distribution. See http://sroucheray.org/blog/2009/11/array-sort-should-not-be-used-to-shuffle-an-array/. Nevertheless, that was not stipulated in the rules so good abuse.

You don't need the space between return and .5

@Greg Shhhh! Do you have any idea how many characters a real shuffling function takes? ;)

@Greg It is a random distribution (assuming Math.random is sufficiently random), it just isn't a uniform one.

The original blog post is gone, adding the internet archive for posterity: https://web.archive.org/web/20150212083701/http://sroucheray.org/blog/2009/11/array-sort-should-not-be-used-to-shuffle-an-array

Forth, 72
needs random.fs : r ': '0 do i loop 9 for i 1+ random roll emit next ; r

Room still to golf, maybe, but Forth made this one hard.  I think.

Prolog,  177/302 characters
I'm a beginner on Prolog, so probably this is not the most condensed code.
:- use_module(library(clpfd)).
sort(N) :-
    N = [N0,N1,N2,N3,N4,N5,N6,N7,N8,N9],
    domain([N0],1,9),
    domain([N1,N2,N3,N4,N5,N6,N7,N8,N9],0,9),
    all_different(N),
    labeling([],N).

Returns:
| ?- sort2(N).
N = [1,0,2,3,4,5,6,7,8,9] ? ;
N = [1,0,2,3,4,5,6,7,9,8] ? ;
N = [1,0,2,3,4,5,6,8,7,9] ? ;
N = [1,0,2,3,4,5,6,8,9,7] ? ;
N = [1,0,2,3,4,5,6,9,7,8] ?
yes

If you want it to return an integer:
:- use_module(library(clpfd)).
sort(M) :-
    N = [N0,N1,N2,N3,N4,N5,N6,N7,N8,N9],
    domain([N0],1,9),
    domain([N1,N2,N3,N4,N5,N6,N7,N8,N9],0,9),
    all_different(N),
    labeling([],N),
    M is (N0*1000000000)+(N1*100000000)+(N2*10000000)+(N3*1000000)+
         (N4*100000)+(N5*10000)+(N6*1000)+(N7*100)+(N8*10)+N9.

Returns:
| ?- sort(N).
N = 1023456789 ? ;
N = 1023456798 ? ;
N = 1023456879 ? ;
N = 1023456897 ? ;
N = 1023456978 ?
yes

Using instead:
labeling([down],N)

Gives the numbers in the opposite order:
| ?- sort(N).
N = 9876543210 ? n
N = 9876543201 ? n
N = 9876543120 ? n
N = 9876543102 ? n
N = 9876543021 ?
yes

Unlike some other codes posted, this returns all possibilities (with no repetitions).

Clojure, 42
(println (apply str (shuffle (range 10))))

6209847315

The generated number should be shown on screen, not it's parts.

q/kdb [6 chars]
-10?10

will generate 10 unique random numbers.

√ å ı ¥ ® Ï Ø ¿ , 4 bytes
XrśO

X    › Push 10 to the stack
 r   › Push the range from [1...10]
  ś  › Shuffle the stack
   O › Output the whole stack separated by spaces

Javascript, 83 characters
a=[];while(!a[9]){b=Math.floor(Math.random()*10);!a.includes(b)&&a.push(b)}alert(a)

While running until array has 10 elements.
Generating random number from 0 - 9 then check if array !includes this number and add it to the array.

Welcome to the site! :)

Vyxal s, 4 bytes
kdÞ℅

Try it Online!
Explanation:
kd   # Digits `0123456789`
  Þ℅ # Random permutation
     # 's' flag - Print the sum of the top of the stack

F#,  71 63 characters
I'm new to F#, but here's what I've come up with:
{ 0..9 }
    |> Seq.sortBy (fun _ -> System.Guid.NewGuid())
    |> Seq.iter (printf "%d")

compacted:
{0..9}|>Seq.sortBy(fun _->Guid.NewGuid())|>Seq.iter(printf"%d")

This is not much smaller than JMK's answer, but here's a slightly smaller C# solution (135):
using System;
using System.Linq;
class P {
    static void Main()
    {
        Console.Write(string.Join("", "0123456789".OrderBy(g => Guid.NewGuid())));
    }
}

Compacted (134):
using System;using System.Linq;class P{static void Main(){Console.Write(string.Join("", "0123456789".OrderBy(g => Guid.NewGuid())));}}

Alternate version (135):
using System;
using System.Linq;
class P {
    static void Main()
    {
        "0123456789".OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);
    }
}

Compacted:
using System;using System.Linq;class P{static void Main(){"0123456789".OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);}}

They're equal in length, but it really just depends on whether you want to use Linq's ForEach function or String's Join function. I was able to remove 10 characters in length by spelling out the range "0123456789" in a string instead of using Enumerable.Range(0, 10).

LOGO, 64 characters
make "d 1234567890
repeat 10 [
    make "n pick d
    show n
    make "d butmember n d
]

pick returns random item of the supplied list.
butmember returns list with all occurrences of the specified item removed.
Note: Not all Logo implementations support butmember command.

Racket 45 43
(map print(shuffle'(0 1 2 3 4 5 6 7 8 9)))

Javascript (96)
function x(){return s.search(r=0|Math.random()*10)<0?r:x()}for(i=0,s='';++i<=10;s+=x());alert(s)

First attempt (109)
s='';for(i=0;++i<=10;s+=(x=function(){return s.indexOf(r=(m=Math).floor(m.random()*10))<0?r:x()})())alert(s);

Java 8, 153 150 143 139 130 bytes
import java.util.*;v->{List l=new Stack();for(int i=0;i<=9;l.add(i+++""));Collections.shuffle(l);System.out.print("".join("",l));}

-7 bytes thanks to @KritixiLithos
Explanation:
Try it here.
import java.util.*;                // Required import for List, Stack, Collections
v->{                               // Method with empty unused parameter and no return-type
  List l=new Stack();              //  List
  for(int i=0;i<=9;                //  Loop from 0 to 9 (inclusive)
    l.add(i+++""));                //   Add these numbers to the List (as String)
  Collections.shuffle(l);          //  Randomly shuffle the List
  System.out.print("".join("",l));}//  Print the List content without delimiter

String.join("",l) is shorter than replacement. Try it online!

But in order for ^ to work, you need only int elements, so you can do l.add(i+++"") in the for-loop

SmileBASIC, 50 bytes
S$="0123456789
@L
SWAP S$[RND(10)],S$[0]?S$GOSUB@L

Explained:
S$="0123456789" 'create string with digits 0-9
@LOOP 'label
SWAP S$[RND(10)],S$[0] 'swap a random character with the first character
PRINT S$ 'print the string
GOSUB @LOOP 'Loop. Using GOSUB without RETURN will eventually cause a stack overflow, ending the program.

what stops this having duplicate numbers?

Wow it seems like a lot of people made the same mistake. It should work correctly now.

Sinclair ZX81/Timex TS1000/1500 BASIC, 133 bytes 144 bytes 97 bytes (listing)
I started this by trying to imagine how PHP's str_shuffle() would work in Sinclair [ZX81] BASIC, and ended here (new and improved version):
1 LET A$="0987654321"
2 LET R=INT (RND* LEN A$)+1
3 PRINT A$(R);
4 LET A$=A$( TO R-1)+A$(R+1 TO )
5 GOTO 2+((A$="")*4)

This solution is based on a post by XavSnap on the Sinclair ZX World forums after I posted my solution below.
Initial entry (slower and bloated):
1 LET A$="0123456789"
2 LET B$=""
3 FOR I=0 TO 9
4 GOSUB 8
5 NEXT I
6 PRINT B$
7 STOP
8 LET A=1+INT (RND*10)
9 IF A$(A)=" " THEN GOTO 8
10 LET B$=B$+A$(A)
11 LET A$(A)=" "
12 RETURN

Some things to note

Sinclair ZX80 and ZX81 BASIC does not accept multi-statemented lines, like 10 PRINT "HELLO":GOTO 10
The interpreter adds in white spaces before and after most commands, so this version of BASIC is one of the most difficult to golf
You can manipulate strings by position like a char[] in C, although strings are indexed from 1 and not 0
This new version will work on an unexpanded (1K/2K) machine for real
When I've worked it out, the byte count is the listing only, it's using more system RAM. As this is 8 bit tech, I'll also work out the actual byte count (listing + variable stack)

05AB1E, 4 bytes
The language probably changed in between the exercise and my solution, so this is not really competing.
žh.r
Try online

Japt, 6 4 bytes
Aö¬q

Try it online

Explanation
ö¬ generates a random permutation of the range [0-10) (with A being the Japt constant for 10) and q joins it to string.

Tcl, 84 bytes
proc f a\ b {expr rand()>.5}
puts [join [lsort -command f {1 2 3 4 5 6 7 8 9 0}] ""]

Try it online!

[split 1234567890 ""] renders the same byte extent as {1 2 3 4 5 6 7 8 9 0}

Failed outgolf: puts [join [lsort -command {apply {a\ b {expr rand()>.5}}} {1 2 3 4 5 6 7 8 9 0}] ""]

Perl 5, 21 bytes
@k{0..9}++;say keys%k

Try it online!
Perl's hash algorithm puts the hash keys into a a random order, so this should satisfy the requirements.
If it doesn't, here's the old method:
Perl 5, 38 bytes
@a=0..9;print splice@a,rand@a,1while@a

Try it online!

LibreLogo, 96 bytes
Code:
x=list(range 10)
c=1
z='' while c>0[ r=int(ps any) if r<c[ z+=str(x.pop(r)) ] c=count x ]print z

Explanation:
x = list(range 10)                 ; x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
c = 1
z = ''
while c > 0 [                      ; While !empty( x )
    r = int(ps any)                ;     r = random 10
    if r < c [                     ;     If Random # < count( x )
        z += str(x.pop(r))         ;         z.append( x[random] ), x.remove( x[random] )
    ]
    c = count x                    ; Keep track of leftover elements
]
print z                            ; Print Result

Result:

Pyt, 3 bytes
ɳᒆʀ

Explanation:
ɳ           Push the string "0123456789" onto the stack
 ᒆ         Push an array containing all possible permutations (of "0123456789") onto the stack
  ʀ         Pick an element from the array uniformly at random

Try it online!

><>, 17 11 12 bytes
-6 bytes thanks to @Teal pelican suggesting a better way to generate the numbers 0-9. Thanks to @Not a Tree for pointing out the previous version only starts with a 9 or a 0.
<v?=9:l
{xn!

Try It Online!
Adds all the numbers to the stack and then randomly chooses between cycling the stack or outputting the number until the stack is the empty. Biased towards larger numbers first, but the random wasn't specified to be uniform.
An 11 byte version that doesn't work on TIO due to { erroring on an empty stack, but works on other platforms such as here.
{l:b=?.!
xn

If you change the 0-9 code you can reduce it a bit; 11 bytes

@Tealpelican Thanks!

I think for the 10 byte version you meant } not { as { will remove 5 from the output but } will remove 0 from the output so none would work. A note :- TIO errors on trying to move right or left on an empty stack because it tries to pop then push from an empty stack. The ><> esolang page doesn't express what should or should not happen in this instance but as the "official" interpreter was written in python with the pop instruction used in both move right and left then TIO is acting correctly.

This kind of question is why I wish we had single way angled mirrors in ><> something like this; ◣ where going up or right reverse the direction but down and right change it axis

Are you sure this can produce every permutation? It always seems to return a number starting with 0 or 9. I think you can fix it by adding ! to the end of the second line, though.

Good point @Notatree! Fixed

Chip, 75 + 17 = 92 bytes
+17 bytes for args -g0i -w -mq -c20
 8 ?]v~S
?/--^]~9
A\0)0/a
B\1)1/b
C\2)2/c
D\3)3/d
,L-v-^e
)\sf
`zzzzzzzzzz*

Try it online! Try adding -vv to the args list to see the values on the queue as it runs, in the debug output.
Not the most straightforward solution... The strategy here is like this:

fill a queue with the numbers 0 through 9
pop the head of the queue, call this x
generate a random number 0 to 3

if 3, print x
if not 3, append x back onto the queue

jump to step 2 until all ten numbers have been printed

This strategy ensures that all permutations are possible, however the permutations are not evenly distributed. Also, it is theoretically possible to never finish printing.
This could potentially be slightly smaller if I generate a single random bit (0 or 1) instead of two (0 to 3), but it would have a more extreme effect on the distribution. My initial attempt, however, didn't actually save many bytes.
If there is interest, I will endeavor to explain further the actual implementation details.

C# (.NET Core), 81 bytes
()=>string.Join("",Enumerable.Range(0,10).OrderBy(x=>new System.Random().Next()))

Try it online!

Zsh, 20 bytes
shuf -i0-9|tr -d \\n
Attempt This Online!

Thunno 2, 4 bytes
kDµr

Attempt This Online!
Explanation
kDµr  # Implicit input
kD    # Push the string "0123456789"
  µr  # Take a random permutation
      # Implicit output

SPSS (174 bytes)
Most of the commands in SPSS can be shortened to the first three letter. It is convenient for code golfing.
new fil.
inp pro.
loo i=0 to 9.
comp R=uni(1).
end cas.
end loo.
end fil.
end inp pro.
sor cas R.
fli i.
for var001 to var010 (f1).
wri /var001 to var010.
exe.

Bash (79 characters)
seq 0 9|awk 'BEGIN{srand()}{print rand()"\t"$0}'|sort -nk1|cut -f2-|tr -d '\n'

Note that the lottery company should not run this more than once per second!
Edit: Oh rats, this answer blows mine away.

C, 97 characters
C is unrepresented...time to fix that!
d[10],i;main(j){srand(&j);while(i++<10){doj=rand()%10;while(d[j]);d[j]=putchar(j+'0');}puts("");}

Slightly more legible:
d[10],i;
main(j){
  srand(&j);
  while(i++<10){
    do
      j=rand()%10;
    while(d[j]);
    d[j]=putchar(j+'0');
  }
  puts("");
}

CJam, 5 bytes
10,mr
10,    e#Range 0..9 inclusive
   mr  e#Shuffle

Powershell, 24 Bytes
-join(0..9|sort{random})

Explanation:
-join( #Join an array of
0..9 #The numbers 0-9
|sort{random} #Sorted into a random order
)

running it 10 times results in:
9184702653
7813529406
0458237691
2158604793
5391782046
4673980251
4870532196
9412576380
4816275309
1098624537
4257910683

C 144 bytes
f(){srand(time(0));j,i,a[10];for(i=0;i<=9;i++){a[i]=i;}for(i=0;i<4;i++){j=rand()%9;a[j]=9-j;a[9-j]=9-a[j];}for(i=0;i<=9;i++)printf("%d",a[i]);}

Ungolfed version:
void f()
{
   srand(time(NULL));
   int j, i, a[10];

   for (i = 0; i <= 9; i++)
      a[i] = i;

   //jumble the array elements
   for (i = 0; i<4; i++)
   {
       j = rand() % 9;
       a[j] = 9 - j;
       a[9 - j] = 9 - a[j];
   }

    for (i = 0; i <= 9; i++)
       printf("%d ", a[i]);

}

Usage
Every time this binary is executed, a new random array of numbers from 0 to 9 is printed.
Explanation

srand is used so that a new seed is produced everytime for rand function.
Store the elements from 0 to 9 in an array.
Jumble the array elements by generating four random values between 0-9. (I'm not sure if that step was so wise, can be done in a better way i guess.)
Print the array elements

Lithp, 66 bytes
(print(join(list-rand(permutations(list 0 1 2 3 4 5 6 7 8 9)))""))

Try it online!
permutations/1 generates all permutations of the given list. There will be no duplicates. We pick a random item from the generated permutations and print it.
The try it online link has a better example for printing out a number of unique entries.
This could be a little shorter if the lists module is imported, but importing it takes up more space than is saved by a (seq 0 9) call.

Python 2, 77 bytes
from random import*;x=range(10);shuffle(x);print ''.join([str(i) for i in x])

Try it online!
This creates the desired list using Python's range, then shuffles it using random.shuffle. random.shuffle just randomizes the list. Then it prints out each item in the list joined by ''.

(space)''.join([str(i) for i in x]) -> \x`[1::3]`

Factor, 33 bytes
10 iota 10 sample [ pprint ] each

Try it online!

Snippet
Comment
Data stack (top on right)

10 iota
A range of numbers from 0 inclusive to 10 exclusive
{ 0 1 2 3 4 5 6 7 8 9 }

10 sample
Take 10 random samples from a sequence without replacement
{ 7 3 8 4 2 5 1 9 6 0 }

[ pprint ] each
Prettyprint each element without a newline

Ly, 24 bytes
9[:,]y[0f?[fsprlr,]puy]p

Try it online!
This adds the digits 0-9 onto the stack, then as long as the stack isn't empty, it picks a random number, rotates the stack entries that many times, then prints the top of the stack.
9[:,]                     - pushes 9, 8, 7, ... 0 onto the stack
     y[              y]p  - loops as long as the stack size>0
       0f?                - generate random number in 0-(stack-size) range
          [      ,]p      - loops for as many rotations as we want to do
           fsp            - flip the random digit to the top, save and delete
              rlr         - reverse the stack, load saved digit, reverse again
                    u     - print the random digit we picked

The number of rotations used really should be in the range 0-(stack-size-1) but the possible extra rotation doesn't hurt anything and it saves a character to use the larger range.


text:
Tips for golfing in Raku
What general tips do you have for golfing in Raku? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Raku (e.g. "remove comments" is not an answer). Please post one tip per answer.

Avoid sub literals. In many cases, you can simply use {} for code blocks. For example, don't write the following code.
sub ($a){$a*2}

Instead, use blocks syntax. This also lets you to use $_, @_, and %_ placeholder variables, if you only need a single variable. If you need more, you can use $^a, $^b variables, and so on.
{$_*2}

Also, in certain rare cases, it's possible to use whatever code (especially when you have simple expressions). The * replaces the placeholder argument.
* *2

Raku has a really bizarre feature where it allows all Unicode characters in categories Nd, Nl, and No to be used as rational number literals. Some of these are shorter than writing their numeric values out in ASCII:

¼ (2 bytes) is shorter than .25 or 1/4 (3 bytes).
¾ (2 bytes) is shorter than .75 or 3/4 (3 bytes).
৴ (3 bytes) is shorter than 1/16 (4 bytes).
 (4 bytes) is shorter than 11/12 (5 bytes).
 (4 bytes) is shorter than 216e3 (5 bytes).
 (4 bytes) is shorter than 432e3 (5 bytes).

As a follow-up for this, you can also use Unicode exponents, even with multiple digits and/or a minus: say (3² + 4², 2²⁰, 5⁻²) ==> (25 1048576 0.04). The complete list of Unicode you can abuse like this is here: https://docs.perl6.org/language/unicode_texas .

Above link is dead, it's now: https://docs.raku.org/language/unicode_ascii

Learn the functions to read the input. Raku has many interesting functions that can easily read the input from ARGV, or STDIN (if nothing was specified on ARGV), which can shorten your code if used correctly. If you call them as filehandle methods, you can force them to work on particular filehandle (useful if you for example read from STDIN, but you have to read arguments on ARGV).
get
This function gets a single line, and automatically chomps it, so you don't have to. This is useful if you need to read just a one line.
lines
This function gets all lines from the file or STDIN. It's a lazy list, so if you use it with for, it will only read what you need. For example.
say "<$_>"for lines

slurp
This will read the entire file or STDIN, and will return the result as a single string.

That bug was fixed -- don't know when, but say "<$_>" for lines works now

Warning: Wall of text approaching. It's a lot of small tricks I gathered over time.
Write your solutions as anonymous blocks
This was mentioned already but I'd like to reiterate it. In TIO, you can write my $f = into the header, the block into the code proper, and start the footer with a ;. This seems to be by far the shortest way to get the job done (since you don't need to care about reading any input, it's given to you in the arguments).
Another nice way is using the -n or the -p switch, but I didn't find a way to make it work in TIO.
Use the colon syntax for passing arguments
That is, instead of thing.method(foo,bar), you can do thing.method:foo,bar and save 1 character. Unfortunately, you can't call another method on the result for obvious reasons, so it makes sense to use only for the last method in a block.
Use $_ as much as you can
Sometimes it's better to take a single list argument than several separate arguments because of this. When accessing $_, you may call methods on it just by starting with a dot: e. g. .sort is equal to $_.sort.
However, bear in mind that each block gets its own $_, so the parameters of the outer block won't propagate into the inner ones. If you need to access the parameters of the main function from an inner block, ...
Use the ^ variables if you can't use $_
Insert a ^ between the sigil and the variable name, like this: $^a. These work only inside a block. The compiler first counts how many of these you have in the block, sorts them lexicographically, and then assigns the first argument to the first one, the second to the second one and so on. The ^ needs to be used only in the first occurrence of the variable. So {$^a - $^b} takes 2 scalars and subtracts them. The only thing that matters is the alphabetical order, so {-$^b + $^a} does the same thing.
If you ever feel like using the pointy block syntax (like ->$a,$b {$a.map:{$_+$b}}), you're far better off writing bogus statement at the start of the block using the ^ for each argument you're not going to use in the main block (like {$^b;$^a.map:{$_+$b}}) (Note that better way to golf this is {$^a.map(*+$^b)}. I just wanted to show off the concept.)
Read through the operator docs carefully
The operators are very powerful and often they're the shortest way to get things done. Especially the meta-operators (operators that take operators as an argument) [], [\], X, <</>> and Z are worth of your attention. Don't forget that a meta-op can take another meta-op as an argument (like a XZ%% I managed to use here). You can use >> for a method call too, which can be a lot cheaper than a map (@list>>.method instead of @list.map(*.method), but beware, they're not same!). And, finally, before you use a binary << >>, bear in mind that Z will often do the same thing in much fewer characters.
If you heap a lot of meta-ops onto each other, you can specify precedence using square brackets []. That will save you when you pile up so many operators that it confuses the compiler. (That doesn't happen very often.)
Finally, if you need to coerce things to Bool, Int or Str, don't use the methods .Bool, .Int and .Str, but rather the operators ?, + and ~. Or even better, just put them into an arithmetic expression to force them into Int and so on. The shortest way to get the length of a list is +@list. If you want to calculate 2 to the power of the length of a list, just say 2**@list and it will do The Right Thing.
Use the free state variables $, @ and %
In each block, every occurence of $ (or @ or %) refers to a shiny new scalar (or array, or hash) state variable (a variable whose value persists across calls to the block). If you need a state variable that needs to be referenced only once in the source code, these three are your big friends. (Most often the $.) For instance, in the Reverse Math Cycles challenge, it could be used to choose the operators cyclically from an array, which was indexed by $++%6.
Use the sub forms of map, grep et al.
That means: do rather map {my block},list than list.map({my block}). Even if you manage to use list.map:{my block}, these two approaches come out at the same number of bytes. And often, you would need to parenthesize the list when calling a method, but not when calling a sub. So the sub approach comes out always better or at least the same as the method one.
The only exception here is when the object which is to be mapped, grepped and so on, is in $_. Then .map:{} obviously beats map {},$_.
Use junctions (& and |) instead of && and ||.
Obviously, they are 1 byte shorter. On the other hand, they must be collapsed by being forced into a boolean context. This can be always done with a ?. Here you should be aware of a meta-op !op which forces bool context, uses op and negates the result.
If you have a list and you want to turn it into a junction, don't use [&] and [|]. Instead use .any and .all. There is also .none which cannot be so easily mimicked by the junction ops.

I think && and || are still useful for short-circuiting?

@ASCII-only: Yes, certainly they are.

Reduce the space used for variables
There's a few parts to this.
Remove whitespace
Variables declared using my can usually be declared without the space between my and the variable name. my @a is equivalent to my@a.
Use sigil-less variables
You can declare variables using a backslash to remove the sigil before the variable name, like so:
my \a=1;

(unfortunately you can't remove the space :( )
This is useful as you can then refer to them as just the bare variable name later.
 a=5;
 a.say

Basically this saves bytes if you use the variable more than once elsewhere in your code. The downside is that the variable needs to be initialised.
Use $! and $/
These pre-declared variables are usually used for exceptions and regex matches respectively, but don't need to be defined using my.
$!=1;
$/=5;

Especially useful is using $/ as an array and using the shortcuts $ followed by a number to access that element of the $/ array;
$/=100..200;
say $5;  #105
say $99; #199

Use ... instead of first
Typically, if you want to find the first number that matches some condition &f, you can represent it like:
first &f,1..*

However, instead you can use the ... operator:
+(1...&f)

If you have to start from 0, you can have -1 afterwards instead of +.
If you want the index of the first element in a list @a that has condition &f, normally you do:
first &f,@a,:k

Instead:
(@a...&f)-1

(or vice-versa if you want 0 indexed). In the same way, you can get all the elements up to the first one that passes the condition.
Downsides to this is that the list has to pass the condition at some point, otherwise the ... operator will try to extrapolate off the end of the list, and most likely throw an error. You also can't use Whatever code in the left hand side, since it would be interpreted as part of the sequence.

source: Stack Exchange

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

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

sort: votes


text:
Search for files on your computer
Task
Write some code that will walk through the entire file-system tree and collect details from file-names, folder-names, text files etc to form a tag-group. This tag group, when searched in (user input) should point to the folders they are located in.
Rules

Any Language (standard libraries only).
Any kind of output (should be legible).
You may extend your code by reading more file-types and their metadata.
Regex is allowed

You'll win

+14 points for the shortest code (will be taken away when some else beats the record)
+6 for each added functionality (anything you could possibly claim).
-2 for each byte exceeding 1024 byte mark.

Example
Python (using os module - os.walk)

input
Enter search term below
>>> *camp*

output
Total results for *camp* = 2
-------------------------------
Camping.avi       - "C:\Users\Amelia\Videos\Summer Camping"
Campus party.avi  - "C:\Users\Public\Campus"

In my neighborhood, "tagging" means something very different.  Anybody know how to get sharpie off my monitor?  Thanks.

@boothby Sharpie? 'Round here we use spray-paint.

@Iszi The rattle can's in my backpack, in the other room, but my sharpie was in my pocket.

BASH, 14 + 6*18 = 122
Cheap, but a win.
locate

Example:
boothby@not ~ $ locate camp
/home/boothby/Desktop/kodak/Pictures/camp.jpg
/home/boothby/Desktop/kodak/Pictures/camp2.jpg
/home/boothby/Downloads/sage-5.12/local/share/doc/networkx-1.7.dev_20131124172629/examples/graph/napoleon_russian_campaign.py
/usr/src/linux-headers-3.8.0-19/arch/arm/plat-samsung/include/plat/camport.h
/usr/src/linux-headers-3.8.0-33/arch/arm/plat-samsung/include/plat/camport.h

Feature: this is super efficient since it caches the file information in a database.  The above runs on my computer in 0.187s.
... and 17 additional features:
   -b, --basename
          Match only the base name against the specified  patterns.   This
          is the opposite of --wholename.

   -c, --count
          Instead of writing file names on standard output, write the num‐
          ber of matching entries only.

   -d, --database DBPATH
          Replace the default database with DBPATH.  DBPATH is  a  :-sepa‐
          rated  list of database file names.  If more than one --database
          option is specified, the resulting path is  a  concatenation  of
          the separate paths.

          An empty database file name is replaced by the default database.
          A database file name - refers to the standard input.  Note  that
          a database can be read from the standard input only once.

   -e, --existing
          Print  only  entries  that  refer  to files existing at the time
          locate is run.

   -L, --follow
          When checking whether files exist (if the --existing  option  is
          specified),  follow trailing symbolic links.  This causes broken
          symbolic links to be omitted from the output.

          This is the default behavior.  The  opposite  can  be  specified
          using --nofollow.

   -h, --help
          Write  a summary of the available options to standard output and
          exit successfully.

   -i, --ignore-case
          Ignore case distinctions when matching patterns.

   -l, --limit, -n LIMIT
          Exit successfully after finding LIMIT entries.  If  the  --count
          option  is  specified,  the  resulting  count is also limited to
          LIMIT.

   -m, --mmap
          Ignored, for compatibility with BSD and GNU locate.

   -P, --nofollow, -H
          When checking whether files exist (if the --existing  option  is
          specified),  do not follow trailing symbolic links.  This causes
          broken symbolic links to be reported like other files.

          This is the opposite of --follow.

   -0, --null
          Separate the entries on output using  the  ASCII  NUL  character
          instead  of  writing each entry on a separate line.  This option
          is designed for interoperability with the --null option  of  GNU
          xargs(1).

   -S, --statistics
          Write  statistics  about  each  read database to standard output
          instead of searching for files and exit successfully.

   -q, --quiet
          Write no messages about errors  encountered  while  reading  and
          processing databases.

   -r, --regexp REGEXP
          Search  for  a  basic regexp REGEXP.  No PATTERNs are allowed if
          this option is used, but this option can be  specified  multiple
          times.

   --regex
          Interpret all PATTERNs as extended regexps.

   -V, --version
          Write  information  about  the  version and license of locate on
          standard output and exit successfully.

   -w, --wholename
          Match only the whole path name against the specified patterns.

          This is the default behavior.  The  opposite  can  be  specified
          using --basename.

And where is your code?

Right there at the top: locate

That right there is validation to a code-golfer: the solution was so small, an observer couldn't even find it.

BASH
find

A cheaper, shorter win. See @boothby answer for examples

Bash has always been better. :P

find is shorter, but locate is quicker - reminds me of my car navigation system :D

C# - 200
void G(string s){foreach (var y in Directory.GetFiles(@"C:\").Where(k => k.ToLower().Contains(s.ToLower())))foreach (var f in Directory.GetDirectories(@"C:\")){Console.WriteLine(y);try{G(f);}catch{}}}

Groovy (59)
a={b-> new File("c:\\").traverse(nameFilter: ~b){print it}}

Call it with
a('test')

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


text:
Align lists like coreutils' `ls`
Make program that takes the list from the files from STDIN, and aligns it nicely, just like ls command from coreutils. For example, assuming the following list (taken from The ASCII Collab, which takes place in the chatroom on this site).
alligator
ant
bear
bee
bird
camel
cat
cheetah
chicken
chimpanzee
cow
crocodile
deer
dog
dolphin
duck
eagle
elephant
fish
fly
fox
frog
giraffe
goat
goldfish
hamster
hippopotamus
horse
kangaroo
kitten
leopard
lion
lizard
llama
lobster
monkey
octopus
ostrich
otter
owl
oyster
panda
parrot
pelican
pig
pigeon
porcupine
puppy
rabbit
rat
reindeer
rhinoceros
rooster
scorpion
seal
shark
sheep
shrimp
snail
snake
sparrow
spider
squid
squirrel
swallow
swan
tiger
toad
tortoise
turtle
vulture
walrus
weasel
whale
wolf
zebra

Align the results, like the in the example below (the example shows columns set to 80). The terminal width is received as the first argument. If any argument is bigger than this argument, you can do anything. Try to use as many columns as possible with two space separators, as long nothing overflows.
alligator   crocodile  giraffe       llama    pig         shark     tiger
ant         deer       goat          lobster  pigeon      sheep     toad
bear        dog        goldfish      monkey   porcupine   shrimp    tortoise
bee         dolphin    hamster       octopus  puppy       snail     turtle
bird        duck       hippopotamus  ostrich  rabbit      snake     vulture
camel       eagle      horse         otter    rat         sparrow   walrus
cat         elephant   kangaroo      owl      reindeer    spider    weasel
cheetah     fish       kitten        oyster   rhinoceros  squid     whale
chicken     fly        leopard       panda    rooster     squirrel  wolf
chimpanzee  fox        lion          parrot   scorpion    swallow   zebra
cow         frog       lizard        pelican  seal        swan

Is the width of a column always 2 more than the biggest word in the column?

@Cruncher: Yes, this is how ls outputs it.

You're right about ls but "as many columns as possible" suggests just a single space between columns.

@DarrenStone: It does? Well then, I modified the question to explicitly mention the 2 space separators then.

Further to this, your example output is not what ls would produce since the column with "ostrich" is narrower than the column with "hippopotamus". On my system, ls generates equal width columns.  You might remove the phrase "just like ls command" to reduce confusion.

@DarrenStone: This is mistake on my part. This was output for 70, not 80. Also, this is output from coreutils' ls - it may be different in other implementations.

I checked FreeBSD's ls for fun. It appears to make equal width columns, which probably simpler to make.

You may miss my point. You ask for output "just like ls command", which means equal width columns. You also ask for output with "as many columns as possible", which means columns of varying widths as your example shows.  I think variable width columns are much more interesting to code but it may be too late since people are submitting answers.

@xfix Your example output is 76 characters wide - which is clearly more than 70.

@Howard: Oh, right. This was my mistake. Anyway, I created some files, and made a screenshot - http://i.stack.imgur.com/g2dzH.png.

Bash, 48 46 bytes
cd `mktemp -d`
xargs -d\\n tee
stty cols $1
ls

Guaranteed to work like ls.

This fails if one of the items contains whitespace. It should be >"$R".

I could swear I read "words" somewhere in the question. Oh, well...

Newest edit uses ls in the answer...

@Shingetsu: All revisions use ls.

Shouldn't using ls to emulate ls be banned?
I mean I get the idea, but it just seems wrong.

@Shingetsu: I agree that using ls to make something "look like ls" is a little bold, but since ls is used in an entirely different manner, I though it would be OK. Now, if the question asked for a program to list a directory's contents and format the output like ls, that would be different...

@Shingetsu: I actually expected this to happen (in fact, my test solution which was used to make an example) was using ls directly.

@xfix what's amusing is they could legitly read the source for GNU ls and just obfuscate it...
Of course they'd need to add the GPL clause, but hey~

GolfScript, 79 characters
n%:I{)I/{{,}$-1=,}:L%{2++}*"#{ARGV[0]}"~)<}I,,?)/{.L{:x' '*+x<}+%}%zip{'  '*n}/

Assumes a two spaces between the columns (although it can be changed easily to one which saves 2 characters).

How is the input entered if one wants to test it? :)

@JoachimIsaksson As specified in the question - console width as first argument and list of names on STDIN.

Tested with 30 columns and getting a rather peculiar result :)

@JoachimIsaksson Thank you - that was simply a bug in the implementation. Fixed now.

Python 3 (394)
Feels longish, but works and isn't horrible to read;
import sys,math
f=sys.stdin.read().splitlines()
l,w=len(f),int(sys.argv[1])
for y in range(w,0,-1):
 n=math.ceil(l/y)
 r=[f[i:l:n]for i in range(0,n)]
 c=[max(len(s[i]) if i<len(s) else 0 for s in r) for i in range(y)]
 if sum(c)+len(c)*2-2<=w:break
for i in range(len(r)):
 s=len(r[i])
 for j in range(s):
  t=r[i][j]
  sys.stdout.write(t+(' '*(c[j]-len(t)+2) if j<s-1 else '\n'))

Basically it tries with fewer and fewer columns until they all fit. It will always output at least one column even if the file names won't fit the width.

BASH, 13 15
column -s"\n"-c

You can append the column width argument like this:
column -s"\n"-c80

Reads text from STDIN and aligns it in columns.

This gives me tab separated columns. I'm not quite sure why it happens (man page for column says that the default is two spaces), but it does (at least for me).

Right, i just noticed that as well. Wasn't meant as a serious submission anyway.

C++11, 409 bytes
#include<vector>
#include<iostream>
using namespace std;main(int i,char*a[]){int w=atoi(a[1]),n,c,x,r;int v[w];vector<string>l;string s;while(getline(cin,s))l.push_back(s);n=l.size();for(c=n;c>1;--c){r=n/c+(n%c!=0);for(i=0;i<n;++i)v[i/r]=max((int)l[i].size(),i%r?v[i/r]:0);for(i=x=0;i<c;++i)x+=v[i]+=i<c-1?2:0;if(x<=w)break;}for(i=0;i<n;++i)printf(((i+1)%c&&i<n-1)?"%1$-*2$s":"%s\n",l[i*r%n].c_str(),v[i%c]);}

Below is the slightly non-golfed version. If I may point you at something potentially interesting, then please take a look at the silly format strings of the last printf.
#include<vector>
#include<iostream>
using namespace std;
main(int i,char*a[]){
int w=atoi(a[1]),n,c,x,r;
int v[w];
vector<string>l;string s;while(getline(cin,s))l.push_back(s);n=l.size();
for(c=n;c>1;--c){
 r=n/c+(n%c!=0);
 for(i=0;i<n;++i)v[i/r]=max((int)l[i].size(),i%r?v[i/r]:0);
 for(i=x=0;i<c;++i)x+=v[i]+=i<c-1?2:0;
 if(x<=w)break;
}
for(i=0;i<n;++i)
 printf(((i+1)%c&&i<n-1)?"%1$-*2$s":"%s\n",l[i*r%n].c_str(),v[i%c]);
}

You don't have to declare int main parameters, or name them like that. argv is just a convention.

@xfix, thank you for the tip, I renamed argc and argv. However, plain argc without the "int" gives an error on my g++, which is why I had left the "int" there.

Come to think of it, if I am stuck with argc, I might it use it for something. Replaced 'i' with it. Now at 409 bytes; not so far from the python solution. :)


text:
How many unique ways are there to achieve a score in Football?
Challenge: given a number, calculate how many unique, order-independent ways there are to achieve a score of that number in American Football.
Let's see how few characters can be used in each of your favorite languages! The usual rules apply.  Input and output in a way that is natural to your language.
Recall that the ways to score in Football are safety (2 points), field goal (3 points), touchdown (6 points), touchdown + extra point (7 points), and touchdown + 2-point conversion (8 points).
For example, given 9 as input, the program should return 4, since you could score:

1 touchdown + extra point and 1 safety
1 touchdown and 1 field goal
3 field goals
3 safeties and 1 field goal

Note that order does not matter.

I'm not familiar with American Football. Is the question just about ways of partitioning the number using 2,3,6,7 and 8?

@swish yup!  Just an actual version of the problem I found myself thinking about.

This is essentially identical to Need change of 78 cents except for the values of some constants. (Although on reflection, since this question is better posed, it might be preferable to close the other one as a duplicate of this one).

Awhh. I watch the Canadian Football League. I want my 1 point for punting into the endzone!

Mathematica - 42
Length@IntegerPartitions[#,∞,{2,3,6,7,8}]&

Prolog - 140
Never wrote anything in Prolog before, just knew that this problem should be quite nice for it.
p(0,_,[]).
p(N,[H|T],O):- N>=H,p(N,T,O).
p(N,[H|S],[H|T]):- N>=H,M is N-H,p(M,[H|S],T).
f(N,C):- aggregate(count,X^p(N,[2,3,6,7,8],X),C).

?- f(9,C).
C = 4.

I only see 42 chars. Does this have something to do with the unicode character?

@Cruncher Oh, I forgot to put f= at the start, so it would be a function definition.

Python - 146
t=int(input())
from itertools import*
print len([a for a in chain(*(combinations_with_replacement([2,3,6,7,8],n) for n in range(t)))if sum(a)==t])

Instead of from itertools import ..., you can use from itertools import*. You only use combinations_with_replacement once, so having to use it wouldn't cost you after this change.

True, I'll change it, thanks!


text:
Find next multiple of 32 that follows given number without using *, / and loops
Imagine simple math problem. You have a number, say it's 1000. And you want to find the next multiple of 32 that follows 1000. You automatically make some simple calculations and get the result. Typical algorithm looks like this:
int number = 1000, result;
result = (1 + (number/32)) * 32; // integer division

It's kind of easy and obvious, right? And now the challenge. Make this calculation without using *, / and loops.
Rules:

Don't use *, / and loops.
Assume that input number is already stored in variable n, store result in the variable r (already declared).
The shortest code wins.

Sample input: (already stored in n)
1000

Sample output: (value of r)
1024

Sample input:
31

Sample output:
32

Sample input:
32

Sample output:
64

It is assumed that n is a positive number.

10 characters in Javascript: r=(n|31)+1. I'd post this as an answer, but the question is really too trivial.

Can you confirm whether numbers that area already an exact multiple of 32 should be rounded up? E.g. 32 -> 64 ?

@PaulR That's already covered in the third sample set.

@squeamishossifrage I'm not familiar with the pipe operator that you (and several others) appear to be using - what exactly does that do?

@Iszi - thanks - I missed that. It's a pity because the more common use case is rounding up to the next multiple of N.

@Iszi: | is bitwise OR in many languages, so n|31 just sets the LS 5 bits of an integer.

@PaulR Aww, drat. The same operator in PowerShell is -bor and you have to force the order of operations with parenthesis. So, it ends up being 1 character longer than the solution I already have.

Isn't the next multiple of 32 after 1000. not 1000 + (1/Infinity). Since the OP doesn't restrict the output to Integer numbers

JavaScript (26 13 chars)
alert((+prompt()>>5)+1<<5)
Re-read the problem statement. Here's my amended answer:
r=(n>>5)+1<<5
And this seems to be the best javascript answer at 10 chars:
r=(n|31)+1

Snap! Geez @Greg, you had me on that one!

Both work in Ruby.

GolfScript (10 chars)
32n+31~&:r

Problems this trivial aren't interesting.

Nevertheless, also trivial problems are golfable ;-) 31n|):r for 7 chars.

C (11 chars)
r=(n|31)+1;

Python (10 chars)
r=(n|31)+1

Work for negative numbers also

This works for Ruby too

Mathematica - 15 13
⌈##⌉&[n+1,32]

It's quite simple if Ceiling (⌈...⌉) isn't forbidden

EXCEL  (14 characters):
=n-MOD(n;32)+32

n is declared name for a an input cell. put the formula in a cell declared as 'r'.
No use of / and * ...

Wow. I think it's a sad attestation to the difficulty of a challenge, when an Excel solution is actually quite competitive with the lengths of real programming/scripting solutions.

Python (11 chars)
r=n+32-n%32

Using modulo
Alternative (10 chars), using bitwise OR like everbody else:
r=(n|31)+1

R, 12
r=n+32-n%%32

This uses modulo %%, subtraction -, and addition +.

Julia, 8
r=n|31+1

(This is based on the C solution.)
Some parentheses can be saved in Julia due to the order in which the functions are called:
:(r=n|31+1) # : returns the ATK
:(r = +(|(n,31),1))

R (10 16)

    r=-n%%32+n

r=-(n=n+1)%%32+n

R (recursive, long)
r<-(function (n) if(n%%32) Recall(n+1) else n)(n+1)

Python (9 14)

    r=-n%32+n

n+=1
r=-n%32+n

this returns 32 for n=32

oops ... corrected (but longer)

PowerShell: 14
$r=$n-$n%32+32

C (16 characters):
r=((n>>5)+1)<<5;

Kona (21)
 r:{_(1+(x%32))%(%32)}

No *, /, nor a loop in the above.

 J - 11 characters
r=:2^>.2^.n

C - 19 characters
not the shortest, but a different method
j=i%32?i+32-i%32:i;

J (10)
This returns n if n is a multiple of 32. So it doesn't satisfy everything I think you want.
r=:n-_32|n

If we need to be stringent on that rule, the following works.
(14)
r=:>:n-_32|>:n

Perl 6 (9 bytes)
r=n+|31+1

r and n can be declared as sigilless variables (my \variable). In Perl 6, bitwise operators (like +|)'s precedence is better, so no parens are needed.

R, 40
Just for kicks, a solution that doesn't use the modulo operator either:
r=tail(which(!cbind(1:n,31:0)[,2]),1)+32

cbind(1:n,31:0) creates an array with one column going from 1 to n and another from 31 to 0. That column is recycled to fit the size of the first one. which(!cbind(1:n,31:0)[,2]) returns the indices of the elements for which the second column is 0 (0 being FALSE, !0 is TRUE), i.e. the multiples of 32. Finally we take the last one using tail and add 32.
Solution at 34 characters with rep:
r=tail(which(!rep(31:0,l=n)),1)+32

Doesn't rep() violate the "no loops" rule?

This is vector recycling not looping. If you have a look at the C definition of do_rep_len (the function called internally when using rep with argument l) you will see that there is no loop (well I don't see one anyway but I m no C expert).

Ok to make it more explicit that this uses vector recycling i ll make a change.

Perl5 14
$r=($n+32)&~31

In Perl5 variables needs sigilia. $n gets added 32 and we strip the last 5 bits by anding by the inverse of 31.

Game Maker Language, 8
r=n|31+1

Yes, | is evaluated before + (see here)

GolfScript, 7 characters
31n|):r

Takes input from variable n and puts the result into r. Note that for testing it is advisable to use another variable name since n is also part of the p and puts built-ins.

x86 Machine Code - 6 bytes
Assuming that the register 'ax' is 'n', and 'bx' is 'r' then
83C81F 40 89C3

Assembled from:
or ax, 0x1F
inc ax
mov bx, ax

TI-BASIC, 12
32(1+N/32)→R

Uses / and implied multiplication, and doesn't even work due to floating point rather than integer division.

C 45
int a=32,b,c;b=31;c=b%a;c=a-c;b=b+c;return c;

Please format your answer and add language and character count as title.

hi howards i am new to it can u plz help in updating and i am seeing a -1 symbol againts my post what is that

Please re-read the question and look at some of the other answers to see what your answer should look like both in terms of functionality and formatting.


text:
Get the remainder of a mathematical division without using any arithemetic operation
Write a code that will display the remainder of a division. Code with shortest byte wins.
Rules:

No arithmetic operation whatsoever should be in your code
No use of functions or methods
If you are using a function or method, it has to be written by you also

Samples:
Sample1: 9/3
Result1: 0

Sample2: 7/2
Result2: 1

I suppose modulo is counted as an arithmetic operation?

yep. it is. @KyleKanos

Does it have to be a function, or just an operation

If you are using a function or method, it has to be written by you also So we have to take input of the form "x/y" and also write our own string to integer converter?

scrbinrd3 What's the difference between a function and an operation? (Assuming the operation has a domain and co-domain.)

Why is everyone downvoting this?

@MistressDavid Becuase it is a very ill-defined problem. For starters, rules 2 and 3 are contradictory.

@LegoStormtroopr I presume Rule 2 is intended to eliminate intrinsic mod functions as some languages use that instead of % or !

This question is very badly defined.  The inability to use any functions or methods disqualifies most (all?) of the answers I see below.  Functions include range, len, map, and split. This may not be @CrowdStar's intent, but that's how it reads.

J (23)
f=:4 :'##~,-.(-y)>\x#1'

e.g.
   f=:4 :'##~,-.(-y)>\x#1'
   9 f 3
0
   7 f 2
1

How it works:

x#1: make a list of 1s as long as the left argument (x)
(-y)>\: divide the list into a y-row (right arg) matrix, padding with zeroes.
-.: negate the list (so the padding is 1)
,: flatten the matrix
#~: replicate each number by itself (so all the zeroes disappear and all the ones remain)
#: count how long the list is now.

CMD - 48 chars
start "" "http://google.com/search?q=%1 %%25 %2"

This program leverages the power of the mighty Google to calculate the result. Very rule bendy...

I'd say mod is an arithmetic operation.

@marinus I'd also say that performing a network request to a site isn't. Very rule bendy, but not breaking.

Also the % characters used in this are not modulo's but used as character substitutions...
%1 and %2 substitute the first and second number; while %%25 substitutes the % sign itself... so technically, the use of %%25 is valid in the actual code itself...

Perl, 46 chars
The challenge is kind of vague, but if string manipulation and regexps are allowed, this should work:
($_,$x)=map$"x$_,split"/",<>;s/$x//g;say y///c

This code reads a line of the form 7/3 from stdin, and outputs the remainder of the division (in this case 1).  Needs Perl 5.10+ and the -M5.010 (or -E) switch for the say feature.

PHP, 38 chars
function m($a,$b){return fmod($a,$b);}

modulo is an arithmetic operation...

I thought it just meant  that there could be no arithmetic operators

Literal reading has it say, "no arithmetic operations". This basically means we have to do some bit shifting.

And now functions have been eliminated.

Hard to write when the rules are constantly changing

Python 2.7 - 67 chars
n,d=raw_input().split('/')
d=-int(d)
print range(int(n))[d::d][-1]

Old answer 87:
Takes a string input and aside from converting it to numbers does no numeric manipulation. The asterisk looks like a multiplication sign, but its actually repeated string concatenation ;)
n,d=raw_input().split('/')
x="."*int(n)
d=int(d)
while len(x)>d:
 x=x[d:]
print len(x)


text:
n-queens problem, displaying more than one solution available
as some of you may know, n-queens problem is a set of algorithm puzzle that given a 'n x n' where n is the board size of a (let's say) chessboard, and the main goal is for the n queens (where n is the number of the queens) not be able to 'attack' one another in the board.
now I have a set of console code where user can input the board size (with an exception of less than 4x4), and the program will display one solution for the board size inputted. here's the code sample in C++:
#include <windows.h>
#include <iostream>
#include <string>

using namespace std;

class point
{
public:
int x, y;
point() { x = y = 0; }
void set( int a, int b ) { x = a; y = b; }
};

class nQueens
{
public:
void solve( int c )
{
    _count = c;
    int len = (c + 1) * (c + 1);
    _queens = new bool[len]; memset( _queens, 0, len );
    _cl = new bool[c]; memset( _cl, 0, c );
    _ln = new bool[c]; memset( _ln, 0, c );
    point pt; pt.set( rand() % c, rand() % c );
    putQueens( pt, c );
    displayBoard();
    delete [] _queens; delete [] _ln; delete [] _cl;
}

private:
void displayBoard()
{
    system( "cls" );
    const string t = "+---+", q = "| Q |", s = "|   |";
    COORD c = { 0, 0 };
    HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE );
    for (int y = 0, cy = 0; y < _count; ++y)
    {
        int yy = y * _count;
        for ( int x = 0; x < _count; x++ )
        {
            SetConsoleCursorPosition( h, c ); cout << t;
            c.Y++; SetConsoleCursorPosition( h, c );
            if (_queens[x + yy]) cout << q; else cout << s;
            c.Y++; SetConsoleCursorPosition( h, c );
            cout << t; c.Y = cy; c.X += 4;
        }
        cy += 2; c.X = 0; c.Y = cy;
    }
}

bool checkD( int x, int y, int a, int b )
{
    if ( x < 0 || y < 0 || x >= _count || y >= _count ) return true;
    if ( _queens[x + y * _count] ) return false;
    if ( checkD( x + a, y + b, a, b ) ) return true;
    return false;
}

bool check( int x, int y )
{
    if ( _ln[y] || _cl[x] )        return false;
    if ( !checkD( x, y, -1, -1 ) ) return false;
    if ( !checkD( x, y,  1, -1 ) ) return false;
    if ( !checkD( x, y, -1,  1 ) ) return false;
    if ( !checkD( x, y,  1,  1 ) ) return false;
    return true;
}

bool putQueens( point pt, int cnt )
{
    int it = _count;
    while (it)
    {
        if ( !cnt ) return true;
        if ( check( pt.x, pt.y ) )
        {
            _queens[pt.x + pt.y * _count] = _cl[pt.x] = _ln[pt.y] = true;
            point tmp = pt;
            if ( ++tmp.x >= _count ) tmp.x = 0;
            if ( ++tmp.y >= _count ) tmp.y = 0;
            if ( putQueens( tmp, cnt - 1 ) ) return true;
            _queens[pt.x + pt.y * _count] = _cl[pt.x] = _ln[pt.y] = false;
        }
        if ( ++pt.x >= _count ) pt.x = 0;
        it--;
    }
    return false;
}

int          _count;
bool*        _queens, *_ln, *_cl;
};

int main( int argc, char* argv[] )
{
nQueens n; int nq;
while( true )
{
    system( "cls" );
    cout << "Enter board size bigger than 3 (0 - 3 to QUIT): "; cin >> nq;
    if ( nq < 4 ) return 0;
    n.solve( nq ); cout << endl << endl;
    system( "pause" );
}
return  0;
}

now, as the code only display one solution only, where 4x4 should have more than one solution available, your challenge is to make the code to be able to display more than one solution should it's possible, and displaying the 'graphic' solution (console is recommended). C++ is recommended, but other programming language is more than welcome. Good luck!

Removed code-challenge tag since no objective winning criterion was given.

i added the objective, is it good enough? sorry, first time on this site

It is perfectly fine for popularity-contest to not have a objective criterion. Popularity-contest and code-challenge are mutually exclusive - either you judge by most votes or by some objective criterion (i.e. based solely on the solution, no matter how many people voted for the answer). Of course in any case a solution has to fulfill all requirements specified in the puzzle. So it's up to you what kind of challenge you want to have.

Python 2.7
Nice object-oriented solution:
class Queen(object):
    def __init__(self, row, col):
        self.row = row
        self.col = col

    @property
    def u(self):
        'Return the SW-NE diagonal by starting row'
        return self.col + self.row

    @property
    def v(self):
        'Return the NW-SE diagonal by starting column'
        return self.col - self.row

class Solver(object):
    '''
    Solver which iterates over solutions.  Each iterator produces a
    string representation of a valid solution.
    '''
    def __init__(self, n):
        self.n = n
        self.queens = [Queen(r, 0) for r in range(n)]

    def __iter__(self):
        return self

    def next(self):
        self.step()
        while not self.is_valid():
            self.step()
        # Draw the solution
        line = ('+---' * self.n) + '+\n'
        text = line
        for row in range(self.n):
            text += '| %s |\n' % ' | '.join(' Q'[c == self.queens[row].col] for c in range(self.n))
            text += line
        return text

    def step(self, _row=None):
        'Increment the solution one step'
        if _row == -1:
            raise StopIteration
        if _row is None:
            _row = self.n - 1
        self.queens[_row].col += 1
        if self.queens[_row].col == self.n:
            self.queens[_row].col = 0
            self.step(_row - 1)

    def is_valid(self):
        'Return True if the queens are all safe'
        qc = len(self.queens)
        return all(len(set(getattr(q, p) for q in self.queens)) == qc for p in ['row', 'col', 'u', 'v'])

if __name__ == '__main__':
    n = int(raw_input('Enter n:'))
    for s in Solver(n):
        print(s)

PHP
Using a simple recursive approach.
<?
function q($n,$t=[],$r=1,$S=str_repeat){
  foreach($r>$n?$t:[]as$v)echo$f=$S('+---',$n)."+\n",$S('|   ',$n)."|\n"|$S(' ',$v*4-2).q;
  for(;$s<$n?$r-$s^abs($c=$p-$t[$s++])&&$c:q($n,$t+[$r=>$p],$r+1)?:$n>=$p+=$s=1;);echo$f;
}
q(4);

Sample output for $n=4:
+---+---+---+---+
|   | q |   |   |
+---+---+---+---+
|   |   |   | q |
+---+---+---+---+
| q |   |   |   |
+---+---+---+---+
|   |   | q |   |
+---+---+---+---+
+---+---+---+---+
|   |   | q |   |
+---+---+---+---+
| q |   |   |   |
+---+---+---+---+
|   |   |   | q |
+---+---+---+---+
|   | q |   |   |
+---+---+---+---+

first answer, and a nice one :)

Mathematica
The positions of n queens on an n x n chessboard can be represented as a permutation of n.
For example,
The permutation, {3, 1, 4, 2},
is shorthand for the idea that there are 4 queens at
{{row3, col1}, {row1, col2}, {row4, col3}, {row2, col4}.
array[{3, 1, 4, 2}] returns the complete array,  with 1' s now representing queens.

{{0, 1, 0, 0}, {0, 0, 0, 1}, {1, 0, 0, 0}, {0, 0, 1, 0}}

This could be displayed as a grid through Grid@array[{3, 1, 4, 2}].

or as a board, using board[{3, 1, 4, 2}]. The black squares are those occupied by a queen.

solutionQ[{3, 1, 4, 2}] displays the board and whether or not that board is a solution.

array[pos_]:=ReplacePart[ConstantArray[0,{l=Length[pos],l}],Partition[Riffle[pos,Range[Length[pos]]],2]/.{{a_,b_}:> ({a,b}-> 1)}]
board[pos_]:=ArrayPlot[array[pos],ImageSize->120,Mesh-> True]

solutionQ[pos_]:=
  Module[{b,safeQ, len=Length[pos],files},
  b=array[pos];
  safeQ[b1_]:=(Max[Tr/@Table[Diagonal[b1,k],{k,-(len-2),len-2}]])<2;
  {board[pos],safeQ[b]\[And]safeQ[Reverse/@b]}]

solutions[gridSize_]:=Cases[solutionQ/@Permutations[Range[gridSize]],{_,True}][[All,1]]

Results
Table[Print[n , " queens solutions: ", Row@solutions[n]], {n, 4, 6}]

Table[Print[ "Number of solutions in a ", n, " by ", n, " table: ", solutions[n] // Length],
{n, 7, 8}]

Number of solutions in an 7 by 7 table: 40
Number of solutions in an 8 by 8 table: 92

nice explanation and graphics, great job!

Haskell (ideone)
import System.Environment (getArgs)

data Board = Board {
  field :: [Int],
  size :: Int
}

-- | Checks whether the board has a conflict
conflict :: Board -> Bool
conflict b = any (==x) xs || step (-1) x xs || step 1 x xs
  where (x:xs) = field b
        step _ _ [] = False
        step s p (x:xs)
          | (s+p) == x = True
          | otherwise  = step (s+p) p xs

-- | Returns all boards one can get by placing a queen in the next column
place :: Board -> [Board]
place b = place' b 1
  where place' b s
          | s > size b        = []
          | conflict newboard = rest
          | otherwise         = newboard:rest
          where newboard = Board newfield (size b)
                newfield = s:(field b)
                rest     = place' b (s+1)

-- | Returns all boards one can get for the n-th queen problem
placeAll :: Int -> [Board]
placeAll n = foldl (>>=) [Board [] n] (replicate n place)

-- | Creates a String from a board
prettyPrint :: Board -> String
prettyPrint b = unlines.map prettyLine.field$b
  where prettyLine n = replicate (n - 1) '.' ++ "@" ++ replicate ((size b) - n) '.'

-- | Shows the first two solutions obtained by placeAll
main = do
  [s] <- getArgs
  mapM_ putStrLn . map prettyPrint . take 2 . placeAll . read $ s

Sample output
$ runghc nqueens.hs 12
...........@
........@...
..........@.
.@..........
.........@..
.......@....
.....@......
...@........
......@.....
....@.......
..@.........
@...........

..........@.
........@...
...........@
.@..........
.........@..
.......@....
.....@......
...@........
......@.....
....@.......
..@.........
@...........

$ time runghc nqueens.hs 48
..............................................@.
...........................................@....
...............................................@
.............................................@..
.........................................@......
............................................@...
..........................................@.....
........................................@.......
......................................@.........
....................................@...........
.......................................@........
.....................................@..........
...................................@............
.................................@..............
...............................@................
..................................@.............
................................@...............
..............................@.................
............................@...................
..........................@.....................
.............................@..................
...........................@....................
.........................@......................
.......................@........................
.....................@..........................
........................@.......................
......................@.........................
....................@...........................
..................@.............................
................@...............................
...................@............................
.................@..............................
...............@................................
.............@..................................
...........@....................................
..............@.................................
............@...................................
..........@.....................................
........@.......................................
.@..............................................
.........@......................................
.......@........................................
.....@..........................................
...@............................................
......@.........................................
....@...........................................
..@.............................................
@...............................................

...............................................@
.............................................@..
...........................................@....
..............................................@.
.........................................@......
............................................@...
..........................................@.....
........................................@.......
......................................@.........
....................................@...........
.......................................@........
.....................................@..........
...................................@............
.................................@..............
...............................@................
..................................@.............
................................@...............
..............................@.................
............................@...................
..........................@.....................
.............................@..................
...........................@....................
.........................@......................
.......................@........................
.....................@..........................
........................@.......................
......................@.........................
....................@...........................
..................@.............................
................@...............................
...................@............................
.................@..............................
...............@................................
.............@..................................
...........@....................................
..............@.................................
............@...................................
..........@.....................................
........@.......................................
.@..............................................
.........@......................................
.......@........................................
.....@..........................................
...@............................................
......@.........................................
....@...........................................
..@.............................................
@...............................................

runghc nqueens.hs 48  0,16s user 0,02s system 93% cpu 0,189 total

Ocaml :
let print_list list =
  List.iter print_int list;
    print_newline();;

let infect x y list =
  let rec infect_rec x y n  = function
      [] -> false
    | a :: r -> if (y = a) then true
      else if ( y = a + x - n ) then true
      else if ( y = a - x + n ) then true
      else infect_rec x y (n-1) r in
    infect_rec x y (x-1) list;;

let rec add_queen x n queen =
  if x > n then print_list queen
  else
    for i = 1 to n do
      if (infect x i queen) = false
      then add_queen (x+1) n (i :: queen)
    done
;;

add_queen 1 8 [];;

My short but quite readable Python solution:
def nqueens(n):
    def state(n):
        return set((i,j) for i in range(n) for j in range(n))
    def move(i,j,n):
        line = lambda ci,cj: set((i+d*ci,j+d*cj) for d in range(-n,n+1))
        return line(1,0) | line(0,1) | line(1,1) | line(1,-1)
    def solve(n1, s=state(n), r=()):
        if n1==0: yield tuple(sorted(r))
        for x in s: yield from solve(n1-1, s-move(x[0],x[1],n), r+(x,))
    return solve(n)

The state of computation is represented as possible moves, and a move as the possibilities is going to remove from current state, so applying a move to a state is just set difference.
Can also generate all the solutions.
Printing the (first) solution:
def sol2str(s,n):
    return '\n'.join(' '.join('X' if (row,col) in s else '.' for col in range(n)) for row in range(n))

n = 8
print(sol2str(next(nqueens(n)),n))

. . . . . X . .
X . . . . . . .
. . . . X . . .
. X . . . . . .
. . . . . . . X
. . X . . . . .
. . . . . . X .
. . . X . . . .

This solution is a slight trolling, but since it's not specified what solutions are considered to be the same, I guess it should qualify :). Let the original program be compiled as queens. Then the extension is:
#!/bin/bash
queens "$@" >tmpfile
cat tmpfile
tac tmpfile

Explanation: A mirrored solution is obviously also a solution. And it must be different from the original one: Pick a queen not positioned in the middle row from the original solution and Let (x,y) be its position (so y != n-y-1). Then the original and mirrored solutions differ at (x,n-y-1). There is a queen at (x,n-y-1) in the mirrored solution, but the position must be empty in the original one.

Groovy
s = (0..7).permutations().findAll{
   def x=0,y=0
   Set a=it.collect{it-x++}
   Set b=it.collect{it+y++}
   a.size()==it.size()&&b.size()==it.size()
}

Delivers a list of all queen solutions like this:
[ [4, 7, 3, 0, 6, 1, 5, 2],
  [6, 2, 7, 1, 4, 0, 5, 3],
  ... ]

For graphical representation add:
s.each { def size = it.size()
         it.each { it.times { print "|_" }
                   print "|Q"
                   (size-it-1).times { print "|_" }
                   println "|"
                 }
         println ""
         }

which looks like this (2 examples of the 92 solutions):
|Q|_|_|_|_|_|_|_|
|_|_|_|_|_|_|Q|_|
|_|_|_|Q|_|_|_|_|
|_|_|_|_|_|Q|_|_|
|_|_|_|_|_|_|_|Q|
|_|Q|_|_|_|_|_|_|
|_|_|_|_|Q|_|_|_|
|_|_|Q|_|_|_|_|_|

|_|_|_|_|Q|_|_|_|
|_|Q|_|_|_|_|_|_|
|_|_|_|_|_|Q|_|_|
|Q|_|_|_|_|_|_|_|
|_|_|_|_|_|_|Q|_|
|_|_|_|Q|_|_|_|_|
|_|_|_|_|_|_|_|Q|
|_|_|Q|_|_|_|_|_|

Explanation:
My first Groovy experiment. I am loving the closures and the conciseness of this language!
Lets take it apart:
   (0..7).permutations()

// returns a list of all permutations of the sequence [0,1,2,3,4,5,6,7]
   .findAll{

Find and return all elements for which the following closure returns true
Here is how we check if all queens are safe:
   def x=0,y=0
   Set a=it.collect

Transform all integers in the permutations using the closure:
        {  it-x++ }

We need to check if 2 queens are on the same diagonal.
Mathematically a diagonally rising line is: y = x + const
   Set b=it.collect{it+y++}

A falling line is y = -x + const
Our closures return const = x+y (or x-y respectively)
We add them to a Set to find duplicates. A Duplicate means 2 queens have the same function (are on the same diagonal).
   a.size()==it.size()&&b.size()==it.size() }

The last statement in the closure returns true if there are no duplicates, so all queens are safe!


text:
Regex Golf: Regions of Italy vs. States of USA
We've already got a meta-regex-golf problem as inspired by the xkcd comic

But, this regex golf looks fun, too!  I want to distinguish between the states of the US and the regions of Italy.  Why?  I'm a citizen of both countries, and I always have trouble with this*.
The regions of Italy are
Abruzzo, Valle d'Aosta, Puglia, Basilicata, Calabria, Campania, Emilia-Romagna, Friuli-Venezia Giulia, Lazio, Liguria, Lombardia, Marche, Molise, Piemonte, Sardegna, Sicilia, Trentino-Alto Adige/Südtirol, Toscana, Umbria, Veneto

and the states of the USA are
Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware, Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana, Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana, Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina, North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina, South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia, Wisconsin, Wyoming

Your job is to write a program which distinguishes these lists with a regular expression.  This is a new game, so here's the
Rules

Distinguishing between lists must be done with a single matching regular expression.
Your score is the length of that regular expression, smaller is better.

To be clear: all work must be done by the regular expression -- no filtering, no replacements, no nothing... even if those are also done with regular expressions.  That is, the input should be passed directly into a regular expression, and only the binary answer (match / no match) can be used by later parts of the code.  The input should never be inspected or changed by anything but the matching expression.  Exception: eating a newline with something akin to Ruby's chomp is fine.
Your program should take a single entry (optionally followed by \n or EOF if it makes things easier) from either list from stdin, and print to stdout the name of that list.  In this case, our lists are named Italy and USA.
To test your code, simply run both lists through it.  Behavior may be undefined for strings which do not occur in the list.
Scoring Issues
This might have to be done on a language-by-language basis.  In Perl,
m/foobarbaz/

is a matching regular expression.  However, in Python,
import re
re.compile('foobarbaz')

does the same thing.  We wouldn't count the quotes for Python, so I say we don't count the m/ and final / in Perl.  In both languages, the above should receive a score of 9.
To clarify a point raised by Abhijit, the actual length of the matching expression is the score, even if you generate it dynamically.  For example, if you found a magical expression m,
n="foo(bar|baz)"
m=n+n

then you should not report a score of 12: m has length 24.  And just to be extra clear, the generated regular expression can't depend on the input.  That would be reading the input before passing it into the regular expression.
Example Session
input> Calabria
Italy
input> New Hampshire
USA
input> Washington
USA
input> Puglia
Italy

* Actually, that's a lie.  I have never had any trouble with this at all.

Can you please explain, what you mean by "no filtering, no replacements, no nothing... even if those are also done with regular expressions.". Just to clarify, does it mean filtering, replacements of the list of states/regions or the focus is wider?

@Abhijit edited.  Is that clearer?

Hopefully, let me post an answer and see if you feel it violates the rule in any way :-)

How are flags counted? Do we  get case-insensitive for free?

@JanDvorak Good thinking! No: flags cost extra, just the m// is free.

@Boothby, aren't you forgetting District of Columbia?

@Eliseod'Annunzio: DC is not a state

"Behavior may be undefined for strings which do not occur in the list." this rule is broken: it allows one to return USA in case of such a string, hence you would just have to check Italian regions, and return USA otherwise.

@Lohoris "This rule is broken" is an opinion.  Codegolf tends to encourage cutting corners like this.

@boothby well, no, it's simple logic: it is basically asking only a regexp to match italian regions, but needlessly worded in a much complicated way. The whole point about american states is totally not relevant to the actual question asked, thanks to this bug. This also makes the question much less interesting.

@Lohoris A cursory perusal of the answers below indicates that your "simple logic" is still just an opinion, and it may be better to match states of the US instead.

@Eliseod'Annunzio: If we include DC, we should also include Guam, CNMI, American Samoa, the US Virgin Islands, and nine uninhabited atolls.

Fair enough... just checking...

@Eliseod'Annunzio The internet is made for dogpiling.

@boothby Please tell me there is a definition for "dogpiling" in this context...? Very 404 here...

@Eliseod'Annunzio https://www.wordnik.com/words/dogpile

Perl - 51 36 bytes (for regex)
print<>=~/.A|ise|net|te|z.o|[cp]a|[lr]ia|r[cd]/?"Italy
":"USA
"

Nothing special, but may as well post it, because it's different to other 51 bytes solution.
Or alternatively, shorten my already short solution by 15 bytes. This wins for now, I think.

Perl, 40 chars
Approaching this from the other direction, i.e. matching the U.S. states:
[DNIOWy]|ss|M.n|^A.*a|or|[aguh]i|[sth]\b

The only Perl/PCRE-specific feature in the regexp is the \b word boundary anchor, which I used instead of the $ end-of-string anchor to let it match "South Carolina".
Here's the regexp in a Perl one-liner for testing:
perl -nE 'say /[DNIOWy]|ss|M.n|^A.*a|or|[aguh]i|[sth]\b/ ? "USA" : "Italy"'

This is a more golfy test harness:
perl -pe '$_=/re/?"USA\n":"Italy\n"'

@Pseudonym: meh. As long as it doesn't count in the score, might as well keep it readable.

Regex (POSIX ERE), 28 bytes
Matching the regions of Italy:
[eldrz]..$|[cpVS]a|-|[hst]e$

Try it online!
Since we're being scored on the length of the pure regex, it just makes sense to show that alone above. The TIO test harness uses bash and egrep, but practically any regex engine would work. The only thing that makes this require POSIX ERE instead of POSIX BRE are the unescaped | alternative separators. Here is a bash oneliner to apply it:
egrep -q '[eldrz]..$|[cpVS]a|-|[hst]e$'&&echo Italy||echo USA

I used regexp-golf-coffeescript, with a little parameter tuning, to brute-force this.
You can experiment with deleting characters from the character classes or deleting alternatives in the TIO to see how many correct matches are lost by doing so. For many, it's just one each.
There may be further optimization possible. The script I used only searches the space in which a single character class is used per alternative, but some regex golf problems of this type benefit from multiple character classes in a single alternative, like [bgr].[ei]. However, given the characteristics of this data set, I expect that the benefit, if any, would probably be no more than a couple bytes.
Regex (POSIX ERE), 41 bytes
Matching the states of the USA:
[IfKNOWwhy]..|[kamed].$|t$|iz|ta.|[guaM]i

Try it online!

Ruby (plain regex), 44
$_ = gets.chomp
puts /'|-|(([^gn]i|gn|at)a|[hst]e|to|zo)$|To|La|pa/ ? "Italy" : "USA"

You know what? Case sensitivity is the best start-of-word anchor.
I'm not sure, but I think I owe the pa to Hax0r778's answer.

Perl - 51
(<STDIN> =~ m/'|-|ru|pu|at|pa|az|gu|mb|rc|ie|rd|ci|os|abr|mol|ven/)?printf("Italy\n"):printf("USA\n");

JavaScript 42
alert(/at|gn|mp|sc|-|'|((zi?|t)o|[hts]e|[lrd]ia)$/g.test(prompt())?"Italy":"USA")
I was initially going to work this out from the USA side, as eliminating KWXY from the USA list strips a lot of the States away... But Italy had it bested by a good 17 characters...
If we go with fat arrow notation we can reduce this to a simple function with a return variable.
r=s=>/at|gn|mp|sc|-|'|((zi?|t)o|[hts]e|[lrd]ia)$/g.test(s)?"Italy":"USA"
> r("South Dakota") // USA
> r("Puglia") // Italy

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