# Question
Title: The Professor's base building number converter
The nutty maths professor wants to encode all of their research using a system sure to fox even the wiliest of their competitors!

To this end the professor has decided to change the base of not just the number that they're writing but every single digit in that number, according to which place the digit finds itself in (counting from the right, starting with 1). For example:

The number 0 has one digit, so it is represented in base 1: 0

The number 1 would have one digit in base ten, but in our professor's system that isn't valid. The first place is reserved for base 1 digits only! This means it must be bumped to the second place where base 2 is allowed: 10

The number 2 requires at least base 3 to be written: 100

But now the number 3 can be written by changing the digit in the second place: 110

and 4 as so: 200

Here are some more examples to help you get the idea:

> 5:210
>
> 6:1000
>
> 7:1010
>
> 8:1100
>
> 9:1110
>
> 10:1200
>
> 11:1210
>
> 12:2000
>
> 13:2010
>
> 14:2100
>
> 15:2110
>
> 16:2200
>
> 17:2210
>
> 18:3000

Using this system the professor's notes will make no sense to anyone but them, and they can finally ~~take over the world!!!!~~ sleep well at night.

Of course the encoding method must be as obscure as possible.

---

Your task is to write 10 code snippets, each representing one of the base 10 digits

> 0 1 2 3 4 5 6 7 8 9

which when combined in the order of the number to be converted will produce a number written in the professor's diabolical numbering system (the output method may be of your choice but must be a human readable number using only the digits 0-9)

For example if my snippets are:

0=MONKEY 1=EXAMPLE, 2=CODE, 3=GOLF and 9=TEST

then

19 = EXAMPLETEST -\> 3010

20 = CODEMONKEY -\> 3100

21 = CODEEXAMPLE -\> 3110

22 = CODECODE -\> 3200

23 = CODEGOLF -\> 3210

No input numbers with more than 10 digits or negative numbers need to be considered, though if you want to write the code for additional digits you will get extra kudos. This is code golf, so shortest answer (using the combined byte totals of all snippets) wins and the standard loopholes aren't allowed.

ADDENDUM: Before anyone gets started on whether 0 is the correct representation of 0 in base 1 I would like to remind you that this professor is nutty. Live with it.

# Answer
> 1 votes
# Mathematica (REPL environment), 858 total bytes

Here is the 86-byte code snippet for the digit 9:

```
1;ValueQ@a||(a=0;b=3);a=10a+9;b++;FromDigits[a~IntegerDigits~MixedRadix@Range[b,1,-1]]

```

The code snippets for the digits 1 through 8 are identical, except that the 9 is replaced by the appropriate digit. The code snippet for the digit 0 is identical, except that `+9` is simply deleted.

`a~IntegerDigits~MixedRadix@Range[b,1,-1]` computes the list of the factorial-number-system digits of `a`, as long as `b` is at least as large as the number of digits; `FromDigits` converts that list of digits to a regular base-10 integer for the purposes of output. (If any of the list elements exceeds 9, something funny happens.)

In Mathematica's REPL environment, computations can be terminated with semicolons to suppress the output; so only the last output in a semicolon-separated chain will be displayed. We recursively define the integer `a` designated by the snippets, and also a bound `b` on the number of factorial-system digits needed. The command `ValueQ@a||(a=0;b=3)` initializes these variables if they're uninitialized (i.e., in the first snippet) and leaves them alone otherwise; then `a=10a+9;b++` carries out the recursion. Finally, the initial `1;` is for gluing the snippets together: it multiplies intermediate computations by 1 (which we never see anyway).

# Answer
> 0 votes
# Goruby, 790 ~~810~~ ~~980~~

Here's a second attempt, relying on the fact that, in basically any shell, printing a carriage return ("\r") without a newline ("\n") will overwrite the previously printed line, ultimately ensuring that only the last bit printed (that is, the final result) is shown.

This must be run in a shell, e.g. `ruby name_of_file.rb`.

It works for positive numbers of unrestricted length.

The code is ten copies of the snippet below, with `X` (at the top) replaced with the digits from 0-9, one per snippet.

```
->*t{n,d,o="X#{t}".toi,0,''
dw{n,r=n.dm d+=1;o.pr r.ts;n>0}
$>.fu
pr"\r",o
o}

```

That is, the snippet representing (for example) 8 would look like:

```
->*t{n,d,o="8#{t}".toi,0,''
dw{n,r=n.dm d+=1;o.pr r.ts;n>0}
$>.fu
pr"\r",o
o}

```

The challenge states that the snippets need to be "combined" to create represent a multiple-digit number, so, to append a digit to a number, simply place it in the square brackets at the number's end. Thus, the number 103 (in decimal) would be:

```
->*t{n,d,o="1#{t}".toi,0,''
dw{n,r=n.dm d+=1;o.pr r.ts;n>0}
$>.fu
pr"\r",o
o}[->*t{n,d,o="0#{t}".toi,0,''
dw{n,r=n.dm d+=1;o.pr r.ts;n>0}
$>.fu
pr"\r",o
o}[->*t{n,d,o="8#{t}".toi,0,''
dw{n,r=n.dm d+=1;o.pr r.ts;n>0}
$>.fu
pr"\r",o
o}[]]]

```

---
Tags: code-golf, sequence, base-conversion
---


# Question
Title: Improvise a Hardware Random-Number Generator
Your task is to improvise a hardware random-number generator with whatever hardware you have lieing around.

## Challenge

Write a program with the following properties:

1. It prints either `0` or `1` (and nothing else).
2. The output depends on a physical process and not just the internal state of the computer.
3. There is no relation between outputs of subsequent runs (one minute apart).
4. The output is not predictable with any realistic effort.
5. The probability of the output being `0` is between 0.2 and 0.8.
6. It runs in less than a minute with a reasonably high probability.

You must explain why your program has these properties, if it is not obvious.

## Clarifications and Restrictions

The following may seem like an awful lot of restrictions for a popularity contest, but ultimatively it’s all to ensure that the program remains within the spirit of the question, somewhat works and to avoid solutions which are popular due to being a total overkill but are ultimatively rather boring.

* The system time does not count as a physical process.
* You may use any consumer-grade hardware you like from 8-inch floopy-disk drives to a USB rocket launcher to headphones – unless it is intended for random-number generation. A piece of hardware is *consumer-grade,* if it is mass-produced and costs less than 1000 $/€/£, so you cannot use radio telescopes, the CERN, MRIs or your home-built particle detector.
* You can only make the most basic assumptions on the state and alignment of the hardware such as being switched on (if it has a power switch) and being properly installed and functional. For example you can assume a CD drive to be generally capable of reading a disk and not to be jammed, but you cannot assume it to be open or closed or to contain a disk. In another example you cannot assume two pieces of hardware to be aligned to allow for a special interaction, but you can assume them to be in the same room.
* You may leave the hardware in any state you like, unless you break it.
* You can and must assume the hardware to be in a natural environment, but nothing more. For example you can assume that the hardware is not positioned in a in tank of liquid helium nor in an extremely sound- and lightproof room nor in space. However, you cannot assume any sound- and lightsources to be present except those that are only avoidable with radical efforts.
* Your program must run on a standard desktop computer with a non-esoteric operating system of your choice. You may employ any software that is not specifically designed for random-number generation.
* You cannot assume Internet access.
* You can neither assume humans to be present nor absent, but you can assume that nobody intentionally interfers with your program, e.g., by manually stopping a fan or running a program that does nothing but switching off the microphone as often as possible.
* You can only make the most basic assumptions about the software settings. For example, you can assume drivers to be installed and activated but you must be prepared for the sound to be muted.
* You may leave the software settings in any state you like.

## Bonus

A special bounty was awarded to a particularly short solution. This was rather by numbers of instructions and similar than by characters. The winners were (tied according to my criteria):

I could only award one answer and Tejas Kale’s answer won by lot.

# Answer
## Shell

Reads a single sample from the microphone stream and prints its least-significant bit, which should be dominated by noise.

**EDIT:** Changed to unmute the microphone ... and everything else too!

```
# Warning - unmutes EVERYTHING!
for DEV in `amixer | grep Simple | sed -e "s/.*'\(.*\)'.*/\\1/" -e "s/ /~/g"`
do
    amixer -q -- sset "`echo $DEV | sed 's/~/ /g'`" unmute 100% 2>/dev/null
done

echo $(( `od -N1 -d < /dev/dsp | head -n1 | sed 's/.* //'` & 1 ))

```
> 31 votes

# Answer
# Bash

```
echo $[`ping -qc1 127.1|sed 's/[^1-9]/+/g'`0&1]

```

Gathers entropy from the response time of a single ping to localhost.

Note that the response time appears exactly thrice in the output of `ping -qc1`:

```
PING 127.1 (127.0.0.1) 56(84) bytes of data.

--- 127.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.044/0.044/0.044/0.000 ms

```

All other numbers and constant and – more importantly – independent from the response time.

`sed 's/[^1-9]/+/g'` converts every zero and non-digit into plus signs, and `echo $[...0&1]` prints the parity of the resulting sum.
> 27 votes

# Answer
# JavaScript + HTML5 DeviceMotion

```
var hash = function(x) {
    var h = 0
    for (var i = 0; i < x.length; i++) {
        h += x.charCodeAt(i)
        h ^= h << 5
        h ^= h >> 3
        h ^= h << 13
        h &= 0xffff
    }
    return h
}
var listener = function(e) {
    var accelerationString = JSON.stringify(e.acceleration)
    var hashed = hash(accelerationString)
    alert(hashed % 2)
    window.removeEventListener("devicemotion", listener, true)
}
window.addEventListener("devicemotion", listener, true);

```

JSFiddle here.

Uses the HTML5 DeviceMotion API on supported devices (mostly mobile devices). It turns the resulting `acceleration` object into JSON, hashes it, and takes the remainder modulo 2.

Most of the code is the hash function (damn you JavaScript, and your total lack of a standard library). It could probably be shorter, but I'm a sucker for a good hash function.
> 25 votes

# Answer
# Python + Webcam

Using code shamelessly stolen from here, takes a shapshot using your webcam, hashes the data, and prints the least significant bit.

```
#!/usr/bin/python
import pygame.camera, hashlib

pygame.camera.init()
cam = pygame.camera.Camera(pygame.camera.list_cameras()[0])
cam.start()
raw = cam.get_raw()
cam.stop()
pygame.camera.quit()

h = hashlib.sha256()
h.update(raw)
print ord(h.digest()[-1]) % 2

```
> 21 votes

# Answer
## Perl

Checks your Harddrive's response time, by timing three operations:

* Reading its own source
* Deleting itself
* Writing itself again

Finally, the time taken is packed as a float, and the 11th most significant bit is used (second most significant bit of the mantissa).

```
use Time::HiRes qw(time);

$t1 = time;
open SELF, "<$0";
read SELF, $_, $^H;
close SELF;

unlink $0;

open SELF, ">$0";
print SELF $_;
close SELF;

print 1&unpack(xB3, pack(f, time-$t1))

```
> 15 votes

# Answer
# Bash

```
echo $[`sensors|sed 's/[^1-9]/+/g'`0&1]

```

`sensors` prints the current system temperatures along with the fan speed.

```
acpitz-virtual-0
Adapter: Virtual device
temp1:        +52.0°C  (crit = +98.0°C)

thinkpad-isa-0000
Adapter: ISA adapter
fan1:        3510 RPM

coretemp-isa-0000
Adapter: ISA adapter
Physical id 0:  +54.0°C  (high = +86.0°C, crit = +100.0°C)
Core 0:         +51.0°C  (high = +86.0°C, crit = +100.0°C)
Core 1:         +46.0°C  (high = +86.0°C, crit = +100.0°C)

```

`sed 's/[^1-9]/+/g'` converts every zero and non-digit into plus signs, and echo `$[...0&1]` prints the parity of the resulting sum.

Regex and parity calculation borrowed from dennis's answer.
> 14 votes

# Answer
## Bash

```
(echo -en "ibase=16;";(find /proc/[0-9]*/s* -type f -maxdepth 2 ; find /sys /proc/[^0-9]* -type f) 2>&1 | xargs -n1 sha256sum  2>&1 | sha256sum | tr abcdef ABCDEF | sed 's/  -/%2/' )| bc

```

Uses everything, just in case...

Depends on

* sensor readings of most hardware sensors (about all somehow expose their values somewhere in `/sys` or `/proc`)
* number, memory layout and runtimes of all processes on the system (which may be considered "state of the system" but usually themselves depend on the timings of the hardware)
* depending on the system, various values in `/proc/<pid>/s*` (e.g. sched/schedstat) depend on the speed of the hardware necessary to bring those processes alive.
* things I might not have thought of that are available in those files too.

Runtime on my system is ~10s, but may vary a lot. Especially don't run this as root, or at least modify it to exclude `/proc/kcore` (unless you are willing to spend a lot of time to include the entropy contained in there, which would probably really include everything)
> 12 votes

# Answer
# Shell + Wi-Fi

```
sudo airmon-ng start wlan0 > /dev/null && sudo dumpcap -a duration:30 -i mon0 -w out.cap > /dev/null && sha512sum out.cap | grep -c "^[0-7]" && sudo airmon-ng stop mon0 > /dev/null

```

Puts the wi-fi card into monitor mode, dumps 30 seconds worth of packets received (including unreadable encrypted data from neighbouring networks), takes the sha512 hash of the packet data, and returns 1 if the first letter of the hash is 0-7. Assumes that your wi-fi card is `wlan0`, and that you do not currently have a `mon0` device.

If there are no nearby wi-fi devices, then the output will be predictable, as it will be the same every time.
> 9 votes

# Answer
Modern 8086 compatible processors manufactured by Intel contain an easily accessible peripheral that generates proper randomness. Driving that peripheral is done using the `rdrand` instruction which either generates a random bit pattern or sets the carry flag if the peripheral is unavailable or out of entropy.

The following short program for 80386 Linux checks if the peripheral is available by means of the `cpuid` instruction and tries to generate a random number. If either the peripheral or a random number is not available, the program will terminate with a status of `1`. If a random number could be generated, either a `1` or a `0` is printed out and the program terminates with exit status `0`.

Save as `rand.s` and assemble with

```
as --32 -o rand.o rand.s
ld -melf_i386 -o rand rand.o

```

Here is the entire assembly:

```
        .globl _start
        .type _start,@function
_start:
        # check if the cpuid instruction is available by trying to
        # toggle the id flag in the eflags register
        pushfl
        mov (%esp),%eax
        btc $21,%eax    # toggle id bit
        push %eax
        popfl           # check if id bit was saved
        pushfl
        pop %eax        # load new flags
        pop %ecx        # load original flags
        xor %ecx,%eax   # difference is in %eax
        bt $21,%eax     # check if bit was flipped
        jnc .Lfailure

        # if we reach this part, we have a cpuid instruction
        # next, check if rdrand exists
        mov $1,%eax     # load cpuid leaf 1
        cpuid
        bt $30,%ecx     # is rdrnd available?
        jnc .Lfailure

        # let's try to get some random data
        rdrand %ax      # don't waste randomness; one bit would suffice
        jnc .Lfailure   # no randomness available
        and $1,%eax     # isolate one bit of randomness
        add $0x30,%al   # 0x30 = '0'
        push %eax
        mov $4,%eax     # prepare a write system call
        mov $1,%ebx
        mov %esp,%ecx   # where we placed the data before
        mov %ebx,%edx   # one byte
        int $0x80

        # okay, we're done here. Let's exit
        mov %ebx,%eax   # do an exit system call with status 0
        xor %ebx,%ebx
        int $0x80

.Lfailure:
        mov $1,%eax     # do an exit system call with status 1
        mov %eax,%ebx
        int $0x80

        .size _start,.-_start

```

And a dump of the resulting 77 bytes of machine code:

```
08048098 <_start>:
 8048098:   9c                      pushf
 8048099:   8b 04 24                mov    (%esp),%eax
 804809c:   0f ba f8 15             btc    $0x15,%eax
 80480a0:   50                      push   %eax
 80480a1:   9d                      popf
 80480a2:   9c                      pushf
 80480a3:   58                      pop    %eax
 80480a4:   59                      pop    %ecx
 80480a5:   31 c8                   xor    %ecx,%eax
 80480a7:   0f ba e0 15             bt     $0x15,%eax
 80480ab:   73 2f                   jae    80480dc <_start+0x44>
 80480ad:   b8 01 00 00 00          mov    $0x1,%eax
 80480b2:   0f a2                   cpuid
 80480b4:   0f ba e1 1e             bt     $0x1e,%ecx
 80480b8:   73 22                   jae    80480dc <_start+0x44>
 80480ba:   66 0f c7 f0             rdrand %ax
 80480be:   73 1c                   jae    80480dc <_start+0x44>
 80480c0:   83 e0 01                and    $0x1,%eax
 80480c3:   04 30                   add    $0x30,%al
 80480c5:   50                      push   %eax
 80480c6:   b8 04 00 00 00          mov    $0x4,%eax
 80480cb:   bb 01 00 00 00          mov    $0x1,%ebx
 80480d0:   89 e1                   mov    %esp,%ecx
 80480d2:   89 da                   mov    %ebx,%edx
 80480d4:   cd 80                   int    $0x80
 80480d6:   89 d8                   mov    %ebx,%eax
 80480d8:   31 db                   xor    %ebx,%ebx
 80480da:   cd 80                   int    $0x80
 80480dc:   b8 01 00 00 00          mov    $0x1,%eax
 80480e1:   89 c3                   mov    %eax,%ebx
 80480e3:   cd 80                   int    $0x80

```
> 8 votes

# Answer
# bash

Aiming for the most unnecessarily expensive random number gathering method. Time how long it takes to spawn emacs a million times, then use Dennis' trick to turn the time taken into a single Boolean (takes about 7 seconds on my machine).

```
$[`(time (seq 1000000 | xargs -P1000 emacs  >/dev/null 2>&1)) |& sed 's/[^1-9]/+/g'`0&1]

```
> 7 votes

# Answer
# Arduino Mega1280

edit: updated version that is robust against having anything plugged into the pins. The idea relies on the fact that the ATMega1280 uses a separate internal oscillator for the watchdog oscillator. I simply setup a watchdog interrupt which sets a flag, have a counter based on the system clock (on the Arduino this is a 16MHz external crystal), and allow clock jitter/variance do the work.

```
#include <avr/interrupt.h>

int time;
volatile bool wdt_ran;

// watchdog interrupt handler
ISR(WDT_vect, ISR_BLOCK)
{
  wdt_ran = true;
}

void setup()
{
  // setup watchdog interrupt
  cli();
  MCUSR &= ~(1 << WDRF);
  WDTCSR |= (1<<WDCE) | (1<<WDE);
  WDTCSR = (1<<WDIE) | (1<<WDP2) | (1<<WDP1) | (1<<WDP0);
  sei();
  // Open serial communications and wait for port to open:
  Serial.begin(57600);
}

void loop()
{
  if(wdt_ran)
  {
    Serial.println(abs(time%2));
    wdt_ran = false;
  }
  ++time;
}

```
> 7 votes

# Answer
# Javascript

http://jsfiddle.net/prankol57/9a6s0gmv/

Takes video input.

You can see the screenshot that it used to calculate the random number.

```
var m = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);

var constraints = {
  video: {
    mandatory: {
      maxWidth: 350,
      maxHeight: 350
    }
  },
  audio: false
};

var video = document.querySelector("video"), canvas = document.createElement("canvas");
document.body.appendChild(canvas);
canvas.width = 350;
canvas.height = 350;

function start() {
    m.call(navigator, constraints, function (stream) {
        video.src = window.URL.createObjectURL(stream);
    }, function() {
        alert("An error occured. Did you deny permission?");
    });
}

if (m) {
    start();
} else {
    alert('getUserMedia() is not supported in your browser');
}

function getRandomData() {
    var ctx = canvas.getContext("2d");
    ctx.drawImage(video, 0, 0);
    var data = ctx.getImageData(0, 0, 350, 350).data;
    var total = 0;
    for (var i = 0; i < data.length; ++i) {
        total += data[i];
        total %= 2;
    }
    alert("The random number is " + total);
}

document.querySelector("button").onclick = getRandomData;

```
> 5 votes

# Answer
# Shell on Linux

Measure read speed of a hard drive + access time of a frequently updated directory on this disc which layout is unpredictable.

```
# Set this to the device node of whatever drive you want to measure
DRIVE_DEVICE=sda
# This must be a path that is
# a) on device "/dev/$DRIVE_PATH"
# b) frequently updated to add additional access time randomization due to
#    less-predictable disk layout due to less-predictable time, amount and
#    ordering uf updates, like logfile directories, maybe cache directories.
FIND_PATH=/var/log
# Better than using 'sync' - sync only the disk that we actually read from
# also sync both internal drive and system buffers
hdparm -f -F "/dev/$DRIVE_DEVICE"
# Note: bash's built-in time command doesn't support formats :/
# Note: the result is only going to be as good as the system's time command,
#       which isn't necessarily equally good on other U*ICes
t=$(command time -f '%e' -- find "$FIND_PATH" -printf '' 2>&1)
echo $((${t#*.}&1))

```

requires:

```
1) read and execute access to every directory under "$FIND_PATH"
2) sending (flush) control commands to a hard drive via a device node.
   Requires root access per default, but can be delegated to a less privileged user
   either by using sudo on this script or by applying
       chgrp 'some_system_group' "$DRIVE_DEVICE" &&
       chmod g+rx "$DRIVE_DEVICE"
   if this is acceptable on your system.

```

This approach has the advantage of not modifying any data on the system and not requiring perl over primo's one.
> 3 votes

# Answer
# Shell

Tested on Linux, but maybe your U\*IX does have /proc/stat as well?

This starts only a single additional process, reads only a single additional file (not even on disc) and is 37 characters short. It's also pretty fast.

```
t=1`sum /proc/stat`;echo $[${t% *}&1]

```

One may think that this is determined by all kernel and userland process states, but that is not the case, since /proc/stat also includes IO-wait time, time to sevice hardware interrupts, time spent in idle task and some other which all depend on external hardware input.
> 3 votes

# Answer
# Matlab

The microphone solution:

```
recObj=audiorecorder;recordblocking(recObj,10);rem(sum(getaudiodata(recObj)<0),2)

```

Records 10 seconds of sound, finds the number of negative samples in the recording and outputs 0 if this number is even and 1 if it's odd. Thus 0 with 50% probability. The approach means that even small amounts of noice, unavoidable in a silent recording, will be enough to generate a random output. The following slightly longer code speeds up the number generator by using a shorter recording, compensated with a higher bitrate, which gives more noise.

```
recObj=audiorecorder(8000,16,1);recordblocking(recObj,0.1);rem(sum(getaudiodata(recObj)<0),2)

```

In a test under quiet conditions, I find that in 100 runs of the latter code, the code outputs zero 51 times. 100 runs under noisy conditions produced zero 40 times.

Edit: Thanks to Emil for pointing out a flaw in the original code :-)
> 2 votes

# Answer
## Bash

(Thanks, Dennis.)

```
echo $[`w|sed 's/[^1-9]/+/g'`0&1]

```
> 0 votes

# Answer
Takes the least significant bit of the computer's accelerometer (needs the `hdaps` Linux module):

```
#!/usr/bin/env python
import re
m = re.search('([-\d]+),([-\d]+)',
              open('/sys/devices/platform/hdaps/position', 'r').read())
print((int(m.group(1)) ^ int(m.group(2))) & 1)

```

This basically measures the noise of the sensor.
> 0 votes

# Answer
# SmileBASIC

```
XON MOTION 'enable motion sensor
ACCEL OUT ,,Z 'get Z acceleration (up/down)
PRINT Z<-1 'if Z is less than -1, output 1, otherwise 0.

```

Uses the 3DS's motion sensor. The Z axis of the accelerometer is usually around -1 (because of gravity), and due to random noise, it can sometimes be above or below that.

Here's one that uses the microphone:

```
XON MIC 'enable microphone
DIM REC%[0] 'make array
MICSTART 0,3,1 'start recording. 0=8180Hz, 3=8 bit unsigned, 1=1 second
WAIT 1 'delay (1 frame is enough since we only check the first sample)
MICSAVE MIC 'save recording
PRINT MIC[0]>0 'if the first sample isn't negative, output 1

```
> 0 votes

# Answer
# Bash

I took Soham’s own suggestion (using `top`):

```
echo $[`top -bn1|sed 's/[^1-9]/+/g'`0&1]

```

Edit: It works the same way Soham's does. It turns all non numeric characters in the output of top into '+' and then evaulates the parity of the resulting string.

the 'b' flag to top runs it in batch mode so that it reports all processes, not just the first screenful and 'n1' says to just run 1 iteration of top.
> -3 votes

---
Tags: popularity-contest, random, hardware
---


title: Mark a UKMT IMC Paper

text:
# Question
Title: Mark a UKMT IMC Paper
I did the IMC this year. Did anyone else here do it?

In a UKMT Intermediate Maths Challenge paper, there are twenty-five questions. The first fifteen questions give you five marks if you get them right. For the other ten questions, you get six marks for getting them right. In the last ten questions, you lose marks if you get them wrong! For questions sixteen to twenty, you lose one marks and for the last five questions, you lose two marks. If you leave a question blank, no marks are awarded or deducted. No marks are deducted for getting any of the first fifteen questions wrong. The paper is multiple choice; you can choose any answer out of A, B, C, D and E for each question. There is always just one right answer for each question.

Create a program/function that takes two strings and outputs a score. The first string will be your answers to the paper. If you skip a question, use a space, a null byte or an underscore. Otherwise, use the letter A, B, C, D or E for the answer. You can either have the inputs uppercase or lowercase. The second string will be the correct answers for each question in the paper. Your program/function will then output a score. Make your code short.

Test cases:

```
DDDDDDDDDDDDDDDDDDDDDDDDD
ABCDEABCDEABCDEABCDEABCDE
15

BDBEACCECEDDBDABBCBDAEBCD
BDBEACCECEDDBDABBCBDAEBCD
135

DBACBDCDBAEDABCDBEECACDC_
DBADBDCDBAEDABCDBEEDACDCA
117

_________________________
DABDABDABDABDABDABDABDABD
0

DBADBDCDBAEDABCD_E__A__C_
DBADBDCDBAEDABCDBEEDACDCA
99

_______________BBBBBBBBBB
AAAAAAAAAAAAAAAAAAAAAAAAA
-15

```

# Answer
# C, ~~88~~ ~~87~~ ~~86~~ 81 bytes

```
c,d;i(char*a,char*b){for(c=d=0;*b;c++,a++)d+=*a^*b++?*a?-c/15-c/20:0:5+c/15;d=d;}

```

Try it online!
> 7 votes

# Answer
# Jelly, ~~26~~ ~~23~~ 22 bytes

```
=s5ị"“HHHQP‘D¤_2Fæ.n⁶¥

```

Try it online!

### How it works

```
=s5ị"“HHHQP‘D¤_2Fæ.n⁶¥  Main link. Argument: t (answer to test), s (answer sheet)

=                       Test the characters of t and s for equality.
 s5                     Split into chunks of length 5.
             ¤          Combine the two preceding links into a niladic chain.
     “HHHQP‘              Yield the code points, i.e., [72, 72, 72, 81, 80].
            D             Decimal; yield [[7, 2], [7, 2], [7, 2], [8, 1], [8, 0]].
   ị"                   Index zipwith; use the Booleans in each chunk to index into
                        the corresponding pair. Indexing is 1-based and modular, so
                        1 gives the first element and 0 the last.
              _2        Subtract 2 from each result.
                F       Flatten the resulting 5x5 matrix.
                     ¥  Combine the two preceding links into a dyadic chain.
                   n⁶     Test the characters of t for inequality with space.
                 æ.     Take the dot product of the integers to the left and the
                        Booleans to the right.

```
> 6 votes

# Answer
## JavaScript (ES6), ~~70~~ ~~68~~ 66 bytes

*Saved 2 bytes thanks to Neil*
*Saved 2 bytes thanks to ETHproductions*

Takes applicant answers `a` and correct answers `c` in currying syntax `(a)(c)`. Expects skipped questions to be marked with a space.

```
a=>c=>a.replace(/\S/g,(a,i)=>s+=a==c[j=i>14,i]?5+j:-j^i>19,s=0)&&s

```

### Test cases

```
let f =

a=>c=>a.replace(/\S/g,(a,i)=>s+=a==c[j=i>14,i]?5+j:-j^i>19,s=0)&&s

console.log(f
  ("DDDDDDDDDDDDDDDDDDDDDDDDD")
  ("ABCDEABCDEABCDEABCDEABCDE")
);
console.log(f
  ("BDBEACCECEDDBDABBCBDAEBCD")
  ("BDBEACCECEDDBDABBCBDAEBCD")
);
console.log(f
  ("DBACBDCDBAEDABCDBEECACDC ")
  ("DBADBDCDBAEDABCDBEEDACDCA")
);
console.log(f
  ("                         ")
  ("DABDABDABDABDABDABDABDABD")
);
console.log(f
  ("DBADBDCDBAEDABCD E  A  C ")
  ("DBADBDCDBAEDABCDBEEDACDCA")
);
console.log(f
  ("               BBBBBBBBBB")
  ("AAAAAAAAAAAAAAAAAAAAAAAAA")
);
```
> 5 votes

# Answer
# Python 2, ~~86~~ ~~85~~ ~~83~~ 77 bytes

```
f=lambda t,s,i=24:~i and(i/10*-(14<i<t[i]<'_'),5+i/15)[t[i]==s[i]]+f(t,s,i-1)

```

Try it online!

### How it works

This defines a recursive function **f** that takes two non-optimal arguments: **t** (the answers to the test) and **s** (the answer sheet). When called only with these two arguments, **f** initializes **i** to **24**, the last index of both **t** and **s**.

Every time **f** is called, it first checks if **~i** (the bitwise NOT of **i**) is truthy/non-zero. Since **~(-1) = 0**, this happens once the **i** reaches the value **-1**. If **i = -1**, **~i = 0** is returned, but as **i** takes values from **24** to **0** (all indices of **t** and **s**), the code following `and` is executed and **f** returns the result.

While **i** is non-negative, the following happens. First,

```
(i/10*-(14<i<t[i]<'_'),5+i/15)

```

creates a tuple of length **2**:

* The quotient `i/10` is **0** if **0 ≤ i \< 10**, **1** if **10 ≤ i \< 20**, and **2** if **20 ≤ i \< 25**. The chained comparison `14<i<t[i]<'_'` returns *True* if and only if all individual comparisons return *True*, i.e., if and only if **i ≥ 15** (the range of questions with penalty), **i** is smaller than **t\[i\]** (always true since all numbers are smaller than all iterables in Python 2), and **t\[i\]** is not an underscore.

If the comparison returns *False*, the unary `-` returns **0** and the entire expression evaluates to **0**. However, if the comparison returns *True*, the unary `-` returns **-1**, so the entire expression evaluates to **0** if **0 ≤ i \< 10**, **-1** if **10 ≤ i \< 20**, and **-2** if **20 ≤ i \< 25**; these are the net results for wrong or missing answers for all indices **i**.
* `5+i/15` returns **5 + 0 = 5** if **0 ≤ i \< 15** and **5 + 1 = 6** if **15 ≤ i \< 25**. These are the net results for correct answers for all indices **i**.

Finally, `[t[i]==s[i]]` selects the first element of the constructed tuple if **t\[i\]** and **s\[i\]** differ (wrong or missing answer) and the second one if they are equal (correct answer), then adds the return value of **f** called with decremented **i** to that result. Once **i** reaches **-1**, the final score has been computed and is returned by **f**.
> 4 votes

# Answer
# Mathematica, 114 bytes

```
Tr@(m=MapThread)[#/.True->#2/.False->-#3&,{Tr/@Partition[m[Equal,#/."_"->u]/.u==_->0,5],{5,5,5,6,6},{0,0,0,1,2}}]&

```

Pure function taking an ordered pair of lists of characters and returning an integer. `m[Equal,#/."_"->u]` returns a list of booleans, except for unevaluated entries of the form `u=="B"` in places where the answer equaled `"_"`; then right away, `u==_->0` turns those unevaluated entries into `0`s. `Tr/@Partition[...,5]` adds these entries up 5 at a time, resulting in a list like `{4False+True, 4False+True, 4False+True, 4False+True, 4False+True}` for the first test case or `{5True, 5True, 5True, 2True, 2True}` for the last test case. Then in each coordinate, `True` and `False` are mapped to the appropriate scores, and the results are added together.
> 3 votes

# Answer
# Jelly, ~~22~~ 21 bytes

```
Zm0ṁ135µ;t€⁶E€’;E€ṫ⁹S

```

Try it online!

I *thought* @Dennis's answer was probably beatable. And after trying out a huge number of different possibilities and benefitting from an amazing coincidence, I've finally managed it!

This program takes a pair of \[student's answers, correct answers\] as input, and uses spaces to indicate a missing answer.

## Explanation

This program uses some bizarre internal input formats to keep track of what's going on, so we'll take this a step at a time.

1. `Z`

This transposes the input, so we'll end up with a list of 25 elements, one for each question; each element is of the form \[student's answer, correct answer\]. We'll indicate an element of this form with a capital letter; `A` for question 1, `B` for question 2, and so on. So the answers are currently being stored as

```
ABCDEFGHIJKLMNOPQRSTUVWXY

```
2. `m0`

This is a "greater palindrome" operation; we append the reverse of the current value to the value itself, yielding this:

```
ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBA

```
3. `ṁ135`

The  (mold) operator does a number of things, but in this context, it effectively takes the first 135 elements of the infinite list produced by appending the current value to itself repeatedly. That gives us the following (which I've broken into groups of 50 elements for convenience; this is just a list of 135 pairs internally):

```
ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQP

```
4. `µ;`

`µ` sets the current value as the new default for missing operands. We then immediately see a builtin that's missing an operand; `;` appends, but we haven't specified what to append with. As a result, the current value is appended to the value as of the last `µ` (which is also the current value), giving us the following 270-element current value:

```
ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPABCDEFGHIJKLMNO
PQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBAABCDEFGHIJKLMNO
PQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBAABCDEFGHIJKLMNO
PQRSTUVWXYYXWVUTSRQP

```
5. `t€⁶`

Remember that all the capital letters above represent pairs of \[student's answer, correct answer\]. The `t€⁶` operation operates on each () pair, and deletes (`t`) spaces () from either side of the pair (i.e. any space that appears in the pair). So we still have the same convoluted list of 270 questions with many repeats, but they're of the form \[correct answer\] (student didn't answer) or \[student's answer, correct answer\] (student did answer).
6. `E€’`

The `E€’` operation also operates on each () element, and, due to the use of `E`, replaces the element with 1 if all the elements are equal (i.e. the student didn't answer or got the question right), or 0 if not all the elements are equal (i.e. the student answered but got the question wrong). The use of  here changes the numbering, meaning that we now use -1 or 0 respectively. I'll use lowercase letters for this new sort of element, which uses -1 for an answer which would be penalised if it were on a penalty-eligible question, or 0 for a missing or correct answer:

```
abcdefghijklmnopqrstuvwxyyxwvutsrqponmlkjihgfedcba
abcdefghijklmnopqrstuvwxyyxwvutsrqponmlkjihgfedcba
abcdefghijklmnopqrstuvwxyyxwvutsrqpabcdefghijklmno
pqrstuvwxyyxwvutsrqponmlkjihgfedcbaabcdefghijklmno
pqrstuvwxyyxwvutsrqponmlkjihgfedcbaabcdefghijklmno
pqrstuvwxyyxwvutsrqp

```
7. `;E€`

We've seen both `E€` and `;` before; we're appending something to the current value, and we're using a format of 1 if all the elements are equal, or 0 if some are different (no  this time!). There's a missing operand here, so we use the value as of the last `µ` (i.e. the output of step 3). Back in step 3, we hadn't deleted spaces from the elements, so we'll have 1 for a correct answer, or 0 for an incorrect or missing answer (because a space won't match the correct answer). From now on, I'll use capital letters for this 1=correct, 0=incorrect/missing format, and continue to use lowercase letters for 0=correct/missing, -1=incorrect. The resulting value has 405 elements, and looks like this:

```
abcdefghijklmnopqrstuvwxyyxwvutsrqponmlkjihgfedcba
abcdefghijklmnopqrstuvwxyyxwvutsrqponmlkjihgfedcba
abcdefghijklmnopqrstuvwxyyxwvutsrqpabcdefghijklmno
pqrstuvwxyyxwvutsrqponmlkjihgfedcbaabcdefghijklmno
pqrstuvwxyyxwvutsrqponmlkjihgfedcbaabcdefghijklmno
pqrstuvwxyyxwvutsrqpABCDEFGHIJKLMNOPQRSTUVWXYYXWVU
TSRQPONMLKJIHGFEDCBAABCDEFGHIJKLMNOPQRSTUVWXYYXWVU
TSRQPONMLKJIHGFEDCBAABCDEFGHIJKLMNOPQRSTUVWXYYXWVU
TSRQP

```
8. `ṫ⁹`

Here comes the amazing coincidence I mentioned earlier. Before talking about this bit of the code, I want to take stock of where we've got to.

Each capital letter represents +1 for a correct answer; the first 15 questions (`A` through `O`) appear 5 times each in the string, and the last 10 questions (`P` through `Y`) appear 6 times each. That bit isn't really magical; I designed it that way when I chose the number 135 earlier on in the program (which is 5 × 15 + 6 × 10), and the only stroke of luck here is that 5 happens to be an odd number (so it's the last 10 questions that end up appearing the extra times, rather than the first 10). The 15 letters immediately preceding this contain `p` through `t` (the -1 penalty questions) once, and `u` through `y` (the -2 penalty questions) twice. That also isn't much of a coincidence; because we used `m0` earlier, the extra copies of the questions are in the order `PQRSTUVWXYYXWVUTSRQP`, and the later questions will naturally occur near the middle of that string (so taking the last 15 of the "extra" questions will give fewer repeats to the ones near the edges; and of course, it's not a surprise that the "extra" questions come last).

Because each lowercase letter subtracts 1 from the score for an incorrect, non-missing answer, and each uppercase letter adds 1 to the score for a correct answer, we therefore simply need to take the last 135 + 15 = 150 elements in order to get each sort of element the correct number of times. Jelly's command for getting a substring at the end of a list is ; however, it doesn't specify the number of elements you want, but rather the index of the first element you want. We have 405 elements at this point, and want 150, so we need to start at index (405 - 150 + 1), or 256. In an amazing coincidence, 256 happens to be the number of distinct octets that exist, and thus has a short representation in Jelly (). There was very little I could do in order to make this happen; step 4 added another 135 elements to the start of the list in order to hit the round number, but the fact that it was 135 elements I had to add (a value which was readily available at that point in the program) was really convenient, with basically any other number being completely unhelpful in this situation.

Here's how the internal value looks now:

```
uvwxyyxwvutsrqpABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQP
ONMLKJIHGFEDCBAABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQP
ONMLKJIHGFEDCBAABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQP

```
9. `S`

Finally, now we've got a list of modifications to the score from questions, all we need to do is sum them using `S`, and we're done.
> 3 votes

# Answer
# Python 2, ~~93~~ 91 bytes

```
f=lambda a,b,n=0:a>""and((a[0]==b[0])*(5+n/15)or-(n/15*n/10)*(a[0]<"^"))+f(a[1:],b[1:],n+1)

```

Try it online!

-2 bytes thanks to @KritixiLithos

---

## Input:

* `a` : Answers of the student as a string, `_` for skipped question
* `b` : correct answers
* `n` : the number of the current question `0`-based, defaults to `0`
> 2 votes

# Answer
# Octave, ~~61~~ 54 bytes

```
@(a,b)[a==b,-(a<95&a~=b)]*[(x=1:25>15)+5,(1:25>20)+x]'

```

Try it online!

Previous answer:

```
@(a,b)(m=a==b)*(((f=kron(z=[0 0 0:2],z|1)')&1)+5)-(a<95&~m)*f

```
> 1 votes

# Answer
# k, 52 bytes

Function takes 2 strings, format per the test cases

```
{+/(~x="_")*(+,/'(15 5 5#'0 -1 -2;15 10#'5 6))@'x=y}

```

Example:

```
k){+/(~x="_")*(+,/'(15 5 5#'0 -1 -2;15 10#'5 6))@'x=y}["DBADBDCDBAEDABCD_E__A__C_";"DBADBDCDBAEDABCDBEEDACDCA"]
99

```
> 1 votes

# Answer
# JavaScript (ES6), ~~105~~ ~~103~~ ~~101~~ ~~94~~ ~~89~~ ~~88~~ ~~85~~ ~~84~~ ~~78~~ 77 bytes

My first solution in ES6, maybe even first in Javascript O.o

```
f=(s,a,i=24)=>i+1&&(s[i]>'Z'?0:s[i]==a[i]?5+(i>14):~(i>19)*(i>14))+f(s,a,i-1)

```

**s** is the submitted solution and **a** is the correct solution. Both will be taken as strings.

Here's a non-recursive solution at 78 bytes:

```
s=>a=>eval([...s].map((c,i)=>c>'Z'?0:c==a[i]?5+(i>14):~(i>19)*(i>14)).join`+`)

```

Takes input through the currying syntax.

Thanks to @ETHproductions for saving 9 bytes! `s[i]` to `c` and `(-1-(i>19|0))` to `~(i>19)`.

Thanks to @Kritixi Lithos for saving a byte! `c=='_'` to `c>'Z'`.

Try it online!
> 1 votes

# Answer
## Haskell, 84 bytes

```
i x a b|a>'Z'=0|a==b=6-0^x|1<2= -x
w x=x<$[1..5*3^0^x]
(sum.).zipWith3 i(w=<<[0..2])

```

Usage example: `((sum.).zipWith3 i(w=<<[0..2])) "DBADBDCDBAEDABCD_E__A__C_" "DBADBDCDBAEDABCDBEEDACDCA"` -\> `99`. Try it online!.

How it works: `i x a b` calculates the score for a single answer `a` with correct result `b` and the penalty `x` for a wrong answer (a non-negative value). If you skip (`a>'Z'`), the score is `0`, if the answer is right (`a==b`), the score is `6-0^x`, else the score is `-x`.

`w=<<[0..2]` makes a list of penalties for all 25 questions by applying `w` to `0`, `1` and `2`, i.e. making `5*3^0^x` copies of each number (-\> 15 times `0`, 5 times `1` and 5 times `2`).

`zipWith3` applies `i` to the list of penalties, list of answers and list of correct results. Finally all scores are added (`sum`).
> 1 votes

---
Tags: code-golf
---


title: Mama Say Mama Sa Mama Coosa

text:
# Question
Title: Mama Say Mama Sa Mama Coosa
## Mama Say Mama Sa Mama Coosa

I'm sure all of you have heard of Michael Jackson and some of you have listened to MJ's song "Wanna be starting something". The line "Mama Say Mama Sa Mama Coosa" is repeated throughout the song.

## Specification

In this line, the word "Mama"occurs three times, "Say", "Sa", "Coosa" occurs once. The task is the following: Given the input number of occurrences of the words "Mama", "Say", "Sa", "Coosa", output the number of times MJ can sing "Mama Say Mama Sa Mama Coosa", like in a complete sentence.

## Input

Input is a single line with four positive integers denoting the number of times he says the words "Mama", "Say", "Sa","Coosa" respectively .

## Output

Output the number of times MJ can sing "Mama Say Mama Sa Mama Coosa"

Shortest code wins.

## Testcases

```
Testcase 1
Input -->  3 1 1 1
Output-->  1

Testcase 2
Input -->  6 1 1 1
Output-->  1

Testcase 3
Input -->  1000 3 2 3
Output-->  2

Testcase 4
Input -->  7 3 4 3
Output-->  2

```

# Answer
> 7 votes
# Jelly, 5 bytes

```
Ḣ:3«Ṃ

```

Try it online!

### How it works

```
Ḣ:3«Ṃ  Main link. Argument: [a, b, c, d]

Ḣ      Head; pop and yield a.
 :3    Perform integer division by 3,
    Ṃ  Yield the minimum of [b, c, d].
   «   Take the minimum of a and the result to the right.

```

# Answer
> 7 votes
# Python 2, 23 bytes

```
lambda a,*x:min(a/3,*x)

```

Try it online!

# Answer
> 3 votes
# MATL, ~~9~~ 8 bytes

*1 byte saved thanks to @Luis*

```
I7Bh/kX<

```

**Try it at MATL Online**

**Explanation**

```
        % Implicitly grab input as an array
I       % Push the literal 3 to the stack
7B      % Push 7 and convert to binary ([1, 1, 1]) and push it to the stack
h       % Horizontally concatenate the two to create the array [3 1 1 1]
/       % Perform element-wise division
k       % Round all values towards minus infinity
X<      % Compute the minimum of the resulting array
        % Implicitly display the result

```

# Answer
> 3 votes
# Perl 6, 19 bytes

```
{min $^a div 3,|@_}

```

Try it online!

### How it works

```
{                 }  # A lambda.
     $^a             # First argument.
         div 3       # Integer division by 3.
                @_   # All regaining arguments as a list.
        ,      |     # Slipped into the outer list.
 min                 # Smallest number in the list.

```

The `$^a` and `@_` are in-place parameter declarations for the surrounding block lambda. One is a positional parameter, and the other to a slurpy parameter that takes all remaining positional arguments.

# Answer
> 2 votes
# MATLAB / Octave, 26 bytes

```
@(a)min(fix(a./[3 1 1 1]))

```

Creates an anonymous function named `ans` which you can then pass the input array as: `ans([3 1 1 1])`

Online Demo

# Answer
> 2 votes
# Cubix, 24 bytes

```
O;@sI3,>I?;^>..^.-!..;;?

```

Try it here

```
    O ;
    @ s
I 3 , > I ? ; ^
> . . ^ . - ! .
    . ;
    ; ?

```

`I` Read number from the input
`3,` Push 3 onto the stack and integer divide
`>` Redirect to the right
`I?` Read number from input and test
if 0 (end of input), `;` remove from stack. `^` redirect to top face, `O@` Output TOS and quit
if positive, `-` subtract from TOS
`?` Test. For 0 and positive `;` remove TOS, for negative `;s` remove TOS and swap top items on the stack. This keeps the lowest number at the top.
Follow arrows back to the 2nd `I` and repeat until done.

# Answer
> 1 votes
# JavaScript (ES6), 30 bytes

```
a=>Math.min(a[0]/3,...a)|0

```

## Usage

```
f=a=>Math.min(a[0]/3,...a)|0
f([2,1,1,1])

```

### Output

```
0

```

## Explanation

This function takes an array as argument, and then feeds all its elements to `Math.min` as well as the first element devided by three. Since `a[0]/3` is smaller than `a[0]` (because `a[0]` is guaranteed to be positive), we don't have to remove it from the main array. `Math.min` returns the minimum value, which is then floored and returned.

# Answer
> 1 votes
# Mathematica, 18 bytes

```
⌊#/3⌋~Min~##2&

```

Pure function taking four integer arguments and returning an integer. Computes the floor of the first argument divided by 3, then finds the minimum of that number and the remaining arguments `##2`.

# Answer
> 1 votes
## Batch, 71 bytes

```
@set/am=%1/3
@for %%n in (%*)do @set/a"n=%%n-m,m-=(n>>31)*n
@echo %m%

```

Unrolling the loop would have been 7 bytes longer.

# Answer
> 1 votes
# C#, 62 bytes

## Golfed

```
int i(int a,int b,int c,int d){return new[]{a/3,b,c,d}.Min();}

```

Pretty self-explanatory I think.

# Answer
> 0 votes
# PowerShell, 44 bytes

```
$a,$b=$args;[int]($a/3),$b|measure -mi|% Mi*

```

Try it online!

# Answer
> 0 votes
# R, 26 bytes

As an unnamed function that takes a vector of numbers as the parameter.

```
function(x)min(x,x[1]%/%3)

```

Return the min of the parameter and the first item integer divided by 3. So for an input of `7,8,9,10`, it will return the min of `7,8,9,10,2`. This was shorter than dividing the complete vector by c(3,1,1,1)

---
Tags: code-golf
---


title: Find a balanced Neighborhood

text:
# Question
Title: Find a balanced Neighborhood
Your task will be to take a and a integer representing a Levenshtein distance (the number of characters that have to be inserted, deleted or changed to make one string into another) and you must find the number of balanced strings with that distance from the original string (i.e. the neighborhood of that string).

## Stipulations

* Balanced strings will consist only of the characters `()<>[]{}`
* You will only be asked to find neighborhoods for positive even distances
* Input and output is flexible. As long as you take in all the proper data and output the correct answer without violating any loopholes I am happy with your answer.
* You may choose to divide all of your integer inputs by 2 if you choose.
* This is so the objective is to minimize the number of bytes in your answer

> This was inspired by this CMC and this answer

## Testcases

```
   Case   | Distance | Size of Neighborhood
--------------------------------------------
    ()    |    2     |         18
   ({})   |    2     |         33
   (())   |    2     |         32
    <>    |    4     |        186
   [][]   |    4     |        688
  <(){}>  |    4     |        1379
    {}    |    6     |        2270
  []{}[]  |    6     |        41097

```

Here are a few small examples with the actual neighborhoods included:

```
(), 2 :
{'', '<>', '()[]', '()()', '(())', '([])', '()<>', '{}', '{()}', '<>()', '(){}', '{}()', '<()>', '(<>)', '[()]', '[]()', '({})', '[]'}

```

---

```
({}), 2 :
{'([]{})', '()', '{}', '<({})>', '({<>})', '<{}>', '({()})', '(<>{})', '({}<>)', '({[]})', '(({}))', '({{}})', '({}[])', '{({})}', '({})()', '{}({})', '(())', '()({})', '([])', '<>({})', '({}{})', '({}){}', '({})<>', '(<{}>)', '({})[]', '((){})', '[{}]', '{{}}', '[]({})', '(<>)', '({}())', '([{}])', '[({})]'}

```

---

```
(()), 2 :
{'(())[]', '<>(())', '()', '{}(())', '{()}', '({()})', '{(())}', '(([]))', '(({}))', '(()[])', '(())<>', '((()))', '([])', '((<>))', '()(())', '(<()>)', '([()])', '[(())]', '(()){}', '(())()', '(()())', '(<>())', '(()<>)', '((){})', '<(())>', '<()>', '([]())', '(<>)', '({}())', '[()]', '({})', '[](())'}

```

---

```
<>, 4 :
{'<><<>>', '(<>)<>', '[<>][]', '<<><>>', '(){<>}', '(<>)()', '[<()>]', '<({})>', '<>()<>', '<[<>]>', '[][]<>', '<>[]<>', '<><><>', '[]<{}>', '[]<<>>', '[]<><>', '{<><>}', '[{<>}]', '<(<>)>', '(())<>', '{}<>{}', '()(<>)', '{()<>}', '(())', '{<>{}}', '(<><>)', '([])<>', '[]<[]>', '<{}<>>', '<><()>', '{()}<>', '{{}}<>', '{<>()}', '<<>>()', '{<<>>}', '<()>()', '<[]>()', '<>[<>]', '(<>())', '{}<>()', '(()<>)', '[{}]', '{{}}', '[]()', '[(<>)]', '<{}[]>', '<<>>[]', '{}<()>', '<>', '[()]<>', '<()><>', '[[]]<>', '[{}]<>', '[]<>[]', '()[<>]', '[]<>()', '{<>}{}', '{<[]>}', '<>(<>)', '(<>)[]', '<{}>()', '{}<><>', '{<>}()', '{[]}', '{[]}<>', '<<<>>>', '[]<()>', '<<[]>>', '<<{}>>', '[[]]', '()()<>', '[]{<>}', '<><[]>', '[[]<>]', '<{}()>', '<{<>}>', '<[]{}>', '{}<{}>', '<{}>[]', '()<<>>', '(<()>)', '[]{}', '{{}<>}', '{}()', '()<>[]', '<{}><>', '{[<>]}', '<><{}>', '<(())>', '<><>{}', '[()]', '<<>>{}', '{}{}<>', '[<<>>]', '<[][]>', '(<<>>)', '<[]><>', '[<>]<>', '[<>[]]', '[{}<>]', '{()}', '{<>[]}', '[]{}<>', '{(<>)}', '(<[]>)', '()[]<>', '<>{<>}', '{[]<>}', '(<>{})', '({}<>)', '[<><>]', '<><>()', '{}[<>]', '<{[]}>', '<<()>>', '<<>{}>', '([<>])', '<[]()>', '()()', '([])', '[[<>]]', '((<>))', '[](<>)', '(){}<>', '[()<>]', '<([])>', '<()()>', '[][]', '<<>[]>', '[<[]>]', '({})<>', '<{{}}>', '<[{}]>', '<{}{}>', '{}(<>)', '<<>><>', '[<>()]', '[][<>]', '({})', '{}[]<>', '{}<[]>', '<[()]>', '()[]', '<()>[]', '{{<>}}', '(<>){}', '{}{}', '({<>})', '{<()>}', '{}{<>}', '[]()<>', '<[]>[]', '(<>[])', '<[]>{}', '{}()<>', '()<[]>', '()<{}>', '{}<<>>', '<{}>{}', '{}[]', '()<>{}', '<()<>>', '[<>{}]', '{<>}[]', '<<>()>', '<><>[]', '{<{}>}', '<()[]>', '()<><>', '[<>]()', '()<>()', '{}<>[]', '<{()}>', '(<{}>)', '(){}', '()<()>', '<(){}>', '{<>}<>', '<[[]]>', '[]<>{}', '([]<>)', '<[]<>>', '[<>]{}', '<()>{}', '<>{}<>', '[<{}>]'}

```

# Answer
## Mathematica, 187 173 bytes

```
Length@Union@Select[""<>#&/@(Tuples[Characters@" ()[]<>{}",StringLength@#+#2]/." "->""),sFixedPoint[StringReplace["()"|"[]"|"{}"|"<>":>""],s]==""&&EditDistance[s,#]==#2]&

```

Brute force pure function. `#` represents the first argument (starting string) and `#2` represents the second argument (distance).

`Characters@" ()[]<>{}"` is the list of possible characters (including `" "`)

`Tuples[Characters@" ()[]<>{}",StringLength@#+#2]` is the list of all tuples of those characters with length at most the original string length plus the distance.

`Tuples[Characters@" ()[]<>{}",StringLength@#+#2]/." "->""` replaces all of the `" "` characters with the empty string.

`""<>#&/@(...)` joins all of those character lists into strings.

Next we `Select` all such strings which are balanced and which have the appropriate `EditDistance` with the following function:

```
s                                                                                String s
                                                                                 maps to
  FixedPoint[StringReplace["()"|"[]"|"{}"|"<>":>""],s]                                              the fixed point of cancelling out pairs of brackets
                                                      ==                                             equals
                                                        ""                                          the empty string
                                                          &&                                        and
                                                            EditDistance[s,#]==#2                   the distance from s to # is #2

```

Next we use `Union` to delete the duplicates and take the `Length`.
> 3 votes

---
Tags: code-golf, balanced-string
---


# Question
Title: Make a code square with your favorite word
Pick your favorite 6 letter common English word that has no repeated letters, such as `wombat`.

Write a program in an N×N grid of characters *without comments* such that **each row and column** contains all the letters of your word in lowercase in any order. The program must output a definition of your word **in 36 characters or more**.

# Rules

* Output to stdout. There is no input.
* Your word must be on Dictionary.com and only contain a-z. No proper nouns, no acronyms, no abbreviations, no contractions.
* Your program and output may only contain printable ASCII characters (hex codes 20 to 7E). (This isn't counting the necessary newlines in the program grid.)
* Comments are anything that the compiler or interpreter traditionally ignores. You may use code that does not contribute to the output or doesn't officially get executed.
* The output definition should be grammatical and accurate, but certainly may be funny or clever.
* Any row or column that at least contains your word\`s 6 unique letters in lowercase is valid. Diagonals do not matter.

# Scoring

This is code golf but since all submissions must be in the same square format you can simply specify your score with N. The lowest N wins, and of course an N below 6 is impossible. In case of ties, the highest voted answer wins.

# Example

If your word was `wombat` your program might look like this (N = 7):

```
wombatD
ombatEw
mbatFwo
bat(wom
atWwomb
tBwomba
)wombat

```

Notice that **every row *and every column*** has the characters `w` `o` `m` `b` `a` `t`.

The output might be: (40 chararacters)

```
Cute short-legged Australian marsupials.

```

# Answer
## Perl - grapes - 11

**edit:** I accidently made this 12 lines...

```
$epagsr=$";
$,=$epagsr;
/gaerp/;say
grep!/a*s/,
qw(A searpg
purple sgar
rpssg pear?
No, a sgerp
s great pse
as grape; s
eat prgpsga
up! sgarse)

```

Output:

```
A purple pear? No, a great grape; eat up!

```

---

# Update!

I eliminated a line to get it down to 11 but I had to change the sentence. Hopefully I didn't make any mistakes this time!

```
$gpasre=$";
$,=$gpasre;
/paerg/;say
grep!/a*s/,
qw(A sgrpea
purple sarg
ressp game?
No, a rgspe
s great gsp
as grape; s
eat),$spegr

```

Output:

```
A purple game? No, a great grape; eat

```

The output is 37 characters.
> 18 votes

# Answer
## Javascript - action - 15x15

"Definetly not the shortest one, but PEW PEW PEW." - James Bond

```
ction="action "
ction+="means "
actionac="PEW "
ctionact="PEW "
tionacti="PEW "
ionactio="PEW "
onaction="PEW "
nactiona="PEW "
ction+=actionac
ction+=ctionact
ction+=tionacti
ction+=ionactio
ction+=onaction
ction+=nactiona
alert(""+ction)

```

Link to the jsfiddle
Output (37 chars):

```
action means PEW PEW PEW PEW PEW PEW

```
> 47 votes

# Answer
# Befunge 93, n=13

This works by redirecting the string with `"v` and `>"`. This only works when the side-length and word-length are coprime and when the side-length is greater than 11. Right now, it works for the "word" `vwombat`, and therefore for `wombat`.

```
"laip"vwombat
wombat>"usr"v
"am "vwombat>
ombat>"nai"vw
lar"vwombat>"
mbat>"tsu"vwo
 d"vwombat>"A
bat>"egg"vwom
-"vwombat>"el
at>"tro"vwomb
"vwombat>"hs
t>"tuC"vwomba
vwombat>:#,_@

```

Outputs `Cute short-legged Australian marsupial`
> 35 votes

# Answer
# C (word : "finder", N = 16)

```
main() finder{ f
printf(finder  i
"it's defined "r
"as a t"finder d
"hing t"finder e
"hat ca"finder r
"n find other t"
"hings" finder);
finder finder f\
inder finder fi\
nder finder fin\
der finder find\
er finder finde\
r finder finder
 finder finder n
return 0;finder}

```

Compiled with GCC, with the options `-Dfinder="" -Df="" -Di="" -Dn="" -Dd="" -De="" -Dr=""`.

It outputs `it's defined as a thing that can find other things` (50 characters). I believe it follows all the rules, but feel free to tell me if there is any mistake !
> 25 votes

# Answer
### GolfScript, N = 12

```
wombat"Cute"
ombat" sho"w
mbat"rt-l"wo
bat"egge"wom
at"d Au"womb
twomb"stra"a
wom"lian "bt
ttwomb"mar"t
"sup"wbwomat
"ia"womabbtt
"ls"bawomtbt
aaawomobt"."

```

The wombat example encoded in GolfScript. Output is

```
Cute short-legged Australian marsupials.

```

as given in the question. The interesting part is that you may use most words and answers and simply insert the corresponding letters into the solution as long as you don't produce a GolfScript built-in which are very rare, `p`, `n` being to obvious ones. All other combinations lead to valid GolfScript variables which are no-ops by default.
> 21 votes

# Answer
## Befunge-98 (n=12)

I chose kelvin because it had a v in it. Outputs `kelvin is like celsius but it's lowe`

```
"ewol "vnlik
"t's"ke<ilnv
kelniv"t i"<
elnik>"ub "v
nkv"elsius"<
ln>"c eki"vl
v0ke"is l"<n
>" nivlek" v
ielnv,k4'k#<
 vivlevlnek<
 ilkkninevei
  elnkn vnle

```
> 18 votes

# Answer
## Python, n=15

Word is "canoes"

```
def canoe(s='S\
ecret weap',sno
='ce',a='ons o\
f the Can',oces
=1,oesn=1,c='a\
dian navy',cose
="""aoenscanaen
canceessanoeeca
anoasanooscanoe
noescccccaeescc
oescneocaeoesca
escaoescan"""):
 canoes=s + a+c
 print (canoes)
s=1;    canoe()

```

Output:

```
Secret weapon of the Canadian navy

```
> 11 votes

# Answer
## Perl - repeat - 11

```
$repeat=qq(
repeat);say
"repeat\n"x
length'pear
repeatrepea
epeatrepeat
peatrepeatr
eatrepeatre
atrepeatrep
trepeatrepe
repeat....'

```

Output:

```
repeat
repeat
repeat
repeat
...keeps going

```

Looking back maybe I should have made this a loop.
> 10 votes

# Answer
# Ruby, `haters`, N = 10

After hours of attempts by hand, writing a generator program, and tweaking parameters, I have finally found a solution for N = 10!

```
aser=ts=?h
tah=re=?\s
sh='Haters
nurse hate
in hardest
hearts.'
rtse=erha=
era=sh.tr'
',tah;aser
 puts erha

```

Outputs `Haters nurse hate in hardest hearts.`, exactly 36 characters. Try it online!

I chose Ruby because its variables don't need `$` (~~Perl~~), and single-quoted strings can contain newlines (~~Python~~). The fact that the `tr` method uses two of my word's letters was an unexpected bonus. The core of the program is straightforward:

```
# Store the definition, with newlines
sh='Haters
nurse hate
in hardest
hearts.'
# Transliterate newline to space
erha=sh.tr('
',' ')
# Output
puts erha

```

Getting all the letters to line up, of course, was *not* simple. I went through several variations on the same structure and learned a couple things about Ruby in the process (`tr` doesn't need parentheses, and `?\s` is another way of getting a space). There were many dead ends and several false positives. And then... success!

Here's a gist of my hacked-together generator program, if anyone's interested.
> 6 votes

# Answer
## Golfscript (n=10)

My first golfscript! It prints `kelvin is like celsius but it's lowe`

```
"kelvin is
like ce"vn
evn"lsiu"k
k"s "elvni
in"bu"kelv
"t "knviel
vl"it'"nke
nevkil"s l
o"ivnkel"w
e"lnevik

```
> 5 votes

# Answer
## GolfScript, 13x13

Not the smallest...

```
squae"A squar
"uarsquaresqu
uareq"e has f
"resuaresquar
resqa"our equ
"squresquares
quars"al side
"arequaresqua
areuq"s and r
"esqaresquare
esqur"ight an
"quaesquaresq
quar"gles..."

```

... **but** ...

```
A squar
e has f
our equ
al side
s and r
ight an
gles...

```

(Having the line-breaks within the words is intentional, because otherwise I'd have leading or trailing whitespace which would look less square.)
> 5 votes

# Answer
## Python, N=11

Word is "parent". This code is not pretty, but it works.

```
eprnt=" a "
at="person"
rnep="that"
nrpt="made"
ea= " prnt"
e="parent:"
pa =(eprnt+
at+" "+rnep
+ea[0]+nrpt
+ eprnt+at)
print(e+pa)

```

Output: `parent: a person that made a person`

Edit: Somehow I missed the fact that columns must also contain the word. In retrospect, a language that includes endline characters as part of the language was not well suited to this puzzle.
> 4 votes

# Answer
# Pip, n=14 (noncompeting)

The language is newer than the question. The word is `quines`.1

```
n_n|quine say&
qu ines     qi
as  harle quin
se?(equins)ns.
 plums|quinces
|quicken bus++
iness|q++++i u
u:++ingl es?eq
ni*:u; s|qe:",
which "Rns|que
eRL:i|quotesne
PUsn    quiet!
u|qe."print".s
JW"quines"  :)

```

Outputs the following (admittedly incomplete) definition:

> quines print quines, which print quines, which print quines, which print quines, which print quines, which print quines, which print quines, which print quines, which print quines, which print quines, which print quines, which print quines, which print quines, which print quines, which print quines, which print quines, which print quines

Try it online!

The meaningful part of the code runs thus:

```
++i          Increment i (initially set to 0)
++++i        Increment i twice
u:++i        Increment i again and assign to u (i & u are now 4)
i*:u         Multiply i by u in-place (i is now 16)
e:",         Assign the string ",\nwhich " to e...
which "Rns   after replacing the newline with a space
eRL:i        Make a list of 16 copies of e and assign back to e
ePUs         Push a space to the front of list e
e."print".s  Concatenate "print" and a space to each element of e...
JW"quines"   and join on "quines", wrapping the result in "quines"

```

The rest of the code is arbitrary no-ops. The main difficulty in the "filler" sections was never to evaluate `q`, since it will prompt the user for a line of input (not a problem on TIO, but I wanted to make it correct in all environments). I used short-circuiting logic operators `|` and `&`, and ternary `?`, to prevent `q`'s evaluation.

1 Dictionary.com has an entry for quine, with a section on the programming meaning at the bottom. Since "quine" is a countable noun, I would argue that "quines" is a valid word.
> 2 votes

# Answer
# Javascript, N = 8

My word is **alerts**.

```
s= alert
alert(s+
s+alert)
aaltrsee
leraatts
ertsalar
rtsaaela
tsaesarl

```

My code outputs the definition of the javascript alert function multiple times. Javascript's definition of alert is "function alert() { \[native code\] }".

Only the first three lines of code actually contribute to the output. The last 5 lines are syntax errors but the original rules stated that not all the code has to be executed as long as the output is correct.

Here is a link to the fiddle: http://jsfiddle.net/tze76pum/
> 1 votes

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


title: Stable marriage problem

text:
# Question
Title: Stable marriage problem
## Background

Suppose that there are `2*n` people to be married, and suppose further that each person is attracted to exactly `n` other people under the constraints that:

1. Attraction is *symmetric*; i.e. if person `A` is attracted to person `B`, then person `B` is attracted to person `A`.
2. Attraction is *antitransitive*; i.e. if person `A` and person `B` are each attracted to person `C`, then person `A` and person `B` are not attracted to each other.

Thus the network of attractions forms the (undirected) complete bipartite graph `Kn,n`. We also assume that each person has ranked the people they are attracted to. These may be represented as edge weights in the graph.

A *marriage* is a pairing `(A,B)` where `A` and `B` are attracted to each other. The marriage is *unstable* if there is another marriage where one person from each marriage could divorce their partner and marry each other and both end up with someone they ranked higher than their former partner.

## Goal

Your task is to write a complete program or function which takes each person's preferences as input and outputs a marriage for each person such that each marriage is stable.

## Input

Input may be in any convenient format; e.g., weighted graph, ordered list of preferences, dictionary/assocation, etc. You may optionally take the total number of people as input, but no other input is allowed.

## Output

Output can also be in any convenient format; e.g. list of tuples, minimal edge cover, a function which associates to each person their partner, etc. Note that the only constraint is that each marriage is stable, there are no other optimality requirements.

## Notes

1. You can find more information and an `O(n^2)` algorithm to solve this problem on Wikipedia or this Numberphile video. You are free to use any algorithm, however.
2. Standard loopholes are forbidden.
3. This is . Shortest answer (in bytes) wins.

# Answer
> 8 votes
## Mathematica, 28 bytes

On would think, this is cheating. I for myself like this:

```
Combinatorica`StableMarriage

```
* Needs to be called with the weight matrices of the preferences for men and women.
* Returns the direct indizes for the coupling.

(Yes `Combinatorica` is deprecated but it costs fewer bytes than `FindIndependentEdgeSet`)

---

**Example (GoT-like):** (To be fair - i guessed the weights...but i'm okay with the results)

```
m = {{2, 4, 3, 1}, {1, 2, 4, 3}, {3, 2, 1, 4}, {4, 2, 1, 3}};
w = {{2, 3, 4, 1}, {3, 2, 1, 4}, {3, 2, 4, 1}, {4, 1, 2, 3}};
result = Combinatorica`StableMarriage[w, m];
MapThread[
  UndirectedEdge[Show[#1, ImageSize -> 130],
    Show[#2, ImageSize -> 130]] &, {names1,
   names2[[result]]}] // TableForm

```

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


# Question
Title: print 1 to 100 without using recursion and conditions
can we print **1 to 100** without using any if conditions and loops in c&c++?

Conditon: main point is you must not use recursion...and doesnt hardcode code in it for e.g

`print(1 2 3..etc);`

# Answer
> 23 votes
## C (90) (79) (59) (47) (42) (40)

static int

```
x=1;a(){char b[8];printf("%d\n",x++);b[24]-=5*(1-x/101);}main(){a();return 0;}

```

The function `a` which prints the numbers does not call itself! I exploited a buffer overflow and changed the return address to make the program counter go over function `a` again as long as I need.

I don't know if this is considered to be a recursion, but I thought it would worth trying. This code works on my 64-bit machines with gcc 4.6, for other platforms the last statement of function `a`, could be a little different.

**Exp1:** I allocated a dummy buffer on stack `b`, and then addressed a passed-by-end location, which is the location of return address. I anticipated the distance between start of buffer and return address location from disassembly of function `a`.

**Exp2:** Expression `5*(1-x/101)`, is `5` for all `x<=100` and `0` for `x=101`. By looking at disassembly of `main` (in my case), if you decrease the return address by 5, you will set the PC to calling point of `a` again. In the updated codes, the return value of `printf` is used for checking loop condition.

**Update:** After applying ugoren's suggestions and some other changes:

```
x;a(){int b[2];b[3*(printf("%d\n",++x)&2)]-=5;}main(){a();}

```

**Update2:** After Removing function `a`:

```
x;main(){int b[2];b[6^printf("%d ",++x)&4]-=7;}

```

**Update3:**

```
x;main(b){(&b)[1|printf("%d ",++x)&2]-=7;}

```

**Update4:** Thanks to mbz :)

```
x;main(b){(&b)[3|printf("%d ",++x)]-=7;}

```

# Answer
> 15 votes
# 85

C (gcc)

```
#define c printf("%d ",i++);
#define b c c c c c
#define a b b b b b
main(i){a a a a}

```

Assuming no command line arguments were passed.

# Answer
> 10 votes
## C++ (~~159~~ 136)

With templates.

```
#include<cstdio>
#define Z(A,B,C,D)template<A>struct P B{P(){C;printf("%d ",D);}};
Z(int N,,P<N-1>(),N)Z(,<1>,0,1)int main(){P<100>();}

```

# Answer
> 7 votes
## C 71 70

Assuming the `?` operator is allowed.

```
#define f(a)a a a a a
int main(i){f(f(f(printf(i<102?"%d ":0,i++);)))}

```

Edit: `""`-\>`0`

If `?` is too similar to an if statement, then use this instead (78)

```
#define f(a)a a a a
#define g(a)f(a)a
int main(i){f(g(g(printf("%d ",i++);)))}

```

# Answer
> 3 votes
# 267

this is the best I can think of, assuming using the preprocessor is fine.

```
#include <stdio.h>
#define a(i)i,i+1,i+2,i+3
#define b(i)a(i),a(i+4),a(i+8),a(i+12)
#define c(i)b(i),b(i+16)
#define e c(1),c(33)
#define f %d %d %d %d
#define g f f f f f f f f
#define r(m) #m
#define s(m) r(m)
int main(){printf(s(g g g f),e,c(65),a(97));return 0;}

```

# Answer
> 3 votes
# C++ (115)

```
#include <cstdio>
template<int i>void p(){printf("%d ",i);p<i+1>();}
template<>void p<101>(){}
int main(){p<1>();}

```

# Answer
> 3 votes
# MATLAB/Octave, (5 chars)

```
1:100

```

# Answer
> 3 votes
## PowerShell (6 characters)

1..100

# Answer
> 2 votes
# Python 3 (25)

```
print(list(range(1,101)))

```

# Answer
> 2 votes
# Python 2 (12)

```
>>> range(1,101)
[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]

```

# Answer
> 1 votes
# Ruby (11) \[non-competitive\]

```
p *(1..100)

```

(Thanks to histocrat)

Previous 14-character solution:

```
p *1.upto(100)

```

This is a non-competitive answer (not C/C++ as requested)

# Answer
> 0 votes
**Scala (22)**

```
1 to 100 foreach print

```

# Answer
> 0 votes
# Perl 6 (10)

```
print ^101

```

If one wants to be able to read the numbers and therefore spaces between the numbers would be nice, the following will do the trick.

```
say ~ ^101

```

# Answer
> 0 votes
## Perl (65)

Here's a non-trivial Perl approach (not like `say for 1 .. 100`). The program uses perl's regular expression engine to count its own characters (two times), and that's the reason why I couldn't golfify the content of `$k`. It tries to find a (minimal, non-greedy) group of arbitrary single characters until `(*FAIL)`.

```
$k='$k =~ /^(.+?)(?{print length($1) . "\n"})(*FAIL)/#'x2;eval$k;

```

The output is a list of all integers from 0 to 100 with newlines.

# Answer
> 0 votes
# Pygmy, (18 characters)

```
alert|[1 100].fill

```

# Answer
> 0 votes
# Python 2 (39 chars)

```
p=lambda d:print d+1,;map(p,range(100))

```

# Python 3 (53 chars)

```
p=lambda d:print(d+1,end=' ');set(map(p,range(100)))

```

or print numbers on separate lines (28 char)

```
set(map(print,range(1,101)))

```

or (tested in Python 3.3.2, set items printing in ascending order - 24 chars)

```
print(set(range(1,101)))

```

# Answer
> 0 votes
## Bash 13

```
echo {1..100}

```

Some more text so it posts.

# Answer
> 0 votes
# JavaScript (ES6), 38 bytes

```
alert([...Array(101).keys()].slice(1))

```

Creates an array of length 101, uses the spread operator to put the array keys (`0` to `100`) into an array, removes the first element (`0`) then `alert`s the numbers within the array.

# Answer
> -1 votes
# Python - 61

Looping? No this is *list comprehension*.

```
d=[0,1,2,3,4,5,6,7,8,9];print[x*10+y+1 for x in d for y in d]

```

# Answer
> -1 votes
# Hassium, 31 Bytes

```
func main()print(range(1, 100))

```

Run online and see expanded here

# Answer
> -1 votes
# JAVA, 52 chars

```
IntStream.range(1,101).forEach(System.out::println);

```

---
Tags: code-golf, c
---


# Question
Title: Change the Code, Change the Sequence: Cops
*This is a challenge. For the robbers thread, go here.*

This challenge involves two OEIS sequences chosen by the cops -- **S1**, **S2** -- and how well those sequences can be golfed and obfuscated.

### The Cops' Challenge

Your challenge as a cop is to pick a freely available language, and two OEIS sequences. Then, write code **A** in that language that takes input *n* and produces S1(n). When that code is modified by a Levenshtein distance of **X** characters (with X no more than `0.5 * (length A)`), and turned into code **B** in the same language, it must then produce S2(n). You must actually write this code **B**, but don't reveal it until your challenge is safe (see below).

The cops' submissions must include the language name, the full code **A**, the byte-count of **A**, the **X** value of how many changes to get to their secret **B** code, and the chosen **S1** and **S2** sequence numbers. You can choose whether each sequence is 0-indexed or 1-indexed, but please specify that in your submission.

To crack a particular submission, robbers must come up with a program **C** in the same language (and version) that produces S2(n) and is **Y** character changes away from **A** (with `Y <= X`). Robbers do not necessarily need to find the exact same **B** code that the cop (secretly) produced.

### Winning and Scoring

If your cop answer has not been cracked within 7 days (168 hours), you may reveal your own **B** solution, at which point your answer is considered safe. As long as you don't reveal your solution, it may still be cracked by robbers, even if the 7 days have already passed. If your answer does get cracked, please indicate this in the header of your answer, along with a link to the corresponding robber's answer.

Cops win by having the uncracked submission with the shortest **A**. If tied, then the smallest **X** will be used as tie-breaker. If still tied, the earlier submission will win.

### Further Rules

* You must not use any built-ins for hashing, encryption, or random number generation (even if you seed the random number generator to a fixed value).
* Either programs or functions are allowed, but the code must not be a snippet and you must not assume a REPL environment.
* You may take input and give output in any convenient format. The input/output methods must be the same for both sequences.
* The definitive calculator for the Levenshtein distance for this challenge is this one on Planet Calc.
* In addition to being a CnR challenge, this is so all usual golfing rules apply.

# Answer
# ~~Brain-Flak, 28 bytes, Distance of 4, A002817, A090809~~ Cracked

This answer uses 1-indexing

```
(({({}[()])}{}){({}[()])}{})

```

Try it online

For anyone interested there are 27475 valid Brain-Flak programs with Levenshtein distance 4 from this program and 27707 with distance 4 or less. So a brute force solution would be feasible on a consumer grade computer.
> 10 votes

# Answer
# , 33 characters, 13 bytes, X = 10, A000124A000142, Safe

```
171720514057071616777023671335133

```

Try it online!

The Levenshtein distance is measured in terms of characters, so I've written the program in terms of the characters it contains above (and Try it online!, including the language itself, is happy to run programs encoded in ASCII). However, the program is stored in disk using 7's sub-byte encoding, meaning that the program itself is actually the following hexdump (thus 13 bytes long):

```
00000000: 3cf4 2982 f1ce 3bfe 13dc b74b 7f         <.)...;....K.

```

(Because the Levenshtein distance is measured in terms of characters, you aren't necessarily adding/deleting/changing 10 *bytes* here, so it's probably best to work with the original ASCII.)

The program as written implements A000124 (triangular numbers + 1); any crack must implement A000142 (factorials). Both programs take input from stdin (as decimal integers), write their output to stdout, and treat an input of 1 as meaning the first element of the sequence (and an input of 2 as the second element, etc.).

Hopefully the very high X value will stop people brute-forcing the program, this time (which is always a risk with cops-and-robbers entries in 7).

## The solution

```
177172051772664057074056167770236713351353

```

Try it online!

Differences from the original:

```
17 172051     405707 **1** 61677702367133513 3
17**7**172051**77266**405707**405**61677702367133513**5**3

```

I don't have explanations prepared for how these work, so it's going to take me a while to get an explanation up, as I'm going to have to figure it out from almost-scratch. Hopefully there will be an explanation eventually.
> 6 votes

# Answer
## Pyke, Levenshtein distance of 1, A036487, A135628.

### Cracked!

```
X*e

```

Try it here!
> 5 votes

# Answer
~~Perl 6, 10 bytes, X = 1, A000012A001477~~

### Cracked!

```
*[0]o 1***

```
* **S1** = A000012 = `1,1,1,1,1,...` = The all 1's sequence. *(0-indexed)*
* **S2** = A001477 = `0,1,2,3,4,...` = The nonnegative integers. *(0-indexed)*

Try it online!

Confirmed to work with Perl 6 release 2017.01, and with the Perl6 version running on TIO.

(**A** could be further golfed to `1***` – I hope it it's also allowed as it is.)
> 4 votes

# Answer
~~Perl 6, 13 bytes, X = 1, A161680A000217~~

### Safe!

```
{[+] [,] ^$_}

```
* **S1** = A161680 = `0 0 1 3 6 10 15 21...` = Zero followed by the triangular numbers.
* **S2** = A000217 = `0 1 3 6 10 15 21 28 ...` = The triangular numbers.
* Zero-indexed.

Try it online!

(Confirmed to work with the Perl 6 version running on TIO.)

### Solution

```
{[+] [\,] ^$_}

```

How the original works:

```
{           }  # A lambda.
          $_   # Lambda argument.                     e.g. 4
         ^     # Range from 0 to n-1.                 e.g. 0, 1, 2, 3
     [,]       # Reduce with comma operator.          e.g. 0, 1, 2, 3
 [+]           # Reduce with addition operator.       e.g. 6

```

How the solution works:

```
{            } # A lambda.
           $_  # Lambda argument.                     e.g. 4
          ^    # Range from 0 to n-1.                 e.g. 0, 1, 2, 3
     [\,]      # Triangle reduce with comma operator. e.g. (0), (0,1), (0,1,2), (0,1,2,3)
 [+]           # Reduce with addition operator.       e.g. 10

```

Exploits the fact that numeric operators like addition treat a list as its number of elements, so in the example the sum is `1 + 2 + 3 + 4 = 10`.

And yeah, the "Reduce with comma operator" no-op in the original is kinda skirting the code-golf rules, but I prefer to look at it as a silly algorithm which has been golfed as much as possible (whitespace etc.) for what it is... :)
> 3 votes

# Answer
# Jelly, 11 bytes, X = 5, A005185A116881

```
ịḣ2S;
1Ç¡ḊḢ

```

This is a full program that takes an integer as command-line argument and prints an integer.

Both sequences are indexed as on OEIS, i.e, A005185 is 1-indexed and A116881 is 0-indexed.

Try it online!
> 2 votes

# Answer
## Javascript, 41 bytes, Distance of 3, A061313, A004526, Cracked

```
f=x=>{return x>1?x%2?f(x+1)+1:f(x/2)+1:0}

```

Try it Online

Uses 1 based indexing, solution uses 0 based indexing.

Once again, a different solution...

```
f=x=>{return x>1?x<2?f(x-1)+1:f(x-2)+1:0}

```
> 2 votes

# Answer
## Pyke, Levenshtein distance of 2, A008788, A007526

### Cracked!

```
'th^

```

Try it here!

Let's get slightly harder shall we?

The first answer is 1 based and the crack is 0 based.
> 1 votes

# Answer
~~Perl 6, 19 bytes, X = 1, A000045A000035~~

### Cracked!

```
{(0,1,*+*...*)[$_]}

```
* **S1** = A000045 = `0 1 1 2 3 5 8 13 21 34...` = "Fibonacci numbers". (*0-indexed*)
* **S2** = A000035 = `0 1 0 1 0 1 0 1 0 1...` = "Period 2". (*0-indexed*)

Try it online!

(Confirmed to work with the Perl 6 version running on TIO.)
> 1 votes

# Answer
# ~~WolframAlpha, 18 bytes, X = 1~~

**Cracked by math\_junkie!**

```
(sum1to#of n^1)*2&

```

Sometimes WolframAlpha will actually be able to display a pure function like this in functional form (other times it gets confused); but it can be cheerfully invoked with a given input—for example, `(sum1to#of n^1)*2&@5` yields `30`.

**S1** = A002378 (pronic numbers)

**S2** = A000537 (sum of the first `n` cubes)

Both sequences are 0-indexed.
> 1 votes

# Answer
# Javascript, 15704 bytes, distance of 2, A059841 and A000004 \- cracked

This solution is extremely long, so you can find the full code at this github gist.

The original answer (this one) is 1 indexed. (I know this is way too long, it is just for fun.)
> 1 votes

# Answer
# Brain-Flak, 16 bytes, Levenshtein distance of 4, A000217 and A002378 -- Cracked by Martin Ender!

```
({({}[()])()}{})

```

Try it online!

This should be fairly easy to crack.
> 1 votes

# Answer
## Javascript, 30 bytes, Distance of 4, A000290, A000079, **-**Cracked!

```
f=x=>{return x?2*x-1+f(x-1):0}

```

0-based indexing

@Kritixi Lithos's solution was actually different from mine

```
f=x=>{return x?f(x-1)+f(x-1):1}

```

Try it online
> 0 votes

# Answer
# Javascript (ES6), distance is 1, A000079 and A000004 \- cracked

```
as=function(){ return 2*2**((11)*-1*~arguments[0]/11-(4-(as+[]).length%89))-(as+[]).length%7}

```

The original answer (this one) is 0 based. Now that it has been cracked, here is the original B function:

```
as=function(){ return 2*2**((1^1)*-1*~arguments[0]/11-(4-(as+[]).length%89))-(as+[]).length%7}

```
> 0 votes

# Answer
~~Perl 6, 7 bytes, X = 2, A059841A001477~~

### Cracked!

```
+(*%%2)

```
* **S1** = A059841 = `1 0 1 0 1 0 1 0...` = "\*Period 2: Repeat (1,0)". *(0-indexed)*
* **S2** = A001477 = `0 1 2 3 4 5 6 7...` = "The nonnegative integers". *(0-indexed)*

Try it online!

(Confirmed to work with the Perl 6 version running on TIO.)
> 0 votes

# Answer
# Java 7, Levenshtein distance of 4, A094683, A000290, Cracked

```
int x{double r=1;for(int i=0;i<42;i++)r=r/2+n/r/2;int k=(int)((int)n*(float)n/Math.pow(n,(Math.sin(n)*Math.sin(n)+Math.cos(n)*Math.cos(n))/2));return n%4%2==(int)Math.log10(Math.E)/Math.log((double)'H'-'@')?(int)r:k;}

```

0-indexed.
Try it here!
> 0 votes

---
Tags: code-golf, sequence, cops-and-robbers
---