title: Operations on Sets

text:
# Question
Title: Operations on Sets
**Note:** I have accepted an answer, but I'm willing to accept a better answer if it comes.

Write a program that computes operations on sets. You may take input either from standard input or from command line arguments. Your program must be able to compute unions, intersections, relative complements, and cartesian products. Output should be the result of these operations.

You may not use built-in functions to do the work for you.

## Input Format

`<A>` and `<B>` represent sets. The format for sets can be anything that is convenient, as long as it *actually represents a set* (no taking advantage of this "looseness"). The elements of a set don't always have to be in the same order because sets aren't ordered. You define what kind of object these elements can be (integers, letters, ...).

* Union: `union <A> <B>`
* Intersection: `intersect <A> <B>`
* Relative complement (difference of sets): `complement <A> <B>`
* Cartesian product: `product <A> <B>` (format for ordered pairs can be anything convenient -- don't take advantage of this "looseness" either)

**For info on what these operations even are, see the Wikipedia page on it.**

# Answer
### GolfScript, 73 characters

```
.' '?:^>~`"~{:^1$?0<{[^]+}*}/
{\\`{[\\]}+/}+%
{?0<!}+,
{?0<}+,"n/^2/2-=~`

```

Uses non of the GolfScript set operators and should work on all valid GolfScript objects. Input must be given on STDIN, for format see also the online examples.

```
> union [1 2 3] [2 3 4]
[1 2 3 4]

> intersect [1 2 3] [2 3 4]
[2 3]

> complement [1 2 3] [2 3 4]
[1]

> product [1 2 3] [2 3 4]
[[1 2] [1 3] [1 4] [2 2] [2 3] [2 4] [3 2] [3 3] [3 4]]

```

The code does not use GolfScript's set operators but implements them using loops.

```
.' '?        # find the first space character in the input
:^>          # save the position to variable ^ and remove from start of string
~            # evaluate the string (i.e. get two sets as arguments)
`            # transform the second set into a string
"..."n/      # generates an array of 4 strings which represent the set operations
             # (see below)
^2/2-        # take position of the first space (i.e. length of the operator)
             # divide by two, subtract two (i.e. union->0, intersect->2,
             # complement->3, product->1)
=~           # take the corresponding command string and evaluate on the arguments
`            # transform the result back into a string representation

### union
~{           # evaluate the second argument (i.e. revert the ` operation)
             # and loop over all items
  :^         #   save item to variable ^
  1$?        #   is it contained in the first set?
  0<{        #   if no then
    [^]+     #     add to set
  }*         #   end if
}/           # end loop

### intersection
{            # prepend second argument to code block {...}+ and filter the first set
  ?0<!       #   is the current item contained in the second set? if yes, keep
}+,          # end filter block

### complement
{            # prepend second argument to code block {...}+ and filter the first set
  ?0<!       #   is the current item contained in the second set? if no, keep
}+,          # end filter block

### product
{            # prepend second argument to code block {...}+ and map on first set
  \`{        #   take current item and prepend to code block `{...}+ and iterate
    [\]      #     swap both items (item of second set + item of first set) and
             #     build a tuple of them
  }+/        #   end loop
}+%          # end map

```
> 5 votes

# Answer
## Ruby, 97 characters

```
$_,a=$*;A,B=eval a
p (~/c/?B.map{|i|~/d/?A.map{|j|[i,j]}:!A.index(i)^~/m/?p: i}:A+B).uniq.compact

```

Usage examples:

```
$ ruby set.rb union [[1,2,3],[8]]
[1, 2, 3, 8]
$ ruby set.rb complement [[1,2,3,6,7],[7,2,1,5]]
[5]
$ ruby set.rb intersect [[1,2,3,6,7],[7,2,1,5]]
[7, 2, 1]
$ ruby set.rb product [[1,2],[7,5,2]]
[[[7, 1], [7, 2]], [[5, 1], [5, 2]], [[2, 1], [2, 2]]]

```
> 3 votes

# Answer
# GolfScript, 77 characters

```
(\~@99-:x{6x={&}{13x={'"#{['@','*+'].product ['+\','*+']}"'+~}{|}if}if}{-}if`

```

Sample inputs and outputs:

```
$ echo "union [1 2 3] [2 3 4]" | golfscript setops.gs
[1 2 3 4]
$ echo "intersect [1 2 3] [2 3 4]" | golfscript setops.gs
[2 3]
$ echo "complement [1 2 3] [2 3 4]" | golfscript setops.gs
[1]
$ echo "product [1 2 3] [2 3 4]" | golfscript setops.gs
"[[1, 2], [1, 3], [1, 4], [2, 2], [2, 3], [2, 4], [3, 2], [3, 3], [3, 4]]"

```

---

Okay, now time to explain this gobbledygook. First, here's an explanation of how it chooses which one of the four blocks (union, intersect, complement, product) to execute.

I noticed something convenient about these commands. They each begin with a unique letter (`u`, `i`, `c`, `p`). Therefore, we only care about this first letter.

Now, to make the code even shorter, these can be converted into ASCII codes (117, 105, 99, 112). Here's an explanation of the main logic of the program:

```
(     # grab the ASCII code of the first letter of the input string
\~    # evaluate the rest of the string. GS will ignore "nion", "tersect", etc.
@     # stack is now [A B CMD]
99-:x # subtract 99 for shorter code. Now 'uicp' maps to [18 6 0 13]

```

After this comes a huge chain of `if`s. With the set operation logic removed, it looks like this:

```
{6x={INTERSECT_CODE}{13x={PRODUCT_CODE}{UNION_CODE}if}if}{COMPLEMENT_CODE}if`

```

Converted to a more readable C-like format, it looks like this:

```
if (x) {
  if (x == 6) {
    INTERSECT_CODE
  } else {
    if (x == 13) {
      PRODUCT_CODE
    } else {
      // x must be 18
      UNION_CODE
    }
  }
} else {
  // x is 0
  COMPLEMENT_CODE
}

```

Now, it's just a matter of looking at the code for the set operations. Most of them are fairly straightforwards: `&` for intersect, `|` for union, and `-` for complement. However, GolfScript doesn't have a built-in product operator, so I had to build some Ruby code for that. Here's an explanation of that mess:

```
'"#{['         # stack: [1 2 3] [2 3 4] '"#{['
@','*+         # stack: [2 3 4] '"#{[1,2,3'
'].product ['+ # stack: [2 3 4] '"#{[1,2,3].product ['
\','*+         # stack: '"#{[1,2,3].product [2,3,4'
']}"'+         # stack: '"#{[1,2,3].product [2,3,4]}"'
~              # evaluate

```

Simply tack on a ``` to show array output correctly, and it's done!
> 2 votes

# Answer
# Bash+coreutils, 200 bytes

I'm not exactly sure what *"You may not use built-in functions to do the work for you"* means, but I am assuming it means no use of APIs **specifically** designed for handling sets. Some of the coreutils used here might be considered to come close, but I am asserting that these utilities operate on files and lines of files, and not specifically on sets:

```
f()(tr \  \\n<<<$1|sort -u)
c()(comm -2$1 <(echo "$a") <(echo "$b"))
a=`f "$2"`
b=`f "$3"`
case $1 in
u*)sort -u<<<"$a
$b";;i*)c 1;;c*)c 3;;p*)eval printf '%s\\n' {${a//$'\n'/,}},{${b//$'\n'/,}};;esac

```

The **union**, **intersect** and **complement** cases are relatively uninteresting calls to `sort` and `comm`. The **product** case uses bash brace expansion. For example `echo {1,2,3},{a,b}` produces the output `1,a 1,b 2,a 2,b 3,a 3,b`. The catch here is that brace expansion normally occurs before variable expansion, so the whole thing must be `eval`ed so the variables are effectively expanded first.

Example output:

```
$ ./sets.sh union "1 2 3 4 3 2 1" "2 4 6 4 6"
1
2
3
4
6
$ ./sets.sh intersect "1 2 3 4 3 2 1" "2 4 6 4 6"
2
4
$ ./sets.sh complement "1 2 3 4 3 2 1" "2 4 6 4 6"
1
3
$ ./sets.sh product "1 2 3 4 3 2 1" "2 4 6 4 6"
1,2
1,4
1,6
2,2
2,4
2,6
3,2
3,4
3,6
4,2
4,4
4,6
$

```
> 2 votes

# Answer
## Haskell, ~~123~~ 96 bytes

Saved the `import Control.Applicative` part since `liftA2` is now in `Prelude`.

Not sure whether this is considered cheating, but:

```
union=liftA2(||)
intersect=liftA2(&&)
complement f=liftA2(&&)f.(not.)
product f g (x,y)=f x&&g y

```

If allowed, `product` could be curried to save extra 1 byte.

The key idea is to implement sets as a predicate (`a -> Bool`) that returns `True` if the element is present. This can represent not only finite sets, but also infinite sets.

Being possibly infinite, the outputted set cannot be represented in a string, but it can be queried:

```
Prelude> union (\_->False) (\_->False) 0
False
Prelude> union (\_->False) (\_->True) 0
True
Prelude> union (\_->False) even 0
True
Prelude> union (\_->False) odd 0
False
Prelude> union even odd 0
True
Prelude> intersect (\_->False) (\_->True) 0
False
Prelude> intersect (\_->True) even 0
True
Prelude> intersect odd even 0
False
Prelude> complement (\_->True) even 0
False
Prelude> complement (\_->True) odd 0
True
Prelude> product even odd (0,0)
False
Prelude> product even odd (0,1)
True
Prelude> product even odd (1,1)
False

```
> 2 votes

# Answer
# Axiom, 186 bytes

```
union(a,b)==removeDuplicates concat(a,b)
intersection(a,b)==[x for x in a|member?(x,b)]
complement(a,b)==[x for x in a|~member?(x,b)]
product(a,b)==concat[[[x,y]for y in b]for x in a]

```

All input for above function has to be List \[of ints\] that have not repetition (for to be a set).

Here the necessary functions for see if one List is a set and for see if two set are equals:

```
isEq?(a,b)==(#a~=#b=>false;(sort(a)=sort(b))@Boolean)
isSet?(a)==isEq?(removeDuplicates(a),a)

```

Some results

```
(9) -> union([1,2,3], [2,3,4])
   (9)  [1,2,3,4]
                                               Type: List PositiveInteger
(10) -> intersection([1,2,3], [2,3,4])
   (10)  [2,3]
                                               Type: List PositiveInteger
(11) -> complement([1,2,3], [2,3,4])
   (11)  [1]
                                               Type: List PositiveInteger
(12) -> product([1,2,3], [2,3,4])
   (12)  [[1,2],[1,3],[1,4],[2,2],[2,3],[2,4],[3,2],[3,3],[3,4]]
                                          Type: List List PositiveInteger

```
> 1 votes

# Answer
# TypeScript's Type System, No Ignore, 353 339 222 219 Bytes

```
type X<S>=S extends`${infer O extends"u"|"i"|"c"|"p"}${any} ${infer A} ${infer B}`?{u:X<A|B>,i:X<A>&X<B>,c:Exclude<X<A>,X<B>>,p:{[K in X<A>]:{[I in X<B>]:[K,I]}}[X<A>][X<B>]}[O]:S extends`${infer A},${infer R}`?A|X<R>:S

```

## Explanation

We can check the first character (infer O) to check if it's union, intersect, complement, or product. However, if it doesn't extend it, we can parse the array of values provided (as this is a self-recursive function). Set operations are native to TypeScript's Type System, so implementing each one is trivial, with union and intersect being native TS operators (`|` and `&` accordingly), cartesian joins using a joined json object, and complement using the `Exclude` type.

TypeScript Playground
> 1 votes

# Answer
## PowerShell, 131

```
param($o,[array]$a,[array]$b)switch($o[0]){'u'{$a+$b|sort -u}'i'{$a|?{$_-in$b}}'c'{$b|?{$_-notin$a}}'p'{$a|%{$x=$_
$b|%{"$x,$_"}}}}

```

Fairly straightforward rendition of all the operators. Sets are given as comma-separated lists and the script takes arguments:

```
PS> .\set.ps1 union 1,2,3 8
1
2
3
8
PS> .\set.ps1 intersect 1,2,3,6,7 7,2,1,5
1
2
7
PS> .\set.ps1 complement 1,2,3,6,7 7,2,1,5
5
PS> .\set.ps1 product 1,2 7,5
1,7
1,5
2,7
2,5

```
> 0 votes

# Answer
# APL NARS 100 chars

```
union←{∪⍺,⍵}⋄intersection←{(⍺∊⍵)/⍺}⋄complement←{(∼⍺∊⍵)/⍺}
∇r←x product y;i;j
r←⍬⋄:for i:in x⋄:for j:in y⋄r←r,⊂(i,j)⋄:endfor⋄:endfor

```

the symbol ∪ in union above means "each elment appear one time only" so it doesn't make union. They are about 135 chars but if i cut the names of anonimous functions it would be 100 chars(25+19+56=100 chars). Test

```
  1 2 3 union 2 3 4
1 2 3 4
  1 2 3 intersection 2 3 4
2 3
  1 2 3 complement 2 3 4
1
  1 2 3 product 2 3 4
1 2  1 3  1 4  2 2  2 3  2 4  3 2  3 3  3 4

```

The APL functions for doing above union, intersection, complement and product could be:

```
  sysunion←∪
  sysintersection←∩
  syscomplement←∼
  sysproduct←{,⍺∘.,⍵}
  1 2 3 sysunion 2 3 4
1 2 3 4
  1 2 3 sysintersection 2 3 4
2 3
  1 2 3 syscomplement 2 3 4
1
  1 2 3 sysproduct 2 3 4
1 2  1 3  1 4  2 2  2 3  2 4  3 2  3 3  3 4
  x←1 3
  y←2 3
  x sysproduct y
1 2  1 3  3 2  3 3

```
> 0 votes

# Answer
# , 105 bytes

```
function(A,B)list(U<-unique(c(A,B)),U[U%in%A&U%in%B],A[!A%in%B],cbind(rep(A,sum(B|1)),rep(B,e=sum(A|1))))

```

Try it online!

Returns a `list` with four elements, the Union, the Intersection, the Difference, and the Cartesian Product, in that order.

Takes input as an R vector of integers.

The Union is the unique values in the concatenation of the two vectors, `U=unique(c(A,B))`.

The Intersection is the subset of the Union where `x in A & x in B`, so `U[U%in%A&U%in%B]`.

The Set Difference is those `a in A` where `a notin B`, so `A[!A%in%B]`

The Cartesian Product is returned as a matrix where each row is an ordered pair. It repeats `A` `|B|` times and the elements of `B` `|A|` times each, then binds them together as matrix columns, i.e.:

```
cbind(                # bind as matrix columns
 rep(A,sum(B|1)),     # repeat A |B| times (concatenate |B| copies of A)
 rep(B,e=sum(A|1)))   # repeat each element of B |A| times

```
> 0 votes

---
Tags: code-golf, math, set-theory
---


title: Partial sums of the Kempner series

text:
# Question
Title: Partial sums of the Kempner series
The Kempner series is a series that sums the inverse of all positive integers that don't contain a "9" in their base-10 representations (i.e., \\$\frac{1}{1} + \frac{1}{2} + \frac{1}{3} + .. + \frac{1}{8} + \frac{1}{10} + ...\\$).

It can be shown that, unlike the Harmonic series, the Kempner series converges (to a value of about 22.92067661926415034816).

**Your task is to find the partial sums of the Kempner series.** These are the ways you can do it:

* Take a number \\$n\\$, and return the sum of the inverse of the first \\$n\\$ numbers that don't have a "9" in them, which is the \\$n\\$th partial sum of the series.
* Take a number \\$n\\$, and return the first \\$n\\$ partial sums of the series.
* Don't take any input and output the partial sums infinitely.

You can choose if your input is 0-indexed or 1-indexed.

~~Your algorithm result's distance from the correct value may not be over \\$10^{-4}\\$, for all possible values of \\$n\\$.~~ While your algorithm should work theoretically for all values for N, you may ignore inaccuracies coming from floating-point errors.

Test cases, in case of returning the \\$n\\$th partial sum, 0-indexed:

```
0 -> 1.0
1 -> 1.5
9 -> 2.908766...
999 -> 6.8253...

```

Standard loopholes are disallowed.

This is , so the shortest answer in bytes wins.

# Answer
# Jelly, ~~7~~ 6 bytes

```
Rb9ḌİS

```

Try it online!

*-1 byte thanks to @Razetime*

Takes input 1-indexed as an argument (footer on TIO converts to 0-indexed like in test cases)

Returns the nth partial sum

### How it Works

Let's look at the denominators in base 10:

\\$\[1, 2, 3, 4, 5, 6, 7, 8, 10,11,12,13,...\]\\$ (base 10)

Since these consist of the nine base-9 digits, we can interpret them as base 9 strings:

\\$\[1\_9, 2\_9, 3\_9, 4\_9, 5\_9, 6\_9, 7\_9, 8\_9, 10\_9, 11\_9, 12\_9, 13\_9, ...\]\\$

\\$=\[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 \]\\$ (base 10)

So all of the denominators can be generated as natural numbers, converted to base 9, then interpreted as base 10.

```
Rb9ḌİS - main link, taking n (1-indexed)
R       - convert to list [1..n]
 b9     - convert each natural number to base 9
   Ḍ   - interpret each base-9 string as base 10 (decimal)
    İ  - reciprocal
     S - sum

```
> 13 votes

# Answer
# Ruby, 52 39 36 bytes

*-13 bytes thanks to Dingus!*

*-3 bytes thanks to Sisyphus*

```
x=0;"#$."[?9]||p(x+=1r/$.)while$.+=1

```

Try it online!

Prints all values.
> 5 votes

# Answer
# 05AB1E, ~~9~~ 5 bytes

-4(!) bytes thanks to Command Master!

Outputs one value 1-indexed

```
L9BzO

```

Try it online! or Try all cases!

```
L      # push the range [1..n]
 9B    # convert each number to base 9
       # this yields the first n natural numbers that don't contain a 9
   z   # take reciprocal of each number
    O  # sum the list

```
> 4 votes

# Answer
# Scala, 56 bytes

```
Stream from 1 filterNot(_+""toSet 57)take _ map 1.0./sum

```

Try it online!

1-indexed. Returns the sum of the inverses of the first \\$n\\$ numbers.

```
Stream from 1      //Infinite list of integers, starting at 1
  filterNot(       //Remove the ones with a 9
    _ + ""         //Convert to string
      toSet        //A Set is also a predicate. Check if it contains
      57)          //57, '9' as an integer
  take _           //Take the first n numbers
  map 1.0./        //Divide 1 by each
  sum              //Sum them

```

## Just for completeness, 58 bytes

```
(Stream.from(1)filterNot(_+""toSet 57)scanLeft.0)(_+1.0/_)

```

Try it online!

This is an infinite stream of partial sums, but also a function that gives the \\$n\\$th partial sum (1-indexed). You can also use `take` on it to get the first \\$n\\$ partial sums. Unfortunately, it's a little longer than the version above.
> 3 votes

# Answer
# Husk, ~~12~~ 10 bytes

Saved 2 bytes on both solutions thanks to @Razetime!

```
ṁ\↑fȯ¬#9dN

```

Try it online!

It's been a while since my last Husk answer. This one outputs the \\$n\\$th number. It outputs a fraction, but I've checked and it seems to be correct.

Explanation

```
ṁ\↑fȯ¬#9dN
         N    Infinite list of natural numbers
   f          Filter by predicate:
        d     Digits in base 10
      #9      Number of occurrences of digit 9
     ¬        Negate that
  ↑           Take the first n elements (implicit input)
ṁ\            Map each to its reciprocal
ṁ             And sum

```

### Infinite sequence, also ~~12~~ 10 bytes

```
∫m\fȯ¬#9dN

```

Try it online!
> 3 votes

# Answer
# Jelly, 8 bytes

```
1w9¬$#İS

```

Try it online!

1-indexed, takes input from STDIN, returns the \\$n\\$th partial sum

My last Jelly answer of the year, and it just so happens to outgolf Husk!

## How it works

```
1w9¬$#İS - Main link. Takes no arguments
1   $#   - Find the first n numbers that meet the following criterion:
 w9      -   The index of 9 in the number’s digits...
   ¬     -   ...is 0 (i.e. 9 is not in the digits)
      İ  - Invert each number
       S - Sum

```
> 3 votes

# Answer
# Husk, ~~8~~ 7 bytes

```
ṁȯ\dB9ḣ

```

Try it online!

Outputs the \\$n^{th}\\$ partial sum. I tried using `İ\` from here, but it's longer.

Uses fireflame's idea.

-1 byte from user.

## Explanation

```
∫mȯ\dB9N
       N the list of natural numbers
 mȯ      map to:
     B9  base 9 digits
    d    represented as base 10 number
   \     take reciprocal
∫        take the cumulative sum

```
> 3 votes

# Answer
# , 20 bytes

```
1#.10%@#.9#.inv>:@i.

```

Try it online!

I just wanted to see if I could golf fireflame's excellent Jelly answer in J.

1 based indexing.

* `>:@i.` Integers 1..argument
* `9#.inv` Each as a list of digits in base 9
* `10#.` Back to single number in base 10
* `%@` Reciprocal of each
* `1#.` Sum
> 3 votes

# Answer
# Python 2, 54 bytes

```
f=lambda k,n=1,b=0:k<2or b/n+f(k-b,n+1,1.-('9'in`~n`))

```

Try it online!

One-indexed. Avoids repeating the `'9'in`n+1`` by passing it as an optional argument `b` to the next iteration of the function where the actual calculation is done.

**58 bytes**

```
f=lambda k,n=1.:k and f(k-1+('9'in`n`),n+1)-~-('9'in`n`)/n

```

Try it online!

**59 bytes**

```
f=lambda k,n=1:'9'in`n`and f(k,n+1)or k and 1./n+f(k-1,n+1)

```

Try it online!

**62 bytes**

```
lambda k:sum([1./n for n in range(1,k*k+1)if~-('9'in`n`)][:k])

```

Try it online!

The `k*k+1` can be `2**k`, saving a byte but making the code really slow.

**64 bytes**

```
s=0
n=1
exec"while'9'in`n`:n+=1\ns+=1./n;n+=1\n"*input()
print s

```

Try it online!

---

# Python 3.8 (pre-release), 53 bytes

```
f=lambda k,n=1:k and(b:=max(str(n))<'9')/n+f(k-b,n+1)

```

Try it online!

*Saved one byte thanks to @dingledooper.*
> 3 votes

# Answer
# Charcoal, 11 bytes

```
ＩΣ∕¹ＩＥＮ⍘⊕ι⁹

```

Try it online! Link is to verbose version of code. 1-indexed. Explanation:

```
     Ｎ      Input number
    Ｅ       Map over implicit range
         ι  Current index
        ⊕   Incremented
       ⍘  ⁹ Convert to base 9 as a string
    Ｉ       Vectorised cast to integer
  ∕¹        Vectorised reciprocal
 Σ          Sum
Ｉ           Cast to string
            Implicitly print

```
> 2 votes

# Answer
# Python 2, ~~78~~ 77 bytes

```
def f(n,i=.0,s=0):
 while n:
	i+=1
	while"9"in`i`:i+=1
	s+=1/i;n-=1
 return s

```

Try it online!
> 2 votes

# Answer
# JavaScript (Node.js), 30 bytes

```
f=n=>n&&1/n.toString(9)+f(n-1)

```

Try it online!

Convert \\$n\\$ to base 9, and read the converted result as base 10. Then inverse it. You will get the \\$n\\$th item.
> 2 votes

# Answer
# Haskell, 45 44 42 bytes

```
f=scanl(+)0[1/x|x<-[1..],all(<'9')$show x]

```

Try it online!

Infinite list. 44 byte thanks to ovs, who suggested `all(<'9')` to replace `not$elem '9'`. 42 bytes thanks to Donat, who suggested `1` to replace `1.0`.
> 2 votes

# Answer
# Japt `-mx`, 6 bytes

1-indexed

```
1/°Us9

```

Try it
> 2 votes

# Answer
# Perl 5, 26 bytes

```
/9/||say$a+=1/$_ while++$_

```

Try it online!
> 1 votes

# Answer
# AWK, 37 bytes

```
{for(;++i<=$1;)i~9?$1++:n+=1/i;$1=n}1

```

Try it online!

{
for(;++i<=$1;)  #loops while i<= the input.
                # also increments the variable 1 every loop.

  i~9?    # if there is a 9 in _i_
  $1++:   # skips this _i_, adding 1 to $1
  n+=1/i; # otherwise, adds 1/i to _n_

$1=n  # in the end, assigns _n_ to $1
}
1  # prints $1
```
</code></pre>
> 1 votes

# Answer
# Wolfram Language (Mathematica), 42 bytes

```
Tr[1/FromDigits/@Range@#~IntegerDigits~9]&

```

Try it online!
> 1 votes

# Answer
# , ~~94 93 92 64~~ 59 bytes

Thanks to Dominic van Essen for suggesting a grepl shortcut!

```
n=scan()+2;while(n<-n-1){F=F+1/T;while(grepl(9,T<-T+1))0};F

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), 46 bytes

1-indexed.

```
f=(n,i=1)=>n&&(/9/.test(i)?0:n/n--/i)+f(n,i+1)

```

Try it online!
> 1 votes

# Answer
# K (ngn/k), 13 bytes

```
+/1%10/9\1+!:

```

Try it online!

A similar approach to many other answers, modeled after @fireflame241's Jelly answer. Uses 1-based indices.

* `1+!:` generate `1..n`
* `10/9\` convert to base-9, then back to base-10
* `+/1%` take the sum of the inverses
> 1 votes

# Answer
# , ~~45~~ 43 bytes

*Edit: -2 bytes thanks to Giuseppe*

```
x=scan();y=1:x^2;sum(1/y[!grepl(9,y)][1:x])

```

Try it online!
> 1 votes

# Answer
# MathGolf, 10 bytes

```
∞╒gÉ9╧┌<∩Σ

```

Outputs the \\$n^{th}\\$ value with 1-based input \\$n\\$.

Try it online.

**Explanation:**

```
∞          # Double the (implicit) input-integer
 ╒         # Pop and push a list in the range [1,2*input]
  g        # Filter this list by,
   É       # using the following 3 characters as inner codeblock:
    9╧     #  Check that the integer contains a digit 9
      ┌    #  And invert the boolean
       <   # Only keep the first (implicit) input amount of values of the filtered list
        ∩  # Map all values to 1/n
         Σ # And sum those together
           # (after which the entire stack joined together is output implicitly as result)

```

MathGolf unfortunately doesn't contain base-conversion builtins, except for binary and hexadecimal. So I use a manual filter instead. The double at the start is to ensure we have enough values left after the filter for which we can keep the first input amount of values. After which we'll map them to \\$\frac{1}{n}\\$, and sum them together.
> 1 votes

# Answer
# Raku, 25 bytes

```
[\+] 1 X/grep {!/9/},1..*

```

Try it online!

This is an expression for an infinite sequence of the partial sums.

* `grep { !/9/ }, 1..*` is the infinite sequence of all natural numbers with no 9 digit in its decimal representation.
* `1 X/` produces the reciprocals of that sequence. (`X` is the cross-product metaoperator, combined here with the `/` division operator.)
* `[\+]` produces the partial sums of that sequence.
> 1 votes

# Answer
# SmileBASIC 4, 139 bytes

Zero-indexed. Returns the nth partial sum of the series.

```
1  DEF F(X)REPEAT INC U,X MOD 9*POW(10,I)X=X DIV 9INC I UNTIL!X RETURN U END
2  DIM O[1]@0 UNSHIFT O,O[0]+1INC S,1/F(O[0])IF N+2>LEN(0)GOTO@0
3  ?S

```

---

Newline chars on lines 1 & 2 are included in byte count. The program iterates through integers 0-N, converts each value to base 9, and adds the base-10 interpreted inverse of the value to a sum. Finally, it prints the sum.
> 0 votes

# Answer
# C (gcc), ~~87~~ 84 bytes

Saved 3 bytes thanks to ceilingcat!!!

```
m;float i,s;float f(n){for(i=s=0;m=n--;s+=1/i)for(;m;)for(m=++i;~m%10*m;m/=10);i=s;}

```

Try it online!

Inputs a \\$1\\$-indexed \\$n\\$ and returns the \\$n^{\text{th}}\\$ partial sum of the series.
> 0 votes

# Answer
# Perl 5, 39 bytes

```
sub f{my$r;$r+=!/9//$_ for 1..$_[0];$r}

```

Try it online!
> 0 votes

# Answer
# Zsh `-o forcefloat`, <sup>~~41~~</sup> 40 bytes

```
for ((;++n;))((n[(I)9]))||echo $[a+=1/n]

```

Try it online!

Outputs infinitely.

Explanation:

```
for ((;++n;))((n[(I)9]))||echo $[a+=1/n]
                                           implicitly intitialise $n and $a to 0
for ((;   ;))                              loop while
       ++n                                  increment $n (always truthy)
                        ||                   if not
               n[(I)9]                        the index of "9" in $n
             ((       ))                       is not zero,
                               $[a+=   ]      then increase $a by
                                    1/n        the reciprocal of $n
                          echo                and print $a

```
> 0 votes

# Answer
# x86 Machine Code (x87 FPU), 35 bytes

```
D9 EE 31 F6 8D 7E 0A 46 89 F0 99 F7 F7 83 FA 09 74 F5
85 C0 75 F4 89 33 DB 03 D9 E8 DE F1 DE C1 E2 E5 C3

```

The above bytes define a function that computes the *n*<sup>th</sup> partial sum of the Kempner series. The function defines a custom calling convention, whereby it accepts two arguments:

* The value *n* is passed in the `ecx` register (this is an unsigned 32-bit integer value).
* The address of a "scratch" memory buffer is passed in the `ebx` register (the buffer's size must be at least 4 bytes in length).

The function returns a single result, the *n*<sup>th</sup> partial sum, at the top of the x87 FPU stack (`st(0)`).

**Try it online!**

In ungolfed assembly language mnemonics:

```
         ; Computes the nth partial sum of the Kempner series.
         ; Input(s):
         ;   ecx = n
         ;   ebx = address of DWORD scratch buffer
         ; Output(s):
         ;   st(0) = nth partial sum
         ; Clobber(s):
         ;   eax, [ebx], ecx, edx, esi, edi, st, flags
         Kempner:
D9 EE      fldz                         ; start with partial sum == 0.0 (at top of x87)
31 F6      xor    esi, esi              ; esi = 0
8D 7E 0A   lea    edi, [esi + 10]       ; edi = 10

         PartialSum:
46         inc    esi                   ; esi += 1
89 F0      mov    eax, esi              ; eax = esi

         CheckDigit:
99         cdq                          ; zero edx (normally, prefer xor edx, edx)
F7 F7      div    edi                   ; edx:eax / edi
83 FA 09   cmp    edx, 9                ; remainder == 9?
74 F5      je     PartialSum            ; skip if digit was a 9
85 C0      test   eax, eax              ; quotient  == 0?
75 F4      jnz    CheckDigit            ; loop if more digits to check

89 33      mov    DWORD PTR [ebx], esi  ; store esi into scratch memory buffer
DB 03      fild   DWORD PTR [ebx]       ; push value from scratch memory buffer to top of x87
D9 E8      fld1                         ; push 1.0 to top of x87
DE F1      fdivrp st(1), st(0)          ; calculate 1.0 / esi
DE C1      faddp  st(1), st(0)          ; accumulate partial sum (result is at top of x87)
E2 E3      loop   PartialSum            ; decrement ecx (n), and continue looping if non-zero
C3         ret

```

---

# \[BONUS:\] x86 Machine Code (AVX), 44 bytes

```
31 F6 46 0F 57 C0 8D 7E 09 F3 0F 2A D6 4E 46 89 F0 99 F7 F7 83 FA
09 74 F5 85 C0 75 F4 C5 F2 2A CE C5 EA 5E C9 C5 FA 58 C1 E2 E3 C3

```

In ungolfed assembly language mnemonics:

```
             ; Computes the nth partial sum of the Kempner series.
             ; Input(s):
             ;   ecx = n
             ; Output(s):
             ;   xmm0 = nth partial sum
             ; Clobber(s):
             ;   eax, ecx, edx, esi, edi, xmm0, xmm1, xmm2, flags
             Kempner:
31 F6          xor       esi,  esi             ; \ set ESI to 1
46             inc       esi                   ; /
0F 57 C0       xorps     xmm0, xmm0            ; zero XMM0
8D 7E 09       lea       edi,  [esi + 9]       ; set EDI to 10
F3 0F 2A D6    cvtsi2ss  xmm2,  esi            ; set XMM2 to 1 (from ESI)
4E             dec       esi                   ; set ESI back to 0

             PartialSum:
46             inc       esi
89 F0          mov       eax,  esi

             CheckDigit:
99             cdq
F7 F7          div       edi
83 FA 09       cmp       edx,  9
74 F5          je        PartialSum
85 C0          test      eax,  eax
75 F4          jne       CheckDigit

C5 F2 2A CE    vcvtsi2ss xmm1, xmm1, esi
C5 EA 5E C9    vdivss    xmm1, xmm2, xmm1
C5 FA 58 C1    vaddss    xmm0, xmm0, xmm1
E2 E3          loop      PartialSum
C3             ret

```

This is larger, since the AVX instructions require more bytes to encode than the x87 instructions. It is essentially the direct translation of the above function targeting the x87 FPU, except that I had to be a bit clever when loading "1.0" in the AVX (`xmm2`) register. Basically, I eagerly set `esi` to 1, load it into `xmm2` using the convert-from-integer instruction, and then set `esi` back to 0. Since `inc` and `dec` are 1-byte instructions, this is the cheapest way that I could find.
> 0 votes

# Answer
# Vyxal `s`, 39 bits<sup>1</sup>, 4.875 bytes

```
9c¬)ȯĖ

```

Try it Online!

1-indexed.

## Explained

```
9c¬)ȯĖ
   )ȯ  # First #input numbers which:
 c¬    #    don't contain
9      #    the number 9
     Ė # reciprocals
# summed by the s flag

```
> 0 votes

---
Tags: code-golf, math, sequence
---


# Question
Title: "Signpost" puzzle from Tatham's collection
Simplified version of "Signpost" puzzle from Simon Tatham's Portable Puzzle Collection.

### How the puzzle is created

We pick up randomly positive integer `N` and one of permutations of `1…N`
*with `1` at the first position:*
N = 12
Numbers `1` and `N` always stay open, and `2` is always on the right of `1`.
So we look at numbers `2` and `3`. `3` is on the left from `2`, so we mark `2` with left arrow:
Next we look at `3` and `4`. `4` is on the right from `3`, so we mark `3` with right arrow:
And so on so that every arrow above the number points towards the number that follows it (though the next number can be any distance away in that direction):
After all we hide initial sequence except `1` and `N`:
and write down puzzle in form of array:

```
["1", "→", "→", "→", "→", "←", "→", "←", "12", "←", "←", "←"]

```

### Task

Given by an array of directions and two key positions, restore the initial sequence of numbers.

### Input

List of directions and keys in any form, suitable for your language: array, json, string etc.
Let for example `"→"` be `"r"` and `"←"` be `"l"`:

```
["1", "r", "r", "r", "l", "r", "l", "12", "l", "l", "l"]

```

You may take `N` as a separate input or calculate it as length of list.
You may assume that key points are given not as numbers,
but as symbols (for example `"1"` = `"b"`(egin) and `N` = `"e"`(nd) )

Input always valid: non-empty, no typos, errors and necessarily corresponds to some valid sequence.

### Output

Encrypted sequence as array, echo-print or as you like.
You may only use test cases that are composed of existing sequences and therefore have at least one solution. But if there may be several, you can print any or all of them.

### Test cases

```
In "r" / "l" / "1" / "N"  form:

["1", "2"] → [1, 2]
["1", "3", "l"] → [1, 3, 2]
["1", "r", "5", "l", "l"] → [1, 3, 5, 2, 4] or [1, 2, 5, 4, 3]
["1", "r", "6", "r", "r", "l"] → [1, 2, 6, 3, 4, 5]
["1", "r", "r", "r", "r", "l", "r", "l", "12", "l", "l", "l"] → [1, 3, 11, 5, 9, 10, 6, 8, 12, 4, 2, 7]
["1", "7", "l", "l", "l", "l", "l"] → [1, 7, 6, 5, 4, 3, 2]
["1", "r", "r", "l", "7", "l", "l"] → [1, 5, 3, 4, 7, 2, 6] or [1, 6, 4, 5, 7, 3, 2]

```

# Answer
# Vyxal, 147 bits1, 18.375 bytes

```
2€÷ṘN"ƛż*⇧⇧›;÷ṘȮL+?LpJ

```

Try it Online!

Takes input as single list without the starting symbol where `1` is an arrow to the right, `-1` is an arrow to the left and `2` is the end.

Doesn't output the first `1`.

## How?

Suppose that we have an input like this:

`> < > < e < > <`

We split the input on the end symbol and in the first part start assigning numbers to the left arrows from right to left.

```
> < > < e < > <
      1

> < > < e < > <
  2   1

```

Then assign numbers to the right arrows from left to right.

```
> < > < e < > <
3 2 4 1

```

This way the last number in the first part points to the right.

Similarly we can assign numbers to the second part in a way that the last number points to the left.

## Code explanation

```
2€÷ṘN"ƛż*⇧⇧›;÷ṘȮL+?LpJ
2€                     # split on 2
  ÷                    # push each element
   Ṙ                   # reverse
    N                  # times -1
     "                 # pair
      ƛ                # map:
       ż*              #   multiply each by it's 1-based index
         ⇧             #   grade up (sort indices by their value)
          ⇧            #   grade up
           ›           #   increment
            ;          # end map
             ÷         # push each element
              Ṙ        # reverse
               Ȯ       # copy the second to last element on the stack to the top of the stack
                L      # length
                 +     # add
                  ?L   # input length
                    p  # prepend
                     J # join

```
> 5 votes

# Answer
# Charcoal, 38 bytes

```
≔⌕Ａ…θ⌕θＩＬθrηＥθ⎇№βιＩ⁺²⌕⁺⁺⁻⌕Ａθrη⮌⌕Ａθlηκι

```

Try it online! Link is to verbose version of code. Explanation:

```
≔⌕Ａ…θ⌕θＩＬθrη

```

Find the indices of all of the `r`s that appear to the left of the ending position.

```
Ｅθ⎇№βιＩ⁺²⌕⁺⁺⁻⌕Ａθrη⮌⌕Ａθlηκι

```

Find the indices of all the right `r`s, concatenate with the reversed indices of all the `l`s and with the indices of the left `r`s. Replace each lowercase letter with the index of its index in the list of indices, plus `2`.
> 4 votes

# Answer
# Jelly, 17 bytes

```
ẹⱮØ<ṚNƭ€F>ÞMA;MŻỤ

```

A monadic Link that accepts the signpost array as a list of characters with no leading `1` and with one `N` mixed with `<` for left and `>` for right and yields a possible input permutation.

**Try it online!**

### How?

```
ẹⱮØ<ṚNƭ€F>ÞMA;MŻỤ - Link: signpost list, S
  Ø<              - "<>"
 Ɱ                - map across (c in "<>") with:
ẹ                 -   indices of (c) in (S)
       €          - for each:
      ƭ           -   alternate between:
    Ṛ             -     a) reverse; and
     N            -     b) negate
        F         - flatten
           M      - maximum indices (of S) -> [index of 'N' in S]
          Þ       - sort (the flattened list) by:
         >        -   is greater than (maximum indices)? (vectorises)
            A     - absolute values
              M   - maximum indices (of S) -> [index of 'N' in S]
             ;    - (absolute values) concatenate (maximum indices)
               Ż  - prepend a zero
                Ụ - sort the indices (of that) by their values

```

### Example

Using `S` with the leading `1` will also work so long as `N>1`, it just increases the results of `ẹⱮØ½` by one with no effect on the final result.

```
S     "><><>>N><>><":
         >   <   >   <   >   >   N   >   <   >   >   <
M                               [7]
ẹⱮØ<     [[2, 4, 9, 12], [ 1, 3, 5, 6, 8, 10, 11]]
ṚNƭ€     [[12, 9, 4, 2], [-1,-3,-5,-6,-8,-10,-11]]
F        [12,  9,  4,  2, -1, -3, -5, -6, -8,-10,-11]
>ÞM      [ 4,  2, -1, -3, -5, -6, -8,-10,-11, 12,  9]
A        [ 4,  2,  1,  3,  5,  6,  8, 10, 11, 12,  9]
;MŻ   [0,  4,  2,  1,  3,  5,  6,  8, 10, 11, 12,  9, 7] (ie 1st, 5th, 3rd, 2nd, ...)
Ụ     [1,  4,  3,  5,  2,  6,  7, 13,  8, 12,  9, 10, 11]
       1   >   <   >   <   >   >   N   >   <   >   >   <

```
> 4 votes

# Answer
# Python, 154 bytes

```
lambda x:(z:=len(x))and next(i for i in permutations(range(z))if all(x[j]==i[j]or("RL"[j>i.index(i[j]+1)]==x[j])for j in range(z)))
from itertools import*

```

Attempt This Online!

0-indexed. I imagine in 5 minutes someone will post a answer in half this number of bytes
> 3 votes

# Answer
# Vyxal, 207 bits1, 25.875 bytes

```
żṖ'£Lɾḣṫ$⟑›"¥vḟƒ>‛rli;pJn‹İ?⁼

```

Try it Online!

Probably times out online for anything larger than a 5 item list.

Signpost is my favourite puzzle in the pack btw - the 5x5 grids are what I main. I sometimes do 6x6s for fun, or 4x4s when I want to see how fast I can solve one. It's especially fun when there's no extra hints, just the start, end, and a whole bunch of arrows. Non-fixed start/end positions are fun too :p

## Explained

This boils down to "find the first permutation where applying the algorithm gives the input"

```
żṖ'£Lɾḣṫ$⟑›"¥vḟƒ>‛rli;pJn‹İ?⁼
żṖ'                            # All permutations (P) of the range [1, input.length] where:
   £Lɾḣṫ$                      #   The range [2, P.length)
         ⟑›"¥vḟƒ>‛rli;         #   With the following applied to each item (eagerly evaluated):
          ›"                   #     [item, item + 1]
            ¥vḟ                #     0-indexed positions in P
               ƒ>              #     reduced by greater than
                 ‛rli          #     indexed into the string "rl"
                               #   (This determines which way a number points in P)
                     pJ        #  With 1 prepended and P.length appended
                       n‹İ     #  In the original of order of P
                          ?⁼   #  Equals the input

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 144 bytes

```
(m=Max@#;r[a_,i_,n_]:=(If[n >0,MapThread[If[#1<2&&#1(#2-i)<0,r[w=ReplacePart[a,#2->n-1],#2,n-1]]&,{a,Range@m}]];w);r[#,Position[#,m][[1,1]],m])&

```

Try it online!

Recursive approach. It seems that no one has used it yet.
I’m sure it can be made shorter and better, but so far so.
Take input with:

* First position `0`
* Max number `N` as it is
* Left direction `-1`
* Right direction `1`

Ungolfed explained:

```
mainRec[arr_, currentInd_, current_] :=
  (If[current > 0,
    MapThread[
     If[#1 < 2 && #1*(#2 - currentInd) < 0,
       (*Recursive call for items that could be predecessors of \
current*)
       mainRec[currentArr = ReplacePart[arr, #2 -> current - 1], #2,
        current - 1]
       ] &,
     {arr, Range@Length@arr}]
    ]; currentArr);
init = {0, 1, 1, 6, 1, -1};
(*First call with initial puzzle, N and index of N*)
mainRec[init, Position[init, Max@init][[1, 1]], Max@init]

```
> 0 votes

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


title: Computer Cipher

text:
# Question
Title: Computer Cipher
## Introduction:

*I have loads of different ciphers stored in a document I once compiled as a kid, I picked a few of the ones I thought were best suitable for challenges (not too trivial, and not too hard) and transformed them into challenges. Most of them are still in the sandbox, and I'm not sure yet whether I'll post all of them, or only a few. But here is the first of them to start things of.*

---

A Computer Cipher will encipher the given text into 'random' character groups of a given `length`. If such a group contains a digit, it will use that digit to index into its own group for the enciphered character. If no digit is present in the group, it means the first character is used.

For example, let's say we want to encipher the text `this is a computer cipher` with a given length of `5`. This is a potential output (note: numbers are 1-indexed in the example below):

```
t     h     i     s     i     s     a     c     o     m     p     u     t     e     r     c     i     p     h     e     r       (without spaces of course, but added as clarification)
qu5dt hprit k3iqb osyw2 jii2o m5uzs akiwb hwpc4 eoo3j muxer z4lpc 4lsuw 2tsmp eirkr r3rsi b5nvc vid2o dmh5p hrptj oeh2l 4ngrv   (without spaces of course, but added as clarification)

```

Let's take a few groups as examples to explain how to decipher the group:

* `qu5dt`: This group contains a digit `5`, so the (1-indexed) 5th character of this group is the character used for the deciphered text: `t`.
* `hprit`: This group contains no digits, so the first character of this group is used implicitly for the deciphered text: `h`.
* `osyw2`: This groups contains a digit `2`, so the (1-indexed) 2nd character of this group is the character used for the deciphered text: `s`.

## Challenge:

Given an integer `length` and string `word_to_encipher`, output a random enciphered string as described above.

You only have to encipher given the `length` and `word_to_encipher`, so no need to create a deciphering program/function as well. I might make a part 2 challenge for the deciphering in the future however.

## Challenge rules:

* You can assume the `length` will be in the range `[3,9]`.
* You can assume the `word_to_encipher` will only contain letters.
* You can use either full lowercase or full uppercase (please state which one you've used in your answer).
* Your outputs, every group, and the positions of the digits in a group (if present) should be uniformly random. So all random letters of the alphabet have the same chance of occurring; the position of the enciphered letter in each group has the same chance of occurring; and the position of the digit has the same chance of occurring (except when it's the first character and no digit is present; and it obviously cannot be on the same position as the enciphered character).
* You are also allowed to use 0-indexed digits instead of 1-indexed. Please state which of the two you've used in your answer.
* The digit `1` (or `0` when 0-indexed) will never be present in the output. So `b1ndh` is not a valid group to encipher the character 'b'. However, `b4tbw` is valid, where the `4` enciphers the `b` at the 4th (1-indexed) position, and the other characters `b`,`t`,`w` are random (which coincidentally also contains a `b`). Other possible valid groups of `length` 5 to encipher the character 'b' are: `abcd2`, `ab2de`, `babbk`, `hue5b`, etc.

## General rules:

* This is , 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 for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

```
Input:
 Length:           5
 Word to encipher: thisisacomputercipher
Possible output:
 qu5dthpritk3iqbosyw2jii2om5uzsakiwbhwpc4eoo3jmuxerz4lpc4lsuw2tsmpeirkrr3rsib5nvcvid2odmh5phrptjoeh2l4ngrv

Input:
 Length:           8
 Word to encipher: test
Possible output:
 ewetng4o6smptebyo6ontsrbtxten3qk

Input:
 Length:           3
 Word to encipher: three
Possible output:
 tomv3h2rvege3le

```

# Answer
# Pyth, 22 bytes

```
smsXWJOQXmOGQJdO-UQJJz

```

Try it online.

Uses lowercase and zero-indexing.

### Explanation

Very straightforward algorithm.

```
                           Implicit: read word in z
                           Implicit: read number in Q
 m                   z     For each char d in z:
      OQ                     Choose a number 0..Q-1
     J                       and call it J.
         m  Q                Make an array of Q
          OG                 random letters.
        X     d              Place d in this string
             J               at position J.
    W                        If J is not 0,
   X                J        place J in this string
               O             at a random position from
                 UQ          0..Q-1
                -  J         except for J.
  s                          Concatenate the letters.
s                          Concatenate the results.

```
> 4 votes

# Answer
# Perl 6, 125 bytes

```
->\n{*.&{S:g{.}=(65..90)>>.chr.roll(n).join.subst(/./,$/,:th($!=roll 1..n:)).subst(/./,$!,:th($!-1??(^n+1∖$!).roll!!n+1))}}

```

Try it online!

Takes input and output in uppercase. Takes input curried, like `f(n)(string)`. Uses 1 indexing.

### Explanation:

```
->\n{*.&{ ...  }}   # Anonymous code block that takes a number n and returns a function
     S:g{.}=        # That turns each character of the given string into
                          .roll(n)      # Randomly pick n times with replacement
            (65..90)>>.chr              # From the uppercase alphabet
                                  .join # And join
            .subst(                         ) # Then replace
                   /./,  ,:th($!=roll 1..n:)  # A random index (saving the number in $!)
                       $/               # With the original character
            .subst(                )    # Replace again
                   /./,$!,:th( ... )    # The xth character with $!, where x is:
                           $!-1??          # If $! is not 1
                                 (^n+1∖$!).roll       # A random index that isn't $!
                                               !!n+1  # Else an index out of range

```
> 5 votes

# Answer
# Python 2, ~~187~~ ~~177~~ ~~176~~ ~~156~~ ~~154~~ 148 bytes

```
lambda l,s:''.join([chr(choice(R(65,91))),c,`n`][(j==n)-(j==i)*(n>0)]for c in s for n,i in[sample(R(l),2)]for j in R(l))
from random import*
R=range

```

Try it online!

Uses uppercase letters, and 0-indexed numbers.

<sub>-3 bytes, thanks to Kevin Cruijssen</sub>
> 4 votes

# Answer
# JavaScript (Node.js), 135 bytes

```
n=>f=([c,...s])=>c?(g=n=>n?g(--n)+(n-p?n-q|!p?(r(26)+10).toString(36):p:c):'')(n,r=n=>Math.random()*n|0,p=r(n),q=r(n-1),q+=q>=p)+f(s):s

```

Try it online!

Thank Arnauld for 1B
> 3 votes

# Answer
# , ~~134~~ ~~132~~ 123 bytes

```
function(S,n,s=sample)for(k in utf8ToInt(S)){o=k+!1:n
P=s(n,1)
o[-P]=s(c(P[i<-P>1],s(17:42,n-1-i,T)))+48
cat(intToUtf8(o))}

```

Try it online!

Takes uppercase letters.

Explanation of old code (mostly the same approach):

```
function(S,n){s=sample				# alias
K=el(strsplit(S,""))				# split to characters
o=1:n						# output array
for(k in K){					# for each character in the string
P=s(n,1)					# pick a Position for that character
o[-P]=						# assign to everywhere besides P:
      s(					# a permutation of:
	c(P[i<-P>1],				# P if it's greater than 1
		s(letters,n-1-i,T)))		# and a random sample, with replacement, of lowercase letters
o[P]=k						# set k to position P
cat(o,sep="")}}					# and print

```
> 3 votes

# Answer
# Japt, 29 bytes

```
;£=VöJ;CöV hUÎX hUÅÎUÎ?UÎs:Cö

```

Try it online!

Zero-indexed.

Explanation:

```
;                                :Set C = [a...z]
 £                               :For each character of the input:
  =VöJ;                          : Get two different random indexes from [0,length)
       CöV                       : Get 5 random letters
           hUÎX                  : Replace one at random with the character from the input
                hUÅÎ             : Replace a different random character with:
                    UÎ?          :  If the input character was not placed at 0:
                       UÎs       :   The index of the input character
                          :      :  Otherwise:
                           Cö    :   A random letter
                                 :Implicitly join back to a string

```
> 2 votes

# Answer
# Java (JDK), 193 bytes

```
s->n->s.flatMap(c->{int a[]=new int[n],i=n,x=0;for(;i-->0;)a[i]+=Math.random()*26+97;a[i+=Math.random()*n+1]=c;x+=Math.random()*~-n;if(i>0)a[x<i?x:x+1]=48+i;return java.util.Arrays.stream(a);})

```

Try it online!

* The index are 0-based.
* This entry uses an `IntStream` (gotten through `String::chars`) as input, as well as a number and returns another `IntStream`.
* Casts from `double` to `int` are unnecessary because of the `+=` hack.
> 2 votes

# Answer
# C, 115 bytes

```
g(_,n)char*_;{int i=rand(),j=i%~-n,k=0;for(i%=n;k<n;k++)putchar(k-i?!i|i<k^k-j?rand()%26+97:48+i:*_);*++_&&g(_,n);}

```

Try it online!

0-indexed, lowercase.

Slightly ungolfed and expanded:

```
g(char*_,int n) {
    int i = rand(), j = i%(n-1), k = 0;
    for(i = i%n; k<n; k++)
        putchar(k!=i ? i!=0 || k==j + (k>i)
                          ? rand()%26 + 'A'
                          : i + '0')
                    : *_);
    if (*++_!=0) g(_,n);
}

```

The code should be pretty straightforward. The two randoms `i`,`j` generated in one `rand()` call are good as independent since gcd(`n`,`~-n`)=1 and `RAND_MAX` is large.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 169 bytes

```
StringJoin@Table[While@FreeQ[a=RandomChoice[Alphabet[],#2],c];If[(p=Position[a,c][[1,1]])!=1,a[[RandomChoice@Complement[Range@#2,{p}]]]=ToString@p];a,{c,Characters@#1}]&

```

Try it online!

Thank you for the interesting challenge!
It turned out a pretty big program,
but I can not do less and at the same time meet the requirements (

Ungolfed explained:

```
str = "thisisacomputercipher"; len = 5;
StringJoin[Table[
  While[(*Get first random choice contained character*)
   FreeQ[arr = RandomChoice[Alphabet[], len], c]
   ];
  If[(pos = Position[arr, c][[1, 1]]) != 1,
   (*If char is at first position - keep it,
   else set random item to digit as index of char*)
   arr[[RandomChoice@Complement[Range@len, {pos}]]] = ToString@pos
   ]; arr,
  {c, Characters@str}]]

```
> 2 votes

# Answer
# Charcoal, ~~35~~ 30 bytes

```
ＮθＦＳ«≔‽θη≔∧η‽Φθ⁻κηζＦθ≡κζＩηηι‽β

```

Try it online! Link is to verbose version of code. 0-indexed. Explanation:

```
Ｎθ

```

Input the length.

```
ＦＳ«

```

Input the word and loop over the characters.

```
≔‽θη

```

Choose a random position for the deciphered letter.

```
≔∧η‽Φθ⁻κηζ

```

Choose a different random position for the digit, unless the letter is at position 0, in which case put the digit at position 0 as well.

```
Ｆθ≡κ

```

Loop once for each output character and switch on the position.

```
ζＩη

```

If this is the position of the digit then output the position of the deciphered letter.

```
ηι

```

But if this is the position of the deciphered letter then output the letter. This takes precedence over the position of the digit because Charcoal takes the last entry if multiple switch cases have the same value.

```
‽β

```

Otherwise output a random letter.
> 1 votes

# Answer
# Clean, 256 bytes

```
import StdEnv
s::!Int->Int
s _=code {
ccall time "I:I"
ccall srand "I:I"
}
r::!Int->Int
r _=code {
ccall rand "I:I"
}
$n|s 0<1#k=map\e.r e rem n
=flatten o map\c.hd[map(\i|i==x=c=toChar if(i==y&&x>0)(x+48)(r i rem 26+97))[0..n-1]\\x<-k[0..]&y<-k[0..]|x<>y]

```

Try it online!

Chooses:

* a random `x` (position of the character in the segment)
* a random `y` that isn't equal to `x` (position of the digit in the segment)
* a random lowercase letter for each position not equal to `x` and not equal to `y` unless `x` is zero
> 1 votes

# Answer
# JavaScript, 134 bytes

```
l=>w=>w.replace(/./g,c=>eval("for(s=c;!s[l-1]||s[t?t-1||9:0]!=c;t=s.replace(/\\D/g,''))s=(p=Math.random()*36**l,p-p%1).toString(36)"))

```

Try it online!

This answer chose the encoded string from all possible encoded string uniformly. So it is more possible to make the encoded letter as the first one.
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 171 bytes

```
s=>n=>{var r=new Random();return s.SelectMany(c=>{int i=r.Next(n),j=r.Next(n-1);j+=j<i?0:1;return new int[n].Select((_,k)=>(char)(i==k?c:j==k&i>0?i+49:r.Next(26)+97));});}

```

Try it online!

Explanation...

```
// s is the input string
// n is the input length
s=>n=>{
  // we need to create an instance
  // of Random and use throughout
  var r=new Random();
  // iterate over s, each iteration
  // returns an array... flatten it
  return s.SelectMany(c=>{
    // i is the position of the letter
    // j is the position of the number
    int i=r.Next(n), j=r.Next(n-1);
    // ensure i and j are different
    j+=j<i?0:1;
    // create an iterable of size n
    return new int[n]
      // iterate over it with index k
      .Select((_,k)=>(char)(
        // return the letter
        i==k?c:
        // return the number
        j==k&i>0?i+49:
        // return a random letter
        r.Next(26)+97)
      );
  });
}

```
> 1 votes

# Answer
# 05AB1E, 26 bytes

```
ε²Ý¨Ω©A.r²£Šǝ®Āi®²Ý¨®KΩǝ]J

```

0-indexed.

Try it online or verify all test cases.

**Explanation:**

```
ε            # Map over the characters of the first (implicit) input-string:
 ²Ý¨         #  Create a list in the range [0, second input)
    Ω        #  Get a random item from this list
     ©       #  Store it in the register (without popping)
 A           #  Push the lowercase alphabet
  .r         #  Shuffle it
    ²£       #  Leave only the first second input amount of characters
      Š      #  Triple swap, so the stack order becomes:
             #  random index; random string; map-character
       ǝ     #  Insert the map-character at this random index into the random string
 ®Āi         #  If the random index was NOT 0:
    ®        #   Push the random index
    ²Ý¨      #   Push the list in the range [0, second input) again
       ®K    #   Remove the random index from this list
         Ω   #   Get a random item from this list
          ǝ  #   Insert the first random index at the second random index into the string
]            # Close both the if-else and map
 J           # Join all strings together (and output implicitly)

```
> 0 votes

---
Tags: code-golf, string, random, cipher, encoding
---


# Question
Title: The number of solutions to Hertzsprung's Problem
Hertzprung's Problem (OEIS A002464) is the number of solutions to a variant of the Eight Queens Puzzle, where instead of placing \\$n\\$ queens, you place \\$n\\$ rook-king fairy pieces (can attack like both a rook and a king); in other words, it's how many possible positions you can place \\$n\\$ rook-kings on an \\$n \times n\\$ board such that each piece does not occupy a neighboring square (both vertically, horizontally, and diagonally).

## Challenge

Write the **shortest** function or full program that will output the number of solutions to Hertzprung's Problem.

You may either:

* output just \\$\operatorname{A002464}(n)\\$, given a positive integer \\$n \> 0\\$, or
* output all terms of \\$\operatorname{A002464}(k) \text{ where } 0 \< k \< \infty\\$ as a .

## Notes

* A formula is derived in this video: $$ \operatorname{A002464}(n) = n! + \sum\_{k=1}^{n-1} (-1)^k(n-k)!\sum\_{r=1}^k 2^r \binom{n-k}{r} \binom{k-1}{r-1} $$

## Test Cases

```
1:  1
2:  0
3:  0
4:  2
5:  14
6:  90
23: 3484423186862152966838

```

# Answer
> 9 votes
# Nekomata \+ `-n`, 6 bytes

```
r↕∆A1>

```

Attempt This Online!

Brute force. Slow for large input.

```
r↕∆A1>
r↕      Find a permutation of [0..n-1] such that
  ∆A    the absolute differences of adjacent elements
    1>  are all greater than 1

```

The flag `-n` count possible solutions.

# Answer
> 4 votes
# Jelly, 7 bytes

I almost asked this question after watching Another Roof's video.

```
Œ!IỊ§¬S

```

A monadic Link that accepts \\$n\\$ and yields the number of solutions.

**Try it online!**

### How?

```
Œ!IỊ§¬S - Link: non-negative integer, n  e.g. 4
Œ!      - all permutations (of [1..n])        [[1,2,3,4],[1,2,4,3],...,[2,4,1,3],...,[3,1,4,2],...,[4,3,2,1]]
  I     - forward differences                 [[1,1,1],[1,2,-1],...,[2,-3,2],...,[-2,3,-2],...[-1,-1,-1]]
   Ị    - insignificant?                      [[1,1,1],[1,0,1],...,[0,0,0],...,[0,0,0],...[1,1,1]]
    §   - sums                                [3,2,...,0,...,0,...3]
     ¬  - logical NOT                         [0,0,...,1,...,1,...,0]
      S - sum                                 2

```

...yes, it also works if \\$n=0\\$ (the alternative of `Œ!IỊ§ċ0` would give \\$0\\$ rather than \\$1\\$).

# Answer
> 4 votes
# 05AB1E (legacy), 7 bytes

```
Lœ¥Ä≠PO

```

Port of *@alephalpha*'s Nekomata answer, so also a slow brute-force for larger inputs.

Try it online or verify most test cases.

**Explanation:**

```
L       # Push a list in the range [1, (implicit) input-integer]
 œ      # Get all permutations of this list
  ¥     # † For each inner permutation-list: get its deltas / forward-differences
   Ä    # Get the absolute value of each inner-most difference
    ≠   # Check for each that it's NOT 1 (so basically >= 2)
     P  # Product on each inner list, to check for which all overlapping pairs are >=2
      O # Take the sum, to check how many are truthy
        # (after which it is output implicitly as result)

```

† Uses the legacy version of 05AB1E to save 1 byte, because `¥` vectorizes on a list of lists, whereas the new 05AB1E version would give an error, and would require an additional  before the `¥` to accomplish the same thing.

# Answer
> 2 votes
# \>\<\> (Fish), 60 bytes

```
11005:&$:@*3[{:}]&3-:&*-4[{:}]&3-:&*-5[{:}]&2+:&*+:nao&5+40.

```

Try it

Infinitely prints values starting at n=4.

Based on the recursive formula pioneered by Arnauld but instead of recursing just keeps previous values pushed to the stack.

# Answer
> 2 votes
# Desmos, 69 bytes

```
K=n-k+1
f(n)=n!-∑_{k=2}^n(-1)^kK!∑_{a=1}^k2^anCr(K,a)nCr(k-2,a-1)

```

Nice.

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 2 votes
# PowerShell, 125 bytes

Try it online

Golfed Version:

```
function G($i){if($i -lt 4){if($i -lt 2){1}else{0}}else{($i+1)*(G($i-1))-($i-2)*(G($i-2))-($i-5)*(G($i-3))+($i-3)*(G($i-4))}}

```

Un-Golfed Version:

```
function G($i){
if($i -lt 4)
    {if($i -lt 2){1}
    else{0}
}else{
    ($i+1)*(G($i-1))-($i-2)*(G($i-2))-($i-5)*(G($i-3))+($i-3)*(G($i-4))
}
}

```

Let me know of any improvements!

# Answer
> 2 votes
# Aussie++, 136 bytes

Tested in commit 9522366. Loses precision for inputs \>18, because all numbers are doubles.

```
THE HARD YAKKA FOR a IS(n)<YA RECKON n <2?BAIL 1;YA RECKON n <4?BAIL 0;BAIL(n +1)*a(n -1)-(n -2)*a(n -2)-(n -5)*a(n -3)+(n -3)*a(n -4);>

```

Aussie++ requires every identifier to be followed by whitespace, a semicolon, a comma, or a paren, so I can't remove the spaces before all the operators. It also doesn't have bitwise operators, and the equivalent to `--` is `PULL YA HEAD IN`, so I can't take the same shortcuts as the JS and C answers.

Example test code:

```
G'DAY MATE!

THE HARD YAKKA FOR a IS(n)<YA RECKON n <2?BAIL 1;YA RECKON n <4?BAIL 0;BAIL(n +1)*a(n -1)-(n -2)*a(n -2)-(n -5)*a(n -3)+(n -3)*a(n -4);>

I RECKON i IS A WALKABOUT FROM [0 TO 18] <
  GIMME "" + i + ": " + a(i);
>

CHEERS C***!

```

# Answer
> 2 votes
# Vyxal `Rl`, 36 bits1, 4.5 bytes

```
Ṗ'¯ȧċA

```

Try it Online! (link is to bitstring)

Port of Kevin Cruijssen's 05AB1E answer, which is in turn a port of alephalpha's Nekomata answer. Like those, it is a brute force solution, suffering with the same slowdown on larger inputs.

```
Ṗ      # permutations of the range 1..n (due to the R flag)
 '     # filtered by
  ¯ȧ   # absolute value of the deltas
     A # are all
    ċ  # not 1
       # the length of this filtered list is taken by the l flag
       # and implicitly output

```

# Answer
> 1 votes
# PARI/GP, 51 bytes

```
n->Vec(sum(i=0,n,i!*(x*(1-x)/(1+x))^i)+O(x^n++))[n]

```

Attempt This Online!

Based on the generating funtion on the OEIS page.

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

Based on the recurrence formula provided on OEIS.

```
f=n=>n<4?n/2^1:-~n--*f(n--)-n*f(n)-(n-3)*f(--n)+n*f(n-1)

```

Try it online!

### With Bigints, 58 bytes

```
f=n=>n<4?n/2n^1n:-~n--*f(n--)-n*f(n--)-~-~-n*f(n)+n--*f(n)

```

Try it online!

# Answer
> 1 votes
# C (gcc), ~~60~~ 58 bytes

```
f(n){n=n<4?n<2:-~n--*f(n--)-n*f(n)-(n-3)*f(--n)+n*f(n-1);}

```

Try it online!

*Port of Arnauld's JavaScipt answer.*

*Saved 2 bytes thanks to Arnauld*

# Answer
> 1 votes
# Raku, 132 bytes

Translated the (corrected) formula directly; not particularly golfed, just crunched out all the unnecessary whitespace:

```
->\n{[*](1..n)+[+]((1..n-1).map: ->\k{(-1)**k*[*](1..n -k)*[+]((1..k).map: ->\r{2**r*combinations(n -k,r)*combinations(k-1,r-1)})})}

```

Try it online!

# Answer
> 1 votes
# Charcoal, 34 bytes

```
Ｆ⁴⊞υ‹ι²ＦＮ⊞υΣ×⮌υ⟦⁺⁵ι±⁺²ι⁻¹ι⊕ι⟧Ｉ§υ±⁴

```

Attempt This Online! Link is to verbose version of code. Outputs the `n`th element. Explanation:

```
Ｆ⁴⊞υ‹ι²

```

Start with the first four values (0-indexed, so `1, 1, 0, 0`).

```
ＦＮ⊞υΣ×⮌υ⟦⁺⁵ι±⁺²ι⁻¹ι⊕ι⟧

```

Use the recurrence relation to calculate `n` more values.

```
Ｉ§υ±⁴

```

Output the `4`th last value.

# Answer
> 1 votes
# Japt `-x`, 10 bytes

```
õ á Ëäa eÉ

```

Try it

# Answer
> 0 votes
# Scala, 97 bytes

Based on the recurrence formula provided by A002464.

Golfed version. Try it online!

```
def f(n:Int):Int=if(n<4){if(n<2)1 else 0}else (n+1)*f(n-1)-(n-2)*f(n-2)-(n-5)*f(n-3)+(n-3)*f(n-4)

```

Ungolfed version.

```
object Main {
  def f(n: Int): Int = {
    if (n < 4) {
      if (n < 2) 1 else 0
    } else {
      (n + 1)*f(n-1) - (n - 2) *f(n-2) - (n - 5) *f(n - 3) + (n - 3)* f(n - 4)
    }
  }

  def main(args: Array[String]): Unit = {
    val tests = Array(1, 2, 3, 4, 5, 6)
    val expected = Array(1, 0, 0, 2, 14, 90)
    val checker = Array("✕", "✓")

    for (index <- tests.indices) {
      val t = tests(index)
      val s = f(t)
      val e = expected(index)
      println(s"$t -> $s ${checker(if (s == e) 1 else 0)}")
    }
  }
}

```

---
Tags: code-golf, number, sequence, integer, combinatorics
---


title: Sanitize the Spaces

text:
# Question
Title: Sanitize the Spaces
Given some raw HTML, sanitize it by formatting the spaces, as defined below.

## Output rules:

Like many challenges, this one is inspired by XKCD.

1. First, "untag" all tags with nothing but spaces in them. (`<i>te<b> </b>xt</i>` becomes `<i>te xt</i>`). If a tag has nothing in it (like `<b></b>`, simply delete it and move on.
2. Next, "push" the spaces to the edge. This means that to push spaces at the edge of the tag outside (so `<b><i> test </i></b>` becomes `<b><i> test</i> </b>` after one step).
3. Keep repeating steps 1 and 2 until no new changes happen.
4. Collapse sets of spaces. For example, `<b><i>test</i></b>`  should become `<b><i>test</i></b>` .
5. Finally, trim the string (this means remove the spaces at the edges, so " ***a*** " becomes "***a***"). An empty string can be the result.

## Input

The input may be taken as an array of bytes or a string. The only tags will be `<b>`, `<strong>`, `<i>`, `<u>`, and `<em>`, and they may have additional attributes may be in the starting tags (so one starting tag could be `<b data-this-is-an-attribute="true">`. The ending tags, in order, are `</b>`, `</strong>`, `</i>`, `</u>`, and `</em>` and will not have attributes. Closing tags will be in order (so `<b><i></i></b>` works, but `<b><i></b></i>` will never be a test case). There are no newlines in the input.

**Edit: attributes may be in single or double quotes.**

Be sure not to follow any of the rules for the tags, especially the spaces!

```
"<b>  <i> </i></b>" -> "<b>   </b>" -> "   " -> "" (the quotes in this test case are to prevent confusion)
<u> x <em onclick="alert('Hi!')" style="font-size: 50px">kcd </em> comics </u> -> <u>x <em onclick="alert('Hi!')" style="font-size: 50px">kcd</em> comics</u>
<strong>Formatting<i> </i>is <u data-info='test     case'>HA     RD</u></strong>    -> <strong>Formatting is <u data-info='test     case'>HA RD</u></strong>
s p a c     e s -> s p a c e s
one<i> </i>space -> one space
    ->     (no changes, as we don't consider  )

```

As this is , the shortest answer in bytes wins!

Note: you can use any language to do this challenge; it's just inspired by HTML.

# Answer
> 4 votes
# Retina, ~~106~~ 97 bytes

```
{`<([a-z]+)[^>]*>( )*</\1>
$2
((^|>)[^<]* ) +([^>]*($|<))
$1$3
^((<[^>]+>)*) | ((<[^>]+>)*)$
$1$3

```

Can definitely be golfed some more.

Try it online.

**Explanation:**

Keep executing the replacements until the result no longer changes:

```
{`

```

Step 1: untag all tags that only contain spaces and remove empty tags:

```
<([a-z]+)[^>]*>( )*</\1>
$2

```

Step 4: collapse sets of spaces to a single space, unless they're inside an attribute:

```
((^|>)[^<]* ) +([^>]*($|<))
$1$3

```

Step 5: 'trim' leading/trailing spaces, ignoring the tags:

```
^((<[^>]+>)*) | ((<[^>]+>)*)$
$1$3

```

# Answer
> 2 votes
# Retina 0.8.2, 86 bytes

```
{`(<[^/>]+>)
 $1
 (</.*?>)
$1
^ |<[^/>]+></.*?>| $|( )+|(?<=<[^>]*)((["']).*?\3)
$1$2

```

Try it online! Link includes test cases. Explanation:

```
{`

```

Repeat the following replacements as many times as necessary.

```
(<[^/>]+>)
 $1

```

Move a space after an open tag to before it.

```
 (</.*?>)
$1

```

Move a space before a close tag to after it.

```
^ |<[^/>]+></.*?>| $|( )+|(?<=<[^>]*)((["']).*?\3)
$1$2

```

Handle all of the remaining cases:

* `^`  Delete leading spaces
* `<[^/>]+></.*?>` Delete empty tags
* `$` Delete trailing spaces
* `( )+|(?<=<[^>]*)((["']).*?\3)` Collapse spaces not inside attributes

---
Tags: code-golf
---


title: Make me a scrolling marquee

text:
# Question
Title: Make me a scrolling marquee
## Introduction

Remember the roaring 80's? I mean, you know, like 30 years ago? No cell phones, no internet, no ATM's, fluorescent clothing (what was that?!) and **scrolling marqee's**! No, no, no! Not the online ones, but real ones, With LED lights.

Since I'm in a nostalgic mood, I'd like you to create a scrolling marquee.

## Challenge

Create a program where you can enter a one line string. You program needs to create a 80 character wide scrolling marquee, repeating the text if necessary.

## Rules

* The user must be able to enter a string to your program as input. The string can be a command line parameter or a string entered while running the program.
* Your program must continuously print a string of exactly 80 (visible) characters.
* The string must be updated every 0.1 second (more or less; I won't be timing it), shifting the characters every iteration one position to the left.
* The string "rotates". At the end of the user supplied string, another instance of the string must appear.
* You program must print it's output on one line, without linefeeds (use a '\r' instead of a '\n')
* Your program must run *ad infinitum*, until an user interrupt.
* This is a codegolf, so shortest code in bytes wins.
* There is a 10% bonus (rounded **up** to the next integer) for printing in red on a black background.
* Standard loopholes apply.

## Reference implementation in Python 2.7

This program isn't golfed, but it provides a reference implementation (and thus an upper limit to the size).

```
import time,sys
s=raw_input()*99
while 1:
    for i in range(80):
        print s[i:i+80]+'\r',
        sys.stdout.flush()
        time.sleep(0.1)

```

# Answer
> 4 votes
# CJam, 31 bytes

```
l80*{Dco_80<o(+es99+{es1$<}g;}h

```

Waits for exactly 100 ms.

This will only work with the official Java interpreter, since the online interpreter only shows output after exiting the program.

Red text on black background is possible in 40 (or 39) bytes, for a score of 36:

```
0000000: 6c 38 30 2a 7b 22 0d 1b 5b 33 31 3b 34 30 6d 22 6f 5f  l80*{"..[31;40m"o_
0000012: 38 30 3c 6f 28 2b 65 73 39 39 2b 7b 65 73 31 24 3c 7d  80<o(+es99+{es1$<}
0000024: 67 3b 7d 68                                            g;}h

```

### How it works

```
l80*                             Read a line and repeat it 80 times.
    {                        }h  Do:
     Dco                           Print the character with code point 13.
        _80<o                      Print the first 80 characters of the string.
             (+                    Rotate the string one charcter to the left.
               es99+               Push the current time (ms) plus 99.
                    {     }g       Do:
                     es1$<           Compare the current time with the sum.
                                     Repeat the loop if 99 or less ms have passed.
                            ;      Discard the time stamp.
                                 Repeat the loop.

```

# Answer
> 10 votes
## PowerShell, 118 113 112 108 102 101 99  96 - 10% = 86

### Code

```
$s=(Read-Host)*180;for(){Write-Host($s.substring(($i=++$i%80),80)+"`r")-N -F R -B 0;sleep -m 99}

```

With the caveat that it now begins the first loop with the second character; The rules don't say it has to start from the front of the string, and the first one is included overall, so that's fine by me. I will get it to 100 chars somehow - edit: thanks @ConnorLSW for the edits to get it below 100.

### Instructions

1. Run PowerShell (normal console, it doesn't work in PowerShell ISE)
2. Paste the single line version into PoSH, press enter
3. Type a message, press enter
4. Ctrl-C to break

### Output

>

### Notes

A more readable version with the variable names and parameters filled out a bit:

```
$test = (Read-Host) * 180
for () {
    Write-Host ($text.substring(($i=++$i%80), 80)+"`r") -NoNewLine -ForegroundColor Red -BackgroundColor Black
    sleep -Miliseconds 99
}

```
* The parameters only need to be long enough to be unique, so `-F R` is unique enough to set a Red ForegroundColor, for example.
* 'Black' has to be 'Bla' to be unique compared to 'Blue', but `-B 0` sets it to color Enum value 0 which is interpreted as Black.

### Alternative, more 'correct' marquee:

The reference code doesn't handle strings longer than 80 characters nicely, skipping anything in the message past ~160 characters, and it glitch-resets every 99\*len(string) characters. e.g. if the sign width was 5 characters long, it does this:

```
   here is my long test input
 0 |here |
 1  |ere i|          ^^^^ never shown
 2   |re is|
 3    |e is |
 4     | is m|
 0 |here |
 1  |ere i|
    ...

```

This version indexes modulo the text length instead of the sign width, so it runs through the whole string. 106 - 10% = 95 chars.

```
$l=($s=Read-Host).Length;for(){Write-Host(($s*160).substring(($i=++$i%$l),80)+"`r")-N -F R -B 0;sleep -m 99}

```

### Alternative: sign which cycles like the .gif in the question, 118-10%=106

Because it looks better.

```
$s=' '*80+(read-host)+' '*80;for(){write-host($s.Substring(($i=++$i%($s.length-80)),80)+"`r")-N -F R -B 0;sleep -m 99}

```

# Answer
> 6 votes
# Matlab, 76 bytes

What I think is nice here is that you can have vectors as array indices. This returns a vector of the corresponding array entries, which makes it very easy to append the given string independently of the length.

```
a=input('');k=1:80;while 1;pause(.1);clc;k=mod(k+1,nnz(a));disp(a(k+1));end

```

Result:

>

# Answer
> 4 votes
# QBasic, ~~116~~ 113 bytes - 10% = ~~105~~ 102

```
INPUT s$
COLOR 4
1CLS
FOR i=a TO a+79
?MID$(s$,i MOD LEN(s$)+1,1);
NEXT
?
a=a+1
t=TIMER+.1
2ON(TIMER<t)+2GOTO 2,1

```

Here's a formatted version with some comments:

```
INPUT s$
COLOR 4   ' 4 is the color code for red (the background's already black)

1 CLS   ' CLear Screen (and mark this as line number 1)

' The variable a represents an offset from the beginning of the string
' As a numeric variable, it is 0 at the beginning of the program
FOR i = a TO a + 79
    ' Print i'th character mod string length (+ 1 because QBasic strings
    ' are 1-indexed)
    PRINT MID$(s$, i MOD LEN(s$) + 1, 1);
NEXT i
PRINT
a = a + 1

' Do a busy-wait for .1 seconds
' (Unfortunately, QBasic's SLEEP command only takes integer values)
' Set t to the time we want to stop waiting, .1 seconds in the future
t = TIMER + .1
' We want to stay on line number 2 while TIMER < t; once that condition is
' no longer true, we want to goto the top of the outer loop (line number 1)
' Since true is -1 and false is 0 in QBasic, adding 2 to the conditional
' gives 1 for true and 2 for false; we can pass these values to the
' ON ... GOTO statement to branch conditionally
2 ON (TIMER < t) + 2 GOTO 2, 1

```

A couple of notes:

* I don't know why the `PRINT` after the `FOR` loop is necessary. `CLS` should reset the cursor to the top left corner each time. But on QB64, at least, if I don't put the extra `PRINT` in, the marquee ends up on the second line instead of the first. If anybody has QBasic set up on DosBox or somesuch, I'd be interested to know if the same thing happens there or if it's a QB64 bug.
* The code has a small glitch because it relies on `TIMER` (number of seconds since midnight) for the delay. If the code is running at midnight, the marquee will get stuck because `TIMER` will reset to `0` and always be less than `t` thereafter.

# Answer
> 4 votes
## Perl, 99 98 bytes (-10% = 89)

```
$|=@_=split('',pop);printf("\e[31m\r%.80s",join('',@_)x80)while select($a,$a,$a,.1)|push@_,shift@_

```

Takes its input from command line parameter.

```
perl marquee.pl "Welcome to Programming Puzzles & Code Golf "

```

# Answer
> 3 votes
# pb, ⌈(216 + 3)\*0.9⌉ = 198

+3 bytes for interpreter flag `d=1`

```
c^w[Y=-1]{w[B!0]{>}t[X]<[X-79]w[X!0]{t[T-1]w[T=-1]{t[0]}<}vw[T=0]{^w[B!0]{t[B]^b[T]>v}<[X]^w[B!0]{t[B]vw[B!0]{>}b[T]<[X]^w[B=0]{>}b[0]>}v}}^w[1=1]{<[X-80]w[X!0]{<t[B]vb[T]^}w[B!0]{t[B]<b[T]>>}<[X]<t[B]w[B!0]{>}<b[T]}

```

A pretty horrible score, but considering how hard it is to do anything in this language it could be worse. This answer's ratio of (bytes used to get red text) to (bonus from having red text) is really good, the whole output is turned red with only the `c` at the beginning!

The time between each tick varies depending on the length of the input string but it's around 0.1 seconds.

By the way, this program's output looks like total garbage because the interpreter is so bad. Every millisecond it clears the terminal and redraws everything, so it gets really flickery.

With comments:

```
c           # Change paint colour to red

^w[Y=-1]{   # While Y=-1 (arbitrary condition we can break later)

    w[B!0]{>}   # Go to end of input

    t[X]        # Save length of input in T

    # SET T TO MAX(T-79, 0)

    <[X-79]     # Go to (79, -1)

    w[X!0]{     # While X is not 0
        t[T-1]      # Subtract 1 from T
        w[T=-1]{    # If T is now negative
            t[0]        # Set it back to 0
        }
        <         # Move left (position doesn't matter except to end the loop eventually)
    }

    # DONE SETTING T TO MAX(T-79, 0)
    # If T == 0, the string needs to be doubled. Otherwise this part of the program is done

    v           # Move down to break the loop unless this is specifically undone
    w[T=0]{     # While T == 0
        ^w[B!0]{    # For each byte of input
            t[B]^b[T] # Copy it up 1 place
            >v        # Go to the next byte
        }
        <[X]^     # First byte of the copy
        w[B!0]{   # For each byte of the copy
            t[B]      # Save the byte's value
            vw[B!0]{>}# Go to the first empty spot after the original
            b[T]      # Write the saved value
            <[X]^w[B=0]{>} # Go back to the first byte of the copy
            b[0]>     # Erase it and go to the next one
        }
        v       # Back to Y=-1 to reset the loop from the very beginning
    }

}

# After ALL OF THAT nonsense, we're now at (0, 0) and the input string is guaranteed to be
# at least 80 characters long

^
w[1=1]{       # While 1=1 (should hold true until mathematics itself breaks down)
    <[X-80]        # Go to the 81st character
    w[X!0]{        # While X!=0
        <t[B]vb[T]^    # Go left and copy that character down
    }

    w[B!0]{      # For each byte in the string
        t[B]<b[T]>>  # Copy that byte left
    }

    <[X]<t[B]    # Go get the first value (copied to (-1, -1))
    w[B!0]{>}<b[T]# Bring it to the end of the string
}

```

# Answer
> 3 votes
## Perl - 120 bytes (-10% = 108)

```
$|=1;$_=<>;chomp;for(;;){print "\e[31m",substr(" "x80 .$_,$p++,80)," \r";select($z,$z,$z,0.1);if($p>length()+80){$p=0}}

```

# Answer
> 2 votes
# Matlab, ⌈188\*.9⌉ = 170

This works in Matlab version R2014b or higher. The result is shown on a figure window.

```
h=text(.1,.1,repmat(' ',1,80),'fontn','courier','ba','k','co','r');set(1,'pos',[90 90 990 90]);axis off
s=input('','s');n=0;while 1
n=n+1;pause(.1)
h.String=s(mod((0:79)+n,numel(s))+1);end

```

In the following **example**, text is typed in boldface for better visualization (not done in the above code because it costs a few bytes). Note also that the speed of the GIF animation does not correspond to the required 0.1 s pause, but the timing is correct in the actual figure shown by running the program.

# Answer
> 2 votes
# SpecBAS, 130 bytes (-10% = 117)

Multiplies the original string to make it 80 or more characters, then chops it to exactly 80.

`TEXT` is a command in SpecBAS that works the same way as `PRINT` (in this example) but saves one character.

The `SCALE` command adds a few extra characters to the code, but makes it look more marquee-ish.

The program keeps going until you press Esc.

```
1 INPUT s$: LET s$=s$*CEIL(80/LEN s$)
2 TEXT PAPER 0;INK 2;SCALE 1,2;AT 1,1;s$( TO 80)
3 LET s$=s$(2 TO)+s$(1): PAUSE 5: GO TO 2

```

# Answer
> 2 votes
# bash, 121 bytes

```
A=$(printf ' %.s' {1..80})$1
while :; do
printf "%s \r" "${A:((P++)):80}"
if [ $P == ${#A} ];then
 P=0
fi
sleep 0.1
done

```

# Answer
> 2 votes
## Perl, 63 (70 chars - 10% for bonus)

Not a hugely different solution to the others, but I wasted my time making it, so I thought I'd post it as well!

```
$_=<>;s/
/ /;print"\x0d\x1b[91m",substr"$_"x80,$z++%y///c,80 until`sleep .1`

```

Relies on a Unix-compatible terminal for ANSI codes and the call to coreutils' `sleep`. The two `\x..` chars in the above are actually a literal line-feed and escape char as per this hex dump:

```
0000000: 245f 3d3c 3e3b 732f 0a2f 202f 3b70 7269  $_=<>;s/./ /;pri
0000010: 6e74 220d 1b5b 3931 6d22 2c73 7562 7374  nt"..[91m",subst
0000020: 7222 245f 2278 3830 2c24 7a2b 2b25 792f  r"$_"x80,$z++%y/
0000030: 2f2f 632c 3830 2075 6e74 696c 6073 6c65  //c,80 until`sle
0000040: 6570 202e 3160                           ep .1`

```

# Answer
> 2 votes
# Ruby, ~~79~~ ~~76~~ 75 bytes

```
t,i=gets.chop*81,0
loop{system'cls'
$><<t[(i=(i+1)%80)..i+79]
sleep 0.1}

```

I'm still not a ruby expert, possibly can be golfed down.

With red & black same score:

```
t,i=gets.chop*81,0
loop{system'cls&color 4'
$><<t[(i=(i+1)%80)..i+79]
sleep 0.1}

```

# Answer
> 2 votes
## Perl, 84 bytes (- 10% = 76)

```
$_=' 'x80 .pop;$|=print"\b \r\e[31m".substr$_,++$p% length,80until select$z,$z,$z,.1

```

This takes a command line argument which is the text in the marquee.

Explanation:

1. Prepend 80 spaces to the text and store in `$_`
2. Print backspace (`\b`) and a space (). This removes the last character from the previous print. Then print the carriage return and colour.
3. Print the 80 characters of the text from position `$p`
4. `$p = ($p+1) % length of text`
5. Sleep for 0.1 secs

# Answer
> 2 votes
# Japt, 12 bytes

Outputs an integer before starting into the marquee.

```
Li@Oq80îUéV´

```

Try it

But, if that's not valid then ...

## Japt, 14 bytes

```
Oq80îUéV´ Lt@ß

```

Try it

```
Oq80îUéV´ Lt@ß     :Implicit input of string U
Oq                 :Overwrite output with
  80î              :  Mould the following to length 80
     Ué            :    Rotate U right this many times
       V           :      Second input variable, defaulting to 0
        ´          :      Postfix decerement
          L        :100
           t       :Set timeout for L milliseconds to
            @      :  Run this function
             ß     :    Recursive call with implicit arguments U & (now decremented) V

```

# Answer
> 1 votes
# Python 3, 96 bytes

```
import time;s=input()*80
while 1:print("\033[2J",end=s[:80],flush=1);s=s[1:]+s[0];time.sleep(.1)

```

This will only work on terminals that support ANSI escape sequences. If you are on Windows, try ansicon.

Hurrah for the `flush` keyword in Python 3, so we don't have to make an expensive `sys.stdout.flush()` call.

# Answer
> 1 votes
## C, ~~293~~ 269 bytes

(Newlines added for readability)

This takes input from standard input terminated by EOF; so it's best to enter a string, a newline, and then the EOF (e.g., Ctrl^D).

```
#include<stdio.h>
#include<string.h>
#define Z '\0'
main(){int i=0,j;char m[80],o[80],n[2];
while(~(j=getchar())&&i<80)j-'\n'?m[i++]=j:0;m[i]=Z;
while(1){for(i=0;m[i]-Z;++i){strcpy(o,&m[i]);
for(j=0;j<i;)*n=m[j++],n[1]=Z,strcat(o,n);
printf("\x1b[40;31m%s\x1b[0m\r",o);}}}

```

Ungolfed:

```
#include <stdio.h>
#include <string.h>
#define ANSI_COLOR_SET "\x1b[40;31m"
#define ANSI_COLOR_RESET "\x1b[0m"

int main(void)
{
  int i, j, c;
  char msg[80], out[80], next[2];

  for (i = 0; (c = getchar()) != EOF && i < 80; ++i) {
    if (c != '\n') {
      msg[i] = c;
    }
  }
  msg[i - 1] = '\0';

  while (1) {
    for (i = 0; msg[i] != '\0'; ++i) {
      strcpy(out, &msg[i]);
      for (j = 0; j < i; ++j) {
        next[0] = msg[j];
        next[1] = '\0';
        strcat(out, next);
      }
      printf(ANSI_COLOR_SET "%s\r" ANSI_COLOR_RESET, out);
    }
  }
  return(0);
}

```

# Answer
> 1 votes
# SmileBASIC BIG, 79 bytes

```
COLOR 3INPUT S$@L
CLS
FOR I=0TO 79?S$[(I+O)MOD LEN(S$)];
NEXT
WAIT 6O=O+1GOTO@L

```

I had a nice graphical solution almost done when I realized it has to scroll 1 whole character at a time.

# Answer
> 1 votes
# Jelly, ~~20~~ ~~19~~ 18 bytes

* -1 byte by replacing the first `80` by  (= 256) because it has to be multiplied by *at least* 80
* -1 byte by changing infinite loop to `Çß` (from `Ç1¿`).

---

```
ẋ⁹ḣ80ṙ1;”ÆṄœS.1
Çß

```

With some tricks from @Dennis' answer here. Jelly is newer than the challenge, but not really specifically tailored for it. Suggestions on how to improve are welcome! If your console is in utf-8, run `export LC_ALL=en_US` or similar before trying.

## Example

## Explanation

```
ẋ⁹ḣ80ṙ1;”ÆṄœS.1         Monadic helper link - Argument: s
ẋ⁹                      Repeat s 256 times.
  ḣ80                   Head. Set {output} to first 80 characters from repeated s.
     ṙ1                 Rotate. Rotates {output} one character to the left.
       ;”Æ              Concatenate character 0D, the carriage return, to {output}.
          Ṅ             Print and return {output}.
           œS.1         Wait 0.1 seconds before returning {output} from the
                        helper link.

Çß                      Monadic main link - Argument: s
Ç                       Execute helper link with argument s. Replace s by
                        result of helper link.
 ß                      Execute this link with argument s (while true).

```

# Answer
> 0 votes
# LOVE2D Lua, 197-10% = 178 Bytes

```
f=io.open("t.t"):read().."  "love.graphics.setColor(255,0,0)love.window.setMode(640,14)function love.draw()s=""for i=1,80 do n=i+os.clock()s=s..f:sub(n%#f,n%#f) end love.graphics.print(s,0,0)end

```

Requires the input to be in a file called 't.t' in the root, thus 3 extra bytes were added to the score.

Really basic in functionality, just in a for loop of 80 iterations, append the character at index of i plus the current time in seconds modulated by the length of the current string, giving a repeated 80 character long string of the input, which shifts left as time goes on.

I used LOVE2D For the laughs.

# Answer
> 0 votes
# Sinclair ZX81/Timex TS1000/1500 BASIC, 110 bytes 182 bytes (for the listing)

```
1 LET A$="I LIKE TO SCROLL IT... HELLO MUM, BY DONKEYSOFT... THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG... STILL SCROLLING... "
2 PRINT AT 0,0;A$(1 TO 80)
3 LET A$=A$(2 TO )+A$(1)
4 GOTO 3

```

It works by printing the first 32 80 characters of the string `A$` at screen position 0,0 in line two, and then manipulating the string from position 2 to the end of the sting in line 3 (Sinclair ZX81 BASIC indexes strings from 1 and not zero), therefore adding the first character to the end and passing it back to the `A$` variable; then there's a unconditional loop back to line 2.

# Answer
> 0 votes
# Commodore 64, 434 bytes

```
0 A$="I LIKE TO SCROLL IT... SAMPLE SCROLLY ROUTINE FOR CODE-GOLF MADE BY DONKEYS
1 A$=A$+"OFT MMXVII... HELLO MUM... SCROLLING IS FUN, INNIT? GREETZ TO ALL...
2 POKE53280,6:PRINT"{CLEAR}";
3 PRINTLEFT$(A$,40)"{HOME}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}"MID$(A$,41,40)"{HOME}";
4 FORI=0TO99:NEXT:A$=RIGHT$(A$,142)+LEFT$(A$,1):GOTO3

```

As this requires 80 characters to show, and the C64 by default is only 40 characters, then 40 characters of the scrolly is printed on the top line of the screen area whilst the other 40 are printed near to the bottom.

To clear up what the `{HOME}` and other symbols translate into as PETSCII then here is a screen grab taken from my emulator:

I will do a full golfed-version when I get CBM PRG Studio installed (or when I'm not on lunch at work).

# Answer
> 0 votes
# Ruby, 79 77 chars

```
->(s){t=0;loop{system("clear");puts (s*80)[t..(80+t)];t=(t+1)%80;sleep(0.1)}}

```

# Answer
> 0 votes
### PHP, 136 bytes

```
<?php
$s="\e[0;31;40m".substr(str_repeat($argv[1],160),0,160);
while(true){for($i=0;$i<=80;$i++){usleep(100000);echo substr($s,$i)."\r";}}die;

```
* Call it with `php -f marquee.php hello\ world` to marquee "hello world" string.
* For some reason, I had to do 160 characters for the initial string, else the output would be something like `hello worlddddddddddddddddddddddddddddddddddddddd`, but it'll only loop through 80 characters - I hope that still counts.

It's been a long day, there's probably something I can do to improve it

# Answer
> 0 votes
# PHP, 85 bytes

```
for(;;usleep(1e5))echo substr(str_repeat($s=$argv[1],80),$i=++$i%strlen($s),80),"\r";

```

takes input from first command line argument; run with `-nr`.

Starts scrolling with the second character. Add one byte to start at the first character:
Replace `=++$i%` with `%=` and `;;` with `;;$i++,`.

# Answer
> 0 votes
# \[Wolfram Language (Mathematica)\], 110 bytes

```
(s=StringPadRight[#,80,#];Monitor[While[True,Pause@.1;s=StringRotateRight@s],Style[s,Red,Background->Black]])&

```

It works well with Mathematica desktop, but not with TIO/ATO (
So if someone can make a running string with TIO, it’ll be cool

---
Tags: code-golf
---