title: Munge my password

text:
# Question
Title: Munge my password
Common words should still be avoided to be used as passwords. This challenge is about coding a very simple program that munges a given password (**M**odify **U**ntil **N**ot **G**uessed **E**asily).

**Input**

A word, which is a string written in the alphabet `abcdefghijklmnopqrstuvwxyz`. It does not matter if the letters are lowercase or uppercase.

**Munging**

1. Change any repeated sequence of a same **letter** to itself preceded by the number of times the letter was repeated (`LLLL` with `4L`)
2. Change the first `a` with `@`
3. Change the first `b` with `8`
4. Change the first `c` with `(`
5. Change the first `d` with `6`
6. Change the first `e` with `3`
7. Change the first `f` with `#`
8. Change the first `g` with `9`
9. Change the first `h` with `#`
10. Change the first `i` with `1`
11. Change the second `i` with `!`
12. Change the first `k` with `<`
13. Change the first `l` with `1`
14. Change the second `l` with `i`
15. Change the first `o` with `0`
16. Change the first `q` with `9`
17. Change the first `s` with `5`
18. Change the second `s` with `$`
19. Change the first `t` with `+`
20. Change the first `v` with `>`
21. Change the second `v` with `<`
22. Change the first `w` with `uu`
23. Change the second `w` with `2u`
24. Change the first `x` with `%`
25. Change the first `y` with `?`

Rule 1 must be applied the needed number of times until it is not possible to apply it more. After that the rest of the rules are applied.

**Output** The munged word

**Examples**

* `codegolf` --\> `(0639o1#`
* `programming` --\> `pr09r@2m1ng`
* `puzzles` --\> `pu2z135`
* `passwords` --\> `p@25uu0r6$`
* `wwww` --\> `4uu`
* `aaaaaaaaaaa` --\> `11a`
* `lllolllolll` --\> `3103io3l`
* `jjjmjjjj` --\> `3jm4j`

This is , so please make your program as short as possible!

Nothing in this post should be used as password ideas or as any part of password practices.

# Answer
# Java 8, ~~237~~ ~~321~~ ~~319~~ ~~280~~ ~~247~~ ~~241~~ ~~240~~ 237 bytes

```
s->{for(int a[]=new int[26],i=0,l=s.length,t,x;i<l;i+=t){for(t=0;++t+i<l&&s[i]==s[t+i];);System.out.print((t>1?t+"":"")+(++a[x=s[i]-65]>2?s[i]:"@8(63#9#1J<1MN0P9R5+U>u%?ZABCDEFGH!JKiMNOPQR$TU<2XYZ".charAt(x+26*~-a[x])+(x==22?"u":"")));}}

```

+84 bytes because the rules got changes.. (*EDIT: Finally back to my initial 237 bytes.*) Replacing `WWWW` with `222W` is easy in Java, but with `4W` not.. If only Java had a way to use the regex capture-group for something.. Getting the length with `"$1".length()`, replacing the match itself with `"$1".replace(...)`, converting the match to an integer with `new Integer("$1")`, or using something similar as Retina (i.e. `s.replaceAll("(?=(.)\\1)(\\1)+","$#2$1")`) or JavaScript (i.e. `s.replaceAll("(.)\\1+",m->m.length()+m.charAt(0))`) would be my number 1 thing I'd like to see in Java in the future to benefit codegolfing.. \>.\> I think this is the 10th+ time I hate Java can't do anything with the capture-group match..
-78 bytes thanks to *@OlivierGrégoire*.

I/O is uppercase.

**Explanation:**

Try it here.

```
s->{                           // Method with String parameter and no return-type
  for(int a[]=new int[26],     //  Array with 26x 0
          i=0,                 //  Index-integer, starting at 0
          l=s.length,          //  Length
          t,x;                 //  Temp integers
      i<l;                     //  Loop (1) over the characters of the input
      i+=t){                   //    After every iteration: Increase `i` by `t`
    for(t=0;++                 //   Reset `t` to 1
        t+i<l                  //   Inner loop (2) from `t+i` to `l` (exclusive)
        &&s[i]==s[t+i];        //   as long as the `i`'th and `t+i`'th characters are equal
    );                         //   End of inner loop (2)
    System.out.print(          //   Print:
     (t>1?t+"":"")             //    If `t` is larger than 1: print `t`
     +(++a[x=s[i]-65]>2?       //    +If the current character occurs for the third time:
       s[i]                    //      Simply print the character
      :                        //     Else:
       "@8(63#9#1J<1MN0P9R5+U>u%?ZABCDEFGH!JKiMNOPQR$TU<2XYZ".charAt(x
                               //      Print the converted character at position `x`
        +26*~-a[x])            //       + 26 if it's the second time occurring
       +(x==22?"u":"")));      //      And also print an additional "u" if it's 'W'
  }                            //  End of loop (1)
}                              // End of method

```
> 11 votes

# Answer
# JavaScript (ES6), 147 bytes

```
s=>[[/(.)\1+/g,m=>m.length+m[0]],..."a@b8c(d6e3f#g9h#i1k<l1o0q9s5t+v>x%y?i!lis$v<".match(/../g),["w","uu"],["w","2u"]].map(r=>s=s.replace(...r))&&s

```

## Test Cases

```
f=
s=>[[/(.)\1+/g,m=>m.length+m[0]],..."a@b8c(d6e3f#g9h#i1k<l1o0q9s5t+v>x%y?i!lis$v<".match(/../g),["w","uu"],["w","2u"]].map(r=>s=s.replace(...r))&&s

;["codegolf","programming","puzzles","passwords","aabaa","www","lllolllolll","jmnpruz"]
.forEach(t=>console.log(t,"->",f(t)))
```

```
.as-console-wrapper{max-height:100%!important}
```

## Explanation

Runs through a series of replacements on the input string, `s`, in the order specified by the challenge. Each item in the series is an array or string, with two items, that is then spread (`...r`) and passed to `s.replace()`.

```
s=>[
    [/(.)\1+/g, m=>m.length + m[0]],// first replacement: transform repeated letters
                                    // into run-length encoding

                                    // string split into length-2 partitions and
                                    // spread into the main array
    ..."a@b8c(d6e3f#g9h#i1k<l1o0q9s5t+v>x%y?i!lis$v<".match(/../g),
                                    // next replacements: all single-char replacements.
                                    // "second" versions are placed at the end so they
                                    //    replace the second instance of that char

    ["w","uu"],["w","2u"]           // last replacements: the two "w" replacements
]
.map(r=> s = s.replace(...r))       // run all replacements, updating s as we go
&& s                                // and return the final string

```
> 10 votes

# Answer
# 05AB1E, 69 bytes

-9 bytes thanks to Emigna

```
γvygD≠×yÙ}J.•k®zĀÒĀ+ÎÍ=ëµι
•"@8(63#9#1<1095+>%?!i$<"ø'w„uu„2u‚â«vy`.;

```

Try it online!
> 6 votes

# Answer
# Perl 5, 152 + 1 (`-p`) = 153 bytes

```
s/(.)\1+/(length$&).$1/ge;%k='a@b8c(d6e3f#g9h#i1j!k<l1mio0q9r5s$t+u>v<x%y?'=~/./g;for$i(sort keys%k){$r=$k{$i};$i=~y/jmru/ilsv/;s/$i/$r/}s/w/uu/;s/w/2u/

```

Try it online!
> 6 votes

# Answer
Probably not the most golfed it could be, but it works.

-6 bytes thanks to ovs

-77 Bytes thanks to NieDzejkob and Jonathan French

# Python 3, 329 323 bytes 246 bytes

```
import re;n=input()
for a in re.finditer('(\w)\\1+',n):b=a.group();n=n.replace(b,str(len(b))+b[0],1)
for A,B,C in[('abcdefghikloqstvxyw','@8(63#9#1<1095+>%?','uu'),('ilsvw','!i$<','2u')]:
	for a,b in zip(A,list(B)+[C]):n=n.replace(a,b,1)
print(n)

```

Try it online!
> 4 votes

# Answer
# Retina, ~~166~~ 124 bytes

```
(.)\1+
$.&$1
([a-y])(?<!\1.+)
¶$&
¶w
uu
T`l¶`@8(63#9#1j<\1mn0\p9r5+u>\w%?_`¶.
([ilsvw])(?<!\1.+)
¶$&
¶w
2u
T`i\lsv¶`!i$<_`¶.

```

Try it online! Explanation:

```
(.)\1+
$.&$1

```

Replace a run of repeated letters with the length and the letter.

```
([a-y])(?<!\1.+)
¶$&

```

Match the first occurrence of the letters `a` to `y` and mark them with a placeholder.

```
¶w
uu

```

Fix the first occurrence of `w`.

```
T`l¶`@8(63#9#1j<\1mn0\p9r5+u>\w%?_`¶.

```

Fix the first occurrence of all the other letters from `a` to `y` and delete the placeholders.

```
([ilsvw])(?<!\1.+)
¶$&

```

Mark the (originally) second occurrence of the letters `i`, `l`, `s`, `v`, or `w` with a placeholder.

```
¶w
2u

```

Fix the second occurrence of `w`.

```
T`i\lsv¶`!i$<_`¶.

```

Fix the second occurrence of the other four letters.
> 3 votes

# Answer
# Haskell, ~~221~~ ~~218~~ 213 bytes

```
($(f<$>words"w2u li i! s$ v< a@ b8 c( d6 e3 f# g9 h# i1 k< l1 o0 q9 s5 t+ v> wuu x% y?")++[r]).foldr($)
f(a:b)(h:t)|a==h=b++t|1>0=h:f(a:b)t
f _ s=s
r(a:b)|(p,q)<-span(==a)b=[c|c<-show$1+length p,p>[]]++a:r q
r s=s

```

Try it online!

Abuses `foldr` to run the string through a sequence of string transformations backwards. The sequence "starts" with `r` which does the repetition count replacement by using `span` to break the tail of the string when it stops being equal to the head. If the first part of that is non-empty it's a repetition so we print the length +1. Next we curry an argument into `f` for each character replacement in (reverse) order. The replacements are encoded as a single string with the first character being the character to be replaced and the rest as the string (since the w replacements are multiple characters) to go in its place. I put these encoded strings in one big string separated by spaces so that `words` can break it into a list for me.

EDIT: Thanks @Laikoni for saving me 5 bytes! That was a clever use of `$` I didn't think of. I also didn't know that `<-` trick.
> 3 votes

# Answer
# , ~~224~~ 219 bytes

```
function(s,K=function(x)el(strsplit(x,"")),u=rle(K(s)))
Reduce(function(x,y)sub(K('abcdefghiiklloqsstvvwwxy')[y],c(K('@8(63#9#1!<1i095$+><'),'uu','2u',K('%?'))[y],x),1:24,paste0(gsub("1","",paste(u$l)),u$v,collapse=""))

```

Try it online!

Nasty, but the main part is the iterative substitution in the `Reduce`. `sub` changes only the first occurrence of the match.

*Thanks to JayCe for pointing out a nice golf!*
> 2 votes

# Answer
# Lua, 173 bytes

```
s=...for c,r in("uua@b8c(d6e3f#g9h#i1i!jjk<l1limmnno0ppq9rrs5s$t+v>v<wuuw2ux%y?zz"):gmatch"(.)(.u?)"do s=s:gsub(c..c.."+",function(p)return#p..c end):gsub(c,r,1)end print(s)

```

Try it online!

Ungolfed and explained:

```
s = ...

--This string contains every character to replace, followed by
--the character(s) it should be replaced with.
--
--It also contains all characters for which repeated sequences
--of them should be replaced by "<number><character>". That is,
--all letters in the alphabet. This way, a single loop can do
--both the "replace repeated characters" and "encode characters"
--operations, saving a for loop iterating over the alphabet.
--
--Characters that shouldn't be replaced will be replaced with
--themselves.
--
--In order to avoid matching half of the "replace u with u"
--command as the replace part of another command, "uu" is placed
--at the beginning of the string. This ensures that only the
--2-character replacements for "w" get an extra "u".

cmdstring = "uua@b8c(d6e3f#g9h#i1i!jjk<l1limmnno0ppq9rrs5s$t+v>v<wuuw2ux%y?zz"

--Iterate over all the search/replace commands.
--The character to replace is in the "c" variable, the string to
--replace it with is in "r".
--
--Due to the dummy search/replace commands (i.e. "mm") placed
--in the string, this loop will also iterate over all letters
--of the alphabet.

for c,r in cmdstring:gmatch("(.)(.u?)") do

	--First, replace any occurences of the current letter
	--multiple times in a row with "<number><letter>".
	s = s:gsub(c..c.."+", function(p)
		return #p .. c
	end)

	--Then, replace the first occurence of the letter
	--with the replacement from the command string.
	s = s:gsub(c, r, 1)
end

print(s)

```
> 2 votes

# Answer
# **C# (.NET Core), ~~317~~, ~~289~~, 279 Bytes**

```
p=>{string r="",l=r,h=r,c="a@b8c(d6e3f#g9h#i1i!k<l1lio0q9s5s$t+v>v<wuw2x%y?";int i=0,n=p.Length,d,a=1;for(;i<n;i++){h=p[i]+"";if(h==p[(i==n-1?i:i+1)]+""&&i!=n-1)a++;else{d=c.IndexOf(h);if(d>=0&&d%2<1){l=c[d+1]+"";h=l=="u"?"uu":l;c=c.Remove(d,2);}r+=a>1?a+""+h:h;a=1;}}return r;};

```

Try it Online!

I hope it's ok to receive a char array as an input and not a string.

**Ungolfed**:

```
string result = "", casesCharReplacement = result, currentChar = result, cases = "a@b8c(d6e3f#g9h#i1i!k<l1lio0q9s5s$t+v>v<wuw2x%y?";
int i = 0, n = pas.Length, casesIndex, charAmounts = 1;

// For every char in the pass.
for (; i < n; i++)
{
    currentChar = pas[i] + "";
    // if the next char is equal to the current and its not the end of the string then add a +1 to the repeated letter.
    if (currentChar == (pas[(i == n - 1 ? i : i + 1)] + "") && i != n - 1)
        charAmounts++;
    else
    {
        // Finished reading repeated chars (N+Char).
        casesIndex = cases.IndexOf(currentChar);
        // Look for the replacement character: only if the index is an even position, otherwise I could mess up with letters like 'i'.
        if (casesIndex >= 0 && casesIndex % 2 < 1)
        {
            casesCharReplacement = cases[casesIndex + 1]+"";
            // Add the **** +u
            currentChar = casesCharReplacement == "u"?"uu": casesCharReplacement;
            // Remove the 2 replacement characters (ex: a@) as I won't need them anymore.
            cases = cases.Remove(casesIndex, 2);
        }
        // if the amount of letters founded is =1 then only the letter, otherwise number and the letter already replaced with the cases.
        result += charAmounts > 1 ? charAmounts + ""+currentChar : currentChar;
        charAmounts = 1;
    }
}
return result;

```
> 2 votes

# Answer
## C++, ~~571~~ ~~495~~ ~~478~~ 444 bytes

-127 bytes thanks to Zacharý

```
#include<string>
#define F r.find(
#define U(S,n)p=F s(S)+b[i]);if(p-size_t(-1)){b.replace(i,1,r.substr(p+n+1,F'/',n+p)-p-2));r.replace(p+1,F'/',p+1)-p,"");}
#define V(A)i<A.size();++i,c
using s=std::string;s m(s a){s b,r="/a@/b8/c(/d6/e3/f#/g9/h#/i1//i!/k</l1//li/o0/q9/s5//s$/t+/v>/wuu//w2u/x%/y?/";int c=1,i=0;for(;V(a)=1){for(;a[i]==a[i+1]&&1+V(a)++);b+=(c-1?std::to_string(c):"")+a[i];}for(i=0;V(b)){auto U("/",1)else{U("//",2)}}return b;}

```

the `"/a@/b8/c(/d6/e3/f#/g9/h#/i1//i!/k</l1//li/o0/q9/s5//s$/t+/v>/wuu//w2u/x%/y?/"` string is used to transform from one character to others. 1 `/` means that the first "next char" should be replaced by what follow the next `/`, 2 means that the second "next char" should be replaced by what follows.

Try it online
> 2 votes

# Answer
## Perl 5, 123 bytes

**122 bytes code + 1 for `-p`.**

Developed independently from @Xcali's answer, but using a very similar process.

```
s/(.)\1+/$&=~y!!!c.$1/ge;eval"s/$1/$2/"while'a@b8c(d6e3f#g9h#i1i!k<l1lio0q9s5t+v>v<x%y?'=~/(.)(.)/g;s/s/\$/;s/w/uu/;s;w;2u

```

Try it online!
> 1 votes

# Answer
# Python 2, ~~220~~ ~~216~~ ~~194~~ ~~190~~ 188 bytes

```
import re
S=re.sub(r'(.)\1+',lambda m:`len(m.group(0))`+m.group(1),input())
for a,b in zip('abcdefghiiklloqsstvvxyww',list('@8(63#9#1!<1i095$+><%?')+['uu','2u']):S=S.replace(a,b,1)
print S

```

Try it online!

# Python 3, 187 bytes

```
import re
S=re.sub(r'(.)\1+',lambda m:str(len(m.group(0)))+m.group(1),input())
for a,b in zip('abcdefghiiklloqsstvvxyww',[*'@8(63#9#1!<1i095$+><%?','uu','2u']):S=S.replace(a,b,1)
print(S)

```

Try it online!
> 1 votes

# Answer
# Pip, ~~103~~ 102 bytes

```
aR:`(.)\1+`#_.B
Fm"abcdefghiiklloqsstvvwwxy"Z"@8(63#9#1!<1i095$+><WU%?"I#Ya@?@maRA:ym@1aR'W"uu"R'U"2u"

```

Try it online!

### Explanation

The code does three steps of transformation:

```
aR:`(.)\1+`#_.B  Process runs of identical letters

a                1st cmdline argument
 R:              Do this replacement and assign back to a:
   `(.)\1+`       This regex (matches 2 or more of same character in a row)
           #_.B   Replace with callback function: concatenate (length of full match) and
                  (first capture group)
                  Note: #_.B is a shortcut form for {#a.b}

Fm"..."Z"..."I#Ya@?@maRA:ym@1  Do the bulk of rules 2-25

  "..."                        String of letters to replace
       Z"..."                  Zip with string of characters to replace with
Fm                             For each m in the zipped list:
                   @m           First item of m is letter to replace
                a@?             Find its index in a, or nil if it isn't in a
               Y                Yank that into y
             I#                 If len of that is truthy:*
                     aRA:        Replace character in a at...
                         y        index y...
                          m@1     with second item of m

aR'W"uu"R'U"2u"  Clean up substitution
                 In the previous step, the replacements each had to be a single character.
                 This doesn't work for uu and 2u, so we use W and U instead (safe, since
                 uppercase letters won't be in the input) and replace them here with the
                 correct substitutions.
aR'W"uu"         In a, replace W with uu
        R'U"2u"  and U with 2u
                 and print the result (implicit)

```

* We need to test whether `a@?m@0` is nil. It's not enough to test that it's truthy, since 0 is a legitimate index that is falsey. Pip doesn't have a short builtin way to test if a value is nil, but testing its length works well enough in this case: any number will have length at least 1 (truthy), and nil has length of nil (falsey).
> 1 votes

---
Tags: code-golf
---


title: Random sampling without replacement

text:
# Question
Title: Random sampling without replacement
Create a function that will output a set of distinct random numbers drawn from a range. The order of the elements in the set is unimportant (they can even be sorted), but it must be possible for the contents of the set to be different each time the function is called.

The function will receive 3 parameters in whatever order you want:

1. Count of numbers in output set
2. Lower limit (inclusive)
3. Upper limit (inclusive)

Assume all numbers are integers in the range 0 (inclusive) to 231 (exclusive). The output can be passed back any way you want (write to console, as an array, etc.)

**Judging**

Criteria includes the 3 R's

1. **Run-time** \- tested on a quad-core Windows 7 machine with whatever compiler is freely or easily available (provide a link if necessary)
2. **Robustness** \- does the function handle corner cases or will it fall into an infinite loop or produce invalid results - an exception or error on invalid input is valid
3. **Randomness** \- it should produce random results that are not easily predictable with a random distribution. Using the built in random number generator is fine. But there should be no obvious biases or obvious predictable patterns. Needs to be better than that random number generator used by the Accounting Department in Dilbert

If it is robust and random then it comes down to run-time. Failing to be robust or random greatly hurts its standings.

# Answer
> 6 votes
## Python

```
import random

def sample(n, lower, upper):
    result = []
    pool = {}
    for _ in xrange(n):
        i = random.randint(lower, upper)
        x = pool.get(i, i)
        pool[i] = pool.get(lower, lower)
        lower += 1
        result.append(x)
    return result

```

I probably just re-invented some well-known algorithm, but the idea is to (conceptually) perform a partial Fisher-Yates shuffle of the range `lower..upper` to get the length `n` prefix of a uniformly shuffled range.

Of course, storing the whole range would be rather expensive, so I only store the locations where the elements have been swapped.

This way, the algorithm should perform well both in the case where you're sampling numbers from a tight range (e.g. 1000 numbers in the range 1..1000), as well as the case where you're sampling numbers from a large range.

I'm not sure about the quality of randomness from the built-in generator in Python, but it's relatively simple to swap in any generator that can generate integers uniformly from some range.

# Answer
> 1 votes
## python 2.7

```
import random
print(lambda x,y,z:random.sample(xrange(y,z),x))(input(),input(),input())

```

not sure what your standing is on using builtin random methods, but here you go anyways. nice and short

edit: just noticed that range() doesn't like to make big lists. results in a memory error. will see if there is any other way to do this...

edit2: range was the wrong function, xrange works. The maximum integer is actually `2**31-1` for python

test:

```
python sample.py
10
0
2**31-1
[786475923, 2087214992, 951609341, 1894308203, 173531663, 211170399, 426989602, 1909298419, 1424337410, 2090382873]

```

# Answer
> 1 votes
**C**

Returns an array containing x unique random ints between min and max. (caller must free)

```
#include <stdlib.h>
#include <stdint.h>
#define MAX_ALLOC ((uint32_t)0x40000000)  //max allocated bytes, fix per platform
#define MAX_SAMPLES (MAX_ALLOC/sizeof(uint32_t))

int* randsamp(uint32_t x, uint32_t min, uint32_t max)
{
   uint32_t r,i=x,*a;
   if (!x||x>MAX_SAMPLES||x>(max-min+1)) return NULL;
   a=malloc(x*sizeof(uint32_t));
   while (i--) {
      r= (max-min+1-i);
      a[i]=min+=(r ? rand()%r : 0);
      min++;
   }
   while (x>1) {
      r=a[i=rand()%x--];
      a[i]=a[x];
      a[x]=r;
   }
   return a;
}

```

Works by generating x sequential random integers in the range, then shuffling them. Add a `seed(time)` somewhere in caller if you don't want the same results every run.

# Answer
> 1 votes
# Ruby \>= 1.8.7

```
def pick(num, min, max)
  (min..max).to_a.sample(num)
end

p pick(5, 10, 20) #=>[12, 18, 13, 11, 10]

```

# Answer
> 1 votes
## R

```
s <- function(n, lower, upper) sample(lower:upper,n); s(10,0,2^31-2)

```

# Answer
> 1 votes
The question is not correct. Do you need uniform sampling or not? In the case uniform sampling is needed I have the following code in R, which has average complexity *O*(*s* log *s*), where *s* is the sample size.

```
# The Tree growing algorithm for uniform sampling without replacement
# by Pavel Ruzankin
quicksample = function (n,size)
# n - the number of items to choose from
# size - the sample size
{
  s=as.integer(size)
  if (s>n) {
    stop("Sample size is greater than the number of items to choose from")
  }
  # upv=integer(s) #level up edge is pointing to
  leftv=integer(s) #left edge is poiting to; must be filled with zeros
  rightv=integer(s) #right edge is pointig to; must be filled with zeros
  samp=integer(s) #the sample
  ordn=integer(s) #relative ordinal number

  ordn[1L]=1L #initial value for the root vertex
  samp[1L]=sample(n,1L)
  if (s > 1L) for (j in 2L:s) {
    curn=sample(n-j+1L,1L) #current number sampled
    curordn=0L #currend ordinal number
    v=1L #current vertice
    from=1L #how have come here: 0 - by left edge, 1 - by right edge
    repeat {
      curordn=curordn+ordn[v]
      if (curn+curordn>samp[v]) { #going down by the right edge
        if (from == 0L) {
          ordn[v]=ordn[v]-1L
        }
        if (rightv[v]!=0L) {
          v=rightv[v]
          from=1L
        } else { #creating a new vertex
          samp[j]=curn+curordn
          ordn[j]=1L
          # upv[j]=v
          rightv[v]=j
          break
        }
      } else { #going down by the left edge
        if (from==1L) {
          ordn[v]=ordn[v]+1L
        }
        if (leftv[v]!=0L) {
          v=leftv[v]
          from=0L
        } else { #creating a new vertex
          samp[j]=curn+curordn-1L
          ordn[j]=-1L
          # upv[j]=v
          leftv[v]=j
          break
        }
      }
    }
  }
  return(samp)
}

```

Of course, one may rewrite it in C for better performance. The complexity of this algorithm is discussed in: Rouzankin, P. S.; Voytishek, A. V. On the cost of algorithms for random selection. Monte Carlo Methods Appl. 5 (1999), no. 1, 39-54. http://dx.doi.org/10.1515/mcma.1999.5.1.39

You may look through this paper for another algorithm with the same average complexity.

But if you do not need uniform sampling, only requiring that all sampled numbers be different, then the situation changes dramatically. It is not hard to write an algorithm that has average complexity *O*(*s*).

See also for uniform sampling: P. Gupta, G. P. Bhattacharjee. (1984) An efficient algorithm for random sampling without replacement. International Journal of Computer Mathematics 16:4, pages 201-209. DOI: 10.1080/00207168408803438

Teuhola, J. and Nevalainen, O. 1982. Two efficient algorithms for random sampling without replacement. /IJCM/, 11(2): 127–140. DOI: 10.1080/00207168208803304

In the last paper the authors use hash tables and claim that their algorithms have *O*(*s*) complexity. There is one more fast hash table algorithm, which will soon be implemented in pqR (pretty quick R): https://stat.ethz.ch/pipermail/r-devel/2017-October/075012.html

# Answer
> 1 votes
# APL, 18 22 bytes

```
{⍵[0]+(1↑⍺)?⍵[1]-⍵[0]}

```

Declares an anonymous function that takes two arguments  and .  is the number of random numbers you want,  is a vector containing the lower and upper bounds, in that order.

`a?b` picks `a` random numbers between 0-`b` without replacement. By taking `⍵[1]-⍵[0]` we get the range size. Then we pick  numbers (see below) from that range and add the lower bound. In C, this would be

```
lower + rand() * (upper - lower)

```

times without replacement. Parentheses not needed because APL operates right-to-left.

Assuming I've understood the conditions correctly, this fails the 'robustness' criteria because the function will fail if given improper arguments (e.g. passing a vector instead of a scalar as ).

In the event that  is a vector rather than a scalar, `1↑⍺` takes the first element of . For a scalar, this is the scalar itself. For a vector, it's the first element. This should make the function meet the 'robustness' criteria.

Example:

```
Input: 100 {⍵[0]+⍺?⍵[1]-⍵[0]} 0 100
Output: 34 10 85 2 46 56 32 8 36 79 77 24 90 70 99 61 0 21 86 50 83 5 23 27 26 98 88 66 58 54 76 20 91 72 71 65 63 15 33 11 96 60 43 55 30 48 73 75 31 13 19 3 45 44 95 57 97 37 68 78 89 14 51 47 74 9 67 18 12 92 6 49 41 4 80 29 82 16 94 52 59 28 17 87 25 84 35 22 38 1 93 81 42 40 69 53 7 39 64 62

```

# Answer
> 0 votes
## Scala

```
object RandSet {
  val random = util.Random

  def rand (count: Int, lower: Int, upper: Int, sofar: Set[Int] = Set.empty): Set[Int] =
    if (count == sofar.size) sofar else
    rand (count, lower, upper, sofar + (random.nextInt (upper-lower) + lower))
}

object RandSetRunner {

  def main (args: Array [String]) : Unit = {
    if (args.length == 4)
      (0 until args (0).toInt).foreach { unused =>
      println (RandSet.rand (args (1).toInt, args (2).toInt, args (3).toInt).mkString (" "))
    }
    else Console.err.println ("usage: scala RandSetRunner OUTERCOUNT COUNT MIN MAX")
  }
}

```

### compile and run:

```
scalac RandSetRunner.scala
scala RandSetRunner 200 15 0 100

```

The second line will run 200 tests with 15 values from 0 to 100, because Scala produces fast bytecode but needs some startup time. So 200 starts with 15 values from 0 to 100 would consume more time.

### Sample on a 2 Ghz Single Core:

```
time scala RandSetRunner 100000 10 0 1000000 > /dev/null

real    0m2.728s
user    0m2.416s
sys     0m0.168s

```

### Logic:

Using the build-in random and recursively picking numbers in the range (max-min), adding min and checking, if the size of the set is the expected size.

### Critique:

* It will be fast for small samples of big ranges, but if the task is to pick nearly all elements of a sample (999 numbers out of 1000) it will repeatedly pick numbers, already in the set.
* From the question, I'm unsure, whether I have to sanitize against unfulfillable requests like Take 10 distinct numbers from 4 to 8. This will now lead to an endless loop, but can easily be avoided with a prior check which I will append if requested.

# Answer
> 0 votes
# Scheme

Not sure why you need 3 parameters passed nor why i need to assume any range...

```
(import srfi-1) ;; for iota
(import srfi-27) ;; randomness
(import srfi-43) ;; for vector-swap!

(define rand (random-source-make-integers
               default-random-source))

;; n: length, i: lower limit
(define (random-range n i)
  (let ([v (list->vector (iota n i))])
    (let f ([n n])
      (let* ([i (rand n)] [n (- n 1)])
        (if (zero? n) v
            (begin (vector-swap! v n i) (f n)))))))

```

# Answer
> 0 votes
## R

```
random <- function(count, from, to) {
  rand.range <- to - from

  vec <- c()

  for (i in 1:count) {
    t <- sample(rand.range, 1) + from
    while(i %in% vec) {
      t <- sample(rand.range, 1) + from
    }
    vec <- c(vec, t)
  }

  return(vec)
}

```

# Answer
> 0 votes
# C++

This code is best when drawing many samples from the range.

```
#include <exception>
#include <stdexcept>
#include <cstdlib>

template<typename OutputIterator>
 void sample(OutputIterator out, int n, int min, int max)
{
  if (n < 0)
    throw std::runtime_error("negative sample size");
  if (max < min)
    throw std::runtime_error("invalid range");
  if (n > max-min+1)
    throw std::runtime_error("sample size larger than range");

  while (n>0)
  {
    double r = std::rand()/(RAND_MAX+1.0);
    if (r*(max-min+1) < n)
    {
      *out++ = min;
      --n;
    }
    ++min;
  }
}

```

# Answer
> 0 votes
## Q (19 characters)

```
f:{(neg x)?y+til z}

```

Then use f\[x;y;z\] as \[count of numbers in output set;starting point;size of range\]

e.g. f\[5;10;10\] will output 5 distinct random numbers between 10 and 19 inclusive.

```
q)\ts do[100000;f[100;1;10000]]
2418 131456j

```

Results above show performance at 100,000 iterations of picking 100 random numbers between 1 & 10,000.

# Answer
> 0 votes
## R, 31 or 40 bytes (depending on the meaning of the word “range”)

If the input has 3 numbers, `a[1], a[2], a[3]`, and by “range” you mean “an integer sequence from a\[2\] to a\[3\]”, then you have this:

```
a=scan();sample(a[2]:a[3],a[1])

```

If you have an array `n` from which you are about to resample, but under the restriction of the lower and upper limits, like “resample values of the given array `n` from the range `a[1]...a[2]`”, then use this:

```
a=scan();sample(n[n>=a[2]&n<=a[3]],a[1])

```

I am quite surprised why the previous result was not golfed considering the built-in sample with replacement facilities! We create a vector that satisfies the range condition and re-sample it.

* Robustness: the corner cases (sequences of the same length as the range to sample from) are handled by default.
* Run-time: extremely fast because it is built in.
* Randomness: the seed is automatically changed every time the RNG is invoked.

# Answer
> 0 votes
## Javascript (using external library) (64 bytes / 104 bytes??)

```
(a,b,n)=>_.Range(0,n).Select(x=>Math.random()*(b-a)+a).ToArray()

```

Link to lib: https://github.com/mvegh1/Enumerable/

Code explanation: Lambda expression accepts min,max,count as args. Create a collection of size n, and map each element to a random number fitting the min/max criteria. Convert to native JS array and return it. I ran this also on an input of size 5,000,000, and after applying a distinct transform still showed 5,000,000 elements. If it is agreed upon that this isn't safe enough of a guarantee for distinctness I will update the answer

I included some statistics in the image below...

EDIT: The below image shows code / performance that guarantees every element will be distinct. It's much much slower (6.65 seconds for 50,000 elements) vs the original code above for same args (0.012 seconds)

# Answer
> 0 votes
# K (oK), 14 bytes

**Solution:**

```
{y+(-x)?1+z-y}

```

Try it online!

**Example:**

```
> {y+(-x)?1+z-y}. 10 10 20      / note: there are two ways to provide input, dot or
13 20 16 17 19 10 14 12 11 18
> {y+(-x)?1+z-y}[10;10;20]      / explicitly with [x;y;z]
12 11 13 19 15 17 18 20 14 10

```

**Explanation:**

Takes 3 implicit inputs per spec:

* `x`, count of numbers in output set,
* `y`, lower limit (inclusive)
* `z`, upper limit (inclusive)

---

```
{y+(-x)?1+z-y} / the solution
{            } / lambda function with x, y and z as implicit inputs
          z-y  / subtract lower limit from upper limit
        1+     / add 1
   (-x)?       / take x many distinct items from 0..(1+z=y)
 y+            / add lower limit

```

**Notes:**

Also a polyglot in `q/kdb+` with an extra set of brackets: `{y+((-)x)?1+z-y}` (16 bytes).

# Answer
> 0 votes
# Axiom + its library

```
f(n:PI,a:INT,b:INT):List INT==
    r:List INT:=[]
    a>b or n>99999999 =>r
    d:=1+b-a
    for i in 1..n repeat
          r:=concat(r,a+random(d)$INT)
    r

```

The above f() function return as error the empty list, in the case f(n,a,b) with a\>b. In other cases of invalid input, it not run with one error message in Axiom window, because argument will be not of the right type. Examples

```
(6) -> f(1,1,5)
   (6)  [2]
                                                       Type: List Integer
(7) -> f(1,1,1)
   (7)  [1]
                                                       Type: List Integer
(10) -> f(10,1,1)
   (10)  [1,1,1,1,1,1,1,1,1,1]
                                                       Type: List Integer
(11) -> f(10,-20,-1)
   (11)  [- 10,- 4,- 18,- 5,- 5,- 11,- 15,- 1,- 20,- 1]
                                                       Type: List Integer
(12) -> f(10,-20,-1)
   (12)  [- 4,- 5,- 3,- 4,- 18,- 1,- 2,- 14,- 19,- 8]
                                                       Type: List Integer
(13) -> f(10,-20,-1)
   (13)  [- 18,- 12,- 12,- 19,- 19,- 15,- 5,- 17,- 19,- 4]
                                                       Type: List Integer
(14) -> f(10,-20,-1)
   (14)  [- 8,- 11,- 20,- 10,- 4,- 8,- 11,- 3,- 10,- 16]
                                                       Type: List Integer
(15) -> f(10,9,-1)
   (15)  []
                                                       Type: List Integer
(16) -> f(10,0,100)
   (16)  [72,83,41,35,27,0,33,18,60,38]
                                                       Type: List Integer

```

---
Tags: code-challenge, fastest-code, number, random
---


title: Case Matching Find Replace

text:
# Question
Title: Case Matching Find Replace
Take three inputs, a string of text, `T`; a string of characters to replace, `F`; and a string of characters to replace them with, `R`. For each substring of `T` with the same (case insensitive) characters as `F`, replace them with the characters in `R`. However, keep the same case as the original text.

If there are more characters in `R` than `F`, the extra characters should be the same case as they are in `R`. If there are numbers or symbols in `F`, then the corresponding characters in `R` should keep the case they have in `R`. `F` will not necessarily appear in `T`.

You can assume all text will be in the printable ASCII range.

# Examples

```
"Text input", "text", "test" -> "Test input"

"tHiS Is a PiEcE oF tExT", "is", "abcde" -> "tHaBcde Abcde a PiEcE oF tExT"

"The birch canoe slid on the smooth planks", "o", " OH MY " -> "The birch can OH MY e slid  OH MY n the sm OH MY  OH MY th planks"

"The score was 10 to 5", "10", "tEn" -> "The score was tEn to 5"

"I wrote my code in Brain$#@!", "$#@!", "Friend" -> "I wrote my code in BrainFriend"

"This challenge was created by Andrew Piliser", "Andrew Piliser", "Martin Ender" -> "This challenge was created by Martin Ender"

// Has a match, but does not match case
"John does not know", "John Doe", "Jane Doe" -> "Jane does not know"

// No match
"Glue the sheet to the dark blue background", "Glue the sheet to the dark-blue background", "foo" -> "Glue the sheet to the dark blue background"

// Only take full matches
"aaa", "aa", "b" -> "ba"

// Apply matching once across the string as a whole, do not iterate on replaced text
"aaaa", "aa", "a" -> "aa"

"TeXT input", "text", "test" -> "TeST input"

```

Sandbox link

# Answer
# APL (Dyalog), ~~75~~ ~~73~~ 72 bytes

Prompts for `T`, `R`, and `F` in that order. `R` must b given in Dyalog transformation format and `F` must be given in PCRE format.

```
⍞⎕R(⍞∘{(⊣⌿d)l¨⍨(1∘⌷≠(⊢⌿d∊⎕A,l⎕A)∧≠⌿)d≠(l←819⌶)d←↑⍺⍵.Match↑¨⍨≢⍺})⍠1⊢⍞

```

Try it online!

prompt for `T`

yield that (separates 1 and `T`)

`⍞⎕R(``)⍠1` prompt for `F` and **R**eplace matches with the result of the following function:

`⍞∘{…}` derive a monadic function by tying the prompted-for `R` as left argument to:

`≢⍺` count the number of letters in `R`

`⍺⍵.Match↑¨⍨` take that many letters from each of `R` and the match
 is the left argument, which we tied `R` as.
 is a namespace in which `Match` contains the currently found string.

mix those two into a two-row matrix

`d←` store as `d`

`(``)` apply the following tacit function to that:

`819⌶` lowercase (mnemonic: **819** looks like **Big**)

`l←` store that function as as `l`

`d≠` Boolean where `d` differs (i.e. gives 0/1 for each lowercase/uppercase letter)

`(``)` apply the following tacit function to that:

`≠⌿` vertical XOR

`(``)∧` Boolean AND with the following array:

`l⎕A` lowercased **A**lphabet

`⎕A,` prepend uppercase **A**lphabet

`d∊` Boolean for each letter in d whether a member of that (i.e. whether a letter)

`⊢⌿` last row i.e. for character of the match whether it is a letter

`1∘⌷≠` XOR with the first row, i.e. whether each character of `R` is uppercase

`(``)l¨⍨` use that to lowercase (if 0) or uppercase (if 1) each letter of:

`⊣⌿` the first row, i.e. `R`

---

* Byte count for Dyalog Classic using `⎕OPT`  instead of .
> 3 votes

# Answer
# Retina, 116 bytes

```
i`(.+)(?=.*¶\1(¶.*)$)|.*¶.*$
¶¶$2¶$1¶¶
{T`l`L`¶¶.(?=.*¶[A-Z])
T`L`l`¶¶.(?=.*¶[a-z])
}`¶¶¶(.)(.*¶).
$1¶¶¶$2
¶¶¶¶.*|¶

```

Try it online! Explanation:

```
i`(.+)(?=.*¶\1(¶.*)$)|.*¶.*$
¶¶$2¶$1¶¶

```

This searches `T` and whenever there's a case-insensitive match against the lookahead to `F` the match is surrounded in a bunch of newlines and the lookahead to `R` is also inserted.

```
{T`l`L`¶¶.(?=.*¶[A-Z])
T`L`l`¶¶.(?=.*¶[a-z])
}`¶¶¶(.)(.*¶).
$1¶¶¶$2

```

Each letter of the copy of `R` is adjusted in case to match that of the match, following which it is moved out of the working area so that the next letter can be processed, until either the copy of `R` or the match runs out of letters.

```
¶¶¶¶.*|¶

```

If the copy of `R` runs out of letters, then the remainder of the match will be preceded by 4 newlines, so delete it. Otherwise, anything left will be left-over pieces of copies of `R` which need to be concatenated with the non-matching parts of the input to produce the result.
> 3 votes

# Answer
*Withdrawn. Dom's answer beats it by a long shot.*

~~\# Perl 5, 136 + 1 (-p) = 137 bytes~~

~~```
$f=<>;chomp$f;@R=($r=<>)=~/./g;for$i(/\Q$f/gi){$c=$n='';$"=$R[$c++],$n.=/[A-Z]/?uc$":/[a-z]/?lc$":$"for$i=~/./g;s/\Q$i/$n.substr$r,$c/e}

```
Try it online!
*made a huge cut after @Dom Hastings mentioned `\Q`*
~~\# Perl 5, 176 + 1 (-p) = 177 bytes~~
```
sub h($){chomp@_;pop=~s/[^a-z0-9 ]/\\$&/gir}$f=h<>;@R=($r=<>)=~/./g;for$i(/$f/gi){$c=$n='';$"=$R[$c++],$n.=/[A-Z]/?uc$":/[a-z]/?lc$":$"for$i=~/./g;$i=h$i;s/$i/$n.substr$r,$c/e}

```
Try it online!
~~
> 2 votes

# Answer
## Perl 5, 108 bytes

**107 bytes code + 1 for `-p`.**

```
chomp(($s,$r)=<>);s|\Q$s|$&=~s!.!$_=substr$r,"@-",1;$&=~/[a-z]/i?$&eq uc$&?uc:lc:$_!egr.substr$r,"@-"+1|gie

```

Try it online!
> 2 votes

# Answer
# PowerShell, 190 bytes

```
param($T,$F,$R)[regex]::Replace($T,'(?i)'+[regex]::escape($F),{param($m)-join(0..$R.Length|%{(($y=$R[$_]),("$y"."To$((('Low','Upp')[($z="$m"[$_])-cmatch($C='[A-Z]')]))er"()))[$z-match$C]})})

```

Try it online!

Explanation:

```
[Regex]::Replace(
    input text T,
    Find text F with case insensitive and [regex]::escape() for symbols,
    {scriptblock} for computing the replacement
)

```

The replacment scriptblock does:

```
$m is the matched text with case information
loop over each character in R as $y
    $z is the same index character in $m ($null if R overruns)
    $z-match'[A-Z]' checks if alphabetic, so we must to case-match
      otherwise, non-alphabetic or null, no case-match, return $y unchanged.
    if case-matching, check if z case-sensitive matches '[A-Z]' and
      use dynamic method calling from a generated string, either
      $y."ToLower"()
      $y."ToUpper"()
      to force the match
-join the loop output into a replacement string

```

Test cases:

```
function f {
param($T,$F,$R)[regex]::Replace($T,'(?i)'+[regex]::escape($F),{param($m)-join(0..$R.Length|%{(($y=$R[$_]),("$y"."To$((('Low','Upp')[($z="$m"[$_])-cmatch($C='[A-Z]')]))er"()))[$z-match$C]})})
}

Import-Module Pester

$Cases = @(
    @{Text = "Text input"; Find = "text"; Replace = "test"; Result = "Test input" }
    @{Text = "tHiS Is a PiEcE oF tExT"; Find = "is"; Replace = "abcde"; Result = "tHaBcde Abcde a PiEcE oF tExT" }
    @{Text = "The birch canoe slid on the smooth planks"; Find = "o"; Replace = " OH MY "; Result = "The birch can OH MY e slid  OH MY n the sm OH MY  OH MY th planks" }
    @{Text = "The score was 10 to 5"; Find = "10"; Replace = "tEn"; Result = "The score was tEn to 5" }
    @{Text = "I wrote my code in Brain$#@!"; Find = "$#@!"; Replace = "Friend"; Result = "I wrote my code in BrainFriend" }
    @{Text = "This challenge was created by Andrew Piliser"; Find = "Andrew Piliser"; Replace = "Martin Ender"; Result = "This challenge was created by Martin Ender" }
    @{Text = "John does not know"; Find = "John Doe"; Replace = "Jane Doe" ; Result ="Jane does not know" }
    @{Text = "Glue the sheet to the dark blue background"; Find = "Glue the sheet to the dark-blue background"; Replace = "foo"; Result ="Glue the sheet to the dark blue background" }
    @{Text = "aaa" ; Find = "aa"; Replace = "b"; Result ="ba" }
    @{Text = "aaaa"; Find = "aa"; Replace = "a"; Result ="aa" }
    @{Text = "TeXT input"; Find = "text"; Replace = "test"; Result ="TeST input" }
)

Describe "Tests" {

    It "works on /<Text>/<Find>/<Replace>/ == '<Result>'" -TestCases $Cases {
        param($Text, $Find, $Replace, $Result)
        f $Text $Find $Replace | Should -BeExactly $Result
    }

}

```
> 2 votes

# Answer
# Python 2, ~~193~~ 200 bytes

```
T,F,R=input()
w=str.lower
i=-len(T)
l=len(F)
T+=' '
while i:
 s=T[i:i+l]
 if w(s)==w(F):T=T[:i]+`[[y,[w(y),y.upper()][x<'a']][x.isalpha()]for x,y in zip(s,R)]`[2::5]+R[l:]+T[i+l:];i+=l-1
 i+=1
print T

```

Try it online!
> 1 votes

# Answer
## TXR Lisp, 285 bytes

```
(defun f(s f r)(let*((w(copy s))(x(regex-compile ^(compound,(upcase-str f))))(m(reverse(tok-where(upcase-str s)x))))(each((n m))(set[w n]r) (for((i(from n)))((< i (min(to n)(len w))))((inc i))(cond((chr-isupper[s i])(upd[w i]chr-toupper))((chr-islower[s i])(upd[w i]chr-tolower)))))w))

```

Conventionally formatted original:

```
(defun f (s f r)
  (let* ((w (copy s))
         (x (regex-compile ^(compound ,(upcase-str f))))
         (m (reverse (tok-where (upcase-str s) x))))
    (each ((n m))
      (set [w n] r)
      (for ((i (from n))) ((< i (min (to n) (len w)))) ((inc i))
        (cond ((chr-isupper [s i]) (upd [w i] chr-toupper))
              ((chr-islower [s i]) (upd [w i] chr-tolower)))))
    w))

```
> 1 votes

# Answer
# JavaScript, 177 bytes

```
(T,F,R)=>T.replace(eval(`/${F.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&')}/gi`),F=>[...R].map((r,i)=>/[A-Z]/i.test(f=F[i]||'')?r[`to${f>'`'&&f<'{'?'Low':'Upp'}erCase`]():r).join``)

```

```
F=
(T,F,R)=>T.replace(eval(`/${F.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&')}/gi`),F=>[...R].map((r,i)=>/[A-Z]/i.test(f=F[i]||'')?r[`to${f>'`'&&f<'{'?'Low':'Upp'}erCase`]():r).join``)

document.write([
  ["Text input", "text", "test"],
  ["tHiS Is a PiEcE oF tExT", "is", "abcde"],
  ["The birch canoe slid on the smooth planks", "o", " OH MY "],
  ["The score was 10 to 5", "10", "tEn"],
  ["I wrote my code in Brain$#@!", "$#@!", "Friend"],
  ["This challenge was created by Andrew Piliser", "Andrew Piliser", "Martin Ender"],
  ["John does not know", "John Doe", "Jane Doe"],
  ["Glue the sheet to the dark blue background", "Glue the sheet to the dark-blue background", "foo"],
  ["aaa", "aa", "b"],
  ["aaaa", "aa", "a"],
  ["TeXT input", "text", "test"],
].map(a=>F(...a)).join('<br>'))

/*
(T,F,R)=>T.replace(
 eval(`/${F.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&')}/gi`),
    //F=>eval("for(i in R)r+=(f=F[i])&&/[A-Z]/i.test(f)?R[i][`to${f>'`'&&f<'{'?'Low':'Upp'}erCase`]():R[i];r",r='')
 //F=>[...R].map((r,i)=>(f=F[i])&&/[A-Z]/i.test(f)?r[`to${f>'`'&&f<'{'?'Low':'Upp'}erCase`]():r).join``
    //F=>[...R].reduce((s,r,i)=>s+(f=F[i])&&/[A-Z]/i.test(f)?r[`to${f>'`'&&f<'{'?'Low':'Upp'}erCase`]():r,'')
    F=>[...R].map((r,i)=>/[A-Z]/i.test(f=F[i]||'')?r[`to${f>'`'&&f<'{'?'Low':'Upp'}erCase`]():r).join``
)*/
```

Less golfed:

```
(T,F,R) => T.replace(
    eval(`/${F.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&')}/gi`),
    F=>[...R].map((r,i) =>
        /[A-Z]/i.test(f = F[i] || '')
            ? r[`to${
                f > '`' && f < '{'
                    ? 'Low'
                    : 'Upp'
                }erCase`]()
            : r
    ).join``
)

```

47 bytes came from this regex escape function since the program has to handle symbols. :(
> 1 votes

# Answer
# Python 3, 183 bytes

```
import re
j="".join
f=lambda T,F,R:j((p,j((y,(y.lower(),y.upper())[x<'a'])[x.isalpha()]for(x,y)in zip(p,R))+R[len(F):])[i%2>0]for i,p in enumerate(re.split('('+re.escape(F)+')',T,0,2)))

```

Try it online!

`re.split` \+ keep all even elements and replace all the odd elements by the correct transformation of the replacement string:

```
>>> re.split("(is)","tHiS Is a PiEcE oF tExT",0,2) # 2=re.IGNORE_CASE
['tH', 'iS', ' ', 'Is', ' a PiEcE oF tExT']

```
> 1 votes

# Answer
# C (gcc), ~~210~~ ~~211~~ ~~207~~ 189 bytes

Had to add one byte to fix a bug with the capitalization for the "BrainFriend" testcase

Wow was this tedious... Now to golf away some bytes

```
char*c,*p;d,l;f(t,f,r){for(d=isalpha(*(p=f)),p=c=t;c=strcasestr(c,f);p=c+=l>0?l:0){for(l=strlen(f);p<c;)putchar(*p++);for(p=r;*p;p++,c+=l-->0)putchar(d*l<1?*p:*c&32?*p|32:*p&~32);}puts(p);}

```

Try it online!
> 1 votes

# Answer
# C# (Mono C# compiler), 241 bytes

```
using System.Text.RegularExpressions;
class Program {
static void Main(string[] args) {
r("Text input","text","Test");
}
static void r(string v,string i,string u)
{
System.Console.WriteLine(Regex.Replace(v,i,u,RegexOptions.IgnoreCase));
}
}

```

Try it online!
> 1 votes

---
Tags: code-golf, string
---


title: Convert RGB color to websafe

text:
# Question
Title: Convert RGB color to websafe
Web safe colors are in intervals of 51, they include 0, 3, 6, 9, c, and, f as digits in hex (such as #993333), or 0, 51, 102, 153, 204, 255 in decimal. Your task today is convert a given color to a web safe one. You may read more about web safe colors on Wikipedia.

**Input**

You will take in 3 integers between 0, 255 inclusive representing red, green, and blue values.

**Output**

Output the converted 3 integers, as an array or similar structure.

**Rules**

* answers must be rounded to the nearest value, not floor or ceiling. (25 -\> 0 and 26 -\> 51)
* As this is code golf, lowest bytes wins.

**Test Cases**

```
Input            Output
(0, 25, 76)      (0, 0, 51)
(1, 26, 77)      (0, 51, 102)
(127, 178, 229)  (102, 153, 204)
(128, 179, 230)  (153, 204, 255)
(0, 254, 255)    (0, 255, 255)
(9, 143, 53)     (0, 153, 51)

```

I'm sure these answers will be pretty short; this is an easier question meant for those more novice at code golf, however feel free to answer regardless of your skill/experience.

# Answer
# Japt, 4 bytes

```
mr51

```

Try it online!

Input and output is a 3-item array.

Just `m`aps each item `r`ounded to the nearest multiple of `51`.
> 8 votes

# Answer
# Taxi, 1015 bytes

```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Tom's Trims.Pickup a passenger going to Tom's Trims.Pickup a passenger going to Tom's Trims.[a]Go to Tom's Trims:n.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Divide and Conquer.51 is waiting at Starchild Numerology.51 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 1 l 2 l.Pickup a passenger going to Divide and Conquer.Pickup a passenger going to Multiplication Station.Go to Divide and Conquer:w 1 r 3 r 1 r 2 r 1 r.Pickup a passenger going to Rounders Pub.Go to Rounders Pub:e 1 r 1 r 1 l.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:n 1 r 1 r 1 l 1 r.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 r 1 l.Pickup a passenger going to Post Office.' ' is waiting at Writer's Depot.Go to Writer's Depot:n 1 l 1 l 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.Switch to plan "a".

```

Try it online!

Un-golfed:

```
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to Tom's Trims.
Pickup a passenger going to Tom's Trims.
Pickup a passenger going to Tom's Trims.
[a]
Go to Tom's Trims: north.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Divide and Conquer.
51 is waiting at Starchild Numerology.
51 is waiting at Starchild Numerology.
Go to Starchild Numerology: north 1st left 1st left 1st left 2nd left.
Pickup a passenger going to Divide and Conquer.
Pickup a passenger going to Multiplication Station.
Go to Divide and Conquer: west 1st right 3rd right 1st right 2nd right 1st right.
Pickup a passenger going to Rounders Pub.
Go to Rounders Pub: east 1st right 1st right 1st left.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station: north 1st right 1st right 1st left 1st right.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st right 1st left.
Pickup a passenger going to Post Office.
' ' is waiting at Writer's Depot.
Go to Writer's Depot: north 1st left 1st left 2nd left.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.
Switch to plan "a".

```

You can't detect if someone is waiting at `Post Office` so you start by picking up the three passengers and moving them. Divide each by 51, round, multiply by 51, and output.
> 5 votes

# Answer
# Python 2, 33 bytes

```
lambda c:[(n+25)/51*51for n in c]

```

Try it online!
> 5 votes

# Answer
# Javascript (ES6), ~~28~~ 27 bytes

-1 byte thanks to @Arnauld

```
a=>a.map(n=>51*(0|.5+n/51))

```

Takes input as an array (`[red, green, blue]`) and returns the output in the same format.

```
f=a=>a.map(n=>51*(0|.5+n/51))
```

```
<div oninput="o.innerText=f([r.value,g.value,b.value])"><input id=r type=number value=0 /><input id=g type=number value=0 /><input id=b type=number value=0 /><pre id=o>
```
> 4 votes

# Answer
# MATLAB/Octave, ~~18~~ 13 bytes

```
@(x)51*(x/51)

```

Try it online!

Takes an array of type `uint8` with three values (R,G,B), and returns a `uint8` array of web-safe (R,G,B). MATLAB/Octave use `uint8` types to represent colours in images, so it's not really cheating to expect the same.
> 4 votes

# Answer
# Jelly, ~~9~~ 8 bytes

*Byte saved thanks to Dennis*

```
51Ɠ÷+.Ḟ×

```

Try it online!
> 3 votes

# Answer
# Perl 5, ~~23~~ 18 + 1 (`-n`) = 19 bytes

```
say 51*int$_/51+.5

```

Try it online!

*-4 bytes thanks to @Dennis*
> 3 votes

# Answer
# Python 2, ~~37~~ ~~36~~ 33 bytes

```
lambda c:[(n+25)/51*51for n in c]

```

Try it online!

# Python 3, ~~36~~ ~~35~~ 34 bytes

```
lambda c:[(n+25)//51*51for n in c]

```

Try it online!
> 3 votes

# Answer
# Mathematica, 24 bytes

```
Nearest[51Range[0,5],#]&

```

Try it online!

-2 bytes from @MishaLavrov
> 3 votes

# Answer
# Excel VBA, 26 Bytes

Anonymous VBE immediate window function that takes input as integers from range `[A1:C1]` and outputs the corresponding safeview values to range `[A2:C2]`.

```
[A2:C2]="=51*INT(.5+A1/51)

```

### Sample Output
> 3 votes

# Answer
# PHP, 42 bytes

```
while($k++<3)echo($argv[$k]/51+.5|0)*51,_;

```

Run with `-nr` or try it online.
> 2 votes

# Answer
## Batch, 50 bytes

```
@for %%i in (%*)do @cmd/cset/a(%%i+25)/51*51&echo(

```

Takes input as command-line parameters.
> 2 votes

# Answer
# Retina, 53 bytes

```

 25;
\d+
$*
;

1{51}
a
1

a
51,
51,
$*
(?<= )1*
$.&

```

Try it online!

Every number in the input has a leading space
> 2 votes

# Answer
## C++, 67 bytes

-3 bytes thanks to Zacharý and ceilingcat

```
#define R(t)t=(t+25)/51*51;
void s(int&r,int&g,int&b){R(r)R(g)R(b)}

```

Return by parameters

Code to test ( include required : `iostream`, `vector` and `tuple` ) :

```
std::vector<std::pair<tuple3int, tuple3int>> testList{
    { { 0,25,76 },{ 0,0,51 } },
    { { 1,26,77 },{ 0,51,102 } },
    { { 127,178,229 },{ 102,153,204 } },
    { { 128,179,230 },{ 153,204,255 } },
    { { 0,254,255 },{ 0,255,255 } },
    { { 9,143,53 },{ 0,153,51 } }
};

for (auto& a : testList) {
    s(std::get<0>(a.first), std::get<1>(a.first), std::get<2>(a.first));
    if (a.first != a.second)
        std::cout << "Error\n";
}

```
> 2 votes

# Answer
# Kotlin, 111 bytes

```
fun w(r:Int,g:Int,b:Int):Array<Int>(){return arrayOf(Math.rint(r/51)*51,Math.rint(g/51)*51,Math.rint(b/51)*51)}

```
> 2 votes

# Answer
# q/kdb+, 11 bytes

**Solution:**

```
51 xbar 25+

```

**Example:**

```
/ apply across test cases and then cut into chunks of 3
q)3 cut 51 xbar 25+0 25 76 1 26 77 127 178 229 128 179 230 0 254 255 9 143 53
0   0   51
0   51  102
102 153 204
153 204 255
0   255 255
0   153 51

```

**Explanation:**

Nice and easy using `xbar` built-in. Q is interpreted right-to-left:

```
51 xbar 25+ / the solution
        25+ / vectorised add (add 25 to each item on the right)
51 xbar     / round down to nearest multiple of 51

```
> 1 votes

# Answer
# C# (.NET Core), 28 bytes

```
a=>a.Select(n=>(n+25)/51*51)

```

Try it online!

Same solution as others. I didnt count headers (system and linq). You can if you want. :)
> 1 votes

# Answer
# Funky, 33 bytes

```
l=>l::map(z=>math.round(z/51)*51)

```

Try it online!
> 1 votes

---
Tags: code-golf, color
---


title: Counting Fibonacci Orbits

text:
# Question
Title: Counting Fibonacci Orbits
If we define a Fibonacci-like sequence as **fk(n) = (fk(n-1) + fk(n-2)) % k**, for some integer **k** (where **%** is the modulo operator), the sequence will necessarily be cyclic, because there are only **k2** different values for **(fk(n-1), fk(n-2))**. However, this cycle doesn't usually include *all* possible pairs of values, so depending on the two starting values **fk(0)** and **fk(1)**, we might get different cycles. For example, for **k = 2**, we have the following four possibilities, depending on the first two values:

```
0, 0, 0, 0, 0, 0, 0, 0, 0, ...
0, 1, 1, 0, 1, 1, 0, 1, 1, ...
1, 0, 1, 1, 0, 1, 1, 0, 1, ...
1, 1, 0, 1, 1, 0, 1, 1, 0, ...

```

Due to the cyclic nature of the sequences, there are really only two fundamentally different sequences here, with orbits **(0)** and **(0, 1, 1)**. Let's look at **k = 3**:

```
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...
0, 1, 1, 2, 0, 2, 2, 1, 0, 1, 1, 2, 0, 2, 2, 1, ...
0, 2, 2, 1, 0, 1, 1, 2, 0, 2, 2, 1, 0, 1, 1, 2, ...
1, 0, 1, 1, 2, 0, 2, 2, 1, 0, 1, 1, 2, 0, 2, 2, ...
1, 1, 2, 0, 2, 2, 1, 0, 1, 1, 2, 0, 2, 2, 1, 0, ...
1, 2, 0, 2, 2, 1, 0, 1, 1, 2, 0, 2, 2, 1, 0, 1, ...
2, 0, 2, 2, 1, 0, 1, 1, 2, 0, 2, 2, 1, 0, 1, 1, ...
2, 1, 0, 1, 1, 2, 0, 2, 2, 1, 0, 1, 1, 2, 0, 2, ...
2, 2, 1, 0, 1, 1, 2, 0, 2, 2, 1, 0, 1, 1, 2, 0, ...

```

Again, there are only two different orbits: **(0)** and **(0, 1, 1, 2, 0, 2, 2, 1)**.

For higher **k** we might get more orbits, but they will still fall into a comparably small number of classes. For example **k = 4** yields the four orbits **(0)**, **(0,1,1,2,3,1)**, **(0, 2, 2)**, **(0, 3, 3, 2, 1, 3)** and **k = 5** the three orbits **(0)**, **(0, 1, 1, 2, 3, 0, 3, 3, 1, 4, 0, 4, 4, 3, 2, 0, 2, 2, 4, 1)** and **(1, 3, 4, 2)**.

Your task in this challenge is to compute how many orbits the sequence generates for a given **k**. This is OEIS A015134. Here are the first 100 values (starting from **k = 1**):

```
1, 2, 2, 4, 3, 4, 4, 8, 5, 6, 14, 10, 7, 8, 12, 16, 9, 16, 22, 16,
29, 28, 12, 30, 13, 14, 14, 22, 63, 24, 34, 32, 39, 34, 30, 58, 19,
86, 32, 52, 43, 58, 22, 78, 39, 46, 70, 102, 25, 26, 42, 40, 27, 52,
160, 74, 63, 126, 62, 70, 63, 134, 104, 64, 57, 78, 34, 132, 101, 60,
74, 222, 37, 38, 62, 328, 89, 64, 82, 124, 41, 86, 42, 172, 75, 44,
184, 178, 181, 132, 82, 180, 99, 140, 104, 246, 49, 50, 114, 76

```

Make sure to check **k = 11**, which is the first input which yields more than **k** orbits.

## Rules

You're given a positive integer **k** and should output **A015134(k)**.

You may write a program or a function and use any of the standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is , so the shortest valid answer – measured in *bytes* – wins.

# Answer
# Husk, ~~17~~ 16 bytes

```
Lüȯ€U¡ȯ↔m%⁰∫π2ŀ⁰

```

Try it online!

## Explanation

```
Lüȯ€U¡ȯ↔m%⁰∫π2ŀ⁰  Implicit input, say n=4.
              ŀ⁰  Lowered range: [0,1,2,3]
            π2    Cartesian second power: [[0,0],[0,1],[1,0],[0,2]..
 üȯ                Deduplicate with respect to this function:
   €U¡ȯ↔m%⁰∫       Arguments are two pairs, say a=[0,2], b=[1,1]
     ¡ȯ            Iterate on a:
           ∫       Cumulative sum,
        m%⁰        take modulo n of each,
       ↔           then reverse: [[0,2],[2,0],[2,2],[0,2],[2,0]..
    U              Cut at first repeated element: [[0,2],[2,0],[2,2]]
   €               Is b in this list? No, so they are distinct in ü.
L                 Number of remaining pairs.

```
> 3 votes

# Answer
# Bash, ~~172~~, ~~119~~, ~~113~~, 91 bytes

```
n=$1;for((k=0;k<n*n;++k)){((H[k]||++c));for((;!H[k];k=(k/n+k)%n*n+k/n)){ H[k]=1;};};echo $c

```

Try it online
> 1 votes

# Answer
# Wolfram Language (Mathematica), ~~76~~ 70 bytes

```
Tr[EdgeCycleMatrix[#->{#[[2]],Tr@#~Mod~n}&/@Tuples[Range[n=#]-1,2]]!]&

```

Try it online!

## How it works

We construct the graph given by the rules `{{0,0}->{0,0}, {1,0}->{1,1}, ...}` that, given two elements of a generalized Fibonacci sequence, find the next one modulo `n`. The `EdgeCycleMatrix` gives the incidence matrix from cycles to edges in this graph; we want to count its rows.

(There are a number of built-ins that do a similar task, but `ConnectedComponents` is longer, and `FindCycle` needs lots of extra inputs to make it work. Besides, `EdgeCycleMatrix` is a rectangular array, not funny-shaped like the other two, which helps later.)

To count the rows of the matrix, we take the factorial of the entries to turn it into a matrix of all ones, then take the trace. (Each cycle contains at least one edge and therefore there are at least as many columns as rows - so this counts the rows and not the columns.)
> 1 votes

# Answer
# MATL, ~~38~~ 36 bytes

```
:qt!J*+le"@GU:"t&Zjwy+G\J*+hu]S]Xhun

```

**Try it online!** It times out in the online compiler for input exceeding `7`.

### Explanation

The code defines orbits in terms of complex numbers, where the imaginary part is the *new term* and the real part is the *preceding term* in the Fibonacci sequence. Each complex value encodes the *state* of the sequence. Namely, given `a+jb` the next value is computed as `b+j(a+b)`.

The possible starting values are `a+jb` with `a`, `b` in `[0, 1, ..., k-1]`. For each starting value, the code iterates `k^2` times. Actually, to make the code shorter, each iteration is applied to *all* accumulated so values so far, and the results are deduplicated (which would be necessary at the end anyway). After the last iteration, the vector of deduplicated complex values is sorted (by absolute value, then by angle). This gives a "signature" for each orbit.

At the end of the program, signatures are collected into a cell array. The number of unique signatures is the desired output.

```
:q          % Implicit input: k. Push row vector [0, 1, ..., k-1]
t!          % Duplicate, transpose: gives column vector [0; 1; ...; k-1]
J*+         % Multiply by 1j, add with broadcast. Gives a k × k matrix of
            % values a+jb with a, b in [0, 1, ..., k-1]
le          % Linearize into a row vector
"           % For each c in that vector
  @         %   Push c
  GU:"      %   Do the following k^2 times
    t&Zj    %     Duplicate and split into real and imaginary parts: a, b
    wy+     %     Swap, duplicate, from below, add: transforms a, b into
            %     b, a+b. This is the basic step in the Fibonacci sequence
            %     In subsequent iterations a and b may be vectors instead
            %     of numbers, as they include all values obtained so far
    G\      %     Modulo k, element-wise
    J*+     %     Times 1j, add. Gives the next complex number for each of
            %     the complex numbers so far
    hu      %     Append to values so far and deduplicate. This may extend
            %     the vector of complex numbers
  ]         %   End
  S         %   Sort
]           % End
Xh          % Collect entire stack into a cell array
u           % Deduplicate
n           % Number of entries. Implicit display

```
> 1 votes

# Answer
# Haskell, ~~196~~ 191 bytes

```
import Data.List
o(a:b)=1+o[x|x<-b,not$(0<$a)==(0<$x)&&isInfixOf a(x++x)]
o _=0
k#(a,b)=(b,mod(a+b)k)
p!(a:b)|elem a p=fst<$>p|r<-p++[a]=r!b
f k=o[[]!iterate(k#)(a,b)|a<-[0..k-1],b<-[0..k-1]]

```

Try it online!

This could probably be improved. Particularly if someone can find a way to avoid `isInfixOf` and remove the import.

Basic idea is to generate a list of "states" (tuples containing the two previous values) to see when it starts to cycle. Then we check whether each orbit is different to its predecessors (really works the other way around but it's hard to put into words). To check if orbits are the same we check if the length is the same and whether one fits into the other concatenated with itself. For example `[0,2,2]`,`[2,2,0]`: length of both is 3 and `[0,2,2,0,2,2]` contains `[2,2,0]` as a continuous subsequence. I'm not sure if it's foolproof but it seems to work.

EDIT: thanks to Laikoni for taking off 5 bytes! I should've read more of those tips.
> 1 votes

# Answer
# Jelly, 17 bytes

```
Ṛ+\%³
Ḷṗ2ÇÐĿ€Ṣ€QL

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), ~~337~~ 335 bytes

Sorry for the Ω(k^3) brute-force algorithm.

```
(k,x=o=0,u=[],s=(q,w,v,j=d=0)=>{while(j++<v)d|=q.reduce((a,b,i)=>a&=b==w[(i+j)%v],1);return d})=>{for(;x<k;x++)for(y=0;y<k;y++){l=2;r=[x,y];do{r.push((c=(d=r[(l+=2)-3])+r[l-4])%k,(c+d)%k)}while(!(t=r.slice(0,h=l/2)).reduce((a,b,i)=>a&=b==r[i+h],1));if(!u.reduce((q,z)=>q|=(t.length-(a=z.length)?0:s(t,z,a)),0)){o++;u.push(t)}}return o}

```

The performance... ~~When I was calculating A015134(something beyond k=50) it exceeded 60s limit on TIO.~~

```
var g=(k,x=o=0,u=[],s=(q,w,v,j=d=0)=>{while(j++<v)d|=q.reduce((a,b,i)=>a&=b==w[(i+j)%v],1);return d})=>{for(;x<k;x++)for(y=0;y<k;y++){l=2;r=[x,y];do{r.push((c=(d=r[(l+=2)-3])+r[l-4])%k,(c+d)%k)}while(!(t=r.slice(0,h=l/2)).reduce((a,b,i)=>a&=b==r[i+h],1));if(!u.reduce((q,z)=>q|=(t.length-(a=z.length)?0:s(t,z,a)),0)){o++;u.push(t)}}return o}

for (var ix = 1; ix <= 15; ix++)
 console.log(`A015134(${ix}) = ${g(ix)}`);
```

# Explanation(Ungolfed)

```
function CheckIfSameOrbit(Array_1, Array_2, Length) { // Checks if the orbits are equal
  var d = false, j = 0;                               // Assume both have same length
  while (j < v) {                                     // Checks for different startings
    j++;
    d |= Array_1.reduce(function(Acc, Item, Index) {  // Element-by-element comparison
      Acc &= Item == w[(Index + j) % v], 1);
    });                                               // Return true if any starting
  }                                                   // point makes two orbits identical
}

function A015134(k) {                                 // Main Program
  var o = 0, u = [];
  for (var x = 0; x < k; x++) {                       // Checks different pairs of (x, y)
    for (var y = 0; y < k; y++) {
      var l = 2, r = [x, y], h = 1, t;
      do {                                            // Find until a complete orbit is
        l += 2;                                       // found (except for (0, 0) case)
        h = l / 2;
        var d = r[l - 3], c = r[l - 3] + r[l - 4];
        r.push(c % k, (c + d) % k);
        t = r.slice(0, h);
      }
      while (!t.reduce(function(Acc, Item, Index) {   // Which is, if 2 identical copies
        Acc &= Item == r[Index + h];                  // of the orbit are calculated
      }, 1));

      if (!u.reduce(function(Acc, Item) {             // If the orbit is a new one
        var a = Item.length;
        Acc |= (t.length - a ? 0 : s(t, Item, a));
      }, 0)) {
        o++;                                          // Increment the counter, and
        u.push(t);                                    // record it to the list
      }
    }
  }
  return o;                                           // Ultimately return the counter;
}

```
> 0 votes

# Answer
# Perl 5, 80+1 (-p) bytes

```
$n=$_;map{$a[$_]||++$\;$a[$_]++until$a[$_=0|($_/$n+$_)%$n*$n+$_/$n]}0..$n**2-1}{

```

Try it online
> 0 votes

# Answer
## JavaScript (ES6), 102 bytes

```
k=>F=(a=0,b=0,C=0,q)=>q?F[q=[a,b%=k]]?0:1|F(b,a+b,C,F[q]=1):b<k?F(a,b+1,C+F(a,b,C,1)):++a<k?F(a,0,C):C

```

Returns a function which returns the result. For 3 more bytes we can have it return the result directly:

```
k=>(F=(a,b,C,q)=>q?F[q=[a,b%=k]]?0:1|F(b,a+b,C,F[q]=1):b<k?F(a,b+1,C+F(a,b,C,1)):++a<k?F(a,0,C):C)(0,0,0)

```

Both have time complexity O(n2).
> 0 votes

# Answer
# Python 2, 214 bytes

```
def h(k):
 R=[]
 for p in[[i/k,i%k,(i/k+i%k)%k]for i in range(k*k)]:
	while p[:2]!=p[-2:]:
		p.append(sum(p[-2:])%k)
	p=p[:-2]
	if not any([p==x[i:]+x[:i]for i in range(len(p))for x in R]):R.append(p)
 print len(R)

```

Try it online!

It's not very efficient but it's the golfiest I could do.
> 0 votes

---
Tags: code-golf, sequence, number-theory, combinatorics, fibonacci
---


title: 24 and 12 Hour Times

text:
# Question
Title: 24 and 12 Hour Times
Write a program or function with no input that prints or returns this string of 24-hour and 12-hour times:

```
00:00 12:00am
01:00  1:00am
02:00  2:00am
03:00  3:00am
04:00  4:00am
05:00  5:00am
06:00  6:00am
07:00  7:00am
08:00  8:00am
09:00  9:00am
10:00 10:00am
11:00 11:00am
12:00 12:00pm
13:00  1:00pm
14:00  2:00pm
15:00  3:00pm
16:00  4:00pm
17:00  5:00pm
18:00  6:00pm
19:00  7:00pm
20:00  8:00pm
21:00  9:00pm
22:00 10:00pm
23:00 11:00pm

```

**The string must be output *exactly* as it appears here.** The only exception is that it may optionally have a single trailing newline.

So the MD5 hash of your output should be

```
827ae6e2dbb1df494930baedb3ee2653

```

if you do not have a trailing newline and

```
cd4c3d18abee9bafb495f390a919a13f

```

if you do. (Your hash could be different if your system uses another type of newline but that's OK.)

**The shortest code in bytes wins. Tiebreaker is earlier answer.**

# Answer
> 13 votes
# Bash + coreutils, 43 30

* Saved 7 bytes thanks to @Yossarian
* Saved 3 bytes thanks to @AndersKaseorg

```
seq 0 23|date -f- +%R\ %l:00%P

```
* `seq` generates integers 0-23, one per line.
* `date` interprets each line as a datetime. Bare integers appear to be sufficient to be recognised as hours of the day by `date`. `date` then outputs each time with the required formatting using the available time format specifiers.

Assumes `LANG=C` locale, as per this meta answer.

Ideone.

# Answer
> 12 votes
# Python 2, 66 bytes

```
for i in range(24):print'%02d:00%3d:00%sm'%(i,12+i%-12,'ap'[i>11])

```

# Answer
> 8 votes
# C, 73 bytes

```
m(i){for(i=25;--i;)printf("%02d:00%3d:00%cm\n",24-i,12-i%12,"pa"[i/13]);}

```

mIllIbyte found a particularly neat way to rewrite this answer. Thanks!

# Answer
> 6 votes
# MATL, ~~46~~ ~~42~~ 34 bytes

```
12tEt:qy/t15XObZ"!b16XOhhkw14:X~Z)

```

Previously, 42 bytes, `12tEt:q2M/736330+t15XObZ"!b16XOhhkw14:X~Z)`, and 46 bytes, `736330 24t:qw/+t15XO' '24TX"b16XOhhk14: 12X~Z)`. Of course the 736330 wasn't needed, that was crazy!

Note: Doesn't work with TryItOnline, I think there is a compatibility issue between Matlab and Octaves implementation of `datestr`.

`datestr` takes the number representation of a date and converts it to the string representation of that date. The time of the day is the fractional part of the number, so 0.0 corrsponds to January 0, 0000, at time 00:00:00, and 1.0 corresponds to January 1, 0000, at 00:00:00. 1/24 is 1am, 2/24 2am etc.

Explanation

```
12t         % push a 12 onto the stack and duplicate
Et          % double the 12 and duplicate the 24 (stack now has 12, 24, 24, bottom to top)
:q          % make vector 1:24 and decrement by 1, stack has 12, 24, 0:23
y           % duplicate second element on stack (24)
/           % divide, for (0:23)/24
t           % duplicate elements
15XO        % string representation of date, 15 specifies format
b           % bubble up element in stack (gets a 24 on top of the stack)
Z"!         % makes a column of 24 spaces, to put between columns of times
b           % bubble up another (0:23)/24
16XO        % string representation of date, 16 for a different format
hh          % concatenate two time vectors and the column of spaces
k           % convert string to lowercase, because CO gives AM/PM not am/pm
w           % swap elements in stack, that first 12 is now on top
14:         % vector of equally spaced values 1:14
X~          % set exclusive-or, returns [1 2 3 4 5 6 7 8 9 10 11 13 14]
Z)          % get the right columns of the string array to remove extra column of blanks
            % implicit display

```

To show it works in Matlab, here is a screenshot

# Answer
> 5 votes
# MarioLANG, ~~965~~ 834 bytes

**Try it online**

well this was ridiculously complicated.

Technically the output is valid but in practice the Tio for MarioLANG output "n " instead of "n" when we print a number with ':'

if I find the time i'll guess i'll try to do a (probably much longer) version of the program that output correctly on Tio

```
++<>) +++@++++>   [!) >)>((((::(.)::((.))+:+:--(.)::)).).).)+++++++++
++""+ +"=====""====#) "+"============================================
+++)+ +>>+++++- <+<)->+++ ![-).).).))(::)).(:(:)))..(((::)).(:+(:((((<
+>+++ ++"====<( ")")-"!+++#=========================================="
+(+++>++!++)<+( ++++-+++++>
 -))+)=(#==="+( ++++)+++++"==========================================!
 [!!+-[!(+++!!! !+!<+!++!>(((((+:(.))::(((.
==##===#====###=#=#"=##=#"=================<
++++)))+++++++++++++++(((![-).).).)::)).(:))   >
>========================#==================   "
+>+ >
+"+ "=======================================[   =====================#===============[
+!> ! -).).).))(::)).)):+(..(((::)).(:+(((((<++!-).).).))(::)).)):+(.(((::)).(:+(((((<
=#==#======================================="==#======================================

```

**Explanation :**

our main problem here is the fact that we have 6 NaN char (newLine, Space, :, a, p, m)

in marioLANG, in order to print character, we need their ascii value:

* **newLine** is 10
* **Space** is 32
* **:** is 58
* **a** is 97
* **p** is 112
* **m** is 109

So the first thing to do is to set the memory :

```
++<>) +++@++++>   [!) >)> !
++""+ +"=====""====#) "+"==
+++)+ +>>+++++- <+<)->+++
+>+++ ++"====<( ")")-"!+++
+(+++>++!++)<+( ++++-+++++
 -))+)=(#==="+( ++++)+++++
 [!!+-[!(+++!!! !+!<+!++!>
==##===#====###=#=#"=##=#"

```

with this, the memory look like :

```
                   v
  32 58 0 0 97 109 10 0
  _  :      a   m  \n

```

we will transform **a** into **p** during the rest of the program

then we do the actual output :

```
++<>) +++@++++>   [!) >)>((((::(.)::((.))+:+:--(.)::)).).).)+++++++++
++""+ +"=====""====#) "+"============================================
+++)+ +>>+++++- <+<)->+++ ![-).).).))(::)).(:(:)))..(((::)).(:+(:((((<
+>+++ ++"====<( ")")-"!+++#=========================================="
+(+++>++!++)<+( ++++-+++++>
 -))+)=(#==="+( ++++)+++++"==========================================!
 [!!+-[!(+++!!! !+!<+!++!>(((((+:(.))::(((.
==##===#====###=#=#"=##=#"=================<
++++)))+++++++++++++++(((![-).).).)::)).(:))   >
>========================#==================   "
+>+ >
+"+ "=======================================[   =====================#===============[
+!> ! -).).).))(::)).)):+(..(((::)).(:+(((((<++!-).).).))(::)).)):+(.(((::)).(:+(((((<
=#==#======================================="==#======================================

```

# Answer
> 5 votes
# ///, 160 bytes

```
/Z/:00 //S/Z //A/:00am
//P/:00pm
/00Z12A01S1A02S2A03S3A04S4A05S5A06S6A07S7A08S8A09S9A10Z10A11Z11A12Z12P13S1P14S2P15S3P16S4P17S5P18S6P19S7P20S8P21S9P22Z10P23Z11P

```

Try it online!

**Ungolfed**

```
00:00 12:00am
01:00  1:00am
02:00  2:00am
03:00  3:00am
04:00  4:00am
05:00  5:00am
06:00  6:00am
07:00  7:00am
08:00  8:00am
09:00  9:00am
10:00 10:00am
11:00 11:00am
12:00 12:00pm
13:00  1:00pm
14:00  2:00pm
15:00  3:00pm
16:00  4:00pm
17:00  5:00pm
18:00  6:00pm
19:00  7:00pm
20:00  8:00pm
21:00  9:00pm
22:00 10:00pm
23:00 11:00pm

```

# Answer
> 4 votes
# Julia, ~~88~~ ~~71~~ ~~66~~ 64 bytes

```
[@printf "%02d:00%3d:00%cm
" i-11 i%12+1 i>22?112:97for i=11:34]

```

This is a full program that prints the string with a single trailing newline.

Try it online!

Saved 5 bytes thanks to Sp3000 and 2 thanks to Dennis!

# Answer
> 4 votes
## C# function, 100 bytes

```
void F(){for(int i=0;i<24;i++){Console.Write($"{i:00}:00 {(i+11)%12+1,2}:00 {(i>11?"p":"a")}m\n");}}

```

**Ungolfed version:**

```
void F()
{
    for (int i = 0; i < 24; i++)
    {
        Console.Write($"{i:00}:00 {(i + 11)%12 + 1,2}:00 {(i > 11 ? "p" : "a")}m\n");
    }
}

```

`Console.Write()` takes too many characters!

# Answer
> 3 votes
# TSQL(SQLServer 2012) ~~146~~ ~~124~~ 121

```
DECLARE @ DATETIME=0WHILE @<1BEGIN PRINT
CONVERT(char(5),@,108)+' '+LOWER(RIGHT(FORMAT(@,'g'),8))SET @=dateadd(hh,1,@)END

```

Try it online!

First attempt, a bit longer, but a one-liner:

```
SELECT CONVERT(char(5),n,108)+' '+LOWER(RIGHT(FORMAT(n,'g'),8))FROM(SELECT
top 24 dateadd(hh,Number,0)n FROM master..spt_values WHERE'P'=type)x

```

Try it online!

# Answer
> 3 votes
## JavaScript (ES2015), ~~147~~ ~~138~~ ~~137~~ ~~134~~ 133 bytes

```
((o,x,r)=>{for(i=0;i<24;)b=i%12,c=b||12,o+='0'[r](i<10)+i+++x+' '[r]((c<10)+1)+c+x+(i<13?'a':'p')+"m\n";return o})('',':00','repeat')

```

In this version I took advantage of String.repeat() method to get rid of lengthy .slice() and .join() and moved incrementation inside loop.

Previous version:

```
((o,x,i)=>{for(;i<24;i++){b=i%12;o+=[`0${i+x}`.slice(-5),(b||12)+x+(i<12?'a':'p')+'m'].join(' '.repeat((b>0&&b<10)+1))+"\n"}return o})('',':00',0)

```

Gives output with trailing newline. Tested in Firefox Scratchpad. Not sure if passing arguments to IIFE is OK with "no input" rule.

It's my first submission, so hello to everyone! :)

# Answer
> 2 votes
# Perl 5, 58

```
map{printf"%02u:00%3u:00%sm
",$_,$_%12||12,$_>11?p:a}0..23

```

# Answer
> 2 votes
# , ~~56~~ 53 bytes

```
i00:00 23ñYpñH12G$yP13G$pgvó $/am
í/pm
í 0/
í/12

```

Try it online!

Since this can be hard to enter, here is a reversible hexdump:

```
00000000: 6930 303a 3030 201b 3233 f159 7001 f148  i00:00 .23.Yp..H
00000010: 1631 3247 2479 5031 3347 2470 6776 f320  .12G$yP13G$pgv.
00000020: 242f 616d 0aed 2f70 6d0a ed20 302f 2020  $/am../pm.. 0/
00000030: 0aed 2f31 320a                           ../12.

```

A noncompeting version is trivially 2 bytes shorter if you replace both occurrences of `G$` with `L`, which was supposed to be the same but had a bug.

Explanation:

```
i00:00<esc>                                     #Enter the starting text.
           23ñYp<C-a>ñ                          #Duplicate and increment 23 times
                      H                         #Move back to the beginning
                       <C-v>12G$y               #Select 12 lines horizontally
                                 P              #Horizontally paste
                                  13G$p         #Move to line 13 and Horizontally paste again
                                       gv       #Reselect the top 12 lines
                                         ó $/am #Replace a space at the end of the line with 'am'

```

---

```
í/pm      #Replace the previous search with 'pm'
í 0/      #Replace "Space+0" with 2 spaces
í/12      #Replace the previous search with "12"

```

# Answer
> 2 votes
# Javascript, 122 Bytes, 120 Bytes

```
f=j=>j>12?j-12:j;for(i=0;i<24;i++)console.log('%s:00 %s:00%s',i<10?'0'+i:i,i==0?12:f(i)<10?' '+f(i):f(i),i>11?'pm':'am')

```

Edit: Small bug fixed + output:

```
00:00 12:00am
01:00  1:00am
02:00  2:00am
03:00  3:00am
04:00  4:00am
05:00  5:00am
06:00  6:00am
07:00  7:00am
08:00  8:00am
09:00  9:00am
10:00 10:00am
11:00 11:00am
12:00 12:00pm
13:00  1:00pm
14:00  2:00pm
15:00  3:00pm
16:00  4:00pm
17:00  5:00pm
18:00  6:00pm
19:00  7:00pm
20:00  8:00pm
21:00  9:00pm
22:00 10:00pm
23:00 11:00pm

```

# Answer
> 2 votes
## 05AB1E, ~~51~~ ~~50~~ ~~48~~ ~~44~~ 42 bytes

Saved two bytes thanks to *carusocomputing*

**Code:**

```
24FNgi0}N…:00©ðN12(%12+Dgiðs}®„paN12‹è'mJ,

```

Try it online!

**Explanation**

```
24F                                         # for N in [0...23]
   Ngi0}                                    # if len(N)=1, push 0
        N                                   # push N
         …:00©                              # push ":00" and store a copy in register
             ð                              # push " "
              N12(%12+D                     # push 2 copies of N%(-12)+12
                       giðs}                # if the length of that number is 1,
                                            # push " " and swap with the number
                            ®               # push ":00" again
                             „pa            # push "pa"
                                N12‹è       # index into that with N<12
                                     'm     # push "m"
                                       J,   # join everything and print with newline

```

# Answer
> 1 votes
## Batch, 167 bytes

```
@echo off
set h=11
set p=a
for /l %%a in (0,1,23)do call:e %%a
exit/b
:e
set a=0%1
set/ah=h%%12+1
set h= %h%
if %1==12 set p=p
echo %a:~-2:00 %h:~-2%:00%p%m

```

# Answer
> 1 votes
## PowerShell v2+, 76 bytes

```
0..23|%{"{0:D2}:00{1,3}:00"-f$_,(($_%12),12)[!($_%12)]+('am','pm')[$_-ge12]}

```

Loops from `0..23` and each loop sets a string with the `-f` operator. The first `{0:D2}` ensures we have prepended zeros, the second `{1,3}` ensures we have padded spaces for the middle column. The `{0}` one corresponds to the `$_` of the `-f` operator, while the `{1}` corresponds to the pseudo-ternary that chooses between `$_%12` or `12` based on whether `$_%12` is non-zero or not (i.e., if we're at `$_=13`, this will choose `1` for 1:00pm). We then concatenate that with another pseudo-ternary that chooses the appropriate `am`/`pm`.

---

As opposed to my answer on List all times in the day at a half hour rate, it's actually shorter *here* to brute-force the numbers since we get significantly cheaper padding. Here's the answer using date functions, at **78 bytes**

```
0..23|%{(Date -h $_ -f 'HH:00')+(Date -h $_ -f "h:00tt").ToLower().PadLeft(8)}

```

# Answer
> 1 votes
# C++, ~~81~~ 79 bytes

```
[]{for(time_t t=0,y;t<24;cout<<put_time(gmtime(&y),"%R %l:00%P\n"))y=t++*3600;}

```

This code requires `using namespace std` somewhere preceding it.

It does a loop on the values 0...23. It multiplies each value by 3600, converts to a `tm` struct and prints it. The print format `%R` outputs the 24-hour and minute; the print formats `%l` and `%P` output the proper 12-hour parts; they require GNU.

A working online version is here.

# Answer
> 1 votes
# Kotlin, 95 bytes

It can be improved for sure.

```
fun p(){for(i in 0..23)println("%02d:00 ${(i+11)%12+1}:00${if(i>12)"p" else "a"}m".format(i))}

```

# Answer
> 1 votes
# Ruby, 66 62 bytes

```
0.upto(23){|i| puts "%02d:00%3d:00#{'ap'[i/12]}m"%[i,(i-1)%12+1]}

```

New version

```
24.times{|i|puts"%02d:00%3d:00#{'ap'[i/12]}m"%[i,(i-1)%12+1]}

```

# Answer
> 1 votes
# JavaScript (ES6), ~~119~~ 116 bytes

```
_=>Array(24).fill().map((_,i)=>`${`0${i}`.slice(-2)}:00 ${` ${(i+11)%12+1}`.slice(-2)}:00${'ap'[+(i>11)]}m`).join`
`

```

# Answer
> 1 votes
# JavaScript, ~~97~~ 95 bytes

This is based off of starcorder’s answer. Thanks to George Reith for a 2 byte improvement.

```
for(i=0,k=12;i<24;k=i++%12+1)console.log('%s:00 %s:00%sm',i>9?i:'0'+i,k>9?k:' '+k,i>11?'p':'a')

```

Ungolfed:

```
for (i=0, k=12; i < 24; k = (i++) % 12 + 1)
    console.log('%s:00 %s:00%sm',
        i > 9 ? i : '0' + i,
        k > 9 ? k : ' ' + k,
        i > 11 ? 'p' : 'a')

```

# Answer
> 1 votes
# Sclipting, 76 bytes

The program assumes that the input is empty (or `'0'` or anything that converts to the integer `0`).

The byte count assumes UTF-16 encoding.

```
군上❶겠小꼀虛嗎❷꾣갰글❷결加곀剩增❶겠小글虛嗎댆밁⓷꾣갰⓷⓼곀小掘닐밊終
```

Ungolfed:

```
군 // 23
上 // for loop (goes from 0 to 23 if input is 0)
    ❶겠小꼀虛嗎 // n < 10 ? "0" : ""
    ❷          // n
    꾣갰글      // ":00 "
    ❷결加곀剩增 // k = (n+11) % 12 + 1
    ❶겠小글虛嗎 // k < 10 ? " " : ""
    댆밁       // "pa"
    ⓷         // Pull n to top of stack
    꾣갰       // ":00"
    ⓷         // Pull "pa" to top of stack
    ⓼         // Pull k to top of stack
    곀小掘     // "pa"[k < 10 ? 1 : 0]
    닐밊       // "m\n"
終 // end of for loop

```

Each iteration of the loop leaves lots of small strings on the stack; at the end they are all automatically concatenated.

# Answer
> 0 votes
# C Function, 82 bytes

```
m(i){for(;i<24;printf("%02d:00 %2d:00%cm\n",i,i%12==0?12:i%12,i>11?'p':'a'),i++);}

```

**Usage, 94 Byte**

```
m(i){for(;i<24;printf("%02d:00 %2d:00%cm\n",i,i%12==0?12:i%12,i>11?'p':'a'),i++);}main(){m();}

```

**Ungolfed, 337 Bytes**

```
#include <stdio.h>
void m(){
    int i,a;
    char c;
    for(i=0;i<24;i++){
        if (i%12==0){
            a = 12;
        }
        else{
            a = i%12;
        }
        if (i>11){
            c = 'p';
        } else{
            c = 'a';
        }
        printf("%02d:00 %2d:00%cm\n",i,a,c);
    }
}
int main(){
    m();
}

```

it works on Windows:

# C Program, 85 bytes

```
main(i){for(;i<24;printf("%02d:00 %2d:00%cm\n",i,i%12==0?12:i%12,i>11?'p':'a'),i++);}

```

# Answer
> 0 votes
# PHP, ~~110~~ 107 bytes

```
for($h=0;$h<24;){$m=($h+11)%12+1;echo($h<10?0:"")."$h:00 ".($m<10?" ":"")."$m:00".($h++<12?"a":"p")."m\n";}

```
**exploded view**
```
for ($h=0; $h<24; ) {
  $m = ($h+11) % 12 + 1;
  echo ($h < 10 ?  0  : "") . "$h:00 " .
       ($m < 10 ? " " : "") . "$m:00"  . ($h++ < 12 ? "a" : "p") . "m\n";
}

```

Somewhat surprised, tried to turn the `($i < 10 ? $s : "") . "$i:00"` bit into a function, but it wound up *adding* ~25 characters. No go there.

# Answer
> 0 votes
## Swift, 85 bytes

```
for x in 0...23{print(String(format:"%02d:00 %2d:00\(x<12 ?"a":"p")m",x,12+x % -12))}

```

# Answer
> 0 votes
# PHP, ~~67~~ ~~65~~ 64 bytes

This uses IBM-850 encoding.

```
for(;$i<24;)printf(~┌¤═ø┼¤¤┌╠ø┼¤¤┌îÆ§,$i,$i%12?:12,$i++>11?p:a);

```

With the unencoded string (66 bytes):

```
for(;$i<24;)printf("%02d:00%3d:00%sm\n",$i,$i%12?:12,$i++>11?p:a);

```

Run like this:

```
php -n -r 'for(;$i<24;)printf(~┌¤═ø┼¤¤┌╠ø┼¤¤┌îÆ§,$i,$i%12?:12,$i++>11?p:a);'

```

## Tweaks

* Saved 2 bytes by improving sprintf format
* Saved a byte by getting rid of unnecessary space (thx @Titus)

# Answer
> 0 votes
# Foo, 163 bytes

Pretty brute-force approach; nothing clever here (I tried in a couple spots but it ended up being shorter not to), just wanted to give Foo a shot. Foo automatically prints anything within quotes. `$c10` prints a line break. `(## ... )` loops until the current cell equals `##`.

```
"00:00 12:00am"$c10+1(10"0"$i":00  "$i":00am"$c10+1)(12$i":00 "$i":00am"$c10+1)"12:00 12:00pm"$c10+1(22$i":00  ">+1$i<":00pm"$c10+1)(24$i":00 ">+1$i<":00pm"$c10+1)

```

Ungolfed a bit:

```
"00:00 12:00am"$c10+1
(10"0"$i":00  "$i":00am"$c10+1)
(12$i":00 "$i":00am"$c10+1)
"12:00 12:00pm"$c10+1
(22$i":00  ">+1$i<":00pm"$c10+1)
(24$i":00 ">+1$i<":00pm"$c10+1)

```

Try it online

# Answer
> 0 votes
# Javascript (using external library - Enumerable) (107 bytes)

```
_.Range(0,24).WriteLine(x=>((x<10?"0"+x:x)+":00 "+(((h=((x+11)%12)+1))<10?" "+h:h)+":00"+(x<12?"am":"pm")))

```

Link to library: https://github.com/mvegh1/Enumerable/

Code explanation: Create array of integers from 0 to 23, for each write a line according to the predicate. That predicate checks if current val is less than 10, and pads it with 0, else uses the current val as is. Then adds the minutes string to it. Then basically does a little trickery to convert military to am/pm time, and handles padding for am/pm times less than 10.

# Answer
> 0 votes
# SmileBASIC, 73 bytes

```
FOR H=0TO 23?FORMAT$(%02D:00 %2D:00%Sm",H,(H+11)MOD 12+1,"ap"[H>11])NEXT

```

Someone found a better 24-\>12 hour formula than my old one, which saves 3 bytes, and 5 bytes in another program

# Answer
> 0 votes
# tcl, 93

```
set i 0;time {puts [format %02d:00%3d:00[expr $i<12?"a":"p"]m $i [expr $i%-12+12]];incr i} 24

```

demo

# Answer
> 0 votes
# VBA, 91 Bytes

Anonymous VBE immediate window function that outputs to the VBE immediate window.

```
For i=0To 23:t=TimeSerial(i,0,0):?Format(t,"hh:mm")Right("  "+Format(t,"h:mmam/pm"),8):Next

```

# Answer
> 0 votes
# Groovy, 90/94 bytes

90 byte version (only works in a script):

```
24.times{a->s=' ';m=a%12?:12;println"${a<10?0:''}$a:00 ${m<10?s:''}$m:00${a<12?'a':'p'}m"}

```

94 byte version:

```
24.times{a->def s=' ',m=a%12?:12;println"${a<10?0:''}$a:00 ${m<10?s:''}$m:00${a<12?'a':'p'}m"}

```

# Answer
> 0 votes
# LOLCODE, 365 bytes

I'll golf down...

```
HAI 1.3
VISIBLE "00:00 12:00am:)01:00 1:00am:)02:00 2:00am:)03:00 3:00am:)04:00 4:00am:)05:00 5:00am:)06:00 6:00am:)07:00 7:00am:)08:00 8:00am:)09:00 9:00am:)10:00 10:00am:)11:00 11:00am:)12:00 12:00pm:)13:00 1:00pm:)14:00 2:00pm:)15:00 3:00pm:)16:00 4:00pm:)17:00 5:00pm:)18:00 6:00pm:)19:00 7:00pm:)20:00 8:00pm:)21:00 9:00pm:)22:00 10:00pm:)23:00 1:00pm"
KTHXBYE

```

Try it online!

# Answer
> -1 votes
# C#, 91 bytes

`for(var i=0;i<24;i++){Console.Write($"{i:00}:00 {(i+11)%12+1,2}:00 {(i>11?"p":"a")}m\n");};`

---
Tags: code-golf, string, kolmogorov-complexity, arithmetic, date
---