Build a 2-way universal logic processor using NAND logic gates A 2-way universal logic processor (2ULP) is a network of logic gates that takes two input wires A and B, as well as four other inputs L_, L_a, L_b, and L_ab, and produces a single output L(a, b) using the four L inputs as a truth table function:

The 2ULP returns L_ if A and B are both 0.
It returns L_a if A = 1 and B = 0.
It returns L_b if A = 0 and B = 1.
It returns L_ab if A and B are both 1.

For example, given the inputs L_ = 0, L_a = 1, L_b = 1, and L_ab = 0, then the output L(a, b) will be equal to A xor B.

Your task is to build a 2ULP using only NAND gates, using as few NAND gates as possible. To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores:

NOT: 1
AND: 2
OR: 3
XOR: 4

Each of these scores corresponds to the number of NAND gates that it takes to construct the corresponding gate.

The logic circuit that uses the fewest NAND gates to produce a correct construction wins.

11 NANDs

Define the gate MUX (cost 4) as

MUX(P, Q, R) = (P NAND Q) NAND (NOT P NAND R)

with truth table

P Q R    (P NAND Q)   (NOT P NAND R)    MUX
0 0 0        1               1           0
0 0 1        1               0           1
0 1 0        1               1           0
0 1 1        1               0           1
1 0 0        1               1           0
1 0 1        1               1           0
1 1 0        0               1           1
1 1 1        0               1           1

Then this is the familiar ternary operator MUX(P, Q, R) = P ? Q : R

We simply have

2ULP = MUX(A, MUX(B, L_ab, L_a), MUX(B, L_b, L_))

for a cost 12, but there's a trivial one-gate saving by reusing the NOT B from the two inner MUXes.


Fivenum and a little bit (a paradox, a paradox, a most ingenious paradox)
This is the first part of a multipart series inspired by different R functions.
The Task
Given a dataset \$D\$ of positive integers, I need you to compute the 5 number summary of \$D\$. However, I'm working on large datasets, so I need your code to be as small as possible, allowing me to store it on my computer.
The five number summary consists of:

Minimum value
First quartile (Q1)
Median / Second quartile (Q2)
Third quartile (Q3)
Maximum value

There are several different ways of defining the quartiles, but we will use the one implemented by R:
Definitions:

Minimum and maximum: the smallest and largest values, respectively.
Median: the middle value if \$D\$ has an odd number of entries, and the arithmetic mean of the two middle-most values if \$D\$ has an even number of entries. Note that this means the median may be a non-integer value. We have had to Compute the Median before.
First and Third Quartiles: Divide the data into two halves, including the central element in each half if \$D\$ has an odd number of entries, and find the median value of each half. The median of the lower half is the First Quartile, and the median of the upper half is the Third Quartile.

Examples:
\$D=[1,2,3,4,5]\$. The median is then \$3\$, and the lower half is \$[1,2,3]\$, yielding a first quartile of \$2\$, and the upper half is \$[3,4,5]\$, yielding a third quartile of \$4\$.
\$D=[1,3,3,4,5,6,7,10]\$. The median is \$4.5\$, and the lower half is \$[1,3,3,4]\$, yielding a first quartile of \$3\$, and the upper half is \$[5,6,7,10]\$, yielding a third quartile of \$6.5\$.
Additional rules:

Input is as an array or your language's nearest equivalent.
You may assume the array is sorted in either ascending or descending order (but please specify which).
You may return/print the results in any consistent order, and in whichever flexible format you like, but please denote the order and format in your answer.
Built-in functions equivalent to fivenum are allowed, but please also implement your own solution.
You may not assume each of the five numbers will be an integer.
Explanations are encouraged.
This is code-golf, so shortest answer in each language wins!

Randomly generated test cases
1 1 1 1 1 2 2 2 2 2 3 3 4 4 4 4 4 5 5 5 -> 1 1.5 2.5 4 5
1 2 2 2 4 4 5 5 6 7 7 8 9 9 9 9 9 10 10 10 -> 1 4 7 9 10
2 2 2 6 8 10 15 16 21 22 23 24 26 33 35 38 38 45 46 47 48 -> 2 10 23 38 48
1 2 9 -> 1 1.5 2 5.5 9
1 2 3 3 3 4 9 -> 1 2.5 3 3.5 9
1 1 2 5 7 7 8 8 15 16 18 24 24 26 26 27 27 28 28 28 29 29 39 39 40 45 46 48 48 48 48 49 50 52 60 63 72 73 79 85 86 87 88 90 91 93 94 95 95 97 100 -> 1 25 45 76 100
2 2 4 4 6 8 10 11 13 14 14 15 17 21 23 24 26 27 27 28 28 30 31 33 33 34 36 36 38 38 39 40 41 42 42 43 45 45 47 47 47 47 47 48 48 48 50 51 53 53 55 56 56 56 57 57 58 62 62 63 64 64 65 65 66 67 67 67 68 69 69 71 71 71 74 79 80 81 81 81 82 82 83 83 86 86 86 87 89 94 94 94 95 95 97 98 99 100 100 100 -> 2 33.5 54 76.5 100
1 3 3 4 -> 1 2 3 3.5 4
1 3 3 3 4 -> 1 3 3 3 4

R, 7 bytes

fivenum

Try it online!

Obvious cheeky answer. ;-)

Interestingly, fivenum(x) is not equivalent to summary(x) even when x is numeric, as the quantiles are computed differently: fivenum averages at discontinuities, whereas summary interpolates. You can force summary to behave like fivenum with the option quantile.type, but this is still longer than

R, 51 bytes

function(x)quantile(x,(0:4)/4,t=2+5*!sum(!!x)%%4-3)

Try it online!

which computes the quantiles of order 0 (min), 0.25 (Q1), 0.5 (median), 0.75 (Q3) and 1 (max). The t=2 specifies how quantiles are defined: there are 9 possible types, and the challenge definition corresponds to type 2 in most cases, and to type 7 when \$n\equiv 3\pmod 4\$. Honestly, this choice of a definition of quantiles is a bit weird.

Note that the source code of the fivenum built-in is very different (and much longer).


Consolidate an Array The task is simple: consolidate an array of ints. Consolidating this array consists of the following:

All instances of 0 need to be moved to the end of the array.
There should be no 0s between the non-zero integers.
All non-zero indices should retain their order.

Challenge

Consolidate an array in the least amount of bytes.

You are consolidating an array of random length with a size up to your language's max with random integers. Input may be any natural way for your language.

Examples

Input

0 5 8 8 3 5 1 6 8 4 0 3 7 5 6 4 4 7 5 6 7 4 4 9 1 0 5 7 9 3 0 2 2 4 3 0 4 8 7 3 1 4 7 5 1 2 1 8 7 8 7 7 2 6 3 1 2 8 5 1 4 2 0 5 0 6 0 3

Output

5 8 8 3 5 1 6 8 4 3 7 5 6 4 4 7 5 6 7 4 4 9 1 5 7 9 3 2 2 4 3 4 8 7 3 1 4 7 5 1 2 1 8 7 8 7 7 2 6 3 1 2 8 5 1 4 2 5 6 3 0 0 0 0 0 0 0 0

Input

-1 -7 -6 5 1 -5 -2 7 -3 -8 0 8 9 1 -8 -1 6 -4 1 -2 1 -7 5 4 -6 7 -3 9 8 3 -1 0 -5 -7 3 8 1 1 3 -3 -2 -2 0 -7 0 -4 8 6 -3 6 0 5 3 2 2 2 -2 -7 -3 9 -1 6 0 6 -7 9 4 -2 8 -8 -4 1 -8 4 3 7 3 5 1 0 3 3 7 -1 -5 1 -3 4 -7 0 3 2 -2 7 -3 0 0 2 -5 8 -3 -2 -7 -5 7 -3 -9 -7 5 8 -3 9 6 7 -2 4 7

Output

-1 -7 -6 5 1 -5 -2 7 -3 -8 8 9 1 -8 -1 6 -4 1 -2 1 -7 5 4 -6 7 -3 9 8 3 -1 -5 -7 3 8 1 1 3 -3 -2 -2 -7 -4 8 6 -3 6 5 3 2 2 2 -2 -7 -3 9 -1 6 6 -7 9 4 -2 8 -8 -4 1 -8 4 3 7 3 5 1 3 3 7 -1 -5 1 -3 4 -7 3 2 -2 7 -3 2 -5 8 -3 -2 -7 -5 7 -3 -9 -7 5 8 -3 9 6 7 -2 4 7 0 0 0 0 0 0 0 0 0 0

Example Code (Java)

public class Consolidate {
    public static void main(String[] args) throws Exception {
        int[] toConsolidate = new int[args.length];
        for (int i=0; i<args.length; i++){
            toConsolidate[i]=Integer.parseInt(args[i]);
        }
        for (int i=0; i<toConsolidate.length; i++) {
            for (int k=0; k<toConsolidate.length-1; k++) {
                if (toConsolidate[k] == 0){
                    toConsolidate[k] = toConsolidate[k+1];
                    toConsolidate[k+1] = 0;
                }
            }
        }
        for (int i:toConsolidate)
            System.out.print(i+" ");
    }
}

Pyth, 3 bytes
!DQ

Explanation:
  Q    Input
!D     Sort by logical NOT

Try it here.


Generate the Abacaba sequence This challenge is about printing the abacaba sequence of a specific depth.

Here is a diagram of the first 5 sequences (a(N) is the abacaba sequence of depth N, upper/lowercase is just to show the pattern, this is not needed in the output of your program):

a(0) = A
a(1) = aBa
a(2) = abaCaba
a(3) = abacabaDabacaba
a(4) = abacabadabacabaEabacabadabacaba
...
a(25) = abacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabahabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabaiabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabahabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabajabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabahabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabaia...

As you can probably tell, the n'th abacaba sequence is the last one with the n'th letter and itself again added to it. (a(n) = a(n - 1) + letter(n) + a(n - 1))

Your task is to make a program or function that takes an integer and prints the abacaba sequence of that depth. The output has to be correct at least for values up to and including 15.

Pyth, 11 bytes
u++GHG<GhQk

Simple reduction.


Oscillation equality We have objects that oscillate between two integer points, [l, r], at the speed of one unit per time unit, starting at l on t=0. You may assume l < r. For example, if an object oscillates on [3, 6], then we have:

t=0 -> 3
t=1 -> 4
t=2 -> 5
t=3 -> 6
t=4 -> 5
t=6 -> 4
t=7 -> 3
t=8 -> 4

Etc. But objects oscillate continuously, so we  also have t=0.5 -> 3.5 and t=3.7 -> 5.3.

Given two objects oscillating between [l1, r1], [l2, r2], determine if there is ever a time t such that the two objects share the same position. You make take l1, r1, l2, r2 in any convenient format, and output any truthy/falsy values.

Truthy inputs:

[[3, 6], [3, 6]]
[[3, 6], [4, 8]]
[[0, 2], [2, 3]]
[[0, 3], [2, 4]]
[[7, 9], [8, 9]]

Falsy inputs:

[[0, 3], [3, 5]]
[[0, 2], [2, 4]]
[[5, 8], [9, 10]]
[[6, 9], [1, 2]]
[[1, 3], [2, 6]]

Python 2, 69 bytes

l,r,L,R=input()
d=r-l;k=1
while(R-L)*k%d:k+=1
print r-L>=k%2*d/k<=R-l

Try it online!


Smallest palindrome divisible by the input Given a positive integer N, output the smallest positive integer such that this number is a palindrome (i.e. is its own reverse) and is divisible by N.

The palindrome (i.e. the output) must not need a leading zero to be a palindrome, e.g. 080 is not the valid answer for 16.

The input will never be a multiple of 10, because of the previous reason.

Your program may take as much time as necessary, even if in practice it would be way too long to output the answer.

Inputs and outputs

You may take the input through STDIN, as a function argument, or anything similar.
You may print the output to STDOUT, return it from a function, or anything similar.
Inputs and outputs must be in the decimal base.

Test cases

N        Output
1        1
2        2
16       272
17       272
42       252
111      111
302      87278
1234     28382

Scoring

This is code-golf, so the shortest answer in bytes wins.

Haskell, 45 37 34 bytes
(+)>>=until((reverse>>=(==)).show)


Graph Google Search Results When you search for something on Google, it conveniently gives a message near the top of the page saying something like About 53,000,000 results (0.22 seconds). (The numbers change depending on what was searched of course.)
In this challenge you will write a program that draws a logarithmic ASCII graph of the number of results given by Google when all the non-empty prefixes of a given search-phrase are searched.
A search-phrase is defined as one or more strings of lowercase alphanumeric characters, separated by one space from each other. In Regex a search-phrase is (?:[a-z0-9]+ )*[a-z0-9]+.
So im ok, r, and 1a 2 are all search-phrases, but I'm OK, R, 1a  2, and  , are not.
(The character restrictions are in place because Google rarely takes case or special symbols into account. Escaping non-alphanumeric characters in URLs is also a hassle.)
Spec
Your program must take in a search-phrase and a positive floating point number H from either stdin or the command line. (You can assume they are valid and it's fine if you need quotes or something around the search-phrase.)
As a working example let's assume the search phrase is a car and H = 0.75.
Step 1:
Gather the non-empty prefixes of your search-phrase, and put them in double quotes. The quotes ensure that that the exact phrase will be searched for, avoiding any 'did you mean...' redirections.
Exclude all prefixes that end in a space such as a[space].
Prefixes
"a"
"a c"
"a ca"
"a car"

Step 2:
Search each of these terms exactly as they appear using https://www.google.com, and note the number of results returned.
Search Term    Message                                       Results
"a"            About 6,950,000,000 results (0.27 seconds)    6950000000
"a c"          About 861,000,000 results (0.27 seconds)      861000000
"a ca"         About 2,990,000 results (0.30 seconds)        2990000
"a car"        About 53,900,000 results (0.39 seconds)       53900000

If the search term did not match any documents, put a 0 in the Results column.
Step 3:
Compute y = floor(H * log10(r + 1)) for each row, where r is the Results value. H is still 0.75 here.
Search Term    Results       y
"a"            6950000000    7
"a c"          861000000     6
"a ca"         2990000       4
"a car"        53900000      5

Step 4:
Arrange y number of vertical bars (|) above the last character of each unquoted search term, using spaces to fill empty areas, in a sort of bar graph.
|
| |
| | |
| |||
| |||
| |||
| |||
a car

This graph is the final result of your program and the only thing it needs to output. It should go to stdout.
Scoring
This is code-golf, so the shortest program in bytes wins.
Notes

You may use URL shorteners or other search tools/APIs as long as the results would be the same as searching https://www.google.com.
I know that double quotes are not a surefire way to exclude "did you mean..." redirections. Adding &nfpr=1 to the URL doesn't always work either. Don't worry about these inaccuracies. Just look for the About X results... message no matter what pops up, or set Results to 0 if there is none.
There is an empty column above any space in the search-phrase in the graph.
The graph should not be wider or taller than it needs to be (e.g. with whitespace).
It's ok if your program has side effects like opening a web browser so the cryptic Google html/js pages can be read as they are rendered.

Ruby, 316 295 bytes

require 'open-uri'
s,h=*$*
r=[]
s.size.times{|i|r<<(s[i]==' '?'':?|*(h.to_f*Math.log10((URI.parse("http://google.com/search?q=#{URI::encode ?"+s[0..i]+?"}").read[/About [\d,]+ results/]||?0).gsub(/\D/,'').to_i+1)).floor)+s[i]}
puts r.map{|l|l.rjust(r.map(&:size).max).chars}.transpose.map &:join

Unfortunately, the requests just stopped working on the online tester I was using, so I need to golf this down further tonight or tomorrow.

Explanation: I'm taking the input via ARGV. Then I'm just sending a request for each substring that doesn't end in a space, find the results via regex (and default to 0 if the regex doesn't match), and then build the histogram with horizontal bars. At the end, I'm reversing all lines and transposing them to create the vertical histogram.


Choose Your Own Adventure Choose Your Own Adventure books are a form of interactive literature where the reader must
make decisions that affect the outcome of the story. At certain points in the story, the
reader has multiple options that can be chosen, each sending the reader to a different page
in the book.

For example, in a fantasy setting, one might have to decide on page 14 whether to venture
into a mysterious cave by "jumping" to page 22, or to explore the nearby forest by jumping
to page 8. These "jumps" can be expressed as pairs of page numbers, like so:

14 22
14 8

In most cases, there are many endings to the story but only a few good ones. The goal is to
navigate the story to reach a good ending.

Task:

Given a list of "jumps" for a given book, your task is to determine a route that will lead
to a specific ending. Since this is fairly easy, the true challenge is to do it in as few
characters as possible.

This is code golf.

Sample input (where 1 is the start and 100 is the goal):

1 10
10 5
10 13
5 12
5 19
13 15
12 20
15 100

Sample output:

1 10 13 15 100

Sample input:

15 2
1 4
2 12
1 9
3 1
1 15
9 3
12 64
4 10
2 6
80 100
5 10
6 24
12 80
6 150
120 9
150 120

Sample output:

1 15 2 12 80 100

Notes:

The list of jumps will be input by the user, either from a file or stdin. You may choose whichever is most convenient.
The input will contain 1 jump per line, with the origin and destination separated by a single space.
The lines in the input are not guaranteed to be in any specific order.
A successful path will start at page 1 and end at page 100.
You may assume there is at least 1 path to the goal. You do not need to find all paths, nor do you need to find the shortest. Just find at least one.
The smallest page number will be 1. There is no limit to the largest page number. (You can assume that it will fit in the range of an int.)
Loops may exist. For example, the list may have jumps from page 5 to 10, 10 to 19, and 19 to 5.
There may be dead-ends. That is, a destination page might not have anywhere to jump to.
Conversely, there may be unreachable pages. That is, an origin page might not be the destination of any jumps.
Not all page numbers between 1 and 100 are guaranteed to be used.
Your output should consist of a valid route of page numbers, starting with 1 and ending at 100, separated by spaces.

Remember, this is code golf, so the shortest solution wins!

EDIT: Added another sample for testing.

Python, 232 213 157 143 135 132 chars (shortest path)

This implementation can handle all of the edge cases described (loops, dead ends, orphan pages etc.) and guarantees that it will find the shortest route to the ending. It is based on Djikstra's shortest path algorithm.

import sys
l=[k.split()for k in sys.stdin]
s={"100":"100"}
while"1"not in s:
 for i,j in l:
    if j in s:s[i]=i+" "+s[j]
print s["1"]


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

Some built-in functions with long names can be replaced with shorter expressions.

For example:

Total => Tr
Transpose => Thread or \[Transpose]
True => 1<2
False => 1>2
Times => 1##&
Alternatives => $|##&
IntegerQ => ⌊#⌋==#&
a[[1]] => #&@@a
a[[All,1]] => #&@@@a
ConstantArray[a,n] => Array[a&,n] or Table[a,{n}]
Union@a => {}⋃a or a⋃a
ToExpression@n => FromDigits@n if n is a number
Divisible[n,m] => m∣n
FromDigits[n,2] => Fold[#+##&,n] if n is a list of 0s and 1s
Complex@z => {1,I}.z where z is a list of the form {x,y}


SOGL V0.12, 24 bytes
ā.∫ā;∫ \*+}ø┼↔±╬¡;øΚ┼}╬³

Try it Here!
Explanation:
ā                         push an empty array (the main canvas)
 .∫                  }    iterate over the input, pushing 1-indexed iteration
   ā;                       push an empty array below the iteration
     ∫    }                 iterate over the iteration counter
       \*                     push current iteration amount of slashes
         +                    append those to the 2nd array
           ø┼               append nothing (so it'd space the array to a square)
             ↔±             reverse horizontally (swapping slashes)
               ╬¡           quad-palindromize with 0 overlap and swapping characters as required
                 ;          get the canvas ontop
                  øΚ        prepend to it an empty line (so the now bigger romb would be one up)
                    ┼       append horizontally the canvas to the current romb
                      ╬³  palindromize horizontally with no overlap and swapping characters


Mask values in a .env file for a screencast Let's say I have a .env file with the following contents:

CF_WORKERS_ACCOUNT_ID=abcdef34632114
CF_WORKERS_API_TOKEN=abcdef34632114def3463def3463
FAB_DEV_ZONE_ID=434932843272439874329

I'm doing a screencast, and I want to quickly cat .env to show what's in the file, without broadcasting the exact values, since they're secret.

What I want is a one-line unix command (I'm on OSX personally) that gives me:

> cat .env | some_command
CF_WORKERS_ACCOUNT_ID=••••••••••••••
CF_WORKERS_API_TOKEN=••••••••••••••••••••••••••••
FAB_DEV_ZONE_ID=•••••••••••••••••••••

A little thing, but would be neat!

My best attempt is cat .env | ruby -pe 'k,v=$_.split("=");$_="#{k}=#{v.gsub(/./,"•")}"' but I'm sure it can be shorter...

05AB1E, 12 bytes

Uhh, I'd just solve it anyway...

'=¡`g'•иJ'=ý

Try it online!

Explanation

'=¡          Split by equal signs
   `         Put both parts onto the stack
    g        Find the length of the second item
     '•иJ    Repeat that many •'s
         '=ý Join by the equal sign


Directory calculation For this challenge, you will be given an absolute path, and a "new" path (which can be absolute or relative), and you need to return the final path.
For example, if your current directory was /var/tmp/test:
my_dir or my_dir/  should return /var/tmp/test/my_dir
../../my_dir should return /var/my_dir
/my_dir/./ should return /my_dir
../../../../../ should return /
To be more pedantic:

A directory is a non-empty string consisting of alphanumeric characters and the symbols -,_, or .
A path is a list of 0 or more directories, separated using /.  An absolute path starts with a /, a relative path does not.  Paths can include an ending /.

You need to "resolve" the second path, given the first path.
The process of resolving is:

Test if the second path is relative.  If so, then insert the absolute path's directories to the beginning of the second path.
If any of the directories is .., then remove it and the preceding directory.  If it is the first directory, then simply remove it.
If any of the directories is ., then remove it.
Output the final absolute path.  You should not output an ending /.

You do not need to handle incorrect input.  The commands should work, whether or not the directories passed actually exist on your machine.  You can assume that everything is a directory, even if it has an extension.
Test cases
Absolute      New          Output
"/a/b/c"      "d"       -> "/a/b/c/d"
"/a/b/c/"     "d"       -> "/a/b/c/d"
"/a/b/c/"     "d/"      -> "/a/b/c/d"
"/a/b/c"      "/d"      -> "/d"
"/a/b/c"      "/d/"     -> "/d"
"/../a/b/c/"  "d"       -> "/a/b/c/d"
"/a/../b/c/"  "d"       -> "/b/c/d"
"/a/b/../c"   "d"       -> "/a/c/d"
"/a/b/c/.."   "d"       -> "/a/b/d"
"/a/b/c/"     ".."      -> "/a/b"
"/a/b/c"      "../d"    -> "/a/b/d"
"/a/b/c"      "/../d"   -> "/d"
"/a/b/c"      ""        -> "/a/b/c"
"/a/b/c"      "."       -> "/a/b/c"
"/a/b/c"      "./d"     -> "/a/b/c/d"
"/a/b/c"      "/./d"    -> "/d"
"/a/b/c"      "d.txt"   -> "/a/b/c/d.txt"
"/a/b/c"      "d."      -> "/a/b/c/d."
"/a/b/c"      ".txt"    -> "/a/b/c/.txt"
"/a/b/c"      ".txt/d"  -> "/a/b/c/.txt/d"
"/a/b/."      "./././." -> "/a/b"
"/direc"      "tory"    -> "/direc/tory"
"/a-_.b/"     "__._-."  -> "/a-_.b/__._-."
"/a/b"        "../.."   -> "/"
"/a/b"        "../../.."-> "/"
"/a"          "../../.."-> "/"
"/"           ""        -> "/"
"/"           "a"       -> "/a"
"/.."         "a"       -> "/a"
"/."          ""        -> "/"

This is a code-golf, so make your submissions as short as possible in your favorite language!

Retina, 44 bytes

+`.+ /| |/\.?/
/
+1`/?[^/]*/\.\.|/\.?$

^$
/

Input is expected to be the two paths separated by a single space.

Try it online! (The first line enables a linefeed-separated test suite.)


JavaScript (ES6), 26 bytes
1-indexed.

a=>a.map(o=x=>o[x]=-~o[x])

Try it online!
Commented
a =>                // a[] = input array
  a.map(o =         // assign the callback function of map() to the variable o, so that
                    // we have an object that can be used to store the counters
    x =>            // for each value x in a[]:
      o[x] = -~o[x] //   increment o[x] and yield the result
                    //   the '-~' syntax allows to go from undefined to 1
  )                 // end of map()


Ruby 2.5, 98 bytes

-15.upto(15){|y|68.times{|x|z=0;250.times{z=0.035*x-1.9751+y/17.21i+z*z};putc z.abs<2?42:32};puts}

Try it online!
Very straightforward implementation, with a little bit of trickery to allow using times instead of upto in the inner loop.
Unfortunately, loop merging is two bytes longer, although it may help in other languages:
-1034.upto(1104){|x|z=0;250.times{z=x%69*0.035-2.0101+x/69/17.21i+z*z};putc x%69>0?z.abs<2?42:32:10}


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

Something that one must know before starting to golf:

In MATLAB calculations a character behaves the same as its ascii code.

'abc' - 'a'  % Returns: [0 1 2]
'123' - '0'  % Returns: [1 2 3]
'“' == 8220  % Returns: 1 (logical)
'a':'e'==100 % Returns: [0 0 0 1 0] (logical)


Golf an Anagram Quine In this question I asked you to guess an anagram quine based on its output.  However it looks like we don't have a question asking to golf an anagram quine yet.  So your task will be to make the shortest anagram quine that you can.

What is an anagram quine?

An anagram quine is a non empty program that prints an anagram of its source code, other than its original source.

Here's an example of an anagram quine in Python 2:

print`'`print`*2'*2`

You should not read your own source for this challenge.

Pyth, 2 bytes

)(

Outputs

()

Try it online!

)  # Ends statement, does nothing in this program
 ( # Create an empty tuple
   # Implicitly print the empty tuple


Brainf*ckish directions Your task – should you choose to accept it – is to build a program that parses and evaluates a string (from left to right and of arbitrary length) of tokens that give directions – either left or right. Here are the four possible tokens and their meanings:

>  go right one single step
<  go left one single step
-> go right the total amount of single steps that you've gone right, plus one,
   before you previously encountered this token and reset this counter to zero
<- go left the total amount of single steps that you've gone left, plus one,
   before you previously encountered this token and reset this counter to zero

There's a catch though – the tokens of directions your program should be able to parse will be presented in this form:

<<->-><<->->>->>->

... in other words, they are concatenated, and it is your program's task to figure out the correct precedence of directions and amount of steps to take (by looking ahead). The order of precedence is as follows (from highest to lowest precedence):

->
<-
>
<

If you encounter <- when no steps to the left had previously been made since either the start or since the last reset, take one single step to the left. Same rule applies to ->, but then for going to the right.

Your program should start at 0 and its result should be a signed integer representing the final end position.

You may expect the input to always be valid (so, nothing like <--->>--<, for instance).

Example input:

><->><-<-><-<>>->

Steps in this example:

 step | token | amount | end position
------+-------+--------+--------------
   1. |   >   |     +1 |           1
   2. |   <   |     -1 |           0
   3. |  ->   |     +2 |           2
   4. |   >   |     +1 |           3
   5. |   <-  |     -2 |           1
   6. |   <   |     -1 |           0
   7. |  ->   |     +2 |           2
   8. |   <-  |     -2 |           0
   9. |   <   |     -1 |          -1
  10. |   >   |     +1 |           0
  11. |   >   |     +1 |           1
  12. |  ->   |     +3 |           4

For clarification: the output of the program should only be the final end position as a signed integer. The table above is just there to illustrate the steps my example took. No need to output such a table, table row, or even just the steps' end positions. Only the final end position, as a signed integer, is required.

Shortest code, after one week, wins.

Python 2.7 - 154 147 134 128 bytes

l=r=p=0
exec"exec raw_input('%s->','p+=r+1;r=0%s<-','p-=l+1;l=0%s>','r+=1;p+=1%s<','l+=1;p-=1;')"%((";').replace('",)*4)
print p

Serious changes have been made to the way this program works. I've removed the old explanation, which can still be found in this answer's edit history.

This one's gross.

It works pretty much the same way as other answers for this question, replacing the characters in the input with valid statements in that language and executing them. There's one major difference, though: replace is a long word. Screw that.

@ProgrammerDan in chat came up with the idea of using a tuple with the string ;').replace(' in it 4 times, to use the pre-str.format() method of formatting text. Four instances of %s are in the string on the second line, each one taking its value from the associated element of the tuple at the end. Since they're all the same, each %s is replaced with ;').replace('. When you perform the operations, you get this string:

exec raw_input(';').replace('->','p+=r+1;r=0;').replace('<-','p-=l+1;l=0;').replace('>','r+=1;p+=1;').replace('<','l+=1;p-=1;')

This is now valid python code that can be executed with exec. That's right, baby: Nested execs let me use string operations on code that needs to perform string operations on code. Someone please kill me.

The rest of it is pretty straightforward: Each command is replaced with code that keeps track of three variables: The current position, the number of rights since the last ->, and the same for lefts and <-. The whole thing is run and the position is printed.

You'll notice that I do raw_input(';'), using ';' as a prompt, rather than raw_input() which has no prompt. This saves characters in an unintuitive way: If I did raw_input(), I'd have to have the tuple filled with ).replace(', and every instance of %s would have ';\'' before it except the first one. Having a prompt creates more redundancy so I can save more characters overall.


Shortest code - Finding the kth good cipher Challenge: A cipher (which is a positive integer) which has any substring not divisible by 2, or has a substring divisible by 11 (other than 0), is defined as 'bad'. All other ciphers are defined as 'good'. Find the kth cipher, in ascending order, which is 'good'.

Input format

The first line of input has a single integer T, the total number of test cases. The next T lines each have an integer k on them.

Output Format

The output should contain T integers on T different lines, the kth good cipher.

Sample Input

2
1
136

Sample Output

2
4008

Perl, 75 74 characters

map{map{1while++$n=~/[13579]|(.+)(?(?{$^N<1|$^N%11})!)/}1..<>;$n=say$n}1..<>

I should point out that the character count is taking advantage of Perl's bizarre feature of allowing a special variable of the form $^X to be spelled with a literal ctrl-X character.

The regex extensions being utilized are also terrifying, but boy do they come in handy.


Center of Mass from a list of coordinates and their masses Here is a quick Monday morning challenge...

Write a function or program in the least number of bytes that:

Takes as input a list of [x,y] coordinates
Takes as input a list of the [x,y] coordinates' respective masses
Outputs the calculated center of mass in the form of [xBar,yBar].

Note:

Input can be taken in any form, as long as an array is used.

The center of mass can be calculated by the following formula:

In plain English...

To find xBar, multiply each mass by its respective x coordinate, sum the resulting list, and divide it by the sum of all masses.
To find yBar, multiply each mass by its respective y coordinate, sum the resulting list, and divide it by the sum of all masses.

Trivial Python 2.7 example:

def center(coord, mass):
    sumMass = float(reduce(lambda a, b: a+b, mass))
    momentX = reduce(lambda m, x: m+x, (a*b for a, b in zip(mass, zip(*coord)[0])))
    momentY = reduce(lambda m, y: m+y, (a*b for a, b in zip(mass, zip(*coord)[1])))
    xBar = momentX / sumMass
    yBar = momentY / sumMass
    return [xBar, yBar]

Test Cases:

> center([[0, 2], [3, 4], [0, 1], [1, 1]], [2, 6, 2, 10])
[1.4, 2.0]

> center([[3, 1], [0, 0], [1, 4]], [2, 4, 1])
[1.0, 0.8571428571428571]

This is code-golf, so the least number of bytes wins!

MATL, 6 5 bytes

ys/Y*

Input format is a row vector with the masses, then a two-column matrix with the coordinates (in which spaces or commas are optional).

First example:

[2, 6, 2, 10]
[0,2; 3,4; 0,1; 1,1]

Second example:

[2, 4, 1]
[3,1; 0,0; 1,4]

Try it online!

Explanation

Let m denote the vector of masses (first input) and c the matrix of coordinates (second input).

y     % implicitly take two inputs. Duplicate the first.
      % (Stack contains, bottom to top: m, c, m)
s     % sum of m.
      % (Stack: m, c, sum-of-m)
/     % divide.
      % (Stack: m, c-divided-by-sum-of-m)
Y*    % matrix multiplication.
      % (Stack: final result)
      % implicitly display


Create an ASCII art unjumble! Given a string of ASCII art like such (This isn't ASCII art but it will do for the example):

abc
d e
fgh

Jumble it as if it was being displayed on a screen with one character per line, like so:

a
b
c
d

e
f
g
h

Print the result, wait one second, ±0.5 seconds before clearing the terminal and the print the same thing, but with 2 characters displayed per line instead of 1. Basically, the width of the display turns from 1 to 2.

ab
c
d
e
fg
h

Note the space after the d. Repeat waiting, then printing with an additional character per line until the inputted text is outputted.

If you hit the end of a line when trying to print characters, then you insert a newline and print the rest of them following this rule. For example the input:

abcdefg
ab

Would print the following when the display length is 4.

abcd
efg
ab

You can find the effect of the terminal resize here: https://repl.it/GoeU/1. Run the program, then drag the thing separating the terminal from the text editor back and forth.

Clarification:

Once a line appears exactly how it was inputted, you can leave that line alone for future larger character counts per line.

abc
ab

should print

ab
c
ab

when the sentence length = 2.

This is code-golf, so least amount of bytes wins!

Rules:

Must print to STDOUT as the only output.
Must clear the terminal, or create the illusion of clearing the terminal by adding 150 or so empty lines.
Can take input through the standard methods.
Default loopholes apply.
Trailing stuff with the text is NOT OKAY.

This idea came to me when I was resizing a terminal with ASCII art on it. It looked interesting, so I decided to make a challenge out of it.

Test cases:

Since it would be too much work to show each step for each test case individually, I will review each answer to make sure it is valid. Make sure the answer can handle the test cases.

 ______   ______     __     __   __     ______      __    __     ______
/\  == \ /\  == \   /\ \   /\ "-.\ \   /\__  _\    /\ "-./  \   /\  ___\
\ \  _-/ \ \  __<   \ \ \  \ \ \-.  \  \/_/\ \/    \ \ \-./\ \  \ \  __\
 \ \_\    \ \_\ \_\  \ \_\  \ \_\\"\_\    \ \_\     \ \_\ \ \_\  \ \_____\
  \/_/     \/_/ /_/   \/_/   \/_/ \/_/     \/_/      \/_/  \/_/   \/_____/

This pastebin.

                        __/\__
                        \    /
                  __/\__/    \__/\__
                  \                /
                  /_              _\
                    \            /
      __/\__      __/            \__      __/\__
      \    /      \                /      \    /
__/\__/    \__/\__/                \__/\__/    \__/\__

Python 3.6, 124 bytes

Loops over length of input string like officialaimm's solution

import re,time
def d(s):
 for i in range(len(s)):print(*'\n'*75,*re.split(f'(.{{1,{i+1}}})',s)[1::2],sep='\n');time.sleep(1)

143 bytes to only go to width of longest line a al Frxstrem's Bash answer

import re,time
def d(s):
 for i in range(max(map(len,s.split()))):print(*'\n'*75,*re.split(f'(.{{1,{i+1}}})', s)[1::2],sep='\n');time.sleep(.5)

Uses "re.split((.{1,i+1}))" to break the string into groups of characters.  Because '.' doesn't match '\n', the groups don't wrap around from one line to the next. If the regex uses a capturing group, then re.split() returns a list with the matched groups at the odd indexes.  These are retrieved with [1::2].

Uses python 3.6 f-string to make the re pattern depend on group width i.

The * in front of re.split() uses python 3.6 unpacking to turn the list into arguments to the print statement.  Similarly, *'\n'*75, turns into 75 '\n' arguments to the print statement.  With the print keyword argument sep='\n', the result is printing about 150 blank lines to clear the screen, followed by each group of characters on a separate line.


Create icy avatar images for the winter season It's winter, and the time of year has come for it to start getting cold (and for strange colorful headcloths to start appearing... soon). Let's write some code to make avatar pictures and other images frozen over, to fit the theme!

Input

The input to submissions to this challenge should be an image (the image to make frozen) and a number (the threshold, which will be explained later).

You may input the image in any way your language supports them (a file path or URL as an argument, taking it from the clipboard, dragging and dropping an image, etc.) and in any format listed here that expresses colors in RGB (you can support / require RGBA instead if you want, but this is not a requirement).

You can input the number in any way you would like as well (command line argument, STDIN, input dialog, etc.), with the exception of hardcoding it into your program (ex. n=10). If you use a file path / URL for the image, it must be input in this manner as well.

Output

The program must process the image according to the description below and then output it in any way you would like (to a file, showing it on screen, putting it on the clipboard, etc.).

Description

Submissions should process the image with the following three steps. n refers to the number that your program received as input along with the image.

Apply a blur of radius n to the input image by replacing each pixel's R, G, and B values with the average R, G, and B values of all pixels within a Manhattan distance of n pixels, ignoring all out-of-bounds coordinates. (I.e. all pixels where the sum of the difference in X and the difference in Y is less than or equal to n.)

(note: I used a Gaussian blur for the images above because there was a convenient built-in function for it, so your images might look a little different.)
Set each pixel to a random pixel within a distance of n/2 pixels ("distance" is defined the same way as in the previous step).

This should be done by looping through the image and setting each pixel to a random pixel in this range, so some pixels might disappear entirely and some might be duplicated.

All changes must apply at the same time. In other words, use the old values of the pixels (after step 1 but before this step), not the new values after setting them to a random pixel.
Multiply the "blue" RGB value of each pixel by 1.5, capping it at 255 (or whatever the maximum value for a band of pixels is) and rounding down.

Rules

You may use image libraries / image processing-related functions built into your language; however, you may not use any functions that perform one of the three major tasks mentioned in the description. For example, you can't use a blur function, but a getPixel function is fine.
This is code-golf, so the shortest code in bytes wins!

Python 2 - 326 339 358
Takes input from the user. File first, then n.
from PIL.Image import*;from random import*
a,N=input()
i=open(a)
d=list(i.getdata())
x,y=i.size
R=range(x*y)
m=lambda p,n,r:[p[i]for i in R if abs(n%x-i%x)+abs(n/y-i/y)<=r]
k=d[:]
for p in R:t=map(lambda x:sum(x)/len(x),zip(*m(k,p,N)));d[p]=t[0],t[1],min(255,t[2]*3/2)
i.putdata([choice(m(d,p,N/2))for p in R])
i.save('t.png')

This could probably be golfed much more :P Thanks to @SP3000 for golf ideas!
Sample input:
(Windows)
"C:/Silly/Optimizer/Trix/Are/For/Kids.png",7

Edit: Bug fixed where blue was being propagated (Martin with n=20 is no longer a river ;_; )
Martin with n=2:

Martin with n=10:

Martin with n=20:


All your bijective base are belong to us Background

A bijective base b numeration, where b is a positive integer, is a bijective positional notation that makes use of b symbols with associated values of 1 to b.

Unlike its non-bijective counterpart, no symbol has a value of 0. This way, each non-negative integer n has a unique representation in bijective base b.

Popular bijective numerations include unary, bijective base 2 (used in bzip2's run-length encoding) and bijective base 26 (used to number columns in spreadsheets).

Definition

In this challenge, we define the set M of symbols as

123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<=>

and a function i from M to the natural number such that i('1') = 1, …, i('>') = 64.

Given a base b between 1 and 64 (both inclusive), we define that each non-negative integer n corresponds to the string ak…a0, consisting  of symbols of M, such that n = bki(ak)+…+b0i(a0).

This correspondence is well-defined and bijective. Since an empty sum is defined as 0, the integer 0 can be encoded as an empty string.

Task

Accept three strings as input:

An input base b between 1 and 64, encoded as a bijective base 64 string.
A non-negative integer n, encoded as a bijective base b string.
An output base B between 1 and 64, encoded as a bijective base 64 string.

Given these three inputs, encode n as a bijective base B string.

Test cases

All test cases specify the input in the order b, n, B.

Input:  "4" "" "8"
Output: ""

Input:  "A" "16" "2"
Output: "1112"

Input:  "2" "122" "A"
Output: "A"

Input:  "3" "31" "1"
Output: "1111111111"

Input:  ">" "Fe" "a"
Output: "RS"

Rules

You may read the three strings in any convenient order, as such, an array of strings, a string representation thereof, concatenated or separated by single-character delimiters of your choice.
If you choose to print the output to STDOUT, you may only print the symbols and (optionally) a trailing newline.
Base conversion built-ins of all kinds are allowed.
Standard code-golf rules apply.

CJam, 43

qA,s"?[a{A<":,:^+:Mf#):B;(bLa{(Bmd)M=\j\+}j

3 bytes eradicated with help from Dennis :) Try it online

Explanation:

The input is taken as bnB, concatenated into a single string.

q           read the input
A,s         make an array of numbers from 0 to 9 and convert to string
"?[a{A<"    push this string, which contains the ends of 3 character ranges:
             uppercase letters: ['A'…'[')
             lowercase letters: ['a'…'{')
             "<=>": ['<'…'?')
             they're in a special order for the symmetric difference below
:,          for each character, make a range of all characters smaller than it
:^          fold/reduce these 6 ranges using symmetric difference
+           concatenate with the digits before
:M          save in M; this is like the M from the statement,
             except it starts with a zero (for matching indexes)
f#          find the indexes in M of all characters from the input string
)           take out the last value from the array
:B;         save it in B and pop it
(           take out the first value
b           use it as a base and convert the remaining array to a number
             this works even if some of the digits are not in the "normal" range
La{…}j      calculate with memoized recursion, using an empty string for value 0
  (         decrement the number
  Bmd       divide by B and get the quotient and remainder
  )         increment the remainder (this is the last digit in bijective base B)
  M=        get the corresponding character from M
  \j        swap with the quotient, and convert the quotient recursively
  \+        swap again and concatenate


Pointlessly make your way down the alphabet Disclaimer: This challenge inspired by me spending the morning debugging recursive functions, which have been frying my brain a little.

Here's an example of recursion, from a letter, we keep going to the previous letter of the alphabet, printing out each one as we go, until we hit the letter a, then we print that and stop. We do this for each letter in a string and there's a pretty pattern at the end of it.

The task

Start with a string of characters

The input string may only contain the lower-case letters a-z and the space character.

For each letter, produce a line of text (terminal output or variable or whatever)

Print out the letter
Print out the previous letter (on the same line)
Print out the previous letter (on the same line)
Print out the previous letter (on the same line)
...
If the letter is 'a', print it out and move to the next line.
If it's a space, print out an empty line (or one just containing the space character.

The rules

It's golf, try and make your code short.
Any language you like.
Please include a link to an online interpreter.
The output should be human-readable (e.g. I can't work it out from a list of bytes.
Follow the rules of the standard loopholes ¯\_(ツ)_/¯
Recursion is not mandated by the rules, but it's probably necessary.

Test Cases

Input: 'abcdefghijklmnopqrstuvwxyz'
Output:

a
ba
cba
dcba
edcba
fedcba
gfedcba
hgfedcba
ihgfedcba
jihgfedcba
kjihgfedcba
lkjihgfedcba
mlkjihgfedcba
nmlkjihgfedcba
onmlkjihgfedcba
ponmlkjihgfedcba
qponmlkjihgfedcba
rqponmlkjihgfedcba
srqponmlkjihgfedcba
tsrqponmlkjihgfedcba
utsrqponmlkjihgfedcba
vutsrqponmlkjihgfedcba
wvutsrqponmlkjihgfedcba
xwvutsrqponmlkjihgfedcba
yxwvutsrqponmlkjihgfedcba
zyxwvutsrqponmlkjihgfedcba

Input: 'zyxwvutsrqponmlkjihgfedcba'

zyxwvutsrqponmlkjihgfedcba
yxwvutsrqponmlkjihgfedcba
xwvutsrqponmlkjihgfedcba
wvutsrqponmlkjihgfedcba
vutsrqponmlkjihgfedcba
utsrqponmlkjihgfedcba
tsrqponmlkjihgfedcba
srqponmlkjihgfedcba
rqponmlkjihgfedcba
qponmlkjihgfedcba
ponmlkjihgfedcba
onmlkjihgfedcba
nmlkjihgfedcba
mlkjihgfedcba
lkjihgfedcba
kjihgfedcba
jihgfedcba
ihgfedcba
hgfedcba
gfedcba
fedcba
edcba
dcba
cba
ba
a

Input: 'hello world'
Output:

hgfedcba
edcba
lkjihgfedcba
lkjihgfedcba
onmlkjihgfedcba

wvutsrqponmlkjihgfedcba
onmlkjihgfedcba
rqponmlkjihgfedcba
lkjihgfedcba
dcba

Dyalog APL Extended, 4 bytes

⌽∘⍳¨

Try it online!

 ∘    the function composition of
  ⍳     iota - 'a'..input for alphabet chars, empty array for space
⌽       and after, reverse
   ¨  applied to each


Wireless Keyboard Inteference Initech are setting up an office of 36 employees in a soul-crushingly efficient square of cubicles, 6 desks long and 6 desks deep.  Management has bought wireless keyboards in bulk from a cheap, international wholesaler.  IT are quickly discovering that the wireless keyboards only operate on 3 different radio frequencies, and each individual keyboard is hardwired to a particular frequency.  When two keyboards on the same frequency are too close to each other, they interfere with each other.  The only identifying mark on the keyboards is a unique serial number which gives no clues as to the keyboard's radio frequency.  Thankfully there are an equal number of keyboards operating on each frequency.

A keyboard can be defined by the following class.

sealed class WirelessKeyboard
{
    private int frequency;
    private int serialNum;

    public WirelessKeyboard(int frequency, int serialNum)
    {
        this.frequency = frequency;
        this.serialNum = serialNum;
    }

    public bool InteferesWith(WirelessKeyboard other)
    {
        return this.frequency == other.frequency;
    }

    public int getSerialNum()
    {
        return serialNum;
    }
}

Your function must accept an array of 36 WirelessKeyboard objects.  Each is predefined with a unique serial number and one of the three frequencies (12 keyboards of each frequency).  The array is in random order.  The only way to determine a keyboard's frequency is to test if it interferes with another keyboard.

Your function must:

Not modify or extend the WirelessKeyboard class beyond translating it into your programming language of choice.
Accept an input array of WirelessKeyboard objects.
Not create or alter any WirelessKeyboard objects.  Only those in the input may be used.
Not use any means (eg. reflection) to read a keyboard's frequency.
Output a 6x6 array (or equivalent) populated with WirelessKeyboard objects, which:

Contains all 36 unique keyboards.
InteferesWith(other) must return false for all horizontally and vertically adjacent keyboards.

For the sake of code golf, the WirelessKeyboard class may be aliased as K and code may be written as a function.  For example, in C/Java, ungolfed and golfed:

WirelessKeyboard[,] FindMap(WirelessKeyboard[] collection) { ... }

K[,]F(K[]c){ ... }

The shortest code in a week gets the points.  Please post your implementation of the WirelessKeyboard class if it differs significantly from the sample above, but do not count it towards your score.  The function and any dependant declarations (eg. library imports) count towards your score.

Julia, 97 chars

s(k)=while any([k[j]>k[j-1]||j>6&&k[j]>k[j-6] for j=2:36]);i,j=rand(1:36,2);k[[i,j]]=k[[j,i]];end

Checks if the array is in an acceptable final state state, if not, randomly flips two entries. It's super slow, which I find highly amusing. Does an in place alteration on the input array k. InterferesWith is implemented as >.

As I said, it's really slow.  I tested it with more frequencies and smaller boards with 3 frequencies, but it hasn't returned in over 30 mins on the actual problem. I suspect that it won't return overnight, but I'll update if it does. Update: Yes it did finish in less than 12 hours, and yielded an answer that I added to the gist.

Gist with commented code, and includes 3x3 test case that finishes fast: https://gist.github.com/ggggggggg/8679916


How do I convert a word document to a pdf? Help guys my assignment says it needs to be in .pdf format but I did it in Word. I'm really stuck.

How do I take a word document in .docx format and make a .pdf that contains all the text from it? Bonus points if it also contains all the images and any formatting, but text is a bare minimum. The sample file I'll be using will be this one, though your solution should be generic.

I don't want it to go through any unnecessary processing steps - simply encoding then decoding the document in base64 or whatever is not in the spirit of the question, though creative use of cowsay will be an exception to this. Standard rules of code trolling apply - the solution should be technically correct, all steps should be technically necessary, the result should be technically useless. This should be more of a "Rube Goldberg" style program, than an obfuscation and obtuseness competition.

Most upvotes on answers other than my own by 5/1/14 wins.

Note: This is a code-trolling question. Please do not take the question and/or answers seriously. More information here.

Ok this is a little tricky but not too bad because pdf uses the same graphics model as postscript which means that once you have postscript it is quite trivial to convert it to pdf and postscript is way to drive printers all you have to do is print to get postscript.

Now you could write a program to convert postscript to pdf, but we don't have to there is ghostscript, which was written for unix and works just fine on linux (no major differences for this project). Unfortunately word only runs on windows, so you need two computers, and to convince windows that the linux computer is a printer you need a serial cable and a null modem. If your computer(s) don't have serial ports usb to rs232 converters work just fine (I recommend ones with a fttdi chipset). Now hook up the two computers with the serial cable and the null modem and verify that you can communicate (make sure that your parameters match).

Ok now that you have them talking it is time to convince your windows box that the linux box is a printer: just install the printer driver for the applewriter II and say it is connected to the serial port. Now when you print you send postscript to the linux box. the next step is to save it as a file.

Now scoot over to your linux box and use this simple command:

dd -if=/dev/ttyS0 -of=- -bs=1 | ps2pdf - - | sed -e '' >tmpfile && mv tmpfile file.pdf

and as simple as that you are done.

This can actually be made to work (if you send a signal to dd when you are finished) but there are easier ways like printing to a file and running gostscript on your windows box, and although fttdi makes good quality usb to serial converters it is a royal pain to install the drivers.


Create your own Gym Exercise and follow along irl Let's do an exercise together, shall we? Simply follow the movements of the stickman. What stickman you ask? The one we are about to create!

Make a program that allows for a string-input only containing integers, and outputs the following nine stick-figures with an interval in between:

 @  \@/ |@_ _@| @/   \@ |@| \@\ /@/
/|\  |   |   |   |   |   |   |   |
/ \ / \ / \ / \ /|\ /|\ / \ / \ / \
 1   2   3   4   5   6   7   8   9

This will result in an animation, which we can then follow along irl.

Here is an example of the output created when the input is "123245762":

Some rules:

This is tagged code-golf, so shortest code in bytes wins
The input is a string only containing [1-9] with a length potentially varying from 2 to 100 characters **
The animation must be an endless loop
The interval time must be 750 ms
No duplicated adjacent integers are allowed in the input - this also includes the first and last integers of the input (see the seventh and eight test cases) **

** How it fails in case of invalid input is completely up to you, but it should be clear that it fails. It could throw an exception; simply return at the start; reboot your PC; delete it's own source-/compile-code; hack into the military and shoots a rocket to the compiling GPS-location. Your call. EDIT: It's not allowed to simply display a (correct / half) animation as failing input. It must be clear that something is wrong with the input for the failing testcases below. Thanks to @user81655 for bringing this to my attention, hence the edit.

Subrules:

Please post the gif for one of the (non-failing) test cases below in your answer, which you can make very easy with the following program: screentogif.codeplex.com (Any other gif-creating program is also allowed of course.)
Bonus points if you actually do the exercise alongside the animation irl when it's finished. ;)

Correct testcases:

123245762
65
121234346565879879132418791576

Failing testcases:

2 // Too few characters
7282918274959292747383785189478174826894958127476192947512897571298593912374857471978269591928974518735891891723878 // Too much characters
1232405762 // Containing invalid input (the 0)
112212 // Fails because of the 11 and 22 present
1232457621 // Fails because of the starting and leading 1

SpecBAS - 387 bytes

1 DIM m$=" @"#13"/|\"#13"/ \","\@/"#13" |"#13"/ \","|@_"#13" |"#13"/ \","_@|"#13" |"#13"/ \","@/"#13" |"#13"/|\"," \@"#13" |"#13"/|\","|@|"#13" |"#13"/ \","\@\"#13" |"#13"/ \","/@/"#13" |"#13"/ \"
2 INPUT a$: o=0
3 IF LEN a$<2 OR LEN a$>100 THEN 10
4 FOR i=1 TO LEN a$
5 n=VAL(a$(i))
6 IF n=0 OR n=o THEN 10
7 CLS : ?m$(n): o=n: WAIT 750
8 NEXT i
9 GO TO 4
10 CLS : ?" @"#13"-O-"#13"/ \"#13"FAT"

Keeps looping until you press ESC. Failure to exercise properly (incorrect input - in this example a 0 as one of the steps) leads to fatness. The GIF loops, in the program it just stops at that point.

#13 is the SpecBAS equivalent to \n and lets you include line feed in strings.


Max of the reversed of two numbers Given two real numbers (postive or negative) in the limits of float pointing number data types, i.e., (\$-3.4e38\$ to \$3.4e38\$) not inclusive, you should output the max of the two reversed numbers.

TEST CASES

Example

Input:

135
210

Output:

531

\$531\$ is \$135\$ reversed, which is greater than \$012\$, i.e., \$210\$ reversed.

Negative numbers are allowed:

Example 2

Input:

-135
-210

Output:

-012

\$-012\$ is \$-210\$ reversed, which is greater than \$-531\$, i.e., \$-135\$ reversed.

Real numbers are allowed:

Example 3

Input:

13.5
10

Output:

5.31

\$5.31\$ is \$13.5\$ reversed, which is greater than \$01\$, i.e., \$10\$ reversed.

Example 4

Input:

-1112313.5
-312.5671

Output:

-5.3132111

\$-5.3132111\$ is \$-1112313.5\$ reversed (it reverses the number but is still negative, which is greater than \$-1765.213\$, i.e., \$-312.5671\$ reversed.

Example 5

Input:

0.0000001
0

Output:

1000000.0

\$1000000.0\$ is \$0.0000001\$ reversed, which is greater than \$0\$, i.e., still \$0\$ reversed.

Example 6

Input:

121
121

Output:

121

Both numbers are equal and are palindrome. Either one is correct.

Rules

Standard loopholes apply
This is code-golf, so the shortest program in bytes wins.

Good Luck!

Wren, 126 124 bytes

As always Wren is the longest. I hate Wren's verbosity.

Fn.new{|a|a.map{|i|i>0?"":"-"+(i.abs.toString[-1..-(i.abs.toString.count)])}.map{|i|Num.fromString(i)}.reduce{|x,y|x<y?x:y}}

Try it online!

Explanation

Fn.new{                                                                                // new anonymous function
       |a|                                                                                // with the parameter a
          a.map{|i|                                                                                // for each item in this parameter
                                  (i>0)?"":"-"                                                                       // The sign of each item. If the item is larger than 0, return the null string, otherwise return a negative sign.
                                              +(                                           )                         // Append this with the following string:
                                                i.abs                                                                // The absolute value of i
                                                     .toString                                                       // Convert this value to a string
                                                              [-1..-(i.abs.toString.count)]                          // Reverse this string
                   Num.fromString(                                                          )                        // convert this to a number from a string
                                                                                }.reduce{|x,y|x<y?x:y}} // Find the minimum value of the list


Square Root a Number my Way Now that we know how to Square a Number my Way, we need an inverse operation, a way to Square Root a Number my Way.  To square a number my way, you simply stack it on top of itself a number of times equal to the number of digits it contains, and then take read off every number that is formed both vertically and horizontally, and then add them together.  More information about squaring a number in this manner can be found here.  To square root a number my way, you simply take the number that has the least decimal digits that squares (my way) to make the number you are square rooting.  For example, since 12 can be formed by squaring 6, and there are no numbers with fewer decimal digits that can be squared to form 12, the square root of 12 is 6.

Your Task:

Write a program or function that takes an integer and square roots it as outlined above.

Input:

An integer or string

Output:

A float or string square rooted as outlined above.

Test Cases:

1263 -> 125
57   -> 12

Scoring:

This is code-golf, lowest score in bytes wins!

Python 2, 101 bytes

Ports from my answer to square the numbers my way.

x,z=1,input()
while sum(float(i*len(z))for z in[[i for i in`x`if"/"<i]]for i in[x]+z)!=z:x+=1
print x

Try it online!


Undo a Range of Numbers It is fairly simple to, given a number n, create a range from 0 to n-1. In fact, many languages provide this operation as a builtin.

The following CJam program reads an integer, and then prints out such a range (Try it online!):

ri,

Notice that it prints out numbers without a separator.

The Challenge

Your task is to reverse this process. You should write a program that, given a string representing a range, returns the number used to produce that range.

Specifications

The numbers are given without any separator.
You may assume the string forms a valid range.
You may use 0- or 1-based indexing for your range.
You may assume that a correct output will never exceed 32,767 (so a valid input will never have a length greater than 152,725).
You may assume that a correct output will always be positive (so you do not have to handle 0 or negative).

This is code-golf, so the shortest competing answer (measured in bytes) wins.

Test Cases

0-indexed:

0123 -> 4
0 -> 1
0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 -> 101

1-indexed:

1234 -> 4
1 -> 1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 -> 100

Prolog (SWI), 91 80 bytes

0-indexed.

X*L:-atom_length(X,L),
     between(0,L,Y),
     numlist(0,Y,B),
     atomic_list_concat(B,X)
     ;L=0.

Newlines added for readability.

Try it online!


Implement an API for probability distributions Introduction

In this challenge, your task is to implement a collection of simple functions that together form a usable mini-library for simple probability distributions.
To accommodate some of the more esoteric languages people like to use here, the following implementations are acceptable:

A code snippet defining a collection of named functions (or closest equivalents).
A collection of expressions that evaluate to named or anonymous functions (or closest equivalents).
A single expression that evaluates to several named or anonymous functions (or closest equivalents).
A collection of independent programs that take inputs from command line, STDIN or closest equivalent, and output to STDOUT or closest equivalent.

The functions

You shall implement the following functions, using shorter names if desired.

uniform takes as input two floating point numbers a and b, and returns the uniform distribution on [a,b]. You can assume that a < b; the case a ≥ b is undefined.
blend takes as inputs three probability distributions P, Q and R. It returns a probability distribution S, which draws values x, y and z from P, Q and R, respectively, and yields y if x ≥ 0, and z if x < 0.
over takes as input a floating point number f and a probability distribution P, and returns the probability that x ≥ f holds for a random number x drawn from P.

For reference, over can be defined as follows (in pseudocode):

over(f, uniform(a, b)):
    if f <= a: return 1.0
    else if f >= b: return 0.0
    else: return (b - f)/(b - a)

over(f, blend(P, Q, R)):
    p = over(0.0, P)
    return p*over(f, Q) + (1-p)*over(f, R)

You can assume that all probability distributions given to over are constructed using uniform and blend, and that the only thing a user is going to do with a probability distribution is to feed it to blend or over.
You can use any convenient datatype to represent the distributions: lists of numbers, strings, custom objects, etc.
The only important thing is that the API works correctly.
Also, your implementation must be deterministic, in the sense of always returning the same output for the same inputs.

Test cases

Your output values should be correct to at least two digits after the decimal point on these test cases.

over(4.356, uniform(-4.873, 2.441)) -> 0.0
over(2.226, uniform(-1.922, 2.664)) -> 0.09550806803314438
over(-4.353, uniform(-7.929, -0.823)) -> 0.49676329862088375
over(-2.491, uniform(-0.340, 6.453)) -> 1.0
over(0.738, blend(uniform(-5.233, 3.384), uniform(2.767, 8.329), uniform(-2.769, 6.497))) -> 0.7701533851999125
over(-3.577, blend(uniform(-3.159, 0.070), blend(blend(uniform(-4.996, 4.851), uniform(-7.516, 1.455), uniform(-0.931, 7.292)), blend(uniform(-5.437, -0.738), uniform(-8.272, -2.316), uniform(-3.225, 1.201)), uniform(3.097, 6.792)), uniform(-8.215, 0.817))) -> 0.4976245638164541
over(3.243, blend(blend(uniform(-4.909, 2.003), uniform(-4.158, 4.622), blend(uniform(0.572, 5.874), uniform(-0.573, 4.716), blend(uniform(-5.279, 3.702), uniform(-6.564, 1.373), uniform(-6.585, 2.802)))), uniform(-3.148, 2.015), blend(uniform(-6.235, -5.629), uniform(-4.647, -1.056), uniform(-0.384, 2.050)))) -> 0.0
over(-3.020, blend(blend(uniform(-0.080, 6.148), blend(uniform(1.691, 6.439), uniform(-7.086, 2.158), uniform(3.423, 6.773)), uniform(-1.780, 2.381)), blend(uniform(-1.754, 1.943), uniform(-0.046, 6.327), blend(uniform(-6.667, 2.543), uniform(0.656, 7.903), blend(uniform(-8.673, 3.639), uniform(-7.606, 1.435), uniform(-5.138, -2.409)))), uniform(-8.008, -0.317))) -> 0.4487803553043079

Ruby, 103

u=b=->*a{a}
o=->f,d{d[2]?(p=o[0,d[0]])*o[f,d[1]]+(1-p)*o[f,d[2]]:(f<a=d[0])?1:(f>b=d[1])?0:(b-f)/(b-a)}

Defines three lambdas, u, b, and o. u and b just create two-element and three-element arrays respectively. o assumes a two-element array is a uniform distribution and a three-element one is a blend of three distributions. In the latter case it calls itself recursively.


Letters, Get Moving! Pt. 2 The first Letters, Get Moving! was very popular, but had limited participation. This one will be easier to solve, but hopefully involve some tricks in golfing.

You are given a string of only lowercase letters. For each letter, with position in the alphabet m, move it so it becomes the mth letter from the end. If the value of m is longer than the length of the string, move it to the very front. Output only the fully transformed string.

Examples:

"giraffe"

'g' is the 7th letter in the alphabet, it is already the 7th letter from the back, so leave it.
'i' is the 9th letter, since 9 is bigger than the length of the word, it goes to the front, so the string becomes igraffe
'r' is the 18th letter, like 'i' it goes to the front: rigaffe
'a' is the 1st letter, it goes to the very end: rigffea
'f' is the 6th letter, it becomes the 6th from the back: rfigfea
the next 'f' is also the 6th letter, so it also goes to 6th from the back : rffigea
'e' is the 5th letters, it goes to 5th from the back: rfefiga

"flower"

'f' (6) => flower
'l' (12) => lfower
'o' (15) => olfwer
'w' (23) => wolfer
'e' (5) => weolfr
'r' (18) => rweolf

"pineapple"

'p' (16) => pineapple
'i' (9) => ipneapple
'n' (14) => nipeapple
'e' (5) => nipaepple
'a' (1) => nipepplea
'p' (16) => pnipeplea
'p' (16) => ppnipelea
'l' (12) => lppnipeea
'e' (5) => lppneipea (make sure you move the e that hasn't been moved already! Here it doesn't matter, but below it does.)

Thanks to @Neil for improving the test cases with these 3 additions:

"pizza"

'p' (16) => pizza
'i' (9) => ipzza
'z' (26) => zipza
'z' (26) => zzipa (moving the second z!)
'a' (1) => zzipa

"abracadabra"

'a' (1) => bracadabraa
'b' (2) => racadabraba
'r' (18) => racadabraba
'a' (1) => rcadabrabaa
'c' (3) => radabrabcaa
'a' (1) => rdabrabcaaa
'd' (4) => rabrabcdaaa
'a' (1) => rbrabcdaaaa
'b' (2) => rrabcdaaaba
'r' (18) => rrabcdaaaba
'a' (1) => rrbcdaaabaa

"characters"

'c' (3) => haractecrs
'h' (8) => arhactecrs
'a' (1) => rhactecrsa
'r' (18) => rhactecrsa
'a' (1) => rhctecrsaa
'c' (3) => rhtecrscaa
't' (20) => trhecrscaa
'e' (5) => trhcrescaa
'r' (18) => rtrhcescaa
's' (19) => srtrhcecaa

CJam, 41 38 bytes

lee_S+W%\{Xa-X1='`-/(Xa+\L*+}fX1>W%1f=

Test it here.


Count the Collatz survivors mod 2^n Introduction
We have 22 Collatz conjecture-related challenges as of October 2020, but none of which cares about the restrictions on counter-examples, if any exists, to the conjecture.
Considering a variant of the operation defined in the conjecture:
$$f(x)=
\cases{
\frac{x}{2}&for even x \cr
\frac{3x+1}{2}&for odd x
}$$
The Wikipedia article suggests that a modular restriction can be easily calculated and used to speed up the search for the first counter-example. For a pair of \$k\$ and \$b\$ where \$0\le b\lt2^k\$, if it is possible to prove that \$f^k(2^ka+b)<2^ka+b\$ for all sufficiently large non-negative integers \$a\$, the pair can be discarded. This is because if the inequality holds for the counter-example, we can find a smaller counter-example from that, contradicting the assumption that the counter-example is the first one.
For example, \$b=0, k=1\$ is discarded because \$f(2a)=a<2a\$, while \$b=3, k=2\$ is not because \$f^2(4a+3)=9a+8>4a+3\$. Indeed, for \$k=1\$ we only have \$b=1\$ and for \$k=2\$, \$b=3\$, to remain (survive) after the sieving process. When \$k=5\$, though, we have 4 survivors, namely 7, 15, 27 and 31.
However, there are still 12,771,274 residues mod \$2^{30}\$ surviving, so just still about a 100x boost even at this level
Challenge
Write a program or function, given a natural number \$k\$ as input, count the number of moduli mod \$2^k\$ that survives the sieving process with the operation applied \$k\$ times. The algorithm used must in theory generalize for arbitrary size of input.
The sequence is indeed A076227.
Examples
Input > Output
1     > 1
2     > 1
3     > 2
4     > 3
5     > 4
6     > 8
7     > 13
8     > 19
9     > 38
10    > 64
15    > 1295
20    > 27328
30    > 12771274

Winning criteria
This is a code-golf challenge, so the shortest submission of each language wins. Standard loopholes are forbidden.

APL (Dyalog Unicode), 18 bytes

+/∧/¨1<×\¨.5+,⍳⎕/2

Try it online!
A full program. Fails to compute the answer for \$k>15\$ due to system limitations (rank of intermediate array).
How it works
If we call the \$\frac{x}{2}\$ the \$D\$-step and \$\frac{3x+1}{2}\$ as the \$U\$-step, it is known that each residue class \$0 \dots 2^k-1\$ modulo \$2^k\$ corresponds to exactly one \$UD\$-sequence of length \$k\$.
In the original formula, the coefficient of \$a\$ is multiplied by \$\frac32\$ for the \$U\$-step, and \$\frac12\$ for the \$D\$-step, and it suffices to count the \$UD\$-sequences where the coefficient never drops under 1.
The program computes this by generating all length-\$k\$ sequences of 0.5 and 1.5 (skipping the \$UD\$ part), and counts the ones where the multiplicative scan ×\ gives all numbers greater than 1.
+/∧/¨1<×\¨.5+,⍳⎕/2  ⍝ Full program; input: k
               ⎕/2  ⍝ k copies of 2
             ,⍳     ⍝ indices in an array of shape 2 2 ... 2
                    ⍝ which generates all binary sequences of length k
          .5+  ⍝ Add 0.5 to get all sequences of 0.5 and 1.5
       ×\¨     ⍝ Product scan
     1<        ⍝ Test if each number is greater than 1
  ∧/¨          ⍝ ... for all numbers in each sequence
+/             ⍝ Count ones


Fourth grade math homework for the week: A most inefficient traveling salesman My daughter had the following assignment for her math homework. Imagine six friends living on a line, named E, F, G, H, J and K. Their positions on the line are as indicated (not to scale) below:

Thus, F lives five units from E, and two units from G, and so forth.

Your assignment: craft a program that identifies a path that visits each friend exactly once with a total length of n units, taking the locations of the friends and n as inputs. It should report the path if it finds it (for example, for length 17 it might report "E,F,G,H,J,K", and it should exit gracefully if no solution exists. For what it's worth, I completed an ungolfed solution in Mathematica in 271 bytes. I suspect it's possible much more concisely than that.

Mathematica, 55 or 90 bytes

Mathematica you said? ;)

FirstCase[Permutations@#,p_/;Tr@Abs@Differences@p==#2]&

This is an anonymous function that first takes the positions of the friends (in any order), and then the target length. It returns Missing[NotFound], if no such path exists.

FirstCase[Permutations@#,p_/;Tr@Abs@Differences@p==#2]&[{0, 5, 7, 13, 16, 17}, 62]
(* {7, 16, 0, 17, 5, 13} *)

I can save four bytes if returning all valid paths is allowed (FirstCase -> Cases).

Returning an array of strings is a bit more cumbersome:

FromCharacterCode[68+#]&/@Ordering@FirstCase[Permutations@#,p_/;Tr@Abs@Differences@p==#2]&


A simple logic gate calculator Your mission, if you choose to accept it, is to construct a simple truth evaluator for the following logical operators:

----------------------------------------------------------------------------------
  Logical Name          |  Gate Name   |  Symbol  |  Symbol Name  |  Truth Table
----------------------------------------------------------------------------------
  Identity              |  is          |          |  (none)       |  10
  Negation              |  not         |    ~     |  tilde        |  01
  Conjunction           |  and         |    &     |  ampersand    |  1000
  Disjunction           |  or          |    |     |  pipe         |  1110
  Negative Conjunction  |  nand        |    ^     |  caret        |  0111
  Joint Denial          |  nor         |    v     |  "vee"        |  0001
  Exclusive Disjunction |  xor         |    x     |  "ecks"       |  0110
  Equivalence           |  equals/xnor |    =     |  equals       |  1001
  Implication           |  implies     |    >     |  greater than |  1011

Truth tables are in the following order:

1 1
1 0
0 1
0 0

Input will come as a simple string of 0, 1, and the symbol.  You can either accept input as a parameter or read it from the user on stdin.  Here are some sample input/output pairs:

Input: 1
Output: 1

Input: ~1
Output: 0

Input: 0|1
Output: 1

Input: 1>0
Output: 0

The unary operator (negation) will always appear before the boolean value, while the binary operators will always appear between the two boolean values.  You can assume that all input will be valid.   Strings are regular ASCII strings.

If you prefer, you can use T and F rather than 1 and 0.  -6 to your character count if you support both.

This is code-golf: shortest code in any language wins!

C - 165 127

That was fun!  Plain lookup table relying on a fixed offset for the lookup.

main(){
  char*s="100011001110110v& x = |^> /~",
       t[6]="0/xxx",
      *u= strchr((gets(t+2),t),0)-3;
  putchar(strchr(s,u[1])[*u*2+u[2]-159]);
}

For some reason gets doesn't get implicitly declared, so when I removed the include I had to change gets(t+2) to (gets(t+2),t) (or similarly elsewhere, costing as much).

Explanation

First of all, since the truth tables for the operators have plenty of overlapping characters we wish to store the lookup tables in a way so that we allow overlap.  Here's how I chose to store them:

v    &    x    =    |    ^    >       ~     (operation)
1000 0001 0110 1001 0111 1110 1101 01 10    (truth table [order 00,01,10,11])
0    1    3    5    7    8    9    B  D     (offset in LUT below)

0123456789ABCDE   (offsets)
100011001110110   (values)

Next, we want to map operator symbols to these offsets.  We do this by storing the operator symbols in the same string at a fixed offset from the LUT data (namely, 16 characters later, i.e. directly after the LUT data).  The lookup process is "find operator in s, subtract 16, add left*2+right (left/right operand). For the lookup of the empty "identity operation", due to how the input is fetched the operator in this case will resolve to whatever t[1] is initialised to--in our case /. Thus, we use / as the lookup table key to represent the identity operation. When we process the unary ~ operation "left" (for the lookup calculation mentioned earlier) is always this same /
.  / happens to be one less than 0 ASCII-wise, meaning when we compensate for ASCII digits \ will represent -1. The slash in the lookup table key area (second-to-last character in s, that is) is positioned to compensate for this.

Next up, input handling.  The input has dynamic length, but it'd be easier if we have specific static names for the left operand, operator and right operand, regardless of input.  If we pretend that we could read the input right-to-left, this would basically happen automagically--the right operand is always the rightmost character, the operator (if present) is second-to-rightmost, the left operand (if present) is third-to-rightmost.  In order to be able to index the string like this, we use strchr in order to locate the \0 terminator (- 3 to simplify indexing).  This shows why t[0] and t[1] become the left operand/operator respectively when the input is 1 or 2 characters.

Putting it together, the output would be putchar(strchr(s,u[1])[(u[0] - '0')*2 + (u[2] - '0') - 15]), but some refactoring and constant folding instead gets us the shorter putchar(strchr(s,u[1])[u[0]*2+u[2]-159]).


How can I golf this code to count all perfect squares below 100? I'm trying to strip down my python code to be as few lines as possible. The task: count how many square numbers are below 100. Here's my code so far:

m = 0
for x in range(0, 100):
    m+=1-(-((-((x+1)**(0.5)-((x+1)**(0.5))//1))//1));
print(m)

That addition statement adds 1 to m (the counter) only when (x+1) is a perfect square. Is it possible to shorten anything? Maybe find a way to print without using a counter -- such as printing a summation in a form such as:

print(sum(min,max,variable,statement))

For the exact question posed: since we know that 1 is a perfect square and all integers between that and the maximal one (here 9) will be included we can simply find that maximal one:

print((100-1)**.5//1)

(//1 performing integer division by one to remove any fractional part may be replaced with /1 prior to Python 3.)

with both endpoints (an inclusive start and exclusive stop equivalent to a range) this could be extended to a function (negative inputs catered for with max):

f=lambda start, stop:print(max(0,stop-1)**.5//1-max(0,start)**.5//1)


Create sets with a Goldbach-like property Goldbach's conjecture states that every even number > 4 is the sum of two prime numbers.  Although this conjecture is not yet proven, similar results have been proven for other series of numbers.  For example, every even number can be written as the sum of two practical numbers.

The Challenge

Given a number N, return a set of positive integers such that every even number in the interval [4,N] can be written as the sum of two numbers in the set.  Furthermore, the set generated must contain as few elements as possible, otherwise this challenge would be trivial.

Shortest answer wins.

Detailed Example

For N=24, one possible output is {2,4,8,10,12}.  This is because it contains the fewest number of elements possible (5).  Also, every even number {4,6,8,... 24} can be written as the sum of exactly two of the members of the set.

4=2+2
6=2+4
...
12=8+4
14=10+4
...
24=12+12

Examples

Here are some examples.  There may be many valid outputs for each input, but only a few are listed.

4:{2}
6:{2,4} or {1,3}
9:{2,4}  #pay attention to how the odd number is handled
10:{2,4,6} or {2,3,5}
12:{2,4,6}
24:{2,4,8,10,12}
26:{1,3,7,11,13}

GolfScript (53 chars)

~2/),3>[2][1 3]]({2*:x;{:S{x<},{x\-S+.&}/}%}/{,}$0=n*

A major speed optimisation results from a bit of duplicate-trimming, at a cost of 3 chars:

~2/),3>[2][1 3]]({2*:x;{:S{x<},{x\-S+.&$}/}%.&}/{,}$0=n*

NB Let f(2n) be the size of the optimal set for [4..2n]. Then f(2n) <= f(2n+2) <= f(2n) + 1. The first inequality is obvious from the definition; the second is easily seen by taking any optimal set S_{2n} for [4..2n] and taking the union with {n+1}, or indeed with {2n+2-x} for any x in S_{2n}.

This suggests a greedy algorithm, which the first revision of this answer implements. However, that greedy algorithm turns out to be incorrect. The unique optimal set for [4..20] is {2,4,8,10}, which is not a subset of either of the two optimal sets for [4..26]: {1,3,7,11,13} and {2,4,8,12,14}.

My current solution assumes that every optimal set will contain only odd numbers or only even numbers. I haven't proven this, but given that odd + even = odd a set which mixes parities is wasting possible pairs.


Create an array with repeated numbers Challenge
Your task in this question is to write a program or a named function which takes a positive integer n (greater than 0) as input via STDIN, ARGV or function arguments and outputs an array via STDOUT or function returned value.
Sounds simple enough ? Now here are the rules

The array will only contain integers from 1 to n
Each integer from 1 to n should be repeated x times where x is the value of each integer.

For example:
Input:
5

Output:
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]

The array may or may not be sorted.
This is code-golf so winner is shortest code in bytes.
Bonus
Multiply your score by 0.5 if no two adjacent integers in your output array are same.
For example for n = 5, one such configuration would be
[5, 4, 5, 4, 3, 4, 5, 2, 5, 3, 1, 2, 3, 4, 5]

Ruby (recursive), 41 bytes * 0.5 = 20.5
def n(n,i=1);i>n ?[]:n(n,i+1)+[*i..n];end

Or using a lambda (as recommended by histocrat and Ventero): 34 bytes * 0.5 = 17
r=->n,i=n{i>0?[*i..n]+r[n,i-1]:[]}

(call using r[argument])


How to shorten this J code? (Or write shorter code in another language) I decided to learn J so that I could better take part in code golfing. Starting it off relatively simple, I tried writing a solution to this problem:

  Find the sum of all the multiples of 3 or 5 below 1000.

After a bit of tinkering, I came up with the following J code that solves it:

x=:i.1000
+/x#(0=3|x)+.0=5|x

Basically, what I'm doing is taking two lists of numbers from 1 to 1000, and finding one modulo 3, and the other modulo 5. Then I OR them together to get a list of indicies where a number is divisible by either 3 or 5. I then use that to sum the numbers.

What I ask is, how do I shorten this? I'm new to J and so do not have enough experience to shorten it any further.

Also, if anyone has a solution shorter than this in another language, I'd be interested to see that as well!

Employing a few forks, a hook and the fact that J works well on lists:

+/(#~[:+./0=3 5|/])i.1000

This answer uses your algorithm, but just uses some J tricks to make it a bit shorter. I'm fairly sure that this can be made shorter still, and I wouldn't be surprised if there's a slightly different way of doing it that results in an even shorter solution.

Here's a list of some things I've done here.

First, I've combined the 3|x and the 5|x into one operation 3 5|/x. This uses the table adverb / to do both operations at once:

   3 5|/i.20
0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1
0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4

Next, I've combined the |/, the 0=, the +., and the # into a train of verbs using forks and a hook. The verb train breaks down into groups of three:

3 5|/]

this is the same as the above, except I'm using ] to grab the list to the right of the brackets.

0=x

x is the result of the previous fork which is fed into the next.

[:+./x

as before the result so far gets fed into this fork. [: tells the verb +./ that it should use its monadic (one argument) form. The / inserts the +. between the top and bottom rows of the result so far.

#~x

This is the hook. The result so far is fed in as the right argument, but the left argument is the value outside the brackets (i.1000) again. So this is equivalent to (i.1000)#~x. The ~ just reverses the order of the arguments.

Then at the end I just use the +/ as you did.


Walkers Join! - Alan Walker's logo You might know Alan Walker from his ever popular song Faded. Now his "followers" are called Walkers and they have a logo, here is a simplified version:

\\
 \\              //\\
  \\            //  \\            //
   \\          //    \\          //
    \\        //      \\        //
     \\      //        \\      //
      \\    //          \\    //
       \\  //    //\\    \\  //
        \\//    //  \\    \\//
         //    //    \\    \\
        //\\  //      \\  //\\
           \\//        \\//  \\
                              \\

The goal of this challenge is to print this logo.

RULES:

If you return a list of strings from a function as per meta standards, please provide a footer that prints it to the screen.
All characters of the above logo have to be there. No shortcuts!
Shortest number of bytes wins!

Charcoal, 31 30 29 27 bytes

Ｆ²«Ｊι⁰↙χ↖↖⁵↙↙⁵↖↖²Ｐ↖χ↙↗χ↘↘¹²

Try it online! Link is to verbose version of code. Sadly Copy doesn't do what I want in this case, so I have to loop instead. Explanation:

Ｆ²«Ｊι⁰

Draw everything twice, but with the cursor starting one character to the right the second time.

   ↙χ↖↖⁵↙↙⁵↖↖²Ｐ↖χ

Draw the main W from right to left, but leave the cursor near the inverted V.

   ↙↗χ↘↘¹²

Draw the inverted V.


Generate Lucky Numbers Story:

Lucy asked George what his Lucky Number was. After some contemplation, George replied that he had several Lucky Numbers. After some brief confusion, Lucy asked George what his first n Lucky Numbers are. George then asked you, his buddy, to write him a program to do the work for him.

The Challenge:

You will write a program/function that will receive from standard input/function argument a string or integer n. The program/function will then return/output the first n Lucky Numbers. Lucky numbers are defined via a sieve as follows.

Start with the positive integers:

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, ...

Now remove every second number:

1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, ...

The second remaining number is 3, so remove every third number:

1, 3, 7, 9, 13, 15, 19, 21, 25, ...

Now the next remaining number is 7, so remove every seventh number:

1, 3, 7, 9, 13, 15, 21, 25, ...

Next, remove every ninth number and so on. The resulting sequence are the lucky numbers.

Winning:

As usual for codegolf, fewest bytes wins.

As usual, submissions using standard loopholes are disqualified.

Python 2, 79

n=input()
L=range(1,2**n)
for r in L:r+=r<2;map(L.remove,L[r-1::r])
print L[:n]

The magic of iterating over a list as the loop modifies it!

The list L starts with all the integers 1 to a sufficiently high value. The code iterates over each element r of L, taking the sublist of every r'th element, and removing each of those values. As a result, the removed values aren't iterated over. At the end, print the first n elements.

The expression map(A.remove,B) is a trick I've been waiting a long time to use. It calls A.remove for each element of B, which causes all the elements of B to removed from A. Effectively, it takes the list difference, though it requires B to be a sublist of A. It requires Python 2, since Python 3 wouldn't actually evaluate the map.

The first loop needs to be special-cased to convert r from 1 to 2, as r+=r<2.

The sufficiently high upper bound of 2**n makes the program very slow for large values of n. Using n*n+1 suffices, but costs a character. Note that n*n doesn't work for n=1.


I'm in your subnets, golfing your code Challenge

Given an IPv4 address in dotted-quad notation, and an IPv4 subnet in CIDR notation, determine if the address is in the subnet. Output a distinct and consistent value if it is in the subnet, and a separate distinct and consistent value if it is not in the subnet. The output values do not necessarily need to be truthy/falsey in your language.

CIDR subnet notation brief primer

IPv4 network addresses are 32 bits in length, split into four groups of 8 bits for ease of reading. CIDR subnet notation is a mask of the specified number of bits, starting leftmost. For example, for a /24 subnet, this means the right-most 8 bits of the address are available in that subnet. Thus two addresses that are separated by at most 255, and have the same subnet mask, are in the same subnet. Note that valid CIDR have all the host-bits (the right hand side) unset (zeros).

xxxxxxxx xxxxxxxx xxxxxxxx 00000000
^---    subnet mask   ---^ ^-hosts-^

For another example, a /32 subnet specifies that all of the bits are the subnet mask, essentially meaning that only one host is allowed per /32.

xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
^---        subnet mask        ---^

Examples:

Using True for "in the subnet" and False for "not in the subnet" as output:

127.0.0.1
127.0.0.0/24
True

127.0.0.55
127.0.0.0/23
True

127.0.1.55
127.0.0.0/23
True

10.4.1.33
10.4.0.0/16
True

255.255.255.255
0.0.0.0/0
True

127.1.2.3
127.0.0.0/24
False

127.1.2.3
127.1.2.1/32
False

10.10.83.255
10.10.84.0/22
False

Rules and Clarifications

Since input parsing isn't the interesting point of this challenge, you're guaranteed to get valid IPv4 addresses and subnet masks.
Input and output can be given by any convenient method.
You can print the result to STDOUT or return it as a function result. Please state in your submission what values the output can take.
Either a full program or a function are acceptable.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Python 3 (62 bytes)

Very straightforward:

from ipaddress import*
lambda i,m:ip_address(i)in ip_network(m)


Tell me, how many squares are there? Given a non-empty 2D array consisting of 0 and 1, find the number of squares whose 4 corners are all 1. The squares do not need to be "upright". All the rows are guaranteed to have the same length.

Reasonable input/output methods are allowed.

Testcases:

0001000
1000000
0000000
0000100
0100000

This returns 1.

10101
00000
10100
00000
10001

This returns 2.

1111
1111
1111
1111

This returns 20.

This is code-golf. Shortest answer in bytes wins. Standard loopholes apply.

JavaScript (ES6), 127 124 119 bytes

Saved 3 bytes thanks to nderscore

m=>(F=(x,y)=>m.map((r,Y)=>r.map((i,X)=>i?1/y?n+=x<X&y<=Y&(g=(a,b)=>(m[b+X-x]||0)[a-Y+y])(x,y)&g(X,Y):F(X,Y):0)))(n=0)|n

How?

This function iterates on all pairs of cells (x, y), (X, Y) of the input matrix m such that:

m[ x, y ] = m[ X, Y ] = 1
x < X
y ≤ Y

Each matching pair describes the coordinates of a potential edge of a square. The inequations guarantee that each edge is tested only once.

We use the vector [ dx, dy ] = [ X - x, Y - y ] rotated 90° clockwise to test the cells located at [ x - dy, y + dx ] and [ X - dy, Y + dx ]. If they both contain a 1, we've found a valid square.

Test cases

let f =

m=>(F=(x,y)=>m.map((r,Y)=>r.map((i,X)=>i?1/y?n+=x<X&y<=Y&(g=(a,b)=>(m[b+X-x]||0)[a-Y+y])(x,y)&g(X,Y):F(X,Y):0)))(n=0)|n

console.log(f([
  [0,0,0,1,0,0,0],
  [1,0,0,0,0,0,0],
  [0,0,0,0,0,0,0],
  [0,0,0,0,1,0,0],
  [0,1,0,0,0,0,0]
]));

console.log(f([
  [1,0,1,0,1],
  [0,0,0,0,0],
  [1,0,1,0,0],
  [0,0,0,0,0],
  [1,0,0,0,1]
]));

console.log(f([
  [1,1,1,1],
  [1,1,1,1],
  [1,1,1,1],
  [1,1,1,1]
]));


Golf me an HQ9+ Compiler Your task is "simple" should you choose to accept it.

Write an HQ9+ compiler in a language of your choice.

HQ9+ has four commands (as you may be able to tell) H prints "Hello, World!" Q prints out the source code (this can either be the compiled source or HQ9+ source for the purpose of this challenge),9 prints out the lyrics to 99 bottles of beer on the wall, and + is essentially a noop.

Your submission should be written in some language X, and should take input of HQ9+ source and output a program in X.

Wait, I know what you're thinking. This is not a duplicate of Creating a HQ9+ interpreter as it should not run HQ9+ code, but rather compile it. It should output a fully functional program.

Rules

Language X should satisfy the traditional definition of a language
Standard loopholes disallowed
This is code golf (shortest program in bytes wins)
Your solution must be testable
X cannot be HQ9+ or an extension of HQ9+

Clarifications

There has been some confusion as to what the q command should do. I had originally thought that it would output the compiled code (i.e code in langauge X), but my reference implementation outputs the hq9+ code. I would like to see either one depending on your golfing preferences.

Actually, 17 bytes
"HQ9"∩εj'N'9(t'.j

Try it online!
This program compiles HQ9+ to Actually.
Actually is (almost) a superset of HQ9+ - the only difference is that the 9 command in HQ9+ is N in Actually. Because + is a NOP in HQ9+ (the accumulator is never actually used or displayed, and thus many implementations treat it as a NOP), it is stripped out.
Explanation:
"HQ9"∩εj'N'9(t'.j
"HQ9"∩εj           strip all characters not in "HQ9", preserving order
        'N'9(t     replace all occurrences of "9" with "N"
              '.j  insert a "." between every pair of characters

-1 byte from Christian Irwin


Check if a string is the anagram of another Skat

I'm a fan of anagrams, so given two strings s1 and s2 write a program or function that outputs a truthy value if s2 is an anagram of s1, and a falsey value otherwise (not accounting for spaces and capital letters).

For example:

Input: s1 = "Anagram"; s2 = "Nag a ram"

true

Input: s1 = "stack overflow"; s2 = "fewer kool cats"

false

Input: s1 = "apple rocks"; s2 = "paler spock"

true

Rules

Program and function allowed.
Shortest code in bytes wins.

Duck logo!

05AB1E, 8 bytes

lðδKJ€{Ë

Try it online!


What valence does this APL train have? Context
In APL, trains are tacit sequences of monadic/dyadic functions that can be called with one or two arguments. We'll code something to check if a given train follows the correct structure we need in order to have a sound train.
Task
Given the sequence of function arities in the train, determine if the train is valid as a monad and/or as a dyad. Don't forget that APL reads from right to left, so when I mention the "start" I mean the end of the array! A train is valid as a monad if

is starts with an arbitrary number of DM (0 or more) and then ends in 1 or 2 monadic functions; e.g. MM, MDM, MMDM and MDMDM are valid monadic trains.

A dyadic train is valid if

the train starts with an odd number of dyadic functions, possibly ending with a monadic function; e.g. D, MDDD and DDDDD are valid dyadic trains.

Input
Your input is going to be a non-empty list of the arities of the functions in the train, where said list contains up to 3 different elements; one for purely monadic functions, another for purely dyadic functions and another for functions that can be either monadic or dyadic, depending on usage.
The input list can be taken in any sensible format and likewise the elements can be whatever 3 distinct elements you choose. E.g. take a string with the letters MDB or take a list of integers 0,1,2. I don't mind you play around with this, just let us know what your answer uses.
APL reads from right to left and we will embody this in the challenge; input cannot be reversed.
Output
Your function should adhere to one of the two output formats:

output one of 4 distinct values; one for a train that only works monadically, one for a train that works dyadically, one for a train that works both ways and yet another one for a train that doesn't work in any way; any consistent 4 distinct values will do;

output two Truthy/Falsy values, with respect to the standard Truthy/Falsy defaults of your language, where the first value flags if the train works monadically and the second to flag if the train works dyadically, or vice-versa.

Test cases:
The pair (a, b) is used, where a says if the train is valid to be used monadically and b says if the train is valid dyadically.
DB
(False, False)
DD
(False, False)
DM
(False, False)
MBDBMDD
(False, False)
DDBB
(False, False)
DMMDDM
(False, False)
DBDDBDMMD
(False, False)
BMDBDD
(False, False)
MMMDD
(False, False)
MMBMBMMBM
(False, False)
DDBBMDDMMD
(False, False)
DDMB
(False, False)
D
(False, True)
MD
(False, True)
BD
(False, True)
BBBDBDDBD
(False, True)
MDBBBBDB
(False, True)
M
(True, False)
MM
(True, False)
BM
(True, False)
MMDM
(True, False)
MDM
(True, False)
BDM
(True, False)
MMBBDMDB
(True, False)
MBM
(True, False)
B
(True, True)
MB
(True, True)
BB
(True, True)
BBB
(True, True)
BBBB
(True, True)
BBBBB
(True, True)
MBBBBBBB
(True, True)
BDBBBBBDB
(True, True)

Generated and tested with this Python code. Feel free to use the TIO link and edit the final printing loop to print all the test cases in a format that is easier for you to use in your answer.

Haskell, 61 bytes

f t=[and$zipWith(/=)t$[2|even$length t]++cycle[x,0]|x<-[2,0]]

Try it online!
Takes a list of: 0 for monad, 1 for both, 2 for dyad. Returns [a,b].
The valid monad trains are:
M
MM
MDM
MMDM
MDMDM
MMDMDM
...

And the valid dyad trains are:
D
MD
DDD
MDDD
DDDDD
MDDDDD
...

So we check the input against this pattern, first for x=M and then x=D:
x
Mx
xDx
MxDx
xDxDx
MxDxDx
...

To generate the pattern, we start with M if the length is even, then alternate x and D. (Haskell's laziness lets me use cycle, which creates an infinite alternating list, rather than specify how long to alternate for: zipWith will only consume the pattern until it hits the end of t.)
I use (/=) and invert the pattern to support B as a wildcard.


Counting triangles with integer perimeter Mary has given John two sticks of lengths a and b respectively, where a and b are positive integers.
John is very curious.
He would like to know how many triangles with integer perimeter can be formed, by having one additional side.
Please help him find it out.
(This is my first time composing this kind of stupid stories in coding problems, so forgive me if it is too stupid.)
Specs

Given two integers a and b, find the number of triangles with integer perimeter that can be formed, by having one additional side.

Details

Congruent triangles are congruent.
Flat triangles are flat out uncounted.
Zero-sided triangles are counted zero times.

Scoring
This is code-golf. Shortest solution in bytes wins.
Testcases
a b output
1 2 1
3 3 5
9 7 13

Jelly, 3 bytes

«Ḥ’

Try it online!

Explanation

«   min(a,b)
 Ḥ          *2
  ’           -1

(Not quite rigorous) proof of correctness:

Let x = min(a,b) and y = max(a,b), and let z be a potential third side.
We can't have z ≤ y-x, because for z < y-x the triangle can't be closed and for z = y-x it would be degenerate. See triangle inequality.
We can't have z ≥ y+x, for the same reasons.
Every integer z in between is valid and gives a different triangle. That means we've got (y+x) - (y-x) - 1 = 2x - 1 different triangles.