# Question
Title: Advent Challenge 1: Help Santa unlock his present vault!
Next \>\>

Descriptive Keywords (for searching): Make Two Matrices Equivalent, Overlap, Array, Find

# Challenge

Santa has had a history of elves stealing presents from his vault in the past, so this year he designed a lock that is very hard to crack, and it seems to have kept the elves out this year. Unfortunately, he has lost the combination and he can't figure out how to open it either! Fortunately, he has hired you to write a program to find the combination. It doesn't need to be the shortest one, but he needs to find it as fast as possible!

He has a very strict schedule and he can't afford to wait for very long. Your score will be the total run-time of your program multiplied by the number of steps your program outputs for the scoring input. Lowest score wins.

# Specifications

The lock is a square matrix of 1s and 0s. It is set to a random arrangement of 1s and 0s and needs to be set to a specified code. Fortunately, Santa remembers the required code.

There are a few steps he can perform. Each step can be performed on any contiguous sub-matrix (that is, you must select a sub-matrix that is entirely bounded by a top-left and bottom-right corner) (it can be a non-square sub-matrix):

1. Rotate right 90 degrees\*
2. Rotate left 90 degrees\*
3. Rotate 180 degrees
4. Cycle each row `n` elements right or left (wraps)
5. Cycle each column `m` elements up or down (wraps)
6. Flip Horizontally
7. Flip Vertically
8. Flip on the Main Diagonal\*
9. Flip on the Main Anti-diagonal\*

\*only if the sub-matrix is square

Of course, he can also perform these steps on the entire matrix. Since 1s and 0s can only be swapped on the matrix but the value of a square cannot be directly changed, the number of 1s and 0s is the same for the start and end configuration.

# Formatting Specifications + Rules

You will be given the input as two square matrices (starting position and ending position) in any reasonable format you want. The output should be a sequence of these steps in any readable format. Since this isn't code-golf, please make it an easily verifiable format, but that's not a strict requirement. You can choose to take the side-length of the matrices in the input if you want.

Your program will be run on my computer (Linux Mint, exact version details available upon request if anyone cares :P) and I will time it based on the amount of time between the time I press "enter" on the command line and when the command exits.

# Test Cases

```
1 0 0 1    0 0 0 0
0 1 1 0 -> 0 0 0 0
0 1 1 0 -> 1 1 1 1
1 0 0 1    1 1 1 1

```
1. Take the entire matrix. Cycle each column up 1.
2. Take the middle two columns as a sub-matrix. Cycle each column down 2.

```
1 0 1 0 1    0 1 0 1 0
0 1 0 1 0    1 0 1 0 1
1 0 1 0 1 -> 0 1 1 1 0
0 1 0 1 0    1 0 1 0 1
1 0 1 0 1    0 1 0 1 0

```
1. Take the entire matrix. Cycle each column down 1.
2. Take the middle column. Cycle it down 2.
3. Take the top 2 rows. Flip it vertically.
4. Take the top row's rightmost 2 elements. Swap them (rotate right/left 1, flip horizontally).
5. Take the top row's leftmost 2 elements. Swap them.

There might be more efficient methods, but that doesn't matter. Feel free to point them out in the comments if you find one though :)

# Judging Test Case

This test case will be used to judge your submission. If I believe that an answer is specializing for the test case too much, I have the right to repick a random input and rejudge all answers with the new case. The test case can be found here where the top is the start and the bottom is the desired configuration.

If I believe answers are specializing too much, the MD5 of the next test case is `3c1007ebd4ea7f0a2a1f0254af204eed`. (This is written here right now to liberate myself from accusations of cheating :P)

Standard Loopholes Apply. No answer will be accepted. Happy coding!

Note: I drew inspiration for this challenge series from Advent Of Code. I have no affiliation with this site

You can see a list of all challenges in the series by looking at the 'Linked' section of the first challenge here.

# Answer
# Java

```
import java.util.Arrays;

public class SantaMatrix4 {

	public static void flipV(int[][] matrix, int row1, int col1, int row2, int col2) {
		for (int row = row1; row <= (row2 - row1) / 2 + row1; row++) {
			for (int col = col1; col <= col2; col++) {
				int tmp = matrix[row][col];
				matrix[row][col] = matrix[row2 - row + row1][col];
				matrix[row2 - row + row1][col] = tmp;
			}
		}
	}

	public static void flipH(int[][] matrix, int row1, int col1, int row2, int col2) {
		for (int row = row1; row <= row2; row++) {
			for (int col = col1; col <= (col2 - col1) / 2 + col1; col++) {
				int tmp = matrix[row][col];
				matrix[row][col] = matrix[row][col2 - col + col1];
				matrix[row][col2 - col + col1] = tmp;
			}
		}
	}

	public static void main(String[] args) {
		int counter = 0;
		int n = Integer.parseInt(args[counter++]);
		int[][] matrix1 = new int[n][n];
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				matrix1[i][j] = Integer.parseInt(args[counter++]);
			}
		}

		int[][] matrix2 = new int[n][n];
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				matrix2[i][j] = Integer.parseInt(args[counter++]);
			}
		}

		int[] ops = new int[5 * matrix1.length * matrix1.length * 2];
		int numOps = 0;
		int opsI = 0;

		for (int row = 0; row < n; row++) {
			for (int col = 0; col < n; col++) {
				int goal = matrix2[row][col];
				boolean gotIt = false;

				//Look for required number to the right
				for (int i = row; i < n && !gotIt; i++) {
					for (int j = col; j < n && !gotIt; j++) {
						if (i == row && j == col) continue;
						if (matrix1[i][j] == goal) {
							flipH(matrix1, row, col, i, j);
							flipV(matrix1, row, col, i, j);
							ops[opsI++] = 1;
							ops[opsI++] = row;
							ops[opsI++] = col;
							ops[opsI++] = i;
							ops[opsI++] = j;
							numOps++;

							gotIt = true;
						}
					}
				}

				//Look for required number below and to the left
				for (int i = row + 1; i < n && !gotIt; i++) {
					for (int j = 0; j < col && !gotIt; j++) {
						if (matrix1[i][j] == goal) {
							flipH(matrix1, i, j, i, col);
							ops[opsI++] = 2;
							ops[opsI++] = i;
							ops[opsI++] = j;
							ops[opsI++] = i;
							ops[opsI++] = col;

							flipV(matrix1, row, col, i, col);
							ops[opsI++] = 3;
							ops[opsI++] = row;
							ops[opsI++] = col;
							ops[opsI++] = i;
							ops[opsI++] = col;

							numOps += 2;
							gotIt = true;
						}
					}
				}

			}
		}

		System.out.println(Arrays.toString(ops));
		System.out.println(numOps);
	}
}

```

Slightly faster hard-coded version: Try it online!

Input is space separated integers via the command line. The first integer is the width of the two matrices. The remaining integers are their elements, row-by-row.

Every permutation of a matrix can be obtained with just the horizontal flip and vertical flip operators, so I ignored the rest except for replacing a consecutive vFlip and hFlip in the same region with a rotation by 180 degrees.

The program scans through each element. Whenever we encounter an element that has the wrong bit, it looks further ahead through the array to find a spot that has the correct bit. I've divided the search region in two: those with an equal or larger column coordinate, and those with a smaller column coordinate. Note that the latter must have a larger row coordinate based on the way we're traversing the array. If we find a correct bit in the first search region, we can just rotate by 180 degrees the sub-matrix spanning the two elements for a total of one operation. If it's in the second region, we can use a horizontal flip to move the correct bit to the same column as the wrong bit and then vertically flip the sub-matrix spanning the two for a total of two operations.

The output of the program is an array that should be mentally split into groups of five. Each group is (i, row1, col1, row2, col2) where i is 0 for a no-op, 1 for a rotation by 180 degrees, 2 for a horizontal flip, and 3 for a vertical flip. The remaining 4 components describe the region over which the operation runs. I am not sure if this is a readable format.

For the given test case, I get 258 operations and two to three milliseconds on my computer.
> 1 votes

---
Tags: code-challenge, array, optimization, binary-matrix
---


# Question
Title: How to improve Ruby code under some restrictions
I'm (still) trying to make another submission to the Largest Number Printable question, and I've got the following bit of code:

```
f=->a{b,c,d=a;b ?a==b ?~-a:a==a-[c-c]?[[b,c,f[d]],~-c,b]:b:$n}
h=[],$n=?~.ord,[]
h=f[h]until h==p($n+=$n)-$n

```

Ungolfed:

```
f=->{b,c,d=a
if b
  if a==b # a is not an array
    return a-1
  elsif a==a-[0] # a does not contain 0
    t = [b,c,f[d]]
    return [t,c-1,b]
  else # a is an array containing 0
    return b
  end
else # if a == []
  return $n
end}

$n = 126
h = [[],n,[]]

until h==0 do
  $n += $n
  p $n
  h = f[h]
end

```

The conditions I'm working with:

* Maximum 100 bytes.
* No digits allowed in my code.

My code is currently at 108 bytes, but I can't figure out how to golf it further.

The `h==p($n+=$n)-$n` may be replaced with `h==0`, but I can't use digits and I still need to print `$n` and apply `$n+=$n` in the `until` loop.

I'm also satisfied with code that replaces `$n+=$n` with `$n+=1`, but I can't use digits unfortunately.

Any suggestions?

# Answer
# 100 bytes

For my purposes, this is good enough.

```
h=[],n=?~.ord,n
f=->a{b,c,d=a;b ?a==b ?~-a:a==a-[c-c]?[[b,c,f[d]],~-c,b]:b:p(n+=n)}
h=f[h]until h==n

```

Replacing `h==0` with `h==n` will not cause the program to fail to terminate, which is what I needed.

Also improves on Jordan's answer by declaring `h` and `n` in the same line.
> 2 votes

# Answer
# 105

You can save three bytes by declaring `n` as a local variable (instead of a global) before `f`:

```
n=?~.ord
f=->a{b,c,d=a;b ?a==b ?~-a:a==a-[c-c]?[[b,c,f[d]],~-c,b]:b:n}
h=[],n,[]
h=f[h]until h==p(n+=n)-n

```
> 2 votes

---
Tags: code-golf, tips, ruby
---


title: Implement simplified kerning

text:
# Question
Title: Implement simplified kerning
## Introduction

Kerning means adjusting the spacing between the letters of a text. As an example, consider the word `Top` written with the following three glyphs:

```
##### ..... .....
..#.. ..... .....
..#.. ..##. .###.
..#.. .#..# .#..#
..#.. .#..# .#..#
..#.. ..##. .###.
..... ..... .#...
..... ..... .#...

```

We could just fill the gaps between the glyphs with dots and be done with it, but the gaps somehow look too wide. Instead, we slide the glyphs to the left so that they almost touch:

```
#####........
..#..........
..#..##..###.
..#.#..#.#..#
..#.#..#.#..#
..#..##..###.
.........#...
.........#...

```

This looks much better! Note how the bar of `T` is on top of the left border of `o`. In this challenge, your task is to implement a simple kerning program for such rectangular glyphs.

## The kerning process

Consider two rectangular 2D character arrays of `.` and `#` of the same shape. In our simple kerning process, we first place the arrays side by side, with one column of `.`s in between. Then, we move each `#` in the right array one step to the left, until some `#`s of the left and right array are orthogonally or diagonally adjacent. The outcome of the kerning is the step *before* we introduce adjacent `#`s. Your task is to implement this process.

Let's take an example:

```
Inputs:
..###
#....
#....
..##.

...#.
...##
..###
....#

Process:
..###....#.
#........##
#.......###
..##......#

..###...#.
#.......##
#......###
..##.....#

..###..#.
#......##
#.....###
..##....#

..###.#.
#.....##
#....###
..##...#

..####.
#....##
#...###
..##..#

```

In the last array, we have new adjacent pairs of `#`s, so the second-to-last array is the result of the kerning process.

## Input and output

For simplicity, you only need to handle kerning of **two** glyphs. Your inputs are two rectangular 2D arrays, in one of the following formats:

* 2D arrays of integers, with 0 standing for `.` and 1 for `#`.
* Multiline strings over `.#`.
* Arrays of strings over `.#`.
* 2D arrays of the characters `.#`.

If the inputs are taken as a single string, you can use any reasonable delimiter. However, the delimiter should go between the two arrays, meaning that you are not allowed to take the two inputs already paired row-by-row.

Your output is the result of the kerning process applied to these two arrays, which is a rectangular 2D array in the same format as the inputs. You are allowed to add or remove any number of leading or trailing columns of `.`s, but the output **must** be rectangular and have the same height as the inputs. It is guaranteed that the kerning process ends before the left edge of the second input slides over the left edge of the first input.

## Rules and scoring

The lowest byte count in each programming language wins. Standard rules apply.

## Test cases

To help with copy-pasting, these test cases are given as lists of strings.

```
["#"] ["#"] -> ["#.#"]
["#.","..",".#"] ["##","..","##"] -> ["#..##",".....",".#.##"]
["..#","#..","#.."] ["...","..#","###"] -> ["..#..","#...#","#.###"]
["###.","##..","#...","...."] ["....","...#","..#.",".#.."] -> ["###..","##..#","#..#.","..#.."]
["..##...","#......","#......"] [".....##",".....##",".#...#."] -> ["..##..##","#.....##","#.#...#."]
["...#.",".....",".....",".....","....#"] [".....","....#","#....",".....","....."] -> ["...#..",".....#",".#....","......","....#."]
["..#..",".....",".....",".....","....#"] [".....","....#","#....",".....","....."] -> ["..#..","....#","#....",".....","....#"]
["######","#.....","#.....","#.....","######"] ["......",".....#",".#...#",".....#","......"] -> ["######..","#......#","#..#...#","#......#","######.."]
["######","#.....","#.....","#.....","######"] ["......","......",".#....","......","......"] -> ["######","#.....","#.#...","#.....","######"]
["#...#","#..#.","#.#..","##...","#.#..","#..#.","#...#"] ["...#.","..#..",".#...",".#...",".#...","..#..","...#."] -> ["#...#..#","#..#..#.","#.#..#..","##...#..","#.#..#..","#..#..#.","#...#..#"]

```

# Answer
> 8 votes
# APL (Dyalog Classic), ~~40~~ 39 bytes

-1 thanks to Erik the Outgolfer

```
{⌈⌿↑⍺(⍉(1-⌈/+⌿+∘×⍨2⌈/0,+/⌈\↑(⌽⍺)⍵)↑⍉⍵)}

```

Try it online!

# Answer
> 2 votes
# Python 3, 154 bytes

```
lambda a,b,p=".":[c.rstrip(p)+d.lstrip(p).rjust(max(len((d+c).strip(p))for(c,d)in zip((a*3)[1:],b[:-1]+b+b[1:]))+1-len(c.rstrip(p)),p)for(c,d)in zip(a,b)]

```

Try it online!

# Answer
> 2 votes
# Retina, 223 bytes

```
+`(.+)¶(¶(.+¶)*)(\W+(¶|$))
$2$1i$4
T`.`i`\.*i\.*
+`(¶(.)*#.*i.*¶(?<-2>.)*)i
$1@
+`(¶(.)*)i(.*¶(?<-2>.)*(?(2)(?!))#.*i)
$1@$3
T`i@`.`i*[#@]+i
mT`.`i`\.+i+$
msT`i`.`.*^\W+$.*
+`(\b(i+)\W+\2i*)i
$1.
+s`\bi((i+).+\b\2\b)
.$1
i

```

Try it online! Link includes test cases plus header script to reformat them to its preferred input format of two newline-delimited strings. This seems overly long yet there's probably an edge case that I've overlooked, but it does at least pass all of the test cases now. Explanation:

```
+`(.+)¶(¶(.+¶)*)(\W+(¶|$))
$2$1i$4

```

Join the two input arrays together using a letter `i` as a separator. (This allows use of `\W` and `\b` later on.)

```
T`.`i`\.*i\.*

```

Change all the `.`s to `i`s at the join.

```
+`(¶(.)*#.*i.*¶(?<-2>.)*)i
$1@

```

Change all `i`s below `#`s to `@`s.

```
+`(¶(.)*)i(.*¶(?<-2>.)*(?(2)(?!))#.*i)
$1@$3

```

Change all `i`s above `#`s to `@`s.

```
T`i@`.`i*[#@]+i

```

Change all the `@`s to `.`s, plus all the `i`s adjacent to `@`s or `#`s.

```
mT`.`i`\.+i+$

```

If there is no `#` after an `i`, then change the adjacent `.` back to an `i` again.

```
msT`i`.`.*^\W+$.*

```

If there is a line with no `i`s, change all the `i`s to `.`s, as there is nothing to do here.

```
+`(\b(i+)\W+\2i*)i
$1.

```

Calculate the minimum number of `i`s on any line.

```
+s`\bi((i+).+\b\2\b)
.$1

```

Propagate to the other lines.

```
i

```

Delete the `i`s, thus performing the required kerning.

---
Tags: code-golf, grid
---


title: The Microwave Challenge

text:
# Question
Title: The Microwave Challenge
Inspired by this comment.

# Input

The number of seconds on the timer.

# Output

Here's our basic microwave:

```
 _____________________________________________________________
|                                             |  ___________  |
|                                             | | [display] | |
|     ___________________________________     | |___________| |
|    |                                   |    | |   |   |   | |
|    |                                   |    | | 1 | 2 | 3 | |
|    |                                   |    | |___|___|___| |
|    |                                   |    | |   |   |   | |
|    |                                   |    | | 4 | 5 | 6 | |
|    |                                   |    | |___|___|___| |
|    |                                   |    | |   |   |   | |
|    |                                   |    | | 7 | 8 | 9 | |
|    |                                   |    | |___|___|___| |
|    |                                   |    | |   |       | |
|    |                                   |    | | 0 | Start | |
|    |                                   |    | |___|_______| |
|    |                                   |    |  ___________  |
|    |___________________________________|    | |           | |
|                                             | |           | |
|                                             | |___________| |
|_____________________________________________|_______________|

```

You should replace `[display]` with:

* The time left to cook in the format `minutes:seconds` if there is any time left.
* The system time in `hours:minutes` if the time left is 0.

# Rules

* The display can be aligned in either direction, but the vertical bars need to align with the ones above them.
* You may assume that the input will never be negative and never exceed 59,999,999.
* No leading zeroes before a cook time. Remove the minutes and the colon for inputs less than 60.
* Use 12-hour time UTC with no leading zeroes for the system time.
* Trailing whitespace is allowed.
* Since this is , the shortest answer in bytes wins.

# Display test cases

You should, of course, print the entire microwave along with the display, and it should work for any input within the boundaries, but here are some test cases for the display:

```
Input     Display
100       1:40
59        59
60        1:00
120       2:00
59999999  999999:59
1         1
0         [show system time]

UTC Time  Display
00:00     12:00
01:00     1:00
13:04     1:04

```

# Answer
# SOGL V0.12, ~~151~~ 150 bytes

```
╔*:@ΚG┐∙+;┐Κ+Γ╬5□
‽uS9w'+*;5wι+}:'+÷;'+%lH⁵!+‽ 0Κ}⁴‽ι}⁰ :∑ā;'!3ž"∑⅓/«juΒ  v←>k─z“M»─4n{_□}4Δ№{' ;3*I:A26□'$a22□}'(7«■  _čž'&'¹"<Ξ‘⁾žL∫L%F3‰4*'℮+f3÷⁽3*ž

```

Try it Here!

Explanation:

```
                □  a function which draws a rectangle
                   uses of the stack [xPos, yPos, height-1, (width+1)/2]
                   the width everywhere luckily is an odd number
╔*                 repeat "_" width times
  :                create a duplicate of that
   @Κ              prepend a space to it
     G             get the height on top of the stack
      ┐∙           repeat "|" vertically that many times
        +          add that below the " ___..."
         ;         get the other copy of the underscores
          ┐Κ       prepend "|" to it
            +      and add that below the rest
             Γ     palindromize horizontally with 1 overlap
              ╬5   place that at the coords [xPos; yPos], without overwriting spaces

system time
‽            }  if the input isn't 0
 uS               push date & time stuff — [year, month, day, hour, minute, second, milliscond, weekday, hours in 12-hour time, am(= 0)/pm(= 1)]
   9w             get the 9th element — hours in 12-hour time
     '+*          multiply by 60
        ;         get the array on top again
         5w       get the 5th item — minutes
           ι      pop the array
            +     add the minutes to hours*60

time formatting
:                           duplicate the time (result of above or input)
 '+÷                        divide by 60
    ;                       get the other time copy
     '+%                    mod by 60
        l                   get the length of the minutes
         H                  decrease it — truthy if the minutes are a single digit
          ⁵!                negate the hours — truthy if the hours aren't 0
            +               add those — acts like OR — truthy if minutes are a single digit or hours aren't 0
             ‽   }          if not that
               0Κ             prepend 0 to the minutes
                  ⁴         get a copy of the hours
                   ‽ }      if equal to 0
                    ι         pop the hours
                      ⁰     wrap the stack in an array
                       :∑   join with ":"

ā;      push an empty array below the time — the main canvas
  '!    push 51
    3   push 3
     ž  at [51; 3] in the canvas insert the time

main microwave body
 "...“           push 196046633463872206014875356167606
      M»─        base 50 decode — [1,1,19,31,6,4,13,18,1,1,19,23,49,2,1,6,49,17,2,6]
         4n      group 4 items — [1,1,19,31],[6,4,13,18],[1,1,19,23],[49,2,1,6],[49,17,2,6]
           {  }  for each group
            _      put the arrays contents on the stack
             □     execute the rectangle making function

boxes for the numbers
4Δ                      push [1,2,3,4]
  №                     reverse — [4,3,2,1]
   {                 }  for each
    ' ;                   push 49 below the current number — X pos
       3*                 multiply the current number by 3
         I                and increment it — Y pos
          :A              save a copy of that on variable A (for the next rectangle)
            26□           create a rectangle at [49; cnum*3+1] with width 11 and height 3
               '$         push 53 — X pos
                 a        push A — Y pos
                  22□     create a rectangle at [53; cnum*3+1] with width 3 and height 3
'(7«■  _              push 57, 14 and "  _"
        č             chop the string into chars (aka make it vertical)
         ž            insert that at [57; 14] in the canvas
          '&'¹"..‘    push 55, 15, "start"
                  ⁾   uppercase the first letter of "start"
                   ž  insert that at [55; 15] in the canvas

number inserting
L∫                   for each in 1..10, pushing counter
  L%                   push counter % 10 — the drawn digit
    F3‰                push (counter-1)%3 + 1
       4*              multiply that by 4
         '℮+           and add 47 — X position
            f3÷        floor divide the 0-based counter by 3
               ⁽       increment by 2
                3*     multiply by 3
                  ž    insert it in the main canvas

```
> 3 votes

# Answer
# JavaScript (ES6), ~~345~~ 342 bytes

*Saved 2 bytes thanks to @StephenLeppik*

```
n=>[...'lmnopqsuvwxyz{}~'].reduce((s,c)=>(x=s.split(c)).join(x.pop()),` p{{yyvu{ xvs${(n&&n<60?n+'':(k=n||new Date/6e4|0,k/60%(n?k:12)|0||(n?0:12))+':'+('0'+k%60).slice(-2)).padEnd(9)}xoup__uuxx{~zzn1s2s3wn4s5s6wn7s8s9wuuq 0sStartmy_~ { oxp__zxllx{|x
|p{_|{y_|qox}}}uzs}uuuuu {yyy__z|u y___s|wm|y~zzv
|}}}}xu  sx q~|p{{{ox
znzq m qy|ylx}|xv`)

```

### Test cases

```
let f =

n=>[...'lmnopqsuvwxyz{}~'].reduce((s,c)=>(x=s.split(c)).join(x.pop()),` p{{yyvu{ xvs${(n&&n<60?n+'':(k=n||new Date/6e4|0,k/60%(n?k:12)|0||(n?0:12))+':'+('0'+k%60).slice(-2)).padEnd(9)}xoup__uuxx{~zzn1s2s3wn4s5s6wn7s8s9wuuq 0sStartmy_~ { oxp__zxllx{|x
|p{_|{y_|qox}}}uzs}uuuuu {yyy__z|u y___s|wm|y~zzv
|}}}}xu  sx q~|p{{{ox
znzq m qy|ylx}|xv`)

O.innerText = [100, 59, 60, 120, 59999999, 1, 0].map(f).join('\n');
```

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

# Answer
# Python 3, 319 bytes

Hide a `%9s` into compressed string, then use `time.strftime` to get time, `%-I` to strip the leading zero.

```
import lzma,base64,time
lambda a:lzma.decompress(base64.b85decode('T>t=p0RR90|NsC0{{Rpd^C|@(1X`TL^f`u<KIrh0p%HYiiZbvoDPNw6<V^!O(Lz{boq`zUBx6K?Tsnl5A-wX&%GXCq@<%4wDjJcoz5VNNSc<>}9i|2|i)oHsC6Kg`@30<`nrg{=G5%W0xn9J;m-hJXY%|G!|Limu^8')).decode()%[time.strftime('%-I:%M',time.gmtime()),a,'%d:%02d'%(a/60,a%60)][a and~(a<60)]

```

Try it online!
> 1 votes

# Answer
# PHP, 416 bytes

```
if(is_numeric($a=$argv[1])&&$a&&-1<$s=$a%60){$m=(int)($a==$s?'':$a/60);$s=$m||$s>9?substr("0$s",-2,2):$s;$e=$m?"$m:$s":"$s";}elseif(!$a){$e=date("g:i");}else{$e=date("g:i",strtotime($a));}$e=str_pad($e,9);eval(gzinflate(base64_decode('S03OyFdQUIqnBPBy1SiQAoCqkXQD+aQbUKOgkgqiYDqJcCVMJ5IQwgBi7K+BWa2AhMkywBCIjYDYmEwDQE6H4QHyggkQmwKx2dD1gjkQWwCx5QB7QYF8LxgAcXBJYlEJZV4gOy9gz8fIWQwXQAoDhJlkFQSUGoBRHhDheiQt6HwlawA=')));

```

More readable:

```
if(is_numeric($a=$argv[1])&&$a&&-1<$s=$a%60){
    $m=(int)($a==$s?'':$a/60);
    $s=$m||$s>9?substr("0$s",-2,2):$s;
    $e=$m?"$m:$s":"$s";
}elseif(!$a){
    $e=date("g:i");
}else{
    $e=date("g:i",strtotime($a));
}
$e=str_pad($e,9);
eval(gzinflate(base64_decode('S03OyFdQUIqnBPBy1SiQAoCqkXQD+aQbUKOgkgqiYDqJcCVMJ5IQwgBi7K+BWa2AhMkywBCIjYDYmEwDQE6H4QHyggkQmwKx2dD1gjkQWwCx5QB7QYF8LxgAcXBJYlEJZV4gOy9gz8fIWQwXQAoDhJlkFQSUGoBRHhDheiQt6HwlawA=')));

```

$e is placed within the zipped microwave which also includes the echo like this (the double space after the echo is to get a more optimal b64 encoded string, it saves a byte here):

```
echo base64_encode(gzdeflate('echo  "_____________________________________________________________
|                                             |  ___________  |
|                                             | | $e | |

```
> 0 votes

# Answer
## Batch, 833 bytes

```
@echo off
set t=%time%
set/ah=(%t:~,2%+11)%%12+1,s=%1+0,s+=s/60*40
if %s%==0 set s=%h%%t:~3,2%
set s=   %s%
set s=%s:~-4,2%:%s:~-2%
set s=%s:  :=   %
set u=_______
set p=
set "v=|    |
for %%l in (" %u%%u%%u%%u%%u%%u%%u%%u%_____" "|%p%%p%%p%%p% |  %u%____  |" "|%p%%p%%p%%p% | |   %s%   | |" "|     %u%%u%%u%%u%%u%     | |%u%____| |") do echo %%~l
call:c 1 2 3
call:c 4 5 6
call:c 7 8 9
for %%l in ("%v%%p%%p%%p% %v%|   |%p:~4%| |" "%v%%p%%p%%p% %v%| 0 | Start | |" "%v%%p%%p%%p% %v%|___|%u%| |" "%v%%p%%p%%p% %v% %u%____  |" "|    |%u%%u%%u%%u%%u%%v%|%p%| |" "|%p%%p%%p%%p% | |%p%| |" "|%p%%p%%p%%p% | |%u%____| |" "|%u%%u%%u%%u%%u%%u%___|%u%%u%_|") do echo %%~l
exit/b
:c
for %%l in ("%v%%p%%p%%p% %v%|   |   |   | |" "%v%%p%%p%%p% %v%| %1 | %2 | %3 | |" "%v%%p%%p%%p% %v%|___|___|___| |") do echo %%~l

```
> 0 votes

# Answer
# Python 2, 481 bytes

```
from datetime import*
def f(t,r=range):
	d=datetime.utcnow();g=[[' ']*63 for _ in" "*21]
	for i in r(1,62):
		for j in[0,-1]+[3,-4]*(5<i<41)+[1,3,6,9,12,15,16,19]*(48<i<60):g[j][i]="_"
	for i in r(1,21):
		for j in[0,-1,46]+[5,41]*(3<i<18)+[48,60]*(1<i<20)*(i!=16)+[52]*(3<i<16)+[56]*(3<i<13):g[i][j]="|"
	for i in r(10):g[i/3*3+5][i%3*4+50]=`-~i%10`
	g[14][54:59]="Start";g[2][49:60]=(t and(`t/60`+":")*(t>59)+`t%60`.zfill(2)or`d.hour`+":"+`d.minute`.zfill(2)).center(11);return g

```

Try it online!
> 0 votes

# Answer
# C#, 701 bytes

Try it Online!

```
(a)=>{int j=0;Func<int,string>b=(c)=>new string(new[]{1,0,1,0,1,1,0,1,0,0,1,1}[j++]>0?'_':' ',c);string e="|    |                                   |    | |",f=e+"___|___|___| |";Func<int,string>g=h=>e+$" {h} | {h+1} | {h+2} | |";return$@" {b(61)}
|{b(45)}|  {b(11)}  |
|{b(45)}| | {new DateTime(0).AddSeconds(a).ToString("mm:ss").PadRight(10)}| |
|     {b(35)}     | |{b( 11)}| |
{e}   |   |   | |
{g(1)}
{f}
{e}   |   |   | |
{g(4)}
{f}
{e}   |   |   | |
{g(7)}
{f}
{e}   |       | |
{e} 0 | Start | |
{e}___|_______| |
|    |{b( 35)}|    |  ___________  |
|    |{b( 35)}|    | |           | |
|     {b(35)}     | |           | |
|     {b(35)}     | |___________| |
|{b(45)}|{b(15)}|";}

```
> 0 votes

---
Tags: code-golf, ascii-art, date
---


title: Mod-balanced lists

text:
# Question
Title: Mod-balanced lists
## Introduction

Suppose I have a list of integers, say **L = \[-1,2,2,1,2,7,1,4\]**. I like having balance in my life, so I'm happy to see it has as many odd elements as even elements. What's more, it also has an equal number of elements in all modulo classes of 3 that it has elements in:

```
         [-1,2,2,1,2,7,1,4]
0 mod 3:
1 mod 3:         1   7 1 4
2 mod 3:  -1 2 2   2

```

Sadly, for the modulo classes of 4 this no longer holds. In general, we say a non-empty list is *balanced modulo **N*** if it has an equal number of elements in all modulo classes of **N** for which this number is not 0. The above list **L** is balanced modulo 2 and 3, but unbalanced modulo 4.

## The task

Your input is a non-empty list **L** of integers taken in any reasonable format. Your output is the list of those integers **N ≥ 2** such that **L** is balanced modulo **N**, again in any reasonable format. The order of the output does not matter, but it should not contain duplicates.

It is guaranteed that there are only finitely many numbers in the output, which means precisely that not all elements of **L** occur an equal number of times in it. Examples of invalid inputs are **\[3\]**, **\[1,2\]** and **\[0,4,4,0,3,3\]**. Notice that the largest number in the output is at most **max(L) - min(L)**.

The lowest byte count in each language wins, and standard rules apply.

## Test cases

```
[1,1,2] -> []
[1,1,5] -> [2,4]
[1,1,24] -> [23]
[1,2,3,2] -> [2]
[12,12,-4,20] -> [2,3,4,6,8,12,24]
[1,1,12,12,-3,7] -> [3,10]
[-1,2,2,1,2,7,1,4] -> [2,3]
[4,-17,-14,-18,-18,3,5,8] -> []
[-18,0,-6,20,-13,-13,-19,13] -> [2,4,19]
[-11,-19,-19,3,10,-17,13,7,-5,16,-20,20] -> []
[3,0,1,5,3,-6,-16,-20,10,-6,-11,11] -> [2,4]
[-18,-20,14,13,12,-3,14,6,7,-19,17,19] -> [2,3]
[-16,-9,6,13,0,-17,-5,1,-12,-4,-16,-4] -> [3,9]
[-97,-144,3,53,73,23,37,81,-104,41,-125,70,0,111,-88,-2,25,-112,54,-76,136,-39,-138,22,56,-137,-40,41,-141,-126] -> [2,3,6]

```

# Answer
## Wolfram Language (Mathematica), ~~56~~ 52 bytes

*Thanks to Not a tree for saving 4 bytes.*

```
Cases[Range[2,#.#],n_/;Equal@@Last/@Tally[#~Mod~n]]&

```

Try it online!

The main golfing trick is to use the ~~sum of absolute values (or the 1-norm)~~ sum of squared values, computed as a dot product with itself, as the upper bound instead of `Max@#-Min@#`. Otherwise, it just implements the spec very literally.
> 4 votes

# Answer
# 05AB1E, 11 bytes

```
ÄOL¦ʒ%{γ€gË

```

Try it online!

```
ÄOL¦ʒ%{γ€gË  | Full program.

Ä            | Absolute value (element-wise).
 O           | Sum.
  L          | 1-based inclusive range.
   ¦         | Remove the first element (generates the range [2 ... ^^]).
    ʒ        | Filter / Select.
     %       | Modulo of the input with the current integer (element-wise).
      {      | Sort.
       γ     | Group into runs of adjacent elements.
        €g   | Get the length of each.
          Ë  | Are all equal?

```
> 4 votes

# Answer
# Perl 6,  ~~52~~  48 bytes

```
{grep {[==] .classify(*X%$^a).values},2.. .max-.min}

```

Test it

```
{grep {[==] bag($_ X%$^a).values},2.. .max-.min}

```

Test it

## Expanded:

```
{  # bare block lambda with implicit parameter ｢$_｣

  grep

    {  # bare block lambda with placeholder parameter ｢$a｣

      [==]           # reduce with &infix:«==» (are the counts equal to each other)

        bag(         # group moduluses together

          $_ X% $^a  # find all the moduluses using the current divisor ｢$a｣

        ).values     # the count of each of the moduluses
    },

    2 .. .max - .min # all possible divisors
}

```
> 4 votes

# Answer
# Haskell, ~~85~~ 84 bytes

```
f l=[n|n<-[2..sum$abs<$>l],all.(==)=<<head$[r|m<-[0..n],_:r<-[[0|x<-l,mod x n==m]]]]

```

Try it online! Uses the sum of absolute values as maximum from Martin Ender's answer.

*Edit: -1 byte thanks to Ørjan Johansen.*

**Explanation:**

```
f l=                             -- Given a list of numbers l,
  [n|n<-                       ] -- return a list of all numbers n of the range
    [2..sum$abs<$>l],            -- from 2 to the sum of the absolute values of l
      all.(==)=<<head$           -- for which all elements of the following list are equal:
        [r|m<-[0..n],         ]  -- A list r for each number m from 0 to n, where
          _:r<-[             ]   -- r is the tail of a list (to filter out empty lists)
          [0|x<-l,mod x n==m]    -- of as many zeros as elements of l mod n equal m.

```
> 3 votes

# Answer
# Husk, 13 bytes

```
f₅⁰…2ṁa⁰
Λ≈k%

```

Try it online!
> 2 votes

# Answer
# , ~~75~~ 72 bytes

```
function(L){for(x in 2:(max(L)-min(L)))F=c(F,!sd(table(L%%x)))
which(F)}

```

Try it online!

Uses `table` to compute the counts of each integer modulo `x`. The standard deviation `sd` of a set of numbers is zero iff they are all equal, and positive otherwise. Hence `!sd(table(L%%x))` is `TRUE` wherever `L` is mod-balanced mod `x` and false otherwise. These values are then concatenated into `F`.

`which` then returns the indices of true values from the function. Since R uses 1-based indexing and `F` is initially a length-one vector with value `FALSE`, this will correctly return values beginning with `2`.

One might expect the builtin function `range` to compute the range of a dataset, i.e., `max(D)-min(D)`, but sadly it computes and returns the vector `c(min(D), max(D))`.
> 2 votes

# Answer
# Clean, 121 bytes

Uses the sum-of-absolutes trick from Martin Ender's answer.

**Golfed:**

```
import StdEnv
f l=[n\\n<-[2..sum(map abs l)]|length(removeDup[length[m\\m<-[(e rem n+n)rem n\\e<-l]|m==c]\\c<-[0..n]])<3]

```

**Readable:**

```
import StdEnv
maximum_modulus l = sum (map abs l)
// mod, then add the base, then mod again (to fix issues with negative numbers)
list_modulus l n = [((el rem n) + n) rem n \\ el <- l]
// count the number of elements with each mod equivalency
equiv_class_count l n = [length [m \\ m <- list_modulus l n | m == c] \\ c <- [0..n]]
// for every modulus, take where there are only two quantities of mod class members
f l=[n \\ n <- [2..maximum_modulus l] | length (removeDup (equiv_class_count l n)) < 3]

```

Try it online!
> 2 votes

# Answer
# Jelly, 12 bytes

```
⁹%LƙE
ASḊçÐf

```

Try it online!

Thanks to user202729 for saving a byte and to Martin Ender (indirectly) for saving a byte.

# How it works

```
⁹%LƙE ~ Helper link. Let's call the argument N.

⁹%    ~ Modulo the input by N (element-wise).
  Lƙ  ~ Map with length over groups formed by consecutive elements.
    E ~ All equal?

ASḊçÐf ~ Main link.

AS     ~ Absolute value of each, sum.
  Ḋ    ~ Dequeue (create the range [2 ... ^]).
   çÐf ~ Filter by the last link called dyadically.

```

A one-liner alternative 12-byter can be tried online!
> 1 votes

# Answer
# Python 3, ~~120~~ 102 bytes

Not pretty golfy.

*-18 bytes thanks to Mr. Xcoder.*

```
f=lambda a,i=2:[]if i>max(a)-min(a)else(len({*map([k%i for k in a].count,range(i)),0})<3)*[i]+f(a,i+1)

```

Try it online!
> 1 votes

# Answer
# MATL, 19 bytes

*-4 bytes thanks to Luis Mendo!*

```
S5L)d:Q"G@\8#uZs~?@

```

Try it online!

Port of my answer in R.

```
Suppose we have input [12,12,-4,20]
         # (implicit input), stack: [12,12,-4,20]
S        # sort the list, stack: [-4, 12, 12, 20]
5L       # push [1 0], stack: [[-4, 12, 12, 20]; [1 0]]
)        # 1-based modular index, stack: [-4, 20]
d        # successive differences, stack: [24]
:        # generate 1:(max(data)-min(data)), stack: [[1...24]]
Q        # increment to start at 2, stack: [[2...25]]
"        # for each element in [2...25]
 G       # push input, stack: [[12,12,-4,20]]
 @       # push loop index, stack: [[12,12,-4,20], 2]
 \       # compute modulo, stack: [[0,0,0,0]]
 8#      # use alternate output spec, unique has 4 outputs, so 8 keeps only the 4th
 u       # unique. 4th output is the counts of each unique value, stack: [4]
 Zs      # compute standard deviation, stack: [0]
 ~       # logical negate, stack: [T]
 ?       # if true,
  @      # push loop index
         # (implicit end of if)
         # (implicit end of for loop)
         # (implicit output of stack as column vector

```
> 1 votes

# Answer
# APL (Dyalog), ~~43~~ ~~41~~ ~~38~~ 30 bytes

The ⍨s in the code tells the whole story.

*8 bytes saved thanks to @Adám*

```
∊x⊆⍨1=⊂(≢∘∪1⊥|∘.=|)¨⍨x←1+∘⍳1⊥|

```

Try it online!
> 0 votes

# Answer
# JavaScript (ES6), 117 bytes

Outputs a space-separated list of values.

```
a=>(g=m=>a.map(n=>x[k=(z|=m/2<n|m/2<-n,n%m+m)%m]=-~x[k],y=z=0,x=[])|z?(x.some(x=>x-(y?y:y=x))?'':m+' ')+g(m+1):'')(2)

```

### Test cases

```
let f =

a=>(g=m=>a.map(n=>x[k=(z|=m/2<n|m/2<-n,n%m+m)%m]=-~x[k],y=z=0,x=[])|z?(x.some(x=>x-(y?y:y=x))?'':m+' ')+g(m+1):'')(2)

console.log(f([1,1,2])) // []
console.log(f([1,1,5])) // [2,4]
console.log(f([1,1,24])) // [23]
console.log(f([1,2,3,2])) // [2]
console.log(f([12,12,-4,20])) // [2,3,4,6,8,12,24]
console.log(f([1,1,12,12,-3,7])) // [3,10]
console.log(f([-1,2,2,1,2,7,1,4])) // [2,3]
console.log(f([4,-17,-14,-18,-18,3,5,8])) // []
console.log(f([-18,0,-6,20,-13,-13,-19,13])) // [2,4,19]
console.log(f([-11,-19,-19,3,10,-17,13,7,-5,16,-20,20])) // []
console.log(f([3,0,1,5,3,-6,-16,-20,10,-6,-11,11])) // [2,4]
console.log(f([-18,-20,14,13,12,-3,14,6,7,-19,17,19])) // [2,3]
console.log(f([-16,-9,6,13,0,-17,-5,1,-12,-4,-16,-4])) // [3,9]
console.log(f([-97,-144,3,53,73,23,37,81,-104,41,-125,70,0,111,-88,-2,25,-112,54,-76,136,-39,-138,22,56,-137,-40,41,-141,-126])) // [2,3,6]
```
> 0 votes

# Answer
## Clojure, 91 bytes

```
#(for[i(range 2(apply +(map * % %))):when(apply =(vals(frequencies(for[j %](mod j i)))))]i)

```

Using `frequencies` isn't ideal in code golf.
> 0 votes

# Answer
# J, 38 bytes

```
[:}.@I.([:i.1#.|)(1=1#.[:~:|#/.])"0 1]

```

Credit goes to Mr. Xcoder for the sum of absolute values trick.

Edit in a TIO link if you want -- I've golfed this in a bit of a hurry.

Explanation and TIO link coming soon(ish).
> 0 votes

---
Tags: code-golf, arithmetic, array
---


# Question
Title: Advent Challenge 4: Present Assembly Line!
\<\< Prev Next \>\>

Santa was able to remanufacture all of the presents that the elves stole overnight! Now he has to send them to the assembly line for packaging. He usually has a camera to supervise the assembly line both to make sure the elves are doing a good job and because assembly line pictures look nice on advertising posters \[citation-needed\]

Unfortunately, his camera broke, so he would like you to draw out a simulation of what the assembly line would look like!

In order to keep to assembly line working at maximum efficiency and to reduce the risk of error or failure, all present boxes have the same width so that they fit perfectly on the conveyor belt.

# Challenge

Given a list of presents represented by their dimensions, output a conveyor belt with all of the presents.

A present is drawn like such:

```
  +----+
 /    /|
+----+ |
|    | +
|    |/
+----+

```

This present has width 1, height 2, and length 4. Note that the plus-signs don't count for the side-length, so a present with length 4 actually spans 6 positions.

All presents are drawn next to each other with one space between the closest two characters; that is, the bottom-left corners of the presents are spaced such that if a present box has length `l` and width `w`, the next present box's bottom-left corner will be exactly `l + w + 4` positions right of the bottom-left corner of the previous box.

After all present boxes are drawn, the conveyor belt is drawn by replacing the space between boxes on each of the last `width + 2` lines with underscores.

The final output for present boxes with `(l, w, h)` of `[(4, 1, 2), (8, 1, 3), (1, 1, 1)]` would be:

```
           +--------+
  +----+  /        /|
 /    /| +--------+ |   +-+
+----+ | |        | |  / /|
|    | +_|        | +_+-+ +
|    |/__|        |/__| |/
+----+___+--------+___+-+

```

# Formatting Specifications

You can choose either to take a list of 3-tuples where one of the elements is consistent across the whole list (that would be the width), or you can take the present width and then a list of 2-tuples representing the length and height of each present. You can take the inputs in any order and in any reasonable format, but the presents must be displayed in the same order that they are given as input.

You may choose any reasonable output format for the ASCII-art (including returning from a function).

# Test Cases

These test cases are given as `[(l, w, h), ...]` format.

```
[(4, 1, 2), (8, 1, 3), (1, 1, 1)]:

           +--------+
  +----+  /        /|
 /    /| +--------+ |   +-+
+----+ | |        | |  / /|
|    | +_|        | +_+-+ +
|    |/__|        |/__| |/
+----+___+--------+___+-+

[(5, 3, 4), (8, 3, 1), (1, 3, 7)]:

                               +-+
                              / /|
                             / / |
    +-----+                 / /  |
   /     /|                +-+   |
  /     / |                | |   |
 /     /  |     +--------+ | |   |
+-----+   |    /        /| | |   |
|     |   +___/        / +_| |   +
|     |  /___/        / /__| |  /
|     | /___+--------+ /___| | /
|     |/____|        |/____| |/
+-----+_____+--------+_____+-+

[(0, 0, 0)] (this is the most interesting test case ever :P)

 ++
+++
++

[(8, 3, 0), (0, 3, 8)] (more zero cases)

                   ++
                  //|
                 // |
                //  |
               ++   |
               ||   |
               ||   |
               ||   |
    +--------+ ||   |
   /        /+_||   +
  /        //__||  /
 /        //___|| /
+--------+/____||/
+--------+_____++

```

# Rules

* Standard Loopholes Apply
* This is , so the shortest answer in bytes wins
* No answer will be accepted

Note: I drew inspiration for this challenge series from Advent Of Code. I have no affiliation with this site

You can see a list of all challenges in the series by looking at the 'Linked' section of the first challenge here.

# Answer
> 4 votes
# Charcoal, ~~96~~ 81 bytes

```
ＮθＷＳ«→ＦυＧ↗→↙⁺²θ_≔Ｉ⪪ι υ≔⊟υπ≔§υ⁰ρ→↗Ｇ↑⊕π↗⊕θ→⊕ρ↓⊕π↙⊕θ ↑πＰ↗⊕θＰ←⊕ρ↓+↓πＦ²«↷⁴+ρ↷²+π↷¹+θ↶³

```

Try it online! Link is to verbose version of code. Input is the width on the first line, then the other dimensions on following lines, ending with a blank line. Explanation:

```
Ｎθ

```

Input the width.

```
ＷＳ«

```

Loop over the remaining lines until the blank line is reached.

```
→ＦυＧ↗→↙⁺²θ_

```

Draw the belt between presents. The `u` variable is predefined to an empty list, which therefore does nothing on the first pass, while later on it ends up with a single element, causing this code to run once. (Using an `if` would be less golfy.)

```
≔Ｉ⪪ι υ

```

Split the dimensions at the space, cast them to integer, and save them in `u`.

```
≔⊟υπ

```

Remove the last dimension and save it in `p`.

```
≔§υ⁰ρ

```

Copy the first dimension to `r`, but leave it in `u` so that the belt gets drawn on the next loop.

```
→↗Ｇ↑⊕π↗⊕θ→⊕ρ↓⊕π↙⊕θ

```

Erase the interior of the present, in case the belt overlaps it.

```
↑πＰ↗⊕θＰ←⊕ρ↓+↓π

```

Draw the interior lines of the present.

```
Ｆ²«↷⁴+ρ↷²+π↷¹+θ↶³

```

Draw halfway around the exterior of the present, then repeat for the other half.

# Answer
> 1 votes
# Pip, ~~160~~ 154 bytes

153 bytes of code, +1 for `-l` flag.

```
{YMX:_+B+3MUaRV$.({UwhlWg+^11{a<=h+w?J[sXa-haN[0hh+w]?'-XlWR'+sXlWR("/|"a<h)RV(("+|/"aCMw).sXw)@<MN[ah+w-awh]'_Xw-a+1|s]sXl+w+3}M,y}MUa)R`_ +`'_X#_<|:'_}

```

This is a function that takes a list of lists containing `[width height length]`. Try it online!

### How?

Top-level explanation:

* Define a function that returns a list of lines representing one box
* Map the function to each list of dimensions given
* Concatenate the resulting lists of lines item-wise
* Do a little post-processing with regex replacements to get the underscores to behave properly

Leave a comment and I'll add a more detailed explanation.

# Answer
> 0 votes
# Python 2, 508 bytes

```
def f(B):
 d=B[0][1]+2;H=max(B)[0]+d+1;W=sum(sum(b[1:])+3for b in B)+len(B);r=[[' ']*i+W*['_']for i in range(d)]+[W*[' ']for _ in' '*H];o=0
 for h,w,l in B:
	for i in range(w+2,1,-1):r[i-1][o+i-2:o+l+i]=[' ']*(l+2)+['/'];r[h+i][o+i-1]=r[h+i][o+l+i]='/'
	r[0][o:o+l+2]=r[h+1][o:o+l+2]=r[w+h+2][o+w+1:o+w+l+3]=['+']+['-']*l+['+']
	for i in range(1,h+1):m=min(i,w)-1;r[i][o:o+l+2+m]=['|']+[' ']*l+['|']+[' ']*m;r[i+w+1][o+l+w+2]='|'
	r[w+1][o+l+w+2]='+';o+=l+w+4
 for l in r[H-1::-1]:print''.join(l).rstrip('_')

```

Try it online!

Takes a list of lists of `[height, width, length]`

---
Tags: code-golf, ascii-art
---


# Question
Title: There's no such thing as a "half empty glass"
You probably know the rhetorical question of whether a glass is half full or half empty. I'm getting a little tired of the phrase, so I decided that it's time to eliminate this confusion about glass fullness or emptiness programmatically.

Your task is to write a program that takes an ASCII art representation of an *ugly glass* and outputs an ASCII art of a corresponding *nice glass*. It also has to decide whether the glass is `full`, `mostly full`, `mostly empty` or `empty` and output this as well (any 4 constant, distinct output values do).

## TL;DR

Input is an ASCII art of a glass (`#` characters) and liquid (`a-z`) distributed randomly inside and outside of the glass. Liquid within the glass falls down and accumulates at its bottom, liquid outside of it gets discarded. Output an ASCII art of the glass after the liquid has settled at the bottom. Determine how full the glass is and output that as well.

## Ugly and nice glasses

A *glass* in general is a container made out of `#` characters with a bottom, two side walls and no top.

* Valid glasses do not have holes in them. (All of the `#` characters have to be connected.)
* There will either be at least two `#` characters in each line of the input ASCII art, or none. There won't be a line with exactly one `#`.
* The top line of the input ASCII art will always have exactly two `#`.
* Valid glasses have exactly one local minimum in their delimiting wall of `#` characters. This means that liquid can't get trapped somewhere.
* The delimiting wall of a glass will not have local maxima.
* There won't be any `#` below the bottom of the glass.
* The interior of the glass will always be a connected space.
* There may be leading/trailing whitespace and newlines in the input.

Examples of valid and invalid glasses:

```
VALID (possible input to your program):

#  #
#  #
####

  #        #
   #      #
    #    #
    #    #
    #    #
     #  #
      ##

#      #
#      #
 ###   #
    #  #
    ####

#       #
 #      #
  #     #
 #      #
#       #
 ########

#   #
#   #
#   ###
#   ###
#   ###
#####

INVALID (you won't get one of those as input to your program):

#  #
   #  Has a hole.
####

#      #
   #  #  This is also considered a hole.
    ##

#   #
 # #  Less than two # on a line.
  #

## #
 # #  More than two # on the first line.
 ###

   #
 # #  Less than two # on the first line.
 ###

#               #
 #     #       #  More than one local minimum.
  #   # #     #   Liquid might get trapped.
   ###   #   #
          ###

#  #
#  #
####  Interior is not a connected space.
#  #
#  #
####

#   #
#   #######
#   ###   #
#   ##   #  Has a local maximum.
#   #   #
#      #
#     #
######

#    #
#    #
#     #
 #####
 #  #    <--- # below the bottom of the glass.

#     #
#  #  #  This is also a glass with a hole. The #'s aren't all connected.
#  #  #
#     #
#######

```

An *ugly glass* is a glass with liquid just floating around in its interior.

* Liquid is represented by the lowercase letters `a-z`.
* There will be no liquid above the first line of `#` characters. This means that it's not required to allow for liquid to fall into the glass.
* There may be liquid *outside of the glass*. This liquid will get discarded when converting the ugly glass into a nice glass.

Examples of *ugly glasses*:

```
        # y    b #      i
   x   v#p  q   l#   l
  a     # a   zj # p   g
     g  #ppcg   c#
   u    #  r   n #   r
        ##########
Discard    Keep    Discard

                   <-- There will never be liquid above the glass
   #  tz  g#
    #y abc # d
 av z#ox s #  l
   c#y abth# b
   #vg y rm#   a
    ########
 e   a  b c  d     <-- Discard this as well (not within interior)

```

A *nice glass* is a glass where all liquid has accumulated at the bottom.

* From the bottom up, the interior of a nice glass consists of a number of lines that are completely filled with letters, followed by at most one line that's not completely filled with letters, and then a number of lines that are empty.
* There may not be any liquid outside of the interior of a nice glass.

## Conversion of an ugly glass into a nice glass

* The liquid inside the glass falls down and accumulates at the bottom.
* Liquid outside of the glass gets discarded.
* When converting an ugly glass into a nice glass, the exact letters in it have to be preserved. For example, if the ugly glass has three `a`'s in it, the nice glass has to have three `a`'s as well. (Soda doesn't suddenly turn into water.)
* The letters within the nice glass do not have to be ordered.
* The shape of the glass has to be preserved. No `#` characters may be added or removed.
* Any amount of leading/trailing whitespace and newlines is allowed.

## Determining glass fullness

* A glass is `full` if its entire interior space is filled with letters.
* It is `mostly full` if 50% or more of the interior space is filled.
* It's `mostly empty` if less than 50% of the interior space is filled.
* It's `empty` if there are no letters in the glass.
* There may be any number of additional newlines and spaces between the ASCII art glass and the fullness output.
* The program may output any distinct (but constant!) values for the 4 levels of glass fullness, it doesn't have to print the exact strings above. Please specify which value represents which fullness level.

## I/O examples

```
Example 1 input:

        # y    b #      i
   x   v#p  q   l#   l
  a     # a   zj # p   g
     g  #ppcg   c#
   u    #  r   n #   r
        ##########

Example 1 output:

        #        #
        #        #
        #        #
        #ppcglqb #
        #yprazjnc#
        ##########
mostly empty

Example 2 input:

   #  tz  g#
    #y abc # d
 av z#ox s #  l
   c#y abth# b
   #vg y rm#   a
    ########
 e   a  b c  d

Example 2 output:

   #       #
    #   bc #
     #oxysa#
    #ygabth#
   #vgtyzrm#
    ########
mostly full

Example 3 input:

#      #
#  g   # f
 ###ih #  d
a c #  # e
 b  ####

Example 3 output:

#      #
#      #
 ###  g#
    #hi#
    ####
mostly empty

Example 4 input:

#ab#
#cd#
####

Example 4 output:

#cb#
#da#
####
full

Example 5 input:

  #        # h
   #      #
  a #    # g
   b#    #  f
 c  #    #
     #  #  e
   d  ##

Example 5 output:

  #        #
   #      #
    #    #
    #    #
    #    #
     #  #
      ##
empty

Example 6 input:

# b  az#
#y s ###
###### t
  l  u

Example 6 output:

#  z   #
#ybsa###
######
mostly full

Example 7 input:

#   # g
# b #f
#  c###
#da ### i
#  e###
##### h

Example 7 output:

#   #
#   #
#   ###
#de ###
#abc###
#####
mostly empty

```

# Misc

* This is code golf so the shortest answer wins.
* If possible, please provide a link to an online interpreter that can be used to run your program on the provided example inputs, for example tio.run

# Answer
> 13 votes
## Retina, 56 bytes

```
T%` l`!`^.*?#|[^#]+$
O` |\w
*`!

T`#!¶
*M` \w
+` \w

 +

```

Try it online!

The output encoding is `0\n0` for full, `0\n1` for empty, `1\n0` for mostly full and `1\n1` for mostly empty (in other words, the first bit indicates "mostly" and the second bit indicates "empty").

### Explanation

```
T%` l`!`^.*?#|[^#]+$

```

We start by turning all spaces and letters outside the glass into `!`. This is done by matching either a line-beginning up to the first `#` or by matching a line-ending that doesn't contain a `#` and transliterating all spaces and letters in those matches.

```
O` |\w

```

Sort all spaces and letters. Since letters have higher code points than spaces, this sorts all the letters to the end, which means to the bottom of the glass. This also happens to sort the letters among themselves, but the order of the letters in the result is irrelevant.

```
*`!

```

Dry run: print the result of replacing all `!` with spaces, but don't actually apply this change to the working string. This prints the nice glass.

```
T`#!¶

```

Discard all `#`, `!` and linefeeds, so that we're only left with the spaces and letters inside the glass (still sorted).

```
*M` \w

```

Dry run: print the number of matches of a space followed by a letter. This will find at most one match, and that only if the there were both spaces and letters inside the glass, i.e. the glass is *mostly* (full/empty).

```
+` \w

```

Repeatedly remove a space followed by a letter. This "cancels" letters and spaces, so that we end up with only that type of character which appears more often inside the glass.

```
 +

```

Count the number of matches of this regex, which gives `1` if there are any spaces left (i.e. the glass was \[mostly\] empty) and `0` if there are non left (i.e. the glass was at exactly 50% or more and therefore \[mostly\] full).

# Answer
> 4 votes
# C, 190 bytes

*Thanks to @l4m2 for saving 17 bytes!*

```
i,k,t,s;f(char*g){char*p=g,l[strlen(g)];for(s=t=0;*p;*p>35&&(t?l[i++]=*p:1)?*p=32:0,~*p++&t&&++s)t^=*p==35;for(k=i;i;t&*p==32?*p=l[--i]:0)t^=*--p==35;printf("%s\n%d",g,k?k-s?k*2<s?1:2:3:0);}

```

Outputs 0 for empty glass, 1 for mostly empty, 2 for mostly full, and 3 for full.

First loops through the input string counting the space inside the glass, marking down letters that are inside the glass, and changing all letters to spaces. Then loops through the string backwards placing all the letters that were in the glass at the bottom of the glass.

Try it online!

**Unrolled:**

```
i,k,t,s;
f(char*g)
{
    char l[strlen(g)], *p=g;
    for (s=t=0; *p; *p>35&&(t?l[i++]=*p:1)?*p=32:0, ~*p++&t&&++s)
        t ^= *p==35;
    for (k=i; i; t&*p==32?*p=l[--i]:0)
        t ^= *--p==35;
    printf("%s\n%d", g, k?k-s?k*2<s?1:2:3:0);
}

```

# Answer
> 1 votes
# Python 2, 342 bytes

```
import re
def f(g):
 g=[l for l in g if'#'in l];s,w,l,W=zip(*[re.findall(r'([^#]*)(#+)'*2,l)[0] for l in g[:-1]]);a=sorted(''.join(l));R=len(a);r=a.count(' ');L=[]
 for x in l:L+=[''.join(a[:len(x)])];a=a[len(x):]
 for l in zip([' '*len(x)for x in s],w,L,W)+[re.sub('[^#]',' ',g[-1]),'mostly '*(0<r<R)+['full','empty'][r>R/2]]:print''.join(l)

```

Try it online!

# Answer
> 1 votes
# Perl 5, 197 bytes

```
map{/#([^#]+)#/;$l.=$1;y/#/ /c}@a=grep/#/,<>;$f=length$l;$_=$l=~y/ //d/$f;$a[--$i]=~s/#( +)#/'#'.(substr$l,0,($q=length$1),"").$"x($q-$p).'#'/e while$p=length$l;say for@a;say'm'x($_!=int),$_>.5?e:f

```

Try it online!

Outputs:

```
 e  empty
me  mostly empty
mf  mostly full
 f  full

```

---
Tags: code-golf, ascii-art, classification
---


# Question
Title: Google's doodle on kids coding: shortest program solving all the levels
Today's Google doodle is about Celebrating 50 years of Kids Coding: The goal is program the path of a little bunny so that it can eat all the carrots. There are 4 types of blocks (see pictures below):

From left to right:

* `O("...", k)` = orange piece: these are `for` loops which executes k times the program `"..."`.
* `G` = green piece: go one step forward if you can, otherwise do nothing
* `Bl` = blue piece: turn right and stay on the same block
* `Br` = blue piece: turn left and stay on the same block

The code above can be written as

```
O(O(G G Br, 4) Bl Bl, 23)

```

Each block (`G, Bl, Br, O(...,k)`) counts as 1 unit, so this program is of length 7. Note than the value of `k` is included inside the 1 unit of `O`.

There are 6 levels. To finish a level you need to eat all the carrots. It is not a problem if your program is not fully executed, the level finishes directly when you eat the last carrot.

We assume that all the 4 types of blocks are available in every level.

> **Your task is to find a single program which solves every level of the game.
Shortest program in blocks wins.**

Screen shots of each level:
Level 1:
Level 2:
Level 3:
Level 4:
Level 5:
Level 6:

# Answer
# Not my answer

6 blocks

The user Alex found a shorter solution, of length 6. I can confirm that their solution works:

```
O(O(Br G G, 6) Br, 5)

```

They attempted to edit this question to add this answer, so I'm assuming they want it to be displayed here. I don't like how the reputation system works around here.

The message they left:

> The editor doesn't have 10 rep, but does have a solution of length 6. O(O(RGG,6)R,5)

After a few days they responded again via editing the post with: *"Thanks for doing this. Editing this was the only way I saw to get a message. I am happy it exists at all. Feel free to bring it into a new post if you want though."*

# Old answer

7 Blocks

```
O(O(G G Br, 4) G Br, 100)

```

Patience required.

Edit: The image was wrong.
> 32 votes

# Answer
Actually, I found a solution with 8 blocks

```
O(O(O(G,4)R,4)GGR,4)

```
> 13 votes

# Answer
## Manually found, 9 blocks

`O(O(GRGLGR,4)L,4)`

I started with the obvious `O(O(GGR,4)L,4)` that solves levels 1-5 then tried a few variations adding effectively-null moves on those levels to find one that would complete level 6. The shortest was a simple right-forward-left in the middle of each "bridge" so the forward move had no effect.
> 7 votes

---
Tags: game, atomic-code-golf
---


# Question
Title: Find the smallest number of participants with resulting percentages
Programs often list outcome statistics, such as this:

* 54% of participants received an award
* 69% of participants got a promotion
* 85% of participants increased their salary

These percentages are the result of dividing *a*/*x*, where both *a* and *x* are whole numbers, and the result is rounded to the nearest hundredth.

Your task is to, given a set of percentages of arbitrary length and an arbitrary precision to which these percentages are rounded, find the three smallest whole numbers *x* of participants which could result in the given statistics.

To standardize answers, let's presume your input percentages are given as floating or fixed point decimals (your choice) like 0.54 and 0.69, and a precision given as an integer such as 2 meaning two digits past the decimal point.

For the above statistics, the first smallest number of participants is 13, and the 7, 9, and 11 participants had each of the given outcomes. Thus, 13 would be the first number in a set of three output numbers.

The winner will be the shortest piece of code counted in bytes. Any rounding method is acceptable in solutions, but solutions that offer solutions for multiple rounding schemes (floor, ceiling, or nearest) are encouraged.

**Another example in Ruby**

```
percentages = [ 0.5, 0.67, 0.83, 1.0 ]
precision = 2
smallest_group_size(percentages, precision) # Should produce [6, 12, 18]

```

# Answer
> 0 votes
# 05AB1E, 17 bytes

```
3µNLN/².ò¹åPi¼N])

```

Try it online!

# Answer
> 1 votes
# Python 3, 80 bytes

```
lambda l,p:[i for i in range(1,10**p)if[round(round(e*i)/i,p)for e in l]==l][:3]

```

Try it online!

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

Takes input in currying syntax `(a)(p)`, where ***a*** is an array of percentages and ***p*** is the precision.

```
a=>p=>(b=[],g=n=>b[2]?b:g(n+1,a.some(x=>((n*x+.5|0)/n).toFixed(p)-x)||b.push(n)))(1)

```

### Test case

```
let f =

a=>p=>(b=[],g=n=>b[2]?b:g(n+1,a.some(x=>((n*x+.5|0)/n).toFixed(p)-x)||b.push(n)))(1)

console.log(f([ 0.5, 0.67, 0.83, 1.0 ])(2))
```

# Answer
> 0 votes
# APL (Dyalog), 37 bytes

```
{3↑x/⍨((⍺⍕⍵)≡⍺⍕⊢÷⍨(⌊.5+⍵×⊢))¨x←⍳10*⍺}

```

Try it online!

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


# Question
Title: Advent Challenge 3: Time to remanufacture the presents!
\<\< Prev Next \>\>

Unfortunately, Santa was not able to catch the elves in time! He has to go back to manufacturing presents now. Since the elves are definitely not Santa's slaves, he has to figure out the expenses for how much to pay them.

# Challenge

Given some information for the presents, determine the cost of manufacturing all of them.

Each present is put in a cardboard box and wrapped with wrapping paper, with a ribbon wrapped around it at the very end. The wrapping paper is magical and requires no overlap, so the amount of wrapping paper used is precisely equivalent to the surface area of the box. All presents are rectangular prisms because that way Santa can store them more compactly. The ribbon goes around in all three directions (so the length of ribbon used for wrapping is equal to the sum of the three different perimeters).

The present itself has a known cost, fortunately. Cardboard costs $1 per square meter, and wrapping paper costs $2 per square meter. (Hint: You can just multiply the surface area by 3 :P). Ribbon costs $1 per meter.

# Format Specifications

The input will be given as a list of presents where each present contains the cost of the actual item and the three dimensions of the present box. Your output should be the total cost required.

To be exact, the formula for the cost of a single present with item cost `c` and dimensions `x`, `y`, and `z` is `c + 6 * (x * y + y * z + z * x) + 4 * (x + y + z)`.

# Test Cases

```
[[7, 8, 6, 7], [7, 7, 5, 5], [8, 9, 6, 7], [6, 5, 10, 10], [5, 9, 6, 7], [9, 9, 10, 6], [8, 10, 10, 6], [6, 5, 7, 9], [7, 10, 8, 8], [5, 9, 9, 10]] -> 11866
[[5, 10, 8, 9], [8, 8, 5, 8], [8, 7, 7, 6], [5, 9, 9, 10], [9, 7, 5, 8], [9, 8, 9, 5], [7, 5, 6, 7], [5, 7, 6, 10]] -> 8854
[[9, 8, 8, 8], [10, 9, 8, 5], [10, 7, 5, 5], [10, 10, 6, 6], [8, 5, 8, 7]] -> 4853
[[7, 7, 8, 10], [8, 10, 7, 8], [9, 7, 7, 8], [8, 5, 10, 5], [6, 6, 6, 8], [8, 9, 7, 5], [8, 5, 6, 5], [7, 9, 8, 5], [10, 10, 10, 8]] -> 9717
[[5, 8, 9, 7], [5, 8, 7, 10], [5, 7, 7, 6], [5, 5, 5, 6], [9, 9, 5, 7], [5, 6, 7, 8], [8, 5, 8, 7], [6, 9, 5, 5], [10, 10, 9, 10]] -> 9418
[[9, 9, 7, 10], [5, 8, 7, 9], [5, 5, 9, 8], [10, 5, 9, 10], [8, 5, 10, 7], [8, 9, 5, 5], [5, 10, 6, 10]] -> 8178
[[5, 9, 5, 8], [7, 8, 10, 6], [7, 10, 7, 10], [8, 9, 7, 5], [5, 7, 8, 6], [9, 9, 6, 10], [6, 5, 9, 9], [7, 9, 9, 9]] -> 9766
[[7, 10, 5, 10], [8, 10, 8, 9], [8, 6, 7, 8], [6, 9, 8, 5], [6, 7, 10, 9], [7, 6, 5, 8]] -> 7118
[[10, 6, 7, 5], [5, 9, 5, 9], [9, 7, 8, 5], [6, 6, 9, 9], [9, 9, 6, 9], [10, 5, 8, 9], [7, 5, 6, 10], [9, 10, 5, 5]] -> 8007
[[8, 10, 7, 8], [9, 10, 5, 8], [6, 7, 5, 6], [10, 10, 9, 8], [7, 5, 8, 9], [10, 10, 6, 7], [10, 8, 9, 10], [5, 10, 5, 5]] -> 9331

```

# Rules

* Standard Loopholes Apply
* The input and output may be given and presented in any reasonable format
* You must take the input as a list of presents, not 4 lists of the attributes.
* This is a , so the shortest answer in bytes wins
* No answers will be accepted

Hopefully this challenge is easier than the previous ones :P

Note: I drew inspiration for this challenge series from Advent Of Code. I have no affiliation with this site

You can see a list of all challenges in the series by looking at the 'Linked' section of the first challenge here.

# Answer
> 5 votes
# JavaScript (ES6), 58 bytes

```
a=>a.reduce((p,[c,x,y,z])=>p+c+6*(y*z+x*(y+=z))+4*(x+y),0)

```

### Test cases

```
let f =

a=>a.reduce((p,[c,x,y,z])=>p+c+6*(y*z+x*(y+=z))+4*(x+y),0)

console.log(f([[7, 8, 6, 7], [7, 7, 5, 5], [8, 9, 6, 7], [6, 5, 10, 10], [5, 9, 6, 7], [9, 9, 10, 6], [8, 10, 10, 6], [6, 5, 7, 9], [7, 10, 8, 8], [5, 9, 9, 10]])) // 11866
console.log(f([[5, 10, 8, 9], [8, 8, 5, 8], [8, 7, 7, 6], [5, 9, 9, 10], [9, 7, 5, 8], [9, 8, 9, 5], [7, 5, 6, 7], [5, 7, 6, 10]])) // 8854
console.log(f([[9, 8, 8, 8], [10, 9, 8, 5], [10, 7, 5, 5], [10, 10, 6, 6], [8, 5, 8, 7]])) // 4853
console.log(f([[7, 7, 8, 10], [8, 10, 7, 8], [9, 7, 7, 8], [8, 5, 10, 5], [6, 6, 6, 8], [8, 9, 7, 5], [8, 5, 6, 5], [7, 9, 8, 5], [10, 10, 10, 8]])) // 9717
console.log(f([[5, 8, 9, 7], [5, 8, 7, 10], [5, 7, 7, 6], [5, 5, 5, 6], [9, 9, 5, 7], [5, 6, 7, 8], [8, 5, 8, 7], [6, 9, 5, 5], [10, 10, 9, 10]])) // 9418
console.log(f([[9, 9, 7, 10], [5, 8, 7, 9], [5, 5, 9, 8], [10, 5, 9, 10], [8, 5, 10, 7], [8, 9, 5, 5], [5, 10, 6, 10]])) // 8178
console.log(f([[5, 9, 5, 8], [7, 8, 10, 6], [7, 10, 7, 10], [8, 9, 7, 5], [5, 7, 8, 6], [9, 9, 6, 10], [6, 5, 9, 9], [7, 9, 9, 9]])) // 9766
console.log(f([[7, 10, 5, 10], [8, 10, 8, 9], [8, 6, 7, 8], [6, 9, 8, 5], [6, 7, 10, 9], [7, 6, 5, 8]])) // 7118
console.log(f([[10, 6, 7, 5], [5, 9, 5, 9], [9, 7, 8, 5], [6, 6, 9, 9], [9, 9, 6, 9], [10, 5, 8, 9], [7, 5, 6, 10], [9, 10, 5, 5]])) // 8007
console.log(f([[8, 10, 7, 8], [9, 10, 5, 8], [6, 7, 5, 6], [10, 10, 9, 8], [7, 5, 8, 9], [10, 10, 6, 7], [10, 8, 9, 10], [5, 10, 5, 5]])) // 9331
```

### How?

The only trick used here is to factorize **(xy + xz)** as **x(y + z)** and re-use the sum **(y + z)** in the last part of the formula.

```
a => a.reduce(                    // for each present in a:
  (s, [c, x, y, z]) =>            //   s = sum, [c, x, y, z] = present parameters
    s +                           //   add to s:
    c +                           //     c
    6 * (y * z + x * (y += z)) +  //     6(yz + x(y + z))
    4 * (x + y),                  //     4(x + (y + z))
  0                               //   initial sum = 0
)                                 // end of reduce()

```

# Answer
> 3 votes
# Mathematica, 34 bytes

```
Tr[#+6#2(+##3)+6##3+4(+##2)&@@@#]&

```

-10 bytes from @alephalpha

Try it online!

# Answer
> 2 votes
# Python 3, 56 bytes

```
lambda*a:sum(c+(6*x+4)*(y+z)+6*y*z+4*x for(c,x,y,z)in a)

```

Try it online!

* -2 bytes thanks to Mr. Xcoder!
* -15 bytes thanks to notjagan!
* -1 byte thanks to Alix Eisenhardt!

# Answer
> 2 votes
# C (gcc), ~~104~~ ~~100~~ ~~99~~ 93 bytes

```
t,x,y,z;f(A,a)int*A;{for(t=0;a--;)t+=*A+++6*((x=*A++)*(y=*A++)+(z=*A++)*(x+=y))+4*(x+z);t=t;}

```

Try it online!

Takes a list of present attributes (list length divisible by four) and an integer specifying the number of presents. Returns the cost of manufacturing all presents.

# Answer
> 2 votes
# Jelly, 25 bytes

```
Ḣɓ;1ị$$ṡ2P€S×6+⁸S×4¤+
Ç€S

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 17 bytes

```
vyćsO4*y¦æ2ùPO6*O

```

Try it online!

**Explanation**

```
v                  # for each present y
 yć                # extract the head (cost)
   s               # swap the dimensions to the top
    O4*            # sum and multiply by 4
       y¦          # push y with the head (cost) removed
         æ         # compute the powerset
          2ù       # keep only elements of length 2
            PO     # product and sum
              6*   # multiply by 6
                O  # sum everything

```

# Answer
> 0 votes
# Pyth, 39 bytes

```
u+G++hH*6++*@H1@H2*@H1@H3*@H2@H3*4stHQ0

```

Try it online!

Takes input as a string representation of a nested list and sums over the cost formula.

# Answer
> 0 votes
# Clean, 64 bytes

```
import StdEnv
f l=sum[c+6*(x*y+y*z+z*x)+4*(x+y+z)\\[c,x,y,z]<-l]

```

Try it online!

# Answer
> 0 votes
# Excel, 60 bytes

Input taken from Columns `A` to `D`, new row per present. Formula in any other column.

```
=SUMPRODUCT(A:A+6*(B:B*C:C+C:C*D:D+B:B*D:D)+4*(B:B+C:C+D:D))

```

---
Tags: code-golf, arithmetic
---


# Question
Title: Make sets disjoint without emptying them
Suppose you have a set of sets of integers. It's possible that some of the sets will overlap (i.e. sharing elements). You could get rid of the overlaps by deleting elements from the sets, but then some of them might end up empty; that would be a shame. Can we make all the sets disjoint without emptying any of them?

Note that in this situation, there's never any reason to leave multiple elements in a set, so this problem can always be solved by reducing each set to just one element. That's the version of the problem we're solving here.

## The task

Write a program or function, as follows:

**Input**: A list of sets of integers.

**Output**: A list of integers, of the same length as the input, for which:

* All integers in the output are distinct; and
* Each integer in the output is an element of the corresponding set of the input.

## Clarifications

* You can represent a set as a list if you wish (or whatever's appropriate for your language), disregarding the order of elements.
* You don't have to handle the case where no solution exists (i.e. there will always be at least one solution).
* There might be more than one solution. Your algorithm must always produce a valid solution, but is allowed to be nondeterministic (i.e. it's OK if it picks a different valid solution each time it runs).
* The number of distinct integers appearing in the input, *n*, will be equal to the number of sets in the input, and for simplicity, will be the integers from 1 to *n* inclusive (as their actual values don't matter). It's up to you whether you wish to exploit this fact or not.

## Testcases

```
[{1,2},{1,3},{1,4},{3,4}] -> [2,3,1,4] or [2,1,4,3]
[{1,3},{1,2,4},{2,3},{3},{2,3,4,5}] -> [1,4,2,3,5]
[{1,3,4},{2,3,5},{1,2},{4,5},{4,5}] -> [1,3,2,4,5] or [3,2,1,4,5] or [1,3,2,5,4] or [3,2,1,5,4]

```

## Victory condition

A program requires an optimal time complexity to win, i.e. if an algorithm with a better time complexity is found, it disqualifies all slower entries. (You can assume that your language's builtins run as fast as possible, e.g. you can assume that a sorting builtin runs in time O(n log n). Likewise, assume that all integers of comparable size to *n* can be added, multiplied, etc. in constant time.)

Because an optimal time complexity is likely fairly easy to obtain in most languages, the winner will therefore be the shortest program among those with the winning time complexity, measured in bytes.

# Answer
# Wolfram Language (Mathematica), 87 bytes and ϴ(n3)

```
-Range[n=Length@#]/.Rule@@@FindIndependentEdgeSet[Join@@Table[-i->j,{i,n},{j,#[[i]]}]]&

```

Try it online!

Builds a bipartite graph whose vertices on one side are the sets (indexed by `-1,-2,...,-n`) and whose vertices on the other side are the elements `1,2,...,n`, with an edge from `-i` to `j` when `j` is contained in the `i`-th set. Finds a perfect matching in this graph using a built-in. Then lists out the elements corresponding to `-1,-2,...,-n` in that order in the perfect matching.

Mathematica's `FindIndependentEdgeSet` is the bottleneck here; everything else takes O(n2) operations to do. Mathematica probably uses the Hungarian algorithm, and so I'll assume that it runs in **ϴ(n3)** time, though it's possible that Mathematica has a naive implementation with O(n4) complexity.
> 3 votes

# Answer
# Jelly, 8 bytes

```
Œp⁼Q$ÐfḢ

```

Try it online!

# Explanation

```
Œp⁼Q$ÐfḢ  Main Link
Œp        Cartesian Product of the elements; all possible lists
     Ðf   Filter; keep elements that are
  ⁼Q$     Equal to themselves uniquified
      Ḣ   Take the first one

```

Extremely inefficient. Asymptotic to **`ϴ(n^(n+1))`** according to Misha Lavrov; I think it's right.
> 2 votes

# Answer
# Haskell, 48 bytes

*-1 byte thanks to nimi.*

```
import Data.List
head.filter((==)<*>nub).mapM id

```

Try it online!
> 2 votes

# Answer
## Mathematica 39 Bytes

```
Last@Union[DeleteDuplicates/@Tuples@#]&

```

On the issue of complexity, I think it is very dependent upon the length of each sublist, as well as a measure of how disjoint the sublists are.

So, I think this algorithm is O(n Log n + n^2 Log m) where m is roughly the average length of each sublist.

Something like this would have complexity O(a^n) where a\>1 is a measure of the overlap in sublists:

```
(For[x={1,1},!DuplicateFreeQ@x,x=RandomChoice/@#];x)&

```

Hard to say which is really faster without knowing the properties of possible inputs.
> 1 votes

# Answer
# 05AB1E, 13 bytes, O(n!\*n)

```
āœʒ‚øε`QO}P}н

```

Try it online! Explanation:

```
ā               Make a range 1..n
 œ              Generate all permutations
  ʒ        }    Filter
   ‚ø           Zip with input
     ε   }      Loop over sets
      `QO       Check each element for membership
          P     All sets must match
            н   Take the first result

```
> 1 votes

# Answer
# Husk, 5 bytes

```
►oLuΠ

```

Try it online!

### Explanation

Just saw the thing about complexity: As so often it is the case with golfing languages' solution they are not very efficient - this one has complexity **O**(n·nⁿ).

```
►(Lu)Π  -- input as a list of lists, for example: [[1,2],[1,3],[1,4],[3,4]]
     Π  -- cartesian product: [[1,1,1,3],...,[2,3,4,4]]
►(  )   -- maximum by the following function (eg. on [1,1,1,3]):
   u    --   deduplicate: [1,3]
  L     --   length: 2

```
> 1 votes

# Answer
# Pyth, 9 bytes (ϴ(nn+1))

Since this works exactly like the Jelly solution, it most likely has the same complexity.

```
h{I#.nM*F

```

**Try it here!**

## How?

```
h{I#.nM*F | Full program.

       *F | Fold Cartesian product.
    .nM   | Flatten each.
   #      | Keep those:
 {I         That are invariant over duplicate elements removal.
h         | Take the first element.

```
> 0 votes

# Answer
# JavaScript (ES6), ~~74~~ 73 bytes

*1 byte saved, thanks to @Neil.*

```
f=([a,...A],s=[],S)=>a?a.map(c=>s.includes(c)||(S=S||f(A,[...s,c])))&&S:s

```

Recursively iterates through the array looking for a solution.

**Ungolfed:**

```
f=(
   [a, ...A],                        //a is the first array, A is the rest
   s = [],                           //s is the current trial solution
   S                                 //S holds the solution (if one exists) at this branch
  )=>
     a ? a.map(                      //if we're not done, iterate through a
           c => s.includes(c) ||     //  if this element already exists, short-circuit
                (S = S ||            //  else if S has a solution, keep it
                 f(A, [...s, c])     //  else look for a solution down this branch
                )
         ) && S                      //return S

```

**Test Cases:**

```
f=([a,...A],s=[],S)=>a?a.map(c=>s.includes(c)||(S=S||f(A,[...s,c])))&&S:s

console.log(f([[1,2],[1,3],[1,4],[3,4]])) // [2,3,1,4] or [2,1,4,3]
console.log(f([[1,3],[1,2,4],[2,3],[3],[2,3,4,5]])) // [1,4,2,3,5]
console.log(f([[1,3,4],[2,3,5],[1,2],[4,5],[4,5]])) // [1,3,2,4,5] or [3,2,1,4,5] or [1,3,2,5,4] or [3,2,1,5,4],4]
```
> 0 votes

# Answer
# Python3, ~~93~~ 84 bytes

*-9 bytes thanks to caird coinheringaahing*

```
lambda I:next(filter(lambda x:len(x)==len({*x}),product(*I)))
from itertools import*

```

Try it online!
> 0 votes

---
Tags: code-golf, array, puzzle-solver, restricted-complexity
---