答:
```<code>#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   1?std::cout<<0:
   std::cout << a/b-a*c;
}
</code>```

15 chars.

Title: m3ph1st0s's programming puzzle 1 (C++)

Body:
This is the first of a series of C++ puzzles for you. Hope you will enjoy.

So, puzzle no.1:

Given the following program:

```<code>#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}
</code>```

Insert some code on a single new line anywhere inside the program so that the output will be 0. The new line will contain AT MOST 18 characters (including spaces), and the rest of the lines will remain unmodified.
 To be clear, here is an example of a valid new code:

```<code>#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   int* p = NULL;
   const float c=0.5;
   std::cout << a/b-a*c;
}
</code>```

A new line with 15 characters was inserted so it's ok. However it does not solve the problem.

If this is too simple for you, don't worry, more is coming!!

Body:
#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   1?std::cout<<0:
   std::cout << a/b-a*c;
}

15 chars.


问:
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

```<code>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"
"/."          ""        -> "/"
</code>```

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

答:
Retina, 44 bytes

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

^$
/
</code>```

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

ContentLicense: CC BY-SA 3.0

Title: Directory calculation

Body:
Retina, 44 bytes

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

^$
/

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

<a href="http://retina.tryitonline.net/#code=JShHYAorYC4rIC98IHwvXC4_LwovCisxYC8_W14vXSovXC5cLnwvXC4_JAoKXiQKLw&input=L2EvYi9jIGQKL2EvYi9jLyBkCi9hL2IvYy8gZC8KL2EvYi9jIC9kCi9hL2IvYyAvZC8KLy4uL2EvYi9jLyBkCi9hLy4uL2IvYy8gZAovYS9iLy4uL2MgZAovYS9iL2MvLi4gZAovYS9iL2MvIC4uCi9hL2IvYyAuLi9kCi9hL2IvYyAvLi4vZAovYS9iL2MgCi9hL2IvYyAuCi9hL2IvYyAuL2QKL2EvYi9jIC8uL2QKL2EvYi9jIGQudHh0Ci9hL2IvYyBkLgovYS9iL2MgLnR4dAovYS9iL2MgLnR4dC9kCi9hL2IvLiAuLy4vLi8uCi9kaXJlYyB0b3J5Ci9hLV8uYi8gX18uXy0uCi9hL2IgLi4vLi4KL2EvYiAuLi8uLi8uLgovYSAuLi8uLi8uLgovLiAKL2EvYi9jIC4vLi4vLi8uLg" rel="nofollow">Try it online! (The first line enables a linefeed-separated test suite.)


问:
Calculate Swatch Internet Time
Output the current time of day as Swatch Internet Time.

Specifically, output a three-digit (zero-padded) number of ".beats" (1000ths of a day) which represent the current time of day in the Swatch Internet Time time zone of UTC+01:00 ("Biel Meantime").

For example, if the current time in UTC is 23:47, then it is 00:47 in UTC+1 ("Biel Meantime"), and the output would be 032.

Examples:

```<code>UTC Current Time  ->  SIT Output
23:47             ->  032
23:00             ->  000
11:00             ->  500
14:37             ->  651
</code>```

The program should produce this output then immediately exit.

Output is to standard output (or equivalent). Must be a complete, runnable program, not a function. The program takes no input; it outputs the current time.

答:
Octave, 64 bytes

```<code>t=gmtime(time);sprintf("%03.f",(mod(++t.hour,24)*60+t.min)/1.44)
</code>```

Uses veganaiZe's printf formatting.

I'm having a bit of difficulty with the time that ideone is returning, so here's a sample run with the time struct returned by gmtime for reference. I'll look around and see if I can get any of the other online Octave compilers to give me proper time.

```<code>t =
  scalar structure containing the fields:
    usec =  528182
    sec =  17
    min =  24
    hour =  21
    mday =  15
    mon =  6
    year =  116
    wday =  5
    yday =  196
    isdst = 0
    zone = UTC

ans = 933
</code>```

Title: Calculate Swatch Internet Time

Body:
Octave, 64 bytes

t=gmtime(time);sprintf("%03.f",(mod(++t.hour,24)*60+t.min)/1.44)

Uses veganaiZe's printf formatting.

I'm having a bit of difficulty with the time that ideone is returning, so here's a sample run with the time struct returned by gmtime for reference. I'll look around and see if I can get any of the other online Octave compilers to give me proper time.

t =
  scalar structure containing the fields:
    usec =  528182
    sec =  17
    min =  24
    hour =  21
    mday =  15
    mon =  6
    year =  116
    wday =  5
    yday =  196
    isdst = 0
    zone = UTC

ans = 933


问:
Sobel edge detector
Your task is to write a program that takes an input image and run it through edge-detection to become an output image.

The edge-detection works as follows (if unclear, see sobel edge detection):

The value for a pixel is the total brightness of a pixel, so if it is in color, you will need to convert it to grayscale first (to keep things simple and golf-able, you can take the average value for R, G and B).

The formulae for Gx and Gy for pixel p(i,j) are:

Gx = -1 * p(i-1, j-1) - 2 * p(i-1, j) - 1 * p(i-1, j+1) + 1 * p(i+1, j-1) + 2 * p(i+1, j) + 1 * p(i+1, j+1)

Gy = -1 * p(i-1, j-1) - 2 * p(i, j-1) - 1 * p(i+1, j-1) + 1 * p(i-1, j+1) + 2 * p(i, j+1) + 1 * p(i+1, j+1)

The value for the size of the edge at that pixel is then: √(Gx2 + Gy2)

The output image is for each pixel the size of the edge √(Gx2 + Gy2) as greyscale.

Bonuses:

Perform a gaussian blur to smooth out the image before edge-detection kicks in, to omit any smaller edges. This gives a bonus of -30% on the end result.

Take the angle of the edge in account. You give the output pixel some color, by taking the same greyscale value and adding color from a color wheel using the angle obtained from the formula arctan(Gy/Gx). This gives another bonus of -30% on the end result.

Rules:

You may omit the value for the edgepixels, and set them to black, or you may use 0 for any pixel outside the image.

Your ouput image must be in an image format that can be opened on most computers.

Output must be written to disk or be pipeable to a file.

Input is given as a commandline argument, in the form of a relative path to the image, or piped in from the commandline.

This is code golf, so shortest code in bytes wins!

答:
MATLAB, 212*0.4=84.8 bytes

Using the filter toolbox and the HSV colorspace

```<code>function f(x);f=@(i,x)imfilter(i,x);s=@(x)fspecial(x);S=s('sobel');A=f(double(rgb2gray(imread(x)))/255,s('gaussian'));X=f(A,S);Y=f(A,S');imwrite(hsv2rgb(cat(3,atan2(Y,X)/pi/2+0.5,0*A+1,sqrt(X.^2+Y.^2))),'t.png')
</code>```

or ungolfed

```<code>function f(x)
f=@(i,x)imfilter(i,x);
s=@(x)fspecial(x);
S=s('sobel');
A=f(double(rgb2gray(imread(x)))/255,s('gaussian'));
X=f(A,S);
Y=f(A,S');
imwrite(hsv2rgb(cat(3,atan2(Y,X)/pi/2+0.5,0*A+1,sqrt(X.^2+Y.^2))),'t.png')
</code>```

Title: Sobel edge detector

Body:
MATLAB, 212*0.4=84.8 bytes

Using the filter toolbox and the HSV colorspace

function f(x);f=@(i,x)imfilter(i,x);s=@(x)fspecial(x);S=s('sobel');A=f(double(rgb2gray(imread(x)))/255,s('gaussian'));X=f(A,S);Y=f(A,S');imwrite(hsv2rgb(cat(3,atan2(Y,X)/pi/2+0.5,0*A+1,sqrt(X.^2+Y.^2))),'t.png')

or ungolfed

function f(x)
f=@(i,x)imfilter(i,x);
s=@(x)fspecial(x);
S=s('sobel');
A=f(double(rgb2gray(imread(x)))/255,s('gaussian'));
X=f(A,S);
Y=f(A,S');
imwrite(hsv2rgb(cat(3,atan2(Y,X)/pi/2+0.5,0*A+1,sqrt(X.^2+Y.^2))),'t.png')


问:
Calculate the day number of the year
Seems like we do not have this one yet, so here we go:

The Challenge

Write a program or function that takes a date as input and outputs the day number of the year. You may not use any builtins for that!

Rules

As usual you may write a full program or a function.

The format of the input is up to you, but it has to contain a year, a month and a day. Make clear which one your solution uses!

No date-related builtins allowed! You gotta do the work by yourself. Builtins which are not related to date operations are fine.

Base for the calcultion is the gregorian calendar.

You have to take account of leap-years.

You only need to handle years in the range [1, 9999]

Standard loopholes are forbidden.

Lowest byte count wins!

Testcases

Input format here is YYYY/MM/DD

```<code>2016/07/05 -> 187
2000/03/28 -> 88
0666/06/06 -> 157
6789/10/11 -> 284
0004/04/04 -> 95
1337/07/13 -> 194
</code>```

Happy Coding!

Title: Calculate the day number of the year

Body:
C, <s>96</s> <s>102</s> <s>89</s> 61 bytes

g(y,m,d){printf("%d",m/2*31+--m/2*30-(y%(y%25?4:16)?2:1)+d);}


问:
Stock Time Machine

Stock Time Machine

You've gained access to a dataset, tomorrowStocks, which contains the stock prices from your favorite business on the NASDAQ. This dataset is a container indexed by minutes past opening. Each index contains the price of the stock at that time.

```<code>// Assume the stock market opens at 9:30AM EDT
// tomorrowStocks[] contains the prices of your target stock.
// If the stock is $22 @ 10:30AM EDT
tomorrowStocks[60] == 22
</code>```

Output

Your task is to determine the best possible outcome of 1 purchase and 1 sale of 1 stock from the given dataset.

Gotchas

You must buy and sell exactly 1 stock.

You may not buy and sell in the same time slot.

You must buy before you sell.

Test Data

```<code>[1,2,3,4,5]    # 4
[1,99,2,105]   # 104
[99,1,99,100]  # 99
[99,1,1,2,1,3] # 2
[5,4,3,3,1]    # 0
[5,4,3,1]      # -1
[5,2,1]        # -1
[5,4,1]        # -1
[55,45,20,1]   # -10
[5,1]          # -4
[10,7,5,1]     # -2
[7]            # Invalid input -- assume size >= 2
</code>```

This is a code-golf; submit the shortest answer in your favorite language!

答:
JavaScript (ES6), <s>57</s> 54 bytes

```<code>a=>(m=Math.max)(...a.map((x,i)=>m(...a.slice(i+1))-x))
</code>```

In JavaScript it's easier to take the max of the remainder of the array and subtract the current element. (In the case of the last element the result will still be -Infinity.) Edit: Saved 3 bytes thanks to @CharlieWynn.

Title: Stock Time Machine

Body:
JavaScript (ES6), <s>57</s> 54 bytes

a=>(m=Math.max)(...a.map((x,i)=>m(...a.slice(i+1))-x))

In JavaScript it's easier to take the max of the remainder of the array and subtract the current element. (In the case of the last element the result will still be -Infinity.) Edit: Saved 3 bytes thanks to @CharlieWynn.


答:
Python 2, <s>265</s> <s>260</s> 254 bytes

```<code>y=lambda:[x for x in raw_input().split("/")if x!=""and x!="."]
a=y();n=y();m=len(a)-1
while m>0:
 if a[m]==".."and m>0:del a[m];del a[m-1];m-=1
 elif a[m]=="..":del a[m]
 m-=1
for i in n:
 if i==".."and len(a)>0:del a[-1]
 else:a+=i,
print"/"+"/".join(a)
</code>```

Title: Directory calculation

Body:
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

```<code>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"
"/."          ""        -> "/"
</code>```

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

Body:
Python 2, <s>265</s> <s>260</s> 254 bytes

y=lambda:[x for x in raw_input().split("/")if x!=""and x!="."]
a=y();n=y();m=len(a)-1
while m>0:
 if a[m]==".."and m>0:del a[m];del a[m-1];m-=1
 elif a[m]=="..":del a[m]
 m-=1
for i in n:
 if i==".."and len(a)>0:del a[-1]
 else:a+=i,
print"/"+"/".join(a)


答:
05AB1E, 4 bytes

Using FryAmTheEggman's approach. Code:

```<code>¥ŒOà
</code>```

Explanation:

```<code>¥     # Calculate the increments of the array.
 Œ    # Get all substring of the array.
  O   # Sum the arrays in the array.
   à  # Get the largest sum and implicitly print that.
</code>```

Uses the CP-1252 encoding. Try it online!.

Title: Stock Time Machine

Body:
Stock Time Machine

You've gained access to a dataset, tomorrowStocks, which contains the stock prices from your favorite business on the NASDAQ. This dataset is a container indexed by minutes past opening. Each index contains the price of the stock at that time.

```<code>// Assume the stock market opens at 9:30AM EDT
// tomorrowStocks[] contains the prices of your target stock.
// If the stock is $22 @ 10:30AM EDT
tomorrowStocks[60] == 22
</code>```

Output

Your task is to determine the best possible outcome of 1 purchase and 1 sale of 1 stock from the given dataset.

Gotchas

You must buy and sell exactly 1 stock.

You may not buy and sell in the same time slot.

You must buy before you sell.

Test Data

```<code>[1,2,3,4,5]    # 4
[1,99,2,105]   # 104
[99,1,99,100]  # 99
[99,1,1,2,1,3] # 2
[5,4,3,3,1]    # 0
[5,4,3,1]      # -1
[5,2,1]        # -1
[5,4,1]        # -1
[55,45,20,1]   # -10
[5,1]          # -4
[10,7,5,1]     # -2
[7]            # Invalid input -- assume size >= 2
</code>```

This is a code-golf; submit the shortest answer in your favorite language!

Body:
05AB1E, 4 bytes

Using FryAmTheEggman's approach. Code:

¥ŒOà

Explanation:

¥     # Calculate the increments of the array.
 Œ    # Get all substring of the array.
  O   # Sum the arrays in the array.
   à  # Get the largest sum and implicitly print that.

Uses the CP-1252 encoding. Try it online!.


问:
I programming puzzles, il code golf

Background

The Italian definite article (corresponding to English the) has seven different forms: l', il, lo, gli, i, la, le. Which one to use depends on three variables:

Gender: masculine / feminine.

Number: singular / plural.

Initial letter of the subsequent word: vowel / consonant type A / consonant type B.

Vowel is any of these: aeiou.

Consonant type B is any of these cases: s- followed by another consonant, z-, gn-, pn-, ps-, x-, i- followed by vowel (this i acts as a semivowel).

Consonant type A is a consonant that is not type B.

The table shows the article form to be used in each of the twelve combinations of the three above variables. Note that the l' form is attached to the following word with a single quote and without a space.

The challenge

Input a word and one or two strings, numbers or Booleans indicating gender and number. (The initial letters will have to be obtained from the input word).

The input word will be a sequence of lowercase ASCII letters. Accented vowels will be replaced by their non-accented versions (for example, realtà will be input as realta).

The gender and number inputs can be separate numbers, Booleans or strings, or a combined number of string (for example, 1 for masculine singular, 2 for feminine singular, etc).

Any reasonable format and separator can be used, as long as it is specified in the answer.

Output the word preceded by the appropriate form of the article, with space or single quote as needed. The output should also be lowercase. Trailing or leading blank space is allowed.

Code golf, shortest wins.

Test cases

In the following I use the input letters m, f to specify gender, and s, p for number (this is just one possible input format).

```<code>Input               Output              Comment

macchina f s        la macchina         Initial letter is cons. A
zio m s             lo zio              Initial letter is cons. B
libri m p           i libri             Initial letter is cons. A
ieri m s            lo ieri             Initial letter is cons. B
aquile f p          le aquile           Initial letter is vowel
spagnoli m p        gli spagnoli        Initial letter is cons. B
golf m s            il golf             Initial letter is cons. A
ombra f s           l'ombra             Initial letter is vowel
impossibili m p     gli impossibili     Initial letter is vowel
</code>```

答:
Retina, <s>138</s> <s>133</s> <s>129</s> 113 bytes

```<code>^.(s[^aeiou]|z|gn|pn|ps|x|i[aeiou])
B$&
^.[aeiou]
V$&
^\d.
A$&
V[02]
l'
A0
il
B0
lo
A1
i
.1
gli
.2
la
.3
le
</code>```

Test suite.
(prepended %(G`\n to run all test-cases at once)

Input format: macchina f s becomes 2macchina instead.

```<code>0: Masculine Singular
1: Masculine Plural
2: Feminine Singular
3: Feminine Plural
</code>```

Conversion table thanks to Kevin Lau.

Title: I programming puzzles, il code golf

Body:
Retina, <s>138</s> <s>133</s> <s>129</s> 113 bytes

^.(s[^aeiou]|z|gn|pn|ps|x|i[aeiou])
B$&
^.[aeiou]
V$&
^\d.
A$&
V[02]
l'
A0
il
B0
lo
A1
i
.1
gli
.2
la
.3
le

Test suite.
(prepended %(G`\n to run all test-cases at once)

Input format: macchina f s becomes 2macchina instead.

0: Masculine Singular
1: Masculine Plural
2: Feminine Singular
3: Feminine Plural

Conversion table thanks to Kevin Lau.


问:
Ascending matrix
The "ascending matrix" is an infinite matrix of whole numbers (0 included) in which any element is the smallest available element which has not been previously used on the respective row and column:

```<code>  | 1 2 3 4 5 6 ...
--+----------------
1 | 0 1 2 3 4 5 ...
2 | 1 0 3 2 5 4 ...
3 | 2 3 0 1 6 7 ...
4 | 3 2 1 0 7 6 ...
5 | 4 5 6 7 0 1 ...
6 | 5 4 7 6 1 0 ...
. | ...............
</code>```

Your task is to write a program that will output the element found at the row and column specified by the input. (standard input and output)

Test cases:

```<code>5 3 -> 6
2 5 -> 5
</code>```

Code Golf rules apply—the shortest code wins.

P.S. Even if this has an algorithmic nature the code can be very, very concise.

EDIT: I wasn't expecting to see the xor solution so early. I was really hoping to see 10 posts with an algorithmic approach and THEN the xor solution. Now, having in mind that it's not much fun to see how to write xor in different languages I recommend that you also try an algorithmic approach.

So, yes, I think no one can beat the 5 character mark now—therefore I congratulate Ilmari Karonen for the smartest and shortest solution. But there's a new challenge up ahead: write the shortest algorithmic solution.

答:
K, 31

```<code>{0b/:{(x|y)&~x~y}. 0b\:'-1+x,y}
</code>```

Stole Ilmari Karonen's XOR logic, which I would never have spotted myself.

Title: Ascending matrix

Body:
K, 31

{0b/:{(x|y)&~x~y}. 0b\:'-1+x,y}

Stole Ilmari Karonen's XOR logic, which I would never have spotted myself.


答:
Python 2.7, <s>131</s> <s>128</s> 121 bytes:

```<code>from datetime import*;S=lambda f:int(datetime.utcnow().strftime(f));print'%03.0f'%(((S('%H')+1%24)*3600+S('%M')*60)/86.4)
</code>```

A full program that outputs the Swatch Internet Time.

Simply uses Python's built in datetime module to first get the UTC+0 time in hours and minutes using datetime.utfnow().strftime('%H') and datetime.utfnow().strftime('%M'), respectively. Then, the time is converted into UTC+1 by adding 1 to the hours and then modding the sum by 24 to ensure the result is in the 24-hour range. Finally, the hour is turned into its equivalent in seconds, which is added to the minute's equivalent in seconds, and the resulting sum is divided by 86.4, as there are 86.4 seconds or 1 min. 24 sec. in 1 ".beat", after which,  using string formatting, the quotient is rounded to the nearest integer and padded with zeroes until the length is 3.

However, I am not the one to stop here. In the above solution, I used a more direct method to convert the time to UTC+1. However, wanted to add a bit of a bigger challenge for myself and implement this using only Python's built in time module, which apparently does not have any built-in method that I know of to convert local time into UTC+0 time. So now, without further ado, here is the perfectly working version using only the time module, currently standing at 125 bytes:

```<code>from time import*;I=lambda g:int(strftime(g));print'%03.0f'%((((I('%H')+1-daylight)%24*3600+timezone)%86400+I('%M')*60)/86.4)
</code>```

This can output the correct Swatch Internet Time for any and all time zones, and basically does pretty much everything the same as in the first solution, except this time converts the local time into UTC+1 by first adding 1 to the hour, and then subtracting 1 if daylight-savings time is currently, locally observed, or 0 otherwise. Then, this difference is modded by 24 to ensure that the result stays within the 24 hour range, after which it is multiplied by 3600 for conversion into seconds. This product is then added to the result from the built-in timezone method, which returns the local offset from UTC+0. After this, you finally have your hours in UTC+1. This then continues on from here as in the first solution.

Title: Calculate Swatch Internet Time

Body:
Output the current time of day as Swatch Internet Time.

Specifically, output a three-digit (zero-padded) number of ".beats" (1000ths of a day) which represent the current time of day in the Swatch Internet Time time zone of UTC+01:00 ("Biel Meantime").

For example, if the current time in UTC is 23:47, then it is 00:47 in UTC+1 ("Biel Meantime"), and the output would be 032.

Examples:

```<code>UTC Current Time  ->  SIT Output
23:47             ->  032
23:00             ->  000
11:00             ->  500
14:37             ->  651
</code>```

The program should produce this output then immediately exit.

Output is to standard output (or equivalent). Must be a complete, runnable program, not a function. The program takes no input; it outputs the current time.

Body:
Python 2.7, <s>131</s> <s>128</s> 121 bytes:

from datetime import*;S=lambda f:int(datetime.utcnow().strftime(f));print'%03.0f'%(((S('%H')+1%24)*3600+S('%M')*60)/86.4)

A full program that outputs the Swatch Internet Time.

Simply uses Python's built in datetime module to first get the UTC+0 time in hours and minutes using datetime.utfnow().strftime('%H') and datetime.utfnow().strftime('%M'), respectively. Then, the time is converted into UTC+1 by adding 1 to the hours and then modding the sum by 24 to ensure the result is in the 24-hour range. Finally, the hour is turned into its equivalent in seconds, which is added to the minute's equivalent in seconds, and the resulting sum is divided by 86.4, as there are 86.4 seconds or 1 min. 24 sec. in 1 ".beat", after which,  using string formatting, the quotient is rounded to the nearest integer and padded with zeroes until the length is 3.

However, I am not the one to stop here. In the above solution, I used a more direct method to convert the time to UTC+1. However, wanted to add a bit of a bigger challenge for myself and implement this using only Python's built in time module, which apparently does not have any built-in method that I know of to convert local time into UTC+0 time. So now, without further ado, here is the perfectly working version using only the time module, currently standing at 125 bytes:

from time import*;I=lambda g:int(strftime(g));print'%03.0f'%((((I('%H')+1-daylight)%24*3600+timezone)%86400+I('%M')*60)/86.4)

This can output the correct Swatch Internet Time for any and all time zones, and basically does pretty much everything the same as in the first solution, except this time converts the local time into UTC+1 by first adding 1 to the hour, and then subtracting 1 if daylight-savings time is currently, locally observed, or 0 otherwise. Then, this difference is modded by 24 to ensure that the result stays within the 24 hour range, after which it is multiplied by 3600 for conversion into seconds. This product is then added to the result from the built-in timezone method, which returns the local offset from UTC+0. After this, you finally have your hours in UTC+1. This then continues on from here as in the first solution.


答:
Batch, <s>282</s> <s>281</s> <s>279</s> 276 bytes

```<code>@echo off
set a=\
set r=%~2
if "%r%"=="" set r=%~1
if not %r:~,1%==/ set r=%~1/%~2
for %%a in (%r:/= %)do call:x %%a
if not %a%==\ set a=%a:~,-1%
echo %a:\=/%
exit/b
:x
if %1==. exit/b
if not %1==.. set a=%a%%1\&exit/b
if not %a%==\ for %%a in (%a:~,-1%)do set a=%%~pa
</code>```

Annoyingly Batch expressions don't generally like empty variables. Edit: Saved 1 byte thanks to @CᴏɴᴏʀO'Bʀɪᴇɴ and 2 bytes thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ (and a bunch of bytes on other answers too, although alas uncredited).

Title: Directory calculation

Body:
Batch, <s>282</s> <s>281</s> <s>279</s> 276 bytes

@echo off
set a=\
set r=%~2
if "%r%"=="" set r=%~1
if not %r:~,1%==/ set r=%~1/%~2
for %%a in (%r:/= %)do call:x %%a
if not %a%==\ set a=%a:~,-1%
echo %a:\=/%
exit/b
:x
if %1==. exit/b
if not %1==.. set a=%a%%1\&exit/b
if not %a%==\ for %%a in (%a:~,-1%)do set a=%%~pa

Annoyingly Batch expressions don't generally like empty variables. Edit: Saved 1 byte thanks to @CᴏɴᴏʀO'Bʀɪᴇɴ and 2 bytes thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ (and a bunch of bytes on other answers too, although alas uncredited).


问:
Rotate a diamond tiling
Any regular hexagon can be tiled with diamonds, for instance like so (stolen from this question):

```<code>   ______
  /_/_/\_\
 /_/\_\/\_\
/\_\/_/\/_/\
\/_/\_\/_/\/
 \_\/_/\_\/
  \_\_\/_/
</code>```

We'll consider the above a tiling of size 1 (since the diamonds' sides are made of one / or \ each). The same tiling of size 2 would look like:

```<code>      ____________
     /   /   /\   \
    /___/___/  \___\
   /   /\   \  /\   \
  /___/  \___\/  \___\
 /\   \  /   /\  /   /\
/  \___\/___/  \/___/  \
\  /   /\   \  /   /\  /
 \/___/  \___\/___/  \/
  \   \  /   /\   \  /
   \___\/___/  \___\/
    \   \   \  /   /
     \___\___\/___/
</code>```

Your task is to rotate diamond tilings by a multiple of 60 degrees. The diamond tiling in the input can be in any size (and the size is not explicitly specified in the input). But it would always be a valid tiling, and all sides of the hexagon would have the same length.

These are the above examples rotated by 60 degrees clockwise:

```<code>   ______
  /_/\_\_\
 /\_\/_/\_\
/\/_/\_\/_/\
\/\_\/_/_/\/
 \/_/\_\_\/
  \_\/_/_/

      ____________
     /   /\   \   \
    /___/  \___\___\
   /\   \  /   /\   \
  /  \___\/___/  \___\
 /\  /   /\   \  /   /\
/  \/___/  \___\/___/  \
\  /\   \  /   /   /\  /
 \/  \___\/___/___/  \/
  \  /   /\   \   \  /
   \/___/  \___\___\/
    \   \  /   /   /
     \___\/___/___/
</code>```

The input is a non-negative integer and a diamond tiling. Your program (or function) should rotate it by the integer * 60 degrees. You decide whether to rotate clockwise or counterclockwise, as long as it is consistent. Both the input and output shouldn't have extra leading or trailing spaces.

This is code-golf. Shortest code wins.

Related questions:

Rotate a Chinese checkerboard

Rotate a two-dimensional list by 45 degrees

Scale up a Diamond Tiling

答:
Pyth, 81 bytes

```<code>ju.es.e.reh|@s.e.e[yYykZ)bGCa+LV,t-y+k*3Y*5J-+kY/lG2Jc2j406610 4K"_/\\_\\"dKbGQ.z
</code>```

Try it online

Rotates counterclockwise.

Each 60° rotation is performed using the following algorithm.  Suppose the input is a hexagon of order k, so it has 2⋅k + 1 rows and 4⋅k columns.  To find the rotated character at row i column j, let

u = i + j − k

v = j − 3⋅i + 5⋅k

Then the output character is

\, if the input has / at row (u + 1)/2 column (v + 1)/2; else

/, if the input has _ at row u/2 column v/2 or row u/2 column (v + 2)/2; else

_, if the input has \ at row (u + 2)/2 column v/2 or row (u + 1)/2 column (v − 1)/2; else

space.

(We do not count characters at half-integer indices.)

Title: Rotate a diamond tiling

Body:
Pyth, 81 bytes

ju.es.e.reh|@s.e.e[yYykZ)bGCa+LV,t-y+k*3Y*5J-+kY/lG2Jc2j406610 4K"_/\\_\\"dKbGQ.z

<a href="https://pyth.herokuapp.com/?code=ju.es.e.reh%7C%40s.e.e%5ByYykZ%29bGCa%2BLV%2Ct-y%2Bk%2a3Y%2a5J-%2BkY%2FlG2Jc2j406610+4K%22_%2F%5C%5C_%5C%5C%22dKbGQ.z&input=5%0A++++++____________%0A+++++%2F+++%2F+++%2F%5C+++%5C%0A++++%2F___%2F___%2F++%5C___%5C%0A+++%2F+++%2F%5C+++%5C++%2F%5C+++%5C%0A++%2F___%2F++%5C___%5C%2F++%5C___%5C%0A+%2F%5C+++%5C++%2F+++%2F%5C++%2F+++%2F%5C%0A%2F++%5C___%5C%2F___%2F++%5C%2F___%2F++%5C%0A%5C++%2F+++%2F%5C+++%5C++%2F+++%2F%5C++%2F%0A+%5C%2F___%2F++%5C___%5C%2F___%2F++%5C%2F%0A++%5C+++%5C++%2F+++%2F%5C+++%5C++%2F%0A+++%5C___%5C%2F___%2F++%5C___%5C%2F%0A++++%5C+++%5C+++%5C++%2F+++%2F%0A+++++%5C___%5C___%5C%2F___%2F" rel="nofollow">Try it online

Rotates counterclockwise.

Each 60° rotation is performed using the following algorithm.  Suppose the input is a hexagon of order k, so it has 2⋅k + 1 rows and 4⋅k columns.  To find the rotated character at row i column j, let

u = i + j − k

v = j − 3⋅i + 5⋅k

Then the output character is

\, if the input has / at row (u + 1)/2 column (v + 1)/2; else

/, if the input has _ at row u/2 column v/2 or row u/2 column (v + 2)/2; else

_, if the input has \ at row (u + 2)/2 column v/2 or row (u + 1)/2 column (v − 1)/2; else

space.

(We do not count characters at half-integer indices.)


答:
Ruby, <s>147</s> 146 bytes

Try it online?

It might be possible to use a better method to determine which article to use, but I'm not aware of any.

As per the spec, the identifier is a number, as follows:

```<code>0: Masculine Singular
1: Masculine Plural
2: Feminine Singular
3: Feminine Plural
</code>```

```<code>->w,i{(%w"lo gli la le l' gli l' le il i la le"[(0..2).find{|r|[/^(i[aeiou]|s[^aeiou]|z|x|[gp]n|ps)/,/^[aeiou]/,//][r]=~w}*4+i]+' '+w).sub"' ",?'}
</code>```

Title: I programming puzzles, il code golf

Body:
Background

The Italian definite article (corresponding to English the) has seven different forms: l', il, lo, gli, i, la, le. Which one to use depends on three variables:

Gender: masculine / feminine.

Number: singular / plural.

Initial letter of the subsequent word: vowel / consonant type A / consonant type B.

Vowel is any of these: aeiou.

Consonant type B is any of these cases: s- followed by another consonant, z-, gn-, pn-, ps-, x-, i- followed by vowel (this i acts as a semivowel).

Consonant type A is a consonant that is not type B.

The table shows the article form to be used in each of the twelve combinations of the three above variables. Note that the l' form is attached to the following word with a single quote and without a space.

The challenge

Input a word and one or two strings, numbers or Booleans indicating gender and number. (The initial letters will have to be obtained from the input word).

The input word will be a sequence of lowercase ASCII letters. Accented vowels will be replaced by their non-accented versions (for example, realtà will be input as realta).

The gender and number inputs can be separate numbers, Booleans or strings, or a combined number of string (for example, 1 for masculine singular, 2 for feminine singular, etc).

Any reasonable format and separator can be used, as long as it is specified in the answer.

Output the word preceded by the appropriate form of the article, with space or single quote as needed. The output should also be lowercase. Trailing or leading blank space is allowed.

Code golf, shortest wins.

Test cases

In the following I use the input letters m, f to specify gender, and s, p for number (this is just one possible input format).

```<code>Input               Output              Comment

macchina f s        la macchina         Initial letter is cons. A
zio m s             lo zio              Initial letter is cons. B
libri m p           i libri             Initial letter is cons. A
ieri m s            lo ieri             Initial letter is cons. B
aquile f p          le aquile           Initial letter is vowel
spagnoli m p        gli spagnoli        Initial letter is cons. B
golf m s            il golf             Initial letter is cons. A
ombra f s           l'ombra             Initial letter is vowel
impossibili m p     gli impossibili     Initial letter is vowel
</code>```

Body:
Ruby, <s>147</s> 146 bytes

Try it online?

It might be possible to use a better method to determine which article to use, but I'm not aware of any.

As per the spec, the identifier is a number, as follows:

0: Masculine Singular
1: Masculine Plural
2: Feminine Singular
3: Feminine Plural

->w,i{(%w"lo gli la le l' gli l' le il i la le"[(0..2).find{|r|[/^(i[aeiou]|s[^aeiou]|z|x|[gp]n|ps)/,/^[aeiou]/,//][r]=~w}*4+i]+' '+w).sub"' ",?'}


答:
Batch, <s>446</s> <s>390</s> <s>385</s> 380 bytes

```<code>@echo off
set w=%2
call:l %1 l' gli_ l' le_ il_ i_ la_ le_ lo_ gli_ le_ le_
exit/b
:l
for /l %%a in (0,1,%1)do shift
set o=%5
for %%a in (gn pn ps)do if %%a==%w:~,2% set o=%9
for %%a in (s z x)do if %%a==%w:~,1% set o=%9
for %%a in (a e i o u)do if %%a==%w:~,1% set o=%1
for %%a in (a e i o u)do if i%%a==%w:~,2% (set o=%9)else if s%%a==%w:~,2% set o=%1
echo %o:_= %%w%
</code>```

New version uses the same 0-3 encoding for the gender and number as several other answers. Works by creating a 1-dimensional array %2 .. %13 of forms, then shifting out the first 1+%1 elements so that the forms of interest become %1, %5 and %9 (which is fortunate as Batch won't go above %9 without shifting). It then laboriously checks the lists of prefixes to find out which form needs to be used. _ is used as a placeholder to represent a space until the word is output.

Title: I programming puzzles, il code golf

Body:
Batch, <s>446</s> <s>390</s> <s>385</s> 380 bytes

@echo off
set w=%2
call:l %1 l' gli_ l' le_ il_ i_ la_ le_ lo_ gli_ le_ le_
exit/b
:l
for /l %%a in (0,1,%1)do shift
set o=%5
for %%a in (gn pn ps)do if %%a==%w:~,2% set o=%9
for %%a in (s z x)do if %%a==%w:~,1% set o=%9
for %%a in (a e i o u)do if %%a==%w:~,1% set o=%1
for %%a in (a e i o u)do if i%%a==%w:~,2% (set o=%9)else if s%%a==%w:~,2% set o=%1
echo %o:_= %%w%

New version uses the same 0-3 encoding for the gender and number as several other answers. Works by creating a 1-dimensional array %2 .. %13 of forms, then shifting out the first 1+%1 elements so that the forms of interest become %1, %5 and %9 (which is fortunate as Batch won't go above %9 without shifting). It then laboriously checks the lists of prefixes to find out which form needs to be used. _ is used as a placeholder to represent a space until the word is output.


答:
PHP, 48 46 bytes

```<code><?=sprintf("%03d",((time()+3600)%86400)/86.4);
</code>```

I have another PHP answer above, but this one avoids using PHP's built-in Swatch Internet Time support, so it's more interesting, if longer.

This is largely self-explanatory if you're familiar with UNIX time and sprintf, though note I'm using |0 as a short way to truncate a float to an integer (actually I realised this is unnecessary in PHP, oops!)

Title: Calculate Swatch Internet Time

Body:
PHP, 48 46 bytes

<?=sprintf("%03d",((time()+3600)%86400)/86.4);

I have another PHP answer above, but this one avoids using PHP's built-in Swatch Internet Time support, so it's more interesting, if longer.

This is largely self-explanatory if you're familiar with UNIX time and sprintf, though note I'm using |0 as a short way to truncate a float to an integer (actually I realised this is unnecessary in PHP, oops!)

ContentLicense: CC BY-SA 4.0


答:
Java, 141 bytes

```<code>a->java.util.stream.IntStream.range(0,a.size()-1).map(i->a.subList(i+1,a.size()).stream().reduce(Math::max).get()-a.get(i)).max().getAsInt();
</code>```

The lambda accepts an ArrayList and returns an Integer.

Ungolfed code with test cases:

```<code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.IntStream;

class Test {

    public static void main(String[] args) {
        Function<ArrayList<Integer>, Integer> f = a -> IntStream
            .range(0, a.size()-1)
            .map(i -> a.subList(i+1, a.size()).stream().reduce(Math::max).get() - a.get(i))
            .max()
            .getAsInt();

        System.out.println(f.apply(new ArrayList<>(Arrays.asList(1,2,3,4,5))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(1,99,2,105))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(99,1,99,100))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(99,1,1,2,1,3))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,4,3,3,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,4,3,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,2,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,4,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(55,45,20,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(10,7,5,1))));
    }
}
</code>```

As far as I know, Java doesn't have a way to look forward in a stream, and manipulating the method from which the stream is generated produces strange results. So doing a.remove(0) inside a map horribly breaks the stream.

Title: Stock Time Machine

Body:
Java, 141 bytes

a->java.util.stream.IntStream.range(0,a.size()-1).map(i->a.subList(i+1,a.size()).stream().reduce(Math::max).get()-a.get(i)).max().getAsInt();

The lambda accepts an ArrayList and returns an Integer.

Ungolfed code with test cases:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.IntStream;

class Test {

    public static void main(String[] args) {
        Function<ArrayList<Integer>, Integer> f = a -> IntStream
            .range(0, a.size()-1)
            .map(i -> a.subList(i+1, a.size()).stream().reduce(Math::max).get() - a.get(i))
            .max()
            .getAsInt();

        System.out.println(f.apply(new ArrayList<>(Arrays.asList(1,2,3,4,5))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(1,99,2,105))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(99,1,99,100))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(99,1,1,2,1,3))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,4,3,3,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,4,3,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,2,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,4,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(55,45,20,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(10,7,5,1))));
    }
}

As far as I know, Java doesn't have a way to look forward in a stream, and manipulating the method from which the stream is generated produces strange results. So doing a.remove(0) inside a map horribly breaks the stream.


答:
C#, 43 bytes

```<code>(x,y)=>Path.GetFullPath(Path.Combine(x,y));
</code>```

Saved 1 byte thanks to @aloisdg

Path.Combine puts the arguments together, and Path.GetFullPath resolves the ..\s

Title: Directory calculation

Body:
C#, 43 bytes

(x,y)=>Path.GetFullPath(Path.Combine(x,y));

Saved 1 byte thanks to @aloisdg

Path.Combine puts the arguments together, and Path.GetFullPath resolves the ..\s


答:
Python 3.5, <s>238</s> <s>235</s> <s>192</s> <s>181</s> 178 bytes:

(-13 bytes thanks to tips from Leaky Nun!)

```<code>import re;R=re.match;lambda a,b:(R('s[^aeiou]|(z|gn|pn|ps|x|i)[aeiou]',a)and['lo ','gli ','la '][b]or R('[aeiou]',a)and["l'",'gli '][b%2]or['il ','i ','la '][b]if b<3else'le ')+a
</code>```

An anonymous lambda function that takes arguments in the form of (<String>, <Integer Gender-Plurality mapping>), where the mapping is as follows:

```<code>0 -> Masculine Singular
1 -> Masculine Plural
2 -> Feminine Singular
3 -> Feminine Plural
</code>```

To call it, simply give the function any valid name, and then call it like a normal function wrapped inside a print statement. Therefore, if the question were to be named U, simply call it like print(U(<String>, <Integer Gender-Plurality mapping>)).

Try It Online! (Ideone)

Title: I programming puzzles, il code golf

Body:
Python 3.5, <s>238</s> <s>235</s> <s>192</s> <s>181</s> 178 bytes:

(-13 bytes thanks to tips from Leaky Nun!)

import re;R=re.match;lambda a,b:(R('s[^aeiou]|(z|gn|pn|ps|x|i)[aeiou]',a)and['lo ','gli ','la '][b]or R('[aeiou]',a)and["l'",'gli '][b%2]or['il ','i ','la '][b]if b<3else'le ')+a

An anonymous lambda function that takes arguments in the form of (<String>, <Integer Gender-Plurality mapping>), where the mapping is as follows:

0 -> Masculine Singular
1 -> Masculine Plural
2 -> Feminine Singular
3 -> Feminine Plural

To call it, simply give the function any valid name, and then call it like a normal function wrapped inside a print statement. Therefore, if the question were to be named U, simply call it like print(U(<String>, <Integer Gender-Plurality mapping>)).

Try It Online! (Ideone)


答:
Java 7, 83 bytes

String p(String a,String b){return Paths.get(a).resolve(b).normalize().toString();}
```

normalize is needed to deal with relative references. add is used to handle the second path starting with /, which Paths.get(a, b) won't handle as specified.

Title: Directory calculation

Body:
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

```<code>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"
"/."          ""        -> "/"
</code>```

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

Body:
Java 7, 83 bytes

String p(String a,String b){return Paths.get(a).resolve(b).normalize().toString();}

normalize is needed to deal with relative references. add is used to handle the second path starting with /, which Paths.get(a, b) won't handle as specified.


问:
Holiday Gift Exchange
Another problem from our internal golfing...this one around the holidays last year.

PROBLEM

Andy, Barb, Carl, Didi, Earl, and Fran are buying gifts for each other. Draw names for a gift exchange.

Each person buys one gift and receives one gift.

Nobody buys their own gift.

Running the solution multiple times should produce different results (giver-receiver pair should not be predictable or identical from run to run).

INPUT

None.

OUTPUT

Formatted as in this example:

Andy buys for Barb

  Barb buys for Carl

  Carl buys for Didi

  Didi buys for Earl

  Earl buys for Fran

  Fran buys for Andy

答:
Scheme, 173

Gives one of two solutions.

```<code>(define(m lst)
    (printf"~v buys for ~v~n"(car lst)(cadr lst))
    (if(eq?(cadr lst)'Andy)0(m(cdr lst)))
)
(m((if(odd?(random 2))reverse values)'(Andy Barb Carl Didi Earl Fran Andy)))
</code>```

ContentLicense: CC BY-SA 2.5

Title: Holiday Gift Exchange

Body:
Scheme, 173

Gives one of two solutions.

(define(m lst)
    (printf"~v buys for ~v~n"(car lst)(cadr lst))
    (if(eq?(cadr lst)'Andy)0(m(cdr lst)))
)
(m((if(odd?(random 2))reverse values)'(Andy Barb Carl Didi Earl Fran Andy)))


答:
PHP, 38

Just a simple implementation of Ilmari Karonen's XOR

<?php echo --$_GET['a']^--$_GET['b']?>

Usage:

.../xor.php?a=4&b=7

will print 6

Title: Ascending matrix

Body:
The "ascending matrix" is an infinite matrix of whole numbers (0 included) in which any element is the smallest available element which has not been previously used on the respective row and column:

```<code>  | 1 2 3 4 5 6 ...
--+----------------
1 | 0 1 2 3 4 5 ...
2 | 1 0 3 2 5 4 ...
3 | 2 3 0 1 6 7 ...
4 | 3 2 1 0 7 6 ...
5 | 4 5 6 7 0 1 ...
6 | 5 4 7 6 1 0 ...
. | ...............
</code>```

Your task is to write a program that will output the element found at the row and column specified by the input. (standard input and output)

Test cases:

```<code>5 3 -> 6
2 5 -> 5
</code>```

Code Golf rules apply—the shortest code wins.

P.S. Even if this has an algorithmic nature the code can be very, very concise.

EDIT: I wasn't expecting to see the xor solution so early. I was really hoping to see 10 posts with an algorithmic approach and THEN the xor solution. Now, having in mind that it's not much fun to see how to write xor in different languages I recommend that you also try an algorithmic approach.

So, yes, I think no one can beat the 5 character mark now—therefore I congratulate Ilmari Karonen for the smartest and shortest solution. But there's a new challenge up ahead: write the shortest algorithmic solution.


答:
Bash, 41 bytes

This bash script has the side effect of creating directories if they don't exist, but it should meet the requirements.  Thanks Karl and Neil for your improvements.

```<code>mkdir -p $1;cd $1;mkdir -p $2;cd "$2";pwd
</code>```

Usage: bash getpath.sh "absolute" "new"

If you don't like the stderr when second argument is an empty string, you can test for it as follows (48 bytes):

```<code>mkdir -p $1;cd $1;[ $2 ]&&mkdir -p $2&&cd $2;pwd
</code>```

Previous 30 byte attempt (requires directories to exist):
<s>cd $1;[ $2 ]&&cd $2;echo pwd</s>

Title: Directory calculation

Body:
Bash, 41 bytes

This bash script has the side effect of creating directories if they don't exist, but it should meet the requirements.  Thanks Karl and Neil for your improvements.

mkdir -p $1;cd $1;mkdir -p $2;cd "$2";pwd

Usage: bash getpath.sh "absolute" "new"

If you don't like the stderr when second argument is an empty string, you can test for it as follows (48 bytes):

mkdir -p $1;cd $1;[ $2 ]&&mkdir -p $2&&cd $2;pwd

Previous 30 byte attempt (requires directories to exist):
<s>cd $1;[ $2 ]&&cd $2;echo pwd</s>


答:
Java, <s>227</s> <s>208</s> 195 bytes

-13 bytes thanks to Leaky Nun

```<code>String f(String a,int o){boolean v=a.matches("^([aeou]|i[^aeiou]).*"),b=a.matches("^([ixz]|gn|pn|ps|s[^aeiou]).*");return(o>1?o>2?"le ":v?"l'":"la ":o>0?v||b?"gli ":"i ":v?"l'":b?"lo ":"il ")+a;}
</code>```

Takes your string and an int based on the following mapping:

```<code>0: Masculine Singular
1: Masculine Plural
2: Feminine Singular
3: Feminine Plural
</code>```

Returns a string with the result.

Ungolfed with test cases and with no ternary operators (for real now):

```<code>class Test {

    public static String f(String a, int o) {
        boolean v = a.matches("^([aeou]|i[^aeiou]).*");
        boolean b = a.matches("^([ixz]|gn|pn|ps|s[^aeiou]).*");
        String r;
        if(o > 1)
            if(o > 2)
                r = "le ";
            else
                if(v)
                    r = "l'";
                else
                    r = "la ";
        else
            if(o > 0)
                if(v || b)
                    r = "gli ";
                else
                    r = "i ";
            else
                if(v)
                    r = "l'";
                else if(b)
                    r = "lo ";
                else
                    r = "il ";
        return r + a;
    }

    public static void main(String[] args) {
        System.out.println(f("macchina", 2));
        System.out.println(f("zio", 0));
        System.out.println(f("libri", 1));
        System.out.println(f("ieri", 0));
        System.out.println(f("aquile", 3));
        System.out.println(f("spagnoli", 1));
        System.out.println(f("golf", 0));
        System.out.println(f("ombra", 2));
        System.out.println(f("impossibili", 1));
    }
}
</code>```

Uses a little bit of regex magic and acts depending on the two booleans specified. To my surprise, no imports are needed, which helps out with the code size!

Title: I programming puzzles, il code golf

Body:
Java, <s>227</s> <s>208</s> 195 bytes

-13 bytes thanks to Leaky Nun

String f(String a,int o){boolean v=a.matches("^([aeou]|i[^aeiou]).*"),b=a.matches("^([ixz]|gn|pn|ps|s[^aeiou]).*");return(o>1?o>2?"le ":v?"l'":"la ":o>0?v||b?"gli ":"i ":v?"l'":b?"lo ":"il ")+a;}

Takes your string and an int based on the following mapping:

0: Masculine Singular
1: Masculine Plural
2: Feminine Singular
3: Feminine Plural

Returns a string with the result.

Ungolfed with test cases and with no ternary operators (for real now):

class Test {

    public static String f(String a, int o) {
        boolean v = a.matches("^([aeou]|i[^aeiou]).*");
        boolean b = a.matches("^([ixz]|gn|pn|ps|s[^aeiou]).*");
        String r;
        if(o > 1)
            if(o > 2)
                r = "le ";
            else
                if(v)
                    r = "l'";
                else
                    r = "la ";
        else
            if(o > 0)
                if(v || b)
                    r = "gli ";
                else
                    r = "i ";
            else
                if(v)
                    r = "l'";
                else if(b)
                    r = "lo ";
                else
                    r = "il ";
        return r + a;
    }

    public static void main(String[] args) {
        System.out.println(f("macchina", 2));
        System.out.println(f("zio", 0));
        System.out.println(f("libri", 1));
        System.out.println(f("ieri", 0));
        System.out.println(f("aquile", 3));
        System.out.println(f("spagnoli", 1));
        System.out.println(f("golf", 0));
        System.out.println(f("ombra", 2));
        System.out.println(f("impossibili", 1));
    }
}

Uses a little bit of regex magic and acts depending on the two booleans specified. To my surprise, no imports are needed, which helps out with the code size!


问:
Simple cat program
One of the most common standard tasks (especially when showcasing esoteric programming languages) is to implement a "cat program": read all of STDIN and print it to STDOUT. While this is named after the Unix shell utility cat it is of course much less powerful than the real thing, which is normally used to print (and concatenate) several files read from disc.

Task

You should write a full program which reads the contents of the standard input stream and writes them verbatim to the standard output stream. If and only if your language does not support standard input and/or output streams (as understood in most languages), you may instead take these terms to mean their closest equivalent in your language (e.g. JavaScript's prompt and alert). These are the only admissible forms of I/O, as any other interface would largely change the nature of the task and make answers much less comparable.

The output should contain exactly the input and nothing else. The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation. This also applies to trailing newlines. If the input does not contain a trailing newline, the output shouldn't include one either! (The only exception being if your language absolutely always prints a trailing newline after execution.)

Output to the standard error stream is ignored, so long as the standard output stream contains the expected output. In particular, this means your program can terminate with an error upon hitting the end of the stream (EOF), provided that doesn't pollute the standard output stream. If you do this, I encourage you to add an error-free version to your answer as well (for reference).

As this is intended as a challenge within each language and not between languages, there are a few language specific rules:

If it is at all possible in your language to distinguish null bytes in the standard input stream from the EOF, your program must support null bytes like any other bytes (that is, they have to be written to the standard output stream as well).

If it is at all possible in your language to support an arbitrary infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case. As an example yes | tr -d \\n | ./my_cat should print an infinite stream of ys. It is up to you how often you print and flush the standard output stream, but it must be guaranteed to happen after a finite amount of time, regardless of the stream (this means, in particular, that you cannot wait for a specific character like a linefeed before printing).

Please add a note to your answer about the exact behaviour regarding null-bytes, infinite streams, and extraneous output.

Additional rules

This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.

Submissions in most languages will be scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.

Some languages, like Folders, are a bit tricky to score. If in doubt, please ask on Meta.

Feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.

Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

Also note that languages do have to fulfil our usual criteria for programming languages.

If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

Unless they have been overruled earlier, all standard code-golf rules apply, including the http://meta.codegolf.stackexchange.com/q/1061.

As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalogue as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code.

Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
Sesos, 1 byte

```<code>Y
</code>```

This program handles both infinite streams and null bytes.

Try it online! Check Debug to see the generated binary code.

How it works

The binary file above has been generated by assembling the following SASM code.

set mask ; Switch to unsigned 8-bit cells.

         ; (implicit jmp)
         ;     Set an entry marker and jump to the jne instruction.
    put  ; Print the byte in the current cell to STDOUT.
jnz      ; (implicitly promoted to jne)
         ;     Read a byte from STDIN and save it in the current cell.
         ;     If EOF has not been hit, jump to the previous instruction.
```

Title: Simple cat program

Body:
Sesos, 1 byte

Y

This program handles both infinite streams and null bytes.

Try it online! Check Debug to see the generated binary code.

How it works

The binary file above has been generated by assembling the following SASM code.

set mask ; Switch to unsigned 8-bit cells.

         ; (implicit jmp)
         ;     Set an entry marker and jump to the jne instruction.
    put  ; Print the byte in the current cell to STDOUT.
jnz      ; (implicitly promoted to jne)
         ;     Read a byte from STDIN and save it in the current cell.
         ;     If EOF has not been hit, jump to the previous instruction.


答:
Java 8, 143 bytes

```<code>import java.time.*;interface A{static void main(String[]a){System.out.format("%03.0f",LocalTime.now(ZoneId.of("UT+1")).toSecondOfDay()/86.4);}}
</code>```

this uses Java 8's java.time package to get current time, convert it to UTC+1, and then get the number of seconds. At the end it divides by the number of 1000s of seconds in a day, which turns out to be 86.4.

Funny how the function that actually calculates the time is only about a third of the overall program size.

Title: Calculate Swatch Internet Time

Body:
Output the current time of day as Swatch Internet Time.

Specifically, output a three-digit (zero-padded) number of ".beats" (1000ths of a day) which represent the current time of day in the Swatch Internet Time time zone of UTC+01:00 ("Biel Meantime").

For example, if the current time in UTC is 23:47, then it is 00:47 in UTC+1 ("Biel Meantime"), and the output would be 032.

Examples:

```<code>UTC Current Time  ->  SIT Output
23:47             ->  032
23:00             ->  000
11:00             ->  500
14:37             ->  651
</code>```

The program should produce this output then immediately exit.

Output is to standard output (or equivalent). Must be a complete, runnable program, not a function. The program takes no input; it outputs the current time.

Body:
Java 8, 143 bytes

import java.time.*;interface A{static void main(String[]a){System.out.format("%03.0f",LocalTime.now(ZoneId.of("UT+1")).toSecondOfDay()/86.4);}}

this uses Java 8's java.time package to get current time, convert it to UTC+1, and then get the number of seconds. At the end it divides by the number of 1000s of seconds in a day, which turns out to be 86.4.

Funny how the function that actually calculates the time is only about a third of the overall program size.


Title: Directory calculation

Body:
Python, 142 137 bytes

def p(a,n,r=[],S="/"):
 for s in[s for s in((n[:1]!=S)*a+S+n).split(S)if"."!=s and s]:e=s!="..";r=[s]*e+r[1-e:]
 return S+S.join(r[::-1])


答:
Python, 53 bytes

```<code>from os.path import*;p=lambda a,n:normpath(join(a,n))
</code>```

Title: Directory calculation

Body:
Python, 53 bytes

from os.path import*;p=lambda a,n:normpath(join(a,n))


问:
Calculate A190810
Your task is pretty simple, calculate the n-th element of A190810.

Elements of A190810 are calculated according to these rules:

The first element is 1

The sequence is increasing

If x occurs in the sequence, then 2x+1 and 3x-1 also do

You can use 1-based or 0-based indexing, but if you use 0-based indexing, please say it in the answer.

Test cases

```<code>a(1) = 1
a(2) = 2
a(3) = 3
a(4) = 5
a(5) = 7
a(10) = 17
a(20) = 50
a(30) = 95
a(55) = 255
</code>```

Since this is code-golf, the shortest answer in bytes wins!

答:
Retina, 48 bytes

```<code>.+
$*
+1`^(((!*)!(!|\3)(?=\3!1))*!)1|\b
!$1
-2`.
</code>```

Try it online!

Inspired by nimi's answer I thought I'd try a different approach for Retina, making use of the regex engine's backtracking to figure out if any given (unary) number is in the sequence or not. It turns out this can be determined with a 27 byte regex, but making use of it costs a few more, but it still ends up shorter than the generative approach.

Here's an alternative 48-byte solution:

```<code>.+
$*
{`1\b
1!
}T`1``1((!*)!(!|\2)(?=!\2$))*!$
!
</code>```

And using unary I/O we can do 42 bytes, but I'm trying to avoid that and the other Retina answer uses decimal as well:

```<code>1\b
1!
}T`1``1((!*)!(!|\2)(?=!\2$))*!$
!
1
</code>```

Title: Calculate A190810

Body:
Retina, 48 bytes

.+
$*
+1`^(((!*)!(!|\3)(?=\3!1))*!)1|\b
!$1
-2`.

Try it online!

Inspired by nimi's answer I thought I'd try a different approach for Retina, making use of the regex engine's backtracking to figure out if any given (unary) number is in the sequence or not. It turns out this can be determined with a 27 byte regex, but making use of it costs a few more, but it still ends up shorter than the generative approach.

Here's an alternative 48-byte solution:

.+
$*
{`1\b
1!
}T`1``1((!*)!(!|\2)(?=!\2$))*!$
!

And using unary I/O we can do 42 bytes, but I'm trying to avoid that and the other Retina answer uses decimal as well:

1\b
1!
}T`1``1((!*)!(!|\2)(?=!\2$))*!$
!
1


Title: Calculate Swatch Internet Time

Body:
q/k (21 bytes)

7h$1e3*(.z.n+0D01)%1D


问:
Draw the national flag of Iceland
This year's UEFA Euro 2016 is over and besides a couple of negative headlines there has been a very positive surprise as well – the Iceland national football team. Let's draw their national flag.

Input

Well, obviously this challenge has no input.

Output

Draw the flag of Iceland in any applicable visual format of at least 100 x 72 pixels or 25 x 18 characters.

Save the output to a file or present it instantly – example formats are: images like png, jpg etc., vector graphics, draw on HTML canvas or even use non-whitespace characters for visualization.

Use these colors: blue: #0048e0, white: #ffffff and red: #d72828.

If your language doesn't support specific color values, use the standard values for red, blue and white from the ANSI color codes.

Draw the flag with the correct proportions, as shown in the figure below:

Boilerplate

You can write a program or a function. If it is an anonymous function, please include an example of how to invoke it.

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

Standard loopholes are disallowed.

Leaderboard

var QUESTION_ID = 85141; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 41859; // This should be the user ID of the challenge author.
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;function answersUrl(index) {return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;}function commentUrl(index, answers) {return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;}function getAnswers() {jQuery.ajax({url: answersUrl(answer_page++),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {answers.push.apply(answers, data.items);answers_hash = [];answer_ids = [];data.items.forEach(function(a) {a.comments = [];var id = +a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id] = a;});if (!data.has_more) more_answers = false;comment_page = 1;getComments();}});}function getComments() {jQuery.ajax({url: commentUrl(comment_page++, answer_ids),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {data.items.forEach(function(c) {if (c.owner.user_id === OVERRIDE_USER)answers_hash[c.post_id].comments.push(c);});if (data.has_more) getComments();else if (more_answers) getAnswers();else process();}});}getAnswers();var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG = /^Override\s*header:\s*/i;function getAuthorName(a) {return a.owner.display_name;}function process() {var valid = [];answers.forEach(function(a) {var body = a.body;a.comments.forEach(function(c) {if(OVERRIDE_REG.test(c.body))body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';});var match = body.match(SCORE_REG);if (match)valid.push({user: getAuthorName(a),size: +match[2],language: match[1],link: a.share_link,});});valid.sort(function (a, b) {var aB = a.size,bB = b.size;return aB - bB});var languages = {};var place = 1;var lastSize = null;var lastPlace = 1;valid.forEach(function (a) {if (a.size != lastSize)lastPlace = place;lastSize = a.size;++place;var answer = jQuery("#answer-template").html();answer = answer.replace("{{PLACE}}", lastPlace + ".").replace("{{NAME}}", a.user).replace("{{LANGUAGE}}", a.language).replace("{{SIZE}}", a.size).replace("{{LINK}}", a.link);answer = jQuery(answer);jQuery("#answers").append(answer);var lang = a.language;if (! /<a/.test(lang)) lang = '' + lang + '';lang = jQuery(lang).text().toLowerCase();languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang};});var langs = [];for (var lang in languages)if (languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function (a, b) {if (a.uniq > b.uniq) return 1;if (a.uniq < b.uniq) return -1;return 0;});for (var i = 0; i < langs.length; ++i){var language = jQuery("#language-template").html();var lang = langs[i];language = language.replace("{{LANGUAGE}}", lang.lang).replace("{{NAME}}", lang.user).replace("{{SIZE}}", lang.size).replace("{{LINK}}", lang.link);language = jQuery(language);jQuery("#languages").append(language);}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}#answer-list {padding: 10px;width: 290px;float: left;}#language-list {padding: 10px;width: 290px;float: left;}table thead {font-weight: bold;}table td {padding: 5px;}</code>```

<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/Sites/codegolf/all.css?v=617d0685f6f3">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}

{{LANGUAGE}}	{{NAME}}	{{SIZE}}

```

If you can't find your answer, format your language and byte count as explained in the Leaderboard's "Info Section".

This challenge is inspired by Draw the national flag of france.

答:
Lua + LÖVE, 212 characters

f="fill"l=love
g=l.graphics
c=g.setColor
r=g.rectangle
l.window.setMode(100,72)function
l.draw()g.setBackgroundColor(0,72,224)c(-1,-1,-1)r(f,28,0,16,72)r(f,0,28,100,16)c(215,40,40)r(f,32,0,8,72)r(f,0,32,100,8)end
```

Sample output:

Title: Draw the national flag of Iceland

Body:
Lua + LÖVE, 212 characters

f="fill"l=love
g=l.graphics
c=g.setColor
r=g.rectangle
l.window.setMode(100,72)function
l.draw()g.setBackgroundColor(0,72,224)c(-1,-1,-1)r(f,28,0,16,72)r(f,0,28,100,16)c(215,40,40)r(f,32,0,8,72)r(f,0,32,100,8)end

Sample output:


问:
Remove duplicated & switched case

Goal

The goal of this challenge is: given a string as input, remove duplicate pairs of letters, if the second item in the pair is of opposite capitalization. (i.e. uppercase becomes lowercase and vice-versa).

Pairs should be replaced from left to right. For example, aAa should become aa and not aA.

Inputs & outputs:

```<code>Input:         Output:
bBaAdD         bad
NniIcCeE       Nice
Tt eE Ss tT    T e S t
sS Ee tT       s E t
1!1!1sStT!     1!1!1st!
nN00bB         n00b
(eE.gG.)       (e.g.)
Hh3lL|@!       H3l|@!
Aaa            Aa
aaaaa          aaaaa
aaAaa          aaaa
</code>```

The input consists of printable ASCII symbols.

You shouldn't remove duplicated digits or other non-letter characters.

Acknowledgement

This challenge is the opposite of @nicael 's "Duplicate & switch case". Can you reverse it?

Thank you for all contributors from the sandbox!

Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
Retina, 18 bytes

```<code>(.)(?!\1)(?i)\1
$1
</code>```

Try it online!

Explanation

This a single (and fairly simple) substitution which matches the relevant pairs and replaces them with only the first character. The pairs are matched by activating case-insensitivity halfway through the pattern:

```<code>(.)     # Match a character and capture it into group 1.
(?!\1)  # Use a negative lookahead to ensure that the next character *isn't* the same
        # as the character we just captured. This doesn't advance the position of the
        # regex engine's "cursor".
(?i)    # Now activate case-insensitivity for the remainder of the pattern.
\1      # Match the second character with a backreference to the first. With the i
        # modifier activated, this will match if the two characters only differ
        # by case.
</code>```

The substitution simply writes back the character we already captured in group 1 anyway.

Title: Remove duplicated & switched case

Body:
Retina, 18 bytes

(.)(?!\1)(?i)\1
$1

Try it online!

Explanation

This a single (and fairly simple) substitution which matches the relevant pairs and replaces them with only the first character. The pairs are matched by activating case-insensitivity halfway through the pattern:

(.)     # Match a character and capture it into group 1.
(?!\1)  # Use a negative lookahead to ensure that the next character *isn't* the same
        # as the character we just captured. This doesn't advance the position of the
        # regex engine's "cursor".
(?i)    # Now activate case-insensitivity for the remainder of the pattern.
\1      # Match the second character with a backreference to the first. With the i
        # modifier activated, this will match if the two characters only differ
        # by case.

The substitution simply writes back the character we already captured in group 1 anyway.


答:
Perl, <s>40</s> 24+1=25 bytes

Use the same regex as Martin.

Use the -p flag

```<code>s/(.)(?!\1)(?i)\1/\1/g
</code>```

Test it on ideone

Title: Remove duplicated & switched case

Body:
Goal

The goal of this challenge is: given a string as input, remove duplicate pairs of letters, if the second item in the pair is of opposite capitalization. (i.e. uppercase becomes lowercase and vice-versa).

Pairs should be replaced from left to right. For example, aAa should become aa and not aA.

Inputs & outputs:

```<code>Input:         Output:
bBaAdD         bad
NniIcCeE       Nice
Tt eE Ss tT    T e S t
sS Ee tT       s E t
1!1!1sStT!     1!1!1st!
nN00bB         n00b
(eE.gG.)       (e.g.)
Hh3lL|@!       H3l|@!
Aaa            Aa
aaaaa          aaaaa
aaAaa          aaaa
</code>```

The input consists of printable ASCII symbols.

You shouldn't remove duplicated digits or other non-letter characters.

Acknowledgement

This challenge is the opposite of @nicael 's "Duplicate & switch case". Can you reverse it?

Thank you for all contributors from the sandbox!

Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
Perl, <s>40</s> 24+1=25 bytes

Use the same regex as Martin.

Use the -p flag

s/(.)(?!\1)(?i)\1/\1/g

Test it on ideone


答:
C#, <s>87</s> 75 bytes

s=>System.Text.RegularExpressions.Regex.Replace(s,@"(.)(?!\1)(?i)\1","$1");
```

<p>With the mighty regex from Martin Ender. C# lambda where the input and the output are <code>string</code>.</p>

<p>12 bytes saved by Martin Ender and TùxCräftîñg.</p>

<hr>

<h1>C#, <s>141</s> 134 bytes</h1>

<pre class="lang-csharp prettyprint-override"><code>s=>{var r="";for(int i=0,l=s.Length;i<l;i++){var c=s[i];r+=c;if(char.IsLetter(c)&i+1<l&&(c|32)==(s[i+1]|32)&c!=s[i+1])i++;}return r;};
</code>```

C# lambda where the input and the output are string. The algorithm is naive. This is the one I use as reference.

Code:

s=>{
    var r = "";
    for(int i = 0; i < s.Length; i++)
    {
        r+=s[i];
        if (char.IsLetter(s[i]) & i+1 < s.Length)
            if (char.ToLower(s[i])==char.ToLower(s[i+1])
              & char.IsLower(s[i])!=char.IsLower(s[i+1]))
                i += 1;
    }
    return r;
};
```

7 bytes thanks to Martin Ender!

Try them online!

Title: Remove duplicated & switched case

Body:
C#, <s>87</s> 75 bytes

s=>System.Text.RegularExpressions.Regex.Replace(s,@"(.)(?!\1)(?i)\1","$1");

With the mighty regex from Martin Ender. C# lambda where the input and the output are string.

12 bytes saved by Martin Ender and TùxCräftîñg.

C#, <s>141</s> 134 bytes

s=>{var r="";for(int i=0,l=s.Length;i<l;i++){var c=s[i];r+=c;if(char.IsLetter(c)&i+1<l&&(c|32)==(s[i+1]|32)&c!=s[i+1])i++;}return r;};

C# lambda where the input and the output are string. The algorithm is naive. This is the one I use as reference.

Code:

s=>{
    var r = "";
    for(int i = 0; i < s.Length; i++)
    {
        r+=s[i];
        if (char.IsLetter(s[i]) & i+1 < s.Length)
            if (char.ToLower(s[i])==char.ToLower(s[i+1])
              & char.IsLower(s[i])!=char.IsLower(s[i+1]))
                i += 1;
    }
    return r;
};

7 bytes thanks to Martin Ender!

Try them online!


答:
Brachylog, 44 bytes

```<code>.v|.l1|hA,?bhB(@uA;A@uB),?bb&~b.hA|?b&~b.h~h?
</code>```

Brachylog has no regular expressions.

Explanation

```<code>    .v          Input = Output = ""
|               OR
    .l1         Input = Output = string of one character
|               OR
    hA,         A is the first char or the Input
    ?bhB        B is the second char of the Input
    (
        @uA         B uppercased is A
        ;           OR
        A@uB        A uppercased is B
    ),
    ?bb&        Call recursively on Input minus the first two elements
    ~b.hA       Output is the result of that call with A appended before it
|               OR
    b&          Call recursively on Input minus the first element
    ~b.h~h?     Output is the result of that call with the first element of Input appended
                  before it
</code>```

Title: Remove duplicated & switched case

Body:
Brachylog, 44 bytes

.v|.l1|hA,?bhB(@uA;A@uB),?bb&~b.hA|?b&~b.h~h?

Brachylog has no regular expressions.

Explanation

    .v          Input = Output = ""
|               OR
    .l1         Input = Output = string of one character
|               OR
    hA,         A is the first char or the Input
    ?bhB        B is the second char of the Input
    (
        @uA         B uppercased is A
        ;           OR
        A@uB        A uppercased is B
    ),
    ?bb&        Call recursively on Input minus the first two elements
    ~b.hA       Output is the result of that call with A appended before it
|               OR
    b&          Call recursively on Input minus the first element
    ~b.h~h?     Output is the result of that call with the first element of Input appended
                  before it


答:
Pyth, <s>24</s> 20 bytes

4 bytes thanks to @Jakube.

This still uses regex, but just for tokenizing.

```<code>shM:zj\|+s_BVGrG1\.1
</code>```

Test suite.

```<code>shM:zj\|+s_BVGrG1\.1   input as z
         s_BVGrG1      generate ['aA', 'Aa', 'bB', 'Bb', ..., 'zZ', 'Zz']
        +        \.    add "." to the back of the array
     j\|               insert "|" between every element of the array,
                       forming a new long string, which will be our
                       tokenizer: "aA|Aa|bB|Bb|cC|Cc|...|yY|Yy|zZ|Zz|."
                       the "." at the end is to capture the remaining characters
  :z               1   return all matches of z against that regex
                       this is effectively a tokenizer
 hM                    take the first character of each token
s                      join all the transformed tokens together, and then
                       implicitly print to STDOUT.
</code>```

24-byte version here.

Title: Remove duplicated & switched case

Body:
Pyth, <s>24</s> 20 bytes

4 bytes thanks to @Jakube.

This still uses regex, but just for tokenizing.

shM:zj\|+s_BVGrG1\.1

Test suite.

shM:zj\|+s_BVGrG1\.1   input as z
         s_BVGrG1      generate ['aA', 'Aa', 'bB', 'Bb', ..., 'zZ', 'Zz']
        +        \.    add "." to the back of the array
     j\|               insert "|" between every element of the array,
                       forming a new long string, which will be our
                       tokenizer: "aA|Aa|bB|Bb|cC|Cc|...|yY|Yy|zZ|Zz|."
                       the "." at the end is to capture the remaining characters
  :z               1   return all matches of z against that regex
                       this is effectively a tokenizer
 hM                    take the first character of each token
s                      join all the transformed tokens together, and then
                       implicitly print to STDOUT.

24-byte version here.


问:
Compute modular inverse
Given two positive numbers \$x\$ and \$n\$ with \$x<2^n\$, write the shortest possible function to compute \$x^{-1} \mod 2^n\$.  In other words, find \$y\$ such that \$xy=1 \mod 2^n\$.

Your function must complete in a reasonable time for at least \$n=64\$, so exhaustive search will not work.

If the inverse does not exist, you must indicate that to the caller somehow (throw an exception, return a sentinel value, etc).

If you're wondering where to start, try the Extended Euclidean Algorithm.

答:
Python, 29 bytes

lambda x,n:pow(x,2**n-1,2**n)
```

This returns 0 for even x. It uses Euler’s theorem, with the observation that 2^n − 1 is divisible by 2^(n − 1) − 1, via Python’s builtin fast modular exponentiation. This is plenty fast enough for n up to 7000 or so, where it starts taking more than about a second.

Title: Compute modular inverse

Body:
Python, 29 bytes

lambda x,n:pow(x,2**n-1,2**n)

This returns 0 for even x. It uses Euler’s theorem, with the observation that 2^n − 1 is divisible by 2^(n − 1) − 1, via Python’s builtin fast modular exponentiation. This is plenty fast enough for n up to 7000 or so, where it starts taking more than about a second.


答:
Haskell, 42 bytes

_!1=1
x!n|r<-x!div(n+1)2=(2-r*x)*r`mod`2^n
```

Using an algorithm based on Hensel’s lemma that doubles the number of digits in every iteration, this runs in under a second for n up to about 30 million!

Title: Compute modular inverse

Body:
Given two positive numbers \$x\$ and \$n\$ with \$x<2^n\$, write the shortest possible function to compute \$x^{-1} \mod 2^n\$.  In other words, find \$y\$ such that \$xy=1 \mod 2^n\$.

Your function must complete in a reasonable time for at least \$n=64\$, so exhaustive search will not work.

If the inverse does not exist, you must indicate that to the caller somehow (throw an exception, return a sentinel value, etc).

If you're wondering where to start, try the Extended Euclidean Algorithm.

Body:
Haskell, 42 bytes

_!1=1
x!n|r<-x!div(n+1)2=(2-r*x)*r`mod`2^n

Using an algorithm based on Hensel’s lemma that doubles the number of digits in every iteration, this runs in under a second for n up to about 30 million!


答:
GLSL + shadertoy, <s>193</s> <s>190</s> <s>187</s> 179 bytes

void mainImage(out vec4 f,vec2 p){vec2 a=abs(p/iResolution.xy*vec2(25,18)-9.);int c=int(min(a.x,min(a.y,2.)));f=vec4(c==0?vec3(215,40,40):c==1?vec3(255):vec3(0,72,224),255)/255.;}

The aspect ratio will be correct as long as the window/screen size is 25:18.

Can be tested at https://www.shadertoy.com/new

I wanted to use an array lookup in the last statement, but it seems I can't really make an array of vectors :/

Additional thanks going to @GáborFekete for tips for further golfing.
Screenshot:

Title: Draw the national flag of Iceland

Body:
This year's UEFA Euro 2016 is over and besides a couple of negative headlines there has been a very positive surprise as well – the Iceland national football team. Let's draw their national flag.

Input

Well, obviously this challenge has no input.

Output

Draw the flag of Iceland in any applicable visual format of at least 100 x 72 pixels or 25 x 18 characters.

Save the output to a file or present it instantly – example formats are: images like png, jpg etc., vector graphics, draw on HTML canvas or even use non-whitespace characters for visualization.

Use these colors: blue: #0048e0, white: #ffffff and red: #d72828.

If your language doesn't support specific color values, use the standard values for red, blue and white from the ANSI color codes.

Draw the flag with the correct proportions, as shown in the figure below:

Boilerplate

You can write a program or a function. If it is an anonymous function, please include an example of how to invoke it.

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

Standard loopholes are disallowed.

Leaderboard

var QUESTION_ID = 85141; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 41859; // This should be the user ID of the challenge author.
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;function answersUrl(index) {return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;}function commentUrl(index, answers) {return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;}function getAnswers() {jQuery.ajax({url: answersUrl(answer_page++),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {answers.push.apply(answers, data.items);answers_hash = [];answer_ids = [];data.items.forEach(function(a) {a.comments = [];var id = +a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id] = a;});if (!data.has_more) more_answers = false;comment_page = 1;getComments();}});}function getComments() {jQuery.ajax({url: commentUrl(comment_page++, answer_ids),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {data.items.forEach(function(c) {if (c.owner.user_id === OVERRIDE_USER)answers_hash[c.post_id].comments.push(c);});if (data.has_more) getComments();else if (more_answers) getAnswers();else process();}});}getAnswers();var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG = /^Override\s*header:\s*/i;function getAuthorName(a) {return a.owner.display_name;}function process() {var valid = [];answers.forEach(function(a) {var body = a.body;a.comments.forEach(function(c) {if(OVERRIDE_REG.test(c.body))body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';});var match = body.match(SCORE_REG);if (match)valid.push({user: getAuthorName(a),size: +match[2],language: match[1],link: a.share_link,});});valid.sort(function (a, b) {var aB = a.size,bB = b.size;return aB - bB});var languages = {};var place = 1;var lastSize = null;var lastPlace = 1;valid.forEach(function (a) {if (a.size != lastSize)lastPlace = place;lastSize = a.size;++place;var answer = jQuery("#answer-template").html();answer = answer.replace("{{PLACE}}", lastPlace + ".").replace("{{NAME}}", a.user).replace("{{LANGUAGE}}", a.language).replace("{{SIZE}}", a.size).replace("{{LINK}}", a.link);answer = jQuery(answer);jQuery("#answers").append(answer);var lang = a.language;if (! /<a/.test(lang)) lang = '' + lang + '';lang = jQuery(lang).text().toLowerCase();languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang};});var langs = [];for (var lang in languages)if (languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function (a, b) {if (a.uniq > b.uniq) return 1;if (a.uniq < b.uniq) return -1;return 0;});for (var i = 0; i < langs.length; ++i){var language = jQuery("#language-template").html();var lang = langs[i];language = language.replace("{{LANGUAGE}}", lang.lang).replace("{{NAME}}", lang.user).replace("{{SIZE}}", lang.size).replace("{{LINK}}", lang.link);language = jQuery(language);jQuery("#languages").append(language);}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}#answer-list {padding: 10px;width: 290px;float: left;}#language-list {padding: 10px;width: 290px;float: left;}table thead {font-weight: bold;}table td {padding: 5px;}</code>```

<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/Sites/codegolf/all.css?v=617d0685f6f3">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}

{{LANGUAGE}}	{{NAME}}	{{SIZE}}

```

If you can't find your answer, format your language and byte count as explained in the Leaderboard's "Info Section".

This challenge is inspired by Draw the national flag of france.


答:
MATL, 21 bytes

```<code>"Kk@k=K@XK=>?4XKx}K&h
</code>```

Try it online!. Or verify all test cases.

Explanation

This processes each character in a loop. Each iteration compares the current character with the previous character. The latter is stored in clipboard K, which is initiallized to 4 by default.

The current character is compared with the previous one twice: first case-insensitively and then case sensitively. The current character should be deleted if and only if the first comparison was true and the second was false. Note that, since clipboard K initially contains 4, the first character will always be kept.

If the current character is deleted clipboard K should be reset (so the next character will be kept); otherwise it should be updated with the current character.

```<code>"            % Take input string implicitly. For each char from this string:
  K          %   Push previous char, initiallized to number 4
  k          %   Convert to lower case. For numbers it rounds down
  @          %   Push current char
  k          %   Convert to lower case.
  =          %   True if current and previous chars are (case-insensitively) equal
  K          %   Push previous char
  @          %   Push current char
  XK         %   Update clipboard K with current char. This doesn't affect the stack
  =          %   True if current and previous chars are (case-sensitively) equal
  >?         %   If first comparison was true and second was false
    4XKx     %     Reset clipboard K to 4
  }          %   Else
    K        %     Push previous char
    &h       %     Concatenate horizontally to gradually build the output string
</code>```

Title: Remove duplicated & switched case

Body:
MATL, 21 bytes

"Kk@k=K@XK=>?4XKx}K&h

Try it online!. Or verify all test cases.

Explanation

This processes each character in a loop. Each iteration compares the current character with the previous character. The latter is stored in clipboard K, which is initiallized to 4 by default.

The current character is compared with the previous one twice: first case-insensitively and then case sensitively. The current character should be deleted if and only if the first comparison was true and the second was false. Note that, since clipboard K initially contains 4, the first character will always be kept.

If the current character is deleted clipboard K should be reset (so the next character will be kept); otherwise it should be updated with the current character.

"            % Take input string implicitly. For each char from this string:
  K          %   Push previous char, initiallized to number 4
  k          %   Convert to lower case. For numbers it rounds down
  @          %   Push current char
  k          %   Convert to lower case.
  =          %   True if current and previous chars are (case-insensitively) equal
  K          %   Push previous char
  @          %   Push current char
  XK         %   Update clipboard K with current char. This doesn't affect the stack
  =          %   True if current and previous chars are (case-sensitively) equal
  >?         %   If first comparison was true and second was false
    4XKx     %     Reset clipboard K to 4
  }          %   Else
    K        %     Push previous char
    &h       %     Concatenate horizontally to gradually build the output string


答:
C, <s>129</s> <s>127</s> <s>125</s> <s>107</s> <s>106</s> <s>105</s> <s>93</s> <s>92</s> <s>90</s> <s>88</s> <s>85</s> <s>78</s> 73 bytes

c;d;f(char*s){for(;c=*s;s+=isalpha(putchar(c))*d*!((d^=c)&95)&&d)d=*++s;}
```
<p>A C port of my C# answer. My C may be a bit bad. I don't use the language a lot anymore. Any help is welcome!</p>
<ul>
<li>1 byte saved thanks to Lowjacker's trick: <code>a!=b</code> = <code>a^b</code></li>
<li>1 byte saved thanks to Walpen's trick: <code>a&&b</code> = <code>a*b</code></li>
<li>12 bytes saved by Lynn's trick and inspired here by TùxCräftîñg</li>
<li>1 byte saved thanks to Joey Adams's trick and inspired here by orlp: Moving variable to global</li>
<li>2 bytes saved by SEJPM by resolving my <code>(c|32)==(d|32)</code> bitwise problem</li>
<li>5 bytes saved by Pietu1998</li>
<li>5 bytes saved by ceilingcat</li>
</ul>
<p>Code:</p>
<pre class="lang-c prettyprint-override"><code>c;d;f(char*s) {
    for(;putchar(c=*s);)
        s+=isalpha(c)*(d=*++s)&&(!((c^d)&95)&&c^d);
}
</code>```

Try it online!

Title: Remove duplicated & switched case

Body:
C, <s>129</s> <s>127</s> <s>125</s> <s>107</s> <s>106</s> <s>105</s> <s>93</s> <s>92</s> <s>90</s> <s>88</s> <s>85</s> <s>78</s> 73 bytes

c;d;f(char*s){for(;c=*s;s+=isalpha(putchar(c))*d*!((d^=c)&95)&&d)d=*++s;}

A C port of my C# answer. My C may be a bit bad. I don't use the language a lot anymore. Any help is welcome!

1 byte saved thanks to Lowjacker's trick: a!=b = a^b

1 byte saved thanks to Walpen's trick: a&&b = a*b

12 bytes saved by Lynn's trick and inspired here by TùxCräftîñg

1 byte saved thanks to Joey Adams's trick and inspired here by orlp: Moving variable to global

2 bytes saved by SEJPM by resolving my (c|32)==(d|32) bitwise problem

5 bytes saved by Pietu1998

5 bytes saved by ceilingcat

Code:

c;d;f(char*s) {
    for(;putchar(c=*s);)
        s+=isalpha(c)*(d=*++s)&&(!((c^d)&95)&&c^d);
}

Try it online!