text
stringlengths 180
608k
|
---|
[Question]
[
The twelve-balls problem is a famous problem where you are given twelve balls, one of which is a different weight, but you don't know whether it is heavier or lighter than the other balls. Using only three weighings of a two-sided scale, it is possible to find the differently weighted ball, *and* determine whether it is heavier or lighter.
Your task is to build a program that does the following:
* Accept a number of balls `N` to be compared, from `8` to `100`. (In the traditional problem, `N = 12`.)
* Produce two lists of numbers, representing the balls to be placed on each side of the balance. An equal number of balls must be placed on each side.
* Accept an input signifying whether the left side of the scale is heavier, the right side is heavier, or the two sides are equal (this can be represented any way you want to: e.g. `-1` for left, `0` for equal, `1` for right, or `1` for left, `2` for right, and `3` for equal), and in response, either produce another pair of lists of balls to be weighed, or a guess as to which ball is the different one and whether it is heavier or lighter.
Your score is the sum of the *maximum* number of weighings for each value of `N` from `8` to `100` that it took to figure out the right answer for `N` balls using your algorithm (each case of "ball `x` is heavier/lighter" must be tested). Lowest score wins.
For example, if for `N = 12`, your algorithm managed to get 3 weighings for every case except "ball 8 is heavy" where it took 4 weighings, your score for `N = 12` is 4. If your maximum score was 10 weighings for each `N` from 8 to 100, your final score would be `930`.
Your algorithm must return the correct answer for all possible test cases (for any `N`, there are `2N` possible test cases, which is a total of 10,044). In addition, the source code of your solution may not exceed 51,200 bytes (50 KB) in size.
[Answer]
## Tcl, ~~455~~ 426
```
proc weight n {
set num [expr {int(log($n*2-1)/log(3))+1}]
set len [expr {$n/3}]
set pn 0
set pri {2 5 7 11 13 17 19 23 29 31 37 41 43 59 61 67}
for {set i 0} {$i < $num} {incr i} {
set a {}
while {![llength $a]} {
set a {}
set b {}
set c {}
while {
($n+1)%[lindex $pri $pn]==0
||($n-1)%[lindex $pri $pn]==0
||$n%[lindex $pri $pn]==0} {incr pn; puts $pn}
set cpn [lindex $pri $pn]
for {set j 0} {$j < $len} {incr j} {
set tmp [expr {($j*$cpn)%$n}]
lappend a $tmp
incr tmp 1
if {$tmp in $a} {set a {}; break}
lappend b $tmp
}
incr pn
}
for {set j 0} {$j < $n} {incr j} {
if {$j ni $a && $j ni $b} {lappend c $j}
}
puts "[lsort -integer $a] VS [lsort -integer $b] - Which is havier? -1 = left, 0 = equal, 1 = right"
set idx [expr {[gets stdin] + 1}]
if {$i == 0} {
if {$idx == 1} {
set p1 $c
set p2 $c
} elseif {$idx == 0} {
set p1 $a
set p2 $b
} else {
set p1 $b
set p2 $a
}
} else {
set lists [list $a $c $b]
set p1 [lmap it [lindex $lists $idx] {if {$it ni $p1} continue; set it}]
set p2 [lmap it [lindex $lists 2-$idx] {if {$it ni $p2} continue; set it}]
}
}
if {[llength $p1]} {puts "Result $p1"} {puts "Result $p2"}
}
puts "Number of balls?"
weight [gets stdin]
```
No matter what you choose, the next question is always the same.
[Answer]
# Python - 4929 weighings
A sketch of a trivial, last-place solution:
```
N = input("Enter number of balls: ")
a = 1
b = 2
print a, "|", b
first_result = input("Is left side heavy (1), right side heavy (2), or both equal (3)? ")
while(True):
b += 1
print a, "|", b
result = input("Is left side heavy (1), right side heavy (2), or both equal (3)?")
if result == first_result and result != 3:
# ball 1 is our culprit.
print "Ball 1 is %s." % ("heavier" if first_result == 1 else "lighter")
break
elif result != first_result and result == 3:
# ball 2 is our culprit.
print "Ball 2 is %s." % ("heavier" if first_result == 2 else "lighter")
break
elif result != first_result and first_result == 3:
# ball b is our culprit.
print "Ball %d is %s." % (b, "heavier" if result == 2 else "lighter")
break
```
This solution simply continuously puts the first ball on the left side and a different ball on the right side, until it's found out that either the first ball is of a different weight, or one of the others is.
This takes a maximum of `N-1` weighings for `N` balls (in any case where the last ball is the different one, `N-1` weighings are required), which is 4929 weighings total.
[Answer]
## Tcl, 369
```
proc weight balls {
if {[llength $balls] == 1 || [llength $balls] == 0} {return [lindex $balls 0]}
set len [expr {([llength $balls]+1)/3}]
set a [lrange $balls 0 ${len}-1]
set b [lrange $balls $len [expr {$len*2-1}]]
set c [lrange $balls [expr {$len*2}] end]
puts "$a VS $b (0 = left side is havier, 1 = right side is havier, 2 = equal)"
tailcall weight [lindex [list $a $b $c] [gets stdin]]
}
puts "Number of balls"
for {set i 1} \$i<=[gets stdin] {incr i} {lappend balls $i}
puts [weight $balls]
```
The algorithm is very simple: (try to) split the list in 3 equal parts (last can be different), weight the first 2, and do that again for the selected part (if equal, use the 3rd part)
[Answer]
# JavaScript 1281
```
// Weigh function
function weigh(a,b) {
weigh.count++;
var len = a.length;
if (len !== b.length) {
throw({name:"NotEqual",message:"Can not compare."});
}
var wa, wb;
wa = wb = 0;
for(var i = 0; i < len; i++) {
wa += a[i];
wb += b[i];
}
return (wa === wb) ? 0 : (wa > wb) ? -1 : 1;
}
weigh.count = 0;
function findOddBall(arr) {
var s = [arr];
var isHeavy = true;
var priorR = null;
var left = null;
var right = null;
//console.log(arr);
while(k=s.pop()) {
//console.log('isHeavy:' + isHeavy + ' ' + k.slice(0));
var len = k.length;
if (len === 1) {
if (priorR !== 0) {
return [k[0], isHeavy]
}
var r = priorR = weigh([left[0]],k);
if (r !== 0) {
// we know that the oddball is one of these.. but which one?
// we need to do a final comparison with the right side.
priorR = r;
r = weigh([right[0]],k);
if (r === 0) {
// prior heavy/light
isHeavy = (priorR === -1)?true:false;
return [left[0],isHeavy]
} else if(r === 1) {
return [k[0], true] // heavy
}
return [k[0], false] //light
}
continue;
}
x = (len % 2 === 0) ? len : len-1;
right = k.splice(0,x);
if(k.length !== 0) {
s.push(k); // remainder
}
left = right.splice(0,x/2);
var r = priorR = weigh(left, right);
if (r === 0) {
// We chose a normal side. Test the other side.
isHeavy = !isHeavy;
} else if ((r === -1 && isHeavy)|| (r === 1 && !isHeavy)) {
s.push(right);
s.push(left); // left is heavier / lighter
} else if((r === 1 && isHeavy)|| (r === -1 && !isHeavy)) {
s.push(left);
s.push(right); // right is heavier / lighter
}
}
throw({name:"NotFound",message:"Can not find oddball."});
}
function main() {
var total = 0;
var variations = 0;
var start = 8;
var end = 100;
function test(isHeavy) {
var normal = (isHeavy) ? 0 : 1;
var oddball = (isHeavy) ? 1 : 0;
var score = 0;
var base = [];
for (var i=0; i < start;i++) {
base.push(normal);
}
for (var i=start; i <=end; i++) {
base.push(normal);
var max = 0;
for (var j=0; j<i; j++) { // try each placement
var arr = base.slice(0);
arr[j]=oddball;
variations++;
weigh.count = 0; // reset the scale
var result = findOddBall(arr);
if (result[0] !== oddball || result[1] !== isHeavy) {
console.log(i);
throw({name:"WrongAnswer",message:"Returned wrong answer."});
}
if (weigh.count > max) {
max = weigh.count;
}
//console.log(variations);
}
total+=max;
}
}
test(true);
test(false);
console.log(variations);
console.log(total);
}
main();
```
[Answer]
# Python - ?
```
#recursive weighing method
def weigh(list, heavy):
l=len(list)
if l==1:
return list[0]
list1=list[0::3]
list2=list[1::3]
list3=[]
if len(list1)>len(list2):
list3.append(list1.pop())
print("%s|%s"%(list1,list2))
side=input("(0,1,2) for (neither,left,right) is %s"%heavy)
if side==2:
return weigh(list2, heavy)
if side:
return weigh(list1, heavy)
for i in list[2::3]:
list3.append(i)
return weigh(list3, heavy)
#End Function, begin rest of program
#This part of the program is long because I need to determine whether the odd ball
#is heavy or light
list=range(input("Number of Balls: "))
#split the list into 3
list1=list[0::3]
list2=list[1::3]
list3=list[2::3]
#make list3 the odd man out, if there is one
if len(list1)>len(list2):
list1,list3=list3,list1
print("%s|%s"%(list1,list2))
side=input("(0,1,2) for (neither,left,right) is heavier")
#if side==0
if not side:
heavy="heavier"
if len(list3)<len(list1):
list3.append(list2.pop())
elif len(list3)>len(list1):
list2.append(list3.pop())
print("%s|%s"%(list1,list3))
side2=input("(0,1,2) for (neither,left,right) is heavier")
if side2==1:
heavy="lighter"
print("%s: %s"%(weigh(list3, heavy),heavy))
else:
if side==2:
list1,list2=list2,list1
if len(list3)!=len(list2):
if len(list3)<len(list1):
list3.append(list1.pop())
if len(list3)>len(list2):
list1.append(list3.pop())
print("%s|%s"%(list2,list3))
side2=input("(0,1,2) for (neither,left,right) is heavier")
if not side2:
print("%s: heavier"%weigh(list1, "heavier"))
else:
possibleAns = list3.pop()
list3.append(list1.pop())
print("%s|%s"%(list2,list3))
side3=input("(0,1,2) for (neither,left,right) is heavier")
if not side3:
print("%s: heavier"%possibleAns)
else:
print("%s: lighter"%weigh(list2,"lighter"))
else:
print("%s|%s"%(list2,list3))
side2=input("(0,1,2) for (neither,left,right) is heavier")
if not side2:
print("%s: heavier"%weigh(list1,"heavier"))
else:
print("%s: lighter"%weigh(list2,"lighter"))
```
This program works by dividing the balls into three lists, comparing them to see which of heavier or lighter the ball is, then recursively finds it.
] |
[Question]
[
## Turing Machine Preliminaries
A Turing machine is specified by the following data
* A finite set of symbols S = \$\{s\_1,s\_2,...\}\$
* A finite set of states M = \$\{m\_1,m\_2,...\}\$
* A partially defined function
$$T : M \times S \to S \times \{\mathrm{left},\mathrm{right}\} \times M $$
Any encoding of such a Turing machine is acceptable, to fix conventions though an example encoding as used for example [at this online simulator](https://morphett.info/turing/turing.html) is to provide a list of lines of code, each line in the format
```
'<current state> <current symbol> <new symbol> <direction> <new state>'.
```
where it is understood that the Turing machine will write the new symbol at the head, move one unit in the specified direction, and enter the new state. Undefined behaviour defaults to halting the Turing machine.
## Problem Statement
There must be at least four symbols in your Turing machine, the blank symbol `_`, the decimal point `.`, and `0`, `1`. There must be at least one state 'begin'. The tape is a one-sided infinite tape, initialized to all blank symbols `['_','_','_',...]`. The Turing machine is initialized with the head pointing at the first symbol, in the 'begin' state. Write a turing machine that never halts, such that for any natural number n the there is some time \$T\_n\$ for which after \$T\_n\$ steps the Turing machine will never change the n-th symbol on the tape, so that the tape will limit to showing the binary decimal representation of pi:
$$11.0010010000111111011…$$
Your score is given by the number of states \$\times\$ the number of symbols in your Turing machine.
## Caveats
* If your Turing machine ever tries to go 'left' at the first symbol, it will halt
]
|
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/210638/edit).
Closed 3 years ago.
[Improve this question](/posts/210638/edit)
In this game of cops and robbers, each cop will make a vault: a program that stores a secret, and requires a key to unlock. The robbers should find a way to get the vault to reveal its secret without knowing the key.
## Cop rules
Cops will write two short segments of code:
* A vault, which takes a key and secret, then allows a robber to guess the key
+ One way to do this would be to use a class, which is constructed with a key and secret, and has a method to enter guesses into
+ The poster should specify a certain set of valid keys and secrets, such as 32 bit integers or strings (note that, unless you add code to prevent it, robbers can still input things that aren't in that set as part of their crack)
+ When a correct guess is made, the vault should return the secret. Otherwise, it should return nothing or a deterministic value that isn't a valid secret
+ Can **not** rely on cryptographic functions, or any system that can only (realistically) be defeated by brute forcing a value
+ Any code necessary to create an instance of the vault does not count toward the byte count (such as `let vault = faulty_vault("key", "secret");`
* A fault, which makes the vault reveal its secret
+ Should work for all keys and secrets
+ Should follow the robber rules
Cop submissions should contain the following information:
* The name of the language used
* The byte count
* The format of the keys and secret
* The maximum number of guesses needed for the fault (to prevent brute forcing)
* The code for the vault
## Robber rules
**Robbers will post their cracking attempts as answers in a separate thread, located [here](https://codegolf.stackexchange.com/questions/210639/robbers-theres-a-fault-in-my-vault).**
* Should work for all keys and secrets
* Should require the same number or fewer guesses as the cop's fault, to prevent brute forcing
* Does not need to be the same as the cop's intended fault
* Multiple cracks may be made for the same cop, as long as they use different methods
## Example
**Cop:**
>
> ## Javascript (V8), too many bytes
>
>
> Maximum **2** guesses.
>
>
> Keys and secrets may be any string
>
>
>
> ```
> function faulty_vault(key, secret) {
> return function(guess) {
> if (guess.constructor != String)
> return;
>
> if (guess == key || typeof(guess) != "string") // Second condition is impossible...right?
> return secret;
> };
> }
>
> ```
>
>
**Robber:**
>
> ## [Javascript (V8)](https://www.youtube.com/watch?v=dQw4w9WgXcQ)
>
>
> Uses 1 guess
>
>
>
> ```
> // Assumes vault instance is in variable "vault"
>
> var not_a_string = new String("typeof thinks this isn't a string");
> vault(not_a_string);
>
> ```
>
>
The winner is the shortest cop not cracked after seven days (safe). Good luck!
]
|
[Question]
[
# Definition
The infinite spiral used in this question has `0` on the position `(0,0)`, and continues like this:
```
16-15-14-13-12
| |
17 4--3--2 11
| | | |
18 5 0--1 10
| | |
19 6--7--8--9
|
20--21...
```
It is to be interpreted as a Cartesian plane.
For example, `1` is on the position `(1,0)`, and `2` is on the position `(1,1)`.
# Task
Given a non-negative integer, output its position in the spiral.
# Specs
* Your spiral can start with `1` instead of `0`. If it starts with `1`, please indicate so in your answer.
* Output the two numbers in any sensible format.
# Testcases
The testcases are 0-indexed but you can use 1-indexed as well.
```
input output
0 (0,0)
1 (1,0)
2 (1,1)
3 (0,1)
4 (-1,1)
5 (-1,0)
6 (-1,-1)
7 (0,-1)
8 (1,-1)
9 (2,-1)
100 (-5,5)
```
[Answer]
## Python, 46 bytes
```
f=lambda n:n and 1j**int((4*n-3)**.5-1)+f(n-1)
```
[Dennis's answer](https://codegolf.stackexchange.com/a/87185/20260) suggested the idea of summing a list of complex numbers representing the unit steps. The question is how to find the number of quarter turns taken by step `i`.
```
[0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7]
```
These are generated by `int((4*k-n)**.5-1)`, and then converted to a direction unit vector via the complex exponent `1j**_`.
[Answer]
# Python, 53 bytes
```
lambda n:sum(1j**int((4*i+1)**.5-1)for i in range(n))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ ~~16~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ḷ×4‘ƽ’ı*S
```
This uses the quarter-turn approach from [@xnor's](https://codegolf.stackexchange.com/a/87188)/[@orlp's](https://codegolf.stackexchange.com/a/87187) answer.
Indexing is 0-based, output is a complex number. [Try it online!](http://jelly.tryitonline.net/#code=4bi2w5c04oCYw4bCveKAmcSxKlM&input=&args=MTAw) or [verify all test cases](http://jelly.tryitonline.net/#code=4bi2w5c04oCYw4bCveKAmcSxKlMKMTDhuLY7MTAwwrU7IsOH4oKsRw&input=).
### How it works
```
Ḷ×4‘ƽ’ı*S Main link. Argument: n (integer)
Ḷ Unlength; create the range [0, ..., n - 1].
×4 Multiply all integers in the range by 4.
‘ Increment the results.
ƽ Take the integer square root of each resulting integer.
’ Decrement the roots.
ı* Elevate the imaginary unit to the resulting powers.
S Add the results.
```
[Answer]
# Python 2, ~~72~~ 62 bytes
```
n=2;x=[]
exec'x+=n/2*[1j**n];n+=1;'*input()
print-sum(x[:n-2])
```
*Thanks to @xnor for suggesting and implementing the quarter-turn idea, which saved 10 bytes.*
Indexing is 0-based, output is a complex number. Test it on [Ideone](http://ideone.com/EHfyPJ).
[Answer]
# Ruby, ~~57~~ 55 bytes
This is a simple implementation based on [Dennis's Python answer](https://codegolf.stackexchange.com/a/87185/47581). Thanks to Doorknob for his help in debugging this answer. Golfing suggestions welcome.
```
->t{(1...t).flat_map{|n|[1i**n]*(n/2)}[0,t].reduce(:+)}
```
**Ungolfed:**
```
def spiral(t)
x = []
(1...t).each do |n|
x+=[1i**n]*(n/2)
end
return x[0,t].reduce(:t)
end
```
[Answer]
## JavaScript (ES7), 75 bytes
```
n=>[0,0].map(_=>((a+2>>2)-a%2*n)*(a--&2?1:-1),a=(n*4+1)**.5|0,n-=a*a>>2)
```
Who needs complex arithmetic? Note: returns `-0` instead of `0` in some cases.
[Answer]
## Batch, 135 bytes
```
@set/an=%1,x=y=f=l=d=0,e=-1
:l
@set/ac=-e,e=d,d=c,n-=l+=f^^=1,x+=d*l,y+=e*l
@if %n% gtr 0 goto l
@set/ax+=d*n,y+=e*n
@echo %x%,%y%
```
Explanation: Follows the spiral out from the centre. Each pass through the loop rotates the current direction `d,e` by 90° anticlockwise, then the length of the arm `l` is incremented on alternate passes via the flag `f` and the next corner is calculated in `x,y`, until we overshoot the total length `n`, at which point we backtrack and print the resulting co-ordinates.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 5 years ago.
[Improve this question](/posts/173553/edit)
[](https://i.stack.imgur.com/ghJty.png)
Given a random coordinate (x,y), determine in which square (squares are referenced by their sidelength) it is (or the borders of which squares).
The squares are drawn in a counter clockwise direction, that is, the first square is drawn in the first quadrant, the one after is to the right, the one after that above, the next to the left and so on. The length of the square sides follows the fibonacci sequence (each new one is the sum of the two previous ones).
So, for example, given a coordinate (0,3) it should display 8, whereas (0,1) would display 0,1,2. Decimal coordinates are also aloud.
]
|
[Question]
[
Back to back challenges I guess. Hopefully this one is more clear than the last.
# Background
I was playing around with Goldbach's conjecture, and decided to plot evens (on the x-axis) vs the number of ways that two primes could be found to sum to a given even on the y axis.
The two plots I've made below in Python are for 10,000 and 1,000,000 evens.
[](https://i.stack.imgur.com/egtRX.jpg)
[](https://i.stack.imgur.com/RphQM.png)
The structure of these graphs is really fascinating! So I decided to go further and color different types of evens (those divisible by different numbers) different colors.
What I found was that each band represented a set of evens divisible by some odd number, e.g., 3, 5, 7, 9. So that got me thinking of the following challenge. I would post the picture, but doing so might make this challenge a bit too easy, so I'll refrain till after I've crowned someone a victor.
# Challenge
Define *G(x)* to be a function defined on the positive evens which returns the number of different ways to sum two primes numbers to form *x*. Note that the primes are indistinguishable, i.e., 3+5 and 5+3 are considered equivalent.
This is a [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'") challenge where your goal is the following:
Find 3 differentiable and concave functions *f,g,h* defined on the positive reals such that:
1. For any even divisible by 6 and less than 10,000,000, and any real *y* less than or equal to this even, *f(y)<=G(even)*
2. For any even divisible by 10 and less than or equal to 10,000,000, and any real *y* less than or equal to this even, *g(y)<=G(even)*
3. For any even divisible by 14 and less than 10,000,000, and any real *y* less than or equal to this even, *h(y)<=G(even)*
Your score will be the integral from 0 to 10,000,000 of (f+g+h).
# Rules
* Each submission must not only include the formulas for all three of these functions, but show through code in whatever language they see fit that the conditions of the challenge are met.
* Each submission must also calculate the integral of their score. This can be done in a separate language if so desired by the user (or by hand if you are a masochist).
* Once a submission has been made, any submission whose score is not at least 5 points higher than the previous submission will not dethrone the current winning submission.
# Prizes
I don't have much reputation, but I'll put up a +50 bounty for first place, along with a +15 for accept. This is somewhat of a new type of challenge for this site, so enjoy!
# Edit
Considering the poor reception this problem has received, I will no longer be offering a prize for this problem. However, I'm working on designing another one, which hopefully will have a prize associated with it!
]
|
[Question]
[
[Ethereum](https://www.ethereum.org/) is a blockchain platform. It has its own native cryptocurrency, ether, but in this challenge, we'll be focusing on its ability to run smart contracts.
The [ERC-20 standard](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md) describes an implementation of fungible tokens within a smart contract. Some examples of this implementation are [EOS](https://etherscan.io/token/EOS), [OmiseGo](https://etherscan.io/token/OmiseGo), and the [Golem Network Token](https://etherscan.io/token/Golem). In this challenge, your job is to find the amount of tokens owned by a certain address using the fewest bytes possible.
The standard defines a `balanceOf(address)` contract method which is simple enough to use; however, it returns it in terms of a much smaller unit. To get the actual balance, you must divide the result by 10 to the power of whatever the `decimals()` method returns. For example, calling `balanceOf(0x4530d03744d7ef769025623d31966da1e8485eef)` returns `1.500000000000015e+21`, and dividing it by 10^`decimals()` (10^18) results in the true balance of `1500.000000000015`.
## Notes
* Assume that the computer that your program/function/etc. will be running on is running a fully-synced [Geth](https://github.com/ethereum/go-ethereum) node on the Ethereum mainnet with the [JSON-RPC](https://github.com/ethereum/wiki/wiki/JSON-RPC) endpoint listening on the default port of `localhost:8545`.
* Your program should take two inputs: the token contract address (e.g. `0xea097a2b1db00627b2fa17460ad260c016016977`) and the wallet address (e.g. `0x4530d03744d7ef769025623d31966da1e8485eef`). Input can be taken in any reasonable format, such as a string, an integer, or an array of bytes (NB: Ethereum addresses are 20 bytes long).
* It should have one output: the token balance of the address in any reasonable format. Cases where the balance is zero must still be handled.
* Loss of *fine* floating-point precision in the *final* balance (e.g. the 17th or 18th decimal after dividing the balance by 10^`decimals()`) is okay.
* The ERC-20 standard technically says that the `decimals()` method might not be implemented; however, you may assume that it is.
* The use of libraries like [web3.js](https://github.com/ethereum/web3.js/) is permitted, but discouraged.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are obviously not allowed.
## Test Cases
```
token, wallet -> balance
0xea097a2b1db00627b2fa17460ad260c016016977, 0x4530d03744d7ef769025623d31966da1e8485eef -> 1500.000000000015
0xab95e915c123fded5bdfb6325e35ef5515f1ea69, 0x4530d03744d7ef769025623d31966da1e8485eef -> 317.18737335873794694
0x6810e776880c02933d47db1b9fc05908e5386b96, 0x3257bde8cf067ae6f1ddc0e4b140fe02e3c5e44f -> 8495410
0xb64ef51c888972c908cfacf59b47c1afbc0ab8ac, 0x0be3dead1ba261560362361838dd9671a34b63bb -> 314873.06011271
```
## Reference Implementation
A reference implementation written in [Crystal](https://crystal-lang.org/) can be found [here](https://gist.github.com/nickbclifford/56efe3ebee672db64471b987ab725747).
]
|
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/65159/edit).
Closed 2 years ago.
[Improve this question](/posts/65159/edit)
# Introduction
By steganography we mean **hiding a message** along an existing text or image so the result would be **unsuspicious** of the existence of the original message. This challenge is about hiding data in Unicode variants of a grapheme called [homoglyphs](https://en.wikipedia.org/wiki/Homoglyph). For instance:
cyrillic Е (ye) appears the same as latin E which appears the same as greek Ε (epsilon). They are all glyphs from an archetypical E grapheme and several fonts renders them the same. This allows us to hide three units of information (0 1 2) in just one character. A whole text makes room for a complex message.
>
> Terms: A **package** (steganographic unsuspicious text) is a **payload** (message) encoded into a **carrier** (raw text)
>
>
>
# Challenge
1. Create an steganographic encoder (SE) and decoder (SD) in your chosen golfing language. It must be capable of steganographically encoding its own code by defining its coded character set.
*SE(payload, carrier) -> package*
*SD(package) -> payload*
2. Create a package by encoding the encoder itself as *payload* in the *carrier* below. Then **provide package and decoder**. Decoder should retrieve encoder inside *package*.
*SE(SE, carrier) -> package*
*SD(package) -> SE*
3. **SHORTEST PACKAGE WINS!** truncate it!
# Challenge input
**A. Coded character set**
Create a coded character set with 6 bits, 7 bits,... as much as characters your chosen language requires. You can use ASCII (8 bits) but be aware of wasting carrier capacity.
Pyth for instance requires 7 bits because it maps from 32 to 126 ASCII codes.
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ <newline>
```
**B. Homoglyph mapping**
**IMPORTANT NOTE:** this is NOT BINARY MAPPING. For instance there are five 'M' and 'v' homoglyphs (0 1 2 3 4). Binary mapping QQ (0 1) is almost trivial (less than 100 bytes of steganographic encoder size)
```
!! "″" $$ %% && (( )) ++ ,‚, -‐- .. /⁄/ 00 11 22 33 44 55 66 77 88 99 :: ;;; << == >> ?? @@ AΑАA BΒВB CϹСⅭC DⅮD EΕЕE FϜF GԌG HΗНH IΙІⅠI JЈJ KΚКKK LⅬL MΜМⅯM NΝN OΟОO PΡРP QQ RR SЅS TΤТT UU VѴⅤV WW XΧХⅩ YΥҮY ZΖZ [[ \\ ]] ^^ __ `` aаa bЬb cϲсⅽc dԁⅾd eеe ff gg hһh iіⅰi jјj kk lⅼl mⅿm nn oοоo pрp qq rr sѕs tt uu vνѵⅴv wѡw xхⅹ yуy zz {{ || }} ~~ ÄӒ ÖӦ ßβ äӓ öӧ
```
**C. Carrier**
>
> “De Chamilly obeyed; he reached Basle, and on the day and at the hour appointed, stationed himself, pen in hand, on the bridge. Presently a market-cart drives by; then an old woman with a basket of fruit passes; anon, a little urchin trundles his hoop by; next an old gentleman in blue top-coat jogs past on his gray mare. Three o'clock chimes from the cathedral tower. Just at the last stroke, a tall fellow in yellow waistcoat and breeches saunters up, goes to the middle of the bridge, lounges over, and looks at the water; then he takes a step back and strikes three hearty blows on the footway with his staff. Down goes every detail in De Chamilly's book. At last the hour of release sounds, and he jumps into his carriage. Shortly before midnight, after two days of ceaseless travelling, De Chamilly presented himself before the minister, feeling rather ashamed at having such trifles to record. M. de Louvois took the portfolio with eagerness, and glanced over the notes. As his eye caught the mention of the yellow-breeched man, a gleam of joy flashed across his countenance. He rushed to the king, roused him from sleep, spoke in private with him for a few moments, and then four couriers who had been held in readiness since five on the preceding evening were despatched with haste. Eight days after, the town of Strasbourg was entirely surrounded by French troops, and summoned to surrender: it capitulated and threw open its gates on the 30th of September 1681. Evidently the three strokes of the stick given by the fellow in yellow costume, at an appointed hour, were the signal of the success of an intrigue concerted between M. de Louvois and the magistrates of Strasbourg, and the man who executed this mission was as ignorant of the motive as was M. de Chamilly of the motive of his.”
>
>
>
If you run out of carrier characters (very unlikely and maybe you'll need to optimize further, but I'm not sure) duplicate the carrier.
---
# Challenge output example
**NOTE:** Please be aware this solution is based on binary mapping (each char carries a 0 or 1 value) so it is far easier than the challenge.
This is the package: a steganographic encoder encoded by itself into the challenge carrier. It could be retrieved again by means of its steganographic decoder (Pyth at footnote) and its coded character set. It is rendered here by an adverse font to contrast homoglyphs.
[](https://i.stack.imgur.com/bHXHb.png)
---
# Simplest example
```
Character set > abcdefghijklmnñopqrstuvwxyz.,?!
Coded character set (5 bits) 0123456789ABCDEF0123456789ABCDEF
Mapping (0) !"$%&()+,-.;<=>?@ABCDEFGHIJKLMNOPSTVXYZ[]^`acdehijmopsvwxy{|}~ÄÖäö
Mapping (1) homoglyphs !″$%&()+‚‐.;<=>?@ΑΒϹⅮΕϜԌΗΙЈΚⅬΜΝΟΡЅΤⅤΧΥΖ[]^`аϲԁеһіјⅿοрѕνѡху{|}~ӒӦӓӧ
```
>
> Ϝοr you whο are rеаdіng thеsе lines dіdn't you rеalize soⅿеthing that lοoks like a key іn tһe kеyһole, thаt suѕрiϲiouѕ Ϝ? These linеs аren't јuѕt οrdinary tехt but а 'package' full of unіcode νarіаnts of ѕаme grapheⅿes whiϲh lοοk verу аlike (hοⅿοglурһs). A 'pаyloаԁ' is ѡitһheld by tһe pаckage. Copу and раѕte tһіs pаrаgraph in nοteраd аnd the differences bеtween glуpһs ѡіll be renԁered notіϲeable.
>
>
>
This is binary mapping: we will assign a **0** to latin ordinary graphemes, and **1** to their homoglyphs
```
Ϝοr you whο are rеаdіng thеsе lines dіdn't you rеalize soⅿеthing that lοoks like a key іn tһe kеyһole, thаt suѕрiϲiouѕ Ϝ? These linеs аren't јuѕt οrdinary tехt but а 'package' full of unіcode νarіаnts of ѕаme grapheⅿes whiϲh lοοk verу аlike (hοⅿοglурһs). A 'pаyloаԁ' is ѡitһheld by tһe pаckage. Copу and раѕte tһіs pаrаgraph in nοteраd аnd the differences bеtween glуpһs ѡіll be renԁered notіϲeable.
11r 00u 001 0r0 r1101ng t0101 l0n00 010n't 00u r10l0z0 0011t00ng t00t l10k0 l0k0 0 k00 1n t10 k1010l00 t01t 0u110100u1 10 00000 l0n10 1r0n't 1u1t 1r00n0r0 t11t but 1 '000k0g0' full 0f un10000 10r11nt0 0f 1100 gr0000100 00010 l11k 00r1 1l0k0 10111gl111000 0 '010l011' 00 10t100l0 b0 t10 010k0g00 0001 0n0 111t0 t110 01r1gr000 0n n1t0110 1n0 t00 00ff0r0n000 b1t000n gl1010 11ll b0 r0n10r00 n0t1100bl0.
11000 w 01001 i 10101 t 01000 h 01000 h 10000 o 01100 l 00100 d 00000 11010 y 10000 o 10110 u 10011 r 00000 00101 e 01110 n 00011 c 10000 o 00100 d 00101 e 10011 r 00000 01000 h 00101 e 10011 r 00101 e 11111 ! 00000 10011 R 00101 e 00001 a 00100 d 00000 10011 r 10110 u 01100 l 00101 e 10100 s 00000 00010 b 00101 e 01100 l 10000 o 11000 w
```
**What is inside?**
>
> "withhold your encoder here! read rules below"
>
>
>
---
]
|
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/40715/edit)
Trick the user that StackExchange is broken:

It can be done in several ways:
* Your program starts a browser in some certain way (with a proxy server, for example);
* Your program shows static picture;
* Your program is executed in address bar using `javascript:`.
* (your other creative way)
StackExchange error page should be displayed to user one way or another. It may appear immediately or after user tries to do something (i.e. to post a comment). The program should look like some useful StackExchange enhancer (e.g. a userscript that highlights happy posts, i.e. posts containing the word `happy`).
Try to aim for the shortest program (original tag was [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")) and/or obfuscated code. You may depend on some concrete browser (Firefox, Chromium, Opera).
Encouraged:
* Preserving address line "normal";
* Finding actual faults in StackExchange software;
* Making it "hard to fix" (on this computer), e.g. making it cached;
* Making it show different error depending on on which site do I start the program (if it is a in-browser snippet);
Discouraged:
* Simply redirecting to [`http://.../error`](https://codegolf.stackexchange.com/error). You can still try to sneak it [underhanded](/questions/tagged/underhanded "show questions tagged 'underhanded'")-style.
* Trying to permanently mess with user's StackExchange account.
(inspired by [this](https://worldbuilding.stackexchange.com/a/3350/935))
]
|
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 9 years ago.
[Improve this question](/posts/5693/edit)
Ask questions if you need to, I'll elaborate on anything that needs clarified.
My challenge is to unsolve a sudoku to a minimal state. Basically take a supplied, solved, sudoku board and unsolve it as far as possible while keeping the solution unique.
I'll leave input up to you, I don't like forcing anything which would make some solutions longer.
Output can be anything reasonable, as long as it spans the nine lines it'll take to display the sudoku board, for example:
```
{[0,0,0], [0,0,0], [0,1,0]} ┐
{[4,0,0], [0,1,0], [0,0,0]} ├ Easily understood to me
{[1,2,0], [0,0,0], [0,0,0]} ┘
000000010 ┐
400010000 ├ A-OKAY
120000000 ┘
000, 000, 010 ┐
400, 010, 000 ├ Perfectly fine
120, 000, 000 ┘
000000010400010000120000000 <-- Not okay!
```
# Example
```
input:
693 784 512
487 512 936
125 963 874
932 651 487
568 247 391
741 398 625
319 475 268
856 129 743
274 836 159
output:
000 000 010
400 000 000
020 000 000
000 050 407
008 000 300
001 090 000
300 400 200
050 100 000
000 806 000
```
Most minimal answer in shortest time is the winner.
]
|
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/15581/edit).
Closed 6 years ago.
[Improve this question](/posts/15581/edit)
Your challenge is generate a [5 pointed star](https://en.wikipedia.org/wiki/Five-pointed_star) like below. The star doesn't need to be filled.
Shortest code wins.

[Answer]
# PHP, 1 character
Although very short it will probably not become the accepted answer.
```
☆
```
(this is U+2606). May work also in other languages (untested).
[Answer]
## LOGO, ~~32~~ 29 bytes
```
REPEAT 5[FW 9LT 144FW 9RT 72]
```
[Run at logo.twentygototen.org](http://logo.twentygototen.org/vaZj5FJG)
[Answer]
# VBA PowerPoint, 92 bytes
```
Sub s()
ActivePresentation.Slides(1).Shapes.AddShape msoShape5pointStar, 0, 0, 99, 99
End Sub
```
Because everything looks better in PowerPoint:
[](https://i.stack.imgur.com/XLtNN.png)
[Answer]
# Mathematica, ~~19~~ 18 bytes
This is easy, using `CirculantGraph`.
I drew a pentagram as defined in the link the OP used.
```
5~CirculantGraph~2
```

---
A slightly longer way, but equally straightforward, is to use the curated "Lamina" entity. This returns a filled pentagram.
```
"FilledPentagram"~LaminaData~"Image"
```
or
```
EntityValue[Entity["Lamina","FilledPentagram"],"Image"]
```
---
[](https://i.stack.imgur.com/vqFiX.png)
[Answer]
# Python 3, 137 bytes
Polar plot.
```
import pylab as P,numpy as N
S=N.sin
p=N.pi
a=.9*p
d=8e-4*p
A=lambda t:N.arange(0,t,d)
P.polar(A(4*p),list(S(a)/S(a-A(.8*p)))*5)
P.show()
```

[Answer]
# Small Basic, 50 bytes
```
For i=1To 5
Turtle.Move(9)
Turtle.Turn(144)
EndFor
```
A verbose language, but it has built in turtle functionality. Slowly draws a very, very tiny pentagram.

[Answer]
# [Scratch](http://scratch.mit.edu), 4-6 blocks (52-79 scratchblocks code)

This produces this

If anyone's interested, [here's](https://scratch.mit.edu/projects/83473614/) the project.
EDIT: To golf it, remove the pen down. You could remove the then flag clicked, too but it would only run if you clicked it. To golf the scratch blocks version, change "100" to "1", although you get a microscopic pentagram.
Nongolfed scratchblocks:
```
when gf clicked
clear
pen down
repeat (5
move (100) steps
turn cw (144) degrees
```
[Answer]
# HTML & CSS: ~~270~~ 269 bytes
```
<p id=a/><p id=b></p><p id=c></p><p id=d></p><p id=e></p><style>p{position:absolute;width:300px;border-top:solid #000;margin:100px;transform-origin:50% 1666%}#b{transform:rotate(72deg)}#c{transform:rotate(144deg)}#d{transform:rotate(216deg)}#e{transform:rotate(288deg)}
```
Sample run:
* <http://jsfiddle.net/fm6Hu/2/> (Explorer, Firefox, Opera)
* <http://jsfiddle.net/fm6Hu/3/> (Chrome, Opera)
## HTML & CSS: 139 bytes
Impressing rewrite by [Neil](https://codegolf.stackexchange.com/users/17602/neil).
```
div{height:20px;width:300px;border-bottom:solid #000;margin:100px;transform-origin:33% 5%;transform:rotate(72deg)}
```
```
<div><div><div><div><div>
```
(Since first posted, all desktope browsers dropped vendor prefixes, so now one CSS code fits all.)
[Answer]
# HTML5, 37 bytes
```
<svg><path d="M4,0 7,8 0,3 8,3 1,8"/>
```
[Answer]
## Tcl/Tk, 57 bytes
```
pack [canvas .c]
.c cr po 72 0 114 130 3 49 140 49 29 130
```
[Answer]
# [TurtleGolf](https://gist.github.com/DJgamer98/4702b11511ad4b1c2be5), 70 24 22 bytes
Note: This is non-competing, as this language was made after this challenge was posted (though specifically for this challenge).
```
0;
aa*^aa*4b*+>1+:5=?;
```
Explaination:
```
0; - Initialize the loop counter and go to the next line.
aa* - Get the value 100
^ - Move forward by 100px
aa*4b*+ - Get the value 144
> - Rotate 144 degrees to the right
1+ - Increment the loop counter by 1
: - Duplicate it cause we need a copy of it.
5= - Check if the loop counter equals 5, push 1 if it is.
?; - If the top of the stack equals 1, terminate the line.
```
### Old, loopless version.
`aa*^aa*4a*+4+>aa*^aa*4a*+4+>aa*^aa*4a*+4+>aa*^aa*4a*+4+>aa*^aa*4a*+4+>`
I didn't add loops yet, so the code is kind of repetitive right now.
Explaination
```
aa*^ Move aa*(100) pixels forward
aa*4a*+a+ Get the value 144
> Turn 144 pixels to the right
```
EDIT: Shaved off lots of bytes.
EDIT2: Shaved off two more bytes.
[Answer]
# Ruby with [Shoes](http://shoesrb.com/), 36 bytes
```
Shoes.app{star(points:5).move 99,99}
```

[Answer]
# [C (msvc)], 88 bytes
```
#include<Windows.h>
main(){int p[]={50,1,20,91,97,35,2,35,79,91};Polygon(GetDC(0),p,5);}
```
[Answer]
# [Desmos](http://desmos.com), 46 characters
```
r=\sec\left(.4\arccos\left(\cos2.5\theta\right)\right)
```
Here is a longer version that allows you to choose some `n`:
```
r=\sec\left(\frac{2}{n}\arccos\left(\cos\frac{n\theta}{2}\right)\right)
```
[Answer]
## PostScript, 27 bytes
```
$ hexdump -C pentagram_binary.ps
00000000 39 20 39 92 ad 30 20 39 92 6b 36 7b 30 20 39 92 |9 9..0 9.k6{0 9.|
00000010 63 31 34 34 92 88 7d 92 83 92 a7 |c144..}....|
0000001b
```
[Download to try](http://www.mediafire.com/view/bovx5co194fswbn/pentagram_binary.ps).
Output:

Un-golfed ASCII version:
```
9 9 translate
0 9 moveto
6{
0 9 lineto
144 rotate
}repeat
stroke
```
[Answer]
# Python, 47 bytes
```
from turtle import*
for i in[144]*5:fd(i);rt(i)
```
[**Try it online**](https://trinket.io/python/16f9d37467)
The following (**42 bytes**) also works (Python 2 only), but Trinket doesn't allow `exec`, so you can't run it online. Also, the result is much smaller.
```
from turtle import*
exec'fd(9);rt(144);'*5
```
[Answer]
# [Google Blockly](https://developers.google.com/blockly/), 3 blocks
In response to the [Scratch answer](https://codegolf.stackexchange.com/a/61230/41257)
Blockly turtle doesn't need "so much" boilerplate code.
[](https://i.stack.imgur.com/Il9dR.png)
This "code" can be ran [here](https://blockly-games.appspot.com/turtle?lang=en&level=3#da57w2) and produces this pentagram
[](https://i.stack.imgur.com/j7Yss.png)
# Five pointed star, 5 blocks
The five pointed star can be tested [here](https://blockly-games.appspot.com/turtle?lang=en&level=1#vm6r6v)
[](https://i.stack.imgur.com/DpKou.png)[](https://i.stack.imgur.com/eYZsX.png)
[Answer]
# Shell, 60 bytes
(Coordinates shamelessly stolen from [user1455003](https://codegolf.stackexchange.com/users/8055/user1455003)'s [SVG answer](https://codegolf.stackexchange.com/a/15603). For artistic merits upvote his answer.)
```
convert -size 9x9 xc: -draw 'polygon 4,0 7,8 0,3 8,3 1,8' x:
```
Sample output:

[Answer]
# R, ~~50~~ 54 bytes
```
plot(1:9,t="n",as=1);polygon(c(5,8,1,9,2),c(1,9,4,4,9))
```
Output:
[](https://i.stack.imgur.com/g9xHy.png)
[Answer]
# R, 40 bytes
```
symbols(1,st=cbind(8,3,8,3,8,3,8,3,8,3))
```
[](https://i.stack.imgur.com/OJHoS.png)
[Answer]
# Swift 3, ~~394~~ 370 bytes
```
import UIKit
UIGraphicsBeginImageContextWithOptions(CGSize(width:2,height:2),false,100)
let c1=0.3,c2=0.8,s1=1.0,s2=0.6,o=(0.0,1.0),p=[o,(s2,-c2),(-s1,c1),(s1,c1),(-s2,-c2),o].map{CGPoint( x:$0.0,y:$0.1)},c=UIGraphicsGetCurrentContext()!
c.translateBy(x:1,y:1)
c.setLineWidth(1/100)
c.move(to:p[0])
p.forEach{c.addLine(to:$0)}
c.fillPath()
UIImage(cgImage:c.makeImage()!)
```
[](https://i.stack.imgur.com/xfdPa.png)
[Answer]
# Octave, 24 bytes
```
polar(t=[1:.8:5]*pi,~~t)
```
Output:
[](https://i.stack.imgur.com/rUvQl.png)
Or, for 36 bytes you can have just the outline:
```
polar(t=[0:.2:2]*pi,1-mod(t,pi/2.5))
```
[](https://i.stack.imgur.com/oIumG.png)
[Answer]
# Tikz, ~~126~~ ~~120~~ 125 bytes
*5 bytes saved thanks to [Julian Wolf](https://codegolf.stackexchange.com/users/66904/julian-wolf)*
```
\documentclass[tikz]{standalone}\usetikzlibrary{shapes}\begin{document}\tikz{\node[draw=red,star]{};}\end{document}
```
This draws a red star shaped node at `(0,0)`.
[Answer]
# Excel VBA, ~~37~~ 35 Bytes
Anonymous VBE immediates window function that takes no input and outputs a five pointed star to the top left of the `Sheet1` (default sheet) object
```
Sheet1.Shapes.AddShape 92,0,0,99,99
```
## Sample Output
[](https://i.stack.imgur.com/bDUX8.png)
[Answer]
# Python 2, 52 bytes
```
from turtle import*;exec('fd(99);rt(144);'*5);done()
```
[](https://i.stack.imgur.com/vRRMJ.png)
[Answer]
# JavaFX / FXML, 138 bytes
```
<?import javafx.scene.layout.*?><?import javafx.scene.shape.*?><Pane><children><SVGPath content="M4,0 7,8 0,3 8,3 1,8"/></children></Pane>
```
I haven't tested it yet, though
```
<?import javafx.scene.layout.*?>
<?import javafx.scene.shape.*?>
<Pane>
<children>
<SVGPath content="M4,0 7,8 0,3 8,3 1,8" stroke="BLACK"/>
</children>
</Pane>
```
[Answer]
# [Python](https://www.python.org/) + Pylab, 48-byte copout answer
```
from pylab import*
plot(0,0,marker=(5,1))
show()
```
Plots a single point using a five-pointed star as a marker.
[Answer]
# TI-83/84 Basic, 32 bytes
```
Line(0,1,1,1:Line(0,0,.5,1.5:Line(1,0,.5,1.5
```
Note I haven't actually tested this out but I'm assuming it's going to show up as a low resolution, distorted star-shaped object.
* [Line(](http://tibasicdev.wikidot.com/line) command is one byte
] |
[Question]
[
Output all 95 bytes from `0x20` to `0x7E` inclusive (printable ASCII including space), in any order, each at least once. The source code of your program must use all of those bytes, each at least once.
* Your program must be irreducible (meaning you cannot strictly remove some characters from the program and then have it still function correctly), so you can't just add a comment containing the remaining characters
* Your program, and its output, can contain any additional bytes outside this range if you like (bytes, not characters), such as newlines
* You must output them as bytes, not decimal code-points or anything else like that
* Standard rules and loopholes apply
* This is Code Golf, so the shortest program in bytes wins (even though all programs will be at least 95 characters)
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~95~~ 95 bytes
*Edit: adjusted to fix bug pointed-out by Neil. Same bytes*
```
mcW=2`R\.5+46L" !#$%&'()*,-/013789:;<=?@ABCDEFGHIJKMNOPQSTUVXYZ[]^_abdefghijklnopqrstuvwxyz{|}~
```
[Try it online!](https://tio.run/##yygtzv7/Pzc53NYoIShGz1TbxMxHSUFRWUVVTV1DU0tHV9/A0NjcwtLK2sbW3sHRydnF1c3dw9PL29fPPyAwOCQ0LCIyKjo2Lj4xKSU1LT0jMys7Jy@/oLCouKS0rLyisqq6prbu/38A "Husk – Try It Online")
Well, [96 bytes](https://tio.run/##yygtzv7//9AKBUUlZRVVNXUNTS1tHV09fQNDI2MTUzNzC0sraxtbO3sHRydnF1c3dw9PL28fXz//gMCg4JDQsPCIyKjomNi4@ITEpOSU1LT0jMys7JzcvPyCwqLiktKy8orKquqa2rr//wE) in [Husk](https://github.com/barbuz/Husk) is trivial as a literal string, but 95 bytes was much more tricky.
The strategy that I've used is to (1) output all 95 printable ASCII characters using a program written using only non-repeating ASCII characters (this isn't completely straightforward, since many of the useful commands in [Husk](https://github.com/barbuz/Husk) are encoded by non-ASCII characters), and then (2) to adjust it so that output is dependent on the length of a literal string containing all the unused characters: this second bit will ensure that all the characters are used, and also that the program is irreducible.
Here's how it works:
```
mcW=2`R\.5+46L"...
m # map this function:
c # ASCII character
# across all the elements in this list:
W # indexes of all elements that satisfy:
=2 # are equal to 2
# among all the elements in this list:
`R # repeat this value:
\ # reciprocal of
.5 # .5
# this number of times:
+46 # add 46 to
L # the length of
"... # this string
# the string consists of all the printable ASCII characters,
# with the characters of the program removed. There are 15
# characters in the program, so the remaining 95-15=80 characters
# are all present in the string.
# So, to output all the ASCII characters up to
# 126, we need to add 126-80 = 46.
```
[Answer]
# [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/), 95 bytes
```
+[.<] !"#$%&'()*,-/0123456789:;=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\^_`abcdefghijklmnopqrstuvwxyz{|}~
```
[Try it online!](https://tio.run/##K85NSvv/XztazyZWQVFJWUVVTV1DU0tHV9/A0MjYxNTM3MLSytrWzt7B0cnZxdXN3cPTy9vH188/IDAoOCQ0LDwiMiomLj4hMSk5JTUtPSMzKzsnNy@/oLCouKS0rLyisqq6prbu/38A "Self-modifying Brainfuck – Try It Online")
The `+` in the beginning is just to enter the loop, `[.<]` prints the source code backwards.
[Answer]
# [Python 3](https://docs.python.org/3/), 105 bytes
```
print(' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~')
```
;)
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ11BUUlZRVUtRl1DU0tbR1dP38DQyNjE1MzcwtLK2sbWzt7B0cnZxdXN3cPTy9vH188/IDAoOCQ0LDwiMio6JjYuPiExKTklNS09IzMrOyc3L7@gsKi4pLSsvKKyqrqmtk5d8/9/AA "Python 3 – Try It Online")
[Answer]
# [R](https://www.r-project.org/) & likely polyglot, 97 bytes
```
" !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
```
[Try it online!](https://tio.run/##K/r/X0lBUVlFVU1dQ1NLW0dXT9/A0MjYxNTM3MLSytrG1s7ewdHJ2cXVzd3D08vbx9fPPyAwKDgkNCw8IjIqOiYmNi4@ITEpOSU1LT0jMys7Jzcvv6CwqLiktKy8orKquqa2Tun/fwA "R – Try It Online")
2 wasted characters: the second "`"`" to close the string, and the need to use "`\\`" to escape the escaping function of the "`\`" character.
This 'program' will probably function in most languages that (like [R](https://www.r-project.org/)) output unassigned strings (or other variables & expressions) by default, and so is a very likely polyglot.
I suspect, though, that most languages will require at least one character (often a quotation mark or similar, as used here) to specify a string, and not all languages output the string together with surrounding quotation marks (or whatever). [R](https://www.r-project.org/) does, which is beneficial here, but getting down to 95 bytes might only work for a few, if any...
[Answer]
# [Text](https://esolangs.org/wiki/Text), 95 bytes
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
Text programs always print their contents.
[Answer]
# [PHP](https://php.net/), 95 bytes
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
[Try it online!](https://tio.run/##K8go@P9fQVFJWUVVTV1DU0tbR1dP38DQyNjE1MzcwtLK2sbWzt7B0cnZxdXN3cPTy9vH188/IDAoOCQ0LDwiMio6JjYuPiExKTklNS09IzMrOyc3L7@gsKi4pLSsvKKyqrqmtu7/fwA "PHP – Try It Online")
I'm not sure If we're allowed not to open the `<?php` tag in the header.. If not, that's only 2 bytes more, the simpler it just to close it:
# [PHP](https://php.net/), 97 bytes
```
?> !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
[Try it online!](https://tio.run/##K8go@G9jXwAk7e0UFJWUVVTV1DU0tbR1dPX0DQyNjE1MzcwtLK2sbWzt7B0cnZxdXN3cPTy9vH18/fwDAoOCQ0LDwiMio6JjYuPiExKTklNS09IzMrOyc3Lz8gsKi4pLSsvKKyqrqmtq6/7/BwA "PHP – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 104 bytes
```
⎕←' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtE9QVFJWUVVTV1NU1NLW0dXT19A0MjYxNTM3MLSytrG1s7ewdHJ2cXVzd3D08vbx9fP38AwKDgkNCw8IjIqOiY2Lj4hMSk5JTUtPSMzKzsnNy8/ILCouKS0rLyisqq6prauvU//8HAA "APL (Dyalog Unicode) – Try It Online")
***Most APL interpreters would not require the `⎕←`, and would thus require only 98 bytes; a quoted string evaluates to itself. The requirement for `⎕←` is an artifact of TIO.***
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~99~~ 97 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
'"" !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~\
```
[Try it online.](https://tio.run/##y00syUjPz0n7/19dSUlBUVlFVU1dQ1NLW0dXT9/A0MjYxNTM3MLSytrG1s7ewdHJ2cXVzd3D08vbx9fPPyAwKDgkNCw8IjIqOjYuPiExKTklNS09IzMrOyc3L7@gsKi4pLSsvKKyqrqmti7m/38A)
**Explanation:**
```
'" # Push the character '"'
"... # Push a string with all printable ASCII characters, except for '"'
# (NOTE: The `\` is at the end so we won't have to escape it to `\\`)
# (implicitly output the entire stack joined together as result)
```
[Answer]
# [Haskell](https://www.haskell.org/), 101 bytes
```
main=putStr[' '.."#$%&()*+,-/01234689:;<>?@ABCDEFGHIJKLMNOPQRTUVWXYZ\\^_`bcdefghjkloqsvwxyz{|}~"!!75]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oLQkuKQoWl1BXU9PSVlFVU1DU0tbR1ffwNDI2MTMwtLK2sbO3sHRydnF1c3dw9PL28fXzz8gMCgkNCw8IjIqJiYuPiEpOSU1LT0jKzsnv7C4rLyisqq6prZOSVHR3DT2/38A "Haskell – Try It Online")
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 96 bytes
```
!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"”
```
[Try it online!](https://tio.run/##S0/MTPz/X0FRWUVVTV1DU0tbR1dP38DQyNjE1MzcwtLK2sbWzt7B0cnZxdXN3cPTy9vH188/IDAoOCQ0LDwiMio6JjYuPiExKTklNS09IzMrOyc3L7@gsKi4pLSsvKKyqrqmtk7pUcPc//8B "Gaia – Try It Online")
Alternately (same byte count):
```
“ !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
```
[Try it online!](https://tio.run/##S0/MTPz//1HDHAVFZRVVNXUNTS1tHV09fQNDI2MTUzNzC0sraxtbO3sHRydnF1c3dw9PL28fXz//gMCg4JDQsPCIyKjomNi4@ITEpOSU1LT0jMys7JzcvPyCwqLiktKy8orKquqa2jql//8B "Gaia – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 101 bytes
```
print[(' !"#$%&*+-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz{\|}~',)]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM68kWkNdQVFJWUVVTUtbV0/fwNDI2MTUzNzC0sraxtbO3sHRydnF1c3dw9PL28fXzz8gMCg4JDQsPCIyKi4@ITEpOSU1LT0jMys7Jzcvv6CwqLiktKy8orKqOqamtk5dRzP2/38A "Python 2 – Try It Online")
[Answer]
# [Assembly (NASM, 32-bit, Linux)](https://www.nasm.us/), 175 bytes
```
mov ecx,y
mov edx,z
mov ebx,1
mov eax,4
int 128
section .data
y db" !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~",34
z equ $-y
```
[Try it online!](https://jdoodle.com/a/2stc)
[Answer]
# ><>, 95 bytes
```
"ra7+2*>o< !#$%&'(),-./01345689:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`bcdefghijklmnpqstuvwxyz{|}~
```
[Try it online!](https://tio.run/##S8sszvj/X6ko0VzbSMsu30ZBUVlFVU1dQ1NHV0/fwNDYxNTMwtLK2tbewdHJ2cXVzd3D08vbx9fPPyAwKDgkNCw8IjIqOiY2Lj4hKTklNS09IzMrOyc3r6CwuKS0rLyisqq6prbu/38A "><> – Try It Online")
Simple `><>` quine, with extra chars added.
```
"ra7+2*>o< !#$%&'(),-./01345689:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`bcdefghijklmnpqstuvwxyz{|}~
" Begin string mode
ra7+2... Pushes string to stack
" End string mode (after wrapping around)
r Reverse stack
a7+2* Push 34 (") to the stack
>o< Repeatedly outputs until stack is empty, when it errors
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~111~~ 107 bytes
Thanks to Noodle9 and Nahuel Fouilleul for noticing the errors and the reductions!
```
main(b){for(b=32;putchar(b++)<" !#$%&'*,-./014789:>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\^_`degjklqsvwxyz|~"[65];);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI0mzOi2/SCPJ1tjIuqC0JDkjEcjR1ta0UVJQVFZRVVPX0tHV0zcwNDG3sLSys3dwdHJ2cXVz9/D08vbx9fMPCAwKDgkNC4@IjIqJi09ISU3Pys4pLC4rr6isqqlTijYzjbXWtK79/x8A "C (gcc) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~99~~ 98 bytes
```
p"<({[CODE G0Lf_FTW!)}]>,.QmAkX/hlP5xwRc6&vZ-:?$Msq*UNb7%IKn'd|B8eYt=rg3S1yi9`z\\j4a2o;@^JVp~#+uH"
```
[Try it online!](https://tio.run/##BcEFAoIwAADAryAGYEzEjtnY3a2AgYHMAYr5dbzDhvi0MLQQmaLf80K7yBNltrFflwZjG/Ndpr2gq@TOE7986YTNR0@KuO4zXyLjaGo397AlRp3V@pXafvKx3VSH@BDsB57H@Oa1WJxCAqcms6vaCP3sHqNCWsjQNYLGHoqkGCDJAtaApmKdgJCgWZNjAWDNKM8ARUC0KyHJmLH@ "Ruby – Try It Online")
I'd love to see a shorter Ruby version but I don't know how it could be built.
I tried to use a regex in order to save one or two characters, but there needs to be a space between `p` and `/`, and `\` needs to be escaped:
```
p /\\# "!$%&'()*+,-.0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXY[Z]^_`abcdefghijklmnopqrstuvwxyz{|}~/
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~112~~ ~~110~~ 111 bytes
Saved 2 bytes thanks to [Nahuel Fouilleul](https://codegolf.stackexchange.com/users/70745/nahuel-fouilleul)!!!
Added a byte to fix a bug kindly pointed out by [Neil](https://codegolf.stackexchange.com/users/17602/neil).
```
f(){puts(" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~");}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NQ7O6oLSkWENJQTFGSVlFVU1dQ1NLW0dXT9/A0MjYxNTM3MLSytrG1s7ewdHJ2cXVzd3D08vbx9fPPyAwKDgkNCw8IjIqOiYmNi4@ITEpOSU1LT0jMys7Jzcvv6CwqLiktKy8orKquqa2TknTuvZ/Zl6JQm5iZp6GJlc1lwIQAB1gzVX7HwA "C (gcc) – Try It Online")
Straight up print those characters, nothing fancy here.
[Answer]
## Batch, 102 bytes
```
@echo " !#$&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~%%
```
Command execution in Batch is a little odd. There are four stages:
* Environment variable expansion
* Parsing a line into individual commands that are piped or chained
* Expanding `for` variables
* Delayed environment variable expansion (if enabled)
`for` variables are named with a leading `%`, which is a source of confusion. Fortunately in Batch scripts any use of `%` other than an environment variable always needs to be quoted as `%%`, which is then turned into a single `%`. (In this script I have put the quoted `%` at the end as it made verifying the script easier.)
To alter the way the line is parsed into commands, special characters can be quoted by preceding them with `^` or (except for `"` itself) by containing them in `"`s. (A trailing `"` is not necessary for the last command on a line.) The `"`s are not actually removed by the parser, as the arguments are passed to the application as a single string, and the application is expected to use the `"`s to help identify quoted arguments.
However `echo` doesn't bother doing any parsing, instead just printing the argument string literally. In this case I've put the `"` at the beginning for readability but it could go anywhere before the first special character.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 96 bytes
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
[Try it online!](https://tio.run/##K0otycxL/P@fS0FRSVlFVU1dQ1NLW0dXT9/A0MjYxNTM3MLSytrG1s7ewdHJ2cXVzd3D08vbx9fPPyAwKDgkNCw8IjIqOiY2Lj4hMSk5JTUtPSMzKzsnNy@/oLCouKS0rLyisqq6prbu/38A "Retina 0.8.2 – Try It Online") Explanation: Simply replaces the empty input with the desired output.
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), 101 bytes
```
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`!"#$%&\'()*+,-./:<=>?@[\\]^_\`{|}~ `\;
```
[Try it online!](https://tio.run/##y05N///fwNDI2MTUzNzCMjEpOSU1LT0jMys7Jzcvv6CwqLiktKy8orLK0cnZxdXN3cPTy9vH188/IDAoOCQ0LDwiMipBUUlZRVUtRl1DU0tbR1dP38rG1s7eITomJjYuPiahuqa2TiEhxvr/fwA "Keg – Try It Online")
The joys of auto pushing everything
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 96 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
“ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
[Try it online.](https://tio.run/##yy9OTMpM/f//UcMcBUUlZRVVNXUNTS1tHV09fQNDI2MTUzNzC0sraxtbO3sHRydnF1c3dw9PL28fXz//gMCg4JDQsPCIyKjomNi4@ITEpOSU1LT0jMys7JzcvPyCwqLiktKy8orKquqa2rr//wE)
**Explanation:**
```
“ # Start a dictionary string
... # Push all printable ASCII characters, which are used as is in dictionary string
# (after which this string is output implicitly as result)
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why this works.
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 96 bytes
```
{" !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz|~"}
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/v1pJQVFZRVVNXUNTS1tHV0/fwNDI2MTUzNzC0sraxtbO3sHRydnF1c3dw9PL28fXzz8gMCg4JDQsPCIyKjomNi4@ITEpOSU1LT0jMys7Jzcvv6CwqLiktKy8orKqpk6p9v9/AA "GolfScript – Try It Online")
The extra byte is because the `"` has to be paired. The block is outputted as it was written in the source code followed by a newline.
[Answer]
# [Unified HQ9+](https://esolangs.org/wiki/Unified_HQ9%2B) and possibly some other dialects, 95 bytes
```
Qh !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPRSTUVWXYZ[\]^_`abcdefgijklmnopqrstuvwxyz{|}~
```
`Q` prints the source code, `h` halts the program to prevent unnecessary output, and the rest are NOPS, but necessary to print everything.
No TIO.
] |
[Question]
[
**Program:** To count the sum of all Unicode characters of a given input.
(No need to display the output. The final answer can be calculated in any base no need to convert back to hexadecimal.)
**Test case** : XyZ= 0058+0079+005A=012B
**Condition:** If the program is inputted, then its output must be an integral multiple of 1729 (hex 06C1). (Sum of all characters [(Unicode)](https://en.wikipedia.org/wiki/Unicode) in the code must be equal to an integral multiple of 1729.)
**Winning criterion:** code golf.
>
> [Sandbox](https://codegolf.meta.stackexchange.com/a/20918/101710)
>
>
>
[Answer]
# [Haskell](https://www.haskell.org/), ~~20~~ 18 bytes
## Sheer luck!
```
sum.fmap(fromEnum)
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzv7g0Vy8tN7FAI60oP9c1rzRX839uYmaegq1CQVFmXomCikKaghKmIqX//5LTchLTi//rJhcUAAA "Haskell – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
Anonymous tacit prefix function
```
+/⎕UCS ⍝õÿ
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X1v/Ud/UUOdghUe9cw9vPbz/f9qjtgmPevsedTU/6l3zqHfLofXGj9omAhUFBzkDyRAPz@D/aQrqEZVR6lxAGl2/OpcGNlHNw9sNzY0sAQ "APL (Dyalog Unicode) – Try It Online")
`+` plus `/` reduction over `⎕UCS` Universal Character Set code points.
`⍝` is the comment symbol and the last two characters are fluff to reach 11×1729.
[Answer]
# [Ohm v2](https://github.com/nickbclifford/Ohm), 5 bytes
```
`Σʾ
```
[Try it online!](https://tio.run/##y8/INfr/P@Hc4lP7oBQA "Ohm v2 – Try It Online")
[Answer]
# Excel, ~~47~~ 43 bytes
*Saved 4 bytes thanks to Axuary*
```
=+sum(unicode(mid(F1,sequence(len(F1)),1)))
```
After input, Excel will autoformat it to look like this:
```
=+SUM(UNICODE(MID(F1,SEQUENCE(LEN(F1)),1)))
```
Input is in the cell `F1` and the formula can be in any other cell. Sum of codepoints is 3,458.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 8 bytes
```
+⌿⍉⊢⎕UCS
+⌿ ⍝ Column first summation
⍉ ⍝ Transpose (no-op)
⊢ ⍝ Identity function (no-op)
⎕UCS ⍝ Universal Character Set index values
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wTtRz37H/V2Pupa9KhvaqhzMFBUQT2iMkqdy9DcyFKhRgHIRVejDgA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Zsh](https://www.zsh.org/), 26 bytes
*Replace `?` with the byte `\x06` below:*
```
for 0 (${(s??)1})((B+=#0))
```
[Try it online!](https://tio.run/##VY6xCsJAEETLkPuKgZxkFxEuFhGRNPb2orEQ8TBNItkT1JBvj3sWgsXCsDO8mbfcJv9oL6HpWsFiJ/AbeOLJd33qUrIDSZJwMTLRdl5ljnky6iFcJYAMgP3rYBhDlPe@aQMs0VlhlXJsjDFz/B2zojypwWxGI5XNFVMHV4dvSf10Zby/qtz8iMoSxgzFarmGjvgA "Zsh – Try It Online")
Zsh is super lenient about the characters used in parameter `${(flags)}`. The `(s)` flag expects a character, then the string to split on, then that character again. And it turns out control characters work perfectly well. (Although TIO wouldn't let me paste in `\x06`, so you get `\x07` in the TIO link, sorry).
I was fortunate that my first program was right around 2000 points, only a couple hundred bytes away from 1 x 1729. Minimizing parameter name codepoints, replacing spaces with tabs, and finally the control characters in flags got me all the way down.
Here's a more standard program:
```
for char (${(s[])1}) # split $1 (first parameter)
((result += #char)) # math function returns last math result
```
[Answer]
# [Python 3](https://docs.python.org/3/), 27 bytes
```
lambda x:sum(map(ord,x))#Ԏ
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCqrg0VyM3sUAjvyhFp0JTU/lK3/@Cosy8Eo00DSU8ipQ0Nf8DAA "Python 3 – Try It Online")
Program inputted unicode sum is `3458` which is `1729*2`, and integral multiple of `0x6C1` or `1729`
Trivial trick, base program unicode (`lambda x:sum(map(ord,x))#`) unicode sum is 2164, then `3458-2164` is 1294 and adding `chr(1294)` = `Ԏ` at the end results `3458`!
[Answer]
# [Red](http://www.red-lang.org), 39 bytes
```
func[s][n: 0 foreach c s[n: n + c]n];ƈ
```
[Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85ujg2Os9KwUAhLb8oNTE5QyFZoRgkkKegrZAcmxdrfazjf0FRZl6JQpqCEpEalLggOgzNjSwVtBSM/gMA "Red – Try It Online")
2 x 1729
[Answer]
# [Coconut](http://coconut-lang.org/), 16 bytes
Defines a function called `ǰ`. This sums to 1729.
```
ǰ=sum<..map$ord
```
[Try it online!](https://tio.run/##S85Pzs8rLfn///gG2@LSXBs9vdzEApX8opT/BUWZeSUaxzdoKKFLKWlq/gcA "Coconut – Try It Online")
`<..` is usually equivalent to `..` (function composition), but has a slightly lower precedence, which allows `map$ord` to be evaluated as partial function application without any parentheses.
[Answer]
# JavaScript, ~~46~~ 42 bytes
```
o=>[...o].map(z=>w+=z.codePointAt(),w=0)|w
```
Definitely not the best language for tasks involving character codes.
*-4 bytes thanks to Arnauld*
[Answer]
# Java, 27 bytes
```
s->s.codePoints().sum()//ը
```
[Try it online!](https://tio.run/##fYyxCsIwFEX3fsWjUzI0/QC10MVJQaibOMTUltQ0Cb6XQpH@jz/k98SIzk6XC@ecQU6yGNpbVEYiwv6RgQ8XoxUgSUozOd3CKLUF1tBd2/50rnmiYEimCKSN6IJVpJ0VR7dztt/@7vrLV9DBJmJRoVCuvR6ctoSMCwwj42X5esZVqjUz0nUULpDwySJjWSek92au8RNl@Z9CznlqLNkS3w)
# Java, 20 bytes
```
ù->ù.chars().sum()
```
This method does not work for all Unicode characters.
[Try it online!](https://tio.run/##bYyxDoIwFEV3vuKFqR14P6CSsDjphJtxqEW0WNqGvpIQw4cx82G1Rkenm5ucczoxiqJrnlFq4T0cXxm4cNVKgidBaUarGuiFMsBqGpS5ny8VTxR0ycRASmMbjCRlDZ7swZr7/ne3X76EFnZxXYpyXVA@xOAZRx96xuMmZerJ061HGwhdwkkb1qJwTk@V/9RY/k/NOU/ynM3xDQ)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 bytes
```
'ЌU¬mc r+
'Ќ // Throwaway one-letter constant to pad the code to desired length.
U¬ // Split the input to letters,
mc // map to char codes
r+ // and reduce with summation.
```
[Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=J1x1MDQwY1WsbWMgcis=&input=IidcdTA0MGNVrG1jIHIrIg==)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 30 bytes
```
"$args"|% T*y|%{$x+=+$_};$x#հ
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0klsSi9WKlGVSFEq7JGtVqlQttWWyW@1lqlQvnqhv///6vjV6EOAA "PowerShell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) `u`, 4 bytes
```
؟OS
```
[Try it online!](https://tio.run/##y0rNyan8///GfP/g/xAKAA "Jelly – Try It Online")
## How It Works
First, the `u` flag tells the interpreter to interpret this encoding as Unicode, rather the Jelly code page, otherwise the `؟` breaks the interpreter: [Try it online!](https://tio.run/##S0oszvj/PzU5I19B6cZ8/2AlBTuFtMycVL2s1JycSi4wqZBWiiQGVQeTwpT5/x8A "Bash – Try It Online")
When the program is actually run, `؟` is an unrecognised symbol, so breaks the parsing, forcing the parser to discard all characters up to the `؟` and begin parsing a new chain with `OS`
`OS` is fairly trivial as Jelly programs go: `O`rdinals then `S`um
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Sums to `5*1729 = 8645`.
```
ÇO,₃
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cLu/zqOmZjgDAA "05AB1E – Try It Online")
`Ç` converts the input string to a list of unicode codepoints, `O` sums the list and `,` prints the result. `₃` pushes 95 to the stack, which is not printed implicitly since there was explicit output before.
[This program](https://tio.run/##yy9OTMpM/f//6L4jbYfbXQ4v4jo1iUvBX@lwOxhrcykYmhtZqhoEctVyHV7@qGmNFxBXH555aPf//wA) was used to find a pair of characters (`,₃`) which are in the codepage and make the program sum to a multiple of 1729.
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, 13 bytes
```
[ Σ dup .o ]
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjkJtYkqFXmpeZnJ@SqlBQlFpSUllQlJlXolCcWliampecWqxgzVWtoBRRGaWkoBStcG6xQkppgYJevkKskkLtfxSB/7mJQMZ/AA "Factor – Try It Online")
## Explanation:
It's a function that takes a sequence as input, prints its sum in octal, and returns the decimal sum as output.
* `[ ... ]` A quotation. An anonymous function that lives on the data stack until called or used by a combinator.
* `Σ` take the sum of a sequence (a string is a sequence of unicode code points)
* `dup` duplicate object on top of the data stack
* `.o` print as octal
[Answer]
# [R](https://www.r-project.org/), 27 bytes
```
sum(utf8ToInt(scan(,"ְ")))
```
[Try it online!](https://tio.run/##K/r/v7g0V6O0JM0iJN8zr0SjODkxT0NH6doGJU1NTbxyAA "R – Try It Online")
The second parameter of `scan` needs to be a string, but can be any string. In code golf, we usually use the empty string, but here using the single character string made of Hebrew Point Sheva (U+05B0) `"ְ"` makes the sum 3458=1729\*2.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes
```
﹪…%d⸿²ΣES℅ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3P6U0J1/DuTI5J9U5I79AQ0k1JaZISUfBSFNHIbg0V8M3sUDDM6@gtCS4BKghXQMo7F@UkpmXmKORqQkE1v//v9@56lHDMtWURzv2H9p0bvH7PUvf79n8qKX13M7/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input string
E Map over characters
ι Current character
℅ Ordinal value
Σ Take the sum
﹪ Perform string formatting
%d⸿ Literal string `%d\r`
… ² Take first two characters
Implicitly print
```
Slightly less satisfying 9 byte version:
```
→⭆¹ΣES℅λ↖
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMqKDM9o0RHIbgEyE33TSzQMARySnM1QEzPvILSEoiMhqaOgn9RSmZeYo5GjiYIWHP55pelaliFFvikppVoWv///6ht0qO1bYd2nlv8fs/S93s2P2ppPbf7Udu0/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
→
```
Print the next value left-to-right (i.e. default direction).
```
⭆¹
```
Cast the expression to string.
```
ΣES℅λ
```
Sum the codepoints of the input string.
```
↖
```
Move the cursor.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 18 bytes
```
->ab{ab.bytes.sum}
```
[Try it online!](https://tio.run/##KypNqvyfZhvzX9cuMak6MUkvqbIktVivuDS39n@BQlq0UkRllFKsXkl@fLGGoZmmra26oVGSOhdYClOLUqytraG5keV/AA "Ruby – Try It Online")
```
x="->ab{ab.bytes.sum}";f=eval(x);f[x] #=> 1729
```
] |
[Question]
[
# Input
An integer \$n\$ greater than or equal to 1.
# Output
The number of bits in the binary representation of the integer that is the product of the first \$n\$ primes.
# Example
The product of the first two primes is 6. This needs 3 bits to represent it.
Given unlimited memory and time your code should always output the correct value for `n <= 1000000`.
[Answer]
# [Factor](https://factorcode.org/), 24 bytes
```
[ primorial bit-length ]
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQm1iSoVeUmJeeWgxhp4GlMxNzoPykzJLyzOJUheLUwtLUvGSgsoKi1JKSyoKizLwSBWsuLiMDhWhDnaTY/9FAmcxcsF4FoC7dnNS89JIMhdj/uYkFCnr/AQ "Factor – Try It Online")
```
primorial ! get the primorial of the input
bit-length ! how many bits does it have?
```
[Answer]
# JavaScript (ES12), 75 bytes
*-1 byte thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)*
Expects a BigInt.
```
n=>eval("for(p=k=1n;p;d?0:p*=n--&&k)for(d=k++;k%d--;)p.toString(2).length")
```
[Try it online!](https://tio.run/##FYxBDoMgEEX3PQUx1jAlGOuydNpD9AISQWshA1Hixnh2qqv/kvfyf3rVSz9PMUkKxuYBM@HLrtrzYggzj@jwTioq824e8YYkZVU5OJVBJ4RyVyOlglin8EnzRCNvofaWxvQtIJ@dt4kRQ3bcHPtE1jYnCQFsuzDWB1qCt7UPI@80Lzfa4ajLbeAEewfqsuc/ "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES12), 76 bytes
```
n=>eval("for(p=k=1n;n;d?0:p*=n--&&k)for(d=k++;k%d--;);p.toString(2).length")
```
[Try it online!](https://tio.run/##FYpBDoMgEADvvoIYa9gSjHos3fYR/YBE0VrIQpR4Mb6d6mkmmfnpTa/9MocoyQ8mjZgIX2bTjuejX3hAiw0pUsO7foQ7kpRlaeFKA1ohlL0NUipQoYr@E5eZJt5C5QxN8ZtDukZnIiOGrFEnnsja@hQhgO0ZY72n1TtTOT/xTvNipwPOt9hHTnB0oLIj/QE "JavaScript (Node.js) – Try It Online")
### Commented
This is a version without `eval()` for readability.
```
n => { // n = input
for( // outer loop:
p = // p = product
k = 1n; // k = current prime candidate
n; // stop when n = 0
d ? // if d is not 0:
0 // do nothing
: // else:
p *= n-- && k // decrement n and multiply p by k
) //
for( // inner loop:
d = k++; // start with d = k and increment k
k % d--; // decrement d until it divides k
); //
return p.toString(2) // convert the final product to base 2
.length // and return the length
} //
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly)
```
Ẓ#PBL
```
A full program that accepts an integer from STDIN that prints the result.
**[Try it online!](https://tio.run/##y0rNyan8///hrknKAU4@//@bAgA "Jelly – Try It Online")**
### How?
Straight forward, just saving a byte over the monadic Link `ÆN€PBL`
```
Ẓ#PBL - Main Link: no arguments
# - starting at {implict k=0} find the first {STDIN} k for which:
Ẓ - is prime?
P - product
B - to binary
L - length
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 30 bytes
```
n->#binary(vecprod(primes(n)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboW-_J07ZSTMvMSiyo1ylKTC4ryUzQKijJzU4s18jQ1NSGKbqqk5Rdp5CnYKhjqKBgZ6CgAVeSVAAWUFHTtgEQaktoFCyA0AA)
[Answer]
# [Python](https://docs.python.org/3.8/), 70 bytes
```
f=lambda n,x=1,i=1:n and f(n-(b:=x**i%i>0),x*i**b,i+1)or len(bin(x))-2
```
[Try it online!](https://tio.run/##FcxBCsIwEAXQvaeYjTATp2DqRgLxLgltdKD@htBFPH3U7Vu8@jleO2732sYocUvvvCSC9ujVog@ghIUKY@IcYnfOzva4inZnzmW1i5e90baCs4G7yDSP8hOQgVrCc2WvNHsJJ6rNcDD034mMLw "Python 3.8 (pre-release) – Try It Online")
The idea is that if `x` is the product of every prime number up to `n`, then the next prime number must not share any prime factors with `x`. This is done by calculating the first `i` greater than `n` such that `x**i%i>0`. This works because if `i` isn't the next prime, all of its prime factors are below `n`, so it will easily divide `x**i`. Raising `x` to the `i`th power makes sure that prime powers are also caught, since `x` by itself only contains each prime factor once.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 34 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4.25 bytes
```
ū錆bL
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiyoHHjs6gYkwiLCIiLCIyIl0=)
Very simple
## Explained
```
ū錆bL¬≠‚Ű‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Ű‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å£‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Ű‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå¬≠
Å«é # ‚Äé‚ŰA list of the first n primes
Π # ‎⁢Take the product of that
bL # ‎⁣And get the length of the binary representation
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Arturo](https://arturo-lang.io), 58 bytes
```
$=>[0x:‚àèselect.first:&2..‚àû=>prime? while->x>0[1+'x/2]]
```
Unfortunately, I have to count bits by counting how many halvings it takes to get to zero since both `log` and `as.binary` no longer work properly once values get into bignum territory. Perhaps there is a smarter way...?
[Try it!](http://arturo-lang.io/playground?2M1JLU)
```
$=>[ ; a function where input is assigned to &
0 ; push 0 -- we'll use this to count bits later
x: ; to x, assign...
‚àè ; product of
select.first:& ; the first <input> number of
2..‚àû=>prime? ; prime numbers in [2..‚àû]
while->x>0[ ; while x is greater than zero...
1+ ; increment our bit count
'x/2 ; divide x by two in place
] ; end while
] ; end function
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-rprime`, 39 bytes
```
->n{'%b'%Prime.take(n).inject(:*)=~/$/}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnW0km5RQVFmbqpS7OI025ilpSVpuhY31XXt8qrVVZPUVQNAcnolidmpGnmaepl5WanJJRpWWpq2dfoq-rUw5QWlJcUKGoZ6ekYGmnq5iQXVSmkaytXxhrWaCrYKytVp0fGGsbVKUOULFkBoAA)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 26 bytes
-3 Thanks to alephalpha:
```
n->#binary(lcm(primes(n)))
```
[Try it online!](https://tio.run/##K0gsytRNL/ifaPs/T9dOOSkzL7GoUiMnOVejoCgzN7VYI09TU/N/Wn6RRp6toY6CoYGOAlAir0QjESIDAA "Pari/GP – Try It Online")
### [Pari/GP](http://pari.math.u-bordeaux.fr/), 29 bytes (original)
```
n->logint(lcm(primes(n)),2)+1
```
[Try it online!](https://tio.run/##K0gsytRNL/ifaPs/T9cuJz89M69EIyc5V6OgKDM3tVgjT1NTx0hT2/B/Wn6RRp6toY6CoYGOAlASqCwRJKv5HwA "Pari/GP – Try It Online")
[Answer]
# [MATLAB](https://nl.mathworks.com/products/matlab.html), 35 bytes
*upd. use `nthprime` instead of `primes(n)`(get all primes up to n)*
```
@(n)ceil(log2(prod(nthprime(1:n))))
```
Full code with test cases:
```
f=...
@(n)ceil(log2(prod(nthprime(1:n))));
disp(arrayfun(f,1:57));
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
√ÖpPbg
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cGtBQFL6//9GAA "05AB1E – Try It Online")
#### Explanation
```
√ÖpPbg # Implicit input
√Öp # First n primes
P # Product
b # To binary
g # Take the length
# Implicit output
```
[Answer]
# Rust + num + num-prime, 59 bytes
```
|n|num_prime::nt_funcs::primorial::<num::BigUint>(n).bits()
```
[Answer]
# Excel, ~~98~~ ~~94~~ 92 bytes
*2 bytes saved thanks to Taylor Alex Raine*
```
=LET(
a,ROW(1:99),
LEN(BASE(PRODUCT(TAKE(FILTER(a,MMULT(N(MOD(a,TOROW(a))=0),a^0)=2),A1)),2))
)
```
Input in cell `A1`.
Fails for `A1>13`.
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `L`, 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
Æppḃ
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMyU4NnBwJUUxJUI4JTgzJmZvb3Rlcj0maW5wdXQ9MiZmbGFncz1M)
#### Explanation
```
Æppḃ # Implicit input
Æp # First n primes
p # Product
ḃ # To binary
# Take the length
# Implicit output
```
[Answer]
# [J](http://jsoftware.com/), 18 bytes
```
f=:3 :'##:*/p:i.y'
```
[Try it online!](https://tio.run/##y/r/P83WyljBSl1Z2UpLv8AqU69S/X@erZWRgUEFV2pyRr5CmkLefwA "J – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
Nθ→→W‹Lυθ¿⬤υ﹪ⅈκ⊞υⅈM→IL↨Πυ²
```
[Try it online!](https://tio.run/##ZY09C8JAEER7f8WWuxALBRtTqZVgJFjZnnHNHW7uzH3En3@egoXYDMw8eNNp5TunJOe9faR4TMOFPY5Uzxo3Ma5Pptfxrz21EQY8cAglbB81JqpgJAJzA9yIYKqgcdckDs9Y0J0Ka1PQb1AWqoElMPx6W29sxJ0K8avdqsDY@mLq4udjWURU57xY5fkkLw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `n`.
```
→→
```
Start searching for primes at `2`.
```
W‹Lυθ
```
Stop when `n` primes have been found.
```
¿⬤υ﹪ⅈκ
```
If none of the primes found so far is a factor of the current value, then...
```
⊞υⅈ
```
... push the current value to the list of primes.
```
M→
```
Otherwise increment the current value. (Note that after a prime is pushed, the value is not immediately incremented, but if more primes are needed then it will "fail" the divisibility test and get incremented that way.)
```
IL↨Πυ²
```
Output the length of the base `2` representation of the product.
[Answer]
# [Python](https://www.python.org), 67 bytes
```
f=lambda N,P=1,p=1:len(-N*f"{P:b}")or f(N-P**p%-~p,P-P**p%~p*P,p+1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3ndNscxJzk1ISFfx0AmwNdQpsDa1yUvM0dP200pSqA6ySapU084sU0jT8dAO0tApUdesKdAIgzLoCrQCdAm1DTahR-mlAhVUKmXkKRYl56akahgaaVgVFmXklGkCTqmoVNKqrtA1rNRWq0zSqNIHGQrTBXAIA)
Disclaimer: This one has one flaw which is that it is "zero-based" which is stretching the rules, I suppose. But I'd still very much like to show it off.
Obviousy, this is heavily based on @dingledooper's answer.
## How?
This leverages a bit of elementary number theory, i.e. Fermat's little theorem, to squeeze out a few bytes.
The basic strategy is the same as dingledooper's: Use the nascent primorial to identify the next prime.What we do differently is when testing the next prime number candidate \$p\$ we raise the primorial \$P\$ to one less power, \$P^{p-1}\mod p\$ instead of \$P^p \mod p\$ That way we know the value can only be \$1\$ (iff \$p\$ is indeed a prime) or \$0\$. The value can, for example, directly be used to decrement the prime number counter. The conditional update of the primorial is also streamlined.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 74 bytes
```
n=>eval("for(i=s=p=1;n;s*=j?1:n--&&i)for(j=i++;s*i<2?i%j--:[++p,s/=2];)p")
```
[Try it online!](https://tio.run/##FYpBDoMgFAX3noIYa6CUtroUfz1I00RisYGQDxHjxnh2iqt5mTdWbSpOiwmrQP/VaYaE8NKbcrSc/UINRAjQSJTxCnZoOhSirg07PwuG8@xN3w7mYoXo3pyHW3xA@5EslCydldMrQQKkkRk9kPaZB@eM7AUhk8fonb47/6OjotWOB8tttc8U2TEyWRzpDw "JavaScript (Node.js) – Try It Online")
Little RAM. Assumes n#(Product of first n primes) don't get too near to \$2^k\$ and therefore need confirm.
# [JavaScript (Node.js)](https://nodejs.org), 73 bytes basically by Arnauld
```
n=>eval("for(p=k=i=1n;n;d?0:p*=n--&&k)for(d=k++;k%d--;);for(;p/=2n;)++i")
```
[Try it online!](https://tio.run/##FYzBCoMwEETvfkUQK9mGtNZjt9v@isHEYhM2QcWL@O2pnmZ4b5ifWc3cT2NaNEfr8kCZ6e1WE2Q5xEkm8jTSg5HRfppnuhJrXdceTmnJK4X@YrVGwJNgulPLCEqNJeSTBLcIFiSOiyNfJNrmbEqB2Aoh@shzDO4W4ld2RlYb73Csq22QDHsHWOz5Dw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 45 bytes
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2Yb898nNS@9JMPBM68kNT21yCUzPbOkODokMze12MEhoAhI1zkWFSVW1inrGMWq/U9T0HdQCErMS0@NNtRRMDKIVdDXB6rKK/kPAA)
```
Length@IntegerDigits[Times@@Prime~Array~#,2]&
```
] |
[Question]
[
**Problem:**
In your choice of language, write the shortest function that returns the floor of the base-2 logarithm of an unsigned 64-bit integer, or –1 if passed a 0. (Note: This means the return type must be capable of expressing a negative value.)
**Test cases:**
Your function must work correctly for all inputs, but here are a few which help illustrate the idea:
```
INPUT ⟶ OUTPUT
0 ⟶ -1
1 ⟶ 0
2 ⟶ 1
3 ⟶ 1
4 ⟶ 2
7 ⟶ 2
8 ⟶ 3
16 ⟶ 4
65535 ⟶ 15
65536 ⟶ 16
18446744073709551615 ⟶ 63
```
**Rules:**
1. You can name your function anything you like.
2. Character count is what matters most in this challenge.
3. You will probably want to implement the function using purely integer and/or boolean artithmetic. However, if you really want to use floating-point calculations, then that is fine so long as you call no library functions. So, simply saying `return n?(int)log2l(n):-1;` in C is off limits even though it would produce the correct result. If you're using floating-point arithmetic, you may use `*`, `/`, `+`, `-`, and exponentiation (e.g., `**` or `^` if it's a built-in operator in your language of choice). This restriction is to prevent "cheating" by calling `log()` or a variant.
4. If you're using floating-point operations (see #3), you aren't required that the return type be integer; only that that the return value is an integer, e.g., floor(log₂(n)).
5. If you're using C/C++, you may assume the existence of an unsigned 64-bit integer type, e.g., `uint64_t` as defined in `stdint.h`. Otherwise, just make sure your integer type is capable of holding any 64-bit unsigned integer.
6. If your langauge does not support 64-bit integers (for example, Brainfuck apparently only has 8-bit integer support), then do your best with that and state the limitation in your answer title. That said, if you can figure out how to encode a 64-bit integer and correctly obtain the base-2 logarithm of it using 8-bit primitive arithmetic, then more power to you!
7. Have fun and get creative!
[Answer]
# C,89
Per my comment on the question, here's a quirky way to do it, inspired by this famous function: <http://en.wikipedia.org/wiki/Fast_inverse_square_root>
```
f(uint64_t x){__float128 y=x;__int128_t i = *(__int128_t*)&y;return x?(i>>112)-16383:-1;}
```
I store the number as a float. Then to extract the exponent of the float, I cast it bitwise to an integer, rightshift the integer and subtract the bias.
Unfortunately to get the last example to run correctly, a 128 bit float is required. A 64 bit float has only 52 bits for the mantissa, so it rounds 18446744073709551615 up to 18446744073709551616 (2^64). The standard IEEE 128-bit float has a 112 bit mantissa (which we shift out and discard) and a bias of 16383 on the exponent. These are the constants you see in the function.
the requirement f(0)=-1 has to be handled with a ternary operator `?:`. Otherwise it would return -16383.
Here's a complete program using type names per GCC. I can't get it to run on visual studio or ideone at the moment, will try later.
```
#include <stdint.h>
uint64_t a;
f(uint64_t x){
__float128 y=x;
__int128_t i = *(__int128_t*)&y;
return x?(i>>112)-16383:-1;
}
main(){
scanf("%llu",&a);
printf("%llu %d",a,f(a));
}
```
[Answer]
# C 40 ~~54~~
**Edit** Clever recursive trick by @Kyle - that's creative!
```
int l(uint64_t n){return n?l(n/2)+1:-1;}
```
(Previous version: That's the bare starting point - creativity level 0)
```
int l(uint64_t n){int r=-1;for(;n;n>>=1)r++;return r;}
```
Test: [Ideone](http://ideone.com/n8HjnP)
[Answer]
# Haskell, 24 bytes
Can't come remotely close to the Golfscript answer, but I think this one in Haskell has everything else beat so far...
```
f 0= -1;f n=f(div n 2)+1
```
E.g.: Running with the test cases provided gives:
```
> map f [0,1,2,3,4,7,8,16,65535,65536,18446744073709551615]
[-1,0,1,1,2,2,3,4,15,16,63]
```
[Answer]
# Golfscript 7 (or 11)
```
2base,(
```
or, if you want the actual function definition:
```
{2base,(}:f
```
you can test it [here](http://golfscript.apphb.com/?c=ezJiYXNlLCh9OmY7CjAgZiBwCjEgZiBwCjIgZiBwCjMgZiBwCjQgZiBwCjcgZiBwCjggZiBwCjE2IGYgcAo2NTUzNSBmIHAKNjU1MzYgZiBwCjE4NDQ2NzQ0MDczNzA5NTUxNjE1IGYgcAo%3D]).
If you consider "base" to be cheating, then add two chars for:
```
{}{2/}/,(
```
[Answer]
# Python 2, 26
```
t=lambda n:len(bin(n+n))-4
```
This is similar to the [Python 3 answer by Tim S](https://codegolf.stackexchange.com/a/35205/36885). However, doubling n and then subtracting 4 from the length has the advantage of working whether n is positive or zero.
If n > 0, then doubling n adds one to the binary length, so we compensate by subtracting 4 instead of 3. On the other hand, if n = 0, then the function returns -1 as desired.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 bytes
```
⌊2⍟.5∘⌈
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1FPl9Gj3vl6po86Zjzq6fif9qhtwqPevkddzY961zzq3XJovfGjtomP@qYGBzkDyRAPz@D/aQpmJlxpCgZAbGZqamwKpc0A "APL (Dyalog Unicode) – Try It Online")
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 13 bytes
```
{⍵=0:¯1⋄⌊2⍟⍵}
```
My first APL answer!
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR71ZbA6tD6w0fdbc86ukyetQ7HyhU@z/tUduER719j7qaH/WuedS75dB640dtEx/1TQ0OcgaSIR6ewf/TFMxMuNIUDIDYzNTU2BRKmwEA "APL (Dyalog Unicode) – Try It Online") (Courtesy of [Adám](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m).)
[Answer]
# [GNU dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 30 bytes
```
[_1pq]sz?d0=z[d2/d0<m]dsmxz2-p
```
Takes input from STDIN. Counts the number of times we can divide by 2.
### Test output:
```
$ for i in 0 1 2 3 4 7 8 16 65535 65536 18446744073709551615
> do echo $i | dc log.dc
> done
-1
0
1
1
2
2
3
4
15
16
63
$
```
[Answer]
# J, 11 chars
Uses the length of the base2 representation but for 0 it yields 1 We add the signum of the original number and subtract 2 thus getting the desired values for all n>=0.
```
(2-~*+#@#:) 18446744073709551615x NB. x is for extended precision number
63
```
[Answer]
# x86\_64 machine language on Linux, ~~11~~ 8 bytes
```
0x0: 83 C8 FF or eax, -1
0x3: 48 0F BD C7 bsf rax, rdi
0x7: C3 ret
```
-3 thanks to @PeterCordes
This uses the "bit scan reverse" instruction to put the index of the most significant `1` bit in `rax`. The `or eax, -1` is to handle the case of zero input. This version no longer depends on ABM or BMI1 instructions and should work on all x86\_64 processors.
To [Try it online!](https://tio.run/##dY5LCsIwEED3PUUICIm0tDG/SvEm2aRpI0WtknYRFK9uTHVTML7lmzfDmOJoTAhoazHCB6h8TZU3tfLWQrBQluDqQK99DgqSgS@xY7GprPJtF3sJl66dHHBL6LphVRoKG7Ailq6fw0UPI8KPDNzcMM4WwU2nRphbVGHc/FqStLukpUnLklYmbZ3@QSS14Jzyv5P0DqkZE5KxSlJZ7TkngnxOPMPL2LM@TqG4974306zN6Q0 "C (gcc) – Try It Online"), compile and run the following C code
```
(*f)()="\x83\xc8\xff" // or eax, -1
"\x48\x0f\xbd\xc7" // bsr rax, rdi
"\xc3"; // ret
main(){
printf("%d\n",f(0));
printf("%d\n",f(1));
printf("%d\n",f(2));
printf("%d\n",f(3));
printf("%d\n",f(4));
printf("%d\n",f(7));
printf("%d\n",f(8));
printf("%d\n",f(16));
printf("%d\n",f(65535));
printf("%d\n",f(65536));
printf("%d\n",f(18446744073709551615));
}
```
[Answer]
# Rust, 28 bytes
```
|n|63-n.leading_zeros()as i8
```
[Try it on the Rust Playground!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&code=%0Afn%20main()%7B%0A%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%0A%20%20%20%20%20%20%20%20vec!%5Bu64%3A%3AMAX%2C0_u64%2C65536_u64%2C65535_u64%5D%0A%20%20%20%20%20%20%20%20.iter()%0A%20%20%20%20%20%20%20%20.map(%7Cn%7C63-n.leading_zeros()as%20i8)%0A%20%20%20%20%20%20%20%20.collect%3A%3A%3CVec%3Ci8%3E%3E()%0A%20%20%20%20)%3B%0A%7D)
An anonymous function that takes in a u64 and outputs the answer as an i8. Change 63 to 127 and it'll work for u128s too.
[Answer]
## Python 3, 38 bytes
```
def f(n):return(-1,len(bin(n))-3)[n>0]
```
`bin(n)` produces a string like `0b100`, so you have to subtract 3, not just 1. `(a,b)[condition]` is a trick I took from [Tips for golfing in Python](https://codegolf.stackexchange.com/a/62/11333).
[Answer]
# C, 72
Using a binary split method
```
int k(uint64_t x){int i=64,r=-!x;while(i/=2)x>>i?x>>=i,r+=i:0;return r;}
```
ungolfed, unwound version with lookup table options.
```
#define USETABLE256
int msb(unsigned long long x){
char ret = -1;
if (x>0xFFFFFFFF){ ret+=32; x>>=32; }
if (x>0xFFFF){ ret+=16; x>>=16; }
if (x>0xFF){ ret+=8; x>>=8; }
#ifdef USETABLE256
return ret + ((const char[256]){
0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
})[x];
#else
if (x>0xF){ ret+=4; x>>=4; }
#ifdef USETABLE16
return ret + ((const char[16]){0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4})[x];
#else
if (x>3){ ret+=2; x>>=2; }
if (x>1){ ret+=1; x>>=1; }
return ret + x;
#endif
#endif
}
```
[Answer]
# Befunge 93 - 23
```
1-&: v
v+1\ _$.@
>\2/:^
```
Limited by implementation to 2^31 or 32-bit signed ints. Given a 64 bit unsigned (128 bit signed?!) implementation this code meets criteria.
[Answer]
## TI-30XB - 19 (Instructions)
I won't actually participate in this contest with the following codes, but I found out this clever solution for my TI-30XB calculator: `log(x)/log(2)+10^12-10^12`. First of all, I wont participate because I clearly used the log function. Second, who actually has TI calculators... Third, this one's probably gonna win because its only 19 instructions. :D (Oh wow, but look at that golfscript code...) I just want to point out that there are more ways to floor a float, if any of you are interested. (For the C programmers its probably still smaller to use int's instead). By the way I am just abusing overflow handeling here. Since the TI-30XB stores floats, adding 10^12 to it will remove everything behind the dot.
## TI-BASIC - 35 bytes
This one is a actual participant, but I bet none of you can execute it... Oh well just buy a TI-84 Plus then :D
```
:PROGRAM:LOG
:0→X
:If N=0
:-1→X
:While N>1
:iPart(N/2→N
:X+1→X
:END
:X
```
You would call the function (Or programs as they are called) like this:
```
:PROGRAM:TEST
:65535→N
:prgmLOG
```
X should now contain the value 15. Also, note that the X on the end of the program can actually be removed if the program is executed using prgmLOG (As shown above), since the X at the end is only used to display the number when the function is executed via the HOME screen. Yes, `While`, `If`, `End` and `iPart(` are one instruction each.
[Answer]
# x87 machine code, ~~27~~ 23 bytes
Binary:
```
00000000: 9bd9 2e15 01d9 e8df 2cd9 f1df 1cad 85c0 ........,.......
00000010: 7902 f7d0 c37f 0f y......
```
Listing:
```
9B D9 2E 013F FLDCW CW ; set FPU CW register for floor rounding
D9 E8 FLD1 ; 1 * multplier into ST(1)
DF 2C FILD QWORD PTR[SI] ; load input into ST(0)
D9 F1 FYL2X ; ST(0) = ST(1) * log2( ST(0) )
DF 1C FISTP WORD PTR[SI] ; store result into [SI]
AD LODSW ; result into AX
85 C0 TEST AX, AX ; was result negative (zero divide)?
79 02 JNS OKAY ; if not, return result
F7 D0 NOT AX ; otherwise, negate AX (AL = -1)
OKAY:
C3 RET ; return to caller
0F7F CW DW 0F7FH ; x87 control word to round down
```
Callable function input as 64 bit signed `QWORD` at `[SI]`, output in `AL`.
Size notes: checking for Zero and returning an explicit `-1` costs 6 bytes. Also, setting FPU to floor rounding costs 7 bytes.
Input/Output from test program:
[](https://i.stack.imgur.com/ypgi8.png)
[Answer]
## [ARMv8](https://www.arm.com/), ~~24~~ 12 bytes
[OakSim](https://wunkolo.github.io/OakSim/) is technically an ARMv7 simulator, but if you want to test all test cases except for the last, you can still use it as reference.
The register widths of ARMv7 are 32 bit. I haven't found a good ARMv8 simulator yet, but the instruction set is backwards compatible, and the register widths should be 64 bit long.
Hexdump:
```
0x00010000: 10 0F 6F E1 3F 00 60 E2 1E FF 2F E1 ..o.?.`.../.
```
(If you're testing on OakSim's ARMv7, here is the respective hexdump:)
```
0x00010000: 10 0F 6F E1 1F 00 60 E2 1E FF 2F E1 ..o...`.../.
```
## Explanation
This is a procedure that expects the argument in `r0`. Output goes to `r0`.
This expects the address of the caller in `lr`, as per the ATPCS (ARM Thumb Procedure Call Standard).
```
log: /* Name of our function */
clz r0, r0 /* r0 = Count Leading Zeroes in r0 */
rsb r0, r0, 63 /* r0 = 63 - r0 */
/* change this number to 31
if you're testing on ARMv7 */
bx lr /* Branch back to caller */
```
Example call:
```
b test /* Skip over this procedure */
log:
/* ommitted to save space */
test:
mov r0, 0 /* Set input argument to e.g. 0 */
mov lr, pc /* Set lr to address of program counter */
b log /* Jump to the procedure */
```
[Answer]
# [Risky](https://github.com/Radvylf/risky), 5 bytes
```
{?+0-_?:0
```
[Try it online!](https://radvylf.github.io/risky?p=WyJ7PyswLV8_OjAiLCJbMTg0NDY3NDQwNzM3MDk1NTE2MTVuXSIsMF0)
Uses a built-in log2 function, but since it operates on integers, it's technically allowed.
## Explanation
```
{?+0-_?:0
{ log2(
? input
+ +
0 0
)
- -
_ (
? input
: =
0 0
)
```
# [Risky](https://github.com/RedwolfPrograms/risky), 7 bytes
```
!_?}_2-__2-:?
```
[Try it online!](https://radvylf.github.io/risky?p=WyIhXz99XzItX18yLTo_IiwiWzE4NDQ2NzQ0MDczNzA5NTUxNjE1bl0iLDBd)
Doesn't use a built-in log2 function.
## Explanation
```
!_?}_2-__2-:?
! length(
_ (
? input
)
} base-convert
_ (
2 2
)
)
- -
_ (
_ (
2 2
)
- -
: (0 ≠
? input
)
)
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 13 bytes
```
-1+/|\(64#2)\
```
[Try it online!](https://ngn.codeberg.page/k#eJx90L0NwkAMBeDeUzyJAhCKcj7/3MEsqTMFu7AFAzEJ4dwFKy7cfHrFe+tj4tv8XC6up3pdiNZzAaNCoGjoYIebiY3v4K7qTbU0aeVuxs5GRDPh/wo+rzcmzoyHoWRWw9KcHJiG1czagfUwSWxrP0z3Fpv8bOufWOTYKRtsmMsX861Ltw==)
Uses "The log base 2 of an integer is the same as the position of the highest bit set" as outlined [here](http://graphics.stanford.edu/%7Eseander/bithacks.html#IntegerLogObvious).
* `(64#2)\` encode as 64 bits
* `|\` cumulative boolean or
* `-1+/` sum and subtract one
If it's ok for an input of `0` to return `0` instead of `-1`, `#1_2\` can be used to save a byte.
[Answer]
## Ruby, 30 bytes
```
f=->n{n>0?n.to_s(2).size-1:-1}
```
E.g.
```
irb(main):019:0> f[0]
=> -1
irb(main):024:0> f[65535]
=> 15
irb(main):025:0> f[65536]
=> 16
```
[Answer]
# Batch - 82
Due to language limitations, this only supports 32-bit ints
```
@set a=-2&set n=%1
:1
@set /aa=%a%+1&set /an=%n%/2&if %n% GTR 0 goto 1
echo %a%
```
[Answer]
# PHP - ~~50~~ 40
My final answer\* inspired by @edc65, who was inspired to do a recursive version from @Kyle
```
function l($n){return $n?l($n>>1)+1:-1;}
```
My original version before the recursive answer was this:
```
function l($n){while($n){$n>>=1;$r++;}return$r-1;}
```
\*I had to use the binary shift (>>) because division (/) kept making it a floating point, yielding wildy inaccurate/large answers (doing floating division until it ran out of decimal places and "became 0").
And casting to an (int) or using floor() cost more characters than the simple right shift.
[Answer]
# MMIX, 16 bytes (4 instrs)
Essentially the same as the C answer, except it forces round-down and therefore can use a 64-bit float.
```
00000000: 0a000300 e400c010 3d000034 f8010000 ½¡¤¡ỵ¡ĊÑ=¡¡4ẏ¢¡¡
```
```
log2 FLOTU $0,ROUND_DOWN,$0
INCH $0,#C010
SR $0,$0,52
POP 1,0
```
[Answer]
# [Pxem](https://esolangs.org/wiki/Pxem), 56 bytes (content)
Unprintables are as backslash followed by its code point in octal.
```
.c.w\000\001\001.v.c.t.y\002.!.c.m.v\001.+.v.a.m.z\001.-XX.a.v.n.d.a.s-1.p
```
## Usage
* Call this subroutine after setting only one item as input.
* Outputs the result to STDOUT instead of returning, as Pxem cannot have negative values unless given from STDIN.
* Some garbages may return.
## With comments
```
XX.z
# if top is not zero; then
.c.wXX.z
# stack usage: input, 2^counter, counter(initially zero)
.a\000\001\001.v.c.tXX.z
# while input is greater than 2^counter; do
.a.yXX.z
# increment counter; done
.a\002.!.c.m.v\001.+.v.aXX.z
# if input differs from 2^counter; then decrement counter; fi
.a.m.z\001.-XX.aXX.z
# output counter; return
.a.v.n.dXX.z
# done; output minus one
.a.a.s-1.p
```
[Try it online!](https://tio.run/##jVj7WuJKEv/fp2gykXQMuTQXRWJUBl2HM8qg47iOgJ5IgoIh4SQB0cB5lX2LfaB9kdnqThAM7nzL9yFdv6rqunc6PgWPvz6hsr1rdne69n1eQWfmCyrlUF7Lk43ADpFsj/Xx0AyekKbl87o9HXl@iE5rd9XTU6Om4/BlZKMHO@x6bi@bZVTXGw5N1xL3VcueqO7YcVB@P0uy2US5Wb38YnA8TuSQPFpswFgiH9EfqTKPF/KcW5j90ahf332/PDLymlZYgM1v3@vXpz/vat8uLo5rlwbRW4jjo8/V71/uro4vvte/NSrSy5xDBnpBnWyWReWhkRf0pzElfY5Vbv6Hhj0cO2Zoo@CRyXujEJbPnm8FI6cfZrOm0zcDJD8ggY@IxPGH3FwwBPorZLONH6entbMjo8JsYGrP0oPHfi/U2RpRuQSwu48e4j@J1DKhljNgKO851n4WUj8xHcRlUM90ApubzVZ5bGumPZ0FtoWEQJ2qL6oewJ9XVWAbvqIOVWJSILNQ7WIRe1CEqovkSTgms9BHci1A7ZYm73aQ0Gq7Wx1h9uDbI6TEm6u3xW1ejSpVnb/XG7radhndBHO3itJ2VVW/r@rzmGzd0n0IyfPqSNXDVbCsrWOEEF71UuDO7jpGCGi7acHyOka0Eq/204KFdWwX5O7SGFjuprDtnXWMEFAO0vEV1jFCwMVJWnB7HSMaZKyXdltbx4gGGbPTPu6uY4QUedVPm86vY4SA9nNacGcdI3nwZ5oWLK9jJA8@vqQFd9cxkgd/XtNF0D7AwB0zHXRpHSMEchumLRfXMaKBO8N0vnfWMaKBO1badHkdK0L5pTQGLsoprABymTQGXvNpDJzZpNhcmOGumRwXlpgMJZtXNTqhQznVLZi/E6rdxkpbbOO2S/8qW22RV9uFdr5NVJAKVGULpnX6fr4rjs5nIrX1PH15Na2Omoka@r0DG871Fxh2Fam62rpNuLTFeRVZ6rs9ZBcJifnW7WGuA3bBA9yKl@BC/hBRFx4TmRhHyhawmGexdYhnxNzk1RxF78EFKHEEVCYKYFVVR/r9OaCxWO4QNngTtN4ELfVoIfhObMFJ8lDxdT6KzR0iujUccUwaVRdIWGWp5TMN4LTdFpJfO1sW3S30VxAIieWnEwerMpYJYiNW0zg4M9aag7eV87ctFeZbeJ46c5N8fIHMHFUhL9OkuCyzy7zF@TlJdmLf2JXYk6TqHykKaPHoWCmI2u9hx7y3HcPg2oQTIxYJbo08t3/XDSY92w@HUobflDtUuk2wqKsPsQztx3ZEcu05ZTVxmyQ8c9WlYHyPOVoQLke1D2DNVbhDLsfMivPE4Hv53wkf8eq9b5tPjIC6VTHneN4IuV6IhmbYfey7DxyICotwJSyq95iIzDeZEXJCZRilxQQPxF8LYpMRVAyGkQ2i0PP8JFfgka6LkaC/TakwF0Rx49c/GtWzY0NQ7hR7Q/GEjdq3xuVx4xKQrvLc1jQNvoR@lQkgofIC67ySgfVQmTBcAo4J1Cuj5OtroCaKq1jwG8hEGQkbI7/vhj24ESS7c7PnLpK78LD/FfhdQ/h8fFJvRFBYKbBtSwx8uIRhtpz3xm437HsuauIjMfreesp9xWLHONJh2ZGkJf8Yi5Fvh2PfRRkJZJacP5YcwPfJkvN1yaHbLRmX7xjUpExW2Nf4QowuDJBibsiynghfLGXGuCZGLHBUW6In@CJ387Y3XDKdvmvvawe8VpFXHPsSG@CJzprrlnWuBD3GceI7CMXQuvkf1PzYNVZsV/HZwqOzGQeNAPmnF9l@iFZMjyD058e@Y@MMpFT0VjMJRATgbDbG18BbMlxcz13ljnKOSKvIFKMrA2R0x3Bs9yF8xFeiTtuxDrfh@p7h6OIY4yMDYglCH1/l6pKUI6L4N8fi4g6OpGK5UiyJ86WRPlhv4pN3hu/wWa6Wu8n9FKMzg1PuKqgBQ2Uiy@72h3A7hWDtB9uH39E45PSaAer6DfhAfaETAe4Wd/Zq2Wxtr1QW2ZjqgNX@5m6LrUKpw8MJc2MUi3ItUY4nGURwOVYjRUhIzTAKeTGKReDFIey7Y3tOM05Fa3vFMsjsl3ZECsXGl2bjncWfBv4poppcLOu0enoT32z9XIm1u8h@E1@@S0KwYFyvFmsCNRnkrsSobmjM4sBgfQzpH9C2zQ1kuWNc0UJRqt5hINShw@hBZyX1/tI0ZBSz@RS3aA@sGHxeDs26N1N8nmO2MjCONMMZoM5Zi1wZ53tUNtG9Wiq9/FZp/2Ol1zc3qBZzQ37nSrgI5hFm13jHGgLrCZoFwXtVE1P@CvMem5DQuMX/oB3exOYBqEsmzUTlOsmIvjwxtgwi57ewuaeJW7Rm8LuS1L/S@w2SiblOgsWDLUeEjgEznLIJjxUFupGroBvbh1tWf9IPYBuONgotinkw2HcOBptOxdkcVNhaZWuo0Tw@YcEzQ@tAO8CrIH47lNkjgJt1RU5YOteDTLyTeju611/NfvNmZsSPtPgeAdc0eMTRN2TZd5/IrDuGlSUgAcm9/OLZB9eeJs6K9BVxxR2bNXP8TI2gcVlDP0mSLkmDPUwPYdq0kPI4/YOEhIWofxwGDdeyHRveoqHOMArJ8QQDIkn1PVCXSDwS7ElTZztKBOYkPvSlmO7MhY1PaOhZ/V4fAuj53hA92r4NYOPb5TE6qf7zK5LPNtiRiuDssNAU3ekWvO7HLvHT/z@j5vMT7DVB9NFocH8u9awikhtFxP69MabT6Q3/5CBaeLpyTEvgNbguwYdDQWwYc5sel@M1UZhNTf8hQHJ9uvAJLuuea/9C6x8N/edf/0Yy2fiARxgPaR/x8jHvQ73Cb3jFmJf/iLfzG1455hU@4JHtmFdM87ZLpUKJ8UjpI16sR7Y3SLlY3N4pFrWdwo62WyqRbRLrbRc2/gs "ksh – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
BL’_¬
```
[Try it online!](https://tio.run/##y0rNyan8/9/J51HDzPhDa/7//29oYWJiZm5iYmBubG5gaWpqaGZoCgA "Jelly – Try It Online")
## Explanation
```
BL’_¬ Main monadic link
B Convert to binary
L Length
’ Decrement
_ Subtract
¬ the argument negated
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 17 bytes
```
n=>n?1+f(n/2n):-1
```
[Try it online!](https://tio.run/##fczNSsQwFIbh/VxFdz0h/clpflqFjOBCcO1WkEyblA4lHduO4NV4F16QN1Kh2WmYs/we3nM2H2Zp5@Gy5n7q7Ob05vXRPyB14MvKk/sct9m@X4fZQuqWlBSzNd3TMNqXT98Cy9Lr6pp9voymtVDCa0dJ8vP1nVAoKCn7DN4yk52IPraTX6bRFuPUg4PHoX/2KxhCtKYnQrbk/7H9UY6HiOFuCYtZFSza8RsmglUxq29YE4xHDFUw8deUlFzuhjJmoUN1wEYIVQvBal6zOylRYegU/wU "JavaScript (Node.js) – Try It Online")
[Similar](https://codegolf.stackexchange.com/a/229647/)
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 38 bytes
```
param($a)for(;$a){$a=$a-shr1;$i++}$i-1
```
[Try it online!](https://tio.run/##hc5Ba4MwFMDxs/kU75ANpQqmJrFDBGG7b6yjlzFG5iLtsOhMZAPnZ3fPi6WMpbkEkl/@L23zpTuz13UdlU2nJ1rlw9SqTh19qoKq6fwM94GqnKrI7DuW0cNqNdJDxKaRkMIngCssfPi74hAiFjgACxG5wBqBs5BcAhzB2gXSS2CDIHEAJhHw/4AUIhEhMOECWGByAWzDuUw5j9MkjW@EYJJhQeIfAviBKxiIR602dqfqXodA9XerS6vfIQf6ineqtL2qH7Xpa4tn17SCkyfe88P2tje2Od6/feC7Fygw6G37stTGzI2z95H@PE3IED5h6U5ZNculOl8sA88CGSHeSEYyTb8 "PowerShell Core – Try It Online")
[With a filter for 39 bytes](https://tio.run/##hc5BS8MwFMDxc/Mp3qFCiy00a5JOhlDQu@LEi8iI9ZVNIp1NikLbz15fL5tDzHLIIe@Xf7JvvrC1WzQmrZoWp6neGYct1P2ujsJN3NOW2m3Lhzq@5CMai33Kx3FirIwY0ErKCP6uLIGUxx7AE0I@sCDgLeTngCCw8IHiHFgSyD2AKwLiP6CkzGUCXPoAFbg6AL4UQhVCZEVeZFdScsWpoOgPMQxwAT0LQofWPWnTYQIhfu@xcvgG1xBuaKYr12nzgLYzbj472KFmwfP9@qazrvm4e32nWy9QUi5Yd1WF1s765HaKn8f@iuAjtW610yfdeXB87ndgxVgwspFN0w8 "PowerShell Core – Try It Online")
[Longer and incorrect results with the built-ins :eyes:](https://tio.run/##hc5Ra4MwEAfwZ/MpbiUbChGMRu1aCsL2vrGOvYiMzMWWkWJnIht0fnZ39sFSxuy9Xe53/8u@/lKN2Sqt/bJuVE@r1aF3852022KxqHRdN2On6407o7LZmBkLPY/53Muvjn3Rd4RkLgEslrnwtwIGyCcAZ4imQIhgMiG6BASCcAqkl8AcQTQBeIJA/AeSOI5iBjyeApjAkxHwuRBJKkSQRmlwG8c84ZiQ4B88@IFrOBCHWmXsi9StYkDV916VVr3DCugrzmRpW6mflGm1xbcbWsHJEyd/XN@1xta7h7cP3Csgw0Bn3ZalMmbIONv31efpwhLhMybdSysHOaYOg/HgWcCSEKcjHen7Xw "PowerShell Core – Try It Online")
## Explanation
```
param($a)for(;$a){ # while a is not 0
$a=$a-shr1 # shift right by 1 the bits of a
$i++} # increases the counter i by 1
$i-1 # outputs the counter minus one
```
[Answer]
# [Julia](http://julialang.org/), 23 bytes
```
!x=ndigits(2x,base=2)-2
```
[Try it online!](https://tio.run/##fdBBTsQgFAbgPad4w6ok1BQKtC7o3juYGHQYw1iRFEww8S7ewgN5kVqLKyXzlv@XPy/5z6@zMyyv6yFrf3SPLsWGZ3pvotWctHxNNqYIGjDGCP5fB18fn9CymrHdoKsZL1bt9RdMFOM1Gy7YWKyvGFPFxF9TUvZyNyZrVnpMITYKoQYhuqEfumspmWKlp3q07QbvE@R2imF2qckU33pM4cnaYJ9DetMnM0dLEEKnlwUSOA/75vtHQ@/ow7Z@6SbyG/5EwSzRXjU3PjE@Umi2lBQPi/Np9o0BPcHBEGT9cf0G "Julia 1.0 – Try It Online")
based on [mathmandan's answer](https://codegolf.stackexchange.com/a/45728/98541)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 21 bytes
```
If[#<1,-1,#0[#/2]+1]&
```
[Try it online!](https://tio.run/##HcSxCsIwEAbgVykcdPEvzTV3lxZUurq5hwxBDHaog2QrPnsEv@Hbc30991y3R27l0m4l0pkxMMhFGqd04tS3@2d710jDtayU@m5cu8OBMcFDEDCDDabq9b@BZxELIi744BZVNtZv@wE "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
Using the word “conemon” print each character 2 times more than the last. The first letter, “c”, should be printed 10 times, the second 12 and so on. Each repeated-letter-string should be printed on a new line.
So the end-result becomes:
```
cccccccccc
oooooooooooo
nnnnnnnnnnnnnn
eeeeeeeeeeeeeeee
mmmmmmmmmmmmmmmmmm
oooooooooooooooooooo
nnnnnnnnnnnnnnnnnnnnnn
```
[Answer]
# [R](https://www.r-project.org/), ~~50~~ ~~47~~ 45 bytes
This is some serious R abuse. I create a `quote` R expression `C(O,N,E,M,O,N)` and feed it into the string repeat function `strrep`, which kindly coerces each name inside the quote into a string. Shorter than `scan` !
```
write(strrep(quote(C(O,N,E,M,O,N)),5:11*2),1)
```
[Try it online!](https://tio.run/##K/r/v7wosyRVo7ikqCi1QKOwNB/Icdbw1/HTcdXx1QHSmpo6plaGhlpGmjqGmv//AwA "R – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 36 bytes
```
i=8
for c in'conemon':i+=2;print c*i
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9PWgistv0ghWSEzTz05Py81Nz9P3SpT29bIuqAoM69EIVkr8/9/AA "Python 2 – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~20~~ 19 bytes
```
(2*5+!7)#'"conemon"
```
[Try it online!](https://tio.run/##y9bNS8/7/1/DSMtUW9FcU1ldKTk/LzU3P0/p/38A "K (ngn/k) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.•Ω‡h₅•Sā·8+×»
```
-2 bytes thanks to *@Emigna*.
[Try it online.](https://tio.run/##yy9OTMpM/f9f71HDonMrHzUszHjU1ApkBx9pPLTdQvvw9EO7//8HAA)
**Explanation:**
```
.•Ω‡h₅• # Push "conemon"
S # Convert it to a list of character: ["c","o","n","e","m","o","n"]
ā # Push a list in the range [1, length]: [1,2,3,4,5,6,7]
· # Double each: [2,4,6,8,10,12,14]
8+ # Add 8: [10,12,14,16,18,20,22]
× # Repeat the characters that many times
» # Join the list by newlines (and output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•Ω‡h₅•` is `"conemon"`.
[Answer]
# Java 11, 78 bytes
```
v->{int i=8;for(var c:"conemon".split(""))System.out.println(c.repeat(i+=2));}
```
[Try it online.](https://tio.run/##VVHPT8IwFL7zV3zZhTaOIZ6MC948aCIeMF6Qw6MUKXbd0r7NEMLfPjs2Q7y0fe/1@9UeqKHJYfvdKksh4JWMO40A41j7HSmNRVcCTWm2UOKj2xqZx955FJfAxEZhAYc52mbyeIpImPl9viu9aMhDPSSqdLooXZKFyhoWSSLl8hhYF1lZc1b5CLFOeF1pYqFSczO/kzI/t3mnUNUbGxUGoYuNIpoUS464r9UaJHuHLlPC1dZezU2neCpqS6y3eIk5MZuNA3pgNshFbQkKGMp@mF66MQF4rxGo0NgcWU9UWTtOsdGK6qD/OGGCGzNKh/fnNxw1X9@lp/tPHme@EwAVHd3g3muuvYPTPwNIdEe1J7/q761lZ9nGLxHJ522SRpYh6bn9BQ) (NOTE: `String.repeat(int)` is emulated as `repeat(String,int)` for the same byte-count, because Java 11 isn't on TIO yet.)
**Explanation:**
```
v->{ // Method with empty unused parameter and no return-type
int i=8; // Integer `i`, starting at 8
for(var c:"conemon".split(""))
// Loop over the characters (as Strings) of "codemon"
System.out.println( // Print with trailing new-line:
c.repeat( // The current character repeated
i+=2));} // `i` amount of times, after we've first increased `i` by 2
```
[Answer]
# Javascript, ~~55~~ 52 bytes
*saved 3 bytes thanks to @Arnauld*
```
s=>[...'conemon'].map(x=>x.repeat(i+=2),i=8).join`
`
```
```
f=s=>[...'conemon'].map(x=>x.repeat(i+=2),i=8).join`
`
console.log(f());
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-R`, 13 bytes
```
`¬¶n`¬Ë²p5+E
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=YKyatm5grMuycDUrRQ==&input=LVI=)
---
## Explanation
```
`¬¶n`¬Ë²p5+E
`¦n` :Compressed string "conemon"
¬ :Split
Ë :Map each character at 0-based index E
² : Repeat twice
p5+E : Repeat 5+E times
:Implicitly join with new lines and output
```
[Answer]
# [Tcl](http://tcl.tk/), 78 bytes
```
set i 8
lmap x {c o n e m o n} {set s ""
time {set s $s$x} [incr i 2]
puts $s}
```
[Try it online!](https://tio.run/##K0nO@f@/OLVEIVPBgisnN7FAoUKhOlkhXyFPIVUhF0TXKlSD5IsVlJS4SjJzU2FclWKVilqF6My85CKgZqNYroLSEpBo7f//AA "Tcl – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~35~~ 34 bytes
```
'conemon'|% t*y|%{"$_$_"*(++$j+4)}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Xz05Py81Nz9PvUZVoUSrska1WkklXiVeSUtDW1slS9tEs/b/fwA "PowerShell – Try It Online")
*-1 byte thanks to mazzy*
Literal string `'conemon'` is converted `t`oCharArra`y`, then for each character we multiply it out by the appropriate length. This is handled by doubling up the character `$_$_` then multiplying by `$j+4` with `$j` pre-incremented each time (i.e., so it'll start at `1+4 = 5`, which gets us 10 characters).
Each newly formed string is left on the pipeline, and implicit `Write-Output` gives us newlines for free.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 15 bytes
```
╕│Pùmon+ô8î∞+*p
```
[Try it online!](https://tio.run/##ASQA2/9tYXRoZ29sZv//4pWV4pSCUMO5bW9uK8O0OMOu4oieKypw//8 "MathGolf – Try It Online")
### Explanation
```
╕│P Compression of 'cone'
ùmon Push 'mon'
+ Concatenate together
ô Foreach over each letter
8 Push 8
î∞ Push the index of the loop (1 based) and double it
+ Add the 8
*p Repeat the letter that many times and print with a newline
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
zR↓4İ0¨cΦ◄‰
```
[Try it online!](https://tio.run/##ARwA4/9odXNr//96UuKGkzTEsDDCqGPOpuKXhOKAsP// "Husk – Try It Online")
### Explanation
```
zR↓4İ0¨cΦ◄‰
¨cΦ◄‰ A = The compressed string "conemon"
İ0 B = The infinite list of even positive numbers
↓4 without its first four elements: [10,12,14,16...]
zR Create a list of strings replicating each character in A as many times
as the corresponding number in B
```
A list of strings in Husk is printed by joining them with newlines.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 29 bytes
```
{i::8;{i+::2;i#x}'x}"conemon"
```
[Try it online!](https://tio.run/##y9bNz/7/vzrTysrCujpT28rKyDpTuaJWvaJWKTk/LzU3P0/p/38A "K (oK) – Try It Online")
I'm not the biggest fan of this solution as it's bad practice (global variables), but it's short. May work on a better solution.
[Answer]
# [Red](http://www.red-lang.org), 53 bytes
```
n: 8 foreach c"conemon"[loop n: n + 2[prin c]print""]
```
[Try it online!](https://tio.run/##K0pN@R@UmhId@z/PSsFCIS2/KDUxOUMhWSk5Py81Nz9PKTonP79AASiZp6CtYBRdUJSZp5AcC6JKlJRi//8HAA "Red – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
Econemon×ι⁺χ⊗κ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUBDKTk/LzU3P09JRyEkMze1WCNTRyEgp7RYw9BAR8ElvzQpJzVFI1sTBKz///@vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
conemon Literal string
E Map over characters
κ Current index
⊗ Doubled
χ Predefined variable 10
⁺ Add
ι Current character
× Repeat
Implicitly print each string on separate lines
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 21 bytes
```
⎕←↑'conemon'⍴¨⍨8+2×⍳7
```
[Try it online!](https://tio.run/##ATkAxv9hcGwtZHlhbG9nLWNsYXNzaWP//@KOleKGkOKGkSdjb25lbW9uJ@KNtMKo4o2oOCsyw5fijbM3//8 "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 44 bytes
```
i=[0..]
g=["conemon"!!n<$take(10+n*2)i|n<-i]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P9M22kBPL5Yr3TZaKTk/LzU3P09JUTHPRqUkMTtVw9BAO0/LSDOzJs9GNzP2f25iZp6CrUJuYoGvQkFpSXBJkU@eQvp/AA "Haskell – Try It Online")
We generate a list of lists of lengths 10, 12 etc. (by taking the appropriate amount of elements from an infinite list) and then replace each element in each such list with corresponding character from the required string.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 14 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
conemon{²«8+×]
```
[Try it here!](https://dzaima.github.io/Canvas/?u=Y29uZW1vbiV1RkY1QiVCMiVBQiV1RkYxOCV1RkYwQiVENyV1RkYzRA__,v=8)
[Answer]
## F#, 71 bytes
```
let d=Seq.iteri(fun i c->System.String(c,10+i*2)|>printfn"%s")"conemon"
```
[Try it online!](https://tio.run/##SyvWTc4vSv3/Pye1RCHFNji1UC@zJLUoUyOtNE8hUyFZ1y64srgkNVcvuKQoMy9dI1nH0EA7U8tIs8auAChQkpanpFqspKmUnJ@Xmpufp/Q/2sY1r6SoMiAfKGkXywUyNjcxM08hsSi9TMGWSwEIUsCkwX8A)
`Seq.iteri` iterates through the sequence and applies the function to the index of the item `i` and the item itself `c`. In this case the string, every character in the string `conemon`.
`System.String` is a shortform of `new System.String`, taking the current letter `c` and repeating it `10+i*2` times, where `i` is the index of the letter. It then prints the string to the output with a new line.
You *can* omit the string and shorten it to:
```
let d=Seq.iteri(fun i c->System.String(c,10+i*2)|>printfn"%s")
```
And this will work with every string. But given this challenge is specifically for `conemon` the string is hard-coded.
[Answer]
# jq, 56 characters
(52 characters code + 4 characters command line options)
```
[[range(5;12)],"conemon"/""]|transpose[]|.[1]*.[0]*2
```
Sample run:
```
bash-4.4$ jq -nr '[[range(5;12)],"conemon"/""]|transpose[]|.[1]*.[0]*2'
cccccccccc
oooooooooooo
nnnnnnnnnnnnnn
eeeeeeeeeeeeeeee
mmmmmmmmmmmmmmmmmm
oooooooooooooooooooo
nnnnnnnnnnnnnnnnnnnnnn
```
[Try it online!](https://tio.run/##yyr8/z86uigxLz1Vw9Ta0EgzVkcpOT8vNTc/T0lfSSm2pgQoV1yQX5waHVujF20Yq6UXbRCrZfT//3/dvCIA "jq – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 48 bytes
```
->{a=4;'conemon'.each_char{|s|puts s*(a=1+a)*2}}
```
[Try it online!](https://tio.run/##KypNqvyfavtf16460dbEWj05Py81Nz9PXS81MTkjPjkjsai6primoLSkWKFYSyPR1lA7UVPLqLb2f6pecmJOjobmfwA "Ruby – Try It Online")
[Answer]
# Pyth, 17 bytes
```
j.e*b+Tyk"conemon
```
[Try it here](http://pyth.herokuapp.com/?code=j.e%2Ab%2BTyk%22conemon&debug=0)
### Explanation
```
j.e*b+Tyk"conemon
.e "conemon For each character 'b' and index 'k' in "conemon"...
*b+Tyk ... get 2k + 10 copies of b.
j Join the result with newlines.
```
[Answer]
## [D](https://dlang.org "The D Programming Language"), 48 bytes
```
foreach(i,c;"conemon")c.repeat(10+i*2).writeln;
```
Explanation:
```
foreach(i,c;"conemon") // Loop over string with index i, char c
c.repeat(10+i*2) // Repeat character 10 + (i*2) times
.writeln; // Write with newline
```
Run with `rdmd`:
```
$ rdmd --eval='foreach(i,c;"conemon")c.repeat(10+i*2).writeln;'
cccccccccc
oooooooooooo
nnnnnnnnnnnnnn
eeeeeeeeeeeeeeee
mmmmmmmmmmmmmmmmmm
oooooooooooooooooooo
nnnnnnnnnnnnnnnnnnnnnn
```
[Answer]
# T-SQL, 84 bytes
```
DECLARE @ INT=1a:PRINT REPLICATE(SUBSTRING('conemon',@,1),2*@+8)SET @+=1IF @<8GOTO a
```
The variable/loop approach turned out shorter than the best set-based variation I came up with (**91 bytes**):
```
SELECT REPLICATE(SUBSTRING('conemon',n,1),2*n+8)FROM(VALUES(1),(2),(3),(4),(5),(6),(7))a(n)
```
I don't know what it is, but I found this question particularly annoying. Which probably means it's a good question.
[Answer]
# [MBASIC](https://en.wikipedia.org/wiki/MBASIC), ~~80~~ 73 bytes
```
1 S$="conemon":FOR I=1 TO LEN(S$):PRINT STRING$(8+I*2,MID$(S$,I,1)):NEXT
```
Saved a loop by using the STRING$ function to generate the string of characters.
Saved another 7 bytes by computing the length relative to the loop index.
Output:
```
cccccccccc
oooooooooooo
nnnnnnnnnnnnnn
eeeeeeeeeeeeeeee
mmmmmmmmmmmmmmmmmm
oooooooooooooooooooo
nnnnnnnnnnnnnnnnnnnnnn
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~27~~ 26 bytes
```
Iµc
¶o
·n
¸e
¹m
±o
±±n<esc>Îä$
```
`<esc>` represents the escape character (ascii 27)
[Try it online!](https://tio.run/##K/v/3/PQ1mSuQ9vyuQ5tz@M6tCOV69DOXK5DG4H8jYc25tmkFifbHe47vETl////umUA "V – Try It Online")
## Explanation
```
I Enter insert mode
µc Write 5 c and a newline
¶o Write 6 o and a newline
·n Write 7 n and a newline
¸e Write 8 e and a newline
¹m Write 9 m and a newline
±o Write 10 o and a newline
±±n Write 11 n
<esc> End insert mode
Îä$ Duplicate every line
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 Thanks to Erik the Outgolfer (pointing me to the [*real* optimal string compressor](https://codegolf.stackexchange.com/a/151721/53748))
...and, of course, to user202729 (for creating it)!
```
“¦[Þ⁷ƥ»J+4×ḤY
```
A full program which prints the output required.
**[Try it online!](https://tio.run/##ASEA3v9qZWxsef//4oCcwqZbw57igbfGpcK7Sis0w5fhuKRZ//8 "Jelly – Try It Online")**
### How?
```
“¦[Þ⁷ƥ»J+4×ḤY - Main Link: no arguments
“¦[Þ⁷ƥ» - compressed string as a list of characters -> ['c','o','n','e','m','o','n']
- (...due to this being a leading constant this is now the argument too)
J - range of length -> [ 1, 2, 3, 4, 5, 6, 7]
4 - literal four
+ - add (vectorises) -> [ 5, 6, 7, 8, 9,10,11]
× - multiply by the argument -> ['ccccc','oooooo',...,'nnnnnnnnnnn']
Ḥ - multiply by 2 (vectorises) -> ['cccccccccc','oooooooooooo',...,'nnnnnnnnnnnnnnnnnnnnnn']
Y - join with newline characters
- implicit print
```
[Answer]
# [J](http://jsoftware.com/), 25 24 bytes
```
echo'conemon'#"0~2*5+i.7
```
[Try it online!](https://tio.run/##y/r/PzU5I189OT8vNTc/T11ZyaDOSMtUO1PP/P9/AA "J – Try It Online")
Note: There are trailing spaces on all lines except the last one.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc) ~~65~~ 64 bytes
```
for(int i=0;i<7;){WriteLine(new string("conemon"[i],i++*2+10));}
```
[Try it online!](https://tio.run/##Sy7WTS7O/P8/Lb9IIzOvRCHT1sA608bcWrM6vCizJNUnMy9VIy@1XKG4pCgzL11DKTk/LzU3P08pOjNWJ1NbW8tI29BAU9O69v9/AA "C# (Visual C# Interactive Compiler) – Try It Online")
thanks to @Jonathan Frech saving 1 byte
`new string(char, int)` repeats the char as often as the int value.
C#, 72 bytes without "Console" as static using (example outside interactive compiler):
```
for(int i=0;i<7;){Console.WriteLine(new string("conemon"[i],i++*2+10));}
```
[Answer]
# Pyth, ~~17~~ 16 bytes
```
V"conemon"*N~+T2
```
Try it online [here](https://pyth.herokuapp.com/?code=V%22conemon%22%2aN%7E%2BT2&debug=0).
```
V"conemon"*N~+T2 Implicit: T=10
V"conemon" For each character in "conemon", as N:
*N T Repeat N T times, implicit print with newline
~+T2 T += 2
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 13 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
╝⌠Ei№‘{ē«L+*P
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTVEJXUyMzIwRWkldTIxMTYldTIwMTglN0IldTAxMTMlQUJMKypQ,v=0.12)
Explanation:
```
╝⌠Ei№‘ push "conemon" - 2 words "cone" and "mon" compressed
{ for each
ē push the value of e (default 0), and increment it (aka e++)
« multiply that by 2
L+ add 10 to that
* repeat the character that many times
P and print it
```
] |
[Question]
[
Use any programming language to display "AWSALILAND" in such a way, so that each letter is in a new line and repeated as many times as its position in the English alphabet. For example letter, (A) should be displayed just once because it is the first letter of the alphabet. Letter D should be displayed 4 times because it is the 4th letter of the alphabet.
So, the output should be this:
```
A
WWWWWWWWWWWWWWWWWWWWWWW
SSSSSSSSSSSSSSSSSSS
A
LLLLLLLLLLLL
IIIIIIIII
LLLLLLLLLLLL
A
NNNNNNNNNNNNNN
DDDD
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~61~~ 59 bytes
```
foreach(var s in"AWSALILAND")WriteLine(new string(s,s-64));
```
[Try it online!](https://tio.run/##Sy7WTS7O/P8/Lb8oNTE5Q6MssUihWCEzT8kxPNjRx9PH0c9FSTO8KLMk1SczL1UjL7VcobikKDMvXaNYp1jXzERT0/r/fwA "C# (Visual C# Interactive Compiler) – Try It Online")
@Kevin Cruijssen Thanks, 2 bytes saved by removing { }
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~18~~ 17 bytes
*-1 byte from @Shaggy*
```
`awÑ¢Ó€`u ¬®pIaZc
```
---
```
`awÑ¢Ó€`u ¬®pIaZc Full program
`awѢӀ` Compressed "awasiland"
u uppercase
¨ split and map each letter
p repeat the letter this many times:
a absolute difference of
Zc get charcode
I and 64
```
[Try it online!](https://tio.run/##ASEA3v9qYXB0//9gYXfDkcKiw5PCgGB1IMKswq5wSWFaY///LVI "Japt – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
```
jm*d-Cd64"AWSALILAND
```
Try it online [here](https://pyth.herokuapp.com/?code=jm%2Ad-Cd64%22AWSALILAND&debug=0).
```
jm*d-Cd64"AWSALILAND
"AWSALILAND String literal "AWSALILAND"
m Map each character of the above, as d, using:
Cd Get character code of d
- 64 Subtract 64
*d Repeat d that many times
j Join on newlines, implicit print
```
**19 byte** alternative, which outputs lower case: `jm*dhxGd"awsaliland` - [link](https://pyth.herokuapp.com/?code=jm%2AdhxGd%22awsaliland&debug=0)
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 112 bytes
```
+++++++[->++>>++>+>++>>+++>+++[<<<]<<]++++>>+>-->++>-->+>-->++>+[[->+>+<<]----[>+<----]>+>[-<.>]++++++++++.<,<<]
```
[Try it online!](https://tio.run/##PYvRCYBADEMHir0JShcp96GCIIIfgvPXRA9D24Twulzzfm73elThU1oAocUIcqS7d44QlmEvpjsiUp8BMkYlk7yzS/MWHb@aT6SqHg "brainfuck – Try It Online")
The actual word generation can probably be optimised further.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 34 bytes
```
"AWSALILAND"|% t*y|%{"$_"*($_-64)}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X8kxPNjRx9PH0c9FqUZVoUSrska1WkklXklLQyVe18xEs/b/fwA "PowerShell – Try It Online")
Takes the string `t`oCharArra`y`, then multiplies each letter out the corresponding number of times. Implicit `Write-Output` gives us newlines for free.
Ho-hum.
[Answer]
# Python 3,41 bytes
```
for i in'AWSALILAND':print(i*(ord(i)-64))
```
# Python 2,40 bytes
```
for i in'AWSALILAND':print i*(ord(i)-64)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes
```
.•DθîRI§•ʒAyk>×u,
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f71HDIpdzOw6vC/I8tBzIPjXJsTLb7vD0Up3//wE "05AB1E – Try It Online")
**Explanation**
```
.•DθîRI§• # push compressed string "awsaliland"
ʒ # filter
Ayk # get the index of the current letter in the alphabet
> # increment
× # repeat it that many times
u # upper-case
, # print
```
We only use filter here to save a byte over other loops due to ac implicit copy of the element on the stack. Filter works here since we print in the loop and don't care about the result of the filter.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~16~~ 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
êôM▄╬æ♠ª+ç█○==.
```
[Run and debug it](https://staxlang.xyz/#p=88934ddcce9106a62b87db093d3d2e&i=)
**Explanation**
```
`'YHu~{YX#`m64-_]* #Full program, unpacked,
`'YHu~{YX#` #Compressed "AWSALILAND"
m #Use the rest of the program as the block. Print each mapped element with a new-line.
64 #Put 64 on stack
- #Subtract current element by 64
_ #Get current index
] #Make a 1 element array
* #Duplicate that many times
```
Saved one byte by figuring out that the "\*" command works with [arr int] and [int arr].
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
EAWSALILAND×ι⊕⌕αι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUBDyTE82NHH08fRz0VJRyEkMze1WCNTR8EzL7koNTc1ryQ1RcMtMy9FI1FHIVMTBKz///@vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
AWSALILAND Literal string
E Map over characters
ι Current character
α Uppercase alphabet
⌕ Find
⊕ Increment
ι Current character
× Repeat
Implicitly print each entry on its own line
```
[Answer]
# [R](https://www.r-project.org/), ~~64~~ 61 bytes
R's clunky string handling characteristics on full display...
-3 thanks to @Giuseppe, who noticed it's actually shorter to *convert a string from utf8 to int and back again* than using R's native string splitting function...
```
write(strrep(intToUtf8(s<-utf8ToInt("AWSALILAND"),T),s-64),1)
```
[Try it online!](https://tio.run/##K/r/v7wosyRVo7ikqCi1QCMzryQkP7QkzUKj2Ea3FEiH5HvmlWgoOYYHO/p4@jj6uShp6oRo6hTrmplo6hhq/v8PAA "R – Try It Online")
[Answer]
# [Scala](https://www.scala-lang.org/) (51 bytes):
```
"AWSALILAND"map(c=>s"$c"*(c-64)mkString)map println
```
# [Scala](https://www.scala-lang.org/) (41 bytes):
```
for(c<-"AWSALILAND")println(s"$c"*(c-64))
```
[Try it online](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFCgUP0/Lb9II9lGV8kxPNjRx9PH0c9FSbOgKDOvJCdPo1hJJVlJSyNZ18xEU/N/7X8A)
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 22 bytes
A more elegant, tacit solution thanks to Adám!
```
(↑⎕A∘⍳⍴¨⊢)'AWSALILAND'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud/UR20TNB61TQSyHB91zHjUu/lR75ZDKx51LdJUdwwPdvTx9HH0c1H//x8A "APL (Dyalog Classic) – Try It Online")
Initial solution:
```
↑a⍴¨⍨⎕A⍳a←'AWSALILAND'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud/UR20THrVNTHzUu@XQike9K4Aijo96NycChdUdw4MdfTx9HP1c1P//BwA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 35 bytes
```
say$_ x(31&ord)for AWSALILAND=~/./g
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVIlXqFCw9hQLb8oRTMtv0jBMTzY0cfTx9HPxbZOX08//f//f/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 23 22 bytes
```
(32!r)#'r:"AWSALILAND"
```
[Try it online!](https://tio.run/##y9bNS8/7/1/D2EixSFNZvchKyTE82NHH08fRz0Xp/38A)
```
r:"AWSALILAND" // set variable r to the string
(32!r) // mod 32 each string in r, the operation will use ASCII number
#' // for each value in the array, take that amount of the corresponding character in the string
```
[Answer]
# Java 11, ~~89~~ ~~83~~ ~~82~~ 81 bytes
```
v->"AWSALILAND".chars().forEach(c->System.out.println(((char)c+"").repeat(c-64)))
```
-1 byte thanks to *@OlivierGrégoire*.
[Try it online.](https://tio.run/##LY7BCoJAEIbvPsXgaZdwT9FFEoQ6BOZFqEN0mKYttXWV3VWI8NltLS8zzM/PfF@NA0b1/TWRQmvhiJX@BACVdtI8kCTk8wkwtNUdiJ3mNfDYZ2Pgh3XoKoIcNGynIUrC9Fyk2SFL810oqERjGReP1uyRSkZRUrytk41oeyc64yFKM8bmHqdVGHJhZCfR@eZmzTmf4pnR9TflGQvqJ9J4TVY4/@F5uQLyv6MWxHSv1KI3Tl8)
**Explanation:**
```
v-> // Method with empty unused parameter and no return-type
"AWSALILAND".chars().forEach(c->
// Loop over the characters as integer unicode values
System.out.println( // Print with trailing newline:
((char)c+"") // The current character converted to char and then String
.repeat(c-64))) // repeated the unicode value minus 64 amount of times
```
[Answer]
# [J](http://jsoftware.com/), 31 bytes
```
echo(#&>~_64+a.i.])'AWSALILAND'
```
[Try it online!](https://tio.run/##y/r/PzU5I19DWc2uLt7MRDtRL1MvVlPdMTzY0cfTx9HPRf3/fwA "J – Try It Online")
## Explanation:
```
echo(#&>~_64+a.i.])'AWSALILAND' - print
# ~ - copy (arguments reversed)
&> - each character (can be "0)
i. - the index of
] - the characters in
a. - the alphabet
_64+ - minus 64 (times)
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 88 bytes
```
S ='AWSALILAND'
L S LEN(1) . X REM . S :F(END)
&UCASE X @Y
OUTPUT =DUPL(X,Y) :(L)
END
```
[Try it online!](https://tio.run/##DYqxCoAgFABn/Yo3pUIEQZMgJGkQvExSydbmqKH/x5wO7u573uu9h1JIAMX0ETQuqJ1hFKtB63gvoIMMu10rA8iZW2cEJU2adLC1jCclW4o@RVAmeeS5PQWRHAWtZyk/ "SNOBOL4 (CSNOBOL4) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 20 bytes
```
'AWSALILAND'"@@64-Y"
```
[Try it online!](https://tio.run/##y00syfn/X90xPNjRx9PH0c9FXcnBwcxEN1Lp/38A "MATL – Try It Online")
### Explanation
```
'AWSALILAND' % Push this string
" % For each character in this string
@ % Push current character
@ % Push current character
64- % Implicitly convert to codepoint and subtract 64
Y" % Repeat that many times. Gives a string with the repeated character
% Implicit end
% Implicit display
```
[Answer]
# [Red](http://www.red-lang.org), 59 bytes
```
foreach c"AWSALILAND"[print pad/with c to-integer c - 64 c]
```
[Try it online!](https://tio.run/##K0pN@R@UmhId@z8tvyg1MTlDIVnJMTzY0cfTx9HPRSm6oCgzr0ShIDFFvzyzBCipUJKvCxRJTU8tAnJ0FcxMFJJj//8HAA "Red – Try It Online")
[Answer]
## Haskell, 43 bytes
```
mapM(putStrLn. \c->c<$['A'..c])"AWSALILAND"
```
[Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZZxsDpAp8NQpKS4JLinzy9BRiknXtkm1UotUd1fX0kmM1lRzDgx19PH0c/VyU/v//l5yWk5he/F83uaAAAA "Haskell – Try It Online")
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 16 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
i|╚┌ž′ø¹‘U{Z⁴W*P
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=aSU3QyV1MjU1QSV1MjUwQyV1MDE3RSV1MjAzMiVGOCVCOSV1MjAxOFUlN0JaJXUyMDc0VypQ,v=0.12)
[Answer]
# T-SQL, 83 bytes
```
SELECT REPLICATE(value,ASCII(value)-64)FROM STRING_SPLIT('A-W-S-A-L-I-L-A-N-D','-')
```
`STRING_SPLIT` is supported by [SQL 2016 and later](https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql).
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-l`, 21 bytes
```
_X A_-64M"AWSALILAND"
```
[Try it online!](https://tio.run/##K8gs@P8/PkLBMV7XzMRXyTE82NHH08fRz0Xp////ujkA "Pip – Try It Online")
```
"AWSALILAND" Literal string
M to the characters of which we map this function:
A_ ASCII value of character
-64 minus 64 (= 1-based index in alphabet)
_X String-repeat character that many times
Autoprint, with each item on its own line (-l flag)
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~96~~ ~~95~~ ~~77~~ 73 bytes
```
*s=L" AWSALILAND";main(i){for(;*++s;puts(""))for(i=*s-63;--i;printf(s));}
```
[Try it online!](https://tio.run/##S9ZNT07@/1@r2NZHScExPNjRx9PH0c9FyTo3MTNPI1OzOi2/SMNaS1u72LqgtKRYQ0lJUxMklGmrVaxrZmytq5tpXVCUmVeSplGsqWld@/8/AA "C (gcc) – Try It Online")
-18 bytes thanks to @ErikF
-5 bytes thanks to @ceilingcat
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~65~~ 63 bytes
```
i=>[...'AWSALILAND'].map(c=>c.repeat(parseInt(c,36)-9)).join`
`
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9mm2lrF62np6fuGB7s6OPp4@jnoh6rl5tYoJFsa5esV5RakJpYolGQWFSc6plXopGsY2ymqWupqamXlZ@Zl8CV8D85P684PydVLyc/XSNNQ1Pz/38A "JavaScript (Node.js) – Try It Online")
**Explanation:**
```
i=> // Prints the result of this function
[...'AWSALILAND'].map(c=> // Loop over the characters
c.repeat( // Repeat the current character
parseInt(c,36)-9))) // Character to alphabetical position
.join`
` // Prints a newline after every new char
```
**Edit:** -2 bytes thanks to @BrianH.
[Answer]
# Julia, 41 bytes
```
[println(l^(l-'@')) for l∈"AWSALILAND"]
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/P7qgKDOvJCdPIydOI0dX3UFdU1MhLb9IIedRR4eSY3iwo4@nj6Ofi1Ls//8A "Julia 1.0 – Try It Online")
[Answer]
# [Swift](https://swift.org), 95 bytes
```
"AWSALILAND".unicodeScalars.forEach{print(String(repeating:String($0),count:Int($0.value)-64))}
```
**[Try it online!](http://jdoodle.com/a/JPk)**
**How?**
```
"AWSALILAND" // Starting string
.unicodeScalars // Convert into a list of unicode values
.forEach { // Loop over each number
print(String( // Create a string
repeating: String($0), // that repeats each character
count: Int($0.value) - 64)) // the unicode value minus 64 (the offset)
}
```
[Answer]
# [Z80Golf](https://github.com/lynn/z80golf), 30 bytes
```
00000000: 2114 007e d640 477e ff10 fd23 3e0a ff7e !..~.@G~...#>..~
00000010: b720 f076 4157 5341 4c49 4c41 4e44 . .vAWSALILAND
```
[Try it online!](https://tio.run/##LYyxCsJAEER7v2LEftm922TVQjwQRAg2FtZq7tIIdilS5NfPlTjF8GYYZtry8HmXWvmvPYKIgtky@lYZak6lCKP0ISJmfnj0DmuimY7nmYg2B@fV8iD@8bTge7YWKo2hiSrQl@5@5pRVsYhAY7rfUnfp0vVU6xc "Z80Golf – Try It Online")
Assembly:
```
ld hl,str ;load address of str
start:
ld a,(hl) ;get current char
sub 64 ;get letter num in alphabet
ld b,a ;store in b
ld a,(hl) ;get current char
print_char:
rst 38h ;print letter
djnz print_char ;repeat print loop b times
inc hl ;increment index of str, to get next char
ld a,10
rst 38h ;print newline
ld a,(hl) ;get current char
or a
jr nz, start ;if current char!=0, keep looping
end:
halt ;end program (if current char==0)
str:
db 'AWSALILAND'
```
[Try it online!](https://tio.run/##hZIxT8MwEIVn51ccU4uUKpFgqGg7RAIkpAoGBkZk19fGxbEj@wqh4r@Hc5SqgqVDFNv3fO97lygZ634jCZbLh5dH@IHCt1TIGLFR9nt2nJcFPzI2UGj8LCJp42DmYcbSrtO91VDbPFIQQiyslxqk1gFjBL8FPs4iyUB3mWChzKe1vWbdDgk2hxDQ8buWIRPxoKDsbsuxaJEIA7hDA2wnbVtLhTQ0UblMVpF8wFRUl1q3wTh6T2umECESG93MxWI4H524oPfuCGetWARskecyyrxvQQGZBmMmjNtw6oTBq4BNMjNOYzeGzoE8JBKH3QljgCy7KjsjnBgcflnj8FIQH0BmYs9jOeYwjDUBbP@orlZlDh@I7UBs3C5Dpzl3LS0lXt5xIr8LsoHpv7urVXnNnyuNSSuYVG@v1fppXT3fT3r@Nfpf "Bash – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 40 bytes
```
"DNALILASWA"v
oa~~<v-*88:<
-:0=?^>$:o$1
```
[Try it online!](https://tio.run/##S8sszvj/X8nFz9HH08cxONxRqYxLIT@xrs6mTFfLwsLKhkvXysDWPs5OxSpfxfD/fwA "><> – Try It Online")
[Answer]
# JavaScript, ~~74~~ 68 bytes
```
for(i in s="AWSALILAND")console.log(s[i].repeat(s.charCodeAt(i)-64))
```
* 74->68, -6B for changing `for` loop to `for...in`, saving bytes on loop statement, removed increment, and removing statement to save the character.
] |
[Question]
[
Good Evening Golfers,
Your challenge, this evening, is logarithmic, and (as Abed would put it) "Meta"
Your goal is to write a program that takes an input from stdin or the command line, and returns the logarithm of that number, in the base of the length of your program in bytes.
So, if your program is 10 bytes, it must return the Log10 of the input number.
Rules:
* Program must be longer then 1 character
* Program must be able to accept floating point input in a form of your choice, or scientific format in a form of your choice with a minimum accuracy of 6 digits
* Program must output to a minimum of 6 digits of accuracy in decimal or scientific format
* Program must be entirely self contained, and must not access any files or network resources.
Your score in the natural logarithm of the amount of bytes in your source code.
Good luck.
[Answer]
## APL 1.0986122886681098
```
3⍟⎕
```
⎕ Requests numerical screen input. Examples of use:
```
3⍟⎕
10
2.0959032742893844
3⍟⎕
1E1
2.0959032742893844
3⍟⎕
○1
1.041978045992186
```
In the last example ○1 represents pi.
[Answer]
## Mathematica: 2.079.. (length in bytes = 8)
```
8~Log~#&
```
Usage
```
8~Log~# &@8
(*
1
*)
```
[Answer]
# bc (with -l) - log(15) = 2.70805
```
l(read())/l(15)
```
[Answer]
# Q (log(16) = 2.772589)
```
16 xlog"F"$(0:)0
```
Example
```
q)16 xlog"F"$(0:)0
16
1f
q)16 xlog"F"$(0:)0
1.6e1
1f
q)16 xlog"F"$(0:)0
13.912231123
0.9495705
```
[Answer]
# Ruby: 2.995732273553991 (`Math.log 20`)
```
p Math.log$_.to_f,20
```
Sample run:
```
bash-4.2$ ruby -ne 'p Math.log$_.to_f,20' <<< 3.14
0.3819509540359265
```
[Answer]
## J, 2.4849066497880003102297094798389 (12 chars)
```
12^.".1!:1[1
```
Usage:
```
12^.".1!:1[1
12
1
```
[Answer]
# Perl: 2.77258872223978 (`log 16`)
```
say log()/log 16
```
Sample run:
```
bash-4.2$ perl -nE 'say log()/log 16' <<< 3.14
0.412691139779226
```
[Answer]
## Tcl, 3.4011973816621555 (log 30)
```
puts [expr log($argv)/log(30)]
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ln(2) = 0.6931471805
```
Zl
```
[Try it online!](https://tio.run/##y00syfn/PwqILQA "MATL – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: [0.693147...](https://tio.run/##yy9OTMpM/f//6L4ivbz//40A) (2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage))
```
.²
```
05AB1E has a 2-byte \$\log\_2{n}\$ builtin. ¯\\_(ツ)\_/¯
[Try it online](https://tio.run/##yy9OTMpM/f9f79Cm//8NDQA) or [verify the inputs in the range [0,3] in increments of 0.1](https://tio.run/##yy9OTMpM/W9kenhuiH5Zpb2SwqO2SQpK9pX/9Q5t@q/zHwA).
Otherwise it would have been 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) instead:
```
3.n
```
[Try it online](https://tio.run/##yy9OTMpM/f/fWC/v/39DAwA) or [verify the inputs in the range [0,3] in increments of 0.1](https://tio.run/##yy9OTMpM/W9kenhuiH5Zpb2SwqO2SQpK9pX/jfXy/uv8BwA).
**Explanation:**
```
.² # Get the logarithm in base 2 of the (implicit) input
# (after which the result is output implicitly)
3 # Push 3
.n # Pop and get the logarithm in base 3 of the (implicit) input
# (after which the result is output implicitly)
```
[Answer]
# Python (`log 38`) score: `3.6375861597263857` <- how embarrassing
```
>>> import math;print math.log(input(),38)
38**8
8.0
```
[Answer]
# Lua 3.5835189384561 (36 38 42 chars)
```
L=math.log;print(L(io.read())/L(36))
```
Sample run:
```
C:...>echo 42 | lua -e "L=math.log;print(L(io.read'*n')/L(36))"
1.0430165662508
C:...>echo 38 | lua -e "L=math.log;print(L(io.read'*n')/L(36))"
1.0150877453695
C:...>echo 36 | lua -e "L=math.log;print(L(io.read'*n')/L(36))"
1
C:...>
```
[Answer]
**Smalltalk** (Pharo 2.0) **(41 ln) 3.713572066704308**
```
Pharo -headless Pharo-2.0.image eval "FileStream stdin nextLine asNumber log:41"
```
No syntactic sugar is Smalltalk's pride, just regular sentence ;)
[Answer]
# Scala - ln(46) = 3.82864...
`print(math.log(args(0).toDouble)/math.log(46))`
`scala log.scala 12.34` -> 0.6563283834264416
[Answer]
# CJam - ln(5) = 1.60943791243
```
rd5mL
```
[Answer]
**JavaScript 69 bytes, score=4.23410650459726**
```
function f(n){return Math.log(n)/Math.log(69);}
```
I counted bytes following this discussion:
<https://stackoverflow.com/questions/2219526/how-many-bytes-in-a-javascript-string>
```
function byteCount(s) {
return encodeURI(s).split(/%..|./).length - 1;
}
```
The number of characters is only 37.
Any advice on counting bytes in code golf?
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 1.38629436112
```
.lQ4
```
[Try it online!](https://tio.run/##K6gsyfj/Xy8n0OT/f1MA "Pyth – Try It Online")
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), score \$\ln(2)=0.693147...\$
```
ļƥ
```
[Try it online!](https://tio.run/##K6gs@f//yJ5jS///NwIA "Pyt – Try It Online")
```
ļ implicit input; log base 2
ƥ prints the top of the stack
```
] |
[Question]
[
(Previously on "Print the \_\_ without using \_\_" ... [this one](https://codegolf.stackexchange.com/questions/36639/the-symbols-vs-the-letters) and [this one](https://codegolf.stackexchange.com/questions/35310/write-the-whole-of-the-holed-using-the-unholed))
The game of [Hearts](https://en.wikipedia.org/wiki/Hearts) has a popular scoring variant called "Shooting the Moon," whereby instead of trying to not acquire penalty cards (and thus penalty points), as is the usual gameplay strategy, if you acquire *all* of the penalty cards you actually score the best that round. We're going to apply that same logic to some code golf.
The ASCII printable characters (plus space) are, in order
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
Let's divide these into three groups:
Alphanumeric:
```
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
```
Symbolic (or non-alphanumeric)
```
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
```
and the space character.
Your task is to use the alphanumeric characters to print the symbolic characters (in any order), with the following restrictions:
* The program/function should take no input and output to STDOUT (or equivalent).
* You can use a symbolic character in your source code for a penalty of +5 per unique character.
* Using the same character more than once does not increase your penalty (e.g., you can use `[` 25 times and only get one +5 penalty)
* Whitespace (including tabs and newlines) in the output or the source code is completely optional. Leading, trailing, inline - no penalties or bonuses. They still count for bytes in source code as usual.
* If you manage to use all 32 symbolic characters in your code, you get a bonus of -100 points for **Shooting the Moon** instead of any penalties.
* If you manage to use all 32 symbolic *and* all 62 alphanumeric characters in your code, you instead get a bonus of -250 points for **Shooting the Sun** instead of any penalties.
* Characters inside literal strings, literal characters, or comments do not count for the bonus or the penalty. (E.g., a Foo program of something like `"!#$%..."` would be allowed, but would not get the bonus or penalty points for the characters inside the literal).
* Literal string or comment *delimiters* do count, however, so something like `// !#$*...` would count the initial `/` for penalty/bonus calculations.
* Yes, this rules out languages like Whitespace or the like, where everything not whitespace is treated as a comment. Bummer.
* Scoring is `bytes of code` + `penalty(ies)` + `bonus(es)`, lowest score wins. Negative scores are possible.
### Example scores:
50 bytes code + (5 unique symbolic characters)\*5 penalty each = 75 points
200 bytes code + (32 unique symbolic characters)\*0 penalty each + (-250 bonus for shooting the sun) = -50 points
[Answer]
# GolfScript, -153
```
{""''!$%&()*+,-./:;<=>?@[\]^_`|~#
}ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
```
Prints
```
{""''!$%&()*+,-./:;<=>?@[\]^_`|~#
}
```
Score:
* 97 bytes of source code: **+97**
* Shooting the Sun: **-250**
[Try it online.](http://golfscript.apphb.com/?c=eyIiJychJCUmKCkqKywtLi86Ozw9Pj9AW1xdXl9gfH4jCn1BQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWmFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6MDEyMzQ1Njc4OQ%3D%3D)
### How it works
Since the code block (lambda, anonymous function)
```
{""''!$%&()*+,-./:;<=>?@[\]^_`|~#
}
```
does not contain any syntax errors, it will be pushed on the stack and printed verbatim if left on it. The linefeed is required to end the comment that `#` started.
Finally, `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789` is an undefined token; it does nothing.
[Answer]
# C++, 310
Well, I started this without realizing that `@` and backticks are totally disallowed in C++ source. Posting it even though it's a very poor entry as it stands, in case anybody knows a way out. Is there a compiler that would allow these characters in symbol names?
```
#include<IOSTREAM>
int main(int bgjkpqvwxyzBCDFGHJKLNPQUVWXYZ$){\
for(char _='!';_<127;++_){_==48?_=58:_==65||_==98-1.?_+=26:!~_^_&_*_%3,""[0];std::cout<<_;}}//
```
* 160 bytes
* 5 \* 30 unique symbolic characters = 150 point penalty
---
# Edit: -90
Leaving the above because it's a little more interesting than the following, which uses an unused `#define` to sneak in the missing symbols.
```
#include<IOSTREAM>
#define bgjkpqvwxyzBCDFGHJKLNPQUVWXYZ !"#$%&'*,-./@[\]^`~
int main(){for(char _=33;_<127;++_){_==48?_=58:_==65||_==97?_+=26:_;std::cout<<_;}}
```
* 160 bytes
* Shooting the sun, -250 points
[Answer]
# CJam, -66
```
{'"#$%&()*.+,-/:!;<=>?@[\]^_`|~}""
```
Prints every symbol exactly once, without any extraneous whitespace.
Score:
* 34 bytes of source code: **+34**
* Shooting the Moon: **-100**
[Try it online.](http://cjam.aditsu.net/#code=%7B'%22%23%24%25%26()*.%2B%2C-%2F%3A!%3B%3C%3D%3E%3F%40%5B%5C%5D%5E_%60%7C~%7D%22%22)
### How it works
Since the code block (lambda, anonymous function) `{'"#$%&()*.+,-/:!;<=>?@[\]^_`|~}` does not contain any syntax errors, it will be pushed on the stack and printed verbatim if left on it.
Since `"` only appears in the character literal `'"`, we also push an emoty string as `""`, which won't affect the output.
[Answer]
# Ruby, -148
```
p %w{!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnoqrstuvxyz}[0]
```
Results in:
```
"!\"\#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
```
Produces an array, takes the special characters and inspects them.
102 (bytes) + 0 (penalty) - 250 (shot the sun) = **-148 points**
[Answer]
# [Befunge-93](http://www.quirkster.com/iano/js/befunge.html), -125
Since having code that is never reached is OK, this is deemed an allowed answer.
```
p>g1g:,"}"`#@_g1+00p #
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
23456789ABCDEFGHIJKLMNOPQRSTUVWX
YZabcdefhijklmnoqrstuvwxyz
```
it's 125 - 250, so -125. I tried to avoid reading the characters in string mode as that seems to violate the rules, but I don't see any violation here. I just read what every character is in the 1st row until it's ascii value is >125. I had to change it a bit to have it run properly in the interpreter
[Answer]
## STATA, -120
```
#d 01256789ABCDEFGHIJKLMNOPQRSTUVWXYZbefgjklmnopqstuvwxyz`!$%&*+,-./:<=>?@[\]^_{|}~'
di "'`!#$%&()*+,-./:;<=>?@[\]^_{|}~"char(34);
```
Abuses the standard STATA interpreter. The `#d` command (short for `#delimit`) changes the delimiter to ; unless whatever follows the command is "cr". But the spec only specifies what happens when what follows is ";" or "cr".
Score:
* 130 bytes of source code: **+130**
* Shooting the Sun: **-250**
[Answer]
# Beam, ~~-34~~ -47
Now that I've fixed my initial misunderstanding, now to try and get some points back:)
```
'''''>`+++++++)--'''''>`@+@+@+vabcdefghi
/+++)++@+@+@+@+@+@\012^ _?Ps)klmopqrtw
+3456789ABv+@+@`<'''++++++++++<!"#$%&*,.
|CDEFGIJKL( ^Z\''''>`+++++)+\=@[]{}~
\+`<'''''@<MNOQRSTUVWXYH@+@+@+@+/:;xyzj
```
Using the same logic for scoring as the [Befunge-93](https://codegolf.stackexchange.com/a/58889/31347) answer. 216 Bytes - 250 Shooting the Sun. Now to see if I can compact it a bit more and improve my logic.
Brief explanation:
[](https://i.stack.imgur.com/nxVhb.png)
```
var ITERS_PER_SEC = 100000;
var TIMEOUT_SECS = 50;
var ERROR_INTERRUPT = "Interrupted by user";
var ERROR_TIMEOUT = "Maximum iterations exceeded";
var ERROR_LOSTINSPACE = "Beam is lost in space";
var code, store, beam, ip_x, ip_y, dir, input_ptr, mem;
var input, timeout, width, iterations, running;
function clear_output() {
document.getElementById("output").value = "";
document.getElementById("stderr").innerHTML = "";
}
function stop() {
running = false;
document.getElementById("run").disabled = false;
document.getElementById("stop").disabled = true;
document.getElementById("clear").disabled = false;
document.getElementById("timeout").disabled = false;
}
function interrupt() {
error(ERROR_INTERRUPT);
}
function error(msg) {
document.getElementById("stderr").innerHTML = msg;
stop();
}
function run() {
clear_output();
document.getElementById("run").disabled = true;
document.getElementById("stop").disabled = false;
document.getElementById("clear").disabled = true;
document.getElementById("input").disabled = false;
document.getElementById("timeout").disabled = false;
code = document.getElementById("code").value;
input = document.getElementById("input").value;
timeout = document.getElementById("timeout").checked;
code = code.split("\n");
width = 0;
for (var i = 0; i < code.length; ++i){
if (code[i].length > width){
width = code[i].length;
}
}
console.log(code);
console.log(width);
running = true;
dir = 0;
ip_x = 0;
ip_y = 0;
input_ptr = 0;
beam = 0;
store = 0;
mem = [];
input = input.split("").map(function (s) {
return s.charCodeAt(0);
});
iterations = 0;
beam_iter();
}
function beam_iter() {
while (running) {
var inst;
try {
inst = code[ip_y][ip_x];
}
catch(err) {
inst = "";
}
switch (inst) {
case ">":
dir = 0;
break;
case "<":
dir = 1;
break;
case "^":
dir = 2;
break;
case "v":
dir = 3;
break;
case "+":
++beam;
break;
case "-":
--beam;
break;
case "@":
document.getElementById("output").value += String.fromCharCode(beam);
break;
case ":":
document.getElementById("output").value += beam;
break;
case "/":
dir ^= 2;
break;
case "\\":
dir ^= 3;
break;
case "!":
if (beam != 0) {
dir ^= 1;
}
break;
case "?":
if (beam == 0) {
dir ^= 1;
}
break;
case "_":
switch (dir) {
case 2:
dir = 3;
break;
case 3:
dir = 2;
break;
}
break;
case "|":
switch (dir) {
case 0:
dir = 1;
break;
case 1:
dir = 0;
break;
}
break;
case "H":
stop();
break;
case "S":
store = beam;
break;
case "L":
beam = store;
break;
case "s":
mem[beam] = store;
break;
case "g":
store = mem[beam];
break;
case "P":
mem[store] = beam;
break;
case "p":
beam = mem[store];
break;
case "u":
if (beam != store) {
dir = 2;
}
break;
case "n":
if (beam != store) {
dir = 3;
}
break;
case "`":
--store;
break;
case "'":
++store;
break;
case ")":
if (store != 0) {
dir = 1;
}
break;
case "(":
if (store != 0) {
dir = 0;
}
break;
case "r":
if (input_ptr >= input.length) {
beam = 0;
} else {
beam = input[input_ptr];
++input_ptr;
}
break;
}
// Move instruction pointer
switch (dir) {
case 0:
ip_x++;
break;
case 1:
ip_x--;
break;
case 2:
ip_y--;
break;
case 3:
ip_y++;
break;
}
if (running && (ip_x < 0 || ip_y < 0 || ip_x >= width || ip_y >= code.length)) {
error(ERROR_LOSTINSPACE);
}
++iterations;
if (iterations > ITERS_PER_SEC * TIMEOUT_SECS) {
error(ERROR_TIMEOUT);
}
}
}
```
```
<div style="font-size:12px;font-family:Verdana, Geneva, sans-serif;">Code:<br><textarea id="code" rows="4" style="overflow:scroll;overflow-x:hidden;width:90%;">'''''>`+++++++)--'''''>`@+@+@+vabcdefghi
/+++)++@+@+@+@+@+@\012^ _?Ps)klmopqrtw
+3456789ABv+@+@`<'''++++++++++<!"#$%&*,.
|CDEFGIJKL( ^Z\''''>`+++++)+\=@[]{}~
\+`<'''''@<MNOQRSTUVWXYH@+@+@+@+/:;xyzj
</textarea><p>Timeout:<input id="timeout" type="checkbox" checked="checked"> <br><br><input id="run" type="button" value="Run" onclick="run()"><input id="stop" type="button" value="Stop" onclick="interrupt()" disabled="disabled"><input id="clear" type="button" value="Clear" onclick="clear_output()"> <span id="stderr" style="color:red"></span></p>Output:<br><textarea id="output" rows="6" style="overflow:scroll;width:90%;"> </textarea><br>Input:<br><textarea id="input" rows="2" style="overflow:scroll;overflow-x:hidden;width:90%;"></textarea></div>
```
[Answer]
# PHP, 154 - 250 = -96
Requires error reporting to be off. I hope I'm not breaking the rules by adding the dead code between `$a=33` and `;$a<65`.
```
<?php #
Z:for($a=33,$ABCDEFGHIJKLMNOPQRSTUVWXYdgijklmnqstuvwxyz_=@``.[!-0/~9%8^3|0&0].''."";$a<65;$a++){echo chr($a+10*($a>47)+26*($a>54)+26*($a>60));}\b;
```
[Answer]
## Tcl, 135-250 = -115
```
set {123456789ABCDEFGHIJKLMNOPQRSTUVXYZbcdhkmqwyz!"#$%&'()*+,-./:;<=>?@[\]^`|~} 0
puts [join [regexp -inline -all {\W+} [info vars]]]_
```
Explanation: Create a variable named `{123456789ABCDEFGHIJKLMNOPQRSTUVXYZbcdhkmqwyz!"#$%&'()*+,-./:;<=>?@[\]^|~}` (basically the entire ASCII sequence minus some alphanumeric characters already in the source) then get the list of all variables in scope (`info vars`) and use regexp to filter out the non-symbols form the resulting list. I believe a variable name qualifies as something that's not a string literal. This is possible because Tcl allows almost any byte sequence for variable and function names (including symbols and even non-printing characters).
Note: Strictly speaking, it's a string literal, which is why it's quoted in `{}` (tcl has two ways of quoting strings: `{}` and `""`). But in tcl, everything is a string literal including the entire program. Tcl is a string-based language after all. So I'm interpreting the "string literal" specification as: "string literal" when used as data.
[Answer]
# Ruby, -126
Nothing in string literals or comments. The output ain't pretty since it's `p`-ing an array of strings, but it's all there.
```
p @bdefgjkoqstuvwyz_BCDHJKLMPQSTUWXYZ=[*32..47,*58..64,*91..96,*123..126].map!{|x|x.chr};+-~0?"":(``%nil<$\>''^ARGF/IO&ENV)#
```
Score:
* Bytes: **+124**
* Shot the sun: **-250**
[Answer]
# FORTH, -118
```
: !#$%&'()*+,-/0123456789=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|} ." !\q#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ " ;
```
Forth names are only delimited by whitespace, so the name is just all the shoot the sun characters minus : ." and ;
* Code: 132
* Shoot the sun: -250
[Answer]
# Batch, -143 bytes
```
@echo !"#$%%&'()*+,-./:;<=>?@[\]^_`{|}~
@goto :a
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZbdfijklmnpqrsuvwxyz
:a
```
* 107 bytes of source code: **+107**
* Shooting the Sun: **-250**
I didn't think this would beat anyone. After all it's batch!
[Answer]
# [Haskell](https://www.haskell.org/), -135
```
main=putStr$!do{(x,y)<-"!:[{"`zip`"/@`~";[x..y]}
veRbOsE#%&*+/:>?@\^|~_0123456789ABCDFGHIJKLMNPQTUVWXYZcfghjklqw'=0
```
Score:
* 115 bytes
* -250 shooting the sun bonus
After re-reading I think dead code was ok so this version is shorter.
The main function is borrowed from @xnor's answer to [this question](https://codegolf.stackexchange.com/a/85728/60340). It basically takes the
endpoints and zips them pairwise to transforms them into ranges, being equal to
```
putStr(concatMap (\(x,y)->[x..y]) [('!','/'),(':','@'),('[','`'),('{','~')])
```
The other line just defines an unused operator `#%&*+/:>?@\^|~` with long parameter names.
`(),;[]`{}"'_` are the special characters that can't be used in operator names but `_` and `'` can be used variable names. The others are all used in the first line.
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oLQkuKRIRTElv1qjQqdS00ZXSdEqulopoSqzIEFJ3yGhTsk6ukJPrzK2lqssNSjJv9hVWVVNS1vfys7eISaupi7ewNDI2MTUzNzC0tHJ2cXN3cPTy9vH1y8gMCQ0LDwiMio5LT0jKzunsFzd1uD/fwA "Haskell – Try It Online")
[Answer]
# MS-SQL, 133 bytes - 250 bonus = -117
```
create TABLE[!"#$%&'()*+,-./:;<=>?@[\]]^_`{|}~](DdfGgHiJkPpQqUuVvWXYZz0123456789 xml)
SELECT NAME FROM sys.objects where name LIKE'!%'
```
Uses a system view specific to MS SQL, so not guaranteed to work on other platforms.
Creates a table with a name consisting of the 32 symbols in order. This is normally invalid for a SQL identifier, but we can make it work by surrounding it by brackets. This name is then retrieved from system view `sys.objects` (assuming that no other tables start with `!`).
Alphanumerics not used elsewhere make up the (unused) xml field name.
Make sure to clean up the table when you are done! (not included in score):
```
DROP TABLE[!"#$%&'()*+,-./:;<=>?@[\]]^_`{|}~]
```
] |
[Question]
[
For example, in traditional web hexadecimal, a certain base-16 number represents an RGB value. For example, 45A19C equals (69,161,156) in RGB.
You'll be converting from that number to RGB value, however, instead you'll be given that number in base-10 rather than base 16.
So in the example used above, 45A19C would equal 4563356 in base-10. Thus 4563356 converted to RGB would equal (69,161,156).
So assume the integer given is previously stored in variable n and is between 0 and 16777215. Take number n and convert it to RGB values between 0 and 255. Return or save in a variable the three values as a list [r,g,b].
[An RGB to RGB int can be found here](http://www.shodor.org/stella2java/rgbint.html). This link converts the opposite of what your trying to do.
Shortest code wins.
If clarification is needed, please ask so I can fix my question to be more helpful.
[Answer]
# AVR ABI, 0
Quantities larger than the registers in the AVR's registers are represented with multiple registers. So, when passing in a 32-bit 'n' to a function, it is passed as 4x8-bit registers. Effectively R(r24),G(r23), and B(r22) are directly addressable without any additional work by virtue of the CPU's register addressing.
Here's some 'C' code for the unpacking operation:
```
unsigned char r( unsigned long n ){return n>>16&255;}
unsigned char g( unsigned long n ){return n>>8&255;}
unsigned char b( unsigned long n ){return n>>0&255;}
```
disassembled examples from avr-gcc 4.8:
```
.global r
.type r, @function
r:
ret
.size r, .-r
.global g
.type g, @function
g:
mov r24,r23
ret
.size g, .-g
.global b
.type b, @function
b:
mov r24,r22
ret
.size b, .-b
```
For red, GCC just emits the return code since the red byte just happens to be in the return register already. For green and blue it copies the corresponding register into the return register and returns. The actual packing/unpacking is handled by the ABI - when done somewhere other than a function call boundary, it's handled purely by the register addressing. Both the copies and return opcode are overhead required to view this happening in the CPU - the compiler can use these registers directly if not required to place the result in the return register. Free RGB packing/unpacking is available when handing any 32-bit integer.
Another way to think about it is that the AVR's registers represent large numbers as a list of 8-bit registers, and that list happens to unpack RGB for us.
[Answer]
# Java ~~35~~ 31 bytes.
Yay!!! A java answer under 40 bytes.
```
new int[]{n>>16,n>>8&255,n&255}
```
Interestingly, java integers are always stored as Binary numbers.
Consequently this snippet returns [69,161,156] whether n = `0x45A19C`, `4563356`, or `0b10001011010000110011100`.
[Answer]
# CJam, 11 bytes
```
NG6#+256b1>
```
This assumes that the base-10 integer is stored in `N` (there are no lower-case variable names), and it leaves the required list on the stack. This simply gets the digits in base 256. To take care of leading zeroes, we first add 2563 = 166. This will always give us 4 digits, the first one being `1`, so at the end we slice off that extraneous digit with `1>`:
```
N "Push N.";
G6# "16^6.";
+ "Add.";
256b "Get base-256 digits.";
1> "Slice off leading digit.";
```
[Test it here.](http://cjam.aditsu.net/) You can use the following framework to initialise `N` and view the stack afterwards:
```
4563356:N;
NG6#+256b1>
ed
```
Of course, if I'm allowed to just have the input on the stack, instead of storing it in `N`, the solution is only 10 bytes, `G6#+256b1>`.
[Answer]
# [Ostrich 0.5.0](https://github.com/KeyboardFire/ostrich-lang/releases/tag/v0.5.0-alpha), 13 bytes
```
n16 6?+256B1>
```
Might as well post this just to promote Ostrich, even though it's essentially the same as @MartinBüttner's. (The only thing I changed was `b` -> `B`, since all built-in functions are either symbols or capital letters in Ostrich, and `G` -> `16` since Ostrich doesn't have that fancy built-in number (which it really should).)
Idential translation to Golfscript (18 bytes):
```
n 16 6?+256base 1>
```
[Answer]
# Mathematica, 22 bytes
```
IntegerDigits[n,256,3]
```
Basically the same as my CJam answer. But I don't know a lot of languages that handle base conversion with arbitrary bases, so I thought I'd post both versions.
This one handles leading zeroes by using `IntegerDigits`' third parameter which pads the result to specified number of digits.
[Answer]
# APL, 8 characters
[`n⊤⍨3⍴256`](http://tryapl.org/?a=n%u21904563356%20%u22C4%20n%u22A4%u23683%u2374256&run)
```
3⍴256 is 256 256 256
B⊤⍨A is A⊤B
A⊤B encodes B in a number system specified by A
It doesn't have to use a uniform radix, e.g.:
365 24 60 60 1000 ⊤ time
```
[Answer]
# Ruby, 25
```
[16,8,0].map{|x|n>>x&255}
```
The javascript answer by @Oriol is valid ruby as well, but at least this uses ruby features... (and it's a byte shorter).
[Answer]
# Rebol - 43 40
```
x: to-tuple to-hex n reduce[x/6 x/7 x/8]
```
Example:
```
>> n: 4563356
== 4563356
>> x: to-tuple to-hex n reduce [x/6 x/7 x/8]
== [69 161 156]
```
Alternative 40 char solution:
```
map-each x[-16 -8 0][(shift n x)and 255]
```
[Answer]
# J (10)
```
(3#256)#:]
```
Demonstration:
```
f=:(3#256)#:]
f 4563356
69 161 156
f 12
0 0 12
```
[Answer]
# C/C++, 31
```
int r=n>>16,g=n>>8&255,b=n&255;
```
Convergently evolved to TheBestOne's answer, with the same size.
# C/C++, 31
```
int c[]={n>>16,n>>8&255,n&255};
```
This one actually makes a list(array). I'm not sure if it would count without "int c[]=". If so, it would be 23 bytes
Also added Uri Zarfaty's optimization to not mask the red channel, as by this point blue and green are already shifted away.
[Answer]
# Erlang, 25 Bytes
```
binary_to_list(<<N:24>>).
```
Using the bit syntax, extracts 24 bits from N, which results in a binary of size 3.
[Answer]
# JavaScript, ~~26~~ 22
```
[n>>16,n>>8&255,n&255]
```
Inspired by [TheBestOne's answer](https://codegolf.stackexchange.com/a/43159/12784). I don't know bitwise operators very much, but it seems to work.
[Answer]
## Python 3, 23 bytes
```
*c,=n.to_bytes(3,'big')
```
If bare expressions are allowed then the following is one byte shorter:
```
[n>>16,n>>8&255,n&255]
```
[Answer]
# Ruby, 44
Not a winner, but this makes use of Ruby's (very useful) optional parameters to `String#to_i` and `Integer#to_s`. They both take a `base`.
```
f=->i{i.to_s(16).scan(/../){|x|p x.to_i 16}}
```
[Answer]
# Python, 28 bytes
The final value is stored in `c`
```
c=[n>>16&255,n>>8&255,n&255]
```
[Answer]
# C - 56 characters, but no calculations required
C doesn't really have lists, but would just like to point out that if you know the architecture (and there are macros to do this for you) you can retrieve RGB with no calculation, just defining types.
Something like this:
```
enum {B, G, R};
typedef union {int i; unsigned char u[3];}T;
```
Then you access like this:
```
#include <stdio.h>
int main(void)
{
T t;
// Set the color
t.i = 0x45A19C;
// Pull out the primaries
printf("%u %u %u\n", t.u[R], t.u[G], t.u[B]);
return 0;
}
```
[Answer]
# dc, 10
dc is a stack-based language so I'm assuming input and output on the stack is OK:
```
256~r256~r
```
[Answer]
# ARM Assembly, 45
```
UXTB r1, r0, 16
UXTB r2, r0, 8
UXTB r3, r0, 0
```
Assuming N is passed in to R0, R1 contains Red, R2 contains Blue, and R3 contains Green. The result list is stored in r1,r2,r3.
Assembles to 12B of ARM instructions or 6B of 16-bit Thumb instructions.
] |
[Question]
[
Your task is to get two numbers, and output the digit sum of them. We'll define digit sum as the following:
* take the **decimal** (base 10) digits of each of them, and pad with 0s the shortest number (e.g. [1,9], [0, 7])
* sum the digits as vectors (e.g. [1, 16])
* convert the number back from base 19, and output it (e.g. 1\*19+16=35)
# Input
You can take the input as two numbers, as a list containing both of them or in any other reasonable format (like an array of digits). You can assume the shortest number is padded with zeros so it fits the length of the longer one
# Output
You can output the digit sum in any reasonable format.
# Test cases
```
1, 2 -> 3
5, 10 -> 24
42, 32 -> 137
15717, 51358 -> 826819
1000, 1 -> 6860
```
explanation of 5, 10: the digits of these are [0, 5] and [1, 0]. Their sum is [1, 5], which when converted from base 19 results in 24.
# Scoring
This is code golf, so the shortest answer wins, good luck!
[Answer]
# [J](http://jsoftware.com/), 6 bytes
```
19#.+/
```
[Try it online!](https://tio.run/##LYy9CsIwAIT3PMVhwSLWmDRN/6CLgpM4uDppm9ZIaKCNFZ@@inG44bv7uMe8oGGHqkSICAzlNxuK/fl4mHkR0PV2XhFy2lHUtp/U4OAsGt1pB6NHN6LVw@giXI2xL9Xg9sbwNGokbUVxKdGBs2VAdT8Rouq7hUCFFhyxxzjxzCB9wUX2a5IY4u/kcZrzwnsy4xkkFzL3W5qn7P/AGPj8AQ "J – Try It Online")
* `19#.` convert the following to base 19...
* `+/` elementwise sum of the input digit lists.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḅ19S
```
A monadic Link accepting a list of lists of digits which yields an integer.
**[Try it online!](https://tio.run/##y0rNyan8///hjlZDy@D///9HG@pYxuooRJvHAgA "Jelly – Try It Online")**
[Answer]
# [Python](https://docs.python.org), 30 bytes
```
lambda a,b:int(a,19)+int(b,19)
```
An unnamed function accepting two strings of (base ten) digit characters which returns an integer.
**[Try it online!](https://tio.run/##LY7BCsMgEETP7VfsbV0qRWMlaSB/0otSpIHGiOQSQr7dumkuu29mWGbTunzmaLqUSxhe5esm/3bgpO/HuAgn9ZNuTJ6phDnXDDyMEYRAjRKwQZIg0DJr9RePhpU5I21b3bJhtbHd6Smljgsk6q@XlLkEg9h2CdtOMNSJ99o3OX4DvIRwbCIqPw "Python 3.8 – Try It Online")**
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-mx`](https://codegolf.meta.stackexchange.com/a/14339/), ~~6~~ 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as an array of digit arrays.
```
ì19
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW14&code=7DE5&input=WwpbMSwwLDAsMF0KWzFdCl0)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
-1 thanks to Command Master.
```
+19β
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f29Dy3Kb//6MNdUx1zHUMdcxjuaJNgbQxkG8RCwA "05AB1E – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 46 bytes
```
f=lambda a,b:a+b and a%10+b%10+19*f(a/10,b/10)
```
[Try it online!](https://tio.run/##HY5NisMwDEb3PoUIDLUnasdymp8W0ouUWdikYQyJY2wz0NOndjZCenr6kH@nv82pfZ/HRa9m0qDR3HVtQLsJ9BfJ2pRCt@@Z6x@SaHIRu139FhLEd2Rs3gIs1r3AugIuMU3W3RkAz1kCc1KEEVbt@etfL3i4l@gXm/jp/DgJkdWQjfnw8@CDdak8gmWPAaF6VnVMgYdxzGmirn6rnRAUnB/QsBaBZGnVlV0VQnNwanpGbU89QktNOxQ2qG6gGyMpZb4ppBs6@QE "Python 2 – Try It Online")
Recursive function that sums each digit pair and convert them to base 19.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes
```
Tr[#~FromDigits~19&/@#]&
```
Unnamed function taking as input a list that contains two lists of digits. The main point here is that converting to base 19 first and then adding means that padding on the left is unnecessary.
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6QoWrnOrSg/1yUzPbOkuM7QUk3fQTlW7X9AUWZeiUNadLVCtaGOqY65jqGOea2CjkK1KZBlDBSxqFWojf0PAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes
```
Total@PadLeft@#~FromDigits~19&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277PyS/JDHHISAxxSc1rcRBuc6tKD/XJTM9s6S4ztBS7X9AUWZeiYJDerRnXklqemoRRMqh2lDHqDaWC5esqY6hAR5pEyMdY3zaDU3NDc11FEwNjU0t8CkzMDDQMayN/f8fAA "Wolfram Language (Mathematica) – Try It Online")
Takes input as list of digits as @my pronoun is monicareinstate suggested and saved 13 bytes (IntegerDigits)
-1 byte @LegionMammal978
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~54~~ ~~53~~ 19 bytes
```
echo $[19#$1+19#$2]
```
[Try the test cases online!](https://tio.run/##NY1BCsIwFET3/xRDzK6o@amhCrU73XoAcRHbYATbSFVsTx9r0M0s5vFmzvbhY22fqO59uPS2RVmK3WEvoqt9gDzyZiY5@6Y@xQkQ1b4NDV7ZgJ9C9PbXm0PvbIMBIwFNmAJIG/MOQg6QI7YVROoXy/9bAknoXGRoMmBFK41cE5uCCxjOzZpYKQWmDw "Bash – Try It Online")
---
The input numbers are passed as two arguments.
Output is on stdout.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~67~~ 65 bytes
Saved 2 bytes thanks to [Mitchell Spector](https://codegolf.stackexchange.com/users/59825/mitchell-spector)!!!
```
s;m;f(a,b){for(s=m=1;a+b;a/=10,b/=10,m*=19)s+=(a%10+b%10)*m;s--;}
```
[Try it online!](https://tio.run/##LY/BjoMgEIbvfYpJExMoYwparQ3LvkjXA2jdeIBuZE9rfHZ3oOXwz8D/zeRnKL@HYd@j9npiFh1fp@fCovFGaSuctmejJLqs/mTUjUdhmC2UFI6En7yOZam33ds5ML4e5vAL9t6DgVUhNAiXCkE1V3WlIqXcdEbcC0meRKipNqpuOrq@gccLqBGqC73WNN5Vbadu2HZt2pJyJjAYqcNHnP8eT/oBP787srgWIlAkoJPIhRYScg89OhKus/OzkDexYzEiFCOUn0lZMfKvcETINLisC1Kq0BsTaXQ7bPs/ "C (gcc) – Try It Online")
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 5 bytes
**Solution:**
```
19/+/
```
[Try it online!](https://tio.run/##y9bNz/7/39BSX1tfw1DBAAStwaSCoeb//wA "K (oK) – Try It Online")
**Explanation:**
Takes input as two lists of digits. Assumes the shorter number is padded with 0s.
```
19/+/ / the solution
+/ / sum
19/ / decode from base 19
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes
```
IΣE²⍘S¹⁹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUDDSEfBKbE4NbgEKJWu4ZlXUFoCZWvqKBhaaoKA9f//hqbmhuYKpobGphb/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as two strings. Explanation:
```
⍘S¹⁹ Convert the input from base 19
E² Repeated twice
IΣ Summed and output in decimal
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 47 bytes
```
?[0q]sZ[sydsxly+0=ZlxA~rlyA~4R+_3Rlfx19*+]dsfxp
```
[Try it online!](https://tio.run/##S0n@/98@2qAwtjgqurgypbgip1LbwDYqp8Kxriin0rHOJEg73jgoJ63C0FJLOzalOK2i4P9/Q1NzQ3MFU0NjUwsuAA "dc – Try It Online")
[Or verify all the test cases online.](https://tio.run/##RYzBCoJAGAbv/1N8LJ2SalcTC7LoUNegYyJh7prBquUWrRC9uiUhXeYwMHNKTN6myR1LXOvqXCcFFgu22W1Zu4r4LTaHyDTSWN04PDxou37Xulm/p3vn6O11ZsV86MTSZPbafiOiNC8qiYdj@x3RM79ohVolEvpSKgJk9QWg0rzCqAQbdB7hEuzvf5LhBZlilGE86YddX6pWwCUfgtPUheeS8AMRwBeePyPBOYegDw)
Input is on stdin (the two numbers on one line, separated by a space).
Output is on stdout.
---
This program makes use of a nice facility in `dc`, where the single-character command `~` will compute **both** the quotient and the remainder in a division operation.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 40 bytes
```
a->b->a.valueOf(""+a,19)+a.valueOf(b,19)
```
[Try it online!](https://tio.run/##ZZBPa8JAEMXvfopBEJK6hqwarFpzLPRQevAoHiYmkbVxE3YnAZF89nSi8R89DLvvN7NvH3PACkeH@LdRxyI3BAfWXkkq896WvX8sLfWOVK7b5i5Da@EblYZzD6Aoo0ztwBISH1WuYjhyz1mTUXq/2QKavXUvowCfnc/Hl6ZknxhxB9dx0fEwhHTV4CiMRiF6FWZl8pM6/f4QhZy7wweKWt0sL@ZK02bLH1JiycKq@xLgDHIuYAa1eAAB42cdCJD@M5iOBUxeRmQwkzMBgZwE7y/c931@fUP1NUuaG3AqNJcwi2sk956IkwJywhZv/K2A6CYkC5PYMiMmqYdFkZ0cdLsLLyByl53J@mQpOXp5SV7BuyPezyAWMIgXXAPdF4BsfLPrntW9turmDw "Java (JDK) – Try It Online")
Takes input as `a:Integer` and `b:String`.
[Answer]
# [PHP](https://php.net/), 75 bytes
```
for($n=strlen($a=$argv[1]);$n--;)$r+=($a[$i]+$argv[2][$i++])*19**$n;echo$r;
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNFTybItLinJS8zRUEm1VEovSy6INYzWtVfJ0da01VYq0bYHi0SqZsdoQOaNYIEdbO1ZTy9BSS0slzzo1OSNfpcj6////Jkb/jY0A "PHP – Try It Online")
As often, getting arguments and dollars makes PHP the longest answer so far :D still i'm content with this
Takes input as strings already padded with zeroes
[Answer]
# [JavaScript (Babel Node)](https://babeljs.io/), 43 bytes
```
f=(a,b)=>a+b&&a%10+b%10+19*f(a/10|0,b/10|0)
```
[Try it online!](https://tio.run/##HYhBDoIwEADvvoIDklYW3AUb9AAfaRrYKhgNUiLGC/J2tF5mMnPnN0/n5218JZZt2yeDu7Tr2pWCwcqy4thGEW8JY@tBp10neE/4QbB/yfXshsn1bdq7q9CaIDOgFRD@dMgg90mqoAIU5eroCxGBjEkfPIq6rBodzrVGs4A3mcUESRWEcyf8Bb/k0ki5Wb8 "JavaScript (Babel Node) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~7~~ ~~6~~ 5 bytes
Takes input as two lists of digits. Assumes the shorter number is padded with 0's.
```
siR19
```
[Try it online!](https://tio.run/##K6gsyfj/vzgzyNDy//9oQx1THXMdQx3zWJ1oUyBtDORbxAIA "Pyth – Try It Online")
```
siR19
R (Right-) Map each digit array of the input to:
i 19 The digit array converted from base 19
s Take the sum
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 24 bytes
```
->a{a.sum{|x|x.to_i 19}}
```
Accepts an array of two strings.
[Try it online!](https://tio.run/##JczNDkNAHATw@z7FxAXpkv1jfRx4kaZpaCkJJV1SDZ5dbXub/DIzr6n47FW6O1m@5K6aumWd19kd@2sDSrZtf9dNW8KakeJRjsq91X032AzIOYoDZ1cNbTPChJPBPHyYRoXqnP/dMjlM@6IPFU4wdMs4QsHK530nDk@LzyQHCR29gAUeh/9z8iNGMqKIQ5IvY22xF8aUMBJCHBstYRyKLw "Ruby – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes
```
~ḃ₁₉ᵐ+
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/XDXznIlBV07BaVyeyD7UduGR01ND3d11j7cOuF/3cMdzY@aGh81dQJ52v//RytEG@oYxeooRJvqGBqAaBMjHWOwgKGpuaG5jqmhsakFmGtgYKBjGKsQCwA "Brachylog – Try It Online")
Takes input as a digit list, but the testing header converts from single integers for convenience.
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 6 \log\_{256}(96) \approx \$ 4.94 bytes
```
z+19Ad
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhbLqrQNLR1TIByo2ILt0YY6pjrmOoY65rFc0aZA2hjIt4iFSAMA)
Takes in the numbers as digit arrays.
## [Thunno](https://github.com/Thunno/Thunno), \$ 7 \log\_{256}(96) \approx \$ 5.76 bytes
```
e19AdES
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhbLUw0tHVNcgyE8qOCCXdHRhjqmOuY6hjrmsToK0aZAhjFQwCI2FqICAA)
Takes in the numbers as digit arrays.
#### Explanations
```
z+19Ad # Implicit input
z+ # Add the digits in the same positions together
Ad # Convert from
19 # base-19
```
```
e19AdES # Implicit input
e E # Map over the input:
Ad # Convert from
19 # base-19
S # Sum the list
# Implicit output
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 4.5 bytes
```
`@19!$_+
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWKxIcDC0VVeK1IVyo6N5opWhDHVMdcx1DHfNYJR2laFMgyxgoYhGrFAtVBAA)
```
`@ Convert from base
19 19
! zip
$ first input
_ second input
+ addition
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~77~~ 72 bytes
```
lambda x,y:sum(n*19**x for x,n in enumerate([*map(sum,zip(x,y))][::-1]))
```
[Try it online!](https://tio.run/##FctBCsMgEEDRq8xylAlEShcRchLrwhIlQp2IVUh6eWu2j//zVfeDHz2sr/5x6b05OOnS35aQpVqkPCEcZRhDZPDcki@uejQyuYwjo1/MOBYhrNF6UlaInkvkigGNotkSmJmeN/8B)
Not one of the shortest approaches, but it works.
*-5 bytes thanks to @ovs*
] |
[Question]
[
**Schlosberg Numbers**
In issue 5 of [Mathematical Reflections](https://www.awesomemath.org/mathematical-reflections/archives/), Dorin Andrica proposed the problem of characterising the positive integers n such that  is an even integer. Eight people submitted correct solutions showing that these are the integers n for which  is even. The published solution was by Joel Schlosberg, so I call them the Schlosberg numbers.
These numbers may be found in OEIS as sequence [A280682](http://oeis.org/A280682).
Your challenge is: given n, output the nth Schlosberg number. (0 or 1 indexed)
The first 50 Schlosberg numbers are:
0
4
5
6
7
8
16
17
18
19
20
21
22
23
24
36
37
38
39
40
41
42
43
44
45
46
47
48
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
100
101
102
103
104
Normal rules and the shortest code wins!
[Answer]
# [Haskell](https://www.haskell.org/), 32 bytes
```
(filter(even.floor.sqrt)[0..]!!)
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzXyMtM6cktUgjtSw1Ty8tJz@/SK@4sKhEM9pATy9WUVHzf25iZp6CrUJBUWZeiYKKQpqNih1IzsQy9v@/5LScxPTi/7rJBQUA "Haskell – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
!fȯ¦2⌊√ΘN
```
[Try it online!](https://tio.run/##yygtzv7/XzHtxPpDy4we9XQ96ph1bobf////TQ0A "Husk – Try It Online")
### Explanation
```
!f(¦2⌊√)ΘN -- 1-indexed number, eg: 4
ΘN -- natural numbers with 0: [0,1,2,3,4,5,6,7,8,9..
f( ) -- filter by
( √) -- | square root: [0,1,1.414213562373095,1.7320508075688774,2,2.23606797749979,2.449489742783178,2.6457513110645903,2.82842712474619,3,..
( ⌊ ) -- | floor: [0,1,1,1,2,2,2,2,2,3,..
(¦2 ) -- | divisible by 2: [1,0,0,0,1,1,1,1,1,0,..
-- : [0,4,5,6,7,8,..
! -- get element: 6
```
[Answer]
# [Python 3](https://docs.python.org/3/), 42 bytes
```
f=lambda n,k=1:n and-~f(n-(k**.5%2<1),k+1)
```
[Try it online!](https://tio.run/##DctBDoMgEAXQtT3FbAyMFSMaN6T2LjQWNejXEDfG4NVp3/7t5zFtaFNy/WLXz2AJpe@1AVkM6nYSSvqiqLq8eWku/VNzclsg0AwKFuNXdjWbR7aHGYd04oJpIqk3Xf/Lpo2C0w8 "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 49 bytes
```
def f(n):
k=(1+(8*n+1)**.5)//4
return n+2*k*k+k
```
[Try it online!](https://tio.run/##FcxNCoAgEAbQfaeY5ThCZT8QQYcJ0hLhMwZbdHqjA7x3v@XKGGs9fKDAMGtDaWNneRFYZ0Ta2XTd1JD68igIdpAkyaYashIognTH6Xnuf3trROE/MvUD "Python 3 – Try It Online")
A slightly different approach. First, if we subtract the sequence 0,1,2,... from the sequence of Schlosberg numbers, we get the sequence 0,3,3,3,3,3,10,10,10,10,10,10,10,10,10,21. Ignoring repetitions, the sequence 0,3,10,21,... is the sequence a(k) = 2k^2+k. If we can find k, the nth Schlosberg number is then n+a(k).
Given k, each a(k) is repeated 4k+1 times. Summing the length of the first k blocks, we get that the kth block of repetition ends at entry n=2k^2-k. Inverting this, we get k=(1+sqrt(8n+1))/4, which gives an explicit formula for k.
[Answer]
# [J](http://jsoftware.com/), 22 bytes
```
{.[:I.0=2|3<.@%:@i.@*]
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8L9aL9rKU8/A1qjG2EbPQdXKIVPPQSv2vyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkKagqnBfwA "J – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 37 bytes
```
function(n)(x=0:n^2)[!x^.5%/%1%%2][n]
```
[Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP08jT1OjwtbAKi/OSDNasSJOz1RVX9VQVdUoNjov9n9xYkFBTqWGoZWpgU6a5n8A "R – Try It Online")
1-based indexing.
[Answer]
## mIRC Scripting, 171 bytes
```
a {
%s = 0
%x = -1
while 1 {
inc %x 2
%i = %x
while %i {
echo - %s
inc %s
dec %i
}
inc %x 2
inc %s %x
}
}
```
I didn't yet see this method for generating new Schlosberg numbers, so above is just a simple one that reads like pseudocode. We start at 0, display **1** number, increase **3**, display **5**, increase **7**, display **9**, etc. A simple pattern emerges.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
½ḞḂ¬Ʋ#Ṫ
```
A full program accepting `n` from STDIN
**[Try it online!](https://tio.run/##ARsA5P9qZWxsef//wr3huJ7huILCrMayI@G5qv//NTA "Jelly – Try It Online")**
### How?
```
½ḞḂ¬Ʋ#Ṫ - Main link: no arguments
# - take input (n) from STDIN & count up (i=0,1,...) collecting truthy results of:
Ʋ - last four links as a monad:
½ - square root
Ḟ - floor (½Ḟ could also be ƽ - integer square root)
Ḃ - bit (modulo by 2 - i.e. isOdd?)
¬ - logical NOT
Ṫ - tail (get the nth rather than the first n)
- implicit print to STDOUT
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 10 bytes
```
e.fiI2s@Z2
```
[Try it here!](https://pyth.herokuapp.com/?code=e.fiI2s%40Z2&input=45&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13&debug=0)
## Explanation
```
e.fiI2s@Z2 – Full program.
.f – Find the first N positive integers satisfying the requirements (var: Z).
e – And take the last one (i.e. the Nth).
@Z2 – Take the square root of Z.
s – Convert to an integer.
iI2 – Check if 2 is invariant over applying GCD with the above (i.e. is it even?)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
µNtóÈ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0Fa/ksObD3f8/29iCgA "05AB1E – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 27 bytes
```
{grep(+^*.sqrt%2,0..*)[$_]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Or0otUBDO05Lr7iwqETVSMdAT09LM1olPrb2f3FipUKahkq8pkJafpFCnKmB9X8A "Perl 6 – Try It Online")
[Answer]
# JavaScript, ~~36~~ 34 bytes
0-indexed
```
n=>(g=i=>i**.5&1||n--?g(++i):i)(0)
```
2 bytes saved thanks to [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)
---
## Test it
```
o.innerText=[...Array(50).keys()].map(
n=>(g=i=>i**.5&1||n--?g(++i):i)(0)
).join`, `
```
```
<pre id=o></pre>
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~11~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Ȭf v}iU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yKxmIHZ9aVU&input=OA)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~45 44~~ 42 bytes
```
->n,i=-1{(i+=1)**0.5%2<1||n+=1while n>i;i}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ9NW17BaI1Pb1lBTS8tAz1TVyMawpiYPyC/PyMxJVcizy7TOrP2vYaCnZ2igqZeamJyhUF2TWaNQoJAWnRlb@x8A "Ruby – Try It Online")
[Answer]
# APL+WIN, ~~29~~ 26 bytes
3 bytes saved thanks to Cows quack
Prompts for integer input:
```
(0,(~2|⌊r*.5)/r←⍳n×3)[n←⎕]
```
Explanation:
```
[n←⎕] prompts for input and selects the nth value of the result
(0,(~2|⌊r*.5)/r←⍳n×3)[n←⎕] create a vector of all results up to n×3
which works up to limit of machine. ×2 works up to n~10E7
```
[Answer]
## [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ḤḶ²Ḷœ^/ị@
```
[Try it online!](https://tio.run/##y0rNyan8///hjiUPd2w7tAlIHJ0cp/9wd7fD////zQE "Jelly – Try It Online")
Unfortunately it's longer than the other answer, but I do like this approach.
### Explanation
The goal is to get the ranges from each even square to each subsequent odd square, excluding the odd square. We can do this by taking the symmetric set difference of some even number of ranges from zero to just below each square.
```
Ḥ Double the input N to ensure it's even.
Ḷ Lowered range, from 0 to 2N-1.
² Square to get the first 2N squares.
Ḷ Get the lowered ranges up to each square.
œ^/ Fold symmetric set difference over the ranges.
ị@ Select the Nth value.
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 81 bytes
Sequence is 1-indexed [f(1) is 0]
```
: f 0 0 begin over s>f fsqrt f>s 1 and 0= - 1 under+ dup 3 pick = until drop 1- ;
```
[Try it online!](https://tio.run/##FYzBDsIwDEPvfIXvqGgV2oVp@xdYklExNSXt@P2SyQdbtvVErb3DJqf1/oBgcL14Sxn6Y0NdBFK/1iBLRcQzE4YZweORie0KOgruKGn9YPaupR1kWhADJicyxuhnUiSn37Crb9OF@x8 "Forth (gforth) – Try It Online")
## Explanation
```
0 0 \ place the loop index and sequence index on the stack
begin \ start an indefinite loop
over \ grab a copy of the loop index
s>f sqrt f>s \ get the square root of the index and truncate
1 and 0= \ determine if result is even
- \ if even, add 1 to sequence tracker (-1 is default for "true" in forth)
1 under+ \ add 1 to the loop index
dup 3 pick = \ check if the current sequence position is the one that was requested
until \ end the loop if condition above is true
drop 1- \ drop the loop index and subtract 1 from the loop index to get the result
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~39~~ 38 bytes
```
->n{(0..n*4).select{|x|x**0.5%2<1}[n]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNATy9Py0RTrzg1JzW5pLqmoqZCS8tAz1TVyMawNjovtvY/SImeqYGmXmpickZ1TWZNgUJadCZQAgA "Ruby – Try It Online")
0-indexed. Instead of simple looping, this approach takes a large enough sequence of numbers and selects only those that fulfill the condition. The particular multiplier `n*4` is necessary to cover the case `n=1 => 4` (`n*n` doesn't fit here), and due to the pattern in the sequence, the value of the nth number fluctuates around `n*2`, so taking `n*4` should always be large enough.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~57~~ 56 bytes
* Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat); golfed `e>=++b*b` to `e/++b/b`.
```
b,e;r(g){for(e=0;g&&++e;b&1&&--g)for(b=0;e/++b/b;);g=e;}
```
[Try it online!](https://tio.run/##JYtLCoQwDEDvIhga0qIyy@hhTI3Bgo6U2Q2evVbcvk8MFmMp4pWzM/yv3@x06tkAiJQFBoAQDB8ulWtHJJ0wsk3KV9nn7XDp/VL1aRz0w3jm7fitrmkX3/hqiBBrfQM "C (gcc) – Try It Online")
[Answer]
These answers are not the most efficient ways to solve the problem, however I do think they are interesting.
# [Haskell](https://www.haskell.org/), ~~37~~ 33 bytes
```
(!!)$do x<-[0,2..];[x^2..x^2+2*x]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P91WQ1FRUyUlX6HCRjfaQMdITy/WOroiDkgDCW0jrYrY/7mJmXm2BUWZeSUquYkFCunRBnp6Rgax/wE "Haskell – Try It Online")
# Haskell, ~~45~~ 42 bytes
```
y#x=not$y^2>x||(y+1)#x
(filter(0#)[0..]!!)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v1K5wjYvv0SlMs7IrqKmRqNS21BTuYIr3VYjLTOnJLVIw0BZM9pATy9WUVHzf25iZp5tQVFmXolKbmKBQjpIwsgg9j8A "Haskell – Try It Online")
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 31 bytes
```
sn_1[d]sD[1+dv2%0=Dzln!<M]dsMxp
```
[Try it online!](https://tio.run/##S0n@b2rwvzgv3jA6JbbYJdpQO6XMSNXA1qUqJ0/Rxjc2pdi3ouB/dEpxXp6pRYCxUUByvGEOUCi2OERBQUG5JLW4RKG4NLMkVaG8KLGgILWIyzAnpELBCEQYgwhDAzDfFESamQHJ/wA "dc – Try It Online") *(1-indexed)*
Rather simple. `D` is a macro that just duplicates the top-of-stack. We begin by storing the user's input in `n`, and placing negative 1 (`_1`) on the stack. Macro `M` increments the top-of-stack by one, duplicates it, and then does the necessary sqrt mod 2 (`v2%`). `dc`'s precision is zero by default, so doing a square root is, by default, actually the floor of the square root. `0=D` compares our `v2%` to zero, and runs our duplication macro (`D`) if true. `z` fetches the stack depth, and then `ln!<M` compares this to `n` (our target), continuing to run `M` until we get to the value we were looking for. Finally, `p`rint it.
[Answer]
# [Tcl](http://tcl.tk/), 84 bytes
```
proc S {x n\ 0 i\ 1} {while \$i<$x {if 1>int(floor([incr n]**.5))%2 {incr i}}
set n}
```
[Try it online!](https://tio.run/##JcqxCoMwFAXQvV9xhwjqULTgUkp/wtFkCpE@SV8kPqkQ8u2xpevhiPWlrDFYjEgHWKMDafQZ6fMi76AVPdSBRDP6J7HUsw8h1hOxjWDTttehaarbN/yAcr5sTsC5CL0d0rrLhn9ezF1jGqEWkzF05QQ "Tcl – Try It Online")
[Answer]
# [Scala 3](https://www.scala-lang.org/), 52 bytes
```
Stream.from(0).filter(n=>math.sqrt(n).toInt%2==0)(_)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY0xCsJAEEV7TzEIwi7iEtRChQgWFhZWYiUiY8xqJDsbN6MikpPY2GjjibyNI1p9Prz__u1ZJphj57Wot8ifMVB9-R779T5NGKaYEVxrAJvUgpOiMGzLAYxCwMtixiGj7VIPYE4ZQyykoAAnzMFKfRzZtnrvrnApOmODdyrSxmY5p0FRPHTIO1MeAivShv2EuNGO40irlf5vm1-fioA9dPvaOCyUFYMXYbJThfxzTlpeq1r1m9zvv_wA)
[Answer]
## JavaScript (ES6), ~~41~~ 40 bytes
```
f=(n,i=0,j=1)=>n<j?n+i:f(n-j,i-2*~j,j+4)
```
```
<input type=number min=0 value=0 oninput=o.textContent=f(this.value)><pre id=o>0
```
Edit: Saved 1 byte thanks to @JonathanFrech.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 39 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4.875 bytes
```
≬√⌊₂l
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJHPSIsIiIsIuKJrOKImuKMiuKCgmwiLCIiLCI1OSJd)
Bitstring:
```
111111000101100000001111100000100100000
```
lol vyncode
] |
[Question]
[
The challenge is this:
You are given a url that is as follows:
`http://sub.example.com/some/dir/file.php?action=delete&file=test.foo&strict=true`
There can be either `http` or `https`, there can be any number of subdomains or directories, and the end file can have any name.
You are to create a full program (that can be compiled/interpreted) that when given a key will return the correct value and if no key is found it will return an empty string.
For example:
```
> https://example.com/index.php?action=delete
...> get(action) #=> delete
> https://this.example.com/cat/index.php?action=delete
...> get(action) #=> delete
> http://example.com, https://action.example.com/actionscript/action.jpg
...> get(action) #=> none
> https://example.com/index.php?genre=action&reaction=1&action=2
...> get(action) #=> 2
```
There are no language restrictions and score is calculated a 1 point for every byte. Smallest score wins.
To clarify:
* You do not need to handle URL encoding
* The script only needs to run once and produce a result
* The script can take any input form: STDIN, Prompt, even passed as a function argument
Example:
Javascript, ~~101~~ 105 bytes
```
function p(k){var m;return((m=location.href.match(new RegExp('.*[&\?]'+k+'=([^&]*).*')))!==null?m[1]:'');}
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), ~~30~~ 27 bytes
```
!`(?<=^\1 .*[?&](.*)=)[^&]+
```
This is a full program that expects the key and the URL to be space-separated on STDIN, e.g.
```
action http://sub.example.com/some/dir/file.php?action=delete&file=test.foo&strict=true
```
This is essentially just a (.NET-flavoured) regex, which matches the correct value by checking that the preceding key is equal to the first string in the input (using a backreference). The only thing that's a bit odd about the regex is that .NET matches lookbehinds from right to left, which is why the "backreference" actually references a group that appears later in the pattern. The `!`` instructs Retina to print the actual match (if there is one) instead of the number of matches.
For those who don't regex, here is an annotated version. Read the lookbehind from the bottom up, because that's how it's processed:
```
(?<= # A lookbehind. Everything we match in here will not be returned as part of
# actual match. Start reading this from the corresponding parenthesis.
^ # Ensure we're at the beginning of the input, so that we've checked
# against the entire input key.
\1 # Backreference to the key to check that it's the one we've asked for.
[ ] # Match a space.
.* # Consume the rest of the URL.
[?&] # Match a ? or a & to ensure we've actually captured the entire key.
( # End of group 1.
.+ # Match the key.
) # Capturing group 1. Use this to keep track of the key.
= # Make sure we start right after a '='
) # Start reading the lookbehind here.
[^&]+ # Match the value, i.e. as many non-& characters as possible.
```
[Answer]
# Pyth - 22 21 18 bytes
Uses the obvious method of constructing a dictionary and using `}` to check existence. Thanks to @FryAmTheEggman for the error handling trick.
```
#@.dcR\=cecw\?\&zq
```
Can probably be golfed a little more. Doing explanation now. Added explanation:
```
# Error handling loop
@ Implicitly print dict lookup
.d Dictionary constructor, takes list of pairs
cR\= Map split with "=" as the second arg
c \& Split by "&"
e Last in sequence of
c Split
w Second input
\? By "?"
q Quit loop
```
[Try it online here](http://pyth.herokuapp.com/?code=%23%40.dcR%5C%3Dcecw%5C%3F%5C%26zq&input=action%0Ahttp%3A%2F%2Fsub.example.com%2Fsome%2Fdir%2Ffile.php%3Faction%3Ddelete%26file%3Dtest.foo%26strict%3Dtrue&debug=1).
[Answer]
# Perl, 25 bytes
```
/[?&]$^I=([^&]*)/;$_=$1
```
This reads the URL from STDIN and the key as an argument to `-i`. It also requires the `-p` switch. I've added two bytes to the count to account for `i` and `p`.
### Example
```
$ perl 2>&- -e'/[?&]$^I=([^&]*)/;$_=$1' -piaction <<< 'http://example.com/?action=delete'
delete
```
[Answer]
# JavaScript (*ES6*) 64
**Edit** Saved 1 byte thx @ismael-miguel
A function with url and key as parameters.
Test running the snippet in Firefox.
```
f=(u,k,e='')=>u.replace(RegExp(`[?&]${k}=([^&]*)`),(m,g)=>e=g)&&e
// TEST
out=x=>O.innerHTML += x+'\n';
test=[
'https://example.com/index.php?action=delete',
'https://this.example.com/cat/index.php?action=delete',
'http://example.com',
'https://action.example.com/actionscript/action.jpg',
'https://example.com/index.php?genre=action&reaction=1&action=2'
]
test.forEach(u=>out('Url '+u+'\nValue ['+f(u,'action')+']'))
```
```
<pre id=O></pre>
```
[Answer]
## Bash - 55 53
*2 bytes saved thanks to izabera*
```
[[ $1 =~ [?\&]$2=([^&]*) ]]
echo ${BASH_REMATCH[1]}
```
Takes the URL as the first arg and the key to find as the second.
```
bash url.sh "https://this.example.com/cat/index.php?action=delete&foo=bar&spam=eggs" spam
```
[Answer]
## Python, 87 bytes
The script takes the first url as the first argument and the key as the second.
```
import re,sys;print re.search(r'[?|&]'+sys.argv[2]+'+=([a-z.]+)',sys.argv[1]).group(1);
```
Sample output:
```
>> runfile('test.py', args='http://sub.example.com/some/dir/file.php?action=delete&file=test.foo&strict=true file')
>> test.foo
```
[Answer]
# PHP 4.1, ~~43~~36 bytes
There's no mention to do not use built-in function, so, here is my go:
```
<?=parse_str(parse_url($U,6))?0:$$P;
```
This restricts the use of the keys `U` and `P` on your URL.
You can pass the data as you please (POST, GET, COOKIE, ...), being the key `U` the url and `P` the parameter.
Thank you, [@manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) for this shorter version!
Also, an alternative, without the previous restrictions:
```
<?=parse_str(parse_url($U,6),$A)?0:$A[$P];
```
---
Old versions:
```
<?parse_str(parse_url($U,6),$A);echo$A[$P];
```
If you are fine with not being able to use the keys `U` and `P`:
```
<?parse_str(parse_url($U,6));echo$$P;
```
[Answer]
# CJam, 22 bytes
```
l'?'&er"&="l*/1>s'&/0=
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=l'%3F'%26er%22%26%3D%22l*%2F1%3Es'%26%2F0%3D&input=http%3A%2F%2Fsub.example.com%2Fsome%2Fdir%2Ffile.php%3Faction%3Ddelete%26file%3Dtest.foo%26strict%3Dtrue%0Aaction).
### How it works
```
l e# Read a line from STDIN.
'?'&er e# Replace question marks with ampersands.
"&="l* e# Place the second line from STDIN between '&' and '='.
/ e# Split the first string at occurrences of the second.
1>s e# Discard the first chunk.
'&/0= e# Discard everything following an ampersand.
```
[Answer]
# Pyth, 25 bytes
```
|smecd\=fqhcT\=zcecw\?\&"
```
Expects the input on two lines, the key followed by the URL.
## Explanation
```
cw\? Split the second input (the URL) by "?"
e The end (the parameter list)
c \& Split the parameter list by "&"
f Filter each parameter T
cT\= Split by "="
h The first part (the key)
q z Equals the first input (the search key)
m Map each valid parameter d
cd\= Split d by "="
e The value
s Print as a string
| " Otherwise, if the key isn't found, print nothing
```
[Try it here](https://pyth.herokuapp.com/?code=|smecd%5C%3DfqhcT%5C%3Dzcecw%5C%3F%5C%26%22&input=foo%0Ahttps%3A%2F%2Fexample.com%2Findex.php%3Faction%3Ddel%26foo%3Dbar%26a%3Db)
[Answer]
# Bash, 37
```
a=${2#*\?};eval "${a//&/;};echo \$$1"
```
Pass the key in the first argument and the URL in the second.
Strips everything off up to and including the first `?`, then treats the remainder as a series of assignments (RFC 1738 URLs can't contain spaces or any of the shell metacharacters, so this works). Finally, print the requested result; by default, strings not found are assumed empty.
Limitation - any key that already exists in the environment may be 'found' when not present in the input.
[Answer]
# Rebol - 97
```
e:["&"| end]p: func[u a][parse u[thru"?"any[copy k to"=""="copy v to e e(if k = a[return v])]]{}]
```
Ungolfed:
```
e: ["&" | end]
p: func [u a] [
parse u [
thru "?"
any [
copy k to "=" "=" copy v to e e
(if k = a [return v])
]
]
{}
]
```
Example usage (in Rebol console):
```
>> p "http://sub.example.com/some/dir/file.php?action=delete&file=test.foo&strict=true" "action"
== "delete"
>> p "https://example.com/index.php?action=delete" "action"
== "delete"
>> p "https://this.example.com/cat/index.php?action=delete" "action"
== "delete"
>> p "http://example.com, https://action.example.com/actionscript/action.jpg" "action"
== ""
>> p "https://action.example.com/actionscript/action.jpg" "action"
== ""
>> p "http://example.com" "action"
== ""
>> p "https://example.com/index.php?genre=action&reaction=1&action=2" "action"
== "2"
```
[Answer]
# Javascript, ~~235~~ ~~228~~ ~~203~~ 190 bytes
Takes the URL as the first input and the key as the second.
```
b=document.createElement('a'),b.href=prompt(u={}),a=b.search;if(a!=""){t=a.substring(1).split("&");for(i=t.length;i--;){p=t[i].split("=");u[p[0]]=p[1]}}c=u[prompt()];alert(c==undefined?"":c)
```
[Answer]
# K, 24
```
{((!)."S=&"0:*|"?"\:x)y}
```
.
```
{((!)."S=&"0:*|"?"\:x)y}["https://example.com/index.php?genre=action&reaction=1&action=2";`genre]
"action"
```
### Explanation:
The function takes two parameters, the url `x` and the key `y`
First we split the url on the `?` character.
```
k)"?"\:"https://example.com/index.php?genre=action&reaction=1&action=2"
"https://example.com/index.php"
"genre=action&reaction=1&action=2"
```
Then we take the last element using `*|` (first reverse)
```
k)*|"?"\:"https://example.com/index.php?genre=action&reaction=1&action=2"
"genre=action&reaction=1&action=2"
```
Process the string using `0:`. The LHS of `0:` is a three character string, where the first is the datatype of the key (`S` for symbol, `I` for int etc), the second is the key-value delimiter (`=` in this case) and the third is the record delimiter (`&` here).
```
k)"S=&"0:*|"?"\:"https://example.com/index.php?genre=action&reaction=1&action=2"
genre reaction action
"action" ,"1" ,"2"
```
Turn this into a dictionary using `!`
```
k)(!)."S=&"0:*|"?"\:"https://example.com/index.php?genre=action&reaction=1&action=2"
genre | "action"
reaction| ,"1"
action | ,"2"
```
Then do a lookup on this dictionary for whichever key you're looking for.
```
k)((!)."S=&"0:*|"?"\:"https://example.com/index.php?genre=action&reaction=1&action=2")`genre
"action"
```
Turn it into a function using `{}` and replace the url string with `x` and the lookup key with `y`, then pass the url and key in as paramters (`func[param1;param2;...;paramN]`)
```
k){((!)."S=&"0:*|"?"\:x)y}["https://example.com/index.php?genre=action&reaction=1&action=2";`genre]
"action"
```
[Answer]
# Gema: ~~44~~ 38 characters
Expects first the parameter name then the URL on separate lines.
```
\B\L*\n=@set{p;$1}
\I$p\=/[^&]+/=$1
?=
```
Sample run:
```
bash-4.3$ gema -p '\B\L*\n=@set{p;$1};\I$p\=/[^&]+/=$1;?=' <<< $'action\nhttps://example.com/index.php?genre=action&reaction=1&action=2'
2
```
[Answer]
# C, 123 bytes
```
char*f(char*s,char*n){for(char*x=n;*s&&(*x||*s!='=');x=*x++==*s++?x:n);return *s=='='?(n=strstr(s++,"&"))?(*n=0)?s:s:s:"";}
```
Note: this function assumes you aren't passing a constant char to it.
[Answer]
# JavaScript, 40 bytes
```
u=>q=>new URL(u).searchParams.get(q)||``
```
[Test it](https://codepen.io/anon/pen/NyaraR)
] |
[Question]
[
**This question already has answers here**:
[Non-Unique/Duplicate Elements](/questions/60610/non-unique-duplicate-elements)
(60 answers)
Closed 5 years ago.
So, I have an array
```
['a', 42, 'b', 42, 'a']
```
I want to alert users to the fact that 42 and 'a' appear in it twice.
```
some_function(['a', 42, 'b', 42, 'a'])
```
should return
```
['a', 42]
```
---
Write some code to extract the duplicates from an array.
* It should accept an array as input.
* The array can have multiple types of object.
* Duplication should be defined as per the language's standard equality function (examples are from ruby).
* It outputs an array of the duplicated items.
* The order of the returned items is irrelevant.
* Duplicates should only appear in the returned array once.
* Golf rules, do it in the smallest number of bytes.
Test cases
```
[1,2,3] => []
[1,2,3,2,1] => [1,2]
[1.0, 2, 2.0, 1.0] => [1, 2] or [1.0, 2.0] or [1, 2.0] or [1.0, 2]
[1, '1', '1.0'] => []
[nil, nil, false, false, true, true] => [nil, false, true]
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
ọ{tℕ₂&h}ˢ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@Hu3uqSRy1THzU1qWXUnl70/3@0oY6RjrGOUklqcYkSkGkIY0Ko2P9RAA "Brachylog – Try It Online")
### Explanation
```
ọ Occurrences
{ }ˢ Select:
&h The elements…
tℕ₂ …which occur at least 2 times
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
{γʒg≠}€н
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/@tzmU5PSH3UuqH3UtObC3v//ow11jHSMgdgwFgA "05AB1E – Try It Online")
**Explanation**
```
{γ # Sort input and split into chunks of identical elements
ʒg≠} # Keeps chunks of length != 1
€н # Map with the first element of each chunk
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 5 bytes
```
{.-Q{
```
[Try it here!](https://pyth.herokuapp.com/?code=%7B.-Q%7B&input=%5B1%2C+2%2C+3%2C+2%2C+1%5D&debug=0)
### How it works?
```
{.-Q{ – Full program.
{ – Deduplicate.
.-Q – And apply bagwise subtraction between the input Q and the above.
{ – Deduplicate the result.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~39~~ 38 bytes
```
lambda l:{v for v in l if~-l.count(v)}
```
[Try it online!](https://tio.run/##bY47C8IwFIV3f8UBh7QQSxudhDo6Orlph1QNFmJSalsQ0b8e01ds0eGe@/jO5d78UV61YkbERyP5LT1zyPWzhtAFamQKEpl4L2Rw0pUqvdp/mbzIVAnhHQgnFCtGQdKh4CTx50C8wUCT2cwtRJTRpTP8EBuRo3YyMQQhhb3AmmybkQ8sgf22t1jUdeO6JdN7IBFpJAjJ3492Wl0oOt1yef@mfVH16hYntpaYDw "Python 2 – Try It Online")
---
# [Python 3](https://docs.python.org/3/), 37 bytes
```
lambda l:[*map(l.remove,{*l})]and{*l}
```
[Try it online!](https://tio.run/##bU/LCsIwELz3KxY8pC2htKknoR49evJWc0hpi0IeJVZBxG@P6cs0KCGzs5lZJts9@4uSuWmLs@FMVDUDvitjwbqQJ7oR6tHgV8zfEWWyHojp9FX2YRuWiCEMW4IBVQthiEbRBqDYwyLTIPhOZJjg3Dl@JHszJ9snz5GkGGwIGapt1kYgFJSG2WO1qVvzUfETAWVogCRF/z91VLLBMOGB8ZsrJ32f0U16vlHy0taH2NW8Pc0H "Python 3 – Try It Online")
[Answer]
# Javascript ES6, 48 bytes
```
a=>[...new Set(a.filter((b,c)=>a.indexOf(b)<c))]
```
Test cases
```
f=
a=>[...new Set(a.filter((b,c)=>a.indexOf(b)<c))];
tests=[
[1,2,3],
[1,2,3,2,1],
[1.0, 2, 2.0, 1.0],
[1, '1', '1.0'],
[undefined, undefined, false, false, true, true],
[1,2,1,1,1,2,1,2,2,1,1]
]
console.log(tests.map(b=>f(b)))
```
[Answer]
# [R], 58 bytes
```
function(x)x[duplicated(x)]
```
(My original code was nonsense.)
This works with an array input (in R an "atomic vector") but all the elements have to have the same type, or will be coerced to the most general type.
This also works with a list input (the only way in R an "array"-ish object can have elements of different types) which is what the challenge seems to want. The list elements can be other lists, atomic vectors, matrices, data frames - anything, really.
But then the "equality" function used by `duplicated` is fairly strict and won't give the same answers as the challenge test cases indicate, which is a flaw in the challenge specs and not this answer.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~13~~ 12 bytes
```
"GX@&)m?6Mvu
```
[Try it online!](https://tio.run/##y00syfn/X8k9wkFNM9fezLes9P//akMdBXVDdRChZ6BeCwA "MATL – Try It Online")
*Thanks to Luis Mendo for saving a byte!*
using `m` is the only way I could use mixed-type equality checking. Takes input as a row cell array.
```
% (implicit input x)
" % for loop:
GX@&) % push input and index, then get x(i) and x(-i),
% where x(-i) means "x excluding element at index i"
m % ismember -- true if x(i) is in x(-i)
? % if true
6M % get x(i)
v % concatenate with prior results
u % and take unique values
% implicit end of if
% implicit end of for loop
% implicit end of program, output results as cell array
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
œ-QQ
```
[Try it online!](https://tio.run/##y0rNyan8///oZN3AwP///0cb6hnoKBgBEYgGcmIB "Jelly – Try It Online")
The last test case (`[None, None, False, False, True, True]`) isn't possible in Jelly.
[Answer]
# [PHP](https://php.net/), 75 bytes
```
function a($b){return array_unique(array_diff_assoc($b,array_unique($b)));}
```
[Try it online!](https://tio.run/##K8go@G9jXwAk00rzkksy8/MUEjVUkjSri1JLSouAnKKixMr40rzMwtJUDQgnJTMtLT6xuDg/GahQB0UBUKOmpnXt/7LEoviU0twCjUSNaPVEdR0FEyMdBfUkGCNRPVZTk4vL3u4/AA "PHP – Try It Online")
[Answer]
# [Javascript (ES6)](https://developer.mozilla.org/bm/docs/Web/JavaScript), 51 bytes
```
a=>[...new Set(a.sort().filter((v,i)=>v===a[i+1]))]
```
[run on tio](https://tio.run/##NYpBCsMgEAC/4s2VmoWWXjef6FFyWNO1WESLinm@TQ@9DMMwbx7c9ho/ffHsJS25PGUGmkyrQ8Qsh3pIB8ZWageDIaYuFWDYaGgdRMQuXq6bMdvcS24lCabyggBOs7bqfrNK@7/8yonznl8).
Try it:
```
a=a=>[...new Set(a.sort().filter((v,i)=>v===a[i+1]))]
console.log(a([1,2,3]));
console.log(a([1,2,3,2,1]));
console.log(a([1.0, 2, 2.0, 1.0]));
console.log(a([1, '1', '1.0']));
console.log(a([null, null, false, false, true, true]));
console.log(a([1,1,1,3,2,3,2,3,4]));
```
[Answer]
# Powershell, ~~38~~ 32 bytes
```
($args|group|?{$_.count-1}).Name
```
[Try it online](https://tio.run/##K8gvTy0qzkjNyfn/X0MlsSi9uCa9KL@0oMa@WiVeLzm/NK9E17BWU88vMTf1////hv@N/hsDsSEA), thanks [AdmBorkBork](https://codegolf.stackexchange.com/users/42963/admborkbork)
using:
1. save the code to a file `get-duplicates.ps1`
2. run `.\get-duplicates.ps1 'a' 42 'b' 42 'a' 42`
Known issues: Powershell supress `$null` value. Result of
```
.\get-duplicates.ps1 $null $null $false $false $true $true
```
is `False, True` without `null`.
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 77 bytes
```
l->{java.util.Set.copyOf(l).forEach(l::remove);return l.stream().distinct();}
```
[Try it online!](https://tio.run/##bZBdb4IwFIbv/RUnJCbtUpvp7kBJzLJdbfGCS@NFxeLKCiXtwYUYfjsroJtmS4DD@ej7vD25OIlZfvjsVFEZi5D7nNeoNH@IJn9qWV2mqEz5b9OhlaLoW6kWzsG7UCWcJwBVvdcqBYcCfTgZdYDC90iCVpXH7Q6EPTo6jAK8XhDLN@WQJYNmDNmq07P4/AtLJPLUVM0mI5ryzNgXkX4QHYZWFuYkaWQl1raEqy1C@cELKi9OaNR20QDb7HOZ4nbnPaB06GB1cQFwnrMFe2rZXerf@U2JPzJY@KePPrkdDtYBG7@Ldqi2I9E7JVfqwAxHMv0B9/dejiMxaO@olF@wtlY0Qycmw7/jwvU56U9TGl0OJ41DWXBTI6/8cjEjwdSFMHXTMmD3Sn5vDDIuqko3/Q5To7VnkucxGus4mmGQXvX7m7STtvsG "Java (JDK 10) – Try It Online")
[Answer]
# [Crystal](https://crystal-lang.org), 42 bytes
```
def f(a)a.reject{|x|a.count(x)<2}.uniq
end
```
[Try it online!](https://tio.run/##bY1BDoMgEEX3nmJiN5gQorit3fcMhgVRSG0NtoiNRjy7BbSNiybwh//fzFDpqTe8XddaSJCIJ5xocReVme1oOam6QRk0Jme6kEE1r0ioep2jMsMU5wyKC5QMOglXZXKK99zdbGPOMp@SFAN1x1dnvhAchVOnYe/wJLjjOxDmV0OcxV5IGv/5WjUthiCSt734FaOHXbehY0tIo4UIXt1m@xATfvPWPuGJJHIuSYrCBcv6AQ "Crystal – Try It Online")
Sometimes, when you can't get the desired results, the problem can be solved... by running your code in a different language.
Initially, I tried solving this in Ruby, but ironically, despite the OP's statement that all test cases correspond to Ruby comparison rules, the above code when run in Ruby actually fails for the third test case, as both `uniq` and array intersection operator use stricter equality checks. However, it passes all tests in Crystal (which shares most of its syntax with Ruby) at the expense of having to declare it as a defined function (`->` proc would be longer in Crystal).
As a bonus, here is the golfier Ruby-only version of the code (doesn't pass test 3):
### [Ruby](https://www.ruby-lang.org/), 33 bytes
```
->a{a.reject{|x|a.count(x)<2}|[]}
```
[Try it online!](https://tio.run/##TY3NDoMgEITvfYpNelATStReiy9COFCD6Y9RQ7XRAM9OF7StCczyzUwWPV0X3zB/qqSRVKuHqkdjZytp3U/dmM7ZpXSWC@fNgRekJGcBrAIuyIZ4i9VCjC7NCZR4wkT4hoApHHsNWyMkkfbvmIiwGpIiCULz5P9jd28JRGlk@1K/Mepp07W7r0T34KiS9c3Yp1rIW7Z2gCFtOJLIGEPD@Q8 "Ruby – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-h`, 7 bytes
```
â £kX â
```
[Try it online!](https://tio.run/##y0osKPn///AihUOLsyMUDi/6/z/aUEcBiIzApDGQEcvFpZsBAA "Japt – Try It Online")
## Explanation:
```
â £kX â
â // Get all unique items from the input
£ // Map X through the results
kX // Remove X from the input
â // Get unique items
-h // Return the last item
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 4 bytes
```
:uDu
```
[Try it online!](https://tio.run/##S0/MTPz/36rUpfR/6qO2if@jDRWMFIyB2DAWAA "Gaia – Try It Online")
`:` duplicates the input, `u` uniquifies it, `D` retrieves the multiset difference between the two and `u` uniquifies the result.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
uṠ-u
```
[Try it online!](https://tio.run/##yygtzv7/v/ThzgW6pf///4821DHUMQJCYx2jWAA "Husk – Try It Online")
**Explanation**
```
-- input, e.g. [2,1,1,3,2,2]
u -- remove duplicates: [2,1,3]
Ṡ- -- subtract this from original list: [2,1,1,3,2,2] - [2,1,3] = [1,2,2]
u -- remove duplicates: [1,2]
```
[Answer]
# [Physica](https://github.com/Mr-Xcoder/Physica), 33 bytes
```
->a:Set@Filter[->e:a.count@e>1;a]
```
[Try it online!](https://tio.run/##K8ioLM5MTvyfZhvzX9cu0So4tcTBLTOnJLUoWtcu1SpRLzm/NK/EIdXO0Dox9n9AUSaQkxZdbWhtZG0MxIa1sf8B "Physica – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 33 bytes
```
nub.((\\)<*>nub)
import Data.List
```
[Try it online!](https://tio.run/##y0gszk7NyfmvnJKalpmXqpCmEPM/rzRJT0MjJkbTRssOyNbkyswtyC8qUXBJLEnU88ksLvmfm5iZp2CrUFCUmVeioKKgkaapEG2oY6RjqGMMJI1i//9LTstJTC/@rxvhHBAAAA "Haskell – Try It Online") Port of my [Husk answer](https://codegolf.stackexchange.com/a/166298/56433).
The point-free version given above is equivalent to `f x=nub$x\\nub x` which is one byte longer.
---
### [Haskell](https://www.haskell.org/), 50 bytes
```
([]#)
a#(x:r)=([x|any(==x)r,all(/=x)a]++a)#r
a#_=a
```
[Try it online!](https://tio.run/##y0gszk7NyfmfpmCrEPNfIzpWWZMrUVmjwqpI01YjuqImMa9Sw9a2QrNIJzEnR0MfyEqM1dZO1FQuAiqLt038n5uYmQfUW1CUmVeioKKQphBtqGOkY6hjDCSNYv//S07LSUwv/q8b4RwQAAA "Haskell – Try It Online") Alternative without imports.
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 32 bytes
```
l=>set(v for v:l if~-l.count(v))
```
[Try it online!](https://tio.run/##KyjKL8nP@59mq/E/x9auOLVEo0whLb9IocwqRyEzrU43Ry85vzQPKKqp@V@Tq6AoE8hO04g21FEw0lEwjtXEFAOThqgyegZgUSMQDeSga1M3VAcRegbqKDJ@@XmpOgoQ0i0xpxhBhRSVQkmghv8A "Proton – Try It Online")
Port of TFeld's Python answer. Could be shorter but `{...}` apparently doesn't work for setcomps.
[Answer]
# [Red](http://www.red-lang.org), 46 bytes
```
func[b][foreach c unique b[alter b c]unique b]
```
Doesn't work for numbers in different representation as float or string.
[Try it online!](https://tio.run/##XYlBDsIwDATvfcUqP2jhxDO4Wj44qS0qVS6Y5P0BURUhDjurnQ2d@1Vn4sEu3ZoXyky2hUq5oaD58miKTLJWDWQUPhT3eyxeYaAkCecJKe8liYfvN2LC6X@/M/4431zxgcn6PFij7eD@Ag "Red – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
═H+U(
```
[Run and debug it](https://staxlang.xyz/#p=cd482b5528&i=[%22a%22,+42,+%22b%22,+42,+%22a%22]&a=1)
Explanation:
```
cu|-uJ Full program, unpacked
cu Copy and make unique
|- Remove each element once
u Make unique again
J Join by space. 'm' would be equally long, but as F has a lower charcode, it can be packed better.
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~23~~ 22 bytes
```
Lmsl`(.+)(?=.+^\1$)
D`
```
[Try it online!](https://tio.run/##K0otycxLNPz/3ye3OCdBQ09bU8PeVk87LsZQRZPLJeH/f2MuIy5DLhBpDAA "Retina – Try It Online") Explanation:
```
Lmsl`(.+)(?=.+^\1$)
```
List duplicated lines. The `m` modifier allows the `^` and `$` to match the start and end of a line in the lookahead. The `s` modifier allows us to look ahead past newlines using just `.+`. The `l` modifier automatically anchors the match to whole lines. I can't use the `p` flag though as the match could be more than one line at once, however the next stage will deal with that.
```
D`
```
Deduplicate that list.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 8 years ago.
[Improve this question](/posts/655/edit)
Write the fastest (best big-O) and smallest multiplication algorithm for positive integers, without using multiplication operators. You are only allowed addition, subtraction, logical functions (AND, OR, XOR, NOT), bit shift, bit rotate, bit flip/set/clear and bit test. Your program should be capable of multiplying 16-bit numbers to produce a 32-bit result. Take input on stdin, separated by commas, spaces or new lines (your choice), but make it clear how to input the data.
**Example input/output:**
```
734 929
681886
```
[Answer]
# C, ~~84~~ ~~83~~ 78 Characters
```
m;main(a,b){for(scanf("%d%d",&a,&b);a;b+=b)a&1?m+=b:0,a>>=1;printf("%d\n",m);}
```
In a more readable form
```
m;main(a,b)
{
scanf("%d%d",&a,&b);
while (a)
{
if (a&1)
m+=b;
a>>=1;
b+=b;
}
printf("%d\n",m);
}
```
The algorithm is better known as the Ethiopian Multiplication or the Russian Peasant Multiplication.Here’s the algorithm :
1. Let the two numbers to be multiplied be a and b.
2. If a is zero then break and print the result.
3. If a is odd then add b to the result.
4. Half a, Double b. Goto Step 2.
[Answer]
## APL (5)
Takes input on standard input separated by newlines.
```
+/⎕⍴⎕
```
[Answer]
## Golfscript - 12 characteres
```
~0\{1$+}*\;
```
Please note that `*` here is *not* the multiplication operator, it's instead a repetition operator, see the second use [here](http://www.golfscript.com/golfscript/builtin.html#%2a).
[Answer]
## Golfscript - 27 chars
Peasants multiplication. There first \* in there *is* a multiply, but only by 0 or 1
```
~2base-1%{1&\..+\@*}%{+}*\;
```
Here's on at 31 chars that doesn't multiply at all
```
~2base-1%{1&\..+\[0\]@=}%{+}*\;
```
[Answer]
# Python, 64 chars
Probably not the most efficient though (or the most compliant, but I'm "adding", aren't I?):
```
a=int(raw_input())
print sum(a for i in range(int(raw_input())))
```
[Answer]
# Ruby, 30
```
->(a){Array.new(*a).inject:+}
```
Based on [GigaWat answer](https://codegolf.stackexchange.com/a/4610/3121).
[Answer]
## Golfscript - 43
```
~\:@;0 1{.3$&{\@+\}{}if@@+:@;.+.3$>!}do;\;
```
Implementation of the [peasant multiplication](http://en.wikipedia.org/wiki/Multiplication_algorithm#Peasant_or_binary_multiplication). I think I may be able to golf it some more later on.
[Answer]
# J, 18 17 characters
```
+/({.${:)".1!:1]3
```
Input needs to be space separated.
[Answer]
# Python, also 64 chars
```
m=lambda x,n:0 if n==0 else x+m(x,n-1);print m(input(),input())
```
[Answer]
## VBA, 70 chars
This is actually quite slow for large numbers, but it's small. I managed to improve the code size while improving speed. Calculation time varies, depending on argument position - not just size. (i.e. 1000, 5000 computes in about 4 seconds while 5000, 1000 calculates in about 19) Since the OP lists both fast and small, I figured I'd go with this one. Input is two numeric args, comma separated.
```
Sub i(j,k)
For m=1 To j:n=n & String(k," "):Next
MsgBox Len(n)
End Sub
```
This longer version (**103 chars**) will ensure it runs with the faster of the two possible arrangements:
```
Sub i(j,k)
If j<k Then a=j:b=k Else b=j:a=k
For m=1 To a:n=n & String(b," "):Next
MsgBox Len(n)
End Sub
```
[Answer]
## Perl: 52 chars
This is an old question, but Perl needs to be represented:
```
perl -pl '($m,$n,$_)=split;$_+=$m&1&&$n,$m>>=1,$n<<=1while$m'
```
(This is the binary algorithm; iterated addition is smaller but *way* too boring.)
This program includes an unintentional feature: if your input line contains a third number, the program will actually calculate A\*B+C.
[Answer]
## A variation in Scala, optimized for size: 48 chars
```
def m(a:Int,b:Int):Int=if(b==1)a else a+m(a,b-1)
```
### optimized for speed a bit:
```
def mul (a:Int, b:Int) : Int = {
print (".")
if (a == 1) b
else if (a > b) mul (b, a)
else if (a % 2 == 0) mul (a >> 1, b << 1)
else b + mul (a - 1, b)
}
```
I swap (a, b) if (a > b), to reach the end more fast. The difference is 11 to 20 steps, when calling mul (1023,31), compared with omitting that line of code.
### golfed: 95 chars:
```
def m(a:Int,b:Int):Int=if(a==1)b
else if(a>b)m(b,a)
else if(a%2==0)m(a>>1,b<<1)
else b+m(a-1,b)
```
[Answer]
# K, 18 16
```
{#,/(!y),\:/:!x}
```
.
```
k){#,/(!y),\:/:!x}[4;20]
80
k){#,/(!y),\:/:!x}[13;21]
273
k){#,/(!y),\:/:!x}[3;6]
18
```
[Answer]
### Ruby, 35 chars
`p $*.map!(&:to_i).pop*$*.inject(:+)`
It's *a program*, which takes input and outputs, not just a function.
```
.-(~/virt)-----------------------------------------------------------------------------------------------------------------------------------------------------(ice@distantstar)-
`--> wc -c golf.rb
35 golf.rb
.-(~/virt)-----------------------------------------------------------------------------------------------------------------------------------------------------(ice@distantstar)-
`--> ruby ./golf.rb 734 929
681886
```
[Answer]
# Ruby, 35 bytes
```
def x(a)Array.new(*a).inject :+end
```
Usage: `x([123, 456]) #=> 56088`
Could probably be shortened if the numbers are read from ARGV, but it complains about them being the wrong format (strings, not ints). Any suggestions would be great.
[Answer]
# Mathematica 12
The following sums `#2` instances of `#1`.
**Code**
```
#1~Sum~{#2}&
```
**Usage**
```
#1~Sum~{#2} &[734, 929]
(* out *)
```
>
> 681886
>
>
>
---
**9 chars?**
If program parameters, `a`, `b`, may be used for input, the same result can be achieved with **9 chars**.
```
a~Sum~{b}
```
[Answer]
# VB11, 101 Chars
```
Dim m As Func(Of Integer, Integer, Integer, Integer) = Function(a, b, t) If(a = 0, t, m(a >> 1, b << 1, t + If(a Mod 2 = 1, b, 0)))
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/3420/edit)
I just looked and saw that there are 399 questions on this wondrous "Programming Puzzles & Code Golf" site!!! That means that...**THIS IS THE 400th question!!!** To celebrate this momentous occasion, here are your goals:
1. Write a piece of code that is **EXACTLY 400 bits**.
* That's right...**BITS**!!!
* For the risk of redundancy and the sake of clarity, that's 50 bytes!!!
2. Because this occasion is so extraordinarily meaningful, each bit and therefore each byte must also be meaningful!
* In other words: You can't just name a variable `aaaaa` because you needed 32 extra bits to get to 400. However, you can rename it to `party` as long as that is a meaningful name for that variable.
3. Your program must do something appropriate (not necessarily output something appropriate) to celebrate this grand occasion!
* For example: You could choose to make a program that outputs `400`. However, I must needs state that although submitting code that does only that would meet this requirement, it would also be like celebrating your birthday party at home by yourself sick in bed. At least you celebrated, but hey: **You can do better!!!**
4. The most creative code wins!!! In this case, creativity will be measured by votes.
5. This contest will last until **400** users have viewed this question. If there is a tie when the 400th user views this question, the contest will go into sudden-death overtime until there is a clear winner
Oh, and lest I forget...**HAPPY 400th QUESTION!!!**
[Answer]
### Python, FOUR HUNDRED bits
```
i=0
while 1:print" "*(i%8>3 and-i%4 or i%4),0;i+=1
```
At first I wanted to make a sine scroller, but there was no place for the import. Now you get a bugged triangle wave. ~~~party~~~
[Answer]
# Brainf\*ck
```
[-]>++++[<+++++++++++++>-]<.----..---------------.
```
And the output will be: 400!
[Answer]
## Ruby
```
1.upto(side=gets.to_i){|i|puts (?**i).center side}
```
This creates a wobbling tree, like the following:
```
*
**
***
****
*****
******
*******
```
[Answer]
### Scala gratulates with 400 Bits:
```
(1 to 400).map(x=>print("""
,
|_|
"""))
```
Sample:
```
,
|_|
,
|_|
,
|_|
,
|_|
```
... due to restrictions, I couldn't light bigger candles. I try to compensate with the scheer number.
[Answer]
### JavaScript, 400 bits
**Code**
```
for(i=0,a='';i<400;)a+='\n!'+i++;alert(a+"\n400!")
```
**Output**
```
!0
!1
!2
!3
..
..
!398
!399
400!
```
Or, how it is read in English: "not 0, not 1, not 2, not 3 .. not 398, not 399, 400!"
**Update**
Just realized I forgot to attach the [Fiddle](http://jsfiddle.net/briguy37/kbRfb/) for this problem!
[Answer]
# HTML
(bad HTML!)
```
<marquee style="font-size:400px">~!400!~</marquee>
```
[Answer]
# Python
50 characters or 400 bits as metered by other submissions.
```
i,j=1,1
while len(str(i))<81:
print i
i,j=j,i+j
```
Simple fibonacci calculator, which terminates once the output no longer fits in a standard 80x60 terminal. Not especially festive I know, but the best I could come up with on short notice. More to follow!
[Answer]
**Here comes C#!**
```
class P{static void Main(){System.Console.Write("400!");}}
```
Ok, that is the smallest, running / valid, and remarkable thing i could squeeze out of .NET! But it fails by 13bytes! (code is 63bytes). Someone might suggest an improvement :D
Maybe using the roman numeral version might slash off an extra byte :-)
```
class P{static void Main(){System.Console.Write("CD!");}}
```
[Answer]
Bits of code, or bits compiled?
Ah well, I see nobody has posted any x86 yet, so here goes...
## x86
```
4D 5A 90 00 03 00 00 00 40 00 00 0F FF F0 00 0B 80 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
```
IDK if this counts, it's the first 400 bits (in hex) of a Win32 PE executable
## VB.NET
```
Sub Main()
Console.WriteLine("400 CodeGolf")
End Sub
```
[Answer]
## Yet another Python answer.
```
k=(1,)
while len(k)<400:k+=(sum(k[-2:]),)
print(k)
```
Print the first 400 Fibonacci numbers. I notice one of the other Python answers also does the Fibonacci sequence... Oh well. I came up with this method of calculating Fibonacci numbers while working on another code golf and I thought it was neat so I figured I'd answer anyway.
[Answer]
## Ada
```
with P;procedure C is begin P("400! Yay!");end C;
```
assuming there is a package *p*:
```
$ cat p.ads
procedure P(S:String);
$ cat p.adb
with Ada.Text_IO;
procedure P(S:String) is
begin
Ada.Text_IO.Put_Line(S);
end P;
```
If I put `with Text_IO;` and `Text_IO.Put("")` into the source code I would already exceed the limit by 7 bytes, without outputting anything.. Ada is hard to golf.
[Answer]
**Shells with [banner](http://en.wikipedia.org/wiki/Banner_%28Unix%29) installed**
```
banner -w80 HAPPY HAPPY HAPPY 400th QUESTION!
```
[Answer]
# Perl
```
$number_400=400;
$and_still_number_400=$still_number_400*4/4;
$when_is_the_500_post="In 100 posts!!";
print $number_400*400/400;
# # ########## ##########
# # # # # #
# # # # # #
######## # # # #
# # # # #
# # # # #
# # # # #
# ########## ##########
```
[Answer]
Perl /\*Life:Eat,sleep,then die \*/
```
$rip=400;$pork="Pi";chop($pork);sleep($rip);die();
```
] |
[Question]
[
**PROBLEM**
For a list of numbers, `list`: Find the *lowest possible* integer, `x`, which is optimally close to the whole number even-harmonics of the values in list.
* `list` has a length of n, and all of the values in list are <= 2000
* `x` has a precision of 1.0 (integers only), and must be a value in the range [20, 100]
* An even-harmonic is a number that is divisible by `list` an even number of times. 20 is an even harmonic of 80 (because 80/20=**4**) -- but an odd harmonic of 60 (because 60/20=**3**).
* In this case, "optimally close" simply means to minimize the absolute cumulative remainder, relative to the nearest even harmonic of the input value(s).
+ Minimizing the absolute cumulative error takes priority over choosing the "lowest allowable value" for `x`.
+ Given `list = [151, 450, 315]` and a candidate guess of `x=25` the absolute cumulative remainder is 0.64 because 25 goes into `list` [6.04, 18, 12.6] times, respectively. The nearest even-harmonics for each instance are [6, 18, 12].
**EXAMPLE**
`list = [100, 300, 700, 1340]`
* `x = 20` is a bad solution because it is an exact or almost-exact odd-harmonic of all of the values of `list`. The number 20 goes into `list` [5, 15, 35, 67] times, respectively (odd numbers = odd harmonics = the opposite of even-harmonics).
+ The absolute cumulative remainder is 4.0 in this case (which is the maximum possible error for this instance of `list`).
* `x = 25` is a *good* solution, but not the best, because it is a exact or almost-exact even-harmonic of all of the values of list. In this case, 25 is an exact even-harmonic in all cases except for 1340. The number 25 goes into `list` [4, 12, 20, 53.6] times, respectively (even numbers).
+ The absolute cumulative remainder is 0.4 in this case.
**BONUS**
Same prompt and problem, except x has a maximum precision of 0.1 (non-integer)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
÷Ɱȷ2Ḃ2_«Ɗ§Ụ>Ƈ19Ḣ
```
A monadic Link that accepts a list of integers and yields an integer.
**[Try it online!](https://tio.run/##y0rNyan8///w9kcb153YbvRwR5NR/KHVx7oOLX@4e4ndsXZDy4c7Fv3//z/a0MBAR8EYRJiDCENjE4NYAA "Jelly – Try It Online")**
### How?
```
÷Ɱȷ2Ḃ2_«Ɗ§Ụ>Ƈ19Ḣ - Link: list of integers, A
ȷ2 - 10^2 = 100
Ɱ - map across x in [1,100] with:
÷ - A divided by x (vectorises)
Ḃ - mod 2 (vectorises)
Ɗ - last three links as a monad - f(v=that):
2 - two
_ - subtract v (vectorises)
« - minimum with v (vectorises)
§ - sums
Ụ - grade-up (one-based indices sorted by the value at that index)
Ƈ - filter keep if:
> 19 - greater than 19
Ḣ - head
```
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, ~~83~~ ~~78~~ 77 bytes
```
[ 20 100 [a,b] [ v/n [ 2 mod dup 1 > 2 0 ? - abs ] map Σ ] with infimum-by ]
```
[Try it online!](https://tio.run/##JY5NCsIwEIX3nuIdQGvSHwQFdSdu3Iir0kXajhq0aU3SShFP4328Uh118YY373swc1SFr@1w2G93mzkq5c@BVeZE7u87@mKHC1lD11/2B63RRV0SHN1aMgX3G0ve943VxmMxGj0ghUDEmrFkFAs8v2EiEScMZILnkCIUv16qxnmGFN3U8AxR1SXKtoHEkjeBFSZQuUPG1xu8X2zumn/R5qirtprkPbIh12sEDsWVlB0@ "Factor – Try It Online")
* `20 100 [a,b]` Create a range from 20 to 100, inclusive.
* `[ ... ] with infimum-by` Find the number in the range that is smallest when `[ ... ]` is applied to it. `with` takes our input into the `[ ... ]` in such a way that it will be underneath each number in the range on the data stack.
* `v/n` Divide each element in the input by the current number in the range.
* `[ ... ] map Σ` Map each element to a new value with the `[ ... ]` quotation and then take the sum.
* `2 mod dup 1 > 2 0 ? - abs` Find the distance to the nearest even number.
[Answer]
# JavaScript (ES6), 79 bytes
```
a=>(m=g=o=>x++>99?o:g(a.map(v=>e+=(v/=x)&1?1-v%1:v%1,e=0)|e>m?o:(m=e,x)))(x=19)
```
[Try it online!](https://tio.run/##FYtBCsMgEAC/0kvLLppUSaEYWPOQ0oOkRlpiNiRFPPTv1hxmTjMfl9w@bu/12yz88mWi4shCpEBMNgthjRm4D@Da6FZIZL0gSFfKeNGDbtJZ9xXpSeHP21jbOnuZEREyaYNl5GXn2bczB5jgoZWSp@7Q/ZDubuqJWP4 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~75~~ 73 bytes
```
lambda l:min(range(20,101),key=lambda x:sum(min(a/x%2,-a/x%2)for a in l))
```
[Try it online!](https://tio.run/##NU7NzoIwELzzFHsx7SY1tkBjQlJfBDn0w0WJUAmtCUp4drTEbw@zPzO7s8Mr3B4uWxtzXjvb/10sdEXfOj5adyWeSqGkQnGnl/nRU@GfPY8Se5h2qdhvCZvHCBZaBx3iGsgHDwZ4qaQUkEU4RlBZLisBpdJKQK4jp3SFCU0D1YEucSfVX7HGpL5Rfacxjtj5mR7zmgnYKpUxTKJhEBQt3@3AN0sB/4ewSOAb8YmGB9yaYWxd4A2bwwL7E8x@gflnUpIxvloYrh8 "Python 3 – Try It Online")
*Saved 2 bytes thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)!!!*
Inputs a list of integers.
Returns the lowest even harmonic.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 49 bytes
```
bc20 100r@)td{?/{JR_2./2.*.-ab}ms}Z]ziq[~<m-]20.+
```
[Try it online!](https://tio.run/##SyotykktLixN/V@U@D8p2chAwdDAoMhBsySl2l6/2iso3khP30hPS083Mak2t7g2KrYqszC6ziZXN9bIQE/7//9oQ1NDHQUTUwMdBWND01gA "Burlesque – Try It Online")
```
bc # Repeat input list
20 100r@ # Range [20..100]
)td # As doubles
{
?/ # Divide each
{ # -- Find difference with nearest 2
J # Duplicate
R_ # Round
2./2.* # Closest multiple of 2
.- # Difference
ab # Abs
}
ms # Map sum
}Z] # Zip range with input and evaluate
zi # Zip indices
q[~<m-] # Index of minimum
20.+ # +20
```
[Answer]
# [R](https://www.r-project.org), 72 bytes
```
\(l,m=20:200,x=outer(l,m,`/`)%%2/2)m[order(colSums(abs(x-round(x))))[1]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHOnPzy1OKS-My8kvjUstS8-IzEotz8vMxk26WlJWm6Fjc9YjRydHJtjQysjAwMdCps80tLUotAQjoJ-gmaqqpG-kaaudH5RSlA0eT8nODS3GKNxKRijQrdovzSvBSNCk0giDaMjYWal4bLQo1kDUNTQx0FE1MDHQVjQ1NNTQVlBXNTLnzqDUBKQYQ5iDA0NjEA6zIy5YLYtmABhAYA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 19 bytes
```
20₁ṡµ⁰$/:1%$∷1=+∑;h
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIyMOKCgeG5ocK14oGwJC86MSUk4oi3MT0r4oiRO2giLCIiLCJbMTAwLCAzMDAsIDcwMCwgMTM0MF0iXQ==)
*-2 bytes thanks to emanresu A, and another -3 by porting 05AB1E*
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
≔E⁸¹Σ↔⊖﹪⊕∕θ⁺²⁰ι²ηI⁺²⁰⌕η⌊η
```
[Try it online!](https://tio.run/##Rc47C8IwFAXg3V@R8QYimGpB6FRaBIdCwbF0iE0wF/LQPPr3Y3XQ6cDhg3MWLcLihSmljREfDgbxhDNn5JYttPfoTU4KerUEZZVLSsLgZTYeru5f9biiVPBiZDQ5QnVgBCmljFT0G5o2uzGgS9CJmOCHLugkaEYGdGi3Pf3htCllmni9fTjVGzryep7LfjVv "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⁸¹ Literal integer `80`
E Map over implicit range
θ Input array
∕ Vectorised divide
ι Current value
⁺ Plus
²⁰ Literal integer `20`
⊕ Vectorised increment
﹪ Vectorised modulo
² Literal integer `2`
⊖ Vectorised decrement
↔ Vectorised absolute
Σ Take the sum
≔ η Store in variable
η List of absolute cumulative errors
⌊ Find the minimum
⌕ Find index in
η List of absolute cumulative errors
⁺ Plus
²⁰ Literal integer 20
I Cast to string
Implicitly print
```
[Answer]
# APL+WIN, 43 bytes
Prompts for vector of numbers in list
```
(m=⌊/m←+/¨|¨m-⌊¨m+1≤¨2|¨m←(⊂⎕)÷¨n)/n←19+⍳81
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv0au7aOeLv1coIi2/qEVNYdW5OoCBYCUtuGjziWHVhiBhICyGo@6moB6NQ9vP7QiT1M/D2SEpfaj3s0Whv@BJnH9T@MyNDVUMDE1UDA2NOUC8gyALCA2B2JDYxMDLgA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 80 bytes
```
a=>Enumerable.Range(20,81).OrderBy(x=>a.Sum(k=>Math.Min(2-k/x%2,k/x%2))).First()
```
[Try it online!](https://tio.run/##dY27CsIwAEV3vyKLkECMSR8o2GQQLDgURUdxiG2qoTZC2mBF/PbY6uDkcu5wX3kzyRvtU2fyZL0yrlZWnq4qKW6uF4GBNq0AJeBecvHzyU6as4IBxXOGyMYWyi4fsONCkr2rYcVFJtsLybSBwaSaduMAf4gQIqm2TQuRX4y2tl@HJTTqDr6Hh@OTUYpBOGA2gIURfSH0LxwzDKJ4aLB4iPk3 "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
20тŸΣ/D1%sÉ+O}н
```
[Try it online](https://tio.run/##yy9OTMpM/f/fyOBi09Ed5xbruxiqFh/u1PavvbD3//9oQ1NDHQUTUwMdBWND01gA) or [verify both test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf@NDC42Hd1xbvGhdcX6LoaqxYc7tf1rL@z9r/M/OtrQ1FBHwcTUQEfB2NA0Vkch2tAAxAYR5iDC0NjEIDYWAA).
**Explanation:**
```
20тŸ # Push a list in the range [20,100]
Σ # Sort it by:
/ # Divide the (implicit) input-list by this value
D # Duplicate the decimal values
1% # Modulo-1 to only keep the decimal portion
s # Swap so the entire values are at the top again
É # Check which ones are odd (ignoring the decimal portions)
+ # Add the values at the same positions together
O # Sum this list together
}н # After the sort-by, keep just the first element
# (so `Σ...}н` basically acted as a minimum-by builtin)
# (which is output implicitly as result)
```
[Answer]
# C, 122 bytes
```
i,j,k;f(n,m)int*n;{float a=m,b,c;for(i=19;99/i++;k=b<a?a=b,i:k)for(j=b=0;j<m;b+=fabs(c-rint(c))*2)c=n[j++]/2./i;return k;}
```
[Try it online!](https://tio.run/##VZBdb8IgFIavy684cXGBFrX1I4ujuB/ivKC0KG2hC61bMuNfXwfuI/HiBPKclwcOcnaUchw1rWnDFLbUEG2H2LKLajsxgOCGFlQy1TmsebZl2@1CJwlreJGLF8ELqp8bEro1L3jK6tywIuFKFD2WM@ddWBISL4nkdl8nyWGxnC80c9VwdhYadh0ftJXtuawg74dSd/PTDt2hVheBIa9CRmiL3ztdEnRBkSdgKMQWOKQUHEMo@jjptgLcS2EVnkzLCYVHQ2AHKQF/JApZV4m27aQfFgzE0OvPqlNeQ4Ig8rMADmodtMwvORgGSaJ/DNGd2@71wZ/z@C0Me@PgG//8GpzOq9Ttvhv7i852MC1frY@7wENUuarCPy/5/aOUoeu4gmyTwXqTwirboDVkqd/5evKVrdbpl1StOPbjrDXf "C (gcc) – Try It Online")
### Bonus:
# C, 134 bytes
```
i,j,k;float f(n,m)int*n;{float a=m,b,c;for(i=199;999/i++;k=b<a?a=b,i:k)for(j=b=0;j<m;b+=fabs(c-rint(c))*2)c=n[j++]/.2/i;return k/10.;}
```
[Try it online!](https://tio.run/##VZDbTsMwDIav26ewJg0lPaztDkIly3iQwUWaNSNtk6J0gMS0V6c4LSBxYTn67f@zHZmepRxHnTRJy1TXiwsoYhNDtb1Ell1nSXCTVIlkqndE86IsWVmWmY5j1vJqLx4FrxL90FJfb3jFc9bsDatirkQ1EJk6pBFJabSmkttjE8fP2Wqdaebqy5uz0GZFvmK3EdtCI7Ql770@0fAaBqiASSCywCFnYTDv41gYBh8vuquBDFJYRRbL0yKBO0PhADkFdAbe4mrRdb3Ei8BABIP@rHuFNOoBAa4LxE/QEx3THgyDONYzIfjHtkf9jD6UX/09kw5Y@NNvnukQpaZ5k/bbmh5guSrUk0WD8xXfrFxdk3mXn4/AE2/jBopdAdtdDptiF26hyPGFcY9RbLb5l1SdOA9j2plv "C (gcc) – Try It Online")
] |
[Question]
[
A set of whole numbers (0-) will be given separated by a space. Some numbers will be missing between certain numbers in the set. Your job is to find the missing odd numbers between them.
## Conditions
1. The input will be a one line string.
2. Your code must left out a variable for inserting the input case
string.
3. The output should be a **string** containing all the missing odd
numbers in the set of numbers given as input.
4. **The numbers of the output must be separated by a comma - `,`**.
5. No extra characters should be included in the output.
6. If there are no odd numbers missing, the code should print out
`null` or a blank line.
Here are some sample inputs and outputs according to its order :
## Input
```
4 6 8 10
5 15 18 21 26
2 15 6
1 20
1 3 5 7 9
```
## Output
```
5,7,9
7,9,11,13,17,19,23,25
3,5,7,9,11,13
3,5,7,9,11,13,15,17,19
null
```
The winner will be decided by the Code length.
**The calculation of code length won't include the variable that is left for the test case.**
[Answer]
# Ruby, 74
```
s="insert your numbers here" # this line not counted per the rules
n=s.split.map &:to_i
puts (n.min..n.max).select{|x|x%2==1&&!n.index(x)}*?,
```
Output is identical to examples in question except that it outputs a blank line for no numbers found.
[Answer]
## GolfScript (20 chars)
```
~]$),\(),+-{1&},','*
```
[Online demo](http://golfscript.apphb.com/?c=IyBUZXN0IGZyYW1ld29yawo7JzQgNiA4IDEwCjUgMTUgMTggMjEgMjYKMiAxNSA2CjEgMjAKMSAzIDUgNyA5J24vewoKIyBQcm9ncmFtCgp%2BXSQpLFwoKSwrLXsxJn0sJywnKgoKIyBNb3JlIHRlc3QgZnJhbWV3b3JrCnB1dHN9Lw%3D%3D)
Dissection:
```
~]$ # Eval the string, wrap the resulting integers in an array, sort
), # Extract the max and make an array A of 0 to max-1 inclusive
\(), # Extract the min and make an array B of 0 to min inclusive
+- # Combine B with the remaining numbers from the input and remove them from A
{1&}, # Filter A to odd numbers
','* # Comma-separate
```
[Answer]
## Python, 82 chars
```
N=map(int,I.split())
R=','.join(`x`for x in range(min(N)|1,max(N),2)if x not in N)
```
Set `I` to your input string, `R` is the output string.
[Answer]
# Groovy, ~~92~~ ~~79~~ 72 chars
```
x=args; //Input does not count
x=x*.toInteger();print((x.min()..x.max()).minus(x).grep{it%2}.join(","))
```
[Answer]
# C#, 205 characters: 222 (total count) - 17 (total length of variable)
```
namespace System.Linq{class A{static void Main(){var a="4 6 8 10";var b=a.Split(' ').Select(int.Parse);Console.WriteLine(String.Join<int>(",",Enumerable.Range(b.Min(),b.Max()-b.Min()).Where(x=>x%2==1&&!b.Contains(x))));}}}
```
**Ungolfed code:**
```
namespace System.Linq
{
class A
{
static void Main()
{
var a = "4 6 8 10";
var b = a.Split(' ').Select(int.Parse);
Console.WriteLine(String.Join<int>(",", Enumerable.Range(b.Min(), b.Max() - b.Min()).Where(x => x % 2 == 1 && !b.Contains(x))));
}
}
}
```
How it works: first, it splits the input string and parses each number into an integer. Then, it creates a range from the minimum occuring integer to the maximum and it takes all odd integers which do not occur in the input string.
[Answer]
# ised, 23 characters (16 code + 7 flags)
This is what [ised](http://ised.sourceforge.net/) is best at!
```
ised --d, --l input.dat 'O[min$1max$1]\$1'
```
Not counting the name of the file (which could be replaced by `-` for standard input), this clocks in at 23 characters plus program name plus punctuation needed for spacing the command line arguments. The actual code is just `O[min$1max$1]\$1`.
Explanation: `--d,` sets the output delimiter. `--l <file>` signifies that the following code is applied to each line. `$1` represents the current line. The min and max elements are used to initialize the sequence constructor `[]`. `O` selects the odd numbers. `\$1` is the set-wise *without* operator, which removes the already given numbers from the generated sequence.
Please clarify how the characters should be counted. Does the name `ised` of the command count or not?
[Answer]
# PHP, 110 chars
```
$a=split(' ',$i);echo join(',',array_filter(array_diff(range(min($a),max($a)),$a),function($n){return$n&1;}));
```
More readable version:
```
$a = split(' ', $i);
echo join(',',
array_filter(
array_diff(
range(min($a), max($a)),
$a
),
function($n) {
return $n & 1;
}
)
);
```
This basically creates an array of all the numbers within the range and uses a bitwise `$n & 1` to check if the number is even or odd.
[**Demo**](https://eval.in/157285)
[Answer]
# PHP 106
```
<?
$a = '4 6 8 10';
$a=split(' ',$a);foreach(range(min($a),max($a))as$i)if($i%2&&!in_array($i,$a))$d[]=$i;echo join(',',$d);
```
i'm not sure about what to discount from the char count, so i just discounted the line with the declaration
[Answer]
# Pyth, 20
```
JSrz7j\,-f%T2rhJeJJ
```
`J` is the list of integers, sorted. `rhJeJ` gives all of the possible integers between the min and max of the input. `f%T2` filters out the even numbers. `-_J` filters out the original elements of J. `j\,` joins the resultant list on commas, and the string is automatically printed.
[Answer]
In the spirit of @Kevin Cruijssen's [answer](https://codegolf.stackexchange.com/a/187447/99035):
# [Vyxal](https://github.com/Lyxal/Vyxal), 7 bytes (flexible I/O)
```
₌htṡF'∷
```
```
₌ht # push head and tail of input
ṡ # range(a, b + 1)
F # filter by elements not in input
'∷ # filter by odds
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%82%8Cht%E1%B9%A1F%27%E2%88%B7&inputs=%5B4%2C%207%5D&header=&footer=)
# [Vyxal](https://github.com/Lyxal/Vyxal), 15 bytes (exact I/O)
```
⌈vI:₌htṡF'∷;\,j
```
Same principles, but `⌈vI:` takes input as a space separated list, and `\,j` formats the list to be comma separated.
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%8C%88vI%3A%E2%82%8Cht%E1%B9%A1F%27%E2%88%B7%3B%5C%2Cj&inputs=%604%20100%60&header=&footer=)
[Answer]
# J - 42 char
```
}.;(',',":)&.>n-.~l#~2|l=.(<./n)}.i.1+>./n=:4 6 8 10
```
I exclude from the character count the `=:4 6 8 10` portion, but I include the `n` because that's part of the rest of the code—assignments can have return values in J.
Explained by explosion:
```
}.;(',',":)&.>n-.~l#~2|l=.(<./n)}.i.1+>./n=:4 6 8 10 NB. missing odd numbers
n=:4 6 8 10 NB. input assigned to n
>./n NB. maximum of n
i.1+ NB. integers from 0 to max(n) incl.
(<./n) NB. minimum of n
}. NB. drop first min(n) values
l=. NB. assign this to l
2| NB. modulo 2: 0 for evens, 1 for odds
l#~ NB. keep the odd numbers from l
n-.~ NB. discard numbers already in n
( )&.> NB. for each number:
": NB. convert to string
',', NB. and prepend a comma
; NB. run together all results
}. NB. remove leading comma
```
Example usage:
```
}.;(',',":)&.>n-.~l#~2|l=.(<./n)}.i.1+>./n=:4 6 8 10
5,7,9
}.;(',',":)&.>n-.~l#~2|l=.(<./n)}.i.1+>./n=:5 15 18 21 26
7,9,11,13,17,19,23,25
}.;(',',":)&.>n-.~l#~2|l=.(<./n)}.i.1+>./n=:2 15 6
3,5,7,9,11,13
}.;(',',":)&.>n-.~l#~2|l=.(<./n)}.i.1+>./n=:1 20
3,5,7,9,11,13,15,17,19
}.;(',',":)&.>n-.~l#~2|l=.(<./n)}.i.1+>./n=:1 3 5 7 9 NB. blank line
# }.;(',',":)&.>n-.~l#~2|l=.(<./n)}.i.1+>./n=:1 3 5 7 9 NB. see? length is 0
0
```
[Answer]
# Javascript (E6) 100 ~~110~~
Edit: join in output is unnecessary (stolen from nderscore but too obvious)
Edit2: see comments
Edit3: fixed bug, skip min if odd
Edit4: teamwork ... (loop for every number, then inside loop skip even ones)
```
t='13 15 20 2'; /* Not counted */
l=t.split(' ').sort((a,b)=>b-a);for(n=l.pop(o=[]);++n<l[0];)n%2&!l.some(x=>x==n)&&o.push(n);alert(o)
```
[Answer]
# GolfScript, ~~51~~ 40 characters
```
' '/{~}/]$:a),\(,\;-{.2%\a?-1=&},{','}/;
```
Input should be on STDIN. [Test online](http://golfscript.apphb.com/?c=OycyIDE1IDYnCgonICcve359L10kOmEpLFwoLFw7LXsuMiVcYT8tMT0mfSx7JywnfS87)
If input on STDIN is not allowed, then changing it so it allows variables only adds 1 character.
Ungolfed code with explanation:
```
' '/ # split input string
{~}/ # convert all strings into integers
]$ # put integers into an array and sort it
:a # put array into variable a
) # take last element from array
, # create an array from 0 to the integer obtained from previous command
\ # swap new array and first array, first array is now on top
( # take first element from first array
, # create an array from 0 to the integer obtained from previous command
\; # swap newest array and first array, and remove first array
- # remove elements from second array if they also occur in third (newest) array
{ # this block will be used to process elements in the array
. # duplicate current item twice
2% # obtain the remainder when dividing it by 2
\ # swap remainder and one of the duplicates
a? # obtain the index of the current item in the first array which is stored in variable a
-1= # check if index is -1 (the item is not found)
& # returns 1 if it is a missing odd number
}, # filter contents of array, only keep missing odd numbers
{','}/; # separate results with commas
```
[Answer]
# PHP, 118 chars
```
// $n='4 6 8 11 14';
$o=[];$a=explode(' ',$n);foreach(range(min($a),max($a))as$b)if($b%2!=0&&!in_array($b,$a))$o[]=$b;echo implode(',',$o);
```
Expanded...
```
// Empty array to hold the output
$o = [];
// Put each number in a zero indexed array
$a = explode(' ', $n);
// Iterate through each number between the smallest number and the largest number, inclusive
foreach(range(min($a), max($a)) as $b) {
// If the number is not even and it's not one of the numbers in the input,
// then add it to the output array
if ($b % 2 != 0 && !in_array($b, $a)) {
$o[] = $b;
}
}
// Glue the numbers in the output array together with a comma
echo implode(',', $o);
```
[Answer]
# Javascript (*ES6*) - 85
Edit: Undeleted, as I found a solution that's different enough from edc65's to justify it's own answer.
```
i='13 15 20 2' // input is not part of byte count
o=[];i.split(' ').sort((a,b)=>a-b).sort((a,b)=>{for(;++a<b;)a%2&&o.push(a)});alert(o)
```
Ungolfed / Commented:
```
o=[]; // array for output
i.split(' '). // split input by spaces
sort((a,b)=>a-b). // sort by numeric order
sort((a,b)=>{ // abuse sort as a way to run a function on every pair of neighboring
// values the array in order
for(;++a<b;) // loop from a+1 to b-1
if(a%2) // if odd
o.push(a) // push to array
}); // the sort function returns nothing, so the order of the array is
// unchanged and no pair is compared twice
alert(o) // the array is cast to a string, which is comma separated by default
```
[Answer]
# Java: 173
```
public class R{
public static void main(String[]a){
int i=0,p=0;
for(String s:a){
int j=new Integer(s);
i=i==0?j:i;
while(++i<j)
if(i%2==1)
System.out.print((p++==0?"":",")+i);
}
}
}
//Compressed:
public class R{public static void main(String[]a){
int i=0,p=0;for(String s:a){int j=new Integer(s);i=i==0?j:i;
while(++i<j)if(i%2==1)System.out.print((p++==0?"":",")+i);}}}
```
To run:
```
java R 5 15 18 21 26
```
Produces:
```
7,9,11,13,17,19,23,25
```
[Answer]
## PowerShell - 59
This creates an array of integers bounded by the max and min values in the array of arguments and sends it through the pipeline. It then passes through the numbers that are odd and not in the array of arguments.
```
$x=$args|sort;($x[0]..$x[-1]|?{$_%2-and$_-notin$x})-join','
```
[Answer]
# PowerShell, ~~101~~ ~~99~~ ~~95~~ ~~91~~ ~~78~~ 58 chars
```
$a=$args #input doesn't count
$a=$a|sort;($a[0]..$a[-1]|?{$_%2-and!($a-like$_)})-join','
```
It outputs the same results as the example, and new line if there are no odd numbers missing.
Ungolfed code:
```
#input doesn't count
$a=$args
# Sort input array
$a=$a | sort;
# Loop from numbers starting at first (min) and ending at last (max) elements of array
($a[0] .. $a[-1] | ?{
# Ouptup if element is even and is not contained in original input array
$_ % 2 -and !($a -like $_
# Print output elements joined by ","
})-join','
```
[Answer]
## Haskell, 137 chars and almost no spaces
```
import Data.List
main=let n=(map read(words$s)::[Int])in putStr$intercalate","$map show$(filter(\x->x`mod`2==1)[minimum n..maximum n])\\n
```
I love how Haskell doesn't give one crap about spaces.
Put the string in a function `s`
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 60 50 bytes (55 47 chars)
HT to JoKing for shrinking it down a substantial number of bytes (mainly via the odd number generation and rearranging to kill some parentheses)
```
{join ',',keys (.min..^.max X+|1)∖$_}o+«*.words
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzorPzNPQV1HXSc7tbJYQUMvNzNPTy9OLzexQiFCu8ZQ81HHNJX42nztQ6u19Mrzi1KK/1tzcRUnViqkaSiZKJgpWCgYGippWsOEjBQMgaJAgf8A "Perl 6 – Try It Online")
Original answer:
```
(+«*.words).&{(.min+|1,*+2…*>.max-2)∖$_}.keys.join(',')
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX0P70GotvfL8opRiTT21ag293Mw87RpDHS1to0cNy7Ts9HITK3SNNB91TFOJr9XLTq0s1svKz8zTUNdR1/xvzcVVnFipkKahZKJgpmChYGiopGkNEzJSMASKAgX@AwA "Perl 6 – Try It Online")
Here's the explanation for it:
```
(+«*.words) # numberize each word in input (*)
.&{ } # pass them to an inline method to
∖ # find the set difference of
( ,*+2… ) # all odd numbers from
.min+|1 # 1st (bitwise OR 1) to
*>.max-2 # last (first odd > max-2)
$_ # and the original number set
.keys.join(',') # print final values (.keys is
# needed for quirk with Set)
```
If the output were just spaces, could use `.Str`instead of `.keys.join(',')`, but directly using `.join` on Set grabs the internal Bool values. I'm legitimately surprised there wasn't anything much smaller, but the input/output requirements really killed options
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
#DZÅÉsWL«K',ý
```
Matching the specs exactly.. Input as space-delimited string, output as comma-separated string, or a blank line if no odd integers are found.
[Try it online](https://tio.run/##yy9OTMpM/f9f2SXqcOvhzuJwn0OrvdV1Du/9/99IwdBUwUzB0BAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9W6aKupHd4h72SwqO2SQpK9v@VXaIOtx7uLA73ObTaW13n8N7/YAU6/6OVTBTMFCwUDA2UdBSUTBUMgchCwchQwcgMJGAEEgCzgCIGENpYwVTBXMESzLEE8oxMFAzNgWKGhkqxAA).
**With flexible/reasonable I/O rules this would be 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage):**
```
ZÅÉsWL«K
```
Input as list, output `[]` if no odd integers are found.
[Try it online](https://tio.run/##yy9OTMpM/f8/6nDr4c7icJ9Dq73//4820jE01THTMTSMBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXiCvZLCo7ZJCkr2/6MOtx7uLA73ObTa@7/O/@hoEx0zHQsdQ4NYHYVoUx1DILLQMTLUMTIDCRiBBMAsoIgBhDbWMdUx17EEcyyBPCMTHUNzoJihYWwsAA).
**Explanation:**
```
# # Split the (implicit) input-string on spaces
D # Duplicate this list
Z # Get the maximum (without popping the list itself)
ÅÉ # Create a list of all positive odd integers in the range [1, max]
s # Swap so the input-list is at the top of the stack again
W # Get the minimum (without popping the list itself)
L # Create a list in the range [1, min]
« # Merge it with the input-list
K # Remove all values in this list from the odd list we created earlier
',ý '# Join the result by ","
# (and output the top of the stack implicitly as result)
```
[Answer]
# Ruby, 73
```
a=$*.map &:to_i;$><<(a.min..a.max).select{|n|n%2>0&&!a.index(n)}.join(?,)
```
[Answer]
# Perl, ~~88~~ ~~76~~ ~~74~~ ~~68~~ ~~63~~ 60 chars
```
@x=@ARGV; # Input doesn't count
sort{$a<=>$b}$x;say join",",grep{$_%2&"@x"!~$_}$x[0]..$x[-1]
```
This can be tested on console as:
```
perl -E '@x=@ARGV;sort{$a<=>$b}$x;say join",",grep{$_%2&"@x"!~$_}$x[0]..$x[-1]' 1 20
```
It outputs the same results as the example, and new line if there are no odd numbers missing.
[Answer]
## R, 59 chars:
```
b=range(a<-scan());d=b[1]:b[2];cat(d[!d%in%a&d%%2],sep=",")
```
Expanded a little:
```
a=scan() #Takes serie of integers as input
b=range(a) #Takes min and max
d=b[1]:b[2] #Creates sequence from min to max
cat(d[!d%in%a & d%%2], #Keep only those that are not in input and are odd
sep=",") #Print them comma-separated
```
Usage:
```
> b=range(a<-scan());d=b[1]:b[2];cat(d[!d%in%a&d%%2],sep=",")
1: 2 15 6
4:
Read 3 items
3,5,7,9,11,13
> b=range(a<-scan());d=b[1]:b[2];cat(d[!d%in%a&d%%2],sep=",")
1: 5 15 18 21 26
6:
Read 5 items
7,9,11,13,17,19,23,25
> b=range(a<-scan());d=b[1]:b[2];cat(d[!d%in%a&d%%2],sep=",")
1: 1 3 5 7 9
6:
Read 5 items
>
```
[Answer]
**VB.net** (154c)
```
Dim a = From w In i.Split(" "c) Select Int32.Parse(w)
Console.WriteLine(String.Join(",",(From n In Range(a.Min,a.Max-a.Min)
Where n Mod 2 = 1).Except(a))
```
[Answer]
# Haskell, 105 (168 with variable+comment)
This code splits the string into 'words', reads the words as integers, and takes all of the odd numbers in the list-difference between the range of the numbers (all integers between the smallest and the largest values) and the list of numbers itself. I then convert it to a string, remove the brackets from the conversion of a list to a string, and print the line.
```
import Data.List
s="1 4 9 12 8 20" -- not counted, in accordance with the rules
main=putStrLn$show[y|let x=(map read).words$s,y<-[minimum x..maximum x]\\x,odd y]\\"[]"
```
[Answer]
## [TinyMUSH](http://www.tinymush.net/index.php/Main_Page), 129
```
&_ me=ifelse(or(eq(words(%0),1),eq(strlen(setr(0,istrue(ldiff(lnum(lmin(%0),lmax(%0)),%0,),mod(##,2),,\\\,))),0)),%r,%q0)
\u(_,X)
```
Replace the "X" in the u() function with the list of whole numbers. The output is just a carriage return when there is one list item or a lack of odds to output. Otherwise, the code constructs a list of integers starting from the lowest to the highest in the input. The code then uses ldiff() to remove from that new list anything that appeared in the input. Then evens are filtered out with mod(), and the list gets "," as the new delimiter.
[Answer]
# Perl 5 - 66
66 characters including 3 for command line options
```
#!perl -lpa
%F=@F=sort{$a<=>$b}@F,@F;$_=join',',grep$_&!$F{$_},"@F"..pop@F
```
Takes multiple lines of data on the standard input.
[Answer]
# Burlesque, 41
```
ln{wdrie!r@{2.%}f[}]m{{Jrij',==$$}f[}m[uN
```
The bloated length is mostly due to mostly formatting the output.
[Answer]
# JavaScript 89
Five less characters and better typing thanks to WallyWest.
```
s='5 15 18 21 26' // not counted
s=s.split(" ");o="";for(i=0;j=+s[i++];)for(;++j<+s[i];)o+=0!=j%2?(o?",":"")+j:"";alert(o)
```
Originally 94 chars.
```
s='5 15 18 21 26' // not counted
s=s.split(' '),o='',i=0;while(j=s[i++])for(j*=1;++j<s[i]*1;)o+=j%2!=0?(o?',':'')+j:'';alert(o)
```
] |
[Question]
[
**This question already has answers here**:
[Shortest code that raises a SIGSEGV](/questions/4399/shortest-code-that-raises-a-sigsegv)
(84 answers)
Closed 7 years ago.
I come across a question in a coding competion
"write a code that returns SIGSEGV(Segmentation fault ) " .
Points were given on the basis of length of code.
The prgramming languages available were asm,c,c++,java .
I knew c language better and submitted my code as
```
main(){char *c="h";c[3]='j';}
```
But others solve it in shorter length than me . How it is possible ? Can any one explain plz.
Platform UBUNTU 10.04
[Answer]
bending the rules a bit ; the C linker doesn't care if 'main' is a function or not :
```
int main=0;
```
indeed, the default type is 'int' and the default global initialiser is 0 :
```
main;
```
[Answer]
There are many ways to make a program return SIGSEGV. One of these is via segmentation fault due to stack overflow of a recursive function calling itself a lot of times. In C, a short (if not the shortest) code for this would be:
```
main(){main();}
```
[Answer]
In C, something like this is fairly short:
```
int main(void)
{
return *(int *)0=1;
}
```
...or for a less proper version with minimal whitespace:
```
main(){*(int*)0=1;}
```
---
...even less proper, but shorter (the source code, at least):
```
main(){puts(0);}
```
It calls `puts()` with an implicit prototype, but still "works" if linked with the standard library.
[Answer]
Besides may other ways of suicide as demonstrated by others, your way could be expressed a bit shorter as
```
main(){++*((int*)"");}
```
[Answer]
## Assembly, 3 characters
```
RET
```
## C, 5 characters
```
main;
```
[Answer]
Nah, as short as this :
```
int main;
```
[Answer]
# Ruby, 18 characters
I know this wasn't requested, but have a Ruby one, because why not. :D
```
Process.kill 11,$$
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/197968/edit).
Closed 4 years ago.
[Improve this question](/posts/197968/edit)
## Challenge
Write a complete program that prints out the time it took to execute a certain part of itself. That part must include a process whose total number of operations (and therefore execution time) is dependent on a user-substituted numeric value - this can be denoted in any way in your code (uppercase N for example) and doesn't count as a byte.
Unlike many code golf challenges, this one is a valid use case - in environments that allow executing code from command line, you may want to have a short code snippet to roughly compare performance across different systems.
## Rules
* Execution time is denoted as a nonnegative integer or decimal value, followed by the corresponding time unit (let's accept **ns**, **µs**/**us**, **ms**, **s**, **m** and **h**). A space between the number and unit is optional, more spaces are also allowed (but not newline characters).
* Output must include the execution time exactly once. There can be additional text around it, as long as no part of it could be matched with the execution time itself. This allows using standard functions for timing code execution that may use various formats for printing out the execution time.
* Output goes to STDOUT. Anything in STDERR is disregarded.
* You can import any standard libraries before the actual code, without any cost to the total number of bytes, but you are not allowed to change the library name in the import declaration.
* Do not just use sleep to control the execution time, as that does not increase the number of operations (and also doesn't work as a performance benchmark). The execution time must also depend on the user-substituted value linearly, exponentially or polynomially (before you ask, a constant polynomial doesn't count).
## Scoring
This is code golf, so the shortest answer in bytes wins.
## Example
This is an unnecessarily long program written in Python:
```
import time
start_time = time.time()
for i in range(N):
pass
end_time = time.time()
print("%fs" % (end_time - start_time))
```
Program description:
* imports the standard `time` library (this adds no bytes to the code size)
* stores the current time in seconds
* loops N times, does nothing each iteration
* stores the time after the loop
* prints the time difference in the correct format
[Answer]
# [Zsh](https://www.zsh.org/), 14(?) bytes
*If `N` is substituted in place of `$1` (as described in the prompt), then **14 bytes**. If `N` is given as an argument, then **16 bytes**.*
---
```
time (: {0..$1})
```
[Try it online!](https://tio.run/##qyrO@P@/JDM3VUHDSqHaQE9PxbBW8////5YGIAAA "Zsh – Try It Online")
Uses the builtin `time` (you can verify that this is a Zsh builtin: run `type time`). The time to expand the brace expansion increases with the input.
You might think to use `time sleep $1`, but `sleep` is an external program, not pure Zsh.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Full program. Returns elapsed time in seconds, followed an "s". Runtime on TIO is roughly linear with N, with a coefficient of about 6×10-10. Uses the dfns library, but per OP, import isn't counted.
```
's',⍨cmpx'⍳N'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qc6R6SlpesTrXo472gv/qxeo6j3pXJOcWVKg/6t3sp/4fKPzf71HbBENXY4VH3S0KBVwQngkKzxTCAwA "APL (Dyalog Unicode) – Try It Online")
`'⍳N'` expression generating the **ɩ**ntegers 1 through N
`cmpx` time the execution of that expression
`'s',⍨` append "s"
[Answer]
# [R](https://www.r-project.org/), ~~29~~ 28 bytes
```
cat(system.time(!1:9e6)[3],"s")
```
[Try it online!](https://tio.run/##K/r/PzmxRKO4srgkNVevJDM3VUPR0Moy1Uwz2jhWR6lYSfP/fwA "R – Try It Online")
A full program printing the number of seconds elapsed complete with unit. The `9e6` is not counted per the rules and can be replaced with any other number. Thanks to @RobinRyder for saving a byte!
An alternative would be `paste(system.time(!1:9e6),"s")`, but this also prints our four other times (the correct one is in the middle).
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 38 bytes
```
param($n)$a={1..$n};Measure-Command $a
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVPUyXRttpQT08lr9baNzWxuLQoVdc5Pzc3MS9FQSXx////hgZgAAA "PowerShell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ƒžc})¥O's«
```
-2 bytes thanks to *@ExpiredData*.
Either add the \$n\$ as leading portion (i.e. `100ƒžc})¥O's«`) or simply use \$n\$ as STDIN input.
Outputs the execution time in whole seconds (without space).
[Try it online.](https://tio.run/##yy9OTMpM/f//2KSj@5JrNQ8t9VcvPrT6/39DAzAAAA)
**Explanation:**
```
ƒ # Loop in the range [0, n]:
žd # Push the current time in seconds
}) # After the loop: wrap all values on the stack into a list
¥ # Get the deltas (paired differences) of this list
O # And sum those (to get the difference between the first and last times)
's« '# And append a trailing "s" (without space)
# (after which this is output implicitly to STDOUT)
```
[Answer]
# [J](http://jsoftware.com/), ~~16~~ ~~14~~ 19 bytes (20 - 1 for N)
```
echo's',~":6!:2'i.N'
```
[Try it online!](https://tio.run/##y/rvZ6tnaGDwPzU5I1@9WF2nTsnKTNHKSD1Tz08dKmdgwAWSVUCX5oJJ41TwHwA "J – Try It Online")
*-2 bytes thanks to Adam -- after looking at his answer I realized I didn't need to sum the integers, just generate them*
*+6 bytes thanks to Adam for pointing out I missed the unit*
Generates the integers `0..N-1`, times it, and prints it to stdout. `'s',~` prepends the unit `s` for seconds.
[Answer]
# Python 2.7 - 32 bytes
```
print timeit.timeit(number=N),'s'
```
We can take advantage of the different scoring rules here. timeit.timeit has been in the standard library since 2.6, so we get to ignore the `import timeit` and hence 14 bytes that would have cost.
timeit is designed to be able to take a statement for execution as a parameter, but has a default of `pass`. So the `pass` statement will be executed N times, and that is what will be timed.
[Answer]
## Raku (18 or 25)
Depending on one's definition of a "standard" library for Raku...
```
use Timer; # uncounted import line
say timer {[+] ^N}
```
or
```
[+] ^N;say now -BEGIN now
$/=now;[+] ^N;say now -$/
```
`[+] ^N` sums all numbers from 0 to N, so the bigger it gets, the more ops it does. The `now - BEGIN now` bit is a common idiom in Raku that virtually makes such libraries unnecessary (the phaserless alternative is as long or longer).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 59 bytes
```
main(c,a){a=clock();for(c=100;c--;);printf("%dus",clock()-a);}
```
[Try it online!](https://tio.run/##RcpLDkAwFAXQuVUIkbSJCuOHvTS3Pi9oRWsk1l4GEtOTAzUBMWeL9TRD2gbehmruk198MOxeiptmK1BqeekOq8MiJI3uEOiauiYoRZL2g20YRVaY02flt5SWdMf4AA "C (gcc) – Try It Online")
[Answer]
# Java 5/6, ~~99~~ ~~98~~ 78 bytes
```
import static java.lang.System.*;
enum A{A;{long s=nanoTime();for(int i=#;i-->0;);out.print(nanoTime()-s+"ns");}}
```
Loops the given \$n\$ amount of times without doing anything in the loop body.
# Java 11, ~~128~~ ~~122~~ ~~121~~ 101 bytes
```
import static java.lang.System.*;
interface M{static void main(String[]a){var s=nanoTime();"x".repeat(#);out.print(nanoTime()-s+"ns");}}
```
Creates a String of \$n\$ amount of `"x"` with the Java 11 [`String#repeat(int)` builtin](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#repeat(int)).
[Try it online.](https://tio.run/##RcqxDsIgEADQXyFMoCmpM/ETnOrWOFxabA7lIHASTdNvxw4mri/PQ4XOz4@GIcXMojAwTsLvbJ5Aixk@hV0wB9uQ2OU7TE5c1l@rEWcRAEkNnJGW8QZ6rZBFORNQvGJwSlv5lia75IDVqe@1jS82ae@s/qkrR0lFarttrX0B)
In both programs, replace the `#` for the actual number.
And both will output the execution time in nanoseconds (without space).
-20 bytes thanks to *@Holger* for remembering me to (ab)use the rule "*You can import any standard libraries before the actual code, without any cost to the total number of bytes, but you are not allowed to change the library name in the import declaration.*" by using a `static import` for `System`.
[Answer]
# SAS, 37 bytes
```
option stimer;data;do i=1to N;end;run;
```
This increments a loop counter `i` and outputs the final value `N` to a SAS dataset. This is not optimised out, so the run time is linearly dependent on `N`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~40~~ ~~29~~ ~~28~~ 26 bytes
```
First@Timing@Do[,N]~Print~s
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/98ts6i4xCEkMzczL93BJT9axzS2LqAoM6@krvj/fwA "Wolfram Language (Mathematica) – Try It Online")
Replace N with number of times to do the operation. Does `null` N times (doing nothing is an operation in this case, as you can observe by increasing N and time increases).
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~10~~ 9 (or 12?) [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
{t}]│Σûms
```
With \$n\$ as STDIN input.
[Try it online.](https://tio.run/##y00syUjPz0n7/7@6pDb20ZSmc4sP784t/v/f0AAEAA)
If this is not allowed, it would be 3 bytes longer instead:
```
"#"i{t}]│Σûms
```
Where the `#` is replaced with the integer \$n\$ (i.e. `"100"i{t}]│Σûms`).
[Try it online.](https://tio.run/##y00syUjPz0n7/1/J0AAElDKrS2pjH01pOrf48O7c4v//AQ)
Both answers output the execution time in milliseconds without space.
**Explanation:**
Uses a similar approach as [my 05AB1E answer](https://codegolf.stackexchange.com/a/197990/52210).
```
# Use the (implicit) input-integer
# Or alternatively:
"#" # Push the integer-string
i # And convert it from a string to an integer
{ } # Loop that many times
t # Push the current timestamp in milliseconds
] # After the loop, wrap all times in a list
| # Get the forward differences of this list
Σ # Sum those differences
ûms # Push the string "ms"
# (after which the entire stack joined together is output implicitly)
```
NOTE: Simply using `100` instead of `"100"` would add three digits (`1,0,0`) to the stack instead, which is why I have to do the `"100"i` to make it universal for all possible \$n\$.
`]│Σ` could alternatively be `⌐-Þ` for the same byte-count: [Try it online](https://tio.run/##y00syUjPz0n7/7@6pPZRzwTdw/MO784t/v/f0AAEAA).
```
⌐ # Rotate all values on the stack clockwise
- # Subtract the top two values on the stack
Þ # Discard everything from the stack, except for the top item
```
[Answer]
# [PHP](https://php.net/), 62 bytes
```
<?php $t=microtime(1);for(;$i<N;$i++);echo microtime(1)-$t.'s';
```
[Try it online!](https://tio.run/##K8go@P/fxr4go0BBpcQ2NzO5KL8kMzdVw1DTOi2/SMNaJdPG0AAMgExtbU3r1OSMfAVkdboqJXrqxerW//8DAA "PHP – Try It Online")
This is my first try in codeGolf, hope I get this right!
**Some explanations:**
* `microtime(true)` gets timestamp in seconds as a float with the precision of microseconds
* taking advatange that errors are discarded, so `$i` is not initialized
* using automatic type conversions
] |
[Question]
[
### The Challenge
**Input:** alphanumeric string. You can assume that the string will only contain the characters [0-9A-Z]. This can come from a parameter, command line, or STDIN. Digits are always before letters in terms of the base. Think like an extended version of HEX.
**Output** `X,Y` Such that `Y` is the *minimum* base required to parse the string and `X` is the decimal value of the input string in that base.
**Examples**
>
> Input: "1"
>
>
> Output: 1,2
>
>
>
>
> Input: "HELLOWORLD"
>
>
> Output: 809608041709942,33
>
>
>
**Scoring:** This is a golf, so shortest code in bytes wins.
[Answer]
# Python 2, ~~74~~ ~~64~~ ~~56~~ ~~55~~ 53 bytes
```
def f(x):a=ord(max(x))-54;a+=7*(a<8);print int(x,a),a
```
Call the function (i.e. `f("HELLOWORLD")`) and outputs to stdout (`809608041709942 33`)
This is case-sensitive, requiring upper case letters, and crashes for invalid input (e.g. `"$^$%!(&£%)()`)
This code gets the `max` letter in the string (z>x>y>...>b>a>9>8>...>2>1>0) and gets the largest base needed to represent it.
Change the `54` into a `76` to make it work for lowercase (but no longer upper case).
[Answer]
# APL (24)
```
{(B⊥D-1),B←⌈/D←⍵⍳⍨⎕D,⎕A}
```
This is a function that takes a string and returns two values, the value and the base.
```
{(B⊥D-1),B←⌈/D←⍵⍳⍨⎕D,⎕A} 'DEADBEEF'
3735928559 16
```
Explanation:
* `⎕D,⎕A`: digits followed by letters
* `D←⍵⍳⍨`: store in `D` the 1-based index of each character of ⍵ in the string of digits followed by letters
* `B←⌈/D`: store in `B` the highest value in `D`. (which is the base to use)
* `(B⊥D-1)`: subtract 1 from each value in `D` (making them the values of the digits), and decode them as a base-`B` number.
[Answer]
# Pure Bash, 48
```
for((b=37;$[--b]#$1;)){ :;}
echo $[$[++b]#$1],$b
```
### Output
```
$ ./minbase.sh HELLOWORLD
./minbase.sh: line 1: ((: 32#HELLOWORLD: value too great for base (error token is "32#HELLOWORLD")
809608041709942,33
$ ./minbase.sh HELLOWORLD 2>/dev/null
809608041709942,33
$ ./minbase.sh 1 2>/dev/null
1,2
$
```
I'm taking advantage of [this meta answer](http://meta.codegolf.stackexchange.com/a/4781/11259) - specifically that warnings output to STDERR may be ignored.
[Answer]
# Pyth, 23 bytes
```
Jmx+jkUTGdrz2KheSJ,iJKK
```
Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=Jmx%2BjkUTGdrz2KheSJ%2CiJKK&input=HALLOWORLD&debug=0)
```
UT create the list [0, 1, 2, ..., 9]
jk join them, creates the string "0123456789"
+ G G is initialized with the alphabet, add both strings
creates "0123456789abcdefghijklmnopqrstuvwxyz"
m rz2 maps each charater d of input().lower() to:
x d the index of d in "012...xyz"
J store the resulting list of indices in J
SJ sorted(J) (doesn't sort J in place, but gives you a sorted copy)
e last element (=maximum)
h + 1
K store result in K
iJK convert J from base K to base 10
, K create the tuple (iJK, K) and prints
```
# Pyth, 16 bytes (?)
I'm not sure if this counts. The functionality I'm using was in Pyth for quite a while, but didn't work because of one stupid little bug. So the following code didn't work when the question was asked, although the docs said that it does.
```
DeGJ1#~J1#R,iGJJ
```
This defines a function `e`. Try it [online](https://pyth.herokuapp.com/?code=DeGJ1%23~J1%23R%2CiGJJ%3Be%22HALLOWORLD%22e%221%22&debug=0).
This one was based a submission by @Reticality. He uses a different algorithm now though.
```
DeG Define a function e(G):
J1 J = 1
# while True:
~J1 J += 1
# try:
izJ convert z (=input) from base J into base 10
R,izJJ return tuple(base_10, J)
if exception (converting failed) do nothing
```
[Answer]
# J - 50 char
Worry not, Martin, I have come to restore order.
```
(>./@i.(u:(47+i.11),65+i.26&)(,&.":,[)'b',tolower)
```
The `u:(47+i.11),65+i.26` portion creates the string `/0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ`, and we want the slash so that when we find the largest digit of `HELLOWORLD` with `>./@i.`, we correct an off-by-one error at no extra charge.
Then we use J's built-in base conversion by evaling e.g. `33bhelloworld`; J has this weird internal language for specifying numbers, so we exploit that to do the base interpretation for us.
```
(>./@i.(u:(47+i.11),65+i.26&)(,&.":,[)'b',tolower) 'HELLOWORLD'
809608041709942 33
f =: (>./@i.(u:(47+i.11),65+i.26&)(,&.":,[)'b',tolower)
f '1'
1 2
f 'POTATO'
627732894 30
f '1FISH2FISH'
22338345482731 29
```
[Answer]
# J, 31 bytes
```
3&u:(-47+7*60<]@)(>./(#.,[)<:@)
```
Usage:
```
f=.3&u:(-47+7*60<]@)(>./(#.,[)<:@)
f 'POTATO'
627732894 30
f '1FISH2FISH'
22338345482731 29
```
1 byte thanks to @FUZxxl.
[Try it online here.](http://tryj.tk/)
[Answer]
## CJam (25 chars)
```
q{i48-_9>7*-}%_:e>):Zb',Z
```
[Online demo](http://cjam.aditsu.net/#code=q%7Bi48-_9%3E7*-%7D%25_%3Ae%3E)%3AZb'%2CZ%0A&input=HELLOWORLD)
It's 28 chars in GolfScript, mainly because `base` doesn't have a one-char alias:
```
{48-.9>7*-}%.$-1=):^base','^
```
[Answer]
# Mathematica, 55 bytes
~~Hmmm, beating J with Mathematica? Something's fishy...~~
```
Print[f=FromDigits;f[#,y=f/@Max@Characters@#+1],",",y]&
```
This defines an unnamed function, which takes the string as a parameter and prints the result. You can either give it a name or use it directly:
```
Print[f=FromDigits;f[#,y=f/@Max@Characters@#+1],",",y]&@"HELLOWORLD"
```
The idea is pretty simple. Mathematica's integer parser supports bases up to 36 out of the box, so we only need to figure out the minimum base. We do that with
```
y=f/@Max@Characters@#+1
```
where `#` is the function's parameter and we've defined `f` as an alias of `FromDigits`. Note that `FromDigits` normally reads things in base 10, but that doesn't change the value of a single digit. Then we just use that to parse the string with `f[#,y...]` and the print the result, a comma and `y`.
[Answer]
# J (61)
Explicit funcions in J can be... Somewhat hard to read.
```
3 :'(+/i*b^|.x:i.#y),b=.>:>./i=.(y i.~a.{~(48+i.10),65+i.26)'
```
### Example usage:
```
f=: 3 :'(+/i*b^|.x:i.#y),b=.>:>./i=.(y i.~a.{~(48+i.10),65+i.26)'
f 'POTATO'
627732894 30
```
[Answer]
# Rust (1.0 beta), ~~81~~ 80 bytes
```
let f=|a|loop{for i in 2..{if let Ok(m)=u64::from_str_radix(a,i){return(m,i)}}};
```
Test:
```
fn main() {
let f=|a|loop{for i in 2..{if let Ok(m)=u64::from_str_radix(a,i){return(m,i)}}};
assert_eq!(f("1"), (1, 2));
assert_eq!(f("POTATO"), (627732894, 30));
assert_eq!(f("HELLOWORLD"), (809608041709942, 33));
println!("ok!");
}
```
---
This is similar to all other answers, we try to parse the string into an integer using the internal function `u32::from_str_radix`, and start from base 2 and return immediately.
Rust is static-typed, and it requires all reachable branches to return the same type of value. The `for` loop is *not* infinite, so Rust would require a return value after the `for` loop. In order to make the type-checker happer, an outer infinite `loop` is added to make sure there is no other exit point. This saves 1 byte compared with returning a default value.
[Answer]
# JavaScript, ~~100~~ 89 bytes
Thanks to nderscore for saving 10 bytes!
Works for base-2 to base-36; that's all bases JavaScript's `parseInt` supports.
```
function b(s){for(i=1;(x=parseInt(s,++i))!=x|!x.toString(i)[s.length-1];);return x+","+i}
```
The code uses a for loop starting from 1 and tries to parse the int on base-N (I use N here as `i + 1`; `i` is incremented before parsing the number) is the current number in the loop. It checks whether the parsed int is not NaN (`x==x` is the shortest way, and it works because `NaN != NaN`). It also checks that the integer converted to base-N equals the original string; this is necessary because when JavaScript parses an int, only the first part has to be valid, so `parseInt` would be able to parse "abc" on base-11 because "a" is a valid base-11 integer (while "b" and "c" are not). If the input cannot be parsed in base-N, then the for loop continues until it finds the correct base; after the for loop, the function returns the base-10 number and the original base.
Ungolfed code:
```
function getBase(str) {
for (var base = 1;
(parsed = parseInt(s, ++base)) != parsed | !parsed.toString(base)[str.length - 1];);
return parsed + "," + base;
}
```
[Answer]
# JavaScript (ES6) 70 ~~72~~
The base is 1 more than the biggest digit in the string, so sort and find it.
**Edit** Save 2 bytes thx @nderscore (particularly, shame on me for using `>=` instead of `>`)
```
F=s=>(b=[...s].sort().pop().charCodeAt()-47,[parseInt(s,b-=b>8&&7),b])
// TEST:
C.innerHTML=F('1') + '\n' + F('HELLOWORLD')+ '\n' + F('POTATO')
```
```
<pre id=C></pre>
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 74 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 9.25 bytes
```
⇩:fGkrḟ›…β,
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyLhuaA9IiwiIiwi4oepOmZHa3LhuJ/igLrigKbOsiwiLCIiLCJIRUxMT1dPUkxEIl0=)
[Answer]
# Swift, 105
Not very short and can probably be improved
```
func n(x:String) {var m=64;for c in x.utf8{m=max(Int(c),m)};println("\(strtoul(x,nil,10+m-64)),\(m-54)")}
```
[Answer]
# Haskell, 97 bytes
```
import Data.Char
j x|x>64=x-54|1<2=x-47
l=j.ord
m=l.maximum
f x=(foldl(\a b->a*m x+l b-1)0 x,m x)
```
Example run:
```
*Main> map f ["HELLOWORLD", "POTATO", "1"]
[(809608041709942,33),(627732894,30),(1,2)]
```
It's so long because I need do `import Data.Char` for `ord` and I don't have a built in read function for integers of arbitrary base.
[Answer]
# PHP (>=5.4), 90
(-2 for an anoynomous function in PHP 7; 74 for a snippet)
```
function f($s){$b+=7*(8>$b=ord(max(str_split($s)))-54);return[base_convert($s,$b,10),$b];}
```
Thanks @user34736 for the -54(+8) idea; saved two bytes on my -54/-47 approach.
The function returns an array instead of printing the result.
+/-0 for printing:
```
function f($s){$b+=7*(8>$b=ord(max(str_split($s)))-54);echo base_convert($s,$b,10),",$b";}
```
but a return value is easier to test:
```
function test($x,$y,$e){static $h='<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>';echo"$h<tr><td>$x</td><td>$y</td><td>$e</td><td>",(strcmp($y,$e)?'N':'Y'),"</td></tr>";$h='';}
foreach([1=>'1,2','HELLOWORLD'=>'809608041709942,33','ILOVECODEGOLF'=>'21537319965321352644,32','POTATO'=>'627732894,30','1FISH2FISH'=>'22338345482731,29']as$x=>$e)test($x,implode(',',f($x)),$e);echo'</table>';
```
[Answer]
## Pascal, 217 B
Extended Pascal (as specified by ISO standard 10206) allows you to write (in your source code) `integer` literals up to base 36 (for example `−16#fF` denotes the value `−255` decimal).
To be functionally consistent, all number literals that are allowed *in Pascal source code* are allowed as user input, too:
Therefore the built‑in procedures `read`/`readLn`/`readStr` accept strings constituting valid number literals in your Pascal source (and in fact all numeric representations defined by ISO standard 6093).
The task can be boiled down to determining the minimal base:
```
program p(input,output);var U,P:string(65);Y,X:integer;begin read(U);Y:=2;for X:=1 to length(U)do
Y:=card([1..Y,1..index('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',U[X])]);writeStr(P,Y:1,'#',U);readStr(P,X);write(X,Y)end.
```
Ungolfed:
```
program minimumBaseToCountToAString(input, output);
const
{ Pascal does not make any assertion with regard to character encoding
(except that `'A' < 'Z'`/`'a' < 'z'` (subject to availability) and
digit characters `'0'` through `'9'` are consecutive and ascending).
Hence another mechanism needs to be sought. }
digit = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
type
{ A `type` range restriction will cause an error
should we attempt to assign values outside of this range. }
base = 2‥36;
var
unprocessed: string(62);
{ This size is sufficient for `'2#1010…0101'` on a 64‑bit system.
However, it will not prevent `'36#ZZZ…ZZZ'` overflow mistakes. }
prefixed: string(65);
{ Stores the value of the largest digit found + 1 (a. k. a. base). }
minimumBase: base value 2;
{ Cannot reuse variable since `minimumBase` needs to be printed, too. }
number: integer;
begin
{ Reads up to `unprocessed.capacity` characters from `input`
and discards the remainder of the line. }
readLn(unprocessed);
{ In Pascal `string` indices are `1`-based. }
for number ≔ 1 to length(unprocessed) do
begin
{ Determines the maximum of two values without calculating
the potential new maximum multiple times.
The Extended Pascal function `index` returns `0`
if `representation[number]` is not found in `digit`. }
minimumBase ≔ card([1‥minimumBase,
1‥index(digit, unprocessed[number])]);
end;
{ The `:1` is necessary so the base specification does not get padded
with an implementation-defined default number of space characters
(possibly causing /trailing/ characters to spill over). }
writeStr(prefixed, minimumBase:1, '#', unprocessed);
{ This performs the actual conversion honoring `minimumBase`. }
readStr(prefixed, number);
{ I can count to potato! }
writeLn(number, minimumBase);
end.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, 46 bytes
```
x=0
1until(x=Integer($_,$.+=1)rescue p)
p x,$.
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6eUuyCpaUlaboWN_UqbA24DEvzSjJzNCpsPfNKUtNTizRU4nVU9LRtDTWLUouTS1MVCjS5ChQqgGIQXVDNC1Z5uPr4-If7B_m4QEQA)
] |
[Question]
[
The problem is simple. Given a string such as `Hello World!` the program would output `8-5-12-12-15 23-15-18-12-4-!`. Any delimiters will do, (please specify what they are though) I just chose to use space between words and dashes between characters.
The conversion is that all alphabetical characters will be converted to their numeric equivalent. i.e. `A=1,B=2,...,Z=26`. All other characters must be kept intact. Case insensitive.
Another example
```
Here's another example, I hope that this will illustrate my point! If it's unable, more specs will be given.
8-5-18-5-'-19 1-14-15-20-8-5-18 5-24-1-13-16-12-5-, 9 8-15-16-5 20-8-1-20 20-8-9-19 23-9-12-12 9-12-12-21-19-20-18-1-20-5 13-25 16-15-9-14-20-! 9-6 9-20-'-19 21-14-1-2-12-5-, 13-15-18-5 19-16-5-3-19 23-9-12-12 2-5 7-9-22-5-14-.
```
Note that there are no trailing or starting delimiters between characters.
Scoring will be based on the shortest amount of code. Any language is welcome.
As long as more answers are provided I will change the winner.
GLHF!
[Answer]
# Ruby 2.0, 41+1 characters
There, now it complies with the updated rules and makes prettier output.
```
gsub(/\w+/){$&.chars.map{|c|c.ord&31}*?-}
```
Run with `-p` switch:
```
ruby -p ord.rb <<< "ABC! Defghi, jklmnopqr stuvwxyz"
1-2-3! 4-5-6-7-8-9, 10-11-12-13-14-15-16-17-18 19-20-21-22-23-24-25-26
```
[Answer]
## GolfScript (24 22 chars)
```
{.32|96^:@`]@(26/!=n}%
```
is a hybrid of Howard's solution and my previous one:
```
{.223&65-.26/!{)`\}*;n}%
```
Since the spec states that I can use any delimiter, I've chosen to use newline.
[Online demo](http://golfscript.apphb.com/?c=OyJIZWxsbywgd29ybGQhIgp7LjMyfDk2XjpAYF1AKDI2LyE9bn0l)
[Answer]
# Perl: ~~42~~ 38 characters
```
s/\S(?=\S)/$&-/g;s/[a-z]/31&ord$&/ige
```
Sample run:
```
bash-4.1$ perl -pe 's/\S(?=\S)/$&-/g;s/[a-z]/31&ord$&/ige' <<< "Here's another example, I hope that this will illustrate my point! If it's unable, more specs will be given."
8-5-18-5-'-19 1-14-15-20-8-5-18 5-24-1-13-16-12-5-, 9 8-15-16-5 20-8-1-20 20-8-9-19 23-9-12-12 9-12-12-21-19-20-18-1-20-5 13-25 16-15-9-14-20-! 9-6 9-20-'-19 21-14-1-2-12-5-, 13-15-18-5 19-16-5-3-19 23-9-12-12 2-5 7-9-22-5-14-.
```
[Answer]
### GolfScript, 37 36 23 characters
The following version takes newline as delimiter (as Peter's solution):
```
{.32|96^:@`]@27,?0>=n}%
```
A version which interprets words and delimiters as in the examples given is 36 characters long:
```
' '/{'-'*{.32|96^:@`]@27,?0>=}%' '}%
```
(Strange enough my first version `'-'*'- -'/' '*{.32|96^:@`@0>@27<&if}%` didn't work...)
Takes input on STDIN. The example can be [tested online](http://golfscript.apphb.com/?c=OyJIZWxsbyB3b3JsZCEiCgonICcveyctJyp7LjMyfDk2XjpAYF1AMjcsPzA%2BPX0lJyAnfSUK&run=true):
```
> 'Hello world!'
8-5-12-12-15 23-15-18-12-4-!
```
[Answer]
## R - 134 characters
A bit too long to be really in competition but here we go:
```
s=sapply
l=letters
cat(s(strsplit(scan(,""),""),function(x)paste(s(tolower(x),function(y)ifelse(y%in%l,which(l==y),y)),collapse="-")))
```
Word delimiter is space, character delimiter is `-`.
[Answer]
## Tcl, 82
```
lmap a [split [string tol $i] {}] {expr {[string is alpha $a]?[scan $a %c]-96:$a}}
```
Because you did not specify what you want, well, here an expression.
Input in `i`, result of the expression is the result.
Example:
```
% set i "Hello World!"
Hello World!
% lmap a [split [string tol $i] {}] {expr {[string is alpha $a]?[scan $a %c]-96:$a}}
8 5 12 12 15 { } 23 15 18 12 4 !
```
Word delimiter is `{ }`, character delimiter is
[Answer]
## Python - 47 ~~63~~
This assumes you've assigned the string to the variable `s`.
47 uses a flagrant abuse of the rules and says that `[` is the delimiter for the start of the original string, `]` marks the end of the original string, `,` marks the different characters and unchanged characters are captured in quotes.
```
str([(x,ord(x)-64)[x.isalpha()] for x in s.upper()])
```
Alternatively, 62 squeezes a line from below (although `'A'<=x<='Z'` is just as long and works just as well.:
```
'-'.join([str((x,ord(x)-64)[x.isalpha()]) for x in s.upper()])
```
63:
```
'-'.join([str((x,ord(x)-64)[64<ord(x)<91]) for x in s.upper()])
```
And the sample output:
```
>>> s = "Hello World!"
>>> '-'.join([str((x,ord(x)-64)[64<ord(x)<91]) for x in s.upper()])
'8-5-12-12-15- -23-15-18-12-4-!'
```
[Answer]
# Mathematica 68
Commas used as separators.
```
If[64 < # < 97, # - 64, FromCharacterCode@#] & /@ ToCharacterCode@ToUpperCase@i
```
**Example**
```
i="To be, or not to be,--that is the question:-- Whether 'tis nobler in
the mind to suffer The slings and arrows of outrageous fortune Or to
take arms against a sea of troubles, And by opposing end them?";
If[64 < # < 97, # - 64, FromCharacterCode@#] & /@ ToCharacterCode@ToUpperCase@i
```
>
> {20, 15, " ", 2, 5, ",", " ", 15, 18, " ", 14, 15, 20, " ", 20, 15, "
> ", 2, 5, ",", "-", "-", 20, 8, 1, 20, " ", 9, 19, " ", 20, 8, 5, " ",
> 17, 21, 5, 19, 20, 9, 15, 14, ":", "-", "-", " ", 23, 8, 5, 20, 8, 5,
> 18, " ", "'", 20, 9, 19, " ", 14, 15, 2, 12, 5, 18, " ", 9, 14, " ",
> 20, 8, 5, " ", 13, 9, 14, 4, " ", 20, 15, " ", 19, 21, 6, 6, 5, 18, "
> ", 20, 8, 5, " ", 19, 12, 9, 14, 7, 19, " ", 1, 14, 4, " ", 1, 18,
> 18, 15, 23, 19, " ", 15, 6, " ", 15, 21, 20, 18, 1, 7, 5, 15, 21, 19,
> " ", 6, 15, 18, 20, 21, 14, 5, " ", 15, 18, " ", 20, 15, " ", 20, 1,
> 11, 5, " ", 1, 18, 13, 19, " ", 1, 7, 1, 9, 14, 19, 20, " ", 1, " ",
> 19, 5, 1, " ", 15, 6, " ", 20, 18, 15, 21, 2, 12, 5, 19, ",", " ", 1,
> 14, 4, " ", 2, 25, " ", 15, 16, 16, 15, 19, 9, 14, 7, " ", 5, 14, 4,
> " ", 20, 8, 5, 13, "?"}
>
>
>
[Answer]
**Javascript, ~~81~~ 74**
~~`""+[].map.call(prompt(),function(c){a=c.charCodeAt(0);return a>65&&a<123?a&31:c})`~~
With the input taken from a variable
`""+[].map.call(s,function(c){a=c.charCodeAt(0);return a>65&&a<123?a&31:c})`
Output from the string you chose
>
> 8,5,18,5,',19, ,1,14,15,20,8,5,18, ,5,24,1,13,16,12,5,,, ,9, ,8,15,16,5, ,20,8,1,20, ,20,8,9,19, ,23,9,12,12, ,9,12,12,21,19,20,18,1,20,5, ,13,25, ,16,15,9,14,20,!, ,9,6, ,9,20,',19, ,21,14,1,2,12,5,,, ,13,15,18,5, ,19,16,5,3,19, ,23,9,12,12, ,2,5, ,7,9,22,5,14,.
>
>
>
```
| Word | Char |
Delimiters| , , | , |
```
[Answer]
## C# - 137 Characters
This code assumes the string to convert is the **s** variable
```
Regex.Replace(Regex.Replace(s.ToUpper(),@"[A-Z]",m=>(((int)m.Value[0])-64).ToString()+'-'),@"[^\w\s-]",m=>m.Value+'-').Replace("- "," ");
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
26R;`,@ØẠyK
```
[Try it online!](https://tio.run/##LYy9DcIwGAVXeVQ0EQUFDQ0lER0T4KAHNvKf7C@AJ2AFSuagzSRMYoxEcdfdXWhtqXW52q8P3WZ6ft6vsqvTo9YtE@cZygfRTOBduWjZoYcOkRCtpMlk3Iy1aIxZkhLCFcRgvMzQn2CkPUavhl/qQiJy5PEfDcTZXOkXXw "Jelly – Try It Online")
Uses space as a delimiter.
## How it works
```
26R;`,@ØẠyK - Main link. Takes a string s on the left
26R - Yield [1, 2, ..., 26]
;` - Concatenate it to itself; [1, 2, ..., 26, 1, 2, ..., 26]
ØẠ - Yield "ABC...XYZabc...xyz"
,@ - Pair; [["A", "B", ..., "Z", "a", ..., "z"], [1, 2, ..., 26, 1, ..., 26]]
y - Transliterate s according to the mapping above
K - Join by spaces
```
[Answer]
# Q, 53
```
{1_ssr[-3!(`$'x)^`$(.Q.a!($)1+(!)26)@(_)x;"``";" "]}
```
Backtick Delimited
```
q){1_ssr[-3!(`$'x)^`$(.Q.a!($)1+(!)26)@(_)x;"``";" "]}"Here's another example, I hope that this will illustrate my point! If it's unable, more specs will be given."
"8`5`18`5`'`19 1`14`15`20`8`5`18 5`24`1`13`16`12`5`, 9 8`15`16`5 20`8`1`20 20`8`9`19 23`9`12`12 9`12`12`21`19`20`18`1`20`5 13`25 16`15`9`14`20`! 9`6 9`20`'`19 21`14`1`2`12`5`, 13`15`18`5 19`16`5`3`19 23`9`12`12 2`5 7`9`22`5`14`."
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
¬®r\lÈc uH
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVM&code=rK5yXGzIYyB1SA&input=IkhlcmUncyBhbm90aGVyIGV4YW1wbGUsIEkgaG9wZSB0aGF0IHRoaXMgd2lsbCBpbGx1c3RyYXRlIG15IHBvaW50ISBJZiBpdCdzIHVuYWJsZSwgbW9yZSBzcGVjcyB3aWxsIGJlIGdpdmVuLiI)
```
¬®r\lÈc uH :Implicit input of string
¬ :Split
® :Map
r : Replace
\l : /[A-Z]/gi
È : Pass each match through a function
c : Character code
u : Modulo
H : 32
```
] |
[Question]
[
>
> **Note to Moderators and editors**:
> This post's title is for effect and should not be changed. The misspelling is intentional and part of the challenge.
>
>
>
# Backstory
The (stereo)typical bad SO question asks something along the lines of "plz send teh codez!" In other words, it asks someone to do the work for the asker and provide a complete solution to a one-time problem. I quote [this question on Meta.SE](https://meta.stackexchange.com/questions/193580/is-the-use-of-plz-send-teh-codez-and-its-derivatives-acceptable-in-stack-excha/193581):
>
> ...its about a specific category of questions which consist of absolutely no research, no effort, and simply ask for the complete solution to a problem. These types of questions generally tend to assume that Stack Overflow is a free coding service...
>
>
>
# So what is your actual challenge? Its simple:
Your program or function, etc. must take input as a string (from STDIN, parameter, etc.) and if the string contains `Plz send teh codez!` output `-1 flag comment` (downvote, flag as off-topic, and comment about how bad a question it is.) Otherwise output `+1` (you are upvoting).
# But wait… there's more!
Your program ***must not*** contain 5 or more of these character sets:
* All special characters (anything not a space, newline (`0x0a`), case-insensitive alphabet, or digit)
* Any digit (0-9)
* Any of `pzcm` (case-insensitive)
* Any of `hten` (case-insensitive)
* Any of `qwryuioasdfgjklxvb`
* Any of `QWRYUIOASDFGJKLXVB`
To be clear, you can only use up to 4 of those charsets.
**Spaces, tabs and newlines are not restricted in any way, but they still are included in your byte count**
# Final restriction
Your program must contain Unicode **ONLY** in the range of `0x20` (space) to `0x7e` (~), as well as `0x0a` (LF newline) and `0x09` (tab). This is to exclude code golfing languages and give traditional languages a change or at least level the playing field.
# Notes:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins!
* Input can be from STDIN, a function parameter, command-line parameter, etc. but **not a variable**.
* Output can be to STDOUT, a function return value, or even an error/exception. Can include a trailing newline.
* Traditional languages are encouraged to compete because this challenge bans a lot of golfing languages by excluding high Unicode characters. C might even have a chance of winning!
* Any questions? Comment below!
# If it's too hard…
You can ignore the character sets in your answer, but it then becomes non-competitive.
# NOTE: You can now use up to 4 character sets. You're welcome.
You can use this snippet to check if your code is valid:
```
let f = code => {
let sets = Array(6).fill(false);
code = code.replace(/\s/g, "");
code = code.replace(/\d/g, _ => (sets[0] = true, ""));
code = code.replace(/[pzcm]/gi, _ => (sets[1] = true, ""));
code = code.replace(/[hten]/gi, _ => (sets[2] = true, ""));
code = code.replace(/[qwryuioasdfgjklxvb]/g, _ => (sets[3] = true, ""));
code = code.replace(/[QWRYUIOASDFGJKLXVB]/g, _ => (sets[4] = true, ""));
if (code) sets[5] = true;
return sets.reduce((a, b) => a + b, 0);
}
```
```
<textarea oninput="var x=f(value);O.innerHTML='You\'re using '+x+' charset'+(x===1?'':'s')+(x>4?', which is too many.':'. Nice job!')"></textarea><br>
<p id=O></p>
```
[Answer]
## JavaScript (ES6), 60 bytes
```
x=>/Plz send teh codez!/.test(x)?~x+' flag comment':'+'+-~[]
```
Everything was straightforward, except avoiding using `1` anywhere. I use `~x` to get `-1` (since if `x` contains `Plz send teh codez!`, it's not a valid number and therefore `~x` will give `-1`), and `-~[]` to get `1` (since if `x` is e.g. `'7'`, `-~x` will be `8`, so we can't rely on `x`).
### Test snippet
```
let f =
x=>/Plz send teh codez!/.test(x)?~x+' flag comment':'+'+-~[];
console.log(f("Hello, Plz send teh codez!"))
console.log(f("Hello, Plz send teh codez?"))
```
[Answer]
# JS (JSFuck), 37959 bytes
[Here's a gist](https://gist.github.com/hjroh0315/e6a34001577f0d8f64c95cdf24a80dd8), since PPCG hates long codes.
Only uses special characters. :P
Heres the original code:
```
alert(prompt().includes("Plz send teh codez!")?"-1 flag comment":"+1")
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~50~~ ~~49~~ 48 bytes
```
q"Plz send teh codez!"#)"- flag comment""+"?(T)@
```
Doesn't use digits or the capital letters set.
[Try it online!](https://tio.run/nexus/cjam#@1@oFJBTpVCcmpeiUJKaoZCcn5JapaikrKmkq5CWk5gOFMjNTc0rUVLSVrLXCNF0@P/fIzWnQAGLJoWQjMS8bAA "CJam – TIO Nexus")
**Explanation**
```
q e# Push the input
"Plz send teh codez!"# e# Find index of "Plz send teh codez!" in the input (-1 if not found)
) e# Increment the index
e# Check the truthiness of the index:
"- flag comment" e# If truthy (i.e. it appeared in the input), push this string
"+" e# If falsy (it wasn't in the input), push this string
? e#
( e# Uncons from left, removes the first character of the string and
e# pushes it on the stack
T) e# Push 0, and increment it to 1
@ e# Bring third-from-top stack element to the top
e# Implicit output of stack contents
```
[Answer]
# C, 102 bytes
```
i;f(char*s){i=strstr(s,"Plz send teh codez!");printf("%+d%s",i?'a'-'b':'b'-'a',i?" flag comment":"");}
```
Doesn't use any digit or any of `QWERTYUIOASDFGHJKLXVBN`. [Try it online!](https://tio.run/nexus/c-gcc#bYxhCoQgEIWv4g6IutkFitgr7BUsdRtIWxx/FZ3d5gDBe/D44HsNx6iX1ZU3mRMnqoWjycJ3OwSF7EUNq1h2H44XmPFfMNeoQXZeElj8KKd6NauB2/NmAiJu7sdKSiFXGIC1qyWHWZuT1efjq90 "C (gcc) – TIO Nexus")
[Answer]
## [Retina](https://github.com/m-ender/retina), 56 bytes
```
(?!.*Plz send teh codez).+
.+
-$#+ flag comment
^$
+$#+
```
[Try it online!](https://tio.run/nexus/retina#ZY5BDoIwEEX3PcUnYkRRruBOXbowcWcsMEBD6RDamsDlseKSxWSS9//LzDa5vufkHGWHu55gyZRw1KDgkqZ9lgoR5hRvUlRa1gF3HRknXrFIA5znG@k@wlqNcJHWZeLJXpcY2aNna1WuR@SEVoUuGfZ1A8dwgzS2Uw6uob/@ox0d0WuSNmxVQbmdheFQ4pD5IpgD@1zTGY9GmnY58qFhXMJIiH711Bc "Retina – TIO Nexus")
Uses special characters, the two case insensitive letter sets and other lower-case letters.
First we remove the entire input if it doesn't contain `Plz send teh codez`. If there is any input left we replace it with `-1 flag comment`, avoiding the digit with `$#+`. `$+` refers to the last capturing group which is `$0` (the entire match) sind there are no capturing groups. `$#+` then gives the number of captures, which is always `1`.
Finally, if the string is still empty (i.e. we cleared it in the first stage), we replace it with `+1` (again using `$#+` for the `1`).
[Answer]
# Python 2, ~~95~~ ~~94~~ 87 Bytes
Uses special characters and all lowercase lowers (plus three char sets and except for "p", which is case insensitive) for a total of **four characters sets used**.
```
b=ord('b')-ord('a')
print["+"+`b`,`-b`+" flag comment"][input()=="Plz send teh codez!"]
```
[Try it online!](https://repl.it/GqPF/4) Thanks to @math\_junkie for saving 8 bytes! Thanks to @officialaimm for saving two bytes!
---
```
a=ord
```
Let `a` be the `ord()` built-in function.
```
b=str(a('b')-a('a'))
```
This is really `b=1`.
```
print["+"+b, "-"+b+" flag comment"][input()=="Plz send teh codez!"]
```
If the statement in the second pair of brackets is true, print the second string in the first pair of brackets. Otherwise, print the first one.
[Answer]
# Python 2/3, ~~81~~ ~~76~~ 68 bytes
```
lambda x:["+%s","-%s flag comment"]["Plz send teh codez!"in x]%+True
```
Uses:
* All special characters (anything not a space, newline (0x0a), case-insensitive alphabet, or digit)
* Any of `pzcm` (case-insensitive)
* Any of `hten` (case-insensitive)
* Any of `qwryuioasdfgjklxvb`
Doesn't use:
* Any of `QWRYUIOASDFGJKLXVB`
* Any digit (0-9)
*-8 bytes thanks to math\_junkie*
[Answer]
# C#, 77 bytes
```
x=>x.Contains("Plz send teh codes!")?$"{'x'-'y'} flag comment":$"+{'x'/'x'}";
```
Not being able to use digits is such a pain.
[Answer]
# Groovy, 78 bytes
```
{a="a".length();it.contains("Plz send teh codez!")?-a+" flag comment":"+"+a}
```
Doesn't use the numbers or the uppercase sets.
Just a straightforward use of the ternary operator. `"a".length()` is a workaround to get 1
[Answer]
# Python 3, 115 bytes
```
if"p".upper()+"lz send teh codez!"in input():print("-"+str(len('a'))+" flag comment")
else:print("+"+str(len('a')))
```
It doesn't use numbers or upper case letters.
[**Try it online**](https://tio.run/nexus/python3#Zc2xDYQwDEDR/qYwbrAVwQBMwQoIDEQKxkpMw/I5mmu4/j/9Glc07C8zycQB0w1FdAGXHeZzkbvBqBDVLiceLEd1wg5D8UxJlNqp5YfBmqbtAcch6sgfSUV@dXjVXOv4v/kC)
[Answer]
## [Pip](https://github.com/dloscutoff/pip), 48 bytes
```
s.a@?"Plz send teh codez!"?v." flag comment"'+.o
```
Tied with CJam.
I am very mad that I was unable to get this under 48 bytes.
The program uses Pip's predefined variables to get around the number sequence, and it doesn't have any characters from the Capitals sequence.
[Try it online!](https://tio.run/##K8gs@P@/WC/RwV4pIKdKoTg1L0WhJDVDITk/JbVKUcm@TE9JIS0nMR0okJubmleipK6tl////39MxQA "Pip – Try It Online")
[Answer]
# Common Lisp, 81 bytes
Special + lower case + 2 mixed-case = 4 charsets
```
(format t"~:[+~s~;-~s flag comment~]"(search"Plz send teh codez!"(read-line))(*))
```
Ungolfed
```
(format t "~:[+~s~;-~s flag comment~]"
(search "Plz send teh codez!" (read-line))
(*))
```
Explanation
`(read-line)`
Accepts a line of input from `*standard-input*` (STDIN, by default).
`(search "Plz send teh codez!" ...)`
Scans through the second argument (the read in line) for the index where the first argument starts. Returns either this index or `nil` (false) if it could not be found.
`(*)`
Multiplication in lisp is defined to take an arbitrary number of arguments, including none- in that case it always returns 1.
`(format t "~:[+~s~;-~s flag comment~]" ...)`
`#'format` is similar to `fprintf` or `sprintf` in C. It's first argument, `t`, designates the output as `*standard-output*` (STDOUT, by default). The next argument is the format string. "~" is used like "%" in `printf`- the character(s) following it designate a formatting operation.
`"~:[<a>~;<b>~]"` is the conditional formatting operation. It takes an argument and continues with `<a>` if the argument was `nil` (false). Any other value, like `t` (true) or a number (for example), has it continue with `<b>`. The third argument to format (the first, after `t` and the format string) is the search, so `<a>` will be chosen if the search fails (and `<b>` otherwise).
In this case, the `<a>` (`nil`/false) branch prints "+~s". "~s" converts a format argument to a string and prints out its characters. The fourth argument to format (the second, after `t` and the format string) is `(*)` or 1, so we get "+1" printed.
The `<b>` branch is similar: "-~s flag comment". It also uses the fourth (second) argument to fill in its "~s", so it prints out "-1 flag comment".
[Answer]
# sh + sed, 72 bytes
Uses character sets: 1, 3, 4, 5.
```
let ""
sed "s/.*Plz send teh codez!.*/-$? flag comment/
tz
s/.*/+$?/
:z"
```
At first, I wanted to go with pure sed, but I had no idea how to avoid using digits. So I used sh just for that. `let ""` has an exit status of `1`, since it can't be evaluated as an arithmetic expression.
`z` is just a label and can be replaced with any other character.
[Answer]
## Mathematica, 265 bytes
This was hard.
```
t[s_,n_]:=ToString@s~StringTake~{n};If[StringFreeQ[#,t[Head[a^b],i=-I I]<>"l"<>(s=t[RSolve[f[a+i]==f@a-i/Sqrt@a,f@a,a],(i+i+i+i)^(e=i+i+i)+i+e])<>" send teh "<>(k=t[i/Sin@x,e])<>"ode"<>s<>"!"],"+"<>t[i,i],"-"<>t[i,i]<>" flag "<>k<>"o"<>(n=Head[a b]~t~e)<>n<>"ent"]&
```
Readable version:
```
t[s_, n_] := ToString@s~StringTake~{n};
If[StringFreeQ[#,
t[Head[a^b], i = -I I] <>
"l" <> (s =
t[RSolve[f[a + i] == f@a - i/Sqrt@a, f@a,
a], (i + i + i + i)^(e = i + i + i) + i + e]) <>
" send teh " <> (k = t[i/Sin@x, e]) <> "ode" <> s <> "!"],
"+" <> t[i, i],
"-" <> t[i, i] <> " flag " <> k <> "o" <> (n = Head[a b]~t~e) <> n <>
"ent"] &
```
Uses special characters, `hten`, `qwryuioasdfgjklxvb` and `QWRYUIOASDFGJKLXVB`. Mathematica without special characters would be basically impossible, and almost all string-related functions include `String` in their name, so that really limits the choice here…
To get the other character sets, we need a few tricks. Firstly, to get `1` we take the negative of the square of the imaginary number `I`: `i = -I I`. Later we also define `3` by `e = i+i+i`.
The letter `P` was fairly straightforward: Mathematica treats `a^b` internally as `Power[a,b]`, so all we need to do is take the head of this (`Power`), turn it into a string, and take the first (aka `i`th) letter. (We'll be turning things into strings and taking the *n*th letter a lot, so we define `t[s_,n_]:=ToString@s~StringTake~{n}`.) The letter `m` is similar: take the head of `a b`, which is `Times`, and get the third (aka `e`th) letter.
The letter `c` is slightly harder: we use the trigonometric identity `1/Sin[x] == Csc[x]` (or rather `i/Sin[x]` since we can't use `1`), and take the third letter of `Csc[x]`.
The really hard part is the `z`. To make a `z`, we use the `HurwitzZeta` function (yes, really). We get that by solving the recurrence relation `RSolve[f[a + i] == f@a - i/Sqrt@a, f@a, a]`, which yields the string
```
" 1 1
{{f[a] -> C[1] + HurwitzZeta[-, a] - Zeta[-]}}
2 2"
```
of which the 68th character is `z`. We get the number 68 as `4^3 + 4`.
This could probably be golfed further: the Hurwitz zeta stuff is pretty much copied from the Mathematica documentation, and there's probably a shorter way of getting 68 — or we could use another method entirely for the `z`. Any suggestions?
[Answer]
# Python 3.5 (137 102 98 87 85 94 Bytes)
### Uses small-case letters(3 charsets) + special characters(1 charset) = 4 charsets
### i was almost planning to avoid whitespaces as well but the indentation in python forced me to keep one newline so i left the whitespaces as they were.
```
i=str(ord('b')-ord('a'))
print(['+'+i,'-'+i+' flag comment']['Plz send teh codez!'in input()])
```
[Try it online!](https://tio.run/nexus/python3#bYoxDoMwEAT7vOJSrU8OT8gf0iMKgg1cBAeyj8afdxA1zWg0mirvbMltKTh8wc0lPZgfexI118LDywvNSQ8al36iYVvXqIauxWcplKMGsjifPcTyhCiJ7oc57rjWm4NCnn9/ "Python 3 – TIO Nexus")
* saved 35 bytes!!!!: apparently i had forgotten the existence of upper() function before(silly me!!)
* saved 4 bytes: reduced i=input() to just input()
* saved 11 bytes!!!: Thanks to [Anthony-Pham](https://codegolf.stackexchange.com/users/36594/anthony-pham) (used 'P' since it is valid in charset)
* saved 2 bytes: (removed a=ord; learnt that shortening a function is not always a good idea! :D)
* added 9 bytes: Thanks to [math-junkie](https://codegolf.stackexchange.com/users/65425/math-junkie) for pointing out that I was not displaying +1 for strings with no 'Plz send teh codez!' before.
[Answer]
# Swift (non-competitive) - 64 bytes
```
print(x.contains("Plz send teh codez!") ?"-1 flag comment":"+1")
```
Unfortunately used 5 charsets, couldn't make it without them... Suggestions are welcome!
] |
[Question]
[
[On a standard 88 key piano, each key has a scientific name.](http://en.wikipedia.org/wiki/Piano_key_frequencies)
The first three keys are A0, B♭0, and B0. The keys then proceed through C1, D♭1, D1, E♭1, E1, F1, G♭1, G1, A♭1, A1, B♭1, B1, and start over again at C2. This continues up through B7, and the final key is C8.
Any flat can instead be written as a sharp of the preceding note, e.g. D♭4 can also be written C♯4. If necessary, you can write "D♭4" as "Db4".
Your program should build an ordered sequence (array, list, vector, etc.) containing the key names (as strings, symbols, or some similar data structure) in order.
Program length should be measured in *characters*, to avoid penalizing people who properly generate ♯ or ♭ rather than # or b. However, Unicode recoding is forbidden.
[Answer]
## Bash shell script (58)
```
echo {8..0}{B,♭B,A,♭A,G,♭G,F,E,♭E,D,♭D,C}|rev|cut -b40-410
```
If you do not have `rev`, you can instead use `tac -rs.` at a cost of five characters.
[Bending the rules](https://codegolf.stackexchange.com/questions/6278/universal-rule-bending-code-golf-solver), I can subtract thirteen characters (for a score of 45):
```
echo {8..0}{B,♭B,A,♭A,G,♭G,F,E,♭E,D,♭D,C}|rev
```
If you really need a bash array, add six characters to the score (for a score of 64):
```
a=(`echo {8..0}{B,♭B,A,♭A,G,♭G,F,E,♭E,D,♭D,C}|rev|cut -b40-410`)
```
[Answer]
### GolfScript, 60 57 characters
```
"A BbB C DbD EbE F GbG Ab"88,{1$2<@2>1$+\{8%},@9+12/+}%\;
```
The snippet produces the following array (see [here](http://golfscript.apphb.com/?c=OwoiQSBCYkIgQyBEYkQgRWJFIEYgR2JHIEFiIjg4LHsxJDI8QDI%2BMSQrXHs4JX0sQDkrMTIvK30lXDsKcAo%3D)):
```
["A0" "Bb0" "B0" "C1" "Db1" "D1" "Eb1" "E1" "F1" "Gb1" "G1" "Ab1"
"A1" "Bb1" "B1" "C2" "Db2" "D2" "Eb2" "E2" "F2" "Gb2" "G2" "Ab2"
"A2" "Bb2" "B2" "C3" "Db3" "D3" "Eb3" "E3" "F3" "Gb3" "G3" "Ab3"
"A3" "Bb3" "B3" "C4" "Db4" "D4" "Eb4" "E4" "F4" "Gb4" "G4" "Ab4"
"A4" "Bb4" "B4" "C5" "Db5" "D5" "Eb5" "E5" "F5" "Gb5" "G5" "Ab5"
"A5" "Bb5" "B5" "C6" "Db6" "D6" "Eb6" "E6" "F6" "Gb6" "G6" "Ab6"
"A6" "Bb6" "B6" "C7" "Db7" "D7" "Eb7" "E7" "F7" "Gb7" "G7" "Ab7"
"A7" "Bb7" "B7" "C8"]
```
*Edit:* Changed from `" "/""*` to `{8%},` to remove space.
[Answer]
# Python 103 96 94 78
```
[x+y for y in'0123456789'for x in'C Db D Eb E F Gb G Ab A Bb B'.split()][9:97]
```
updated according to Ev\_genus's suggestion
updated according to Howard's suggestion
[Answer]
# Ruby: ~~75~~ 71 characters
```
[*?0..?9].product(%w{C Db D Eb E F Gb G Ab A Bb B}).map{|a,b|b+a}[9,88]
```
(Base idea borrowed from [Matt's solution](https://codegolf.stackexchange.com/a/6808).)
[Answer]
# Mathematica 95 112 100 97 104 chars
Admittedly not very streamlined:
```
Take[Flatten@Table[# <> ToString@k & /@
Partition[Characters[" CDb DEb E FGb GAb ABb B"], 2], {k, 0, 8}], {10, 97}]
```
The Flat symbol, although it occupies a single character, is transcribed to SO as `\[Flat]` so I used the letter "b" here.
Output:

```
Length@%
(* out *)
88
```
[Answer]
## *Mathematica*, 88
88 characters for 88 keys :-)
```
(Row@{#2,#1}&@@@Tuples@{0~Range~8,StringSplit@"C D♭ D E♭ E F G♭ G A♭ A B♭ B"})[[10;;97]]
```
[Answer]
## J, 81 76 63 62 61 58 characters
```
_11}.9}.(_2]\,|:9#"0'C DbD EbE F GbG AbA BbB '),.12#1":i.9
```
Output:
```
A 0
Bb0
B 0
C 1
Db1
D 1
Eb1
E 1
...
G 7
Ab7
A 7
Bb7
B 7
C 8
```
Probably a bit of room for shortening here.
[Answer]
# C (92 84 characters)
Not impressive, could be reduced further.
```
main(i){for(i=9;printf("%c%c%d\n","CDDEEFGGAABB"[i%12]," b b b b b "[i%12],i/12),++i<97;);}
```
Using Dietrich Epp's suggestion :
```
main(i){for(i=9;printf("%.2s%d\n","C DbD EbE F GbG AbA BbB "+2*i%24,i/12),++i<97;);}
```
It produces the following output :
```
A 0
Bb0
B 0
C 1
Db1
D 1
Eb1
E 1
F 1
Gb1
... // lines skipped
Eb7
E 7
F 7
Gb7
G 7
Ab7
A 7
Bb7
B 7
C 8
```
[Answer]
# C, 105 chars
## - failing on size, so ended up aiming for a wtf different solution.
Probably only works on little-endian arch (e.g. intel) due to assumptions of treating int as small string...
Assumes C program is called with no arguments, i.e. that w=1
```
t=12352,f;
main(w){
t=t&64?t>>8:(w=1+w%7,(w-3)%3?t<<8|98:t+(w==3));
f=t<<8|w+64;
puts(&f);
f-14403?main(w):0;
}
```
Output:
```
A0
Bb0
B0
C1
Db1
D1
Eb1
E1
F1
Gb1
G1
Ab1
--lines skipped--
Bb7
B7
C8
```
## Edits
* -9 chars - removing some brackets and reorganising an 'if'
* -18 chars - code shuffling, sub 64 from w and pass as main arg
* -13 chars - Use 't' to carry state rather than 'f'
[Answer]
## Haskell: 72 chars
```
take 88$drop 9[p++show o|o<-[0..],p<-words$"C D♭ D E♭ F F♯ G G♯ A B♭ B"]
```
[Answer]
# Clojure - 71 chars
```
(for[c(range 10)n["C""Db""D""Eb""E""F""Gb""G""Ab""A""Bb""B"]](str n c))
```
[Answer]
## Perl, 57+1
Just dug this up, a nice golfing exercise. Requires `-E` for `say` -- counted in score.
`say+(CDbDEbEFGbGAbABbB=~/(.b?)/g)[$_%12],$_/12%9for 9..96`
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 88 bytes
```
(o=`C,Db,D,Eb,E,F,Gb,G,Ab,A,Bb,B`.split`,`)=>o.flatMap((x,i)=>o.map(n=>n+i)).slice(9,97)
```
[Try it online!](https://tio.run/##HchJDgIhEAXQ61TFL1vTCzrptoeVd2AQDQYpIsR4ezQu33vYt63@FUs7ZrmG7iVXSUEluRN1Em3OWBwWrA4rNuwOOyaHCbPDbFQtKTYDw3oUdUu2XWwh@iD@4/lD1mM@RGZVU/SBBgwn7kzM/Qs "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
Given an array of integers as input(including negative integers), find all (can include duplicates) permutations that **do not** have the same number next to each other, then print them all out.
If no permutations were found, print Nothing or return an empty list or any consistent output indicating that none were found.
Note that the original array can be a permutation.
Test cases:
```
[0, 1, 1, 0] -> [1, 0, 1, 0], [0, 1, 0, 1]
[0, 1, 2, 0] -> [0, 1, 2, 0], [0, 2, 1, 0], [1, 0, 2, 0], [0, 1, 0, 2], [2, 0, 1, 0], [0, 2, 0, 1]
[0, 1, 0] -> [0, 1, 0]
[1, 1, 1] -> [] or Nothing
[0, 0, 1, 1] -> [0, 1, 0, 1], [1, 0, 1, 0]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), all usual golfing rules apply and the shortest answer (in bytes) wins!
Leaderboard:
```
var QUESTION_ID=244078;
var OVERRIDE_USER=8478;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
```
```
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
Ṗ'¯A
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZYnwq9BIiwiIiwiWzEsMCwxLDJdIl0=)
Port of Jonathan Allan's Jelly answer.
-1 thanks to ovs.
[Answer]
# [J](http://jsoftware.com/), 30 bytes
```
[:~.@(#~0=1#.2=/\"1])i.@!@#A.]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o63q9Bw0lOsMbA2V9Yxs9WOUDGM1M/UcFB2UHfVi/2typSZn5CukAXUYKhgpGEC46rq66sgShtgkQMKG2NSDdXBx@TnpKUQb6CgY6igYAV0VqwPmGYEFwDwQjSIHFQDxjMBMQxR9IIHY/wA "J – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 69 bytes
```
import Data.List
f=(filter$and.(zipWith(/=)<*>tail)).nub.permutations
```
[Try it online!](https://tio.run/##bcqxDsIgEIDhvU9xQwcwBMFZnDq6OxiHM4X0IlBCr4svj8Y4VfNvX/4Jl4ePsTVKZa4MAzLqMy3cBScCRfa1xzxq8aRyIZ7E3snj7sRIUUqd17suvqaVkWnOS0tIGRyMM3RQKmWGHgJcjbLvzG2DYBUcFPz1DdoP2p/TfL29AA "Haskell – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `grouping.extras math.combinatorics`, 59 bytes
```
[ [ [ = ] 2clump-map vnone? ] filter-permutations members ]
```
[Try it online!](https://tio.run/##XY67DoJAEEV7vmJ@AAKUGmNpbGyMlaFYNgNuZB/OzhIN4dvXxZhgnFudM7e4nZBsKV7Ox9NhA3ckgwP0ZINTpi/wySQ8aMG3YsSl@QVpdauMSEJJDx7ZgyNkfjlShpN4BDQSPWyzbMog3QQlVCklzD9c//FK1Sfrr/zynMUrLNlBA7Ucgna5Fg5GYw3uk@vUwEi5Q9KBBStr0mbULabtTVyqRXwD "Factor – Try It Online")
* `[ ... ] filter-permutations` Select the permutations of the input for which `[ ... ]` returns true.
* `[ = ] 2clump-map` Map `=` to every two elements of a sequence with overlapping. e.g. `{ 1 0 1 1 2 } [ = ] 2clump-map` -> `{ f f t f }`
* `vnone?` Returns true only if every element of a sequence is `f`.
* `members` Get the unique elements of a sequence.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 35 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
{(‚à߬¥1¬´¬ª‚ↂä¢)¬®‚ä∏/‚ç∑ùï©‚äèÀú‚öá1‚çã‚àò‚çã‚ä∏‚â°Àú¬®‚ä∏/‚•ä‚Üï‚•äÀú‚â†ùï©}
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgeyjiiKfCtDHCq8K74omg4oqiKcKo4oq4L+KNt/Cdlaniio/LnOKahzHijYviiJjijYviirjiiaHLnMKo4oq4L+KliuKGleKlisuc4omg8J2VqX0KCuKImOKAvzHipYpGwqgg4p+oCuKfqDAsIDEsIDEsIDDin6kK4p+oMCwgMSwgMiwgMOKfqQrin6gwLCAxLCAw4p+pCuKfqDEsIDEsIDHin6kK4p+oMCwgMCwgMSwgMeKfqQrin6k=)
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 73 bytes
```
f(x)=r=[];forperm(vecsort(x),p,prod(i=2,#p,p[i]-p[i-1])&&r=concat(r,p));r
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWNz3TNCo0bYtso2Ot0_KLClKLcjXKUpOL84tKgOI6BToFRfkpGpm2RjrKQHZ0ZqwukNA1jNVUUyuyTc7PS04s0SjSKdDUtC6CGLi5oCgzr0QjTSPaQMcQCA1iNTUhMjArAQ)
After a lot of head scratching and asking @alephalpha in chat, here it is.
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~310~~ ~~301~~ ~~283~~ 278 bytes
EDIT: -22 bytes thanks to `ceilingcat` and -1 byte from the label statement.
```
#include"bits/stdc++.h"
#define c std::cout<<
#define Q&a[0],&*end(a))
#define T;for(j=0;j<a.size()
int j,k;l(std::deque<int>a){auto p=[&]{c"["T;)c","+!j<<a[j++];c"]";};p();c"->";for(std::sort(Q;std::next_permutation(Q;){T-1;)if(a[j]==a[++j])goto e;c","+1/++k;p();e:;}k||c"[]";}
```
[Try it online!](https://tio.run/##PY7RboMgGEbv@xSOJgYGtrpLwb5DE@8MWRiiQy06wWWZ9dXnKBe9@3L@5JxfTlPSSrnvR23ksNQKfGhnz9bVEuPTJzgca9VooyIZeZbnclwcY096jUWVchK/KlNDgdDzUNJmnGFXpLRj4mT1r4LooI2LOtLTAQZXrb4WxTy8CLSKxY3RVFQxXyWoQEmRBATgl44xUXUYcyoBB3SjE0R@JhcQCkFkx9nBKw3bqB/3Pqn5tjjh9Gg8R2uZZBTpBnoTLwpRYdxx1I6@qGjIZGeM@6BWOd36@93/8KjtN6ENROsA14xkJCVvG/J0/5PNIFq7J80jpa3V3@of "C++ (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
≈ì í¬•ƒÄP
```
Includes duplicated items.
[Try it online](https://tio.run/##yy9OTMpM/f//6ORTkw4tPdIQ8P9/tIGOIRAaxAIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/o5NPTTq09EhDwP9anf/R0QY6hkBoEKsDZhnBWSAaJGMI5oNVxcYCAA).
**Explanation:**
```
œ # Get all permutations of the (implicit) input-list
í # Filter it by:
¥ # Get the deltas/forward-differences
Ā # Check for each whether it's NOT 0
P # Product: check if all of them are truthy
# (after which the result is output implicitly)
```
`¥Ā` could alternatively be `üÊ` for the same byte-count:
```
ü # For each overlapping pair:
Ê # Check that they are not equal
```
[Answer]
# JavaScript (ES6), 90 bytes
Returns a set of strings.
```
f=(a,p=[],s=new Set)=>a.map((v,i)=>v==p[0]||f(a.filter(_=>i--),[v,...p],s))+a?s:s.add(p+a)
```
[Try it online!](https://tio.run/##fczBCsIwEATQu1/R4y5Nl9SjsPoRHkORpU0kUpvQlHjpv8ei4KkIcxkeMw/JkvrZx6WZwmBLcQyiIptOJZ7sq7raBfks9JQIkJXfSmaORnfr6kDI@XGxM9z47JsGlcmKiOK2Rqzlkk6JZBgg1oKlD1MKo6Ux3MGB0apqP9Ed4mEXj/9wT76H7f5G/7C8AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~55~~ 53 bytes
```
->l{[]|l.permutation.select{|r,*f|f.all?{|x|r!=r=x}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOjq2JkevILUot7QksSQzP0@vODUnNbmkuqZIRyutJk0vMSfHvrqmoqZI0bbItqK2tvZ/gUJadLSBjiEQGsTGcoG5II5hbOx/AA "Ruby – Try It Online")
Thanks AZTECCO for -2 bytes
[Answer]
# [Python 3](https://docs.python.org/3/), 88 bytes
*Thanks to user `loopy walt` for `-7 bytes` and user pxeger for `-1 byte`.*
Returns a set of non-duplicate tuples. For the `nothing` case an empty `set()` is returned.
```
lambda l:{p for p in permutations(l)if p[:len([*groupby(p)])]==p}
from itertools import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY7PCoMwDMbvPkVua0VBdxqCe45B14MysxVqG2o9iPgkuwhje6e9zfzTy0Ig-UK-X_L80OAf1swvLK_v3mN6-l501da3CnQxEqB1QKAMUOPa3ldeWdMxzRUCiUI3hon47mxP9cCISy7LkqYInW1B-cZ5a3UHqiXrfBz4uDL1yhQiSyDfMpMJBHX8U1u77-RhGkxSFhEsQU4Zz_Aw6gnSM4y4vDcd-H5tnvf6Aw)
# [Python 3.10](https://www.python.org), 95 bytes
*Thanks to user `LeopardShark` for `-1 byte`.*
```
lambda l:{p for p in permutations(l)if all(i!=j for i,j in pairwise(p))}
from itertools import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY5BCoMwEEX3PcV0ZVIUtKsi2ItYKSl16EhiQoyUIp6kG6G0d-ptqjGbDgMzf3ifP8-PebibbqcXFqd37zA5fM9SqMtVgMwHA6gtGKAWTG1V74Qj3XZMckIQUjLaFo1nKG48JcjeqauZ4XzcoNUKyNXWaS07IGW0dbsQg4tNLqayTGPIfKdVDEHt_5RfVyYL12CqqnwDcxlLrWMYDXKE5AgDzl-OEV_TpmmdPw)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Œ!IẠ$Ƈ
```
**[Try it online!](https://tio.run/##y0rNyan8///oJEXPh7sWqBxr////f7ShjoGOoY5RLAA "Jelly – Try It Online")**
### How?
```
Œ!IẠ$Ƈ - Link: list of numbers, A
Œ! - all permutations of A
Ƈ - filter keep those for which:
$ - last two links as a monad:
I - forward differences
Ạ - all non-zero?
```
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 53 bytes
```
[]#s=s
(x++a:y)#s|s==[]||a/=head s=(x++y)#(a:s)
(#[])
```
[Try it online!](https://tio.run/##FclBCoAgEADAe69Y8KJoZB2FfYl4WCwpogiXIMG/W8114p1z6S/aI7fmg2DkTj5akytKcGVEH2qlAdeFZmD87xtJjlWXUAofVDtoOwEhgbcGRgOTARvaCw "Curry (PAKCS) – Try It Online")
Curry supports non-deterministic operations which can return different values for the same input. This is a non-deterministic function whose different return values are the all complex permutations (including duplicates).
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes
```
p.{s‚ÇÇ=}·∂ú0‚àß
```
A [generator](https://codegolf.meta.stackexchange.com/a/10753/16766) predicate that takes a list through its input parameter and produces permutations (including duplicates) through its output parameter. [Try it online!](https://tio.run/##ATMAzP9icmFjaHlsb2cy/@KGsOKCgeG6ieKKpf9wLntz4oKCPX3htpww4oin//9bMCwwLDEsMl0 "Brachylog – Try It Online")
### Explanation
```
p.{s‚ÇÇ=}·∂ú0‚àß
p Get a permutation of the input list
. This is the output
{ }·∂ú Count the number of ways to:
s‚ÇÇ Get a length-2 sublist
= whose elements are equal
0 Assert that the result is 0
‚àß Don't try to unify 0 with the output
```
[Answer]
# [Scala](http://www.scala-lang.org/), 162 bytes
Port of [@G B's Ruby answer](https://codegolf.stackexchange.com/a/244114/110802) in Scala.
---
Golfed version. [Try it online!](https://tio.run/##bU5Na8MwDL3nV@hoQwntVeBCdxtsu4ydSilq5nQqjl1sBRJCfntqp6eNCSHQ@@C91JCjJVxuthF4J/YwLd@2hV45fOMkx1cvJ21cfbex64WEg091y05sVKxrCUVVFQv/suBLCM6SNw46kuZnaihZ@GBn9hJ7C@t7RvyDDIgj4pDMnls1GDPqllzGbTmsVk7PC0BJ7HJfRfGaEA4x0nj8lMj@msPhy7OAgamCPPeMivOqV6Wf2m5gt@5Wa/2f4MnunuxczcsD)
```
def u(l:List[Int])=l.permutations.filter(i).toList
def i(l:List[Int]):Boolean=l match{case Nil=>true case _::Nil=>true case x::y::xs=>if(x==y)false else i(y::xs)}
```
Ungolfed version. [Try it online!](https://tio.run/##jVBNS8QwEL33V7xjAlJ2r4EK6klQEcTTskis0zWSpmsylRbpb69JtywVKghhCG/ex8yEUls9js3rB5WMe20cvjPgjSq0zny29Ei@blmzaVwQ1gRWuIt1d@t4L@f/GdijmORAYubHhTavjGXywoTnyfcmYlS2bL5I5twkiygcsjl8hbaSft00lrT7lYpac/k@A0CpA@HBWBSXYN/SEn5R6o9Op1SvVBdSz1QQHYoCvUSlbexSKmsTTho5GQ3Lbep4V6H9IShcea/73RN74w5phWjC5/mPEWXrxMrp09pic4Ht9DZSyn8pTvTtiT5kwzj@AA)
```
object Main {
def uniquePermutations(list: List[Int]): List[List[Int]] = {
list.permutations.filter(isUniqueConsecutive).toList
}
def isUniqueConsecutive(list: List[Int]): Boolean = {
list match {
case Nil => true
case _::Nil => true
case x::y::xs => if (x == y) false else isUniqueConsecutive(y::xs)
}
}
def main(args: Array[String]): Unit = {
println(uniquePermutations(List(0, 1, 1, 0)))
println(uniquePermutations(List(1, 1, 1)))
}
}
```
[Answer]
# [R](https://www.r-project.org/), 93 bytes
```
\(v,m=permute::allPerms(v))for(i in 1:nrow(m)){l=v[m[i,]];if(all(l!=lag(l),na.rm=T))print(l)}
```
Prints in console, including duplicates:
>
> v=c(0,-2,1,0) ; a(v)
>
>
>
>
> [1] 0 -2 0 1
>
> [1] 0 1 -2 0
>
> [1] 0 1 0 -2
>
> [1] -2 0 1 0
>
> [1] -2 0 1 0
>
> [1] 1 0 -2 0
>
> [1] 1 0 -2 0
>
> [1] 0 -2 0 1
>
> [1] 0 -2 1 0
>
> [1] 0 1 0 -2
>
> [1] 0 1 -2 0
>
>
>
] |
[Question]
[
You work for a social media platform, and are told to create a program in a language of your choice that will automatically flag certain post titles as "spam".
Your program must take the title as a string as input and output a [truthy](https://codegolf.meta.stackexchange.com/a/2194) value if the title is spam, and a [falsey](https://codegolf.meta.stackexchange.com/a/2194/94032) value if not.
To qualify as non-spam, a title must conform to the following rules, otherwise it is spam:
* A title can only contain spaces and the following characters: a-z, A-Z, 0-9, `-`, `_`, `.`, `,`, `?`, `!`
* A title cannot have more than one Capital Letter per word
* A title cannot have more than one exclamation mark or question mark
* A title cannot have more than three full-stops (`.`)
* A title cannot have more than one comma (`,`)
Test cases:
```
Input: How On eaRth diD tHis happeN
Output: False
Input: How on earth did this happen üîä
Output: True
Input: How ON earth did this happen
Output: True
Input: How on earth did this happen??
Output: True
Input: How on earth did this happen?!
Output: True
Input: How on earth did this happen!!
Output: True
Input: How! on! earth! did! this! happen!
Output: True
Input: How on earth did this happen! !
Output: True
Input: How on earth did this happen?
Output: False
Input: How on earth did this happen!
Output: False
Input: How on earth did this happen...
Output: False
Input: How.on.earth.did.this.happen
Output: True
Input: How.on.earth.did this happen
Output: False
Input: How, on, earth did this happen
Output: True
Input: How, on earth did this happen
Output: False
Input: How_on_earth_did_this_happen
Output: False
Input: How-on-earth-did-this-happen
Output: False
Input: How on earth did (this) happen
Output: True
Input: How on earth did "this" happen
Output: True
Input: How on earth did 'this' happen
Output: True
Input: How on earth did *this* happen
Output: True
Input: How on earth did [this] happen
Output: True
```
# FAQ
**Q:** What is a valid title?
**A:** Single-character titles are valid. Your program has to validate a string that is not completely whitespace against the bullet-point rules above.
**Q:** What is a word?
**A:** Split the title string by a space. Each item in the resulting array is considered a word.
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~72 71 68~~ 64 bytes
-1 byte thanks to @ThisFieldIsRequired
-3 bytes inspired by @Neil's Retina answer
-2 bytes thanks to @emanresuA (see @Neil's answer)
-2 bytes by modifying final test slightly
```
m=>/[^\w-.,?! ]|[A-Z]\S*[A-Z]|[!?].*[!?]|,.*,|(\..*){4}/.test(m)
```
[Try it online!](https://tio.run/##ldS7TsMwGAXgvU9hd8lF9l/SlpuqErExwcBGEqKoDbSotava0IHwAszsvCJvEOIgRCj9G7M403eOLR3lIXvK1GQ9X2ku5DQvJ1IoTdS4XI7PetFtvOHAQkqSIjrnN0l87dffIqJhAr45CwY@K9wYwPeehy890LnS7tIrR52OCZOLHBby3nXIgcMoVa5zITdECpJnaz0j0/mU6NlckVm2WuWCfLy/vToe0@vH3BttBQSNgKvL3QGY7VuUhyGmBzaaYnpooSmqD380rTj98tQE0DqBfkdgCUc2/QTlxzaPr/BdtlB/9YlNOapPLTQAYD5obA6kgNpD5cF42DuZIEDs1tx2Fzf2xqqbs3@tNRj81ije3d3YWypFWuO0wqnBaQtuzI1LwWvMK8wN5i0YXZprtNfyanRoXaO7LRodWuwYHjstHp2ab7i/X/fRn1tkdLKty08 "JavaScript (Node.js) – Try It Online")
Regex abuse FTW.
Here's how it works:
* `[^\w-.,?! ]` matches any character that isn't allowed.
* `[A-Z]\S*[A-Z]` matches two uppercase letters without a space in between, i.e. two capitals in a single word
* `[!?].*[!?]` matches two exclamation/question marks with anything in between
* `,.*,` matches two commas with anything in between
* `(\..*){4}` matches four periods with anything in between
If you put these together in a single regex as alternates, you get a spam filter that matches all criteria.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~251~~ ~~219~~ ~~215~~ ~~199~~ ~~197~~ ~~193~~ ~~189~~ ~~184~~ 181 bytes
-32 bytes thanks to @ceilingcat
-4 bytes by subtracting 43 from `c`
-16 bytes by moving comparisons inside ternaries
-2 bytes by removing unneeded brackets
-4 bytes by realising that `++x>1` is equivalent to `x++`
-4 bytes by rearranging outer ternary and adjusting subtracted amount
-5 bytes by moving checks inside loop condition
-3 bytes by using the `n` array for storing the output.
```
#define C(l,h)c>l&c<h?n[l]++
f(char*s){int c,n[64]={1};while((c=*s++)&&!(c-=41,c+9?*n=c+8&&c-22?C(55,82)<0:C(23,50):C(6,17)<0:C(4,6)>2:C(2,4):c-4&&c-54:n[1]++:(n[23]=0)));return*n;}
```
[Try it online!](https://tio.run/##hZHBbqMwEIbP4SmGVCU2GASUZNsQkkP20FMr9UqjKDFQLGVNBFSVNsoL7Hnv@4r7BlmPk0iVugkcwJ7vs/0z5u4b54fDTZYXQuYwJxtWUj7dWHxSzmS6WTiOURBermq7oTshW@BMpqNokeyCffxRik1OCE/sxnGoZZmEu0kUMO48zGyZcOfesrgbhrM5GQ7ZfUgn/nhOwjs29KkajFjw7ViK2IhOQ2QsomPuRrhuGI1lGqgEYyLT8G6R@JTSuM7b91raMt4fboTkm/csh0nTZqLyyqlhYMQfKyEJhZ3Rw@CwTiP/YbSIT1ObqxFqQn31HwBp@EoWpH@b9RlYgjIQME3A13v0ire8bciaQSN@5lUBOFLnSRojrGogHBJYx7gzcNUIVe6JAoit6gkMXuVAl3o4Bx9XIS3ImoKZgNBwW6tIOgLW1Pu2eZUqDVoqDoM1Hrc39ocA8DF8eKw@4FlCvnppS8jEd2gfRQPlarvNn4xA4wpxrXEGbXnGEv7@@f3r5Dw//d/p2GI26xLMDsE8CaYyzKNiomNqyTxbXbuAeerFxSAdvGu953nHDF4lPW14yvDQ8E6t8r/gr51k6gB2odX@WbjGl5VcarxUeIl4@Rm7lXQ1dhV2EbuXL5Igp1duuo9C/4owQGFwRbBRsK8IKQqLs@AG/wA "C (gcc) – Try It Online")
The C macro increments a counter for a character class. I used decimal literals instead of char literals. When a space is encountered the uppercase counter is reset.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~55~~ ~~53~~ 51 bytes
```
[^-.,?!\w ]|[?!].*[?!]|,.*,|(\..*){4}|[A-Z]\S*[A-Z]
```
[Try it online!](https://tio.run/##fdGxCsIwEAbg3afICdIakpvci5NOOrjZ1liw0C6JaKGD9QWc3X1F36DmoiKKyZIM33@XcHcom1oX/Siebft0I1EkkLUs79IEcuR0dgK56OIMkY9Pk3OXTuU6z1bc3X0/Ny0zmpXFoanYrt6xpqqPrCr2@1Kz@@16GVBiufifGITKkyTMEGRwDNbhGQBKgIvAOxPuwMIe/l64FhHJ0Wh0jtaRHD@D@cLfqQnbWviHKrwvkyqjlUNlURGqD0qjpUNpURJK37Ji0rF3l0PioZcj4sjLnJh7OSXOX/wA "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 2 bytes thanks to @Ausername and another 2 bytes thanks to @nununoisy. Simply reports on the number of banned patterns it finds, so for some spam the truthy value might be greater than `1`; if this is undesirable, `1`` can be prefixed to the program which limits the count to `1`. Explanation:
```
[^-.,?!\w ] Check for illegal characters.
[?!].*[?!] Check for two question or exclamation marks.
,.*, Check for two commas.
(\..*){4} Check for four or more full stops.
[A-Z]\S*[A-Z] Check for two uppercase letters in the same word.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~38~~ ~~37~~ 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žj…,!?©… -.JÃÊ·IS#.uOI®S¢ā£OI'.¢;M2@
```
[Try it online](https://tio.run/##AV0Aov9vc2FiaWX//8W@auKApiwhP8Kp4oCmIC0uSsODw4rCt0lTIy51T0nCrlPCosSBwqNPSScuwqI7TTJA//9Ib3cgb24gZWFydGggZGlkIHRoaXMgaGFwcGVuIPCflIo) or [verify all test cases](https://tio.run/##fdExS8NAFAfw/T7FuyhUS3IFV4NxUYygGTqKhGtzkIjchSbSVREcOoq7UEFwcXXrcNUv0k/gN4j3UkuxeDfd8Pu/9473BrzKmyGv4QCGKhNMVXxQCAhDOEqOSeTB4uERvKj5ml0tbl99Guk380LATuf384n@iPtb7CaJ9XtfTz/v9EsSd5ie7p/tHTY@wRZknBfXAkaCZ1BIkikC0FNl3VtO@n02hoew3WalaE7UGJQEwUd1DlmRQZ0XFeS8LIWE7@enCcFEcv5/grjKo8jN1Mm0ZWqcLgMUE7SN0FXG3QHc7v6eu5Yxhs6UZK0z4wydrRfzBze35pvWvn2pvnUyaqpk2mJqMEVM1xgoGbQYGAwQA9uxdlB3rbf0kD0rd5A7Vu4id618gXy54h8).
**Explanation:**
```
žj # "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"
…,!? # Push string ",!?"
© # Store it in variable `®` (without popping)
… -. # Push string " -."
J # Join all three strings on the stack together
à # Only keep those characters from the (implicit) input
Ê # Check if it's now NOT equal to the (implicit) input
· # Double it (2 if truthy; 0 if falsey)
I # Push the input
S # Convert it to a list of characters
# # Split it on spaces
.u # Check for each character if it's an uppercased letter
O # Sum those checks for each word
®S # Push [",","!","?"] (variable `®` as list of characters)
I ¢ # Count these characters in the input
ā # Push a list in the range [1,length] (without popping): [1,2,3]
£ # Split the counts into those parts: [[a],[b,c],[]]
# (a=count of ","; b=count of "!"; c=count of "?")
O # Sum each inner list: [a,b+c,0]
I # Push the input yet again
'.¢ '# Count the amount of "." in the input
; # Halve it
M # Push the largest number of the stack (including within lists)
2@ # Check if this max is ≥2
# (after which it is output implicitly as result)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes
```
⌈⟦⊙θ¬№⁺ !,-.?_⭆⁶²⍘λφι‹¹⁺№θ!№θ?‹¹№θ,‹³№θ.⊙⪪θ ‹¹LΦι№αλ
```
[Try it online!](https://tio.run/##TY7NCsIwEITvPsWa0wbWgApePIgK4kFF8CgiQWMTiEltUn@ePtYWafewsN/sDHPRsrh4aVPaF8ZF3Mq3uZd3PM7dBx8EOx9x6ctK2dsyIIM@DcTszAgOsTJkW5njZESwkEE1BC3BjXNOYOq9USHgkKD2N1FVLuuzSmvPGev@tpxaPu5yUfNfyUNuTcOAdSI2ymVR48rYqAo0f68ksPw3J86nKa39S3gnlCyiFldzhahNAC3zXLleGjztFw "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for spam, nothing if not. Explanation:
```
⌈⟦
```
Output if any of the following is true.
```
⊙θ¬№⁺ !,-.?_⭆⁶²⍘λφι
```
Check whether any characters aren't contained in the permitted list including the 62 alphanumeric characters used by default for base conversion.
```
‹¹⁺№θ!№θ?
```
Check whether there is more than one exclamation or question mark.
```
‹¹№θ,
```
Check whether there is more than one comma.
```
‹³№θ.
```
Check whether there are more than three full stops.
```
⊙⪪θ ‹¹LΦι№αλ
```
Check whether any word has more than one upper case letter.
[Answer]
# [Python](https://www.python.org), ~~177~~ 171 bytes
This requires the `re` module, so that adds an additional 9 bytes.
```
lambda i:any([re.search('[^a-zA-Z0-9\-.\,\?\! ]',i),*[len(re.findall("[A-Z]",w))>1for w in i.split(" ")],len(re.findall('[?!]'))>1,i.count(".")>3,i.count(",")>1])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY5NCsIwEEavErNpIklQ3KgLxVMIphFif-hAmpS0pdSruCmCgifwLN7GSAXBzQzv-97AXO5V3xTODg8oK-cb5LNb2-R8-boaXZ5SjWCtbU-kz0SdaZ8UJJJHzc87fpjxVcxFzOJtPEEqYkDZVJrMkuDmYFNtDMEyiAqzjtLNPHcedQgsAlFXBhqCEaaK_Z1EcjtR0cdnIBLX2uAJTDeLH7KAc0XHT5-VhxDmBHfOpzXad2Fi-m2HYdxv)
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque) (no RegEx), ~~103~~ ~~88~~ ~~81~~ ~~76~~ 74 bytes
```
Jwd{qsnfl2.<}aljJbc".,?!"qCNZ]^p.+1<=j1<=&&j3<=&&jNBqrifn" -_.,?!"\\z?&&&&
```
[Try it online!](https://tio.run/##SyotykktLixN/f/fqzylurA4Ly3HSM@mNjEnyyspWUlPx15RqdDZLyo2rkBP29DGNguI1dSyjMGkn1NhUWZanpKCbjxYYUxMlb0aEPz/H55flFJsrxAOpvX09AA "Burlesque – Try It Online")
Almost certainly a shorter answer possible. This is pretty brute force.
```
Jwd{qsnfl2.<}alj # Check double caps
J # Duplicate input
wd # Split into words
{
qsn # isUpper
fl # filter length
2.< # <2
} #
al # All
j # Swap input to top of stack
Jbc".,?!"qCNZ]^p.+1<=j1<=&&j3<=&&j # Check char counts
J # Duplicate input
bc # Box and repeat infinitely
".,?!" # String
qCN # Count occurences
Z] # Zip with count (return list of counts for each)
^p # Push list to stack
.+ # Add ?s and !s
1<=j # ?+! <= 1
1<=&&j # , <= 1
3<=&& # . <= 3
NBqrifn" -_.,?!"\\z? # Check valid chars
NB # Remove duplicates
qri # Quoted is alphanum
fn # Filter not
" -_.,?!" # Valid non-letter
\\ # List diff
z? # Empty
&&&& # Reduce all 3 by ands
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 132 bytes
```
n=>n.split` `.some(w=>/[^\w-.,?!]/.test(w)+(F=C=>w.split(C).length-1,c+=F`.`,d+=F(/[?!]/),e+=F`,`,F(/[A-Z]/)>1),c=d=e=0)|c>3|d>1|e>1
```
[Try it online!](https://tio.run/##fdJBT4MwFAfwO5/idRfare0kHpd2MUsWT3p3UyBQBgZbAlUu@wSevfsV/QZI2cyiEU5N3@//Cnntc/wWN0ldVJZpk6ouE50WUvOmKgsbQcQb86JwK@Ry97RvGadr9LjkVjUWt2SBt2IjZHtK4w3hpdIHm7OAJguxjXhE037Fy53rIlS5Io2oq9ywh74kA0ITkQolrsgxkdfHVAZHJYOu0NWrBQHRrWnBaFBxbXNIixRsXjSQx1WlNHx9frx7LnF/93/Cm2pfr6cZTTIaGPWOTgHkEmiIoJ/M9Akw7dO/N93LOXfOjeaD8965c34ZzC/8OzXaH03Hh0pHv@w0NDocMOwxdBhekBnNBmQ9Mods7LKwUzJ6lzPHs1H2HfujPHc8H@Wd48czR@cn7u@1T1ael5kacGJ0Y6GxdaEPYDIY3iwBVzal4qU54BNS8Jn0KWTnPSGr7hs "JavaScript (Node.js) – Try It Online")
If you want to be completely sure that the answer works, add a backslash before the dash in the first regular expression. The code above passes all test cases, but a comment on the python answer seems to indicate that there should be a backslash or space before the dash. If anyone could confirm or disprove the statement above, it would be very helpful.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~62~~ ~~58~~ ~~57~~ 56 bytes
```
`[^\w.,?! -]`ẎL‛?!øB?ẎL1>?⌈ƛ`[A-Z]`nẎL1>;a?\.O3>?\,O1>Wa
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgW15cXHcuLD8hIC1dYOG6jkzigJs/IcO4Qj/huo5MMT4/4oyIxptgW0EtWl1gbuG6jkwxPjthP1xcLk8zPj9cXCxPMT5XYSIsIiIsImFhYmJBYyEhISEhIl0=)
My first Vyxal answer, and I'm loving this language. So much more intuitive than Jelly. 99% sure this can be golfed more.
Explanation:
```
`[^\w.,?! -]`?ẎL‛?!øB?ẎL1>?⌈ƛ`[A-Z]`nẎL1>;a?\.O3>?\,O1>Wa ; Takes the word as input
`[^\w.,?! -]`ẎL ; Length of any matched of illegal characters (0 if no matches)
‚Äõ?! ; The string '?!'
√∏B ; Bracketify: converts '?!' to '[?!]'
?ẎL ; Find all '?' and '!' and count them
1> ; More than 1?
?‚åà ; Split the input on spaces
∆õ ; ; Mapping lambda: maps all the words using the following criteria
`[A-Z]`nẎL ; How many capital letters in the word?
1> ; More than 1?
a ; Any truthy? (i.e. any words with more than 1 capital letter?)
?\.O ; Count full stops in string
3> ; More than 3?
?\,O ; Count commas in string
1> ; More than 1?
W ; Turn the stack into a list
a ; Any truthy? (i.e. are any of the conditions true?)
```
# [Vyxal](https://github.com/Vyxal/Vyxal), 56 bytes
```
`[^\w-.,?! ]|[A-Z]\S*[A-Z]|[!?].*[!?]|,.*,|(\..*){4}`?ẎL
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%60%5B%5E%5Cw-.%2C%3F!%20%5D%7C%5BA-Z%5D%5CS*%5BA-Z%5D%7C%5B!%3F%5D.*%5B!%3F%5D%7C%2C.*%2C%7C%28%5C..*%29%7B4%7D%60%3F%E1%BA%8EL&inputs=abc!&header=&footer=)
A different version based off of the [regex Node.js answer](https://codegolf.stackexchange.com/a/242499/107299)
] |
[Question]
[
In this challenge you have to find out which nth second it is now in this year, current date and time now. Or in other words, how many seconds have passed since New Year.
An example current Date is (it's not given, you'll have to find the current Date):
```
March 5, 2021 1:42:44 AM
```
For which the answer is `5449364` (or optionally `5449365` if you count January 1, 2021 0:00:00 as the first second).
So you should return or output which 'th second it is now in this year. Standard loopholes apply, shortest code wins. You may keep fractional seconds in output optionally.
[Answer]
# [PHP](https://php.net/), 27 bytes
```
<?=time()-strtotime('1/1');
```
---
```
time() // current timestamp in seconds
strtotime('1/1') // timestamp of January 1st
```
[Try it online!](https://tio.run/##K8go@P/fxt62JDM3VUNTt7ikqCQfzFY31DdU17T@/x8A "PHP – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 55 bytes
```
from time import*
k=86400
print~-gmtime()[7]*k+time()%k
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehJDM3VSEztyC/qESLK9vWwszEwICroCgzr6RONz0XJKuhGW0eq5WtDWGrZv//DwA "Python 2 – Try It Online")
*-4 bytes thanks to Wasif*
*-11 bytes thanks to dingledooper*
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 31 bytes
```
new-timespan 1/1 (date)|% t*ls*
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Py@1XLckMze1uCAxT8FQ31BBIyWxJFWzRlWhRCunWOv/fwA "PowerShell – Try It Online")
Too late to post this one
---
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 71 bytes
```
$x=date;((($x|% d*r)-1)*86400)+($x.hour*3600)+($x.minute*60)+($x|% s*d)
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X6XCNiWxJNVaQ0NDpaJGVSFFq0hT11BTy8LMxMBAUxsoqJeRX1qkZWwG4@Zm5pWWpGqZQbhALcVaKZr//wMA "PowerShell – Try It Online")
Example output:
```
Friday, March 5, 2021 6:20:21 AM
5466021
```
You just multiply day of year by 86400 (24*60*60) and then minutes by 60, hours by 3600 (60\*60) and seconds, and sum up all
[Answer]
# [R](https://www.r-project.org/), 73 bytes
```
`?`=as.double
-?as.POSIXct(paste0(substr(t<-Sys.time(),1,4),"-01-01"))-?t
```
[Try it online!](https://tio.run/##K/r/P8E@wTaxWC8lvzQpJ5VL1x7IDvAP9oxILtEoSCwuSTXQKC5NKi4p0iix0Q2uLNYrycxN1dDUMdQx0dRR0jUwBCIlTU1d@5L//wE "R – Try It Online")
Returns the index of the current second, in the year that the program is run (currently 2021 at time of posting).
The [POSIXct class](https://stat.ethz.ch/R-manual/R-devel/library/base/html/DateTimeClasses.html) used by [R](https://www.r-project.org/) to represent dates conveniently equals the number of seconds since the start of 1970.
So, to calculate the index of the current second *this year* (2021), we just need to subtract the number of seconds between 1 Jan 1970 and 1 Jan 2021, which is 1609455600. This requires only [32 bytes](https://tio.run/##K/r/P7FYLyW/NCknVSO4slivJDM3VUNT19DMwNLE1NTMwEDz/38A) of code.
Unfortunately, all of the slickness of the approach above is somewhat lost by the clunkiness of extracting a string to represent 1 Jan of the *current year*...
[Answer]
# [Red](http://www.red-lang.org), 58 bytes
```
d: now prin d/11 - 1 * 86400 +(d/7 * 3600)+(d/8 * 60)+ d/9
```
[Try it online!](https://tio.run/##K0pN@R@UmhId@z/FSiEvv1yhoCgzTyFF39BQQVfBUEFLwcLMxMBAQVsjRd8cyDM2MzDQBHEsgBwzIBOo1PL/fwA "Red – Try It Online")
Explanation:
`d` is of `date!` datatype. I would normally acces its fields usng `path` notation like `d/yearday` to find which date of the year is today. Luckily [Red](http://www.red-lang.org) has ordinal accessors for the fields as follows:
```
Index Name
1 date
2 year
3 month
4 day
5 zone
6 time
7 hour
8 minute
9 second
10 weekday
11 yearday
12 timezone
13 week
14 isoweek
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 53 bytes
```
print(((n=new Date)-new Date(n.getFullYear(),0))/1e3)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/v6AoM69EQ0MjzzYvtVzBJbEkVVMXxtLI00tPLXErzcmJTE0s0tDUMdDU1DdMNdb8/x8A "JavaScript (V8) – Try It Online")
Prints fractional number of seconds. Adding `|0` will make this an integer for 2 more bytes.
[Answer]
## Excel, 20 or 36 bytes
This works for just 2021
```
=(NOW()-44197)*86400
```
This works for all years.
```
=(NOW()-DATE(YEAR(NOW()),1,1))*86400
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~46~~ 32 bytes
-14 bytes thanks to [ophact](https://codegolf.stackexchange.com/users/100690/ophact)!
```
_=>(Date.now()-16094592e5)/1e3|0
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/3tZOwyWxJFUvL79cQ1PX0MzA0sTU0ijVVFPfMNW4xuB/cn5ecX5Oql5OfrpGmoampvV/AA "JavaScript (V8) – Try It Online")
The function gets the timestamp of the current time, i.e. number of milliseconds from the 1st January 1970
```
new Date().getTime()
```
Then subtract the number of milliseconds passed from 1970 to 2021
```
1609459200000
```
And divides the result by `1000` to get the number of seconds.
Finally it returns the result after having converted it to unsigned integer through the bitwise OR `|` (because the division gives a floating point number)
The variable `_` is never used but passing no argument would cost one byte `()=>`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~19 12~~ 11 bytes
```
K-ÐKi T)zA³
```
[Try it online!](https://tio.run/##y0osKPn/31v38ATvTIUQzSrHQ5v//wcA "Japt – Try It Online")
does current time(in ms) - january 1 , divide by 1000 and floor.
-7 bytes from Shaggy and AZTECC0.
-1 byte from Shaggy.
[Answer]
# Javascript (Browser), 163 bytes
```
d=new Date();x=d.getFullYear();y=((Date.UTC(x,d.getMonth(),d.getDate())-Date.UTC(x,0,0))/864e5)-1;alert(y*86400+d.getHours()*3600+d.getMinutes()*60+d.getSeconds())
```
UTC based day of year calculation thanks to [this answer in Stack Overflow](https://stackoverflow.com/questions/8619879/javascript-calculate-the-day-of-the-year-1-366/40975730#40975730), I then tried to golf and use the function
# [JavaScript (V8)](https://v8.dev/), 163 bytes
```
d=new Date();x=d.getFullYear();y=((Date.UTC(x,d.getMonth(),d.getDate())-Date.UTC(x,0,0))/864e5)-1;print(y*86400+d.getHours()*3600+d.getMinutes()*60+d.getSeconds())
```
[Try it online!](https://tio.run/##TcvNDoIwEATgV/G4ixRrVEJCetIYL5zUg8cGNoghLSktwtNXfjTxON/MvGQn29xUjWVd4n0hFL1XJ2kJMO1FEZVkz66uHyTNKIMAmMrofjtCH851ppV9Ai5heSL7G/GQI26SeE8HZNu0MZWyMAQjcL6eTxftTAsY7OKfZJVyliaLv3KlXKtiFPT@Aw "JavaScript (V8) – Try It Online")
[Answer]
# [T-SQL](https://docs.microsoft.com/en-us/sql/t-sql/language-reference?view=sql-server-ver15) 55 Bytes,
`PRINT DATEDIFF(S,STR(YEAR(GETDATE()))+'0101',GETDATE())`
DATEDIFF takes difference between two DATETIME types, S makes the difference be in seconds.
GETDATE() gets the local datetime as a DATETIME.
YEAR takes a DATETIME/DATE argument, returns the year component of the argument.
STR converts the YEAR integer to a string. + is also string concatenation in T-SQL.
The string in format 'YYYYMMDD' is implicitly converted to a DATETIME with a zero time component in the DATEDIFF function.
Results in the number of seconds since the 1st of Jan this Year.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 47 bytes
```
$0=strftime("%j",r=systime(),1)*(q=86400)+r%q-q
```
[Try it online!](https://tio.run/##SyzP/v9fxcC2uKQorSQzN1VDSTVLSafItriyGMzV1DHU1NIotLUwMzEw0NQuUi3ULfz/X0kJAA "AWK – Try It Online")
I wasn't sure if the seconds into the year should start from midnight Jan 1 in the local timezone or in UTC. This version works for UTC.
It figures out the julian date (the number of days into the year), converts that to seconds then adds in the fractional day's worth of seconds.
```
strftime("%j",r=systime(),1)
```
Gets the julian date, and stores the UNIX epoch in variable `r` in the process. It add a 3rd parameter on `strftime` to get the time in UTC.
```
*(q=86400)
```
Converts the days to seconds and saves the constant "seconds per day" in for use later.
```
+r%q
```
Adds in the seconds corresponding to the `HH:MM:SS` offset from midnight UTC using modulo math.
```
-q
```
And this is annoying 2 characters I couldn't figure out how to drop... Since julian days start with 1, the `%j` include the current day so we have to subtract a full day.
```
$0=
```
Finally, assigning the result to `$0` means the whole expression is actually a condition, which is always truthy except for at exactly midnight on Jan 1st, so the value is printed.
If an offset in seconds from local time is acceptable, this more straightforward, and slightly shorter code would work.
```
$0=systime()-mktime(strftime("%Y 1 1 0 0 0"))
```
That one just subtracts the UNIX epoch for Jan 1st at mightnight of the current year from the current epoch time.
[Answer]
# [Python 2](https://docs.python.org/2/), 79 bytes
```
from datetime import*
print (datetime.now()-datetime(2021,1,1)).total_seconds()
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1chJbEktSQzN1UhM7cgv6hEi6ugKDOvREEDJq6Xl1@uoakL42oYGRgZ6gChpqZeSX5JYk58cWpyfl5KsYbm//8A "Python 2 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 105 bytes
```
from datetime import*
n=datetime.now();print n.timetuple().tm_yday*86400+n.hour*3600+n.minute*60+n.second
```
[Try it online!](https://tio.run/##NchRCoQgEADQ/z2Fn2UgUiHBsmeJyImEZkbckfD0RkF/jxeL7Ex9rVtiVH4RkICgAkZOoj/0e8sQn037jSmQKDJ3SY4HNK0RnItfip7caG1HZuec9OAeY6AsoN3tP6xMvtYL "Python 2 – Try It Online")
**Equal-byte alternative:**
# [Python 2](https://docs.python.org/2/), 105 bytes
```
from datetime import*
n=datetime.now();print int(n.strftime('%j'))*86400+n.hour*3600+n.minute*60+n.second
```
[Try it online!](https://tio.run/##NYlbCoAgEAD/O4U/kRpIVEgQHSbKyMBd2Tai09sD@hgYZuLFK0Kd0kIYxDyyYx@c8CEisc5g@JMBPKXqI3lg8SDB7EzLu2SRb4VSurNtVZVgVjxIN/bz4OFgp@3ru5sQ5pRu "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 84 bytes
```
from datetime import*
n=datetime.now();print(n-datetime(n.year,1,1)).total_seconds()
```
[Try it online!](https://tio.run/##NcjBCoAgDADQe1/hUcMEu0bfEpKLhNxkDqKvXyff8bVPbsJV9WKqJicBKRVMqY1Y5gn3UQHptW5rXFAsLqMthg8S@@ijc0FI0nN0OAlzt071Bw "Python 2 – Try It Online")
Thanks to @ovs for -21 bytes
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 33
```
dc<<<`date -f- +%s<<<"now
1/1"`-p
```
[Try it online!](https://tio.run/##S0oszvj/PyXZxsYmISWxJFVBN01XQVu1GMhXyssv5zLUN1RK0C34/x8A "Bash – Try It Online")
### Explanation
```
"now\n1/1" # newline separated now, Jan-1st dates
date -f- +%s<<<"now\n1/1" # with -f, date formats multiple lines as multiple seconds-since-1970/01/01
`date -f- +%s<<<"now\n1/1"`-p # expands to dc expression to push now-seconds, Jan-1st-seconds, then subtract, then print
dc<<<`date -f- +%s<<<"now\n1/1"`-p # evaluate the dc expression
```
[Answer]
# JavaScript, ~~83~~ 61 bytes
```
_=>(new Date()-new Date(new Date().getFullYear()+'-1-1'))/1e3
```
Yes, it was possible in the end. Could probably shave off a few more bytes.
This code outputs the number of seconds since January 1 of the current year, 2021 at the time of writing. Returns a floating point number.
This code does not explicitly output, but running something like
```
console.log(f())
```
where `f` is the function I posted, will output the result
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 26 bytes
```
kτ‹86400*kḢ3600*+kṀ60*+kṠ+
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=k%CF%84%E2%80%B986400*k%E1%B8%A23600*%2Bk%E1%B9%8060*%2Bk%E1%B9%A0%2B&inputs=&header=&footer=)
For some unknown reason, `s` flag dosen't work
[Answer]
# [Julia 1.0](http://julialang.org/), 54 bytes
```
using Dates
f(n=now())=(n-DateTime(year(n))).value/1e3
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/v7Q4My9dwSWxJLWYK00jzzYvv1xDU9NWI08XJBaSmZuqUZmaWKSRp6mpqVeWmFOaqm@Yavy/oCgzryQnTyMNqPg/AA "Julia 1.0 – Try It Online")
[Answer]
# R, ~~60~~ 31 bytes
```
-difftime(paste0(substr(t<-Sys.time(),1,4),"-01-01"),t,,'s')
```
using difftime with @Dominic van Essen's new years day replacement method
answer is in the following format:
>
> Time difference of 11203844 secs
>
>
>
[TIO\_link](https://tio.run/##K/r/XzclMy2tJDM3VaMgsbgk1UCjuDSpuKRIo8RGN7iyWA8so6ljqGOiqaOka2AIREqaOiU6OurF6pr//wMA)
[rdrr.io link](https://rdrr.io/snippets/embed/?code=-difftime(paste0(substr(t%3C-Sys.time()%2C1%2C4)%2C%22-01-01%22)%2Ct%2C%2C%27s%27)%0A)
a much shorter version:
```
as.double(Sys.time())%%31536000
```
[Try it online!](https://tio.run/##K/r/P7FYLyW/NCknVSO4slivJDM3VUNTU1XV2NDU2MzAwOD/fwA "R – Try It Online")
[Answer]
# IBM/Lotus Notes Formula, 33 bytes
```
@Now-@Date(@Year(@Now);1;1;0;0;0)
```
Date comparisons return seconds by default. Unfortunately `@Date` requires the seconds otherwise it constructs a date with the current time.
No TIO for formula so here are a couple of screenshots:
[](https://i.stack.imgur.com/I5KRt.png)
[](https://i.stack.imgur.com/LD6sw.png)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes
```
DateDifference[{2021},Now,"Second"]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n24bWJqZWuLw3yWxJNUlMy0ttSg1Lzk1utrIwMiwVscvv1xHKTg1OT8vRSlW4X9AUWZeicOjnq70Rz3d//8DAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/) 18.0, 16 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
Full program
```
-/20⎕DT↑∘⎕TS¨6 1
```
[Try APL online!](https://tryapl.org/?clear&q=%7C-%2F20%E2%8E%95DT%E2%86%91%E2%88%98%E2%8E%95TS%C2%A86%201&run)
`6 1` a 2-element list `[6,1]`
`↑∘⎕TS¨` for each number, take that many elements from the current YMDhmsf list
`20⎕DT` convert the two dates (the 1-element date is padded with the lowest valid values, i.e. `[1,1,0,0,0,0]` for the beginning of the 1st of January) to UNIX time (seconds since the beginning of 1970)
`-/` difference between them
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•ΘÏF•ºS₂+žf<£že<ªOŽª+·*žaŽEU*žb60*žcO
```
[Try it online.](https://tio.run/##yy9OTMpM/f//UcOiczMO97sB6UO7gh81NWkf3Zdmc2jx0X2pNodW@R/de2iV9qHtWkf3JR7d6xoKpJPMDIBksv///wA)
**Explanation:**
```
•ΘÏF• # Push compressed integer 5254545
º # Mirror it to 52545455454525
S # Convert it to a list of digits: [5,2,5,4,5,4,5,5,4,5,4,5,2,5]
₂+ # Add 26 to each: [31,28,31,30,31,30,31,31,30,31,30,31,28,31]
žf # Push the current month
< # Decrease it by 1
£ # Leave that many leading integers from the list
že # Push the current day of the month
< # Decrease it by 1 as well
ª # Append it to the list
O # Sum it together (total amount of days thus far)
Žª+ # Push compressed integer 43200
· # Double it to 86400
* # And multiply it to the amount of days
ža # Push the current hours
ŽEU* # Multiply it by compressed 3600
žb # Push the current minutes
60* # Multiply it by 60
žc # Push the current seconds
O # Sum all values on the stack together
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•ΘÏF•` is `5254545`; `Žª+` is `43200`; and `ŽEU` is `3600`.
[Answer]
# [Factor](https://factorcode.org/), 38 bytes
```
now now start-of-year time- second>> .
```
TIO is too old to have `start-of-year`, so have a screenshot of running the code in the listener. Link to online documentation for the word: <https://docs.factorcode.org/content/word-start-of-year,calendar.html>
[](https://i.stack.imgur.com/aJUSq.png)
## How it works:
Generate two timestamps: one now, and the other at the beginning of the year. Subtract them and then extract the result
[Answer]
# Javascript 25 bytes
Reach 38 with the console.log().
```
console.log(Date.now()/1e3-1609459200)
```
[Answer]
# [Nim](http://nim-lang.org/), 59 bytes
```
import times
echo inSeconds now()-($now().year).parse"YYYY"
```
[Try it on the Nim playground!](https://play.nim-lang.org/#ix=3mtd) (For some reason, it doesn't work correctly on TIO.)
] |
[Question]
[
John, a knight wants to kill a dragon to escape the castle! The dragon has `A` heads and `B` tails.
He knows, that:
* if you cut off one tail, two new tails grow
* if you cut off two tails, one new head grows
* if you cut off one head, one new tail grows
* if you cut off two heads, nothing grows
To defeat the dragon, John needs to cut off all his heads and all his tails. Help the knight to do this by making no more than 1000 strikes.
**Input**
The input contains two integers A and B (1 ≤ A, B ≤ 100).
**Output**
Print the sequence of strikes in the order in which they should be performed by encoding them with the following combinations of letters: `T` (one tail), `TT` (two tails), `H` (one head), `HH` (two heads) in the most optimal order.
**Example**
```
3 1
T
TT
HH
HH
```
The winning condition is the least number of bytes!
UPDATE: Bounty on offer for answers with Python
[Answer]
# JavaScript (ES6), ~~136~~ 134 bytes
Takes input as `(heads)(tails)`. Naive brute force search.
```
h=>F=(t,x=0)=>(g=(h,t,p=[],i=-6)=>h|t?h<0|t<0||p[x]?0:['HH','H','T','TT'].some(m=>g(h+i+4,i++%5%4-~t,[...p,m]))&&P:P=p)(h,t)||F(t,x+1)
```
[Try it online!](https://tio.run/##Fc2xCoMwFEDRr1HzSAxKbQfp000cHdwkg1g1KWpCDcUh9NdTHc5yl/vuv/0@fJSx8aZfo5/QSywqJJYdmAAWZEYimWUGO8EUxo@zSWdL@UycPTnTHaJM8i6q64hFl/bSRoLveh3JisVMJFU0Y4rS4B5k8c@yjnNu2CoAwrDJGzRwXcC56jrTFPygt10vI1/0TCZyA5IC@D8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~122~~ ~~121~~ 117 bytes
```
def f(a,b):x=a+b/2;b+=1;return b%2*x%2and['H']+a%2*['TT']+f(a-~a%2,b-a%2*2)or~b%2*['HT'[x%2]]+b/2*['TT']+-~x/2*['HH']
```
[Try it online!](https://tio.run/##TYyxCsMgEIb3PsUtYqyGEodCDdnzAG6SQTG2ZjBBLKRLXt1qoNDp7vvu/n/7pNcaeM52duAazQwR@6CpufHe0KHr45zeMYBB/LojroNVeMQT1YUVlrKsJdUehZlpq@VkjYc5z6PEqoSmqdb93ttjP2EsNdmtETz4AFGH59x07E7EBapd/u2jWtiiDwkwsgxZgVHj2UKYO0f@Ag "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 121 bytes
Outputs to stderr, tries all possible sequences until the first one succeeds.
```
r=[([],)+input()]
for s,h,t in r:h==t==0>exit(s);r+=[(s+['HT'[i/9]*(2-i%2)],h+i/4-2,t+i%4-2)for i in 11,12,7,2 if h>-1<t]
```
[Try it online!](https://tio.run/##Fcy/DsIgEIDx3adgaQpypHI2Mf65zj6AG2G04RbawJno02M7fdP3W3@SloytFQo6RDCW8/oRbeJhXoqqkEAUZ1VuiUiITtP7y6KruRe7HdWG/vnqAw/XeNTouEMTIVkeRocglrutZpd4V7wHj3ABVDyrNDn/kNjaGfwf "Python 2 – Try It Online")
I don't think the `if h>-1<t` part is necessary, without it it would be [111 bytes](https://tio.run/##FcwxDsIwDEDRnVNkqZoQVyUGCVFkZg7AFnkExUtaJUaC06ft9Kf/lr@mOWNrhaKNDM5LXr5qHR8@czEVEqiRbMqUiJTo9Hj/RG119@K3o/rYP199lPHGR4uDdOgYkpfxMiCol26r2yXZlRAgIFwBubUzhBU).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 71 bytes
```
⁴HḞ
“TT¶”ẋ¢
³ḂḤ⁴+
“H¶TT¶“H¶H¶TT¶“T¶TT¶“”¢ị
Ø+ŻUŻ3£ị+1£+³H
“HH¶”ẋ¢
2£4£¢
```
[Try it online!](https://tio.run/##y0rNyan8//9R4xaPhzvmcT1qmBMScmjbo4a5D3d1H1rEdWjzwx1ND3csAcprgyQ9Dm2DyINYCE4InAXUeWjRw93dXIdnaB/dHXp0t/GhxUCutuGhxdqHNnuAzfBAssDo0GKTQ4sPLfr//7/Rf1MA "Jelly – Try It Online")
I'm quite new to Jelly, so this is not optimal, but here's my explanation:
```
(1st link)
⁴ starting number of tails
H halved
Ḟ and floored
(2nd link)
“TT¶” take the string "TT\n"
ẋ¢ and repeat it (last link) amount of times
(3rd link)
³ starting number of heads
Ḃ mod 2
Ḥ doubled
+ plus
⁴ starting number of tails
(4th link)
“H¶TT¶“H¶H¶TT¶“T¶TT¶“” array of actions
¢ based on the last link
ị get the (n % len(array))th element
(5th link)
Ø+ [1, -1]
Ż prepend 0 ([0, 1, -1])
U reverse the array ([-1, 1, 0])
Ż prepend 0 ([0, -1, 1, 0])
ị index
3£ of the 3rd link
+ plus
1£ 1st link
+ plus
³H half the number of heads
(6th link)
“HH¶” take the string "HH\n"
ẋ¢ repeat it (last link) amount of times
(Main link)
2£ 2nd link
4£ 4th link
¢ last link
```
[Answer]
## Batch, 201 bytes
```
@set/aa=%1,b=%2,c=(b+a+a)%%4
@if %1%c%==12 echo TT&set/ab-=a=c=2
@if %c%==3 echo T&set/ab+=1,c=0
@set/ab+=c,a+=b/2-c,c+=c
@for %%v in (%c%.H %b%.TT %a%.HH)do @for /l %%i in (2,2,%%~nv)do @echo%%~xv
```
Works by directly calculating the number of `H`, `TT` and `HH` strikes required. This handles all cases except where \$2a+b\equiv3\pmod4\$ (which requires an initial `T`) and the case \$a=1,b=4k\$ (which requires an initial `TT`). Edit: Fixed second special case for \$k>1\$.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~104~~ ~~91~~ 77 bytes
-14 bytes thanks to @att
```
Table@@@Join[{H,b=1-#~Mod~2},{T,q=Mod[2-#2-b,4]},{TT,n=(#2+q)/2},HH|(#+n)/2]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyQxKSfVwcHBKz8zL7raQyfJ1lBXuc43P6XOqFanOkSn0BbIjjbSVTbSTdIxiQWJhejk2WooG2kXauoD1Xh41Ggoa@cB2bFq/wOKMvNKotOijYx1zGNj9fUDSzNTS/4DAA "Wolfram Language (Mathematica) – Try It Online")
A 74 byte version, but can't be run in TIO, as it fakes Put. Put is the only valid operator with a higher precedence than Set, so it can be used in place of List in each pair, save a byte over each.
```
Table@@@Join[H>>b=1-#~Mod~2,T>>q=Mod[2-#2-b,4],TT>>n=(#2+q)/2,HH|(#+n)/2]&
```
[Answer]
# Java 8, ~~194~~ ~~167~~ ~~164~~ ~~163~~ ~~140~~ 135 bytes
```
(h,t)->{for(;t>-h;)System.out.println(t+h%2<1&&h>(h-=2)?"HH":h<1&t%4<3|t%4==h%2*2&&h<++h&t>(t-=2)?"TT":t++%4!=3-h%2*2&&h>--h?"H":"T");}
```
-51 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##fZA/b4MwEMV3PsXVEsjUMVL@LMWYrizNEraqg0ugJiUQwSVSlfLZ6UGStkNVD086/56t925nTkbutu9DVpmugydT1mcHoKwxbwuT5bAeR4BTU26h4HQPdjYq@opA75B0aLDMYA01aBi4naEv43PRtFxhLK3yNx8d5vugOWJwaOlxVXMU1l1Ec8@zMbdSL/xHliQstHSF7ipafpJqTZ77BXkiIayHMceLM01ZiEK4qzu9lDdPLKWlT1jIUuarflBjtMPxtaJo14RTiT1V5BukHG/PL2D8S78x7VROzxXYSD@QCnGFPxhHjBPGXxjgj4osyc22C4EJKxj5TVlNEwrKOG3vcuqgmHam/vvsm/bOTXunH74A)
**Explanation:**
I first tried all possible cases by hand:
```
Heads Tails Steps
1 (odd) 5 (%4==1) 1,5 → T(1,6) TT(2,4) TT(3,2) TT(4,0) HH(2,0) HH(0,0)
1 (odd) 6 (%4==2) 1,6 → see above after first step
2 (even) 6 (%4==2) 2,6 → H(1,7) H(0,8) TT(1,6) TT(2,4) TT(3,2) TT(4,0) HH(2,0) HH(0,0)
1 (odd) 7 (%4==3) 1,7 → see above after first step
3 (odd) 8 (%4==0) 3,8 → H(2,9) H(1,10) TT(2,8) TT(3,6) TT(4,4) TT(5,2) TT(6,0) HH(4,0) HH(2,0) HH(0,0)
2 (even) 9 (%4==1) 2,9 → see above after first step
2 (even) 7 (%4==3) 2,7 → T(2,8) TT(3,6) TT(4,4) TT(5,2) TT(6,0) HH(4,0) HH(2,0) HH(0,0)
2 (even) 8 (%4==0) 2,8 → see above after first step
0 (zero) 6 (%4==2) 0,6 → TT(1,4) H(0,5) TT(1,3) H(0,4) TT(1,2) TT(2,0) HH(0,0)
0 (zero) 5 (%4==1) 0,5 → see above after second step
0 (zero) 4 (%4==0) 0,4 → see above after fourth step
0 (zero) 7 (%4==3) 0,7 → T(0,8) TT(1,6) TT(2,4) TT(3,2) TT(4,0) HH(2,0) HH(0,0)
5 (odd) 0 (zero) 5,0 → H(4,1) H(3,2) TT(4,0) HH(2,0) HH(0,)
4 (even) 0 (zero) 4,0 → see above after third step
```
After that I knew the first moves for every possibility. Which I displayed here in table form:
```
| 0 %4==0 %4==1 %4==2 %4==3 < Tails
------|-------------------------------------
0 | - TT TT TT T
%2==0 | HH TT H H T
%2==1 | H H T TT H
^
Heads
```
As for my code:
```
(h,t)->{ // Method with two integer parameters and String return-type
for(;t>-h;) // Loop until both the amount of heads and tails are 0:
System.out.println( // Print with trailing newline:
t+h%2<1&& // If there are 0 tails and an even amount of heads:
h>(h-=2)? // Decrease the amount of heads by 2
"HH" // And print "HH"
:h<1&t%4<3 // Else if there are 0 heads and tails modulo 4 is 0, 1, or 2
|t%4==h%2*2&& // Or there is an even amount of heads and tails modulo 4 is 0
// Or there is an odd amount of heads and tails modulo 4 is 2:
h<++h& // Increase the amount of heads by 1
t>(t-=2)? // Decrease the amount of tails by 2
"TT" // And print "TT"
:t++%4!=3-h%2*2&& // Else-if there are an odd amount of heads and tails modulo-4 is NOT 1
// Or there are an even amount of heads and tails modulo-4 is NOT 3:
// (and increase `t` by 1 with `t++` right after this check)
h>--h? // Decrease the amount of heads by 1
"H" // And print "H"
: // Else:
"T");} // Print "T"
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~91~~ 79 bytes
*Saved 1 byte thanks to @[ovs](https://codegolf.stackexchange.com/users/64121/ovs)*
```
{⍺=-⍵:⍬⋄⍵>1:'TT ',(⍺+1)∇⍵-2⋄3=⍺+⍵:'H ',(⍺-1)∇⍵+1⋄1=⍺⌈⍵:'T ',⍺∇⍵+1⋄'HH ',⍵∇⍨⍺-2}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6sf9e6y1X3Uu9XqUe@aR90tQJadoZV6SIiCuo4GUE7bUPNRRztQVNcIKGtsCxICqVb3gCrQhSnQNgQqMAQpeNTTAVYCMgPERUire3iAxbaCxVaAtBvV/k8DuuRRb9@jrmaQG3q3HFpv/KhtItCNwUHOQDLEwzP4v6FCmoIhlxGYNAaTJmDSAEgacJkBSVMucxAJAA "APL (Dyalog Unicode) – Try It Online")
Here is my "research." The x-axis is heads, y-axis is tails. Each cell contains the minimum number of moves to get to (0, 0), and the optimal move(s) you can make from there.
[](https://i.stack.imgur.com/CqEeN.png)
There are multiple ways you can divide it up, but I am going to hold `t>=2` to be one section (TT); (2, 1) and (3, 0) to be another (H); (1, 0), (0, 1), and (1, 1) to be another (T), and the rest to be HH.
The first case is if the dragon has no heads or tails (`h==-t`), in which case we return the empty set (`⍬`).
As you can see, the optimal move if the dragon has 2 or more tails is a double tail-chop, and that is our second case. We prepend `'TT '` to the result of calling the function again with one more head and two less tails. `∇` refers to the current function, `⍺` is heads, and `⍵` is tails.
The third case is the single head chop. The only two times when the only option available is `H` is at (3,0) and (2,1). Our condition here is that `h+t` is 3 (this condition is also met with (1,2) and (0,3), but those were covered in the second case).
The third case is the single tail chop. Only one square requires it - (1, 1), so we check if the maximum of `h` and `t` is 1.
The last case doesn't need any condition checking, so we can go ahead and decapitate the dragon twice.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~75~~ 71 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[UVXY+_#XÈY_*i„HHYXÍëY4%©X_i3‹ëXÈi_ë2Q}}i„TTYÍX>ë®XÈi3Q}i'TY>Xë'HY>X<]»
```
Port of [my Java answer](https://codegolf.stackexchange.com/a/184915/52210). Can definitely be golfed, though (probably by using a different approach all-together more suitable to 05AB1E..)
[Try it online](https://tio.run/##yy9OTMpM/f8/OjQsIlI7XjnicEdkvFbmo4Z5Hh6REYd7D6@ONFE9tDIiPtP4UcPOw6uB8pnxh1cbBdbWghSFhEQe7o2wO7z60DqQjHFgbaZ6SKRdxOHV6h5Ayib20O7//424TAE) or [verify some more test cases](https://tio.run/##yy9OTMpM/W/p6ne6DUi4hB1af26HS6iSR2piSrGVwuH91goliZk5YKbCo7ZJCkr2kRH/o0PDIiK145UjDndExmtlPmqY5@ERGXG49/DqSBPVQysj4jONHzXsPLwaKJ8Zf3i1UWBtLUhRSEjk4d4Iu8OrD60DyRgH1maqh0TaRRxere4BpGxqgeDwhsN7/@v8BwA).
**Explanation:**
```
[ # Start an infinite loop:
U # Pop and save the top of the stack (or the first (implicit) input
# in the first iteration) in variable `X` (the heads)
V # Pop and save the top of the stack (or the second (implicit) input
# in the first iteration) in variable `Y` (the tails)
XY+_ # If the amount of heads and tails are both 0:
# # Stop the infinite loop
XÈ i # If there is an even amount of heads
Y_* # and there are 0 tails:
„HH # Push "HH" to the stack
Y # Leave `Y` the same
XÍ # Decrease `X` by 2
ë # Else:
Y4% # Push tails modulo-4 to the stack
© # (and add it to the register without popping as well)
X_i # If there are 0 heads:
3‹ # Check if tails modulo-4 is 0, 1, or 2
ëXÈi # Else-if there are an even amount of heads (but not 0)
_ # Check if tails modulo-4 is 0
ë # Else (there are an odd amount of heads)
2Q # Check if tails modulo-4 is 2
}}i # And if it is truthy:
„TT # Push "TT" to the stack
YÍ # Decrease `Y` by 2
X> # Increase `X` by 1
ë # Else:
® # Push tails modulo-4 to the stack again (from the register)
XÈi # If there are an even amount of heads:
3Q # Check if tails modulo-4 is 3
}i # If this is truthy or tails modulo-4 is 1:
'T '# Push "T" to the stack
Y> # Increase `Y` by 1
X # Leave `X` the same
ë # Else:
'H '# Push "H" to the stack
Y> # Increase `Y` by 1
X< # Decrease `X` by 1
] # After all if-else statements and the loop:
» # Join everything on the stack by newlines
# (which is output implicitly as result)
```
[Answer]
# [Scala](https://www.scala-lang.org/), ~~154~~ 147 bytes
```
a=>b=>{var(h,t,s)=(a,b,"")
while(-t<h)s+=(if(t>1){h+=1;t-=2
"TT "}else if(3==h+t){h-=1;t+=1
"H "}else if(2>h.max(t)){t+=1
"T "}else{h-=2
"HH "})
s}
```
[Try it online!](https://scastie.scala-lang.org/uwdVsZJ4QDO8qVB7x1UX5Q)
Uses a completely different approach, but it's *still* longer than Java. :(
See my [APL answer](https://codegolf.stackexchange.com/a/215716/95792) for an explanation.
### Previous solution, 182 bytes
```
h=>t=>{var m=Map(0->0->"")
while(!m.keySet(h->t)){for{g->s->p<-m
i->u->q<-Map(g+2->s->"HH",(g+1,s-1)->"H",(g,s-1)->"T",(g-1,s+2)->"TT")--m.keySet
if-1<i*u}m+=i->u->s"$q $p"}
m(h->t)}
```
[Try it online!](https://scastie.scala-lang.org/0PuzjJZTRKW3JihQG3V0RQ)
Uses the pathfinding approach Lynn suggested in the comments.
[Answer]
# [Python 3](https://docs.python.org/3/), 107 bytes
```
def f(a,b):return'TT '+f(a+1,b-2)if b>2else'HH '+f(a-2,b)if a>2else'H '+f(1,b+1)if a>1else'T TT HH'[2*b-2:]
```
[Try it online!](https://tio.run/##ZcwxDgIhEAXQ3lNMBwhbgIkFhTUHoDMWEBllY9gNYuHpcWRjZTXJm///@m73pRx6vyYE5EFFYWtqr1qY98AkkdQqTkZkhHgy6fFMzLntMxmKk4efD6a41BvrwR5oyjl2NnsaspeOS4UMuUAN5ZaocBR2B1@d/xTWmkvjPKtZKBxH9A8 "Python 3 – Try It Online")
The only way to reduce the tails is TT. You can safely do this as long as b > 2.
You can also safely reduce heads by HH as long as a > 2. I do this after reducing the tails, so it does not mix with TT operations.
When no more than 2 heads and tails are left, there are two cases:
1. a = 2: Cut off a head (H) then call recursively (with a = 1 now).
2. a = 1: Manually coded using a constant string.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 110 bytes
```
String f(int a,int b){return b>2?"TT "+f(a+1,b-2):a>2?"HH "+f(a-2,b):a>1?"H "+f(1,b+1):b>1?"TT HH":"T TT HH";}
```
[Try it online!](https://tio.run/##TZA9b4MwEIZ3fsXJk60zSDB0gH6sLJ3CVnWwEyhOiYngSFUhfjs9Q6rWw2vreezTK5/NzcTn0@d67Mw4wqtxfl4PNDj/AY10nsDokFbNQ03T4ME@Zy@iqkBgIw2m2saZyk2AZbnDONM2oJTRRvgSpiq3gfDLshS5qGA/FcsKcJ1s544wkiHebr07wYWbyL3I2zsYNUfAq@mHrVT7lBbQPj5wIN7dn6VgKVj6ZwEO3yPVl6SfKLnyYOq8FFJgi0JzT0KhQACCr7@2j5AqaWSrSaniPmKJfnOJlvUH "Java (JDK) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 102 bytes
```
sub f($a,$b){$b>2?"TT ".f($a+1,$b-2):$a>2?"HH ".f($a-2,$b):$a>1?"H ".f(1,$b+1):$b>1?"TT HH":"T TT HH"}
```
[Try it online!](https://tio.run/##PcyxCoMwFIXh3ae4XO5gMAoR2qFDu2bp5tjFgCmRNkqiQxFfvWlibbefj8MZO/c4hOBnBTqnlpNiC6lzfcGmAaySFSJqWbMTtcml3L2s0zqpiLphWhYimkoWH6TEEzbwrTXowcHzBWRyUVVHtmTwk/4vMDpjJ8CcDKeeAXK9J8ebxQzWbA3vYZzMYH0or7prp9l1hTd3u5X/AA "Perl 5 – Try It Online")
6 Chars less due to hint by Dom Hastings.
] |
[Question]
[
## Challenge
For a given positive integer \$n\$:
1. Repeat the following until \$n < 10\$ (until \$n\$ contains one digit).
2. Extract the last digit.
3. If the extracted digit is even (including 0) multiply the rest of the integer by \$2\$ and add \$1\$ ( \$2n+1\$ ). Then go back to `step 1` else move to `step 4`.
4. Divide the rest of the integer with the extracted digit (integer / digit) and add the remainder (integer % digit), that is your new \$n\$.
**Note**: In case `n < 10` at the very beginning obviously you don't move to step 2. Skip everything and print \$[n, 0]\$.
---
## Input
**n**: Positive integer.
---
## Output
**[o, r]**: `o`: the last `n`, `r`: number of repeats.
---
## Step-by-step example
For input `n = 61407`:
```
Repeat 1: 6140_7 -> 6140 / 7 = 877, 6140 % 7 = 1 => 877 + 1 = 878
Repeat 2: 87_8 -> 2 * 87 + 1 = 175 (even digit)
Repeat 3: 17_5 -> 17 / 5 = 3, 17 % 5 = 2 => 3 + 2 = 5 ( < 10, we are done )
```
The output is `[5, 3]` (last `n` is 5 and 3 steps repeats).
---
## Rules
There are really no rules or restrictions just assume `n > 0`. You can either print or return the output.
[Answer]
# [R](https://www.r-project.org/), 93 bytes
```
function(n,r=0,e=n%%10,d=(n-e)/10)"if"(n<10,c(n,r),"if"(e%%2,f(d%/%e+d%%e,r+1),f(d*2+1,r+1)))
```
[Try it online!](https://tio.run/##HcpLCoAwDADRuwiBxEbaiOjGnsYm0E2Eouevn@U8pnXL3W4/rno6OrecWLMDSOKS0SelKImGagP6/uLxTcQ/KMDMhgUiaCgAyi0IfTLOQf4g6oarLGmj/gA "R – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~78 77 76~~ 73 bytes
Recursive version. Saved 3 bytes thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech).
```
f=lambda n,r=0:n>9and f(n%2*sum(divmod(n/10,n%10))or n/10*2+1,-~r)or[n,r]
```
[Try it online!](https://tio.run/##FctLCoAgFADAq7gJnmakEkVBXSRaGCIJ@Qz7QJuubrWcxWz3sQRUKdl@1X42miCPvehwaDUaYgEzxfbTg3GXDwawlIJjJgWlIZJfTOWSF0/8PH53Slt0eICFWlaioTS9 "Python 2 – Try It Online")
# 74 bytes
Full program.
```
n,i=input(),0
while n>9:i+=1;r,R=n/10,n%10;n=[r-~r,r/R+r%R][R&1]
print n,i
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P08n0zYzr6C0RENTx4CrPCMzJ1Uhz87SKlPb1tC6SCfINk/f0EAnT9XQwDrPNrpIt65Ip0g/SLtINSg2OkjNMJaroCgzr0QBaMz//2aGJgbmAA "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), ~~62~~ 59 bytes
```
f=(n,r=0)=>(x=n/10|0)?f((n%=10)&1?x/n+x%n|0:x-~x,r+1):[n,r]
```
[Try it online!](https://tio.run/##DctBCoNADADA11gS1JpAURBSHyIeRN1SkaysIjmIX1@d@8z90W9D@K97rn6cYnQCmgUhlC@YaMF0EjYOQBNhwhc3VmhqiZ5UW35ZFlLGun1OFwevm1@m9@J/4KDkD1WI8QY "JavaScript (Node.js) – Try It Online")
### Commented
```
f = (n, r = 0) => // n = input, r = number of iterations
(x = n / 10 | 0) ? // x = floor(n / 10); if x is not equal to 0:
f( // do a recursive call:
(n %= 10) & 1 ? // n = last digit; if odd:
x / n + x % n | 0 // use quotient + remainder of x / n
: // else:
x - ~x, // use x - (-x - 1) = x + x + 1 = 2x + 1
r + 1 // increment the number of iterations
) // end of recursive call
: // else:
[n, r] // return [ final_result, iterations ]
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 19 bytes
```
[DgD–#ÁćDÈi\·>ë‰O]?
```
Explanation:
```
[ Start infinite loop
DgD Get the length
–# If it's 1, print the loop index and break.
ÁćD Extract: "hello" -> "hell", "o"
Èi if even,
\·> Double and increment
ë else,
‰O Divmod, and sum the result (div and mod).
] End if statement & infinite loop
? Print
```
[Try it online!](https://tio.run/##ASsA1P8wNWFiMWX//1tEZ0TigJMjw4HEh0TDiGlcwrc@w6vigLBPXT///zYxNDA3 "05AB1E (legacy) – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), ~~81~~ ~~80~~ 79 bytes
```
function d(n,c=0)l,r=n÷10,n%10;n>9 ? d(r%2<1 ? 2l+1 : l÷r+l%r,c+1) : [n,c]end
```
[Try it online!](https://tio.run/##PY7tCoIwFIZv5UAIG4q4ZR9W1oVE4JpTFuNMTkrdmRfgha35p3/v837A@5qcVeIbQjehHq1HaBlmui64y6jGZRZFhokoznit4BZDSuRFRCVdKuAEbpkpdQllOhU88j2OHwbbMJDF0SFrmZDbcrc/HCvOYQOdJ3jaHmJqekNv@JAaVvLQRL@B/xGT9/laZZ3SoyerHFuplJzz8AM "Julia 1.0 – Try It Online")
* -1 (thanks Mr. Xcoder)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 61 bytes
```
f=->n,r=0{n>9?(a=n%10;n/=10;f[a%2<1?n-~n:n/a+n%a,r+1]):[n,r]}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y5Pp8jWoDrPztJeI9E2T9XQwDpP3xZIpkUnqhrZGNrn6dblWeXpJ2rnqSbqFGkbxmpaRQP1xNb@L1BIizYzNDEwj@UCMS1j/wMA "Ruby – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 79 bytes
```
(\d+)[02468]$
;$.(_2*$1*
(\d+)(.)
$2*_;$1*
}`(_+);(\1)*(_*)
;$.($3$#2*
^;*
$.&;
```
[Try it online!](https://tio.run/##HcoxCoAwDEDRPdcwSJJCaWtRIUexWgUdXBzE1bNX7Prfv4/nvDZfCqXd8ORC7McZQdFSDoJeoAJZBgyS9S/vStmwUvIslIXrjR02QWBRAbStltL76IYP "Retina – Try It Online") Explanation:
```
(\d+)[02468]$
;$.(_2*$1*
```
If the last digit is even, multiply the rest of the integer by 2 and add 1. This always results in an odd number, so we don't need to repeat this.
```
(\d+)(.)
$2*_;$1*
```
Split off the last digit and convert to unary for the divmod.
```
}`(_+);(\1)*(_*)
;$.($3$#2*
```
Divide the rest of the integer by the last digit and add the remainder. Then repeat the whole program until there's only one digit left.
```
^;*
$.&;
```
Count the number of operations performed.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 61 bytes
```
{tail kv $_,{$1%2??$0/$1+$0%$1+|0!!$0*2+1}...{!/(.+)(.)/}: 2}
```
[Try it online!](https://tio.run/##DcTRCkAwFADQX7mrS5vp7m6JIvkUeaCEElKaffs4D2cfj7WM2wPpBG301zCvsNyAfe7RJq7rkA1ajZz8vywEcua0DUTkhZGklSRlQg0uxHN4YJKlLbhSTfwA "Perl 6 – Try It Online")
Returns (r, o).
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 43 bytes
Feels messy and bad but here it is anyway
```
;0{hl1&|⟨{h⟨k{t%₂0&h×₂+₁|⟨÷+%⟩}t⟩}↰₁{t+₁}⟩}
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/39qgOiPHUK3m0fwV1RlAIru6RPVRU5OBWsbh6UBa@1FTI0ju8HZt1UfzV9aWgIhHbRuAwtUlIMlakMD//2aGJgbm/6MA "Brachylog – Try It Online")
[Answer]
**VBA (Excel), ~~145?, 142, 139,~~ 123 bytes**
Condensed Form:
```
Sub t(n)
While n>10
e=Right(n, 1)
n=Left(n,Len(n)-1)
If e Mod 2=0Then n=n*2+1 Else n=Int(n/e)+n Mod e
c=c+1
wend
Debug.?n;c
End Sub
```
Expanded (with comments)
```
Sub test(n) 'For a given positive integer n
'Repeat the following until n<10
While n > 10
'Extract the last digit
e = Right(n, 1)
'Remove the last digit
n = Left(n, Len(n) - 1)
'If the extracted digit is even...
If e Mod 2 = 0 Then
'Multiply the rest of the integer by 2 and add 1
n = n * 2 + 1
Else
'Divide the rest of the integer with the extracted digit and add the remainder
n = Int(n / e) + n Mod e
End If
'Keep count
c = c + 1
'End the Loop
Wend
'Give the output
Debug.Print (n ; c)
End Sub
```
(Do excuse me, as this is my first post. I will happily edit! Right now, it looks like to test it you open the Immediate Window and type 't n' where n is your number to test :D)
[Answer]
# [Swift 4](https://developer.apple.com/swift/), ~~112~~ ~~104~~ ~~100~~ 93 bytes
```
var n=Int(readLine()!)!,r=0,p=n%10;while n>9{n=[n/10*2+1,n/10/p+n/10%p][n%2];r+=1};print(n,r)
```
[Try it online!](https://tio.run/##Ky7PTCsx@f@/LLFIIc/WM69Eoyg1McUnMy9VQ1NRU1GnyNZAp8A2T9XQwLo8IzMnVSHPzrI6zzY6T9/QQMtI21AHxNAv0AZRqgWx0XmqRrHWRdq2hrXWBUWZQOPydIo0//83MzQxMP8PAA "Swift 4 – Try It Online")
Prints `n r`
* -7 (Thanks to Mr. Xcoder)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
dd/Sɗ:Ḥ‘ɗḂ?Ƭ⁵ṖṖṪ,LƊ
```
[Try it online!](https://tio.run/##y0rNyan8/z8lRT/45HSrhzuWPGqYcXL6wx1N9sfWPGrc@nDnNDBapeNzrOv///9mhiYG5gA "Jelly – Try It Online")
[Answer]
# Common Lisp, 145 bytes
A function which takes the `n` provided and returns the list `(n r)`. Lisp syntax is fun.
```
(defun f(n &optional(r 0))(if(< n 10)`(,n,r)(let((h(floor n 10))(l(mod n 10)))(if(evenp l)(f(1+(* 2 h))(1+ r))(f(+(mod h l)(floor h l))(1+ r)))))
```
[Answer]
## Haskell, 78 bytes
```
f n|n<10=(n,0)|(d,m)<-divMod n 10=(1+)<$>f(last$2*d+1:[div d m+mod d m|odd n])
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hrybPxtDAViNPx0CzRiNFJ1fTRjcls8w3P0UhTwEkYaitaaNil6aRk1hcomKklaJtaBUNVKCQopCrnQtUBaRr8lOAqmM1/@cmZuYp2Cqk5HMpKBQUZeaVKKgopCmYGZoYmKOImP8HAA "Haskell – Try It Online")
[Answer]
# 8086 machine code, 35 bytes
```
00000000 31 c9 31 d2 bb 0a 00 f7 f3 85 c0 74 14 f6 c2 01 |1.1........t....|
00000010 75 05 d1 e0 40 e2 eb 89 d3 88 f2 f7 f3 01 d0 e2 |u...@...........|
00000020 e1 f7 d9 |...|
00000023
```
Input: `AX = n`
Output: `DX = o`, `CX = r`
Assembled from:
```
xor cx, cx
next: xor dx, dx
mov bx, 10
div bx
test ax, ax
jz done
test dl, 1
jnz odd
shl ax, 1
inc ax
loop next
odd: mov bx, dx
mov dl, dh
div bx
add ax, dx
loop next
done: neg cx
```
[Answer]
# [Red](http://www.red-lang.org), 131 bytes
```
func[n][s: 0 while[n > 9][r: do form take/last t: form n t: do t
n: either r % 2 = 1[t / r +(t % r)][2 * t + 1]s: s + 1]print[n s]]
```
[Try it online!](https://tio.run/##JY0xDsIwEAT7vGIbJCBF4giBsASPoD1dEWFbsQhOdD7E842Bbna2GPGu3LwjboIt4ZXulJiyRY/3FGdPCVecmcTCLQiLPKHjw3fzmBVq/yZ9qd7aJAsfdfICwQYDLjCk6Opqt1qN7JgG7KFoYbhm8g9WiUlrKjOXgKM59KfyAQ "Red – Try It Online")
## More readable:
```
f: func [ n ] [
s: 0
while [ n > 9 ] [
r: do form take/last t: form n
t: do t
n: either r % 2 = 1
[ t / r + (t % r) ]
[ 2 * t + 1 ]
s: s + 1
]
print [ n s ]
]
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/113134/edit).
Closed 6 years ago.
[Improve this question](/posts/113134/edit)
Challenge is to write a function/program which outputs a [truthy or falsey](https://codegolf.meta.stackexchange.com/a/2194/52210) value alternately each time you call it. No input.
It can start with either true or false.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
®¬©
```
[Try it online!](https://tio.run/nexus/jelly#@39o3aE1h1b@P7TIGhtSeLhj@6OGOQrOiTk5OgrJ@XnJiSWpeUCso1CUWpCaWKL3HwA "Jelly – TIO Nexus")
### How it works
```
®¬© Main link. No arguments.
® Retrieve the value stored in the register.
¬ Negate it.
© Copy the result to the register.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 30 bytes
```
def f():f.n^=1;print f.n
f.n=0
```
[Try it online!](https://tio.run/nexus/python2#@5@SmqaQpqFplaaXF2draF1QlJlXogDkcAGxrcF/oBQXHvwfAA "Python 2 – TIO Nexus")
[Answer]
# JavaScript ES6, 11 bytes
```
f=i=_=>i=!i
```
```
f=i=_=>i=!i
console.log(f());
console.log(f());
console.log(f());
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~34~~ ~~33~~ 32 bytes
-1 byte thanks to Cyoce
```
def f(x=[]):x+=0,;print len(x)%2
```
[Try it online!](https://tio.run/nexus/python2#@5@SmqaQplFhGx2raVWhbWugY11QlJlXopCTmqdRoalq9D8tv0ghUyEzT11BXcvQwCpNQ/M/AA "Python 2 – TIO Nexus")
This works because the list used as (optional) argument is kept between function calls.
[It's not a bug, it's a feature](http://effbot.org/zone/default-values.htm)
[Answer]
# Java 7, ~~36~~ 35 bytes
```
int f=0;boolean c(){return++f%2<1;}
// OR
boolean f;boolean c(){return f=!f;} // Thanks to @Poke
```
Old answer: `int f=0;boolean c(){return(f^=1)<1;}`
Extremely short for a Java 7 answer. :D (Although still the longest of all submissions of course)
**Explanation:**
```
int f=0; // Integer flag on class level
boolean c(){ // Method with no parameters and a boolean return-type
return ++f % 2 < 1 // return whether `f` modulo 2 is 0 (but increase `f` first)
} // End of method
```
**Test code:**
[Try it here.](https://tio.run/nexus/java-openjdk#xY1BCsIwFET3PcVshJRCULexR@iqS3GR1lQCyU9JfhUpOXuMXsLVwJvHTJmdTgnD3gCWGEt/VFMIzmjCLNo9Gt4idd1yOF9OKjdVW7fJ2RmJNdd4BnuH15bEyNHS43qDbr9rwACPHmReGESrfmh8JzZeho3lWm12JLysP3@vc5NL@QA)
```
class M{
int f=0;boolean c(){return++f%2<1;}
public static void main(String[] a){
M m = new M();
System.out.println(m.c());
System.out.println(m.c());
System.out.println(m.c());
System.out.println(m.c());
System.out.println(m.c());
}
}
```
**Output:**
```
false
true
false
true
false
```
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 6 bytes
```
{T!:T}
```
[Try it online!](https://tio.run/nexus/cjam#@18domgVUvvfys2ayw0G/gMA "CJam – TIO Nexus")
Pushes `T` (initially `0`, falsy), negates it (toggling between `1`, truthy, and `0`), stores the result in `T` for the next invocation and leaves it on the stack.
[Answer]
# Octave, 4 bytes
```
i=~i
```
`i` is initially `sqrt(-1)`. Everything that's not `0` is considered `true` in Octave (note, this doesn't work in MATLAB).
`i=~i` assigns `not(true)` to `i`, making it `false`, The next iteration it will be `false` again.
This is a full program, that can be called using the file name. Example from [octave-online](http://octave-online.net/) with a file name called `inverter.m`:
```
octave:1> source("inverter.m")
i = 0
octave:1> source("inverter.m")
i = 1
octave:1> source("inverter.m")
i = 0
octave:1> source("inverter.m")
i = 1
```
[Answer]
# [Python 3](https://docs.python.org/3/), 31 bytes
```
def f(x=[]):x+=print(len(x)&1),
```
[Try it online!](https://tio.run/nexus/python3#@5@SmqaQplFhGx2raVWhbVtQlJlXopGTmqdRoalmqKnzP01DkwsP/g8A "Python 3 – TIO Nexus")
[Answer]
## Mathematica, 12 bytes
Either of these works:
```
(x=x=!=1>0)&
(x=x===0>1)&
```
I would love to express the `True` or `False` at the end using only `x` and `=` or maybe `!` as well, but unfortunately, that gets longer.
In the notebook environment we can also use this 8-byte solution:
```
%=!=1>0&
```
But it only works if the call to the function is the only thing on its line and there are no other function calls in between, so I won't count this one.
[Answer]
# C, ~~39~~ ~~30~~ ~~26~~ ~~19~~ 18 Bytes
Using a Macro now
```
i;
#define f i++%2
```
Thanks for the help i=!i
~~i;f(){return i=!i;}~~
~~i;f(){return i++?i=0,1:0;}~~
~~i;f(){putchar(i++?i=0,70:84);}~~
~~f(){static i=0;putchar(i++?i=0,70:84);}~~
```
main()
{
putchar(48+f);puts("");
putchar(48+f);puts("");
putchar(48+f);puts("");
putchar(48+f);puts("");
}
```
Output
```
0
1
0
1
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 11 bytes
```
f()((n^=1))
```
Output is via the function's status code.
[Try it online!](https://tio.run/nexus/bash#PcmxCoAgEADQWb/ikAZvCdwCif6kCL1DQRQ0p@jbbaq3vsEatc77ahAHlwoHxAy3meflseCLFJGBLVyBshSCXCigWneOWgM9baikoNToPz5j6pW@4yh9yTRe "Bash – TIO Nexus")
[Answer]
# Ruby, ~~15 14~~ 12 bytes
```
->{0>$.^=-1}
```
[Answer]
# [PHP](https://php.net/), ~~31~~ 25 bytes
*Thanks to user63956 for golfing 6 bytes*
```
function(){echo$_GET^=1;}
```
[Try it online!](https://tio.run/nexus/php#s7EvyChQ4OJSSVOwVfifVpqXXJKZn6ehWZ2anJGvEu/uGhJna2hd@98aqEJDEyf5HwA "PHP – TIO Nexus")
This is an anonymous function.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 25 bytes
```
sed -i y/TF/FT/ $0
echo T
```
[Try it online!](https://tio.run/nexus/bash#S03OyFdQ/1@cmqKgm6lQqR/ipu8Woq@gYsCVCpIJ@a9uV5KaW2CdlFicoUCY9R8A "Bash – TIO Nexus")
This is a full program. You must have write access to the file in addition to execute.
[Answer]
# Applescript, 25
```
property i:0
set i to 1-i
```
Applescript properties are persistent. The result of the last assignment is implicitly given as the program result.
[Answer]
## Haskell, 52 bytes
```
import Control.Monad.State
execState(modify not)True
```
This uses the State monad to store a boolean value which is initially set to `True`. Additional calls must also run within the State monad, e.g.
```
execState(modify not>>modify not>>modify not)True
```
which evaluates to `False`.
[Answer]
# Scala, 25 bytes
```
var b=8<9
def f={b= !b;b}
```
### Explanation:
```
var b = 8 < 9 // define a variable b as false
def f = { // define a function f wothout parameters
b = !b // invert the state of b
b // return b
}
```
There needs to be a space in `b= !b`, so scala doesn't want to invoke the method `=!` on b, which doesn't exists.
[Answer]
# Java, 32 bytes
Not competing because ints aren't truth and false values in Java and an answer like that already exists.
```
int a;int f(){return a=a>0?0:1;}
```
Ungolfed(barely anything to ungolf):
```
int a;
int f() {
return a = a > 0 ? 0 : 1;
}
```
] |
[Question]
[
**(spoilers on decade-old TV show below)**
In the HBO show "The Wire", the dealers use a system of encoding phone numbers where they "jump the 5" on the number pad.
```
+-----------+
| 1 | 2 | 3 |
+-----------+
| 4 | 5 | 6 |
+-----------+
| 7 | 8 | 9 |
+-----------+
| # | 0 | * |
+-----------+
```
A "1" becomes a "9", "4" becomes "6", etc ... and "5" and "0" swap places. So, the input number 2983794-07 becomes 8127316-53. # and \* are undefined. Input in the show was numeric with a dash, your code does not need to preserve the dash but it does need to accept it. No real restrictions on how user interaction is handled, can be a function or console application as needed.
Scoring criteria:
This is a code golf, fewest characters wins. There is a 100 character penalty for solving it with a number/character swap or array lookup (I'm trying to broadly paint a brush stroke to avoid `"9876043215"[i]`-style lookups). 10 character bonus for not stripping dashes.
[Answer]
# MATLAB, 25 bytes
Function accepting a string.
`-` is converted to `=`... so the dash is not just preserved, there is twice as much of it?
```
@(n)106-n-5*(n==48|n==53)
```
[Answer]
## tr, 107 (17 + 100 - 10)
```
tr 0-9 5987604321
```
[Answer]
## GolfScript 9 (= 19 - 10)
```
{16|106\-.5%3=5*-}%
```
or
```
{16|~107+.5%3=5*-}%
```
[Online demo](http://golfscript.apphb.com/?c=OycxMjM0Njc4OS01MCcKCnsxNnx%2BMTA3Ky41JTM9NSotfSU%3D)
### Explanation
As observed by a few people, this calls for subtraction of the digit from 10 in most cases. Since the digits in ASCII start at 48, that means subtracting the ASCII code from `48*2+10 = 106`. That leaves three special cases:
* `0` and `5`: these map to `10` and `5` respectively, and need to map to `5` and `0`. Solution: `.5%3=5*-` subtracts `5` if the result is equal to `3` modulo `5`.
* `-`: this is the fun one. ASCII code `45`, so equivalent to digit `-3`. After the reflection it's equivalent to digit `13`, so I need to subtract `16`. But I can equivalently do that by *adding* `16` before the reflection, and since `45` is the only relevant ASCII code not to have the bit corresponding to `16` set, I can accomplish that with a simple bitwise OR: `16|`.
[Answer]
## JavaScript, ES6, 27 bytes (37 - 10)
```
f=_=>_.replace(/\d/g,y=>y%5?10-y:5-y)
```
Try it in latest Firefox like
```
f("2983794-07")
```
[Answer]
## CJam, 13 (23 - 10) bytes
```
'-_l\/{{si_5%A5?\-}%}%*
```
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# C (63 - 10 = 53)
```
main(_){while(_=getchar())putchar(_>47?(_-=48)%5?58-_:53-_:_);}
```
] |
[Question]
[
Write a function (or macro) that returns true **if and only if** at least one of its arguments contains a call to the function itself and **false otherwise**.
For example:
```
int a=function(); //a==false
int b=function(0); //b==false
int c=function(function(0)); //c==true
int d=function(3*function(1)+2); //d==true (weakly-typed language)
bool e=function(true||function(1)); //e==true (strongly-typed language)
```
EDIT: The function/macro may call other auxiliary function/macros.
EDIT 2: The function must take at least one argument, unless the language used behaves like C, where a function that takes no arguments may still be called with arguments nonetheless.
[Answer]
# Mathematica...
...was *made* for this.
```
SetAttributes[f, HoldAll]
f[x___] := ! FreeQ[Hold@x, _f]
f[] (* False *)
f[0] (* False *)
f[f[0]] (* True *)
f[3 f[1] + 2] (* True *)
f[True || f[1]] (* True *)
```
Everything is an expression, and an expression has a Head and a number of elements. So `1+2` is actually `Plus[1,2]`, and `{1,2}` is actually `List[1,2]`. This means we can match any expression for the head we're interested in - in this case the function `f` itself.
All we need to do is find a way to prevent Mathematica from evaluating the function arguments before the function is called, such that we can analyse the expression tree within the function. What's what `Hold` and `HoldAll` is for. Mathematica itself uses this to all over the place to provide special cases for certain implementations. E.g. if you call `Length[Permutations[list]]` it will never actually create all those permutations and waste loads of memory, but instead realise that it can simply compute this as `Length[list]!`.
Let's look at the code above in detail, using the last call `f[True || f[1]]` as an example. Normally, Mathematica will evaluate function arguments first, so this would simply short-circuit and call `f[True]`. However we have set
```
SetAttributes[f, HoldAll]
```
This instructs Mathematica not to evaluate the arguments, so the `FullForm` of the call (i.e. the internal expression tree, without any syntactic sugar) is
```
f[Or[True,f[1]]]
```
And the argument will actually be received by `f` in this form. The next issue is that, within `f`, as soon as we use the argument, Mathematica will again try to evaluate it. We can suppress this locally with `Hold@x` (syntactic sugar for `Hold[x]`). At this point we've got a handle on the original expression tree and do with it whatever we want.
To look for a pattern in an expression tree we can use `FreeQ`. It checks that a given pattern is not found in the expression tree. We use the patter `_f`, which matches any subexpression with head `f` (exactly what we're looking for). Of course, `FreeQ` returns the opposite of what we want, so we negate the result.
One more subtlety: I've specified the argument as `x___`, which is a sequence of 0 or more elements. This ensures that `f` works with any number of arguments. In the first call, `f[]` this means that `Hold@x` will simply become `Hold[]`. If there were multiple arguments, like `f[0,f[1]]`, then `Hold@x` would be `Hold[0,f[1]]`.
That's really all there is to it.
[Answer]
## C++11
Similar to expression templates we can propagate the fact that we did call the function inside a functions parameters list in its return type.
At first we need some helper classes and functions:
```
#include <iostream>
template <bool FunctionWasInParameters> struct FunctionMarker {
operator bool() const { return FunctionWasInParameters; }
operator int() const { return FunctionWasInParameters; }
};
template <bool... values> struct Or;
template <bool first, bool... values> struct Or<first, values...> {
static constexpr bool value = first || Or<values...>::value;
};
template <> struct Or<> { static constexpr bool value = false; };
template <class T> struct is_FunctionMarker {
static constexpr bool value = false;
};
template <bool B> struct is_FunctionMarker<FunctionMarker<B>> {
static constexpr bool value = true;
};
#define OVERLOAD_OPERATOR_FOR_FUNCTION_MARKER(OPERATOR) \
template <bool B, class T> \
FunctionMarker<B> operator OPERATOR(FunctionMarker<B>, T) { \
return {}; \
} \
template <bool B, class T> \
FunctionMarker<B> operator OPERATOR(T, FunctionMarker<B>) { \
return {}; \
} \
/* to break ambiguity by specialization */ \
template <bool B, bool B2> \
FunctionMarker<B || B2> operator OPERATOR(FunctionMarker<B>, \
FunctionMarker<B2>) { \
return {}; \
}
OVERLOAD_OPERATOR_FOR_FUNCTION_MARKER(|| )
OVERLOAD_OPERATOR_FOR_FUNCTION_MARKER(+)
OVERLOAD_OPERATOR_FOR_FUNCTION_MARKER(*)
// TODO: overload all other operators!
```
Now, we can use it for the exact same code as in the question:
```
template <class... Args>
auto function(Args... args)
-> FunctionMarker<Or<is_FunctionMarker<Args>::value...>::value> {
return {};
}
FunctionMarker<false> function() { return {}; }
int main() {
int a = function();
int b = function(0);
int c = function(function(0));
int d = function(3 * function(1) + 2);
bool e = function(true || function(1));
// clang-format off
std::cout << a << "//a==false\n"
<< b << "//b==false\n"
<< c << "//c==true\n"
<< d << "//d==true (weakly-typed language)\n"
<< e << "//e==true (strongly-typed language)\n";
}
```
[Output from ideone:](http://ideone.com/xkK7PC)
```
0//a==false
0//b==false
1//c==true
1//d==true (weakly-typed language)
1//e==true (strongly-typed language)
```
[Answer]
# C#
```
public PcgBool f(params object[] args)
{
return args.Any(p => p is PcgBool);
}
public class PcgBool
{
public PcgBool() { }
public PcgBool(bool value)
{
Value = value;
}
private bool Value;
public static implicit operator bool(PcgBool pcgBool)
{
return pcgBool.Value;
}
public static implicit operator PcgBool(bool value)
{
return new PcgBool(value);
}
}
```
**Usage** (in [LINQPad](http://www.linqpad.net/)):
```
void Main()
{
Console.WriteLine(f(1,2,f(3),4)); // True
Console.WriteLine(f(1,2,3,"4")); // False
}
```
The trick here is to make `f` more aware of the parameters, by passing a custom type (`PcgBool`) which is kind-of-like a boolean.
P.S. I hope returning a custom type which is implicitly castable from and to a bool is not considered as cheating. Technically you can use the return value as if it was of bool type, and the question asked to "return true if and only if" etc., but never stated the return type must be bool.
[Answer]
# Lua
```
local x
local function f()
local y = x
x = true
return y
end
debug.sethook(function()
if debug.getinfo(2).func ~= f then
x = false
end
end, "l")
print(f())
print(f(0))
print(f(f()))
print(f(f(0)))
print(f("derp" .. tostring(f())))
```
[Answer]
**C++11 TMP**
This one is a bit longer. Because of some limitations in C++ templates I had to do everything with types. Thus "True" as well as the numbers were turned into bool and int. Also The operations +, - and || were turned into add, mul and or\_.
I hope this still qualifies as a valid answer.
```
template <typename... Args>
struct foo;
template <>
struct foo<>
{
static bool const value = false;
};
template <typename T>
struct is_foo
{
static bool const value = false;
};
template <typename... Args>
struct is_foo<foo<Args...>>
{
static bool const value = true;
};
template <typename T>
struct is_given_foo
{
static bool const value = false;
};
template <template <typename...> class T, typename... Args>
struct is_given_foo<T<Args...>>
{
static bool const value = foo<Args...>::value;
};
template <typename Head, typename... Tail>
struct foo<Head, Tail...>
{
static bool const value = is_foo<Head>::value || is_given_foo<Head>::value || foo<Tail...>::value;
};
template <typename... Args>
struct add {};
template <typename... Args>
struct mul {};
template <typename... Args>
struct or_ {};
static_assert(foo<>::value == false, "int a=function(); //a==false");
static_assert(foo<int>::value == false, "int b=function(0); //b==false");
static_assert(foo<foo<int>>::value == true, "int c=function(function(0)); //c==true");
static_assert(foo<add<mul<int, foo<int>>, int>>::value == true, "int d=function(3*function(1)+2); //d==true (weakly-typed language)");
static_assert(foo<or_<bool,foo<int>>>::value == true, "bool e=function(true||function(1)); //e==true (strongly-typed language)");
// just for the sake of C++
int main()
{
return 0;
}
```
[Answer]
# C
I don't think it can be done with procedures, but we can always (ab)use macros.
```
#include <stdio.h>
#define f(x) ((max_depth = ++depth), (x), (depth-- < max_depth))
int depth = 0;
int max_depth = 0;
char* bool(int x) { // Helper - not necessary for solution
return x ? "true" : "false";
}
int main() {
printf("f(1): %s\n", bool(f(1)));
printf("f(f(1)): %s\n", bool(f(f(1))));
printf("f(bool(f(1))): %s\n", bool(f(bool(f(1)))));
printf("f(printf(\"f(1): %%s\\n\", bool(f(1)))): %s\n", bool(printf("f(1): %s\n", bool(f(1)))));
}
```
This outputs:
```
f(1): false
f(f(1)): true
f(bool(f(1))): true
f(1): false
f(printf("f(1): %s\n", bool(f(1)))): true
```
Our macro `f` keeps track of the current depth, and the maximum depth achieved since it was invoked. If the latter is greater than the former, then it has been called recursively.
[Answer]
# C, 13
```
#define F(X)0
```
The argument is never expanded, so it cannot call any macros. It is nothing more than a bunch of plain text. Thus, the answer is always false.
[Answer]
# C
```
#include <stdio.h>
int a, b;
#define foo(x) (b=a++,(void)x,a--,!!b)
int
main(int argc, char **argv)
{
printf("%d\n", foo(1));
printf("%d\n", foo(0));
printf("%d\n", foo(foo(1)));
printf("%d\n", foo(foo(foo(1))));
return 0;
}
```
We can count the recursion depth in the macro. We then overwrite the return value of the outer macro in the inner macro. `!!b` is to normalize the return value to a boolean. The preprocessed code ends up like this:
```
int a, b;
int
main(int argc, char **argv)
{
printf("%d\n", (b=a++,(void)1,a--,!!b));
printf("%d\n", (b=a++,(void)0,a--,!!b));
printf("%d\n", (b=a++,(void)(b=a++,(void)1,a--,!!b),a--,!!b));
printf("%d\n", (b=a++,(void)(b=a++,(void)(b=a++,(void)1,a--,!!b),a--,!!b),a--,!!b));
return 0;
}
```
[Answer]
# C
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BLAH(x) (strncmp( "BLAH(", #x, strlen("BLAH(")) == 0)
int main(int argc, char** argv)
{
printf("%d\n", BLAH(1));
printf("%d\n", BLAH("1234"));
printf("%d\n", BLAH("BLAH"));
printf("%d\n", BLAH(BLAHA));
printf("%d\n", BLAH(BLAHB()));
printf("%d\n", BLAH(BLAH));
printf("%d\n", BLAH(BLAH()));
printf("%d\n", BLAH(BLAH("1234")));
return 0;
}
```
The macro compares if its argument starts with "BLAH(".
[Answer]
# Algol 60
Here's a `boolean procedure` that does what the question asks for (note: Algol 60 is defined in terms of a list of tokens without fixing syntax for them, the below uses Marst syntax to represent the individual tokens that make up the program):
```
boolean procedure recursion detector(n);
boolean n;
begin
own boolean nested, seen nested;
boolean was nested, retval;
was nested := nested;
begin if nested then seen nested := true end;
nested := true;
retval := n; comment "for the side effects, we ignore the result";
nested := was nested;
retval := seen nested;
begin if ! nested then seen nested := false end;
recursion detector := retval
end;
```
## Verification
Here's the test code I used:
```
procedure outboolean(c, b);
integer c;
boolean b;
begin
if b then outstring(c, "true\n") else outstring(c, "false\n")
end;
begin
outboolean(1, recursion detector(false));
outboolean(1, recursion detector(true));
outboolean(1, recursion detector(recursion detector(false)));
outboolean(1, recursion detector(false | recursion detector(true)));
outboolean(1, recursion detector(false & recursion detector(true)));
outboolean(1, recursion detector(recursion detector(recursion detector(false))))
end
```
As expected, the output is:
```
false
false
true
true
true comment "because & does not short-circuit in Algol 60";
true
```
## Explanation
Algol 60 has a different evaluation order from most languages, which has a logic of its own, and is actually much more powerful and general than the typical evaluation order, but is fairly hard for humans to get their head around (and also fairly hard for computers to implement efficiently, which is why it got changed for Algol 68). This allows for a solution with no sort of cheating (the program doesn't need to look at the parse tree or anything like that, and unlike almost all the other solutions here, this would work just fine if the nested call were made via an FFI).
I also decided to show off a few other quirks of the language. (Notably, variable names can contain whitespace; this is fairly useful for readability, because they *can't* contain underscores. I also love the fact that the comment indicator is the literal word `comment` in most syntax encodings. Algol 68 found this fairly awkward for short comments, and introduced `¢` as an alternative. The quotes around the comment body aren't normally needed, I just add them for clarity and to prevent the comment accidentally ending when I type a semicolon.) I actually really like the broad concepts of the language (if not the details), but it's so verbose that I rarely get to use it on PPCG.
The main way in which Algol 60 differs from the languages it inspired (such as Algol 68, and indirectly C, Java, etc; people who know K&R C will probably recognise this syntax for functions) is that a function argument is treated a bit like a little lambda of its own; for example, if you give the argument `5` to a function that's just the number 5, but if you give it the argument `x+1` you get exactly what you specified, the concept of "`x` plus 1", rather than the *result* of `x` plus 1. The difference here is that if `x` changes, then attempts to evaluate the function argument in question will see the *new* value of `x`. If a function argument isn't evaluated inside the function, it won't be evaluated outside the function either; likewise, if it's evaluated multiple times inside the function, it'll be evaluated separately each time (assuming that this can't be optimised out). This means that it's possible to do things like capture the functionality of, say, `if` or `while` in a function.
In this program, we're exploiting the fact that if a call to a function appears in an argument to that function, that means that the function will run recursively (because the argument is evaluated at exactly the point or points that the function evaluates it, no earlier or later, and this must necessarily be inside the function body). This reduces the problem to detecting if the function is running recursively, which is much easier; all you need is a thread-local variable that senses if there's a recursive call (plus, in this case, another one to communicate information back the other way). We can use a static variable (i.e. `own`) for the purpose, because Algol 60 is single-threaded. All we have to do after that is to put everything back the way it was, so that the function will function correctly if called multiple times (as required by PPCG rules).
The function doesn't return the desired value from the inside calls at the moment (at least if you assume they should look for self-calls in only *their* arguments, rather than counting themselves); making that work is fairly easy using the same general principles, but more complex and would obscure the workings of the function. If that's deemed necessary to comply with the question, it shouldn't be too hard to change.
[Answer]
## Java
```
public class FuncOFunc{
private static int count = 0;
public static void main(String[] args){
System.out.println("First\n" + function());
reset();
System.out.println("Second\n" + function(1));
reset();
System.out.println("Third\n" + function(function(1)));
reset();
System.out.println("Fourth\n" + function(3*function(1)+2));
reset();
System.out.println("Fifth\n" + function(function(1), function(), 4));
}
/**
* @param args
*/
private static int function(Object...args) {
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
count+=stackTraceElements.length;
if(count>3) return 1;
else return 0;
}
static void reset(){
count = 0;
}
}
```
can `reset()` be counted as auxiliary?
**Output:**
```
First
0
Second
0
Third
1
Fourth
1
Fifth
1
```
## EDIT
Here is another version that doesn't use the `reset()` method, but a lot of madness. It creates and compiles at runtime the above code with the call to the function passed as an argument in stdin. I wanted a more elegant solution but sadly I don't have too much time for this :(
To run it simply call for example `javac FuncOFunc.java function(function(1),function(),4)`.
```
import java.io.File;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
public class FuncOFunc {
public static void main(String[] args) throws Exception {
JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager sjfm = jc.getStandardFileManager(null, null, null);
File jf = new File("FuncOFuncOFunc.java");
PrintWriter pw = new PrintWriter(jf);
pw.println("public class FuncOFuncOFunc{"
+ "public static void main(){ "
+ " System.out.println("+ args[0] +");"
+ "}"
+ " private static int function(Object...args) {"
+ " StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();"
+ " if(stackTraceElements.length>3) return 1;"
+ " else return 0;"
+ " }"
+ "}");
pw.close();
Iterable<? extends JavaFileObject> fO = sjfm.getJavaFileObjects(jf);
if(!jc.getTask(null,sjfm,null,null,null,fO).call()) {
throw new Exception("compilation failed");
}
URL[] urls = new URL[]{new File("").toURI().toURL()};
URLClassLoader ucl = new URLClassLoader(urls);
Object o= ucl.loadClass("FuncOFuncOFunc").newInstance();
o.getClass().getMethod("main").invoke(o);
ucl.close();
}
}
```
[Answer]
# Python
```
import ast, inspect
def iscall(node, name, lineno=None):
return isinstance(node, ast.Call) \
and (node.lineno == lineno or lineno is None) \
and hasattr(node.func, 'id') \
and node.func.id == name
def find_call(node, name, lineno):
for node in ast.walk(node):
if iscall(node, name, lineno):
return node
def is_call_in_args(call):
descendants = ast.walk(call);
name = next(descendants).func.id
return any(map(lambda node: iscall(node, name), descendants))
def function(*args):
this = inspect.currentframe()
_, _, funcname, _, _ = inspect.getframeinfo(this)
outer = inspect.getouterframes(this)[1]
frame, filename, linenum, _, context, cindex = outer
module = ast.parse(open(filename).read())
call = find_call(module, funcname, linenum)
return is_call_in_args(call)
if __name__ == '__main__':
print("Works with these:")
assert(function() == False)
assert(function(3*function(1)+2) == True)
assert(function(0) == False)
assert(function(function(0)) == True)
assert(function(True or function(1) == True))
print("Does not work with multiple expressions on the same line:")
assert(function(function()) == False); function()
function(); assert(function(function()) == False)
```
Save it as `selfarg.py` and run it or `from selfarg import function` in another script. It does not work in the repl.
Using the current and outer stack frames `function` obtains its name and place
of call (file and line number). It then opens the obtained file and parses it
into an abstract syntax tree. It skips to the function call identified by the
line number and inspects if it has another function call with the same name in
its arguments.
*edit*: It's OK with python2 too. Changed python3 to python in the title.
] |
[Question]
[
Two numbers are coprime if their greatest common divisor is 1.
Given a positive integer **N**, your task is to compute the first **N** terms of [OEIS A061116](http://oeis.org/A061116), which is the sequence of positive integers higher than 1 that are coprime to all their *decimal* digits.
Here are the first few terms of the sequence:
```
11, 13, 17, 19, 21, 23, 27, 29, 31, 37, 41, 43, 47, 49, 51, 53, 57, 59, 61, 67, 71
```
You can assume that **N < 200**.
---
# Test Cases
```
Input -> Output
1 -> 11
3 -> 11, 13, 17
6 -> 11, 13, 17, 19, 21, 23
25 -> 11, 13, 17, 19, 21, 23, 27, 29, 31, 37, 41, 43, 47, 49, 51, 53, 57, 59, 61, 67, 71, 73, 79, 81, 83
```
You may output in any decent form (as a list, with a separator or whatever else). You can take input as the String representation of **N** or as an integer. [Standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply.
---
[Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
[Answer]
# [Plain English](https://github.com/Folds/english) ~~853~~ ~~787~~ ~~738~~ ~~594~~ ~~550~~ ~~538~~ 532 bytes
Removed 66 bytes of white space. Removed 49 bytes by using a more generic output type. Removed 144 bytes by abbreviating variable names, and reusing the quotient and the remainder. Removed 44 bytes by abbreviating an interface. Shortened `Destroy the number things.` to `Destroy the L.` Removed 6 bytes by changing "some" to "a", and "number" to "count".
Golfed code:
```
To create a L number things given a c count:
Put 0 in a i count.
Loop.
Add 1 to a n count.
If the i is at least the c, exit.
If the n is g,
append the n to the L;
add 1 to the i.
Repeat.
To decide if a n count is g:
If the n is at most 10, say no.
Put 1 in a m count.
Loop.
If the m is greater than the n, say yes.
Divide the n by the m giving a q quotient and a r remainder.
Divide the q by 10 giving the q and the r.
Get a gcd given the n and the r.
If the gcd is at least 2, say no.
Multiply the m by 10.
Repeat.
```
Ungolfed code:
```
Some special numbers are some number things.
To create some special numbers given a count:
Put 0 in another count.
Loop.
Add 1 to a number.
If the other count is at least the count, exit.
If the number is coprime with its digits,
Append the number to the special numbers;
Add 1 to the other count.
Repeat.
To decide if a number is coprime with its digits:
If the number is at most 10, say no.
Put 1 in another number.
Loop.
If the other number is greater than the number, say yes.
Divide the number by the other number giving a quotient and a remainder.
Divide the quotient by 10 giving another quotient and another remainder.
Get a gcd given the number and the other remainder.
If the gcd is greater than 1, say no.
Multiply the other number by 10.
Repeat.
```
"Some number things" are a doubly-linked list of numbers.
The calling code has the responsibility to `Destroy the special numbers.`, so I have added the corresponding bytes.
The Plain English IDE is available at [github.com/Folds/english](https://github.com/Folds/english). The IDE runs on Windows. It compiles to 32-bit x86 code.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~, 8 bytes
```
gQỊẠ
2Ç#
```
[Try it online!](https://tio.run/##y0rNyan8/z898OHuroe7FnAZHW5X/v//vxkA "Jelly – Try It Online")
2 bytes saved thanks to @Dennis!
Explanation:
```
# Helper link: Is it in the sequence at all?
Ạ # All of...
g # The GCDs of A and...
Q # The unique digits of A
Ị # Are less than or equal to 1
#
# Main link:
# # The first *n* truthy results of
Ç # The last link
2 # Starting at 2
```
[Answer]
# [Perl 6](http://perl6.org/), 39 bytes
```
{(grep {$_ gcd.comb.all==1},2..*)[^$_]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiO9KLVAoVolXiE9OUUvOT83SS8xJ8fW1rBWx0hPT0szOk4lPrb2v7VCcWKlQpqGoYGBpvV/AA "Perl 6 – Try It Online")
[Answer]
# Mathematica, ~~80~~ ~~70~~ 64 bytes
```
For[t=2;n=#,n>0,t++,Max[t~GCD~IntegerDigits@t]<2&&Print@t&&n--]&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvvfLb8ousTWyDrPVlknz85Ap0RbW8c3sSK6pM7d2aXOM68kNT21yCUzPbOk2KEk1sZITS2gKDOvxKFETS1PVzdW7T@Yq@CQpuBgZPofAA "Mathics – Try It Online")
*-10 bytes thanx to @MartinEnder*
*-6 bytes from @JungHwan Min*
[Answer]
# Haskell, ~~64~~ ~~59~~ ~~58~~ ~~57~~ 51 bytes
Saved a total of 6 bytes thanks to @Laikoni and @Ørjan Johansen
```
(`take`[x|x<-[2..],and[x`gcd`read[c]<2|c<-show x]])
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P81WI6EkMTs1IbqipsJGN9pITy9WJzEvJboiIT05JaEoNTElOjnWxqgm2Ua3OCO/XKEiNlbzf25iZp6CrUJKPpcCEBQUZeaVKKgopCkYovGNTP8DAA)
[Answer]
## Haskell, 115 bytes
```
q n=take n(filter(\x->1==(maximum$map(x%)(d x)))[11,13..])
d 0=[]
d x=mod(x)10:(d(x`quot`10))
x%0=x
x%y=y%(x`mod`y)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
↑tfȯεΠṠM⌋dN
```
[Try it online!](https://tio.run/##AR8A4P9odXNr///ihpF0ZsivzrXOoOG5oE3ijItkTv///zUx "Husk – Try It Online")
[Answer]
## JavaScript (ES6), 93 bytes
```
f=(n,k=11,g=(a,b)=>b?g(b,a%b):a)=>n?[...''+k].some(d=>g(k,d)>1)?f(n,k+1):[k,...f(n-1,k+1)]:[]
```
[Answer]
# [PHP](https://php.net/), 120 bytes
```
for($n=2;!$r[$argn-1];$t?:$r[]=$n,$n++)for($t=$i=0;~$s=("$n")[$i++];$t|=$d)for($d=$s?:$t|=1;$s%$d|$n%$d--;);print_r($r);
```
[Try it online!](https://tio.run/##Jcs/C8IwEAXwvd/CcEJDLFjBQc@jg3Rw0cWtlCL0X5ZruGYs/eox1uXgvfc7N7pwK9zokk5kkkY6N4m3PKRr2Txf78e91JjARwYmdb4oDP0kKTCdcAdSbUOW1wi@uMZcE/AB2Bi9MU9g6YgrzJQqYKUrsMb89ELQ/k1LMMff2OQI8x7aBTjeLEONTiz7JiLRGMIX "PHP – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Èì ejX}jUB
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yOwgZWpYfWpVQg&input=MjU)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
```
↑tfλΛȯεnḊ¹Ḋd)N
```
[Try it online!](https://tio.run/##yygtzv7//1HbxJK0c7vPzT6x/tzWvIc7ug7tBBIpmn7///83AQA "Husk – Try It Online")
## Explanation
```
↑tfλΛȯεnḊ¹Ḋd)N
fλ )N filter all natural numbers by the following lambda:
Λȯ d map each digit of the natural number, and check if all are truthy:
Ḋ¹Ḋ divisors of the digit and divisors of the argument
n set intersection
ε has length 1? (co primality check)
t remove the first element
↑ take n items from the sequence(n → input)
```
] |
[Question]
[
The [MMIX](https://en.wikipedia.org/wiki/MMIX) architecture is a fairly simple big-endian RISC design. It has a couple of interesting features, one of them is the `MXOR` instruction, which is what you should implement.
The `MXOR` instruction interprets its arguments (two 64-bit registers) as two 8×8 matrices of bits and performs a matrix multiplication where exclusive-or is used for addition and logical and is used for multiplication.
An argument in binary representation where the leftmost digit is most significant
>
> a0 a1 a2 … a63
>
>
>
is interpreted as a matrix like this:
>
> a0 a1 … a7
>
> a8 a9 … a15
>
> …
>
> a56 a57 … a63
>
>
>
Your task is to write a function, subroutine or similar in a language of choice which can be evoked from a single-letter name (i.e. `f(x,y)`) that implements this function. The two arguments of the function shall be of equal implementation-defined unsigned 64 bit integer type, the function shall return a value of the same type.
he winner of this competition is the shortest submission (measured in bytes or characters if the language you use uses a meaningful character encoding). You are encouraged to post a readable commented version of your code in addition to the golfed solution so other's can understand how it works.
[Answer]
### APL, 28 characters
```
f←{2⊥,↑≠.×/{8 8⍴(64⍴2)⊤⍵}¨⍵}
```
Usage:
```
> f 12345678 87654321
3977539
```
You can read it almost literally if you go right-to-left. `(64⍴2)⊤` transforms each argument into 64 bit representation and `8 8⍴` makes an 8x8 matrix out of the results. `≠.×/` then applies the inner product to both arguments, where multiplication `×` and xor `≠` is used. The matrix is then transformed back to vector form `,↑`, before `2⊥` undoes the basis transformation.
[Answer]
## x86 machine code, 45 44 40 bytes
```
40072c: b1 08 mov $0x8,%cl
40072e: 48 c1 c7 08 rol $0x8,%rdi
400732: b5 08 mov $0x8,%ch
400734: 48 0f 6e c6 movq %rsi,%mm0
400738: 0f d7 d0 pmovmskb %mm0,%edx
40073b: 40 20 fa and %dil,%dl
40073e: 7a 01 jp 400741 <amul+0x15>
400740: f9 stc
400741: 48 11 c0 adc %rax,%rax
400744: 48 d1 c6 rol %rsi
400747: fe cd dec %ch
400749: 75 e9 jne 400734 <amul+0x8>
40074b: 48 c1 ce 08 ror $0x8,%rsi
40074f: fe c9 dec %cl
400751: 75 db jne 40072e <amul+0x2>
400753: c3 retq
```
The code uses two tricky moves. The first is the `pmovmskb` intsruction which takes every 8th bit of an mmx register and packs them together into an integer register. Very useful for extracting columns. The second is the parity flag which is used to accumulate the dot product (the `and`/`jp`/`stc` combo).
Here's the expanded code with comments:
```
# rowloop
mov $8, %cl
1:
rol $8, %rdi # get next row of A into low 8 bits
# columnloop
mov $8, %ch
2:
# extract first column
movq %rsi, %mm0
pmovmskb %mm0, %edx
# dot with current row
testb %dil, %dl
# shift result and add parity bit
jp 3f
stc
3:
adc %rax, %rax
# shift over columns of B
rol %rsi
dec %ch
jne 2b
# restore B
ror $8, %rsi
dec %cl
jne 1b
ret
```
[Answer]
## GolfScript (49 48 45 chars)
This takes a completely different approach to my earlier GolfScript entry, so I think it wants a separate answer.
```
{0{1$M&16.?M/:K*3$K&M*&^@2/@M)/@}255:M*++}:f;
```
It's pure bit-bashing.
If we consider `a` as a series of matrix elements we get
```
a_00 a_01 a_02 a_03 a_04 a_05 a_06 a_07 a_10 a_11 ...
```
Similarly `b`. Now, `c_ij = a_i0 & b_0j ^ a_i1 & b1j ^ ... ^ a_i7 & b7j`. So by grouping over the common index we get
```
c = (a_00 a_00 ... a_00 a_00 a_10 a_10 ...) & (b_00 b_01 b_02 ... b_07 b_00 b_01 ...)
^ (a_01 a_01 ... a_01 a_01 a_11 a_11 ...) & (b_10 b_11 b_12 ... b_17 b_10 b_11 ...)
^ ...
= (((a >> 7) & 0x0101010101010101) * 0xff) & (((b >> 56) & 0xff) * 0x0101010101010101)
^ (((a >> 6) & 0x0101010101010101) * 0xff) & (((b >> 48) & 0xff) * 0x0101010101010101)
^ ...
```
That's enough background to be able to explain the code:
```
{ # Function declaration boilerplate; stack is a b
0 # Accumulator for the result
{ # Loop: stack holds a>>k b>>8k partial-sum
1$M& # M holds 255 (see below); get (b>>8k) & 0xff
16.?M/:K # Derive 0x0101010101010101 and store in K
* # Multiply: stack is a>>k b>>8k partial-sum rhs-of-and
3$K&M* # Similarly for a: add lhs-of-and to the stack
&^ # Do the pointwise multiplication and addition
@2/@M)/@ # Restore loop invariant with a>>=1 and b>>=8
}255:M* # Store 255 in M and execute the loop that many times
# 8 times suffices to get the correct result; after that b>>8k == 0 and the
# partial sum doesn't change. After 64 iterations, a>>k == 0
++ # So we can ditch their remnants by adding to the partial sum
}:f; # Function declaration boilerplate
```
Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for the observation that `16.?` is equal to `2 64?` (or `2.6??`); since it's one char shorter, I've stolen it. Thanks to [Howard](https://codegolf.stackexchange.com/users/1490/howard) for suggesting a 2-char improvement which became 48->45.
[Answer]
# CJam, 35 bytes
```
{2{GG#+2b1>8/\}*zm*{z{:&}%:^}%2b}:F
```
[Try it online](http://cjam.aditsu.net/ "CJam interpreter") by pasting the following *Code*:
```
{2{GG#+2b1>8/\}*zm*{z{:&}%:^}%2b}:F; " Define function and clear stack. ";
12345678 87654321 F " Call function. ";
```
### How it works
```
2{ " Do the following twice: ";
GG#+ " Add 16 ** 16 = 2 ** 64 to the topmost integer on the stack. ";
2b " Convert it into an array of its digits in base two. ";
1> " Discard the first digit. ";
8/ " Split into arrays of 8 digits. ";
\ " Swap the resulting array with the second topmost stack element. ";
}* " This converts two 64-bit integers into 8×8 matrices of its base 2 digits. ";
zm* " Transpose the second matrix and compute the cartesian product of both. ";
{ " For each pair (one row of the first and one column of the second matrix): ";
z " Transpose the array. ";
{:&}% " For each array of the array, compute the logical AND of its elements. ";
:^ " Compute the logical XOR of the results. ";
}% " Note that ^ and & are addition and multiplication in GF(2). ";
2b " Convert the array of base 2 digits into and integer. ";
```
[Answer]
## GolfScript (65 chars)
```
{[{2.6??+2base(;8/\}2*zip 8*\{{.}7*}%]zip{zip{~&}%{^}*}%2base}:f;
```
This turns out to be similar to BeetDemGuise's Python solution, although it uses more zips and less eval.
Dissection:
```
{
# Stack: a b (as integers)
[ # Start gathering into array for subsequent zip
{ # Repeat twice:
2.6??+2base(; # Convert to 64 bits
8/ # Break into an 8x8 matrix
\ # Flip top of stack
}2*
# Stack: a b (as matrices)
# Each cell of the matrix product needs a row of a and a column of b
zip 8* # Get 8 copies of columns of b, ordered
# [col_0 col_1 ... col_7 col_0 col_1 ...]
\{{.}7*}% # Get 8 copies of rows of a, ordered
# [row_0 row_0 row_0 ... row_7 row_7]
] # Gather into array
zip # Zip: each array entry is now an array [col_j row_i]
{ # Map each array item
zip # Pair up each bit from col_j with corresponding bit of row_i
{~&}% # Multiply the bits in each pair
{^}* # Add the products
}%
2base # Convert back from an array of 64 bits to an integer
}:f; # Assign to f and don't leave a copy lying about on the stack
```
[Answer]
## J, 50 chars
Here is a version that does not use J's built-in [general matrix product conjunction](http://www.jsoftware.com/help/dictionary/d300.htm) `.`.
```
f=:#.@,@:(|."1)@(~:/@:*"2 1"1 2|.)&(8 8$]#:~64#2:)
```
### Testing (with 4×4 matrices)
```
g=:#.@,@:(|."1)@(~:/@:*"2 1"1 2|.)&(4 4$]#:~16#2:)
44584 g 28371
46550
```
And the matrices visualized, for manual verification.
```
(4 4$]#:~16#2:)&.> 44584;28371;46550
┌───────┬───────┬───────┐
│1 0 1 0│0 1 1 0│1 0 1 1│
│1 1 1 0│1 1 1 0│0 1 0 1│
│0 0 1 0│1 1 0 1│1 1 0 1│
│1 0 0 0│0 0 1 1│0 1 1 0│
└───────┴───────┴───────┘
```
### Exploded view
```
&( ) to each of the arguments,
64#2: generate 64 2's (radix for below)
]#:~ decode from radix
8 8$ reshape as 8×8 array
( |.) reverse the right argument
"2 1"1 2 for each pair of rows,
* multiply
@: composed with
~:/ xor folded
(|."1)@ reverse each row
,@: ravel (flatten array)
#.@ back to binary again
f=: assign function to name 'f'
```
[Answer]
# Python 2 - 183
```
def m(a,b):a,b=map(lambda x:'{:064b}'.format(x),[a,b]);r=range(8);return int(''.join(`eval('^'.join(o+'&'+t for o,t in zip(a[8*i:8+8*i],v)))`for i in r for v in[b[j::8]for j in r]),2)
```
This is the first thing that came to my mind and so it can mostly likely be golfed down quite a bit more. In any case, its pretty straight-forward string manipulation:
```
def m(a,b):
# Convert the integer inputs to their 64bit binary versions.
a,b=map(lambda x:'{:064b}'.format(x),[a,b])
n=''
# For all rows in matrix a...
for row in [a[8*i:8+8*i] for i in range(8)]:
# For all columns in matrix b...
for col in [b[j::8] for j in range(8)]:
# Get each pair.
pairs = zip(row, col)
# Multiply each pair.
mul_pairs = ['&'.join(z) for z in pairs]
# XOR them all together.
result = '^'.join(mul_pairs)
# Append the result to n.
n+=`eval(result)`
return int(n,2)
```
[Answer]
# J (34)
This *should* work I think. It would be nice if you gave some test cases...
```
f=:~:/ .*&.(8 8&$@(_64&{.) :.,@#:)
```
This works with the test cases supplied in the comments (when changing `8 8` to `4 4` and changing `64` to `16`)
### Explanation
The whole function can be simplified to the following:
```
F&.G
```
Visual representation:

What this means: `G` is applied to both arguments. Then `F` is applied with `G x` as its left argument, and `G y` as its right argument. Then, the inverse of `G` is applied to the result of `F`. "Inverse?", you might ask. With inverse I mean a function applied `_1` times, so for example the inverse of `#:` (dec -> bin vector) is `#:^:_1` (or `#.`) (bin vector -> dec).
So, applying this theory, this would be `G`:
* `#:` takes the binary form of the argument
* `_64&{.` takes the last 64 items of the list. When there aren't 64 or
more items, it will be padded with 0's
* `8 8&$` shapes it to an 8\*8 matrix
* `:.,` sets the reverse of `(4 4&$@(_16&{.)` to be just `,`: [ravel](http://www.jsoftware.com/help/dictionary/d320.htm)
and this would be `F`:
* `~:/ .*` is matrix multiplication
] |
[Question]
[
**INPUT:**
* 10 random numbers
* each number is greater than 0 and less than 100
* list of numbers is presorted, lowest to highest
* the list will not contain any duplicate numbers
**CHALLENGE:**
Write a function that would take in the numbers, and return the count of the longest group of consecutive numbers.
**EXAMPLE OUTPUT:**
```
1 2 33 44 55 66 77 88 90 98 => return of the function would be 2
1 3 23 24 30 48 49 70 75 80 => return of the function would be 2
6 9 50 51 52 72 81 83 90 92 => return of the function would be 3
```
[Answer]
## APL, ~~26~~ 21 characters
```
1+⌈/+/^\9 9⍴0,1=-2-/⎕
```
Here's the 26-character solution:
```
i←⎕⋄⌈/{1++/^\⍵↓1=-2-/i}¨⍳9
```
I used Dyalog APL as my interpreter, and `⎕IO` should be set to 0 for the 26-character version.
Example:
```
1+⌈/+/^\9 9⍴0,1=-2-/⎕
⎕:
6 7 51 51 53 51 54 55 56 55
3
```
[This answer](https://codegolf.stackexchange.com/a/4492/3284) explains most of what I in the 26-character solution, but I might have to write a new one up for the 21-character version.
[Answer]
# Haskell, 54
```
import List
f=maximum.map length.group.zipWith(-)[1..]
```
[Answer]
## GolfScript, 23 characters
```
~]1\{.@-(!@*).@}*;]$)p;
```
Test cases:
```
"1 2 33 44 55 66 77 88 98" --> 2
"1 3 23 24 30 48 49 70 80" --> 2
"6 9 50 51 52 72 81 83 92" --> 3
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
_JŒɠṀ
```
[Try it online!](https://tio.run/##y0rNyan8/z/e6@ikkwse7mz4//9/tJmOpY6pgY6poY6pkY65kY6FoY6FsY6lUSwA "Jelly – Try It Online")
```
_J Subtract [1,2,3…] from the input.
This will turn a run like [48,49,50] into something like [45,45,45].
Œɠ Get group lengths. (“aaaabbc” → [4,2,1])
Ṁ Maximum.
```
[Answer]
# J, 23
```
>:>./(+*[)/\.(}.=>:&}:)
```
Sample use:
```
>:>./(+*[)/\.(}.=>:&}:) 1 2 33 44 55 66 77 88 98
2
>:>./(+*[)/\.(}.=>:&}:) 1 3 23 24 30 48 49 70 80
2
>:>./(+*[)/\.(}.=>:&}:) 6 9 50 51 52 72 81 83 92
3
```
[Answer]
## Python, 79 characters
```
f=lambda l:max(map(len,''.join(' x'[a-b==1]for a,b in zip(l[1:],l)).split()))+1
```
[Answer]
## Mathematica, ~~50~~ 31 bytes
```
Max[Length/@Split[#,#2-#==1&]]&
```
This is an anonymous function. You can either give it a name, by assigning it to something, or you can just append `@{6, 9, 50, 51, 52, 72, 81, 83, 90, 92}` to use it straight away.
Here is how it works:
`#2-#==1&` is a nested anonymous function, which takes two arguments and returns `True` if the arguments are consecutive integers (and `False` for other integer pairs).
`Split` then partitions the resulting array into runs of elements, for which the above function returns `True`.
Now we map `Length` onto the result to figure out how many numbers each run contains, and select the maximum.
Thanks to David Carraher for eliminating large parts by using a test function in `Split`!
[Answer]
## Python
new:
```
def s(q):
i = r = 1
l = -1
for n in q:
if n == l + 1:
i += 1
elif i > r:
r,i = i,1
else:
i=1
l=n
return i if i > r else r
```
old (buggy):
```
def s(q):
i=r=1;l=-1
for n in q:
if n==l+1:i+=1
elif i>r:r,i=i,1
l=n
return r
```
test case:
```
x = [1,2,3,50,56,58,60,61,90,100]
print x
print s(x)
>>> 3
```
edit: forgot the input numbers had to be in order. fixed
edit2: fixed a problem when all the numbers are a sequence, eg 1,2,3,4,5,6,7,8,9,10, and it returned just '1'
edit3: oops, didn't realize it wasn't code golf.
[Answer]
## Scheme/Racket
Here's a trivial answer in Scheme...
```
(define f
(λ (l)
(letrec ((g (λ (l M c p)
(cond ((null? l)
(max M c))
((= (car l) (+ p 1))
(g (cdr l) M (+ c 1) (car l)))
(else (g (cdr l) (max M c) 1 (car l)))))))
(g l 1 1 -2))))
(f '(1 2 33 44 55 66 77 88 98)) ;=> 2
(f '(1 3 23 24 30 48 49 70 80)) ;=> 2
(f '(6 9 50 51 52 72 81 83 92)) ;=> 3
```
where
* `l` is the `l`ist
* `M` is the `M`aximum consecutive number count found so far
* `c` is the `c`urrent consecutive number count
* `p` is the `p`revious number in the list
[Answer]
## JavaScript (80 93 107)
```
for(n=prompt(c=m=1).split(' '),i=9;i;m=++c>m?c:m)c*=!(--n[i]-n[--i])|0;alert(m);
```
Demo: <http://jsfiddle.net/QqfY4/3/>
**Edit 1**: Replaced `a` with `n[i]` and `b` with `n[i-1]`. Converted `Math.max` to ternary if. Moved initialization statement into `for(`.
**Edit 2**: Reversed iteration direction to eliminate need for `i++` by changing to `--i` in second `n[--i]`. Replaced `i++` with part of `if` body. Changed condition to `i` to take advantage of ending at 0 = false. Hard-code starting value of `9` due to spec `10 random numbers`.
[Answer]
## Python, 87 characters
Recursive solution:
```
def s(l):
n=1
while n<len(l)and l[n]-l[0]==n:n+=1
return max(n,s(l[n:])if l else 0)
```
Testing:
```
>>> s([1, 2, 33, 44, 55, 66, 77, 88, 98])
2
>>> s([1, 3, 23, 24, 30, 48, 49, 70, 80])
2
>>> s([6, 9, 50, 51, 52, 72, 81, 83, 92])
3
```
[Answer]
Since I can't edit code, I'll redefine the Scheme answer (Racket or not, portable and easier to read). Variables have descriptive names and there is only one recursion of the list while being error free (i think). Who cares about characters when you got efficiency?
```
(define (count-consecutive lst)
(call-with-current-continuation
(lambda (return)
(define (test n)
(unless (integer? n)
(return (error "Not integer: " n))))
(define (g best) (f best n (cdr lst)))
(let ([prev (car lst)] [count 0]) (test prev)
(let f ([best 0] [prev prev]
[lst (cdr lst)])
(if (null? lst) best
(let ([n (car lst)]) (test n)
(if (= (- n prev) 1)
(let ([count (+ count 1)])
(if (> count best) (g count)
(g best)))
(let ([count 0])
(g best))))))))))
```
[Answer]
## Scala
```
def maxconsec(ln:List[Int]):Int=
{
var (max,current,last)=(1,1,-1)
for(n<-ln)
{
if(n==last+1)
{
current+=1;
if(current>max)max=current
}
else
{
current=1
}
last=n
}
return max
}
```
I think this is O(n); is it possible to be more efficient? Can the OP elaborate on how efficiency is being measured here?
Usage: (you can test it on [simplyscala.com](http://www.simplyscala.com))
```
maxconsec(List(6,9,50,51,52,72,81,83,90,92))
```
[Answer]
## Python
```
def s(n):
l=0
t=1
for i in range(0,9):
if n[i]+1==n[i+1]:
t+=1
else:
if l<t:
l=t
t=1
return l
```
[Answer]
# Ruby
I'm generally not that great at knowing more efficient methods. Might be some ruby standard lib things I'm missing.
```
def consec_count(arr)
tg = 1
cg = 1
l = arr[0]
arr.each do |v|
if l + 1 == v
cg += 1
tg = cg if tg < cg
else
cg = 1
end
l = v
end
tg
end
```
[Answer]
# [R](https://www.r-project.org/), 34 bytes
```
u=rle(1:99%in%scan());max(u$l*u$v)
```
[Try it online!](https://tio.run/##jc5bCoJAAIXh91bxQwra01ydmcL2YqYU2AjmVLu3ywJCOM/f@adli0ShNcZgLVWFc3hPEARPfWTq5jRFxp750tGn2M7XMfIc03Dm1KE2X0KjPjNogfGYgBM4ixdriYqAFViJVTiFl3j9q1BrCL2kehq6Qu5DyK8xv7dNLMrycGteRcqGXcoe5fLnY3kD "R – Try It Online")
This is a copy-paste of [Micky T's answer](https://codegolf.stackexchange.com/a/168438/80010) to [this challenge](https://codegolf.stackexchange.com/q/168427/80010). Upvote him!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 6 bytes
```
∞-γ€gZ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//Ucc83XObHzWtSY/6/z/aTEfBUkfB1ACIDYHYSEfBHIgtgGwLY6AUUNzSKBYA "05AB1E – Try It Online")
Thanks to @Kevin Cruijssen for -1 byte
Code:
```
∞ push endless list [1, 2, 3, 4, 5, ...]
- subtract that from input
γ group by equal elements
€g push lengths of each group
Z push max length
implicitly print top of stack
```
[Answer]
# [Python 3](https://docs.python.org/3/), 73 bytes
```
def f(l):s=[n-i for i,n in enumerate(l)];return max(s.count(i)for i in s)
```
[Try it online!](https://tio.run/##VY7BDoIwDIbvPkWPLKkGGWND45MQDkRHXKKDjJHo088f5SCHJk3/72s7vuN98DKlm@2pzx7iNF0av3fUD4Ece3KerJ@fNnTRIm7PwcY5eHp2r2w6XIfZx8yJL72wk0hjcJj1WXNkKpikZCpLJqWYqopJayZjmOocZVohdv8C4GIpCBJACbCsIaHXWGDyjYB1CBVCBVfhmkYZ9EauFzY8ButTWAsBH0EB/QPTBw "Python 3 – Try It Online")
This works by subtracting the index from each number in the list and finding the greatest frequency in the list.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
▲mLgz-N
```
[Try it online!](https://tio.run/##yygtzv7//9G0Tbk@6VW6fv///48207HUMTXQMTXUMTXSMTfSsTDUsTDWsTTQsTSKBQA "Husk – Try It Online")
### Explanation
```
▲mLgz-N
z N zip input and infinite list [1..]
- with '-'
g group adjacent equal values
mL map length
▲ maximum
```
[Answer]
## Java
```
public static int getConsecutiveCount(int[] A) {
int r = 1, t = 1;
boolean c = false;
for (int i = 0; i < A.length; i++) {
if (i + 1 < A.length) {
if (A[i + 1] - A[i] == 1) {
t++;
c = true;
} else {
c = false;
}
} else {
c = false;
}
if (t > r && !c) {
r = t;
t = 1;
}
}
return r;
}
```
[Answer]
## Just for fun, CJam, 24 bytes
```
l~]M\{:H(=+H}*;0a/:,$W=)
```
I know this is not valid as the language did not exist at the time of asking the question, but I thought I will give it a try.
**How it works:**
```
l~]M\ "Read the input, convert to array, put an empty array M before it";
{ }* "For each pair of the array, run the code block";
:H( "Assign the second number from the pair to H and decrement it";
=+ "Check if it is equal to previous number and put result in M";
H "Put back the second number so as to be used in next iteration":
;0a "Drop the trailing last number and put [0] on stack";
/ "Split M on [0]";
:, "For each split element, replace it with its length";
$W= "Sort the final array and take its last element";
) "Increment this highest element from the array";
```
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# Perl
```
my @o = (1,4,4,6,7,45,46,47,48,98);
sub r{
$c=1;
$l=pop@_;
$m=1;
while($n=pop@_){
if($l-$n==1){++$c;$m=$c if $c>$m}
else{$c=1}
$l=$n
}
$m
}
print "MAX: " . r(@o);
```
**Output:**
MAX: 4
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 bytes
```
äa è_¥1ÃÄ
```
[Try it online!](https://tio.run/##y0osKPn///CSRIXDK@IPLTU83Hy45f//aDMdBUsdBVMDIDYEYiMdBXMgtgCyLYyBUkaxAA "Japt – Try It Online")
[Answer]
# [Julia 0.6](http://julialang.org/), 55 bytes
```
a->((d=diff(a))[d.!=1]=x=0;maximum(x=(x+y)y for y=d)+1)
```
[Try it online!](https://tio.run/##LY5BasMwAATvecX0JhG1SLJsSy3KR4wPAsWgErtBJGC/3nVKYQ/Dzh72@3krqdsnInt6vwiRYy7TJJKUQ/54i2aMa9Rfc1rL/JzFGsV63uTG9FPZYpZnI/cXp1opC2IwNNgjjkbjPC7Qa/oWr8fhc1QMHYFW0xpaS2/xBt8QNMH@L4LCKKyiUThFp/CK/mXcX3cYM8oT3GtZHrdFHH9rlfJ0XfL@Cw "Julia 0.6 – Try It Online")
Going for \$ O(n) \$,
### 82 bytes
```
a->(l=m=0;i=1;while i<length(a);a[i]==a[i+1]-1 ? l+=1 : l=1;l>m&&(m=l);i+=1;end;m)
```
[Try it online!](https://tio.run/##LY7BasMwGIPvfQqdik1d8O84iV3P3YMEHwxLVpc/3ggtffzMGwOhgz6BdH9yycO@IGLP56vguEYdSqTwuhWeUd54rp@Pm8gy5KmkGJufKJ0J7@BTJFzArc3X9XgUa2QZSkvDXD/CKvfla0PeNpQKMRE6mCaLTsM6WI9RY@zhdJouSWEa4NFr9ITeYDRwBNfBa3jz3/AKpGAUOgWrMCg4hfGX2L@sEUryAHxvpT64ikW0fSkP7dD@Aw "Julia 0.6 – Try It Online")
which ungolfed is:
```
function f(a)
l = m = 0
i = 1
while i < length(a)
a[i] == a[i+1]-1 ? l+=1 : l=1
if l > m
m = l
end
i += 1
end
return m
end
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
í- ò¦ mÊn
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=7S0g8qYgbcpu&input=WzYgOSA1MCA1MSA1MiA3MiA4MSA4MyA5MCA5Ml0)
[Answer]
# [Factor](https://factorcode.org/), 45 bytes
```
[ [ - -1 = ] monotonic-split longest length ]
```
[Try it online!](https://tio.run/##PY@7asMwAEX3fMX5AQdZD0tuKXQLWbqUTiGDMaor4kiupA6l9Ntd46Fw4Q6HC@e@D2NNeX17Pb@cHrgP9YObz9HPlGUOtYY4He8ppppiGCn@88vH0ReW7Gv9XnKIlcfD4YcWiVJojTF0HdbiHL2gd/zuXCG3aJRAO3SPFViDEzvv6DEC02IkVuJanNr3cuPrhQsNTcsTV/6Fml2SOcXJl619nLYD17Xm8MyxMM5@yOsf "Factor – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 30 bytes
```
x=scan();max(rle(x-seq(!x))$l)
```
[Try it online!](https://tio.run/##VY3BCsIwEETvfsUKHrKwQm2SJkX6MSVEFGulrUKK@O1xCgXpYWCZnTcz5nCN4R7H5vLuw@v27NXMnym0/d/gOadmsRSfH21SYxdVOk5xUPvEfOg4f3driwrqJFQKaS1kjJC1QlUl5JyQ90J1AXnmLYBwuQiARsAgaGpAuB0KfLEBUIenxdOCtVhzkMft9bpQMucf "R – Try It Online")
Approach boringly copied from other answers, but different from (and slightly shorter than) [JayCe's earlier R answer](https://codegolf.stackexchange.com/a/169761/95126).
] |
[Question]
[
# Challenge
**In this challenge**, all numbers are in \$\mathbb{N}\_0\$.
Create a function or program that, when given a number \$N\$ and a tuple of \$k\$ numbers \$(n\_i)\$ (all ≤ \$N\$), returns the number of ways \$N\$ can be written as a sum of \$k\$ integers (\$x\_1 + x\_2 + ... + x\_k\$) such that \$n\_i \le x\_i \le N\$.
The input format is not fixed. You can read and parse strings, take two parameters as int and int[], etc.
This is a variation of the classical **Integer Partition** problem.
# Test Cases
\$N=4, n=(0, 0, 2) \implies 6\$ `(2+0+2, 1+1+2, 0+2+2, 1+0+3, 0+1+3, 0+0+4)`
\$N=121, n=(7, 16, 21, 36, 21, 20) \implies 1\$ `(7+16+21+36+21+20)`
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest byte count for each language wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
rŒp§ċ
```
A dyadic Link accepting the lower bound tuple on the left and the total on the right which yields the count.
**[Try it online!](https://tio.run/##y0rNyan8/7/o6KSCQ8uPdP///z/aQEcBiIxi/5sAAA "Jelly – Try It Online")**
### How?
```
rŒp§ċ - Link: T, N e.g. [2,1,3], 5
r - inclusive range [[2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
Œp - Cartesian product [[2,1,1],[2,1,2],[2,1,3],[2,1,4],[2,1,5],[2,2,1],...,[5,5,4],[5,5,5]]
§ - sums [ 4, 5, 6, 7, 8, 5, ..., 14, 15]
ċ - count (Ns) 2
```
[Answer]
# [Haskell](https://www.haskell.org/), 35 bytes
```
n%(x:t)=sum$map(%t)[0..n-x]
n%_=0^n
```
[Try it online!](https://tio.run/##HcRBCoAgEADAe6/YQwsFW6wWBYEvEQsPQVEukQb93qA5zObjsZ5nzoLVO6XaxCeUwV8Vptpy20rzukJwMTxLDn4XMHDduySwPVomJu0IlFZoR1IDaUXdv2bnIH8 "Haskell – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~9~~ 7 bytes
*Edit: -2 bytes thanks to [user](https://codegolf.stackexchange.com/users/95792/user)*
```
#¹mΣΠm…
```
[Try it online!](https://tio.run/##yygtzv7/X/nQztxzi88tyH3UsOz///8m/6MNdAx0jGIB "Husk – Try It Online")
```
#¹ # number of times that arg 1 appears in the list of
mΣ # sums of
Π # cartesian product of
m # mapping
… # range up to arg 1
# for each element of arg 2
```
[Answer]
# Python 3.8+, 62 bytes
```
import math
f=lambda S,N:math.comb(S-sum(N)+len(N)-1,len(N)-1)
```
The result can be found using the formula:
$$R = \binom{N-(\Sigma x\_i)+k-1}{k-1}$$
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~62~~ 51 bytes
```
->n,k{[*1..n-k.sum+z=k.size-1].combination(z).size}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ7s6WstQTy9PN1uvuDRXu8oWSGdWpeoaxuol5@cmZeYllmTm52lUaYKFa/8XKKRFm@hEG@gY6BjFxnKBuIZGhjrR5jqGZjpAhjGYNDKIjf0PAA "Ruby – Try It Online")
[Answer]
# JavaScript (ES6), 65 bytes
Expects `(n)(list)`. Uses the [formula provided by the OP](https://codegolf.stackexchange.com/a/219572/58563).
```
n=>a=>(n-=eval(a.join`-1+`),g=k=>!k||g(--k)*(k-n)/~k)(a.length-1)
```
[Try it online!](https://tio.run/##VcqxDsIgEIDh3bdwu1OuApo6wYsYk5JKsYUcxjadGl8diZvLv3z/5FY39@/xtRDnhy@DKWysMxaYjF9dAtdMeeSO1LFDEUw0dh@3LQBRxANEYjx9ItYteQ7LkxSWPvOck29SDjDABeEmhRT6jrj7J6VVxatQrdBKnH/Vsn7lCw "JavaScript (Node.js) – Try It Online")
### How?
The expression `eval(a.join('-1+'))` subtracts 1 from all entries in `a[]` except the last one and sums everything. For instance:
```
[ 2, 3, 4 ] --> "2-1+3-1+4" --> 7
```
So, this is equivalent to: $$\sum\_{i=1}^{k} x\_i-k+1$$
We could also use `eval(a.join('+~-'))` which subtracts 1 from all entries but the first one, leading to the same result.
The helper function `g` computes the combination.
[Answer]
# [R](https://www.r-project.org/), 46 bytes
**(using n\_choose\_k)**
```
function(x,y)choose(x-sum(y)+(z=sum(y|1)-1),z)
```
[Try it online!](https://tio.run/##K/qfV5qblFoUn58WX55YWWz7P600L7kkMz9Po0KnUjM5Iz@/OFWjQre4NFejUlNbo8oWzKox1NQ11NSp0kTTrmGik6xhoGOgY6Sp@R8A "R – Try It Online")
# [R](https://www.r-project.org/), 58 bytes
**(by enumeration)**
```
function(x,y)sum(rowSums(z<-expand.grid(Map(`:`,y,x)))==x)
```
[Try it online!](https://tio.run/##Xcy7DYAgEADQde6S0xhjZWQEKwcQBDEUfAISweWx9w3wYnPZHmfcvd4fURNrOjt5G@@gUMWULUT/bNkmeJfuLEE41V/RKFhFAD5zqlQQkbGCvwomkjDQQCNi@wA "R – Try It Online")
[Answer]
# [Julia 0.6](http://julialang.org/), 38 bytes
port of [xnor's answer](https://codegolf.stackexchange.com/a/219567/98541)
```
n>N=n==[]?0^N:sum([n[2:end]].>0:N-n[])
```
[Try it online!](https://tio.run/##yyrNyUw0@/8/z87PNs/WNjrW3iDOz6q4NFcjOi/ayCo1LyU2Vs/OwMpPNy86VvN/QVFmXklOnka0gY6BjlGsnYkmF1zIXMfQTMfIUMcYTBoZxNoZGhlq/gcA "Julia 0.6 – Try It Online")
### alternative answer, 38 bytes too
```
!N=0^N;!(N,x,t...)=sum(.!(0:N-x,t...))
```
[Try it online!](https://tio.run/##yyrNyUw0@/9f0c/WIM7PWlHDT6dCp0RPT0/Ttrg0V0NPUcPAyk8XKqT5P8/OzxakJg/E5SooyswrycnTiDbQMdAxirUzQRIy1zE00zEy1DEGk0YGsXaGRoaa/wE "Julia 0.6 – Try It Online")
a few more bytes with julia 1.0+
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 bytes
```
.c+-hAQsHJtlHJ
```
[Try it online!](https://tio.run/##K6gsyfj/Xy9ZWzfDMbDYw6skx8Pr/38TnWgDHQMdo1gA "Pyth – Try It Online")
Translation of [zdimension](https://codegolf.stackexchange.com/users/25314/zdimension)['s Python 3 answer](https://codegolf.stackexchange.com/questions/219564/constrained-integer-partition/219572#219572).
# 14 bytes
```
/sMsM*F}RGeAQG
```
[Try it online!](https://tio.run/##K6gsyfj/X7/Yt9hXy602yD3VMdD9/38TnWgDHQMdo1gA "Pyth – Try It Online")
Translation of [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)['s Jelly answer](https://codegolf.stackexchange.com/questions/219564/constrained-integer-partition/219566#219566).
[Answer]
# JavaScript (ES2020), 59 bytes
```
f=(n,[h,...t],s=0)=>eval('for(;n>=h;)s+=f(n-h++,t)')??!n&!h
```
```
f=(n,[h,...t],s=0)=>eval('for(;n>=h;)s+=f(n-h++,t)')??!n&!h
console.log(f(4, [0,0,2]));
console.log(f(121, [7,16,21,36,21,20]));
```
Firefox 72+, Chrome 80+, IE no. TIO currently out of date.
Simple brute force, literally.
* `eval()` return *completion value* of given statement(s).
+ Completion value of `for` statement is completion value of its execute body in last iteration.
+ Completion value of assignment is the value assigned.
+ In case the control flow does not goes into for loop due to the looping condition, `for` statement has no completion value.
+ As the result, `eval(for(;n>=h;)...)` returns the value of `s` (an integer) if once `n>=h`, and return `undefined` if `n>=h` never happened.
* `??` is nullish coalescing operator which is introduced in ES2020.
+ If left side of `??` is null or undefined, it equals to right side. Otherwise, it returns left side (short circuit evaluation). (Similar as what `??` in C# do.)
+ If `n>=h` is falsy, it may due to `n<h` or `h` is undefined.
+ We found a valid integer partition as long as `n == 0` and `h` is undefined (undefined value of `h` means the array is empty.).
+ `!n&!h` check both `n` and `h` are falsy. As `n` may only be integers, it would be `0`. `h` may be integers or undefined. But if `h === 0`, `n >= h` is true, the `??` operator short circuit current expression. As the result, we know `h` is undefined.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
≔…¹LηζI÷Π⁺ζ⁻θΣηΠζ
```
[Try it online!](https://tio.run/##NYu7CgIxEAB7vyLlBlY4xe4q0UZQCFoeV4RcSAJxD/O4Ij@/msJuBmaM18msOjKfcw6O4KnJWTiguFtyxYOXEkWT406lQAUuOhe4UbmGLSwWVFqXagqoWDM0FI9AP/igeNV3X/v8b1rXkXk64TTggMd55v0Wvw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Based on the OP's formula.
```
≔…¹Lηζ
```
Get the exclusive range from `1` to `k`.
```
I÷Π⁺ζ⁻θΣηΠζ
```
Subtract the sum of `xᵢ` from `N`, add it element-wise to the the range, take the product, and divide by the product of the range. This is equivalent to calculating the number of combinations.
] |
[Question]
[
**This question already has answers here**:
[Maximum sub-array](/questions/138697/maximum-sub-array)
(26 answers)
Closed last year.
Let's say you are given an integer array. Create a function to determine the largest sum of any array's adjacent subarrays. For instance, the contiguous subarray with the largest sum is `[4, -1, 2, 1]` in the array `[-2, 1, -3, 4, -1, 2, 1, -5, 4]`.
You can employ a variant of Kadane's algorithm to resolve this issue. The steps are as follows:
1. Set `max_so_far` and `max_ending_here`, two variables, to the first array element.
2. From the second element all the way to the end, traverse the array.
3. Update the `max_ending_here` variable for each element by either adding the current element to it or setting it to the current element if it is larger than the sum of the previous elements.
4. If the `max_ending_here` variable is larger than the `max_so_far` variable, update it.
5. The `max_so_far` variable holds the largest sum of any contiguous subarray after traversing the entire array.
The steps are optional to perform if you may like. The best one which wins is the shortest in length!
# Leaderboard
```
var QUESTION_ID=257808,OVERRIDE_USER=116868;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} /* font fix */ body {font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;} /* #language-list x-pos fix */ #answer-list {margin-right: 200px;}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# Vyxal `G`, 3 bytes
```
ÞSṠ
```
This is my first Vyxal answer but I'm already outgolfing TheThonnu lol
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJHIiwiIiwiw55T4bmgIiwiIiwiWy0yLCAxLCAtMywgNCwgLTEsIDIsIDEsIC01LCA0XSJd)
```
ÞSṠ
ÞS : Sublists
Ṡ : Vectorized sum (sum each)
: -G: Max
```
[Answer]
# [Python](https://www.python.org), 69 bytes
```
lambda x:max(sum(x[a:b])for a in range(len(x))for b in range(len(x)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3XXMSc5NSEhUqrHITKzSKS3M1KqITrZJiNdPyixQSFTLzFIoS89JTNXJS8zQqNMGiSRiimlDDVAuKMvNKNNI0og11jHSMdXSNdQxiNTW54MK6hrEwxQsWQGgA)
# [Python](https://www.python.org), 74 bytes
Outputs the list
```
lambda x:max((x[a:b]for a in range(len(x))for b in range(len(x))),key=sum)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3vXISc5NSEhUqrHITKzQ0KqITrZJi0_KLFBIVMvMUihLz0lM1clLzNCo0NUGiSRiimjrZqZW2xaW5mlATVQuKMvNKNNI0og11jHSMdXSNdQxiNTW54MK6hkAuRPGCBRAaAA)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 9 bytes
Anonymous tacit prefix function.
```
⌈/∘∊⍋+/¨⊂
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1FPh/6jjhmPOroe9XZr6x9a8air6X/ao7YJj3r7HnU1P@pd86h3y6H1xo/aJj7qmxoc5AwkQzw8g4Fq@qZ6Bfv7qUfrGukoGOoo6BrrKJgAKSATKmAKFIhVBwA "APL (Dyalog Unicode) – Try It Online")
`⊂` on the entire input:
`+/¨` sum sub-sequences of each of the following lengths:
`⍋` the grade (permutation that would sort, but the order doesn't matter; we just need all the indices as lengths)
`∘∊` **e**nlist (flatten), and then:
`⌈/` find the maximum (lit. maximum reduction)
---
For reference, Kadane's algorithm can be [found on APLcart](https://aplcart.info?q=kadane), but is much longer:
```
{s←0 ⋄ ⌈/{s⊢←0⌈s+⍵}¨⍵}
```
This sets the maximum sum with `s←0` then, for each element `{`…`}¨⍵` we update the sum `s⊢←` with the maximum of zero and `0⌈` the sum plus that element `s+⍵`. Finally, we find the maximum `⌈/`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 bytes
```
►ΣQ
```
[Try it online!](https://tio.run/##yygtzv7//9G0XecWB/7//z9a10jHUEfXWMdER9dQB8w21TGJBQA "Husk – Try It Online")
```
► # maximum by
Σ # sum
# of
Q # all contiguous subarrays
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 9 bytes
```
Lʀ:Ẋƛ?$i∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJHIiwiIiwiTMqAOuG6isabPyRp4oiRIiwiIiwiWy0yLCAxLCAtMywgNCwgLTEsIDIsIDEsIC01LCA0XSJd)
#### Explanation
```
Lʀ:Ẋƛ?$i∑ # Implicit input
Lʀ # Length range
:Ẋ # Cartesian product with itself
ƛ # Map:
?$i # Slice input
∑ # Sum
# G flag gets maximum
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
sᶠ+ᵐ⌉
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/jhtgXaD7dOeNTT@f9/dLyRjoKhjkK8sY6CCZACMqECpkCB2P9RAA "Brachylog – Try It Online")
Please note that the negative symbol for negative numbers is the underscore `_` in Brachylog, not the standard dash `-`.
### Explanation
```
sᶠ Find all sublists of consecutive elements
+ᵐ Map sum
⌉ Get the max
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Because the required ouput is not clear from the spec, the first solution below outputs the sub-array, while the second outputs its sum.
```
ã ñx
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=4yDxeA&input=Wy0yLCAxLCAtMywgNCwgLTEsIDIsIDEsIC01LCA0XQ)
```
ãx Í
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=43ggzQ&input=Wy0yLCAxLCAtMywgNCwgLTEsIDIsIDEsIC01LCA0XQ)
```
ã ñx :Implicit input of array
ã :Sub-arrays
ñ :Sort by
x : Sum
:Implicit output of last element
```
```
ãx Í :Implicit input of array
ã :Sub-arrays
x :Reduced by addition
Í :Sort
:Implicit output of last element
```
[Answer]
# Excel, ~~70~~ 74 bytes
```
=LET(b,SEQUENCE(ROWS(A1#)),MAX(SUBTOTAL(9,OFFSET(A1#,b-1,,TRANSPOSE(b)))))
```
where `A1#` is a *vertical* spill range comprising the values from the array.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 65 bytes
```
f=lambda a,x=0,y=0:max(x-y,len(a)and f(a[1:],x:=x+a[0],min(x,y)))
```
[Try it online!](https://tio.run/##LYpBCsMgEAC/sseVrGCSForgS8TDllQaiFsJOayvNx56mmGY2q7vT9ZXPXvP4eDy3hiYNDhqwfnCimobHR9BNiwbZOQ4@0Tqg04cXaKyCyo1Y0yv5y4XZox2IZgJ7ErwGBj6D88R0jhv "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes
```
Max[Tr/@Subsequences@#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zexIjqkSN8huDSpOLWwNDUvObXYQTlW7X9AUWZeiUO6g0K1rpGOgqGOgq6xjoIJkAIyoQKmQIHa//8B "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python](https://www.python.org), 41 bytes
```
lambda a,x=0:max(x:=max(c+x,0)for c in a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3NXMSc5NSEhUSdSpsDaxyEys0KqxsQVSydoWOgWZafpFCskJmnkKiJlSDf0FRZl6JRppGtKGOkY6xjq6xjkGspiYXXFjXSEfBUEcBKK5gAqSATKiAKVAAVaUhkAsxdsECCA0A)
Version that can handle empty input:
# [Python](https://www.python.org), 43 bytes
```
lambda a,x=0:max(x:=c+x*(x>0)for c in[0]+a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3tXMSc5NSEhUSdSpsDaxyEys0Kqxsk7UrtDQq7Aw00_KLFJIVMvOiDWK1EzWhWmIKijLzSjTSNKINdYx0jHV0jXUMYjU1ueDCukY6CoY6CkBxBRMgBWRCBUyBAqgqDVG4QA7EjgULIDQA)
[Answer]
# JavaScript (ES6), 41 bytes
Like several other answers, this assumes that the empty array is a valid subarray.
```
a=>Math.max(...a.map(v=>s=v>-s&&s+v,s=0))
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1s43sSRDLzexQkNPTy8RyCjQKLO1K7Yts9MtVlMr1i7TKbY10NT8n5yfV5yfk6qXk5@ukaYRrWuko2Coo6BrrKNgAqSATKiAKVAgFqgeAA "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŒOZ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6CT/qP//o410FAx1FHSNdRRMgBSQCRUwBQrEAgA "05AB1E – Try It Online")
TIL that there's a "sublists" command in both 05AB1E and Vyxal!
```
Œ # Sublists
O # Sum each
Z # Maximum
```
[Answer]
# JavaScript, 42 bytes
```
a=>a.map(s=m=n=>m=m>(s=0<s?n+s:n)?m:s)|m
```
Try it:
```
f=a=>a.map(s=m=n=>m=m>(s=0<s?n+s:n)?m:s)|m
;[
[-2, 1, -3, 4, -1, 2, 1, -5, 4], // 6
[1], // 1
[1, 2, 3, 4, 5, 6, 7], // 28
[-1, -2, -3, -4, -5, -6, -7], // -1
[-3, -2, -1, 0, 1, 2, 3], // 6
].map(a=>console.log(f(a)))
```
## UPD 45 -> 42
Thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) for the [tip](https://codegolf.stackexchange.com/questions/257808/find-the-largest-sum-of-any-contiguous-subarray-of-the-array/257814?noredirect=1#comment569763_257814) to reduce bytes count
[Answer]
# [R](https://www.r-project.org), ~~46~~ 45 bytes
*Edit: -1 byte thanks to pajonk*
```
\(s){b=0;for(x in s)b=max(F<-max(x,F+x),b);b}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHG3MSK-OLSpMSiosRKICPXdmlpSZquxU3dGI1izeokWwPrtPwijQqFzDyFYs0kW6ByDTcbXRBVoeOmXaGpk6RpnVQL1WSEbppGsoaukY6CoY6CrrGOggmQAjKhAqZAAU1NiM4FCyA0AA)
Outputs the sum of the subarray with the largest sum (as requested in the second sentence of the question)
---
# [R](https://www.r-project.org), 59 bytes
```
\(s,`+`=sum,b={}){for(x in s)if(+(F=c(F[+F>0],x))>+b)b=F;b}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHG3MSK-OLSpMSiosRKICPXdmlpSZquxU3rGI1inQTtBFugmE6SbXWtZnVafpFGhUJmnkKxZmaahraGm22yhlu0tpudQaxOhaamnXaSZpKtm3VSLdQII3SzNZI1dI10FAx1FHSNdRRMgBSQCRUwBQpoakJ0LlgAoQE)
Outputs the subarray with the largest sum (as in the example in the third sentence of the question).
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 6 bytes
```
eSsM.:
```
[Try it online!](https://tio.run/##K6gsyfj/PzW42FfP6v//aF0jHQVDHQVdYx0FEyAFZEIFTIECsQA "Pyth – Try It Online")
### Explanation
```
eSsM.:Q # implicitly add Q
# implicitly assign Q = eval(input())
.:Q # list all subarrays of Q
sM # map to their sums
eS # sort and take the last value (the largest sum)
```
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), 48 bytes
```
00i:?v/::0$0)?$~-{20.
+i}-1/\&~$?(@:$@:&:
;n~~/
```
[Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiMDBpOj92Lzo6MCQwKT8kfi17MjAuXG4raX0tMS9cXCZ+JD8oQDokQDomOlxuIDtufn4vIiwiaW5wdXQiOiI3IDEgLTIgMSAyIDMgLTMgMiIsInN0YWNrIjoiIiwic3RhY2tfZm9ybWF0IjoibnVtYmVycyIsImlucHV0X2Zvcm1hdCI6Im51bWJlcnMifQ==)
I thought Kadane's algorithm would always be longer but for ><>, which lacks normal array manipulation, it's actually shorter.
Takes input as a length-prefixed array.
[](https://i.stack.imgur.com/DTQfx.png)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
I⌈Eθ⌈Eθ↨¹✂θκ⊕μ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexIjO3NBdIF2gU6iigcZ0Si1M1DHUUgnMyk1NBAtk6Cp55yUWpual5JakpGrmaMGD9/390tK6RjgJQta6xjoIJkAIyoQKmQIHY2P@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input array
E Map over elements
θ Input array
E Map over elements
✂θκ⊕μ Inclusive slice of elements
↨¹ Take the sum
⌈ Take the maximum
⌈ Take the maximum
I Cast to string
Implicitly print
```
(Using "base 1" to take the sum as that returns `0` for empty lists.)
] |
[Question]
[
This is my first time here at Code Golf SE so feel free to add your input/advice/suggestions to improve my post if necessary. The week after my computer science exam, the solutions were publicly published. One problem had a 45 line example solution but my solution was only 18 lines, (which I was very proud of), but I bet you guys here at code golf SE can do better.
**Here are the requirements:**
* Takes two inputs, string1 and string2.
* Delete the first occurrence of string2 found in the string1.
* Add string2 in reverse order to the beginning of string1, and
* Add string2 in reverse order to the end of the string1.
* If string2 does not occur in string1, do not modify string1.
* Output the modified string1
**Example:**
Input:
```
batman
bat
thebatman
bat
batman
cat
```
Output:
```
tabmantab
tabthemantab
batman
```
**Note:**
The problem was intended to handle basic inputs. Assume all expected inputs are restricted to characters A-Z, numbers, or other special characters visible on your keyboard. It does not need to handle tabs or newlines.
Submissions with shortest byte counts in each language win.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 16 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ÄE┘¢8·╦Ωb•∩
```
[Run and debug it online](https://staxlang.xyz/#p=8e45d99b38facbea6207ef&i=%22batman%22+%22bat%22%0A%22batman%22+%22robin%22%0A%22thebatman%22+%22bat%22%0A%22thebatman%22+%22.*%22&a=1&m=2)
The corresponding ascii representation of the same program is this.
```
Y#xyz|eyr|Sx?
```
This fixes the bugs in original version. It uses conditionals and stuff.
```
Y Save 2nd input in y. Now the two inputs are x and y.
# Occurrences of y in x. (a)
xyz x, y, ""
|e replace first occurrence
yr|S surround with y reversed. (b)
x first input. (c)
? a ? b : c
```
The result is printed implicitly.
[Answer]
# [Python](https://docs.python.org/2/), 55 bytes
```
lambda s,t:s.replace(t,'',1).join(2*[t[::-1]*(t in s)])
```
[Try it online!](https://tio.run/##XctBDsIgEIXhvadgx9BgE7rE9CRtF6A0HUMHAmOMp8e6MDHuXr68P794SzS0dZxbdLu/OVE129qXkKO7BmAtpTaqvyckGLqJJ2vPZumABZKoalHtuWEMwtgjHJHyg0FdckFiscJhqoH0jndHUovPkur0KyV5pK/9Hd8 "Python 2 – Try It Online")
Using `join` to get the `a+b+a` pattern. This lets us write expression for `a` only once while still using a `lambda`. Compare:
**[Python 2](https://docs.python.org/2/), 57 bytes**
```
def f(s,t):r=t[::-1]*(t in s);print r+s.replace(t,'',1)+r
```
[Try it online!](https://tio.run/##XYxBCsIwEEX3nmJ2M7FRiMuUnkRcpJrSgToNkxHx9FERQdw9Hu//8rB5lUNrlzzBRNWbizrYMcZdOG3JgAWq64uyGGhX95rLks6ZzCP64Dpt95mXDCG@tgNLuRm5/vPUCMdk1yTo4U3oNr9G15Hl6/7CJw "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 36 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Look ma, no regex!
Anonymous infix lambda, taking string2 as left argument and string1 as right argument. Assumes `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems.
```
{r,⍵[(⍳≢⍵)~(f⍳1)+⍳≢⍺],r←⌽⍺/⍨∨/f←⍺⍷⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OAZHWRzqPerdEaj3o3P@pcBGRq1mmkATmGmtowoV2xOkVAlY969gLZ@o96VzzqWKEP0gvkPurdDtRT@/@/elJiibpCmoJ6bmKeOhecB6QxBDDEgDyoGAA "APL (Dyalog Unicode) – Try It Online")
`{`…`}` "dfn"; `⍺` is left argument, `⍵` is right argument; e.g. `"bat"` and `"manbatmanbat"`:
`⍺⍷⍵` find where string2 begins in string1; `[0,0,0,1,0,0,0,0,0,1,0,0]`
`f←` assign to `f` (**f**ind)
`∨/` OR-reduction (does string2 occur at all?); `1`
`⍺/⍨` use that to compress string2 (`""` if not found); `"bat"`
`⌽` reverse that; `"tab"`
`r←` assign to `r` (**r**everse)
`⍵[`…`],` prepend string2 indexed by the following indices:
`≢⍵` the length of string2; `3`
`⍳` the indices of that; `[0,1,2]`
`(`…`)+` add the following to that:
`f⍳1` index of first 1 in `f`; `3`
Now we have the indices to be removed; `[3,4,5]`
`(`…`)~` the following indices except those indices:
`≢⍵` length of string2; `12`
`⍳` the indices of that; `[0,1,2,3,4,5,6,7,8,9,10,11]`
Now we have the indices we want to keep; `[0,1,2,6,7,8,9,10,11]`
This gives us the remaining parts of string1 followed by a reversed string2; `"manmanbattab"`
`r,` prepend `r` to that; `"tabmanmanbattab"`
[Answer]
# C#, 148 bytes
```
using System.Linq;using System.Text.RegularExpressions;(a,b)=>a==(a=new Regex(Regex.Escape(b)).Replace(a,"",1))?a:(b=string.Concat(b.Reverse()))+a+b
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~39~~ ~~38~~ 35 bytes
-3 bytes due to a neat trick by Asone Tuhid
```
->x,y{(x[y]&&="")?y.reverse!+x+y:x}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf165Cp7JaoyK6MlZNzVZJSdO@Uq8otSy1qDhVUbtCu9KqovZ/QWlJsUJatFJSYkluYp6SDoihFMsFEy7JSMUhAxdOBgn/BwA "Ruby – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 56 bytes
```
lambda s,t:[s,t[::-1]+s.replace(t,'',1)+t[::-1]][t in s]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFYp8QqGkhEW1npGsZqF@sVpRbkJCanapToqKvrGGpqQ2Vio0sUMvMUimP/FxRl5pVopGmoJyWW5CbmqesogFjqmppcWGSK8pMy89Dl0DX@BwA "Python 3 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 35 bytes
```
^(.*)¶(.*?)\1(.*)
¶$^$1$2$3$^$1
0A`
```
[Try it online!](https://tio.run/##K0otycxLNPz/P05DT0vz0DYgaa8ZYwjicB3aphKnYqhipGIMorkMHBP@/09KLOEqyUgFUrmJeQA "Retina – Try It Online") `$^` is new in Retina 1 and reverses its argument which is just what's needed here.
[Answer]
# Java 8, ~~126~~ 113 bytes
```
(a,b)->a.equals(a=a.replaceFirst(java.util.regex.Pattern.quote(b),""))?a:(b=new StringBuffer(b).reverse()+"")+a+b
```
[Port of *@lee*'s C# .NET answer](https://codegolf.stackexchange.com/a/157376/52210), so make sure to upvote him!
[Try it online.](https://tio.run/##lY/BasMwDIbveQqRk01SP8BKNthht5XBjmMH2VU7p4mTxnK2MfLsmQKG3cYGwkjW/0ufWpxxN4wU2uNldR3GCI/ow1cB4APTdEJHcNhKgGeefDiDUznBOidW70WwFPJERvYODhCggVVhbfXuFg1dE3ZRYYNmorGToQ9@iqxaWW8S@06@z/RhnpBlaTDXNDApq@uy1PoOb5RtAr1ngvt0OtEkXTHNNEVSuhJdhZVdNxCJMdlOMDLNPPgj9HJWJn95RZ1P@oxMvRkSm1E63AUVjFOlRe4xlDVsmSDsf1XzG/3P8KN2fxrvo5FAwxTZbDaTTUuxrN8)
**Old 126 byte answer:**
```
a->b->{Object r=new StringBuffer(b).reverse();return a.contains(b)?r+a.replaceFirst(java.util.regex.Pattern.quote(b),"")+r:a;}
```
[Try it online.](https://tio.run/##nY/BasMwDIbvfQqRk00bP8CyZrBDb2OHHscOsqtszhzH2HJGKXn2zKNhjF02BgJJ/P@H9Pc4YT0G8v3pbTEOU4IHtP6yAUiMbA30xaEyW6e67A3b0avDOtweOVr/svuT59rbFgzsYcG61XV7edQ9GYa49/S@Ou5z11EUWqpIE8VEQjaROEcPqMzoubyXinwXt1gswaGhg42Jhd5VldzGG2zmpSkBSoWsXcmwRplGe4Kh8OJ66ukZ5WdSgOM5MQ1qzKxCUdh5YRSG4M6i0sgD@kp@2yspm185fqX/oj8588XNm3n5AA)
**Explanation:**
```
a->b->{ // Method with two String parameters and String return-type
Object r=new StringBuffer(b).reverse();
// 2nd input reversed
return a.contains(b)? // If the 1st input contains the 2nd:
r // Output the reversed 2nd input
+a.replaceFirst(java.util.regex.Pattern.quote(b),"")
// Removed the first occurrence of the 2nd in the 1st input,
// escaping any characters like dots, pluses, etc.
// and then append that to the result
+r // appended with the reversed 2nd input again
: // Else:
a;} // Simply output the 1st input
```
[Answer]
# [Perl 5](https://www.perl.org/) + `-pl`, ~~38~~ 34 bytes
```
$s=<>;s/\Q$s//&&s/^|$/reverse$s/ge
```
*-4 thanks to Ton Hospel*
[Try it online!](https://tio.run/##K0gtyjH9/1@l2NbGzrpYPyZQpVhfX02tWD@uRkW/KLUstag4FSiUnvr/f1JiSW5iHheQ@pdfUJKZn1f8X7cgBwA "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
DIåiIõ.;IR.ø
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fxfPw0kzPw1v1rD2D9A7v@P8/KbEEiHIT87iAFAA "05AB1E – Try It Online")
**Explanation**
```
D # duplicate 1st input
Iåi # if 2nd input is in first input
Iõ.; # replace the first occurrence of 2nd input with the empty string
IR.ø # surround with 2nd input reversed
```
[Answer]
# Javascript (ES6), ~~69~~ ~~65~~ 64 bytes
```
x=>y=>x.match(y)?(k=[...y].reverse().join``)+x.replace(y,'')+k:x
```
[Try it online!](https://tio.run/##hcpNCsIwEIbhvRfJDNU5gJB6EBE6jVP7kyYlCSU5fZRuBDfuPt7nm3nnaMK0pYvzT6mDrlm3RbeZVk5mhII3WPSdiMqDguwSogDS7CfXddjkT9ssG4FyVgqb5Zqr8S56K2T9CwZQPaeVncJjKcTTj6dR/l2@bg6vbw "JavaScript (Node.js) – Try It Online")
[Answer]
# [K4](http://kx.com/download/), 36 bytes
**Solution:**
```
{$[#s:x ss y;r,(x_/(#y)#*s),r:|y;x]}
```
**Examples:**
```
q)k){$[#s:x ss y;r,x_/(#y)#*s,r:|y;x]}["batman";"bat"]
"tabman"
q)k){$[#s:x ss y;r,(x_/(#y)#*s),r:|y;x]}["batman";"bat"]
"tabmantab"
q)k){$[#s:x ss y;r,(x_/(#y)#*s),r:|y;x]}["thebatman";"bat"]
"tabthemantab"
q)k){$[#s:x ss y;r,(x_/(#y)#*s),r:|y;x]}["batman";"cat"]
"batman"
q)k){$[#s:x ss y;r,(x_/(#y)#*s),r:|y;x]}["batbatbat";"bat"]
"tabbatbattab
```
**Explanation:**
If string 2 (y) is found in string 1 (x) then drop first indices of first occurrence.
```
{$[#s:x ss y;r,(x_/(#y)#*s),r:|y;x]} / the solution
{ } / lambda with implicit x,y
$[ ; ; ] / $[condition;true;false]
x ss y / string-search for y in x
s: / save result as s
# / count length
|y / reverse (|) y
r: / save as r
, / join with
( ) / do this together
*s / first (*) s
# / take
(#y) / length of y
x_/ / drop (_) over (/)
r, / join with r
x / (else) return x
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
œṣ⁹Ḣ;jɗ⁹ṭṚ};Ṛ}ðẇ@¡
```
[Try it online!](https://tio.run/##y0rNyan8///o5Ic7Fz9q3PlwxyLrrJPTQaydax/unFVrDSIOb3i4q93h0ML///8nJiWnJKf@T04FAA "Jelly – Try It Online")
Full program.
[Answer]
## Javascript 85 bytes
```
a=>b=>a.includes(b)?[...b].reverse().join``+a.replace(b,'')+[...b].reverse().join``:a
```
If someone knows how to avoid using `split('').reverse().join('')` for reversing string, please let me know
```
f=a=>b=>a.includes(b)?[...b].reverse().join``+a.replace(b,'')+[...b].reverse().join``:a
console.log(f('batman')('bat'))
console.log(f('thebatman')('bat'))
console.log(f('batman')('cat'))
```
[Answer]
# Javascript, ES6 - 73 bytes
```
b=x=>y=>{v=[...y].reverse().join``;u=x.replace(y,"");alert(u==x?x:v+u+v)}
```
[Answer]
# Python 2, 62 Bytes
```
def f(a,b):b*=b in a;a=a.replace(b,"",1);b=b[::-1];print b+a+b
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 20 bytes
```
œṣµḢ;j⁹$ɓ;;@ðU}
ç¹w?
```
[Try it online!](https://tio.run/##ATkAxv9qZWxsef//xZPhuaPCteG4ojtq4oG5JMmTOztAw7BVfQrDp8K5dz////9hYmlqY2lqZGVpamb/aWo "Jelly – Try It Online")
---
Ouch! Why can other languages get 11~12 bytes? Am I doing something wrong?
And *finally*, I *think* I know how chain separators works...
```
œṣµḢ;j⁹$ɓ;;@ðU} Helper link (dyadic). General structure:
œṣ <dyad> - given x and y, split x at
sublists equal to y.
Ḣ;j⁹$ <monad> - given x, join with y except at
first index.
;;@ <dyad> - given x and y, return y+x+y.
Note that this link is flipped.
U} <dyad> - reverse right argument.
ç¹w? Main link. Evaluate the last link if the second input is a substring
of the first input, otherwise - apply identity (do nothing).
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 73 bytes
```
S =INPUT
T =INPUT
S T = :F(O)
T =REVERSE(T)
S =T S T
O OUTPUT =S
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/nzNYwdbTLyA0hIszBM4KVgCyOa3cNPw1wcJBrmGuQcGuGiGaIDnbEAWgAi5/Tv/QEKByBdtgLlc/l///kxJLchPzuJITSwA "SNOBOL4 (CSNOBOL4) – Try It Online")
What's a regular expression?
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 85 bytes
```
{for(;x++<N=split($0,a,"");)p=a[x]p;$0=NR%2?L=$0:sub($0,"",L)?p L p:L}!(NR%2)
```
[Try it online!](https://tio.run/##SyzP/v@/usBWSck6Lb9Io8LWwLpCW9vGz7a4ICezREPFQCdRR0lJ01qzwDYxuiK2wFrFwNYvSNXI3sdWxcCquDQJpERJScdH075AwUehwMqnVlEDpEDz//@kxJLcxDwuIMVVkpGKxIMykxNLAA "AWK – Try It Online")
Input is: primary string on odd-lines, replacement on even lines. Replacement is case sensitive.
[Answer]
# Python 3, 58 bytes
```
def f(a,b):z=(b in a)*b[::-1];return z+a.replace(b,'',1)+z
```
] |
[Question]
[
**This question already has answers here**:
[Code that will only execute once](/questions/28672/code-that-will-only-execute-once)
(82 answers)
Closed 6 years ago.
# Challenge
Create a program that, when run, changes the contents of the source file. This means that you can delete/add/change characters in the source file, but you can't delete the (source) file itself (deletion is when the source file does not exist after the program is run).
In the case of pre-compiled languages such as C++, your program can change the source file only, such that when compiled, either fails or does not produce the same result.
Your program must not return any errors, such as access violations (e.g. opening a file that is already open).
* This is an advantage to pre-compiled languages, as the source file does not have to be in use to run it.
## Input
You may take an optional path to the source file, but nothing more.
## Output
You may output anything.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer wins!
[Answer]
# [Zsh](https://www.zsh.org/), 3 bytes
```
>$0
```
Truncates the script to length **0**.
Unlike its Bash counterpart, this handles filenames that contain whitespace.
[Try it online!](https://tio.run/nexus/zsh#@5@XmJtqq55bqVBQlJ9elJirV5yhzpWanJGvoJunoG6nYqCuYKegAlIFEXVydfMPcuWqqEhR0E1XMIRKlScr6CZD2VXFGcgaHN1CXIPwqP//HwA "Zsh – TIO Nexus")
[Answer]
# C, ~~35~~ 25 bytes
```
f(){fopen(__FILE__,"w");}
```
Just empties the source file.
[Online test suite on TIO](https://tio.run/nexus/bash#S04sUbBTSM5PSdVLVrCxUXD1d/ufpqFZnZZfkJqnER/v5unjGh@vo1SupGld@z83MTMPJKkB5HABlXJxpSZn5Cs4pablF6UqpFakJpeWZObnWXElA42FGApWwcWVnpwMs0U3H6ySS08fTEGMcEwrSS3CbsJ/AA)
[Answer]
# Octave, 27 bytes
```
fwrite(fopen('f','w'),'')
```
**Explanation:**
`fopen('f','w')` opens the file `f` (itself) with writing privileges (the file has no file extension (it's not `f.m`)). `fwrite` writes an empty string `''` to that file, overwriting the content of it.
Run it from the GUI / CLI using: `run f`. PS!
Note: You should close the file again afterwards using `fclose(3)`, but this is not necessary for it to work.
[Answer]
# Python, ~~18~~ 17 bytes
```
open(input(),"w")
```
-1 thanks to @EriktheOutgolfer
Opens itself in write mode, deleting everything in the file.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
“µ÷ⱮÑċẊṚ⁾Ṁ)ɦGl»ŒV
```
Never fails, but produces different outputs.
Takes relative path through STDIN (unquoted).
Explanation:
```
“µ÷ⱮÑċẊṚ⁾Ṁ)ɦGl»ŒV Main link. Arguments: 0
“µ÷ⱮÑċẊṚ⁾Ṁ)ɦGl» Literal "open(input(),'w')"
ŒV Python eval and listify
```
Open a file in write mode in Python overwrites it.
[Answer]
# PHP, 18
```
fopen(__FILE__,w);
```
From the [manual](http://php.net/manual/en/function.fopen.php):
```
Open for writing only; place the file pointer at the beginning
of the file and truncate the file to zero length. If the file
does not exist, attempt to create it.
```
I guess that should also work in most other languages
[Answer]
# [Ruby](https://www.ruby-lang.org/), 10 bytes
```
open $0,?w
```
Not very original, almost everybody is doing it the same way nowadays.
[Answer]
## C, 27 bytes
```
f(){system("cd>"__FILE__);}
```
Overwrites the contents of the file wtih the current directory.
[Answer]
# Batch, ~~7~~ 4 bytes
Thanks to Neil for saving 3 bytes
```
.>%0
```
`>` overwrites the contents of a file and `%0` returns the current batch file's path.
Result: Blank batch file.
[Answer]
# Node.js, 47 bytes
```
require('fs').writeFileSync(process.argv[1],'')
```
Erase the content of the source file
] |
[Question]
[
So I was playing around with my compose key, and found some cool things, one of them being that by pressing `compose + ( + alphanumeric + )`, you get that character inside a bubble, like so: `ⓐ`.
Your task in this challenge is simple, to convert ordinary text to bubble letter text.
Here are the ascii chars, the bubble characters and their Unicode code points:
```
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
⓪①②③④⑤⑥⑦⑧⑨ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ
9450 9312 9313 9314 9315 9316 9317 9318 9319 9320 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423
```
Your input will contain only printable ascii characters, and if a character cannot be bubbleified, leave it as is.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins!
*Note: This is not isomorphic to my earlier challenge about small-caps conversion since unlike small-caps, bubble letters are in a mostly contiguous segment of code-points, allowing for more interesting approaches.*
[Answer]
# [Retina](http://github.com/mbuettner/retina), 20 bytes
```
T`Lld`Ⓐ-⓪①-⑨
```
[Try it online!](http://retina.tryitonline.net/#code=VGBMbGRg4pK2LeKTquKRoC3ikag&input=ICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX4)
### How it works
There's a gap between the code points of **(0)** and **(1)**, but – fortunately – the character right after **(z)** is **(0)**. This way, we can transliterate the character from concatenated ranges **A-Za-z0-9** to the characters of the concatenated ranges **(A)-(0)(1)-(9)**.
The rest is straightforward: `T` activates transliteration mode, `Lld` yields all uppercase ASCII letters (`L`), all lowercase ASCII letters (`l`) and all digits (`d`), and `Ⓐ-⓪①-⑨` the corresponding bubble characters.
[Answer]
# Python 3, 146 bytes
```
for p in list(input()):
t=0
if p.isdigit():t=9263
if p=='0':t=9402
if p.isalpha():
t=9327
if p.upper()==p:t=9333
print(end=chr(ord(p)+t))
```
This might be able to be made shorter, any help would be appreciated.
Try it on repl.it, [here.](https://repl.it/DYYt/3)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 19 bytes
Uses [CP-1252](http://www.cp1252.com) encoding.
```
žKš52Ý86+8Ý«9312+ç‡
```
[Try it online!](http://05ab1e.tryitonline.net/#code=xb5LxaE1MsOdODYrOMOdwqs5MzEyK8On4oCh&input=VGhpcyBpUyB0M3g3IQ)
**Explanation**
```
žK # Push the string "a-zA-Z0-9"
š # switch case: "A-Za-z0-9"
52Ý # push range [0 ... 52]
86+ # add 86: [86 ... 138]
8Ý« # concatenate with range [0 ... 8]: [86 ... 138, 0 ... 8]
9312+ # add 9312: [9398 ... 9450, 9312 ... 9320]
ç # convert to char: ['Ⓐ', ... 'Ⓩ', 'ⓐ', ..., 'ⓩ', '⓪', ..., '⑨']
‡ # transliterate alphabet to bubble alphabet
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ ~~22~~ 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“2Ỵf“2Ṇ3‘r/9.ȷ_ỌFØB,y
```
[Try it online!](http://jelly.tryitonline.net/#code=4oCcMuG7tGbigJwy4bmGM-KAmHIvOS7It1_hu4xGw5hCLHk&input=&args=ICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX4)
### How it works
```
“2Ỵf“2Ṇ3‘r/9.ȷ_FỌØB,y Main link. Argument: s (string)
“2Ỵf“2Ṇ3‘ Yield [[50, 188, 102], [50, 180, 51]].
r/ Reduce by range.
This yields [[50], [188, ..., 180], [102, ..., 51].
9.ȷ_ Subtract these integers from 9500.
This yields [[9450], [9312, ..., 9320], [9398, ..., 9449]].
Ọ Unordinal; convert the resulting code points to characters.
F Flatten the resulting array of strings.
This yields the bubbles of
[0, ..., 9, A, ..., Z, a, ..., z].
ØB, Pair "0...9A...Za...z" with the generated string.
y Transliterate.
```
[Answer]
# Bash on OSX, 27
* 3 bytes saved thanks to @Dennis.
```
tr A-Za-z0-9 Ⓐ-⓪①-⑨
```
I/O via STDIN/STDOUT. The OSX `tr` apparently handles these unicode characters whereas the GNU coreutils `tr` does not.
[Answer]
# Ruby, ~~38~~ [34](https://mothereff.in/byte-counter#%24%5f.tr!%22A-Za-z0-9%22%2C%22%E2%92%B6-%E2%93%AA%E2%91%A0-%E2%91%A8%22) + 1 = 35 bytes
+1 byte for `-p` flag. Takes input on STDIN.
-3 bytes thanks to Dennis.
```
$_.tr!"A-Za-z0-9","Ⓐ-⓪①-⑨"
```
See it on eval.in: <https://eval.in/636978>
[Answer]
# Perl, 27 bytes
Includes +1 for `-p`
Give input on STDIN, uses the Dennis transliteration order. The only thing interesting about this solution is the lack of the final `;` (needs a recent enough perl)
```
#!/usr/bin/perl -p
y;A-Za-z0-9;Ⓐ-⓪①-⑨
```
[Answer]
# JavaScript (ES6) 93 ~~104~~
**Edit** 11 bytes saved thx @Neil again
Having to use `String.fromCharCode`, javascript is doomed...
```
s=>s.replace(/[^\W_]/g,c=>String.fromCharCode(9388+parseInt(c,36)+(-c?-77:62-c||c>'Z'&&26)))
```
**Test**
```
f=
s=>s.replace(/[^\W_]/g,c=>String.fromCharCode(9388+parseInt(c,36)+(-c?-77:62-c||c>'Z'&&26)))
function update() {
O.textContent=f(I.value)
}
update()
```
```
<input id=I oninput="update()" value='Hello world!'>
<pre id=O></pre>
```
[Answer]
# R, 140 bytes
A bit late to the party again.
```
x=utf8ToInt(scan(,""));a=x<58&x>48;b=x>95&x<123;c=x>64&x<91;d=x==48;x[a]=x[a]+9263;x[b]=x[b]+9327;x[c]=x[c]+9333;x[d]=x[d]+9402;intToUtf8(x)
```
**Ungolfed**
```
x=utf8ToInt(scan(,""));
a=x<58&x>48;
b=x>95&x<123;
c=x>64&x<91;
d=x==48;
x[a]=x[a]+9263;
x[b]=x[b]+9327;
x[c]=x[c]+9333;
x[d]=x[d]+9402;
intToUtf8(x)
```
Will add an explanation and try to golf this tomorrow again.
[Answer]
# R, ~~124~~ 91 characters
Takes input from stdin. Probably can be golfed with some cleverness. Saved some bytes by replacing the list of bubble characters with UTF code points.
```
chartr(paste(c(1:9,LETTERS,letters,0),collapse=""),intToUtf8(c(0:8,86:138)+9312),scan(,""))
```
[Answer]
# Groovy (135 Bytes)
```
b=(9312..9320)+(9424..9450)+(9398..9423);r=('0'..'9')+('a'..'z')+('A'..'Z');x={s->s.collect{(x=r.indexOf(it))>=0?(char)b[x]:it}}.join()
```
<https://groovyconsole.appspot.com/script/5189010641125376>
[Answer]
# Java, 747 bytes
```
String a(String...A){for(int i=1;i<A.length-1;i+=2)A[0]=A[0].replace(A[i],A[i+1]);return A[0];}String b(String B){return a(B,"0","⓪","1","①","2","②","3","③","4","④","5","⑤","6","⑥","7","⑦","8","⑧","9","⑨","a","ⓐ","b","ⓑ","c","ⓒ","d","ⓓ","e","ⓔ","f","ⓕ","g","ⓖ","h","ⓗ","i","ⓘ","j","ⓙ","k","ⓚ","l","ⓛ","m","ⓜ","n","ⓝ","o","ⓞ","p","ⓟ","q","ⓠ","r","ⓡ","s","ⓢ","t","ⓣ","u","ⓤ","v","ⓥ","w","ⓦ","x","ⓧ","y","ⓨ","z","ⓩ","A","Ⓐ","B","Ⓑ","C","Ⓒ","D","Ⓓ","E","Ⓔ","F","Ⓕ","G","Ⓖ","H","Ⓗ","I","Ⓘ","J","Ⓙ","K","Ⓚ","L","Ⓛ","M","Ⓜ","N","Ⓝ","O","Ⓞ","P","Ⓟ","Q","Ⓠ","R","Ⓡ","S","Ⓢ","T","Ⓣ","U","Ⓤ","V","Ⓥ","W","Ⓦ","X","Ⓧ","Y","Ⓨ","Z","Ⓩ");}
```
If the source code may only contain ASCII characters, then replace every non-ASCII character with `\uINSERTRESPECTIVECODEPOINTINHEXADECIMALHERE`. Doing so results in a 933-byte program.
[Answer]
# Python 3, 107.
This borrows part of its algorithm from [nedla2004's answer](https://codegolf.stackexchange.com/a/92748/38770).
```
lambda x:list(map(lambda p:chr(ord(p)+(((9327+6*('@'<p<'[')*p.isalpha(),9402)[p<'1'],9263)['0'<p<':'])),x))
```
[Answer]
# Java 10, ~~152~~ ~~151~~ 142 bytes
```
s->{var r=new StringBuffer();s.chars().forEach(c->r.appendCodePoint(c+(c>47&c<58?c<49?9402:9263:c>64&c<91?9333:c>96&c<123?9327:0)));return r;}
```
-1 byte thanks to *@ceilingcat*.
**Explanation:**
[Try it online.](https://tio.run/##VZDbUsIwEIbvfYqIio1IhbYUSqFVEM8gimfwENIUyiGtSQsi1lfHMHDjzO7FNzs7@/07QBOUHjjDBR4hzkEdeXS@AYBHQ8JchAloLBGAVsg82qtErksYwNIKAYemmMaiRfEQhR4GDUBBGSx42ppPEAOsTMn037oETS7jPmJcgrLrsxrCfQmnLSajICDUqfoOafrCQMIpCVtaPolLuYKNS5phG1pGKRqKrhaxpWtiYGRtQ1WXaOgCs4oqWMkXMxBCk5EwYhQwM16YK8cg6o6E41p14nsOGIvI6zztVwTXcWc8JGPZj0I5YEsVKmMpATY7ia3tneSuBPdS@2n5ICPuaTk9XzCKZqls2YdHlepx7eT07Pzi8qreuG7e3Lbu7h8en55f2p3O69v7B@pih7i9vjcYjsbUDz4ZD6PJ9Gv2Pf@JfxNw/dB48Qc)
**Explanation:**
```
s->{ // Method with String parameter and StringBuffer return-type
var r=new StringBuffer(); // Resulting StringBuffer
s.chars().forEach(c-> // Loop over the chars of the input as integers
r.appendCodePoint( // Convert int to char, and append it to the result:
c // The current character as integer
+(c>47&c<58? // If it's a digit:
c<49? // If it's 0 (special case)
9402 // Add 9402 to convert it
: // Else (1-9)
9263 // Add 9263 to convert it
:c>64&c<91? // Else-if it's an uppercase letter:
9333 // Add 9333 to convert it
:c>96&c<123? // Else-if it's a lowercase letter:
9327 // Add 9327 to convert it
: // Else:
0))); // Leave it as is by adding 0
return r;} // Return the resulting StringBuffer
```
[Answer]
# [Python 3](https://docs.python.org/3/), 103 bytes
Might save a byte on shuffling added and subtracted numbers
```
lambda i:i.translate({x:x+(9333-6*(x>96)-70*(x<58)+139*(x<49))*chr(x).isalnum()for x in range(48,123)})
```
[Try it online!](https://tio.run/##NYzRCoIwGEbve4qFZf@vTayZuqigeo0IplkN1hKdsIiefVnU3TkfnK9@mOtdM6fWB6fErTgJIpcyMo3QrRKmgqdd2hA4Y4ymAdgNT5FmcU@rRY7hjPEPJhwxKK8NWIxkK5TuboDne0MskZr0X5cKknw6mzN8oZO67gxZk4koSrrd7Wm/J4s0yzmNqe8FCP5o6B3HOBnUjdSGwLfAv6mfo3sD "Python 3 – Try It Online")
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/19727/edit).
Closed 7 years ago.
[Improve this question](/posts/19727/edit)
Your goal is to write a hash function, that accepts morse code character and returns a hash code that you get to define.
### You can be sure, passed string will be:
* One of the Latin characters (A-Z) encoded into Morse Code using `.` and `-`, or
* One of the digits (0-9) encoded into Morse Code using `.` and `-`, or
* Empty
So, there could be any of 37 different strings passed to you.
### Requirements:
* The returned number should be unique for all 37 strings
* For empty string the function should return 0
### Score:
1. Initially, you have a 100 points.
2. You will lose
* 1 point for every bitwise operator in your code
* 2 points for every addition (subtraction) operator in your code (operators in loop clauses (e.g. inside `for(;;)` or `while()` don't count)
* 4 points for every multiplication (division, modulo, etc) operator
* 6 points for every if (else) statement
* 8 points for every loop statement (including loops in the called functions. You can presume that any called function has no more than one loop)
* 12 points for every conditional operator
* 200 points for using a built-in hash function
### Bonuses:
* If all numbers, produced by your function are less than `N`, you will get additional `137 - N` points (of course, if the bonus is positive)
### Winners:
Score matters, but be creative!
---
### Example:
## Score: 100 - 5\*2 - 3\*4 - 8 + (137 - 134) = 73
I know, this could be improved by removing modulo operator and make a loop starts from 1, but this is just an example
```
#include <iostream>
#include <map>
#include <set>
std::size_t hash_morse(const std::string& s)
{
std::size_t ans = 0;
for(std::size_t i = 0; i < s.size(); ++i)
{
ans += (s.at(i) - '-' + 2) * (i + 1) * (i + 1);
}
return ans % 134;
}
int main()
{
std::map<std::string, char> m
{
{"", 0},
{".-", 'A'},
{"-...", 'B'},
{"-.-.", 'C'},
{"-..", 'D'},
{".", 'E'},
{"..-.", 'F'},
{"--.", 'G'},
{"....", 'H'},
{"..", 'I'},
{".---", 'J'},
{"-.-", 'K'},
{".-..", 'L'},
{"--", 'M'},
{"-.", 'N'},
{"---", 'O'},
{".--.", 'P'},
{"--.-", 'Q'},
{".-.", 'R'},
{"...", 'S'},
{"-", 'T'},
{"..-", 'U'},
{"...-", 'V'},
{".--", 'W'},
{"-..-", 'X'},
{"-.--", 'Y'},
{"--..", 'Z'},
{".----", '1'},
{"..---", '2'},
{"...--", '3'},
{"....-", '4'},
{".....", '5'},
{"-....", '6'},
{"--...", '7'},
{"---..", '8'},
{"----.", '9'},
{"-----", '0'}
};
std::map<std::size_t, std::string> hashes;
for(const auto& elem: m)
{
auto hash = hash_morse(elem.first);
if(hashes.find(hash) != hashes.end())
{
std::cout << "Collision" << std::endl;
std::cout << '"' << hashes[hash] << R"(" and ")" << elem.first << '"' << std::endl;
std::cout << "Hash: " << hash << std::endl;
std::cout << std::endl;
}
else
{
hashes[hash] = elem.first;
}
}
std::cout << "Total amount of collisions: " << (m.size() - hashes.size()) << std::endl;
return 0;
}
```
[Answer]
## Arguably perfect score
There are some possible loopholes in the scoring system. In particular,
>
> 8 points for every loop statement (including loops in the called functions. You can presume that any called function has no more than one loop)
>
>
>
According to PHP documentation,
>
> **array()** is a language construct used to represent literal arrays, and not a regular function.
>
>
>
So it's arguable that
```
$hash = array(
'' => 0,
'.-' => -1,
...
);
return $hash[$morse];
```
contains no called functions and should score a perfect 100 + (137 - 1) = 236 points.
[Answer]
# bash — 236 points
I understand there's some griping over using negative numbers, so have revised:
```
echo '' '[morse code]'|grep -o ' [\.-]*'|tr -t '.-' '19'|sed 's/ /0./g'|awk '{printf("%g\n",$0)}'
```
Will generate codes from 0.1 to 0.99999 for valid Morse Code and 0 for empty input.
e.g.
```
$ echo '' '. - .. -- .-.- -.-. ..... -----'|grep -o ' [\.-]*'|tr -t '.-' '19'|sed 's/ /0./g'|awk '{printf("%g\n",$0)}'
0.1
0.9
0.11
0.99
0.1919
0.9191
0.11111
0.99999
```
As per specs, empty input `''` returns 0:
```
$ echo '' ''|grep -o ' [\.-]*'|tr -t '.-' '19'|sed 's/ /0./g'|awk '{printf("%g\n",$0)}'
0
```
**Points Calculation**
Starting with 100, deduct:
* 1 point for every bitwise operator - none
* 2 points for every addition (subtraction) operator - none
* 4 points for every multiplication (division, modulo, etc) operator - none
* 6 points for every if (else) statement - none
* 8 points for every loop statement - none
* 12 points for every conditional operator - none
* 200 points for using a built-in hash function - none
So still have 100 points.
**Bonus Calculation**
All numbers are less than 1 (largest is 0.99999 for ----- a.k.a. Morse Code Zero), so the bonus is 137 - 1 or 136 points, again for a total of 236 points.
---
# bash — 236 points
```
echo '' '[morse code]'|grep -o ' [\.-]*'|tr -t '.-' '67'|sed 's/ /-0/g'|awk '{printf("%d\n",$0)}'
```
Will generate codes from -77777 to -6 for valid Morse Code and 0 for empty input.
e.g.
```
$ echo '' '. - ..--. -..- .--- .. -..-. .. -----'|grep -o ' [\.-]*'|tr -t '.-' '67'|sed 's/ /-0/g'|awk '{printf("%d\n",$0)}'
-6
-7
-66776
-7667
-6777
-66
-76676
-66
-77777
```
As per specs, empty input `''` returns 0:
```
$ echo '' ''|grep -o ' [\.-]*'|tr -t '.-' '67'|sed 's/ /-0/g'|awk '{printf("%d\n",$0)}'
0
```
**Points Calculation**
Starting with 100, deduct:
* 1 point for every bitwise operator - none
* 2 points for every addition (subtraction) operator - none
* 4 points for every multiplication (division, modulo, etc) operator - none
* 6 points for every if (else) statement - none
* 8 points for every loop statement - none
* 12 points for every conditional operator - none
* 200 points for using a built-in hash function - none
So still have 100 points.
**Bonus Calculation**
All numbers are less than 1 (largest is 0 for an empty input), so the bonus is 137 - 1 or 136 points for a total of 236 points.
[Answer]
# Ruby 100 - 6 (one if/else) - 2 (one subtraction) = 92 + 75 (largest value is 62) = 167 (159 if string find/replace counts as looping)
```
code = gets.chomp
if code.empty?
p -1
else
p ('1' + code.gsub(/./){|c| c.ord - 45 }).to_i(2)
end
```
Simply does a find/replace on the string, but replaces each character with its ASCII code - 45. This turns `-` into `0` and `.` into `1`. It then prepends a `1` (to handle leading zeroes) and parses this string as binary.
[Answer]
## GolfScript (143 164 192 points)
I was slightly wrong about the relationship with the other Morse question: this one is much much simpler.
```
2base
```
scores 100 - 8 points for an implicit loop = 92, with no bonus.
```
2base 87%
```
scores 100 - 4 points for a modulo - 8 points for an implicit loop + (137 - 82) bonus points for a total of 143 points.
That has two parameters which can potentially be optimised to improve the bonus. The best I've found so far is
```
46base 62%
```
for `N=61` and a total of 164 points.
But it's possible to do even better.
```
2base MAGIC_STRING=
```
scores 100 - 8 points for an implicit loop + (137 - 37) bonus points for a total of 192 points, where MAGIC\_STRING is a suitable 1427-character string literal:
```
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1E\x0F\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x17\x18\v\x13\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x19\x11\x15\x0E!\x1C\x1F\x1D\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\e$#\r\"\f\x14\x1A\x00\x16\x00\x10 \x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\n\x00\t\x00\x00\x00\b\x00\x00\x00\x00\x00\x00\x00\a\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x04\x00\x05\x06"
```
[Answer]
## Perl - score = 165
```
print~-oct'0b1'.<>=~y/.-/10/r
```
Re-interpretting morse as binary, with a `1` prepended.
**Score break-down**
* **-1** - bitwise inversion (`~`)
* **-8** - loop statement (`y`)
* **+74** - the largest value produced is *62*
[Answer]
# Scheme:
Initial 100 points and it has no reduction since there was no mention of `switch/case` there and the `/` is part of the number not an operator..
The output is a rational number between 0 and 1. Extra score would be 137-1=136.
Total score: 236
```
(define (hash-morse-code code)
(case code
(("") 0)
((".-") 1)
(("-...") 1/2)
(("-.-.") 1/3)
(("-..") 1/4)
((".") 1/5)
(("..-.") 1/6)
(("--.") 1/7)
(("....") 1/8)
(("..") 1/9)
((".---") 1/10)
(("-.-") 1/11)
((".-..") 1/12)
(("--") 1/13)
(("-.") 1/14)
(("---") 1/15)
((".--.") 1/16)
(("--.-") 1/17)
((".-.") 1/18)
(("...") 1/19)
(("-") 1/20)
(("..-") 1/21)
(("...-") 1/22)
((".--") 1/23)
(("-..-") 1/24)
(("-.--") 1/25)
(("--..") 1/26)
((".----") 1/27)
(("..---") 1/28)
(("...--") 1/29)
(("....-") 1/30)
((".....") 1/31)
(("-....") 1/31)
(("--...") 1/32)
(("---..") 1/33)
(("----.") 1/34)
(("-----") 1/35)))
(hash-morse-code "...") => 1/19
```
[Answer]
# Java - 100 + 136 = 236
```
public static int hashMorse(String toHash) {
switch (toHash){
case ".-": //A
return -36;
case "-...": //B
return -35;
case "-.-.": //C
return -34;
case "-..": //D
return -33;
case ".": //E
return -32;
case "..-.": //F
return -31;
case "--.": //G
return -30;
case "....": //H
return -29;
case "..": //I
return -28;
case ".---": //J
return -27;
case "-.-": //K
return -26;
case ".-..": //L
return -25;
case "--": //M
return -24;
case "-.": //N
return -23;
case "---": //O
return -22;
case ".--.": //P
return -21;
case "--.-": //Q
return -20;
case ".-.": //R
return -19;
case "...": //S
return -18;
case "-": //T
return -17;
case "..-": //U
return -16;
case "...-": //V
return -15;
case ".--": //W
return -14;
case "-..-": //X
return -13;
case "-.--": //Y
return -12;
case "--..": //Z
return -11;
case ".----": //1
return -10;
case "..---": //2
return -9;
case "...--": //3
return -8;
case "....-": //4
return -7;
case ".....": //5
return -6;
case "-....": //6
return -5;
case "--...": //7
return -4;
case "---..": //8
return -3;
case "----.": //9
return -2;
case "-----": //0
return -1;
default:
return 0;
}
}
```
All those `-` signs don't count; they stand for the literal number. If you want to count them, then I'll just replace all those numbers with the binary literal (no minuses then).
Switches are free according to the question; neither an if nor an else. If you don't want switches, I'll just replace it with a `HashMap`
The largest possible number is `0`, for the empty string or invalid strings.
---
Don't like negative numbers? This works (score of 200):
```
public static int hashMorse(String toHash) {
switch (toHash){
case ".-": //A
return 36;
case "-...": //B
return 35;
case "-.-.": //C
return 34;
case "-..": //D
return 33;
case ".": //E
return 32;
case "..-.": //F
return 31;
case "--.": //G
return 30;
case "....": //H
return 29;
case "..": //I
return 28;
case ".---": //J
return 27;
case "-.-": //K
return 26;
case ".-..": //L
return 25;
case "--": //M
return 24;
case "-.": //N
return 23;
case "---": //O
return 22;
case ".--.": //P
return 21;
case "--.-": //Q
return 20;
case ".-.": //R
return 19;
case "...": //S
return 18;
case "-": //T
return 17;
case "..-": //U
return 16;
case "...-": //V
return 15;
case ".--": //W
return 14;
case "-..-": //X
return 13;
case "-.--": //Y
return 12;
case "--..": //Z
return 11;
case ".----": //1
return 10;
case "..---": //2
return 9;
case "...--": //3
return 8;
case "....-": //4
return 7;
case ".....": //5
return 6;
case "-....": //6
return 5;
case "--...": //7
return 4;
case "---..": //8
return 3;
case "----.": //9
return 2;
case "-----": //0
return 1;
default:
return 0;
}
}
```
[Answer]
# Java - 100 + 136 = 236
```
public static int hash(String morse){
try{
morse.charAt(0);
}catch (IndexOutOfBoundsException e){
return 0;
}
return Integer.parseInt("-1" + help(morse), 2);
}
private static String help(String morse) {
int a = 0;
try {
a = (int) morse.charAt(0);
} catch (IndexOutOfBoundsException e) {
return "";
}
a = Integer.parseInt(String.valueOf(Integer.toString(a, 2).charAt(4)));
return a + help(morse.substring(1));
}
```
call `hash(someString);` to use this function. I'm working on a loop-free alternative to `Integer.parseInt` and `Integer.toString`.
I avoided the penalties by:
* using recursion instead of loops
* using Strings and String concatenation instead of numbers
So I get 100 + 136 as the largest output is 0.
[Answer]
# JavaScript, 217pts
```
replace : Minus 8pts (loop)
replace : Minus 8pts (loop)
/ 100000: Minus 4pts (division)
```
100 - 20 = 80 + (137 - 0) = 217
```
function mc2(s) {
return s.replace(/\./g,'1').replace(/-/g,'2') / 100000
}
```
# JavaScript 199pts
```
for : Minus 8pts (loop)
r+= : Minus 2pts (addition)
(c>'-') : Minus 6pts (if)
c>'-' : Minus 12pts (conditional operator)
:2 : Minus 6pts (else)
r/ : Minus 4pts (division)
```
100-38pts = 62pts + (137-0) = 199pts
```
function mc2(s) {
r=''
for(i=0;(c=s[i]);i++)r+=(c>'-')?1:2
return r/100000
}
```
[Answer]
## Python, 236
Now, Peter Taylor claims to have a perfect score. But really, he's only got 200. Negative numbers all being smaller than zero, my bonus is `137-1`, so this solution is 36 points better.
```
F = lambda s:-eval(''.join([
'12340'[s[0:].find('-')],'12340'[s[0:].find('.')],
'12340'[s[1:].find('-')],'12340'[s[1:].find('.')],
'12340'[s[2:].find('-')],'12340'[s[2:].find('.')],
'12340'[s[3:].find('-')],'12340'[s[3:].find('.')],
'12340'[s[4:].find('-')],'12340'[s[4:].find('.')]]))
```
] |
[Question]
[
**This question already has answers here**:
[Sum of primes between given range](/questions/113/sum-of-primes-between-given-range)
(61 answers)
Closed 6 years ago.
The primorial of a number is the product of all the primes until that number, itself included.
Take a number from `STDIN` as the input and evaluate its primorial, also known as the prime factorial.
Don't use libraries. Shortest code wins.
**Test cases:**
```
1 1
2 2
3 6
4 6
5 30
6 30
7 210
8 210
9 210
10 210
11 2310
12 2310
13 30030
14 30030
15 30030
16 30030
17 510510
18 510510
19 9699690
```
[Answer]
## J, 13 characters
```
*/p:i._1 p:1+
```
Examples:
```
*/p:i._1 p:1+7
210
*/p:i._1 p:1+12
2310
```
[Answer]
## Python 2, 49 bytes
```
P=k=1
exec"P*=P**k%k<1or k;k+=1;"*input()
print P
```
Counts up `k` from 1 to the input, updating the primorial `P` by multiplying `P` by `k` whenever it's prime. Since `P` contains all lower prime factors, a sufficiently high power of `P` will contain `k` as a factor if and only if `k` is non-prime. The power `P**k` suffices, and we check whether `P**k%k<1`, multipling `P` by 1 if so (doing nothing) and by `k` otherwise.
[Answer]
# Mathematica 21
The large Pi represents the product function.
`PrimePi@n` returns the number of primes up to and including n.
`Prime@i` returns the ith prime.

[Answer]
# PARI/GP, 22 bytes
```
prodeuler(x=1,input,x)
```
[Answer]
## Mathematica, 27 chars
```
Times@@Prime@Range@PrimePi@
```
Usage
```
Times@@Prime@Range@PrimePi@100
(*
2305567963945518424753102147331756070
*)
```
[Answer]
### Python, 72 characters
Quickly golfed, I imagine there are better python solutions.
```
n=t=1;exec"t*=(1,n)[all(n%i for i in range(2,n))];n+=1;"*input();print t
```
I used [wikipedia](http://en.wikipedia.org/wiki/Primorial) to verify up to 71
Usage:
```
$ python primorial.py
100
2305567963945518424753102147331756070
$ python primorial.py
101
232862364358497360900063316880507363070
```
[Answer]
## Haskell, 90 chars
```
main=getLine>>= \v->print.product.takeWhile(<=read v)$[n|n<-[2..],all((>0).rem n)[2..n-1]]
```
or (also 90 chars):
```
main=getLine>>=print.product.flip takeWhile [n|n<-[2..],all((>0).rem n)[2..n-1]].(>=).read
```
### Compilation
```
ghc primorial.hs
```
### Usage
```
$ echo "12" | ./primorial
2310
```
or
```
$ ./primorial
12<ENTER>
2310
```
[Answer]
## R - 48
```
x=1:scan();prod(x[rowSums(outer(x,x,`%%`)<1)<3])
```
[Answer]
# MATLAB/Octave, 23 bytes
```
prod(primes(input('')))
```
[Try it online!](https://tio.run/##y08uSSxL/f@/oCg/RaOgKDM3tVgjM6@gtERDXV1TU/P/f3MA)
[Answer]
# C, 125 bytes
```
p(n,x){return x==1?n:n%x?p(n,x-1):1;}
f(n){return n==1?1:p(n,n-1)*f(n-1);}
main(){int n;scanf("%d",&n);printf("%d\n",f(n));}
```
[Answer]
# Casio-Basic, 41 bytes
```
prod(seq(piecewise(isPrime(x),x,1),x,1,n
```
Since the calculator doesn't have a "select" function of any kind, a piecewise/hybrid function is used to return the number if it's prime, otherwise return 1. `seq` does this over a range of integers from 1 to n, and `prod` multiplies the whole list together.
40 bytes for the function, +1 byte to enter `n` in the parameters box.
[Answer]
**Smalltalk**, Squeak 4.x flavour
Let's say we read n from stdin in 38 chars (this kind of requirement is just killing!)
```
n:=FileStream stdin nextLine asNumber.
```
If only product were defined in Collection in base image, this could be as simple as
```
^(0class primesUpTo:n+1)product
```
or:
```
^((2to:n)select:#isPrime)product
```
Unfortunately, we have to code #product by ourself in 48 chars (**86** total).
```
(0class primesUpTo:n+1)inject:1into:[:p :i|p*i]
```
Or if primesUpTo: is considered as a library, we can use isPrime in 62 chars (**100** total)
```
^(1to:n)inject:1into:[:p :i|i isPrime ifTrue:[p*i]ifFalse:[p]]
```
If even isPrime is forbidden we can find by ourselves in 67 chars (**105** total)
```
p:=1. 2to:n do:[:i|((2to:i-1)anySatisfy:[:d|i\\d=0])or:[p:=p*i]].^p
```
Or for the fun, we can use a sieve in 108 chars (**146** total)
```
s:=(p:=y:=1)<<n-2. 2to:n do:[:x|y:=(z:=y)*2+1.(z+1bitAnd:s)=0or:[p:=p*x.s:=z<<(n//x*x+x)//y+z+1bitAnd:s]].^p
```
Explanation of the sieve at <http://smallissimo.blogspot.fr/2011/07/revisiting-sieve-of-erathostenes.html>
Nota: bitAnd: has a short-cut operator & in Pharo 2.0, which would reduce Sieve cost to 94 chars (**132** total)
```
s:=(p:=y:=1)<<n-2. 2to:n do:[:x|y:=(z:=y)*2+1.z+1&s=0or:[p:=p*x.s:=z<<(n//x*x+x)//y+z+1&s]].^p
```
[Answer]
# Haskell, 76 bytes
```
main=interact$ \n->show$product[x|x<-[2..read n],and[x`mod`y>0|y<-[2..x-1]]]
```
Example:
```
$ echo 12 | ./primorial
2310
```
[Answer]
# Java 7, 213 bytes
```
class M{public static void main(String[]a){c(new Long(a[0]));}static void c(long n){long r=1,i=0;for(;++i<=n;r*=p(i)?i:1);System.out.print(r);}static boolean p(long n){int i=2;while(i<n)n=n%i++<1?0:n;return n>1;}}
```
**Ungolfed:**
```
class M{
static void c(long n){
long r = 1,
i = 0;
for (; ++i <= n; r *= p(i) ? i : 1);
System.out.print(r);
}
public static void main(String[] a){
c(new Long(a[0]));
}
static boolean p(long n){
int i = 2;
while(i < n){
n = n % i++ < 1 ? 0 : n;
}
return n > 1;
}
}
```
**Usage:** `java -jar M.jar 17`
**Output:** `510510`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
ÆRP
```
[Try it online!](https://tio.run/##y0rNyan8//9wW1DA////zQE "Jelly – Try It Online")
[Answer]
# [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 6 bytes
```
S²P¬-*
```
## Explained
```
S²P¬-*
S # Produce as stack from 1 to the input.
² - # Filter it by the function provided
P¬ # Is it not a prime?
* # Get the product of the now list of primes.
```
[Try it online!](https://tio.run/##Kyooyk/P0zX6/z/40KaAQ2t0tf7//29oAAA "RProgN 2 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 6 bytes
```
õ fj ×
```
[Try it here](https://ethproductions.github.io/japt/?v=1.4.5&code=9SBmaiDX&input=OA==)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
ÅPP
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cGtAwP//hpYA "05AB1E – Try It Online")
] |
[Question]
[
Your task is given an input string of the full/short name of a CS:GO ([Counter-Strike: Global Offensive](https://en.wikipedia.org/wiki/Counter-Strike:_Global_Offensive), a computer game) rank return an integer from 1-18 representing the rank number. A higher number means you are a higher rank and so "better" at CS:GO.
**Input**
A string representing either the full name or short name of the CS:GO rank. Your code must be able to handle both cases.
**Output**
An integer representing the rank number of the given input. You can output in either 0-indexing or 1-indexing as 0-17 and 1-18 respectively.
**Test cases:**
The test cases use 1 - 18 as the output, just subtract one if you are using 0-indexing. Where SN means short name.
```
Full name SN -> output
Silver I S1 -> 1
Silver II S2 -> 2
Silver III S3 -> 3
Silver IV S4 -> 4
Silver Elite SE -> 5
Silver Elite Master SEM -> 6
Gold Nova I GN1 -> 7
Gold Nova II GN2 -> 8
Gold Nova III GN3 -> 9
Gold Nova Master GNM -> 10
Master Guardian I MG1 -> 11
Master Guardian II MG2 -> 12
Master Guardian Elite MGE -> 13
Distinguished Master Guardian DMG -> 14
Legendary Eagle LE -> 15
Legendary Eagle Master LEM -> 16
Supreme Master First Class SMFC -> 17
Global Elite GE -> 18
```
[Answer]
## Ruby, ~~120~~ ~~111~~ ~~100~~ 99 bytes
```
->x{x.tr!'a-z ','';x.gsub!(/I.*/){$&.sum%18%11};'
'[x.sum%36%20+x.ord%4].ord}
```
Hexdump, since the Stack Exchange software mangles lots of the unprintables in the source code:
```
00000000: 2d3e 787b 782e 7472 2127 612d 7a20 272c ->x{x.tr!'a-z ',
00000010: 2727 3b78 2e67 7375 6221 282f 492e 2a2f '';x.gsub!(/I.*/
00000020: 297b 2426 2e73 756d 2531 3825 3131 7d3b ){$&.sum%18%11};
00000030: 270e 0f0d 0920 2010 0102 0304 0511 0a20 '.... ........
00000040: 1206 200b 0c20 0708 275b 782e 7375 6d25 .. .. ..'[x.sum%
00000050: 3336 2532 302b 782e 6f72 6425 345d 2e6f 36%20+x.ord%4].o
00000060: 7264 7d rd}
```
[Try it online!](https://tio.run/##ZVDbasJAEKX3dlp6@4IRmm5vxiZKKYh90RgE40ugFMSHtVnjQkxkN5FY9dvTrTbUKsxhzjnMzM6sSPrTbFDLim/pLNVjUSC0@IXkiZBqqvsy6RfuSi39oXQ/u7nVZTLSjFfNMBZVcn7xcYJ4ubO7t39wBXh9iKdneHRMuumyrPyimc@PqR4JT6v0ftIii4c89CXWkLg8mDCBLcjJGvuj7zmzAh6zfwIdKmMmwI4CDzvRhKpZa/y/WFe/fauEdkKFx2mourecbWu1RoPLWN2RcDlkHm7UQJv5LPSomKJF/YBt6vx9NxkLNsolNrmQMdYDKiXYQdSnQX6zAa4JbhncCriWCgfsjqFgKpQVHHBsQ8FUsKDh2NC2VDjgOs062BaB1a/rAQ@ZRC/C@dKY4ziJJQ66S6V/DqPRuFdFtWv2DQ "Ruby – Try It Online")
(Note: I can't figure out how to get a carriage return into the "Code" box on TIO, so the TIO version has it replaced with an `X` and hence outputs `88` instead of `13` for MGE.)
Explanation:
```
x.tr!'a-z ',''
```
This deletes all lowercase letters and spaces from the input.
```
x.gsub!(/I.*/){$&.sum%18%11}
```
This searches for an `I` in the string and, if found, replaces it to the end of the string with the result of a black-magic algorithm (found by brute force search) that produces the numeric equivalent of the Roman numeral.
```
'junk'[more junk].ord
```
The first section of junk (and the `ord`) maps the values `[7, 8, 9, 10, 11, 16, 21, 22, 3, 13, 18, 19, 2, 0, 1, 6, 12, 15]` to the range `1..18` by indexing into the string, which contains the appropriate bytes at their corresponding indices.
The second section of junk maps the values `["S1", "S2", "S3", ...]` to the values `[7, 8, 9, ...]`. The formula was produced by a simple brute force search minimizing the maximum value obtained while ensuring that 18 unique values still exist.
[Answer]
# JavaScript (ES6), ~~164~~ ~~150~~ 135 bytes
```
s=>'GE S1|S2|S3|S4|SE|SEMGN1GN2GN3GNMMG1MG2MGEDMGLE LEMSMFC'.search(s[r='replace'](/[a-z ]/g,'')[r]('IV',4)[r](/I+/,a=>a.length))/3||18
```
(Saved a bunch of bytes thanks to @Craig Ayre and @Steve Bennett.)
**Explanation:**
`s[r='replace'](/[a-z ]/g,'')[r]('IV',4)[r](/I+/,a=>a.length)` converts **Full names** to the **SN** equivalents. It doesn't change **SN**s.
We then simply index into the array of **SN**s created by `split`.
**Snippet:**
```
f=
s=>'GE S1|S2|S3|S4|SE|SEMGN1GN2GN3GNMMG1MG2MGEDMGLE LEMSMFC'.search(s[r='replace'](/[a-z ]/g,'')[r]('IV',4)[r](/I+/,a=>a.length))/3||18
console.log(f('Silver I')); // S1 -> 1
console.log(f('Silver II')); // S2 -> 2
console.log(f('Silver III')); // S3 -> 3
console.log(f('Silver IV')); // S4 -> 4
console.log(f('Silver Elite')); // SE -> 5
console.log(f('Silver Elite Master')); // SEM -> 6
console.log(f('Gold Nova I')); // GN1 -> 7
console.log(f('Gold Nova II')); // GN2 -> 8
console.log(f('Gold Nova III')); // GN3 -> 9
console.log(f('Gold Nova Master')); // GNM -> 10
console.log(f('Master Guardian I')); // MG1 -> 11
console.log(f('Master Guardian II')); // MG2 -> 12
console.log(f('Master Guardian Elite')); // MGE -> 13
console.log(f('Distinguished Master Guardian')); // DMG -> 14
console.log(f('Legendary Eagle')); // LE -> 15
console.log(f('Legendary Eagle Master')); // LEM -> 16
console.log(f('Supreme Master First Class')); // SMFC -> 17
console.log(f('Global Elite')); // GE -> 18
console.log(f('S1'));
console.log(f('S2'));
console.log(f('S3'));
console.log(f('S4'));
console.log(f('SE'));
console.log(f('SEM'));
console.log(f('GN1'));
console.log(f('GN2'));
console.log(f('GN3'));
console.log(f('GNM'));
console.log(f('MG1'));
console.log(f('MG2'));
console.log(f('MGE'));
console.log(f('DMG'));
console.log(f('LE'));
console.log(f('LEM'));
console.log(f('SMFC'));
console.log(f('GE'));
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 70 bytes
```
V
3
G.*N.*M|L
55
G.*N
6
M.*G.*E
67
G.*E
99
D
4
E
5
F
88
G
9
\d
$*I
I|M
```
[Try it online!](https://tio.run/##ZZBPa4MwHIbv76fIYYPhoaDWrp5r/CEYL0JPOyzD4AKZjkQLg353F9u69c8p7/MQXt7EqkF3cnp@ofdpjxi0CqpVII4lkuQE2ECsAp84Nq84nWmKDGtwJMix3YKQ4q3BU1CgOIppqrU5KMsK1CGW7CH6B0/xH@1RrxfgRg8KNb9hJqQblPVagHrTsKo/SF9PVXjNs4huxGziK3PpoUrgHBmN0jZadr5NUPhoZx096PNKQRyZdv7/2lG7T9Wwu3vIBKFUreoaaX8Yl61RKPm9WmaV/nn1@G3V16JYrq0b2M5I51CLfAcy/Yc0lwHEfwE "Retina – Try It Online") Works by converting specific upper case letter combos into digits and totalling the digits.
[Answer]
# PHP, 151 Bytes
0-Indexing
Remove all characters that not Uppercase or digit
After that replace the digits with their roman numbers
Search and Output the Key in the Array
```
<?=array_flip([SI,SII,SIII,SIV,SE,SEM,GNI,GNII,GNIII,GNM,MGI,MGII,MGE,DMG,LE,LEM,SMFC,GE])[strtr(preg_replace("#[^C-V\d]#","",$argn),[_,I,II,III,IV])];
```
[Try it online!](https://tio.run/##JY4xC8IwEEb3/ozUIYFzcqy1Q40hYFwCXWIsQWMrFDnOLv76mtTjvTd80@GIy77BEYtNoOFdM7tjVdEc0lgHovDtn9MLubMarF7N6cDKhAF10dl/cg0YpbM5Eo5GwVkmDFhzakFJL9xnppk4Uhx6ijiFe@SsdLd2210fvmTAGKzPCHA9aNCZZOeFr5Z0Pw "PHP – Try It Online")
# PHP, 158 Bytes
0-Indexing
Remove all characters that not Uppercase
After that replace the roman numbers with their digit
Search and Output the Key in the Array
```
<?=array_flip([S1,S2,S3,S4,SE,SEM,GN1,GN2,GN3,GNM,MG1,MG2,MGE,DMG,LE,LEM,SMFC,GE])[preg_replace(["#[^C-V]#","#IV#","#III#","#II#","#I#"],["",4,3,2,1],$argn)];
```
[Try it online!](https://tio.run/##LY6xCoMwGIR3n6IkHRSug9HNWgdrQ6DpEnAJqUixKkgJGQp9evtTe9zHN9xyfvLrsfKTj/Z9GF8lM/PyHsJOsSKqTjSVfQj9p3sus4@tSWEETAaTwzRUDXlLCUFkhIaWKSGIBmctcW2oGkZfasjGJdaHYezC4Jf@McSWcXuvD63jDIyrdpNSf2/izMEyhhwZBFKH39XEFSvlCw "PHP – Try It Online")
# PHP, 295 Bytes
0-Indexing Without Regex
Search and Output the Key of an Array
If more than 4 characters are set in the input take the array with the longer names else take the array with the short names
```
<?=array_flip(explode(_,$argn[4]?strtr("0I_0II_0III_0IV_03_03 4_1I_1II_1III_14_45I_45II_453_Distinguished 45DMG_2_2 4_Supreme 4 First Class_Global 3",["Silver ","Gold Nova ","Legendary Eagle",Elite,Master," Guardian "]):S1_S2_S3_S4_SE_SEM_GN1_GN2_GN3_GNM_MG1_MG2_MGE_DMG_LE_LEM_SMFC_GE))[$argn];
```
[Try it online!](https://tio.run/##TZDNasMwEITveQoherDBB/8olyapD4kjDFEugl6CWVSs2gLVFpIdmqdP1y6FivkGBBp2Vq53z33perd5Ub4bDlTOzusvTYQKk/bkbHyYyNGqEOhuU77h44PyXj3g0xoX6W9nx1ZHkKzxG2vKMPnJRzStIa1XFnuHtEARBlmNWkFjwLb1wmIFnEyYzNDNJvS6JWx7EhxyyDH114r9LwTcjh/KkoImNyqNvWNfmlA@2pZcx7taLhfd6aFV/kEq1VlNk8qaSSe/2yWU8Fn51qiB0CZ@lRnIHGQBEidWKAH8miE5UiACBM@QHKlgqXepUAKkOB@BV3F8W/@h2T3x/AA "PHP – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~51 49 46~~ 45 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Oḅ4%⁽+Þ%63“¬>ṬṿḄḋḷ<¶Ġþṛṫ9ṡt[`3"G£ḳọċ’b59¤i‘:2
```
A monadic link accepting a list of characters and returning an integer.
Result is 0-indexed.
**[Try it online!](https://tio.run/##AXwAg/9qZWxsef//T@G4hTQl4oG9K8OeJTYz4oCcwqw@4bms4bm/4biE4biL4bi3PMK2xKDDvuG5m@G5qznhuaF0W2AzIkfCo@G4s@G7jcSL4oCZYjU5wqRp4oCYOjL///8iRGlzdGluZ3Vpc2hlZCBNYXN0ZXIgR3VhcmRpYW4i)** or see all valid inputs at the **[test suite](https://tio.run/##bZBNS8MwHMa/SijupJe1U5iIl9kFYZ2HgZchmNFQI7GVthvsVkXxMLwrikz05m6CNqgT2vlB0i9Sm9S9ustDnt@T/F9yjCntpukeDy9LheTsazV@KGxoSXAfDbY5G3D2zcMLHvZ4@L4VvY368ZCzO85eypw9@s1DTYHREw9f@cf1qJcEt631cvRMkuBmU01/PuMrzoYryfkApmlTaRDawS7YVdaURlHIn5dAnQWSaDNkX5xLU6BT4mNh9QUGDOT52JWRkSl0qAnqTgfJtrBenGc5VBdgTrU5OqkL66JubgFsI9ckyJbVDVhcluSRuiQab2FAscYO8XxiW23iHWETLNwVuQEzrWEL2yZyu0BHFhWva/p/PB23Jr@h0T518ckYgypxPR9UKPI8ERrViliMOi1EJ0NlMx38Ag)**.
### How?
```
Oḅ4%⁽+Þ%63“ ... ’b59¤i‘:2 - Main link: list of characters, s e.g. "Global Elite"
O - cast to ordinals [71,108,111,98,97,108,32,69,108,105,116,101]
ḅ4 - convert from base 4 448653509 (71 * 4 ^ 15 + 108 * 4 ^ 14 + ... + 116 * 4 + 101 = 448653509)
⁽+Þ - base 250 compressed number 11771
% - modulo 1844 (448653509 = 11771 * 38115 + 1844)
%63 - modulo 63 17 (1844 = 63 * 29 + 17)
i - first index (or 0 if not found) in: 33 -----------------------------------------------------------------------+
¤ - nilad followed by link(s) as a nilad: |
“ ... ’ - base 250 integer = 29327561081972369663135271131767983884313794468054748055733 v
b59 - convert to base 59 = [1,4,5,44,6,14,7,23,43,45,16,48,21,49,50,51,13,55,2,53,28,54,10,37,18,36,8,58,31,57,24,47,17,37]
- i.e. all valid results of the hashing except Silver I (40) and S1 (3) in ascending rank order.
‘ - increment 34
:2 - integer divide by 2 17
```
(another 45 byter: `Oḅ30%⁽EÐ%53“ḷṡ{Żiȧ)ߨẊ×HuÑç%Ɱȧḷ9)×ḍỊ’b53¤i‘:2`)
[Answer]
# Python 3 + [Roman](https://pypi.python.org/pypi/roman), 291 bytes
```
import roman as r,sys
a=sys.argv
x,y,o=a[1],a[-1],{r:i for i,r in enumerate(["S1","S2","S3","S4","SE","SEM","GN1","GN2","GN3","GNM","MG1","MG2","MGE","DMG","LE","LEM","SMFC","GE"])}
print(o[x if x in o else "".join([n[0] for n in a[1:-1]] + [str(r.fromRoman(y)) if y in "IIIV" else y[0]])])
```
Non-golfed version:
```
import roman
from sys import argv
if __name__ == "__main__":
ranks = ["S1", "S2", "S3", "S4", "SE", "SEM", "GN1", "GN2", "GN3", "GNM",
"MG1", "MG2", "MGE", "DMG", "LE", "LEM", "SMFC", "GE"]
output = {rank : i for i, rank in enumerate(ranks)}
if argv[1] in output:
print(output[argv[1]])
else:
argv[-1] = str(roman.fromRoman(argv[-1])) if argv[-1] in "IIIV" else argv[-1][0]
print(output["".join([x[0].upper() for x in argv[1:]])])
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~100~~ 96 bytes
```
lambda s:"F]u^B_&`5qDy,MeN<O$iW'?(d;hHQ2Y:1o%a".find(chr((9*ord(s[0])+ord((s*18)[35]))%92+33))/2
```
An unnamed function accepting the string `s` and returning an integer.
Result is 0-indexed.
**[Try it online!](https://tio.run/##bZJrT8IwFIY/669oFtEViLJNEpm3RBjThM0YEo3BqcUW1qSs0HYkhPDbcd3kKl9Oe563PZeejmcq5om9HNx@LBka9TEC0jXaUfr58HX6XZ@0ZtWAhDfPJ/Tt7N7E1/Hji/3uWryEjPMBTbD5EwvTbJS5wKbs1SJY0TtTlq0r2HPqEYSlhl1xHAgvsiRcAEWkAjQBPaNL2ZQI8GRUja6lzZ@fA3sb5MTZIq96f7kBHqOKaNfbYyBAUhGRS0Fmfc4wCPkU5Wn90NplBbT3YEGdHbqO64c6buECP0UCU5Tk0QPfOqQUkn1AWnUR@LqNFpWKJsOUyphgsHdW64Gf2Q4ZkgQjMQMeGjJ9u@P9x5tyO/kzdNOxIKMVBm0qsqE0GZJSi0G7qRtjvI/Yuqispsg9PhoLmihgzGvund1YABfMrUX2E7gYIWXq2VbBIF8hXP4C)**
### How?
Takes the 1st and 36th (modulo the length) characters of the input using `s[0]` and `(s*18)[35]` respectively, that produces the mapping:
```
{"Silver I":"Sv", "S1":"S1", "Silver II":"SI", "S2":"S2", "Silver III":"Sr", "S3":"S3", "Silver IV":"SV", "S4":"S4", "Silver Elite":"Se", "SE":"SE", "Silver Elite Master":"St", "SEM":"SM", "Gold Nova I":"Gl", "GN1":"G1", "Gold Nova II":"GI", "GN2":"G2", "Gold Nova III":"G ", "GN3":"G3", "Gold Nova Master":"Gd", "GNM":"GM", "Master Guardian I":"Ma", "MG1":"M1", "Master Guardian II":"MI", "MG2":"M2", "Master Guardian Elite":"Mn", "MGE":"ME", "Distinguished Master Guardian":"Dg", "DMG":"DG", "Legendary Eagle":"Ld", "LE":"LE", "Legendary Eagle Master":"Ll", "LEM":"LM", "Supreme Master First Class":"Sa", "SMFC":"SC", "Global Elite":"Ge", "GE":"GE"}
```
Converts them to ordinals and converts that from base 9 (ignoring the "base 9 only has 9-digits" restriction) by multiplying the first ordinal by nine and adding it to the second (`9*ord(s[0])+ord((s*18)[35])`).
Reduces the range of those numbers while maintaining uniqueness by taking the modulo 92 of the result. Adds 33 to make the range fit across printable characters (while avoiding the pesky `\` which would require escaping).
Looks up the index of the resulting character in a string, using `find` and integer divides the result by two with `/2` (since every two characters represent a "class" - one for the long name and one for the short name).
] |
[Question]
[
**Challenge: Read a string from user, print number of each vowel, then place all remaining chars in a line. Shortest answer wins!**
Output must look like this:
>
> Enter String: *Input*
>
>
> Vowel Count: a: *#*, e: *#*, i: *#*, o: *#*, u: *#*
>
>
> Remaining characters: *Vowel-less Input*
>
>
>
For example:
```
Enter String: LoremIpsumDolorSitAmetConsecuteurAdipscingElit!
Vowel Count: a: 0, e: 4, i: 4, o: 4, u: 3
Remaining characters: LrmIpsmDlrStAmtCnsctrAdpscngElt!
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 62 bytes
### Code:
```
”‡Á•Ë: ÿ”,”Vowelš‹: ”?"aeiou"©vy": "¹y¢««}", "ý,“«¶šÞ: “ª¹®-J,
```
### Explanation:
There is a lot of string compression going on here. Here is a list of all strings that are compressed:
* [`”‡Á•Ë”`](http://05ab1e.tryitonline.net/#code=4oCd4oChw4HigKLDi-KAnQ&input=) is equivalent to `Enter String`.
* [`”Vowelš‹”`](http://05ab1e.tryitonline.net/#code=4oCdVm93ZWzFoeKAueKAnQ&input=) is equivalent to `Vowel Count`.
* [`“«¶šÞ“ª`](http://05ab1e.tryitonline.net/#code=4oCcwqvCtsWhw57igJzCqg&input=) is equivalent to `Remaining characters`.
To see how the actual string compression works, see the [Hello, World!](https://codegolf.stackexchange.com/a/67457/34388) answer, or an even more elaborate explanation at the bottom of the [Code Review question](https://codereview.stackexchange.com/q/121090/98677). Without the string compression, the code looks like this:
```
"Enter String: ÿ","Vowel Count: "?"aeiou"©vy": "¹y¢««}", "ý,"Remaining characters: "¹®-J,
```
Or a more readable 3-part version:
```
"Enter String: ÿ",
"Vowel Count: "?"aeiou"©vy": "¹y¢««}", "ý,
"Remaining characters: "¹®-J,
```
**Part 1:**
We first push the string `"Enter String: ÿ"`. The `ÿ` here is used for *string interpolation*. But since the stack is empty, implicit input is requested. The `ÿ` will be substituted with the user input. We print this with a newline using `,`.
**Part 2:**
We first print the `"Vowel Count: "` string *without* a newline using `?`. After that, we push the `aeiou` string, `©`opy that to the register and map over the string using `v` and do the following:
```
vy": "¹y¢««} # Mapping loop
v } # The loop itself
y # Push the current letter (which is a, e, i, o or u)
": " # Push this string
¬π # Push the first input again
y # Push the letter again
¢ # Count the number of occurences of that letter in the input
¬´¬´ # Concatenate to one single string, (e.g. "a: 4")
```
This leaves 5 different string onto the stack, the stack looks like this now:
```
stack: ['a: 0', 'e: 1', 'i: 0', 'o: 2', 'u: 0']
```
We join each element in the stack with `", "` using `√Ω`. After this, we print it with a newline using `,`.
**Part 3:**
We first push the string `"Remaining characters: "`. We push the first input again using `¹`. We then push `"aeiou"` which we retrieve from the register using `®`. After this, we remove all letters in `aeiou` using `-` and `J`oin this with the `Remaining characters`-string. Finally, we output this with a newline using `,`.
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=4oCd4oChw4HigKLDizogw7_igJ0s4oCdVm93ZWzFoeKAuTog4oCdPyJhZWlvdSLCqXZ5IjogIsK5ecKiwqvCq30iLCAiw70s4oCcwqvCtsWhw546IOKAnMKqwrnCri1KLA&input=TG9yZW1JcHN1bURvbG9yU2l0QW1ldENvbnNlY3V0ZXVyQWRpcHNjaW5nRWxpdCE).
[Answer]
## Python, 168 bytes
```
s=input('Enter String:')
v='aeiou'
print('Vowel Count: '+', '.join([a+':'+str(s.count(a)) for a in v])+'\nRemaining characters: '+''.join([a for a in s if a not in v]))
```
<https://repl.it/CMzO/1>
[Answer]
# JavaScript (ES6), 165
Fixed error in output, thx @Neil
3 bytes saved thx @Dom Hastings
```
a=prompt`Enter String:`.replace(/[aeiou]/g,v=>(V[v]=-~V[v],''),V=[]);alert("Vowel Count: "+[...'aeiou'].map(v=>v+': '+(V[v]|0)).join`, `+`
Remaining characters: `+a)
```
[Answer]
## Lua, 242 Bytes
For a moment, I thought that it will be longer than SQL... still a monster for such a simple task.
```
t={}x="aeiou"i=io.write
x:gsub(".",function(c)t[c]=0 end)i("Enter string: ")z=io.read()s="Remaining characters: "..z:gsub(".",function(c)if x:find(c)then
t[c]=t[c]+1return""end end)i("Vowel Count: ")x:gsub(".",function(c)i(c..": "..t[c]..(c=="u"and"\n"or", "))end)i(s)
```
The job is done by the part
```
z:gsub(".",function(c)if x:find(c)then t[c]=t[c]+1return""end end)
```
Everything else is mainly for the purpose of outputing in the right format.
### Ungolfed
```
t={} -- create an empty array
x="aeiou" -- list of vowels
i=io.write -- shorthand for outputing
x:gsub(".",function(c)t[c]=0 end)-- create a celle at 0 for each vowel
i("Enter string: ") -- output some boilerplate
z=io.read() -- take the input
s="Remaining characters: ".. -- save in s the concatenation of this string
z:gsub(".",function(c) -- and the result of gsubing on each character of the input
if x:find(c) -- if the current char is a vowel
then
t[c]=t[c]+1 -- increment its counter
return"" -- suppress it from the input
end
end)
i("Vowel Count: ") -- output some more boilerplate
x:gsub(".",function(c) -- iterate over the vowels
i(c..": "..t[c].. -- output "l: #" appended with
(c=="u"
and"\n" -- "\n" if the current char is "u"
or", ")) -- ", " otherwise
end)
i(s) -- output the content of s
```
[Answer]
# Perl 5, 127 bytes
```
$_=<>;print"Enter String: ${_}Vowel Count:";for$s(a,e,i,o,u){print" $s: ".~~s/$s//g,$s!~u&&","}print"
Remaining characters: $_"
```
Many thanks to [Dom Hastings](/u/9365) (in a comment hereon) for 14 bytes.
[Answer]
# Java, 272 bytes
```
class L{public static void main(String[]v){String p=v[0],o="Enter String: "+p+"\nVowel Count:",d=" ",e="aeiou";for(char c:e.toCharArray()){o+=d+c+": "+p.replaceAll("[^"+c+"]","").length();d=", ";}System.out.println("\nRemaining characters: "+p.replaceAll("["+e+"]",""));}}
```
### Ungolfed
```
class L {
public static void main(String[] v) {
String input = v[0], result = "Enter String: " + input + "\nVowel Count:", delimiter = " ", vowels = "aeiou";
for (char c : vowels.toCharArray()) {
result += delimiter + c + ": " + input.replaceAll("[^" + c + "]", "").length();
delimiter = ", ";
}
System.out.println("\nRemaining characters: " + input.replaceAll("[" + vowels + "]", ""));
}
}
```
### Notes
* Input via program arguments: Save as `L.java`, compile with `javac L.java`, run with `java L LoremIpsumDolorSitAmetConsecuteurAdipscingElit!`
### Output
```
Enter String: LoremIpsumDolorSitAmetConsecuteurAdipscingElit!
Vowel Count: a: 0, e: 4, i: 4, o: 4, u: 3
Remaining characters: LrmIpsmDlrStAmtCnsctrAdpscngElt!
```
[Answer]
# PostgreSQL, 295, 263 bytes
```
SELECT v "Enter string:", string_agg(r,', 'ORDER BY n) "Vowel Count:",TRANSLATE(v,'aeyiou','') "Remaining characters:"
FROM (SELECT 'LoremIpsumDolorSitAmetConsecuteurAdipscingElit!'::text v)s
,LATERAL(SELECT LENGTH(v)l)a
,LATERAL(SELECT c||': '||l-LENGTH(REPLACE(v,c,''))r,n FROM (VALUES('a',1),('e',2),('i',3),('o',4),('u',5))t(c,n))b
GROUP BY v
```
`**[`SqlFiddleDemo`](http://sqlfiddle.com/#!15/9eecb7db59d16c80417c72d1e1f4fbf1/8236/0)**`
Output:
```
╔══════════════════════════════════════════════════╦═══════════════════════════════╦══════════════════════════════════╗
‚ïë Enter string: ‚ïë Vowel Count: ‚ïë Remaining characters: ‚ïë
╠══════════════════════════════════════════════════╬═══════════════════════════════╬══════════════════════════════════╣
‚ïë LoremIpsumDolorSitAmetConsecuteurAdipscingElit! ‚ïë a: 0, e: 4, i: 4, o: 4, u: 3 ‚ïë LrmIpsmDlrStAmtCnsctrAdpscngElt! ‚ïë
╚══════════════════════════════════════════════════╩═══════════════════════════════╩══════════════════════════════════╝
```
Input: `(SELECT '...'::text v)s`
How it works:
* `(SELECT 'LoremIpsumDolorSitAmetConsecuteurAdipscingElit!'::text v)s` input
* `,LATERAL(SELECT LENGTH(v)l)a` - length of input
* `(VALUES('a',1),('e',2),('i',3),('o',4),('u',5))` - vowels with oridinal
* `SELECT c||': '||l-LENGTH(REPLACE(v,c,''))r,n` - calculate number of occurences
* `string_agg(r,', 'ORDER BY n) ... GROUP BY v` combine result
* `TRANSLATE(v,'aeyiou','')` string without vowels
**EDIT 3:**
Removed additional `LATERAL`, input moved to table.
```
SELECT v"Enter string:",string_agg(r,', 'ORDER BY n)"Vowel Count:",TRANSLATE(v,'aeyiou','')"Remaining characters:"
FROM s,LATERAL(SELECT c||': '||LENGTH(v)-LENGTH(REPLACE(v,c,''))r,n FROM(VALUES('a',1),('e',2),('i',3),('o',4),('u',5))t(c,n))b
GROUP BY v
```
`**[`SqlFiddleDemo`](http://sqlfiddle.com/#!15/f1b88/2/0)**`
[Answer]
**Python, ~~220~~ 201 bytes**
This is my first submission on codegolf so go easy. :P
```
def f(y):
global x;c=x.count(y);x=x.replace(y,'');return c;
x=input('Enter string: ');print('Vowel Count: a: {}, e: {}, i: {}, o: {}, u: {}'.format(*map(f,"aeiou")));print('Remaining characters: '+x)
```
**Ungolfed:**
```
def f(y):
global x
c=x.count(y)
x=x.replace(y,'')
return c;
x=input('Enter string: ')
print('Vowel Count: a: {}, e: {}, i: {}, o: {}, u: {}'.format(*map(f,"aeiou")))
print('Remaining characters: '+x)
```
**Output:**
```
Enter string: LoremIpsumDolorSitAmetConsecuteurAdipscingElit!
Vowel Count: a: 0, e: 4, i: 4, o: 4, u: 3
Remaining characters: LrmIpsmDlrStAmtCnsctrAdpscngElt!
```
[Answer]
# JavaScript, ~~190~~ 186 bytes
```
(s,a=[..."aeiou"].map(v=>(s.match(v,"g")||[]).length))=>`Enter String: ${s}
Vowel Count: ${[..."aeiou"].map((v,i)=>v+": "+a[i]).join`, `}
Remaining characters: `+s.replace(/[aeiou]/g,"")
```
I just remembered that literal newlines are only 1 byte! Also remembered to golf something I missed before.
[Answer]
## PowerShell v2+, ~~196~~ 149 bytes
```
$z=read-host "Enter string"
"Vowel Count: "+(([char[]]"aeiou"|%{$_+": "+($z.length-($z=$z-creplace$_).length)})-join', ')
"Remaining characters: "+$z
```
Takes input via `read-host` with a prompt, save into `$z`.
We then output a string literal `"Vowel Count: "` concatenated with the result of a loop/join through the vowels to construct the `a: #, e: #,...` string. This is done by taking the current string's `.length` minus the new string's `.length` after we perform a case-sensitive replacement with `-creplace` (i.e., how many did we remove). In addition, we re-save the result of the replace back into `$z` for the next loop.
We then also output the second string literal concatenated with whatever is still left in `$z`.
This keeps the current specification intact, in that capital vowels are distinguished from lowercase vowels, since `-creplace` is explicitly case sensitive.
### Examples
```
PS C:\Tools\Scripts\golfing> .\briefest-code-find-vowels.ps1
Enter string: LoremIpsumDolorSitAmetConsecuteurAdipscingElit!
Vowel Count: a: 0, e: 4, i: 4, o: 4, u: 3
Remaining characters: LrmIpsmDlrStAmtCnsctrAdpscngElt!
PS C:\Tools\Scripts\golfing> .\briefest-code-find-vowels.ps1
Enter string: ProgrammingPuzzlesAndCodeGolf
Vowel Count: a: 1, e: 2, i: 1, o: 3, u: 1
Remaining characters: PrgrmmngPzzlsAndCdGlf
```
[Answer]
# Retina, 133 bytes
```
(a()|e()|i()|o()|u()|.)+
Enter string: $&¶Vowel count: a: $#2, e: $#3, i:$#4, o:$#5, u:$#6¶Remaining characters: $&
(?<=s:.+)[aeiou]
<empty-line>
```
[Try it online!](http://retina.tryitonline.net/#code=KGEoKXxlKCl8aSgpfG8oKXx1KCl8LikrCkVudGVyIHN0cmluZzogJCbCtlZvd2VsIGNvdW50OiBhOiAkIzIsIGU6ICQjMywgaTokIzQsIG86JCM1LCB1OiQjNsK2UmVtYWluaW5nIGNoYXJhY3RlcnM6ICQmCig_PD1zOi4rKVthZWlvdV0K&input=dm93ZWw)
Who is more fit for this challenge than Retina?
[Answer]
# Groovy, 181 177 bytes
[online](http://groovyconsole.appspot.com/script/5124473388793856)
```
‚Äã{i->r=[:].withDefault{0};o=i.toLowerCase().replaceAll(/[aeiou]/,{r[it]++;''})
"Enter String: $i\nVowel Count: ${r.collect{k,v->"$k: $v"}.join(' ')}\nRemaining characters: $o"}
```
[Answer]
# Tcl, 184 (counting majuscule vowels) / 180 (ignoring them)
```
puts -nonewline {Enter String: }
flush stdout
gets stdin s
set c {Vowel Count:}
foreach v {a e i o u} {append c " $v: [regsub -all (?i)$v $s {} s]"}
puts "$c\nRemaining Characters: $s"
```
**Explanation**
Most of the code is actually dealing with the strict I/O requirements. The remainder works by doing a regular expression substitution (deletion) on the input string `$s` for every vowel and appending the vowel `$v` and associated number of substitutions to the output string `$c`.
The above code works for mixed-case vowels. Remove the `(?i)` option from the regular expression on the penultimate line for strictly minuscule vowels.
[Answer]
# Python 162 Bytes
```
v,s="aeiou",input()
print "String:"+s+"\n"+"Vowel Count"+" ".join([c+":"+str(s.count(c)) for c in v])+"\n"+"Remaining Characters:"+filter(lambda x:v.count(x)<1,s)
```
[Answer]
# C# 317 bytes
```
string t=Console.ReadLine();Dictionary v = new Dictionary<char,int>{{'a',0},{'e',0},{'i',0},{'o',0},{'u',0}};string o="";foreach(char c in t){if(v.Keys.Contains(c)){v[c]++;}else{o+=c;}}Console.WriteLine("a: "+v['a']+", e: "+v['e']+", i: "+v['i']+", o: "+v['o']+", u: "+v['u']);Console.WriteLine("Remaining Characters: "+o);
```
Any suggestions, trying to learn to golf with C#. 1KB is obviously way bigger than the other answers though.
Ungolfed:
```
string t=Console.ReadLine();
Dictionary v = new Dictionary<char,int>
{
{'a',0},
{'e',0},
{'i',0},
{'o',0},
{'u',0}
};
string o="";
foreach(char c in t)
{
if(v.Keys.Contains(c))
{
v[c]++;
}
else
{
o+=c;
}
}
Console.WriteLine("a: "+v['a']+", e: "+v['e']+", i: "+v['i']+", o: "+v['o']+", u: "+v['u']);
Console.WriteLine("Remaining Characters: "+o);
```
[Answer]
## Ruby, 202 bytes
```
print"Enter String: ";t=gets;c=->(x){t.chars.count(x)};a="aeiou".chars
s=a.zip(a.map(&c)).map{|e|"#{e[0]}: #{e[1]}"}.join(", ");r=t.gsub(/[aeiou]/,"")
puts"Vowel Count: #{s}\nRemaining characters: #{r}"
```
[Answer]
## C++, 449 bytes
### Golfed:
```
#include <iostream>
#include <string>
int main(){std::string x;std::cout<<"Enter String: ",std::cin>>x;int a=0,e=0,i=0,o=0,u=0;for(int c=0;c<x.length();c++){switch(x[c]){case 'a':a++;x.erase(c,1);break;case 'e':e++;x.erase(c,1);break;case 'i':i++;x.erase(c,1);break;case 'o':o++;x.erase(c,1);break;case 'u':u++;x.erase(c,1);break;}}std::cout<<"\n Vowel Count: a: "<<a<<", e: "<<e<<", i: "<<i<<", o: "<<o<<", u: "<<u<<"\n Remaining characters: "<<x;}
```
### Ungolfed:
```
#include <iostream>
#include <string>
int main(){
std::string x;
std::cout<<"Enter String: ", std::cin>>x;
int a=0,e=0,i=0,o=0,u=0;
for(int c = 0; c < x.length(); c++){
switch(x[c]){
case 'a':
a++;
x.erase(c,1);
break;
case 'e':
e++;
x.erase(c,1);
break;
case 'i':
i++;
x.erase(c,1);
break;
case 'o':
o++;
x.erase(c,1);
break;
case 'u':
u++;
x.erase(c,1);
break;
}
}
std::cout<<"\n Vowel Count: a: "<<a<<", e: "<<e<<", i: "<<i<<", o: "<<o<<", u: "<<u<<"\n Remaining characters: "<<x;
}
```
[Answer]
# C++17, 313 bytes
```
#include <cctype>
#include <iostream>
#include <string>
using namespace std;int main(){int n,h[6]={0};string s,v="aeiou",r;cout<<"Enter String: ";getline(cin,s);for(c:s){h[n=v.find(tolower(c))+1]++;if(!n)r+=c;}cout<<"Vowel Count:";n=1;for(c:v)cout<<" "<<c<<": "<<h[n++];cout<<"\nRemaining Characters: "<<r<<"\n";}
```
I suppose I could make this just a function to eliminate standard boilerplate from the byte count.
**Ungolfed**
```
#include <cctype>
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
int histogram[6] = {0}; // { (consonants), A, E, I, O, U }
string source;
string vowels = "aeiou"; // vowel order matches the histogram
string consonants;
cout << "Enter String: ";
getline( cin, source );
for (c : source)
{
// n ‚Üê consonants=0, A=1, E=2, ...
n = vowels.find( tolower(c) ) + 1;
histogram[n]++;
if (!n)
consonants += c;
}
cout<<"Vowel Count:";
n = 1;
for (vowel : vowels)
cout << " " << vowel << ": " << histogram[n++];
cout << "\nRemaining Characters: " << consonants << "\n";
}
```
**Explanation**
Computes a histogram using the `std::string` lookup functions.
Again, you can eliminate 27 bytes from the count if only minuscule vowels matter. (Remove the first #include and the call to `tolower()`.)
[Answer]
# Ruby, ~~134~~ ~~133~~ 131 bytes
Because the other Ruby answer didn't respond to my suggestions, I golfed it down further myself.
-2 bytes from @manatwork
```
$><<"Enter String: "
r=gets.tr v='aeiou',''
puts"Vowel Count: #{v.chars.map{|e|e+": #{$_.count e}"}*', '}
Remaining characters: "+r
```
] |
[Question]
[
# The challenge
Insert one string into another at a given index.
Given a string input in the format:
```
#:Pattern:Word
```
Where:
* `#` is a positive integer marking the index
* `Pattern` is the string (whose length is undefined) to insert
* `:` is a delimiter
* `Word` is the string to insert into.
Assume that a `:` will not be used in either string.
For example, if your input was
```
3:A2C:Hello World!
```
The output would be
```
HelA2Clo World!
```
If an invalid index is provided, the program must respond with an error. For example
```
12:!*!:Hello
```
is a valid input and must be explicitly handled somehow. For example, printing "Invalid input!" (or nothing at all!) is a valid way to catch, however crashing is not valid.
[Answer]
# CJam, 20 bytes
```
q':/~La+@~/(@@_{];}|
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q'%3A%2F~La%2B%40~%2F(%40%40_%7B%5D%3B%7D%7C&input=13%3AA2C%3AHello%20World!).
### How it works
```
q':/ e# Read all input and split it at colons.
~ e# Dump index, pattern and word on the stack.
La+ e# Append the array [""] to the word.
e# This increases the word's length by 1 (to deal with the
e# highest index possible index) without affecting output.
@~ e# Rotate the index on top and evaluate it.
/ e# Split the word into chunks of that length.
( e# Shift out the first chunk.
@@ e# Rotate pattern and remaining chunks on top.
_ e# Copy the array of remaining chunks.
e# This array will be empty if the index was too high.
{];}| e# If the array if falsy, clear the stack.
```
[Answer]
# CJam, 34 bytes
Terribly ungolfed, but its my first CJam golf ever! Thanks to sp3000 for helping me with this on The Nineteenth Byte chat!
```
l':/~_,W$i>{W$i/(:+-2$+-3$+:+p}&];
```
**EDIT:** oops, I was in the process of posting this and I didn't see Dennis' CJam post. If the answers do end up using the same process, just count mine as a non-competitive answer. Sorry for the confusion.
[Answer]
# JavaScript ES6, 49 bytes
```
s=>([a,b,c]=s.split`:`,c.slice(0,a)+b+c.slice(a))
```
Very straightforward. Slices the string and inserts the new substring in the middle
[Answer]
## Python 3, 65 bytes
```
a,b,c=input().split(':')
a=int(a)
if c[a-1:]:print(c[:a]+b+c[a:])
```
Does nothing if the index is past the end of the string. [Try it online](http://ideone.com/T3N7qZ).
[Answer]
# Pyth, 33
```
=Ycw\:JvhYp?>leYJjk[<eYJ@Y1>eYJ)Z
```
Prints `0` if the index is past the end of the string
[Try is online](https://pyth.herokuapp.com/?code=%3DYcw%5C%3AJvhYp%3F%3EleYJjk%5B%3CeYJ%40Y1%3EeYJ%29Z&input=3%3AA2C%3AHello%20World%21&debug=0)
[Answer]
# Ruby, 43 bytes
37 bytes of code:
```
G,O,L=$F
$_=(L[G.to_i,0]=O;L)rescue p
```
and 6 bytes of flags:
```
$ ruby -apF: code.rb < input
^^^^^^
```
[Answer]
# Pyth, 23
```
*sX0ceJcz\:KvhJhtJgleJK
```
Unfortunately (in this scenario anyway), Pyth doesn't error on chopping a string by too large a value. Otherwise the check would go from 6 bytes to 2.
I'm unsure if this is the most optimal approach, but this chops the word after the number of characters from the input. Then it does a `+=` on the first element of the list and returns the sum. It multiplies the resulting string by a boolean representing if the value was out of range.
Also note that this does not work if the input is 0. The OP said we could assume the number is positive, so I believe this is ok.
[Try it online](http://pyth.herokuapp.com/?code=%2AsX0ceJcz%5C%3AKvhJhtJgleJK&input=13%3AA2C%3AHello%20World%21&debug=0)
[Answer]
# Pyth, 32 bytes
Beats the other Pyth answer! Still needs a lot of golfing though. Took the naïve approach.
```
?gleJcz":"KvhJ++:eJ0KhtJ:eJKleJ"
```
[Try it online.](http://pyth.herokuapp.com/?code=%3F%3EleJcz%22%3A%22KvhJ%2B%2B%3AeJ0KhtJ%3AeJKleJ%22&input=3%3AA2C%3AHello+World%21)
[Answer]
# Perl 5, 41 Bytes (40 + 1)
Outputs 0 when a replacement couldn't be made.
```
($n,$s,$_)=split/:/;$_=0if!s/.{$n}/$&$s/
```
### Test
```
$ echo "6:Online :Hello World!" |perl -p -e '($n,$s,$_)=split/:/;$_=0if!s/.{$n}/$&$s/'
$ Hello Online World!
```
[Answer]
# Perl, 34 bytes
(includes 1 switch)
```
perl -pe '$x="."x$_;s/.*:(.*):($x)|.*/$2$1/'
```
Prints an empty line on error.
[Answer]
# C++11, 186 bytes
Golfed
```
#include<iostream>
#include<regex>
int main(){std::string p,w;int i,j;std::getline(std::cin>>i,p);j=p.find(58,1);w=p.substr(j+1);if(i<=w.length())std::cout<<w.insert(i,p.substr(1,j-1));}
```
Ungolfed
```
#include <iostream>
#include <regex>
int main()
{
std::string p, w;
int i, j;
std::getline(std::cin >> i, p);
j = p.find(':', 1);
w = p.substr(j + 1);
if (i <= w.length())
std::cout << w.insert(i, p.substr(1, j - 1));
}
```
Looking for: Improvements and someone who can do Shakespear, so that I am not last again :)
[Answer]
# [Retina](https://github.com/mbuettner/retina), 38 bytes
```
(()1)*:(.+):((?<-2>.)*)(?!\2)|^.+
$4$3
```
Run the code from a single file with the `-s` flag. This [takes input in unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary), e.g.
```
111:A2C:Hello World!
```
yields
```
HelA2Clo World!
```
If the index is too large, an empty line will be printed.
[Answer]
# Haskell, 97 bytes
```
a=fmap tail.span(/=':')
m!(n,e)|m>length e=""|0<1=take m e++n++drop m e
f l|(o,r)<-a l=read o!a r
```
Defines `f`, a function that takes a string like `"2:x:ABC"` and returns `"ABxC"`.
[Answer]
# Julia, 66 bytes
```
s->(x=split(s,":");i=parse(Int,x[1]);x[3][1:i]*x[2]*x[3][i+1:end])
```
This creates an unnamed function that accepts a string and returns a string. It errors if the index is out of bounds.
Ungolfed:
```
function f(s::AbstractString)
# Split the input on the colon
x = split(s, ":")
# Convert the first element of x to an integer
i = parse(Int, x[1])
# Join the pieces
return x[3][1:i] * x[2] * x[3][i+1:end]
end
```
[Answer]
# Ruby, 55 bytes
```
a,b,c=gets.split ?:;(c[a,0]=b;p c)if c.size>=(a=a.to_i)
```
It's been a while since I've golfed in Ruby... this feels a bit suboptimal.
[Answer]
# Gema: 47 characters
```
*\:*\:*=@subst{<U$1>\*=\$1@quote{$2}\*\;\*=;$3}
```
Sample run:
```
bash-4.3$ gema '*\:*\:*=@subst{<U$1>\*=\$1@quote{$2}\*\;\*=;$3}' <<< '3:!*!:Hello'
Hel!*!lo
bash-4.3$ gema '*\:*\:*=@subst{<U$1>\*=\$1@quote{$2}\*\;\*=;$3}' <<< '13:!*!:Hello'
```
(If you want an explicit error message, just insert it after the last `=` sign.)
[Answer]
# MUMPS, 70 bytes
```
a(s) s w=$P(s,":",3) q:s>$L(w) w $E(w,1,s)_$P(s,":",2)_$E(w,s+1,9**9)
```
There is no output if an invalid index is provided.
This code is *basically* ANSI-compliant; the only issue is that I've saved a byte by taking advantage of the fact that the maximum length of a string on the two major surviving MUMPS platforms is less than 99 bytes: [InterSystems Caché caps strings at 32 KiB](http://docs.intersystems.com/ens201512/csp/docbook/DocBook.UI.Page.cls?KEY=RERR_system#RERR_B101753), and [GT.M caps strings at 1 MiB](http://tinco.pair.com/bhaskar/gtm/doc/books/mr/manual/MAXSTRLEN.html). Nonetheless, in principle, some jerk could write an implementation that allows strings over ~369 MiB, in which case there would be valid inputs for which this code fails.
We can save 3 additional bytes, bringing us down to 67, if we use non-ANSI [Caché ObjectScript-specific extensions to `$EXTRACT`](http://docs.intersystems.com/ens201512/csp/docbook/DocBook.UI.Page.cls?KEY=RERR_system):
```
a(s) s w=$P(s,":",3) q:s>$L(w) w $E(w,1,s)_$P(s,":",2)_$E(w,s+1,*)
```
[Answer]
## Perl 6, 58 bytes
```
$_=[split ':',@*ARGS];substr-rw(.[2],.[0],0)=.[1];.[2].say
```
] |
[Question]
[
**Objective:**
The objective is to calculate e^N for some real or imaginary N (e.g. 2, -3i, 0.7, 2.5i, but not 3+2i). This is code golf, so, shortest code (in bytes) wins.
So, for example:
1. N = 3, e^N = 20.0855392
2. N = -2i, e^N = -0.416146837 - 0.9092974268i
The letter `i` shouldn't be capitalized (since in math it is lowercase)
If your language supports raising numbers to complex numbers, you can't use that. You may use built-in real exponentiation.
For any answer where b (in a + bi) is negative, it is OK to have both the plus and minus sign (e.g. 2 + -3i), since that is understood to be (2 - 3i)
**Bonus (-15 bytes):** Solve this for N is a any complex number (e.g. 5 + 7i). If you are going for the bonus, you can assume that both components will always be given (even for the standard objective)
[Answer]
# CJam, 22 - 15 = 7
```
l~_mc\ms@me:X*\X*'+@'i
```
[Try it online here](http://cjam.aditsu.net/)
Takes input in the form of `a b` where `a` is the real component and `b` is the complex.
For ex. `2i` is
```
0 2
```
gives
```
-0.4161468365471424+0.9092974268256817i
```
[Answer]
# 80386 Assembly (41 bytes - 15 = 26)
```
8B 4C 24 04 8B 54 24 08 D9 EA DC 09 D9 C0 D9 FC DC E9 D9 C9 D9 F0 D9 E8 DE C1 D9 FD DD 02 D9 FB D8 CA DD 19 D8 C9 DD 1A C3
```
Floating point math in assembly is a pain..
This is a function (cdecl calling convention) that calculates `e^(a+bi)` via the relation `e^(a+bi)=e^a cos b + e^a sin b * i`. (It accepts two `double *` parameters, a and b in that order, and outputs the real part into the `a` pointer, and the imaginary part into the `b` pointer).
The function prototype in C would be:
```
void __attribute__((cdecl)) exp_complex(double *a, double *b);
```
About half (20, to be exact) of the 41 bytes were spent calculating `e^a`; another 8 were spent getting the function arguments into registers.
The above bytecode was written by hand, from the following assembly (NASM-style, commented):
```
; get pointers into ecx, edx
mov ecx, [esp+4] ; 8B 4C 24 04
mov edx, [esp+8] ; 8B 54 24 08
; log(2,e)
fldl2e ; D9 EA
; a log(2,e)
fmul qword [ecx] ; DC 09
; duplicate
fld st0 ; D9 C0
; get integer part
frndint ; D9 FC
; get fractional part
fsub st1, st0 ; DC E9
; put fractional part on top
fxch st1 ; D9 C9
; 2^(fract(a log(2,e))) - 1
f2xm1 ; D9 F0
; 2^(fract(a log(2,e)))
fld1 ; D9 E8
faddp st1 ; DE C1
; 2^(fract(a log(2,e))) * 2^(int(a log(2,e)))
; = e^a
fscale ; D9 FD
; push b
fld qword [edx] ; DD 02
; sin and cos
fsincos ; D9 FB
; e^a cos b
fmul st2 ; D8 CA
; output as real part
fstp qword [ecx] ; DD 19
; e^a sin b
fmul st1 ; D8 C9
; output as imaginary part
fstp qword [edx] ; DD 1A
; exit
ret ; C3
```
To try this in C (gcc, linux, intel processor):
```
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
int main(){
// bytecode from earlier
char code[] = {
0x8B, 0x4C, 0x24, 0x04, 0x8B, 0x54, 0x24, 0x08,
0xD9, 0xEA, 0xDC, 0x09, 0xD9, 0xC0, 0xD9, 0xFC,
0xDC, 0xE9, 0xD9, 0xC9, 0xD9, 0xF0, 0xD9, 0xE8,
0xDE, 0xC1, 0xD9, 0xFD, 0xDD, 0x02, 0xD9, 0xFB,
0xD8, 0xCA, 0xDD, 0x19, 0xD8, 0xC9, 0xDD, 0x1A,
0xC3,
};
// allocate executable memory to a function pointer called 'exp_complex'
void __attribute__( (__cdecl__) ) (*exp_complex)(double *,double *) = mmap(0,sizeof code,PROT_WRITE|PROT_EXEC,MAP_ANON|MAP_PRIVATE,-1,0);
memcpy(exp_complex, code, sizeof code);
// test inputs
double a = 42.24, b = -2.7182818;
printf("%.07g + %.07g i\n", a, b);
// call bytecode as a c function
exp_complex(&a, &b);
printf("%.07g + %.07g i\n", a, b);
// release allocated memory
munmap(exp_complex, sizeof code);
return 0;
}
```
[Answer]
# Mathematica, ~~23~~ 20 bytes - 15 = 5
```
E^#(Cos@#2+Sin@#2I)&
```
This is an anonymous function taking two arguments (real and imaginary component). You should supply floats unless you want exact result (with square roots and exponentials). So you can use this like
```
E^#(Cos@#2+Sin@#2I)&[3.0,-2.0]
```
Note that `I` is Mathematica's imaginary unit, but I'm not actually using any complex arithmetic. Also note, that Mathematica will actually print the result using a (double-struck) *lowercase* `i` as required. See the screenshot in belisarius's comment.
[Answer]
## ES6, ~~63~~ ~~56~~ 55 bytes - 15 = 40
```
(a,b)=>(m=Math,e=m.exp(a),e*m.cos(b)+`+${e*m.sin(b)}i`)
```
---
This is a function that accepts a number in the form `a + bi` with `a` and `b` as the function arguments.
It uses Euler's formula `e^ix=cosx+isinx`.
[Answer]
## TI-BASIC (NSpire) 13 (28 bytes-15)
```
f(r,j):=^r*(sin(j)i+cos(j
```
The `` is `e`. This computes `e^z` for `z=r+i*j`. `i` is an undefined variable. This defines a function f which accepts two parameters: the real part and the imaginary part.
[Answer]
# Haskell 30 raw, 15 with bonus:
```
e a b=map(*exp a)[cos b,sin b]
```
load it up into the GHCi, then try out the function:
```
Ok, modules loaded: Main.
*Main> e 3 0
[20.085536923187668,0.0]
*Main> e 0 (-2)
[-0.4161468365471424,-0.9092974268256817]
```
Also, humans can understand why this works :)
I hope the GHCi is a code golf legal way of bringing Haskell in.
Also note that a human must infer that the second field is the complex one.
[edit1]
[Answer]
# CJam, 33 bytes
```
l_"i"&{);d_mc\ms_0<!'+*\'i}{dme}?
```
[Test it here.](http://cjam.aditsu.net/)
This supports only purely real or purely imaginary input.
[Answer]
# BBC BASIC - 44 bytes (with tokenisation) - 15 = 29
Put this after the END statement. Arguments are the same as
```
a+bi = (a,b)
```
### Code
```
DEFFNf(a,b)e=EXPa:=STR$(e*COSb)+"+"+STR$(e*SINb)+"i"
```
### Usage
```
imaginary$ = FNf(1,1)
PRINT imaginary$
END
DEFFNf(a,b)e=EXPa:=STR$(e*COSb)+"+"+STR$(e*SINb)+"i"
```
Where the output is:
```
1.46869394+2.28735529i
```
[Answer]
# Python, (94 - 15) = 79 bytes
```
from math import *
import cmath
n=input()
print `e**(n[0])*(cos(n[1])+1j*sin(n[1]))`[1:-2]+'i'
```
Pretty straightforward implementation. Since python uses "j" instead of "i" for imaginary numbers, replacing the characters in the final string eats up quite a few (12) bytes. This can definitely still be golfed.
Takes input in the form of `[a,b]` for a + bi.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~20~~ 16 - 15 = 1 [byte](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
```
'+i',⍨¨*⍤⊣×2 1○⊢
```
`'+i',⍨¨` append "+" and "i" to the ends of
`*` *e* to the power of
`⊣` the left argument (the real part)
`×` times
`2 1○` the cosine and sine of
`⊢` the right argument (the imaginary part)
[TryAPL online!](http://tryapl.org/?a=f%u2190%2C%27+i%27%2C%u2368%28%u236A%28*%u22A3%29%D72%201%u25CB%u22A2%29%20%u22C4%20%203%20f%200%20%u22C4%200%20f%20%AF2%20%u22C4%203%20f%20%AF2&run)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~51~~ 47 bytes - 15 = 32
```
#define f(x)(cos((x)*1i)-1i*sin(1i*(x)))*exp(x)
```
[Try it online!](https://tio.run/##hY0xDsIwDEV3TmEVVbIDGQojV2GJTBwZJaFqO1RCXJ1gBAMb0/f7X09mn5hb216iaI0guBLybUZLNyj5Qd2sFS2sIXJxHe1oWhcowQa6bwDGyVgQul52vVzPtdsDTzFkFDwSGWgJ6QNApz@G/fKHX@tbvM1He7LkkObmc3kB "C (gcc) – Try It Online")
] |
[Question]
[
**Generate math problems (addition, subtraction, or multiplication) using numbers 0-10. Provide feedback on whether the user was right or wrong and show a score.**
Specifics:
* Must generate addition, subtraction, or multiplication problems
* Numbers used must be 0-10
* Each problem must be equally likely
* If user is correct, must print "correct!" (with the exclamation point)
* If user is wrong, must print "wrong!" (with the exclamation point)
* After providing correct or wrong feedback, must show score with these specifications:
+ Starts with "Score:"
+ Shows number correct and then "correct"
+ Pipe (`|`) separation
+ Shows number wrong and then "wrong"
+ 2 newlines for separation
* Must repeat forever
For counting characters, the [Text Mechanic](http://textmechanic.co/Count-Text.html) counter will be used.
Sample session:
```
1-7=-6
correct!
Score: 1 correct | 0 wrong
9+3=12
correct!
Score: 2 correct | 0 wrong
4*5=20
correct!
Score: 3 correct | 0 wrong
7-8=3
wrong!
Score: 3 correct | 1 wrong
1*1=3
wrong!
Score: 3 correct | 2 wrong
7+6=
```
[Answer]
**Post-mortem update:**
## Perl 130 bytes
Combining techniques from [dan1111's excellent solution](https://codegolf.stackexchange.com/a/10858/4098) with my own, I was able to squeeze one more byte:
```
@b=qw(Score: 0 correct | 0 wrong);$b[$#x=eval^<>?4:1]++while print"$b[@x]!
@b
"x/./,$_=(0|rand 11).chr(41^2+rand 3).~~rand 11,'='
```
There's a few things that might not be immediately obvious. If `@x` is an array, then `$#x` (the largest index of `@x`) will be one smaller than the length of `@x`. In this way, I can use `$#x` to point to the appropriate counting variable, and the length of `@x` to the corresponding message in a single assignment, without having to `+1`. The score string is repeating by `/./`, which will return `1` if an only if `$_` is non-empty.
---
## Perl 131 bytes
Here's my Perl attempt, which is more or less a direct translation of my PHP solution below.
```
@r=correct,${_^($n=eval^<>?z:r)}++while@z=wrong,print"@$n!
Score: $- @r | $% @z
"x@r,$_=(0|rand 11).chr(41^2+rand 3).~~rand 11,'='
```
`$-` and `$%` are used for counting variables as they default to `0`, alleviating the need for a `printf`, and at the same time allowing me to combine the `print` statements into one. The score string is not printed the first iteration because `@r` has not yet been defined, and therefore `x@r` (repeat by the length of the array `@r`) repeats the string zero times, resulting in an empty string.
Once again using `chr(41^2+rand 3)` to generate `+*-`, as well as a bitwise xor `_^` to switch between `r`→`-` and `z`→`%`. I would have liked to use a type glob for `*n=eval^<>?z:r`, saving a byte `@$n`→`@n`, but unfortunately typed as a string this comes back as either `*main::r` or `*main::z`, which isn't very useful.
</bandwagon>
---
## PHP 157 (155) bytes
Just to get a smattering of languages:
```
<?for($X=$Y=+$x=correct;$y=wrong;)echo$q=rand(0,10).chr(rand(2,4)^41).rand(0,10),'=',eval("\${_&\$n=$q^fgets(STDIN)?y:x}++;"),$$n,"!
Score: $X $x | $Y $y
";
```
The initial `$X=$Y=+` is necessary, because undefined variables print as an empty string, instead of `0`. Unfortunate, but still shorter than using a `printf`. One thing to notice is the 'magic formula' `chr(rand(2,4)^41)`. *2^41 = 43* (+), *3^41 = 42* (\*) and *4^41 = 45* (-). `chr(rand(3,5)^46)` would also work, but in a different order.
This can be made 2 bytes shorter by using a few binary characters:
```
<?for($‡=$†=+$x=correct;$y=wrong;)echo$q=rand(0,10).chr(rand(2,4)^41).rand(0,10),~Â,eval("\${~\$n=$q^fgets(STDIN)?y:x}++;"),$$n,"!
Score: $‡ $x | $† $y
";
```
where `†`, `‡` and `Â` are characters *134*, *135* and *194* respectively.
[Answer]
## APL ~~146~~ 145
In index origin zero:
```
o←'+-×'
s←0 0
t←'wrong' 'correct'
l:⍞←(e←(⍕?11),o[?3],(⍕?11)),'='
r←(⍎e)=⍎⍞
s[r]←s[r]+1
(∊t[r]),'!'
'Score: ',s[1],t[1],'|',s[0],t[0]
' '
' '
→l
10×8=80
correct!
Score: 1 correct | 0 wrong
2×6=16
wrong!
Score: 1 correct | 1 wrong
2+5=
```
[Answer]
**Perl, 144 characters**
```
@b=qw/+ - * Score: correct 0 | wrong 0/;sub _{print@_;~~rand 11}{_$_=_.$b[rand 3]._,'=';_$b[$x=eval==<>?4:7];$b[$x+1]++;_"!\n@b[3..8]\n\n";redo}
```
Updated (thanks ardnew)
[Answer]
## Perl 154 chars
```
$x=correct;$y=wrong;R:$_=join qw|+ - *|[rand 3],map~~rand 11,0,0;print"$_=";$c+=$b=<>==eval;printf"%s!$/Score: %d $x | %d $y$/$/",$b?$x:$y,$c,$.-$c;goto R
```
with some newlines:
```
$x=correct;
$y=wrong;
R:
$_=join qw|+ - *|[rand 3],map~~rand 11,0,0;
print"$_=";
$c+=$b=<>==eval;
printf"%s!$/Score: %d $x | %d $y$/$/",$b?$x:$y,$c,$.-$c;
goto R
```
[Answer]
## Python 2, 180 176
```
from random import*
r=randrange
a='correct'
b='wrong'
c=w=0
while 1:e=`r(11)`+'+-*'[r(3)]+`r(11)`;x=input(e+'=')==eval(e);c+=x;w+=1-x;print(b,a)[x]+'!\nScore:',c,a,'|',w,b+'\n'
```
[That](http://textmechanic.com/Count-Text.html) counter says it's only 171 chars, but I've counted new lines since that's what we normally do in code golf.
Thanks to [flornquake](https://codegolf.stackexchange.com/users/7409/flornquake) for some improvements.
Ungolfed:
```
from random import *
num_correct = num_wrong = 0
while 1:
expression = str(randrange(11)) + '+-*'[randrange(3)] + str(randrange(11))
is_correct = input(expression + '=') == eval(expression)
num_correct += is_correct
num_wrong += 1 - is_correct
print ('wrong', 'correct')[is_correct] + '!\nScore:', num_correct, 'correct', '|', num_wrong, 'wrong\n'
```
[Answer]
# CJam, 90 bytes
Seems like I'm a little late to this question... as is my language, so per site rules, this answer can't officially be selected as the winner. But I had completed my answer for a recent question that was marked as a duplicate of this question and didn't want to let it go to waste, so I modified it a bit for this question.
```
{Bmr3mr"+-*"=Bmr]_o'=o~\~li=:R["correct":C"wrong":W?'!N"Score:"SUR+:USCS'|SVR!+:VSWNN]o1}g
```
Due to the interactive nature of the program, the online interpreter cannot be used. You must use the [Java interpreter](https://sourceforge.net/p/cjam/).
I normally post a lengthy explanation, but the code works in about as straightforward of a manner as you can get. That's not to say that I banged this answer out in all of a couple of minutes, though, as there was a fair amount of time spent searching for and making small optimizations.
[Answer]
## Javascript 169 chars
Here's a solution that doesn't use the console (does that break the rules?) but works via alert boxes (yeah I know...):
```
for(c=w=0;r=Math.random;){prompt(x=~~(r()*9+1)+"+-*"[~~(r()*3)]+~~(r()*9+1))==eval(x)?(m="correct",c++):(m="wrong",w++);alert(m+"!\nScore: "+c+" correct | "+w+" wrong")}
```
The attempts at golfing are quite weak, but this was just for fun right? :)
**EDIT**: Ungolfed version follows. I expanded variable names and split up the assignment of `x` into `a`, `op` and `b`. The logic is the same. Bear in mind that `~~(X)` == `Math.floor(X)` for positive `X`. This is just easier to type.
```
correct=wrong=0;
rand=Math.random;
while(1){
a=~~(rand()*9+1);
op="+-*"[~~(rand()*3)];
b=~~(rand()*9+1);
x=a+op+b;
if(prompt(x)==eval(x)){msg="correct";correct++}
else{msg="wrong";wrong++}
alert(msg+"!\nScore: "+c+" correct | "+w+" wrong");
}
```
[Answer]
## **C# - 283 Characters**
This is my solution in C# in 283 characters:
```
var r=new Random();int a=0,b=0,x=0,y=0;var w="";Action C=()=>Console.WriteLine(w);for(;;){x=r.Next(11);y=r.Next(11);int[]R={x+y,x-y,x*y};w=""+x+"+-*"[x%3]+y+"=";C();var f=Console.ReadLine()==""+R[x%3];x=f?a++:b++;w=(f?"correct":"wrong")+"!\nScore:"+a+" correct | "+b+" wrong\n";C();}
```
With more indentation, it looks like:
```
var r=new Random();
int a=0,b=0,x=0,y=0;
var w="";
Action C=()=>Console.WriteLine(w);
for(;;){
x=r.Next(11);y=r.Next(11);
int[] R={x+y,x-y,x*y};
w=""+x+"+-*"[x%3]+y+"=";C();
var f=Console.ReadLine()==""+R[x%3];
x=f?a++:b++;
w=(f?"correct":"wrong")+"!\nScore:"+a+" correct | "+b+" wrong\n";C();
}
```
[Answer]
# K, 155
```
k:l:0;
while[1;
1@(s:,/(($2?11),(1?"+-*"))0 2 1),"=";
-1@*$[(.:s)="I"$0:0;("correct!";l+:1);("wrong!";k+:1)];
-1"Score: ",($l)," correct | ",($k)," wrong\n\n"
]
```
[Answer]
## Haskell 286
```
import System.Random
main=0?0
s=show
a°b=s a++b
r=randomRIO
d=r(0,10)
p=putStr
c?w=do a<-d;b<-d;i<-r(0,2);let{(#)=[(+),(-),(*)]!!i;o="+-*"!!i};p(s a++o:b°"=");r<-getLine;let{u=fromEnum$read r/=a#b;d=c+1-u;v=w+u};p(["correct!\n","wrong!\n"]!!u);p("Score: "++d°" correct | "++v°" wrong\n\n");d?v
```
[Answer]
## VBA - 250
```
Sub t()
a=0
b=0
While 1
x=Int(Rnd()*11)
y=Int(Rnd()*11)
o=Int(Rnd()*3)
If InputBox(x & Array("+","-","*")(o) & y & "=")=Array(x+y,x-y,x*y)(o) Then r="Correct!":a=a+1 Else r="Wrong!":b=b+1
MsgBox r & vbCr & "Score:" & a & " correct|" & b & " wrong"
Wend
End Sub
```
Runs until the memory limit for the variables is reached, otherwise it runs 'forever'.
] |
[Question]
[
My user id is `106959`
How to check if the number is Fmbalbuena number?
First Step: Check if the number of digits is a multiple of 3: `6` = `3` \* `2`
Second step: Split the digits into even thirds: `106959 -> 10 69 59`
Third step: Subtract the first set of digits from the second modulo 10: `6` - `1` = `5`, `9` - `0` = `9`
Last step: Check that the result is the same as the third set of digits: `59 = 59`
## Sequence
Here is the sequence until `106959`
```
109, 110, 121, 132, 143, 154, 165, 176, 187, 198, 208, 219, 220, 231, 242, 253, 264, 275, 286, 297, 307, 318, 329, 330, 341, 352, 363, 374, 385, 396, 406, 417, 428, 439, 440, 451, 462, 473, 484, 495, 505, 516, 527, 538, 549, 550, 561, 572, 583, 594, 604, 615, 626, 637, 648, 659, 660, 671, 682, 693, 703, 714, 725, 736, 747, 758, 769, 770, 781, 792, 802, 813, 824, 835, 846, 857, 868, 879, 880, 891, 901, 912, 923, 934, 945, 956, 967, 978, 989, 990, 100090, 100191, 100292, 100393, 100494, 100595, 100696, 100797, 100898, 100999, 101000, 101101, 101202, 101303, 101404, 101505, 101606, 101707, 101808, 101909, 102010, 102111, 102212, 102313, 102414, 102515, 102616, 102717, 102818, 102919, 103020, 103121, 103222, 103323, 103424, 103525, 103626, 103727, 103828, 103929, 104030, 104131, 104232, 104333, 104434, 104535, 104636, 104737, 104838, 104939, 105040, 105141, 105242, 105343, 105444, 105545, 105646, 105747, 105848, 105949, 106050, 106151, 106252, 106353, 106454, 106555, 106656, 106757, 106858, 106959
```
You can generate the first N numbers, infinite numbers, Check if the number is Fmbalbuena number or get Nth number of the sequence
## Test cases
Truthy
```
106959
109
219
103222
666666000
777666999
```
Falsy
```
100
230
320
666666666
125466
1069592
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Checks if a given number is a Fmbalbuena:
```
S3äR`-T%Q*g3Ö
```
Could be 12 bytes by taking the input as a list of digits, removing the leading `S`.
[Try it online](https://tio.run/##yy9OTMpM/f8/2PjwkqAE3RDVQK1048PT/v83NDCzNLUEAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/2Djw0uCEnRDVAO10o0PT/uv8z/a0MDM0tRSx9DAUsfIEEQbGxkZ6ZiBgYGBgY65uTmQZWlpCRIDcgwNDXUMdAx1jIFKDXSMjA10jI0MoOqBQMfQyNQERIGNNYJqAmqPBQA).
We can add a leading `∞ʒD` to output the infinite sequence:
[Try it online.](https://tio.run/##yy9OTMpM/f//Uce8U5PSjQ9Pqz01Kdj48JKgBN0Q1cD//wE)
**Explanation:**
```
S # Split the (implicit) input-integer to a list of digits
3ä # (Try to) split it into three equal-sized parts
R # Reverse these parts from [A,B,C] to [C,B,A]
` # Pop and push all three lists separated to the stack
- # Subtract the digits of the top two lists: B-A
T% # Modulo-10
Q # Check if it's equal to C: B-A=C (1 if truthy; 0 if falsey)
* # Multiply this by the (implicit) input-integer
# (remains unchanged if the check was truthy or becomes 0 otherwise)
g # Pop and push its length
3Ö # Check if this is divisible by 3
# (after which it is output implicitly as result)
```
```
∞ # Push an infinite positive list: [1,2,3,...]
ʒ # Filter it by:
D # Duplicate the current integer
S3äR`-T%Q*g3Ö
# Same as above
# (after which the filtered infinite list is output implicitly as result)
```
[Answer]
# JavaScript (ES6), 66 bytes
Expects the input number as a string. Returns a Boolean value.
```
n=>![...n].some((d,i)=>i<(l=n.length/3)&(n[i+=l]-d+10)%10!=n[i+l])
```
[Try it online!](https://tio.run/##dZDNDoIwEITvvgVNNG2QWlqBNLEcfQJvlQPh39TWAJr49AicNFnnON9mMrO3/JUPRd89xsC6sppqNVmVeppSajM6uHuFcbnviEq7EzbKUlPZZmwPguyw1Z2vTBaUfsjINmSeWhyTkalwdnCmosY1GOlL/xzbd4bI5tuvMQpZLCOJCAAgl4fwreCcAyBexRgDWJIkM5NyDfyB6Gr1OTcD3BfK4gJyBWd/O82ChvDoCIP1TcvE6QM "JavaScript (Node.js) – Try It Online")
### How?
We don't explicitly test whether the length of the input number is a multiple of 3. When it's not, `l` is a non-integer value, both `n[i+l]` and `n[i+2*l]` are *undefined*, `n[i+l]-d+10` is *NaN*, and we end up testing `NaN != undefined`, which is true and makes the test fail as expected.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~13~~ ~~9~~ 8 bytes
```
ḍ₃\-ᵐtᵛ0
```
[Try it online!](https://tio.run/##NZZNimVFEIW38qhxtUTGX0ZOdCHqoBV/Bg1C29JI2xMF0YHg3AU4ddIg7qZqI@U5caNqkHkf737n3ZsRX1BfvH755bc/vvruG3169/bu9uLj293bT949/vrP48@/PP72992b1z989dHdT7z8@uWr73H9/uG/398/fPjz6eHfP3DTZy9w/ebhw1/y9PTpkjxx7m9LsOjqK1PV@1v2n4jc3/beuDynv8VnNSym8nwT/vCNhvfeidqRBNaEryW8iR@N37phCceSgWUTrY3lFH5Bah5HtX8QmDowDWCawHQD0wKmB5gJl1V8MGDWj@jALIBZArMNzAqYHWAuXBYwV2BuwNyBeQDzBOYbmBcwP8BCuCxgocDCgIUDiwAWCSw2sChgcYClcFnAUoGlAUsHljx0HC@WDSyLJ36AbeGygG0Ftg3YdmA7gO08LAdrUsA2z7mEywJWCqwMWDmwCmCVwGoDqwJWB9gRLgvYUWDHgB0HdgLYSWBnAzsF7Bzpssvs63RFRa8ai/GpsTvfF3vwpLDn6WaQzepgL9YV@7TR6s7CvqTzlkrnLZPOWy6dt/rQsad03trSeauk89bp5hKV7i/RdXWc6uo8tE7nqa/O01idp7k6T/fqPK3VeXpGAtHOs6tlRwrspp1nrp2H9uo86wJj39p5Vtp5drTzXKzzfFnnubYF4mad526d52Gd52mdhxbsPC/rPD/WeSHeebG886L1wG4tloR750V450V650U3E/byzkObdl5KdB6atfNSo/PSovPS21XJiM7LjEv2HZ2XFfUsP2VnSJ9Yv14/S4M9IjaR4v1sBu3Zw2PuM1G@gPLXlJNBORmUk0HZQcay22rFaTffuh/ROBSMQ8E4FIxt5@wVZ2Fd226KzfdyzgPnPHDOA2evBhss2A3B0oW12HSaoyA4CoKjoBs82ZXdQsl6J4uT3k5TZ06B5BRIWrHZypt9t9kkXdHN49/ROtNkDoBNlYr9X2zWYmcV26BYsz7gyjZ50WT6S2kOO/ywHQ9757DQh1U5dP/slniNxGsk1pHYRmIfiWMkzpF4j8Q1Ej/Lu0ZeHXlt5PWRN0beHHn3yFsj75VzRloZaddIqyOtjbQ@0sZImyPtHmnrkhYzSUbeNfLqyGsjr4@8MfLmyLtH3hp5ryFwRloZaddIqyOtjbQ@0sZImyPtHmnrkhYzUkbeNfLqyGsjr4@8MfLmyLtH3hp5ryFwRloZaddIqyOtjbQ@0sZImyPtHmnr@h8AM1s@/x8 "Brachylog – Try It Online") ([infinite sequence version](https://tio.run/##ATEAzv9icmFjaHlsb2cy/@KEleKJnOKGsOKCgSbhuoniiqX/4biN4oKDXC3htZB04bWbMP//))
Not sure how I missed that by making it about congruence to 0, I dodged any thorny sign issues in taking the last digit versus performing a proper mod 10.
```
ḍ₃ Split the input into three digit lists of similar lengths.
\ Check that the lengths are strictly equal, and transpose.
ᵐ For each triple,
- subtract the second digit from the sum of the first and third.
tᵛ0 Is the last digit of every difference 0?
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
¬∨﹪Lθ³⊙∕θ³﹪⍘⭆³§§⪪θ÷Lθ³λκ±¹χ
```
[Try it online!](https://tio.run/##VU1BCsIwEPyKxykotBSF4knxUrBV6AtCs6TBkLRxLfr6mNB6cGF2hmVnph@E750wIdy9tozWMW4ejZMv43Alq3jAlG03ZcTJfnDRs5aEabmsf2fxpI5jgMJCjRhRRgPXVtIbP@5Gozl5a8tr0F9FXCbikURLSjChSLrIszTHEIr8UO2rsJvNFw "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if the input is an Fmbalbuena number, nothing if not. Explanation:
```
θ Input as a string
L Length
﹪ ³ Is not divisible by `3`
∨ Logical Or
θ Input as a string
∕ ³ Reduced to a third in length
⊙ Any index satisfies
³ Literal integer `3`
⭆ Map over implicit range and join
θ Input string
⪪ ÷Lθ³ Split into three parts
§ Indexed by
λ Inner value
§ Indexed by
κ Outer index
⍘ ±¹ Interpreted as base `-1`
﹪ χ Is not divisible by `10`
¬ Logical Not
Implicitly print
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~19~~ 14 bytes
```
L3/₌ẎȯI÷‟-ȧ₀%⁼
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJMMy/igozhuo7Ir0nDt+KAny3Ip+KCgCXigbwiLCIiLCJbMSwgMCwgNiwgOSwgNSwgOSwgMl0iXQ==)
Checks whether an input number is a Fmbalbuena number. Takes input as a list of digits.
*can't believe I forgot to handle the case where the length isn't divisible by 3...*
*-5 thanks to Fmbalbuena*
## Explained
```
L3/₌ẎȯI÷‟-ȧ₀%⁼
L # Push the length of the input
3/ # divide that by 3
₌Ẏȯ # and push input[0:that], input[that:-1]
I # split input[that:-1] into two lists
÷ # and dump that onto the stack - the stack is now [first N/3, remaining first half, remaining second half]
‟ # rotate the stack right - this sets it up for the subtraction
-ȧ # subtract the first N/3 digits from the second half and take the absolute value
₀% # and modulo by 10
⁼ # does that exactly equal the first half?
```
[Answer]
# [Factor](https://factorcode.org/) + `grouping.extras`, ~~75~~ 45 bytes
```
[ 3 n-group first3 spin v- [ 10 rem ] map = ]
```
Returns whether or not the input is a Fmbalbuena number.
[](https://i.stack.imgur.com/NFK6E.png)
## Explanation
```
! { 1 0 6 9 5 9 }
3 n-group ! { { 1 0 } { 6 9 } { 5 9 } }
first3 ! { 1 0 } { 6 9 } { 5 9 }
spin ! { 5 9 } { 6 9 } { 1 0 }
v- ! { 5 9 } { 5 9 }
[ 10 rem ] map ! { 5 9 } { 5 9 }
= ! t
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Dœs3µZI%⁵z-Ḣ⁼Ṫ
```
A monadic Link accepting a positive integer that yields `1` if it is Fmbalbuena, or `0` if not.
**[Try it online!](https://tio.run/##y0rNyan8/9/l6ORi40NbozxVHzVurdJ9uGPRo8Y9D3eu@n90z@H2R01r3P//jzY0MLM0tdRRMDQAEkaGYJaxkZGRjoIZGBgYGOgomJubA5mWlmBZIN/IGEgYGxnAFAEBUMbI1ARMg000igUA "Jelly – Try It Online")**
Or test every positive integer up to and including \$106959\$ [here](https://tio.run/##AS4A0f9qZWxsef//RMWTczPCtVpJJeKBtXot4bii4oG84bmq/8OH4oKsVP//MTA2OTU5 "Jelly – Try It Online").
### How?
```
Dœs3µZI%⁵z-Ḣ⁼Ṫ - Link: positive integer, I
D - digits of I
3 - literal three
œs - split the digits into three equal(ish) parts
(if not equally splittable leftmost get longer first)
µ - start a new monadic chain with X=that as the argument
Ṫ - tail X (gets the digits in the last part and modifies X)
Z - transpose the remaining parts
I - deltas
⁵ - literal ten
% - modulo (the deltas)
- - literal minus one
z - transpose with filler -1 (avoiding false positives like 1009)
Ḣ - head
⁼ - does that equal the tail we removed?
```
[Answer]
# [R](https://www.r-project.org/), 65 bytes
```
function(x,y=matrix(x,,3))!any((y[,2]-y[,1])%%10-y[,3],sum(x,-y))
```
[Try it online!](https://tio.run/##nZLBCsIwDIbvvoWHQQMdtqnbqKNPIhPq5lBwFeYG7dPXrgfPxhxCDv@X/AmZ4zjZ53W9OWviuLp@ebwc8zyYyS7zw6eSK4C9dYGxcObYlSnLDopCiq1UHX@vU5KVASB6I0WtK90OxheHJLkw19/tzDycZCkz1X4nsgF2G0GSoyR2V4hIIeocQggK1DRNgrQmeMvmSENQkeQKBX3vFKTzYnUkEvlB8J/j/s7EDw "R – Try It Online")
Input as list of digits; checks whether this is a 'Fmalbuena' number.
[+24 bytes](https://tio.run/##ZY/NCoMwDMfve4sdCimrLE2n0oFPMhx0MjdBK4hCfXqXeZl1OYTkl/zzMSx159rH9PSuWOrJV2PTewhqLjo3Dk2AIM5C4x3w2vYvjRCkFAyUMlIeffV2AyMhzMn5GWC@KSoT9rpc276hKeVvCWjMbGrlYUuilPSuaohoS7LVEHEL8zxnaC1rI3HURCZKDeH/XLZoPaWXHVkf4IuWDw) for input as integer.
Pretty straightforward, except that we can check whether length of `x` is divisible by 3 using `sum(x,-y)` instead of `length(x)%%3` (or its usual [R](https://www.r-project.org/) golf `sum(x|1)%%3`), since we know that all elements of `x` must be non-negative, and the first one must be positive.
[Answer]
# [Python3](https://python.org), 246 bytes
This can probably be cut down a bit, but I didn't see a Python answer, so I thought I'd try it out. Just counting the actual code in the byte count, not the characters assigning the `n` variable.
```
n=106959
c=lambda:int(len(str(n))/3);f=lambda z,x,y:int(list(z[x])[y])
j=str(n);a=[j,list(j),len(list(j))];
if(len(a[0])%3==0):z=[a[0][x:x+c()]for x in range(0,a[2],c())];p="%s%s"%(f(z,1,0)-f(z,0,0),f(z,1,1)-f(z,0,1));print(p==z[-1:][0])
else:print(False)
```
[Answer]
# J, 64 bytes
Check whether a number is Fmbalbuena. The input is a number as a string, for example `'219'`. Yield `1` if the number is Fmbalbuena, `0` otherwise.
```
([:>(2{])((9|~[)=9|~])&.>(1{])-&.>0{])(]$~3,3%~#)".&.>(#$1<;.1])
(#$1<;.1]) split into digits (characters)
".&.> convert digits into real digits
(]$~3,3%~#) reshape into thirds
([:>(2{])((9|~[)=9|~])&.>(1{])-&.>0{]) substract modulo 9 and check for equality
```
It can probably golfed a lot more but I am helpless when it comes to performing operations on cells.
] |
[Question]
[
Odd prime numbers are either in the form of `4k+1` or `4k+3` where `k` is a non-negative integer. If we divide the set of odd prime numbers into two such groups like this:
```
4k+3 | 3 7 11 19 23 31 43 47 59 67 71
|
4k+1 | 5 13 17 29 37 41 53 61 73
```
we can see that the two groups are kind of *racing* with each other. Sometimes the so-called 'upper' group wins and sometimes the 'lower' one is on track. In fact, [Chebyshev discovered that](https://en.wikipedia.org/wiki/Chebyshev%27s_bias) in this race, the upper group wins slightly more often.
## The problem
Let's assume that we are interested in knowing the shape of this race track up to a certain number. Something like this:
[](https://i.stack.imgur.com/PCLJD.png)
The upper and lower horizontal lines indicate that the next prime stays in the same group, while the slanted lines indicate a 'jump' from one group to the other.
Now assume that the underline character `_` represents a lower horizontal line and the overline character `‾` (U+203E) represents an upper one. The slanted lines are represented by slash `/` or backslash `\` characters.
## Challenge
Write a program or function that gets a number `N` as input, and draws this prime race track up to `N`, in a *kind of* ASCII-art-form described as above (Well, it's not an actual ASCII-art since it would contain a non-ASCII character).
## Rules
* `N` is an integer and not necessarily a prime number. Draw the race path for the primes up to, (and maybe including) `N`.
* For a valid `N` as input, the output shall only be composed of these four characters `‾_/\`. No other character, space or separator is allowed (except maybe at the end of output).
* The output can either be in a text file or stdout or wherever supports displaying those characters. But an actual plot (like the blue figure above) is not desired.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Examples
Here is a list of possible inputs and their acceptable outputs.
```
N < 5 no output or maybe an error message whatsoever
N = 5 \
N = 20 \/‾\_/
N = 100 \/‾\_/‾\/\_/‾\/\/‾\/‾\_
```
## Trivia
The resulting plots of this challenge may actually resemble the *derivative* of the plots shown in [there](https://www.makethebrainhappy.com/2018/10/chebyshev-bias.html).
[Answer]
# [Python 2 (IronPython)](http://ironpython.net), 87 bytes
I'm using IronPython here to display the unicode character `‾`, since Python can't print it.
```
P=a=b=1
s=''
exec"if P%a:s+='\/‾_'[b%4/2-a%4];b=a\nP*=a*a;a+=1\n"*input()
print s[2:]
```
[Try it online!](https://tio.run/##K6gsycjPM9LNLMrP@6@skJyfkpmXbqVQWpKma/E/wDbRNsnWkKvYVl2dK7UiNVkpM00hQDXRqljbVj1G/1HDvnj16CRVE30j3URVk1jrJNvEmLwALdtErUTrRG1bw5g8Ja3MvILSEg1NroKizLwSheJoI6vY//8NDQwA "Python 2 (IronPython) – Try It Online")
## Explanation
The idea of calculating primes comes from [this answer](https://codegolf.stackexchange.com/a/27022/88546), which uses Wilson's theorem. To figure out which character to print, we use the following formula: \$ \frac{b \bmod 4} 2 - a \bmod 4 \$, where \$ a \$ and \$ b \$ represent the current and previous prime numbers. Here is a table to show how this works:
```
a mod 4 | b mod 4 | a'/2-b'
---------+---------+---------
1 | 1 | -1
1 | 3 | -3
3 | 1 | 0
3 | 3 | -2
```
And in Python negative indices wrap around to the end of the string, so each index maps to its own character.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~31~~ ~~26~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
…\/_ŽW ç«ÀIÅP¦4%üeè
```
-5 bytes by taking inspiration from [*@HyperNeutrino*'s Jelly answer](https://codegolf.stackexchange.com/a/203541/52210).
-7 bytes thanks to *@Grimmy*.
Outputs as a list of characters.
[Try it online](https://tio.run/##ASsA1P9vc2FiaWX//@KAplwvX8W9VyDDp8Krw4BJw4VQwqY0JcO8ZcOo/0r/NTAw) (the `J` in the footer is to join the list together to pretty-print it).
**Explanation:**
```
…\/_ # Push the string "\/_"
ŽW # Push compressed integer 8254
ç # Convert it to a character with this codepoint: "‾"
« # Append it to the earlier string: "\/_‾"
À # And rotate it once to the left: "/_‾\"
IÅP # Push a list of all primes <= the input-integer
# i.e. 50 → [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]
¦ # Remove the first value
# → [3,5,7,11,13,17,19,23,29,31,37,41,43,47]
4% # Take modulo-4 on each value
# → [3,1,3,3,1,1,3,3,1,3,1,1,3,3]
ü # For each overlapping pair:
# → [[3,1],[1,3],[3,3],[3,1],[1,1],[1,3],[3,3],[3,1],[1,3],[3,1],[1,1],[1,3],[3,3]]
e # Get the number of permutations; short for ⌊a!/|a-b|!⌋
# → [3,0,6,3,1,0,6,3,0,3,1,0,6]
è # And index each into the earlier created string
# (0-based and with wraparound, so the 6 is index 2 in this case)
# → ["\","/","‾","\","_","/","‾","\","/","\","_","/","‾"]
# (after which the result is output implicitly as result)
```
[See this 05AB1E tip of mine (section *How to compress large integer?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ŽW` is `8254`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 102 bytes
TIO doesn't display U+203E...
```
""<>(Partition[Prime@Range[2,PrimePi@#]~Mod~4,2,1]/.{{3,1}->"\\",{3,3}->"‾",{1,1}->"_",{1,3}->"/"})&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X0nJxk4jILGoJLMkMz8vOqAoMzfVISgxLz012kgHzAvIdFCOrfPNT6kz0THSMYzV16uuNtYxrNW1U4qJUdIBso1B7EcN@4AcQ4hEPJgJFtdXqtVU@w80Ka9EwSE92jSWC842MkDiGBoYxP7/DwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 50 bytes
```
1('/^\_'{~[:(+_1&|.*1&=)1+2*@-/\4&|)@}.(#~1&p:)@i.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DTXU9eNi4tWr66KtNLTjDdVq9LQM1Ww1DbWNtBx09WNM1Go0HWr1NJTrDNUKrDQdMvX@a3KlJmfkK6jHqCvYKqQpmMG4IHP01RV0rYCCRoYoonEx@lASRIDsgygzNDD8DwA "J – Try It Online")
Had to replace `‾` with `^` because the formatting on TIO screws up otherwise.
This uses < N convention.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
ÆRḊ%4ḄƝṣ9ị“\/_”j⁽ø¤Ọ
```
[Try it online!](https://tio.run/##ATUAyv9qZWxsef//w4ZS4biKJTThuITGneG5oznhu4vigJxcL1/igJ1q4oG9w7jCpOG7jP///zEwMA "Jelly – Try It Online")
-3 bytes thanks to Jonathan Allan
# Explanation
```
ÆRḊ%4ḄƝṣ9ị“\/_”j⁽ø¤Ọ Main Link
ÆR Primes up to N
Ḋ All but the first (3, 5, 7, 11, ...)
%4 Modulo 4
ḄƝ Convert each pair (overlapping run of 2) to binary (even though the digits are 1 and 3, this still works because it's just 2 x first digit + second digit) - 1,1: 3; 1,3: 5; 3,1: 7; 3,3: 9
ṣ9 Split on 9 (the upper bar)
ị“\/_” Index into "\/_" (3 is _, 5 wraps around to /, 7 wraps around twice to \)
j⁽ø¤ Join on 8254
Ọ Convert from char code to character; doesn't affect characters, only the 8254s
```
[Answer]
# JavaScript (ES6), 86 bytes
```
n=>(g=x=>x>n?'':['\\_/‾'[(P=n=>n%--d?P(n):d<2)(d=x)&&(q==(q=x%4))|q&2]]+g(x+1))(q=4)
```
[Try it online!](https://tio.run/##ZckxDoIwFIDh3XvQvhdShQYX4itXYAdiCIUGQ1oRYzo4eDIP40VqV@PwL99/6R/9Ntzm611Yp8cwUbCkwJAn5ZWtOC8b3rbnw@f15g3UFK9NhNBVDRZLfZIImjwyBitRzCcF4nNlsutSAz7NEaMWGAZnN7eM@8UZmOCIuPsVmf1RnkULXw "JavaScript (Node.js) – Try It Online")
### Commented
```
n => ( // n = input
g = x => // g is a recursive function taking the current integer x
x > n ? // if x is greater than n:
'' // stop recursion
: // else:
[ // make sure to turn undefined into an empty string
'\\_/‾'[ // pick the relevant character:
( P = n => // P is a helper function taking n:
n % --d ? // decrement d; if d does not divide n:
P(n) // try again until it does
: // else:
d < 2 // return true if d = 1 (i.e. n is prime)
)(d = x) // initial call to P with n = d = x
&& // if x is not prime, ['\\_/‾'[false]] ~> empty string
( // if x is prime:
q == // yield 1 if q is equal to ...
(q = x % 4) // ... the new value of q which is x mod 4
) | q & 2 // bitwise OR with q & 2 for the direction
] // end of character lookup
] + g(x + 1) // add the result of a recursive call with x + 1
)(q = 4) // initial call to g with x = q = 4
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~105 103 96 89~~ 88 bytes
```
f=lambda n,i=3,j=5,t=24:n//j*" "and"\/‾_"[i%4//2-j%4]*(P:=t%j>0)+f(n,[i,j][P],j+1,t*j)
```
[Try it online!](https://tio.run/##jY9RioMwEIbfPcUQELSNjbUWFml6hr6rBJdWNqHGEPNSSmFPtofZi7iJUsmWfVgImZn83/yZUTfz0cvdm9Lj2NJr072fG5CY0x0WdI8NzfJCEiJWCFAjz6gi359fDJU8zAnJEhHm9So6FdSE4pjG6zaSuORY1OWpxmK9xWYl4pF3qtcGhtsQtL2GK5cX4NLVm8GcuSwCsH9CIweg0DUqGoy2iuYKT/BmUFduIpQcURxbVlusjbg0kZxqpV3eorssDvkDkiPcdXHI9g8o75alzvlRo3jcAjg12M@xCrJ0TtxWFSPBNk392t1kiXOYFAf@j2S/gKf0ZOdj81mbkuWB@TZsaWZe5x8WpHrpJS9DPBucJVsG8hDPlPm7/AA "Python 3.8 (pre-release) – Try It Online")
*-1 byte thanks to @xnor!*
### Explanation:
This is a recursive function that increases `j` from `5` to `n`. If `j` is prime, the function compares it to the previous prime `i` to determine the race track character.
The following expression evaluates to `1` or `0` depending on whether `j` is prime or not:
```
t%j>0
```
where `t` is `factorial(j-1)`. This uses [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem), taken from [@xnor's answer](https://codegolf.stackexchange.com/a/27022/92237) on another prime problem.
Given 2 consecutive prime `i` and `j`, the following code determines the character (shamelessly stolen from [@dingledooper's answer](https://codegolf.stackexchange.com/a/203517/92237)):
```
"\/‾_"[i%4//2-j%4]
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 65 bytes
```
.+
$*
1
_1$`
^.{6}|_(11+)\1+(?!1)|1111|1(1?)
$2
_1
/1
1/
‾
1_
\
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYvLkCveUCWBK06v2qy2Jl7D0FBbM8ZQW8Ne0VCzxhAIagw1DO01uVSMgOq49A25DPW5HjXs4zKM54r5/9/QwAAA "Retina 0.8.2 – Try It Online") Explanation:
```
.+
$*
```
Convert `N` to unary.
```
1
_1$`
```
Count up to `N`, using `_` to separate the unary values, thus assuming all odd primes have a remainder of 1 (modulo 4) by default.
```
^.{6}|_(11+)\1+(?!1)|1111|1(1?)
$2
```
Delete `1`, `2` and their separators; delete all composite numbers and their separators; reduce the odd primes modulo 4, and identify the primes with a remainder of 3 (modulo 4).
```
_1
/1
```
Still assuming that the prime previous to a prime with a remainder with 3 has a remainder of 1, change the `_` to a `/`.
```
1/
‾
```
But if it turns out that the previous prime also has a remainder of 3, then change the `/` to a `‾`.
```
1_
\
```
Any remaining primes with a remainder of 3 must have a next prime with a remainder of 1, so change the `_` to a `\\`.
[Answer]
# [Erlang (escript)](http://erlang.org/doc/man/escript.html), 118 bytes
Erlang doesn't support negative indices so I had to do my own. (Also it doesn't display `‾`, so it's replaced with `^`.)
```
p([_])->[];p([H|T])->[lists:nth(H rem 4+1rem(hd(T)rem 4),"_/\\^")|p([A||A<-T,A rem H>0])];p(X)->tl(p(lists:seq(2,X))).
```
[Try it online!](https://tio.run/##fYyxDoIwEIZ3nqJhuosFgeiChoSNB2AgASREqzQpFdsmLn33WnExMfGWuy//fx9TYpS3iOmz4otxgVugHXqMirY/@LOy9QqCa6NzaSaoiGIz2W1Sv2C6QI0rIw2HbdedQrT@rbS2PEY1LddyVSQ9vnWNVxkBC3x0mj0gow0ixm4euYQBSVQExA@/59en4ob58h6RepYCkP6EWfIvTZOvOHYv "Erlang (escript) – Try It Online")
# Replaced formula
```
a % 4 | b % 4 | a + 1%b
---------+---------+---------
1 | 1 | 1
1 | 3 | 2
3 | 1 | 3
3 | 3 | 4
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 26 bytes
```
J'¯†!"¦/_"x9ẊoB2em%4t↑İp
```
[Try it online!](https://tio.run/##ASoA1f9odXNr//9KJ8Kv4oCgISLCpi9fIng54bqKb0IyZW0lNHTihpHEsHD///8 "Husk – Try It Online")
] |
[Question]
[
## Your task
You must write a program, to print a **reverse Fibonacci series**, given a number.
## Input
A **non-negative** integer ***N***.
## Output
You must output all the Fibonacci numbers from ***Fk*** to ***F0***, where ***k*** is the smallest non-negative integer such that ***Fk*** ‚â§ ***N*** ‚â§ ***Fk+1***.
## Example
```
IN: 5
OUT: 5 3 2 1 1 0
```
***If input isn't a Fibonacci number, the series should begin from the closest Fibonacci number less than the input.***
```
IN: 15
OUT: 13 8 5 3 2 1 1 0
```
***If input is 1, the series should be.***
```
IN: 1
OUT: 1 0
```
## Scoring:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte count wins.
## Leaderboard
```
var QUESTION_ID=136123,OVERRIDE_USER=60869;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# Haskell, 52 bytes
```
p=0:scanl(+)1p
f 1=[1,0]
f n=reverse$takeWhile(<=n)p
```
Second line is necessary for the `n = 1` edge-case. I wasn't able to get around it.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḤḶÆḞṚ>Ðḟ
```
A monadic link taking a number and returning the list of numbers.
**[Try it online!](https://tio.run/##AR8A4P9qZWxsef//4bik4bi2w4bhuJ7huZo@w5DhuJ////81 "Jelly – Try It Online")**
Note: I am assuming 1s are not both required, if they are the previous 9 byter works: `+2ḶµÆḞṚfṖ`
### How?
```
ḤḶÆḞṚ>Ðḟ - Link: number, n
·∏§ - double n (this is to cater for inputs less than 6)
·∏∂ - lowered range of that -> [0,1,2,...,2*n-1]
ÆḞ - nth Fibonacci number for €ach -> [0,1,1,...,fib(2*n-1)]
·πö - reverse that
Ðḟ - filter discard if:
> - greater than n?
```
...the reason this only outputs `[1,0]` for an input of `1` is that the unfiltered list does not contain `fib(2)`, the second `1`.
The 9 byter works by adding two, `+2`, to form the lowered range `[0,1,2,...,n,(n+1)]` rather than doubling and then filter keeping, `f`, any results which are in a popped, `Ṗ`, version of that same list, `[0,1,2,...,n]` (the value accessed by making a monadic chain, `µ`).
[Answer]
# [Python 2](https://docs.python.org/2/), ~~62~~ 59 bytes
```
n,l,a,b=input(),[],0,1
while a<=n:l=[a]+l;a,b=b,a+b
print l
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P08nRydRJ8k2M6@gtERDUyc6VsdAx5CrPCMzJ1Uh0cY2zyrHNjoxVjvHGqQqSSdRO4mroCgzr0Qh5/9/Q1MA "Python 2 – Try It Online")
[Answer]
# [Neim](https://github.com/okx-code/Neim), 5 bytes
```
f‚ÇÅ>ùïñùê´
```
[Try it online!](https://tio.run/##y0vNzP3/P@1RU6Pdh7lTp32YO2H1//@mXAA "Neim – Try It Online")
# Explanation
```
f infinite list of fibonacci numbers
‚ÇÅ> get input and increment it
ùïñ first b elements of a
ùê´ reverse the list
```
I feel like this could be golfed more. `‚ÇÅ>` feels a bit inefficient...
[Answer]
# Dyalog APL, 28 bytes
```
{x/⍨⍵≥x←⌽{1∧+∘÷/0,⍵/1}¨⍳2×⍵}
```
Requires `‚éïIO‚Üê0`.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HfVE//R20TDLjSgGR1hf6j3hWPerc@6lxaAeQ/6tlbbfioY7n2o44Zh7frG@gApfQNaw8BlWw2OjwdyKsFGtG7qhrI0lFQf9Q2SV1HIQ0kfGiFoTZIkQEA)
**How?**
`{1‚àß+‚àò√∑/0,‚çµ/1}` - apply fibonacci
`¨⍳2×⍵` - to the range `0` .. `2n`
`x←⌽` - reverse and assign to `x`
`x/‚ç®` - filter x with
`⍵≥x` - the function `x <= n`
[Answer]
# [Python 2](https://docs.python.org/2/), 58 bytes
*Note: invalidated by recent specification change* (`1` -> `(1, 1, 0)`)
```
n=input()
r=1,0
while r[0]<=n:r=(r[0]+r[1],)+r
print r[1:]
```
A full program accepting from stdin and printing (a tuple representation of) the numbers in the reversed order.
**[Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERDk6vI1lDHgKs8IzMnVaEo2iDWxjbPqshWA8TULoo2jNXR1C7iKijKzCsBShtaxf7/b2gEAA "Python 2 – Try It Online")** or see a [test suite](https://tio.run/##JY5BDsIgEADP3VdwA1IOhSORlzQcsEVLUheyxaivx6K3SSaTTPnULaNpS14jc4xz3tAlLM8qJJDTaoLXlvbIaJ78xaElJzqONGuv5EhQKGE9tba@nTn8YreHx3UNtsajwi0T68ASMgp4j8IYaWH4l90oGOI7LqJfyPYF "Python 2 – Try It Online")
[Answer]
# Mathematica, 46 bytes
```
Reverse@Select[Array[Fibonacci,t=1+#,0],#<t&]&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvs/KLUstag41SE4NSc1uSTasagosTLaLTMpPy8xOTlTp8TWUFtZxyBWR9mmRC1W7X9AUWZeiYJDmoKDIRcS2/Q/AA "Mathics – Try It Online")
thanx to @JungHwan Min for -16 bytes
[Answer]
# [Perl 6](https://perl6.org), 40 bytes
```
{[R,] 0,1,*+*...^{2>$_??$^a==1!!$^b>$_}}
```
[Test it](https://tio.run/##ZZDBbsIwEETv/oqFRpUdFguDQAjLwAf0VPVWNVWabKWIFCzioEZRvj21SeHCcWeeZmfX0rlc9XVFcFnJTLOfBp6zU05g@vb9FT9ghgrjSSylTNr5Nvrc7aIkNUaNRlHy5eeu658eyDgYIWvvqHJggDOAJZgt8CUucO5JhTOBXlWDrBa4xgdvsK6T0Cy0fPN5mtkyPcLkGq7Z9@n8v2fqadgcqOFRcbS1EwibS1rWxPf0aylzlAsQ0ProoprmRLZsIFx74@VLUTmEO40wHpxQ5K5K65/GxVizrv8D "Perl 6 – Try It Online")
## Explanation:
* `{…}` create a bare block lambda with implicit parameter `$_`
* `[R,] **LIST**` is a Left fold using the reverse meta-op `R` combined with the comma op `,`.
(shorter than `reverse`)
* `0, 1, *+* ...^ **Callable**` produces a Fibonacci sequence that stops on the value before **`Callable`** returns a `True` value.
The remaining code is a bit complicated as it has to return `True` if the original input is `1` and the second to latest value is `1`. This is so that the full lambda returns `(1,0)` instead of `(1,1,0)`.
```
{ # bare block lambda with two placeholder params ÔΩ¢$aÔΩ£ and ÔΩ¢$bÔΩ£
2 > $_ # is the original input smaller than 2
?? # if it is
$^a == 1 # check if the second to latest value is 1
!! # otherwise
$^b > $_ # check if the latest value is bigger than the original input
}
```
---
If the code was allowed to return `(1,1,0)` when given the value `1`, it can be dramatically shorter at 22 bytes:
```
{[R,] 0,1,*+*...^*>$_}
```
[Test it](https://tio.run/##ZZDBCsIwEETv@YpBRJK6BqsoYqj4AZ7Em6hIu0KxarCpWMRvr6lVLx535jGzu5av2bgqcsZtrGMjTiU68SVhRNVjvaQN@hRS0A201ttg1t49K0/MHecOEaQARohmkCMa0sCTIfUVeTVs5HBIE/rzGuszKyPq9pVPNMJm@zO673gjDpfrp6nneUyPXMp2eraFU4TpbZ8VLOd8txw7ThQUHj48zXsJs81K1Fd8eb1Ic0f40YRW49Sr/FRt/TOkahnxrF4 "Perl 6 – Try It Online")
In this case `* > $_` creates a *WhateverCode* lambda that in this use-case will return `True` if the generated value is greater than the original input.
Everything else is the same as above.
[Answer]
# Mathematica, ~~52~~ 41 bytes
```
{1,0}//.{a_,b_,c___}/;a+b<#:>{a+b,a,b,c}&
Fibonacci@Range[Floor[Log[GoldenRatio,1+‚àö5#]],0,-1]&
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
ÎÅF)˜RIi¦
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cN/hVjfN03OCPDMPLfv/39AUAA "05AB1E – Try It Online")
If `[1, 1, 0]` is valid output for **1** this would be `ÎÅF)˜R` at 6 bytes
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~20~~ ~~18~~ ~~17~~ 13 bytes
Thanks a lot @Zgarb for telling me about `İf` which is a built-in for Fibonacci numbers, this saved me `4` bytes:
```
§↓=1ȯ↔`↑:0İf≤
```
[Try it online!](https://tio.run/##ASMA3P9odXNr///Cp@KGkz0xyK/ihpRg4oaROjDEsGbiiaT///8yMA "Husk – Try It Online")
### Ungolfed/Explanation
```
-- implicit input N
İf -- get all Fibonacci numbers,
:0 -- prepend 0,
`‚Üë ‚â§ -- take as as long as the number is ‚â§ N,
ȯ↔ -- reverse and
§ =1 -- if input == 1:
‚Üì -- drop 1 element else no element
```
---
## Old answer without built-in (17 bytes)
The old answer is quite similar to [shooqie](https://codegolf.stackexchange.com/a/136137/48198)'s Haskell answer:
```
§↓=1ȯ↔`↑ȯƒo:0G+1≤
```
[Try it online!](https://tio.run/##ASgA1/9odXNr///Cp@KGkz0xyK/ihpRg4oaRyK/Gkm86MEcrMeKJpP///zIw "Husk – Try It Online")
### Ungolfed/Explanation
A really short way to compute Fibonacci numbers in Haskell is to define a recursive function like this (also see the Haskell answer):
```
fibos = 0 : scanl (+) 1 fibos
```
Essentially that code computes the [fixpoint](https://en.wikipedia.org/wiki/Fixed-point_combinator) of the function `\f -> 0 : scanl (+) 1 f`, so you can rewrite `fibos` in an anonymous way like this:
```
fix (\f -> 0 : scanl (+) 1 f)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/nysts0IhTcEWiDXATE0urtzEzDygSEFRZl6JgooCSFgjJk1B107BQMFKoTg5MS9HQUNbU8EQqPr/fwA "Haskell – Try It Online")
This corresponds to the [Husk](https://github.com/barbuz/Husk) code `(ƒo:0G+1)`, here's the remaining code annotated:
```
-- implicit input N
ȯƒo:0G+1 -- generate Fibonacci numbers (ȯ is to avoid brackets),
`‚Üë ‚â§ -- take as as long as the number is ‚â§ N,
ȯ↔ -- reverse and
§ =1 -- if input == 1:
‚Üì -- drop 1 element else no element
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 70 bytes
```
n=>{var t="0";for(int a=0,b=1,c;b<=n;c=a,a=b,b+=c)t=b+" "+t;return t;}
```
[Try it online!](https://tio.run/##dcuxCsIwEIDhvU9xdGpplBYRh/S6CE46iINzEmMJ1Ask14KUPnusu87f/5u4MT7YNEZHPdzeke1LZmZQMcJ1ziIrdgYm7x5wUY6Kcs5OI5nWEQuIHNargx4TYTdPKgBjXufy6UOxFqCwFhobYaRukaRBJRRqoSs0JaOucsgrlsHyGAhYLklmR0/RD3Z7D47t2ZEt@mJXlr/h8A@a/VeWJX0A "C# (.NET Core) – Try It Online")
Input is an integer into the Lambda. Output is a space-delimited string of the fibonacci sequence in reverse.
[Answer]
# Javascript (ES6), 42 bytes
```
f=(n,a=0,b=1)=>b>n|a>=n?a:f(n,b,a+b)+" "+a
```
Alternative, if `f(1)` = `1 1 0`
```
f=(n,a=0,b=1)=>b>n?a:f(n,b,a+b)+" "+a
```
Example code snippet:
```
f=(n,a=0,b=1)=>b>n|a>=n?a:f(n,b,a+b)+" "+a
console.log(f(5))
console.log(f(15))
console.log(f(1))
```
[Answer]
# [Röda](https://github.com/fergusq/roda), 58 bytes
```
{|k|a=0;b=1{{[a];b=a+b;a=b-a}while[a<k,b<=k];[a]}|reverse}
```
[Try it online!](https://tio.run/##TYoxDsIwEARr3ytOaQkSKWhI/ADeEKLoTC4QBezItqCw/XZjiQJWW6x2xpqJcgAsmU/ykkNcI8lDq2QTQk9DGbRTLUm1p/S@Lw/uqVtr1cl1aAtP0fKLreOUE8CTFo0BxEblOWvPN7Y4YsTZWPTs/HglxzgZEGKzi/ZYSYlV/WMFzH9mxK82gpiMZkj5CE3pBw "Röda – Try It Online")
] |
[Question]
[
You will be given a positive integer as input.
The integer is the board of a seesaw.
Th integer will not have leading zeroes. You may take this input however you like.
Your task is to output the location of the pivot point of this seesaw, such that the board would balance.
A board balances if the moments on each side are equal in magnitude. A moment is calculated by multiplying the force by the distance from the pivot point. In this case, the force is equal to the digit.
For the integer `100` with a pivot point below the first `0`, the moment on the left is 1x1=1. The moment on the right is 0x1=0. If the pivot point was below the second `0`, the moment on the left would be 2x1=2 (because the `1` is now 2 away from the pivot).
For example, for the integer `31532` the pivot goes underneath the number 5. This is because the moments on the left are 3x2 + 1x1 = 7 and on the right the moments are 3x1 + 2x2 = 7.
The output for this integer is `3` because the pivot goes underneath the 3rd digit.
If the integer cannot be balanced, your code does not have to do anything - it can hang, error, output nothing - whatever you want.
Note that a pivot cannot go between two numbers. The pivot location must be an integer.
## Test cases:
```
31532 -> 3
101 -> 2
231592 -> 4
8900311672 -> 5
```
Standard loopholes apply, this is code golf so shortest answer wins.
[Answer]
# [Haskell](https://www.haskell.org/), ~~64~~ ~~62~~ ~~59~~ ~~57~~ ~~45~~ ~~35~~ 31 bytes
```
d l=sum(zipWith(*)[1..]l)/sum l
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0Uhx7a4NFejKrMgPLMkQ0NLM9pQTy82R1MfKKqQ8z83MTPPtqAoM69EJUUlN7FAoyg1MUWvoLQoVVOlOCO/XMHCwMjA4j8A "Haskell – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 66 bytes
```
sum(1:length(n<-strtoi(strsplit(paste(scan()),"")[[1]]))*n)/sum(n)
```
[Try it online!](https://tio.run/##K/r/v7g0V8PQKic1L70kQyPPRre4pKgkP1MDSBUX5GSWaBQkFpekahQnJ@ZpaGrqKClpRkcbxsZqamrlaeqD9OZp/rewNDAwNjQ0Mzf6DwA "R – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Dµæ.J:S
```
[Try it online!](https://tio.run/##y0rNyan8/9/l0NbDy/S8rIL///9vYWlgYGxoaGZuBAA "Jelly – Try It Online") or [verify all inputs at once](https://tio.run/##y0rNyan8/9/l0NbDy/S8rIL/H25/1LTm/39jQ1NjIx1DA0MdIyDT0kjHwtLAwNjQ0MzcCAA).
[Answer]
# [J](http://jsoftware.com/), 29 bytes
```
[:>:@(+/%~]+/@:*i.@$)10#.inv]
```
[Try it online!](https://tio.run/##y/r/P83WKtrKzspBQ1tftS5WW9/BSitTz0FF09BAWS8zryz2f2pyRr5CmoKxoamxEReUY2hgCGMaASUs4RIWlgYGxoaGZuZG/wE "J – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 64 bytes
```
({({}[((((()()()){}){}){}){}]<>{})<>}<>)({()<({}[({})])>}<>)
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6Nao7o2WgMENEFQs7oWjmJt7IC0jV2tjZ0mUJ2mDVgpUChWEyz2/7@FpYGBsaGhmbnRf93EIgA "Brain-Flak – Try It Online")
60+4 bytes for the `-ar` flags.
### Explanation
```
{ } for each digit in input (starting at the end)
{} get digit as ASCII code
[((((()()()){}){}){}){}] subtract 48 to get digit as number
( <>{})<> add to cumulative sum on second stack
( <>) push total of all cumulative sums (the sum of moments)
{ } while sum of moments != 0
({}[({})]) subtract sum of weights
()< > count the number of iterations needed
( <>) push onto first stack and implicitly output
```
[Answer]
# [Python 3](https://docs.python.org/3/), 66 bytes
```
f=lambda n,a=0,b=0,c=1:n and f(n//10,a+n%10*c,b+n%10,c+1)or c-a//b
```
[Try it online!](https://tio.run/##TYlBCsIwEEX3niIbIbEjmd9gtUIOM0kJCjotpRtPH4MgdPHhv/eWz/aYNdRa4kveaRKjJJEpteWIuxrRyRSr3oNJOj2CT5nS71Du4ObV5LN4n@qyPnWzxQZcQu/c4c9g7Khvedzn28gcgOHaZP0C "Python 3 – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes
```
ẹ⟨{iᶠ×ᵐ+}÷+⟩+₁
```
[Try it online!](https://tio.run/##ATYAyf9icmFjaHlsb2cy///hurnin6h7aeG2oMOX4bWQK33Dtyvin6kr4oKB//84OTAwMzExNjcy/1o "Brachylog – Try It Online")
[Answer]
## GolfScript (24 bytes)
```
0:i.@{15&.@+@@i):i*+\}//
```
[Online demo](http://golfscript.apphb.com/?c=OyI0MDAwMDEiCgowOmkuQHsxNSYuQCtAQGkpOmkqK1x9Ly8%3D)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 72 bytes
```
a,b,c;f(long n){a=b=c=0;for(;n;a+=n%10*++c,n/=10)b+=n%10;return-~c-a/b;}
```
[Try it online!](https://tio.run/##bYtLDoIwFADXegqCIWmlSAvxQ2o9iZv2QZEEH6bCiuDVK@pSdpOZDCQ1gN80CO1QVsH52ZdNt7tdvGaGgbSk7bAOkI5aGQWKS9s5IlHqWGEk@DaOgWGqBKfmZ6Sr@sFh8oJEp0ZOvsE@uOsGyQc0Hderh5vRkjAqrxgyS3KxzzNK5X8RXCz6bF6K5eVUcJ4LcTh@8@Tf "C (gcc) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
48-ttn:*sws/
```
[Try it online!](https://tio.run/##y00syfn/38RCt6Qkz0qruLxY//9/dQtLAwNjQ0MzcyN1AA "MATL – Try It Online")
[Answer]
# [Mathematica](https://www.wolfram.com/mathematica/), 42 bytes
```
Range@Length@#.#/Total@#&@IntegerDigits@#&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvs/KDEvPdXBJzUvvSTDQVlPWT8kvyQxx0FZzcEzryQ1PbXIJTM9s6QYKPA/oCgzr8QhzcHY0NTYiAvGMzQwhLONgFKWCCkLSwMDY0NDM3Oj/wA "Mathics – Try It Online") ([Mathics](http://mathics.github.io/))
[Answer]
# [Python 3](https://docs.python.org/3/), 69 bytes
```
x=[*map(int,input())]
print(sum(v*k for k,v in enumerate(x))//sum(x))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8I2Wis3sUAjM69EJzOvoLREQ1MzlqugCMjXKC7N1SjTylZIyy9SyNYpU8jMU0jNK81NLUosSdWo0NTU1wepADL@/zc2NDU2AgA "Python 3 – Try It Online")
-7 bytes and fixed thanks to ovs
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 bytes
```
h/s.e*bkJjQTsJ
```
[Test suite](http://pyth.herokuapp.com/?code=h%2Fs.e%2abkJjQTsJ&test_suite=1&test_suite_input=31532%0A101%0A231592%0A8900311672&debug=0).
[Answer]
# [Actually](https://github.com/Mego/Seriously), 10 bytes
```
♂≡;Σ@;r*\u
```
[Try it online!](https://tio.run/##S0wuKU3Myan8///RzKZHnQutzy12sC7Siin9/1/JwtLAwNjQ0MzcSAkA "Actually – Try It Online")
[Answer]
# [Cheddar](http://cheddar.vihan.org/), 63 bytes
```
n->(a->a.map((x,y)->x*y).sum/a.sum+1)(("%d"%n).bytes=>((-)&48))
```
[Try it online!](https://tio.run/##S85ITUlJLPqfk1qikKZg@z9P104jUdcuUS83sUBDo0KnUlPXrkKrUlOvuDRXPxFEahtqamgoqaYoqeZp6iVVlqQW29ppaOhqqplYaGr@LyjKzAOapGFsaGpspMkF4xoaGCI4RkBJSyRJC0sDA2NDQzNzI83/AA "Cheddar – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), 43 bytes
```
$
;$`
(?=(.*);)
$1
\d
$*
^(1+)(\1)*;\1$
$#2
```
[Try it online!](https://tio.run/##K0otycxL/P9fhctaJYFLw95WQ09L01qTS8WQKyaFS0WLK07DUFtTI8ZQU8s6xlCFS0XZ6P9/C0sDA2NDQzNzIwA "Retina – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 80 bytes
```
int f(long n){int a=0,b=0,c=0;for(;n>0;a+=n%10*++c,n/=10)b+=n%10;return-~c-a/b;}
```
[Try it online!](https://tio.run/##jY7BbsIwEETP5St8qWQ3JNiJoEVW@gVw4og4bEwSGcI6sh2qKgq/HgyIMxxWo9l9mtkDnCE2bYmH/XFsu6LRiqgGnCNr0NiPGj2paGOwJsj6m4OcT4swKueyMpZK/OUSohw/Bf@KIjXFWS44Kx4baUvfWYwvKoZZIYdnh/Pgg5yN3pNTaKIbbzXW2x3Y2rF@8rH5d748JabzSRsuvkGK5d/9K8qSimZinqWMydek4OItLg2Ry/cif5acZ0IsvtPVjR8mw3gF "Java (OpenJDK 8) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
TвÐgL*OsO÷
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/5MKmwxPSfbT8i/0Pb///38LSwMDY0NDM3AgA "05AB1E – Try It Online")
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 33 bytes
```
{48-}%.[.,,]zip{{*}*}%{+}*\{+}*/)
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/v9rEQrdWVS9aT0cntiqzoLpaq1arVrVau1YrBkToa/7/b2FpYGBsaGhmbgQA "GolfScript – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~132 134 126~~ 112 bytes
* Thanks @ovs for 14 bytes.
```
n,m=map(int,input()),0
z=lambda a,b:sum(n[j]*abs(m-j)for j in range(a,b))
while z(0,m)<z(m,len(n)):m+=1
print-~m
```
[Try it online!](https://tio.run/##Dc1BDoIwEADAO6/ojV0tSYuJIpGXGA9tRGnDLk0pMfbg1yv3SSZ807RwWwpLGsgEcJyk47AlQJSqysNsyD6NMNL260bAd/84GLsCNR5fSxReOBbR8HuE3SBWn8nNo8igJOEtA8l5ZGDEno6DrkLch@ZHpdTdVamT1udLW/8B "Python 2 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), 30 bytes
```
$'¶
1>`¶
.
$*
(1+)¶(\1)+
$#2
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wn0tF/dA2LkO7BCDJpcelosWlYaiteWibRoyhpjaXirLR//@GBoZcxoamxkZcRkDK0ojLwtLAwNjQ0MzcCAA "Retina – Try It Online") Link includes test cases. Explanation: The first stage sneakily creates newline-delimited duplicates of all the suffixes of the original string. This means that the each digit appears after the first newline the number of times according to how far away it is from the left, effectively multiplying to give its moment. The second stage deletes all the newlines after the first, completing the calculation of the moments. The third stage converts the digits to unary, summing them, and the fourth stage divides the sums (exact division is assumed to apply here).
[Answer]
# [J](https://jsoftware.com), 29 bytes
```
(0 i.~]+/ .*[:-/~#\)@(,.&.":)
```
J executes verbs right-to-left, so let's start at the end and work our way towards the beginning.
**Explanation**
```
,.&.": NB. Explode integer into digits
#\ NB. 0 .. N-1, where N=number of digits
-/~ NB. Distance table, one row per digit
] +/ .* … NB. Forces at each pivot (F=digit * distance)
0 i.~ … NB. Digit index where F=0
```
Note that J is an index-origin 0 language, so it would be more natural and idiomatic for the answer to 8900311672 to be 4 rather than 5, for 231592 to be 3 rather than 4, etc, and so that's the way this function is written.
But if the index-origin 1 is required for output, then add `1+` before `0 i.~` and add 2 bytes to the score, bringing it up from 29 to 31.
[Answer]
# Python 3, 127 bytes
I am a newbie golfer. All suggestions and tips are greatly apreciated :).
```
lambda x:min([(abs(eval("+".join(list(x[:i+1])))-eval("+".join(list(x[i:])))),i+1)for i in range(len(x))],key=lambda x:x[0])[1]
```
[Try it Online!](https://tio.run/##bY3LDoIwFAX3fkWDm3sDmpbGByR8SWVRYtFqKYRWU76@wkZD4vLMTHKGyd97y2NbXaKRXXOVJJSdtiBANg7UWxpI0mT/6GdmtPMQRKlTViPi7q/V5eIwmyNs@5Fooi0Zpb0pMMpCQKyzp5qq71sQtEbB6rglXjlP3Et7tRlGbT20kHB24HmC@COMstXO56RYJ@eCUs7Y8bTg@AE)
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 84 bytes
```
a=>{int p=0,q=0,i=1;for(;i<=a.Length;p+=a[i-1],q+=i*a[i++-1]);return q/(q%p>0?0:p);}
```
[Try it online!](https://tio.run/##jU6xbsIwEJ3rr7ilUtIYkoAYWmM6FHWiElIrdUAMJrnCSWAntkNEo3x7GkqZ6XC6e@/evXuZG2TGYlc50lt4PzmPB8EuaC4veDhXHj/ogNfFH70gXQqW7ZVzsGyY88pTBq@Vzqak/WrNoW8zWNLReJDQKTlregYKmfCyL5Kp@DI2EDSVarhAvfU7UURSrWiQrnkZSXro5yjqUSgs@spqKOOgvC9myXPyVISi7QS7Pj4ayuFNkQ5C1rC7F6Od2ePw05LHPioGv0ECjfVqDc2Yp3zCx3zUhqG4qU55wtN/KUf84vx4dY7jm97nm8lZDXEMfmdN7SCnI@UImxN8ozVQ71CDQ3SqBnJQ6Y3aK51hzlrWdj8 "C# (.NET Core) – Try It Online")
Takes in an array of single digits as the 'integer' input. Uses the image moments approach for finding the centre of mass. Throws a divide by zero if the seesaw is unbalanced.
### DeGolfed
```
a=>{
int p=0, // used to store the image moment of order 0
q=0, // used to store the image moment of order 1
i=1; // array index, offset to 1 as 1 based indexing is required
for (; i <= a.Length; // go through the array
p += a[i-1], // getting the order 0 image moment value
q += i*a[i++-1]); // and the order 1 image moment value
// q / p is the centre of mass, but as an exact integer pivot is required,
// if q is not evenly divisible by p,
// then throw a divide by zero error.
// otherwise return q / p
return q / ( q % p > 0? 0 : p);
}
```
] |
[Question]
[
Your task is to devise a programme that extracts the bits, in order, represented by the first argument based on the set bits represented by the second argument (the mask).
**Formal Definition:**
* Let the first argument `x` represent the binary string
`S=(xn)(xn-1)...(x1)` with `n>=0` and `x1` being the least
significant digit and `xn = 1`.
* Let the second argument `y` represent the binary string `T=(ym)(ym-1)...(y1)` with `m>=0` and `y1` being the least significant digit and `ym = 1`.
* Let the result represent `0` if `x` represents 0 or `y` represents 0.
* Let the number of `1` digits in `T` be `p`. Let `{di}, i in [1, p]` be the set of binary strings of the form `(dim)(di(m-1))...(d1)` defined by (for all i, (for all k, `|{dik such that dik = 1}| = 1`)) and (`if 1 <= i < j <= p then 0 < di < dj`) and (`dp | dp-1 | ... | d1 = T`). In other words, `{di}` is the ordered set of strings with a single `1` digit that makes up the string `T` when `|` is applied.
* Let the **result** of the programme represent the following binary string:
`((dp & S) << (p - 1))| ... | ((d2 & S) << 1) | (d1 & S)`
**Examples:**
* 1111, 110 -> 11
* 1010, 110 -> 01
* 1010, 10110 -> 01
* 1101010111, 11111000 -> 01010
**Input and Output:**
* The two arguments may be taken in any way
* The two arguments need not be binary strings. They can also be integers which represent binary strings.
* Answers which do not take input representing binary strings of arbitrary length **are** permitted.
**Winning:**
Shortest code wins.
**Clarifications:**
* If your output gives a bit string, order of bits is not important. Simply state the order in your answer. As stated before, the output of your programme need only represent the bits required.
[Answer]
# *Edit:* APL, 1 character
`/`, the compression operator [(Documentation)](http://www.microapl.co.uk/apl_help/ch_020_020_840.htm).
Example of use:
```
0 0 1 1 1 1 1 0 0 0/1 1 0 1 0 1 0 1 1 1
0 1 0 1 0
```
Try it yourself at [http://ngn.github.io/apl/web/index.html](http://ngn.github.io/apl/web/index.html#code=0%200%201%201%201%201%201%200%200%200/1%201%200%201%200%201%200%201%201%201)
The mask is left, and the input bitstring is right. **Disclaimer:** *I'm not an expert in APL and have never used it; I only submitted this to substitute the disqualification of my machine-code solution below. I admit that a limitation of the code above is that the left and right bitstrings must be of equal length in APL, and lack the APL skills to fix this.*
# *Rejected as loophole*:
# x86-64 Machine Code (BMI2, Haswell+), 5 bytes
`c4 e2 f2 f5 d0` is the hex representation of the raw bytes of the program as they would appear in an executable x86-64 binary program.
This represents the *single instruction* `pext %rax, %rcx, %rdx`, which accepts `S` in `rax`, `T` in `rcx` and stores the result in `rdx`. Max 64 bits. Runs in 3 clock cycles on Haswell, has throughput of 1 per clock cycle.
```
xxx@xxx:~/Documents/SO> cat > bmi2.s
.text
pext %rax, %rcx, %rdx
xxx@xxx:~/Documents/SO> gcc bmi2.s -c -o bmi2.o
xxx@xxx:~/Documents/SO> objdump -d bmi2.o
bmi2.o: file format elf64-x86-64
Disassembly of section .text:
0000000000000000 <.text>:
0: c4 e2 f2 f5 d0 pext %rax,%rcx,%rdx
```
Of course, requires a pretty modern assembler.
The documentation for PEXT is much clearer than OP's description, so here it is:

[Answer]
# CJam, 9 bytes
```
eaz{)~*}%
```
This reads the bit strings (LSB first) as command line arguments and prints the result (also LSB first).
To try this code in the [CJam interpreter](http://cjam.aditsu.net/), change `ea` to `qS%` and separate the strings with a space.
### Example run
```
$ cjam <(echo 'eaz{)~*}%') 1110101111 00011111; echo
01011
```
### How it works
```
ea " Read both command line arguments and collects them in an array. ";
z " Interleave the characters of both strings. ";
{ }% " For each pair of characters: ";
)~ " Pop the last character and interpret it as an integer. ";
* " Repeat the remaining strings that many times. ";
```
* If the mask character is 0, the string consisting of the corresponding character is repeated zero times.
* If the mask character or the corresponding character do not exist, popping a character will result in an empty string to be repeated.
In either case, the result will be an empty string.
[Answer]
# Haskell, 68 characters
```
f[c:d,'0':b]=f[d,b];f[c:d,_:b]=c:f[d,b];f _="";main=interact$f.words
```
Prints nothing if the input isn't exactly two words.
The first argument can contain any characters. So can the filter; only `0` is treated as "not select".
If arguments are of different length, they are taken left-aligned (LSB first; explicitly allowed since revision #4).
# Haskell function, 48 characters
```
f(c:d)('0':b)=f d b;f(c:d)(_:b)=c:f d b;f _ _=""
```
Subtract two more characters if "function of two integer arrays" is an acceptable signature
[Answer]
# Golfscript, ~~54~~ 51 characters
```
'0':x;{.,64\-x*\+}:b~:m;'X':x;b{m(\:m;48={;}*}%'X'-
```
Only works for binary strings of length 64 or less.
Explanation:
```
'0':x; store '0' in the x variable (which will be used in the following)
{.,64\-x*\+} block that pads strings to a length of 64 with the character stored in x
:b~ store the block in b and execute, second argument (y) is now padded with '0's
:m; store second argument as mask (m)
'X':x;b pad the first argument with 'X's (will be removed later)
{...}% for each character in the first argument (x), ...
m(\:m; grab and delete the first character of m (mask)
48={...}* if this character is equal to 48 (0 in ASCII)...
; remove the digit. Hence, this if statement keeps a digit only if the mask is 1.
'X'- finally, remove the 'X's added in step 5
```
[Answer]
# J, 16 Characters:
```
(#=@i.@#)@],@:#[
```
**Usage:**
```
1 0 1 0 1 1 ((#=@i.@#)@],@:#[) 0 1 1 1 0 0 -> 0 1 0
```
**Explanation:**
First argument is left, second argument is right (mask).
```
(#=@i.@#)@],@:#[ -> (# =@i.@#)@] ,@:# [
```
* Take right argument, produce identity matrix of size length of right argument.
* Use set bits of right argument to choose rows of produced identity matrix.
* Use chosen rows of identity matrix to choose digits of left argument.
* Concatenate the digits chosen from left argument.
# J, 13 Characters
According to the rules, the form of output is not important. Therefore, if we omit the concatenation of the output digits, we can have the following shorter answer.
```
`(#=@i.@#)@]#[`
```
[Answer]
# J, 1 character
`#`, the tally operator [(Documentation)](http://www.jsoftware.com/help/dictionary/d400.htm).
Example of use:
```
0 0 1 1 1 1 1 0 0 0#1 1 0 1 0 1 0 1 1 1
0 1 0 1 0
```
This solution does not cater for the case when the length of the mask is less than that of the string. Given that the above might be seen as a loophole, we have the following solution.
# J, 11 characters
```
[#~],0$~-&#
```
This solution is like the original `#`, but also caters for the case when the length of the mask is less than that of the string. Note here that the mask is the right argument, and not the left argument as in the first solution.
```
x ([ #~ ] , 0 $~ -&#) y
x #~ (y , (0 $~ (x -&# y)))
x #~ (y , (0 $~ ((# x) - (# y))))
x #~ (y , (((# x) - (# y)) $ 0))
x #~ (y , 0 0 ... 0 0)
x #~ y 0 0 ... 0 0
y 0 0 ... 0 # x
```
* `[` and `]` choose `x` and `y` respectively.
* `x (u&v) y` -> `(v x) u (v y)`.
* `(x -&# y)` -> `(# x) - (# y)`.
* `# x` -> length of `x`.
* `x v~ y` -> `y v x`.
* `n $ 0` -> list of n `0`s.
* `(0 $~ (x -&# y))` -> `m` `0`s, where `m` is the difference between the length of the string and the length of the mask.
* `(y , 0 0 ... 0 0)` -> the list `y 0 0 ... 0 0` such that its length is equal to that of the string.
* `a # b` -> the elements of `b` chosen by the binary mask `a`.
Even though this solution is shorter than my other solution of 16 characters, I think it still makes unfair use of `#`. In any case, I think it's still interesting.
[Answer]
# Haskell, 33 characters
```
((map snd.filter((>0).fst)).).zip
```
# Usage
```
(((map snd.filter((>0).fst)).).zip) [1, 0, 1, 0] [1, 0, 0, 1]
[1, 0]
(((map snd.filter((>0).fst)).).zip) [1, 1] [1, 1, 0, 1]
[1, 1]
```
[Answer]
# J, 10 characters, no use of tally `#`
This solution does not cater for input where mask is shorter than string.
```
;@:(<@$"0)
```
**Usage**
```
1 0 0 1 (;@:(<@$"0)) 1 0 1 0
1 0
```
**Explanation**
* This makes no use of `#`, which on its own can be used to solve this golfing problem.
* This solution works by interleaving both sides, one element by one. This is expressed by `"0`, which makes `<@$` applied to each pair of elements.
* `x $ y` means `x` `y`s as a list. `3 $ 4` -> `4 4 4`.
* `< x` puts `x` in a "box". A box can contain an object of any dimension (list, matrix, nothing). Boxes can be concatenated into lists.
* `1 $ x` -> one-dimensional list consisting of `x`.
* `0 $ x` -> nothing
* `1 (<@$"0) x` -> one-dimensional list consisting of `x` inside a box.
* `0 (<@$"0) x` -> nothing in a box.
* `;` takes a list of boxes and concatenates its contents, throwing away empty boxes.
* `u@:v` composes `u` and `v` in such a way that `u` is applied only after `v` has been applied to the whole of the arguments. In this case `;` is applied only after the right side of the `@:` has been applied to each interleaved pair `x` and `y` made from the arguments.
] |
[Question]
[
One reason why [ISO8601](https://en.wikipedia.org/wiki/ISO_8601) is the best date string format, is that you can simply append as much precision as you like. Given 2 integers representing seconds and nanoseconds that have passed since `1970-01-01T00:00:00`, return an ISO8601 string as described below.
**Output:**
The standard output format without timezone looks like this:
`1970-01-01T00:00:00.000001`
The date is encoded as "year, month,day" with 4,2,2 digits respectively, separated by a "-". The time of day is encoded as "hour, minute, seconds" with 2,2,2 digits respectively. Then, optionally a dot with exactly 6 digits of precision can follow, encoding microseconds that have passed after the given date+(time in hours+minutes+seconds) since. This is only appended if it'd be not equal to 000000. See examples below
Yes, we are allowed to append 6 digits(microseconds) of precision and theoretically more are simply appendable, though not defined further in the standard.
**Input:**
You'll get 2 integers(seconds, nanoseconds). For the sake of simplicity, let's constrain them to be within `0 <= x < 10^9` both. Make sure to discard/round down any precision beyond microseconds.
**Examples:**
```
Input: 616166982 , 34699909 Output: 1989-07-11T13:29:42.034699
Input: 982773555 , 886139278 Output: 2001-02-21T16:39:15.886139
Input: 885454423 , 561869693 Output: 1998-01-22T07:33:43.561869
Input: 0 , 100000 Output: 1970-01-01T00:00:00.000100
Input: 0 , 1000 Output: 1970-01-01T00:00:00.000001
Input: 0 , 999 Output: 1970-01-01T00:00:00
Input: 999999999 , 999999999 Output: 2001-09-09T01:46:39.999999
```
**Task:**
Provide a function that takes in 2 integers as described in the Input section and returns a String as described in the Output section.
For details and limitations for input/output please refer to the [default input/output rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
This is codegolf: Shortest solution in bytes wins.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + sed, ~~37~~, ~~59~~, 50 bytes
~~```
printf '%(%FT%T)T.%06d' $1 $[$2/1000]
```~~
```
printf "%(%FT%T)T.%06d" $1 ${2::-3}|sed s/\\.0*$//
```
[Try it online!](https://tio.run/##PYy9DoJAEIT7e4oNgURNhPtdbrH3CeiAAuUMJAQMkFiIz45nos4U800xc6nndnu0Xe9gcnUDPaxrUUDYQ1WdmhFmt/iy3aduWG4QRLvonEf5Po8jjk0AoYDwKbPsqF7r7BqYk7KM@SFMks1d29E/DG5D4Y1kJSiNRMSJ@ZKmyhgD1qJQJFPLrDXaaC0VGBQWCUkxDoJ/9AUffs/oJ/jTGw "Bash – Try It Online")
8 bytes saved thanks to @DigitalTrauma
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 91 bytes
```
DateString[6!3068040+#2,"ISODateTime"]<>If[#>999,"."<>IntegerString[‚åä#/1000‚åã,10,6],""]&
```
[Try it online!](https://tio.run/##PY6xjsIwDIb3vsUlEssZzmkSN5GOioGF6U4qW9UhQil0aAeUrSoPwPGUvEhJxIG9fP5/@bd7F06@d6E7uLldz1sXfBXO3XCs6UMiGVT4yXNgu@onefuu96z5LndtzUtrLbAVi9MQ/NGf/xfvtyv/Eoh4v/2BQKAGGGsW8290Q82XZbvZ8GZxqQ5uuIzZKBXFJLRAIjZZk0@QjcaQkDYvDEShKKTWOsmahCFLVoIxWmmlcpnkdA4R8MVPSg@@4Fnwpimb5gc "Wolfram Language (Mathematica) – Try It Online")
Mathematica supports milliseconds, but not microseconds.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~108~~ 106 bytes
Saved 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
#import<time.h>
o[9];f(s,n)long s;{strftime(o,99,"%FT%T",gmtime(&s));printf((n/=1e3)?"%s.%06d":"%s",o,n);}
```
[Try it online!](https://tio.run/##fVLbbqMwEH3PV1hesYLWUF/AYOjlodr9At6aaFWBSZE2JsI8RBvl27MDhrRR1RoD9pyZ4zOeqcJtVZ3PP9rdvuuH@6Hd6ejtcdW9qE3R@JaY4G9ntsgWRzv0zQj7HVGKYO936ZWYbHeT7acNgmLft2ZofN/cPTAtgifs2cijssY5rDDpgKw4ncEH7V5b4wer4wrBGA2DtsMf@7JBD@goGTxSZZwg@KSpSJKEoCxL4iSOuSCILlMt41RcMxnHJGIJIFVjtGRC8TQjKJEsk0oqIGJ0HO4/sX2mrN5e@xukD3tdDbp2tJipTIU0DRkrmci5ymMe0ekwTBDmlLKQ8pADKnOhcpZE7vwRZUplIThwXtI0FyKPReQkOTSlI0pZSWk@zQjEgcBvUMC/QN/lgF5VUpbHo6LIpYivcuzn5NaHX3x9UM/wJmP8h71YIpqu98fLbk2tDxBFi3l5j2z7T3eNv9xYcDcbbi6WAt3eTt4Bcg2wlM4C09wIE74prmCzwOYTPHce9mri1Sh8RCDcEgT9dnFxzfy@nwsLnJfifsWKfM8GawOceiY4rU7n/w "C (gcc) – Try It Online")
Inputs seconds and nanoseconds as integers and outputs the formatted date/time to `stdout`.
[Answer]
# [Perl 5](https://www.perl.org/) (`-p` `-MPOSIX+strftime` `-Minteger`), ~~55~~, ~~51~~, 60 bytes
Thanks to @Abigail for giving me the idea to change the input format. + 9 bytes to handle the microseconds=0 case.
~~```
$_=(strftime"%FT%T",gmtime$_).sprintf".%06d",<>/1e3
```~~
```
$_=(strftime"%FT%T",gmtime$_).sprintf".%06d",<>/1e3;s;\.0+$;
```
[Try it online!](https://tio.run/##RY5LC8IwEITv@RmhBcW2Js2jWaoeBQ@iYA8ehF5MS6GPkOb3G1NUnGXZbxYGxmjbC@@jer@anW1cN2gcH6u4wkk7LC6q19lsbDe6BmcxkU@c7A5bqlk5l4@MbKLSe0nDSFA5YlwCAAEUTFEwIQRSSlIGeaECCS44zxkSkioJEhgiiJJFXwgn5Jf96E@vybhuGmef9san5@vldrpvfpXDIxTUrbZv "Perl 5 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~32~~ 28 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as a pair of strings, with the nanoseconds first. Can save (at least) 4 bytes if we can include leading `0`s with the nanoseconds.
```
ùT9 ¯6
pU=n g)iÐV*A³ s3 ¯UÄ9
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=%2bVQ5IK82CnBVPW4gZylp0FYqQbMgczMgr1XEOQ&input=IjM0Njk5OTA5IgoiNjE2MTY2OTgyIg)
Or, to "translate" that to JavaScript:
```
U=>V=>(
U=U.padStart(9,0).slice(0,6),
U.repeat(U=Math.sign(parseInt(U))).replace(/^/,new Date(V*10**3).toISOString().slice(0,U+19))
)
```
```
ùT9 ¯6\npU=n g)iÐV*A³ s3 ¯UÄ9 :Implicit input of strings U=nanoseconds & V=seconds
√π :Left pad U
T : With 0
9 : To length 9
¯6 :Slice to length 6
\n :Reassign to U
p :Repeat U
U= : Reassign to U
n : Convert to integer
g : Get sign
) :End repeat
i :Prepend
Ð : Create Date object from
V* : V multiplied by
A : 10
³ : Cubed
s3 : To ISO String
¯U : Slice to length U
Ä9 : +19
```
[Answer]
# [Groovy](http://groovy-lang.org/), ~~62 60~~ 68 bytes
```
f={s,n->"${java.time.Instant.ofEpochSecond(s,n|1)}"[0..25]-~/\.0+$/}
```
[Try it online!](https://tio.run/##ndFNS8NAEAbgu79iKYW22N3O7Fd2FurNg2dzUw@htn6AiTShILX@9ThNXBWlFnyTwzCbZ5Od3K2ravPStqv5tp6W8mww3D4Wm0I1D09LdVHWTVE2qlqdP1eL@8vloipvx/zcK052gytQSrsb@Ta7VnA6nO3aoq6X60aMkAJJyCRijiZqilYrMNYTjcR8LlZjj3x5ClpMRdcnoMlJ4hoAJWipmftoKKJTIXg0iTPMMuOcY94v6Cx8eSQKkrfQOocsGhOtUc5j8MmH4KyzVhv2/YIn891nsPeAOUDsbgX8TQAfHkTKVHCXw@VRzzsc8F35px8l8Mvz7MQP38@P/wDlgNHuR6ioS5pfSu/7/PP9n/Wx8@8PenB@3Jm07w "Groovy – Try It Online")
## Explanation
The Java `ofEpochSecond(epochSecond, nanoAdjustment)` method returns the `Instant` corresponding to the given seconds and nanoseconds (exactly what we want for this challenge). The nanoseconds are bitwise-ORed with `1` to ensure we never end up with exactly 0 or 1\_000\_000 nanoseconds, while still maintaining the same 6-digit rounding behavior.
`"${...}"` converts the `Instant` to a [`GString`](https://docs.groovy-lang.org/latest/html/api/groovy/lang/GString.html) consisting of the `String` value of the instant. The `toString` representation of an `Instant` is in ISO-8601 format: "2011-12-03T10:15:30.000000001Z". It automatically excludes extra decimal places past 0/3/6 decimal places (seconds/milliseconds/microseconds) if the remaining digits are 0, hence the earlier bitwise-OR.
`"${value}"[0..25]` returns characters 0 through 25 of the string, which is up through the sixth decimal place.
`-~/\.0+$/` subtracts the first instance of the regex pattern `\.0+$` from the resulting string; namely, a decimal place followed by all zeros, followed by the end of the string. This will only match if the string ends in `.000000`, and the code is one character shorter than subtracting `'.000000'`.
[Answer]
# [Groovy](http://groovy-lang.org/), 63 bytes
```
f={s,n->sprintf('%tFT%1$tT.%06d',s*1000L,n/1E3as int)-~/\.0+$/}
```
[Try it online!](https://tio.run/##ndE9T8MwEAbgnV/hoVFaiN07f8VnqWwwMXpkqQRBLClqIiSE4K@HS4IBgUqlXjJY5zy27s3Dfrd7fhmGZvPaVa287J72j23fLMuiv04FLvqkCvB3ZdWdIwDcVO0ar8y2E/zVSr6vbxVcLNZvw7br7ve9KJECSaglYkITNUWrFRjriUqx2Yhm6ZEfT0GLSkx9AlqdZa4BUIKWmrmPhiI6FYJHkznDujbOOebzhq7Dt0eiIPkIrRPU0ZhojXIeg88@BGedtdqwnzc8mZ@@htEDJoA4vYrH5tE/PYhclRgDgbFx1PMJB/y0/NeXGfzxnJ345ef8@A9QAox2jFDRVDm/XLOf68T7v9bH5h8HPZgfd1bDBw "Groovy – Try It Online")
A different Groovy approach using format strings (inspired by other similar answers).
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/) 18.0, 53 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
Full program. Prompts for nanoseconds, then seconds.
```
(¯7×0=f)↓⊃'%ISO%.ffffff'(1200⌶)20 1⎕DT⎕+1E¯6×f←⌊⎕÷1E3
```
[Try it online!](https://tio.run/##fVA9SwNBEO3vV2wT9o58sLt3u7cbEASTIpUB01gG4olwmGBsgrFRuRxnLigSzsbKxi6FaMAy90/mj8RJgtE0vt1i581b3ptp98JyZ9AOu6dLiKNaC6KHKyGl0kVIP/K5Vh5j14RA@kJ63XAQnIUhCboXhOsKo30Ck2mtZTVWvyC5sWm53KpW6b4tim6eQfouHYgTSKeLNxuS2xJnrMghfoboyVEQPXbalyfo45QEMgp1fLh2zDM@RJ5A8kroSkTR6OCYdoLzPiVwf4eBvvD@l2z8aUE8ai7txczPM7YXOOiBIWihcXRYqARrUJsLxhqOYIRv5p9Mi7y@mKk8C3AqGCfI5HNed3E/oyVZo2m5njLGMGMpjkcZLayfltaKu0b42kLW910p5bYnFdfKKOOiSnrS84S77eFuEBbbIf6U6LdbbfD7@gY "APL (Dyalog Unicode) – Try It Online") (polyfills for `⌶` and `⎕DT` because TIO still uses 17.1)
`‚éï√∑1E3`‚ÄÉdivide input nanoseconds by 1000
`f‚Üê`‚ÄÉassign to `f`
`1E¯6×` multiply by 0.000001
`‚éï+`‚ÄÉadd input seconds to that
`20 1‚éïDT`‚ÄÉconvert from UNIX time (seconds since 1970) to Dyalog Date Number (days since 1989-12-31)
`'%ISO%.ffffff'(1200‚å∂)`‚ÄÉformat according to ISO with six-digit fractional second precision
`⊃` disclose (because a "string" is an enclosed character vector)
`(`…`)↓` drop the following number of characters
`0=f`‚ÄÉone if `f` is zero
`¯7×` seven from the rear if so (lit. negative seven multiplied by that)
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~83 94 ...~~ 78 bytes
```
s=>n=>new Date(s*1e3).toJSON(n=0|n/1e3).slice(0,20-!n)+`${n+1e6}`.slice(n?1:7)
```
[Try it online!](https://tio.run/##bZBNS8QwEIbv/RVj8NDaD2eSNk0C1YsnD3pwb2vBRbqwIllpiy6s@9vXabqCwk4@mfd5J0zeVp@r4bXffIz5pzmum@PQ3Hie3RfcrcYuHq6oU0kxbu@fHh9i3@C3vw6Z4X3z2sWYScwvfJK@XO59Sp0@vJwUf0uuTo5jN4xDs1xq4qGtkZCBKrW1Fi1kgqyxOdY50YKUk9aVssCgizZbMl7XqqoqNhmjSVlZG74LiUg5ylyyTTtlHVXFDEw2Y6qyKkupGK00GW21VeExa3I2SrnA2inlSlXM@uQCZJxwCgjB75CtcXIgLRBdmAXrTP1zhNpnSWZnMgNu@TwXAPsbkP29nzrlP7ILJFdOzRazKNo2itbbPn7vRtjtdrBdQ/jtZB/BlOsbWMcsLLFNwkltEsFHv/HjKZ2KTKSzkgpwz15ACj0vAc@etzTmIs0EyDZJBetJdIiOPw "JavaScript (V8) – Try It Online")
* Thanks to @Neil for the great help!
* Saved another 5 thanks to @Arnauld
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 46 bytes 40 chars, 42 bytes
```
{(~DateTime.new($^a+$^b div‚ÖØ/1e6)).chop}
```
[Try it online!](https://tio.run/##ddBNSgNBEAXg/ZyiwCAJZtqq/q9u3HmEWQdGnWDAaFBRgujO83gnLzLWpGdwk7zuTdH10fB23fOD77d7OF/DVf8x/7puX7tms@3UY/c@n63ai9nqBu42b7/fP5fU@cVC3d4/7T77XFUv7R7W4EmO56hhCcZ6ZkbOAGdAHLnGUBM1ZJLmZLXCw8YoxYRgnHMiY/RkWIeYRWpEqlHXWqRPhhM5VRZGGaOzzlptRDpP0bNnkw9/cqwFa91gSMYka1RZGCXClCUQDsnDMMiAg0RqENPhKnmVnRMyl@GkFHtESj0jPC6naqYUUvJfjfTKDVKyQzuqvFb9Hw "Perl 6 – Try It Online")
Saved a few bytes by using a non-digit numeral (which could be replaced by others like `‡µ≤`, but others like `êÑ¢` or `ëÅ•` add an extra byte), which allowed the space removed after `div`. Only trick here was needing to force the round down, and stringify the `DateTime` to be able to `.chop`. There may in fact be a bug here in that Rakudo's implementation rounds up, and if we consider it as such, then it can be further golfed to
```
{(~DateTime.new($^a+$^b/1e9)).chop}
```
Which would only be 35 chars/bytes.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/) 106, 81 bytes
```
lambda a,b:datetime.fromtimestamp(a+b//1e3/1e6).isoformat()
from datetime import*
```
[Try it online!](https://tio.run/##rZBNasMwEEb3OsWgleSqjk2g1AYdIKtcIFBGWE4E0Q/KZJHTO1JMoNBFFukIMbN48xi@dKNTDNvvlJdZH5YzejMhoDLjhGTJedvOOfo6XAh9EvhhNpvebsv/kq27xDlmjyQkqxw8t8D5FDM1y9ohY5iiZ6iN7rumGeCzZym7QILvQrrSyBUqXp5RNkyaH4jLJ7C/0krMAhUYKYumY1VU6180b0uGYXjDUTKEH3ChxnS0ou/kyKAUgoa6sqbXrk3I5hGhfCDmNfLyrl/Qn9uWOw "Python 3.8 (pre-release) – Try It Online")
[Answer]
# Excel, ~~102~~ 101 bytes
```
=TEXT(25569+A1/86400,"yyy-mm-ddThh:mm:ss")&SUBSTITUTE(LEFT(TEXT(B1/10^9,"."&REPT(0,9)),7),".000000",)
```
Input is seconds in `A1` and nanoseconds in `B1`.
There are two major pieces to this:
---
`TEXT(25569+A1/86400,"yyy-mm-ddThh:mm:ss")`
`25569` is the numerical equivalent of 1970-01-01 in Excel which measures from 1900-01-00 as zero.
`A1/86400` converts seconds into days.
`"yyyy-mm-ddThh:mm:ss"` formats the result, giving us the majority of the desired output.
---
`SUBSTITUTE(LEFT(TEXT(B1/10^9,"."&REPT(0,9)),7),".000000",)`
`TEXT(B1/10^9,"."&REPT(0,9))` converts from an integer of nanoseconds to a decimal of seconds.
`LEFT(TEXT(~),7)` gives the decimal point with the leading 6 digits.
`SUBSTITUTE(LEFT(~),".000000",)` accounts for a <1,000 nanoseconds by dropping the result.
---
Aside: Given how friendly Excel is with dates, it makes sense - but is still annoying - that it takes more bytes to deal with `.000000` than it does to deal with `1970-01-01T00:00:00`. I found alternate approaches with less bytes but they only work if we can round the nanoseconds or display zero values. Alack and alas.
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 42 bytes
Uses `-rtime` flag to get `Time#iso8601`.
```
~(~(:at&Time)&:nsec)|~:iso8601&6|~:[]&26&0
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXJVtJJuUUlmbqpS7CI326WlJWm6Fje16jTqNKwSS9RCgBKaalZ5xanJmjV1VpnF-RZmBoZqZkB2dKyakZmaAUTH7oLSkmIFt2gzQyA0s7Qw0lEwNjGztLQ0sIyFqFiwAEIDAA)
## Explanation
```
~(~(:at & Time) & :nsec) | # Time.at(secs, nsecs, :nsec), then
~:iso8601 & 6 | # ISO-8601 w/ 6 fractional digits, then
~:[] & 26 & 0 # Get first 26 chars (drop time zone)
```
] |
[Question]
[
Given a string containing only letters (case-insensitive), split it into words of uniformly random lengths, using the distribution below, with the exception of the last word, which can be of any valid length (1-10). Your output is these words, as a space-separated string (`"test te tests"`), an array of strings (`["test","te","tests"]`), or any other similar output format.
## Word Length Distribution
```
Word Length - Fractional Chance / 72 - Rounded Percentage
1 - 2 / 72 - 2.78%
2 - 14 / 72 - 19.44%
3 - 16 / 72 - 22.22%
4 - 12 / 72 - 16.67%
5 - 8 / 72 - 11.11%
6 - 6 / 72 - 8.33%
7 - 5 / 72 - 6.94%
8 - 4 / 72 - 5.56%
9 - 3 / 72 - 4.17%
10 - 2 / 72 - 2.78%
```
Your odds do not need to match exactly - they can be off by `1/144`th, or `.69%`, in either direction (but obviously they still must sum up to `72/72` or `100%`).
Data roughly guessed from the fourth page, first figure of [this paper](http://ac.els-cdn.com/S0019995858902298/1-s2.0-S0019995858902298-main.pdf?_tid=511ad80e-6cb2-11e7-ad2e-00000aacb360&acdnat=1500490058_0448c8a94d2bdaa5228521b4842e42b7).
# Test Cases with Sample Output
Behavior on very short (length < 11) test cases is undefined.
Note that I created these by hand, so they may or may not follow the uniform distribution above.
```
abcdefghijklmnopqrstuvwxyz
abcd efgh i jklmnopq rs tu vwx yz
thequickbrownfoxjumpedoverthelazydog
t heq uick brown fo xj ump edo vert helazydog
ascuyoiuawerknbadhcviuahsiduferbfalskdjhvlkcjhaiusdyfajsefbksdbfkalsjcuyasjehflkjhfalksdblhsgdfasudyfekjfalksdjfhlkasefyuiaydskfjashdflkasdhfksd
asc uyoi uawer k nb a dhcviua hsid ufe r bfa lskd jhv lkcj haius dy faj se fbks dbfkals jcuyasjehf lkjh falk sd blhsgdf asudyfekjf alk sdjfhlk asefyu iaydskfja shdflk as dhf ksd
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“¤Œæ×¿®¬©¥¤‘Jẋ"$FẋLẊ‘1¦+\Ṭœṗ
```
A monadic link taking a list and returning a list of lists.
**[Try it online!](https://tio.run/##FYy7CsIwGIWfRXFz8iUc1EdwSZufJpKLJH9Bt26CbjrUwbEWhOLeLkJKHyR9kZguh8O5fAcQ4hzCWLxcNdz7ui/dz31d4z7u7aqxeG58d5sv1lF3vrvGYOXq5d63zfDwbRn6yzYEZNxya7UEhBMiI8it0CoDE71CBloByxU1QFUuEzA2t0D51FgijwIMieMkR84IRU0onVhSG0gZMSTF@ECdQUSDgdkf "Jelly – Try It Online")** (the footer separates the resulting list of lists with spaces)
### How?
Uses all the percentages in the distribution rounded to their nearest integer (thus being within the 0.69% allowed thresholds).
```
“¤Œæ×¿®¬©¥¤‘Jẋ"$FẋLẊ‘1¦+\Ṭœṗ - Link: list (of characters), s
“¤Œæ×¿®¬©¥¤‘ - code page indexes = [3,19,22,17,11,8,7,6,4,3]
$ - last two links as a monad:
J - range of length = [1, 2, 3, 4, 5,6,7,8,9,10]
" - zip with:
ẋ - repeat list = [[1,1,1],...,[9,9,9,9],[10,10,10]]
F - flatten (into one list of length 100)
L - length of s
ẋ - repeat list (one list of length 100*length(s) with the
- correct distribution of integer lengths)
Ẋ - shuffle
¦ - sparse application of:
‘ - increment
1 - to indexes: 1 (offset indexes for the partition below)
\ - cumulative reduce by:
+ - addition (e.g. [4,4,7,1,...] -> [4,8,15,16,...])
Ṭ - untruth (yield a list with 1s at those indexes (1 indexed)
œṗ - partition s at truthy indexes (note: excess ignored)
```
[Answer]
# PHP, 94 bytes
```
for(;$c=$argn[$k++];print$c." "[--$e])if(!$e)for($r=rand(0,71);$r>ord(x^"ywgSKAF:=?"[$e++]););
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/470507b43b89e2a98d4f14a2b1d474cdc7020370).
**breakdown**
```
for(;$c=$argn[$i++]; # loop $c through string
print$c # 2. print current character,
." " # 4. if remaining length is 0, print space
[--$e] # 3. decrement remaining length
)
if(!$e) # 1. if remaining length is 0,
for($r=rand(0,71); # get random value from 0 to 71
$r>ord(x^"ywgSKAF:=?"[$e++]) # and increment $e while $r is > probability
;);
```
Note: `ywgSKAF:=?` represents the increasing probabities -1: `[1,15,31,43,51,57,62,66,69,71]`
[Answer]
# Octave, 108 bytes
```
@(s)mat2cell(s,1,[k=(w=repelems(1:10,[1:10;'AMOKGEDCBA'-63])(randi(72,1,n=nnz(s))))(cumsum(w)<=n) n-sum(k)])
```
[Try it online!](https://tio.run/##FYzNCoJAFEZfJdx4Lyg0BgXVQPZDi4geQFxM41TmzNUcf8qXn/RbHDiL85WyEZ1ybgcWjWgiqbQGG7AgKTj0vFaV0spYYGs2D5KJGz@@3i7n0/Gwj/1wuUgRakFZDqtozIgTDePXOJCtsa2BHreccEbhJAWm6ARZ8MRdZurxfOXvQhsqq09tm7brv7/BQ/cH "Octave – Try It Online")
\*Takes the string as input and outputs an array of strings.
\*The last element of the output may be an empty string.
[Answer]
## Python 2, 154 150 147 145 bytes
Allright, this is my first attempt on code golf. Straight up with the code:
```
import numpy.random as r
def f(s):
i=0
while i<len(s):
i+=r.choice(11,p=[x/72. for x in [0,2,14,16,12,8,6,5,4,3,2]])
s=s[:i]+' '+s[i:]
i+=1
return s
```
The second indent is by a tab char as you can see in my TIO version:
[Try it Online](https://tio.run/##HY5BboMwEADP8Sv2RhArGjtpWqHyEsSBgAnbgtddmwb6eYJynZFG49c4sDPbRpNnieDmya@5NK7jCZoAojrbQ38MaaGAypOCx0CjBfoarXvRA2Wl5O3A1Nqj1ujLann7MDn0LLAAOahOaFBfUF9RG/zEK77jBc9o6jpVh1CGqqA6SyDJQkVF/SpqBWLjLA7C5oVc3B@SONjfmdqfm/DD9bx877O24z8ruxmb/7Xje5JuTw).
What I do is adding a space in the string according to the given distribution. I veryfied my distribution by using:
```
import collections
dist = r.choice(11,100000,p=[x/72. for x in [0,2,14,16,12,8,6,5,4,3,2]])
print collections.Counter(dist)
```
Which gave me:
```
Word Length - Rounded Percentage as asked - Rounded Percentage as counted
1 - 2.78% - 2.794%
2 - 19.44% - 19.055%
3 - 22.22% - 22.376%
4 - 16.67% - 16.638%
5 - 11.11% - 11.246%
6 - 8.33% - 8.362%
7 - 6.94% - 7.063%
8 - 5.56% - 5.533%
9 - 4.17% - 4.153%
10 - 2.78% - 2.780%
```
Which I think is correct enough. I then repeat that process of adding a space until the length of my string is succeeded. I also increment my position index by one after adding a space. I hope someone can help me golf this line out but I did not see how to get it out without falsifying the first space.
As I see my text I recognice that I have to learn alot about this Site. Could someone link me a guide how to use the Stackoverflow answer function in the comments so I can learn for my next posts.
---
Edit:
Apperently while rereading my post I did figure out a way to get rid of the i+=1. So i saved 4 bytes by doing that. The new code looks like this:
```
import numpy.random as r
def f(s):
i=-1
while i<len(s):
i+=r.choice(11,p=[x/72. for x in[0,2,14,16,12,8,6,5,4,3,2]])+1
s=s[:i]+' '+s[i:]
return s
```
[Try it online!](https://tio.run/##HY4xcoMwEABr6xXXYYYLsRTbyTDhJQwFAWHOAZ1yEjH484RJu1vs@jUO7My20eRZIrh58msujet4giaAqM720B9DWiig8kUreAw0WqDP0bp/fKCslLwdmFp71Bp9WS2v7yaHngUWIFed0KA@o76iNviBV7zgGd/Q1HWaaXUIZagKqrMEkixUVNQKxMZZHITNC7m495M42J@Z2u8v4Yfrebnvo7bjXyu7GZvn2vEtSbc/)
---
Edit:
I figured out that i can remove some linebreaks.
```
import numpy.random as r
def f(s):
i=-1
while i<len(s):i+=r.choice(11,p=[x/72. for x in[0,2,14,16,12,8,6,5,4,3,2]])+1;s=s[:i]+' '+s[i:]
return s
```
---
Edit:
I modyfied my import and placed the definition of i inside the function.
```
from numpy.random import*
def f(s,i=-1):
while i<len(s):i+=choice(11,p=[x/72. for x in[0,2,14,16,12,8,6,5,4,3,2]])+1;s=s[:i]+' '+s[i:]
return s
```
[Try it online!](https://tio.run/##DY7BVoMwEADvfMXeANlWE2vbh/IlPA4IiaxCNt0EAX8eOc6bw4zf4sBO77sVnsDNk9/O0rr@AJo8S3xKemPBZgGpOqm8TGAZaDRAH6NxWchLKqpuYOpMphT6ql6fb/oMlgVWIFe/oEZ1QXVFpfGOV3zDC76ibpq8UO@hCnVJTZFCWoSayiYBMXEWB2H3Qi4e5TQO5jFT9/MpvDjL6/dxaXr@NXKYsf3bev5K8/0f)
[Answer]
# Dyalog APL, 90 bytes
```
{k←⍵⋄{' '~⍨(2⊃⍵)↓k↑⍨⊃⍵}¨(↓(o[1;2]),0),↓o←1↓⍉2(1-⍨≢⍵)⍴+\((2 14 16 12 8,⌽1+⍳5)\⍳10)[72?⍨≢⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqbCDxqHfro@6WanUF9bpHvSs0jB51NQOFNB@1TQbKTgQKQQRqD63QAIpp5EcbWhvFauoYaOoAuflAAwyB9KPeTiMNQ12Q6s5FYO29W7RjNDSMFAxNFAzNFAyNFCx0HvXsNdR@1LvZVDMGSBoaaEabG9nDtcTWAh2loF6SkVpYmpmcnVSUX56Xll@RVZpbkJqSX5ZaBJTJSayqTMlPVwcA) Hit Run a few times to see how it changes.
**How?**
`72?⍨≢⍵` - roll 72 sided dice length of input times
`[...]` - index inside
`(2 14 16 12 8,⌽1+⍳5)\⍳10` - expand range of 10 by `2 14 16 12 8 6 5 4 3 2` (to create weighted random)
`+\` - cummulative sum
`⍉2(1-⍨≢⍵)⍴` - shape as a zipped table `x y z` → `z x, x y, y z`
`o←1↓` - drop first element
`(↓(o[1;2]),0),↓o` - encase with its first coordinate paired with 0
`¨` - for each pair (x, y)
`(2⊃⍵)↓k↑⍨⊃⍵` - take input from index x to y
`' '~⍨` - and remove spaces
[Answer]
# [Python 2](https://docs.python.org/2/), 155 bytes
```
from random import*
def f(s):
i=sum([[i+1]*[2,14,16,12,8,6,5,4,3,2][i]for i in range(10)],[])[randint(0,71)]
return s if len(s)<11else s[:i]+' '+f(s[i:])
```
[Try it online!](https://tio.run/##FY7BFoIgEEX3fsXsFJ1FUFnHU1/CYVEJOaVggJX9vOHqrd69d5xj56xYFuPdAP5i2zQ0jM7HMmu1AVME1mRA5zANhZRUcVVKgXyHvEYu8Ig17nGHWxRKkjLOAwHZFXXXBd8whVIxuZLJxmKDB85UBl7HyVsIQAZ6bZPkxLnug4YgG1JVDnmV1JIaxZbRp2sqyS/XW2q6d/R49oN148uHOL0/3/mXs@UP "Python 2 – Try It Online")
[Answer]
# Mathematica, 164 bytes
```
(s=Length[c=Characters@#];t=0;l={};While[t<s,If[t+(r=RandomChoice[{2,14,16,12,8,6,5,4,3,2}->Range@10])<=s,l~AppendTo~r];t=Tr@l];""<>#&/@FoldPairList[TakeDrop,c,l])&
```
takes a string as input
outputs array of strings
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~43~~ 39 bytes
```
FθF⁺¹I‽⪫Eχ×Iκ⌕α§”v↷£o8″!”κω⊞υ⎇κω Fθ⁺ι⊟υ
```
[Try it online!](https://tio.run/##NY3JCoMwFEX3/YqHq5eFUNeuxA7YIg3FH0iN1lRNNINDfz4VoWdzFofLLRumS8U672ulAUcCu2nnDEaQMmPxySRXPd6UkJizAaMjFKKvDO61JXARkiODxGaSVwsGaf64Z9fL@ZQG0JINmMku6kyDDopKS6ZXbGGGAAJC4sP/nGohLSacowCqBnTbLPaevUpe1e9GfNqul2oYtbFumpf168PJh6b7AQ "Charcoal – Try It Online") Link is to verbose version of code. Outputs a trailing space if the last word was the exact size randomly chosen.
[Answer]
# [Perl 5](https://www.perl.org/), 107 bytes
```
@B=((1,10,9,5,2)x2,(2,3,4)x12,(5,6)x6,7,(3,7,8)x4,9);while(10<length){$i=$B[rand 72];s/.{$i}//;print"$& "}
```
[Try it online!](https://tio.run/##DcjRCoIwGEDhVxGR2OBXt5mamBDe9wTRhaXpyuaaK1fhq7e8OXwc2ag@tnZXFghRoAQyiIFhwwAxiGCNDV0YQ4JNAimgaMkGmzVkOJ863jeIkm3fiFZ3@OvxwisPqhK1k7JjPobBsuYwzKXiQrveynFna6vTuW4ubcevt/4uBvlQo36@JvP@/Aap@SBG6@/jgFBiffkH "Perl 5 – Try It Online")
106 bytes of code +1 for -p
[Answer]
# [Ruby](https://www.ruby-lang.org/), 96+1 = 97 bytes
Uses the `-p` flag.
```
i=0
m=[3,19,22,17,11,8,7,6,4,3].flat_map{|k|[i+=1]*k}
i=0
$_[i-1,0]=' 'while~/$/+1>i+=1+m.sample
```
[Try it online!](https://tio.run/##JYzNbsIwEITvPAUHJCRifgxVaQ/pi0QRWsferr0OibIYFJX20Zs66nFmvm@GZMZp8uVh0ZbVSel3dTwqfVZaqzd1Vq/qRZ3qHUa4XVrov578rHxR6nrD34vZWl0qv9XqUJfr5fpBPrqf/Wpf6I@ZKtqdQNtHN00gTRo7n@DhBr4asNTccyLxNqEbDEIUtoHukZtA4JPYESGIQ8NiDXLeQ74ACY4wcqBszEsk@bQIkjLvOPy3ASkyZHlMHkYrjAGELM6lJczEb9fffHeVadv/AQ "Ruby – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~168~~ 152 bytes
```
<v?(0:i
~/<r
/x\/oo \
012\oo~\!/ !ox\
\v/:1=?^?\ooo>>
x^
v\:1\/>> o
|/o\=\x^!/
voo/? >x
v\o~/ v_
>" "\?\x>xoo\
^oooooo<<< \
^.22/ \>x!/xv
^ooooooo_o<<<
```
[Try it online](https://tio.run/##7Y4xCsMwEAT7e8XJVaqc5dLIp48ccmfiaiEBcUXw1xU5kFfEC9PsFLvb/nq0lmq@jfNOh6QniZsAbDTGyYDDgnCAG1mVOS655N5CldgLVZujiSqD3gJbzEsQqoBkVu8ah3BdSQceLJurA0YF36SU@ky5T5OwqQfx@lNYT9va1v9dXFz8Jx8 "><> – Try It Online"), or watch it at the [fish playground](https://fishlanguage.com/playground)!
Randomness is tricky in ><>: there's only one random instruction, `x`, which sets the fish's direction to either up, down, left or right. This is a complicated program, so here's a colour-coded diagram to help you:
[](https://i.stack.imgur.com/8qRva.png)
I tried to split up the probabilities into chunks so that the probabilities within and between the chunks were fairly simple (preferring, say, 1/3 to 25/72). I did this as follows:
[](https://i.stack.imgur.com/WkzRq.png)
The fish starts at the grey bit of the code (**X**). This is fairly standard ><> code to read in all of the input. It gets more interesting, so let's move on.
Next, the fish comes to the light and dark green sections (**Y**). You may notice from the probability tree that the three major branches each sum to 1/3, and that each of these branches splits into a 2/3 sub-branch and a 1/3 sub-branch. The green sections of code cover these two levels of the tree. First, we pick a random number out of 0, 1, 2 with equal chance of each, in the top lobe of the light green bit. We can simulate a 1/3 chance using the four-way instruction `x` by cutting off one of the exits so that it just redirects the fish back to the `x` — then there are only three escape routes from the `x`, and by symmetry they have equal probabilities.
The next `x`, a little below this one, sends the fish to the `^` next to it with 2/3 chance — note that the fish wraps around if it swims left from the `x` — and down to a `\` with 1/3 chance. The fish then swims along one of the two tails of the light green section. These tails are functionally the same: each checks if we pushed 0, 1 or 2 earlier, and branches out accordingly. And this completes the first two levels of the tree.
The next six sections (**A**–**F**), in essence, use more `x`s to branch the fish further, and then use some number of `o`s to print a number of letters from the input. These sections range from straightforward (e.g. dark blue, **C**, which just prints three letters) to, well, not so straightforward (e.g. orange, **D**, which needs two `x`s to simulate a 3/8–5/8 split, printing letters in multiple stages). The details of these are left as an exercise. (I'm particularly pleased with yellow, **E**, which sends the fish in a loop-the-loop!)
After each of these branches, the fish ultimately reaches the pink section (**Z**). This draws all the branches back together, prints a space, then finally makes the fish jump to position (2,2) in the grid and start again at the first `x`.
---
In case the "it's complicated" explanation above doesn't convince you that this gives the correct probabilities, I also tested this on a length 65,000 input string (64 KiB, only 13 seconds in TIO!), and the resulting distribution of word lengths was
```
{{1,0.027377},{2,0.191237},{3,0.226599},{4,0.164128},{5,0.113064},{6,0.0818627},{7,0.0703885},{8,0.0543515},{9,0.0426089},{10,0.0283835}}
```
These probabilities are at most 0.0044 away from the expected probabilities.
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/1771/edit).
Closed 7 years ago.
[Improve this question](/posts/1771/edit)
I posted this to [The Daily WTF coder challenge forum](http://forums.thedailywtf.com/forums/t/10689.aspx) a few years ago but only got one response. I figure CodeGolf stack exchange might generate more interest!
**Description**
Write a program that runs when the rows and columns of the source code are transposed.
In other words, imagine each character on each line is a cell in a matrix (pad out shorter lines as necessary to make the matrix rectangular). Write a functioning program that still functions even if its "matrix" is transposed.
*This is just a creative puzzle, not a golf.*
**Details**
1. The program must execute without error and do something interesting\*
2. The transpose of the program must execute without error and do something interesting, although not necessarily the same thing as the original.
3. Any language.
4. No shebang required.
5. Single row/single column entries disallowed.
\*Interesting is the subjective opinion of the CodeGolf community.
**Deadline** April 15 2011
**Trivial Example**
Here's a really stupid example, but it illustrates the rules pretty well. Of course, any "symmetric" program will meet this challenge, but I encourage you to try non-symmetric programs.
```
# #####################
print "hello,world\n";
#r
#i
#n
#t
#
#"
#h
#e
#l
#l
#o
#,
#w
#o
#r
#l
#d
#\
#n
#"
#;
```
**Transposer Reference Implementation**
Here's a perl snippet that does the type of transposing that I am talking about. *This is not the objective of the puzzle, it is just a helper tool.*
```
#!/usr/bin/perl
my @matrix;
open('SOURCE', $ARGV[0]);
my $matrixwidth = -1;
my $matrixheight = 0;
foreach (<SOURCE>) {
chomp;
if ($matrixwidth < length $_) {$matrixwidth = length $_}
my @row = split(//, $_);
push @matrix, \@row;
$matrixheight++;
}
foreach my $x (0 .. ($matrixwidth-1)) {
foreach my $y (0 .. ($matrixheight-1)) {
print(defined $matrix[$y]->[$x] ? $matrix[$y]->[$x] : ' ');
}
print "\n";
}
```
[Answer]
Here's one I came up with when I originally wrote the challenge a few years back. It's a perl script that can transpose other scripts. You can run it on itself, save the output as a new script, then run that new script on itself to get the original.
```
####### p $f f ]'
# ofm u $ ho o -
# poy s w +r r p>'
# er ####h########=##+ # r[}
open 'M' , $ARGV[ 0] ; # i$p
for(; <M> ; ){ # nxr
#((@ $ }( ( t]i
#';r # $ $ ?n
#M<= @ r x y $t
#'M m + = = m
# > , 1 0 0 ["
my @r= $_ =~ /./g;# > ; ; $\
# _ / \ # yn
push @m, \@r; # ]"
# ;= r $ $ -}
# ~ ; $ x y >
$w=($#r + 1> $w) # [
?$#r+1: $w ;$h++}# ? < < $
for ( $x=0 ;$x<$w; # x
$x++ ){ # ]
for ( $y=0 ;$y<$h;
$y++ ){ #$
print #$ $ h d:
defined # w ; e
#$)/ # r ; $ f
#A{. + $ y i
#R#/ 1 x + n
#G g : + + e
#V ; + ) d
$m[ $y]->[$x]
#0 # ) { $
?$m[$y]->[$x]:' '} # m
#) $ { [
#; w $
print "\n"} # ; y
```
[Answer]
## c
Not-quite-trivial, not-quite-symmetric solution that prints it's command line arguments, one per line. As shown it prints them in order, as transposed in reverse order.
```
/*******ipcc;m(acaw-{aa)
********nuohiairhrh-prr;
********ttnaningagiaugg}
******** ssrtntcrvlrtvc}
******** (t* ,*)egs[]
******** s *{(c(
******** ) )
*******/
int
puts(
const
char*s)
;int
main
(int
argc,
char**
argv){
int i;
for(i=1;
i<argc;
i++)
{puts(
argv[i]
);}}
```
] |
[Question]
[
Given a positive input \$n\$, output a random pair of primes whose difference is \$n\$. It's fine if there's another prime between them.
Every pair should possibly appear and the program should have zero possibility to fall into infinite loop.
It's promised that such pair exist, but not always infinite, so beware. You also shouldn't assume it's infinite for even \$n\$ until a proof exist.
Test cases:
```
2 -> [3,5], [11,13], [29,31], etc.
3 -> [2,5]
4 -> [3,7], [19,23], etc.
7 -> Undefined behavior
```
Shortest code win.
[Answer]
# [R](https://www.r-project.org/), ~~111~~ ~~105~~ ~~103~~ ~~73~~ ~~70~~ 69 bytes
*Edit: -2 bytes thanks to Robin Ryder (as well as -5 more bytes for the now-discarded previous version)*
```
function(s){while(sum(!(z=T+s*0:1)%%rep(2:T,e=2))>1)T=1+rpois(1,9)
z}
```
[Try it online!](https://tio.run/##TY/RTsMwDEXf@xVGaJLD8tAUhlil8hX9gVBSZilLotjZtCG@vaRoSHu0fXXOdV5SpqPjZCcKX8MylzAJxYCsvs8H8g65HPEBr8O45ae2N2qzyS5h14/aDZ1S70aNg9nmFInR6L1qrj/LI2THxQvDHDPMlFlgdmc4WU@fcJNx37BNyV9wwk4/6xe906/6Te@1aZW@r6WaphJLAB8rMs4g6@2PfUusyw4kAnlfWLIVB3KwAtaLy2Ed/xvZ7CBFZvrwrm8qAwkogOm7VlVpELxXY31x@QU "R – Try It Online")
Picks random numbers `n` until (`n`,`n+s`) are both prime.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
Generates a random integer \$k\$ until both \$k\$ and \$k+n\$ are prime.
```
[΂[>₄Ω#}DpP#
```
[Try it online!](https://tio.run/##ASsA1P9vc2FiaWX/MTAwMEb/W8OO4oCaWz7igoTOqSN9RHBQI/99y4Z9wq/Dqv8y "05AB1E – Try It Online") Runs the program 1000 times and shows the unique results.
**Commented:**
```
[ # loop:
΂ # push [0, input]
[ } # loop:
> # increment both integers
₄Ω # draw a random digit of 1000
# # if this is 1, stop the loop
D # duplicate the current pair
p # for both integers: are they prime?
P # take the product
# # if both are prime, end the main loop
```
---
Old answer that always just generates one random integer, 22 bytes:
```
∞+∞ø.ΔpP}D[₄Ω#>}DpP_i\
```
[Try it online!](https://tio.run/##yy9OTMpM/W9oYODm@f9RxzxtID68Q@/clIKAWpfoR00t51Yq29W6FATEZ8b8r7VXV7D/bwQA "05AB1E – Try It Online") Runs the program 100 times to demonstrate different outputs.
`∞+∞ø.ΔpP}` finds the first valid pair.
`[₄Ω#>}` is a loops which increments the pair and has a \$50\%\$ probability to stop at every iteration.
`DpP_i\` removes the new pair if any of the numbers is not prime.
[Answer]
# [Haskell](https://www.haskell.org/), ~~132~~ 130 bytes
```
f$[2..]>>= \x->[2..x]
f(x:y)n=do b<-randomIO;last$f y n:[pure(x,x+n)|b,p x,p$x+n]
p n=all((>0).mod n)[2..n-1]
import System.Random
```
[Try it online!](https://tio.run/##ZY5da4MwGIXv/RUvxQvFJLTug62rudrNYKOwXmoYaTWtLHkTTGQK@@1zWna3c/ccDg/nIv1no/XUGme7AIfRh8awd4m1NdFf@SyDZK@tD0Ap9L6pwaIeoUUIlwaUtaHponNRTSouc8YE5wVUA@ULDCJSybAdUyxqC8cd7a7ql/2Tlj7ECkbAben6rkkGMmSYfh@Jg4G4eAYROcBCap0kfJ0yY2vAdLEi3YiI0v@XJyNbLJRuHRjp3j7KnNyQW3JH7skDeRQxVEh5bSMAvaPYH3cxX3bJyeL85rzoN4xt1teIeeb6cAhd7C/2CzDLVkA5rLLsynrmClfTz0lpefYTPTk30X3@Cw "Haskell – Try It Online")
The relevant function is `f$[2..]>>= \x->[2..x]`, which takes `n` as input and returns a random pair of primes `(x,x+n)`.
Definitely not the shortest possible answer, but what I like about it is that, when given enough time, it will actually generate *every* possible pair of primes at distance \$n\$, no matter how large. Also, unlike my two other answers below, it has the nice advantage of actually taking less than a googol years to produce some output.
## How?
The idea is to iterate over the list
```
[2..]>>= \x->[2..x]≡[2,2,3,2,3,4,2,3,4,5,2,3,4,5,6,2,3,4,5,6,7,...]
```
which contains every integer \$\ge 2\$ infinitely many times. Whenever we encounter a number \$x\$ such that \$x\$ and \$x+n\$ are prime, we output the pair \$(x,x+n)\$ with probability \$\frac{1}{2}\$ (`b<-randomIO` picks a `Bool` at random), otherwise we keep going. The program will halt with probability \$1\$, however the probability of outputting anything other than the first pair is *very* low, especially for larger values of \$n\$. The TIO link above runs the function \$1,\!000,\!000\$ times, and collect the unique results.
# [Haskell](https://www.haskell.org/), ~~115~~ ~~102~~ 104 bytes
* -13 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).
```
f n=do x<-randomIO;last$f n:[pure(x,x+n)|x>1,p x,p$x+n]
p n=all((>0).mod n)[2..n-1]
import System.Random
```
[Try it online!](https://tio.run/##bY29DoIwFEZ3n@IODhApEUe07EwmOhKGAkUb@3NTLrEkxkcXG2fHc5LvfHcxPaTWqzLoPMF1mUia/CLs4Mw6guWDg3Bi/ifq81GLibbRlw3OXiYhCzubvkK1zxBChtuI7QbjzrghYejdMPfUHPLcsqJNLefFhrE/V0Yoy8fkUJa1JXmTPq0qjl5ZAsbgqbQGUkaCmykS3SGmO9EprWiBd7F@@lGL27SyHvEL "Haskell – Try It Online")
The relevant function here is `f`.
This code will *almost never* run in a reasonable amount of time, but theoretically, if given enough time, it should output all the prime pairs \$(x,x+n)\$ with \$x<2^{63}\$ (the `System.Random` random generator can't generate numbers larger than this).
## How?
This is the naive approach: generate a random number \$x\$, check if \$x\$ and \$x+n\$ are prime, and in this case return \$(x,x+n)\$. Otherwise try again.
# [Haskell](https://www.haskell.org/), 117 bytes
```
(2?)
x?n=do d<-randomIO;last$(x+d)?n:[pure(x,x+n)|d>0,x>1,p x,p$x+n]
p n=all((>0).mod n)[2..n-1]
import System.Random
```
[Try it online!](https://tio.run/##bY2xTsMwFEX3fMUbOthqHEjYAk7mTkgwVh3c2G0t7Ocn50W4EuLTCREzwxnuGe65mfnDhbD6SCkzvN9ndrF5M2hTXEU3yqqMqG0C@6Lynz28Pgcz806UvZUj9kdashOlLnuUX3Z4rMsGQalpt6lTRYA6JisU5WSXiY9d06BqTxK1biul/ulG41FfxFPfH5Dd1WU5DJqyRwal4NOHAOyjg7TwtvgG2/XZnH3wfIfv9qFbf6ZLMNd5VRPRLw "Haskell – Try It Online")
The relevant function is `(2?)`.
A mix of the two solutions above. It has the theoretical guarantees of the first (given enough time, it should generate all the prime pairs with difference \$n\$, even if the primes are larger than \$2^{63}\$). However, the probability of generating some output within a reasonable amount of time is close to \$0\$, except if \$(2+n)\$ is prime.
## How?
Start with `x=2`. If `x` and `x+n` are both primes, then return `(x,x+n)` with probability \$\frac{1}{2}\$. Otherwise, add a random number `d` (which can be positive or negative) to `x` and repeat.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~16~~ 15 bytes
```
`,1r/kYq]-G-}2M
```
Outputs the two primes in decreasing order. [**Try it online!**](https://tio.run/##y00syfn/P0HHsEg/O7IwVtddt9bI9/9/YwA)
### Explanation
Let \$q(k)\$ denote the \$k\$-th prime: \$q(1)=2\$, \$q(2)=3\$, \$q(3)=5\$, \$\ldots\$
The code generates two random primes \$r\_1, r\_2\$ independently with distribution
\$\quad \displaystyle \Pr[r\_i = q(k)] = \frac 1 {k\cdot(k+1)}; \quad i = 1,2; \quad k = 1,2,3,\ldots\$
The distribution of \$k\$ is easily obtained as the inverse of a normalized uniform random variable rounded down. Each pair of primes has nonzero probability of occuring.
If the two generated primes happen to differ by the input \$n\$, they are displayed and the program ends. Else the process is repeated.
```
` % Do while
, % Do twice
1 % Push 1
r % Push random number between 0 and 1
/ % Divide
k % Round down. Gives a random positive integer, k
Yq % k-th prime
] % End
- % Subtract. Gives the difference between the two primes (*)
G % Push program input, n
- % Subtract. (This will used as the loop condition) (**)
} % Finally (execute on loop exit)
2M % Push inputs to second-to-last normal function (*): latest two primes
% End (implicit). A new iteration will be run if (**) is nonzero
% Display stack (implicit)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 15 bytes
```
ḟΛṗmoSe+⁰L↓x1İπ
```
[Try it online!](https://tio.run/##yygtzv7//@GO@edmP9w5PTc/OFX7UeMGn0dtkysMj2w43/A/sSjdUMFWoaAoMzdVobggMTkzL10hz1oBKG4EFC9OTU1RSMsvUihKzEvJz1XIK81NSi1SSE/NSy1KLMnMz/v/3@i/oZExAA "Husk – Try It Online")
**Note: requires input of a random 'seed' to generate different output on different runs**
[Husk](https://github.com/barbuz/Husk) is completely deterministic, and has no built-in random number generator. However, some googling indicates that the digits of Pi have been shown to be 'random' (in a certain statistical sense), if a set of constraints about the distribution of chaotic sequences holds true (1). Although this conjecture is still unproven, it suggests that we can use the digits of Pi as the basis for a random number generator, until proven otherwise (2).
Obviously, Pi is constant, so we will need to 'seed' the random number generator if we wish to obtain different results for successive runs of the program. However, one could argue that this is not substantially different from the 'seeding' of other pseudo-random number generators in other programming languages.
So: our Pi-based random number generator (`mL↓x1İπ`: [try it!](https://tio.run/##AUsAtP9odXNr/@KGkTEwMOKCgeKBsP9tTOKGk3gxxLDPgP9hcmcxID0gc2VlZCBmb3IgcmFuZG9tIG51bWJlciBnZW5lcmF0aW9u//8xMjM)) outputs the separation between occurrences of the digit `1` in the decimal representation of Pi, after skipping the first `s` outputted numbers with `s` given as the 'seed'. I believe that this series should include all non-negative integers with non-zero frequency. Please correct me if I'm wrong!
With that out of the way, here's the 'random pair of primes' program, which simply outputs the first pair it finds of randomly-picked numbers with spacing `n` that are both primes:
```
İπ # Get the (decimal) digits of pi as an infinite list;
x1 # split into sublists on every occurrence of the digit '1';
↓ # discard as many initial sublists as the random 'seed';
L # and get the length of each sublist:
# this is our random sequence.
moSe # Now, for each random number, make a 2-element list
+⁰ # by combining with itself plus the input value of 'n';
ḟ # and output the first 2-element list that satisfies:
Λṗ # both elements are primes.
```
[This link](https://tio.run/##ATUAyv9odXNr/21v4oKB4oGw4oaQ4bijMTAw/@G4n86b4bmXbW9TZSvigbBM4oaTeDHEsM@A////NA) tests `n=4` for random seeds of 1..100 to confirm that various different outputs can be obtained when there is more-than-one solution;
[This link](https://tio.run/##ATUAyv9odXNr/21v4oKB4oGw4oaQ4bijMTAw/@G4n86b4bmXbW9TZSvigbBM4oaTeDHEsM@A////Mw) tests `n=3` for random seeds of 1..100 to confirm that when there is only one solution, this is always outputted.
(1) <https://www.nersc.gov/news-publications/nersc-news/science-news/2001/are-the-digits-of-pi-random/>
(2) And if that's not Ok, then this is probably not Ok either: <https://codegolf.stackexchange.com/a/223136/95126>
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 40 bytes
```
{⍵{⍵[⊃(?∘⍴⌷⊢)⍸⍺=-∘.-⍨⍵]}(⊢~∘.×⍨)1↓⍳3300}
```
Not entirely certain that I understood the problem statement. I run out of memory with primes larger than around 3300. Not great, but it's my first stab at it.
```
⍵{...} ⍝ passing user input to nested function as left argument
⍵[...] ⍝ retrieving primes for given index values
⊃(?∘⍴⌷⊢) ⍝ randomly selecting pair of primes from list
⍸⍺= ⍝ index value of every difference equal to the user input n
- ⍝ negation
∘.-⍨⍵ ⍝ matrix of all possible differences between primes
(⊢~∘.×⍨) ⍝ list of primes in range (inclusive) found by not being members of the composite matrix (created by outer product)
1↓⍳3300 ⍝ range 2–3300 (determined by tio memory limit, though TryAPL allowed for double that)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71bQTj6UVezhv2jjhmPerc86tn@qGuR5qPeHY96d9nqAgX1dB/1rgCqiq3VAMrUgUQOTwcKaRo@apv8qHezsbGBQS3QQAVDrjQFIyA2BmITIDY0ABNQEkQBVRoAAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 68 bytes
```
f=n=>(g=d=>k%--d?g(d):d>1)(k=2/Math.random()|0)|g(k+=n)?f(n):[k-n,k]
```
[Try it online!](https://tio.run/##jcpBC4IwFADge7@iS/getWXWJeEpnaVTx5AYbppNN9FRFP72VlD3@s7fRVzFUPR155ixUnlfkqEEKpKU6BljMq1AYiyTFYKmaLkX7sx7YaRtAccQxwr0nAymJRiMj5qZhc59RkfO@a7vxR1WYRhiPimsGWyjeGMrMOo2PSgHGW9FBydKSohwHgSI@Out/3yb7/NP27n6fT1jgxOFZkP9ULT9eAE "JavaScript (Node.js) – Try It Online")
Still shorter than Arnauld's wrong answer
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
2‘XḂ$¿,³Ä¹ßẒẠ$?
```
A full program that prints a random, valid pair - if given enough time and recursion stack/memory (recursion depth is set to \$2^{30}\$ in TIOs interpreter/Dennis' GitHub; but we seg-fault before then generally).
**[Try it online!](https://tio.run/##AScA2P9qZWxsef//MuKAmFjhuIIkwr8swrPDhMK5w5/hupLhuqAkP////zQ "Jelly – Try It Online")** Note that there is a seg-fault for high `n` (or always for those invalid `n` which are odd while `n+2` is not prime).
### How?
Chooses a random integer greater than 1, pairs it with the integer that's `n` greater. Then, if both are prime stops and outputs, otherwise repeats the whole procedure again.
The procedure for choosing a random integer, while golfy, will find low numbers exponentially more often than high numbers, so the lowest possible pair is produced extremely often with even modest n.
```
2‘XḂ$¿,³Ä¹ßẒẠ$? - Main Link - called with 1 program argument, n
2 - set the left argument, say v, to two
¿ - while...
$ - ...this is true: last two links as a monad - f(v):
X - random integer in [1,v]
Ḃ - is odd?
‘ - ...do: increment
,³ - pair with n -> [v, n]
Ä - cumulative sums -> [v, n + v]
? - if...
$ - ...condition:
Ẓ - is prime (vectorises)
Ạ - all?
¹ - ...then: no-op
ß - ...else: call Main Link again
- implicit print
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 25 bytes
**Warning:** This **will** hang your browser if the random value is unfavorable. It does however not have an infinite loop, just a very, very long runtime in bad cases.
This relies on the given assumption that a satisfactory pair is guaranteed to exist. Starting from a random whole number ensures that any pair can be returned, after that we just move -1, +1, -2, +2 etc until we find a number that satisfies the input.
```
@T=[X,X+U];Tej}c(1/Mr)c;T
(1/Mr)c // Starting from a random whole number,
@ }c // try that number -1, +1, -2, +2 etc until we find one where
T=[X,X+U]; // that number as well as that number plus input
Tej // are both prime.
;T // Return the resulting array.
```
[Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=QFQ9W1gsWCtVXTtUZWp9YygxL01yKWM7VA==&input=LVEKNA==)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~14~~ 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as a single integer array. Weighted very heavily towards the earlier pairs in the sequence.
```
iT Èej}a@m+Xö
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=aVQgyGVqfWFAbStY9g&input=WzJd)
] |
[Question]
[
Leonhard Euler wants to visit a few friends who live in houses *2, 3, ..., N* (he lives in house 1). However, because of how his city is laid out, none of the paths between any houses form a loop (so, the houses exist on a graph which is a tree).
He gets bored easily but if he visits his friends in a different order, he won't be bored. So, he wants you to help him find how many unique ways there are for him to visit every friend and return home by the end of the day.
He doesn't have a map of his city, but he does remember the order of houses he visited last time he went on a walk.
## Problem Statement
Given the [Euler Tour Representation](https://en.wikipedia.org/wiki/Euler_tour_technique) of a tree, determine the number of unique ETRs of the same tree, with the root at 1.
## Input
The ETR of a tree. The Euler Tour Representation essentially starts at the root and traverses the tree depth-first writing out the label of each node as it goes along. A 3-node tree with one root and two children would be represented as `1 -> 2 -> 1 -> 3 -> 1`. A 3-node tree with one root, one child, and one grandchild would be represented as `1 -> 2 -> 3 -> 2 -> 1`.
In other words, it represents the Eulerian circuit of a directed graph derived from creating two edges from each edge in the tree, one in each direction.
Here is a visual example of an ETR:
[](https://i.stack.imgur.com/8OqFC.png)
I will allow a few alterations to the input:
1. You can choose if you want leaf nodes to be written once or twice consecutively.
2. You can choose if you want to return to the root at the end.
For example, here is a tree:
```
1
/ \
2 3
/ \ \
4 5 6
```
The following are acceptable:
* `1 2 4 2 5 2 1 3 6 3 1`
* `1 2 4 2 5 2 1 3 6 3`
* `1 2 4 4 2 5 5 2 1 3 6 6 3 1`
* `1 2 4 4 2 5 5 2 1 3 6 6 3` (this is shown on the Wikipedia article)
You can take the input in any reasonable format for a list of integers. You may also request to input `N` (the number of nodes) first, and to index at any arbitrary value (I use 1-indexing here). However, your node labels starting from `x` must be `x, x+1, x+2, ..., x+N-1`.
## Output
An integer, representing the number of unique ETRs of this tree, starting from the same root node.
## Challenge Specifications and Rules
* note that inputs are NOT always binary trees; see the second test case
* this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") problem, so scoring is by code length with a lower score being better
* no answer will be accepted
* [Standard Loopholes apply](https://codegolf.meta.stackexchange.com/q/1061/68942)
## Test Cases
```
[1, 2, 3, 2, 4, 5, 4, 6, 4, 2, 1, 7, 8, 9, 8, 7, 1] -> 8
[1, 2, 3, 2, 4, 2, 1, 5, 6, 5, 7, 5, 1, 8, 9, 8, 10, 8, 1] -> 48
[1, 2, 3, 4, 5, 6, 7, 6, 8, 6, 5, 9, 5, 4, 10, 4, 3, 11, 3, 2, 12, 2, 1] -> 32
[1] -> 1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1] -> 1
```
If you want to test with more data, my reference implementation is [here](https://tio.run/##XZCxbsMwDERn8ys4ShmCGtkC5EsED0JNNUJsSWDYoQjy7S5pBQjajeK74x3UfuRay2nbEtcV1yhXzGurLJjip1TOcQEQvGAYJx2YSOfHeMYwPaFFpmLw8YRSZ0MfAKkyZswF5QxDTtiJIn0OL1mGgRZl2UA/c/wicYb9f92dbGPZwdbTMbZGZXbZ67qbQ55UbfSPt5t2FrT@TAlJ@K5OvWjFRxis7m2v27V7Fh4uXXnTDCb5ZuV4eH@KW6i4l8N7gMa5iNsto/fb9gs). It's pretty bad but it's correct so you can use it; just modify the list in line 3.
[Answer]
# [Python 2](https://docs.python.org/2/), 45 bytes
```
f=lambda l:l==[]or(l.count(l.pop())or 1)*f(l)
```
[Try it online!](https://tio.run/##dY7NCoMwEITvfYo9JiUU1xr/wCcRD/ZHFNIkSKT06dO4NkUKvcyEzXyza19uNDr1fmhU/7jcelC1apq2MzNTp6tZtAtujWWcmxmQHwemuH@Ok7oD1naetIOBTdouLkR8iwJSAWfSTIAkzUnDJPwWAkoBFWl4Y3f4ZbacJExSSNLki2Gy2R7NIlGQlpGu4g0rlFEUMS7DdLO16F/Z/tg8ln3w7g0 "Python 2 – Try It Online")
It seems that one way to get the answer is take the counts of each node, that is the number of times each node is listed, subtract 1 from each, and multiply their factorials. That is,
$$\prod\_i (c\_i-1)!$$
where node \$i\$ is listed \$c\_i\$ times. Note that it doesn't matter what order the nodes appear in the Euler Tour Representation, only how many times they do. Listing leaf nodes once or twice doesn't make a difference, since \$0!=1!=1\$.
Since Python doesn't have a built-in factorial, we make do like this. For each entry of the list, we will count how many times that same values appears before it, that is label its `k`'th appearance 0-indexed as `k`. For example,
```
1 2 4 2 5 2 1 3 6 3 1
0 0 0 1 0 2 1 0 0 1 2
```
If we then remove all zeroes (or convert them to 1's) and multiply, we get the desired result.
To do this recursively, we repeatedly remove the last element and consider its its count in the remainder of the list, converting any count of 0 to 1. Then, we multiply by the recursive result on the list with its last element now removed, with a base case of 1 for the empty list.
We can save a couple of bytes using splatted input and `True` for 1 if this is allowed.
**43 bytes**
```
f=lambda a,*l:l==()or(l.count(a)or 1)*f(*l)
```
[Try it online!](https://tio.run/##dY7NCoMwEITvfYo9JhKKa41/4JMUD@mPKKSJSKT06dO4NkUKvcwmk/kmO73cYE3mfd9q9bjcFCiR6Ea3LeN2Zvp4tYtxTIULIE96lmjun8Oo74DNNI/GQfBGMy2Oce7PKCATcCLNBUjSgjQ44bUUUAmoScMZu8Mvs@UkYZJCkpwvhuk29mgeiZK0inQdd1ihnKKI8TPMtrEW/SvbL1vEsg/evQE "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~17~~ 11 [bytes](https://github.com/abrudz/SBCS)
Based on [xnor's answer](https://codegolf.stackexchange.com/a/211977/64121). The `⍤` operator requires version 18, which is not yet on TIO.
```
(×/!÷⊢)≢⍤⊢⌸
```
Here is a longer variant that works in lower versions:
```
(×/!÷⊢)∘(+/∪∘.=⊢)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wSNw9P1FQ9vf9S1SPNRxwwNbf1HHauADD1bkMj/R31TFYCKFNIUDBWMFIyB2ETBFIjNgNgIKGauYKFgCcTmCoZc2NSC1JgCVZsCVZgC2RDVhgYgAkODCVipORBbgLVYgq0CKjYBShoago00NAIRyFof9W7BbRTMdWZgo8AG/AcA "APL (Dyalog Unicode) – Try It Online")
`+/∪∘.=⊢`/`≢⍤⊢⌸` counts the occurrences of the unique items in the input, `×/!÷⊢` calculates $$\prod\_i{c\_i!\over c\_i}$$
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 27 [bytes](https://github.com/abrudz/SBCS)
I think this works with all suggested input formats.
```
{2>≢⍵:1⋄(×/∇¨,∘!≢)⍵⊆⍨⍵≠⌊/⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqI7tHnYse9W61MnzU3aJxeLr@o472Qyt0HnXMUARKaAJlHnW1PepdAWJ0LnjU06UPZNX@f9Q3VQGoXSFNwVDBSMEYiE0UTIHYDIiNgGLmChYKlkBsrmDIhU0tSI0pULUpUIUpkA1RbWgAIjA0mICVmgOxBViLJdgqoGIToKShIdhIQyMQgaz1Ue8W3EbBXGcGNgpswH8A "APL (Dyalog Unicode) – Try It Online")
I don't think the base case `2>≢⍵:1` is really necessary, since at some point there are no subtrees left to recurse on, but I can't get this to work without it.
**Commented:**
```
{2>≢⍵:1⋄(×/∇¨,∘!≢)⍵⊆⍨⍵≠⌊/⍵} ⍝ A recursive dfns
2>≢⍵ ⍝ If the input has less than 2 elements
:1 ⍝ return 1
⍵⊆⍨ ⍝ Partition the input ...
⍵≠ ⍝ ... taking the elements that are not equal
⌊/⍵ ⍝ to the minimum (the root of the current tree)
⍝ These are the new subtrees
!≢ ⍝ Take the factorial of the number of subtrees
, ⍝ And append it to the results of ...
∇¨ ⍝ the recursive calls on each subtree
×/ ⍝ take the product of the vector
⍝ this is the result
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ĠẈ’!P
```
[Try it online!](https://tio.run/##y0rNyan8///Igoe7Oh41zFQM@P//f7ShjoKRjoIxmDQBk0ARUx0FMzBpDiaBIhY6CpZg0tAAQsUCAA "Jelly – Try It Online")
[Count Euler's Tours](https://codegolf.stackexchange.com/questions/211969/count-eulers-tours#comment499070_211977) 5 Byte Jelly Solution, as mentioned by [HyperNeutrino](https://codegolf.stackexchange.com/users/68942/hyperneutrino).
The idea is the same as an earlier python solution, but I'd still like to explain how I came about it.
Note that we can solve this recursively. If our current node is N, with C children, our answer is C! times the product of the sub-answers from all the children. The reason is we can descend (in our euler tour) into the children in any order we so choose.
The second observation is that for every node except the root, where count(x) is the number of occurences of x in the euler tour:
$$count(i) = deg(i)$$
For the root,
$$count(r) = deg(r) + 1$$
Now, if we look at our formula above, we note that our answer is
$$deg(r)! \* [deg(n) - 1]!$$
for every other node `n`. This actually works out hilariously well. We note that, as mentioned before, the answer is:
$$\prod\_{i = 1}^v [count(v) - 1]!$$
This solution lends itself very well to jelly.
```
ĠẈ’!P
```
First, we get the count array that we need, by `Ġ`rouping indices by their elements and taking vectorized length. Then we decrement and factorial, and finally product:
```
ĠẈ Count array
’ Decrement
! Factorial
P Product
```
P.S.: Thanks to [HyperNeutrino](https://codegolf.stackexchange.com/users/68942/hyperneutrino) for helping me with the jelly solution, seeing as my jelly is a bit rusty...
[Answer]
# JavaScript (ES6), 42 bytes
This is based on [@xnor's conjecture](https://codegolf.stackexchange.com/a/211977/58563).
```
a=>a.map(x=>t*=(a[~x]=-~a[~x])-1||1,t=1)|t
```
[Try it online!](https://tio.run/##lZBNDoJADIX3nqJLMANY/lkMFyEsJghGg0CEGBaEq49YGGMiEu3itelMvr72Iu6izW7npjOq@pjLgkvBY2FeRaP1PO72XBPJ2KfcGCnrBg4Dso6jPnQyq6u2LnOzrE9aoSXIwGbgkLoMPFKfdOpMrwGDkEFEOtWYwlroOlgWQLjbxs9IjyZ4xPOo85qAhzmla3j3O95V1IA0VBMitdIT7NJXRGUI7TmlM96xP/Dry/4by3HwJ/fvx/aV@8Xv5u1RPgA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes
```
IΠEθ∨№…θκι¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI6AoP6U0uUTDN7FAo1BHwb9Iwzm/FCRZmZyT6pyRDxbN1tRRyARiQ00QsP7/PzraUEfBSEfBGEyagEmgiKmOghmYNAeTQBELHQVLMGloAKFiY//rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Uses @xnor's algorithm. Explanation:
```
θ Input array
E Map over elements
θ Input array
… Truncated to length
κ Current index
№ Count occurrences of
ι Current element
∨ Logical Or
¹ Literal `1`
Π Take the product
I Cast to string
Implicitly print
```
Using the form of representation whereby leaf nodes are visited once and the root node is considered to have an extra edge so that it gets visited both at the start and the end, then the number of edges for a given node is equal to the number of times it was visited. On the first visit to a node with `n` edges you only have a choice of `n-1` edges since you have to completely traverse all of its subtrees before returning to the parent, and similarly on subsequent visits you have fewer choices until finally the last two visits both give you no choice at all. This could be reduced to the products of the relevant factorials for each node, although as @xnor points out it's actually golfier for some languages to replace each visit with the count of remaining choices and take the overall product (the Charcoal algorithm actually takes the product in reverse order but of course this makes no difference to the total).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ü ®ÅÊÊÃ×
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=/CCuxcrKw9c&input=WzEsMiwzLDIsNCw1LDQsNiw0LDIsMSw3LDgsOSw4LDcsMV0)
```
ü ®ÅÊÊÃ× :Implicit input of array
ü :Group and sort by value
® :Map
Å : Slice off the first element
Ê : Length
Ê : Factorial
à :End map
× :Reduce by multiplication
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ù¢<!P
```
A bit lame, but this is simply a port of [*@xnor*'s Python 2 answer](https://codegolf.stackexchange.com/a/211977/52210) and [*@Riolku*'s Jelly answer](https://codegolf.stackexchange.com/a/211992/52210), so make sure to upvote them!
[Try it online](https://tio.run/##yy9OTMpM/f//8MxDi2wUA/7/jzbUMdIxBmITHVMgNgNiIx1DHXMdCx1LIDbXMYwFAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/8MzDy2yUQz4r/M/OtpQx0jHGIhNdEyB2AyIjXQMdcx1LHQsgdhcxzBWB0kNSM4UqMoUKGMKZENUGRqACLhCE7AScyC2ACu1BBsNVGQClDQ0BBtlaAQiQFowtMFsNgNrAyuOjQUA).
**Explanation:**
```
Ù # Uniquify the (implicit) input-list
¢ # Count how many times each occurs in the (implicit) input-list
< # Decrease each count by 1
! # Take the factorial on each value
P # And take the product of that
# (after which it is output implicitly as result)
```
[Answer]
# [Perl 5](https://www.perl.org/) `-ap`, 27 bytes
```
$\=1;$\*=$h{$_}++||1for@F}{
```
[Try it online!](https://tio.run/##XY3BCsIwDEDv@4ocKgPHZJntulEGnrz5BwXZwbGB2rJ5Gdt@3ZpWRfDwkpC8JPYyXIW7TZtOjc3EdN8yrZiu41g5Skj1tmbdzM5rkiwLtmY4HNfZOYQc9gQHQRREDggSSqgICRj9DD8R5AjqC6rfDmY@fDQeBEmUQazCWVI4DRHDIcx9iP5Xvh@LsBLEp7GP3txHlzbWpSexy/AF "Perl 5 – Try It Online")
] |
[Question]
[
## Introduction
Some time ago, I need to write function which split string in some specific way. At the first look, task looks trivial, but it was not so easy - especially when I want to decrease code size.
## Challenge
As example we have following input string (it can be arbitrary)
>
> Lorem ipsum dolor sit amet consectetur adipiscing elit sed doeiusmod tempor incididunt ut Duis aute irure dolor in reprehenderit in esse cillum dolor eu fugia ...
>
>
>
We need to splitting it into elements (
groups of adjacent words) using following rules (A-E)
```
"Lorem ipsum dolor", // A: take Three words if each has <6 letters
"sit amet", // B: take Two words if they have <6 letters and third word >=6 letters
"consectetur", // C: take One word >=6 letters if next word >=6 letters
"adipiscing elit", // D: take Two words when first >=6, second <6 letters
"sed doeiusmod", // E: Two words when first<6, second >=6 letters
"tempor" // rule C
"incididunt ut" // rule D
"Duis aute irure" // rule A
"dolor in" // rule B
"reprehenderit in" // rule D
"esse cillum" // rule E
"dolor eu fugia" // rule D
...
```
So as you can see input string (only alphanumeric characters) is divided to elements (substrings) - each element can have min one and max three words. You have 5 rules (A-E) to divide your string - if you take words one by one from beginning - only one of this rule applied. When you find rule, then you will know how many words move from input to output (1,2 or 3 words) - after that start again: find next rule for the remaining input words.
Boundary conditions: if last words/word not match any rules then just add them as last element (but two long words cannot be newer in one element)
In the output we should get divided string - each element separated by new line or `|` (you don't need to use double quotes to wrap each element)
## Example Input and Output
Here is example input (only alphanumeric ASCII characters):
```
Lorem ipsum dolor sit amet consectetur adipiscing elit sed doeiusmod tempor incididunt ut Duis aute irure dolor in reprehenderit in esse cillum dolor eu fugia
```
and its output:
```
Lorem ipsum dolor|sit amet|consectetur|adipiscing elit|sed doeiusmod|tempor|incididunt ut|Duis aute irure|dolor in|reprehenderit in|esse cillum|dolor eu fugia
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~92~~ ~~90~~ ~~88~~ ~~87~~ ~~86~~ 85 bytes
```
r=''
n=0
for w in input().split():L=w[:5]<w;x=n+L<3;r+='| '[x]+w;n=n*x-~L
print r[1:]
```
[Try it online!](https://tio.run/##PY7LasQwDEX3@QrtPG2Y0gfdJONdl/mDkEWINTOCWDaSRTJQ@uupF6UgEIh7j05@lHvi9@MQ71zD/rW5JoENiOtkK6enF80r1d0Nfhu7z@my9bvndrh89NJ69w1u3Kd269nz837@GZosxAVkfOum43BDEoxAWS1CSGuFKxWYIxZYEisuBYsJzIEy6UJ8A6zvQDHUOJJpTAEKxlybxAsFClbxVuDLSGG2gkBign/0Ki6YBe/IAaWS6gFVERZa138HNLjajWb3Cw "Python 2 – Try It Online")
-1 byte, thanks to Kevin Cruijssen
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḲµẈṁ3<6Ḅ+8:5⁸sḢKṄȧƲẎµ¹¿
```
A full-program printing the result.
**[Try it online!](https://tio.run/##PY49akJBFEa3cjuLlEEJIaWd2cRj5tPcMD@PuXMLS8HCykWkSS8I79kEXiFuY9zIZAqx/Tjf4XzDuW2tZThN53I5lHH3@rEow/7l7X1@3w1Shp9VGfe33@upXI7TeRqnv1rr7DMmeOJe1JONLiYSztR5ZDIxCExG1kSd5Z7FcNgQXAMEtuFgFR8tZfi@PTkYtmw1ZNJMS2WhTjOIkyY87BwooU/4QrBIzdQGiIAMO/dsgNJaN9zN/gE "Jelly – Try It Online")**
### How?
Given the lengths of three words (`a`, `b`, and `c`) we can write the following mapping for how many word we should take:
```
a<6? b<6? c<6? words
1 1 1 3
1 1 0 2
1 0 1 2
1 0 0 2
0 1 1 2
0 1 0 2
0 0 1 1
0 0 0 1
```
Treating the comparisons as a single number in binary this is:
```
bin([a<6,b<6,c<6]): 7 6 5 4 3 2 1 0
words: 3 2 2 2 2 2 1 1
```
So we can map like so:
```
bin([a<6,b<6,c<6]): 7 6 5 4 3 2 1 0
add eight: 15 14 13 12 11 10 9 8
divide by five: 3 2 2 2 2 2 1 1
```
Note that when less than three words remain we want to take all of them, unless there are two left and they are both of length six or more when case `C` says to take one word. To make this the case we repeat what we have up to length three (with `ṁ3` instead of `ḣ3`) and use that.
```
a<6? b<6? moulded bin + 8 div 5 (= words)
1 111 7 15 3 (i.e. all 1)
0 000 0 8 2 (i.e. all 1)
1 1 111 7 15 3 (i.e. all 2)
1 0 101 5 13 2 (i.e. all 2)
0 1 010 2 10 2 (i.e. all 2)
0 0 (i.e. C) 000 0 8 1 (i.e. just 1)
```
The code then works as follows.
```
ḲµẈṁ3<6Ḅ+8:5⁸sḢKṄȧƲẎµ¹¿ - Main Link: list of characters
·∏≤ - split at spaces
¬ø - while...
¬π - ...condition: identity (i.e. while there are still words)
µ µ - ...do: the monadic chain:
Ẉ - length of each
3 - literal three
ṁ - mould like ([1,2,3])
6 - literal six
< - less than? (vectorises)
Ḅ - from binary to integer
8 - literal eight
+ - add
5 - literal five
: - integer divide
⁸ - chain's left argument
s - split into chunks (of that length)
∆≤ - last four links as a monad (f(x)):
·∏¢ - head (alters x too)
K - join with spaces
Ṅ - print & yield
ȧ - logical AND (with altered x)
Ẏ - tighten (back to a list of words)
```
[Answer]
# [Perl 5](https://www.perl.org/), 47 bytes
seems regex can be shorten with this equivalent one
```
s/(\w{1,5} ){3}|\w{6,} (?=\w{6})|\w+ \w+ /$&
/g
```
[Try it online!](https://tio.run/##PU7LSkNBFNv7FVmItFjvRaTuihuX/QQ3l5nj9cC8OA@6qPfXHacgLgJJSEIaSTr2rvPu43J9Phw37K8v2/cQr4cNu7fTjW37YTzihvn@4W5eez9XoQxu6hmxpipQNiyZDKEWpWBkLlgiN9bAZQWlEVCKI07smmuEUW6jySVw5OjF4IZ3Z8XiRmBxob91LhBqQl9UIslYGgapEgKn9P@BHJ@@8oJpmn5qMx5X@lP7BQ "Perl 5 – Try It Online")
Previous regex
# [Perl 5](https://www.perl.org/), 86 bytes
```
s/(\w{1,5} ){3}|((\w{1,5} ){2}|\w{6,} )(?=\w{6})|\w{6,} \w{1,5} |\w{1,5} \w{6,} /$&
/g
```
[Try it online!](https://tio.run/##TY69SgRBEIRzn6IDkT04d1E5s8PE0EcwWWbKtWH@6J7G4HZf3XGEWzGrKr4qqkDCqTWdhvevy8PxtNHh8rStwz/7uK3dPB@7Hl7Ov3I77MlOrbu45tPt3c20tPaWBZG4qEXyOWQh5UpzRCWXk8JVVBOaPRdWx2khhA4ofMfBpjF7qoilNzk59uwtVbJKr8ZKs1UQiwmu65xIUASfSB7Sl3oAVZDjEP4@wOjDFp5pHMfvXCr3K@2@/AA "Perl 5 – Try It Online")
Not valid:
# [Perl 5](https://www.perl.org/) (`-M5.01` `-lnF/(?:\S{1,5}\K\s+){3}|\S{6,}\K\s+(?=\S{6})|\S+\s+\S+\K\s+/`), 9 bytes
```
say for@F
```
[Try it online!](https://tio.run/##PY7LSgNBEEV/pZYJSSYGGReCJAvJRl25nU3TXYkF/aIeC4nz67Y9KG4KzuHW5VbkOLYm7hMuhU/n1l4LYwKqYglCiYVBSMElVPAlC3pFNQYXqJJ4ylfA2AOCoceRTFIJoJhq/6TsKVCwrGAKz0YCzhSB2Bj/2ikDY2X8wByQe1MXKILgKcb/DWhwsSs5GIbhu1SlPqXt3sbh7tB2MZ/3q@Pj9H47bMd5eplks77dz19dPGx/eXV8Wmhed7npvNzF738A "Perl 5 – Try It Online")
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 65 bytes (thanks manatwork!)
```
BEGIN{RS=FS}{printf(x=n+(L=length($1)>5)<3)?FS$1:"|"$1;n=n*x+L+1}
```
[Try it online!](https://tio.run/##PY7RSsQwEEV/ZVj60FooFPFF7QqiK0LxwX5BSGa7g8kkJDO4sO631zyIr5dzD8d8f23b8@vb@8flc5kOy/WSMrEc2/PEfTtPHnmVU9uM3f6ue7ztng5LM97vfnbN@MAT35z7uR@v2zbHjAEoFQ3goo8ZCgmYgAI2ckErKJrBOEpULPEK6CtQ0FUcSUuIDgRDqk9iS46csoAKvCgVMCoIlDXjn50YMqaMJ2SHuZrqgKUgWPL@vwEVjrqSgWEYfgE "AWK – Try It Online")
I didn't even know AWK had a ternary operator
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 97 79 72 bytes (thanks manatwork!)
```
BEGIN{a[0]="|";a[1]=RS=FS}{printf a[x=n+(L=length($1)>5)<3]$1;n=n*x+L+1}
```
[Try it online!](https://tio.run/##PY5BSwMxEEb/ylB6aF1YuoinGg9iFWHxYI/LHsJmuh1MJiGZwULtb19zEK8f73s8@/21LM@Ht/ePqx12o1n9rPZ26EbzeTSvx9s1ZWI5gR0uhptNbzzyLOfNuts@PWwf78d1t2fDd5emb7rbsvQxYwBKRQO46GOGQgI2oMAUueAkKJrBOkpUJuIZ0FegoKs4kpYQHQiGVJ/EEzlyygIq8KJUwKogUNaMf3ZiyJgynpEd5mqqA5aCMJH3/w2ocNKZLLRt@ws "AWK – Try It Online")
I shamelessly stole the algorithm from @TFeld's Python2 solution.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Commands)
```
0U#v„
yg6@DX+3‹DŠX*+>Uèy}J¦
```
Port of [*@TFeld*'s Python answer](https://codegolf.stackexchange.com/a/193568/52210), so make sure to upvote him!
[Try it online.](https://tio.run/##PY4xCgIxEEV7TzFg5zaCYCkWW4mtYBuT7zqwSZZMRrAQPIlYiVewVbzIXmRNIbaf9x8vitkxhmG6GR/7y3VEp2a@rLfVrL88689tO6kWm/fjdF697sOwjgmeuBP15GIbEwlnMh6ZbAwCm5E1kXHcsVgODaEtgMAVHKzio6MM35UnB8uOnYZMmqlWFjKaQZw04WfnQAldwgHBIRVTGSACsty2/wYo7bVh8wU)
**Explanation:**
```
0U # Set variable `X` to 0 (it's 1 by default)
# # Split the (implicit) input-string on spaces
v # Loop over each word `y`:
yg # Get the length of the word
6@ # And check that it's >= 6
D # Duplicate this
X+ # Add variable `X` to it
3‹ # And check that it's smaller than 3
DŠ # Duplicate this as well, and triple-swap (a,b,c to c,a,b)
X* # Multiply the <3 check with variable `X`
+ # Add it to the length >=6 check
>U # Increase it by 1, and set it as the new variable `X`
„\n è # Index the <3 check into the string "\n "
y # And push the current word
}J # After the loop: join the entire stack together
¦ # And remove the leading space
# (after which the top of the stack is output implicitly as result)
```
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 206 bytes
```
import StdEnv,Text
$s=join"|"(map(join" "o map fst)(?[(w,size w<6)\\w<-split" "s]))
?l=case l of[a,b,c:t]|all(snd)[a,b,c]=[[a,b,c]: ?t];[a:t=:[b:_]]|not(snd a||snd b)=[[a]: ?t];[]=[];l=[take 2l: ?(drop 2l)]
```
[Try it online!](https://tio.run/##PZA/T8NADMX3fgor6pBI7cLAkDbqUgakDkhlSyPk3jnFcH@iOx8FlM9OuFJg8vPTz5b9lCF0k/U6GQKL7Ca2gw8Ce9F37m3xSO8ym8fmxbMrxqK0OJQ/Ggqf@QH6KFW5acvzIvInwXl9Wx0O5/UyDoYlU7GrqtnGNAojgQHft7g4LlQt3YjGlNHp6up0TfsrathIt2qxlqZuj/VT143OywUFHMdLOVYX@A/Mk93KNK3gK8GNyW6pgx@yrLppL5i/aWAOxc4HssBDTBa0Nz5AZAG0JKC8i6SEJAVAzQNHxe4ElH@ASDrjxCnmmEDokg@wU6xZJyeQBLaJI2ASAg4p0O92dhBoCPRMTlPIm7JBMceg2Jj/GyhBn06MxfSleoOnOC3vd9P2w6FldW0eDErvg52Wx28 "Clean – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes
```
Ḳµḣ3Ẉ5<+2/Ṁ3_⁸sḢKṄṛƲẎµ¹¿
```
[Try it online!](https://tio.run/##y0rNyan8///hjk2Htj7csdj44a4OUxttI/2HOxuM4x817ih@uGOR98OdLQ93zj626eGuvkNbD@08tP/////qxZkVQKSAh1IHAA "Jelly – Try It Online")
-1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 23 bytes
```
ḲµẈ<6ḣ3Ḅ+8:5Ṭk⁸KṄṛɗ/µÐL
```
[Try it online!](https://tio.run/##PY6rbkJBFEV/5fgKRNOGkMq68hM3Mxs4ZR43c@aIyiYIJA6BxKJISO5FUtXPmP7IMILU7qy9sj7h3FetZTjfLuW6fXstw/G5DJun6eyljKf13/fwUcZNGQ@/@8nt8rOb11rnMcET96KebHQxkXCmziOTiUFgMrIm6iz3LIbDkuAaILANB6v4aCnD9@3JwbBlqyGTZnpXFuo0gzhpwsPOgRL6hBWCRWqmNkAEZNi5/wYoLXTJ8Q4 "Jelly – Try It Online")
A full program that takes as its argument the input string and prints newline-separated groups of words. Takes advantage of the fact that if the current first three words have their length checked to see if <6 and this is then treated as a binary number, the number of words needed will be 1,1,2,2,2,2,2,2,3 for numbers from 0 to 7 respectively.
## Explanation
```
·∏≤ | Split at spaces
µ µÐL | Repeat the following until no new results:
Ẉ | - Lengths of lists (i.e. words)
<6 | - Less than 6
·∏£3 | - First three
Ḅ | - Comvert from binary to integer
+8 | - Add 8
:5 | - Integer divide by 5
·π¨ | - Convert from index to boolean list
k⁸ | - Split input to this loop iteration at that point
…ó/ | - Reduce using following as a dyad:
K | - Join with spaces
Ṅ | - Output with trailing newline
·πõ | - Right argument (i.e. rest of list)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 49 bytes
```
≔⮌⪪S θWθ«≔⌊⟦Lθ⊕ΣE²›⁶L§θ⁻κ²⟧ι⪫E⁻ι∧⁼鳋⁵L§θ±³⊟θ ¿θ|
```
[Try it online!](https://tio.run/##bZAxTwMxDIVn@iusm3JSWFrBwlQJhIpaVNERMUSJe2eRS9LEKUjAbz9MrzCRJYrtfO89295kG40fx2Up1AX1hEfMBdUueWK1CqnyjjOFTrUaGmhauQ7tzeytJ4@gDi18zC7OfzcUaKiDel5j6LiXpoZVsBkHDIxO7aS3MUnNNdxnNIxZXWs4Dy95FRy@q4MG4dSiXjXM2@m8CIhE9GIrTlg9RAon0DRIGpbBqbtDNf70WrQ/1FLU1X/0R@xEWi0mtIZtTOL0N52I0P6Ua9JqPhupfY3jOkoOoFTqAC76mKEQgxmQwcZQ0DJyzWAcJSpWFgYoG4SCTsaRahmiA8YhyU8Klhy5Ghgqw22lAqYyAuWa8UynABlTxh7FeBaSFCQTgiXv/zxghX3tyMzGy6M33w "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⮌⪪S θ
```
Split the input into words and reverse it so that we can use `Pop` to remove words in order.
```
Wθ«
```
Repeat while there are still words left.
```
≔⌊⟦Lθ⊕ΣE²›⁶L§θ⁻κ²⟧ι
```
Estimate the number of words needed as equal to one more than the number of the first two words that are less than 6 letters, but no more than the number of words left.
```
⪫E⁻ι∧⁼鳋⁵L§θ±³⊟θ
```
Adjust the number of words if there are three and the third word is not less than 6 letters, then remove that many words and print them separated with spaces.
```
¿θ|
```
Output a separator if there are still more words left.
[Answer]
# [J](http://jsoftware.com/), ~~55~~ 53 bytes
```
</.~[:+/\@}:[:(}:@],[((3<]),,{~4>])_1{+)/0|.@,1+5<#&>
```
[Try it online!](https://tio.run/##PY5NS8NAGITv@RWDgknIumlRL2taAoqnnrzWUEL2TftKshv2gx5q@9djDuJhLsMzD/M938m0x0YhhcAKasmjxNvn7mOuSnnbq6L8qq9qr7Krqhuxz7KnqsmFuNyet01@WF@KvFz9yFqsi5fq/mE750lyxkbiVaU762gETz6O0HawDp4D2pECOms8dYFCdGg1T@w7NkfQsACe9IITRz9ajUDjtCzZdKxZRxMQA94je7QxENhFR392NnA0OTqR0eQW01KQ94SOh@H/A0X08chtmiTUnSyERI/z/As "J – Try It Online")
] |
[Question]
[
And then the King said: *You fought bravely, Knight, and your deed will not be forgotten for centuries. For your valor I grant you this castle and the lands around it. Things rush me, and I can not take you to the castle. Therefore, I will give you the way from this place to the castle. Now go and come back after the deadline.* - as it is written in the Green Book of Years.
In addition, it is known from the Green Book of Years that the lands with which the castle was granted were in the shape of a circle. The king was very wise and, in order to avoid unnecessary proceedings regarding the right to land, always granted only areas of land on the map that have a convex shape.
Recently, historians have had information about where the castle was located and where this historical conversation took place. They want to know how much land did the Knight get on the assumption that the road to the castle was perfectly straight.
## Explanation
The following figure shows in light gray the territory originally granted to the knight, and in dark gray, the one that came to him as a result of the king giving him the way.
[](https://i.stack.imgur.com/i9kAS.gif)
## Input
The first line of the input contains two floating-point numbers: xk and yk - the coordinates of the place where the dialogue took place. The second line contains three floating-point numbers: xc, yc and rc - the coordinates of the castle and the radius of the circle that bounds the land granted with it.
## Output
Print one floating-point number - the area of the land obtained by the Knight, with an accuracy of at least three characters after the decimal point.
## Tests
### Input Output
`2 5` `5.69646`
`2 1 1`
---
`3 9` `80.7130`
`2 3 5`
---
`1 3` `3.141`
`1 2 1`
**Note:** A triangle may not include the entire semicircle if it is too close to the center, as in the test I have given.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 51 bytes
```
Area@ConvexHullMesh[CirclePoints[##2,7!]~Append~#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b737EoNdHBOT@vLLXCozQnxze1OCPaObMoOSc1ID8zr6Q4WlnZSMdcMbbOsaAgNS@lTjlW7X9AEVAmWlnXLs3BAcjXd6jmqq420jGt1QGShrUgBBQw1rEECxjXgmSAAoYgJpA0Aqngqv0PAA "Wolfram Language (Mathematica) – Try It Online")
```
CirclePoints[##2,7!] (* generate 5040 points on the perimeter of the circle *)
~Append~# (* append the point at the end of the way, *)
Area@ConvexHullMesh[ ]& (* and find the area of the convex hull of those points *)
```
[Answer]
# JavaScript (ES7), 76 bytes
Port of [Jitse's answer](https://codegolf.stackexchange.com/a/190737/58563).
```
with(Math)f=(X,Y,x,y,r,h=hypot(X-x,Y-y))=>r*(r*(PI-acos(r/h))+(h*h-r*r)**.5)
```
[Try it online!](https://tio.run/##fYuxCsIwEEB3v6LjXbxUFDrG3UFwbMcQW69SeuUStPn6mC8QHm95vLf/@Bh03pJd5TmW8p0Tw90nxslBTwPtlEmJHedNEvR2p8FmRHdVA5XHzfogEfTEiEdgw1aNojFthyXIGmUZ20VeMMGFmo6a6nMF8fCn1hnLDw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 107 bytes
```
from math import*
def f(X,Y,x,y,r):d=hypot(X-x,Y-y);return(r>d)*pi*r*r or(pi-acos(r/d))*r*r+(d*d-r*r)**.5*r
```
[Try it online!](https://tio.run/##bcrBCsIwEATQu1@R4@66UdLSg4p@R3sspqE5tAlrhObrYwsKCjKXmcfEnMYw16U4CZOa@jQqP8UgiXZ2cMpByx0vnFnwbK9jjiFBqxfudMaLDOkpM8jNIkVPQqKCQPS6v4cHyNEibrgHS1avBYkODUmJ4ucEDipuuGLDBnH3sZpPq9XcfJlZt9mef6z6sXcQyws "Python 3 – Try It Online")
*-3 bytes thanks to Arnauld*
*-4 bytes thanks to squid*
*-5 bytes thanks to Greg Martin*
### Explanation
First, we calculate the traveled distance between both coordinates using the Pythagorean theorem. Let's call it `d`.
Then, we construct a rectangular triangle between coordinate 1, coordinate 2 and the point on the circle where it meets with the straight line. Using the Pythaogrean theorem again, the area of this triangle is given by $$\frac{1}{2}\times\sqrt{d^2-r^2}\times r$$
where `d` is the distance between the coordinates and `r` is the radius of the circle. Since we have two of those triangles, this area is resembled in the code by `(d*d-r*r)**.5*r`
Next, we need to calculate the remaining area of the circle. A circle's area is given by $$ a = \pi\times r^2$$
However, part of the circle is already taken into account. The angular fraction of the circle that is already described by the triangles is given as $$\cos^{-1}(r/d)$$
so that the remaining area in the circle can be described by `(pi-acos(r/d))*r*r`.
And then some code juggle to make it as short as possible.
### Except...
when the traveled distance lies within the circle. Then just return the circle area.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 33 bytes
```
½÷@ÆAØP_ײ}
I²SḢ_²}½×ʋ+çɗṛ²×ØPʋ>?
```
[Try it online!](https://tio.run/##y0rNyan8///Q3sPbHQ63OR6eERB/ePqhTbVcnoc2BT/csSgeyAZKTj/VrX14@cnpD3fOPrTp8HSgslPddvb/j056uHPGo6Y13taPGuYo6NopPGqYa314uT5YXIXrcDtQLpJMw7m4ormio6ONdIxidaJNdQxjY4FYByRkDBay1DEGCplChAxBcmAJuCqIkCFUI1fs///UNQ8A "Jelly – Try It Online")
Port of @jitse’s Python answer so be sure to upvote that one! A full program taking as its arguments `[[xk, xc], [yk, yx]]` and `r`.
[Answer]
# [Python 3](https://docs.python.org/3/), 96 bytes
```
from math import*
def f(X,Y,x,y,r):t=max(hypot(X-x,Y-y)**2/r/r-1,0)**.5;return(t-atan(t)+pi)*r*r
```
[Try it online!](https://tio.run/##VcpBCsMgEAXQfU7h0rFjUxOySEvvkSyFRszCKMMU9PTWQgsts/j/PyYV9vEYa3UUgwiWvdhDisSqe2xOOLngihkLElz5HmyWvqTIctEZV11AqaGnnrTBS@vn6UYbP@mQrC3bFnBKOyhSVBPtB0snB5xwQIMGoPvaiHOzEacfM22b9@effQ6gvgA "Python 3 – Try It Online")
In Python 3.8, the solution can be further improved using assignment expressions:
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 91 bytes
```
lambda X,Y,x,y,r:((t:=max(hypot(X-x,Y-y)**2/r/r-1,0)**.5)-atan(t)+pi)*r*r
from math import*
```
[Try it online!](https://tio.run/##VcrBCoMwEATQu1@R4266qY0iWMH/UOglpQSFxoRlD@brUwsttMxl5jEpyxK3tk9c/HgrTxfuD6cmmmmnTDwAyDAGt8OSUxSYzE6zyah1U3PNxtLl6OcOjRO3geAprahZc@U5BhWcLGoNKbLoknjdBDw01FFDlixi9bWWroe11P2YPbZ9P//sE8TyAg "Python 3.8 (pre-release) – Try It Online")
*-2 bytes thanks to @Jitse*
This solution is based on a bit more math manipulation of the formula. Let \$\theta\$ be the size of common angle of each triangle and its corresponding sector. The area of each triangle equals to \$\frac{1}{2}\times r\tan{\theta}\times r\$ and the area of the common sector of the triangles and the circle equals to \$\theta\times r\times r\$. Hence, the total area $$S=\tan{\theta}\cdot r^2 +\pi r^2-\theta r^2=(\pi+\tan{\theta}-\theta)r^2$$
We define \$t\$ to be $$t=\tan{\theta}=\frac{\sqrt{d^2-r^2}}{r}=\sqrt{\frac{d^2}{r^2}-1}$$
Here, \$d\$ is the distance between the two given coordinate pairs. Then we have $$S=(\pi+t-\arctan{t})r^2$$
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~111~~ ~~103~~ 93 bytes
```
float f(X,x,r)_Complex X,x,r;{X=cabs(X-x)/r;return(4*atan(1)-atan(X=csqrt(X*X-1))+X)*r*r;}
```
[Try it online!](https://tio.run/##bY1BCoMwEEXX9RRBKCTRUGLrooSueoksCiUNRoQY7ZiCIF69aRS7c/X4/PdnNNNWuToEYzvlkcEyH3Mgz3vX9rYa0RrFJG9avQYs2UhOIKDyH3D4QpVXDnPCVkZneIPHkkrGCckkoUBBzKFxHrWqcZigKTn0ELPB6dE8XJrHjwXKUNnkaCGPjFuxo51jfd20c2S5r/GtXlj8r80iCV9trKqHwGz7Aw "C (clang) – Try It Online")
It's 90 bytes for the code, but +3 bytes because we need to pass `-lm` to the compiler.
Thanks to @ceilingcat for shaving off 12 bytes, and the brilliant use of `csqrt()` inspired me to take the coordinates as complex numbers, to shave off another 10 bytes.
] |
[Question]
[
It turns out that my toaster is a tad broken. It lost WiFi (You know, it's one of those newfangled smart toasters), and its been going bonkers! Since it no longer works, I've been having to hack into my breakfast's source code and run `Plate.bread.toastAs(3);` every morning. Will you help?
My toaster takes one input: the amount of time you want to toast your bread. This is written as `min:sec`, such as `5:45` or `0:40` (Up to `59:59`). It then returns a specific value for different levels of toastiness:
```
0:00-0:30 = Bread
0:31-1:00 = Warm Bread
1:01-2:00 = Toasty
2:01-3:30 = Burnt
3:31 and up = Brûlée (or Brulee)
```
But here's the catch: my toaster has a broken keyboard! Your code can't contain any semicolons or...colons. This might be harder than the toaster repairman said it would be...
Here are some test cases, so you can...test your cases?
```
0:00 = Bread
5:50 = Brulee or Brûlée
2:00 = Toasty
ChicknMcNuggets = Anything
-1:00 = Anything
0:60 = Anything
1 = Anything
60:00 = Anything
1:00:00 = Anything
```
* [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are prohibited
* [All Acceptable Forms of Input/Output](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) are accepted
* My Toaster's new code cannot contain a semicolon (;) or colon (:)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in each language) wins!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~124~~ ~~118~~ 116
```
t=eval(input().replace("\x3A","."))
print["Bread","Warm Bread","Toasty","Burnt","Brulee"][sum([t>3.3,t>2,t>1,t>.3])]
```
[Try it online!](https://tio.run/##NY6xisMwDIZ3P4XRZEMJSUyHGhpoobfeUrghl8GkggbSxMjyXfL0OffcDuLT9/OD5Fe@z1O99fMNgzxKANj4iD9uVMPkIytdEPrR9ajgezEn2EEBWgtPw8QtnAndLWVfjh7yLdfZBV7Tco408ZMUR0To2hAfquXGFGbHTZ2mSlOYTndbOiwE02qFlL/3YUR5pYhW4oK9@v9OC1x69Cwvnx8Xopms9C6EDUpbliASzAtVQpXDhKfV2epsJjdNbu4Pdn@APw "Python 2 – Try It Online")
-6 with thanks to @tsh and also thanks for tho TIO test cases.
-2 with a couple of cool tips from @BlackOwlKai
Throws a `ValueError` for invalid inputs that cannot be converted to a float. For numbers less than 0 it returns "Bread" because it is still bread. Guess if we are really strict on ensuring that the input is a valid time it could be done but for me the interesting bit was how to avoid the `:` in Python.
[Answer]
# T-SQL, 409 379 328 318 bytes
```
DECLARE @i varchar(9)DECLARE @a time='0'+CHAR(58)+@i DECLARE @ int=DATEPART(N,@a),@s int=DATEPART(S,@a)SELECT CASE WHEN @<1AND @s<31THEN'Bread'WHEN @<1OR @=1AND @s=0THEN'Warm Bread'WHEN @<2OR @=2AND @s=0THEN'Toasty'WHEN @<3OR @<4AND @s<31THEN'Burnt'ELSE'Brulee'END WHERE LEN(RIGHT(@i,LEN(@i)-CHARINDEX(CHAR(58),@i)))=2
```
*-30 bytes: removed* `AS` *keywords, combined* `DECLARE` *statements (thanks to [BradC](https://codegolf.stackexchange.com/questions/175152/toasty-burnt-br%C3%BBl%C3%A9e/175555?noredirect=1#comment422923_175555))*
*-51 bytes: changed declarations/where clause to take advantage of SQL's datetime functionality*
*-10 bytes: changed* `MINUTE` *to* `N` *and* `SECOND` *to* `S` (thanks to [BradC](https://codegolf.stackexchange.com/questions/175152/toasty-burnt-br%C3%BBl%C3%A9e#comment422956_175555))
Did you know that SQL can't natively split strings in any decent capacity? Don't let `STRING_SPLIT` fool you; it doesn't work for this. Or at least, I'm not smart enough to figure it out.
Different from BradC's [table-based T-SQL solution](https://codegolf.stackexchange.com/a/175614/83280).
Ungolfed:
```
-- Input variable
DECLARE @i varchar(9)
-- Time declarations (passes in as form "00:mm:ss")
-- CHAR(58) maps to ':'
DECLARE @a time = '0' + CHAR(58) + @i
-- Integer declarations
DECLARE @ int = DATEPART(N, @a), -- minutes
@s int = DATEPART(S, @a) -- seconds
SELECT CASE
WHEN @ < 1 AND @x < 31 -- 0:00 - 0:30
THEN 'Bread'
WHEN @ < 1 OR @ = 1 AND @x = 0 -- 0:31 - 1:00
THEN 'Warm Bread'
WHEN @ < 2 OR @ = 2 AND @x = 0 -- 1:01 - 2:00
THEN 'Toasty'
WHEN @ < 3 OR @ < 4 AND @x < 31 -- 2:01 - 3:30
THEN 'Burnt'
ELSE 'Brulee' -- 3:31 - 59:59
END
-- Setting input as a time means that you only have to check if the seconds input is two characters, all other checks accounted for
WHERE LEN(RIGHT(@i, LEN(@i) - CHARINDEX(CHAR(58), @i))) = 2
```
[Answer]
# Java 8, 148 bytes
a lambda from `String` to `String`
```
t->{float n=new Float(t.replace("\72","."))\u003breturn n>3.3?"Brulee"\u003an>2?"Burnt"\u003an>1?"Toasty"\u003an>.3?"Warm Bread"\u003a"Bread"\u003b}
```
`\u003b` and `\u003a` are source-level Unicode escape sequences for `;` and `:` respectively.
[Try It Online](https://tio.run/##TVDBasJAED3HrxgGhATikipSTGsED956stBD9bDGjazdbMLurCVIvj3daJTCwMy8NzPMe2d@4ZPz8aer3UHJHHLFrYUPLjVcR8EAWuLk06WSRyg9FW7JSH363gM3Jxv1k8HZH2KOpGKF0znJSrPNULzfx2O45wwKWHY0ya6FqjiBXmrxC5u@DokZUSueixB3r1OMkWEU7VySzA5GkDMadDZjsxWujVNC4I3iOpt6xLP0BF5W@FlxS80T6be@uClhbQQ/DjD@aw5tFwRvXkpRGRgkgvchhf6/p@QrJmmSYAw4T@e3PH30i3S@wPbuR7BtLImSVY5Y7VdJPWxj/n7pteLYpjC2flPqGArG61o1odRRFPVftCMfbfcH)
## Ungolfed
```
t -> {
float n = new Float(t.replace("\72",".")) \u003b
return
n > 3.3 ? "Brulee" \u003a
n > 2 ? "Burnt" \u003a
n > 1 ? "Toasty" \u003a
n > .3 ? "Warm Bread" \u003a
"Bread"
\u003b
}
```
## Acknowledgments
* -24 bytes thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%c3%a9goire)
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 100 bytes
```
a=>'Bread,Warm Bread,Toasty,Burnt,Brulee'.split`,`[((t=a.replace(/\D/,'.'))>3.3)+(t>2)+(t>1)+(t>.3)]
```
[Try it online!](https://tio.run/##dY69DoIwFIV3n4KwtI21/DQMYGAgPoKJg5rQQDFooU1bTHh6RByly8nNd77cnCd7M1PrTtmDUV3DdS@HF5/m1su9meUFKDVnDb4w3Xu/8yyZsRMuRz1YXOpRcA6IUaKzFa6uENqcEc2VYDWHwe0UYEAAQgUlFO2hLeI1ozUXdJ9rORgpOBHyAVvoh1kY@ggdd3@cuni0xSPHn4Vv@rHDjx0@deyhjj1JmiXpt5g/ "JavaScript (SpiderMonkey) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 91 bytes
```
a=>[,b='Bread','Warm '+b,o='Toasty',o,u='Burnt',u,u][new Date([70,a])/-~18e5+1|0]||'Brulee'
```
[Try it online!](https://tio.run/##dY5BC4IwGIbv/YrhZYqzNkVKYx2inxB0EA9LP6OwLeZWBNJfX3bOXZ/34eG9iacYGn19mESqFlyHOHKC7ypy5nivQbSY4JPQd4TjM1EcH5UYzBsTRewkWC0NJpbYupLwQgdhIKzWlIg6WiUftoE8ZiOtx3Fq2R4Au0bJQfWw7NUl7MKAlpQGUbRd/PHMx9kcZ57OxGf91OOnHj/z/Mk8f/KizIvf4L4 "JavaScript (Node.js) – Try It Online")
[Answer]
# PHP, 96 bytes
```
<?=[Bread,"Warm Bread",$t=Toasty,$t,$u=Burnt,$u,$u,Brulee][min(7,2*$argn+substr($argn,-2)/30)]?>
```
requires PHP 5.5 or later. Run as pipe with `-nF` or [try it online](http://sandbox.onlinephpfunctions.com/code/f29115a7aaa3e30a7a9952696de8ad464ea8c70f).
[Answer]
# T-SQL, ~~143 155~~ 145 bytes
```
SELECT TOP 1b FROM i,
(VALUES(31,'Bread'),(61,'Warm Bread'),(121,'Toasty'),(211,'Burnt'),(1E4,'Brulee'))t(a,b)
WHERE a>DATEDIFF(s,0,'0'+CHAR(58)+v)
```
Line breaks are for readability only. Different method than Meerkat's [variable-based SQL solution](https://codegolf.stackexchange.com/a/175555/70172).
Input is taken via pre-existing table **i** with varchar field **v**, [per our IO standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). That input table is cross-joined to an in-memory table **t** with our cutoff values (in seconds) and the desired labels.
The magic happens in the `WHERE` clause: `DATEDIFF` calculates the difference in seconds between midnight and our input (with an extra `0:` attached to the front), then returns the lowest matching label (via the `TOP 1`).
Invalid inputs either return an unpredictable value or throw an error:
`Conversion failed when converting date and/or time from character string.`
The question was a little vague, but if needed I can avoid these errors (and return nothing) by adding the following `LIKE` pattern to the `WHERE` clause, bringing the total bytes to **~~238 211~~ 201**:
```
AND RIGHT('0'+v,5)LIKE'[0-5][0-9]'+CHAR(58)+'[0-5][0-9]'
```
**EDIT**: My original shorter submission was failing for inputs over `24:00`, since I was treating it as `hh:mm`. Had to add the `'0'+CHAR(58)+` prefix, which added 12 bytes.
**EDIT 2**: Shaved 27 bytes from the `LIKE` in my alternate version
**EDIT 3**: Removed `ORDER BY` from both versions, as it proved unnecessary in testing. (SQL doesn't *guarantee* sort order will be maintained without an explicit `ORDER BY`, but it seemed to work fine for me in this specific case.)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~43~~ 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
þ30тx330)ć‹O„©Ãº™D#θ‚R.•liSÕô6>µ·•6ôÀ«™sè
```
[Try it online](https://tio.run/##AVYAqf9vc2FiaWX//8O@MzDRgngzMzApxIfigLlP4oCewqnDg8K64oSiRCPOuOKAmlIu4oCibGlTw5XDtDY@xIDCtcK34oCiNsO0w4DCq@KEonPDqP//MToxNQ) or [verify some more test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/8P7jA0uNlUYGxtoHml/1LDT/1HDvEMrDzcf2vWoZZGL8rkdjxpmBek9aliUkxl8eOrhLWZ2RxoObT20HShidnjL4YZDq4Hqig@v@K/z38DKwIDLwMrQCEgYg1jGhlyGIDEgAWIBJYxAXCMQ1wjENYYQQMXGIMUmIK4pkAAA).
**Explanation:**
```
þ # Leave only the digits of the (implicit) input
# i.e. "1:15" → 115
30 # Push 30
т # Push 100
x # Pop and push 100 and 100 doubled (200)
330 # Push 330
) # Wrap the stack into a list: [inputDigits,30,100,200,330]
ć # Pop and push the head and rest of array as separated items to the stack
‹ # Check for each if its smaller than the head (1=truthy, 0=falsey)
# i.e. [30,100,200,330] and 115 → [1,1,0,0]
O # Take the sum of this
# i.e. [1,1,0,0] → 2
„©Ãº™ # Push string "warm bread"
D# # Duplicate it, and split it by spaces: ["warm","bread"]
θ # And only leave the last element: "bread"
‚R # Pair them into a list, and reverse that list: ["bread","warm bread"]
.•liSÕô6>µ·• # Push string "bruleetoastyburnt"
6ô # Split into parts of size 6: ["brulee","toasty","burnt"]
À # Rotate it once towards the left: ["toasty","burnt", "brulee"]
« # Merge both lists together:
# ["bread","warm bread","toasty","burnt","brulee"]
™ # Titlecase each word: ["Bread","Warm Bread","Toasty","Burnt","Brulee"]
s # Swap so the number is at the top of the stack again
è # Index it into the list (and output implicitly)
# i.e. 2 → "Toasty"
```
[See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `„©Ãº™` is `"warm bread"` and `.•liSÕô6>µ·•` is `"bruleetoastyburnt"`.
`þ30тx330)ć` can alternatively be `30тx)DOªsþ` for the same byte-count: [Try it online.](https://tio.run/##AVYAqf9vc2FiaWX//zMw0YJ4KURPwqpzw77igLlP4oCewqnDg8K64oSiRCPOuOKAmlIu4oCibGlTw5XDtDY@xIDCtcK34oCiNsO0w4DCq@KEonPDqP//MToxNQ)
[Answer]
# Javascript(ES6+), 180 bytes
Node.js(180 bytes)
```
let f=(s,i=s.split("\u{3a}"),j=i[0]*60+1*i[1],k="Bread",l=assert(new RegExp("^(.|[0-5].)\u{3a}[0-5].$").test(s)))=>eval("(j<31)?k\u{3a}(j<61)?'Warm '+k\u{3a}(j<121)?'Toasty'\u{3a}(j<211)?'Burnt'\u{3a}'Brulee'")
```
Browser(188 bytes):
```
let f=(s,i=s.split("\u{3a}"),j=i[0]*60+1*i[1],k="Bread",l=console.assert(new RegExp("^(.|[0-5].)\u{3a}[0-5].$").test(s)))=>eval("(j<31)?k\u{3a}(j<61)?'Warm '+k\u{3a}(j<121)?'Toasty'\u{3a}(j<211)?'Burnt'\u{3a}'Brulee'")
```
Gotta use those unicode escape sequences :-) just a big chain of ternary operators, with variables defined by default parameters. Also a one-liner, so no semicolon-hungry js
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 97 bytes
```
.+(..)
$*1#$1$*
+`1#
#60$*
#1{211,}
Brulee
#1{121,}
Burnt
#1{61,}
Toasty
#1{31,}
Warm #
#1*
Bread
```
[Try it online!](https://tio.run/##K0otycxL/P9fT1tDT0@TS0XLUFnFUEWLSzvBUJlL2cwAyFQ2rDYyNNSp5XIqKs1JTQXxDY3A/NKivBIQ1wzEC8lPLC6pBHGNQdzwxKJcBaARhlpAfamJKf//G1gZGHCZWpkacBkBWQA "Retina 0.8.2 – Try It Online") Link includes test cases. Explantion:
```
.+(..)
$*1#$1$*
```
Convert the minutes and seconds to unary.
```
+`1#
#60$*
```
Multiply the minutes by 60 and add to the seconds.
```
#1{211,}
Brulee
#1{121,}
Burnt
#1{61,}
Toasty
```
Decode the seconds into the toastiness.
```
#1{31,}
Warm #
```
Decode Warm Bread by noting that `#` (for 0:00) decodes to `Bread`.
```
#1*
Bread
```
If we don't have a toastiness yet then the bread is still cold.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~86 79~~ 67 bytes
*-4 bytes thanks to nwellnhof! -12 bytes by porting [tsh's solution](https://codegolf.stackexchange.com/a/175180/76162)*
```
{<<Bread'Warm Bread'Toasty Burnt Brulee>>[sum S/\D/./X>.3,1,2,3.3]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv9rGxqkoNTFFPTyxKFcBwgzJTywuqVRwKi3KKwEKleakptrZRReX5ioE68e46OvpR9jpGesY6hjpGOsZx9b@L06sVEjTUDKwMjBQ0rTmgnONULnGqFwTUySuIapeINcQhYui1whVsRGqYmNUWWNUvUAusmJTVFlTSytTSyD/PwA "Perl 6 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 130 bytes
```
f(a){if(*strchr(a,58)=48,a=atoi(a),a=(int*[]){"Bread","Warm Bread","Toasty","Burnt","Brulee"}[(a>30)+(a>1e3)+(a>2e3)+(a>3030)]){}}
```
[Try it online!](https://tio.run/##NZDBioMwEIbP@hRpoJCoC1EbaFPcQ59hYQ@uh8GabWCrJYmHInl2d7JdT98/8w//DNO/fff9umoGfDGaZc7b/mYZFPLIm8OxgAb8ZNBFxczos7bjC73YAa60oJ9g72QrPiZw/oniMtvRR9r5ZxhoaBm814LniHKo/1j9sxZoYGIIK4aTO5iR8SVN@htYkvnBedd2zUKFEgITpZIR1asqlSgjhColslbVKc6clIwUqsauCOc00ZONtxPTiPMr03Q71CbP47LkYdHVjO4dUWTvvkZabGOFZviS6/xgW4dzjpEhDesv "C (gcc) – Try It Online")
[Answer]
# [Snap! 4.2](https://snap.berkeley.edu/), 257 251 bytes
Minified the text version some more.
I haven't found any answers in Snap!, a visual programming language similar to Scratch, so I'll use scratchblocks2 syntax, pretending that Snap! exclusive blocks are valid in scratchblocks2.
[**Try it online!**](https://snap.berkeley.edu/snapsource/snap.html#present:Username=wockykitaki&ProjectName=Toasty%2C%20Burnt%2C%20Br%C3%BBl%C3%A9e!) (click the button with the two arrows to see the code)
```
when gf clicked
ask[]and wait
set[l v]to(split(answer)by(unicode(58)as letter
set [t v]to(((item(1 v)of(l))*(60))+(item(2 v)of(l
if<(t)<[31
say[Bread
else
if<(t)<[61
say[Warm Bread
else
if<(t)<[121
say[Toasty
else
if<(t)<[211
say[Burnt
else
say[Brulee
```
[Answer]
# [R](https://www.r-project.org/), ~~127~~ 122 bytes
```
function(t)cut((x=eval(parse(t=t)))[1]*60+tail(x,1),30*c(0:2,4,7,Inf),c("Bread","Warm Bread","Toasty","Burnt","Brulee"),T)
```
[Try it online!](https://tio.run/##NcexCsIwEIDhVyk33dUTUpUKxS7d3AsO4nDEBAoxlfQi9emjDk7/96fiq9O2@BytTnNEJZsVce3dSwI@JS0OtVciuja3ujUblSngyg3x3tQWTbfjAx/5HD2xRRiSkzswXCQ9qv@Msyz6/mLIKeqvKQfngHik4hHazhig8gE "R – Try It Online")
Returns a `factor` with the appropriate level.
-5 bytes thanks to JayCe.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 48 bytes
```
`BÎ%
W‡m BÎ%
To†ty
B¨›
BrÔ‡`·g[30LLÑ,330]è<Ur58d
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=YELOJQpXh20gQs4lClRvhnR5CkKomwpCctSHYLdnWzMwTDIwMCwzMzBd6DxVcjU4ZA==&input=WyIwOjAwIiwKIjU6MDAiLAoiMjowMCJdCi1SbQ==)
Saved 5 bytes by actually reading the [tips](https://codegolf.stackexchange.com/a/142629/71434)...
Explanation:
```
`BÎ%...BrÔ‡`· Compressed array of possible outputs
g Get the one at the index given by...
è The number of items...
[30LLÑ,330] From the list [30,100,200,330]...
<Ur58d Which are less than the input without ":"
```
An [extra byte](https://ethproductions.github.io/japt/?v=1.4.6&code=YN+EubBybSDnsCUphnR5ab9ym2lictSHYHFpIGdbRtFMTNEsMzMwXeg8VXI1OGQ=&input=WyIwOjAwIiwKIjU6MDAiLAoiMjowMCJdCi1SbQo=) could be saved by outputting in all lower case.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~43~~ ~~41~~ 40 bytes
```
fØD~~ḌH“Ð2dʠ‘<Sị“¡Ḳḋ\ḞvṾƤSİƓƥeF½ÞØ+®°»Ỵ¤
```
[Try it online!](https://tio.run/##AV0Aov9qZWxsef//ZsOYRH5@4biMSOG4nuKAnMOHMWPGpeKAmDxT4buL4oCcwqHhuLLhuItc4bieduG5vsakU8SwxpPGpWVGwr3DnsOYK8KuwrDCu@G7tMKk////MTM6Mzc "Jelly – Try It Online")
### Explanation (old)
`“¡Ḳḋ\ḞvṾƤSİƓƥeF½ÞØ+®°»` is the compressed string `Warm Bread\nToasty\nBurnt\nBrulee\nBread`, found by the [compression optimizer](https://tio.run/##jVRLbhtHEF1zTlGxFtNjjQiSgh2EMheRkYW8jREtaMJozjTJpme6B91NUqRhwwdJrpFNdj6KL6K8ag4/kTaBCKGmuj6vXn2abVhYc/04c7ampaqqLem6sS5QYUv1sZFzlVOpi6CtkW77eAG98UGa0CWhHopq5fVaZYky5cdKGRrRgC6plg8CX2KT0cw62pA2Z0G6lTXzjC7IWDJKlRRsjKpL5c7N/IJxTFUhV16Rna61Xflqm5MOqaf4qlySXNCdKZySsFGzmS60MsWWNhqFrQJXU6lamaDNnCQFpxUJYPJhQV7XupIuS54lHdHn9ZB0RK9zWnMByqxq5WRQ4ql59iV5Uh39/wjRHBGSopLe01tbN055LyrtQzZMOqWaUbGQThaoVuxyKljb0dByzPSD@fDw8@z73ylrOxaJf3kFSVWwSPH3ZgRD/Eu/niysK0WRXV0PoqFX8cFJDQr/kNVK/eacdaJAJ1@Q9mgSyERvGqdNkNNK0a@/v727Q/8cKK20UTO0sfsiQ5gdA3j9cndp249ryD3IToWVM7RL9iWdGOCaNjmCGVU3YRurCx6eB82@2s142J/QaMRFDTFSI2j6w8kNtbYBAizLgrv3rKEI0A7kG3pNXPPTgYTvfU6@gLcAnF7GPvvJRcjoISKGrt/IpsC4iQwERRA59bM9yvuIZO80pGeUblpKTRqNwOo5jEjgDABQEo9ocUNLhjNgKEAWQfQjMFjEr94NZmzE2cb3k6SlnCuFJgPzulUNWDZBnEhoAc9i7w@NWp5//Gc6Dsr@81bOrdjFrhXt7GKlRzSeQLNZaEzLbh8Boxtbs65tKXZ0Rf2cBq96fAney084Htr4RmM/QAfFg/SODxJ2faqXCiytFU15zXEs1sp5NpPV3DpMZ80ZTvm7smlwksTxiI2LSXZCnv749ufn3pfv/6Rd7Gctg0jT7tJqI04hxsPhVX@SwWtfpW2CrmUlfHCx2LLhInsTeklXX5lWfuD@8cJzc500cyUOL3TVz@MvOsN7rDHNx3XvnlacnzAmfUwVHGHGUWPY5SksqKsBN3a6QXC@Me0NzvYZOsFt98IxGXtEOT/lPdtDfrpcHtIO97Kmn0ZYhoihg4OvmnA20G2CBpeLpRPDnGrMqpbqH9/@OnLNdOT8dgSBCULy3iSqkfST2o64ksd4ccTR7tADi@aKXtbF1S9FlmWP99LVdMufyXsrPW7GLVCE5NatKqWS@PIv "Python 3 – Try It Online").
```
fØD Filter out the non-digits (i.e. colon) from input
~~ Use binary NOT twice to convert to digit list
Ḍ
HḞ Halve and floor. Now we have "01:45" -> 72.
“Ç1cƥ‘ The array [14,49,99,164]
< Vectorized less than
S Sum
fØD~~ḌHḞ“Ç1cƥ‘<S How many threshold times is input less than?
(0 -> Bread, 4 -> Brulee.)
ị Index (note 0ị gives the last list item) into
¤ the new dyadic link given by
“...» The long string, decoded and
Ỵ split by newlines.
```
Inspired by Kamil Drakari's [answer](https://codegolf.stackexchange.com/a/175217/39328).
-2 bytes using snippet `~~Ḍ` from Dennis.
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 118 bytes
```
\>`tt
tt`,kw,kw,kw,ki
\uqn.3X)?\ . 1C)?\.2C)?\'Ŋ)?\"Brulee"
\D"daerB"L" mraW"/
$L"ytsaoT"L?9"tnruB"L?aL?3 F/
```
[Try it online!](https://tio.run/##KyrNy0z@/z/GLqGEiYWxhIkbiIWAOEEnuxyGMrliSgvz9IwjNO1jFPQUDJ2BtJ4RiFQ/2gUklZyKSnNSU5W4YlyUUhJTi5yUfJQUcosSw5X0uVR8lCpLihPzQ5R87C2VSvKKSoGy9ok@9sYKbvr//xtZGVkCAA "Runic Enchantments – Try It Online")
Utilizes some unprinting ASCII characters (STX, EOT, SOH, STX, VT, SOH, STX, DC2, SOH, and STX in that order) on the first line, which is reading in a sequence of bytes in the order that they're going to be needed on the stack. 3 divide (`'t'/2` equals `:`) and reflective-write operations are then performed. This puts 3 `:` (duplicate) commands where there are currently `.` (NOP) in order to non-destructively compare the input with the time thresholds. A fourth `:` is left on the stack before reading input.
Time is read in as a string, then split on `:`, and concatenated back into a string. As values above `59:59` do not have any specification on output, values like `1:00:00` will have undefined (but deterministic) output. This string is then converted to a number and compared against 30, 100, 200, and 330 (the byte value of `Ŋ`). `"Bread"` (line 3, executing RTL) is used twice, both for `Bread` and `Warm Bread` results, saving at least 5 bytes.
Saves 1 byte by not having a classic terminator command (`;`) by using `F`izzle on the last line instead. This convinces the parser that the program is guaranteed to terminate without causing it to do so immediately (and, more importantly, not touching the stack). Valid inputs will leave the stack empty so that when it loops around and touches a `w` the IP is terminated for performing an illegal action.
[Answer]
# Javascript, ~~115~~ 101 bytes
*-6 from tsh*
```
d=>[b="Bread","Warm "+b,a="Toasty",a,c="Burnt",c,c][~~(parseInt(d)*1.999+d.slice(-2)/30.1)]||"Brulee"
```
[Answer]
## JavaScript (ES6), 171 bytes
```
(x,y=Math.ceil(x.split(/\D/).reduce((a,b)=>(+a)*60+(+b))/30))=>["Bread","Bread","Warm Bread","Toasty","Toasty","Burnt","Burnt","Burnt","Brulee","Brulee","Brulee"][y>8?8:y]
```
Run some test cases with this Stack Snippet:
```
var f=(x,y=Math.ceil(x.split(/\D/).reduce((a,b)=>(+a)*60+(+b))/30))=>["Bread","Bread","Warm Bread","Toasty","Toasty","Burnt","Burnt","Burnt","Brulee","Brulee","Brulee"][y>8?8:y]
var result = document.getElementById("result");
["0:00", "0:30", "0:31", "1:00", "1:01", "2:00", "2:01", "2:30", "2:31", "3:00", "3:01", "3:30", "3:31", "4:00", "4:01", "4:30", "4:31", "5:00", "6:00"].forEach(x => result.innerHTML += `${x}: ${f(x)}\n`);
```
```
<pre id="result"></pre>
```
[Answer]
## F#, 177 bytes
```
let t i=
let s=i.ToString().Split(char 58)
let m=int s.[0]*60+int s.[1]
if m<31 then"Bread"elif m<61 then"Warm Bread"elif m<121 then"Toasty"elif m<211 then"Burnt"else"Brulee"
```
[Try it online!](https://tio.run/##XZJda4MwFIbv@ysOgYJuU6KjMlzbi41d9GJjUGEXrYxgo4ZpdPHYUeh/d9G2VpuLkPc57/kISVxZUaF402QcAUEsJtCeqoWwg2KNSsjEMO11mQk0opQpmD2ZJ0u@EFIb7Q0N7zx6fxZOOAERQz5/dABTLsmL4mxHeNZB7wy/mMphFHHccygoWIWHC3adS5laSdS04rpinXFOms38TaI6fBa69TKcdDMxIYGpZA/6Hnptur1dxPUthzxfNfUpHeqZPxtp9yb@moroR75HH3WScKyGIcu58VLfG@lRY@@2c5vdoo6E3X5cwpr/2jkrwYhrCShyvpJljWAt@8QePsCVqUN/7vTV1fM/gWkvjvCtawJZyT3LxI6Yw/4CuToNYAyaYftCXAWamG1uqT8JxhLItNqiv8VpRQYDD91dbdr8Aw)
Thanks to Jo King for straightening out my, umm, needlessly literal interpretation of the challenge...
F# is fairly okay for functions without semi-colons or colons. The only real issue was that I couldn't do `i.Split` directly without a type annotation - F# would not have been able to deduce the type of `i` based on the method call. That would have required defining the type directly in the function, like `let t (i:string)=` which would have been against the rules.
But I could easily get by it by `i.ToString()`, which then allowed me to call `Split` on it. Then `char 58` is a colon character, and after that it's straight-forward.
] |
[Question]
[
**This question already has answers here**:
[Fill in the next numbers](/questions/243764/fill-in-the-next-numbers)
(30 answers)
Closed 1 year ago.
You are given a list of 2-tuples of positive integers, of the form:
`a1 b1, a2 b2, ..., an bn`
In other words, the 2-tuples are comma-separated, and the integers within each tuple are space-separated. All of the `a` numbers are in strictly increasing order, as well as the `b`s. Your goal is to "fill in the gaps." What is meant by that is the following:
* If ai+1 == ai+1, don't do anything.
* Else if ai+1 < ai+1, you will insert tuples into the sequence as follows: ai bi, ai+1 bi+1, ai+2 bi+1, ..., ai+1-1 bi+1, ai+1 bi+1.
In other words, if there is a "gap" in the ai, then you will insert more into the list with the inserted `b`s to be bi+1 (the end of the gap).
**Example**:
Input: `6 125, 7 170, 10 185`
Output: `6 125, 7 170, 8 185, 9 185, 10 185`
**Scoring**: the score of the submission is the number of bytes needed to construct a program to, when given a string as described above, output in the same format the "filled" list of tuples.
Lowest score wins!
[Answer]
# CJam, ~~42~~ ~~41~~ ~~39~~ 38 bytes
```
q~,]:T(\-2=),>{IST2/z~\{I<!}#=,',S}fI&
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%2C%5D%3AT(%5C-2%3D)%2C%3E%7BIST2%2Fz~%5C%7BI%3C!%7D%23%3D%2C'%2CS%7DfI%26&input=6%20125%2C%207%20170%2C%2010%20185).
[Answer]
# Python 2, ~~192~~ ~~180~~ 171 Bytes
Unfortunately, it takes a *ton* of bytes to parse the input and format output. Also, thanks to Sp3000 for kicking my brain into gear :)
```
n=[map(int,x.split())for x in input().split(',')]
for i in range(len(n)-1):j=0;exec'print n[i][0]+j,`n[i+(j>0)][1]`+",",;j+=1;'*(n[i+1][0]-n[i][0])
print n[-1][0],n[-1][1]
```
[Answer]
# [Python 3.5.0b1](https://www.python.org/downloads/release/python-350b1/)+, 123 bytes
```
L=map(eval,(input()+",").split())
o=""
while L:
*L,a,b=L;x=a-1
while[x,b,*L][-2]<a:o=", %d %d"%(a,*b)+o;a-=1
print(o[2:])
```
Parsing the input was a pain, so I just ignored it and parsed it as is. This means that
```
6 125, 7 170, 10 185
```
gets parsed as
```
[6, (125,), 7, (170,), 10, (185,)]
```
hence the splat in the string formatting.
[Answer]
# JavaScript (*ES6*), 97 ~~103~~
Finding the question wording hard to understand, I based my work on the example.
~~First try, there could be a shorter way with just 1 split~~ Scanning the input string in a single pass using replace.
```
f=l=>
l.replace(/\d+/g,b=>{
for(i=p||a-1;a&&i++<a;p=a)o+=`, ${i} `+b;
a=a?0:b
},p=a=o='')
&&o.slice(2)
// TEST
out=x=>O.innerHTML+=x+'\n'
test=v=>out(v+'\n->'+f(v))
test('6 125, 7 170, 10 185')
```
```
<pre id=O></pre>
<input id=I><button onclick='test(I.value)'>-></button>
```
.
[Answer]
# Pyth, ~~31~~ 30 bytes
```
Jsrz7Pjds,R+ehfghTdcJ2\,}hJePJ
```
*1 byte thanks to Jakube.*
At the high level, for each number in the range of the a's, the list is filtered for a's greater than that number, then the b from the first such tuple is used as the b.
[Demonstration.](https://pyth.herokuapp.com/?code=Jsrz7Pjds%2CR%2BehfghTdcJ2%5C%2C%7DhJePJ&input=6+125%2C+7+170%2C+10+185&debug=0)
[Answer]
# Haskell, 152 bytes
```
p(x,y)=", "++show x++' ':show y
(a:b:c)%x|a<x=c%x|0<1=(x,b)
g a=p.(a%)=<<[0+head a..last$init a]
main=interact$drop 2.g.(map(read.fst).lex=<<).words
```
### How it works
`p` is a simple string formatting helper function:
```
>>> p (6, 125)
", 6 125"
```
`(%)` is a "lookup" function for filling in blanks:
```
>>> let nums = [6, 125, 7, 135, 10, 185]
>>> nums % 8
(8,185)
```
`[head a..last$init a]` is the range of numbers to use: from the first integer parsed until the second-to-last integer parsed. (The `0+` helps the type-checker infer that the whole program deals with `Num` values; otherwise `read` doesn't know what to parse.) Then we `concatMap` (or `=<<`) our previous functions over the range to get one big string. That's what `g` does:
```
>>> g nums
", 6 125, 7 135, 8 185, 9 185, 10 185"
```
Finally, there's `main`. It's of the form `interact$s`, so all we care about is the function `s :: String -> String` that turns *stdin* into *stdout*.
First, to read input, we split into words:
```
>>> (words) "6 125, 7 170, 10 185"
["6","125,","7","170,","10","185"]
```
Then we `concatMap` the function `map(read.fst).lex` over this list. For one word, this does:
```
>>> (map(read.fst).lex) "125," :: [Int]
[125]
```
So for a list of words, you get `concat [[6], [125], [7], ...] == [6, 125, 7...]`, which is the list we want to pass to `g`. Finally, we `drop` the leading `", "` from the string `g` gives us.
[Answer]
# CJam, 34 bytes
```
ri_[_q~,]:,2/::fe&:.e|+ee>Sf*", "*
```
I started with golfing [Dennis's answer](https://codegolf.stackexchange.com/a/53028/25180) but finally it becomes nothing like the original.
[Try it online.](http://cjam.aditsu.net/#code=ri_%5B_q%7E%2C%5D%3A%2C2%2F%3A%3Afe%26%3A.e%7C%2Bee%3ESf*%22%2C%20%22*&input=6%20125%2C%207%20170%2C%2010%20185)
[Answer]
# Perl, 67 bytes
(66 characters code + 1 character command line option)
```
s/(\b\d+ \d+)(?=, (?!(??{$k=$1+1}) ).+( \d+))/"$1, ".$k.$2/e&&redo
```
Execution example:
```
perl -pe 's/(\b\d+ \d+)(?=, (?!(??{$k=$1+1}) ).+( \d+))/"$1, ".$k.$2/e&&redo' <<< "6 125, 7 170, 10 185"
```
**Explanation:**
General approach is to construct a regex which is capable of looking ahead to the next token to determine if it increases by one (regex is rubbish at arithmetic, so we add a perl execution to do the addition, then look for that). If it does not, we replace this match with the original text, plus the new token with the increased index. We then repeat this multiple times on the input until it does not change.
For the below explanation, a 'section' is the comma separated value, and the 'tokens' are the space separated values within this.
```
s/
(\b\d+ \d+) # Matches the first two numbers in a section
(?=, # Look ahead to the next section
(?!(??{$k=$1+1}) ) # Make sure the first token in the next section is not increased by one, store this value in $k. Happily, although our $1 contains TWO space separated numbers, it increases the first number and ignores the second - strange behaviour in Perl.
.+ # Ignore the actual value of first token of the next section (i.e. the index)
( \d+) # Create a backreference on the second (i.e. the value)
)
/ # Start the replacement string...
"$1, " # Put the first section back into the result
.$k # Append the increased index
.$2 # Append the value of the next token
/e # Modifier - allows us to execute Perl inside the RegEx
&&redo # Repeat until it no longer changes the string
```
[Answer]
## C#, 174 bytes
Indented for clarity:
```
class P{
static void Main(string[]z){
int a=0,b,i=-1;
while(++i<z.Length){
b=int.Parse(z[i++]);
while(a<b)
System.Console.Write((a==0?"":", ")+(a+=a==0?b:1)+" "+z[i].Trim(','));
}
}
}
```
[Answer]
# Bash + coreutils, 87
```
tr , \\n|while read a b
do for((p=p?p:a-1;p++<a;c=1)){
echo -n ${c+, }$p $b
}
p=$a
done
```
### Test output:
```
$ echo "6 125, 7 170, 10 185" | ./fillblanks.sh
6 125, 7 170, 8 185, 9 185, 10 185
```
[Answer]
# Python 3, 232 bytes
Not really *that* short, but it uses a different method to the Python solution already posted
```
l=list(map(int,[y for x in input().split(',')for y in x.split(' ')]))
f=[];x=1
while x:
x=0
for i in range(0,len(l)-2,2):
if l[i+2]-l[i]>1:l[:i+2]+=l[i]+1,;l[:i+3]+=l[i+4],;x+=1
for n in range(len(l)):print(l[n],end=','if n%2 else' ')
```
[Answer]
## Java, 229 bytes
I *think* I've whittled this down as much as I can. I would be interested to see if there is a better approach that leads to a shorter Java answer:
```
String f(String s){String r="",g=" ",x[]=s.split(",\\s"),z[];int i=0,p=0,l=x.length,a,b;while(i<l){z=x[i].split(g);a=new Integer(z[0]);b=new Integer(z[1]);if(i++>0)while(a>++p)r+=p+g+b+", ";r+=a+g+b+(i==l?"":", ");p=a;}return r;}
```
Formatted:
```
String f(String s) {
String r = "", g = " ", x[] = s.split(",\\s"), z[];
int i = 0, p = 0, l = x.length, a, b;
while (i < l) {
z = x[i].split(g);
a = new Integer(z[0]);
b = new Integer(z[1]);
if (i++ > 0)
while (a > ++p)
r += p + g + b + ", ";
r += a + g + b + (i == l ? "" : ", ");
p = a;
}
return r;
}
```
] |
[Question]
[
## Input:
A decimal
## Output:
The input truncated
**How to truncate them?**
The integer part of the input will remain the same. The decimal part of the input will be truncated based on the lowest digit in consecutive order. The two step-by-step examples below should clarify what I mean by that:
*Example 1:* Input: `17.46940822`
Step 1: Leave the integer part unchanged: `17`
Step 2: Look at the first decimal digit, and truncate it to that many decimal digits: `4` → `.4694`
Step 3: Look at the next decimal digit. If it's lower, adjust the truncation accordingly. If not, continue to the next decimal digit: `6` → remains `.4694`
Step 3 again: `9` → remains `.4694`
Step 3 again: `4` → remains `.4694`
So the output will be: `17.4694`.
*Example 2:* Input: `10.4521084`
Step 1: Leave the integer part unchanged: `10`
Step 2: Look at the first decimal digit, and truncate it to that many decimal digits: `4` → `.4521`
Step 3: Look at the next decimal digit. If it's lower, adjust the truncation accordingly. If not, continue to the next decimal digit: `5` → remains `.4521`
Step 3 again: `2` → truncation adjusted to: `.45`
So the output will be: `10.45`
## Challenge rules:
* You are allowed to take the input as decimal, string, list/array/stream of characters, etc. (Same applies to the output, although I doubt there are a lot of languages that have the proper truncation while remain working with decimal values.)
You are also allowed to use a comma `,` instead of a dot `.` (perhaps useful for regex-based solution/languages).
* If the decimal part is not long enough for the truncation, you are optionally allowed to add trailing zeros. I.e. `123.4` can be both `123.4` or `123.4000`
* If you have to truncate to `0` decimal digits we omit the decimal digits. The dot/comma may remain optionally if you use strings. I.e. `847.3072` → `847` (or `847.`)
* You can assume the input will always contain at least one decimal digit, so `123` won't be an input, but `123.0` can be an input.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
```
Input: Output:
17.46940822 17.4694
10.4521084 10.45
123.4 123.4000 (or 123.4)
-847.3072 -847 (or -847.)
123.0 123 (or 123.)
98.76543210 98.7654
0.3165 0.3
-0.1365 -0.1
82937.82937 82937.82
-0.1010101 -0.1
-1.0101010 -1 (or -1.)
28.684297 28.68
13.35 13.350 (or 13.35)
0.99999999999 0.999999999
28.321 28.32
0.56462 0.5646
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes
2 bytes extra due to a bug with `£` not handling **0** correctly.
```
'.¡`DvÐgsNè-F¨]'.ý
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fXe/QwgSXssMT0ov9Dq/QdTu0IlZd7/De//91LUzM9YwNzI0A "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##JYqxCsJAEET7/QpJk8Zb9nb3cneNlVjaCZYqiFhZBAIB8w9@gI1dfkICuQ87w8nAzJthHu35cr/mZ9f3h1zj/Dltu/S6tfs0mt08DkON6UvpnY9VmlZms0pTtc7WozZRKTCDJVTHloKCZUEFE9SjkOfSCWJA3ziV5QOEYhsHhtDKkoGjeCxeNioCY/FPBBywCcrRgxUU9wM)
**Explanation**
```
'.¡ # split input on "."
` # push int and decimals separately to stack
D # duplicate decimal digits
v # for each
Ð # triplicate the current decimal digits
g # get the length
sNè # get the Nth digit
- # subtract from the total length
F¨] # drop that many digits from the end
# end loop
'.ý # join on "."
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~103 101 98~~ ~~94~~ ~~93~~ 87 bytes
```
a,b=input().split('.');i,w=0,len(b)
while w>i:w=min(int(b[i]),w);i+=1
print a+'.'+b[:w]
```
[Try it online!](https://tio.run/##RY1NboMwEIX3PgViM1DIaPyH7VR003bdA0RZhAoplqiDUiq3p6cG0nQsjfzmzZtv/JnOlyDm57eX1zbP8/lUd60P49dUlPg5Dn4qAKF89HVsqR76UHQli2c/9Fl88vvYfvhQ@DAV3cEfyzqmzarlbLymWXaqUrbqDvt4nNNt1n/379lCeuB6Bm5QNU6RFQIYcEKlBSerIEtKSEyftRjsrDIoyQjIbh7dPWfRNFrJFE1XCCVvNPzlCLm8SQZWOGlw7bB5tL6Ft@O4CVqUsNhYJZzZeBKlvvMI3X/BupvY8As "Python 2 – Try It Online")
---
Saved:
* -2 bytes, thanks to Kevin Cruijssen
* -3 bytes, thanks to Vedant Kandoi
* -4 bytes, thanks to Lynn
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 58 bytes
```
f=(s,p=1/0,q=1,c=s[q])=>c?f(s.slice(0,p-~c),++c?p:q,q+1):s
```
[Try it online!](https://tio.run/##VZBNbsIwEIX3PoV3eJRksJ1/qtBVT0GRiJxAg0IcMK266tWp7aRAHcny997M5NnH@qs26tKN12jQTXu77StmwrESSx6eKxGqymzOW6jW6nXPDJq@Uy3j4Rj9KAiDQL2Oq3N4DgSszO1lR0SOSVYmvJCSujUzERyTVApeJHTSHRMhY5yFSXXMOadMXyYAEhVJjjHP5Vzj2PveAD@D/59xbwdSFphnaRLbX3t3ZsIxFln66LJMIo4ifhIdk0KWcY5@9@If@2ruv6fqSOCkzYkiMUUVNoosMCsSWebzeM9ExBinz/Edzw/gjmCjlo/lo97JzbRXe3R7th1plmTy6XKOyQ6vl@7EAM3Yd1e2eB8WQPBUj6yn1Zr29nhVH2y5ifC92QbLA1h7ry9vtVXZpgspIrZbcMVKD0b3Lfb64B1NK7pnHYS0xW5Q/WfTGqZh68d/uw62WNCAfgOOdfM2NExyADzqbrAGANx@AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
≔⪪S.θW⊟EθΦκ‹ΣμLκ⊞θ…⊟θI§ι⁰⪫θ.
```
[Try it online!](https://tio.run/##HY3LCoMwFET3fkVwdQNRLKXduJJCwVJB8AuCBhOMeZhr279PjbMYGDiHGSXfRst1jE0IajYwOK0QWuN2HHBTZgbKSF7mR3taZ1@ptCDQWwcdd@AZeSqNYoOFkbcIAYZ9hZWmYWaUsNAzpN@DTHRn9XTa/mAePCA02JpJ/EAxUiW0zvrjFuFllUlG@qZ1jEVVXq73Wyw@@g8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪪S.θ
```
Split the input on `.`.
```
W⊟EθΦκ‹ΣμLκ
```
Filter each part on those digits that are less than the string's length. Then take the last result. (This saves 1 byte over filtering on just the decimals.) Loop until that is empty.
```
⊞θ…⊟θI§ι⁰
```
Take the first filtered digit and truncate the decimals to that length.
```
⪫θ.
```
Join the parts back together and implicitly print.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-pl`, 48 bytes
```
c=i=j=$_=~/,/;$_=$_[0,c.to_i-~j]while c=$_[i+=1]
```
[Try it online!](https://tio.run/##RYzNCsJADITveQoP3szaZP8X2SeRUrAIbim2aEW89NFd1/VgApnMxzC3x@mVcx9THOK2i2uDzaHotjsS9vtl6pJYh/Z5SeN5039x2kVuc2aH2gZNXkpgQm0kk9fAUqEG4bVDRU5WTxA8Omu0KhkgVGwNCEJWRb0MymG9lVFdEIy/j0B6tF7L4IAVKlMKwn/e07yk6XrPYh4/ "Ruby – Try It Online")
Uses a decimal comma instead of a dot.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~84~~, 78 bytes
Takes input as a pointer to a string buffer, outputs by modification. Note that providing a pointer to a buffer that is too small (`intPartLen + 1 + 9 > bufSize`) can cause `SEGFAULT`.
If assuming the size of the buffer to be sufficient is not allowed, +7 to the score.
```
l,M;f(char*F){F=strchr(F,46);for(l=47,M=57;*++F&&++l<M;*F<M?M=*F:0);F[M-l]=0;}
```
[Try it online!](https://tio.run/##RU7LasMwEDwnXyECCX5J6GVLquL2ppu/wM0hFTgxuGmw05QS8uvdykqhu7CzOzMM6/HBe4ChaGyX@ON@zFx6c/V0Gf1xTFwhq9R2H2My1FIVTV0qm@W522zyfNg2NnPb5qWpM/dEU@vaBg@7mto7vO/7U9KfLsgXaA5FWXZN0W25CFEoCj2qEbMBtsgHyPM0qIvoffvsWkbpzgZi/uP8nQSqQNe236Uz2c133M5jyOqS1XpC@Bmtp9fT6uEr0J/lvrwDMEVkZSTVnAOjRJacUS2BcUEkYC0VEVTxeFMwmqiqlCJ4gBLBqhIwJUwE1NwIReKMHI0NmJHHRoFrUmnJjQImiCjBGGL@68d3w/4wAf76BQ "C (gcc) – Try It Online")
## Degolf
```
l,M;f(char*F){
F=strchr(F,46); // Find the pointer to the period.
for(l=47,M=57; // Initialize variables (48='0', 57='9')
*++F&&++l<M; // Check for null terminator, and that we're not
// going through too many decimals
*F<M?M=*F:0); // Keep smaller of M and the char pointed to by F.
F[M-l]=0; // Explained below.
}
```
At the end of the loop, `F` is a pointer to the `n`th decimal after the decimal point (`ptr`). `M` is the smallest digit observed as its ASCII value. `l` is `'0'+n-1` (or `47+n`). Thus:
```
F[M-l] == *(F + M - l)
F[M-l] == *(ptr + n + M - '0' - n + 1)
F[M-l] == *(ptr + M - '0' + 1)
```
Which gives us a pointer to the first character to truncate; replacing this character with a `\0` results in the truncation of the remaining digits for most intents and purposes. This is also where the `SEGFAULT` happens; for example, if the input is `123.4`, the smallest digit is `4`, and the pointer will point to the character `*` in `123.4\0??*`.
[Answer]
# PHP, 92 bytes
several solutions, same length:
```
# any PHP:
for($n=$argn,$t=9;~$d=$n[$i+++$p=1+strpos($n,46)];$n=substr($n,0,$p+$t))$t<$d||$t=$d;echo$n;
for($t=9;$i<$t&&~$d=$n[$i+++$p=1+strpos($n=$argn,46)];)$t<$d||$t=$d;echo substr($n,0,$p+$t);
for($t=9;$i<$t&&~$d=$n[++$i+$p=strpos($n=$argn,46)];)$t<$d||$t=$d;echo substr($n,0,$p+$t+1);
# PHP 7:
for($t=9;~$d=($n=&$argn)[$i+++$p=1+strpos($n,46)];$n=substr($n,0,$p+$t))$t<$d||$t=$d;echo$n;
for($n=$argn;~$d=$n[$i+++$p=1+strpos($n,46)];$n=substr($n,0,$p+$t))($t??9)<$d||$t=$d;echo$n;
```
Run as pipe with `-nR` or [try (most of) them online](http://sandbox.onlinephpfunctions.com/code/1cdb748d133f6bcd5472dd2b186edd1c83a8e3dd).
[Answer]
# JavaScript, 58 bytes
Input and output as a string, using a comma as the decimal separator.
```
s=>s.replace(/,.+/,g=d=>d[++n]?g(d.slice(0,-~d[n])):d,n=0)
```
[Try it online](https://tio.run/##bZJfb4IwFMXf/RSE@NCGK7b8Z0ndkw97W/bqSFopGg0rRHDR6PbVHaUQzbaS0HPOvbS/lO7Fp2jyw65uZ6qSxS2vVFOVhVtWW8RfVH1srXFcrbeiOZbt6JanusjbQhr3KprmXXGHz7h7KOpCtCgkGE827NawRaOzUuQFmoPrzGHLJFvIleOo7HmLpNuUu65GYPYtVyrD@EmCYgTfWrayaQxBlAYk8TwbbEogCD1KkkAbzwc9z5IgBp/E3pCRbk4TiKMw8LvezhHwaRTqVgLU71XipX4M/XvISf9oQ8Fo/amXQJQEXqq7qA9@2C@X3ofp6Tays8nhDmyDPhkDPGrDaxngh1BnA/CQdsC96sGMGoF/5b2hMGrLAI@L/wXWFQNsW9lk8vjHW/dD1Aid4IzZgk8vpy/u1kIulUQ0wA6/WtOLYBt0wv8U1uywOmd/CtxBgrE1xu6@2ine3RF8@wE)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg) `-p`, ~~57~~ 41 bytes
```
$!=m/\./.to;.=substr(0,$!+$/)while m:c/./
```
[Try it online!](https://tio.run/##RUzLCsJAELvPV1joQdGdndnZp9I/8aQULLS2tBX/3rWsBxNIMkPI1M69z7mumkFfUeM6XrBZXrdlnfd0qqtjrQ/vR9e3u@F816hz5oDWJ0vRGGBC6wxTtMBG0IKKNqBQMOUmSBGDd1a2DhAKeweKkGXzaJIELFp@VAiK8ZcITEQfrUkBWFDcNpD@@IzT2o3PJavpCw "Perl 6 – Try It Online")
### Explanation
```
$!=m/\./.to; # Store position of decimal point in $!
.=substr(0,$!+$/) # Truncate string to length $!+$/
while m:c/./ # while there's a match for the next digit
```
[Answer]
# [Python 3](https://docs.python.org/3/), 77 bytes
```
g,h=input().split(".")
for i in h:h=h[:int(i)]if i in h else h
print(g+"."+h)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P10nwzYzr6C0RENTr7ggJ7NEQ0lPSZMrLb9IIVMhM08hwyrDNiPaKjOvRCNTMzYzDSqqkJpTnKqQwVVQBJJJ1wZq0s7Q/P8fAA "Python 3 – Try It Online")
Somehow, despite slicing past the end of a string and modifying while iterating on that same string, the interpreter doesn't complain.
This answer has a similar structure to the other Python one, but uses a different method to find where to truncate and works in newer versions of Python.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~78~~ 68 bytes
*-10 bytes from @tsh*
```
a=>eval('for([x,y]=a.split`.`,i=0;c=y[i++];y=y.slice(0,c));x+`.`+y')
```
[Try it online!](https://tio.run/##hZLdjoIwEIWv3acg3ghBxumPUELqK@wDGBMJCxs2RAygkadnKeJqllHbhNCefqeHGX7ic1wnVX5svEP5lXaZ7mK9Sc9xYS@ysrK3l2W70zHUxyJv9rBf5hqjRLfb3HV3UatbqIs8SW1cJo4TXdz@iNsunC4pD3VZpFCU33Zmz1kA0g8lKs7njuVa89lqZX2ejqfG0htrVHvFjNnHfxhBrjlDJSnWiCNJoFwASZl9RLTssrounJsHbeQpGYDAgIpvtMFoOHQ3ItMgneYvyJscoYLAX0vRl4MwGtVnhUQQzF8TXC88Xjv9egQmSNIoD@iEVDwUAQxPgr6pzwIbdxzmm6unJIMrSJXJY9d2sXu1JwZcga8kD6nYg/aizQIEVathf/zlzOubViOE90E27UHtfgE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 115 bytes
```
import StdEnv,Text
$s#[i,d:_]=split['.']s
=i++['.':iter 9(\p=hd([take n\\n<-map digitToInt p|n<length p]++[id])p)d]
```
[Try it online!](https://tio.run/##bVBba4MwFH6uvyKwgco0xMR6Ge3b9lDYYNC@aRiuZm2YRqnpLrDfPhet2qxMwZzv4nfOybZgmWjLKj8WDJQZFy0v6@ogwVrm9@Ld2bBPaVw3Vwl38ttnumzqgsvEhCZtjCW/uenKWy7ZAcRWWi/3uZXI7I0BkaZi4ZZZDXK@43JTrYQE9bdYFEzs5B7UVP3Lc2rXdk7btcxUyyVIePPIyheVZl0DLuqjtEF1lOpsQJoCq6eckbLBwgWSNbKhxseeHZgx61EXZMxmVmJ6IfSD2EcRxiZ1QDIxJqW2M3gQ9OfYQ5E/WjpCN2ACJ62rEUIKTsJkdCM/hASFY68O98ZeuEhE58QpTLPEEQyDuU/UYINxYDQPgsQL5oOsgD4Kgh6ZtA5pYoRjEsL@OxhG5iIB9e//Ia4HT/I4n@uddvX0NXAEg8jH8diox/pNEEjGKft6uNkTrW0an59pYY3RG6o7O3cj@E/MPPADPAV0qJOVStuf7WuR7ZrWXT20d18iK/n2BJ6KTL5Wh/IX "Clean – Try It Online")
Defines the function `$ :: [Char] -> [Char]`. Link includes test suite.
] |
[Question]
[
The goal of this challenge is to reduce a list of string to a shorter more general list of string.
# Input
The Input is provided with space between the string (a b c) or in list form (["a","b", "c"]). It's a list list of string that can be of the following form :
* aaa
* aaaX
* aaaX/Y
With **aaa** any set of non capital alphabetic letter, and **X** or **Y** any digit between 0 and 9.
# Ouput
A list of generalized string that can be separated by anything. String are of the form :
* aaa
* aaaX
* aaaX/Y
With **aaa** any set of non capital alphabetic letter that were in the input list. X and Y stay the same and symbolise the digit. The goal of the challenge is to reduce the input list of string into their generic representation.
# Examples
Two strings can be reduced :
```
Input : regex1 regex2 split1/0
Output : regexX splitX/Y
```
Full example :
```
Input : toto toto titi titi1 titi2 titi5 tutu tutu0 tutu1 tutu1/2 tutu0/1
Output : toto titi titiX tutu tutuX tutuX/Y
```
Another example :
```
Input: ["foo0","bar0","baz0/0","eth0/0","eth0/1","eth1/0","eth1/1","vlan8","modem0"]
Output: ["fooX","barX","bazX/Y","ethX/Y","vlanX","modemX"]
```
# Scoring
This is code-golf; shortest code in bytes wins.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~25~~ ~~18~~ 13 bytes
**6 byte thanks to FryAmTheEggman, and for inspiration of extra 1 byte.**
```
\d
X
/X
/Y
D`
```
[Try it online!](http://retina.tryitonline.net/#code=XGQKWAovWAovWQpEYA&input=dG90bwp0b3RvCnRpdGkKdGl0aTEKdGl0aTIKdGl0aTUKdHV0dQp0dXR1MAp0dXR1MQp0dXR1MS8yCnR1dHUwLzE)
[Answer]
# Perl, ~~29~~ 27 bytes
Includes +1 for `-p`
Give input list as seperate lines on STDIN:
```
perl reduce.pl
regex1
regex2
split1/0
^D
```
reduce.pl:
```
#!/usr/bin/perl -p
s/\d/X/&&s//Y/;$_ x=!$$_++
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 21 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)
```
∪'/\d' '\d'⎕R'/Y' 'X'
```
`⎕R` regex replaces the left-side strings with the right-side ones
`∪` returns the unique elements
[TryAPL online!](http://tryapl.org/?a=f%u2190%u222A%27/%5Cd%27%20%27%5Cd%27%u2395R%27/Y%27%20%27X%27%20%u22C4%20f%27regex1%27%20%27regex2%27%20%27split1/0%27%20%u22C4%20f%27toto%27%20%27toto%27%20%27titi%27%20%27titi1%27%20%27titi2%27%20%27titi5%27%20%27tutu%27%20%27tutu0%27%20%27tutu1%27%20%27tutu1/2%27%20%27tutu0/1%27%20%u22C4%20f%27foo0%27%20%27bar0%27%20%27baz0/0%27%20%27eth0/0%27%20%27eth0/1%27%20%27eth1/0%27%20%27eth1/1%27%20%27vlan8%27%20%27modem0%27&run)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~61~~ ~~59~~ ~~44~~ 42 bytes
**2 bytes thanks to Fatalize.**
```
~~:{:ef:{~s"0123456789","X".;?.}ac.}a:{rbh"/",?rbr:"Y"c.;?.}ad.~~
~~:{:ef:{~s"0123456789","X".;?.}ac.L(rbh"/",Lrbr:"Y"c.;.)}ad.~~
~~:{s"/",?rbbbr:"X/Y"c.;.?t~s@A;?rbr:"X"c.}ad.~~
:{s"/",?rbbbr:"X/Y"c.|.t~s@A|rbr:"X"c.}ad.
```
[Try it online!](http://brachylog.tryitonline.net/#code=OntzIi8iLD9yYmJicjoiWC9ZImMufC50fnNAQXxyYnI6IlgiYy59YWQu&input=WyJ0b3RvIjoidG90byI6InRpdGkiOiJ0aXRpMSI6InRpdGkyIjoidGl0aTUiOiJ0dXR1IjoidHV0dTAiOiJ0dXR1MSI6InR1dHUxLzIiOiJ0dXR1MC8xIl0&args=Wg)
[Answer]
# Python, 69 bytes
```
import re
lambda s:set(re.sub("\d","X",s).replace("/X","/Y").split())
```
[Answer]
# Javascript, ~~92~~ 78 bytes
```
a=a=>[...new Set(a.replace(/\d/g,"X").replace(/\/./g,"/Y").split` `)].join` `;
```
[Answer]
# PHP, 104 bytes
```
<?=join(' ',array_unique(explode(' ',preg_replace('%\d%','X',preg_replace('%\d/\d%', 'X/Y',$argv[1])))))
```
expects input as single argument
I could replace the `join(' ',array_unique(explode(' ',...)))` with `preg_replace('%(\b\w+\b)(?=.*\b\1\b)%','',...)`, but it´s 6 bytes shorter via the array.
**127 bytes for list of arguments:**
```
<?foreach($argv as$i=>$s)if($i)$r[]=preg_replace('%\d%','X',preg_replace('%\d/\d%', 'X/Y',$s));echo join(' ',array_unique($r));
```
**120 bytes for a function on an array:**
```
function r($a){foreach($a as$s)$r[]=preg_replace('%\d%','X',preg_replace('%\d/\d%', 'X/Y',$s));return array_unique($r);}
```
] |
[Question]
[
Your program's input is a string containing whitespaces, parentheses, and other characters. The string is assumed to be parenthesed correctly, i.e. each right parenthesis matches a unique left parenthesis and vice versa : so the program is allowed to do anything on incorrectly parenthesed strings, such as `)abc`, `(abc` or `)abc(`.
The character interval between a left parenthesis and the corresponding right parenthesis (including the parentheses) is called a *parenthesed interval*.
Your program's job is to decompose the string into blocks according to the rules below, and output the result as a "vertical list", with one block per line.
Now, two characters in the string are in the same block if either
(a) there is no whitespace character strictly between them
or
(b) there is a parenthesed interval containing them both.
Also,
(c) Whitespaces not in any parenthesed interval are mere separators
and to be discarded in the decomposition. All the other characters (including whitespaces) are retained.
For example, if the input is
```
I guess () if(you say ( so)), I'll have(( ))to pack my (((things))) and go
```
The output should be
```
I
guess
()
if(you say ( so)),
I'll
have(( ))to
pack
my
(((things)))
and
go
```
Another useful test (thanks to NinjaBearMonkey) :
```
Hit the ( Road (Jack Don't) come ) back (no (more ) ) no more
```
The output should be
```
Hit
the
( Road (Jack Don't) come )
back
(no (more ) )
no
more
```
The shortest code in bytes wins.
[Answer]
## [Retina](https://github.com/m-ender/retina/), 31 bytes
```
S-_` (?=([^)]|(\()|(?<-2>.))+$)
```
[Try it online!](http://retina.tryitonline.net/#code=Uy1fYCAoPz0oW14pXXwoXCgpfCg_PC0yPi4pKSskKQ&input=SSBndWVzcyAgICAgKCkgaWYoeW91IHNheSAoIHNvKSksIEknbGwgaGF2ZSgoICApKXRvIHBhY2sgbXkgKCgodGhpbmdzKSkpIGFuZCBnbwpIaXQgdGhlICggUm9hZCAoSmFjayBEb24ndCkgY29tZSApIGJhY2sgKG5vIChtb3JlICkgKSBubyBtb3Jl)
This is a standard exercise in [balancing groups](https://stackoverflow.com/a/17004406/1633117). We simply match all spaces from which we can reach the end of the string while passing only correctly matched parentheses (since the ones we don't want to remove are followed by an unmatched closing parenthesis), and split the input around those matches. The `_` option removes empty segments in case there are several spaces in a row and the `-` suppresses the default behaviour to include captured substrings in the result.
[Answer]
# Retina, 30 bytes
```
!`(\(()|(?<-2>)\)|(?(2).|\S))+
```
1 byte shorter...
[Try it here.](http://retina.tryitonline.net/#code=IWAoXCgoKXwoPzwtMj4pXCl8KD8oMikufFxTKSkr&input=SSBndWVzcyAgICAgKCkgaWYoeW91IHNheSAoIHNvKSksIEknbGwgaGF2ZSgoICApKXRvIHBhY2sgbXkgKCgodGhpbmdzKSkpIGFuZCBnbwpIaXQgdGhlICggUm9hZCAoSmFjayBEb24ndCkgY29tZSApIGJhY2sgKG5vIChtb3JlICkgKSBubyBtb3Jl)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 22 bytes
```
j0G40=G41=-YsG32=*g(Yb
```
[**Try it online!**](http://matl.tryitonline.net/#code=ajBHNDA9RzQxPS1Zc0czMj0qZyhZYg&input=SSBndWVzcyAgICAgKCkgaWYoeW91IHNheSAoIHNvKSksIEknbGwgaGF2ZSgoICApKXRvIHBhY2sgbXkgKCgodGhpbmdzKSkpIGFuZCBnbw)
### Explanation
This uses a builtin function for splitting a string at spaces. To avoid splitting at spaces between matching parentheses, these are first detected and replaced by character 0. This is not detected as a space by the string-splitting function, but is treated as a space by the implicit display function.
```
j % Take input as a string.
0 % Push 0
G40= % True for occurrences of '('
G41= % True for occurrences of ')'
-Ys % Subtract and cumulative sum. Positive values correspond to characters
% between matching parentheses
G32= % True for occurrences of space
*g % Multiply, convert to logical. Gives true for spaces between matching
% parentheses
( % Assign 0 to those positions. This replaces spaces between matching
% parentheses by character 0
Yb % Split at spaces, treating consecutive spaces as a single space.
% Character 0 does not cause splitting, but is displayed as a space
```
[Answer]
## JavaScript (ES6), 61 bytes
```
s=>s.replace(/[()]| +/g,c=>(c<`(`?n:c<`)`?++n:n--)?c:`
`,n=0)
```
Works by matching all parentheses and runs of spaces, maintaining a count of the nesting depth and replacing the run with a newline if the nesting depth is zero.
[Answer]
## APL, ~~55~~ 53 bytes
```
{⍵⊂⍨((⍵≠' ')∨~b)×+\1,¯1↓(b←0=+\1 ¯1 0['()'⍳⍵])∧⍵=' '}
```
To be run in `⎕ml←3`. Usual trick: cumulative scans of 1s and -1s to identify the areas enclosed by parentheses. Where the cumulative sum is 0, then we are outside parentheses. Boolean and the vector with the boolean vector with 1s where there are spaces. Rotate by 1 to the right inserting a 1 on the left. Build another running sum where each change identifies a segment. We're almost done, but we still need to remove the spaces at level 0. That's what the left side of the multiplication does: it zeroes out the level 0 spaces in the running sum. The dyadic enclose `⊂⍨` splits every time the running sum changes while throwing away the zeroes.
[Answer]
## Perl, 80 bytes (79 + `-n` flag)
```
$r=qr/[^\(\)]*(\((??{$r})\))?[^\(\)]*/;/((([^ \(]*(\($r\))?)+ *)(?{say$^N}))+/
```
Run with :
```
perl -M5.010 -ne '$r=qr/[^\(\)]*(\((??{$r})\))?[^\(\)]*/;/((([^ \(]*(\($r\))?)+ *)(?{say$^N}))+/'
```
It might not be easy to read, so here are the explanations :
```
# The first regex ($r) is meant to match anything between two matching parenthesis
$r = qr/ [^\(\)]* # match anything but parenthesis
(\( # match an opening parenthesis
(??{$r}) # reccursive call to the same regex
\) # match a closing parenthesis
)? # the 3 previous lines are optionnal
[^\(\)]* # match anything but parenthesis
/x;
# The second regex kinda split the input according to the rules
/(
(
([^ \(]* # match anything but spaces and parenthesis
(\($r\))? # optionnal : match an opening parenthesis, then let the
# first regex match anything until the matching closing parenthesis.
)+ # repeat (no spaces out of parenthesis has been found yet)
\ * # match the space(s) that delimite the outputed lines.
)
(?{say$^N}) # execute the code 'say $^N' which prints the content
# of the last closed group (which is the line above)
)+ # repeat as many times as possible
/x
```
[Answer]
# C (32-bit), 115 113 bytes
```
s,*P;main(q,c){char*p=P=1[P=c],*o=p;for(;c=*p++;c^=32,s+=c^9?c==8:-1,*o=s|c?c^32:10,o+=s|c||q,q=c);*o=0;puts(P);}
```
Compile as 32-bit C, and pass input string as command-line argument. E.g.:
```
~/golf/ λ gcc -m32 -w golf.c && ./a.out "Hit the ( Road (Jack Don't) come ) back (no (more ) ) no more"
Hit
the
( Road (Jack Don't) come )
back
(no (more ) )
no
more
```
] |
[Question]
[
A partition of a list \$A\$ is a way of splitting \$A\$ up into smaller parts, concretely it is list of lists that when concatenated gives back \$A\$.
For example `[[1],[2,3],[5,6]]` is a partition of `[1,2,3,5,6]`. The trivial partition is a partition that "splits" the list into only one piece, so `[[1,2,3,5,6]]` is also a partition of `[1,2,3,5,6]`.
One partition \$X\$ is finer than another partition \$Y\$ iff \$X\$ can be made by partitioning the pieces of \$Y\$ in place. So for example `[[1],[2],[3],[5,6]]` is finer than `[[1],[2,3],[5,6]]`. But `[[1,2],[3],[5],[6]]` is *not* finer than `[[1],[2,3],[5,6]]`, even though it splits it into more parts. Note by this definition every partition is finer than itself. For two partitions it can easily be the case that neither of them is finer than the other.
Your task is to take as input a partition \$A\$ of a list of positive integers and output a distinct partition \$B\$ of the same list, such that \$A\$ is not finer than \$B\$ and \$B\$ is not finer than \$A\$. The input will never be the trivial partition (no cuts made) or the cotrivial partition (all cuts made). That is you don't need to worry about cases where there is no valid output.
Input can be taken as a list of list, array of arrays, vector of vectors or any reasonable equivalent. Output should be given in the same format as input.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 7 bytes
```
T`,;`;,
```
[Try it online!](https://tio.run/##K0otycxL/P8/JEHHOsFa5/9/Q2sjHWMuQx0jayAJYlub6pgBAA "Retina 0.8.2 – Try It Online") Takes input and output as a semicolon-delimited list of comma-delimited lists. Explanation: Simply partitions the original list only in the places that the input list didn't partition it. In particular, anywhere the input list partitions the original list, the output list does not, and therefore is not finer than the input list, but the same applies in reverse so that the input list is not finer than the output list.
13 bytes with a more standard I/O format:
```
,
},{
}},{{
,
```
[Try it online!](https://tio.run/##K0otycxL/P9fh6tWp5qrFkhUc@n8/19dbQhkGukY19ZyAdk6RkAelA0V16k21TGrrQUA "Retina 0.8.2 – Try It Online") Takes output as a list of lists, each element separated by `,` and each list wrapped with `{` and `}`. Explanation: Switches between `,` and `},{` (which represents `;` above) by first wrapping each `,` to `},{` and then double-unwrapping `}},{{` to `,`.
[Answer]
# [Haskell](https://www.haskell.org/), 47 bytes
```
f((h:t):r)|t>[]=[h]:[id=<<t:r]|a:b<-f r=(h:a):b
```
[Try it online!](https://tio.run/##bY6/DoIwEMZ3nuJiHCA5B0UcGuoT6OR46VCCUGL5k1LjwrvXSkxAYfhyd798990p2T/uWjtXhKFiNmImGuyZBCclGFU5T1PLjBgky9JdAYZ7l4xY5krQvJbdFbqnvVlzaYB61b5A41i2UPh2sxFBLasGOORtACUQ7QXSwSvGoxBfhCPwmtDHhfG/43fEhX2eMIViMoO4dmfxiwdICZ4Wi7gGV9LcGw "Haskell – Try It Online")
Recursively pattern matching first element *`(h:t)`:r*
*t>[]* : if its tail is a list, we isolate head *[h]* and join everything else.
Else we do the same with the rest and join first el. of result with *h* which is a singleton.
[Answer]
# [Python](https://www.python.org), 98 bytes
```
lambda a:[(l:=[*chain(*a)])[:(i:=-~[len(x)>1for x in a].index(1))]]+[l[i:]]
from itertools import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Lc1NCsIwEEDhvaeIu0xNhfpbAvUi4yxS29CBNCkxQt14ETcF0Tt5GwVdfZsH7_4arqkLfnrY6vi8JJuX79qZvm6MMBql0xVmp86wl5kBAtSSdZXf0LVejnAobIhiFOyFoSX7ph1lAUC0QIesiWY2hl5wamMKwZ0F90OIKfuf5kNkn6SViIVakcK12qjt153aq5II4BdO088P)
Takes input as a list of lists, returns as a list of list.
Though the code is a bit retch-inducing, the way it works is
1. Join all of the lists together.
2. Split the list at an index which is associated with a list of at least 2 elements in \$A\$.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-Q`](https://codegolf.meta.stackexchange.com/a/14339/), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
m¸·¸m·
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVE&code=bbi3uG23&input=W1siMSIsIjIiXSxbIjMiLCI0Il1d)
Basically the same logic as [Neil's Retina answer](https://codegolf.stackexchange.com/a/252641/71434).
```
m¸·¸m·
m¸ # Join each part to a string with " " as a delimiter
· # Join the resulting strings with "\n" as a delimiter
¸ # Split that string at " " characters
m· # Split the substrings at "\n" characters
```
Input and output are "Array of arrays of strings". The same code works for input as numbers/output as strings. Input and output as numbers takes an extra [2 bytes](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVE&code=bbi3uK63bW4&input=W1sxLDJdLFszLDRdXQ).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ẈÄṬ¬kẎ
```
[Try it online!](https://tio.run/##ASoA1f9qZWxsef//4bqIw4ThuazCrGvhuo7/w4fFkuG5mP//WzEsMl0sWzMsNF0 "Jelly – Try It Online")
Another port of Neil's logic--completely invert the partition--except without string operations. Takes and returns a list of lists.
```
Ṭ Generate an array with 1s at the indices in
Ä the cumulative sum of
Ẉ the lengths of the original partitions.
k Partition the array
Ẏ concatenated
¬ after positions of 0s.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 58 bytes (@AZTECCO)
```
lambda s:eval(`s`.replace('], [',',').replace(', ','],['))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMHiNNuYpaUlaboWN61yEnOTUhIViq1SyxJzNBKKE_SKUgtyEpNTNdRjdRSi1XWAUBMhpqMA5MfqRKtrakJM2FVQlJlXopCmER1tqGMElDHWMQGSprGxUAULFkBoAA)
Port of @Neil's answer. This takes and returns a list of lists.
# [Python](https://www.python.org), 50 bytes
```
lambda s:s.replace(',','],[').replace(']],[[',',')
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3jXISc5NSEhWKrYr1ilILchKTUzXUdYAwVidaXRMhFAvkR4MlNCE69xYUZeaVaKRpqEdHG-oYAaWNdUyApGlsrLomVM2CBRAaAA)
Port of @Neil's answer. Takes and returns strings (brackets, commas, no spaces).
### [Python](https://www.python.org), 73 bytes
```
def f(s):
*o,i=[],[],0
for c,*r in s:o[i]+=c,;o[1]+=r;i|=r>[]
return o
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3PVNS0xTSNIo1rbgUtPJ1Mm2jY3WAyIBLIS2_SCFZR6tIITNPodgqPzozVts2Wcc6P9oQyCiyzqyxLbKLjuVSKEotKS3KU8iHGmhZUJSZV6KRphEdbahjBDTMWMcESJrGxmpqciHJAcXQZCEGwFwGAA)
Port (to no-itertools) of @97.100.97.109's answer.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 46 bytes
```
f@{x___,{a_,b__},y___}:=Flatten/@{{x,a},{b,y}}
```
[Try it online!](https://tio.run/##LYuxCsJAEER/5SBgNRKSqIWgXGVtfxzLRhIMmBRyRcKy376uaDED7zEzc3kOM5fpwWZjlJWIIEzoiRSbk54vtxeXMix1FFnBCumxqdr9PS0lVWF/DWOqcg67UMcgIg1aH3U4qMK5cWjReR9x@qvf4qs8LtUsucxIfssf "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
»#¶δ¡
```
Inspired by [*@Neil*'s Retina answer](https://codegolf.stackexchange.com/a/252641/52210): outputs the inverted partition of the given input.
I/O as a list of lists of strings.
[Try it online](https://tio.run/##yy9OTMpM/f//0G7lQ9vObTm08P//6GglQ6VYHYVoJSMlHQUlYwjbFMQ2U4qNBQA) or [verify some more test cases](https://tio.run/##ASsA1P9vc2FiaWX/NUwuxZPCpsKowqd2eT8iIOKGkiAiP3n/wrsjwrbOtMKh/yz/).
**Explanation:**
```
» # Join each inner list by spaces, and then each string by newlines
# # Split this multiline string by spaces
δ # Map over each substring:
¶ ¡ # Split it by newlines
# (after which the result is output implicitly)
```
[Answer]
# [Python](https://www.python.org), 72 bytes
```
def f(a):
a+=[z:=[]]
for x in a:z+=[x.pop()]
while[]in a:a.remove([])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3PVJS0xTSNBI1rbgUErVto6usbKNjY7kU0vKLFCoUMvMUEq2qgMIVegX5BRqaQInyjMyc1OhYsEyiXlFqbn5ZqkZ0rCbUPM1EBVuF6GhDHaNYnWhjHRMdUyBtpmOuYwE0FWQPV0FRZl4JkAHRAHMIAA)
Port of [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)'s [solution](https://codegolf.stackexchange.com/a/252838/73593)
] |
[Question]
[
>
> [Related](https://codegolf.stackexchange.com/questions/135484/calculating-bpm-with-inputs) as it requires you to measure the time between the first and last input. But here you're required to count how many inputs in a period of time.
>
>
>
I was assigned a task to stand by a gate and count how many students enter it. The problem is that my memory is not as good as it was when I first started this job. I need some kind of program to help me count how many students enter the gate until my shift is over.
# Task
Given an integer `t` that represents the number of seconds until my shift is over. Tell me how many times I pressed the button during that time.
# Rules
* The button press can be any convenient user input, such as pressing the Return key;
* You can assume that `t` will allways be in range `[1; 60]`;
* You can assume that the number of students will be less than 231;
* When the time is up, you must output within 1 second;
* Your program does not need to end, as long as the only output to stdout is at the end of the shift;
* If your input method (such as Enter-key) repeats if held, you can choose to count it just once, or several times. Either way, you must still be able to handle separate inputs.
[Answer]
# TI-Basic, 22 bytes
Fairly simple. Sets a time `Ans` seconds in the future which we call `T` which is when the loop stops. While the loop is going, we check for if a key is pressed. It's been a while since I had the fgitw :)
```
startTmr+Ans->T
0
While T≠startTmr
Ans+not(not(getKey
End
```
[Answer]
# Ruby, ~~38~~ 42 bytes
Uses the global variable `$.`, which counts how many times the standard input function `gets` has successfully been completed. As such, it will only give accurate results the first time it is called per program run.
Input via command-line argument, such as `ruby gatekeeper.rb 40`
```
Thread.new{loop{gets}}
sleep eval$*[0]
p$.
```
[Answer]
# [AHK](https://autohotkey.com/), 110 bytes
```
1*=-1000
c=0
Loop,255
Hotkey,% Format("vk{:x}",A_Index),s,On
SetTimer,q,%1%
Return
s:
c++
Return
q:
MsgBox,%c%
```
This is not as short as other submissions, but it distinguishes itself by allowing you to use practically [***any key***](http://www.kbdedit.com/manual/low_level_vk_list.html) as a counter. This includes mouse clicks and control keys like `Ctrl`, `Shift`, etc. *unless* you use special keys that can never be blocked such `Ctrl`+`Alt`+`Del` on Windows.
Two important notes:
* The key presses and mouse clicks are blocked from other software
* The program does not terminate
If you actually run this program, it will count for `1` seconds (where the variable `1` is the first passed parameter), all the while counting how many key presses you made and blocking each one. When that time expires, it pops up a message box with the total. However, seeing as how all keyboard and mouse inputs are still blocked, it's rather difficult to dismiss that message. That sounds like a job for the next gatekeeper.
[Answer]
## C++ 11, MSVC, ~~255~~ ~~254~~ ~~246~~ 244 bytes, MSVC without `/Za` flag : ~~204~~ 202 bytes
-1 byte thanks to Zacharý
-8 bytes thanks to Tas
-42 bytes for the second version thanks to Tas
Can be compiled with `/Za` flag ( disabled extensions ) :
```
#include<thread>
#include<conio.h>
#define S(t)std::this_thread::sleep_for(std::chrono::milliseconds(t))
int r=1;void k(int*a){while(r){if(_kbhit()&&_getch())++*a;S(1);}}int c(int n){int a=0;std::thread t(k,&a);S(n*1000);r=0;t.join();return a;}
```
Can't be compiled with `/Za` flag ( require enabled extensions ). For more details, see [this answer](https://stackoverflow.com/a/5489774/6784509)
```
#include<thread>
#include<conio.h>
#include<Windows.h>
int r=1;void k(int*a){while(r){if(_kbhit()&&_getch())++*a;Sleep(1);}}int c(int n){int a=0;std::thread t(k,&a);Sleep(n*1000);r=0;t.join();return a;}
```
Ungolfed and explanations :
```
#include<thread> // For the thread standard library
// Console IO, C header used mostly by MS-DOS compilers. Not ISO C nor POSIX standard
#include<conio.h> // Used for _getch and _kbhit
//Macro that takes the number of milliseconds to make the current thread go to bed and sleep
#define S(t) std::this_thread::sleep_for(std::chrono::milliseconds(t))
//Global bool that will indicate the input thread if it continues to run or not
bool r=true;
/**
* @brief: Function that increment a variable every time a key is pressed
* @param a : a pointer to the memory location where to increment the counter
* References are unfortunately forbidden
*/
void k(int* a) {
while(r) {
if(_kbhit() && _getch())
++*a;
S(1);
}
}
/** Function to call
* @brief : Counts the number of time a key is pressed
* @param : The number of seconds it have to capture the key presses
* @return : the number of times a key was pressed
*/
int c(int n) {
int a=0;
std::thread t(k,&a);
S(n*1000);
r=false;
t.join();
return a;
}
```
[Conio.h Wikipedia page](https://en.wikipedia.org/wiki/Conio.h)
[Answer]
# JavaScript (ES6), 50 bytes
```
t=>setTimeout("alert(i)",1e3*t,i=0,onclick=_=>i++)
```
## Test Snippet
```
f=
t=>setTimeout("alert(i)",1e3*t,i=0,onclick=_=>i++)
;f(10)
document.write("click to count...")
```
```
*{user-select:none}
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + [coreutils](http://www.gnu.org/software/coreutils), 39 bytes
This is an ugly way that creates a file `t` in the current directory because I couldn't get process substitution to work.. You count by pressing the return key and it continues counting if it's held down.
Use it like this: `$ f DURATION`
---
```
f(){ timeout -s3 $1 cat>t;cat t|wc -l;}
```
[Try it online!](https://tio.run/##NcSxDoIwEAbg3af4gw46MBg2SXwJV5fSXOFiOUjvGkLAZ68u5Eu@zulQSrjeNhiPNGVDrQ0ud3hnT2v/w/bFo47tt5zx4jFHZ4RElpPgQyvmRKqk6FaQHyaWHkJLZCF9nObEYgHVWw4VdgQ05Qc "Bash – Try It Online")
[Answer]
# C#, ~~132~~ 122 bytes
```
namespace System.Threading.Tasks{n=>{int c=0;Task.Run(()=>{for(;;++c)Console.ReadKey();});Thread.Sleep(n*1000);return c;}}
```
*Saved 10 bytes thanks to @DaveParsons.*
Full/Formatted version:
```
namespace System.Threading.Tasks
{
class P
{
static void Main()
{
Func<int, int> f = n =>
{
int c = 0;
Task.Run(() =>
{
for (; ; ++c)
Console.ReadKey();
});
Thread.Sleep(n * 1000);
return c;
};
Console.WriteLine(f(10));
Console.ReadLine();
}
}
}
```
[Answer]
# Python 3, ~~116~~ 110 Bytes
```
import time
def f(t):
s,l=time.time(),[]
while True:
l.append(input())
if time.time()-s>t:return len(l)
```
This is my first post, so not sure if this follows the format correctly.
Thanks for another few bytes Step
[Answer]
# [C + gcc + Linux x86\_64](https://gcc.gnu.org/), 89 bytes
```
d[999];f(n){for(*d=0,d[1]=n;d[5]=1;*d+=read(0,d+5,4))if(!select(1,d+5,0,0,d+1))return*d;}
```
Pass the number of seconds in as the argument `n`. Press Enter to count a student (and don't press other keys before or during the function). Returns the number of students counted when time is up.
Extremely unportable, and easily the most evil code I've ever written. It makes assumptions about the size and layout of `fd_set` and `struct timeval`, and about the behavior of `select`.
Anyway, `d[0]` is the student counter, `d[1]` through `d[4]` is the `struct timeval`, and `d[5]` through `d[260]` is the `fd_set`. `d[5]` is also the unused scratch space passed to `read`, and then gets immediately reset to `1` for the next `select` call.
[Answer]
# GameMaker Language, ~~49~~ 45 bytes
Make sure you have default that uninitialized variables are treated as 0. Also, default fps is 30. We're looking for any key to be pressed and this does repeat if held down.
In step:
```
while s<argument0*30{a+=keyboard_check(1)++s}
```
Alternatively,
```
while(get_timer()<argument0*1000000)a+=keyboard_check(1)
```
[Answer]
# JavaScript (Node.js), ~~112~~ 111 bytes
```
t=>require('readline').createInterface(process.stdin).on('line',_=>k++,k=0,setTimeout(_=>console.log(k),t*1e3))
```
I don't think it can be golfed more because Node.js function names are pretty verbose.
[Answer]
# [Python 3](https://docs.python.org/3/), 88 bytes
Takes Enter as input and doesn't terminate.
```
from threading import*
l=[0]
Timer(int(input()),print,l).start()
while 1:input();l[0]+=1
```
] |
[Question]
[
i.e each byte appears in a different ANSI shell colour.
# Rules
* Resetting the color of the shell after output is not required
* Must be output in STDOUT or the primary colour text output of your language.
* Must be done programmatically (iterating through each color and letter of the string induvidually) instead of just writing a fixed string to shell like the reference command.
* Must output the same as the reference command:
`echo -e '\e[30mH\e[31me\e[32my\e[33m!\e[34mH\e[35me\e[36my\e[37m!\e[90mH\e[91me\e[92my\e[93m!\e[94mH\e[95me\e[96my\e[97m!'`
on a recent version of bash (I am using 4.3 installed via Homebrew on OS X) i.e like this:
[](https://i.stack.imgur.com/qNLmH.png)
Obviously colours will vary based on terminal colour scheme.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest bytes wins.
[Answer]
# Bash, 62
```
h=y!He
for i in {3,9}{0..7};do printf \\e[${i}m${h:i%4:1};done
```
Must be run from an actual script file. If you want to try it from the command line, you'll need to escape the `!`, i.e. `h=y\!He`
[Online.](http://www.tutorialspoint.com/execute_bash_online.php?PID=0Bw_CjBb95KQMdHBzOVpIWHdHRUU)
[Answer]
# C, 126 bytes
```
#define a"\x1B[%d;%dm"
#define b j,i++
i,j;main(){for(;i=30,j<2;j++)printf(a"H"a"e"a"y"a"!"a"H"a"e"a"y"a"!",b,b,b,b,b,b,b,b);}
```
*output may vary depending on your compiler, linker, operating system, and processor*
Ideone doesn't have colour output, so have a screenshot from my phone:
[](https://i.stack.imgur.com/BQunj.jpg)
[Answer]
# bash, ~~101~~ 72 bytes
29 bytes saved with a trick from @DomHastings.
```
s='y!He'
for i in {30..37} {90..97}
do
printf "\e["$i"m"${s:$i%4:1}
done
```
If I hadn´t scrambled the string, this would have been 105 (`($i+2)%4` instead of `$i%4`), just as my
**previous approach, 105 bytes**
```
function p
{
s='Hey!'
for i in {0..3}
do
let r=i+$1
printf "\e["$r"m"${s:$i:1}
done
}
p 30;p 34;p 90;p 94
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~72~~ 71 bytes
```
Fi4C 2:c6B 3:c81 0:c23 1:c28si20[d1CP61Pn74Pd4%;cP1+dli>P]dsPx68si60lPx
```
Of course the escape codes won't render right on TIO, but you can still [try it online!](https://tio.run/##S0n@/98t08RZwcgq2cxJwdgq2cJQwcAq2chYwRBIWhRnGhlEpxg6B5gZBuSZmwSkmKhaJwcYaqfkZNoFxKYUB1SYAdWYGeQEVPz/DwA "dc – Try It Online")
First we set our input to base 15, this is solely for the sake of saving a byte. Make an array, `c`, of the code points for 'y', '!', 'H', and 'e'. We'll exploit the fact that 30 mod 4 == 90 mod 4; for both of our sets of color values, value mod 4 starts at 2, so that's where we put our 'H' in the array. From there it's just a matter of setting up a loop that runs until we hit the value stored in `i`. We have our color code on the stack, we print the necessary escape codes, print the stack value, mod 4 and print that value from the array `c`, then increment the stack. We run through this once starting from 30 w/ `i` set at 38, then once more starting from 90 w/ `i` set at 98.
Shaved off one byte by doing everything in base 15; decimal version below for slightly more clarity:
```
72 2:c101 3:c121 0:c33 1:c38si30[d27P91Pn109Pd4%;cP1+dli>P]dsPx98si90lPx
```
[Answer]
# J, 59 bytes
```
echo,(u:27 91),"1(16$'Hey!'),.~'m',.~,/30 90":@+/i.8
exit''
```
Save it as a script to run using J. It will print the output to stdout with the escaped colors.
[Answer]
# Octave, 78 bytes
```
c=[b=[a="\x1b[30m"' a a a;'Hey!'] b];c(4,:)+=0:7;d=c;d(3,:)+=6;disp([c d](:)')
```
Usage:
If the code is in a file `hey.m`:
```
$ octave hey.m
Hey!Hey!Hey!Hey!
```
[Answer]
## Pyke, 25 bytes
```
"Hey!"4*F\mo8.D6*3+"["s_
```
[Try it here!](http://pyke.catbus.co.uk/?code=%22Hey%21%224%2aF%5Cmo8.D6%2a3%2B%22%5B%1B%22s_)
```
- o = 0
"Hey!"4* - "Hey!Hey!Hey!Hey!"
F - for i in ^:
- stack = [i]
\m - stack.append("m")
o - o += 1
8.D - stack.extend(divmod(^, 8))
6*3+ - stack[-1] = stack[-1]*6+3
"[" - stack.append("[\x1b")
s - stack = sum(stack)
_ - stack = reverse(stack)
- print "".join(^)
```
[Answer]
# Python 3, 81 bytes
```
print(*['\33[%sm%s'%(i,'Hey!'[i%4-2])for i in range(30,98)if not 37<i<90],sep='')
```
A full program that prints to STDOUT.
**How it works**
```
for i in range(30,98)... For all possible colour codes i in [30,97]...
...if not 37<i<90 If i is in the desired range [30,37] or [90,97]...
'\33[%sm%s'%(i,'Hey!'[i%4-2]) ...create a string of the form
'\033[{colour code}m{current string character}'...
[...] ...and store all strings in a list X
print(*...,sep='') Print all strings in X with no separating space
```
[Try it on CodingGround](http://www.tutorialspoint.com/execute_python3_online.php?PID=0Bw_CjBb95KQMZ2UzdzNJOExCQjQ)
[Answer]
# SmileBASIC, 39 bytes
```
FOR I=0TO 15COLOR I?("Hey!"*4)[I];
NEXT
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~38~~ 41 bytes
Now returns right result too!
```
∊(⍕¨∊29 89∘.+⍳8){'\e[',⍺,'m',⍵}¨16⍴'Hey!'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdI7XS0AzI6NJ41Dv10Aogw8hSwcLyUccMPe1HvZstNKvVY1Kj1XUe9e7SUc8F0VtrD60wNHvUu0UdqFdRHWTIf7ApAA "APL (Dyalog Unicode) – Try It Online")
`16⍴'Hey!'` cyclically **r**eshape the string to length 16
`(`…`){`…`}¨` apply the below anonymous function to each letter pairing it with the corresponding element for this list as left argument:
`⍳8` 1 through 8
`29 89∘.+` addition table with these numbers vertically and those horizontally
`∊` **ϵ**nlist (flatten)
`⍕¨` format (stringify) each
`'m',⍵` prepend an "m"
`⍺,` prepend the left argument
`'\e[',` prepend the string
`∊` **ϵ**nlist (flatten)
[Answer]
# 4, 392 bytes
```
3.600486014960250603516045260553606546075560957610276119161318012111362072623336241062530021112402211255105115035005125205105115035015125215105115035025125225105115035035125235105115035045125205105115035055125215105115035065125225105115035075125235105115095005125205105115095015125215105115095025125225105115095035125235105115095045125205105115095055125215105115095065125225105115095075125234
```
[Try it online!](https://tio.run/##ZY5BDgMxCAN/VNmAnfL/h6XpHqpUXAAN0mhq73wZqLfBaiMEI0WjFIaUhlXGkozWMhFnsGkm32CQTAdWODLPVYRDCXw/UYizQyJE6rhxjlDgInwILxIPiYvkQ/IiNTwaHg/P@vf06OnR06OnR0@Pnh49PXr611N7fwA "4 – Try It Online")
Tip: [use the `-verb`ose flag](https://tio.run/##ZY5BDgJBCARfpOkGulc@5vfHcQ9mDBcgRVKpWiufBuplsNoIwUjRKIUhpWGVcUlG6zIRe7BpJl9gkEwHrnBk7qsIhxL4fqIQe4dEiNR2Yx@hwEF4Ex4kbhIHyZvkQWp4NDwenuvf06OnR0@Pnh49PXp69PTo6V9PrbUe7w8).
[Answer]
## [Perl 5](https://www.perl.org/), 50 bytes
**49 bytes code + 1 for `-p`. Note that `\x1b` is a literal escape character. Utilises empty input which TIO doesn't support, so a newline is provided and not used.**
```
$_="Hey!"x4;s/./\x1b[@{[(30..37,90..97)[$-++]]}m$&/g
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lbJI7VSUanCxLpYX09fOtqhOlrD2EBPz9hcxxJIWZprRqvoamvHxtbmqqjpp///z/Uvv6AkMz@v@L9uAQA "Perl 5 – Try It Online")
[Answer]
# PowerShell, 41 Bytes.
```
0..15|%{Write-Host -n('Hey!'[$_%4])-f $_}
```
The day we get an alias for Write-Host is a good day.
[](https://i.stack.imgur.com/Hw2UW.png)
[Answer]
# JavaScript 134 bytes
```
<script>
var a=0;
var c=["H","e","y","!"];
for(;a<3;){
var b=-1;
for(;++b<4;){
document.write(<b style='color:rgb(0,0,"+(a*4+b)+"'>"+c[b]);
}
}
</script>
```
Golfed
```
<script>a=0;c=["H","e","y","!"];for(;a++<3;){b=-1;for(;++b<4;){document.write(<b style='color:rgb(0,0,"+(a*4+b)+"'>"+c[b]);}}</script>
```
] |
[Question]
[
*You don't need to know these languages to participate. All necessary information has been provided in this question.*
You should write a program or function which given a [brainfuck (BF)](http://esolangs.org/wiki/Brainfuck) code as input outputs its [tinyBF](http://esolangs.org/wiki/TinyBF) equivalent.
BF has 8 instructions characters: `+-><[],.` and tinyBF has 4: `=+>|`. Converting works the following way: starting from the beginning of the BF code each symbol is replaced by on of its two tinyBF counterparts based on the number of `=` signs in the tinyBF code until that point (i.e. `=` behaves like a toggle switch).
The converter table (with columns: Brainfuck symbol; tinyBF symbol(s) when ther are even `=`'s before; tinyBF symbol(s) when ther are odd `=`'s before):
```
BF even odd
+ + =+
- =+ +
> > =>
< => >
[ | =|
] =| |
. == ==
, |=| =|=|
```
(This creates an almost unique tinyBF code. The only conflict occurs if the BF code contains a `[]` which is generally unused as it creates an infinite void loop.)
## Input
* An at least 1 byte long valid brainfuck program containing only the characters `+-><[],.`
* Guaranteed not to contain the string `[]`
* Trailing newline is optional.
## Output
* A tinyBF program.
* Trailing newline is optional.
## Examples
You can convert any BF program to tinyBF with [this (1440 byte long) converter](http://bataais.com/tinyBF.html) (see the Edit section for a small deviation).
```
Format is Input into Output
++- into ++=+
,[.,] into |=||==|=|=| or |=|=|==|=|| (both is acceptable check the Edit section)
>++.--.[<]+-, into >++===++===|=>|=+=+=|=|
>++-+++++++[<+++++++++>-]<. into >++=+=+++++++|=>=+++++++++>=+|>==
```
## Edit
As @Jakube pointed out in the official tinyBF converter in the equivalents of the `,` BF instruction (`|=|` and `=|=|`) the last `=` signs aren't counted towards the toggle state. Both the official and mine interpretations are acceptable but you have to choose one.
This is code-golf so the shortest entry wins.
[Answer]
# [Extended BrainFuck](http://sylwester.no/ebf/) 276 bytes
(not counting uneccesary linefeeds)
```
{a<<]>&c}{b<<-]<[->}{c]<]>[>[}{d 4+[-<}3>4->3->5->-->>&d 4+>]<[-<
4+<3+<4+<8+4>]<[<]<<,[>3+&d 6->]+<-[-[-[-[14-[--[>&d 6->]+<+[--[[
-]>[-&c>.&b>>.<.<+&a->>.<.&b>.<&a->>.>>.3<&b 4>.4<&a 4>.3<&b+>>.>
>.6<]>]<]>[-3>..3<&c 3>.<<&b+>>.>.3<&a>>.<.>.<.&b+>.>.<.<&a->>.>.
<<&b 3>.5<]>]<,]
```
How to compile and run:
```
beef ebf.bf < tinybf.ebf > tinybf.bf
beef tinybf.bf < source.bf > source.tbf
```
It will work with any wrapping BF interpreter that uses/support 0 as EOF.
Actual EBF source before golfing:
```
:i:f:o:p:e:a:g
$p ~"|=+>"<[<]@o
$i,( $f+++++++(-$i------)+$i-; +
($i-; ,
($i-; -
($i-; .
($i--------------; <
($i--; >
($f++++(-$i------)+$i+; [
($i--; ]
((-) $f(-) )
$f ( $o[$p.$f-]<[@f-$e.$p.$o+$i] ) ; ]
) $f ( $o[-$e.$p.$f-]<[@f-$p.$i] ) ; [
) $f ( $o[-$e.$g.$f-]<[@f-$g.$i] ) ; >
) $f ( $o[$g.$f-]<[@f-$o+$e.$g.$i] ) ; <
) $f (- $e.. ) ; .
) $f ( $o[$a.$f-]<[@f-$o+$e.$a.$i] ) ; -
) $f ( $o[$e.$p.$e.$p.$f-]<[@f-$o+$p.$e.$p.$i] ) ; ,
) $f ( $o[-$e.$a.$f-]<[@f-$a.$i] ) ; +
$i,)
```
# BrainFuck 404 bytes
This is the trimmed output of the compiled EBF.
```
>>>---->--->----->-->>++++[-<++++>]<[-<++++<+++<++++<++++++++>>>>]<
[<]<<,[>+++++++[-<------>]+<-[-[-[-[--------------[--[>++++[-<-----
->]+<+[--[[-]>[-]<]>[>[>.<<-]<[->>>.<.<+<<]>]<]>[>[->>.<.<<-]<[->>.
<<<]>]<]>[>[->>.>>.<<<<<-]<[->>>>>.<<<<<<]>]<]>[>[>>>>.<<<<<-]<[->+
>>.>>.<<<<<<]>]<]>[->>>..<<<]<]>[>[>>>.<<<<-]<[->+>>.>.<<<<<]>]<]>[
>[>>.<.>.<.<<-]<[->+>.>.<.<<<]>]<]>[>[->>.>.<<<<-]<[->>>>.<<<<<]>]<,]
```
[Answer]
# CJam, 50 bytes
```
l{"..+-><[],"#2mdT2$@T?:T=L'=?"== + > | |=|"S/@=}/
```
Try [one example](http://cjam.aditsu.net/#code=l%7B%22..%2B-%3E%3C%5B%5D%2C%22%232mdT2%24%40T%3F%3AT%3DL'%3D%3F%22%3D%3D%20%2B%20%3E%20%7C%20%7C%3D%7C%22S%2F%40%3D%7D%2F&input=%3E%2B%2B.--.%5B%3C%5D%2B-%2C) or [all of them](http://cjam.aditsu.net/#code=qN%25%7B0%3AT%3B%7B%22..%2B-%3E%3C%5B%5D%2C%22%232mdT2%24%40T%3F%3AT%3DL'%3D%3F%22%3D%3D%20%2B%20%3E%20%7C%20%7C%3D%7C%22S%2F%40%3D%7D%2F%5DoNo%7D%2F&input=%2B%2B-%0A%2C%5B.%2C%5D%0A%3E%2B%2B.--.%5B%3C%5D%2B-%2C%0A%3E%2B%2B-%2B%2B%2B%2B%2B%2B%2B%5B%3C%2B%2B%2B%2B%2B%2B%2B%2B%2B%3E-%5D%3C.) online.
### Explanation
The magic is in the mapping! Looking up each operator's index in a carefully ordered yet simple string produces three useful pieces of information at once: whether the operator is directionless (index == 0), the direction the operator requires (index mod 2), and the index of the output operator (index / 2).
Using that handy mapping, it's a simple case of looping through each input operator and producing a direction swap operator if the direction needs to be changed, updating the direction, and producing the output operator.
```
l "Read a line of input.";
{ "For each character of input:";
"..+-><[],"# "Map the character:
'.' -> 0 |
'+' -> 2 | '-' -> 3
'>' -> 4 | '<' -> 5
'[' -> 6 | ']' -> 7
',' -> 8 | ";
2md "Calculate the quotient and remainder of the mapping
divided by 2.";
T2$@T?:T "If the the mapping is nonzero (not '.'), set the
direction after this operator to the remainder above.
Otherwise ('.'), don't change the direction.";
=L'=? "If the direction before this operator is equal to the
direction after, produce an empty string. Otherwise,
produce the direction switch operator, '='.";
"== + > | |=|"S/@= "Map the previous mapping divided by 2 to an operator:
0 ('.') -> '=='
1 ('+', '-') -> '+'
2 ('>', '<') -> '>'
3 ('[', ']') -> '|'
4 (',') -> '|=|' ";
}/
```
[Answer]
# TinyBF\*\*\*, 558 bytes
Don't credit me for this, this is the TinyBF version of @Sylwester's BrainF\*\*\* answer (I used his code to convert his code into this code, :P). I just felt the need to put this answer up.
```
>>>=++++=>=+++=>=+++++=>=++=>>++++|=+>=++++>=|>=|=+>=++++=>=+++=>=++++=>=+++++++
+>>>>=|>=|=>|>>=|=|=|>+++++++|=+>++++++=>=|=+=>+=|=+=|=+=|=+=|=++++++++++++++=|=
++=|>++++|=+>++++++=>=|=+=>=+|=++=||=+|=>|=+|>|=>|>|>===>>+|>=|=+=>>>===>==>=+=>
>|=>=|>|=>|>|=+=>>===>==>>+|>=|=+=>>===>>>|=>=|>|=>|>|=+=>>==>>===>>>>>+|>=|=+=>
>>>>===>>>>>>|=>=|>|=>|>|>>>>===>>>>>+|>=|=+=>+>>==>>===>>>>>>|=>=|>|=>|=+=>>>==
===>>>|>|=>|>|>>>===>>>>+|>=|=+=>+>>==>===>>>>>|=>=|>|=>|>|>>===>===>===>==>>+|>
=|=+=>+>==>===>==>>>|=>=|>|=>|>|=+=>>==>===>>>>+|>=|=+=>>>>===>>>>>|=>=|>=|=||
```
[Answer]
# Perl, ~~244~~ ~~241~~ ~~226~~ 217 bytes
```
open(B,$ARGV[0]);%e=qw(+ + - =+ > > < => [ | ] =| . == , |=|);%o=qw(+ =+ - + > => < > [ =| ] | . == , =|=|);$q=0;while(<B>){$p='';@c=split('');foreach$c(@c){if($q%2>0){$p.=$o{$c}}else{$p.=$e{$c};}$q=$p=~/=/g;}print$p}
```
Works on all cases. Run with `perl file.pl [filename]` where `file.pl` is the name of the program, and `[filename]` is the name of the BF file.
**Changes**
* Saved 3 bytes by using `split('')` instead of `split('',$_)`.
* Saved 15 bytes by:
+ Getting rid of `$f=` in front of open (3 bytes)
+ Replacing `if($eo%2==1)` with `if($eo%2>0)` (1 byte)
+ Replacing `$p=$p.` with `$p.=` (2 bytes \* 2 times = 4 bytes)
+ Removing trailing newline, as it was optional (5 bytes)
+ Removed `=()` (3 bytes)
* Saved 9 bytes by shortening variable names.
[Answer]
# K, 91 bytes
```
o:0;{:[i:"..+-><[],"?x;t:i!2;t:0];`0::[o=t;"";"="],("==";"+";">";"|";"|=|")@i%2;o::t}',/0:`
```
It's more-or-less a direct port of @Runer112's CJam answer. And it's much longer. Life sucks.
[Answer]
# JavaScript (ES6), 129 bytes
```
b=>[...b].map(x=>p+="=+,+,=>,>,=|,|,==,=|=|,+,=+,>,=>,|,=|,==,|=|".split`,`["+-><[].,".indexOf(x)+p.split`=`.length%2*8],p="")&&p
```
Uses an array of the 16 possibilities (8 characters times 2 parities), and indexes into this. The array is built by splitting a string, which saves 26 bytes over an array.
[Answer]
# Ruby, ~~233~~ 217 bytes
```
p,m,g,l,b,s,d,a,q,f=%w(+ - > < [ ] . , | =)
z=[{p=>p,m=>f+p,g=>g,l=>f+g,b=>q,s=>f+q,d=>f+f,a=>q+f+q},{p=>f+p,m=>p,g=>f+g,l=>g,b=>f+q,s=>q,d=>f+f,a=>f+q+f+q}]
i=0
ARGV[0].each_char{|c|v=z[i%2][c];print v;i+=v.count(f)}
```
An 8-byte improvement on the previous non-esoteric answers!
Saved 16 bytes with the [`%w()` syntax](https://ruby-doc.org/core-2.5.1/doc/syntax/literals_rdoc.html#label-Percent+Strings)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 101 bytes
```
->s{t="";s.chars{|c|t<<((t.count(?=)+i="..+-><[],".index(c))%2<1&&i>0?"":?=)+%w(= + > | |=|)[i/2]};t}
```
[Try it online!](https://tio.run/##XU7BasMwDL3vK4RHi4Nib@txtdzTvsL4kLguMRtJiR22UffbsySlW9h7ICQ96Un9UH@PJxqFjpdEjO2jdE3Vx0t2OSnFeZKuG9rED1RgICYlCq2MLZkM7dF/cVcUm5162W6Dfj4w9jrPbT45AYKGDJlyYcLTzl736TqehxThZBiiYPYRILSpA0AkfLhLpZGlXYmTQSbKM6HrYUmWOgOvu9RAiFA558@pqj88uMa7d0iNh7djSBC9S6Fri197jSiFkEZZFOXqzNQnoiVk0pmml@Yj6z2BNxiFd2hhlfznMvGGyYf@JgmzJhp/AA "Ruby – Try It Online")
Uses the second interpretation of the ambiguous `,` translation rule.
] |
[Question]
[
Given an alphabet and a string, your job is to create the
[Lempel–Ziv–Welch compression](http://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch) of the string. Your implementation can either be a function with
two parameters and a return value, or a full program that uses stdin and
stdout.
## Input
* **The alphabet**, in the form of a string, from which you will have to create
the initial dictionary: Each character should be mapped to its index in the
string, where the first index is 0. You will be expanding this dictionary as
you iterate through the algorithm.
* **The string** to be compressed.
## Output
* **The compressed string** in the form of dictionary keys. This must be an array of
integers if you're creating a function, or printed integers separated by either
whitespace or newline (and nothing else) if you're making a full program.
## Algorithm
After you have initialized the dictionary, the algorithm goes something like this:
* Find the longest string *W* in the dictionary that matches the current input.
* Emit the dictionary index for *W* to output and remove *W* from the input.
* Add *W* followed by the next symbol in the input to the dictionary.
* Repeat
## Examples
```
"ABC", "AABAACABBA" ==> [0,0,1,3,2,4,5]
"be torn", "to be or not to be" ==> [3,4,2,0,1,2,4,5,2,6,4,3,2,7,9,1]
```
## Rules
* No use of external resources
* No predefined built-in functions or libraries of any kind that solves the problem for you.
* Fore!
[Answer]
## GolfScript (52 51 chars)
```
{[\1/\{\.{.,3$<=},-1=.2$?@@,:L)[3$<]+@L>.}do;;]}:C;
```
[Online demo](http://golfscript.apphb.com/?c=e1tcMS9ce1wuey4sMyQ8PX0sLTE9LjIkP0BALDpMKVszJDxdK0BMPi59ZG87O119OkM7CiJBQkMiICJBQUJBQUNBQkJBIiBDIHAKImJlIHRvcm4iICJ0byBiZSBvciBub3QgdG8gYmUiIEMgcA%3D%3D)
### Dissection
```
{ }:C;
```
is standard function boilerplate.
```
# Wrap the values we compute in an array
[
# Stack: alphabet uncompressed-string
# Split the alphabet from a string into an array of 1-char strings
\1/\
# Stack: dictionary uncompressed-string
{
# Stack: ... dictionary uncompressed-string-suffix
# Find the dictionary elements which are prefixes of uncompressed-string-suffix
\.{.,3$<=},
# The last of them must be the longest by construction
-1=
# Stack: ... uncompressed-string-suffix dictionary prefix
# Find the index of prefix in dictionary
.2$?
# Stack: ... uncompressed-string-suffix dictionary prefix index
# Push index down the stack
@@
# Stack: ... uncompressed-string-suffix index dictionary prefix
# Assign len(prefix) to L and append a 1-char-longer prefix to dictionary
,:L)[3$<]+
# Fetch up the uncompressed-string-suffix and chop off the first L chars
@L>
# Stack: ... index dictionary' uncompressed-string-suffix'
# Duplicate uncompressed-string-suffix' for the do-loop condition test
.
}do
# Stack: index0 index1 ... indexN dictionary' ""
# Pop the last two to leave just the indexes
;;
]
```
[Answer]
# Python (141 Characters)
```
def a(b,c,r=[]):
if c:l,i,d=max((len(d),i,d) for i,d in enumerate(b) if c.find(d)==0)
return a(list(b)+[c[:l+1]],c[l:],r+[i]) if c else r
```
Not golfed very small, but no chance of beating any of the golfscript solutions anyway.
[Answer]
# Racket/R5RS Scheme: 359 bytes
```
(define(l d i)(let*((h(make-hash))(s string->list)(r(λ(x)(hash-ref h x #f)))(i(s i))(s(let l((s 0)(d(s d)))(if(null? d)s
(and(hash-set! h(car d)s)(l(+ s 1)(cdr d)))))))(let l((i(cdr i))(c(r(car i)))(o'())(s s))(if(null? i)(reverse(cons c o))
(let*((q(cons(car i)c))(n(r q)))(if n(l(cdr i) n o s)(and(hash-set! h q s)(l(cdr i)(r(car i))(cons c o)(+ s 1)))))))))
```
Usage:
```
(l "ABC" "AABAACABBA") ; ==> (0 0 1 3 2 4 5)
(l "be torn" "to be or not to be") ; ==> (3 4 2 0 1 2 4 5 2 6 4 3 2 7 9 1)
```
[Answer]
## PHP 220
implemented as a function
```
<? function l($d,$s){@$n=strlen;@$r=substr;$d=str_split($d);$o=[];while($s){$l=0;foreach($d as$k=>$v){$b=$n($v);if($b<=$n($s)&&!strncmp($s,$v,$b)&&$b>$l){$l=$b;$i=$k;}}$o[]=$i;$d[]=$r($s,0,$l+1);$s=$r($s,$l);}return $o;}
```
[Answer]
# PHP: 176
Just making it return a function would require one byte less. It utilizes PHP arrays (`$d`)as [Trie trees](http://en.wikipedia.org/wiki/Trie):
```
<? function l($d,$s){@$S=str_split;$o=[];$d=array_flip($S($d));foreach($S($s)AS$v){if(null===$t=@$d[$c.$v]){$d[$c.$v]=count($d);$o[]=$c;$c=$d[$v];}else$c=$t;}$o[]=$c;return$o;}
```
Usage:
```
print_r(l("ABC","AABAACABBA")) ; ==> array(0, 0, 1, 3, 2, 4, 5)
```
[Answer]
## **Perl, ~~188~~ ~~177~~ ~~156~~ ~~145~~ ~~137~~ 112**
```
sub l{($_,$s,@o)=@_;@d=split'';while($s){$s=~s/^$d[$_](.?)/push@o,$_;push@d,$&;$1/e&&last for reverse 0..$#d}@o}
```
i.e.
```
sub l {
($_,$s,@o)=@_;
@d=split'';
while($s){
$s=~s/^$d[$_](.?)/push@o,$_;push@d,$&;$1/e
&& last for reverse 0..$#d
}
@o
}
```
Can be **109** if global `@o` is expected undefined or empty when entering sub. And yes, global variables are modified. Below is properly un-golfed version with lexicals.
```
use strict;
use warnings;
sub lzw {
my ($alphabet, $string, @out) = @_;
my @dict = split '', $alphabet;
LOOP: while ($string) {
for my $k (reverse 0..$#dict) {
if ($string =~ s/^$dict[$k](.?)/$1/) {
push @out, $k;
push @dict, $&;
next LOOP
}
}
die "we shouldn't be here!\n"
}
return @out
}
print qq/@{[lzw("ABC", "AABAACABBA")]}\n/;
print qq/@{[lzw("be torn", "to be or not to be")]}\n/;
```
.
```
perl lzw.pl
0 0 1 3 2 4 5
3 4 2 0 1 2 4 5 2 6 4 3 2 7 9 1
```
[Answer]
# SWI-Prolog, ~~313~~ 244
The list of alphabet is no longer reversed. And it uses `nth0` to brute force index + prefix pair.
```
b([],[]).
b([H|T],[[H]|R]):-b(T,R).
l(A,W,O):-b(A,B),r(B,W,O).
r(A,W,[I|T]):-m(A,W,I,E,0),append(E,R,W),(R=[N|_],!,append(E,[N],C),append(A,[C],B),r(B,R,T);T=[]).
m(A,W,I,E,N):-nth0(J,A,F),prefix(F,W),length(F,L),L>N,!,(m(A,W,I,E,L),!;I=J,E=F).
```
Usage:
```
l("be torn", "to be or not to be",O).
O = [3,4,2,0,1,2,4,5,2,6,4,3,2,7,9,1].
```
### Old version
**313 chars**
Working on a reversed list of alphabet, which is convenient when I need to add new alphabet, but it is more roundabout to get the index.
This should do less work than the 244 chars version, but more code.
```
b([],O,O).
b([H|T],O,A):-b(T,O,[[H]|A]).
l(A,W,O):-b(A,B,[]),r(B,W,O).
r(A,W,[I|T]):-m(A,W,I,E,_),I>=0,append(E,R,W),(R=[N|_],!,append(E,[N],C),r([C|A],R,T);T=[]).
m([],_,-1,_,0).
m([H|T],W,I,E,M):-prefix(H,W),!,length(H,L),m(T,W,J,F,N),(N>L,!,M=N,I=J,E=F;M=L,length(T,D),I=D,E=H).
m([_|T],W,I,E,M):-m(T,W,I,E,M).
```
[Answer]
# [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), 245 bytes
Golfed version. [Try it online!](https://tio.run/##XY9dS8MwFIbv/RU1V0ozZm/NUpoWL0QFP4pehDBictYEt2QkESZj/es1ExX08v3gPc/ZyGRgI5NVcppWXC5xXIpLeqYpi9ErmxPvehNAat4ZGaRKEGIjZ/WjdAPwC/yUgnXDLbghmexXQpBA9wdiaUUURYi8GLsGbhf0TzNi82308g14xHt7EMRRtagNuV5xPd7Ax9XOxhQfRocVdTiMbLsFp3s/6kaRH0DoPdfYzeo7uePPcv0OsdGirEQ@bwSxZSmOg@o0w/zbyKjn@WvE2g7hAjHWMtaxtmVIzOf3GS6d5PQViuSDOzaSL7LyoXA@FV/itzl9Ag)
```
f[a_,s_]:=(d=AssociationThread[Characters@a->Range[0,StringLength@a-1]];r={};i=1;c="";While[i<=StringLength@s,h=StringTake[s,{i}];n=c<>h;If[d~KeyExistsQ~n,c=n,r~AppendTo~d@c;AssociateTo[d,n->Max[Values@d]+1];c=h];i++];If[c!="",r~AppendTo~d@c];r)
```
Ungolfed version. [Try it online!](https://tio.run/##hVNta9tADP6eX6Hl09a4dPm6NAUnFDbWwl7CCjPHUG01Pubcmbvzmi7kt2e68zl2Q8uMsa2T9OjRI3mDrqQNOpnj4XDz826pN7UhazOs6hLvyf367oxU6wSkqpvOEvBhDre6aCrKRgC7QuYugbwxhhR/KNryk2Gait@SPeU@4Ti@357BJyWdxEr@JeDa4HOlVmie4FG6Mpx1xeHsHef4CJhDaq3OJfrgVWkIi2xZosHckenpCji/gm@o1pS9T6Ble0Nq7co@5HwqxIxxW4KMvNt7M9Jnezz2tuSv6aylfVdKblXC5fw5ZhBF@N44v4TOu8Lf1PoS2Ml9qAZBFg7p6lxecUrrCQ8vzUNoX9Ej2AAEtJXWWRb/RKsEmrpA10rYIcacIBowWPaZnq4DwNesHZGnEOkOGw4Di6fxxWyuK0sJYF2TKk5H9QerhkA/vFTf6XAa5x/x@MKiOG0vhg77Qi7GqTz811sDSAOrlc66LfMQWYwWUXA47gxxZK@A35Fb3GY/fBM2OISYTI9ZvTDdgMRgTnIy8ZaYHTf6I3Ou2lFUaB3T36BUnu@QNs@jA37jdyz5XxNdhdY7YnM0Gv6i43SxZJRxmi7SdJkuFulYwMXFFy7pngfeMzltlA9mxdnSBpR2EIw@6XD4Bw)
```
LZWCompress[alphabet_String, input_String] := Module[
{dict, current, next, result, i, ch},
(* Initialize the dictionary with the alphabet *)
dict = AssociationThread[Characters[alphabet] -> Range[0, StringLength[alphabet]-1]];
result = {};
current = "";
i = 1;
While[i <= StringLength[input],
ch = StringTake[input, {i}];
next = current <> ch;
(* If the new string exists in the dictionary, update the current string *)
If[KeyExistsQ[dict, next],
current = next,
(* Else, append the dictionary value of the current string to the result,
add the new string to the dictionary, and reset the current string *)
AppendTo[result, dict[current]];
AssociateTo[dict, next -> Max[Values[dict]]+1];
current = ch;
];
i++;
];
(* Handle the last remaining string *)
If[current != "", AppendTo[result, dict[current]]];
result
];
LZWCompress["ABC", "AABAACABBA"] //Print
LZWCompress["be torn", "to be or not to be"] //Print
```
[Answer]
### GolfScript, 53 characters
```
n%~\1/\{.,,{)1$<2$?}%{)},-1=.p@.@=,:^)2$[<]+\^>.}do;;
```
The input must be given as two lines, first alphabet, second string to compress. The second example can be tested [online](http://golfscript.apphb.com/?c=ImJlIHRvcm4KdG8gYmUgb3Igbm90IHRvIGJlIgoKbiV%2BXDEvXHsuLCx7KTEkPDIkP30leyl9LC0xPS5wQC5APSw6XikyJFs8XStcXj4ufWRvOzsKCg%3D%3D&run=true).
[Answer]
## **Postscript, ~~388~~ 267**
It's my Perl answer re-written, just for fun:
```
/lzw {
10 dict begin
/str exch def
/alphabet exch def
/concat
{dup length 2 index length add string dup dup 4 index length
5 -1 roll putinterval 0 4 -1 roll putinterval}
def
/push
{1 index load dup length /_n exch def
[exch aload pop _n 2 add -1 roll]def}
def
/dict [-1 alphabet length {
1 add dup alphabet exch 1 getinterval exch
} repeat pop] def
[
{
str length 0 eq {exit} if
dict length dup {
1 sub dup
dict exch get
str exch anchorsearch
{
1 index
dup length 0 ne {0 1 getinterval} if concat
/dict exch push
/str exch def
exit
} {pop} ifelse
} repeat
} loop
]
end
} def
(ABC)(AABAACABBA) lzw
{10 string cvs print( )print} forall
(\n)print
(be torn)(to be or not to be) lzw
{10 string cvs print( )print} forall
```
and
```
gs -dBATCH -q lzw.ps
0 0 1 3 2 4 5
3 4 2 0 1 2 4 5 2 6 4 3 2 7 9 1
```
Procedure expects 2 strings on stack and returns an array. Not sure about quality of my Postscript, but with little help of 'binarization' (binary tokens), compression (LZW 4 bytes more efficient than Deflate) and encoding, it can be golfed to something like that:
```
/l<~J.+mR+f\'O00,h`aW[%a_[;,+b\+;Ei?VkM,`<7VO9Ho+MT&&IW4:>B/Jt:Fkp+9b5W"\IAS74n7,WEV`lsSZ&A6g1)4'7^,a$SAD@f9&15SkO))[/:$Z^e$4N0:?`F7fk8MV#<6.'Dr'AOkP"!5De'2kXm`>,I(@^ERI/e\Tneg#0M3_7tOQWJ$Y0n%F-#bWHFEC6hWX'hBaBu?;D~>/LZWDecode filter 500 string readstring pop cvx def
```
And that's **267** bytes procedure of pure ASCII code -- still not the longest of the answers :-)
[Answer]
# [Extended BrainFuck](http://sylwester.no/ebf/): 490 bytes
I know I won't win here, but I love compression algorithms. It was fun writing, not too difficult and shorter than I imagined :)
```
{l[>>]}{k[<<]}{j&k +&l }{i]>>[-<<+>>]}{h,10-[22-[-}{g&k>>[->>]}{f>]3<[-3>+3<]}{e>+3>&l+<<&k}{d&k>[-3<+4>&l}{c 48+[-<+<+>>]<[.[-]<]10+.[-]}{a 10+<[->-[>+>>]>[+[-<+>]>+>>]5<]>[-]}{b 5<&k&f>>&g}192>&h 4<&j>>]<[-3<&k>+>&l>>+<]3<&g>>+[-<+>],10-]<[-<+>]<[->+>+<<]3>,32-[-5<&j 3>]5<&d 3>+&b 4>&h 6<&j 4>]<5<&d 4>+<&b>[-<+3>[->&e 3<&i 4<]<[->+<]4>+[-&e<<]>-[-<+>]3>&l<[-3>+4<&k<+3>&l<]3>[-3<+3>]4<&k+<[<<[-&i>-<]>[-<<[-4<+4>]4>-4<&a 4>+<&c<<[->+5>&l<+<&k 4<]>+[-<+&f 6>]>>&l<<[-<<]<<[-],10-]&a 3>&c
```
Usage:
```
$ bf ebf.bf < lzw.ebf > lzw.bf
$ bf lzw.bf <<eof
> ABC
> AABAACABBA
> eof
00
00
01
03
02
04
05
```
To support codes above 99 I need to add a stack structure. Doable, but since both test cases don't even use the second digit I though I'd stop here.
Here's the resulting BrainFuck code (1096):
```
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>,----------[----------------------[-<<<<[<<]+[>>
]>>]<[-<<<[<<]>+>[>>]>>+<]<<<[<<]>>[->>]>>+[-<+>],----------]<[-<+>]<[->+>+<<]>>
>,--------------------------------[-<<<<<[<<]+[>>]>>>]<<<<<[<<]>[-<<<+>>>>[>>]>>
>+<<<<<[<<]>]<<<[->>>+<<<]>>[<<]>>[->>]>>>>,----------[----------------------[-<
<<<<<[<<]+[>>]>>>>]<<<<<<[<<]>[-<<<+>>>>[>>]>>>>+<<<<<<[<<]>]<<<[->>>+<<<]>>[<<]
>>[->>]>[-<+>>>[->>+>>>[>>]+<<[<<]<<<]>>[-<<+>>]<<<<]<[->+<]>>>>+[->+>>>[>>]+<<[
<<]<<]>-[-<+>]>>>[>>]<[->>>+<<<<[<<]<+>>>[>>]<]>>>[-<<<+>>>]<<<<[<<]+<[<<[-]>>[-
<<+>>]>-<]>[-<<[-<<<<+>>>>]>>>>-<<<<++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-
]>>>>+<++++++++++++++++++++++++++++++++++++++++++++++++[-<+<+>>]<[.[-]<]++++++++
++.[-]<<[->+>>>>>[>>]<+<[<<]<<<<]>+[-<+>]<<<[->>>+<<<]>>>>>>]>>[>>]<<[-<<]<<[-],
----------]++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>>+++++++++++++++++++++
+++++++++++++++++++++++++++[-<+<+>>]<[.[-]<]++++++++++.[-]
```
Keep in mind that I have aimed for short EBF code, not BF code.
Here's the ungolfed EBF source code source code (3,5kB):
```
;; The data type for the lookup array
:lc the crumble for lookup array
:lv the value for this byte
:lz always zero
;; macros for lookup
;; move to open area
{to_lookup $lc(@lz)}
;; move back
{from_lookup $lz(@lc)}
{open_lookup (- &to_lookup+
@lz &from_lookup)
}
{close_lookup &to_lookup
$lz(-@lc)
}
;; makes a move to a higher
;; crumble and increments it
{lookup_backup
$lc@lz
$lc+$lz@lc
}
;; restore backup
{lookup_restore
$lc@lz
$lc(-$lz@lc^0+$lc@lz)
$lz@lc
}
;; opens the lookup with the
;; index of the current register
;; and replaces it with the
;; code representing that
{lookup_value
&open_lookup
&to_lookup
$lv(- &lookup_backup
&from_lookup
^0+
&to_lookup)
&lookup_restore
&close_lookup
}
;; We have a possible alphabet of ASCII 32-126=94 and
;; we need an empty as well * 2 slots/element = 190
190> @lz
;; The variables we use
:lec lookup element count
:ndv next dictionary value
:prev previos match
:cur current index
:ax general purpose register a
;; The trie tree data structure
:tz the empty element
:tv the value of this node
:tc the crumble of this node
;; macros for the trie structure
{to_trie $tc(@tz)}
{from_trie $tz(@tc)}
;; makes a move to a higher
;; crumble and increments it
{trie_backup
$tc@tz
$tc+$tz@tc
}
;; restore backup
{trie_restore
$tc@tz
$tc(-$tz@tc^0+$tc@tz)
$tz@tc
}
{open_trie
;; we take prev times lec first
;; we use %lz as temporary for lec
;; and
$lec(-
$lz+ ; backup lec
$prev(-
$ax+ ; backup prev
&to_trie+
&from_trie
)
$ax(-$prev+) ; restore backup
)
$lz(-$lec+) ; restore lec
$cur+(-
$ax+
&to_trie+
&from_trie)
$ax-(-$cur+)
}
{trie_close &to_trie $tz(-@tc)}
;; divmod divides ^0 with ^1
;; leaving remainder in ^2
;; and quotient in ^3
;; Needs up to ^5 for working area
{divmod
(-^1-
[^2+^4]
^5[*-3+[-^1+^2]^3+^5])
}
;; First we need to fill our lookup
;; we'll use ndv
$ndv,10-
( ; while not lf
22-
&open_lookup
$lec(- &to_lookup $lv+
&from_lookup $ndv+)
&close_lookup
$ndv+(-$lec+)
%ndv , 10-
)
;; Now that we have all symbols we make a copy
$lec(-$lz+)
$lz(-$lec+$ndv+)
#
$prev, 32- &lookup_value
$cur, 10-
(
22-
#&lookup_value
#
&open_trie
;; somehow if tv is we copy it to ax and reset prev
;; if prev is set we copy it to tv and
&to_trie
$tv(-
&trie_backup
&from_trie
$ax+
&to_trie
)
&trie_restore
&from_trie
$tz+
$ax( $prev(-)$ax(-$prev+)$tz-)
$tz(-
$cur(-$lz+) ; make copy of cur
$tc-
$cur 10+ $prev &divmod
$cur(-)
$tc+
$tv 48+(-$tz+$ax+)
$tz[.(-)<]@cur
10+.(-)
$ndv(- $prev+
&to_trie $tv+
&from_trie
)
$prev+(-$ndv+)
$lz(-$prev+)
)
&trie_close
$cur(-), 10-
)
#$cur 10+ $prev &divmod
$cur(-)
$tv 48+(-$tz+$ax+)
$tz[.(-)<]@cur
10+.(-)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 104 bytes
Only lightly golfed. Very similar to [user2846289's Perl solution](https://codegolf.stackexchange.com/a/20325/11261). I'm not sure why this straightforward challenge saw so few attempts; maybe we can revive it.
```
->a,s,*o{d=a.chars
(d.size-1).downto(0){(o<<_1
d<<$&
break)if s.gsub! /^#{d[_1]}(.?)/,'\1'}while s[0]
o}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY1BCoJAFED3c4qfSY6hk-5ajLXzEmYyNppS-GNmREo8SRuJOlS3KbLV48GDd3-qNr-Ojzh6tab01-_K3whPe0vsZSTYoRJKEyqZrm-FH7pMYtcYpIHbU-Q8C4nk3F6QXBXi5NYlaHbUbT6D1X7eyyQL04GyrbvynF3oDF1VnwvQSZASHP4_-wJxYuUFGFSN5YFlEL6GCho08BMrndpxnPgB)
] |
[Question]
[
*Related: [Sort these bond ratings](https://codegolf.stackexchange.com/q/71723/73593)*
[Credit rating agencies](https://en.wikipedia.org/wiki/Credit_rating_agency) assign ratings to bonds according to the credit-worthiness of the issuer.
The rating business is mostly controlled by ["Big Three" credit rating agencies](https://en.wikipedia.org/wiki/Big_Three_(credit_rating_agencies)) (i.e. [Fitch Ratings](https://en.wikipedia.org/wiki/Fitch_Group), [Moody's](https://en.wikipedia.org/wiki/Moody%27s), and [Standard & Poor's (S&P)](https://en.wikipedia.org/wiki/Standard_%26_Poor%27s)), which use a similar [tiered rating system](https://en.wikipedia.org/wiki/Bond_credit_rating#Rating_tier_definitions).
## Task
For this challenge, we will consider only long-term non in-default tiers of two rating formats, Moody's and Fitch/S&P. NA-style ratings such as `NR` or `WR` will not be included.
Your task is to design a program or function that takes as input a rating tier in one of the two format and outputs the equivalent tier in the other format. Your program must support both formats in input and output, i.e. your program cannot be able only to convert from Moody's to Fitch/S&P or vice versa.
**Edit**: your program may output trailing whitepaces.
The following table shows the tier pairs.
```
Moody's Fitch/S&P
------- ---------
Aaa AAA
Aa1 AA+
Aa2 AA
Aa3 AA-
A1 A+
A2 A
A3 A-
Baa1 BBB+
Baa2 BBB
Baa3 BBB-
Ba1 BB+
Ba2 BB
Ba3 BB-
B1 B+
B2 B
B3 B-
Caa CCC
Ca CC
Ca C
```
#### Notes
* there are no tiers in the two formats that are identical;
* for each rating tier (except `Ca`) there is one (and only one) equivalent tier in the other format;
* `Ca` is equivalent to either `CC` or `C`, depending on the specific case;
+ when your program takes as input `Ca`, it must output either `CC` or `C` indifferently;
+ your program must output `Ca` when the input is `CC` or `C`.
## Rules and scoring
This is code golf, so lowest byte count wins, standard loopholes disallowed.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 36 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Assumes that we may use ASCII only input (so `-` rather than the similarly looking `−` used in the post) and that "indifferently" is being used to mean either/or (here `Ca` produces `CC` only).
```
;⁼¡“C”Ḣð;“13-+a”,Ṛ$y⁹⁸;;ḟẇ“¶®O^»$?”2
```
A monadic Link that accepts a list of characters (one of the ratings) and outputs the equivalent rating from the other agency.
**[Try it online!](https://tio.run/##HYsxDoJAEEX7OQUFjQEKoNyo2d3E1trGZAsbwgXooOIORmP0AMZCDYjVcpLdi6x/TPbPf//PTnWo6yYE4buvvfr2pH17dsNtfgiEvMwSgyJ14zFufDf6bhDCDRf36bG2b3vf7u0Ur/GnCG562tcmnfsKu2i5itAudiEK0hiSJocKqCQJBJWkDFqMggdHThzAQFBJGsca91JCCf0tIyaCK6USHixOHOiPIIJrrYnfDw "Jelly – Try It Online")**
### How?
```
;⁼¡“C”Ḣð;“13-+a”,Ṛ$y⁹⁸;;ḟẇ“¶®O^»$?”2 - Link: list of characters, R
“C” - set the right argument to ['C']
¡ - repeat...
⁼ - ...times: is {R} equal to {['C']}?
; - ...action: {R} concatenate {['C']}
-> R="C" becomes "CC" others unaffected
Ḣ - head
ð - start a new dyadic chain - f(Head, say 'H', Rest)
;“13-+a” - {Head} concatenate "13-+a"
,Ṛ$ - pair with its reverse -> ["H13-+a","a+-31H"]
y⁹ - translate {Rest} using {that mapping}
⁸; - left arg {=Head} concatenate {translated Rest}
”2 - set the right argument to '2'
? - if...
ẇ“¶®O^»$ - ...condition: is sublist of "AaBaa"?
; - ...then: concatenate {'2'}
ḟ - ...else: filter discard {'2'}
```
[Answer]
# Google Sheets, 168 bytes
`iferror(find())` by [JvdV](https://codegolf.stackexchange.com/users/100057/jvdv), **168 bytes**:
```
=let(b,left(A1),c,right(A1),f,len(split(A1,"123+-")),iferror(rept(b,f)&mid("+-",find(c,"132a"),1),b&rept("a",f-1+(A1="C"))&rept(mid(1223,find(c,"+AB-C"),1),A1<>"AAA")))
```
Brute force `hlookup()`, **217 bytes**:
```
=let(m,split("Aaa0Aa10Aa20Aa30A10A20A30Baa10Baa20Baa30Ba10Ba20Ba30B10B20B30Caa0Ca0Ca",0),f,split("AAA0AA+0AA0AA-0A+0A0A-0BBB+0BBB0BBB-0BB+0BB0BB-0B+0B0B-0CCC0CC0C",0),ifna(hlookup(A1,{m;f},2,0),hlookup(A1,{f;m},2,0)))
```
`regexextract()` and `regexmatch()`, **221 bytes**:
```
=let(a,regexextract(A1,"[A-c]+"),c,left(a)&rept("a",len(a)-1)&switch(right(A1),"+","1","-","3",),if(regexmatch(A1,"[a-c\d]"),rept(left(a),len(a))&switch(right(A1),"1","+","3","-",),c&if(regexmatch(c,"^(Aa?|Ba?a?)$"),2,)))
```
Convoluted arrays of regexes applied two ways, **298 bytes**:
```
=let(r,lambda(a,b,reduce(A1,sequence(rows(a)),lambda(t,i,regexreplace(t,index(a,i),index(b,i))))),a,{"Baa";"Ba";"Caa";"Ca";"1";"2";"3";"$12";"Ca"},b,{"BBB";"BB";"CCC";"^C$";"\+";"ø";"-";"^(AA?|Ba?a?)$";"^CC$"},regexreplace(if(regexmatch(A1,"[a-c\d]"),upper(r(a,b)),proper(r(b,a))),"\\|Ø|\^|\$",""))
```
Put the rating in cell `A1` and the formula in cell `B1`.
[Answer]
# JavaScript (ES6), 91 bytes
*-1 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)*
*-4 thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)*
The output may contain a trailing space.
```
([o,...a],s=o+` +-a213`)=>"C"+a.map(c=>o+=s[s.indexOf(c)^4])<s?"Ca":/^A?$|B$/.test(a)?o+2:o
```
[Try it online!](https://tio.run/##VZFBbtswEEX3PsWACGASFBlYajZOZMMjZN0DCApCyHbiIDFVyygKtL1BgW66TO6R8@QCOYJDUVNkuBGBp6@h3p8H99317WHXHc3erzenbXmStc@sta7J@tLrW9DG5bPiVpULUQnt7JPrZFsuvC77ure7/Xrz4@tWturmS6Ou@qWonJif36yWZ7/w7NweN/1ROrX0Op/702U9AahBrJwTGYRztRIATfafzojqhOZEA2S0IGp4Ng4Ip06yOdEBftKCqOFZdPEnBCKGGYzmREWSLYganh0t4gBGc6LpbQVRboFkgYkFkgUmFkgWmFhU1G9VVYLTMRvhQKmI0GysMnzE6gkdjnSWUCot6HBqKFtwqik7S5YRYVwKp4ayRaI8dJjRUjgdSxuWwqmhbMGppiy3GAeMS@HUUJZbIFlgYoFkgYkFkgUmFsMS4jKSfkcYl8KzNJfopJnYrT9cu/Zeyhq6DL5Bo6BcwM@Qb/2@948b@@jvZGc7t77er@WFAg3CLECEcys7lbyQkRwPuycZxpRh3BKm769/357/hecU5jB9e/kzVepy8ludPgA "JavaScript (Node.js) – Try It Online")
### Commented
```
( [o, // o = 1st character of the input
...a], // a[] = remaining characters
s = o + // s is a lookup string used to transpose:
` +-a213` // "a" <-> first character
// "+" <-> "1"
// " " <-> "2"
// "-" <-> "3"
) => //
"C" + // prefix the result of the map() with "C"
a.map(c => // for each character c in a[]:
o += s[ // append to o ...
s.indexOf(c) // ... the character corresponding to
^ 4 // the transposition of c
] //
) // end of map()
< s ? // if o is "C":
"Ca" // return "Ca"
: // else:
/^A?$|B$/ // if the input was any of "A", "AA", "B",
.test(a) ? // "BB" or "BBB":
o + 2 // append a "2"
: // else:
o // leave o unchanged
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 59 bytes
```
^C$
CC
(?<!AA)[AB]$
$&,
1>T`321+--aL`-_+1-3#a`.
+`(.)#
$1$1
```
[Try it online!](https://tio.run/##XZAxbgMhEEX7OQWRcQQmrASkjL0aKNy4s7usE4jkwk0KryU3PpcPkIsRRkwRhQK9L57mj7icrufvUvd5@lLjerrpuxrfnqZZU5o1LNU2148kISWgF0T9jvEoQT6/gNsccvDOWFt22X4aZ8Oi5AFMVoNegHTSVb3N8PNQg9H/75Umw8tXGSqWIuggImBxzKaxZxaNA7MF7IogxTM2IzBaiKVPiTEaCp6DoBA4kNYHdcszkxSYm8NdpHAXGdzVhMTLp/ZHqaP4i/AL "Retina 0.8.2 – Try It Online") Link is to test suite that does some magic splitting and joining. Converts `Ca` to `CC`. Explanation:
```
^C$
CC
```
Change `C` to `CC`.
```
(?<!AA)[AB]$
$&,
```
Except for `AAA`, append a `,` to any string ending with `A` or `B`. The choice of `,` is important for the transliteration as it is between `+` and `-` in ASCII.
```
1>T`321+--aL`-_+1-3#a`.
```
Excluding the first character, transliterate `3` to `-`, delete `2`, transliterate `1` to `+`, `+` to `-` to `1` to `3`, `a` to `#` and all uppercase letters to `a`. (Having the `-` be first in the target pattern makes it a literal `-`. I couldn't do that in both patterns but fortunately in the source pattern I could use a range from `+` to `-`.)
```
+`(.)#
$1$1
```
Make `#`s copy the preceding letter.
[Answer]
# Python, 171 bytes
```
dict(zip(a:="Aaa Aa1 Aa2 Aa3 A1 A2 A3 Baa1 Baa2 Baa3 Ba1 Ba2 Ba3 B1 B2 B3 Caa Ca Ca C CC CCC B- B B+ BB- BB BB+ BBB- BBB BBB+ A- A A+ AA- AA AA+ AAA".split(),a[::-1])).get
```
[Try it online!](https://tio.run/##RZHBboMwEETv@xUjLsEKIAUuFRIHm88gHKwUWksNQdg9tD9Pd7FFkW3eoF2WGdaf8Plamrd12@fuvr@7R8h/3Zrbtsu0tdD2xrvm3UAzMjUwlp/yUcshUpQIZkamBj0393Ghl9XDlDAwVxgBpgMPFsFKl9DQfBdgOlBnlV@/XMhVYYe2LW@jUtXHFPYw@fCwfvLo4L@f@TD4sxInxpYR82uDh1uQZRmJM7n47SQOI19JnEYGiePIJelYIt9Guk4M5iZxCTpC4Uuc0BFOFHRkFLkkk6bFojqxdDeJuSZN40TIpGmGp5k0jSOjPjngXJmRGP/M9ey08mHjv6lSGpf7clFjgWFUJIG4ApNkckbZkjSvm1tCPudOoeswFRBU@x8 "Python 3.8 (pre-release) – Try It Online")
Boring hard-code Python answer is shorter than current ones...
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
⭆×⁻θ2⊕⁼θC⎇κ§⁺§θ⁰13-+a⌕a+-31ιι¿№AABBBθ2
```
[Try it online!](https://tio.run/##RY5BCoMwEEX3PUXIakIjtHbpykoLLgRpvcCgQw2NsSYq7enTKJVuhpnhfd6vW7R1j9r71Dn1MFDqyUE65qahNwySHYRkfB/FpyPysLYi2f3I@2iVeRT4gkp15BY4N7WljsxIDVyGCfX65RkXImQrsgbtB56SbYJWsqsyDdxoJusI2oApsY0hyMogGWGLZv0ULp7iGZEvgGRr4cUSL/0KZf6nEIn3Gfpo1l8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @JonathanAllan's Jelly answer.
```
⭆×⁻θ2⊕⁼θC⎇κ§⁺§θ⁰13-+a⌕a+-31ιι
```
Remove any `2` from the input, double it if it's `C`, and then transliterate all characters after the first from `a+-31` to `#13-+a`, where `#` is the first character of the input; characters in the input that don't match the source string are replaced with the last character of the destination string.
```
¿№AABBBθ2
```
Append a `2` if the input is a substring of `AABBB`.
[Answer]
# [Python 3](https://docs.python.org/3/), 200 bytes
```
def f(x):
r=str.replace;d=(6,0)[(x*2)[1]in'a123'];y=x
for i in 0,1,2:y=r(y,chr(49+i-d),chr(43+i+d))
y=r(y,',','')*((x=='C')+1)+'2'[not d*(x in'ABBBAA'):]
return x[0]+r(y[1:],*('a',x[0])[::1-d//3])
```
[Try it online!](https://tio.run/##fVLBjpswEL37K6a52A6QDaZaqYk4AFIvPfQDKIqsYHatpoDAkYiifHs6BnfDsm3N5Y15782bgfZiXps6uhs1GIhhtVolUoI9SZKQRIYOe4iFw4A4cjggyUSBxMN74TAgjhwOgKRyMkrT1LOFcIXFkcMBFpPVRBIOW3XkMHJctxS7pa5bit1S1y3FbpmbIMsyxODwA@KQhBxlr3qc@HojVdPBSdcKdA12D5u@PWnD6I@a8h2xEl23Z3MwzU9V@9CczVuFBlbpFHwkj875TFIgay66l6qCig3WvIt702061Z7kUe3LmD37W56zYS14Hha6pjIUES32l3ggYINqm3Lrh77YXeKOXfzja8c@f/F0UPIJR572So5ZpvfUPpSvGRvimGaUeyH3qKB53Rgo12xAQ5rgB0gSHLfASMqcuxqGfFt4aJCHu8JfMyqpb694vtuFQfn0FBX8PgaaBsW9@aCGVh2NKg/TuDbquI2NNupXz/5sswL2HxWHTzEwmmFDsHknkT3yaM7y5GiHENdazYz4g9f3qjMf6fGylQ8V/Sr1SZXjbq8Ps9v@jQvXhermwwvu7rrwv1HyMaQYQy4nJP9MKWzK@XLeB1wmmaechf9rQOECkrbTNf7e379Rfv8N "Python 3 – Try It Online")
Probably can be optimized, but it's the best I could come up with.
```
r=str.replace
# Set an alias for `str.replace`, we'll use it three times
d=(6,0)[(x*2)[1]in'a123']
# Detects if `x` is on Moody's format by checking the 2nd character.
# If positive, set `d` to 0, otherwise set `d` to 6.
# The multiplication by 2 is to handle single-character strings.
y=x
# Create a variable for the following replacements:
for i in 0,1,2:y=r(y,chr(49+i-d),chr(43+i+d))
# If `d` is 0, it will replace all '123' occurrences with '+,-', respectively
# If `d` is 6, it will replace all '+,-' occurrences with '123', respectively
y=r(y,',','')
# An annoying comma will appear in the first conversion, so remove it
y=y*((x=='C')+1)
# Handle the special case where `x` is equal to 'C', duplicating it
y=y+'2'[not d*(x in'ABBBAA'):]
# If `x` is on Fitch/S&P format, add a trailing '2' to the
# result if `x` is either 'A', 'AA', 'B', 'BB' or 'BBB'
return x[0]+r(y[1:],*('a',x[0])[::1-d//3])
# Since the first character of the input string will not change,
# keep it. For the remaining characters, if `x` is on Moody's
# format, replace all 'a's with the first character. Otherwise,
# replace all occurrences of the first character with 'a's.
```
[Answer]
# Excel ms365, ~~207~~179 bytes
Thanks to @[doubleunary](https://codegolf.stackexchange.com/posts/268721/revisions)'s idea for nesting `TEXTSPLIT()` inside `LEN()`.
Assuming input in `A1`:
```
=LET(a,A1,b,LEFT(a),c,RIGHT(a),e,LEN(@TEXTSPLIT(a,{1,2,3,"+","-"})),IFERROR(REPT(b,e)&MID("+-",FIND(c,"132a"),1),b&REPT("a",e-1+(a="C"))&IF(a="AAA",,MID(1223,FIND(c,"+AB-C"),1))))
```
[Answer]
# [Python 3](https://docs.python.org/3/), 235 bytes
```
eval('lambda x:(x?a",x[0])?1","+")?2","")?3","-")if"a"in x or x[-1]in"123"else x[0]+x[1:]?+","1")?-","3")?B","a")?C","a")?A","a")+("2"if x[-1]not in"+-"else""))?Aaa2","Aaa")?C2","Ca")?Ca2","Ca")?Caa2","Caa")'.replace('?','.replace("'))
```
[Try it online!](https://tio.run/##TZHBboMwDIbP4ykiX0gWmAq5IXUIkPoSrIdsDSoSA8TQlD09M8XOdvq@@I8dI@af9T6NZuvOb5v7toOMB/v5frPCF9KXFhLfnq6qzCABDarMkQiDSEH1HVjoR@HFtAjfptm1HyHLDbjhy4m9U/s2K66lxvsZ9qVIg6yRFtkQq4NaQg59d4wap1XgOJ0@puGreM3afQHE3rtr8zD7T8nxEL8sbh7sh5NxGSd/J4iV2m6uExfpVRE9zUs/rtInAs6vkIgOqyq6yOOZQzKWnMWQcMIB1WvLPbXlJrSQhjBkHHHCAdUbXmb/zOhYGX/Bszkd71YVLVBpFmZKwgGBynVd62BBQhgyJiccEKjcNA0LEdT2Cw "Python 3 – Try It Online")
Returns an anonymous function.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~285~~ ~~275~~ 248 bytes
-10 bytes by moving `strcmp` inside `for` condition and using "incorrect" pointer types (thanks @ceilingcat)
-27 by assuming 64-bit little-endian `long`
```
i;*t="Aaa AAA Aa1 AA+ Aa2 AA Aa3 AA- A1 A+ A2 A A3 A- Baa1BBB+Baa2BBB Baa3BBB-Ba1 BB+ Ba2 BB Ba3 BB- B1 B+ B2 B B3 B- Caa CCC Ca CC Ca C ";f(int*s){long j=538976288;memcpy(&j,s,strlen(s));for(i=38;t[--i]-j;);j=t[i^1];puts(&j);}
```
[Try it online!](https://tio.run/##RZDvaoMwFMW/5ykuwoapDcyEbZbgIPExug6CtJ3S2mLch1H27N25S2DC5fzu9f7R06tj39/vg10tbeFCIOccuVBDK6iGEtRAFbkaXCE0ghAGoYh8CLX3voJqKOcGqjz2oIxcQ7nPQBV57EGZPPagTB57UKYO97uug4I7Sor3hT2Uw7SsorydLtORxvbZNJvXF9009rw/99fv8nFcx3Vc5tN@KqOU9nCZy6E1jV22Sg07NVppx3bZDh/1zl6/logJaX/u5zBMpbz1n2GmuN3s/gZt7MN0KIuHWKyjfHvCeey8zviGv@r7wnVMs2H8wDTBpiWuBBuXmASbl1gJl1rYROF0ZgKbzIoEm8nMhnKic8JsMivh87XUpDPztMmMnnwNVgufr8Fu4fM1WC66/AewXXQJ2fp/JvoF "C (gcc) – Try It Online")
[Answer]
# Python 3 (256)
I know its not very short or optimized, but here is my first attempt at code golf! Please let me know if you have a tip for me to improve!
```
f=lambda r:(s:=r.replace("1","+").replace("3","-"))[0]*len(s.strip("+-2"))+s[-1].strip("2a")if "a" in r or r[-1]in[1,2,3] else r[0]+"a"*(l:=len(r.strip("+-"))-1)+(""if r[0]=="C"or r=="A"*3 else str(["+"," ","-"].index((r+" ")[l+1])+1))+("a"if r=="C"else"")
```
I do see that it is longer than the hardcoded python option, so I'll definitely have to try to beat that at the very least. Also comment if you want an explanation.
Edit: Here is another method using regex that turned out to unfortunately be longer (**268**) with the import
```
import re
t=str.maketrans("+-13","13+-")
f=lambda r: (r.replace("a",r[0]).translate(t).strip("2"))if r[-1]in"123"or"a"in r else((o:=re.sub("(Aa?|Ba*)$",lambda m:m.group()+"2",re.sub("(?<=\\w)\\w+",lambda m:"a"*len(m.group()),r)).translate(t))+("a"if len(o)<2 else""))
```
] |
[Question]
[
**This question already has answers here**:
[Substitution cipher [duplicate]](/questions/77899/substitution-cipher)
(13 answers)
Closed 2 years ago.
Given a permutation of the alphabet and an input string, encrypt the input string by replacing all characters with the one's you've been given.
The capitalization should be kept the same and non-letters are not to be changed.
```
[hnvwyajzpuetroifqkxmblgcsd], "Hello, World!" -> "Zytti, Giktw!"
```
As `[abcdefghijklmnopqrstuvwxyz]` has been mapped to `[hnvwyajzpuetroifqkxmblgcsd]`
## IO
Input may be taken in any reasonable form, output can either be to `STDOUT` or as a String.
## More test cases:
```
[ghrbufspqklwezvitmnjcdyaox], "Foo" -> "Fvv"
[ubjvhketxrfigzpwcalmoqysdn], "123Test String :D" -> "123Mhlm Lmaxze :V"
[qscxudkgemwrtbvnzolhyfaipj], "AAbcdeFghijK" -> "QQscxuDkgemW"
```
Standard ruleset applies!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
DuìD{s‡
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fpfTwGpfq4kcNC///L03KKsvITi2pKErLTK8qKE9OzMnNL6wsTsnjMjQyDkktLlEILinKzEtXsHIBAA "05AB1E – Try It Online")
```
Du # make a copy of the permutation and convert it to uppercase
ì # prepend the uppercase copy to the permutation
D{ # make a copy of the new string and sort it
# this always creates 'A ... Za ... z'
s # swap alphabet and permutation
‡ # transliterate the second input based on the given strings
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 60 bytes
Expects `(permutation_string)(string)`.
```
p=>s=>(B=Buffer)(s).map(c=>(B(p)[q=c&32,c-q-65]||c)&95|q)+''
```
[Try it online!](https://tio.run/##Zc5dS8MwGAXge39FloutwX3gxgQHHWyMKagXQ1FQvEjTpE2bNmmSph/sv9d1CIo7l@flPLwJdtgQzZWd5DKkHfM75a@Nv/a2/rZkjGrkGTTNsPJIX3oKfRY@GS7mYzIpJrfLr@ORoOHd8lig69GoIzI3UtCpkJHHPBjnrmpw0qqSWi05K9I6C0RETAiRBx@oEHIM3qUW4QCCUxACsxmAH421fAzueWqrAbz6h0axDkpmVJGKiraO2yxPSNhgWffoXsoz9ZsfdO/cBVUGiYtTamvNeNSqimCRyaIxYd5TN/PFKzUWvFjN8wisdvCHOh2eY5GBpwzXLQWrtwu4MKQuwzSiWaVt4PJWirhhmKukhzebgIR0H8U8eYR/fzwc@t3uvIPdNw "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 42 bytes
Assuming using lists of ASCII codes is acceptable:
```
p=>s=>s.map(c=>(p[q=c&32,c-q-65]||c)&95|q)
```
[Try it online!](https://tio.run/##fdHfS8MwEAfw9/0VZx9GC12HjgkqHYzNKagPQ1Gw9CFN0zZt2qRJ1l/sf5/tVvHNLyEvd/fh4FJUIYUlFXpW8JCcIvck3JXqn5MjYWJ3ZQqvdPF0cWPjWTm7XfrHI7amd8tjaZ0evAmAB0ZSVHWL0k4ciJacRmXW5AGLsQoNG4xnwhi34YtLFl4ZMMS3YT4H47vVmtrwRDNdXxkXK05kcIiUKDNWk66iOi9SHLaIN4O14/wi/GW0dlU1CocgrZKM6EZGNO5EjRHLedmqsBiE65vFB1Ea3rWkRQz3W@NX6CtvCcvhNUdNR@D@c/RKhZtDmMUkr6UOqqLjLGkjREU6eOt1gEOyixOavoyr@XD29vthcHseNCb@xIm4fEQ4MU1P2KB8C9wVYF4ozojDeGxeVnIiyfNNguSmP4jpOE5kev0v/MtFzkMOHutrbVqWdW5Q/zT0Of0A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
Œu;$ØẠ,y
```
[Try it online!](https://tio.run/##FY67DoIwAEV/BRtHFnXTicQYE0dNjCN90AelhT6A8hlOjm7@gyvxQ/ySaqeT3HOHI4iUIcbP3e@W8@P7fuYhzi9wixEw1Q@hFFPriTOaV109NlBSZDHIM0CZgb6ybVfLgUw9d40SCIdSj8l6KHpWEzeaitOpHVApG90Fi1WynUWjxzUlzWAc7NWkJQtVyVsBIjj@i3SeXbWReJHeB60TVuvNhViXnZ3himbbfRqLAiJMDpRxcQI/ "Jelly – Try It Online")
Chaining rules make this too long.
## How it works
```
Œu;$ØẠ,y - Main link. Takes permutation P on the left, string S on the right
$ - Last two links as a monad f(P):
Œu - Uppercase P
; - Prepend that to P
ØẠ - Alphabet; Yield "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
, - Pair; [ØẠ, P ; upper(P)]
y - Transliterate S, according to that mapping
```
[Answer]
# [Zsh](https://www.zsh.org), 18 bytes
```
tr a-zA-Z $1${1:u}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhabSooUEnWrHHWjFFQMVaoNrUprIRJQ-X3RShl5ZeWViVlVBaWpJUX5mWmF2RW5STnpycUpSrFrPVJzcvJ1FMLzi3JSFCFaAA)
Trivial.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
:⇧+kL$Ŀ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%3A%E2%87%A7%2BkL%24%C4%BF&inputs=hnvwyajzpuetroifqkxmblgcsd%0AHello%2C%20World!&header=&footer=)
## Explained
```
:⇧+kL$Ŀ
:⇧+ # append the uppercase version of the input to the input
kL # push a-zA-Z
$ # swap those
Ŀ # and transĿiterate the message
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~25~~ 21bytes
```
{(×⍵)×⍺∘(,⊃⍨⎕A⍳⊢)¨⌈⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTflfrXF4@qPerZogctejjhnVGkBaByQS/ahvquOj3s1AdmztoRWPejqArFouLBrg6jQfdTVDtSN0YFihoQNWtgKmr2uRJkKxs8KjtgkKQJ56Rl5ZeWViVlVBaWpJUX5mWmF2RW5STnpycYo6VzBYlbpHak5Ovo5CeH5RToqiOhfQQLC4Myk2Bv8HAA "APL (Dyalog Extended) – Try It Online")
This can most definitely be shorter.
-4 bytes thanks to ovs.
[Answer]
## Python 3, ~~147~~ ~~179~~ 151 Bytes
This method doesn't work for test cases containing ABCDEF due to the "g-97" statement.
```
x=[ord(i) for i in input()];c=chr
print("".join([c(g)*(not(c(g).isalpha())) or(c(x[g-97])*(g>97)or c(x[g-65]-32))for g in[ord(i)for i in input()]]))
```
There must be a shorter way to do this using mapping, but I haven' quite figured the mapping function out yet. Golf'ed down from an original 180 just a shame its not quite a one liner.
```
x=[ord(i)for i in input()];y=[ord(i) for i in input()];t=""
for i in range(len(y)):
g=y[i]
if 122>g>97:t+=chr(x[g-97])
else:t+=chr(g)*(not(90>g>65))or chr(x[g-65]-32)
print(t)
```
New method gets it to work with fewer bytes:
```
x=[ord(i)for i in input()];c=chr
print("".join([(c(x[g-97])if 123>g>96 else c(x[g-65]-32))if c(g).isalpha()else c(g)for g in[ord(i)for i in input()]]))
```
Movatica has a shorter [solution](https://codegolf.stackexchange.com/a/235702/55243) using the string library. And using := I could reduced my answer to a one-liner at the expense of a few bytes
[Answer]
# [Python 3](https://docs.python.org/3/), 84 bytes
*Codebook needs to be a string too.*
```
lambda a,s:s.translate(str.maketrans(ascii_letters,a+a.upper()))
from string import*
```
[Try it online!](https://tio.run/##HYzLDoIwEADvfkXlQqsNF28m3v0DLiZmgRYq24fbRcWfr8TjTCaTVp5iOBV7uRUE3w0gQOdzbpggZAQ2MjM1HmbzNxJy79wdDbOhrOEIzZKSIamU2lmKXmy5C6NwPkXiQ0kbsbSynsLrvcLjm5btFJ19zh/f4djnodaiuhrEqEUbCYd9pVT5AQ "Python 3 – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[Play the "bzzt" game](/questions/32267/play-the-bzzt-game)
(82 answers)
Closed 7 years ago.
This is my first code golf exercise for you:
Your input is two integers n and k. You can assume n >= 1 and k >= 1
You have to output all numbers from 1 to n (inclusively) and replace every element that is a multiple of k or that contains k with "Shaggy".
you can take the input in any convenient form and output it in a human readable form (seperators can be whitespaces, commas or whatever)
Standard loop holes are forbidden. Functions or programs are acceptable. Shortest code in byte wins!
This is different from the "Bzzt"-game, as this takes a variable "Bzzt" parameter, which, for values>=10, may increase the difficulty in some languages.
**Examples:**
```
Input: 20 6
Output: 1 2 3 4 5 Shaggy 7 8 9 10 11 Shaggy 13 14 15 Shaggy 17 Shaggy 19 20
Input: 21 4
Output: 1 2 3 Shaggy 5 6 7 Shaggy 9 10 11 Shaggy 13 Shaggy 15 Shaggy 17 18 19 Shaggy 21
Input: 212 11
Output: 1 2 3 4 5 6 7 8 9 10 Shaggy 12 13 14 15 16 17 18 19 20 21 Shaggy 23 24 25 26 27 28 29 30 31 32 Shaggy 34 35 36 37 38 39 40 41 42 43 Shaggy 45 46 47 48 49 50 51 52 53 54 Shaggy 56 57 58 59 60 61 62 63 64 65 Shaggy 67 68 69 70 71 72 73 74 75 76 Shaggy 78 79 80 81 82 83 84 85 86 87 Shaggy 89 90 91 92 93 94 95 96 97 98 Shaggy 100 101 102 103 104 105 106 107 108 109 Shaggy Shaggy Shaggy Shaggy Shaggy Shaggy Shaggy Shaggy Shaggy Shaggy 120 Shaggy 122 123 124 125 126 127 128 129 130 131 Shaggy 133 134 135 136 137 138 139 140 141 142 Shaggy 144 145 146 147 148 149 150 151 152 153 Shaggy 155 156 157 158 159 160 161 162 163 164 Shaggy 166 167 168 169 170 171 172 173 174 175 Shaggy 177 178 179 180 181 182 183 184 185 186 Shaggy 188 189 190 191 192 193 194 195 196 197 Shaggy 199 200 201 202 203 204 205 206 207 208 Shaggy 210 Shaggy 212
```
[Answer]
# Python 2, ~~64~~ 63 bytes
Anonymous function with arguments `n` and `k`, returns the list to output.
```
lambda n,k:[[i,'Shaggy'][i%k<1or`k`in`i`]for i in range(1,n+1)]
```
Alternatively, a function which prints to `STDOUT` for the same bytecount:
```
def f(n,k,i=1):exec"print[i,'Shaggy'][i%k<1or`k`in`i`];i+=1;"*n
```
[Answer]
# [Pyth](http://github.com/isaacg1/pyth), ~~25~~ 23 bytes
```
m?|!%dQ}`Q`d"Shaggy"dSE
```
A program that takes input of two newline-separated integers `k, n` and prints a list.
[Try it online!](http://pyth.tryitonline.net/#code=bT98ISVkUX1gUWBkIlNoYWdneSJkU0U&input=MTEKMjEy)
**How it works**
```
m?|!%dQ}`Q`d"Shaggy"dSE Program. Inputs: Q, E
m SE Map over [1, 2, 3, 4, ..., E] with varaible d:
? If
%dQ d % Q
! negated is truthy (divisible by H)
| or
`Q str(Q)
} is in
`d str(d):
"Shaggy" Yield "Shaggy"
Else:
d Yield d
Implicitly print
```
[Answer]
# SQL (PostgreSQL flavour), 130 ~~136~~ bytes
Done as a prepared statement:
```
prepare p(int,int)as select CASE WHEN i%$2=0or i::char like'%'||$2||'%'THEN'Shaggy'else i::char end from generate_series(1,$1)a(i)
```
This is executed in the following manner
```
execute p(20,6)
```
and the result is output as rows.
[Answer]
# Lua, ~~71~~ 70 Bytes
*Saved a byte thanks to Flp.Tkc*
Getting in before Jelly or Pyth or similar can swoop in and destroy my byte count.
```
a,b=...for i=1,a do print(((i..""):find(b)or i%b<1)and"Shaggy"or i)end
```
## Ungolfed with comments
```
local a,b = ... -- Command Line Input
for i=1, a do -- For all numbers between 1 and a
print( -- Print with newlines...
((i..""):find(b) or i%b<1) -- if the String version of i contains b, or if the remainder when i is divided by b == 0
and "Shaggy" -- then Shaggy
or i -- Else i
)
end
```
[Answer]
# Python 2, ~~74~~ 72 bytes
Having already been soundly beaten by @Flp.Tkc I'll just post my ~~74~~ 72 byte recursive solution because it's different and it works and not because it will win (and also because I like recursive functions).
```
def f(a,b,c=1):
print(c,"Shaggy")[c%b<1or`b`in`c`]
if c<a:f(a,b,c+1)
```
**Edit**
-2 by removing the unneeded `` around the `c` in the print statement
**From comments:**
Call using
```
f(a,b)
```
c will default to 1 due to the
```
c=1
```
in the function definition and can then be incremented for the recursive function calls.
[Answer]
# C, 122 bytes
```
f(n,k){int m,i;for(i=1;i<=n;++i){if(i%k){for(m=i;m>0;m/=10)if(m%10==k)goto l;printf("%d ",i);continue;}l:puts("Shaggy");}}
```
Newlines and spaces both act as separators.
[Answer]
# C#, 97 bytes
```
n=>k=>{var r="";for(int i=1;i<=n;i++)r+=i%k>0&&(i+"").IndexOf(k+"")<0?i+" ":"Shaggy ";return r;};
```
Full program with ungolfed method and test cases:
```
using System;
namespace Shaggy
{
class Program
{
static void Main(string[] args)
{
Func<int,Func<int,string>>f= n=>k=>
{
var r = "";
for(int i = 1; i <=n ; i++)
r += i % k > 0 && (i + "").IndexOf(k + "") < 0 ? i + " " : "Shaggy ";
return r;
};
Console.WriteLine(f(20)(6));
Console.WriteLine(f(21)(4));
Console.WriteLine(f(212)(11));
}
}
}
```
[Answer]
# C, ~~98~~ 96 bytes
```
n,h[],t[];s(i,j){for(;n<=i;n&&puts(!strstr(t,h)&&n%j?t:"Shaggy"),n++)sprintf(n?t:h,"%d",n?n:j);}
```
[Wandbox](http://melpon.org/wandbox/permlink/54NThYLcET5IZ9Sl)
] |
[Question]
[
As a programmer or computer scientist one might encounter quite a lot of trees - of course not the woody growing-in-the-wrong-direction kind, but the nice, pure mathematical kind:
```
*<- root (also a node)
/|\<- edge
* * *<- inner node
| / \
* * *<- leaf (also a node)
|
*
```
Naturally over time we all have put together our own small handy toolbox to analyse such trees as we encounter them, right?
Now is the time to show it off!
---
**Task**
The toolbox must include the following functions:
* `size`: The number of nodes in the tree.
* `depth`: The number of edges on the longest path from the root to any leaf.
* `breadth`: The number of leaves.
* `degree`: The maximum number of child nodes for any node.
You have to submit a program or function for each of the tools, however they might share subroutines (e.g. parsing) which then have to be submitted only once. Note that those subroutines need to be full programs or functions too.
---
**Input Format**
The trees can be given in any reasonable format capturing the structure, e.g. the tree
```
*
/ \
* *
```
could be represented through parentheses `(()())`, lists of lists `[[],[]]`, or data structures with a constructor `T[T[],T[]]`.
However not through linearisation `[2,0,0]` or a format like `(size, depth, breath, degree, whatever-else-is-needed-to-make-this-format-unique-for-every-tree)`.
Generally speaking, your tree format should not contain numbers.
**Output Format**
A natural number for each of the properties described above.
**Scoring**
Lowest code in bytes for the 4 functions *in every language* wins, thus I will not accept an answer.
Feel free to provide additional tree tools like `fold`, `isBinaryTree`, `preLinearise`, `postLinearize`, or whatever you like. Of course those don't have to be included in the byte count.
**Examples**
First the tree is given in the sample formats from above, then the results of the functions as `(size, depth, breadth, degree)`.
```
()
[]
T[]
(1,0,1,0)
(()())
[[],[]]
T[T[],T[]]
(3,1,2,2)
((())()((())()))
[[[]],[],[[[]],[]]]
T[T[T[]],T[],T[T[T[]],T[]]]
(8,3,4,3)
((()())((())()((())()))(()())(()))
[[[],[]],[[[]],[],[[[]],[]]],[[],[]],[[]]]
T[T[T[],T[]],T[T[T[]],T[],T[T[T[]],T[]]],T[T[],T[]],T[T[]]]
(17,4,9,4)
((((((((()))))))))
[[[[[[[[[]]]]]]]]]
T[T[T[T[T[T[T[T[T[]]]]]]]]]
(9,8,1,1)
(((((((()()))((()()))))((((()()))((()()))))))((((((()()))((()()))))((((()()))((()())))))))
[[[[[[[[],[]]],[[[],[]]]]],[[[[[],[]]],[[[],[]]]]]]],[[[[[[[],[]]],[[[],[]]]]],[[[[[],[]]],[[[],[]]]]]]]]
T[T[T[T[T[T[T[T[],T[]]],T[T[T[],T[]]]]],T[T[T[T[T[],T[]]],T[T[T[],T[]]]]]]],T[T[T[T[T[T[T[],T[]]],T[T[T[],T[]]]]],T[T[T[T[T[],T[]]],T[T[T[],T[]]]]]]]]
(45,7,16,2)
```
[Answer]
## Ruby, ~~122~~ 110 bytes
```
f=->s{->t{t.to_s.scan(s).size}}
s=f[?[]
d=->t{[-1,*t.map(&d)].max+1}
b=f['[]']
g=->t{([t.size]+t.map(&g)).max}
```
Inspired by Neil's JavaScript solution. **d** and **g** are just translations from his JS to Ruby. For **s** and **b** I'm using string conversion tricks.
Shaved a few bytes off of **s** and **b** by adding the helper **f**, and a few more byte off of **d** and **g** thanks to Jordan.
[Answer]
## Python, 136 bytes
```
f=lambda z,c:lambda t:eval(t,{'T':lambda*a:a and eval(z)or c})
s,d,b,g=map(f,['sum(a)+1','max(a)+1','sum(a)','max(len(a),*a)'],[1,0]*2)
```
The input format is the 'T[]' format but with parens instead of brackets and passed as a string. It's the longest submission so far, but I thought the approach is pretty cute.
[Answer]
## tinylisp, 248 bytes
```
(d X(q((m n)(i(l m n)n m))))(d F(q(()g(c(q(T))(c(c(q i)(c(q T)g))())))))(d S(F(s(S(h T))(s 0(S(t T))))1))(d H(F(X(s 1(s 0(H(h T))))(H(t T)))0))(d B(F(s(B(h T))(s 0(i(t T)(B(t T))0)))1))(d C(F(s 1(s 0(C(t T))))0))(d D(F(X(C T)(X(D(h T))(D(t T))))0))
```
Fun fact: 49% of that program is parentheses.
[tinylisp](https://codegolf.stackexchange.com/q/62886/16766) is a minimalistic version of Lisp, containing only 10 built-in functions and macros. Because [Lisp is awesome](https://xkcd.com/224/), it is nonetheless very powerful, and well-suited to manipulating abstract data structures like trees.
The program defines functions `S`, `H` (for "height"), `B`, and `D`, as well as a max function `X` and a number-of-children function `C`. It uses the `(()())` form of trees, with the added requirement that each tree must be *quoted* to be treated as data rather than code: `(q (()()))`. Example run:
```
tl> (d tree (q ((())()((())()))))
tree
tl> (S tree)
8
tl> (H tree)
3
tl> (B tree)
4
tl> (D tree)
3
```
Here's an ungolfed version, with a couple extra utility functions defined to make things clearer. For reference, the built-ins used are `d`efine, `q`uote, `i`f, `l`ess than, `c`ons, `s`ubtract, `h`ead, and `t`ail. (Yes, addition has to be implemented from subtraction.)
```
(d lambda (q (() args args)))
(d add
(lambda (a b)
(s a (s 0 b))))
(d max
(lambda (a b)
(i (l a b) b a)))
(d size
(lambda (tree)
(i tree
(add (size (h tree)) (size (t tree)))
1)))
(d depth
(lambda (tree)
(i tree
(max (add 1 (depth (h tree))) (depth (t tree)))
0)))
(d breadth
(lambda (tree)
(i tree
(add
(breadth (h tree))
(i (t tree)
(breadth (t tree))
0))
1)))
(d children
(lambda (tree)
(i tree
(add 1 (children (t tree)))
0)))
(d degree
(lambda (tree)
(i tree
(max (children tree) (max (degree (h tree)) (degree (t tree))))
0))))
```
This is pretty horrible Lisp style, since there's no tail recursion, but hey--it's code golf. ;^)
[Answer]
## JavaScript (ES6), 131 bytes
```
s=a=>a.reduce((r,e)=>r+s(e),1)
d=a=>Math.max(...a.map(d),-1)+1
b=a=>a.reduce((r,e)=>r+b(e),+!a[0])
g=a=>Math.max(...a.map(g),a.length)
```
Since all the functions are recursive, I've given them one letter names to save bytes: **s**ize, **d**epth, **b**readth and de**g**ree. Takes input using the `[,]` format.
[Answer]
## Perl 5 - 130 bytes
```
sub z{$_[0]=~y/<//c}
sub d{$_=$_[0];{s/><//&&redo}-1+z$_}
sub b{()=$_[0]=~/<>/g}
sub g{(grep{$_[0]=~/<(<(?1)*>){$_}>/}0..z$_)[-1]}
```
These take input as a string using angle brackets (e.g. `<<><>>`). `z` (size) and `b` (breadth) count the substrings for either all nodes or leafs, `d` (depth) collapses adjacent nodes until there's no branching then gets the size, and `g` (degree) uses a recursive regex to test for the presence of nodes of each degree up to the size then returns the largest found.
[Answer]
# C#, ~~380~~, 357 bytes
I've just noticed I forgot to remove some of my test code, so 23 bytes shaved off...
This is my first submission on PPCG and I'm not sure if the format is entirely correct especially because I'm using C#, but here are my four functions:
```
int d(string t){int l=-1,p=0;t.Max(m=>p=p<(l+=m=='('?1:-1)?l:p);return p;}
int s(string t){return t.Count(c=>c=='(');}
int f(string t){int q=0,w=d(t)+2;int[]l=new int[w],i=new int[w];t.Max(m=>l[q]=m=='('?l[q++]+1:(0*(i[q]=l[q]>i[q]?l[q]:i[q])*(q--)));return i.Max();}
int b(string t){var f='(';int l=0;t.Max(m=>l+=(f=='('&m==')')?(f=m)*0+1:(f=m)*0);return l;}
```
d: Depth
s: Size:
f: Degree
b: Breadth
The functions use `()` as input
I'm using LINQ's Max function to iterate through the items in the string array. I'm not using the functionality of `Max`, I only use it because it's the shortest iterative function; I could just as well have used `Min`. There's no recursion and all is done in linear time.
A slightly more readable version of my code, but the LINQ is still a bit cryptic:
```
/*Depth: Increment counter on open bracket and
decrement on closed bracket;
return highest number reached*/
int d(string t)
{
int l = -1, p = 0;
t.Max(m => p = p < (l += m == '(' ? 1 : -1) ? l : p);
return p;
}
int s(string t)//Size: Count the number of open brackets
{
return t.Count(c => c == '(');
}
int f(string t)//Degree, this one took me hours to figure out
{
int q = 0, w = d(t) + 2;
int[] l = new int[w], i = new int[w];
t.Max(m => l[q] = m == '(' ? l[q++] + 1 : (0 * (i[q] = l[q] > i[q] ? l[q] : i[q]) * (q--)));
return i.Max();
}
int b(string t)//Breadth
{
var f = '(';
int l = 0;
t.Max(m => l += (f == '(' & m == ')') ? (f = m) * 0 + 1 : (f = m) * 0);
return l;
}
```
[Answer]
# Mathematica, 77 bytes
```
s=LeafCount
d=Depth@#-2&
b=Length@Level[#,{-2}]&
g=Max[Length@#,##&@@#]&//@#&
```
Take any Mathematica expression as input.
[Answer]
# [Standard ML](https://en.wikipedia.org/wiki/Standard_ML), 149 bytes
```
val m=Int.max
val% =foldl
fun f?(T%)= ?(map(f?)%)
val s=f(%op+1)
val d=f(fn t=>1+ %m~1t)
val b=f(fn[]=>1|t=> %op+0t)
val g=f(fn t=>m(length t,%m 0t))
```
[Try it on Tutorialspoint.](https://goo.gl/yY4LQO) Uses the constructor notation (e.g. `T[T[],T[]]`) with the following data structure declaration: `datatype tree = T of tree list`
Ungolfed:
```
fun fold f (T xs) = f (map (fold f) xs)
val size = fold (foldl op+ 1)
val depth = fold (fn t => 1 + foldl Int.max ~1 t)
val breadth = fold (fn nil => 1 | t => foldl op+ 0 t)
val degree = fold (fn t => Int.max(length t, foldl Int.max 0 t))
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/7293/edit).
Closed 6 years ago.
[Improve this question](/posts/7293/edit)
I would like to see the shortest expression to calculate the days (or the last day) of a month in any language.
Considering y as the number of year and m as month.
Basic rules
* without date / time functions.
* considering leap years.
* there is not other rule.
[Answer]
## C, 40 33 31 characters
Reduced length in three ways:
1. Replaced `m%2^m>7` with `m^m>7`. The first is 0/1 in 30/31 day months, the second is even/odd. But the high bits don't matter, because their all set in 30 anyway (months with 30/31 days look like a really good idea now).
2. Used mob's idea (`y%(y%100?4:400)` as a leap year test)
3. Used `<1` instead of `!` saves parenthesis.
4. `y%(y%100?4:400)` -> `y%(y%25?4:16)` - works the same.
```
m-2?30|m^m>7:28|y%(y%25?4:16)<1
```
[Answer]
## C, 47 45 characters
```
30+(m>7^m&1)-(m^2?0:2-!(y%100||(y/=100),y%4))
```
Taken from [an answer](https://codegolf.stackexchange.com/a/3412/737) to an earlier question where I borrowed a couple of tricks from [another user](https://codegolf.stackexchange.com/users/2501/griffin). Returns the length of month `m` in year `y` for the Gregorian calendar. [ugoren's answer](https://codegolf.stackexchange.com/a/5041/737) to the same question is shorter and may give a shorter answer to this question.
With thanks to [mob](https://codegolf.stackexchange.com/users/5202/mob) for his leap year calculation.
[Answer]
I've already answered it before in stackoverflow:
```
(62648012>>m*2&3)+28+(m==2&&y%4==0)
```
<https://stackoverflow.com/questions/2675720/calculate-days-of-month/11675530#11675530>
[EDIT]
Matt advertised me about leap yars below and he's asked about language. About the language: the expression works on c/c++ and maybe others.
So, the simplest form will work until 2100... but to prevents the 2100 bug :) I've copied the Matt solution to leap year:
```
(62648012>>m*2&3)+28+(m==2&&(y%4==0&&(y%100!=0||y%400==0)))
```
[Answer]
# Python 64 61 59
```
(62648012>>m*2&3)+28+(m==2and y%4==0*(y%100>0 or y%400==0))
```
Based on olivecoder's solution, but accounting for [multiples of 100](http://en.wikipedia.org/wiki/Leap_year#Gregorian_calendar).
[Answer]
## VBA, 84
```
28+Val(Mid("303232332323",M,1))-(M=2 And Y Mod 4=0 And (Y Mod 100>0 Or Y Mod 400=0))
```
[Answer]
# Python 50 ~~54~~ ~~57~~
```
29+{2:y%(y%25and 4or 16)and-1}.get(m,(1&m^m>>3)+1)
```
with inspiration from mob, and the interesting fact, that
a dict saves 1 byte in contrast to m==2and(..)or(...)
[Answer]
# Mathematica 97 91 83 82 78 76
A bit long, but gets the job done.
>
>
>
>
> d
> =
>
>
> y
> ~
> Divisible
> ~
> #
>
> &
>
>
> ;
>
> 30
> +
>
>
> {
>
> 1
> ,
>
>
> Boole
> [
>
>
> d
> @
> 400
>
> ∨
>
> (
>
>
> d
> @
> 4
>
> ∧
>
> ¬
>
> d
> @
> 100
>
>
>
> )
>
>
> ]
>
> -
> 2
>
> ,
> 1
> ,
> 0
> ,
> 1
> ,
> 0
> ,
> 1
> ,
> 1
> ,
> 0
> ,
> 1
> ,
> 0
> ,
> 1
>
> }
>
> [
>
> [
> m
> ]
>
> ]
>
>
>
>
>
[Answer]
### VB.net (89 81c)
shame about the date function restriction as **VB.net** at only **(21c)**
```
Date.DaysInMonth(y,m)
```
may have won one for a change. DAMN YOU!
So current best is **89c**
{0,31,28,31,30,31,30,31,31,30,31,30,31}(m)+(If( m=2 AndAlso (y Mod 4)=0 AndAlso (y Mod 400)>0,1,0)
```
{0,31,28,31,30,31,30,31,31,30,31,30,31}(m)+(If( m=2 And (y Mod 4)=0 And (y Mod 400)>0,1,0)
```
] |
[Question]
[
Implement a function that takes a list that consists of 0, 1 or 2, the list is called "pattern". Your job is to return all possible lists that match the pattern.
* 0 matches 0
* 1 matches 1
* 2 matches 0 and 1
Examples:
```
f([0, 1, 1]) == [[0, 1, 1]]
f([0, 2, 0, 2]) == [[0, 0, 0, 0], [0, 1, 0, 0], [0, 1, 0, 1], [0, 0, 0, 1]]
f([2, 1, 0]) == [[0, 1, 0], [1, 1, 0]]
```
Order does not matter, you can use a {set} data structure instead.
You cannot use regular expressions or other **string** pattern matching mechanisms. You cannot use a brute-force search.
Shortest solution wins.
[Answer]
## Haskell, 49 characters
```
f[]=[[]]
f(2:r)=f(0:r)++f(1:r)
f(x:r)=map(x:)$f r
```
Interestingly this is exactly what I'd write even if this wasn't golf - except for removing spaces and calling the list's tail `r` rather than `xs`.
[Answer]
## Haskell, ~~34~~ 26 characters
Saved 8 characters thanks to Zgarb.
```
r 2=[0,1]
r n=[n]
f=mapM r
```
[Answer]
# Prolog, 62 characters
```
f([],[]). f([H|T],[A|B]):-((H=2,(A=0;A=1));(H<2,A=H)),f(T,B).
```
Example:
```
?- f([0,2,0,2],X).
X = [0, 0, 0, 0] ;
X = [0, 0, 0, 1] ;
X = [0, 1, 0, 0] ;
X = [0, 1, 0, 1] ;
```
[Answer]
# Mathematica, 30 chars
```
f=Tuples[{#}&/@#/.{2}->{0,1}]&
```
Examples:
```
f[{0, 1, 1}]
```
>
> {{0, 1, 1}}
>
>
>
```
f[{0, 2, 0, 2}]
```
>
> {{0, 0, 0, 0}, {0, 0, 0, 1}, {0, 1, 0, 0}, {0, 1, 0, 1}}
>
>
>
```
f[{2, 1, 0}]
```
>
> {{0, 1, 0}, {1, 1, 0}}
>
>
>
[Answer]
## Ruby - 76 characters
```
def f l;l==l-[2]?[l]:((j=l.dup)[k=l.index(2)]=0;(i=l.dup)[k]=1;f(j)+f(i))end
```
### Testing script:
```
require_relative 'golf-lists'
[
[0, 1, 1],
[0, 2, 0, 2],
[2, 1, 0]
].each do |list|
puts "f([#{list.join(', ')}]) == #{f(list)}"
end
```
Result:
```
f([0, 1, 1]) == [[0, 1, 1]]
f([0, 2, 0, 2]) == [[0, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 1, 0, 1]]
f([2, 1, 0]) == [[0, 1, 0], [1, 1, 0]]
```
[Answer]
## Scheme (149) (148)
```
(define(f l)(if(null? l)'(())(let((t(f(cdr l)))(n(car l)))(if(< n 2)(map(lambda(m)`(,n,@m))t)`(,@(map(lambda(m)`(0,@m))t),@(map(lambda(m)`(1,@m))t]
```
With whitespace (the closing square brace closes all open parentheses on certain Scheme implementations; 154 chars without it):
```
(define (f l)
(if (null? l)
'(())
(let ((t (f (cdr l)))(n(car l)))
(if (< n 2)
(map (lambda (m) `(,n ,@m)) t)
`(,@(map (lambda (m) `(0 ,@m)) t)
,@(map (lambda (m) `(1 ,@m)) t]
```
[Answer]
# CJam, 18 bytes
CJam is much younger than this challenge, so this is answer is not eligible for being accepted.
```
]]l~{2b\f{\f+~}}/p
```
Reads input from STDIN as a CJam style array.
[Test it here.](http://cjam.aditsu.net/#code=%5D%5Dl~%7B2b%5Cf%7B%5Cf%2B~%7D%7D%2Fp&input=%5B0%202%201%202%5D)
## Explanation
```
]]l~{2b\f{\f+~}}/p
]] "Push a nested empty array [[]] onto the stack. This is the base case.";
l~ "Read and eval the input.";
{ }/ "For each integer in the input.";
2b "Convert to base 2. This turns 0 into [0], 1 into [1] and 2 into [1 0].";
\f{ } "Swap with the current result and map this block onto the base-2 representation
copying in the current list of lists on each iteration.";
\f+ "Swap the list of lists with the 0 or 1 and add the number to each list.";
~ "Unwrap the list of lists. They'll be regrouped by the surrounding f{...}.";
p "Pretty-print the result.";
```
[Answer]
# [Python 2](https://docs.python.org/2/), 156 bytes
```
def f(l):R,L=range(len(l)),[];exec"\n".join(" "*j+"for v%d in[[l[%d]],[0,1]][l[%d]>1]:"%(j,j,j)for j in R)+"L+=["+"".join("v%d,"%j for j in R)+"],";return L
```
[Try it online!](https://tio.run/##lY7BasMwDIbvewohCNiLKXWOLekThB16dXUoi7PFBLsoXmmfPnUbb5CNwSYL49/6@fSfrvE9@GqaWttBJwa52aum5qN/s2KwPn1IZWhrL/YVDx5XLvReIOCzK7ELDOeihd4bM5iiJVJmrTTRrHaaNlgIp9KRd69LTtjLEpuyNljiJy0xFBYOFh5SuGUbP9hDMx3H0XJM@RIfdGqSkKquYQwcbSvAfE0I/lXyaQGvFNzvxP8Oz00K8qofSme1zooW8Gq2/Zr8wdL5SX9KfuLeR8CXAPOaPniwzIFXON0A "Python 2 – Try It Online")
[Answer]
# J, 19 bytes
```
[:>@,[:{{&(0;1;0 1)
```
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/6Ot7Bx0oq2qq9U0DKwNrQ0UDDX/a3Ip6Smop9laqSvoKNRaKaQVc3GlJmfkK6QpGAG1ATGCa6hg@B8A "J – Try It Online")
I had originally created a much longer version using amend and binary numbers, but user b\_jonas suggested the above approach in IRC to me.
It essentially converts 0 and 1 to themselves, and 2 to the list `0 1`, and the just cross products everything using catalog `{`. Since catalog requires boxed data, and returns structured data, everything is (un)raveled and unboxed at the end: `>@,`.
] |
[Question]
[
Given two non-empty 01 strings, check if there is string containing both given strings, and their first appearance end at same position.
Test cases:
```
01, 1 => true (01)
0, 00 => false (0 would at least come 1 character earlier)
01, 11 => false (can't meet on same position)
01, 0 => false (can't meet on same position)
11, 11 => true (11)
0101, 1 => false
```
The input can be encoded in whichever way you like.
As a [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'"), the output (true/false) can also be encoded using any 2 distinct, fixed values, or using your languages (optionally swapped) convention
Shortest code wins.
# Note:
This is the promise checker of <https://codegolf.meta.stackexchange.com/a/26193/>
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
LÞṫw¥@Ƒ/
```
[Try it online!](https://tio.run/##y0rNyan8/9/n8LyHO1eXH1rqcGyi/v@Hu7cc2vpwx6bD7ZqR//8bGCoYchkYKBhwgViGINKAyxDKBAkBAA "Jelly – Try It Online")
Ran through a lot of 10-12 byters, but eventually lucked out into this. Takes monadic input as a pair of values. (`ṫw¥@Ƒ` for 5 bytes dyadic if the shorter input can be assumed to be on the left.)
```
L√û Sort by length.
/ With the shorter string on the left and the longer on the right:
Ƒ Is the left equal to
·π´ @ the right without the characters before
w¥ the first occurrence of the left in it?
```
[Answer]
# [Uiua](https://www.uiua.org), 10 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
↥∩/<⌕⊃:⌕∩⇌
```
[Try it!](https://uiua.org/pad?src=0_7_1__ZiDihpAg4oal4oipLzzijJXiioM64oyV4oip4oeMCmYgIjAxIiAiMSIKZiAiMSIgIjAxIgpmICIwMCIgIjAiCmYgIjAiICIwMCIKZiAiMDEiICIwIgpmICIxMSIgIjExIgpmICIwMTAxIiAiMSIK)
Given two strings `a` and `b`, reverse them, evaluate "find" (a boolean array containing 1 at the starting points of appearance of `b` in `a`), and test if it is in the form of a 1 followed by a bunch of zeros (so the original strings match only at the end). Repeat it with arguments swapped and return the OR of the two results.
```
↥∩/<⌕⊃:⌕∩⇌ input: two strings a, b
‚à©‚áå reverse both a and b
⊃:⌕ reuse arguments:
: top: push b, a
‚åï below: push find(a, b)
‚åï take b, a from top and push find(b, a)
‚à©/< test if each array is in the form of [1 0 0 ... 0] (APL trick)
‚Ü• return the OR of the two
```
[Answer]
# [Haskell](https://www.haskell.org) + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), 28 bytes
```
eq[0]<<on(ap<fa<<mNl*^maL)rv
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FNxczcgvyiEoXC0sSczLTM1BSFgKLUnNKUVC6oRMDS0pI0XYt9abaphdEGsTY2-XkaiQU2aYk2Nrl-OVpxuYk-mkVlEEXbcxMz82wLilTSFJQMDQyVFJQMDEA0RHbBAggNAA)
## Explanation
* `on ... rv` reverse both arguments
* `fa` get the indexes of all occurrences of ...
+ `mNl` the shorter string
... in ..
+ `maL` the longer string
* `eq[0]` check if it is equal to `[0]`
## Tuple version, 29 bytes
```
eq[0]<(fa<U mNl*^U maL)<jB rv
```
## Reflection
Argument routing is really expensive in this answer, so improvements here are mostly about argument rerouting.
* A lot of the other answers here use a "try this or the arguments swapped" method and solve the problem with an assumed argument order. A function that does this could be useful.
* It would be good to have some functions which parallelize mins and maxes. i.e. take two arguments and spit out a tuple placing them in order. This would make a massive difference, with a function `xNl` which sorts two arguments by length, the whole thing would be 21 bytes:
```
eq[0]<<fa<<%(nXl.*rv)
```
* Two tuple related functions:
```
ot.*U :: (a -> b -> c) -> (a -> b -> c) -> (a, b) -> (c, c)
```
and
```
Cu<<(ot.*U) :: (a -> b -> c) -> (a -> b -> c) -> a -> b -> (c, c)
```
would both allow you to parallelize the mins and maxes properly. They'd be generally useful for this sort of thing and without the above bullet point implemented they'd save bytes here.
* A shortcut for `U x<y` exists but not one for `x<U y`. While the missing one not as philosophically motivated as the other both should probably exist.
* Similarly a shortcut for `jB x<y` exists but not one for `x<jB y`. No harm in both.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/), 36 bytes
```
$1~$2a&&$1!~$2"."||$2~$1a&&$2!~$1"."
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m704sTx7wYKlpSVpuhY3VVQM61SMEtXUVAwVgQwlPaWaGhWjOhVDkJARUMgQKARRC9Wy4KatgaGCIZehgoEhl4GCgQGXAZDkAokBBSGihiABEMsQLGpgCNdhYAgxBQA)
This is a pattern that takes two strings on a line separated by a space and evaluates to a boolean. As a full program, it accepts multiple lines and prints only the lines that pass the test.
* `string ~ pattern` and `string !~ pattern` are "match" and "not match" respectively, i.e. regex `pattern` is found/not found in the `string`. `$1~$2a&&$1!~$2"."` tests if `$1` contains `$2` but only as a suffix (`$1` does not contain a pattern that is `$2` followed by any extra char).
+ `x y` is string concatenation. If `$2` is `"0110"`, `$2"."` is `"0110."`, which becomes `/0110./` in regex context. Since the input is numeric, `$2` needs to be explicitly coerced to a string (fortunately, Awk keeps numeric inputs in its original form as a string, so this works). `$2a` concats `$2` with `a` (an uninitialized variable, which evaluates to `""`).
* The code is repeated twice with `$1` and `$2` swapped so that the test is done in both directions.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 12 bytes [SBCS](https://github.com/abrudz/SBCS)
```
A⍨∨A←</∘⌽⍷⍥⌽
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=c3zUu@JRxwrHR20TbPQfdcx41LP3Ue/2R71LgQwA&f=UzcwVE9TN1TnUjcwADIMQAywCEjIEMEyMIRIAwA&i=AwA&r=tryapl&l=apl-dyalog-extended&m=train&n=f)
A tacit function which takes strings on the left and right and determines whether one is a substring of the other only at the end.
## Explanation
```
A⍨∨A←</∘⌽⍷⍥⌽­⁡​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁡​‎⁠⁠‎⁡⁠⁣‏⁠‏​⁡⁠⁡‌⁢⁢​‎⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌­
⍥⌽ ⍝ ‎⁡reverse both strings
⍷ ⍝ ‎⁢find positions subsequences of right equal to left
⌽ ⍝ ‎⁣reverse
</ ⍝ ‎⁣less than reduce
</∘⌽ ⍝ ‎⁣checks if a Boolean vector is 1 0 0 ... 0
A← ⍝ ‎⁤assign this tacit function to A
∨ ⍝ ‎⁢⁡OR
⍨ ⍝ ‎⁢⁢swapped arguments of
A ⍝ ‎⁢⁣function A
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 10 bytes
```
·∂ú$·µó{iq=}s=
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6Fusebpuj8nDr9OrMQtvaYtslxUnJxVCpBTetlQwMlRSUDJW4lAwMgAwDEAMsAhIyhLMMDOHqDGGiEDMA)
```
·∂ú$·µó{iq=}s=
·∂ú$ Optionally swap the two inputs
·µó{ } Check that the following is not true:
iq a substring of the first input with the last character removed
= is equal to the second input
s= Check that the second input is a suffix of the first
```
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 10 bytes
```
A⍨∨A←</⍷⍢⌽
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfz/P@1R2wTHR70rHnWscAQybfQf9W5/1LvoUc/e/4/6pgJF1A0M1dMUHvWu0VE3VOeCiRnAxAwQYkB16oYINYbofANDJF3/AQ "APL (dzaima/APL) – Try It Online")
Same as my [Dyalog APL answer](https://codegolf.stackexchange.com/a/268770/117598), but we can take advantage of the Under operator `⍢` to reverse before and after the `⍷`.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 24 bytes
```
O#$`
$.&
^(.+)¶.*?\1
^$
```
[Try it online!](https://tio.run/##K0otycxL/K@qEZwQ46L9319ZJYFLRU@NK05DT1vz0DY9LfsYQy6uOJX//w0MdRQMuQx0FAwMuMBsQzBlwGUI44BFAQ "Retina 0.8.2 – Try It Online") Takes input on separate lines but link is to test suite that splits on non-digits for convenience. Explanation:
```
O#$`
$.&
```
Sort in order of length.
```
^(.+)¶.*?\1
```
Delete the shorter string and up to the end of the first match of the shorter string in the longer string, if any.
```
^$
```
Check whether this actually removed the entire longer string.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~18~~ 17 bytes
```
⁼⁰⌈⌈⟦⌕A⮌θ⮌η⌕A⮌η⮌θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO1sDQxp1jDQEfBN7EiM7c0VwNGR7tl5qU45uRoBKWWpRYVp2oUauoowNgZmkAOuoIMJAWFmpqxmkBg/f@/IZeBoYHhf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for true, nothing for false. Explanation:
```
‚åïÔº° Find all matches of
η Second input
‚Æå Reversed
θ In first input
‚Æå Reversed
‚åïÔº° Find all matches of
θ First input
‚Æå Reversed
η In second input
‚Æå Reversed
⌈⟦ Take the maximum
‚åà Take the maximum
⁼ Is equal to
⁰ Literal integer `0`
Implicitly print
```
There are three cases:
* Neither string is a substring of the other. In that case, both calls to `FindAll` return the empty list, so the maximum of the maximum is `None`. This therefore results in a false output.
* Both strings are equal. In that case, both calls to `FindAll` return the list `[0]`, so the maximum of the maximum is `0`. This therefore results in a true output.
* One string is a substring of the other. In that case, one `FindAll` will return the empty list, while the other will return a list of indices. In that case, the maximum of the maximum is the number of the characters after the end of first match, which we want to be `0` for a true output.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~101~~ ~~78~~ ~~77~~ 53 bytes
```
lambda x,y:['']==y.split(x)[1:]or['']==x.split(y)[1:]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZqsQ8z8nMTcpJVGhQqfSKlpdPdbWtlKvuCAns0SjQjPa0Co2vwgiWgEVrQSL/i8oyswr0UjTUDIwVNJRMlTS1ORCCCnpKCgZGKCKGYIEDQ2xCKIqNMSuEKofKPofAA "Python 3 – Try It Online")
-23 bytes by using a different approach
-1 byte by changing from `==2` to `<3`
-24 bytes thanks by [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2) by combining `len(x.split(y))` and `x.split(y)[-1]` into one, then slightly changing the code.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 50 bytes
```
a=>b=>(g=c=>/^\d*,$/.test(c.split(b)))(a)|g(b,b=a)
```
[Try it online!](https://tio.run/##jZFNTsMwEIX3OcUskOJBJnHWlcOKU9BCJ67TBjlxZLvQCjh7sJUolB3LefO@@X2jd/LKdWN4GOxBT62cSNaNrNlRKlmXL9vDPb8ri6B9YKrwo@kCaxCREX4dWcMbSTilrCKvPUjYZ6LiUIGsIbizBiYqzKIiVikTMRIpasn45IAPezYHoABGkw@gbK9jCXUiRypoB5qc6bTDTCR2RedW1U0pRUMeoNc6gB3AU6wzWt@Fzg5xinWMX1r8FxZ/2WrtPG9ZxS1Fta6@mBJzS@2L4Lqe4XLIfDvkWPQ0MpM8ZpFL/gglzgn2fOFw5fDKQe8wuRZBg5SQp@b5DjfZ@oKite6J1GklF@wzg3jXwVujC2OPrGUXZFeM@Uh/42b6AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-pl`, 44 bytes
```
$_=($b=<>)=~/$_$/*$b!~/$_.+$/+/$b$/*!/$b.+$/
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lZDJcnWxk7Ttk5fJV5FX0slSRHE0tNW0dfWV0kCiigCKRD3/38DQy4DA8N/@QUlmfl5xf91C3IA "Perl 5 – Try It Online")
] |
[Question]
[
I am quite surprised that [a variant of linear regression](https://codegolf.stackexchange.com/questions/106260/linear-regression-on-a-string) has been proposed for a challenge, whereas an estimation via ordinary least squares regression has not, despite the fact the this is arguably the most widely used method in applied economics, biology, psychology, and social sciences!
[](https://i.stack.imgur.com/hNohR.png)
For details, check out the [Wikipedia page on OLS](https://en.wikipedia.org/wiki/Ordinary_least_squares). To keep things concise, suppose one has a model:
$$Y=\beta\_0+\beta\_1X\_1+\beta\_2X\_2+\dots+\beta\_kX\_k+U$$
where all right-hand side *X* variables—regressors—are linearly independent and are assumed to be exogenous (or at least uncorrelated) to the model error *U*. Then you solve the problem
$$\min\_{\beta\_0,\dots,\beta\_k}\sum\_{i=1}^n\left(Y\_i-\beta\_0-\beta\_1X\_1-\dots-\beta\_kX\_k\right)^2$$
on a sample of size *n*, given observations
$$\left(\begin{matrix}Y\_1&X\_{1,1}&\cdots&X\_{k,1}\\\vdots&\vdots&\ddots&\vdots\\Y\_n&X\_{1,n}&\cdots&X\_{k,n}\end{matrix}\right)$$
The OLS solution to this problem as a vector looks like
$$\hat{\beta}=(\textbf{X}'\textbf{X})^{-1}(\textbf{X}'\textbf{Y})$$
where **Y** is the first column of the input matrix and **X** is a matrix made of **a column of ones** and remaining columns. This solution can be obtained via many numerical methods (matrix inversion, QR decomposition, Cholesky decomposition etc.), so pick your favourite!
*Of course, econometricians prefer slightly different notation, but let’s just ignore them.*
Non other than Gauss himself is watching you from the skies, so do not disappoint one of the greatest mathematicians of all times and write the shortest code possible.
## Task
Given the observations in a matrix form as shown above, estimate the coefficients of the linear regression model via OLS.
## Input
A matrix of values. The first column is always `Y[1], ..., Y[n]`, the second column is `X1[1], ..., X1[n]`, the next one is `X2[1], ..., X2[n]` etc. **The column of ones is not given** (as in real datasets), **but you have to add it first in order to estimate** `beta0` (as in real models).
**NB.** In statistics, regressing on a constant is widely used. This means that the model is `Y = b0 + U`, and the OLS estimate of `b0` is the sample average of `Y`. In this case, the input is just a matrix with one column, `Y`, and it is regressed on a column of ones.
You can safely assume that the variables are not exactly collinear, so the matrices above are invertible. In case your language cannot invert matrices with condition numbers larger than a certain threshold, state it explicitly, and provide a unique return value (that cannot be confused with output in case of success) denoting that the system seems to be computationally singular (`S` or any other unambiguous characters).
## Output
OLS estimates of `beta_0, ..., beta_k` from a linear regression model in an unambiguous format or an indication that your language could not solve the system.
## Challenge rules
* I/O formats are flexible. A matrix can be several lines of space-delimited numbers separated by newlines, or an array of row vectors, or an array of column vectors etc.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
* Built-in functions are **allowed** as long as they are tweaked to produce a solution given the input matrix as an argument. That is, the two-byte answer `lm` in **R** is **not** a valid answer because it expects a different kind of input.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs.
* [Default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
## Test cases
1. `[[4,5,6],[1,2,3]]` → output: `[3,1]`. Explanation: **X** = [[1,1,1], [1,2,3]], **X'X** = [[3,6],[6,14]], inverse(**X'X**) = [[2.333,-1],[-1,0.5]], **X'Y** = [15, 32], and inverse(**X'X**)⋅**X'Y**=[3, 1]
2. `[[5.5,4.1,10.5,7.7,6.6,7.2],[1.9,0.4,5.6,3.3,3.8,1.7],[4.2,2.2,3.2,3.2,2.5,6.6]]` → output: `[2.1171050,1.1351122,0.4539268]`.
3. `[[1,-2,3,-4],[1,2,3,4],[1,2,3,4.000001]]` → output: `[-1.3219977,6657598.3906250,-6657597.3945312]` or `S` (any code for a computationally singular system).
4. `[[1,2,3,4,5]]` → output: `3`.
**Bonus points** (to your karma, not to your byte count) if your code can solve very ill-conditioned (quasi-multicollinear) problems (e. g. if you throw in an extra zero in the decimal part of `X2[4]` in Test Case 3) with high precision.
**For fun:** you can implement estimation of standard errors (White’s sandwich form or the simplified homoskedastic version) or any other kind of post-estimation diagnostics to amuse yourself if your language has built-in tools for that (I am looking at you, R, Python and Julia users). In other words, if your language allows to do cool stuff with regression objects in few bytes, you can show it!
[Answer]
# [R](https://www.r-project.org/), 34 bytes
```
function(x)try(lm(V1~.,x,si=F)$co)
```
[Try it online!](https://tio.run/##hU7LCsJADLz7HR42MA3dZ/XQq5/gfakuFGyFdoV68dfXSMWbGjJMEmaSTCW1Jd3GLvfXUS2Up7u6DOqoH4wFc98eaNtdqSQVZz7FHDlNcTirIeapX1SnHDwCNAwsSRJtvko9ezjW0LUUDTcIHIQNNO9Rs2yS3rIV7GTWiNjACOwbRnziIYSfdzQq0aNy61v4MNev0AT3x7@6PEkSlSc "R – Try It Online")
Notes:
* Takes input as a data frame (which is what `lm` expects)
* `lm` would in principle work even without formula with input of indicated format, but it is needed for the constant regression case
* `si=F`, short for `singular.ok=FALSE`
throws an error for singular case, which is then caught by `try`, eventually returning nothing and printing the error as debug info.
Otherwise, the regression would actually return some output, but not the
expected one.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~18 15~~ 10 bytes
```
llZ(GlZ)Y\
```
Basically works the same as my Octave program. Thanks for -5 bytes @LuisMendo! This improvement was achieved by inputting the ones directly into the input instead of deleting a column and concatenating another one as well as some reordering of the steps.
**Explanation**
```
ll push two ones for later use in the next line
Z( implicitly take the input and plug in all ONES in to the FIRST column
Gl push input again, push a one for use in the next line
Z) get the FIRST column of the input matrix
Y\ multiply this column with the pseudo inverse of the matrix from the beginnign
```
[Try it online!](https://tio.run/##y00syfn/PycnSsM9J0ozMub//@hoE2tTa7NYnWhDayNr49hYAA "MATL – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~41 33~~ 32 bytes
The whole magic happens at the `\`: This operator left multiplies the second argument with the inverse of the first. If there is no inverse, it uses a suitable pseudo inverse. `x(:,1)` extracts the first column \$ Y \$ and `[x(:,1).^0,...]` adds a column of ones to the remaining part \$ X \$ such that we also get the intercept `beta0`.
Thanks @LuisMendo for -1 byte!
```
@(x)[(t=x(:,1)).^0,x(:,2:end)]\t
```
[Try it online!](https://tio.run/##TU7RioMwEHz3K/JyoBCX7MYk2qVw/3CPngfS6lGwelR71K/3Vm3hAkMms5mZHU5T/dss7REAlvf4kZTxdHzEB41JAl9Gr5QOTX9Oqs9p4aiNyzJjx77SJTKxraokeiutxirahg4cZ4CMRkiAwB683LT@h4INiFsUC1aQM0KQSQbEJLBPkHjFt2cTIAY0zmgEtA6RSEuMswX5/NmKnIqT0@y1Fv9jYNaDe1qKYAmLIgTtvQuuyMEWxpPEp7sQRJB0pEoNN/Wh4rqf1Wk4N6qVdy30@nOf6uky9HXXzWq89N/3rr6pcR6n5pq8Ntq62W21ykK0/AE "Octave – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 30 bytes
Adapted from @flawr
```
!x=[(t=x[1]).^0 x[2:end]...]\t
```
[Try it online!](https://tio.run/##XY7BisMwDETv/oqUXhJQhEeO7bjQL3FVWNgeWkpYlizk77My20NZw2Axkubp8fO8f2Db98N2rv163ip04Kvvtiqn2/KpzKyXdf/6vi/rc@kPfa0TRUpKXQUJBdVh6NyxBoI69z4XOdLEIHgrMmdKnOwXpQou5NmCzAkcTDOBs3UmFhJTeEls1/YaxSDCQIaP3qYRIiDScmIokuZ/eNBoETROjdcupbeKfXt4xY7gICgl240p5lhmDsUnMc74Z2QzDAPRzrn9Fw "Julia 1.0 – Try It Online")
] |
[Question]
[
The partitions of an integer **N** are all the combinations of integers smaller than or equal to **N** and higher than **0** which sum up to **N**.
A relatively prime partition is an integer partition, but whose elements are *(overall)* coprime; or in other words, there is no integer greater than 1 which divides all of the parts.
# Task
Given an integer as input, your task is to output the count of relatively prime partitions it has. Rather not surprised that there is an [OEIS sequence](https://oeis.org/A000837) for this. The aim is to shorten your code as much as possible, with usual code golf rules.
Also, you don't have to worry about memory errors. Your algorithm must only theoretically work for an arbitrarily big values of **N**, but it is fine if your language has certain limitations. You can assume that **N** will always be at least 1.
# Test cases and Example
Let's take `5` as an example. Its integer partitions are:
```
1 1 1 1 1
1 1 1 2
1 1 3
1 2 2
1 4
2 3
5
```
From this, the first 6 only are relatively prime partitions. Note that the last one (formed by the integer in question only) must not be taken into account as a relatively prime partition (except for **N**=1) because its GCD is **N**.
```
N -> Output
1 -> 1
2 -> 1
3 -> 2
4 -> 3
5 -> 6
6 -> 7
7 -> 14
8 -> 17
9 -> 27
10 -> 34
```
[Answer]
# JavaScript (ES6), ~~130~~ 120 bytes
```
f=(n,d=n)=>d&&(n%d?0:(M=n=>n%++k?k>n||M(n):n/k%k&&-M(n/k))(n/d,k=1)*(P=n=>!k|n<0?0:n?P(n,k--)+P(n-++k):1)(k=d))+f(n,d-1)
```
### Demo
```
f=(n,d=n)=>d&&(n%d?0:(M=n=>n%++k?k>n||M(n):n/k%k&&-M(n/k))(n/d,k=1)*(P=n=>!k|n<0?0:n?P(n,k--)+P(n-++k):1)(k=d))+f(n,d-1)
for(n = 1; n <= 30; n++) {
console.log('a(' + n + ') = ' + f(n))
}
```
### How?
This is recursively computing:
```
/ \ / \
| (M = n => | | (P = n => |
| n % ++k ? | | !k | n < 0 ? |
| k > n || | | 0 |
| M(n) | | : |
sum | : | * | n ? | for d in divisors(n)
| n / k % k && | | P(n, k--) + |
| - M(n / k) | | P(n - ++k) |
| )(n / d, k = 1) | | : |
| | | 1 |
| | | )(k = d) |
\ / \ /
Möbius(n / d) npartitions(d)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 7 bytes
```
/iM./Q1
```
**[Test suite.](https://pyth.herokuapp.com/?code=%2FiM.%2FQ1&input=10&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&debug=0)**
### Explanation
```
/iM./Q1 | Full program.
|
./Q | The integer partitions (./) of the evaluated input (Q).
iM | Get the GCD (i) of each (M).
/ 1 | Count (/) the 1's (1).
```
Pyth's behaviour comes in handy, since mapping with a 2-argument function automatically folds the command on the list, and the GCD of a one-element list is the element itself, so we don't have to handle that separately.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 39 bytes
This sequence ([A000837](https://oeis.org/A000837)) is the Möbius transform of the partition numbers ([A000041](https://oeis.org/A000041)).
```
n->sumdiv(n,d,moebius(n/d)*numbpart(d))
```
[Try it online!](https://tio.run/##DcpBDsAQEADAr0hPq1lpPYC/kK3GwZJFv68uc5oWJJu3reQWG99nofwBI2GpT8yzA1@kT54ltiADSOuVqgA7i/bGJpkHsDqU8ZsErHf4AQ "Pari/GP – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes
```
Count[GCD@@@IntegerPartitions@#,1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zm/NK8k2t3ZxcHBwTOvJDU9tSggsagksyQzP6/YQVnHMFbtf0BRZl6JQ5qD5X8A "Wolfram Language (Mathematica) – Try It Online")
This is my first Mathematica submission. *Thanks to [alephalpha](https://codegolf.stackexchange.com/users/9288/alephalpha) for -4 bytes!*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Œṗg/€ċ1
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7p6frP2pac6Tb8P@jxq1Bh9uBnP8A "Jelly – Try It Online")
[Answer]
# [Swift](https://swift.org), ~~202~~ 185 bytes
*Saved 17 bytes thanks to @Mr.Xcoder*
```
func p(_ n:Int,_ m:[Int]=[])->[[Int]]{return 0<n ?(1...min(m.last ?? n,n)).flatMap{p(n-$0,m+[$0])}:[m]}
{n in n>1 ?p(n).filter{a in !(2...n).contains{m in !a.contains{$0%m>0}}}.count:1}
```
[Try it online!](https://tio.run/##Rc7BasQgEAbge59iuqSg1Igpe5Jucu6hTyCyyBJBiBMxk/YgPntq9tLbz8f/D7P9Bk/X4/A7PiCxO6D@QhJ3iNq0YG/G8n40z2xLnmnPCOoTYWKDlDIGZFEubiOYJkCBnEu/OPp2qSSGfadEfDedsrxqE219@XEZ/K0gBAQcB5haq03CQnMu7tRX9tEON3ysSC7gVuKT3T906i2OqtbaaEfSQz38miGcvfOrQZWUAxILwrPAxTYnlx2tWV@gH@HC6/EH)
## Explanation
```
func p(_ n:Int,_ m:[Int]=[])->[[Int]]{// Recursive helper function p where p(n, prefix) is
// a list of all possiblie partitions of n
return n > 0 ? // If n > 0:
(1 ... min(m.last ?? n, n)) // For i in range from 1 to min(n, last value in prefix):
.flatMap{p(n - $0, m + [$0])} // Add p(n - i, prefix + i) to the return list
: // Else:
[m] // Return just the prefix
}
{n in // Main function:
n > 1 ? // If n > 1:
p(n).filter {a in // Take the list of possible partitions of n where
!(2...n).contains{m in // there is no integer m in the range from 2 to n where
!a.contains{$0%m>0} // all elements in the partitioning divide m
}
}.count // and return the length of the list
: // Else (if n == 1):
1} // Return 1
```
] |
[Question]
[
A [Directed Acyclic Graph (DAG)](https://en.wikipedia.org/wiki/Directed_acyclic_graph) is a type of graph that has no cycles in it. In other words, if there is a link from node A to node B, there exists no path from B to A (via any nodes).
# Challenge
Determine whether the directed graph given as input is acyclic.
# Input
A list of lists of integers representing the links between nodes, where a node is identified by its index in the list.
# Output
Standard I/O for decision problems; generally a truthy value for acyclic graphs, and a falsy one for cyclic graphs. Additionally, your program may halt/not halt to indicate truthy and falsy, if you wish.
# Test Cases
```
[[1, 2], [3, 4], [5], [], [6], [6], []]
```
Represents the following graph (where all edges are directed downwards):
```
0
/ \
1 2
/ \ /
3 4 5
| /
6
```
This example is acyclic, so the result should be truthy.
```
[[1, 3], [2], [0], [1]]
```
Represents the following graph:
```
-----<-----<----
/ \
0 --> 3 --> 1 --> 2
\---->----/
```
This example is cyclic, so the result should be falsey. (Sorry for my terrible drawing; if this is unclear let me know.)
# Constraints
* No input will ever be invalid; i.e. no node will link to a node that does not exist
* Self loops *must* be handled (`[[0]]` is a cyclic graph)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the fewest bytes in each language wins.
[Answer]
# Mathematica, ~~80~~ ~~44~~ ~~40~~ ~~30~~ 22 bytes
```
#//.x_:>#[[Union@@x]]&
```
Uses 1-based indexing for input. Returns an empty list iff the graph is acyclic.
### Example:
```
In[1]:= #//.x_:>#[[Union@@x]]&[{{2,3},{4,5},{6},{},{7},{7},{}}]
Out[1]= {}
In[2]:= #//.x_:>#[[Union@@x]]&[{{2,4},{3},{1},{2}}]
Out[2]= {{2, 4}, {3}, {1}, {2}}
In[3]:= #//.x_:>#[[Union@@x]]&[{{1}}]
Out[3]= {{1}}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
µị³FµL¡
```
A full program, printing no output for an acyclic input; or some output for a cyclic input.
**[Try it online!](https://tio.run/nexus/jelly#@39o68Pd3Yc2ux3a6nNo4f///6OjjXQUTGJ1FKKNQYQhiDCKjQUA)**
### How?
```
µị³FµL¡ - Main link: list of lists of natural numbers, g
µ µ ¡ - repeat
L - length times:
³ - program's 3rd command line argument, 1st program input, g
ị - index into
F - flatten (makes a list of nodes that are reachable, possibly with repeats)
- implicit print - If cyclic: it contains integers, and the Jelly representation
is a `[]` enclosed `, ` separated string of them.
If acyclic: it contains nothing, anf the Jelly representation
is an empty string (the `[]` is not even printed)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 70 bytes
```
f=lambda G,s=0,v=-1:G[s:]and all(f(G,s+1,x)for x in(G+[sum(G,[])])[v])
```
[Try it online!](https://tio.run/nexus/python2#RY/BCoMwDIbP8ylytJiBbbcdhJ59iJCDQwKCuqGd@PYuVeag@UOa8CX/JqFvhmfbQI1zKHEJV1vVNFfcjC00fZ9Lrp3C4mrkNcEK3ZjXBc2fQf@JDRta2GzRQgAii@AYgTzCLeV7khSPU5iz6PZhRipT5f@VBtpD0f0yep3K5NzgE2ZfUyax2pWDmHBy4o6nd6Qz6ICohVotAEWL0WH0KBbFoXiusst76sYI6ths2Rc "Python 2 – TIO Nexus")
An n-vertex graph is cyclic only if one can take an n-step path. In an acyclic graph, no vertex on the path can repeat so it must hit a dead end.
This recursive function tries all paths in the graph `G`, tracking the current number of steps `s` and current vertex `v`. Once `s` is at least `len(G)`, we the Falsey value of `[]` is returned. To allow the walk to start on any vertex, the initial phantom vertex `v=-1` connects to every (reachable) node of `G`, extracted as `sum(G,[])`.
An iterative version tied in length.
**[Python 2](https://docs.python.org/2/), 70 bytes**
```
G=input()
r=sum(G,[])
for _ in G:r=sum([G[v]for v in r],[])
print[]==r
```
[Try it online](https://tio.run/nexus/python2#@@9um5lXUFqioclVZFtcmqvhrhMdq8mVll@kEK@QmafgbgURjnaPLosFiZaBRItiwaoKijLzSqJjbW2L/v@PjjbUUTCK1VGINtZRMAHRpiAChM3gRGwsAA "Python 2 – TIO Nexus")
[Answer]
# [Haskell](https://www.haskell.org/), 28 bytes (halts or doesn’t halt)
```
f g|let s=(>>=s.(g!!))=g>>=s
```
[Try it online!](https://tio.run/##PYe9CoAgAAZf5cvJQIJ@N3uCtkYRFDKLLCpt690Nl4a74xbtN@NcjDPs60yA57TvuS@ozbI85zZN3PV6gGOGECVDJRlEzdCktkmJ7peUUN5cCucTxnAPB8iiXTATiR8 "Haskell – Try It Online")
For any list `xs` of nodes, `s xs` = `xs >>= s . (g !!)` = `[y | x <- xs, y <- s (g !! x)]` does a recursive search through all nodes reachable from them. We run this on all nodes in the graph with `g >>= s`.
# Haskell, 36 bytes (returns `True` or `False`)
```
f g=null$foldr(=<<)(id=<<g)$(g!!)<$g
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00h3TavNCdHJS0/J6VIw9bGRlMjMwVIpWuqpNvZRWukKypqxv7PTczMU7BVSMnnUlAoKMrMK1HQSFOIjjbUUTCK1VGINtZRMAHRpiAChM3gRGysJoYeY5AEWKMBiDAEqvkPAA "Haskell – Try It Online")
For any list `xs` of nodes, `(g!!) =<< xs` = `[y | x <- xs, y <- g !! x]` is the list of endpoints of all edges starting at nodes in `xs`. Now if `g` has length *n*, then
`foldr(=<<)(id=<<g)$(g!!)<$g`
= `foldr (=<<) (id =<< g) [(g!!), (g!!), …, (g!!), (g!!)]` (*n* repetitions)
= `(g!!) =<< (g!!) =<< … =<< (g!!) =<< (g!!) =<< id =<< g`
= `(g!!) =<< (g!!) =<< … =<< (g!!) =<< (g!!) =<< concat g`
= `(g!!) =<< (g!!) =<< … =<< (g!!) =<< (g!!) =<<` [endpoints of all edges, i.e., paths of length 1]
= `(g!!) =<< (g!!) =<< … =<< (g!!) =<<` [endpoints of all paths of length 2]
= …
= `(g!!) =<<` [endpoints of all paths of length *n*]
= [endpoints of all paths of length *n* + 1],
which is `null` if and only if the graph is acyclic.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 20 bytes
```
⍳∘≢∨.∊⊂{⍵∪∊⍺[⍵]}⍣≡¨⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04Dko97NjzpmPOpc9Khjhd6jjq5HXU3Vj3q3PupYBeL07ooGcmJrH/UuftS58NCKR12L/v9P0zBUMNLUMFYw0dTQMdV81LtGQ8dME4SBTC6QrDGQB1ShYwDEhpoA "APL (Dyalog Classic) – Try It Online")
[Answer]
## Mathematica, 82 bytes
```
AcyclicGraphQ[g=Graph[Join@@Thread/@Thread[Range@Length@#->#]]]&&LoopFreeGraphQ@g&
```
[Answer]
# [Python 2](https://docs.python.org/2/), 53 bytes
```
f=lambda i:map(f,l[i]);l=input();map(f,range(len(l)))
```
Crashes if and only if the graph is cyclic, due to infinite recursion. Takes input via stdin.
[Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJBplZtYoJGmkxOdGatpnWObmVdQWqKhaQ0RLUrMS0/VyEnN08jR1NT8/z86OlYn2iA2FgA "Python 2 – TIO Nexus")
[Answer]
## JavaScript (ES6), 98 bytes
```
f=(a,b=[...a.keys()],c=b.filter(i=>b.some(b=>a[b].some(b=>b==i))))=>1/b[c.length]?f(a,c):!(1/c[0])
```
Returns `true` for acyclic, `false` for cyclic. Explanation: Starting with the set `b` of all the nodes in `a`, the subset of all nodes of `b` which are the target of a link is iterated until it doesn't change. If the resulting subset is empty then the graph is acyclic.
] |
[Question]
[
My Python 3 function `golf(...)` should take a list of lists of lists of strings representing a solid cube and return whether there are any places in which two equal strings are directly next to each other on the x, y or z axis (not diagonally).
If there are no adjacent duplicates, True shall be returned, else False.
The input list and all of its sublists have the same length as they represent a cube, and their length is greater than 1 but lower than or equal to 5. The only possible values for the Strings inside the nested lists are "X" and "Z".
The maximum code length should be less than 200 bytes.
This is an example test case:
```
golf([[["X", "Z"],
["Z", "X"]],
[["Z", "X"],
["X", "Z"]]]) == True
golf([[["X", "Z"],
["Z", "X"]],
[["X", "Z"],
["Z", "X"]]]) == False
```
My current solution has 234 bytes:
```
def golf(c):
r=range(len(c));R=[(a,b)for a in r for b in r];j="".join
return all("XX"not in l and"ZZ"not in l for l in[j(c[x][y][z]for x in r)for y,z in R]+[j(c[x][y][z]for y in r)for x,z in R]+[j(c[x][y][z]for z in r)for x,y in R])
```
How can I golf this code any further to save another 35 bytes?
[Answer]
# Python 3, ~~108~~ 107 bytes
Since the cube only contains the strings `"X"` and `"Z"`, there are only two valid cube patterns. The one that starts with `XZXZX...` and the one that starts with `ZXZXZ...`.
My solutions generates these 2 cubes and checks if the inputted cube is one of them.
`def golf(l):L=len(l);r=range(L);return l in[[[list("XZ"*L)[(i+j+k)%2:][:L]for j in r]for k in r]for i in r]`
`i` iterates over the possible cubes. Since the dimension is at least 2, we can reuse `r` instead of writing `for i in(0,1)`.
[Answer]
## Python 3, 60 bytes
```
golf=g=lambda l:all(g(a)*g(b)*(a!=b)for a,b in zip(l,l[1:]))
```
The function recursively decides whether an N-dimensional array is alternating by checking if:
* Any two adjacent elements are unequal
* Each element is alternating
This successfully bottoms out for the strings `'X'` and `'Z'` because their length is `1`, so the `all` is taken of an empty list.
[Answer]
# Python 3 with NumPy, 125 bytes
```
import numpy
def golf(a):a=numpy.array(a);return(a[:-1]!=a[1:]).all()&(a[:,:-1]!=a[:,1:]).all()&(a[:,:,:-1]!=a[:,:,1:]).all()
```
# Python 3, ~~146~~ 128 bytes
```
e=lambda x,y:x!=y
z=lambda f:lambda*l:all(map(f,*l))
u=lambda f,g:lambda a:z(f)(a,a[1:])&z(g)(a)
golf=u(z(z(e)),u(z(e),u(e,id)))
```
] |
[Question]
[
The standard long addition method:
>
> The standard algorithm for adding multidigit numbers is to align the addends vertically and add the columns, starting from the ones column on the right. If a column exceeds ten, the extra digit is "carried" into the next column. ([wikipedia](https://en.wikipedia.org/wiki/Addition#Carry))
>
>
>
A long addition example:
```
145
+ 98
-----
243
```
Backwards long addition is similar but you start adding from the leftmost column and carry to the next column (on it's right). If the last (ones) column produces a carry you write it behind the current sum in the next column. If there is no carry in the last column no extra column is needed.
```
145
+ 98
-----
1341
```
Explanation for the above example by columns, left to right: `1 = 1; 4+9 = 10(carried) + 3; 5+8+1(carry) = 10(carried) + 4; 1(carry) = 1`
You should write a program or function which receives two positive integers as input and returns their sum using backwards long addition.
## Input
* Two positive integers.
## Output
* An integer, the sum of the two input numbers using backwards long addition.
* There should be no leading zeros. (Consider `5+5=1` or `73+33=7`.)
## Examples
Format is `Input => Output`.
```
1 3 => 4
5 5 => 1
8 9 => 71
22 58 => 701
73 33 => 7
145 98 => 1341
999 1 => 9901
5729 7812 => 26411
```
[Answer]
# Pyth, 16 bytes
Still new to Pyth, but this looks promising..
```
s_`smvs.[_d0lzcz
```
The idea here is simple. To do backwards addition, you need backwards numbers. We take the input, reverse it, make sure that it has same number of digits be adding trailing 0, sum the two numbers, reverse it again and make sure no leading zero exists.
**Code expansion**
```
cz # Take the input and Python split it. Splits on space automatically
m # Now we map over these two strings
_d # Reverse the string
.[ 0lz # Pad it with 0 on right so that its length is same as input length
vs # We have array of character and number, stringify and eval
s # Sum the numbers in array
` # Stringify
_ # Reverse
s # Convert back to number, removing leading 0
```
[Try it online here](http://pyth.herokuapp.com/?code=s_%60smvs.%5B_d0lzcz&input=5729%207812&debug=0)
[Answer]
# Python 2, ~~80~~ 78 Bytes
I didn't intend to have to reverse at the end, but apparently I need to.. I will fix this (maybe)!
*Thanks to Alex A. for saving 2 bytes, and flornquake for saving 3 bytes!*
```
a,b=input();s=0
while a+b:s=s*10+a%10+b%10;a/=10;b/=10
print int(str(s)[::-1])
```
Input like so: `num1, num2`.
[Answer]
# CJam, 22 bytes
```
q:QS/{W%Q,0e]s~}/+sW%~
```
This is pretty much the same algorithm as the Pyth answer, just a bit longer due to different syntax.
**Code expansion**
```
q:Q e# Read the input and store it in Q
S/ e# Split the input on space.
{ }/ e# Now we map over the two values in the array
W% e# Reverse the number treating it like a string
Q,0e] e# Right pad it with enough 0 to make its length same as input
s~ e# Convert to string and evaluate to get integer
+s e# Sum the two numbers and convert the sum to string
W%~ e# Reverse the sum as a string and evaluate to remove leading 0
```
[Try it online here](http://cjam.aditsu.net/#code=q%3AQS%2F%7BW%25Q%2C0e%5Ds%7E%7D%2F%2BsW%25%7E&input=5729%207812)
[Answer]
# CJam, 26 bytes
This is the first time I'm using CJam, I don't know many operators yet so it's surely sub-optimal. Gotta start somewhere :)
```
l~]$~s_,@s\0e[sW%i\W%i+sW%
```
[Try it online](http://cjam.aditsu.net/#code=l~%5D%24~s_%2C%40s%5C0e%5BsW%25i%5CW%25i%2BsW%25&input=145%2098).
Ungolfed:
```
l~ e# Takes input
]$~ e# Wrap in array, sort and unwrap
s_, e# Convert highest to string, push length
@s\ e# Setup stack for padding (["hi" "lo" len])
0e[s e# Left pad with zeroes and convert to string
W%i\ e# Reverse digits, convert to int, swap stack
W%i+ e# Reverse digits, convert to int, sum
sW% e# Convert result to string and reverse digits
e# Stack is automatically printed
```
[Answer]
# Bash + coreutils, 62
Not sure if this counts or not, but it does give the right answers (for 32-bit integers):
```
r()(printf %09d#01 $1|rev)
rev<<<$[`r $1`+`r $2`]|sed s/^0\*//
```
### Test output:
```
$ for t in "1 3" "5 5" "8 9" "22 58" "73 33" "145 98" "999 1" "5729 7812"
do ./backlongadd.sh $t; done
4
1
71
701
7
1341
9901
26411
$
```
[Answer]
# Java, ~~337~~ 312 bytes
Not quite a golfed language or solution, but it at least works and was fun to write. There's quite a few byte penalties to this approach, but I'm mostly happy with it.
```
void g(int a,int b){String p=(a>b?a:b)+"",o=(a>b?b:a)+"",s="";int m=p.length(),i=0,c=0,t;for(;i++<m;)o=(o.length()==m?"":"0")+o;for(i=-1;i++<m-1;){t=Integer.parseInt(p.charAt(i)+"")+Integer.parseInt(o.charAt(i)+"")+c;c=0;if(t>9){c=1;t=Integer.parseInt((t+"").charAt(1)+"");}s+=t;}System.out.print(s+(c>0?c:""));}
```
Input/Output:
```
g(8,9) --> 71
g(145,98) --> 1341
g(999,1) --> 9901
```
Spaced and tabbed out:
```
void g(int a,int b){
String p=(a>b?a:b)+"",
o=(a>b?b:a)+"",
s="";
int m=p.length(),
i=0,
c=0,
t;
for(;i++<m;)
o=(o.length()==m?"":"0")+o;
for(i=-1;i++<m-1;){
t=Integer.parseInt(p.charAt(i)+"")+Integer.parseInt(o.charAt(i)+"")+c;
c=0;
if(t>9){
c=1;
t=Integer.parseInt((t+"").charAt(1)+"");
}
s+=t;
}
System.out.print(s+(c>0?c:""));
}
```
[Answer]
# [O](http://esolangs.org/wiki/O), 22 bytes
```
ii`\`e@e@\-{0+}d#\#+`o
```
Padding zeros, can be golfed a lot.
[Answer]
## JavaScript (ES6), 112 bytes
```
g=(a,b,r=z=>+[...z].reverse().join``,x=(a<b?a:b)+'')=>r(r(y=(a<b?b:a)+'')+r('0'.repeat(y.length-x.length)+x)+'')
```
### Algorithm
1. Determine the smaller number (`x`)
2. Pads `x` with leading zeroes up to the length of the bigger number `y`
3. Reverse both strings, cast to integer, add them together and convert it back to a string
4. Reverse that string and cast to integer to get rid of leading zeroes
### Demo
As with all ES6 code, it only works in Firefox at time of writing:
```
g=(a,b,r=z=>+[...z].reverse().join``,x=(a<b?a:b)+'')=>r(r(y=(a<b?b:a)+'')+r('0'.repeat(y.length-x.length)+x)+'')
// For demonstration purposes
console.log = x => X.innerHTML += x + '\n';
console.log(g(1,3));
console.log(g(5,5))
console.log(g(8,9))
console.log(g(22,58))
console.log(g(73,33))
console.log(g(145,98))
console.log(g(999,1))
console.log(g(5729,7812))
```
```
<pre><output id=X></output></pre>
```
[Answer]
# Julia, ~~190~~ ~~173~~ ~~163~~ 160 bytes
```
f(a,b)=(n=ndigits;d=digits;m=max(n(a),n(b));C=reverse([0,d(a,10,m).+d(b,10,m)]);for i=1:m C[i+1]+=C[i]÷10;C[i]=C[i]%10end;c=join(C);int(c[end]=='0'?chop(c):c))
```
This creates a function `f` that accepts two integers and returns an integer.
Ungolfed + explanation:
```
function f(a,b)
# Determine the maximum number of digits between a and b
m = max(ndigits(a), ndigits(b))
# Create an array as the elementwise sum of the digits of
# a and b with a single trailing 0, where the digit arrays
# are left padded with zeros to each have length m
C = reverse([0, digits(a, 10, m) .+ digits(b, 10, m)])
# Carry digits as necessary
for i = 1:m
C[i+1] += C[i] ÷ 10
C[i] = C[i] % 10
end
# Join the array into a string
c = join(C)
# If the string has a trailing zero, lop it off, then
# convert the string to an integer and return it
int(c[end] == '0' ? chop(c) : c)
end
```
[Answer]
## PHP, 112 bytes
Same algorithm as [my JavaScript answer](https://codegolf.stackexchange.com/a/53244/22867). It's sad that PHP has the same amount of chars (unless my other answer can be golfed further). Then again, the built-in string functions and implicit conversions really helped.
```
function g($a,$b,$r='strrev'){echo$r($r($y=max($a,$b))+$r(str_pad($x=min($a,$b),strlen($y)-strlen($x),0,0)))+0;}
```
Unminified:
```
function g($a, $b) {
$y = max($a,$b);
$x = min($a,$b);
echo strrev(strrev($y) + strrev(str_pad($x, strlen($y) - strlen($x), 0, STR_PAD_LEFT))) + 0;
}
```
[Answer]
## Python 3, 92 bytes
For what it's worth (if anything), this function accepts an *arbitrary* number of inputs and adds them all.
```
r=lambda *a:int(str(sum(map(int,(format(n,'0>'+str(len(str(max(a)))))[::-1]for
n in a))))[::-1])
```
Ungolfed version:
```
def rsum(*summands):
l = len(str(max(summands)))
fmt = '0>' + str(l)
reverse_summands = (format(n, fmt)[::-1] for n in summands)
reverse_sum = sum(int(nrev) for nrev in reverse_summands)
return int(str(reverse_sum)[::-1])
```
It's the same approach as [Digital Trauma's answer](https://codegolf.stackexchange.com/a/53236/13959): pad the shorter number with leading zeroes, reverse them, add them, and reverse the sum. The bulk of the code is int-to-string-to-int-to... conversion.
[Answer]
# Pyth, 17 bytes
```
s_`isM.TmsMdc_z)T
```
An alternative method without 0 padding.
] |
[Question]
[
James Bond is about to start a new mission and you are his computer scientist friend. As Tic Tac Toe is becoming more and more popular you decide that nothing would be more underhanded than a **Tic Tac Toe encoder/decoder™**.
For each line the decoder will follow the following steps:
* Convert from 'O','X' and ' ' [space] to trinary
+ ' ' -> 0
+ 'O' -> 1
+ 'X' -> 2
* Convert from trinary to decimal
* Convert from decimal to letter
Example: **"XO "**
* 210
* 21
* v
The encoder will do the reverse.
As code is much more precise than words, see the reference answer below in which I give an example (very long) implementation of the problem in Python:
Your decoder should be able to decode all the messages encoded with my encoder correctly and my decoder should be able to decode all the messages encoded with your encoder.
This is code-golf, the shortest wins.
## Additional informations
* 0 must be converted to a, the alphabet ends with a whitespace, so 26-> ' ' [whitespace]
* "XXX" is the max, it translates to "222" that translates to 26.
* As in Tic Tac Toe the max line lenght is 3.
* `X -> 2` means X should be replaced by 2
* Encoder/Decoder
+ The encoder goes from plaintext to code.
+ The decoder goes from code to plaintext.
[Answer]
## BRAINFUCK, 393 bytes (encoder only)
Guys, we're making something for James Bond. Languages like javascript and C are way too readable! If you want something that the russians will never understand, brainfuck is the only option. It's surly not the shortest or fastest option, but no-one will understand it (and, let's be honest, everyone loves brainfuck)
The code has a couple of limitations though, It only encodes and only one character at a time. Also it doesn't manually stop, you have the stop it after it spits out the output. But hey, it works. This is the code:
```
>>>,>++++++++[<-------->-]<->+++<[>[->+>+<<]>[-<<-[>]>>>[<[-<->]<[>]>>[[-]>>+<]
>-<]<<]>>>+<<[-<<+>>]<<<]>>>>>[-<<<<<+>>>>>]<<<<[-<<+>>]+++<[>[->+>+<<]>[-<<-[
>]>>>[<[-<->]<[>]>>[[-]>>+<]>-<]<<]>>>+<<[-<<+>>]<<<]>>>>>[-<<<<<+>>>>>]<<<<<<
[->>>+<<<]+[[-]>[-<+<+<+>>>]<[>++++++++++++++++++++++++++++++++++++++++++++++
++++++<[-]]<-[>> ++++++++++++++++++++++++++++++++++++<<[-]]<--[>>>---<<<[-]]>>>.]
```
If you want to try it: just run the code with one capital letter as input.
If you want it commented just ask me nicely. A lot of things can be done better but I don't feel like optimizing it now (because brainfuck). Maybe I'll make a decoder too as reversing the process probably isn't that difficult.
[Answer]
# C++, 168 + 135 = 303 bytes
EDIT: saved one byte by requiring uppercase input
I like doing these in C++ because I get to do all sorts of fun nastiness I would never ever do in C++ code.
**Encoder (168):**
Takes a string of uppercase letters and spaces as an argument.
```
#include<cstdio>
int main(int h,char**c){c[0][3]=0;for(c++;h=**c;c[0]++){h=h&32?26:h-65;for(int d=2,e;d+1;d--){h=(h-(e=h%3))/3;c[-1][d]=e&2?88:e*47+32;}printf(c[-1]);}}
```
Readable:
```
#include<cstdio>
int main(int h,char**c)
{
c[0][3]=0;
for(c++;h=**c;c[0]++)
{
h=h&32?26:h-65;
for(int d=2,e;d+1;d--)
{
h=(h-(e=h%3))/3;
c[-1][d]=e&2?88:e*47+32;
}
printf(c[-1]);
}
}
```
**Decoder (135):**
Takes a string of X, O, and space as an argument.
```
#include<cstdio>
int b=9,v;int main(int h,char**c){for(c++;h=**c;c[0]++){v+=(h&16?2:h&1)*b;b/=3;if(!b)putchar(v==26?32:v+97),v=0,b=9;}}
```
Readable:
```
#include<cstdio>
int b=9,v;
int main(int h,char**c)
{
for(c++;h=**c;c[0]++)
{
v+=(h&16?2:h&1)*b;
b/=3;
if(!b)putchar(v==26?32:v+97),v=0,b=9;
}
}
```
[Answer]
# CJam, 24 + 25 = 49 bytes
**Encoder**
```
qN/{:i40f/3b'a+_'{=S@?}%
```
**Decoder**
```
q{_Sc=26@'a-?Zb" OX"f=N}%
```
[Try it online here](http://cjam.aditsu.net/)
[Answer]
## Javascript, ES6, 157 chars
### Only encoder, 83
```
f=s=>s=="XXX"?" ":(parseInt(s.replace(/./g,x=>" OX".indexOf(x)),3)+10).toString(36)
```
### Only decoder, 77
```
g=s=>(parseInt(10+s,36)-10).toString(3).substr(-3).replace(/./g,x=>" OX"[x])
```
### Both, 157
```
p=parseInt;f=s=>s=="XXX"?" ":(p(s.replace(/./g,x=>" OX".indexOf(x)),3)+10).toString(36);g=s=>(p(10+s,36)-10).toString(3).substr(-3).replace(/./g,x=>" OX"[x])
```
### Test
```
console.log(x=[" ", "XO ", "XXX"], x=x.map(f), x.map(g))
```
PS: Tried to perform some optimization, but failed: resulting code was longer then just concatenation. I don't publish it as it also contains a bug, which had already been fixed.
[Answer]
## R, 121 + 115 = 236
I think I got the spec correct
**Decoder Function 121**
```
d=function(s){i=rev(as.integer(unlist(strsplit(chartr('XO ','210',s),''))));c(letters,' ')[sum(3^(0:(length(i)-1))*i)+1]}
```
**Encoder Function 115**
```
e=function(s){i=which(c(letters,' ')==s)-1;paste(chartr("210","XO ",c(i%/%9%%3,i%/%3%%3,i%%3)),sep='',collapse='')}
```
This only works on lower case characters. Is that a requirement?
Quick Test
```
> mapply(d,c("OO "," OO"," OO","X O","XXX"))
OO OO OO X O XXX
"m" "e" "e" "t" " "
> mapply(e,unlist(strsplit('meet ','')))
m e e t
"OO " " OO" " OO" "X O" "XXX"
```
[Answer]
# [Go](https://go.dev), 372 bytes \$= 29 + 171 + 170\$
* Imports = 29 bytes
* Decoder = 171 bytes
* Encoder = 170 bytes
```
import(."strings";."strconv")
func d(s string)(k string){for _,l:=range Split(s,"\n"){i,_:=ParseInt(NewReplacer(" ","0","O","1","X","2").Replace(l),3,64)
k+=string('A'+i)}
return ReplaceAll(k,"["," ")}
func e(s string)(k string){q:=ReplaceAll(s," ","[")
for _,r:=range q{k+=NewReplacer("0"," ","1","O","2","X").Replace(FormatInt(int64(r-'A'),3))+"\n"}
return Trim(k,"\n")}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fZHdSsMwFMfxtk9xCIgJi8MvRCa9mKx-XLiOOaWgYMvWjrI2nUmm4NiTeDMEX8JH8Wk8SVs_cA56muT8_4fzO8nL67hYvk-j4SQax5BHqXDSfFpIDU2S5Jq8zXSyffSxocssbRKlZSrGihzb7bAQj4Q5yUwMYUQVlCqjk3o3TwoJ9zxruTIS2OJqmqWaKk7uBGHzlN-33F4kVXwhNO3GT_14mkXDWFIChJMdDB9jFyPA2COsWTloxvg-PzxgzqThlr3oVnurkbKFI2M9kwIqZzvL6ISTW6wHgqpljVeyPrTcH0WKW4hbM58dQtZDPMyx6S_aHVKadyviPUv8TXtayDzSZshU6MMDKrcRFidgrGFu4ot5INPc0JrbWdSX_2yRzeNQBnPnMZJQ0zs9_OuEknBThVjERzQMfAgZW6kEwT8KgK1Rbuj74Pi--QLACAKnyphtAOaIaukxGZtF1a89vi0xFnuqXPZsqsIV7VUNleGEBuLmryu2LtRgjdZeo1163gAuPbjudrw-DM496HsdOOlfdM68_8qqJ1guy_UT)
### Explanation
#### Decoder
```
import(."strings";."strconv")
func d(s string)(k string){
for _,l:=range Split(s,"\n"){ // for each line...
i,_:=ParseInt( // turn the string into an int
NewReplacer(" ","0","O","1","X","2") // define the replacements
.Replace(l), // replace the chars
3,64) // turn it into trinary
k+=string('A'+i)} // append to the output string
return ReplaceAll(k,"["," ")} // replace `[` with spaces
```
#### Encoder
```
import(."strings";."strconv")
func e(s string)(k string){
q:=ReplaceAll(s," ","[") // replace `[` with spaces
for _,r:=range q{ // for each character...
k+=NewReplacer("0"," ","1","O","2","X") // define the replacements...
.Replace( // and apply onto...
FormatInt(int64(r-'A'),3)) // the character, turned into trinary
+"\n"} // and add a newline
return Trim(k,"\n")} // trim the final newline
```
[Answer]
# Excel, 81 + 87 = 168 bytes
**Encoder**:
```
=CONCAT(SWITCH(0+MID(BASE(TEXT(CODE(A1)-97,"[=63]26"),3,3),{1,2,3},1),2,"X",1,"O"," "))
```
**Decoder**:
```
=CHAR(97+TEXT(MMULT(SWITCH(MID(A1,{1,2,3},1),"X",2,"O",1,),3^{2;1;0}),"[=26]63"))
```
Input in cell `A1` in both cases.
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 12 + 14 = 26 bytes
## Encoder, 12 bytes
```
.@.`@3%-$6 91=$"OX "
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWW_Qc9BIcjFV1VcwULA1tVZT8IxSUIFJQFQv25KamlijkpiqU5qWkFimUZKQqFKWmKCQVZaakp0LUAAA)
*-1 byte thanks to Dominic van Essen*
```
.@.`@3%-%$32~27=$"OX "
. For each character c in
@ the input as a string
. for each digit d in
`@3 convert to base 3
%$32 ord(c) mod 32
- ~ minus 1
% 27 mod 27
=$ take the d-th character (1-indexed, wrapping)
"OX " from "OX "
```
## Decoder, 14 bytes
```
*" "`%.;@+`@3.$%/$10 3'a'"{"
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWe7SUFJQSVPWsHbQTHIz1VFT1VQwNFIzVE9WVqpUgSqAqF9xM8PdX4PL3B6EIBSCOiOCCioCYEQogLlAWogYkAhYFyvrD1PiDtYCUgHlQVWA-SBfEIgA)
```
*" "`%.;@+`@3.$%/$10 3'a'"{"
*" " Join by spaces
`% "{" split on '{' characters
. for each line l in
;@ the input as a list of lines
+ 'a' add the character code of 'a' to
`@3 convert from base 3
. for each character c in
$ l
/$10 ord(c) divided by 10
% 3 modulo 3
```
I realized later that I could've simply used `?"OX"$` instead of `%/$10 3`. The byte count is equal.
[Answer]
Reference answer, completely ungolfed:
```
# Tic-Tac-Toe code encoder
def from_letter_to_decimal(letter):
alphabet = "abcdefghijklmnopqrstuvwxyz "
return alphabet.index(letter)
def from_decimal_to_trinary(decimal):
digits = []
while decimal:
digits.append(str(decimal % 3))
decimal //= 3
return ''.join(list(reversed((digits))))
def from_trinary_to_line(trinary):
replace_dict = {"0": " ",
"1": "O",
"2": "X"}
for char in replace_dict:
trinary = trinary.replace(char,replace_dict[char])
return trinary
def encode_letter(letter):
decimal = from_letter_to_decimal(letter)
trinary = from_decimal_to_trinary(decimal)
line = from_trinary_to_line(trinary)
return line
def encode_text(text):
return '\n'.join([encode_letter(letter) for letter in text])
print(encode_text("meet me under the red bridge"))
```
---
```
# Tic-Tac-Toe code decoder
boards = """
OO
OO
OO
X O
XXX
OO
OO
XXX
X X
OOO
O
OO
OXX
XXX
X O
XO
OO
XXX
OXX
OO
O
XXX
O
OXX
XX
O
X
OO
"""
def from_line_to_trinary(line):
replace_dict = {" ": "0",
"O": "1",
"X": "2"}
for char in replace_dict:
line = line.replace(char,replace_dict[char])
return line
def from_trinary_to_decimal(n):
result = 0
for position,i in enumerate(reversed(n)):
result += int(i) * 3**position
return result
def from_decimal_to_letter(n):
alphabet = "abcdefghijklmnopqrstuvwxyz "
return alphabet[n]
def decode_line(line):
trinary = from_line_to_trinary(line)
decimal = from_trinary_to_decimal(trinary)
letter = from_decimal_to_letter(decimal)
return letter
def decode_boards(boards):
return ''.join([decode_line(line) for line in boards.splitlines() if not line==""])
print(decode_boards(boards))
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 44 + 54 = 98 bytes
## Encoder
```
->s{[*?A..?Z," "][s.tr(" OX","012").to_i 3]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3dXTtiqujtewd9fTso3SUFJRio4v1Soo0lBT8I5R0lAwMjZQ09Ury4zMVjGNrIXq2Fii4RStF-APVckGYERFKsRC5BQsgNAA)
## Decoder
```
->c{((c<?A??[:c).ord-65).digits(3).join.tr"012"," OX"}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3zXTtkqs1NJJt7B3t7aOtkjX18otSdM1MNfVSMtMzS4o1jDX1svIz8_RKipQMDI2UdJQU_COUaiG6NxYouEUrhSnFcoEZCkqxEPEFCyA0AA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v1.4.5, 12 + 17 = 29 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
**Encoder**
```
;C+S gUn" OX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.5&code=O0MrUyBnVW4iIE9Y&input=WwoiICAgIgoiICBPIgoiICBYIgoiIE8gIgoiIE9PIgoiIE9YIgoiIFggIgoiIFhPIgoiIFhYIgoiTyAgIgoiTyBPIgoiTyBYIgoiT08gIgoiT09PIgoiT09YIgoiT1ggIgoiT1hPIgoiT1hYIgoiWCAgIgoiWCBPIgoiWCBYIgoiWE8gIgoiWE9PIgoiWE9YIgoiWFggIgoiWFhPIgoiWFhYIgpdLW1S)
**Decoder**
```
;C+S aU s" OX" ù3
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.5&code=O0MrUyBhVSBzIiBPWCIg%2bTM&input=WwoiYSIKImIiCiJjIgoiZCIKImUiCiJmIgoiZyIKImgiCiJpIgoiaiIKImsiCiJsIgoibSIKIm4iCiJvIgoicCIKInEiCiJyIgoicyIKInQiCiJ1IgoidiIKInciCiJ4IgoieSIKInoiCiIgIgpdLW1S)
I tried some options that worked with codepoints rather than indexing into `C+S`, but they always ended up being longer in order to handle the space.
#### Explanations:
```
;C+S gUn" OX
; # C = "abcdefghijklmnopqrstuvwxyz"
C+S # Add a space to the end of C
g # Get the character at index:
U # Input string
n" OX # Converted to base 10 from base " OX"
```
---
```
;C+S aU s" OX" ù3
; # C = "abcdefghijklmnopqrstuvwxyz"
C+S # Add a space to the end of C
aU # Find the index of the input string
s" OX" # Convert to base " OX"
ù3 # Left pad with spaces to length 3
```
[Answer]
# [Scala](https://www.scala-lang.org/), 90+107=197 bytes
Port of [@Jordan's Ruby answer](https://codegolf.stackexchange.com/a/253466/110802) in Scala.
---
### Encoder
Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=bY6xasMwFEV3f8VDy5NQY9pmKQYZQqcOxUMoiIQMr67sOjiyK6mFEvwlXby0_5S_qVJ1zPTO5V7evV8_vqaelvOpGp73pg7wSJ2FYwbwYho4RMHJtb6AlXP0uV0H19l2Jwp4sl0AFZPZB_XQFDxZqrx_JSdAfb-HZnF32nhVco4rDANuUEi5Nm8cAYXgDzaY1rh8JOdNFNznBxqPNXmDFaoSb_CP9ZlvE8OZr3G6Wgrx36DjVoAxlofecrZlUjac6QqYyMOQVknJdkxcDmp9KThlU_o_z-n-Ag)
```
s=>(('A'to'Z')++Seq(' '))(Integer.parseInt(s.map{case'O'=>'1'case'X'=>'2'case' '=>'0'},3))
```
Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=bZGxTsMwEIbFmqf45cW2XCKgC6pUpIqJAXWokCKqDtfESVOliXEMAqG8Ai_A0gUeiqfB1KSqqk72_f93vjvf53ebUkXD7fbr2eXn1z9nH81yrVOHeyprvEdApnNsfCDIFu0IE2vpbT5ztqyLhRzhoS4dxjsysLnwVPC9fbsiu7eBF6pAlVnRUv9lCT7hcA34I5dQCjP9JDi4PKA3ZIzOPNvG_rp_CEip1eBTjvEN-CU_0pOgXx3rCPpFr3cHpcrs1de5q50utI0N2Vb7QIQOBhj2bfUDCJ8QtC7aHcYP7apasDlTKhcsmYLJ2DXhN5RiCyZPg0lyCuyiLqzlfzv9ln4B)
```
object Main {
def main(args: Array[String]): Unit = {
def f(s: String): Char = {
val alphabet = ('A' to 'Z') ++ Seq(' ')
val mapped = s.map {
case 'O' => '1'
case 'X' => '2'
case ' ' => '0'
}
val idx = Integer.parseInt(mapped, 3)
alphabet(idx)
}
println("["++f("XO ").toString++"]")
println("["++f("XXX").toString++"]")
}
}
```
### Decoder
Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=XY5NasMwEIX3PsVsykjQmPxAKU5kCIFAFqGL0h8IWUyVsevGUYKkBorxSbrxpr1TblM59qqzGb7HzHvv-9dpKmnSXG6Obx-sPaypMFBF0ZlKWCZi8U5WpY_eFiaXoH4-fTa4v-y1Sqv2wqgiE3qGc5TjO-DSMehBoOnKeM7Zxv7Y_QpzO5HxgU6VJsc4RJUi4PQKoxYeehi38Ip1bPnM1nHdR74A7DiDQ6gnyOYugbm19LXp7LcygSdTeFChO4Q5BdWXRiwFPqOU_zXotDrq7Zum238)
```
c=>{val n=if(c<'A')26 else c-'A';Integer.toString(n,3).map{case'0'=>' ';case'1'=>'O';case'2'=>'X'}.reverse}
```
Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=XdDBSgMxEAZgvO5T_LckYBftgshixSIUPIgHUQTpYRpn15VtWpJYENkn8dKLPpRP47hZC_U4X2aS_PPxFSy1VGy3n6-xGp1-H1ysFi9sI66pcXjPgCeuMNO2xOUzeVPiNvrG1Zj0h8CGWjipmgra4gxqqgzGJ-A28K-Mesnj6srF3cCCAhcyJMY1ezlNt2p3iML0bX1LvqT18A5gRaCOFCbnUFB7epz0Zl_HSR-SdrnnDfvAUnXZkGwpMTX5OpSYek9vj-kjcwl655q4i7kWja3TM63ulTH_Dcm6rMvSIod9_u31Bw)
```
object Main {
def F(c: Char): String = {
val n = if (c < 'A') 26 else (c - 'A').toInt
val base3 = Integer.toString(n, 3)
base3.map {
case '0' => ' '
case '1' => 'O'
case '2' => 'X'
}.reverse
}
def main(args: Array[String]): Unit = {
println(F('V'))
println(F(' '))
}
}
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 + 18 = 36 bytes
Decoder:
```
(⊂3⊥⍉' O'⍳⎕)⌷27↑⎕A
```
Encoder:
```
' OX'[⍉3 3 3⊤⎕A⍳⎕]
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/x91tCukpCbnp6QWcWk86moyftS19FFvp7qCv/qj3s1AdZqPerYbmT9qmwhkO3IBlYOwQmoeRAtQXYR6NFCDsQIQPupaAlIF0RgLUvj/vwIYwKwAmqMe4a@grqAeERGhzqWrq8sFUQA3MExBHQA "APL (Dyalog Unicode) – Try It Online")
] |
[Question]
[
Given two numbers r and n on separate lines, write a program to print n natural numbers starting from 1 onwards, excluding the r-th powers. For example,
If `r=2` and `n=10`, the results would be `2,3,5,6,7,8,10,11,12,13`
4 and 9 were excluded because 4 is `2^2` and 9 is `3^2`
```
Sample Input
2
10
Sample Output
2 3 5 6 7 8 10 11 12 13
Sample Input
3
30
Sample Output
2 3 4 5 6 7 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 28 29 30 31 32 33
```
1. `1 < r < 10`
2. `0 < n < 1,000,000`
>
> Since nobody came up with this, here's
> a hint to reduce your solution sizes:
>
>
> The `i`th term of the output is given by
> `floor(i+pow(i+pow(i,1/r), 1/r))`.
>
>
>
[Answer]
## Golfscript, 18 characters
```
~.3*,.{3$?}%-@;<n*
```
Basically a direct port of my [Ruby solution](https://codegolf.stackexchange.com/questions/2529/remove-r-th-powers/2536#2536). Also probably not completely golfed yet, I'll take a look at it later today again.
[Answer]
## Ruby, 56 characters
```
r,n=$<.map &:to_i;puts ([*l=1..2*n]-l.map{|i|i**r})[0,n]
```
Pretty straightforward (and similar to [Lars' solution](https://codegolf.stackexchange.com/questions/2529/remove-r-th-powers/2535#2535)). Takes about 5 seconds to complete for `r = 2, n = 1000000` and 8 seconds for `r = 10, n = 1000000` here.
[Answer]
## Python 2, 84 83 80 chars
```
r,n=input()
r+=.0
i=c=1
while c<=n:
p=i**(1/r)
if p!=int(p):print i;c+=1
i+=1
```
Runs in about 3 seconds for r=2, n=1000000
[Answer]
**Python 68 Chars**
```
r=input();i=0;exec'i+=1;print int(i+(i+i**(1./r))**(1./r));'*input()
```
[Answer]
### Golfscript (18 17 chars)
```
~.3*,@{?}+1$%-<n*
```
This turns out to be similar to Ventero's solution, but slightly shorter (at time of writing!)
For a more efficient solution, 26 chars gives
```
~2.@{.2$4$?={)\)\}*.p)}*];
```
which uses the obvious algorithm:
```
int k = 2, x = 2;
for (i = 0; i < n; i++) {
if (pow(k,r) == x) {k++; x++;}
println(x++);
}
```
[Answer]
## Ruby (~~79~~ 77 chars)
```
n,r=$<.map &:to_i
a=(0..n*2).map{|x|[x,x**r]}.transpose
p (a[0]-a[1])[0,n]*?,
```
Yes, this does a lot of wasted effort, but it completes in about 8 secs
for n=1E6,r=10 on my laptop.
[Answer]
## Windows PowerShell, 88
```
for($x,$r,[int]$n=,1+@($input);$n--){if((1..$n|%{[Math]::Pow($_,$r)})-eq$x){$x++}($x++)}
```
Fairly straightforward, but probably way too long.
[Answer]
## [Qwerty RPN](http://www.shinkirou.org/projects/qwerty-rpn) (52)
```
@=r@=n>L$i)=i$i 1$r/^:\=<S$n(=n$i#32.>S 0$n=<B 1<L>B
```
Ungolfed
```
@ =r ; input number r
@ =n ; input number n, counter variable
0 =i ; the next number to be printed (pre-assigning variable is optional)
>loop ; label loop
$i ) =i ; pre-increase i
$i 1 $r / ^ : \ = <skipped ; skip printing and increasing counter n if i^(1 / r) == round(i^(1 / r))
$n ( =n ; decrease n
$i # ; print number i
32 . ; print space
>skipped
0 $n = <break ; if n == 0: break loop
1 ; TRUE
<loop ; go back to beginning of loop
>break ; this is where the loop ends
```
[Answer]
# J, 32
```
(4 :'y{.I.(~:<.)x%:i.1001000')/,
```
This assumes the input has the shape `2 1`, i.e., a vertical list of two rows with one atom per row, e.g.,
```
2
10
```
This solution is instantaneous for r = 9, n = 999999, which (unless I've misread the question) are the upper bounds for the input parameters.
[Answer]
## JavaScript, ~~118~~ 111 bytes
```
function d(r,n){for(var a=[],i=m=0,p=1;i<n;p++,m=Math.pow(p,1/r))if((m|0)!=m){a.push(p);i++}return a.join(" ")}
```
[Answer]
# Perl - 51
```
map{print$_.$/if($_**(1/$ARGV[0])!~/^\d+$/)}1..pop;
```
Not quite up to spec, as it takes ~12/13s for r=10/n=1000000, and takes r/n as command line args instead of on separate lines -- but other than that it works.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
+¹$r'¹Ėe:I≠
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%2B%C2%B9%24r%27%C2%B9%C4%96e%3AI%E2%89%A0&inputs=2%0A12&header=&footer=)
```
+¹$r # Input range
'¹Ėe # r-th root of each item in range
:I≠ # Filter roots with no fractional part
```
[Answer]
**C++, ~~97~~ ~~95~~ 90**
```
int main(){int r,s,n,m=0;cin>>r;cin>>n;s=r;while(m++!=n)r!=m?cout<<m<<' ',r*=r<m?s:1:++n;}
```
**(eventually +20)**
```
using namespace std;
```
[Answer]
**Scala 172**
```
def p(r:Int,n:Int)={def f(n:Int):Stream[Int]=n#::f(n+1);lazy val i=f(0);lazy val o=i.filter(a => math.pow(a,1.0/r)!=math.pow(a,1.0/r).toInt);print(o.take(n).mkString(","))}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 60 bytes
```
r,n=input();i=0
while n:
i+=1
if i**r**-1%1:
print i;n-=1
```
[Try it online!](https://tio.run/##DcTBCoAgDADQc37FLkEtBZe3ZJ9TOIglYkRfv3qHV99eLl3NmlcWrXef5iwc3VPk3EE3B7Iw/R8giA0x0EibG2oT7SBZA5NZ8il@ "Python 2 – Try It Online")
] |
[Question]
[
[Cops thread](https://codegolf.stackexchange.com/questions/241380/find-my-other-token-cops)
Robbers,
Write a program in the cop's language using the cop's P string and your own S string, and the amount of each of them specified in the cop's post. Your S string may not exceed the cop's S string in bytes.
### The program
Using only strings P and S, write a program which takes a list of 5 or more non-repeating positive integers, and returns them reordered such that the maximum of the list is in the center, the elements before it are in ascending order, and the elements after it are in descending order. You can output any list that meets these requirements. You may assume the list has an odd number of elements.
Examples (your outputs may differ):
```
input: [1,2,3,4,5]
output: [1,2,5,4,3]
input: [7,6,5,4,3,2,1]
output: [2,4,6,7,5,3,1]
input: [1,3,5,7,9,2,4,6,8]
output: [1,2,3,7,9,8,6,5,4]
```
For posterity, please specify your exact S string and its byte count in your answer, and link the cop which you are cracking.
### Scoring
Most cracks wins.
[Answer]
# [Crack](https://codegolf.stackexchange.com/a/241393/), 39 bytes
```
;_=(x,y)=>x[y.toString(32)]((x,y)=>y-x)
```
[Try it online!](https://tio.run/##bcpBCoMwEEDRfU8yQ8eASTSmJfYQXYpIsBosYopK0dOnEboq3fzN@0/7tks7D681mfyjC72xpgR31J7trYGqAUs8F1ogMcYcWKyJa6mFKqTMOV4swvFoybUSiOHaGNhoR1Nu1c5Wf1/nYXIgONbwhT3ZMLR@WvzYsdE76KFKiZMgSVmNePoxRTll0UR80j@eRslIkY4u41vEJ3wA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 21 + 33(32) bytes
```
def f(i):m=len(i)//2;i.sort();return i[:m]+i[:m-1:-1]
```
[Try it online!](https://tio.run/##VcpNDoMgEIbhvadwCelYMyL@QHoSw64QSRQM0oWnp@OmSTeTL@8zx5XXGEQpb@tqxzxX@2uzgUbbdto/z5gy4zrZ/Emh9ovazeO@DaoGTTmSD5k5tiB0IKAHaTjX1S@PMICkLIjxn5CihBFmop7eppvLFw "Python 3 – Try It Online")
Cracking this [one](https://codegolf.stackexchange.com/a/241550/110555). The S string is 32 bytes (1 shorter than expected)
```
i.sort();return i[:m]+i[:m-1:-1]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 63 bytes
```
x=>x.sort((a,b)=>a-b).map((e,i)=>i<L?e:x[L*3-i],L=x.length/2|0)
```
[Try it online!](https://tio.run/##DcdLDsIgEADQq7icMQNq6yexUi/ADZouppVWDEJTiGHh3dG3ey/@cBxXuyThw8OUSZWs2ixjWBMA04CqZTGgfPMCYMj@b2/6bq6509ta2J60ytIZP6fnrvrusTSbMfgYnJEuzDBBd6CKajrSic506RGb8gM "JavaScript (Node.js) – Try It Online")
Cracks [this one](https://codegolf.stackexchange.com/a/241389/106710).
The S-string is 37 bytes long:
```
(e,i)=>i<L?e:x[L*3-i],L=x.length/2|0)
```
My function just keeps the first half (rounded down), and reverses the rest. For instance, given `[4,5,1,3,2]`, it first sorts `[1,2,3,4,5]` (part of l4m2's cop post), then it keeps the first half rounded down, which is the first 5/2 | 0 = 2 elements. It reverses the rest, giving `[1,2,5,4,3]` which indeed satisfies the question's requirements.
EDIT: @Arnauld has made me aware of a potential byte-saving, which I will not accept (nor will I accept other byte-savings) because I was deliberately aiming for a solution with a length exactly matching the expected one.
[Answer]
# JavaScript, 60 bytes
Crack of the 2nd version of [l4m2's challenge](https://codegolf.stackexchange.com/a/241389/58563).
```
x=>x.sort((a,b)=>a-b).map(e=>x[i+=2]?e:b.pop(),i=0,b=[...x])
```
[Try it online!](https://tio.run/##bcpBDsIgEADAuy@BuN1IW6yaUB9COEClBlMLKY3h97hn43nmZT82T1tIe7PGh6@zqkWNBXPcdsYsOK5G2ziOb5uYJ9HhqFpz9zeHKSbGIagTOKURsRhep7jmuHhc4pPNTAtooYMepOH88GMDnEGSdXTEHxckEga4kvd0L3TqFw "JavaScript (Node.js) – Try It Online")
The secret string is 33 bytes long (shorter than the expected solution of 36 bytes):
```
=>x[i+=2]?e:b.pop(),i=0,b=[...x])
```
[Answer]
# [J](http://jsoftware.com/), 10 bytes, cracks [Jonah's answer](https://codegolf.stackexchange.com/a/241414/64121)
```
(,|.)/@/:~
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NXRq9DT1HfSt6v5rcqUmZ@QrpCkYKhgpGCuYKJjCBMwVzBRMgQLGQAlDhCpjoKC5giVQ0ASowOI/AA "J – Try It Online")
`/:~` sorts the list and `(,|.)/` reduces the sorted list by *reverse intermediate result*, *prepend new value*.
[Answer]
# [Bash](https://codegolf.stackexchange.com/a/241432/), 29 bytes
```
sort -n|sed '2~2p;G;1~2h;$!d'
```
[Try it online!](https://tio.run/##S0oszvj/vzi/qERBN6@mODVFQd2ozqjA2t3asM4ow1pFMUX9/39TLhMuYy4jLkMuQwMuQyAJZBoDAA "Bash – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 19 bytes, cracks [DLosc's answer](https://codegolf.stackexchange.com/a/241752/95126)
```
FiRSNalPBi&R:llR:ll
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgebSSbkWBUuyCpaUlaboWm90yg4L9EnMCnDLVgqxyckAYIgNVsD5aKdrU2sja2NrQ2iQWrg8A)
The secret 4-byte 'S' string is `R:ll`. The full code works with either [one](https://ato.pxeger.com/run?1=m724ILNgebSSbkWBUuyCpaUlaboW690yg4L9EnMCnDLVgqxyciCiMMlopWhTayNrY2tDa5NYuB4A) or (as required here) two copies of 'S'.
The public 'P' string:
```
FiRSNalPBi&
Fi # For each i in...
R # Reversed...
SN # Sorted by number...
a # 'a' (input);
PBi # Push i to the Back of...
l # 'l'...
& # ...and do something secret...
```
The secret 'S' string:
```
R:ll
# ...the secret thing to do each step is:
R:l # Reverse 'l'
l # And finally output 'l'
```
If we use the 'S' string twice, we simply reverse '`l`' one more time at the end before outputting it.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 15 bytes, cracks [DLosc's 2nd answer](https://codegolf.stackexchange.com/a/241801/95126)
```
SN:a;R:a&@UWRFa
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgebSSbkWBUuyCpaUlaboW64P9rBKtg6wS1RxCw4PcEiGiUMnt0UrRhtbG1qbW5taW1kbWJtZm1haxcL0A)
The secret 7-byte 'S' string is `&@UWRFa`.
This was either very sneaky, or I haven't found the *intended* crack.
The task could be accomplished with an 11-byte [Pip] program - `SN:a;@UWRFa` - which numerically sorts (`SN`) the input `a`, reflects it (`RF`; appending to itself), unweaves it (`UW`; splitting into two lists of odd & even indexed elements), and then takes the first list (`@`).
However, the 'P' string appears to reverse the sorted input in-place, which completely messes-up this approach (which would now put the smallest item in the centre instead of the largest).
But wait... there's no semicolon finishing this command... we can append to it...
So we append an `&` (logical AND) followed directly by our `@UWRFa` code: this appears to result in both expressions being evaluated independently, returning the result only of the second (our code).
So the reversing of the input is never actually used, and (I think) was just a decoy...
[Answer]
# [Python 3](https://codegolf.stackexchange.com/a/241670/), 42 bytes
```
def f(a):a.sort();return a[1::2]+a[-1::-2]
```
[Try it online!](https://tio.run/##VcqxCoAgFIXhvadoVLoFambZo4iDUFKLidnQ09ttCdoO/3finbcjiFKW1deeOKpddx4pEzqnNV8p1M4wrbltnGlxtNyWmPaQiSeGAQcBPUhL6Vx9WcEAErNAZn9iGCUomJB6vI0vlwc "Python 3 – Try It Online")
# 41 bytes
```
def f(a):a.sort();return a[::2]+a[-2::-2]
```
[Try it online!](https://tio.run/##Vco7DoAgEADR3lNYQlxNAPGzHoVQkCjRBg1i4elxbUxs581xp3UPKud58aVnjqNrzj0mxqe4pCuG0hlEaStnaolYS5uPuIXEPDMCJChoQVvOp@LLPXSgKSti8SdBUUMPI1FL2/ByfgA "Python 3 – Try It Online")
Trivial
] |
[Question]
[
I have 2 inputs: 1 single number and some numbers separated by whitespace:
```
1
1 2 3 4 5
```
I want to loop over the second input, and I don't need the first input. I did this, which works:
```
input()
for x in input().split():somecode()
```
But can I go directly to the second input without doing the `input()` at the beginning or with shorter code?
I tried this code (-2 bytes) but it doesn't work, it needs two `input()` to work:
```
a,b=input()
for x in b.split():somecode() #Error : not enough values to unpack (expected 2, got 1)
a,b=input(),input()
for x in b.split():somecode() #OK
```
[Answer]
# `open(0)`, 40 bytes
The builtin function [`open`](https://docs.python.org/3.8/library/functions.html#open) returns a file object which can be iterated over, line by line. Usually you pass a path to `open`, but it also takes *file descriptor*, which are integers that refer to special files.
`0` is the file descriptor for the standard input ([source](https://docs.python.org/3.8/library/os.html?highlight=file%20descriptor#file-descriptor-operations)), and this allows you to open the input as file with `open(0)`.
Converting this file to a list (of lines) and accessing the second entry saves 3 bytes in this case:
```
for x in[*open(0)][1].split():somecode()
```
Other than `input()` this does not remove trailing newline characters (`\n`), but in this case `split` takes care of it. Another downside is that you can not combine `input()` and `open(0)`.
The same technique often helps when you need to read multiple lines of input, example:
```
# a is the first line of input, b the seconds and r contains all remaining lines.
a,b,*r=open(0)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 42 bytes
You can use `open(0)` to read all the inputs in once and unpack them.
```
_,a=open(0)
for i in a.split():somecode(i)
```
[Try it online!](https://tio.run/##K6gsycjPM/5fnJ@bmpyfkmpbUJSZV/I/XifRNr8gNU/DQJMrLb9IIVMhM08hUa@4ICezREPTCqZaI1Pz/3@3zKLiEq5goEBeikJIRmZRioJbfmlRSQYA "Python 3 – Try It Online")
if the inputs contains more than two lines you can also use:
```
_,*a=open(0)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P15HK9E2vyA1T8NA839BUWZeiUai5n@3zKLiEq7g1OT8vBSukIzMohQut/zSopIMAA "Python 3 – Try It Online")
but it will append a trailing newline to all the elements but the last
] |
[Question]
[
## Task
Given an input, evaluate it as a mathematical equation following the order of operations.
But, instead of the using PEMDAS, we drop the parentheses and exponentiation and introduce spaces - SMDAS - spaces, then multiplication & division, then addition & subtraction.
### How does that work?
Every operator with more spaces around it gets more precedence - but that can change from one side to the other. Usual precedence test - `2+2*2` still gets evaluated to 6 - so does `2 + 2*2` - which would be spelled out like `two .. plus .. two-times-two`, but `2+2 *2` or `2+2 * 2` would equal 8 - `twoPlusTwo .. times two`.
So, from any operator to any side every operator and number with less spaces can be grouped as in parentheses and then calculated as normal.
Alternatively, you can think of it as spaces around operators dropping the operator lower in precedence, or if the spaces are different on each side, drop the precedence on each side differently.
## Examples
```
input = output
2+2*2 = 6
2+2-2 = 2
2+12/6 = 4
228+456/228 = 230
2+0*42 = 2
73-37-96+200 = 140
2+2 * 2 = 8
5*6 + 7*8 -3 *5 = 415
4+4*4+ 4*4-4*2 / 4*4-2 = 2
228+456 /228 = 3
2+2 * 3-6 * 4/2 + 4*3 + 1000 / 5*5 / 5-3 + 1 = 9
2+0 * 42 = 84
5*5 *7-1 = 174
```
## Notes
* The input will always be valid - it will always contain at least 2 numbers, separated by a sign (`-+/*` (for which you may use alternatives such as `∙` or `÷`))
* The input will never end or start in spaces.
* There will never be unary subtraction - `-4*-6`.
* There will never be division by zero.
* There may be negative integers in the process but never in the output.
* Division is only required to work for integers.
* Floating-point inaccuracies at any step of the process are fine.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer per language wins!
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 15 bytes
```
OvUr" +%d"_rS'(
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=T3ZVciIgKyVkIl9yUyco&input=IjIrMCAqIDQyIg==)
### How it works
This challenge was practically made for Japt. I shall attempt to explain how:
Japt is basically a shortened version of JavaScript. In fact, after making some changes to the code ("transpiling" to JS), it is evaluated directly as JavaScript. What comes in handy here is that a space in Japt becomes `)` in JavaScript (a feature I occasionally regret adding, as it makes it hard to write "ungolfed" Japt code), and missing parentheses are automatically added.
What this all means for this challenge is that we can obtain the correct result simply by changing all spaces after an operator (before a number) to left-parentheses:
```
5*6 + 7*8 -3 *5 Original string
5*6 +((7*8 -3 *5 Japt code that evaluates to the correct number
```
When transpiled to JS, the changes mentioned above are made, which results in this:
```
5*6 +((7*8 -3 *5 Japt code
(((((5*6))+((7*8)))-3))*5 transpiled JS code
```
The JS code is then evaluated, which gives the expected result.
```
OvUr" +%d"_rS'( Implicit: U = input string
Ur" +%d" Replace each match of / +\d/ in U with
_rS'( the match with each Space replaced with a '('.
Ov Evaluate the result as Japt.
Implicit: output result of last expression
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 59 bytes
```
òÍ ¨Ä*[+*¯-]©/)±
ͨ[+*¯-]Ä*© /±(ò
Ïò])|é(kòJïò[(Á)jòHDi="
```
[Try it online!](https://tio.run/##K/v///Cmw70Kh1YcbtGK1tY6tF439tBKfc1DG7kO9x5aARUByh1aqaB/aKPG4U1ch/sPb4rVrDm8UiP78Cavw@sPb4rWONyomXV4k4dLppCtkNL//0baBgpaCiZGAA "V – Try It Online")
I'm looking into golfing this down more later. The idea is that it turns spaces on the left of an operator into `)` and `(` on the right, the surrounds with appropriate `()` to make all parens match, and calculates the line. Mostly my regexes need work:
```
\(\D*[+*\/-]\)/)\1
\([+*\/-]\D*\) /\1(
```
[Answer]
## JavaScript (ES6), 116 bytes
```
f=
s=>(s=s.replace(/./g,c=>c>` `?(b=1/c?`)`:`(`,c):b),g=c=>s.split(c).length,eval(`(`.repeat(g`)`)+s+`)`.repeat(g`(`)))
```
```
<input><input type=button value=Evaluate onclick=o.textContent=``,o.textContent=f(this.previousSibling.value)><pre id=o>
```
Changes the spaces into the appropriate brackets, then adds matching brackets on each side (at least one pair of which will be redundant, not that it matters) and evaluates the result.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/119226/edit).
Closed 6 years ago.
[Improve this question](/posts/119226/edit)
I am making a customizable password generator.
But I (for some reason) thought it'd be better to let you guys do it.
---
# Umm.. then?
You only get one integer. That will include all the information about the customization.
The first 4 bits (1,2,4,8) will be used for choosing which charsets will be used.
Each bit corresponds to:
1: Lowercase alphabet(`qwertyuiopasdfghjklzxcvbnm`)
2: Uppercase alphabet(`QWERTYUIOPASDFGHJKLZXCVBNM`)
4: Numbers(`0123456789`)
8: Special chars(All printable characters except ones stated above and the space)
The length of the password will be shifted 4 bits. In other words, multiplied by 16.
Then generate the password with the charsets and the length.
# Examples
```
175 (10*16 + 15 (1111)): a_U0!/h96%
```
[Answer]
# Python 2, ~~217~~ 203 bytes
```
from random import*
r=[10]+range(33,127)
r=[r[65:91],r[33:59],r[16:26],r[:16]+r[26:33]+r[59:65]+r[91:]]
x=input()
l=x>>4
print''.join(map(chr,sample(sum([k[1]for k in enumerate(r)if x&2**k[0]],[])*l,l)))
```
Ugh this is horribly long. The part I think could be golfed the most is the part to get the charsets; that part was a pain.
By the way, I am @HyperNeutrino; I'm just getting enough rep to chat. :P
-14 bytes thanks @ValueInk!
Bug fix thanks to @ovs!
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), ~~80~~ ~~79~~ 78 bytes
```
:2 tb _4 drop ascii'\' 'modI'toarr+match[''#`]map\keep''#`\16/~~:>$randin~2/"!
```
[Try it online!](https://tio.run/nexus/stacked#JY7LCoJAGIX3PsXpAr8SIRNdaBbhtmdQqUkNp5oL47iKfOvWNtLmwOH7OJx85Bv4Gy5b1M5YiK6SkgoCKVOfyRvh3EoJX7U50eJaKmGLZ9PYqRRsnw4DPy2d0LXUwyadz8aSpRm/R/lN6mm0sy/phQdlhIeRukSgygcaxdsj2GGHHWMJ3tDgEUJSJmvE2V9KOAgz2N4HcofpffRB@DB@tVlXomqbHw) Takes input from the top of the stack and leaves output on the top of the stack. TIO link includes test suite (thingy) for convenience.
[Answer]
## Mathematica 175 Bytes
```
""<>RandomChoice[(j=Join)@@Pick[c~j~{Complement[(r=CharacterRange)[1,127],j@@(c=r@@#&/@{{97,122},{65,90},{48,57}})]},(i=IntegerDigits[#,2])[[-4;;]],1],i[[;;-5]]~FromDigits~2]&
```
Coded pretty much as explained in the question. Seems like rearranging the ASCII table was expensive.
Also, there is a bug in CharacterRange which doesn't allow it to accept 0 as an argument (at least in M10.2, which is what I have handy on my laptop), so to fix that would need another 7 bytes to include the ASCII null character.
[Answer]
# PHP, ~~127~~ 113 bytes
Jörg helped my tired brain with 10-2 bytes and I found another 2+4.
```
for(;$i<$argn>>4;$c=chr(rand()))foreach([lower,upper,digit,punct]as$t=>$f)$argn>>$t&(ctype_.$f)($c)&&$i+=print$c;
```
**breakdown**
Run as pipe with `php -nR '<code>'`.
```
// loop while length not reached
for(;$i<$argn>>4;
// pick random character
$c=chr(rand())
)
// loop through bits and functions
foreach([lower,upper,digit,punct]as$t=>$f)
// if test is positive, increment length counter and print character
$argn>>$t&(ctype_.$f)($c)&&$i+=print$c;
```
Neat tricks:
The `ctype` functions return `false` on failure (resulting in `$argn>>$t&0`, so the bit is irrelevant);
[Answer]
# [Python 2](https://docs.python.org/2/), 180 bytes
```
lambda x,r=[10]+range(33,127):''.join(chr(choice(r[65:91]*(x&1)+r[33:59]*(x&2>0)+r[16:26]*(x&4>0)+(r[:16]+r[26:33]+r[59:65]+r[91:])*(x&8>0)))for i in' '*(x>>4))
from random import*
```
[Try it online!](https://tio.run/nexus/python2#NY7RqsIwDIbvfYrghWt1Sru66gLuRXp20c1NK66VsAtBfGyvZyuchJA/H39ChtPffLdje7bwzOlkpGg2ZP2lZ0rlsjhwzLLdLTjPuivFCq7rGRldYiWbNXuuJN@QUQrL6jcWtUhAaiz0D@wTiBsodbxsCo1KJVFWqMskKokNT85jdHI@BAIHzmeQRVjXe84XA4UR4lfn2Nz4CDSt538fGNFKKVKKHJJO0eACHuT8BMsXimP7hm0Nr/dyF9dGOzGXD8xxPn982Ha2u/Zf "Python 2 – TIO Nexus")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~93~~ 78 bytes
*Saved 15 bytes thanks to ETHproductions*
```
;>>4 o_=ApU&1©CU&2©BU&4©9o U&8©Q+"\{|}\\!#$%&'()*+,-.:;<=>?@[]^_`" f q)gMqZlÃq
```
[Try it online!](https://tio.run/nexus/japt#@29tZ2eikB9v61gQqmZ4aKVzqJrRoZVOoWomh1Za5iuEqlkcWhmorRRTXVMbE6OorKKqpq6hqaWto6tnZW1ja2fvEB0bF5@gpJCmUKiZ7lsYlXO4ufD/f0Nz0695@brJickZqQA "Japt – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 54 bytes
```
ØBUð,ø33r126µFỌQðṁø“ııµþ’b250Rðị@ø³%16b2UTµF
¢XȮµ:⁴’µ¡
```
[Try it online!](https://tio.run/nexus/jelly#AWcAmP//w5hCVcOwLMO4MzNyMTI2wrVG4buMUcOw4bmBw7jigJzEscSxwrXDvuKAmWIyNTBSw7Dhu4tAw7jCsyUxNmIyVVTCtUYKwqJYyK7CtTrigbTigJnCtcKh////MTc19W5vLWNhY2hl "Jelly – TIO Nexus")
**Explanation**
```
ØBUð,ø33r126µFỌQðṁø“ııµþ’b250Rðị@ø³%16b2UTµF - nilad which returns charset
ØB - yield alphanumeric characters
U - reverse to get proper order
ð,ø33r126 - append char values of printable characters
µFỌQ - flatten and remove repeats to get "z-aZ-A9-0[specials]"
ðṁø - mold this string like ...
“ııµþ’b250 - literal [26,26,10,32]
R - [26R,26R,10R,32R]. All that matters is the length of each sublist.
ðị@ - get the elements numbered ...
³%16b2UT - those indices we want based on the last 4 bits of the input.
¢XȮµ:⁴’µ¡ - monad with input a
X - pick a random element from ...
¢ - the above charset.
Ȯ - Print it.
¡ - Repeat this ...
µ:⁴’ - floor(a/16)-1 times. (⁴ is literal 16).
```
] |
[Question]
[
[Gamma function](https://en.wikipedia.org/wiki/Gamma_function) is defined as
[](https://i.stack.imgur.com/ES8hs.png)
It is a well-known fact that for positive integers it coincides with a properly shifted factorial function: `Γ(n) = (n - 1)!`. However, a less famous fact is
>
> Γ(1/2) = π1/2
>
>
>
Actually, the Gamma function can be evaluated for all half-integer arguments, and the result is a rational number multiplied by π1/2. The formulas, as mentioned in Wikipedia, are:
[](https://i.stack.imgur.com/DrL55.png) (for n > 0)
In this challenge, you should write code (program or function) that receives an integer `n` and returns the rational representation of **Γ(1/2 + n) / π1/2**, as a rational-number object, a pair of integers or a visual plain-text representation like `15/8`.
The numerator and denominator don't need to be relatively prime. The code should support values of `n` at least in the range -10 ... 10 (I chose 10 because 20! < 264 and 19!! < 232).
Test cases (taken from Wikipedia):
```
Input | Output (visual) | Output (pair of numbers)
0 | 1 | 1, 1
1 | 1/2 | 1, 2
-1 | -2 | -2, 1
-2 | 4/3 | 4, 3
-3 | -8/15 | -8, 15
```
[Answer]
# [M](https://github.com/DennisMitchell/m), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
,0_.!÷/
```
[Try it online!](http://m.tryitonline.net/#code=LDBfLiHDty8&input=&args=LTI) or [verify all test cases](http://m.tryitonline.net/#code=LDBfLiHDty8&input=&args=MCwgMSwgLTEsIC0yLCAtMw).
### Trivia
Meet M!
M is a fork of Jelly, aimed at mathematical challenges. The core difference between Jelly and M is that M uses infinite precision for all internal calculations, representing results symbolically. Once M is more mature, Jelly will gradually become more multi-purpose and less math-oriented.
M is very much work in progress (full of bugs, and not really *that* different from Jelly right now), but it works like a charm for this challenge and I just couldn't resist.
### How it works
```
,0_.!÷/ Main link. Argument: n
,0 Pair with 0. Yields [n, 0].
_. Subtract 1/2. Yields [n - 1/2, -1/2].
! Apply the Π function. Yields [Π(n - 1/2), Π(-1/2)] = [Γ(n + 1/2), Γ(1/2)].
÷/ Reduce by division. Yields Γ(n + 1/2) ÷ Γ(1/2) = Γ(n + 1/2) ÷ √π.
```
[Answer]
# Octave, 27 bytes
```
@(n)rats(gamma(n+.5)/pi^.5)
```
Built-ins all the way.
Test suite on [ideone](http://ideone.com/NkkEtR).
[Answer]
# Pyth - ~~27~~ ~~26~~ ~~25~~ 24 bytes
Too cumbersome for my liking. Also, implicit input seems not to work with `W`. Uses the ~~second to last~~ first form listed above.
```
_W<QZ,.!yK.aQ*^*4._QK.!K
```
[Test Suite](http://pyth.herokuapp.com/?code=_W%3CQZ%2C.%21yK.aQ%2a%5E%2a4._QK.%21K&test_suite=1&test_suite_input=0%0A1%0A-1%0A-2%0A-3%0A11%0A-11&debug=0).
[Answer]
# J, ~~20~~ ~~17~~ ~~19~~ 18 bytes
Saved 3 bytes using @Dennis's technique in his M, and another! This is a tacit verb.
```
x:@%&!/@(0.5-~,&0)
```
(Previous answers: `x:@%/@(!@-&0.5@,&0)`, `x:%/(!@-&0.5@,&0)`, `x:((%:o.1)%~!@-&0.5)`)
(Note that instead of being `-a/b`, it's `_arb`.)
Test cases:
```
gamma =: x:@%&!/@(0.5-~,&0)
gmR0 =: gamma"0 NB. apply to 0-cells of a list
gamma 0
1
gamma 1
1r2
gamma 2
3r4
gamma -1
_2
gamma -2
4r3
i:2
_2 _1 0 1 2
gmR0 i:2
4r3 _2 1 1r2 3r4
gmR0 i:5
_32r945 16r105 _8r15 4r3 _2 1 1r2 3r4 15r8 105r16 945r32
```
[Answer]
# Mathematica, ~~17~~ 15 bytes
```
(#-1/2)!/√π&
```
Uses factorial function since `gamma(n + 1/2) = (n - 1/2)!`.
There are only 12 characters now but it needs 15 bytes to be represented. The bytes are counted using UTF-8. `Sqrt = √` is 3 bytes from 5 bytes with `@` (2 bytes saved, thanks to @[CatsAreFluffy](https://codegolf.stackexchange.com/users/51443/catsarefluffy)) and `Pi = π` is 2 bytes (equal).
[](https://i.stack.imgur.com/Xm539.png)
[Answer]
# Haskell, ~~81~~ ~~71~~ 69 bytes
```
import Data.Ratio
p=product
f n|n<0=1/(p[n+1%2..0-1])|0<1=p[1%2..n-1]
```
This seems bloated, but I'm not sure where to golf this from here. Any golfing suggestions are welcome.
**Edit:** Used the fact that the default step of range `[x..y]` is 1, and moved `product` to `p=product` to save two bytes.
**Ungolfing:**
```
import Data.Ratio
gamma_half n | n < 0 = 1 / ( product [ n + 1%2 .. (-1) ] )
| otherwise = product [ 1%2 .. n-1 ]
```
[Answer]
# Ruby, ~~80~~ ~~59~~ 58 bytes
```
f=->n{n<0?(-1)**n/f[-n]:(1..n).reduce(1){|z,a|z*(a-1r/2)}}
```
Any golfing suggestions are welcome.
**Ungolfing:**
```
def half_gamma(n)
if n < 0
return (-1) ** n / f(-n)
else
# Is there an golfier way to write product([1/2,3/2..(2*n-1)/2])?
return (1..n).reduce(1) {|z, a| z * (a - 1r/2)}
end
end
```
] |
[Question]
[
You should write a program or function which outputs or returns the sum of the digits in base `b` representation of the first `n` natural power of `a` in ascending order.
Example for `a = 2`, `b = 3` and `n = 4`
```
The base10 numbers are 2^0, 2^1, 2^2 and 2^3.
Their base3 representations are 1, 2, 11, 22.
The digit sums are 1, 2, 2, 4.
The sorted digit sums are 1, 2, 2, 4 which is the result.
```
## Input
* 3 integers `a > 1`, `b > 1` and`n > 0`
## Output
* A list of integers
## Examples
Input => Output
```
2 5 10 => 1 2 4 4 4 4 4 4 8 8
3 2 20 => 1 2 2 3 4 5 6 6 6 8 9 10 11 11 13 14 14 14 15 17
5 6 1 => 1
6 6 11 => 1 1 1 1 1 1 1 1 1 1 1
6 8 20 => 1 6 6 8 8 8 13 13 15 20 22 22 22 27 29 34 34 34 36 41
8 2 10 => 1 1 1 1 1 1 1 1 1 1
15 17 18 => 1 15 17 31 31 33 49 49 63 65 81 95 95 95 95 113 127 129
```
This is code-golf so shortest code wins.
[Answer]
# CJam, 13 bytes
```
q~,f#\fb::+$p
```
I think this can be improved, but lets get this started.
The input is in the following order : `b a n`
Example input:
```
3 2 4
```
Output:
```
[1 2 2 4]
```
**Code expansion**:
```
q~ "Read the input and parse it. Now we have on stack, b a and n"
, "Get an array from 0 to n-1";
f# "Get all the powers of a present in the array, i.e. 0 to n-1";
\ "Swap the array of a^i and bring the base on top";
fb "For each number in the array, convert it into its base representation array";
::+ "Calculate the sum of each of the sub arrays in the bigger array";
$p "Sort and print the sum of digits of base representation of n powers of a";
```
[Try it online here](http://cjam.aditsu.net/#code=q%7E%2Cf%23%5Cfb%3A%3A%2B%24p&input=3%202%204)
[Answer]
# Pyth, 11
```
Smsj^vzdQvw
```
Note that this requires the inputs separated by newlines in the order a,b,n.
[Try it online here](https://pyth.herokuapp.com/?code=Smsj%5EvzdQvw&input=15%0A17%0A18)
Pyth has built-ins that do each step for us. We `m`ap over each value from `0` to `n-1`, raising `a` to that power. Then we use `j` to convert each of these numbers to base `b`. We `s`um the resulting lists, and the final list of numbers is `S`orted.
The input is read in the order `z`, `Q` then `w`. `z` and `w` have to be `eval`ed in order to be used as numbers.
[Answer]
# JavaScript (ES6) 170 ~~175 196 98 100~~
**Edit** New version, handles bigger numbers using digits array. Score *almost* doubled :-(
Multiplying digit by digit is more difficult, summing the digits is simpler.
```
F=(a,b,n)=>
(t=>{
for(r=t;--n;r[n]=s)
for(k=1,y=t,z=a;z;z=z/b|0)
t=[...t.map(v=>(v=c+(k?w*~~y[i++]+v:w*v),s+=d=v%b,c=v/b|0,d),
w=z%b,s=c=0,i=--k),c]
})([1])||r.sort((a,b)=>a-b)
```
*Less golfed*
```
F=(a, b, n) =>
{
var r=[1]; // power 0 in position 0
for(w=[]; w.push(a%b),a=a/b|0; ); // a in base b
for(t = [1]; --n; )
{
// calc next power, meanwhile compute digits sum
y=[...t]
k=1
w.map(w=>
(t=[...t.map(v=>(
v = c + (k?w*~~y[i++]+v:w*v),
d = v % b, // current digit
s += d, // digits sum
c = (v-d)/b, // carry
d)
,s=c=0,i=--k),c]
)
);
r[n] = s // store sum in result array (positions n-1..1)
}
return r.sort((a,b)=>a-b) // sort result in numeric order
}
```
**My first attempt** using `doubles`, fails for big numbers.
JS doubles have 52 mantissa bits when for instance 15^14 needs 55 bits.
```
F=(a,b,n,r=[1])=>(x=>{for(;--n;r[n]=s)for(t=x*=a,s=0;t;t=(t-d)/b)s+=d=t%b})(1)
||r.sort((a,b)=>a-b)
```
*Less golfed*
```
F=(a, b, n) =>
{
var r=[1]; // power 0 in position 0
for(x = 1; --n; )
{
x *= a; // calc next power starting at 1
for(t = x, s = 0; t; t = (t-d) / b) // loop to find digits
{
d = t % b;
s += d;
}
r[n] = s // store sum in result array (positions n-1..1)
}
return r.sort((a,b)=>a-b) // sort result in numeric order
}
```
**Test** In Firefox/FireBug console
```
;[[2,5,10],[3,2,20],[5,6,1],[6,6,11],[6,8,20],[8,2,10],[15,17,18]]
.forEach(t=>console.log(...t,F(...t)))
```
>
> 2 5 10 [1, 2, 4, 4, 4, 4, 4, 4, 8, 8]
>
> 3 2 20 [1, 2, 2, 3, 4, 5, 6, 6, 6, 8, 9, 10, 11, 11, 13, 14, 14, 14, 15, 17]
>
> 5 6 1 [1]
>
> 6 6 11 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
>
> 6 8 20 [1, 6, 6, 8, 8, 8, 13, 13, 15, 20, 22, 22, 22, 27, 29, 34, 34, 34, 36, 41]
>
> 8 2 10 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
>
> 15 17 18 [1, 15, 17, 31, 31, 33, 49, 49, 63, 65, 81, 95, 95, 95, 95, 113, 127, 129]
>
>
>
[Answer]
# A purely mathematical equation on the Cartesian Plane, written in LaTeX: Unknown size, incomplete
Demonstrated here:
<https://www.desmos.com/calculator/svpkyarzxh>
`a`, `b`, and `n` are adjustable inputs.
To avoid spaghetti code, it's split into two functions, although it could be condensed.
```
f\left(x\right)=\floor \left(x-\left(b-1\right)\sum _{i=1}^{\log _bx}\floor \left(xb^{-i}\right)\right)
y=f\left(a^{\floor \left(x\right)}\right)\left\{0<x\le n\right\}
```
I'm not sure how to put the values in an adjustable list or sort the list without using an actual programming language. However, the fact that this equation allows you to put it on a programmable graphing calculator and figure out the rest from there. I know it can be done in TI-BASIC, but I'm too busy to put an example here.
[Answer]
# Mathematica, ~~43~~ 41 bytes
```
Sort[Tr/@IntegerDigits[#^Range@#3/#,#2]]&
```
Very straightforward and apart from the slight abuse of `Tr` very readable. This is an unnamed function which is called with the three parameters in order.
Example outputs:
```
f=Sort[Tr/@IntegerDigits[#^Range@#3/#,#2]]&
f[2, 5, 10]
(* {1, 2, 4, 4, 4, 4, 4, 4, 8, 8} *)
f[3, 2, 20]
(* {1, 2, 2, 3, 4, 5, 6, 6, 6, 8, 9, 10, 11, 11, 13, 14, 14, 14, 15, 17} *)
f[5, 6, 1]
(* {1} *)
f[6, 6, 11]
(* {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} *)
f[6, 8, 20]
(* {1, 6, 6, 8, 8, 8, 13, 13, 15, 20, 22, 22, 22, 27, 29, 34, 34, 34, 36, 41} *)
f[8, 2, 10]
(* {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} *)
f[15, 17, 18]
(* {1, 15, 17, 31, 31, 33, 49, 49, 63, 65, 81, 95, 95, 95, 95, 113, 127, 129} *)
```
Two bytes saved thanks to alephalpha.
[Answer]
## J - 19
```
/:~+/"1#.inv`(^i.)/
```
Takes numbers in that order: b a c
Usage example (x stands for extended precision):
```
/:~+/"1#.inv`(^i.)/ 5 2 10
1 2 4 4 4 4 4 4 8 8
/:~+/"1#.inv`(^i.)/ 17 15x 18
1 15 17 31 31 33 49 49 63 65 81 95 95 95 95 113 127 129
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~29~~ 24 bytes
```
{(⊂∘⍋⌷⊢)+⌿⍵(⊥⍣¯1)∊*∘⍳/⍺}
```
-5 bytes from Jo King.
Takes inputs as `a n` function `b`.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXECWWxCQZWhkYf6/WuNRV9OjjhmPersf9Wx/1LVIU/tRz/5HvVuB4ksf9S4@tN5Q81FHlxZYyWb9R727av@nATU/6u171NX8qHfNo94th9YbP2qbCDQ2OMgZSIZ4eAb/N1IwNFBIUzBV4DJWMAKxjLhMFQyBtBkA "APL (Dyalog Unicode) – Try It Online")
```
{(⊂∘⍋⌷⊢)+⌿(⊃⌽⍵)(⊥⍣¯1)(⊃⍵)*⍳⍺}
```
Takes inputs as `n` function `a b`
Thanks to [Jo King](https://chat.stackexchange.com/transcript/message/55516302#55516302) for helping me fix this answer.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXECWWxCQZWhkYf6/WuNRV9OjjhmPersf9Wx/1LVIU/tRz36gYPOjnr2PerdqAplLH/UuPrTeUBMsChTSetS7@VHvrtr/aUBTHvX2gYXXPOrdcmi98aO2iUDzg4OcgWSIh2fwf0MDhTQFIwVTBS4jEMtYwYjLEEibKpgBAA "APL (Dyalog Unicode) – Try It Online")
## Explanation
```
{(⊂∘⍋⌷⊢)+⌿(⊃⌽⍵)(⊥⍣¯1)(⊃⍵)*⍳⍺} ⍺ → n, ⍵ → [a,b]
⍳⍺ range (1..n)
(⊃⍵)* a to the power of the range
(⊃⌽⍵) take b from reverse of ⍵
(⊥⍣¯1) inverse encode(decode) using b till it reaches zero
+⌿ reduce with addition along non-leading axis
i.e: sum the columns
(⊂∘⍋⌷⊢) tacit fn:
⍋ Get indices for ascending order
⌷ Get elements at those indices
⊢ From the right arg
⊂ Enclose it
```
[Answer]
# Haskell, 79 bytes
```
import Data.Digits
import Data.List
f a b n=sort$map(sum.digits b.(a^))[0..n-1]
```
Usage: `f 6 8 20`, output: `[1,6,6,8,8,8,13,13,15,20,22,22,22,27,29,34,34,34,36,41]`
This is a typical Haskell function: straight forward, same as ungolfed version but the `import`s ruin the golf score: for every element e of the list from `0` to `n-1` calculate `a^e`, convert to a list of base `b` digits and `sum` it. `Sort` the resulting list.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Ḷ*@b⁵§Ṣ
```
[Try it online!](https://tio.run/##ASAA3/9qZWxsef//4bi2KkBi4oG1wqfhuaL///8xOP8xNf8xNw "Jelly – Try It Online")
Takes input as 3 command line arguments, \$n\$, \$a\$ then \$b\$.
## How it works
```
Ḷ*@b⁵§Ṣ - Main link. n on the left, a on the right and b as the 3rd argument
Ḷ - Range [0, 1, ..., n-1]
*@ - Take a to the power of each [1, a, ..., a^(n-1)]
⁵ - Yield b
b - Convert each power to base b
§ - Take the digit sums of each
Ṣ - Sort the digit sums
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 13 bytes
```
OmoΣB²`z^R¹⁴ŀ
```
[Try it online!](https://tio.run/##ASIA3f9odXNr//9PbW/Oo0LCsmB6XlLCueKBtMWA////M/8y/zIw "Husk – Try It Online")
## Explanation
```
OmoΣB²`z^R¹⁴ŀ
ŀ range from 0..n-1
R¹⁴ a replicated n times
`z^ zip both with power
moΣB² convert each power to base n, and sum digits
O Sort in ascending order
```
] |
[Question]
[
This is an optimization/algorithms challenge. Given two sets of points X and Y, which are to be thought of as points on a circle of circumference T, the challenge is to find the rotation which minimizes the distance from the set X to the set Y. Here the distance is just the sum of the absolute distance from each point in X to its closest point in Y. Here closest is really just the minimum distance you need to travel along the circle to reach a point in Y (remembering that you can go clockwise or anti-clockwise). Note that this measure of distance is **not** symmetric.
In order to be able to create the test data, you will need to be able to run Python, but your answer can be in any language of your choosing that is available without cost to run on Linux. You can also use any libraries you choose as long as they are easy to install on Linux and available without cost.
The test data will be created using the following Python code. It outputs two lines to standard out. The first is circle X and the second is circle Y.
```
import numpy as np
#Set T to 1000, 10000, 100000, 1000000, 10000000, 1000000000
T = 1000
N = int(T/5)
#Set the seed to make data reproducible
np.random.seed(seed = 10)
timesY = np.sort(np.random.uniform(low = 0.0, high = T, size = N))
indices = np.sort(np.random.randint(0,N, N/10))
rotation = np.random.randint(0,T, 1)[0]
timesX = [(t + rotation + np.random.random()) % T for t in timesY[indices]]
for tX in timesX:
print tX,
print
for tY in timesY:
print tY,
```
For those who don't run python, I have also uploaded some test files. Each file has three lines. The first line is the points for circle X, the second is the points for circle Y, and the last is the score you get from the generic optimizer in the python code below. This score will be in no way optimal and you should do much better.
```
http://wikisend.com/download/359660/1000.txt.lzma
http://wikisend.com/download/707350/10000.txt.lzma
http://wikisend.com/download/582950/100000.txt.lzma
http://wikisend.com/download/654002/1000000.txt.lzma
http://wikisend.com/download/416516/10000000.txt.lzma
```
Here is also a toy **worked example** of the distance between two sets of point to make the distance function clear.
Let `timesX = [2, 4, 98]` and `timesY = [1, 7, 9, 99]`. Let us assume the circumference of the circle is `100`. As it stands the distance is `(2-1)+(7-4)+(99-98) = 5`. Now if we rotate `timesX` by `3` we get `[5, 7, 1]` which has total absolute distance `2` to `timesY`. In this case this appears to be the optimal solution.
Here is some sample code which assumes that the circles are called `timesX` and `timesY`, and outputs the minimum distance it finds. It doesn't, however, do a very good job, as you will see.
```
from bisect import bisect_left
from scipy.optimize import minimize_scalar
def takeClosest(myList, myNumber, T):
"""
Assumes myList is sorted. Returns closest value to myNumber in a circle of circumference T.
"""
pos = bisect_left(myList, myNumber)
if (pos == 0 and myList[pos] != myNumber):
before = myList[pos - 1] - T
after = myList[0]
elif (pos == len(myList)):
before = myList[pos-1]
after = myList[0] + T
else:
before = myList[pos - 1]
after = myList[pos]
if after - myNumber < myNumber - before:
return after
else:
return before
def circle_dist(timesX, timesY):
dist = 0
for t in timesX:
closest_number = takeClosest(timesY, t, T)
dist += np.abs(closest_number - t)
return dist
def dist(x):
timesX_rotated = [(tX+x) % T for tX in timesX]
return circle_dist(timesX_rotated, timesY)
#Now perform the optimization
res = minimize_scalar(dist, bounds=(0,T), method='bounded', options={ 'disp':True})
print res.fun
```
**Scoring**
You should run your code for T = 1000, 10000, 100000, 1000000, 10000000. Your code should output both the optimum rotation and the distance you get for it so that it can be checked. The scoring criterion is as follows.
* You should calculate the sum of the distances you find for the five values of T. Low is better and the best possible is 0. You aren't allowed to cheat by looking at what rotation was used to create the data in the first place.
* Then you should calculate `551431.326508571/(the sum you just calculated)` and report that as your score.
---
**Edit 1**. Changed score so that high is better and removed time restriction so you can just run it on your own computer.
**Edit 2** Note that the function `dist` can be used as a verifier. Just put the points for circle X in `timesX` and the points for circle Y in `timesY` and set `x` to be the rotation you want to test. It will return a score which you can compare to what you get.
**Edit 3** Fixed the data creation code which wasn't exactly the code I had used to create the data.
[Answer]
## C++, 10.60236
If we assume nothing about the data then it seems unlikely that we can do much better than brute force/Monte Carlo plus maybe some local minimization.
The distance/rotation graphs for *T=1,000* and *T=10,000* are already pretty noisy:


However, assuming this is fair game, taking into account the fact that *X* is simply a rotated subset of *Y* with some small error, recovering the approximate rotation and minimizing locally is easy:
Compile with `g++ mindist.cpp -omindist -std=c++11 -O3`.
Run with `./mindist T < dataset` (e.g. `./mindist 1000 < 1000.txt`).
```
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <tuple>
#include <cmath>
using namespace std;
/* Positive modulo */
template <typename T>
T mod(T x, T y) { x = fmod(x, y); return x >= 0 ? x : x + y; }
/* Less-than comparison with a margin. Can be used to search for elements
* within +-epsilon. */
template <typename T>
struct epsilon_less {
T epsilon;
bool operator()(const T& x, const T& y) const { return x < y - epsilon; }
};
/* Calculates the distance between X and Y on a circle with circumference T,
* where X is rotated by `rotation`. */
template <typename P, typename Ps>
P distance(P T, const Ps& X, const Ps& Y, P rotation) {
P dist = 0;
for (P x : X) {
x = mod(x + rotation, T);
auto l = lower_bound(Y.begin(), Y.end(), x);
auto r = prev(l);
dist += min(*l - x, x - *r);
}
return dist;
}
/* Minimizes a function f on the interval [l, r]. f is assumed to be "well-
* behaved" within this range. This is a simple n-iterations binary search
* based on the sign of the derivative of f. */
template <typename T, typename F>
T minimize(F f, T l, T r, int n = 32) {
auto fl = f(l), fr = f(r);
for (; n; --n) {
T m = (l + r) / 2;
auto fm = f(m);
T dm = (r - l) / 1e5;
auto fm2 = f(m + dm);
auto df_dm = (fm2 - fm) / dm;
(df_dm < 0 ? tie(l, fl) : tie(r, fr)) = make_tuple(m, fm);
}
return (l + r) / 2;
}
int main(int argc, const char* argv[]) {
typedef double point;
const point T = stod(argv[1]);
const point error_margin = /*+-*/1;
// Read input. Assumed to be sorted.
vector<point> X, Y(1);
for (auto* P : {&X, &Y}) {
string line; getline(cin, line);
stringstream s(line);
copy(
istream_iterator<point>(s), istream_iterator<point>(),
back_inserter(*P)
);
}
// Add wrap-around points to Y to simplify distance calculation
Y[0] = Y.back() - T; Y.push_back(Y[1] + T);
for (point y : Y) {
// For each point y in Y we rotation X so that the last point in X
// aligns with y.
auto rotation = mod(y - X.back(), T);
// See if the rest of X aligns within the error margin
if (all_of(
X.begin(), X.end(), [=, &Y] (point x) {
return binary_search(
Y.begin(), Y.end(), mod(x + rotation, T),
epsilon_less<point>{error_margin}
);
}
)) {
// We found a rotation. Minimize the distance within the error
// margin.
rotation = minimize(
[&] (point r) { return distance(T, X, Y, r); },
rotation - error_margin, rotation + error_margin
);
// Print results and exit.
cout.precision(12);
cout << "Rotation: " << rotation << endl;
cout << "Distance: " << distance(T, X, Y, rotation) << endl;
return 0;
}
}
// We didn't find a rotation. Something must have went wrong!
return 1;
}
```
The program assumes *X* is a rotated subset of *Y* with an error margin of *±1* for each point in *X*.
It tries to rotate *X* such that it aligns with *Y* within this error margin (that is, s.t. each point in *X* is at distance at most *1* from *Y*.)
The reason that we can do this efficiently is that we don't have to try arbitrary rotations:
It's enough to choose an arbitrary point *x* in *X* and rotate *X* such that *x* aligns with each of the points in *Y*.
For one such rotation it's guaranteed that *X* and *Y* align within the error range;
for every other rotation, it's very unlikely that even two points will align, so we can abandon nonoptimal rotations very quickly.
It's extremely unlikely that two different rotations will both align *X* and *Y*, so once the program finds a rotation that does it doesn't bother to look any further.
Once a rotation is found, it's adjusted within the error margin to minimize the overall distance.
Results:
```
T Rotation Distance
1,000 494.64423 5.59189
10,000 6,967.55630 45.03235
100,000 24,454.48700 471.71127
1,000,000 974,011.50572 4,671.75611
10,000,000 2,720,706.49829 46,816.15372
Total distance: 52,010.24535
Score: 10.60236
```
[Answer]
## Mathematica, 1.04834
Okay, maybe people just need to be shown how simple it is to perform better than the reference implementation.
So here is a random implementation. I'm simply trying out some 10,000 random rotations (basically, as many as I care to wait for) and pick the best one I find.
```
First@SortBy[(
r = RandomReal[t];
f =
Nearest[Flatten[{First[z = Sort@Mod[y + r, t]] + t, z,
Last@z - t}]];
{r, Total[Abs[# - f[#][[1]]~Mod~t] & /@ x]}
) & /@ Range@100, Last@# &]
```
This assumes `t` to be the circumference, `x` to be the X list and `y` to be the Y list.
Results:
```
T rotation dist Reference dist
1000 494.669 5.59189 33.0305
10000 6967.74 53.6250 429.212
100000 24452.5 2774.90 4676.23
1000000 974013. 27023.3 49149.0
10000000 9315070 496149. 497144.
=======
Sum: 526006.
Score: 1.04834
```
Unfortunately, T = 107 takes too long to run more than 600 trials, such that I can hardly beat the reference implementation there (and even more unfortunately, this dominates the score). This still shows that there is a lot of improvement possible.
Fun fact: I actually wanted to submit a *proper* solution, by using one of Mathematica's minimisers on the distance function, but somehow I couldn't convince Mathematica to use my compound statement as a function to be minimised (and I wasn't patient enough to figure out why it didn't work), so I thought - well, then let's just Monte Carlo it.
[Answer]
# Java - 10.60236
As promised, Lembik:
```
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public final class SpinDots {
public static void main( String[] sArgs ) {
final int T = Integer.parseInt( sArgs[0] );
List<Double> LDX = new LinkedList<>(),
LDY = new LinkedList<>();
double RS = 0.;
try( BufferedReader BR = new BufferedReader( new FileReader( T + ".txt" ), 65536 ) ) {
String SX = BR.readLine();
StringTokenizer STX = new StringTokenizer( SX );
while( STX.hasMoreTokens() )
LDX.add( Double.parseDouble( STX.nextToken() ) );
String SY = BR.readLine();
StringTokenizer STY = new StringTokenizer( SY );
while( STY.hasMoreTokens() )
LDY.add( Double.parseDouble( STY.nextToken() ) );
RS = Double.parseDouble( BR.readLine() );
BR.close();
} catch( IOException ioe ) {
System.err.println( "Unable to read contents of file: " + T + ".txt" );
System.exit( 1 );
}
final int NX = LDX.size(),
NY = LDY.size(),
RNY = 2*NY+3;
final double[] DX = new double[NX],
DY = new double[RNY];
final int[] X = new int[NX],
Y = new int[RNY];
int[] YS = new int[RNY],
YSP = new int[RNY];
int dx = 0;
for( Double dx_ : LDX ) {
DX[dx] = dx_;
X[dx] = (int)Math.round( dx_ );
dx++;
}
Arrays.sort( X );
Arrays.sort( DX );
int dy = 1;
for( Double dy_ : LDY ) {
DY[dy] = dy_;
DY[dy+NY] = dy_+T;
Y[dy] = (int)Math.round( dy_ );
Y[dy+NY] = Y[dy] + T;
dy++;
}
DY[0] = DY[NY] - T;
DY[2*NY+1] = DY[1] + 2*T;
DY[2*NY+2] = DY[2] + 2*T;
Y[0] = Y[NY] - T;
Y[2*NY+1] = Y[1] + 2*T;
Y[2*NY+2] = Y[2] + 2*T;
System.out.println( "Computing optimum shift for: |X| = " + NX + ", |Y| = " + NY + ", T = " + T );
int DO_ = scoreForShiftFirstPass( X, Y, YSP );
List<Integer> LXO = new LinkedList<>(),
LDXO = new LinkedList<>();
LXO.add( 0 );
LDXO.add( DO_ );
for( int iShift = 1; iShift < T; iShift++ ) {
int D_ = scoreForShift( X, Y, iShift, YSP, YS );
int[] YT = YSP;
YSP = YS;
YS = YT;
if( D_ < DO_ ) {
DO_ = D_;
Iterator<Integer> I = LXO.iterator(),
DI = LDXO.iterator();
while( DI.hasNext() ) {
I.next();
if( DI.next() > DO_ + NX ) {
DI.remove();
I.remove();
}
}
}
if( D_ <= DO_ + NX && LXO.size() < 100 ) {
LXO.add( iShift );
LDXO.add( D_ );
}
if( iShift %(T/100) == 0 )
System.out.println( "Completed " + (iShift*100/T) + "% of coarse pass." );
}
System.out.println( "Completed 100% of coarse pass. Coarse optimum is: " + DO_ );
System.out.println( "Identified " + LXO.size() + " fine filtering candidates." );
double ddoo = 0.;
double DDOO_ = Double.MAX_VALUE;
for( int iShift : LXO ) {
double DDO_ = doubleScoreForShiftFirstPass( DX, DY, iShift-1, YSP );
double ddo = iShift;
for( int iFineShift = -999; iFineShift < 1000; iFineShift++ ) {
double dd = iShift + iFineShift/1000.0;
double DD_ = doubleScoreForShift( DX, DY, dd, YSP, YS );
int[] YT = YSP;
YSP = YS;
YS = YT;
if( DD_ < DDO_ ) {
DDO_ = DD_;
ddo = dd;
}
}
if( DDO_ < DDOO_ ) {
DDOO_ = DDO_;
ddoo = ddo;
}
}
System.out.println( "Fine optimum is: " + DDOO_ );
double ddooo = ddoo-1e-3;
double DDOOO_ = doubleScoreForShiftFirstPass( DX, DY, ddoo-1e-3, YSP );
for( int iHyperFineShift = -999; iHyperFineShift < 1000; iHyperFineShift++ ) {
double dd = ddoo + iHyperFineShift/1.e6;
double DD_ = doubleScoreForShift( DX, DY, dd, YSP, YS );
int[] YT = YSP;
YSP = YS;
YS = YT;
if( DD_ < DDOOO_ ) {
DDOOO_ = DD_;
ddooo = dd;
}
}
System.out.println( "Optimal forward rotation in X: " + ddooo );
System.out.println( "Optimal score: " + DDOOO_ );
System.out.println( "Reference score: " + RS );
}
static int scoreForShift( int[] X, int[] Y, int iShift, int[] YSP, int[] YS ) {
int D_ = 0;
for( int x = 0; x < X.length; x++ ) {
int x_ = X[x]+iShift;
int y = YSP[x],
y_ = Y[y];
int D = x_ < y_ ? y_ - x_ : x_ - y_;
int y_nx_ = Y[y+1];
int D_nx = x_ < y_nx_ ? y_nx_ - x_ : x_ - y_nx_;
while( D_nx <= D ) {
D = D_nx;
y_nx_ = Y[++y+1];
D_nx = x_ < y_nx_ ? y_nx_ - x_ : x_ - y_nx_;
}
YS[x] = y;
D_ += D;
}
return D_;
}
static int scoreForShiftFirstPass( int[] X, int[] Y, int[] YS ) {
int D_ = 0;
int y = 0;
for( int x = 0; x < X.length; x++ ) {
int x_ = X[x];
int y_ = Y[y];
int D = x_ < y_ ? y_ - x_ : x_ - y_;
int y_nx_ = Y[y+1];
int D_nx = x_ < y_nx_ ? y_nx_ - x_ : x_ - y_nx_;
while( D_nx <= D ) {
D = D_nx;
y_nx_ = Y[++y+1];
D_nx = x_ < y_nx_ ? y_nx_ - x_ : x_ - y_nx_;
}
YS[x] = y;
D_ += D;
}
return D_;
}
static double doubleScoreForShift( double[] X, double[] Y, double d_Shift, int[] YSP, int[] YS ) {
double D_ = 0;
for( int x = 0; x < X.length; x++ ) {
double x_ = X[x]+d_Shift;
int y = YSP[x];
double y_ = Y[y];
double D = x_ < y_ ? y_ - x_ : x_ - y_;
double y_nx_ = Y[y+1];
double D_nx = x_ < y_nx_ ? y_nx_ - x_ : x_ - y_nx_;
while( D_nx <= D ) {
D = D_nx;
y_nx_ = Y[++y+1];
D_nx = x_ < y_nx_ ? y_nx_ - x_ : x_ - y_nx_;
}
YS[x] = y;
D_ += D;
}
return D_;
}
static double doubleScoreForShiftFirstPass( double[] X, double[] Y, double d_Shift, int[] YS ) {
double D_ = 0;
int y = 0;
for( int x = 0; x < X.length; x++ ) {
double x_ = X[x]+d_Shift;
double y_ = Y[y];
double D = x_ < y_ ? y_ - x_ : x_ - y_;
double y_nx_ = Y[y+1];
double D_nx = x_ < y_nx_ ? y_nx_ - x_ : x_ - y_nx_;
while( D_nx <= D ) {
D = D_nx;
y_nx_ = Y[++y+1];
D_nx = x_ < y_nx_ ? y_nx_ - x_ : x_ - y_nx_;
}
YS[x] = y;
D_ += D;
}
return D_;
}
}
```
My approach is similar to Ell's in that it does a grid search over all potentials (first at integer resolution, then at a resolution of 1/1,000ths, then at a resolution of 1/1,000,000ths). Unlike Ell's approach, mine doesn't require or make use of the fact that the error in `X` is tightly bounded. I literally evaluate all 10,000,000 possibilities during coarse filtering in the `T = 10,000,000` case and store a list of candidates with distance small enough to be within "fine filtering" distance of the optimum.
Modular arithmetic is slow, and Java doesn't support template methods for native types. Hence my implementation "unwinds" `Y` to avoid the use of remainder operators, and the four working methods are near-identical clones of each other with differing types and 1-2 lines of code that would be handled in C/C++ using templates and macros.
I compute shifts sequentially, which allows the nearest neighbour search to incrementally tweak values from the previous shift. As a result, the routine completes in about 2 hours, which was acceptable since I slept through it. ;)
My outcomes are technically better than Ell's since I search to a higher resolution, but the improvement is utterly negligible, and probabilistic to boot. In particular, a higher resolution search only yields an improved score if the number of shifted `X` values falling in the set of intervals `[Y-eps,Y]` is different from the number of shifted `X` values falling in the set of intervals `[Y,Y+eps]`, where `eps` is the coarser resolution (`0.000001`, in the case of Ell's implementation). I don't know if this is the case for any of the datasets in this problem. In any event, his code should "win" since it predates mine.
**Output**
```
Optimal forward rotation in X: 494.64500000000004
Optimal score: 5.591890690289915
Reference score: 33.0305238422
Optimal forward rotation in X: 6967.556309
Optimal score: 45.032350687407416
Reference score: 429.211871389
Optimal forward rotation in X: 24454.487003000002
Optimal score: 471.7112722703896
Reference score: 4676.23391624
Optimal forward rotation in X: 974011.505734
Optimal score: 4671.756109326729
Reference score: 49148.9676631
Optimal forward rotation in X: 2720706.498309
Optimal score: 46816.15372609813
Reference score: 497143.882534
```
[Answer]
## C++, Optimal, O(|X|\*|Y|\*log|X|)
Where X = T / 50 and Y = T / 5. It may take about 2 days on my laptop to finish the T = 10000000 case.
Given two set of points `X` and `Y`. We denote the function `f(x)` to be:
```
f(x) = min(|x - y| for y in Y)
```
And then answer we want is:
```
dist = min(sum(f(x + t) for x in X) for t in [0, T))
```
However, it's impossible and unnecessary to try all the values of `t`. Instead we try the `t` values on "key points". My approach is a scanning from t = 0 to t = T with the help of a priority queue. There will have `|X| * |Y|` key points and trying each will need `O(log|X|)` operations. So the overall time complexity is `O(|X|*|Y|*log|X|)`.
### Score
```
T angle dist ref_dist
1000.0 494.64422766 5.59189069 33.03052384
10000.0 6967.55630010 45.03235069 429.21187139
100000.0 24454.48700190 471.71127227 4676.23391624
1000000.0 974011.50572340 4671.75610935 49148.96766310
10000000.0 (still running...)
```
### Code
```
#include <iostream>
#include <cstdio>
#include <cassert>
#include <string>
#include <sstream>
#include <cmath>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
struct Answer {
double angle;
double dist;
};
double check(double T, const vector<double>& xs, const vector<double>& ys, Answer answer) {
double dist = -answer.dist;
double angle = answer.angle;
for(double x : xs) {
double x1 = x + angle;
while(x1 > T) x1 -= T;
int i = upper_bound(ys.begin(), ys.end(), x1) - ys.begin();
double d;
if(i == 0) {
d = min(ys[0] - x1, x1 - (ys.back() - T));
} else if(i == ys.size()) {
d = min(ys[0] + T - x1, x1 - ys.back());
} else {
d = min(ys[i] - x1, x1 - ys[i - 1]);
}
dist += d;
}
return dist;
}
Answer solve(double T, const vector<double>& xs, vector<double> ys) {
assert(ys.size() >= 1);
sort(ys.begin(), ys.end());
vector<double> ps;
ps.push_back(ys.back() - T);
for(int i = 0; i < ys.size(); i++) {
ps.push_back((ps.back() + ys[i]) / 2);
ps.push_back(ys[i]);
}
ps.push_back((ps.back() + ys.front() + T) / 2);
ps.push_back(ys.front() + T);
struct X {
double npd;
int sign;
int j;
bool operator<(const X& rhs)const {
return npd > rhs.npd;
}
};
priority_queue<X> que;
int count = 0;
Answer ans, cur;
cur.angle = 0;
cur.dist = 0;
for(int i = 0; i < xs.size(); i++) {
double x = xs[i];
int j = upper_bound(ps.begin(), ps.end(), x) - ps.begin();
assert(j > 0 && j < ps.size());
X q;
q.j = j;
q.sign = j % 2 == 1 ? 1 : -1;
if(q.sign == 1) {
cur.dist += x - ps[j - 1];
} else {
cur.dist += ps[j] - x;
}
count += q.sign;
q.npd = ps[j] - x;
que.push(q);
}
ans = cur;
while(cur.angle < T) {
X q = que.top(); que.pop();
double da = q.npd - cur.angle;
cur.dist += da * count;
cur.angle += da;
assert(cur.dist >= 0);
if(cur.dist < ans.dist) {
ans = cur;
}
count -= q.sign * 2;
q.sign *= -1;
if(q.j == ps.size() - 1) {
q.j = 3;
} else {
q.j ++;
}
int j = q.j;
q.npd = cur.angle + ps[j] - ps[j - 1];
que.push(q);
}
double d_dist = check(T, xs, ys, ans);
cerr << "check: " << d_dist << endl;
ans.dist += d_dist;
return ans;
}
vector<double> read_nums() {
stringstream ss;
string line;
while(line.empty()) getline(cin, line);
ss << line;
vector<double> xs;
while(ss) {
double x;
if(ss >> x)
xs.push_back(x);
}
return xs;
}
int main() {
#ifdef DEBUG
freopen("1000.txt", "r", stdin);
#endif
double T;
cin >> T;
vector<double> xs = read_nums();
vector<double> ys = read_nums();
double ref_dist;
cin >> ref_dist;
Answer ans = solve(T, xs, ys);
printf("%16s %16s %16s %16s\n", "T", "angle", "dist", "ref_dist");
printf("%16.1f %16.8f %16.8f %16.8f\n", T, ans.angle, ans.dist, ref_dist);
}
```
### A bit of details
The function `f(x)` is something like:

So the graph of sum `d(t) = sum(f(x + t) for x in X)` is will be a set of connected segments. We need to try each `t` on the connecting points, with the help of a priority queue.
] |
Subsets and Splits