title: Reinvent the For loop

text:
# Question
Title: Reinvent the For loop
`For` loops are used extensively in many languages, but what would you do if no languages supported them?

Create a way to execute a basic `for` loop without using any repetition structures (`for`, `foreach`, `while`, `do`, etc).

The basic for loop that you need to replicate is set up like this

```
for(i=0;i<1000;i++)

```

You must be able to replicate this without using repetition structures. It must also execute code in your language that would be in the body of the loop. Any form of `eval` is allowed, though it may not execute the `for` loop on its own.

You can test your code by having it print `i` with a space 100 times, add this test case to the end of your answer to verify your code with others.

There are no restrictions on what exactly it has to be, all it needs to do is replicate the `for` loop.

Winner will be decided based on upvotes at the time that it is chosen.

# Answer
> 23 votes
## C, 45 chars without goto, if, for, ...

Not the smallest solution, but I find this way of doing it quite interesting in C :)

Doesn't use `goto`, `if`, `for`, or any other kind of control structures.

The function by itself (45 chars):

```
m(){int (*a[])()={m,exit};i++;(*a[i>999])();}

```

A compilable, working program:

```
#include <stdio.h>
#include <stdlib.h>

int i=0;
m(){int (*a[])()={m,exit};i++;printf("%i ",i);(*a[i>999])();}

int main()
{
  m();
}

```

# Answer
> 15 votes
## Haskell, 33 chars

This is more like *inventing* the for loop, because there is no such nonsense in Haskell :P.

```
mapM_(putStr.(' ':).show)[0..999]

```

# Answer
> 12 votes
## GCC - 106 95 chars

```
#define FOR(i,l,h)auto F();L(F,l,h);int F(i)
L(int f(int),int l,int h){l<=h?f(l),L(f,l+1,h):0;}

```

Unlike the other C solutions where you have to declare a callback, this one does it for you automagically:

```
FOR(i, 1, 10) {
    printf("%d\n", i);
}

```

It works by using GCC's nested function extension. Namely, it forward-declares the nested function `F`, passes it to the looping function `L`, and then starts the definition of `F`, leaving the braces for the user to add.

One beautiful thing about nested functions in GCC is that they support downward funargs, meaning the illusion is nearly complete:

```
long n = 1;
FOR(i, 1, 10) {
    n *= i;
}
printf("%ld\n", n); // 3628800

```

There is one major caveat: if you use `FOR` twice in the same scope, you'll get a conflict (namely, it will compile, but all the `FOR` loops will share one loop body). To allow multiple FOR loops in the same scope, we'll need 69 65 more characters:

**175 160 chars:**

```
#define FOR(i,l,h)F(i,l,h,__COUNTER__)
#define F(i,l,h,f)auto N(f)();L(N(f),l,h);int N(f)(i)
#define N(n)F##n
L(int f(int),int l,int h){l<=h?f(l),L(f,l+1,h):0;}

```

# Answer
> 11 votes
## C, 21 characters

```
f(){if(c++<999)f();}

```

For example:

```
#include <stdio.h>
int c = 0;
f()
{
    printf("%d ", c);
    if (c++<999) f();
}
int main(void)
{
    f();
}

```

Outputs:

```
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ... 998 999

```

# Answer
> 8 votes
## C# — no recursion, no goto

(using the Y combinator from lambda calculus)

```
class Program
{
    delegate Func<TInput, TResult> Lambda<TInput, TResult>(Lambda<TInput, TResult> f);

    static Func<TInput, TResult> Y<TInput, TResult>(Func<Func<TInput, TResult>, Func<TInput, TResult>> f)
    {
        Lambda<TInput, TResult> y = r => n => f(r(r))(n);
        return y(y);
    }

    static void Main()
    {
        Func<int, int> fibonacci = Y<int, int>(f => n => n > 1 ? f(n - 1) + f(n - 2) : n);
        Func<int, int> factorial = Y<int, int>(f => n => n == 0 ? 1 : n * f(n - 1));

        // Executes “fibonacci” 10 times, yielding 55
        Console.WriteLine(fibonacci(10));
        // Executes “factorial” 5 times, yielding 120
        Console.WriteLine(factorial(5));
    }
}

```

# Answer
> 7 votes
## x86 assembly, ~~12~~ 11 bytes' worth of instructions

```
66 31 c0                xor    %ax,%ax
<body>                ; involving %ax
66 40                   inc    %ax
66 3d  e8 03            cmp    $1000,%ax
75 ??                   jne    <body>

```

# Answer
> 6 votes
### Yet another Scala variant

Since Scala allows to use non-ASCII characters, we can implement real for :) (`o` is cyrillic).

```
def fоr(s:Unit,c: ⇒Boolean,e: ⇒Unit)(b: ⇒Unit):Unit=if(c){b;e;fоr(0,c,e)(b)}

```

Test:

```
var i:Int = _

fоr (i = 0, i < 1000, i += 1) {
  print(i + " ")
}

```

# Answer
> 5 votes
## Ruby 1.9 - 51 characters

```
def f a,b,c,&d
a[]
k=->{d[];c[];redo if b[]}
k[]end

```

This is a lot larger than other entries, but I think it captures the essence of the question better. In effect this allows you to write code almost exactly like the example:

```
def f a,b,c,&d
a[]
k=->{d[];c[];redo if b[]}
k[]end

i = 0 # Have to pre-declare i to have the closures work properly
f(proc{ i = 0 }, proc{ i < 1000 }, proc{ i += 1}) do
  p i
end

# Been a long time since I've actually used for's so took a long
# time to think of a non-trivial use.

j, sum = 0, 0 # Pre-declare variables for the closures

goal = 1000

f(proc{ j = 1; sum = 1 }, proc{ sum < goal }, proc{ j += 1 }) do
  sum = sum * j
end

puts "The next largest factorial after #{goal} is #{j-1}! at #{sum}"

```

# Answer
> 5 votes
# JavaScript, 34 characters

This assumes the actual printing function is *not* part of the `for` loop.

parameterized recursion **(43)**:

```
function f(i,m,c){if (i<m){c();f(++i,m,c)}}

function f(i, max, callback)
{
  if (i<max)
  {
    callback();
    f(++i,max,callback);
  }
}

```

reverse recursion **(36)**:
assumes `max >= 0`

```
function f(m,c){if(m){c()
f(--m,c)}}

function f(max,callback)
{
  if(max)
  {
    callback();
    f(--max,callback);
  }
}

```

ternary operator **(34)**

```
function f(m,c)
{m?c()&f(--m,c):0}

```

# Answer
> 5 votes
# C#, 70 57 characters

C# isn't the weapon of choice for code golf, but I thought I'd try it out:

```
void f(int i,Func<int,bool>j,int k){if(j(i)) f(i+k,j,k);}

```

This doesn't only perform the task of counting up to 1000; rather, it attempts to actually replicate `for` loop behavior for any task. That seemed somewhat closer to the intent of the challenge, but maybe that's just me.

Expanded:

```
void f(int i, Func<int, bool> j, int k)
{
    if (j(i))
    {
        f(i + k, j, k);
    }
}

```

Usage is very close to for-loop syntax:

```
f(0, i => i < 1000, 1);

```

# Answer
> 4 votes
**C: 33 chars** for the base for loop (assuming goto is allowed)

```
int i=0;s:if(i<1000){/`*code inside for loop here`*/i++;goto s;}

int i=0;s:if(i<1000){printf("%d ",i);i++;goto s;}

```

# Answer
> 4 votes
## Python

Specific case:

```
exec("print i,"+";")*1000

```

And in general:

```
exec("f"+";")*1000

```

where 'f' is your code. Proabably doesn't work for all cases.

# Answer
> 3 votes
## PowerShell 18

```
filter p{$i=$_;$i}

```

1 - 10

```
PS C:\> (1..100 | p)-join' '
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 6
4 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

```

Yeah, it's completely useless and you have to rewrite the function to do anything useful. But isn't that kind of the point? :)

# Answer
> 3 votes
I shall bear great shame for this, but here it is in Linux shell:

```
cat -An /dev/urandom|head -n1000|cut -f1

```

40 characters.

# Answer
> 3 votes
Here's your loop using Brainfuck, which is probably cheating:

```
,[.,]

```

# Answer
> 3 votes
# C (No recursion, no goto's)

```
#include <stdio.h>

int main()
{
    puts("0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999");
    return 0;
}

```

Completely according to the definition, isn't it?

# Answer
> 2 votes
## Perl, 21 characters

```
map{print"$_ "}0..999

```

# Answer
> 2 votes
## JavaScript - 39 characters in test case

**Chrome, Opera, and IE:** `eval(s="i<1e3&&eval(s,print(i++))",i=0)`. This fails with "call stack size exceeded" on Safari and "too much recursion" on Firefox.

**Firefox:** `(function f()i<1e3&&f(print(i++)))(i=0)`. This uses Mozilla's non-standard "expression closure" feature to eliminate a pair of curly braces.

**Note:** Change `print(i++)` to `alert(i++)` if you need to. You can change `1e3` to `100` to reduce the number of iterations for Safari.

# Answer
> 2 votes
## QBasic (24 characters)

```
1?i:i=i+1:IF i<1E3THEN 1

```

expands to:

```
1 PRINT i: i = i + 1: IF i < 1000! THEN 1

```

**Note:** This assumes that `i` still has its original value of 0.

# Answer
> 2 votes
## J, ?\<10 chars

```
f^:1000

```

In J there are (almost) no loops; instead, one usually uses arrays and implicit loops through them. For example, to sum the integers 1..100, you apply (/) the "verb" plus (+) to the array 1..100 (i.101)

```
+/i.101
5050

```

To display the numbers 0..99, we just construct the array:

```
i.100
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ...

```

`^:` is the "power" verb; `f^:1000` is something like `exec()*1000` in python.

# Answer
> 2 votes
## C#, 58 characters

**Update:** D'oh...appears this is a virtually identical answer to Eelvex who beat me by a few minutes.

Not very clever - just simple recursion in .NET.

```
void f(int c,int m){Console.Write(c+" ");if(c++<m)f(c,m);}

```

Or taking out the body of the "for loop" (35 characters):

```
void f(int c,int m)if(c++<m)f(c,m);

```

Allows to seed the initial value and the max value.

# Answer
> 2 votes
# Scala

Inspired from Nemo157's answer:

```
def myfor(test: =>Boolean, inc: =>Unit)(stmts: =>Unit) : Unit =
        if (test) {
                stmts
                inc
                myfor(test, inc)(stmts)
        }

```

And this can be used like this:

```
var i = 0
myfor(i<1000, i+=1) {
        print(i+" ")
}

```

Golfed (62) :

```
def f(t: =>Boolean,i: =>Unit)(s: =>Unit){if(t){s;i;f(t,i)(s)}}

```

---

Or:

```
def myfor[A](init: A, test: (A)=>Boolean, inc: (A)=>(A))(stmts: =>Unit) : Unit =
        if (test(init)) {
                stmts
                myfor(inc(init), test, inc)(stmts)
        }

myfor[Int](0, _<10, _+1) {
        println("loop")
}

```

# Answer
> 2 votes
**Clojure**
`(map #(print (str % " ")) (range 1 (inc 100)))`

Replace print with the function to execute.
Use (inc 100) or 101 for the last value.

# Answer
> 2 votes
# Perl most simple - 18 chars (ok, cheating)

```
print"@{[0..999]}"

```

output: 0 1 2 3 ... 998 999

but:

# Perl regex/goatse op (real pseudoloop) - 39 (16) chars

```
()="@{[0..999]}"=~/\d+(?{print"$& "})/g

```

### the 'base loop' beeing 16 chars

```
()=             =~/\d+(?{          })/g

```

output: 0 1 2 3 ... 998 999

Regards

rbo

# Answer
> 2 votes
# Javascript - 86 chars

```
e=eval,n=function(j,k,c){if(e(j))e(k),c(),n(j,k,c)},f=function(i,j,k,c){e(i),n(j,k,c)}

```

Maybe not the shortest javascript solution, but it replicates iterator declaration, iterator manipulation as well as a looping condition.

Example use case:

```
f('a = 0', 'a < 9', 'a++', function() {
    console.log(a);
});

```

# Answer
> 1 votes
## C#, 70 chars

```
Enumerable.Range(0,999).ToList().ForEach(x=>Console.WriteLine(x+" "));

```

This can probably be golfed down, but it's the best I could come up with quickly.

# Answer
> 1 votes
## QuickBASIC, 103 characters

```
10 IF i < 1000 THEN PRINT MID$(STR$(i) + SPACE$(1), 2, ABS(i < 100) * 5); : i = i + 1: GOTO 10 ELSE END

```

# Answer
> 1 votes
```
;; for (int index=1, result=1; !cmp(result, max); index=incr(index)) result=body(index,result);
((lambda (index result cmp max body incr)
   ((lambda (f n i)
      (if (cmp i max) n
          (f f (body i n) (incr i))))
    (lambda (f n i)
      (if (cmp i max) n
          (f f (body i n) (incr i)))) result index)) 1 1 > 1000 (lambda (i n) (printf "i:~a~nn:~a~n" i n) (* n i)) (lambda (x) (+ x 1)))

```

# Answer
> 1 votes
## LISP, 91 characters

```
(defun m(x)(if(= 1000(length x))x(m(append x(list(1+(car(last x))))))))
(mapcar #'f(m'(0)))

```

*It could be shorter with labels.*

Example usage:

```
(defun f(x) (format t "~a " x))
(mapcar #'f (m '(0)))
0 1 2 3 4 5 6 7 8 9 10 11 12 ...  997 998 999

```

# Answer
> 1 votes
## Perl (23 chars.):

```
print join " ",(0..999);*

```

or same Perl but in simpler yet more lengthy and recursive words:

```
sub i {($s,$e)=@_; return if $s==$e; print "$s "; i($s+1,$e)}

i(0,1000);

```

# Answer
> 1 votes
bash:

```
echo {1..1000}

```

14 chars.

# Answer
> 1 votes
## Python3 - 27 chars

```
any(map(print,range(1000)))

```

# Answer
> 1 votes
## Windows Batch File, 65

```
set I=%S%
:l
if %I% GEQ %E% goto :eof
call %C%
set /a I+=1
goto l

```

Test file:

```
@echo off
set S=0
set E=100
set "C=<nul set /p X=%%I%% "
call for.cmd

```

Can save two bytes if the loop always starts at 0.

# Answer
> 1 votes
# sh

```
cat -An /dev/urandom|head -n1000|cut -f1|xargs

```

# Answer
> 1 votes
## Java with Lambda — 259 characters

I just built the prerelease Java langtools with the experimental lambda support that has recently been canceled for JDK 7 and pushed back until JDK 8 in 2012 (boo!) and wanted to try it out.

Formatted nicely, this version clocks in at 304 characters. If you reformat it so all the code of the interface is on one line and the class is on another, it gets down to 259 characters. I'm sure you could golf it down lower (shorten the identifiers, for starters), but Java is never going to be competitive at golf, so why obfuscate it.

```
interface Fore {
    void exec(int i);
}

public class ForLoop {
    public static void main(String[] args) {
        loop(1, 10, #{ int i -> System.out.println(i) });
    }

    public static void loop(int x, int max, Fore fore) {
        fore.exec(x);
        if (x < max) loop(x+1, max, fore);
    }
}

```

I just wanted to demonstrate what will be possible with lambdas in Java SE 8. The call to loop could be written with an anonymous inner class, instead:

```
loop(1, 10, new Fore() {
    public void exec(int i) {
        System.out.println(i);
    }
});

```

Yuck.

The syntax for lambdas in Java hasn't been settled yet; this is just what works with the current dev build of javac. Thanks to those who are working to make it happen. Java should have gotten lambdas and closures years ago. Alas.

# Answer
> 1 votes
## C

(not really golfing, but fun)

```
#include <setjmp.h>
#include <stdio.h>

int main() {
    jmp_buf b;
    int i;
    if ((i = setjmp(b)) < 100) {
        printf("%d\n", i);
        longjmp(b, i + 1);
    }
}

```

# Answer
> 1 votes
## JavaScript, 63 characters

```
(function i(s,r){r+=s+' ';s++<1e3?i(s,r):console.log(r)})(0,'')

```

with proper console output

# Answer
> 1 votes
Javascript This one supports a few extra things, with plenty still missing. Breaks after 3000 iterations cuz it's recursive.

```
function r(a,c,b,o,q,f) {var d=c=='<'?a<b:(c=='>'?a>b:(c=='=='?a==b:(c=='!='?a!=b:null)));if(d){f(a);a=o=='+'?a+q:(o=='-'?a-q:(o=='*'?a*q:(o=='/'?a/q:null)));r(a,c,b,o,q,f);}}
//params:  a = iterator start
// c = comparison type (supports >, <, ==, !=)
// b = iterator compare
// o = iterator operation (+, -, *, /)
// q = increment or whatever you call it
// f = function to execute each successful iteration

// from 0 to 99
r(0, '<', 100, '+', 1, function(i) {document.write(i + ' ');});
// from 100 to 1
r(100, '>', 0, '-', 1, function(i) {document.write(i + ' ');});
// powers of 10
r(1, '!=', 1000000, '*', 10, function(i) {document.write(i + ' ');});

```

# Answer
> 1 votes
## R - 11 characters

General case:

```
f(1:1000)

```

Where *f* is your function.

Specific case:

```
cat(1:1000)

```

# Answer
> 1 votes
## C 45 characters including printout

Compiles, links, and runs as-is; no need to define a separate function and then call it, adding to source size.

```
main(a){printf("%d ",a-1);a<1000&&main(a+1);}

```

# Answer
> 1 votes
## Javascript (44 chars.):

Another rather pointless option, but then who said golf had to have a point :) Plus I gained something new... I never realised you could get away with `i+++`

```
eval(Array((i=0)+1e3).join('i+++" "+')+'i')

```

I also learned that running `.map` and `.forEach` on an initialised *undefined filled* Array does nothing... *at least in FireFox anyway*

```
Array(1000).forEach(function(){ /* this code is never executed :( */ })

```

# Answer
> 1 votes
# Javascript, 71. No if, for, or recursive function

```
function f(i,c,b){a=[]
eval(s=b+";a[++i]=s;a=a.slice(0,c);eval(a[i])")}

```

Test:

```
f(0,1000,'console.log(i)')

```

# Answer
> 1 votes
## Spaghetti PHP 44

```
<?$i=0;a:if($i<1001){echo $i++." ";goto a;}

```

# Answer
> 1 votes
# Python 2.7, 60 Bytes with command-line parameter

Prints 'O' to the console:

```
import sys
def l(t,m):
 print 'O'
  if t!=m:
   l(t+1,m)
l(0,int(sys.argv[0]))

```

EDIT: Realised it didn't work, so byte count has gone up to fix On another note, here's a 127 byte version, including print function, that will let you actually call functions with one argument

```
import sys
def println(a):
print(a)
def l(t,m,f,a):
    f(a)
    if t!=m:
        l(t+1,m,f,a)
p=println
l(0,int(sys.argv[1]),p,"there")

```

# Answer
> 0 votes
## Python 2.x - 17 chars

```
print range(1000)

```

# Answer
> 0 votes
# Groovy, 32 bytes

```
(0..1000).each{ print "${it} " }

```

# Answer
> 0 votes
**Scala:**

```
(1 to 100)mkString" "

```

21 chars not that ugly:

```
(1 to 100) mkString " "

```

# Answer
> 0 votes
Language = C

just loop - 59 characters

```
(int(*)())\x66\x31\xc0\x66\x40\x66\x3d\xe8\x03\x75\xf8\xc3"

```

loop+call - 92 characters

```
(int(*)())"\x66\x31\xc0\x8b\x5c\x24\x04\x66\x40\x50\xff\xd3\x58\x66\x3d\xe8\x03\x75\xf4\xc3"

```

Example usage:

```
#include <stdio.h>

void disp(int n){printf("%d ", n&(0xffff));}

int main(){
    ((int(*)())"\x66\x31\xc0\x8b\x5c\x24\x04\x66\x40\x50\xff\xd3\x58\x66\x3d\xe8\x03\x75\xf4\xc3")(&disp);
    return 0;
}

```

This will only work on x86 machines. Tested with gcc (and works on codepad.org -\> http://codepad.org/uyhFR9XU)

```
int fn(int n){ // n is at esp+4

    xor %ax, %ax ; zeros ax
    mov 4(%esp), %ebx ; saves esp+4 (addr of n) to ebx

    body:
    inc %ax ; add one to ax (this will print from 1 to 1000 instead of 0-999)
    push %eax ; pushes eax onto the stack
    call *%ebx ; calls n, which should contain &disp
    pop %eax ; pop eax off the stack assuming disp did not use eax
    cmp $1000, %ax ; compare
    jne body ; if not 1000, goto body

    ret
}

```

# Answer
> 0 votes
### APL (26)

```
{(⊃⍵)>⊃⌽⍵:⍬⋄⍺⍺∇⍵+1 0⊣⍺⍺⊃⍵}

```

Usage:

```
<function> {(⊃⍵)>⊃⌽⍵:⍬⋄⍺⍺∇⍵+1 0⊣⍺⍺⊃⍵} <start> <end>

```

i.e.

```
{⍞←⍵ ' '} {(⊃⍵)>⊃⌽⍵:⍬⋄⍺⍺∇⍵+1 0⊣⍺⍺⊃⍵} 1 100

```

prints the numbers from 1 to 100.

# Answer
> 0 votes
**VB11 (95c)**

```
Dim F As Action(Of Integer, Integer, Action(Of Integer)) =
  Sub(i, m, a)
    If i > m Then Return
    a(i)
    F(i + 1, i, a)
  End Sub

```

And in use

```
 F(1, 1000, Sub(X) Console.WriteLine(X))

```

**C# 52**

```
f(int i,int m, action<int> a){if(i<=m){a(i);f(i-1,m,a);}

```

# Answer
> 0 votes
# Python 2.6 (42)

```
def f(i,p,j=0):j<i and(p(j)or f(i,p,j+1))

# Test:
def do(i):
    print i
f(100,do)

```

This for-Function also includes the break command:

```
def do(i):
    print i
    if i==7:
        return True
        # break
f(100,do)

```

# Answer
> 0 votes
## clang (152)

Tested with Apple clang version 4.0

```
bfor(int n,void(^b)(int)){
    __block void(^e)(int,int)=^(int l,int h){
        int m;
        h<l?:(m=(l+h)/2,e(l,m-1),b(m),e(m+1,h));
    };
    e(0,n-1);
}

```

Usage:

```
main(){
    bfor(100,^(int i){
        printf("%d ", i);
    });
    puts("");
}

```

The stack depth is log2 of the count due to the binary tree and thus it's unlikely to overflow due to recursion.

# Answer
> 0 votes
## Ti-84 Basic, 34

Here, `>` represents the calculator's `STO->` button.

```
:-1>I:Lbl A:I+1>I:If I<1000:Goto A

```

# Answer
> 0 votes
## Golf-Basic 84, 23 characters

```
:-1_Il`A:I++I@I<1000o`A

```

# Answer
> 0 votes
# Lua, 59

```
local function f(x)if x<1000 then return f(x+1)end end f(0)

```

The loop body is located right after the `then`. This does not overflow stack because of the tail call optimization.

Test case:

```
local function f(x)if x<1000 then print(x)return f(x+1)end end f(0)

```

# Answer
> 0 votes
Same as @houbysoft, but in C++.

```
#include <iostream>
#include <vector>

int main(int argc, char *argv[])
{
    int i = 0;
    std::function<int()> m = [&i, &m]()->int {
        std::vector<std::function<int()>> functors;
        functors.push_back(m);
        functors.push_back([]()->int{return 0;});
        i++;
        std::cout << i << std::endl;
        functors[i>999]();
        return i;
    };
    m();
    return 0;
}

```

And Objective C (Just C using blocks, actually...)

```
#import <Foundation/Foundation.h>

int main(int argc, char *argv[])
{
    __block int i = 0;
    __block int (^m)();
    m = ^() {
        int (^a[])() = {m, ^(){return 0;}};
        i++;
        NSLog(@"i: %d", i);
        a[i>9]();
        return i;
    };
    m();
    return 0;
}

```

# Answer
> 0 votes
**Nemerle (?c)**

```
macro for (init, cond, change, body)
syntax ("for", "(", init, ";", cond, ";", change, ")", body)
{
 <[
   $init;
   def loop () : void
   {
     if ($cond) { $body; $change; loop() }
        else ()
   };
   loop ()
  ]>
}

```

Usage

```
 for (mutable i = 0, i < 10, i++, printf ("%d", i))

```

# Answer
> 0 votes
## Lua (63 chars)

`function F(n,f,...)if n>0 then f(...)return F(n-1,f,...)end end`

Slightly longer, but more generic, than @mniip's version. Use like `F(1000,print,' ')`.

# Answer
> 0 votes
# C - 48 characters

Compilable code.

```
main(int i){i^1002&&main(i+1);printf("%i",i-2);}

```

# Answer
> 0 votes
# **Objective-C 58 Characters (Or 45...)**

```
int i;
-(void)f {
    NSLog(@"%d",i++);
    if (i<1000) [self f];
}

[self f];

```

\*13 chars went on printing `i`, so only the for-loop is actually 45...

# Answer
> 0 votes
# CPython 2, 158 bytes

(Yes, this is both implementation and version specific)

```
class K(object):
 def __init__(s,b,c,e,n):
  if not n:n={};exec b in n
  else:exec e in n
  s.n=n;s.c=c;s.e=e
 def __del__(s):eval(s.c,s.n)or K(0,s.c,s.e,s.n)

```

Example usage:

```
K('i=55','i<88','i+=1;print i`,0)

```

---
Tags: popularity-contest
---


title: Find words that rhyme

text:
# Question
Title: Find words that rhyme
# Challenge

Joe the rapper is struggling with rhyming words in his lyrics. He needs your help.

For this situation, we will use rhymes where the last syllable in a word is the same as the other word (spelled the same).

When Joe inputs a word, the program will read a list of words from a file and output those that rhyme with Joe's word.

To show that the program works, we will only need to use a small list.

txt File:

```
hello
joe
crew
flow
time
apple
heart
glow
rhyme
art
jello
grew
doe
flue
blow
smart
dime
cat
slime
show
bedtime
clue
grime
toe
dart
cart
brew
snow
prime
hat
chart
lime
blue
knew
lunchtime
restart

```

# Examples

Input: `snow`

Output: `blow flow glow show` *Note- Should not output the input*

Input: `fart`

Output: `restart art dart cart chart smart heart` *Note- Should work for inputs not in list*

Input: `crime`

Output: `time slime prime grime dime lime bedtime lunchtime` *Note- Should work for all syllables*

# Rules

1. Should output all words that rhyme with input

*does not need to output rhymes with different letters Ex: `Crime` should not output `rhyme`*
2. Should not output the input
3. Should work with inputs not in the list
4. Should work will all syllables

Shortest Bytes Wins!

# Answer
# Ruby, 68 bytes

FGITW. Full program, takes file and word from command line: `ruby script.rb words.txt "hello"`.

Assumes the last syllable (or rather, the section of the syllable to match against for the purposes of rhyming) is at least 2 characters long, or more if there are extra vowels before that.

```
f,w=$*
w=~/[aeiou]*..$/
puts open(f).map(&:chomp).grep(/#{$&}$/)-[w]

```
> 1 votes

# Answer
## JavaScript (ES6), 67 bytes

```
(a,w)=>a.filter(s=>s!=w&s.endsWith(w.replace(/.*([aeiou].)/,"$1")))

```

Function that accepts an array of words and an input word as parameters. Uses the definition of rhyme as the substring of the word starting at the last vowel before the last letter.

```
a=
(a,w)=>a.filter(s=>s!=w&s.endsWith(w.replace(/.*([aeiou].)/,"$1")))
;
u=w=>r.value=a(f.value.split`\n`,w).join`\n`
```

```
File:
<textarea rows=5 id=f>
hello
joe
crew
flow
time
apple
heart
glow
rhyme
art
jello
grew
doe
flue
blow
smart
dime
cat
slime
show
bedtime
clue
grime
toe
dart
cart
brew
snow
prime
hat
chart
lime
blue
knew
lunchtime
restart
</textarea>
<br>
Word:
<input oninput="u(this.value)">
<br>
Rhymes:
<textarea rows=5 id=r>
</textarea>
```
> 1 votes

---
Tags: code-golf, natural-language
---


title: Three Indistinguishable Dice

text:
# Question
Title: Three Indistinguishable Dice
**Given three dice rolls** (integer values from 1-6) in sorted order (so as to be indistinguishable), **convert them to the sum of two fair dice** with an identical distribution.

The answer for three to one is summing them all, modulo 6. The end-result is a perfectly flat distribution, where each of the six numbers are equally likely (just like a single die).

It's easy to do this for three-to-one, by summing them all modulo 6. The end-result is a perfectly flat distribution, where each of the six numbers are equally likely (just like a single die). Your challenge is to do the same for three-to-two.

Inspired by standupmath's The Three Indistinguishable Dice Puzzle. A follow-up "solution" video was also posted, but arguing about "elegance" of one way or another is a bit subjective. Counting characters isn't. `:D`

## Instructions

Write a program or function that accepts three **sorted** integers/digits, 1-6, and outputs or returns a single integer, 2-12, such that, for the 216 possible inputs, the outputs are distributed as:

```
 222222
 333333333333
 444444444444444444
 555555555555555555555555
 666666666666666666666666666666
 777777777777777777777777777777777777
 888888888888888888888888888888
 999999999999999999999999
 AAAAAAAAAAAAAAAAAA
 BBBBBBBBBBBB
 CCCCCC

```

(I've used hex to keep to single characters; decimal output is fine)

**Because the dice are indistinguishable, there is no intrinsic order to them, hence the sorted input. You cannot simply "drop the third" because that would be ambiguous.**

## Details

* Score is the length of the program in bytes
* The program can be a function that's called somehow, or executable script that reads from stdin, or whatever's convienent.
* No "rerolling" by getting entropy from another source

## Example (and test)

Rather than doing any sort of probabilistic testing, it's easy enough to rip through the 216 (6³) cases of all the three dice and assert that your function returns each value as many times as it should. It will be called with identical parameters (e.g. the cases `1, 2, 3` and `3, 2, 1`, ... are presumed indistinguishable and are (arbitrarily) converted to `1, 2, 3`).

An example answer (extremely brute-force and inefficient) and test suite is provided below in Python. Hopefully the test bits are clear enough to port to your language of choice, though doing stdin/stdout would be a bit different. The testing code is just for testing and not scored (though if you want to provide it for other users of your language or I/O method, that might be useful).

```
# 6x6 lists of numbers with digits sorted
LUT = [
    [[124], [133, 166], [346], [223, 355], [256], [115, 445]],
    [[233, 266], [125], [224, 455], [134], [116, 446], [356]],
    [[126], [111, 333, 555, 225], [234], [144, 366], [456], [135]],
    [[112, 244], [235], [334, 466], [145], [226, 556], [136]],
    [[146], [122, 155], [236], [113, 344], [245], [335, 566]],
    [[246], [123], [114, 336], [345], [222, 444, 666, 255], [156]],
]

def three2two(rolls):
    look_for = int('{}{}{}'.format(*sorted(rolls)))
    for i in range(6):
        for j in range(6):
            if look_for in LUT[i][j]:
                return i + j + 2

# fair distribution of the sum of two dice multiplied by 6 (because each should be hit 6x)
expected_counts = {
    2: 6,   12: 6,
    3: 12,  11: 12,
    4: 18,  10: 18,
    5: 24,   9: 24,
    6: 30,   8: 30,
    7: 36,
}

d = [1, 2, 3, 4, 5, 6]
for i in d:
    for j in d:
        for k in d:
            ijk = sorted([i, j, k])
            result = three2two(ijk)
            expected_counts[result] -= 1

for key in expected_counts:
    assert expected_counts[key] == 0

```

# Answer
> 5 votes
# Jelly, ~~22~~ 20 bytes

```
6ṗ3Ṣ€ṢðQ€L€Ụịḷi’:6d6‘S

```

Try it online! or simulate all 216 outcomes.

### Background

We map each unordered triplet of dice rolls (listed with respective multiplicities) to an ordered pair of dice rolls in the following fashion:

```
[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3] -> [1,1]
[1,2,4],[1,2,4],[1,2,4],[1,2,4],[1,2,4],[1,2,4] -> [1,2]
[1,2,5],[1,2,5],[1,2,5],[1,2,5],[1,2,5],[1,2,5] -> [1,3]
[1,2,6],[1,2,6],[1,2,6],[1,2,6],[1,2,6],[1,2,6] -> [1,4]
[1,3,4],[1,3,4],[1,3,4],[1,3,4],[1,3,4],[1,3,4] -> [1,5]
[1,3,5],[1,3,5],[1,3,5],[1,3,5],[1,3,5],[1,3,5] -> [1,6]
[1,3,6],[1,3,6],[1,3,6],[1,3,6],[1,3,6],[1,3,6] -> [2,1]
[1,4,5],[1,4,5],[1,4,5],[1,4,5],[1,4,5],[1,4,5] -> [2,2]
[1,4,6],[1,4,6],[1,4,6],[1,4,6],[1,4,6],[1,4,6] -> [2,3]
[1,5,6],[1,5,6],[1,5,6],[1,5,6],[1,5,6],[1,5,6] -> [2,4]
[2,3,4],[2,3,4],[2,3,4],[2,3,4],[2,3,4],[2,3,4] -> [2,5]
[2,3,5],[2,3,5],[2,3,5],[2,3,5],[2,3,5],[2,3,5] -> [2,6]
[2,3,6],[2,3,6],[2,3,6],[2,3,6],[2,3,6],[2,3,6] -> [3,1]
[2,4,5],[2,4,5],[2,4,5],[2,4,5],[2,4,5],[2,4,5] -> [3,2]
[2,4,6],[2,4,6],[2,4,6],[2,4,6],[2,4,6],[2,4,6] -> [3,3]
[2,5,6],[2,5,6],[2,5,6],[2,5,6],[2,5,6],[2,5,6] -> [3,4]
[3,4,5],[3,4,5],[3,4,5],[3,4,5],[3,4,5],[3,4,5] -> [3,5]
[3,4,6],[3,4,6],[3,4,6],[3,4,6],[3,4,6],[3,4,6] -> [3,6]
[3,5,6],[3,5,6],[3,5,6],[3,5,6],[3,5,6],[3,5,6] -> [4,1]
[4,5,6],[4,5,6],[4,5,6],[4,5,6],[4,5,6],[4,5,6] -> [4,2]
[1,2,2],[1,2,2],[1,2,2],[1,3,3],[1,3,3],[1,3,3] -> [4,3]
[1,4,4],[1,4,4],[1,4,4],[1,5,5],[1,5,5],[1,5,5] -> [4,4]
[1,6,6],[1,6,6],[1,6,6],[2,3,3],[2,3,3],[2,3,3] -> [4,5]
[2,4,4],[2,4,4],[2,4,4],[2,5,5],[2,5,5],[2,5,5] -> [4,6]
[2,6,6],[2,6,6],[2,6,6],[3,4,4],[3,4,4],[3,4,4] -> [5,1]
[3,5,5],[3,5,5],[3,5,5],[3,6,6],[3,6,6],[3,6,6] -> [5,2]
[4,5,5],[4,5,5],[4,5,5],[4,6,6],[4,6,6],[4,6,6] -> [5,3]
[5,6,6],[5,6,6],[5,6,6],[1,1,2],[1,1,2],[1,1,2] -> [5,4]
[1,1,3],[1,1,3],[1,1,3],[1,1,4],[1,1,4],[1,1,4] -> [5,5]
[1,1,5],[1,1,5],[1,1,5],[1,1,6],[1,1,6],[1,1,6] -> [5,6]
[2,2,3],[2,2,3],[2,2,3],[2,2,4],[2,2,4],[2,2,4] -> [6,1]
[2,2,5],[2,2,5],[2,2,5],[2,2,6],[2,2,6],[2,2,6] -> [6,2]
[3,3,4],[3,3,4],[3,3,4],[3,3,5],[3,3,5],[3,3,5] -> [6,3]
[3,3,6],[3,3,6],[3,3,6],[4,4,5],[4,4,5],[4,4,5] -> [6,4]
[4,4,6],[4,4,6],[4,4,6],[5,5,6],[5,5,6],[5,5,6] -> [6,5]
[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5],[6,6,6] -> [6,6]

```

This makes all outcomes equiprobable.

### How it works

```
6ṗ3Ṣ€ṢðĠ€Ụịḷi’:6d6‘S  Main link. Argument: D (three dice rolls, sorted)

6ṗ3                     Generate lists of length 3 over [1, 2, 3, 4, 5, 6].
   Ṣ€                   Sort each triplet.
     Ṣ                  Sort the list of triplets.
      ð                 Begin a new, dyadic chain.
                        Arguments: A (list of triplets), D
       Ġ€               Group each; group the indices of each triplet by the
                        the corresponding values.
                        For a triplet [a, b, c], this yields:
                          [[1], [2], [3]] if a < b < c
                          [[1], [2, 3]]   if a < b = c
                          [[1, 2], [3]]   if a = b < c
                          [[1, 2, 3]]     if a = b = c
           Ụ            Grade up; sort the indices of A by those 2D lists.
            ịḷ          Retrieve the elements of A at those indices.
                        This sorts A as in the previous section.
              i         Find the (1-based) index of D.
               ’        Decrement to get the 0-based index.
                :6      Divide the index by 6, rounding down.
                  d6    Divmod; return quotient and remainder of division by 6.
                    ‘   Increment to map [0, ..., 5] to [1, ..., 6].
                     S  Sum the results.

```

# Answer
> 1 votes
# Pyth, ~~41~~ 27 bytes

```
JSSM^S6 3+2sPtj+216xo/JNJQ6

```

10 random testcases

Confirmation of validity.

### Conversion table:

```
2: [111, 222, 333, 444, 555, 666]
3: [112, 113, 223, 224]
4: [114, 115, 225, 226, 355, 366]
5: [116, 122, 125, 233, 244, 445, 446]
6: [126, 133, 144, 146, 255, 266, 455, 466]
7: [134, 155, 156, 166, 246, 334, 335, 556, 566]
8: [123, 135, 234, 256, 336, 344]
9: [124, 136, 235, 345]
10: [145, 236, 346]
11: [245, 356]
12: [456]

```

## Previous 41-byte solution:

I need to golf this...

```
JSM^S6 3+2f/@co,/JNNJ.u+NY*R6t+S5_S6 6TQ0

```

Try it online!

### Conversion table:

```
2: [111, 222, 333, 444, 555, 666]

3: [112, 113, 114, 115]

4: [116, 122, 133, 144, 155, 166]

5: [223, 224, 225, 226, 233, 244, 255, 266]

6: [334, 335, 336, 344, 355, 366, 445, 446, 455, 466]

7: [556, 566, 123, 124, 125, 126, 134]

8: [135, 136, 145, 146, 156]

9: [234, 235, 236, 245]

10: [246, 256, 345]

11: [346, 356]

12: [456]

```

# Answer
> 1 votes
# CJam, 37 35 bytes

Probably not golfed well. ~~But beat Pyth.~~

```
8aq~\;[_2$>8+@7+@:U2+1$([8U4$7]])er

```

Try it here.

# Answer
> 1 votes
# CJam, ~~25~~ 24 bytes

```
6Zm*{$e`z}$q~:(a#6bW2t1b

```

This is a port of my Jelly answer.

Try it online! or simulate all 216 outcomes.

*Thanks to @jimmy23013 for golfing off 1 byte!*

---
Tags: code-golf, number
---


title: Normal and visual string reversion

text:
# Question
Title: Normal and visual string reversion
Write some code that acts as a cat program. That is, to input a string and output it as is. But the normal reversion of your code must output the normal reversion of the input string. And the visual reversion of your code must output the visual reversion of the input string.

The normal reversion is the reversed character sequence of a string. The visual reversion is the normal reversion with the characters `()[]{}<>` replaced by `)(][}{><` respectively.

You could use any codepage that has the characters `()[]{}<>` and is published before this challenge to define characters. You must use the same codepage for all your code. Your original code must be valid in this codepage, and applying either of your reversed code to that should yield itself.

This is , shortest code in bytes wins.

### Example

For the string `AB(XY)`, its normal and visual reversions are `)YX(BA` and `(YX)BA` respectively.

If your code (in a hypothetical language) is `AB(XY)`, then the code `)YX(BA` and `(YX)BA` should output the normal and visual reversions of the input string respectively. And `AB(XY)` should act as a cat program.

# Answer
# 05AB1E, 16 bytes

Uses the fact that 05AB1E has a constant predefined to `"()<>[]{}"` and isn't affected the visually reversion.

Code:

```
,q‡"}{][><)("užR

```

Explanation:

```
,                 # Pop and print the input.
 q                # Quit.
  ‡"}{][><)("užR  # This part is ignored.

```

Try it online!

---

Reversed:

```
Ržu"()<>[]{}"‡q,

```

Explanation:

```
R                 # Reverse the input.
 žu               # Short for "()<>[]{}".
   "()<>[]{}"     # Push this string.
             ‡    # Transliterate (no-op, since everything is transliterated to itself).
              q   # Quit and implicitly print.
               ,  # This part is ignored.

```

Try it online!

---

Visually reversed:

```
Ržu")(><][}{"‡q,

```

Explanation:

```
R                 # Reverse the input.
 žu               # Short for "()<>[]{}".
   ")(><][}{"     # Push this string.
             ‡    # Transliterate (giving the visually reversed string).
              q   # Quit and implicitly print.
               ,  # This part is ignored.

```

Try it online!

Uses **CP-1252** encoding.
> 9 votes

# Answer
## CJam, 21 bytes

```
qe#ere$_"}{][><)("%Wq

```

Test it here.

Normal reversion:

```
qW%"()<>[]{}"_$ere#eq

```

Test it here.

Visual reversion:

```
qW%")(><][}{"_$ere#eq

```

Test it here.

### Explanation

First, the normal code:

```
qe#ere$_"}{][><)("%Wq

```

This is simple: `q` reads all input, `e#` comments out the remainder of the program, and the input is printed implicitly at the end.

Now the normal reversion:

```
q            e# Read all input.
W%           e# Reverse it.
"()<>[]{}"   e# Push this string.
_$           e# Duplicate and sort it. However, the string is already sorted
             e# so we just get two copies of it.
er           e# Transliteration (i.e. character-wise substitution). But since the
             e# source and target string are identical, the reversed input
             e# is left unchanged.
e#eq            Just a comment...

```

And finally, the visual reversion:

```
q            e# Read all input.
W%           e# Reverse it.
")(><][}{"   e# Push this string.
_$           e# Duplicate and sort it. This gives us "()<>[]{}", i.e. the
             e# same string with each bracket pair swapped.
er           e# Transliteration (i.e. character-wise substitution). This
             e# time, this toggles all the brackets in the reversed input
             e# completing the visual reversion.
e#eq            Just a comment...

```
> 6 votes

# Answer
## Haskell, 124 bytes

Forward:

```
f=id
--esrever.q pam=2>1|esrever=2<1|f;x=x q;')'='(' q;'('=')' q;']'='[' q;'['=']' q;'>'='<' q;'<'='>' q;'}'='{' q;'{'='}' q

```

Normal reverse:

```
q '}'='{';q '{'='}';q '>'='<';q '<'='>';q ']'='[';q '['=']';q ')'='(';q '('=')';q x=x;f|1<2=reverse|1>2=map q.reverse--
di=f

```

Visual reverse:

```
q '{'='}';q '}'='{';q '<'='>';q '>'='<';q '['=']';q ']'='[';q '('=')';q ')'='(';q x=x;f|1>2=reverse|1<2=map q.reverse--
di=f

```

Each version defines a function `f` which takes and returns a string. In forward mode `f` is the identity function `id`, the rest of the code is a comment. In normal reverse mode the guard `1<2` in `f` is `True`, so `reverse` is applied. In visual reverse mode, the `<` is switched to `>` and the guard is `False`. The second guard is just the other way around and `True`in visual mode, so additionally `q` is applied which switches "()\<\>{}\[\]".

```
f|1<2=reverse|1>2=map q.reverse      -- normal reverse mode
f|1>2=reverse|1<2=map q.reverse      -- visual reverse mode

```

Besides `<`and `>` in the guards, my code doesn't use any of the brackets, so they can't be messed up.
> 6 votes

# Answer
# Bash + common linux utilities, 51

* 2 bytes saved thanks to @jimmy23013
* 2 bytes saved thanks to @AdamKatz

```
#'><}{][)(' `P5BD706D5AC79E196iFe- cd` rt|ver|
\cat

```

Normal reversion:

```
tac\
|rev|tr `dc -eFi691E97CA5D607DB5P` '()[]{}<>'#

```

Visual reversion:

```
tac\
|rev|tr `dc -eFi691E97CA5D607DB5P` ')(][}{><'#

```

The main trick here is that the string `()[]{}<>` is encoded as 691E97CA5D607DB5 (base 15). The resulting `dc` command will yield this same result after either kind of reversion. However the `'()[]{}<>'` string literal is sensitive to the reversal type.

`tac` is required to reverse order of input lines and `rev` is required to reverse the characters of each line. Any ASCII input should be acceptable.
> 6 votes

# Answer
# MATL, ~~26~~ ~~24~~ ~~22~~ 16 bytes

**Forward**

```
DPEXSt'><}{][)('

```

Try it Online!

Explanation:

```
                % Implicitly grab the input as a string
D               % Pop the top of the stack and display it
P               % Tries to flip the top element on the stack but errors out
                % because the stack is empty. Program terminates.
EXSt'><}{][)('  % Not executed

```

---

**Normal reversion:**

```
'()[]{}<>'tSXEPD

```

Try it Online!

Explanation:

```
            % Implicitly grab input as a string
'()[]{}<>'  % String literal (search string)
tS          % Duplicate and sort to create the replacement string: '()[]{}<>'
XE          % Replace all entries in the input using the search and replacement strings.
            % Corresponding characters in the strings are used for the replacement.
            % Effectively a no-op
P           % Flip the string
D           % Explicitly display result

```

---

**Visual reversion:**

```
')(][}{><'tSXEPD

```

Try it Online!

Explanation:

```
            % Implicitly grab the input as a string
')(][}{><'  % String literal (search string)
tS          % Duplicate and sort to create the replacement string: '()[]{}<>'
XE          % Replace all entries in the input using the search and replacement strings.
            % Corresponding characters in the strings are used for the replacement.
P           % Flip the result
D           % Explicitly display the result

```
> 5 votes

# Answer
## GolfScript, ~~32~~ 28 bytes

```
#%{=1-[=-\7?@.`{[(<>)]}.}%1-

```

Try it online!

Normal reversion:

```
-1%}.}])><([{`.@?7\-=[-1={%#

```

Try it online!

Visual reversion:

```
-1%{.{[(<>)]}`.@?7\-=]-1=}%#

```

Try it online!

The fact that an unmatched `}` terminates the program in GolfScript, made this fairly simple. However, I'm pretty sure that my code for swapping the brackets isn't optimal yet.
> 3 votes

# Answer
### Python 2.7, 208 bytes

**Forward**

```
import sys#
print''.join(sys.stdin)#
#0:tpecxe
#"]1-::[)nidts.sys(nioj.'' tnirp"cexe:yrt
#0:tpecxe
#"(('<>{}[]()','><}{][)(')snartekam.s)etalsnart.[1-::](nidts.sys)nioj.'' tnirp"cexe:yrt
#s sa gnirts,sys tropmi

```

**Normal reversion**

```
import sys,string as s#
try:exec"print''.join)sys.stdin(]::-1[.translate)s.maketrans)'()[]{}<>',')(][}{><'(("#
except:0#
try:exec"print''.join(sys.stdin)[::-1]"#
except:0#
#)nidts.sys(nioj.''tnirp
#sys tropmi

```

https://eval.in/574639

**Visual reversion**

```
import sys,string as s#
try:exec"print''.join(sys.stdin)[::-1].translate(s.maketrans(')(][}{><','()[]{}<>'))"#
except:0#
try:exec"print''.join)sys.stdin(]::-1["#
except:0#
#(nidts.sys)nioj.''tnirp
#sys tropmi

```

https://eval.in/574638

All directions read from stdin until EOF.

Nothing super clever here. Trailing comments to only execute the forward vs the backward code, then an `exec` statement in a try block to catch syntax errors for the two different reversions.
> 0 votes

---
Tags: code-golf, string, source-layout
---


title: Locate and rotate

text:
# Question
Title: Locate and rotate
## The task

This is a simple challenge. Your input is a single non-empty string, containing only digits `0123456789` and hashes `#`. It will contain exactly one run of digits, which encodes a nonnegative integer and may wrap around the end of the string, and at least one `#`. The integer may have leading zeroes. For example, `##44##`, `013####` and `23###1` are valid inputs, while `###`, `0099` and `#4#4` are not.

Your task is to extract the integer `n` from the string, and output the string rotated `n` steps to the right.

## Examples

* The input `#1##` should be rotated 1 step to the right, so the correct output is `##1#`.
* The input `#026###` should be rotated 26 steps to the right, since the leading 0 is ignored. The correct output is `26####0`.
* The input `1####2` contains the integer 21 wrapped over the end, so it should be rotated 21 steps to the right. The correct output is `##21##`.

## Rules and scoring

You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.

You can assume that the number `n` fits into the standard `int` type of your language. Conversely, if that standard `int` type implements arbitrary-precision integers, you must support (in theory) an arbitrarily large `n`.

## Test cases

```
#1## -> ##1#
##4## -> #4###
1####1 -> ####11
1####2 -> ##21##
#026### -> 26####0
#000### -> #000###
###82399 -> ##82399#
51379#97 -> #9751379
#98##### -> ###98###
#######4## -> #4########
60752#1183 -> 8360752#11
####99366800## -> 366800######99
########9##### -> ###9##########
91#####515694837 -> 1#####5156948379
###6114558###### -> #6114558########
######219088736090042#### -> 9088736090042##########21
#46055080150577874656291186550000138168########### -> 0138168############4605508015057787465629118655000
568375993099127531613012513406622393034741346840434468680494753262730615610086255892915828812820699971764142551702608639695081452206500085233149468399533981039485419872101852######################3680 -> 99533981039485419872101852######################36805683759930991275316130125134066223930347413468404344686804947532627306156100862558929158288128206999717641425517026086396950814522065000852331494683

```

# Answer
> 10 votes
# CJam, 11 bytes

```
q_'#%W%sim>

```

Try it online! or verify all test cases.

Note that this won't work for the last two test cases, since the involved numbers don't fit into 64 bits.

### How it works

```
q_          e# Read all input and push it twice.
  '#%       e# Split at runs of '#'.
     W%     e# Reverse the resulting array.
       si   e# Cast to string, then to int.
         m> e# Rotate the original input that many places to the right.

```

# Answer
> 7 votes
# Julia, ~~71~~ 65 bytes

```
s->join(circshift([s...],maximum(parse,split(s*s,"#",keep=1<0))))

```

This is an anonymous function that accepts a string and returns a string. To call it, assign it to a variable.

We append the input to itself, split it into an array with `#` as the separator, parse each integer, and take the maximum. This defines the number of times we shift the string to the right. We splat the string into a `Char` array, shift, and `join` it back together.

# Answer
> 7 votes
# Python, 66 bytes

```
lambda l:(2*l)[-int(''.join(l.split('#')[::-1]))%len(l):][:len(l)]

```

# Answer
> 5 votes
# Retina, ~~65~~ ~~57~~ 49

```
(\d*)#*(\d+)
$2$1 $0
^\d+
$*
+`1 (.*)(.)
 $2$1
<space>

```

Saved 8 bytes thanks to Martin!

Try it Online!

Note that this will time out / run out of memory for the very large test cases online, and on most sane machines, for some of the larger ones.

This takes the last number in the string and the first or no number in the string and puts them in front of the string. Then it converts that combined number to unary and repeatedly rotates while dropping a unary digit.

# Answer
> 3 votes
# Jelly, ~~12~~ 10 bytes

```
ẋ2~ṣ0‘ḌṂṙ@

```

Try it online! or verify all test cases.

### Background

Say the input is `51379#97`.

By repeating the string twice (`51379#9751379#97`), we can make sure that it will contain a contiguous representation of the number.

Next, we apply bitwise NOT to all characters. This attempts to cast to int, so **'1'** gets evaluated to **1**, then mapped to **~1 = -2**. On failure (`#`), it returns **0**.

For our example, this gives

```
[-6, -2, -4, -8, -10, 0, -10, -8, -6, -2, -4, -8, -10, 0, -10, -8]

```

Next, we split at zeroes to separate the part that encodes the number from the rest.

```
[[-6, -2, -4, -8, -10], [-10, -8, -6, -2, -4, -8, -10], [-10, -8]]

```

Bitwise NOT maps **n** to **-n - 1**, so we increment each to obtain **-n**.

```
[[-5, -1, -3, -7, -9], [-9, -7, -5, -1, -3, -7, -9], [-9, -7]]

```

Next, we convert each list from base 10 to integer.

```
[-51379, -9751379, -97]

```

The lowest number is the negative of the one we're searching for. Since Jelly list rotation atom  rotates to the *left*, this avoid multiplying by **-1** to rotate to the right.

### How it works

```
ẋ2~ṣ0‘ḌṂṙ@  Main link. Input: S (string)

ẋ2          Repeat the string twice.
  ~         Apply bitwise NOT to all characters.
            This maps 'n' to ~n = -(n+1) and '# to 0.
   ṣ0       Split at occurrences of zeroes.
     ‘      Increment all single-digit numbers.
      Ḍ     Convert each list from base 10 to integer.
       Ṃ    Take the minimum.
        ṙ@  Rotate S that many places to the left.

```

# Answer
> 3 votes
# MATL, ~~28~~ ~~25~~ ~~17~~ 16 bytes

```
!G1Y4XXPZcXvUYS!

```

*8 bytes less borrowing Dennis' idea of splitting the array and reversing the order of the pieces*

The two last test cases don't work because the number is too large.

*EDIT (May 20, 2016) The code in the link uses `Xz` instead of `Xv`, owing to recent changes in the language.*

**Try it online!**

```
!         % take implicit input: string. Transpose into column char array
G         % push input string again
1Y4       % predefined literal '\d' (for regexp)
XX        % match regexp. Gives cell array with 1 or 2 strings
P         % flip that array
ZcXv      % join the strings in that array, without spaces
U         % convert to number
YS        % rotate the transposed input that many times
!         % put back into row form (string). Implicitly display

```

# Answer
> 2 votes
## PowerShell, 153 bytes

(But see the Extra Credit section, below)

```
param($a)$d=[System.collections.arraylist][char[]]$a;for($b=+("$a$a"-split"#"-ne'')[1];$b;$b--){$r=$d[-1];$d.removeAt($d.Count-1);$d.insert(0,$r)}-join$d

```

PowerShell doesn't have the concept of "shifting" an array, so I had to roll my own solution. Will take a *long* time for larger numbers, but it should eventually complete anything that fits in a 32-bit int.

Takes input `$a`, and sets a new variable `$d` as a \[System.Collections.ArrayList\] object. This is done because, technically, arrays in PowerShell are immutable (further explained below in Extra Credit), and thus don't support arbitrary insertions or removals, which is needed for shifting. Then, we enter a `for` loop.

The initial condition is a trick I found -- if we concatenate the input together, split on `#`, and ignore empties, the second element of the resulting array will be equal to our number, regardless of wrapping. We set that to `$b`, and decrement `$b` each time until it's zero.

Each iteration, we set helper `$r` as the last element in the arraylist, remove that last element, and then insert the element onto the front ... effectively "shifting" the array to the right by one element.

Finally, we simply output with `-join$d` so that it's concatenated into one string.

---

### Extra Credit

If the problem was shifting the array *left* instead of *right*, we can do it significantly shorter using *multiple assignment*. Basically, "If the assignment value contains more elements than variables, all the remaining values are assigned to the last variable."

In essence, this means something like `$c=@(1,2,3)` and `$a,$b=$c`
will have `$a=1` an int and `$b=@(2,3)` an array.

### PowerShell, 90 bytes, does a left shift instead of a right shift

```
param($a)$b=+("$a$a"-split"#"-ne'')[1];$a=[char[]]$a;for(;$b;$b--){$r,$a=$a;$a+=$r}-join$a

```

Here we once again take input, and set `$b` as above. We re-cast `$a` as a char-array, and then enter the same `for` loop as above. This time, though, we've not needed to support arbitrary removal/insertion, so we don't need to use the costly `[System.Collections.ArrayList]` object, nor the expensive method calls. Instead we simply set `$r` to be the first element of `$a`, and the remaining elements are re-saved in `$a`. Then we `+=` to tack it back on to the end.

*(As I said, PowerShell arrays are technically immutable, but the `+=` operator here is overloaded - it takes an array and another object, mushes them together (technical term) into a new array, returns that and saves it as the variable name, and destroys the original array. Functionally, we've just added an element to the end of the array, but technically (and from a memory/garbage-cleanup perspective, etc.) it's a brand-new array. This can obviously become a costly operation if the array is large or complex. The flipside is that, since arrays are immutable, indexing into them or iterating over them is very cheap.)*

Output remains the same action, with a `-join` statement to turn it into a single string.

# Answer
> 1 votes
# Pyth, ~~22~~ 14 bytes

```
.>zs-.<zxz\#\#

```

Try it here!

### Explanation

```
.>zs-.<zxz\#\#    # z=input

     .<z          # rotate z left by
        xz\#      # index of the first occurence of a hash
                  # this ensures that the integer is not wrapped around the end
    -       \#    # filter all hashes out
   s              # cast to an integer, also removes leading zeroes
.>z               # do the final roation of the input string and print it

```

This works for all testcases and also almosts finishes instantly for the very big numbers.

# Answer
> 1 votes
## Seriously, 21 bytes

```
,;;+'#@s`≈`MM@#@`/`nΣ

```

Try it online!

Warning: this solution is very inefficient, so the larger test cases will time out on TIO. Use the local interpreter.

Explanation:

```
,;;+'#@s`≈`MM@#@`/`nΣ
,;;+                   make 3 copies of input, and concatenate two of them
    '#@s               split on #s
        `≈`MM          convert strings to ints, take maximum
             @#@       explode final copy of input
                `/`n   rotate to the right n times
                    Σ  join

```

# Answer
> 1 votes
## JavaScript (ES6), ~~67~~ 64 bytes

```
s=>(l=s.length,s+s).substr(l-s.split(/#+/).reverse().join``%l,l)

```

Another port of Dennis's CJam answer.

Edit: Saved 3 bytes by appropriating the part of edc65's answer that he didn't draw attention to.

# Answer
> 1 votes
# Mathematica, 69 Bytes

```
#~StringRotateRight~ToExpression[""<>Reverse@TextCases[#,"Number"]]&

```

Find sequences of numbers in the, if there are 2 then their order needs to be reversed. Concatenate the strings (if it's only one it just returns the number string). Convert string to numeric and rotate the string that number of times.

# Answer
> 1 votes
# JavaScript (ES6) 66

For once, the stupid negative `%` of javascript for negative numbers come useful

```
z=>(z+z).substr(-(l=z.length,[a,b]=z.match(/\d+/g),b?b+a:a)%l-l,l)

```

# Answer
> 1 votes
# Pyth, 10 bytes

```
.>zss_cz\#

```

Try it online. Test suite.

This is a translation of Dennis' CJam answer. I'm making it a community wiki, since I didn't come up with it.

### Explanation

```
      cz\#   split input at #
     _       reverse
    s        join
   s         cast to integer
.>z          rotate input right

```

# Answer
> 1 votes
# Perl 5, 41 bytes

39 bytes plus two for the `-lF` flags (`-M5.01` is free): `perl -lF -M5.01 script.pl`

```
/#+/;map{unshift@F,pop@F}1..$'.$`;say@F

```

Explanation:

* `-lF` reads the input, removes the trailing newline, puts the remainder into the string `$_`, splits it up into characters, and puts that split into the array `@F`.
* `/#+/` finds the first string of `#`s in `$_` and sets `$`` equal to the stuff before it and `$'` equal to the stuff after it. If `$`` is empty then `$'` may contain more `#`s. However, `$'.$`` is a string whose initial substring is the number of times to rotate the array.
* Now we build the list `1..$'.$``, which treats `$'.$`` as an integer and thus numifies it, which strips any final `#`s, so the list is from `1` to the number of times to rotate the array.
* For each element in that list, we rotate the array (`pop` the last element and `unshift` it onto the beginning).
* Then `say` all the elements of the rotated array.

# Answer
> 1 votes
# Ruby - ~~68~~ ~~72~~ 70 bytes

```
s=ARGV[0]
p s.split(//).rotate(-(s+s).scan(/\d+/).map(&:to_i).max)*""

```
* `split` converts string into an array
* `(s+s).scan(/\d+/)` concatenate string to itself and get an array of numbers (as strings)
* `map(&:to_i)` convert strings to ints
* `max` pick the largest int
* `rotate` `max` times
* `*""` convert the array back into a string (shorthand for `join`)

Usage : `ruby scriptname.rb "[string]"`

# Answer
> 0 votes
# 05AB1E, ~~14~~ 13 bytes

Well, the code is very unlikely to terminate for the numbers bigger than 100000, but if you're patient enough, there will be an output :). Code:

```
'#¡rJ¹sF¤rS\J

```

Explanation:

```
'#¡             # Split the input on '#'
   r            # Reverse the stack
    J           # Join the stack
     ¹          # Take the first input
      s         # Swap with the number
       F        # For N in range(0, number), do...
        ¤       #   Obtain the last character
         r      #   Reverse the stack
          S     #   Split everything to individual characters
           \    #   Delete the last character
            J   #   Join the stack

```

Try it online!

Uses **CP-1252** encoding

# Answer
> 0 votes
# Mathematica, ~~73~~ 58 bytes

```
#~StringRotateRight~Max[FromDigits/@StringSplit[#<>#,"#"]]&

```

Much byte. *15* *bytes* *saved* *thanks* *to* *IPoiler*

# Answer
> 0 votes
**VBSCRIPT, 82  99 BYTES**

previous code didn't handle cases with number wrapped over the end

```
b=len(a):f=replace(a,"#","/",1,1):c=replace(split(f&f,"/")(1),"#",d) mod b:d=right(a,c)&left(a,b-c)

```

UNGOLFED

```
b=len(a)                                 -a->implicit input, get its length
f=replace(a,"#","/",1,1)  -replace first instance of # so we can split later
c=replace(split(f&f,"/")(1),"#",d) mod b    -get the number and calc the mod
d=right(a,c)&left(a,b-c)                    -d->implicit output

```

this kinda sucks ... there's probably a better way to do it, even in VBscript

# Answer
> 0 votes
## matlab~~(86)~~72

```
 @(n)circshift(n,[0 str2num(circshift(n(n~='#'),[0,-find(n=='#',1)+1]))])

```
* The function totates the string two times, once for integer extraction, second for the desired task, it doesnt take too much time because matlab proceeds to rotate by `(Dim)modulus(Length)` to the exception that it falls in segmentation failure for bigger ranges.
* Will struggle how to golf it more ....

---

## (86)

```
  @(n)circshift(n,[0 str2num([strtok(n(find(n=='#',1,'last'):end),'#') strtok(n,'#')])])

```
* The difference between this function and the previous, this one does concatenate two distant occurences of integers way backwards, while the first one just rotates it.

# Answer
> 0 votes
## Matlab(73)

```
  @(a)regexprep(a,'(\d*)#*(\d*)#*','${circshift($0,[0 str2num([$2 $1])])}')

```
* This is using another approach that i wonder if @luis used it, because refering to his description there is some points in common while (un)?fortunately i dont understand the cropped Matl language.

---
Tags: code-golf, string, parsing
---


title: How should you arrange your chairs?

text:
# Question
Title: How should you arrange your chairs?
You teach a class of students with interesting preferences for how their chairs are arranged. There are 3 very specific requirements they have for how the chairs are arranged:

1. They most be arranged in a rectangle, even if it means some chairs go empty.
2. There must be as few empty chairs as possible.
3. They must be as "squarey" as possible. Squarey-ness is determined by the distance between the width and the height of the rectangle, lower is better. For example, a rectangle that is `4x7` has a squarey-ness of 3.

To be more specific, the "score" of an arrangement is the distance between the width and height plus the number of chairs that would go empty.

Let's take an example. Let's say you have 13 students. You could arrange the chairs any of these ways:

```
1x13
2x7
3x5
4x4

```

`1x13` is not very squarey. In fact, 1 and 13 are 12 apart, so we give this arrangement 12 points. It also has 0 empty chairs, so we add 0 points, giving this arrangement a score of 12. Not that great.

`2x7` is certainly better. 2 and 7 are only 5 apart, so we give this arrangement 5 points. However, if you actually arranged 2 rows of seven chairs, that would take 14 chairs, meaning one chair would be empty. So we add one point, giving this arrangement a score of 6.

We could also do `3x5`. 3 and 5 are 2 apart, so +2 points. It takes 15 chairs, meaning we'd have two extra chairs, so another +2 points, for a score of 4.

Last option, `4x4`. 4 and 4 are 0 apart, so we give this +0 points. 4x4 takes 16 chairs, so 3 chairs go empty, for a total score of 3. This is the optimal solution.

In case of a tie, the optimal solution is the one with less empty chairs.

# The challenge

You must write a program or function that takes an integer and outputs the optimal arrangement of chairs for that number of students. IO can be in any reasonable format. Here is sample output for any number of students from 1 to 100:

```
1:  (1, 1)
2:  (1, 2)
3:  (2, 2)
4:  (2, 2)
5:  (2, 3)
6:  (2, 3)
7:  (3, 3)
8:  (3, 3)
9:  (3, 3)
10: (2, 5)
11: (3, 4)
12: (3, 4)
13: (4, 4)
14: (4, 4)
15: (4, 4)
16: (4, 4)
17: (3, 6)
18: (3, 6)
19: (4, 5)
20: (4, 5)
21: (3, 7)
22: (5, 5)
23: (5, 5)
24: (5, 5)
25: (5, 5)
26: (4, 7)
27: (4, 7)
28: (4, 7)
29: (5, 6)
30: (5, 6)
31: (4, 8)
32: (4, 8)
33: (6, 6)
34: (6, 6)
35: (6, 6)
36: (6, 6)
37: (5, 8)
38: (5, 8)
39: (5, 8)
40: (5, 8)
41: (6, 7)
42: (6, 7)
43: (5, 9)
44: (5, 9)
45: (5, 9)
46: (7, 7)
47: (7, 7)
48: (7, 7)
49: (7, 7)
50: (5, 10)
51: (6, 9)
52: (6, 9)
53: (6, 9)
54: (6, 9)
55: (7, 8)
56: (7, 8)
57: (6, 10)
58: (6, 10)
59: (6, 10)
60: (6, 10)
61: (8, 8)
62: (8, 8)
63: (8, 8)
64: (8, 8)
65: (6, 11)
66: (6, 11)
67: (7, 10)
68: (7, 10)
69: (7, 10)
70: (7, 10)
71: (8, 9)
72: (8, 9)
73: (7, 11)
74: (7, 11)
75: (7, 11)
76: (7, 11)
77: (7, 11)
78: (9, 9)
79: (9, 9)
80: (9, 9)
81: (9, 9)
82: (7, 12)
83: (7, 12)
84: (7, 12)
85: (8, 11)
86: (8, 11)
87: (8, 11)
88: (8, 11)
89: (9, 10)
90: (9, 10)
91: (7, 13)
92: (8, 12)
93: (8, 12)
94: (8, 12)
95: (8, 12)
96: (8, 12)
97: (10, 10)
98: (10, 10)
99: (10, 10)
100: (10, 10)

```

As usual, this is code-golf, so standard loopholes apply, and the winner is the shortest answer in bytes.

# Answer
> 8 votes
# Jelly, ~~16~~ ~~15~~ 14 bytes

```
÷RĊ,Rµạ/+PỤḢịZ

```

Try it online! or verify all test cases.

### How it works

```
÷RĊ,Rµạ/+PỤḢịZ  Main link. Argument: n

 R              Range; yield [1, ..., n].
÷               Divide n by each k in [1, ..., n].
  Ċ             Ceil; round the quotients up to the nearest integer.
    R           Range; yield [1, ..., n].
   ,            Pair; yield A := [[ ⌈n ÷ 1⌉, ..., ⌈n ÷ n⌉ ], [ 1, ..., n ]].
     µ          Begin a new, monadic chain. Argument: A
      ạ/        Reduce A by absolute difference.
                This yields [ |⌈n ÷ 1⌉ - 1|, ..., |⌈n ÷ n⌉ - n| ].
         P      Product; reduce A by multiplication.
                This yields [ ⌈n ÷ 1⌉ × 1, ..., ⌈n ÷ n⌉ × n].
       +        Add the results to left and right, element by element. This yields
                [ |⌈n ÷ 1⌉ - 1| + ⌈n ÷ 1⌉ × 1, ..., |⌈n ÷ n⌉ - n| + ⌈n ÷ n⌉ × n ].
          Ụ     Grade up; sort the indices of the list of sums by their values.
           Ḣ    Head; extract the first value, which corresponds to the smallest
                sum. Grading up is stable, so this selects the first index of all
                with the smallest sum in case of a tie. In this event, the first
                index will have the highest absolute difference of all indices
                with the smallest sum, meaning that it has the lowest product and,
                therefore, the lowest number of empty chairs.
             Z  Zip; transpose A's rows and columns.
                This yields [[ ⌈n ÷ 1⌉, 1 ], ..., [ ⌈n ÷ n⌉, n ]].
            ị   Retrieve the pair at that index.

```

# Answer
> 4 votes
# Python 2, 68 bytes

```
lambda n:min((abs(~i-n/~i)+n/~i*~i,i+1,0-n/~i)for i in range(n))[1:]

```

Equivalent to the more “obvious”:

```
lambda n:min([(i+1,0-n/~i)for i in range(n)],key=lambda(p,q):abs(p-q)+p*q)

```

# Answer
> 3 votes
## Haskell, 65 bytes

```
f x=snd$minimum[((a*b+a-b,a*b),(b,a))|a<-[1..x],b<-[1..a],a*b>=x]

```

Usage example: `map f [1..5]` -\> `[(1,1),(1,2),(2,2),(2,2),(2,3)]`.

Goes through an outer loop `a` from `1` to `x` (x -\> number of students) and an inner loop `b` from `1` to `a`. Keeps all `(b,a)` where `a*b>=x` and builds pairs of `((arrangement points,seats left), (b,a))` which follow the lexicographical order we need to find the minimum. Note: `a` is always greater than `b`, so we don't need `abs` for squareyness. No need to subtract `x` from the "seats left" score, because only the relative order matters. Finally we remove the score pair with `snd`.

# Answer
> 3 votes
## Javascript, 98 bytes

My first code golf, so I post anyway!

```
f=n=>{for(o=1/0,i=1;i<=n;i++)for(j=n;i*j>=n;j--)t=i*j-n+Math.abs(i-j),o>t&&(o=t,a=[i,j]);return a}

```

Initially my `o` was an empty object and I checked if `o.a` was empty, so it was a special case at the first round. But I found the 1/0 trick in edc65's answer to initialize the variable to Infinity.

# Answer
> 2 votes
# MATL, 18 bytes

```
:Gy/Xkvtd|yp+&X<Z)

```

**Try it online!**

### Explanation

```
:      % Implicit input number N. Range [1 2 ... N]
G      % Push N again
y      % Duplicate second-from-top: push [1 2 ... N] again
/Xk    % Divide and round up
v      % Vertically concatenate. Gives 2×N array of rectangle sizes
td|    % Duplicate. Absolute difference of each column
y      % Duplicate second-from-top: push 2×N array again
p      % Product of each column
+      % Sum absolute differences and products
&X<    % Arg min
Z)     % Use as column index into the 2×N array. Implicitly display

```

# Answer
> 2 votes
# Ruby, 64 bytes

```
->n{(1..n).map{|w|h=(n+w-1)/w;[(h-w).abs+h*w,w*h,w,h]}.min[2,3]}

```

A lambada that takes the number of people as an argument and returns an array with width and height of the optimal solution.

# Answer
> 1 votes
# Pyth, ~~24~~ ~~22~~ 21 bytes

**Edit**: in the sorting key, I realize that there is no need to find the number of empty chairs. It is equivalent to score the total number of chairs. This saved me 2 bytes.

```
h.m_+B*FbaFbm,d.EcQdS

```

Try it online!

# Answer
> 1 votes
# Matlab~~(174)(146)~~121

```
  function g(n),f=@(n,i)ceil(n/i);x=[];for i=1:n,x=[sortrows(x); f(n,i)*i-1/(f(n,i)*i)+abs(f(n,i)-i) i f(n,i)];end,x(1,2:3)

```
* **trick 1:** i added the amount `1-1/length*width` as tie-scoring
* **trick 2:** i calculated `number_students/length` ceiled for the width of rectangle, ~~upper bound is the square but ceiled too~~
* I'm sure it can be golfed further ...

try it

---

**Edit :** referenced to @StewieGriffin 's remarks .

**Edit 2 :**

* `1` and `n` are constants no need to add 'em to the overall score.
* A function is few bytes less than stdin standalone program.
* I used ascendent sorting technique it saves too much bytes though.

**Edit 3:** peformance test.

# Answer
> 1 votes
# JavaScript (ES6) 74 ~~78~~

*Edit* keeping the temp result as an array instead of 2 vars, borrowed from Thiht's answer

```
n=>(z=>{for(x=0;y=-~(~-n/++x),x<=y;)(s=y-x+x*y-n)>=z||(z=s,r=[x,y])})()||r

```

*Less golfed*

```
n=>{
  z = 1/0
  for (x=0; y=(n-1)/++x+1|0, x <= y; )
  {
    s = y-x+x*y-n;
    if (s<z)
      z=s, r=[x,y]
  }
  return r
}

```

**Test**

```
f=n=>(z=>{for(x=0;y=-~(~-n/++x),x<=y;)(s=y-x+x*y-n)>=z||(z=s,r=[x,y])})()||r

out=x=>O.textContent+=x+'\n'

for(i=1;i<=100;i++)out(i+' :( '+f(i)+' )')
```

```
<pre id=O></pre>
```

# Answer
> 1 votes
# Julia, ~~61~~ ~~59~~ ~~55~~ ~~53~~ 52 bytes

```
/ =cld
n->[m=indmax([~i*~-max(i,n/i)for i=1:n]),n/m]

```

Try it online!

### How it works

The code is equivalent to the following, ungolfed version, where `cld` is ceiling division.

```
function chairs(n)
    m = indmin([(i + 1) * (max(i, cld(n, i)) - 1) for i in 1:n])
    return [m, cld(n, m)]
end

```

To find the optimal arrangement, it is clearly sufficient to examine the pairs **\[i, j\]**, where **1 ≤ i ≤ n** and **j = ⌈n / i⌉**.

The score for such an arrangement is **|j - i| + (ij - n)**, where the second summand is the number of empty chairs. Instead of the actual scores, we can compare scores augmented by a constant, such as **ij + |j - i| + 1**.

It is sufficient to consider pairs **\[i, j\]** where **i ≤ j** since the arrangements **\[i, j\]** and **\[j, i\]** are equally valid. We deal with strictly descending pairs by setting **j = max(⌈n / i⌉, i)** instead, which makes sure that **j ≥ i** and will yield a suboptimal score if **⌈n / i⌉ \< i**.

Since **j - i ≥ 0**, we have **ij + |j - i| + 1 = ij + j - i + 1 = (i + 1) × (j - 1)**, which can be computed in fewer bytes of code.

Finally `indmin` / `indmax` gives the index **m** (and thus the value of **i**) of the optimal arrangement, which is **m** by **⌈n / m⌉**. Ties are broken by first occurrence, which corresponds to the lowest value of **i**, therefore the highest value of **j - i** and thus the lowest value of **ij - n** (empty chairs).

# Answer
> 1 votes
# Python 2, 64 bytes

```
lambda n:max((~-i*~min(i,n/i),0-n/i,-i)for i in range(-n,0))[1:]

```

This is an amalgamation of @Lynn's Python answer (from where I took the `max(...)[1:]` trick) and the algorithm from my Julia answer (which allows a slightly shorter implementation).

Test it on Ideone.

# Answer
> 1 votes
## PHP, 129 bytes

```
function f($i){$s=INF;for($x=1;$x<$i;$x++){if($s>$t=(abs($x-$e=ceil($i/$x))-$i+($e*$x))){$s=$t;$d[0]=$x;$d[1]=$e;}}var_dump($d);}

```

Ungolfed:

```
function f ($i){
    $s=INF;
    for($x=1; $x<$i; $x++){ // for every number less than the input
        if( $s > $t=( abs($x-$e=ceil($i/$x))-$i+($e*$x) ) ){
            // determine the other dimension, the score, and compare to the minimum score
            $s=$t;
            $d[0]=$x;
            $d[1]=$e;
        }
    }
    var_dump($d);
}

```

# Answer
> 1 votes
# PHP, 104 bytes

The algorithm that solves this problem is simple and it is probably used by other answers in languages similar to PHP (JavaScript, f.e.):

* start with a large value for the initial score; `n` is large enough (where `n` is the input value); the score of the arrangement computed on the first iteration (`1, n`) is `(n-1)+0`;
* iterate for all values of width between `1` and `n`; compute the minimum height as `ceil(n/width)`, compute the arrangement score using the formula provided in the question (i.e. `abs(width - height) + (width * height - n)`); if the score is better than the previous best score then remember the width, the height and the new best score; on ties use the value of `width * height - n` for current arrangement and previous best arrangement to detect the new best arrangement;
* that's all.

After golfing, this algorithm produces something like this (wrapped here for readability):

```
for($s=$h=$j=$n=$argv[$w=$i=1];$i<=$j;$j=ceil($n/++$i)
{$c=$j-$i+$i*$j-$n;if($c<$s||$c==$s&&$i*$j<$w*$h){$w=$i;$h=$j;$s=$c;}}
echo"$w,$h";

```

It uses **137 bytes** (when put on a single line) and it is far from the 104 bytes advertised in the title. The code can probably be shortened by another 2-3 bytes but the big source of improvement is somewhere else: in the details of the algorithm.

## The revised algorithm:

There are several places where the algorithm can be improved by removing useless code.

* there is no need to iterate the width from `1` to `$n`; for speed, the width (`$i`) must iterate between `1` and `floor(sqrt($n))` but this makes the code even longer instead of shortening it; but if the width doesn't exceed `sqrt($n)`, the minimum height (`$j`) will always be larger than `sqrt($n)` (their product must be at least `$n`);
* the previous statement allows using `$i <= $j` (width \<= height) as the termination condition for loop; this way, the width will iterate from `1` to `floor(sqrt($n))` and the height will get values starting with `$n` and going down to `ceil(sqrt($n))` (not necessarily all of them);
* knowing that width is always smaller than or equal to the height allow us know that `abs(width - height)` is always `height - width` (`$j-$i`); 5 bytes saved this way;
* the input value `$n` is used in the computation of score (the number of unoccupied seats is `width * height - n`) but it is not needed; the score does not need to be displayed, it is computed only for comparison of the arrangements; by removing `- n` from the score formula we save another 3 bytes (the PHP code is `-$n`) without losing anything;
* given the last two statements, the score formula becomes `height - width + width * height` (`$j-$i+$i*$j`);
* on ties (the score of the current arrangement is the same as the previous best score), the rules say to use the arrangement with less free seats; because width always increases and height always decreases, the `height - width` part of the score decreases on each step;
* if the current score is equal with the previous best score, the previous statements tells us that the number of free seats of the current arrangement is larger than the one of the previous best arrangement; this means the previous best arrangement win the tie;
* because the ties are always won by the previous best arrangement, a new arrangement becomes the new best arrangement only when its score is smaller than the previous best; the code that checks for ties is useless and can be removed (`||$c==$s&&$i*$j<$w*$h` -- a lot of bytes);
* because of the removal of `-$n` from the score's formula, the score for the first arrangement (`1x$n`) is `$n-1+1*$n` (i.e. `2*$n-1`); the initial value of the best score (`$s`) can be any value greater than or equal to `2*$n`; the first iteration has a better score and it becomes the best arrangement letting the algorithm run without initialization problems.

The new code (**104 bytes**), after applying the improvements described above is:

```
for($s=2*$j=$n=$argv[$i=1];$i<=$j;$j=ceil($n/++$i))
if($s>$c=$j-$i+$i*$j){$w=$i;$h=$j;$s=$c;}echo"$w,$h";

```

It is wrapped here for readability. Prepend the code above with the PHP marker `<?php` (technically, it is not part of the code), put it into a file (let's say `arrange-your-chairs.php`) and run it with an integer greater than zero as argument. It will display the width and height of the computed arrangement, separated by comma:

```
$ php arrange-your-chairs.php 1001
28,36

```

### Another solution (116 bytes)

Another solution that uses a different algorithm:

```
for($n=$argv[1];++$j<=$n;)for($i=0;++$i<=$j;)
if($n<=$k=$i*$j)$a["$i,$j"]=($j-$i+$k-$n)*$n+$k;asort($a);echo key($a);

```

It puts all the combinations of at least `$n` seats into an associative list; the key is the text representation of the arrangement, the value is the arrangement's score. It then sorts the list (ascending by value) and gets the key of the first entry.

### One more (115 bytes)

```
foreach(range(1,$m=$n=$argv[1])as$i)
if(($d=ceil($n/$i))<=$i&&$m>=$s=$i*$d-$n+$i-$d){$m=$s;$w=$d;$h=$i;}echo"$w,$h";

```

This is the PHP version of @Neil's answer (JavaScript/ES6, 85 bytes).

There are some noticeable differences due to the features of each language:

* the JS answer generates an array of `n` (undefined) values then uses its keys to iterate from `0` to `n-1`; it increments `i` (`d=(n+i++)/i|0`) to make it iterate from `1` to `n`; the PHP solution doesn't need to increment; it uses `range()` to generate an array then it uses the generated values (`1` to `n`) to iterate;
* the JS answer uses `(n+i)/i` then converts the value to integer using `|0` to get the smallest integer larger than `n/i`; the PHP answer solves this issue easily with the PHP function `ceil()`; JavaScript also provides `Math.ceil()` but it uses 5 bytes more than the solution found by Neil;
* PHP provides the function `array_map()` that is somehow similar with JS `Array.map()` but it doesn't help here; its syntax is verbose, a `foreach` produces shorter code; it is larger than the JS code, though;
* merging the assignments into the conditions using `||` is not possible in PHP because it lacks the comma operator; I translated `a||b||c` into `if(!a&&!b)c` then, because `a` and `b` are comparisons, I negated their operators (replaced `<` with `>=`); this also produces larger code than the JS version;
* another 23 bytes have to be added just because the names of variables in PHP have to be prefixed by `$`.

The ungolfed versions of all solutions and the test suite can be found on Github.

# Answer
> 0 votes
## JavaSCript (ES6), 83 bytes

```
n=>[...Array(m=n)].map((_,i)=>(d=(n+i++)/i|0)>i||(s=i*d-n+i-d)>m||(m=s,r=[d,i]))&&r

```

# Answer
> 0 votes
## Julia, 87

I think this is one step in direction towards finding a *magic function* for the problem:

```
f(i)=(i+n)÷(i+1)|>j->(j*i<n)+j
_=indmin([sqrt(n)<=i?i-f(i)*(1-i):2n for i=1:n])
_,f(_)

```

It only looks at pairs `(i, j=(i+n)/(i+1))` or `(i, j+1)`

# Answer
> 0 votes
# Oracle SQL 11.2, 173 bytes

```
SELECT MIN(x||','||y)KEEP(DENSE_RANK FIRST ORDER BY y-x+(y*x-:1))FROM(SELECT CEIL(LEVEL/:1)x,CEIL(MOD(LEVEL+.1,:1))y FROM DUAL CONNECT BY LEVEL<=:1*:1)WHERE x<=y AND:1<=x*y;

```

Un-golfed

```
SELECT MIN(x||','||y)KEEP(DENSE_RANK FIRST ORDER BY y-x+(y*x-:1))  -- Keeps the minimal score
FROM   (SELECT CEIL(LEVEL/:1)x,CEIL(MOD(LEVEL+.1,:1))y FROM DUAL CONNECT BY LEVEL<=:1*:1) -- Generate x,y combinations
WHERE  x<=y AND :1<=x*y  -- Filters out wrong combinations

```

# Answer
> 0 votes
## Q 58 Bytes

```
{c@d?&/d:+/(-/;*/)@\:+c:{((b<a)?1b)#+(b:-_-x%a;a:1+!x)}x}

```

Lamba that calculates minimal cost for a given value (x) and returns a sequence of two values (width,height)

Adding name to that lambda requires other two char (ex f:{..} instead of {..})

**Test**

```
{..}'1+!100

```

where {..} is the lambda. Read as "applies lambda to each value of 1+first 100 ints" (in other words to each value 1..100)

Generates

```
1 1
2 1
2 2
2 2
3 2
3 2
3 3
3 3
3 3
5 2
4 3
4 3
4 4
4 4
4 4
4 4
6 3
6 3
5 4
5 4
7 3
5 5
..

```

**Explanation**

Nested lamdba `{((b<a)?1b)#+(b:-_-x%a;a:1+!x)}` generates all candidates (widht,height) pairs for x chairs as two sequences (w1 w2 w3 ..; h1 h2 h3 ..) (widths and heights). Read from left to right, but evaluates from right to left

`a:1+!x` generates values 1..x and assign that sequence to a

`-_-` is negate floor negate, and implements ceil (ceil is not a primitive of the language)

`b:-_-x%a` applies ceil to each value of x divided by any item im a, and assign the resulting sequence to b. In other words, b is ceil each x dividedBy each 1..x

`+(b;a)` return a secuence composed of seq a and seq b, an then flips it (the result is a sequence of pair where i-pair contains element i of a and element i of b)

`b<a` compares item by item of b and a, and generates a secuence of logical values (true=1b for each index where b\[i\]

`s?x` returns the first position of item x in sequence s. With `(b<a)?1b` We look for 1b (true value) in sequence resulting of compare b and a, and get first position where b

`n#s` takes n first n items from seq s. We want to discard duplicate pairs, so we stop when first item of a pair \< second item (ex. consider 13,1 but not 1,13).

As a side effect, each pair of the resulting sequence are of decreasing distance between a and b (ex (13 1; 7 2; 5 3; 4 4)

The candidate pair generated by nested lambda are assigned to c. We then flip c (obtains b,a again) and applies two functions to that argument: `*/` multiplies over, and `-/` subtract over. The result of `(-/;*/)@\:+c` is the difference and product of each pair. `+/` is sum over, and calculares final cost. The cost of each patir is assigned to d

&/ is minimum over, so `&/`d is the minimum cost. With `d?&/d` we find the first occurrence of minimum cost in d, and with c@.. we retrieve the pair at that position. As each pair is of decreasing distante between a and n, the first minimum found has the maximum distante betwwen other minimum pairs, so we apply tie rule correctly

---
Tags: code-golf, math
---


title: The confused twister

text:
# Question
Title: The confused twister
The basic idea is to write a program that twists itself, and the twisted version untwists itself. The first program will just be the twisting algorithm described here, and when given its own source code as input, outputs a program that reverses the twisting algorithm.

## How strings are twisted

The twisting algorithm is very simple. Each column is shifted down by its index (col 0 moves down 0, col 1 moves 1, ...). The column shift wraps to the top. It kinda looks like this:

```
a
ba
cba
----
 cba
  cb
   c

```

With everything under the line wrapping to the top. Real example:

```
Original:
\\\\\\\\\\\\
............
............
............

Twisted:
\...\...\...
.\...\...\..
..\...\...\.
...\...\...\

```

(Further examples are here)

## Input

Input is either an array of strings, or a multi-line string. All lines have the same length.

## Output

The (un)twisted string, multi-line output to std-out (or closest alternative).

### Example

I'm not quite sure what this is written in but oh well ;)

```
Twisting:
magic  TwistingAlgo
magic ntwistingAlgo
magicU twistingAlgo

Untwisting:
magic  twistingAlgo
magicUnTwistingAlgo
magic  twistingAlgo

```

# Other notes

* Your first and second program must be in the same language.
* The programs must work for any input, not just itself.
* Your program must have at least 2 rows and 2 columns.

# Answer
> 1 votes
## CJam, 21 bytes

```
qN/zee::m>
zN*z e#: <

```

Test it here.

When you twist it, you get:

```
qN/zee::m<
zN*z e#: >

```

### Explanation

This is based on my CJam answer to the original challenge and works basically the same.

The `e#` is a comment, so we can ignore it and the stuff after it. The means the code boils down to

```
qN/zee::m>zN*z

```

Which is the same as in the previous answer, plus a trailing `z` which just wraps the string in an array but that doesn't affect the output.

Notice that the two rows match up in all columns which are rotated (`N`, `z`, `e`, `:`) except for the last one. That means all the twisting will do is swap `>` and `<` which switches the direction of the column rotation.

# Answer
> 3 votes
# Japt, 63 bytes

```
Uy m@XsV=(Y*Xl +Y %Xl)+X¯V}R y;
Uy m@XsV=(Y*Xl -Y %Xl)+X¯V}R y;

```

Twisted:

```
Uy m@XsV=(Y*Xl -Y %Xl)+X¯V}R y;
Uy m@XsV=(Y*Xl +Y %Xl)+X¯V}R y;

```

Test it online: Original, Twisted

### How it works

I hadn't posted yet on the original twisting challenge, but the shortest answer I could come up with is 31 bytes:

```
Uy m@XsV=(Y*Xl -Y %Xl)+X¯V}R y;

```

The untwisting algorithm I came up with is a lot shorter:

```
Uy m@XsV=Y%Xl)+X¯V}R y;

```

However, this won't work very well when intertwined with the other program. Fortunately, there's a way to make the two more similar:

```
Uy m@XsV=(Y*Xl -Y %Xl)+X¯V}R y;
Uy m@XsV=(Y*Xl +Y %Xl)+X¯V}R y;

```

Now all that's different between the two is the `+`/`-`, which is already properly aligned to switch places when twisted!

```
Uy m@XsV=(Y*Xl -Y %Xl)+X¯V}R y;
Uy        // Transpose rows and columns in U.
m@     }R // Map each item X and index Y in the result, split at newlines, to:
Y*Xl -Y   //  Take Y times X.length and subtract Y.
%Xl)      //  Modulate the result by X.length.
XsV=      //  Set V to the result of this, and slice off the first V chars of X.
+X¯V      //  Concatenate this with the first V chars of X.
y;        // Transpose the result again.
          // Implicit: output *last* expression

```

# Answer
> 2 votes
## Haskell, 235 bytes

```
main=interact$unlines.g.lines;g l@("":_)=l; g l|t<-tail<$>l,n<-length t=zipWith(:)(head<$>l)$ g$take n$drop(n-1)$t++t
maim=interact$unlines.h.lines;h l@("":_)=l; h l|t<-tail<$>l,n<-length t=zipWith(:)(head<$>l)$ h$take n$drop(2-1)$t++t

```

and twisted by itself:

```
maim=interact$unlines.g.lines;g l@("":_)=l; g l|t<-tail<$>l,n<-length t=zipWith(:)(head<$>l)$ g$take n$drop(n-1)$t++t
main=interact$unlines.h.lines;h l@("":_)=l; h l|t<-tail<$>l,n<-length t=zipWith(:)(head<$>l)$ h$take n$drop(2-1)$t++t

```

This is a full program. Both lines are mostly the same so that they are not messed up. The differences are:

```
normal  twisted
=================================
main=   maim=     -- after twisting the second lines defines the main function
maim=   main=     -- the other defines an unused function maim

g       g         -- As I cannot define a function (say f) multiple times,
h       h         -- I need different names for the function in both lines

n-1     n-1       -- this is for the different functionalities (twisting up /
2-1     2-1       -- twisting down). When calling g/h recursively I go with the
                  -- rest of each input line. To twist down, I drop (length n) -1
                  -- chars of two copies of the line. To twist up, I drop 2-1 chars
                  -- Then cut to the original length.
                  --
                  -- e.g.  2222    two     2222    twist   4444    twist   3333
                           3333    copies  3333    down    2222    up      4444
                           4444            4444    ->      3333    ->      2222
                                           2222    drop 2          drop 1
                                           3333
                                           4444

```

---
Tags: code-golf, string, source-layout
---


title: Judge Some Titrations

text:
# Question
Title: Judge Some Titrations
In chemistry class, we were learning about titrations, and attempting one as a lab. We were using phenolphthalein as the indicator for the titration, so on top of grading the lab normally, my teacher held a little contest to see who had the lightest shade of pink, and thus the most accurate transition.

Your task is to write a program that acts like the teacher and judges the titrations.

# Specs

As input, you take a list of RGB triples in any sane format representing the titration of each student. ex: `["D966FF", "ECB3FF", "AC00E6"]`. You will be guaranteed that if converted to HSL, the hue is `285` and the saturation is `100`.

The conversion for RGB to HSL lightness is the average of the max and min of the normalized RGB components (`*100` for a percentage).

Now the teacher is a human being and therefore cannot measure the lightness of the solution perfectly, so before you do any of the things described below, randomly change the lightness value of each of the titrations by `±3`, uniformly distributed.

If a titration has a lightness value greater than `94`, it is too light to visibly see that all the acid has neutralized. Therefore, the first output is a list, sorted in descending order, of all the titrations whose RGB triples, when converted to HSL, yield a lightness value less than 94. This represents the results of the contest.

The other output is a list of all the people who have failed the lab. This includes the people with the lightness values greater than `94`, but also people whose lightness values are less than or equal to `65` because these people's titrations are too inaccurate.

This is , so shortest code in **bytes** win.

# Test Cases

*These test cases all assume that the error is always 0 for ease in checking if your program is correct. The results from your program should be different each time you run it.*

```
["D966FF", "ECB3FF", "AC00E6"] -> ["ECB3FF", "D966FF", "AC00E6"], ["AC00E6"]
["EDB8FF", "D761FF", "9100C2", "FBEFFF"] -> ["EDB8FF", "D761FF", "9100C2"], ["FBEFFF", "9100C2"]
["F5D6FF"] -> ["F5D6FF"], []

```

# Answer
# Pyth, ~~35~~ 34 bytes

Input already converted to decimal.

```
L+O32+eSbhSbf<yTJ495Qf|gyTJ<yT347Q

```

Test suite.

## Previous 35-byte version:

Input already converted to decimal.

```
L+O32+eSbhSbf<yT495Qf|gyT495<yT347Q

```

Test suite.

**Verify that the third testcase is not the same for each run.**

Sample input/output:

```
input:
[[217, 102, 255], [236, 179, 255], [172, 0, 230]]
output:
[[217, 102, 255], [236, 179, 255], [172, 0, 230]]
[[172, 0, 230]]

```

## Explanation

```
(max/255 + min/255)/2 + random[-0.03 .. 0.03] >= 0.94
(max/255 + min/255) + random[-0.06 .. 0.06] >= 1.88
max + min + random[-15 .. 15] >= 479.4
max + min + random[0 .. 31] >= 494.4
max + min + random[0 .. 31] >= 495

(max/255 + min/255)/2 + random[-0.03 .. 0.03] <= 0.65
(max/255 + min/255) + random[-0.06 .. 0.06] <= 1.30
max + min + random[-15 .. 15] <= 331.5
max + min + random[0 .. 31] <= 346.4
max + min + random[0 .. 31] < 347

L+O32+eSbhSbf<yT495Qf|gyT495<yT347Q
                                     @memoized
L                                    def y(b):
 +O32                                    return random(range(32)) +
     +eSb                                b.sort[-1] +
         hSb                             b.sort[0]
            f      Q                 filter for elements in Q as T:
             <yT495                      y(T) < 495
                                     (implicitly printed)
                    f             Q  filter for elements in Q as T
                     |gyT495             y(T) >= 495 or
                            <yT347       y(T) < 347
                                     (implicitly printed)

```

Before you complain that it calls random three times, hence having inconsistent outputs from the function, note that the function is memoized.

Before you complain that different students with the same colour always produce the same outcome, note that the question never said that the random generator must be independent. It must only be uniform.
> 1 votes

---
Tags: code-golf, conversion, chemistry
---